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

invocation.ts

76 lines2.6 KB

1import * as Effect from "effect/Effect";
2​
3import { HostProcessArguments } from "@t3tools/shared/hostProcess";
4​
5import packageJson from "../../package.json" with { type: "json" };
6​
7export type CliRunner = "npx" | "pnpm dlx" | "bunx";
8​
9/**
10 * How the CLI was launched, judged by where its entry script lives. Each
11 * package runner executes out of a distinctive cache/temp layout:
12 *
13 * npx ~/.npm/_npx/<hash>/node_modules/...
14 * pnpm dlx ~/.cache/pnpm/dlx/..., $PNPM_HOME/.pnpm/dlx/...,
15 * or %LOCALAPPDATA%/pnpm-cache/dlx/... on Windows
16 * bunx ~/.bun/install/cache/... or $TMPDIR/bunx-<uid>-<spec>/...
17 *
18 * Global installs and repo checkouts match none of these and return null.
19 * Detection is best-effort; callers must fail closed to a plain `t3` command.
20 */
21function detectCliRunner(entryPath: string): CliRunner | null {
22 const path = entryPath.replaceAll("\\", "/");
23 if (path.includes("/_npx/")) {
24 return "npx";
25 }
26 if (
27 path.includes("/pnpm/dlx/") ||
28 path.includes("/.pnpm/dlx/") ||
29 path.includes("/pnpm-cache/dlx/")
30 ) {
31 return "pnpm dlx";
32 }
33 if (path.includes("/.bun/install/cache/") || path.includes("/bunx-")) {
34 return "bunx";
35 }
36 return null;
38​
39/**
40 * The `t3` package spec to suggest. The literal spec the user typed (e.g.
41 * `t3@nightly`) is resolved away before our process starts, so re-derive it
42 * from the running version: nightly builds re-suggest the nightly channel,
43 * anything else suggests the bare package.
44 */
45function suggestedPackageSpec(version: string): string {
46 const channel = /^[^-+]+-(nightly|preview)\./.exec(version)?.[1];
47 return channel === undefined ? "t3" : `t3@${channel}`;
49​
50/**
51 * Render a `t3 <subcommand>` suggestion that matches how this process was
52 * launched, so copy/pasting it actually works: `npx t3 connect` suggests
53 * `npx t3 serve`, a global install suggests `t3 serve`, and a nightly build
54 * keeps the `@nightly` tag.
55 */
56export function formatCliCommand(input: {
57 readonly subcommand: string;
58 readonly entryPath: string;
59 readonly version: string;
60}): string {
61 const runner = detectCliRunner(input.entryPath);
62 if (runner === null) {
63 return `t3 ${input.subcommand}`;
64 }
65 return `${runner} ${suggestedPackageSpec(input.version)} ${input.subcommand}`;
67​
68/** `formatCliCommand` against this process's real entry path and version. */
69export const resolveCliCommand = (subcommand: string) =>
70 Effect.map(HostProcessArguments, (processArguments) =>
71 formatCliCommand({
72 subcommand,
73 entryPath: processArguments[1] ?? "",
74 version: packageJson.version,
75 }),
76 );