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

shell.ts

1,299 lines46.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 Cache from "effect/Cache";
7import * as Clock from "effect/Clock";
8import * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14​
15import type { ShellEnvironmentPatch } from "@t3tools/contracts";
16import * as HostProcess from "./HostProcess.ts";
17import * as Context from "effect/Context";
18const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
19const WINDOWS_PATH_DELIMITER = ";";
20const POSIX_PATH_DELIMITER = ":";
21const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
22const WINDOWS_SHELL_PROBE_TIMEOUT_MS = 5000;
23// A shell stuck in the kernel survives the kill and holds stdout, so execFile's callback never fires.
24const WINDOWS_SHELL_PROBE_DEADLINE = Duration.millis(WINDOWS_SHELL_PROBE_TIMEOUT_MS + 1000);
25​
26type ExecFileSyncLike = (
27 file: string,
28 args: ReadonlyArray<string>,
29 options: {
30 encoding: "utf8";
31 timeout: number;
32 killSignal?: NodeJS.Signals | number;
33 detached?: true;
34 stdio?: ["ignore", "pipe", "ignore"];
35 },
36) => string;
37​
38function canExecuteFile(filePath: string): boolean {
39 try {
40 NodeFS.accessSync(filePath, NodeFS.constants.X_OK);
41 return true;
42 } catch {
43 return false;
44 }
46​
47export interface CommandAvailabilityOptions {
48 readonly env?: NodeJS.ProcessEnv;
49 readonly extendEnv?: boolean;
51​
52export type CommandAvailabilityChecker = (
53 command: string,
54 options?: CommandAvailabilityOptions,
55) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;
56​
57const WINDOWS_SHELL_META_CHARS = /([()\][%!^"`<>&|;, *?])/g;
58​
59// Escape dynamic arguments for both cmd.exe and the target's CommandLineToArgvW parsing.
60function escapeWindowsShellArg(arg: string): string {
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 escaped = `"${escaped}"`;
65 return escaped.replace(WINDOWS_SHELL_META_CHARS, "^$1");
67​
68export interface ResolvedSpawnCommand {
69 readonly command: string;
70 readonly args: ReadonlyArray<string>;
71 readonly shell: boolean;
73​
74export type SpawnExecutableResolver = (
75 command: string,
76 platform: NodeJS.Platform,
77 env: NodeJS.ProcessEnv,
78) => string | undefined | Promise<string | undefined>;
79​
80async function resolveSpawnExecutableWithNode(
81 command: string,
82 platform: NodeJS.Platform,
83 env: NodeJS.ProcessEnv,
84): Promise<string | undefined> {
85 const path = platform === "win32" ? NodePath.win32 : NodePath.posix;
86 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
87 const candidates = resolveCommandCandidates(
88 command,
89 platform,
90 windowsPathExtensions,
91 path.extname,
92 );
93 const isExecutable = async (candidate: string) => {
94 try {
95 if (!(await NodeFS.promises.stat(candidate)).isFile()) return false;
96 if (platform === "win32") {
97 return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());
98 }
99 await NodeFS.promises.access(candidate, NodeFS.constants.X_OK);
100 return true;
101 } catch {
102 return false;
103 }
104 };
105​
106 if (command.includes("/") || command.includes("\\")) {
107 for (const candidate of candidates) {
108 if (await isExecutable(candidate)) return candidate;
109 }
110 return undefined;
111 }
112​
113 for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) {
114 const normalizedPathEntry = normalizePathEntry(pathEntry, platform);
115 if (normalizedPathEntry.length === 0) continue;
116 const names =
117 platform === "win32"
118 ? await listResolverPathDirectory(normalizedPathEntry, path.isAbsolute)
119 : undefined;
120 for (const candidate of candidates) {
121 if (isAbsentFromListing(names, candidate)) continue;
122 const candidatePath = path.join(normalizedPathEntry, candidate);
123 if (await isExecutable(candidatePath)) return candidatePath;
124 }
125 }
126 return undefined;
128​
129export const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(
130 "@t3tools/shared/shell/SpawnExecutableResolution",
131 {
132 defaultValue: () => resolveSpawnExecutableWithNode,
133 },
134);
135​
136export interface WindowsEnvironmentProbeOptions {
137 readonly loadProfile?: boolean;
139​
140function trimNonEmpty(value: string | null | undefined): string | undefined {
141 const trimmed = value?.trim();
142 return trimmed && trimmed.length > 0 ? trimmed : undefined;
144​
145export function readUserLoginShell(): string | undefined {
146 try {
147 return trimNonEmpty(NodeOS.userInfo().shell);
148 } catch {
149 return undefined;
150 }
152​
153export function listLoginShellCandidates(
154 platform: NodeJS.Platform,
155 shell: string | undefined,
156 userShell = readUserLoginShell(),
157): ReadonlyArray<string> {
158 const fallbackShell =
159 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
160 const seen = new Set<string>();
161 const candidates: string[] = [];
162​
163 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
164 if (!candidate || seen.has(candidate)) {
165 continue;
166 }
167 seen.add(candidate);
168 candidates.push(candidate);
169 }
170​
171 return candidates;
173​
174export function readPathFromLaunchctl(
175 execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,
176): string | undefined {
177 try {
178 return trimNonEmpty(
179 execFile("/bin/launchctl", ["getenv", "PATH"], {
180 encoding: "utf8",
181 timeout: 2000,
182 }),
183 );
184 } catch {
185 return undefined;
186 }
188​
189export function mergePathEntries(
190 preferredPath: string | undefined,
191 inheritedPath: string | undefined,
192 platform: NodeJS.Platform,
193): string | undefined {
194 const delimiter = platform === "win32" ? ";" : ":";
195 const merged: string[] = [];
196 const seen = new Set<string>();
197​
198 for (const pathValue of [preferredPath, inheritedPath]) {
199 if (!pathValue) continue;
200 for (const entry of pathValue.split(delimiter)) {
201 const trimmedEntry = trimPathEntry(entry, platform);
202 if (!trimmedEntry || seen.has(trimmedEntry)) {
203 continue;
204 }
205 seen.add(trimmedEntry);
206 merged.push(trimmedEntry);
207 }
208 }
209​
210 return merged.length > 0 ? merged.join(delimiter) : undefined;
212​
213function envCaptureStart(name: string): string {
214 return `__T3CODE_ENV_${name}_START__`;
216​
217function envCaptureEnd(name: string): string {
218 return `__T3CODE_ENV_${name}_END__`;
220​
221const DEBUG_TRAP_SHELLS = new Set(["bash", "zsh", "sh", "ksh", "ksh93"]);
222const POSIX_CAPTURE_SYNTAX = { assignment: "__T3CODE_PRINTENV=$(", orElse: " || " };
223const PRINTENV_CAPTURE_SYNTAX = new Map(
224 [...DEBUG_TRAP_SHELLS, "dash", "ash"].map((shell) => [shell, POSIX_CAPTURE_SYNTAX] as const),
225).set("fish", { assignment: "set -l __T3CODE_PRINTENV (", orElse: "; or " });
226// Network PATH entries must be probed inside the shell's deadline, away from the desktop thread.
227const PRINTENV_LOOKUP_COMMAND = `/bin/sh -c 'command -v printenv || { [ -n "$1" ] && PATH="$1" command -v printenv; } || printf %s /usr/bin/printenv' t3`;
228​
229export function buildEnvironmentCaptureCommand(
230 shell: string,
231 names: ReadonlyArray<string>,
232): string {
233 const executableName = NodePath.basename(shell).toLowerCase();
234 const isNushell = executableName.startsWith("nu");
235 const syntax = PRINTENV_CAPTURE_SYNTAX.get(executableName);
236 const supportsFallback = syntax !== undefined;
237 const inheritedPath = resolvePathEnvironmentVariable(process.env)
238 .split(POSIX_PATH_DELIMITER)
239 .filter(Boolean)
240 .map((entry) => NodePath.posix.resolve(entry))
241 .join(POSIX_PATH_DELIMITER);
242 const lookupPrintenv = `${PRINTENV_LOOKUP_COMMAND} '${inheritedPath.replaceAll("'", "'\\''")}'`;
243 const { assignment, orElse } = syntax ?? POSIX_CAPTURE_SYNTAX;
244 const resolvePrintenv = `${assignment}${lookupPrintenv}); `;
245​
246 const capture = names
247 .map((name) => {
248 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
249 throw new Error(`Unsupported environment variable name: ${name}`);
250 }
251​
252 if (isNushell) {
253 // Without a configured conversion, Nu expands home paths only in a list PATH.
254 const defaultValue =
255 name === "PATH"
256 ? "if ($env.PATH? | describe | str starts-with 'list') { " +
257 "$env.PATH | each {|p| if ($p | str starts-with '~') { " +
258 "$p | path expand --no-symlink } else { $p } } | str join (char esep) " +
259 "} else { $env.PATH? | default '' }"
260 : `$env.${name}? | default ''`;
261 const value =
262 `if $env.${name}? == null { '' } else if ` +
263 `$env.ENV_CONVERSIONS?.${name}?.to_string? != null { ` +
264 `$env.${name} | do $env.ENV_CONVERSIONS.${name}.to_string $env.${name} ` +
265 `} else { ${defaultValue} }`;
266 return [
267 `print '${envCaptureStart(name)}'`,
268 `print (${value})`,
269 `print '${envCaptureEnd(name)}'`,
270 ].join("; ");
271 }
272​
273 return [
274 `printf '%s\\n' '${envCaptureStart(name)}'`,
275 supportsFallback
276 ? `printenv ${name}${orElse}"$__T3CODE_PRINTENV" ${name}${orElse}true`
277 : `printenv ${name} || true`,
278 `printf '%s\\n' '${envCaptureEnd(name)}'`,
279 ].join("; ");
280 })
281 .join("; ");
282​
283 // A DEBUG trap that echoes each command (e.g. into the terminal title) would print the markers.
284 // OpenBSD ksh (also its /bin/sh) exits on `trap - DEBUG`, so try it in a subshell first.
285 const command = supportsFallback ? resolvePrintenv + capture : capture;
286 return DEBUG_TRAP_SHELLS.has(executableName)
287 ? `(trap - DEBUG) 2>/dev/null && trap - DEBUG; ${command}`
288 : command;
290​
291// Process first so profile prepends win; User and Machine add dirs missing from the launch snapshot.
292export function windowsEnvironmentValueCommand(name: string): string {
293 if (name === "PATH") {
294 return (
295 "$value = (@(" +
296 "[Environment]::GetEnvironmentVariable('PATH','Process')," +
297 "[Environment]::GetEnvironmentVariable('PATH','Machine')," +
298 "[Environment]::GetEnvironmentVariable('PATH','User')" +
299 ") | Where-Object { $_ }) -join ';'"
300 );
301 }
302 return `$value = [Environment]::GetEnvironmentVariable('${name}')`;
304​
305function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
306 return [
307 "$ErrorActionPreference = 'Stop'",
308 // Redirected PowerShell output uses the console code page, which mangles non-ASCII paths.
309 "try { [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch {}",
310 ...names.flatMap((name) => {
311 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
312 throw new Error(`Unsupported environment variable name: ${name}`);
313 }
314​
315 return [
316 `Write-Output '${envCaptureStart(name)}'`,
317 windowsEnvironmentValueCommand(name),
318 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
319 `Write-Output '${envCaptureEnd(name)}'`,
320 ];
321 }),
322 ].join("; ");
324​
325function extractEnvironmentValue(output: string, name: string): string | undefined {
326 const startMarker = envCaptureStart(name);
327 const endMarker = envCaptureEnd(name);
328 const startIndex = output.indexOf(startMarker);
329 if (startIndex === -1) return undefined;
330​
331 const valueStartIndex = startIndex + startMarker.length;
332 const endIndex = output.indexOf(endMarker, valueStartIndex);
333 if (endIndex === -1) return undefined;
334​
335 const value = output
336 .slice(valueStartIndex, endIndex)
337 .replace(/^\r?\n/, "")
338 .replace(/\r?\n$/, "");
339​
340 return value.length > 0 ? value : undefined;
342​
343/** Reads the values `buildEnvironmentCaptureCommand` printed; unset or empty names are omitted. */
344export function extractEnvironmentValues(
345 output: string,
346 names: ReadonlyArray<string>,
347): Partial<Record<string, string>> {
348 const environment: Partial<Record<string, string>> = {};
349 for (const name of names) {
350 const value = extractEnvironmentValue(output, name);
351 if (value !== undefined) {
352 environment[name] = value;
353 }
354 }
355 return environment;
357​
358export type ShellEnvironmentReader = (
359 shell: string,
360 names: ReadonlyArray<string>,
361 execFile?: ExecFileSyncLike,
362) => Partial<Record<string, string>>;
363​
364export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
365 shell,
366 names,
367 execFile = NodeChildProcess.execFileSync,
368) => {
369 if (names.length === 0) {
370 return {};
371 }
372​
373 // Interactive startup loads PATH entries; detaching prevents job control on an
374 // inherited controlling TTY from stopping the probe while the parent waits.
375 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(shell, names)], {
376 encoding: "utf8",
377 timeout: 5000,
378 killSignal: "SIGKILL",
379 detached: true,
380 stdio: ["ignore", "pipe", "ignore"],
381 });
382​
383 return extractEnvironmentValues(output, names);
384};
385​
386export type WindowsShellEnvironmentReader = (
387 names: ReadonlyArray<string>,
388 options?: WindowsEnvironmentProbeOptions,
389) => Effect.Effect<Partial<Record<string, string>>>;
390​
391export const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(
392 "@t3tools/shared/shell/WindowsShellEnvironment",
393 {
394 defaultValue: () => readEnvironmentFromWindowsShell,
395 },
396);
397​
398export const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(
399 "@t3tools/shared/shell/CommandAvailability",
400 {
401 defaultValue: () => isCommandAvailable,
402 },
403);
404​
405const execWindowsEnvironmentProbe = (
406 file: string,
407 args: ReadonlyArray<string>,
408 options: { encoding: "utf8"; timeout: number },
409) =>
410 Effect.callback<Option.Option<string>>((resume) => {
411 let child: NodeChildProcess.ChildProcess;
412 try {
413 child = NodeChildProcess.execFile(
414 file,
415 args,
416 { ...options, windowsHide: true },
417 (error, stdout) => {
418 resume(Effect.succeed(error ? Option.none() : Option.some(stdout)));
419 },
420 );
421 } catch {
422 resume(Effect.succeedNone);
423 return;
424 }
425 return Effect.sync(() => {
426 child.kill();
427 child.stdout?.destroy();
428 child.stderr?.destroy();
429 child.unref();
430 });
431 });
432​
433export const readEnvironmentFromWindowsShell = Effect.fn("shell.readEnvironmentFromWindowsShell")(
434 function* (
435 names: ReadonlyArray<string>,
436 options: WindowsEnvironmentProbeOptions = {},
437 execFile: typeof execWindowsEnvironmentProbe = execWindowsEnvironmentProbe,
438 ) {
439 if (names.length === 0) return {};
440​
441 const command = buildWindowsEnvironmentCaptureCommand(names);
442 const args = [
443 "-NoLogo",
444 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
445 "-NonInteractive",
446 "-Command",
447 command,
448 ];
449 for (const shell of WINDOWS_SHELL_CANDIDATES) {
450 const output = yield* execFile(shell, args, {
451 encoding: "utf8",
452 timeout: WINDOWS_SHELL_PROBE_TIMEOUT_MS,
453 }).pipe(Effect.timeoutOption(WINDOWS_SHELL_PROBE_DEADLINE), Effect.map(Option.flatten));
454 if (Option.isNone(output)) continue;
455​
456 const environment: Partial<Record<string, string>> = {};
457 for (const name of names) {
458 const value = extractEnvironmentValue(output.value, name);
459 if (value !== undefined) environment[name] = value;
460 }
461 return environment;
462 }
463​
464 return {};
465 },
466);
467​
468function trimPathEntry(entry: string, platform: NodeJS.Platform): string {
469 return platform === "win32" ? entry.trim() : entry;
471​
472// POSIX PATH entries are literal: whitespace and quotes are part of the directory name.
473function normalizePathEntry(entry: string, platform: NodeJS.Platform): string {
474 return platform === "win32" ? entry.trim().replace(/^"+|"+$/g, "") : entry;
476​
477function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
478 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
480​
481function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
482 const normalized = normalizePathEntry(entry, platform);
483 return platform === "win32" ? normalized.toLowerCase() : normalized;
485​
486function sanitizePathEntry(entry: string, platform: NodeJS.Platform): string {
487 return platform === "win32" ? entry.replaceAll('"', "") : entry;
489​
490export function mergePathValues(
491 preferredPath: string | undefined,
492 inheritedPath: string | undefined,
493 platform: NodeJS.Platform,
494): string | undefined {
495 const delimiter = pathDelimiterForPlatform(platform);
496 const merged: string[] = [];
497 const seen = new Set<string>();
498​
499 for (const rawValue of [preferredPath, inheritedPath]) {
500 if (!rawValue) continue;
501​
502 for (const entry of rawValue.split(delimiter)) {
503 const sanitized = sanitizePathEntry(trimPathEntry(entry, platform), platform);
504 if (sanitized.length === 0) continue;
505​
506 const normalized = normalizePathEntryForComparison(sanitized, platform);
507 if (normalized.length === 0 || seen.has(normalized)) continue;
508​
509 seen.add(normalized);
510 merged.push(sanitized);
511 }
512 }
513​
514 return merged.length > 0 ? merged.join(delimiter) : undefined;
516​
517function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
518 return env.PATH ?? env.Path ?? env.path;
520​
521function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
522 return readEnvPath(env) ?? "";
524​
525function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
526 const rawValue =
527 env.PATHEXT ??
528 Object.entries(env).find(
529 ([key, value]) => key.toUpperCase() === "PATHEXT" && value !== undefined,
530 )?.[1];
531 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
532 if (!rawValue) return fallback;
533​
534 const parsed: string[] = [];
535 for (const entry of rawValue.split(";")) {
536 const trimmed = entry.trim();
537 if (trimmed.length === 0) continue;
538 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
539 }
540 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
542​
543function resolveCommandCandidates(
544 command: string,
545 platform: NodeJS.Platform,
546 windowsPathExtensions: ReadonlyArray<string>,
547 extname: (path: string) => string,
548): ReadonlyArray<string> {
549 if (platform !== "win32") return [command];
550 const extension = extname(command);
551 const normalizedExtension = extension.toUpperCase();
552​
553 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
554 const commandWithoutExtension = command.slice(0, -extension.length);
555 return Array.from(
556 new Set([
557 command,
558 `${commandWithoutExtension}${normalizedExtension}`,
559 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
560 ]),
561 );
562 }
563​
564 const candidates: string[] = [];
565 for (const candidateExtension of windowsPathExtensions) {
566 candidates.push(`${command}${candidateExtension}`);
567 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
568 }
569 return Array.from(new Set(candidates));
571​
572// Explicit paths bypass the cache for new installs; cached misses can otherwise hide binaries for 30 seconds.
573const COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;
574const COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;
575const COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);
576​
577interface CommandResolutionCacheEntry {
578 readonly resolvedPath: string | null;
579 readonly expiresAtNanos: bigint;
581​
582export const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(
583 "@t3tools/shared/shell/CommandResolutionCache",
584 {
585 defaultValue: () => new Map(),
586 },
587);
588​
589interface PathDirectoryListing {
590 readonly modified: number | null | undefined;
591 /** Lowercased entry names; undefined when the directory cannot be listed. */
592 readonly names: ReadonlySet<string> | undefined;
593 readonly reusable: boolean;
595​
596const PATH_DIRECTORY_LISTINGS_MAX_ENTRIES = 1024;
597// A directory changed within a coarse filesystem's timestamp step (FAT: 2 s) can change again
598// without moving its mtime, so its listing serves the lookups waiting on it but is not kept.
599const PATH_DIRECTORY_SETTLE_MS = 2_000;
600const NO_DIRECTORY_NAMES: ReadonlySet<string> = new Set();
601​
602// A listing only speaks for names Windows matches by ASCII case folding. It omits 8.3 aliases
603// (`~`), Windows trims a trailing dot, and other characters fold differently than in JS.
604const LISTED_NAME_PATTERN = /^[\w.+-]*[\w+-]$/;
605​
606function isAbsentFromListing(names: ReadonlySet<string> | undefined, candidate: string): boolean {
607 return (
608 names !== undefined &&
609 LISTED_NAME_PATTERN.test(candidate) &&
610 !names.has(candidate.toLowerCase())
611 );
613​
614// The listing must start after the mtime's timestamp step has passed, and a relative entry
615// names another directory once the working directory changes.
616function isReusableListing(
617 directory: string,
618 modified: number,
619 listedAtMs: number,
620 isAbsolute: (path: string) => boolean,
621): boolean {
622 return isAbsolute(directory) && listedAtMs - modified >= PATH_DIRECTORY_SETTLE_MS;
624​
625const directoryMtime = (directory: string) =>
626 FileSystem.FileSystem.use((fileSystem) => fileSystem.stat(directory)).pipe(
627 Effect.map((info) =>
628 info.type === "Directory" ? Option.getOrUndefined(info.mtime)?.getTime() : undefined,
629 ),
630 Effect.catch((error) => Effect.succeed(error.reason._tag === "NotFound" ? null : undefined)),
631 );
632​
633// Timestamp before reading so concurrent additions change the next mtime check; missing listings fall back to direct probes.
634const listPathDirectory = Effect.fnUntraced(function* (
635 directory: string,
636): Effect.fn.Return<PathDirectoryListing, never, FileSystem.FileSystem | Path.Path> {
637 const path = yield* Path.Path;
638 const modified = yield* directoryMtime(directory);
639 if (modified === null) {
640 return { modified, names: NO_DIRECTORY_NAMES, reusable: path.isAbsolute(directory) };
641 }
642 if (modified === undefined) return { modified, names: undefined, reusable: false };
643 const listedAtMs = yield* Clock.currentTimeMillis;
644 const entries = yield* FileSystem.FileSystem.use((fileSystem) =>
645 fileSystem.readDirectory(directory),
646 ).pipe(Effect.orElseSucceed(() => undefined));
647 return {
648 modified,
649 names: entries && new Set(entries.map((entry) => entry.toLowerCase())),
650 reusable:
651 entries !== undefined && isReusableListing(directory, modified, listedAtMs, path.isAbsolute),
652 };
653});
654​
655export const makePathDirectoryListings = Cache.makeWith(listPathDirectory, {
656 capacity: PATH_DIRECTORY_LISTINGS_MAX_ENTRIES,
657 timeToLive: (exit) =>
658 Exit.isSuccess(exit) && exit.value.reusable ? Duration.infinity : Duration.zero,
659 requireServicesAt: "lookup",
660});
661​
662/** Windows PATH directory listings for the process; each use rechecks the directory's mtime. */
663export const PathDirectoryListings = Context.Reference(
664 "@t3tools/shared/shell/PathDirectoryListings",
665 { defaultValue: () => Effect.runSync(makePathDirectoryListings) },
666);
667​
668const resolverPathDirectoryListings = new Map<
669 string,
670 { readonly modified: number; readonly names: ReadonlySet<string> }
671>();
672​
673// The spawn resolver's counterpart of `PathDirectoryListings`, under the same rules.
674async function listResolverPathDirectory(
675 directory: string,
676 isAbsolute: (path: string) => boolean,
677): Promise<ReadonlySet<string> | undefined> {
678 let modified: number;
679 try {
680 const stats = await NodeFS.promises.stat(directory);
681 if (!stats.isDirectory()) return undefined;
682 modified = stats.mtimeMs;
683 } catch (error) {
684 return (error as NodeJS.ErrnoException).code === "ENOENT" ? NO_DIRECTORY_NAMES : undefined;
685 }
686 const cached = resolverPathDirectoryListings.get(directory);
687 if (cached?.modified === modified) return cached.names;
688 resolverPathDirectoryListings.delete(directory);
689 // This resolver runs outside Effect, so it has no Clock to read.
690 // @effect-diagnostics-next-line globalDate:off
691 const listedAtMs = Date.now();
692 let names: ReadonlySet<string>;
693 try {
694 names = new Set((await NodeFS.promises.readdir(directory)).map((entry) => entry.toLowerCase()));
695 } catch {
696 return undefined;
697 }
698 if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) {
699 if (resolverPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) {
700 const oldest = resolverPathDirectoryListings.keys().next().value;
701 if (oldest !== undefined) resolverPathDirectoryListings.delete(oldest);
702 }
703 resolverPathDirectoryListings.set(directory, { modified, names });
704 }
705 return names;
707​
708// An injected resolver or locator may answer differently for the same search, so its
709// entries are kept apart from every other resolver's.
710let spawnResolverCacheIdCount = 0;
711const spawnResolverCacheIds = new WeakMap<SpawnExecutableResolver | XcodeGitLocator, number>();
712function spawnResolverCacheId(resolver: SpawnExecutableResolver | XcodeGitLocator): number {
713 const known = spawnResolverCacheIds.get(resolver);
714 if (known !== undefined) return known;
715 const id = spawnResolverCacheIdCount++;
716 spawnResolverCacheIds.set(resolver, id);
717 return id;
719​
720function cacheCommandResolution(
721 cache: Map<string, CommandResolutionCacheEntry>,
722 cacheKey: string,
723 resolvedPath: string | null,
724 nowNanos: bigint,
725): void {
726 if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {
727 const oldestKey = cache.keys().next().value;
728 if (oldestKey !== undefined) {
729 cache.delete(oldestKey);
730 }
731 }
732 cache.set(cacheKey, {
733 resolvedPath,
734 expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,
735 });
737​
738const isExecutableFile = Effect.fnUntraced(function* (
739 filePath: string,
740 platform: NodeJS.Platform,
741 windowsPathExtensions: ReadonlyArray<string>,
742): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
743 const fileSystem = yield* FileSystem.FileSystem;
744 const path = yield* Path.Path;
745 const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
746 if (stat === null || stat.type !== "File") return false;
747​
748 if (platform === "win32") {
749 const extension = path.extname(filePath);
750 if (extension.length === 0) return false;
751 return windowsPathExtensions.includes(extension.toUpperCase());
752 }
753​
754 return canExecuteFile(filePath);
755});
756​
757// Called within the traced command resolvers.
758const findOnPath = Effect.fnUntraced(function* (
759 pathValue: string,
760 commandCandidates: ReadonlyArray<string>,
761 platform: NodeJS.Platform,
762 windowsPathExtensions: ReadonlyArray<string>,
763 isLast: (match: string) => boolean,
764): Effect.fn.Return<ReadonlyArray<string>, never, FileSystem.FileSystem | Path.Path> {
765 const path = yield* Path.Path;
766 // Keep case variants: Windows can make PATH directories case-sensitive.
767 const pathEntries: string[] = [];
768 const seenPathEntries = new Set<string>();
769 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
770 const pathEntry = normalizePathEntry(entry, platform);
771 if (pathEntry.length === 0 || seenPathEntries.has(pathEntry)) continue;
772​
773 seenPathEntries.add(pathEntry);
774 pathEntries.push(pathEntry);
775 }
776​
777 // Only Windows multiplies the candidates per directory; elsewhere a listing saves no probe.
778 const listings = platform === "win32" ? yield* PathDirectoryListings : undefined;
779 const matches: string[] = [];
780 for (const pathEntry of pathEntries) {
781 let listing = listings && (yield* Cache.get(listings, pathEntry));
782 if (listings && listing?.names && listing.modified !== (yield* directoryMtime(pathEntry))) {
783 yield* Cache.invalidate(listings, pathEntry);
784 listing = yield* Cache.get(listings, pathEntry);
785 }
786 for (const candidate of commandCandidates) {
787 if (isAbsentFromListing(listing?.names, candidate)) continue;
788 const candidatePath = path.join(pathEntry, candidate);
789 if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
790 matches.push(candidatePath);
791 if (isLast(candidatePath)) return matches;
792 break;
793 }
794 }
795 }
796 return matches;
797});
798​
799const resolveCommandPathForPlatform = Effect.fn("shell.resolveCommandPathForPlatform")(function* (
800 command: string,
801 options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },
802): Effect.fn.Return<string | null, never, FileSystem.FileSystem | Path.Path> {
803 const path = yield* Path.Path;
804 const platform = options.platform;
805 const env = options.env ?? process.env;
806 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
807 const commandCandidates = resolveCommandCandidates(
808 command,
809 platform,
810 windowsPathExtensions,
811 path.extname,
812 );
813​
814 if (command.includes("/") || command.includes("\\")) {
815 for (const candidate of commandCandidates) {
816 if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {
817 return candidate;
818 }
819 }
820 return null;
821 }
822​
823 const pathValue = resolvePathEnvironmentVariable(env);
824 if (pathValue.length === 0) {
825 return null;
826 }
827​
828 const cacheKey = [platform, pathValue, windowsPathExtensions.join(";"), command].join(
829 COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,
830 );
831 const cache = yield* CommandResolutionCache;
832 const nowNanos = yield* Clock.monotonicTimeNanos;
833 const cached = cache.get(cacheKey);
834 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
835 return cached.resolvedPath;
836 }
837​
838 const [resolvedPath = null] = yield* findOnPath(
839 pathValue,
840 commandCandidates,
841 platform,
842 windowsPathExtensions,
843 () => true,
844 );
845 cacheCommandResolution(cache, cacheKey, resolvedPath, nowNanos);
846 return resolvedPath;
847});
848​
849export const resolveCommandPath = Effect.fn("shell.resolveCommandPath")(function* (
850 command: string,
851 options: CommandAvailabilityOptions = {},
852) {
853 return yield* resolveCommandPathForPlatform(command, {
854 env: options.env ?? (yield* HostProcess.Environment),
855 platform: yield* HostProcess.Platform,
856 });
857});
858​
859// Matches for a bare command in PATH order, up to the first one `until` accepts; not cached.
860export const resolveCommandPaths = Effect.fn("shell.resolveCommandPaths")(function* (
861 command: string,
862 options: CommandAvailabilityOptions & { readonly until: (match: string) => boolean },
863) {
864 const path = yield* Path.Path;
865 const platform = yield* HostProcess.Platform;
866 const env = options.env ?? (yield* HostProcess.Environment);
867 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
868 return yield* findOnPath(
869 resolvePathEnvironmentVariable(env),
870 resolveCommandCandidates(command, platform, windowsPathExtensions, path.extname),
871 platform,
872 windowsPathExtensions,
873 options.until,
874 );
875});
876​
877// Git 2.56 x64 uses ucrt64; ARM64 uses clangarm64; older x64/32-bit builds use mingw64/mingw32.
878const GIT_FOR_WINDOWS_BUILDS = ["ucrt64", "clangarm64", "mingw64", "mingw32"] as const;
879​
880function isFileSync(filePath: string): boolean {
881 try {
882 return NodeFS.statSync(filePath).isFile();
883 } catch {
884 return false;
885 }
887​
888/** Bypass the launcher's extra process and kernel-token leak. Retain it when MSYSTEM is set, or git.exe omits hook/helper PATH entries. */
889export function preferGitForWindowsBinary(
890 executable: string,
891 env: NodeJS.ProcessEnv,
892 isFile: (filePath: string) => boolean = isFileSync,
893): string {
894 if (env.MSYSTEM) return executable;
895 const path = NodePath.win32;
896 if (path.basename(executable).toLowerCase() !== "git.exe") return executable;
897 const launcherDirectory = path.dirname(executable);
898 const launcherFolder = path.basename(launcherDirectory).toLowerCase();
899 if (launcherFolder !== "cmd" && launcherFolder !== "bin") return executable;
900 const installRoot = path.dirname(launcherDirectory);
901 for (const build of GIT_FOR_WINDOWS_BUILDS) {
902 const candidate = path.join(installRoot, build, "bin", "git.exe");
903 if (isFile(candidate)) return candidate;
904 }
905 return executable;
907​
908/** Git for Windows' bash beside a git.exe from its install, never WSL's System32 bash.exe. */
909export function gitForWindowsBash(
910 gitExecutable: string,
911 isFile: (filePath: string) => boolean = isFileSync,
912): string | undefined {
913 const path = NodePath.win32;
914 if (path.basename(gitExecutable).toLowerCase() !== "git.exe") return undefined;
915 // git.exe lives in <root>\cmd, <root>\bin, or <root>\<build>\bin.
916 const launcherRoot = path.dirname(path.dirname(gitExecutable));
917 return [launcherRoot, path.dirname(launcherRoot)]
918 .map((root) => path.join(root, "bin", "bash.exe"))
919 .find(isFile);
921​
922// npm cmd-shim format for native executables.
923const NPM_EXECUTABLE_SHIM_PREFIX = [
924 "@ECHO off",
925 "GOTO start",
926 ":find_dp0",
927 "SET dp0=%~dp0",
928 "EXIT /b",
929 ":start",
930 "SETLOCAL",
931 "CALL :find_dp0",
932];
933const NPM_EXECUTABLE_SHIM_RUN = /^"%dp0%\\([^"%]+\.exe)" +%\*$/;
934​
935function readFileSyncOrUndefined(filePath: string): string | undefined {
936 try {
937 return NodeFS.readFileSync(filePath, "utf8");
938 } catch {
939 return undefined;
940 }
942​
943/** Resolve shims that only launch native executables so direct spawning keeps them in libuv's kill-on-close job. */
944export function npmShimExecutable(
945 shimPath: string,
946 readFile: (filePath: string) => string | undefined = readFileSyncOrUndefined,
947 isFile: (filePath: string) => boolean = isFileSync,
948): string | undefined {
949 const path = NodePath.win32;
950 if (path.extname(shimPath).toLowerCase() !== ".cmd") return undefined;
951 // Match exactly because preserved SET whitespace can select a different file.
952 const lines = readFile(shimPath)
953 ?.split(/\r?\n/)
954 .filter((line) => line.length > 0);
955 if (lines?.length !== NPM_EXECUTABLE_SHIM_PREFIX.length + 1) return undefined;
956 if (NPM_EXECUTABLE_SHIM_PREFIX.some((expected, index) => lines[index] !== expected)) {
957 return undefined;
958 }
959 const target = NPM_EXECUTABLE_SHIM_RUN.exec(lines.at(-1)!)?.[1];
960 if (target === undefined) return undefined;
961 const executable = path.join(path.dirname(shimPath), target);
962 return isFile(executable) ? executable : undefined;
964​
965export type XcodeGitLocator = (env: NodeJS.ProcessEnv) => string | undefined;
966​
967// xcrun honors DEVELOPER_DIR and the `xcode-select` choice, as the shim does.
968function locateXcodeGitWithXcrun(env: NodeJS.ProcessEnv): string | undefined {
969 try {
970 const located = NodeChildProcess.execFileSync("/usr/bin/xcrun", ["--find", "git"], {
971 encoding: "utf8",
972 env,
973 timeout: 5_000,
974 stdio: ["ignore", "pipe", "ignore"],
975 }).trim();
976 return NodePath.isAbsolute(located) ? located : undefined;
977 } catch {
978 return undefined;
979 }
981​
982export const XcodeGitLocation = Context.Reference<XcodeGitLocator>(
983 "@t3tools/shared/shell/XcodeGitLocation",
984 { defaultValue: () => locateXcodeGitWithXcrun },
985);
986​
987const MACOS_GIT_SHIM = "/usr/bin/git";
988​
989/**
990 * Skip the xcrun shim's per-spawn lookup only when git resolves to /usr/bin/git.
991 * User-selected git on PATH still wins, children keep PATH, and lookup failures use `git`.
992 */
993const resolveMacosGit = Effect.fnUntraced(function* (
994 env: NodeJS.ProcessEnv,
995 resolveExecutable: SpawnExecutableResolver,
996) {
997 const locateXcodeGit = yield* XcodeGitLocation;
998 const cache = yield* CommandResolutionCache;
999 const cacheKey = [
1000 "xcode-git",
1001 String(spawnResolverCacheId(resolveExecutable)),
1002 String(spawnResolverCacheId(locateXcodeGit)),
1003 resolvePathEnvironmentVariable(env),
1004 env.DEVELOPER_DIR ?? "",
1005 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
1006 const nowNanos = yield* Clock.currentTimeNanos;
1007 const cached = cache.get(cacheKey);
1008 // An Xcode update or removal deletes the binary; look again instead of failing the spawn.
1009 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
1010 const cachedPath = cached.resolvedPath;
1011 if (
1012 cachedPath === null ||
1013 (yield* Effect.promise(async () => resolveExecutable(cachedPath, "darwin", env))) !==
1014 undefined
1015 ) {
1016 return cachedPath ?? "git";
1019 const onPath = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env));
1020 const located = onPath === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined;
1021 const realGit =
1022 located !== undefined &&
1023 (yield* Effect.promise(async () => resolveExecutable(located, "darwin", env))) !== undefined
1024 ? located
1025 : null;
1026 cacheCommandResolution(cache, cacheKey, realGit, nowNanos);
1027 return realGit ?? "git";
1028});
1029​
1030export interface SpawnCommandOptions extends CommandAvailabilityOptions {
1031 /** Bypass npm cmd-shims; see npmShimExecutable for process-lifetime semantics. */
1032 readonly bypassNpmShim?: boolean;
1034​
1035// `*` is one argument that is not an option. These forms read refs or config
1036// only, so git starts no hook, helper, pager, editor or lazy fetch for them.
1037const CONSOLE_FREE_GIT_READS = [
1038 "rev-parse --git-path index",
1039 "rev-parse --git-common-dir",
1040 "rev-parse --show-toplevel",
1041 "rev-parse --git-common-dir --show-toplevel",
1042 "rev-parse --path-format=absolute --git-path index --git-common-dir --show-toplevel",
1043 "rev-parse --symbolic-full-name HEAD",
1044 "rev-parse --abbrev-ref --symbolic-full-name @{upstream}",
1045 "symbolic-ref --quiet HEAD",
1046 "symbolic-ref *",
1047 "remote",
1048 "remote get-url *",
1049 "remote get-url -- *",
1050 "config --get *",
1051].map((form) => form.split(" "));
1052​
1053export function runsGitWithoutConsole(
1054 platform: NodeJS.Platform,
1055 executable: string,
1056 args: ReadonlyArray<string>,
1057): boolean {
1058 if (platform !== "win32") return false;
1059 const { basename, dirname } = NodePath.win32;
1060 const bin = dirname(executable);
1061 const build = basename(dirname(bin)).toLowerCase();
1062 if (basename(executable).toLowerCase() !== "git.exe" || basename(bin).toLowerCase() !== "bin") {
1063 return false;
1065 if (!GIT_FOR_WINDOWS_BUILDS.some((candidate) => candidate === build)) return false;
1066 const rest =
1067 args[0] === "--git-dir" && args[1] !== undefined && !args[1].startsWith("-")
1068 ? args.slice(2)
1069 : args;
1070 return CONSOLE_FREE_GIT_READS.some(
1071 (form) =>
1072 form.length === rest.length &&
1073 form.every((part, i) => part === rest[i] || (part === "*" && !rest[i]!.startsWith("-"))),
1074 );
1076​
1077export const resolveSpawnCommand = Effect.fnUntraced(function* (
1078 command: string,
1079 args: ReadonlyArray<string>,
1080 options: SpawnCommandOptions = {},
1081): Effect.fn.Return<ResolvedSpawnCommand> {
1082 const platform = yield* HostProcess.Platform;
1083 const isMacosGit = platform === "darwin" && command === "git";
1084 if (platform !== "win32" && !isMacosGit) {
1085 return { command, args: [...args], shell: false };
1087​
1088 const hostEnvironment = yield* HostProcess.Environment;
1089 const env =
1090 options.env === undefined
1091 ? hostEnvironment
1092 : options.extendEnv
1093 ? { ...hostEnvironment, ...options.env }
1094 : options.env;
1095 const resolveExecutable = yield* SpawnExecutableResolution;
1096 if (isMacosGit) {
1097 return {
1098 command: yield* resolveMacosGit(env, resolveExecutable),
1099 args: [...args],
1100 shell: false,
1101 };
1103 // Cache successful PATH lookups. Explicit paths and misses stay uncached so
1104 // newly installed executables are discoverable immediately.
1105 const explicitPath = command.includes("/") || command.includes("\\");
1106 const cache = yield* CommandResolutionCache;
1107 const cacheKey = [
1108 "spawn",
1109 String(spawnResolverCacheId(resolveExecutable)),
1110 platform,
1111 resolvePathEnvironmentVariable(env),
1112 resolveWindowsPathExtensions(env).join(";"),
1113 env.MSYSTEM ? "msystem" : "",
1114 command,
1115 ].join(COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR);
1116 const nowNanos = yield* Clock.currentTimeNanos;
1117 const cached = explicitPath ? undefined : cache.get(cacheKey);
1118 let resolvedExecutable: string | null;
1119 if (cached !== undefined && cached.expiresAtNanos > nowNanos) {
1120 resolvedExecutable = cached.resolvedPath;
1121 } else {
1122 const found = yield* Effect.promise(async () => resolveExecutable(command, platform, env));
1123 resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env);
1124 if (!explicitPath && resolvedExecutable !== null) {
1125 cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos);
1128 const resolvedCommand = resolvedExecutable ?? command;
1129 const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();
1130 if (extension !== ".cmd" && extension !== ".bat") {
1131 return { command: resolvedCommand, args: [...args], shell: false };
1133 const shimExecutable = options.bypassNpmShim ? npmShimExecutable(resolvedCommand) : undefined;
1134 if (shimExecutable !== undefined) {
1135 return { command: shimExecutable, args: [...args], shell: false };
1137​
1138 // Build the escaped command line without separate args to avoid Node DEP0190 with shell:true.
1139 return {
1140 command: [resolvedCommand, ...args].map(escapeWindowsShellArg).join(" "),
1141 args: [],
1142 shell: true,
1143 };
1144});
1145​
1146export const isCommandAvailable = Effect.fn("shell.isCommandAvailable")(function* (
1147 command: string,
1148 options: CommandAvailabilityOptions = {},
1149) {
1150 return (yield* resolveCommandPath(command, options)) !== null;
1151});
1152​
1153function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
1154 const appData = env.APPDATA?.trim();
1155 const localAppData = env.LOCALAPPDATA?.trim();
1156 const userProfile = env.USERPROFILE?.trim();
1157​
1158 return [
1159 ...(appData ? [`${appData}\\npm`] : []),
1160 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
1161 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
1162 ...(userProfile
1163 ? [`${userProfile}\\.local\\bin`, `${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`]
1164 : []),
1165 ];
1167​
1168/** Keep one PATH spelling in copied Windows environment records. */
1169export function setWindowsPath(env: NodeJS.ProcessEnv, value: string | null): void {
1170 for (const key of Object.keys(env)) {
1171 if (key.toUpperCase() === "PATH") {
1172 delete env[key];
1175 if (value !== null) env.PATH = value;
1177​
1178function mergeWindowsEnv(
1179 currentEnv: NodeJS.ProcessEnv,
1180 patch: Partial<Record<string, string>>,
1181): NodeJS.ProcessEnv {
1182 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
1183 for (const [key, value] of Object.entries(patch)) {
1184 if (value === undefined) continue;
1185 if (key === "PATH") {
1186 setWindowsPath(nextEnv, value);
1187 } else {
1188 nextEnv[key] = value;
1191 return nextEnv;
1193​
1194export const resolveWindowsEnvironment = Effect.fn("shell.resolveWindowsEnvironment")(function* (
1195 env: NodeJS.ProcessEnv,
1196): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {
1197 const readEnvironment = yield* WindowsShellEnvironment;
1198 const commandAvailable = yield* CommandAvailability;
1199 const inheritedPath = readEnvPath(env);
1200 const shellPath = (yield* readEnvironment(["PATH"], { loadProfile: false })).PATH;
1201 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
1202 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
1203 const baselinePath = mergePathValues(mergedPath, knownCliPath, "win32");
1204 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
1205 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
1206​
1207 if (yield* commandAvailable("node", { env: baselineEnv })) {
1208 return baselinePatch;
1210​
1211 const profiledEnvironment = yield* readEnvironment(["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"], {
1212 loadProfile: true,
1213 });
1214 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
1215 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
1216 ...(profiledPath ? { PATH: profiledPath } : {}),
1217 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
1218 ...(profiledEnvironment.FNM_MULTISHELL_PATH
1219 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
1220 : {}),
1221 };
1222 return Object.keys(profiledPatch).length > 0
1223 ? { ...baselinePatch, ...profiledPatch }
1224 : baselinePatch;
1225});
1226​
1227export function applyShellEnvironment(
1228 env: NodeJS.ProcessEnv,
1229 patch: ShellEnvironmentPatch,
1230 platform: NodeJS.Platform,
1231): void {
1232 for (const [key, value] of Object.entries(patch)) {
1233 if (key === "PATH" && platform === "win32") setWindowsPath(env, value);
1234 else if (value === null) delete env[key];
1235 else env[key] = value;
1238​
1239interface PathSetupInput {
1240 readonly directory: string;
1241 readonly home: string;
1242 readonly shell: string | undefined;
1243 readonly platform: NodeJS.Platform;
1244 /** `XDG_CONFIG_HOME`, where fish reads its startup file when set. */
1245 readonly configHome?: string | undefined;
1246 /** `ZDOTDIR`, where zsh reads `.zshrc` when set. */
1247 readonly zdotdir?: string | undefined;
1249​
1250/**
1251 * The startup file (`~/...`, or absolute under `configHome`) and line that put `directory` last on
1252 * PATH for new zsh, bash, or fish terminals, so it never shadows another `t3`. Undefined on Windows (writing PATH there would flatten the registry's
1253 * `%VAR%` entries), for other shells, macOS bash, or unsafe paths.
1254 */
1255export function pathSetup(
1256 input: PathSetupInput,
1257): { readonly file: string; readonly line: string } | undefined {
1258 // A relative folder on PATH would follow the working directory into any checkout.
1259 if (input.platform === "win32" || !input.directory.startsWith("/")) return undefined;
1260 const underHome = input.directory.startsWith(`${input.home}/`);
1261 const rest = underHome ? input.directory.slice(input.home.length) : input.directory;
1262 if (!/^[\w./-]+$/.test(rest)) return undefined;
1263 const directory = underHome ? `$HOME${rest}` : rest;
1264 const shell = input.shell?.split("/").pop();
1265 // A set folder the shell reads from replaces the default; one unsafe to write means no setup,
1266 // since the default file would never be read.
1267 const readFrom = (value: string | undefined, fallback: string) =>
1268 !value ? fallback : value.startsWith("/") && /^[\w./-]+$/.test(value) ? value : undefined;
1269 if (shell === "fish") {
1270 const configHome = readFrom(input.configHome, "~/.config");
1271 if (configHome === undefined) return undefined;
1272 // --path changes $PATH itself; fish_user_paths would go ahead of the system folders.
1273 return {
1274 file: `${configHome}/fish/config.fish`,
1275 line: `fish_add_path --append --path ${directory}`,
1276 };
1278 // macOS bash reads only the first of .bash_profile, .bash_login, and .profile; no file is safe.
1279 const zdotdir = readFrom(input.zdotdir, "~");
1280 const file =
1281 shell === "zsh"
1282 ? zdotdir && `${zdotdir}/.zshrc`
1283 : shell === "bash" && input.platform !== "darwin"
1284 ? "~/.bashrc"
1285 : undefined;
1286 return file === undefined ? undefined : { file, line: `export PATH="$PATH:${directory}"` };
1288​
1289/** A command to paste that does what {@link pathSetup} describes. */
1290export function pathSetupCommand(input: PathSetupInput): string | undefined {
1291 const setup = pathSetup(input);
1292 if (!setup) return undefined;
1293 // The leading newline keeps the line out of a final comment with no newline after it.
1294 const append = `printf '\\n%s\\n' '${setup.line}' >> ${setup.file}`;
1295 // fish's config folder may not exist yet; `&&` works in fish 3 too.
1296 return setup.file.endsWith(".fish")
1297 ? `mkdir -p ${setup.file.slice(0, setup.file.lastIndexOf("/"))} && ${append}`
1298 : append;