@asaidimu/utils-store 5.0.0 → 6.0.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 +31 -267
- package/index.d.mts +397 -125
- package/index.d.ts +397 -125
- package/index.js +1 -1
- package/index.mjs +1 -1
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e,t,s=require("uuid"),i=Object.create,r=Object.defineProperty,a=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t,s)=>(s=null!=e?i(o(e)):{},((e,t,s,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of n(t))c.call(e,o)||o===s||r(e,o,{get:()=>t[o],enumerable:!(i=a(t,o))||i.enumerable});return e})(e&&e.__esModule?s:r(s,"default",{value:e,enumerable:!0}),e)),d=(e={"src/store/node_modules/@asaidimu/events/index.js"(e,t){var s,i=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var s in t)i(e,s,{get:t[s],enumerable:!0})})(o,{createEventBus:()=>c}),t.exports=(s=o,((e,t,s,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))n.call(e,c)||c===s||i(e,c,{get:()=>t[c],enumerable:!(o=r(t,c))||o.enumerable});return e})(i({},"__esModule",{value:!0}),s));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let s=[],i=0,r=0;const a=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{i++,r+=t,a.set(e,(a.get(e)||0)+1)},l=()=>{const t=s;s=[],t.forEach((({name:t,payload:s})=>{const i=performance.now();try{(n.get(t)||[]).forEach((e=>e(s)))}catch(i){e.errorHandler({...i,eventName:t,payload:s})}c(t,performance.now()-i)}))},d=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),h=e=>{const s=t.get(e);s?n.set(e,Array.from(s)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:s}=e.data;(n.get(t)||[]).forEach((e=>e(s)))}),{subscribe:(e,s)=>{t.has(e)||t.set(e,new Set);const i=t.get(e);return i.add(s),h(e),()=>{i.delete(s),0===i.size?(t.delete(e),n.delete(e)):h(e)}},emit:({name:t,payload:i})=>{if(e.async)return s.push({name:t,payload:i}),s.length>=e.batchSize?l():d(),void(o&&o.postMessage({name:t,payload:i}));const r=performance.now();try{(n.get(t)||[]).forEach((e=>e(i))),o&&o.postMessage({name:t,payload:i})}catch(s){e.errorHandler({...s,eventName:t,payload:i})}c(t,performance.now()-r)},getMetrics:()=>({totalEvents:i,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:a,averageEmitDuration:i>0?r/i:0}),clear:()=>{t.clear(),n.clear(),s=[],i=0,r=0,a.clear(),o&&(o.close(),o=null)}}}}},function(){return t||(0,e[n(e)[0]])((t={exports:{}}).exports,t),t.exports}),h=l(d()),u=Symbol.for("delete"),p=e=>Array.isArray(e)?[...e]:{...e};function m(e){const t=e?.deleteMarker||u;return function(e,s){if("object"!=typeof e||null===e)return"object"==typeof s&&null!==s?a(s):s===t?{}:s;if("object"!=typeof s||null===s)return e;const i=p(e),r=[{target:i,source:s}];for(;r.length>0;){const{target:e,source:s}=r.pop();for(const i of Object.keys(s)){if(!Object.prototype.hasOwnProperty.call(s,i))continue;const n=s[i];if(n!==t)if(Array.isArray(n))e[i]=n.map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:a(e)));else if("object"==typeof n&&null!==n){const t=i in e&&"object"==typeof e[i]&&null!==e[i]?e[i]:{};e[i]=p(t),r.push({target:e[i],source:n})}else e[i]=n;else delete e[i]}}return i;function a(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:a(e)));if("object"==typeof e){const s={};for(const[i,r]of Object.entries(e))if(r!==t)if("object"==typeof r&&null!==r){const e=a(r);void 0!==e&&(s[i]=e)}else s[i]=r;return s}return e===t?void 0:e}}}var f=m();l(d());var g=class{reactiveSelectors=new Map;reactiveSelectorCache=new WeakMap;pathBasedCache=new Map;getState;eventBus;unsubscribeFromStore;constructor(e,t){this.getState=e,this.eventBus=t,this.unsubscribeFromStore=this.eventBus.subscribe("update:complete",this.handleStoreUpdate)}handleStoreUpdate=e=>{const t=e.deltas.map((e=>e.path));this.reEvaluateReactiveSelectors(t)};reEvaluateReactiveSelectors=e=>{this.reactiveSelectors.forEach((t=>{if(t.accessedPaths.some((t=>e.some((e=>e.startsWith(t)||t.startsWith(e)))))){let e;try{e=t.selector(this.getState())}catch{e=void 0}e!==t.lastResult&&(t.lastResult=e,t.subscribers.forEach((e=>e(t.lastResult))),this.eventBus.emit({name:"selector:changed",payload:{selectorId:t.id,newResult:e,timestamp:performance.now()}}))}}))};createReactiveSelector(e){const t=this.reactiveSelectorCache.get(e);if(t)return t;const s=y(e);this.validateSimpleSelector(e,s);const i=s.sort().join("|"),r=this.pathBasedCache.get(i);if(r)return this.reactiveSelectorCache.set(e,r),r;const a=`selector-${Math.random().toString(36).substring(2,9)}`,n=e(this.getState()),o={id:a,selector:e,lastResult:n,accessedPaths:s,subscribers:new Set,reactiveSelectorInstance:null},c={get:()=>o.lastResult,subscribe:t=>(o.subscribers.add(t),()=>{o.subscribers.delete(t),queueMicrotask((()=>{0===o.subscribers.size&&(this.reactiveSelectors.delete(a),this.reactiveSelectorCache.delete(e),this.pathBasedCache.delete(i))}))}),id:a};return o.reactiveSelectorInstance=c,this.reactiveSelectors.set(a,o),this.reactiveSelectorCache.set(e,c),this.pathBasedCache.set(i,c),this.eventBus.emit({name:"selector:accessed",payload:{selectorId:a,accessedPaths:s,duration:0,timestamp:performance.now()}}),c}validateSimpleSelector(e,t){const s=e.toString(),i=s.match(/=>\s*(.+)$/),r=i?i[1].trim():s,a=["map","filter","reduce","forEach","find","findIndex","some","every","includes","flatMap","flat","slice","splice"];for(const e of a)if(new RegExp(`\\.${e}\\s*\\(`).test(r))throw new Error(`Selector contains .${e}() which is not allowed. Selectors must be simple property accessors only. Use store effects for transformations.`);if(/\?[^:]*:/.test(r))throw new Error("Selector contains ternary operator (? :) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/\bif\s*\(|\bswitch\s*\(/.test(r))throw new Error("Selector contains conditional logic (if/switch) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/(?<![.\w])[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/.test(r))throw new Error("Selector contains function calls which are not allowed. Selectors must be simple property accessors only.");const n=/[+\-*/%&|^](?!=)|[<>!]=?(?!=)/.test(r),o=/\[.*\]/.test(r);if(n&&!o)throw new Error("Selector contains operations (+, -, *, /, etc.) which are not allowed. Selectors must be simple property accessors only. Use store effects for computed values.");if(0===t.length)throw new Error("Selector doesn't access any state properties. Selectors must access at least one state property.")}dispose(){this.unsubscribeFromStore(),this.reactiveSelectors.clear(),this.pathBasedCache.clear()}createMemoizedSelector(e){const t=y(e);this.validateSimpleSelector(e,t);let s,i=null;return r=>{const a=this.extractStateSubset(r,t);return i===a||(i=a,s=e(r)),s}}extractStateSubset(e,t){const s=[];for(const i of t){const t=i.split(".");let r=e;for(const e of t){if(null==r){s.push(void 0);break}r=r[e]}s.push(r)}return s}};function y(e,t="."){const s=new Set,i=(e=[])=>new Proxy({},{get:(r,a)=>{if("symbol"==typeof a)return;const n=[...e,a],o=n.join(t);return s.add(o),i(n)}});try{e(i())}catch(e){throw new Error(`Selector failed during path analysis. This usually means the selector is too complex. Selectors must be simple property accessors only. Error: ${e instanceof Error?e.message:String(e)}`)}const r=Array.from(s);return r.filter((e=>!r.some((s=>s!==e&&s.startsWith(e+t)))))}function w(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;let s,i;if(Array.isArray(e)){if(s=e.length,s!=t.length)return!1;for(i=s;i-- >0;)if(!w(e[i],t[i]))return!1;return!0}const[r,a]=[Object.keys(e),Object.keys(t)];if(s=r.length,s!==a.length)return!1;for(i=s;i-- >0;){const s=r[i];if(!Object.prototype.hasOwnProperty.call(t,s)||!w(e[s],t[s]))return!1}return!0}return e!=e&&t!=t}function v(e){const t=e?.deleteMarker||u;return function(e,s){const i=[],r=[{pathArray:[],pathStr:"",orig:e||{},part:s||{}}];for(;r.length>0;){const{pathArray:e,pathStr:s,orig:a,part:n}=r.pop();if(null!=n&&!w(a,n))if("object"!=typeof n||Array.isArray(n))s&&i.push({path:s,oldValue:a,newValue:n});else for(const o of Object.keys(n)){const c=[...e,o],l=s?s+"."+o:o,d=n[o],h=a&&"object"==typeof a?a[o]:void 0;d!==t?"object"==typeof d&&null!==d?r.push({pathArray:c,pathStr:l,orig:h,part:d}):w(h,d)||i.push({path:l,oldValue:h,newValue:d}):void 0===h&&a&&"object"==typeof a||i.push({path:l,oldValue:h,newValue:void 0})}}return i}}function b(e){const t=e?.deleteMarker||u;return function(e){const s=new Set,i=[{obj:e,currentPath:""}];for(;i.length>0;){const{obj:e,currentPath:r}=i.pop();if(null!=e&&"object"==typeof e&&!Array.isArray(e))for(const a of Object.keys(e)){const n=r?`${r}.${a}`:a;s.add(n);const o=n.split(".");if(o.length>1)for(let e=o.length-1;e>0;e--){const t=o.slice(0,e).join(".");if(s.has(t))break;s.add(t)}const c=e[a];"object"==typeof c&&null!==c&&c!==t&&i.push({obj:c,currentPath:n})}}return Array.from(s)}}var S=v(),E=b(),x=class{constructor(e,t,s){this.updateBus=t,this.diff=s,this.cache=structuredClone(e)}cache;get(e){return e?structuredClone(this.cache):this.cache}applyChanges(e,t=!1,s=!1,i=[]){if(t)return this.cache=s?structuredClone(e):e,this.notifyListeners([]),[];0===i.length&&(i=[e]);const r=this.get(!1),a=new Map;for(let e=0;e<i.length;e++){const t=i[e],s=this.diff(r,t);for(let e=0;e<s.length;e++){const t=s[e];a.set(t.path,t)}}const n=a.size?[...a.values()]:[];if(n.length>0){this.cache=s?structuredClone(e):e;const t=new Set;for(let e=0;e<n.length;e++){let s=n[e].path;for(;s&&!t.has(s);){t.add(s);const e=s.lastIndexOf(".");if(e<0)break;s=s.slice(0,e)}}this.notifyListeners(t)}return n}notifyListeners(e){for(const t of e)this.updateBus.emit({name:"update",payload:t})}};l(d());var k=class{constructor(e,t,s){this.eventBus=e,this.executionState=t,this.merge=s}middleware=[];blockingMiddleware=[];async executeBlocking(e,t){for(const{fn:s,name:i,id:r}of this.blockingMiddleware){const a={id:r,name:i,startTime:performance.now()};this.executionState.runningMiddleware={id:r,name:i,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:r,name:i,type:"blocking"});try{const n=await Promise.resolve(s(e,t));if(a.endTime=performance.now(),a.duration=a.endTime-a.startTime,!1===n)return a.blocked=!0,this.emitMiddlewareLifecycle("blocked",{id:r,name:i,duration:a.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),{blocked:!0};this.emitMiddlewareLifecycle("complete",{id:r,name:i,type:"blocking",duration:a.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:{...a,blocked:!1}})}catch(e){return a.endTime=performance.now(),a.duration=a.endTime-a.startTime,a.error=e instanceof Error?e:new Error(String(e)),a.blocked=!0,this.emitMiddlewareError(r,i,a.error,a.duration),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),{blocked:!0,error:a.error}}finally{this.executionState.runningMiddleware=null}}return{blocked:!1}}async executeTransform(e,t){let s=e,i=t;for(const{fn:e,name:r,id:a}of this.middleware){const n={id:a,name:r,startTime:performance.now()};this.executionState.runningMiddleware={id:a,name:r,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:a,name:r,type:"transform"});try{const o=await Promise.resolve(e(s,t));n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.blocked=!1,o&&"object"==typeof o&&(s=this.merge(s,o),i=this.merge(i,o)),this.emit(this.eventBus,{name:"middleware:executed",payload:n}),this.emitMiddlewareLifecycle("complete",{id:a,name:r,type:"transform",duration:n.duration})}catch(e){n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.error=e instanceof Error?e:new Error(String(e)),n.blocked=!1,this.emit(this.eventBus,{name:"middleware:executed",payload:n}),this.emitMiddlewareError(a,r,n.error,n.duration),console.error(`Middleware ${r} error:`,e)}finally{this.executionState.runningMiddleware=null}}return i}addMiddleware(e,t="unnamed-middleware"){const s=this.generateId();return this.middleware.push({fn:e,name:t,id:s}),this.updateExecutionState(),s}addBlockingMiddleware(e,t="unnamed-blocking-middleware"){const s=this.generateId();return this.blockingMiddleware.push({fn:e,name:t,id:s}),this.updateExecutionState(),s}removeMiddleware(e){const t=this.middleware.length+this.blockingMiddleware.length;return this.middleware=this.middleware.filter((t=>t.id!==e)),this.blockingMiddleware=this.blockingMiddleware.filter((t=>t.id!==e)),this.updateExecutionState(),this.middleware.length+this.blockingMiddleware.length<t}updateExecutionState(){this.executionState.middlewares=[...this.middleware.map((e=>e.name)),...this.blockingMiddleware.map((e=>e.name))]}emitMiddlewareLifecycle(e,t){this.emit(this.eventBus,{name:`middleware:${e}`,payload:{...t,timestamp:Date.now()}})}emitMiddlewareError(e,t,s,i){this.emit(this.eventBus,{name:"middleware:error",payload:{id:e,name:t,error:s,duration:i,timestamp:Date.now()}})}generateId(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var T=class{constructor(e,t,s,i){this.eventBus=e,this.coreState=t,this.instanceID=s,this.maxRetries=i?.maxRetries??3,this.retryDelay=i?.retryDelay??1e3}persistence;instanceID;persistenceReady=!1;backgroundQueue=[];isProcessingQueue=!1;maxRetries=3;retryDelay=1e3;queueProcessor;async initialize(e){e?await this.setPersistence(e):this.setPersistenceReady()}isReady(){return this.persistenceReady}handleStateChange(e,t){if(!this.persistence||0===e.length)return;const s={id:`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,state:structuredClone(t),changedPaths:[...e],timestamp:Date.now(),retries:0};this.backgroundQueue.push(s),this.scheduleQueueProcessing(),this.emit(this.eventBus,{name:"persistence:queued",payload:{taskId:s.id,changedPaths:e,queueSize:this.backgroundQueue.length,timestamp:s.timestamp}})}getQueueStatus(){return{queueSize:this.backgroundQueue.length,isProcessing:this.isProcessingQueue,oldestTask:this.backgroundQueue[0]?.timestamp}}async flush(){this.isProcessingQueue||await this.processQueue()}clearQueue(){const e=this.backgroundQueue.length;this.backgroundQueue=[],this.queueProcessor&&(clearTimeout(this.queueProcessor),this.queueProcessor=void 0),this.emit(this.eventBus,{name:"persistence:queue_cleared",payload:{clearedTasks:e,timestamp:Date.now()}})}scheduleQueueProcessing(){this.queueProcessor||this.isProcessingQueue||(this.queueProcessor=setTimeout((()=>{this.processQueue().catch((e=>{console.error("Queue processing failed:",e)}))}),10))}async processQueue(){if(!this.isProcessingQueue&&0!==this.backgroundQueue.length){this.isProcessingQueue=!0,this.queueProcessor=void 0;try{for(;this.backgroundQueue.length>0;){const e=this.backgroundQueue.shift();await this.processTask(e)}}finally{this.isProcessingQueue=!1}}}async processTask(e){try{await this.persistence.set(this.instanceID,e.state)?this.emit(this.eventBus,{name:"persistence:success",payload:{taskId:e.id,changedPaths:e.changedPaths,duration:Date.now()-e.timestamp,timestamp:Date.now()}}):await this.handleTaskFailure(e,new Error("Persistence returned false"))}catch(t){await this.handleTaskFailure(e,t)}}async handleTaskFailure(e,t){if(e.retries++,e.retries<=this.maxRetries){const s=this.retryDelay*Math.pow(2,e.retries-1);this.emit(this.eventBus,{name:"persistence:retry",payload:{taskId:e.id,attempt:e.retries,maxRetries:this.maxRetries,nextRetryIn:s,error:t,timestamp:Date.now()}}),setTimeout((()=>{this.backgroundQueue.unshift(e),this.scheduleQueueProcessing()}),s)}else this.emit(this.eventBus,{name:"persistence:failed",payload:{taskId:e.id,changedPaths:e.changedPaths,attempts:e.retries,error:t,timestamp:Date.now()}})}setPersistenceReady(){this.persistenceReady=!0,this.emit(this.eventBus,{name:"persistence:ready",payload:{timestamp:Date.now()}})}async setPersistence(e){this.persistence=e;try{const e=await this.persistence.get();e&&this.coreState.applyChanges(e)}catch(e){console.error("Failed to initialize persistence:",e),this.emit(this.eventBus,{name:"persistence:init_error",payload:{error:e,timestamp:Date.now()}})}finally{this.setPersistenceReady()}this.persistence.subscribe&&this.persistence.subscribe(this.instanceID,(async e=>{const t=this.coreState.applyChanges(e);t.length>0&&this.emit(this.eventBus,{name:"update:complete",payload:{changedPaths:t,source:"external",timestamp:Date.now()}})}))}dispose(){this.clearQueue(),this.isProcessingQueue=!1,this.persistenceReady=!1}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var C=class{constructor(e,t,s){this.eventBus=e,this.coreState=t,this.executionState=s}async execute(e){const t=this.coreState.get(!0);this.executionState.transactionActive=!0,this.emit(this.eventBus,{name:"transaction:start",payload:{timestamp:Date.now()}});try{const t=await Promise.resolve(e());return this.emit(this.eventBus,{name:"transaction:complete",payload:{timestamp:Date.now()}}),this.executionState.transactionActive=!1,t}catch(e){throw this.coreState.applyChanges(t,!0,!1),this.emit(this.eventBus,{name:"transaction:error",payload:{error:e instanceof Error?e:new Error(String(e)),timestamp:Date.now()}}),this.executionState.transactionActive=!1,e}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var A=class{updateCount=0;listenerExecutions=0;averageUpdateTime=0;largestUpdateSize=0;mostActiveListenerPaths=[];totalUpdates=0;blockedUpdates=0;averageUpdateDuration=0;middlewareExecutions=0;transactionCount=0;totalEventsFired=0;totalActionsDispatched=0;totalActionsSucceeded=0;totalActionsFailed=0;averageActionDuration=0;updateTimes=[];actionTimes=[];pathExecutionCounts=new Map;constructor(e){this.setupEventListeners(e)}getMetrics(){return{updateCount:this.updateCount,listenerExecutions:this.listenerExecutions,averageUpdateTime:this.averageUpdateTime,largestUpdateSize:this.largestUpdateSize,mostActiveListenerPaths:[...this.mostActiveListenerPaths],totalUpdates:this.totalUpdates,blockedUpdates:this.blockedUpdates,averageUpdateDuration:this.averageUpdateDuration,middlewareExecutions:this.middlewareExecutions,transactionCount:this.transactionCount,totalEventsFired:this.totalEventsFired,totalActionsDispatched:this.totalActionsDispatched,totalActionsSucceeded:this.totalActionsSucceeded,totalActionsFailed:this.totalActionsFailed,averageActionDuration:this.averageActionDuration}}setupEventListeners(e){const t=e.emit;e.emit=s=>(this.totalEventsFired++,t.call(e,s)),e.subscribe("update:complete",(e=>{if(this.totalUpdates++,e.blocked)this.blockedUpdates++;else{if(e.duration){this.updateTimes.push(e.duration),this.updateTimes.length>100&&this.updateTimes.shift();const t=this.updateTimes.reduce(((e,t)=>e+t),0)/this.updateTimes.length;this.averageUpdateTime=t,this.averageUpdateDuration=t}e.deltas?.length&&(this.updateCount++,this.largestUpdateSize=Math.max(this.largestUpdateSize,e.deltas.length),e.deltas.forEach((e=>{const t=this.pathExecutionCounts.get(e.path)||0;this.pathExecutionCounts.set(e.path,t+1)})),this.mostActiveListenerPaths=Array.from(this.pathExecutionCounts.entries()).sort((([,e],[,t])=>t-e)).slice(0,5).map((([e])=>e)))}})),e.subscribe("middleware:start",(()=>{this.middlewareExecutions++})),e.subscribe("transaction:start",(()=>{this.transactionCount++})),e.subscribe("action:start",(()=>{this.totalActionsDispatched++})),e.subscribe("action:complete",(e=>{this.totalActionsSucceeded++,e.duration&&(this.actionTimes.push(e.duration),this.actionTimes.length>100&&this.actionTimes.shift(),this.averageActionDuration=this.actionTimes.reduce(((e,t)=>e+t),0)/this.actionTimes.length)})),e.subscribe("action:error",(()=>{this.totalActionsFailed++}))}reset(){this.updateCount=0,this.listenerExecutions=0,this.averageUpdateTime=0,this.largestUpdateSize=0,this.mostActiveListenerPaths=[],this.totalUpdates=0,this.blockedUpdates=0,this.averageUpdateDuration=0,this.middlewareExecutions=0,this.transactionCount=0,this.totalEventsFired=0,this.totalActionsDispatched=0,this.totalActionsSucceeded=0,this.totalActionsFailed=0,this.averageActionDuration=0,this.updateTimes=[],this.actionTimes=[],this.pathExecutionCounts.clear()}getDetailedMetrics(){return{pathExecutionCounts:new Map(this.pathExecutionCounts),recentUpdateTimes:[...this.updateTimes],successRate:this.totalUpdates>0?(this.totalUpdates-this.blockedUpdates)/this.totalUpdates:1,averagePathsPerUpdate:this.updateCount>0?Array.from(this.pathExecutionCounts.values()).reduce(((e,t)=>e+t),0)/this.updateCount:0}}dispose(){this.reset()}};l(d());var P=class extends Error{constructor(){super("Action Cancelled by Debounce"),this.name="ActionCancelledError"}},M=class{constructor(e,t){this.eventBus=e,this.set=t}actions=new Map;register(e){const t=e.debounce,i={name:e.name,id:s.v4(),action:e.fn,debounce:t?{...t,condition:t.condition||(()=>!0)}:void 0};return this.actions.set(e.name,i),()=>{const t=this.actions.get(e.name);t?.debounce?.timer&&clearTimeout(t.debounce.timer),this.actions.delete(e.name)}}async dispatch(e,...t){const s=this.actions.get(e);if(!s)throw new Error(`unknown action ${e}`);const{id:i,action:r,debounce:a}=s;return!a||void 0===a.delay||a.delay<=0||a.condition&&!a.condition(a.args,t)?this.executeAction(e,i,r,t):(a.timer&&(clearTimeout(a.timer),a.reject?.(new P)),new Promise(((s,n)=>{a.resolve=s,a.reject=n,a.timer=setTimeout((async()=>{a.timer=void 0,a.resolve=void 0,a.reject=void 0;try{const a=await this.executeAction(e,i,r,t);s(a)}catch(e){n(e)}}),a.delay)})))}async executeAction(e,t,s,i){const r=performance.now();this.emit(this.eventBus,{name:"action:start",payload:{actionId:t,name:e,params:i||[],timestamp:r}});try{const a=await this.set((e=>s(e,...i)),{actionId:t}),n=this.actions.get(e);n?.debounce&&(n.debounce.args=i);const o=performance.now();return this.emit(this.eventBus,{name:"action:complete",payload:{actionId:t,name:e,params:i,startTime:r,endTime:o,duration:o-r,result:a}}),a}catch(s){const a=performance.now();throw this.emit(this.eventBus,{name:"action:error",payload:{actionId:t,name:e,params:i,startTime:r,endTime:a,duration:a-r,error:s}}),s}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},B=(e=>(e.Singleton="singleton",e.Transient="transient",e))(B||{});exports.ActionManager=M,exports.ArtifactContainer=class{artifacts=new Map;resolvingStack=[];listeners=new Map;getState;subscribe;constructor(e){this.getState=(...t)=>e.get(...t),this.subscribe=(...t)=>e.watch(...t)}watch(e){return{id:e,get:()=>{const t=this.artifacts.get(e);return t&&(void 0!==t.instance||t.error)?this.packageArtifact(t):null},subscribe:t=>{this.listeners.has(e)||this.listeners.set(e,new Set);const s=this.listeners.get(e);return s.add(t),()=>s.delete(t)}}}get(e){return this.artifacts.get(e)?.instance}register(e){const{key:t,factory:s,scope:i="singleton",lazy:r=!0}=e;this.artifacts.has(t)&&(console.warn(`[ArtifactContainer] Warning: Overwriting existing artifact "${t}".`),this.disposeArtifact(t));const a={key:t,factory:s,scope:i,lazy:r,cleanupFunctions:[],stateDependencies:new Set,artifactDependencies:new Set,dependents:new Set};return this.artifacts.set(t,a),r||"singleton"!==i||this.resolve(t).catch((e=>{console.error(`[ArtifactContainer] Eager load failed for "${t}":`,e)})),async()=>{await this.unregister(t)}}async unregister(e){this.artifacts.has(e)&&(await this.disposeArtifact(e),this.artifacts.delete(e))}async resolve(e){if(this.resolvingStack.includes(e))throw new Error(`[ArtifactContainer] Circular dependency: ${this.resolvingStack.join(" -> ")} -> ${e}`);this.resolvingStack.push(e);try{const t=this.artifacts.get(e);if(!t)throw new Error(`[ArtifactContainer] Artifact with key "${e}" not found.`);if("transient"===t.scope){const e=await this.createArtifactInstance(t,new Set,new Set);return{instance:e.instance,cleanup:e.cleanup,error:e.error,invalidate:async()=>{}}}if(void 0!==t.instance||void 0!==t.error)return this.packageArtifact(t);if(t.initializationPromise)try{return await t.initializationPromise,this.packageArtifact(t)}catch(e){return this.packageArtifact(t)}const s=(async()=>{try{const e=new Set,s=new Set,i=await this.createArtifactInstance(t,e,s);return this.updateGraph(t,e,s),i.error&&(t.error=i.error),i.instance}catch(e){throw t.error=e,t.initializationPromise=void 0,e}})();t.initializationPromise=s;try{await s}catch(e){}return this.packageArtifact(t)}finally{this.resolvingStack.pop()}}packageArtifact(e){return{instance:e.instance,cleanup:this.createCompositeCleanup(e.cleanupFunctions),error:e.error,invalidate:async t=>this.invalidate(e.key,t)}}async createArtifactInstance(e,t,s){const i=[];let r=!0;i.push((()=>{r=!1}));const a={state:this.getState,current:e.instance,use:async i=>i({resolve:async s=>{if(s===e.key)throw new Error(`[ArtifactContainer] Self-dependency detected in "${e.key}"`);return t.add(s),this.resolve(s)},select:e=>(y(e).forEach((e=>s.add(e))),e(this.getState()))}),onCleanup:e=>{i.push(e)},yield:t=>{r?"transient"!==e.scope?(e.instance=t,e.error=void 0,this.processYieldPropagation(e.key)):console.warn(`[ArtifactContainer] Yield ignored on transient artifact "${e.key}"`):console.warn(`[ArtifactContainer] Ignored yield on disposed artifact "${e.key}"`)}};let n,o;try{n=await e.factory(a)}catch(e){o=e,n=void 0}"singleton"===e.scope&&(void 0!==n&&(e.instance=n),e.cleanupFunctions=i);return{instance:"singleton"===e.scope?e.instance:n,cleanup:this.createCompositeCleanup(i),error:o}}async processYieldPropagation(e){const t=this.artifacts.get(e);if(t&&(void 0!==t.instance||t.error))try{const s=Array.from(t.dependents);await Promise.all(s.map((e=>this.invalidate(e,!1)))),this.notifyListeners(e)}catch(t){console.error(`[ArtifactContainer] Yield propagation failed for "${e}":`,t)}}updateGraph(e,t,s){e.artifactDependencies.forEach((t=>{const s=this.artifacts.get(t);s&&s.dependents.delete(e.key)})),e.artifactDependencies=t,t.forEach((t=>{const s=this.artifacts.get(t);s&&s.dependents.add(e.key)}));const i=e.stateSubscriptionCleanup;e.stateDependencies=s,s.size>0?e.stateSubscriptionCleanup=this.subscribe(Array.from(s),(()=>this.invalidate(e.key))):e.stateSubscriptionCleanup=void 0,i&&i(),this.detectCycles(e.key),this.notifyListeners(e.key)}async invalidate(e,t=!1){const s=this.artifacts.get(e);if(!s)return;if(s.initializationPromise)try{await s.initializationPromise}catch(e){}if(s.rebuildPromise)return s.rebuildPromise;const i=(async()=>{try{const i=Array.from(s.dependents);await Promise.all(i.map((e=>this.invalidate(e,t)))),await this.disposeInstance(s),!t&&s.lazy||await this.resolve(e).catch((t=>{console.error(`[ArtifactContainer] Rebuild failed for "${e}":`,t)}))}finally{s.rebuildPromise=void 0}})();return s.rebuildPromise=i,i}async disposeInstance(e){if(e.stateSubscriptionCleanup&&(e.stateSubscriptionCleanup(),e.stateSubscriptionCleanup=void 0),e.cleanupFunctions.length>0)for(let t=e.cleanupFunctions.length-1;t>=0;t--)try{await e.cleanupFunctions[t]()}catch(t){console.error(`[ArtifactContainer] Cleanup error for "${e.key}":`,t)}e.instance=void 0,e.error=void 0,e.cleanupFunctions=[],e.initializationPromise=void 0,this.notifyListeners(e.key)}async disposeArtifact(e){const t=this.artifacts.get(e);t&&(t.rebuildPromise&&await t.rebuildPromise,await this.disposeInstance(t),t.artifactDependencies.forEach((t=>{const s=this.artifacts.get(t);s&&s.dependents.delete(e)})))}createCompositeCleanup(e){if(0!==e.length)return async()=>{for(let t=e.length-1;t>=0;t--)try{await e[t]()}catch(e){}}}notifyListeners(e){const t=this.listeners.get(e);t&&t.forEach((e=>e()))}detectCycles(e){const t=new Set,s=new Set,i=e=>{if(s.has(e))throw new Error(`[ArtifactContainer] Circular dependency: ${Array.from(s).join(" -> ")} -> ${e}`);if(t.has(e))return;t.add(e),s.add(e);const r=this.artifacts.get(e);r&&r.artifactDependencies.forEach((e=>i(e))),s.delete(e)};i(e)}dispose(){this.artifacts.forEach(((e,t)=>this.disposeArtifact(t))),this.artifacts.clear()}isLoading(e){return this.resolvingStack.includes(e)||void 0!==this.artifacts.get(e)?.initializationPromise}},exports.ArtifactScope=B,exports.DELETE_SYMBOL=u,exports.ReactiveDataStore=class{coreState;middlewareEngine;persistenceHandler;transactionManager;metricsCollector;selectorManager;actionManager;updateQueue=Promise.resolve();updateBus=(0,h.createEventBus)();eventBus=(0,h.createEventBus)();executionState;instanceID=s.v4();merge;diff;constructor(e,t,s=u,i){this.executionState={executing:!1,changes:null,pendingChanges:[],middlewares:[],runningMiddleware:null,transactionActive:!1},this.merge=m({deleteMarker:s}),this.diff=v({deleteMarker:s}),this.coreState=new x(e,this.updateBus,this.diff),this.middlewareEngine=new k(this.eventBus,this.executionState,this.merge),this.persistenceHandler=new T(this.eventBus,this.coreState,this.instanceID,{maxRetries:i?.persistenceMaxRetries,retryDelay:i?.persistenceRetryDelay}),this.transactionManager=new C(this.eventBus,this.coreState,this.executionState),this.metricsCollector=new A(this.eventBus),this.actionManager=new M(this.eventBus,this.set.bind(this)),this.persistenceHandler.initialize(t),this.setupPersistenceListener(),this.selectorManager=new g(this.get.bind(this),this.eventBus)}isReady(){return this.persistenceHandler.isReady()}state(){return this.executionState}get(e){return this.coreState.get(e??!1)}select(e){return this.selectorManager.createReactiveSelector(e)}register(e){return this.actionManager.register(e)}async dispatch(e,...t){return this.actionManager.dispatch(e,...t)}async set(e,t={}){const s=this.updateQueue.then((()=>this._performUpdate(e,t)));return this.updateQueue=s.catch((()=>{})),s}async _performUpdate(e,t){this.executionState.executing=!0;const s=performance.now();this.emit(this.eventBus,{name:"update:start",payload:{timestamp:s,actionId:t.actionId}});try{if(t.force){const t=this.get(!1),s="function"==typeof e?e(t):e;return this.coreState.applyChanges(s,!0),s}let i;const r=this.get(!1);if("function"==typeof e){const t=e(r);i=t instanceof Promise?await t:t}else i=e;const a=await this.middlewareEngine.executeBlocking(r,i);if(a.blocked)throw a.error||new Error("Update blocked by middleware");const n=this.merge(r,i),o=await this.middlewareEngine.executeTransform(n,i),c=this.merge(n,o),l=this.coreState.applyChanges(c,!1,!1,[i,o]),d=performance.now(),h=this.get(!1);return this.emit(this.eventBus,{name:"update:complete",payload:{deltas:l,duration:d-s,timestamp:Date.now(),actionId:t.actionId,newState:h}}),h}catch(e){throw this.emit(this.eventBus,{name:"update:complete",payload:{blocked:!0,error:e,timestamp:Date.now(),actionId:t.actionId,newState:this.get(!1)}}),e}finally{this.executionState.executing=!1,this.executionState.changes=null,this.executionState.runningMiddleware=null,this.executionState.pendingChanges=[]}}setupPersistenceListener(){this.updateBus.subscribe("update",(e=>{e&&this.persistenceHandler.isReady()&&this.persistenceHandler.handleStateChange([e],this.get(!1))}))}watch(e,t){const s=Array.isArray(e)?e:[e],i=""===e||0===s.length;return this.updateBus.subscribe("update",(e=>{(i||s.includes(e))&&(t(this.get(!1)),this.metricsCollector.listenerExecutions++)}))}subscribe(e,t){return this.watch(e,t)}id(){return this.instanceID}async transaction(e){return this.transactionManager.execute(e)}use(e){const t=(e.block?this.middlewareEngine.addBlockingMiddleware:this.middlewareEngine.addMiddleware).bind(this.middlewareEngine)(e.action,e.name);return()=>this.middlewareEngine.removeMiddleware(t)}metrics(){return this.metricsCollector.getMetrics()}on(e,t){return this.eventBus.subscribe(e,t)}onStoreEvent(e,t){return this.eventBus.subscribe(e,t)}getPersistenceStatus(){return this.persistenceHandler.getQueueStatus()}async flushPersistence(){return this.persistenceHandler.flush()}clearPersistenceQueue(){this.persistenceHandler.clearQueue()}dispose(){this.persistenceHandler.dispose(),this.metricsCollector.dispose?.(),this.selectorManager.dispose?.()}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},exports.StoreObserver=class{store;eventHistory=[];stateHistory=[];unsubscribers=[];isTimeTraveling=!1;devTools=null;middlewareExecutions=[];activeTransactionCount=0;activeBatches=new Set;maxEvents;maxStateHistory;enableConsoleLogging;isSilent;logEvents;performanceThresholds;constructor(e,t={}){this.store=e,this.maxEvents=t.maxEvents??500,this.maxStateHistory=t.maxStateHistory??20,this.enableConsoleLogging=t.enableConsoleLogging??!1,this.isSilent=t.silent??!1,this.logEvents={updates:t.logEvents?.updates??!0,middleware:t.logEvents?.middleware??!0,transactions:t.logEvents?.transactions??!0,actions:t.logEvents?.actions??!0,selectors:t.logEvents?.selectors??!0},this.performanceThresholds={updateTime:t.performanceThresholds?.updateTime??50,middlewareTime:t.performanceThresholds?.middlewareTime??20},this.recordStateSnapshot([]),this.setupEventListeners()}_consoleLog(e,...t){this.isSilent||"function"==typeof console[e]&&console[e](...t)}setupEventListeners(){const e=["update:start","update:complete","middleware:start","middleware:complete","middleware:error","middleware:blocked","transaction:start","transaction:complete","transaction:error","middleware:executed","action:start","action:complete","action:error","selector:accessed"];for(const t of e){const e=t.startsWith("update")&&this.logEvents.updates||t.startsWith("middleware")&&this.logEvents.middleware||t.startsWith("transaction")&&this.logEvents.transactions||t.startsWith("action")&&this.logEvents.actions||t.startsWith("selector")&&this.logEvents.selectors;this.unsubscribers.push(this.store.onStoreEvent(t,(s=>{"update:complete"!==t||s.blocked||this.isTimeTraveling||this.recordStateSnapshot(s.deltas),"middleware:executed"===t?this.middlewareExecutions.push(s):"transaction:start"===t?this.activeTransactionCount++:"transaction:complete"!==t&&"transaction:error"!==t||(this.activeTransactionCount=Math.max(0,this.activeTransactionCount-1)),s.batchId&&(t.endsWith("start")?this.activeBatches.add(s.batchId):(t.endsWith("complete")||t.endsWith("error"))&&this.activeBatches.delete(s.batchId)),this.recordEvent(t,s),this.enableConsoleLogging&&e&&this._log(t,s),this._checkPerformance(t,s)})))}}recordStateSnapshot(e){const t={state:this.store.get(!0),timestamp:Date.now(),deltas:e};this.stateHistory.unshift(t),this.stateHistory.length>this.maxStateHistory&&this.stateHistory.pop()}recordEvent(e,t){const s={type:e,timestamp:Date.now(),data:structuredClone(t)};this.eventHistory.unshift(s),this.eventHistory.length>this.maxEvents&&this.eventHistory.pop()}getEventHistory(){return structuredClone(this.eventHistory)}getStateHistory(){return structuredClone(this.stateHistory)}getMiddlewareExecutions(){return this.middlewareExecutions}getTransactionStatus(){return{activeTransactions:this.activeTransactionCount,activeBatches:Array.from(this.activeBatches)}}createLoggingMiddleware(e={}){const{logLevel:t="debug",logUpdates:s=!0}=e;return(e,i)=>{if(s){(console[t]||console.log)("State Update:",i)}return i}}createValidationMiddleware(e){return(t,s)=>{const i=e(t,s);return"boolean"==typeof i?i:(!i.valid&&i.reason&&this._consoleLog("warn","Validation failed:",i.reason),i.valid)}}getRecentChanges(e=5){const t=[],s=Math.min(e,this.stateHistory.length);for(let e=0;e<s;e++){const s=this.stateHistory[e];if(!s.deltas||0===s.deltas.length)continue;const i={},r={},a=(e,t,s)=>{t.reduce(((e,i,r)=>(r===t.length-1?e[i]=s:e[i]=e[i]??{},e[i])),e)};for(const e of s.deltas){const t=e.path.split(".");a(i,t,e.oldValue),a(r,t,e.newValue)}t.push({timestamp:s.timestamp,changedPaths:s.deltas.map((e=>e.path)),from:i,to:r})}return t}clearHistory(){this.eventHistory=[],this.stateHistory.length>0&&(this.stateHistory=[this.stateHistory[0]])}getHistoryForAction(e){return this.eventHistory.filter((t=>t.data?.actionId===e))}async replay(e){const t=this.eventHistory.filter((e=>"update:start"===e.type))[e];t?.data.update?(this._consoleLog("log",`Replaying event at index ${e}:`,t),await this.store.set(t.data.update,{force:!0})):this._consoleLog("warn",`No replayable event found at index ${e}.`)}createTimeTravel(){let e=0,t=[];const s=this.store.onStoreEvent("update:complete",(s=>{this.isTimeTraveling||s.blocked||(t=[],e=0)}));this.unsubscribers.push(s);const i=()=>this.stateHistory.length,r=()=>e<i()-1,a=()=>t.length>0;return{canUndo:r,canRedo:a,undo:async()=>{if(!r())return;t.unshift(this.stateHistory[e]),e++;const s=this.stateHistory[e].state;this.isTimeTraveling=!0,await this.store.set({...s},{force:!0}),this.isTimeTraveling=!1},redo:async()=>{if(!a())return;const s=t.shift();e--,this.isTimeTraveling=!0,await this.store.set({...s.state},{force:!0}),this.isTimeTraveling=!1},length:i,clear:()=>{t=[],e=0}}}async saveSession(e){const t=this.store.id(),s={eventHistory:this.eventHistory,stateHistory:this.stateHistory};return Promise.resolve(e.set(t,s))}async loadSession(e){const t=await Promise.resolve(e.get());return!!t&&(this.eventHistory=t.eventHistory||[],this.stateHistory=t.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),!0)}exportSession(){const e={eventHistory:this.eventHistory,stateHistory:this.stateHistory},t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),s=URL.createObjectURL(t),i=document.createElement("a");i.href=s,i.download=`store-observer-session-${(new Date).toISOString()}.json`,i.click(),URL.revokeObjectURL(s)}importSession(e){return new Promise(((t,s)=>{const i=new FileReader;i.onload=async e=>{try{const s=JSON.parse(e.target?.result);this.eventHistory=s.eventHistory||[],this.stateHistory=s.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),t()}catch(e){s(e)}},i.onerror=e=>s(e),i.readAsText(e)}))}disconnect(){this.unsubscribers.forEach((e=>e())),this.unsubscribers=[],this.devTools?.disconnect(),this.clearHistory()}_log(e,t){const s=new Date(t.timestamp||Date.now()).toISOString().split("T")[1].replace("Z","");if("update:start"===e)this._consoleLog("group",`%c⚡ Store Update Started [${s}]`,"color: #4a6da7");else if("update:complete"===e){if(t.blocked)this._consoleLog("warn",`%c✋ Update Blocked [${s}]`,"color: #bf8c0a",t.error);else{const e=t.deltas||[];e.length>0&&(this._consoleLog("log",`%c✅ Update Complete [${s}] - ${e.length} paths changed in ${t.duration?.toFixed(2)}ms`,"color: #2a9d8f"),this._consoleLog("table",e.map((e=>({path:e.path,oldValue:e.oldValue,newValue:e.newValue})))))}this._consoleLog("groupEnd")}else"middleware:start"===e?this._consoleLog("debug",`%c◀ Middleware "${t.name}" started [${s}] (${t.type})`,"color: #8c8c8c"):"middleware:complete"===e?this._consoleLog("debug",`%c▶ Middleware "${t.name}" completed [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #7c9c7c"):"middleware:error"===e?this._consoleLog("error",`%c❌ Middleware "${t.name}" error [${s}]:`,"color: #e63946",t.error):"middleware:blocked"===e?this._consoleLog("warn",`%c🛑 Middleware "${t.name}" blocked update [${s}]`,"color: #e76f51"):"transaction:start"===e?this._consoleLog("group",`%c📦 Transaction Started [${s}]`,"color: #6d597a"):"transaction:complete"===e?(this._consoleLog("log",`%c📦 Transaction Complete [${s}]`,"color: #355070"),this._consoleLog("groupEnd")):"transaction:error"===e?(this._consoleLog("error",`%c📦 Transaction Error [${s}]:`,"color: #e56b6f",t.error),this._consoleLog("groupEnd")):"action:start"===e?this._consoleLog("group",`%c🚀 Action "${t.name}" Started [${s}]`,"color: #9b59b6",{params:t.params}):"action:complete"===e?(this._consoleLog("log",`%c✔️ Action "${t.name}" Complete [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #2ecc71"),this._consoleLog("groupEnd")):"action:error"===e?(this._consoleLog("error",`%c🔥 Action "${t.name}" Error [${s}]:`,"color: #e74c3c",t.error),this._consoleLog("groupEnd")):"selector:accessed"===e&&this._consoleLog("debug",`%c👀 Selector Accessed [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #f1c40f",{accessedPaths:t.accessedPaths,selectorId:t.selectorId})}_checkPerformance(e,t){this.enableConsoleLogging&&("update:complete"===e&&!t.blocked&&t.duration>this.performanceThresholds.updateTime&&this._consoleLog("warn",`%c⚠️ Slow update detected [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{deltas:t.deltas,threshold:this.performanceThresholds.updateTime}),"middleware:complete"===e&&t.duration>this.performanceThresholds.middlewareTime&&this._consoleLog("warn",`%c⚠️ Slow middleware "${t.name}" [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{threshold:this.performanceThresholds.middlewareTime}))}},exports.createDerivePaths=b,exports.createDiff=v,exports.createMerge=m,exports.derivePaths=E,exports.diff=S,exports.merge=f,exports.shallowClone=p;
|
|
1
|
+
"use strict";var e,t,s=require("uuid"),i=Object.create,r=Object.defineProperty,a=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t,s)=>(s=null!=e?i(o(e)):{},((e,t,s,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of n(t))c.call(e,o)||o===s||r(e,o,{get:()=>t[o],enumerable:!(i=a(t,o))||i.enumerable});return e})(e&&e.__esModule?s:r(s,"default",{value:e,enumerable:!0}),e)),d=(e={"src/store/node_modules/@asaidimu/events/index.js"(e,t){var s,i=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var s in t)i(e,s,{get:t[s],enumerable:!0})})(o,{createEventBus:()=>c}),t.exports=(s=o,((e,t,s,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))n.call(e,c)||c===s||i(e,c,{get:()=>t[c],enumerable:!(o=r(t,c))||o.enumerable});return e})(i({},"__esModule",{value:!0}),s));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let s=[],i=0,r=0;const a=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{i++,r+=t,a.set(e,(a.get(e)||0)+1)},l=()=>{const t=s;s=[],t.forEach((({name:t,payload:s})=>{const i=performance.now();try{(n.get(t)||[]).forEach((e=>e(s)))}catch(i){e.errorHandler({...i,eventName:t,payload:s})}c(t,performance.now()-i)}))},d=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),h=e=>{const s=t.get(e);s?n.set(e,Array.from(s)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:s}=e.data;(n.get(t)||[]).forEach((e=>e(s)))}),{subscribe:(e,s)=>{t.has(e)||t.set(e,new Set);const i=t.get(e);return i.add(s),h(e),()=>{i.delete(s),0===i.size?(t.delete(e),n.delete(e)):h(e)}},emit:({name:t,payload:i})=>{if(e.async)return s.push({name:t,payload:i}),s.length>=e.batchSize?l():d(),void(o&&o.postMessage({name:t,payload:i}));const r=performance.now();try{(n.get(t)||[]).forEach((e=>e(i))),o&&o.postMessage({name:t,payload:i})}catch(s){e.errorHandler({...s,eventName:t,payload:i})}c(t,performance.now()-r)},getMetrics:()=>({totalEvents:i,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:a,averageEmitDuration:i>0?r/i:0}),clear:()=>{t.clear(),n.clear(),s=[],i=0,r=0,a.clear(),o&&(o.close(),o=null)}}}}},function(){return t||(0,e[n(e)[0]])((t={exports:{}}).exports,t),t.exports}),h=l(d()),u=Symbol.for("delete"),p=e=>Array.isArray(e)?[...e]:{...e};function m(e){const t=e?.deleteMarker||u;return function(e,s){if("object"!=typeof e||null===e)return"object"==typeof s&&null!==s?a(s):s===t?{}:s;if("object"!=typeof s||null===s)return e;const i=p(e),r=[{target:i,source:s}];for(;r.length>0;){const{target:e,source:s}=r.pop();for(const i of Object.keys(s)){if(!Object.prototype.hasOwnProperty.call(s,i))continue;const n=s[i];if(n!==t)if(Array.isArray(n))e[i]=n.map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:a(e)));else if("object"==typeof n&&null!==n){const t=i in e&&"object"==typeof e[i]&&null!==e[i]?e[i]:{};e[i]=p(t),r.push({target:e[i],source:n})}else e[i]=n;else delete e[i]}}return i;function a(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:a(e)));if("object"==typeof e){const s={};for(const[i,r]of Object.entries(e))if(r!==t)if("object"==typeof r&&null!==r){const e=a(r);void 0!==e&&(s[i]=e)}else s[i]=r;return s}return e===t?void 0:e}}}var f=m();l(d());var g=class{reactiveSelectors=new Map;reactiveSelectorCache=new WeakMap;pathBasedCache=new Map;getState;eventBus;unsubscribeFromStore;constructor(e,t){this.getState=e,this.eventBus=t,this.unsubscribeFromStore=this.eventBus.subscribe("update:complete",this.handleStoreUpdate)}handleStoreUpdate=e=>{const t=e.deltas.map((e=>e.path));this.reEvaluateReactiveSelectors(t)};reEvaluateReactiveSelectors=e=>{this.reactiveSelectors.forEach((t=>{if(t.accessedPaths.some((t=>e.some((e=>e.startsWith(t)||t.startsWith(e)))))){let e;try{e=t.selector(this.getState())}catch{e=void 0}e!==t.lastResult&&(t.lastResult=e,t.subscribers.forEach((e=>e(t.lastResult))),this.eventBus.emit({name:"selector:changed",payload:{selectorId:t.id,newResult:e,timestamp:performance.now()}}))}}))};createReactiveSelector(e){const t=this.reactiveSelectorCache.get(e);if(t)return t;const s=y(e);this.validateSimpleSelector(e,s);const i=s.sort().join("|"),r=this.pathBasedCache.get(i);if(r)return this.reactiveSelectorCache.set(e,r),r;const a=`selector-${Math.random().toString(36).substring(2,9)}`,n=e(this.getState()),o={id:a,selector:e,lastResult:n,accessedPaths:s,subscribers:new Set,reactiveSelectorInstance:null},c={get:()=>o.lastResult,subscribe:t=>(o.subscribers.add(t),()=>{o.subscribers.delete(t),queueMicrotask((()=>{0===o.subscribers.size&&(this.reactiveSelectors.delete(a),this.reactiveSelectorCache.delete(e),this.pathBasedCache.delete(i))}))}),id:a};return o.reactiveSelectorInstance=c,this.reactiveSelectors.set(a,o),this.reactiveSelectorCache.set(e,c),this.pathBasedCache.set(i,c),this.eventBus.emit({name:"selector:accessed",payload:{selectorId:a,accessedPaths:s,duration:0,timestamp:performance.now()}}),c}validateSimpleSelector(e,t){const s=e.toString(),i=s.match(/=>\s*(.+)$/),r=i?i[1].trim():s,a=["map","filter","reduce","forEach","find","findIndex","some","every","includes","flatMap","flat","slice","splice"];for(const e of a)if(new RegExp(`\\.${e}\\s*\\(`).test(r))throw new Error(`Selector contains .${e}() which is not allowed. Selectors must be simple property accessors only. Use store effects for transformations.`);if(/\?[^:]*:/.test(r))throw new Error("Selector contains ternary operator (? :) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/\bif\s*\(|\bswitch\s*\(/.test(r))throw new Error("Selector contains conditional logic (if/switch) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/(?<![.\w])[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/.test(r))throw new Error("Selector contains function calls which are not allowed. Selectors must be simple property accessors only.");const n=/[+\-*/%&|^](?!=)|[<>!]=?(?!=)/.test(r),o=/\[.*\]/.test(r);if(n&&!o)throw new Error("Selector contains operations (+, -, *, /, etc.) which are not allowed. Selectors must be simple property accessors only. Use store effects for computed values.");if(0===t.length)throw new Error("Selector doesn't access any state properties. Selectors must access at least one state property.")}dispose(){this.unsubscribeFromStore(),this.reactiveSelectors.clear(),this.pathBasedCache.clear()}createMemoizedSelector(e){const t=y(e);this.validateSimpleSelector(e,t);let s,i=null;return r=>{const a=this.extractStateSubset(r,t);return i===a||(i=a,s=e(r)),s}}extractStateSubset(e,t){const s=[];for(const i of t){const t=i.split(".");let r=e;for(const e of t){if(null==r){s.push(void 0);break}r=r[e]}s.push(r)}return s}};function y(e,t="."){const s=new Set,i=(e=[])=>new Proxy({},{get:(r,a)=>{if("symbol"==typeof a)return;const n=[...e,a],o=n.join(t);return s.add(o),i(n)}});try{e(i())}catch(e){throw new Error(`Selector failed during path analysis. This usually means the selector is too complex. Selectors must be simple property accessors only. Error: ${e instanceof Error?e.message:String(e)}`)}const r=Array.from(s);return r.filter((e=>!r.some((s=>s!==e&&s.startsWith(e+t)))))}function w(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;let s,i;if(Array.isArray(e)){if(s=e.length,s!=t.length)return!1;for(i=s;i-- >0;)if(!w(e[i],t[i]))return!1;return!0}const[r,a]=[Object.keys(e),Object.keys(t)];if(s=r.length,s!==a.length)return!1;for(i=s;i-- >0;){const s=r[i];if(!Object.prototype.hasOwnProperty.call(t,s)||!w(e[s],t[s]))return!1}return!0}return e!=e&&t!=t}function v(e){const t=e?.deleteMarker||u;return function(e,s){const i=[],r=[{pathArray:[],pathStr:"",orig:e||{},part:s||{}}];for(;r.length>0;){const{pathArray:e,pathStr:s,orig:a,part:n}=r.pop();if(null!=n&&!w(a,n))if("object"!=typeof n||Array.isArray(n))s&&i.push({path:s,oldValue:a,newValue:n});else for(const o of Object.keys(n)){const c=[...e,o],l=s?s+"."+o:o,d=n[o],h=a&&"object"==typeof a?a[o]:void 0;d!==t?"object"==typeof d&&null!==d?r.push({pathArray:c,pathStr:l,orig:h,part:d}):w(h,d)||i.push({path:l,oldValue:h,newValue:d}):void 0===h&&a&&"object"==typeof a||i.push({path:l,oldValue:h,newValue:void 0})}}return i}}function b(e){const t=e?.deleteMarker||u;return function(e){const s=new Set,i=[{obj:e,currentPath:""}];for(;i.length>0;){const{obj:e,currentPath:r}=i.pop();if(null!=e&&"object"==typeof e&&!Array.isArray(e))for(const a of Object.keys(e)){const n=r?`${r}.${a}`:a;s.add(n);const o=n.split(".");if(o.length>1)for(let e=o.length-1;e>0;e--){const t=o.slice(0,e).join(".");if(s.has(t))break;s.add(t)}const c=e[a];"object"==typeof c&&null!==c&&c!==t&&i.push({obj:c,currentPath:n})}}return Array.from(s)}}var S=v(),E=b(),x=class{constructor(e,t,s){this.updateBus=t,this.diff=s,this.cache=structuredClone(e)}cache;get(e){return e?structuredClone(this.cache):this.cache}applyChanges(e,t=!1,s=!1,i=[]){if(t)return this.cache=s?structuredClone(e):e,this.notifyListeners([]),[];0===i.length&&(i=[e]);const r=this.get(!1),a=new Map;for(let e=0;e<i.length;e++){const t=i[e],s=this.diff(r,t);for(let e=0;e<s.length;e++){const t=s[e];a.set(t.path,t)}}const n=a.size?[...a.values()]:[];if(n.length>0){this.cache=s?structuredClone(e):e;const t=new Set;for(let e=0;e<n.length;e++){let s=n[e].path;for(;s&&!t.has(s);){t.add(s);const e=s.lastIndexOf(".");if(e<0)break;s=s.slice(0,e)}}this.notifyListeners(t)}return n}notifyListeners(e){for(const t of e)this.updateBus.emit({name:"update",payload:t})}};l(d());var k=class{constructor(e,t,s){this.eventBus=e,this.executionState=t,this.merge=s}middleware=[];blockingMiddleware=[];async executeBlocking(e,t){for(const{fn:s,name:i,id:r}of this.blockingMiddleware){const a={id:r,name:i,startTime:performance.now()};this.executionState.runningMiddleware={id:r,name:i,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:r,name:i,type:"blocking"});try{const n=await Promise.resolve(s(e,t));if(a.endTime=performance.now(),a.duration=a.endTime-a.startTime,!1===n)return a.blocked=!0,this.emitMiddlewareLifecycle("blocked",{id:r,name:i,duration:a.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),{blocked:!0};this.emitMiddlewareLifecycle("complete",{id:r,name:i,type:"blocking",duration:a.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:{...a,blocked:!1}})}catch(e){return a.endTime=performance.now(),a.duration=a.endTime-a.startTime,a.error=e instanceof Error?e:new Error(String(e)),a.blocked=!0,this.emitMiddlewareError(r,i,a.error,a.duration),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),{blocked:!0,error:a.error}}finally{this.executionState.runningMiddleware=null}}return{blocked:!1}}async executeTransform(e,t){let s=e,i=t;for(const{fn:e,name:r,id:a}of this.middleware){const n={id:a,name:r,startTime:performance.now()};this.executionState.runningMiddleware={id:a,name:r,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:a,name:r,type:"transform"});try{const o=await Promise.resolve(e(s,t));n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.blocked=!1,o&&"object"==typeof o&&(s=this.merge(s,o),i=this.merge(i,o)),this.emit(this.eventBus,{name:"middleware:executed",payload:n}),this.emitMiddlewareLifecycle("complete",{id:a,name:r,type:"transform",duration:n.duration})}catch(e){n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.error=e instanceof Error?e:new Error(String(e)),n.blocked=!1,this.emit(this.eventBus,{name:"middleware:executed",payload:n}),this.emitMiddlewareError(a,r,n.error,n.duration),console.error(`Middleware ${r} error:`,e)}finally{this.executionState.runningMiddleware=null}}return i}addMiddleware(e,t="unnamed-middleware"){const s=this.generateId();return this.middleware.push({fn:e,name:t,id:s}),this.updateExecutionState(),s}addBlockingMiddleware(e,t="unnamed-blocking-middleware"){const s=this.generateId();return this.blockingMiddleware.push({fn:e,name:t,id:s}),this.updateExecutionState(),s}removeMiddleware(e){const t=this.middleware.length+this.blockingMiddleware.length;return this.middleware=this.middleware.filter((t=>t.id!==e)),this.blockingMiddleware=this.blockingMiddleware.filter((t=>t.id!==e)),this.updateExecutionState(),this.middleware.length+this.blockingMiddleware.length<t}updateExecutionState(){this.executionState.middlewares=[...this.middleware.map((e=>e.name)),...this.blockingMiddleware.map((e=>e.name))]}emitMiddlewareLifecycle(e,t){this.emit(this.eventBus,{name:`middleware:${e}`,payload:{...t,timestamp:Date.now()}})}emitMiddlewareError(e,t,s,i){this.emit(this.eventBus,{name:"middleware:error",payload:{id:e,name:t,error:s,duration:i,timestamp:Date.now()}})}generateId(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var T=class{constructor(e,t,s,i){this.eventBus=e,this.coreState=t,this.instanceID=s,this.maxRetries=i?.maxRetries??3,this.retryDelay=i?.retryDelay??1e3}persistence;instanceID;persistenceReady=!1;backgroundQueue=[];isProcessingQueue=!1;maxRetries=3;retryDelay=1e3;queueProcessor;async initialize(e){e?await this.setPersistence(e):this.setPersistenceReady()}isReady(){return this.persistenceReady}handleStateChange(e,t){if(!this.persistence||0===e.length)return;const s={id:`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,state:structuredClone(t),changedPaths:[...e],timestamp:Date.now(),retries:0};this.backgroundQueue.push(s),this.scheduleQueueProcessing(),this.emit(this.eventBus,{name:"persistence:queued",payload:{taskId:s.id,changedPaths:e,queueSize:this.backgroundQueue.length,timestamp:s.timestamp}})}getQueueStatus(){return{queueSize:this.backgroundQueue.length,isProcessing:this.isProcessingQueue,oldestTask:this.backgroundQueue[0]?.timestamp}}async flush(){this.isProcessingQueue||await this.processQueue()}clearQueue(){const e=this.backgroundQueue.length;this.backgroundQueue=[],this.queueProcessor&&(clearTimeout(this.queueProcessor),this.queueProcessor=void 0),this.emit(this.eventBus,{name:"persistence:queue_cleared",payload:{clearedTasks:e,timestamp:Date.now()}})}scheduleQueueProcessing(){this.queueProcessor||this.isProcessingQueue||(this.queueProcessor=setTimeout((()=>{this.processQueue().catch((e=>{console.error("Queue processing failed:",e)}))}),10))}async processQueue(){if(!this.isProcessingQueue&&0!==this.backgroundQueue.length){this.isProcessingQueue=!0,this.queueProcessor=void 0;try{for(;this.backgroundQueue.length>0;){const e=this.backgroundQueue.shift();await this.processTask(e)}}finally{this.isProcessingQueue=!1}}}async processTask(e){try{await this.persistence.set(this.instanceID,e.state)?this.emit(this.eventBus,{name:"persistence:success",payload:{taskId:e.id,changedPaths:e.changedPaths,duration:Date.now()-e.timestamp,timestamp:Date.now()}}):await this.handleTaskFailure(e,new Error("Persistence returned false"))}catch(t){await this.handleTaskFailure(e,t)}}async handleTaskFailure(e,t){if(e.retries++,e.retries<=this.maxRetries){const s=this.retryDelay*Math.pow(2,e.retries-1);this.emit(this.eventBus,{name:"persistence:retry",payload:{taskId:e.id,attempt:e.retries,maxRetries:this.maxRetries,nextRetryIn:s,error:t,timestamp:Date.now()}}),setTimeout((()=>{this.backgroundQueue.unshift(e),this.scheduleQueueProcessing()}),s)}else this.emit(this.eventBus,{name:"persistence:failed",payload:{taskId:e.id,changedPaths:e.changedPaths,attempts:e.retries,error:t,timestamp:Date.now()}})}setPersistenceReady(){this.persistenceReady=!0,this.emit(this.eventBus,{name:"persistence:ready",payload:{timestamp:Date.now()}})}async setPersistence(e){this.persistence=e;try{const e=await this.persistence.get();e&&this.coreState.applyChanges(e)}catch(e){console.error("Failed to initialize persistence:",e),this.emit(this.eventBus,{name:"persistence:init_error",payload:{error:e,timestamp:Date.now()}})}finally{this.setPersistenceReady()}this.persistence.subscribe&&this.persistence.subscribe(this.instanceID,(async e=>{const t=this.coreState.applyChanges(e);t.length>0&&this.emit(this.eventBus,{name:"update:complete",payload:{changedPaths:t,source:"external",timestamp:Date.now()}})}))}dispose(){this.clearQueue(),this.isProcessingQueue=!1,this.persistenceReady=!1}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var C=class{constructor(e,t,s){this.eventBus=e,this.coreState=t,this.executionState=s}async execute(e){const t=this.coreState.get(!0);this.executionState.transactionActive=!0,this.emit(this.eventBus,{name:"transaction:start",payload:{timestamp:Date.now()}});try{const t=await Promise.resolve(e());return this.emit(this.eventBus,{name:"transaction:complete",payload:{timestamp:Date.now()}}),this.executionState.transactionActive=!1,t}catch(e){throw this.coreState.applyChanges(t,!0,!1),this.emit(this.eventBus,{name:"transaction:error",payload:{error:e instanceof Error?e:new Error(String(e)),timestamp:Date.now()}}),this.executionState.transactionActive=!1,e}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var M=class{updateCount=0;listenerExecutions=0;averageUpdateTime=0;largestUpdateSize=0;mostActiveListenerPaths=[];totalUpdates=0;blockedUpdates=0;averageUpdateDuration=0;middlewareExecutions=0;transactionCount=0;totalEventsFired=0;totalActionsDispatched=0;totalActionsSucceeded=0;totalActionsFailed=0;averageActionDuration=0;updateTimes=[];actionTimes=[];pathExecutionCounts=new Map;constructor(e){this.setupEventListeners(e)}getMetrics(){return{updateCount:this.updateCount,listenerExecutions:this.listenerExecutions,averageUpdateTime:this.averageUpdateTime,largestUpdateSize:this.largestUpdateSize,mostActiveListenerPaths:[...this.mostActiveListenerPaths],totalUpdates:this.totalUpdates,blockedUpdates:this.blockedUpdates,averageUpdateDuration:this.averageUpdateDuration,middlewareExecutions:this.middlewareExecutions,transactionCount:this.transactionCount,totalEventsFired:this.totalEventsFired,totalActionsDispatched:this.totalActionsDispatched,totalActionsSucceeded:this.totalActionsSucceeded,totalActionsFailed:this.totalActionsFailed,averageActionDuration:this.averageActionDuration}}setupEventListeners(e){const t=e.emit;e.emit=s=>(this.totalEventsFired++,t.call(e,s)),e.subscribe("update:complete",(e=>{if(this.totalUpdates++,e.blocked)this.blockedUpdates++;else{if(e.duration){this.updateTimes.push(e.duration),this.updateTimes.length>100&&this.updateTimes.shift();const t=this.updateTimes.reduce(((e,t)=>e+t),0)/this.updateTimes.length;this.averageUpdateTime=t,this.averageUpdateDuration=t}e.deltas?.length&&(this.updateCount++,this.largestUpdateSize=Math.max(this.largestUpdateSize,e.deltas.length),e.deltas.forEach((e=>{const t=this.pathExecutionCounts.get(e.path)||0;this.pathExecutionCounts.set(e.path,t+1)})),this.mostActiveListenerPaths=Array.from(this.pathExecutionCounts.entries()).sort((([,e],[,t])=>t-e)).slice(0,5).map((([e])=>e)))}})),e.subscribe("middleware:start",(()=>{this.middlewareExecutions++})),e.subscribe("transaction:start",(()=>{this.transactionCount++})),e.subscribe("action:start",(()=>{this.totalActionsDispatched++})),e.subscribe("action:complete",(e=>{this.totalActionsSucceeded++,e.duration&&(this.actionTimes.push(e.duration),this.actionTimes.length>100&&this.actionTimes.shift(),this.averageActionDuration=this.actionTimes.reduce(((e,t)=>e+t),0)/this.actionTimes.length)})),e.subscribe("action:error",(()=>{this.totalActionsFailed++}))}reset(){this.updateCount=0,this.listenerExecutions=0,this.averageUpdateTime=0,this.largestUpdateSize=0,this.mostActiveListenerPaths=[],this.totalUpdates=0,this.blockedUpdates=0,this.averageUpdateDuration=0,this.middlewareExecutions=0,this.transactionCount=0,this.totalEventsFired=0,this.totalActionsDispatched=0,this.totalActionsSucceeded=0,this.totalActionsFailed=0,this.averageActionDuration=0,this.updateTimes=[],this.actionTimes=[],this.pathExecutionCounts.clear()}getDetailedMetrics(){return{pathExecutionCounts:new Map(this.pathExecutionCounts),recentUpdateTimes:[...this.updateTimes],successRate:this.totalUpdates>0?(this.totalUpdates-this.blockedUpdates)/this.totalUpdates:1,averagePathsPerUpdate:this.updateCount>0?Array.from(this.pathExecutionCounts.values()).reduce(((e,t)=>e+t),0)/this.updateCount:0}}dispose(){this.reset()}};l(d());var A=class extends Error{constructor(){super("Action Cancelled by Debounce"),this.name="ActionCancelledError"}},P=class{constructor(e,t){this.eventBus=e,this.set=t}actions=new Map;register(e){const t=e.debounce,i={name:e.name,id:s.v4(),action:e.fn,debounce:t?{...t,condition:t.condition||(()=>!0)}:void 0};return this.actions.set(e.name,i),()=>{const t=this.actions.get(e.name);t?.debounce?.timer&&clearTimeout(t.debounce.timer),this.actions.delete(e.name)}}async dispatch(e,...t){const s=this.actions.get(e);if(!s)throw new Error(`unknown action ${e}`);const{id:i,action:r,debounce:a}=s;return!a||void 0===a.delay||a.delay<=0||a.condition&&!a.condition(a.args,t)?this.executeAction(e,i,r,t):(a.timer&&(clearTimeout(a.timer),a.reject?.(new A)),new Promise(((s,n)=>{a.resolve=s,a.reject=n,a.timer=setTimeout((async()=>{a.timer=void 0,a.resolve=void 0,a.reject=void 0;try{const a=await this.executeAction(e,i,r,t);s(a)}catch(e){n(e)}}),a.delay)})))}async executeAction(e,t,s,i){const r=performance.now();this.emit(this.eventBus,{name:"action:start",payload:{actionId:t,name:e,params:i||[],timestamp:r}});try{const a=await this.set((e=>s(e,...i)),{actionId:t}),n=this.actions.get(e);n?.debounce&&(n.debounce.args=i);const o=performance.now();return this.emit(this.eventBus,{name:"action:complete",payload:{actionId:t,name:e,params:i,startTime:r,endTime:o,duration:o-r,result:a}}),a}catch(s){const a=performance.now();throw this.emit(this.eventBus,{name:"action:error",payload:{actionId:t,name:e,params:i,startTime:r,endTime:a,duration:a-r,error:s}}),s}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},D=class extends Error{constructor(e){super(e),this.name="SystemError"}},B=class extends D{constructor(e){super(`[ArtifactContainer] Cycle detected: ${e.join(" -> ")}`),this.name="CircularDependencyError"}},H=class extends D{constructor(e){super(`[ArtifactContainer] Artifact "${e}" not found.`),this.name="ArtifactNotFoundError"}},L=(e=>(e.Singleton="singleton",e.Transient="transient",e))(L||{});exports.ActionManager=P,exports.ArtifactContainer=class e{artifacts=new Map;resolvingStack=[];listeners=new Map;watcherCache=new Map;props;parent;isDisposed=!1;constructor({watch:e,get:t},s){this.props={watch:(...t)=>e(...t),get:()=>t(!0)},this.parent=s}createChild(){return new e(this.props,this)}getDebugInfo(){const e=[];return this.artifacts.forEach(((t,s)=>{e.push({id:s,scope:t.scope,status:t.debounceTimer?"debouncing":t.initializationPromise?"building":t.error?"error":t.instance?"active":"idle",dependencies:Array.from(t.artifactDependencies).map((e=>e.key)),dependents:Array.from(t.dependents).map((e=>e.key)),stateDependencies:Array.from(t.stateDependencies),renderCount:t.buildCount})})),e}register({key:e,factory:t,...s}){const i=e;this.artifacts.has(i)&&(console.warn(`[ArtifactContainer] Overwriting "${i}".`),this.disposeArtifact(i));const r={key:e,factory:t,scope:s.scope??"singleton",lazy:s.lazy??!0,timeoutMs:s.timeoutMs,retries:s.retries??0,baseDebounceMs:s.debounce??0,activeDebounceMs:s.debounce??0,isInvalidationScheduled:!1,cleanupFunctions:[],disposeFunctions:[],stateDependencies:new Set,artifactDependencies:new Set,dependents:new Set,buildCount:0};return this.artifacts.set(i,r),r.lazy||"singleton"!==r.scope||this.resolve(e).catch((e=>{console.error(`[ArtifactContainer] Eager load failed for "${i}":`,e)})),()=>this.unregister(e)}async unregister(e){const t=e;this.artifacts.has(t)&&(await this.disposeArtifact(t),this.artifacts.delete(t))}async resolve(e){const t=e;if(this.resolvingStack.includes(t))throw new B([...this.resolvingStack,t]);const{def:s,container:i}=this.findDefinition(t)||{};if(!s||!i){if(this.parent)return this.parent.resolve(e);throw new H(t)}if(i!==this)return i.resolve(e);this.resolvingStack.push(t);try{if("transient"===s.scope){const e=await this.createArtifactInstance(s,new Set,new Set);return{instance:e.instance,cleanup:e.cleanup,error:e.error,invalidate:async()=>console.warn(`[ArtifactContainer] Cannot invalidate transient "${t}"`)}}if(void 0!==s.instance||void 0!==s.error)return this.packageArtifact(s);if(s.initializationPromise){try{await s.initializationPromise}catch(e){}return this.packageArtifact(s)}const e=(async()=>{try{const e=new Set,t=new Set,i=await this.createArtifactInstance(s,e,t);this.updateGraph(s,e,t),i.error?s.error=i.error:s.instance=i.instance}catch(e){if(e instanceof D)throw e;s.error=e}finally{s.initializationPromise=void 0}})();return s.initializationPromise=e,await e,this.packageArtifact(s)}finally{this.resolvingStack.pop()}}watch(e){const t=e;if(!this.artifacts.has(t)&&this.parent)return this.parent.watch(e);if(this.watcherCache.has(t))return this.watcherCache.get(t);const s={id:t,get:()=>{const e=this.artifacts.get(t);return!e||void 0===e.instance&&!e.error?null:this.packageArtifact(e)},subscribe:e=>this.isDisposed?()=>{}:(this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>this.listeners.get(t)?.delete(e))};return this.watcherCache.set(t,s),s}peek(e){return this.artifacts.get(e)?.instance??this.parent?.peek(e)}findDefinition(e){return this.artifacts.has(e)?{def:this.artifacts.get(e),container:this}:this.parent?this.parent.findDefinition(e):null}packageArtifact(e){return{instance:e.instance,cleanup:this.createCompositeCleanup(e.cleanupFunctions),error:e.error,invalidate:async t=>this.invalidate(e.key,t)}}async createArtifactInstance(e,t,s){e.buildCount++;const i=[],r=[];let a=!0;e.activeDebounceMs=e.baseDebounceMs,i.push((()=>{a=!1}));const n={state:(...e)=>this.props.get(...e),current:e.instance,onCleanup:e=>i.push(e),onDispose:e=>r.push(e),use:async(i,r)=>(r?.debounce&&r.debounce>e.activeDebounceMs&&(e.activeDebounceMs=r.debounce),i({resolve:async s=>{if(s===e.key)throw new D(`Artifact "${String(e.key)}" depends on itself.`);const i=this.findDefinition(s);return i&&t.add({key:s,container:i.container}),this.resolve(s)},select:e=>(y(e).forEach((e=>s.add(e))),e(this.props.get()))})),yield:t=>{a&&("transient"!==e.scope?(e.instance=t,e.error=void 0,this.processYieldPropagation(e.key)):console.error(`[ArtifactContainer] Illegal yield on transient artifact "${String(e.key)}"`))}};let o,c,l=0;const d=(e.retries||0)+1;for(;l<d;)try{const t=e.factory(n);if(e.timeoutMs){const s=new Promise(((t,s)=>setTimeout((()=>s(new Error(`Timeout: ${e.timeoutMs}ms`))),e.timeoutMs)));o=await Promise.race([t,s])}else o=await t;break}catch(e){if(e instanceof D)throw e;l++,l>=d&&(c=e)}return"singleton"===e.scope&&(e.cleanupFunctions=i,e.disposeFunctions=r),{instance:o,cleanup:this.createCompositeCleanup(i),error:c}}async processYieldPropagation(e){const t=this.artifacts.get(e);if(t)try{await Promise.all(Array.from(t.dependents).map((e=>e.container.invalidate(e.key,!1).catch((t=>{console.error(`[ArtifactContainer] Failed to invalidate dependent "${e.key}":`,t)}))))),this.notifyListeners(e)}catch(t){console.error(`[ArtifactContainer] Yield propagation error "${e}":`,t)}}registerDependent(e,t,s){const i=this.artifacts.get(e);i&&i.dependents.add({key:t,container:s})}removeDependent(e,t,s){const i=this.artifacts.get(e);if(i)for(const e of i.dependents)if(e.key===t&&e.container===s){i.dependents.delete(e);break}}async invalidate(e,t=!1){const s=e,i=this.artifacts.get(s);if(i){if(i.debounceTimer&&(clearTimeout(i.debounceTimer),i.debounceTimer=void 0,i.isInvalidationScheduled=!1),!t&&i.activeDebounceMs>0&&!i.isInvalidationScheduled){i.isInvalidationScheduled=!0;const s=new Promise((s=>{i.debounceTimer=setTimeout((()=>{i.debounceTimer=void 0,i.isInvalidationScheduled=!1,this.executeInvalidation(e,t).then(s).catch(s)}),i.activeDebounceMs)}));return i.rebuildPromise=s,s}return t&&i.isInvalidationScheduled&&(i.isInvalidationScheduled=!1),this.executeInvalidation(e,t)}}async executeInvalidation(e,t){const s=e,i=this.artifacts.get(s);if(!i)return;if(i.initializationPromise)try{await i.initializationPromise}catch{}if(i.rebuildPromise&&!i.debounceTimer&&!t)return i.rebuildPromise;const r=(async()=>{try{await Promise.all(Array.from(i.dependents).map((e=>e.container.invalidate(e.key,t).catch((t=>{console.error(`[ArtifactContainer] Cascade failed for "${e.key}":`,t)}))))),await this.disposeInstance(i),!t&&i.lazy||await this.resolve(e)}finally{i.rebuildPromise=void 0}})();return i.rebuildPromise=r,r}async disposeInstance(e){e.stateSubscriptionCleanup&&(e.stateSubscriptionCleanup(),e.stateSubscriptionCleanup=void 0),e.debounceTimer&&(clearTimeout(e.debounceTimer),e.debounceTimer=void 0);for(let t=e.disposeFunctions.length-1;t>=0;t--)try{await e.disposeFunctions[t]()}catch(e){console.error(e)}for(let t=e.cleanupFunctions.length-1;t>=0;t--)try{await e.cleanupFunctions[t]()}catch(e){console.error(e)}e.instance=void 0,e.error=void 0,e.cleanupFunctions=[],e.disposeFunctions=[],e.initializationPromise=void 0,this.notifyListeners(e.key)}async disposeArtifact(e){const t=this.artifacts.get(e);t&&(this.watcherCache.delete(e),t.rebuildPromise&&await t.rebuildPromise,await this.disposeInstance(t),t.artifactDependencies.forEach((t=>{t.container.removeDependent(t.key,e,this)})))}updateGraph(e,t,s){e.artifactDependencies.forEach((s=>{let i=!1;for(const e of t)if(e.key===s.key&&e.container===s.container){i=!0;break}i||s.container.removeDependent(s.key,e.key,this)})),t.forEach((t=>{t.container.registerDependent(t.key,e.key,this)})),e.artifactDependencies=t,e.stateSubscriptionCleanup&&e.stateSubscriptionCleanup(),e.stateDependencies=s,s.size>0?e.stateSubscriptionCleanup=this.props.watch(Array.from(s),(()=>this.invalidate(e.key,!1))):e.stateSubscriptionCleanup=void 0,this.notifyListeners(e.key)}createCompositeCleanup(e){if(e.length)return async()=>{for(let t=e.length-1;t>=0;t--)try{await e[t]()}catch(e){console.error(e)}}}notifyListeners(e){this.listeners.get(e)?.forEach((e=>{try{e()}catch(e){console.error(e)}}))}dispose(){this.isDisposed=!0,this.artifacts.forEach(((e,t)=>this.disposeArtifact(t))),this.artifacts.clear(),this.watcherCache.clear(),this.listeners.clear()}},exports.ArtifactNotFoundError=H,exports.ArtifactScope=L,exports.CircularDependencyError=B,exports.DELETE_SYMBOL=u,exports.IllegalScopeError=class extends D{constructor(e){super(`[ArtifactContainer] ${e}`),this.name="IllegalScopeError"}},exports.ReactiveDataStore=class{coreState;middlewareEngine;persistenceHandler;transactionManager;metricsCollector;selectorManager;actionManager;updateQueue=Promise.resolve();updateBus=(0,h.createEventBus)();eventBus=(0,h.createEventBus)();executionState;instanceID=s.v4();merge;diff;constructor(e,t,s=u,i){this.executionState={executing:!1,changes:null,pendingChanges:[],middlewares:[],runningMiddleware:null,transactionActive:!1},this.merge=m({deleteMarker:s}),this.diff=v({deleteMarker:s}),this.coreState=new x(e,this.updateBus,this.diff),this.middlewareEngine=new k(this.eventBus,this.executionState,this.merge),this.persistenceHandler=new T(this.eventBus,this.coreState,this.instanceID,{maxRetries:i?.persistenceMaxRetries,retryDelay:i?.persistenceRetryDelay}),this.transactionManager=new C(this.eventBus,this.coreState,this.executionState),this.metricsCollector=new M(this.eventBus),this.actionManager=new P(this.eventBus,this.set.bind(this)),this.persistenceHandler.initialize(t),this.setupPersistenceListener(),this.selectorManager=new g(this.get.bind(this),this.eventBus)}isReady(){return this.persistenceHandler.isReady()}state(){return this.executionState}get(e){return this.coreState.get(e??!1)}select(e){return this.selectorManager.createReactiveSelector(e)}register(e){return this.actionManager.register(e)}async dispatch(e,...t){return this.actionManager.dispatch(e,...t)}async set(e,t={}){const s=this.updateQueue.then((()=>this._performUpdate(e,t)));return this.updateQueue=s.catch((()=>{})),s}async _performUpdate(e,t){this.executionState.executing=!0;const s=performance.now();this.emit(this.eventBus,{name:"update:start",payload:{timestamp:s,actionId:t.actionId}});try{if(t.force){const t=this.get(!1),s="function"==typeof e?e(t):e;return this.coreState.applyChanges(s,!0),s}let i;const r=this.get(!1);if("function"==typeof e){const t=e(r);i=t instanceof Promise?await t:t}else i=e;const a=await this.middlewareEngine.executeBlocking(r,i);if(a.blocked)throw a.error||new Error("Update blocked by middleware");const n=this.merge(r,i),o=await this.middlewareEngine.executeTransform(n,i),c=this.merge(n,o),l=this.coreState.applyChanges(c,!1,!1,[i,o]),d=performance.now(),h=this.get(!1);return this.emit(this.eventBus,{name:"update:complete",payload:{deltas:l,duration:d-s,timestamp:Date.now(),actionId:t.actionId,newState:h}}),h}catch(e){throw this.emit(this.eventBus,{name:"update:complete",payload:{blocked:!0,error:e,timestamp:Date.now(),actionId:t.actionId,newState:this.get(!1)}}),e}finally{this.executionState.executing=!1,this.executionState.changes=null,this.executionState.runningMiddleware=null,this.executionState.pendingChanges=[]}}setupPersistenceListener(){this.updateBus.subscribe("update",(e=>{e&&this.persistenceHandler.isReady()&&this.persistenceHandler.handleStateChange([e],this.get(!1))}))}watch(e,t){const s=Array.isArray(e)?e:[e],i=""===e||0===s.length;return this.updateBus.subscribe("update",(e=>{(i||s.includes(e))&&(t(this.get(!1)),this.metricsCollector.listenerExecutions++)}))}subscribe(e,t){return this.watch(e,t)}id(){return this.instanceID}async transaction(e){return this.transactionManager.execute(e)}use(e){const t=(e.block?this.middlewareEngine.addBlockingMiddleware:this.middlewareEngine.addMiddleware).bind(this.middlewareEngine)(e.action,e.name);return()=>this.middlewareEngine.removeMiddleware(t)}metrics(){return this.metricsCollector.getMetrics()}on(e,t){return this.eventBus.subscribe(e,t)}onStoreEvent(e,t){return this.eventBus.subscribe(e,t)}getPersistenceStatus(){return this.persistenceHandler.getQueueStatus()}async flushPersistence(){return this.persistenceHandler.flush()}clearPersistenceQueue(){this.persistenceHandler.clearQueue()}dispose(){this.persistenceHandler.dispose(),this.metricsCollector.dispose?.(),this.selectorManager.dispose?.()}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},exports.StoreObserver=class{store;eventHistory=[];stateHistory=[];unsubscribers=[];isTimeTraveling=!1;devTools=null;middlewareExecutions=[];activeTransactionCount=0;activeBatches=new Set;maxEvents;maxStateHistory;enableConsoleLogging;isSilent;logEvents;performanceThresholds;constructor(e,t={}){this.store=e,this.maxEvents=t.maxEvents??500,this.maxStateHistory=t.maxStateHistory??20,this.enableConsoleLogging=t.enableConsoleLogging??!1,this.isSilent=t.silent??!1,this.logEvents={updates:t.logEvents?.updates??!0,middleware:t.logEvents?.middleware??!0,transactions:t.logEvents?.transactions??!0,actions:t.logEvents?.actions??!0,selectors:t.logEvents?.selectors??!0},this.performanceThresholds={updateTime:t.performanceThresholds?.updateTime??50,middlewareTime:t.performanceThresholds?.middlewareTime??20},this.recordStateSnapshot([]),this.setupEventListeners()}_consoleLog(e,...t){this.isSilent||"function"==typeof console[e]&&console[e](...t)}setupEventListeners(){const e=["update:start","update:complete","middleware:start","middleware:complete","middleware:error","middleware:blocked","transaction:start","transaction:complete","transaction:error","middleware:executed","action:start","action:complete","action:error","selector:accessed"];for(const t of e){const e=t.startsWith("update")&&this.logEvents.updates||t.startsWith("middleware")&&this.logEvents.middleware||t.startsWith("transaction")&&this.logEvents.transactions||t.startsWith("action")&&this.logEvents.actions||t.startsWith("selector")&&this.logEvents.selectors;this.unsubscribers.push(this.store.onStoreEvent(t,(s=>{"update:complete"!==t||s.blocked||this.isTimeTraveling||this.recordStateSnapshot(s.deltas),"middleware:executed"===t?this.middlewareExecutions.push(s):"transaction:start"===t?this.activeTransactionCount++:"transaction:complete"!==t&&"transaction:error"!==t||(this.activeTransactionCount=Math.max(0,this.activeTransactionCount-1)),s.batchId&&(t.endsWith("start")?this.activeBatches.add(s.batchId):(t.endsWith("complete")||t.endsWith("error"))&&this.activeBatches.delete(s.batchId)),this.recordEvent(t,s),this.enableConsoleLogging&&e&&this._log(t,s),this._checkPerformance(t,s)})))}}recordStateSnapshot(e){const t={state:this.store.get(!0),timestamp:Date.now(),deltas:e};this.stateHistory.unshift(t),this.stateHistory.length>this.maxStateHistory&&this.stateHistory.pop()}recordEvent(e,t){const s={type:e,timestamp:Date.now(),data:structuredClone(t)};this.eventHistory.unshift(s),this.eventHistory.length>this.maxEvents&&this.eventHistory.pop()}getEventHistory(){return structuredClone(this.eventHistory)}getStateHistory(){return structuredClone(this.stateHistory)}getMiddlewareExecutions(){return this.middlewareExecutions}getTransactionStatus(){return{activeTransactions:this.activeTransactionCount,activeBatches:Array.from(this.activeBatches)}}createLoggingMiddleware(e={}){const{logLevel:t="debug",logUpdates:s=!0}=e;return(e,i)=>{if(s){(console[t]||console.log)("State Update:",i)}return i}}createValidationMiddleware(e){return(t,s)=>{const i=e(t,s);return"boolean"==typeof i?i:(!i.valid&&i.reason&&this._consoleLog("warn","Validation failed:",i.reason),i.valid)}}getRecentChanges(e=5){const t=[],s=Math.min(e,this.stateHistory.length);for(let e=0;e<s;e++){const s=this.stateHistory[e];if(!s.deltas||0===s.deltas.length)continue;const i={},r={},a=(e,t,s)=>{t.reduce(((e,i,r)=>(r===t.length-1?e[i]=s:e[i]=e[i]??{},e[i])),e)};for(const e of s.deltas){const t=e.path.split(".");a(i,t,e.oldValue),a(r,t,e.newValue)}t.push({timestamp:s.timestamp,changedPaths:s.deltas.map((e=>e.path)),from:i,to:r})}return t}clearHistory(){this.eventHistory=[],this.stateHistory.length>0&&(this.stateHistory=[this.stateHistory[0]])}getHistoryForAction(e){return this.eventHistory.filter((t=>t.data?.actionId===e))}async replay(e){const t=this.eventHistory.filter((e=>"update:start"===e.type))[e];t?.data.update?(this._consoleLog("log",`Replaying event at index ${e}:`,t),await this.store.set(t.data.update,{force:!0})):this._consoleLog("warn",`No replayable event found at index ${e}.`)}createTimeTravel(){let e=0,t=[];const s=this.store.onStoreEvent("update:complete",(s=>{this.isTimeTraveling||s.blocked||(t=[],e=0)}));this.unsubscribers.push(s);const i=()=>this.stateHistory.length,r=()=>e<i()-1,a=()=>t.length>0;return{canUndo:r,canRedo:a,undo:async()=>{if(!r())return;t.unshift(this.stateHistory[e]),e++;const s=this.stateHistory[e].state;this.isTimeTraveling=!0,await this.store.set({...s},{force:!0}),this.isTimeTraveling=!1},redo:async()=>{if(!a())return;const s=t.shift();e--,this.isTimeTraveling=!0,await this.store.set({...s.state},{force:!0}),this.isTimeTraveling=!1},length:i,clear:()=>{t=[],e=0}}}async saveSession(e){const t=this.store.id(),s={eventHistory:this.eventHistory,stateHistory:this.stateHistory};return Promise.resolve(e.set(t,s))}async loadSession(e){const t=await Promise.resolve(e.get());return!!t&&(this.eventHistory=t.eventHistory||[],this.stateHistory=t.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),!0)}exportSession(){const e={eventHistory:this.eventHistory,stateHistory:this.stateHistory},t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),s=URL.createObjectURL(t),i=document.createElement("a");i.href=s,i.download=`store-observer-session-${(new Date).toISOString()}.json`,i.click(),URL.revokeObjectURL(s)}importSession(e){return new Promise(((t,s)=>{const i=new FileReader;i.onload=async e=>{try{const s=JSON.parse(e.target?.result);this.eventHistory=s.eventHistory||[],this.stateHistory=s.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),t()}catch(e){s(e)}},i.onerror=e=>s(e),i.readAsText(e)}))}disconnect(){this.unsubscribers.forEach((e=>e())),this.unsubscribers=[],this.devTools?.disconnect(),this.clearHistory()}_log(e,t){const s=new Date(t.timestamp||Date.now()).toISOString().split("T")[1].replace("Z","");if("update:start"===e)this._consoleLog("group",`%c⚡ Store Update Started [${s}]`,"color: #4a6da7");else if("update:complete"===e){if(t.blocked)this._consoleLog("warn",`%c✋ Update Blocked [${s}]`,"color: #bf8c0a",t.error);else{const e=t.deltas||[];e.length>0&&(this._consoleLog("log",`%c✅ Update Complete [${s}] - ${e.length} paths changed in ${t.duration?.toFixed(2)}ms`,"color: #2a9d8f"),this._consoleLog("table",e.map((e=>({path:e.path,oldValue:e.oldValue,newValue:e.newValue})))))}this._consoleLog("groupEnd")}else"middleware:start"===e?this._consoleLog("debug",`%c◀ Middleware "${t.name}" started [${s}] (${t.type})`,"color: #8c8c8c"):"middleware:complete"===e?this._consoleLog("debug",`%c▶ Middleware "${t.name}" completed [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #7c9c7c"):"middleware:error"===e?this._consoleLog("error",`%c❌ Middleware "${t.name}" error [${s}]:`,"color: #e63946",t.error):"middleware:blocked"===e?this._consoleLog("warn",`%c🛑 Middleware "${t.name}" blocked update [${s}]`,"color: #e76f51"):"transaction:start"===e?this._consoleLog("group",`%c📦 Transaction Started [${s}]`,"color: #6d597a"):"transaction:complete"===e?(this._consoleLog("log",`%c📦 Transaction Complete [${s}]`,"color: #355070"),this._consoleLog("groupEnd")):"transaction:error"===e?(this._consoleLog("error",`%c📦 Transaction Error [${s}]:`,"color: #e56b6f",t.error),this._consoleLog("groupEnd")):"action:start"===e?this._consoleLog("group",`%c🚀 Action "${t.name}" Started [${s}]`,"color: #9b59b6",{params:t.params}):"action:complete"===e?(this._consoleLog("log",`%c✔️ Action "${t.name}" Complete [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #2ecc71"),this._consoleLog("groupEnd")):"action:error"===e?(this._consoleLog("error",`%c🔥 Action "${t.name}" Error [${s}]:`,"color: #e74c3c",t.error),this._consoleLog("groupEnd")):"selector:accessed"===e&&this._consoleLog("debug",`%c👀 Selector Accessed [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #f1c40f",{accessedPaths:t.accessedPaths,selectorId:t.selectorId})}_checkPerformance(e,t){this.enableConsoleLogging&&("update:complete"===e&&!t.blocked&&t.duration>this.performanceThresholds.updateTime&&this._consoleLog("warn",`%c⚠️ Slow update detected [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{deltas:t.deltas,threshold:this.performanceThresholds.updateTime}),"middleware:complete"===e&&t.duration>this.performanceThresholds.middlewareTime&&this._consoleLog("warn",`%c⚠️ Slow middleware "${t.name}" [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{threshold:this.performanceThresholds.middlewareTime}))}},exports.SystemError=D,exports.createDerivePaths=b,exports.createDiff=v,exports.createMerge=m,exports.derivePaths=E,exports.diff=S,exports.merge=f,exports.shallowClone=p;
|
package/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{v4 as e}from"uuid";var t,s,i=Object.create,r=Object.defineProperty,a=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t,s)=>(s=null!=e?i(o(e)):{},((e,t,s,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of n(t))c.call(e,o)||o===s||r(e,o,{get:()=>t[o],enumerable:!(i=a(t,o))||i.enumerable});return e})(e&&e.__esModule?s:r(s,"default",{value:e,enumerable:!0}),e)),d=(t={"src/store/node_modules/@asaidimu/events/index.js"(e,t){var s,i=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var s in t)i(e,s,{get:t[s],enumerable:!0})})(o,{createEventBus:()=>c}),t.exports=(s=o,((e,t,s,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))n.call(e,c)||c===s||i(e,c,{get:()=>t[c],enumerable:!(o=r(t,c))||o.enumerable});return e})(i({},"__esModule",{value:!0}),s));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let s=[],i=0,r=0;const a=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{i++,r+=t,a.set(e,(a.get(e)||0)+1)},l=()=>{const t=s;s=[],t.forEach((({name:t,payload:s})=>{const i=performance.now();try{(n.get(t)||[]).forEach((e=>e(s)))}catch(i){e.errorHandler({...i,eventName:t,payload:s})}c(t,performance.now()-i)}))},d=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),h=e=>{const s=t.get(e);s?n.set(e,Array.from(s)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:s}=e.data;(n.get(t)||[]).forEach((e=>e(s)))}),{subscribe:(e,s)=>{t.has(e)||t.set(e,new Set);const i=t.get(e);return i.add(s),h(e),()=>{i.delete(s),0===i.size?(t.delete(e),n.delete(e)):h(e)}},emit:({name:t,payload:i})=>{if(e.async)return s.push({name:t,payload:i}),s.length>=e.batchSize?l():d(),void(o&&o.postMessage({name:t,payload:i}));const r=performance.now();try{(n.get(t)||[]).forEach((e=>e(i))),o&&o.postMessage({name:t,payload:i})}catch(s){e.errorHandler({...s,eventName:t,payload:i})}c(t,performance.now()-r)},getMetrics:()=>({totalEvents:i,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:a,averageEmitDuration:i>0?r/i:0}),clear:()=>{t.clear(),n.clear(),s=[],i=0,r=0,a.clear(),o&&(o.close(),o=null)}}}}},function(){return s||(0,t[n(t)[0]])((s={exports:{}}).exports,s),s.exports}),h=l(d()),u=Symbol.for("delete"),p=e=>Array.isArray(e)?[...e]:{...e};function m(e){const t=e?.deleteMarker||u;return function(e,s){if("object"!=typeof e||null===e)return"object"==typeof s&&null!==s?a(s):s===t?{}:s;if("object"!=typeof s||null===s)return e;const i=p(e),r=[{target:i,source:s}];for(;r.length>0;){const{target:e,source:s}=r.pop();for(const i of Object.keys(s)){if(!Object.prototype.hasOwnProperty.call(s,i))continue;const n=s[i];if(n!==t)if(Array.isArray(n))e[i]=n.map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:a(e)));else if("object"==typeof n&&null!==n){const t=i in e&&"object"==typeof e[i]&&null!==e[i]?e[i]:{};e[i]=p(t),r.push({target:e[i],source:n})}else e[i]=n;else delete e[i]}}return i;function a(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:a(e)));if("object"==typeof e){const s={};for(const[i,r]of Object.entries(e))if(r!==t)if("object"==typeof r&&null!==r){const e=a(r);void 0!==e&&(s[i]=e)}else s[i]=r;return s}return e===t?void 0:e}}}var f=m();l(d());var g=class{reactiveSelectors=new Map;reactiveSelectorCache=new WeakMap;pathBasedCache=new Map;getState;eventBus;unsubscribeFromStore;constructor(e,t){this.getState=e,this.eventBus=t,this.unsubscribeFromStore=this.eventBus.subscribe("update:complete",this.handleStoreUpdate)}handleStoreUpdate=e=>{const t=e.deltas.map((e=>e.path));this.reEvaluateReactiveSelectors(t)};reEvaluateReactiveSelectors=e=>{this.reactiveSelectors.forEach((t=>{if(t.accessedPaths.some((t=>e.some((e=>e.startsWith(t)||t.startsWith(e)))))){let e;try{e=t.selector(this.getState())}catch{e=void 0}e!==t.lastResult&&(t.lastResult=e,t.subscribers.forEach((e=>e(t.lastResult))),this.eventBus.emit({name:"selector:changed",payload:{selectorId:t.id,newResult:e,timestamp:performance.now()}}))}}))};createReactiveSelector(e){const t=this.reactiveSelectorCache.get(e);if(t)return t;const s=y(e);this.validateSimpleSelector(e,s);const i=s.sort().join("|"),r=this.pathBasedCache.get(i);if(r)return this.reactiveSelectorCache.set(e,r),r;const a=`selector-${Math.random().toString(36).substring(2,9)}`,n=e(this.getState()),o={id:a,selector:e,lastResult:n,accessedPaths:s,subscribers:new Set,reactiveSelectorInstance:null},c={get:()=>o.lastResult,subscribe:t=>(o.subscribers.add(t),()=>{o.subscribers.delete(t),queueMicrotask((()=>{0===o.subscribers.size&&(this.reactiveSelectors.delete(a),this.reactiveSelectorCache.delete(e),this.pathBasedCache.delete(i))}))}),id:a};return o.reactiveSelectorInstance=c,this.reactiveSelectors.set(a,o),this.reactiveSelectorCache.set(e,c),this.pathBasedCache.set(i,c),this.eventBus.emit({name:"selector:accessed",payload:{selectorId:a,accessedPaths:s,duration:0,timestamp:performance.now()}}),c}validateSimpleSelector(e,t){const s=e.toString(),i=s.match(/=>\s*(.+)$/),r=i?i[1].trim():s,a=["map","filter","reduce","forEach","find","findIndex","some","every","includes","flatMap","flat","slice","splice"];for(const e of a)if(new RegExp(`\\.${e}\\s*\\(`).test(r))throw new Error(`Selector contains .${e}() which is not allowed. Selectors must be simple property accessors only. Use store effects for transformations.`);if(/\?[^:]*:/.test(r))throw new Error("Selector contains ternary operator (? :) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/\bif\s*\(|\bswitch\s*\(/.test(r))throw new Error("Selector contains conditional logic (if/switch) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/(?<![.\w])[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/.test(r))throw new Error("Selector contains function calls which are not allowed. Selectors must be simple property accessors only.");const n=/[+\-*/%&|^](?!=)|[<>!]=?(?!=)/.test(r),o=/\[.*\]/.test(r);if(n&&!o)throw new Error("Selector contains operations (+, -, *, /, etc.) which are not allowed. Selectors must be simple property accessors only. Use store effects for computed values.");if(0===t.length)throw new Error("Selector doesn't access any state properties. Selectors must access at least one state property.")}dispose(){this.unsubscribeFromStore(),this.reactiveSelectors.clear(),this.pathBasedCache.clear()}createMemoizedSelector(e){const t=y(e);this.validateSimpleSelector(e,t);let s,i=null;return r=>{const a=this.extractStateSubset(r,t);return i===a||(i=a,s=e(r)),s}}extractStateSubset(e,t){const s=[];for(const i of t){const t=i.split(".");let r=e;for(const e of t){if(null==r){s.push(void 0);break}r=r[e]}s.push(r)}return s}};function y(e,t="."){const s=new Set,i=(e=[])=>new Proxy({},{get:(r,a)=>{if("symbol"==typeof a)return;const n=[...e,a],o=n.join(t);return s.add(o),i(n)}});try{e(i())}catch(e){throw new Error(`Selector failed during path analysis. This usually means the selector is too complex. Selectors must be simple property accessors only. Error: ${e instanceof Error?e.message:String(e)}`)}const r=Array.from(s);return r.filter((e=>!r.some((s=>s!==e&&s.startsWith(e+t)))))}function w(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;let s,i;if(Array.isArray(e)){if(s=e.length,s!=t.length)return!1;for(i=s;i-- >0;)if(!w(e[i],t[i]))return!1;return!0}const[r,a]=[Object.keys(e),Object.keys(t)];if(s=r.length,s!==a.length)return!1;for(i=s;i-- >0;){const s=r[i];if(!Object.prototype.hasOwnProperty.call(t,s)||!w(e[s],t[s]))return!1}return!0}return e!=e&&t!=t}function v(e){const t=e?.deleteMarker||u;return function(e,s){const i=[],r=[{pathArray:[],pathStr:"",orig:e||{},part:s||{}}];for(;r.length>0;){const{pathArray:e,pathStr:s,orig:a,part:n}=r.pop();if(null!=n&&!w(a,n))if("object"!=typeof n||Array.isArray(n))s&&i.push({path:s,oldValue:a,newValue:n});else for(const o of Object.keys(n)){const c=[...e,o],l=s?s+"."+o:o,d=n[o],h=a&&"object"==typeof a?a[o]:void 0;d!==t?"object"==typeof d&&null!==d?r.push({pathArray:c,pathStr:l,orig:h,part:d}):w(h,d)||i.push({path:l,oldValue:h,newValue:d}):void 0===h&&a&&"object"==typeof a||i.push({path:l,oldValue:h,newValue:void 0})}}return i}}function b(e){const t=e?.deleteMarker||u;return function(e){const s=new Set,i=[{obj:e,currentPath:""}];for(;i.length>0;){const{obj:e,currentPath:r}=i.pop();if(null!=e&&"object"==typeof e&&!Array.isArray(e))for(const a of Object.keys(e)){const n=r?`${r}.${a}`:a;s.add(n);const o=n.split(".");if(o.length>1)for(let e=o.length-1;e>0;e--){const t=o.slice(0,e).join(".");if(s.has(t))break;s.add(t)}const c=e[a];"object"==typeof c&&null!==c&&c!==t&&i.push({obj:c,currentPath:n})}}return Array.from(s)}}var S=v(),E=b(),k=class{constructor(e,t,s){this.updateBus=t,this.diff=s,this.cache=structuredClone(e)}cache;get(e){return e?structuredClone(this.cache):this.cache}applyChanges(e,t=!1,s=!1,i=[]){if(t)return this.cache=s?structuredClone(e):e,this.notifyListeners([]),[];0===i.length&&(i=[e]);const r=this.get(!1),a=new Map;for(let e=0;e<i.length;e++){const t=i[e],s=this.diff(r,t);for(let e=0;e<s.length;e++){const t=s[e];a.set(t.path,t)}}const n=a.size?[...a.values()]:[];if(n.length>0){this.cache=s?structuredClone(e):e;const t=new Set;for(let e=0;e<n.length;e++){let s=n[e].path;for(;s&&!t.has(s);){t.add(s);const e=s.lastIndexOf(".");if(e<0)break;s=s.slice(0,e)}}this.notifyListeners(t)}return n}notifyListeners(e){for(const t of e)this.updateBus.emit({name:"update",payload:t})}};l(d());var x=class{constructor(e,t,s){this.eventBus=e,this.executionState=t,this.merge=s}middleware=[];blockingMiddleware=[];async executeBlocking(e,t){for(const{fn:s,name:i,id:r}of this.blockingMiddleware){const a={id:r,name:i,startTime:performance.now()};this.executionState.runningMiddleware={id:r,name:i,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:r,name:i,type:"blocking"});try{const n=await Promise.resolve(s(e,t));if(a.endTime=performance.now(),a.duration=a.endTime-a.startTime,!1===n)return a.blocked=!0,this.emitMiddlewareLifecycle("blocked",{id:r,name:i,duration:a.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),{blocked:!0};this.emitMiddlewareLifecycle("complete",{id:r,name:i,type:"blocking",duration:a.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:{...a,blocked:!1}})}catch(e){return a.endTime=performance.now(),a.duration=a.endTime-a.startTime,a.error=e instanceof Error?e:new Error(String(e)),a.blocked=!0,this.emitMiddlewareError(r,i,a.error,a.duration),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),{blocked:!0,error:a.error}}finally{this.executionState.runningMiddleware=null}}return{blocked:!1}}async executeTransform(e,t){let s=e,i=t;for(const{fn:e,name:r,id:a}of this.middleware){const n={id:a,name:r,startTime:performance.now()};this.executionState.runningMiddleware={id:a,name:r,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:a,name:r,type:"transform"});try{const o=await Promise.resolve(e(s,t));n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.blocked=!1,o&&"object"==typeof o&&(s=this.merge(s,o),i=this.merge(i,o)),this.emit(this.eventBus,{name:"middleware:executed",payload:n}),this.emitMiddlewareLifecycle("complete",{id:a,name:r,type:"transform",duration:n.duration})}catch(e){n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.error=e instanceof Error?e:new Error(String(e)),n.blocked=!1,this.emit(this.eventBus,{name:"middleware:executed",payload:n}),this.emitMiddlewareError(a,r,n.error,n.duration),console.error(`Middleware ${r} error:`,e)}finally{this.executionState.runningMiddleware=null}}return i}addMiddleware(e,t="unnamed-middleware"){const s=this.generateId();return this.middleware.push({fn:e,name:t,id:s}),this.updateExecutionState(),s}addBlockingMiddleware(e,t="unnamed-blocking-middleware"){const s=this.generateId();return this.blockingMiddleware.push({fn:e,name:t,id:s}),this.updateExecutionState(),s}removeMiddleware(e){const t=this.middleware.length+this.blockingMiddleware.length;return this.middleware=this.middleware.filter((t=>t.id!==e)),this.blockingMiddleware=this.blockingMiddleware.filter((t=>t.id!==e)),this.updateExecutionState(),this.middleware.length+this.blockingMiddleware.length<t}updateExecutionState(){this.executionState.middlewares=[...this.middleware.map((e=>e.name)),...this.blockingMiddleware.map((e=>e.name))]}emitMiddlewareLifecycle(e,t){this.emit(this.eventBus,{name:`middleware:${e}`,payload:{...t,timestamp:Date.now()}})}emitMiddlewareError(e,t,s,i){this.emit(this.eventBus,{name:"middleware:error",payload:{id:e,name:t,error:s,duration:i,timestamp:Date.now()}})}generateId(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var T=class{constructor(e,t,s,i){this.eventBus=e,this.coreState=t,this.instanceID=s,this.maxRetries=i?.maxRetries??3,this.retryDelay=i?.retryDelay??1e3}persistence;instanceID;persistenceReady=!1;backgroundQueue=[];isProcessingQueue=!1;maxRetries=3;retryDelay=1e3;queueProcessor;async initialize(e){e?await this.setPersistence(e):this.setPersistenceReady()}isReady(){return this.persistenceReady}handleStateChange(e,t){if(!this.persistence||0===e.length)return;const s={id:`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,state:structuredClone(t),changedPaths:[...e],timestamp:Date.now(),retries:0};this.backgroundQueue.push(s),this.scheduleQueueProcessing(),this.emit(this.eventBus,{name:"persistence:queued",payload:{taskId:s.id,changedPaths:e,queueSize:this.backgroundQueue.length,timestamp:s.timestamp}})}getQueueStatus(){return{queueSize:this.backgroundQueue.length,isProcessing:this.isProcessingQueue,oldestTask:this.backgroundQueue[0]?.timestamp}}async flush(){this.isProcessingQueue||await this.processQueue()}clearQueue(){const e=this.backgroundQueue.length;this.backgroundQueue=[],this.queueProcessor&&(clearTimeout(this.queueProcessor),this.queueProcessor=void 0),this.emit(this.eventBus,{name:"persistence:queue_cleared",payload:{clearedTasks:e,timestamp:Date.now()}})}scheduleQueueProcessing(){this.queueProcessor||this.isProcessingQueue||(this.queueProcessor=setTimeout((()=>{this.processQueue().catch((e=>{console.error("Queue processing failed:",e)}))}),10))}async processQueue(){if(!this.isProcessingQueue&&0!==this.backgroundQueue.length){this.isProcessingQueue=!0,this.queueProcessor=void 0;try{for(;this.backgroundQueue.length>0;){const e=this.backgroundQueue.shift();await this.processTask(e)}}finally{this.isProcessingQueue=!1}}}async processTask(e){try{await this.persistence.set(this.instanceID,e.state)?this.emit(this.eventBus,{name:"persistence:success",payload:{taskId:e.id,changedPaths:e.changedPaths,duration:Date.now()-e.timestamp,timestamp:Date.now()}}):await this.handleTaskFailure(e,new Error("Persistence returned false"))}catch(t){await this.handleTaskFailure(e,t)}}async handleTaskFailure(e,t){if(e.retries++,e.retries<=this.maxRetries){const s=this.retryDelay*Math.pow(2,e.retries-1);this.emit(this.eventBus,{name:"persistence:retry",payload:{taskId:e.id,attempt:e.retries,maxRetries:this.maxRetries,nextRetryIn:s,error:t,timestamp:Date.now()}}),setTimeout((()=>{this.backgroundQueue.unshift(e),this.scheduleQueueProcessing()}),s)}else this.emit(this.eventBus,{name:"persistence:failed",payload:{taskId:e.id,changedPaths:e.changedPaths,attempts:e.retries,error:t,timestamp:Date.now()}})}setPersistenceReady(){this.persistenceReady=!0,this.emit(this.eventBus,{name:"persistence:ready",payload:{timestamp:Date.now()}})}async setPersistence(e){this.persistence=e;try{const e=await this.persistence.get();e&&this.coreState.applyChanges(e)}catch(e){console.error("Failed to initialize persistence:",e),this.emit(this.eventBus,{name:"persistence:init_error",payload:{error:e,timestamp:Date.now()}})}finally{this.setPersistenceReady()}this.persistence.subscribe&&this.persistence.subscribe(this.instanceID,(async e=>{const t=this.coreState.applyChanges(e);t.length>0&&this.emit(this.eventBus,{name:"update:complete",payload:{changedPaths:t,source:"external",timestamp:Date.now()}})}))}dispose(){this.clearQueue(),this.isProcessingQueue=!1,this.persistenceReady=!1}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var C=class{constructor(e,t,s){this.eventBus=e,this.coreState=t,this.executionState=s}async execute(e){const t=this.coreState.get(!0);this.executionState.transactionActive=!0,this.emit(this.eventBus,{name:"transaction:start",payload:{timestamp:Date.now()}});try{const t=await Promise.resolve(e());return this.emit(this.eventBus,{name:"transaction:complete",payload:{timestamp:Date.now()}}),this.executionState.transactionActive=!1,t}catch(e){throw this.coreState.applyChanges(t,!0,!1),this.emit(this.eventBus,{name:"transaction:error",payload:{error:e instanceof Error?e:new Error(String(e)),timestamp:Date.now()}}),this.executionState.transactionActive=!1,e}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var A=class{updateCount=0;listenerExecutions=0;averageUpdateTime=0;largestUpdateSize=0;mostActiveListenerPaths=[];totalUpdates=0;blockedUpdates=0;averageUpdateDuration=0;middlewareExecutions=0;transactionCount=0;totalEventsFired=0;totalActionsDispatched=0;totalActionsSucceeded=0;totalActionsFailed=0;averageActionDuration=0;updateTimes=[];actionTimes=[];pathExecutionCounts=new Map;constructor(e){this.setupEventListeners(e)}getMetrics(){return{updateCount:this.updateCount,listenerExecutions:this.listenerExecutions,averageUpdateTime:this.averageUpdateTime,largestUpdateSize:this.largestUpdateSize,mostActiveListenerPaths:[...this.mostActiveListenerPaths],totalUpdates:this.totalUpdates,blockedUpdates:this.blockedUpdates,averageUpdateDuration:this.averageUpdateDuration,middlewareExecutions:this.middlewareExecutions,transactionCount:this.transactionCount,totalEventsFired:this.totalEventsFired,totalActionsDispatched:this.totalActionsDispatched,totalActionsSucceeded:this.totalActionsSucceeded,totalActionsFailed:this.totalActionsFailed,averageActionDuration:this.averageActionDuration}}setupEventListeners(e){const t=e.emit;e.emit=s=>(this.totalEventsFired++,t.call(e,s)),e.subscribe("update:complete",(e=>{if(this.totalUpdates++,e.blocked)this.blockedUpdates++;else{if(e.duration){this.updateTimes.push(e.duration),this.updateTimes.length>100&&this.updateTimes.shift();const t=this.updateTimes.reduce(((e,t)=>e+t),0)/this.updateTimes.length;this.averageUpdateTime=t,this.averageUpdateDuration=t}e.deltas?.length&&(this.updateCount++,this.largestUpdateSize=Math.max(this.largestUpdateSize,e.deltas.length),e.deltas.forEach((e=>{const t=this.pathExecutionCounts.get(e.path)||0;this.pathExecutionCounts.set(e.path,t+1)})),this.mostActiveListenerPaths=Array.from(this.pathExecutionCounts.entries()).sort((([,e],[,t])=>t-e)).slice(0,5).map((([e])=>e)))}})),e.subscribe("middleware:start",(()=>{this.middlewareExecutions++})),e.subscribe("transaction:start",(()=>{this.transactionCount++})),e.subscribe("action:start",(()=>{this.totalActionsDispatched++})),e.subscribe("action:complete",(e=>{this.totalActionsSucceeded++,e.duration&&(this.actionTimes.push(e.duration),this.actionTimes.length>100&&this.actionTimes.shift(),this.averageActionDuration=this.actionTimes.reduce(((e,t)=>e+t),0)/this.actionTimes.length)})),e.subscribe("action:error",(()=>{this.totalActionsFailed++}))}reset(){this.updateCount=0,this.listenerExecutions=0,this.averageUpdateTime=0,this.largestUpdateSize=0,this.mostActiveListenerPaths=[],this.totalUpdates=0,this.blockedUpdates=0,this.averageUpdateDuration=0,this.middlewareExecutions=0,this.transactionCount=0,this.totalEventsFired=0,this.totalActionsDispatched=0,this.totalActionsSucceeded=0,this.totalActionsFailed=0,this.averageActionDuration=0,this.updateTimes=[],this.actionTimes=[],this.pathExecutionCounts.clear()}getDetailedMetrics(){return{pathExecutionCounts:new Map(this.pathExecutionCounts),recentUpdateTimes:[...this.updateTimes],successRate:this.totalUpdates>0?(this.totalUpdates-this.blockedUpdates)/this.totalUpdates:1,averagePathsPerUpdate:this.updateCount>0?Array.from(this.pathExecutionCounts.values()).reduce(((e,t)=>e+t),0)/this.updateCount:0}}dispose(){this.reset()}};l(d());var P=class extends Error{constructor(){super("Action Cancelled by Debounce"),this.name="ActionCancelledError"}},M=class{constructor(e,t){this.eventBus=e,this.set=t}actions=new Map;register(t){const s=t.debounce,i={name:t.name,id:e(),action:t.fn,debounce:s?{...s,condition:s.condition||(()=>!0)}:void 0};return this.actions.set(t.name,i),()=>{const e=this.actions.get(t.name);e?.debounce?.timer&&clearTimeout(e.debounce.timer),this.actions.delete(t.name)}}async dispatch(e,...t){const s=this.actions.get(e);if(!s)throw new Error(`unknown action ${e}`);const{id:i,action:r,debounce:a}=s;return!a||void 0===a.delay||a.delay<=0||a.condition&&!a.condition(a.args,t)?this.executeAction(e,i,r,t):(a.timer&&(clearTimeout(a.timer),a.reject?.(new P)),new Promise(((s,n)=>{a.resolve=s,a.reject=n,a.timer=setTimeout((async()=>{a.timer=void 0,a.resolve=void 0,a.reject=void 0;try{const a=await this.executeAction(e,i,r,t);s(a)}catch(e){n(e)}}),a.delay)})))}async executeAction(e,t,s,i){const r=performance.now();this.emit(this.eventBus,{name:"action:start",payload:{actionId:t,name:e,params:i||[],timestamp:r}});try{const a=await this.set((e=>s(e,...i)),{actionId:t}),n=this.actions.get(e);n?.debounce&&(n.debounce.args=i);const o=performance.now();return this.emit(this.eventBus,{name:"action:complete",payload:{actionId:t,name:e,params:i,startTime:r,endTime:o,duration:o-r,result:a}}),a}catch(s){const a=performance.now();throw this.emit(this.eventBus,{name:"action:error",payload:{actionId:t,name:e,params:i,startTime:r,endTime:a,duration:a-r,error:s}}),s}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},B=class{coreState;middlewareEngine;persistenceHandler;transactionManager;metricsCollector;selectorManager;actionManager;updateQueue=Promise.resolve();updateBus=(0,h.createEventBus)();eventBus=(0,h.createEventBus)();executionState;instanceID=e();merge;diff;constructor(e,t,s=u,i){this.executionState={executing:!1,changes:null,pendingChanges:[],middlewares:[],runningMiddleware:null,transactionActive:!1},this.merge=m({deleteMarker:s}),this.diff=v({deleteMarker:s}),this.coreState=new k(e,this.updateBus,this.diff),this.middlewareEngine=new x(this.eventBus,this.executionState,this.merge),this.persistenceHandler=new T(this.eventBus,this.coreState,this.instanceID,{maxRetries:i?.persistenceMaxRetries,retryDelay:i?.persistenceRetryDelay}),this.transactionManager=new C(this.eventBus,this.coreState,this.executionState),this.metricsCollector=new A(this.eventBus),this.actionManager=new M(this.eventBus,this.set.bind(this)),this.persistenceHandler.initialize(t),this.setupPersistenceListener(),this.selectorManager=new g(this.get.bind(this),this.eventBus)}isReady(){return this.persistenceHandler.isReady()}state(){return this.executionState}get(e){return this.coreState.get(e??!1)}select(e){return this.selectorManager.createReactiveSelector(e)}register(e){return this.actionManager.register(e)}async dispatch(e,...t){return this.actionManager.dispatch(e,...t)}async set(e,t={}){const s=this.updateQueue.then((()=>this._performUpdate(e,t)));return this.updateQueue=s.catch((()=>{})),s}async _performUpdate(e,t){this.executionState.executing=!0;const s=performance.now();this.emit(this.eventBus,{name:"update:start",payload:{timestamp:s,actionId:t.actionId}});try{if(t.force){const t=this.get(!1),s="function"==typeof e?e(t):e;return this.coreState.applyChanges(s,!0),s}let i;const r=this.get(!1);if("function"==typeof e){const t=e(r);i=t instanceof Promise?await t:t}else i=e;const a=await this.middlewareEngine.executeBlocking(r,i);if(a.blocked)throw a.error||new Error("Update blocked by middleware");const n=this.merge(r,i),o=await this.middlewareEngine.executeTransform(n,i),c=this.merge(n,o),l=this.coreState.applyChanges(c,!1,!1,[i,o]),d=performance.now(),h=this.get(!1);return this.emit(this.eventBus,{name:"update:complete",payload:{deltas:l,duration:d-s,timestamp:Date.now(),actionId:t.actionId,newState:h}}),h}catch(e){throw this.emit(this.eventBus,{name:"update:complete",payload:{blocked:!0,error:e,timestamp:Date.now(),actionId:t.actionId,newState:this.get(!1)}}),e}finally{this.executionState.executing=!1,this.executionState.changes=null,this.executionState.runningMiddleware=null,this.executionState.pendingChanges=[]}}setupPersistenceListener(){this.updateBus.subscribe("update",(e=>{e&&this.persistenceHandler.isReady()&&this.persistenceHandler.handleStateChange([e],this.get(!1))}))}watch(e,t){const s=Array.isArray(e)?e:[e],i=""===e||0===s.length;return this.updateBus.subscribe("update",(e=>{(i||s.includes(e))&&(t(this.get(!1)),this.metricsCollector.listenerExecutions++)}))}subscribe(e,t){return this.watch(e,t)}id(){return this.instanceID}async transaction(e){return this.transactionManager.execute(e)}use(e){const t=(e.block?this.middlewareEngine.addBlockingMiddleware:this.middlewareEngine.addMiddleware).bind(this.middlewareEngine)(e.action,e.name);return()=>this.middlewareEngine.removeMiddleware(t)}metrics(){return this.metricsCollector.getMetrics()}on(e,t){return this.eventBus.subscribe(e,t)}onStoreEvent(e,t){return this.eventBus.subscribe(e,t)}getPersistenceStatus(){return this.persistenceHandler.getQueueStatus()}async flushPersistence(){return this.persistenceHandler.flush()}clearPersistenceQueue(){this.persistenceHandler.clearQueue()}dispose(){this.persistenceHandler.dispose(),this.metricsCollector.dispose?.(),this.selectorManager.dispose?.()}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},D=(e=>(e.Singleton="singleton",e.Transient="transient",e))(D||{}),H=class{artifacts=new Map;resolvingStack=[];listeners=new Map;getState;subscribe;constructor(e){this.getState=(...t)=>e.get(...t),this.subscribe=(...t)=>e.watch(...t)}watch(e){return{id:e,get:()=>{const t=this.artifacts.get(e);return t&&(void 0!==t.instance||t.error)?this.packageArtifact(t):null},subscribe:t=>{this.listeners.has(e)||this.listeners.set(e,new Set);const s=this.listeners.get(e);return s.add(t),()=>s.delete(t)}}}get(e){return this.artifacts.get(e)?.instance}register(e){const{key:t,factory:s,scope:i="singleton",lazy:r=!0}=e;this.artifacts.has(t)&&(console.warn(`[ArtifactContainer] Warning: Overwriting existing artifact "${t}".`),this.disposeArtifact(t));const a={key:t,factory:s,scope:i,lazy:r,cleanupFunctions:[],stateDependencies:new Set,artifactDependencies:new Set,dependents:new Set};return this.artifacts.set(t,a),r||"singleton"!==i||this.resolve(t).catch((e=>{console.error(`[ArtifactContainer] Eager load failed for "${t}":`,e)})),async()=>{await this.unregister(t)}}async unregister(e){this.artifacts.has(e)&&(await this.disposeArtifact(e),this.artifacts.delete(e))}async resolve(e){if(this.resolvingStack.includes(e))throw new Error(`[ArtifactContainer] Circular dependency: ${this.resolvingStack.join(" -> ")} -> ${e}`);this.resolvingStack.push(e);try{const t=this.artifacts.get(e);if(!t)throw new Error(`[ArtifactContainer] Artifact with key "${e}" not found.`);if("transient"===t.scope){const e=await this.createArtifactInstance(t,new Set,new Set);return{instance:e.instance,cleanup:e.cleanup,error:e.error,invalidate:async()=>{}}}if(void 0!==t.instance||void 0!==t.error)return this.packageArtifact(t);if(t.initializationPromise)try{return await t.initializationPromise,this.packageArtifact(t)}catch(e){return this.packageArtifact(t)}const s=(async()=>{try{const e=new Set,s=new Set,i=await this.createArtifactInstance(t,e,s);return this.updateGraph(t,e,s),i.error&&(t.error=i.error),i.instance}catch(e){throw t.error=e,t.initializationPromise=void 0,e}})();t.initializationPromise=s;try{await s}catch(e){}return this.packageArtifact(t)}finally{this.resolvingStack.pop()}}packageArtifact(e){return{instance:e.instance,cleanup:this.createCompositeCleanup(e.cleanupFunctions),error:e.error,invalidate:async t=>this.invalidate(e.key,t)}}async createArtifactInstance(e,t,s){const i=[];let r=!0;i.push((()=>{r=!1}));const a={state:this.getState,current:e.instance,use:async i=>i({resolve:async s=>{if(s===e.key)throw new Error(`[ArtifactContainer] Self-dependency detected in "${e.key}"`);return t.add(s),this.resolve(s)},select:e=>(y(e).forEach((e=>s.add(e))),e(this.getState()))}),onCleanup:e=>{i.push(e)},yield:t=>{r?"transient"!==e.scope?(e.instance=t,e.error=void 0,this.processYieldPropagation(e.key)):console.warn(`[ArtifactContainer] Yield ignored on transient artifact "${e.key}"`):console.warn(`[ArtifactContainer] Ignored yield on disposed artifact "${e.key}"`)}};let n,o;try{n=await e.factory(a)}catch(e){o=e,n=void 0}"singleton"===e.scope&&(void 0!==n&&(e.instance=n),e.cleanupFunctions=i);return{instance:"singleton"===e.scope?e.instance:n,cleanup:this.createCompositeCleanup(i),error:o}}async processYieldPropagation(e){const t=this.artifacts.get(e);if(t&&(void 0!==t.instance||t.error))try{const s=Array.from(t.dependents);await Promise.all(s.map((e=>this.invalidate(e,!1)))),this.notifyListeners(e)}catch(t){console.error(`[ArtifactContainer] Yield propagation failed for "${e}":`,t)}}updateGraph(e,t,s){e.artifactDependencies.forEach((t=>{const s=this.artifacts.get(t);s&&s.dependents.delete(e.key)})),e.artifactDependencies=t,t.forEach((t=>{const s=this.artifacts.get(t);s&&s.dependents.add(e.key)}));const i=e.stateSubscriptionCleanup;e.stateDependencies=s,s.size>0?e.stateSubscriptionCleanup=this.subscribe(Array.from(s),(()=>this.invalidate(e.key))):e.stateSubscriptionCleanup=void 0,i&&i(),this.detectCycles(e.key),this.notifyListeners(e.key)}async invalidate(e,t=!1){const s=this.artifacts.get(e);if(!s)return;if(s.initializationPromise)try{await s.initializationPromise}catch(e){}if(s.rebuildPromise)return s.rebuildPromise;const i=(async()=>{try{const i=Array.from(s.dependents);await Promise.all(i.map((e=>this.invalidate(e,t)))),await this.disposeInstance(s),!t&&s.lazy||await this.resolve(e).catch((t=>{console.error(`[ArtifactContainer] Rebuild failed for "${e}":`,t)}))}finally{s.rebuildPromise=void 0}})();return s.rebuildPromise=i,i}async disposeInstance(e){if(e.stateSubscriptionCleanup&&(e.stateSubscriptionCleanup(),e.stateSubscriptionCleanup=void 0),e.cleanupFunctions.length>0)for(let t=e.cleanupFunctions.length-1;t>=0;t--)try{await e.cleanupFunctions[t]()}catch(t){console.error(`[ArtifactContainer] Cleanup error for "${e.key}":`,t)}e.instance=void 0,e.error=void 0,e.cleanupFunctions=[],e.initializationPromise=void 0,this.notifyListeners(e.key)}async disposeArtifact(e){const t=this.artifacts.get(e);t&&(t.rebuildPromise&&await t.rebuildPromise,await this.disposeInstance(t),t.artifactDependencies.forEach((t=>{const s=this.artifacts.get(t);s&&s.dependents.delete(e)})))}createCompositeCleanup(e){if(0!==e.length)return async()=>{for(let t=e.length-1;t>=0;t--)try{await e[t]()}catch(e){}}}notifyListeners(e){const t=this.listeners.get(e);t&&t.forEach((e=>e()))}detectCycles(e){const t=new Set,s=new Set,i=e=>{if(s.has(e))throw new Error(`[ArtifactContainer] Circular dependency: ${Array.from(s).join(" -> ")} -> ${e}`);if(t.has(e))return;t.add(e),s.add(e);const r=this.artifacts.get(e);r&&r.artifactDependencies.forEach((e=>i(e))),s.delete(e)};i(e)}dispose(){this.artifacts.forEach(((e,t)=>this.disposeArtifact(t))),this.artifacts.clear()}isLoading(e){return this.resolvingStack.includes(e)||void 0!==this.artifacts.get(e)?.initializationPromise}},L=class{store;eventHistory=[];stateHistory=[];unsubscribers=[];isTimeTraveling=!1;devTools=null;middlewareExecutions=[];activeTransactionCount=0;activeBatches=new Set;maxEvents;maxStateHistory;enableConsoleLogging;isSilent;logEvents;performanceThresholds;constructor(e,t={}){this.store=e,this.maxEvents=t.maxEvents??500,this.maxStateHistory=t.maxStateHistory??20,this.enableConsoleLogging=t.enableConsoleLogging??!1,this.isSilent=t.silent??!1,this.logEvents={updates:t.logEvents?.updates??!0,middleware:t.logEvents?.middleware??!0,transactions:t.logEvents?.transactions??!0,actions:t.logEvents?.actions??!0,selectors:t.logEvents?.selectors??!0},this.performanceThresholds={updateTime:t.performanceThresholds?.updateTime??50,middlewareTime:t.performanceThresholds?.middlewareTime??20},this.recordStateSnapshot([]),this.setupEventListeners()}_consoleLog(e,...t){this.isSilent||"function"==typeof console[e]&&console[e](...t)}setupEventListeners(){const e=["update:start","update:complete","middleware:start","middleware:complete","middleware:error","middleware:blocked","transaction:start","transaction:complete","transaction:error","middleware:executed","action:start","action:complete","action:error","selector:accessed"];for(const t of e){const e=t.startsWith("update")&&this.logEvents.updates||t.startsWith("middleware")&&this.logEvents.middleware||t.startsWith("transaction")&&this.logEvents.transactions||t.startsWith("action")&&this.logEvents.actions||t.startsWith("selector")&&this.logEvents.selectors;this.unsubscribers.push(this.store.onStoreEvent(t,(s=>{"update:complete"!==t||s.blocked||this.isTimeTraveling||this.recordStateSnapshot(s.deltas),"middleware:executed"===t?this.middlewareExecutions.push(s):"transaction:start"===t?this.activeTransactionCount++:"transaction:complete"!==t&&"transaction:error"!==t||(this.activeTransactionCount=Math.max(0,this.activeTransactionCount-1)),s.batchId&&(t.endsWith("start")?this.activeBatches.add(s.batchId):(t.endsWith("complete")||t.endsWith("error"))&&this.activeBatches.delete(s.batchId)),this.recordEvent(t,s),this.enableConsoleLogging&&e&&this._log(t,s),this._checkPerformance(t,s)})))}}recordStateSnapshot(e){const t={state:this.store.get(!0),timestamp:Date.now(),deltas:e};this.stateHistory.unshift(t),this.stateHistory.length>this.maxStateHistory&&this.stateHistory.pop()}recordEvent(e,t){const s={type:e,timestamp:Date.now(),data:structuredClone(t)};this.eventHistory.unshift(s),this.eventHistory.length>this.maxEvents&&this.eventHistory.pop()}getEventHistory(){return structuredClone(this.eventHistory)}getStateHistory(){return structuredClone(this.stateHistory)}getMiddlewareExecutions(){return this.middlewareExecutions}getTransactionStatus(){return{activeTransactions:this.activeTransactionCount,activeBatches:Array.from(this.activeBatches)}}createLoggingMiddleware(e={}){const{logLevel:t="debug",logUpdates:s=!0}=e;return(e,i)=>{if(s){(console[t]||console.log)("State Update:",i)}return i}}createValidationMiddleware(e){return(t,s)=>{const i=e(t,s);return"boolean"==typeof i?i:(!i.valid&&i.reason&&this._consoleLog("warn","Validation failed:",i.reason),i.valid)}}getRecentChanges(e=5){const t=[],s=Math.min(e,this.stateHistory.length);for(let e=0;e<s;e++){const s=this.stateHistory[e];if(!s.deltas||0===s.deltas.length)continue;const i={},r={},a=(e,t,s)=>{t.reduce(((e,i,r)=>(r===t.length-1?e[i]=s:e[i]=e[i]??{},e[i])),e)};for(const e of s.deltas){const t=e.path.split(".");a(i,t,e.oldValue),a(r,t,e.newValue)}t.push({timestamp:s.timestamp,changedPaths:s.deltas.map((e=>e.path)),from:i,to:r})}return t}clearHistory(){this.eventHistory=[],this.stateHistory.length>0&&(this.stateHistory=[this.stateHistory[0]])}getHistoryForAction(e){return this.eventHistory.filter((t=>t.data?.actionId===e))}async replay(e){const t=this.eventHistory.filter((e=>"update:start"===e.type))[e];t?.data.update?(this._consoleLog("log",`Replaying event at index ${e}:`,t),await this.store.set(t.data.update,{force:!0})):this._consoleLog("warn",`No replayable event found at index ${e}.`)}createTimeTravel(){let e=0,t=[];const s=this.store.onStoreEvent("update:complete",(s=>{this.isTimeTraveling||s.blocked||(t=[],e=0)}));this.unsubscribers.push(s);const i=()=>this.stateHistory.length,r=()=>e<i()-1,a=()=>t.length>0;return{canUndo:r,canRedo:a,undo:async()=>{if(!r())return;t.unshift(this.stateHistory[e]),e++;const s=this.stateHistory[e].state;this.isTimeTraveling=!0,await this.store.set({...s},{force:!0}),this.isTimeTraveling=!1},redo:async()=>{if(!a())return;const s=t.shift();e--,this.isTimeTraveling=!0,await this.store.set({...s.state},{force:!0}),this.isTimeTraveling=!1},length:i,clear:()=>{t=[],e=0}}}async saveSession(e){const t=this.store.id(),s={eventHistory:this.eventHistory,stateHistory:this.stateHistory};return Promise.resolve(e.set(t,s))}async loadSession(e){const t=await Promise.resolve(e.get());return!!t&&(this.eventHistory=t.eventHistory||[],this.stateHistory=t.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),!0)}exportSession(){const e={eventHistory:this.eventHistory,stateHistory:this.stateHistory},t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),s=URL.createObjectURL(t),i=document.createElement("a");i.href=s,i.download=`store-observer-session-${(new Date).toISOString()}.json`,i.click(),URL.revokeObjectURL(s)}importSession(e){return new Promise(((t,s)=>{const i=new FileReader;i.onload=async e=>{try{const s=JSON.parse(e.target?.result);this.eventHistory=s.eventHistory||[],this.stateHistory=s.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),t()}catch(e){s(e)}},i.onerror=e=>s(e),i.readAsText(e)}))}disconnect(){this.unsubscribers.forEach((e=>e())),this.unsubscribers=[],this.devTools?.disconnect(),this.clearHistory()}_log(e,t){const s=new Date(t.timestamp||Date.now()).toISOString().split("T")[1].replace("Z","");if("update:start"===e)this._consoleLog("group",`%c⚡ Store Update Started [${s}]`,"color: #4a6da7");else if("update:complete"===e){if(t.blocked)this._consoleLog("warn",`%c✋ Update Blocked [${s}]`,"color: #bf8c0a",t.error);else{const e=t.deltas||[];e.length>0&&(this._consoleLog("log",`%c✅ Update Complete [${s}] - ${e.length} paths changed in ${t.duration?.toFixed(2)}ms`,"color: #2a9d8f"),this._consoleLog("table",e.map((e=>({path:e.path,oldValue:e.oldValue,newValue:e.newValue})))))}this._consoleLog("groupEnd")}else"middleware:start"===e?this._consoleLog("debug",`%c◀ Middleware "${t.name}" started [${s}] (${t.type})`,"color: #8c8c8c"):"middleware:complete"===e?this._consoleLog("debug",`%c▶ Middleware "${t.name}" completed [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #7c9c7c"):"middleware:error"===e?this._consoleLog("error",`%c❌ Middleware "${t.name}" error [${s}]:`,"color: #e63946",t.error):"middleware:blocked"===e?this._consoleLog("warn",`%c🛑 Middleware "${t.name}" blocked update [${s}]`,"color: #e76f51"):"transaction:start"===e?this._consoleLog("group",`%c📦 Transaction Started [${s}]`,"color: #6d597a"):"transaction:complete"===e?(this._consoleLog("log",`%c📦 Transaction Complete [${s}]`,"color: #355070"),this._consoleLog("groupEnd")):"transaction:error"===e?(this._consoleLog("error",`%c📦 Transaction Error [${s}]:`,"color: #e56b6f",t.error),this._consoleLog("groupEnd")):"action:start"===e?this._consoleLog("group",`%c🚀 Action "${t.name}" Started [${s}]`,"color: #9b59b6",{params:t.params}):"action:complete"===e?(this._consoleLog("log",`%c✔️ Action "${t.name}" Complete [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #2ecc71"),this._consoleLog("groupEnd")):"action:error"===e?(this._consoleLog("error",`%c🔥 Action "${t.name}" Error [${s}]:`,"color: #e74c3c",t.error),this._consoleLog("groupEnd")):"selector:accessed"===e&&this._consoleLog("debug",`%c👀 Selector Accessed [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #f1c40f",{accessedPaths:t.accessedPaths,selectorId:t.selectorId})}_checkPerformance(e,t){this.enableConsoleLogging&&("update:complete"===e&&!t.blocked&&t.duration>this.performanceThresholds.updateTime&&this._consoleLog("warn",`%c⚠️ Slow update detected [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{deltas:t.deltas,threshold:this.performanceThresholds.updateTime}),"middleware:complete"===e&&t.duration>this.performanceThresholds.middlewareTime&&this._consoleLog("warn",`%c⚠️ Slow middleware "${t.name}" [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{threshold:this.performanceThresholds.middlewareTime}))}};export{M as ActionManager,H as ArtifactContainer,D as ArtifactScope,u as DELETE_SYMBOL,B as ReactiveDataStore,L as StoreObserver,b as createDerivePaths,v as createDiff,m as createMerge,E as derivePaths,S as diff,f as merge,p as shallowClone};
|
|
1
|
+
import{v4 as e}from"uuid";var t,s,i=Object.create,r=Object.defineProperty,a=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,o=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t,s)=>(s=null!=e?i(o(e)):{},((e,t,s,i)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let o of n(t))c.call(e,o)||o===s||r(e,o,{get:()=>t[o],enumerable:!(i=a(t,o))||i.enumerable});return e})(e&&e.__esModule?s:r(s,"default",{value:e,enumerable:!0}),e)),d=(t={"src/store/node_modules/@asaidimu/events/index.js"(e,t){var s,i=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,o={};((e,t)=>{for(var s in t)i(e,s,{get:t[s],enumerable:!0})})(o,{createEventBus:()=>c}),t.exports=(s=o,((e,t,s,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let c of a(t))n.call(e,c)||c===s||i(e,c,{get:()=>t[c],enumerable:!(o=r(t,c))||o.enumerable});return e})(i({},"__esModule",{value:!0}),s));var c=(e={async:!1,batchSize:1e3,batchDelay:16,errorHandler:e=>console.error("EventBus Error:",e),crossTab:!1,channelName:"event-bus-channel"})=>{const t=new Map;let s=[],i=0,r=0;const a=new Map,n=new Map;let o=null;e.crossTab&&"undefined"!=typeof BroadcastChannel?o=new BroadcastChannel(e.channelName):e.crossTab&&console.warn("BroadcastChannel is not supported in this browser. Cross-tab notifications are disabled.");const c=(e,t)=>{i++,r+=t,a.set(e,(a.get(e)||0)+1)},l=()=>{const t=s;s=[],t.forEach((({name:t,payload:s})=>{const i=performance.now();try{(n.get(t)||[]).forEach((e=>e(s)))}catch(i){e.errorHandler({...i,eventName:t,payload:s})}c(t,performance.now()-i)}))},d=(()=>{let t;return()=>{clearTimeout(t),t=setTimeout(l,e.batchDelay)}})(),h=e=>{const s=t.get(e);s?n.set(e,Array.from(s)):n.delete(e)};return o&&(o.onmessage=e=>{const{name:t,payload:s}=e.data;(n.get(t)||[]).forEach((e=>e(s)))}),{subscribe:(e,s)=>{t.has(e)||t.set(e,new Set);const i=t.get(e);return i.add(s),h(e),()=>{i.delete(s),0===i.size?(t.delete(e),n.delete(e)):h(e)}},emit:({name:t,payload:i})=>{if(e.async)return s.push({name:t,payload:i}),s.length>=e.batchSize?l():d(),void(o&&o.postMessage({name:t,payload:i}));const r=performance.now();try{(n.get(t)||[]).forEach((e=>e(i))),o&&o.postMessage({name:t,payload:i})}catch(s){e.errorHandler({...s,eventName:t,payload:i})}c(t,performance.now()-r)},getMetrics:()=>({totalEvents:i,activeSubscriptions:Array.from(t.values()).reduce(((e,t)=>e+t.size),0),eventCounts:a,averageEmitDuration:i>0?r/i:0}),clear:()=>{t.clear(),n.clear(),s=[],i=0,r=0,a.clear(),o&&(o.close(),o=null)}}}}},function(){return s||(0,t[n(t)[0]])((s={exports:{}}).exports,s),s.exports}),h=l(d()),u=Symbol.for("delete"),p=e=>Array.isArray(e)?[...e]:{...e};function m(e){const t=e?.deleteMarker||u;return function(e,s){if("object"!=typeof e||null===e)return"object"==typeof s&&null!==s?a(s):s===t?{}:s;if("object"!=typeof s||null===s)return e;const i=p(e),r=[{target:i,source:s}];for(;r.length>0;){const{target:e,source:s}=r.pop();for(const i of Object.keys(s)){if(!Object.prototype.hasOwnProperty.call(s,i))continue;const n=s[i];if(n!==t)if(Array.isArray(n))e[i]=n.map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:a(e)));else if("object"==typeof n&&null!==n){const t=i in e&&"object"==typeof e[i]&&null!==e[i]?e[i]:{};e[i]=p(t),r.push({target:e[i],source:n})}else e[i]=n;else delete e[i]}}return i;function a(e){if(null==e)return e;if(Array.isArray(e))return e.filter((e=>e!==t)).map((e=>"object"!=typeof e||null===e||Array.isArray(e)?e===t?void 0:e:a(e)));if("object"==typeof e){const s={};for(const[i,r]of Object.entries(e))if(r!==t)if("object"==typeof r&&null!==r){const e=a(r);void 0!==e&&(s[i]=e)}else s[i]=r;return s}return e===t?void 0:e}}}var f=m();l(d());var g=class{reactiveSelectors=new Map;reactiveSelectorCache=new WeakMap;pathBasedCache=new Map;getState;eventBus;unsubscribeFromStore;constructor(e,t){this.getState=e,this.eventBus=t,this.unsubscribeFromStore=this.eventBus.subscribe("update:complete",this.handleStoreUpdate)}handleStoreUpdate=e=>{const t=e.deltas.map((e=>e.path));this.reEvaluateReactiveSelectors(t)};reEvaluateReactiveSelectors=e=>{this.reactiveSelectors.forEach((t=>{if(t.accessedPaths.some((t=>e.some((e=>e.startsWith(t)||t.startsWith(e)))))){let e;try{e=t.selector(this.getState())}catch{e=void 0}e!==t.lastResult&&(t.lastResult=e,t.subscribers.forEach((e=>e(t.lastResult))),this.eventBus.emit({name:"selector:changed",payload:{selectorId:t.id,newResult:e,timestamp:performance.now()}}))}}))};createReactiveSelector(e){const t=this.reactiveSelectorCache.get(e);if(t)return t;const s=y(e);this.validateSimpleSelector(e,s);const i=s.sort().join("|"),r=this.pathBasedCache.get(i);if(r)return this.reactiveSelectorCache.set(e,r),r;const a=`selector-${Math.random().toString(36).substring(2,9)}`,n=e(this.getState()),o={id:a,selector:e,lastResult:n,accessedPaths:s,subscribers:new Set,reactiveSelectorInstance:null},c={get:()=>o.lastResult,subscribe:t=>(o.subscribers.add(t),()=>{o.subscribers.delete(t),queueMicrotask((()=>{0===o.subscribers.size&&(this.reactiveSelectors.delete(a),this.reactiveSelectorCache.delete(e),this.pathBasedCache.delete(i))}))}),id:a};return o.reactiveSelectorInstance=c,this.reactiveSelectors.set(a,o),this.reactiveSelectorCache.set(e,c),this.pathBasedCache.set(i,c),this.eventBus.emit({name:"selector:accessed",payload:{selectorId:a,accessedPaths:s,duration:0,timestamp:performance.now()}}),c}validateSimpleSelector(e,t){const s=e.toString(),i=s.match(/=>\s*(.+)$/),r=i?i[1].trim():s,a=["map","filter","reduce","forEach","find","findIndex","some","every","includes","flatMap","flat","slice","splice"];for(const e of a)if(new RegExp(`\\.${e}\\s*\\(`).test(r))throw new Error(`Selector contains .${e}() which is not allowed. Selectors must be simple property accessors only. Use store effects for transformations.`);if(/\?[^:]*:/.test(r))throw new Error("Selector contains ternary operator (? :) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/\bif\s*\(|\bswitch\s*\(/.test(r))throw new Error("Selector contains conditional logic (if/switch) which is not allowed. Selectors must be simple property accessors only. Use store effects for conditional transformations.");if(/(?<![.\w])[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/.test(r))throw new Error("Selector contains function calls which are not allowed. Selectors must be simple property accessors only.");const n=/[+\-*/%&|^](?!=)|[<>!]=?(?!=)/.test(r),o=/\[.*\]/.test(r);if(n&&!o)throw new Error("Selector contains operations (+, -, *, /, etc.) which are not allowed. Selectors must be simple property accessors only. Use store effects for computed values.");if(0===t.length)throw new Error("Selector doesn't access any state properties. Selectors must access at least one state property.")}dispose(){this.unsubscribeFromStore(),this.reactiveSelectors.clear(),this.pathBasedCache.clear()}createMemoizedSelector(e){const t=y(e);this.validateSimpleSelector(e,t);let s,i=null;return r=>{const a=this.extractStateSubset(r,t);return i===a||(i=a,s=e(r)),s}}extractStateSubset(e,t){const s=[];for(const i of t){const t=i.split(".");let r=e;for(const e of t){if(null==r){s.push(void 0);break}r=r[e]}s.push(r)}return s}};function y(e,t="."){const s=new Set,i=(e=[])=>new Proxy({},{get:(r,a)=>{if("symbol"==typeof a)return;const n=[...e,a],o=n.join(t);return s.add(o),i(n)}});try{e(i())}catch(e){throw new Error(`Selector failed during path analysis. This usually means the selector is too complex. Selectors must be simple property accessors only. Error: ${e instanceof Error?e.message:String(e)}`)}const r=Array.from(s);return r.filter((e=>!r.some((s=>s!==e&&s.startsWith(e+t)))))}function w(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(e.constructor!==t.constructor)return!1;let s,i;if(Array.isArray(e)){if(s=e.length,s!=t.length)return!1;for(i=s;i-- >0;)if(!w(e[i],t[i]))return!1;return!0}const[r,a]=[Object.keys(e),Object.keys(t)];if(s=r.length,s!==a.length)return!1;for(i=s;i-- >0;){const s=r[i];if(!Object.prototype.hasOwnProperty.call(t,s)||!w(e[s],t[s]))return!1}return!0}return e!=e&&t!=t}function v(e){const t=e?.deleteMarker||u;return function(e,s){const i=[],r=[{pathArray:[],pathStr:"",orig:e||{},part:s||{}}];for(;r.length>0;){const{pathArray:e,pathStr:s,orig:a,part:n}=r.pop();if(null!=n&&!w(a,n))if("object"!=typeof n||Array.isArray(n))s&&i.push({path:s,oldValue:a,newValue:n});else for(const o of Object.keys(n)){const c=[...e,o],l=s?s+"."+o:o,d=n[o],h=a&&"object"==typeof a?a[o]:void 0;d!==t?"object"==typeof d&&null!==d?r.push({pathArray:c,pathStr:l,orig:h,part:d}):w(h,d)||i.push({path:l,oldValue:h,newValue:d}):void 0===h&&a&&"object"==typeof a||i.push({path:l,oldValue:h,newValue:void 0})}}return i}}function b(e){const t=e?.deleteMarker||u;return function(e){const s=new Set,i=[{obj:e,currentPath:""}];for(;i.length>0;){const{obj:e,currentPath:r}=i.pop();if(null!=e&&"object"==typeof e&&!Array.isArray(e))for(const a of Object.keys(e)){const n=r?`${r}.${a}`:a;s.add(n);const o=n.split(".");if(o.length>1)for(let e=o.length-1;e>0;e--){const t=o.slice(0,e).join(".");if(s.has(t))break;s.add(t)}const c=e[a];"object"==typeof c&&null!==c&&c!==t&&i.push({obj:c,currentPath:n})}}return Array.from(s)}}var S=v(),k=b(),E=class{constructor(e,t,s){this.updateBus=t,this.diff=s,this.cache=structuredClone(e)}cache;get(e){return e?structuredClone(this.cache):this.cache}applyChanges(e,t=!1,s=!1,i=[]){if(t)return this.cache=s?structuredClone(e):e,this.notifyListeners([]),[];0===i.length&&(i=[e]);const r=this.get(!1),a=new Map;for(let e=0;e<i.length;e++){const t=i[e],s=this.diff(r,t);for(let e=0;e<s.length;e++){const t=s[e];a.set(t.path,t)}}const n=a.size?[...a.values()]:[];if(n.length>0){this.cache=s?structuredClone(e):e;const t=new Set;for(let e=0;e<n.length;e++){let s=n[e].path;for(;s&&!t.has(s);){t.add(s);const e=s.lastIndexOf(".");if(e<0)break;s=s.slice(0,e)}}this.notifyListeners(t)}return n}notifyListeners(e){for(const t of e)this.updateBus.emit({name:"update",payload:t})}};l(d());var T=class{constructor(e,t,s){this.eventBus=e,this.executionState=t,this.merge=s}middleware=[];blockingMiddleware=[];async executeBlocking(e,t){for(const{fn:s,name:i,id:r}of this.blockingMiddleware){const a={id:r,name:i,startTime:performance.now()};this.executionState.runningMiddleware={id:r,name:i,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:r,name:i,type:"blocking"});try{const n=await Promise.resolve(s(e,t));if(a.endTime=performance.now(),a.duration=a.endTime-a.startTime,!1===n)return a.blocked=!0,this.emitMiddlewareLifecycle("blocked",{id:r,name:i,duration:a.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),{blocked:!0};this.emitMiddlewareLifecycle("complete",{id:r,name:i,type:"blocking",duration:a.duration}),this.emit(this.eventBus,{name:"middleware:executed",payload:{...a,blocked:!1}})}catch(e){return a.endTime=performance.now(),a.duration=a.endTime-a.startTime,a.error=e instanceof Error?e:new Error(String(e)),a.blocked=!0,this.emitMiddlewareError(r,i,a.error,a.duration),this.emit(this.eventBus,{name:"middleware:executed",payload:a}),{blocked:!0,error:a.error}}finally{this.executionState.runningMiddleware=null}}return{blocked:!1}}async executeTransform(e,t){let s=e,i=t;for(const{fn:e,name:r,id:a}of this.middleware){const n={id:a,name:r,startTime:performance.now()};this.executionState.runningMiddleware={id:a,name:r,startTime:performance.now()},this.emitMiddlewareLifecycle("start",{id:a,name:r,type:"transform"});try{const o=await Promise.resolve(e(s,t));n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.blocked=!1,o&&"object"==typeof o&&(s=this.merge(s,o),i=this.merge(i,o)),this.emit(this.eventBus,{name:"middleware:executed",payload:n}),this.emitMiddlewareLifecycle("complete",{id:a,name:r,type:"transform",duration:n.duration})}catch(e){n.endTime=performance.now(),n.duration=n.endTime-n.startTime,n.error=e instanceof Error?e:new Error(String(e)),n.blocked=!1,this.emit(this.eventBus,{name:"middleware:executed",payload:n}),this.emitMiddlewareError(a,r,n.error,n.duration),console.error(`Middleware ${r} error:`,e)}finally{this.executionState.runningMiddleware=null}}return i}addMiddleware(e,t="unnamed-middleware"){const s=this.generateId();return this.middleware.push({fn:e,name:t,id:s}),this.updateExecutionState(),s}addBlockingMiddleware(e,t="unnamed-blocking-middleware"){const s=this.generateId();return this.blockingMiddleware.push({fn:e,name:t,id:s}),this.updateExecutionState(),s}removeMiddleware(e){const t=this.middleware.length+this.blockingMiddleware.length;return this.middleware=this.middleware.filter((t=>t.id!==e)),this.blockingMiddleware=this.blockingMiddleware.filter((t=>t.id!==e)),this.updateExecutionState(),this.middleware.length+this.blockingMiddleware.length<t}updateExecutionState(){this.executionState.middlewares=[...this.middleware.map((e=>e.name)),...this.blockingMiddleware.map((e=>e.name))]}emitMiddlewareLifecycle(e,t){this.emit(this.eventBus,{name:`middleware:${e}`,payload:{...t,timestamp:Date.now()}})}emitMiddlewareError(e,t,s,i){this.emit(this.eventBus,{name:"middleware:error",payload:{id:e,name:t,error:s,duration:i,timestamp:Date.now()}})}generateId(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var x=class{constructor(e,t,s,i){this.eventBus=e,this.coreState=t,this.instanceID=s,this.maxRetries=i?.maxRetries??3,this.retryDelay=i?.retryDelay??1e3}persistence;instanceID;persistenceReady=!1;backgroundQueue=[];isProcessingQueue=!1;maxRetries=3;retryDelay=1e3;queueProcessor;async initialize(e){e?await this.setPersistence(e):this.setPersistenceReady()}isReady(){return this.persistenceReady}handleStateChange(e,t){if(!this.persistence||0===e.length)return;const s={id:`${Date.now()}-${Math.random().toString(36).substr(2,9)}`,state:structuredClone(t),changedPaths:[...e],timestamp:Date.now(),retries:0};this.backgroundQueue.push(s),this.scheduleQueueProcessing(),this.emit(this.eventBus,{name:"persistence:queued",payload:{taskId:s.id,changedPaths:e,queueSize:this.backgroundQueue.length,timestamp:s.timestamp}})}getQueueStatus(){return{queueSize:this.backgroundQueue.length,isProcessing:this.isProcessingQueue,oldestTask:this.backgroundQueue[0]?.timestamp}}async flush(){this.isProcessingQueue||await this.processQueue()}clearQueue(){const e=this.backgroundQueue.length;this.backgroundQueue=[],this.queueProcessor&&(clearTimeout(this.queueProcessor),this.queueProcessor=void 0),this.emit(this.eventBus,{name:"persistence:queue_cleared",payload:{clearedTasks:e,timestamp:Date.now()}})}scheduleQueueProcessing(){this.queueProcessor||this.isProcessingQueue||(this.queueProcessor=setTimeout((()=>{this.processQueue().catch((e=>{console.error("Queue processing failed:",e)}))}),10))}async processQueue(){if(!this.isProcessingQueue&&0!==this.backgroundQueue.length){this.isProcessingQueue=!0,this.queueProcessor=void 0;try{for(;this.backgroundQueue.length>0;){const e=this.backgroundQueue.shift();await this.processTask(e)}}finally{this.isProcessingQueue=!1}}}async processTask(e){try{await this.persistence.set(this.instanceID,e.state)?this.emit(this.eventBus,{name:"persistence:success",payload:{taskId:e.id,changedPaths:e.changedPaths,duration:Date.now()-e.timestamp,timestamp:Date.now()}}):await this.handleTaskFailure(e,new Error("Persistence returned false"))}catch(t){await this.handleTaskFailure(e,t)}}async handleTaskFailure(e,t){if(e.retries++,e.retries<=this.maxRetries){const s=this.retryDelay*Math.pow(2,e.retries-1);this.emit(this.eventBus,{name:"persistence:retry",payload:{taskId:e.id,attempt:e.retries,maxRetries:this.maxRetries,nextRetryIn:s,error:t,timestamp:Date.now()}}),setTimeout((()=>{this.backgroundQueue.unshift(e),this.scheduleQueueProcessing()}),s)}else this.emit(this.eventBus,{name:"persistence:failed",payload:{taskId:e.id,changedPaths:e.changedPaths,attempts:e.retries,error:t,timestamp:Date.now()}})}setPersistenceReady(){this.persistenceReady=!0,this.emit(this.eventBus,{name:"persistence:ready",payload:{timestamp:Date.now()}})}async setPersistence(e){this.persistence=e;try{const e=await this.persistence.get();e&&this.coreState.applyChanges(e)}catch(e){console.error("Failed to initialize persistence:",e),this.emit(this.eventBus,{name:"persistence:init_error",payload:{error:e,timestamp:Date.now()}})}finally{this.setPersistenceReady()}this.persistence.subscribe&&this.persistence.subscribe(this.instanceID,(async e=>{const t=this.coreState.applyChanges(e);t.length>0&&this.emit(this.eventBus,{name:"update:complete",payload:{changedPaths:t,source:"external",timestamp:Date.now()}})}))}dispose(){this.clearQueue(),this.isProcessingQueue=!1,this.persistenceReady=!1}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var C=class{constructor(e,t,s){this.eventBus=e,this.coreState=t,this.executionState=s}async execute(e){const t=this.coreState.get(!0);this.executionState.transactionActive=!0,this.emit(this.eventBus,{name:"transaction:start",payload:{timestamp:Date.now()}});try{const t=await Promise.resolve(e());return this.emit(this.eventBus,{name:"transaction:complete",payload:{timestamp:Date.now()}}),this.executionState.transactionActive=!1,t}catch(e){throw this.coreState.applyChanges(t,!0,!1),this.emit(this.eventBus,{name:"transaction:error",payload:{error:e instanceof Error?e:new Error(String(e)),timestamp:Date.now()}}),this.executionState.transactionActive=!1,e}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}};l(d());var M=class{updateCount=0;listenerExecutions=0;averageUpdateTime=0;largestUpdateSize=0;mostActiveListenerPaths=[];totalUpdates=0;blockedUpdates=0;averageUpdateDuration=0;middlewareExecutions=0;transactionCount=0;totalEventsFired=0;totalActionsDispatched=0;totalActionsSucceeded=0;totalActionsFailed=0;averageActionDuration=0;updateTimes=[];actionTimes=[];pathExecutionCounts=new Map;constructor(e){this.setupEventListeners(e)}getMetrics(){return{updateCount:this.updateCount,listenerExecutions:this.listenerExecutions,averageUpdateTime:this.averageUpdateTime,largestUpdateSize:this.largestUpdateSize,mostActiveListenerPaths:[...this.mostActiveListenerPaths],totalUpdates:this.totalUpdates,blockedUpdates:this.blockedUpdates,averageUpdateDuration:this.averageUpdateDuration,middlewareExecutions:this.middlewareExecutions,transactionCount:this.transactionCount,totalEventsFired:this.totalEventsFired,totalActionsDispatched:this.totalActionsDispatched,totalActionsSucceeded:this.totalActionsSucceeded,totalActionsFailed:this.totalActionsFailed,averageActionDuration:this.averageActionDuration}}setupEventListeners(e){const t=e.emit;e.emit=s=>(this.totalEventsFired++,t.call(e,s)),e.subscribe("update:complete",(e=>{if(this.totalUpdates++,e.blocked)this.blockedUpdates++;else{if(e.duration){this.updateTimes.push(e.duration),this.updateTimes.length>100&&this.updateTimes.shift();const t=this.updateTimes.reduce(((e,t)=>e+t),0)/this.updateTimes.length;this.averageUpdateTime=t,this.averageUpdateDuration=t}e.deltas?.length&&(this.updateCount++,this.largestUpdateSize=Math.max(this.largestUpdateSize,e.deltas.length),e.deltas.forEach((e=>{const t=this.pathExecutionCounts.get(e.path)||0;this.pathExecutionCounts.set(e.path,t+1)})),this.mostActiveListenerPaths=Array.from(this.pathExecutionCounts.entries()).sort((([,e],[,t])=>t-e)).slice(0,5).map((([e])=>e)))}})),e.subscribe("middleware:start",(()=>{this.middlewareExecutions++})),e.subscribe("transaction:start",(()=>{this.transactionCount++})),e.subscribe("action:start",(()=>{this.totalActionsDispatched++})),e.subscribe("action:complete",(e=>{this.totalActionsSucceeded++,e.duration&&(this.actionTimes.push(e.duration),this.actionTimes.length>100&&this.actionTimes.shift(),this.averageActionDuration=this.actionTimes.reduce(((e,t)=>e+t),0)/this.actionTimes.length)})),e.subscribe("action:error",(()=>{this.totalActionsFailed++}))}reset(){this.updateCount=0,this.listenerExecutions=0,this.averageUpdateTime=0,this.largestUpdateSize=0,this.mostActiveListenerPaths=[],this.totalUpdates=0,this.blockedUpdates=0,this.averageUpdateDuration=0,this.middlewareExecutions=0,this.transactionCount=0,this.totalEventsFired=0,this.totalActionsDispatched=0,this.totalActionsSucceeded=0,this.totalActionsFailed=0,this.averageActionDuration=0,this.updateTimes=[],this.actionTimes=[],this.pathExecutionCounts.clear()}getDetailedMetrics(){return{pathExecutionCounts:new Map(this.pathExecutionCounts),recentUpdateTimes:[...this.updateTimes],successRate:this.totalUpdates>0?(this.totalUpdates-this.blockedUpdates)/this.totalUpdates:1,averagePathsPerUpdate:this.updateCount>0?Array.from(this.pathExecutionCounts.values()).reduce(((e,t)=>e+t),0)/this.updateCount:0}}dispose(){this.reset()}};l(d());var A=class extends Error{constructor(){super("Action Cancelled by Debounce"),this.name="ActionCancelledError"}},P=class{constructor(e,t){this.eventBus=e,this.set=t}actions=new Map;register(t){const s=t.debounce,i={name:t.name,id:e(),action:t.fn,debounce:s?{...s,condition:s.condition||(()=>!0)}:void 0};return this.actions.set(t.name,i),()=>{const e=this.actions.get(t.name);e?.debounce?.timer&&clearTimeout(e.debounce.timer),this.actions.delete(t.name)}}async dispatch(e,...t){const s=this.actions.get(e);if(!s)throw new Error(`unknown action ${e}`);const{id:i,action:r,debounce:a}=s;return!a||void 0===a.delay||a.delay<=0||a.condition&&!a.condition(a.args,t)?this.executeAction(e,i,r,t):(a.timer&&(clearTimeout(a.timer),a.reject?.(new A)),new Promise(((s,n)=>{a.resolve=s,a.reject=n,a.timer=setTimeout((async()=>{a.timer=void 0,a.resolve=void 0,a.reject=void 0;try{const a=await this.executeAction(e,i,r,t);s(a)}catch(e){n(e)}}),a.delay)})))}async executeAction(e,t,s,i){const r=performance.now();this.emit(this.eventBus,{name:"action:start",payload:{actionId:t,name:e,params:i||[],timestamp:r}});try{const a=await this.set((e=>s(e,...i)),{actionId:t}),n=this.actions.get(e);n?.debounce&&(n.debounce.args=i);const o=performance.now();return this.emit(this.eventBus,{name:"action:complete",payload:{actionId:t,name:e,params:i,startTime:r,endTime:o,duration:o-r,result:a}}),a}catch(s){const a=performance.now();throw this.emit(this.eventBus,{name:"action:error",payload:{actionId:t,name:e,params:i,startTime:r,endTime:a,duration:a-r,error:s}}),s}}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},D=class{coreState;middlewareEngine;persistenceHandler;transactionManager;metricsCollector;selectorManager;actionManager;updateQueue=Promise.resolve();updateBus=(0,h.createEventBus)();eventBus=(0,h.createEventBus)();executionState;instanceID=e();merge;diff;constructor(e,t,s=u,i){this.executionState={executing:!1,changes:null,pendingChanges:[],middlewares:[],runningMiddleware:null,transactionActive:!1},this.merge=m({deleteMarker:s}),this.diff=v({deleteMarker:s}),this.coreState=new E(e,this.updateBus,this.diff),this.middlewareEngine=new T(this.eventBus,this.executionState,this.merge),this.persistenceHandler=new x(this.eventBus,this.coreState,this.instanceID,{maxRetries:i?.persistenceMaxRetries,retryDelay:i?.persistenceRetryDelay}),this.transactionManager=new C(this.eventBus,this.coreState,this.executionState),this.metricsCollector=new M(this.eventBus),this.actionManager=new P(this.eventBus,this.set.bind(this)),this.persistenceHandler.initialize(t),this.setupPersistenceListener(),this.selectorManager=new g(this.get.bind(this),this.eventBus)}isReady(){return this.persistenceHandler.isReady()}state(){return this.executionState}get(e){return this.coreState.get(e??!1)}select(e){return this.selectorManager.createReactiveSelector(e)}register(e){return this.actionManager.register(e)}async dispatch(e,...t){return this.actionManager.dispatch(e,...t)}async set(e,t={}){const s=this.updateQueue.then((()=>this._performUpdate(e,t)));return this.updateQueue=s.catch((()=>{})),s}async _performUpdate(e,t){this.executionState.executing=!0;const s=performance.now();this.emit(this.eventBus,{name:"update:start",payload:{timestamp:s,actionId:t.actionId}});try{if(t.force){const t=this.get(!1),s="function"==typeof e?e(t):e;return this.coreState.applyChanges(s,!0),s}let i;const r=this.get(!1);if("function"==typeof e){const t=e(r);i=t instanceof Promise?await t:t}else i=e;const a=await this.middlewareEngine.executeBlocking(r,i);if(a.blocked)throw a.error||new Error("Update blocked by middleware");const n=this.merge(r,i),o=await this.middlewareEngine.executeTransform(n,i),c=this.merge(n,o),l=this.coreState.applyChanges(c,!1,!1,[i,o]),d=performance.now(),h=this.get(!1);return this.emit(this.eventBus,{name:"update:complete",payload:{deltas:l,duration:d-s,timestamp:Date.now(),actionId:t.actionId,newState:h}}),h}catch(e){throw this.emit(this.eventBus,{name:"update:complete",payload:{blocked:!0,error:e,timestamp:Date.now(),actionId:t.actionId,newState:this.get(!1)}}),e}finally{this.executionState.executing=!1,this.executionState.changes=null,this.executionState.runningMiddleware=null,this.executionState.pendingChanges=[]}}setupPersistenceListener(){this.updateBus.subscribe("update",(e=>{e&&this.persistenceHandler.isReady()&&this.persistenceHandler.handleStateChange([e],this.get(!1))}))}watch(e,t){const s=Array.isArray(e)?e:[e],i=""===e||0===s.length;return this.updateBus.subscribe("update",(e=>{(i||s.includes(e))&&(t(this.get(!1)),this.metricsCollector.listenerExecutions++)}))}subscribe(e,t){return this.watch(e,t)}id(){return this.instanceID}async transaction(e){return this.transactionManager.execute(e)}use(e){const t=(e.block?this.middlewareEngine.addBlockingMiddleware:this.middlewareEngine.addMiddleware).bind(this.middlewareEngine)(e.action,e.name);return()=>this.middlewareEngine.removeMiddleware(t)}metrics(){return this.metricsCollector.getMetrics()}on(e,t){return this.eventBus.subscribe(e,t)}onStoreEvent(e,t){return this.eventBus.subscribe(e,t)}getPersistenceStatus(){return this.persistenceHandler.getQueueStatus()}async flushPersistence(){return this.persistenceHandler.flush()}clearPersistenceQueue(){this.persistenceHandler.clearQueue()}dispose(){this.persistenceHandler.dispose(),this.metricsCollector.dispose?.(),this.selectorManager.dispose?.()}emit(e,t){queueMicrotask((()=>{e.emit(t)}))}},B=class extends Error{constructor(e){super(e),this.name="SystemError"}},H=class extends B{constructor(e){super(`[ArtifactContainer] Cycle detected: ${e.join(" -> ")}`),this.name="CircularDependencyError"}},L=class extends B{constructor(e){super(`[ArtifactContainer] Artifact "${e}" not found.`),this.name="ArtifactNotFoundError"}},$=class extends B{constructor(e){super(`[ArtifactContainer] ${e}`),this.name="IllegalScopeError"}},I=(e=>(e.Singleton="singleton",e.Transient="transient",e))(I||{}),U=class e{artifacts=new Map;resolvingStack=[];listeners=new Map;watcherCache=new Map;props;parent;isDisposed=!1;constructor({watch:e,get:t},s){this.props={watch:(...t)=>e(...t),get:()=>t(!0)},this.parent=s}createChild(){return new e(this.props,this)}getDebugInfo(){const e=[];return this.artifacts.forEach(((t,s)=>{e.push({id:s,scope:t.scope,status:t.debounceTimer?"debouncing":t.initializationPromise?"building":t.error?"error":t.instance?"active":"idle",dependencies:Array.from(t.artifactDependencies).map((e=>e.key)),dependents:Array.from(t.dependents).map((e=>e.key)),stateDependencies:Array.from(t.stateDependencies),renderCount:t.buildCount})})),e}register({key:e,factory:t,...s}){const i=e;this.artifacts.has(i)&&(console.warn(`[ArtifactContainer] Overwriting "${i}".`),this.disposeArtifact(i));const r={key:e,factory:t,scope:s.scope??"singleton",lazy:s.lazy??!0,timeoutMs:s.timeoutMs,retries:s.retries??0,baseDebounceMs:s.debounce??0,activeDebounceMs:s.debounce??0,isInvalidationScheduled:!1,cleanupFunctions:[],disposeFunctions:[],stateDependencies:new Set,artifactDependencies:new Set,dependents:new Set,buildCount:0};return this.artifacts.set(i,r),r.lazy||"singleton"!==r.scope||this.resolve(e).catch((e=>{console.error(`[ArtifactContainer] Eager load failed for "${i}":`,e)})),()=>this.unregister(e)}async unregister(e){const t=e;this.artifacts.has(t)&&(await this.disposeArtifact(t),this.artifacts.delete(t))}async resolve(e){const t=e;if(this.resolvingStack.includes(t))throw new H([...this.resolvingStack,t]);const{def:s,container:i}=this.findDefinition(t)||{};if(!s||!i){if(this.parent)return this.parent.resolve(e);throw new L(t)}if(i!==this)return i.resolve(e);this.resolvingStack.push(t);try{if("transient"===s.scope){const e=await this.createArtifactInstance(s,new Set,new Set);return{instance:e.instance,cleanup:e.cleanup,error:e.error,invalidate:async()=>console.warn(`[ArtifactContainer] Cannot invalidate transient "${t}"`)}}if(void 0!==s.instance||void 0!==s.error)return this.packageArtifact(s);if(s.initializationPromise){try{await s.initializationPromise}catch(e){}return this.packageArtifact(s)}const e=(async()=>{try{const e=new Set,t=new Set,i=await this.createArtifactInstance(s,e,t);this.updateGraph(s,e,t),i.error?s.error=i.error:s.instance=i.instance}catch(e){if(e instanceof B)throw e;s.error=e}finally{s.initializationPromise=void 0}})();return s.initializationPromise=e,await e,this.packageArtifact(s)}finally{this.resolvingStack.pop()}}watch(e){const t=e;if(!this.artifacts.has(t)&&this.parent)return this.parent.watch(e);if(this.watcherCache.has(t))return this.watcherCache.get(t);const s={id:t,get:()=>{const e=this.artifacts.get(t);return!e||void 0===e.instance&&!e.error?null:this.packageArtifact(e)},subscribe:e=>this.isDisposed?()=>{}:(this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>this.listeners.get(t)?.delete(e))};return this.watcherCache.set(t,s),s}peek(e){return this.artifacts.get(e)?.instance??this.parent?.peek(e)}findDefinition(e){return this.artifacts.has(e)?{def:this.artifacts.get(e),container:this}:this.parent?this.parent.findDefinition(e):null}packageArtifact(e){return{instance:e.instance,cleanup:this.createCompositeCleanup(e.cleanupFunctions),error:e.error,invalidate:async t=>this.invalidate(e.key,t)}}async createArtifactInstance(e,t,s){e.buildCount++;const i=[],r=[];let a=!0;e.activeDebounceMs=e.baseDebounceMs,i.push((()=>{a=!1}));const n={state:(...e)=>this.props.get(...e),current:e.instance,onCleanup:e=>i.push(e),onDispose:e=>r.push(e),use:async(i,r)=>(r?.debounce&&r.debounce>e.activeDebounceMs&&(e.activeDebounceMs=r.debounce),i({resolve:async s=>{if(s===e.key)throw new B(`Artifact "${String(e.key)}" depends on itself.`);const i=this.findDefinition(s);return i&&t.add({key:s,container:i.container}),this.resolve(s)},select:e=>(y(e).forEach((e=>s.add(e))),e(this.props.get()))})),yield:t=>{a&&("transient"!==e.scope?(e.instance=t,e.error=void 0,this.processYieldPropagation(e.key)):console.error(`[ArtifactContainer] Illegal yield on transient artifact "${String(e.key)}"`))}};let o,c,l=0;const d=(e.retries||0)+1;for(;l<d;)try{const t=e.factory(n);if(e.timeoutMs){const s=new Promise(((t,s)=>setTimeout((()=>s(new Error(`Timeout: ${e.timeoutMs}ms`))),e.timeoutMs)));o=await Promise.race([t,s])}else o=await t;break}catch(e){if(e instanceof B)throw e;l++,l>=d&&(c=e)}return"singleton"===e.scope&&(e.cleanupFunctions=i,e.disposeFunctions=r),{instance:o,cleanup:this.createCompositeCleanup(i),error:c}}async processYieldPropagation(e){const t=this.artifacts.get(e);if(t)try{await Promise.all(Array.from(t.dependents).map((e=>e.container.invalidate(e.key,!1).catch((t=>{console.error(`[ArtifactContainer] Failed to invalidate dependent "${e.key}":`,t)}))))),this.notifyListeners(e)}catch(t){console.error(`[ArtifactContainer] Yield propagation error "${e}":`,t)}}registerDependent(e,t,s){const i=this.artifacts.get(e);i&&i.dependents.add({key:t,container:s})}removeDependent(e,t,s){const i=this.artifacts.get(e);if(i)for(const e of i.dependents)if(e.key===t&&e.container===s){i.dependents.delete(e);break}}async invalidate(e,t=!1){const s=e,i=this.artifacts.get(s);if(i){if(i.debounceTimer&&(clearTimeout(i.debounceTimer),i.debounceTimer=void 0,i.isInvalidationScheduled=!1),!t&&i.activeDebounceMs>0&&!i.isInvalidationScheduled){i.isInvalidationScheduled=!0;const s=new Promise((s=>{i.debounceTimer=setTimeout((()=>{i.debounceTimer=void 0,i.isInvalidationScheduled=!1,this.executeInvalidation(e,t).then(s).catch(s)}),i.activeDebounceMs)}));return i.rebuildPromise=s,s}return t&&i.isInvalidationScheduled&&(i.isInvalidationScheduled=!1),this.executeInvalidation(e,t)}}async executeInvalidation(e,t){const s=e,i=this.artifacts.get(s);if(!i)return;if(i.initializationPromise)try{await i.initializationPromise}catch{}if(i.rebuildPromise&&!i.debounceTimer&&!t)return i.rebuildPromise;const r=(async()=>{try{await Promise.all(Array.from(i.dependents).map((e=>e.container.invalidate(e.key,t).catch((t=>{console.error(`[ArtifactContainer] Cascade failed for "${e.key}":`,t)}))))),await this.disposeInstance(i),!t&&i.lazy||await this.resolve(e)}finally{i.rebuildPromise=void 0}})();return i.rebuildPromise=r,r}async disposeInstance(e){e.stateSubscriptionCleanup&&(e.stateSubscriptionCleanup(),e.stateSubscriptionCleanup=void 0),e.debounceTimer&&(clearTimeout(e.debounceTimer),e.debounceTimer=void 0);for(let t=e.disposeFunctions.length-1;t>=0;t--)try{await e.disposeFunctions[t]()}catch(e){console.error(e)}for(let t=e.cleanupFunctions.length-1;t>=0;t--)try{await e.cleanupFunctions[t]()}catch(e){console.error(e)}e.instance=void 0,e.error=void 0,e.cleanupFunctions=[],e.disposeFunctions=[],e.initializationPromise=void 0,this.notifyListeners(e.key)}async disposeArtifact(e){const t=this.artifacts.get(e);t&&(this.watcherCache.delete(e),t.rebuildPromise&&await t.rebuildPromise,await this.disposeInstance(t),t.artifactDependencies.forEach((t=>{t.container.removeDependent(t.key,e,this)})))}updateGraph(e,t,s){e.artifactDependencies.forEach((s=>{let i=!1;for(const e of t)if(e.key===s.key&&e.container===s.container){i=!0;break}i||s.container.removeDependent(s.key,e.key,this)})),t.forEach((t=>{t.container.registerDependent(t.key,e.key,this)})),e.artifactDependencies=t,e.stateSubscriptionCleanup&&e.stateSubscriptionCleanup(),e.stateDependencies=s,s.size>0?e.stateSubscriptionCleanup=this.props.watch(Array.from(s),(()=>this.invalidate(e.key,!1))):e.stateSubscriptionCleanup=void 0,this.notifyListeners(e.key)}createCompositeCleanup(e){if(e.length)return async()=>{for(let t=e.length-1;t>=0;t--)try{await e[t]()}catch(e){console.error(e)}}}notifyListeners(e){this.listeners.get(e)?.forEach((e=>{try{e()}catch(e){console.error(e)}}))}dispose(){this.isDisposed=!0,this.artifacts.forEach(((e,t)=>this.disposeArtifact(t))),this.artifacts.clear(),this.watcherCache.clear(),this.listeners.clear()}},j=class{store;eventHistory=[];stateHistory=[];unsubscribers=[];isTimeTraveling=!1;devTools=null;middlewareExecutions=[];activeTransactionCount=0;activeBatches=new Set;maxEvents;maxStateHistory;enableConsoleLogging;isSilent;logEvents;performanceThresholds;constructor(e,t={}){this.store=e,this.maxEvents=t.maxEvents??500,this.maxStateHistory=t.maxStateHistory??20,this.enableConsoleLogging=t.enableConsoleLogging??!1,this.isSilent=t.silent??!1,this.logEvents={updates:t.logEvents?.updates??!0,middleware:t.logEvents?.middleware??!0,transactions:t.logEvents?.transactions??!0,actions:t.logEvents?.actions??!0,selectors:t.logEvents?.selectors??!0},this.performanceThresholds={updateTime:t.performanceThresholds?.updateTime??50,middlewareTime:t.performanceThresholds?.middlewareTime??20},this.recordStateSnapshot([]),this.setupEventListeners()}_consoleLog(e,...t){this.isSilent||"function"==typeof console[e]&&console[e](...t)}setupEventListeners(){const e=["update:start","update:complete","middleware:start","middleware:complete","middleware:error","middleware:blocked","transaction:start","transaction:complete","transaction:error","middleware:executed","action:start","action:complete","action:error","selector:accessed"];for(const t of e){const e=t.startsWith("update")&&this.logEvents.updates||t.startsWith("middleware")&&this.logEvents.middleware||t.startsWith("transaction")&&this.logEvents.transactions||t.startsWith("action")&&this.logEvents.actions||t.startsWith("selector")&&this.logEvents.selectors;this.unsubscribers.push(this.store.onStoreEvent(t,(s=>{"update:complete"!==t||s.blocked||this.isTimeTraveling||this.recordStateSnapshot(s.deltas),"middleware:executed"===t?this.middlewareExecutions.push(s):"transaction:start"===t?this.activeTransactionCount++:"transaction:complete"!==t&&"transaction:error"!==t||(this.activeTransactionCount=Math.max(0,this.activeTransactionCount-1)),s.batchId&&(t.endsWith("start")?this.activeBatches.add(s.batchId):(t.endsWith("complete")||t.endsWith("error"))&&this.activeBatches.delete(s.batchId)),this.recordEvent(t,s),this.enableConsoleLogging&&e&&this._log(t,s),this._checkPerformance(t,s)})))}}recordStateSnapshot(e){const t={state:this.store.get(!0),timestamp:Date.now(),deltas:e};this.stateHistory.unshift(t),this.stateHistory.length>this.maxStateHistory&&this.stateHistory.pop()}recordEvent(e,t){const s={type:e,timestamp:Date.now(),data:structuredClone(t)};this.eventHistory.unshift(s),this.eventHistory.length>this.maxEvents&&this.eventHistory.pop()}getEventHistory(){return structuredClone(this.eventHistory)}getStateHistory(){return structuredClone(this.stateHistory)}getMiddlewareExecutions(){return this.middlewareExecutions}getTransactionStatus(){return{activeTransactions:this.activeTransactionCount,activeBatches:Array.from(this.activeBatches)}}createLoggingMiddleware(e={}){const{logLevel:t="debug",logUpdates:s=!0}=e;return(e,i)=>{if(s){(console[t]||console.log)("State Update:",i)}return i}}createValidationMiddleware(e){return(t,s)=>{const i=e(t,s);return"boolean"==typeof i?i:(!i.valid&&i.reason&&this._consoleLog("warn","Validation failed:",i.reason),i.valid)}}getRecentChanges(e=5){const t=[],s=Math.min(e,this.stateHistory.length);for(let e=0;e<s;e++){const s=this.stateHistory[e];if(!s.deltas||0===s.deltas.length)continue;const i={},r={},a=(e,t,s)=>{t.reduce(((e,i,r)=>(r===t.length-1?e[i]=s:e[i]=e[i]??{},e[i])),e)};for(const e of s.deltas){const t=e.path.split(".");a(i,t,e.oldValue),a(r,t,e.newValue)}t.push({timestamp:s.timestamp,changedPaths:s.deltas.map((e=>e.path)),from:i,to:r})}return t}clearHistory(){this.eventHistory=[],this.stateHistory.length>0&&(this.stateHistory=[this.stateHistory[0]])}getHistoryForAction(e){return this.eventHistory.filter((t=>t.data?.actionId===e))}async replay(e){const t=this.eventHistory.filter((e=>"update:start"===e.type))[e];t?.data.update?(this._consoleLog("log",`Replaying event at index ${e}:`,t),await this.store.set(t.data.update,{force:!0})):this._consoleLog("warn",`No replayable event found at index ${e}.`)}createTimeTravel(){let e=0,t=[];const s=this.store.onStoreEvent("update:complete",(s=>{this.isTimeTraveling||s.blocked||(t=[],e=0)}));this.unsubscribers.push(s);const i=()=>this.stateHistory.length,r=()=>e<i()-1,a=()=>t.length>0;return{canUndo:r,canRedo:a,undo:async()=>{if(!r())return;t.unshift(this.stateHistory[e]),e++;const s=this.stateHistory[e].state;this.isTimeTraveling=!0,await this.store.set({...s},{force:!0}),this.isTimeTraveling=!1},redo:async()=>{if(!a())return;const s=t.shift();e--,this.isTimeTraveling=!0,await this.store.set({...s.state},{force:!0}),this.isTimeTraveling=!1},length:i,clear:()=>{t=[],e=0}}}async saveSession(e){const t=this.store.id(),s={eventHistory:this.eventHistory,stateHistory:this.stateHistory};return Promise.resolve(e.set(t,s))}async loadSession(e){const t=await Promise.resolve(e.get());return!!t&&(this.eventHistory=t.eventHistory||[],this.stateHistory=t.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),!0)}exportSession(){const e={eventHistory:this.eventHistory,stateHistory:this.stateHistory},t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),s=URL.createObjectURL(t),i=document.createElement("a");i.href=s,i.download=`store-observer-session-${(new Date).toISOString()}.json`,i.click(),URL.revokeObjectURL(s)}importSession(e){return new Promise(((t,s)=>{const i=new FileReader;i.onload=async e=>{try{const s=JSON.parse(e.target?.result);this.eventHistory=s.eventHistory||[],this.stateHistory=s.stateHistory||[],this.stateHistory.length>0&&await this.store.set(this.stateHistory[0].state,{force:!0}),t()}catch(e){s(e)}},i.onerror=e=>s(e),i.readAsText(e)}))}disconnect(){this.unsubscribers.forEach((e=>e())),this.unsubscribers=[],this.devTools?.disconnect(),this.clearHistory()}_log(e,t){const s=new Date(t.timestamp||Date.now()).toISOString().split("T")[1].replace("Z","");if("update:start"===e)this._consoleLog("group",`%c⚡ Store Update Started [${s}]`,"color: #4a6da7");else if("update:complete"===e){if(t.blocked)this._consoleLog("warn",`%c✋ Update Blocked [${s}]`,"color: #bf8c0a",t.error);else{const e=t.deltas||[];e.length>0&&(this._consoleLog("log",`%c✅ Update Complete [${s}] - ${e.length} paths changed in ${t.duration?.toFixed(2)}ms`,"color: #2a9d8f"),this._consoleLog("table",e.map((e=>({path:e.path,oldValue:e.oldValue,newValue:e.newValue})))))}this._consoleLog("groupEnd")}else"middleware:start"===e?this._consoleLog("debug",`%c◀ Middleware "${t.name}" started [${s}] (${t.type})`,"color: #8c8c8c"):"middleware:complete"===e?this._consoleLog("debug",`%c▶ Middleware "${t.name}" completed [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #7c9c7c"):"middleware:error"===e?this._consoleLog("error",`%c❌ Middleware "${t.name}" error [${s}]:`,"color: #e63946",t.error):"middleware:blocked"===e?this._consoleLog("warn",`%c🛑 Middleware "${t.name}" blocked update [${s}]`,"color: #e76f51"):"transaction:start"===e?this._consoleLog("group",`%c📦 Transaction Started [${s}]`,"color: #6d597a"):"transaction:complete"===e?(this._consoleLog("log",`%c📦 Transaction Complete [${s}]`,"color: #355070"),this._consoleLog("groupEnd")):"transaction:error"===e?(this._consoleLog("error",`%c📦 Transaction Error [${s}]:`,"color: #e56b6f",t.error),this._consoleLog("groupEnd")):"action:start"===e?this._consoleLog("group",`%c🚀 Action "${t.name}" Started [${s}]`,"color: #9b59b6",{params:t.params}):"action:complete"===e?(this._consoleLog("log",`%c✔️ Action "${t.name}" Complete [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #2ecc71"),this._consoleLog("groupEnd")):"action:error"===e?(this._consoleLog("error",`%c🔥 Action "${t.name}" Error [${s}]:`,"color: #e74c3c",t.error),this._consoleLog("groupEnd")):"selector:accessed"===e&&this._consoleLog("debug",`%c👀 Selector Accessed [${s}] in ${t.duration?.toFixed(2)}ms`,"color: #f1c40f",{accessedPaths:t.accessedPaths,selectorId:t.selectorId})}_checkPerformance(e,t){this.enableConsoleLogging&&("update:complete"===e&&!t.blocked&&t.duration>this.performanceThresholds.updateTime&&this._consoleLog("warn",`%c⚠️ Slow update detected [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{deltas:t.deltas,threshold:this.performanceThresholds.updateTime}),"middleware:complete"===e&&t.duration>this.performanceThresholds.middlewareTime&&this._consoleLog("warn",`%c⚠️ Slow middleware "${t.name}" [${t.duration.toFixed(2)}ms]`,"color: #ff9f1c",{threshold:this.performanceThresholds.middlewareTime}))}};export{P as ActionManager,U as ArtifactContainer,L as ArtifactNotFoundError,I as ArtifactScope,H as CircularDependencyError,u as DELETE_SYMBOL,$ as IllegalScopeError,D as ReactiveDataStore,j as StoreObserver,B as SystemError,b as createDerivePaths,v as createDiff,m as createMerge,k as derivePaths,S as diff,f as merge,p as shallowClone};
|