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

terminal-links.ts

181 lines5.8 KB

1import { isMacPlatform } from "./lib/utils";
2​
3export type TerminalLinkKind = "url" | "path";
4​
5export interface TerminalLinkMatch {
6 kind: TerminalLinkKind;
7 text: string;
8 start: number;
9 end: number;
11​
12export interface TerminalBufferLineLike {
13 readonly isWrapped?: boolean;
14 translateToString(trimRight?: boolean): string;
16​
17export interface WrappedTerminalLinkLineSegment {
18 bufferLineNumber: number;
19 text: string;
20 startIndex: number;
21 endIndex: number;
23​
24export interface WrappedTerminalLinkLine {
25 text: string;
26 segments: ReadonlyArray<WrappedTerminalLinkLineSegment>;
28​
29const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/giu;
30const FILE_PATH_PATTERN =
31 /(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:[\\/][A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
32const QUOTED_FILE_PATH_PATTERN =
33 /(["'`])(?<path>(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\|[A-Za-z0-9._ -]+[\\/])[^\r\n]*?|[A-Za-z0-9._ -]+\.[A-Za-z0-9_-]+(?::\d+){0,2})\1(?<position>(?::\d+){0,2})/g;
34const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
35// Paths also drop a trailing colon: compilers end `file:line:col:` with one.
36const TRAILING_PATH_PUNCTUATION_PATTERN = /[.,;:!?]+$/;
37// A question mark is legal in filenames; only exclude query-bearing request targets.
38const REQUEST_ROUTE_PATTERN =
39 /(?:^|[\s"'`])(?:GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|CONNECT|TRACE|proxying)\s+["'`]?(?:\/|[A-Za-z0-9_-]+\/)[^\s?]*\?\S*/g;
40​
41function trimClosingDelimiters(value: string, kind: TerminalLinkKind): string {
42 let output = value.replace(
43 kind === "path" ? TRAILING_PATH_PUNCTUATION_PATTERN : TRAILING_PUNCTUATION_PATTERN,
44 "",
45 );
46 if (output.length === 0) return output;
47​
48 const trimUnbalanced = (open: string, close: string) => {
49 while (output.endsWith(close)) {
50 const opens = output.split(open).length - 1;
51 const closes = output.split(close).length - 1;
52 if (opens >= closes) return;
53 output = output.slice(0, -1);
54 }
55 };
56​
57 trimUnbalanced("(", ")");
58 trimUnbalanced("[", "]");
59 trimUnbalanced("{", "}");
60 return output;
62​
63function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
64 return a.start < b.end && b.start < a.end;
66​
67function collectMatches(
68 line: string,
69 kind: TerminalLinkKind,
70 pattern: RegExp,
71 existing: TerminalLinkMatch[],
72): TerminalLinkMatch[] {
73 const matches: TerminalLinkMatch[] = [];
74 pattern.lastIndex = 0;
75​
76 for (const rawMatch of line.matchAll(pattern)) {
77 const quotedPath = rawMatch.groups?.path;
78 const raw =
79 quotedPath === undefined ? rawMatch[0] : quotedPath + (rawMatch.groups?.position ?? "");
80 const start = rawMatch.index + (quotedPath === undefined ? 0 : 1);
81 if (start < 0 || raw.length === 0) continue;
82​
83 const trimmed = quotedPath === undefined ? trimClosingDelimiters(raw, kind) : raw;
84 if (trimmed.length === 0) continue;
85 if (kind === "path" && isTerminalUrl(trimmed)) continue;
86​
87 const candidate: TerminalLinkMatch = {
88 kind,
89 text: trimmed,
90 start,
91 // A position outside quotes spans the closing quote in the terminal buffer.
92 end: start + trimmed.length + (rawMatch.groups?.position ? 1 : 0),
93 };
94​
95 const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
96 if (collides) continue;
97​
98 matches.push(candidate);
99 }
100​
101 return matches;
103​
104export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
105 const requestRoutes = Array.from(line.matchAll(REQUEST_ROUTE_PATTERN), (match) => ({
106 start: match.index,
107 end: match.index + match[0].length,
108 }));
109 const urlMatches = collectMatches(line, "url", URL_PATTERN, []);
110 const quotedMatches = collectMatches(line, "path", QUOTED_FILE_PATH_PATTERN, urlMatches);
111 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, [
112 ...urlMatches,
113 ...quotedMatches,
114 ]);
115 return [...urlMatches, ...quotedMatches, ...pathMatches]
116 .filter(
117 (match) => match.kind === "url" || !requestRoutes.some((route) => overlaps(match, route)),
118 )
119 .toSorted((a, b) => a.start - b.start);
121​
122export function isTerminalUrl(value: string): boolean {
123 return /^https?:\/\//iu.test(value);
125​
126export function collectWrappedTerminalLinkLine(
127 bufferLineNumber: number,
128 getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined,
129): WrappedTerminalLinkLine | null {
130 const anchorLine = getLine(bufferLineNumber - 1);
131 if (!anchorLine) return null;
132​
133 let startBufferLineNumber = bufferLineNumber;
134 let startLine = anchorLine;
135​
136 while (startBufferLineNumber > 1 && startLine.isWrapped) {
137 const previousLine = getLine(startBufferLineNumber - 2);
138 if (!previousLine) return null;
139 startBufferLineNumber -= 1;
140 startLine = previousLine;
141 }
142​
143 const segments: WrappedTerminalLinkLineSegment[] = [];
144 let nextStartIndex = 0;
145 let currentBufferLineNumber = startBufferLineNumber;
146​
147 while (true) {
148 const currentLine = getLine(currentBufferLineNumber - 1);
149 if (!currentLine) break;
150​
151 const nextLine = getLine(currentBufferLineNumber);
152 const hasWrappedContinuation = nextLine?.isWrapped === true;
153 const text = currentLine.translateToString(!hasWrappedContinuation);
154​
155 segments.push({
156 bufferLineNumber: currentBufferLineNumber,
157 text,
158 startIndex: nextStartIndex,
159 endIndex: nextStartIndex + text.length,
160 });
161 nextStartIndex += text.length;
162​
163 if (!hasWrappedContinuation) break;
164 currentBufferLineNumber += 1;
165 }
166​
167 return {
168 text: segments.map((segment) => segment.text).join(""),
169 segments,
170 };
172​
173export function isTerminalLinkActivation(
174 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
175 platform = typeof navigator === "undefined" ? "" : navigator.platform,
176): boolean {
177 if (platform.length === 0) return false;
178 return isMacPlatform(platform)
179 ? event.metaKey && !event.ctrlKey
180 : event.ctrlKey && !event.metaKey;