@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,130 @@
|
|
|
1
|
+
// 個人化:把一期信的 HTML/純文字/標頭裡的佔位換成這一位收件人的值。純函式。
|
|
2
|
+
// 第一版只開四個欄位:name(沒有就整段省略)、email、unsubscribe_url、web_url;另有追蹤簽章 {{c:N}}、{{o}}。
|
|
3
|
+
// 一次掃完(單趟替換):收件人的值裡就算寫了 {{email}},也不會被再展開。
|
|
4
|
+
|
|
5
|
+
export interface RecipientVars {
|
|
6
|
+
name?: string | null;
|
|
7
|
+
email: string;
|
|
8
|
+
unsubscribe_url: string;
|
|
9
|
+
web_url: string;
|
|
10
|
+
/** 退訂用的 mailto 連結(含退訂券,例 `mailto:unsub@example.com?subject=<券>`)。只有內容裡用到 {{unsubscribe_mailto}}(compose 的 unsubscribeMailto)時才必填。 */
|
|
11
|
+
unsubscribe_mailto?: string | null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface PersonalizeOptions {
|
|
15
|
+
/** 產生追蹤簽章:kind 'c'=第 index 個連結、'o'=開信圖。寄出時由簽章函式提供;預覽可傳固定字串。 */
|
|
16
|
+
track?: (kind: 'c' | 'o', index?: number) => string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class PersonalizeError extends Error {
|
|
20
|
+
readonly code: 'missing_field' | 'bad_url' | 'unknown_placeholder' | 'unbalanced_section' | 'missing_track';
|
|
21
|
+
constructor(code: PersonalizeError['code'], message: string) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.name = 'PersonalizeError';
|
|
24
|
+
this.code = code;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const SECTION_KEYS = ['name', 'email'] as const;
|
|
29
|
+
const VALUE_KEYS = ['name', 'email', 'unsubscribe_url', 'web_url', 'unsubscribe_mailto'] as const;
|
|
30
|
+
const TOKEN = /\{\{\s*([#/]?)\s*([a-z_]+)(?::(\d+))?\s*\}\}/g;
|
|
31
|
+
|
|
32
|
+
export function escapeHtmlValue(s: string): string {
|
|
33
|
+
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 名字:去掉控制字元與換行、壓縮空白、最多 60 字;空字串=沒有名字。 */
|
|
37
|
+
export function cleanName(v: string | null | undefined): string {
|
|
38
|
+
if (typeof v !== 'string') return '';
|
|
39
|
+
// eslint-disable-next-line no-control-regex
|
|
40
|
+
const s = v.replace(/[\u0000-\u001f\u007f\u2028\u2029]/g, ' ').replace(/\s+/g, ' ').trim();
|
|
41
|
+
return Array.from(s).slice(0, 60).join('');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function checkVars(v: RecipientVars): { name: string; email: string; unsubscribe_url: string; web_url: string; unsubscribe_mailto: string } {
|
|
45
|
+
const name = cleanName(v.name);
|
|
46
|
+
const email = typeof v.email === 'string' ? v.email.trim() : '';
|
|
47
|
+
if (!email || /[\s<>"]/.test(email)) throw new PersonalizeError('missing_field', 'email 缺或格式不對');
|
|
48
|
+
for (const k of ['unsubscribe_url', 'web_url'] as const) {
|
|
49
|
+
const u = typeof v[k] === 'string' ? v[k].trim() : '';
|
|
50
|
+
if (!u) throw new PersonalizeError('missing_field', `${k} 不能是空的`);
|
|
51
|
+
if (!/^https:\/\/[^\s<>"]+$/i.test(u)) throw new PersonalizeError('bad_url', `${k} 必須是 https 網址`);
|
|
52
|
+
}
|
|
53
|
+
// 給網址的欄位不准夾換行(會被拿去組標頭)
|
|
54
|
+
if (/[\r\n]/.test(v.unsubscribe_url) || /[\r\n]/.test(v.web_url)) throw new PersonalizeError('bad_url', '網址不能含換行');
|
|
55
|
+
let mailto = '';
|
|
56
|
+
if (v.unsubscribe_mailto !== undefined && v.unsubscribe_mailto !== null && v.unsubscribe_mailto !== '') {
|
|
57
|
+
mailto = String(v.unsubscribe_mailto).trim();
|
|
58
|
+
if (!/^mailto:[^\s<>",]+$/i.test(mailto)) throw new PersonalizeError('bad_url', 'unsubscribe_mailto 必須是 mailto: 連結(不含空白、逗號、角括號)');
|
|
59
|
+
}
|
|
60
|
+
return { name, email, unsubscribe_url: v.unsubscribe_url.trim(), web_url: v.web_url.trim(), unsubscribe_mailto: mailto };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** 展開一段內容。mode 'html' 會跳脫值;'text' 與 'header' 原樣放入(header 另外擋掉換行)。 */
|
|
64
|
+
export function fill(template: string, vars: RecipientVars, mode: 'html' | 'text' | 'header', opts: PersonalizeOptions = {}): string {
|
|
65
|
+
const v = checkVars(vars);
|
|
66
|
+
// 第一趟:區段。沒有該欄位的值,整段(含標籤)一起拿掉。
|
|
67
|
+
let out = template;
|
|
68
|
+
for (const key of SECTION_KEYS) {
|
|
69
|
+
const re = new RegExp(`\\{\\{\\s*#\\s*${key}\\s*\\}\\}([\\s\\S]*?)\\{\\{\\s*/\\s*${key}\\s*\\}\\}`, 'g');
|
|
70
|
+
out = out.replace(re, (_m, inner: string) => (v[key] ? inner : ''));
|
|
71
|
+
}
|
|
72
|
+
// 第二趟:單趟替換所有佔位;不認得的、沒配對的區段一律拋錯(不准寄出殘留)。
|
|
73
|
+
const enc = (s: string) => (mode === 'html' ? escapeHtmlValue(s) : s);
|
|
74
|
+
out = out.replace(TOKEN, (_m, mark: string, key: string, n: string | undefined) => {
|
|
75
|
+
if (mark) throw new PersonalizeError('unbalanced_section', `區段標記 ${mark}${key} 沒有配對`);
|
|
76
|
+
if (key === 'c' && n !== undefined) return needTrack(opts)('c', Number(n));
|
|
77
|
+
if (key === 'o' && n === undefined) return needTrack(opts)('o');
|
|
78
|
+
if ((VALUE_KEYS as readonly string[]).includes(key) && n === undefined) {
|
|
79
|
+
const val = v[key as (typeof VALUE_KEYS)[number]];
|
|
80
|
+
if (key === 'unsubscribe_mailto' && !val) throw new PersonalizeError('missing_field', '內容用到 {{unsubscribe_mailto}},但收件人資料沒有 unsubscribe_mailto');
|
|
81
|
+
return enc(val);
|
|
82
|
+
}
|
|
83
|
+
throw new PersonalizeError('unknown_placeholder', `不認得的佔位 {{${key}}}`);
|
|
84
|
+
});
|
|
85
|
+
if (mode === 'header' && /[\r\n]/.test(out)) throw new PersonalizeError('bad_url', '標頭值不能含換行');
|
|
86
|
+
// 原稿跳脫過的「{」換回來;純文字版區段拿掉後留下的連續空行壓成一個
|
|
87
|
+
if (mode === 'text') out = out.replace(/\uE000/g, '{').replace(/\n{3,}/g, '\n\n');
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function needTrack(opts: PersonalizeOptions): NonNullable<PersonalizeOptions['track']> {
|
|
92
|
+
if (!opts.track) throw new PersonalizeError('missing_track', '內容含追蹤佔位,但沒有提供簽章函式');
|
|
93
|
+
return opts.track;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function personalize(
|
|
97
|
+
content: { html: string; text: string; headers?: Record<string, string> },
|
|
98
|
+
vars: RecipientVars,
|
|
99
|
+
opts: PersonalizeOptions = {},
|
|
100
|
+
): { html: string; text: string; headers: Record<string, string> } {
|
|
101
|
+
const headers: Record<string, string> = {};
|
|
102
|
+
for (const [k, val] of Object.entries(content.headers ?? {})) headers[k] = fill(val, vars, 'header', opts);
|
|
103
|
+
return { html: fill(content.html, vars, 'html', opts), text: fill(content.text, vars, 'text', opts), headers };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 列出一段內容用到的佔位,找出不在白名單的與沒配對的區段(寄前檢查用)。 */
|
|
107
|
+
export function scanPlaceholders(s: string): { unknown: string[]; unbalanced: string[]; used: Set<string> } {
|
|
108
|
+
const unknown: string[] = [];
|
|
109
|
+
const used = new Set<string>();
|
|
110
|
+
const open: Record<string, number> = {};
|
|
111
|
+
const close: Record<string, number> = {};
|
|
112
|
+
for (const m of s.matchAll(TOKEN)) {
|
|
113
|
+
const [raw, mark, key, n] = m;
|
|
114
|
+
if (mark === '#' || mark === '/') {
|
|
115
|
+
if ((SECTION_KEYS as readonly string[]).includes(key) && n === undefined) {
|
|
116
|
+
(mark === '#' ? open : close)[key] = ((mark === '#' ? open : close)[key] ?? 0) + 1;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
unknown.push(raw);
|
|
120
|
+
} else if (key === 'c' && n !== undefined) used.add('c');
|
|
121
|
+
else if (key === 'o' && n === undefined) used.add('o');
|
|
122
|
+
else if ((VALUE_KEYS as readonly string[]).includes(key) && n === undefined) used.add(key);
|
|
123
|
+
else unknown.push(raw);
|
|
124
|
+
}
|
|
125
|
+
const unbalanced = SECTION_KEYS.filter((k) => (open[k] ?? 0) !== (close[k] ?? 0)).map((k) => k as string);
|
|
126
|
+
// 沒被 TOKEN 吃掉但長得像佔位的殘渣(例如 {{ foo bar }}、{{name})
|
|
127
|
+
const stripped = s.replace(TOKEN, '');
|
|
128
|
+
for (const m of stripped.matchAll(/\{\{[^}]{0,40}\}?\}?/g)) unknown.push(m[0]);
|
|
129
|
+
return { unknown, unbalanced, used };
|
|
130
|
+
}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
// 寄前檢查:任何一條 error 沒過,就不准排程。純函式+一個可注入 fetch 的連結檢查。
|
|
2
|
+
// 規則:HTTP 404/410 才算壞連結;逾時、連不上、其他狀態碼照實記成 warn,不擋。
|
|
3
|
+
import type { Problem } from './markdown.ts';
|
|
4
|
+
import type { ComposeResult } from './compose.ts';
|
|
5
|
+
import type { EmailTemplate } from './template.ts';
|
|
6
|
+
import { scanPlaceholders } from './personalize.ts';
|
|
7
|
+
|
|
8
|
+
export interface PreflightOptions {
|
|
9
|
+
template: EmailTemplate;
|
|
10
|
+
/** HTML 大小上限(位元組);預設 90,000(Gmail 超過約 102KB 會折疊,留餘裕)。檢查時會把每個追蹤簽章與頁尾替換的長度估進去。 */
|
|
11
|
+
maxHtmlBytes?: number;
|
|
12
|
+
maxSubjectChars?: number;
|
|
13
|
+
/** 網頁版網址(要檢查它打不打得開)。沒給也會記 error(web_url_unchecked):網頁版沒查過,不准排程。 */
|
|
14
|
+
webUrl?: string;
|
|
15
|
+
/** 要不要實際打網路檢查連結與圖片(預設要)。給 false=離線檢查,結果會記一條 error(links_unchecked):連結沒查過,不准排程。 */
|
|
16
|
+
checkLinks?: boolean;
|
|
17
|
+
/** 可注入的 fetch(測試用假的)。 */
|
|
18
|
+
fetch?: (url: string, init?: { method?: string; signal?: AbortSignal; redirect?: 'manual' }) => Promise<{ status: number; headers?: { get(name: string): string | null } }>;
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
concurrency?: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface PreflightResult {
|
|
24
|
+
/** 沒有任何 error。 */
|
|
25
|
+
ok: boolean;
|
|
26
|
+
/** 連結與圖片真的打網路查過了(離線模式=false)。 */
|
|
27
|
+
linksChecked: boolean;
|
|
28
|
+
/** 網頁版網址有給、也查過了。 */
|
|
29
|
+
webChecked: boolean;
|
|
30
|
+
issues: Problem[];
|
|
31
|
+
/** 每個檢查過的網址的結果(HTTP 狀態碼;0=連不上)。 */
|
|
32
|
+
linkStatuses: { url: string; status: number; kind: 'link' | 'image' | 'web' }[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 從最終 HTML 抓出全部 <img src> 與 <a href>(含樣板頁尾,不只正文)。 */
|
|
36
|
+
function htmlRefs(html: string): { imgs: { src: string; alt: string | null }[]; hrefs: string[] } {
|
|
37
|
+
const dec = (v: string) => v.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>');
|
|
38
|
+
const body = html.replace(/<style[\s\S]*?<\/style>/gi, '').replace(/<!--[\s\S]*?-->/g, '');
|
|
39
|
+
const imgs: { src: string; alt: string | null }[] = [];
|
|
40
|
+
for (const m of body.matchAll(/<img\b[^>]*>/gi)) {
|
|
41
|
+
const src = m[0].match(/\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
|
|
42
|
+
const alt = m[0].match(/\balt\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
|
|
43
|
+
imgs.push({ src: dec(src?.[1] ?? src?.[2] ?? ''), alt: alt ? dec(alt[1] ?? alt[2] ?? '') : null });
|
|
44
|
+
}
|
|
45
|
+
const hrefs: string[] = [];
|
|
46
|
+
for (const m of body.matchAll(/<a\b[^>]*?\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)) hrefs.push(dec(m[1] ?? m[2] ?? ''));
|
|
47
|
+
return { imgs, hrefs };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 樣板裡「這裡還沒填」的標記格式:[[TODO: 要補什麼]](或【待補:…】)。看到就不准寄。 */
|
|
51
|
+
export const TODO_MARKER = /\[\[TODO[^\]]*\]\]|【待補[^】]*】/;
|
|
52
|
+
/** 寄出時每個追蹤簽章與頁尾替換最多比佔位多出的位元組(保守估計)。 */
|
|
53
|
+
const PER_TOKEN_EXTRA = 64;
|
|
54
|
+
const PER_MESSAGE_EXTRA = 400;
|
|
55
|
+
|
|
56
|
+
function cp(s: string): number {
|
|
57
|
+
return Array.from(s).length;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function v4Blocked(a: number, b: number, c: number): boolean {
|
|
61
|
+
return a === 0 || a === 10 || a === 127 || a >= 224 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 192 && b === 0 && c === 0) || (a === 198 && (b === 18 || b === 19));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 內網、本機、保留位址(只看網址裡的主機寫法;URL 解析器已把十進位/十六進位的 IPv4 寫法統一成點分格式)。 */
|
|
65
|
+
export function privateHost(host: string): boolean {
|
|
66
|
+
const h = host.toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
|
|
67
|
+
if (h === '' || h === 'localhost' || h.endsWith('.localhost') || h.endsWith('.local') || h.endsWith('.internal') || h.endsWith('.lan') || h.endsWith('.home.arpa')) return true;
|
|
68
|
+
const m4 = h.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
|
|
69
|
+
if (m4) return v4Blocked(Number(m4[1]), Number(m4[2]), Number(m4[3]));
|
|
70
|
+
if (h.includes(':')) {
|
|
71
|
+
if (h === '::' || h === '::1') return true;
|
|
72
|
+
if (/^f[cd]/.test(h) || /^fe[89ab]/.test(h) || h.startsWith('64:ff9b:')) return true;
|
|
73
|
+
// IPv4 對映/相容寫法(::ffff:7f00:1、::7f00:1、::ffff:127.0.0.1):取出內嵌的 IPv4 再判斷
|
|
74
|
+
const tail = h.match(/^(?:0{0,4}:){1,6}(?:ffff:)?([0-9a-f]{1,4}):([0-9a-f]{1,4})$/) ?? null;
|
|
75
|
+
if (tail) {
|
|
76
|
+
const hi = parseInt(tail[1], 16);
|
|
77
|
+
const lo = parseInt(tail[2], 16);
|
|
78
|
+
return v4Blocked(hi >> 8, hi & 255, lo >> 8);
|
|
79
|
+
}
|
|
80
|
+
const dotted = h.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
|
|
81
|
+
if (dotted) return v4Blocked(Number(dotted[1]), Number(dotted[2]), Number(dotted[3]));
|
|
82
|
+
}
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function preflight(c: ComposeResult, opts: PreflightOptions): Promise<PreflightResult> {
|
|
87
|
+
const issues: Problem[] = [...c.problems];
|
|
88
|
+
const add = (code: string, severity: Problem['severity'], message: string, where?: string) => issues.push({ code, severity, message, where });
|
|
89
|
+
|
|
90
|
+
// 1. 大小
|
|
91
|
+
const max = opts.maxHtmlBytes ?? 90_000;
|
|
92
|
+
const estimated = c.htmlBytes + (c.links.length + 1) * PER_TOKEN_EXTRA + PER_MESSAGE_EXTRA;
|
|
93
|
+
if (estimated >= max) add('html_too_large', 'error', `HTML 估計 ${estimated} 位元組,超過上限 ${max}(含寄出時簽章與個人化的估計)`);
|
|
94
|
+
|
|
95
|
+
// 2. 純文字版
|
|
96
|
+
if (c.text.trim().length === 0) add('text_missing', 'error', '沒有純文字版');
|
|
97
|
+
|
|
98
|
+
// 3. 退訂連結與兩個標頭
|
|
99
|
+
const needle = '{{unsubscribe_url}}';
|
|
100
|
+
const hrefUnsub = /href="\{\{unsubscribe_url\}\}"/.test(c.html);
|
|
101
|
+
if (!hrefUnsub) add('unsubscribe_link_missing', 'error', 'HTML 沒有退訂連結(href 必須是退訂佔位)');
|
|
102
|
+
if (!c.text.includes(needle)) add('unsubscribe_text_missing', 'error', '純文字版沒有退訂連結');
|
|
103
|
+
const lu = c.headers['List-Unsubscribe'] ?? '';
|
|
104
|
+
const lup = c.headers['List-Unsubscribe-Post'] ?? '';
|
|
105
|
+
if (!/^<\{\{unsubscribe_url\}\}>(?:\s*,\s*<\{\{unsubscribe_mailto\}\}>)?$/.test(lu.trim())) add('unsubscribe_header_missing', 'error', '缺 List-Unsubscribe 標頭(要指向退訂佔位;可再加一段 mailto 佔位)');
|
|
106
|
+
if (lup.trim() !== 'List-Unsubscribe=One-Click') add('unsubscribe_post_header_missing', 'error', '缺 List-Unsubscribe-Post 標頭(一鍵退訂)');
|
|
107
|
+
// 退訂連結不准被改寫成追蹤連結(href 是退訂佔位但被包過的情形)
|
|
108
|
+
if (c.links.some((l) => /unsubscribe/i.test(l.original) && l.url.includes('/c/'))) add('unsubscribe_tracked', 'error', '退訂連結被改寫成追蹤連結');
|
|
109
|
+
|
|
110
|
+
// 4. 實體地址
|
|
111
|
+
const addr = opts.template.postalAddress.trim();
|
|
112
|
+
if (!addr) add('address_missing', 'error', '樣板沒有實體地址');
|
|
113
|
+
else {
|
|
114
|
+
if (TODO_MARKER.test(addr)) add('address_todo', 'error', '實體地址還是待補標記,不能寄出');
|
|
115
|
+
const esc = addr.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
|
116
|
+
if (!c.html.includes(esc)) add('address_not_in_html', 'error', 'HTML 裡找不到實體地址');
|
|
117
|
+
if (!c.text.includes(addr)) add('address_not_in_text', 'error', '純文字版裡找不到實體地址');
|
|
118
|
+
}
|
|
119
|
+
// 樣板其他地方殘留的待補標記(頁尾文字等)
|
|
120
|
+
for (const [label, body] of [['HTML', c.html], ['純文字', c.text]] as const) {
|
|
121
|
+
const visible = label === 'HTML' ? body.replace(/<style[\s\S]*?<\/style>/g, '') : body; // 含標籤屬性(圖片網址也可能是待補)
|
|
122
|
+
const m = visible.match(TODO_MARKER);
|
|
123
|
+
if (m) add('todo_marker', 'error', `${label}裡有待補標記「${m[0]}」,補完才能寄`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// 5. 圖片替代文字、圖片網址協定(看最終 HTML,頁尾的圖也算;開信圖不用替代文字)
|
|
127
|
+
const refs = htmlRefs(c.html);
|
|
128
|
+
const isPixel = (src: string) => /\/o\/\{\{o\}\}\.gif$/.test(src);
|
|
129
|
+
for (const img of refs.imgs) {
|
|
130
|
+
if (isPixel(img.src)) continue;
|
|
131
|
+
if (!(img.alt ?? '').trim()) add('image_alt_missing', 'error', '有圖片沒有替代文字', img.src.slice(0, 80));
|
|
132
|
+
if (/^http:\/\//i.test(img.src)) add('image_insecure', 'warn', '圖片用 http(建議 https)', img.src.slice(0, 80));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// 6. 主旨、預覽文字
|
|
136
|
+
const maxSubject = opts.maxSubjectChars ?? 80;
|
|
137
|
+
if (!c.subject.trim()) add('subject_missing', 'error', '沒有主旨');
|
|
138
|
+
else {
|
|
139
|
+
if (cp(c.subject) > maxSubject) add('subject_too_long', 'error', `主旨 ${cp(c.subject)} 字,超過 ${maxSubject} 字`);
|
|
140
|
+
// eslint-disable-next-line no-control-regex
|
|
141
|
+
if (/[\u0000-\u001f\u007f\u2028\u2029]/.test(c.subject)) add('subject_invalid', 'error', '主旨含換行或控制字元');
|
|
142
|
+
}
|
|
143
|
+
if (!c.preheader.trim()) add('preheader_missing', 'error', '沒有預覽文字');
|
|
144
|
+
|
|
145
|
+
// 7. 殘留佔位
|
|
146
|
+
for (const [label, body] of [['HTML', c.html], ['純文字', c.text]] as const) {
|
|
147
|
+
const s = scanPlaceholders(body);
|
|
148
|
+
if (s.unknown.length) add('unknown_placeholder', 'error', `${label}有不認得的佔位(沒有殘留 {{…}} 才能寄):${[...new Set(s.unknown)].slice(0, 5).join(' ')}`);
|
|
149
|
+
if (s.unbalanced.length) add('unbalanced_section', 'error', `${label}的區段標記沒有配對:${s.unbalanced.join('、')}`);
|
|
150
|
+
}
|
|
151
|
+
for (const [k, v] of Object.entries(c.headers)) {
|
|
152
|
+
const s = scanPlaceholders(v);
|
|
153
|
+
if (s.unknown.length) add('unknown_placeholder', 'error', `標頭 ${k} 有不認得的佔位`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// 8. 連結與圖片打得開(404/410 才算壞)。檢查對象=最終 HTML 裡所有 <a href> 與 <img src>(含頁尾),不只正文。
|
|
157
|
+
const linkStatuses: PreflightResult['linkStatuses'] = [];
|
|
158
|
+
let linksChecked = false;
|
|
159
|
+
let webChecked = false;
|
|
160
|
+
if (!opts.webUrl) add('web_url_unchecked', 'error', '沒有提供網頁版網址,網頁版沒檢查過,不准排程');
|
|
161
|
+
if (opts.checkLinks === false) {
|
|
162
|
+
add('links_unchecked', 'error', '連結與圖片沒有實際檢查(離線模式),不准排程');
|
|
163
|
+
} else {
|
|
164
|
+
linksChecked = true;
|
|
165
|
+
const f = opts.fetch ?? (globalThis.fetch as unknown as NonNullable<PreflightOptions['fetch']>);
|
|
166
|
+
const targets = new Map<string, 'link' | 'image' | 'web'>();
|
|
167
|
+
for (const l of c.links) targets.set(l.original, 'link');
|
|
168
|
+
const skipHref = (h: string) => h === '' || h.startsWith('{{') || /^(mailto:|tel:|#)/i.test(h) || /\/c\/\{\{c:\d+\}\}$/.test(h);
|
|
169
|
+
const finalUrls = new Set(c.links.map((l) => l.url)); // 沒有追蹤網址時 HTML 裡放的是加了 utm 的網址,已用原網址查過,不重複打
|
|
170
|
+
for (const h of refs.hrefs) if (!skipHref(h) && !targets.has(h) && !finalUrls.has(h)) targets.set(h, 'link');
|
|
171
|
+
for (const i of refs.imgs) if (i.src && !isPixel(i.src)) targets.set(i.src, 'image');
|
|
172
|
+
if (opts.webUrl) targets.set(opts.webUrl, 'web');
|
|
173
|
+
const list = [...targets.entries()];
|
|
174
|
+
let cursor = 0;
|
|
175
|
+
const timeout = opts.timeoutMs ?? 10_000;
|
|
176
|
+
const worker = async () => {
|
|
177
|
+
while (cursor < list.length) {
|
|
178
|
+
const [url, kind] = list[cursor++];
|
|
179
|
+
let host = '';
|
|
180
|
+
try {
|
|
181
|
+
const u = new URL(url);
|
|
182
|
+
if (!/^https?:$/.test(u.protocol)) throw new Error('scheme');
|
|
183
|
+
host = u.hostname;
|
|
184
|
+
} catch {
|
|
185
|
+
add('link_invalid', 'error', kind === 'image' ? '圖片網址格式不對(或是待補標記)' : '網址格式不對(或是待補標記)', url.slice(0, 80));
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
if (privateHost(host)) {
|
|
189
|
+
add('link_private_host', 'error', '連結指向內網或本機位址', url.slice(0, 80));
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
const { status, blocked } = await probe(f, url, timeout);
|
|
193
|
+
linkStatuses.push({ url, status, kind });
|
|
194
|
+
if (kind === 'web' && status > 0 && !blocked) webChecked = true;
|
|
195
|
+
const what = kind === 'image' ? '圖片' : kind === 'web' ? '網頁版' : '連結';
|
|
196
|
+
if (blocked) {
|
|
197
|
+
add(blocked === 'private' ? 'link_redirect_private' : 'link_redirect_bad', 'error', blocked === 'private' ? `${what}轉址到內網或本機位址` : `${what}轉址次數過多或轉址目標不合法`, url.slice(0, 120));
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (status === 404 || status === 410) add(kind === 'image' ? 'image_broken' : 'link_broken', 'error', `${what}打不開(HTTP ${status})`, url.slice(0, 120));
|
|
201
|
+
else if (status === 0) add('link_unverified', 'warn', `${what}連不上或逾時,無法確認`, url.slice(0, 120));
|
|
202
|
+
else if (status >= 400) add('link_status', 'warn', `${what}回 HTTP ${status}(不算壞連結,照實記)`, url.slice(0, 120));
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
await Promise.all(Array.from({ length: Math.min(opts.concurrency ?? 6, Math.max(1, list.length)) }, worker));
|
|
206
|
+
linkStatuses.sort((a, b) => a.url.localeCompare(b.url));
|
|
207
|
+
}
|
|
208
|
+
if (opts.webUrl && linksChecked && !webChecked) add('web_url_unverified', 'warn', '網頁版網址連不上或逾時,無法確認');
|
|
209
|
+
|
|
210
|
+
return { ok: !issues.some((i) => i.severity === 'error'), linksChecked, webChecked, issues, linkStatuses };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const MAX_HOPS = 5;
|
|
214
|
+
type ProbeResult = { status: number; blocked?: 'private' | 'too_many_redirects' | 'bad_redirect' };
|
|
215
|
+
|
|
216
|
+
/** 先 HEAD;伺服器不支援 HEAD(405/501)再 GET。轉址自己一跳一跳跟,每一跳都重做內網檢查。連不上或逾時回 status 0。 */
|
|
217
|
+
async function probe(f: NonNullable<PreflightOptions['fetch']>, url: string, timeoutMs: number): Promise<ProbeResult> {
|
|
218
|
+
const once = async (method: 'HEAD' | 'GET'): Promise<ProbeResult> => {
|
|
219
|
+
let cur = url;
|
|
220
|
+
for (let hop = 0; hop <= MAX_HOPS; hop++) {
|
|
221
|
+
const ctl = new AbortController();
|
|
222
|
+
const timer = setTimeout(() => ctl.abort(), timeoutMs);
|
|
223
|
+
let res: { status: number; headers?: { get(name: string): string | null } };
|
|
224
|
+
try {
|
|
225
|
+
res = await f(cur, { method, signal: ctl.signal, redirect: 'manual' });
|
|
226
|
+
} catch {
|
|
227
|
+
return { status: 0 };
|
|
228
|
+
} finally {
|
|
229
|
+
clearTimeout(timer);
|
|
230
|
+
}
|
|
231
|
+
const loc = res.status >= 300 && res.status < 400 ? res.headers?.get('location') : null;
|
|
232
|
+
if (!loc) return { status: res.status };
|
|
233
|
+
if (hop === MAX_HOPS) return { status: res.status, blocked: 'too_many_redirects' };
|
|
234
|
+
let next: URL;
|
|
235
|
+
try {
|
|
236
|
+
next = new URL(loc, cur);
|
|
237
|
+
} catch {
|
|
238
|
+
return { status: res.status, blocked: 'bad_redirect' };
|
|
239
|
+
}
|
|
240
|
+
if (!/^https?:$/.test(next.protocol)) return { status: res.status, blocked: 'bad_redirect' };
|
|
241
|
+
if (privateHost(next.hostname)) return { status: res.status, blocked: 'private' };
|
|
242
|
+
cur = next.toString();
|
|
243
|
+
}
|
|
244
|
+
return { status: 0 };
|
|
245
|
+
};
|
|
246
|
+
const r = await once('HEAD');
|
|
247
|
+
// 有些伺服器對 HEAD 亂回(405/501,甚至 404/410):判壞連結之前再用 GET 確認一次
|
|
248
|
+
if (r.status === 405 || r.status === 501 || r.status === 404 || r.status === 410) return once('GET');
|
|
249
|
+
return r;
|
|
250
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// 預覽輸出:同一期信產成一組檔案(信件 HTML、純文字、檢查報告、一頁看全部的預覽頁)。純函式,寫檔由呼叫端做。
|
|
2
|
+
import type { ComposeResult } from './compose.ts';
|
|
3
|
+
import type { PreflightResult } from './preflight.ts';
|
|
4
|
+
import { personalize, type RecipientVars } from './personalize.ts';
|
|
5
|
+
import { escapeHtml } from './template.ts';
|
|
6
|
+
|
|
7
|
+
export const SAMPLE_VARS: RecipientVars = {
|
|
8
|
+
name: 'Sample Reader',
|
|
9
|
+
email: 'reader@example.com',
|
|
10
|
+
unsubscribe_url: 'https://example.com/unsubscribe/preview',
|
|
11
|
+
web_url: 'https://example.com/issue/preview',
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export interface PreviewOptions {
|
|
15
|
+
vars?: RecipientVars;
|
|
16
|
+
/** 範例收件人沒有名字時的樣子也要看=另外產一份。 */
|
|
17
|
+
withoutName?: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface PreviewFiles {
|
|
21
|
+
/** 檔名 → 內容。 */
|
|
22
|
+
files: Record<string, string>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function buildPreview(c: ComposeResult, check: PreflightResult, opts: PreviewOptions = {}): PreviewFiles {
|
|
26
|
+
const vars = opts.vars ?? SAMPLE_VARS;
|
|
27
|
+
const track = (kind: 'c' | 'o', index?: number) => (kind === 'c' ? `preview-${index}` : 'preview');
|
|
28
|
+
const a = personalize(c, vars, { track });
|
|
29
|
+
const files: Record<string, string> = {
|
|
30
|
+
'email.html': a.html,
|
|
31
|
+
'email.txt': a.text,
|
|
32
|
+
'check.json': JSON.stringify({ ok: check.ok, issues: check.issues, linkStatuses: check.linkStatuses }, null, 2),
|
|
33
|
+
'links.json': JSON.stringify(c.links, null, 2),
|
|
34
|
+
};
|
|
35
|
+
if (opts.withoutName) {
|
|
36
|
+
const b = personalize(c, { ...vars, name: null }, { track });
|
|
37
|
+
files['email-no-name.html'] = b.html;
|
|
38
|
+
files['email-no-name.txt'] = b.text;
|
|
39
|
+
}
|
|
40
|
+
files['index.html'] = previewPage(c, check, a.html, a.text);
|
|
41
|
+
return { files };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function previewPage(c: ComposeResult, check: PreflightResult, html: string, text: string): string {
|
|
45
|
+
const rows = check.issues
|
|
46
|
+
.map((i) => `<tr class="${i.severity}"><td>${escapeHtml(i.severity)}</td><td>${escapeHtml(i.code)}</td><td>${escapeHtml(i.message)}${i.where ? ` <code>${escapeHtml(i.where)}</code>` : ''}</td></tr>`)
|
|
47
|
+
.join('');
|
|
48
|
+
const frame = (w: number) => `<iframe sandbox="" style="width:${w}px;height:900px;border:1px solid #bbb;background:#fff" srcdoc="${escapeHtml(html)}"></iframe>`;
|
|
49
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Preview</title>
|
|
50
|
+
<style>body{font:14px/1.5 system-ui,sans-serif;margin:20px;color:#222}h2{margin:24px 0 8px}table{border-collapse:collapse}td{border:1px solid #ccc;padding:4px 8px;vertical-align:top}tr.error td{background:#fde8e8}tr.warn td{background:#fff6dd}.row{display:flex;gap:20px;flex-wrap:wrap;align-items:flex-start}pre{white-space:pre-wrap;background:#f5f5f5;padding:12px;max-width:760px}</style></head><body>
|
|
51
|
+
<h1>${escapeHtml(c.subject)}</h1>
|
|
52
|
+
<p>Preheader: ${escapeHtml(c.preheader)}</p>
|
|
53
|
+
<p><strong>${check.ok ? 'Checks passed' : 'Checks FAILED — do not schedule'}</strong> · HTML ${c.htmlBytes} bytes · ${c.links.length} tracked links · ${c.images.length} images</p>
|
|
54
|
+
<h2>Checks</h2>${rows ? `<table>${rows}</table>` : '<p>No issues.</p>'}
|
|
55
|
+
<h2>Mobile (375px) and desktop (700px)</h2><div class="row">${frame(375)}${frame(700)}</div>
|
|
56
|
+
<h2>Plain text</h2><pre>${escapeHtml(text)}</pre>
|
|
57
|
+
</body></html>`;
|
|
58
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// 區塊結構 → 信件安全的 HTML(內嵌樣式、表格友善)與純文字。純函式。
|
|
2
|
+
import type { Block, Inline } from './markdown.ts';
|
|
3
|
+
import { escapeHtml, type Labels, type Theme } from './template.ts';
|
|
4
|
+
|
|
5
|
+
interface Ctx {
|
|
6
|
+
theme: Theme;
|
|
7
|
+
labels: Labels;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const T = (c: Ctx) => `font-family:${c.theme.font};color:${c.theme.text}`;
|
|
11
|
+
|
|
12
|
+
function linkHtml(l: Inline & { t: 'link' }, c: Ctx): string {
|
|
13
|
+
const inner = l.c.map((n) => inlineHtml(n, c)).join('');
|
|
14
|
+
const href = l.out ?? l.href;
|
|
15
|
+
if (href === '') return inner; // 不安全的連結已被改成純文字
|
|
16
|
+
return `<a class="mr-link" href="${escapeHtml(href)}" style="color:${c.theme.link};text-decoration:underline;word-break:break-word;overflow-wrap:anywhere">${inner}</a>`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function imgHtml(src: string, alt: string, c: Ctx): string {
|
|
20
|
+
return `<img src="${escapeHtml(src)}" alt="${escapeHtml(alt)}" style="display:block;border:0;max-width:100%;height:auto">`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function inlineHtml(n: Inline, c: Ctx): string {
|
|
24
|
+
switch (n.t) {
|
|
25
|
+
case 'text':
|
|
26
|
+
return escapeHtml(n.v);
|
|
27
|
+
case 'code':
|
|
28
|
+
return `<code class="mr-code" style="background:${c.theme.codeBg};padding:1px 5px;border-radius:3px;font-family:Menlo,Consolas,monospace;font-size:0.9em">${escapeHtml(n.v)}</code>`;
|
|
29
|
+
case 'br':
|
|
30
|
+
return '<br>';
|
|
31
|
+
case 'strong':
|
|
32
|
+
return `<strong>${n.c.map((x) => inlineHtml(x, c)).join('')}</strong>`;
|
|
33
|
+
case 'em':
|
|
34
|
+
return `<em>${n.c.map((x) => inlineHtml(x, c)).join('')}</em>`;
|
|
35
|
+
case 'link':
|
|
36
|
+
return linkHtml(n, c);
|
|
37
|
+
case 'image':
|
|
38
|
+
return imgHtml(n.src, n.alt, c).replace('display:block;', 'display:inline-block;');
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const inlines = (ns: Inline[], c: Ctx) => ns.map((n) => inlineHtml(n, c)).join('');
|
|
43
|
+
|
|
44
|
+
function listItemHtml(blocks: Block[], c: Ctx): string {
|
|
45
|
+
// 只有一個段落的項目不要段落邊距
|
|
46
|
+
if (blocks.length === 1 && blocks[0].t === 'p') return inlines(blocks[0].c, c);
|
|
47
|
+
return blocks.map((b, i) => blockHtml(b, c, i === blocks.length - 1)).join('');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function blockHtml(b: Block, c: Ctx, last = false): string {
|
|
51
|
+
const mb = last ? '0' : '18px';
|
|
52
|
+
switch (b.t) {
|
|
53
|
+
case 'p':
|
|
54
|
+
return `<p class="mr-text" style="margin:0 0 ${mb};font-size:16px;line-height:1.8;${T(c)}">${inlines(b.c, c)}</p>`;
|
|
55
|
+
case 'h': {
|
|
56
|
+
const size = [0, 26, 22, 19, 17, 16, 16][b.level];
|
|
57
|
+
const lv = Math.min(b.level, 6);
|
|
58
|
+
return `<h${lv} class="mr-text" style="margin:${b.level <= 2 ? '28px' : '22px'} 0 12px;font-size:${size}px;line-height:1.4;font-weight:700;${T(c)}">${inlines(b.c, c)}</h${lv}>`;
|
|
59
|
+
}
|
|
60
|
+
case 'hr':
|
|
61
|
+
return `<hr class="mr-bd" style="border:0;border-top:1px solid ${c.theme.border};margin:24px 0">`;
|
|
62
|
+
case 'quote':
|
|
63
|
+
return `<blockquote class="mr-bd mr-muted" style="margin:0 0 ${mb};padding:2px 0 2px 14px;border-left:3px solid ${c.theme.border};color:${c.theme.muted}">${b.c.map((x, i) => blockHtml(x, c, i === b.c.length - 1)).join('')}</blockquote>`;
|
|
64
|
+
case 'list': {
|
|
65
|
+
const tag = b.ordered ? 'ol' : 'ul';
|
|
66
|
+
const items = b.items.map((it) => `<li class="mr-text" style="margin:0 0 8px;font-size:16px;line-height:1.8;${T(c)}">${listItemHtml(it, c)}</li>`).join('');
|
|
67
|
+
return `<${tag} style="margin:0 0 ${mb};padding-left:24px">${items}</${tag}>`;
|
|
68
|
+
}
|
|
69
|
+
case 'code':
|
|
70
|
+
return `<pre class="mr-code mr-text" style="margin:0 0 ${mb};padding:12px 14px;background:${c.theme.codeBg};font-family:Menlo,Consolas,monospace;font-size:13px;line-height:1.6;white-space:pre-wrap;overflow-wrap:anywhere;color:${c.theme.text}">${escapeHtml(b.v)}</pre>`;
|
|
71
|
+
case 'table': {
|
|
72
|
+
const cell = (tag: 'th' | 'td', cellIn: Inline[], align: string | null) =>
|
|
73
|
+
`<${tag} class="mr-bd mr-text" style="border:1px solid ${c.theme.border};padding:8px 10px;font-size:14px;line-height:1.6;text-align:${align ?? 'left'};vertical-align:top;${tag === 'th' ? 'font-weight:700;' : ''}${T(c)}">${inlines(cellIn, c)}</${tag}>`;
|
|
74
|
+
const head = `<tr>${b.head.map((h, i) => cell('th', h, b.align[i] ?? null)).join('')}</tr>`;
|
|
75
|
+
const rows = b.rows.map((r) => `<tr>${r.map((x, i) => cell('td', x, b.align[i] ?? null)).join('')}</tr>`).join('');
|
|
76
|
+
return `<div style="margin:0 0 ${mb};overflow-x:auto"><table role="presentation" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;width:100%">${head}${rows}</table></div>`;
|
|
77
|
+
}
|
|
78
|
+
case 'image': {
|
|
79
|
+
const img = imgHtml(b.src, b.alt, c);
|
|
80
|
+
const inner = b.link && (b.link.out ?? b.link.href) !== '' ? `<a href="${escapeHtml(b.link.out ?? b.link.href)}" style="text-decoration:none">${img}</a>` : img;
|
|
81
|
+
return `<div style="margin:0 0 ${mb};line-height:0">${inner}</div>`;
|
|
82
|
+
}
|
|
83
|
+
case 'embed':
|
|
84
|
+
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin:0 0 ${mb}"><tr><td class="mr-code mr-bd" style="background:${c.theme.codeBg};border:1px solid ${c.theme.border};padding:14px 16px;font-size:15px;${T(c)}"><a class="mr-link" href="{{web_url}}" style="color:${c.theme.link}">${escapeHtml(c.labels.embedCard)}</a></td></tr></table>`;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function renderBodyHtml(blocks: Block[], theme: Theme, labels: Labels): string {
|
|
89
|
+
const c = { theme, labels };
|
|
90
|
+
return blocks.map((b, i) => blockHtml(b, c, i === blocks.length - 1)).join('\n');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ───────────── 純文字 ─────────────
|
|
94
|
+
|
|
95
|
+
function inlineText(n: Inline, labels: Labels): string {
|
|
96
|
+
switch (n.t) {
|
|
97
|
+
case 'text':
|
|
98
|
+
return n.v;
|
|
99
|
+
case 'code':
|
|
100
|
+
return n.v;
|
|
101
|
+
case 'br':
|
|
102
|
+
return '\n';
|
|
103
|
+
case 'strong':
|
|
104
|
+
case 'em':
|
|
105
|
+
return n.c.map((x) => inlineText(x, labels)).join('');
|
|
106
|
+
case 'image':
|
|
107
|
+
return labels.image(n.alt);
|
|
108
|
+
case 'link': {
|
|
109
|
+
const text = n.c.map((x) => inlineText(x, labels)).join('');
|
|
110
|
+
const url = n.tu ?? n.href;
|
|
111
|
+
if (url === '') return text;
|
|
112
|
+
if (n.bare || text.trim() === '' || text.trim() === n.href) return url;
|
|
113
|
+
return `${text} (${url})`;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const inlinesText = (ns: Inline[], l: Labels) => ns.map((n) => inlineText(n, l)).join('');
|
|
119
|
+
|
|
120
|
+
function blockText(b: Block, l: Labels, indent = ''): string {
|
|
121
|
+
const pad = (s: string) => s.split('\n').map((x) => (x === '' ? x : indent + x)).join('\n');
|
|
122
|
+
switch (b.t) {
|
|
123
|
+
case 'p':
|
|
124
|
+
return pad(inlinesText(b.c, l));
|
|
125
|
+
case 'h':
|
|
126
|
+
return pad(inlinesText(b.c, l));
|
|
127
|
+
case 'hr':
|
|
128
|
+
return pad('----------');
|
|
129
|
+
case 'quote':
|
|
130
|
+
return pad(b.c.map((x) => blockText(x, l)).join('\n\n').split('\n').map((x) => `> ${x}`.trimEnd()).join('\n'));
|
|
131
|
+
case 'list':
|
|
132
|
+
return b.items
|
|
133
|
+
.map((it, i) => {
|
|
134
|
+
const mark = b.ordered ? `${i + 1}. ` : '- ';
|
|
135
|
+
const body = it.map((x) => blockText(x, l)).join('\n\n');
|
|
136
|
+
const [first, ...rest] = body.split('\n');
|
|
137
|
+
return pad([mark + first, ...rest.map((x) => (x === '' ? x : ' '.repeat(mark.length) + x))].join('\n'));
|
|
138
|
+
})
|
|
139
|
+
.join('\n');
|
|
140
|
+
case 'code':
|
|
141
|
+
return pad(b.v.split('\n').map((x) => ` ${x}`).join('\n'));
|
|
142
|
+
case 'table':
|
|
143
|
+
return pad([b.head, ...b.rows].map((r) => r.map((cell) => inlinesText(cell, l).replace(/\n/g, ' ')).join(' | ')).join('\n'));
|
|
144
|
+
case 'image':
|
|
145
|
+
return pad(l.image(b.alt));
|
|
146
|
+
case 'embed':
|
|
147
|
+
return pad(`${l.embedCard.replace(/\s*→\s*$/, '')}: {{web_url}}`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function renderBodyText(blocks: Block[], labels: Labels): string {
|
|
152
|
+
return blocks.map((b) => blockText(b, labels)).join('\n\n');
|
|
153
|
+
}
|