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

shell.ts

501 lines15.2 KB

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