@joelincc/mailroom 0.3.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.
- package/README.md +8 -4
- package/dist/cli/errors.js +6 -0
- package/dist/cli/main.js +60 -2
- package/dist/compose/compose.js +51 -0
- package/dist/compose/markdown.js +837 -277
- package/dist/compose/render.js +8 -3
- package/docs/composing.md +25 -4
- package/docs/export.md +2 -1
- package/docs/lists.md +4 -2
- package/docs/security-model.md +2 -0
- package/docs/ses.md +1 -1
- package/docs/tracking.md +102 -0
- package/docs/unsubscribe.md +11 -4
- package/docs/welcome.md +72 -0
- package/migrations/0008_tracking.sql +5 -0
- package/migrations/0009_welcome.sql +17 -0
- package/package.json +3 -1
- package/src/broadcast/campaigns.ts +21 -8
- package/src/broadcast/dispatch.ts +16 -3
- package/src/broadcast/events.ts +6 -3
- package/src/broadcast/worker.ts +44 -3
- package/src/cli/errors.ts +6 -0
- package/src/cli/main.ts +51 -2
- package/src/compose/compose.ts +40 -0
- package/src/compose/markdown.ts +796 -247
- package/src/compose/render.ts +8 -3
- package/src/core.ts +3 -1
- package/src/feedback.ts +21 -4
- package/src/index.ts +31 -6
- package/src/list-routes.ts +18 -5
- package/src/lists.ts +13 -2
- package/src/track.ts +409 -0
- package/src/welcome.ts +257 -0
package/src/broadcast/events.ts
CHANGED
|
@@ -38,13 +38,15 @@ export async function ingestEvent(db: Db, ev: ProviderEvent, opts: IngestOptions
|
|
|
38
38
|
|
|
39
39
|
// 對到帳本列與期別/收件人:優先用郵差的信件 id,其次用事件帶的標籤。
|
|
40
40
|
let msg = ev.providerMessageId
|
|
41
|
-
? await db.prepare('SELECT id, to_email FROM messages WHERE provider_id = ? LIMIT 1').bind(String(ev.providerMessageId)).first<{ id: number; to_email: string }>()
|
|
41
|
+
? await db.prepare('SELECT id, to_email, stream FROM messages WHERE provider_id = ? LIMIT 1').bind(String(ev.providerMessageId)).first<{ id: number; to_email: string; stream?: string }>()
|
|
42
42
|
: null;
|
|
43
43
|
let campaign = typeof ev.campaign === 'string' && ev.campaign ? ev.campaign.slice(0, 64) : null;
|
|
44
44
|
let contact = ev.contact !== undefined && ev.contact !== null && /^\d{1,15}$/.test(String(ev.contact)) ? Number(ev.contact) : null;
|
|
45
45
|
// 事件可能比「帳本記下郵差 id」更早回來;帳本列在交郵差前就建好了,用去重鍵找得到。
|
|
46
46
|
if (!msg && campaign && contact !== null) {
|
|
47
|
-
|
|
47
|
+
// 歡迎信的標籤是 _welcome-{名單},去重鍵是 welcome:{名單}:{聯絡人}。
|
|
48
|
+
const key = campaign.startsWith('_welcome-') ? `welcome:${campaign.slice('_welcome-'.length)}:${contact}` : `c:${campaign}:${contact}`;
|
|
49
|
+
msg = await db.prepare("SELECT id, to_email, stream FROM messages WHERE dedupe_key = ? AND stream = 'marketing' LIMIT 1").bind(key).first<{ id: number; to_email: string; stream?: string }>();
|
|
48
50
|
}
|
|
49
51
|
if (msg && (campaign === null || contact === null)) {
|
|
50
52
|
const r = await db.prepare('SELECT campaign_id, contact_id FROM campaign_recipients WHERE message_id = ? LIMIT 1').bind(msg.id).first<{ campaign_id: string; contact_id: number }>();
|
|
@@ -83,7 +85,8 @@ export async function ingestEvent(db: Db, ev: ProviderEvent, opts: IngestOptions
|
|
|
83
85
|
...(ev.cause === 'mailbox' || ev.cause === 'content' ? { cause: ev.cause } : {}),
|
|
84
86
|
}
|
|
85
87
|
: ev.type === 'complaint'
|
|
86
|
-
?
|
|
88
|
+
? // 這裡是電子報郵差的事件:被檢舉的是電子報那類信,只擋電子報(交易信照寄)。只有對到的帳本列明確是交易類才擋全部。
|
|
89
|
+
{ type: 'complaint', email, source, detail, scope: msg?.stream === 'transactional' ? 'all' : 'marketing' }
|
|
87
90
|
: { type: 'delivery', email };
|
|
88
91
|
if (opts.feedback) await opts.feedback(fb);
|
|
89
92
|
else await applyFeedback(db, fb, { now: () => now });
|
package/src/broadcast/worker.ts
CHANGED
|
@@ -9,6 +9,7 @@ import type { IngestOptions } from './events.ts';
|
|
|
9
9
|
import { FakePostman, type FakeRule, type Postman } from './postman.ts';
|
|
10
10
|
import { parseAllowed, type TestSendDeps } from './test-send.ts';
|
|
11
11
|
import { SesPostman } from './ses.ts';
|
|
12
|
+
import { trackHost, trackSecrets, trackSigner } from '../track.ts';
|
|
12
13
|
|
|
13
14
|
export interface BroadcastEnv {
|
|
14
15
|
DB: D1Database;
|
|
@@ -40,6 +41,14 @@ export interface BroadcastEnv {
|
|
|
40
41
|
UNSUB_MAILTO?: string;
|
|
41
42
|
/** 允許收測試信的內部信箱(JSON 陣列或逗號分隔)。沒設=測試信功能關閉。 */
|
|
42
43
|
TEST_RECIPIENTS?: string | string[];
|
|
44
|
+
/** 追蹤網址的根(https,例 https://t.example.com)。要同時有 TRACK_TOKEN_SECRET 才開追蹤端點。 */
|
|
45
|
+
TRACK_BASE_URL?: string;
|
|
46
|
+
/** 追蹤券簽章鑰匙(Secret,至少 16 字元)。內容用到追蹤佔位卻沒設=那期因 render_error 暫停(不寄出點了會壞的信)。 */
|
|
47
|
+
TRACK_TOKEN_SECRET?: string;
|
|
48
|
+
/** 換鑰匙過渡期:舊鑰匙(逗號分隔),只驗證不簽新券。 */
|
|
49
|
+
TRACK_TOKEN_SECRET_PREVIOUS?: string;
|
|
50
|
+
/** 追蹤設定(JSON,只寫想改的欄位,見 docs/tracking.md)。 */
|
|
51
|
+
TRACK_CONFIG?: string | Record<string, unknown>;
|
|
43
52
|
}
|
|
44
53
|
|
|
45
54
|
export const DEFAULT_BROADCAST_QUEUE = 'mailroom-broadcast';
|
|
@@ -95,7 +104,9 @@ type Links = { unsubscribe_url: string; unsubscribe_mailto?: string | null };
|
|
|
95
104
|
* 預設的個人化:compose 的 personalize({{name}} {{email}} {{unsubscribe_url}} {{unsubscribe_mailto}} {{web_url}},標頭一起填)。
|
|
96
105
|
* 退訂連結由 links 提供;拿不到=丟例外(這期會被暫停,不寄出沒有退訂連結的信)。
|
|
97
106
|
*/
|
|
98
|
-
export
|
|
107
|
+
export type TrackFor = (c: CampaignRow, r: RecipientRow, contents: string[]) => Promise<NonNullable<Parameters<typeof personalize>[2]>['track']>;
|
|
108
|
+
|
|
109
|
+
export function personalizeRender(links?: (c: CampaignRow, r: RecipientRow) => Links | null | Promise<Links | null>, track?: Parameters<typeof personalize>[2] | TrackFor) {
|
|
99
110
|
return async (c: CampaignRow, r: RecipientRow & { name: string | null }): Promise<RenderResult> => {
|
|
100
111
|
const l = await links?.(c, r);
|
|
101
112
|
if (!l) throw new Error('unsubscribe links not configured');
|
|
@@ -106,7 +117,8 @@ export function personalizeRender(links?: (c: CampaignRow, r: RecipientRow) => L
|
|
|
106
117
|
} catch {
|
|
107
118
|
throw new Error('bad campaign headers');
|
|
108
119
|
}
|
|
109
|
-
|
|
120
|
+
const opts = typeof track === 'function' ? { track: await track(c, r, [c.html, c.text, ...Object.values(headers)]) } : track;
|
|
121
|
+
return personalize({ html: c.html, text: c.text, headers }, { name: r.name, email: r.email, web_url: c.web_url, ...l }, opts);
|
|
110
122
|
};
|
|
111
123
|
}
|
|
112
124
|
|
|
@@ -120,6 +132,34 @@ export function unsubLinksFromEnv(env: BroadcastEnv) {
|
|
|
120
132
|
};
|
|
121
133
|
}
|
|
122
134
|
|
|
135
|
+
/** 追蹤券(每位收件人、每個連結一張)。沒設鑰匙=undefined:內容沒用到追蹤佔位就照常寄;用到了 personalize 會丟例外、這期暫停。 */
|
|
136
|
+
export function trackFromEnv(env: BroadcastEnv): TrackFor | undefined {
|
|
137
|
+
const secrets = trackSecrets(env.TRACK_TOKEN_SECRET, env.TRACK_TOKEN_SECRET_PREVIOUS);
|
|
138
|
+
const host = trackHost(env.TRACK_BASE_URL);
|
|
139
|
+
// 鑰匙、追蹤網址缺一=追蹤端點不存在:不簽(內容有追蹤佔位就會 render_error 暫停,不寄出點了 404 的信)。
|
|
140
|
+
if (!secrets.length || !host) return undefined;
|
|
141
|
+
const origin = `https://${host}`;
|
|
142
|
+
return async (c, r, contents) => {
|
|
143
|
+
// 內容裡的追蹤佔位必須掛在這個部署的追蹤網址下(compose 的 trackBase 跟 TRACK_BASE_URL 不一致=連結會壞)。
|
|
144
|
+
for (const s of contents) {
|
|
145
|
+
for (const m of s.matchAll(/\{\{\s*(c:\d+|o)\s*\}\}/g)) {
|
|
146
|
+
const want = m[1] === 'o' ? `${origin}/o/` : `${origin}/c/`;
|
|
147
|
+
if (s.slice(Math.max(0, m.index - want.length), m.index).toLowerCase() !== want) throw new Error('tracking placeholder is not under TRACK_BASE_URL');
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
let count: number | null = 0;
|
|
151
|
+
if (c.links) {
|
|
152
|
+
try {
|
|
153
|
+
const parsed = JSON.parse(c.links);
|
|
154
|
+
count = Array.isArray(parsed) ? parsed.length : 0;
|
|
155
|
+
} catch {
|
|
156
|
+
count = 0;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return trackSigner(secrets[0], c.id, r.contact_id, contents, count);
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
123
163
|
export interface BroadcastWiring {
|
|
124
164
|
render?: BroadcastDeps['render'];
|
|
125
165
|
feedback?: IngestOptions['feedback'];
|
|
@@ -138,8 +178,9 @@ export function broadcastDeps(env: BroadcastEnv, wiring: BroadcastWiring = {}):
|
|
|
138
178
|
domain: env.MARKETING_DOMAIN.toLowerCase(),
|
|
139
179
|
queue: env.BROADCAST as unknown as BroadcastDeps['queue'],
|
|
140
180
|
config,
|
|
141
|
-
render: wiring.render ?? personalizeRender(unsubLinksFromEnv(env)),
|
|
181
|
+
render: wiring.render ?? personalizeRender(unsubLinksFromEnv(env), trackFromEnv(env)),
|
|
142
182
|
feedback: wiring.feedback,
|
|
183
|
+
unsub: { secrets: unsubSecrets(env.UNSUB_TOKEN_SECRET, env.UNSUB_TOKEN_SECRET_PREVIOUS), baseUrl: env.UNSUB_BASE_URL, mailto: env.UNSUB_MAILTO },
|
|
143
184
|
alert: wiring.alert ?? ((a) => (a.level === 'info' ? console.log : console.warn)('broadcast', a.level, a.code, a.campaign ?? '-', a.message)),
|
|
144
185
|
};
|
|
145
186
|
}
|
package/src/cli/errors.ts
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
// 引擎回的失敗原因 → 人看得懂的一句話+下一步。找不到對照的,照實印原因代碼。
|
|
2
2
|
|
|
3
3
|
const TABLE: Record<string, [string, string]> = {
|
|
4
|
+
links_missing: ['The content uses a tracked link that is not in the link table.', 'Run `campaign create` again with the current engine (it stores the link table), or compose without trackBase.'],
|
|
5
|
+
bad_links: ['The link table is malformed (numbers must be 1..N, http(s) URLs only).', 'Compose the issue again with `campaign create`.'],
|
|
6
|
+
marketing_domain_not_set: ['Newsletters are not configured on this deployment (no sender domain), so the welcome mail cannot be checked or stored.', 'Set MARKETING_DOMAIN first; the welcome mail can be stored switched off (--disable).'],
|
|
7
|
+
enabled_required: ['Say explicitly whether the welcome mail is on.', 'Add --enable or --disable.'],
|
|
8
|
+
unsubscribe_link_missing: ['The welcome mail has no {{unsubscribe_url}} link in the HTML or the text.', 'Use a template whose footer contains the unsubscribe link.'],
|
|
9
|
+
tracking_not_supported: ['The welcome mail contains tracking placeholders.', 'Compose it without trackBase (the `welcome` command does this).'],
|
|
4
10
|
not_found: ['No such issue.', 'Check the issue id with `campaign status <id>`; create it with `campaign create` first.'],
|
|
5
11
|
illegal_transition: ['The issue is not in a state where this is allowed.', 'Run `campaign status <id>` to see the current state and what comes next.'],
|
|
6
12
|
illegal_state: ['The issue is not in a state where this is allowed (retry-failed works only while it is sending or paused; a finished (done) issue is closed for good: recipients that failed are recorded with their reason).', 'Run `campaign status <id>` to see the current state.'],
|
package/src/cli/main.ts
CHANGED
|
@@ -47,7 +47,7 @@ export interface CliIo {
|
|
|
47
47
|
export interface RunOptions { defaults?: CliDefaults; env?: Record<string, string | undefined>; io?: Partial<CliIo> }
|
|
48
48
|
|
|
49
49
|
const VALUES = ['issue', 'source', 'post', 'web-url', 'list', 'from', 'subject', 'audience', 'source-ref', 'to', 'note', 'reason', 'at', 'out', 'contact', 'as', 'tz', 'base-url'];
|
|
50
|
-
const BOOLEANS = ['yes', 'json', 'offline', 'force', 'release-domain', 'to-defaults', 'help'];
|
|
50
|
+
const BOOLEANS = ['yes', 'json', 'offline', 'force', 'release-domain', 'to-defaults', 'help', 'enable', 'disable'];
|
|
51
51
|
|
|
52
52
|
class CliError extends Error {
|
|
53
53
|
readonly code: number;
|
|
@@ -76,6 +76,9 @@ Changes state (dry-run unless --yes is given):
|
|
|
76
76
|
cancel <id> --reason "..." --yes
|
|
77
77
|
retry-failed <id> --yes resolve <id> --contact N --as sent|failed --note "..." --yes
|
|
78
78
|
hold release --note "..." --yes release the sender-domain hold
|
|
79
|
+
welcome [--list L] show the list's welcome mail (subject, on/off)
|
|
80
|
+
welcome --source <file.md> --web-url U (--enable | --disable) [--list L] [--subject S] --yes
|
|
81
|
+
compose, check and store the welcome mail for new subscribers
|
|
79
82
|
Options: --json (machine-readable output), --base-url, --tz +08:00
|
|
80
83
|
Environment: MAILROOM_URL, MAILROOM_ADMIN_TOKEN`;
|
|
81
84
|
|
|
@@ -225,6 +228,7 @@ export async function runCli(argv: readonly string[], opts: RunOptions = {}): Pr
|
|
|
225
228
|
return r.ok ? 0 : 1;
|
|
226
229
|
}
|
|
227
230
|
case 'create': return await create();
|
|
231
|
+
case 'welcome': return await welcome();
|
|
228
232
|
case 'preview': {
|
|
229
233
|
const id = idArg();
|
|
230
234
|
if (!yes) {
|
|
@@ -396,12 +400,57 @@ export async function runCli(argv: readonly string[], opts: RunOptions = {}): Pr
|
|
|
396
400
|
const data = { issue, subject: composed.subject, checkOk: check.ok, issues: check.issues };
|
|
397
401
|
if (!yes) return dry(lines, data);
|
|
398
402
|
const sourceRef = (typeof flags['source-ref'] === 'string' ? flags['source-ref'] : undefined) ?? post?.ref ?? sourcePath;
|
|
399
|
-
const saved = await call('PUT', `/v1/campaigns/${issue}`, { list, subject: composed.subject, preheader: composed.preheader || undefined, from, ...(d.replyTo ? { replyTo: d.replyTo } : {}), html: composed.html, text: composed.text, headers: composed.headers, webUrl, sourceRef, audience });
|
|
403
|
+
const saved = await call('PUT', `/v1/campaigns/${issue}`, { list, subject: composed.subject, preheader: composed.preheader || undefined, from, ...(d.replyTo ? { replyTo: d.replyTo } : {}), html: composed.html, text: composed.text, headers: composed.headers, webUrl, sourceRef, audience, ...(composed.links.length ? { links: composed.links.map((l) => ({ index: l.index, url: l.url })) } : {}) });
|
|
400
404
|
const rec = await call('POST', `/v1/campaigns/${issue}/preflight`, { ok: check.ok, issues: check.issues.map((i) => ({ severity: i.severity, code: i.code, message: i.message })) });
|
|
401
405
|
emit([...lines, '', `saved as draft (${saved.changed ? 'new or changed' : 'unchanged'}); check recorded: ${rec.preflightOk ? 'passed' : 'failed'}`, rec.preflightOk ? `Next: campaign preview ${issue} --yes` : 'Next: fix the errors above in the source, then run create again (same id updates the draft).'], { ...data, saved, preflightOk: rec.preflightOk });
|
|
402
406
|
return rec.preflightOk ? 0 : 1;
|
|
403
407
|
}
|
|
404
408
|
|
|
409
|
+
async function welcome(): Promise<number> {
|
|
410
|
+
const list = (typeof flags.list === 'string' ? flags.list : d.list) ?? '';
|
|
411
|
+
if (!ID.test(list)) throw new CliError('welcome needs a list: pass --list or set it in the defaults.', 2);
|
|
412
|
+
if (typeof flags.source !== 'string') {
|
|
413
|
+
const r = await api('GET', `/v1/lists/${list}/welcome`);
|
|
414
|
+
if (r.status === 404 && r.body.reason === 'not_found') {
|
|
415
|
+
emit([`${list}: no welcome mail stored (new subscribers get none).`, 'Next: welcome --source <file.md> --web-url https://... --disable --yes (store it switched off first, look at it, then --enable).'], { list, exists: false });
|
|
416
|
+
return 0;
|
|
417
|
+
}
|
|
418
|
+
if (r.status >= 400 || r.body.ok === false) throw new CliError(friendly(String(r.body.reason ?? `http_${r.status}`)));
|
|
419
|
+
emit([`${list}: "${r.body.subject}" from ${r.body.from}`, `welcome mail is ${r.body.enabled ? 'ON (sent to first-time subscribers while newsletters are enabled)' : 'OFF'}; updated ${r.body.updatedAt}`], { list, exists: true, subject: r.body.subject, enabled: r.body.enabled, updatedAt: r.body.updatedAt });
|
|
420
|
+
return 0;
|
|
421
|
+
}
|
|
422
|
+
if (flags.enable === true && flags.disable === true) throw new CliError('Pick one: --enable or --disable.', 2);
|
|
423
|
+
if (!d.template) throw new CliError('No email template is configured.\nNext: pass `template` in the defaults (see docs/composing.md).');
|
|
424
|
+
const from = (typeof flags.from === 'string' ? flags.from : d.from) ?? '';
|
|
425
|
+
if (!from) throw new CliError('The sender is required: pass --from or set it in the defaults.', 2);
|
|
426
|
+
let source: string;
|
|
427
|
+
try {
|
|
428
|
+
source = await io.readFile(flags.source);
|
|
429
|
+
} catch {
|
|
430
|
+
throw new CliError(`Could not read the source file "${flags.source}".\nNext: check the path.`);
|
|
431
|
+
}
|
|
432
|
+
const webUrl = typeof flags['web-url'] === 'string' ? flags['web-url'] : '';
|
|
433
|
+
if (!webUrl) throw new CliError('Pass --web-url https://... (the {{web_url}} link, for example the newsletter archive).', 2);
|
|
434
|
+
const template = createTemplate(d.template);
|
|
435
|
+
// 歡迎信不追蹤:不給 trackBase(歡迎信沒有期別的連結表)。
|
|
436
|
+
const { trackBase: _ignored, ...composeOpts } = d.composeDefaults ?? {};
|
|
437
|
+
const composed = compose({ ...composeOpts, source, template, issue: 'welcome', ...(typeof flags.subject === 'string' ? { subject: flags.subject } : {}) });
|
|
438
|
+
const check: PreflightResult = await preflight(composed, { template, webUrl, checkLinks: flags.offline !== true, fetch: io.fetch });
|
|
439
|
+
const errors = check.issues.filter((i) => i.severity === 'error');
|
|
440
|
+
const lines = [
|
|
441
|
+
`welcome mail for ${list}: "${composed.subject}"`, `from ${from} {{web_url}} ${webUrl}`, `HTML ${composed.htmlBytes} bytes, ${composed.links.length} links (not tracked)`,
|
|
442
|
+
`pre-send check: ${check.ok ? 'PASSED' : `FAILED (${errors.length} error${errors.length === 1 ? '' : 's'})`}`,
|
|
443
|
+
...check.issues.map((i) => ` [${i.severity}] ${i.code}: ${i.message}${i.where ? ` (${i.where})` : ''}`),
|
|
444
|
+
];
|
|
445
|
+
const data = { list, subject: composed.subject, checkOk: check.ok, issues: check.issues };
|
|
446
|
+
if (!yes) return dry(lines, data);
|
|
447
|
+
if (!check.ok) throw new CliError(`${lines.join('\n')}\n\nNot stored: fix the errors above first.`, 1);
|
|
448
|
+
if (flags.enable !== true && flags.disable !== true) throw new CliError('Say whether new subscribers should get it now: --enable or --disable.', 2);
|
|
449
|
+
const saved = await call('PUT', `/v1/lists/${list}/welcome`, { subject: composed.subject, from, ...(d.replyTo ? { replyTo: d.replyTo } : {}), html: composed.html, text: composed.text, webUrl, enabled: flags.enable === true });
|
|
450
|
+
emit([...lines, '', `stored (${saved.changed ? 'new or changed' : 'unchanged'}); welcome mail is ${saved.enabled ? 'ON' : 'OFF'}.`, saved.enabled ? 'It is sent only while newsletters are enabled on this deployment, and only to first-time subscribers.' : 'Next: look at it, then run again with --enable --yes.'], { ...data, saved });
|
|
451
|
+
return 0;
|
|
452
|
+
}
|
|
453
|
+
|
|
405
454
|
function previewLines(id: string, p: Record<string, any>, marked: boolean): string[] {
|
|
406
455
|
const pf = p.preflight as { ok?: boolean; errors?: string[]; issues?: { severity: string; code: string; message: string }[] } | null;
|
|
407
456
|
return [
|
package/src/compose/compose.ts
CHANGED
|
@@ -222,6 +222,7 @@ export function compose(opts: ComposeOptions): ComposeResult {
|
|
|
222
222
|
const parts = { subject, preheader, bodyHtml, bodyText, pixelUrl };
|
|
223
223
|
const html = t.renderHtml(parts);
|
|
224
224
|
const text = t.renderText(parts);
|
|
225
|
+
checkOutputForComments(parsed.blocks, parts, t, problems);
|
|
225
226
|
|
|
226
227
|
return {
|
|
227
228
|
subject,
|
|
@@ -255,3 +256,42 @@ function flatBlocks(blocks: Block[]): Block[] {
|
|
|
255
256
|
}
|
|
256
257
|
return out;
|
|
257
258
|
}
|
|
259
|
+
|
|
260
|
+
/** 數 <!--(含跳脫成 <!-- 的)出現幾次。 */
|
|
261
|
+
const commentMarks = (s: string) => s.split('<!--').length - 1 + (s.split('<!--').length - 1);
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* 最後一道保險:看「最終」HTML 與純文字版(不是解析樹)。把程式碼的內容遮掉重排一次,跟「只有樣板、沒有正文」的版本比:
|
|
265
|
+
* 程式碼以外多出任何一個 <!--,就代表有註解字樣會寄到讀者眼前(解析或排版哪裡出了錯),記 error 擋下。
|
|
266
|
+
* 樣板自己的 Outlook 條件註解(<!--[if mso]>)在兩邊一樣多,所以不會誤報。
|
|
267
|
+
*/
|
|
268
|
+
function checkOutputForComments(blocks: Block[], parts: { subject: string; preheader: string; bodyHtml: string; bodyText: string; pixelUrl?: string }, t: EmailTemplate, problems: Problem[]): void {
|
|
269
|
+
if (problems.some((p) => p.code === 'comment_leaked' || p.code === 'unclosed_comment')) return; // 已經擋下,不重複報
|
|
270
|
+
const masked = structuredClone(blocks);
|
|
271
|
+
const mask = (bs: Block[]): void => {
|
|
272
|
+
const inl = (ns: Inline[]) => {
|
|
273
|
+
for (const n of ns) {
|
|
274
|
+
if (n.t === 'code') n.v = '';
|
|
275
|
+
else if (n.t === 'strong' || n.t === 'em' || n.t === 'link') inl(n.c);
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
for (const b of bs) {
|
|
279
|
+
if (b.t === 'code') b.v = '';
|
|
280
|
+
else if (b.t === 'p' || b.t === 'h') inl(b.c);
|
|
281
|
+
else if (b.t === 'quote') mask(b.c);
|
|
282
|
+
else if (b.t === 'list') for (const it of b.items) mask(it);
|
|
283
|
+
else if (b.t === 'table') {
|
|
284
|
+
for (const c of b.head) inl(c);
|
|
285
|
+
for (const r of b.rows) for (const c of r) inl(c);
|
|
286
|
+
} else if (b.t === 'image' && b.link) inl(b.link.c);
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
mask(masked);
|
|
290
|
+
const withBody = { ...parts, bodyHtml: renderBodyHtml(masked, t.theme, t.labels), bodyText: renderBodyText(masked, t.labels) };
|
|
291
|
+
const empty = { ...parts, bodyHtml: '', bodyText: '' };
|
|
292
|
+
const extraHtml = commentMarks(t.renderHtml(withBody)) - commentMarks(t.renderHtml(empty));
|
|
293
|
+
const extraText = commentMarks(t.renderText(withBody)) - commentMarks(t.renderText(empty));
|
|
294
|
+
if (extraHtml > 0 || extraText > 0) {
|
|
295
|
+
problems.push({ code: 'comment_leaked', severity: 'error', message: `信件${extraHtml > 0 ? ' HTML' : ''}${extraText > 0 ? ' 純文字版' : ''}在程式碼以外含有 <!-- 字樣,會原樣寄到讀者眼前;請檢查原稿裡的註解寫法` });
|
|
296
|
+
}
|
|
297
|
+
}
|