Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Option from "effect/Option";
4import * as Path from "effect/Path";
5import * as Schema from "effect/Schema";
6
7import type { ServerInstallation } from "@t3tools/contracts";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import { isCommandAvailable } from "@t3tools/shared/shell";
10
11import packageJson from "../../package.json" with { type: "json" };
12
13export type CliRunner = "npx" | "pnpm dlx" | "bunx";
14
15/** Detection is best-effort; callers must fail closed to a plain `t3` command. */
16function detectCliRunner(entryPath: string): CliRunner | null {
17 const path = entryPath.replaceAll("\\", "/");
18 if (path.includes("/_npx/")) {
19 return "npx";
20 }
21 if (
22 path.includes("/pnpm/dlx/") ||
23 path.includes("/.pnpm/dlx/") ||
24 path.includes("/pnpm-cache/dlx/")
25 ) {
26 return "pnpm dlx";
27 }
28 if (path.includes("/.bun/install/cache/") || path.includes("/bunx-")) {
29 return "bunx";
30 }
31 return null;
32}
33
34const InstallManifest = Schema.Struct({
35 name: Schema.String,
36 version: Schema.String,
37 bin: Schema.optionalKey(Schema.Struct({ t3: Schema.String })),
38});
39const decodeInstallManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(InstallManifest));
40
41/**
42 * The script this CLI was started through: the `t3` npm launcher that
43 * downloaded and ran this executable (it names itself in
44 * `T3CODE_NPM_LAUNCHER_PATH`), or the Node entry script of a build run from
45 * source. A standalone executable has none and reports its own path.
46 *
47 * The variable is inherited by everything the server spawns, so a launcher
48 * counts only when its package is this exact version: a different `t3` run
49 * from an agent's shell must not claim to be the npm install.
50 */
51const resolveEntryPath = Effect.gen(function* () {
52 const npmLauncher = (yield* HostProcess.Environment).T3CODE_NPM_LAUNCHER_PATH?.trim();
53 if (npmLauncher) {
54 const fs = yield* FileSystem.FileSystem;
55 const path = yield* Path.Path;
56 const manifest = yield* fs
57 .readFileString(path.join(path.dirname(npmLauncher), "../package.json"))
58 .pipe(Effect.flatMap(decodeInstallManifest), Effect.option);
59 if (
60 Option.isSome(manifest) &&
61 manifest.value.name === "t3" &&
62 manifest.value.version === packageJson.version
63 ) {
64 return npmLauncher;
65 }
66 }
67 if (yield* HostProcess.IsExecutable) return yield* HostProcess.ExecutablePath;
68 return (yield* HostProcess.Arguments)[1] ?? "";
69});
70
71export const resolveServerInstallation = Effect.gen(function* () {
72 const fs = yield* FileSystem.FileSystem;
73 const path = yield* Path.Path;
74 const platform = yield* HostProcess.Platform;
75 const entry = yield* fs.realPath(yield* resolveEntryPath);
76 const match = /^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.mjs)$/.exec(entry);
77 if (!match) {
78 const runner = detectCliRunner(entry);
79 return runner === null
80 ? null
81 : ({ kind: runner === "pnpm dlx" ? "pnpm-dlx" : runner } satisfies ServerInstallation);
82 }
83 if (platform === "win32") return null;
84 const prefix = match[1] || "/";
85 if (
86 prefix.includes("/node_modules/") ||
87 /\/(?:Cellar|Caskroom)\//i.test(prefix) ||
88 /\/mise\/installs\/(?!node\/)[^/]+\//.test(prefix)
89 )
90 return null;
91
92 const packageRoot = path.join(prefix, "lib/node_modules/t3");
93 const manifest = yield* fs
94 .readFileString(path.join(packageRoot, "package.json"))
95 .pipe(Effect.flatMap(decodeInstallManifest));
96 if (manifest.name !== "t3" || !manifest.bin) return null;
97 const bin = yield* fs.realPath(path.join(packageRoot, manifest.bin.t3));
98 const globalBin = yield* fs.realPath(path.join(prefix, "bin/t3"));
99 if (globalBin !== bin || bin !== entry) return null;
100 return { kind: "npm-global", prefix } satisfies ServerInstallation;
101}).pipe(Effect.orElseSucceed(() => null));
102
103/**
104 * The literal spec the user typed (e.g. `t3@nightly`) is resolved away before
105 * our process starts, so re-derive it from the running version: nightly builds
106 * re-suggest the nightly channel, anything else suggests the bare package.
107 */
108function suggestedPackageSpec(version: string): string {
109 const channel = /^[^-+]+-(nightly|preview)\./.exec(version)?.[1];
110 return channel === undefined ? "t3" : `t3@${channel}`;
111}
112
113export function formatCliCommand(input: {
114 readonly subcommand: string;
115 readonly entryPath: string;
116 readonly version: string;
117}): string {
118 const runner = detectCliRunner(input.entryPath);
119 if (runner === null) {
120 return `t3 ${input.subcommand}`;
121 }
122 return `${runner} ${suggestedPackageSpec(input.version)} ${input.subcommand}`;
123}
124
125export const resolveCliCommand = (subcommand: string) =>
126 Effect.map(resolveEntryPath, (entryPath) =>
127 formatCliCommand({ subcommand, entryPath, version: packageJson.version }),
128 );
129
130const shellWord = (value: string) =>
131 /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'"'"'`)}'`;
132
133/**
134 * Quotes `value` for PowerShell, the default Windows terminal. Always quoted,
135 * so a path reads the same whether or not it holds a space. Inside double
136 * quotes `"` and its typographic forms (which also end the string) double,
137 * and `$` and the backtick are escaped so nothing expands.
138 */
139const powershellWord = (value: string) =>
140 `"${value
141 .replaceAll("`", "``")
142 .replaceAll("$", "`$")
143 .replace(/["\u201C\u201D\u201E]/g, "$&$&")}"`;
144
145/** Quotes a word for the host's shell: POSIX, or PowerShell on Windows. */
146const hostShellWord = (platform: NodeJS.Platform, value: string) =>
147 platform === "win32" ? powershellWord(value) : shellWord(value);
148
149/**
150 * The launcher a person can type to run this install when `t3` is not on
151 * PATH: the desktop app's `t3` shim, which the app and the shim itself name in
152 * `T3CODE_CLI_PATH`, or a standalone binary's own path. Script installs (a
153 * repo checkout) have no single launcher and keep plain `t3`.
154 */
155const resolveInstallLauncher = Effect.gen(function* () {
156 const fs = yield* FileSystem.FileSystem;
157 const shim = (yield* HostProcess.Environment).T3CODE_CLI_PATH?.trim();
158 if (shim && (yield* fs.exists(shim).pipe(Effect.orElseSucceed(() => false)))) {
159 return Option.some(shim);
160 }
161 return (yield* HostProcess.IsExecutable)
162 ? Option.some(yield* HostProcess.ExecutablePath)
163 : Option.none<string>();
164});
165
166/**
167 * `t3 <subcommand> <args>` for a person to run on this host: `t3` when it is
168 * on PATH, the package runner this process came from, or else the absolute
169 * path of the launcher for this install, such as the one the desktop app
170 * installs. `args` are quoted for the host's shell: POSIX, or PowerShell on
171 * Windows.
172 */
173export const resolveHostCliCommand = (subcommand: string, args: ReadonlyArray<string> = []) =>
174 Effect.gen(function* () {
175 const platform = yield* HostProcess.Platform;
176 const withArgs = (prefix: string) =>
177 [prefix, ...args.map((arg) => hostShellWord(platform, arg))].join(" ");
178 const command = yield* resolveCliCommand(subcommand);
179 if (command !== `t3 ${subcommand}`) return { command: withArgs(command), launcher: false };
180 if (yield* isCommandAvailable("t3")) return { command: withArgs(command), launcher: false };
181 const launcher = yield* resolveInstallLauncher;
182 if (Option.isNone(launcher)) return { command: withArgs(command), launcher: false };
183 // PowerShell runs a quoted path only through the call operator.
184 const quoted = hostShellWord(platform, launcher.value);
185 const call = platform === "win32" ? `& ${quoted}` : quoted;
186 return { command: withArgs(`${call} ${subcommand}`), launcher: true };
187 });
188
189/**
190 * `sudo` resets PATH on most distributions, which drops a user-installed Node
191 * (nvm, fnm, a tarball) and with it `npx` or a global `t3`, so the command
192 * carries PATH through unless Node is on root's PATH too. An absolute launcher
193 * needs neither.
194 */
195export const resolveRootCliCommand = (subcommand: string) =>
196 Effect.gen(function* () {
197 const { command, launcher } = yield* resolveHostCliCommand(subcommand);
198 if (launcher) return `sudo ${command}`;
199 const executablePath = yield* HostProcess.ExecutablePath;
200 const systemNode = ROOT_PATH_DIRECTORIES.some((directory) =>
201 executablePath.startsWith(`${directory}/`),
202 );
203 return systemNode ? `sudo ${command}` : `sudo env "PATH=$PATH" ${command}`;
204 });
205
206const ROOT_PATH_DIRECTORIES = [
207 "/usr/local/sbin",
208 "/usr/local/bin",
209 "/usr/sbin",
210 "/usr/bin",
211 "/sbin",
212 "/bin",
213];