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/**
16 * How the CLI was launched, judged by where its entry script lives. Each
17 * package runner executes out of a distinctive cache/temp layout:
18 *
19 * npx ~/.npm/_npx/<hash>/node_modules/...
20 * pnpm dlx ~/.cache/pnpm/dlx/..., $PNPM_HOME/.pnpm/dlx/...,
21 * or %LOCALAPPDATA%/pnpm-cache/dlx/... on Windows
22 * bunx ~/.bun/install/cache/... or $TMPDIR/bunx-<uid>-<spec>/...
23 *
24 * Global installs and repo checkouts match none of these and return null.
25 * Detection is best-effort; callers must fail closed to a plain `t3` command.
26 */
27function detectCliRunner(entryPath: string): CliRunner | null {
28 const path = entryPath.replaceAll("\\", "/");
29 if (path.includes("/_npx/")) {
30 return "npx";
31 }
32 if (
33 path.includes("/pnpm/dlx/") ||
34 path.includes("/.pnpm/dlx/") ||
35 path.includes("/pnpm-cache/dlx/")
36 ) {
37 return "pnpm dlx";
38 }
39 if (path.includes("/.bun/install/cache/") || path.includes("/bunx-")) {
40 return "bunx";
41 }
42 return null;
43}
44
45const InstallManifest = Schema.Struct({
46 name: Schema.String,
47 version: Schema.String,
48 bin: Schema.optionalKey(Schema.Struct({ t3: Schema.String })),
49 optionalDependencies: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
50});
51const decodeInstallManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(InstallManifest));
52
53/** Prove the running package and its global bin belong together before suggesting an update. */
54export const resolveServerInstallation = Effect.gen(function* () {
55 const fs = yield* FileSystem.FileSystem;
56 const path = yield* Path.Path;
57 const args = yield* HostProcess.Arguments;
58 const executable = yield* HostProcess.IsExecutable;
59 const executablePath = yield* HostProcess.ExecutablePath;
60 const platform = yield* HostProcess.Platform;
61 const entry = yield* fs.realPath(executable ? executablePath : (args[1] ?? ""));
62 const match =
63 /^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.js|node_modules\/@t3code\/t3-[^/]+\/t3)$/.exec(
64 entry,
65 );
66 if (!match) {
67 const runner = detectCliRunner(entry);
68 return runner === null
69 ? null
70 : ({ kind: runner === "pnpm dlx" ? "pnpm-dlx" : runner } satisfies ServerInstallation);
71 }
72 // A global prefix can contain runner-like names; prove its ownership first.
73 // Windows shims and other package managers need their own ownership proof.
74 if (platform === "win32") return null;
75 const prefix = match[1] || "/";
76 if (
77 prefix.includes("/node_modules/") ||
78 /\/(?:Cellar|Caskroom)\//i.test(prefix) ||
79 /\/mise\/installs\/(?!node\/)[^/]+\//.test(prefix)
80 )
81 return null;
82
83 const packageRoot = path.join(prefix, "lib/node_modules/t3");
84 const manifest = yield* fs
85 .readFileString(path.join(packageRoot, "package.json"))
86 .pipe(Effect.flatMap(decodeInstallManifest));
87 if (manifest.name !== "t3" || !manifest.bin) return null;
88 const bin = yield* fs.realPath(path.join(packageRoot, manifest.bin.t3));
89 const globalBin = yield* fs.realPath(path.join(prefix, "bin/t3"));
90 if (globalBin !== bin) return null;
91 if (executable) {
92 const nativeManifest = yield* fs
93 .readFileString(path.join(path.dirname(entry), "package.json"))
94 .pipe(Effect.flatMap(decodeInstallManifest));
95 if (
96 manifest.bin.t3 !== "./bin/t3.js" ||
97 manifest.optionalDependencies?.[nativeManifest.name] !== nativeManifest.version ||
98 nativeManifest.version !== manifest.version
99 )
100 return null;
101 } else if (bin !== entry) {
102 return null;
103 }
104 return { kind: "npm-global", prefix } satisfies ServerInstallation;
105}).pipe(Effect.orElseSucceed(() => null));
106
107/**
108 * The `t3` package spec to suggest. The literal spec the user typed (e.g.
109 * `t3@nightly`) is resolved away before our process starts, so re-derive it
110 * from the running version: nightly builds re-suggest the nightly channel,
111 * anything else suggests the bare package.
112 */
113function suggestedPackageSpec(version: string): string {
114 const channel = /^[^-+]+-(nightly|preview)\./.exec(version)?.[1];
115 return channel === undefined ? "t3" : `t3@${channel}`;
116}
117
118/**
119 * Render a `t3 <subcommand>` suggestion that matches how this process was
120 * launched, so copy/pasting it actually works: `npx t3 connect` suggests
121 * `npx t3 serve`, a global install suggests `t3 serve`, and a nightly build
122 * keeps the `@nightly` tag.
123 */
124export function formatCliCommand(input: {
125 readonly subcommand: string;
126 readonly entryPath: string;
127 readonly version: string;
128}): string {
129 const runner = detectCliRunner(input.entryPath);
130 if (runner === null) {
131 return `t3 ${input.subcommand}`;
132 }
133 return `${runner} ${suggestedPackageSpec(input.version)} ${input.subcommand}`;
134}
135
136/** `formatCliCommand` against this process's real entry path and version. */
137export const resolveCliCommand = (subcommand: string) =>
138 Effect.map(HostProcess.Arguments, (processArguments) =>
139 formatCliCommand({
140 subcommand,
141 entryPath: processArguments[1] ?? "",
142 version: packageJson.version,
143 }),
144 );
145
146/** Quotes `value` for a POSIX shell when it needs it. */
147const shellWord = (value: string) =>
148 /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'"'"'`)}'`;
149
150/**
151 * The launcher a person can type to run this install when `t3` is not on
152 * PATH: the desktop app's `t3` shim, which the app and the shim itself name in
153 * `T3CODE_CLI_PATH`, or a standalone binary's own path. Script installs (a
154 * repo checkout) have no single launcher and keep plain `t3`.
155 */
156const resolveInstallLauncher = Effect.gen(function* () {
157 const fs = yield* FileSystem.FileSystem;
158 const shim = (yield* HostProcess.Environment).T3CODE_CLI_PATH?.trim();
159 if (shim && (yield* fs.exists(shim).pipe(Effect.orElseSucceed(() => false)))) {
160 return Option.some(shim);
161 }
162 return (yield* HostProcess.IsExecutable)
163 ? Option.some(yield* HostProcess.ExecutablePath)
164 : Option.none<string>();
165});
166
167/**
168 * `t3 <subcommand>` for a person to run on this host: `t3` when it is on PATH,
169 * the package runner this process came from, or else the absolute path of the
170 * launcher for this install, such as the one the desktop app installs.
171 */
172const resolveHostCliCommand = (subcommand: string) =>
173 Effect.gen(function* () {
174 const command = yield* resolveCliCommand(subcommand);
175 if (command !== `t3 ${subcommand}`) return { command, launcher: false };
176 if (yield* isCommandAvailable("t3")) return { command, launcher: false };
177 const launcher = yield* resolveInstallLauncher;
178 return Option.isSome(launcher)
179 ? { command: `${shellWord(launcher.value)} ${subcommand}`, launcher: true }
180 : { command, launcher: false };
181 });
182
183/**
184 * `t3 <subcommand>` as root, for setup a person runs once on the host. `sudo`
185 * resets PATH on most distributions, which drops a user-installed Node (nvm,
186 * fnm, a tarball) and with it `npx` or a global `t3`, so the command carries
187 * PATH through unless Node is on root's PATH too. An absolute launcher needs
188 * neither.
189 */
190export const resolveRootCliCommand = (subcommand: string) =>
191 Effect.gen(function* () {
192 const { command, launcher } = yield* resolveHostCliCommand(subcommand);
193 if (launcher) return `sudo ${command}`;
194 const executablePath = yield* HostProcess.ExecutablePath;
195 const systemNode = ROOT_PATH_DIRECTORIES.some((directory) =>
196 executablePath.startsWith(`${directory}/`),
197 );
198 return systemNode ? `sudo ${command}` : `sudo env "PATH=$PATH" ${command}`;
199 });
200
201/** Debian and Ubuntu's sudo `secure_path`, minus snap. */
202const ROOT_PATH_DIRECTORIES = [
203 "/usr/local/sbin",
204 "/usr/local/bin",
205 "/usr/sbin",
206 "/usr/bin",
207 "/sbin",
208 "/bin",
209];