|
| 1 | +import { execFile } from "node:child_process"; |
| 2 | +import { promisify } from "node:util"; |
| 3 | + |
| 4 | +import boxen from "boxen"; |
| 5 | +import chalk from "chalk"; |
| 6 | +import semverGt from "semver/functions/gt.js"; |
| 7 | +// @types/update-notifier@6 targets v6 but the API surface we use is unchanged |
| 8 | +// in v7. No v7-aligned types exist on DefinitelyTyped as of 2026-03. |
| 9 | +import updateNotifier from "update-notifier"; |
| 10 | + |
| 11 | +import { CliError } from "./errors.js"; |
| 12 | +import { getSpinner } from "./utils/cli-env.js"; |
| 13 | +import { |
| 14 | + BIN_NAME, |
| 15 | + COMMAND_NAME, |
| 16 | + IS_NPX, |
| 17 | + PACKAGE_NAME, |
| 18 | + PACKAGE_VERSION, |
| 19 | +} from "./utils/command-info.js"; |
| 20 | + |
| 21 | +const execFileAsync = promisify(execFile); |
| 22 | + |
| 23 | +const ONE_DAY_MS = 86_400_000; |
| 24 | + |
| 25 | +let updateCheckDone = false; |
| 26 | + |
| 27 | +/** |
| 28 | + * Check for a newer version in the background and register an on-exit |
| 29 | + * notification to stderr. Fully fire-and-forget: errors are silently ignored |
| 30 | + * so normal CLI operation is never affected. |
| 31 | + * |
| 32 | + * The constructor creates a configstore and the background check process. |
| 33 | + * `check()` reads the cached result into `notifier.update` and, if the check |
| 34 | + * interval has elapsed, spawns a new background process for next time. |
| 35 | + * |
| 36 | + * We write to stderr (not stdout) so piped output stays clean, and we check |
| 37 | + * `process.stderr.isTTY` rather than stdout because notifications should |
| 38 | + * still appear when stdout is piped (e.g. `iterable users list | jq .`). |
| 39 | + * |
| 40 | + * CI, NO_UPDATE_NOTIFIER, and NODE_ENV=test suppression are handled |
| 41 | + * internally by update-notifier (notifier.config will be undefined). |
| 42 | + */ |
| 43 | +export function checkForUpdate(): void { |
| 44 | + if (updateCheckDone) return; |
| 45 | + updateCheckDone = true; |
| 46 | + |
| 47 | + try { |
| 48 | + if (IS_NPX) return; |
| 49 | + if (!process.stderr.isTTY) return; |
| 50 | + |
| 51 | + const notifier = updateNotifier({ |
| 52 | + pkg: { name: PACKAGE_NAME, version: PACKAGE_VERSION }, |
| 53 | + updateCheckInterval: ONE_DAY_MS, |
| 54 | + }); |
| 55 | + |
| 56 | + notifier.check(); |
| 57 | + |
| 58 | + if (!notifier.update) return; |
| 59 | + if (!semverGt(notifier.update.latest, PACKAGE_VERSION)) return; |
| 60 | + |
| 61 | + const message = |
| 62 | + `Update available: ${chalk.dim(notifier.update.current)} ${chalk.reset("→")} ${chalk.green(notifier.update.latest)}\n` + |
| 63 | + `Run ${chalk.cyan(`${COMMAND_NAME} update`)} to update`; |
| 64 | + |
| 65 | + const box = boxen(message, { |
| 66 | + padding: 1, |
| 67 | + margin: { top: 1, bottom: 0 }, |
| 68 | + borderStyle: "round", |
| 69 | + borderColor: "yellow", |
| 70 | + textAlignment: "center", |
| 71 | + }); |
| 72 | + |
| 73 | + process.on("exit", () => { |
| 74 | + try { |
| 75 | + process.stderr.write(`${box}\n`); |
| 76 | + } catch { |
| 77 | + // Best-effort; swallow write errors at exit (e.g. EPIPE) |
| 78 | + } |
| 79 | + }); |
| 80 | + } catch { |
| 81 | + // Never let the update check interfere with normal operation |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +/** |
| 86 | + * Self-upgrade: detect the package manager and run a global install of the |
| 87 | + * latest version. |
| 88 | + */ |
| 89 | +export async function handleUpdateCommand(): Promise<void> { |
| 90 | + if (IS_NPX) { |
| 91 | + // eslint-disable-next-line no-console |
| 92 | + console.error( |
| 93 | + chalk.yellow( |
| 94 | + "You're running via npx, which always fetches the latest version.\n" + |
| 95 | + `Run ${chalk.cyan(`npm install -g ${PACKAGE_NAME}`)} to install permanently.` |
| 96 | + ) |
| 97 | + ); |
| 98 | + return; |
| 99 | + } |
| 100 | + |
| 101 | + const { getUserAgent } = await import("package-manager-detector/detect"); |
| 102 | + const { resolveCommand } = await import("package-manager-detector/commands"); |
| 103 | + |
| 104 | + // npm_config_user_agent is only set when invoked through a package manager. |
| 105 | + // When the user runs the globally-installed binary directly, this falls back |
| 106 | + // to npm. If they installed via pnpm/yarn, the upgrade may go to npm's |
| 107 | + // global prefix instead — the spinner shows the exact command being run so |
| 108 | + // the user can verify. |
| 109 | + const agent = getUserAgent() ?? "npm"; |
| 110 | + |
| 111 | + const resolved = resolveCommand(agent, "global", [`${PACKAGE_NAME}@latest`]); |
| 112 | + if (!resolved) { |
| 113 | + throw new CliError( |
| 114 | + `Could not determine install command for package manager "${agent}".` |
| 115 | + ); |
| 116 | + } |
| 117 | + |
| 118 | + const spinner = await getSpinner(); |
| 119 | + const cmdStr = `${resolved.command} ${resolved.args.join(" ")}`; |
| 120 | + spinner.start(`Upgrading ${PACKAGE_NAME} (${cmdStr})...`); |
| 121 | + |
| 122 | + try { |
| 123 | + // shell: true is required on Windows where npm/pnpm/yarn are .cmd shims |
| 124 | + await execFileAsync(resolved.command, resolved.args, { shell: true }); |
| 125 | + |
| 126 | + let versionLine = "Upgrade complete"; |
| 127 | + try { |
| 128 | + const { stdout } = await execFileAsync(BIN_NAME, ["--version"], { |
| 129 | + shell: true, |
| 130 | + }); |
| 131 | + versionLine = `Upgraded to ${stdout.trim()}`; |
| 132 | + } catch { |
| 133 | + // Binary may not be on PATH yet; that's fine |
| 134 | + } |
| 135 | + spinner.succeed(versionLine); |
| 136 | + } catch (error: unknown) { |
| 137 | + spinner.fail("Upgrade failed"); |
| 138 | + |
| 139 | + if ( |
| 140 | + error instanceof Error && |
| 141 | + "code" in error && |
| 142 | + (error as NodeJS.ErrnoException).code === "EACCES" |
| 143 | + ) { |
| 144 | + throw new CliError( |
| 145 | + "Permission denied. Try running with sudo or fix your global npm prefix permissions." |
| 146 | + ); |
| 147 | + } |
| 148 | + throw new CliError(error instanceof Error ? error.message : String(error)); |
| 149 | + } |
| 150 | +} |
0 commit comments