import type { Call } from '@astrale-os/sdk/client' import type { SessionRequestOptions } from '@astrale-os/sdk/client/session' import type { Value } from '@astrale-os/sdk/value' import type { Action } from '../action.js' import { useSessionKernel } from '../../auth/session-kernel.js' import { useAction } from '../action.js' export interface CallOptions extends SessionRequestOptions { readonly onError?: (error: unknown) => void } export type CallResult = Value type CallAuthor = Call | ((...args: A) => Call) export function useCall(call: Call | null, options?: CallOptions): Action<[], CallResult> export function useCall( author: ((...args: A) => Call) | null, options?: CallOptions, ): Action export function useCall( author: CallAuthor | null, options?: CallOptions, ): Action { const kernel = useSessionKernel() return useAction(async (...args: A) => { if (author === null) throw new Error('useCall: idle action invoked') const call = typeof author === 'function' ? author(...args) : author try { return await kernel.call(call, options) } catch (error) { options?.onError?.(error) throw error } }) }