Open History to see the last commit
1import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
2import { describe, expect, it } from "vite-plus/test";
3
4import {
5 collectWrappedTerminalLinkLine,
6 extractTerminalLinks,
7 isTerminalUrl,
8 resolveTerminalLinkTarget,
9 type TerminalBufferLineLike,
10} from "./terminal-links";
11
12function createBufferLine(text: string, isWrapped = false): TerminalBufferLineLike {
13 return {
14 isWrapped,
15 translateToString: (trimRight = false) => (trimRight ? text.replace(/\s+$/u, "") : text),
16 };
17}
18
19describe("extractTerminalLinks", () => {
20 it.each([
21 String.raw`C:\dev\ai-test\dir 1`,
22 String.raw`C:\dev\ai-test\dir 1\test`,
23 "C:\\",
24 String.raw`\\server\my share\dir 1`,
25 "/home/Jane Doe/project",
26 String.raw`C:\dev\folder (draft)\name!`,
27 ])("keeps the full PowerShell prompt path %s in one link", (path) => {
28 expect(extractTerminalLinks(`PS ${path}> `)).toEqual([
29 { kind: "path", text: path, start: 3, end: 3 + path.length },
30 ]);
31 });
32
33 it("keeps links in a command separate from the PowerShell prompt path", () => {
34 const path = String.raw`C:\dev\dir 1\test`;
35 const prompt = `PS ${path}> `;
36 const url = "https://example.com";
37 expect(extractTerminalLinks(`${prompt}echo ${url}`)).toEqual([
38 { kind: "path", text: path, start: 3, end: 3 + path.length },
39 { kind: "url", text: url, start: prompt.length + 5, end: prompt.length + 5 + url.length },
40 ]);
41 });
42
43 it("does not extend ordinary output paths through trailing prose", () => {
44 const path = String.raw`C:\dev\project`;
45 expect(extractTerminalLinks(`see ${path} for details`)).toEqual([
46 { kind: "path", text: path, start: 4, end: 4 + path.length },
47 ]);
48 });
49
50 it.each([
51 String.raw`src\index.ts:12`,
52 String.raw`.\src\index.ts:12:7`,
53 String.raw`..\src\index.ts:12`,
54 String.raw`C:\Users\Jane\project\index.ts:12`,
55 String.raw`\\server\share\index.ts:12`,
56 ])("finds Windows path %s", (text) => {
57 const line = `error at ${text}: failed`;
58 expect(extractTerminalLinks(line)).toEqual([
59 { kind: "path", text, start: 9, end: 9 + text.length },
60 ]);
61 });
62
63 it.each(['"', "'", "`"])("finds paths containing spaces enclosed in %s", (quote) => {
64 const text = String.raw`C:\Users\Jane Doe\project\index.ts:12:7`;
65 expect(extractTerminalLinks(`see ${quote}${text}${quote}.`)).toEqual([
66 { kind: "path", text, start: 5, end: 5 + text.length },
67 ]);
68 const atText = "src/my contact@support.vue:12:3";
69 expect(extractTerminalLinks(`see ${quote}${atText}${quote}.`)).toEqual([
70 { kind: "path", text: atText, start: 5, end: 5 + atText.length },
71 ]);
72 });
73
74 it.each([
75 String.raw`src\my folder\index.ts`,
76 "./my folder/index.ts",
77 "/home/Jane Doe/index.ts",
78 "/home/Jane Doe/file)",
79 String.raw`\\server\my share\index.ts`,
80 ])("keeps positions outside quotes on %s", (path) => {
81 expect(extractTerminalLinks(`"${path}":12:7: error`)).toEqual([
82 { kind: "path", text: `${path}:12:7`, start: 1, end: path.length + 7 },
83 ]);
84 });
85
86 it.each([
87 'error: "something went wrong"',
88 'error: "something went wrong."',
89 "see README.md, Node.js v22 on 127.0.0.1:3000",
90 "README.md(42,7): see details",
91 "main.cs(42,7): error CS1002: expected semicolon",
92 "Connecting to api.example.com:443...",
93 "dial tcp: lookup db.internal:5432: no such host",
94 "redis.local:6379> PING",
95 "postgres@db.internal:5432",
96 ])("does not treat prose or unsupported locations as a path: %s", (line) => {
97 expect(extractTerminalLinks(line)).toEqual([]);
98 });
99
100 it("keeps quoted paths and URLs separate without duplicate partial paths", () => {
101 const path = String.raw`C:\Jane Doe\index.ts:12`;
102 const url = "https://example.com/docs";
103 const line = `"${path}" ${url} src/index.ts`;
104 expect(extractTerminalLinks(line)).toEqual([
105 { kind: "path", text: path, start: 1, end: 1 + path.length },
106 { kind: "url", text: url, start: path.length + 3, end: path.length + 3 + url.length },
107 { kind: "path", text: "src/index.ts", start: line.length - 12, end: line.length },
108 ]);
109 });
110
111 it("classifies uppercase schemes as URLs at activation time too", () => {
112 expect(isTerminalUrl("HTTPS://example.com/docs")).toBe(true);
113 expect(isTerminalUrl("Http://example.com")).toBe(true);
114 expect(isTerminalUrl("src/components/main.ts")).toBe(false);
115 expect(isTerminalUrl("httpsdocs/readme.md")).toBe(false);
116 });
117
118 it("trims trailing punctuation from links", () => {
119 const line = "(https://example.com/docs), ./src/main.ts:12.";
120 expect(extractTerminalLinks(line)).toEqual([
121 {
122 kind: "url",
123 text: "https://example.com/docs",
124 start: 1,
125 end: 25,
126 },
127 {
128 kind: "path",
129 text: "./src/main.ts:12",
130 start: 28,
131 end: 44,
132 },
133 ]);
134 });
135
136 it.each([
137 ["https://example.com/a(b)c)", "https://example.com/a(b)c"],
138 ["https://example.com/(docs)", "https://example.com/(docs)"],
139 ["https://example.com/docs)}])", "https://example.com/docs)"],
140 ["https://example.com/docs):", "https://example.com/docs):"],
141 ["/tmp/a[b]c]", "/tmp/a[b]c"],
142 ["/tmp/docs)}])", "/tmp/docs)"],
143 ["/tmp/docs):", "/tmp/docs"],
144 ])("trims only unbalanced closing delimiters from %s", (raw, text) => {
145 expect(extractTerminalLinks(`see ${raw}`)).toEqual([
146 { kind: isTerminalUrl(text) ? "url" : "path", text, start: 4, end: 4 + text.length },
147 ]);
148 });
149
150 it.each([
151 "src/żółć.ts:12:7",
152 "żółć/main.ts:12",
153 String.raw`żółć\main.ts:12`,
154 "src/cafe\u0301.ts:12",
155 "src/𐐀.ts:12",
156 "src/app/[id]/page.tsx:3:10",
157 "src/routes/(app)/+page.svelte:12:4",
158 "src/routes/(app)/+page@.svelte:12:3",
159 "src/contact@support.vue:12:3",
160 String.raw`src\contact@support.ts:12:3`,
161 "src/équipe@home.ts:12:3",
162 "src/foo$contact@support.ts:12:3",
163 "node_modules/.pnpm/react@18.3.1/node_modules/react/index.js:12:5",
164 "app/routes/posts.$id.tsx:5",
165 "main.c:1:25",
166 "page.test.tsx:5:3",
167 "foo$bar.ts:12:3",
168 "+page.svelte:12:4",
169 "contact@support.ts:12:3",
170 ])("keeps the complete relative path %s", (text) => {
171 expect(extractTerminalLinks(`see ${text} for details`)).toEqual([
172 { kind: "path", text, start: 4, end: 4 + text.length },
173 ]);
174 });
175
176 it.each([
177 ["./src/a.js:1:function inner() {", "./src/a.js:1:function", "./src/a.js:1"],
178 ["./src/a.js:4:1:function outer() {", "./src/a.js:4:1:function", "./src/a.js:4:1"],
179 ["/app/top.rb:2:in `f': boom (RuntimeError)", "/app/top.rb:2:in", "/app/top.rb:2"],
180 ["./data.csv:5:2024-01-01 ok", "./data.csv:5:2024-01-01", "./data.csv:5"],
181 [
182 "/var/lib/bluetooth/AA:BB:CC:11:22:DD",
183 "/var/lib/bluetooth/AA:BB:CC:11:22:DD",
184 "/var/lib/bluetooth/AA:BB:CC:11:22",
185 ],
186 ])("keeps %s whole and offers its location as the fallback", (line, text, fallback) => {
187 expect(extractTerminalLinks(line)).toEqual([
188 {
189 kind: "path",
190 text,
191 start: 0,
192 end: text.length,
193 fallback: { text: fallback, end: fallback.length },
194 },
195 ]);
196 });
197
198 it("finds Windows absolute paths with forward slashes", () => {
199 const line = "see C:/Users/someone/project/src/file.ts:42 for details";
200 const path = "C:/Users/someone/project/src/file.ts:42";
201 const start = line.indexOf(path);
202 expect(extractTerminalLinks(line)).toEqual([
203 {
204 kind: "path",
205 text: path,
206 start,
207 end: start + path.length,
208 },
209 ]);
210 });
211
212 it("keeps a trailing colon on URLs", () => {
213 expect(extractTerminalLinks("GET https://example.test/items/foo:")).toEqual([
214 { kind: "url", text: "https://example.test/items/foo:", start: 4, end: 35 },
215 ]);
216 });
217
218 it.each([
219 ["./main.go:10:5: undefined: x", "./main.go:10:5"],
220 ["/home/dev/app/src/main.c:10:5: error: expected ';'", "/home/dev/app/src/main.c:10:5"],
221 ["C:\\dev\\app\\src\\main.c:10:5: error: expected ';'", "C:\\dev\\app\\src\\main.c:10:5"],
222 ["wrote ./out/report.txt:", "./out/report.txt"],
223 ])("drops the colon that ends a compiler diagnostic location in %s", (line, text) => {
224 const start = line.indexOf(text);
225 expect(extractTerminalLinks(line)).toEqual([
226 { kind: "path", text, start, end: start + text.length },
227 ]);
228 });
229
230 it.each([
231 " GET /api/trpc/post.list,user.me?batch=1&input=%7B%220%22%3A%7B%22json%22%3Anull%7D%7D 200 in 35ms",
232 "GET /api?+debug 200",
233 'Started GET "/posts?page=2" for ::1',
234 "proxying api/trpc/post.list?batch=1 to the backend",
235 ])("does not turn a logged request route into an editor link: %s", (line) => {
236 expect(extractTerminalLinks(line)).toEqual([]);
237 });
238
239 it("keeps file and URL links before and after a logged request route", () => {
240 const before = "src/server.ts:12";
241 const after = "/app/bin/server:3:7";
242 const url = "https://example.com/api/users?id=42";
243 const line = `${before} GET /api/users?id=42 200 ${after} ${url}`;
244 const afterStart = line.indexOf(after);
245 const urlStart = line.indexOf(url);
246
247 expect(extractTerminalLinks(line)).toEqual([
248 { kind: "path", text: before, start: 0, end: before.length },
249 { kind: "path", text: after, start: afterStart, end: afterStart + after.length },
250 { kind: "url", text: url, start: urlStart, end: urlStart + url.length },
251 ]);
252 });
253
254 it.each([
255 "connected to redis://127.0.0.1:6379/0",
256 "connected to postgres://localhost:5432/app",
257 "uploaded s3://bucket/reports/today.csv",
258 " at main (file:///Users/jane/app/src/index.mjs:3:7)",
259 "+redis://localhost:6379/0",
260 "-redis://localhost:6379/0",
261 "git clone git@github.com:acme/widgets.git",
262 "remote: git@gitlab.com:group/sub/project.git",
263 ])("does not turn part of a non-web URL into an editor link: %s", (line) => {
264 expect(extractTerminalLinks(line)).toEqual([]);
265 });
266
267 it("keeps file links beside a non-web URL", () => {
268 const line = "src/db.ts:4 redis://localhost:6379/0 C:/app/src/db.ts:9";
269 expect(extractTerminalLinks(line)).toEqual([
270 { kind: "path", text: "src/db.ts:4", start: 0, end: 11 },
271 { kind: "path", text: "C:/app/src/db.ts:9", start: 37, end: 55 },
272 ]);
273 });
274
275 it("keeps a question mark inside a filesystem path", () => {
276 const path = "/tmp/report?draft";
277 expect(extractTerminalLinks(`wrote ${path}`)).toEqual([
278 { kind: "path", text: path, start: 6, end: 6 + path.length },
279 ]);
280 });
281});
282
283describe("collectWrappedTerminalLinkLine", () => {
284 it("reconstructs a wrapped line from any physical row", () => {
285 const firstSegment = "see https://example.com/a";
286 const secondSegment = "/bc?x=1";
287 const lines = [
288 createBufferLine("prompt> "),
289 createBufferLine(firstSegment),
290 createBufferLine(secondSegment, true),
291 createBufferLine("done"),
292 ];
293
294 const fromFirstRow = collectWrappedTerminalLinkLine(2, (index) => lines[index]);
295 const fromWrappedRow = collectWrappedTerminalLinkLine(3, (index) => lines[index]);
296
297 expect(fromFirstRow).toEqual({
298 text: `${firstSegment}${secondSegment}`,
299 segments: [
300 {
301 bufferLineNumber: 2,
302 text: firstSegment,
303 startIndex: 0,
304 endIndex: firstSegment.length,
305 },
306 {
307 bufferLineNumber: 3,
308 text: secondSegment,
309 startIndex: firstSegment.length,
310 endIndex: firstSegment.length + secondSegment.length,
311 },
312 ],
313 });
314 expect(fromWrappedRow).toEqual(fromFirstRow);
315 });
316
317 it("preserves trailing spaces on continued segments for downstream offsets", () => {
318 const firstSegment = "prefix ";
319 const secondSegment = "https://example.com/path";
320 const lines = [createBufferLine(firstSegment), createBufferLine(secondSegment, true)];
321
322 const wrappedLine = collectWrappedTerminalLinkLine(2, (index) => lines[index]);
323
324 expect(wrappedLine?.text).toBe(`${firstSegment}${secondSegment}`);
325 expect(extractTerminalLinks(wrappedLine?.text ?? "")).toEqual([
326 {
327 kind: "url",
328 text: secondSegment,
329 start: firstSegment.length,
330 end: firstSegment.length + secondSegment.length,
331 },
332 ]);
333 });
334});
335
336describe("resolvePathLinkTarget", () => {
337 it("resolves a quoted terminal link against a Windows environment", () => {
338 const [link] = extractTerminalLinks(String.raw`error at "src\my folder\index.ts":12:7`);
339 expect(resolvePathLinkTarget(link?.text ?? "", String.raw`C:\Users\Jane Doe\project`)).toBe(
340 String.raw`C:\Users\Jane Doe\project\src\my folder\index.ts:12:7`,
341 );
342 });
343
344 // regression: #13408 terminal links kept a trailing colon
345 it("keeps the line and column of a compiler diagnostic", () => {
346 const [link] = extractTerminalLinks("/Users/julius/project/main.c:10:5: error: expected ';'");
347 expect(resolvePathLinkTarget(link?.text ?? "", "/Users/julius/project")).toBe(
348 "/Users/julius/project/main.c:10:5",
349 );
350 });
351
352 it.each([
353 ["src/main.ts", "/repo/src/main.ts"],
354 ["/repo/src/main.ts", "/repo/src/main.ts"],
355 [String.raw`C:\repo\src\main.ts`, String.raw`C:\repo\src\main.ts`],
356 ["app/(auth)/page.tsx", "/repo/app/(auth)/page.tsx"],
357 ])("preserves a TypeScript compiler location on %s", (path, target) => {
358 const text = `${path}(42,7)`;
359 const links = extractTerminalLinks(`${text}: error TS2322: Type mismatch`);
360 expect(links).toEqual([{ kind: "path", text: `${path}:42:7`, start: 0, end: text.length }]);
361 expect(resolveTerminalLinkTarget(links[0]?.text ?? "", "/repo")).toBe(`${target}:42:7`);
362 });
363
364 it.each([
365 [String.raw`PS C:\dev\folder (42,7)> `, String.raw`C:\dev\folder (42,7)`],
366 ["/tmp/report(42,7)", "/tmp/report(42,7)"],
367 ["src/Program.cs(3,10): error CS1002: x", "/repo/src/Program.cs"],
368 ])("preserves existing path targets in %s", (line, target) => {
369 const [link] = extractTerminalLinks(line);
370 expect(resolveTerminalLinkTarget(link?.text ?? "", "/repo")).toBe(target);
371 });
372
373 // regression: #36005 OSC 8 file URIs were joined onto the cwd as relative paths
374 it("does not resolve an OSC 8 file URI target against the cwd", () => {
375 expect(resolveTerminalLinkTarget("file:///var/tmp/report.txt", "/workspace/project")).toBe(
376 "file:///var/tmp/report.txt",
377 );
378 expect(
379 resolveTerminalLinkTarget("file://remote.invalid/var/tmp/report.txt", "/workspace/project"),
380 ).not.toMatch(/^\/workspace\/project\//);
381 expect(
382 resolveTerminalLinkTarget(
383 "file://myhost/var/tmp/report.txt:12#L5",
384 "/workspace/project",
385 "myhost",
386 ),
387 ).toBe("file:///var/tmp/report.txt:12#L5");
388 expect(
389 resolveTerminalLinkTarget(
390 "file://foreign/var/tmp/report.txt:12#L5",
391 "/workspace/project",
392 "myhost",
393 ),
394 ).toBe("file://foreign/var/tmp/report.txt:12#L5");
395 for (const name of ["report.txt:12-64", "report.txt:0", "report.txt:12"]) {
396 const uri = `file:///var/tmp/${encodeURIComponent(name)}`;
397 expect(resolveTerminalLinkTarget(uri, "/workspace/project")).toBe(uri);
398 }
399 expect(
400 resolveTerminalLinkTarget("file:///var/tmp/report.txt:12#L5", "/workspace/project"),
401 ).toBe("file:///var/tmp/report.txt:12#L5");
402 expect(resolvePathLinkTarget("file:notes.md", "/workspace/project")).toBe(
403 "/workspace/project/file:notes.md",
404 );
405 });
406});