Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { it as effectIt } from "@effect/vitest";
3import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
4import * as Effect from "effect/Effect";
5import { describe, expect, it, vi } from "vite-plus/test";
6
7import {
8 extractPathFromShellOutput,
9 CommandAvailability,
10 type CommandAvailabilityChecker,
11 isCommandAvailable,
12 listLoginShellCandidates,
13 mergePathEntries,
14 mergePathValues,
15 readEnvironmentFromLoginShell,
16 readEnvironmentFromWindowsShell,
17 readPathFromLaunchctl,
18 readPathFromLoginShell,
19 resolveCommandPath,
20 resolveKnownWindowsCliDirs,
21 resolveSpawnCommand,
22 resolveWindowsEnvironment,
23 SpawnExecutableResolution,
24 WindowsShellEnvironment,
25 type WindowsShellEnvironmentReader,
26} from "./shell.ts";
27
28const withWindowsEnvironmentMocks = <A, E, R>(
29 effect: Effect.Effect<A, E, R>,
30 readEnvironment: WindowsShellEnvironmentReader,
31 commandAvailable: CommandAvailabilityChecker,
32) =>
33 effect.pipe(
34 Effect.provideService(WindowsShellEnvironment, readEnvironment),
35 Effect.provideService(CommandAvailability, commandAvailable),
36 );
37
38describe("extractPathFromShellOutput", () => {
39 it("extracts the path between capture markers", () => {
40 expect(
41 extractPathFromShellOutput(
42 "__T3CODE_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__T3CODE_PATH_END__\n",
43 ),
44 ).toBe("/opt/homebrew/bin:/usr/bin");
45 });
46
47 it("ignores shell startup noise around the capture markers", () => {
48 expect(
49 extractPathFromShellOutput(
50 "Welcome to fish\n__T3CODE_PATH_START__\n/opt/homebrew/bin:/usr/bin\n__T3CODE_PATH_END__\nBye\n",
51 ),
52 ).toBe("/opt/homebrew/bin:/usr/bin");
53 });
54
55 it("returns null when the markers are missing", () => {
56 expect(extractPathFromShellOutput("/opt/homebrew/bin /usr/bin")).toBeNull();
57 });
58});
59
60describe("readPathFromLoginShell", () => {
61 it("uses a shell-agnostic printenv PATH probe", () => {
62 const execFile = vi.fn<
63 (
64 file: string,
65 args: ReadonlyArray<string>,
66 options: { encoding: "utf8"; timeout: number },
67 ) => string
68 >(() => "__T3CODE_ENV_PATH_START__\n/a:/b\n__T3CODE_ENV_PATH_END__\n");
69
70 expect(readPathFromLoginShell("/opt/homebrew/bin/fish", execFile)).toBe("/a:/b");
71 expect(execFile).toHaveBeenCalledTimes(1);
72
73 const firstCall = execFile.mock.calls[0] as
74 | [string, ReadonlyArray<string>, { encoding: "utf8"; timeout: number }]
75 | undefined;
76 expect(firstCall).toBeDefined();
77 if (!firstCall) {
78 throw new Error("Expected execFile to be called");
79 }
80
81 const [shell, args, options] = firstCall;
82 expect(shell).toBe("/opt/homebrew/bin/fish");
83 expect(args).toHaveLength(2);
84 expect(args?.[0]).toBe("-ilc");
85 expect(args?.[1]).toContain("printenv PATH || true");
86 expect(args?.[1]).toContain("__T3CODE_ENV_PATH_START__");
87 expect(args?.[1]).toContain("__T3CODE_ENV_PATH_END__");
88 expect(options).toEqual({ encoding: "utf8", timeout: 5000 });
89 });
90});
91
92describe("readPathFromLaunchctl", () => {
93 it("returns a trimmed PATH value from launchctl", () => {
94 const execFile = vi.fn<
95 (
96 file: string,
97 args: ReadonlyArray<string>,
98 options: { encoding: "utf8"; timeout: number },
99 ) => string
100 >(() => " /opt/homebrew/bin:/usr/bin \n");
101
102 expect(readPathFromLaunchctl(execFile)).toBe("/opt/homebrew/bin:/usr/bin");
103 expect(execFile).toHaveBeenCalledWith("/bin/launchctl", ["getenv", "PATH"], {
104 encoding: "utf8",
105 timeout: 2000,
106 });
107 });
108
109 it("returns undefined when launchctl is unavailable", () => {
110 const execFile = vi.fn<
111 (
112 file: string,
113 args: ReadonlyArray<string>,
114 options: { encoding: "utf8"; timeout: number },
115 ) => string
116 >(() => {
117 throw new Error("spawn /bin/launchctl ENOENT");
118 });
119
120 expect(readPathFromLaunchctl(execFile)).toBeUndefined();
121 });
122});
123
124describe("readEnvironmentFromLoginShell", () => {
125 it("extracts multiple environment variables from a login shell command", () => {
126 const execFile = vi.fn<
127 (
128 file: string,
129 args: ReadonlyArray<string>,
130 options: { encoding: "utf8"; timeout: number },
131 ) => string
132 >(() =>
133 [
134 "__T3CODE_ENV_PATH_START__",
135 "/a:/b",
136 "__T3CODE_ENV_PATH_END__",
137 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
138 "/tmp/secretive.sock",
139 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
140 ].join("\n"),
141 );
142
143 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
144 PATH: "/a:/b",
145 SSH_AUTH_SOCK: "/tmp/secretive.sock",
146 });
147 expect(execFile).toHaveBeenCalledTimes(1);
148 });
149
150 it("omits environment variables that are missing or empty", () => {
151 const execFile = vi.fn<
152 (
153 file: string,
154 args: ReadonlyArray<string>,
155 options: { encoding: "utf8"; timeout: number },
156 ) => string
157 >(() =>
158 [
159 "__T3CODE_ENV_PATH_START__",
160 "/a:/b",
161 "__T3CODE_ENV_PATH_END__",
162 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
163 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
164 ].join("\n"),
165 );
166
167 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
168 PATH: "/a:/b",
169 });
170 });
171
172 it("preserves surrounding whitespace in captured values", () => {
173 const execFile = vi.fn<
174 (
175 file: string,
176 args: ReadonlyArray<string>,
177 options: { encoding: "utf8"; timeout: number },
178 ) => string
179 >(() =>
180 ["__T3CODE_ENV_CUSTOM_VAR_START__", " padded value ", "__T3CODE_ENV_CUSTOM_VAR_END__"].join(
181 "\n",
182 ),
183 );
184
185 expect(readEnvironmentFromLoginShell("/bin/zsh", ["CUSTOM_VAR"], execFile)).toEqual({
186 CUSTOM_VAR: " padded value ",
187 });
188 });
189});
190
191describe("listLoginShellCandidates", () => {
192 it("returns env shell, user shell, then the platform fallback without duplicates", () => {
193 expect(listLoginShellCandidates("darwin", " /opt/homebrew/bin/nu ", "/bin/zsh")).toEqual([
194 "/opt/homebrew/bin/nu",
195 "/bin/zsh",
196 ]);
197 });
198
199 it("falls back to the platform default when no shells are available", () => {
200 expect(listLoginShellCandidates("linux", undefined, "")).toEqual(["/bin/bash"]);
201 });
202});
203
204describe("mergePathEntries", () => {
205 it("prefers login-shell PATH entries and keeps inherited extras", () => {
206 expect(
207 mergePathEntries("/opt/homebrew/bin:/usr/bin", "/Users/test/.local/bin:/usr/bin", "darwin"),
208 ).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
209 });
210
211 it("uses the platform-specific delimiter", () => {
212 expect(mergePathEntries("C:\\Tools;C:\\Windows", "C:\\Windows;C:\\Git", "win32")).toBe(
213 "C:\\Tools;C:\\Windows;C:\\Git",
214 );
215 });
216});
217
218describe("readEnvironmentFromWindowsShell", () => {
219 it("extracts environment variables from a PowerShell command", () => {
220 const execFile = vi.fn<
221 (
222 file: string,
223 args: ReadonlyArray<string>,
224 options: { encoding: "utf8"; timeout: number },
225 ) => string
226 >(
227 () =>
228 "__T3CODE_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__T3CODE_ENV_PATH_END__\n",
229 );
230
231 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
232 PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
233 });
234 expect(execFile).toHaveBeenCalledWith(
235 "pwsh.exe",
236 expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
237 { encoding: "utf8", timeout: 5000 },
238 );
239 });
240
241 it("strips CRLF delimiters from captured PowerShell values", () => {
242 const execFile = vi.fn<
243 (
244 file: string,
245 args: ReadonlyArray<string>,
246 options: { encoding: "utf8"; timeout: number },
247 ) => string
248 >(
249 () =>
250 "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
251 );
252
253 expect(readEnvironmentFromWindowsShell(["FNM_DIR"], execFile)).toEqual({
254 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
255 });
256 });
257
258 it("omits -NoProfile when loadProfile is enabled", () => {
259 const execFile = vi.fn<
260 (
261 file: string,
262 args: ReadonlyArray<string>,
263 options: { encoding: "utf8"; timeout: number },
264 ) => string
265 >(() => "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n");
266
267 expect(readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, execFile)).toEqual({
268 PATH: "C:\\Tools",
269 });
270 expect(execFile).toHaveBeenCalledWith(
271 "pwsh.exe",
272 expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
273 { encoding: "utf8", timeout: 5000 },
274 );
275 expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
276 });
277
278 it("falls back to Windows PowerShell when pwsh.exe is unavailable", () => {
279 const execFile = vi.fn<
280 (
281 file: string,
282 args: ReadonlyArray<string>,
283 options: { encoding: "utf8"; timeout: number },
284 ) => string
285 >((file) => {
286 if (file === "pwsh.exe") {
287 throw new Error("spawn pwsh.exe ENOENT");
288 }
289 return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
290 });
291
292 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
293 PATH: "C:\\Tools",
294 });
295 expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
296 encoding: "utf8",
297 timeout: 5000,
298 });
299 expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
300 encoding: "utf8",
301 timeout: 5000,
302 });
303 });
304});
305
306describe("mergePathValues", () => {
307 it("sanitizes and dedupes Windows entries while preserving preferred order", () => {
308 expect(
309 mergePathValues(
310 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs"',
311 "c:\\users\\testuser\\appdata\\roaming\\npm;C:\\Windows\\System32",
312 "win32",
313 ),
314 ).toBe(
315 "C:\\Users\\testuser\\AppData\\Roaming\\npm;C:\\Program Files\\nodejs;C:\\Windows\\System32",
316 );
317 });
318
319 it("removes stray quotes from Windows entries", () => {
320 expect(
321 mergePathValues(
322 'C:\\Windows\\System32;C:\\cloudflared.exe;C:";C:\\Program Files\\nodejs',
323 undefined,
324 "win32",
325 ),
326 ).toBe("C:\\Windows\\System32;C:\\cloudflared.exe;C:;C:\\Program Files\\nodejs");
327 });
328
329 it("dedupes case-sensitively on POSIX", () => {
330 expect(mergePathValues("/usr/local/bin:/usr/bin", "/usr/bin:/USR/BIN", "linux")).toBe(
331 "/usr/local/bin:/usr/bin:/USR/BIN",
332 );
333 });
334});
335
336describe("resolveKnownWindowsCliDirs", () => {
337 it("returns known Windows CLI install directories in priority order", () => {
338 expect(
339 resolveKnownWindowsCliDirs({
340 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
341 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
342 USERPROFILE: "C:\\Users\\testuser",
343 }),
344 ).toEqual([
345 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
346 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
347 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
348 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
349 "C:\\Users\\testuser\\.local\\bin",
350 "C:\\Users\\testuser\\.bun\\bin",
351 "C:\\Users\\testuser\\scoop\\shims",
352 ]);
353 });
354});
355
356effectIt.layer(NodeServices.layer)("isCommandAvailable", (it) => {
357 it.effect("returns false when PATH is empty", () =>
358 Effect.gen(function* () {
359 expect(
360 yield* isCommandAvailable("definitely-not-installed", {
361 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
362 }).pipe(Effect.provideService(HostProcessPlatform, "win32")),
363 ).toBe(false);
364 }),
365 );
366});
367
368effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => {
369 it.effect("fails when PATH is empty", () =>
370 Effect.gen(function* () {
371 const result = yield* resolveCommandPath("definitely-not-installed", {
372 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
373 }).pipe(Effect.provideService(HostProcessPlatform, "win32"), Effect.result);
374
375 expect(result._tag).toBe("Failure");
376 }),
377 );
378});
379
380effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
381 it.effect("runs Windows executables directly without a shell", () =>
382 Effect.gen(function* () {
383 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
384 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
385 }).pipe(Effect.provideService(HostProcessPlatform, "win32"));
386
387 expect(command).toEqual({
388 command: "node.exe",
389 args: ["script.js", "hello & goodbye"],
390 shell: false,
391 });
392 }),
393 );
394
395 it.effect("escapes the executable and arguments for Windows command shims", () =>
396 Effect.gen(function* () {
397 const command = yield* resolveSpawnCommand(
398 "vp",
399 ["run", "value & calc", "%PATH%", 'quote"value'],
400 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
401 ).pipe(
402 Effect.provideService(HostProcessPlatform, "win32"),
403 Effect.provideService(
404 SpawnExecutableResolution,
405 () => "C:\\Program Files\\npm & tools\\vp.cmd",
406 ),
407 );
408
409 expect(command.shell).toBe(true);
410 expect(command.command).not.toContain(" & ");
411 expect(command.command).toContain("^&");
412 expect(command.args).toEqual([
413 '^"run^"',
414 '^"value^ ^&^ calc^"',
415 '^"^%PATH^%^"',
416 '^"quote\\^"value^"',
417 ]);
418 }),
419 );
420
421 it.effect("resolves against the effective environment when extending host env", () =>
422 Effect.gen(function* () {
423 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
424 yield* resolveSpawnCommand("codex", ["app-server"], {
425 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
426 extendEnv: true,
427 }).pipe(
428 Effect.provideService(HostProcessPlatform, "win32"),
429 Effect.provideService(HostProcessEnvironment, {
430 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
431 PATHEXT: ".COM;.EXE;.BAT;.CMD",
432 }),
433 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
434 resolvedEnvironment = env;
435 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
436 }),
437 );
438
439 expect(resolvedEnvironment).toEqual({
440 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
441 PATHEXT: ".COM;.EXE;.BAT;.CMD",
442 CODEX_HOME: "C:\\Users\\tester\\.codex",
443 });
444 }),
445 );
446
447 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
448 Effect.gen(function* () {
449 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
450 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
451 }).pipe(Effect.provideService(HostProcessPlatform, "win32"));
452
453 expect(command).toEqual({
454 command: "missing & calc",
455 args: ["unsafe & value"],
456 shell: false,
457 });
458 }),
459 );
460});
461
462effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
463 it.effect("uses known CLI directories as a fallback without changing shell PATH priority", () =>
464 Effect.gen(function* () {
465 const readEnvironment = vi.fn(
466 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
467 options?.loadProfile
468 ? { PATH: "C:\\Profile\\Bin" }
469 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
470 );
471 const commandAvailable = vi.fn(() => Effect.succeed(true));
472
473 expect(
474 yield* withWindowsEnvironmentMocks(
475 resolveWindowsEnvironment({
476 PATH: "C:\\Windows\\System32",
477 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
478 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
479 USERPROFILE: "C:\\Users\\testuser",
480 }),
481 readEnvironment,
482 commandAvailable,
483 ),
484 ).toEqual({
485 PATH: [
486 "C:\\Shell\\Bin",
487 "C:\\Windows\\System32",
488 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
489 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
490 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
491 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
492 "C:\\Users\\testuser\\.local\\bin",
493 "C:\\Users\\testuser\\.bun\\bin",
494 "C:\\Users\\testuser\\scoop\\shims",
495 ].join(";"),
496 });
497 expect(readEnvironment).toHaveBeenCalledTimes(1);
498 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
499 expect(commandAvailable).toHaveBeenCalledWith(
500 "node",
501 expect.objectContaining({ env: expect.any(Object) }),
502 );
503 }),
504 );
505
506 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
507 Effect.gen(function* () {
508 const readEnvironment = vi.fn(
509 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
510 options?.loadProfile
511 ? {
512 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
513 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
514 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
515 }
516 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
517 );
518 const commandAvailable = vi.fn(() => Effect.succeed(false));
519
520 expect(
521 yield* withWindowsEnvironmentMocks(
522 resolveWindowsEnvironment({
523 PATH: "C:\\Windows\\System32",
524 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
525 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
526 USERPROFILE: "C:\\Users\\testuser",
527 }),
528 readEnvironment,
529 commandAvailable,
530 ),
531 ).toEqual({
532 PATH: [
533 "C:\\Profile\\Node",
534 "C:\\Windows\\System32",
535 "C:\\Shell\\Bin",
536 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
537 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
538 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
539 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
540 "C:\\Users\\testuser\\.local\\bin",
541 "C:\\Users\\testuser\\.bun\\bin",
542 "C:\\Users\\testuser\\scoop\\shims",
543 ].join(";"),
544 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
545 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
546 });
547 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
548 expect(readEnvironment).toHaveBeenNthCalledWith(
549 2,
550 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
551 {
552 loadProfile: true,
553 },
554 );
555 expect(commandAvailable).toHaveBeenCalledTimes(1);
556 }),
557 );
558
559 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
560 Effect.gen(function* () {
561 const readEnvironment = vi.fn(
562 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
563 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
564 );
565 const commandAvailable = vi.fn(() => Effect.succeed(false));
566
567 expect(
568 yield* withWindowsEnvironmentMocks(
569 resolveWindowsEnvironment({
570 PATH: "C:\\Windows\\System32",
571 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
572 USERPROFILE: "C:\\Users\\testuser",
573 }),
574 readEnvironment,
575 commandAvailable,
576 ),
577 ).toEqual({
578 PATH: [
579 "C:\\Windows\\System32",
580 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
581 "C:\\Users\\testuser\\.local\\bin",
582 "C:\\Users\\testuser\\.bun\\bin",
583 "C:\\Users\\testuser\\scoop\\shims",
584 ].join(";"),
585 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
586 });
587 expect(commandAvailable).toHaveBeenCalledTimes(1);
588 }),
589 );
590});