Open History to see the last commit
1import type { DesktopCliCommandState } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import * as Stream from "effect/Stream";
9import * as ChildProcess from "effect/process/ChildProcess";
10import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
11
12import * as DesktopCliShim from "./DesktopCliShim.ts";
13import * as DesktopEnvironment from "./DesktopEnvironment.ts";
14
15export class DesktopCliCommandError extends Schema.TaggedError<DesktopCliCommandError>()(
16 "DesktopCliCommandError",
17 { message: Schema.String },
18) {}
19
20const unixCandidates = (home: string, platform: NodeJS.Platform) =>
21 platform === "darwin"
22 ? ["/opt/homebrew/bin", "/usr/local/bin", `${home}/.local/bin`, `${home}/bin`]
23 : [`${home}/.local/bin`, `${home}/bin`];
24
25const pathEntries = (value: string | undefined, separator: string) =>
26 (value ?? "").split(separator).filter((entry) => entry.length > 0);
27
28const sameWindowsPath = (left: string, right: string) =>
29 left.replace(/[\\/]+$/, "").toLowerCase() === right.replace(/[\\/]+$/, "").toLowerCase();
30
31/**
32 * Reads, or with `T3_SET` set writes, the user's PATH in the registry, keeping
33 * `%VAR%` entries unexpanded. Writes keep REG_EXPAND_SZ (Windows' default for
34 * PATH; `SetEnvironmentVariable` would store REG_SZ and break every `%VAR%`
35 * entry), then broadcast WM_SETTINGCHANGE so Explorer and the terminals it
36 * opens see the change. A failed read exits nonzero rather than reading as
37 * empty, so a write never replaces the user's PATH wholesale.
38 */
39const WINDOWS_USER_PATH_SCRIPT = `
40$ErrorActionPreference = 'Stop'
41if ($env:T3_SET -eq '1') {
42 $key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
43 $kind = [Microsoft.Win32.RegistryValueKind]::ExpandString
44 if ($key.GetValueNames() -contains 'Path' -and $key.GetValueKind('Path') -eq 'String') {
45 $kind = [Microsoft.Win32.RegistryValueKind]::String
46 }
47 $key.SetValue('Path', $env:T3_PATH, $kind)
48 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);'
49 $result = [System.UIntPtr]::Zero
50 [void][T3.Env]::SendMessageTimeout([System.IntPtr]0xffff, 0x1A, [System.UIntPtr]::Zero, 'Environment', 2, 5000, [ref]$result)
51} else {
52 $key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment')
53 $value = if ($key) { $key.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } else { '' }
54 [Console]::Out.Write([Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes([string]$value)))
55}
56`;
57
58export class DesktopCliCommand extends Context.Service<
59 DesktopCliCommand,
60 {
61 readonly state: Effect.Effect<DesktopCliCommandState>;
62 readonly install: Effect.Effect<DesktopCliCommandState, DesktopCliCommandError>;
63 readonly uninstall: Effect.Effect<DesktopCliCommandState, DesktopCliCommandError>;
64 }
65>()("@t3tools/desktop/app/DesktopCliCommand") {}
66
67/** @public Service construction is part of the canonical Effect module API. */
68export const make = Effect.gen(function* () {
69 const environment = yield* DesktopEnvironment.DesktopEnvironment;
70 const fs = yield* FileSystem.FileSystem;
71 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
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 const powershell = (env: Record<string, string>) =>
99 Effect.scoped(
100 Effect.gen(function* () {
101 const root = process.env.SystemRoot ?? process.env.WINDIR;
102 const handle = yield* spawner.spawn(
103 ChildProcess.make(
104 root ? `${root}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe` : "powershell.exe",
105 ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", WINDOWS_USER_PATH_SCRIPT],
106 { stdin: "ignore", stderr: "ignore", env, extendEnv: true },
107 ),
108 );
109 const [stdout, exitCode] = yield* Effect.all(
110 [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
111 { concurrency: "unbounded" },
112 );
113 if (exitCode !== 0) return yield* Effect.fail(`powershell exited with ${exitCode}`);
114 return stdout;
115 }),
116 );
117 const readUserPath = powershell({}).pipe(
118 Effect.map((encoded) => Buffer.from(encoded.trim(), "base64").toString("utf8")),
119 Effect.mapError(() => fail("Could not read your PATH, so it was left unchanged.")),
120 );
121 const writeUserPath = (value: string) =>
122 powershell({ T3_SET: "1", T3_PATH: value }).pipe(
123 Effect.asVoid,
124 Effect.mapError(() => fail("Could not update your PATH.")),
125 );
126
127 const firstOnPath = Effect.gen(function* () {
128 for (const directory of pathEntries(process.env.PATH, ":")) {
129 const candidate = path.join(directory, "t3");
130 if (yield* exists(candidate)) return Option.some(candidate);
131 }
132 return Option.none<string>();
133 });
134
135 const foreignFirstOnPath = Effect.gen(function* () {
136 if (windows) return Option.none<string>();
137 const first = yield* firstOnPath;
138 if (Option.isNone(first) || (yield* isOurLink(first.value))) return Option.none<string>();
139 return first;
140 });
141
142 const installedAt = Effect.gen(function* () {
143 if (windows) {
144 if (!(yield* exists(ownedPathMarker))) return Option.none<string>();
145 const entries = pathEntries(yield* readUserPath, ";");
146 return entries.some((entry) => sameWindowsPath(entry, binDirectory))
147 ? Option.some(launcher)
148 : Option.none<string>();
149 }
150 for (const directory of unixCandidates(environment.homeDirectory, environment.platform)) {
151 const link = path.join(directory, "t3");
152 if (yield* isOurLink(link)) return Option.some(link);
153 }
154 return Option.none<string>();
155 });
156
157 const state: DesktopCliCommand["Service"]["state"] = Effect.gen(function* () {
158 if (!environment.isPackaged) {
159 return { supported: false, installedPath: null, onPath: false } as const;
160 }
161 const installed = yield* installedAt;
162 const shadowedBy = yield* foreignFirstOnPath;
163 const shadow = Option.isSome(shadowedBy) ? { shadowedBy: shadowedBy.value } : {};
164 if (Option.isNone(installed)) {
165 return { supported: true, installedPath: null, onPath: false, ...shadow };
166 }
167 const first = yield* firstOnPath;
168 const onPath = windows || (Option.isSome(first) && (yield* isOurLink(first.value)));
169 return { supported: true, installedPath: installed.value, onPath, ...shadow };
170 }).pipe(Effect.orElseSucceed(() => ({ supported: false, installedPath: null, onPath: false })));
171
172 const ensureLauncher = DesktopCliShim.install.pipe(
173 Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
174 Effect.provideService(FileSystem.FileSystem, fs),
175 Effect.flatMap(
176 Option.match({
177 onNone: () => Effect.fail(fail(`Could not set up the t3 launcher at ${launcher}.`)),
178 onSome: () => Effect.void,
179 }),
180 ),
181 );
182
183 const install: DesktopCliCommand["Service"]["install"] = Effect.gen(function* () {
184 if (!environment.isPackaged) return yield* fail("The t3 command needs an installed app.");
185 yield* ensureLauncher;
186 if (windows) {
187 const entries = pathEntries(yield* readUserPath, ";");
188 if (!entries.some((entry) => sameWindowsPath(entry, binDirectory))) {
189 yield* writeUserPath([...entries, binDirectory].join(";"));
190 yield* fs
191 .writeFileString(ownedPathMarker, `${binDirectory}\n`)
192 .pipe(Effect.mapError(() => fail("Added t3 to your PATH but could not record it.")));
193 }
194 return yield* state;
195 }
196 const existing = yield* installedAt;
197 if (Option.isSome(existing)) {
198 const target = yield* fs.readLink(existing.value).pipe(Effect.option);
199 if (Option.getOrUndefined(target) === launcher) return yield* state;
200 yield* fs
201 .remove(existing.value)
202 .pipe(Effect.mapError(() => fail(`Could not replace ${existing.value}.`)));
203 }
204 const shadowedBy = yield* foreignFirstOnPath;
205 if (Option.isSome(shadowedBy)) {
206 return yield* fail(
207 `Another t3 at ${shadowedBy.value} runs first in a new terminal. Remove it, or run the launcher directly at ${launcher}.`,
208 );
209 }
210 const onPath = pathEntries(process.env.PATH, ":");
211 const candidates = unixCandidates(environment.homeDirectory, environment.platform);
212 for (const directory of [
213 ...candidates.filter((candidate) => onPath.includes(candidate)),
214 ...candidates.filter((candidate) => !onPath.includes(candidate)),
215 ]) {
216 const link = path.join(directory, "t3");
217 const created = (yield* exists(directory))
218 ? yield* writableDirectory(directory)
219 : yield* fs.makeDirectory(directory, { recursive: true }).pipe(
220 Effect.as(true),
221 Effect.orElseSucceed(() => false),
222 );
223 if (!created) continue;
224 const linked = yield* fs.symlink(launcher, link).pipe(
225 Effect.as(true),
226 Effect.orElseSucceed(() => false),
227 );
228 if (linked) return yield* state;
229 }
230 return yield* fail(
231 `Another t3 command is already installed, or no folder on your PATH is writable. Run the launcher directly at ${launcher}.`,
232 );
233 }).pipe(Effect.withSpan("desktop.cliCommand.install"));
234
235 const uninstall: DesktopCliCommand["Service"]["uninstall"] = Effect.gen(function* () {
236 if (windows) {
237 if (yield* exists(ownedPathMarker)) {
238 const entries = pathEntries(yield* readUserPath, ";");
239 const kept = entries.filter((entry) => !sameWindowsPath(entry, binDirectory));
240 if (kept.length !== entries.length) yield* writeUserPath(kept.join(";"));
241 yield* fs.remove(ownedPathMarker).pipe(Effect.ignore);
242 }
243 return yield* state;
244 }
245 for (const directory of unixCandidates(environment.homeDirectory, environment.platform)) {
246 const link = path.join(directory, "t3");
247 if (yield* isOurLink(link)) {
248 yield* fs.remove(link).pipe(Effect.mapError(() => fail(`Could not remove ${link}.`)));
249 }
250 }
251 return yield* state;
252 }).pipe(Effect.withSpan("desktop.cliCommand.uninstall"));
253
254 return DesktopCliCommand.of({ state, install, uninstall });
255});
256
257export const layer = Layer.effect(DesktopCliCommand, make);