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

invocation.ts

173 lines6.3 KB

1import * as Effect from "effect/Effect";
2import * as FileSystem from "effect/FileSystem";
3import * as Path from "effect/Path";
4import * as Schema from "effect/Schema";
5​
6import type { ServerInstallation } from "@t3tools/contracts";
7import {
8 HostProcessArguments,
9 HostProcessExecutablePath,
10 HostProcessIsExecutable,
11 HostProcessPlatform,
12} from "@t3tools/shared/hostProcess";
13​
14import packageJson from "../../package.json" with { type: "json" };
15​
16export type CliRunner = "npx" | "pnpm dlx" | "bunx";
17​
18/**
19 * How the CLI was launched, judged by where its entry script lives. Each
20 * package runner executes out of a distinctive cache/temp layout:
21 *
22 * npx ~/.npm/_npx/<hash>/node_modules/...
23 * pnpm dlx ~/.cache/pnpm/dlx/..., $PNPM_HOME/.pnpm/dlx/...,
24 * or %LOCALAPPDATA%/pnpm-cache/dlx/... on Windows
25 * bunx ~/.bun/install/cache/... or $TMPDIR/bunx-<uid>-<spec>/...
26 *
27 * Global installs and repo checkouts match none of these and return null.
28 * Detection is best-effort; callers must fail closed to a plain `t3` command.
29 */
30function detectCliRunner(entryPath: string): CliRunner | null {
31 const path = entryPath.replaceAll("\\", "/");
32 if (path.includes("/_npx/")) {
33 return "npx";
34 }
35 if (
36 path.includes("/pnpm/dlx/") ||
37 path.includes("/.pnpm/dlx/") ||
38 path.includes("/pnpm-cache/dlx/")
39 ) {
40 return "pnpm dlx";
41 }
42 if (path.includes("/.bun/install/cache/") || path.includes("/bunx-")) {
43 return "bunx";
44 }
45 return null;
47​
48const InstallManifest = Schema.Struct({
49 name: Schema.String,
50 version: Schema.String,
51 bin: Schema.optionalKey(Schema.Struct({ t3: Schema.String })),
52 optionalDependencies: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
53});
54const decodeInstallManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(InstallManifest));
55​
56/** Prove the running package and its global bin belong together before suggesting an update. */
57export const resolveServerInstallation = Effect.gen(function* () {
58 const fs = yield* FileSystem.FileSystem;
59 const path = yield* Path.Path;
60 const args = yield* HostProcessArguments;
61 const executable = yield* HostProcessIsExecutable;
62 const executablePath = yield* HostProcessExecutablePath;
63 const platform = yield* HostProcessPlatform;
64 const entry = yield* fs.realPath(executable ? executablePath : (args[1] ?? ""));
65 const match =
66 /^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.js|node_modules\/@t3code\/t3-[^/]+\/t3)$/.exec(
67 entry,
68 );
69 if (!match) {
70 const runner = detectCliRunner(entry);
71 return runner === null
72 ? null
73 : ({ kind: runner === "pnpm dlx" ? "pnpm-dlx" : runner } satisfies ServerInstallation);
74 }
75 // A global prefix can contain runner-like names; prove its ownership first.
76 // Windows shims and other package managers need their own ownership proof.
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) return null;
94 if (executable) {
95 const nativeManifest = yield* fs
96 .readFileString(path.join(path.dirname(entry), "package.json"))
97 .pipe(Effect.flatMap(decodeInstallManifest));
98 if (
99 manifest.bin.t3 !== "./bin/t3.js" ||
100 manifest.optionalDependencies?.[nativeManifest.name] !== nativeManifest.version ||
101 nativeManifest.version !== manifest.version
102 )
103 return null;
104 } else if (bin !== entry) {
105 return null;
106 }
107 return { kind: "npm-global", prefix } satisfies ServerInstallation;
108}).pipe(Effect.orElseSucceed(() => null));
109​
110/**
111 * The `t3` package spec to suggest. The literal spec the user typed (e.g.
112 * `t3@nightly`) is resolved away before our process starts, so re-derive it
113 * from the running version: nightly builds re-suggest the nightly channel,
114 * anything else suggests the bare package.
115 */
116function suggestedPackageSpec(version: string): string {
117 const channel = /^[^-+]+-(nightly|preview)\./.exec(version)?.[1];
118 return channel === undefined ? "t3" : `t3@${channel}`;
120​
121/**
122 * Render a `t3 <subcommand>` suggestion that matches how this process was
123 * launched, so copy/pasting it actually works: `npx t3 connect` suggests
124 * `npx t3 serve`, a global install suggests `t3 serve`, and a nightly build
125 * keeps the `@nightly` tag.
126 */
127export function formatCliCommand(input: {
128 readonly subcommand: string;
129 readonly entryPath: string;
130 readonly version: string;
131}): string {
132 const runner = detectCliRunner(input.entryPath);
133 if (runner === null) {
134 return `t3 ${input.subcommand}`;
135 }
136 return `${runner} ${suggestedPackageSpec(input.version)} ${input.subcommand}`;
138​
139/** `formatCliCommand` against this process's real entry path and version. */
140export const resolveCliCommand = (subcommand: string) =>
141 Effect.map(HostProcessArguments, (processArguments) =>
142 formatCliCommand({
143 subcommand,
144 entryPath: processArguments[1] ?? "",
145 version: packageJson.version,
146 }),
147 );
148​
149/**
150 * `t3 <subcommand>` as root, for setup a person runs once on the host. `sudo`
151 * resets PATH on most distributions, which drops a user-installed Node (nvm,
152 * fnm, a tarball) and with it `npx` or a global `t3`, so the command carries
153 * PATH through unless Node is on root's PATH too.
154 */
155export const resolveRootCliCommand = (subcommand: string) =>
156 Effect.gen(function* () {
157 const command = yield* resolveCliCommand(subcommand);
158 const executablePath = yield* HostProcessExecutablePath;
159 const systemNode = ROOT_PATH_DIRECTORIES.some((directory) =>
160 executablePath.startsWith(`${directory}/`),
161 );
162 return systemNode ? `sudo ${command}` : `sudo env "PATH=$PATH" ${command}`;
163 });
164​
165/** Debian and Ubuntu's sudo `secure_path`, minus snap. */
166const ROOT_PATH_DIRECTORIES = [
167 "/usr/local/sbin",
168 "/usr/local/bin",
169 "/usr/sbin",
170 "/usr/bin",
171 "/sbin",
172 "/bin",
173];