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