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

terminal-links.ts

231 lines8.5 KB

1import {
2 formatFilePathPosition,
3 parseFileUrlHref,
4 resolvePathLinkTarget,
5 splitFilePathPosition,
6} from "@t3tools/shared/fileLinks";
7import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks";
8import { stripSlashPrefixedWindowsDrive } from "@t3tools/shared/path";
9import { isMacPlatform } from "./lib/utils";
10​
11export type TerminalLinkKind = "url" | "path";
12​
13export interface TerminalLinkMatch {
14 kind: TerminalLinkKind;
15 text: string;
16 start: number;
17 end: number;
19​
20export interface TerminalBufferLineLike {
21 readonly isWrapped?: boolean;
22 translateToString(trimRight?: boolean): string;
24​
25export interface WrappedTerminalLinkLineSegment {
26 bufferLineNumber: number;
27 text: string;
28 startIndex: number;
29 endIndex: number;
31​
32export interface WrappedTerminalLinkLine {
33 text: string;
34 segments: ReadonlyArray<WrappedTerminalLinkLineSegment>;
36​
37const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/giu;
38// The default PowerShell prompt delimits its unquoted path with `PS ` and `>`.
39const POWERSHELL_PROMPT_PATH_PATTERN = /^PS ((?:[A-Za-z]:[\\/]|\\\\|\/)[^>\r\n]*)>/u;
40// Bare paths start only at a segment boundary: hover detection runs this on
41// every frame, so separator-free output must not be rescanned at every suffix.
42// For the same reason `]` needs its `[`: trimming a long run of `]` is quadratic.
43// Parenthesized path segments need a following slash to distinguish compiler locations.
44const FILE_PATH_PATTERN =
45 /(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|(?<![\p{L}\p{M}\p{N}._-])[\p{L}\p{M}\p{N}._-]+(?:[\\/](?:[\p{L}\p{M}\p{N}._$+@-]|\[{1,2}[\p{L}\p{M}\p{N}._-]+\]{1,2}|\([\p{L}\p{M}\p{N}._-]+\)(?=[\\/]))+)+(?:(?::\d+){1,2}|\(\d+,\d+\)(?=:\s+(?:error|warning) TS\d+:))?/gu;
46const QUOTED_FILE_PATH_PATTERN =
47 /(["'`])(?<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;
48const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
49// Paths also drop a trailing colon: compilers end `file:line:col:` with one.
50const TRAILING_PATH_PUNCTUATION_PATTERN = /[.,;:!?]+$/;
51// A question mark is legal in filenames; only exclude query-bearing request targets.
52const REQUEST_ROUTE_PATTERN =
53 /(?:^|[\s"'`])(?:GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|CONNECT|TRACE|proxying)\s+["'`]?(?:\/|[A-Za-z0-9_-]+\/)[^\s?]*\?\S*/g;
54// The tail of `redis://host/0` or `file:///a.mjs` is not a path. One-letter schemes stay drives,
55// a diff's `+` or `-` may lead, and the lookbehind keeps runs from being rescanned at every suffix.
56const SCHEME_URL_PATTERN = /(?<![A-Za-z\d+.-])[+-]?[A-Za-z][A-Za-z\d+.-]+:\/\/[^\s"'`<>]+/gu;
57// Nor is the tail of an SCP-style Git remote such as `git@github.com:acme/widgets.git`. Only a
58// path wholly inside the tail is dropped, so `src/contact@support.vue:12:3` keeps its link.
59const SCP_REMOTE_PATTERN = /(?<![\w.@-])[\w.-]+@[\w.-]+:[^\s"'`<>]+/gu;
60​
61function trimClosingDelimiters(value: string, kind: TerminalLinkKind): string {
62 let output = value.replace(
63 kind === "path" ? TRAILING_PATH_PUNCTUATION_PATTERN : TRAILING_PUNCTUATION_PATTERN,
64 "",
65 );
66 if (output.length === 0) return output;
67​
68 const trimUnbalanced = (open: string, close: string) => {
69 while (output.endsWith(close)) {
70 const opens = output.split(open).length - 1;
71 const closes = output.split(close).length - 1;
72 if (opens >= closes) return;
73 output = output.slice(0, -1);
74 }
75 };
76​
77 trimUnbalanced("(", ")");
78 trimUnbalanced("[", "]");
79 trimUnbalanced("{", "}");
80 return output;
82​
83function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
84 return a.start < b.end && b.start < a.end;
86​
87function collectMatches(
88 line: string,
89 kind: TerminalLinkKind,
90 pattern: RegExp,
91 existing: TerminalLinkMatch[],
92): TerminalLinkMatch[] {
93 const matches: TerminalLinkMatch[] = [];
94 pattern.lastIndex = 0;
95​
96 for (const rawMatch of line.matchAll(pattern)) {
97 const quotedPath = rawMatch.groups?.path;
98 const raw =
99 quotedPath === undefined ? rawMatch[0] : quotedPath + (rawMatch.groups?.position ?? "");
100 const start = rawMatch.index + (quotedPath === undefined ? 0 : 1);
101 if (start < 0 || raw.length === 0) continue;
102​
103 const trimmed = quotedPath === undefined ? trimClosingDelimiters(raw, kind) : raw;
104 if (trimmed.length === 0) continue;
105 if (kind === "path" && isTerminalUrl(trimmed)) continue;
106​
107 const candidate: TerminalLinkMatch = {
108 kind,
109 text:
110 kind === "path" && /^:\s+(?:error|warning) TS\d+:/u.test(line.slice(start + trimmed.length))
111 ? trimmed.replace(/\((\d+),(\d+)\)$/, ":$1:$2")
112 : trimmed,
113 start,
114 // A position outside quotes spans the closing quote in the terminal buffer.
115 end: start + trimmed.length + (rawMatch.groups?.position ? 1 : 0),
116 };
117​
118 const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
119 if (collides) continue;
120​
121 matches.push(candidate);
122 }
123​
124 return matches;
126​
127export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
128 const promptPath = POWERSHELL_PROMPT_PATH_PATTERN.exec(line)?.[1];
129 const promptMatches: TerminalLinkMatch[] = promptPath
130 ? [{ kind: "path", text: promptPath, start: 3, end: 3 + promptPath.length }]
131 : [];
132 const nonPathRanges = Array.from(
133 [...line.matchAll(REQUEST_ROUTE_PATTERN), ...line.matchAll(SCHEME_URL_PATTERN)],
134 (match) => ({ start: match.index, end: match.index + match[0].length }),
135 );
136 const remoteTails = Array.from(line.matchAll(SCP_REMOTE_PATTERN), (match) => ({
137 start: match.index + match[0].indexOf(":") + 1,
138 end: match.index + match[0].length,
139 }));
140 const urlMatches = collectMatches(line, "url", URL_PATTERN, promptMatches);
141 const quotedMatches = collectMatches(line, "path", QUOTED_FILE_PATH_PATTERN, [
142 ...promptMatches,
143 ...urlMatches,
144 ]);
145 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, [
146 ...promptMatches,
147 ...urlMatches,
148 ...quotedMatches,
149 ]);
150 return [...promptMatches, ...urlMatches, ...quotedMatches, ...pathMatches]
151 .filter(
152 (match) =>
153 match.kind === "url" ||
154 (!nonPathRanges.some((range) => overlaps(match, range)) &&
155 !remoteTails.some((tail) => match.start >= tail.start && match.end <= tail.end)),
156 )
157 .toSorted((a, b) => a.start - b.start);
159​
160export function isTerminalUrl(value: string): boolean {
161 return /^https?:\/\//iu.test(value);
163​
164/** Explicit OSC 8 targets may be `file://` URIs; everything else is a path relative to `cwd`. */
165export function resolveTerminalLinkTarget(text: string, cwd: string): string {
166 const fileUrl = /^file:\/\//iu.test(text) ? parseFileUrlHref(text) : null;
167 if (!fileUrl) return resolvePathLinkTarget(text, cwd);
168 return formatFilePathPosition(
169 splitFilePathPosition(
170 stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(fileUrl.path)),
171 fileUrl.hash,
172 ),
173 );
175​
176export function collectWrappedTerminalLinkLine(
177 bufferLineNumber: number,
178 getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined,
179): WrappedTerminalLinkLine | null {
180 const anchorLine = getLine(bufferLineNumber - 1);
181 if (!anchorLine) return null;
182​
183 let startBufferLineNumber = bufferLineNumber;
184 let startLine = anchorLine;
185​
186 while (startBufferLineNumber > 1 && startLine.isWrapped) {
187 const previousLine = getLine(startBufferLineNumber - 2);
188 if (!previousLine) return null;
189 startBufferLineNumber -= 1;
190 startLine = previousLine;
191 }
192​
193 const segments: WrappedTerminalLinkLineSegment[] = [];
194 let nextStartIndex = 0;
195 let currentBufferLineNumber = startBufferLineNumber;
196​
197 while (true) {
198 const currentLine = getLine(currentBufferLineNumber - 1);
199 if (!currentLine) break;
200​
201 const nextLine = getLine(currentBufferLineNumber);
202 const hasWrappedContinuation = nextLine?.isWrapped === true;
203 const text = currentLine.translateToString(!hasWrappedContinuation);
204​
205 segments.push({
206 bufferLineNumber: currentBufferLineNumber,
207 text,
208 startIndex: nextStartIndex,
209 endIndex: nextStartIndex + text.length,
210 });
211 nextStartIndex += text.length;
212​
213 if (!hasWrappedContinuation) break;
214 currentBufferLineNumber += 1;
215 }
216​
217 return {
218 text: segments.map((segment) => segment.text).join(""),
219 segments,
220 };
222​
223export function isTerminalLinkActivation(
224 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
225 platform = typeof navigator === "undefined" ? "" : navigator.platform,
226): boolean {
227 if (platform.length === 0) return false;
228 return isMacPlatform(platform)
229 ? event.metaKey && !event.ctrlKey
230 : event.ctrlKey && !event.metaKey;