Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import { pathSetupCommand, resolveCommandPath } from "@t3tools/shared/shell";
3import * as Console from "effect/Console";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import { Command, Prompt } from "effect/cli";
11import * as ChildProcess from "effect/process/ChildProcess";
12import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13
14import packageJson from "../../package.json" with { type: "json" };
15import {
16 generatedWindowsShimTarget,
17 isVersionExecutable,
18 readPosixLauncherTarget,
19 recordPinnedRuntimeLauncher,
20 writePosixLauncher,
21} from "../cloud/pinnedRuntime.ts";
22import { detectCliRunner, resolveCliCommand, resolveEntryPath } from "./invocation.ts";
23
24export class CliInstallError extends Schema.TaggedError<CliInstallError>()("CliInstallError", {
25 reason: Schema.String,
26 cause: Schema.optional(Schema.Defect()),
27}) {
28 override get message(): string {
29 return this.reason;
30 }
31}
32
33/** `<T3 home>/runtime/versions/<version>/t3`: the layout the install scripts and npm launcher share. */
34const standaloneRuntime = Effect.gen(function* () {
35 const path = yield* Path.Path;
36 if (!(yield* HostProcess.IsExecutable)) return Option.none();
37 const executable = yield* HostProcess.ExecutablePath;
38 const versionsDir = path.dirname(path.dirname(executable));
39 const runtimeDir = path.dirname(versionsDir);
40 if (path.basename(versionsDir) !== "versions" || path.basename(runtimeDir) !== "runtime") {
41 return Option.none();
42 }
43 return Option.some({ executable, versionsDir, runtimeDir });
44});
45
46/** Installs this runtime as the `t3` command the way the install scripts do, replacing only our own launcher. */
47export const installCli = Effect.fn("cli.install.install")(function* () {
48 const fs = yield* FileSystem.FileSystem;
49 const path = yield* Path.Path;
50 const platform = yield* HostProcess.Platform;
51 const environment = yield* HostProcess.Environment;
52 const home = yield* HostProcess.HomeDirectory;
53 const runtime = yield* standaloneRuntime;
54 const windows = platform === "win32";
55 if (Option.isNone(runtime)) {
56 const script = windows
57 ? "irm https://t3.codes/install.ps1 | iex"
58 : "curl -fsSL https://t3.codes/install.sh | sh";
59 return yield* new CliInstallError({
60 reason: `Only the standalone t3 can install itself. Use \`${script}\`, or Settings in the desktop app.`,
61 });
62 }
63 const { executable, versionsDir, runtimeDir } = runtime.value;
64 // cmd.exe expands `%` and reads the shim in the OEM code page, so such a path would not run.
65 if (windows && /[%\u0080-\uffff]/.test(executable)) {
66 return yield* new CliInstallError({
67 reason: `A t3.cmd cannot run ${executable}, because the path has % or non-ASCII characters. Keep using npx t3.`,
68 });
69 }
70 // Absolute, so the PATH hint never adds a folder that changes with the working directory.
71 const binDir = path.resolve(
72 environment.T3CODE_INSTALL_BIN_DIR?.trim() || path.join(home, ".local", "bin"),
73 );
74 const name = windows ? "t3.cmd" : "t3";
75 const link = path.join(binDir, name);
76 const failed = (reason: string) => (cause: unknown) => new CliInstallError({ reason, cause });
77
78 // Resolve fully so a link through a symlinked T3 home still counts as ours; a dangling one
79 // (a pruned version) falls back to its own text.
80 const realVersionsDir = yield* fs
81 .realPath(versionsDir)
82 .pipe(Effect.orElseSucceed(() => versionsDir));
83 const current = windows
84 ? yield* fs.readFileString(link).pipe(Effect.map(generatedWindowsShimTarget), Effect.option)
85 : yield* fs.readLink(link).pipe(
86 Effect.flatMap((target) =>
87 fs.realPath(link).pipe(Effect.orElseSucceed(() => path.resolve(binDir, target))),
88 ),
89 // Not a link: the script this command and the install scripts write.
90 Effect.catch(() => readPosixLauncherTarget(link)),
91 Effect.option,
92 Effect.map(Option.filter((target) => target !== undefined)),
93 );
94 // A dangling symlink is occupied too: writing the shim would follow it.
95 const occupied =
96 Option.isSome(current) ||
97 (yield* fs.exists(link)) ||
98 Option.isSome(yield* fs.readLink(link).pipe(Effect.option));
99 if (
100 occupied &&
101 !(
102 Option.isSome(current) &&
103 current.value !== undefined &&
104 (isVersionExecutable(path, versionsDir, current.value) ||
105 isVersionExecutable(path, realVersionsDir, current.value) ||
106 // This home's desktop launcher, which install.sh also replaces.
107 current.value === path.join(path.dirname(runtimeDir), "bin", name))
108 )
109 ) {
110 return yield* new CliInstallError({
111 reason: `Another t3 is already at ${link}. Remove it, then run this again.`,
112 });
113 }
114
115 yield* fs
116 .makeDirectory(binDir, { recursive: true })
117 .pipe(Effect.mapError(failed(`Could not create ${binDir}.`)));
118 // An empty spot is created exclusively, so a file that appears after the check above is kept.
119 if (windows) {
120 yield* fs
121 .writeFileString(link, `@echo off\r\n"${executable}" %*`, occupied ? {} : { flag: "wx" })
122 .pipe(Effect.mapError(failed(`Could not write ${link}.`)));
123 } else {
124 yield* writePosixLauncher({ launcher: link, executable, exclusive: !occupied }).pipe(
125 Effect.mapError(failed(`Could not write ${link}.`)),
126 );
127 }
128
129 // Pruning keeps what recorded launchers point at; a background service cannot see binDir otherwise.
130 const recorded = path.join(
131 yield* fs.realPath(binDir).pipe(Effect.orElseSucceed(() => binDir)),
132 name,
133 );
134 yield* recordPinnedRuntimeLauncher({
135 baseDir: path.dirname(runtimeDir),
136 launcher: recorded,
137 }).pipe(
138 Effect.catch(() =>
139 Console.error(
140 `Warning: could not record ${recorded} in ${path.join(runtimeDir, "launchers")}. Cleanup may remove the version it runs.`,
141 ),
142 ),
143 );
144
145 // resolve() drops trailing separators, so `~/.local/bin/` on PATH still matches.
146 const normalize = (value: string) =>
147 windows ? path.resolve(value).toLowerCase() : path.resolve(value);
148 const same = (entry: string) => entry !== "" && normalize(entry) === normalize(binDir);
149 const rawPath = environment.PATH ?? environment.Path ?? "";
150 const entries = rawPath === "" ? [] : rawPath.split(windows ? ";" : ":");
151 let cwd = yield* Effect.catchDefect(HostProcess.WorkingDirectory, () => Effect.undefined);
152 // A t3 earlier on PATH runs instead, and an added folder goes last. Runner caches (npx's own
153 // .bin) are not installs.
154 const firstOther = Effect.gen(function* () {
155 for (const entry of entries) {
156 const absolute = path.isAbsolute(entry);
157 if ((windows || absolute) && same(entry)) return null;
158 const dir = absolute ? entry : windows || !cwd ? undefined : path.resolve(cwd, entry);
159 if (dir === undefined || detectCliRunner(`${dir}/`) !== null) continue;
160 for (const name of windows ? ["t3.cmd", "t3.exe"] : ["t3"]) {
161 const candidate = path.join(dir, name);
162 if (!(yield* resolveCommandPath(candidate, { env: environment }))) continue;
163 if (windows) return candidate;
164 const resolved = yield* fs.realPath(candidate).pipe(Effect.orElseSucceed(() => candidate));
165 if (normalize(resolved) !== normalize(recorded)) return candidate;
166 if (absolute) return null;
167 cwd = undefined; // Ours already won in cwd; later relative entries lose.
168 }
169 }
170 return undefined;
171 });
172 // null: this launcher runs first; a path: another t3 does; undefined: no t3 on PATH.
173 const found = yield* firstOther;
174 return {
175 link,
176 onPath: found === null,
177 shadowedBy: found ?? undefined,
178 pathCommand:
179 found !== undefined
180 ? undefined
181 : windows
182 ? // PowerShell; it covers this window only, since changing the saved PATH would flatten
183 // its %VAR% entries. A `;` would split the folder.
184 binDir.includes(";")
185 ? undefined
186 : `$env:Path += ';${binDir.replaceAll("'", "''")}'`
187 : pathSetupCommand({
188 directory: binDir,
189 home,
190 shell: environment.SHELL,
191 platform,
192 configHome: environment.XDG_CONFIG_HOME,
193 zdotdir: environment.ZDOTDIR,
194 }),
195 binDir,
196 };
197});
198
199const reportInstalled = Effect.fn("cli.install.report")(function* (
200 installed: Effect.Success<ReturnType<typeof installCli>>,
201) {
202 yield* Console.log(`Installed t3 ${packageJson.version} at ${installed.link}.`);
203 if (installed.shadowedBy !== undefined) {
204 return yield* Console.log(
205 `Another t3 at ${installed.shadowedBy} runs first, so run ${installed.link} to use this one.`,
206 );
207 }
208 if (installed.onPath) return yield* Console.log("Run `t3` to get started.");
209 if (installed.pathCommand === undefined) {
210 return yield* Console.log(`Add ${installed.binDir} to your PATH, then run \`t3\`.`);
211 }
212 if ((yield* HostProcess.Platform) === "win32") {
213 yield* Console.log(
214 `${installed.binDir} is not on your PATH yet. In this PowerShell window, run:`,
215 );
216 yield* Console.log(` ${installed.pathCommand}`);
217 return yield* Console.log("Then run `t3`. For new windows, add the folder to your PATH.");
218 }
219 yield* Console.log(`${installed.binDir} is not on your PATH yet. Add it with:`);
220 yield* Console.log(` ${installed.pathCommand}`);
221 yield* Console.log("Then open a new terminal and run `t3`.");
222});
223
224export const installCommand = Command.make("install").pipe(
225 Command.withDescription("Install this version as the `t3` command."),
226 Command.withHandler(() => installCli().pipe(Effect.flatMap(reportInstalled))),
227);
228
229/** Saying no lasts until the next minor release: `0.2` covers `0.2.5` and `0.2.6-nightly.…`. */
230const minorRelease = (version: string) => version.split(".").slice(0, 2).join(".");
231
232const SKIPPED_ARGUMENTS = new Set([
233 "help",
234 "--help",
235 "-h",
236 "--version",
237 "-v",
238 "--completions",
239 // Scripts and machine-readable output; a prompt would stall them or corrupt their output.
240 "--json",
241 "--yes",
242 "-y",
243]);
244
245/** The subcommand, past global flags that may come first (two take a value). */
246const topLevelCommand = (args: ReadonlyArray<string>) => {
247 for (let index = 0; index < args.length; index++) {
248 const arg = args[index]!;
249 if (arg === "--log-level" || arg === "--completions") index++;
250 else if (!arg.startsWith("-")) return arg;
251 }
252 return undefined;
253};
254
255/** Agents can run commands in a terminal that nobody answers; no answer counts as no. */
256const PROMPT_TIMEOUT = Duration.seconds(30);
257
258/** `/proc/<pid>/stat` fields after the parenthesized command name: state ppid pgrp session tty_nr tpgid. */
259export const isForegroundProcStat = (stat: string) => {
260 const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
261 return fields[2] !== undefined && fields[2] !== "" && fields[2] === fields[5];
262};
263
264/** Output of `ps -o tpgid=,pgid=`; tpgid is -1 without a controlling terminal. */
265export const isForegroundPs = (output: string) => {
266 const [tpgid, pgid] = output.trim().split(/\s+/);
267 return tpgid !== undefined && tpgid !== "" && tpgid === pgid;
268};
269
270/**
271 * A background job (`npx t3 serve &`) that reads the terminal is stopped by the shell, so only
272 * the terminal's foreground process group may prompt. Unknown counts as background.
273 */
274export const inTerminalForeground = Effect.gen(function* () {
275 const fs = yield* FileSystem.FileSystem;
276 const platform = yield* HostProcess.Platform;
277 if (platform === "win32") return true;
278 if (platform === "linux") {
279 return isForegroundProcStat(
280 yield* fs.readFileString("/proc/self/stat").pipe(Effect.orElseSucceed(() => "")),
281 );
282 }
283 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
284 return isForegroundPs(
285 yield* spawner
286 .string(
287 // Absolute: under npx, PATH starts with a project's node_modules/.bin.
288 ChildProcess.make("/bin/ps", ["-o", "tpgid=,pgid=", "-p", String(process.pid)], {
289 stdin: "ignore",
290 stderr: "ignore",
291 }),
292 )
293 .pipe(Effect.orElseSucceed(() => "")),
294 );
295});
296
297/**
298 * Before a command run through npx, pnpm dlx, or bunx at a terminal, asks to install the `t3`
299 * command. Yes is the default. No, no answer, or a failed install is saved in the T3 home until
300 * the next minor release. Returns false when the user quits the prompt, so the command does not run.
301 */
302export const offerCliInstall = Effect.fn("cli.install.offer")(function* <E, R, E2, R2>(input: {
303 readonly args: ReadonlyArray<string>;
304 readonly interactive: boolean;
305 readonly foreground: Effect.Effect<boolean, E2, R2>;
306 /** Undefined when the user quits the prompt. */
307 readonly confirm: Effect.Effect<boolean | void, E, R>;
308}) {
309 const fs = yield* FileSystem.FileSystem;
310 const path = yield* Path.Path;
311 const platform = yield* HostProcess.Platform;
312 const environment = yield* HostProcess.Environment;
313 if (!input.interactive || environment.CI || environment.SUDO_USER) return true;
314 if (environment.TERM === "dumb") return true;
315 // `npx --yes` asks for no prompts; npm passes it on to the command as npm_config_yes.
316 if (environment.npm_config_yes === "true") return true;
317 // `--json=true` and `-y=true` are the same flags.
318 if (input.args.some((arg) => SKIPPED_ARGUMENTS.has(arg.split("=")[0]!))) return true;
319 const command = topLevelCommand(input.args);
320 if (command === "install" || command === "uninstall") return true;
321 if (detectCliRunner(yield* resolveEntryPath) === null) return true;
322 const runtime = yield* standaloneRuntime;
323 if (Option.isNone(runtime)) return true;
324 const { runtimeDir } = runtime.value;
325
326 // Any t3 already installed means no prompt: ours (even when off PATH) or another on PATH.
327 // Runners put their own cache's node_modules/.bin on PATH, so skip those.
328 const windows = platform === "win32";
329 const names = windows ? ["t3.cmd", "t3.exe"] : ["t3"];
330 const launchers = yield* fs
331 .readFileString(path.join(runtimeDir, "launchers"))
332 .pipe(Effect.orElseSucceed(() => ""));
333 const candidates = [
334 ...launchers.split(/\r?\n/).filter((launcher) => path.isAbsolute(launcher)),
335 path.join(path.dirname(runtimeDir), "bin", windows ? "t3.cmd" : "t3"),
336 ...(environment.PATH ?? environment.Path ?? "")
337 .split(windows ? ";" : ":")
338 .filter(
339 (directory) => path.isAbsolute(directory) && detectCliRunner(`${directory}/`) === null,
340 )
341 .flatMap((directory) => names.map((name) => path.join(directory, name))),
342 ];
343 for (const candidate of candidates) {
344 if (yield* resolveCommandPath(candidate, { env: environment })) return true;
345 }
346
347 const declinedFile = path.join(runtimeDir, "install-prompt-declined");
348 const declined = yield* fs.readFileString(declinedFile).pipe(Effect.orElseSucceed(() => ""));
349 const minor = minorRelease(packageJson.version);
350 if (declined.trim() === minor) return true;
351 if (!(yield* input.foreground)) return true;
352
353 const installHint = `Run \`${yield* resolveCliCommand("install")}\` any time.`;
354 const saveDecline = fs.writeFileString(declinedFile, `${minor}\n`).pipe(Effect.ignore);
355 const answer = yield* input.confirm.pipe(Effect.timeoutOption(PROMPT_TIMEOUT));
356 if (Option.isNone(answer)) {
357 yield* saveDecline;
358 yield* Console.log(`\nNo answer, so t3 was not installed. ${installHint}\n`);
359 return true;
360 }
361 if (answer.value === undefined) return false;
362 if (!answer.value) {
363 yield* saveDecline;
364 yield* Console.log(`Skipped. ${installHint}\n`);
365 return true;
366 }
367 yield* installCli().pipe(
368 Effect.flatMap(reportInstalled),
369 Effect.catch((error) =>
370 Effect.andThen(saveDecline, Console.error(`Could not install t3: ${error.message}`)),
371 ),
372 );
373 yield* Console.log("");
374 return true;
375});
376
377export const confirmCliInstall = Prompt.run(
378 Prompt.Confirm({
379 message: "Install the t3 command? Then you can run `t3` directly.",
380 initial: true,
381 }),
382).pipe(Effect.catchTags({ QuitError: () => Effect.void }));