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

shell.ts

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