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