import type { BoundNode } from '@astrale-os/sdk/client' import type { StoreQueryResponse } from '@astrale-os/sdk/client/store' import type { Node } from '@astrale-os/sdk/graph/node' import type { PathLike } from '@astrale-os/sdk/graph/path' import type { ResolvedClass } from '@astrale-os/sdk/schema' import { Path } from '@astrale-os/sdk/graph/path' import { Query } from '@astrale-os/sdk/query' import { useCallback, useMemo } from 'react' import type { GraphResource } from '../graph/resource.js' import { useStoreResource } from '../graph/resource.js' import { bindingFor } from './domain.hook.js' export interface RichReadOptions { readonly pageSize?: number } /** Read and bind one exact rich object definition exclusively through GraphStore. */ export function useObject>( definition: Class, target: PathLike | null | undefined, options: RichReadOptions = {}, ): GraphResource | null> { const binding = bindingFor(definition) const path = target === null || target === undefined ? null : Path.from(target) const query = useMemo( () => path === null ? null : Query.from({ nodes: [path], binding: 'object' }) .filter({ class: definition }) .select({ kind: 'graph' }), [definition, path?.raw], ) const project = useCallback( (response: StoreQueryResponse>) => { const result = response.result if (result.kind !== 'graph' || result.selection.kind !== 'node') return null const id = result.selection.ids[0] const node = id === undefined ? undefined : result.graph.nodes.find((candidate: { readonly id: unknown }) => candidate.id === id) return node === undefined ? null : binding.wrapNode(definition, node) }, [binding, definition], ) return useStoreResource(query, options.pageSize ?? 1, project) } /** Explicitly untyped point read for inspectors; it never impersonates `useObject`. */ export function useDynamicObject( target: PathLike | null | undefined, options: RichReadOptions = {}, ): GraphResource { const path = target === null || target === undefined ? null : Path.from(target) const query = useMemo( () => path === null ? null : Query.from({ nodes: [path], binding: 'dynamic_object' }).select({ kind: 'graph', }), [path?.raw], ) const project = useCallback((response: StoreQueryResponse>) => { const result = response.result if (result.kind !== 'graph' || result.selection.kind !== 'node') return null const id = result.selection.ids[0] return id === undefined ? null : (result.graph.nodes.find((candidate) => candidate.id === id) ?? null) }, []) return useStoreResource(query, options.pageSize ?? 1, project) }