import { snapshot } from '../snapshot.js' import type { VanillaStore } from '../create.js' import type { SnapshotSelector } from '../snapshot.js' export interface WithSnapshotContributes { /** * Get the snapshot of the state. */ snapshot: (selector?: SnapshotSelector) => StateSlice } /** * Enhances a store with a `snapshot` method that returns a snapshot of the store's state. * * @param store - The store to enhance. * @returns The enhanced store. * * @since 0.2.0 * * @example * * ```tsx * const store = withSnapshot( * createVanilla({ * count: 123, * info: { name: 'Viki' }, * }), * ) * * // in normal JS/TS * console.log(store.snapshot(), store.snapshot((s) => s.count)) * ``` */ export function withSnapshot>( store: Store ): Store & WithSnapshotContributes { const _snapshot = ( selector: SnapshotSelector = (s) => s as unknown as StateSlice ) => { return snapshot(store.mutate, selector) as StateSlice } return { ...store, snapshot: _snapshot, } }