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

shell.ts

506 lines15.3 KB

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;
24​
25export interface WindowsEnvironmentProbeOptions {
26 readonly loadProfile?: boolean;
28​
29function trimNonEmpty(value: string | null | undefined): string | undefined {
30 const trimmed = value?.trim();
31 return trimmed && trimmed.length > 0 ? trimmed : undefined;
33​
34function readUserLoginShell(): string | undefined {
35 try {
36 return trimNonEmpty(NodeOS.userInfo().shell);
37 } catch {
38 return undefined;
39 }
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;
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;
74​
75export function readPathFromLoginShell(
76 shell: string,
77 execFile: ExecFileSyncLike = execFileSync,
78): string | undefined {
79 return readEnvironmentFromLoginShell(shell, ["PATH"], execFile).PATH;
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 }
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;
120​
121function envCaptureStart(name: string): string {
122 return `__T3CODE_ENV_${name}_START__`;
124​
125function envCaptureEnd(name: string): string {
126 return `__T3CODE_ENV_${name}_END__`;
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("; ");
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("; ");
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;
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 {};
270​
271function stripWrappingQuotes(value: string): string {
272 return value.replace(/^"+|"+$/g, "");
274​
275function pathDelimiterForPlatform(platform: NodeJS.Platform): string {
276 return platform === "win32" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;
278​
279function normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {
280 const normalized = stripWrappingQuotes(entry.trim());
281 return platform === "win32" ? normalized.toLowerCase() : normalized;
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;
310​
311function readEnvPath(env: NodeJS.ProcessEnv): string | undefined {
312 return env.PATH ?? env.Path ?? env.path;
314​
315function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
316 return readEnvPath(env) ?? "";
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: string[] = [];
325 for (const entry of rawValue.split(";")) {
326 const trimmed = entry.trim();
327 if (trimmed.length === 0) continue;
328 parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
329 }
330 return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
332​
333function resolveCommandCandidates(
334 command: string,
335 platform: NodeJS.Platform,
336 windowsPathExtensions: ReadonlyArray<string>,
337): ReadonlyArray<string> {
338 if (platform !== "win32") return [command];
339 const extension = extname(command);
340 const normalizedExtension = extension.toUpperCase();
341​
342 if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
343 const commandWithoutExtension = command.slice(0, -extension.length);
344 return Array.from(
345 new Set([
346 command,
347 `${commandWithoutExtension}${normalizedExtension}`,
348 `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
349 ]),
350 );
351 }
352​
353 const candidates: string[] = [];
354 for (const candidateExtension of windowsPathExtensions) {
355 candidates.push(`${command}${candidateExtension}`);
356 candidates.push(`${command}${candidateExtension.toLowerCase()}`);
357 }
358 return Array.from(new Set(candidates));
360​
361function isExecutableFile(
362 filePath: string,
363 platform: NodeJS.Platform,
364 windowsPathExtensions: ReadonlyArray<string>,
365): boolean {
366 try {
367 const stat = statSync(filePath);
368 if (!stat.isFile()) return false;
369 if (platform === "win32") {
370 const extension = extname(filePath);
371 if (extension.length === 0) return false;
372 return windowsPathExtensions.includes(extension.toUpperCase());
373 }
374 accessSync(filePath, constants.X_OK);
375 return true;
376 } catch {
377 return false;
378 }
380​
381export function resolveCommandPath(
382 command: string,
383 options: CommandAvailabilityOptions = {},
384): string | null {
385 const platform = options.platform ?? process.platform;
386 const env = options.env ?? process.env;
387 const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
388 const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
389​
390 if (command.includes("/") || command.includes("\\")) {
391 for (const candidate of commandCandidates) {
392 if (isExecutableFile(candidate, platform, windowsPathExtensions)) {
393 return candidate;
394 }
395 }
396 return null;
397 }
398​
399 const pathValue = resolvePathEnvironmentVariable(env);
400 if (pathValue.length === 0) return null;
401 const pathEntries: string[] = [];
402 for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
403 const pathEntry = stripWrappingQuotes(entry.trim());
404 if (pathEntry.length > 0) {
405 pathEntries.push(pathEntry);
406 }
407 }
408​
409 for (const pathEntry of pathEntries) {
410 for (const candidate of commandCandidates) {
411 const candidatePath = join(pathEntry, candidate);
412 if (isExecutableFile(candidatePath, platform, windowsPathExtensions)) {
413 return candidatePath;
414 }
415 }
416 }
417 return null;
419​
420export function isCommandAvailable(
421 command: string,
422 options: CommandAvailabilityOptions = {},
423): boolean {
424 return resolveCommandPath(command, options) !== null;
426​
427export function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
428 const appData = env.APPDATA?.trim();
429 const localAppData = env.LOCALAPPDATA?.trim();
430 const userProfile = env.USERPROFILE?.trim();
431​
432 return [
433 ...(appData ? [`${appData}\\npm`] : []),
434 ...(localAppData ? [`${localAppData}\\Programs\\nodejs`, `${localAppData}\\Volta\\bin`] : []),
435 ...(localAppData ? [`${localAppData}\\pnpm`] : []),
436 ...(userProfile ? [`${userProfile}\\.bun\\bin`, `${userProfile}\\scoop\\shims`] : []),
437 ];
439​
440export interface WindowsEnvironmentResolverOptions {
441 readonly readEnvironment?: WindowsShellEnvironmentReader;
442 readonly commandAvailable?: typeof isCommandAvailable;
444​
445function readWindowsEnvironmentSafely(
446 readEnvironment: WindowsShellEnvironmentReader,
447 names: ReadonlyArray<string>,
448 options?: WindowsEnvironmentProbeOptions,
449): Partial<Record<string, string>> {
450 try {
451 return readEnvironment(names, options);
452 } catch {
453 return {};
454 }
456​
457function mergeWindowsEnv(
458 currentEnv: NodeJS.ProcessEnv,
459 patch: Partial<Record<string, string>>,
460): NodeJS.ProcessEnv {
461 const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };
462 for (const [key, value] of Object.entries(patch)) {
463 if (value !== undefined) {
464 nextEnv[key] = value;
465 }
466 }
467 return nextEnv;
469​
470export function resolveWindowsEnvironment(
471 env: NodeJS.ProcessEnv,
472 options: WindowsEnvironmentResolverOptions = {},
473): Partial<NodeJS.ProcessEnv> {
474 const readEnvironment = options.readEnvironment ?? readEnvironmentFromWindowsShell;
475 const commandAvailable = options.commandAvailable ?? isCommandAvailable;
476 const inheritedPath = readEnvPath(env);
477 const shellPath = readWindowsEnvironmentSafely(readEnvironment, ["PATH"], {
478 loadProfile: false,
479 }).PATH;
480 const mergedPath = mergePathValues(shellPath, inheritedPath, "win32");
481 const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);
482 const baselinePath = mergePathValues(knownCliPath, mergedPath, "win32");
483 const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};
484 const baselineEnv = mergeWindowsEnv(env, baselinePatch);
485​
486 if (commandAvailable("node", { platform: "win32", env: baselineEnv })) {
487 return baselinePatch;
488 }
489​
490 const profiledEnvironment = readWindowsEnvironmentSafely(
491 readEnvironment,
492 ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
493 { loadProfile: true },
494 );
495 const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, "win32");
496 const profiledPatch: Partial<NodeJS.ProcessEnv> = {
497 ...(profiledPath ? { PATH: profiledPath } : {}),
498 ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),
499 ...(profiledEnvironment.FNM_MULTISHELL_PATH
500 ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }
501 : {}),
502 };
503 return Object.keys(profiledPatch).length > 0
504 ? { ...baselinePatch, ...profiledPatch }
505 : baselinePatch;