Open History to see the last commit
1// @effect-diagnostics-next-line nodeBuiltinImport:off -- FileSystem.access has no execute check.
2import * as NodeFSP from "node:fs/promises";
3
4import type { DesktopCliCommandState } from "@t3tools/contracts";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import * as Context from "effect/Context";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import * as ChildProcess from "effect/process/ChildProcess";
14import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15
16import * as DesktopCliShim from "./DesktopCliShim.ts";
17import * as DesktopEnvironment from "./DesktopEnvironment.ts";
18
19export class DesktopCliCommandError extends Schema.TaggedError<DesktopCliCommandError>()(
20 "DesktopCliCommandError",
21 { message: Schema.String },
22) {}
23
24const unixCandidates = (home: string, platform: NodeJS.Platform) =>
25 platform === "darwin"
26 ? ["/opt/homebrew/bin", "/usr/local/bin", `${home}/.local/bin`, `${home}/bin`]
27 : [`${home}/.local/bin`, `${home}/bin`];
28
29const pathEntries = (value: string | undefined, separator: string) =>
30 (value ?? "").split(separator).filter((entry) => entry.length > 0);
31
32const sameWindowsPath = (left: string, right: string) =>
33 left.replace(/[\\/]+$/, "").toLowerCase() === right.replace(/[\\/]+$/, "").toLowerCase();
34
35// Preserve REG_EXPAND_SZ and %VAR% expansion; notify Explorer with WM_SETTINGCHANGE.
36// Failed reads must exit nonzero to prevent replacing PATH wholesale.
37const WINDOWS_USER_PATH_SCRIPT = `
38$ErrorActionPreference = 'Stop'
39if ($env:T3_SET -eq '1') {
40 $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
41 $kind = [Microsoft.Win32.RegistryValueKind]::ExpandString
42 if ($key.GetValueNames() -contains 'Path' -and $key.GetValueKind('Path') -eq 'String') {
43 $kind = [Microsoft.Win32.RegistryValueKind]::String
44 }
45 $key.SetValue('Path', $env:T3_PATH, $kind)
46 Add-Type -Namespace T3 -Name Env -MemberDefinition '[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern System.IntPtr SendMessageTimeout(System.IntPtr hWnd, uint Msg, System.UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out System.UIntPtr lpdwResult);'
47 $result = [System.UIntPtr]::Zero
48 [void][T3.Env]::SendMessageTimeout([System.IntPtr]0xffff, 0x1A, [System.UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$result)
49} else {
50 $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment')
51 $value = if ($key) { $key.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } else { '' }
52 [Console]::Out.Write([Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes([string]$value)))
53}
54`;
55
56export class DesktopCliCommand extends Context.Service<
57 DesktopCliCommand,
58 {
59 readonly state: Effect.Effect<DesktopCliCommandState>;
60 readonly install: Effect.Effect<DesktopCliCommandState, DesktopCliCommandError>;
61 readonly uninstall: Effect.Effect<DesktopCliCommandState, DesktopCliCommandError>;
62 }
63>()("@t3tools/desktop/app/DesktopCliCommand") {}
64
65export const make = Effect.gen(function* () {
66 const environment = yield* DesktopEnvironment.DesktopEnvironment;
67 const fs = yield* FileSystem.FileSystem;
68 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
69 // Read the live env: shell discovery patches PATH after startup, and Windows variable
70 // names are case-insensitive only on process.env, not on Config's copy of it.
71 const env = yield* HostProcess.Environment;
72 const path = environment.path;
73 const windows = environment.platform === "win32";
74 const launcher = DesktopCliShim.launcherPath(environment);
75 const binDirectory = path.dirname(launcher);
76 const ownedPathMarker = path.join(environment.stateDir, "cli-command-path-entry");
77
78 const fail = (message: string) => new DesktopCliCommandError({ message });
79 const exists = (target: string) => fs.exists(target).pipe(Effect.orElseSucceed(() => false));
80 const writableDirectory = (directory: string) =>
81 fs.access(directory, { writable: true }).pipe(
82 Effect.as(true),
83 Effect.orElseSucceed(() => false),
84 );
85
86 const isOurLink = Effect.fn("DesktopCliCommand.isOurLink")(
87 function* (link: string) {
88 yield* fs.readLink(link);
89 // The launcher is a few KB; never read a large binary another `t3` links to.
90 const info = yield* fs.stat(link);
91 if (info.type !== "File" || Number(info.size) > 16_384) return false;
92 const content = yield* fs.readFileString(link);
93 return content.includes(DesktopCliShim.MARKER);
94 },
95 Effect.orElseSucceed(() => false),
96 );
97
98 // PATH can reach the regular launcher directly; removal still requires isOurLink.
99 const runsOurLauncher = Effect.fn("DesktopCliCommand.runsOurLauncher")(
100 function* (candidate: string) {
101 if (yield* isOurLink(candidate)) return true;
102 const [resolved, ours] = yield* Effect.all([fs.realPath(candidate), fs.realPath(launcher)]);
103 if (resolved !== ours) return false;
104 const info = yield* fs.stat(candidate);
105 if (info.type !== "File" || Number(info.size) > 16_384) return false;
106 return (yield* fs.readFileString(candidate)).includes(DesktopCliShim.MARKER);
107 },
108 Effect.orElseSucceed(() => false),
109 );
110
111 const powershell = (overrides: Record<string, string>) =>
112 Effect.scoped(
113 Effect.gen(function* () {
114 const root = env.SystemRoot ?? env.WINDIR;
115 const handle = yield* spawner.spawn(
116 ChildProcess.make(
117 root ? `${root}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe` : "powershell.exe",
118 ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", WINDOWS_USER_PATH_SCRIPT],
119 { stdin: "ignore", stderr: "ignore", env: overrides, extendEnv: true },
120 ),
121 );
122 const [stdout, exitCode] = yield* Effect.all(
123 [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
124 { concurrency: "unbounded" },
125 );
126 if (exitCode !== 0) return yield* Effect.fail(`powershell exited with ${exitCode}`);
127 return stdout;
128 }),
129 );
130 const readUserPath = powershell({}).pipe(
131 Effect.map((encoded) => Buffer.from(encoded.trim(), "base64").toString("utf8")),
132 Effect.mapError(() => fail("Could not read your PATH, so it was left unchanged.")),
133 );
134 const writeUserPath = (value: string) =>
135 powershell({ T3_SET: "1", T3_PATH: value }).pipe(
136 Effect.asVoid,
137 Effect.mapError(() => fail("Could not update your PATH.")),
138 );
139
140 const isExecutableFile = Effect.fn("DesktopCliCommand.isExecutableFile")(
141 function* (target: string) {
142 if ((yield* fs.stat(target)).type !== "File") return false;
143 yield* Effect.tryPromise({
144 try: () => NodeFSP.access(target, NodeFSP.constants.X_OK),
145 catch: () => fail(`${target} is not executable.`),
146 });
147 return true;
148 },
149 Effect.orElseSucceed(() => false),
150 );
151
152 const firstOnPath = Effect.gen(function* () {
153 for (const directory of pathEntries(env.PATH, ":")) {
154 const candidate = path.join(directory, "t3");
155 if (yield* isExecutableFile(candidate)) return Option.some(candidate);
156 }
157 return Option.none<string>();
158 });
159
160 const foreignFirstOnPath = Effect.gen(function* () {
161 if (windows) return Option.none<string>();
162 const first = yield* firstOnPath;
163 if (Option.isNone(first) || (yield* runsOurLauncher(first.value))) return Option.none<string>();
164 return first;
165 });
166
167 const installedAt = Effect.gen(function* () {
168 if (windows) {
169 if (!(yield* exists(ownedPathMarker))) return Option.none<string>();
170 const entries = pathEntries(yield* readUserPath, ";");
171 return entries.some((entry) => sameWindowsPath(entry, binDirectory))
172 ? Option.some(launcher)
173 : Option.none<string>();
174 }
175 for (const directory of unixCandidates(environment.homeDirectory, environment.platform)) {
176 const link = path.join(directory, "t3");
177 if (yield* isOurLink(link)) return Option.some(link);
178 }
179 return Option.none<string>();
180 });
181
182 const state: DesktopCliCommand["Service"]["state"] = Effect.gen(function* () {
183 if (!environment.isPackaged) {
184 return { supported: false, installedPath: null, onPath: false, launcherPath: null } as const;
185 }
186 const launcherPath = (yield* exists(launcher)) ? launcher : null;
187 const installed = yield* installedAt;
188 const shadowedBy = yield* foreignFirstOnPath;
189 const shadow = Option.isSome(shadowedBy) ? { shadowedBy: shadowedBy.value } : {};
190 const first = yield* firstOnPath;
191 const onPath = windows
192 ? Option.isSome(installed)
193 : Option.isSome(first) && (yield* runsOurLauncher(first.value));
194 return {
195 supported: true,
196 installedPath: Option.getOrNull(installed),
197 onPath,
198 launcherPath,
199 ...shadow,
200 };
201 }).pipe(
202 Effect.orElseSucceed(() => ({
203 supported: false,
204 installedPath: null,
205 onPath: false,
206 launcherPath: null,
207 })),
208 );
209
210 const ensureLauncher = DesktopCliShim.install.pipe(
211 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
212 Effect.provideService(FileSystem.FileSystem, fs),
213 Effect.flatMap(
214 Option.match({
215 onNone: () => Effect.fail(fail(`Could not set up the t3 launcher at ${launcher}.`)),
216 onSome: () => Effect.void,
217 }),
218 ),
219 );
220
221 const install: DesktopCliCommand["Service"]["install"] = Effect.gen(function* () {
222 if (!environment.isPackaged) return yield* fail("The t3 command needs an installed app.");
223 yield* ensureLauncher;
224 if (windows) {
225 const entries = pathEntries(yield* readUserPath, ";");
226 if (!entries.some((entry) => sameWindowsPath(entry, binDirectory))) {
227 yield* writeUserPath([...entries, binDirectory].join(";"));
228 yield* fs
229 .writeFileString(ownedPathMarker, `${binDirectory}\n`)
230 .pipe(Effect.mapError(() => fail("Added t3 to your PATH but could not record it.")));
231 }
232 return yield* state;
233 }
234 const existing = yield* installedAt;
235 if (Option.isSome(existing)) {
236 const target = yield* fs.readLink(existing.value).pipe(Effect.option);
237 if (Option.getOrUndefined(target) === launcher) return yield* state;
238 yield* fs
239 .remove(existing.value)
240 .pipe(Effect.mapError(() => fail(`Could not replace ${existing.value}.`)));
241 }
242 const shadowedBy = yield* foreignFirstOnPath;
243 if (Option.isSome(shadowedBy)) {
244 return yield* fail(
245 `Another t3 at ${shadowedBy.value} runs first in a new terminal. Remove it, or run the launcher directly at ${launcher}.`,
246 );
247 }
248 const onPath = pathEntries(env.PATH, ":");
249 const candidates = unixCandidates(environment.homeDirectory, environment.platform);
250 for (const directory of [
251 ...candidates.filter((candidate) => onPath.includes(candidate)),
252 ...candidates.filter((candidate) => !onPath.includes(candidate)),
253 ]) {
254 const link = path.join(directory, "t3");
255 const created = (yield* exists(directory))
256 ? yield* writableDirectory(directory)
257 : yield* fs.makeDirectory(directory, { recursive: true }).pipe(
258 Effect.as(true),
259 Effect.orElseSucceed(() => false),
260 );
261 if (!created) continue;
262 const linked = yield* fs.symlink(launcher, link).pipe(
263 Effect.as(true),
264 Effect.orElseSucceed(() => false),
265 );
266 if (linked) return yield* state;
267 }
268 return yield* fail(
269 `Another t3 command is already installed, or no folder on your PATH is writable. Run the launcher directly at ${launcher}.`,
270 );
271 }).pipe(Effect.withSpan("desktop.cliCommand.install"));
272
273 const uninstall: DesktopCliCommand["Service"]["uninstall"] = Effect.gen(function* () {
274 if (windows) {
275 if (yield* exists(ownedPathMarker)) {
276 const entries = pathEntries(yield* readUserPath, ";");
277 const kept = entries.filter((entry) => !sameWindowsPath(entry, binDirectory));
278 if (kept.length !== entries.length) yield* writeUserPath(kept.join(";"));
279 yield* fs.remove(ownedPathMarker).pipe(Effect.ignore);
280 }
281 return yield* state;
282 }
283 for (const directory of unixCandidates(environment.homeDirectory, environment.platform)) {
284 const link = path.join(directory, "t3");
285 if (yield* isOurLink(link)) {
286 yield* fs.remove(link).pipe(Effect.mapError(() => fail(`Could not remove ${link}.`)));
287 }
288 }
289 return yield* state;
290 }).pipe(Effect.withSpan("desktop.cliCommand.uninstall"));
291
292 return DesktopCliCommand.of({ state, install, uninstall });
293});
294
295export const layer = Layer.effect(DesktopCliCommand, make);