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

DesktopShellEnvironment.ts

355 lines10.9 KB

1import * as Context from "effect/Context";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
7​
8import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
9​
10type EnvironmentPatch = Record<string, string>;
11​
12interface ShellEnvironmentConfig {
13 readonly env: NodeJS.ProcessEnv;
14 readonly platform: NodeJS.Platform;
15 readonly userShell: Option.Option<string>;
17​
18interface WindowsProbeOptions {
19 readonly loadProfile: boolean;
21​
22export interface DesktopShellEnvironmentShape {
23 readonly installIntoProcess: Effect.Effect<void, never>;
25​
26export class DesktopShellEnvironment extends Context.Service<
27 DesktopShellEnvironment,
28 DesktopShellEnvironmentShape
29>()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
30​
31const LOGIN_SHELL_ENV_NAMES = [
32 "PATH",
33 "SSH_AUTH_SOCK",
34 "HOMEBREW_PREFIX",
35 "HOMEBREW_CELLAR",
36 "HOMEBREW_REPOSITORY",
37 "XDG_CONFIG_HOME",
38 "XDG_DATA_HOME",
39] as const;
40const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
41const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
42const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
43const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
44const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
45​
46const trimNonEmpty = (value: string | null | undefined): Option.Option<string> =>
47 Option.fromNullishOr(value).pipe(
48 Option.map((entry) => entry.trim()),
49 Option.filter((entry) => entry.length > 0),
50 );
51​
52const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";" : ":");
53​
54const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
55 trimNonEmpty(env.PATH ?? env.Path ?? env.path);
56​
57const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
58 const normalized = entry.trim().replace(/^"+|"+$/g, "");
59 return platform === "win32" ? normalized.toLowerCase() : normalized;
60};
61​
62const mergePaths = (
63 platform: NodeJS.Platform,
64 values: ReadonlyArray<Option.Option<string>>,
65): Option.Option<string> => {
66 const delimiter = pathDelimiter(platform);
67 const entries: string[] = [];
68 const seen = new Set<string>();
69​
70 for (const value of values) {
71 if (Option.isNone(value)) continue;
72​
73 for (const entry of value.value.split(delimiter)) {
74 const trimmed = entry.trim();
75 if (trimmed.length === 0) continue;
76​
77 const key = pathComparisonKey(trimmed, platform);
78 if (key.length === 0 || seen.has(key)) continue;
79​
80 seen.add(key);
81 entries.push(trimmed);
82 }
83 }
84​
85 return entries.length > 0 ? Option.some(entries.join(delimiter)) : Option.none();
86};
87​
88const listLoginShellCandidates = (config: ShellEnvironmentConfig): ReadonlyArray<string> => {
89 const fallback =
90 config.platform === "darwin" ? "/bin/zsh" : config.platform === "linux" ? "/bin/bash" : "";
91 const seen = new Set<string>();
92 const candidates: string[] = [];
93​
94 for (const candidate of [
95 trimNonEmpty(config.env.SHELL),
96 config.userShell,
97 trimNonEmpty(fallback),
98 ]) {
99 if (Option.isNone(candidate) || seen.has(candidate.value)) continue;
100 seen.add(candidate.value);
101 candidates.push(candidate.value);
102 }
103​
104 return candidates;
105};
106​
107const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
108 ...trimNonEmpty(env.APPDATA).pipe(
109 Option.match({
110 onNone: () => [],
111 onSome: (value) => [`${value}\\npm`],
112 }),
113 ),
114 ...trimNonEmpty(env.LOCALAPPDATA).pipe(
115 Option.match({
116 onNone: () => [],
117 onSome: (value) => [`${value}\\Programs\\nodejs`, `${value}\\Volta\\bin`, `${value}\\pnpm`],
118 }),
119 ),
120 ...trimNonEmpty(env.USERPROFILE).pipe(
121 Option.match({
122 onNone: () => [],
123 onSome: (value) => [`${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
124 }),
125 ),
126];
127​
128const startMarker = (name: string) => `__T3CODE_ENV_${name}_START__`;
129const endMarker = (name: string) => `__T3CODE_ENV_${name}_END__`;
130​
131const capturePosixEnvironmentCommand = (names: ReadonlyArray<string>) =>
132 names
133 .map((name) => {
134 return [
135 `printf '%s\\n' '${startMarker(name)}'`,
136 `printenv ${name} || true`,
137 `printf '%s\\n' '${endMarker(name)}'`,
138 ].join("; ");
139 })
140 .join("; ");
141​
142const captureWindowsEnvironmentCommand = (names: ReadonlyArray<string>) =>
143 [
144 "$ErrorActionPreference = 'Stop'",
145 ...names.flatMap((name) => {
146 return [
147 `Write-Output '${startMarker(name)}'`,
148 `$value = [Environment]::GetEnvironmentVariable('${name}')`,
149 "if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }",
150 `Write-Output '${endMarker(name)}'`,
151 ];
152 }),
153 ].join("; ");
154​
155const extractEnvironment = (output: string, names: ReadonlyArray<string>): EnvironmentPatch => {
156 const environment: EnvironmentPatch = {};
157​
158 for (const name of names) {
159 const start = output.indexOf(startMarker(name));
160 if (start === -1) continue;
161​
162 const valueStart = start + startMarker(name).length;
163 const end = output.indexOf(endMarker(name), valueStart);
164 if (end === -1) continue;
165​
166 const value = output
167 .slice(valueStart, end)
168 .replace(/^\r?\n/, "")
169 .replace(/\r?\n$/, "");
170 if (value.length > 0) {
171 environment[name] = value;
172 }
173 }
174​
175 return environment;
176};
177​
178const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")(function* (input: {
179 readonly command: string;
180 readonly args: ReadonlyArray<string>;
181 readonly timeout: Duration.Duration;
182 readonly shell?: boolean;
183}): Effect.fn.Return<string, never, ChildProcessSpawner.ChildProcessSpawner> {
184 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
185 return yield* spawner
186 .string(
187 ChildProcess.make(input.command, input.args, {
188 shell: input.shell ?? false,
189 stdin: "ignore",
190 stdout: "pipe",
191 stderr: "pipe",
192 killSignal: "SIGTERM",
193 forceKillAfter: PROCESS_TERMINATE_GRACE,
194 }),
195 )
196 .pipe(
197 Effect.timeoutOption(input.timeout),
198 Effect.map(Option.getOrElse(() => "")),
199 Effect.orElseSucceed(() => ""),
200 );
201});
202​
203const readLoginShellEnvironment = (
204 shell: string,
205 names: ReadonlyArray<string>,
206): Effect.Effect<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> =>
207 names.length === 0
208 ? Effect.succeed({})
209 : runCommandOutput({
210 command: shell,
211 args: ["-ilc", capturePosixEnvironmentCommand(names)],
212 timeout: LOGIN_SHELL_TIMEOUT,
213 }).pipe(Effect.map((output) => extractEnvironment(output, names)));
214​
215const readLaunchctlPath: Effect.Effect<
216 Option.Option<string>,
217 never,
218 ChildProcessSpawner.ChildProcessSpawner
219> = runCommandOutput({
220 command: "/bin/launchctl",
221 args: ["getenv", "PATH"],
222 timeout: LAUNCHCTL_TIMEOUT,
223}).pipe(Effect.map(trimNonEmpty));
224​
225const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")(
226 function* (
227 names: ReadonlyArray<string>,
228 options: WindowsProbeOptions,
229 ): Effect.fn.Return<EnvironmentPatch, never, ChildProcessSpawner.ChildProcessSpawner> {
230 if (names.length === 0) return {};
231​
232 const args = [
233 "-NoLogo",
234 ...(options.loadProfile ? ([] as const) : (["-NoProfile"] as const)),
235 "-NonInteractive",
236 "-Command",
237 captureWindowsEnvironmentCommand(names),
238 ];
239​
240 for (const command of WINDOWS_SHELL_CANDIDATES) {
241 const output = yield* runCommandOutput({
242 command,
243 args,
244 timeout: LOGIN_SHELL_TIMEOUT,
245 });
246 const environment = extractEnvironment(output, names);
247 if (Object.keys(environment).length > 0) {
248 return environment;
249 }
250 }
251​
252 return {};
253 },
254);
255​
256const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
257 function* (
258 config: ShellEnvironmentConfig,
259 ): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
260 const noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
261 const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
262 loadProfile: true,
263 });
264 const mergedPath = mergePaths("win32", [
265 trimNonEmpty(profile.PATH),
266 trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
267 trimNonEmpty(noProfile.PATH),
268 readEnvPath(config.env),
269 ]);
270​
271 if (Option.isSome(mergedPath)) {
272 config.env.PATH = mergedPath.value;
273 }
274 if (!config.env.FNM_DIR && profile.FNM_DIR) {
275 config.env.FNM_DIR = profile.FNM_DIR;
276 }
277 if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
278 config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
279 }
280 },
281);
282​
283const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
284 function* (
285 config: ShellEnvironmentConfig,
286 ): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
287 const shellEnvironment: EnvironmentPatch = {};
288​
289 for (const shell of listLoginShellCandidates(config)) {
290 Object.assign(
291 shellEnvironment,
292 yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
293 );
294 if (shellEnvironment.PATH) break;
295 }
296​
297 const launchctlPath =
298 config.platform === "darwin" && !shellEnvironment.PATH
299 ? yield* readLaunchctlPath
300 : Option.none<string>();
301 const mergedPath = mergePaths(config.platform, [
302 trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
303 readEnvPath(config.env),
304 ]);
305​
306 if (Option.isSome(mergedPath)) {
307 config.env.PATH = mergedPath.value;
308 }
309 if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
310 config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
311 }
312​
313 for (const name of [
314 "HOMEBREW_PREFIX",
315 "HOMEBREW_CELLAR",
316 "HOMEBREW_REPOSITORY",
317 "XDG_CONFIG_HOME",
318 "XDG_DATA_HOME",
319 ] as const) {
320 if (!config.env[name] && shellEnvironment[name]) {
321 config.env[name] = shellEnvironment[name];
322 }
323 }
324 },
325);
326​
327const installShellEnvironment = (
328 config: ShellEnvironmentConfig,
329): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
330 if (config.platform === "win32") {
331 return installWindowsEnvironment(config);
332 }
333 if (config.platform === "darwin" || config.platform === "linux") {
334 return installPosixEnvironment(config);
335 }
336 return Effect.void;
337};
338​
339export const layer = Layer.effect(
340 DesktopShellEnvironment,
341 Effect.gen(function* () {
342 const environment = yield* DesktopEnvironment.DesktopEnvironment;
343 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
344 return DesktopShellEnvironment.of({
345 installIntoProcess: installShellEnvironment({
346 env: process.env,
347 platform: environment.platform,
348 userShell: Option.none(),
349 }).pipe(
350 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
351 Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
352 ),
353 });
354 }),
355);