Open History to see the last commit
1import { ThreadId } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import * as Schema from "effect/Schema";
4
5export const THREAD_LINK_PROTOCOL = "t3-thread";
6const THREAD_LINK_HREF_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`;
7// Code comes first in the alternation so a link written inside a code span or fence is skipped.
8const THREAD_LINK_OUTSIDE_CODE =
9 /(?<fence>(`{3,}|~{3,})[\s\S]*?(?:\2|$))|(?<span>(`+)[^\n]*?\4)|\[[^\]\n]*\]\((?<href>t3-thread:\/\/v1\/[^\s)]+)\)/g;
10
11const decodeThreadId = Schema.decodeUnknownOption(ThreadId);
12
13/** The id as written. Thread ids can hold percent escapes of their own, so it is not decoded. */
14export function parseThreadLinkHref(href: string): ThreadId | null {
15 if (!href.startsWith(THREAD_LINK_HREF_PREFIX)) return null;
16 return Option.getOrNull(decodeThreadId(href.slice(THREAD_LINK_HREF_PREFIX.length)));
17}
18
19export function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null {
20 try {
21 const decoded = decodeURIComponent(threadId);
22 return decoded === threadId ? null : Option.getOrNull(decodeThreadId(decoded));
23 } catch {
24 return null;
25 }
26}
27
28export function formatThreadLink(threadId: string, label: string): string {
29 const cleaned = label
30 .replace(/[[\]\\\r\n]/g, " ")
31 .replace(/\s+/g, " ")
32 .trim();
33 return `[${cleaned || threadId}](${THREAD_LINK_HREF_PREFIX}${threadId})`;
34}
35
36export function hasThreadLinks(markdown: string): boolean {
37 return markdown.includes(`](${THREAD_LINK_HREF_PREFIX}`);
38}
39
40export function relabelThreadLinks(
41 markdown: string,
42 title: (threadId: ThreadId) => string | undefined,
43): string {
44 if (!hasThreadLinks(markdown)) return markdown;
45 return markdown.replace(THREAD_LINK_OUTSIDE_CODE, (source, ...args) => {
46 const href = (args.at(-1) as { href?: string }).href;
47 if (href === undefined) return source;
48 const written = parseThreadLinkHref(href);
49 if (written === null) return source;
50 const decoded = percentDecodedThreadLinkId(written);
51 const threadId =
52 title(written) === undefined && decoded !== null && title(decoded) !== undefined
53 ? decoded
54 : written;
55 const label = title(threadId)?.trim();
56 return label ? formatThreadLink(threadId, label) : source;
57 });
58}