Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeOS from "node:os";
3import { execFileSync } from "node:child_process";
4import { accessSync, constants, statSync } from "node:fs";
5import { extname, join } from "node:path";
6
7const PATH_CAPTURE_START = "__T3CODE_PATH_START__";
8const PATH_CAPTURE_END = "__T3CODE_PATH_END__";
9const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;
10const WINDOWS_PATH_DELIMITER = ";";
11const POSIX_PATH_DELIMITER = ":";
12const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
13
14type ExecFileSyncLike = (
15 file: string,
16 args: ReadonlyArray<string>,
17 options: { encoding: "utf8"; timeout: number },
18) => string;
19
20export interface CommandAvailabilityOptions {
21 readonly platform?: NodeJS.Platform;
22 readonly env?: NodeJS.ProcessEnv;
23}
24
25export interface WindowsEnvironmentProbeOptions {
26 readonly loadProfile?: boolean;
27}
28
29function trimNonEmpty(value: string | null | undefined): string | undefined {
30 const trimmed = value?.trim();
31 return trimmed && trimmed.length > 0 ? trimmed : undefined;
32}
33
34function readUserLoginShell(): string | undefined {
35 try {
36 return trimNonEmpty(NodeOS.userInfo().shell);
37 } catch {
38 return undefined;
39 }
40}
41
42export function listLoginShellCandidates(
43 platform: NodeJS.Platform,
44 shell: string | undefined,
45 userShell = readUserLoginShell(),
46): ReadonlyArray<string> {
47 const fallbackShell =
48 platform === "darwin" ? "/bin/zsh" : platform === "linux" ? "/bin/bash" : undefined;
49 const seen = new Set<string>();
50 const candidates: string[] = [];
51
52 for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {
53 if (!candidate || seen.has(candidate)) {
54 continue;
55 }
56 seen.add(candidate);
57 candidates.push(candidate);
58 }
59
60 return candidates;
61}
62
63export function extractPathFromShellOutput(output: string): string | null {
64 const startIndex = output.indexOf(PATH_CAPTURE_START);
65 if (startIndex === -1) return null;
66
67 const valueStartIndex = startIndex + PATH_CAPTURE_START.length;
68 const endIndex = output.indexOf(PATH_CAPTURE_END, valueStartIndex);
69 if (endIndex === -1) return null;
70
71 const pathValue = output.slice(valueStartIndex, endIndex).trim();
72 return pathValue.length > 0 ? pathValue : null;
73}
74
75export function readPathFromLoginShell(
76 shell: string,
77 execFile: ExecFileSyncLike = execFileSync,
78): string | undefined {
79 return readEnvironmentFromLoginShell(shell, ["PATH"], execFile).PATH;
80}
81
82export function readPathFromLaunchctl(
83 execFile: ExecFileSyncLike = execFileSync,
84): string | undefined {
85 try {
86 return trimNonEmpty(
87 execFile("/bin/launchctl", ["getenv", "PATH"], {
88 encoding: "utf8",
89 timeout: 2000,
90 }),
91 );
92 } catch {
93 return undefined;
94 }
95}
96
97export function mergePathEntries(
98 preferredPath: string | undefined,
99 inheritedPath: string | undefined,
100 platform: NodeJS.Platform,
101): string | undefined {
102 const delimiter = platform === "win32" ? ";" : ":";
103 const merged: string[] = [];
104 const seen = new Set<string>();
105
106 for (const pathValue of [preferredPath, inheritedPath]) {
107 if (!pathValue) continue;
108 for (const entry of pathValue.split(delimiter)) {
109 const trimmedEntry = entry.trim();
110 if (!trimmedEntry || seen.has(trimmedEntry)) {
111 continue;
112 }
113 seen.add(trimmedEntry);
114 merged.push(trimmedEntry);
115 }
116 }
117
118 return merged.length > 0 ? merged.join(delimiter) : undefined;
119}
120
121function envCaptureStart(name: string): string {
122 return `__T3CODE_ENV_${name}_START__`;
123}
124
125function envCaptureEnd(name: string): string {
126 return `__T3CODE_ENV_${name}_END__`;
127}
128
129function buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
130 return names
131 .map((name) => {
132 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
133 throw new Error(`Unsupported environment variable name: ${name}`);
134 }
135
136 return [
137 `printf '%s\\n' '${envCaptureStart(name)}'`,
138 `printenv ${name} || true`,
139 `printf '%s\\n' '${envCaptureEnd(name)}'`,
140 ].join("; ");
141 })
142 .join("; ");
143}
144
145function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {
146 return [
147 "$ErrorActionPreference = 'Stop'",
148 ...names.flatMap((name) => {
149 if (!SHELL_ENV_NAME_PATTERN.test(name)) {
150 throw new Error(`Unsupported environment variable name: ${name}`);
151 }
152
153 return [
154 `Write-Output '${envCaptureStart(name)}'`,
155 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
156 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
157 `Write-Output '${envCaptureEnd(name)}'`,
158 ];
159 }),
160 ].join("; ");
161}
162
163function extractEnvironmentValue(output: string, name: string): string | undefined {
164 const startMarker = envCaptureStart(name);
165 const endMarker = envCaptureEnd(name);
166 const startIndex = output.indexOf(startMarker);
167 if (startIndex === -1) return undefined;
168
169 const valueStartIndex = startIndex + startMarker.length;
170 const endIndex = output.indexOf(endMarker, valueStartIndex);
171 if (endIndex === -1) return undefined;
172
173 const value = output
174 .slice(valueStartIndex, endIndex)
175 .replace(/^\r?\n/, "")
176 .replace(/\r?\n$/, "");
177
178 return value.length > 0 ? value : undefined;
179}
180
181export type ShellEnvironmentReader = (
182 shell: string,
183 names: ReadonlyArray<string>,
184 execFile?: ExecFileSyncLike,
185) => Partial<Record<string, string>>;
186
187export const readEnvironmentFromLoginShell: ShellEnvironmentReader = (
188 shell,
189 names,
190 execFile = execFileSync,
191) => {
192 if (names.length === 0) {
193 return {};
194 }
195
196 const output = execFile(shell, ["-ilc", buildEnvironmentCaptureCommand(names)], {
197 encoding: "utf8",
198 timeout: 5000,
199 });
200
201 const environment: Partial<Record<string, string>> = {};
202 for (const name of names) {
203 const value = extractEnvironmentValue(output, name);
204 if (value !== undefined) {
205 environment[name] = value;
206 }
207 }
208
209 return environment;
210};
211
212export type WindowsShellEnvironmentReader = (
213 names: ReadonlyArray<string>,
214 options?: WindowsEnvironmentProbeOptions,
215) => Partial<Record<string, string>>;
216
217export function readEnvironmentFromWindowsShell(
218 names: ReadonlyArray<string>,
219 execFile?: ExecFileSyncLike,
220): Partial<Record<string, string>>;
221export function readEnvironmentFromWindowsShell(
222 names: ReadonlyArray<string>,
223 options?: WindowsEnvironmentProbeOptions,
224 execFile?: ExecFileSyncLike,
225): Partial<Record<string, string>>;
226export function readEnvironmentFromWindowsShell(
227 names: ReadonlyArray<string>,
228 optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,
229 maybeExecFile?: ExecFileSyncLike,
230): Partial<Record<string, string>> {
231 if (names.length === 0) {
232 return {};
233 }
234
235 const options =
236 typeof optionsOrExecFile === "function"
237 ? ({} satisfies WindowsEnvironmentProbeOptions)
238 : (optionsOrExecFile ?? {});
239 const execFile: ExecFileSyncLike =
240 typeof optionsOrExecFile === "function"
241 ? optionsOrExecFile
242 : (maybeExecFile ?? (execFileSync as ExecFileSyncLike));
243 const command = buildWindowsEnvironmentCaptureCommand(names);
244 const args = [
245 "-NoLogo",
246 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
247 "-NonInteractive",
248 "-Command",
249 command,
250 ];
251 for (const shell of WINDOWS_SHELL_CANDIDATES) {
252 try {
253 const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
254
255 const environment: Partial<Record<string, string>> = {};
256 for (const name of names) {
257 const value = extractEnvironmentValue(output, name);
258 if (value !== undefined) {
259 environment[name] = value;
260 }
261 }
262 return environment;
263 } catch {
264 continue;
265 }
266 }
267
268 return {};
269}
270
271function stripWrappingQuotes(value: string): string {
272 return value.replace(/^"+|"+$/g, "");
273}
274
275function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
276 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
277}
278
279function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
280 const normalized = stripWrappingQuotes(entry.trim());
281 return platform === "win32" ? normalized.toLowerCase() : normalized;
282}
283
284export function mergePathValues(
285 preferredPath: string | undefined,
286 inheritedPath: string | undefined,
287 platform: NodeJS.Platform,
288): string | undefined {
289 const delimiter = pathDelimiterForPlatform(platform);
290 const merged: string[] = [];
291 const seen = new Set<string>();
292
293 for (const rawValue of [preferredPath, inheritedPath]) {
294 if (!rawValue) continue;
295
296 for (const entry of rawValue.split(delimiter)) {
297 const trimmed = entry.trim();
298 if (trimmed.length === 0) continue;
299
300 const normalized = normalizePathEntryForComparison(trimmed, platform);
301 if (normalized.length === 0 || seen.has(normalized)) continue;
302
303 seen.add(normalized);
304 merged.push(trimmed);
305 }
306 }
307
308 return merged.length > 0 ? merged.join(delimiter) : undefined;
309}
310
311function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
312 return env.PATH ?? env.Path ?? env.path;
313}
314
315function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
316 return readEnvPath(env) ?? "";
317}
318
319function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
320 const rawValue = env.PATHEXT;
321 const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
322 if (!rawValue) return fallback;
323
324 const parsed = rawValue
325 .split(";")
326 .map((entry) => entry.trim())
327 .filter((entry) => entry.length > 0)
328 .map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
329 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
330}
331
332function resolveCommandCandidates(
333 command: string,
334 platform: NodeJS.Platform,
335 windowsPathExtensions: ReadonlyArray<string>,
336): ReadonlyArray<string> {
337 if (platform !== "win32") return [command];
338 const extension = extname(command);
339 const normalizedExtension = extension.toUpperCase();
340
341 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
342 const commandWithoutExtension = command.slice(0, -extension.length);
343 return Array.from(
344 new Set([
345 command,
346 `${commandWithoutExtension}${normalizedExtension}`,
347 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
348 ]),
349 );
350 }
351
352 const candidates: string[] = [];
353 for (const candidateExtension of windowsPathExtensions) {
354 candidates.push(`${command}${candidateExtension}`);
355 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
356 }
357 return Array.from(new Set(candidates));
358}
359
360function isExecutableFile(
361 filePath: string,
362 platform: NodeJS.Platform,
363 windowsPathExtensions: ReadonlyArray<string>,
364): boolean {
365 try {
366 const stat = statSync(filePath);
367 if (!stat.isFile()) return false;
368 if (platform === "win32") {
369 const extension = extname(filePath);
370 if (extension.length === 0) return false;
371 return windowsPathExtensions.includes(extension.toUpperCase());
372 }
373 accessSync(filePath, constants.X_OK);
374 return true;
375 } catch {
376 return false;
377 }
378}
379
380export function resolveCommandPath(
381 command: string,
382 options: CommandAvailabilityOptions = {},
383): string | null {
384 const platform = options.platform ?? process.platform;
385 const env = options.env ?? process.env;
386 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
387 const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
388
389 if (command.includes("/") || command.includes("\\")) {
390 for (const candidate of commandCandidates) {
391 if (isExecutableFile(candidate, platform, windowsPathExtensions)) {
392 return candidate;
393 }
394 }
395 return null;
396 }
397
398 const pathValue = resolvePathEnvironmentVariable(env);
399 if (pathValue.length === 0) return null;
400 const pathEntries = pathValue
401 .split(pathDelimiterForPlatform(platform))
402 .map((entry) => stripWrappingQuotes(entry.trim()))
403 .filter((entry) => entry.length > 0);
404
405 for (const pathEntry of pathEntries) {
406 for (const candidate of commandCandidates) {
407 const candidatePath = join(pathEntry, candidate);
408 if (isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
409 return candidatePath;
410 }
411 }
412 }
413 return null;
414}
415
416export function isCommandAvailable(
417 command: string,
418 options: CommandAvailabilityOptions = {},
419): boolean {
420 return resolveCommandPath(command, options) !== null;
421}
422
423export function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
424 const appData = env.APPDATA?.trim();
425 const localAppData = env.LOCALAPPDATA?.trim();
426 const userProfile = env.USERPROFILE?.trim();
427
428 return [
429 ...(appData ? [`${appData}\\npm`] : []),
430 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
431 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
432 ...(userProfile ? [`${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`] : []),
433 ];
434}
435
436export interface WindowsEnvironmentResolverOptions {
437 readonly readEnvironment?: WindowsShellEnvironmentReader;
438 readonly commandAvailable?: typeof isCommandAvailable;
439}
440
441function readWindowsEnvironmentSafely(
442 readEnvironment: WindowsShellEnvironmentReader,
443 names: ReadonlyArray<string>,
444 options?: WindowsEnvironmentProbeOptions,
445): Partial<Record<string, string>> {
446 try {
447 return readEnvironment(names, options);
448 } catch {
449 return {};
450 }
451}
452
453function mergeWindowsEnv(
454 currentEnv: NodeJS.ProcessEnv,
455 patch: Partial<Record<string, string>>,
456): NodeJS.ProcessEnv {
457 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
458 for (const [key, value] of Object.entries(patch)) {
459 if (value !== undefined) {
460 nextEnv[key] = value;
461 }
462 }
463 return nextEnv;
464}
465
466export function resolveWindowsEnvironment(
467 env: NodeJS.ProcessEnv,
468 options: WindowsEnvironmentResolverOptions = {},
469): Partial<NodeJS.ProcessEnv> {
470 const readEnvironment = options.readEnvironment ?? readEnvironmentFromWindowsShell;
471 const commandAvailable = options.commandAvailable ?? isCommandAvailable;
472 const inheritedPath = readEnvPath(env);
473 const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
474 loadProfile: false,
475 }).PATH;
476 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
477 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
478 const baselinePath = mergePathValues(knownCliPath, mergedPath, "win32");
479 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
480 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
481
482 if (commandAvailable("node", { platform: "win32", env: baselineEnv })) {
483 return baselinePatch;
484 }
485
486 const profiledEnvironment = readWindowsEnvironmentSafely(
487 readEnvironment,
488 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
489 { loadProfile: true },
490 );
491 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
492 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
493 ...(profiledPath ? { PATH: profiledPath } : {}),
494 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
495 ...(profiledEnvironment.FNM_MULTISHELL_PATH
496 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
497 : {}),
498 };
499 return Object.keys(profiledPatch).length > 0
500 ? { ...baselinePatch, ...profiledPatch }
501 : baselinePatch;
502}