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

shell.test.ts

776 lines27.6 KB

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 * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7import * as TestClock from "effect/testing/TestClock";
8import { describe, expect, it, vi } from "vite-plus/test";
9​
10import {
11 CommandAvailability,
12 CommandResolutionCache,
13 type CommandAvailabilityChecker,
14 isCommandAvailable,
15 listLoginShellCandidates,
16 mergePathEntries,
17 mergePathValues,
18 readEnvironmentFromLoginShell,
19 readEnvironmentFromWindowsShell,
20 readPathFromLaunchctl,
21 readPathFromLoginShell,
22 resolveCommandPath,
23 resolveKnownWindowsCliDirs,
24 resolveSpawnCommand,
25 resolveWindowsEnvironment,
26 SpawnExecutableResolution,
27 type SpawnExecutableResolver,
28 WindowsShellEnvironment,
29 withPathDirectoryListings,
30 type WindowsShellEnvironmentReader,
31} from "./shell.ts";
32​
33const withWindowsEnvironmentMocks = <A, E, R>(
34 effect: Effect.Effect<A, E, R>,
35 readEnvironment: WindowsShellEnvironmentReader,
36 commandAvailable: CommandAvailabilityChecker,
37) =>
38 effect.pipe(
39 Effect.provideService(WindowsShellEnvironment, readEnvironment),
40 Effect.provideService(CommandAvailability, commandAvailable),
41 );
42​
43describe("readPathFromLoginShell", () => {
44 it("uses a shell-agnostic printenv PATH probe", () => {
45 const execFile = vi.fn<
46 (
47 file: string,
48 args: ReadonlyArray<string>,
49 options: { encoding: "utf8"; timeout: number },
50 ) => string
51 >(() => "__T3CODE_ENV_PATH_START__\n/a:/b\n__T3CODE_ENV_PATH_END__\n");
52​
53 expect(readPathFromLoginShell("/opt/homebrew/bin/fish", execFile)).toBe("/a:/b");
54 expect(execFile).toHaveBeenCalledTimes(1);
55​
56 const firstCall = execFile.mock.calls[0] as
57 | [string, ReadonlyArray<string>, { encoding: "utf8"; timeout: number }]
58 | undefined;
59 expect(firstCall).toBeDefined();
60 if (!firstCall) {
61 throw new Error("Expected execFile to be called");
62 }
63​
64 const [shell, args, options] = firstCall;
65 expect(shell).toBe("/opt/homebrew/bin/fish");
66 expect(args).toHaveLength(2);
67 expect(args?.[0]).toBe("-ilc");
68 expect(args?.[1]).toContain("printenv PATH || true");
69 expect(args?.[1]).toContain("__T3CODE_ENV_PATH_START__");
70 expect(args?.[1]).toContain("__T3CODE_ENV_PATH_END__");
71 expect(options).toEqual({ encoding: "utf8", timeout: 5000 });
72 });
73});
74​
75describe("readPathFromLaunchctl", () => {
76 it("returns a trimmed PATH value from launchctl", () => {
77 const execFile = vi.fn<
78 (
79 file: string,
80 args: ReadonlyArray<string>,
81 options: { encoding: "utf8"; timeout: number },
82 ) => string
83 >(() => " /opt/homebrew/bin:/usr/bin \n");
84​
85 expect(readPathFromLaunchctl(execFile)).toBe("/opt/homebrew/bin:/usr/bin");
86 expect(execFile).toHaveBeenCalledWith("/bin/launchctl", ["getenv", "PATH"], {
87 encoding: "utf8",
88 timeout: 2000,
89 });
90 });
91​
92 it("returns undefined when launchctl is unavailable", () => {
93 const execFile = vi.fn<
94 (
95 file: string,
96 args: ReadonlyArray<string>,
97 options: { encoding: "utf8"; timeout: number },
98 ) => string
99 >(() => {
100 throw new Error("spawn /bin/launchctl ENOENT");
101 });
102​
103 expect(readPathFromLaunchctl(execFile)).toBeUndefined();
104 });
105});
106​
107describe("readEnvironmentFromLoginShell", () => {
108 it("extracts multiple environment variables from a login shell command", () => {
109 const execFile = vi.fn<
110 (
111 file: string,
112 args: ReadonlyArray<string>,
113 options: { encoding: "utf8"; timeout: number },
114 ) => string
115 >(() =>
116 [
117 "__T3CODE_ENV_PATH_START__",
118 "/a:/b",
119 "__T3CODE_ENV_PATH_END__",
120 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
121 "/tmp/secretive.sock",
122 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
123 ].join("\n"),
124 );
125​
126 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
127 PATH: "/a:/b",
128 SSH_AUTH_SOCK: "/tmp/secretive.sock",
129 });
130 expect(execFile).toHaveBeenCalledTimes(1);
131 });
132​
133 it("omits environment variables that are missing or empty", () => {
134 const execFile = vi.fn<
135 (
136 file: string,
137 args: ReadonlyArray<string>,
138 options: { encoding: "utf8"; timeout: number },
139 ) => string
140 >(() =>
141 [
142 "__T3CODE_ENV_PATH_START__",
143 "/a:/b",
144 "__T3CODE_ENV_PATH_END__",
145 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
146 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
147 ].join("\n"),
148 );
149​
150 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
151 PATH: "/a:/b",
152 });
153 });
154​
155 it("preserves surrounding whitespace in captured values", () => {
156 const execFile = vi.fn<
157 (
158 file: string,
159 args: ReadonlyArray<string>,
160 options: { encoding: "utf8"; timeout: number },
161 ) => string
162 >(() =>
163 ["__T3CODE_ENV_CUSTOM_VAR_START__", " padded value ", "__T3CODE_ENV_CUSTOM_VAR_END__"].join(
164 "\n",
165 ),
166 );
167​
168 expect(readEnvironmentFromLoginShell("/bin/zsh", ["CUSTOM_VAR"], execFile)).toEqual({
169 CUSTOM_VAR: " padded value ",
170 });
171 });
172});
173​
174describe("listLoginShellCandidates", () => {
175 it("returns env shell, user shell, then the platform fallback without duplicates", () => {
176 expect(listLoginShellCandidates("darwin", " /opt/homebrew/bin/nu ", "/bin/zsh")).toEqual([
177 "/opt/homebrew/bin/nu",
178 "/bin/zsh",
179 ]);
180 });
181​
182 it("falls back to the platform default when no shells are available", () => {
183 expect(listLoginShellCandidates("linux", undefined, "")).toEqual(["/bin/bash"]);
184 });
185});
186​
187describe("mergePathEntries", () => {
188 it("prefers login-shell PATH entries and keeps inherited extras", () => {
189 expect(
190 mergePathEntries("/opt/homebrew/bin:/usr/bin", "/Users/test/.local/bin:/usr/bin", "darwin"),
191 ).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
192 });
193​
194 it("uses the platform-specific delimiter", () => {
195 expect(mergePathEntries("C:\\Tools;C:\\Windows", "C:\\Windows;C:\\Git", "win32")).toBe(
196 "C:\\Tools;C:\\Windows;C:\\Git",
197 );
198 });
199});
200​
201describe("readEnvironmentFromWindowsShell", () => {
202 it("extracts environment variables from a PowerShell command", () => {
203 const execFile = vi.fn<
204 (
205 file: string,
206 args: ReadonlyArray<string>,
207 options: { encoding: "utf8"; timeout: number },
208 ) => string
209 >(
210 () =>
211 "__T3CODE_ENV_PATH_START__\nC:\\Users\\testuser\\AppData\\Roaming\\npm\n__T3CODE_ENV_PATH_END__\n",
212 );
213​
214 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
215 PATH: "C:\\Users\\testuser\\AppData\\Roaming\\npm",
216 });
217 expect(execFile).toHaveBeenCalledWith(
218 "pwsh.exe",
219 expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
220 { encoding: "utf8", timeout: 5000 },
221 );
222 });
223​
224 it("strips CRLF delimiters from captured PowerShell values", () => {
225 const execFile = vi.fn<
226 (
227 file: string,
228 args: ReadonlyArray<string>,
229 options: { encoding: "utf8"; timeout: number },
230 ) => string
231 >(
232 () =>
233 "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
234 );
235​
236 expect(readEnvironmentFromWindowsShell(["FNM_DIR"], execFile)).toEqual({
237 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
238 });
239 });
240​
241 it("omits -NoProfile when loadProfile is enabled", () => {
242 const execFile = vi.fn<
243 (
244 file: string,
245 args: ReadonlyArray<string>,
246 options: { encoding: "utf8"; timeout: number },
247 ) => string
248 >(() => "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n");
249​
250 expect(readEnvironmentFromWindowsShell(["PATH"], { loadProfile: true }, execFile)).toEqual({
251 PATH: "C:\\Tools",
252 });
253 expect(execFile).toHaveBeenCalledWith(
254 "pwsh.exe",
255 expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
256 { encoding: "utf8", timeout: 5000 },
257 );
258 expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
259 });
260​
261 it("falls back to Windows PowerShell when pwsh.exe is unavailable", () => {
262 const execFile = vi.fn<
263 (
264 file: string,
265 args: ReadonlyArray<string>,
266 options: { encoding: "utf8"; timeout: number },
267 ) => string
268 >((file) => {
269 if (file === "pwsh.exe") {
270 throw new Error("spawn pwsh.exe ENOENT");
271 }
272 return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
273 });
274​
275 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
276 PATH: "C:\\Tools",
277 });
278 expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
279 encoding: "utf8",
280 timeout: 5000,
281 });
282 expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
283 encoding: "utf8",
284 timeout: 5000,
285 });
286 });
287});
288​
289describe("mergePathValues", () => {
290 it("sanitizes and dedupes Windows entries while preserving preferred order", () => {
291 expect(
292 mergePathValues(
293 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs"',
294 "c:\\users\\testuser\\appdata\\roaming\\npm;C:\\Windows\\System32",
295 "win32",
296 ),
297 ).toBe(
298 "C:\\Users\\testuser\\AppData\\Roaming\\npm;C:\\Program Files\\nodejs;C:\\Windows\\System32",
299 );
300 });
301​
302 it("removes stray quotes from Windows entries", () => {
303 expect(
304 mergePathValues(
305 'C:\\Windows\\System32;C:\\cloudflared.exe;C:";C:\\Program Files\\nodejs',
306 undefined,
307 "win32",
308 ),
309 ).toBe("C:\\Windows\\System32;C:\\cloudflared.exe;C:;C:\\Program Files\\nodejs");
310 });
311​
312 it("dedupes case-sensitively on POSIX", () => {
313 expect(mergePathValues("/usr/local/bin:/usr/bin", "/usr/bin:/USR/BIN", "linux")).toBe(
314 "/usr/local/bin:/usr/bin:/USR/BIN",
315 );
316 });
317});
318​
319describe("resolveKnownWindowsCliDirs", () => {
320 it("returns known Windows CLI install directories in priority order", () => {
321 expect(
322 resolveKnownWindowsCliDirs({
323 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
324 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
325 USERPROFILE: "C:\\Users\\testuser",
326 }),
327 ).toEqual([
328 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
329 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
330 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
331 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
332 "C:\\Users\\testuser\\.local\\bin",
333 "C:\\Users\\testuser\\.bun\\bin",
334 "C:\\Users\\testuser\\scoop\\shims",
335 ]);
336 });
337});
338​
339effectIt.layer(NodeServices.layer)("isCommandAvailable", (it) => {
340 it.effect("returns false when PATH is empty", () =>
341 Effect.gen(function* () {
342 expect(
343 yield* isCommandAvailable("definitely-not-installed", {
344 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
345 }).pipe(Effect.provideService(HostProcessPlatform, "win32")),
346 ).toBe(false);
347 }),
348 );
349});
350​
351effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => {
352 it.effect("fails when PATH is empty", () =>
353 Effect.gen(function* () {
354 const result = yield* resolveCommandPath("definitely-not-installed", {
355 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
356 }).pipe(Effect.provideService(HostProcessPlatform, "win32"), Effect.result);
357​
358 expect(result._tag).toBe("Failure");
359 }),
360 );
361​
362 // Records every path the scan stats, without ever reporting a match, so the
363 // walk runs to exhaustion and the probe set can be inspected. Assertions
364 // below count probes rather than naming paths: `Path` is the host's, so the
365 // separator differs between a Windows and a Linux CI runner.
366 const recordProbes = (env: NodeJS.ProcessEnv) =>
367 Effect.gen(function* () {
368 const probed: Array<string> = [];
369 const result = yield* resolveCommandPath("definitely-not-installed", { env }).pipe(
370 Effect.provideService(HostProcessPlatform, "win32"),
371 Effect.provideService(CommandResolutionCache, new Map()),
372 Effect.provide(
373 FileSystem.layerNoop({
374 stat: (filePath) =>
375 Effect.sync(() => {
376 probed.push(filePath);
377 return { type: "Directory" } as FileSystem.File.Info;
378 }),
379 }),
380 ),
381 Effect.result,
382 );
383​
384 expect(result._tag).toBe("Failure");
385 return probed;
386 });
387​
388 it.effect("visits a repeated PATH directory only once", () =>
389 Effect.gen(function* () {
390 const probed = yield* recordProbes({
391 PATH: "C:\\bin;C:\\other;C:\\bin;C:\\other",
392 PATHEXT: ".COM;.EXE",
393 });
394​
395 // Two directories, two extensions, upper and lowercase spellings.
396 expect(probed).toHaveLength(8);
397 expect(new Set(probed).size).toBe(probed.length);
398 }),
399 );
400​
401 it.effect("still visits a PATH entry that differs only in case", () =>
402 Effect.gen(function* () {
403 const probed = yield* recordProbes({
404 PATH: "C:\\bin;C:\\BIN",
405 PATHEXT: ".COM;.EXE",
406 });
407​
408 // Deliberately not folded together. Windows 10+ can mark a directory
409 // case-sensitive, so the two spellings are not provably one directory and
410 // skipping the second could hide a command that is really there.
411 expect(probed).toHaveLength(8);
412 }),
413 );
414​
415 it.effect.each(["audit-command", "audit-command.CMD"])(
416 "resolves lowercase executable files for %s in a case-sensitive Windows PATH directory",
417 (command) =>
418 Effect.gen(function* () {
419 const fs = yield* FileSystem.FileSystem;
420 const path = yield* Path.Path;
421 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-case-sensitive-path-" });
422 const executable = path.join(cwd, "audit-command.cmd");
423 yield* fs.writeFileString(executable, "@echo off\n");
424​
425 const resolved = yield* resolveCommandPath(command, {
426 env: { PATH: cwd, PATHEXT: ".CMD" },
427 }).pipe(
428 Effect.provideService(HostProcessPlatform, "win32"),
429 Effect.provideService(CommandResolutionCache, new Map()),
430 Effect.provideService(FileSystem.FileSystem, {
431 ...fs,
432 // Keep this case-sensitive fixture portable to case-insensitive hosts.
433 stat: (filePath) =>
434 fs.stat(filePath === executable ? filePath : path.join(cwd, "missing")),
435 }),
436 );
437​
438 expect(resolved).toBe(executable);
439 }),
440 );
441​
442 it.effect("keeps cached misses until expiry while allowing explicit paths", () =>
443 Effect.gen(function* () {
444 const fs = yield* FileSystem.FileSystem;
445 const path = yield* Path.Path;
446 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-path-cache-" });
447 const executable = path.join(cwd, "appeared.CMD");
448 const options = { env: { PATH: `${cwd};${cwd}`, PATHEXT: ".CMD" } };
449​
450 expect((yield* resolveCommandPath("appeared", options).pipe(Effect.result))._tag).toBe(
451 "Failure",
452 );
453 yield* fs.writeFileString(executable, "@echo off\n");
454 expect((yield* resolveCommandPath("appeared", options).pipe(Effect.result))._tag).toBe(
455 "Failure",
456 );
457 expect(yield* resolveCommandPath(executable, options)).toBe(executable);
458 yield* TestClock.adjust("30 seconds");
459 expect(yield* resolveCommandPath("appeared", options)).toBe(executable);
460 }).pipe(
461 Effect.provideService(HostProcessPlatform, "win32"),
462 Effect.provideService(CommandResolutionCache, new Map()),
463 ),
464 );
465​
466 it.effect("keeps upper and lowercase PATHEXT candidates", () =>
467 Effect.gen(function* () {
468 const probed = yield* recordProbes({
469 PATH: "C:\\bin",
470 PATHEXT: ".COM;.EXE;.BAT;.CMD",
471 });
472​
473 expect(probed).toHaveLength(8);
474 expect(probed.filter((filePath) => /\.(COM|EXE|BAT|CMD)$/.test(filePath))).toHaveLength(4);
475 expect(probed.filter((filePath) => /\.(com|exe|bat|cmd)$/.test(filePath))).toHaveLength(4);
476 }),
477 );
478​
479 it.effect("probes only listed PATH names and relists a directory that changes", () =>
480 Effect.gen(function* () {
481 const fs = yield* FileSystem.FileSystem;
482 const path = yield* Path.Path;
483 const first = yield* fs.makeTempDirectoryScoped();
484 const second = yield* fs.makeTempDirectoryScoped();
485 yield* fs.writeFileString(path.join(first, "cursor.CMD"), "");
486 yield* fs.writeFileString(path.join(second, "cursor.EXE"), "");
487 const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" };
488 const probed: Array<string> = [];
489 yield* Effect.gen(function* () {
490 expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD"));
491 expect(yield* isCommandAvailable("absent", { env })).toBe(false);
492 yield* fs.writeFileString(path.join(second, "late.EXE"), "");
493 yield* fs.utimes(second, 4_102_444_800, 4_102_444_800); // seconds: 2100-01-01
494 expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE"));
495 }).pipe(
496 withPathDirectoryListings,
497 Effect.provideService(FileSystem.FileSystem, {
498 ...fs,
499 stat: (file) => {
500 // Record candidate probes, not the per-lookup directory mtime checks.
501 if (file !== first && file !== second) probed.push(file);
502 return fs.stat(file);
503 },
504 }),
505 );
506 expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]);
507 }).pipe(
508 Effect.provideService(HostProcessPlatform, "win32"),
509 Effect.provideService(CommandResolutionCache, new Map()),
510 ),
511 );
512});
513​
514effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
515 it.effect("runs Windows executables directly without a shell", () =>
516 Effect.gen(function* () {
517 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
518 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
519 }).pipe(
520 Effect.provideService(HostProcessPlatform, "win32"),
521 Effect.provideService(CommandResolutionCache, new Map()),
522 );
523​
524 expect(command).toEqual({
525 command: "node.exe",
526 args: ["script.js", "hello & goodbye"],
527 shell: false,
528 });
529 }),
530 );
531​
532 it.effect("escapes the executable and arguments for Windows command shims", () =>
533 Effect.gen(function* () {
534 const command = yield* resolveSpawnCommand(
535 "vp",
536 ["run", "value & calc", "%PATH%", 'quote"value'],
537 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
538 ).pipe(
539 Effect.provideService(HostProcessPlatform, "win32"),
540 Effect.provideService(CommandResolutionCache, new Map()),
541 Effect.provideService(
542 SpawnExecutableResolution,
543 () => "C:\\Program Files\\npm & tools\\vp.cmd",
544 ),
545 );
546​
547 expect(command.shell).toBe(true);
548 expect(command.command).not.toContain(" & ");
549 expect(command.command).toContain("^&");
550 expect(command.args).toEqual([
551 '^"run^"',
552 '^"value^ ^&^ calc^"',
553 '^"^%PATH^%^"',
554 '^"quote\\^"value^"',
555 ]);
556 }),
557 );
558​
559 it.effect("resolves against the effective environment when extending host env", () =>
560 Effect.gen(function* () {
561 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
562 yield* resolveSpawnCommand("codex", ["app-server"], {
563 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
564 extendEnv: true,
565 }).pipe(
566 Effect.provideService(HostProcessPlatform, "win32"),
567 Effect.provideService(CommandResolutionCache, new Map()),
568 Effect.provideService(HostProcessEnvironment, {
569 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
570 PATHEXT: ".COM;.EXE;.BAT;.CMD",
571 }),
572 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
573 resolvedEnvironment = env;
574 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
575 }),
576 );
577​
578 expect(resolvedEnvironment).toEqual({
579 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
580 PATHEXT: ".COM;.EXE;.BAT;.CMD",
581 CODEX_HOME: "C:\\Users\\tester\\.codex",
582 });
583 }),
584 );
585​
586 it.effect("scans PATH once per command until the search environment changes", () =>
587 Effect.gen(function* () {
588 const scans: Array<string> = [];
589 const scan: SpawnExecutableResolver = (name, _platform, env) => {
590 scans.push(`${name}@${env.PATH}`);
591 return name === "missing" ? undefined : `${env.PATH}\\${name}.exe`;
592 };
593 const resolve = (command: string, path: string, resolver = scan) =>
594 resolveSpawnCommand(command, [], { env: { PATH: path, PATHEXT: ".EXE" } }).pipe(
595 Effect.provideService(HostProcessPlatform, "win32"),
596 Effect.provideService(SpawnExecutableResolution, resolver),
597 );
598​
599 expect((yield* resolve("git", "C:\\one")).command).toBe("C:\\one\\git.exe");
600 expect((yield* resolve("git", "C:\\one")).command).toBe("C:\\one\\git.exe");
601 // A failed spawn is how a provider reports "not installed", so a miss
602 // must clear the moment the binary appears.
603 yield* resolve("missing", "C:\\one");
604 yield* resolve("missing", "C:\\one");
605 expect((yield* resolve("git", "C:\\two")).command).toBe("C:\\two\\git.exe");
606 // Callers probe explicit paths they may have just written.
607 yield* resolve("C:\\tools\\git.exe", "C:\\one");
608 yield* resolve("C:\\tools\\git.exe", "C:\\one");
609 expect(scans).toEqual([
610 "git@C:\\one",
611 "missing@C:\\one",
612 "missing@C:\\one",
613 "git@C:\\two",
614 "C:\\tools\\git.exe@C:\\one",
615 "C:\\tools\\git.exe@C:\\one",
616 ]);
617​
618 yield* TestClock.adjust("31 seconds");
619 yield* resolve("git", "C:\\one");
620 expect(scans).toHaveLength(7);
621​
622 // Another resolver sharing the cache gets its own answer, not the cached one.
623 const elsewhere = yield* resolve("git", "C:\\one", () => "D:\\elsewhere\\git.exe");
624 expect(elsewhere.command).toBe("D:\\elsewhere\\git.exe");
625 expect((yield* resolve("git", "C:\\one")).command).toBe("C:\\one\\git.exe");
626 expect(scans).toHaveLength(7);
627 }).pipe(Effect.provideService(CommandResolutionCache, new Map())),
628 );
629​
630 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
631 Effect.gen(function* () {
632 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
633 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
634 }).pipe(
635 Effect.provideService(HostProcessPlatform, "win32"),
636 Effect.provideService(CommandResolutionCache, new Map()),
637 );
638​
639 expect(command).toEqual({
640 command: "missing & calc",
641 args: ["unsafe & value"],
642 shell: false,
643 });
644 }),
645 );
646});
647​
648effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
649 it.effect("uses known CLI directories as a fallback without changing shell PATH priority", () =>
650 Effect.gen(function* () {
651 const readEnvironment = vi.fn(
652 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
653 options?.loadProfile
654 ? { PATH: "C:\\Profile\\Bin" }
655 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
656 );
657 const commandAvailable = vi.fn(() => Effect.succeed(true));
658​
659 expect(
660 yield* withWindowsEnvironmentMocks(
661 resolveWindowsEnvironment({
662 PATH: "C:\\Windows\\System32",
663 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
664 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
665 USERPROFILE: "C:\\Users\\testuser",
666 }),
667 readEnvironment,
668 commandAvailable,
669 ),
670 ).toEqual({
671 PATH: [
672 "C:\\Shell\\Bin",
673 "C:\\Windows\\System32",
674 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
675 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
676 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
677 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
678 "C:\\Users\\testuser\\.local\\bin",
679 "C:\\Users\\testuser\\.bun\\bin",
680 "C:\\Users\\testuser\\scoop\\shims",
681 ].join(";"),
682 });
683 expect(readEnvironment).toHaveBeenCalledTimes(1);
684 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
685 expect(commandAvailable).toHaveBeenCalledWith(
686 "node",
687 expect.objectContaining({ env: expect.any(Object) }),
688 );
689 }),
690 );
691​
692 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
693 Effect.gen(function* () {
694 const readEnvironment = vi.fn(
695 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
696 options?.loadProfile
697 ? {
698 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
699 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
700 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
701 }
702 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
703 );
704 const commandAvailable = vi.fn(() => Effect.succeed(false));
705​
706 expect(
707 yield* withWindowsEnvironmentMocks(
708 resolveWindowsEnvironment({
709 PATH: "C:\\Windows\\System32",
710 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
711 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
712 USERPROFILE: "C:\\Users\\testuser",
713 }),
714 readEnvironment,
715 commandAvailable,
716 ),
717 ).toEqual({
718 PATH: [
719 "C:\\Profile\\Node",
720 "C:\\Windows\\System32",
721 "C:\\Shell\\Bin",
722 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
723 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
724 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
725 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
726 "C:\\Users\\testuser\\.local\\bin",
727 "C:\\Users\\testuser\\.bun\\bin",
728 "C:\\Users\\testuser\\scoop\\shims",
729 ].join(";"),
730 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
731 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
732 });
733 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
734 expect(readEnvironment).toHaveBeenNthCalledWith(
735 2,
736 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
737 {
738 loadProfile: true,
739 },
740 );
741 expect(commandAvailable).toHaveBeenCalledTimes(1);
742 }),
743 );
744​
745 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
746 Effect.gen(function* () {
747 const readEnvironment = vi.fn(
748 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
749 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
750 );
751 const commandAvailable = vi.fn(() => Effect.succeed(false));
752​
753 expect(
754 yield* withWindowsEnvironmentMocks(
755 resolveWindowsEnvironment({
756 PATH: "C:\\Windows\\System32",
757 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
758 USERPROFILE: "C:\\Users\\testuser",
759 }),
760 readEnvironment,
761 commandAvailable,
762 ),
763 ).toEqual({
764 PATH: [
765 "C:\\Windows\\System32",
766 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
767 "C:\\Users\\testuser\\.local\\bin",
768 "C:\\Users\\testuser\\.bun\\bin",
769 "C:\\Users\\testuser\\scoop\\shims",
770 ].join(";"),
771 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
772 });
773 expect(commandAvailable).toHaveBeenCalledTimes(1);
774 }),
775 );
776});