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

shell.ts

982 lines32.8 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 Cache from "effect/Cache";
7import * as Clock from "effect/Clock";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12​
13import type { ShellEnvironmentPatch } from "@t3tools/contracts";
14import * as HostProcess 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: {
25 encoding: "utf8";
26 timeout: number;
27 killSignal?: NodeJS.Signals | number;
28 detached?: true;
29 stdio?: ["ignore", "pipe", "ignore"];
30 },
31) => string;
32​
33function canExecuteFile(filePath: string): boolean {
34 try {
35 NodeFS.accessSync(filePath, NodeFS.constants.X_OK);
36 return true;
37 } catch {
38 return false;
39 }
41​
42export interface CommandAvailabilityOptions {
43 readonly env?: NodeJS.ProcessEnv;
44 readonly extendEnv?: boolean;
46​
47export type CommandAvailabilityChecker = (
48 command: string,
49 options?: CommandAvailabilityOptions,
50) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;
51​
52const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
53​
54// Escape dynamic arguments for both cmd.exe and the target's CommandLineToArgvW parsing.
55function escapeWindowsShellArg(arg: string): string {
56 let escaped = arg.replace(/(\\*)"/g, '$1$1\\"');
57 // Double up trailing backslashes so the closing quote is not escaped away.
58 escaped = escaped.replace(/(\\*)$/, "$1$1");
59 escaped = `"${escaped}"`;
60 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
62​
63export interface ResolvedSpawnCommand {
64 readonly command: string;
65 readonly args: ReadonlyArray<string>;
66 readonly shell: boolean;
68​
69export type SpawnExecutableResolver = (
70 command: string,
71 platform: NodeJS.Platform,
72 env: NodeJS.ProcessEnv,
73) => string | undefined;
74​
75function resolveSpawnExecutableWithNode(
76 command: string,
77 platform: NodeJS.Platform,
78 env: NodeJS.ProcessEnv,
79): string | undefined {
80 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
81 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
82 const candidates = resolveCommandCandidates(
83 command,
84 platform,
85 windowsPathExtensions,
86 path.extname,
87 );
88 const isExecutable = (candidate: string) => {
89 try {
90 if (!NodeFS.statSync(candidate).isFile()) return false;
91 if (platform === "win32") {
92 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
93 }
94 return canExecuteFile(candidate);
95 } catch {
96 return false;
97 }
98 };
99​
100 if (command.includes("/") || command.includes("\\")) {
101 return candidates.find(isExecutable);
102 }
103​
104 for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) {
105 const normalizedPathEntry = stripWrappingQuotes(pathEntry.trim());
106 if (normalizedPathEntry.length === 0) continue;
107 for (const candidate of candidates) {
108 const candidatePath = path.join(normalizedPathEntry, candidate);
109 if (isExecutable(candidatePath)) return candidatePath;
110 }
111 }
112 return undefined;
114​
115export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
116 "@t3tools/shared/shell/SpawnExecutableResolution",
117 {
118 defaultValue: () => resolveSpawnExecutableWithNode,
119 },
120);
121​
122export interface WindowsEnvironmentProbeOptions {
123 readonly loadProfile?: boolean;
125​
126function trimNonEmpty(value: string | null | undefined): string | undefined {
127 const trimmed = value?.trim();
128 return trimmed && trimmed.length > 0 ? trimmed : undefined;
130​
131function readUserLoginShell(): string | undefined {
132 try {
133 return trimNonEmpty(NodeOS.userInfo().shell);
134 } catch {
135 return undefined;
136 }
138​
139export function listLoginShellCandidates(
140 platform: NodeJS.Platform,
141 shell: string | undefined,
142 userShell = readUserLoginShell(),
143): ReadonlyArray<string> {
144 const fallbackShell =
145 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
146 const seen = new Set<string>();
147 const candidates: string[] = [];
148​
149 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
150 if (!candidate || seen.has(candidate)) {
151 continue;
152 }
153 seen.add(candidate);
154 candidates.push(candidate);
155 }
156​
157 return candidates;
159​
160export function readPathFromLaunchctl(
161 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
162): string | undefined {
163 try {
164 return trimNonEmpty(
165 execFile("/bin/launchctl", ["getenv", "PATH"], {
166 encoding: "utf8",
167 timeout: 2000,
168 }),
169 );
170 } catch {
171 return undefined;
172 }
174​
175export function mergePathEntries(
176 preferredPath: string | undefined,
177 inheritedPath: string | undefined,
178 platform: NodeJS.Platform,
179): string | undefined {
180 const delimiter = platform === "win32" ? ";" : ":";
181 const merged: string[] = [];
182 const seen = new Set<string>();
183​
184 for (const pathValue of [preferredPath, inheritedPath]) {
185 if (!pathValue) continue;
186 for (const entry of pathValue.split(delimiter)) {
187 const trimmedEntry = entry.trim();
188 if (!trimmedEntry || seen.has(trimmedEntry)) {
189 continue;
190 }
191 seen.add(trimmedEntry);
192 merged.push(trimmedEntry);
193 }
194 }
195​
196 return merged.length > 0 ? merged.join(delimiter) : undefined;
198​
199function envCaptureStart(name: string): string {
200 return `__T3CODE_ENV_${name}_START__`;
202​
203function envCaptureEnd(name: string): string {
204 return `__T3CODE_ENV_${name}_END__`;
206​
207export function buildEnvironmentCaptureCommand(
208 shell: string,
209 names: ReadonlyArray<string>,
210): string {
211 const executableName = NodePath.basename(shell).toLowerCase();
212 const isNushell = executableName.startsWith("nu");
213​
214 return names
215 .map((name) => {
216 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
217 throw new Error(`Unsupported environment variable name: ${name}`);
218 }
219​
220 if (isNushell) {
221 // Without a configured conversion, Nu expands home paths only in a list PATH.
222 const defaultValue =
223 name === "PATH"
224 ? "if ($env.PATH? | describe | str starts-with 'list') { " +
225 "$env.PATH | each {|p| if ($p | str starts-with '~') { " +
226 "$p | path expand --no-symlink } else { $p } } | str join (char esep) " +
227 "} else { $env.PATH? | default '' }"
228 : `$env.${name}? | default ''`;
229 const value =
230 `if $env.${name}? == null { '' } else if ` +
231 `$env.ENV_CONVERSIONS?.${name}?.to_string? != null { ` +
232 `$env.${name} | do $env.ENV_CONVERSIONS.${name}.to_string $env.${name} ` +
233 `} else { ${defaultValue} }`;
234 return [
235 `print '${envCaptureStart(name)}'`,
236 `print (${value})`,
237 `print '${envCaptureEnd(name)}'`,
238 ].join("; ");
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 // Interactive startup loads PATH entries; detaching prevents job control on an
302 // inherited controlling TTY from stopping the probe while the parent waits.
303 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(shell, names)], {
304 encoding: "utf8",
305 timeout: 5000,
306 killSignal: "SIGKILL",
307 detached: true,
308 stdio: ["ignore", "pipe", "ignore"],
309 });
310​
311 const environment: Partial<Record<string, string>> = {};
312 for (const name of names) {
313 const value = extractEnvironmentValue(output, name);
314 if (value !== undefined) {
315 environment[name] = value;
316 }
317 }
318​
319 return environment;
320};
321​
322export type WindowsShellEnvironmentReader = (
323 names: ReadonlyArray<string>,
324 options?: WindowsEnvironmentProbeOptions,
325) => Effect.Effect<Partial<Record<string, string>>>;
326​
327export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
328 "@t3tools/shared/shell/WindowsShellEnvironment",
329 {
330 defaultValue: () => readEnvironmentFromWindowsShell,
331 },
332);
333​
334export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
335 "@t3tools/shared/shell/CommandAvailability",
336 {
337 defaultValue: () => isCommandAvailable,
338 },
339);
340​
341const execWindowsEnvironmentProbe = (
342 file: string,
343 args: ReadonlyArray<string>,
344 options: { encoding: "utf8"; timeout: number },
345) =>
346 Effect.callback<Option.Option<string>>((resume) => {
347 let child: NodeChildProcess.ChildProcess;
348 try {
349 child = NodeChildProcess.execFile(
350 file,
351 args,
352 { ...options, windowsHide: true },
353 (error, stdout) => {
354 resume(Effect.succeed(error ? Option.none() : Option.some(stdout)));
355 },
356 );
357 } catch {
358 resume(Effect.succeedNone);
359 return;
360 }
361 return Effect.sync(() => {
362 child.kill();
363 });
364 });
365​
366export const readEnvironmentFromWindowsShell = Effect.fn("shell.readEnvironmentFromWindowsShell")(
367 function* (
368 names: ReadonlyArray<string>,
369 options: WindowsEnvironmentProbeOptions = {},
370 execFile: typeof execWindowsEnvironmentProbe = execWindowsEnvironmentProbe,
371 ) {
372 if (names.length === 0) return {};
373​
374 const command = buildWindowsEnvironmentCaptureCommand(names);
375 const args = [
376 "-NoLogo",
377 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
378 "-NonInteractive",
379 "-Command",
380 command,
381 ];
382 for (const shell of WINDOWS_SHELL_CANDIDATES) {
383 const output = yield* execFile(shell, args, { encoding: "utf8", timeout: 5000 });
384 if (Option.isNone(output)) continue;
385​
386 const environment: Partial<Record<string, string>> = {};
387 for (const name of names) {
388 const value = extractEnvironmentValue(output.value, name);
389 if (value !== undefined) environment[name] = value;
390 }
391 return environment;
392 }
393​
394 return {};
395 },
396);
397​
398function stripWrappingQuotes(value: string): string {
399 return value.replace(/^"+|"+$/g, "");
401​
402function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
403 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
405​
406function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
407 const normalized = stripWrappingQuotes(entry.trim());
408 return platform === "win32" ? normalized.toLowerCase() : normalized;
410​
411function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
412 return platform === "win32" ? entry.replaceAll('"', "") : entry;
414​
415export function mergePathValues(
416 preferredPath: string | undefined,
417 inheritedPath: string | undefined,
418 platform: NodeJS.Platform,
419): string | undefined {
420 const delimiter = pathDelimiterForPlatform(platform);
421 const merged: string[] = [];
422 const seen = new Set<string>();
423​
424 for (const rawValue of [preferredPath, inheritedPath]) {
425 if (!rawValue) continue;
426​
427 for (const entry of rawValue.split(delimiter)) {
428 const sanitized = sanitizePathEntry(entry.trim(), platform);
429 if (sanitized.length === 0) continue;
430​
431 const normalized = normalizePathEntryForComparison(sanitized, platform);
432 if (normalized.length === 0 || seen.has(normalized)) continue;
433​
434 seen.add(normalized);
435 merged.push(sanitized);
436 }
437 }
438​
439 return merged.length > 0 ? merged.join(delimiter) : undefined;
441​
442function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
443 return env.PATH ?? env.Path ?? env.path;
445​
446function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
447 return readEnvPath(env) ?? "";
449​
450function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
451 const rawValue = env.PATHEXT;
452 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
453 if (!rawValue) return fallback;
454​
455 const parsed: string[] = [];
456 for (const entry of rawValue.split(";")) {
457 const trimmed = entry.trim();
458 if (trimmed.length === 0) continue;
459 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
460 }
461 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
463​
464function resolveCommandCandidates(
465 command: string,
466 platform: NodeJS.Platform,
467 windowsPathExtensions: ReadonlyArray<string>,
468 extname: (path: string) => string,
469): ReadonlyArray<string> {
470 if (platform !== "win32") return [command];
471 const extension = extname(command);
472 const normalizedExtension = extension.toUpperCase();
473​
474 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
475 const commandWithoutExtension = command.slice(0, -extension.length);
476 return Array.from(
477 new Set([
478 command,
479 `${commandWithoutExtension}${normalizedExtension}`,
480 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
481 ]),
482 );
483 }
484​
485 const candidates: string[] = [];
486 for (const candidateExtension of windowsPathExtensions) {
487 candidates.push(`${command}${candidateExtension}`);
488 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
489 }
490 return Array.from(new Set(candidates));
492​
493// Explicit paths bypass the cache for new installs; cached misses can otherwise hide binaries for 30 seconds.
494const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
495const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
496const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
497​
498interface CommandResolutionCacheEntry {
499 readonly resolvedPath: string | null;
500 readonly expiresAtNanos: bigint;
502​
503export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
504 "@t3tools/shared/shell/CommandResolutionCache",
505 {
506 defaultValue: () => new Map(),
507 },
508);
509​
510interface PathDirectoryListing {
511 readonly modified: number | null | undefined;
512 readonly names: ReadonlySet<string> | undefined;
514​
515const directoryMtime = (directory: string) =>
516 FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe(
517 Effect.map((info) =>
518 info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined,
519 ),
520 Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)),
521 );
522​
523// Timestamp before reading so concurrent additions change the next mtime check; missing listings fall back to direct probes.
524const listPathDirectory = Effect.fnUntraced(function* (
525 directory: string,
526): Effect.fn.Return<PathDirectoryListing, never, FileSystem.FileSystem> {
527 const modified = yield* directoryMtime(directory);
528 if (modified == null) return { modified, names: modified === null ? new Set() : undefined };
529 const entries = yield* FileSystem.FileSystem.use((fileSystem) =>
530 fileSystem.readDirectory(directory),
531 ).pipe(Effect.orElseSucceed(() => undefined));
532 return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) };
533});
534​
535const PathDirectoryListings = Context.Reference<
536 Cache.Cache<string, PathDirectoryListing, never, FileSystem.FileSystem> | undefined
537>("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined });
538​
539export const withPathDirectoryListings =
540 /* Directory reads are cached inside one shell operation; a span for each lookup adds noise. */
541 Effect.fnUntraced(function* <A, E, R>(effect: Effect.Effect<A, E, R>) {
542 const listings = yield* Cache.make({
543 capacity: 1024,
544 lookup: listPathDirectory,
545 requireServicesAt: "lookup",
546 });
547 return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings));
548 });
549​
550// An injected resolver or locator may answer differently for the same search, so its
551// entries are kept apart from every other resolver's.
552let spawnResolverCacheIdCount = 0;
553const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver | XcodeGitLocator, number>();
554function spawnResolverCacheId(resolver: SpawnExecutableResolver | XcodeGitLocator): number {
555 const known = spawnResolverCacheIds.get(resolver);
556 if (known !== undefined) return known;
557 const id = spawnResolverCacheIdCount++;
558 spawnResolverCacheIds.set(resolver, id);
559 return id;
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 });
579​
580const isExecutableFile = Effect.fnUntraced(function* (
581 filePath: string,
582 platform: NodeJS.Platform,
583 windowsPathExtensions: ReadonlyArray<string>,
584): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
585 const fileSystem = yield* FileSystem.FileSystem;
586 const path = yield* Path.Path;
587 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
588 if (stat === null || stat.type !== "File") return false;
589​
590 if (platform === "win32") {
591 const extension = path.extname(filePath);
592 if (extension.length === 0) return false;
593 return windowsPathExtensions.includes(extension.toUpperCase());
594 }
595​
596 return canExecuteFile(filePath);
597});
598​
599const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
600 command: string,
601 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
602): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
603 const path = yield* Path.Path;
604 const platform = options.platform;
605 const env = options.env ?? process.env;
606 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
607 const commandCandidates = resolveCommandCandidates(
608 command,
609 platform,
610 windowsPathExtensions,
611 path.extname,
612 );
613​
614 if (command.includes("/") || command.includes("\\")) {
615 for (const candidate of commandCandidates) {
616 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
617 return candidate;
618 }
619 }
620 return null;
621 }
622​
623 const pathValue = resolvePathEnvironmentVariable(env);
624 if (pathValue.length === 0) {
625 return null;
626 }
627​
628 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
629 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
630 );
631 const cache = yield* CommandResolutionCache;
632 const nowNanos = yield* Clock.monotonicTimeNanos;
633 const cached = cache.get(cacheKey);
634 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
635 return cached.resolvedPath;
636 }
637​
638 // Keep case variants: Windows can make PATH directories case-sensitive.
639 const pathEntries: string[] = [];
640 const seenPathEntries = new Set<string>();
641 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
642 const pathEntry = stripWrappingQuotes(entry.trim());
643 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
644​
645 seenPathEntries.add(pathEntry);
646 pathEntries.push(pathEntry);
647 }
648​
649 const listings = yield* PathDirectoryListings;
650 for (const pathEntry of pathEntries) {
651 let listing = listings && (yield* Cache.get(listings, pathEntry));
652 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
653 yield* Cache.invalidate(listings, pathEntry);
654 listing = yield* Cache.get(listings, pathEntry);
655 }
656 for (const candidate of commandCandidates) {
657 if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue;
658 const candidatePath = path.join(pathEntry, candidate);
659 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
660 cacheCommandResolution(cache, cacheKey, candidatePath, nowNanos);
661 return candidatePath;
662 }
663 }
664 }
665 cacheCommandResolution(cache, cacheKey, null, nowNanos);
666 return null;
667});
668​
669export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
670 command: string,
671 options: CommandAvailabilityOptions = {},
672) {
673 return yield* resolveCommandPathForPlatform(command, {
674 env: options.env ?? (yield* HostProcess.Environment),
675 platform: yield* HostProcess.Platform,
676 });
677});
678​
679// Git 2.56 x64 uses ucrt64; ARM64 uses clangarm64; older x64/32-bit builds use mingw64/mingw32.
680const GIT_FOR_WINDOWS_BUILDS = ["ucrt64", "clangarm64", "mingw64", "mingw32"] as const;
681​
682function isFileSync(filePath: string): boolean {
683 try {
684 return NodeFS.statSync(filePath).isFile();
685 } catch {
686 return false;
687 }
689​
690/** Bypass the launcher's extra process and kernel-token leak. Retain it when MSYSTEM is set, or git.exe omits hook/helper PATH entries. */
691export function preferGitForWindowsBinary(
692 executable: string,
693 env: NodeJS.ProcessEnv,
694 isFile: (filePath: string) => boolean = isFileSync,
695): string {
696 if (env.MSYSTEM) return executable;
697 const path = NodePath.win32;
698 if (path.basename(executable).toLowerCase() !== "git.exe") return executable;
699 const launcherDirectory = path.dirname(executable);
700 const launcherFolder = path.basename(launcherDirectory).toLowerCase();
701 if (launcherFolder !== "cmd" && launcherFolder !== "bin") return executable;
702 const installRoot = path.dirname(launcherDirectory);
703 for (const build of GIT_FOR_WINDOWS_BUILDS) {
704 const candidate = path.join(installRoot, build, "bin", "git.exe");
705 if (isFile(candidate)) return candidate;
706 }
707 return executable;
709​
710// npm cmd-shim format for native executables.
711const NPM_EXECUTABLE_SHIM_PREFIX = [
712 "@ECHO off",
713 "GOTO start",
714 ":find_dp0",
715 "SET dp0=%~dp0",
716 "EXIT /b",
717 ":start",
718 "SETLOCAL",
719 "CALL :find_dp0",
720];
721const NPM_EXECUTABLE_SHIM_RUN = /^"%dp0%\\([^"%]+\.exe)" +%\*$/;
722​
723function readFileSyncOrUndefined(filePath: string): string | undefined {
724 try {
725 return NodeFS.readFileSync(filePath, "utf8");
726 } catch {
727 return undefined;
728 }
730​
731/** Resolve shims that only launch native executables so direct spawning keeps them in libuv's kill-on-close job. */
732export function npmShimExecutable(
733 shimPath: string,
734 readFile: (filePath: string) => string | undefined = readFileSyncOrUndefined,
735 isFile: (filePath: string) => boolean = isFileSync,
736): string | undefined {
737 const path = NodePath.win32;
738 if (path.extname(shimPath).toLowerCase() !== ".cmd") return undefined;
739 // Match exactly because preserved SET whitespace can select a different file.
740 const lines = readFile(shimPath)
741 ?.split(/\r?\n/)
742 .filter((line) => line.length > 0);
743 if (lines?.length !== NPM_EXECUTABLE_SHIM_PREFIX.length + 1) return undefined;
744 if (NPM_EXECUTABLE_SHIM_PREFIX.some((expected, index) => lines[index] !== expected)) {
745 return undefined;
746 }
747 const target = NPM_EXECUTABLE_SHIM_RUN.exec(lines.at(-1)!)?.[1];
748 if (target === undefined) return undefined;
749 const executable = path.join(path.dirname(shimPath), target);
750 return isFile(executable) ? executable : undefined;
752​
753export type XcodeGitLocator = (env: NodeJS.ProcessEnv) => string | undefined;
754​
755// xcrun honors DEVELOPER_DIR and the `xcode-select` choice, as the shim does.
756function locateXcodeGitWithXcrun(env: NodeJS.ProcessEnv): string | undefined {
757 try {
758 const located = NodeChildProcess.execFileSync("/usr/bin/xcrun", ["--find", "git"], {
759 encoding: "utf8",
760 env,
761 timeout: 5_000,
762 stdio: ["ignore", "pipe", "ignore"],
763 }).trim();
764 return NodePath.isAbsolute(located) ? located : undefined;
765 } catch {
766 return undefined;
767 }
769​
770export const XcodeGitLocation = Context.Reference<XcodeGitLocator>(
771 "@t3tools/shared/shell/XcodeGitLocation",
772 { defaultValue: () => locateXcodeGitWithXcrun },
773);
774​
775const MACOS_GIT_SHIM = "/usr/bin/git";
776​
777/**
778 * Skip the xcrun shim's per-spawn lookup only when git resolves to /usr/bin/git.
779 * User-selected git on PATH still wins, children keep PATH, and lookup failures use `git`.
780 */
781const resolveMacosGit = Effect.fnUntraced(function* (
782 env: NodeJS.ProcessEnv,
783 resolveExecutable: SpawnExecutableResolver,
784) {
785 const locateXcodeGit = yield* XcodeGitLocation;
786 const cache = yield* CommandResolutionCache;
787 const cacheKey = [
788 "xcode-git",
789 String(spawnResolverCacheId(resolveExecutable)),
790 String(spawnResolverCacheId(locateXcodeGit)),
791 resolvePathEnvironmentVariable(env),
792 env.DEVELOPER_DIR ?? "",
793 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
794 const nowNanos = yield* Clock.currentTimeNanos;
795 const cached = cache.get(cacheKey);
796 // An Xcode update or removal deletes the binary; look again instead of failing the spawn.
797 if (
798 cached !== undefined &&
799 cached.expiresAtNanos > nowNanos &&
800 (cached.resolvedPath === null ||
801 resolveExecutable(cached.resolvedPath, "darwin", env) !== undefined)
802 ) {
803 return cached.resolvedPath ?? "git";
804 }
805 const located =
806 resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined;
807 const realGit =
808 located !== undefined && resolveExecutable(located, "darwin", env) !== undefined
809 ? located
810 : null;
811 cacheCommandResolution(cache, cacheKey, realGit, nowNanos);
812 return realGit ?? "git";
813});
814​
815export interface SpawnCommandOptions extends CommandAvailabilityOptions {
816 /** Bypass npm cmd-shims; see npmShimExecutable for process-lifetime semantics. */
817 readonly bypassNpmShim?: boolean;
819​
820export const resolveSpawnCommand = Effect.fnUntraced(function* (
821 command: string,
822 args: ReadonlyArray<string>,
823 options: SpawnCommandOptions = {},
824): Effect.fn.Return<ResolvedSpawnCommand> {
825 const platform = yield* HostProcess.Platform;
826 const isMacosGit = platform === "darwin" && command === "git";
827 if (platform !== "win32" && !isMacosGit) {
828 return { command, args: [...args], shell: false };
829 }
830​
831 const hostEnvironment = yield* HostProcess.Environment;
832 const env =
833 options.env === undefined
834 ? hostEnvironment
835 : options.extendEnv
836 ? { ...hostEnvironment, ...options.env }
837 : options.env;
838 const resolveExecutable = yield* SpawnExecutableResolution;
839 if (isMacosGit) {
840 return {
841 command: yield* resolveMacosGit(env, resolveExecutable),
842 args: [...args],
843 shell: false,
844 };
845 }
846 // The scan is synchronous and runs before every child process, so it shares
847 // the PATH scan cache above. Explicit paths stay uncached for the same reason,
848 // and so do misses: a failed spawn is how providers report "not installed",
849 // and that has to clear the moment the binary appears.
850 const explicitPath = command.includes("/") || command.includes("\\");
851 const cache = yield* CommandResolutionCache;
852 const cacheKey = [
853 "spawn",
854 String(spawnResolverCacheId(resolveExecutable)),
855 platform,
856 resolvePathEnvironmentVariable(env),
857 resolveWindowsPathExtensions(env).join(";"),
858 env.MSYSTEM ? "msystem" : "",
859 command,
860 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
861 const nowNanos = yield* Clock.currentTimeNanos;
862 const cached = explicitPath ? undefined : cache.get(cacheKey);
863 let resolvedExecutable: string | null;
864 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
865 resolvedExecutable = cached.resolvedPath;
866 } else {
867 const found = resolveExecutable(command, platform, env);
868 resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env);
869 if (!explicitPath && resolvedExecutable !== null) {
870 cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos);
871 }
872 }
873 const resolvedCommand = resolvedExecutable ?? command;
874 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
875 if (extension !== ".cmd" && extension !== ".bat") {
876 return { command: resolvedCommand, args: [...args], shell: false };
877 }
878 const shimExecutable = options.bypassNpmShim ? npmShimExecutable(resolvedCommand) : undefined;
879 if (shimExecutable !== undefined) {
880 return { command: shimExecutable, args: [...args], shell: false };
881 }
882​
883 // Build the escaped command line without separate args to avoid Node DEP0190 with shell:true.
884 return {
885 command: [resolvedCommand, ...args].map(escapeWindowsShellArg).join(" "),
886 args: [],
887 shell: true,
888 };
889});
890​
891export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
892 command: string,
893 options: CommandAvailabilityOptions = {},
894) {
895 return (yield* resolveCommandPath(command, options)) !== null;
896});
897​
898function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
899 const appData = env.APPDATA?.trim();
900 const localAppData = env.LOCALAPPDATA?.trim();
901 const userProfile = env.USERPROFILE?.trim();
902​
903 return [
904 ...(appData ? [`${appData}\\npm`] : []),
905 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
906 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
907 ...(userProfile
908 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
909 : []),
910 ];
912​
913/** Keep one PATH spelling in copied Windows environment records. */
914export function setWindowsPath(env: NodeJS.ProcessEnv, value: string | null): void {
915 for (const key of Object.keys(env)) {
916 if (key.toUpperCase() === "PATH") {
917 delete env[key];
918 }
919 }
920 if (value !== null) env.PATH = value;
922​
923function mergeWindowsEnv(
924 currentEnv: NodeJS.ProcessEnv,
925 patch: Partial<Record<string, string>>,
926): NodeJS.ProcessEnv {
927 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
928 for (const [key, value] of Object.entries(patch)) {
929 if (value === undefined) continue;
930 if (key === "PATH") {
931 setWindowsPath(nextEnv, value);
932 } else {
933 nextEnv[key] = value;
934 }
935 }
936 return nextEnv;
938​
939export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
940 env: NodeJS.ProcessEnv,
941): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
942 const readEnvironment = yield* WindowsShellEnvironment;
943 const commandAvailable = yield* CommandAvailability;
944 const inheritedPath = readEnvPath(env);
945 const shellPath = (yield* readEnvironment(["PATH"], { loadProfile: false })).PATH;
946 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
947 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
948 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
949 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
950 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
951​
952 if (yield* commandAvailable("node", { env: baselineEnv })) {
953 return baselinePatch;
954 }
955​
956 const profiledEnvironment = yield* readEnvironment(["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"], {
957 loadProfile: true,
958 });
959 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
960 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
961 ...(profiledPath ? { PATH: profiledPath } : {}),
962 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
963 ...(profiledEnvironment.FNM_MULTISHELL_PATH
964 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
965 : {}),
966 };
967 return Object.keys(profiledPatch).length > 0
968 ? { ...baselinePatch, ...profiledPatch }
969 : baselinePatch;
970});
971​
972export function applyShellEnvironment(
973 env: NodeJS.ProcessEnv,
974 patch: ShellEnvironmentPatch,
975 platform: NodeJS.Platform,
976): void {
977 for (const [key, value] of Object.entries(patch)) {
978 if (key === "PATH" && platform === "win32") setWindowsPath(env, value);
979 else if (value === null) delete env[key];
980 else env[key] = value;
981 }