An open source design system that's fully customizable and agent ready
TypeScript
feat(core/Markdown): opt-in GFM autolinks via `autolink` prop (#2394)
Alexander Blom4eee09f267f6
diff --git a/.changeset/gfm-autolinks.md b/.changeset/gfm-autolinks.mdnew file mode 100644index 0000000000..cd03527f06--- /dev/null+++ b/.changeset/gfm-autolinks.md@@ -0,0 +1,7 @@+---+'@xds/core': minor+---++`<XDSMarkdown>` gains an opt-in `autolink` prop. Setting `autolink="gfm"` enables GitHub-Flavored Markdown autolink-literal rules: bare `https?://…`, `www.…`, `<scheme:url>`, `<email>`, and `user@host` all render as links. Trailing sentence punctuation (`?!.,:*_~`) and unbalanced trailing `)` are excluded; matches inside code spans, code blocks, existing links, and image alt text are skipped. Default behavior is unchanged.++The same option is also available on `parseMarkdown`, `parseInline`, and `parseMarkdownIncremental` via a new `ParseOptions` argument (`{sourceIds?, autolink?}`); the existing `ReadonlySet<string>` positional signature is preserved.diff --git a/packages/core/src/Markdown/Markdown.doc.mjs b/packages/core/src/Markdown/Markdown.doc.mjsindex 15da669ca3..9e39365118 100644--- a/packages/core/src/Markdown/Markdown.doc.mjs+++ b/packages/core/src/Markdown/Markdown.doc.mjs@@ -82,6 +82,12 @@ export const docs = {description:'Transforms regex matches in parsed text nodes into custom inline React elements. Use for issue refs, diff refs, mentions, and other shorthand patterns. Inline code and fenced code blocks are unaffected.',},+ {+ name: 'autolink',+ type: "'gfm'",+ description:+ "Opt-in autolinking of bare URLs and emails. 'gfm' applies GitHub-Flavored Markdown autolink-literal rules: bare https?://…, www.…, <scheme:url>, <email>, and user@host all become links. Trailing sentence punctuation and unbalanced trailing close-parens are excluded; matches inside code spans, code blocks, existing links, and image alt text are skipped. Default behavior (option unset) is unchanged.",+ },{name: 'xstyle',type: 'StyleXStyles',@@ -127,6 +133,15 @@ export const docs = {],},examples: [+ {+ label: 'GFM autolinks',+ code: `+<XDSMarkdown autolink="gfm">+ {'Visit https://example.com or email [email protected]. ' ++ 'You can also bracket links: <https://docs.example.com>.'}+</XDSMarkdown>;+`,+ },{label: 'Inline Plugins',code: `@@ -218,6 +233,12 @@ export const docsZh = {description:'将已解析文本节点中的正则匹配转换为自定义内联 React 元素。适用于 issue 引用、diff 引用、用户提及等简写模式。内联代码和围栏代码块不受影响。',},+ {+ name: 'autolink',+ type: "'gfm'",+ description:+ "可选的裸 URL 和电子邮箱自动链接。设为 'gfm' 启用 GitHub Flavored Markdown 自动链接规则:裸 https?://、www.、<scheme:url>、<email> 以及 user@host 都会变成链接。末尾句末标点和不平衡的末尾右括号会被排除;代码块、现有链接和图片替代文本内部的匹配会被跳过。默认为关闭。",+ },{name: 'xstyle',type: 'StyleXStyles',@@ -281,6 +302,7 @@ export const docsDense = {contentWidth: 'number|string. Max width for prose (headings, paragraphs, lists). Tables/code unconstrained.',contentAlign: "'start'|'center'. Prose alignment when contentWidth < container. Default: 'start'.",inlinePlugins: 'MarkdownInlinePlugin[]. Regex matches in text nodes -> custom inline React elements. Skips inline/fenced code.',+ autolink: "'gfm'. Opt-in GFM autolinking: bare URLs (https?://, www.), <scheme:url>, <email>, user@host. Skips code, code blocks, existing links. Default: off.",xstyle: 'stylex.create() for layout (margins, sizing).',className: 'CSS class. Prefer xstyle.',style: 'Inline styles. Prefer xstyle.',diff --git a/packages/core/src/Markdown/XDSMarkdown.test.tsx b/packages/core/src/Markdown/XDSMarkdown.test.tsxindex 04316d7570..3d72b0c69c 100644--- a/packages/core/src/Markdown/XDSMarkdown.test.tsx+++ b/packages/core/src/Markdown/XDSMarkdown.test.tsx@@ -449,4 +449,68 @@ describe('inlinePlugins', () => {expect(link!.textContent).toBe('PROJ-123');expect(link!.closest('strong')).toBeInTheDocument();});++ describe('autolink prop', () => {+ it('renders bare URLs as plain text by default', () => {+ const {container} = render(+ <XDSMarkdown>{'see https://example.com here'}</XDSMarkdown>,+ );+ expect(container.querySelector('a')).toBeNull();+ expect(container.textContent).toContain('https://example.com');+ });++ it('renders bare https URLs as links when autolink="gfm"', () => {+ const {container} = render(+ <XDSMarkdown autolink="gfm">+ {'see https://example.com here'}+ </XDSMarkdown>,+ );+ const link = container.querySelector('a');+ expect(link).not.toBeNull();+ expect(link!.getAttribute('href')).toBe('https://example.com');+ expect(link!.textContent).toBe('https://example.com');+ });++ it('renders bare www URLs with http:// prefix', () => {+ const {container} = render(+ <XDSMarkdown autolink="gfm">{'go www.example.com'}</XDSMarkdown>,+ );+ const link = container.querySelector('a');+ expect(link).not.toBeNull();+ expect(link!.getAttribute('href')).toBe('http://www.example.com');+ expect(link!.textContent).toBe('www.example.com');+ });++ it('renders bare emails with mailto: href', () => {+ const {container} = render(+ <XDSMarkdown autolink="gfm">+ {'ping [email protected] please'}+ </XDSMarkdown>,+ );+ const link = container.querySelector('a');+ expect(link).not.toBeNull();+ expect(link!.getAttribute('href')).toBe('mailto:[email protected]');+ expect(link!.textContent).toBe('[email protected]');+ });++ it('does not autolink URLs inside code spans', () => {+ const {container} = render(+ <XDSMarkdown autolink="gfm">+ {'try `https://example.com` here'}+ </XDSMarkdown>,+ );+ expect(container.querySelector('a')).toBeNull();+ expect(container.querySelector('code')).not.toBeNull();+ });++ it('does not autolink URLs inside code blocks', () => {+ const {container} = render(+ <XDSMarkdown autolink="gfm">+ {'```\nhttps://example.com\n```'}+ </XDSMarkdown>,+ );+ expect(container.querySelector('a')).toBeNull();+ expect(container.querySelector('pre')).not.toBeNull();+ });+ });});diff --git a/packages/core/src/Markdown/XDSMarkdown.tsx b/packages/core/src/Markdown/XDSMarkdown.tsxindex dec2cd85db..21856c2288 100644--- a/packages/core/src/Markdown/XDSMarkdown.tsx+++ b/packages/core/src/Markdown/XDSMarkdown.tsx@@ -167,6 +167,19 @@ export interface XDSMarkdownProps extends XDSBaseProps<HTMLDivElement> {* for overlapping ranges.*/inlinePlugins?: MarkdownInlinePlugin[];+ /**+ * Opt-in autolinking of bare URLs and emails inside text.+ * - `'gfm'` — GitHub-Flavored Markdown autolink-literal rules:+ * `https?://…`, `www.…`, `<scheme:url>`, `<email>`, and bare+ * `user@host` all become `<a>` links. Trailing sentence punctuation+ * (`?!.,:*_~`) and unbalanced trailing `)` are excluded; matches inside+ * code spans, code blocks, existing links, and image alt text are+ * skipped.+ *+ * Default behavior (option unset) is unchanged — bare URLs render as+ * literal text.+ */+ autolink?: 'gfm';}// ---------------------------------------------------------------------------@@ -835,7 +848,8 @@ function renderInline(</LinkComp>);}- const isExternal = safeHref.startsWith('http');+ const isExternal =+ safeHref.startsWith('https://') || safeHref.startsWith('http://');const handleClick = onLinkClick? (e: React.MouseEvent<HTMLAnchorElement>) => {const result = onLinkClick(safeHref, e);@@ -1512,6 +1526,7 @@ export function XDSMarkdown({contentAlign = 'start',components,inlinePlugins,+ autolink,xstyle,className,style,@@ -1524,6 +1539,11 @@ export function XDSMarkdown({[sources],);+ const parseOptions = useMemo(+ () => ({sourceIds, autolink}),+ [sourceIds, autolink],+ );+// Smooth bursty streamed chunks into a steady character-by-character reveal.// When not streaming, the hook returns children unchanged (no-op).const smoothedText = useXDSStreamingText(children, isStreaming);@@ -1531,6 +1551,13 @@ export function XDSMarkdown({const incrementalStateRef = useRef<IncrementalState>(createIncrementalState(),);+ // Reset incremental cache when the autolink option toggles — cached+ // settled blocks were parsed with the previous setting.+ const prevAutolinkRef = useRef(autolink);+ if (prevAutolinkRef.current !== autolink) {+ incrementalStateRef.current = createIncrementalState();+ prevAutolinkRef.current = autolink;+ }const blocks = useMemo(() => {if (isStreaming) {@@ -1542,11 +1569,11 @@ export function XDSMarkdown({return parseMarkdownIncremental(input,incrementalStateRef.current,- sourceIds,+ parseOptions,);}- return parseMarkdown(children, sourceIds);- }, [smoothedText, children, isStreaming, sourceIds]);+ return parseMarkdown(children, parseOptions);+ }, [smoothedText, children, isStreaming, parseOptions]);// Track recent boundaries for stacked fade-in animation.// The number of spans needed = ceil(animationDuration / tickInterval).diff --git a/packages/core/src/Markdown/incremental.test.ts b/packages/core/src/Markdown/incremental.test.tsindex cfca453054..a2bb8751f4 100644--- a/packages/core/src/Markdown/incremental.test.ts+++ b/packages/core/src/Markdown/incremental.test.ts@@ -565,4 +565,69 @@ describe('streaming end-to-end: no raw syntax visible', () => {expect(visible).not.toContain('![');}});++ describe('with autolink option', () => {+ it('produces same final result as full parse with autolink: gfm', () => {+ const text = 'Visit https://example.com or mail [email protected] today.';+ const state = createIncrementalState();+ const incremental = parseMarkdownIncremental(text, state, {+ autolink: 'gfm',+ });+ const full = parseMarkdown(text, {autolink: 'gfm'});+ expect(incremental).toEqual(full);+ // Sanity: the autolink transform actually fired+ const para = incremental[0];+ if (para.type === 'paragraph') {+ const linkHrefs = para.children+ .filter((n: InlineNode) => n.type === 'link')+ .map((n: InlineNode) => (n.type === 'link' ? n.href : ''));+ expect(linkHrefs).toEqual([+ 'https://example.com',+ 'mailto:[email protected]',+ ]);+ } else {+ throw new Error('expected paragraph block');+ }+ });++ it('streams character-by-character to the same final result', () => {+ const text = 'see https://example.com here and mail [email protected] soon.';+ const state = createIncrementalState();+ let last: BlockNode[] = [];+ for (let i = 1; i <= text.length; i++) {+ last = parseMarkdownIncremental(text.slice(0, i), state, {+ autolink: 'gfm',+ });+ }+ const full = parseMarkdown(text, {autolink: 'gfm'});+ expect(last).toEqual(full);+ });++ it('invalidates the cache when the autolink option toggles', () => {+ const text = 'first https://a.com.\n\nsecond https://b.com.';+ const state = createIncrementalState();+ // Prime cache with autolink off.+ const off = parseMarkdownIncremental(text, state);+ expect(off).toEqual(parseMarkdown(text));+ const noLinks = off.every(+ b =>+ b.type !== 'paragraph' ||+ b.children.every((n: InlineNode) => n.type !== 'link'),+ );+ expect(noLinks).toBe(true);+ // Re-parse same text with autolink on — stale settled blocks must NOT+ // be reused as plain text.+ const on = parseMarkdownIncremental(text, state, {autolink: 'gfm'});+ expect(on).toEqual(parseMarkdown(text, {autolink: 'gfm'}));+ const hasLink = on.some(+ b =>+ b.type === 'paragraph' &&+ b.children.some((n: InlineNode) => n.type === 'link'),+ );+ expect(hasLink).toBe(true);+ // Toggle back off — cache must invalidate again.+ const offAgain = parseMarkdownIncremental(text, state);+ expect(offAgain).toEqual(parseMarkdown(text));+ });+ });});diff --git a/packages/core/src/Markdown/parser.test.ts b/packages/core/src/Markdown/parser.test.tsindex 3360149845..c55e400e70 100644--- a/packages/core/src/Markdown/parser.test.ts+++ b/packages/core/src/Markdown/parser.test.ts@@ -591,4 +591,299 @@ describe('citation parsing', () => {}});});++ describe('autolink (gfm)', () => {+ it('is opt-in: bare URLs stay literal by default', () => {+ const result = parseInline('see https://example.com for info');+ expect(result).toEqual([+ {type: 'text', content: 'see https://example.com for info'},+ ]);+ });++ it('links a bare https URL when enabled', () => {+ const result = parseInline('see https://example.com for info', {+ autolink: 'gfm',+ });+ expect(result).toEqual([+ {type: 'text', content: 'see '},+ {+ type: 'link',+ href: 'https://example.com',+ children: [{type: 'text', content: 'https://example.com'}],+ },+ {type: 'text', content: ' for info'},+ ]);+ });++ it('links a bare http URL', () => {+ const result = parseInline('go to http://example.com', {+ autolink: 'gfm',+ });+ expect(result[1]).toEqual({+ type: 'link',+ href: 'http://example.com',+ children: [{type: 'text', content: 'http://example.com'}],+ });+ });++ it('links a bare www. URL with http:// prefix on href', () => {+ const result = parseInline('go www.example.com', {autolink: 'gfm'});+ expect(result[1]).toEqual({+ type: 'link',+ href: 'http://www.example.com',+ children: [{type: 'text', content: 'www.example.com'}],+ });+ });++ it('links a bare email', () => {+ const result = parseInline('ping [email protected] please', {+ autolink: 'gfm',+ });+ expect(result[1]).toEqual({+ type: 'link',+ href: 'mailto:[email protected]',+ children: [{type: 'text', content: '[email protected]'}],+ });+ });++ it('allows + and % in the email local part', () => {+ const result = parseInline('mail user+tag%[email protected] here', {+ autolink: 'gfm',+ });+ expect(result[1].type).toBe('link');+ if (result[1].type === 'link') {+ expect(result[1].href).toBe('mailto:user+tag%[email protected]');+ }+ });++ it('parses <scheme:url> angle-bracket autolinks', () => {+ const result = parseInline('see <https://example.com> ok', {+ autolink: 'gfm',+ });+ expect(result[1]).toEqual({+ type: 'link',+ href: 'https://example.com',+ children: [{type: 'text', content: 'https://example.com'}],+ });+ });++ it('parses <email> angle-bracket autolinks', () => {+ const result = parseInline('mail <[email protected]> please', {+ autolink: 'gfm',+ });+ expect(result[1]).toEqual({+ type: 'link',+ href: 'mailto:[email protected]',+ children: [{type: 'text', content: '[email protected]'}],+ });+ });++ it('peels trailing sentence punctuation off bare URLs', () => {+ const result = parseInline('see https://example.com.', {+ autolink: 'gfm',+ });+ expect(result).toEqual([+ {type: 'text', content: 'see '},+ {+ type: 'link',+ href: 'https://example.com',+ children: [{type: 'text', content: 'https://example.com'}],+ },+ {type: 'text', content: '.'},+ ]);+ });++ it('peels unbalanced trailing close-parens', () => {+ const result = parseInline('(see https://example.com/foo) here', {+ autolink: 'gfm',+ });+ expect(result).toEqual([+ {type: 'text', content: '(see '},+ {+ type: 'link',+ href: 'https://example.com/foo',+ children: [{type: 'text', content: 'https://example.com/foo'}],+ },+ {type: 'text', content: ') here'},+ ]);+ });++ it('keeps balanced parens inside the URL', () => {+ const result = parseInline('go https://example.com/Foo_(bar) ok', {+ autolink: 'gfm',+ });+ expect(result[1]).toEqual({+ type: 'link',+ href: 'https://example.com/Foo_(bar)',+ children: [{type: 'text', content: 'https://example.com/Foo_(bar)'}],+ });+ });++ it('peels multiple trailing punctuation chars in one pass', () => {+ const result = parseInline('see https://example.com?!.', {+ autolink: 'gfm',+ });+ expect(result).toEqual([+ {type: 'text', content: 'see '},+ {+ type: 'link',+ href: 'https://example.com',+ children: [{type: 'text', content: 'https://example.com'}],+ },+ {type: 'text', content: '?!.'},+ ]);+ });++ it('peels interleaved punct and unbalanced parens', () => {+ const result = parseInline('(https://example.com/path).', {+ autolink: 'gfm',+ });+ expect(result).toEqual([+ {type: 'text', content: '('},+ {+ type: 'link',+ href: 'https://example.com/path',+ children: [{type: 'text', content: 'https://example.com/path'}],+ },+ {type: 'text', content: ').'},+ ]);+ });++ it('peels all trailing punctuation leaving only scheme', () => {+ // "https://..." peels the dots, leaving "https://" as the href.+ // This is a degenerate case but not rejected — the PR intentionally+ // does not validate TLDs or path content.+ const result = parseInline('see https://...', {+ autolink: 'gfm',+ });+ const link = result.find(n => n.type === 'link');+ expect(link).toBeDefined();+ if (link && link.type === 'link') {+ expect(link.href).toBe('https://');+ }+ });++ it('does not autolink URLs inside inline code', () => {+ const result = parseInline('try `https://example.com` here', {+ autolink: 'gfm',+ });+ expect(result).toEqual([+ {type: 'text', content: 'try '},+ {type: 'code', content: 'https://example.com'},+ {type: 'text', content: ' here'},+ ]);+ });++ it('does not nest links: skips URLs inside an existing link', () => {+ const result = parseInline(+ '[my site https://other.com](https://example.com)',+ {autolink: 'gfm'},+ );+ expect(result).toHaveLength(1);+ expect(result[0].type).toBe('link');+ if (result[0].type === 'link') {+ expect(result[0].href).toBe('https://example.com');+ // The label still has the URL as plain text, not a nested link.+ expect(result[0].children).toEqual([+ {type: 'text', content: 'my site https://other.com'},+ ]);+ }+ });++ it('does not autolink the destination of a markdown link', () => {+ const result = parseInline('see [docs](https://example.com)', {+ autolink: 'gfm',+ });+ expect(result).toHaveLength(2);+ expect(result[1].type).toBe('link');+ if (result[1].type === 'link') {+ expect(result[1].href).toBe('https://example.com');+ }+ });++ it('autolinks inside emphasis containers', () => {+ const result = parseInline('see **https://example.com** ok', {+ autolink: 'gfm',+ });+ expect(result[1].type).toBe('bold');+ if (result[1].type === 'bold') {+ expect(result[1].children).toEqual([+ {+ type: 'link',+ href: 'https://example.com',+ children: [{type: 'text', content: 'https://example.com'}],+ },+ ]);+ }+ });++ it('does not match when preceded by an alphanumeric char', () => {+ const result = parseInline('xhttps://example.com', {autolink: 'gfm'});+ expect(result).toEqual([{type: 'text', content: 'xhttps://example.com'}]);+ });++ it('handles multiple autolinks in one block', () => {+ const result = parseInline(+ 'see https://a.com or https://b.com or [email protected]',+ {autolink: 'gfm'},+ );+ const linkHrefs = result+ .filter(n => n.type === 'link')+ .map(n => (n.type === 'link' ? n.href : ''));+ expect(linkHrefs).toEqual([+ 'https://a.com',+ 'https://b.com',+ 'mailto:[email protected]',+ ]);+ });++ it('does not autolink inside fenced code blocks', () => {+ const md = '```\nhttps://example.com\n```';+ const blocks = parseMarkdown(md, {autolink: 'gfm'});+ expect(blocks).toHaveLength(1);+ expect(blocks[0]).toEqual({+ type: 'codeblock',+ language: 'plaintext',+ content: 'https://example.com',+ });+ });++ it('passes through parseMarkdown for headings and paragraphs', () => {+ const md = '# https://heading.com\n\nsee https://para.com here';+ const blocks = parseMarkdown(md, {autolink: 'gfm'});+ expect(blocks).toHaveLength(2);+ if (blocks[0].type === 'heading') {+ expect(blocks[0].children[0]).toEqual({+ type: 'link',+ href: 'https://heading.com',+ children: [{type: 'text', content: 'https://heading.com'}],+ });+ }+ if (blocks[1].type === 'paragraph') {+ expect(blocks[1].children.some(n => n.type === 'link')).toBe(true);+ }+ });++ it('still accepts ReadonlySet<string> sourceIds via legacy signature', () => {+ // Default behavior — no autolink, sourceIds passed positionally+ const sources = new Set(['abc1']);+ const result = parseInline('see [abc1] for https://example.com', sources);+ expect(result.some(n => n.type === 'citation')).toBe(true);+ // Bare URL remains literal text because autolink is unset+ expect(result).toContainEqual({+ type: 'text',+ content: ' for https://example.com',+ });+ });++ it('combines sourceIds + autolink in the options bag', () => {+ const sources = new Set(['abc1']);+ const result = parseInline('see [abc1] for https://example.com', {+ sourceIds: sources,+ autolink: 'gfm',+ });+ expect(result.some(n => n.type === 'citation')).toBe(true);+ expect(result.some(n => n.type === 'link')).toBe(true);+ });+ });});diff --git a/packages/core/src/Markdown/parser.ts b/packages/core/src/Markdown/parser.tsindex e7513b94ca..5a82e17d9a 100644--- a/packages/core/src/Markdown/parser.ts+++ b/packages/core/src/Markdown/parser.ts@@ -47,6 +47,60 @@ export type ListItemNode = {checked?: boolean; children: BlockNode[]};export type TableCellNode = {children: InlineNode[]};export type TableAlignment = 'left' | 'center' | 'right' | null;+// ---------------------------------------------------------------------------+// Parse options+// ---------------------------------------------------------------------------++/**+ * Options for the markdown parser entry points.+ *+ * Backward-compatible: the public `parseMarkdown` / `parseInline` /+ * `parseMarkdownIncremental` functions also accept the legacy+ * `ReadonlySet<string>` shape as the second argument.+ */+export type ParseOptions = {+ /** Set of citation source ids — `[id]` / `【id】` markers in this set+ * become citation nodes instead of plain text / links. */+ sourceIds?: ReadonlySet<string>;+ /**+ * Autolink mode. When set to `'gfm'`, the parser turns bare+ * `https?://…` / `www.…` URLs, `<URL>` / `<email>` angle-bracket+ * forms, and `user@host` emails into `link` inline nodes (per the+ * GitHub Flavored Markdown autolink-literal extension plus the+ * CommonMark §6.5 autolink form). Disabled by default.+ *+ * Two intentional deviations from the strict GFM spec for v1:+ * trailing `&entity;` is not peeled off the URL, and an invalid TLD+ * suffix is not rejected (XDS accepts any plausible TLD shape).+ */+ autolink?: 'gfm';+};++type ResolvedOptions = {+ readonly sourceIds: ReadonlySet<string> | undefined;+ readonly autolink: 'gfm' | undefined;+};++const EMPTY_OPTS: ResolvedOptions = {sourceIds: undefined, autolink: undefined};++function resolveOptions(+ arg: ReadonlySet<string> | ParseOptions | undefined,+): ResolvedOptions {+ if (arg == null) {+ return EMPTY_OPTS;+ }+ // Duck-type the legacy `ReadonlySet<string>` form: any object whose+ // `.has` is callable is treated as the legacy sourceIds set. This is+ // safer than `instanceof Set`, which would misclassify cross-realm+ // or polyfilled `ReadonlySet` implementations as a `ParseOptions` bag+ // and silently lose citation resolution.+ if (typeof (arg as {has?: unknown}).has === 'function') {+ return {sourceIds: arg as ReadonlySet<string>, autolink: undefined};+ }+ const opts = arg as ParseOptions;+ return {sourceIds: opts.sourceIds, autolink: opts.autolink};+}+// ---------------------------------------------------------------------------// Inline parser helpers// ---------------------------------------------------------------------------@@ -85,9 +139,9 @@ function isWordChar(ch: string | undefined): boolean {function matchFullwidthCitation(text: string,i: number,- sourceIds: ReadonlySet<string> | undefined,+ opts: ResolvedOptions,): {sourceId: string; end: number} | null {- if (!sourceIds || text[i] !== '\u3010') {+ if (!opts.sourceIds || text[i] !== '\u3010') {return null;}const closeIndex = text.indexOf('\u3011', i + 1);@@ -95,7 +149,7 @@ function matchFullwidthCitation(return null;}const id = text.slice(i + 1, closeIndex);- if (id.length === 0 || !sourceIds.has(id)) {+ if (id.length === 0 || !opts.sourceIds.has(id)) {return null;}return {sourceId: id, end: closeIndex + 1};@@ -108,9 +162,9 @@ function matchFullwidthCitation(function matchBracketCitation(text: string,i: number,- sourceIds: ReadonlySet<string> | undefined,+ opts: ResolvedOptions,): {sourceId: string; end: number} | null {- if (!sourceIds || text[i] !== '[') {+ if (!opts.sourceIds || text[i] !== '[') {return null;}const closeIndex = text.indexOf(']', i + 1);@@ -121,7 +175,7 @@ function matchBracketCitation(return null;}const id = text.slice(i + 1, closeIndex);- if (id.length === 0 || !sourceIds.has(id)) {+ if (id.length === 0 || !opts.sourceIds.has(id)) {return null;}return {sourceId: id, end: closeIndex + 1};@@ -130,7 +184,30 @@ function matchBracketCitation(export function parseInline(text: string,sourceIds?: ReadonlySet<string>,+): InlineNode[];+export function parseInline(text: string, options: ParseOptions): InlineNode[];+export function parseInline(+ text: string,+ arg?: ReadonlySet<string> | ParseOptions,): InlineNode[] {+ return parseInlineEntry(text, resolveOptions(arg));+}++/**+ * Internal block-level inline entry point: parses, then applies the GFM+ * autolink transform when enabled. Recursive calls inside `parseInlineImpl`+ * (link labels, bold/italic/strikethrough bodies) intentionally bypass this+ * wrapper and call `parseInlineImpl` directly so the transform runs only on+ * the outermost block's inline tree — letting `transformAutolinks` decide+ * which subtrees to descend into (text, bold, italic, strikethrough) and+ * which to skip (link, code, image, citation, break).+ */+function parseInlineEntry(text: string, opts: ResolvedOptions): InlineNode[] {+ const nodes = parseInlineImpl(text, opts);+ return opts.autolink === 'gfm' ? transformAutolinks(nodes) : nodes;+}++function parseInlineImpl(text: string, opts: ResolvedOptions): InlineNode[] {const nodes: InlineNode[] = [];let i = 0;@@ -156,7 +233,7 @@ export function parseInline(// --- Citation: fullwidth 【id】 ---{- const citation = matchFullwidthCitation(text, i, sourceIds);+ const citation = matchFullwidthCitation(text, i, opts);if (citation) {nodes.push({type: 'citation', sourceId: citation.sourceId});i = citation.end;@@ -183,7 +260,7 @@ export function parseInline(// --- Citation: bracket [id] (before link — link requires `(` after `]`) ---{- const citation = matchBracketCitation(text, i, sourceIds);+ const citation = matchBracketCitation(text, i, opts);if (citation) {nodes.push({type: 'citation', sourceId: citation.sourceId});i = citation.end;@@ -200,7 +277,7 @@ export function parseInline(nodes.push({type: 'link',href: text.slice(textClose + 2, urlClose),- children: parseInline(text.slice(i + 1, textClose), sourceIds),+ children: parseInlineImpl(text.slice(i + 1, textClose), opts),});i = urlClose + 1;continue;@@ -228,7 +305,7 @@ export function parseInline(children: [{type: 'italic',- children: parseInline(text.slice(i + 3, closeIndex), sourceIds),+ children: parseInlineImpl(text.slice(i + 3, closeIndex), opts),},],});@@ -255,7 +332,7 @@ export function parseInline() {nodes.push({type: 'bold',- children: parseInline(text.slice(i + 2, closeIndex), sourceIds),+ children: parseInlineImpl(text.slice(i + 2, closeIndex), opts),});i = closeIndex + 2;continue;@@ -269,7 +346,7 @@ export function parseInline(if (closeIndex !== -1) {nodes.push({type: 'strikethrough',- children: parseInline(text.slice(i + 2, closeIndex), sourceIds),+ children: parseInlineImpl(text.slice(i + 2, closeIndex), opts),});i = closeIndex + 2;continue;@@ -290,7 +367,7 @@ export function parseInline() {nodes.push({type: 'italic',- children: parseInline(text.slice(i + 1, closeIndex), sourceIds),+ children: parseInlineImpl(text.slice(i + 1, closeIndex), opts),});i = closeIndex + 1;continue;@@ -335,6 +412,289 @@ export function parseInline(return nodes;}+// ---------------------------------------------------------------------------+// GFM autolink post-pass (opt-in via ParseOptions.autolink === 'gfm')+// ---------------------------------------------------------------------------++// Character classes used in autolink patterns.+const ANY_NON_WHITESPACE_OR_ANGLE = '[^\\s<]+';+const SCHEME = 'https?:\\/\\/';+const EMAIL_LOCAL_PART = '[A-Za-z0-9._%+-]+';+const DOMAIN_LABEL = '[A-Za-z0-9-]+';+const DOMAIN_WITH_DOT = `${DOMAIN_LABEL}(?:\\.${DOMAIN_LABEL})+`;+const ANGLE_SCHEME = '[a-zA-Z][a-zA-Z0-9+.-]*';+const ANGLE_URL_BODY = '[^<>\\s]*';++/** Bare http(s) URL up to whitespace or `<`. Trailing punctuation is peeled afterwards. */+const URL_LITERAL_RE = new RegExp(`${SCHEME}${ANY_NON_WHITESPACE_OR_ANGLE}`, 'g');++/** Bare www. URL. Resulting href gets `http://` prepended. */+const WWW_LITERAL_RE = new RegExp(`www\\.${ANY_NON_WHITESPACE_OR_ANGLE}`, 'g');++/** Bare email: local-part@domain (at least one dot in domain). */+const EMAIL_LITERAL_RE = new RegExp(`${EMAIL_LOCAL_PART}@${DOMAIN_WITH_DOT}`, 'g');++/** Angle-bracket autolink: `<scheme:url>` (CommonMark §6.5). */+const ANGLE_URL_RE = new RegExp(`<(${ANGLE_SCHEME}:${ANGLE_URL_BODY})>`, 'g');++/** Angle-bracket email: `<[email protected]>`. */+const ANGLE_EMAIL_RE = new RegExp(`<(${EMAIL_LOCAL_PART}@${DOMAIN_WITH_DOT})>`, 'g');++/** Characters treated as trailing sentence punctuation per GFM §6.9. */+const TRAILING_PUNCT_CHARS = new Set('?!.,:*_~');++/** Characters valid in an email local part (used for boundary detection). */+const EMAIL_LOCAL_CHARS = new Set(+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._%+-@',+);++interface AutolinkMatch {+ start: number;+ end: number;+ href: string;+ display: string;+}++/**+ * Peel trailing sentence-end punctuation and unbalanced trailing `)` off a+ * bare URL. Mirrors GFM §6.9: `?!.,:*_~` immediately after the URL aren't+ * part of it; a trailing `)` is excluded if there are more `)` than `(` in+ * the candidate (so `(https://example.com)` ends at the second `)` but+ * `https://example.com/Foo_(bar)` keeps the inner pair).+ */+function peelTrailingPunctAndParens(url: string): string {+ let s = url;+ while (s.length > 0) {+ // Peel trailing punctuation characters in one pass.+ if (TRAILING_PUNCT_CHARS.has(s[s.length - 1])) {+ let end = s.length - 1;+ while (end > 0 && TRAILING_PUNCT_CHARS.has(s[end - 1])) {+ end--;+ }+ s = s.slice(0, end);+ continue;+ }+ if (s.endsWith(')')) {+ let open = 0;+ let close = 0;+ for (let idx = 0; idx < s.length; idx++) {+ if (s[idx] === '(') {+ open++;+ } else if (s[idx] === ')') {+ close++;+ }+ }+ if (close > open) {+ s = s.slice(0, -1);+ continue;+ }+ }+ break;+ }+ return s;+}++/** Characters that, when preceding a URL, indicate it's part of a larger token. */+const URL_CONTINUATION_CHARS = new Set(+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/=',+);++/**+ * The character immediately before a bare-URL or bare-www match must not+ * make the URL look like the tail of a larger token (`xhttps`, `=https://`,+ * `/https://`). null means start-of-text — always allowed.+ */+function isUrlBoundaryChar(ch: string | undefined): boolean {+ if (ch == null) {+ return true;+ }+ return !URL_CONTINUATION_CHARS.has(ch);+}++function scanAutolinksInText(text: string): AutolinkMatch[] {+ const matches: AutolinkMatch[] = [];++ // <scheme:url> angle-bracket form+ {+ const re = new RegExp(ANGLE_URL_RE.source, 'g');+ let m: RegExpExecArray | null;+ while ((m = re.exec(text)) !== null) {+ const url = m[1];+ matches.push({+ start: m.index,+ end: m.index + m[0].length,+ href: url,+ display: url,+ });+ }+ }++ // <email> angle-bracket form+ {+ const re = new RegExp(ANGLE_EMAIL_RE.source, 'g');+ let m: RegExpExecArray | null;+ while ((m = re.exec(text)) !== null) {+ const email = m[1];+ matches.push({+ start: m.index,+ end: m.index + m[0].length,+ href: `mailto:${email}`,+ display: email,+ });+ }+ }++ // bare https?:// URL+ {+ const re = new RegExp(URL_LITERAL_RE.source, 'g');+ let m: RegExpExecArray | null;+ while ((m = re.exec(text)) !== null) {+ const prev = text[m.index - 1];+ if (!isUrlBoundaryChar(prev)) {+ continue;+ }+ if (text.slice(m.index - 2, m.index) === '](') {+ continue;+ }+ const cleaned = peelTrailingPunctAndParens(m[0]);+ if (cleaned.length === 0) {+ continue;+ }+ matches.push({+ start: m.index,+ end: m.index + cleaned.length,+ href: cleaned,+ display: cleaned,+ });+ }+ }++ // bare www. URL+ {+ const re = new RegExp(WWW_LITERAL_RE.source, 'g');+ let m: RegExpExecArray | null;+ while ((m = re.exec(text)) !== null) {+ const prev = text[m.index - 1];+ if (!isUrlBoundaryChar(prev)) {+ continue;+ }+ // Don't match inside an https://www… capture from the previous pattern+ if (text.slice(m.index - 3, m.index) === '://') {+ continue;+ }+ const cleaned = peelTrailingPunctAndParens(m[0]);+ if (cleaned.length === 0) {+ continue;+ }+ matches.push({+ start: m.index,+ end: m.index + cleaned.length,+ href: `http://${cleaned}`,+ display: cleaned,+ });+ }+ }++ // bare email+ {+ const re = new RegExp(EMAIL_LITERAL_RE.source, 'g');+ let m: RegExpExecArray | null;+ while ((m = re.exec(text)) !== null) {+ const prev = text[m.index - 1];+ // Reject if previous char could be part of the local part or sits in+ // a position that would make this match continuation of something+ // bigger (`[email protected]@host`, `foo+bar@x`, `mailto:user@host`).+ if (prev != null && EMAIL_LOCAL_CHARS.has(prev)) {+ continue;+ }+ if (text.slice(Math.max(0, m.index - 7), m.index) === 'mailto:') {+ continue;+ }+ matches.push({+ start: m.index,+ end: m.index + m[0].length,+ href: `mailto:${m[0]}`,+ display: m[0],+ });+ }+ }++ // Sort by start; first-match-wins on overlaps so e.g. an angle-bracket+ // <https://x> outranks the bare https://x inside it.+ matches.sort((a, b) => a.start - b.start);+ const resolved: AutolinkMatch[] = [];+ let lastEnd = 0;+ for (const m of matches) {+ if (m.start >= lastEnd) {+ resolved.push(m);+ lastEnd = m.end;+ }+ }+ return resolved;+}++/**+ * Split a text-node `content` string into a sequence of text + link nodes+ * based on autolink matches.+ */+function splitTextOnAutolinks(content: string): InlineNode[] {+ const matches = scanAutolinksInText(content);+ if (matches.length === 0) {+ return [{type: 'text', content}];+ }+ const out: InlineNode[] = [];+ let cursor = 0;+ for (const m of matches) {+ if (m.start > cursor) {+ out.push({type: 'text', content: content.slice(cursor, m.start)});+ }+ out.push({+ type: 'link',+ href: m.href,+ children: [{type: 'text', content: m.display}],+ });+ cursor = m.end;+ }+ if (cursor < content.length) {+ out.push({type: 'text', content: content.slice(cursor)});+ }+ return out;+}++/**+ * Walk an inline-node tree and replace bare URLs / emails inside `text`+ * nodes with `link` nodes. Recurses into emphasis containers+ * (`bold`/`italic`/`strikethrough`) so wrapped URLs link too, but never+ * descends into existing `link` children (no nested links), `code` content,+ * `image` alt text, `citation`, or `break`. Runs only on the outermost+ * block's inline tree (see `parseInlineEntry`).+ */+function transformAutolinks(nodes: InlineNode[]): InlineNode[] {+ const out: InlineNode[] = [];+ for (const node of nodes) {+ if (node.type === 'text') {+ const split = splitTextOnAutolinks(node.content);+ for (const seg of split) {+ const last = out[out.length - 1];+ if (seg.type === 'text' && last?.type === 'text') {+ last.content += seg.content;+ } else {+ out.push(seg);+ }+ }+ } else if (+ node.type === 'bold' ||+ node.type === 'italic' ||+ node.type === 'strikethrough'+ ) {+ out.push({...node, children: transformAutolinks(node.children)});+ } else {+ out.push(node);+ }+ }+ return out;+}+// ---------------------------------------------------------------------------// Block parser helpers// ---------------------------------------------------------------------------@@ -451,10 +811,10 @@ function splitTableRow(line: string): string[] {function parseTable(lines: string[],lineIndex: number,- sourceIds?: ReadonlySet<string>,+ opts: ResolvedOptions,): {node: BlockNode; nextIndex: number} {const headers: TableCellNode[] = splitTableRow(lines[lineIndex]).map(- cell => ({children: parseInline(cell, sourceIds)}),+ cell => ({children: parseInlineEntry(cell, opts)}),);const alignments: TableAlignment[] = splitTableRow(lines[lineIndex + 1]).map(cell => {@@ -479,7 +839,7 @@ function parseTable() {rows.push(splitTableRow(lines[rowIndex]).map(cell => ({- children: parseInline(cell, sourceIds),+ children: parseInlineEntry(cell, opts),})),);rowIndex++;@@ -494,7 +854,7 @@ function parseList(lines: string[],startIndex: number,ordered: boolean,- sourceIds?: ReadonlySet<string>,+ opts: ResolvedOptions,): {node: BlockNode; nextIndex: number} {const items: ListItemNode[] = [];const baseIndent = getIndent(lines[startIndex]);@@ -543,7 +903,7 @@ function parseList(itemText += '\n' + deindented.join('\n');}- items.push({checked, children: parseMarkdown(itemText, sourceIds)});+ items.push({checked, children: parseMarkdownImpl(itemText, opts)});// CommonMark loose list: blank line(s) between items of the same style// and indent still form one list. Skip the blanks and continue if the@@ -574,7 +934,19 @@ function parseList(export function parseMarkdown(input: string,sourceIds?: ReadonlySet<string>,+): BlockNode[];+export function parseMarkdown(+ input: string,+ options: ParseOptions,+): BlockNode[];+export function parseMarkdown(+ input: string,+ arg?: ReadonlySet<string> | ParseOptions,): BlockNode[] {+ return parseMarkdownImpl(input, resolveOptions(arg));+}++function parseMarkdownImpl(input: string, opts: ResolvedOptions): BlockNode[] {const lines = input.split('\n');const blocks: BlockNode[] = [];let index = 0;@@ -608,7 +980,7 @@ export function parseMarkdown(blocks.push({type: 'heading',level: headingMatch[1].length as 1 | 2 | 3 | 4 | 5 | 6,- children: parseInline(headingMatch[2], sourceIds),+ children: parseInlineEntry(headingMatch[2], opts),});index++;continue;@@ -635,7 +1007,7 @@ export function parseMarkdown(line.includes('|') &&isTableSeparator(lines[index + 1])) {- const tableResult = parseTable(lines, index, sourceIds);+ const tableResult = parseTable(lines, index, opts);blocks.push(tableResult.node);index = tableResult.nextIndex;continue;@@ -653,14 +1025,14 @@ export function parseMarkdown(}blocks.push({type: 'blockquote',- children: parseMarkdown(quoteLines.join('\n'), sourceIds),+ children: parseMarkdownImpl(quoteLines.join('\n'), opts),});continue;}// --- Unordered list ---if (/^ {0,9}[-*+] /.test(line)) {- const listResult = parseList(lines, index, false, sourceIds);+ const listResult = parseList(lines, index, false, opts);blocks.push(listResult.node);index = listResult.nextIndex;continue;@@ -668,7 +1040,7 @@ export function parseMarkdown(// --- Ordered list ---if (/^ {0,9}\d+\. /.test(line)) {- const listResult = parseList(lines, index, true, sourceIds);+ const listResult = parseList(lines, index, true, opts);blocks.push(listResult.node);index = listResult.nextIndex;continue;@@ -687,7 +1059,7 @@ export function parseMarkdown(}blocks.push({type: 'paragraph',- children: parseInline(paraLines.join('\n'), sourceIds),+ children: parseInlineEntry(paraLines.join('\n'), opts),});}return blocks;@@ -702,6 +1074,13 @@ export interface IncrementalState {settledText: string;settledBlocks: BlockNode[];settledUpTo: number;+ /**+ * The `autolink` option the cached `settledBlocks` were parsed with.+ * `parseMarkdownIncremental` invalidates the cache when the caller flips+ * this option, so already-settled URLs flip between link/text along+ * with newly-arriving content.+ */+ autolink?: 'gfm';}export function createIncrementalState(): IncrementalState {@@ -1001,7 +1380,28 @@ export function parseMarkdownIncremental(input: string,state: IncrementalState,sourceIds?: ReadonlySet<string>,+): BlockNode[];+export function parseMarkdownIncremental(+ input: string,+ state: IncrementalState,+ options: ParseOptions,+): BlockNode[];+export function parseMarkdownIncremental(+ input: string,+ state: IncrementalState,+ arg?: ReadonlySet<string> | ParseOptions,): BlockNode[] {+ const opts = resolveOptions(arg);+ // Invalidate cache when the autolink option flips — cached settled blocks+ // were parsed with the previous setting and would otherwise be reused+ // unchanged.+ if (state.autolink !== opts.autolink) {+ state.prevInput = '';+ state.settledText = '';+ state.settledBlocks = [];+ state.settledUpTo = 0;+ state.autolink = opts.autolink;+ }if (input === '') {state.prevInput = '';state.settledText = '';@@ -1016,7 +1416,7 @@ export function parseMarkdownIncremental(if (boundary < 0) {// Inside an unclosed fence or no blank-line boundary — full re-parsestate.prevInput = input;- return parseMarkdown(input, sourceIds);+ return parseMarkdownImpl(input, opts);}const settledText = lines.slice(0, boundary).join('\n');@@ -1034,15 +1434,15 @@ export function parseMarkdownIncremental() {// Settled portion grew — parse only the new deltaconst delta = settledText.slice(state.settledText.length);- const deltaBlocks = parseMarkdown(delta, sourceIds);+ const deltaBlocks = parseMarkdownImpl(delta, opts);settledBlocks = mergeSettledBlocks(state.settledBlocks, deltaBlocks);} else {// Content before the boundary changed — full re-parse of settled portion- settledBlocks = parseMarkdown(settledText, sourceIds);+ settledBlocks = parseMarkdownImpl(settledText, opts);}const unsettledBlocks = unsettledText- ? parseMarkdown(unsettledText, sourceIds)+ ? parseMarkdownImpl(unsettledText, opts): [];state.settledText = settledText;