Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import {
3 listLoginShellCandidates,
4 mergePathEntries,
5 readEnvironmentFromLoginShell,
6 readPathFromLaunchctl,
7 resolveWindowsEnvironment,
8 setWindowsPath,
9} from "@t3tools/shared/shell";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Path from "effect/Path";
13import * as NodeOS from "node:os";
14
15function logPathHydrationWarning(message: string, error?: unknown): void {
16 process.stderr.write(
17 `[server] ${message} ${error instanceof Error ? error.message : (error ?? "")}\n`,
18 );
19}
20
21function hydratePosixPath(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): void {
22 let shellEnvironment: Partial<Record<string, string>> = {};
23 for (const shell of listLoginShellCandidates(platform, env.SHELL)) {
24 try {
25 // mise's record of the PATH entries it added. It must travel with the
26 // shell's PATH, or `mise x` can rebuild PATH behind a same-named wrapper
27 // (`exec mise x claude -- claude`) that then re-runs itself forever.
28 shellEnvironment = readEnvironmentFromLoginShell(shell, ["PATH", "__MISE_DIFF", "JAVA_HOME"]);
29 } catch (error) {
30 logPathHydrationWarning(`Failed to read PATH from login shell ${shell}.`, error);
31 }
32
33 if (shellEnvironment.PATH) break;
34 }
35
36 const shellPath = shellEnvironment.PATH;
37 const launchctlPath = platform === "darwin" && !shellPath ? readPathFromLaunchctl() : undefined;
38 const mergedPath = mergePathEntries(shellPath ?? launchctlPath, env.PATH, platform);
39 if (mergedPath) {
40 env.PATH = mergedPath;
41 }
42 if (shellPath && shellEnvironment.__MISE_DIFF) {
43 env.__MISE_DIFF = shellEnvironment.__MISE_DIFF;
44 }
45 // Android SDK tools are Java programs. A keg-only JDK (Homebrew's openjdk)
46 // is only reachable through the JAVA_HOME the shell profile sets.
47 if (!env.JAVA_HOME && shellEnvironment.JAVA_HOME) {
48 env.JAVA_HOME = shellEnvironment.JAVA_HOME;
49 }
50}
51
52export function hydratePosixHome(
53 env: NodeJS.ProcessEnv,
54 resolveHomeDir = () => NodeOS.userInfo().homedir,
55): void {
56 if ((env.HOME?.trim() ?? "").length > 0) return;
57
58 const homeDir = resolveHomeDir();
59 if (homeDir.length > 0) {
60 env.HOME = homeDir;
61 }
62}
63
64export const fixPath = Effect.fn("fixPath")(function* (options?: {
65 readonly shellEnvironmentPrepared?: boolean | undefined;
66}): Effect.fn.Return<void, never, FileSystem.FileSystem | Path.Path> {
67 const platform = yield* HostProcess.Platform;
68 const env = yield* HostProcess.Environment;
69
70 if (platform === "win32") {
71 // The desktop already ran both PowerShell probes into the env this child
72 // extends. Repeating them here costs seconds of startup on Windows.
73 if (options?.shellEnvironmentPrepared === true) return;
74 const repairedEnvironment = yield* resolveWindowsEnvironment(env).pipe(
75 Effect.catchDefect((defect) =>
76 Effect.sync(() => {
77 logPathHydrationWarning("Failed to hydrate PATH from the user environment.", defect);
78 return {} as Partial<NodeJS.ProcessEnv>;
79 }),
80 ),
81 );
82 for (const [key, value] of Object.entries(repairedEnvironment)) {
83 if (value === undefined) continue;
84 if (key === "PATH") {
85 setWindowsPath(env, value);
86 } else {
87 env[key] = value;
88 }
89 }
90 return;
91 }
92
93 if (platform !== "darwin" && platform !== "linux") return;
94
95 yield* Effect.sync(() => hydratePosixHome(env)).pipe(
96 Effect.catchDefect((defect) =>
97 Effect.sync(() => {
98 logPathHydrationWarning("Failed to hydrate HOME from the user account.", defect);
99 }),
100 ),
101 );
102 if (options?.shellEnvironmentPrepared === true) return;
103 yield* Effect.sync(() => hydratePosixPath(env, platform)).pipe(
104 Effect.catchDefect((defect) =>
105 Effect.sync(() => {
106 logPathHydrationWarning("Failed to hydrate PATH from the user environment.", defect);
107 }),
108 ),
109 );
110});
111
112export const expandHomePath = Effect.fn(function* (input: string) {
113 const { join } = yield* Path.Path;
114 const home = yield* HostProcess.HomeDirectory;
115 if (input === "~") {
116 return home;
117 }
118 if (input.startsWith("~/") || input.startsWith("~\\")) {
119 return join(home, input.slice(2));
120 }
121 return input;
122});
123
124export const resolveBaseDir = Effect.fn(function* (raw: string | undefined) {
125 const { join, resolve } = yield* Path.Path;
126 if (!raw || raw.trim().length === 0) {
127 return join(yield* HostProcess.HomeDirectory, ".t3");
128 }
129 return resolve(yield* expandHomePath(raw.trim()));
130});