@joelincc/mailroom 0.1.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +54 -8
- 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 +37 -0
- package/dist/cli/main.js +533 -0
- package/dist/compose/clicks.js +29 -0
- package/dist/compose/compose.js +275 -0
- package/dist/compose/index.js +8 -0
- package/dist/compose/markdown.js +1197 -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 +141 -0
- package/dist/compose/template.js +118 -0
- package/docs/broadcast.md +199 -0
- package/docs/composing.md +156 -0
- package/docs/desk-commands.md +52 -0
- package/docs/export.md +52 -0
- package/docs/lists.md +68 -0
- package/docs/security-model.md +6 -4
- package/docs/ses.md +116 -0
- package/docs/tracking.md +102 -0
- package/docs/unsubscribe.md +124 -0
- package/docs/welcome.md +72 -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/migrations/0008_tracking.sql +5 -0
- package/migrations/0009_welcome.sql +17 -0
- package/package.json +21 -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 +352 -0
- package/src/broadcast/config.ts +136 -0
- package/src/broadcast/dispatch.ts +779 -0
- package/src/broadcast/events.ts +110 -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 +218 -0
- package/src/cf-events.ts +4 -3
- package/src/cli/args.ts +27 -0
- package/src/cli/errors.ts +39 -0
- package/src/cli/main.ts +515 -0
- package/src/compose/clicks.ts +45 -0
- package/src/compose/compose.ts +297 -0
- package/src/compose/index.ts +8 -0
- package/src/compose/markdown.ts +1173 -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 +158 -0
- package/src/compose/template.ts +197 -0
- package/src/core.ts +45 -2
- package/src/export.ts +184 -0
- package/src/feedback.ts +128 -0
- package/src/http.ts +17 -0
- package/src/index.ts +146 -32
- package/src/list-routes.ts +55 -0
- package/src/lists.ts +381 -0
- package/src/ses-events.ts +426 -0
- package/src/track.ts +409 -0
- package/src/unsub-wiring.ts +64 -0
- package/src/unsub.ts +499 -0
- package/src/webhook.ts +5 -3
- package/src/welcome.ts +257 -0
- package/wrangler.example.jsonc +16 -2
|
@@ -0,0 +1,1197 @@
|
|
|
1
|
+
// 產信第一步:把 markdown 原稿解析成「區塊+行內」結構。純函式,不碰網路,不 import cloudflare:*。
|
|
2
|
+
// 只支援信件排得出來的語法;不認得的東西一律記成 problem(檢查會擋下),絕不默默吞掉或亂猜。
|
|
3
|
+
const clip = (s, n = 60) => (s.length > n ? `${s.slice(0, n)}…` : s).replace(/\s+/g, ' ');
|
|
4
|
+
/** 嵌入類 HTML(互動圖表、影片):信裡放不了,換成「到網站看」的連結卡。 */
|
|
5
|
+
const EMBED_TAG = /^\s*<\s*(iframe|video|audio|embed|object|canvas)\b/i;
|
|
6
|
+
const ANY_TAG = /<\/?[a-zA-Z][^>]*>/;
|
|
7
|
+
/** 行內標籤開頭的行不是 HTML 區塊,當一般段落(a、b、strong、i、em、br)。 */
|
|
8
|
+
const INLINE_START = /^\s*<\s*(a|b|strong|i|em|br)\b|^\s*<https?:\/\//i;
|
|
9
|
+
/** 原稿裡寫的 \{ 先換成這個私用字元,輸出時才變成真的「{」,避免被當成佔位。 */
|
|
10
|
+
export const LBRACE = '\uE000';
|
|
11
|
+
const protectBraces = (v) => v.replace(/\{\{/g, LBRACE + LBRACE);
|
|
12
|
+
const NAMED = { nbsp: '\u00a0', amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
|
|
13
|
+
/** 原稿文字裡的 HTML 實體( & ' …)還原成字元;輸出時再統一跳脫一次。 */
|
|
14
|
+
export function decodeEntities(t) {
|
|
15
|
+
return t.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]+);/gi, (m, e) => {
|
|
16
|
+
if (e[0] === '#') {
|
|
17
|
+
const n = e[1].toLowerCase() === 'x' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
|
|
18
|
+
return n > 0 && n < 0x110000 && !(n >= 0xd800 && n <= 0xdfff) ? String.fromCodePoint(n) : m;
|
|
19
|
+
}
|
|
20
|
+
return NAMED[e.toLowerCase()] ?? m;
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/** 常見的 HTML 標籤名;不在這張表裡的「<…>」多半只是文字(例如 <Research.example>)。 */
|
|
24
|
+
const HTML_TAG_NAMES = new Set('a abbr b blockquote body br button canvas center code dd del details div dl dt em embed figure font footer form h1 h2 h3 h4 h5 h6 head header hr html i iframe img input ins kbd label li link main mark meta nav object ol p picture pre q s samp script section small source span strike strong style sub summary sup svg table tbody td tfoot th thead title tr u ul var video audio'.split(' '));
|
|
25
|
+
function tagProblem(tag, inline) {
|
|
26
|
+
const name = tag.match(/^<\/?\s*([a-zA-Z][\w-]*)/)?.[1]?.toLowerCase() ?? '';
|
|
27
|
+
const where = clip(tag);
|
|
28
|
+
const wellFormed = /^<\/?[a-zA-Z][\w-]*(?:\s[^>]*)?\/?>$/.test(tag.trim()); // </p/100110> 這種名字像標籤、寫法不是標籤的不算
|
|
29
|
+
if (HTML_TAG_NAMES.has(name) && wellFormed)
|
|
30
|
+
return { message: inline ? '原稿有信件排不出來的行內 HTML 標籤' : '原稿有信件排不出來的 HTML 區塊', where };
|
|
31
|
+
return { message: '原稿有看起來像 HTML 標籤的文字(角括號包著的字),引擎會當成標籤而排不出來;如果它不是標籤,請改寫(拿掉角括號,或用反引號包起來)', where };
|
|
32
|
+
}
|
|
33
|
+
// 非 ASCII 的字(中日韓文、全形標點)也算網址的一部分,跟網站一樣:維基條目、商品頁的中文路徑要整串連過去;
|
|
34
|
+
// 只有空白(含全形空白、不換行空白)和 < 會讓網址結束。私用區字元是引擎自己的記號(例:跳脫的大括號),不算。
|
|
35
|
+
const URL_RE = /https?:\/\/(?:[A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]|[^\x00-\x7F\s\uE000-\uF8FF])+/g;
|
|
36
|
+
/** 網址裡的非 ASCII 字照網站的寫法轉成 %XX(UTF-8),連結目的地才跟網站一樣、也能安全放進轉址標頭。 */
|
|
37
|
+
function encodeNonAscii(u) {
|
|
38
|
+
return u.replace(/[^\x00-\x7F]+/g, (m) => {
|
|
39
|
+
try {
|
|
40
|
+
return encodeURIComponent(m);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return encodeURIComponent(m.replace(/[\uD800-\uDFFF]/g, '\uFFFD'));
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
function splitFrontmatter(src) {
|
|
48
|
+
const text = src.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
|
|
49
|
+
const m = text.match(/^---\n([\s\S]*?)\n---[ \t]*(?:\n|$)/);
|
|
50
|
+
if (!m)
|
|
51
|
+
return { body: text, fm: {} };
|
|
52
|
+
const fm = {};
|
|
53
|
+
for (const line of m[1].split('\n')) {
|
|
54
|
+
const kv = line.match(/^([A-Za-z_][\w-]*):[ \t]*(.*)$/);
|
|
55
|
+
if (!kv)
|
|
56
|
+
continue;
|
|
57
|
+
let v = kv[2].trim();
|
|
58
|
+
if (v === '' || v.startsWith('[') || v.startsWith('{') || v === '|' || v === '>')
|
|
59
|
+
continue; // 清單/巢狀/多行不收
|
|
60
|
+
if ((v.startsWith('"') && v.endsWith('"') && v.length >= 2) || (v.startsWith("'") && v.endsWith("'") && v.length >= 2)) {
|
|
61
|
+
const q = v[0];
|
|
62
|
+
v = v.slice(1, -1);
|
|
63
|
+
v = q === '"' ? v.replace(/\\(["\\])/g, '$1') : v.replace(/''/g, "'");
|
|
64
|
+
}
|
|
65
|
+
fm[kv[1]] = v;
|
|
66
|
+
}
|
|
67
|
+
return { body: text.slice(m[0].length), fm };
|
|
68
|
+
}
|
|
69
|
+
const newCtx = () => ({ problems: [], hidden: 0, inCode: 0, tab: '', defs: [], refs: new Set(), inDef: false, inLink: 0, mdLink: 0, urlCtx: 0, dest: [], lastDefEnd: -1 });
|
|
70
|
+
const scratch = newCtx;
|
|
71
|
+
/** 行首空白裡有 tab。 */
|
|
72
|
+
const tabLead = (l) => /^[ \t]*\t/.test(l.startsWith(LAZY) ? l.slice(1) : l);
|
|
73
|
+
const noteTab = (ctx, l) => {
|
|
74
|
+
if (!ctx.tab)
|
|
75
|
+
ctx.tab = l;
|
|
76
|
+
};
|
|
77
|
+
const marks = (s) => s.split('<!--').length - 1;
|
|
78
|
+
/** CommonMark 可用反斜線跳脫的字元(ASCII 標點)。 */
|
|
79
|
+
const ESCAPABLE = /[!-/:-@[-`{-~]/;
|
|
80
|
+
/** s[i] 起是 <!--:回傳註解結束後的位置(第一個 -->;<!--> 與 <!---> 是空註解)。沒收尾回 -1。區塊與行內共用。 */
|
|
81
|
+
function commentEnd(s, i) {
|
|
82
|
+
const e = s.indexOf('-->', i + 2);
|
|
83
|
+
return e < 0 ? -1 : e + 3;
|
|
84
|
+
}
|
|
85
|
+
/** 一段要藏起來的註解:記帳;裡面有「--!>」時瀏覽器會提早結束註解(網站藏的範圍和這裡不同),記 error。 */
|
|
86
|
+
function hideComment(text, ctx) {
|
|
87
|
+
ctx.hidden += marks(text);
|
|
88
|
+
if (text.includes('--!>')) {
|
|
89
|
+
ctx.problems.push({ code: 'comment_ambiguous', severity: 'error', message: 'HTML 註解裡有「--!>」:瀏覽器會在那裡就結束註解,後面的字會被讀者看到;請拿掉這三個字元', where: clip(text) });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const unclosedComment = (where) => ({ code: 'unclosed_comment', severity: 'error', message: 'HTML 註解(<!--)沒有收尾:網站上它會把後面的內容藏起來,信裡則會露出來;請補上 -->', where: clip(where) });
|
|
93
|
+
/**
|
|
94
|
+
* 行內程式碼:s[i] 是一串反引號的開頭,找下一串「剛好一樣長」的反引號當收尾。找不到=不是程式碼(回 null,整串反引號當一般字元)。
|
|
95
|
+
* s 是已經切好的一個區塊的內容(段落、標題、表格的一格),所以不會跨區塊配對。
|
|
96
|
+
*/
|
|
97
|
+
function codeSpanAt(s, i) {
|
|
98
|
+
let n = 0;
|
|
99
|
+
while (s[i + n] === '`')
|
|
100
|
+
n++;
|
|
101
|
+
let j = i + n;
|
|
102
|
+
while (j < s.length) {
|
|
103
|
+
if (s[j] === '`') {
|
|
104
|
+
let m = 0;
|
|
105
|
+
while (s[j + m] === '`')
|
|
106
|
+
m++;
|
|
107
|
+
if (m === n)
|
|
108
|
+
return { open: n, close: j, end: j + m };
|
|
109
|
+
j += m;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
j++;
|
|
113
|
+
}
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
const RAW_TAG = /^<\/?[a-zA-Z][^>]*>/;
|
|
117
|
+
const AUTOLINK = /^<(https?:\/\/[^\s<>]+)>/i;
|
|
118
|
+
/**
|
|
119
|
+
* s[i] 起若是一個「不可切開」的行內單位(反斜線跳脫、行內程式碼或一串沒配對的反引號、註解、自動連結、HTML 標籤),回傳它結束的位置;不是回 -1。
|
|
120
|
+
* 找連結的 ]、強調的收尾記號、</a> 時都跳過這些單位,所以強調或連結不會把程式碼或註解切成兩半(CommonMark 的優先順序)。
|
|
121
|
+
*/
|
|
122
|
+
function atomEnd(s, i) {
|
|
123
|
+
const ch = s[i];
|
|
124
|
+
if (ch === '\\' && i + 1 < s.length && ESCAPABLE.test(s[i + 1]))
|
|
125
|
+
return i + 2;
|
|
126
|
+
if (ch === '`') {
|
|
127
|
+
const span = codeSpanAt(s, i);
|
|
128
|
+
if (span)
|
|
129
|
+
return span.end;
|
|
130
|
+
let n = 0;
|
|
131
|
+
while (s[i + n] === '`')
|
|
132
|
+
n++;
|
|
133
|
+
return i + n;
|
|
134
|
+
}
|
|
135
|
+
if (ch === '<') {
|
|
136
|
+
if (s.startsWith('<!--', i))
|
|
137
|
+
return commentEnd(s, i);
|
|
138
|
+
// 偽註解(<?…?>、<!X…>、<![CDATA[…]]>)在網站上也是一整塊原始 HTML,不能從中間切開(例如吞掉連結的 ](網址))
|
|
139
|
+
const close = s.startsWith('<![CDATA[', i) ? ']]>' : s.startsWith('<?', i) ? '?>' : /^<![A-Za-z]/.test(s.slice(i, i + 3)) ? '>' : '';
|
|
140
|
+
if (close) {
|
|
141
|
+
const e = s.indexOf(close, i + 2);
|
|
142
|
+
if (e >= 0)
|
|
143
|
+
return e + close.length;
|
|
144
|
+
}
|
|
145
|
+
const m = s.slice(i).match(AUTOLINK) ?? s.slice(i).match(RAW_TAG);
|
|
146
|
+
if (m)
|
|
147
|
+
return i + m[0].length;
|
|
148
|
+
}
|
|
149
|
+
return -1;
|
|
150
|
+
}
|
|
151
|
+
/** 從 from 起找 mark(大小寫不分),跳過不可切開的單位;找不到回 -1。 */
|
|
152
|
+
function findMark(s, from, mark) {
|
|
153
|
+
const lower = mark.toLowerCase();
|
|
154
|
+
for (let i = from; i < s.length;) {
|
|
155
|
+
if (s.slice(i, i + mark.length).toLowerCase() === lower)
|
|
156
|
+
return i;
|
|
157
|
+
const a = atomEnd(s, i);
|
|
158
|
+
i = a > i ? a : i + 1;
|
|
159
|
+
}
|
|
160
|
+
return -1;
|
|
161
|
+
}
|
|
162
|
+
/** 從 s[start](必須是 '[')找對應的 ']'(可巢狀,跳過程式碼、註解、跳脫),回傳位置。 */
|
|
163
|
+
function matchBracket(s, start) {
|
|
164
|
+
let depth = 0;
|
|
165
|
+
for (let i = start; i < s.length;) {
|
|
166
|
+
const a = i === start ? -1 : atomEnd(s, i);
|
|
167
|
+
if (a > i) {
|
|
168
|
+
i = a;
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
if (s[i] === '[')
|
|
172
|
+
depth++;
|
|
173
|
+
else if (s[i] === ']') {
|
|
174
|
+
depth--;
|
|
175
|
+
if (depth === 0)
|
|
176
|
+
return i;
|
|
177
|
+
}
|
|
178
|
+
i++;
|
|
179
|
+
}
|
|
180
|
+
return -1;
|
|
181
|
+
}
|
|
182
|
+
/** 從 s[start](必須是 '(')讀一個括號平衡的網址,回傳 [網址, 下一個位置];讀不到回 null。 */
|
|
183
|
+
function readParenUrl(s, start) {
|
|
184
|
+
if (s[start] !== '(')
|
|
185
|
+
return null;
|
|
186
|
+
let depth = 0;
|
|
187
|
+
let i = start;
|
|
188
|
+
for (; i < s.length; i++) {
|
|
189
|
+
const c = s[i];
|
|
190
|
+
if (c === '\n')
|
|
191
|
+
return null;
|
|
192
|
+
if (c === '(')
|
|
193
|
+
depth++;
|
|
194
|
+
else if (c === ')') {
|
|
195
|
+
depth--;
|
|
196
|
+
if (depth === 0)
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (depth !== 0)
|
|
201
|
+
return null;
|
|
202
|
+
const inner = s.slice(start + 1, i).trim();
|
|
203
|
+
// 去掉可選的 "title"
|
|
204
|
+
const m = inner.match(/^(\S+)(?:\s+(?:"[^"]*"|'[^']*'))?$/);
|
|
205
|
+
if (!m)
|
|
206
|
+
return null;
|
|
207
|
+
let url = m[1];
|
|
208
|
+
if (url.startsWith('<') && url.endsWith('>'))
|
|
209
|
+
url = url.slice(1, -1);
|
|
210
|
+
return [url, i + 1];
|
|
211
|
+
}
|
|
212
|
+
function trimUrlTail(u) {
|
|
213
|
+
// 網址尾巴的標點不算網址
|
|
214
|
+
let end = u.length;
|
|
215
|
+
while (end > 0 && /[.,;:!?'*_~\]]/.test(u[end - 1]))
|
|
216
|
+
end--;
|
|
217
|
+
// 不成對的右括號也不算
|
|
218
|
+
while (end > 0 && u[end - 1] === ')') {
|
|
219
|
+
const sub = u.slice(0, end);
|
|
220
|
+
if ((sub.match(/\(/g) ?? []).length < (sub.match(/\)/g) ?? []).length)
|
|
221
|
+
end--;
|
|
222
|
+
else
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
return u.slice(0, end);
|
|
226
|
+
}
|
|
227
|
+
/** 網址最後一個字是中日韓文的句讀或右括號(詳見https://….、(https://…)):多半是作者沒在網址後面空格。 */
|
|
228
|
+
const CJK_PUNCT_END = /[,。、;:!?)」』】》〉]$/;
|
|
229
|
+
function autolink(text, ctx) {
|
|
230
|
+
const out = [];
|
|
231
|
+
let last = 0;
|
|
232
|
+
for (const m of text.matchAll(URL_RE)) {
|
|
233
|
+
const raw = m[0];
|
|
234
|
+
const url = trimUrlTail(raw);
|
|
235
|
+
const at = m.index ?? 0;
|
|
236
|
+
if (url.length < 9)
|
|
237
|
+
continue;
|
|
238
|
+
// 網址前面緊接英文字母或數字(例:abchttps://…):網站不做成連結,照字面留著
|
|
239
|
+
if (at > 0 && /[A-Za-z0-9]/.test(text[at - 1]))
|
|
240
|
+
continue;
|
|
241
|
+
if (at > last)
|
|
242
|
+
out.push({ t: 'text', v: text.slice(last, at) });
|
|
243
|
+
// 網址緊貼全形標點(詳見https://…。、(https://…)):網站把標點算進網址(連結多半會壞),信裡照網站做,提醒作者
|
|
244
|
+
if (ctx && CJK_PUNCT_END.test(url))
|
|
245
|
+
ctx.problems.push({ code: 'url_glued_text', severity: 'warn', message: '網址後面緊貼著全形標點或文字,網站會把它們都算進網址(連結多半會壞);信裡照網站的樣子做。請在網址和後面的字之間加空格', where: clip(url) });
|
|
246
|
+
out.push({ t: 'link', href: encodeNonAscii(url), c: [{ t: 'text', v: url }], bare: true });
|
|
247
|
+
last = at + url.length;
|
|
248
|
+
}
|
|
249
|
+
if (last < text.length)
|
|
250
|
+
out.push({ t: 'text', v: text.slice(last) });
|
|
251
|
+
return out.map((n) => (n.t === 'text' ? { t: 'text', v: decodeEntities(n.v) } : n));
|
|
252
|
+
}
|
|
253
|
+
/** 網站會自動連結的網址(http、https、www.、email)出現在一串不含空白的字裡。 */
|
|
254
|
+
const URL_TAIL = /(?:https?:\/\/|www\.|[\w.+-]+@[\w-]+\.)/i;
|
|
255
|
+
/** 腳註標籤比對:不分大小寫,照 Unicode 的大小寫折疊(ß=ss、ς=σ)。 */
|
|
256
|
+
const EMAIL_TAIL = /[\w.+-]+@[\w-]+\./;
|
|
257
|
+
/** 一串字裡每一個網址的開頭(https://www. 只算一次)。 */
|
|
258
|
+
const URL_STARTS = /https?:\/\/(?:www\.)?|www\./gi;
|
|
259
|
+
/**
|
|
260
|
+
* 原稿這一串(不含空白)裡有裸網址:網站的自動連結會從網址一路吞到下一個空白(中間的 [..](..)、**、反引號都吞)。
|
|
261
|
+
* 每一個網址都要看(不只第一個);只有信裡真的收成連結目的地的才不算——[文字](網址)、、<網址>、<a href>,
|
|
262
|
+
* 而且那個連結在網站上也得是連結(連結文字裡又有連結時,網站不把外層當連結,外層的 ](網址) 就變成裸網址)。
|
|
263
|
+
* at=這一串在最外層原稿裡從哪裡開始;ctx.dest 記著這些連結目的地在最外層原稿裡的範圍。
|
|
264
|
+
*/
|
|
265
|
+
function bareUrlBefore(srcTail, at, ctx) {
|
|
266
|
+
for (const m of srcTail.matchAll(URL_STARTS)) {
|
|
267
|
+
const p = at + (m.index ?? 0);
|
|
268
|
+
if (!ctx.dest.some(([a, b]) => p >= a && p < b))
|
|
269
|
+
return true;
|
|
270
|
+
}
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
const hasLink = (ns) => ns.some((n) => n.t === 'link' || ('c' in n && Array.isArray(n.c) && hasLink(n.c)));
|
|
274
|
+
const fnLabel = (l) => l.toLowerCase().toUpperCase().toLowerCase();
|
|
275
|
+
/**
|
|
276
|
+
* 緊貼寫法的總檢查(判不準就擋):一串不含空白的字裡,
|
|
277
|
+
* ① 裸網址(http(s)://、www.)後面還緊貼著 [ * ` 這類記號(或前面緊貼實體字):網站會把它們全吞進網址,信裡卻當成語法;
|
|
278
|
+
* ② 出現 ![^:網站不當腳註引用;
|
|
279
|
+
* ③ 腳註引用前面有巢狀中括號:網站的切法判不準。
|
|
280
|
+
* 程式碼片段的內容先遮掉不看。
|
|
281
|
+
*/
|
|
282
|
+
function gluedProblem(s) {
|
|
283
|
+
let masked = '';
|
|
284
|
+
for (let i = 0; i < s.length;) {
|
|
285
|
+
if (s[i] === '`') {
|
|
286
|
+
const span = codeSpanAt(s, i);
|
|
287
|
+
if (span) {
|
|
288
|
+
masked += '`' + ' '.repeat(Math.max(0, span.end - i - 2)).replace(/ /g, '\u0001') + '`';
|
|
289
|
+
i = span.end;
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
masked += s[i++];
|
|
294
|
+
}
|
|
295
|
+
for (const tok of masked.split(/\s+/)) {
|
|
296
|
+
if (!tok)
|
|
297
|
+
continue;
|
|
298
|
+
if (tok.includes('(www.…**…),不只第一個
|
|
301
|
+
for (let from = 0;;) {
|
|
302
|
+
URL_STARTS.lastIndex = from;
|
|
303
|
+
const m = URL_STARTS.exec(tok);
|
|
304
|
+
if (!m)
|
|
305
|
+
break;
|
|
306
|
+
const u = m.index;
|
|
307
|
+
// 實體字(& 等)緊接網址:網站解碼後的切法跟信裡不同
|
|
308
|
+
if (u > 0 && /&[A-Za-z0-9#]+;$/.test(tok.slice(0, u)))
|
|
309
|
+
return tok;
|
|
310
|
+
// ](網址)、<網址>、[網址](…)(網址當連結文字)、href="網址"(HTML 屬性)裡的網址不是裸網址;
|
|
311
|
+
// 跳過整個網址再找下一個(存檔網址 https://web.archive.org/web/…/https://… 、app.www.… 裡面的不另算)
|
|
312
|
+
const wrap = tok.slice(0, u).match(/(?:\]\(|<|\[|=(["']))$/);
|
|
313
|
+
if (wrap) {
|
|
314
|
+
const close = wrap[0] === '](' ? ')' : wrap[0] === '<' ? '>' : wrap[0] === '[' ? ']' : wrap[1];
|
|
315
|
+
const end = tok.indexOf(close, u);
|
|
316
|
+
if (end < 0)
|
|
317
|
+
break;
|
|
318
|
+
from = end + 1;
|
|
319
|
+
continue;
|
|
320
|
+
}
|
|
321
|
+
// 裸網址:網站一路吞到這一串結束,後面緊貼的 [ * ` 都會被吞進去;後面的網址也在它裡面,不必再看
|
|
322
|
+
if (GLUE_AFTER_URL.test(tok.slice(u)))
|
|
323
|
+
return tok;
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
const f = tok.search(/\[\^[^\]\s]+\]/);
|
|
327
|
+
if (f > 0) {
|
|
328
|
+
let d = 0;
|
|
329
|
+
for (const ch of tok.slice(0, f)) {
|
|
330
|
+
if (ch === '[')
|
|
331
|
+
d++;
|
|
332
|
+
else if (ch === ']')
|
|
333
|
+
d = Math.max(0, d - 1);
|
|
334
|
+
if (d >= 2)
|
|
335
|
+
return tok;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
return null;
|
|
340
|
+
}
|
|
341
|
+
// 網址本身常有 _ & ~ !(查詢字串、維基檔名),不算;只看會被信裡當成語法的 [ * `
|
|
342
|
+
const GLUE_AFTER_URL = /[[*`]/;
|
|
343
|
+
function parseInline(s, ctx, depth = 0, off = 0) {
|
|
344
|
+
// off=s 在最外層原稿裡從哪裡開始(腳註、強調前面有沒有裸網址,要對照 ctx.dest 的範圍)
|
|
345
|
+
if (depth === 0)
|
|
346
|
+
ctx.dest = [];
|
|
347
|
+
if (depth === 0 && !ctx.inLink) {
|
|
348
|
+
const g = gluedProblem(s);
|
|
349
|
+
if (g)
|
|
350
|
+
ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '網址、腳註引用、強調記號沒有空格緊貼在一起,網站上的切法判不準;請在網址前後加空格', where: clip(g) });
|
|
351
|
+
}
|
|
352
|
+
const out = [];
|
|
353
|
+
let buf = '';
|
|
354
|
+
const flush = () => {
|
|
355
|
+
if (buf) {
|
|
356
|
+
// [文字](網址) 的連結文字裡,網站不再自動連結(連結裡不能有連結);<a href> 裡的網站會自動連結,照做
|
|
357
|
+
out.push(...(ctx.mdLink ? [{ t: 'text', v: decodeEntities(buf) }] : autolink(buf, ctx)));
|
|
358
|
+
buf = '';
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
let i = 0;
|
|
362
|
+
// 強調的內層:前面緊接裸網址時,網站把整串吞進網址,內層的腳註引用不算
|
|
363
|
+
const tailAt = () => {
|
|
364
|
+
const t = s.slice(0, i).match(/\S*$/)[0];
|
|
365
|
+
return [t, off + i - t.length];
|
|
366
|
+
};
|
|
367
|
+
const inner = (from, to) => {
|
|
368
|
+
const u = bareUrlBefore(...tailAt(), ctx) || URL_TAIL.test(buf.match(/\S*$/)[0]);
|
|
369
|
+
if (u)
|
|
370
|
+
ctx.urlCtx++;
|
|
371
|
+
const r = parseInline(s.slice(from, to), ctx, depth + 1, off + from);
|
|
372
|
+
if (u)
|
|
373
|
+
ctx.urlCtx--;
|
|
374
|
+
return r;
|
|
375
|
+
};
|
|
376
|
+
while (i < s.length) {
|
|
377
|
+
const ch = s[i];
|
|
378
|
+
if (ch === '\\' && i + 1 < s.length && ESCAPABLE.test(s[i + 1])) {
|
|
379
|
+
buf += s[i + 1] === '{' ? LBRACE : s[i + 1];
|
|
380
|
+
i += 2;
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
if (ch === '\n') {
|
|
384
|
+
buf = buf.replace(/[ \t]+$/, '');
|
|
385
|
+
flush();
|
|
386
|
+
out.push({ t: 'br' });
|
|
387
|
+
i++;
|
|
388
|
+
while (s[i] === ' ' || s[i] === '\t')
|
|
389
|
+
i++;
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
if (ch === '`') {
|
|
393
|
+
// 網址後面緊接反引號:網站會把反引號收進自動連結,程式碼的切法就跟信裡不同,判不準
|
|
394
|
+
if (URL_TAIL.test(buf.match(/\S*$/)[0]) || bareUrlBefore(...tailAt(), ctx))
|
|
395
|
+
ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '網址後面緊接反引號,網站會把反引號當成網址的一部分;請在網址和反引號之間加空格', where: clip(buf.match(/\S*$/)[0] + s.slice(i, i + 20)) });
|
|
396
|
+
const span = codeSpanAt(s, i);
|
|
397
|
+
if (span) {
|
|
398
|
+
flush();
|
|
399
|
+
const raw = s.slice(i + span.open, span.close);
|
|
400
|
+
ctx.inCode += marks(raw);
|
|
401
|
+
// CommonMark:換行當空白;頭尾各有一個空白(且不全是空白)就各去掉一個
|
|
402
|
+
let v = raw.replace(/\n/g, ' ');
|
|
403
|
+
if (v.length > 2 && v.startsWith(' ') && v.endsWith(' ') && v.trim() !== '')
|
|
404
|
+
v = v.slice(1, -1);
|
|
405
|
+
out.push({ t: 'code', v: protectBraces(v) });
|
|
406
|
+
i = span.end;
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
// 沒配對的反引號:整串當一般字元
|
|
410
|
+
let n = 0;
|
|
411
|
+
while (s[i + n] === '`')
|
|
412
|
+
n++;
|
|
413
|
+
buf += '`'.repeat(n);
|
|
414
|
+
i += n;
|
|
415
|
+
continue;
|
|
416
|
+
}
|
|
417
|
+
if (ch === '<' && s.startsWith('<!--', i)) {
|
|
418
|
+
const e = commentEnd(s, i);
|
|
419
|
+
if (e < 0) {
|
|
420
|
+
// 網站上這是字面文字;信裡也照原樣留著,但記 error 擋下(作者多半是忘了收尾)
|
|
421
|
+
ctx.problems.push(unclosedComment(s.slice(i)));
|
|
422
|
+
buf += '<!--';
|
|
423
|
+
i += 4;
|
|
424
|
+
continue;
|
|
425
|
+
}
|
|
426
|
+
flush(); // 註解把前後的字隔開:網址到這裡就結束,不能跟註解後面的字黏成一個網址
|
|
427
|
+
hideComment(s.slice(i, e), ctx);
|
|
428
|
+
i = e;
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
if (ch === '<' && PSEUDO_COMMENT.test(s.slice(i, i + 9))) {
|
|
432
|
+
flush();
|
|
433
|
+
ctx.problems.push({ code: 'unsupported_html', severity: 'error', message: '原稿有 <? 、<!X 或 <![CDATA[ 開頭的寫法,網站上會被當成註解藏起來,信裡做不到;請拿掉', where: clip(s.slice(i)) });
|
|
434
|
+
const close = s.indexOf('>', i);
|
|
435
|
+
const end = close < 0 ? s.length : close + 1;
|
|
436
|
+
ctx.hidden += marks(s.slice(i, end));
|
|
437
|
+
i = end;
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
if (ch === '!' && s[i + 1] === '[') {
|
|
441
|
+
const close = matchBracket(s, i + 1);
|
|
442
|
+
if (close > 0 && s[close + 1] === '(') {
|
|
443
|
+
const u = readParenUrl(s, close + 1);
|
|
444
|
+
if (u) {
|
|
445
|
+
flush();
|
|
446
|
+
ctx.dest.push([off + close + 1, off + u[1]]);
|
|
447
|
+
out.push({ t: 'image', src: u[0], alt: s.slice(i + 2, close).replace(/\\(.)/g, '$1') });
|
|
448
|
+
i = u[1];
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
// 腳註引用 [^名稱]:記下來(判斷定義有沒有被引用);字面照留。連結文字裡的引用網站不做連結,判不準,記 error
|
|
454
|
+
if (ch === '[') {
|
|
455
|
+
const fn = s.slice(i).match(/^\[\^([^\]\s\\]+)\]/);
|
|
456
|
+
// 接在網址後面(https://…[^1]、(www.…)[^1])的不算:網站會把整串變成自動連結(只看還沒處理的字,連結的 ](網址) 不算)
|
|
457
|
+
// 原稿這一串(例:*www.e.com*[^1])裡有網址、又不是 [文字](網址) 或 <網址> 收好的,也不算
|
|
458
|
+
const [srcTail, tailStart] = tailAt();
|
|
459
|
+
const inUrl = URL_TAIL.test(buf.match(/\S*$/)[0]) || bareUrlBefore(srcTail, tailStart, ctx) || (EMAIL_TAIL.test(srcTail) && !srcTail.includes('](') && !srcTail.endsWith('>'));
|
|
460
|
+
const isRef = fn && s[i + fn[0].length] !== '(' && s[i + fn[0].length] !== ':';
|
|
461
|
+
if (isRef && !inUrl && !ctx.urlCtx) {
|
|
462
|
+
if (!ctx.inDef)
|
|
463
|
+
ctx.refs.add(fnLabel(fn[1]));
|
|
464
|
+
if (ctx.inLink)
|
|
465
|
+
ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '連結文字裡有腳註引用,網站上不會做成連結;請把腳註移到連結外面', where: clip(fn[0]) });
|
|
466
|
+
}
|
|
467
|
+
else if (isRef) {
|
|
468
|
+
// 網站把這個腳註引用吞進前面的網址(例:(www.…**[^1]**)、**https://…**[^1]),不顯示腳註;信裡分不出來,擋下
|
|
469
|
+
ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '腳註引用緊貼在網址(或包著網址的括號、強調記號)後面,網站會把它當成網址的一部分、不顯示腳註;請在網址和腳註引用之間加空格', where: clip(srcTail + fn[0]) });
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
if (ch === '[' && depth < 3) {
|
|
473
|
+
const close = matchBracket(s, i);
|
|
474
|
+
if (close > 0 && s[close + 1] === '(') {
|
|
475
|
+
const u = readParenUrl(s, close + 1);
|
|
476
|
+
if (u) {
|
|
477
|
+
flush();
|
|
478
|
+
ctx.inLink++;
|
|
479
|
+
ctx.mdLink++;
|
|
480
|
+
const c = parseInline(s.slice(i + 1, close), ctx, depth + 1, off + i + 1);
|
|
481
|
+
ctx.mdLink--;
|
|
482
|
+
ctx.inLink--;
|
|
483
|
+
// 連結文字裡又有連結:網站不把外層當連結,外層的 (網址) 是裸網址,不記成收好的目的地
|
|
484
|
+
if (!hasLink(c))
|
|
485
|
+
ctx.dest.push([off + close + 1, off + u[1]]);
|
|
486
|
+
else {
|
|
487
|
+
// 網站不把外層當連結:外層的 [、](網址) 都照字面顯示。信裡做不到一模一樣(會變成巢狀連結、少掉那幾個字),擋下。
|
|
488
|
+
ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '連結文字裡又有一個連結:網站不會把外層當成連結(外層的方括號與網址會照字面顯示),信裡會少字;請把裡面那個連結拿出來', where: clip(s.slice(i, u[1])) });
|
|
489
|
+
}
|
|
490
|
+
out.push({ t: 'link', href: u[0], c });
|
|
491
|
+
i = u[1];
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
if (ch === '<') {
|
|
497
|
+
const br = s.slice(i).match(/^<br\s*\/?>/i);
|
|
498
|
+
if (br) {
|
|
499
|
+
flush();
|
|
500
|
+
out.push({ t: 'br' });
|
|
501
|
+
i += br[0].length;
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
const auto = s.slice(i).match(AUTOLINK);
|
|
505
|
+
if (auto) {
|
|
506
|
+
flush();
|
|
507
|
+
ctx.dest.push([off + i, off + i + auto[0].length]);
|
|
508
|
+
out.push({ t: 'link', href: auto[1], c: [{ t: 'text', v: auto[1] }], bare: true });
|
|
509
|
+
i += auto[0].length;
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
// <a href="…">文字</a>:只取 href 當一般連結,其他屬性丟掉
|
|
513
|
+
const a = s.slice(i).match(/^<a\s+([^>]*)>/i);
|
|
514
|
+
if (a) {
|
|
515
|
+
const href = a[1].match(/\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
|
|
516
|
+
const closeAt = findMark(s, i + a[0].length, '</a>');
|
|
517
|
+
if (href && closeAt > 0) {
|
|
518
|
+
flush();
|
|
519
|
+
ctx.dest.push([off + i, off + i + a[0].length]);
|
|
520
|
+
ctx.inLink++;
|
|
521
|
+
const c = parseInline(s.slice(i + a[0].length, closeAt), ctx, depth + 1, off + i + a[0].length);
|
|
522
|
+
ctx.inLink--;
|
|
523
|
+
out.push({ t: 'link', href: decodeEntities(href[1] ?? href[2] ?? ''), c });
|
|
524
|
+
i = closeAt + 4;
|
|
525
|
+
continue;
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
// <b>/<strong>/<i>/<em> 成對才收
|
|
529
|
+
const fmt = s.slice(i).match(/^<(b|strong|i|em)>/i);
|
|
530
|
+
if (fmt) {
|
|
531
|
+
const name = fmt[1].toLowerCase();
|
|
532
|
+
const closeAt = findMark(s, i + fmt[0].length, `</${name}>`);
|
|
533
|
+
if (closeAt > 0) {
|
|
534
|
+
flush();
|
|
535
|
+
out.push({ t: name === 'b' || name === 'strong' ? 'strong' : 'em', c: inner(i + fmt[0].length, closeAt) });
|
|
536
|
+
i = closeAt + name.length + 3;
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
const tag = s.slice(i).match(RAW_TAG);
|
|
541
|
+
if (tag) {
|
|
542
|
+
flush();
|
|
543
|
+
ctx.problems.push({ code: 'unsupported_html', severity: 'error', ...tagProblem(tag[0], true) });
|
|
544
|
+
ctx.hidden += marks(tag[0]);
|
|
545
|
+
i += tag[0].length;
|
|
546
|
+
continue;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
if (ch === '*' && depth < 4) {
|
|
550
|
+
const strong = s[i + 1] === '*';
|
|
551
|
+
const mark = strong ? '**' : '*';
|
|
552
|
+
const end = findMark(s, i + mark.length, mark);
|
|
553
|
+
if (end > i + mark.length && !/^\s/.test(s[i + mark.length]) && !/\s$/.test(s.slice(i + mark.length, end))) {
|
|
554
|
+
flush();
|
|
555
|
+
out.push({ t: strong ? 'strong' : 'em', c: inner(i + mark.length, end) });
|
|
556
|
+
i = end + mark.length;
|
|
557
|
+
continue;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
if (ch === '_' && depth < 4) {
|
|
561
|
+
const prev = s[i - 1] ?? ' ';
|
|
562
|
+
const end = findMark(s, i + 1, '_');
|
|
563
|
+
if (end > i + 1 && !/[A-Za-z0-9]/.test(prev) && !/\s/.test(s[i + 1]) && !/[A-Za-z0-9]/.test(s[end + 1] ?? ' ') && !/\s/.test(s[end - 1])) {
|
|
564
|
+
flush();
|
|
565
|
+
out.push({ t: 'em', c: inner(i + 1, end) });
|
|
566
|
+
i = end + 1;
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
buf += ch;
|
|
571
|
+
i++;
|
|
572
|
+
}
|
|
573
|
+
flush();
|
|
574
|
+
return out;
|
|
575
|
+
}
|
|
576
|
+
// ───────────── 區塊 ─────────────
|
|
577
|
+
// 照 CommonMark 的區塊規則切:先決定每一行屬於哪個區塊(程式碼框、註解區塊、段落…),區塊內容才交給行內解析。
|
|
578
|
+
const HR = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/;
|
|
579
|
+
const ATX = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
|
|
580
|
+
const SETEXT = /^ {0,3}(=+|-+)[ \t]*$/;
|
|
581
|
+
const QUOTE = /^ {0,3}>/;
|
|
582
|
+
/** HTML 註解區塊(CommonMark HTML 區塊第 2 型):行首(最多縮 3 格)是 <!--,到含 --> 的那一行結束;可以打斷段落。 */
|
|
583
|
+
const COMMENT_START = /^ {0,3}<!--/;
|
|
584
|
+
/** 會打斷段落的其他 HTML 區塊開頭(CommonMark 第 1、3~6 型)。 */
|
|
585
|
+
const HTML_INTERRUPT = /^ {0,3}(?:<(?:script|pre|style|textarea)(?:[\s>]|$)|<\?|<![A-Za-z]|<!\[CDATA\[|<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:[\s>]|\/>|$))/i;
|
|
586
|
+
const BLOCK_HTML = /^ {0,3}<\/?[a-zA-Z!]/;
|
|
587
|
+
/** 一行只有一個完整標籤(CommonMark HTML 區塊第 7 型):網站原樣輸出到空行為止,不轉 markdown;不能打斷段落,但會切斷懶惰續行。 */
|
|
588
|
+
const LONE_TAG = /^ {0,3}(?:<[A-Za-z][A-Za-z0-9-]*(?:\s+[^<>]*?)?\s*\/?>|<\/[A-Za-z][A-Za-z0-9-]*\s*>)\s*$/;
|
|
589
|
+
/** 瀏覽器當成註解藏起來的另外三種寫法(<?…>、<!X…>、<![CDATA[…]]>):信裡沒法照做,一律記 error。 */
|
|
590
|
+
const PSEUDO_COMMENT = /<(?:\?|![A-Za-z]|!\[CDATA\[)/;
|
|
591
|
+
/** 參照式連結定義([名稱]: 網址):網站上不顯示,信裡不支援,記 error(不然網站看不到的字會寄出去)。 */
|
|
592
|
+
const LINK_REF_DEF = /^ {0,3}\[(?!\^[^\]\s]+\]:)[^\]]+\]:/;
|
|
593
|
+
const DIV_WRAPPER = /^ {0,3}(?:<div(?:\s+lang\s*=\s*(?:"[A-Za-z-]*"|'[A-Za-z-]*'))?\s*>|<\/div\s*>)\s*$/i;
|
|
594
|
+
const TABLE_SEP = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
|
|
595
|
+
/** 懶惰續行的記號:引言或清單收進來的「沒縮排、接在段落後面」的行,在內層一律當段落續行(不能變成表頭或標題底線)。 */
|
|
596
|
+
const LAZY = '\uE002';
|
|
597
|
+
/*
|
|
598
|
+
* tab 的欄位:CommonMark 的 tab 是跳到「絕對欄位」4 的倍數。引言、清單裡的行拿掉外層記號後,行首不再是第 0 欄,
|
|
599
|
+
* 所以下面幾個函式都帶 col=這一行在原稿裡從第幾欄開始。只在判斷「縮了幾格、是什麼區塊」時換算;
|
|
600
|
+
* 程式碼內容一律從原行切出來,裡面的 tab 原樣保留(不然 Go、Makefile 的 tab 會被悄悄換成空白)。
|
|
601
|
+
*/
|
|
602
|
+
/** 行首縮排的欄數。 */
|
|
603
|
+
function indentCols(line, col = 0) {
|
|
604
|
+
let c = col;
|
|
605
|
+
for (const ch of line) {
|
|
606
|
+
if (ch === ' ')
|
|
607
|
+
c++;
|
|
608
|
+
else if (ch === '\t')
|
|
609
|
+
c += 4 - (c % 4);
|
|
610
|
+
else
|
|
611
|
+
break;
|
|
612
|
+
}
|
|
613
|
+
return c - col;
|
|
614
|
+
}
|
|
615
|
+
/** 去掉行首最多 n 欄的空白(tab 跨過界線時,剩下的欄數補成空白)。 */
|
|
616
|
+
function stripCols(line, n, col = 0) {
|
|
617
|
+
let c = col;
|
|
618
|
+
let i = 0;
|
|
619
|
+
while (i < line.length && c < col + n) {
|
|
620
|
+
if (line[i] === ' ') {
|
|
621
|
+
c++;
|
|
622
|
+
i++;
|
|
623
|
+
}
|
|
624
|
+
else if (line[i] === '\t') {
|
|
625
|
+
const w = 4 - (c % 4);
|
|
626
|
+
if (c + w > col + n)
|
|
627
|
+
return ' '.repeat(c + w - col - n) + line.slice(i + 1);
|
|
628
|
+
c += w;
|
|
629
|
+
i++;
|
|
630
|
+
}
|
|
631
|
+
else
|
|
632
|
+
break;
|
|
633
|
+
}
|
|
634
|
+
return line.slice(i);
|
|
635
|
+
}
|
|
636
|
+
/** 拿掉行首 n 欄時,拿掉的部分有沒有碰到 tab(剩下的 tab 屬於內容,不算)。 */
|
|
637
|
+
function consumedHasTab(line, n, col = 0) {
|
|
638
|
+
if (line.startsWith(LAZY))
|
|
639
|
+
line = line.slice(1);
|
|
640
|
+
let c = col;
|
|
641
|
+
for (let i = 0; i < line.length && c < col + n; i++) {
|
|
642
|
+
if (line[i] === ' ')
|
|
643
|
+
c++;
|
|
644
|
+
else if (line[i] === '\t')
|
|
645
|
+
return true;
|
|
646
|
+
else
|
|
647
|
+
break;
|
|
648
|
+
}
|
|
649
|
+
return false;
|
|
650
|
+
}
|
|
651
|
+
/** 縮排不到 4 欄(不是程式碼)的行:行首空白換成等寬的空格,給只認空格的區塊判斷用。 */
|
|
652
|
+
function normLead(line, col) {
|
|
653
|
+
if (line.startsWith(LAZY))
|
|
654
|
+
return line;
|
|
655
|
+
const lead = line.match(/^[ \t]*/)[0];
|
|
656
|
+
if (!lead.includes('\t'))
|
|
657
|
+
return line;
|
|
658
|
+
const k = indentCols(line, col);
|
|
659
|
+
return k >= 4 ? line : ' '.repeat(k) + line.slice(lead.length);
|
|
660
|
+
}
|
|
661
|
+
/** 拿掉一行引言記號 >(和它後面可省略的一格;後面是 tab 時只吃掉一欄)。qcol=引言內層的起始欄(第一行的);p=這一行自己的。 */
|
|
662
|
+
function stripQuote(line, col, qcol) {
|
|
663
|
+
const m = line.match(/^( {0,3})>/);
|
|
664
|
+
let rest = line.slice(m[0].length);
|
|
665
|
+
let p = col + m[1].length + 1;
|
|
666
|
+
if (rest[0] === ' ') {
|
|
667
|
+
rest = rest.slice(1);
|
|
668
|
+
p++;
|
|
669
|
+
}
|
|
670
|
+
else if (rest[0] === '\t') {
|
|
671
|
+
rest = ' '.repeat(3 - (p % 4)) + rest.slice(1);
|
|
672
|
+
p++;
|
|
673
|
+
}
|
|
674
|
+
// 這一行內層起點跟其他行不同(> 前面縮排不一樣)而行首還有 tab:照它自己的欄位換成空格,免得對不齊
|
|
675
|
+
if (p !== qcol && /^[ ]*\t/.test(rest)) {
|
|
676
|
+
const lead = rest.match(/^[ \t]*/)[0];
|
|
677
|
+
rest = ' '.repeat(indentCols(rest, p)) + rest.slice(lead.length);
|
|
678
|
+
}
|
|
679
|
+
// 起點不同、而結構前綴(清單記號、> 之後)裡還有 tab:欄位換算判不準,交給呼叫端記 error
|
|
680
|
+
// > 後面是 tab、換算後縮到 4 欄以上又像表格分隔列:網站的引擎會把 tab 整個吃掉照樣排表格,也判不準
|
|
681
|
+
const tabSep = line.slice(m[0].length).startsWith('\t') && indentCols(rest, p) >= 4 && TABLE_SEP.test(rest.trim()) && rest.includes('|');
|
|
682
|
+
const ambiguous = tabSep || (p !== qcol && /^(?:[ \t]*(?:>|[-*+]|\d{1,9}[.)])(?=[ \t]|$))*[ \t]*/.exec(rest)[0].includes('\t'));
|
|
683
|
+
return { rest, p, ambiguous };
|
|
684
|
+
}
|
|
685
|
+
/** 表格分隔列前面是 tab、換算後剛好縮到 4 欄以上:網站的引擎在引言裡會把 tab 吃掉照樣排表格,排法判不準,記 error。 */
|
|
686
|
+
function tabTableAmbiguous(line, next, col) {
|
|
687
|
+
if (next === undefined || line.trim() === '' || next.startsWith(LAZY) || line.startsWith(LAZY))
|
|
688
|
+
return false;
|
|
689
|
+
const lead = next.match(/^[ \t]*/)[0];
|
|
690
|
+
if (!lead.includes('\t') || indentCols(next, col) < 4)
|
|
691
|
+
return false;
|
|
692
|
+
const t = next.trim();
|
|
693
|
+
return TABLE_SEP.test(t) && t.includes('|') && splitRow(line).length === splitRow(t).length;
|
|
694
|
+
}
|
|
695
|
+
/** 程式碼框開頭:最多縮 3 格、3 個以上 ` 或 ~;反引號框的說明文字裡不能有反引號(不然那是行內程式碼)。 */
|
|
696
|
+
function fenceOpen(line) {
|
|
697
|
+
const m = line.match(/^( {0,3})(`{3,}|~{3,})(.*)$/);
|
|
698
|
+
if (!m || (m[2][0] === '`' && m[3].includes('`')))
|
|
699
|
+
return null;
|
|
700
|
+
return { indent: m[1].length, ch: m[2][0], len: m[2].length, info: m[3].trim() };
|
|
701
|
+
}
|
|
702
|
+
/** 程式碼框收尾:同一種記號、至少一樣長、最多縮 3 格、後面只能有空白。 */
|
|
703
|
+
function fenceCloses(line, f) {
|
|
704
|
+
const m = line.match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/);
|
|
705
|
+
return !!m && m[1][0] === f.ch && m[1].length >= f.len;
|
|
706
|
+
}
|
|
707
|
+
function listMarker(line, col = 0) {
|
|
708
|
+
if (HR.test(line))
|
|
709
|
+
return null;
|
|
710
|
+
const m = line.match(/^( {0,3})([-*+]|(\d{1,9})([.)]))(?=[ \t]|$)([ \t]*)(.*)$/);
|
|
711
|
+
if (!m)
|
|
712
|
+
return null;
|
|
713
|
+
const ordered = m[3] !== undefined;
|
|
714
|
+
const at = m[1].length + m[2].length;
|
|
715
|
+
let spaces = 0;
|
|
716
|
+
for (const ch of m[5])
|
|
717
|
+
spaces += ch === '\t' ? 4 - ((col + at + spaces) % 4) : 1;
|
|
718
|
+
const empty = m[6].trim() === '';
|
|
719
|
+
const base = { ordered, kind: ordered ? m[4] : m[2], start: ordered ? Number(m[3]) : 0, empty };
|
|
720
|
+
if (empty)
|
|
721
|
+
return { ...base, content: at + 1, first: '' };
|
|
722
|
+
// 記號後空 5 欄以上=內容是縮排程式碼:只拿掉一欄,剩下的空白(含 tab)原樣留給程式碼
|
|
723
|
+
if (spaces >= 5)
|
|
724
|
+
return { ...base, content: at + 1, first: stripCols(m[5] + m[6], 1, col + at) };
|
|
725
|
+
return { ...base, content: at + spaces, first: m[6] };
|
|
726
|
+
}
|
|
727
|
+
function splitRow(line) {
|
|
728
|
+
let t = line.trim();
|
|
729
|
+
if (t.startsWith('|'))
|
|
730
|
+
t = t.slice(1);
|
|
731
|
+
if (t.endsWith('|') && !t.endsWith('\\|'))
|
|
732
|
+
t = t.slice(0, -1);
|
|
733
|
+
const cells = [];
|
|
734
|
+
let cur = '';
|
|
735
|
+
for (let i = 0; i < t.length; i++) {
|
|
736
|
+
if (t[i] === '\\' && t[i + 1] === '|') {
|
|
737
|
+
cur += '|';
|
|
738
|
+
i++;
|
|
739
|
+
}
|
|
740
|
+
else if (t[i] === '|') {
|
|
741
|
+
cells.push(cur.trim());
|
|
742
|
+
cur = '';
|
|
743
|
+
}
|
|
744
|
+
else
|
|
745
|
+
cur += t[i];
|
|
746
|
+
}
|
|
747
|
+
cells.push(cur.trim());
|
|
748
|
+
return cells;
|
|
749
|
+
}
|
|
750
|
+
/** 表格開頭:這一行+下一行是分隔列(要有 |、格數相同)。兩行都不能縮 4 欄以上,也不能本身是清單項目、標題、引言(那些先成立)。 */
|
|
751
|
+
function isTableStart(line, next, col = 0) {
|
|
752
|
+
if (next === undefined || line.trim() === '' || next.startsWith(LAZY))
|
|
753
|
+
return false;
|
|
754
|
+
line = normLead(line, col);
|
|
755
|
+
next = normLead(next, col);
|
|
756
|
+
if (indentCols(line) >= 4 || indentCols(next) >= 4)
|
|
757
|
+
return false;
|
|
758
|
+
if (listMarker(line, col) || listMarker(next, col) || ATX.test(line) || QUOTE.test(line) || QUOTE.test(next) || fenceOpen(line))
|
|
759
|
+
return false;
|
|
760
|
+
return TABLE_SEP.test(next) && next.includes('|') && splitRow(line).length === splitRow(next).length;
|
|
761
|
+
}
|
|
762
|
+
/** 這一行能不能打斷同一層正在進行的段落(CommonMark 的規則:有序清單要從 1 開始、空項目不行、縮 4 格以上不行)。 */
|
|
763
|
+
function interrupts(line, next, tables = true, col = 0) {
|
|
764
|
+
if (indentCols(line, col) >= 4)
|
|
765
|
+
return false;
|
|
766
|
+
line = normLead(line, col);
|
|
767
|
+
if (fenceOpen(line) || HR.test(line) || ATX.test(line) || QUOTE.test(line) || COMMENT_START.test(line) || HTML_INTERRUPT.test(line))
|
|
768
|
+
return true;
|
|
769
|
+
const lm = listMarker(line, col);
|
|
770
|
+
if (lm && !lm.empty && (!lm.ordered || lm.start === 1))
|
|
771
|
+
return true;
|
|
772
|
+
return tables && isTableStart(line, next, col);
|
|
773
|
+
}
|
|
774
|
+
/** 懶惰續行(引言、清單裡沒縮排的下一行):只有「內層最後是一個還開著的段落」才接得上;任何清單項目、區塊開頭都會斷開(表格不會:那時表頭只是段落續行)。 */
|
|
775
|
+
function lazyBreaks(line, col = 0) {
|
|
776
|
+
if (indentCols(line, col) >= 4)
|
|
777
|
+
return false;
|
|
778
|
+
line = normLead(line, col);
|
|
779
|
+
return !!fenceOpen(line) || HR.test(line) || ATX.test(line) || QUOTE.test(line) || COMMENT_START.test(line) || HTML_INTERRUPT.test(line) || LONE_TAG.test(line) || listMarker(line, col) !== null;
|
|
780
|
+
}
|
|
781
|
+
/** 註解區塊收尾那一行,--> 後面剩下的字(網站上原樣當 HTML 顯示):再藏掉裡面的註解,其他照字面留著。 */
|
|
782
|
+
function rawTail(rest, ctx) {
|
|
783
|
+
let out = '';
|
|
784
|
+
let pos = 0;
|
|
785
|
+
while (pos < rest.length) {
|
|
786
|
+
const c = rest.indexOf('<!--', pos);
|
|
787
|
+
if (c < 0) {
|
|
788
|
+
out += rest.slice(pos);
|
|
789
|
+
break;
|
|
790
|
+
}
|
|
791
|
+
out += rest.slice(pos, c);
|
|
792
|
+
const e = commentEnd(rest, c);
|
|
793
|
+
if (e < 0) {
|
|
794
|
+
ctx.problems.push(unclosedComment(rest.slice(c)));
|
|
795
|
+
out += rest.slice(c);
|
|
796
|
+
break;
|
|
797
|
+
}
|
|
798
|
+
hideComment(rest.slice(c, e), ctx);
|
|
799
|
+
pos = e;
|
|
800
|
+
}
|
|
801
|
+
if (PSEUDO_COMMENT.test(out))
|
|
802
|
+
ctx.problems.push({ code: 'unsupported_html', severity: 'error', ...tagProblem(out.match(PSEUDO_COMMENT)[0], false) });
|
|
803
|
+
const tag = out.match(/<\/?[a-zA-Z][^>]*>/) ?? out.match(/<[A-Za-z/!?][^\s>]*/); // 沒收尾的 <字母 也算:瀏覽器會把後面整段吞成標籤
|
|
804
|
+
if (tag)
|
|
805
|
+
ctx.problems.push({ code: 'unsupported_html', severity: 'error', ...tagProblem(tag[0], false) });
|
|
806
|
+
const v = decodeEntities(out.trim());
|
|
807
|
+
return v ? { t: 'p', c: [{ t: 'text', v }] } : null;
|
|
808
|
+
}
|
|
809
|
+
/** 腳註定義(合格的單行寫法、任何寫法、內容是區塊寫法)。 */
|
|
810
|
+
const FN_DEF = /^\[\^([^\]\s\\]+)\]:/;
|
|
811
|
+
const FN_DEF_ANY = /^ {0,3}\[\^[^\]]*\]:/;
|
|
812
|
+
const FN_DEF_BLOCK = /^(?:\s{4,}\S|\s*<|\s*\[[^\]]*\]:|\s*(?:>|[-*+](?:\s|$)|\d{1,9}[.)](?:\s|$)|`{3,}|~{3,}|#{1,6}(?:\s|$)|\|))/;
|
|
813
|
+
/** 段落:從 lines[start] 收到空行或能打斷段落的行為止;下一行是 === 或 --- =標題(setext)。回傳下一個要看的行。 */
|
|
814
|
+
function paragraph(lines, start, ctx, blocks, col) {
|
|
815
|
+
const n = lines.length;
|
|
816
|
+
const unlazy = (l) => (l.startsWith(LAZY) ? l.slice(1) : l);
|
|
817
|
+
const para = [unlazy(lines[start])];
|
|
818
|
+
const raw = [lines[start]];
|
|
819
|
+
let i = start + 1;
|
|
820
|
+
let setext = 0;
|
|
821
|
+
let tabTable = false;
|
|
822
|
+
while (i < n) {
|
|
823
|
+
const l = lines[i];
|
|
824
|
+
if (l.trim() === '')
|
|
825
|
+
break;
|
|
826
|
+
if (tabLead(l))
|
|
827
|
+
noteTab(ctx, l);
|
|
828
|
+
if (tabTableAmbiguous(lines[i - 1], l, col))
|
|
829
|
+
tabTable = true;
|
|
830
|
+
if (!l.startsWith(LAZY)) {
|
|
831
|
+
const sx = indentCols(l, col) < 4 ? normLead(l, col).match(SETEXT) : null;
|
|
832
|
+
if (sx) {
|
|
833
|
+
setext = sx[1][0] === '=' ? 1 : 2;
|
|
834
|
+
i++;
|
|
835
|
+
break;
|
|
836
|
+
}
|
|
837
|
+
if (interrupts(l, lines[i + 1], true, col) || (BLOCK_HTML.test(normLead(l, col)) && EMBED_TAG.test(l)))
|
|
838
|
+
break;
|
|
839
|
+
}
|
|
840
|
+
para.push(unlazy(l));
|
|
841
|
+
raw.push(l);
|
|
842
|
+
i++;
|
|
843
|
+
}
|
|
844
|
+
if (tabTable)
|
|
845
|
+
ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '表格分隔列前面用 tab 縮排,網站上的排法判不準;請改用空格或不縮排', where: clip(para[0]) });
|
|
846
|
+
// 腳註定義:只有「最外層、從第 0 欄寫起、整段每一行都是單行定義、內容不是區塊寫法、不是標題」判得準
|
|
847
|
+
const isDef = (l) => FN_DEF.test(l) && !FN_DEF_BLOCK.test(l.replace(FN_DEF, ''));
|
|
848
|
+
const defLike = para.some((l) => FN_DEF_ANY.test(l));
|
|
849
|
+
let def = false;
|
|
850
|
+
if (defLike) {
|
|
851
|
+
// 後面要接空行或文末:被別的區塊(表格、清單…)打斷時,網站會把那個區塊也收進腳註
|
|
852
|
+
if (col === 0 && !setext && (i >= n || lines[i].trim() === '') && raw.every((l) => !l.startsWith(LAZY) && isDef(l))) {
|
|
853
|
+
def = true;
|
|
854
|
+
for (const l of raw)
|
|
855
|
+
ctx.defs.push(fnLabel(l.match(FN_DEF)[1]));
|
|
856
|
+
}
|
|
857
|
+
else
|
|
858
|
+
ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '腳註定義要從行首寫起、前面空一行、一則一行(不能縮排、不能放在引言或清單裡、不能接在段落後面或變成標題,內容不能是清單、引言、程式碼);不然網站上的顯示判不準', where: clip(para.find((l) => FN_DEF_ANY.test(l))) });
|
|
859
|
+
}
|
|
860
|
+
ctx.inDef = def;
|
|
861
|
+
// 連續的腳註定義在網站上是各自獨立的一則:一行一行分開轉(行內程式碼不能跨到下一則)
|
|
862
|
+
const inline = def ? para.flatMap((l, k) => [...(k ? [{ t: 'br' }] : []), ...parseInline(l.trim(), ctx)]) : parseInline(para.join('\n').trim(), ctx);
|
|
863
|
+
ctx.inDef = false;
|
|
864
|
+
if (def)
|
|
865
|
+
ctx.lastDefEnd = i;
|
|
866
|
+
if (setext)
|
|
867
|
+
blocks.push({ t: 'h', level: setext, c: inline });
|
|
868
|
+
// 整段只有一張圖(或一個包著圖的連結)=圖片區塊
|
|
869
|
+
else if (inline.length === 1 && inline[0].t === 'image')
|
|
870
|
+
blocks.push({ t: 'image', src: inline[0].src, alt: inline[0].alt });
|
|
871
|
+
else if (inline.length === 1 && inline[0].t === 'link' && inline[0].c.length === 1 && inline[0].c[0].t === 'image') {
|
|
872
|
+
const img = inline[0].c[0];
|
|
873
|
+
blocks.push({ t: 'image', src: img.src, alt: img.alt, link: inline[0] });
|
|
874
|
+
}
|
|
875
|
+
else
|
|
876
|
+
blocks.push({ t: 'p', c: inline });
|
|
877
|
+
return i;
|
|
878
|
+
}
|
|
879
|
+
/** 把一個容器(整份原稿、引言內層、清單項目)的行切成區塊。open=最後一個區塊是還開著的段落(給懶惰續行判斷)。 */
|
|
880
|
+
/**
|
|
881
|
+
* restrictFirst=第一行是「打斷段落的那一行」開出來的內層(例:段落下一行的「- 2. …」):
|
|
882
|
+
* 網站的規則是打斷段落時,不是從 1 開始的有序清單、空的清單項目都不成立,這個限制要一路帶進同一行開的內層容器。
|
|
883
|
+
*/
|
|
884
|
+
function parseBlocks(lines, ctx, col = 0, restrictFirst = false) {
|
|
885
|
+
const blocks = [];
|
|
886
|
+
const n = lines.length;
|
|
887
|
+
let open = false;
|
|
888
|
+
// 沒收尾的註解區塊:CommonMark 裡它一路延伸到容器結尾,所以容器最後不是「開著的段落」,懶惰續行接不上
|
|
889
|
+
let unclosedHtml = false;
|
|
890
|
+
// 上一個區塊是縮排程式碼:網站的引擎在它後面不認「不是從 1 開始的有序清單」,當成段落(照網站做)
|
|
891
|
+
let afterIndentedCode = false;
|
|
892
|
+
// 上一個段落結束在哪一行(那一行若開了清單或引言=打斷段落)
|
|
893
|
+
let paraEnd = -1;
|
|
894
|
+
let i = 0;
|
|
895
|
+
while (i < n) {
|
|
896
|
+
const line = normLead(lines[i], col);
|
|
897
|
+
open = false;
|
|
898
|
+
if (line.trim() === '') {
|
|
899
|
+
i++;
|
|
900
|
+
continue;
|
|
901
|
+
}
|
|
902
|
+
const prevIndentedCode = afterIndentedCode;
|
|
903
|
+
afterIndentedCode = false;
|
|
904
|
+
// 行首結構用 tab:縮排程式碼只看拿掉的那 4 欄,其他行看整段行首空白
|
|
905
|
+
if (indentCols(lines[i], col) >= 4 ? consumedHasTab(lines[i], 4, col) : tabLead(lines[i]))
|
|
906
|
+
noteTab(ctx, lines[i]);
|
|
907
|
+
// 腳註定義後面空行、再接縮 4 欄的行:網站上那是腳註的續段(多段腳註),判不準
|
|
908
|
+
if (col === 0 && ctx.lastDefEnd >= 0 && i > ctx.lastDefEnd && lines.slice(ctx.lastDefEnd, i).every((l) => l.trim() === '') && indentCols(lines[i]) >= 1) {
|
|
909
|
+
ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '腳註定義後面接了縮排的行(可能是多段腳註),網站上的顯示判不準;請把腳註寫成一則一行、後面的段落不要縮排', where: clip(lines[i]) });
|
|
910
|
+
}
|
|
911
|
+
if (line.startsWith(LAZY)) {
|
|
912
|
+
i = paragraph(lines, i, ctx, blocks, col);
|
|
913
|
+
if (blocks[blocks.length - 1]?.t === 'p')
|
|
914
|
+
paraEnd = i;
|
|
915
|
+
open = i >= n;
|
|
916
|
+
continue;
|
|
917
|
+
}
|
|
918
|
+
const interrupting = i === paraEnd || (restrictFirst && i === 0);
|
|
919
|
+
// 縮排 4 格以上=程式碼(段落中間的縮排行不算,那是段落續行)
|
|
920
|
+
if (indentCols(lines[i], col) >= 4) {
|
|
921
|
+
const body = [];
|
|
922
|
+
while (i < n && (lines[i].trim() === '' || indentCols(lines[i], col) >= 4)) {
|
|
923
|
+
if (consumedHasTab(lines[i], 4, col))
|
|
924
|
+
noteTab(ctx, lines[i]);
|
|
925
|
+
body.push(stripCols(lines[i++], 4, col));
|
|
926
|
+
}
|
|
927
|
+
while (body.length && body[body.length - 1].trim() === '')
|
|
928
|
+
body.pop();
|
|
929
|
+
const v = body.join('\n');
|
|
930
|
+
ctx.inCode += marks(v);
|
|
931
|
+
blocks.push({ t: 'code', v: protectBraces(v) });
|
|
932
|
+
afterIndentedCode = true;
|
|
933
|
+
continue;
|
|
934
|
+
}
|
|
935
|
+
// 圍欄程式碼
|
|
936
|
+
const fence = fenceOpen(line);
|
|
937
|
+
if (fence) {
|
|
938
|
+
const body = [];
|
|
939
|
+
i++;
|
|
940
|
+
let closed = false;
|
|
941
|
+
while (i < n) {
|
|
942
|
+
if (fenceCloses(normLead(lines[i], col), fence)) {
|
|
943
|
+
closed = true;
|
|
944
|
+
i++;
|
|
945
|
+
break;
|
|
946
|
+
}
|
|
947
|
+
body.push(stripCols(lines[i++], fence.indent, col));
|
|
948
|
+
}
|
|
949
|
+
// 沒收尾的程式碼框:網站上它會把後面整段都變成程式碼,所以記 error
|
|
950
|
+
if (!closed)
|
|
951
|
+
ctx.problems.push({ code: 'unclosed_fence', severity: 'error', message: '程式碼框(```)沒有收尾,後面的內容會被吃掉', where: clip(line) });
|
|
952
|
+
const v = body.join('\n');
|
|
953
|
+
ctx.inCode += marks(v);
|
|
954
|
+
// 圖表(mermaid)信裡畫不出來:換成「到網站看」連結卡
|
|
955
|
+
if (fence.info.split(/\s+/)[0].toLowerCase() === 'mermaid')
|
|
956
|
+
blocks.push({ t: 'embed' });
|
|
957
|
+
else
|
|
958
|
+
blocks.push({ t: 'code', v: protectBraces(v) });
|
|
959
|
+
continue;
|
|
960
|
+
}
|
|
961
|
+
if (HR.test(line)) {
|
|
962
|
+
blocks.push({ t: 'hr' });
|
|
963
|
+
i++;
|
|
964
|
+
continue;
|
|
965
|
+
}
|
|
966
|
+
const h = line.match(ATX);
|
|
967
|
+
if (h) {
|
|
968
|
+
blocks.push({ t: 'h', level: h[1].length, c: parseInline(h[2] ?? '', ctx) });
|
|
969
|
+
i++;
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
// HTML 註解區塊:到含 --> 的那一行為止整段藏起來(中間的空行也算在內)
|
|
973
|
+
if (COMMENT_START.test(line)) {
|
|
974
|
+
const col = line.indexOf('<!--');
|
|
975
|
+
let j = i;
|
|
976
|
+
let close = line.indexOf('-->', col + 2);
|
|
977
|
+
while (close < 0 && j + 1 < n)
|
|
978
|
+
close = lines[++j].indexOf('-->');
|
|
979
|
+
if (close < 0) {
|
|
980
|
+
// 沒收尾:只拿掉開頭這一行,後面照常轉(內容不能被吃掉),並記 error 擋下
|
|
981
|
+
ctx.problems.push(unclosedComment(line));
|
|
982
|
+
unclosedHtml = true;
|
|
983
|
+
i++;
|
|
984
|
+
continue;
|
|
985
|
+
}
|
|
986
|
+
const text = j === i ? line.slice(col, close + 3) : [line.slice(col), ...lines.slice(i + 1, j), lines[j].slice(0, close + 3)].join('\n');
|
|
987
|
+
hideComment(text, ctx);
|
|
988
|
+
const tail = rawTail((j === i ? line : lines[j]).slice(close + 3), ctx); // 同一行收尾時用換算過 tab 的那一行,位置才對得上
|
|
989
|
+
if (tail)
|
|
990
|
+
blocks.push(tail);
|
|
991
|
+
i = j + 1;
|
|
992
|
+
continue;
|
|
993
|
+
}
|
|
994
|
+
// 只有 <div> 、<div lang="…"> 或 </div> 的行(語言標記的外框;帶 hidden/style 等其他屬性的 div 不收),而且下一行是空行:
|
|
995
|
+
// 外框丟掉,裡面的內容照常轉。下一行不是空行時,網站會把接著的幾行當原始 HTML(不轉 markdown),所以走下面的 HTML 區塊。
|
|
996
|
+
if (DIV_WRAPPER.test(line) && (i + 1 >= n || lines[i + 1].trim() === '')) {
|
|
997
|
+
i++;
|
|
998
|
+
continue;
|
|
999
|
+
}
|
|
1000
|
+
if (LINK_REF_DEF.test(line)) {
|
|
1001
|
+
const start = line;
|
|
1002
|
+
while (i < n && lines[i].trim() !== '')
|
|
1003
|
+
ctx.hidden += marks(lines[i++]);
|
|
1004
|
+
ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '原稿有參照式連結定義([名稱]: 網址),網站上不顯示、信裡不支援;請改成一般的 [文字](網址)', where: clip(start) });
|
|
1005
|
+
continue;
|
|
1006
|
+
}
|
|
1007
|
+
// 自訂區塊語法(:::note 之類)
|
|
1008
|
+
if (line.trim().startsWith(':::')) {
|
|
1009
|
+
const start = line;
|
|
1010
|
+
while (i < n && lines[i].trim() !== '')
|
|
1011
|
+
ctx.hidden += marks(lines[i++]);
|
|
1012
|
+
ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '原稿有信件轉不了的區塊語法', where: clip(start) });
|
|
1013
|
+
continue;
|
|
1014
|
+
}
|
|
1015
|
+
// 區塊 HTML
|
|
1016
|
+
if ((BLOCK_HTML.test(line) && ANY_TAG.test(line) && !INLINE_START.test(line)) || LONE_TAG.test(line) || /^ {0,3}<(?:\?|![A-Za-z]|!\[CDATA\[)/.test(line)) {
|
|
1017
|
+
const start = line;
|
|
1018
|
+
while (i < n && lines[i].trim() !== '')
|
|
1019
|
+
ctx.hidden += marks(lines[i++]);
|
|
1020
|
+
if (EMBED_TAG.test(start)) {
|
|
1021
|
+
blocks.push({ t: 'embed' });
|
|
1022
|
+
}
|
|
1023
|
+
else {
|
|
1024
|
+
ctx.problems.push({ code: 'unsupported_html', severity: 'error', ...tagProblem(start.trim().match(/^<\/?[a-zA-Z!][^>]*>?/)?.[0] ?? start, false) });
|
|
1025
|
+
}
|
|
1026
|
+
continue;
|
|
1027
|
+
}
|
|
1028
|
+
if (QUOTE.test(line)) {
|
|
1029
|
+
const inner = [];
|
|
1030
|
+
const qcol = stripQuote(line, col, -1).p;
|
|
1031
|
+
let ambiguous = false;
|
|
1032
|
+
while (i < n) {
|
|
1033
|
+
const l = normLead(lines[i], col);
|
|
1034
|
+
if (QUOTE.test(l)) {
|
|
1035
|
+
if (tabLead(lines[i]) || /^ {0,3}>\t/.test(l))
|
|
1036
|
+
noteTab(ctx, lines[i]);
|
|
1037
|
+
const q = stripQuote(l, col, qcol);
|
|
1038
|
+
if (q.rest.trim() === '' && l.includes('\t'))
|
|
1039
|
+
noteTab(ctx, lines[i]); // 只有空白的引言行裡有 tab
|
|
1040
|
+
if (q.ambiguous)
|
|
1041
|
+
ambiguous = true;
|
|
1042
|
+
inner.push(q.rest);
|
|
1043
|
+
i++;
|
|
1044
|
+
continue;
|
|
1045
|
+
}
|
|
1046
|
+
if (l.trim() !== '' && inner.length > 0 && !lazyBreaks(l, col) && parseBlocks(inner, scratch(), qcol, interrupting).open) {
|
|
1047
|
+
if (tabLead(lines[i]))
|
|
1048
|
+
noteTab(ctx, lines[i]);
|
|
1049
|
+
inner.push(l.startsWith(LAZY) ? l : LAZY + l);
|
|
1050
|
+
i++;
|
|
1051
|
+
continue;
|
|
1052
|
+
}
|
|
1053
|
+
break;
|
|
1054
|
+
}
|
|
1055
|
+
if (ambiguous)
|
|
1056
|
+
ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '引言裡 > 後面用 tab 縮排(或有的接空格、有的沒有),網站上的排法判不準;請統一寫成「> 」並改用空格', where: clip(line) });
|
|
1057
|
+
const r = parseBlocks(inner, ctx, qcol, interrupting);
|
|
1058
|
+
blocks.push({ t: 'quote', c: r.blocks });
|
|
1059
|
+
open = r.open && i >= n;
|
|
1060
|
+
continue;
|
|
1061
|
+
}
|
|
1062
|
+
if (isTableStart(line, lines[i + 1], col)) {
|
|
1063
|
+
const head = splitRow(line);
|
|
1064
|
+
const align = splitRow(lines[i + 1]).map((c) => (/^:-+:$/.test(c) ? 'center' : /^-+:$/.test(c) ? 'right' : /^:-+$/.test(c) ? 'left' : null));
|
|
1065
|
+
i += 2;
|
|
1066
|
+
const rows = [];
|
|
1067
|
+
// 表格不是段落:任何清單項目(不從 1 開始、空項目也算)都會結束表格
|
|
1068
|
+
while (i < n && lines[i].trim() !== '' && indentCols(lines[i], col) < 4 && !lines[i].startsWith(LAZY) && !interrupts(lines[i], lines[i + 1], false, col) && !listMarker(normLead(lines[i], col), col)) {
|
|
1069
|
+
if (tabLead(lines[i]))
|
|
1070
|
+
noteTab(ctx, lines[i]);
|
|
1071
|
+
if (FN_DEF_ANY.test(normLead(lines[i], col)))
|
|
1072
|
+
ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message: '表格裡有腳註定義,網站上的顯示判不準', where: clip(lines[i]) });
|
|
1073
|
+
const cells = splitRow(lines[i++]);
|
|
1074
|
+
while (cells.length < head.length)
|
|
1075
|
+
cells.push('');
|
|
1076
|
+
for (const extra of cells.slice(head.length))
|
|
1077
|
+
ctx.hidden += marks(extra); // 多出來的格子網站上也不顯示(表格裡再出現像表頭的兩行,也只是一般的列)
|
|
1078
|
+
rows.push(cells.slice(0, head.length).map((c) => parseInline(c, ctx)));
|
|
1079
|
+
}
|
|
1080
|
+
blocks.push({ t: 'table', head: head.map((c) => parseInline(c, ctx)), align, rows });
|
|
1081
|
+
continue;
|
|
1082
|
+
}
|
|
1083
|
+
const lm = listMarker(line, col);
|
|
1084
|
+
const restricted = prevIndentedCode || interrupting;
|
|
1085
|
+
const first = lm && !(restricted && ((lm.ordered && lm.start !== 1) || lm.empty)) ? lm : null;
|
|
1086
|
+
if (first) {
|
|
1087
|
+
const items = [];
|
|
1088
|
+
let cur = first;
|
|
1089
|
+
while (true) {
|
|
1090
|
+
// 清單記號後面用 tab
|
|
1091
|
+
if (/^ {0,3}(?:[-*+]|\d{1,9}[.)])[ ]*\t/.test(normLead(lines[i], col)))
|
|
1092
|
+
noteTab(ctx, lines[i]);
|
|
1093
|
+
const itemLines = [cur.first];
|
|
1094
|
+
i++;
|
|
1095
|
+
while (i < n) {
|
|
1096
|
+
const l = lines[i];
|
|
1097
|
+
if (l.trim() === '') {
|
|
1098
|
+
// 空行之後若還有縮排到項目內容的行,屬於本項(項目最多只能以一個空行開頭)
|
|
1099
|
+
let j = i;
|
|
1100
|
+
while (j < n && lines[j].trim() === '')
|
|
1101
|
+
j++;
|
|
1102
|
+
const startsBlank = itemLines.length === 1 && itemLines[0] === '';
|
|
1103
|
+
if (j < n && indentCols(lines[j], col) >= cur.content && !startsBlank) {
|
|
1104
|
+
for (; i < j; i++)
|
|
1105
|
+
itemLines.push('');
|
|
1106
|
+
continue;
|
|
1107
|
+
}
|
|
1108
|
+
break;
|
|
1109
|
+
}
|
|
1110
|
+
if (indentCols(l, col) >= cur.content) {
|
|
1111
|
+
if (consumedHasTab(l, cur.content, col))
|
|
1112
|
+
noteTab(ctx, l);
|
|
1113
|
+
itemLines.push(stripCols(l, cur.content, col));
|
|
1114
|
+
i++;
|
|
1115
|
+
continue;
|
|
1116
|
+
}
|
|
1117
|
+
if (!lazyBreaks(l, col) && parseBlocks(itemLines, scratch(), col + cur.content, interrupting && items.length === 0).open) {
|
|
1118
|
+
if (tabLead(l))
|
|
1119
|
+
noteTab(ctx, l);
|
|
1120
|
+
itemLines.push(l.startsWith(LAZY) ? l : LAZY + l); // 懶惰續行
|
|
1121
|
+
i++;
|
|
1122
|
+
continue;
|
|
1123
|
+
}
|
|
1124
|
+
break;
|
|
1125
|
+
}
|
|
1126
|
+
const r = parseBlocks(itemLines, ctx, col + cur.content, interrupting && items.length === 0);
|
|
1127
|
+
items.push(r.blocks);
|
|
1128
|
+
open = r.open && i >= n;
|
|
1129
|
+
// 下一個同類的清單記號=同一張清單的下一項(中間可以有空行)
|
|
1130
|
+
let j = i;
|
|
1131
|
+
while (j < n && lines[j].trim() === '')
|
|
1132
|
+
j++;
|
|
1133
|
+
const next = j < n ? listMarker(normLead(lines[j], col), col) : null;
|
|
1134
|
+
if (next && next.ordered === first.ordered && next.kind === first.kind) {
|
|
1135
|
+
i = j;
|
|
1136
|
+
cur = next;
|
|
1137
|
+
open = false;
|
|
1138
|
+
continue;
|
|
1139
|
+
}
|
|
1140
|
+
break;
|
|
1141
|
+
}
|
|
1142
|
+
blocks.push(first.ordered && first.start !== 1 ? { t: 'list', ordered: true, start: first.start, items } : { t: 'list', ordered: first.ordered, items });
|
|
1143
|
+
continue;
|
|
1144
|
+
}
|
|
1145
|
+
// 段落
|
|
1146
|
+
i = paragraph(lines, i, ctx, blocks, col);
|
|
1147
|
+
if (blocks[blocks.length - 1]?.t === 'p')
|
|
1148
|
+
paraEnd = i;
|
|
1149
|
+
open = i >= n && blocks[blocks.length - 1]?.t !== 'h';
|
|
1150
|
+
}
|
|
1151
|
+
return { blocks, open: open && !unclosedHtml };
|
|
1152
|
+
}
|
|
1153
|
+
/** 最後的總檢查:行首結構用 tab、腳註定義有沒有被引用與重複。 */
|
|
1154
|
+
function finalChecks(ctx, blocks) {
|
|
1155
|
+
const fail = (message, where) => ctx.problems.push({ code: 'unsupported_syntax', severity: 'error', message, where: clip(where) });
|
|
1156
|
+
// 連結被拆壞的跡象:「](」後面直接接一個裸網址(例:*[**c**](https://…)字*,強調先切開了連結)。網站上那是連結,信裡變成吞掉後面字的裸網址
|
|
1157
|
+
let broken = '';
|
|
1158
|
+
const walk = (x) => {
|
|
1159
|
+
if (broken || !x || typeof x !== 'object')
|
|
1160
|
+
return;
|
|
1161
|
+
if (Array.isArray(x)) {
|
|
1162
|
+
x.forEach((n, k) => {
|
|
1163
|
+
const prev = x[k - 1];
|
|
1164
|
+
if (n && n.t === 'link' && n.bare && prev?.t === 'text' && prev.v.endsWith(']('))
|
|
1165
|
+
broken = n.href;
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
for (const v of Object.values(x))
|
|
1169
|
+
if (v && typeof v === 'object')
|
|
1170
|
+
walk(v);
|
|
1171
|
+
};
|
|
1172
|
+
walk(blocks);
|
|
1173
|
+
if (broken)
|
|
1174
|
+
fail('強調和連結的組合(例:*[**文字**](網址)字*)信裡排不出來,連結會被拆開;請把強調移到連結文字裡面或外面加空格', broken);
|
|
1175
|
+
if (ctx.tab)
|
|
1176
|
+
fail('行首的縮排、引言 > 或清單記號後面用了 tab,網站上的排法判不準;請改用空格(程式碼框裡的 tab 不受影響)', ctx.tab);
|
|
1177
|
+
const seen = new Set();
|
|
1178
|
+
for (const label of ctx.defs) {
|
|
1179
|
+
if (seen.has(label))
|
|
1180
|
+
fail(`腳註 [^${label}] 定義了兩次,網站只顯示第一個;請刪掉重複的`, `[^${label}]:`);
|
|
1181
|
+
seen.add(label);
|
|
1182
|
+
if (!ctx.refs.has(label))
|
|
1183
|
+
fail(`腳註 [^${label}] 有定義但正文沒引用,網站上不顯示;請刪掉或在正文引用它`, `[^${label}]:`);
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
export function parseMarkdown(source) {
|
|
1187
|
+
const { body, fm } = splitFrontmatter(source);
|
|
1188
|
+
const ctx = newCtx();
|
|
1189
|
+
const { blocks } = parseBlocks(body.split('\n'), ctx);
|
|
1190
|
+
finalChecks(ctx, blocks);
|
|
1191
|
+
// 對帳:原文每一個 <!--,不是被當成註解藏起來,就是落在程式碼裡;對不上=有一個註解符號跑進了正文(或內容不見了),擋下。
|
|
1192
|
+
const total = marks(body);
|
|
1193
|
+
if (total !== ctx.hidden + ctx.inCode && !ctx.problems.some((p) => p.code === 'unclosed_comment')) {
|
|
1194
|
+
ctx.problems.push({ code: 'comment_leaked', severity: 'error', message: `原稿有 ${total} 個 <!--,其中 ${ctx.hidden} 個當註解藏起來、${ctx.inCode} 個在程式碼裡,剩下的會以文字出現在信裡(例如反斜線跳脫的 \\<!--、圖片替代文字或網址裡的 <!--);請改寫或用反引號包起來`, where: clip(body.slice(Math.max(0, body.indexOf('<!--') - 10))) });
|
|
1195
|
+
}
|
|
1196
|
+
return { blocks, problems: ctx.problems, frontmatter: fm };
|
|
1197
|
+
}
|