@mesh-tech/mesh-cli
Version:
CLI for Mesh platform development utilities
58 lines (57 loc) • 1.88 kB
JavaScript
import chalk from "chalk";
export class MeshCliError extends Error {
remediation;
exitCode;
constructor(message, options = {}) {
super(message, options.cause !== undefined ? { cause: options.cause } : undefined);
this.name = "MeshCliError";
this.remediation = options.remediation;
this.exitCode = options.exitCode ?? 1;
}
}
export function renderErrorBody(err) {
const message = err instanceof Error ? err.message : String(err);
if (!(err instanceof MeshCliError))
return message;
const lines = [message];
if (err.remediation?.command) {
lines.push(chalk.cyan(" → run: ") + err.remediation.command);
}
if (err.remediation?.docs) {
lines.push(chalk.cyan(" → see: ") + err.remediation.docs);
}
return lines.join("\n");
}
export function renderError(err) {
return chalk.red("✗") + " " + renderErrorBody(err);
}
export function renderErrorJson(err) {
if (err instanceof MeshCliError) {
return JSON.stringify({
error: err.message,
...(err.remediation ? { remediation: err.remediation } : {}),
});
}
return JSON.stringify({ error: err instanceof Error ? err.message : String(err) });
}
let jsonPayloadEmitted = false;
export function emitJsonPayload(payload) {
console.log(JSON.stringify(payload, null, 2));
jsonPayloadEmitted = true;
}
export function hasEmittedJsonPayload() {
return jsonPayloadEmitted;
}
export function resetJsonPayloadEmitted() {
jsonPayloadEmitted = false;
}
export function handleCliError(err) {
const wantsJson = process.argv.includes("--json");
if (wantsJson && !hasEmittedJsonPayload()) {
console.log(renderErrorJson(err));
}
else {
console.error(renderError(err));
}
process.exit(err instanceof MeshCliError ? err.exitCode : 1);
}