Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadLinks.ts

596 lines26.2 KB

1import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import * as Schema from "effect/Schema";
4import type { Nodes } from "mdast";
5import remarkGfm from "remark-gfm";
6import remarkParse from "remark-parse";
7import { unified, type Processor } from "unified";
8​
9import { DEFAULT_HOSTED_APP_URL } from "./connectAuth.ts";
10​
11export const THREAD_LINK_PROTOCOL = "t3-thread";
12const V1_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`;
13const V2_PREFIX = `${THREAD_LINK_PROTOCOL}://v2/`;
14const HOSTED_PREFIX = `${DEFAULT_HOSTED_APP_URL}/threads/`;
15const HOSTED_SEGMENT = "[A-Za-z0-9_%-]+(?:\\.+[A-Za-z0-9_%-]+)*";
16const HOSTED_LINK = `${HOSTED_PREFIX.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}${HOSTED_SEGMENT}/${HOSTED_SEGMENT}`;
17const THREAD_HREF = String.raw`t3-thread:\/\/v[12]\/`;
18// Unescaped brackets end a label, so consecutive unclosed brackets cannot restart a long scan.
19const LABEL = String.raw`(?:\\[^\n]|[^\\[\]\n])*`;
20const FLAT_LABEL = new RegExp(`^${LABEL}$`);
21const LIST_MARKERS = String.raw`(?:(?:[-*+]|\d{1,9}[.)])[ \t]+)*`;
22const QUOTE_PREFIX = new RegExp(String.raw`^([ \t]*${LIST_MARKERS})(>(?:[ \t]*>)+)`, "gm");
23// Move inter-marker spacing before the quote so fence depth matches and offsets stay intact. A label
24// may span \r or U+2028, which multiline `^` follows, so labels and output are read from the original.
25const threadLinkSource = (markdown: string) =>
26 markdown.replace(QUOTE_PREFIX, (_source, indent: string, quote: string) => {
27 const markers = quote.replace(/[ \t]/g, "");
28 return indent + " ".repeat(quote.length - markers.length) + markers;
29 });
30// CommonMark fences start on their own line (optional blockquotes, indentation, or list markers)
31// and close on a line with at least as many of the same marker; backtick info strings hold no `.
32// Quote markers are compared from the first `>`, so lines may indent them differently.
33// Space after the markers is matched only after a `>`: two adjacent `[ \t]*` backtrack quadratically.
34const AFTER_QUOTE = String.raw`(?:(?<=>)[ \t]*)?`;
35const OPENER_LIST_MARKERS = String.raw`(?:(?:[-*+]|\d{1,9}[.)])[ \t]{1,4}(?![ \t]))*`;
36const fencedCode = (char: "`" | "~", name: string) => {
37 const bq = `${name}Bq`;
38 const info = char === "`" ? "[^`\\r\\n]*" : "[^\\r\\n]*";
39 const closer = String.raw`[ \t]*\k<${bq}>${AFTER_QUOTE}\k<${name}>${char}*(?!${char})[ \t]*\r?$`;
40 return String.raw`^[ \t]*${OPENER_LIST_MARKERS}(?<${bq}>(?:>(?:[ \t]*>)*)?)(?:(?<=>)[ \t]{0,4}(?![ \t])${OPENER_LIST_MARKERS})?(?<${name}>${char}{3,}(?!${char}))${info}(?=\r?$)(?:(?:\r\n?|\n)(?!${closer})[ \t]*\k<${bq}>[^\r\n]*)*(?:(?:\r\n?|\n)${closer})?`;
41};
42// A code span may wrap lines until its paragraph ends: a blank line, heading, list item, fence, rule,
43// setext underline, or deeper blockquote.
44const SPAN_BREAK_LINE =
45 /[ \t>]*(?:\r?$|#{1,6}(?:[ \t]|\r?$)|(?:[-*+]|\d{1,9}[.)])[ \t]|`{3,}[^`\r\n]*\r?$|~{3,})/my;
46const LINE_PREFIX = /([ \t]*)(>|(?:[-*+]|\d{1,9}[.)])[ \t]+)?/y;
47const THEMATIC_BREAK = /^(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})\r?$/;
48const SETEXT_UNDERLINE = /^(?:-+|=+)[ \t]*\r?$/;
49// Earlier alternatives claim text so later ones cannot match inside it: an escaped character opens
50// nothing, code is literal, and a link to anywhere else keeps a thread URL in its label or href.
51const ESCAPED_CHARACTER = String.raw`\\[!-/:-@[-\`{-~]`;
52const LABEL_MARKER = new RegExp(String.raw`${ESCAPED_CHARACTER}|[[\]\n<\`]`, "g");
53// A labeled link's destination may be angle-bracketed, as CommonMark allows: [label](<href>).
54const DESTINATION_PADDING = String.raw`[ \t]*(?:(?:\r\n?|\n)[ \t]*)?`;
55const DESTINATION_END = String.raw`${DESTINATION_PADDING}\)`;
56const PADDED_DESTINATION_END = new RegExp(`^${DESTINATION_END}`);
57const THREAD_DESTINATION = String.raw`(?:(?:<(?<angleHref>${THREAD_HREF}[^\s<>]+|${HOSTED_LINK})>|(?<href>${HOSTED_LINK}))${DESTINATION_END}|(?<customHref>${THREAD_HREF}))`;
58const PARSED_THREAD_DESTINATION = new RegExp(`^${THREAD_DESTINATION}`);
59const TITLE_BREAK = String.raw`(?:\r\n?|\n)(?![ \t]*(?:\r|\n))`;
60const titleChars = (forbidden: string) =>
61 String.raw`(?:\\(?:[^\r\n]|(?=\r|\n))|[^${forbidden}\\\r\n]|${TITLE_BREAK})*`;
62const LINK_TITLE = String.raw`(?:"${titleChars('"')}"|'${titleChars("'")}'|\(${titleChars("()")}\))`;
63const TITLE_SEPARATOR = String.raw`(?=[ \t\r\n])${DESTINATION_PADDING}`;
64const LINK_TITLE_END = new RegExp(`^${TITLE_SEPARATOR}${LINK_TITLE}${DESTINATION_END}`);
65const LINK_PATTERNS = [
66 String.raw`\[(?<label>${LABEL})\]\(${DESTINATION_PADDING}${THREAD_DESTINATION}`,
67 // A bare destination is read by readDestination, which balances nested parentheses and escapes.
68 String.raw`\[${LABEL}\]\((?:${DESTINATION_PADDING}(?:<[^<>\r\n]*>(?:${TITLE_SEPARATOR}${LINK_TITLE})?${DESTINATION_END}|${LINK_TITLE}${DESTINATION_END}|(?<siteHref>(?=[^\s)])))|${DESTINATION_END})`,
69 String.raw`<(?<autolink>${THREAD_HREF}[^\s<>]+|${HOSTED_LINK})>`,
70 // After a URL character the hosted link is part of a longer URL, such as a redirect target.
71 String.raw`(?<![A-Za-z0-9%/?#=&@+-])(?<bare>${HOSTED_LINK})(?!\.*[\w%/?#-])`,
72].join("|");
73const THREAD_LINK = new RegExp(`${ESCAPED_CHARACTER}|${LINK_PATTERNS}`, "gm");
74const THREAD_LINK_OUTSIDE_CODE = new RegExp(
75 [
76 ESCAPED_CHARACTER,
77 fencedCode("`", "bt"),
78 fencedCode("~", "tl"),
79 String.raw`(?<spanTicks>\`+)`,
80 LINK_PATTERNS,
81 ].join("|"),
82 "gm",
83);
84​
85function codeSpanLines(markdown: string) {
86 const lines: Array<{ start: number; depth: number; breaksSpan: boolean }> = [];
87 const listIndents: number[] = [];
88 let paragraphDepth: number | undefined;
89 let start = 0;
90 for (const rawLine of markdown.split(/(?<=\n)|(?<=\r)(?!\n)/u)) {
91 const line = rawLine.replace(/[\r\n]+$/u, "");
92 let offset = 0;
93 let depth = 0;
94 let hasList = false;
95 let listOffset = 0;
96 while (offset < line.length) {
97 LINE_PREFIX.lastIndex = offset;
98 const prefix = LINE_PREFIX.exec(line);
99 if (prefix === null) break;
100 const indent = prefix[1]!.replace(/\t/g, " ").length;
101 if (
102 listOffset === 0 &&
103 paragraphDepth === undefined &&
104 indent < (listIndents[depth] ?? 0) &&
105 line.trim()
106 ) {
107 listIndents.length = depth;
108 }
109 const containerIndent = listIndents[depth] ?? 0;
110 const continuedIndent = indent >= containerIndent ? containerIndent : 0;
111 if (prefix[2] === undefined || indent - continuedIndent > 3) break;
112 offset = LINE_PREFIX.lastIndex;
113 if (prefix[2] === ">") {
114 depth++;
115 listOffset = 0;
116 if (line[offset] === " " || line[offset] === "\t") offset++;
117 } else {
118 listOffset += indent + prefix[2]!.replace(/\t/g, " ").length;
119 listIndents[depth] = listOffset;
120 hasList = true;
121 }
122 }
123 const content = line.slice(offset);
124 const text = content.trimStart();
125 const indent = content.slice(0, content.length - text.length).replace(/\t/g, " ").length;
126 const containerIndent = hasList ? 0 : (listIndents[depth] ?? 0);
127 const lazy = indent < containerIndent || depth < (paragraphDepth ?? 0);
128 // Rules and setext underlines end a paragraph unless indented as code; a lazy line is never an underline.
129 const breaksSpan =
130 !hasList &&
131 (lazy ? indent : indent - containerIndent) <= 3 &&
132 (THEMATIC_BREAK.test(text) ||
133 (paragraphDepth !== undefined && !lazy && SETEXT_UNDERLINE.test(text)));
134 const endsParagraph =
135 breaksSpan ||
136 /^(?:[ \t\r]*$|[ \t]*#{1,6}(?:[ \t]|$)|[ \t]*`{3,}[^`]*$|[ \t]*~{3,})/.test(content);
137 const effectiveDepth = endsParagraph || hasList ? depth : Math.max(depth, paragraphDepth ?? 0);
138 lines.push({ start, depth: effectiveDepth, breaksSpan });
139 paragraphDepth = endsParagraph ? undefined : effectiveDepth;
140 start += rawLine.length;
141 }
142 return lines;
144​
145function findCodeSpanEnd(
146 markdown: string,
147 openIndex: number,
148 tickCount: number,
149 lines: ReturnType<typeof codeSpanLines>,
150 lineIndex: number,
151): number {
152 const openDepth = lines[lineIndex]!.depth;
153 for (let i = openIndex + tickCount; i < markdown.length; i++) {
154 if (markdown[i] === "`") {
155 let runEnd = i + 1;
156 while (markdown[runEnd] === "`") runEnd++;
157 if (runEnd - i === tickCount) return runEnd;
158 i = runEnd - 1;
159 } else if (i + 1 === lines[lineIndex + 1]?.start) {
160 lineIndex++;
161 SPAN_BREAK_LINE.lastIndex = i + 1;
162 const line = lines[lineIndex]!;
163 if (SPAN_BREAK_LINE.test(markdown) || line.breaksSpan || line.depth > openDepth) return -1;
164 }
165 }
166 return -1;
168​
169const decodeThreadId = Schema.decodeUnknownOption(ThreadId);
170const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId);
171​
172/** A v1 link names no environment; the message's own, or a unique match, stands in. */
173export interface ThreadLink {
174 readonly environmentId: EnvironmentId | null;
175 readonly threadId: ThreadId;
176 readonly hosted?: boolean;
178​
179// Escapes even URL-safe punctuation, so a sentence's closing period never reads as part of an id.
180const hostedSegment = (id: string) =>
181 encodeURIComponent(id).replace(
182 /[.!~*'()]/g,
183 (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
184 );
185​
186/** Opens the thread from anywhere: the hosted app offers the desktop app, the mobile app, or itself. */
187export function hostedThreadLink(ref: ScopedThreadRef, origin = DEFAULT_HOSTED_APP_URL): string {
188 const path = `/threads/${hostedSegment(ref.environmentId)}/${hostedSegment(ref.threadId)}`;
189 return new URL(path, origin).toString();
191​
192const HOSTED_PATH = new RegExp(`^(${HOSTED_SEGMENT})/(${HOSTED_SEGMENT})$`);
193​
194function parseHostedThreadLink(href: string): ThreadLink | null {
195 const match = HOSTED_PATH.exec(href.slice(HOSTED_PREFIX.length));
196 if (!match) return null;
197 try {
198 const environmentId = Option.getOrNull(decodeEnvironmentId(decodeURIComponent(match[1]!)));
199 const threadId = Option.getOrNull(decodeThreadId(decodeURIComponent(match[2]!)));
200 return environmentId === null || threadId === null
201 ? null
202 : { environmentId, threadId, hosted: true };
203 } catch {
204 return null;
205 }
207​
208/**
209 * The ids as written. Thread ids can hold percent escapes of their own, so they are not decoded,
210 * except in a hosted link, which escapes them itself.
211 */
212export function parseThreadLinkHref(href: string): ThreadLink | null {
213 if (href.startsWith(HOSTED_PREFIX)) return parseHostedThreadLink(href);
214 if (href.startsWith(V1_PREFIX)) {
215 const threadId = Option.getOrNull(decodeThreadId(href.slice(V1_PREFIX.length)));
216 return threadId === null ? null : { environmentId: null, threadId };
217 }
218 if (!href.startsWith(V2_PREFIX)) return null;
219 const path = href.slice(V2_PREFIX.length);
220 const slash = path.indexOf("/");
221 if (slash < 0) return null;
222 const environmentId = Option.getOrNull(decodeEnvironmentId(path.slice(0, slash)));
223 const threadId = Option.getOrNull(decodeThreadId(path.slice(slash + 1)));
224 return environmentId === null || threadId === null ? null : { environmentId, threadId };
226​
227function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null {
228 try {
229 const decoded = decodeURIComponent(threadId);
230 return decoded === threadId ? null : Option.getOrNull(decodeThreadId(decoded));
231 } catch {
232 return null;
233 }
235​
236/** The threads a link can name, in its own environment or else the message's: as written, then decoded for custom-scheme links. */
237export function threadLinkCandidates(
238 link: ThreadLink,
239 messageEnvironmentId: EnvironmentId,
240): ReadonlyArray<ScopedThreadRef> {
241 const environmentId = link.environmentId ?? messageEnvironmentId;
242 const written = { environmentId, threadId: link.threadId };
243 if (link.hosted) return [written];
244 const decodedId = percentDecodedThreadLinkId(link.threadId);
245 return decodedId === null ? [written] : [written, { environmentId, threadId: decodedId }];
247​
248/** A v1 link its message's environment lacks opens a unique match elsewhere; a v2 link never does. */
249export function guessThreadLinkRef(
250 link: ThreadLink,
251 refs: ReadonlyArray<ScopedThreadRef>,
252): ScopedThreadRef | null {
253 if (link.environmentId !== null) return null;
254 const decodedId = percentDecodedThreadLinkId(link.threadId);
255 for (const threadId of decodedId === null ? [link.threadId] : [link.threadId, decodedId]) {
256 let match: ScopedThreadRef | null = null;
257 for (const ref of refs) {
258 if (ref.threadId !== threadId) continue;
259 if (match !== null) return null;
260 match = ref;
261 }
262 if (match !== null) return match;
263 }
264 return null;
266​
267// A Markdown destination cannot hold these verbatim. v2 ids are written unescaped, so those links
268// become hosted links, which escape; v1 ids may be escaped because their readers also try decoding.
269const UNSAFE_HREF = /[\s<>\\\p{Cc}]/u;
270​
271function threadLinkHref({ environmentId, threadId }: ThreadLink): string {
272 if (environmentId === null) {
273 return V1_PREFIX + (UNSAFE_HREF.test(threadId) ? encodeURIComponent(threadId) : threadId);
274 }
275 // A v2 link splits at its first slash, so an environment id holding one cannot be written there.
276 return environmentId.includes("/") || UNSAFE_HREF.test(environmentId + threadId)
277 ? hostedThreadLink({ environmentId, threadId })
278 : `${V2_PREFIX}${environmentId}/${threadId}`;
280​
281const linkLabel = (label: string | undefined) =>
282 label
283 ?.replace(/[[\]\\\r\n]/g, " ")
284 .replace(/\s+/g, " ")
285 .trim();
286​
287/** Without a label, an autolink: clients show the thread's current title. */
288export function formatThreadLink(ref: ThreadLink, label?: string): string {
289 const cleaned = linkLabel(label);
290 const href = threadLinkHref(ref);
291 const destination = /[()]/.test(href) ? `<${href}>` : href;
292 return cleaned ? `[${cleaned}](${destination})` : `<${href}>`;
294​
295/** What a person copies out of T3 Code: a Markdown link that opens the thread anywhere. */
296export function formatHostedThreadLink(
297 ref: ScopedThreadRef,
298 label: string,
299 origin?: string,
300): string {
301 const href = hostedThreadLink(ref, origin);
302 const cleaned = linkLabel(label);
303 return cleaned ? `[${cleaned}](${href})` : href;
305​
306export function hasThreadLinks(markdown: string): boolean {
307 return markdown.includes(`${THREAD_LINK_PROTOCOL}://v`) || markdown.includes(HOSTED_PREFIX);
309​
310/** Every thread the markdown's links can name, so their titles are keyed reads. */
311export function threadLinkRefs(
312 markdown: string,
313 messageEnvironmentId: EnvironmentId,
314): ReadonlyArray<ScopedThreadRef> {
315 const refs = new Map<string, ScopedThreadRef>();
316 replaceThreadLinks(markdown, (link) => {
317 for (const ref of threadLinkCandidates(link, messageEnvironmentId)) {
318 refs.set(`${ref.environmentId}/${ref.threadId}`, ref);
319 }
320 return undefined;
321 });
322 return [...refs.values()];
324​
325const resourceStarts = new WeakMap<Nodes, number>();
326const destinationRanges = new WeakMap<Nodes, { start: number; end: number }>();
327​
328function recordLinkPositions(this: Processor) {
329 (this.data().fromMarkdownExtensions ??= []).push({
330 enter: {
331 resourceDestination(token) {
332 const node = this.stack.at(-1);
333 const { start, end } = token;
334 if (
335 (node?.type === "link" || node?.type === "image") &&
336 start.offset !== undefined &&
337 end.offset !== undefined
338 ) {
339 destinationRanges.set(node, { start: start.offset, end: end.offset });
340 }
341 },
342 resource(token) {
343 const node = this.stack.at(-1);
344 if ((node?.type === "link" || node?.type === "image") && token.start.offset !== undefined) {
345 resourceStarts.set(node, token.start.offset);
346 }
347 },
348 },
349 });
351​
352// GFM like the chat renderer, so footnotes and other GFM containers hold prose, not code.
353const markdownParser = unified().use(remarkParse).use(remarkGfm).use(recordLinkPositions);
354const commonMarkParser = unified().use(remarkParse).use(recordLinkPositions);
355const INDENTED_CODE_LINE = /^[ \t>*+\-\d.)]*(?: {4}|\t)/m;
356const FENCE_LIKE_LINE = /^[ \t>*+\-\d.)]*(?:`{3}|~{3})/m;
357const LIST_ITEM_LINE = /^[ \t>]*(?:[-*+]|\d{1,9}[.)])(?:[ \t]|\r?$)/m;
358​
359function mayHaveComplexLabel(markdown: string) {
360 if (!markdown.includes("](")) return false;
361 const markers = new RegExp(LABEL_MARKER);
362 let previousBracket: string | undefined;
363 let complex = false;
364 for (let match = markers.exec(markdown); match !== null; match = markers.exec(markdown)) {
365 const marker = match[0];
366 if (marker.length !== 1) continue;
367 if (marker === "[" || marker === "]") {
368 if (marker === previousBracket) return true;
369 if (marker === "]" && markdown[markers.lastIndex] === "(") {
370 if (complex) return true;
371 previousBracket = undefined;
372 continue;
373 }
374 previousBracket = marker;
375 } else if (previousBracket !== undefined) {
376 // Line breaks and inline HTML or code can make bracket order alone misleading.
377 complex = true;
378 }
379 }
380 return false;
382​
383function parseMarkdown(markdown: string) {
384 // GFM walks the tree recursively. Plain CommonMark can still parse deeply nested input.
385 for (const parser of [markdownParser, commonMarkParser]) {
386 try {
387 return parser.parse(markdown);
388 } catch (error) {
389 if (!(error instanceof RangeError)) throw error;
390 }
391 }
392 return undefined;
394​
395// An HTML tag's attribute may hold a backtick, which must not open a code span, or a thread URL,
396// which must stay literal. As in CommonMark, escapes and code are read left to right first, so
397// only real tags are masked.
398const HTML_TAG_SCAN = new RegExp(
399 String.raw`${ESCAPED_CHARACTER}|${fencedCode("`", "bt")}|${fencedCode("~", "tl")}|(?<ticks>\`+)|<[A-Za-z][A-Za-z0-9-]*(?:\s+[A-Za-z_:][\w.:-]*(?:\s*=\s*(?:[^\s"'=<>\`]+|'[^']*'|"[^"]*"))?)*\s*\/?>`,
400 "gm",
401);
402​
403// Masks whole tags, keeping offsets and line breaks. `;` is not a URL character to `bare`, so a
404// bare URL touching a masked tag still matches.
405function maskHtmlTags(markdown: string) {
406 if (!/<[A-Za-z][A-Za-z0-9-]*\s/.test(markdown)) return markdown;
407 const pattern = new RegExp(HTML_TAG_SCAN);
408 let lines: ReturnType<typeof codeSpanLines> | undefined;
409 let lineIndex = 0;
410 let masked = "";
411 let cursor = 0;
412 for (let match = pattern.exec(markdown); match !== null; match = pattern.exec(markdown)) {
413 const ticks = match.groups?.ticks;
414 if (ticks !== undefined) {
415 lines ??= codeSpanLines(markdown);
416 while (lineIndex + 1 < lines.length && lines[lineIndex + 1]!.start <= match.index)
417 lineIndex++;
418 const spanEnd = findCodeSpanEnd(markdown, match.index, ticks.length, lines, lineIndex);
419 if (spanEnd !== -1) pattern.lastIndex = spanEnd;
420 } else if (match[0].startsWith("<") && (match[0].includes("`") || hasThreadLinks(match[0]))) {
421 masked += markdown.slice(cursor, match.index) + match[0].replace(/[^\r\n]/g, ";");
422 cursor = pattern.lastIndex;
423 }
424 }
425 return masked + markdown.slice(cursor);
427​
428function parsedLinkSource(markdown: string) {
429 const text = maskHtmlTags(markdown);
430 // Parse only when an indented line could be code, when a list could end an unclosed fence,
431 // when a footnote or link reference definition may appear, or when a label may exceed the flat scanner.
432 const scanCode =
433 markdown.includes("]:") ||
434 INDENTED_CODE_LINE.test(markdown) ||
435 (text !== markdown && FENCE_LIKE_LINE.test(markdown)) ||
436 (LIST_ITEM_LINE.test(markdown) && FENCE_LIKE_LINE.test(markdown));
437 const scanLabels = mayHaveComplexLabel(markdown);
438 const source = threadLinkSource(text);
439 const links = new Map<number, { end: number; href: string | undefined; label: string }>();
440 if (!scanCode && !scanLabels) return { text, source, links, skippedRanges: undefined };
441​
442 const root = parseMarkdown(markdown);
443 if (!root) return { text, source, links, skippedRanges: undefined };
444​
445 const skippedRanges = scanCode ? new Array<{ start: number; end: number }>() : undefined;
446 let lines: ReturnType<typeof codeSpanLines> | undefined;
447 let lineIndex = 0;
448 const pending: Nodes[] = [root];
449 while (pending.length > 0) {
450 const node = pending.pop()!;
451 const start = node.position?.start.offset;
452 const end = node.position?.end.offset;
453 if (
454 node.type === "code" ||
455 node.type === "inlineCode" ||
456 node.type === "definition" ||
457 node.type === "linkReference" ||
458 node.type === "imageReference"
459 ) {
460 if (start !== undefined && end !== undefined) skippedRanges?.push({ start, end });
461 continue;
462 }
463 if (node.type === "html" && skippedRanges && start !== undefined && end !== undefined) {
464 // A raw HTML block has no inlineCode nodes; keep the flat scanner's code spans inside it.
465 lines ??= codeSpanLines(text);
466 // Bounded to the node: a span never leaves its block, and later blocks are not rescanned.
467 const block = text.slice(0, end);
468 const ticks = new RegExp(String.raw`${ESCAPED_CHARACTER}|\`+`, "g");
469 ticks.lastIndex = start;
470 for (let match = ticks.exec(block); match; match = ticks.exec(block)) {
471 if (match[0][0] !== "`") continue;
472 while (lineIndex + 1 < lines.length && lines[lineIndex + 1]!.start <= match.index)
473 lineIndex++;
474 const spanEnd = findCodeSpanEnd(block, match.index, match[0].length, lines, lineIndex);
475 if (spanEnd === -1) continue;
476 skippedRanges.push({ start: match.index, end: spanEnd });
477 ticks.lastIndex = spanEnd;
478 }
479 continue;
480 }
481 if (scanLabels && (node.type === "link" || node.type === "image")) {
482 const resource = resourceStarts.get(node);
483 if (start !== undefined && end !== undefined && resource !== undefined) {
484 const opening = node.type === "image" ? start + 1 : start;
485 const label = markdown.slice(opening + 1, resource - 1);
486 if (!FLAT_LABEL.test(label)) {
487 // Keep the image's leading !, matching the existing flat-label behavior.
488 const range = destinationRanges.get(node);
489 const href =
490 node.title == null && range
491 ? readParsedThreadDestination(markdown.slice(range.start, range.end), node.url)
492 : undefined;
493 links.set(opening, { end, href, label });
494 continue;
495 }
496 }
497 }
498 if ("children" in node) {
499 for (let index = node.children.length - 1; index >= 0; index--) {
500 pending.push(node.children[index]!);
501 }
502 }
503 }
504 return { text, source: scanCode ? text : source, links, skippedRanges };
506​
507function readDestination(markdown: string, match: RegExpExecArray) {
508 const start = match.index + match[0].length - (match.groups!.customHref?.length ?? 0);
509 for (let i = start, depth = 0; i < markdown.length; i++) {
510 const ch = markdown[i]!;
511 if (ch === "\\" && /[!-/:-@[-`{-~]/.test(markdown[i + 1] ?? "")) i++;
512 // micromark rejects deeper nesting; the cap also bounds rescans of repeated `[x](` openers.
513 else if (ch === "(" && ++depth > 32) break;
514 else if (ch === ")" && depth-- === 0)
515 return { href: markdown.slice(start, i).replace(/\\([!-/:-@[-`{-~])/g, "$1"), end: i + 1 };
516 else if (/[\s\p{Cc}]/u.test(ch)) {
517 const padding = depth === 0 ? PADDED_DESTINATION_END.exec(markdown.slice(i)) : null;
518 if (padding)
519 return {
520 href: markdown.slice(start, i).replace(/\\([!-/:-@[-`{-~])/g, "$1"),
521 end: i + padding[0].length,
522 };
523 const skip = depth === 0 ? LINK_TITLE_END.exec(markdown.slice(i)) : null;
524 return { href: undefined, end: skip ? i + skip[0].length : match.index + 1 };
525 }
526 }
527 return { href: undefined, end: match.index + 1 };
529​
530function readParsedThreadDestination(destination: string, decoded: string) {
531 // Hosted URLs allow Markdown escapes. Custom-scheme IDs keep their literal spelling.
532 if (decoded.startsWith(HOSTED_PREFIX)) return decoded;
533 const source = destination + ")";
534 const match = PARSED_THREAD_DESTINATION.exec(source);
535 return match?.groups?.customHref ? readDestination(source, match).href : match?.groups?.angleHref;
537​
538/** Rewrites each link outside code `replace` answers for. `label` is a Markdown link's own text. */
539export function replaceThreadLinks(
540 markdown: string,
541 replace: (link: ThreadLink, label: string | undefined) => string | undefined,
542): string {
543 if (!hasThreadLinks(markdown)) return markdown;
544 // A leading BOM is not content: Markdown blocks such as fences start after it.
545 if (markdown.startsWith("\uFEFF"))
546 return `\uFEFF${replaceThreadLinks(markdown.slice(1), replace)}`;
547 // Hermes' matchAll yields matches without `groups`; exec keeps them.
548 const { text, source, links, skippedRanges } = parsedLinkSource(markdown);
549 const basePattern = skippedRanges ? THREAD_LINK : THREAD_LINK_OUTSIDE_CODE;
550 const pattern = new RegExp(
551 links.size ? String.raw`${basePattern.source}|\[` : basePattern.source,
552 "gm",
553 );
554 let result = "";
555 let cursor = 0;
556 let lines: ReturnType<typeof codeSpanLines> | undefined;
557 let lineIndex = 0;
558 let rangeIndex = 0;
559 for (let match = pattern.exec(source); match !== null; match = pattern.exec(source)) {
560 while (skippedRanges?.[rangeIndex] && skippedRanges[rangeIndex]!.end <= match.index) {
561 rangeIndex++;
562 }
563 const range = skippedRanges?.[rangeIndex];
564 if (range && range.start <= match.index) {
565 pattern.lastIndex = range.end;
566 continue;
567 }
568 const spanTicks = match.groups?.spanTicks;
569 if (spanTicks !== undefined) {
570 lines ??= codeSpanLines(text);
571 while (lineIndex + 1 < lines.length && lines[lineIndex + 1]!.start <= match.index)
572 lineIndex++;
573 const spanEnd = findCodeSpanEnd(text, match.index, spanTicks.length, lines, lineIndex);
574 if (spanEnd !== -1) pattern.lastIndex = spanEnd;
575 continue;
576 }
577 const parsed = links.get(match.index);
578 let href =
579 match.groups?.angleHref ?? match.groups?.href ?? match.groups?.autolink ?? match.groups?.bare;
580 if (parsed) ({ href, end: pattern.lastIndex } = parsed);
581 else if (match.groups?.customHref)
582 ({ href, end: pattern.lastIndex } = readDestination(markdown, match));
583 else if (match.groups?.siteHref !== undefined)
584 pattern.lastIndex = readDestination(markdown, match).end;
585 const link = href === undefined ? null : parseThreadLinkHref(href);
586 const flatLabel = match.groups?.label;
587 const label =
588 parsed?.label ??
589 (flatLabel && markdown.slice(match.index + 1, match.index + 1 + flatLabel.length));
590 const rewritten = link === null ? undefined : replace(link, label);
591 if (rewritten === undefined) continue;
592 result += markdown.slice(cursor, match.index) + rewritten;
593 cursor = pattern.lastIndex;
594 }
595 return cursor === 0 ? markdown : result + markdown.slice(cursor);