Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

invocation.ts

232 lines9.2 KB

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;
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}`;
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}`;
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 * Quotes `value` for PowerShell, the default Windows terminal. Always quoted,
152 * so a path reads the same whether or not it holds a space. Inside double
153 * quotes `"` and its typographic forms (which also end the string) double,
154 * and `$` and the backtick are escaped so nothing expands.
155 */
156const powershellWord = (value: string) =>
157 `"${value
158 .replaceAll("`", "``")
159 .replaceAll("$", "`$")
160 .replace(/["\u201C\u201D\u201E]/g, "$&$&")}"`;
161​
162/** Quotes a word for the host's shell: POSIX, or PowerShell on Windows. */
163const hostShellWord = (platform: NodeJS.Platform, value: string) =>
164 platform === "win32" ? powershellWord(value) : shellWord(value);
165​
166/**
167 * The launcher a person can type to run this install when `t3` is not on
168 * PATH: the desktop app's `t3` shim, which the app and the shim itself name in
169 * `T3CODE_CLI_PATH`, or a standalone binary's own path. Script installs (a
170 * repo checkout) have no single launcher and keep plain `t3`.
171 */
172const resolveInstallLauncher = Effect.gen(function* () {
173 const fs = yield* FileSystem.FileSystem;
174 const shim = (yield* HostProcess.Environment).T3CODE_CLI_PATH?.trim();
175 if (shim && (yield* fs.exists(shim).pipe(Effect.orElseSucceed(() => false)))) {
176 return Option.some(shim);
177 }
178 return (yield* HostProcess.IsExecutable)
179 ? Option.some(yield* HostProcess.ExecutablePath)
180 : Option.none<string>();
181});
182​
183/**
184 * `t3 <subcommand> <args>` for a person to run on this host: `t3` when it is
185 * on PATH, the package runner this process came from, or else the absolute
186 * path of the launcher for this install, such as the one the desktop app
187 * installs. `args` are quoted for the host's shell: POSIX, or PowerShell on
188 * Windows.
189 */
190export const resolveHostCliCommand = (subcommand: string, args: ReadonlyArray<string> = []) =>
191 Effect.gen(function* () {
192 const platform = yield* HostProcess.Platform;
193 const withArgs = (prefix: string) =>
194 [prefix, ...args.map((arg) => hostShellWord(platform, arg))].join(" ");
195 const command = yield* resolveCliCommand(subcommand);
196 if (command !== `t3 ${subcommand}`) return { command: withArgs(command), launcher: false };
197 if (yield* isCommandAvailable("t3")) return { command: withArgs(command), launcher: false };
198 const launcher = yield* resolveInstallLauncher;
199 if (Option.isNone(launcher)) return { command: withArgs(command), launcher: false };
200 // PowerShell runs a quoted path only through the call operator.
201 const quoted = hostShellWord(platform, launcher.value);
202 const call = platform === "win32" ? `& ${quoted}` : quoted;
203 return { command: withArgs(`${call} ${subcommand}`), launcher: true };
204 });
205​
206/**
207 * `t3 <subcommand>` as root, for setup a person runs once on the host. `sudo`
208 * resets PATH on most distributions, which drops a user-installed Node (nvm,
209 * fnm, a tarball) and with it `npx` or a global `t3`, so the command carries
210 * PATH through unless Node is on root's PATH too. An absolute launcher needs
211 * neither.
212 */
213export const resolveRootCliCommand = (subcommand: string) =>
214 Effect.gen(function* () {
215 const { command, launcher } = yield* resolveHostCliCommand(subcommand);
216 if (launcher) return `sudo ${command}`;
217 const executablePath = yield* HostProcess.ExecutablePath;
218 const systemNode = ROOT_PATH_DIRECTORIES.some((directory) =>
219 executablePath.startsWith(`${directory}/`),
220 );
221 return systemNode ? `sudo ${command}` : `sudo env "PATH=$PATH" ${command}`;
222 });
223​
224/** Debian and Ubuntu's sudo `secure_path`, minus snap. */
225const ROOT_PATH_DIRECTORIES = [
226 "/usr/local/sbin",
227 "/usr/local/bin",
228 "/usr/sbin",
229 "/usr/bin",
230 "/sbin",
231 "/bin",
232];