Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(shared): one autolink clip for desktop and mobile URL tails

Chris351cbb9aca9c
diff --git a/apps/desktop/src/renderer/__tests__/remarkTruncateCjkUrls.test.ts b/apps/desktop/src/renderer/__tests__/remarkTruncateCjkUrls.test.ts
index 54f3ee9e38..8658fe7f7e 100644
--- a/apps/desktop/src/renderer/__tests__/remarkTruncateCjkUrls.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remarkTruncateCjkUrls.test.ts
@@ -143,6 +143,23 @@ describe('remarkTruncateCjkUrls', () => {
expect(tail.value).toBe('(说明)');
});
+ it('issue comment fragment + 全角说明:…#issuecomment-1(无 @)', () => {
+ const tree = autolinkTree(
+ 'https://github.com/example/app/issues/3561#issuecomment-5391602790(无 @)',
+ );
+ transform(tree);
+ const para = tree.children[0] as Paragraph;
+ const link = para.children[0] as Link;
+ const tail = para.children[1] as Text;
+ expect(link.url).toBe(
+ 'https://github.com/example/app/issues/3561#issuecomment-5391602790',
+ );
+ expect((link.children[0] as Text).value).toBe(
+ 'https://github.com/example/app/issues/3561#issuecomment-5391602790',
+ );
+ expect(tail.value).toBe('(无 @)');
+ });
+
it('URL + 直接跟中文文字:https://example.com/path这是说明', () => {
const tree = autolinkTree('https://example.com/path这是说明');
transform(tree);
diff --git a/apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts b/apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts
index fa879df676..81d674f862 100644
--- a/apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts
+++ b/apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts
@@ -12,11 +12,8 @@
* 在 ast 层后处理一刀:扫描 link 节点,url 命中 CJK / 全角范围就在那里切断,
* 把切掉的尾巴作为 text 节点放回 link 后面,保持 visible text 与 href 一致。
*
- * 切断后还要补一次 GFM 风格的「尾部标点剥离」:GFM autolink 在 URL 自然结束
- * (空白/EOF)时会剥掉末尾的 ?!.,:*_~ 等标点,但我们的切点在 CJK 处,原本
- * 粘在 CJK 前面的 ASCII 标点(典型如 `**https://x.com/pr/90**(中文)` 里的
- * `**(`)就会残留在 head 末尾,产生一个点开 404 的脏链接。所以切完再从尾部
- * 把这类标点、悬空的 `(`、未配对的 `)` 一并剥进 tail。
+ * 切边规则在 `@cindy/maker-shared/url-text-boundary`:本插件只负责认出
+ * GFM autolink literal、把尾巴拆回 text,并在 query 后补回被拆开的括号。
*
* 仅处理「children 只有一个 text 且 value === url」这种 autolink literal 形态;
* 显式 `[text](url)` / `<https://...>` 因为 parser 自带闭合括号/尖括号边界,
@@ -28,46 +25,11 @@ import type { Root, Link, Text, PhrasingContent } from 'mdast';
import { visit, SKIP } from 'unist-util-visit';
import {
- countUnmatchedOpeningParens,
- cutBeforeClosingMarkdownWrap,
- cutBeforePathBracketProse,
- cutBeforeUnbalancedParenProse,
- isCodeHostNumericResourcePath,
- isMarkdownWrapOpenBoundary,
- MARKDOWN_WRAP_MARKERS,
- shrinkAutolinkTrailingJunk,
-} from '@/lib/urlTextBoundary';
+ clipBareHttpAutolink,
+ markdownWrapMarkerFromPrefix,
+} from '@cindy/maker-shared/url-text-boundary';
import { findLinkifyMatches } from './userMessageLinkify';
-// Unicode / ASCII 区段,命中即视为 URL 结束边界:
-// " `: 常见 prose 引号;裸 URL 里不应直接出现,应该 percent-encode
-// Apostrophe 可以是合法 path 字符 (`Guns_N'_Roses`) 或 URL 尾字
-// 符,只在能看到对应 opening apostrophe 时按包裹引号剥离。
-// 2018-201F: 弯引号 / 类似的 general punctuation
-// 2026: …
-// 3000-303F: CJK Symbols and Punctuation(、。「」『』【】〈〉《》 等)
-// 3040-30FF: Hiragana + Katakana
-// 3400-4DBF: CJK Extension A
-// 4E00-9FFF: CJK Unified Ideographs
-// AC00-D7AF: Hangul Syllables
-// FF00-FFEF: Halfwidth and Fullwidth Forms(()!?.,;: 等)
-const AUTOLINK_TEXT_BOUNDARY = new RegExp(
- '[' +
- '"`' + // ASCII quotes except apostrophe
- '\\u2018-\\u201F' + // smart quotes
- '\\u2026' + // …
- '\\u3000-\\u303F' + // CJK Symbols and Punctuation
- '\\u3040-\\u30FF' + // Hiragana + Katakana
- '\\u3400-\\u4DBF' + // CJK Extension A
- '\\u4E00-\\u9FFF' + // CJK Unified Ideographs
- '\\uAC00-\\uD7AF' + // Hangul Syllables
- '\\uFF00-\\uFFEF' + // Halfwidth and Fullwidth Forms
- ']',
-);
-
-const MARKDOWN_FORMATTING_STRIP_BOUNDARY =
- /[\u3000-\u303F\u3040-\u30FF\u3400-\u4DBF\u4E00-\u9FFF\uAC00-\uD7AF\uFF00-\uFFEF]/;
-
function hasSamePosition(a: Link, b: Text): boolean {
return (
a.position?.start.offset != null &&
@@ -77,17 +39,6 @@ function hasSamePosition(a: Link, b: Text): boolean {
);
}
-function getMarkdownWrapMarkerBeforeAutolink(prevText: string | null): string | null {
- if (!prevText) return null;
- for (const marker of MARKDOWN_WRAP_MARKERS) {
- if (!prevText.endsWith(marker)) continue;
- return isMarkdownWrapOpenBoundary(prevText[prevText.length - marker.length - 1])
- ? marker
- : null;
- }
- return null;
-}
-
function textFromPhrasingContent(node: PhrasingContent): string {
if (node.type === 'text' || node.type === 'inlineCode') return node.value;
if ('children' in node) {
@@ -121,36 +72,13 @@ const remarkTruncateCjkUrls: Plugin<[], Root> = () => {
parent.children as PhrasingContent[],
index,
);
- const match = node.url.match(AUTOLINK_TEXT_BOUNDARY);
- const boundaryIndex = match?.index;
-
const prev = parent.children[index - 1];
const prevText = prev?.type === 'text' ? (prev as Text).value : null;
const prefixText = textBeforeAutolink(parent.children as PhrasingContent[], index);
- const hasLeadingApostrophe =
- prefixText.endsWith("'");
- const marker = getMarkdownWrapMarkerBeforeAutolink(prevText);
- const wrappingParenCount = countUnmatchedOpeningParens(prefixText);
- const boundaryCut = boundaryIndex ?? node.url.length;
- const markdownCut = cutBeforeClosingMarkdownWrap(node.url, marker);
- const proseCut = Math.min(
- boundaryCut,
- cutBeforeUnbalancedParenProse(node.url, Math.min(boundaryCut, markdownCut), {
- wrappingParenCount,
- }),
- cutBeforePathBracketProse(node.url),
- markdownCut,
- );
- const shouldStripMarkdownFormattingPunct =
- markdownCut < node.url.length ||
- hasTrailingMultiCharMarkdownMarkerAfterCodeHostResource(node.url, proseCut) ||
- (boundaryIndex != null &&
- proseCut === boundaryCut &&
- MARKDOWN_FORMATTING_STRIP_BOUNDARY.test(node.url[boundaryIndex]));
- const cut = shrinkAutolinkTrailingJunk(node.url, proseCut, {
- stripMarkdownFormattingPunct: shouldStripMarkdownFormattingPunct,
- stripWrappingApostrophe: hasLeadingApostrophe,
- stripWrappingParenCount: wrappingParenCount,
+ const cut = clipBareHttpAutolink(node.url, {
+ prefix: prefixText,
+ markdownWrapMarker: markdownWrapMarkerFromPrefix(prevText),
+ stripMarkdownFormattingPunct: 'auto',
});
if (cut === node.url.length) return;
if (cut === 0) return;
@@ -170,15 +98,6 @@ const remarkTruncateCjkUrls: Plugin<[], Root> = () => {
export default remarkTruncateCjkUrls;
-function hasTrailingMultiCharMarkdownMarkerAfterCodeHostResource(raw: string, cut: number): boolean {
- if (cut < 2) return false;
- return ['**', '__', '~~'].some(
- (marker) =>
- raw.slice(cut - marker.length, cut) === marker &&
- isCodeHostNumericResourcePath(raw.slice(0, cut - marker.length)),
- );
-}
-
function linkifyTailUrls(tail: string): PhrasingContent[] {
const matches = findLinkifyMatches(tail).filter((match) => match.kind === 'url');
if (matches.length === 0) {
diff --git a/apps/desktop/src/renderer/components/chat/userMessageLinkify.ts b/apps/desktop/src/renderer/components/chat/userMessageLinkify.ts
index c6149e4470..5929b09179 100644
--- a/apps/desktop/src/renderer/components/chat/userMessageLinkify.ts
+++ b/apps/desktop/src/renderer/components/chat/userMessageLinkify.ts
@@ -1,12 +1,7 @@
import {
- cutBeforeUnbalancedParenProse,
- cutBeforeClosingMarkdownWrap,
- cutBeforePathBracketProse,
- countUnmatchedOpeningParens,
- isMarkdownWrapOpenBoundary,
- MARKDOWN_WRAP_MARKERS,
- shrinkAutolinkTrailingJunk,
-} from '@/lib/urlTextBoundary';
+ BARE_HTTP_URL_RE_SOURCE,
+ clipBareHttpAutolink,
+} from '@cindy/maker-shared/url-text-boundary';
import {
SESSION_DEEP_LINK_RE_SOURCE,
PROJECT_DEEP_LINK_RE_SOURCE,
@@ -29,18 +24,9 @@ import { stripDeepLinkPathPrefix } from '../../../shared/deepLinkSchemes';
* (png/jpg/jpeg/gif/webp/svg/bmp/ico) and the main-process xdt-file://
* protocol's IMAGE_EXT_WHITELIST. Keep them in sync.
*/
-// The trailing range in the negation class spans U+0080..U+FFFF, so any
-// non-ASCII char (CJK text, full-width punctuation) terminates the URL —
-// URLs at this layer are ASCII-only, otherwise a Chinese comma right after
-// the URL gets gobbled into the link and breaks the click target.
-//
-// ASCII double quotes / angle brackets are prose boundaries. Apostrophes can be
-// valid path text (`Guns_N'_Roses`) and can also validly end a URL, so a trailing
-// apostrophe is only stripped when the URL is visibly wrapped by a leading
-// apostrophe. Parentheses and square/brace brackets are handled after matching so
-// URL-valid query / fragment punctuation survives while path-level prose is
-// returned to text.
-const URL_RE = /(https?:\/\/[^\s<>"\u0080-\uFFFF]+)/g;
+// 匹配源与切边都来自 maker-shared/url-text-boundary:ASCII-only 匹配,
+// 半角括号/包裹引号/尾部句读由 clipBareHttpAutolink 统一收口。
+const URL_RE = new RegExp(`(${BARE_HTTP_URL_RE_SOURCE})`, 'g');
const IMG_PATH_RE =
/([A-Za-z]:[\\/][^\s<>"']*?\.(?:png|jpe?g|gif|webp|svg|bmp|ico)|\/[^\s<>"']*?\.(?:png|jpe?g|gif|webp|svg|bmp|ico))/gi;
// \u4F1A\u8BDD\u6DF1\u94FE cindy://session/<id>[?message=<clientId>](\u5386\u53F2 xdt-maker:// \u540C):ASCII \u767D\u540D\u5355,CJK /
@@ -82,36 +68,13 @@ export type LinkifyMatch =
| ({ kind: 'session' } & DeepLinkMatchFields)
| ({ kind: 'project' } & DeepLinkMatchFields);
-function getMarkdownWrapMarkerBeforeUrl(source: string, index: number): string | null {
- for (const marker of MARKDOWN_WRAP_MARKERS) {
- if (index < marker.length || source.slice(index - marker.length, index) !== marker) {
- continue;
- }
- return isMarkdownWrapOpenBoundary(source[index - marker.length - 1])
- ? marker
- : null;
- }
- return null;
-}
-
function pushUrlMatch(
matches: LinkifyMatch[],
source: string,
index: number,
raw: string,
): number | null {
- const marker = getMarkdownWrapMarkerBeforeUrl(source, index);
- const markdownCut = cutBeforeClosingMarkdownWrap(raw, marker);
- const wrappingParenCount = countUnmatchedOpeningParens(source.slice(0, index));
- const cut = Math.min(
- cutBeforeUnbalancedParenProse(raw, markdownCut, { wrappingParenCount }),
- cutBeforePathBracketProse(raw),
- markdownCut,
- );
- const end = shrinkAutolinkTrailingJunk(raw, cut, {
- stripWrappingApostrophe: source[index - 1] === "'",
- stripWrappingParenCount: wrappingParenCount,
- });
+ const end = clipBareHttpAutolink(raw, { prefix: source.slice(0, index) });
if (end <= 0) return null;
const text = raw.slice(0, end);
matches.push({
diff --git a/apps/mobile/src/__tests__/messageMarkdown.test.ts b/apps/mobile/src/__tests__/messageMarkdown.test.ts
index ac4994371b..737da3f8c5 100644
--- a/apps/mobile/src/__tests__/messageMarkdown.test.ts
+++ b/apps/mobile/src/__tests__/messageMarkdown.test.ts
@@ -251,6 +251,44 @@ describe('messageMarkdown', () => {
]);
});
+ it('does not swallow fullwidth parentheses or CJK punctuation after a bare URL', () => {
+ expect(parseMobileMarkdownInlines(
+ '诊断已写在 https://github.com/example/app/issues/3561#issuecomment-5391602790(无 @)。',
+ )).toEqual([
+ { type: 'text', text: '诊断已写在 ' },
+ {
+ type: 'link',
+ text: 'https://github.com/example/app/issues/3561#issuecomment-5391602790',
+ url: 'https://github.com/example/app/issues/3561#issuecomment-5391602790',
+ },
+ { type: 'text', text: '(无 @)。' },
+ ]);
+ expect(parseMobileMarkdownInlines('看 https://example.com/path(说明)然后')).toEqual([
+ { type: 'text', text: '看 ' },
+ { type: 'link', text: 'https://example.com/path', url: 'https://example.com/path' },
+ { type: 'text', text: '(说明)然后' },
+ ]);
+ expect(parseMobileMarkdownInlines('看 https://example.com/path。然后')).toEqual([
+ { type: 'text', text: '看 ' },
+ { type: 'link', text: 'https://example.com/path', url: 'https://example.com/path' },
+ { type: 'text', text: '。然后' },
+ ]);
+ expect(parseMobileMarkdownInlines('见 https://en.wikipedia.org/wiki/Foo_(bar) 词条')).toEqual([
+ { type: 'text', text: '见 ' },
+ {
+ type: 'link',
+ text: 'https://en.wikipedia.org/wiki/Foo_(bar)',
+ url: 'https://en.wikipedia.org/wiki/Foo_(bar)',
+ },
+ { type: 'text', text: ' 词条' },
+ ]);
+ expect(parseMobileMarkdownInlines('见 (https://example.com/path) 收尾')).toEqual([
+ { type: 'text', text: '见 (' },
+ { type: 'link', text: 'https://example.com/path', url: 'https://example.com/path' },
+ { type: 'text', text: ') 收尾' },
+ ]);
+ });
+
it('parses common inline formatting tokens', () => {
expect(parseMobileMarkdownInlines(
'Use **bold**, *em*, `code`, ~~gone~~, [docs](https://example.com/docs).',
diff --git a/apps/mobile/src/session/messageMarkdown.ts b/apps/mobile/src/session/messageMarkdown.ts
index bdbc7fa000..533cbf4de8 100644
--- a/apps/mobile/src/session/messageMarkdown.ts
+++ b/apps/mobile/src/session/messageMarkdown.ts
@@ -1,4 +1,8 @@
import { normalizeMathDelimiters } from '@cindy/maker-shared/math-markdown';
+import {
+ BARE_HTTP_URL_RE_SOURCE,
+ clipBareHttpAutolinkText,
+} from '@cindy/maker-shared/url-text-boundary';
import {
classifyChatPathLinkTarget,
findBareFilePathMatch,
@@ -868,8 +872,8 @@ function findNextInlineToken(
type: 'emphasis' as const,
text: match[2],
}), 1),
- // 裸链接:http(s) 通用形态 + 会话/项目深链(ASCII 白名单,CJK / 空白处
- // 天然收尾;尾部粘连的英文句读由 trimUrlPunctuation 统一剥掉。project
+ // 裸链接:http(s) 走共享 BARE_HTTP_URL_RE_SOURCE + clipBareHttpAutolink
+ // (CJK/全角标点/包裹括号/尾部句读同一套);会话/项目深链仍是。project
// 白名单与桌面 PROJECT_DEEP_LINK_RE_SOURCE 同口径,含尾部负向前瞻
// (白名单 ∪ `'(`):旧编码产出的链接可能含裸 `'` `(`,白名单在此截断
// 会得到指错项目的前缀匹配——匹配终止处紧跟 `'` / `(` 时整段拒绝;
@@ -880,14 +884,16 @@ function findNextInlineToken(
input,
from,
new RegExp(
- `(?:https?://[^\\s<>()]+[^\\s<>().,;:!?]|(?:${DEEP_LINK_SCHEME_GROUP})://session/[A-Za-z0-9%~_-]+(?:\\?[A-Za-z0-9%&=~._-]*[A-Za-z0-9%~_-])?|(?:${DEEP_LINK_SCHEME_GROUP})://project/[A-Za-z0-9%~._!*-]+(?![A-Za-z0-9%~._!*('-]))`,
+ `(?:${BARE_HTTP_URL_RE_SOURCE}|(?:${DEEP_LINK_SCHEME_GROUP})://session/[A-Za-z0-9%~_-]+(?:\\?[A-Za-z0-9%&=~._-]*[A-Za-z0-9%~_-])?|(?:${DEEP_LINK_SCHEME_GROUP})://project/[A-Za-z0-9%~._!*-]+(?![A-Za-z0-9%~._!*('-]))`,
'g',
),
- (match) => ({
- type: 'link' as const,
- text: trimUrlPunctuation(match[0]),
- url: trimUrlPunctuation(match[0]),
- }),
+ (match) => {
+ const rawHref = match[0];
+ const href = /^https?:\/\//i.test(rawHref)
+ ? clipBareHttpAutolinkText(rawHref, { prefix: input.slice(0, match.index) })
+ : trimUrlPunctuation(rawHref);
+ return { type: 'link' as const, text: href, url: href };
+ },
);
// 剥掉的尾部句读要留在正文里:matchRegex 的 end 按未剥原文推进,而
// project 白名单含 `.`(`!` 同理),`…%2Frepo.` 的句号会被吞掉不再
diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.json
index e42ac72e9c..f1a75b67e4 100644
--- a/packages/maker-shared/package.json
+++ b/packages/maker-shared/package.json
@@ -68,6 +68,7 @@
"./turn-continuation": "./src/turnContinuation.ts",
"./tool-use-descriptor": "./src/toolUseDescriptor.ts",
"./update-channel": "./src/updateChannel.ts",
+ "./url-text-boundary": "./src/urlTextBoundary.ts",
"./usage-format": "./src/usageFormat.ts",
"./work-activity-projection": "./src/workActivityProjection.ts",
"./worktree-paths": "./src/worktreePaths.ts",
diff --git a/packages/maker-shared/src/__tests__/urlTextBoundary.test.ts b/packages/maker-shared/src/__tests__/urlTextBoundary.test.ts
new file mode 100644
index 0000000000..c8cfc2b257
--- /dev/null
+++ b/packages/maker-shared/src/__tests__/urlTextBoundary.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest';
+import {
+ BARE_HTTP_URL_RE_SOURCE,
+ clipBareHttpAutolinkText,
+} from '../urlTextBoundary.js';
+
+function matchBareHttp(text: string): string | null {
+ const match = new RegExp(BARE_HTTP_URL_RE_SOURCE, 'g').exec(text);
+ return match?.[0] ?? null;
+}
+
+describe('clipBareHttpAutolinkText', () => {
+ it('strips fullwidth parentheses and CJK punctuation glued to a URL', () => {
+ expect(
+ clipBareHttpAutolinkText(
+ 'https://github.com/example/app/issues/3561#issuecomment-5391602790(无 @)',
+ ),
+ ).toBe('https://github.com/example/app/issues/3561#issuecomment-5391602790');
+ expect(clipBareHttpAutolinkText('https://example.com/path(说明)')).toBe(
+ 'https://example.com/path',
+ );
+ expect(clipBareHttpAutolinkText('https://example.com/path。')).toBe(
+ 'https://example.com/path',
+ );
+ });
+
+ it('keeps balanced Wikipedia-style parentheses', () => {
+ expect(
+ clipBareHttpAutolinkText('https://en.wikipedia.org/wiki/Foo_(bar)'),
+ ).toBe('https://en.wikipedia.org/wiki/Foo_(bar)');
+ });
+
+ it('does not swallow a wrapping closer from surrounding prose', () => {
+ expect(
+ clipBareHttpAutolinkText('https://example.com/path)', { prefix: '见 (' }),
+ ).toBe('https://example.com/path');
+ });
+
+ it('strips trailing English sentence punctuation', () => {
+ expect(clipBareHttpAutolinkText('https://example.com/path,')).toBe(
+ 'https://example.com/path',
+ );
+ expect(clipBareHttpAutolinkText('https://example.com/path.')).toBe(
+ 'https://example.com/path',
+ );
+ });
+});
+
+describe('BARE_HTTP_URL_RE_SOURCE', () => {
+ it('stops the match before non-ASCII prose', () => {
+ expect(
+ matchBareHttp(
+ '诊断已写在 https://github.com/example/app/issues/3561#issuecomment-5391602790(无 @)。',
+ ),
+ ).toBe('https://github.com/example/app/issues/3561#issuecomment-5391602790');
+ expect(matchBareHttp('看 https://example.com/path。然后')).toBe(
+ 'https://example.com/path',
+ );
+ });
+
+ it('includes balanced ASCII parentheses for later clip', () => {
+ expect(matchBareHttp('https://en.wikipedia.org/wiki/Foo_(bar) next')).toBe(
+ 'https://en.wikipedia.org/wiki/Foo_(bar)',
+ );
+ });
+});
diff --git a/packages/maker-shared/src/index.ts b/packages/maker-shared/src/index.ts
index f4909cc63c..c511e7d9a3 100644
--- a/packages/maker-shared/src/index.ts
+++ b/packages/maker-shared/src/index.ts
@@ -52,5 +52,6 @@ export * from './toolUseDescriptor.js';
export * from './thinkingText.js';
export * from './turnContinuation.js';
export * from './updateChannel.js';
+export * from './urlTextBoundary.js';
export * from './workActivityProjection.js';
export * from './worktreePaths.js';
diff --git a/apps/desktop/src/renderer/lib/urlTextBoundary.ts b/packages/maker-shared/src/urlTextBoundary.ts
similarity index 74%
rename from apps/desktop/src/renderer/lib/urlTextBoundary.ts
rename to packages/maker-shared/src/urlTextBoundary.ts
index 4ff5e15469..0e872c1e25 100644
--- a/apps/desktop/src/renderer/lib/urlTextBoundary.ts
+++ b/packages/maker-shared/src/urlTextBoundary.ts
@@ -1,7 +1,13 @@
+/**
+ * 裸 http(s) URL 在聊天正文里的切边权威。
+ *
+ * Desktop 用户消息、Desktop GFM autolink 后处理、Mobile markdown 分词共用这一份,
+ * 避免「URL 后面粘着(说明)」这类尾巴在一端被切掉、另一端点进 404。
+ * 匹配可以按扫描器各自写;href 从哪一刀结束只问 `clipBareHttpAutolink`。
+ */
+
// 尾部 ASCII 标点集合:GFM spec 会剥掉 ? ! . , : * _ ~,此处额外加了 ;
// 以便把 `https://x.com/foo; 然后` 这类散文分号也视为 URL 边界。
-// 用在我们自己的 plain-text linkifier 和 remark 后处理里,避免两条渲染链路
-// 对 `https://x.com/foo.` / `https://x.com/foo(base` 这类边界给出不同结果。
const PROSE_TRAILING_PUNCT = new Set(['?', '!', '.', ',', ':', ';']);
const MARKDOWN_FORMATTING_TRAILING_PUNCT = new Set(['*', '_', '~']);
@@ -333,3 +339,102 @@ export function shrinkAutolinkTrailingJunk(
}
return end;
}
+
+/**
+ * 扫描器用的裸 http(s) 源。空白 / 尖括号 / ASCII 引号 / 任何非 ASCII
+ * (含全角括号与中文)处结束,避免匹配阶段就把说明吃进候选。
+ * 半角括号留给 `clipBareHttpAutolink` 按配对/包裹处理。
+ */
+export const BARE_HTTP_URL_RE_SOURCE =
+ String.raw`https?://[^\s<>"\u0080-\uFFFF]+`;
+
+const AUTOLINK_PROSE_BOUNDARY = new RegExp(
+ '[' +
+ '"`' +
+ '\\u2018-\\u201F' +
+ '\\u2026' +
+ '\\u3000-\\u303F' +
+ '\\u3040-\\u30FF' +
+ '\\u3400-\\u4DBF' +
+ '\\u4E00-\\u9FFF' +
+ '\\uAC00-\\uD7AF' +
+ '\\uFF00-\\uFFEF' +
+ ']',
+);
+
+const MARKDOWN_FORMATTING_STRIP_BOUNDARY =
+ /[\u3000-\u303F\u3040-\u30FF\u3400-\u4DBF\u4E00-\u9FFF\uAC00-\uD7AF\uFF00-\uFFEF]/;
+
+export function markdownWrapMarkerFromPrefix(prefix: string | null | undefined): string | null {
+ if (!prefix) return null;
+ for (const marker of MARKDOWN_WRAP_MARKERS) {
+ if (!prefix.endsWith(marker)) continue;
+ return isMarkdownWrapOpenBoundary(prefix[prefix.length - marker.length - 1])
+ ? marker
+ : null;
+ }
+ return null;
+}
+
+export type ClipBareHttpAutolinkOptions = {
+ prefix?: string | null;
+ markdownWrapMarker?: string | null;
+ stripMarkdownFormattingPunct?: boolean | 'auto';
+};
+
+/**
+ * 返回 `raw` 里真实 href 的结束下标(不含)。
+ * prefix 是 URL 前面的正文,用来识别包裹括号 / 引号 / markdown 开标记。
+ */
+export function clipBareHttpAutolink(
+ raw: string,
+ options: ClipBareHttpAutolinkOptions = {},
+): number {
+ const prefix = options.prefix ?? '';
+ const wrappingParenCount = countUnmatchedOpeningParens(prefix);
+ const marker =
+ options.markdownWrapMarker === undefined
+ ? markdownWrapMarkerFromPrefix(prefix)
+ : options.markdownWrapMarker;
+ const boundaryIndex = raw.search(AUTOLINK_PROSE_BOUNDARY);
+ const boundaryCut = boundaryIndex >= 0 ? boundaryIndex : raw.length;
+ const markdownCut = cutBeforeClosingMarkdownWrap(raw, marker);
+ const limited = Math.min(boundaryCut, markdownCut);
+ const proseCut = Math.min(
+ limited,
+ cutBeforeUnbalancedParenProse(raw, limited, { wrappingParenCount }),
+ cutBeforePathBracketProse(raw),
+ );
+ const stripMarkdown =
+ options.stripMarkdownFormattingPunct === true ||
+ (options.stripMarkdownFormattingPunct === 'auto' &&
+ (markdownCut < raw.length ||
+ hasTrailingMultiCharMarkdownMarkerAfterCodeHostResource(raw, proseCut) ||
+ (boundaryIndex >= 0 &&
+ proseCut === boundaryCut &&
+ MARKDOWN_FORMATTING_STRIP_BOUNDARY.test(raw[boundaryIndex]))));
+ return shrinkAutolinkTrailingJunk(raw, proseCut, {
+ stripMarkdownFormattingPunct: stripMarkdown,
+ stripWrappingApostrophe: prefix.endsWith("'"),
+ stripWrappingParenCount: wrappingParenCount,
+ });
+}
+
+export function clipBareHttpAutolinkText(
+ raw: string,
+ options: ClipBareHttpAutolinkOptions = {},
+): string {
+ return raw.slice(0, clipBareHttpAutolink(raw, options));
+}
+
+function hasTrailingMultiCharMarkdownMarkerAfterCodeHostResource(
+ raw: string,
+ cut: number,
+): boolean {
+ if (cut < 2) return false;
+ return ['**', '__', '~~'].some(
+ (marker) =>
+ raw.slice(cut - marker.length, cut) === marker &&
+ isCodeHostNumericResourcePath(raw.slice(0, cut - marker.length)),
+ );
+}