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

invocation.ts

68 lines2.3 KB

1import * as Effect from "effect/Effect";
2​
3import { HostProcessArguments } from "@piku/shared/hostProcess";
4​
5export type CliRunner = "npx" | "pnpm dlx" | "bunx";
6​
7/**
8 * How the CLI was launched, judged by where its entry script lives. Each
9 * package runner executes out of a distinctive cache/temp layout:
10 *
11 * npx ~/.npm/_npx/<hash>/node_modules/...
12 * pnpm dlx ~/.cache/pnpm/dlx/... or $PNPM_HOME/.pnpm/dlx/...
13 * bunx ~/.bun/install/cache/... or $TMPDIR/bunx-<uid>-<spec>/...
14 *
15 * Global installs and repo checkouts match none of these and return null.
16 * Detection is best-effort; callers must fail closed to a plain `piku` command.
17 */
18export function detectCliRunner(entryPath: string): CliRunner | null {
19 const path = entryPath.replaceAll("\\", "/");
20 if (path.includes("/_npx/")) {
21 return "npx";
22 }
23 if (
24 path.includes("/pnpm/dlx/") ||
25 path.includes("/.pnpm/dlx/") ||
26 path.includes("/pnpm-cache/dlx/")
27 ) {
28 return "pnpm dlx";
29 }
30 if (path.includes("/.bun/install/cache/") || path.includes("/bunx-")) {
31 return "bunx";
32 }
33 return null;
35​
36/**
37 * The `piku` package spec to suggest. The literal spec the user typed (e.g.
38 * `piku@nightly`) is resolved away before our process starts, and `nightly` is
39 * the only published dist-tag, so always re-suggest it: a bare `piku` would
40 * resolve through `latest`, which no release publishes.
41 */
42export const SUGGESTED_PACKAGE_SPEC = "piku@nightly";
43​
44/**
45 * Render a `piku <subcommand>` suggestion that matches how this process was
46 * launched, so copy/pasting it actually works: `npx piku connect` suggests
47 * `npx piku@nightly serve`, while a global install suggests a plain
48 * `piku serve` against the already-installed binary.
49 */
50export function formatCliCommand(input: {
51 readonly subcommand: string;
52 readonly entryPath: string;
53}): string {
54 const runner = detectCliRunner(input.entryPath);
55 if (runner === null) {
56 return `piku ${input.subcommand}`;
57 }
58 return `${runner} ${SUGGESTED_PACKAGE_SPEC} ${input.subcommand}`;
60​
61/** `formatCliCommand` against this process's real entry path. */
62export const resolveCliCommand = (subcommand: string) =>
63 Effect.map(HostProcessArguments, (processArguments) =>
64 formatCliCommand({
65 subcommand,
66 entryPath: processArguments[1] ?? "",
67 }),
68 );