import { isNonPrimitive } from '@orpc/shared' import { RECURSIVE_CLIENT_UNWRAP_KEYS } from './consts' import type { AnyNestedClient, Client, ClientRest } from './types' import type { SafeResult } from './utils' import { safe } from './utils' export type SafeClient = SafeClientInternal export type SafeClientInternal = T extends Client ? (...rest: ClientRest) => Promise> : { [K in keyof T]: SafeClientInternal } /** * Create a safe client that automatically wraps all procedure calls with the `safe` util. * * @example * ```ts * const safeClient = createSafeClient(client) * const { error, data, definedError, isSuccess } = await safeClient.doSomething({ id: '123' }) * // or const [error, data, definedError, isSuccess] = await safeClient.doSomething({ id: '123' }) * ``` * * @see {@link https://orpc.dev/docs/client/error-handling#safe-client | Client Error Handling - Safe Client} */ export function createSafeClient(client: T): SafeClient { const cache = new Map>() const proxy = new Proxy((...args: any[]) => safe((client as any)(...args)), { get(target, prop) { if (typeof prop !== 'string' || RECURSIVE_CLIENT_UNWRAP_KEYS.has(prop)) { return Reflect.get(target, prop) } let safeClient = cache.get(prop) if (safeClient === undefined) { const value = (client as Record)[prop] if (!isNonPrimitive(value)) { return value } safeClient = createSafeClient(value as AnyNestedClient) cache.set(prop, safeClient) } return safeClient }, }) return proxy as SafeClient }