@joelincc/mailroom 0.1.0 → 0.3.0
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.
- package/README.md +47 -5
- package/SECURITY.md +1 -1
- package/bin/mailroom.mjs +26 -0
- package/dist/broadcast/config.js +79 -0
- package/dist/broadcast/explain.js +50 -0
- package/dist/cli/args.js +29 -0
- package/dist/cli/errors.js +31 -0
- package/dist/cli/main.js +475 -0
- package/dist/compose/clicks.js +29 -0
- package/dist/compose/compose.js +224 -0
- package/dist/compose/index.js +8 -0
- package/dist/compose/markdown.js +637 -0
- package/dist/compose/personalize.js +123 -0
- package/dist/compose/preflight.js +251 -0
- package/dist/compose/preview.js +41 -0
- package/dist/compose/render.js +136 -0
- package/dist/compose/template.js +118 -0
- package/docs/broadcast.md +199 -0
- package/docs/composing.md +135 -0
- package/docs/desk-commands.md +52 -0
- package/docs/export.md +51 -0
- package/docs/lists.md +66 -0
- package/docs/security-model.md +4 -4
- package/docs/ses.md +116 -0
- package/docs/unsubscribe.md +117 -0
- package/migrations/0004_last_error.sql +2 -0
- package/migrations/0005_lists.sql +41 -0
- package/migrations/0006_broadcast.sql +154 -0
- package/migrations/0007_unsubscribe.sql +12 -0
- package/package.json +19 -3
- package/src/alert.ts +123 -0
- package/src/aws-sigv4.ts +100 -0
- package/src/broadcast/audience.ts +96 -0
- package/src/broadcast/campaigns.ts +339 -0
- package/src/broadcast/config.ts +136 -0
- package/src/broadcast/dispatch.ts +766 -0
- package/src/broadcast/events.ts +107 -0
- package/src/broadcast/explain.ts +73 -0
- package/src/broadcast/freeze.ts +93 -0
- package/src/broadcast/index.ts +21 -0
- package/src/broadcast/postman.ts +229 -0
- package/src/broadcast/reconcile.ts +120 -0
- package/src/broadcast/routes.ts +181 -0
- package/src/broadcast/ses.ts +181 -0
- package/src/broadcast/stats.ts +59 -0
- package/src/broadcast/status.ts +60 -0
- package/src/broadcast/test-send.ts +88 -0
- package/src/broadcast/warmup.ts +150 -0
- package/src/broadcast/worker.ts +177 -0
- package/src/cf-events.ts +4 -3
- package/src/cli/args.ts +27 -0
- package/src/cli/errors.ts +33 -0
- package/src/cli/main.ts +466 -0
- package/src/compose/clicks.ts +45 -0
- package/src/compose/compose.ts +257 -0
- package/src/compose/index.ts +8 -0
- package/src/compose/markdown.ts +624 -0
- package/src/compose/personalize.ts +130 -0
- package/src/compose/preflight.ts +250 -0
- package/src/compose/preview.ts +58 -0
- package/src/compose/render.ts +153 -0
- package/src/compose/template.ts +197 -0
- package/src/core.ts +42 -1
- package/src/export.ts +184 -0
- package/src/feedback.ts +111 -0
- package/src/http.ts +17 -0
- package/src/index.ts +120 -31
- package/src/list-routes.ts +42 -0
- package/src/lists.ts +370 -0
- package/src/ses-events.ts +426 -0
- package/src/unsub-wiring.ts +64 -0
- package/src/unsub.ts +499 -0
- package/src/webhook.ts +5 -3
- package/wrangler.example.jsonc +16 -2
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// 群發的管理入口(HTTP,帶管理口令;口令與速度上限由 index.ts 先檢查過才進來)。
|
|
2
|
+
// 指令(AI 用的 campaign create/approve/schedule/pause/resume…)背後打的就是這些路徑。
|
|
3
|
+
//
|
|
4
|
+
// GET /v1/throttle 今天額度、已用、網域停寄、各期狀態
|
|
5
|
+
// PUT /v1/campaigns/{id} 存草稿(內容改了就退回 draft)
|
|
6
|
+
// GET /v1/campaigns/{id} 進度
|
|
7
|
+
// GET /v1/campaigns/{id}/preview 預覽內容(範例收件人填好;唯讀,不留記號)
|
|
8
|
+
// GET /v1/campaigns/{id}/audience 現在開寄會寄給誰(每波每群人數、被擋人數;唯讀,不凍結)
|
|
9
|
+
// POST /v1/campaigns/{id}/preview 同上,並記下「這份內容已產生預覽」(核准的前提)
|
|
10
|
+
// POST /v1/campaigns/{id}/test 寄測試信 { to: [...], subjectPrefix? }(只准白名單信箱)
|
|
11
|
+
// POST /v1/campaigns/{id}/{action} preflight/approve/schedule/unschedule/pause/resume/cancel/
|
|
12
|
+
// retry-failed/resolve/reconcile
|
|
13
|
+
// POST /v1/broadcast/release-hold 解除寄件網域停寄 { note }
|
|
14
|
+
// PUT /v1/warmup/{plan}/{step} 設定一步 { waves, maxCount?, gate? }
|
|
15
|
+
// GET /v1/warmup/{plan} 列出這條梯子
|
|
16
|
+
// POST /v1/warmup/{plan}/evaluate 評過關 { campaign, baselineOpenRate }
|
|
17
|
+
// POST /v1/warmup/{plan}/unblock 解鎖 { note }
|
|
18
|
+
|
|
19
|
+
import type { ListDb } from '../lists.ts';
|
|
20
|
+
import {
|
|
21
|
+
approveCampaign, cancelCampaign, getCampaign, pauseCampaign, recordPreflight, resumeCampaign, saveDraft, scheduleCampaign, unscheduleCampaign,
|
|
22
|
+
type CampaignInput,
|
|
23
|
+
} from './campaigns.ts';
|
|
24
|
+
import { resolveConfig, type BroadcastConfig } from './config.ts';
|
|
25
|
+
import { releaseHold, resolveUncertain, retryFailed } from './dispatch.ts';
|
|
26
|
+
import { audiencePlan } from './audience.ts';
|
|
27
|
+
import { reconcileCampaign } from './reconcile.ts';
|
|
28
|
+
import { previewContent, sendTest, type TestSendDeps } from './test-send.ts';
|
|
29
|
+
import { campaignStatus, previewedHash, throttleStatus } from './status.ts';
|
|
30
|
+
import { evaluateWarmup, planSteps, unblockWarmup, upsertWarmupStep } from './warmup.ts';
|
|
31
|
+
|
|
32
|
+
export interface RouteDeps {
|
|
33
|
+
db: ListDb; domain: string; config?: Partial<BroadcastConfig> | string; now?: () => Date;
|
|
34
|
+
/** 測試信要用的郵差、個人化與白名單;沒給=測試信功能關閉(回 test_recipients_not_configured)。 */
|
|
35
|
+
test?: Omit<TestSendDeps, 'domain' | 'now'>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' } });
|
|
39
|
+
|
|
40
|
+
const CAMPAIGN_PATH = /^\/v1\/campaigns\/([a-z0-9][a-z0-9-]{0,39})(?:\/([a-z-]{3,20}))?$/;
|
|
41
|
+
const WARMUP_PATH = /^\/v1\/warmup\/([a-z0-9][a-z0-9-]{0,39})(?:\/(\d{1,3}|evaluate|unblock))?$/;
|
|
42
|
+
|
|
43
|
+
/** 這個路徑歸不歸群發管(index.ts 用來決定要不要先驗口令)。 */
|
|
44
|
+
export function isBroadcastPath(pathname: string): boolean {
|
|
45
|
+
return pathname === '/v1/throttle' || pathname === '/v1/broadcast/release-hold' || CAMPAIGN_PATH.test(pathname) || WARMUP_PATH.test(pathname);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 失敗的結果對應狀態碼:找不到 404、狀態不對 409、其他 400。 */
|
|
49
|
+
function outcome(r: { ok: boolean; reason?: string }): Response {
|
|
50
|
+
if (r.ok) return json(r);
|
|
51
|
+
const status = r.reason === 'not_found' ? 404 : r.reason === 'recipient_not_allowed' ? 403 : ['illegal_transition', 'locked', 'changed_meanwhile', 'conflict', 'domain_held', 'illegal_state', 'not_uncertain', 'preview_required', 'duplicate_content'].includes(r.reason ?? '') ? 409 : 400;
|
|
52
|
+
return json(r, status);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function parseCounts(counts: string | null): unknown {
|
|
56
|
+
try {
|
|
57
|
+
return counts ? JSON.parse(counts) : null;
|
|
58
|
+
} catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 預覽:POST 才會記「已預覽」(綁內容雜湊)。內容裡只有範例收件人,沒有任何真實地址。 */
|
|
64
|
+
async function previewResponse(db: ListDb, id: string, mark: boolean, _cfg: BroadcastConfig, now = new Date()): Promise<Response> {
|
|
65
|
+
const c = await getCampaign(db, id);
|
|
66
|
+
if (!c) return json({ ok: false, reason: 'not_found' }, 404);
|
|
67
|
+
const p = previewContent(c);
|
|
68
|
+
if ('error' in p) return json({ ok: false, reason: 'preview_failed', error: p.error }, 400);
|
|
69
|
+
if (mark) {
|
|
70
|
+
await db.prepare("UPDATE campaigns SET counts = json_set(COALESCE(counts, '{}'), '$.previewHash', ?, '$.previewAt', ?) WHERE id = ?").bind(c.content_hash, now.toISOString(), id).run();
|
|
71
|
+
}
|
|
72
|
+
let preflight: unknown = null;
|
|
73
|
+
try {
|
|
74
|
+
preflight = c.preflight ? JSON.parse(c.preflight) : null;
|
|
75
|
+
} catch {
|
|
76
|
+
/* 留 null */
|
|
77
|
+
}
|
|
78
|
+
const headerOnly = c.headers ? (() => { try { return JSON.parse(c.headers) as Record<string, string>; } catch { return {}; } })() : {};
|
|
79
|
+
return json({
|
|
80
|
+
ok: true, id: c.id, status: c.status, list: c.list_id, subject: c.subject, preheader: c.preheader, from: c.from_addr, replyTo: c.reply_to, webUrl: c.web_url, sourceRef: c.source_ref,
|
|
81
|
+
htmlBytes: new TextEncoder().encode(c.html).length, html: p.html, text: p.text, htmlNoName: p.htmlNoName, textNoName: p.textNoName, headers: Object.keys(headerOnly),
|
|
82
|
+
preflight, previewed: mark, contentHash: c.content_hash,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function handleBroadcastRequest(request: Request, url: URL, deps: RouteDeps): Promise<Response | null> {
|
|
87
|
+
const { db, domain } = deps;
|
|
88
|
+
const now = deps.now ?? (() => new Date());
|
|
89
|
+
const cfg = resolveConfig(deps.config);
|
|
90
|
+
const m = request.method;
|
|
91
|
+
const body = async (): Promise<Record<string, unknown> | null> => {
|
|
92
|
+
if (m === 'GET') return {};
|
|
93
|
+
const b = (await request.json().catch(() => null)) as Record<string, unknown> | null;
|
|
94
|
+
return b && typeof b === 'object' && !Array.isArray(b) ? b : null;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
if (url.pathname === '/v1/throttle') {
|
|
98
|
+
if (m !== 'GET') return null;
|
|
99
|
+
return json(await throttleStatus(db, domain, deps.config, now()));
|
|
100
|
+
}
|
|
101
|
+
if (url.pathname === '/v1/broadcast/release-hold') {
|
|
102
|
+
if (m !== 'POST') return null;
|
|
103
|
+
const b = await body();
|
|
104
|
+
if (!b) return json({ ok: false, reason: 'bad_json' }, 400);
|
|
105
|
+
return outcome(await releaseHold(db, domain, String(b.note ?? ''), now()));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const cp = CAMPAIGN_PATH.exec(url.pathname);
|
|
109
|
+
if (cp) {
|
|
110
|
+
const [, id, action] = cp;
|
|
111
|
+
if (!action) {
|
|
112
|
+
if (m === 'GET') {
|
|
113
|
+
const s = await campaignStatus(db, id, deps.config);
|
|
114
|
+
return s ? json(s) : json({ ok: false, reason: 'not_found' }, 404);
|
|
115
|
+
}
|
|
116
|
+
if (m !== 'PUT') return null;
|
|
117
|
+
const b = await body();
|
|
118
|
+
if (!b) return json({ ok: false, reason: 'bad_json' }, 400);
|
|
119
|
+
return outcome(await saveDraft(db, { ...(b as unknown as CampaignInput), id }, { marketingDomain: domain, now }));
|
|
120
|
+
}
|
|
121
|
+
if (action === 'audience' && m === 'GET') {
|
|
122
|
+
const p = await audiencePlan(db, id);
|
|
123
|
+
return p ? json(p) : json({ ok: false, reason: 'not_found' }, 404);
|
|
124
|
+
}
|
|
125
|
+
if (action === 'preview' && m === 'GET') return previewResponse(db, id, false, cfg);
|
|
126
|
+
if (m !== 'POST') return null;
|
|
127
|
+
const b = await body();
|
|
128
|
+
if (!b) return json({ ok: false, reason: 'bad_json' }, 400);
|
|
129
|
+
switch (action) {
|
|
130
|
+
case 'preview':
|
|
131
|
+
return previewResponse(db, id, true, cfg, now());
|
|
132
|
+
case 'test':
|
|
133
|
+
return outcome(await sendTest(db, id, b, { ...(deps.test ?? { postman: null as never, render: null as never, allowed: [] }), domain, now }));
|
|
134
|
+
case 'preflight':
|
|
135
|
+
return outcome(await recordPreflight(db, id, b as never, now));
|
|
136
|
+
case 'approve': {
|
|
137
|
+
// 沒有預覽就不能核准:預覽那一刻的內容雜湊要等於現在的內容(內容改過要重新預覽)。
|
|
138
|
+
const cur = await getCampaign(db, id);
|
|
139
|
+
if (cur && previewedHash(parseCounts(cur.counts)) !== cur.content_hash) return json({ ok: false, reason: 'preview_required' }, 409);
|
|
140
|
+
return outcome(await approveCampaign(db, id, String(b.note ?? ''), now));
|
|
141
|
+
}
|
|
142
|
+
case 'schedule':
|
|
143
|
+
return outcome(await scheduleCampaign(db, id, String(b.at ?? ''), now));
|
|
144
|
+
case 'unschedule':
|
|
145
|
+
return outcome(await unscheduleCampaign(db, id, now));
|
|
146
|
+
case 'pause':
|
|
147
|
+
return outcome(await pauseCampaign(db, id, String(b.reason ?? ''), now));
|
|
148
|
+
case 'resume':
|
|
149
|
+
return outcome(await resumeCampaign(db, id, String(b.note ?? ''), { marketingDomain: domain, now }));
|
|
150
|
+
case 'cancel':
|
|
151
|
+
return outcome(await cancelCampaign(db, id, String(b.reason ?? ''), now));
|
|
152
|
+
case 'retry-failed':
|
|
153
|
+
return outcome(await retryFailed(db, id));
|
|
154
|
+
case 'resolve':
|
|
155
|
+
return outcome(await resolveUncertain(db, id, Number(b.contact), b.as as 'sent' | 'failed', String(b.note ?? ''), now()));
|
|
156
|
+
case 'reconcile': {
|
|
157
|
+
if (!(await getCampaign(db, id))) return json({ ok: false, reason: 'not_found' }, 404);
|
|
158
|
+
return json(await reconcileCampaign(db, id, cfg));
|
|
159
|
+
}
|
|
160
|
+
default:
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const wp = WARMUP_PATH.exec(url.pathname);
|
|
166
|
+
if (wp) {
|
|
167
|
+
const [, plan, sub] = wp;
|
|
168
|
+
if (!sub) return m === 'GET' ? json({ plan, steps: await planSteps(db, plan) }) : null;
|
|
169
|
+
const b = await body();
|
|
170
|
+
if (!b) return json({ ok: false, reason: 'bad_json' }, 400);
|
|
171
|
+
if (/^\d+$/.test(sub)) {
|
|
172
|
+
if (m !== 'PUT') return null;
|
|
173
|
+
return outcome(await upsertWarmupStep(db, { plan, step: Number(sub), waves: b.waves as string[][], maxCount: b.maxCount as number | undefined, gate: b.gate as never }));
|
|
174
|
+
}
|
|
175
|
+
if (m !== 'POST') return null;
|
|
176
|
+
if (sub === 'unblock') return outcome(await unblockWarmup(db, plan, String(b.note ?? '')));
|
|
177
|
+
const r = await evaluateWarmup(db, plan, String(b.campaign ?? ''), b.baselineOpenRate as number, cfg, now);
|
|
178
|
+
return json(r);
|
|
179
|
+
}
|
|
180
|
+
return null;
|
|
181
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Amazon SES(API v2)郵差:電子報用。實作 postman.ts 的 Postman 介面。
|
|
2
|
+
//
|
|
3
|
+
// 送一封:POST https://email.{地區}.amazonaws.com/v2/email/outbound-emails(SendEmail,Simple 內容+自訂標頭)。
|
|
4
|
+
// - 帶設定組(ConfigurationSetName)→ 事件經 SNS 回郵務室(ses-events.ts);帶 EmailTags(campaign、contact)→ 事件對得到人。
|
|
5
|
+
// - 退訂兩個標頭(List-Unsubscribe、List-Unsubscribe-Post)由 render 放進 mail.headers,原樣送出。
|
|
6
|
+
// - 自訂 MAIL FROM 是 SES 身分(寄件網域)層級的設定,不在每封信的請求裡;寄件網域在 SES 驗過就會套用。
|
|
7
|
+
// 報上限:GET /v2/email/account(GetAccount)→ 每秒上限、24 小時上限、已用量、帳號健康狀態。
|
|
8
|
+
//
|
|
9
|
+
// 錯誤分類(SES 沒有冪等鍵:沒拿到明確答覆就不能假設沒寄出):
|
|
10
|
+
// - 200+MessageId → ok。
|
|
11
|
+
// - 限流(TooManyRequestsException、Throttling…,「每秒上限」那種)→ throttled(引擎延遲再試)。
|
|
12
|
+
// - 「每日額度用完」→ daily_quota(引擎今天停放水、明天自動恢復;不在這裡無限重試)。
|
|
13
|
+
// - 帳號被停/暫停、寄件網域沒驗證、設定組不存在、鑰匙或權限錯(403)→ account_paused(每一封都會一樣失敗,停下來查)。
|
|
14
|
+
// - 其他 4xx(地址不合格、沙盒沒驗證的收件人、內容被拒)→ permanent(只影響這一位)。
|
|
15
|
+
// - 5xx、逾時、連線錯、回應讀不懂 → 丟例外=不知道有沒有寄出(引擎記 uncertain、絕不自動重寄)。
|
|
16
|
+
// 鑰匙、收件人、內容都不進 log 與錯誤訊息;錯誤只留 HTTP 狀態與 SES 的錯誤名稱。
|
|
17
|
+
|
|
18
|
+
import { signRequest, type AwsCredentials } from '../aws-sigv4.ts';
|
|
19
|
+
import type { Postman, PostmanLimits, PostmanMail, PostmanOutcome } from './postman.ts';
|
|
20
|
+
|
|
21
|
+
export interface SesPostmanOptions {
|
|
22
|
+
region: string;
|
|
23
|
+
credentials: AwsCredentials;
|
|
24
|
+
/** SES 設定組名稱(事件發布用)。沒給=不帶,事件就不會回來(只建議測試用)。 */
|
|
25
|
+
configurationSet?: string;
|
|
26
|
+
fetcher?: typeof fetch;
|
|
27
|
+
timeoutMs?: number;
|
|
28
|
+
now?: () => Date;
|
|
29
|
+
name?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const SES_REGION = /^[a-z]{2}(-[a-z]+)+-\d{1,2}$/;
|
|
33
|
+
const CONFIG_SET = /^[A-Za-z0-9_-]{1,64}$/;
|
|
34
|
+
const TAG_VALUE = /^[A-Za-z0-9_-]{1,256}$/;
|
|
35
|
+
/** SES MessageHeader:名稱可見 ASCII(不含冒號)≤126;值可見 ASCII ≤995、名稱+值 ≤996。 */
|
|
36
|
+
const HEADER_NAME = /^[!-9;-~]{1,126}$/;
|
|
37
|
+
const HEADER_VALUE = /^[ -~]{1,995}$/;
|
|
38
|
+
/** 這些標頭 SES 自己組,或由 API 欄位決定;不准從 mail.headers 帶進去。 */
|
|
39
|
+
const RESERVED_HEADERS = new Set(['from', 'to', 'cc', 'bcc', 'subject', 'reply-to', 'sender', 'return-path', 'message-id', 'date', 'mime-version', 'content-type', 'content-transfer-encoding']);
|
|
40
|
+
|
|
41
|
+
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
42
|
+
|
|
43
|
+
const THROTTLE_CODES = new Set(['TooManyRequestsException', 'Throttling', 'ThrottlingException']);
|
|
44
|
+
const PAUSE_CODES = new Set([
|
|
45
|
+
'AccountSuspendedException', 'SendingPausedException', 'MailFromDomainNotVerifiedException', 'NotFoundException',
|
|
46
|
+
'AccessDeniedException', 'UnrecognizedClientException', 'InvalidSignatureException', 'SignatureDoesNotMatch', 'InvalidClientTokenId',
|
|
47
|
+
'ExpiredTokenException', 'MissingAuthenticationTokenException', 'IncompleteSignatureException', 'RequestExpired', 'RequestTimeTooSkewed',
|
|
48
|
+
]);
|
|
49
|
+
|
|
50
|
+
/** 非 ASCII 的顯示名稱用 RFC 2047 編碼(SES 要求);地址本身照舊。 */
|
|
51
|
+
export function encodeAddress(a: string): string {
|
|
52
|
+
const m = /^(.*?)\s*<([^<>\s]+)>$/.exec(a.trim());
|
|
53
|
+
if (!m || !m[1]) return a.trim();
|
|
54
|
+
const name = m[1].replace(/^"(.*)"$/, '$1');
|
|
55
|
+
if (/^[\x20-\x7e]*$/.test(name)) return /[(),.:;<>@[\\\]"]/.test(name) ? `"${name.replace(/["\\]/g, '\\$&')}" <${m[2]}>` : `${name} <${m[2]}>`;
|
|
56
|
+
const bytes = new TextEncoder().encode(name);
|
|
57
|
+
let bin = '';
|
|
58
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
59
|
+
return `=?UTF-8?B?${btoa(bin)}?= <${m[2]}>`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** SES 回的錯誤名稱:x-amzn-ErrorType 標頭(`名稱:網址`)或內文 __type/code。 */
|
|
63
|
+
export function sesErrorCode(res: Response, body: Record<string, unknown>): string {
|
|
64
|
+
const h = res.headers.get('x-amzn-errortype');
|
|
65
|
+
const raw = h ?? (typeof body.__type === 'string' ? body.__type : typeof body.code === 'string' ? body.code : typeof body.Code === 'string' ? body.Code : '');
|
|
66
|
+
return raw.split(':')[0].split('#').pop()!.trim().slice(0, 80) || 'Unknown';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function errorMessage(body: Record<string, unknown>): string {
|
|
70
|
+
const m = body.message ?? body.Message;
|
|
71
|
+
return typeof m === 'string' ? m : '';
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function classifySesError(status: number, code: string, message: string): Exclude<PostmanOutcome, { ok: true }> | null {
|
|
75
|
+
if (status >= 500) return null; // 不知道有沒有收下
|
|
76
|
+
if (/daily message quota exceeded/i.test(message)) return { ok: false, kind: 'daily_quota', error: `${status} ${code} daily_quota_exceeded` };
|
|
77
|
+
if (status === 429 || THROTTLE_CODES.has(code)) return { ok: false, kind: 'throttled', error: `${status} ${code}` };
|
|
78
|
+
if (status === 403 || PAUSE_CODES.has(code)) return { ok: false, kind: 'account_paused', error: `${status} ${code}` };
|
|
79
|
+
if (status >= 400) return { ok: false, kind: 'permanent', error: `${status} ${code}` };
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export class SesPostman implements Postman {
|
|
84
|
+
readonly name: string;
|
|
85
|
+
private readonly opts: SesPostmanOptions;
|
|
86
|
+
private readonly endpoint: string;
|
|
87
|
+
|
|
88
|
+
constructor(opts: SesPostmanOptions) {
|
|
89
|
+
if (!SES_REGION.test(opts.region)) throw new Error('ses: bad region');
|
|
90
|
+
if (!opts.credentials?.accessKeyId || !opts.credentials?.secretAccessKey) throw new Error('ses: missing credentials');
|
|
91
|
+
if (opts.configurationSet !== undefined && !CONFIG_SET.test(opts.configurationSet)) throw new Error('ses: bad configuration set name');
|
|
92
|
+
this.opts = opts;
|
|
93
|
+
this.name = opts.name ?? 'ses';
|
|
94
|
+
this.endpoint = `https://email.${opts.region}.amazonaws.com`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
private async call(method: 'GET' | 'POST', path: string, body?: string): Promise<{ res: Response; json: Record<string, unknown> }> {
|
|
98
|
+
const url = `${this.endpoint}${path}`;
|
|
99
|
+
const signed = await signRequest({
|
|
100
|
+
method, url, body, region: this.opts.region, service: 'ses', credentials: this.opts.credentials,
|
|
101
|
+
headers: body !== undefined ? { 'content-type': 'application/json' } : {},
|
|
102
|
+
now: (this.opts.now ?? (() => new Date()))(),
|
|
103
|
+
});
|
|
104
|
+
// host 由 fetch 依網址自己帶(簽進去的就是同一個值)。
|
|
105
|
+
const { host: _host, ...headers } = signed;
|
|
106
|
+
const controller = new AbortController();
|
|
107
|
+
const timeoutMs = this.opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
108
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
109
|
+
try {
|
|
110
|
+
const res = await (this.opts.fetcher ?? fetch)(url, { method, headers, body, signal: controller.signal });
|
|
111
|
+
const text = await res.text();
|
|
112
|
+
let json: Record<string, unknown> = {};
|
|
113
|
+
try {
|
|
114
|
+
const parsed = text ? JSON.parse(text) : {};
|
|
115
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) json = parsed;
|
|
116
|
+
} catch {
|
|
117
|
+
/* 讀不懂就當空的;下面依狀態碼判斷 */
|
|
118
|
+
}
|
|
119
|
+
return { res, json };
|
|
120
|
+
} catch (e) {
|
|
121
|
+
if (e instanceof Error && e.name === 'AbortError') throw new Error(`ses timeout (${timeoutMs}ms)`);
|
|
122
|
+
throw new Error('ses network error');
|
|
123
|
+
} finally {
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async send(mail: PostmanMail): Promise<PostmanOutcome> {
|
|
129
|
+
const headers: { Name: string; Value: string }[] = [];
|
|
130
|
+
for (const [name, value] of Object.entries(mail.headers ?? {})) {
|
|
131
|
+
if (!HEADER_NAME.test(name) || typeof value !== 'string' || !HEADER_VALUE.test(value) || name.length + value.length > 996 || RESERVED_HEADERS.has(name.toLowerCase())) {
|
|
132
|
+
return { ok: false, kind: 'permanent', error: 'bad_header' };
|
|
133
|
+
}
|
|
134
|
+
headers.push({ Name: name, Value: value });
|
|
135
|
+
}
|
|
136
|
+
const tags: { Name: string; Value: string }[] = [];
|
|
137
|
+
for (const [name, value] of [['campaign', mail.tags.campaign], ['contact', mail.tags.contact]] as const) {
|
|
138
|
+
if (!TAG_VALUE.test(String(value))) return { ok: false, kind: 'permanent', error: `bad_tag_${name}` };
|
|
139
|
+
tags.push({ Name: name, Value: String(value) });
|
|
140
|
+
}
|
|
141
|
+
const payload: Record<string, unknown> = {
|
|
142
|
+
FromEmailAddress: encodeAddress(mail.from),
|
|
143
|
+
Destination: { ToAddresses: [mail.to] },
|
|
144
|
+
Content: {
|
|
145
|
+
Simple: {
|
|
146
|
+
Subject: { Data: mail.subject, Charset: 'UTF-8' },
|
|
147
|
+
Body: { Html: { Data: mail.html, Charset: 'UTF-8' }, Text: { Data: mail.text, Charset: 'UTF-8' } },
|
|
148
|
+
...(headers.length ? { Headers: headers } : {}),
|
|
149
|
+
},
|
|
150
|
+
},
|
|
151
|
+
EmailTags: tags,
|
|
152
|
+
...(mail.replyTo ? { ReplyToAddresses: [encodeAddress(mail.replyTo)] } : {}),
|
|
153
|
+
...(this.opts.configurationSet ? { ConfigurationSetName: this.opts.configurationSet } : {}),
|
|
154
|
+
};
|
|
155
|
+
const { res, json } = await this.call('POST', '/v2/email/outbound-emails', JSON.stringify(payload));
|
|
156
|
+
if (res.ok) {
|
|
157
|
+
if (typeof json.MessageId === 'string' && json.MessageId) return { ok: true, providerId: json.MessageId };
|
|
158
|
+
throw new Error(`ses ${res.status} without MessageId`);
|
|
159
|
+
}
|
|
160
|
+
const code = sesErrorCode(res, json);
|
|
161
|
+
const out = classifySesError(res.status, code, errorMessage(json));
|
|
162
|
+
if (!out) throw new Error(`ses ${res.status} ${code}`);
|
|
163
|
+
return out;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async limits(): Promise<PostmanLimits> {
|
|
167
|
+
const { res, json } = await this.call('GET', '/v2/email/account');
|
|
168
|
+
if (!res.ok) throw new Error(`ses GetAccount ${res.status} ${sesErrorCode(res, json)}`);
|
|
169
|
+
const q = (json.SendQuota ?? {}) as { Max24HourSend?: unknown; MaxSendRate?: unknown; SentLast24Hours?: unknown };
|
|
170
|
+
const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : 0);
|
|
171
|
+
// 寄信被關(SendingEnabled=false)也當成不健康:引擎會停寄。
|
|
172
|
+
const enforcement = json.SendingEnabled === false ? 'SENDING_DISABLED' : typeof json.EnforcementStatus === 'string' && json.EnforcementStatus ? json.EnforcementStatus : 'UNKNOWN';
|
|
173
|
+
return {
|
|
174
|
+
perSecond: num(q.MaxSendRate),
|
|
175
|
+
perDay: num(q.Max24HourSend),
|
|
176
|
+
sentLast24h: num(q.SentLast24Hours),
|
|
177
|
+
enforcement,
|
|
178
|
+
...(typeof json.ProductionAccessEnabled === 'boolean' ? { production: json.ProductionAccessEnabled } : {}),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// 煞車、暖機、對帳共用的計數。分母一律是「真的寄出」(campaign_recipients.state='done');
|
|
2
|
+
// 退信、檢舉、開信都以「人」計(同一人同一期多則事件只算一次)。
|
|
3
|
+
|
|
4
|
+
import type { Db } from '../core.ts';
|
|
5
|
+
|
|
6
|
+
export interface CampaignRates {
|
|
7
|
+
sent: number;
|
|
8
|
+
hardBounces: number;
|
|
9
|
+
complaints: number;
|
|
10
|
+
opens: number;
|
|
11
|
+
hardBounceRate: number;
|
|
12
|
+
complaintRate: number;
|
|
13
|
+
/** 開信人數 ÷(寄出 − 永久退信)。 */
|
|
14
|
+
openRate: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const rate = (n: number, d: number) => (d > 0 ? n / d : 0);
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* wave=只算這一波;since=只算這個時間之後寄出的人(續寄後重新起算:人查過、放行了,舊的比率不再拿來踩煞車)。
|
|
21
|
+
*/
|
|
22
|
+
export async function campaignRates(db: Db, campaignId: string, wave?: number, since?: string | null): Promise<CampaignRates> {
|
|
23
|
+
const waveSql = (wave === undefined ? '' : ' AND r.wave = ?') + (since ? ' AND r.done_at >= ?' : '');
|
|
24
|
+
const waveBind: unknown[] = [...(wave === undefined ? [] : [wave]), ...(since ? [since] : [])];
|
|
25
|
+
const sent = await db.prepare(`SELECT COUNT(*) AS n FROM campaign_recipients r WHERE r.campaign_id = ? AND r.state = 'done'${waveSql}`).bind(campaignId, ...waveBind).first<{ n: number }>();
|
|
26
|
+
const ev = await db
|
|
27
|
+
.prepare(
|
|
28
|
+
`SELECT
|
|
29
|
+
COUNT(DISTINCT CASE WHEN e.type = 'bounce' AND e.subtype LIKE 'Permanent%' THEN e.contact_id END) AS hard,
|
|
30
|
+
COUNT(DISTINCT CASE WHEN e.type = 'complaint' THEN e.contact_id END) AS complaints,
|
|
31
|
+
COUNT(DISTINCT CASE WHEN e.type = 'open' THEN e.contact_id END) AS opens
|
|
32
|
+
FROM events e JOIN campaign_recipients r ON r.campaign_id = e.campaign_id AND r.contact_id = e.contact_id
|
|
33
|
+
WHERE e.campaign_id = ?${waveSql}`,
|
|
34
|
+
)
|
|
35
|
+
.bind(campaignId, ...waveBind)
|
|
36
|
+
.first<{ hard: number; complaints: number; opens: number }>();
|
|
37
|
+
const s = Number(sent?.n ?? 0);
|
|
38
|
+
const hard = Number(ev?.hard ?? 0);
|
|
39
|
+
const complaints = Number(ev?.complaints ?? 0);
|
|
40
|
+
const opens = Number(ev?.opens ?? 0);
|
|
41
|
+
return { sent: s, hardBounces: hard, complaints, opens, hardBounceRate: rate(hard, s), complaintRate: rate(complaints, s), openRate: rate(opens, s - hard) };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 寄件網域的滾動比率:最近 days 天寄出的電子報裡,有幾封後來永久退信/被檢舉(以信件計)。 */
|
|
45
|
+
export async function domainRates(db: Db, site: string, since: string): Promise<{ sent: number; hardBounces: number; complaints: number; hardBounceRate: number; complaintRate: number }> {
|
|
46
|
+
const row = await db
|
|
47
|
+
.prepare(
|
|
48
|
+
`SELECT COUNT(*) AS sent,
|
|
49
|
+
SUM(CASE WHEN EXISTS (SELECT 1 FROM events e WHERE e.message_id = m.id AND e.type = 'bounce' AND e.subtype LIKE 'Permanent%') THEN 1 ELSE 0 END) AS hard,
|
|
50
|
+
SUM(CASE WHEN EXISTS (SELECT 1 FROM events e WHERE e.message_id = m.id AND e.type = 'complaint') THEN 1 ELSE 0 END) AS complaints
|
|
51
|
+
FROM messages m WHERE m.site = ? AND m.stream = 'marketing' AND m.status = 'sent' AND m.sent_at >= ?`,
|
|
52
|
+
)
|
|
53
|
+
.bind(site, since)
|
|
54
|
+
.first<{ sent: number; hard: number | null; complaints: number | null }>();
|
|
55
|
+
const sent = Number(row?.sent ?? 0);
|
|
56
|
+
const hard = Number(row?.hard ?? 0);
|
|
57
|
+
const complaints = Number(row?.complaints ?? 0);
|
|
58
|
+
return { sent, hardBounces: hard, complaints, hardBounceRate: rate(hard, sent), complaintRate: rate(complaints, sent) };
|
|
59
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// 進度與節流狀態(唯讀):給指令與報表看。不回信件內文、不回收件人地址。
|
|
2
|
+
|
|
3
|
+
import { localDay } from '../core.ts';
|
|
4
|
+
import type { ListDb } from '../lists.ts';
|
|
5
|
+
import { getCampaign } from './campaigns.ts';
|
|
6
|
+
import { resolveConfig, type BroadcastConfig } from './config.ts';
|
|
7
|
+
import { activeHold } from './dispatch.ts';
|
|
8
|
+
import { explainPause } from './explain.ts';
|
|
9
|
+
import { campaignRates } from './stats.ts';
|
|
10
|
+
|
|
11
|
+
export async function campaignStatus(db: ListDb, id: string, config?: Partial<BroadcastConfig> | string) {
|
|
12
|
+
const c = await getCampaign(db, id);
|
|
13
|
+
if (!c) return null;
|
|
14
|
+
const states = (await db.prepare('SELECT state, skip_reason, wave, COUNT(*) AS n FROM campaign_recipients WHERE campaign_id = ? GROUP BY state, skip_reason, wave ORDER BY wave').bind(id).all()).results;
|
|
15
|
+
const rates = await campaignRates(db, id);
|
|
16
|
+
let counts: unknown = null;
|
|
17
|
+
try {
|
|
18
|
+
counts = c.counts ? JSON.parse(c.counts) : null;
|
|
19
|
+
} catch {
|
|
20
|
+
/* 留 null */
|
|
21
|
+
}
|
|
22
|
+
const parse = (s: string | null) => {
|
|
23
|
+
try {
|
|
24
|
+
return s ? JSON.parse(s) : null;
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
return {
|
|
30
|
+
id: c.id, list: c.list_id, subject: c.subject, status: c.status, pauseReason: c.pause_reason,
|
|
31
|
+
audience: parse(c.audience), audienceResolved: parse(c.audience_resolved),
|
|
32
|
+
approved: c.approved_hash !== null && c.approved_hash === c.content_hash, approvedAt: c.approved_at, approvedNote: c.approved_note,
|
|
33
|
+
preflight: parse(c.preflight), scheduledAt: c.scheduled_at, startedAt: c.started_at, frozenAt: c.frozen_at,
|
|
34
|
+
lastReleaseAt: c.last_release_at, lastProgressAt: c.last_progress_at, finishedAt: c.finished_at,
|
|
35
|
+
recipients: states, rates, counts, pauseExplain: explainPause(c.pause_reason, resolveConfig(config)),
|
|
36
|
+
previewed: previewedHash(counts) === c.content_hash,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 預覽記號:POST preview 時記下當時的內容雜湊;內容一改就對不上。 */
|
|
41
|
+
export function previewedHash(counts: unknown): string | null {
|
|
42
|
+
return counts && typeof counts === 'object' && typeof (counts as { previewHash?: unknown }).previewHash === 'string' ? (counts as { previewHash: string }).previewHash : null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function throttleStatus(db: ListDb, domain: string, config?: Partial<BroadcastConfig> | string, now = new Date()) {
|
|
46
|
+
const cfg = resolveConfig(config);
|
|
47
|
+
const day = localDay(now, cfg.utcOffsetHours);
|
|
48
|
+
const today = await db.prepare('SELECT * FROM throttle_days WHERE domain = ? AND day = ?').bind(domain, day).first();
|
|
49
|
+
const hold = await activeHold(db, domain);
|
|
50
|
+
const campaigns = (await db.prepare("SELECT id, status, pause_reason, started_at, last_release_at, last_progress_at, counts FROM campaigns WHERE status IN ('scheduled', 'sending', 'paused') ORDER BY id").all<Record<string, unknown>>()).results.map((r) => {
|
|
51
|
+
let counts: unknown = null;
|
|
52
|
+
try {
|
|
53
|
+
counts = r.counts ? JSON.parse(String(r.counts)) : null;
|
|
54
|
+
} catch {
|
|
55
|
+
/* 留 null */
|
|
56
|
+
}
|
|
57
|
+
return { ...r, counts };
|
|
58
|
+
});
|
|
59
|
+
return { domain, day, today, hold, config: cfg, campaigns };
|
|
60
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// 測試信與預覽:測試信走真郵差、帶真標頭,但只寄給「設定檔白名單」裡的內部信箱,不進凍結名單、不進暖機、不算統計。
|
|
2
|
+
// 預覽:把一期信用範例收件人填好(不需要郵差),給預覽頁與指令看。
|
|
3
|
+
|
|
4
|
+
import { personalize } from '../compose/personalize.ts';
|
|
5
|
+
import type { ListDb } from '../lists.ts';
|
|
6
|
+
import { getCampaign, type CampaignRow, type Fail, type Ok } from './campaigns.ts';
|
|
7
|
+
import { activeHold, type Render } from './dispatch.ts';
|
|
8
|
+
import type { Postman } from './postman.ts';
|
|
9
|
+
|
|
10
|
+
export const MAX_TEST_RECIPIENTS = 10;
|
|
11
|
+
const DEFAULT_PREFIX = '[Test] ';
|
|
12
|
+
const SAMPLE = { email: 'reader@example.com', unsubscribe_url: 'https://example.com/unsubscribe/preview', unsubscribe_mailto: 'mailto:unsubscribe@example.com?subject=preview' };
|
|
13
|
+
|
|
14
|
+
export interface TestSendDeps {
|
|
15
|
+
postman: Postman;
|
|
16
|
+
render: Render;
|
|
17
|
+
/** 允許收測試信的內部信箱(全部小寫)。空=測試信功能關閉。 */
|
|
18
|
+
allowed: readonly string[];
|
|
19
|
+
domain: string;
|
|
20
|
+
now?: () => Date;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const ctl = (s: string) => /[\u0000-\u001f\u007f]/.test(s);
|
|
24
|
+
|
|
25
|
+
/** 白名單從環境變數來:JSON 陣列或逗號分隔字串。 */
|
|
26
|
+
export function parseAllowed(v: unknown): string[] {
|
|
27
|
+
let list: unknown[] = [];
|
|
28
|
+
if (Array.isArray(v)) list = v;
|
|
29
|
+
else if (typeof v === 'string' && v.trim()) {
|
|
30
|
+
try {
|
|
31
|
+
const p = JSON.parse(v);
|
|
32
|
+
list = Array.isArray(p) ? p : v.split(',');
|
|
33
|
+
} catch {
|
|
34
|
+
list = v.split(',');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return [...new Set(list.map((x) => String(x).trim().toLowerCase()).filter((x) => /^[^\s@<>",]+@[^\s@<>",]+$/.test(x)))];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function sendTest(db: ListDb, id: string, input: { to?: unknown; subjectPrefix?: unknown }, deps: TestSendDeps): Promise<Ok<{ results: { to: string; ok: boolean; error?: string }[] }> | Fail> {
|
|
41
|
+
if (!deps.allowed.length) return { ok: false, reason: 'test_recipients_not_configured' };
|
|
42
|
+
const c = await getCampaign(db, id);
|
|
43
|
+
if (!c) return { ok: false, reason: 'not_found' };
|
|
44
|
+
if (c.status === 'cancelled' || c.status === 'done') return { ok: false, reason: 'illegal_state', status: c.status };
|
|
45
|
+
if (!Array.isArray(input.to) || input.to.length === 0 || input.to.length > MAX_TEST_RECIPIENTS) return { ok: false, reason: 'bad_recipients' };
|
|
46
|
+
const to = [...new Set(input.to.map((x) => String(x).trim().toLowerCase()))];
|
|
47
|
+
if (to.some((a) => !deps.allowed.includes(a))) return { ok: false, reason: 'recipient_not_allowed' };
|
|
48
|
+
const prefix = input.subjectPrefix === undefined ? DEFAULT_PREFIX : typeof input.subjectPrefix === 'string' && input.subjectPrefix.length <= 20 && !ctl(input.subjectPrefix) ? input.subjectPrefix : null;
|
|
49
|
+
if (prefix === null) return { ok: false, reason: 'bad_prefix' };
|
|
50
|
+
if (await activeHold(db, deps.domain)) return { ok: false, reason: 'domain_held' };
|
|
51
|
+
const now = (deps.now ?? (() => new Date()))();
|
|
52
|
+
const results: { to: string; ok: boolean; error?: string }[] = [];
|
|
53
|
+
for (const [i, addr] of to.entries()) {
|
|
54
|
+
try {
|
|
55
|
+
// contact 0=不存在的收件人:退訂連結照樣產生,但點了查無此人(測試信不該真的讓誰退訂)。
|
|
56
|
+
const mail = await deps.render(c, { campaign_id: c.id, contact_id: 0, email: addr, segment: null, wave: null, rank: 0, state: 'planned', skip_reason: null, attempts: 0, message_id: null, error: null, enqueued_at: null, done_at: null, name: null });
|
|
57
|
+
const out = await deps.postman.send({
|
|
58
|
+
from: c.from_addr, to: addr, subject: `${prefix}${c.subject}`.slice(0, 320), html: mail.html, text: mail.text, replyTo: c.reply_to ?? undefined,
|
|
59
|
+
headers: { ...(mail.headers ?? {}) }, tags: { campaign: c.id, contact: 'test' }, idempotencyKey: `test:${c.id}:${now.getTime()}:${i}`,
|
|
60
|
+
});
|
|
61
|
+
results.push(out.ok ? { to: addr, ok: true } : { to: addr, ok: false, error: `${out.kind} ${out.error}`.slice(0, 200) });
|
|
62
|
+
} catch (e) {
|
|
63
|
+
// 丟例外=不知道有沒有寄出:照實回報,不自動重寄。
|
|
64
|
+
results.push({ to: addr, ok: false, error: `unknown_outcome ${e instanceof Error ? e.message.slice(0, 150) : ''}`.trim() });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return { ok: true, results };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 預覽內容:用範例收件人填好個人化欄位與追蹤簽章(簽章是假的,連結不會真的記點擊)。 */
|
|
71
|
+
export function previewContent(c: CampaignRow): { html: string; text: string; htmlNoName: string; textNoName: string; headers: Record<string, string> } | { error: string } {
|
|
72
|
+
try {
|
|
73
|
+
let headers: Record<string, string> = {};
|
|
74
|
+
try {
|
|
75
|
+
headers = c.headers ? (JSON.parse(c.headers) as Record<string, string>) : {};
|
|
76
|
+
} catch {
|
|
77
|
+
return { error: 'bad_headers' };
|
|
78
|
+
}
|
|
79
|
+
if (!c.web_url) return { error: 'web_url_required' };
|
|
80
|
+
const track = (kind: 'c' | 'o', index?: number) => (kind === 'c' ? `preview-${index}` : 'preview');
|
|
81
|
+
const vars = { ...SAMPLE, web_url: c.web_url };
|
|
82
|
+
const a = personalize({ html: c.html, text: c.text, headers }, { ...vars, name: 'Sample Reader' }, { track });
|
|
83
|
+
const b = personalize({ html: c.html, text: c.text, headers }, { ...vars, name: null }, { track });
|
|
84
|
+
return { html: a.html, text: a.text, htmlNoName: b.html, textNoName: b.text, headers: a.headers ?? headers };
|
|
85
|
+
} catch (e) {
|
|
86
|
+
return { error: e instanceof Error ? e.message.slice(0, 200) : 'preview_failed' };
|
|
87
|
+
}
|
|
88
|
+
}
|