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

invocation.ts

211 lines8.0 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 { resolveCommandPath } 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. */
16export function 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;
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 * `T3CODE_NPM_LAUNCHER_PATH` is inherited by child shells, so accept it only for this package
43 * version to avoid claiming another `t3` invocation is the npm install.
44 */
45export const resolveEntryPath = Effect.gen(function* () {
46 const npmLauncher = (yield* HostProcess.Environment).T3CODE_NPM_LAUNCHER_PATH?.trim();
47 if (npmLauncher) {
48 const fs = yield* FileSystem.FileSystem;
49 const path = yield* Path.Path;
50 const manifest = yield* fs
51 .readFileString(path.join(path.dirname(npmLauncher), "../package.json"))
52 .pipe(Effect.flatMap(decodeInstallManifest), Effect.option);
53 if (
54 Option.isSome(manifest) &&
55 manifest.value.name === "t3" &&
56 manifest.value.version === packageJson.version
57 ) {
58 return npmLauncher;
59 }
60 }
61 if (yield* HostProcess.IsExecutable) return yield* HostProcess.ExecutablePath;
62 return (yield* HostProcess.Arguments)[1] ?? "";
63});
64​
65export const resolveServerInstallation = Effect.gen(function* () {
66 const fs = yield* FileSystem.FileSystem;
67 const path = yield* Path.Path;
68 const platform = yield* HostProcess.Platform;
69 const entry = yield* fs.realPath(yield* resolveEntryPath);
70 const match = /^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.mjs)$/.exec(entry);
71 if (!match) {
72 const runner = detectCliRunner(entry);
73 return runner === null
74 ? null
75 : ({ kind: runner === "pnpm dlx" ? "pnpm-dlx" : runner } satisfies ServerInstallation);
76 }
77 if (platform === "win32") return null;
78 const prefix = match[1] || "/";
79 if (
80 prefix.includes("/node_modules/") ||
81 /\/(?:Cellar|Caskroom)\//i.test(prefix) ||
82 /\/mise\/installs\/(?!node\/)[^/]+\//.test(prefix)
83 )
84 return null;
85​
86 const packageRoot = path.join(prefix, "lib/node_modules/t3");
87 const manifest = yield* fs
88 .readFileString(path.join(packageRoot, "package.json"))
89 .pipe(Effect.flatMap(decodeInstallManifest));
90 if (manifest.name !== "t3" || !manifest.bin) return null;
91 const bin = yield* fs.realPath(path.join(packageRoot, manifest.bin.t3));
92 const globalBin = yield* fs.realPath(path.join(prefix, "bin/t3"));
93 if (globalBin !== bin || bin !== entry) return null;
94 return { kind: "npm-global", prefix } satisfies ServerInstallation;
95}).pipe(Effect.orElseSucceed(() => null));
96​
97/** The original package spec is unavailable at startup; infer its channel from the version. */
98function suggestedPackageSpec(version: string): string {
99 const channel = /^[^-+]+-(nightly|preview)\./.exec(version)?.[1];
100 return channel === undefined ? "t3" : `t3@${channel}`;
102​
103function formatCliCommand(input: {
104 readonly subcommand: string;
105 readonly entryPath: string;
106 readonly version: string;
107}): string {
108 const runner = detectCliRunner(input.entryPath);
109 if (runner === null) {
110 return `t3 ${input.subcommand}`;
111 }
112 return `${runner} ${suggestedPackageSpec(input.version)} ${input.subcommand}`;
114​
115export const resolveCliCommand = (subcommand: string) =>
116 Effect.map(resolveEntryPath, (entryPath) =>
117 formatCliCommand({ subcommand, entryPath, version: packageJson.version }),
118 );
119​
120const shellWord = (value: string) =>
121 /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'"'"'`)}'`;
122​
123/** PowerShell also treats typographic quotes as delimiters; escape them and suppress expansion. */
124const powershellWord = (value: string) =>
125 `"${value
126 .replaceAll("`", "``")
127 .replaceAll("$", "`$")
128 .replace(/["\u201C\u201D\u201E]/g, "$&$&")}"`;
129​
130const hostShellWord = (platform: NodeJS.Platform, value: string) =>
131 platform === "win32" ? powershellWord(value) : shellWord(value);
132​
133/** Script installs have no single launcher; desktop shims and standalone binaries do. */
134const resolveInstallLauncher = Effect.gen(function* () {
135 const fs = yield* FileSystem.FileSystem;
136 const shim = (yield* HostProcess.Environment).T3CODE_CLI_PATH?.trim();
137 if (shim && (yield* fs.exists(shim).pipe(Effect.orElseSucceed(() => false)))) {
138 return Option.some(shim);
139 }
140 return (yield* HostProcess.IsExecutable)
141 ? Option.some(yield* HostProcess.ExecutablePath)
142 : Option.none<string>();
143});
144​
145/**
146 * Uses this install's `t3` on PATH, the originating runner, or its absolute launcher path.
147 * Arguments are quoted for POSIX shells or PowerShell on Windows.
148 */
149export const resolveHostCliCommand = Effect.fn("invocation.resolveHostCliCommand")(function* (
150 subcommand: string,
151 args: ReadonlyArray<string> = [],
152) {
153 const platform = yield* HostProcess.Platform;
154 const withArgs = (prefix: string) =>
155 [prefix, ...args.map((arg) => hostShellWord(platform, arg))].join(" ");
156 const command = yield* resolveCliCommand(subcommand);
157 if (command !== `t3 ${subcommand}`) return { command: withArgs(command), launcher: false };
158 const onPath = yield* resolveCommandPath("t3");
159 if (onPath !== null) {
160 const shim = (yield* HostProcess.Environment).T3CODE_CLI_PATH?.trim();
161 const fs = yield* FileSystem.FileSystem;
162 const real = (file: string) => fs.realPath(file).pipe(Effect.orElseSucceed(() => null));
163 // Windows `t3.cmd` shims are text files that never realpath to the executable they run.
164 const own = shim
165 ? yield* real(shim)
166 : platform !== "win32" && (yield* HostProcess.IsExecutable)
167 ? yield* resolveEntryPath.pipe(
168 Effect.flatMap((entry) =>
169 real(entry).pipe(Effect.map((resolved) => resolved ?? entry)),
170 ),
171 )
172 : null;
173 if (own === null || own === (yield* real(onPath))) {
174 return { command: withArgs(command), launcher: false };
175 }
176 }
177 const launcher = yield* resolveInstallLauncher;
178 if (Option.isNone(launcher)) return { command: withArgs(command), launcher: false };
179 // PowerShell runs a quoted path only through the call operator.
180 const quoted = hostShellWord(platform, launcher.value);
181 const call = platform === "win32" ? `& ${quoted}` : quoted;
182 return { command: withArgs(`${call} ${subcommand}`), launcher: true };
183});
184​
185/**
186 * `sudo` resets PATH on most distributions, which drops a user-installed Node
187 * (nvm, fnm, a tarball) and with it `npx` or a global `t3`, so the command
188 * carries PATH through unless Node is on root's PATH too. An absolute launcher
189 * needs neither.
190 */
191export const resolveRootCliCommand = Effect.fn("invocation.resolveRootCliCommand")(function* (
192 subcommand: string,
193 args: ReadonlyArray<string> = [],
194) {
195 const { command, launcher } = yield* resolveHostCliCommand(subcommand, args);
196 if (launcher) return `sudo ${command}`;
197 const executablePath = yield* HostProcess.ExecutablePath;
198 const systemNode = ROOT_PATH_DIRECTORIES.some((directory) =>
199 executablePath.startsWith(`${directory}/`),
200 );
201 return systemNode ? `sudo ${command}` : `sudo env "PATH=$PATH" ${command}`;
202});
203​
204const ROOT_PATH_DIRECTORIES = [
205 "/usr/local/sbin",
206 "/usr/local/bin",
207 "/usr/sbin",
208 "/usr/bin",
209 "/sbin",
210 "/bin",
211];