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

shell.test.ts

806 lines27.2 KB

1// @effect-diagnostics nodeBuiltinImport:off -- The synchronous shell probe runs real commands with isolated config files.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { it as effectIt } from "@effect/vitest";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as NodeChildProcess from "node:child_process";
9import * as NodeFS from "node:fs";
10import * as NodeOS from "node:os";
11import * as NodePath from "node:path";
12import { describe, expect, it, vi } from "vite-plus/test";
13​
14import {
15 CommandAvailability,
16 CommandResolutionCache,
17 type CommandAvailabilityChecker,
18 isCommandAvailable,
19 listLoginShellCandidates,
20 mergePathEntries,
21 mergePathValues,
22 npmShimExecutable,
23 preferGitForWindowsBinary,
24 readEnvironmentFromLoginShell,
25 readEnvironmentFromWindowsShell,
26 resolveCommandPath,
27 resolveSpawnCommand,
28 resolveWindowsEnvironment,
29 SpawnExecutableResolution,
30 WindowsShellEnvironment,
31 withPathDirectoryListings,
32 type WindowsShellEnvironmentReader,
33} from "./shell.ts";
34​
35const withWindowsEnvironmentMocks = <A, E, R>(
36 effect: Effect.Effect<A, E, R>,
37 readEnvironment: WindowsShellEnvironmentReader,
38 commandAvailable: CommandAvailabilityChecker,
39) =>
40 effect.pipe(
41 Effect.provideService(WindowsShellEnvironment, readEnvironment),
42 Effect.provideService(CommandAvailability, commandAvailable),
43 );
44​
45describe("readEnvironmentFromLoginShell", () => {
46 // Opt in with an explicit binary, like the provider live probes; CI need not install Nu.
47 it.runIf(process.env.T3_TEST_NU_PATH !== undefined)(
48 "captures Nushell PATH and multiline values without external tools",
49 () => {
50 const shell = process.env.T3_TEST_NU_PATH!;
51 const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-nu-env-"));
52 try {
53 const toolPath = NodePath.join(home, "nu tools", "bin");
54 const extraToolPath = NodePath.join(home, "extra-tools", "bin");
55 NodeFS.mkdirSync(toolPath, { recursive: true });
56 NodeFS.mkdirSync(extraToolPath, { recursive: true });
57 const config = NodePath.join(home, "config.nu");
58 const envConfig = NodePath.join(home, "env.nu");
59 NodeFS.writeFileSync(envConfig, "");
60 NodeFS.writeFileSync(
61 config,
62 [
63 `$env.PATH = [${JSON.stringify(toolPath)}, "~/extra-tools/bin", "rel/dir", ""]`,
64 '$env.CUSTOM_VAR = " first\\nsecond "',
65 '$env.EMPTY_VAR = ""',
66 'print "startup noise"',
67 ].join("\n"),
68 );
69​
70 expect(
71 readEnvironmentFromLoginShell(
72 shell,
73 ["MISSING_VAR", "PATH", "EMPTY_VAR", "CUSTOM_VAR"],
74 (file, args, options) =>
75 NodeChildProcess.execFileSync(
76 file,
77 ["--no-history", "--config", config, "--env-config", envConfig, ...args],
78 {
79 ...options,
80 env: { HOME: home, XDG_CONFIG_HOME: home, PATH: toolPath },
81 },
82 ),
83 ),
84 ).toEqual({
85 PATH: `${toolPath}:${extraToolPath}:rel/dir:`,
86 CUSTOM_VAR: " first\nsecond ",
87 });
88 } finally {
89 NodeFS.rmSync(home, { recursive: true, force: true });
90 }
91 },
92 );
93​
94 it("extracts multiple environment variables from a login shell command", () => {
95 const execFile = vi.fn<
96 (
97 file: string,
98 args: ReadonlyArray<string>,
99 options: { encoding: "utf8"; timeout: number },
100 ) => string
101 >(() =>
102 [
103 "__T3CODE_ENV_PATH_START__",
104 "/a:/b",
105 "__T3CODE_ENV_PATH_END__",
106 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
107 "/tmp/secretive.sock",
108 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
109 ].join("\n"),
110 );
111​
112 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
113 PATH: "/a:/b",
114 SSH_AUTH_SOCK: "/tmp/secretive.sock",
115 });
116 expect(execFile).toHaveBeenCalledTimes(1);
117 });
118​
119 it("omits environment variables that are missing or empty", () => {
120 const execFile = vi.fn<
121 (
122 file: string,
123 args: ReadonlyArray<string>,
124 options: { encoding: "utf8"; timeout: number },
125 ) => string
126 >(() =>
127 [
128 "__T3CODE_ENV_PATH_START__",
129 "/a:/b",
130 "__T3CODE_ENV_PATH_END__",
131 "__T3CODE_ENV_SSH_AUTH_SOCK_START__",
132 "__T3CODE_ENV_SSH_AUTH_SOCK_END__",
133 ].join("\n"),
134 );
135​
136 expect(readEnvironmentFromLoginShell("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"], execFile)).toEqual({
137 PATH: "/a:/b",
138 });
139 });
140​
141 it("preserves multiline values and surrounding whitespace", () => {
142 const execFile = vi.fn<
143 (
144 file: string,
145 args: ReadonlyArray<string>,
146 options: { encoding: "utf8"; timeout: number },
147 ) => string
148 >(() =>
149 [
150 "__T3CODE_ENV_CUSTOM_VAR_START__",
151 " first\nsecond ",
152 "__T3CODE_ENV_CUSTOM_VAR_END__",
153 ].join("\n"),
154 );
155​
156 expect(readEnvironmentFromLoginShell("/bin/zsh", ["CUSTOM_VAR"], execFile)).toEqual({
157 CUSTOM_VAR: " first\nsecond ",
158 });
159 });
160});
161​
162describe("listLoginShellCandidates", () => {
163 it("returns env shell, user shell, then the platform fallback without duplicates", () => {
164 expect(listLoginShellCandidates("darwin", " /opt/homebrew/bin/nu ", "/bin/zsh")).toEqual([
165 "/opt/homebrew/bin/nu",
166 "/bin/zsh",
167 ]);
168 });
169});
170​
171describe("mergePathEntries", () => {
172 it("prefers login-shell PATH entries and keeps inherited extras", () => {
173 expect(
174 mergePathEntries("/opt/homebrew/bin:/usr/bin", "/Users/test/.local/bin:/usr/bin", "darwin"),
175 ).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
176 });
177});
178​
179describe("readEnvironmentFromWindowsShell", () => {
180 it("strips CRLF delimiters from captured PowerShell values", () => {
181 const execFile = vi.fn<
182 (
183 file: string,
184 args: ReadonlyArray<string>,
185 options: { encoding: "utf8"; timeout: number },
186 ) => string
187 >(
188 () =>
189 "__T3CODE_ENV_FNM_DIR_START__\r\nC:\\Users\\testuser\\AppData\\Roaming\\fnm\r\n__T3CODE_ENV_FNM_DIR_END__\r\n",
190 );
191​
192 expect(readEnvironmentFromWindowsShell(["FNM_DIR"], execFile)).toEqual({
193 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
194 });
195 });
196​
197 it("falls back to Windows PowerShell when pwsh.exe is unavailable", () => {
198 const execFile = vi.fn<
199 (
200 file: string,
201 args: ReadonlyArray<string>,
202 options: { encoding: "utf8"; timeout: number },
203 ) => string
204 >((file) => {
205 if (file === "pwsh.exe") {
206 throw new Error("spawn pwsh.exe ENOENT");
207 }
208 return "__T3CODE_ENV_PATH_START__\nC:\\Tools\n__T3CODE_ENV_PATH_END__\n";
209 });
210​
211 expect(readEnvironmentFromWindowsShell(["PATH"], execFile)).toEqual({
212 PATH: "C:\\Tools",
213 });
214 expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
215 encoding: "utf8",
216 timeout: 5000,
217 });
218 expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
219 encoding: "utf8",
220 timeout: 5000,
221 });
222 });
223});
224​
225describe("mergePathValues", () => {
226 it("sanitizes and dedupes Windows entries while preserving preferred order", () => {
227 expect(
228 mergePathValues(
229 'C:\\Users\\testuser\\AppData\\Roaming\\npm;"C:\\Program Files\\nodejs"',
230 "c:\\users\\testuser\\appdata\\roaming\\npm;C:\\Windows\\System32",
231 "win32",
232 ),
233 ).toBe(
234 "C:\\Users\\testuser\\AppData\\Roaming\\npm;C:\\Program Files\\nodejs;C:\\Windows\\System32",
235 );
236 });
237​
238 it("removes stray quotes from Windows entries", () => {
239 expect(
240 mergePathValues(
241 'C:\\Windows\\System32;C:\\cloudflared.exe;C:";C:\\Program Files\\nodejs',
242 undefined,
243 "win32",
244 ),
245 ).toBe("C:\\Windows\\System32;C:\\cloudflared.exe;C:;C:\\Program Files\\nodejs");
246 });
247​
248 it("dedupes case-sensitively on POSIX", () => {
249 expect(mergePathValues("/usr/local/bin:/usr/bin", "/usr/bin:/USR/BIN", "linux")).toBe(
250 "/usr/local/bin:/usr/bin:/USR/BIN",
251 );
252 });
253});
254​
255effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => {
256 const recordProbes = (env: NodeJS.ProcessEnv) =>
257 Effect.gen(function* () {
258 const probed: Array<string> = [];
259 const result = yield* resolveCommandPath("definitely-not-installed", { env }).pipe(
260 Effect.provideService(HostProcess.Platform, "win32"),
261 Effect.provideService(CommandResolutionCache, new Map()),
262 Effect.provide(
263 FileSystem.layerNoop({
264 stat: (filePath) =>
265 Effect.sync(() => {
266 probed.push(filePath);
267 return { type: "Directory" } as FileSystem.File.Info;
268 }),
269 }),
270 ),
271 );
272​
273 expect(result).toBeNull();
274 return probed;
275 });
276​
277 it.effect("still visits a PATH entry that differs only in case", () =>
278 Effect.gen(function* () {
279 const probed = yield* recordProbes({
280 PATH: "C:\\bin;C:\\BIN",
281 PATHEXT: ".COM;.EXE",
282 });
283​
284 // Windows 10+ can mark a directory case-sensitive, so the two spellings
285 // are not provably one directory and skipping the second could hide a
286 // command that is really there.
287 expect(probed).toHaveLength(8);
288 }),
289 );
290​
291 it.effect.each(["audit-command", "audit-command.CMD"])(
292 "resolves lowercase executable files for %s in a case-sensitive Windows PATH directory",
293 (command) =>
294 Effect.gen(function* () {
295 const fs = yield* FileSystem.FileSystem;
296 const path = yield* Path.Path;
297 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-case-sensitive-path-" });
298 const executable = path.join(cwd, "audit-command.cmd");
299 yield* fs.writeFileString(executable, "@echo off\n");
300​
301 const resolved = yield* resolveCommandPath(command, {
302 env: { PATH: cwd, PATHEXT: ".CMD" },
303 }).pipe(
304 Effect.provideService(HostProcess.Platform, "win32"),
305 Effect.provideService(CommandResolutionCache, new Map()),
306 Effect.provideService(FileSystem.FileSystem, {
307 ...fs,
308 stat: (filePath) =>
309 fs.stat(filePath === executable ? filePath : path.join(cwd, "missing")),
310 }),
311 );
312​
313 expect(resolved).toBe(executable);
314 }),
315 );
316​
317 it.effect("probes only listed PATH names and relists a directory that changes", () =>
318 Effect.gen(function* () {
319 const fs = yield* FileSystem.FileSystem;
320 const path = yield* Path.Path;
321 const first = yield* fs.makeTempDirectoryScoped();
322 const second = yield* fs.makeTempDirectoryScoped();
323 yield* fs.writeFileString(path.join(first, "cursor.CMD"), "");
324 yield* fs.writeFileString(path.join(second, "cursor.EXE"), "");
325 const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" };
326 const probed: Array<string> = [];
327 yield* Effect.gen(function* () {
328 expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD"));
329 expect(yield* isCommandAvailable("absent", { env })).toBe(false);
330 yield* fs.writeFileString(path.join(second, "late.EXE"), "");
331 yield* fs.utimes(second, 4_102_444_800, 4_102_444_800);
332 expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE"));
333 }).pipe(
334 withPathDirectoryListings,
335 Effect.provideService(FileSystem.FileSystem, {
336 ...fs,
337 stat: (file) => {
338 if (file !== first && file !== second) probed.push(file);
339 return fs.stat(file);
340 },
341 }),
342 );
343 expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]);
344 }).pipe(
345 Effect.provideService(HostProcess.Platform, "win32"),
346 Effect.provideService(CommandResolutionCache, new Map()),
347 ),
348 );
349});
350​
351describe("preferGitForWindowsBinary", () => {
352 const files =
353 (...paths: Array<string>) =>
354 (filePath: string) =>
355 paths.includes(filePath);
356​
357 it("runs the git.exe Git for Windows' launcher would start", () => {
358 expect(
359 preferGitForWindowsBinary(
360 "C:\\Program Files\\Git\\cmd\\git.EXE",
361 {},
362 files(
363 "C:\\Program Files\\Git\\ucrt64\\bin\\git.exe",
364 "C:\\Program Files\\Git\\mingw64\\bin\\git.exe",
365 ),
366 ),
367 ).toBe("C:\\Program Files\\Git\\ucrt64\\bin\\git.exe");
368 expect(
369 preferGitForWindowsBinary(
370 "D:\\PortableGit\\bin\\git.exe",
371 {},
372 files("D:\\PortableGit\\mingw64\\bin\\git.exe"),
373 ),
374 ).toBe("D:\\PortableGit\\mingw64\\bin\\git.exe");
375 expect(
376 preferGitForWindowsBinary(
377 "C:\\Program Files\\Git\\cmd\\git.exe",
378 {},
379 files("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe"),
380 ),
381 ).toBe("C:\\Program Files\\Git\\clangarm64\\bin\\git.exe");
382 });
383​
384 it("keeps the launcher when MSYSTEM is set", () => {
385 // The real git.exe only adds its own folders to PATH when MSYSTEM is unset;
386 // without them a `#!/bin/sh` hook cannot start.
387 expect(
388 preferGitForWindowsBinary(
389 "C:\\Program Files\\Git\\cmd\\git.exe",
390 { MSYSTEM: "MINGW64" },
391 files("C:\\Program Files\\Git\\mingw64\\bin\\git.exe"),
392 ),
393 ).toBe("C:\\Program Files\\Git\\cmd\\git.exe");
394 });
395​
396 it("leaves other gits and other launchers alone", () => {
397 const everything = () => true;
398 expect(preferGitForWindowsBinary("C:\\Users\\me\\scoop\\shims\\git.exe", {}, everything)).toBe(
399 "C:\\Users\\me\\scoop\\shims\\git.exe",
400 );
401 expect(preferGitForWindowsBinary("C:\\Program Files\\Git\\cmd\\gitk.exe", {}, everything)).toBe(
402 "C:\\Program Files\\Git\\cmd\\gitk.exe",
403 );
404 });
405});
406​
407// Byte for byte what `npm install -g opencode-ai` writes as `opencode.cmd`.
408const NPM_OPENCODE_SHIM = [
409 "@ECHO off",
410 "GOTO start",
411 ":find_dp0",
412 "SET dp0=%~dp0",
413 "EXIT /b",
414 ":start",
415 "SETLOCAL",
416 "CALL :find_dp0",
417 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
418 "",
419].join("\r\n");
420​
421describe("npmShimExecutable", () => {
422 const shimPath = "C:\\Users\\me\\AppData\\Roaming\\npm\\opencode.cmd";
423 const executable =
424 "C:\\Users\\me\\AppData\\Roaming\\npm\\node_modules\\opencode-ai\\bin\\opencode.exe";
425 const exists = (filePath: string) => filePath === executable;
426​
427 it("finds the executable npm's shim runs", () => {
428 expect(npmShimExecutable(shimPath, () => NPM_OPENCODE_SHIM, exists)).toBe(executable);
429 expect(
430 npmShimExecutable(shimPath.replace(".cmd", ".CMD"), () => NPM_OPENCODE_SHIM, exists),
431 ).toBe(executable);
432 });
433​
434 it("keeps a shim that does more than run the executable", () => {
435 const withSetting = NPM_OPENCODE_SHIM.replace(
436 "SETLOCAL",
437 "SETLOCAL\r\nSET OPENCODE_CONFIG=C:\\x",
438 );
439 expect(npmShimExecutable(shimPath, () => withSetting, exists)).toBeUndefined();
440 const nodeScript = NPM_OPENCODE_SHIM.replace(
441 '"%dp0%\\node_modules\\opencode-ai\\bin\\opencode.exe" %*',
442 '"%_prog%" "%dp0%\\node_modules\\opencode-ai\\bin\\opencode.js" %*',
443 );
444 expect(
445 npmShimExecutable(
446 shimPath,
447 () => nodeScript,
448 () => true,
449 ),
450 ).toBeUndefined();
451 });
452​
453 it("keeps a shim CMD would read differently", () => {
454 // CMD keeps trailing characters in an unquoted `SET` value, so these point
455 // `dp0`, and with it the executable, somewhere else.
456 for (const suffix of ["\u00a0", "\t", " "]) {
457 const altered = NPM_OPENCODE_SHIM.replace("SET dp0=%~dp0", `SET dp0=%~dp0${suffix}`);
458 expect(
459 npmShimExecutable(
460 shimPath,
461 () => altered,
462 () => true,
463 ),
464 ).toBeUndefined();
465 }
466 const nonBreakingSeparator = NPM_OPENCODE_SHIM.replace(
467 'opencode.exe" %*',
468 'opencode.exe"\u00a0%*',
469 );
470 expect(
471 npmShimExecutable(
472 shimPath,
473 () => nonBreakingSeparator,
474 () => true,
475 ),
476 ).toBeUndefined();
477 const indented = NPM_OPENCODE_SHIM.replace("SETLOCAL", " SETLOCAL");
478 expect(
479 npmShimExecutable(
480 shimPath,
481 () => indented,
482 () => true,
483 ),
484 ).toBeUndefined();
485 });
486​
487 it("keeps the shim when its executable is missing or it is not a .cmd", () => {
488 expect(
489 npmShimExecutable(
490 shimPath,
491 () => NPM_OPENCODE_SHIM,
492 () => false,
493 ),
494 ).toBeUndefined();
495 expect(
496 npmShimExecutable(
497 shimPath,
498 () => undefined,
499 () => true,
500 ),
501 ).toBeUndefined();
502 expect(
503 npmShimExecutable(
504 shimPath.replace(".cmd", ".bat"),
505 () => NPM_OPENCODE_SHIM,
506 () => true,
507 ),
508 ).toBeUndefined();
509 });
510});
511​
512effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
513 it.effect("runs Windows executables directly without a shell", () =>
514 Effect.gen(function* () {
515 const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], {
516 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
517 }).pipe(
518 Effect.provideService(HostProcess.Platform, "win32"),
519 Effect.provideService(CommandResolutionCache, new Map()),
520 );
521​
522 expect(command).toEqual({
523 command: "node.exe",
524 args: ["script.js", "hello & goodbye"],
525 shell: false,
526 });
527 }),
528 );
529​
530 it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
531 "runs the executable behind an npm shim directly when asked",
532 () =>
533 Effect.scoped(
534 Effect.gen(function* () {
535 const fs = yield* FileSystem.FileSystem;
536 const path = yield* Path.Path;
537 const prefix = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-shim-" });
538 const shim = path.join(prefix, "opencode.cmd");
539 const executable = path.join(
540 prefix,
541 "node_modules",
542 "opencode-ai",
543 "bin",
544 "opencode.exe",
545 );
546 yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
547 yield* fs.writeFileString(executable, "");
548 yield* fs.writeFileString(shim, NPM_OPENCODE_SHIM);
549 const resolve = (bypassNpmShim: boolean) =>
550 resolveSpawnCommand("opencode", ["serve", "--port=4096"], {
551 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
552 bypassNpmShim,
553 }).pipe(
554 Effect.provideService(HostProcess.Platform, "win32"),
555 Effect.provideService(CommandResolutionCache, new Map()),
556 Effect.provideService(SpawnExecutableResolution, () => shim),
557 );
558​
559 expect(yield* resolve(true)).toEqual({
560 command: executable,
561 args: ["serve", "--port=4096"],
562 shell: false,
563 });
564 expect((yield* resolve(false)).shell).toBe(true);
565 }),
566 ),
567 );
568​
569 it.effect("builds one escaped cmd.exe line for Windows command shims", () =>
570 Effect.gen(function* () {
571 const command = yield* resolveSpawnCommand(
572 "vp",
573 [
574 "run",
575 "value & calc",
576 "%PATH%",
577 'quote"value',
578 "C:\\dir with space\\",
579 'slash\\"quote',
580 "x|y<z>^",
581 ],
582 { env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" } },
583 ).pipe(
584 Effect.provideService(HostProcess.Platform, "win32"),
585 Effect.provideService(CommandResolutionCache, new Map()),
586 Effect.provideService(
587 SpawnExecutableResolution,
588 () => "C:\\Program Files\\npm & tools\\vp.cmd",
589 ),
590 );
591​
592 // No args alongside `shell: true`: Node prints DEP0190 for that pairing.
593 expect(command).toEqual({
594 command: [
595 String.raw`^"C:\Program^ Files\npm^ ^&^ tools\vp.cmd^"`,
596 String.raw`^"run^"`,
597 String.raw`^"value^ ^&^ calc^"`,
598 String.raw`^"^%PATH^%^"`,
599 String.raw`^"quote\^"value^"`,
600 String.raw`^"C:\dir^ with^ space\\^"`,
601 String.raw`^"slash\\\^"quote^"`,
602 String.raw`^"x^|y^<z^>^^^"`,
603 ].join(" "),
604 args: [],
605 shell: true,
606 });
607 }),
608 );
609​
610 it.effect("resolves against the effective environment when extending host env", () =>
611 Effect.gen(function* () {
612 let resolvedEnvironment: NodeJS.ProcessEnv | undefined;
613 yield* resolveSpawnCommand("codex", ["app-server"], {
614 env: { CODEX_HOME: "C:\\Users\\tester\\.codex" },
615 extendEnv: true,
616 }).pipe(
617 Effect.provideService(HostProcess.Platform, "win32"),
618 Effect.provideService(CommandResolutionCache, new Map()),
619 Effect.provideService(HostProcess.Environment, {
620 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
621 PATHEXT: ".COM;.EXE;.BAT;.CMD",
622 }),
623 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) => {
624 resolvedEnvironment = env;
625 return "C:\\Users\\tester\\AppData\\Roaming\\npm\\codex.cmd";
626 }),
627 );
628​
629 expect(resolvedEnvironment).toEqual({
630 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
631 PATHEXT: ".COM;.EXE;.BAT;.CMD",
632 CODEX_HOME: "C:\\Users\\tester\\.codex",
633 });
634 }),
635 );
636​
637 it.effect("does not fall back to a shell for unresolved Windows commands", () =>
638 Effect.gen(function* () {
639 const command = yield* resolveSpawnCommand("missing & calc", ["unsafe & value"], {
640 env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
641 }).pipe(
642 Effect.provideService(HostProcess.Platform, "win32"),
643 Effect.provideService(CommandResolutionCache, new Map()),
644 );
645​
646 expect(command).toEqual({
647 command: "missing & calc",
648 args: ["unsafe & value"],
649 shell: false,
650 });
651 }),
652 );
653});
654​
655effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => {
656 it.effect("uses known CLI directories as a fallback without changing shell PATH priority", () =>
657 Effect.gen(function* () {
658 const readEnvironment = vi.fn(
659 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
660 options?.loadProfile
661 ? { PATH: "C:\\Profile\\Bin" }
662 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
663 );
664 const commandAvailable = vi.fn(() => Effect.succeed(true));
665​
666 expect(
667 yield* withWindowsEnvironmentMocks(
668 resolveWindowsEnvironment({
669 PATH: "C:\\Windows\\System32",
670 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
671 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
672 USERPROFILE: "C:\\Users\\testuser",
673 }),
674 readEnvironment,
675 commandAvailable,
676 ),
677 ).toEqual({
678 PATH: [
679 "C:\\Shell\\Bin",
680 "C:\\Windows\\System32",
681 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
682 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
683 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
684 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
685 "C:\\Users\\testuser\\.local\\bin",
686 "C:\\Users\\testuser\\.bun\\bin",
687 "C:\\Users\\testuser\\scoop\\shims",
688 ].join(";"),
689 });
690 expect(readEnvironment).toHaveBeenCalledTimes(1);
691 expect(readEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
692 expect(commandAvailable).toHaveBeenCalledWith(
693 "node",
694 expect.objectContaining({ env: expect.any(Object) }),
695 );
696 }),
697 );
698​
699 it.effect(
700 "probes node with one PATH key when inherited environment records have mixed casing",
701 () =>
702 Effect.gen(function* () {
703 const probedEnvironments: Array<NodeJS.ProcessEnv | undefined> = [];
704​
705 yield* withWindowsEnvironmentMocks(
706 resolveWindowsEnvironment({ Path: "C:\\Stale", PATH: "C:\\Windows\\System32" }),
707 () => ({ PATH: "C:\\Shell\\Bin" }),
708 (_command, options) =>
709 Effect.sync(() => {
710 probedEnvironments.push(options?.env);
711 return true;
712 }),
713 );
714​
715 const pathEntries = Object.entries(probedEnvironments[0] ?? {}).filter(
716 ([key]) => key.toUpperCase() === "PATH",
717 );
718 expect(pathEntries).toEqual([["PATH", "C:\\Shell\\Bin;C:\\Windows\\System32"]]);
719 }),
720 );
721​
722 it.effect("loads the PowerShell profile when baseline env cannot resolve node", () =>
723 Effect.gen(function* () {
724 const readEnvironment = vi.fn(
725 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
726 options?.loadProfile
727 ? {
728 PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
729 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
730 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
731 }
732 : { PATH: "C:\\Shell\\Bin;C:\\Windows\\System32" },
733 );
734 const commandAvailable = vi.fn(() => Effect.succeed(false));
735​
736 expect(
737 yield* withWindowsEnvironmentMocks(
738 resolveWindowsEnvironment({
739 PATH: "C:\\Windows\\System32",
740 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
741 LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
742 USERPROFILE: "C:\\Users\\testuser",
743 }),
744 readEnvironment,
745 commandAvailable,
746 ),
747 ).toEqual({
748 PATH: [
749 "C:\\Profile\\Node",
750 "C:\\Windows\\System32",
751 "C:\\Shell\\Bin",
752 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
753 "C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
754 "C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
755 "C:\\Users\\testuser\\AppData\\Local\\pnpm",
756 "C:\\Users\\testuser\\.local\\bin",
757 "C:\\Users\\testuser\\.bun\\bin",
758 "C:\\Users\\testuser\\scoop\\shims",
759 ].join(";"),
760 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
761 FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
762 });
763 expect(readEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
764 expect(readEnvironment).toHaveBeenNthCalledWith(
765 2,
766 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
767 {
768 loadProfile: true,
769 },
770 );
771 expect(commandAvailable).toHaveBeenCalledTimes(1);
772 }),
773 );
774​
775 it.effect("keeps the baseline env when profiled probe still does not resolve node", () =>
776 Effect.gen(function* () {
777 const readEnvironment = vi.fn(
778 (_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
779 options?.loadProfile ? { FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm" } : {},
780 );
781 const commandAvailable = vi.fn(() => Effect.succeed(false));
782​
783 expect(
784 yield* withWindowsEnvironmentMocks(
785 resolveWindowsEnvironment({
786 PATH: "C:\\Windows\\System32",
787 APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
788 USERPROFILE: "C:\\Users\\testuser",
789 }),
790 readEnvironment,
791 commandAvailable,
792 ),
793 ).toEqual({
794 PATH: [
795 "C:\\Windows\\System32",
796 "C:\\Users\\testuser\\AppData\\Roaming\\npm",
797 "C:\\Users\\testuser\\.local\\bin",
798 "C:\\Users\\testuser\\.bun\\bin",
799 "C:\\Users\\testuser\\scoop\\shims",
800 ].join(";"),
801 FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
802 });
803 expect(commandAvailable).toHaveBeenCalledTimes(1);
804 }),
805 );
806});