@coherent.js/state 1.1.0 → 2.0.0-rc.0
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.
- package/README.md +84 -15
- package/dist/index.js +929 -335
- package/dist/index.js.map +3 -3
- package/dist/reactive-state.js +468 -111
- package/dist/reactive-state.js.map +2 -2
- package/dist/state-manager.js +141 -38
- package/dist/state-manager.js.map +3 -3
- package/dist/state-persistence.js +239 -143
- package/dist/state-persistence.js.map +2 -2
- package/dist/state-validation.js +70 -43
- package/dist/state-validation.js.map +2 -2
- package/package.json +1 -4
- package/types/index.d.ts +143 -36
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/reactive-state.js", "../src/state-manager.js", "../src/state-persistence.js", "../src/state-validation.js", "../src/enhanced-state-patterns.js", "../src/index.js"],
|
|
4
|
-
"sourcesContent": ["/**\n * Reactive State Management System for Coherent.js\n * Provides computed properties, watchers, and reactive updates\n */\n\n// Simple error handling for this module\nexport class StateError extends Error {\n constructor(message, options = {}) {\n super(message);\n this.name = 'StateError';\n this.type = options.type || 'state';\n this.component = options.component;\n this.context = options.context;\n this.timestamp = Date.now();\n }\n}\n\nexport const globalErrorHandler = {\n handle(error, context = {}) {\n console.error('State Error:', error.message, context);\n }\n};\n\n/**\n * Observable wrapper for tracking state changes\n */\nexport class Observable {\n constructor(value, options = {}) {\n this._value = value;\n this._observers = new Set();\n this._computedDependents = new Set();\n this._options = {\n deep: options.deep !== false,\n immediate: options.immediate !== false,\n ...options\n };\n }\n\n get value() {\n // Track dependency for computed properties\n if (Observable._currentComputed) {\n this._computedDependents.add(Observable._currentComputed);\n }\n return this._value;\n }\n\n set value(newValue) {\n if (this._value === newValue && !this._options.deep) {\n return;\n }\n\n const oldValue = this._value;\n this._value = newValue;\n\n // Notify observers\n this._observers.forEach(observer => {\n try {\n observer(newValue, oldValue);\n } catch (_error) {\n globalErrorHandler.handle(_error, {\n type: 'watcher-_error',\n context: { newValue, oldValue }\n });\n }\n });\n\n // Update computed dependents\n this._computedDependents.forEach(computed => {\n computed._invalidate();\n });\n }\n\n watch(callback, options = {}) {\n if (typeof callback !== 'function') {\n throw new StateError('Watch callback must be a function');\n }\n\n const observer = (newValue, oldValue) => {\n callback(newValue, oldValue, () => this.unwatch(observer));\n };\n\n this._observers.add(observer);\n\n // Call immediately if requested\n if (options.immediate !== false) {\n observer(this._value, undefined);\n }\n\n // Return unwatch function\n return () => this.unwatch(observer);\n }\n\n unwatch(observer) {\n this._observers.delete(observer);\n }\n\n unwatchAll() {\n this._observers.clear();\n this._computedDependents.clear();\n }\n}\n\n/**\n * Computed property implementation\n */\nclass Computed extends Observable {\n constructor(getter, options = {}) {\n super(undefined, options);\n this._getter = getter;\n this._cached = false;\n this._dirty = true;\n\n if (typeof getter !== 'function') {\n throw new StateError('Computed getter must be a function');\n }\n }\n\n get value() {\n if (this._dirty || !this._cached) {\n this._compute();\n }\n return this._value;\n }\n\n set value(newValue) {\n throw new StateError('Cannot set value on computed property');\n }\n\n _compute() {\n const prevComputed = Observable._currentComputed;\n Observable._currentComputed = this;\n\n try {\n const newValue = this._getter();\n\n if (newValue !== this._value) {\n const oldValue = this._value;\n this._value = newValue;\n\n // Notify observers\n this._observers.forEach(observer => {\n observer(newValue, oldValue);\n });\n }\n\n this._cached = true;\n this._dirty = false;\n } catch (_error) {\n globalErrorHandler.handle(_error, {\n type: 'computed-_error',\n context: { getter: this._getter.toString() }\n });\n } finally {\n Observable._currentComputed = prevComputed;\n }\n }\n\n _invalidate() {\n this._dirty = true;\n this._computedDependents.forEach(computed => {\n computed._invalidate();\n });\n }\n}\n\n// Static property for tracking current computed\nObservable._currentComputed = null;\n\n/**\n * Reactive state container with advanced features\n */\nexport class ReactiveState {\n constructor(initialState = {}, options = {}) {\n this._state = new Map();\n this._computed = new Map();\n this._watchers = new Map();\n this._middleware = [];\n this._history = [];\n this._options = {\n enableHistory: options.enableHistory !== false,\n maxHistorySize: options.maxHistorySize || 50,\n enableMiddleware: options.enableMiddleware !== false,\n deep: options.deep !== false,\n ...options\n };\n\n // Initialize state\n Object.entries(initialState).forEach(([key, value]) => {\n this.set(key, value);\n });\n }\n\n /**\n * Get reactive state value\n */\n get(key) {\n const observable = this._state.get(key);\n return observable ? observable.value : undefined;\n }\n\n /**\n * Set reactive state value\n */\n set(key, value, options = {}) {\n const config = { ...this._options, ...options };\n\n // Run middleware\n if (config.enableMiddleware) {\n const middlewareResult = this._runMiddleware('set', { key, value, oldValue: this.get(key) });\n if (middlewareResult.cancelled) {\n return false;\n }\n value = middlewareResult.value !== undefined ? middlewareResult.value : value;\n }\n\n // Get or create observable\n let observable = this._state.get(key);\n if (!observable) {\n observable = new Observable(value, config);\n this._state.set(key, observable);\n } else {\n // Record history\n if (config.enableHistory) {\n this._addToHistory('set', key, observable.value, value);\n }\n\n observable.value = value;\n }\n\n return true;\n }\n\n /**\n * Check if state has a key\n */\n has(key) {\n return this._state.has(key);\n }\n\n /**\n * Delete state key\n */\n delete(key) {\n const observable = this._state.get(key);\n if (observable) {\n // Record history\n if (this._options.enableHistory) {\n this._addToHistory('delete', key, observable.value, undefined);\n }\n\n observable.unwatchAll();\n this._state.delete(key);\n return true;\n }\n return false;\n }\n\n /**\n * Clear all state\n */\n clear() {\n // Record history\n if (this._options.enableHistory) {\n this._addToHistory('clear', null, this.toObject(), {});\n }\n\n // Cleanup observables\n for (const observable of this._state.values()) {\n observable.unwatchAll();\n }\n\n this._state.clear();\n this._computed.clear();\n this._watchers.clear();\n }\n\n /**\n * Create computed property\n */\n computed(key, getter, options = {}) {\n if (typeof getter !== 'function') {\n throw new StateError(`Computed property '${key}' getter must be a function`);\n }\n\n const computed = new Computed(getter, { ...this._options, ...options });\n this._computed.set(key, computed);\n\n return computed;\n }\n\n /**\n * Get computed property value\n */\n getComputed(key) {\n const computed = this._computed.get(key);\n return computed ? computed.value : undefined;\n }\n\n /**\n * Watch state changes\n */\n watch(key, callback, options = {}) {\n if (typeof key === 'function') {\n // Watch computed expression\n return this._watchComputed(key, callback, options);\n }\n\n const observable = this._state.get(key);\n if (!observable) {\n throw new StateError(`Cannot watch undefined state key: ${key}`);\n }\n\n const unwatch = observable.watch(callback, options);\n\n // Store watcher for cleanup\n if (!this._watchers.has(key)) {\n this._watchers.set(key, new Set());\n }\n this._watchers.get(key).add(unwatch);\n\n return unwatch;\n }\n\n /**\n * Watch computed expression\n */\n _watchComputed(expression, callback, options = {}) {\n const computed = new Computed(expression, options);\n const unwatch = computed.watch(callback, options);\n\n return unwatch;\n }\n\n /**\n * Batch state updates\n */\n batch(updates) {\n if (typeof updates === 'function') {\n // Batch function updates\n const oldEnableHistory = this._options.enableHistory;\n this._options.enableHistory = false;\n\n try {\n const result = updates(this);\n\n // Record batch in history\n if (oldEnableHistory) {\n this._addToHistory('batch', null, null, this.toObject());\n }\n\n return result;\n } finally {\n this._options.enableHistory = oldEnableHistory;\n }\n } else if (typeof updates === 'object') {\n // Batch object updates\n return this.batch(() => {\n Object.entries(updates).forEach(([key, value]) => {\n this.set(key, value);\n });\n });\n }\n }\n\n /**\n * Subscribe to multiple state changes\n */\n subscribe(keys, callback, options = {}) {\n if (!Array.isArray(keys)) {\n keys = [keys];\n }\n\n const unwatchers = keys.map(key => {\n return this.watch(key, (newValue, oldValue) => {\n callback({\n key,\n newValue,\n oldValue,\n state: this.toObject()\n });\n }, options);\n });\n\n // Return unsubscribe function\n return () => {\n unwatchers.forEach(unwatch => unwatch());\n };\n }\n\n /**\n * Add middleware for state changes\n */\n use(middleware) {\n if (typeof middleware !== 'function') {\n throw new StateError('Middleware must be a function');\n }\n this._middleware.push(middleware);\n }\n\n /**\n * Run middleware chain\n */\n _runMiddleware(action, context) {\n let result = { ...context, cancelled: false };\n\n for (const middleware of this._middleware) {\n try {\n const middlewareResult = middleware(action, result);\n if (middlewareResult) {\n result = { ...result, ...middlewareResult };\n if (result.cancelled) {\n break;\n }\n }\n } catch (_error) {\n globalErrorHandler.handle(_error, {\n type: 'middleware-_error',\n context: { action, middleware: middleware.toString() }\n });\n }\n }\n\n return result;\n }\n\n /**\n * Add action to history\n */\n _addToHistory(action, key, oldValue, newValue) {\n if (!this._options.enableHistory) return;\n\n this._history.unshift({\n action,\n key,\n oldValue,\n newValue,\n timestamp: Date.now()\n });\n\n // Limit history size\n if (this._history.length > this._options.maxHistorySize) {\n this._history = this._history.slice(0, this._options.maxHistorySize);\n }\n }\n\n /**\n * Get state history\n */\n getHistory(limit = 10) {\n return this._history.slice(0, limit);\n }\n\n /**\n * Undo last action\n */\n undo() {\n const lastAction = this._history.shift();\n if (!lastAction) return false;\n\n const { action, key, oldValue } = lastAction;\n\n // Temporarily disable history\n const oldEnableHistory = this._options.enableHistory;\n this._options.enableHistory = false;\n\n try {\n switch (action) {\n case 'set':\n if (oldValue === undefined) {\n this.delete(key);\n } else {\n this.set(key, oldValue);\n }\n break;\n case 'delete':\n this.set(key, oldValue);\n break;\n case 'clear':\n this.clear();\n Object.entries(oldValue || {}).forEach(([k, v]) => {\n this.set(k, v);\n });\n break;\n }\n return true;\n } finally {\n this._options.enableHistory = oldEnableHistory;\n }\n }\n\n /**\n * Convert state to plain object\n */\n toObject() {\n const result = {};\n for (const [key, observable] of this._state.entries()) {\n result[key] = observable.value;\n }\n return result;\n }\n\n /**\n * Convert computed properties to object\n */\n getComputedValues() {\n const result = {};\n for (const [key, computed] of this._computed.entries()) {\n result[key] = computed.value;\n }\n return result;\n }\n\n /**\n * Get state statistics\n */\n getStats() {\n return {\n stateKeys: this._state.size,\n computedKeys: this._computed.size,\n watcherKeys: this._watchers.size,\n historyLength: this._history.length,\n middlewareCount: this._middleware.length\n };\n }\n\n /**\n * Cleanup and destroy\n */\n destroy() {\n // Clear all watchers\n for (const observable of this._state.values()) {\n observable.unwatchAll();\n }\n for (const computed of this._computed.values()) {\n computed.unwatchAll();\n }\n\n // Clear collections\n this._state.clear();\n this._computed.clear();\n this._watchers.clear();\n this._middleware.length = 0;\n this._history.length = 0;\n }\n}\n\n/**\n * Create reactive state store\n */\nexport function createReactiveState(initialState, options = {}) {\n return new ReactiveState(initialState, options);\n}\n\n/**\n * Create observable value\n */\nexport function observable(value, options = {}) {\n return new Observable(value, options);\n}\n\n/**\n * Create computed property\n */\nexport function computed(getter, options = {}) {\n return new Computed(getter, options);\n}\n\n/**\n * Utility functions for common state patterns\n */\nexport const stateUtils = {\n /**\n * Create a toggle state\n */\n toggle(initialValue = false) {\n const obs = observable(initialValue);\n obs.toggle = () => {\n obs.value = !obs.value;\n };\n return obs;\n },\n\n /**\n * Create a counter state\n */\n counter(initialValue = 0) {\n const obs = observable(initialValue);\n obs.increment = (by = 1) => {\n obs.value += by;\n };\n obs.decrement = (by = 1) => {\n obs.value -= by;\n };\n obs.reset = () => {\n obs.value = initialValue;\n };\n return obs;\n },\n\n /**\n * Create an array state with utilities\n */\n array(initialArray = []) {\n const obs = observable([...initialArray]);\n obs.push = (...items) => {\n obs.value = [...obs.value, ...items];\n };\n obs.pop = () => {\n const newArray = [...obs.value];\n const result = newArray.pop();\n obs.value = newArray;\n return result;\n };\n obs.filter = (predicate) => {\n obs.value = obs.value.filter(predicate);\n };\n obs.clear = () => {\n obs.value = [];\n };\n return obs;\n },\n\n /**\n * Create object state with deep reactivity\n */\n object(initialObject = {}) {\n const state = createReactiveState(initialObject, { deep: true });\n return state;\n }\n};\n\nexport default ReactiveState;\n", "/**\n * Simple state management for server-side rendering\n * This is mainly for component state during rendering\n */\n\nconst globalState = new Map();\n\n/**\n * Creates a state container for a request/render cycle\n * @param {Object} initialState - Initial state object\n * @returns {Object} State container\n */\nexport function createState(initialState = {}) {\n const state = new Map(Object.entries(initialState));\n\n return {\n get(key) {\n return state.get(key);\n },\n\n set(key, value) {\n state.set(key, value);\n return this;\n },\n\n has(key) {\n return state.has(key);\n },\n\n delete(key) {\n return state.delete(key);\n },\n\n clear() {\n state.clear();\n return this;\n },\n\n toObject() {\n return Object.fromEntries(state);\n },\n\n // For debugging\n _internal: state\n };\n}\n\n/**\n * Global state for sharing data across components during SSR\n */\nexport const globalStateManager = {\n set(key, value) {\n globalState.set(key, value);\n },\n\n get(key) {\n return globalState.get(key);\n },\n\n has(key) {\n return globalState.has(key);\n },\n\n clear() {\n globalState.clear();\n },\n\n // Create isolated state for each request\n createRequestState() {\n return createState();\n }\n};\n\n/**\n * Context stack for managing nested context providers\n */\nconst contextStacks = new Map();\n\n/**\n * Context provider for passing data down the component tree\n * @param {string} key - Context key\n * @param {*} value - Context value\n * @param {Object} children - Children to render with context\n * @returns {Object} Children with context available\n */\nexport function provideContext(key, value) {\n // Initialize context stack if it doesn't exist\n if (!contextStacks.has(key)) {\n contextStacks.set(key, []);\n }\n \n const stack = contextStacks.get(key);\n \n // Store previous value\n const previousValue = globalState.get(key);\n \n // Push previous value to stack and set new value\n stack.push(previousValue);\n globalState.set(key, value);\n}\n\n/**\n * Create a context provider component that works with the rendering system\n * @param {string} key - Context key\n * @param {*} value - Context value\n * @param {Object} children - Children to render with context\n * @returns {Function} Component function that provides context\n */\nexport function createContextProvider(key, value, children) {\n // Return a function that will render the children within the context\n return (renderFunction) => {\n try {\n // Provide context\n provideContext(key, value);\n \n // If a render function is provided, use it to render children\n // Otherwise return children to be rendered by the caller\n if (renderFunction && typeof renderFunction === 'function') {\n return renderFunction(children);\n } else {\n return children;\n }\n } finally {\n // Always restore context when done\n restoreContext(key);\n }\n };\n}\n\n/**\n * Restore context to previous value\n * @param {string} key - Context key\n */\nexport function restoreContext(key) {\n if (!contextStacks.has(key)) return;\n \n const stack = contextStacks.get(key);\n \n // Restore previous value from stack\n const previousValue = stack.pop();\n \n if (stack.length === 0) {\n // No more providers, delete the key if it was undefined before\n if (previousValue === undefined) {\n globalState.delete(key);\n } else {\n globalState.set(key, previousValue);\n }\n \n // Clean up empty stack\n contextStacks.delete(key);\n } else {\n // Restore previous value\n globalState.set(key, previousValue);\n }\n}\n\n/**\n * Clear all context stacks (useful for cleanup after rendering)\n *\n * useContext() reads from globalState, which is module-level and therefore\n * shared by every render in the process. Clearing only contextStacks left the\n * values themselves in place, so a context provided while rendering one\n * request stayed readable while rendering the next \u2014 and became unrecoverable,\n * since restoreContext() bails out once a key's stack is gone.\n *\n * Unwind each tracked key to the value it held before its first\n * provideContext() \u2014 the bottom of that key's stack. Only keys that were\n * actually provided as contexts are touched, so unrelated global state\n * survives, which is what the previous implementation was trying to protect.\n */\nexport function clearAllContexts() {\n for (const [key, stack] of contextStacks) {\n const beforeFirstProvide = stack[0];\n\n if (beforeFirstProvide === undefined) {\n globalState.delete(key);\n } else {\n globalState.set(key, beforeFirstProvide);\n }\n }\n\n contextStacks.clear();\n}\n\n/**\n * Context consumer to access provided context\n * @param {string} key - Context key\n * @returns {*} Context value\n */\nexport function useContext(key) {\n return globalState.get(key);\n}\n", "/**\n * @fileoverview State Persistence for Coherent.js\n * Provides persistent state management with multiple storage backends\n * @module @coherent.js/core/state/state-persistence\n */\n\n/**\n * @typedef {'localStorage'|'sessionStorage'|'indexedDB'|'memory'} StorageType\n */\n\n/**\n * @typedef {Object} PersistenceOptions\n * @property {StorageType} [storage='localStorage'] - Storage backend to use\n * @property {string} [key='coherent-state'] - Storage key prefix\n * @property {boolean} [debounce=true] - Debounce state saves\n * @property {number} [debounceDelay=300] - Debounce delay in ms\n * @property {Function} [serialize=JSON.stringify] - Serialization function\n * @property {Function} [deserialize=JSON.parse] - Deserialization function\n * @property {Array<string>} [include] - Keys to include (whitelist)\n * @property {Array<string>} [exclude] - Keys to exclude (blacklist)\n * @property {boolean} [encrypt=false] - Encrypt stored data\n * @property {string} [encryptionKey] - Encryption key\n * @property {Function} [onSave] - Callback when state is saved\n * @property {Function} [onLoad] - Callback when state is loaded\n * @property {Function} [onError] - Error callback\n * @property {boolean} [versioning=false] - Enable versioning\n * @property {string} [version='1.0.0'] - Current version\n * @property {Function} [migrate] - Migration function for version changes\n * @property {number} [ttl] - Time to live in milliseconds\n * @property {boolean} [crossTab=false] - Enable cross-tab synchronization\n */\n\n/**\n * Storage adapter interface\n * @interface StorageAdapter\n */\n\n/**\n * LocalStorage adapter\n */\nclass LocalStorageAdapter {\n constructor() {\n this.available = typeof localStorage !== 'undefined';\n }\n\n async get(key) {\n if (!this.available) return null;\n try {\n return localStorage.getItem(key);\n } catch (error) {\n console.error('LocalStorage get error:', error);\n return null;\n }\n }\n\n async set(key, value) {\n if (!this.available) return false;\n try {\n localStorage.setItem(key, value);\n return true;\n } catch (error) {\n console.error('LocalStorage set error:', error);\n return false;\n }\n }\n\n async remove(key) {\n if (!this.available) return false;\n try {\n localStorage.removeItem(key);\n return true;\n } catch (error) {\n console.error('LocalStorage remove error:', error);\n return false;\n }\n }\n\n async clear() {\n if (!this.available) return false;\n try {\n localStorage.clear();\n return true;\n } catch (error) {\n console.error('LocalStorage clear error:', error);\n return false;\n }\n }\n}\n\n/**\n * SessionStorage adapter\n */\nclass SessionStorageAdapter {\n constructor() {\n this.available = typeof sessionStorage !== 'undefined';\n }\n\n async get(key) {\n if (!this.available) return null;\n try {\n return sessionStorage.getItem(key);\n } catch (error) {\n console.error('SessionStorage get error:', error);\n return null;\n }\n }\n\n async set(key, value) {\n if (!this.available) return false;\n try {\n sessionStorage.setItem(key, value);\n return true;\n } catch (error) {\n console.error('SessionStorage set error:', error);\n return false;\n }\n }\n\n async remove(key) {\n if (!this.available) return false;\n try {\n sessionStorage.removeItem(key);\n return true;\n } catch (error) {\n console.error('SessionStorage remove error:', error);\n return false;\n }\n }\n\n async clear() {\n if (!this.available) return false;\n try {\n sessionStorage.clear();\n return true;\n } catch (error) {\n console.error('SessionStorage clear error:', error);\n return false;\n }\n }\n}\n\n/**\n * IndexedDB adapter\n */\nclass IndexedDBAdapter {\n constructor(dbName = 'coherent-db', storeName = 'state') {\n this.dbName = dbName;\n this.storeName = storeName;\n this.available = typeof indexedDB !== 'undefined';\n this.db = null;\n }\n\n async init() {\n if (!this.available) return false;\n if (this.db) return true;\n\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(this.dbName, 1);\n\n request.onerror = () => {\n console.error('IndexedDB open error:', request.error);\n reject(request.error);\n };\n\n request.onsuccess = () => {\n this.db = request.result;\n resolve(true);\n };\n\n request.onupgradeneeded = (event) => {\n const db = event.target.result;\n if (!db.objectStoreNames.contains(this.storeName)) {\n db.createObjectStore(this.storeName);\n }\n };\n });\n }\n\n async get(key) {\n if (!this.available) return null;\n await this.init();\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([this.storeName], 'readonly');\n const store = transaction.objectStore(this.storeName);\n const request = store.get(key);\n\n request.onerror = () => {\n console.error('IndexedDB get error:', request.error);\n reject(request.error);\n };\n\n request.onsuccess = () => {\n resolve(request.result || null);\n };\n });\n }\n\n async set(key, value) {\n if (!this.available) return false;\n await this.init();\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([this.storeName], 'readwrite');\n const store = transaction.objectStore(this.storeName);\n const request = store.put(value, key);\n\n request.onerror = () => {\n console.error('IndexedDB set error:', request.error);\n reject(request.error);\n };\n\n request.onsuccess = () => {\n resolve(true);\n };\n });\n }\n\n async remove(key) {\n if (!this.available) return false;\n await this.init();\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([this.storeName], 'readwrite');\n const store = transaction.objectStore(this.storeName);\n const request = store.delete(key);\n\n request.onerror = () => {\n console.error('IndexedDB remove error:', request.error);\n reject(request.error);\n };\n\n request.onsuccess = () => {\n resolve(true);\n };\n });\n }\n\n async clear() {\n if (!this.available) return false;\n await this.init();\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([this.storeName], 'readwrite');\n const store = transaction.objectStore(this.storeName);\n const request = store.clear();\n\n request.onerror = () => {\n console.error('IndexedDB clear error:', request.error);\n reject(request.error);\n };\n\n request.onsuccess = () => {\n resolve(true);\n };\n });\n }\n}\n\n/**\n * Memory adapter (for testing or fallback)\n */\nclass MemoryAdapter {\n constructor() {\n this.storage = new Map();\n this.available = true;\n }\n\n async get(key) {\n return this.storage.get(key) || null;\n }\n\n async set(key, value) {\n this.storage.set(key, value);\n return true;\n }\n\n async remove(key) {\n return this.storage.delete(key);\n }\n\n async clear() {\n this.storage.clear();\n return true;\n }\n}\n\n/**\n * Simple encryption/decryption (basic XOR cipher)\n * For production, use Web Crypto API or a proper crypto library\n */\nclass SimpleEncryption {\n constructor(key) {\n this.key = key || 'default-key';\n }\n\n encrypt(text) {\n let result = '';\n for (let i = 0; i < text.length; i++) {\n result += String.fromCharCode(\n text.charCodeAt(i) ^ this.key.charCodeAt(i % this.key.length)\n );\n }\n return btoa(result);\n }\n\n decrypt(encrypted) {\n const text = atob(encrypted);\n let result = '';\n for (let i = 0; i < text.length; i++) {\n result += String.fromCharCode(\n text.charCodeAt(i) ^ this.key.charCodeAt(i % this.key.length)\n );\n }\n return result;\n }\n}\n\n/**\n * Create storage adapter\n * @param {StorageType} type - Storage type\n * @returns {StorageAdapter} Storage adapter instance\n */\nfunction createStorageAdapter(type) {\n switch (type) {\n case 'localStorage':\n return new LocalStorageAdapter();\n case 'sessionStorage':\n return new SessionStorageAdapter();\n case 'indexedDB':\n return new IndexedDBAdapter();\n case 'memory':\n return new MemoryAdapter();\n default:\n return new LocalStorageAdapter();\n }\n}\n\n/**\n * Create persistent state manager\n * @param {Object} initialState - Initial state\n * @param {PersistenceOptions} options - Persistence options\n * @returns {Object} Persistent state manager\n */\nexport function createPersistentState(initialState = {}, options = {}) {\n const opts = {\n storage: 'localStorage',\n key: 'coherent-state',\n debounce: true,\n debounceDelay: 300,\n serialize: JSON.stringify,\n deserialize: JSON.parse,\n include: null,\n exclude: null,\n encrypt: false,\n encryptionKey: null,\n onSave: null,\n onLoad: null,\n onError: null,\n versioning: false,\n version: '1.0.0',\n migrate: null,\n ttl: null,\n crossTab: false,\n ...options\n };\n\n const adapter = createStorageAdapter(opts.storage);\n const encryption = opts.encrypt ? new SimpleEncryption(opts.encryptionKey) : null;\n\n let state = { ...initialState };\n let saveTimeout = null;\n const listeners = new Set();\n\n /**\n * Filter state keys based on include/exclude options\n * @param {Object} obj - State object\n * @returns {Object} Filtered state\n */\n function filterKeys(obj) {\n if (!obj || typeof obj !== 'object') return obj;\n\n // If include list is provided, only include those keys\n if (opts.include && Array.isArray(opts.include)) {\n const filtered = {};\n opts.include.forEach(key => {\n if (key in obj) {\n filtered[key] = obj[key];\n }\n });\n return filtered;\n }\n\n // If exclude list is provided, exclude those keys\n if (opts.exclude && Array.isArray(opts.exclude)) {\n const filtered = { ...obj };\n opts.exclude.forEach(key => {\n delete filtered[key];\n });\n return filtered;\n }\n\n return obj;\n }\n\n /**\n * Save state to storage\n * @param {boolean} immediate - Save immediately without debounce\n */\n async function save(immediate = false) {\n if (opts.debounce && !immediate) {\n clearTimeout(saveTimeout);\n saveTimeout = setTimeout(() => save(true), opts.debounceDelay);\n return;\n }\n\n try {\n const filteredState = filterKeys(state);\n const serialized = opts.serialize(filteredState);\n\n // Add metadata\n const data = {\n state: serialized,\n version: opts.version,\n timestamp: Date.now(),\n ttl: opts.ttl\n };\n\n let dataString = JSON.stringify(data);\n\n // Encrypt if enabled\n if (encryption) {\n dataString = encryption.encrypt(dataString);\n }\n\n await adapter.set(opts.key, dataString);\n\n // Call onSave callback\n if (opts.onSave) {\n opts.onSave(filteredState);\n }\n\n // Broadcast to other tabs if cross-tab sync is enabled\n if (opts.crossTab && typeof BroadcastChannel !== 'undefined') {\n const channel = new BroadcastChannel('coherent-state-sync');\n channel.postMessage({ type: 'state-update', state: filteredState });\n channel.close();\n }\n } catch (error) {\n console.error('State save error:', error);\n if (opts.onError) {\n opts.onError(error);\n }\n }\n }\n\n /**\n * Load state from storage\n */\n async function load() {\n try {\n let dataString = await adapter.get(opts.key);\n if (!dataString) return null;\n\n // Decrypt if enabled\n if (encryption) {\n dataString = encryption.decrypt(dataString);\n }\n\n const data = JSON.parse(dataString);\n\n // Check TTL\n if (data.ttl && data.timestamp) {\n const age = Date.now() - data.timestamp;\n if (age > data.ttl) {\n await adapter.remove(opts.key);\n return null;\n }\n }\n\n // Check version and migrate if needed\n if (opts.versioning && data.version !== opts.version) {\n if (opts.migrate) {\n const migrated = opts.migrate(data.state, data.version, opts.version);\n return opts.deserialize(migrated);\n }\n return null;\n }\n\n const loadedState = opts.deserialize(data.state);\n\n // Call onLoad callback\n if (opts.onLoad) {\n opts.onLoad(loadedState);\n }\n\n return loadedState;\n } catch (error) {\n console.error('State load error:', error);\n if (opts.onError) {\n opts.onError(error);\n }\n return null;\n }\n }\n\n /**\n * Subscribe to state changes\n * @param {Function} listener - Change listener\n * @returns {Function} Unsubscribe function\n */\n function subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n\n /**\n * Notify listeners of state changes\n * @param {Object} oldState - Previous state\n * @param {Object} newState - New state\n */\n function notifyListeners(oldState, newState) {\n listeners.forEach(listener => {\n try {\n listener(newState, oldState);\n } catch (error) {\n console.error('Listener error:', error);\n }\n });\n }\n\n /**\n * Get current state\n * @param {string} [key] - State key\n * @returns {*} State value or entire state\n */\n function getState(key) {\n return key ? state[key] : { ...state };\n }\n\n /**\n * Set state\n * @param {Object|Function} updates - State updates or updater function\n * @param {boolean} persist - Persist to storage\n */\n function setState(updates, persist = true) {\n const oldState = { ...state };\n\n if (typeof updates === 'function') {\n updates = updates(oldState);\n }\n\n state = { ...state, ...updates };\n\n notifyListeners(oldState, state);\n\n if (persist) {\n save();\n }\n }\n\n /**\n * Reset state to initial values\n * @param {boolean} persist - Persist to storage\n */\n function resetState(persist = true) {\n const oldState = { ...state };\n state = { ...initialState };\n notifyListeners(oldState, state);\n\n if (persist) {\n save(true);\n }\n }\n\n /**\n * Clear persisted state\n */\n async function clearStorage() {\n await adapter.remove(opts.key);\n }\n\n /**\n * Manually trigger persistence\n */\n async function persist() {\n await save(true);\n }\n\n /**\n * Restore state from storage\n */\n async function restore() {\n const loaded = await load();\n if (loaded) {\n const oldState = { ...state };\n state = { ...state, ...loaded };\n notifyListeners(oldState, state);\n return true;\n }\n return false;\n }\n\n // Setup cross-tab synchronization\n if (opts.crossTab && typeof BroadcastChannel !== 'undefined') {\n const channel = new BroadcastChannel('coherent-state-sync');\n channel.onmessage = (event) => {\n if (event.data.type === 'state-update') {\n const oldState = { ...state };\n state = { ...state, ...event.data.state };\n notifyListeners(oldState, state);\n }\n };\n }\n\n // Auto-restore on creation\n if (opts.storage !== 'memory') {\n restore();\n }\n\n return {\n getState,\n setState,\n resetState,\n subscribe,\n persist,\n restore,\n clearStorage,\n load,\n save: () => save(true),\n get adapter() {\n return adapter;\n }\n };\n}\n\n/**\n * Create persistent state with localStorage\n * @param {Object} initialState - Initial state\n * @param {string} key - Storage key\n * @param {Partial<PersistenceOptions>} options - Additional options\n * @returns {Object} Persistent state manager\n */\nexport function withLocalStorage(initialState = {}, key = 'coherent-state', options = {}) {\n return createPersistentState(initialState, {\n ...options,\n storage: 'localStorage',\n key\n });\n}\n\n/**\n * Create persistent state with sessionStorage\n * @param {Object} initialState - Initial state\n * @param {string} key - Storage key\n * @param {Partial<PersistenceOptions>} options - Additional options\n * @returns {Object} Persistent state manager\n */\nexport function withSessionStorage(initialState = {}, key = 'coherent-state', options = {}) {\n return createPersistentState(initialState, {\n ...options,\n storage: 'sessionStorage',\n key\n });\n}\n\n/**\n * Create persistent state with IndexedDB\n * @param {Object} initialState - Initial state\n * @param {string} key - Storage key\n * @param {Partial<PersistenceOptions>} options - Additional options\n * @returns {Object} Persistent state manager\n */\nexport function withIndexedDB(initialState = {}, key = 'coherent-state', options = {}) {\n return createPersistentState(initialState, {\n ...options,\n storage: 'indexedDB',\n key\n });\n}\n\nexport default {\n createPersistentState,\n withLocalStorage,\n withSessionStorage,\n withIndexedDB,\n createStorageAdapter\n};\n", "/**\n * @fileoverview State Validation for Coherent.js\n * Provides JSON Schema validation and custom validators for state management\n * @module @coherent.js/core/state/state-validation\n */\n\n/**\n * @typedef {Object} ValidationOptions\n * @property {Object} [schema] - JSON Schema for validation\n * @property {Object<string, Function>} [validators] - Custom validator functions\n * @property {boolean} [strict=false] - Strict mode (throw on validation errors)\n * @property {boolean} [coerce=false] - Coerce types to match schema\n * @property {Function} [onError] - Validation error callback\n * @property {boolean} [validateOnSet=true] - Validate on state updates\n * @property {boolean} [validateOnGet=false] - Validate on state reads\n * @property {Array<string>} [required] - Required fields\n * @property {boolean} [allowUnknown=true] - Allow unknown properties\n */\n\n/**\n * @typedef {Object} ValidationResult\n * @property {boolean} valid - Whether validation passed\n * @property {Array<ValidationError>} errors - Array of validation errors\n * @property {*} value - Validated/coerced value\n */\n\n/**\n * @typedef {Object} ValidationError\n * @property {string} path - Property path that failed validation\n * @property {string} message - Error message\n * @property {string} type - Error type\n * @property {*} value - The invalid value\n * @property {*} expected - Expected value/type\n */\n\n/**\n * Simple JSON Schema validator\n */\nclass SchemaValidator {\n constructor(schema, options = {}) {\n this.schema = schema;\n this.options = {\n coerce: false,\n allowUnknown: true,\n ...options\n };\n }\n\n /**\n * Validate value against schema\n * @param {*} value - Value to validate\n * @param {Object} schema - Schema to validate against\n * @param {string} path - Current path in object\n * @returns {ValidationResult} Validation result\n */\n validate(value, schema = this.schema, path = '') {\n const errors = [];\n let coercedValue = value;\n\n // Type validation\n if (schema.type) {\n const typeResult = this.validateType(value, schema.type, path);\n if (!typeResult.valid) {\n errors.push(...typeResult.errors);\n if (!this.options.coerce) {\n return { valid: false, errors, value };\n }\n }\n coercedValue = typeResult.value;\n }\n\n // Enum validation\n if (schema.enum) {\n const enumResult = this.validateEnum(coercedValue, schema.enum, path);\n if (!enumResult.valid) {\n errors.push(...enumResult.errors);\n }\n }\n\n // String validations\n if (schema.type === 'string') {\n const stringResult = this.validateString(coercedValue, schema, path);\n if (!stringResult.valid) {\n errors.push(...stringResult.errors);\n }\n }\n\n // Number validations\n if (schema.type === 'number' || schema.type === 'integer') {\n const numberResult = this.validateNumber(coercedValue, schema, path);\n if (!numberResult.valid) {\n errors.push(...numberResult.errors);\n }\n }\n\n // Array validations\n if (schema.type === 'array') {\n const arrayResult = this.validateArray(coercedValue, schema, path);\n if (!arrayResult.valid) {\n errors.push(...arrayResult.errors);\n }\n coercedValue = arrayResult.value;\n }\n\n // Object validations\n if (schema.type === 'object') {\n const objectResult = this.validateObject(coercedValue, schema, path);\n if (!objectResult.valid) {\n errors.push(...objectResult.errors);\n }\n coercedValue = objectResult.value;\n }\n\n // Custom validation function\n if (schema.validate && typeof schema.validate === 'function') {\n const customResult = schema.validate(coercedValue);\n if (customResult !== true) {\n errors.push({\n path,\n message: typeof customResult === 'string' ? customResult : 'Custom validation failed',\n type: 'custom',\n value: coercedValue\n });\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n value: coercedValue\n };\n }\n\n validateType(value, type, path) {\n const actualType = Array.isArray(value) ? 'array' : typeof value;\n const errors = [];\n let coercedValue = value;\n\n // Support array of types\n const types = Array.isArray(type) ? type : [type];\n\n const isValid = types.some(t => {\n if (t === 'array') return Array.isArray(value);\n if (t === 'null') return value === null;\n if (t === 'integer') return typeof value === 'number' && Number.isInteger(value);\n return typeof value === t;\n });\n\n if (!isValid) {\n if (this.options.coerce) {\n // Try to coerce\n const primaryType = types[0];\n try {\n if (primaryType === 'string') {\n coercedValue = String(value);\n } else if (primaryType === 'number') {\n coercedValue = Number(value);\n if (isNaN(coercedValue)) {\n errors.push({\n path,\n message: `Cannot coerce \"${value}\" to number`,\n type: 'type',\n value,\n expected: primaryType\n });\n }\n } else if (primaryType === 'boolean') {\n coercedValue = Boolean(value);\n } else if (primaryType === 'integer') {\n coercedValue = parseInt(value, 10);\n if (isNaN(coercedValue)) {\n errors.push({\n path,\n message: `Cannot coerce \"${value}\" to integer`,\n type: 'type',\n value,\n expected: primaryType\n });\n }\n }\n } catch {\n errors.push({\n path,\n message: `Cannot coerce value to ${primaryType}`,\n type: 'type',\n value,\n expected: primaryType\n });\n }\n } else {\n errors.push({\n path,\n message: `Expected type ${types.join(' or ')}, got ${actualType}`,\n type: 'type',\n value,\n expected: type\n });\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n value: coercedValue\n };\n }\n\n validateEnum(value, enumValues, path) {\n const errors = [];\n if (!enumValues.includes(value)) {\n errors.push({\n path,\n message: `Value must be one of: ${enumValues.join(', ')}`,\n type: 'enum',\n value,\n expected: enumValues\n });\n }\n return { valid: errors.length === 0, errors };\n }\n\n validateString(value, schema, path) {\n const errors = [];\n\n if (schema.minLength !== undefined && value.length < schema.minLength) {\n errors.push({\n path,\n message: `String length must be >= ${schema.minLength}`,\n type: 'minLength',\n value\n });\n }\n\n if (schema.maxLength !== undefined && value.length > schema.maxLength) {\n errors.push({\n path,\n message: `String length must be <= ${schema.maxLength}`,\n type: 'maxLength',\n value\n });\n }\n\n if (schema.pattern) {\n const regex = new RegExp(schema.pattern);\n if (!regex.test(value)) {\n errors.push({\n path,\n message: `String does not match pattern: ${schema.pattern}`,\n type: 'pattern',\n value\n });\n }\n }\n\n if (schema.format) {\n const formatResult = this.validateFormat(value, schema.format, path);\n if (!formatResult.valid) {\n errors.push(...formatResult.errors);\n }\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n validateFormat(value, format, path) {\n const errors = [];\n const formats = {\n email: /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/,\n url: /^https?:\\/\\/.+/,\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n date: /^\\d{4}-\\d{2}-\\d{2}$/,\n 'date-time': /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/\n };\n\n if (formats[format] && !formats[format].test(value)) {\n errors.push({\n path,\n message: `String does not match format: ${format}`,\n type: 'format',\n value,\n expected: format\n });\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n validateNumber(value, schema, path) {\n const errors = [];\n\n if (schema.minimum !== undefined && value < schema.minimum) {\n errors.push({\n path,\n message: `Number must be >= ${schema.minimum}`,\n type: 'minimum',\n value\n });\n }\n\n if (schema.maximum !== undefined && value > schema.maximum) {\n errors.push({\n path,\n message: `Number must be <= ${schema.maximum}`,\n type: 'maximum',\n value\n });\n }\n\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) {\n errors.push({\n path,\n message: `Number must be > ${schema.exclusiveMinimum}`,\n type: 'exclusiveMinimum',\n value\n });\n }\n\n if (schema.exclusiveMaximum !== undefined && value >= schema.exclusiveMaximum) {\n errors.push({\n path,\n message: `Number must be < ${schema.exclusiveMaximum}`,\n type: 'exclusiveMaximum',\n value\n });\n }\n\n if (schema.multipleOf !== undefined && value % schema.multipleOf !== 0) {\n errors.push({\n path,\n message: `Number must be multiple of ${schema.multipleOf}`,\n type: 'multipleOf',\n value\n });\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n validateArray(value, schema, path) {\n const errors = [];\n const coercedValue = [...value];\n\n if (schema.minItems !== undefined && value.length < schema.minItems) {\n errors.push({\n path,\n message: `Array must have at least ${schema.minItems} items`,\n type: 'minItems',\n value\n });\n }\n\n if (schema.maxItems !== undefined && value.length > schema.maxItems) {\n errors.push({\n path,\n message: `Array must have at most ${schema.maxItems} items`,\n type: 'maxItems',\n value\n });\n }\n\n if (schema.uniqueItems) {\n const seen = new Set();\n const duplicates = [];\n value.forEach((item, index) => {\n const key = JSON.stringify(item);\n if (seen.has(key)) {\n duplicates.push(index);\n }\n seen.add(key);\n });\n if (duplicates.length > 0) {\n errors.push({\n path,\n message: 'Array items must be unique',\n type: 'uniqueItems',\n value\n });\n }\n }\n\n // Validate items\n if (schema.items) {\n value.forEach((item, index) => {\n const itemPath = `${path}[${index}]`;\n const itemResult = this.validate(item, schema.items, itemPath);\n if (!itemResult.valid) {\n errors.push(...itemResult.errors);\n }\n if (this.options.coerce) {\n coercedValue[index] = itemResult.value;\n }\n });\n }\n\n return {\n valid: errors.length === 0,\n errors,\n value: coercedValue\n };\n }\n\n validateObject(value, schema, path) {\n const errors = [];\n const coercedValue = { ...value };\n\n // Required properties\n if (schema.required) {\n schema.required.forEach(prop => {\n if (!(prop in value)) {\n errors.push({\n path: path ? `${path}.${prop}` : prop,\n message: `Required property \"${prop}\" is missing`,\n type: 'required',\n value: undefined\n });\n }\n });\n }\n\n // Validate properties\n if (schema.properties) {\n Object.entries(schema.properties).forEach(([prop, propSchema]) => {\n if (prop in value) {\n const propPath = path ? `${path}.${prop}` : prop;\n const propResult = this.validate(value[prop], propSchema, propPath);\n if (!propResult.valid) {\n errors.push(...propResult.errors);\n }\n if (this.options.coerce) {\n coercedValue[prop] = propResult.value;\n }\n }\n });\n }\n\n // Additional properties\n if (schema.additionalProperties === false && !this.options.allowUnknown) {\n const allowedProps = new Set(Object.keys(schema.properties || {}));\n Object.keys(value).forEach(prop => {\n if (!allowedProps.has(prop)) {\n errors.push({\n path: path ? `${path}.${prop}` : prop,\n message: `Unknown property \"${prop}\"`,\n type: 'additionalProperties',\n value: value[prop]\n });\n }\n });\n }\n\n // Min/max properties\n const propCount = Object.keys(value).length;\n if (schema.minProperties !== undefined && propCount < schema.minProperties) {\n errors.push({\n path,\n message: `Object must have at least ${schema.minProperties} properties`,\n type: 'minProperties',\n value\n });\n }\n\n if (schema.maxProperties !== undefined && propCount > schema.maxProperties) {\n errors.push({\n path,\n message: `Object must have at most ${schema.maxProperties} properties`,\n type: 'maxProperties',\n value\n });\n }\n\n return {\n valid: errors.length === 0,\n errors,\n value: coercedValue\n };\n }\n}\n\n/**\n * Create validated state manager\n * @param {Object} initialState - Initial state\n * @param {ValidationOptions} options - Validation options\n * @returns {Object} Validated state manager\n */\nexport function createValidatedState(initialState = {}, options = {}) {\n const opts = {\n schema: null,\n validators: {},\n strict: false,\n coerce: false,\n onError: null,\n validateOnSet: true,\n validateOnGet: false,\n required: [],\n allowUnknown: true,\n ...options\n };\n\n const schemaValidator = opts.schema ? new SchemaValidator(opts.schema, {\n coerce: opts.coerce,\n allowUnknown: opts.allowUnknown\n }) : null;\n\n let state = { ...initialState };\n const listeners = new Set();\n const validationErrors = new Map();\n\n /**\n * Validate state\n * @param {Object} value - State to validate\n * @param {string} key - State key (for partial validation)\n * @returns {ValidationResult} Validation result\n */\n function validateState(value, key = null) {\n const errors = [];\n let validatedValue = value;\n\n // JSON Schema validation\n if (schemaValidator) {\n const schema = key && opts.schema.properties\n ? opts.schema.properties[key]\n : opts.schema;\n\n const result = schemaValidator.validate(value, schema, key || '');\n if (!result.valid) {\n errors.push(...result.errors);\n }\n validatedValue = result.value;\n }\n\n // Custom validators\n if (key && opts.validators[key]) {\n const validator = opts.validators[key];\n const result = validator(value);\n if (result !== true) {\n errors.push({\n path: key,\n message: typeof result === 'string' ? result : 'Validation failed',\n type: 'custom',\n value\n });\n }\n } else if (!key) {\n // Run custom validators for all fields when validating full state\n Object.entries(opts.validators).forEach(([fieldKey, validator]) => {\n if (fieldKey in value) {\n const result = validator(value[fieldKey]);\n if (result !== true) {\n errors.push({\n path: fieldKey,\n message: typeof result === 'string' ? result : 'Validation failed',\n type: 'custom',\n value: value[fieldKey]\n });\n }\n }\n });\n }\n\n // Required fields\n if (opts.required.length > 0 && !key) {\n opts.required.forEach(field => {\n if (!(field in value)) {\n errors.push({\n path: field,\n message: `Required field \"${field}\" is missing`,\n type: 'required',\n value: undefined\n });\n }\n });\n }\n\n return {\n valid: errors.length === 0,\n errors,\n value: validatedValue\n };\n }\n\n /**\n * Get state\n * @param {string} key - State key\n * @returns {*} State value\n */\n function getState(key) {\n const value = key ? state[key] : { ...state };\n\n if (opts.validateOnGet) {\n const result = validateState(value, key);\n if (!result.valid) {\n validationErrors.set(key || '__root__', result.errors);\n if (opts.onError) {\n opts.onError(result.errors);\n }\n }\n }\n\n return value;\n }\n\n /**\n * Set state\n * @param {Object|Function} updates - State updates\n * @throws {Error} If validation fails in strict mode\n */\n function setState(updates) {\n const oldState = { ...state };\n\n if (typeof updates === 'function') {\n updates = updates(oldState);\n }\n\n // Create the new full state for validation\n const newState = { ...state, ...updates };\n\n // Validate before setting\n if (opts.validateOnSet) {\n const result = validateState(newState);\n\n if (!result.valid) {\n validationErrors.set('__root__', result.errors);\n\n if (opts.onError) {\n opts.onError(result.errors);\n }\n\n if (opts.strict) {\n const error = new Error('Validation failed');\n error.validationErrors = result.errors;\n throw error;\n }\n\n // Don't update state if validation fails in non-strict mode\n return;\n }\n\n // Use coerced value if coercion is enabled\n if (opts.coerce) {\n const updatedKeys = Object.keys(updates);\n const newUpdates = {};\n updatedKeys.forEach(key => {\n if (result.value[key] !== state[key]) {\n newUpdates[key] = result.value[key];\n }\n });\n updates = newUpdates;\n }\n\n // Clear errors on successful validation\n validationErrors.clear();\n }\n\n state = { ...state, ...updates };\n\n // Notify listeners\n listeners.forEach(listener => {\n try {\n listener(state, oldState);\n } catch (error) {\n console.error('Listener error:', error);\n }\n });\n }\n\n /**\n * Subscribe to state changes\n * @param {Function} listener - Change listener\n * @returns {Function} Unsubscribe function\n */\n function subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n\n /**\n * Get validation errors\n * @param {string} key - State key\n * @returns {Array<ValidationError>} Validation errors\n */\n function getErrors(key = '__root__') {\n return validationErrors.get(key) || [];\n }\n\n /**\n * Check if state is valid\n * @returns {boolean} Whether state is valid\n */\n function isValid() {\n const result = validateState(state);\n if (!result.valid) {\n validationErrors.set('__root__', result.errors);\n }\n return result.valid;\n }\n\n /**\n * Validate specific field\n * @param {string} key - Field key\n * @param {*} value - Field value\n * @returns {ValidationResult} Validation result\n */\n function validateField(key, value) {\n return validateState(value, key);\n }\n\n return {\n getState,\n setState,\n subscribe,\n getErrors,\n isValid,\n validateField,\n validate: () => validateState(state)\n };\n}\n\n/**\n * Common validators\n */\nexport const validators = {\n /**\n * Email validator\n * @param {string} value - Email to validate\n * @returns {boolean|string} True if valid, error message otherwise\n */\n email: (value) => {\n if (typeof value !== 'string') return 'Email must be a string';\n if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(value)) return 'Invalid email format';\n return true;\n },\n\n /**\n * URL validator\n * @param {string} value - URL to validate\n * @returns {boolean|string} True if valid, error message otherwise\n */\n url: (value) => {\n if (typeof value !== 'string') return 'URL must be a string';\n try {\n new URL(value);\n return true;\n } catch {\n return 'Invalid URL format';\n }\n },\n\n /**\n * Range validator\n * @param {number} min - Minimum value\n * @param {number} max - Maximum value\n * @returns {Function} Validator function\n */\n range: (min, max) => (value) => {\n if (typeof value !== 'number') return 'Value must be a number';\n if (value < min || value > max) return `Value must be between ${min} and ${max}`;\n return true;\n },\n\n /**\n * Length validator\n * @param {number} min - Minimum length\n * @param {number} max - Maximum length\n * @returns {Function} Validator function\n */\n length: (min, max) => (value) => {\n if (typeof value !== 'string') return 'Value must be a string';\n if (value.length < min || value.length > max) {\n return `Length must be between ${min} and ${max}`;\n }\n return true;\n },\n\n /**\n * Pattern validator\n * @param {RegExp|string} pattern - Pattern to match\n * @returns {Function} Validator function\n */\n pattern: (pattern) => (value) => {\n if (typeof value !== 'string') return 'Value must be a string';\n const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern;\n if (!regex.test(value)) return `Value does not match pattern: ${pattern}`;\n return true;\n },\n\n /**\n * Required validator\n * @param {*} value - Value to validate\n * @returns {boolean|string} True if valid, error message otherwise\n */\n required: (value) => {\n if (value === undefined || value === null || value === '') {\n return 'Value is required';\n }\n return true;\n }\n};\n\nexport default {\n createValidatedState,\n validators,\n SchemaValidator\n};\n", "/**\n * Enhanced OOP State Patterns for Coherent.js\n *\n * Specialized state classes that encapsulate complex behaviors\n * while maintaining the hybrid FP/OOP architecture\n */\n\nimport { createReactiveState } from './reactive-state.js';\n\n/**\n * Form State - OOP encapsulation for form logic\n */\nexport class FormState {\n constructor(initialValues = {}, options = {}) {\n this._state = createReactiveState({\n values: { ...initialValues },\n errors: {},\n touched: {},\n isSubmitting: false,\n isValid: true\n }, options);\n\n this._validators = {};\n this._options = options;\n }\n\n // OOP methods for form management\n setValue(field, value) {\n this._state.set('values', {\n ...this._state.get('values'),\n [field]: value\n });\n this._validateField(field);\n this._state.set('touched', {\n ...this._state.get('touched'),\n [field]: true\n });\n }\n\n getValue(field) {\n return this._state.get('values')[field];\n }\n\n setError(field, error) {\n this._state.set('errors', {\n ...this._state.get('errors'),\n [field]: error\n });\n this._updateIsValid();\n }\n\n addValidator(field, validator) {\n this._validators[field] = validator;\n }\n\n validateAll() {\n const values = this._state.get('values');\n const errors = {};\n\n Object.entries(this._validators).forEach(([field, validator]) => {\n const error = validator(values[field], values);\n if (error) {\n errors[field] = error;\n }\n });\n\n this._state.set('errors', errors);\n this._updateIsValid();\n return Object.keys(errors).length === 0;\n }\n\n async submit(onSubmit) {\n if (!this.validateAll()) return false;\n\n this._state.set('isSubmitting', true);\n\n try {\n await onSubmit(this._state.get('values'));\n return true;\n } catch (error) {\n this.setError('_form', error.message);\n return false;\n } finally {\n this._state.set('isSubmitting', false);\n }\n }\n\n reset() {\n this._state.set('values', {});\n this._state.set('errors', {});\n this._state.set('touched', {});\n this._state.set('isSubmitting', false);\n this._state.set('isValid', true);\n }\n\n // Watch methods for FP integration\n watchValues(callback) {\n return this._state.watch('values', callback);\n }\n\n watchErrors(callback) {\n return this._state.watch('errors', callback);\n }\n\n watchSubmitting(callback) {\n return this._state.watch('isSubmitting', callback);\n }\n\n // Private methods\n _validateField(field) {\n const value = this.getValue(field);\n const validator = this._validators[field];\n\n if (validator) {\n const error = validator(value, this._state.get('values'));\n this.setError(field, error);\n }\n }\n\n _updateIsValid() {\n const hasErrors = Object.keys(this._state.get('errors')).some(key =>\n this._state.get('errors')[key]\n );\n this._state.set('isValid', !hasErrors);\n }\n}\n\n/**\n * List State - OOP for collection management\n */\nexport class ListState {\n constructor(initialItems = [], options = {}) {\n this._state = createReactiveState({\n items: [...initialItems],\n loading: false,\n error: null,\n filters: {},\n sortBy: null,\n sortOrder: 'asc',\n page: 1,\n pageSize: options.pageSize || 10\n }, options);\n\n this._options = options;\n }\n\n // OOP methods for list operations\n addItem(item) {\n this._state.set('items', [...this._state.get('items'), item]);\n }\n\n removeItem(indexOrPredicate) {\n const items = this._state.get('items');\n let newItems;\n\n if (typeof indexOrPredicate === 'number') {\n newItems = items.filter((_, i) => i !== indexOrPredicate);\n } else {\n newItems = items.filter(item => !indexOrPredicate(item));\n }\n\n this._state.set('items', newItems);\n }\n\n updateItem(indexOrPredicate, updates) {\n const items = this._state.get('items');\n const newItems = items.map((item, i) => {\n if (typeof indexOrPredicate === 'number') {\n return i === indexOrPredicate ? { ...item, ...updates } : item;\n } else {\n return indexOrPredicate(item) ? { ...item, ...updates } : item;\n }\n });\n\n this._state.set('items', newItems);\n }\n\n filter(filters) {\n this._state.set('filters', filters);\n this._state.set('page', 1); // Reset to first page\n }\n\n sort(sortBy, order = 'asc') {\n this._state.set('sortBy', sortBy);\n this._state.set('sortOrder', order);\n }\n\n setPage(page) {\n this._state.set('page', Math.max(1, page));\n }\n\n async load(loader) {\n this._state.set('loading', true);\n this._state.set('error', null);\n\n try {\n const items = await loader(this._state.get('filters'));\n this._state.set('items', items);\n return items;\n } catch (error) {\n this._state.set('error', error.message);\n return [];\n } finally {\n this._state.set('loading', false);\n }\n }\n\n // Computed properties\n get filteredItems() {\n const items = this._state.get('items');\n const filters = this._state.get('filters');\n\n return items.filter(item => {\n return Object.entries(filters).every(([key, value]) => {\n if (!value) return true;\n return String(item[key] || '').toLowerCase().includes(String(value).toLowerCase());\n });\n });\n }\n\n get sortedItems() {\n const items = this.filteredItems;\n const sortBy = this._state.get('sortBy');\n const sortOrder = this._state.get('sortOrder');\n\n if (!sortBy) return items;\n\n return [...items].sort((a, b) => {\n const aVal = a[sortBy];\n const bVal = b[sortBy];\n\n if (aVal === bVal) return 0;\n\n const comparison = aVal < bVal ? -1 : 1;\n return sortOrder === 'desc' ? -comparison : comparison;\n });\n }\n\n get paginatedItems() {\n const items = this.sortedItems;\n const page = this._state.get('page');\n const pageSize = this._state.get('pageSize');\n\n const start = (page - 1) * pageSize;\n const end = start + pageSize;\n\n return items.slice(start, end);\n }\n\n get totalPages() {\n return Math.ceil(this.sortedItems.length / this._state.get('pageSize'));\n }\n\n // Watch methods\n watchItems(callback) {\n return this._state.watch('items', callback);\n }\n\n watchLoading(callback) {\n return this._state.watch('loading', callback);\n }\n}\n\n/**\n * Modal State - OOP for modal/dialog management\n */\nexport class ModalState {\n constructor(_initialState = {}) {\n this._state = createReactiveState({\n isOpen: false,\n data: null,\n loading: false,\n error: null\n });\n\n this._resolvers = new Map();\n this._currentId = 0;\n }\n\n // OOP methods for modal control\n async open(data) {\n return new Promise((resolve) => {\n const id = ++this._currentId;\n this._resolvers.set(id, resolve);\n\n this._state.set('data', data);\n this._state.set('isOpen', true);\n this._state.set('error', null);\n });\n }\n\n close(result = null) {\n const currentId = this._currentId;\n const resolver = this._resolvers.get(currentId);\n\n if (resolver) {\n resolver(result);\n this._resolvers.delete(currentId);\n }\n\n this._state.set('isOpen', false);\n this._state.set('data', null);\n }\n\n setLoading(loading) {\n this._state.set('loading', loading);\n }\n\n setError(error) {\n this._state.set('error', error);\n }\n\n // Watch methods\n watchOpen(callback) {\n return this._state.watch('isOpen', callback);\n }\n\n watchData(callback) {\n return this._state.watch('data', callback);\n }\n}\n\n/**\n * Router State - OOP for navigation state\n */\nexport class RouterState {\n constructor(initialRoute = '/', options = {}) {\n this._state = createReactiveState({\n current: initialRoute,\n params: {},\n query: {},\n history: [initialRoute],\n canGoBack: false,\n canGoForward: false\n }, options);\n\n this._routes = new Map();\n this._options = options;\n }\n\n // OOP methods for routing\n addRoute(path, handler) {\n this._routes.set(path, handler);\n }\n\n navigate(path, params = {}, query = {}) {\n this._state.set('history', [...this._state.get('history'), path]);\n this._state.set('current', path);\n this._state.set('params', params);\n this._state.set('query', query);\n this._updateNavigationState();\n }\n\n back() {\n const history = this._state.get('history');\n if (history.length > 1) {\n const newHistory = history.slice(0, -1);\n const previousRoute = newHistory[newHistory.length - 1];\n\n this._state.set('history', newHistory);\n this._state.set('current', previousRoute);\n this._updateNavigationState();\n }\n }\n\n forward() {\n // Implementation for forward navigation\n // Would need to track forward history separately\n }\n\n // Watch methods\n watchRoute(callback) {\n return this._state.watch('current', callback);\n }\n\n watchParams(callback) {\n return this._state.watch('params', callback);\n }\n\n // Private methods\n _updateNavigationState() {\n const history = this._state.get('history');\n this._state.set('canGoBack', history.length > 1);\n this._state.set('canGoForward', false); // Simplified\n }\n}\n\n/**\n * Factory functions for creating enhanced state\n */\nexport function createFormState(initialValues, options) {\n return new FormState(initialValues, options);\n}\n\nexport function createListState(initialItems, options) {\n return new ListState(initialItems, options);\n}\n\nexport function createModalState(initialState) {\n return new ModalState(initialState);\n}\n\nexport function createRouterState(initialRoute, options) {\n return new RouterState(initialRoute, options);\n}\n\n/**\n * Demo showing hybrid FP/OOP usage\n */\nexport function demoEnhancedPatterns() {\n // OOP state management\n const userForm = createFormState({\n name: '',\n email: '',\n age: ''\n });\n\n const userList = createListState([]);\n const userModal = createModalState();\n\n // Add validators (OOP methods)\n userForm.addValidator('name', (value) => {\n if (!value || value.length < 2) {\n return 'Name must be at least 2 characters';\n }\n });\n\n userForm.addValidator('email', (value) => {\n if (!value.includes('@')) {\n return 'Invalid email address';\n }\n });\n\n // FP component that uses OOP state\n const UserForm = () => ({\n form: {\n onsubmit: async (e) => {\n e.preventDefault();\n const success = await userForm.submit(async (values) => {\n userList.addItem(values);\n userModal.close();\n });\n\n if (!success) {\n console.log('Form validation failed');\n }\n },\n children: [\n { input: {\n type: 'text',\n placeholder: 'Name',\n value: userForm.getValue('name'),\n oninput: (e) => userForm.setValue('name', e.target.value)\n }},\n { input: {\n type: 'email',\n placeholder: 'Email',\n value: userForm.getValue('email'),\n oninput: (e) => userForm.setValue('email', e.target.value)\n }},\n { button: {\n type: 'submit',\n text: userForm._state.get('isSubmitting') ? 'Saving...' : 'Save User',\n disabled: !userForm._state.get('isValid') || userForm._state.get('isSubmitting')\n }}\n ]\n }\n });\n\n return {\n UserForm,\n userForm,\n userList,\n userModal\n };\n}\n\nexport default {\n FormState,\n ListState,\n ModalState,\n RouterState,\n createFormState,\n createListState,\n createModalState,\n createRouterState,\n demoEnhancedPatterns\n};\n", "/**\n * @coherent.js/state - Reactive State Management Package\n *\n * A comprehensive state management solution for Coherent.js applications\n * providing reactive state, persistence, validation, and SSR-compatible state management.\n */\n\n// Re-export everything from reactive-state\nexport {\n Observable,\n ReactiveState,\n StateError,\n globalErrorHandler,\n createReactiveState,\n observable,\n computed,\n stateUtils\n} from './reactive-state.js';\n\n// Import for default export\nimport {\n createReactiveState,\n observable,\n computed,\n stateUtils\n} from './reactive-state.js';\n\nimport {\n createState,\n globalStateManager,\n provideContext,\n createContextProvider,\n restoreContext,\n clearAllContexts,\n useContext\n} from './state-manager.js';\n\nimport {\n createPersistentState,\n withLocalStorage,\n withSessionStorage,\n withIndexedDB\n} from './state-persistence.js';\n\nimport {\n createValidatedState,\n validators\n} from './state-validation.js';\n\n// Import enhanced state patterns\nimport {\n createFormState,\n createListState,\n createModalState,\n createRouterState\n} from './enhanced-state-patterns.js';\n\n// Re-export everything from state-manager (SSR-compatible state)\nexport {\n createState,\n globalStateManager,\n provideContext,\n createContextProvider,\n restoreContext,\n clearAllContexts,\n useContext\n} from './state-manager.js';\n\n// Re-export everything from state-persistence\nexport {\n createPersistentState,\n withLocalStorage,\n withSessionStorage,\n withIndexedDB\n} from './state-persistence.js';\n\n// Re-export everything from state-validation\nexport {\n createValidatedState,\n validators\n} from './state-validation.js';\n\n// Re-export enhanced state patterns\nexport {\n FormState,\n ListState,\n ModalState,\n RouterState,\n createFormState,\n createListState,\n createModalState,\n createRouterState\n} from './enhanced-state-patterns.js';\n\n// Default export provides all utilities\nexport default {\n // Reactive state utilities\n createReactiveState,\n observable,\n computed,\n\n // SSR-compatible state management\n createState,\n globalStateManager,\n provideContext,\n createContextProvider,\n restoreContext,\n clearAllContexts,\n useContext,\n\n // Persistence utilities\n createPersistentState,\n withLocalStorage,\n withSessionStorage,\n withIndexedDB,\n\n // Validation utilities\n createValidatedState,\n validators,\n\n // Enhanced state patterns\n createFormState,\n createListState,\n createModalState,\n createRouterState,\n\n // State utilities\n stateUtils\n};\n"],
|
|
5
|
-
"mappings": ";A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,cAAc,SAAS;AACrD,SAAO,IAAI,UAAU,cAAc,OAAO;AAC5C;AAEO,SAAS,iBAAiB,cAAc;AAC7C,SAAO,IAAI,WAAW,YAAY;AACpC;AAEO,SAAS,kBAAkB,cAAc,SAAS;AACvD,SAAO,IAAI,YAAY,cAAc,OAAO;AAC9C;;;ACrTA,IAAO,gBAAQ;AAAA;AAAA,EAEX;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AACJ;",
|
|
6
|
-
"names": ["computed", "observable", "persist"]
|
|
4
|
+
"sourcesContent": ["/**\n * Reactive State Management System for Coherent.js\n * Provides computed properties, watchers, and reactive updates\n *\n * Design:\n *\n * - Reading an Observable or Computed inside a computed getter records it as a\n * dependency. A Computed recomputes lazily, on read, and only when a\n * dependency actually changed (version check).\n * - A Computed that is watched, or that a watched Computed depends on, is\n * \"live\": it subscribes to its dependencies so a change marks it dirty and\n * schedules its watchers. When it stops being watched it unsubscribes, so\n * nothing keeps a discarded computed reachable.\n * - Watchers do not run inside the setter: changes are queued and flushed in\n * a loop once the outermost batch() ends (every write outside a batch is its\n * own batch). A watcher that writes queues further work instead of\n * recursing; a loop that never settles is stopped and reported.\n * - Each watcher runs in isolation: an error is reported through the\n * `onError` option, or `globalErrorHandler`, and the other watchers still run.\n * - Reading a computed that (indirectly) reads itself throws a StateError.\n */\n\n// Simple error handling for this module\nexport class StateError extends Error {\n constructor(message, options = {}) {\n super(message);\n this.name = 'StateError';\n this.type = options.type || 'state';\n this.component = options.component;\n this.context = options.context;\n this.timestamp = Date.now();\n }\n}\n\nexport const globalErrorHandler = {\n handle(error, context = {}) {\n console.error('State Error:', error.message, context);\n }\n};\n\n/** Flush iterations after which a watcher loop is considered runaway. */\nconst MAX_FLUSH_ITERATIONS = 100;\n\n/** The computed currently collecting dependencies. */\nlet activeComputed = null;\n/** Nesting depth of batch(). */\nlet batchDepth = 0;\n/** Whether the notification queue is being flushed. */\nlet flushing = false;\n/** Observables with watchers that changed: observable -> value before the change. */\nconst pendingObservables = new Map();\n/** Watched computeds whose dependencies changed. */\nconst pendingComputeds = new Set();\n/** Bumped on every write, so an unobserved computed can skip validation. */\nlet globalVersion = 0;\n\nfunction reportError(source, error, type, context = {}) {\n const onError = source?._options?.onError;\n if (typeof onError === 'function') {\n try {\n onError(error, { type, ...context });\n return;\n } catch (handlerError) {\n error = handlerError;\n }\n }\n globalErrorHandler.handle(error, { type, context });\n}\n\nfunction runObserver(source, observer, newValue, oldValue) {\n try {\n observer.callback(newValue, oldValue, observer.unwatch);\n } catch (error) {\n reportError(source, error, 'watcher-error', { newValue, oldValue });\n }\n}\n\nfunction flush() {\n flushing = true;\n let iterations = 0;\n\n try {\n while (pendingObservables.size > 0 || pendingComputeds.size > 0) {\n if (++iterations > MAX_FLUSH_ITERATIONS) {\n const culprits = [...pendingObservables.keys(), ...pendingComputeds];\n pendingObservables.clear();\n pendingComputeds.clear();\n reportError(\n culprits[0],\n new StateError(\n `Watchers kept changing state after ${MAX_FLUSH_ITERATIONS} rounds; ` +\n 'a watcher probably writes a new value to a state it (indirectly) watches.',\n { type: 'update-depth' }\n ),\n 'update-depth'\n );\n return;\n }\n\n const observables = [...pendingObservables];\n pendingObservables.clear();\n for (const [source, oldValue] of observables) {\n const newValue = source._value;\n // Changed and changed back within one batch\n if (!source._changed(oldValue, newValue)) continue;\n for (const observer of [...source._observers]) {\n if (source._observers.has(observer)) {\n runObserver(source, observer, newValue, oldValue);\n }\n }\n }\n\n const computeds = [...pendingComputeds];\n pendingComputeds.clear();\n for (const source of computeds) {\n if (source._observers.size === 0) continue;\n try {\n source._refresh();\n } catch (error) {\n reportError(source, error, 'computed-error');\n continue;\n }\n const newValue = source._value;\n const oldValue = source._lastNotified;\n if (Object.is(newValue, oldValue)) continue;\n source._lastNotified = newValue;\n for (const observer of [...source._observers]) {\n if (source._observers.has(observer)) {\n runObserver(source, observer, newValue, oldValue);\n }\n }\n }\n }\n } finally {\n flushing = false;\n }\n}\n\nfunction scheduleFlush() {\n if (batchDepth === 0 && !flushing) {\n flush();\n }\n}\n\n/**\n * Run `fn` with watcher notifications deferred until it returns; every\n * watcher then runs once, with the final value. Nested batches flush when the\n * outermost one ends. `fn` must be synchronous.\n *\n * @template T\n * @param {() => T} fn\n * @returns {T}\n */\nexport function batch(fn) {\n batchDepth++;\n try {\n return fn();\n } finally {\n batchDepth--;\n scheduleFlush();\n }\n}\n\n/**\n * Observable wrapper for tracking state changes\n */\nexport class Observable {\n constructor(value, options = {}) {\n this._value = value;\n this._version = 0;\n /** @type {Set<{callback: Function, unwatch: Function}>} */\n this._observers = new Set();\n /** Live computeds depending on this value */\n this._subscribers = new Set();\n this._options = {\n deep: options.deep !== false,\n immediate: options.immediate !== false,\n ...options\n };\n }\n\n get value() {\n activeComputed?._track(this);\n return this._value;\n }\n\n set value(newValue) {\n this._write(newValue);\n }\n\n /** Read without registering a dependency. */\n peek() {\n return this._value;\n }\n\n /**\n * Whether a write from `oldValue` to `newValue` is a change. Identical\n * primitives never are; with `deep` (the default) re-assigning the same\n * object is, since it may have been mutated in place.\n * @private\n */\n _changed(oldValue, newValue) {\n if (!Object.is(oldValue, newValue)) return true;\n return this._options.deep && newValue !== null && typeof newValue === 'object';\n }\n\n /** @private */\n _write(newValue) {\n const oldValue = this._value;\n if (!this._changed(oldValue, newValue)) {\n return;\n }\n\n this._value = newValue;\n this._version++;\n globalVersion++;\n\n for (const subscriber of [...this._subscribers]) {\n subscriber._markDirty();\n }\n if (this._observers.size > 0 && !pendingObservables.has(this)) {\n pendingObservables.set(this, oldValue);\n }\n scheduleFlush();\n }\n\n /** @private */\n _addSubscriber(computed) {\n this._subscribers.add(computed);\n }\n\n /** @private */\n _removeSubscriber(computed) {\n this._subscribers.delete(computed);\n }\n\n /** @private */\n _addObserver(observer) {\n this._observers.add(observer);\n }\n\n /** @private */\n _removeObserver(observer) {\n this._observers.delete(observer);\n }\n\n watch(callback, options = {}) {\n if (typeof callback !== 'function') {\n throw new StateError('Watch callback must be a function');\n }\n\n const observer = { callback, unwatch: null };\n observer.unwatch = () => this._removeObserver(observer);\n this._addObserver(observer);\n\n // Call immediately if requested\n if (options.immediate !== false) {\n runObserver(this, observer, this._value, undefined);\n }\n\n // Return unwatch function\n return observer.unwatch;\n }\n\n /**\n * Remove a watcher, by the callback passed to watch()\n * @param {Function} callback\n */\n unwatch(callback) {\n for (const observer of [...this._observers]) {\n if (observer.callback === callback || observer.unwatch === callback) {\n this._removeObserver(observer);\n }\n }\n }\n\n /** Remove every watcher. */\n unwatchAll() {\n for (const observer of [...this._observers]) {\n this._removeObserver(observer);\n }\n }\n}\n\n/**\n * Computed property implementation\n */\nclass Computed extends Observable {\n constructor(getter, options = {}) {\n if (typeof getter !== 'function') {\n throw new StateError('Computed getter must be a function');\n }\n super(undefined, options);\n this._getter = getter;\n /** Dependencies read by the last computation: source -> its version then */\n this._deps = new Map();\n this._dirty = true;\n this._computing = false;\n this._globalVersionSeen = -1;\n this._lastNotified = undefined;\n }\n\n get value() {\n this._refresh();\n activeComputed?._track(this);\n return this._value;\n }\n\n set value(_newValue) {\n throw new StateError('Cannot set value on computed property');\n }\n\n peek() {\n this._refresh();\n return this._value;\n }\n\n /** Watched, or a dependency of a live computed. @private */\n get _live() {\n return this._observers.size > 0 || this._subscribers.size > 0;\n }\n\n /** @private */\n _track(source) {\n if (!this._deps.has(source)) {\n this._deps.set(source, source._version);\n }\n }\n\n /** Bring the cached value up to date. @private */\n _refresh() {\n if (this._computing) {\n throw new StateError('Circular dependency between computed properties', {\n type: 'computed-cycle',\n context: { getter: this._getter.name || 'anonymous' }\n });\n }\n if (!this._dirty) {\n // A live computed is marked dirty by its dependencies\n if (this._live || this._globalVersionSeen === globalVersion) return;\n if (!this._dependenciesChanged()) {\n this._globalVersionSeen = globalVersion;\n return;\n }\n }\n this._recompute();\n }\n\n /** @private */\n _dependenciesChanged() {\n for (const [source, version] of this._deps) {\n if (source instanceof Computed) {\n source._refresh();\n }\n if (source._version !== version) return true;\n }\n return false;\n }\n\n /** @private */\n _recompute() {\n const previousDeps = this._deps;\n const previousActive = activeComputed;\n this._deps = new Map();\n this._computing = true;\n activeComputed = this;\n\n let newValue;\n try {\n newValue = this._getter();\n } catch (error) {\n // Stay dirty so the next read retries\n this._deps = previousDeps;\n this._dirty = true;\n throw error;\n } finally {\n this._computing = false;\n activeComputed = previousActive;\n }\n\n if (this._live) {\n for (const source of previousDeps.keys()) {\n if (!this._deps.has(source)) source._removeSubscriber(this);\n }\n for (const source of this._deps.keys()) {\n if (!previousDeps.has(source)) source._addSubscriber(this);\n }\n }\n\n this._dirty = false;\n this._globalVersionSeen = globalVersion;\n if (!Object.is(newValue, this._value)) {\n this._value = newValue;\n this._version++;\n }\n }\n\n /** A dependency changed. @private */\n _markDirty() {\n if (this._dirty) return;\n this._dirty = true;\n if (this._observers.size > 0) {\n pendingComputeds.add(this);\n }\n for (const subscriber of [...this._subscribers]) {\n subscriber._markDirty();\n }\n }\n\n /** Subscribe to dependencies. @private */\n _goLive() {\n this._refresh();\n for (const source of this._deps.keys()) {\n source._addSubscriber(this);\n }\n }\n\n /** Unsubscribe from dependencies. @private */\n _goLazy() {\n for (const source of this._deps.keys()) {\n source._removeSubscriber(this);\n }\n }\n\n /** @private */\n _addSubscriber(computed) {\n const wasLive = this._live;\n this._subscribers.add(computed);\n if (!wasLive) this._goLive();\n }\n\n /** @private */\n _removeSubscriber(computed) {\n this._subscribers.delete(computed);\n if (!this._live) this._goLazy();\n }\n\n /** @private */\n _addObserver(observer) {\n const hadObservers = this._observers.size > 0;\n const wasLive = this._live;\n this._observers.add(observer);\n try {\n if (wasLive) {\n this._refresh();\n } else {\n this._goLive();\n }\n } catch (error) {\n this._observers.delete(observer);\n throw error;\n }\n if (!hadObservers) {\n // Baseline for the next notification's oldValue\n this._lastNotified = this._value;\n }\n }\n\n /** @private */\n _removeObserver(observer) {\n if (!this._observers.delete(observer)) return;\n if (!this._live) this._goLazy();\n }\n}\n\n/** Placeholder observables for keys read before they exist or after delete(). */\nconst ABSENT = Symbol('absent');\n\nfunction isPath(key) {\n return typeof key === 'string' && key.includes('.');\n}\n\nfunction readPath(value, segments) {\n let current = value;\n for (const segment of segments) {\n if (current === null || current === undefined) return undefined;\n current = current[segment];\n }\n return current;\n}\n\n/** A copy of `target` with `segments` set to `value`, creating objects as needed. */\nfunction writePath(target, segments, value) {\n const [head, ...rest] = segments;\n const base = target !== null && typeof target === 'object'\n ? (Array.isArray(target) ? [...target] : { ...target })\n : {};\n const next = rest.length === 0 ? value : writePath(base[head], rest, value);\n Object.defineProperty(base, head, { value: next, enumerable: true, writable: true, configurable: true });\n return base;\n}\n\n/** A copy of `target` without the property at `segments`. */\nfunction deletePath(target, segments) {\n if (target === null || typeof target !== 'object') return target;\n const [head, ...rest] = segments;\n if (!Object.prototype.hasOwnProperty.call(target, head)) return target;\n const base = Array.isArray(target) ? [...target] : { ...target };\n if (rest.length === 0) {\n delete base[head];\n } else {\n base[head] = deletePath(base[head], rest);\n }\n return base;\n}\n\n/**\n * Reactive state container with advanced features\n *\n * Keys may be dot paths into object values: `set('user.name', 'Ada')` writes\n * a copy of `user` with the new name (notifying watchers of `user` and of\n * `user.name`), and `get`/`has`/`watch`/`delete` accept paths too.\n */\nexport class ReactiveState {\n constructor(initialState = {}, options = {}) {\n /** @type {Map<string, Observable>} */\n this._state = new Map();\n this._computed = new Map();\n this._watchers = new Map();\n this._expressionWatchers = new Set();\n this._middleware = [];\n this._history = [];\n this._options = {\n enableHistory: options.enableHistory !== false,\n maxHistorySize: options.maxHistorySize || 50,\n enableMiddleware: options.enableMiddleware !== false,\n deep: options.deep !== false,\n ...options\n };\n\n // Initialize state\n Object.entries(initialState).forEach(([key, value]) => {\n this.set(key, value);\n });\n }\n\n /** Observable for a key, created as an absent placeholder if needed. @private */\n _observable(key) {\n let observable = this._state.get(key);\n if (!observable) {\n observable = new Observable(ABSENT, this._options);\n this._state.set(key, observable);\n }\n return observable;\n }\n\n /** Whether a key is stored under its full name. @private */\n _hasOwnKey(key) {\n const observable = this._state.get(key);\n return Boolean(observable) && observable._value !== ABSENT;\n }\n\n /** [rootKey, pathSegments] for a dot path, or null for a plain key. @private */\n _splitPath(key) {\n if (!isPath(key)) return null;\n const [root, ...segments] = key.split('.');\n return [root, segments];\n }\n\n /**\n * Get reactive state value\n */\n get(key) {\n const path = this._splitPath(key);\n if (path) {\n return readPath(this.get(path[0]), path[1]);\n }\n // Reading a missing key inside a computed still records the\n // dependency, so the computed updates once the key is set.\n const observable = activeComputed ? this._observable(key) : this._state.get(key);\n if (!observable) return undefined;\n const value = observable.value;\n return value === ABSENT ? undefined : value;\n }\n\n /**\n * Set reactive state value\n */\n set(key, value, options = {}) {\n const config = { ...this._options, ...options };\n const oldValue = this.get(key);\n\n // Run middleware\n if (config.enableMiddleware) {\n const middlewareResult = this._runMiddleware('set', { key, value, oldValue });\n if (middlewareResult.cancelled) {\n return false;\n }\n value = middlewareResult.value !== undefined ? middlewareResult.value : value;\n }\n\n const path = this._splitPath(key);\n if (path) {\n const [root, segments] = path;\n if (config.enableHistory) {\n this._addToHistory('set', key, oldValue, value);\n }\n this._writeKey(root, writePath(this.get(root), segments, value));\n return true;\n }\n\n // Record history\n if (config.enableHistory && this._hasOwnKey(key)) {\n this._addToHistory('set', key, oldValue, value);\n }\n\n this._writeKey(key, value);\n return true;\n }\n\n /** @private */\n _writeKey(key, value) {\n this._observable(key)._write(value);\n }\n\n /**\n * Check if state has a key\n */\n has(key) {\n const path = this._splitPath(key);\n if (path) {\n const parent = readPath(this.get(path[0]), path[1].slice(0, -1));\n return parent !== null && typeof parent === 'object' &&\n Object.prototype.hasOwnProperty.call(parent, path[1][path[1].length - 1]);\n }\n return this._hasOwnKey(key);\n }\n\n /**\n * Delete state key. Its watchers are removed; computed properties that\n * read it update.\n */\n delete(key) {\n const path = this._splitPath(key);\n if (path) {\n if (!this.has(key)) return false;\n if (this._options.enableHistory) {\n this._addToHistory('delete', key, this.get(key), undefined);\n }\n this._writeKey(path[0], deletePath(this.get(path[0]), path[1]));\n return true;\n }\n\n if (!this._hasOwnKey(key)) {\n return false;\n }\n\n const observable = this._state.get(key);\n\n // Record history\n if (this._options.enableHistory) {\n this._addToHistory('delete', key, observable._value, undefined);\n }\n\n observable.unwatchAll();\n this._releaseKeyWatchers(key);\n observable._write(ABSENT);\n return true;\n }\n\n /** @private */\n _releaseKeyWatchers(key) {\n const unwatchers = this._watchers.get(key);\n if (unwatchers) {\n for (const unwatch of unwatchers) unwatch();\n this._watchers.delete(key);\n }\n }\n\n /**\n * Clear all state\n */\n clear() {\n // Record history\n if (this._options.enableHistory) {\n this._addToHistory('clear', null, this.toObject(), {});\n }\n\n batch(() => {\n for (const [key, observable] of this._state) {\n observable.unwatchAll();\n this._releaseKeyWatchers(key);\n observable._write(ABSENT);\n }\n });\n\n this._computed.clear();\n this._watchers.clear();\n }\n\n /**\n * Create computed property\n */\n computed(key, getter, options = {}) {\n if (typeof getter !== 'function') {\n throw new StateError(`Computed property '${key}' getter must be a function`);\n }\n\n const computed = new Computed(getter, { ...this._options, ...options });\n this._computed.set(key, computed);\n\n return computed;\n }\n\n /**\n * Get computed property value\n */\n getComputed(key) {\n const computed = this._computed.get(key);\n return computed ? computed.value : undefined;\n }\n\n /**\n * Watch state changes: a key, a dot path into a key, or a getter\n * expression (re-evaluated whenever what it reads changes).\n */\n watch(key, callback, options = {}) {\n if (typeof key === 'function') {\n // Watch computed expression\n return this._watchComputed(key, callback, options);\n }\n\n const path = this._splitPath(key);\n if (path) {\n if (!this._hasOwnKey(path[0])) {\n throw new StateError(`Cannot watch undefined state key: ${path[0]}`);\n }\n const computed = new Computed(() => this.get(key), { ...this._options, ...options });\n return this._track(key, computed.watch(callback, options));\n }\n\n if (!this._hasOwnKey(key)) {\n throw new StateError(`Cannot watch undefined state key: ${key}`);\n }\n\n return this._track(key, this._state.get(key).watch(callback, options));\n }\n\n /** Remember an unwatch function for cleanup. @private */\n _track(key, unwatch) {\n if (!this._watchers.has(key)) {\n this._watchers.set(key, new Set());\n }\n const unwatchers = this._watchers.get(key);\n const release = () => {\n unwatch();\n unwatchers.delete(release);\n };\n unwatchers.add(release);\n return release;\n }\n\n /**\n * Watch computed expression\n */\n _watchComputed(expression, callback, options = {}) {\n const computed = new Computed(expression, { ...this._options, ...options });\n const unwatch = computed.watch(callback, options);\n const release = () => {\n unwatch();\n this._expressionWatchers.delete(release);\n };\n this._expressionWatchers.add(release);\n return release;\n }\n\n /**\n * Batch state updates: watchers run once, after every update, with the\n * final values.\n */\n batch(updates) {\n if (typeof updates === 'function') {\n // Batch function updates\n const oldEnableHistory = this._options.enableHistory;\n this._options.enableHistory = false;\n\n try {\n const result = batch(() => updates(this));\n\n // Record batch in history\n if (oldEnableHistory) {\n this._addToHistory('batch', null, null, this.toObject());\n }\n\n return result;\n } finally {\n this._options.enableHistory = oldEnableHistory;\n }\n } else if (typeof updates === 'object') {\n // Batch object updates\n return this.batch(() => {\n Object.entries(updates).forEach(([key, value]) => {\n this.set(key, value);\n });\n });\n }\n }\n\n /**\n * Subscribe to multiple state changes\n */\n subscribe(keys, callback, options = {}) {\n if (!Array.isArray(keys)) {\n keys = [keys];\n }\n\n const unwatchers = keys.map(key => {\n return this.watch(key, (newValue, oldValue) => {\n callback({\n key,\n newValue,\n oldValue,\n state: this.toObject()\n });\n }, options);\n });\n\n // Return unsubscribe function\n return () => {\n unwatchers.forEach(unwatch => unwatch());\n };\n }\n\n /**\n * Add middleware for state changes\n */\n use(middleware) {\n if (typeof middleware !== 'function') {\n throw new StateError('Middleware must be a function');\n }\n this._middleware.push(middleware);\n }\n\n /**\n * Run middleware chain\n */\n _runMiddleware(action, context) {\n let result = { ...context, cancelled: false };\n\n for (const middleware of this._middleware) {\n try {\n const middlewareResult = middleware(action, result);\n if (middlewareResult) {\n result = { ...result, ...middlewareResult };\n if (result.cancelled) {\n break;\n }\n }\n } catch (error) {\n reportError(this, error, 'middleware-error', { action });\n }\n }\n\n return result;\n }\n\n /**\n * Add action to history\n */\n _addToHistory(action, key, oldValue, newValue) {\n if (!this._options.enableHistory) return;\n\n this._history.unshift({\n action,\n key,\n oldValue,\n newValue,\n timestamp: Date.now()\n });\n\n // Limit history size\n if (this._history.length > this._options.maxHistorySize) {\n this._history = this._history.slice(0, this._options.maxHistorySize);\n }\n }\n\n /**\n * Get state history\n */\n getHistory(limit = 10) {\n return this._history.slice(0, limit);\n }\n\n /**\n * Undo last action\n */\n undo() {\n const lastAction = this._history.shift();\n if (!lastAction) return false;\n\n const { action, key, oldValue } = lastAction;\n\n // Temporarily disable history\n const oldEnableHistory = this._options.enableHistory;\n this._options.enableHistory = false;\n\n try {\n switch (action) {\n case 'set':\n if (oldValue === undefined) {\n this.delete(key);\n } else {\n this.set(key, oldValue);\n }\n break;\n case 'delete':\n this.set(key, oldValue);\n break;\n case 'clear':\n this.clear();\n Object.entries(oldValue || {}).forEach(([k, v]) => {\n this.set(k, v);\n });\n break;\n }\n return true;\n } finally {\n this._options.enableHistory = oldEnableHistory;\n }\n }\n\n /**\n * Convert state to plain object\n */\n toObject() {\n // Object.fromEntries defines own properties, so a \"__proto__\" key\n // stays a key instead of replacing the result's prototype.\n return Object.fromEntries(\n [...this._state]\n .filter(([, observable]) => observable._value !== ABSENT)\n .map(([key, observable]) => [key, observable._value])\n );\n }\n\n /**\n * Convert computed properties to object\n */\n getComputedValues() {\n return Object.fromEntries(\n [...this._computed].map(([key, computed]) => [key, computed.value])\n );\n }\n\n /**\n * Get state statistics\n */\n getStats() {\n let stateKeys = 0;\n for (const observable of this._state.values()) {\n if (observable._value !== ABSENT) stateKeys++;\n }\n return {\n stateKeys,\n computedKeys: this._computed.size,\n watcherKeys: this._watchers.size,\n historyLength: this._history.length,\n middlewareCount: this._middleware.length\n };\n }\n\n /**\n * Cleanup and destroy\n */\n destroy() {\n // Clear all watchers\n for (const key of [...this._watchers.keys()]) {\n this._releaseKeyWatchers(key);\n }\n for (const release of [...this._expressionWatchers]) {\n release();\n }\n for (const observable of this._state.values()) {\n observable.unwatchAll();\n }\n for (const computed of this._computed.values()) {\n computed.unwatchAll();\n }\n\n // Clear collections\n this._state.clear();\n this._computed.clear();\n this._watchers.clear();\n this._middleware.length = 0;\n this._history.length = 0;\n }\n}\n\n/**\n * Create reactive state store\n */\nexport function createReactiveState(initialState, options = {}) {\n return new ReactiveState(initialState, options);\n}\n\n/**\n * Create observable value\n */\nexport function observable(value, options = {}) {\n return new Observable(value, options);\n}\n\n/**\n * Create computed property\n */\nexport function computed(getter, options = {}) {\n return new Computed(getter, options);\n}\n\n/**\n * Utility functions for common state patterns\n */\nexport const stateUtils = {\n /**\n * Create a toggle state\n */\n toggle(initialValue = false) {\n const obs = observable(initialValue);\n obs.toggle = () => {\n obs.value = !obs.value;\n };\n return obs;\n },\n\n /**\n * Create a counter state\n */\n counter(initialValue = 0) {\n const obs = observable(initialValue);\n obs.increment = (by = 1) => {\n obs.value += by;\n };\n obs.decrement = (by = 1) => {\n obs.value -= by;\n };\n obs.reset = () => {\n obs.value = initialValue;\n };\n return obs;\n },\n\n /**\n * Create an array state with utilities\n */\n array(initialArray = []) {\n const obs = observable([...initialArray]);\n obs.push = (...items) => {\n obs.value = [...obs.value, ...items];\n };\n obs.pop = () => {\n const newArray = [...obs.value];\n const result = newArray.pop();\n obs.value = newArray;\n return result;\n };\n obs.filter = (predicate) => {\n obs.value = obs.value.filter(predicate);\n };\n obs.clear = () => {\n obs.value = [];\n };\n return obs;\n },\n\n /**\n * Create object state with deep reactivity\n */\n object(initialObject = {}) {\n const state = createReactiveState(initialObject, { deep: true });\n return state;\n }\n};\n\nexport default ReactiveState;\n", "/**\n * Simple state management for server-side rendering\n * This is mainly for component state during rendering\n */\n\nconst globalState = new Map();\n\n/**\n * Creates a state container for a request/render cycle\n * @param {Object} initialState - Initial state object\n * @returns {Object} State container\n */\nexport function createState(initialState = {}) {\n const state = new Map(Object.entries(initialState));\n\n return {\n get(key) {\n return state.get(key);\n },\n\n set(key, value) {\n state.set(key, value);\n return this;\n },\n\n has(key) {\n return state.has(key);\n },\n\n delete(key) {\n return state.delete(key);\n },\n\n clear() {\n state.clear();\n return this;\n },\n\n toObject() {\n return Object.fromEntries(state);\n },\n\n // For debugging\n _internal: state\n };\n}\n\n/**\n * Global state for sharing data across components during SSR.\n *\n * This store is process-wide: every request sees it. It is also the fallback\n * useContext() reads when no context has been provided for a key, so it suits\n * application-wide defaults, never request data.\n */\nexport const globalStateManager = {\n set(key, value) {\n globalState.set(key, value);\n },\n\n get(key) {\n return globalState.get(key);\n },\n\n has(key) {\n return globalState.has(key);\n },\n\n clear() {\n globalState.clear();\n },\n\n // Create isolated state for each request\n createRequestState() {\n return createState();\n }\n};\n\n// ============================================================================\n// Context API\n// ============================================================================\n//\n// A scope is an immutable Map from context key to a linked stack entry\n// `{ value, previous }`. A holder `{ scope, owned }` points at the current\n// scope.\n//\n// On Node the holder lives in an AsyncLocalStorage, so it follows each\n// request's async execution:\n//\n// - runWithContext() (and a provider) runs its callback with a fresh holder\n// that it owns. Inside it every change updates that holder in place, so\n// the value stays put across the awaits and yields of an async or\n// streaming render, and nothing leaks out of it.\n// - Outside any owned holder there is nothing request-scoped to write to, so\n// providing a value throws (see setScope()).\n//\n// Browsers have no AsyncLocalStorage. There a single module holder is updated\n// in place, which is exact for synchronous rendering; a value read after an\n// `await` sees whatever is current at that point.\n\nconst EMPTY_SCOPE = new Map();\n\nfunction createAsyncStorage() {\n try {\n // Never a static import: this module also runs in browsers.\n const asyncHooks = globalThis.process?.getBuiltinModule?.('node:async_hooks');\n const AsyncLocalStorage = asyncHooks?.AsyncLocalStorage;\n return typeof AsyncLocalStorage === 'function' ? new AsyncLocalStorage() : null;\n } catch {\n return null;\n }\n}\n\nconst asyncStorage = createAsyncStorage();\n\n/** The holder used when AsyncLocalStorage is unavailable. */\nconst syncHolder = { scope: EMPTY_SCOPE, owned: true };\n\nfunction currentHolder() {\n return asyncStorage ? asyncStorage.getStore() : syncHolder;\n}\n\nfunction currentScope() {\n return currentHolder()?.scope ?? EMPTY_SCOPE;\n}\n\n/**\n * Make `scope` current in `holder` (the scope of the enclosing\n * runWithContext() call, or the browser's single holder).\n *\n * There is deliberately no fallback outside runWithContext() on the server.\n * AsyncLocalStorage#enterWith() attached the value to the caller's async\n * context, and a request's async context is shared with the next request\n * on the same keep-alive connection: the value leaked to other users (and\n * a module-level store would leak to every request).\n */\nfunction setScope(scope, holder = currentHolder()) {\n if (!holder?.owned) {\n throw new Error(\n 'Context can only be provided inside runWithContext() on the server: outside it the value ' +\n 'would leak into other requests. Wrap each request or render: runWithContext(() => ...).'\n );\n }\n holder.scope = scope;\n}\n\n/**\n * Run `fn(...args)` with `scope` current in a holder of its own, restoring the\n * previous scope afterwards.\n */\nfunction runInScope(scope, fn, args) {\n if (asyncStorage) {\n return asyncStorage.run({ scope, owned: true }, fn, ...args);\n }\n\n const previous = syncHolder.scope;\n syncHolder.scope = scope;\n try {\n return fn(...args);\n } finally {\n syncHolder.scope = previous;\n }\n}\n\nfunction withValue(scope, key, value) {\n const next = new Map(scope);\n next.set(key, { value, previous: scope.get(key) });\n return next;\n}\n\n/**\n * Run `fn` in a fresh, isolated context scope \u2014 one per request or render.\n *\n * Nothing provided inside `fn` is visible outside it and nothing provided\n * outside is visible inside. On Node this holds across `await`s, so wrap each\n * request (or each `renderToStream()` consumer) in it.\n *\n * @template T\n * @param {() => T} fn - Work to run, typically a request handler or a render\n * @param {Object} [values] - Initial context values, keyed by context key\n * @returns {T} Whatever `fn` returns (a promise for an async `fn`)\n */\nexport function runWithContext(fn, values) {\n if (typeof fn !== 'function') {\n throw new TypeError(`runWithContext() requires a function, received: ${typeof fn}`);\n }\n\n let scope = EMPTY_SCOPE;\n if (values && typeof values === 'object') {\n for (const [key, value] of Object.entries(values)) {\n scope = withValue(scope, key, value);\n }\n }\n\n return runInScope(scope, fn, []);\n}\n\n/**\n * Provide a context value for the rest of the current runWithContext() scope,\n * remembering the previous one so {@link restoreContext} can unwind it.\n *\n * On Node it must be called inside {@link runWithContext} (it throws\n * otherwise); a concurrent request does not see the value, even across\n * `await`s. In browsers it may be called anywhere.\n *\n * @throws {Error} On Node, when called outside runWithContext()\n *\n * @param {string} key - Context key\n * @param {*} value - Context value\n */\nexport function provideContext(key, value) {\n setScope(withValue(currentScope(), key, value));\n}\n\n/**\n * Create a context provider component.\n *\n * The provider is a zero-argument function component. When the renderer calls\n * it, it evaluates the function components and function-valued props below\n * it with the value provided, and returns the resulting plain tree; its\n * siblings do not see the value. Nothing is pre-rendered, so the renderer\n * escapes the children exactly once. Values read later, such as in an event\n * handler, do not see it.\n *\n * Called with a render function instead, the provider runs\n * `renderFunction(children)` with the context provided and returns its result.\n * On Node an async render function keeps the context across its `await`s.\n *\n * @param {string} key - Context key\n * @param {*} value - Context value\n * @param {*} children - Children to render with context\n * @returns {Function} Context provider component\n */\nexport function createContextProvider(key, value, children) {\n // Rest parameters keep `length` at 0, so a renderer calls this as an\n // ordinary function component.\n function contextProvider(...args) {\n const renderFunction = args[0];\n const scope = withValue(currentScope(), key, value);\n\n if (typeof renderFunction === 'function') {\n return runInScope(scope, renderFunction, [children]);\n }\n\n // Evaluate the function components below the provider inside its\n // scope, and hand the renderer the resulting plain tree. The scope\n // is restored even when a child throws; enter/leave marker\n // components used to leave the value set for the next request when\n // a child threw before the \"leave\" marker ran.\n return runInScope(scope, resolveComponents, [children]);\n }\n\n return contextProvider;\n}\n\nconst TAG_NAME = /^[a-zA-Z][a-zA-Z0-9-]*$/;\n\n/**\n * Call the function components in a tree the way the renderer does (no\n * arguments, following returned functions), so context reads happen now.\n * Unchanged nodes are returned as they are (trusted-content markers keep\n * their brand); event handlers are props and are never called.\n */\nfunction resolveComponents(node, depth = 0) {\n if (depth > 1000) return node;\n\n if (typeof node === 'function') {\n return resolveComponents(node(), depth + 1);\n }\n if (Array.isArray(node)) {\n let changed = false;\n const resolved = node.map((child) => {\n const next = resolveComponents(child, depth + 1);\n if (next !== child) changed = true;\n return next;\n });\n return changed ? resolved : node;\n }\n if (!node || typeof node !== 'object') return node;\n\n if (node.__isLazy === true && typeof node.evaluate === 'function') {\n return resolveComponents(node.evaluate(), depth + 1);\n }\n\n const tags = Object.keys(node);\n if (tags.length === 0 || !tags.every((tag) => TAG_NAME.test(tag))) return node;\n\n let changed = false;\n const resolved = {};\n for (const tag of tags) {\n let content = node[tag];\n if (typeof content === 'function') {\n content = resolveComponents(content(), depth + 1);\n }\n if (content && typeof content === 'object' && !Array.isArray(content) && !isTrusted(content)) {\n content = resolveProps(content, depth);\n }\n if (content !== node[tag]) changed = true;\n resolved[tag] = content;\n }\n return changed ? resolved : node;\n}\n\nfunction isTrusted(value) {\n return value[Symbol.for('coherent.js.trustedContent')] === true;\n}\n\n/**\n * Evaluate the function-valued props the renderer would call (`text`,\n * `html` and attributes other than `on*` event handlers) and the children.\n * An attribute function that throws is left for the renderer, which\n * reports it and renders an empty value.\n */\nfunction resolveProps(props, depth) {\n let next = props;\n const set = (key, value) => {\n if (next === props) next = { ...props };\n next[key] = value;\n };\n\n for (const key of Object.keys(props)) {\n const value = props[key];\n if (key === 'children') {\n if (value !== undefined && value !== null) {\n const children = resolveComponents(value, depth + 1);\n if (children !== value) set(key, children);\n }\n } else if (typeof value === 'function' && key !== 'key') {\n if (key === 'text' || key === 'html') {\n set(key, value());\n } else if (!key.startsWith('on')) {\n try {\n set(key, value());\n } catch {\n // left in place for the renderer\n }\n }\n }\n }\n return next;\n}\n\n/**\n * Restore context to its previous value\n * @param {string} key - Context key\n */\nexport function restoreContext(key) {\n const scope = currentScope();\n const entry = scope.get(key);\n if (!entry) return;\n\n const next = new Map(scope);\n if (entry.previous) {\n next.set(key, entry.previous);\n } else {\n next.delete(key);\n }\n setScope(next);\n}\n\n/**\n * Drop every context provided in the current execution.\n *\n * Values set through {@link globalStateManager} are not contexts and are left\n * alone; useContext() falls back to them again.\n */\nexport function clearAllContexts() {\n if (currentScope().size > 0) {\n setScope(EMPTY_SCOPE);\n }\n}\n\n/**\n * Context consumer to access provided context\n *\n * Falls back to {@link globalStateManager} when no context has been provided\n * for `key`.\n *\n * @param {string} key - Context key\n * @returns {*} Context value\n */\nexport function useContext(key) {\n const entry = currentScope().get(key);\n return entry ? entry.value : globalState.get(key);\n}\n", "/**\n * @fileoverview State Persistence for Coherent.js\n * Provides persistent state management with multiple storage backends\n * @module @coherent.js/core/state/state-persistence\n */\n\n/**\n * @typedef {'localStorage'|'sessionStorage'|'indexedDB'|'memory'} StorageType\n */\n\n/**\n * @typedef {Object} PersistenceOptions\n * @property {StorageType} [storage='localStorage'] - Storage backend to use\n * @property {StorageAdapter} [adapter] - Custom storage backend; used as is,\n * also on the server\n * @property {string} [key='coherent-state'] - Storage key prefix\n * @property {boolean} [debounce=true] - Debounce state saves\n * @property {number} [debounceDelay=300] - Debounce delay in ms\n * @property {Function} [serialize=JSON.stringify] - Serialization function\n * @property {Function} [deserialize=JSON.parse] - Deserialization function\n * @property {Array<string>} [include] - Keys to include (whitelist)\n * @property {Array<string>} [exclude] - Keys to exclude (blacklist)\n * @property {boolean} [encrypt=false] - Obfuscate stored data with\n * `encryptionKey` (XOR \u2014 not encryption; anyone with the key, which ships\n * to the browser, can read it)\n * @property {string} [encryptionKey] - Obfuscation key; required with `encrypt`\n * @property {Function} [onSave] - Callback when state is saved\n * @property {Function} [onLoad] - Callback when state is loaded\n * @property {Function} [onError] - Error callback (load, save or storage failures)\n * @property {boolean} [versioning=false] - Enable versioning\n * @property {string} [version='1.0.0'] - Current version\n * @property {Function} [migrate] - Migration function for version changes\n * @property {number} [ttl] - Time to live in milliseconds\n * @property {boolean} [crossTab=false] - Enable cross-tab synchronization\n * @property {string} [dbName='coherent-db'] - IndexedDB database name (`storage: 'indexedDB'`)\n * @property {string} [storeName='state'] - IndexedDB object store name (`storage: 'indexedDB'`)\n */\n\n/**\n * Storage adapter interface: async get/set/remove/clear. `set` resolves to\n * `true` once the value is stored and rejects (or resolves `false`) when it\n * could not be.\n * @interface StorageAdapter\n */\n\n/**\n * Web Storage adapter (localStorage / sessionStorage). Storage errors, such as\n * QuotaExceededError, propagate to the caller.\n */\nclass WebStorageAdapter {\n constructor(storageName) {\n this.storageName = storageName;\n this.available = typeof globalThis[storageName] !== 'undefined' && globalThis[storageName] !== null;\n }\n\n get storage() {\n return globalThis[this.storageName];\n }\n\n async get(key) {\n if (!this.available) return null;\n return this.storage.getItem(key);\n }\n\n async set(key, value) {\n if (!this.available) return false;\n this.storage.setItem(key, value);\n return true;\n }\n\n async remove(key) {\n if (!this.available) return false;\n this.storage.removeItem(key);\n return true;\n }\n\n async clear() {\n if (!this.available) return false;\n this.storage.clear();\n return true;\n }\n}\n\n/**\n * LocalStorage adapter\n */\nclass LocalStorageAdapter extends WebStorageAdapter {\n constructor() {\n super('localStorage');\n }\n}\n\n/**\n * SessionStorage adapter\n */\nclass SessionStorageAdapter extends WebStorageAdapter {\n constructor() {\n super('sessionStorage');\n }\n}\n\n/**\n * IndexedDB adapter: values are kept in the object store `storeName` of the\n * database `dbName`.\n */\nclass IndexedDBAdapter {\n constructor(dbName = 'coherent-db', storeName = 'state') {\n this.dbName = dbName;\n this.storeName = storeName;\n this.available = typeof indexedDB !== 'undefined';\n this.db = null;\n this.opening = null;\n }\n\n /**\n * Open the database, creating the store in an upgrade. Without `version`,\n * opens the current version (creating version 1 for a new database).\n */\n open(version) {\n return new Promise((resolve, reject) => {\n const request = version === undefined\n ? indexedDB.open(this.dbName)\n : indexedDB.open(this.dbName, version);\n\n request.onerror = () => {\n console.error('IndexedDB open error:', request.error);\n reject(request.error);\n };\n\n request.onsuccess = () => {\n resolve(request.result);\n };\n\n request.onupgradeneeded = (event) => {\n const db = event.target.result;\n if (!db.objectStoreNames.contains(this.storeName)) {\n db.createObjectStore(this.storeName);\n }\n };\n });\n }\n\n async init() {\n if (!this.available) return false;\n if (this.db) return true;\n\n this.opening ??= (async () => {\n let db = await this.open();\n // The database already exists without this store (another store with\n // the same dbName created it): add the store in a version upgrade.\n if (!db.objectStoreNames.contains(this.storeName)) {\n const version = db.version + 1;\n db.close();\n db = await this.open(version);\n }\n // Let another store's upgrade proceed; reopen on the next access.\n db.onversionchange = () => {\n db.close();\n if (this.db === db) this.db = null;\n };\n this.db = db;\n return true;\n })().finally(() => {\n this.opening = null;\n });\n\n return this.opening;\n }\n\n async get(key) {\n if (!this.available) return null;\n await this.init();\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([this.storeName], 'readonly');\n const store = transaction.objectStore(this.storeName);\n const request = store.get(key);\n\n request.onerror = () => {\n console.error('IndexedDB get error:', request.error);\n reject(request.error);\n };\n\n request.onsuccess = () => {\n resolve(request.result || null);\n };\n });\n }\n\n async set(key, value) {\n if (!this.available) return false;\n await this.init();\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([this.storeName], 'readwrite');\n const store = transaction.objectStore(this.storeName);\n const request = store.put(value, key);\n\n request.onerror = () => {\n console.error('IndexedDB set error:', request.error);\n reject(request.error);\n };\n\n request.onsuccess = () => {\n resolve(true);\n };\n });\n }\n\n async remove(key) {\n if (!this.available) return false;\n await this.init();\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([this.storeName], 'readwrite');\n const store = transaction.objectStore(this.storeName);\n const request = store.delete(key);\n\n request.onerror = () => {\n console.error('IndexedDB remove error:', request.error);\n reject(request.error);\n };\n\n request.onsuccess = () => {\n resolve(true);\n };\n });\n }\n\n async clear() {\n if (!this.available) return false;\n await this.init();\n\n return new Promise((resolve, reject) => {\n const transaction = this.db.transaction([this.storeName], 'readwrite');\n const store = transaction.objectStore(this.storeName);\n const request = store.clear();\n\n request.onerror = () => {\n console.error('IndexedDB clear error:', request.error);\n reject(request.error);\n };\n\n request.onsuccess = () => {\n resolve(true);\n };\n });\n }\n}\n\n/**\n * Memory adapter (for testing or fallback)\n */\nclass MemoryAdapter {\n constructor() {\n this.storage = new Map();\n this.available = true;\n }\n\n async get(key) {\n return this.storage.get(key) || null;\n }\n\n async set(key, value) {\n this.storage.set(key, value);\n return true;\n }\n\n async remove(key) {\n return this.storage.delete(key);\n }\n\n async clear() {\n this.storage.clear();\n return true;\n }\n}\n\n\n/**\n * Stand-in for browser storage on the server. Web Storage there (Node's\n * `--experimental-webstorage`, on by default in newer releases) is shared by\n * every request in the process, so one visitor's state would be restored into\n * another's render. Nothing is read or written.\n */\nclass ServerAdapter {\n constructor() {\n this.available = false;\n }\n\n async get() {\n return null;\n }\n\n async set() {\n return false;\n }\n\n async remove() {\n return false;\n }\n\n async clear() {\n return false;\n }\n}\n\nfunction toBase64(bytes) {\n let binary = '';\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n }\n return btoa(binary);\n}\n\nfunction fromBase64(encoded) {\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/**\n * XOR obfuscation of the stored payload (option `encrypt`).\n *\n * This is NOT encryption: the key has to ship to the browser, and XOR with a\n * repeating key is trivially reversible. It only keeps casual readers of the\n * storage from seeing plain JSON. Do not store secrets in browser storage.\n *\n * Works on UTF-8 bytes, so any Unicode text round-trips.\n */\nclass XorObfuscation {\n constructor(key) {\n if (typeof key !== 'string' || key.length === 0) {\n throw new TypeError(\n 'createPersistentState: `encrypt: true` requires a non-empty `encryptionKey`. ' +\n 'It is XOR obfuscation, not encryption; there is no default key.'\n );\n }\n this.keyBytes = new globalThis.TextEncoder().encode(key);\n }\n\n xor(bytes) {\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] ^= this.keyBytes[i % this.keyBytes.length];\n }\n return bytes;\n }\n\n encode(text) {\n return toBase64(this.xor(new globalThis.TextEncoder().encode(text)));\n }\n\n decode(encoded) {\n return new globalThis.TextDecoder().decode(this.xor(fromBase64(encoded)));\n }\n}\n\n/**\n * Create storage adapter\n * @param {StorageType} type - Storage type\n * @param {Pick<PersistenceOptions, 'dbName'|'storeName'>} [options] - IndexedDB\n * database and object store names\n * @returns {StorageAdapter} Storage adapter instance\n */\nfunction createStorageAdapter(type, options = {}) {\n switch (type) {\n case 'localStorage':\n return new LocalStorageAdapter();\n case 'sessionStorage':\n return new SessionStorageAdapter();\n case 'indexedDB':\n return new IndexedDBAdapter(options.dbName ?? undefined, options.storeName ?? undefined);\n case 'memory':\n return new MemoryAdapter();\n default:\n return new LocalStorageAdapter();\n }\n}\n\nfunction createInstanceId() {\n const cryptoApi = globalThis.crypto;\n if (cryptoApi && typeof cryptoApi.randomUUID === 'function') {\n return cryptoApi.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n\n/**\n * Create persistent state manager\n *\n * Unless the backend is `'memory'`, stored state is restored on creation;\n * `ready` settles once that is done. Keys set before then keep the value they\n * were set to rather than the stored one.\n *\n * On the server (no `window`), browser storage backends read and write\n * nothing and cross-tab sync is off; pass an explicit `adapter` to persist\n * there.\n *\n * @param {Object} initialState - Initial state\n * @param {PersistenceOptions} options - Persistence options\n * @returns {Object} Persistent state manager\n */\nexport function createPersistentState(initialState = {}, options = {}) {\n const opts = {\n storage: 'localStorage',\n adapter: null,\n key: 'coherent-state',\n debounce: true,\n debounceDelay: 300,\n serialize: JSON.stringify,\n deserialize: JSON.parse,\n include: null,\n exclude: null,\n encrypt: false,\n encryptionKey: null,\n onSave: null,\n onLoad: null,\n onError: null,\n versioning: false,\n version: '1.0.0',\n migrate: null,\n ttl: null,\n crossTab: false,\n ...options\n };\n\n const onServer = typeof window === 'undefined';\n const obfuscation = opts.encrypt ? new XorObfuscation(opts.encryptionKey) : null;\n\n let adapter;\n if (opts.adapter) {\n adapter = opts.adapter;\n } else if (onServer && opts.storage !== 'memory') {\n adapter = new ServerAdapter();\n } else {\n adapter = createStorageAdapter(opts.storage, opts);\n }\n\n const instanceId = createInstanceId();\n let state = { ...initialState };\n let saveTimeout = null;\n let destroyed = false;\n const listeners = new Set();\n\n // Keys written while the initial restore is in flight; it must not\n // overwrite them with the older stored values.\n let initialRestorePending = false;\n const touchedKeys = new Set();\n\n function reportError(error) {\n if (opts.onError) {\n opts.onError(error);\n } else {\n console.error('State persistence error:', error);\n }\n }\n\n /**\n * Filter state keys based on include/exclude options\n * @param {Object} obj - State object\n * @returns {Object} Filtered state\n */\n function filterKeys(obj) {\n if (!obj || typeof obj !== 'object') return obj;\n\n // If include list is provided, only include those keys\n if (opts.include && Array.isArray(opts.include)) {\n const filtered = {};\n opts.include.forEach(key => {\n if (key in obj) {\n filtered[key] = obj[key];\n }\n });\n return filtered;\n }\n\n // If exclude list is provided, exclude those keys\n if (opts.exclude && Array.isArray(opts.exclude)) {\n const filtered = { ...obj };\n opts.exclude.forEach(key => {\n delete filtered[key];\n });\n return filtered;\n }\n\n return obj;\n }\n\n // Cross-tab synchronisation: one channel per storage key, so unrelated\n // stores never merge each other's state, and messages carry the sender's\n // id so a store never applies its own update.\n let channel = null;\n if (opts.crossTab && !onServer && typeof BroadcastChannel !== 'undefined') {\n channel = new BroadcastChannel(`coherent-state-sync:${opts.key}`);\n channel.onmessage = (event) => {\n const message = event.data;\n if (destroyed || !message || message.type !== 'state-update' || message.source === instanceId) {\n return;\n }\n const oldState = { ...state };\n state = { ...state, ...message.state };\n notifyListeners(oldState, state);\n };\n // Node: do not keep the process alive for this channel\n channel.unref?.();\n }\n\n function broadcast(filteredState) {\n if (!channel) return;\n try {\n channel.postMessage({ type: 'state-update', source: instanceId, state: filteredState });\n } catch (error) {\n reportError(error);\n }\n }\n\n /**\n * Write the current state now.\n * @returns {Promise<boolean>} Whether it was stored\n */\n async function write() {\n if (adapter.available === false) {\n return false;\n }\n\n try {\n const filteredState = filterKeys(state);\n const serialized = opts.serialize(filteredState);\n\n // Add metadata\n const data = {\n state: serialized,\n version: opts.version,\n timestamp: Date.now(),\n ttl: opts.ttl\n };\n\n let dataString = JSON.stringify(data);\n\n if (obfuscation) {\n dataString = obfuscation.encode(dataString);\n }\n\n const stored = await adapter.set(opts.key, dataString);\n if (stored === false) {\n throw new Error(`State \"${opts.key}\" could not be written to storage`);\n }\n\n // Call onSave callback\n if (opts.onSave) {\n opts.onSave(filteredState);\n }\n\n broadcast(filteredState);\n return true;\n } catch (error) {\n reportError(error);\n return false;\n }\n }\n\n /**\n * Save state to storage\n * @param {boolean} immediate - Save immediately without debounce\n * @returns {Promise<boolean>|undefined} Whether it was stored (immediate saves)\n */\n function save(immediate = false) {\n if (destroyed) {\n return Promise.resolve(false);\n }\n\n if (opts.debounce && !immediate) {\n clearTimeout(saveTimeout);\n saveTimeout = setTimeout(() => {\n saveTimeout = null;\n write();\n }, opts.debounceDelay);\n return undefined;\n }\n\n clearTimeout(saveTimeout);\n saveTimeout = null;\n return write();\n }\n\n /**\n * Load state from storage\n */\n async function load() {\n try {\n let dataString = await adapter.get(opts.key);\n if (!dataString) return null;\n\n if (obfuscation) {\n dataString = obfuscation.decode(dataString);\n }\n\n const data = JSON.parse(dataString);\n\n // Check TTL\n if (data.ttl && data.timestamp) {\n const age = Date.now() - data.timestamp;\n if (age > data.ttl) {\n await adapter.remove(opts.key);\n return null;\n }\n }\n\n // Check version and migrate if needed\n if (opts.versioning && data.version !== opts.version) {\n if (opts.migrate) {\n const migrated = opts.migrate(data.state, data.version, opts.version);\n return opts.deserialize(migrated);\n }\n return null;\n }\n\n const loadedState = opts.deserialize(data.state);\n\n // Call onLoad callback\n if (opts.onLoad) {\n opts.onLoad(loadedState);\n }\n\n return loadedState;\n } catch (error) {\n reportError(error);\n return null;\n }\n }\n\n /**\n * Subscribe to state changes\n * @param {Function} listener - Change listener\n * @returns {Function} Unsubscribe function\n */\n function subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n\n /**\n * Notify listeners of state changes\n * @param {Object} oldState - Previous state\n * @param {Object} newState - New state\n */\n function notifyListeners(oldState, newState) {\n listeners.forEach(listener => {\n try {\n listener(newState, oldState);\n } catch (error) {\n console.error('Listener error:', error);\n }\n });\n }\n\n /**\n * Merge loaded state, optionally leaving keys touched since creation alone.\n * @returns {boolean} Whether stored state was found\n */\n function applyLoaded(loaded, skipTouched) {\n if (!loaded || typeof loaded !== 'object') {\n return false;\n }\n\n // Object.fromEntries defines keys as own data properties, so a stored\n // \"__proto__\" key cannot reach a prototype.\n const updates = Object.fromEntries(\n Object.entries(loaded).filter(([key]) => !skipTouched || !touchedKeys.has(key))\n );\n\n if (Object.keys(updates).length > 0) {\n const oldState = { ...state };\n state = { ...state, ...updates };\n notifyListeners(oldState, state);\n }\n return true;\n }\n\n /**\n * Get current state\n * @param {string} [key] - State key\n * @returns {*} State value or entire state\n */\n function getState(key) {\n return key ? state[key] : { ...state };\n }\n\n /**\n * Set state\n * @param {Object|Function} updates - State updates or updater function\n * @param {boolean} persist - Persist to storage\n */\n function setState(updates, persist = true) {\n const oldState = { ...state };\n\n if (typeof updates === 'function') {\n updates = updates(oldState);\n }\n\n if (initialRestorePending && updates && typeof updates === 'object') {\n for (const key of Object.keys(updates)) touchedKeys.add(key);\n }\n\n state = { ...state, ...updates };\n\n notifyListeners(oldState, state);\n\n if (persist) {\n save();\n }\n }\n\n /**\n * Reset state to initial values\n * @param {boolean} persist - Persist to storage\n */\n function resetState(persist = true) {\n const oldState = { ...state };\n\n if (initialRestorePending) {\n for (const key of Object.keys(oldState)) touchedKeys.add(key);\n for (const key of Object.keys(initialState)) touchedKeys.add(key);\n }\n\n state = { ...initialState };\n notifyListeners(oldState, state);\n\n if (persist) {\n save(true);\n }\n }\n\n /**\n * Clear persisted state\n */\n async function clearStorage() {\n try {\n await adapter.remove(opts.key);\n } catch (error) {\n reportError(error);\n }\n }\n\n /**\n * Manually trigger persistence\n * @returns {Promise<boolean>} Whether it was stored\n */\n async function persist() {\n return save(true);\n }\n\n /**\n * Restore state from storage\n * @returns {Promise<boolean>} Whether stored state was found\n */\n async function restore() {\n return applyLoaded(await load(), false);\n }\n\n /**\n * Stop syncing and saving: flushes a pending debounced save, closes the\n * cross-tab channel and drops listeners.\n * @returns {Promise<void>}\n */\n async function destroy() {\n if (destroyed) return;\n const pending = saveTimeout !== null;\n clearTimeout(saveTimeout);\n saveTimeout = null;\n if (pending) {\n await write();\n }\n destroyed = true;\n channel?.close();\n channel = null;\n listeners.clear();\n }\n\n // Auto-restore on creation\n let ready;\n if (opts.storage !== 'memory' || opts.adapter) {\n initialRestorePending = true;\n ready = load().then((loaded) => {\n initialRestorePending = false;\n if (destroyed) return false;\n const restored = applyLoaded(loaded, true);\n // Keys set meanwhile were saved without the restored ones; save the merge\n if (restored && touchedKeys.size > 0) save();\n touchedKeys.clear();\n return restored;\n });\n } else {\n ready = Promise.resolve(false);\n }\n\n return {\n getState,\n setState,\n resetState,\n subscribe,\n persist,\n restore,\n clearStorage,\n load,\n save: () => save(true),\n destroy,\n /** Settles once the automatic restore on creation is done */\n ready,\n get adapter() {\n return adapter;\n }\n };\n}\n\n/**\n * Create persistent state with localStorage\n * @param {Object} initialState - Initial state\n * @param {string} key - Storage key\n * @param {Partial<PersistenceOptions>} options - Additional options\n * @returns {Object} Persistent state manager\n */\nexport function withLocalStorage(initialState = {}, key = 'coherent-state', options = {}) {\n return createPersistentState(initialState, {\n ...options,\n storage: 'localStorage',\n key\n });\n}\n\n/**\n * Create persistent state with sessionStorage\n * @param {Object} initialState - Initial state\n * @param {string} key - Storage key\n * @param {Partial<PersistenceOptions>} options - Additional options\n * @returns {Object} Persistent state manager\n */\nexport function withSessionStorage(initialState = {}, key = 'coherent-state', options = {}) {\n return createPersistentState(initialState, {\n ...options,\n storage: 'sessionStorage',\n key\n });\n}\n\n/**\n * Create persistent state with IndexedDB\n * @param {Object} initialState - Initial state\n * @param {string} key - Storage key\n * @param {Partial<PersistenceOptions>} options - Additional options\n * @returns {Object} Persistent state manager\n */\nexport function withIndexedDB(initialState = {}, key = 'coherent-state', options = {}) {\n return createPersistentState(initialState, {\n ...options,\n storage: 'indexedDB',\n key\n });\n}\n\nexport default {\n createPersistentState,\n withLocalStorage,\n withSessionStorage,\n withIndexedDB,\n createStorageAdapter\n};\n", "/**\n * @fileoverview State Validation for Coherent.js\n * Provides JSON Schema validation and custom validators for state management\n * @module @coherent.js/core/state/state-validation\n */\n\n/**\n * Email shape check: a local part, then a dotted domain.\n *\n * Domain labels use `[^\\s@.]` rather than `[^\\s@]` so that the literal dot\n * separators are the only thing that can match a dot. Allowing `[^\\s@]+` on\n * both sides of `\\.` makes the split ambiguous, and a non-matching subject\n * with many dots (\"a@\" + \"a.\" * n + \" \") then costs O(n\u00B2) backtracking \u2014\n * CodeQL js/polynomial-redos.\n *\n * @private\n */\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@.]+(?:\\.[^\\s@.]+)+$/;\n\n/**\n * Longest address RFC 5321 permits, used to bound work before matching.\n * @private\n */\nconst EMAIL_MAX_LENGTH = 254;\n\n/**\n * Test whether a value has the shape of an email address.\n * @private\n * @param {unknown} value - Value to check\n * @returns {boolean} True if the value looks like an email address\n */\nfunction isEmailShaped(value) {\n return (\n typeof value === 'string' &&\n value.length <= EMAIL_MAX_LENGTH &&\n EMAIL_PATTERN.test(value)\n );\n}\n\n\n/**\n * @typedef {Object} ValidationOptions\n * @property {Object} [schema] - JSON Schema for validation\n * @property {Object<string, Function>} [validators] - Custom validator functions\n * @property {boolean} [strict=false] - Strict mode (throw on validation errors)\n * @property {boolean} [coerce=false] - Coerce types to match schema\n * @property {Function} [onError] - Validation error callback\n * @property {boolean} [validateOnSet=true] - Validate on state updates\n * @property {boolean} [validateOnGet=false] - Validate on state reads\n * @property {Array<string>} [required] - Required fields\n * @property {boolean} [allowUnknown=true] - Allow unknown properties\n */\n\n/**\n * @typedef {Object} ValidationResult\n * @property {boolean} valid - Whether validation passed\n * @property {Array<ValidationError>} errors - Array of validation errors\n * @property {*} value - Validated/coerced value\n */\n\n/**\n * @typedef {Object} ValidationError\n * @property {string} path - Property path that failed validation\n * @property {string} message - Error message\n * @property {string} type - Error type\n * @property {*} value - The invalid value\n * @property {*} expected - Expected value/type\n */\n\n/**\n * Whether a value has a JSON Schema type. `object` excludes null and arrays;\n * `number` excludes NaN, which JSON cannot represent.\n * @private\n */\nfunction matchesType(value, type) {\n switch (type) {\n case 'array':\n return Array.isArray(value);\n case 'null':\n return value === null;\n case 'object':\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'number':\n return typeof value === 'number' && !Number.isNaN(value);\n default:\n return typeof value === type;\n }\n}\n\n/** @private */\nfunction describeValue(value) {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n if (typeof value === 'string') return JSON.stringify(value);\n return typeof value === 'object' ? 'object' : String(value);\n}\n\n/**\n * Coerce a value to a JSON Schema type, refusing conversions that would\n * invent data: `Boolean('false')` is true, `Number('')` is 0 and\n * `String({})` is \"[object Object]\", so none of those are accepted.\n * @private\n * @returns {{ ok: boolean, value?: * }}\n */\nfunction coerceTo(value, type) {\n switch (type) {\n case 'string':\n if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {\n return { ok: !Number.isNaN(value), value: String(value) };\n }\n return { ok: false };\n case 'number':\n case 'integer': {\n let number;\n if (typeof value === 'string' && value.trim() !== '') {\n number = Number(value);\n } else if (typeof value === 'boolean') {\n number = value ? 1 : 0;\n } else {\n return { ok: false };\n }\n const valid = type === 'integer' ? Number.isInteger(number) : !Number.isNaN(number);\n return valid ? { ok: true, value: number } : { ok: false };\n }\n case 'boolean':\n if (typeof value === 'string') {\n const normalized = value.trim().toLowerCase();\n if (normalized === 'true' || normalized === '1') return { ok: true, value: true };\n if (normalized === 'false' || normalized === '0' || normalized === '') return { ok: true, value: false };\n return { ok: false };\n }\n if (value === 1 || value === 0) return { ok: true, value: value === 1 };\n return { ok: false };\n default:\n return { ok: false };\n }\n}\n\n/**\n * Simple JSON Schema validator\n */\nclass SchemaValidator {\n constructor(schema, options = {}) {\n this.schema = schema;\n this.options = {\n coerce: false,\n allowUnknown: true,\n ...options\n };\n }\n\n /**\n * Validate value against schema\n * @param {*} value - Value to validate\n * @param {Object} schema - Schema to validate against\n * @param {string} path - Current path in object\n * @returns {ValidationResult} Validation result\n */\n validate(value, schema = this.schema, path = '') {\n const errors = [];\n let coercedValue = value;\n\n // Type validation. A value of the wrong type that could not be coerced\n // gets no further checks: they assume the declared type.\n if (schema.type) {\n const typeResult = this.validateType(value, schema.type, path);\n if (!typeResult.valid) {\n return { valid: false, errors: typeResult.errors, value };\n }\n coercedValue = typeResult.value;\n }\n\n // Enum validation\n if (schema.enum) {\n const enumResult = this.validateEnum(coercedValue, schema.enum, path);\n if (!enumResult.valid) {\n errors.push(...enumResult.errors);\n }\n }\n\n // String validations\n if (schema.type === 'string') {\n const stringResult = this.validateString(coercedValue, schema, path);\n if (!stringResult.valid) {\n errors.push(...stringResult.errors);\n }\n }\n\n // Number validations\n if (schema.type === 'number' || schema.type === 'integer') {\n const numberResult = this.validateNumber(coercedValue, schema, path);\n if (!numberResult.valid) {\n errors.push(...numberResult.errors);\n }\n }\n\n // Array validations\n if (schema.type === 'array') {\n const arrayResult = this.validateArray(coercedValue, schema, path);\n if (!arrayResult.valid) {\n errors.push(...arrayResult.errors);\n }\n coercedValue = arrayResult.value;\n }\n\n // Object validations\n if (schema.type === 'object') {\n const objectResult = this.validateObject(coercedValue, schema, path);\n if (!objectResult.valid) {\n errors.push(...objectResult.errors);\n }\n coercedValue = objectResult.value;\n }\n\n // Custom validation function\n if (schema.validate && typeof schema.validate === 'function') {\n const customResult = schema.validate(coercedValue);\n if (customResult !== true) {\n errors.push({\n path,\n message: typeof customResult === 'string' ? customResult : 'Custom validation failed',\n type: 'custom',\n value: coercedValue\n });\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n value: coercedValue\n };\n }\n\n validateType(value, type, path) {\n const actualType = Array.isArray(value) ? 'array' : typeof value;\n const errors = [];\n let coercedValue = value;\n\n // Support array of types\n const types = Array.isArray(type) ? type : [type];\n\n const isValid = types.some(t => matchesType(value, t));\n\n if (!isValid) {\n if (this.options.coerce) {\n // Try to coerce to the first declared type\n const primaryType = types[0];\n const coerced = coerceTo(value, primaryType);\n if (coerced.ok) {\n coercedValue = coerced.value;\n } else {\n errors.push({\n path,\n message: `Cannot coerce ${describeValue(value)} to ${primaryType}`,\n type: 'type',\n value,\n expected: primaryType\n });\n }\n } else {\n errors.push({\n path,\n message: `Expected type ${types.join(' or ')}, got ${actualType}`,\n type: 'type',\n value,\n expected: type\n });\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n value: coercedValue\n };\n }\n\n validateEnum(value, enumValues, path) {\n const errors = [];\n if (!enumValues.includes(value)) {\n errors.push({\n path,\n message: `Value must be one of: ${enumValues.join(', ')}`,\n type: 'enum',\n value,\n expected: enumValues\n });\n }\n return { valid: errors.length === 0, errors };\n }\n\n validateString(value, schema, path) {\n const errors = [];\n\n if (schema.minLength !== undefined && value.length < schema.minLength) {\n errors.push({\n path,\n message: `String length must be >= ${schema.minLength}`,\n type: 'minLength',\n value\n });\n }\n\n if (schema.maxLength !== undefined && value.length > schema.maxLength) {\n errors.push({\n path,\n message: `String length must be <= ${schema.maxLength}`,\n type: 'maxLength',\n value\n });\n }\n\n if (schema.pattern) {\n const regex = new RegExp(schema.pattern);\n if (!regex.test(value)) {\n errors.push({\n path,\n message: `String does not match pattern: ${schema.pattern}`,\n type: 'pattern',\n value\n });\n }\n }\n\n if (schema.format) {\n const formatResult = this.validateFormat(value, schema.format, path);\n if (!formatResult.valid) {\n errors.push(...formatResult.errors);\n }\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n validateFormat(value, format, path) {\n const errors = [];\n const formats = {\n email: EMAIL_PATTERN,\n url: /^https?:\\/\\/.+/,\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n date: /^\\d{4}-\\d{2}-\\d{2}$/,\n 'date-time': /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/\n };\n\n if (formats[format] && !formats[format].test(value)) {\n errors.push({\n path,\n message: `String does not match format: ${format}`,\n type: 'format',\n value,\n expected: format\n });\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n validateNumber(value, schema, path) {\n const errors = [];\n\n if (schema.minimum !== undefined && value < schema.minimum) {\n errors.push({\n path,\n message: `Number must be >= ${schema.minimum}`,\n type: 'minimum',\n value\n });\n }\n\n if (schema.maximum !== undefined && value > schema.maximum) {\n errors.push({\n path,\n message: `Number must be <= ${schema.maximum}`,\n type: 'maximum',\n value\n });\n }\n\n if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) {\n errors.push({\n path,\n message: `Number must be > ${schema.exclusiveMinimum}`,\n type: 'exclusiveMinimum',\n value\n });\n }\n\n if (schema.exclusiveMaximum !== undefined && value >= schema.exclusiveMaximum) {\n errors.push({\n path,\n message: `Number must be < ${schema.exclusiveMaximum}`,\n type: 'exclusiveMaximum',\n value\n });\n }\n\n if (schema.multipleOf !== undefined && value % schema.multipleOf !== 0) {\n errors.push({\n path,\n message: `Number must be multiple of ${schema.multipleOf}`,\n type: 'multipleOf',\n value\n });\n }\n\n return { valid: errors.length === 0, errors };\n }\n\n validateArray(value, schema, path) {\n const errors = [];\n const coercedValue = [...value];\n\n if (schema.minItems !== undefined && value.length < schema.minItems) {\n errors.push({\n path,\n message: `Array must have at least ${schema.minItems} items`,\n type: 'minItems',\n value\n });\n }\n\n if (schema.maxItems !== undefined && value.length > schema.maxItems) {\n errors.push({\n path,\n message: `Array must have at most ${schema.maxItems} items`,\n type: 'maxItems',\n value\n });\n }\n\n if (schema.uniqueItems) {\n const seen = new Set();\n const duplicates = [];\n value.forEach((item, index) => {\n const key = JSON.stringify(item);\n if (seen.has(key)) {\n duplicates.push(index);\n }\n seen.add(key);\n });\n if (duplicates.length > 0) {\n errors.push({\n path,\n message: 'Array items must be unique',\n type: 'uniqueItems',\n value\n });\n }\n }\n\n // Validate items\n if (schema.items) {\n value.forEach((item, index) => {\n const itemPath = `${path}[${index}]`;\n const itemResult = this.validate(item, schema.items, itemPath);\n if (!itemResult.valid) {\n errors.push(...itemResult.errors);\n }\n if (this.options.coerce) {\n coercedValue[index] = itemResult.value;\n }\n });\n }\n\n return {\n valid: errors.length === 0,\n errors,\n value: coercedValue\n };\n }\n\n validateObject(value, schema, path) {\n const errors = [];\n const coercedValue = { ...value };\n\n // Required properties\n if (schema.required) {\n schema.required.forEach(prop => {\n if (!(prop in value)) {\n errors.push({\n path: path ? `${path}.${prop}` : prop,\n message: `Required property \"${prop}\" is missing`,\n type: 'required',\n value: undefined\n });\n }\n });\n }\n\n // Validate properties\n if (schema.properties) {\n Object.entries(schema.properties).forEach(([prop, propSchema]) => {\n if (prop in value) {\n const propPath = path ? `${path}.${prop}` : prop;\n const propResult = this.validate(value[prop], propSchema, propPath);\n if (!propResult.valid) {\n errors.push(...propResult.errors);\n }\n if (this.options.coerce) {\n coercedValue[prop] = propResult.value;\n }\n }\n });\n }\n\n // Additional properties: rejected by the schema's own\n // `additionalProperties: false`, or for any object schema that lists its\n // properties when the validator runs with `allowUnknown: false`\n if (schema.additionalProperties === false || (!this.options.allowUnknown && schema.properties)) {\n const allowedProps = new Set(Object.keys(schema.properties || {}));\n Object.keys(value).forEach(prop => {\n if (!allowedProps.has(prop)) {\n errors.push({\n path: path ? `${path}.${prop}` : prop,\n message: `Unknown property \"${prop}\"`,\n type: 'additionalProperties',\n value: value[prop]\n });\n }\n });\n }\n\n // Min/max properties\n const propCount = Object.keys(value).length;\n if (schema.minProperties !== undefined && propCount < schema.minProperties) {\n errors.push({\n path,\n message: `Object must have at least ${schema.minProperties} properties`,\n type: 'minProperties',\n value\n });\n }\n\n if (schema.maxProperties !== undefined && propCount > schema.maxProperties) {\n errors.push({\n path,\n message: `Object must have at most ${schema.maxProperties} properties`,\n type: 'maxProperties',\n value\n });\n }\n\n return {\n valid: errors.length === 0,\n errors,\n value: coercedValue\n };\n }\n}\n\n/**\n * Create validated state manager\n * @param {Object} initialState - Initial state\n * @param {ValidationOptions} options - Validation options\n * @returns {Object} Validated state manager\n */\nexport function createValidatedState(initialState = {}, options = {}) {\n const opts = {\n schema: null,\n validators: {},\n strict: false,\n coerce: false,\n onError: null,\n validateOnSet: true,\n validateOnGet: false,\n required: [],\n allowUnknown: true,\n ...options\n };\n\n const schemaValidator = opts.schema ? new SchemaValidator(opts.schema, {\n coerce: opts.coerce,\n allowUnknown: opts.allowUnknown\n }) : null;\n\n let state = { ...initialState };\n const listeners = new Set();\n const validationErrors = new Map();\n\n /**\n * Validate state\n * @param {Object} value - State to validate\n * @param {string} key - State key (for partial validation)\n * @returns {ValidationResult} Validation result\n */\n function validateState(value, key = null) {\n const errors = [];\n let validatedValue = value;\n\n // JSON Schema validation\n if (schemaValidator) {\n const schema = key && opts.schema.properties\n ? opts.schema.properties[key]\n : opts.schema;\n\n const result = schemaValidator.validate(value, schema, key || '');\n if (!result.valid) {\n errors.push(...result.errors);\n }\n validatedValue = result.value;\n }\n\n // Custom validators\n if (key && opts.validators[key]) {\n const validator = opts.validators[key];\n const result = validator(value);\n if (result !== true) {\n errors.push({\n path: key,\n message: typeof result === 'string' ? result : 'Validation failed',\n type: 'custom',\n value\n });\n }\n } else if (!key) {\n // Run custom validators for all fields when validating full state\n Object.entries(opts.validators).forEach(([fieldKey, validator]) => {\n if (fieldKey in value) {\n const result = validator(value[fieldKey]);\n if (result !== true) {\n errors.push({\n path: fieldKey,\n message: typeof result === 'string' ? result : 'Validation failed',\n type: 'custom',\n value: value[fieldKey]\n });\n }\n }\n });\n }\n\n // Required fields\n if (opts.required.length > 0 && !key) {\n opts.required.forEach(field => {\n if (!(field in value)) {\n errors.push({\n path: field,\n message: `Required field \"${field}\" is missing`,\n type: 'required',\n value: undefined\n });\n }\n });\n }\n\n return {\n valid: errors.length === 0,\n errors,\n value: validatedValue\n };\n }\n\n /**\n * Get state\n * @param {string} key - State key\n * @returns {*} State value\n */\n function getState(key) {\n const value = key ? state[key] : { ...state };\n\n if (opts.validateOnGet) {\n const result = validateState(value, key);\n if (!result.valid) {\n validationErrors.set(key || '__root__', result.errors);\n if (opts.onError) {\n opts.onError(result.errors);\n }\n }\n }\n\n return value;\n }\n\n /**\n * Set state\n * @param {Object|Function} updates - State updates\n * @throws {Error} If validation fails in strict mode\n */\n function setState(updates) {\n const oldState = { ...state };\n\n if (typeof updates === 'function') {\n updates = updates(oldState);\n }\n\n // Create the new full state for validation\n const newState = { ...state, ...updates };\n\n // Validate before setting\n if (opts.validateOnSet) {\n const result = validateState(newState);\n\n if (!result.valid) {\n validationErrors.set('__root__', result.errors);\n\n if (opts.onError) {\n opts.onError(result.errors);\n }\n\n if (opts.strict) {\n const error = new Error('Validation failed');\n error.validationErrors = result.errors;\n throw error;\n }\n\n // Don't update state if validation fails in non-strict mode\n return;\n }\n\n // Use coerced value if coercion is enabled\n if (opts.coerce) {\n const updatedKeys = Object.keys(updates);\n const newUpdates = {};\n updatedKeys.forEach(key => {\n if (result.value[key] !== state[key]) {\n newUpdates[key] = result.value[key];\n }\n });\n updates = newUpdates;\n }\n\n // Clear errors on successful validation\n validationErrors.clear();\n }\n\n state = { ...state, ...updates };\n\n // Notify listeners\n listeners.forEach(listener => {\n try {\n listener(state, oldState);\n } catch (error) {\n console.error('Listener error:', error);\n }\n });\n }\n\n /**\n * Subscribe to state changes\n * @param {Function} listener - Change listener\n * @returns {Function} Unsubscribe function\n */\n function subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n }\n\n /**\n * Get validation errors\n * @param {string} key - State key\n * @returns {Array<ValidationError>} Validation errors\n */\n function getErrors(key = '__root__') {\n return validationErrors.get(key) || [];\n }\n\n /**\n * Check if state is valid\n * @returns {boolean} Whether state is valid\n */\n function isValid() {\n const result = validateState(state);\n if (!result.valid) {\n validationErrors.set('__root__', result.errors);\n }\n return result.valid;\n }\n\n /**\n * Validate specific field\n * @param {string} key - Field key\n * @param {*} value - Field value\n * @returns {ValidationResult} Validation result\n */\n function validateField(key, value) {\n return validateState(value, key);\n }\n\n return {\n getState,\n setState,\n subscribe,\n getErrors,\n isValid,\n validateField,\n validate: () => validateState(state)\n };\n}\n\n/**\n * Common validators\n */\nexport const validators = {\n /**\n * Email validator\n * @param {string} value - Email to validate\n * @returns {boolean|string} True if valid, error message otherwise\n */\n email: (value) => {\n if (typeof value !== 'string') return 'Email must be a string';\n if (!isEmailShaped(value)) return 'Invalid email format';\n return true;\n },\n\n /**\n * URL validator\n * @param {string} value - URL to validate\n * @returns {boolean|string} True if valid, error message otherwise\n */\n url: (value) => {\n if (typeof value !== 'string') return 'URL must be a string';\n try {\n new URL(value);\n return true;\n } catch {\n return 'Invalid URL format';\n }\n },\n\n /**\n * Range validator\n * @param {number} min - Minimum value\n * @param {number} max - Maximum value\n * @returns {Function} Validator function\n */\n range: (min, max) => (value) => {\n if (typeof value !== 'number') return 'Value must be a number';\n if (value < min || value > max) return `Value must be between ${min} and ${max}`;\n return true;\n },\n\n /**\n * Length validator\n * @param {number} min - Minimum length\n * @param {number} max - Maximum length\n * @returns {Function} Validator function\n */\n length: (min, max) => (value) => {\n if (typeof value !== 'string') return 'Value must be a string';\n if (value.length < min || value.length > max) {\n return `Length must be between ${min} and ${max}`;\n }\n return true;\n },\n\n /**\n * Pattern validator\n * @param {RegExp|string} pattern - Pattern to match\n * @returns {Function} Validator function\n */\n pattern: (pattern) => (value) => {\n if (typeof value !== 'string') return 'Value must be a string';\n const regex = typeof pattern === 'string' ? new RegExp(pattern) : pattern;\n if (!regex.test(value)) return `Value does not match pattern: ${pattern}`;\n return true;\n },\n\n /**\n * Required validator\n * @param {*} value - Value to validate\n * @returns {boolean|string} True if valid, error message otherwise\n */\n required: (value) => {\n if (value === undefined || value === null || value === '') {\n return 'Value is required';\n }\n return true;\n }\n};\n\nexport default {\n createValidatedState,\n validators,\n SchemaValidator\n};\n", "/**\n * Enhanced OOP State Patterns for Coherent.js\n *\n * Specialized state classes that encapsulate complex behaviors\n * while maintaining the hybrid FP/OOP architecture\n */\n\nimport { createReactiveState } from './reactive-state.js';\n\n/**\n * Form State - OOP encapsulation for form logic\n */\nexport class FormState {\n constructor(initialValues = {}, options = {}) {\n this._state = createReactiveState({\n values: { ...initialValues },\n errors: {},\n touched: {},\n isSubmitting: false,\n isValid: true\n }, options);\n\n this._validators = {};\n this._options = options;\n }\n\n // OOP methods for form management\n setValue(field, value) {\n this._state.set('values', {\n ...this._state.get('values'),\n [field]: value\n });\n this._validateField(field);\n this._state.set('touched', {\n ...this._state.get('touched'),\n [field]: true\n });\n }\n\n getValue(field) {\n return this._state.get('values')[field];\n }\n\n setError(field, error) {\n this._state.set('errors', {\n ...this._state.get('errors'),\n [field]: error\n });\n this._updateIsValid();\n }\n\n addValidator(field, validator) {\n this._validators[field] = validator;\n }\n\n validateAll() {\n const values = this._state.get('values');\n const errors = {};\n\n Object.entries(this._validators).forEach(([field, validator]) => {\n const error = validator(values[field], values);\n if (error) {\n errors[field] = error;\n }\n });\n\n this._state.set('errors', errors);\n this._updateIsValid();\n return Object.keys(errors).length === 0;\n }\n\n async submit(onSubmit) {\n if (!this.validateAll()) return false;\n\n this._state.set('isSubmitting', true);\n\n try {\n await onSubmit(this._state.get('values'));\n return true;\n } catch (error) {\n this.setError('_form', error.message);\n return false;\n } finally {\n this._state.set('isSubmitting', false);\n }\n }\n\n reset() {\n this._state.set('values', {});\n this._state.set('errors', {});\n this._state.set('touched', {});\n this._state.set('isSubmitting', false);\n this._state.set('isValid', true);\n }\n\n // Watch methods for FP integration\n watchValues(callback) {\n return this._state.watch('values', callback);\n }\n\n watchErrors(callback) {\n return this._state.watch('errors', callback);\n }\n\n watchSubmitting(callback) {\n return this._state.watch('isSubmitting', callback);\n }\n\n // Private methods\n _validateField(field) {\n const value = this.getValue(field);\n const validator = this._validators[field];\n\n if (validator) {\n const error = validator(value, this._state.get('values'));\n this.setError(field, error);\n }\n }\n\n _updateIsValid() {\n const hasErrors = Object.keys(this._state.get('errors')).some(key =>\n this._state.get('errors')[key]\n );\n this._state.set('isValid', !hasErrors);\n }\n}\n\n/**\n * List State - OOP for collection management\n */\nexport class ListState {\n constructor(initialItems = [], options = {}) {\n this._state = createReactiveState({\n items: [...initialItems],\n loading: false,\n error: null,\n filters: {},\n sortBy: null,\n sortOrder: 'asc',\n page: 1,\n pageSize: options.pageSize || 10\n }, options);\n\n this._options = options;\n }\n\n // OOP methods for list operations\n addItem(item) {\n this._state.set('items', [...this._state.get('items'), item]);\n }\n\n removeItem(indexOrPredicate) {\n const items = this._state.get('items');\n let newItems;\n\n if (typeof indexOrPredicate === 'number') {\n newItems = items.filter((_, i) => i !== indexOrPredicate);\n } else {\n newItems = items.filter(item => !indexOrPredicate(item));\n }\n\n this._state.set('items', newItems);\n }\n\n updateItem(indexOrPredicate, updates) {\n const items = this._state.get('items');\n const newItems = items.map((item, i) => {\n if (typeof indexOrPredicate === 'number') {\n return i === indexOrPredicate ? { ...item, ...updates } : item;\n } else {\n return indexOrPredicate(item) ? { ...item, ...updates } : item;\n }\n });\n\n this._state.set('items', newItems);\n }\n\n filter(filters) {\n this._state.set('filters', filters);\n this._state.set('page', 1); // Reset to first page\n }\n\n sort(sortBy, order = 'asc') {\n this._state.set('sortBy', sortBy);\n this._state.set('sortOrder', order);\n }\n\n setPage(page) {\n this._state.set('page', Math.max(1, page));\n }\n\n async load(loader) {\n this._state.set('loading', true);\n this._state.set('error', null);\n\n try {\n const items = await loader(this._state.get('filters'));\n this._state.set('items', items);\n return items;\n } catch (error) {\n this._state.set('error', error.message);\n return [];\n } finally {\n this._state.set('loading', false);\n }\n }\n\n // Computed properties\n get filteredItems() {\n const items = this._state.get('items');\n const filters = this._state.get('filters');\n\n return items.filter(item => {\n return Object.entries(filters).every(([key, value]) => {\n if (!value) return true;\n return String(item[key] || '').toLowerCase().includes(String(value).toLowerCase());\n });\n });\n }\n\n get sortedItems() {\n const items = this.filteredItems;\n const sortBy = this._state.get('sortBy');\n const sortOrder = this._state.get('sortOrder');\n\n if (!sortBy) return items;\n\n return [...items].sort((a, b) => {\n const aVal = a[sortBy];\n const bVal = b[sortBy];\n\n if (aVal === bVal) return 0;\n\n const comparison = aVal < bVal ? -1 : 1;\n return sortOrder === 'desc' ? -comparison : comparison;\n });\n }\n\n get paginatedItems() {\n const items = this.sortedItems;\n const page = this._state.get('page');\n const pageSize = this._state.get('pageSize');\n\n const start = (page - 1) * pageSize;\n const end = start + pageSize;\n\n return items.slice(start, end);\n }\n\n get totalPages() {\n return Math.ceil(this.sortedItems.length / this._state.get('pageSize'));\n }\n\n // Watch methods\n watchItems(callback) {\n return this._state.watch('items', callback);\n }\n\n watchLoading(callback) {\n return this._state.watch('loading', callback);\n }\n}\n\n/**\n * Modal State - OOP for modal/dialog management\n */\nexport class ModalState {\n constructor(_initialState = {}) {\n this._state = createReactiveState({\n isOpen: false,\n data: null,\n loading: false,\n error: null\n });\n\n this._resolvers = new Map();\n this._currentId = 0;\n }\n\n // OOP methods for modal control\n\n /**\n * Open the modal with `data`. Resolves with the value passed to close().\n * Opening again while open replaces the modal: the earlier promise\n * resolves with `null`, as if it had been closed without a result.\n */\n async open(data) {\n for (const [id, resolver] of this._resolvers) {\n resolver(null);\n this._resolvers.delete(id);\n }\n\n return new Promise((resolve) => {\n const id = ++this._currentId;\n this._resolvers.set(id, resolve);\n\n this._state.set('data', data);\n this._state.set('isOpen', true);\n this._state.set('error', null);\n });\n }\n\n close(result = null) {\n const currentId = this._currentId;\n const resolver = this._resolvers.get(currentId);\n\n if (resolver) {\n resolver(result);\n this._resolvers.delete(currentId);\n }\n\n this._state.set('isOpen', false);\n this._state.set('data', null);\n }\n\n setLoading(loading) {\n this._state.set('loading', loading);\n }\n\n setError(error) {\n this._state.set('error', error);\n }\n\n // Watch methods\n watchOpen(callback) {\n return this._state.watch('isOpen', callback);\n }\n\n watchData(callback) {\n return this._state.watch('data', callback);\n }\n}\n\n/**\n * Router State - OOP for navigation state\n */\nexport class RouterState {\n constructor(initialRoute = '/', options = {}) {\n this._state = createReactiveState({\n current: initialRoute,\n params: {},\n query: {},\n history: [initialRoute],\n canGoBack: false,\n canGoForward: false\n }, options);\n\n this._routes = new Map();\n this._options = options;\n }\n\n // OOP methods for routing\n addRoute(path, handler) {\n this._routes.set(path, handler);\n }\n\n navigate(path, params = {}, query = {}) {\n this._state.set('history', [...this._state.get('history'), path]);\n this._state.set('current', path);\n this._state.set('params', params);\n this._state.set('query', query);\n this._updateNavigationState();\n }\n\n back() {\n const history = this._state.get('history');\n if (history.length > 1) {\n const newHistory = history.slice(0, -1);\n const previousRoute = newHistory[newHistory.length - 1];\n\n this._state.set('history', newHistory);\n this._state.set('current', previousRoute);\n this._updateNavigationState();\n }\n }\n\n forward() {\n // Implementation for forward navigation\n // Would need to track forward history separately\n }\n\n // Watch methods\n watchRoute(callback) {\n return this._state.watch('current', callback);\n }\n\n watchParams(callback) {\n return this._state.watch('params', callback);\n }\n\n // Private methods\n _updateNavigationState() {\n const history = this._state.get('history');\n this._state.set('canGoBack', history.length > 1);\n this._state.set('canGoForward', false); // Simplified\n }\n}\n\n/**\n * Factory functions for creating enhanced state\n */\nexport function createFormState(initialValues, options) {\n return new FormState(initialValues, options);\n}\n\nexport function createListState(initialItems, options) {\n return new ListState(initialItems, options);\n}\n\nexport function createModalState(initialState) {\n return new ModalState(initialState);\n}\n\nexport function createRouterState(initialRoute, options) {\n return new RouterState(initialRoute, options);\n}\n\nexport default {\n FormState,\n ListState,\n ModalState,\n RouterState,\n createFormState,\n createListState,\n createModalState,\n createRouterState\n};\n", "/**\n * @coherent.js/state - Reactive State Management Package\n *\n * A comprehensive state management solution for Coherent.js applications\n * providing reactive state, persistence, validation, and SSR-compatible state management.\n */\n\n// Re-export everything from reactive-state\nexport {\n Observable,\n ReactiveState,\n StateError,\n globalErrorHandler,\n createReactiveState,\n observable,\n computed,\n batch,\n stateUtils\n} from './reactive-state.js';\n\n// Import for default export\nimport {\n createReactiveState,\n observable,\n computed,\n batch,\n stateUtils\n} from './reactive-state.js';\n\nimport {\n createState,\n globalStateManager,\n provideContext,\n createContextProvider,\n restoreContext,\n clearAllContexts,\n useContext,\n runWithContext\n} from './state-manager.js';\n\nimport {\n createPersistentState,\n withLocalStorage,\n withSessionStorage,\n withIndexedDB\n} from './state-persistence.js';\n\nimport {\n createValidatedState,\n validators\n} from './state-validation.js';\n\n// Import enhanced state patterns\nimport {\n createFormState,\n createListState,\n createModalState,\n createRouterState\n} from './enhanced-state-patterns.js';\n\n// Re-export everything from state-manager (SSR-compatible state)\nexport {\n createState,\n globalStateManager,\n provideContext,\n createContextProvider,\n restoreContext,\n clearAllContexts,\n useContext,\n runWithContext\n} from './state-manager.js';\n\n// Re-export everything from state-persistence\nexport {\n createPersistentState,\n withLocalStorage,\n withSessionStorage,\n withIndexedDB\n} from './state-persistence.js';\n\n// Re-export everything from state-validation\nexport {\n createValidatedState,\n validators\n} from './state-validation.js';\n\n// Re-export enhanced state patterns\nexport {\n FormState,\n ListState,\n ModalState,\n RouterState,\n createFormState,\n createListState,\n createModalState,\n createRouterState\n} from './enhanced-state-patterns.js';\n\n// Default export provides all utilities\nexport default {\n // Reactive state utilities\n createReactiveState,\n observable,\n computed,\n batch,\n\n // SSR-compatible state management\n createState,\n globalStateManager,\n provideContext,\n createContextProvider,\n restoreContext,\n clearAllContexts,\n useContext,\n runWithContext,\n\n // Persistence utilities\n createPersistentState,\n withLocalStorage,\n withSessionStorage,\n withIndexedDB,\n\n // Validation utilities\n createValidatedState,\n validators,\n\n // Enhanced state patterns\n createFormState,\n createListState,\n createModalState,\n createRouterState,\n\n // State utilities\n stateUtils\n};\n"],
|
|
5
|
+
"mappings": ";AAuBO,IAAM,aAAN,cAAyB,MAAM;AAAA,EAClC,YAAY,SAAS,UAAU,CAAC,GAAG;AAC/B,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,S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