Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeOS from "node:os";
3import * as NodePath from "node:path";
4import * as NodeChildProcess from "node:child_process";
5import * as NodeFS from "node:fs";
6import * as Cache from "effect/Cache";
7import * as Clock from "effect/Clock";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12
13import * as HostProcess from "./HostProcess.ts";
14import * as Context from "effect/Context";
15const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
16const WINDOWS_PATH_DELIMITER = ";";
17const POSIX_PATH_DELIMITER = ":";
18const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
19
20type ExecFileSyncLike = (
21 file: string,
22 args: ReadonlyArray<string>,
23 options: {
24 encoding: "utf8";
25 timeout: number;
26 detached?: true;
27 stdio?: ["ignore", "pipe", "ignore"];
28 },
29) => string;
30
31function canExecuteFile(filePath: string): boolean {
32 try {
33 NodeFS.accessSync(filePath, NodeFS.constants.X_OK);
34 return true;
35 } catch {
36 return false;
37 }
38}
39
40export interface CommandAvailabilityOptions {
41 readonly env?: NodeJS.ProcessEnv;
42 readonly extendEnv?: boolean;
43}
44
45export type CommandAvailabilityChecker = (
46 command: string,
47 options?: CommandAvailabilityOptions,
48) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;
49
50const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
51
52/**
53 * Node hands the command string to `cmd.exe /d /s /c "<command>"` without any
54 * quoting, so every dynamic argument must be escaped to survive both cmd.exe
55 * parsing and the target program's `CommandLineToArgvW` parsing.
56 */
57function escapeWindowsShellArg(arg: string): string {
58 let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
59 // Double up trailing backslashes so the closing quote is not escaped away.
60 escaped = escaped.replace(/(\\*)$/, "$1$1");
61 escaped = `"${escaped}"`;
62 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
63}
64
65export interface ResolvedSpawnCommand {
66 readonly command: string;
67 readonly args: ReadonlyArray<string>;
68 readonly shell: boolean;
69}
70
71export type SpawnExecutableResolver = (
72 command: string,
73 platform: NodeJS.Platform,
74 env: NodeJS.ProcessEnv,
75) => string | undefined;
76
77function resolveSpawnExecutableWithNode(
78 command: string,
79 platform: NodeJS.Platform,
80 env: NodeJS.ProcessEnv,
81): string | undefined {
82 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
83 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
84 const candidates = resolveCommandCandidates(
85 command,
86 platform,
87 windowsPathExtensions,
88 path.extname,
89 );
90 const isExecutable = (candidate: string) => {
91 try {
92 if (!NodeFS.statSync(candidate).isFile()) return false;
93 if (platform === "win32") {
94 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
95 }
96 return canExecuteFile(candidate);
97 } catch {
98 return false;
99 }
100 };
101
102 if (command.includes("/") || command.includes("\\")) {
103 return candidates.find(isExecutable);
104 }
105
106 for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) {
107 const normalizedPathEntry = stripWrappingQuotes(pathEntry.trim());
108 if (normalizedPathEntry.length === 0) continue;
109 for (const candidate of candidates) {
110 const candidatePath = path.join(normalizedPathEntry, candidate);
111 if (isExecutable(candidatePath)) return candidatePath;
112 }
113 }
114 return undefined;
115}
116
117export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
118 "@t3tools/shared/shell/SpawnExecutableResolution",
119 {
120 defaultValue: () => resolveSpawnExecutableWithNode,
121 },
122);
123
124export interface WindowsEnvironmentProbeOptions {
125 readonly loadProfile?: boolean;
126}
127
128function trimNonEmpty(value: string | null | undefined): string | undefined {
129 const trimmed = value?.trim();
130 return trimmed && trimmed.length > 0 ? trimmed : undefined;
131}
132
133function readUserLoginShell(): string | undefined {
134 try {
135 return trimNonEmpty(NodeOS.userInfo().shell);
136 } catch {
137 return undefined;
138 }
139}
140
141export function listLoginShellCandidates(
142 platform: NodeJS.Platform,
143 shell: string | undefined,
144 userShell = readUserLoginShell(),
145): ReadonlyArray<string> {
146 const fallbackShell =
147 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
148 const seen = new Set<string>();
149 const candidates: string[] = [];
150
151 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
152 if (!candidate || seen.has(candidate)) {
153 continue;
154 }
155 seen.add(candidate);
156 candidates.push(candidate);
157 }
158
159 return candidates;
160}
161
162export function readPathFromLaunchctl(
163 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
164): string | undefined {
165 try {
166 return trimNonEmpty(
167 execFile("/bin/launchctl", ["getenv", "PATH"], {
168 encoding: "utf8",
169 timeout: 2000,
170 }),
171 );
172 } catch {
173 return undefined;
174 }
175}
176
177export function mergePathEntries(
178 preferredPath: string | undefined,
179 inheritedPath: string | undefined,
180 platform: NodeJS.Platform,
181): string | undefined {
182 const delimiter = platform === "win32" ? ";" : ":";
183 const merged: string[] = [];
184 const seen = new Set<string>();
185
186 for (const pathValue of [preferredPath, inheritedPath]) {
187 if (!pathValue) continue;
188 for (const entry of pathValue.split(delimiter)) {
189 const trimmedEntry = entry.trim();
190 if (!trimmedEntry || seen.has(trimmedEntry)) {
191 continue;
192 }
193 seen.add(trimmedEntry);
194 merged.push(trimmedEntry);
195 }
196 }
197
198 return merged.length > 0 ? merged.join(delimiter) : undefined;
199}
200
201function envCaptureStart(name: string): string {
202 return `__T3CODE_ENV_${name}_START__`;
203}
204
205function envCaptureEnd(name: string): string {
206 return `__T3CODE_ENV_${name}_END__`;
207}
208
209function buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
210 return names
211 .map((name) => {
212 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
213 throw new Error(`Unsupported environment variable name: ${name}`);
214 }
215
216 return [
217 `printf '%s\\n' '${envCaptureStart(name)}'`,
218 `printenv ${name} || true`,
219 `printf '%s\\n' '${envCaptureEnd(name)}'`,
220 ].join("; ");
221 })
222 .join("; ");
223}
224
225function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
226 return [
227 "$ErrorActionPreference = 'Stop'",
228 ...names.flatMap((name) => {
229 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
230 throw new Error(`Unsupported environment variable name: ${name}`);
231 }
232
233 return [
234 `Write-Output '${envCaptureStart(name)}'`,
235 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
236 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
237 `Write-Output '${envCaptureEnd(name)}'`,
238 ];
239 }),
240 ].join("; ");
241}
242
243function extractEnvironmentValue(output: string, name: string): string | undefined {
244 const startMarker = envCaptureStart(name);
245 const endMarker = envCaptureEnd(name);
246 const startIndex = output.indexOf(startMarker);
247 if (startIndex === -1) return undefined;
248
249 const valueStartIndex = startIndex + startMarker.length;
250 const endIndex = output.indexOf(endMarker, valueStartIndex);
251 if (endIndex === -1) return undefined;
252
253 const value = output
254 .slice(valueStartIndex, endIndex)
255 .replace(/^\r?\n/, "")
256 .replace(/\r?\n$/, "");
257
258 return value.length > 0 ? value : undefined;
259}
260
261export type ShellEnvironmentReader = (
262 shell: string,
263 names: ReadonlyArray<string>,
264 execFile?: ExecFileSyncLike,
265) => Partial<Record<string, string>>;
266
267export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
268 shell,
269 names,
270 execFile = NodeChildProcess.execFileSync,
271) => {
272 if (names.length === 0) {
273 return {};
274 }
275
276 // Interactive startup loads PATH entries; detaching prevents job control on an
277 // inherited controlling TTY from stopping the probe while the parent waits.
278 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(names)], {
279 encoding: "utf8",
280 timeout: 5000,
281 detached: true,
282 stdio: ["ignore", "pipe", "ignore"],
283 });
284
285 const environment: Partial<Record<string, string>> = {};
286 for (const name of names) {
287 const value = extractEnvironmentValue(output, name);
288 if (value !== undefined) {
289 environment[name] = value;
290 }
291 }
292
293 return environment;
294};
295
296export type WindowsShellEnvironmentReader = (
297 names: ReadonlyArray<string>,
298 options?: WindowsEnvironmentProbeOptions,
299) => Partial<Record<string, string>>;
300
301export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
302 "@t3tools/shared/shell/WindowsShellEnvironment",
303 {
304 defaultValue: () => readEnvironmentFromWindowsShell,
305 },
306);
307
308export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
309 "@t3tools/shared/shell/CommandAvailability",
310 {
311 defaultValue: () => isCommandAvailable,
312 },
313);
314
315export function readEnvironmentFromWindowsShell(
316 names: ReadonlyArray<string>,
317 execFile?: ExecFileSyncLike,
318): Partial<Record<string, string>>;
319export function readEnvironmentFromWindowsShell(
320 names: ReadonlyArray<string>,
321 options?: WindowsEnvironmentProbeOptions,
322 execFile?: ExecFileSyncLike,
323): Partial<Record<string, string>>;
324export function readEnvironmentFromWindowsShell(
325 names: ReadonlyArray<string>,
326 optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
327 maybeExecFile?: ExecFileSyncLike,
328): Partial<Record<string, string>> {
329 if (names.length === 0) {
330 return {};
331 }
332
333 const options =
334 typeof optionsOrExecFile === "function"
335 ? ({} satisfies WindowsEnvironmentProbeOptions)
336 : (optionsOrExecFile ?? {});
337 const execFile: ExecFileSyncLike =
338 typeof optionsOrExecFile === "function"
339 ? optionsOrExecFile
340 : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));
341 const command = buildWindowsEnvironmentCaptureCommand(names);
342 const args = [
343 "-NoLogo",
344 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
345 "-NonInteractive",
346 "-Command",
347 command,
348 ];
349 for (const shell of WINDOWS_SHELL_CANDIDATES) {
350 try {
351 const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
352
353 const environment: Partial<Record<string, string>> = {};
354 for (const name of names) {
355 const value = extractEnvironmentValue(output, name);
356 if (value !== undefined) {
357 environment[name] = value;
358 }
359 }
360 return environment;
361 } catch {
362 continue;
363 }
364 }
365
366 return {};
367}
368
369function stripWrappingQuotes(value: string): string {
370 return value.replace(/^"+|"+$/g, "");
371}
372
373function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
374 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
375}
376
377function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
378 const normalized = stripWrappingQuotes(entry.trim());
379 return platform === "win32" ? normalized.toLowerCase() : normalized;
380}
381
382function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
383 return platform === "win32" ? entry.replaceAll('"', "") : entry;
384}
385
386export function mergePathValues(
387 preferredPath: string | undefined,
388 inheritedPath: string | undefined,
389 platform: NodeJS.Platform,
390): string | undefined {
391 const delimiter = pathDelimiterForPlatform(platform);
392 const merged: string[] = [];
393 const seen = new Set<string>();
394
395 for (const rawValue of [preferredPath, inheritedPath]) {
396 if (!rawValue) continue;
397
398 for (const entry of rawValue.split(delimiter)) {
399 const sanitized = sanitizePathEntry(entry.trim(), platform);
400 if (sanitized.length === 0) continue;
401
402 const normalized = normalizePathEntryForComparison(sanitized, platform);
403 if (normalized.length === 0 || seen.has(normalized)) continue;
404
405 seen.add(normalized);
406 merged.push(sanitized);
407 }
408 }
409
410 return merged.length > 0 ? merged.join(delimiter) : undefined;
411}
412
413function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
414 return env.PATH ?? env.Path ?? env.path;
415}
416
417function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
418 return readEnvPath(env) ?? "";
419}
420
421function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
422 const rawValue = env.PATHEXT;
423 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
424 if (!rawValue) return fallback;
425
426 const parsed: string[] = [];
427 for (const entry of rawValue.split(";")) {
428 const trimmed = entry.trim();
429 if (trimmed.length === 0) continue;
430 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
431 }
432 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
433}
434
435function resolveCommandCandidates(
436 command: string,
437 platform: NodeJS.Platform,
438 windowsPathExtensions: ReadonlyArray<string>,
439 extname: (path: string) => string,
440): ReadonlyArray<string> {
441 if (platform !== "win32") return [command];
442 const extension = extname(command);
443 const normalizedExtension = extension.toUpperCase();
444
445 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
446 const commandWithoutExtension = command.slice(0, -extension.length);
447 return Array.from(
448 new Set([
449 command,
450 `${commandWithoutExtension}${normalizedExtension}`,
451 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
452 ]),
453 );
454 }
455
456 const candidates: string[] = [];
457 for (const candidateExtension of windowsPathExtensions) {
458 candidates.push(`${command}${candidateExtension}`);
459 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
460 }
461 return Array.from(new Set(candidates));
462}
463
464// Explicit-path resolution is never cached - callers probe paths they have
465// just written (e.g. managed binary installs). A "not-found" outcome is also
466// cached for the TTL, so a just-installed binary can stay invisible for up to
467// 30s unless resolved by explicit path.
468const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
469const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
470const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
471
472interface CommandResolutionCacheEntry {
473 readonly resolvedPath: string | null;
474 readonly expiresAtNanos: bigint;
475}
476
477export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
478 "@t3tools/shared/shell/CommandResolutionCache",
479 {
480 defaultValue: () => new Map(),
481 },
482);
483
484interface PathDirectoryListing {
485 readonly modified: number | null | undefined;
486 readonly names: ReadonlySet<string> | undefined;
487}
488
489const directoryMtime = (directory: string) =>
490 FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe(
491 Effect.map((info) =>
492 info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined,
493 ),
494 Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)),
495 );
496
497// Dated before it is read, so an entry added in between changes the mtime seen
498// on the next check. Without names, lookups probe candidates directly.
499const listPathDirectory = Effect.fnUntraced(function* (
500 directory: string,
501): Effect.fn.Return<PathDirectoryListing, never, FileSystem.FileSystem> {
502 const modified = yield* directoryMtime(directory);
503 if (modified == null) return { modified, names: modified === null ? new Set() : undefined };
504 const entries = yield* FileSystem.FileSystem.use((fileSystem) =>
505 fileSystem.readDirectory(directory),
506 ).pipe(Effect.orElseSucceed(() => undefined));
507 return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) };
508});
509
510const PathDirectoryListings = Context.Reference<
511 Cache.Cache<string, PathDirectoryListing, never, FileSystem.FileSystem> | undefined
512>("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined });
513
514export const withPathDirectoryListings =
515 /* Directory reads are cached inside one shell operation; a span for each lookup adds noise. */
516 Effect.fnUntraced(function* <A, E, R>(effect: Effect.Effect<A, E, R>) {
517 const listings = yield* Cache.make({
518 capacity: 1024,
519 lookup: listPathDirectory,
520 requireServicesAt: "lookup",
521 });
522 return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings));
523 });
524
525// An injected resolver may answer differently for the same search, so its
526// entries are kept apart from every other resolver's.
527let spawnResolverCacheIdCount = 0;
528const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver, number>();
529function spawnResolverCacheId(resolver: SpawnExecutableResolver): number {
530 const known = spawnResolverCacheIds.get(resolver);
531 if (known !== undefined) return known;
532 const id = spawnResolverCacheIdCount++;
533 spawnResolverCacheIds.set(resolver, id);
534 return id;
535}
536
537function cacheCommandResolution(
538 cache: Map<string, CommandResolutionCacheEntry>,
539 cacheKey: string,
540 resolvedPath: string | null,
541 nowNanos: bigint,
542): void {
543 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
544 const oldestKey = cache.keys().next().value;
545 if (oldestKey !== undefined) {
546 cache.delete(oldestKey);
547 }
548 }
549 cache.set(cacheKey, {
550 resolvedPath,
551 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
552 });
553}
554
555const isExecutableFile = Effect.fnUntraced(function* (
556 filePath: string,
557 platform: NodeJS.Platform,
558 windowsPathExtensions: ReadonlyArray<string>,
559): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
560 const fileSystem = yield* FileSystem.FileSystem;
561 const path = yield* Path.Path;
562 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
563 if (stat === null || stat.type !== "File") return false;
564
565 if (platform === "win32") {
566 const extension = path.extname(filePath);
567 if (extension.length === 0) return false;
568 return windowsPathExtensions.includes(extension.toUpperCase());
569 }
570
571 return canExecuteFile(filePath);
572});
573
574const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
575 command: string,
576 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
577): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
578 const path = yield* Path.Path;
579 const platform = options.platform;
580 const env = options.env ?? process.env;
581 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
582 const commandCandidates = resolveCommandCandidates(
583 command,
584 platform,
585 windowsPathExtensions,
586 path.extname,
587 );
588
589 if (command.includes("/") || command.includes("\\")) {
590 for (const candidate of commandCandidates) {
591 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
592 return candidate;
593 }
594 }
595 return null;
596 }
597
598 const pathValue = resolvePathEnvironmentVariable(env);
599 if (pathValue.length === 0) {
600 return null;
601 }
602
603 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
604 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
605 );
606 const cache = yield* CommandResolutionCache;
607 const nowNanos = yield* Clock.monotonicTimeNanos;
608 const cached = cache.get(cacheKey);
609 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
610 return cached.resolvedPath;
611 }
612
613 // Keep case variants: Windows can make PATH directories case-sensitive.
614 const pathEntries: string[] = [];
615 const seenPathEntries = new Set<string>();
616 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
617 const pathEntry = stripWrappingQuotes(entry.trim());
618 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
619
620 seenPathEntries.add(pathEntry);
621 pathEntries.push(pathEntry);
622 }
623
624 const listings = yield* PathDirectoryListings;
625 for (const pathEntry of pathEntries) {
626 let listing = listings && (yield* Cache.get(listings, pathEntry));
627 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
628 yield* Cache.invalidate(listings, pathEntry);
629 listing = yield* Cache.get(listings, pathEntry);
630 }
631 for (const candidate of commandCandidates) {
632 if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue;
633 const candidatePath = path.join(pathEntry, candidate);
634 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
635 cacheCommandResolution(cache, cacheKey, candidatePath, nowNanos);
636 return candidatePath;
637 }
638 }
639 }
640 cacheCommandResolution(cache, cacheKey, null, nowNanos);
641 return null;
642});
643
644export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
645 command: string,
646 options: CommandAvailabilityOptions = {},
647) {
648 return yield* resolveCommandPathForPlatform(command, {
649 env: options.env ?? (yield* HostProcess.Environment),
650 platform: yield* HostProcess.Platform,
651 });
652});
653
654// Git for Windows 2.56 moved x64 builds from mingw64 to ucrt64; ARM64 builds
655// live in clangarm64 and 32-bit ones in mingw32.
656const GIT_FOR_WINDOWS_BUILDS = ["ucrt64", "clangarm64", "mingw64", "mingw32"] as const;
657
658function isFileSync(filePath: string): boolean {
659 try {
660 return NodeFS.statSync(filePath).isFile();
661 } catch {
662 return false;
663 }
664}
665
666/**
667 * The launcher costs a second process on every git command, and each launch
668 * leaks a kernel token reference that slows process creation machine-wide until
669 * reboot. The real binary sets HOME itself, but adds its own folders to PATH
670 * for hooks, ssh and credential helpers only when MSYSTEM is unset, so the
671 * launcher stays when MSYSTEM is set.
672 */
673export function preferGitForWindowsBinary(
674 executable: string,
675 env: NodeJS.ProcessEnv,
676 isFile: (filePath: string) => boolean = isFileSync,
677): string {
678 if (env.MSYSTEM) return executable;
679 const path = NodePath.win32;
680 if (path.basename(executable).toLowerCase() !== "git.exe") return executable;
681 const launcherDirectory = path.dirname(executable);
682 const launcherFolder = path.basename(launcherDirectory).toLowerCase();
683 if (launcherFolder !== "cmd" && launcherFolder !== "bin") return executable;
684 const installRoot = path.dirname(launcherDirectory);
685 for (const build of GIT_FOR_WINDOWS_BUILDS) {
686 const candidate = path.join(installRoot, build, "bin", "git.exe");
687 if (isFile(candidate)) return candidate;
688 }
689 return executable;
690}
691
692// What npm's cmd-shim writes for a package whose bin is a native executable.
693const NPM_EXECUTABLE_SHIM_PREFIX = [
694 "@ECHO off",
695 "GOTO start",
696 ":find_dp0",
697 "SET dp0=%~dp0",
698 "EXIT /b",
699 ":start",
700 "SETLOCAL",
701 "CALL :find_dp0",
702];
703const NPM_EXECUTABLE_SHIM_RUN = /^"%dp0%\\([^"%]+\.exe)" +%\*$/;
704
705function readFileSyncOrUndefined(filePath: string): string | undefined {
706 try {
707 return NodeFS.readFileSync(filePath, "utf8");
708 } catch {
709 return undefined;
710 }
711}
712
713/**
714 * The executable an npm cmd-shim runs, when the shim does nothing else.
715 * Started through the shim, the executable is a child of `cmd.exe` and so
716 * escapes the kill-on-close job libuv puts every child in: it keeps running
717 * after this process is killed. Started directly it is in the job.
718 */
719export function npmShimExecutable(
720 shimPath: string,
721 readFile: (filePath: string) => string | undefined = readFileSyncOrUndefined,
722 isFile: (filePath: string) => boolean = isFileSync,
723): string | undefined {
724 const path = NodePath.win32;
725 if (path.extname(shimPath).toLowerCase() !== ".cmd") return undefined;
726 // Compared exactly: whitespace CMD keeps, such as after `SET dp0=`, would
727 // make it run a different file than the one found here.
728 const lines = readFile(shimPath)
729 ?.split(/\r?\n/)
730 .filter((line) => line.length > 0);
731 if (lines?.length !== NPM_EXECUTABLE_SHIM_PREFIX.length + 1) return undefined;
732 if (NPM_EXECUTABLE_SHIM_PREFIX.some((expected, index) => lines[index] !== expected)) {
733 return undefined;
734 }
735 const target = NPM_EXECUTABLE_SHIM_RUN.exec(lines.at(-1)!)?.[1];
736 if (target === undefined) return undefined;
737 const executable = path.join(path.dirname(shimPath), target);
738 return isFile(executable) ? executable : undefined;
739}
740
741export interface SpawnCommandOptions extends CommandAvailabilityOptions {
742 /** Run the executable behind an npm cmd-shim directly (see `npmShimExecutable`). */
743 readonly bypassNpmShim?: boolean;
744}
745
746export const resolveSpawnCommand = Effect.fnUntraced(function* (
747 command: string,
748 args: ReadonlyArray<string>,
749 options: SpawnCommandOptions = {},
750): Effect.fn.Return<ResolvedSpawnCommand> {
751 const platform = yield* HostProcess.Platform;
752 if (platform !== "win32") {
753 return { command, args: [...args], shell: false };
754 }
755
756 const hostEnvironment = yield* HostProcess.Environment;
757 const env =
758 options.env === undefined
759 ? hostEnvironment
760 : options.extendEnv
761 ? { ...hostEnvironment, ...options.env }
762 : options.env;
763 const resolveExecutable = yield* SpawnExecutableResolution;
764 // The scan is synchronous and runs before every child process, so it shares
765 // the PATH scan cache above. Explicit paths stay uncached for the same reason,
766 // and so do misses: a failed spawn is how providers report "not installed",
767 // and that has to clear the moment the binary appears.
768 const explicitPath = command.includes("/") || command.includes("\\");
769 const cache = yield* CommandResolutionCache;
770 const cacheKey = [
771 "spawn",
772 String(spawnResolverCacheId(resolveExecutable)),
773 platform,
774 resolvePathEnvironmentVariable(env),
775 resolveWindowsPathExtensions(env).join(";"),
776 env.MSYSTEM ? "msystem" : "",
777 command,
778 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
779 const nowNanos = yield* Clock.currentTimeNanos;
780 const cached = explicitPath ? undefined : cache.get(cacheKey);
781 let resolvedExecutable: string | null;
782 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
783 resolvedExecutable = cached.resolvedPath;
784 } else {
785 const found = resolveExecutable(command, platform, env);
786 resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env);
787 if (!explicitPath && resolvedExecutable !== null) {
788 cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos);
789 }
790 }
791 const resolvedCommand = resolvedExecutable ?? command;
792 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
793 if (extension !== ".cmd" && extension !== ".bat") {
794 return { command: resolvedCommand, args: [...args], shell: false };
795 }
796 const shimExecutable = options.bypassNpmShim ? npmShimExecutable(resolvedCommand) : undefined;
797 if (shimExecutable !== undefined) {
798 return { command: shimExecutable, args: [...args], shell: false };
799 }
800
801 // Node runs a shell spawn as `cmd.exe /d /s /c "<command> <args...>"`, but
802 // passing args with `shell: true` prints DEP0190. Build the same escaped line
803 // here and pass no args.
804 return {
805 command: [resolvedCommand, ...args].map(escapeWindowsShellArg).join(" "),
806 args: [],
807 shell: true,
808 };
809});
810
811export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
812 command: string,
813 options: CommandAvailabilityOptions = {},
814) {
815 return (yield* resolveCommandPath(command, options)) !== null;
816});
817
818export function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
819 const appData = env.APPDATA?.trim();
820 const localAppData = env.LOCALAPPDATA?.trim();
821 const userProfile = env.USERPROFILE?.trim();
822
823 return [
824 ...(appData ? [`${appData}\\npm`] : []),
825 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
826 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
827 ...(userProfile
828 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
829 : []),
830 ];
831}
832
833function readWindowsEnvironmentSafely(
834 readEnvironment: WindowsShellEnvironmentReader,
835 names: ReadonlyArray<string>,
836 options?: WindowsEnvironmentProbeOptions,
837): Partial<Record<string, string>> {
838 try {
839 return readEnvironment(names, options);
840 } catch {
841 return {};
842 }
843}
844
845/** Keep one PATH spelling in copied Windows environment records. */
846export function setWindowsPath(env: NodeJS.ProcessEnv, value: string): void {
847 for (const key of Object.keys(env)) {
848 if (key.toUpperCase() === "PATH") {
849 delete env[key];
850 }
851 }
852 env.PATH = value;
853}
854
855function mergeWindowsEnv(
856 currentEnv: NodeJS.ProcessEnv,
857 patch: Partial<Record<string, string>>,
858): NodeJS.ProcessEnv {
859 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
860 for (const [key, value] of Object.entries(patch)) {
861 if (value === undefined) continue;
862 if (key === "PATH") {
863 setWindowsPath(nextEnv, value);
864 } else {
865 nextEnv[key] = value;
866 }
867 }
868 return nextEnv;
869}
870
871export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
872 env: NodeJS.ProcessEnv,
873): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
874 const readEnvironment = yield* WindowsShellEnvironment;
875 const commandAvailable = yield* CommandAvailability;
876 const inheritedPath = readEnvPath(env);
877 const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
878 loadProfile: false,
879 }).PATH;
880 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
881 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
882 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
883 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
884 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
885
886 if (yield* commandAvailable("node", { env: baselineEnv })) {
887 return baselinePatch;
888 }
889
890 const profiledEnvironment = readWindowsEnvironmentSafely(
891 readEnvironment,
892 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
893 { loadProfile: true },
894 );
895 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
896 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
897 ...(profiledPath ? { PATH: profiledPath } : {}),
898 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
899 ...(profiledEnvironment.FNM_MULTISHELL_PATH
900 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
901 : {}),
902 };
903 return Object.keys(profiledPatch).length > 0
904 ? { ...baselinePatch, ...profiledPatch }
905 : baselinePatch;
906});