import { create } from 'zustand' import { devtools } from 'zustand/middleware' import { immer } from 'zustand/middleware/immer' import type { SourceState } from './types' export type SlicesState = Record> interface SliceActions { initSlice: (key: string) => void setSlice: (key: string, update: Partial>) => void patchSlice: ( key: string, updater: (prev: SourceState) => void, ) => void } export interface EngineStoreState { slices: SlicesState actions: SliceActions } export interface EngineStoreConfig { devtools?: boolean | { name?: string } /** Project-level name used as the DevTools label when devtools.name is not set explicitly. */ name?: string } export function createIdleState(): SourceState { return { data: null, status: 'idle', isLoading: false, isFetching: false, isError: false, error: null, isStale: false, lastUpdated: null, warnings: [], lastParamsKey: null, } } export function createEngineStore(config: EngineStoreConfig = {}) { const devtoolsEnabled = config.devtools !== undefined && config.devtools !== false const devtoolsName = typeof config.devtools === 'object' ? (config.devtools.name ?? config.name ?? 'ZustandEngine') : (config.name ?? 'ZustandEngine') return create()( devtools( immer((set) => ({ slices: {}, actions: { initSlice: (key) => set( (state) => { if (!state.slices[key]) { state.slices[key] = createIdleState() } }, false, `slices/${key}/init`, ), setSlice: (key, update) => set( (state) => { const slice = state.slices[key] if (slice) Object.assign(slice, update) }, false, `slices/${key}/set`, ), patchSlice: (key, updater) => set( (state) => { const slice = state.slices[key] if (slice) updater(slice) }, false, `slices/${key}/patch`, ), }, })), { name: devtoolsName, enabled: devtoolsEnabled }, ), ) } export type EngineStore = ReturnType