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