import { EffectModule, ActionOfEffectModule } from '@sigi/core' import { ConstructorOf } from '@sigi/types' import { useServerInstance } from './injectable-context' export type StateSelector = { (state: S): U } export type StateSelectorConfig = { selector: StateSelector } const SERVER_DISPATCHERS = new Proxy(Object.create(null), { apply() { if (process.env.NODE_ENV !== 'production') { console.warn(new Error('Dispatch while calling react-dom/server functions is forbidden')) } }, }) export function useDispatchers, S = any>(_A: ConstructorOf): ActionOfEffectModule { return SERVER_DISPATCHERS } export function useModuleState>( A: ConstructorOf, ): M extends EffectModule ? State : never export function useModuleState, U>( A: ConstructorOf, config: M extends EffectModule ? StateSelectorConfig : never, ): M extends EffectModule ? (typeof config)['selector'] extends StateSelector ? NewState : never : never export function useModuleState, U>( A: ConstructorOf, config?: M extends EffectModule ? StateSelectorConfig : never, ) { const { store } = useServerInstance(A) return typeof config?.selector === 'function' ? config.selector(store.state) : store.state } export function useModule>( A: ConstructorOf, ): M extends EffectModule ? [State, ActionOfEffectModule] : never export function useModule, U>( A: ConstructorOf, config: M extends EffectModule ? StateSelectorConfig : never, ): M extends EffectModule ? (typeof config)['selector'] extends StateSelector ? [NewState, ActionOfEffectModule] : never : never export function useModule, U, S>(A: ConstructorOf, config?: StateSelectorConfig) { const effectModule = useServerInstance(A) const { store } = effectModule const appState = typeof config?.selector === 'function' ? config.selector(store.state) : store.state return [appState, SERVER_DISPATCHERS] } export { SSRContext } from './ssr-context' export * from './injectable-context'