The best way to control Claude Code, Codex and more from any computer or phone

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