59 lines
1.9 KiB
TypeScript
59 lines
1.9 KiB
TypeScript
export type CliExitCode = 1 | 2 | 10 | 11 | 12;
|
|
|
|
export class CliError extends Error {
|
|
readonly exitCode: CliExitCode;
|
|
readonly nextAction?: string;
|
|
|
|
constructor(message: string, exitCode: CliExitCode, nextAction?: string) {
|
|
super(message);
|
|
this.name = "CliError";
|
|
this.exitCode = exitCode;
|
|
this.nextAction = nextAction;
|
|
}
|
|
}
|
|
|
|
export class PayloadTooLargeError extends CliError {
|
|
constructor(message: string, nextAction?: string) {
|
|
super(message, 12, nextAction);
|
|
this.name = "PayloadTooLargeError";
|
|
}
|
|
}
|
|
|
|
export function usageError(message: string, nextAction?: string): CliError {
|
|
return new CliError(message, 2, nextAction);
|
|
}
|
|
|
|
export function confirmationRequired(message: string, nextAction: string): CliError {
|
|
return new CliError(message, 10, nextAction);
|
|
}
|
|
|
|
export function classifyCliError(error: unknown): {
|
|
exitCode: CliExitCode;
|
|
nextAction?: string;
|
|
} {
|
|
if (error instanceof CliError) {
|
|
return { exitCode: error.exitCode, nextAction: error.nextAction };
|
|
}
|
|
|
|
const value = error instanceof Error ? error.message : String(error);
|
|
const status = responseStatus(error);
|
|
if (status === 401 || status === 403 || /(?:^|\s)(?:token|bearer|session) (?:expired|missing|invalid)/i.test(value)) {
|
|
return { exitCode: 11 };
|
|
}
|
|
if (/^(?:Usage:|Unknown (?:[a-z0-9_-]+ )?command|Invalid (?:number|boolean|command)|--json must|Missing required JSON field)/i.test(value)) {
|
|
return { exitCode: 2 };
|
|
}
|
|
if (/^Refusing to (?:clear|delete)|without --yes|without confirm=true/i.test(value)) {
|
|
return { exitCode: 10 };
|
|
}
|
|
return { exitCode: 1 };
|
|
}
|
|
|
|
function responseStatus(error: unknown): number | undefined {
|
|
if (!error || typeof error !== "object") return undefined;
|
|
const response = (error as { response?: unknown }).response;
|
|
if (!response || typeof response !== "object") return undefined;
|
|
const status = (response as { status?: unknown }).status;
|
|
return typeof status === "number" ? status : undefined;
|
|
}
|