@oxog/state 1.2.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/utils/deep-clone.ts","../src/utils/deep-equal.ts","../src/utils/shallow-equal.ts","../src/utils/deep-merge.ts","../src/utils/is-function.ts","../src/utils/pick.ts","../src/utils/omit.ts","../src/utils/identity.ts","../src/kernel.ts","../src/batch-context.ts","../src/batch.ts","../src/store.ts","../src/subscribe.ts","../src/computed.ts","../src/slices.ts","../src/federation.ts","../src/plugins/persist.ts","../src/plugins/devtools.ts","../src/plugins/history.ts","../src/plugins/sync.ts","../src/plugins/immer.ts","../src/plugins/selector.ts","../src/plugins/logger.ts","../src/plugins/effects.ts","../src/plugins/validate.ts","../src/testing.ts","../src/compat/middleware.ts"],"names":["StoreErrorCode","subscription","delay","selector","state","computed","createDebounced","result"],"mappings":";;;AAuYO,IAAK,cAAA,qBAAAA,eAAAA,KAAL;AAEL,EAAAA,gBAAA,iBAAA,CAAA,GAAkB,iBAAA;AAElB,EAAAA,gBAAA,eAAA,CAAA,GAAgB,eAAA;AAEhB,EAAAA,gBAAA,2BAAA,CAAA,GAA4B,2BAAA;AAE5B,EAAAA,gBAAA,sBAAA,CAAA,GAAuB,sBAAA;AAEvB,EAAAA,gBAAA,cAAA,CAAA,GAAe,cAAA;AAEf,EAAAA,gBAAA,gBAAA,CAAA,GAAiB,gBAAA;AAEjB,EAAAA,gBAAA,uBAAA,CAAA,GAAwB,uBAAA;AAdd,EAAA,OAAAA,eAAAA;AAAA,CAAA,EAAA,cAAA,IAAA,EAAA;AAoBL,IAAM,UAAA,GAAN,cAAyB,KAAA,CAAM;AAAA,EACpC,WAAA,CACS,IAAA,EACP,OAAA,EACA,OAAA,EACA;AACA,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AAJf,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAKP,IAAA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;AAEA,EAAA,OAAO,GAAA;AACT;AAwBO,SAAS,sBAAA,CACd,MACA,QAAA,EAGiB;AACjB,EAAA,MAAM,UAAA,GAAa,QAAA;AAEnB,EAAA,MAAA,CAAO,eAAe,UAAA,EAAY,MAAA,EAAQ,EAAE,KAAA,EAAO,MAAM,CAAA;AACzD,EAAA,OAAO,UAAA;AACT;AAsBO,SAAS,WACX,WAAA,EACc;AACjB,EAAA,OAAO,CAAC,OAAA,KAAY;AAClB,IAAA,OAAO,WAAA,CAAY,WAAA,CAAY,CAAC,GAAA,EAAK,UAAA,KAAe;AAClD,MAAA,OAAO,WAAW,GAAG,CAAA;AAAA,IACvB,GAAG,OAAO,CAAA;AAAA,EACZ,CAAA;AACF","file":"chunk-IWT3T2PM.cjs","sourcesContent":["/**\n * Deep partial type for nested optional properties.\n *\n * @typeParam T - The type to make partially deep\n *\n * @example\n * ```typescript\n * type User = {\n * name: string;\n * profile: { age: number; city: string; };\n * };\n *\n * const partial: DeepPartial<User> = {\n * name: 'John',\n * profile: { age: 30 } // city is optional\n * };\n * ```\n */\nexport type DeepPartial<T> = T extends object\n ? {\n [P in keyof T]?: DeepPartial<T[P]>;\n }\n : T;\n\n/**\n * Action function that receives state and optional arguments, returning a partial state update.\n *\n * @typeParam TState - The store state type\n * @typeParam TArgs - The action argument types tuple\n *\n * @example\n * ```typescript\n * type CounterAction = Action<{ count: number }, [number: number]>;\n *\n * const incrementBy: CounterAction = (state, amount) => ({\n * count: state.count + amount\n * });\n * ```\n */\nexport type Action<TState, TArgs extends unknown[] = any[]> = (\n state: TState,\n ...args: TArgs\n) => Partial<TState> | void | Promise<Partial<TState> | void>;\n\n/**\n * Collection of actions indexed by name.\n *\n * @typeParam TState - The store state type\n *\n * @example\n * ```typescript\n * const actions: Actions<{ count: number }> = {\n * increment: (state) => ({ count: state.count + 1 }),\n * decrement: (state) => ({ count: state.count - 1 })\n * };\n * ```\n */\nexport type Actions<TState> = Record<string, Action<TState, any[]>>;\n\n/**\n * The bound form of an action: the `state` argument is supplied by the store.\n *\n * @example\n * ```typescript\n * type Fn = BoundAction<(state: { n: number }, by: number) => { n: number }>;\n * // (by: number) => { n: number }\n * ```\n */\nexport type BoundAction<F> = F extends (state: any, ...args: infer A) => infer R\n ? (...args: A) => R\n : never;\n\n/**\n * Bound versions of a map of actions.\n */\nexport type BoundActions<TActions> = {\n [K in keyof TActions]: BoundAction<TActions[K]>;\n};\n\n/**\n * Bound versions of the inline (`$`-prefixed) actions of an initial state,\n * keyed without the `$` prefix.\n */\nexport type InlineActions<T> = {\n [K in keyof T as K extends `$${infer Name}`\n ? T[K] extends (...args: any[]) => any\n ? Name\n : never\n : never]: BoundAction<T[K]>;\n};\n\n/**\n * An initial state without its inline (`$`-prefixed) action functions.\n */\nexport type StateWithoutInlineActions<T> = [Extract<keyof T, `$${string}`>] extends [never]\n ? T\n : {\n [K in keyof T as K extends `$${string}`\n ? T[K] extends (...args: any[]) => any\n ? never\n : K\n : K]: T[K];\n };\n\n/**\n * The state type of a store created from `initialState` and `actions`:\n * data plus every bound action.\n */\nexport type StateWithActions<T, TActions = {}> = [Extract<keyof T, `$${string}`>] extends [never]\n ? [keyof TActions] extends [never]\n ? T\n : T & BoundActions<TActions>\n : StateWithoutInlineActions<T> & InlineActions<T> & BoundActions<TActions>;\n\n/**\n * The store returned by `createStore`: the store API plus every bound action\n * as a method.\n */\nexport type CreatedStore<T, TActions = {}> = StoreBuilder<StateWithActions<T, TActions>> &\n InlineActions<T> &\n BoundActions<TActions>;\n\n/**\n * Selector function to extract a slice of state.\n *\n * @typeParam TState - The store state type\n * @typeParam TSelected - The selected value type\n *\n * @example\n * ```typescript\n * const selectCount: Selector<{ count: number; name: string }, number> =\n * (state) => state.count;\n * ```\n */\nexport type Selector<TState, TSelected> = (state: TState) => TSelected;\n\n/**\n * Equality function for comparing two values.\n *\n * @typeParam T - The type to compare\n *\n * @example\n * ```typescript\n * const shallowEquality: EqualityFn<{ a: number }> = (a, b) =>\n * a.a === b.a;\n * ```\n */\nexport type EqualityFn<T> = (a: T, b: T) => boolean;\n\n/**\n * Listener function called when state changes.\n *\n * @typeParam TState - The store state type\n *\n * @example\n * ```typescript\n * const listener: Listener<{ count: number }> = (state, prevState) => {\n * console.log(`Count changed from ${prevState.count} to ${state.count}`);\n * };\n * ```\n */\nexport type Listener<TState> = (state: TState, prevState: TState) => void;\n\n/**\n * Storage interface for persisting state.\n *\n * @example\n * ```typescript\n * const sessionStorage: StorageLike = {\n * getItem: (key) => sessionStorage.getItem(key),\n * setItem: (key, value) => sessionStorage.setItem(key, value),\n * removeItem: (key) => sessionStorage.removeItem(key)\n * };\n * ```\n */\nexport interface StorageLike {\n /** Get an item from storage */\n getItem(key: string): string | null;\n /** Set an item in storage */\n setItem(key: string, value: string): void;\n /** Remove an item from storage */\n removeItem(key: string): void;\n}\n\n/**\n * Store configuration options.\n *\n * @typeParam TState - The store state type\n *\n * @example\n * ```typescript\n * const options: StoreOptions<{ count: number }> = {\n * name: 'Counter',\n * devtools: true\n * };\n * ```\n */\nexport interface StoreOptions<TState> {\n /** Initial state */\n initialState: TState;\n /** Store name for debugging */\n name?: string;\n /** Enable/disable devtools (default: true in development) */\n devtools?: boolean;\n}\n\n/**\n * Plugin interface for extending store functionality.\n *\n * @typeParam TState - The store state type\n *\n * @example\n * ```typescript\n * const loggerPlugin: Plugin<{ count: number }> = {\n * name: 'logger',\n * version: '1.0.0',\n * install(store) {\n * store.subscribe((state) => console.log('State:', state));\n * }\n * };\n * ```\n */\nexport interface Plugin<TState = unknown> {\n /** Unique plugin identifier (kebab-case) */\n name: string;\n /** Semantic version (e.g., \"1.0.0\") */\n version: string;\n /** Other plugins this plugin depends on */\n dependencies?: string[];\n /**\n * Called when plugin is registered.\n *\n * @param store - The store instance\n * @param options - Plugin-specific options\n */\n install: (store: Store<TState>, options?: unknown) => void;\n /**\n * Called after all plugins are installed.\n *\n * @param store - The store instance\n */\n onInit?: (store: Store<TState>) => void | Promise<void>;\n /**\n * Called when plugin is unregistered.\n */\n onDestroy?: () => void | Promise<void>;\n /**\n * Called on state change.\n *\n * @param state - New state\n * @param prevState - Previous state\n */\n onStateChange?: (state: TState, prevState: TState) => void;\n /**\n * Called on error in store.\n *\n * @param error - The error that occurred\n */\n onError?: (error: Error) => void;\n}\n\n/**\n * Store instance with state management methods.\n *\n * @typeParam TState - The store state type\n *\n * @example\n * ```typescript\n * const store: Store<{ count: number }> = createStore({ count: 0 });\n * const state = store.getState(); // { count: 0 }\n * store.setState({ count: 1 });\n * ```\n */\nexport interface Store<TState> {\n /** Get current state snapshot */\n getState(): TState;\n /**\n * Update state with partial object or function.\n *\n * @param partial - Partial state or updater function\n *\n * @example\n * ```typescript\n * store.setState({ count: 10 });\n * store.setState((state) => ({ count: state.count + 1 }));\n * ```\n */\n setState(partial: Partial<TState> | ((state: TState) => Partial<TState>)): void;\n /**\n * Deep merge state.\n *\n * @param partial - Partial state to merge\n *\n * @example\n * ```typescript\n * store.merge({ user: { name: 'John' } });\n * ```\n */\n merge(partial: DeepPartial<TState>): void;\n /** Reset to initial state */\n reset(): void;\n /**\n * Subscribe to state changes.\n *\n * @param listener - Function called on state changes\n * @returns Unsubscribe function\n *\n * @example\n * ```typescript\n * const unsubscribe = store.subscribe((state) => console.log(state));\n * unsubscribe();\n * ```\n */\n subscribe(listener: Listener<TState>): () => void;\n /**\n * Subscribe to state changes with selector.\n *\n * @param selector - Function to extract state slice\n * @param listener - Function called when selected value changes\n * @param equalityFn - Optional custom equality function\n * @returns Unsubscribe function\n *\n * @example\n * ```typescript\n * const unsubscribe = store.subscribe(\n * (state) => state.count,\n * (count) => console.log('Count:', count)\n * );\n * ```\n */\n subscribe<TSelected>(\n selector: Selector<TState, TSelected>,\n listener: Listener<TSelected>,\n equalityFn?: EqualityFn<TSelected>\n ): () => void;\n /**\n * Register a plugin.\n *\n * @param plugin - The plugin to register\n * @param options - Plugin-specific options\n * @returns The store instance for chaining\n *\n * @example\n * ```typescript\n * store.use(persist({ key: 'app' }));\n * ```\n */\n use(plugin: Plugin<TState>, options?: unknown): this;\n /** Destroy store and cleanup all resources */\n destroy(): void;\n}\n\n/**\n * Store builder interface for fluent API.\n *\n * @typeParam TState - The store state type\n *\n * @example\n * ```typescript\n * createStore({ count: 0 })\n * .action('increment', (s) => ({ count: s.count + 1 }))\n * .action('decrement', (s) => ({ count: s.count - 1 }));\n * ```\n */\nexport interface StoreBuilder<TState> extends Store<TState> {\n /**\n * Add an action to the store.\n *\n * @param name - Action name\n * @param fn - Action function\n * @returns The builder for chaining\n */\n action<K extends string, F extends Action<TState, any[]>>(\n name: K,\n fn: F\n ): this & { [P in K]: BoundAction<F> };\n}\n\n/**\n * History-enabled store with undo/redo methods.\n */\nexport interface HistoryStore<TState> extends Store<TState> {\n /** Undo last state change */\n undo(): void;\n /** Redo last undone state change */\n redo(): void;\n}\n\n/**\n * Error codes for store errors.\n */\nexport enum StoreErrorCode {\n /** Store was destroyed and cannot be used */\n STORE_DESTROYED = 'STORE_DESTROYED',\n /** Plugin with same name already registered */\n PLUGIN_EXISTS = 'PLUGIN_EXISTS',\n /** Required plugin dependency not found */\n PLUGIN_DEPENDENCY_MISSING = 'PLUGIN_DEPENDENCY_MISSING',\n /** Invalid state update argument */\n INVALID_STATE_UPDATE = 'INVALID_STATE_UPDATE',\n /** Action threw an error */\n ACTION_ERROR = 'ACTION_ERROR',\n /** `use()` was given an object without name, version or install function */\n INVALID_PLUGIN = 'INVALID_PLUGIN',\n /** A plugin's install function threw (the original error is `cause`) */\n PLUGIN_INSTALL_FAILED = 'PLUGIN_INSTALL_FAILED',\n}\n\n/**\n * Store error class.\n */\nexport class StoreError extends Error {\n constructor(\n public code: StoreErrorCode,\n message: string,\n options?: { cause?: unknown }\n ) {\n super(message, options);\n this.name = 'StoreError';\n }\n}\n","/**\n * Deep clone a value, creating copies of nested objects and arrays.\n *\n * Handles:\n * - Primitives (returned as-is)\n * - null and undefined (returned as-is)\n * - Date objects\n * - Arrays\n * - Plain objects\n * - Circular references\n * - Other objects (returned as-is, not cloned)\n *\n * @typeParam T - The type to clone\n * @param value - The value to clone\n * @param seen - Internal map for tracking circular references\n * @returns A deep clone of the value\n *\n * @example\n * ```typescript\n * const original = { a: 1, b: { c: 2 } };\n * const cloned = deepClone(original);\n * cloned.b.c = 3;\n * console.log(original.b.c); // 2 (unchanged)\n * ```\n */\nexport function deepClone<T>(value: T, seen?: WeakMap<object, unknown>): T {\n // Primitives, null, undefined - return as-is\n if (value === null || typeof value !== 'object') {\n return value;\n }\n\n // Date - create new Date instance\n if (value instanceof Date) {\n return new Date(value.getTime()) as T;\n }\n\n // Handle circular references\n if (!seen) {\n seen = new WeakMap();\n }\n if (seen.has(value)) {\n return seen.get(value) as T;\n }\n seen.set(value, value);\n\n // Array - map and recursively clone\n if (Array.isArray(value)) {\n const cloned = [] as unknown as T;\n seen.set(value, cloned);\n (value as unknown[]).forEach((item, index) => {\n (cloned as unknown[])[index] = deepClone(item, seen);\n });\n return cloned;\n }\n\n // Plain object - create new object and clone properties\n if (value.constructor === Object) {\n const cloned = {} as T;\n seen.set(value, cloned);\n for (const key in value) {\n // An own \"__proto__\" key (e.g. from JSON.parse) would become a prototype\n // change when assigned; skip it.\n if (key !== '__proto__' && Object.prototype.hasOwnProperty.call(value, key)) {\n (cloned as any)[key] = deepClone((value as any)[key], seen);\n }\n }\n return cloned;\n }\n\n // For other objects (classes, etc.), return as-is\n // This handles RegExp, Map, Set, and custom classes\n return value;\n}\n","/**\n * Deep equality check for two values.\n *\n * Recursively compares objects and arrays.\n * Uses Object.is for primitive comparison.\n *\n * @param a - First value\n * @param b - Second value\n * @returns true if values are deeply equal\n *\n * @example\n * ```typescript\n * deepEqual(1, 1); // true\n * deepEqual({ a: { b: 1 } }, { a: { b: 1 } }); // true\n * deepEqual({ a: { b: 1 } }, { a: { b: 2 } }); // false\n * deepEqual([1, 2], [1, 2]); // true\n * deepEqual([1, 2], [1, 2, 3]); // false\n * ```\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n // Object.is handles NaN and -0/+0 correctly\n if (Object.is(a, b)) {\n return true;\n }\n\n // If either is null or not an object, not equal\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') {\n return false;\n }\n\n // Array comparison\n if (Array.isArray(a) !== Array.isArray(b)) {\n return false;\n }\n\n if (Array.isArray(a)) {\n const arrB = b as unknown[];\n if (a.length !== arrB.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], arrB[i])) {\n return false;\n }\n }\n return true;\n }\n\n // Object comparison\n const keysA = Object.keys(a as object);\n const keysB = Object.keys(b as object);\n\n if (keysA.length !== keysB.length) {\n return false;\n }\n\n for (const key of keysA) {\n if (\n !Object.prototype.hasOwnProperty.call(b, key) ||\n !deepEqual((a as any)[key], (b as any)[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n","/**\n * Shallow equality check for two values.\n *\n * Uses Object.is for comparison, which handles NaN correctly\n * and distinguishes between +0 and -0.\n *\n * @param a - First value\n * @param b - Second value\n * @returns true if values are shallowly equal\n *\n * @example\n * ```typescript\n * shallowEqual(1, 1); // true\n * shallowEqual({ a: 1 }, { a: 1 }); // true\n * shallowEqual({ a: 1 }, { a: 2 }); // false\n * shallowEqual(NaN, NaN); // true\n * ```\n */\nexport function shallowEqual(a: unknown, b: unknown): boolean {\n // Object.is handles NaN and -0/+0 correctly\n if (Object.is(a, b)) {\n return true;\n }\n\n // If either is not an object (or is null), not equal\n if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {\n return false;\n }\n\n // Compare keys\n const keysA = Object.keys(a as object);\n const keysB = Object.keys(b as object);\n\n if (keysA.length !== keysB.length) {\n return false;\n }\n\n for (const key of keysA) {\n if (!keysB.includes(key) || !Object.is((a as any)[key], (b as any)[key])) {\n return false;\n }\n }\n\n return true;\n}\n","/**\n * Deep merge a partial object into a target object.\n *\n * Creates a new object with nested objects merged recursively.\n * Arrays are replaced, not merged.\n *\n * @typeParam T - The target type\n * @param target - The target object\n * @param source - The partial source to merge\n * @returns A new merged object\n *\n * @example\n * ```typescript\n * const target = { a: 1, b: { c: 2, d: 3 } };\n * const source = { b: { c: 10 }, e: 4 };\n * const merged = deepMerge(target, source);\n * // { a: 1, b: { c: 10, d: 3 }, e: 4 }\n * ```\n */\n\nimport type { DeepPartial } from '../types.js';\nimport { deepClone } from './deep-clone.js';\n\nexport function deepMerge<T>(target: T, source: Partial<T> | DeepPartial<T>): T;\nexport function deepMerge<T, S extends object>(target: T, source: S): T & S;\nexport function deepMerge<T>(target: T, source: unknown): T {\n if (source === null) {\n return target;\n }\n if (typeof source !== 'object') {\n return source as T;\n }\n\n // Deep clone target to avoid reference issues with Date objects\n const output = deepClone(target) as any;\n\n for (const key in source) {\n // Never merge \"__proto__\": assigning it would change the prototype.\n if (key !== '__proto__' && Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = (source as any)[key];\n const targetValue = output[key];\n\n // Date objects - clone and replace\n if (sourceValue instanceof Date) {\n output[key] = new Date(sourceValue.getTime());\n continue;\n }\n\n // Both are plain objects (but not arrays) - recursively merge\n if (\n Object.prototype.hasOwnProperty.call(output, key) &&\n sourceValue !== null &&\n typeof sourceValue === 'object' &&\n !Array.isArray(sourceValue) &&\n !(sourceValue instanceof Date) &&\n targetValue !== null &&\n typeof targetValue === 'object' &&\n !Array.isArray(targetValue) &&\n !(targetValue instanceof Date)\n ) {\n output[key] = deepMerge(targetValue, sourceValue as object);\n } else {\n // Replace with cloned value\n output[key] = cloneValue(sourceValue);\n }\n }\n }\n\n return output;\n}\n\n/**\n * Clone a value for merging.\n */\nfunction cloneValue(value: unknown): unknown {\n if (value === null || typeof value !== 'object') {\n return value;\n }\n\n if (value instanceof Date) {\n return new Date(value.getTime());\n }\n\n if (Array.isArray(value)) {\n return value.map((v) => cloneValue(v));\n }\n\n if (value.constructor === Object) {\n const cloned: Record<string, unknown> = {};\n for (const key in value) {\n if (key !== '__proto__' && Object.prototype.hasOwnProperty.call(value, key)) {\n cloned[key] = cloneValue((value as any)[key]);\n }\n }\n return cloned;\n }\n\n return value;\n}\n","/**\n * Type guard to check if a value is a function.\n *\n * @param value - The value to check\n * @returns true if the value is a function\n *\n * @example\n * ```typescript\n * const value: unknown = () => {};\n * if (isFunction(value)) {\n * value(); // TypeScript knows this is a function\n * }\n * ```\n */\nexport function isFunction(value: unknown): value is (...args: any[]) => any {\n return typeof value === 'function';\n}\n","/**\n * Pick specified properties from an object.\n *\n * Creates a new object with only the specified keys.\n *\n * @typeParam T - The object type\n * @typeParam K - The keys to pick\n * @param obj - The source object\n * @param keys - The keys to pick\n * @returns A new object with only the picked keys\n *\n * @example\n * ```typescript\n * const user = { name: 'John', age: 30, city: 'NYC' };\n * const picked = pick(user, ['name', 'age']);\n * // { name: 'John', age: 30 }\n * ```\n */\nexport function pick<T extends object, K extends keyof T>(\n obj: T,\n keys: readonly K[]\n): Pick<T, K> {\n const result = {} as Pick<T, K>;\n for (const key of keys) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = obj[key];\n }\n }\n return result;\n}\n","/**\n * Omit specified properties from an object.\n *\n * Creates a new object without the specified keys.\n *\n * @typeParam T - The object type\n * @typeParam K - The keys to omit\n * @param obj - The source object\n * @param keys - The keys to omit\n * @returns A new object without the omitted keys\n *\n * @example\n * ```typescript\n * const user = { name: 'John', age: 30, city: 'NYC' };\n * const omitted = omit(user, ['age', 'city']);\n * // { name: 'John' }\n * ```\n */\nexport function omit<T extends object, K extends keyof T>(\n obj: T,\n keys: readonly K[]\n): Omit<T, K> {\n const result = { ...obj } as Omit<T, K>;\n for (const key of keys) {\n delete (result as any)[key];\n }\n return result;\n}\n","/**\n * Identity function that returns its input.\n *\n * Useful as a default selector when no transformation is needed.\n *\n * @typeParam T - The value type\n * @param value - The value to return\n * @returns The same value\n *\n * @example\n * ```typescript\n * const selector = identity;\n * selector(42); // 42\n * selector('hello'); // 'hello'\n * ```\n */\nexport function identity<T>(value: T): T {\n return value;\n}\n","import type { Plugin, Store } from './types.js';\nimport { StoreError, StoreErrorCode } from './types.js';\n\n/**\n * Plugin instance with runtime state.\n */\ninterface PluginInstance<TState = unknown> {\n plugin: Plugin<TState>;\n options: unknown;\n}\n\n/**\n * Event handler type.\n */\ntype EventHandler = (data: unknown) => void;\n\n/**\n * Event bus for inter-plugin communication.\n */\nclass EventBus {\n private listeners: Map<string, Set<EventHandler>> = new Map();\n\n /**\n * Subscribe to an event.\n *\n * @param event - Event name\n * @param handler - Event handler\n * @returns Unsubscribe function\n */\n on(event: string, handler: EventHandler): () => void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)!.add(handler);\n\n return () => {\n this.listeners.get(event)?.delete(handler);\n };\n }\n\n /**\n * Emit an event to all subscribers.\n *\n * @param event - Event name\n * @param data - Event data\n */\n emit(event: string, data: unknown): void {\n const handlers = this.listeners.get(event);\n if (handlers) {\n for (const handler of handlers) {\n try {\n handler(data);\n } catch (error) {\n console.error(`Error in ${event} handler:`, error);\n }\n }\n }\n }\n\n /** Clear all listeners. */\n destroy(): void {\n this.listeners.clear();\n }\n}\n\n/**\n * Kernel configuration.\n */\ninterface KernelConfig {\n name?: string;\n devtools?: boolean;\n}\n\n/**\n * Kernel managing plugins and events.\n */\nexport class Kernel {\n plugins: Map<string, PluginInstance<any>> = new Map();\n eventBus: EventBus = new EventBus();\n config: KernelConfig;\n errorHandlers: Set<(error: Error) => void> = new Set();\n private initializing = false;\n\n constructor(config?: KernelConfig) {\n this.config = config || {};\n }\n\n /**\n * Register a plugin.\n *\n * @param plugin - The plugin to register\n * @param options - Plugin options\n * @param store - The store instance\n * @throws {StoreError} If the plugin is invalid, already registered, has missing\n * dependencies or its install function throws\n */\n register<TState>(\n plugin: Plugin<TState>,\n options: unknown,\n store: Store<TState>\n ): void {\n // Validate plugin\n if (!plugin.name || !plugin.version || typeof plugin.install !== 'function') {\n throw new StoreError(\n StoreErrorCode.INVALID_PLUGIN,\n 'Invalid plugin: must have name, version, and install function'\n );\n }\n\n // Check for duplicate\n if (this.plugins.has(plugin.name)) {\n throw new StoreError(\n StoreErrorCode.PLUGIN_EXISTS,\n `Plugin '${plugin.name}' is already registered`\n );\n }\n\n // Check dependencies\n if (plugin.dependencies) {\n for (const dep of plugin.dependencies) {\n if (!this.plugins.has(dep)) {\n throw new StoreError(\n StoreErrorCode.PLUGIN_DEPENDENCY_MISSING,\n `Plugin '${plugin.name}' requires '${dep}' to be registered first`\n );\n }\n }\n }\n\n // Create plugin instance\n const instance: PluginInstance<TState> = {\n plugin,\n options,\n };\n\n // Install plugin\n try {\n plugin.install(store, options);\n } catch (error) {\n throw new StoreError(\n StoreErrorCode.PLUGIN_INSTALL_FAILED,\n `Failed to install plugin '${plugin.name}': ${error}`,\n { cause: error }\n );\n }\n\n this.plugins.set(plugin.name, instance);\n\n // If not in init phase and plugin has onInit, call it\n if (!this.initializing && plugin.onInit) {\n this.runOnInit(plugin, store);\n }\n }\n\n /**\n * Initialize all plugins.\n *\n * @param store - The store instance\n */\n async initializeAll<TState>(store: Store<TState>): Promise<void> {\n this.initializing = true;\n\n const plugins = Array.from(this.plugins.values());\n\n for (const { plugin } of plugins) {\n if (plugin.onInit) {\n await this.runOnInit(plugin, store);\n }\n }\n\n this.initializing = false;\n }\n\n /**\n * Run plugin's onInit safely.\n */\n private async runOnInit<TState>(plugin: Plugin<TState>, store: Store<TState>): Promise<void> {\n try {\n await plugin.onInit!(store);\n } catch (error) {\n console.error(`Error in ${plugin.name} onInit:`, error);\n }\n }\n\n /**\n * Unregister a plugin.\n *\n * @param name - Plugin name\n */\n async unregister(name: string): Promise<void> {\n const instance = this.plugins.get(name);\n if (!instance) {\n return;\n }\n\n if (instance.plugin.onDestroy) {\n try {\n await instance.plugin.onDestroy();\n } catch (error) {\n console.error(`Error in ${name} onDestroy:`, error);\n }\n }\n\n this.plugins.delete(name);\n }\n\n /**\n * Emit a state change event.\n *\n * @param state - New state\n * @param prevState - Previous state\n */\n emitStateChange<TState>(state: TState, prevState: TState): void {\n this.eventBus.emit('stateChange', { state, prevState });\n\n for (const { plugin } of this.plugins.values()) {\n if (plugin.onStateChange) {\n try {\n plugin.onStateChange(state, prevState);\n } catch (error) {\n console.error(`Error in ${plugin.name} onStateChange:`, error);\n }\n }\n }\n }\n\n /**\n * Emit an error event.\n *\n * @param error - The error\n */\n emitError(error: Error): void {\n this.eventBus.emit('error', error);\n\n for (const { plugin } of this.plugins.values()) {\n if (plugin.onError) {\n try {\n plugin.onError(error);\n } catch (err) {\n console.error(`Error in ${plugin.name} onError:`, err);\n }\n }\n }\n\n for (const handler of this.errorHandlers) {\n try {\n handler(error);\n } catch (err) {\n console.error('Error in error handler:', err);\n }\n }\n }\n\n /**\n * Add an error handler.\n *\n * @param handler - Error handler function\n * @returns Unsubscribe function\n */\n onError(handler: (error: Error) => void): () => void {\n this.errorHandlers.add(handler);\n return () => {\n this.errorHandlers.delete(handler);\n };\n }\n\n /**\n * Subscribe to an event.\n *\n * @param event - Event name\n * @param handler - Event handler\n * @returns Unsubscribe function\n */\n on(event: string, handler: EventHandler): () => void {\n return this.eventBus.on(event, handler);\n }\n\n /** Destroy the kernel and cleanup. */\n async destroy(): Promise<void> {\n const pluginNames = Array.from(this.plugins.keys());\n\n for (const name of pluginNames) {\n await this.unregister(name);\n }\n\n this.eventBus.destroy();\n this.errorHandlers.clear();\n }\n}\n\n/**\n * Create a new kernel.\n *\n * @param config - Kernel configuration\n * @returns A new Kernel instance\n */\nexport function createKernel(config?: KernelConfig): Kernel {\n return new Kernel(config);\n}\n","/**\n * Shared batch context singleton.\n * This ensures that all modules access the same batch context instance.\n * Using module-level variables and functions for maximum bundler compatibility.\n */\n\nimport type { Store } from './types.js';\n\n// Module-level state - these are guaranteed to be singletons\nlet batchDepth = 0;\nconst batchStores = new Set<Store<any>>();\nconst batchManagedStores = new Set<Store<any>>();\n\n/**\n * Check if currently batching.\n */\nexport function isBatching(): boolean {\n return batchDepth > 0;\n}\n\n/**\n * Get current batch depth.\n */\nexport function getBatchDepth(): number {\n return batchDepth;\n}\n\n/**\n * Increment batch depth.\n */\nexport function incrementBatchDepth(): number {\n return ++batchDepth;\n}\n\n/**\n * Decrement batch depth.\n */\nexport function decrementBatchDepth(): number {\n return --batchDepth;\n}\n\n/**\n * Get all batch stores.\n */\nexport function getBatchStores(): Set<Store<any>> {\n return batchStores;\n}\n\n/**\n * Get all managed stores.\n */\nexport function getBatchManagedStores(): Set<Store<any>> {\n return batchManagedStores;\n}\n\n/**\n * Clear all batch stores.\n */\nexport function clearBatchStores(): void {\n batchStores.clear();\n batchManagedStores.clear();\n}\n\n/**\n * Add a store to batch tracking.\n */\nexport function addBatchStore(store: Store<any>): void {\n batchStores.add(store);\n}\n\n/**\n * Add a store to managed tracking.\n */\nexport function addManagedStore(store: Store<any>): void {\n batchManagedStores.add(store);\n}\n\n/**\n * Check if a store is managed.\n */\nexport function isStoreManaged(store: Store<any>): boolean {\n return batchManagedStores.has(store);\n}\n\n// Legacy exports for compatibility\nexport const sharedBatchContext = {\n get depth() { return batchDepth; },\n get stores() { return batchStores; },\n get managedStores() { return batchManagedStores; },\n\n isBatching,\n batch<T>(store: Store<any>, fn: () => T): T {\n const wasAlreadyBatching = isStoreManaged(store);\n\n incrementBatchDepth();\n addBatchStore(store);\n\n // Call beginBatch on the store if it has one and we haven't already\n if (!wasAlreadyBatching && 'beginBatch' in store) {\n (store as any).beginBatch();\n addManagedStore(store);\n }\n\n try {\n const result = fn();\n decrementBatchDepth();\n\n if (getBatchDepth() === 0) {\n // Flush all pending notifications\n for (const s of getBatchManagedStores()) {\n if ('flushNotifications' in s) {\n (s as any).flushNotifications();\n }\n if ('endBatch' in s) {\n (s as any).endBatch();\n }\n }\n clearBatchStores();\n }\n\n return result;\n } catch (error) {\n decrementBatchDepth();\n // Cleanup on error\n if (getBatchDepth() === 0) {\n for (const s of getBatchManagedStores()) {\n if ('endBatch' in s) {\n (s as any).endBatch();\n }\n }\n clearBatchStores();\n }\n throw error;\n }\n },\n};\n\n// Type for BatchContext (legacy)\nexport interface BatchContext {\n depth: number;\n stores: Set<Store<any>>;\n managedStores: Set<Store<any>>;\n isBatching(): boolean;\n batch<T>(store: Store<any>, fn: () => T): T;\n}\n","import type { Store } from './types.js';\nimport type { BatchContext } from './batch-context.js';\nimport {\n sharedBatchContext,\n isBatching as checkIsBatching,\n getBatchDepth,\n incrementBatchDepth,\n decrementBatchDepth,\n getBatchManagedStores,\n clearBatchStores,\n} from './batch-context.js';\n\n/**\n * Get the global batch context.\n *\n * @internal\n */\nexport function getBatchContext(): BatchContext {\n return sharedBatchContext;\n}\n\n/**\n * Check if currently in a batch context.\n *\n * @returns true if batching\n *\n * @internal\n */\nexport function isBatching(): boolean {\n return checkIsBatching();\n}\n\n/**\n * Batch multiple state updates into a single notification.\n *\n * This reduces the number of subscriber notifications when making multiple\n * state updates in sequence. All updates within the batch function will\n * result in only one notification to subscribers.\n *\n * @param fn - Function containing state updates\n * @returns The return value of fn\n *\n * @example\n * ```typescript\n * import { batch, createStore } from '@oxog/state';\n *\n * const store = createStore({ count: 0, name: '' });\n *\n * // Without batch - 3 re-renders in React\n * store.setState({ count: 1 });\n * store.setState({ count: 2 });\n * store.setState({ name: 'John' });\n *\n * // With batch - 1 re-render in React\n * batch(() => {\n * store.setState({ count: 1 });\n * store.setState({ count: 2 });\n * store.setState({ name: 'John' });\n * });\n * ```\n */\nexport function batch<T>(fn: () => T): T {\n // Increment depth first to signal batching is active\n incrementBatchDepth();\n\n try {\n const result = fn();\n decrementBatchDepth();\n\n if (getBatchDepth() === 0) {\n // End batch on all managed stores\n // Create a copy to avoid mutation during iteration\n const storesArray = Array.from(getBatchManagedStores());\n for (const s of storesArray) {\n if ('flushNotifications' in s) {\n // Only flush notifications, don't call endBatch (which would decrement batchDepth again)\n (s as any).flushNotifications();\n }\n }\n clearBatchStores();\n }\n\n return result;\n } catch (error) {\n decrementBatchDepth();\n // Cleanup on error\n const storesArray = Array.from(getBatchManagedStores());\n for (const s of storesArray) {\n if ('flushNotifications' in s) {\n (s as any).flushNotifications();\n }\n }\n clearBatchStores();\n throw error;\n }\n}\n\n/**\n * Create a store-bound batch function.\n *\n * @param store - The store to batch\n * @returns A batch function bound to the store\n *\n * @example\n * ```typescript\n * import { createStore, createBatch } from '@oxog/state';\n *\n * const store = createStore({ count: 0 });\n * const batchStore = createBatch(store);\n *\n * batchStore(() => {\n * store.setState({ count: 1 });\n * store.setState({ count: 2 });\n * });\n * ```\n */\nexport function createBatch(store: Store<any>): <T>(fn: () => T) => T {\n return <T>(fn: () => T): T => {\n return sharedBatchContext.batch(store, fn);\n };\n}\n","import type {\n Action,\n Actions,\n CreatedStore,\n DeepPartial,\n EqualityFn,\n Listener,\n Plugin,\n Selector,\n Store,\n StoreBuilder,\n StoreOptions,\n} from './types.js';\nimport { StoreError, StoreErrorCode } from './types.js';\nimport { deepClone, deepMerge, shallowEqual, isFunction } from './utils/index.js';\nimport { createKernel, type Kernel } from './kernel.js';\nimport { sharedBatchContext as globalBatchContext, type BatchContext } from './batch-context.js';\n\n// Export types\nexport type { Store, StoreBuilder, StoreOptions };\nexport { StoreError, StoreErrorCode } from './types.js';\nexport { batch } from './batch.js';\n\n/**\n * State update function or partial object.\n */\ntype StateUpdate<TState> = Partial<TState> | ((state: TState) => Partial<TState>);\n\n/**\n * A plain (whole-state) subscription.\n */\ninterface PlainSubscription<TState> {\n listener: Listener<TState>;\n /** State version at subscribe time; older queued notifications are skipped. */\n since: number;\n}\n\n/**\n * A selector subscription. Every call to `subscribe(selector, ...)` gets its\n * own entry so each listener keeps its own equality function and baseline.\n */\ninterface SelectorSubscription<TState, TSelected> {\n selector: Selector<TState, TSelected>;\n listener: Listener<TSelected>;\n equalityFn: EqualityFn<TSelected>;\n value: TSelected;\n}\n\n/**\n * A pending notification.\n */\ninterface PendingNotification<TState> {\n state: TState;\n prevState: TState;\n version: number;\n}\n\n/**\n * Internal store implementation.\n */\nclass StoreImpl<TState> implements Store<TState> {\n private state: TState;\n private initialState: TState;\n private listeners: Set<PlainSubscription<TState>> = new Set();\n private selectorSubscriptions: Set<SelectorSubscription<TState, any>> = new Set();\n private kernel: Kernel;\n private destroyed = false;\n private batchDepth = 0;\n private pendingNotify = false;\n private queuedState: TState | null = null;\n private queuedPrevState: TState | null = null;\n private actions: Actions<TState> = {};\n /** Incremented on every state change. */\n private version = 0;\n /** True while listeners are being notified. */\n private notifying = false;\n /** Notifications raised by listeners while notifying; delivered in order. */\n private notifyQueue: PendingNotification<TState>[] = [];\n\n constructor(initialState: TState, kernel: Kernel) {\n this.state = deepClone(initialState);\n this.initialState = deepClone(initialState);\n this.kernel = kernel;\n\n // Handle errors from kernel\n this.kernel.onError((error) => {\n console.error('Store error:', error);\n });\n }\n\n /** Get current state snapshot. */\n getState(): TState {\n this.checkNotDestroyed();\n return this.state;\n }\n\n /** Update state with partial object or function. */\n setState(partial: StateUpdate<TState>): void {\n this.checkNotDestroyed();\n\n const prevState = this.state;\n const update = typeof partial === 'function' ? (partial as (state: TState) => Partial<TState>)(this.state) : partial;\n // Nothing to apply (e.g. an action that returned nothing): no notification.\n if (update === null || update === undefined) {\n return;\n }\n this.state = { ...this.state, ...withoutProtoKey(update) };\n\n this.notifyOrQueue(this.state, prevState);\n }\n\n /** Deep merge state. */\n merge(partial: DeepPartial<TState>): void {\n this.checkNotDestroyed();\n\n const prevState = this.state;\n this.state = deepMerge(this.state, partial);\n\n this.notifyOrQueue(this.state, prevState);\n }\n\n /** Reset to initial state. */\n reset(): void {\n this.checkNotDestroyed();\n const prevState = this.state;\n this.state = deepClone(this.initialState);\n\n this.notifyOrQueue(this.state, prevState);\n }\n\n /** Subscribe to all state changes. */\n subscribe(listener: Listener<TState>): () => void;\n /** Subscribe with selector. */\n subscribe<TSelected>(\n selector: Selector<TState, TSelected>,\n listener: Listener<TSelected>,\n equalityFn?: EqualityFn<TSelected>\n ): () => void;\n subscribe(arg1: any, arg2?: any, arg3?: any): () => void {\n this.checkNotDestroyed();\n\n // If first arg is a plain function (no selector), it's a simple listener\n if (arg2 === undefined && typeof arg1 === 'function') {\n const subscription: PlainSubscription<TState> = { listener: arg1, since: this.version };\n this.listeners.add(subscription);\n return () => {\n this.listeners.delete(subscription);\n };\n }\n\n // Otherwise, it's a selector-based subscription\n const subscription: SelectorSubscription<TState, any> = {\n selector: arg1,\n listener: arg2,\n equalityFn: arg3 || shallowEqual,\n value: (arg1 as Selector<TState, unknown>)(this.state),\n };\n this.selectorSubscriptions.add(subscription);\n\n return () => {\n this.selectorSubscriptions.delete(subscription);\n };\n }\n\n /** Register a plugin. */\n use(plugin: Plugin<TState>, options?: unknown): this {\n this.checkNotDestroyed();\n\n this.kernel.register(plugin, options, this);\n\n return this;\n }\n\n /** Destroy store and cleanup. */\n destroy(): void {\n if (this.destroyed) {\n return;\n }\n\n this.destroyed = true;\n this.kernel.destroy().catch((error) => {\n console.error('Error destroying store plugins:', error);\n });\n this.listeners.clear();\n this.selectorSubscriptions.clear();\n this.notifyQueue = [];\n this.actions = {};\n }\n\n /** Add an action (for fluent builder pattern). */\n addAction<K extends string>(name: K, fn: (state: TState, ...args: any[]) => Partial<TState>): this {\n (this.actions as any)[name] = fn;\n return this;\n }\n\n /**\n * Expose a bound action on the state object (and on the initial state, so\n * `reset()` keeps it). Construction-time only: no notification is sent.\n */\n exposeAction(name: string, fn: (...args: any[]) => unknown): void {\n if (name === '__proto__') return;\n this.state = { ...this.state, [name]: fn };\n this.initialState = { ...this.initialState, [name]: fn };\n }\n\n /** Get all actions. */\n getActions(): Actions<TState> {\n return this.actions;\n }\n\n /** Check if store is destroyed. */\n private checkNotDestroyed(): void {\n if (this.destroyed) {\n throw new StoreError(StoreErrorCode.STORE_DESTROYED, 'Cannot use destroyed store');\n }\n }\n\n /** Notify listeners or queue if batching. */\n private notifyOrQueue(state: TState, prevState: TState): void {\n this.version++;\n\n // Check if we're in a global batch context\n const inGlobalBatch = globalBatchContext.isBatching();\n\n if (inGlobalBatch) {\n // Register this store with the global batch context\n const managedStores = globalBatchContext.managedStores;\n if (!managedStores.has(this)) {\n managedStores.add(this);\n }\n }\n\n // Check if either local batching or global batching is active\n if (this.batchDepth > 0 || inGlobalBatch) {\n // Queue notification - only set prevState on first state change\n this.queuedState = state;\n if (!this.pendingNotify) {\n this.queuedPrevState = prevState;\n }\n this.pendingNotify = true;\n } else {\n // Immediate notification\n this.notify(state, prevState);\n }\n }\n\n /**\n * Notify all listeners.\n *\n * Re-entrant updates (a listener calling setState) are queued and delivered\n * after the current pass, so every listener sees changes in order and ends\n * on the latest state.\n */\n private notify(state: TState, prevState: TState): void {\n this.notifyQueue.push({ state, prevState, version: this.version });\n if (this.notifying) {\n return;\n }\n\n this.notifying = true;\n try {\n let next: PendingNotification<TState> | undefined;\n while ((next = this.notifyQueue.shift()) !== undefined) {\n this.deliver(next);\n }\n } finally {\n this.notifying = false;\n this.notifyQueue = [];\n }\n }\n\n /** Deliver one notification to plugins and listeners. */\n private deliver({ state, prevState, version }: PendingNotification<TState>): void {\n // Notify state change listeners\n this.kernel.emitStateChange(state, prevState);\n\n // Notify all-state listeners. Iterate over a snapshot: listeners added\n // during this pass wait for the next change, removed ones are skipped.\n for (const subscription of Array.from(this.listeners)) {\n if (!this.listeners.has(subscription) || subscription.since >= version) {\n continue;\n }\n try {\n subscription.listener(state, prevState);\n } catch (error) {\n this.kernel.emitError(error as Error);\n }\n }\n\n // Notify selector listeners\n for (const subscription of Array.from(this.selectorSubscriptions)) {\n if (!this.selectorSubscriptions.has(subscription)) {\n continue;\n }\n try {\n const newValue = subscription.selector(state);\n if (subscription.equalityFn(newValue, subscription.value)) {\n continue;\n }\n const prevValue = subscription.value;\n subscription.value = newValue;\n subscription.listener(newValue, prevValue);\n } catch (error) {\n this.kernel.emitError(error as Error);\n }\n }\n }\n\n /** Flush pending notifications (end of batch). */\n flushNotifications(): void {\n if (this.pendingNotify) {\n const state = this.queuedState!;\n const prevState = this.queuedPrevState!;\n this.pendingNotify = false;\n this.queuedState = null;\n this.queuedPrevState = null;\n if (!this.destroyed) {\n this.notify(state, prevState);\n }\n }\n }\n\n /** Start batching. */\n beginBatch(): void {\n this.batchDepth++;\n }\n\n /** End batching. */\n endBatch(): void {\n this.batchDepth--;\n if (this.batchDepth === 0) {\n this.flushNotifications();\n }\n }\n}\n\n/**\n * Drop an own `__proto__` key (e.g. from `JSON.parse`) so later clones and\n * merges cannot turn it into a prototype change.\n */\nfunction withoutProtoKey<T>(update: T): T {\n if (update !== null && typeof update === 'object' && Object.prototype.hasOwnProperty.call(update, '__proto__')) {\n const copy: Record<string, unknown> = {};\n for (const key of Object.keys(update as object)) {\n if (key !== '__proto__') copy[key] = (update as Record<string, unknown>)[key];\n }\n return copy as T;\n }\n return update;\n}\n\n/**\n * Store builder for fluent API.\n */\nclass StoreBuilderImpl<TState> implements StoreBuilder<TState> {\n private store: StoreImpl<TState>;\n\n constructor(initialState: TState, kernel: Kernel) {\n this.store = new StoreImpl<TState>(initialState, kernel);\n }\n\n getState(): TState {\n return this.store.getState();\n }\n\n setState(partial: StateUpdate<TState>): void {\n this.store.setState(partial);\n }\n\n merge(partial: DeepPartial<TState>): void {\n this.store.merge(partial);\n }\n\n reset(): void {\n this.store.reset();\n }\n\n subscribe(listener: Listener<TState>): () => void;\n subscribe<TSelected>(\n selector: Selector<TState, TSelected>,\n listener: Listener<TSelected>,\n equalityFn?: EqualityFn<TSelected>\n ): () => void;\n subscribe(arg1: any, arg2?: any, arg3?: any): () => void {\n if (arg2 === undefined) {\n // It's a simple listener (no selector)\n return this.store.subscribe(arg1);\n } else {\n // It's a selector-based subscription\n return this.store.subscribe(arg1, arg2, arg3);\n }\n }\n\n use(plugin: Plugin<TState>, options?: unknown): this {\n this.store.use(plugin, options);\n return this;\n }\n\n destroy(): void {\n this.store.destroy();\n }\n\n action<K extends string>(\n name: K,\n fn: (state: any, ...args: any[]) => any\n ): any {\n this.store.addAction(name, fn);\n\n // Bound wrapper: available as `store[name](...)` and `getState()[name](...)`.\n // It calls `this.setState` dynamically so plugins that wrap setState apply.\n const bound = (...args: any[]) => {\n const result = fn(this.getState(), ...args);\n if (result instanceof Promise) {\n return result.then((partial) => {\n this.setState(partial);\n return partial;\n });\n }\n this.setState(result);\n return result;\n };\n Object.defineProperty(bound, 'name', { value: name, configurable: true });\n (this as any)[name] = bound;\n this.store.exposeAction(name, bound);\n\n return this;\n }\n\n /** Add action (internal use). */\n addAction<K extends string>(name: K, fn: (state: TState, ...args: any[]) => Partial<TState>): this {\n this.store.addAction(name, fn);\n return this;\n }\n\n /** Get actions (internal use). */\n getActions(): Actions<TState> {\n return this.store.getActions();\n }\n\n /** Start batching. */\n beginBatch(): void {\n this.store.beginBatch();\n }\n\n /** End batching. */\n endBatch(): void {\n this.store.endBatch();\n }\n\n /** Flush pending notifications. */\n flushNotifications(): void {\n this.store.flushNotifications();\n }\n}\n\n/**\n * Create a new reactive store.\n *\n * Supports three action definition styles:\n * - **Inline**: Actions defined within state object (functions starting with $)\n * - **Separate**: Actions passed as second argument\n * - **Fluent**: Actions added via `.action()` method\n *\n * @typeParam TState - The type of the store state\n * @param initialState - Initial state object, may include inline actions\n * @param actions - Optional separate actions object\n * @returns A new Store instance\n *\n * @example\n * ```typescript\n * // Style A: Inline actions (prefix with $)\n * const store = createStore({\n * count: 0,\n * $increment: (state) => ({ count: state.count + 1 }),\n * });\n *\n * // Style B: Separate actions\n * const store = createStore(\n * { count: 0 },\n * { increment: (state) => ({ count: state.count + 1 }) }\n * );\n *\n * // Style C: Fluent builder\n * const store = createStore({ count: 0 })\n * .action('increment', (state) => ({ count: state.count + 1 }));\n * ```\n */\nexport function createStore<\n TState,\n TActions extends { [K in keyof TActions]: Action<TState, any[]> } = {}\n>(\n initialState: TState,\n // The Record part gives `state` its type inside an object literal.\n actions?: TActions & Record<string, Action<TState, any[]>>\n): CreatedStore<TState, TActions>;\nexport function createStore<TState, TActions>(\n initialState: TState,\n actions?: TActions\n): CreatedStore<TState, TActions> {\n const kernel = createKernel({ name: 'store' });\n\n // Handle inline actions (properties starting with $)\n const state: any = {};\n const extractedActions: Record<string, (...args: any[]) => any> = {};\n\n for (const key of Object.keys(initialState as object)) {\n const value = (initialState as any)[key];\n if (key === '__proto__') continue;\n if (isFunction(value) && key.startsWith('$')) {\n extractedActions[key.substring(1)] = value as (...args: any[]) => any;\n } else {\n state[key] = value;\n }\n }\n\n // Merge with provided actions\n const allActions: Record<string, (...args: any[]) => any> = { ...extractedActions, ...(actions as any) };\n\n // Create builder for fluent API or regular store\n const builder = new StoreBuilderImpl<TState>(state as TState, kernel);\n\n // Bind every action: callable as store.name(...) and getState().name(...)\n for (const [name, fn] of Object.entries(allActions)) {\n builder.action(name, fn);\n }\n\n // Initialize plugins\n /* c8 ignore start */\n kernel.initializeAll(builder).catch((error) => {\n console.error('Error initializing plugins:', error);\n });\n /* c8 ignore stop */\n\n // Return a Proxy that forwards unknown calls to the underlying store\n // This allows plugins to add methods that are accessible on the builder\n return new Proxy(builder, {\n get(target, prop) {\n if (prop in target) {\n return (target as any)[prop];\n }\n // Forward to the underlying store\n const store = (target as any).store;\n if (store && typeof store[prop] === 'function') {\n return store[prop].bind(store);\n }\n if (store && prop in store) {\n return store[prop];\n }\n return undefined;\n },\n set(target, prop, value) {\n if (prop in target || typeof value === 'function') {\n (target as any)[prop] = value;\n return true;\n }\n // Forward to the underlying store\n const store = (target as any).store;\n /* c8 ignore start */\n if (store) {\n store[prop] = value;\n return true;\n }\n return false;\n /* c8 ignore stop */\n },\n }) as unknown as CreatedStore<TState, TActions>;\n}\n\n// Export for testing\nexport { StoreImpl, BatchContext };\n","/**\n * Enhanced subscription system with advanced options.\n *\n * @module subscribe\n */\n\nimport type { Store, Selector, EqualityFn, Listener } from './types.js';\nimport { shallowEqual } from './utils/index.js';\n\n/**\n * Options for enhanced subscriptions.\n *\n * @typeParam T - The store state type\n * @typeParam U - The selected value type\n *\n * @example\n * ```typescript\n * const options: SubscribeOptions<State, number> = {\n * debounce: 100,\n * fireImmediately: true,\n * when: (state) => state.isReady\n * };\n * ```\n */\nexport interface SubscribeOptions<T, U = T> {\n /** Custom equality function for comparing selected values */\n equalityFn?: EqualityFn<U>;\n /** Fire callback immediately with current state */\n fireImmediately?: boolean;\n /** Debounce notifications (ms) */\n debounce?: number;\n /** Throttle notifications (ms) */\n throttle?: number;\n /** Only fire when condition is met */\n when?: (state: T, prevState: T) => boolean;\n}\n\n/**\n * Creates a debounced function.\n */\nfunction createDebounced<T extends (...args: any[]) => void>(\n fn: T,\n delay: number\n): T & { cancel: () => void } {\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const debounced = ((...args: Parameters<T>) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n fn(...args);\n timeoutId = null;\n }, delay);\n }) as T & { cancel: () => void };\n\n debounced.cancel = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n return debounced;\n}\n\n/**\n * Creates a throttled function.\n */\nfunction createThrottled<T extends (...args: any[]) => void>(\n fn: T,\n delay: number\n): T & { cancel: () => void } {\n let lastCall = 0;\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n let lastArgs: Parameters<T> | null = null;\n\n const throttled = ((...args: Parameters<T>) => {\n const now = Date.now();\n const remaining = delay - (now - lastCall);\n\n lastArgs = args;\n\n if (remaining <= 0) {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n lastCall = now;\n fn(...args);\n } else if (!timeoutId) {\n timeoutId = setTimeout(() => {\n lastCall = Date.now();\n timeoutId = null;\n if (lastArgs) {\n fn(...lastArgs);\n }\n }, remaining);\n }\n }) as T & { cancel: () => void };\n\n throttled.cancel = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n lastArgs = null;\n };\n\n return throttled;\n}\n\n/**\n * Enhanced subscribe function with advanced options.\n *\n * @param store - The store to subscribe to\n * @param selectorOrListener - Selector function or direct listener\n * @param listenerOrOptions - Listener function or options (if no selector)\n * @param options - Subscription options\n * @returns Unsubscribe function\n *\n * @example\n * ```typescript\n * // With debounce\n * const unsubscribe = subscribeWithOptions(\n * store,\n * (state) => state.searchQuery,\n * (query) => performSearch(query),\n * { debounce: 300 }\n * );\n *\n * // With throttle and condition\n * const unsubscribe = subscribeWithOptions(\n * store,\n * (state) => state.scrollPosition,\n * (pos) => updateUI(pos),\n * { throttle: 16, when: (state) => state.isVisible }\n * );\n *\n * // Fire immediately\n * const unsubscribe = subscribeWithOptions(\n * store,\n * (state) => state.user,\n * (user) => console.log('User:', user),\n * { fireImmediately: true }\n * );\n * ```\n */\nexport function subscribeWithOptions<TState, TSelected>(\n store: Store<TState>,\n selector: Selector<TState, TSelected>,\n listener: Listener<TSelected>,\n options: SubscribeOptions<TState, TSelected> = {}\n): () => void {\n const {\n equalityFn = shallowEqual,\n fireImmediately = false,\n debounce,\n throttle,\n when,\n } = options;\n\n // Validate options\n if (debounce !== undefined && throttle !== undefined) {\n throw new Error('Cannot use both debounce and throttle options');\n }\n\n // Wrap listener with debounce/throttle if needed\n let wrappedListener: Listener<TSelected> & { cancel?: () => void } = listener;\n let cleanup: (() => void) | null = null;\n\n if (debounce !== undefined && debounce > 0) {\n const debouncedListener = createDebounced(listener, debounce);\n wrappedListener = debouncedListener;\n cleanup = () => debouncedListener.cancel();\n } else if (throttle !== undefined && throttle > 0) {\n const throttledListener = createThrottled(listener, throttle);\n wrappedListener = throttledListener;\n cleanup = () => throttledListener.cancel();\n }\n\n // Create conditional listener if 'when' is provided\n let finalListener: Listener<TSelected>;\n let prevState: TState = store.getState();\n\n if (when) {\n finalListener = (value, prevValue) => {\n const currentState = store.getState();\n if (when(currentState, prevState)) {\n wrappedListener(value, prevValue);\n }\n prevState = currentState;\n };\n } else {\n finalListener = wrappedListener;\n }\n\n // Fire immediately if requested\n if (fireImmediately) {\n const currentValue = selector(store.getState());\n finalListener(currentValue, currentValue);\n }\n\n // Subscribe with equality function\n const unsubscribe = store.subscribe(selector, finalListener, equalityFn);\n\n // Return unsubscribe function that also cleans up debounce/throttle\n return () => {\n unsubscribe();\n if (cleanup) {\n cleanup();\n }\n };\n}\n\n/**\n * Create a subscription factory with preset options.\n *\n * @param defaultOptions - Default options for all subscriptions\n * @returns A subscribe function with preset options\n *\n * @example\n * ```typescript\n * const debouncedSubscribe = createSubscriber({ debounce: 100 });\n *\n * const unsubscribe = debouncedSubscribe(\n * store,\n * (state) => state.input,\n * (input) => validate(input)\n * );\n * ```\n */\nexport function createSubscriber<TState = any>(\n defaultOptions: SubscribeOptions<TState, any> = {}\n): <S extends TState, TSelected>(\n store: Store<S>,\n selector: Selector<S, TSelected>,\n listener: Listener<TSelected>,\n options?: SubscribeOptions<S, TSelected>\n) => () => void {\n return <S extends TState, TSelected>(\n store: Store<S>,\n selector: Selector<S, TSelected>,\n listener: Listener<TSelected>,\n options: SubscribeOptions<S, TSelected> = {}\n ) => {\n return subscribeWithOptions(store, selector, listener, {\n ...defaultOptions,\n ...options,\n });\n };\n}\n\n/**\n * Subscribe to multiple selectors with a single listener.\n *\n * @param store - The store to subscribe to\n * @param selectors - Object of named selectors\n * @param listener - Listener called when any selector value changes\n * @param options - Subscription options\n * @returns Unsubscribe function\n *\n * @example\n * ```typescript\n * const unsubscribe = subscribeToMany(\n * store,\n * {\n * count: (s) => s.count,\n * name: (s) => s.name,\n * },\n * ({ count, name }) => console.log(`${name}: ${count}`)\n * );\n * ```\n */\nexport function subscribeToMany<TState, TSelectors extends Record<string, Selector<TState, any>>>(\n store: Store<TState>,\n selectors: TSelectors,\n listener: (values: { [K in keyof TSelectors]: ReturnType<TSelectors[K]> }) => void,\n options: Omit<SubscribeOptions<TState, any>, 'equalityFn'> = {}\n): () => void {\n const keys = Object.keys(selectors) as (keyof TSelectors)[];\n let prevValues: { [K in keyof TSelectors]: ReturnType<TSelectors[K]> } = {} as any;\n\n // Initialize prev values\n const state = store.getState();\n for (const key of keys) {\n const selector = selectors[key];\n if (selector) {\n prevValues[key] = selector(state);\n }\n }\n\n // Create combined selector\n const combinedSelector = (state: TState) => {\n const result: any = {};\n for (const key of keys) {\n const selector = selectors[key];\n if (selector) {\n result[key] = selector(state);\n }\n }\n return result;\n };\n\n // Custom equality - check each value\n const combinedEqualityFn = (\n a: { [K in keyof TSelectors]: ReturnType<TSelectors[K]> },\n b: { [K in keyof TSelectors]: ReturnType<TSelectors[K]> }\n ) => {\n for (const key of keys) {\n if (!shallowEqual(a[key], b[key])) {\n return false;\n }\n }\n return true;\n };\n\n return subscribeWithOptions(\n store,\n combinedSelector,\n listener,\n { ...options, equalityFn: combinedEqualityFn }\n );\n}\n\n/**\n * Subscribe only once - automatically unsubscribes after first call.\n *\n * @param store - The store to subscribe to\n * @param selector - Selector function\n * @param listener - Listener called once when value changes\n * @param options - Subscription options\n * @returns Unsubscribe function (can be called to cancel before trigger)\n *\n * @example\n * ```typescript\n * // Wait for user to be loaded\n * subscribeOnce(\n * store,\n * (state) => state.user,\n * (user) => console.log('User loaded:', user),\n * { when: (state) => state.user !== null }\n * );\n * ```\n */\nexport function subscribeOnce<TState, TSelected>(\n store: Store<TState>,\n selector: Selector<TState, TSelected>,\n listener: Listener<TSelected>,\n options: SubscribeOptions<TState, TSelected> = {}\n): () => void {\n let unsubscribe: (() => void) | null = null;\n let fired = false;\n\n const onceListener: Listener<TSelected> = (value, prevValue) => {\n // `fireImmediately` calls this before `unsubscribe` exists.\n if (fired) return;\n fired = true;\n listener(value, prevValue);\n if (unsubscribe) {\n unsubscribe();\n }\n };\n\n unsubscribe = subscribeWithOptions(store, selector, onceListener, options);\n if (fired) {\n unsubscribe();\n }\n return unsubscribe;\n}\n","/**\n * Computed values (derived state) with memoization.\n *\n * @module computed\n */\n\nimport type { Store, Selector, EqualityFn } from './types.js';\nimport { shallowEqual } from './utils/index.js';\n\n/**\n * Options for computed values.\n *\n * @typeParam _TState - The store state type (unused, kept for compatibility)\n * @typeParam U - The computed value type\n */\nexport interface ComputedOptions<_TState, U> {\n /** Custom equality for caching */\n equals?: EqualityFn<U>;\n /** Lazy evaluation (only compute when accessed) */\n lazy?: boolean;\n /** Keep last N values in cache for time-travel debugging */\n cacheSize?: number;\n}\n\n/**\n * Computed value interface with getter and utilities.\n */\nexport interface Computed<U> {\n /** Get the computed value */\n (): U;\n /** Get value (alias) */\n get(): U;\n /** Force recomputation */\n invalidate(): void;\n /** Subscribe to value changes */\n subscribe(listener: (value: U, prevValue: U) => void): () => void;\n /** Get cache history (if cacheSize > 1) */\n getHistory(): U[];\n /** Destroy and cleanup */\n destroy(): void;\n}\n\n/**\n * Cache entry for computed values.\n */\ninterface CacheEntry<T, U> {\n input: T;\n output: U;\n}\n\n/**\n * Create a computed (derived) value from store state.\n *\n * Computed values are memoized and only recompute when dependencies change.\n *\n * @param store - The store to derive from\n * @param selector - Function to compute the derived value\n * @param options - Computed options\n * @returns A computed value accessor\n *\n * @example\n * ```typescript\n * const store = createStore({ items: [], filter: 'all' });\n *\n * // Simple computed\n * const filteredItems = computed(store, (state) => {\n * if (state.filter === 'all') return state.items;\n * return state.items.filter(item => item.status === state.filter);\n * });\n *\n * console.log(filteredItems()); // Get computed value\n *\n * // With caching for debugging\n * const total = computed(\n * store,\n * (state) => state.items.reduce((sum, item) => sum + item.price, 0),\n * { cacheSize: 10 }\n * );\n *\n * console.log(total.getHistory()); // See past values\n * ```\n */\nexport function computed<TState, TComputed>(\n store: Store<TState>,\n selector: Selector<TState, TComputed>,\n options: ComputedOptions<TState, TComputed> = {}\n): Computed<TComputed> {\n const { equals = shallowEqual, lazy = false, cacheSize = 1 } = options;\n\n // Cache storage\n const cache: CacheEntry<TState, TComputed>[] = [];\n let currentValue: TComputed | undefined;\n // Last value delivered to listeners\n let notifiedValue: TComputed | undefined;\n // State the current value was computed from\n let computedFrom: TState | undefined;\n let isInitialized = false;\n let isDestroyed = false;\n\n // Listeners for value changes\n const listeners = new Set<(value: TComputed, prevValue: TComputed) => void>();\n\n // Unsubscribe from store\n let unsubscribe: (() => void) | null = null;\n\n /**\n * Compute value from state, using cache if possible.\n */\n const compute = (state: TState): TComputed => {\n // Check cache\n for (const entry of cache) {\n if (entry.input === state || shallowEqual(entry.input, state)) {\n return entry.output;\n }\n }\n\n // Compute new value\n const newValue = selector(state);\n\n // Add to cache\n cache.unshift({ input: state, output: newValue });\n\n // Trim cache\n while (cache.length > cacheSize) {\n cache.pop();\n }\n\n return newValue;\n };\n\n /**\n * Bring the current value up to date with the store. Reads are always\n * fresh, even before this computed's own store listener has run (e.g. from\n * another listener or from a combined computed).\n */\n const refresh = (): void => {\n const state = store.getState();\n if (isInitialized && state === computedFrom) return;\n const newValue = compute(state);\n if (!isInitialized || !equals(newValue, currentValue as TComputed)) {\n currentValue = newValue;\n }\n computedFrom = state;\n };\n\n /**\n * Notify listeners if the value changed since the last notification.\n */\n const emit = (): void => {\n const prevValue = notifiedValue as TComputed;\n const value = currentValue as TComputed;\n if (equals(value, prevValue)) return;\n notifiedValue = value;\n for (const listener of Array.from(listeners)) {\n try {\n listener(value, prevValue);\n } catch (error) {\n console.error('Computed listener error:', error);\n }\n }\n };\n\n /**\n * Initialize the computed value.\n */\n const initialize = () => {\n if (isInitialized || isDestroyed) return;\n\n // Compute initial value\n refresh();\n isInitialized = true;\n notifiedValue = currentValue;\n\n // Subscribe to store changes\n unsubscribe = store.subscribe(() => {\n refresh();\n emit();\n });\n };\n\n // Initialize immediately if not lazy\n if (!lazy) {\n initialize();\n }\n\n /**\n * Get current computed value.\n */\n const get = (): TComputed => {\n if (isDestroyed) {\n throw new Error('Cannot access destroyed computed value');\n }\n\n // Lazy initialization\n if (!isInitialized) {\n initialize();\n } else {\n refresh();\n }\n\n return currentValue!;\n };\n\n /**\n * Force recomputation.\n */\n const invalidate = (): void => {\n if (isDestroyed) return;\n\n cache.length = 0;\n if (isInitialized) {\n const state = store.getState();\n const newValue = compute(state);\n computedFrom = state;\n if (!equals(newValue, currentValue as TComputed)) {\n currentValue = newValue;\n }\n emit();\n }\n };\n\n /**\n * Subscribe to computed value changes.\n */\n const subscribe = (\n listener: (value: TComputed, prevValue: TComputed) => void\n ): (() => void) => {\n if (isDestroyed) {\n throw new Error('Cannot subscribe to destroyed computed value');\n }\n\n // Ensure initialized\n if (!isInitialized) {\n initialize();\n }\n\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n };\n\n /**\n * Get computation history (cached outputs).\n */\n const getHistory = (): TComputed[] => {\n return cache.map((entry) => entry.output);\n };\n\n /**\n * Destroy the computed value.\n */\n const destroy = (): void => {\n if (isDestroyed) return;\n isDestroyed = true;\n\n if (unsubscribe) {\n unsubscribe();\n unsubscribe = null;\n }\n\n listeners.clear();\n cache.length = 0;\n currentValue = undefined;\n notifiedValue = undefined;\n computedFrom = undefined;\n };\n\n // Create the computed function\n const computedFn = get as Computed<TComputed>;\n computedFn.get = get;\n computedFn.invalidate = invalidate;\n computedFn.subscribe = subscribe;\n computedFn.getHistory = getHistory;\n computedFn.destroy = destroy;\n\n return computedFn;\n}\n\n/**\n * Create a computed value that depends on other computed values.\n *\n * @param computeds - Array of computed values to depend on\n * @param combiner - Function to combine the computed values\n * @param options - Computed options\n * @returns A combined computed value\n *\n * @example\n * ```typescript\n * const subtotal = computed(store, (s) => s.items.reduce((sum, i) => sum + i.price, 0));\n * const tax = computed(store, (s) => s.taxRate);\n *\n * const total = combineComputed(\n * [subtotal, tax],\n * ([subtotalVal, taxVal]) => subtotalVal * (1 + taxVal)\n * );\n *\n * console.log(total()); // Subtotal + tax\n * ```\n */\nexport function combineComputed<TInputs extends Computed<any>[], TOutput>(\n computeds: [...TInputs],\n combiner: (values: { [K in keyof TInputs]: TInputs[K] extends Computed<infer U> ? U : never }) => TOutput,\n options: Omit<ComputedOptions<any, TOutput>, 'lazy'> = {}\n): Computed<TOutput> {\n const { equals = shallowEqual, cacheSize = 1 } = options;\n\n let currentValue: TOutput | undefined;\n let isDestroyed = false;\n const listeners = new Set<(value: TOutput, prevValue: TOutput) => void>();\n const unsubscribes: (() => void)[] = [];\n const cache: TOutput[] = [];\n\n /**\n * Compute combined value.\n */\n const compute = (): TOutput => {\n const values = computeds.map((c) => c()) as any;\n return combiner(values);\n };\n\n // Value last delivered to listeners\n let notifiedValue: TOutput;\n\n // Recompute from the (always fresh) inputs; keep the old reference when equal.\n const refresh = (): void => {\n const newValue = compute();\n if (!equals(newValue, currentValue as TOutput)) {\n currentValue = newValue;\n cache.unshift(newValue);\n while (cache.length > cacheSize) {\n cache.pop();\n }\n }\n };\n\n // Initialize\n currentValue = compute();\n cache.push(currentValue);\n notifiedValue = currentValue;\n\n // Subscribe to all source computeds\n for (const computed of computeds) {\n const unsub = computed.subscribe(() => {\n if (isDestroyed) return;\n\n refresh();\n const prevValue = notifiedValue;\n const value = currentValue as TOutput;\n if (equals(value, prevValue)) return;\n notifiedValue = value;\n\n for (const listener of Array.from(listeners)) {\n try {\n listener(value, prevValue);\n } catch (error) {\n console.error('Combined computed listener error:', error);\n }\n }\n });\n unsubscribes.push(unsub);\n }\n\n const get = (): TOutput => {\n if (isDestroyed) {\n throw new Error('Cannot access destroyed computed value');\n }\n refresh();\n return currentValue!;\n };\n\n const invalidate = (): void => {\n if (isDestroyed) return;\n for (const computed of computeds) {\n computed.invalidate();\n }\n };\n\n const subscribe = (\n listener: (value: TOutput, prevValue: TOutput) => void\n ): (() => void) => {\n if (isDestroyed) {\n throw new Error('Cannot subscribe to destroyed computed value');\n }\n listeners.add(listener);\n return () => listeners.delete(listener);\n };\n\n const getHistory = (): TOutput[] => [...cache];\n\n const destroy = (): void => {\n if (isDestroyed) return;\n isDestroyed = true;\n for (const unsub of unsubscribes) {\n unsub();\n }\n listeners.clear();\n cache.length = 0;\n };\n\n const combinedFn = get as Computed<TOutput>;\n combinedFn.get = get;\n combinedFn.invalidate = invalidate;\n combinedFn.subscribe = subscribe;\n combinedFn.getHistory = getHistory;\n combinedFn.destroy = destroy;\n\n return combinedFn;\n}\n\n/**\n * Create a memoized selector for use with store.subscribe.\n *\n * @param selector - The selector function to memoize\n * @param equals - Custom equality function\n * @returns A memoized selector\n *\n * @example\n * ```typescript\n * const selectExpensiveComputation = memoizeSelector(\n * (state: State) => expensiveOperation(state.data)\n * );\n *\n * store.subscribe(selectExpensiveComputation, (result) => {\n * console.log('Result:', result);\n * });\n * ```\n */\nexport function memoizeSelector<TState, TSelected>(\n selector: Selector<TState, TSelected>,\n equals: EqualityFn<TSelected> = shallowEqual\n): Selector<TState, TSelected> {\n let lastState: TState | undefined;\n let lastResult: TSelected | undefined;\n let isInitialized = false;\n\n return (state: TState): TSelected => {\n if (!isInitialized || lastState !== state) {\n const newResult = selector(state);\n\n if (!isInitialized || !equals(newResult, lastResult!)) {\n lastResult = newResult;\n }\n\n lastState = state;\n isInitialized = true;\n }\n\n return lastResult!;\n };\n}\n","/**\n * Slices pattern for modular store composition.\n *\n * @module slices\n */\n\nimport type { Store } from './types.js';\nimport { createStore } from './store.js';\nimport { deepClone } from './utils/deep-clone.js';\n\n/**\n * Initial data of each slice, per store, for resetSlices().\n */\nconst sliceRegistry = new WeakMap<object, Map<string, Record<string, unknown>>>();\n\nfunction registerSlice(store: object, name: string, data: Record<string, unknown>): void {\n let slices = sliceRegistry.get(store);\n if (!slices) {\n slices = new Map();\n sliceRegistry.set(store, slices);\n }\n slices.set(name, data);\n}\n\n/**\n * Put a slice action on the state (`getState().name()`), as createStore does\n * for its actions. Stores from createStore keep it across `reset()`; other\n * Store implementations get it through setState.\n */\nfunction exposeAction(store: object, name: string, action: (...args: any[]) => unknown): void {\n const target = store as {\n exposeAction?: (name: string, fn: (...args: any[]) => unknown) => void;\n setState: (partial: Record<string, unknown>) => void;\n };\n if (typeof target.exposeAction === 'function') {\n target.exposeAction(name, action);\n } else if (name !== '__proto__') {\n target.setState({ [name]: action });\n }\n}\n\n/**\n * SetSlice function type for updating slice state.\n */\nexport type SetSlice<TState> = (\n partial: Partial<TState> | ((state: TState) => Partial<TState>)\n) => void;\n\n/**\n * GetSlice function type for getting current state.\n */\nexport type GetSlice<TState> = () => TState;\n\n/**\n * Slice creator function signature.\n *\n * @typeParam TState - The full store state type\n * @typeParam TSlice - The slice state type\n */\nexport type SliceCreator<TState, TSlice extends Partial<TState>> = (\n set: SetSlice<TState>,\n get: GetSlice<TState>,\n store: Store<TState>\n) => TSlice;\n\n/**\n * Slice definition with state and actions.\n */\nexport interface SliceDefinition<TState, TSlice extends Partial<TState>> {\n /** Slice name for debugging */\n name: string;\n /** Slice creator function */\n creator: SliceCreator<TState, TSlice>;\n}\n\n/**\n * Create a slice definition for use with combineSlices.\n *\n * Slices are modular pieces of state and actions that can be combined\n * to create a complete store.\n *\n * @param name - Slice name for debugging\n * @param creator - Slice creator function\n * @returns A slice definition\n *\n * @example\n * ```typescript\n * // Define a counter slice\n * const counterSlice = createSlice('counter', (set, get) => ({\n * count: 0,\n * increment: () => set((s) => ({ count: s.count + 1 })),\n * decrement: () => set((s) => ({ count: s.count - 1 })),\n * reset: () => set({ count: 0 }),\n * }));\n *\n * // Define a user slice\n * const userSlice = createSlice('user', (set, get) => ({\n * user: null as User | null,\n * setUser: (user: User) => set({ user }),\n * logout: () => set({ user: null }),\n * }));\n *\n * // Combine slices into a store\n * const store = combineSlices(counterSlice, userSlice);\n *\n * // Use the store\n * store.increment();\n * store.setUser({ name: 'John' });\n * ```\n */\nexport function createSlice<TState = any, TSlice extends Partial<TState> = Partial<TState>>(\n name: string,\n creator: SliceCreator<TState, TSlice>\n): SliceDefinition<TState, TSlice> {\n return { name, creator };\n}\n\n/**\n * Internal slice creator type for type inference.\n */\ntype InferSlice<T> = T extends SliceDefinition<any, infer S> ? S : never;\n\n/**\n * Combined state type from multiple slices.\n */\ntype UnionToIntersection<U> = (U extends unknown ? (value: U) => void : never) extends (\n value: infer I\n) => void\n ? I\n : never;\n\ntype CombinedState<TSlices extends SliceDefinition<any, any>[]> = UnionToIntersection<\n { [K in keyof TSlices]: InferSlice<TSlices[K]> }[number]\n> extends infer I\n ? { [K in keyof I]: I[K] }\n : never;\n\n/**\n * Combine multiple slices into a single store.\n *\n * @param slices - Slice definitions to combine\n * @returns A store with combined state and actions\n *\n * @example\n * ```typescript\n * const counterSlice = createSlice('counter', (set) => ({\n * count: 0,\n * increment: () => set((s) => ({ count: s.count + 1 })),\n * }));\n *\n * const userSlice = createSlice('user', (set) => ({\n * user: null,\n * setUser: (user) => set({ user }),\n * }));\n *\n * const store = combineSlices(counterSlice, userSlice);\n *\n * // Type-safe access to all slice methods\n * store.increment();\n * store.setUser({ name: 'John' });\n * ```\n */\nexport function combineSlices<TSlices extends SliceDefinition<any, any>[]>(\n ...slices: TSlices\n): Store<CombinedState<TSlices>> & CombinedState<TSlices> {\n // First pass: collect initial state from all slices\n const initialState: any = {};\n const actions: Record<string, Function> = {};\n\n // Create a temporary store to pass to slice creators\n // We'll replace its state after collecting from all slices\n let tempStore: Store<any> | null = null;\n\n const set: SetSlice<any> = (partial) => {\n if (tempStore) {\n if (typeof partial === 'function') {\n tempStore.setState(partial);\n } else {\n tempStore.setState(partial);\n }\n }\n };\n\n const get: GetSlice<any> = () => {\n return tempStore ? tempStore.getState() : initialState;\n };\n\n // Create placeholder store for initial state collection\n const placeholderStore = {\n getState: () => initialState,\n setState: () => {},\n subscribe: () => () => {},\n merge: () => {},\n reset: () => {},\n use: () => placeholderStore,\n destroy: () => {},\n } as Store<any>;\n\n // Collect initial state and actions from all slices\n const sliceData = new Map<string, Record<string, unknown>>();\n for (const slice of slices) {\n const sliceResult = slice.creator(set, get, placeholderStore);\n const data: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(sliceResult)) {\n if (typeof value === 'function') {\n actions[key] = value;\n } else {\n initialState[key] = value;\n data[key] = value;\n }\n }\n sliceData.set(slice.name, data);\n }\n\n // Create the actual store\n tempStore = createStore(initialState);\n\n // Re-run slice creators with the actual store to bind actions\n for (const slice of slices) {\n const sliceResult = slice.creator(\n (partial) => {\n if (typeof partial === 'function') {\n tempStore!.setState(partial);\n } else {\n tempStore!.setState(partial);\n }\n },\n () => tempStore!.getState(),\n tempStore\n );\n\n // Update actions with properly bound versions\n for (const [key, value] of Object.entries(sliceResult)) {\n if (typeof value === 'function') {\n actions[key] = value;\n }\n }\n }\n\n for (const [name, data] of sliceData) {\n registerSlice(tempStore, name, data);\n }\n\n // Add actions to the store and to its state (as createStore does)\n const store = tempStore as any;\n for (const [name, action] of Object.entries(actions)) {\n store[name] = action;\n exposeAction(store, name, action as (...args: any[]) => unknown);\n }\n\n return store;\n}\n\n/**\n * Create a namespaced slice that prefixes all state keys.\n *\n * @param namespace - The namespace prefix\n * @param creator - Slice creator function\n * @returns A namespaced slice definition\n *\n * @example\n * ```typescript\n * const settingsSlice = createNamespacedSlice('settings', (set) => ({\n * theme: 'dark',\n * language: 'en',\n * setTheme: (theme) => set({ theme }),\n * }));\n *\n * // State will be: { settings: { theme: 'dark', language: 'en' } }\n * // Actions will be: setTheme\n * ```\n */\nexport function createNamespacedSlice<TSlice extends Record<string, any>>(\n namespace: string,\n creator: (\n set: (partial: Partial<TSlice>) => void,\n get: () => TSlice\n ) => TSlice\n): SliceDefinition<Record<string, any>, Record<string, any>> {\n return createSlice(namespace, (set, get) => {\n // Wrapper set that updates the namespaced state\n const namespacedSet = (partial: Partial<TSlice> | ((current: TSlice) => Partial<TSlice>)) => {\n const current = (get()[namespace] || {}) as TSlice;\n const update = typeof partial === 'function' ? partial(current) : partial;\n set({ [namespace]: { ...current, ...update } } as any);\n };\n\n // Wrapper get that returns namespaced state\n const namespacedGet = (): TSlice => {\n return (get()[namespace] || {}) as TSlice;\n };\n\n // Get slice result\n const sliceResult = creator(namespacedSet, namespacedGet);\n\n // Separate state and actions\n const state: any = {};\n const actions: any = {};\n\n for (const [key, value] of Object.entries(sliceResult)) {\n if (typeof value === 'function') {\n actions[key] = value;\n } else {\n state[key] = value;\n }\n }\n\n // Return namespaced state with actions at root\n return {\n [namespace]: state,\n ...actions,\n };\n });\n}\n\n/**\n * Extend an existing store with additional slices.\n *\n * @param store - The existing store\n * @param slices - Additional slices to add\n * @returns The extended store\n *\n * @example\n * ```typescript\n * const baseStore = createStore({ count: 0 });\n *\n * const extendedStore = extendStore(\n * baseStore,\n * createSlice('user', (set) => ({\n * user: null,\n * setUser: (user) => set({ user }),\n * }))\n * );\n * ```\n */\nexport function extendStore<TState, TSlices extends SliceDefinition<TState & any, any>[]>(\n store: Store<TState>,\n ...slices: TSlices\n): Store<TState & CombinedState<TSlices>> & CombinedState<TSlices> {\n const actions: Record<string, Function> = {};\n\n const set: SetSlice<any> = (partial) => {\n if (typeof partial === 'function') {\n store.setState(partial as any);\n } else {\n store.setState(partial as any);\n }\n };\n\n const get: GetSlice<any> = () => store.getState();\n\n // Process each slice\n for (const slice of slices) {\n const sliceResult = slice.creator(set, get, store as any);\n const data: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(sliceResult)) {\n if (typeof value === 'function') {\n actions[key] = value;\n // On the state as well, as createStore does for its actions\n exposeAction(store, key, value as (...args: any[]) => unknown);\n } else {\n // Merge initial state\n store.setState({ [key]: value } as any);\n data[key] = value;\n }\n }\n registerSlice(store, slice.name, data);\n }\n\n // Add actions to store\n const extendedStore = store as any;\n for (const [name, action] of Object.entries(actions)) {\n extendedStore[name] = action;\n }\n\n return extendedStore;\n}\n\n/**\n * Reset specific slices to their initial state.\n *\n * @param store - The store\n * @param sliceNames - Names of slices to reset\n *\n * @example\n * ```typescript\n * // Reset only the user slice\n * resetSlices(store, 'user');\n *\n * // Reset multiple slices\n * resetSlices(store, 'user', 'cart');\n * ```\n */\nexport function resetSlices<TState>(\n store: Store<TState>,\n ...sliceNames: string[]\n): void {\n const slices = sliceRegistry.get(store);\n if (!slices) {\n // Not built with combineSlices/extendStore: slice boundaries are unknown.\n console.warn('resetSlices: store was not created with combineSlices/extendStore; resetting all state');\n store.reset();\n return;\n }\n\n const update: Record<string, unknown> = {};\n for (const name of sliceNames) {\n const data = slices.get(name);\n if (!data) {\n console.warn(`resetSlices: unknown slice '${name}'`);\n continue;\n }\n Object.assign(update, data);\n }\n if (Object.keys(update).length > 0) {\n store.setState(deepClone(update) as Partial<TState>);\n }\n}\n","/**\n * Store Federation - Multi-store coordination and communication.\n *\n * Enables coordinated updates across multiple stores with\n * atomic transactions and unified state access.\n *\n * @module federation\n */\n\nimport type { Store } from './types.js';\n\n/**\n * Extract state type from a Store.\n */\nexport type StoreState<S> = S extends Store<infer T> ? T : never;\n\n/**\n * Map of store names to their state types.\n */\nexport type FederatedState<Stores extends Record<string, Store<any>>> = {\n [K in keyof Stores]: StoreState<Stores[K]>;\n};\n\n/**\n * Federation listener callback.\n */\nexport type FederationListener<Stores extends Record<string, Store<any>>> = (\n state: FederatedState<Stores>,\n prevState: FederatedState<Stores>,\n changedStore: keyof Stores\n) => void;\n\n/**\n * Federation transaction function.\n */\nexport type TransactionFn<Stores extends Record<string, Store<any>>> = (\n stores: Stores\n) => void | Promise<void>;\n\n/**\n * Federation options.\n */\nexport interface FederationOptions {\n /** Name for debugging */\n name?: string;\n /** Enable transaction logging */\n debug?: boolean;\n}\n\n/**\n * Federation interface for coordinating multiple stores.\n */\nexport interface Federation<Stores extends Record<string, Store<any>>> {\n /** Access to individual stores */\n readonly stores: Stores;\n\n /** Get combined state from all stores */\n getState(): FederatedState<Stores>;\n\n /** Subscribe to any store change */\n subscribe(listener: FederationListener<Stores>): () => void;\n\n /** Atomic multi-store update (synchronous) */\n transaction(fn: TransactionFn<Stores>): void;\n\n /** Async transaction with rollback on error */\n transactionAsync(fn: TransactionFn<Stores>): Promise<void>;\n\n /** Get a specific store */\n getStore<K extends keyof Stores>(name: K): Stores[K];\n\n /** Subscribe to the changes of one member store. */\n subscribeStore<K extends keyof Stores>(\n name: K,\n listener: (state: StoreState<Stores[K]>, prevState: StoreState<Stores[K]>) => void\n ): () => void;\n\n /** Destroy federation and unsubscribe from all stores */\n destroy(): void;\n}\n\n/**\n * Create a federation of multiple stores.\n *\n * @param stores - Object containing named stores\n * @param options - Federation options\n * @returns A federation instance\n *\n * @example\n * ```typescript\n * import { createStore, createFederation } from '@oxog/state';\n *\n * // Create individual stores\n * const userStore = createStore({\n * user: null,\n * setUser: (state, user) => ({ user }),\n * });\n *\n * const cartStore = createStore({\n * items: [],\n * addItem: (state, item) => ({ items: [...state.items, item] }),\n * clear: () => ({ items: [] }),\n * });\n *\n * const settingsStore = createStore({\n * theme: 'light',\n * setTheme: (state, theme) => ({ theme }),\n * });\n *\n * // Create federation\n * const federation = createFederation({\n * user: userStore,\n * cart: cartStore,\n * settings: settingsStore,\n * });\n *\n * // Get combined state\n * const state = federation.getState();\n * // { user: { user: null, ... }, cart: { items: [], ... }, settings: { theme: 'light', ... } }\n *\n * // Subscribe to any store change\n * federation.subscribe((state, prevState, changedStore) => {\n * console.log(`${changedStore} changed:`, state[changedStore]);\n * });\n *\n * // Atomic cross-store transaction\n * federation.transaction(({ user, cart }) => {\n * cart.setState({ items: [] });\n * user.setState({ user: null });\n * });\n * ```\n */\nexport function createFederation<Stores extends Record<string, Store<any>>>(\n stores: Stores,\n options: FederationOptions = {}\n): Federation<Stores> {\n const { name = 'federation', debug = false } = options;\n\n const listeners = new Set<FederationListener<Stores>>();\n const unsubscribers: (() => void)[] = [];\n let isInTransaction = false;\n let transactionChanges: (keyof Stores)[] = [];\n let previousStates: FederatedState<Stores> | null = null;\n\n // Get combined state\n const getState = (): FederatedState<Stores> => {\n const state = {} as FederatedState<Stores>;\n for (const key in stores) {\n const store = stores[key];\n if (store) {\n state[key] = store.getState();\n }\n }\n return state;\n };\n\n // Notify listeners\n const notify = (changedStore: keyof Stores) => {\n if (isInTransaction) {\n if (!transactionChanges.includes(changedStore)) {\n transactionChanges.push(changedStore);\n }\n return;\n }\n\n const state = getState();\n const prevState = previousStates || state;\n\n for (const listener of listeners) {\n try {\n listener(state, prevState, changedStore);\n } catch (error) {\n console.error(`Federation listener error:`, error);\n }\n }\n\n previousStates = state;\n };\n\n // Subscribe to all stores\n for (const key in stores) {\n const store = stores[key];\n if (store) {\n const unsubscribe = store.subscribe(() => {\n notify(key);\n });\n unsubscribers.push(unsubscribe);\n }\n }\n\n // Initialize previous states\n previousStates = getState();\n\n // Log helper\n const log = (message: string, ...args: any[]) => {\n if (debug) {\n console.log(`[${name}] ${message}`, ...args);\n }\n };\n\n return {\n stores,\n\n getState,\n\n subscribe(listener: FederationListener<Stores>) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n\n transaction(fn: TransactionFn<Stores>) {\n if (isInTransaction) {\n // Nested transaction - just execute\n fn(stores);\n return;\n }\n\n isInTransaction = true;\n transactionChanges = [];\n const snapshotStates = getState();\n\n log('Transaction started');\n\n try {\n const result = fn(stores);\n\n // Check if async (should use transactionAsync)\n if (result instanceof Promise) {\n throw new Error(\n 'Async operations in transaction() are not supported. Use transactionAsync() instead.'\n );\n }\n\n isInTransaction = false;\n\n // Notify for all changed stores\n if (transactionChanges.length > 0) {\n log('Transaction committed, changed stores:', transactionChanges);\n const state = getState();\n\n for (const listener of listeners) {\n try {\n // Notify once with the first changed store\n listener(state, snapshotStates, transactionChanges[0]!);\n } catch (error) {\n console.error(`Federation listener error:`, error);\n }\n }\n\n previousStates = state;\n }\n } catch (error) {\n isInTransaction = false;\n\n // Rollback all stores to snapshot\n log('Transaction failed, rolling back');\n for (const key in stores) {\n const store = stores[key];\n if (store) {\n store.setState(snapshotStates[key] as any);\n }\n }\n\n throw error;\n }\n },\n\n async transactionAsync(fn: TransactionFn<Stores>) {\n if (isInTransaction) {\n // Nested transaction\n await fn(stores);\n return;\n }\n\n isInTransaction = true;\n transactionChanges = [];\n const snapshotStates = getState();\n\n log('Async transaction started');\n\n try {\n await fn(stores);\n\n isInTransaction = false;\n\n // Notify for all changed stores\n if (transactionChanges.length > 0) {\n log('Async transaction committed, changed stores:', transactionChanges);\n const state = getState();\n\n for (const listener of listeners) {\n try {\n listener(state, snapshotStates, transactionChanges[0]!);\n } catch (error) {\n console.error(`Federation listener error:`, error);\n }\n }\n\n previousStates = state;\n }\n } catch (error) {\n isInTransaction = false;\n\n // Rollback all stores to snapshot\n log('Async transaction failed, rolling back');\n for (const key in stores) {\n const store = stores[key];\n if (store) {\n store.setState(snapshotStates[key] as any);\n }\n }\n\n throw error;\n }\n },\n\n getStore<K extends keyof Stores>(storeName: K): Stores[K] {\n return stores[storeName];\n },\n\n subscribeStore<K extends keyof Stores>(\n storeName: K,\n listener: (state: StoreState<Stores[K]>, prevState: StoreState<Stores[K]>) => void\n ): () => void {\n const store = stores[storeName];\n if (!store) {\n throw new Error(`Unknown store '${String(storeName)}' in federation '${name}'`);\n }\n const unsubscribe = store.subscribe(listener);\n unsubscribers.push(unsubscribe);\n return unsubscribe;\n },\n\n destroy() {\n log('Destroying federation');\n for (const unsubscribe of unsubscribers) {\n unsubscribe();\n }\n listeners.clear();\n },\n };\n}\n\n/**\n * Create a selector that combines state from multiple stores.\n *\n * @param federation - The federation instance\n * @param selector - Selector function\n * @returns A function that returns the selected value\n *\n * @example\n * ```typescript\n * const getCartTotal = createFederatedSelector(\n * federation,\n * (state) => {\n * const items = state.cart.items;\n * const discount = state.user.user?.discount || 0;\n * const total = items.reduce((sum, item) => sum + item.price, 0);\n * return total * (1 - discount);\n * }\n * );\n *\n * const total = getCartTotal();\n * ```\n */\nexport function createFederatedSelector<\n Stores extends Record<string, Store<any>>,\n R\n>(\n federation: Federation<Stores>,\n selector: (state: FederatedState<Stores>) => R\n): () => R {\n return () => selector(federation.getState());\n}\n\n/**\n * Create a computed value from federated state.\n *\n * @param federation - The federation instance\n * @param selector - Selector function\n * @param equalityFn - Optional equality function for caching\n * @returns Object with get() and subscribe() methods\n *\n * @example\n * ```typescript\n * const isLoggedIn = createFederatedComputed(\n * federation,\n * (state) => state.user.user !== null\n * );\n *\n * // Get current value\n * if (isLoggedIn.get()) {\n * showDashboard();\n * }\n *\n * // Subscribe to changes\n * isLoggedIn.subscribe((value) => {\n * console.log('Login status:', value);\n * });\n * ```\n */\nexport function createFederatedComputed<\n Stores extends Record<string, Store<any>>,\n R\n>(\n federation: Federation<Stores>,\n selector: (state: FederatedState<Stores>) => R,\n equalityFn: (a: R, b: R) => boolean = Object.is\n): {\n get(): R;\n subscribe(listener: (value: R, prevValue: R) => void): () => void;\n} {\n let cachedValue = selector(federation.getState());\n const listeners = new Set<(value: R, prevValue: R) => void>();\n\n federation.subscribe((state) => {\n const newValue = selector(state);\n if (!equalityFn(newValue, cachedValue)) {\n const prevValue = cachedValue;\n cachedValue = newValue;\n for (const listener of listeners) {\n listener(newValue, prevValue);\n }\n }\n });\n\n return {\n get() {\n return cachedValue;\n },\n subscribe(listener: (value: R, prevValue: R) => void) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n\n/**\n * Wait for a condition across federated stores.\n *\n * @param federation - The federation instance\n * @param predicate - Condition to wait for\n * @param timeout - Optional timeout in ms\n * @returns Promise that resolves when condition is met\n *\n * @example\n * ```typescript\n * // Wait for user to be logged in and cart to have items\n * await waitForFederated(\n * federation,\n * (state) => state.user.user !== null && state.cart.items.length > 0,\n * 5000 // 5 second timeout\n * );\n *\n * // Now proceed with checkout\n * checkout();\n * ```\n */\nexport function waitForFederated<Stores extends Record<string, Store<any>>>(\n federation: Federation<Stores>,\n predicate: (state: FederatedState<Stores>) => boolean,\n timeout?: number\n): Promise<FederatedState<Stores>> {\n return new Promise((resolve, reject) => {\n // Check if already satisfied\n const state = federation.getState();\n if (predicate(state)) {\n resolve(state);\n return;\n }\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let unsubscribe: (() => void) | undefined;\n\n const cleanup = () => {\n if (timeoutId) clearTimeout(timeoutId);\n if (unsubscribe) unsubscribe();\n };\n\n if (timeout) {\n timeoutId = setTimeout(() => {\n cleanup();\n reject(new Error(`waitForFederated timed out after ${timeout}ms`));\n }, timeout);\n }\n\n unsubscribe = federation.subscribe((state) => {\n if (predicate(state)) {\n cleanup();\n resolve(state);\n }\n });\n });\n}\n","/**\n * Persist plugin - Save and restore state from storage.\n *\n * Automatically persists state to localStorage, sessionStorage, or any\n * storage implementation. State is restored on store creation.\n *\n * @example\n * ```typescript\n * import { createStore, persist } from '@oxog/state';\n *\n * const store = createStore({ count: 0, user: null })\n * .use(persist({\n * key: 'my-app',\n * storage: localStorage,\n * whitelist: ['count'] // Only persist count\n * }));\n * ```\n */\n\n// Global type declarations\ninterface Storage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n clear?: () => void;\n length?: number;\n key?: (index: number) => string | null;\n}\n\ndeclare const window: {\n localStorage: Storage;\n sessionStorage: Storage;\n} | undefined;\n\nimport type { Plugin, Store } from '../types.js';\nimport type { PersistOptions, StorageLike } from './types.js';\nimport { pick, omit } from '../utils/index.js';\n\n/**\n * Default localStorage implementation.\n */\nconst defaultStorage: StorageLike = {\n getItem: (key: string): string | null => {\n /* c8 ignore next */\n if (typeof window === 'undefined') return null;\n try {\n return window.localStorage.getItem(key);\n } catch {\n return null;\n }\n },\n setItem: (key: string, value: string): void => {\n /* c8 ignore next */\n if (typeof window === 'undefined') return;\n // Errors (QuotaExceededError, SecurityError) propagate to the persist\n // plugin, which reports them through onPersistError / console.error.\n window.localStorage.setItem(key, value);\n },\n /* c8 ignore next 3 */\n removeItem: (): void => {\n // No-op: removeItem is not used by persist plugin\n },\n};\n\n/**\n * SessionStorage implementation.\n */\nexport const sessionStorage: StorageLike = {\n getItem: (key: string): string | null => {\n /* c8 ignore next */\n if (typeof window === 'undefined') return null;\n try {\n return window.sessionStorage.getItem(key);\n } catch {\n return null;\n }\n },\n setItem: (key: string, value: string): void => {\n /* c8 ignore next */\n if (typeof window === 'undefined') return;\n // Errors propagate so the persist plugin can report them.\n window.sessionStorage.setItem(key, value);\n },\n removeItem: (key: string): void => {\n /* c8 ignore next */\n if (typeof window === 'undefined') return;\n try {\n window.sessionStorage.removeItem(key);\n } catch {\n // Ignore storage errors\n }\n },\n};\n\n/**\n * Create a debounced function for persist writes.\n */\nfunction createDebounced<T extends (...args: any[]) => any>(\n fn: T,\n delay: number\n): T & { flush: () => void } {\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n let pendingArgs: Parameters<T> | null = null;\n\n const debounced = ((...args: Parameters<T>) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n pendingArgs = args;\n timeoutId = setTimeout(() => {\n timeoutId = null;\n const callArgs = pendingArgs!;\n pendingArgs = null;\n fn(...callArgs);\n }, delay);\n }) as T & { flush: () => void };\n\n // Run a pending call now (used on destroy so the last change is saved).\n debounced.flush = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n const callArgs = pendingArgs!;\n pendingArgs = null;\n fn(...callArgs);\n }\n };\n\n return debounced;\n}\n\n/**\n * Storage wrapper with versioning.\n */\ninterface PersistedData<T> {\n state: T;\n version: number;\n}\n\n/**\n * Create a persist plugin.\n *\n * @param options - Plugin options\n * @returns A persist plugin\n *\n * @example\n * ```typescript\n * import { persist, sessionStorage } from '@oxog/state';\n *\n * // Using localStorage (default)\n * const store = createStore({ count: 0 })\n * .use(persist({ key: 'counter' }));\n *\n * // Using sessionStorage\n * const store = createStore({ count: 0 })\n * .use(persist({ key: 'counter', storage: sessionStorage }));\n *\n * // With whitelist\n * const store = createStore({ count: 0, temp: '' })\n * .use(persist({ key: 'app', whitelist: ['count'] }));\n *\n * // With encryption\n * const store = createStore({ secret: 'data' })\n * .use(persist({\n * key: 'secure',\n * encrypt: (data) => btoa(data),\n * decrypt: (data) => atob(data),\n * }));\n *\n * // With debounce and migration\n * const store = createStore({ count: 0 })\n * .use(persist({\n * key: 'app',\n * writeDebounce: 1000,\n * version: 2,\n * migrate: (state, version) => {\n * if (version < 2) return { ...state, newField: 'default' };\n * return state;\n * },\n * }));\n * ```\n */\nexport function persist<TState>(options: PersistOptions<TState>): Plugin<TState> {\n const {\n key,\n storage = defaultStorage,\n whitelist,\n blacklist,\n partialize,\n merge: customMerge,\n version = 0,\n migrate,\n serialize = JSON.stringify,\n deserialize = JSON.parse,\n encrypt,\n decrypt,\n writeDebounce,\n onRehydrateStorage,\n onHydrationComplete,\n onPersistError,\n } = options;\n\n let flushDebounce: (() => void) | null = null;\n\n return {\n name: 'persist',\n version: '1.0.0',\n install(store: Store<TState>) {\n // Hydrate state from storage\n try {\n let saved = storage.getItem(key);\n\n // Decrypt if needed\n if (saved && decrypt) {\n try {\n saved = decrypt(saved);\n } catch {\n // Decryption failed, treat as no saved data\n saved = null;\n }\n }\n\n if (saved) {\n let parsed: Partial<TState>;\n let persistedVersion = 0;\n\n // Try to parse with versioning\n try {\n const data = deserialize(saved) as PersistedData<Partial<TState>> | Partial<TState>;\n\n // Check if it's versioned data\n if (data && typeof data === 'object' && 'state' in data && 'version' in data) {\n parsed = (data as PersistedData<Partial<TState>>).state;\n persistedVersion = (data as PersistedData<Partial<TState>>).version;\n } else {\n parsed = data as Partial<TState>;\n }\n } catch {\n // Fallback to direct parse\n parsed = deserialize(saved);\n }\n\n // Call onRehydrateStorage\n if (onRehydrateStorage) {\n onRehydrateStorage(parsed as TState);\n }\n\n // Run migration if needed\n if (migrate && persistedVersion < version) {\n parsed = migrate(parsed, persistedVersion) as Partial<TState>;\n }\n\n // Merge with current state\n if (customMerge) {\n const currentState = store.getState();\n const mergedState = customMerge(parsed, currentState);\n store.setState(mergedState as any);\n } else {\n store.merge(parsed as any);\n }\n\n // Call onHydrationComplete\n if (onHydrationComplete) {\n onHydrationComplete(store.getState());\n }\n }\n } catch (error) {\n if (onPersistError) {\n onPersistError(error as Error);\n } else {\n console.error(`Failed to hydrate state from '${key}':`, error);\n }\n }\n\n // Persist function\n const persistState = (state: TState) => {\n try {\n let toSave: Partial<TState> = state;\n\n // Apply partialize first\n if (partialize) {\n toSave = partialize(state);\n } else if (whitelist) {\n toSave = pick(state as any, whitelist) as Partial<TState>;\n } else if (blacklist) {\n toSave = omit(state as any, blacklist) as unknown as Partial<TState>;\n }\n\n // Wrap with version\n const dataToStore: PersistedData<Partial<TState>> = {\n state: toSave,\n version,\n };\n\n // Serialize\n let serialized = serialize(dataToStore as any);\n\n // Encrypt if needed\n if (encrypt) {\n serialized = encrypt(serialized);\n }\n\n storage.setItem(key, serialized);\n } catch (error) {\n if (onPersistError) {\n onPersistError(error as Error);\n } else {\n console.error(`Failed to persist state to '${key}':`, error);\n }\n }\n };\n\n // Apply debounce if configured\n let debouncedPersist: (state: TState) => void = persistState;\n if (writeDebounce && writeDebounce > 0) {\n const debounced = createDebounced(persistState, writeDebounce);\n flushDebounce = debounced.flush;\n debouncedPersist = debounced;\n }\n\n // Subscribe to state changes and persist\n store.subscribe(debouncedPersist);\n },\n onDestroy() {\n // Write a pending debounced change now instead of dropping it\n if (flushDebounce) {\n flushDebounce();\n flushDebounce = null;\n }\n },\n };\n}\n\n/**\n * Create a custom storage from a storage object.\n *\n * @param storage - Any object with getItem, setItem, removeItem\n * @returns A StorageLike interface\n *\n * @example\n * ```typescript\n * import { createStorage } from '@oxog/state';\n *\n * const AsyncStorage = createStorage({\n * getItem: async (key) => await AsyncStorage.getItem(key),\n * setItem: async (key, value) => await AsyncStorage.setItem(key, value),\n * removeItem: async (key) => await AsyncStorage.removeItem(key),\n * });\n * ```\n */\nexport function createStorage(storage: StorageLike): StorageLike {\n return storage;\n}\n","/**\n * Devtools plugin - Redux DevTools integration.\n *\n * Connects to Redux DevTools extension for debugging state changes.\n *\n * @example\n * ```typescript\n * import { createStore, devtools } from '@oxog/state';\n *\n * const store = createStore({ count: 0 })\n * .use(devtools({ name: 'Counter' }));\n * ```\n */\n\n// Global type declarations\ndeclare const window: {\n __REDUX_DEVTOOLS_EXTENSION__?: DevtoolsExtension;\n} | undefined;\n\nimport type { Plugin, Store } from '../types.js';\nimport type { DevtoolsOptions } from './types.js';\n\n/**\n * DevTools connection interface.\n */\ninterface DevtoolsConnection {\n init(state: unknown): void;\n send(action: unknown, state: unknown): void;\n subscribe(callback: (message: any) => void): (() => void) | void;\n}\n\n/**\n * DevTools extension interface.\n */\ninterface DevtoolsExtension {\n connect(options: { name?: string }): DevtoolsConnection;\n}\n\n/**\n * Check if DevTools extension is available.\n */\nfunction hasDevtools(): boolean {\n return typeof window !== 'undefined' && !!window.__REDUX_DEVTOOLS_EXTENSION__;\n}\n\n/**\n * Get DevTools extension.\n */\nfunction getDevtools(): DevtoolsExtension | null {\n /* c8 ignore next 2 */\n if (typeof window === 'undefined') return null;\n return window.__REDUX_DEVTOOLS_EXTENSION__ || null;\n}\n\n/**\n * Create a DevTools plugin.\n *\n * @param options - Plugin options\n * @returns A DevTools plugin\n *\n * @example\n * ```typescript\n * import { devtools } from '@oxog/state';\n *\n * // Basic usage\n * const store = createStore({ count: 0 })\n * .use(devtools({ name: 'My Store' }));\n *\n * // Disabled in production\n * const store = createStore({ count: 0 })\n * .use(devtools({\n * name: 'My Store',\n * enabled: process.env.NODE_ENV === 'development'\n * }));\n * ```\n */\nexport function devtools<TState>(options: DevtoolsOptions = {}): Plugin<TState> {\n const { name = 'OxogState Store', enabled = true, maxAge = 50 } = options;\n let connection: DevtoolsConnection | null = null;\n let unsubscribeStore: (() => void) | null = null;\n let unsubscribeDevtools: (() => void) | null = null;\n // States in DevTools order: index 0 is the state DevTools was initialised\n // with, index n the state after the n-th recorded update.\n let states: TState[] = [];\n\n return {\n name: 'devtools',\n version: '1.0.0',\n install(store: Store<TState>) {\n // Check if DevTools is available\n if (!enabled || !hasDevtools()) {\n return;\n }\n\n const extension = getDevtools();\n /* c8 ignore next */\n if (!extension) return;\n\n // Connect to DevTools\n const conn = extension.connect({ name });\n connection = conn;\n\n // Initialize with current state\n conn.init(store.getState());\n states = [store.getState()];\n\n // True while DevTools drives the state (time travel): those changes\n // are not sent back as new actions.\n let applyingFromDevtools = false;\n const apply = (fn: () => void) => {\n applyingFromDevtools = true;\n try {\n fn();\n } finally {\n applyingFromDevtools = false;\n }\n };\n\n // Subscribe to state changes\n unsubscribeStore = store.subscribe((state, prevState) => {\n if (!connection || applyingFromDevtools) return;\n\n states.push(state);\n if (states.length > maxAge + 1) {\n states.shift();\n }\n\n // Send to DevTools\n connection.send({ type: 'UPDATE', prev: prevState }, state);\n });\n\n // The serialized state DevTools attaches to time-travel messages.\n const parseState = (message: any): Partial<TState> | undefined => {\n if (typeof message.state !== 'string') return undefined;\n try {\n return JSON.parse(message.state) as Partial<TState>;\n } catch {\n return undefined;\n }\n };\n\n // Subscribe to DevTools messages\n const unsubscribe = conn.subscribe((message: any) => {\n if (message?.type !== 'DISPATCH' || !message.payload) return;\n\n switch (message.payload.type) {\n case 'JUMP_TO_STATE':\n case 'JUMP_TO_ACTION': {\n // Time travel\n const target = parseState(message) ?? states[message.payload.index];\n if (target !== undefined) {\n apply(() => store.setState(target as any));\n }\n break;\n }\n case 'COMMIT': {\n // Commit current state\n conn.init(store.getState());\n states = [store.getState()];\n break;\n }\n case 'ROLLBACK': {\n // Back to the last committed state\n const target = parseState(message) ?? states[0];\n if (target !== undefined) {\n apply(() => store.setState(target as any));\n }\n conn.init(store.getState());\n states = [store.getState()];\n break;\n }\n case 'RESET': {\n // Reset to initial state\n apply(() => store.reset());\n conn.init(store.getState());\n states = [store.getState()];\n break;\n }\n }\n });\n if (typeof unsubscribe === 'function') {\n unsubscribeDevtools = unsubscribe;\n }\n },\n onDestroy() {\n // Cleanup connection\n unsubscribeStore?.();\n unsubscribeStore = null;\n unsubscribeDevtools?.();\n unsubscribeDevtools = null;\n connection = null;\n states = [];\n },\n };\n}\n","/**\n * History plugin - Undo/redo functionality.\n *\n * Tracks state changes and provides undo/redo methods.\n *\n * @example\n * ```typescript\n * import { createStore, history } from '@oxog/state';\n *\n * const store = createStore({ count: 0 })\n * .use(history({ limit: 100 }));\n *\n * // Now store has undo() and redo() methods\n * store.setState({ count: 1 });\n * store.setState({ count: 2 });\n * store.undo(); // { count: 1 }\n * store.redo(); // { count: 2 }\n * ```\n */\n\nimport type { Plugin, Store } from '../types.js';\nimport type { HistoryOptions, HistoryStore } from './types.js';\n\n/**\n * History state for tracking past and future states.\n */\ninterface HistoryState<TState> {\n past: TState[];\n present: TState;\n future: TState[];\n}\n\n/**\n * Create a history plugin.\n *\n * @param options - Plugin options\n * @returns A history plugin\n *\n * @example\n * ```typescript\n * import { history } from '@oxog/state';\n *\n * // Default options\n * const store = createStore({ count: 0 })\n * .use(history());\n *\n * // Custom limit\n * const store = createStore({ count: 0 })\n * .use(history({ limit: 50 }));\n *\n * // Track specific keys only\n * const store = createStore({ count: 0, temp: '' })\n * .use(history({ keys: ['count'] }));\n * ```\n */\nexport function history<TState>(options: HistoryOptions<TState> = {}): Plugin<TState> {\n const { limit = 50, keys } = options;\n let historyState: HistoryState<TState> | null = null;\n let isInternalUpdate = false; // Flag to skip recording during undo/redo\n // State produced by the last undo/redo; its (possibly batched) notification is not recorded\n let internalState: unknown = null;\n\n return {\n name: 'history',\n version: '1.0.0',\n install(store: Store<TState>) {\n\n // Initialize history\n historyState = {\n past: [],\n present: store.getState(),\n future: [],\n };\n\n // Subscribe to state changes\n store.subscribe((state) => {\n if (!historyState || isInternalUpdate) return;\n if (internalState !== null && state === internalState) {\n internalState = null;\n return;\n }\n internalState = null;\n\n const previousPresent = historyState.present;\n const newPresent = state;\n\n // Check if state actually changed (respect keys if provided)\n let hasChanged = true;\n if (keys && keys.length > 0) {\n hasChanged = keys.some((key) => {\n return (previousPresent as any)[key] !== (newPresent as any)[key];\n });\n } else {\n hasChanged = previousPresent !== newPresent;\n }\n\n if (!hasChanged) return;\n\n // Add to history\n historyState.past.push(previousPresent);\n if (historyState.past.length > limit) {\n historyState.past.shift();\n }\n historyState.present = newPresent;\n historyState.future = [];\n });\n\n // Add undo method\n (store as any).undo = () => {\n if (!historyState || historyState.past.length === 0) return;\n\n const previous = historyState.past.pop()!;\n historyState.future.push(historyState.present);\n historyState.present = previous;\n\n // Update store state without triggering history recording\n isInternalUpdate = true;\n try {\n store.setState(previous as any);\n internalState = store.getState();\n } finally {\n isInternalUpdate = false;\n }\n };\n\n // Add redo method\n (store as any).redo = () => {\n if (!historyState || historyState.future.length === 0) return;\n\n const next = historyState.future.pop()!;\n historyState.past.push(historyState.present);\n historyState.present = next;\n\n // Update store state without triggering history recording\n isInternalUpdate = true;\n try {\n store.setState(next as any);\n internalState = store.getState();\n } finally {\n isInternalUpdate = false;\n }\n };\n\n // Add clear history method\n (store as any).clearHistory = () => {\n /* c8 ignore next */\n if (!historyState) return;\n historyState.past = [];\n historyState.future = [];\n };\n\n // Add canUndo method\n (store as any).canUndo = () => {\n return historyState !== null && historyState.past.length > 0;\n };\n\n // Add canRedo method\n (store as any).canRedo = () => {\n return historyState !== null && historyState.future.length > 0;\n };\n },\n onDestroy() {\n historyState = null;\n },\n };\n}\n\n/**\n * Check if a store has history capabilities.\n *\n * @param store - The store to check\n * @returns true if store supports undo/redo\n *\n * @example\n * ```typescript\n * import { hasHistory } from '@oxog/state';\n *\n * if (hasHistory(store)) {\n * store.undo();\n * store.redo();\n * }\n * ```\n */\nexport function hasHistory<TState>(store: Store<TState>): store is HistoryStore<TState> {\n return (\n typeof (store as any).undo === 'function' &&\n typeof (store as any).redo === 'function'\n );\n}\n","/**\n * Sync plugin - Cross-tab state synchronization.\n *\n * Synchronizes state across browser tabs using BroadcastChannel API.\n * A newly opened tab asks the open tabs for their state instead of\n * broadcasting its initial state; every local change is broadcast.\n *\n * @example\n * ```typescript\n * import { createStore, sync } from '@oxog/state';\n *\n * const store = createStore({ count: 0 })\n * .use(sync({ channel: 'my-app-state' }));\n *\n * // State changes will sync across all tabs\n * ```\n */\n\n// Global type declarations\ndeclare const BroadcastChannel: {\n prototype: BroadcastChannel;\n new (name: string): BroadcastChannel;\n} | undefined;\n\ninterface MessageEvent {\n data: any;\n type: string;\n target: EventTarget | null;\n srcElement: EventTarget | null;\n currentTarget: EventTarget | null;\n bubbles: boolean;\n cancelable: boolean;\n}\n\ninterface BroadcastChannel {\n name: string;\n postMessage(message: any): void;\n close(): void;\n onmessage: ((event: MessageEvent) => void) | null;\n onmessageerror: ((event: MessageEvent) => void) | null;\n addEventListener(\n type: 'message' | 'messageerror',\n listener: (event: MessageEvent) => void\n ): void;\n removeEventListener(\n type: 'message' | 'messageerror',\n listener: (event: MessageEvent) => void\n ): void;\n}\n\nimport type { Plugin, Store } from '../types.js';\nimport type { SyncOptions } from './types.js';\n\n/**\n * Create a sync plugin.\n *\n * @param options - Plugin options\n * @returns A sync plugin\n *\n * @example\n * ```typescript\n * import { sync } from '@oxog/state';\n *\n * // Default channel name\n * const store = createStore({ count: 0 })\n * .use(sync());\n *\n * // Custom channel name\n * const store = createStore({ count: 0 })\n * .use(sync({ channel: 'my-app' }));\n * ```\n */\nexport function sync<TState>(options: SyncOptions = {}): Plugin<TState> {\n const { channel = 'oxog-state' } = options;\n let broadcastChannel: BroadcastChannel | null = null;\n let currentStore: Store<TState> | null = null;\n let unsubscribe: (() => void) | null = null;\n // True while a state received from another tab is applied, so it is not\n // broadcast back (no echo loop).\n let applyingRemote = false;\n // True from the start-up request until this tab has a state shared with\n // the others: the first reply, any state message or a local change.\n let awaitingInitialState = false;\n\n const post = (message: unknown, errorMessage: string) => {\n if (!broadcastChannel) return;\n try {\n broadcastChannel.postMessage(message);\n } catch (error) {\n console.error(errorMessage, error);\n }\n };\n\n const applyRemote = (target: Store<TState>, state: unknown) => {\n applyingRemote = true;\n try {\n target.setState(state as any);\n } catch (error) {\n console.error('Error applying sync state:', error);\n } finally {\n applyingRemote = false;\n }\n };\n\n return {\n name: 'sync',\n version: '1.0.0',\n install(store: Store<TState>) {\n currentStore = store;\n\n // Check if BroadcastChannel is available\n if (typeof BroadcastChannel === 'undefined') {\n console.warn('BroadcastChannel is not supported in this environment');\n return;\n }\n\n // Create broadcast channel\n broadcastChannel = new BroadcastChannel(channel);\n\n // Listen for messages from other tabs\n broadcastChannel.onmessage = (event: MessageEvent) => {\n const target = currentStore;\n if (!target) return;\n const data = event.data;\n const control = controlMessage(data);\n if (control === 'request') {\n // A newly opened tab asks for the current state\n post({ [SYNC_MESSAGE]: 'reply', state: toMessage(target.getState()) }, 'Error broadcasting state:');\n return;\n }\n if (control === 'reply') {\n // Only a tab that is still starting up takes a reply; once it has\n // changed or received a state the reply would be stale.\n if (awaitingInitialState) {\n awaitingInitialState = false;\n applyRemote(target, (data as { state: unknown }).state);\n }\n return;\n }\n // A state change from another tab (or triggerSync)\n awaitingInitialState = false;\n applyRemote(target, data);\n };\n\n // Broadcast local changes to the other tabs\n unsubscribe = store.subscribe((state) => {\n if (!applyingRemote) {\n awaitingInitialState = false;\n post(toMessage(state), 'Error broadcasting state:');\n }\n });\n },\n\n onInit() {\n // A new tab does not broadcast its initial state (that would overwrite\n // the other tabs); it asks the open tabs for theirs instead.\n if (currentStore && broadcastChannel) {\n awaitingInitialState = true;\n post({ [SYNC_MESSAGE]: 'request' }, 'Error requesting state:');\n }\n },\n\n onDestroy() {\n if (unsubscribe) {\n unsubscribe();\n unsubscribe = null;\n }\n // Close the broadcast channel\n if (broadcastChannel) {\n broadcastChannel.onmessage = null;\n broadcastChannel.close();\n broadcastChannel = null;\n }\n currentStore = null;\n },\n };\n}\n\n/** Key that marks the plugin's own control messages (state request/reply). */\nconst SYNC_MESSAGE = '__oxogStateSync';\n\nfunction controlMessage(data: unknown): 'request' | 'reply' | null {\n if (data === null || typeof data !== 'object') return null;\n const kind = (data as Record<string, unknown>)[SYNC_MESSAGE];\n return kind === 'request' || kind === 'reply' ? kind : null;\n}\n\n/**\n * The data part of a state: functions (bound actions) cannot be cloned by\n * `postMessage` and are left out.\n */\nfunction toMessage<TState>(state: TState): unknown {\n if (state === null || typeof state !== 'object') return state;\n const data: Record<string, unknown> = {};\n for (const key of Object.keys(state as object)) {\n const value = (state as Record<string, unknown>)[key];\n if (typeof value !== 'function') {\n data[key] = value;\n }\n }\n return data;\n}\n\n/**\n * Manually trigger a sync broadcast.\n *\n * @param store - The store to sync\n * @param channel - The channel to broadcast on\n *\n * @example\n * ```typescript\n * import { createStore, sync, triggerSync } from '@oxog/state';\n *\n * const store = createStore({ count: 0 })\n * .use(sync({ channel: 'my-app' }));\n *\n * // Manually trigger sync\n * triggerSync(store, 'my-app');\n * ```\n */\nexport function triggerSync<TState>(store: Store<TState>, channel = 'oxog-state'): void {\n if (typeof BroadcastChannel === 'undefined') {\n console.warn('BroadcastChannel is not supported in this environment');\n return;\n }\n\n const broadcastChannel = new BroadcastChannel(channel);\n broadcastChannel.postMessage(toMessage(store.getState()));\n broadcastChannel.close();\n}\n","/**\n * Immer plugin - Immutable updates with mutable syntax.\n *\n * Uses Proxy to enable writing immutable state updates with mutable syntax.\n *\n * @example\n * ```typescript\n * import { createStore, immer } from '@oxog/state';\n *\n * const store = createStore({\n * users: [{ name: 'John', age: 30 }]\n * }).use(immer());\n *\n * // Now you can write mutable-style updates\n * store.setState((draft) => {\n * draft.users[0].age = 31; // Mutate draft directly\n * });\n * ```\n */\n\nimport type { Plugin, Store } from '../types.js';\n\n/** Marker used to read the internal state of a draft proxy. */\nconst DRAFT_STATE = Symbol('oxog-state.draft');\n\n/**\n * Bookkeeping for one draft (one object or array of the base state).\n */\ninterface DraftState {\n /** The original, never mutated value. */\n base: any;\n /** Shallow copy, created on the first write (copy-on-write). */\n copy: any;\n /** Parent draft; a write here also copies every ancestor. */\n parent: DraftState | null;\n /** Lazily created drafts for nested base values. */\n children: Map<PropertyKey, DraftState>;\n /** The proxy handed to the recipe. */\n proxy: any;\n /** Memoized finalized value. */\n finalized: boolean;\n result: any;\n}\n\n/** Plain objects and arrays are drafted; everything else is used as-is. */\nfunction isDraftable(value: unknown): value is object {\n if (value === null || typeof value !== 'object') return false;\n if (Array.isArray(value)) return true;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\nfunction getDraftState(value: unknown): DraftState | undefined {\n if (value === null || typeof value !== 'object') return undefined;\n return (value as any)[DRAFT_STATE] as DraftState | undefined;\n}\n\nfunction latest(state: DraftState): any {\n return state.copy ?? state.base;\n}\n\nfunction hasOwn(target: object, key: PropertyKey): boolean {\n return Object.prototype.hasOwnProperty.call(target, key);\n}\n\nfunction shallowCopy(base: any): any {\n if (Array.isArray(base)) return base.slice();\n // Spread defines own data properties, so an own \"__proto__\" key stays data.\n return Object.getPrototypeOf(base) === null ? Object.assign(Object.create(null), base) : { ...base };\n}\n\nfunction markChanged(state: DraftState): void {\n if (state.copy === null) {\n state.copy = shallowCopy(state.base);\n if (state.parent) markChanged(state.parent);\n }\n}\n\nfunction createDraft(base: any, parent: DraftState | null): DraftState {\n const state: DraftState = {\n base,\n copy: null,\n parent,\n children: new Map(),\n proxy: null,\n finalized: false,\n result: undefined,\n };\n\n // A blank target keeps proxy invariants independent of the (possibly\n // frozen) base; every trap reads from the latest copy.\n const target = Array.isArray(base) ? [] : {};\n state.proxy = new Proxy(target, {\n get(_target, prop) {\n if (prop === DRAFT_STATE) return state;\n const source = latest(state);\n const value = Reflect.get(source, prop, state.proxy);\n if (!hasOwn(source, prop) || !isDraftable(value)) return value;\n // Only values still shared with the base are drafted; values assigned\n // during the recipe are new and returned as they are.\n if (value !== state.base[prop]) return value;\n let child = state.children.get(prop);\n if (!child) {\n child = createDraft(value, state);\n state.children.set(prop, child);\n }\n return child.proxy;\n },\n set(_target, prop, value) {\n if (prop === '__proto__') return true;\n const source = latest(state);\n if (hasOwn(source, prop) && Object.is(source[prop], value)) return true;\n markChanged(state);\n state.copy[prop] = value;\n state.children.delete(prop);\n return true;\n },\n deleteProperty(_target, prop) {\n if (!hasOwn(latest(state), prop)) return true;\n markChanged(state);\n delete state.copy[prop];\n state.children.delete(prop);\n return true;\n },\n has(_target, prop) {\n return prop in latest(state);\n },\n ownKeys() {\n return Reflect.ownKeys(latest(state));\n },\n getOwnPropertyDescriptor(_target, prop) {\n const source = latest(state);\n const descriptor = Reflect.getOwnPropertyDescriptor(source, prop);\n if (!descriptor) return undefined;\n if (Array.isArray(source) && prop === 'length') return descriptor;\n return { ...descriptor, configurable: true };\n },\n defineProperty(_target, prop, descriptor) {\n markChanged(state);\n Object.defineProperty(state.copy, prop, { ...descriptor, configurable: true });\n return true;\n },\n getPrototypeOf() {\n return Object.getPrototypeOf(state.base);\n },\n setPrototypeOf() {\n return false;\n },\n });\n\n return state;\n}\n\n/** Replace drafts inside a value created during the recipe. */\nfunction finalizeValue(value: any, seen: Set<object>): any {\n const draft = getDraftState(value);\n if (draft) return finalizeDraft(draft, seen);\n if (!isDraftable(value) || seen.has(value)) return value;\n seen.add(value);\n for (const key of Object.keys(value)) {\n const item = (value as any)[key];\n const finalized = finalizeValue(item, seen);\n if (finalized !== item) (value as any)[key] = finalized;\n }\n return value;\n}\n\n/** Turn a draft into its final value (the base itself if untouched). */\nfunction finalizeDraft(state: DraftState, seen: Set<object>): any {\n if (state.finalized) return state.result;\n state.finalized = true;\n if (state.copy === null) {\n state.result = state.base;\n return state.result;\n }\n const copy = state.copy;\n state.result = copy;\n for (const key of Object.keys(copy)) {\n const value = copy[key];\n const child = state.children.get(key);\n if (child && value === child.base) {\n copy[key] = finalizeDraft(child, seen);\n } else if (value !== state.base[key]) {\n copy[key] = finalizeValue(value, seen);\n }\n }\n return copy;\n}\n\n/**\n * Produce a new state by applying mutations to a draft.\n *\n * Copy-on-write: only the objects and arrays on the path of a change are\n * copied, untouched branches keep their identity, and `base` is never\n * mutated. If the recipe returns an object, that object is the result.\n *\n * @param base - The base state\n * @param recipe - The mutation function\n * @returns The new state\n *\n * @example\n * ```typescript\n * import { produce } from '@oxog/state';\n *\n * const state = { users: [{ name: 'John', age: 30 }] };\n * const newState = produce(state, (draft) => {\n * draft.users[0].age = 31;\n * });\n * // state is unchanged; newState.users[0].age === 31\n * ```\n */\nexport function produce<T>(base: T, recipe: (draft: T) => T | Partial<T> | void): T {\n if (!isDraftable(base)) {\n const result = recipe(base);\n return (result === undefined ? base : result) as T;\n }\n\n const root = createDraft(base, null);\n const result = recipe(root.proxy as T);\n if (result !== null && typeof result === 'object' && result !== root.proxy) {\n return finalizeValue(result, new Set()) as T;\n }\n return finalizeDraft(root, new Set()) as T;\n}\n\n/**\n * Create an immer plugin.\n *\n * With the plugin installed, `setState` accepts a recipe that mutates a\n * draft. Regular updaters that return a partial state keep working.\n *\n * @returns An immer plugin\n *\n * @example\n * ```typescript\n * import { createStore, immer } from '@oxog/state';\n *\n * const store = createStore({\n * items: [{ id: 1, name: 'Item 1' }]\n * }).use(immer());\n *\n * // Now setState can accept a mutable recipe function\n * store.setState((draft) => {\n * draft.items[0].name = 'Updated Item';\n * draft.items.push({ id: 2, name: 'Item 2' });\n * });\n * ```\n */\nexport function immer<TState>(): Plugin<TState> {\n return {\n name: 'immer',\n version: '1.0.0',\n install(store: Store<TState>) {\n // Wrap setState to support recipe functions\n const originalSetState = store.setState.bind(store);\n\n store.setState = (update: any) => {\n if (typeof update === 'function') {\n const current = store.getState();\n const next = produce(current, update);\n if (next === current) return;\n originalSetState(next as any);\n } else {\n originalSetState(update);\n }\n };\n },\n };\n}\n","/**\n * Selector plugin - Computed/derived values.\n *\n * Define computed values that automatically update when dependencies change.\n *\n * @example\n * ```typescript\n * import { createStore, selector } from '@oxog/state';\n *\n * const store = createStore({\n * items: [] as { status: string }[],\n * filter: 'all',\n * filteredItems: [] as { status: string }[],\n * itemCount: 0,\n * })\n * .use(selector({\n * selectors: {\n * // Computed: filtered items\n * filteredItems: (state) =>\n * state.filter === 'all' ? state.items : state.items.filter((item) => item.status === state.filter),\n * // Computed: item count\n * itemCount: (state) => state.items.length,\n * },\n * }));\n *\n * // Access computed values\n * const state = store.getState();\n * console.log(state.filteredItems); // Computed value\n * ```\n */\n\nimport type { Plugin, Store } from '../types.js';\nimport type { SelectorOptions } from './types.js';\n\n/**\n * Create a selector plugin for computed values.\n *\n * @param options - Plugin options with selectors\n * @returns A selector plugin\n *\n * @example\n * ```typescript\n * import { selector } from '@oxog/state';\n *\n * const store = createStore({\n * items: [{ price: 10 }, { price: 20 }],\n * taxRate: 0.1,\n * })\n * .use(selector({\n * // Computed total\n * total: (state) =>\n * state.items.reduce((sum: number, item: any) => sum + item.price, 0),\n *\n * // Computed total with tax\n * totalWithTax: (state) => {\n * const total = state.items.reduce((sum: number, item: any) => sum + item.price, 0);\n * return total * (1 + state.taxRate);\n * },\n * }));\n * ```\n */\nexport function selector<TState>(options: SelectorOptions<TState>): Plugin<TState> {\n const { selectors } = options;\n\n return {\n name: 'selector',\n version: '1.0.0',\n install(store: Store<TState>) {\n // Save original getState before overriding\n const originalGetState = store.getState.bind(store);\n\n // One snapshot per state: a new state gets a new snapshot (so\n // useSyncExternalStore and equality checks see the change), the same\n // state returns the same snapshot.\n let lastState: TState | undefined;\n let lastSnapshot: TState | undefined;\n\n const createSnapshot = (state: TState): TState => {\n if (state === null || typeof state !== 'object') return state;\n const cache = new Map<PropertyKey, unknown>();\n return new Proxy(state as unknown as object, {\n get(target, prop, receiver) {\n const selectorFn = Object.prototype.hasOwnProperty.call(selectors, prop)\n ? selectors[prop as keyof TState]\n : undefined;\n if (selectorFn) {\n if (!cache.has(prop)) {\n cache.set(prop, selectorFn(state));\n }\n return cache.get(prop);\n }\n return Reflect.get(target, prop, receiver);\n },\n getOwnPropertyDescriptor(target, prop) {\n const descriptor = Reflect.getOwnPropertyDescriptor(target, prop);\n const selectorFn = Object.prototype.hasOwnProperty.call(selectors, prop)\n ? selectors[prop as keyof TState]\n : undefined;\n if (descriptor && selectorFn && 'value' in descriptor && descriptor.configurable) {\n if (!cache.has(prop)) {\n cache.set(prop, selectorFn(state));\n }\n return { ...descriptor, value: cache.get(prop) };\n }\n return descriptor;\n },\n }) as TState;\n };\n\n // Override getState to return the computed snapshot\n store.getState = () => {\n const state = originalGetState();\n if (state !== lastState || lastSnapshot === undefined) {\n lastState = state;\n lastSnapshot = createSnapshot(state);\n }\n return lastSnapshot;\n };\n },\n };\n}\n","/**\n * Logger plugin for console logging state changes.\n *\n * @module plugins/logger\n */\n\n// Global type declarations\ndeclare const window: {\n document: unknown;\n} | undefined;\n\nimport type { Plugin, Store } from '../types.js';\n\n/**\n * Log level for filtering messages.\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Logger options.\n */\nexport interface LoggerOptions<TState = unknown> {\n /** Log level filter (default: 'debug') */\n level?: LogLevel;\n /** Custom logger (default: console) */\n logger?: Console;\n /** Use collapsed console groups (default: true) */\n collapsed?: boolean;\n /** Show state diff (default: true) */\n diff?: boolean;\n /** Colorize output (default: true in browsers) */\n colors?: boolean;\n /** Show timestamp (default: true) */\n timestamp?: boolean;\n /** Filter function to skip certain changes */\n filter?: (state: TState, prevState: TState) => boolean;\n /** Transform state before logging */\n stateTransformer?: (state: TState) => unknown;\n /** Custom action name (default: 'STATE_CHANGE') */\n actionName?: string | ((state: TState, prevState: TState) => string);\n /** Name for this logger instance */\n name?: string;\n /** Enabled flag (default: true) */\n enabled?: boolean;\n}\n\n/**\n * Log level priority.\n */\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\n/**\n * Console colors for different parts of the log.\n */\nconst COLORS = {\n title: '#9E9E9E',\n prevState: '#9E9E9E',\n action: '#03A9F4',\n nextState: '#4CAF50',\n error: '#F44336',\n diff: {\n added: '#4CAF50',\n removed: '#F44336',\n changed: '#2196F3',\n },\n};\n\n/**\n * Format timestamp.\n */\nfunction formatTime(date: Date): string {\n const hours = date.getHours().toString().padStart(2, '0');\n const minutes = date.getMinutes().toString().padStart(2, '0');\n const seconds = date.getSeconds().toString().padStart(2, '0');\n const ms = date.getMilliseconds().toString().padStart(3, '0');\n return `${hours}:${minutes}:${seconds}.${ms}`;\n}\n\n/**\n * Calculate diff between two states.\n */\nfunction calculateDiff<T>(prevState: T, nextState: T): Record<string, { prev: any; next: any }> {\n const diff: Record<string, { prev: any; next: any }> = {};\n\n if (typeof prevState !== 'object' || typeof nextState !== 'object') {\n if (prevState !== nextState) {\n diff['value'] = { prev: prevState, next: nextState };\n }\n return diff;\n }\n\n if (prevState === null || nextState === null) {\n if (prevState !== nextState) {\n diff['value'] = { prev: prevState, next: nextState };\n }\n return diff;\n }\n\n const allKeys = new Set([\n ...Object.keys(prevState as object),\n ...Object.keys(nextState as object),\n ]);\n\n for (const key of allKeys) {\n const prev = (prevState as any)[key];\n const next = (nextState as any)[key];\n\n if (prev !== next) {\n diff[key] = { prev, next };\n }\n }\n\n return diff;\n}\n\n/**\n * Check if running in browser.\n */\nfunction isBrowser(): boolean {\n return typeof window !== 'undefined' && typeof window.document !== 'undefined';\n}\n\n/**\n * Create a logger plugin.\n *\n * @param options - Logger options\n * @returns A logger plugin\n *\n * @example\n * ```typescript\n * import { createStore, logger } from '@oxog/state';\n *\n * // Basic usage\n * const store = createStore({ count: 0 })\n * .use(logger());\n *\n * // With options\n * const store = createStore({ count: 0 })\n * .use(logger({\n * level: 'info',\n * collapsed: false,\n * diff: true,\n * name: 'CounterStore',\n * }));\n *\n * // Disabled in production\n * const store = createStore({ count: 0 })\n * .use(logger({\n * enabled: process.env.NODE_ENV !== 'production',\n * }));\n * ```\n */\nexport function logger<TState = unknown>(\n options: LoggerOptions<TState> = {}\n): Plugin<TState> {\n const {\n level = 'debug',\n logger: customLogger = console,\n collapsed = true,\n diff = true,\n colors = isBrowser(),\n timestamp = true,\n filter,\n stateTransformer,\n actionName = 'STATE_CHANGE',\n name = 'Store',\n enabled = true,\n } = options;\n\n const minLevel = LOG_LEVELS[level];\n\n return {\n name: 'logger',\n version: '1.0.0',\n\n install(store: Store<TState>) {\n if (!enabled) return;\n\n // Subscribe to state changes\n store.subscribe((state, prevState) => {\n // Check filter\n if (filter && !filter(state, prevState)) {\n return;\n }\n\n // Skip if log level too low\n if (LOG_LEVELS.info < minLevel) {\n return;\n }\n\n const now = new Date();\n const action = typeof actionName === 'function'\n ? actionName(state, prevState)\n : actionName;\n\n // Transform states if needed\n const displayPrevState = stateTransformer ? stateTransformer(prevState) : prevState;\n const displayNextState = stateTransformer ? stateTransformer(state) : state;\n\n // Build title\n const timeStr = timestamp ? ` @ ${formatTime(now)}` : '';\n const title = `${name} ${action}${timeStr}`;\n\n // Log with grouping\n if (colors && isBrowser()) {\n logWithColors(\n customLogger,\n title,\n displayPrevState,\n displayNextState,\n collapsed,\n diff ? calculateDiff(prevState, state) : undefined\n );\n } else {\n logPlain(\n customLogger,\n title,\n displayPrevState,\n displayNextState,\n collapsed,\n diff ? calculateDiff(prevState, state) : undefined\n );\n }\n });\n },\n };\n}\n\n/**\n * Log with colors (browser).\n */\nfunction logWithColors(\n log: Console,\n title: string,\n prevState: unknown,\n nextState: unknown,\n collapsed: boolean,\n diff?: Record<string, { prev: any; next: any }>\n): void {\n const titleStyle = `color: ${COLORS.title}; font-weight: lighter;`;\n const groupMethod = collapsed ? 'groupCollapsed' : 'group';\n\n log[groupMethod](`%c${title}`, titleStyle);\n\n log.log('%cprev state', `color: ${COLORS.prevState}; font-weight: bold;`, prevState);\n log.log('%cnext state', `color: ${COLORS.nextState}; font-weight: bold;`, nextState);\n\n if (diff && Object.keys(diff).length > 0) {\n log.log('%cdiff', `color: ${COLORS.action}; font-weight: bold;`);\n for (const [key, { prev, next }] of Object.entries(diff)) {\n log.log(\n ` %c${key}:`,\n `color: ${COLORS.diff.changed};`,\n prev,\n '→',\n next\n );\n }\n }\n\n log.groupEnd();\n}\n\n/**\n * Log without colors (Node.js or no color support).\n */\nfunction logPlain(\n log: Console,\n title: string,\n prevState: unknown,\n nextState: unknown,\n collapsed: boolean,\n diff?: Record<string, { prev: any; next: any }>\n): void {\n const hasGroupCollapsed = typeof log.groupCollapsed === 'function';\n const groupMethod = collapsed && hasGroupCollapsed ? 'groupCollapsed' : 'group';\n const hasGroup = typeof log[groupMethod] === 'function';\n\n if (hasGroup) {\n log[groupMethod](title);\n } else {\n log.log(`=== ${title} ===`);\n }\n\n log.log('prev state:', prevState);\n log.log('next state:', nextState);\n\n if (diff && Object.keys(diff).length > 0) {\n log.log('diff:');\n for (const [key, { prev, next }] of Object.entries(diff)) {\n log.log(` ${key}:`, prev, '→', next);\n }\n }\n\n if (hasGroup) {\n log.groupEnd();\n } else {\n log.log('===');\n }\n}\n\n/**\n * Create a logger with preset options.\n *\n * @param defaultOptions - Default options\n * @returns A logger factory function\n *\n * @example\n * ```typescript\n * const devLogger = createLogger({\n * enabled: process.env.NODE_ENV === 'development',\n * collapsed: true,\n * });\n *\n * const store = createStore({ count: 0 })\n * .use(devLogger({ name: 'Counter' }));\n * ```\n */\nexport function createLogger<TState = unknown>(\n defaultOptions: LoggerOptions<TState> = {}\n): (options?: LoggerOptions<TState>) => Plugin<TState> {\n return (options = {}) => logger({ ...defaultOptions, ...options });\n}\n","/**\n * Effects plugin for managing side effects.\n *\n * Provides a declarative way to handle async operations,\n * API calls, and other side effects in response to state changes.\n *\n * @module plugins/effects\n */\n\nimport type { Plugin, Store, Selector, EqualityFn } from '../types.js';\nimport { shallowEqual } from '../utils/index.js';\n\n/**\n * Effect cleanup function.\n */\nexport type EffectCleanup = () => void;\n\n/**\n * Effect function that runs when dependencies change.\n */\nexport type EffectFn<T> = (\n value: T,\n prevValue: T,\n utils: EffectUtils\n) => void | EffectCleanup | Promise<void | EffectCleanup>;\n\n/**\n * Utilities available to effects.\n */\nexport interface EffectUtils {\n /** Get current store state */\n getState: () => unknown;\n /**\n * Set store state. Ignored once this run is no longer active (superseded\n * by a newer run, cancelled, or the store was destroyed), so a slow earlier\n * run cannot overwrite the result of a later one.\n */\n setState: (partial: any) => void;\n /** Check if this run is still active (not superseded, cancelled or destroyed) */\n isActive: () => boolean;\n /** Cancel this run */\n cancel: () => void;\n /** Run a callback only if this run is active */\n onlyIfActive: <T>(fn: () => T) => T | undefined;\n /** Aborted when this run is superseded, cancelled or the store is destroyed (pass it to fetch). */\n signal: AbortSignal;\n}\n\n/**\n * Effect definition for the effects plugin.\n */\nexport interface EffectDefinition<TState, TSelected = TState> {\n /** Selector to watch */\n selector: Selector<TState, TSelected>;\n /** Effect function */\n effect: EffectFn<TSelected>;\n /** Custom equality function */\n equalityFn?: EqualityFn<TSelected>;\n /** Fire effect immediately with current value */\n fireImmediately?: boolean;\n /** Debounce effect (ms) */\n debounce?: number;\n /** Effect name for debugging */\n name?: string;\n}\n\n/**\n * Options for the effects plugin.\n */\nexport interface EffectsOptions<TState> {\n /** Array of effect definitions */\n effects: EffectDefinition<TState, any>[];\n /** Error handler for effect errors */\n onError?: (error: Error, effectName?: string) => void;\n}\n\n/**\n * Create a debounced function.\n */\nfunction createDebounced<T extends (...args: any[]) => any>(\n fn: T,\n delay: number\n): T & { cancel: () => void } {\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const debounced = ((...args: Parameters<T>) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n timeoutId = setTimeout(() => {\n fn(...args);\n timeoutId = null;\n }, delay);\n }) as T & { cancel: () => void };\n\n debounced.cancel = () => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n };\n\n return debounced;\n}\n\n/**\n * Create an effects plugin.\n *\n * @param options - Effects configuration\n * @returns An effects plugin\n *\n * @example\n * ```typescript\n * import { createStore, effects } from '@oxog/state';\n *\n * const store = createStore({\n * userId: null,\n * user: null,\n * loading: false,\n * }).use(effects({\n * effects: [\n * {\n * name: 'fetchUser',\n * selector: (s) => s.userId,\n * effect: async (userId, _prev, { setState, isActive }) => {\n * if (!userId) return;\n *\n * setState({ loading: true });\n * try {\n * const user = await fetchUser(userId);\n * if (isActive()) {\n * setState({ user, loading: false });\n * }\n * } catch (error) {\n * if (isActive()) {\n * setState({ user: null, loading: false });\n * }\n * }\n * },\n * },\n * ],\n * }));\n * ```\n */\nexport function effects<TState>(options: EffectsOptions<TState>): Plugin<TState> {\n const { effects: effectDefs, onError } = options;\n let destroyAll: (() => void) | null = null;\n\n return {\n name: 'effects',\n version: '1.0.0',\n\n install(store: Store<TState>) {\n const cleanups: (() => void)[] = [];\n let destroyed = false;\n\n const report = (error: unknown, name?: string) => {\n if (onError) {\n onError(error as Error, name);\n } else {\n console.error(`Effect error${name ? ` in '${name}'` : ''}:`, error);\n }\n };\n\n // Set up each effect\n for (let i = 0; i < effectDefs.length; i++) {\n const def = effectDefs[i];\n if (!def) continue;\n\n const {\n selector,\n effect,\n equalityFn = shallowEqual,\n fireImmediately = false,\n debounce,\n name,\n } = def;\n\n // The run whose result counts; older runs become inactive.\n let currentRun: { active: boolean; controller: AbortController } | null = null;\n let currentCleanup: EffectCleanup | null = null;\n\n const runCleanup = (cleanup: EffectCleanup | null) => {\n if (!cleanup) return;\n try {\n cleanup();\n } catch (error) {\n report(error, name);\n }\n };\n\n const deactivate = (run: { active: boolean; controller: AbortController } | null) => {\n if (run && run.active) {\n run.active = false;\n run.controller.abort();\n }\n };\n\n // Run effect function\n const runEffect = async (value: any, prev: any) => {\n if (destroyed) return;\n\n // Supersede the previous run and clean it up\n deactivate(currentRun);\n const previousCleanup = currentCleanup;\n currentCleanup = null;\n runCleanup(previousCleanup);\n\n const run = { active: true, controller: new AbortController() };\n currentRun = run;\n\n const utils: EffectUtils = {\n getState: () => store.getState(),\n setState: (partial) => {\n if (run.active) store.setState(partial);\n },\n isActive: () => run.active,\n cancel: () => deactivate(run),\n onlyIfActive: <T>(fn: () => T): T | undefined => (run.active ? fn() : undefined),\n signal: run.controller.signal,\n };\n\n const settle = (result: void | EffectCleanup) => {\n if (typeof result !== 'function') return;\n if (run.active) {\n currentCleanup = result;\n } else {\n // The run was superseded while it was pending: clean up now.\n runCleanup(result);\n }\n };\n const fail = (error: unknown) => {\n // An abort caused by superseding/cancelling the run is expected.\n if (!(run.controller.signal.aborted && (error as Error)?.name === 'AbortError')) {\n report(error, name);\n }\n };\n\n try {\n const result = effect(value, prev, utils);\n if (result instanceof Promise) {\n try {\n settle(await result);\n } catch (error) {\n fail(error);\n }\n } else {\n settle(result);\n }\n } catch (error) {\n fail(error);\n }\n };\n\n // Wrap with debounce if needed\n const debounced = debounce && debounce > 0 ? createDebounced(runEffect, debounce) : null;\n const effectFn = debounced ?? runEffect;\n\n // Fire immediately if requested\n if (fireImmediately) {\n const initial = selector(store.getState());\n void effectFn(initial, initial);\n }\n\n // Subscribe to changes\n const unsubscribe = store.subscribe(\n selector,\n (value, prev) => {\n void effectFn(value, prev);\n },\n equalityFn\n );\n\n // Track cleanup\n cleanups.push(() => {\n unsubscribe();\n debounced?.cancel();\n deactivate(currentRun);\n const cleanup = currentCleanup;\n currentCleanup = null;\n runCleanup(cleanup);\n });\n }\n\n destroyAll = () => {\n if (destroyed) return;\n destroyed = true;\n for (const cleanup of cleanups) {\n cleanup();\n }\n };\n\n // Kept for backwards compatibility: stops every effect of this plugin.\n (store as any).__effectsCleanup = destroyAll;\n },\n\n onDestroy() {\n destroyAll?.();\n },\n };\n}\n\n/**\n * Create an effect definition helper.\n *\n * @param name - Effect name\n * @param selector - Selector to watch\n * @param effect - Effect function\n * @param options - Additional options\n * @returns Effect definition\n *\n * @example\n * ```typescript\n * const fetchUserEffect = createEffect(\n * 'fetchUser',\n * (s) => s.userId,\n * async (userId, _prev, { setState }) => {\n * const user = await api.getUser(userId);\n * setState({ user });\n * },\n * { fireImmediately: true }\n * );\n *\n * const store = createStore({ userId: null, user: null })\n * .use(effects({ effects: [fetchUserEffect] }));\n * ```\n */\nexport function createEffect<TState, TSelected>(\n name: string,\n selector: Selector<TState, TSelected>,\n effect: EffectFn<TSelected>,\n options: Omit<EffectDefinition<TState, TSelected>, 'name' | 'selector' | 'effect'> = {}\n): EffectDefinition<TState, TSelected> {\n return {\n name,\n selector,\n effect,\n ...options,\n };\n}\n\n/**\n * Create a simple effect that runs on any state change.\n *\n * @param effect - Effect function\n * @param options - Effect options\n * @returns Effect definition\n *\n * @example\n * ```typescript\n * const logEffect = createSimpleEffect(\n * (state, prevState) => {\n * console.log('State changed:', state);\n * }\n * );\n * ```\n */\nexport function createSimpleEffect<TState>(\n effect: (state: TState, prevState: TState, utils: EffectUtils) => void | EffectCleanup,\n options: Omit<EffectDefinition<TState, TState>, 'selector' | 'effect'> = {}\n): EffectDefinition<TState, TState> {\n return {\n selector: (s) => s,\n effect,\n equalityFn: () => false, // Always run\n ...options,\n };\n}\n\n/**\n * Combine multiple effect definitions.\n *\n * @param effectDefs - Effect definitions to combine\n * @returns Combined effects options\n *\n * @example\n * ```typescript\n * const store = createStore({ ... })\n * .use(effects(combineEffects(\n * fetchUserEffect,\n * saveToStorageEffect,\n * analyticsEffect,\n * )));\n * ```\n */\nexport function combineEffects<TState>(\n ...effectDefs: EffectDefinition<TState, any>[]\n): EffectsOptions<TState> {\n return {\n effects: effectDefs,\n };\n}\n\n/**\n * Create a debounced effect that only fires after a delay.\n *\n * @param delay - Debounce delay in ms\n * @param selector - Selector to watch\n * @param effect - Effect function\n * @returns Effect definition\n *\n * @example\n * ```typescript\n * const searchEffect = createDebouncedEffect(\n * 300,\n * (s) => s.searchQuery,\n * async (query, _prev, { setState }) => {\n * const results = await api.search(query);\n * setState({ searchResults: results });\n * }\n * );\n * ```\n */\nexport function createDebouncedEffect<TState, TSelected>(\n delay: number,\n selector: Selector<TState, TSelected>,\n effect: EffectFn<TSelected>,\n options: Omit<EffectDefinition<TState, TSelected>, 'selector' | 'effect' | 'debounce'> = {}\n): EffectDefinition<TState, TSelected> {\n return {\n selector,\n effect,\n debounce: delay,\n ...options,\n };\n}\n","/**\n * Validation plugin for state schema validation.\n *\n * Provides schema-agnostic validation with support for Zod, Yup,\n * or custom validation functions.\n *\n * @module plugins/validate\n */\n\nimport type { Plugin, Store } from '../types.js';\n\n/**\n * Validation error type.\n */\nexport interface ValidationError {\n /** Path to the invalid field */\n path: string[];\n /** Error message */\n message: string;\n /** Validation rule that failed */\n rule?: string;\n /** The invalid value */\n value?: unknown;\n}\n\n/**\n * Validation result.\n */\nexport interface ValidationResult {\n /** Whether validation passed */\n valid: boolean;\n /** List of validation errors */\n errors: ValidationError[];\n}\n\n/**\n * Custom validator function type.\n */\nexport type ValidatorFn<T> = (state: T) => boolean | ValidationResult | ValidationError[];\n\n/**\n * Zod-like schema interface.\n */\nexport interface ZodLikeSchema<T> {\n safeParse(data: unknown): {\n success: boolean;\n error?: {\n issues: Array<{\n path: (string | number)[];\n message: string;\n code?: string;\n }>;\n };\n data?: T;\n };\n}\n\n/**\n * Yup-like schema interface.\n */\nexport interface YupLikeSchema<T> {\n validateSync(data: unknown, options?: { abortEarly?: boolean }): T;\n validate(data: unknown, options?: { abortEarly?: boolean }): Promise<T>;\n}\n\n/**\n * Schema type - supports Zod, Yup, or custom validators.\n */\nexport type Schema<T> = ZodLikeSchema<T> | YupLikeSchema<T> | ValidatorFn<T>;\n\n/**\n * Validation timing options.\n */\nexport type ValidationTiming = 'change' | 'commit' | 'manual';\n\n/**\n * Blocks inference from the schema, so the state type comes from the store\n * (`store.use(validate(...))`) and `paths` stays typed with a Zod/Yup schema.\n */\ntype NoInferState<T> = [T][T extends any ? 0 : never];\n\n/**\n * Validation plugin options.\n */\nexport interface ValidateOptions<T> {\n /** Schema to validate against (Zod, Yup, or custom function) */\n schema: ZodLikeSchema<unknown> | YupLikeSchema<unknown> | ValidatorFn<NoInferState<T>>;\n /**\n * When to validate: 'change' (after every state change) or 'manual' (only\n * when validate() is called). 'commit' is currently handled like 'manual'.\n */\n on?: ValidationTiming;\n /** Callback when validation fails */\n onError?: (errors: ValidationError[]) => void;\n /**\n * Make validate() throw on failure. Validation on change runs inside a\n * store listener, so there the error is reported through the store's error\n * handling (console.error / plugin onError) and the update is kept.\n */\n throwOnError?: boolean;\n /** Only validate these paths (keys of state) */\n paths?: Array<keyof T>;\n /** Name for debugging */\n name?: string;\n}\n\n/**\n * Validation API added to store.\n */\nexport interface ValidationAPI {\n /** Manually trigger validation */\n validate(): ValidationResult;\n /** Check if current state is valid */\n isValid(): boolean;\n /** Get current validation errors */\n getErrors(): ValidationError[];\n /** Clear validation errors */\n clearErrors(): void;\n}\n\n/**\n * Detect if schema is Zod-like.\n */\nfunction isZodLike<T>(schema: Schema<T>): schema is ZodLikeSchema<T> {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n 'safeParse' in schema &&\n typeof schema.safeParse === 'function'\n );\n}\n\n/**\n * Detect if schema is Yup-like.\n */\nfunction isYupLike<T>(schema: Schema<T>): schema is YupLikeSchema<T> {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n 'validateSync' in schema &&\n typeof schema.validateSync === 'function'\n );\n}\n\n/**\n * Extract partial state for path-based validation.\n */\nfunction extractPaths<T>(state: T, paths: Array<keyof T>): Partial<T> {\n const result: Partial<T> = {};\n for (const path of paths) {\n if (path in (state as object)) {\n result[path] = (state as any)[path];\n }\n }\n return result;\n}\n\n/**\n * Validate state using the provided schema.\n */\nfunction validateState<T>(\n state: T,\n schema: Schema<T>,\n paths?: Array<keyof T>\n): ValidationResult {\n const stateToValidate = paths ? extractPaths(state, paths) : state;\n\n // Custom validator function\n if (typeof schema === 'function') {\n const result = schema(stateToValidate as T);\n\n // Boolean result\n if (typeof result === 'boolean') {\n return {\n valid: result,\n errors: result\n ? []\n : [{ path: [], message: 'Validation failed' }],\n };\n }\n\n // ValidationResult\n if ('valid' in result && 'errors' in result) {\n return result as ValidationResult;\n }\n\n // Array of errors\n if (Array.isArray(result)) {\n return {\n valid: result.length === 0,\n errors: result,\n };\n }\n\n return { valid: true, errors: [] };\n }\n\n // Zod-like schema\n if (isZodLike(schema)) {\n const result = schema.safeParse(stateToValidate);\n\n if (result.success) {\n return { valid: true, errors: [] };\n }\n\n const errors: ValidationError[] = (result.error?.issues || []).map((issue) => ({\n path: issue.path.map(String),\n message: issue.message,\n rule: issue.code,\n }));\n\n return { valid: false, errors };\n }\n\n // Yup-like schema\n if (isYupLike(schema)) {\n try {\n schema.validateSync(stateToValidate, { abortEarly: false });\n return { valid: true, errors: [] };\n } catch (error: any) {\n // Yup throws ValidationError with inner array\n const errors: ValidationError[] = [];\n\n if (error.inner && Array.isArray(error.inner)) {\n for (const err of error.inner) {\n errors.push({\n path: err.path ? err.path.split('.') : [],\n message: err.message,\n rule: err.type,\n value: err.value,\n });\n }\n } else {\n errors.push({\n path: error.path ? error.path.split('.') : [],\n message: error.message || 'Validation failed',\n rule: error.type,\n });\n }\n\n return { valid: false, errors };\n }\n }\n\n // Unknown schema type\n return { valid: true, errors: [] };\n}\n\n/**\n * Create a validation plugin.\n *\n * @param options - Validation options\n * @returns A validation plugin\n *\n * @example\n * ```typescript\n * import { createStore, validate } from '@oxog/state';\n * import { z } from 'zod';\n *\n * // With Zod schema\n * const userSchema = z.object({\n * name: z.string().min(1),\n * age: z.number().min(0),\n * email: z.string().email(),\n * });\n *\n * const store = createStore({ name: '', age: 0, email: '' })\n * .use(validate({\n * schema: userSchema,\n * on: 'change',\n * onError: (errors) => console.log('Validation errors:', errors),\n * }));\n *\n * // Manual validation\n * const result = store.validate();\n * if (!result.valid) {\n * console.log(result.errors);\n * }\n *\n * // Check if valid\n * if (store.isValid()) {\n * submitForm();\n * }\n * ```\n *\n * @example\n * ```typescript\n * // With custom validator function\n * const store = createStore({ password: '', confirmPassword: '' })\n * .use(validate({\n * schema: (state) => {\n * const errors = [];\n * if (state.password.length < 8) {\n * errors.push({\n * path: ['password'],\n * message: 'Password must be at least 8 characters',\n * });\n * }\n * if (state.password !== state.confirmPassword) {\n * errors.push({\n * path: ['confirmPassword'],\n * message: 'Passwords must match',\n * });\n * }\n * return errors;\n * },\n * on: 'change',\n * }));\n * ```\n *\n * @example\n * ```typescript\n * // With partial validation\n * const store = createStore({ name: '', age: 0, temp: '' })\n * .use(validate({\n * schema: userSchema,\n * paths: ['name', 'age'], // Only validate these fields\n * }));\n * ```\n */\nexport function validate<TState>(\n options: ValidateOptions<TState>\n): Plugin<TState> {\n const {\n schema,\n on = 'change',\n onError,\n throwOnError = false,\n paths,\n name = 'validate',\n } = options;\n\n return {\n name,\n version: '1.0.0',\n\n install(store: Store<TState>) {\n let currentErrors: ValidationError[] = [];\n\n // Validation function\n const doValidate = (): ValidationResult => {\n const state = store.getState();\n const result = validateState(state, schema as Schema<TState>, paths);\n\n currentErrors = result.errors;\n\n if (!result.valid) {\n if (onError) {\n onError(result.errors);\n }\n\n if (throwOnError) {\n const errorMessages = result.errors\n .map((e) => `${e.path.join('.')}: ${e.message}`)\n .join(', ');\n throw new Error(`Validation failed: ${errorMessages}`);\n }\n }\n\n return result;\n };\n\n // Subscribe if validation timing is 'change'\n if (on === 'change') {\n store.subscribe(() => {\n doValidate();\n });\n }\n\n // Add validation API to store\n const validationAPI: ValidationAPI = {\n validate: doValidate,\n isValid: () => currentErrors.length === 0,\n getErrors: () => [...currentErrors],\n clearErrors: () => {\n currentErrors = [];\n },\n };\n\n // Extend store with validation API\n Object.assign(store, validationAPI);\n },\n };\n}\n\n/**\n * Create a simple boolean validator.\n *\n * @param predicate - Validation predicate function\n * @param message - Error message when validation fails\n * @returns A validator function\n *\n * @example\n * ```typescript\n * const isPositive = createValidator(\n * (state) => state.count >= 0,\n * 'Count must be positive'\n * );\n *\n * const store = createStore({ count: 0 })\n * .use(validate({ schema: isPositive }));\n * ```\n */\nexport function createValidator<T>(\n predicate: (state: T) => boolean,\n message: string\n): (state: T) => ValidationResult {\n return (state: T): ValidationResult => {\n const valid = predicate(state);\n return {\n valid,\n errors: valid ? [] : [{ path: [], message }],\n };\n };\n}\n\n/**\n * Combine multiple validators into one.\n *\n * @param validators - Array of validator functions\n * @returns Combined validator function\n *\n * @example\n * ```typescript\n * const combinedValidator = combineValidators(\n * createValidator((s) => s.name.length > 0, 'Name required'),\n * createValidator((s) => s.age >= 18, 'Must be 18+'),\n * );\n *\n * const store = createStore({ name: '', age: 0 })\n * .use(validate({ schema: combinedValidator }));\n * ```\n */\nexport function combineValidators<T>(\n ...validators: ValidatorFn<T>[]\n): (state: T) => ValidationResult {\n return (state: T): ValidationResult => {\n const allErrors: ValidationError[] = [];\n\n for (const validator of validators) {\n const result = validator(state);\n\n if (typeof result === 'boolean') {\n if (!result) {\n allErrors.push({ path: [], message: 'Validation failed' });\n }\n } else if ('valid' in result && 'errors' in result) {\n allErrors.push(...(result as ValidationResult).errors);\n } else if (Array.isArray(result)) {\n allErrors.push(...result);\n }\n }\n\n return {\n valid: allErrors.length === 0,\n errors: allErrors,\n };\n };\n}\n\n/**\n * Create a field-level validator.\n *\n * @param field - Field name to validate\n * @param predicate - Validation predicate for field value\n * @param message - Error message when validation fails\n * @returns A validator function\n *\n * @example\n * ```typescript\n * const emailValidator = createFieldValidator(\n * 'email',\n * (email) => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email),\n * 'Invalid email format'\n * );\n *\n * const store = createStore({ email: '' })\n * .use(validate({ schema: emailValidator }));\n * ```\n */\nexport function createFieldValidator<T, K extends keyof T>(\n field: K,\n predicate: (value: T[K], state: T) => boolean,\n message: string\n): (state: T) => ValidationResult {\n return (state: T): ValidationResult => {\n const valid = predicate(state[field], state);\n return {\n valid,\n errors: valid ? [] : [{ path: [String(field)], message, value: state[field] }],\n };\n };\n}\n\n/**\n * Create an async validator (for server-side validation).\n *\n * @param validator - Async validation function\n * @returns A promise that resolves to validation result\n *\n * @example\n * ```typescript\n * const checkUsername = createAsyncValidator(async (state) => {\n * const exists = await api.checkUsername(state.username);\n * return exists\n * ? [{ path: ['username'], message: 'Username already taken' }]\n * : [];\n * });\n *\n * // Manual validation\n * const result = await checkUsername(store.getState());\n * ```\n */\nexport function createAsyncValidator<T>(\n validator: (state: T) => Promise<ValidationError[]>\n): (state: T) => Promise<ValidationResult> {\n return async (state: T): Promise<ValidationResult> => {\n const errors = await validator(state);\n return {\n valid: errors.length === 0,\n errors,\n };\n };\n}\n","/**\n * Testing utilities for @oxog/state.\n *\n * Provides helpers for testing stores, state changes,\n * and async effects in unit tests.\n *\n * @module testing\n */\n\nimport type { Store, Selector } from './types.js';\nimport { createStore } from './store.js';\nimport { shallowEqual } from './utils/index.js';\n\n/**\n * Mock storage for testing persist plugin.\n */\nexport interface MockStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n clear(): void;\n getAll(): Record<string, string>;\n}\n\n/**\n * Create a mock storage for testing.\n *\n * @returns A mock storage implementation\n *\n * @example\n * ```typescript\n * import { createMockStorage, persist } from '@oxog/state';\n *\n * const mockStorage = createMockStorage();\n *\n * const store = createStore({ count: 0 })\n * .use(persist({ key: 'test', storage: mockStorage }));\n *\n * store.setState({ count: 5 });\n * expect(mockStorage.getItem('test')).toBe('{\"count\":5}');\n * ```\n */\nexport function createMockStorage(): MockStorage {\n const storage = new Map<string, string>();\n\n return {\n getItem(key: string): string | null {\n return storage.get(key) ?? null;\n },\n setItem(key: string, value: string): void {\n storage.set(key, value);\n },\n removeItem(key: string): void {\n storage.delete(key);\n },\n clear(): void {\n storage.clear();\n },\n getAll(): Record<string, string> {\n const result: Record<string, string> = {};\n for (const [key, value] of storage) {\n result[key] = value;\n }\n return result;\n },\n };\n}\n\n/**\n * State change record for tracking.\n */\nexport interface StateChange<TState> {\n state: TState;\n prevState: TState;\n timestamp: number;\n}\n\n/**\n * Store spy for testing state changes.\n */\nexport interface StoreSpy<TState> {\n /** All recorded state changes */\n changes: StateChange<TState>[];\n /** Get the last state change */\n lastChange: () => StateChange<TState> | undefined;\n /** Get the last state */\n lastState: () => TState | undefined;\n /** Reset recorded changes */\n reset: () => void;\n /** Unsubscribe from store */\n unsubscribe: () => void;\n /** Wait for a specific state condition */\n waitFor: (\n predicate: (state: TState) => boolean,\n timeout?: number\n ) => Promise<TState>;\n /** Wait for a specific number of changes */\n waitForChanges: (count: number, timeout?: number) => Promise<StateChange<TState>[]>;\n}\n\n/**\n * Create a spy to track store state changes.\n *\n * @param store - The store to spy on\n * @returns A store spy object\n *\n * @example\n * ```typescript\n * import { createStore, spyOnStore } from '@oxog/state';\n *\n * const store = createStore({ count: 0 });\n * const spy = spyOnStore(store);\n *\n * store.setState({ count: 1 });\n * store.setState({ count: 2 });\n *\n * expect(spy.changes).toHaveLength(2);\n * expect(spy.lastState()?.count).toBe(2);\n * ```\n */\nexport function spyOnStore<TState>(store: Store<TState>): StoreSpy<TState> {\n const changes: StateChange<TState>[] = [];\n const waiters: Array<{\n resolve: (state: TState) => void;\n predicate: (state: TState) => boolean;\n }> = [];\n\n const unsubscribe = store.subscribe((state, prevState) => {\n changes.push({\n state,\n prevState,\n timestamp: Date.now(),\n });\n\n // Check waiters\n for (let i = waiters.length - 1; i >= 0; i--) {\n const waiter = waiters[i];\n if (waiter && waiter.predicate(state)) {\n waiter.resolve(state);\n waiters.splice(i, 1);\n }\n }\n });\n\n return {\n changes,\n lastChange: () => changes[changes.length - 1],\n lastState: () => changes[changes.length - 1]?.state,\n reset: () => {\n changes.length = 0;\n },\n unsubscribe,\n waitFor: (predicate, timeout = 5000) => {\n return new Promise((resolve, reject) => {\n // Check immediately\n const current = store.getState();\n if (predicate(current)) {\n resolve(current);\n return;\n }\n\n // Set up waiter\n const waiter = { resolve, predicate };\n waiters.push(waiter);\n\n // Set timeout\n const timeoutId = setTimeout(() => {\n const index = waiters.indexOf(waiter);\n if (index >= 0) {\n waiters.splice(index, 1);\n reject(new Error(`waitFor timeout after ${timeout}ms`));\n }\n }, timeout);\n\n // Clear timeout on resolve\n const originalResolve = waiter.resolve;\n waiter.resolve = (state) => {\n clearTimeout(timeoutId);\n originalResolve(state);\n };\n });\n },\n waitForChanges: (count, timeout = 5000) => {\n return new Promise((resolve, reject) => {\n const startCount = changes.length;\n\n const check = () => {\n if (changes.length >= startCount + count) {\n return changes.slice(startCount, startCount + count);\n }\n return null;\n };\n\n // Check immediately\n const immediate = check();\n if (immediate) {\n resolve(immediate);\n return;\n }\n\n // Set up interval check\n const intervalId = setInterval(() => {\n const result = check();\n if (result) {\n clearInterval(intervalId);\n clearTimeout(timeoutId);\n resolve(result);\n }\n }, 10);\n\n // Set timeout\n const timeoutId = setTimeout(() => {\n clearInterval(intervalId);\n reject(new Error(`waitForChanges timeout after ${timeout}ms`));\n }, timeout);\n });\n },\n };\n}\n\n/**\n * Test helper for asserting state values.\n */\nexport interface StateAssertion<TState> {\n /** Assert the current state equals expected */\n toEqual: (expected: Partial<TState>) => void;\n /** Assert a selector value equals expected */\n toHaveSelected: <T>(selector: Selector<TState, T>, expected: T) => void;\n /** Assert state matches a predicate */\n toMatch: (predicate: (state: TState) => boolean) => void;\n}\n\n/**\n * Create assertions for a store's state.\n *\n * @param store - The store to assert on\n * @returns State assertion helpers\n *\n * @example\n * ```typescript\n * import { createStore, assertState } from '@oxog/state';\n *\n * const store = createStore({ count: 0, name: 'test' });\n * const assert = assertState(store);\n *\n * assert.toEqual({ count: 0 });\n * assert.toHaveSelected(s => s.name, 'test');\n * assert.toMatch(s => s.count >= 0);\n * ```\n */\nexport function assertState<TState>(store: Store<TState>): StateAssertion<TState> {\n return {\n toEqual: (expected) => {\n const state = store.getState();\n for (const [key, value] of Object.entries(expected)) {\n if ((state as any)[key] !== value) {\n throw new Error(\n `Expected state.${key} to be ${JSON.stringify(value)}, ` +\n `but got ${JSON.stringify((state as any)[key])}`\n );\n }\n }\n },\n toHaveSelected: <T>(selector: Selector<TState, T>, expected: T) => {\n const actual = selector(store.getState());\n if (!shallowEqual(actual, expected)) {\n throw new Error(\n `Expected selector to return ${JSON.stringify(expected)}, ` +\n `but got ${JSON.stringify(actual)}`\n );\n }\n },\n toMatch: (predicate) => {\n const state = store.getState();\n if (!predicate(state)) {\n throw new Error(\n `State did not match predicate: ${JSON.stringify(state)}`\n );\n }\n },\n };\n}\n\n/**\n * Options for test store creation.\n */\nexport interface TestStoreOptions<TState> {\n /** Initial state */\n initialState: TState;\n /** Whether to enable spy automatically */\n spy?: boolean;\n}\n\n/**\n * Test store wrapper with built-in utilities.\n */\nexport interface TestStore<TState> {\n /** The underlying store */\n store: Store<TState>;\n /** State spy (if enabled) */\n spy?: StoreSpy<TState>;\n /** State assertions */\n assert: StateAssertion<TState>;\n /** Reset store to initial state */\n reset: () => void;\n /** Destroy store and cleanup */\n destroy: () => void;\n}\n\n/**\n * Create a test store with built-in utilities.\n *\n * @param options - Test store options\n * @returns A test store wrapper\n *\n * @example\n * ```typescript\n * import { createTestStore } from '@oxog/state';\n *\n * describe('Counter', () => {\n * let testStore: TestStore<{ count: number }>;\n *\n * beforeEach(() => {\n * testStore = createTestStore({ initialState: { count: 0 }, spy: true });\n * });\n *\n * afterEach(() => {\n * testStore.destroy();\n * });\n *\n * it('should increment count', () => {\n * testStore.store.setState({ count: 1 });\n * testStore.assert.toEqual({ count: 1 });\n * expect(testStore.spy?.changes).toHaveLength(1);\n * });\n * });\n * ```\n */\nexport function createTestStore<TState>(\n options: TestStoreOptions<TState>\n): TestStore<TState> {\n const { initialState, spy: enableSpy = true } = options;\n\n const store = createStore(initialState) as unknown as Store<TState>;\n const spy = enableSpy ? spyOnStore(store) : undefined;\n const assert = assertState(store);\n\n return {\n store,\n spy,\n assert,\n reset: () => {\n store.reset();\n spy?.reset();\n },\n destroy: () => {\n spy?.unsubscribe();\n store.destroy();\n },\n };\n}\n\n/**\n * Wait for a specified amount of time.\n *\n * @param ms - Milliseconds to wait\n * @returns A promise that resolves after the delay\n *\n * @example\n * ```typescript\n * await delay(100);\n * ```\n */\nexport function delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Run a function and wait for all pending microtasks.\n *\n * @param fn - Function to run\n * @returns A promise that resolves after microtasks complete\n *\n * @example\n * ```typescript\n * await flushMicrotasks(() => {\n * store.setState({ count: 1 });\n * });\n * ```\n */\nexport async function flushMicrotasks(fn?: () => void): Promise<void> {\n if (fn) {\n fn();\n }\n await Promise.resolve();\n}\n\n/**\n * Wrap a store action for testing with call tracking.\n */\nexport interface MockedAction<TArgs extends any[], TReturn> {\n /** Call the action */\n (...args: TArgs): TReturn;\n /** Number of times called */\n callCount: number;\n /** Arguments from each call */\n calls: TArgs[];\n /** Reset call tracking */\n reset: () => void;\n}\n\n/**\n * Create a mocked action for testing.\n *\n * @param fn - The original function\n * @returns A mocked action with call tracking\n *\n * @example\n * ```typescript\n * const mockIncrement = mockAction((amount: number) => {\n * store.setState(s => ({ count: s.count + amount }));\n * });\n *\n * mockIncrement(5);\n * mockIncrement(3);\n *\n * expect(mockIncrement.callCount).toBe(2);\n * expect(mockIncrement.calls).toEqual([[5], [3]]);\n * ```\n */\nexport function mockAction<TArgs extends any[], TReturn>(\n fn: (...args: TArgs) => TReturn\n): MockedAction<TArgs, TReturn> {\n const calls: TArgs[] = [];\n\n const mocked = ((...args: TArgs): TReturn => {\n calls.push(args);\n return fn(...args);\n }) as MockedAction<TArgs, TReturn>;\n\n Object.defineProperty(mocked, 'callCount', {\n get: () => calls.length,\n });\n\n mocked.calls = calls;\n mocked.reset = () => {\n calls.length = 0;\n };\n\n return mocked;\n}\n\n/**\n * Create a snapshot of the current store state.\n *\n * @param store - The store to snapshot\n * @returns A deep clone of the current state\n *\n * @example\n * ```typescript\n * const before = snapshot(store);\n * store.setState({ count: 5 });\n * const after = snapshot(store);\n *\n * expect(before.count).toBe(0);\n * expect(after.count).toBe(5);\n * ```\n */\nexport function snapshot<TState>(store: Store<TState>): TState {\n return JSON.parse(JSON.stringify(store.getState()));\n}\n\n/**\n * Compare two state snapshots and return differences.\n *\n * @param before - State before changes\n * @param after - State after changes\n * @returns Object containing changed keys and their values\n *\n * @example\n * ```typescript\n * const before = { count: 0, name: 'test' };\n * const after = { count: 5, name: 'test' };\n *\n * const diff = stateDiff(before, after);\n * // { count: { before: 0, after: 5 } }\n * ```\n */\nexport function stateDiff<TState extends Record<string, any>>(\n before: TState,\n after: TState\n): Record<string, { before: any; after: any }> {\n const diff: Record<string, { before: any; after: any }> = {};\n const allKeys = new Set([...Object.keys(before), ...Object.keys(after)]);\n\n for (const key of allKeys) {\n if (!shallowEqual(before[key], after[key])) {\n diff[key] = { before: before[key], after: after[key] };\n }\n }\n\n return diff;\n}\n","/**\n * Middleware Compatibility Layer\n *\n * Provides a generic middleware pattern for state management,\n * enabling compatibility with various middleware ecosystems.\n *\n * @module compat/middleware\n */\n\nimport type { Plugin, Store } from '../types.js';\nimport { createStore } from '../store.js';\n\n/**\n * Middleware-style SetState function.\n */\nexport type MiddlewareSetState<T> = {\n (partial: Partial<T> | ((state: T) => Partial<T>), replace?: boolean): void;\n};\n\n/**\n * Middleware-style GetState function.\n */\nexport type MiddlewareGetState<T> = () => T;\n\n/**\n * Middleware-style Subscribe function.\n */\nexport type MiddlewareSubscribe<T> = (listener: (state: T, prevState: T) => void) => () => void;\n\n/**\n * Generic StoreApi for middleware compatibility.\n */\nexport interface MiddlewareStoreApi<T> {\n setState: MiddlewareSetState<T>;\n getState: MiddlewareGetState<T>;\n subscribe: MiddlewareSubscribe<T>;\n destroy?: () => void;\n}\n\n/**\n * State creator function for middleware pattern.\n */\nexport type StateCreatorFn<T, _Mps extends unknown[] = [], _Mcs extends unknown[] = []> = (\n set: MiddlewareSetState<T>,\n get: MiddlewareGetState<T>,\n api: MiddlewareStoreApi<T>\n) => T;\n\n/**\n * Generic Middleware type.\n */\nexport type MiddlewareFn<\n T,\n Mps extends unknown[] = [],\n Mcs extends unknown[] = []\n> = (\n creator: StateCreatorFn<T, Mps, Mcs>\n) => StateCreatorFn<T, Mps, Mcs>;\n\n/**\n * Convert an @oxog/state store to middleware-compatible API.\n *\n * @param store - An @oxog/state store\n * @returns A middleware-compatible store API\n *\n * @example\n * ```typescript\n * import { createStore, toMiddlewareApi } from '@oxog/state';\n *\n * const store = createStore({ count: 0 });\n * const api = toMiddlewareApi(store);\n *\n * // Use middleware-style API\n * api.setState({ count: 1 });\n * api.setState((state) => ({ count: state.count + 1 }));\n * console.log(api.getState()); // { count: 2 }\n * ```\n */\nexport function toMiddlewareApi<T>(store: Store<T>): MiddlewareStoreApi<T> {\n return {\n setState: (partial, replace) => {\n if (typeof partial === 'function') {\n const currentState = store.getState();\n const newPartial = partial(currentState);\n if (replace) {\n store.setState(newPartial as any);\n } else {\n store.merge(newPartial as any);\n }\n } else {\n if (replace) {\n store.setState(partial as any);\n } else {\n store.merge(partial as any);\n }\n }\n },\n getState: () => store.getState(),\n subscribe: (listener) => store.subscribe(listener),\n destroy: () => store.destroy(),\n };\n}\n\n/**\n * Wrap a middleware to work as an @oxog/state plugin.\n *\n * @param middleware - A middleware function\n * @param options - Optional middleware options\n * @returns An @oxog/state plugin\n *\n * @example\n * ```typescript\n * import { createStore, middlewareCompat } from '@oxog/state';\n *\n * // Use external middleware with @oxog/state\n * const store = createStore({ count: 0 })\n * .use(middlewareCompat(someMiddleware, { name: 'MyStore' }));\n * ```\n */\nexport function middlewareCompat<T>(\n middleware: MiddlewareFn<T>,\n _options?: Record<string, unknown>\n): Plugin<T> {\n return {\n name: 'middleware-compat',\n version: '1.0.0',\n\n install(store: Store<T>) {\n // Create middleware-compatible API\n const api = toMiddlewareApi(store);\n\n // Create a state creator that returns current state\n const stateCreator: StateCreatorFn<T> = (set, get) => {\n // Return current state - middleware can modify it\n return get();\n };\n\n // Apply the middleware\n const enhancedCreator = middleware(stateCreator);\n\n // Create enhanced API with middleware's modifications\n const enhancedState = enhancedCreator(api.setState, api.getState, api);\n\n // If middleware returned new state/methods, merge them\n if (enhancedState && typeof enhancedState === 'object') {\n const currentState = store.getState();\n const stateOnly: Partial<T> = {};\n\n // Extract only state values (not functions)\n for (const key in enhancedState) {\n const value = enhancedState[key];\n if (typeof value !== 'function') {\n stateOnly[key as keyof T] = value;\n }\n }\n\n // Merge new state if different\n if (Object.keys(stateOnly).length > 0) {\n const hasChanges = Object.keys(stateOnly).some(\n (key) => currentState[key as keyof T] !== stateOnly[key as keyof T]\n );\n if (hasChanges) {\n store.merge(stateOnly as any);\n }\n }\n }\n },\n };\n}\n\n/**\n * Create a store using middleware-style state creator.\n *\n * @param creator - Middleware-style state creator function\n * @returns A store API\n *\n * @example\n * ```typescript\n * import { createWithMiddleware } from '@oxog/state';\n *\n * const store = createWithMiddleware((set, get) => ({\n * count: 0,\n * increment: () => set((state) => ({ count: state.count + 1 })),\n * decrement: () => set((state) => ({ count: state.count - 1 })),\n * reset: () => set({ count: 0 }),\n * getDoubled: () => get().count * 2,\n * }));\n *\n * store.getState().increment();\n * console.log(store.getState().count); // 1\n * ```\n */\nexport function createWithMiddleware<T extends object>(\n creator: StateCreatorFn<T>\n): MiddlewareStoreApi<T> & { use: (plugin: Plugin<T>) => MiddlewareStoreApi<T> } {\n\n // Create temporary state holder\n let currentState: T | null = null;\n let storeRef: Store<T> | null = null;\n\n // Create middleware-style set/get\n const set: MiddlewareSetState<T> = (partial, replace) => {\n if (!storeRef) {\n throw new Error('Store not initialized');\n }\n\n if (typeof partial === 'function') {\n const newPartial = partial(storeRef.getState());\n if (replace) {\n storeRef.setState(newPartial as any);\n } else {\n storeRef.merge(newPartial as any);\n }\n } else {\n if (replace) {\n storeRef.setState(partial as any);\n } else {\n storeRef.merge(partial as any);\n }\n }\n };\n\n const get: MiddlewareGetState<T> = () => {\n if (storeRef) {\n return storeRef.getState();\n }\n if (currentState) {\n return currentState;\n }\n throw new Error('Store not initialized');\n };\n\n // Create placeholder API for initialization\n const placeholderApi: MiddlewareStoreApi<T> = {\n setState: set,\n getState: get,\n subscribe: () => () => {},\n };\n\n // Run creator to get initial state\n currentState = creator(set, get, placeholderApi);\n\n // Create actual store\n storeRef = createStore(currentState) as unknown as Store<T>;\n\n // Create full API\n const api: MiddlewareStoreApi<T> & { use: (plugin: Plugin<T>) => MiddlewareStoreApi<T> } = {\n setState: (partial, replace) => {\n if (typeof partial === 'function') {\n const newPartial = partial(storeRef!.getState());\n if (replace) {\n storeRef!.setState(newPartial as any);\n } else {\n storeRef!.merge(newPartial as any);\n }\n } else {\n if (replace) {\n storeRef!.setState(partial as any);\n } else {\n storeRef!.merge(partial as any);\n }\n }\n },\n getState: () => storeRef!.getState(),\n subscribe: (listener) => storeRef!.subscribe(listener),\n destroy: () => storeRef!.destroy(),\n use: (plugin) => {\n storeRef!.use(plugin);\n return api;\n },\n };\n\n return api;\n}\n\n/**\n * Create a simple middleware.\n *\n * @param name - Middleware name\n * @param enhancer - Function that enhances the state creator\n * @returns A middleware function\n *\n * @example\n * ```typescript\n * const loggerMiddleware = createSimpleMiddleware('logger', (creator) => (set, get, api) => {\n * const loggedSet: typeof set = (partial, replace) => {\n * console.log('Before:', get());\n * set(partial, replace);\n * console.log('After:', get());\n * };\n * return creator(loggedSet, get, api);\n * });\n *\n * const store = createStore({ count: 0 })\n * .use(middlewareCompat(loggerMiddleware));\n * ```\n */\nexport function createSimpleMiddleware<T>(\n name: string,\n enhancer: (\n creator: StateCreatorFn<T>\n ) => StateCreatorFn<T>\n): MiddlewareFn<T> {\n const middleware = enhancer as MiddlewareFn<T>;\n // Add name for debugging\n Object.defineProperty(middleware, 'name', { value: name });\n return middleware;\n}\n\n/**\n * Compose multiple middlewares.\n *\n * @param middlewares - Array of middlewares\n * @returns A single composed middleware\n *\n * @example\n * ```typescript\n * import { compose, middlewareCompat } from '@oxog/state';\n *\n * const composedMiddleware = compose(\n * loggerMiddleware,\n * devtoolsMiddleware,\n * persistMiddleware,\n * );\n *\n * const store = createStore({ count: 0 })\n * .use(middlewareCompat(composedMiddleware));\n * ```\n */\nexport function compose<T>(\n ...middlewares: MiddlewareFn<T>[]\n): MiddlewareFn<T> {\n return (creator) => {\n return middlewares.reduceRight((acc, middleware) => {\n return middleware(acc);\n }, creator);\n };\n}\n\n/**\n * Type helper for extracting state type from a store API.\n */\nexport type ExtractStateType<S> = S extends MiddlewareStoreApi<infer T> ? T : never;\n\n/**\n * Type helper for selector function.\n */\nexport type SelectorFn<T, U> = (state: T) => U;\n\n/**\n * Type helper for equality function.\n */\nexport type EqualityCheck<T> = (a: T, b: T) => boolean;\n\n// Legacy aliases for backward compatibility (deprecated)\n/** @deprecated Use MiddlewareSetState instead */\nexport type ZustandSetState<T> = MiddlewareSetState<T>;\n/** @deprecated Use MiddlewareGetState instead */\nexport type ZustandGetState<T> = MiddlewareGetState<T>;\n/** @deprecated Use MiddlewareSubscribe instead */\nexport type ZustandSubscribe<T> = MiddlewareSubscribe<T>;\n/** @deprecated Use MiddlewareStoreApi instead */\nexport type ZustandStoreApi<T> = MiddlewareStoreApi<T>;\n/** @deprecated Use StateCreatorFn instead */\nexport type ZustandStateCreator<T, Mps extends unknown[] = [], Mcs extends unknown[] = []> = StateCreatorFn<T, Mps, Mcs>;\n/** @deprecated Use MiddlewareFn instead */\nexport type ZustandMiddleware<T, Mps extends unknown[] = [], Mcs extends unknown[] = []> = MiddlewareFn<T, Mps, Mcs>;\n/** @deprecated Use toMiddlewareApi instead */\nexport const toZustandApi = toMiddlewareApi;\n/** @deprecated Use middlewareCompat instead */\nexport const zustandCompat = middlewareCompat;\n/** @deprecated Use createWithMiddleware instead */\nexport const createWithZustand = createWithMiddleware;\n/** @deprecated Use createSimpleMiddleware instead */\nexport const createMiddleware = createSimpleMiddleware;\n/** @deprecated Use compose instead */\nexport const composeMiddleware = compose;\n/** @deprecated Use ExtractStateType instead */\nexport type ExtractState<S> = ExtractStateType<S>;\n/** @deprecated Use SelectorFn instead */\nexport type ZustandSelector<T, U> = SelectorFn<T, U>;\n/** @deprecated Use EqualityCheck instead */\nexport type ZustandEqualityFn<T> = EqualityCheck<T>;\n"]}