Something went wrong. Try again.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import { isAbsolute } from "node:path";import { externalUrl, findLinks, type LinkRule, linkUrl } from "../links/contract.ts";
export interface ReferenceContext { recordId: string; matchers?: LinkRule[];}export interface ReferencePart { text: string; href?: string;}export interface FileReference { path: string; line?: number;}
export function fileReference(text: string): FileReference | undefined { if (!text.isWellFormed()) { return undefined; } const match = /^(.*?)(?::(\d+)(?:-\d+)?(?::\d+)?)?$/.exec(text); if (!match) { return undefined; } const path = match[1]; if ( !isAbsolute(path) || path.startsWith("//") || path.includes("\0") || /[\n\r<>"|?*]/.test(path) ) { return undefined; } const line = match[2] ? Number(match[2]) : undefined; if (line !== undefined && (!Number.isSafeInteger(line) || line < 1)) { return undefined; } return { path, line };}
function fileTarget(text: string, recordId: string): string | undefined { const file = recordId ? fileReference(text) : undefined; return file ? `/records/${encodeURIComponent(recordId)}/file?path=${encodeURIComponent(file.path)}${file.line ? `#L${file.line}` : ""}` : undefined;}
export function referenceTarget(text: string, context: ReferenceContext): string | undefined { if (/^https?:\/\//i.test(text)) { return externalUrl(text); } for (const rule of context.matchers ?? []) { for (const match of text.matchAll(rule.pattern)) { if (match.index === 0 && match[0].length === text.length) { const href = linkUrl(rule, match); if (href) { return href; } } } } return fileTarget(text, context.recordId);}
const FILES = /(?<![\w./@+-])(?:(?:\.{1,2}\/|\/)?(?:[\w.@+-]+\/)+[\w.@+-]*[\w@+-](?::\d+(?:-\d+)?(?::\d+)?)?|\b[\w.-]+\.[a-zA-Z][\w-]*(?::\d+(?:-\d+)?(?::\d+)?)?)(?![\w/@+-]|\.[\w/@+-]|:\d| [\w.@+-]+\/)/g;
export function referenceParts(text: string, context: ReferenceContext): ReferencePart[] { const matches = findLinks(text, context.matchers ?? []); for (const match of text.matchAll(FILES)) { const href = fileTarget(match[0], context.recordId); if (href) { matches.push({ index: match.index, text: match[0], href }); } } matches.sort((a, b) => a.index - b.index); const parts: ReferencePart[] = []; let offset = 0; for (const match of matches) { if (match.index < offset) { continue; } if (match.index > offset) { parts.push({ text: text.slice(offset, match.index) }); } parts.push({ text: match.text, href: match.href }); offset = match.index + match.text.length; } parts.push({ text: text.slice(offset) }); return parts;}