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

shell.ts

747 lines24.3 KB

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