@kangyishuai/dsh-btw 0.2.0 → 0.4.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.
@@ -0,0 +1,695 @@
1
+ // @ts-check
2
+ // 轻量 Markdown → JSON 树(块 + 行内),供 client 用 React 元素渲染。
3
+ //
4
+ // 为什么不引依赖 / 不生成 HTML:
5
+ // - 仓库约定不引入构建器(ADR 0001),client 半是 classic script;
6
+ // - 生成 HTML 再塞 innerHTML 会把模型输出当代码执行;输出纯数据、client 只建
7
+ // React 元素,文本永远是文本节点,天然转义。
8
+ // - DSH 明确不允许插件加载宿主 UI 包(`dsh-client-ui-primitives` 等),所以
9
+ // 渲染器只能自己写;解析放在 host 半,既好单测,client 又只做薄映射。
10
+ //
11
+ // 支持:ATX 标题、段落、围栏代码(含未闭合的流式态)、有序/无序列表(单层)、
12
+ // 引用(可嵌套到 3 层)、表格、分隔线;行内:代码、粗体、斜体、删除线、链接、裸 URL。
13
+ // 刻意不支持:HTML 内嵌、图片、脚注、嵌套列表(旁问答案里极少出现,手写风险高)。
14
+ //
15
+ // 输出形状(JSON 可序列化,跨 RPC 传):
16
+ // block: {type:'paragraph',inlines} | {type:'heading',level,inlines}
17
+ // | {type:'code',lang,code,streaming?,marker?} | {type:'list',ordered,start,items}
18
+ // | {type:'quote',blocks} | {type:'table',align,header,rows} | {type:'hr'}
19
+ // inline: {type:'text',text} | {type:'code',text}
20
+ // | {type:'strong'|'em'|'del',children} | {type:'link',href,children}
21
+
22
+ const MAX_INLINE_DEPTH = 8;
23
+ const MAX_QUOTE_DEPTH = 3;
24
+ /** 反斜杠可转义的 ASCII 标点(CommonMark 的一个子集)。 */
25
+ const ESCAPABLE = new Set("\\`*_{}[]()#+-.!~|<>".split(""));
26
+ /** 裸 URL 截止字符:空白、尖括号、圆括号,以及中日韩标点/全角字符。 */
27
+ const URL_STOP = /[\s<>()\u3000-\u303f\uff00-\uffef]/u;
28
+
29
+ /**
30
+ * 把任意输入整理成统一换行的字符串。
31
+ * @param {unknown} value
32
+ * @returns {string}
33
+ */
34
+ function normalize(value) {
35
+ return String(value ?? "")
36
+ .replace(/\r\n?/gu, "\n")
37
+ .replace(/\t/gu, " ");
38
+ }
39
+
40
+ /**
41
+ * 解析 Markdown。
42
+ * @param {unknown} value
43
+ * @returns {{ blocks: any[] }}
44
+ */
45
+ export function parseMarkdown(value) {
46
+ return { blocks: parseBlocks(normalize(value), 0) };
47
+ }
48
+
49
+ /**
50
+ * 解析行内 Markdown(供测试与列表/表格单元格复用)。
51
+ * @param {unknown} value
52
+ * @returns {any[]}
53
+ */
54
+ export function parseInline(value) {
55
+ return parseInlineRuns(normalize(value).replace(/\n/gu, " "), 0);
56
+ }
57
+
58
+ /**
59
+ * 把一段行内树拍平成纯文本(测试与兜底展示用)。
60
+ * @param {any[]} runs
61
+ * @returns {string}
62
+ */
63
+ export function inlineText(runs) {
64
+ let out = "";
65
+ for (const run of Array.isArray(runs) ? runs : []) {
66
+ if (run?.type === "text" || run?.type === "code") out += String(run.text ?? "");
67
+ else if (Array.isArray(run?.children)) out += inlineText(run.children);
68
+ }
69
+ return out;
70
+ }
71
+
72
+ /**
73
+ * 若文本以未闭合的代码围栏结尾,补上闭合标记(转正草稿截断时用,避免输入框里
74
+ * 留一段永远开着的代码块)。
75
+ * @param {unknown} value
76
+ * @returns {string}
77
+ */
78
+ export function closeOpenFences(value) {
79
+ const text = String(value ?? "");
80
+ const { blocks } = parseMarkdown(text);
81
+ const last = blocks[blocks.length - 1];
82
+ if (last?.type !== "code" || last.streaming !== true) return text;
83
+ const marker = typeof last.marker === "string" && last.marker !== "" ? last.marker : "```";
84
+ return `${text.replace(/\s+$/u, "")}\n${marker}`;
85
+ }
86
+
87
+ /**
88
+ * 在预算内截断 Markdown:尽量不在代码围栏中间截断。
89
+ *
90
+ * 截断点若落在未闭合围栏内,先尝试补上闭合标记;补完超过预算就退回到围栏开头,
91
+ * 避免输入框里留半段代码块。调用方负责追加省略号(因此预算要留 1 个字符)。
92
+ * @param {unknown} value
93
+ * @param {number} maxChars
94
+ * @returns {string}
95
+ */
96
+ export function truncateMarkdown(value, maxChars) {
97
+ const text = String(value ?? "");
98
+ const budget = Math.max(1, Math.trunc(Number(maxChars) || 1));
99
+ if (text.length <= budget) return text;
100
+ let cut = text.slice(0, budget).replace(/\s+$/u, "");
101
+ const closed = closeOpenFences(cut);
102
+ if (closed.length <= budget) return closed;
103
+ const { blocks } = parseMarkdown(cut);
104
+ const last = blocks[blocks.length - 1];
105
+ if (last?.type === "code" && last.streaming === true) {
106
+ const marker = typeof last.marker === "string" && last.marker !== "" ? last.marker : "```";
107
+ const start = cut.lastIndexOf(marker);
108
+ if (start > 0) cut = cut.slice(0, start).replace(/\s+$/u, "");
109
+ }
110
+ return cut;
111
+ }
112
+
113
+ // --- blocks ----------------------------------------------------------------
114
+
115
+ /**
116
+ * @param {string} text
117
+ * @param {number} quoteDepth
118
+ * @returns {any[]}
119
+ */
120
+ function parseBlocks(text, quoteDepth) {
121
+ const lines = text.split("\n");
122
+ /** @type {any[]} */
123
+ const blocks = [];
124
+ let index = 0;
125
+ while (index < lines.length) {
126
+ const line = lines[index];
127
+ if (isBlank(line)) {
128
+ index += 1;
129
+ continue;
130
+ }
131
+
132
+ const fence = matchFence(line);
133
+ if (fence !== null) {
134
+ const body = [];
135
+ let cursor = index + 1;
136
+ let closed = false;
137
+ while (cursor < lines.length) {
138
+ if (isClosingFence(lines[cursor], fence.marker)) {
139
+ closed = true;
140
+ cursor += 1;
141
+ break;
142
+ }
143
+ body.push(lines[cursor]);
144
+ cursor += 1;
145
+ }
146
+ blocks.push({
147
+ type: "code",
148
+ lang: fence.lang,
149
+ code: body.join("\n"),
150
+ marker: fence.marker,
151
+ streaming: !closed,
152
+ });
153
+ index = cursor;
154
+ continue;
155
+ }
156
+
157
+ const heading = /^ {0,3}(#{1,6})[ \t]+(.*)$/u.exec(line);
158
+ if (heading !== null) {
159
+ blocks.push({
160
+ type: "heading",
161
+ level: heading[1].length,
162
+ inlines: parseInlineRuns(heading[2].replace(/[ \t]+#+[ \t]*$/u, ""), 0),
163
+ });
164
+ index += 1;
165
+ continue;
166
+ }
167
+
168
+ if (isHorizontalRule(line)) {
169
+ blocks.push({ type: "hr" });
170
+ index += 1;
171
+ continue;
172
+ }
173
+
174
+ const quote = /^ {0,3}>[ \t]?(.*)$/u.exec(line);
175
+ if (quote !== null) {
176
+ /** @type {string[]} */
177
+ const inner = [];
178
+ let cursor = index;
179
+ while (cursor < lines.length) {
180
+ const current = /^ {0,3}>[ \t]?(.*)$/u.exec(lines[cursor]);
181
+ if (current !== null) {
182
+ inner.push(current[1]);
183
+ cursor += 1;
184
+ continue;
185
+ }
186
+ // 引用里的空行:后面还有 `>` 才继续,否则引用结束。
187
+ if (isBlank(lines[cursor]) && cursor + 1 < lines.length) {
188
+ const next = /^ {0,3}>/u.test(lines[cursor + 1]);
189
+ if (next) {
190
+ inner.push("");
191
+ cursor += 1;
192
+ continue;
193
+ }
194
+ }
195
+ break;
196
+ }
197
+ blocks.push({
198
+ type: "quote",
199
+ blocks:
200
+ quoteDepth >= MAX_QUOTE_DEPTH
201
+ ? [{ type: "paragraph", inlines: parseInlineRuns(inner.join("\n"), 0) }]
202
+ : parseBlocks(inner.join("\n"), quoteDepth + 1),
203
+ });
204
+ index = cursor;
205
+ continue;
206
+ }
207
+
208
+ const table = matchTable(lines, index);
209
+ if (table !== null) {
210
+ blocks.push(table.block);
211
+ index = table.next;
212
+ continue;
213
+ }
214
+
215
+ const list = matchList(lines, index);
216
+ if (list !== null) {
217
+ blocks.push(list.block);
218
+ index = list.next;
219
+ continue;
220
+ }
221
+
222
+ // 段落:吃到空行或下一个块级开头。
223
+ /** @type {string[]} */
224
+ const paragraph = [line];
225
+ let cursor = index + 1;
226
+ while (cursor < lines.length && !isBlank(lines[cursor]) && !startsBlock(lines, cursor)) {
227
+ paragraph.push(lines[cursor]);
228
+ cursor += 1;
229
+ }
230
+ blocks.push({
231
+ type: "paragraph",
232
+ inlines: parseInlineRuns(
233
+ paragraph
234
+ .map((entry) => entry.replace(/[ \t]+$/u, ""))
235
+ .join("\n")
236
+ .trim(),
237
+ 0,
238
+ ),
239
+ });
240
+ index = cursor;
241
+ }
242
+ return blocks;
243
+ }
244
+
245
+ /** @param {string} line */
246
+ function isBlank(line) {
247
+ return /^[ \t]*$/u.test(line);
248
+ }
249
+
250
+ /**
251
+ * @param {string} line
252
+ * @returns {{ marker: string, lang: string } | null}
253
+ */
254
+ function matchFence(line) {
255
+ const match = /^ {0,3}(`{3,}|~{3,})[ \t]*(.*)$/u.exec(line);
256
+ if (match === null) return null;
257
+ const marker = match[1];
258
+ // 反引号围栏的 info string 里不能再出现反引号(CommonMark),出现就不当围栏。
259
+ if (marker[0] === "`" && match[2].includes("`")) return null;
260
+ return { marker, lang: (match[2].trim().split(/\s+/u)[0] ?? "").slice(0, 32) };
261
+ }
262
+
263
+ /**
264
+ * @param {string} line
265
+ * @param {string} marker
266
+ * @returns {boolean}
267
+ */
268
+ function isClosingFence(line, marker) {
269
+ const trimmed = line.trim();
270
+ if (trimmed.length < marker.length) return false;
271
+ if (!/^[`~]+$/u.test(trimmed)) return false;
272
+ return trimmed[0] === marker[0];
273
+ }
274
+
275
+ /** @param {string} line */
276
+ function isHorizontalRule(line) {
277
+ return /^ {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$/u.test(line);
278
+ }
279
+
280
+ /**
281
+ * 当前行是否会开启一个新块(段落收集时的停止条件)。
282
+ * @param {string[]} lines
283
+ * @param {number} index
284
+ * @returns {boolean}
285
+ */
286
+ function startsBlock(lines, index) {
287
+ const line = lines[index];
288
+ if (matchFence(line) !== null) return true;
289
+ if (/^ {0,3}#{1,6}[ \t]+/u.test(line)) return true;
290
+ if (isHorizontalRule(line)) return true;
291
+ if (/^ {0,3}>/u.test(line)) return true;
292
+ if (/^ {0,3}([-*+]|\d{1,9}[.)])[ \t]+/u.test(line)) return true;
293
+ return matchTable(lines, index) !== null;
294
+ }
295
+
296
+ /**
297
+ * 表格:表头行 + 分隔行(`|---|:--:|`)。
298
+ * @param {string[]} lines
299
+ * @param {number} index
300
+ * @returns {{ block: any, next: number } | null}
301
+ */
302
+ function matchTable(lines, index) {
303
+ const headerLine = lines[index];
304
+ if (headerLine === undefined || !headerLine.includes("|")) return null;
305
+ const separatorLine = lines[index + 1];
306
+ if (separatorLine === undefined || !separatorLine.includes("|")) return null;
307
+ const header = splitTableRow(headerLine);
308
+ const separator = splitTableRow(separatorLine);
309
+ if (header === null || separator === null || separator.length === 0) return null;
310
+ if (!separator.every((cell) => /^:?-{1,}:?$/u.test(cell))) return null;
311
+
312
+ const align = separator.map((cell) => {
313
+ const left = cell.startsWith(":");
314
+ const right = cell.endsWith(":");
315
+ if (left && right) return "center";
316
+ if (right) return "right";
317
+ if (left) return "left";
318
+ return "";
319
+ });
320
+ /** @type {any[][]} */
321
+ const rows = [];
322
+ let cursor = index + 2;
323
+ while (cursor < lines.length && !isBlank(lines[cursor]) && lines[cursor].includes("|")) {
324
+ const cells = splitTableRow(lines[cursor]);
325
+ if (cells === null) break;
326
+ rows.push(align.map((_, column) => parseInlineRuns(String(cells[column] ?? ""), 0)));
327
+ cursor += 1;
328
+ }
329
+ return {
330
+ block: {
331
+ type: "table",
332
+ align,
333
+ header: align.map((_, column) => parseInlineRuns(String(header[column] ?? ""), 0)),
334
+ rows,
335
+ },
336
+ next: cursor,
337
+ };
338
+ }
339
+
340
+ /**
341
+ * @param {string} line
342
+ * @returns {string[] | null}
343
+ */
344
+ function splitTableRow(line) {
345
+ const trimmed = line.trim();
346
+ if (!trimmed.includes("|")) return null;
347
+ let body = trimmed;
348
+ if (body.startsWith("|")) body = body.slice(1);
349
+ if (body.endsWith("|")) body = body.slice(0, -1);
350
+ // `\\|` 是单元格里的转义竖线:逐字符切,避免占位符出现在用户内容里。
351
+ /** @type {string[]} */
352
+ const cells = [];
353
+ let buffer = "";
354
+ for (let index = 0; index < body.length; index += 1) {
355
+ if (body[index] === "\\" && body[index + 1] === "|") {
356
+ buffer += "|";
357
+ index += 1;
358
+ continue;
359
+ }
360
+ if (body[index] === "|") {
361
+ cells.push(buffer.trim());
362
+ buffer = "";
363
+ continue;
364
+ }
365
+ buffer += body[index];
366
+ }
367
+ cells.push(buffer.trim());
368
+ return cells;
369
+ }
370
+
371
+ /**
372
+ * 列表:连续同类型的条目。缩进续行并入上一条目(单层列表)。
373
+ * @param {string[]} lines
374
+ * @param {number} index
375
+ * @returns {{ block: any, next: number } | null}
376
+ */
377
+ function matchList(lines, index) {
378
+ const first = matchListItem(lines[index]);
379
+ if (first === null) return null;
380
+ const ordered = first.ordered;
381
+ const start = first.start;
382
+ /** @type {{ inlines: any[] }[]} */
383
+ const items = [];
384
+ let cursor = index;
385
+ while (cursor < lines.length) {
386
+ const item = matchListItem(lines[cursor]);
387
+ if (item === null || item.ordered !== ordered) break;
388
+ /** @type {string[]} */
389
+ const parts = [item.text];
390
+ cursor += 1;
391
+ while (cursor < lines.length) {
392
+ if (isBlank(lines[cursor])) break;
393
+ if (matchListItem(lines[cursor]) !== null) break;
394
+ if (!/^ {2,}\S/u.test(lines[cursor])) break;
395
+ parts.push(lines[cursor].replace(/^ {2,}/u, ""));
396
+ cursor += 1;
397
+ }
398
+ items.push({ inlines: parseInlineRuns(parts.join("\n"), 0) });
399
+ }
400
+ return { block: { type: "list", ordered, start, items }, next: cursor };
401
+ }
402
+
403
+ /**
404
+ * @param {string} line
405
+ * @returns {{ ordered: boolean, start: number, text: string } | null}
406
+ */
407
+ function matchListItem(line) {
408
+ const match = /^ {0,3}([-*+]|\d{1,9}[.)])[ \t]+(.*)$/u.exec(line);
409
+ if (match === null) return null;
410
+ const marker = match[1];
411
+ const ordered = /^\d/u.test(marker);
412
+ return {
413
+ ordered,
414
+ start: ordered ? Number.parseInt(marker, 10) : 1,
415
+ text: match[2],
416
+ };
417
+ }
418
+
419
+ // --- inline ----------------------------------------------------------------
420
+
421
+ /**
422
+ * @param {string} text
423
+ * @param {number} depth
424
+ * @returns {any[]}
425
+ */
426
+ function parseInlineRuns(text, depth) {
427
+ if (depth > MAX_INLINE_DEPTH) return [{ type: "text", text }];
428
+ /** @type {any[]} */
429
+ const runs = [];
430
+ let buffer = "";
431
+ let index = 0;
432
+ /** @param {string} piece */
433
+ const pushText = (piece) => {
434
+ buffer += piece;
435
+ };
436
+ const flush = () => {
437
+ if (buffer !== "") {
438
+ runs.push({ type: "text", text: buffer });
439
+ buffer = "";
440
+ }
441
+ };
442
+ /** @param {any} run */
443
+ const push = (run) => {
444
+ flush();
445
+ runs.push(run);
446
+ };
447
+
448
+ while (index < text.length) {
449
+ const char = text[index];
450
+
451
+ if (char === "\\" && index + 1 < text.length && ESCAPABLE.has(text[index + 1])) {
452
+ pushText(text[index + 1]);
453
+ index += 2;
454
+ continue;
455
+ }
456
+
457
+ if (char === "`") {
458
+ const span = matchCodeSpan(text, index);
459
+ if (span !== null) {
460
+ push({ type: "code", text: span.text });
461
+ index = span.next;
462
+ continue;
463
+ }
464
+ }
465
+
466
+ if (char === "[") {
467
+ const link = matchLink(text, index, depth);
468
+ if (link !== null) {
469
+ push(link.run);
470
+ index = link.next;
471
+ continue;
472
+ }
473
+ }
474
+
475
+ if (char === "<") {
476
+ const autolink = matchAutolink(text, index);
477
+ if (autolink !== null) {
478
+ push(autolink.run);
479
+ index = autolink.next;
480
+ continue;
481
+ }
482
+ }
483
+
484
+ if ((char === "h" || char === "H") && isBareUrlStart(text, index)) {
485
+ const url = matchBareUrl(text, index);
486
+ if (url !== null) {
487
+ push({ type: "link", href: url.href, children: [{ type: "text", text: url.href }] });
488
+ index = url.next;
489
+ continue;
490
+ }
491
+ }
492
+
493
+ if (char === "*" || char === "_" || char === "~") {
494
+ const emphasis = matchEmphasis(text, index, depth);
495
+ if (emphasis !== null) {
496
+ push(emphasis.run);
497
+ index = emphasis.next;
498
+ continue;
499
+ }
500
+ }
501
+
502
+ pushText(char);
503
+ index += 1;
504
+ }
505
+ flush();
506
+ return runs;
507
+ }
508
+
509
+ /**
510
+ * @param {string} text
511
+ * @param {number} start
512
+ * @returns {{ text: string, next: number } | null}
513
+ */
514
+ function matchCodeSpan(text, start) {
515
+ let length = 1;
516
+ while (text[start + length] === "`") length += 1;
517
+ const marker = "`".repeat(length);
518
+ const close = text.indexOf(marker, start + length);
519
+ if (close === -1) return null;
520
+ let content = text.slice(start + length, close).replace(/\n/gu, " ");
521
+ if (
522
+ content.length > 2 &&
523
+ content.startsWith(" ") &&
524
+ content.endsWith(" ") &&
525
+ content.trim() !== ""
526
+ ) {
527
+ content = content.slice(1, -1);
528
+ }
529
+ return { text: content, next: close + length };
530
+ }
531
+
532
+ /**
533
+ * `[label](href "title")`:只接受 http(s)/mailto,其它一律当纯文本。
534
+ * @param {string} text
535
+ * @param {number} start
536
+ * @param {number} depth
537
+ * @returns {{ run: any, next: number } | null}
538
+ */
539
+ function matchLink(text, start, depth) {
540
+ const closeLabel = findClosing(text, start + 1, "[", "]");
541
+ if (closeLabel === -1 || text[closeLabel + 1] !== "(") return null;
542
+ const closeTarget = findClosing(text, closeLabel + 2, "(", ")");
543
+ if (closeTarget === -1) return null;
544
+ const label = text.slice(start + 1, closeLabel);
545
+ const href = normalizeHref(text.slice(closeLabel + 2, closeTarget));
546
+ if (href === "") return null;
547
+ return {
548
+ run: { type: "link", href, children: parseInlineRuns(label, depth + 1) },
549
+ next: closeTarget + 1,
550
+ };
551
+ }
552
+
553
+ /**
554
+ * 找配对的结束符(允许嵌套与反斜杠转义)。
555
+ * @param {string} text
556
+ * @param {number} from
557
+ * @param {string} open
558
+ * @param {string} close
559
+ * @returns {number}
560
+ */
561
+ function findClosing(text, from, open, close) {
562
+ let depth = 1;
563
+ for (let index = from; index < text.length; index += 1) {
564
+ if (text[index] === "\\") {
565
+ index += 1;
566
+ continue;
567
+ }
568
+ if (text[index] === open) depth += 1;
569
+ else if (text[index] === close) {
570
+ depth -= 1;
571
+ if (depth === 0) return index;
572
+ }
573
+ }
574
+ return -1;
575
+ }
576
+
577
+ /**
578
+ * @param {string} raw
579
+ * @returns {string}
580
+ */
581
+ function normalizeHref(raw) {
582
+ let target = String(raw ?? "").trim();
583
+ if (target.startsWith("<") && target.endsWith(">")) target = target.slice(1, -1).trim();
584
+ // 去掉可选的 title:`https://x "标题"`。
585
+ const space = target.search(/[ \t]/u);
586
+ if (space !== -1) target = target.slice(0, space);
587
+ if (!/^(https?:\/\/|mailto:)/iu.test(target)) return "";
588
+ // 控制字符不允许出现在链接里(等价于 /[\u0000-\u001f\u007f]/,但 Biome 禁止控制字符正则)。
589
+ const control = [...target].some((char) => {
590
+ const code = char.codePointAt(0) ?? 0;
591
+ return code < 0x20 || code === 0x7f;
592
+ });
593
+ if (control) return "";
594
+ return target;
595
+ }
596
+
597
+ /**
598
+ * @param {string} text
599
+ * @param {number} start
600
+ * @returns {{ run: any, next: number } | null}
601
+ */
602
+ function matchAutolink(text, start) {
603
+ const close = text.indexOf(">", start + 1);
604
+ if (close === -1) return null;
605
+ const target = text.slice(start + 1, close).trim();
606
+ if (!/^(https?:\/\/|mailto:)/iu.test(target)) return null;
607
+ return {
608
+ run: { type: "link", href: target, children: [{ type: "text", text: target }] },
609
+ next: close + 1,
610
+ };
611
+ }
612
+
613
+ /**
614
+ * 裸 URL 只在词边界开始,避免把 `xhttps://` 当链接。
615
+ * @param {string} text
616
+ * @param {number} start
617
+ * @returns {boolean}
618
+ */
619
+ function isBareUrlStart(text, start) {
620
+ if (!/^https?:\/\//iu.test(text.slice(start, start + 8))) return false;
621
+ if (start === 0) return true;
622
+ return /[\s(([【"'“”‘’]/u.test(text[start - 1]);
623
+ }
624
+
625
+ /**
626
+ * @param {string} text
627
+ * @param {number} start
628
+ * @returns {{ href: string, next: number } | null}
629
+ */
630
+ function matchBareUrl(text, start) {
631
+ let end = start;
632
+ while (end < text.length && !URL_STOP.test(text[end])) end += 1;
633
+ if (end === start) return null;
634
+ let href = text.slice(start, end);
635
+ // 句末标点不属于 URL。
636
+ href = href.replace(/[.,;:!?]+$/u, "");
637
+ if (!/^https?:\/\/\S+$/iu.test(href)) return null;
638
+ return { href, next: start + href.length };
639
+ }
640
+
641
+ /**
642
+ * 强调:`**粗**`、`*斜*`、`__粗__`、`~~删~~`。匹配不到就按普通字符处理。
643
+ * @param {string} text
644
+ * @param {number} start
645
+ * @param {number} depth
646
+ * @returns {{ run: any, next: number } | null}
647
+ */
648
+ function matchEmphasis(text, start, depth) {
649
+ const marker = text[start];
650
+ if (marker === "~") {
651
+ if (!text.startsWith("~~", start)) return null;
652
+ const close = text.indexOf("~~", start + 2);
653
+ if (close === -1) return null;
654
+ const inner = text.slice(start + 2, close);
655
+ if (inner.trim() === "") return null;
656
+ return {
657
+ run: { type: "del", children: parseInlineRuns(inner, depth + 1) },
658
+ next: close + 2,
659
+ };
660
+ }
661
+ const doubled = text.slice(start, start + 2) === marker.repeat(2);
662
+ if (doubled) {
663
+ const close = text.indexOf(marker.repeat(2), start + 2);
664
+ if (close === -1) return null;
665
+ const inner = text.slice(start + 2, close);
666
+ if (inner.trim() === "" || /^\s|\s$/u.test(inner)) return null;
667
+ return {
668
+ run: { type: "strong", children: parseInlineRuns(inner, depth + 1) },
669
+ next: close + 2,
670
+ };
671
+ }
672
+ if (marker === "_") {
673
+ // 下划线强调要求词边界,避免把 file_name / snake_case 拆坏。
674
+ const before = start === 0 ? "" : text[start - 1];
675
+ if (before !== "" && /[A-Za-z0-9_]/u.test(before)) return null;
676
+ const close = text.indexOf("_", start + 1);
677
+ if (close === -1) return null;
678
+ const after = text[close + 1] ?? "";
679
+ if (after !== "" && /[A-Za-z0-9_]/u.test(after)) return null;
680
+ const inner = text.slice(start + 1, close);
681
+ if (inner.trim() === "") return null;
682
+ return {
683
+ run: { type: "em", children: parseInlineRuns(inner, depth + 1) },
684
+ next: close + 1,
685
+ };
686
+ }
687
+ const close = text.indexOf("*", start + 1);
688
+ if (close === -1 || text[close + 1] === "*") return null;
689
+ const inner = text.slice(start + 1, close);
690
+ if (inner.trim() === "" || /^\s|\s$/u.test(inner) || inner.includes("\n")) return null;
691
+ return {
692
+ run: { type: "em", children: parseInlineRuns(inner, depth + 1) },
693
+ next: close + 1,
694
+ };
695
+ }