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

DesktopShellEnvironment.ts

356 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>()("t3/desktop/ShellEnvironment") {}
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.catch(() => Effect.succeed("")),
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 shell: true,
245 timeout: LOGIN_SHELL_TIMEOUT,
246 });
247 const environment = extractEnvironment(output, names);
248 if (Object.keys(environment).length > 0) {
249 return environment;
250 }
251 }
252​
253 return {};
254 },
255);
256​
257const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWindowsEnvironment")(
258 function* (
259 config: ShellEnvironmentConfig,
260 ): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
261 const noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
262 const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
263 loadProfile: true,
264 });
265 const mergedPath = mergePaths("win32", [
266 trimNonEmpty(profile.PATH),
267 trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
268 trimNonEmpty(noProfile.PATH),
269 readEnvPath(config.env),
270 ]);
271​
272 if (Option.isSome(mergedPath)) {
273 config.env.PATH = mergedPath.value;
274 }
275 if (!config.env.FNM_DIR && profile.FNM_DIR) {
276 config.env.FNM_DIR = profile.FNM_DIR;
277 }
278 if (!config.env.FNM_MULTISHELL_PATH && profile.FNM_MULTISHELL_PATH) {
279 config.env.FNM_MULTISHELL_PATH = profile.FNM_MULTISHELL_PATH;
280 }
281 },
282);
283​
284const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
285 function* (
286 config: ShellEnvironmentConfig,
287 ): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
288 const shellEnvironment: EnvironmentPatch = {};
289​
290 for (const shell of listLoginShellCandidates(config)) {
291 Object.assign(
292 shellEnvironment,
293 yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES),
294 );
295 if (shellEnvironment.PATH) break;
296 }
297​
298 const launchctlPath =
299 config.platform === "darwin" && !shellEnvironment.PATH
300 ? yield* readLaunchctlPath
301 : Option.none<string>();
302 const mergedPath = mergePaths(config.platform, [
303 trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)),
304 readEnvPath(config.env),
305 ]);
306​
307 if (Option.isSome(mergedPath)) {
308 config.env.PATH = mergedPath.value;
309 }
310 if (!config.env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
311 config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
312 }
313​
314 for (const name of [
315 "HOMEBREW_PREFIX",
316 "HOMEBREW_CELLAR",
317 "HOMEBREW_REPOSITORY",
318 "XDG_CONFIG_HOME",
319 "XDG_DATA_HOME",
320 ] as const) {
321 if (!config.env[name] && shellEnvironment[name]) {
322 config.env[name] = shellEnvironment[name];
323 }
324 }
325 },
326);
327​
328const installShellEnvironment = (
329 config: ShellEnvironmentConfig,
330): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
331 if (config.platform === "win32") {
332 return installWindowsEnvironment(config);
333 }
334 if (config.platform === "darwin" || config.platform === "linux") {
335 return installPosixEnvironment(config);
336 }
337 return Effect.void;
338};
339​
340export const layer = Layer.effect(
341 DesktopShellEnvironment,
342 Effect.gen(function* () {
343 const environment = yield* DesktopEnvironment.DesktopEnvironment;
344 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
345 return DesktopShellEnvironment.of({
346 installIntoProcess: installShellEnvironment({
347 env: process.env,
348 platform: environment.platform,
349 userShell: Option.none(),
350 }).pipe(
351 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
352 Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
353 ),
354 });
355 }),
356);