Open History to see the last commit
1import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import * as Schema from "effect/Schema";
4
5import { DEFAULT_HOSTED_APP_URL } from "./connectAuth.ts";
6
7export const THREAD_LINK_PROTOCOL = "t3-thread";
8const V1_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`;
9const V2_PREFIX = `${THREAD_LINK_PROTOCOL}://v2/`;
10const HOSTED_PREFIX = `${DEFAULT_HOSTED_APP_URL}/threads/`;
11const HOSTED_SEGMENT = "[A-Za-z0-9_%-]+";
12const HOSTED_LINK = `${HOSTED_PREFIX.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}${HOSTED_SEGMENT}/${HOSTED_SEGMENT}`;
13const THREAD_HREF = String.raw`t3-thread:\/\/v[12]\/`;
14// A label stops at any bracket, so a run of unclosed brackets is scanned once, not once per bracket.
15const LABEL = String.raw`[^[\]\n]*`;
16const LIST_MARKERS = String.raw`(?:(?:[-*+]|\d{1,9}[.)])[ \t]+)*`;
17const QUOTE_PREFIX = new RegExp(String.raw`^([ \t]*${LIST_MARKERS})(>(?:[ \t]*>)+)`, "gm");
18// Move inter-marker spacing before the quote so fence depth matches and offsets stay intact. A label
19// may span \r or U+2028, which multiline `^` follows, so labels and output are read from the original.
20const threadLinkSource = (markdown: string) =>
21 markdown.replace(QUOTE_PREFIX, (_source, indent: string, quote: string) => {
22 const markers = quote.replace(/[ \t]/g, "");
23 return indent + " ".repeat(quote.length - markers.length) + markers;
24 });
25// CommonMark fences start on their own line (optional blockquotes, indentation, or list markers)
26// and close on a line with at least as many of the same marker; backtick info strings hold no `.
27// Quote markers are compared from the first `>`, so lines may indent them differently.
28// Space after the markers is matched only after a `>`: two adjacent `[ \t]*` backtrack quadratically.
29const AFTER_QUOTE = String.raw`(?:(?<=>)[ \t]*)?`;
30const fencedCode = (char: "`" | "~", name: string) => {
31 const bq = `${name}Bq`;
32 const info = char === "`" ? "[^`\\r\\n]*" : "[^\\r\\n]*";
33 const closer = String.raw`[ \t]*\k<${bq}>${AFTER_QUOTE}\k<${name}>${char}*(?!${char})[ \t]*\r?$`;
34 return String.raw`^[ \t]*${LIST_MARKERS}(?<${bq}>(?:>(?:[ \t]*>)*)?)(?:(?<=>)[ \t]*${LIST_MARKERS})?(?<${name}>${char}{3,}(?!${char}))${info}(?=\r?$)(?:(?:\r\n?|\n)(?!${closer})[ \t]*\k<${bq}>[^\r\n]*)*(?:(?:\r\n?|\n)${closer})?`;
35};
36// A code span may wrap lines until its paragraph ends: a blank line, heading, list item, fence, rule,
37// setext underline, or deeper blockquote.
38const SPAN_BREAK_LINE =
39 /[ \t>]*(?:\r?$|#{1,6}(?:[ \t]|\r?$)|(?:[-*+]|\d{1,9}[.)])[ \t]|`{3,}[^`\r\n]*\r?$|~{3,})/my;
40const LINE_PREFIX = /([ \t]*)(>|(?:[-*+]|\d{1,9}[.)])[ \t]+)?/y;
41const THEMATIC_BREAK = /^(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})\r?$/;
42const SETEXT_UNDERLINE = /^(?:-+|=+)[ \t]*\r?$/;
43// Earlier alternatives claim text so later ones cannot match inside it: an escaped character opens
44// nothing, code is literal, and a link to anywhere else keeps a thread URL in its label or href.
45const THREAD_LINK_OUTSIDE_CODE = new RegExp(
46 [
47 String.raw`\\[!-/:-@[-\`{-~]`,
48 fencedCode("`", "bt"),
49 fencedCode("~", "tl"),
50 String.raw`(?<spanTicks>\`+)`,
51 // A labeled link's destination may be angle-bracketed, as CommonMark allows: [label](<href>).
52 String.raw`\[(?<label>${LABEL})\]\((?:<(?<angleHref>${THREAD_HREF}[^\s<>]+|${HOSTED_LINK})>|(?<href>${THREAD_HREF}[^\s>)]+|${HOSTED_LINK}))\)`,
53 String.raw`\[${LABEL}\]\((?:<[^<>\n]*>|[^\s()]*(?:\([^\s()]*\)[^\s()]*)*)(?:[ \t]+(?:"[^"\n]*"|'[^'\n]*'))?\)`,
54 String.raw`<(?<autolink>${THREAD_HREF}[^\s<>]+|${HOSTED_LINK})>`,
55 // After a URL character the hosted link is part of a longer URL, such as a redirect target.
56 String.raw`(?<![A-Za-z0-9%/?#=&@+-])(?<bare>${HOSTED_LINK})(?![\w%/?#-])`,
57 ].join("|"),
58 "gm",
59);
60
61function codeSpanLines(markdown: string) {
62 const lines: Array<{ start: number; depth: number; breaksSpan: boolean }> = [];
63 const listIndents: number[] = [];
64 let paragraphDepth: number | undefined;
65 let start = 0;
66 for (const line of markdown.split("\n")) {
67 let offset = 0;
68 let depth = 0;
69 let hasList = false;
70 let listOffset = 0;
71 while (offset < line.length) {
72 LINE_PREFIX.lastIndex = offset;
73 const prefix = LINE_PREFIX.exec(line);
74 if (prefix === null) break;
75 const indent = prefix[1]!.replace(/\t/g, " ").length;
76 if (
77 listOffset === 0 &&
78 paragraphDepth === undefined &&
79 indent < (listIndents[depth] ?? 0) &&
80 line.trim()
81 ) {
82 listIndents.length = depth;
83 }
84 const containerIndent = listIndents[depth] ?? 0;
85 const continuedIndent = indent >= containerIndent ? containerIndent : 0;
86 if (prefix[2] === undefined || indent - continuedIndent > 3) break;
87 offset = LINE_PREFIX.lastIndex;
88 if (prefix[2] === ">") {
89 depth++;
90 listOffset = 0;
91 if (line[offset] === " " || line[offset] === "\t") offset++;
92 } else {
93 listOffset += indent + prefix[2]!.replace(/\t/g, " ").length;
94 listIndents[depth] = listOffset;
95 hasList = true;
96 }
97 }
98 const content = line.slice(offset);
99 const text = content.trimStart();
100 const indent = content.slice(0, content.length - text.length).replace(/\t/g, " ").length;
101 const containerIndent = hasList ? 0 : (listIndents[depth] ?? 0);
102 const lazy = indent < containerIndent || depth < (paragraphDepth ?? 0);
103 // Rules and setext underlines end a paragraph unless indented as code; a lazy line is never an underline.
104 const breaksSpan =
105 !hasList &&
106 (lazy ? indent : indent - containerIndent) <= 3 &&
107 (THEMATIC_BREAK.test(text) ||
108 (paragraphDepth !== undefined && !lazy && SETEXT_UNDERLINE.test(text)));
109 const endsParagraph =
110 breaksSpan ||
111 /^(?:[ \t\r]*$|[ \t]*#{1,6}(?:[ \t]|$)|[ \t]*`{3,}[^`]*$|[ \t]*~{3,})/.test(content);
112 const effectiveDepth = endsParagraph || hasList ? depth : Math.max(depth, paragraphDepth ?? 0);
113 lines.push({ start, depth: effectiveDepth, breaksSpan });
114 paragraphDepth = endsParagraph ? undefined : effectiveDepth;
115 start += line.length + 1;
116 }
117 return lines;
118}
119
120function findCodeSpanEnd(
121 markdown: string,
122 openIndex: number,
123 tickCount: number,
124 lines: ReturnType<typeof codeSpanLines>,
125 lineIndex: number,
126): number {
127 const openDepth = lines[lineIndex]!.depth;
128 for (let i = openIndex + tickCount; i < markdown.length; i++) {
129 if (markdown[i] === "`") {
130 let runEnd = i + 1;
131 while (markdown[runEnd] === "`") runEnd++;
132 if (runEnd - i === tickCount) return runEnd;
133 i = runEnd - 1;
134 } else if (markdown[i] === "\n") {
135 lineIndex++;
136 SPAN_BREAK_LINE.lastIndex = i + 1;
137 const line = lines[lineIndex]!;
138 if (SPAN_BREAK_LINE.test(markdown) || line.breaksSpan || line.depth > openDepth) return -1;
139 }
140 }
141 return -1;
142}
143
144const decodeThreadId = Schema.decodeUnknownOption(ThreadId);
145const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId);
146
147/** A v1 link names no environment; the message's own, or a unique match, stands in. */
148export interface ThreadLink {
149 readonly environmentId: EnvironmentId | null;
150 readonly threadId: ThreadId;
151}
152
153// Escapes even URL-safe punctuation, so a sentence's closing period never reads as part of an id.
154const hostedSegment = (id: string) =>
155 encodeURIComponent(id).replace(
156 /[.!~*'()]/g,
157 (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
158 );
159
160/** Opens the thread from anywhere: the hosted app offers the desktop app, the mobile app, or itself. */
161export function hostedThreadLink(ref: ScopedThreadRef, origin = DEFAULT_HOSTED_APP_URL): string {
162 const path = `/threads/${hostedSegment(ref.environmentId)}/${hostedSegment(ref.threadId)}`;
163 return new URL(path, origin).toString();
164}
165
166const HOSTED_PATH = new RegExp(`^(${HOSTED_SEGMENT})/(${HOSTED_SEGMENT})$`);
167
168function parseHostedThreadLink(href: string): ThreadLink | null {
169 const match = HOSTED_PATH.exec(href.slice(HOSTED_PREFIX.length));
170 if (!match) return null;
171 try {
172 const environmentId = Option.getOrNull(decodeEnvironmentId(decodeURIComponent(match[1]!)));
173 const threadId = Option.getOrNull(decodeThreadId(decodeURIComponent(match[2]!)));
174 return environmentId === null || threadId === null ? null : { environmentId, threadId };
175 } catch {
176 return null;
177 }
178}
179
180/**
181 * The ids as written. Thread ids can hold percent escapes of their own, so they are not decoded,
182 * except in a hosted link, which escapes them itself.
183 */
184export function parseThreadLinkHref(href: string): ThreadLink | null {
185 if (href.startsWith(HOSTED_PREFIX)) return parseHostedThreadLink(href);
186 if (href.startsWith(V1_PREFIX)) {
187 const threadId = Option.getOrNull(decodeThreadId(href.slice(V1_PREFIX.length)));
188 return threadId === null ? null : { environmentId: null, threadId };
189 }
190 if (!href.startsWith(V2_PREFIX)) return null;
191 const path = href.slice(V2_PREFIX.length);
192 const slash = path.indexOf("/");
193 if (slash < 0) return null;
194 const environmentId = Option.getOrNull(decodeEnvironmentId(path.slice(0, slash)));
195 const threadId = Option.getOrNull(decodeThreadId(path.slice(slash + 1)));
196 return environmentId === null || threadId === null ? null : { environmentId, threadId };
197}
198
199function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null {
200 try {
201 const decoded = decodeURIComponent(threadId);
202 return decoded === threadId ? null : Option.getOrNull(decodeThreadId(decoded));
203 } catch {
204 return null;
205 }
206}
207
208/** The threads a link can name, in its own environment or else the message's: as written, then decoded. */
209export function threadLinkCandidates(
210 link: ThreadLink,
211 messageEnvironmentId: EnvironmentId,
212): ReadonlyArray<ScopedThreadRef> {
213 const environmentId = link.environmentId ?? messageEnvironmentId;
214 const decodedId = percentDecodedThreadLinkId(link.threadId);
215 const written = { environmentId, threadId: link.threadId };
216 return decodedId === null ? [written] : [written, { environmentId, threadId: decodedId }];
217}
218
219/** A v1 link its message's environment lacks opens a unique match elsewhere; a v2 link never does. */
220export function guessThreadLinkRef(
221 link: ThreadLink,
222 refs: ReadonlyArray<ScopedThreadRef>,
223): ScopedThreadRef | null {
224 if (link.environmentId !== null) return null;
225 const decodedId = percentDecodedThreadLinkId(link.threadId);
226 for (const threadId of decodedId === null ? [link.threadId] : [link.threadId, decodedId]) {
227 let match: ScopedThreadRef | null = null;
228 for (const ref of refs) {
229 if (ref.threadId !== threadId) continue;
230 if (match !== null) return null;
231 match = ref;
232 }
233 if (match !== null) return match;
234 }
235 return null;
236}
237
238function threadLinkHref(link: ThreadLink): string {
239 return link.environmentId === null
240 ? `${V1_PREFIX}${link.threadId}`
241 : `${V2_PREFIX}${link.environmentId}/${link.threadId}`;
242}
243
244const linkLabel = (label: string | undefined) =>
245 label
246 ?.replace(/[[\]\\\r\n]/g, " ")
247 .replace(/\s+/g, " ")
248 .trim();
249
250/** Without a label, an autolink: clients show the thread's current title. */
251export function formatThreadLink(ref: ThreadLink, label?: string): string {
252 const cleaned = linkLabel(label);
253 const href = threadLinkHref(ref);
254 const destination = /[()]/.test(href) ? `<${href}>` : href;
255 return cleaned ? `[${cleaned}](${destination})` : `<${href}>`;
256}
257
258/** What a person copies out of T3 Code: a Markdown link that opens the thread anywhere. */
259export function formatHostedThreadLink(
260 ref: ScopedThreadRef,
261 label: string,
262 origin?: string,
263): string {
264 const href = hostedThreadLink(ref, origin);
265 const cleaned = linkLabel(label);
266 return cleaned ? `[${cleaned}](${href})` : href;
267}
268
269export function hasThreadLinks(markdown: string): boolean {
270 return markdown.includes(`${THREAD_LINK_PROTOCOL}://v`) || markdown.includes(HOSTED_PREFIX);
271}
272
273/** Every thread the markdown's links can name, so their titles are keyed reads. */
274export function threadLinkRefs(
275 markdown: string,
276 messageEnvironmentId: EnvironmentId,
277): ReadonlyArray<ScopedThreadRef> {
278 const refs = new Map<string, ScopedThreadRef>();
279 replaceThreadLinks(markdown, (link) => {
280 for (const ref of threadLinkCandidates(link, messageEnvironmentId)) {
281 refs.set(`${ref.environmentId}/${ref.threadId}`, ref);
282 }
283 return undefined;
284 });
285 return [...refs.values()];
286}
287
288/** Rewrites each link outside code `replace` answers for. `label` is a Markdown link's own text. */
289export function replaceThreadLinks(
290 markdown: string,
291 replace: (link: ThreadLink, label: string | undefined) => string | undefined,
292): string {
293 if (!hasThreadLinks(markdown)) return markdown;
294 // Hermes' matchAll yields matches without `groups`; exec keeps them.
295 const pattern = new RegExp(THREAD_LINK_OUTSIDE_CODE);
296 const source = threadLinkSource(markdown);
297 let result = "";
298 let cursor = 0;
299 let lines: ReturnType<typeof codeSpanLines> | undefined;
300 let lineIndex = 0;
301 for (let match = pattern.exec(source); match !== null; match = pattern.exec(source)) {
302 const spanTicks = match.groups?.spanTicks;
303 if (spanTicks !== undefined) {
304 lines ??= codeSpanLines(markdown);
305 while (lineIndex + 1 < lines.length && lines[lineIndex + 1]!.start <= match.index)
306 lineIndex++;
307 const spanEnd = findCodeSpanEnd(markdown, match.index, spanTicks.length, lines, lineIndex);
308 if (spanEnd !== -1) pattern.lastIndex = spanEnd;
309 continue;
310 }
311 const href =
312 match.groups?.angleHref ?? match.groups?.href ?? match.groups?.autolink ?? match.groups?.bare;
313 const link = href === undefined ? null : parseThreadLinkHref(href);
314 const label = match.groups?.label;
315 const rewritten =
316 link === null
317 ? undefined
318 : replace(link, label && markdown.slice(match.index + 1, match.index + 1 + label.length));
319 if (rewritten === undefined) continue;
320 result += markdown.slice(cursor, match.index) + rewritten;
321 cursor = match.index + match[0].length;
322 }
323 return cursor === 0 ? markdown : result + markdown.slice(cursor);
324}