()
| 72 | * Results are cached for 1 minute to avoid repeated operations. |
| 73 | */ |
| 74 | export async function getShellEnvironment(): Promise<Record<string, string>> { |
| 75 | const now = Date.now(); |
| 76 | const ttl = isFallbackCache ? FALLBACK_CACHE_TTL_MS : CACHE_TTL_MS; |
| 77 | if (cachedEnv && now - cacheTime < ttl) { |
| 78 | // Return a copy to prevent caller mutations from corrupting cache |
| 79 | return { ...cachedEnv }; |
| 80 | } |
| 81 | |
| 82 | // Windows: derive PATH without shell invocation |
| 83 | // Git Bash PATH doesn't include Windows user paths, so we build it manually |
| 84 | if (process.platform === "win32") { |
| 85 | console.log( |
| 86 | "[shell-env] Windows detected, deriving PATH without shell invocation", |
| 87 | ); |
| 88 | const env: Record<string, string> = { |
| 89 | ...process.env, |
| 90 | PATH: buildWindowsPath(), |
| 91 | HOME: os.homedir(), |
| 92 | USER: os.userInfo().username, |
| 93 | USERPROFILE: os.homedir(), |
| 94 | }; |
| 95 | |
| 96 | // Ensure all values are strings |
| 97 | const stringEnv: Record<string, string> = {}; |
| 98 | for (const [key, value] of Object.entries(env)) { |
| 99 | if (typeof value === "string") { |
| 100 | stringEnv[key] = value; |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | cachedEnv = stringEnv; |
| 105 | cacheTime = now; |
| 106 | isFallbackCache = false; |
| 107 | console.log( |
| 108 | `[shell-env] Built Windows environment with ${Object.keys(stringEnv).length} vars`, |
| 109 | ); |
| 110 | return { ...stringEnv }; |
| 111 | } |
| 112 | |
| 113 | // macOS/Linux: spawn login shell to get full environment |
| 114 | const shell = |
| 115 | process.env.SHELL || |
| 116 | (process.platform === "darwin" ? "/bin/zsh" : "/bin/bash"); |
| 117 | |
| 118 | try { |
| 119 | // Use -lc flags (not -ilc): |
| 120 | // -l: login shell (sources .zprofile/.profile for PATH setup) |
| 121 | // -c: execute command |
| 122 | // Avoids -i (interactive) to skip TTY prompts and reduce latency |
| 123 | const { stdout } = await execFileAsync(shell, ["-lc", "env"], { |
| 124 | timeout: 10_000, |
| 125 | env: { |
| 126 | ...process.env, |
| 127 | HOME: os.homedir(), |
| 128 | }, |
| 129 | }); |
| 130 | |
| 131 | const env: Record<string, string> = {}; |
no test coverage detected