import type { Writable } from '@orpc/shared' import { isPlainObject } from '@orpc/shared' import type { AnyORPCError, ORPCErrorCode, ORPCErrorJSON } from './error' import { ORPCError } from './error' /** * Checks if an error is an `ORPCError` that matches a definition in the procedure's `.errors` map, * narrowing it so `code` and `data` are fully typed. * * @see {@link https://orpc.dev/docs/client/error-handling#using-safe-and-isdefinederror | Client Error Handling - Using safe and isDefinedError} */ export function isDefinedError(error: T): error is Extract { return error instanceof ORPCError && error.defined } export function toORPCError( error: T, ): Extract | ORPCError<'INTERNAL_SERVER_ERROR', undefined> { return error instanceof ORPCError ? error : new ORPCError('INTERNAL_SERVER_ERROR', { cause: error }) } export function isORPCErrorJson(json: unknown): json is ORPCErrorJSON { if (!isPlainObject(json)) { return false } const validKeys = ['defined', 'code', 'message', 'data'] if (Object.keys(json).some((k) => !validKeys.includes(k))) { return false } return ( 'defined' in json && typeof json.defined === 'boolean' && 'code' in json && typeof json.code === 'string' && 'message' in json && typeof json.message === 'string' ) } export function createORPCErrorFromJson( json: ORPCErrorJSON, options: ErrorOptions = {}, ): ORPCError { const error = new ORPCError(json.code, { ...json, ...options, }) ;(error.defined as Writable) = json.defined return error } /** * Clones an `ORPCError` while preserving its prototype chain, so instances of * `ORPCError` subclasses remain `instanceof` their class. * * Limitation: subclass constructors are not re-run, so private fields * (`#field`) are not carried over and subclass members that read them * will throw on the clone. */ export function cloneORPCError(error: T): T { const cloned = new ORPCError(error.code, { message: error.message, data: error.data, cause: error.cause, }) Object.setPrototypeOf(cloned, Object.getPrototypeOf(error)) Object.defineProperties(cloned, Object.getOwnPropertyDescriptors(error)) cloned.stack = error.stack return cloned as T }