// Single responsibility: `UltimateError` — the one error type every Ultimate package throws. // Stable code + cause + exact fix command, rendered identically in the terminal, the browser // overlay and `--json`. Never throw a bare Error anywhere in the framework. /** * Structural brand. `instanceof` is unreliable across duplicated module instances, so the guard is * duck-typed on a well-known symbol instead. It is `@ultimat3/schema`'s — declared once, at the * tier both error classes can reach (`core -> schema` is the declared edge) — and imported from * there by anything that needs the symbol itself: core does not publish it a second time. */ import { ULTIMATE_ERROR_BRAND } from '@ultimat3/schema'; import { describeErrorCode, hasErrorCode } from './error-codes'; import { boundedCause, isThrownError, renderCauseValue, renderMetaRecord, renderThrowable, singleLine, } from './error-render'; import { DEFAULT_ERROR_RETRY, type ErrorRetry, isErrorRetry, retryFor } from './error-retry'; export interface UltimateErrorInit { /** `SCREAMING_SNAKE`, prefixed `X_`. Must exist in the code registry to get a title. */ readonly code: string; /** What actually happened, concrete and specific. Never a generic sentence. */ readonly cause: string; /** The exact command or edit that fixes it. */ readonly fix: string; /** * The fix for a REMOTE caller — an agent over MCP, a client reading a problem document — when * `fix` names something only the app's developer can do (`x policy explain`, an edit to a * declaration). Omitted, every surface reads `fix`. The developer's `fix` is never replaced: the * terminal, the log line and `--json` keep it, and a dev-mode problem document does too. */ readonly callerFix?: string | undefined; /** * Where the reader goes next. Defaults to the code's registered page. An app may point it at its * own guide — `docs://recipes/refund-a-payment` — and `@ultimat3/mcp` then prints it as a fourth * `docs:` line in the tool result, the moment the agent is stuck. */ readonly docs?: string | undefined; readonly meta?: Readonly> | undefined; /** * Overrides the code's registered classification for this one throw — the same code can be * transient at one call site and permanent at another. Defaults to `retryFor(code)`, which * defaults to `terminal`. */ readonly retry?: ErrorRetry | undefined; /** The underlying thrown value, when this error wraps one. */ readonly sourceError?: unknown; /** * A title off the WIRE — a problem document's `title` — used only when this realm registered * none for `code`. A browser rebuilds a server's refusal by code and may never have loaded the * package that titles it; the registry still wins wherever it has an answer, so a server can * never retitle a code this realm owns. Untrusted display text: the decoder caps it, and the * constructor makes it one line like every other field. */ readonly remoteTitle?: string | undefined; } export interface UltimateErrorJSON { readonly code: string; readonly title: string; readonly cause: string; readonly fix: string; /** Present only when the error declared one. See `UltimateErrorInit.callerFix`. */ readonly callerFix?: string | undefined; readonly docs: string; /** Whether a client may try again. Always present — a client never has to infer it. */ readonly retry: ErrorRetry; readonly meta?: Readonly> | undefined; readonly stack?: string | undefined; } /** * Who reads a rendering. `'developer'` (the default) is the terminal, a log line, `--json`: the * `fix` the author wrote. `'caller'` is a remote client that cannot run the app's CLI — an MCP * tool result, a production problem document: `callerFix` when the error declared one, else `fix`. */ export type ErrorAudience = 'developer' | 'caller'; export interface FormatErrorOptions { /** Append a 4th `docs:` line. Off by default — the contract's rendering is 3 lines. */ readonly docs?: boolean | undefined; /** Whose fix the `fix:` line carries. See `ErrorAudience`. */ readonly audience?: ErrorAudience | undefined; } /** The fix line a reader of `audience` is given: `callerFix` for a caller when one exists. */ export function fixFor( error: { readonly fix: string; readonly callerFix?: string | undefined }, audience: ErrorAudience | undefined, ): string { return audience === 'caller' && error.callerFix !== undefined ? error.callerFix : error.fix; } export class UltimateError extends Error { readonly [ULTIMATE_ERROR_BRAND] = true; override readonly name: string = 'UltimateError'; readonly code: string; readonly title: string; /** Set by `Error`'s `cause` option; always a human-readable string in Ultimate. */ declare readonly cause: string; readonly fix: string; readonly callerFix: string | undefined; readonly docs: string; readonly retry: ErrorRetry; readonly meta: Readonly> | undefined; readonly sourceError: unknown; constructor(init: UltimateErrorInit) { const described = describeErrorCode(init.code); // Every line-bearing field is escaped HERE, once, and never again downstream. A `cause` is a // single line by contract, and a caller controls one often enough to matter: `claims.iss` off // an unverified JWT, an IdP's `error_description`, a forwarded IP. One newline in any of them // writes a second line an operator, a CI log or a `
` reads as a genuine framework
    // message. Escaping at each RENDERER was the first fix and it cannot hold — it is six call
    // sites today, a seventh whenever someone writes one, and zero of the renderers an APP writes.
    // Escaping at construction is the one place that covers all of them, and it is what #97 called
    // the real answer. `singleLine` is idempotent, so a call site that already escaped is unharmed.
    const code = singleLine(init.code);
    const remote = init.remoteTitle !== undefined && !hasErrorCode(init.code);
    const title = singleLine(remote ? (init.remoteTitle ?? described.title) : described.title);
    // Bounded after escaping: the cap is on what is WRITTEN, and an escape only ever grows it.
    const cause = boundedCause(singleLine(init.cause));
    // `message` carries the cause because it is the ONLY field a runtime prints when an
    // error escapes uncaught — a worker log, a CI transcript, a stack trace. A message of
    // just `code: title` tells an operator which rule fired but not which row, column or
    // value, which is the opposite of "errors are instructions". `format()` still renders
    // the canonical 3 lines from the fields, so the two never disagree.
    super(`${code}: ${title} — ${cause}`, { cause });
    this.code = code;
    this.title = title;
    this.fix = singleLine(init.fix);
    this.callerFix = init.callerFix === undefined ? undefined : singleLine(init.callerFix);
    this.docs = singleLine(init.docs ?? described.docs);
    this.retry = init.retry ?? retryFor(init.code);
    this.meta = init.meta;
    this.sourceError = init.sourceError;
  }

  /**
   * The canonical 3-line terminal rendering:
   *
   * ```text
   * X_DB_DRIFT: schema differs from migrations
   *   cause: table "posts" has column "publish_at" not present in any migration
   *   fix:   x db gen "add publish_at"
   * ```
   */
  format(options?: FormatErrorOptions): string {
    // No `singleLine` here. The constructor already escaped all five fields, so a second pass
    // would be a second place that has to be right — and the one that gets forgotten. This method
    // is line-oriented and stays exactly 3 lines (4 with `docs`) because the fields cannot carry
    // a line break, not because this joiner removes them.
    const fix = fixFor(this, options?.audience);
    const lines = [`${this.code}: ${this.title}`, `  cause: ${this.cause}`, `  fix:   ${fix}`];
    if (options?.docs === true) lines.push(`  docs:  ${this.docs}`);
    return lines.join('\n');
  }

  /**
   * `meta` is the only field here the framework does not build itself — `parseId` puts the value
   * it rejected straight in — so it goes through `renderMetaRecord`, which returns a record that
   * serialises unchanged and degrades only the keys that would have thrown. `--json` on every
   * error is a promise this method keeps; a `meta` that throws breaks it one layer past the
   * constructor.
   */
  toJSON(): UltimateErrorJSON {
    return {
      code: this.code,
      title: this.title,
      cause: this.cause,
      fix: this.fix,
      ...(this.callerFix === undefined ? {} : { callerFix: this.callerFix }),
      docs: this.docs,
      retry: this.retry,
      meta: renderMetaRecord(this.meta),
      stack: this.stack,
    };
  }
}

export function isUltimateError(value: unknown): value is UltimateError {
  // TOTAL, like `isThrownError`: `in` runs a `Proxy`'s `has` trap, and every caller asks this
  // question inside a `catch` block that has nothing left to answer with if the probe itself
  // throws. `false` is the honest answer for a value that refuses to be examined.
  try {
    return typeof value === 'object' && value !== null && ULTIMATE_ERROR_BRAND in value;
  } catch {
    return false;
  }
}

/**
 * The `callerFix` of an authorization denial (`X_FORBIDDEN`), ONE sentence for the five packages
 * that refuse one — policy, action, query, auth, http — so a remote caller reads the same
 * instruction whichever layer said no. A permission is granted by whoever administers the account,
 * never by retrying, and saying so is what stops an agent looping on a refusal. `permission`, when
 * the denial names a bare `resource:verb`, is what to ask for.
 */
export function deniedCallerFix(permission?: string): string {
  const ask =
    permission === undefined
      ? 'this caller is not permitted to do this: ask the account owner or an administrator for access'
      : `this caller lacks the permission ${permission}: ask the account owner or an administrator to grant it`;
  return `${ask}, or call with credentials that have it — retrying the same call is refused the same way`;
}

/** Init for a subclass that owns its code. */
export type CodedErrorInit = Omit;

export class ConfigInvalidError extends UltimateError {
  static readonly code = 'X_CONFIG_INVALID';
  override readonly name = 'ConfigInvalidError';
  constructor(init: CodedErrorInit) {
    super({ ...init, code: ConfigInvalidError.code });
  }
}

export class EnvMissingError extends UltimateError {
  static readonly code = 'X_ENV_MISSING';
  override readonly name = 'EnvMissingError';
  constructor(init: CodedErrorInit) {
    super({ ...init, code: EnvMissingError.code });
  }
}

export class NotImplementedError extends UltimateError {
  static readonly code = 'X_NOT_IMPLEMENTED';
  override readonly name = 'NotImplementedError';
  constructor(init: CodedErrorInit) {
    super({ ...init, code: NotImplementedError.code });
  }
}

export class InternalError extends UltimateError {
  static readonly code = 'X_INTERNAL';
  override readonly name = 'InternalError';
  constructor(init: CodedErrorInit) {
    super({ ...init, code: InternalError.code });
  }
}

/** The blessed shape for an unimplemented remote driver. Always carries a real fix line. */
export function notImplemented(feature: string, fix: string): never {
  throw new NotImplementedError({ cause: `${feature} is not implemented by this driver`, fix });
}

/**
 * Normalise anything caught into an `UltimateError` without losing the original.
 *
 * `renderCauseValue`, not `String(value)`: this is the framework's universal normaliser — the CLI's
 * every catch, `formatError`, the HTTP 500 path — and `String()` runs the value's own `toString`,
 * so a thrown object could make the wrapper throw and take both errors with it.
 */
export function toUltimateError(value: unknown, fix?: string): UltimateError {
  if (isUltimateError(value)) return value;
  // `isThrownError` / `renderThrowable`, not `instanceof` and `.message` directly: a `Proxy` traps
  // `getPrototypeOf` and a subclass can put a getter on `message`, so both reads throw where this
  // function is the last thing standing between a caught value and a surface that must answer.
  const cause = isThrownError(value)
    ? renderThrowable(value)
    : `non-error value thrown: ${renderCauseValue(value)}`;
  return new InternalError({
    cause,
    fix: fix ?? 'fix the underlying failure named in cause, then re-run',
    sourceError: value,
  });
}

/**
 * May a client try this again? The one question a retry loop asks, answered from the error rather
 * than from a status code — `X_DB_DRIFT` and `X_TENANCY_UNSCOPED` are both 500s and neither is
 * worth a second attempt. A value that is not an Ultimate error is `terminal`: fail closed.
 */
export function errorRetry(value: unknown): ErrorRetry {
  if (!isUltimateError(value)) return DEFAULT_ERROR_RETRY;
  // Read defensively: the brand is duck-typed across duplicated module instances, so a value from
  // an older copy of this package can satisfy the guard without carrying the field.
  const retry: unknown = value.retry;
  return isErrorRetry(retry) ? retry : DEFAULT_ERROR_RETRY;
}

/** Render any caught value with the 3-line contract, so CLI output never varies. */
export function formatError(value: unknown, options?: FormatErrorOptions): string {
  return toUltimateError(value).format(options);
}