mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-18 16:08:56 +00:00
* fix(cli): every --json failure answers with one envelope, and --json only where supported
Under --json, failures came back as a bare string (`"error": "Command failed"`
from lint), a command-specific shape, or nothing at all on stdout (info,
compositions, render, snapshot, cloud get). Now every failure is
`{"ok": false, "error": {"code", "message", "hint"?}}`:
- jsonFailure() in utils/jsonError.ts builds it. The commands that printed
`{ok: false, error: "<text>"}` use it, keeping their extra fields (lint's
findings, validate's errors). A refused timeline edit now writes it to stdout
instead of stderr, and keeps its `reason` and `fix` fields.
- When a --json run fails without writing anything to stdout, cli.ts writes the
envelope itself: usage errors carry their own code (unknown_flag,
unknown_command, json_unsupported, confirmation_required), anything else is
runtime_error with the message the command printed on stderr.
--json is no longer accepted by every command. A command supports it by
declaring a `json` arg; the others reject it with exit 2 and the code
json_unsupported, instead of accepting the flag and printing prose.
The contract test now checks every command's --json path, and packages/cli
gets an AGENTS.md with the rules: stdout is data, stderr is messages, never
prompt without a TTY, exit 2 for usage errors, --json always returns an
envelope.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(cli): put the real failure in the --json envelope, never the generic text or a notice
lint --json and check --json in a directory with no project answered
"message": "Command failed". The project check reports the problem, then
throws a presented "Command failed" with the real error as its cause, and the
command's own catch serialized that generic text. failureMessage() now returns
the cause, or else what the command reported through errorBox, and every
command catch that writes a --json failure uses it (lint, check, validate,
layout, snapshot, compare, grade-compare, media-treatment, tts,
remove-background, add, skills, lambda policies). compare, grade-compare and
add share failCaught() for that catch.
The boundary envelope follows the same order: the error's own message unless
it is the generic one, then its cause, then the errorBox title and hint, and
only then the stderr text. Notices (the telemetry disclosure, deprecation
lines, diag progress) are no longer captured, so validate, layout and inspect
no longer put "is deprecated" in the error message.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(cli): render --json keeps human output off stdout so a failure answers with the envelope
Under --json a single render printed its header, lint findings and progress on
stdout, so a later failure such as `render --variables '{bad' --json` ended
with no JSON envelope. --json now silences that output the way --batch --json
already did, and --variables is parsed before the browser check so a bad value
fails without a Chrome download.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(cli): a --strict lint abort says why, even under --json
Under --json the render is quiet, so a --strict lint abort printed nothing and
the envelope said only "Command failed". The abort is now an error box on
stderr in every mode, naming the error and warning counts and the first
finding, and the --json envelope carries the same message. Lint now runs
before the browser check, so the abort never waits on a Chrome download.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(cli): time the render setup cancel from the wrapper's exit
The 1 s budget started when the command did. With lint now running before the
browser check, its subprocess (about 250 ms here) sat inside that budget, and
the test failed once under load. The budget now starts when the wrapper exits,
which is the latency the test is about.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
263 lines
9.8 KiB
TypeScript
263 lines
9.8 KiB
TypeScript
import { existsSync, readFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { compareVersions } from "compare-versions";
|
|
import { readConfig, readConfigFresh, writeConfig } from "../telemetry/config.js";
|
|
import { VERSION } from "../version.js";
|
|
import { isCI, isUnattended } from "./attendedTerminal.js";
|
|
import { isDevMode } from "./env.js";
|
|
import { asNotice } from "./jsonError.js";
|
|
import { hostAnswers } from "./hostAnswers.js";
|
|
import { detectInstaller } from "./installerDetection.js";
|
|
import { readPinnedHyperframesVersions } from "./projectPin.js";
|
|
import { isSafeVersion } from "./safeVersion.js";
|
|
|
|
export { isSafeVersion } from "./safeVersion.js";
|
|
|
|
const NPM_REGISTRY_URL = "https://registry.npmjs.org/hyperframes/latest";
|
|
const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
|
|
const FETCH_TIMEOUT_MS = 3000;
|
|
|
|
/** Returns true if `a` is newer than `b` per semver (handles alpha, beta, rc). */
|
|
function isNewerSemver(a: string, b: string): boolean {
|
|
try {
|
|
return compareVersions(a, b) > 0;
|
|
} catch {
|
|
return a !== b;
|
|
}
|
|
}
|
|
|
|
export interface UpdateCheckResult {
|
|
current: string;
|
|
latest: string;
|
|
updateAvailable: boolean;
|
|
}
|
|
|
|
export interface UpdateMeta {
|
|
version: string;
|
|
latestVersion?: string;
|
|
updateAvailable: boolean;
|
|
/** Present (and true) only for commands superseded by `check`; absent otherwise. */
|
|
deprecated?: boolean;
|
|
}
|
|
|
|
/**
|
|
* Check npm registry for the latest version. Uses a 24h cache to avoid
|
|
* hitting the registry on every invocation.
|
|
*
|
|
* @param force - Skip the cache, opt-outs and DNS probe: the caller waits for the registry
|
|
*/
|
|
export async function checkForUpdate(force?: boolean): Promise<UpdateCheckResult> {
|
|
const config = readConfig();
|
|
if (!force && !updateCheckDue(config)) return fallbackResult(config.latestVersion);
|
|
|
|
try {
|
|
if (!force && !(await hostAnswers(new URL(NPM_REGISTRY_URL).hostname))) {
|
|
return fallbackResult(config.latestVersion);
|
|
}
|
|
const controller = new AbortController();
|
|
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
let data: { version?: unknown };
|
|
try {
|
|
const res = await fetch(NPM_REGISTRY_URL, {
|
|
signal: controller.signal,
|
|
headers: { Connection: "close" },
|
|
});
|
|
if (!res.ok) return fallbackResult(config.latestVersion);
|
|
data = (await res.json()) as { version?: unknown };
|
|
} finally {
|
|
clearTimeout(timeout);
|
|
}
|
|
// Registry boundary guard: only a strict-semver STRING is trusted. This
|
|
// value is cached and later flows into an install command that the
|
|
// background auto-updater executes, so a poisoned or non-string
|
|
// data.version (e.g. "1.2.3; rm -rf /") must never be persisted. Reject it
|
|
// and fall back to the last known-good version. Closes the injection class
|
|
// for every consumer at one point.
|
|
if (typeof data.version !== "string" || !isSafeVersion(data.version)) {
|
|
return fallbackResult(config.latestVersion);
|
|
}
|
|
const latest = data.version;
|
|
|
|
// The registry request can take seconds. Merge its two metadata fields
|
|
// into a fresh snapshot rather than writing the object captured before
|
|
// the network call: the stale object previously reverted a concurrent
|
|
// `telemetry disable` back to the default `true`.
|
|
const freshConfig = readConfigFresh();
|
|
freshConfig.lastUpdateCheck = new Date().toISOString();
|
|
freshConfig.latestVersion = latest;
|
|
writeConfig(freshConfig);
|
|
|
|
return { current: VERSION, latest, updateAvailable: isNewerSemver(latest, VERSION) };
|
|
} catch {
|
|
return fallbackResult(config.latestVersion);
|
|
}
|
|
}
|
|
|
|
/** Whether the background check should ask the registry: not opted out, and no fresh safe cache. */
|
|
export function updateCheckDue(config = readConfig()): boolean {
|
|
if (updateCheckDisabled()) return false;
|
|
if (!config.lastUpdateCheck || !config.latestVersion || !isSafeVersion(config.latestVersion)) {
|
|
return true;
|
|
}
|
|
const fresh = Date.now() - new Date(config.lastUpdateCheck).getTime() < CHECK_INTERVAL_MS;
|
|
return !fresh;
|
|
}
|
|
|
|
export function cachedUpdateCheck(): UpdateCheckResult {
|
|
return fallbackResult(readConfig().latestVersion);
|
|
}
|
|
|
|
function fallbackResult(cachedLatest?: string): UpdateCheckResult {
|
|
// Only surface a cached version we can prove is safe — a pre-existing
|
|
// poisoned cache must not leak through the fallback path either.
|
|
const safeCached = safeCachedVersion(cachedLatest);
|
|
return {
|
|
current: VERSION,
|
|
latest: safeCached ?? VERSION,
|
|
updateAvailable: safeCached ? isNewerSemver(safeCached, VERSION) : false,
|
|
};
|
|
}
|
|
|
|
function safeCachedVersion(value: unknown): string | undefined {
|
|
return typeof value === "string" && isSafeVersion(value) ? value : undefined;
|
|
}
|
|
|
|
/**
|
|
* Synchronous read from cache — for _meta envelope on --json commands.
|
|
* Never fetches. Returns what the last background check found.
|
|
*/
|
|
export function getUpdateMeta(): UpdateMeta {
|
|
const latestVersion = safeCachedVersion(readConfig().latestVersion);
|
|
return {
|
|
version: VERSION,
|
|
latestVersion,
|
|
updateAvailable: latestVersion ? isNewerSemver(latestVersion, VERSION) : false,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Wrap a JSON payload with the _meta version envelope.
|
|
* Use this in all --json command outputs for consistent agent-friendly metadata.
|
|
*
|
|
* Pass `{ deprecated: true }` from a command superseded by `check` (validate,
|
|
* inspect, layout) to add `_meta.deprecated: true`; every other call site is
|
|
* unaffected — the key is only ever added, never set to `false`.
|
|
*/
|
|
export function withMeta<T extends object>(
|
|
data: T,
|
|
options?: { deprecated?: boolean },
|
|
): T & { _meta: UpdateMeta } {
|
|
const meta = getUpdateMeta();
|
|
if (options?.deprecated) meta.deprecated = true;
|
|
return { ...data, _meta: meta };
|
|
}
|
|
|
|
/**
|
|
* One-line deprecation notice for a command superseded by `check`. Always
|
|
* writes to stderr (never stdout), so a --json invocation's stdout stays
|
|
* pure, parseable JSON. Call once per invocation, before the command's own
|
|
* output.
|
|
*/
|
|
export function printDeprecationNotice(command: string): void {
|
|
asNotice(() =>
|
|
process.stderr.write(
|
|
`'hyperframes ${command}' is deprecated and will be removed in a future release. Use 'hyperframes check' instead.\n`,
|
|
),
|
|
);
|
|
}
|
|
|
|
/** True when the update check is off: dev mode, CI, or the HYPERFRAMES_NO_UPDATE_CHECK opt-out. */
|
|
export function updateCheckDisabled(): boolean {
|
|
if (isDevMode()) return true;
|
|
if (isCI()) return true;
|
|
return process.env["HYPERFRAMES_NO_UPDATE_CHECK"] === "1";
|
|
}
|
|
|
|
/**
|
|
* True when update / freshness notices should stay silent: the check is off or stderr is not a
|
|
* terminal. Shared with the skills freshness notice so both honour the same gating.
|
|
*/
|
|
export function updateNoticesSuppressed(): boolean {
|
|
return updateCheckDisabled() || !process.stderr.isTTY || isUnattended();
|
|
}
|
|
|
|
/**
|
|
* Print update notice to stderr if a newer version is available.
|
|
* Skipped in CI, non-TTY, dev mode, or when HYPERFRAMES_NO_UPDATE_CHECK is set.
|
|
*/
|
|
export function printUpdateNotice(): void {
|
|
if (updateNoticesSuppressed()) return;
|
|
|
|
const meta = getUpdateMeta();
|
|
if (!meta.updateAvailable || !meta.latestVersion) return;
|
|
if (readConfig().pendingUpdate?.version === meta.latestVersion) return;
|
|
|
|
// Show the command that updates *this* install: the detected package
|
|
// manager's upgrade for owned global installs (npm/bun/pnpm/brew), and the
|
|
// universal `npx hyperframes@latest` for ephemeral/unknown installs (where a
|
|
// manager command wouldn't apply). detectInstaller() only runs here, after
|
|
// the suppression + update-available gates, so it adds no cost to normal runs.
|
|
const safeLatest = isSafeVersion(meta.latestVersion);
|
|
const managerCommand = safeLatest ? detectInstaller().installCommand(meta.latestVersion) : null;
|
|
const command = managerCommand ?? "npx hyperframes@latest";
|
|
|
|
process.stderr.write(
|
|
`\n Update available: ${meta.version} \u2192 ${meta.latestVersion}\n` +
|
|
` Run: ${command}\n\n`,
|
|
);
|
|
}
|
|
|
|
const STALE_PIN_THROTTLE_MS = 24 * 60 * 60 * 1000;
|
|
|
|
/**
|
|
* Actionable notice when the running CLI is older than the project's pin (every
|
|
* run), or when the pin is older than the latest release (once/24h per install).
|
|
* Unlike printUpdateNotice this DOES fire on non-TTY (agents render with piped
|
|
* stderr), but never under --json/CI/dev/opt-out: the whole cli.ts update block
|
|
* is skipped for --json, so a JSON stdout stays clean regardless.
|
|
*/
|
|
export function printStalePinNotice(cwd: string = process.cwd()): void {
|
|
if (updateCheckDisabled()) return;
|
|
|
|
let scripts: Record<string, string> = {};
|
|
try {
|
|
const pkgPath = join(cwd, "package.json");
|
|
if (!existsSync(pkgPath)) return;
|
|
scripts = (JSON.parse(readFileSync(pkgPath, "utf-8")).scripts ?? {}) as Record<string, string>;
|
|
} catch {
|
|
return;
|
|
}
|
|
const pins = readPinnedHyperframesVersions(scripts);
|
|
// A CLI older than the pin (e.g. a stale npx cache) misjudges every run, so this is never throttled.
|
|
const newerPins = pins.filter((v) => isNewerSemver(v, VERSION)).sort(compareVersions);
|
|
if (newerPins.length > 0) {
|
|
process.stderr.write(
|
|
`\n This is hyperframes ${VERSION}, but this project pins hyperframes@${newerPins.join(", ")}.\n` +
|
|
` Run it through the project's npm scripts, or npx hyperframes@${newerPins.at(-1)}.\n\n`,
|
|
);
|
|
return;
|
|
}
|
|
|
|
const latest = getUpdateMeta().latestVersion;
|
|
if (!latest || !isSafeVersion(latest)) return;
|
|
const stale = pins.filter((v) => {
|
|
try {
|
|
return compareVersions(latest, v) > 0;
|
|
} catch {
|
|
return false;
|
|
}
|
|
});
|
|
if (stale.length === 0) return;
|
|
|
|
const last = readConfig().lastStalePinNoticeAt ?? 0;
|
|
if (Date.now() - last < STALE_PIN_THROTTLE_MS) return;
|
|
const config = readConfigFresh();
|
|
config.lastStalePinNoticeAt = Date.now();
|
|
writeConfig(config);
|
|
|
|
process.stderr.write(
|
|
`\n This project pins hyperframes@${stale.join(", ")} (latest ${latest}).\n` +
|
|
` Bump it: npx hyperframes@latest upgrade --project\n\n`,
|
|
);
|
|
}
|