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 Data from "effect/Data";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13
14import { HostProcessEnvironment, HostProcessPlatform } from "./hostProcess.ts";
15import * as Context from "effect/Context";
16const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
17const WINDOWS_PATH_DELIMITER = ";";
18const POSIX_PATH_DELIMITER = ":";
19const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
20
21type ExecFileSyncLike = (
22 file: string,
23 args: ReadonlyArray<string>,
24 options: { encoding: "utf8"; timeout: number },
25) => string;
26
27function canExecuteFile(filePath: string): boolean {
28 try {
29 NodeFS.accessSync(filePath, NodeFS.constants.X_OK);
30 return true;
31 } catch {
32 return false;
33 }
34}
35
36export interface CommandAvailabilityOptions {
37 readonly env?: NodeJS.ProcessEnv;
38 readonly extendEnv?: boolean;
39}
40
41export type CommandAvailabilityChecker = (
42 command: string,
43 options?: CommandAvailabilityOptions,
44) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;
45
46export class CommandResolutionError extends Data.TaggedError("CommandResolutionError")<{
47 readonly command: string;
48 readonly reason: "not-found";
49}> {}
50
51const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
52
53/**
54 * Escapes a single argument for `cmd.exe` shell mode (`spawn(..., { shell: true })`
55 * on Windows). Node joins the command and arguments with spaces and hands the
56 * resulting string to `cmd.exe` without any quoting, so every dynamic argument
57 * must be escaped to survive both cmd.exe parsing and the target program's
58 * `CommandLineToArgvW` parsing. Mirrors cross-spawn's argument escaping.
59 */
60function escapeWindowsShellArg(arg: string): string {
61 // Double up backslashes that precede a double quote, then escape the quote
62 // itself so it survives CommandLineToArgvW.
63 let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
64 // Double up trailing backslashes so the closing quote is not escaped away.
65 escaped = escaped.replace(/(\\*)$/, "$1$1");
66 // Quote the whole argument so embedded whitespace is preserved.
67 escaped = `"${escaped}"`;
68 // Escape cmd.exe metacharacters so cmd passes them through verbatim.
69 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
70}
71
72/**
73 * Escapes arguments for shell-mode spawns: applies {@link escapeWindowsShellArg}
74 * when the platform is `win32` (where `shell: true` routes through `cmd.exe`)
75 * and returns the arguments untouched everywhere else.
76 */
77function sanitizeShellModeArgsForPlatform(
78 args: ReadonlyArray<string>,
79 platform: NodeJS.Platform,
80): Array<string> {
81 return platform === "win32" ? args.map(escapeWindowsShellArg) : [...args];
82}
83
84export interface ResolvedSpawnCommand {
85 readonly command: string;
86 readonly args: ReadonlyArray<string>;
87 readonly shell: boolean;
88}
89
90export type SpawnExecutableResolver = (
91 command: string,
92 platform: NodeJS.Platform,
93 env: NodeJS.ProcessEnv,
94) => string | undefined;
95
96function resolveSpawnExecutableWithNode(
97 command: string,
98 platform: NodeJS.Platform,
99 env: NodeJS.ProcessEnv,
100): string | undefined {
101 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
102 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
103 const candidates = resolveCommandCandidates(
104 command,
105 platform,
106 windowsPathExtensions,
107 path.extname,
108 );
109 const isExecutable = (candidate: string) => {
110 try {
111 if (!NodeFS.statSync(candidate).isFile()) return false;
112 if (platform === "win32") {
113 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
114 }
115 return canExecuteFile(candidate);
116 } catch {
117 return false;
118 }
119 };
120
121 if (command.includes("/") || command.includes("\\")) {
122 return candidates.find(isExecutable);
123 }
124
125 for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) {
126 const normalizedPathEntry = stripWrappingQuotes(pathEntry.trim());
127 if (normalizedPathEntry.length === 0) continue;
128 for (const candidate of candidates) {
129 const candidatePath = path.join(normalizedPathEntry, candidate);
130 if (isExecutable(candidatePath)) return candidatePath;
131 }
132 }
133 return undefined;
134}
135
136export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
137 "@t3tools/shared/shell/SpawnExecutableResolution",
138 {
139 defaultValue: () => resolveSpawnExecutableWithNode,
140 },
141);
142
143export interface WindowsEnvironmentProbeOptions {
144 readonly loadProfile?: boolean;
145}
146
147function trimNonEmpty(value: string | null | undefined): string | undefined {
148 const trimmed = value?.trim();
149 return trimmed && trimmed.length > 0 ? trimmed : undefined;
150}
151
152function readUserLoginShell(): string | undefined {
153 try {
154 return trimNonEmpty(NodeOS.userInfo().shell);
155 } catch {
156 return undefined;
157 }
158}
159
160export function listLoginShellCandidates(
161 platform: NodeJS.Platform,
162 shell: string | undefined,
163 userShell = readUserLoginShell(),
164): ReadonlyArray<string> {
165 const fallbackShell =
166 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
167 const seen = new Set<string>();
168 const candidates: string[] = [];
169
170 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
171 if (!candidate || seen.has(candidate)) {
172 continue;
173 }
174 seen.add(candidate);
175 candidates.push(candidate);
176 }
177
178 return candidates;
179}
180
181export function readPathFromLoginShell(
182 shell: string,
183 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
184): string | undefined {
185 return readEnvironmentFromLoginShell(shell, ["PATH"], execFile).PATH;
186}
187
188export function readPathFromLaunchctl(
189 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
190): string | undefined {
191 try {
192 return trimNonEmpty(
193 execFile("/bin/launchctl", ["getenv", "PATH"], {
194 encoding: "utf8",
195 timeout: 2000,
196 }),
197 );
198 } catch {
199 return undefined;
200 }
201}
202
203export function mergePathEntries(
204 preferredPath: string | undefined,
205 inheritedPath: string | undefined,
206 platform: NodeJS.Platform,
207): string | undefined {
208 const delimiter = platform === "win32" ? ";" : ":";
209 const merged: string[] = [];
210 const seen = new Set<string>();
211
212 for (const pathValue of [preferredPath, inheritedPath]) {
213 if (!pathValue) continue;
214 for (const entry of pathValue.split(delimiter)) {
215 const trimmedEntry = entry.trim();
216 if (!trimmedEntry || seen.has(trimmedEntry)) {
217 continue;
218 }
219 seen.add(trimmedEntry);
220 merged.push(trimmedEntry);
221 }
222 }
223
224 return merged.length > 0 ? merged.join(delimiter) : undefined;
225}
226
227function envCaptureStart(name: string): string {
228 return `__T3CODE_ENV_${name}_START__`;
229}
230
231function envCaptureEnd(name: string): string {
232 return `__T3CODE_ENV_${name}_END__`;
233}
234
235function buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
236 return names
237 .map((name) => {
238 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
239 throw new Error(`Unsupported environment variable name: ${name}`);
240 }
241
242 return [
243 `printf '%s\\n' '${envCaptureStart(name)}'`,
244 `printenv ${name} || true`,
245 `printf '%s\\n' '${envCaptureEnd(name)}'`,
246 ].join("; ");
247 })
248 .join("; ");
249}
250
251function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
252 return [
253 "$ErrorActionPreference = 'Stop'",
254 ...names.flatMap((name) => {
255 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
256 throw new Error(`Unsupported environment variable name: ${name}`);
257 }
258
259 return [
260 `Write-Output '${envCaptureStart(name)}'`,
261 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
262 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
263 `Write-Output '${envCaptureEnd(name)}'`,
264 ];
265 }),
266 ].join("; ");
267}
268
269function extractEnvironmentValue(output: string, name: string): string | undefined {
270 const startMarker = envCaptureStart(name);
271 const endMarker = envCaptureEnd(name);
272 const startIndex = output.indexOf(startMarker);
273 if (startIndex === -1) return undefined;
274
275 const valueStartIndex = startIndex + startMarker.length;
276 const endIndex = output.indexOf(endMarker, valueStartIndex);
277 if (endIndex === -1) return undefined;
278
279 const value = output
280 .slice(valueStartIndex, endIndex)
281 .replace(/^\r?\n/, "")
282 .replace(/\r?\n$/, "");
283
284 return value.length > 0 ? value : undefined;
285}
286
287export type ShellEnvironmentReader = (
288 shell: string,
289 names: ReadonlyArray<string>,
290 execFile?: ExecFileSyncLike,
291) => Partial<Record<string, string>>;
292
293export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
294 shell,
295 names,
296 execFile = NodeChildProcess.execFileSync,
297) => {
298 if (names.length === 0) {
299 return {};
300 }
301
302 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(names)], {
303 encoding: "utf8",
304 timeout: 5000,
305 });
306
307 const environment: Partial<Record<string, string>> = {};
308 for (const name of names) {
309 const value = extractEnvironmentValue(output, name);
310 if (value !== undefined) {
311 environment[name] = value;
312 }
313 }
314
315 return environment;
316};
317
318export type WindowsShellEnvironmentReader = (
319 names: ReadonlyArray<string>,
320 options?: WindowsEnvironmentProbeOptions,
321) => Partial<Record<string, string>>;
322
323export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
324 "@t3tools/shared/shell/WindowsShellEnvironment",
325 {
326 defaultValue: () => readEnvironmentFromWindowsShell,
327 },
328);
329
330export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
331 "@t3tools/shared/shell/CommandAvailability",
332 {
333 defaultValue: () => isCommandAvailable,
334 },
335);
336
337export function readEnvironmentFromWindowsShell(
338 names: ReadonlyArray<string>,
339 execFile?: ExecFileSyncLike,
340): Partial<Record<string, string>>;
341export function readEnvironmentFromWindowsShell(
342 names: ReadonlyArray<string>,
343 options?: WindowsEnvironmentProbeOptions,
344 execFile?: ExecFileSyncLike,
345): Partial<Record<string, string>>;
346export function readEnvironmentFromWindowsShell(
347 names: ReadonlyArray<string>,
348 optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
349 maybeExecFile?: ExecFileSyncLike,
350): Partial<Record<string, string>> {
351 if (names.length === 0) {
352 return {};
353 }
354
355 const options =
356 typeof optionsOrExecFile === "function"
357 ? ({} satisfies WindowsEnvironmentProbeOptions)
358 : (optionsOrExecFile ?? {});
359 const execFile: ExecFileSyncLike =
360 typeof optionsOrExecFile === "function"
361 ? optionsOrExecFile
362 : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));
363 const command = buildWindowsEnvironmentCaptureCommand(names);
364 const args = [
365 "-NoLogo",
366 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
367 "-NonInteractive",
368 "-Command",
369 command,
370 ];
371 for (const shell of WINDOWS_SHELL_CANDIDATES) {
372 try {
373 const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
374
375 const environment: Partial<Record<string, string>> = {};
376 for (const name of names) {
377 const value = extractEnvironmentValue(output, name);
378 if (value !== undefined) {
379 environment[name] = value;
380 }
381 }
382 return environment;
383 } catch {
384 continue;
385 }
386 }
387
388 return {};
389}
390
391function stripWrappingQuotes(value: string): string {
392 return value.replace(/^"+|"+$/g, "");
393}
394
395function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
396 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
397}
398
399function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
400 const normalized = stripWrappingQuotes(entry.trim());
401 return platform === "win32" ? normalized.toLowerCase() : normalized;
402}
403
404function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
405 return platform === "win32" ? entry.replaceAll('"', "") : entry;
406}
407
408export function mergePathValues(
409 preferredPath: string | undefined,
410 inheritedPath: string | undefined,
411 platform: NodeJS.Platform,
412): string | undefined {
413 const delimiter = pathDelimiterForPlatform(platform);
414 const merged: string[] = [];
415 const seen = new Set<string>();
416
417 for (const rawValue of [preferredPath, inheritedPath]) {
418 if (!rawValue) continue;
419
420 for (const entry of rawValue.split(delimiter)) {
421 const sanitized = sanitizePathEntry(entry.trim(), platform);
422 if (sanitized.length === 0) continue;
423
424 const normalized = normalizePathEntryForComparison(sanitized, platform);
425 if (normalized.length === 0 || seen.has(normalized)) continue;
426
427 seen.add(normalized);
428 merged.push(sanitized);
429 }
430 }
431
432 return merged.length > 0 ? merged.join(delimiter) : undefined;
433}
434
435function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
436 return env.PATH ?? env.Path ?? env.path;
437}
438
439function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
440 return readEnvPath(env) ?? "";
441}
442
443function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
444 const rawValue = env.PATHEXT;
445 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
446 if (!rawValue) return fallback;
447
448 const parsed: string[] = [];
449 for (const entry of rawValue.split(";")) {
450 const trimmed = entry.trim();
451 if (trimmed.length === 0) continue;
452 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
453 }
454 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
455}
456
457function resolveCommandCandidates(
458 command: string,
459 platform: NodeJS.Platform,
460 windowsPathExtensions: ReadonlyArray<string>,
461 extname: (path: string) => string,
462): ReadonlyArray<string> {
463 if (platform !== "win32") return [command];
464 const extension = extname(command);
465 const normalizedExtension = extension.toUpperCase();
466
467 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
468 const commandWithoutExtension = command.slice(0, -extension.length);
469 return Array.from(
470 new Set([
471 command,
472 `${commandWithoutExtension}${normalizedExtension}`,
473 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
474 ]),
475 );
476 }
477
478 const candidates: string[] = [];
479 for (const candidateExtension of windowsPathExtensions) {
480 candidates.push(`${command}${candidateExtension}`);
481 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
482 }
483 return Array.from(new Set(candidates));
484}
485
486// Session bootstrap resolves the same commands over and over, each PATH scan
487// costing hundreds of 'shell.isExecutableFile' filesystem probes (tens of
488// thousands per connect). Memoize the scan outcome per
489// (platform, PATH, PATHEXT, command) for a short window: repeat scans hit the
490// cache while any change to the search environment invalidates immediately.
491// Explicit-path resolution is never cached - callers probe paths they have
492// just written (e.g. managed binary installs). A "not-found" outcome is also
493// cached for the TTL, so a just-installed binary can stay invisible for up to
494// 30s unless resolved by explicit path.
495// TTL expiry uses the monotonic clock (Clock.currentTimeNanos) so backward
496// wall-clock adjustments cannot keep expired entries alive.
497const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
498const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
499const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
500
501interface CommandResolutionCacheEntry {
502 readonly resolvedPath: string | null;
503 readonly expiresAtNanos: bigint;
504}
505
506// The cache lives in the Effect environment (like HostProcessPlatform above)
507// so tests and embedders can provide an isolated instance; the default is a
508// single process-wide map shared by all consumers.
509export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
510 "@t3tools/shared/shell/CommandResolutionCache",
511 {
512 defaultValue: () => new Map(),
513 },
514);
515
516interface PathDirectoryListing {
517 readonly modified: number | null | undefined;
518 readonly names: ReadonlySet<string> | undefined;
519}
520
521// mtime of a PATH directory; null when missing, undefined when unreadable.
522const directoryMtime = (directory: string) =>
523 FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe(
524 Effect.map((info) =>
525 info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined,
526 ),
527 Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)),
528 );
529
530// Dated before it is read, so an entry added in between changes the mtime seen
531// on the next check. Without names, lookups probe candidates directly.
532const listPathDirectory = Effect.fnUntraced(function* (
533 directory: string,
534): Effect.fn.Return<PathDirectoryListing, never, FileSystem.FileSystem> {
535 const modified = yield* directoryMtime(directory);
536 if (modified == null) return { modified, names: modified === null ? new Set() : undefined };
537 const entries = yield* FileSystem.FileSystem.use((fileSystem) =>
538 fileSystem.readDirectory(directory),
539 ).pipe(Effect.orElseSucceed(() => undefined));
540 return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) };
541});
542
543const PathDirectoryListings = Context.Reference<
544 Cache.Cache<string, PathDirectoryListing, never, FileSystem.FileSystem> | undefined
545>("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined });
546
547/**
548 * Run a batch of command lookups (e.g. editor discovery) that lists each PATH
549 * directory once, relisting it if its mtime changes, and probes only listed
550 * names instead of every PATH x PATHEXT candidate per command.
551 */
552export const withPathDirectoryListings = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
553 Effect.gen(function* () {
554 const listings = yield* Cache.make({
555 capacity: 1024,
556 lookup: listPathDirectory,
557 requireServicesAt: "lookup",
558 });
559 return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings));
560 });
561
562function cacheCommandResolution(
563 cache: Map<string, CommandResolutionCacheEntry>,
564 cacheKey: string,
565 resolvedPath: string | null,
566 nowNanos: bigint,
567): void {
568 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
569 const oldestKey = cache.keys().next().value;
570 if (oldestKey !== undefined) {
571 cache.delete(oldestKey);
572 }
573 }
574 cache.set(cacheKey, {
575 resolvedPath,
576 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
577 });
578}
579
580// Trace each command lookup, not every candidate file it probes.
581const isExecutableFile = Effect.fnUntraced(function* (
582 filePath: string,
583 platform: NodeJS.Platform,
584 windowsPathExtensions: ReadonlyArray<string>,
585): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
586 const fileSystem = yield* FileSystem.FileSystem;
587 const path = yield* Path.Path;
588 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
589 if (stat === null || stat.type !== "File") return false;
590
591 if (platform === "win32") {
592 const extension = path.extname(filePath);
593 if (extension.length === 0) return false;
594 return windowsPathExtensions.includes(extension.toUpperCase());
595 }
596
597 return canExecuteFile(filePath);
598});
599
600const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
601 command: string,
602 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
603): Effect.fn.Return<string, CommandResolutionError, FileSystem.FileSystem | Path.Path> {
604 const path = yield* Path.Path;
605 const platform = options.platform;
606 const env = options.env ?? process.env;
607 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
608 const commandCandidates = resolveCommandCandidates(
609 command,
610 platform,
611 windowsPathExtensions,
612 path.extname,
613 );
614
615 if (command.includes("/") || command.includes("\\")) {
616 for (const candidate of commandCandidates) {
617 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
618 return candidate;
619 }
620 }
621 return yield* new CommandResolutionError({ command, reason: "not-found" });
622 }
623
624 const pathValue = resolvePathEnvironmentVariable(env);
625 if (pathValue.length === 0) {
626 return yield* new CommandResolutionError({ command, reason: "not-found" });
627 }
628
629 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
630 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
631 );
632 const cache = yield* CommandResolutionCache;
633 const nowNanos = yield* Clock.currentTimeNanos;
634 const cached = cache.get(cacheKey);
635 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
636 if (cached.resolvedPath === null) {
637 return yield* new CommandResolutionError({ command, reason: "not-found" });
638 }
639 return cached.resolvedPath;
640 }
641
642 // Keep case variants: Windows can make PATH directories case-sensitive.
643 const pathEntries: string[] = [];
644 const seenPathEntries = new Set<string>();
645 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
646 const pathEntry = stripWrappingQuotes(entry.trim());
647 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
648
649 seenPathEntries.add(pathEntry);
650 pathEntries.push(pathEntry);
651 }
652
653 const listings = yield* PathDirectoryListings;
654 for (const pathEntry of pathEntries) {
655 let listing = listings && (yield* Cache.get(listings, pathEntry));
656 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
657 yield* Cache.invalidate(listings, pathEntry);
658 listing = yield* Cache.get(listings, pathEntry);
659 }
660 for (const candidate of commandCandidates) {
661 // The stat below still checks exact case and rejects non-files.
662 if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue;
663 const candidatePath = path.join(pathEntry, candidate);
664 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
665 cacheCommandResolution(cache, cacheKey, candidatePath, nowNanos);
666 return candidatePath;
667 }
668 }
669 }
670 cacheCommandResolution(cache, cacheKey, null, nowNanos);
671 return yield* new CommandResolutionError({ command, reason: "not-found" });
672});
673
674export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
675 command: string,
676 options: CommandAvailabilityOptions = {},
677) {
678 return yield* resolveCommandPathForPlatform(command, {
679 env: options.env ?? (yield* HostProcessEnvironment),
680 platform: yield* HostProcessPlatform,
681 });
682});
683
684// Untraced because it runs before most spawns and returns at once off Windows.
685export const resolveSpawnCommand = Effect.fnUntraced(function* (
686 command: string,
687 args: ReadonlyArray<string>,
688 options: CommandAvailabilityOptions = {},
689): Effect.fn.Return<ResolvedSpawnCommand> {
690 const platform = yield* HostProcessPlatform;
691 if (platform !== "win32") {
692 return { command, args: [...args], shell: false };
693 }
694
695 const hostEnvironment = yield* HostProcessEnvironment;
696 const env =
697 options.env === undefined
698 ? hostEnvironment
699 : options.extendEnv
700 ? { ...hostEnvironment, ...options.env }
701 : options.env;
702 const resolveExecutable = yield* SpawnExecutableResolution;
703 const resolvedCommand = resolveExecutable(command, platform, env) ?? command;
704 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
705 if (extension !== ".cmd" && extension !== ".bat") {
706 return { command: resolvedCommand, args: [...args], shell: false };
707 }
708
709 return {
710 command: escapeWindowsShellArg(resolvedCommand),
711 args: sanitizeShellModeArgsForPlatform(args, platform),
712 shell: true,
713 };
714});
715
716export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
717 command: string,
718 options: CommandAvailabilityOptions = {},
719) {
720 return yield* resolveCommandPath(command, options).pipe(
721 Effect.as(true),
722 Effect.catchTag("CommandResolutionError", () => Effect.succeed(false)),
723 );
724});
725
726export function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
727 const appData = env.APPDATA?.trim();
728 const localAppData = env.LOCALAPPDATA?.trim();
729 const userProfile = env.USERPROFILE?.trim();
730
731 return [
732 ...(appData ? [`${appData}\\npm`] : []),
733 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
734 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
735 ...(userProfile
736 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
737 : []),
738 ];
739}
740
741function readWindowsEnvironmentSafely(
742 readEnvironment: WindowsShellEnvironmentReader,
743 names: ReadonlyArray<string>,
744 options?: WindowsEnvironmentProbeOptions,
745): Partial<Record<string, string>> {
746 try {
747 return readEnvironment(names, options);
748 } catch {
749 return {};
750 }
751}
752
753function mergeWindowsEnv(
754 currentEnv: NodeJS.ProcessEnv,
755 patch: Partial<Record<string, string>>,
756): NodeJS.ProcessEnv {
757 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
758 for (const [key, value] of Object.entries(patch)) {
759 if (value !== undefined) {
760 nextEnv[key] = value;
761 }
762 }
763 return nextEnv;
764}
765
766export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
767 env: NodeJS.ProcessEnv,
768): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
769 const readEnvironment = yield* WindowsShellEnvironment;
770 const commandAvailable = yield* CommandAvailability;
771 const inheritedPath = readEnvPath(env);
772 const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
773 loadProfile: false,
774 }).PATH;
775 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
776 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
777 // Preserve the order a user's shell uses. These directories fill gaps when
778 // desktop apps launch without the full interactive-shell PATH.
779 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
780 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
781 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
782
783 if (yield* commandAvailable("node", { env: baselineEnv })) {
784 return baselinePatch;
785 }
786
787 const profiledEnvironment = readWindowsEnvironmentSafely(
788 readEnvironment,
789 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
790 { loadProfile: true },
791 );
792 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
793 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
794 ...(profiledPath ? { PATH: profiledPath } : {}),
795 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
796 ...(profiledEnvironment.FNM_MULTISHELL_PATH
797 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
798 : {}),
799 };
800 return Object.keys(profiledPatch).length > 0
801 ? { ...baselinePatch, ...profiledPatch }
802 : baselinePatch;
803});