sailfork / t3code-github / packages/ shared/ src/ threadLinks.ts

import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";

import { DEFAULT_HOSTED_APP_URL } from "./connectAuth.ts";

export const THREAD_LINK_PROTOCOL = "t3-thread";
const V1_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`;
const V2_PREFIX = `${THREAD_LINK_PROTOCOL}://v2/`;
const HOSTED_PREFIX = `${DEFAULT_HOSTED_APP_URL}/threads/`;
const HOSTED_SEGMENT = "[A-Za-z0-9_%-]+";
const HOSTED_LINK = `${HOSTED_PREFIX.replace(/[.*+?^${}()|[\]\\/]/g, "\\

Loading Sailfork

amp;")}${HOSTED_SEGMENT}/${HOSTED_SEGMENT}`; // Code comes first in the alternation so a link written inside a code span or fence is skipped. const THREAD_LINK_OUTSIDE_CODE = new RegExp( String.raw`(?<fence>(\`{3,}|~{3,})[\s\S]*?(?:\2|$))|(?<span>(\`+)[^\n]*?\4)|\[(?<label>[^\]\n]*)\]\((?<href>t3-thread:\/\/v[12]\/[^\s)]+|${HOSTED_LINK})\)|<(?<autolink>t3-thread:\/\/v[12]\/[^\s<>]+|${HOSTED_LINK})>|(?<bare>${HOSTED_LINK})(?![\w%/?#-])`, "g", ); const decodeThreadId = Schema.decodeUnknownOption(ThreadId); const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId); /** A v1 link names no environment; the message's own, or a unique match, stands in. */ export interface ThreadLink { readonly environmentId: EnvironmentId | null; readonly threadId: ThreadId; } // Escapes even URL-safe punctuation, so a sentence's closing period never reads as part of an id. const hostedSegment = (id: string) => encodeURIComponent(id).replace( /[.!~*'()]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`, ); /** Opens the thread from anywhere: the hosted app offers the desktop app, the mobile app, or itself. */ export function hostedThreadLink(ref: ScopedThreadRef, origin = DEFAULT_HOSTED_APP_URL): string { const path = `/threads/${hostedSegment(ref.environmentId)}/${hostedSegment(ref.threadId)}`; return new URL(path, origin).toString(); } const HOSTED_PATH = new RegExp(`^(${HOSTED_SEGMENT})/(${HOSTED_SEGMENT}) packages/shared/src/threadLinks.ts at main · sailfork/t3code-github · Sailfork
); function parseHostedThreadLink(href: string): ThreadLink | null { const match = HOSTED_PATH.exec(href.slice(HOSTED_PREFIX.length)); if (!match) return null; try { const environmentId = Option.getOrNull(decodeEnvironmentId(decodeURIComponent(match[1]!))); const threadId = Option.getOrNull(decodeThreadId(decodeURIComponent(match[2]!))); return environmentId === null || threadId === null ? null : { environmentId, threadId }; } catch { return null; } } /** * The ids as written. Thread ids can hold percent escapes of their own, so they are not decoded, * except in a hosted link, which escapes them itself. */ export function parseThreadLinkHref(href: string): ThreadLink | null { if (href.startsWith(HOSTED_PREFIX)) return parseHostedThreadLink(href); if (href.startsWith(V1_PREFIX)) { const threadId = Option.getOrNull(decodeThreadId(href.slice(V1_PREFIX.length))); return threadId === null ? null : { environmentId: null, threadId }; } if (!href.startsWith(V2_PREFIX)) return null; const path = href.slice(V2_PREFIX.length); const slash = path.indexOf("/"); if (slash < 0) return null; const environmentId = Option.getOrNull(decodeEnvironmentId(path.slice(0, slash))); const threadId = Option.getOrNull(decodeThreadId(path.slice(slash + 1))); return environmentId === null || threadId === null ? null : { environmentId, threadId }; } export function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null { try { const decoded = decodeURIComponent(threadId); return decoded === threadId ? null : Option.getOrNull(decodeThreadId(decoded)); } catch { return null; } } /** The threads a link can name, in its own environment or else the message's: as written, then decoded. */ export function threadLinkCandidates( link: ThreadLink, messageEnvironmentId: EnvironmentId, ): ReadonlyArray<ScopedThreadRef> { const environmentId = link.environmentId ?? messageEnvironmentId; const decodedId = percentDecodedThreadLinkId(link.threadId); const written = { environmentId, threadId: link.threadId }; return decodedId === null ? [written] : [written, { environmentId, threadId: decodedId }]; } /** A v1 link its message's environment lacks opens a unique match elsewhere; a v2 link never does. */ export function guessThreadLinkRef( link: ThreadLink, refs: ReadonlyArray<ScopedThreadRef>, ): ScopedThreadRef | null { if (link.environmentId !== null) return null; const decodedId = percentDecodedThreadLinkId(link.threadId); for (const threadId of decodedId === null ? [link.threadId] : [link.threadId, decodedId]) { let match: ScopedThreadRef | null = null; for (const ref of refs) { if (ref.threadId !== threadId) continue; if (match !== null) return null; match = ref; } if (match !== null) return match; } return null; } function threadLinkHref(link: ThreadLink): string { return link.environmentId === null ? `${V1_PREFIX}${link.threadId}` : `${V2_PREFIX}${link.environmentId}/${link.threadId}`; } const linkLabel = (label: string | undefined) => label ?.replace(/[[\]\\\r\n]/g, " ") .replace(/\s+/g, " ") .trim(); /** Without a label, an autolink: clients show the thread's current title. */ export function formatThreadLink(ref: ThreadLink, label?: string): string { const cleaned = linkLabel(label); return cleaned ? `[${cleaned}](${threadLinkHref(ref)})` : `<${threadLinkHref(ref)}>`; } /** What a person copies out of T3 Code: a Markdown link that opens the thread anywhere. */ export function formatHostedThreadLink( ref: ScopedThreadRef, label: string, origin?: string, ): string { const href = hostedThreadLink(ref, origin); const cleaned = linkLabel(label); return cleaned ? `[${cleaned}](${href})` : href; } export function hasThreadLinks(markdown: string): boolean { return markdown.includes(`${THREAD_LINK_PROTOCOL}://v`) || markdown.includes(HOSTED_PREFIX); } /** Every thread the markdown's links can name, so their titles are keyed reads. */ export function threadLinkRefs( markdown: string, messageEnvironmentId: EnvironmentId, ): ReadonlyArray<ScopedThreadRef> { const refs = new Map<string, ScopedThreadRef>(); // Hermes' matchAll yields matches without `groups`; exec keeps them. const pattern = new RegExp(THREAD_LINK_OUTSIDE_CODE); for (let match = pattern.exec(markdown); match !== null; match = pattern.exec(markdown)) { const href = match.groups?.href ?? match.groups?.autolink ?? match.groups?.bare; const link = href === undefined ? null : parseThreadLinkHref(href); if (link === null) continue; for (const ref of threadLinkCandidates(link, messageEnvironmentId)) { refs.set(`${ref.environmentId}/${ref.threadId}`, ref); } } return [...refs.values()]; } export function unknownThreadLinkLabel( link: ThreadLink, messageEnvironmentId: EnvironmentId, ): string { return link.environmentId === null || link.environmentId === messageEnvironmentId ? "Thread no longer available" : "Thread on another machine"; } /** Rewrites each link outside code `replace` answers for. `label` is a Markdown link's own text. */ export function replaceThreadLinks( markdown: string, replace: (link: ThreadLink, label: string | undefined) => string | undefined, ): string { if (!hasThreadLinks(markdown)) return markdown; return markdown.replace(THREAD_LINK_OUTSIDE_CODE, (source, ...args) => { const groups = args.at(-1) as Partial<Record<"href" | "autolink" | "bare" | "label", string>>; const href = groups.href ?? groups.autolink ?? groups.bare; const link = href === undefined ? null : parseThreadLinkHref(href); return (link && replace(link, groups.label)) ?? source; }); } /** * Writes each link with its thread's current title, a hosted link as a v2 link. A link `title` * cannot resolve becomes plain text, its written label or a neutral one, except a labeled v1 * link, which may open elsewhere. */ export function relabelThreadLinks( markdown: string, messageEnvironmentId: EnvironmentId, title: (ref: ScopedThreadRef) => string | undefined, ): string { return replaceThreadLinks(markdown, (written, label) => { const environmentId = written.environmentId ?? messageEnvironmentId; const decoded = percentDecodedThreadLinkId(written.threadId); const threadId = title({ environmentId, threadId: written.threadId }) === undefined && decoded !== null && title({ environmentId, threadId: decoded }) !== undefined ? decoded : written.threadId; const current = title({ environmentId, threadId }); if (current === undefined) { if (label !== undefined && written.environmentId === null) return undefined; return label?.trim() || unknownThreadLinkLabel(written, messageEnvironmentId); } return formatThreadLink( { environmentId: written.environmentId, threadId }, current.trim() || label || threadId, ); }); }
packages/shared/src/threadLinks.ts at main · sailfork/t3code-github · Sailfork
);\n\nfunction parseHostedThreadLink(href: string): ThreadLink | null {\n const match = HOSTED_PATH.exec(href.slice(HOSTED_PREFIX.length));\n if (!match) return null;\n try {\n const environmentId = Option.getOrNull(decodeEnvironmentId(decodeURIComponent(match[1]!)));\n const threadId = Option.getOrNull(decodeThreadId(decodeURIComponent(match[2]!)));\n return environmentId === null || threadId === null ? null : { environmentId, threadId };\n } catch {\n return null;\n }\n}\n\n/**\n * The ids as written. Thread ids can hold percent escapes of their own, so they are not decoded,\n * except in a hosted link, which escapes them itself.\n */\nexport function parseThreadLinkHref(href: string): ThreadLink | null {\n if (href.startsWith(HOSTED_PREFIX)) return parseHostedThreadLink(href);\n if (href.startsWith(V1_PREFIX)) {\n const threadId = Option.getOrNull(decodeThreadId(href.slice(V1_PREFIX.length)));\n return threadId === null ? null : { environmentId: null, threadId };\n }\n if (!href.startsWith(V2_PREFIX)) return null;\n const path = href.slice(V2_PREFIX.length);\n const slash = path.indexOf(\"/\");\n if (slash \u003c 0) return null;\n const environmentId = Option.getOrNull(decodeEnvironmentId(path.slice(0, slash)));\n const threadId = Option.getOrNull(decodeThreadId(path.slice(slash + 1)));\n return environmentId === null || threadId === null ? null : { environmentId, threadId };\n}\n\nexport function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null {\n try {\n const decoded = decodeURIComponent(threadId);\n return decoded === threadId ? null : Option.getOrNull(decodeThreadId(decoded));\n } catch {\n return null;\n }\n}\n\n/** The threads a link can name, in its own environment or else the message's: as written, then decoded. */\nexport function threadLinkCandidates(\n link: ThreadLink,\n messageEnvironmentId: EnvironmentId,\n): ReadonlyArray\u003cScopedThreadRef> {\n const environmentId = link.environmentId ?? messageEnvironmentId;\n const decodedId = percentDecodedThreadLinkId(link.threadId);\n const written = { environmentId, threadId: link.threadId };\n return decodedId === null ? [written] : [written, { environmentId, threadId: decodedId }];\n}\n\n/** A v1 link its message's environment lacks opens a unique match elsewhere; a v2 link never does. */\nexport function guessThreadLinkRef(\n link: ThreadLink,\n refs: ReadonlyArray\u003cScopedThreadRef>,\n): ScopedThreadRef | null {\n if (link.environmentId !== null) return null;\n const decodedId = percentDecodedThreadLinkId(link.threadId);\n for (const threadId of decodedId === null ? [link.threadId] : [link.threadId, decodedId]) {\n let match: ScopedThreadRef | null = null;\n for (const ref of refs) {\n if (ref.threadId !== threadId) continue;\n if (match !== null) return null;\n match = ref;\n }\n if (match !== null) return match;\n }\n return null;\n}\n\nfunction threadLinkHref(link: ThreadLink): string {\n return link.environmentId === null\n ? `${V1_PREFIX}${link.threadId}`\n : `${V2_PREFIX}${link.environmentId}/${link.threadId}`;\n}\n\nconst linkLabel = (label: string | undefined) =>\n label\n ?.replace(/[[\\]\\\\\\r\\n]/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n\n/** Without a label, an autolink: clients show the thread's current title. */\nexport function formatThreadLink(ref: ThreadLink, label?: string): string {\n const cleaned = linkLabel(label);\n return cleaned ? `[${cleaned}](${threadLinkHref(ref)})` : `\u003c${threadLinkHref(ref)}>`;\n}\n\n/** What a person copies out of T3 Code: a Markdown link that opens the thread anywhere. */\nexport function formatHostedThreadLink(\n ref: ScopedThreadRef,\n label: string,\n origin?: string,\n): string {\n const href = hostedThreadLink(ref, origin);\n const cleaned = linkLabel(label);\n return cleaned ? `[${cleaned}](${href})` : href;\n}\n\nexport function hasThreadLinks(markdown: string): boolean {\n return markdown.includes(`${THREAD_LINK_PROTOCOL}://v`) || markdown.includes(HOSTED_PREFIX);\n}\n\n/** Every thread the markdown's links can name, so their titles are keyed reads. */\nexport function threadLinkRefs(\n markdown: string,\n messageEnvironmentId: EnvironmentId,\n): ReadonlyArray\u003cScopedThreadRef> {\n const refs = new Map\u003cstring, ScopedThreadRef>();\n // Hermes' matchAll yields matches without `groups`; exec keeps them.\n const pattern = new RegExp(THREAD_LINK_OUTSIDE_CODE);\n for (let match = pattern.exec(markdown); match !== null; match = pattern.exec(markdown)) {\n const href = match.groups?.href ?? match.groups?.autolink ?? match.groups?.bare;\n const link = href === undefined ? null : parseThreadLinkHref(href);\n if (link === null) continue;\n for (const ref of threadLinkCandidates(link, messageEnvironmentId)) {\n refs.set(`${ref.environmentId}/${ref.threadId}`, ref);\n }\n }\n return [...refs.values()];\n}\n\nexport function unknownThreadLinkLabel(\n link: ThreadLink,\n messageEnvironmentId: EnvironmentId,\n): string {\n return link.environmentId === null || link.environmentId === messageEnvironmentId\n ? \"Thread no longer available\"\n : \"Thread on another machine\";\n}\n\n/** Rewrites each link outside code `replace` answers for. `label` is a Markdown link's own text. */\nexport function replaceThreadLinks(\n markdown: string,\n replace: (link: ThreadLink, label: string | undefined) => string | undefined,\n): string {\n if (!hasThreadLinks(markdown)) return markdown;\n return markdown.replace(THREAD_LINK_OUTSIDE_CODE, (source, ...args) => {\n const groups = args.at(-1) as Partial\u003cRecord\u003c\"href\" | \"autolink\" | \"bare\" | \"label\", string>>;\n const href = groups.href ?? groups.autolink ?? groups.bare;\n const link = href === undefined ? null : parseThreadLinkHref(href);\n return (link && replace(link, groups.label)) ?? source;\n });\n}\n\n/**\n * Writes each link with its thread's current title, a hosted link as a v2 link. A link `title`\n * cannot resolve becomes plain text, its written label or a neutral one, except a labeled v1\n * link, which may open elsewhere.\n */\nexport function relabelThreadLinks(\n markdown: string,\n messageEnvironmentId: EnvironmentId,\n title: (ref: ScopedThreadRef) => string | undefined,\n): string {\n return replaceThreadLinks(markdown, (written, label) => {\n const environmentId = written.environmentId ?? messageEnvironmentId;\n const decoded = percentDecodedThreadLinkId(written.threadId);\n const threadId =\n title({ environmentId, threadId: written.threadId }) === undefined &&\n decoded !== null &&\n title({ environmentId, threadId: decoded }) !== undefined\n ? decoded\n : written.threadId;\n const current = title({ environmentId, threadId });\n if (current === undefined) {\n if (label !== undefined && written.environmentId === null) return undefined;\n return label?.trim() || unknownThreadLinkLabel(written, messageEnvironmentId);\n }\n return formatThreadLink(\n { environmentId: written.environmentId, threadId },\n current.trim() || label || threadId,\n );\n });\n}\n","preview":null,"history":null,"version":"aba7d5f983a0a1490fd4b7dd34b378f70f2bc488"},"/_session?shell=1":null}