@blac/core 2.0.0-rc-13 → 2.0.0-rc-14
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/dist/index.cjs.js +2 -2
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +522 -297
- package/dist/index.es.js +1833 -1550
- package/dist/index.es.js.map +1 -1
- package/package.json +6 -7
- package/src/Blac.ts +38 -71
- package/src/Bloc.ts +8 -9
- package/src/BlocBase.ts +246 -540
- package/src/Cubit.ts +1 -16
- package/src/__tests__/Blac.config.test.ts +10 -17
- package/src/__tests__/Bloc.event.test.ts +27 -52
- package/src/__tests__/BlocBase.subscription.test.ts +349 -0
- package/src/__tests__/Cubit.test.ts +39 -50
- package/src/__tests__/memory-leaks.test.ts +383 -0
- package/src/__tests__/plugins.test.ts +107 -97
- package/src/adapter/BlacAdapter.ts +347 -207
- package/src/adapter/ProxyFactory.ts +196 -255
- package/src/adapter/__tests__/BlacAdapter.test.ts +71 -77
- package/src/adapter/__tests__/ProxyFactory.test.ts +1 -1
- package/src/adapter/index.ts +0 -1
- package/src/errors/BlacError.ts +69 -0
- package/src/errors/ErrorManager.ts +101 -0
- package/src/errors/handleError.ts +114 -0
- package/src/errors/index.ts +13 -0
- package/src/events.ts +7 -1
- package/src/index.ts +7 -1
- package/src/lifecycle/BlocLifecycle.ts +156 -0
- package/src/lifecycle/index.ts +1 -0
- package/src/plugins/BlocPluginRegistry.ts +71 -51
- package/src/plugins/SystemPluginRegistry.ts +63 -13
- package/src/plugins/__tests__/BlocPluginRegistry.test.ts +450 -0
- package/src/plugins/__tests__/SystemPluginRegistry.test.ts +404 -0
- package/src/plugins/types.ts +32 -3
- package/src/subscription/README.md +132 -0
- package/src/subscription/SubscriptionManager.ts +395 -0
- package/src/subscription/__tests__/SubscriptionManager.test.ts +355 -0
- package/src/subscription/index.ts +2 -0
- package/src/subscription/types.ts +90 -0
- package/src/testing.ts +31 -37
- package/src/types.ts +4 -21
- package/src/utils/BatchingManager.ts +59 -0
- package/src/utils/RerenderLogger.ts +265 -0
- package/src/utils/__tests__/generateInstanceId.test.ts +104 -0
- package/src/utils/__tests__/shallowEqual.test.ts +171 -0
- package/src/utils/__tests__/uuid.test.ts +144 -0
- package/src/utils/generateInstanceId.ts +54 -0
- package/src/utils/shallowEqual.ts +1 -1
- package/README.md +0 -329
- package/src/BlacObserver.ts +0 -189
- package/src/__tests__/BlocBase.lifecycle.test.ts +0 -441
- package/src/__tests__/props.test.ts +0 -256
- package/src/adapter/ConsumerTracker.ts +0 -241
- package/src/adapter/__tests__/ConsumerTracker.test.ts +0 -562
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var q=Object.defineProperty;var K=(c,e,t)=>e in c?q(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var i=(c,e,t)=>K(c,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class M{constructor(e){i(this,"bloc");i(this,"_observers",new Set);this.bloc=e}get size(){return this._observers.size}get observers(){return this._observers}subscribe(e){const t=this.bloc._disposalState;return t===y.DISPOSED||t===y.DISPOSING?(u.log("BlacObservable.subscribe: Cannot subscribe to disposed/disposing bloc.",this.bloc,e),()=>{}):(u.log("BlacObservable.subscribe: Subscribing observer.",this.bloc,e),this._observers.add(e),t===y.DISPOSAL_REQUESTED&&(u.log("BlacObservable.subscribe: Cancelling disposal due to new subscription.",this.bloc),this.bloc._atomicStateTransition(y.DISPOSAL_REQUESTED,y.ACTIVE)),()=>{u.log("BlacObservable.subscribe: Unsubscribing observer.",this.bloc,e),this.unsubscribe(e)})}unsubscribe(e){this._observers.delete(e),this.size===0&&(u.log("BlacObservable.unsubscribe: No observers left.",this.bloc),this.bloc._consumers.size===0&&!this.bloc._keepAlive&&this.bloc._disposalState===y.ACTIVE&&(u.log(`[${this.bloc._name}:${this.bloc._id}] No observers or consumers left. Scheduling disposal.`),this.bloc._scheduleDisposal()))}notify(e,t,s){this._observers.forEach(r=>{let n=!1;if(r.dependencyArray){const o=r.lastState,a=r.dependencyArray(e,t,this.bloc);if(!o)n=!0;else if(o.length!==a.length)n=!0;else for(let l=0;l<a.length;l++)if(!Object.is(o[l],a[l])){n=!0;break}r.lastState=a}else n=!0;n&&r.fn(e,t,s)}),u.instance.plugins.notifyStateChanged(this.bloc,t,e)}clear(){this._observers.clear()}}function E(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){const e=Math.random()*16|0;return(c==="x"?e:e&3|8).toString(16)})}class R{constructor(){i(this,"plugins",new Map);i(this,"executionOrder",[]);i(this,"attached",!1)}add(e){if(this.plugins.has(e.name))throw new Error(`Plugin '${e.name}' is already registered`);e.capabilities&&this.validateCapabilities(e),this.plugins.set(e.name,e),this.executionOrder.push(e.name)}remove(e){const t=this.plugins.get(e);if(!t)return!1;if(this.attached&&t.onDetach)try{t.onDetach()}catch(s){console.error(`Plugin '${e}' error in onDetach:`,s)}return this.plugins.delete(e),this.executionOrder=this.executionOrder.filter(s=>s!==e),!0}get(e){return this.plugins.get(e)}getAll(){return this.executionOrder.map(e=>this.plugins.get(e))}clear(){if(this.attached){for(const e of this.getAll())if(e.onDetach)try{e.onDetach()}catch(t){console.error(`Plugin '${e.name}' error in onDetach:`,t)}}this.plugins.clear(),this.executionOrder=[],this.attached=!1}attach(e){if(this.attached)throw new Error("Plugins are already attached");for(const t of this.getAll())if(t.onAttach)try{t.onAttach(e)}catch(s){console.error(`Plugin '${t.name}' error in onAttach:`,s),this.remove(t.name)}this.attached=!0}transformState(e,t){let s=t;for(const r of this.getAll())if(r.transformState&&this.canTransformState(r))try{s=r.transformState(e,s)}catch(n){console.error(`Plugin '${r.name}' error in transformState:`,n)}return s}transformEvent(e){let t=e;for(const s of this.getAll()){if(t===null)break;if(s.transformEvent&&this.canInterceptEvents(s))try{t=s.transformEvent(t)}catch(r){console.error(`Plugin '${s.name}' error in transformEvent:`,r)}}return t}notifyStateChange(e,t){for(const s of this.getAll())if(s.onStateChange&&this.canReadState(s))try{s.onStateChange(e,t)}catch(r){console.error(`Plugin '${s.name}' error in onStateChange:`,r)}}notifyEvent(e){for(const t of this.getAll())if(t.onEvent&&this.canReadState(t))try{t.onEvent(e)}catch(s){console.error(`Plugin '${t.name}' error in onEvent:`,s)}}notifyError(e,t){for(const s of this.getAll())if(s.onError)try{s.onError(e,t)}catch(r){console.error(`Plugin '${s.name}' error in onError:`,r)}}validateCapabilities(e){const t=e.capabilities;if(t.transformState&&!t.readState)throw new Error(`Plugin '${e.name}': transformState requires readState capability`);if(t.interceptEvents&&!t.readState)throw new Error(`Plugin '${e.name}': interceptEvents requires readState capability`)}canReadState(e){return!e.capabilities||e.capabilities.readState!==!1}canTransformState(e){return!e.capabilities||e.capabilities.transformState===!0}canInterceptEvents(e){return!e.capabilities||e.capabilities.interceptEvents===!0}}var y=(c=>(c.ACTIVE="active",c.DISPOSAL_REQUESTED="disposal_requested",c.DISPOSING="disposing",c.DISPOSED="disposed",c))(y||{});class w{constructor(e){i(this,"uid",E());i(this,"defaultDependencySelector");i(this,"_isolated",!1);i(this,"_observer");i(this,"_id");i(this,"_instanceRef");i(this,"_keepAlive",!1);i(this,"_createdAt",Date.now());i(this,"_disposalState","active");i(this,"_disposalRequestTime",0);i(this,"_state");i(this,"_oldState");i(this,"props",null);i(this,"_batchingLock",!1);i(this,"_pendingUpdates",[]);i(this,"_consumerRefs",new Map);i(this,"_plugins");i(this,"_validateConsumers",()=>{const e=[];for(const[t,s]of this._consumerRefs)s.deref()===void 0&&e.push(t);for(const t of e)this._consumers.delete(t),this._consumerRefs.delete(t);this._consumers.size===0&&!this._keepAlive&&this._disposalState==="active"&&this._scheduleDisposal()});i(this,"_updateId",e=>{const t=this._id;!e||e===t||(this._id=e)});i(this,"onDispose");i(this,"_consumers",new Set);i(this,"_addConsumer",(e,t)=>{var s;return this._disposalState!=="active"?!1:(this._consumers.has(e)||(this._consumers.add(e),t&&this._consumerRefs.set(e,new WeakRef(t)),(s=globalThis.Blac)==null||s.log(`[${this._name}:${this._id}] Consumer added. Total consumers: ${this._consumers.size}`)),!0)});i(this,"_removeConsumer",e=>{var t,s;this._consumers.has(e)&&(this._consumers.delete(e),this._consumerRefs.delete(e),(t=globalThis.Blac)==null||t.log(`[${this._name}:${this._id}] Consumer removed. Remaining consumers: ${this._consumers.size}, keepAlive: ${this._keepAlive}`),this._consumers.size===0&&!this._keepAlive&&this._disposalState==="active"&&((s=globalThis.Blac)==null||s.log(`[${this._name}:${this._id}] No consumers left and not keep-alive. Scheduling disposal.`),this._scheduleDisposal()))});i(this,"_disposalHandler");i(this,"lastUpdate",Date.now());i(this,"_batchingEnabled",!1);i(this,"_pushState",(e,t,s)=>{if(e===void 0||s!==void 0&&typeof s!="object"&&typeof s!="function")return;let r=e;try{r=this._plugins.transformState(t,e)}catch(n){this._plugins.notifyError(n,{phase:"state-change",operation:"transformState"})}if(this._batchingEnabled){this._pendingUpdates.push({newState:r,oldState:t,action:s}),this._oldState=t,this._state=r;return}this._oldState=t,this._state=r;try{this._plugins.notifyStateChange(t,r)}catch(n){console.error("Error notifying bloc plugins of state change:",n)}this._observer.notify(r,t,s),this.lastUpdate=Date.now()});i(this,"batch",e=>{if(this._batchingLock)return e();this._batchingLock=!0,this._batchingEnabled=!0,this._pendingUpdates=[];try{const t=e();if(this._pendingUpdates.length>0){const s=this._pendingUpdates[this._pendingUpdates.length-1];this._observer.notify(s.newState,s.oldState,s.action),this.lastUpdate=Date.now()}return t}finally{this._batchingEnabled=!1,this._batchingLock=!1,this._pendingUpdates=[]}});this._state=e,this._observer=new M(this),this._id=this.constructor.name;const t=this.constructor;if(this._keepAlive=typeof t.keepAlive=="boolean"?t.keepAlive:!1,this._isolated=typeof t.isolated=="boolean"?t.isolated:!1,this._plugins=new R,t.plugins&&Array.isArray(t.plugins))for(const s of t.plugins)this.addPlugin(s)}get isIsolated(){return this._isolated}get isKeepAlive(){return this._keepAlive}get state(){return this._disposalState==="disposed"?this._state:this._state}get isDisposed(){return this._disposalState==="disposed"}get _name(){return this.constructor.name}_atomicStateTransition(e,t){var s,r,n,o;if(this._disposalState===e){const a=this._disposalState;return this._disposalState=t,(s=globalThis.Blac)!=null&&s.enableLog&&((r=globalThis.Blac)==null||r.log(`[${this._name}:${this._id}] State transition: ${a} -> ${t} (SUCCESS)`)),{success:!0,currentState:t,previousState:a}}return(n=globalThis.Blac)!=null&&n.enableLog&&((o=globalThis.Blac)==null||o.log(`[${this._name}:${this._id}] State transition failed: expected ${e}, current ${this._disposalState}`)),{success:!1,currentState:this._disposalState,previousState:e}}_dispose(){var t;let e=this._atomicStateTransition("active","disposing");if(e.success||(e=this._atomicStateTransition("disposal_requested","disposing")),!e.success)return!1;try{return this._consumers.clear(),this._consumerRefs.clear(),this._observer.clear(),(t=this.onDispose)==null||t.call(this),this._atomicStateTransition("disposing","disposed").success}catch(s){throw this._disposalState="active",s}}_setDisposalHandler(e){this._disposalHandler=e}_scheduleDisposal(){if(!this._atomicStateTransition("active","disposal_requested").success)return;if(!(this._consumers.size===0&&!this._keepAlive)){this._atomicStateTransition("disposal_requested","active");return}this._disposalRequestTime=Date.now(),queueMicrotask(()=>{this._consumers.size===0&&!this._keepAlive&&this._observer.size===0&&this._disposalState==="disposal_requested"?this._disposalHandler?this._disposalHandler(this):this._dispose():this._atomicStateTransition("disposal_requested","active")})}_notifyObservers(e,t){this._observer.notify(e,t)}addPlugin(e){if(this._plugins.add(e),this._disposalState==="active")try{e.onAttach&&e.onAttach(this)}catch(t){throw console.error(`Failed to attach plugin '${e.name}':`,t),this._plugins.remove(e.name),t}}removePlugin(e){return this._plugins.remove(e)}getPlugin(e){return this._plugins.get(e)}getPlugins(){return this._plugins.getAll()}_activatePlugins(){if(this._disposalState==="active")try{this._plugins.attach(this)}catch(e){console.error(`Failed to activate plugins for ${this._name}:`,e)}}}i(w,"isolated",!1),i(w,"keepAlive",!1);class O{constructor(){i(this,"plugins",new Map);i(this,"metrics",new Map);i(this,"executionOrder",[])}add(e){if(this.plugins.has(e.name))throw new Error(`Plugin '${e.name}' is already registered`);this.plugins.set(e.name,e),this.executionOrder.push(e.name),this.initializeMetrics(e.name)}remove(e){return this.plugins.get(e)?(this.plugins.delete(e),this.metrics.delete(e),this.executionOrder=this.executionOrder.filter(s=>s!==e),!0):!1}get(e){return this.plugins.get(e)}getAll(){return this.executionOrder.map(e=>this.plugins.get(e))}clear(){this.plugins.clear(),this.metrics.clear(),this.executionOrder=[]}executeHook(e,t,s){for(const r of this.executionOrder){const n=this.plugins.get(r),o=n[e];if(typeof o!="function")continue;const a=performance.now();try{o.apply(n,t),this.recordSuccess(r,e,a)}catch(l){this.recordError(r,e,l),s?s(l,n):console.error(`Plugin '${r}' error in hook '${e}':`,l)}}}bootstrap(){this.executeHook("beforeBootstrap",[]),this.executeHook("afterBootstrap",[])}shutdown(){this.executeHook("beforeShutdown",[]),this.executeHook("afterShutdown",[])}notifyBlocCreated(e){this.executeHook("onBlocCreated",[e])}notifyBlocDisposed(e){this.executeHook("onBlocDisposed",[e])}notifyStateChanged(e,t,s){this.executeHook("onStateChanged",[e,t,s])}notifyEventAdded(e,t){this.executeHook("onEventAdded",[e,t])}notifyError(e,t,s){this.executeHook("onError",[e,t,s],(r,n)=>{console.error(`Plugin '${n.name}' error handler failed:`,r)})}getMetrics(e){return this.metrics.get(e)}initializeMetrics(e){this.metrics.set(e,new Map)}recordSuccess(e,t,s){const r=this.metrics.get(e),n=r.get(t)||{executionTime:0,executionCount:0,errorCount:0},o=performance.now()-s;r.set(t,{...n,executionTime:n.executionTime+o,executionCount:n.executionCount+1,lastExecutionTime:o})}recordError(e,t,s){const r=this.metrics.get(e),n=r.get(t)||{executionTime:0,executionCount:0,errorCount:0};r.set(t,{...n,errorCount:n.errorCount+1,lastError:s})}}const _=class _{getInstance(){return _._instance||(_._instance=new u({__unsafe_ignore_singleton:!0})),_._instance}setInstance(e){_._instance=e}resetInstance(){const e=_._instance;if(_._instance=new u({__unsafe_ignore_singleton:!0}),e)for(const t of e.keepAliveBlocs)_._instance.keepAliveBlocs.add(t),_._instance.uidRegistry.set(t.uid,t)}};i(_,"_instance");let P=_,S=new P;function Q(c){S=c}const h=class h{constructor(e={}){i(this,"createdAt",Date.now());i(this,"blocInstanceMap",new Map);i(this,"isolatedBlocMap",new Map);i(this,"isolatedBlocIndex",new Map);i(this,"uidRegistry",new Map);i(this,"keepAliveBlocs",new Set);i(this,"postChangesToDocument",!1);i(this,"plugins",new O);i(this,"log",(...e)=>{h.logSpy&&h.logSpy(e),h.enableLog&&h.logLevel,h.enableLog&&h.logLevel});i(this,"warn",(e,...t)=>{h.enableLog});i(this,"error",(e,...t)=>{h.enableLog});i(this,"resetInstance",()=>{this.log("Reset Blac instance");const e=new Map(this.blocInstanceMap),t=new Map(this.isolatedBlocMap);e.forEach(s=>{!s._keepAlive&&s._disposalState===y.ACTIVE&&this.disposeBloc(s)}),t.forEach(s=>{s.forEach(r=>{!r._keepAlive&&r._disposalState===y.ACTIVE&&this.disposeBloc(r)})}),this.blocInstanceMap.clear(),this.isolatedBlocMap.clear(),this.isolatedBlocIndex.clear(),S.resetInstance()});i(this,"disposeBloc",e=>{const t=e._disposalState;if(![y.ACTIVE,y.DISPOSAL_REQUESTED].includes(t)){this.log(`[${e._name}:${String(e._id)}] disposeBloc called on bloc in invalid state: ${t}`);return}const r=e.constructor,n=this.createBlocInstanceMapKey(e._name,e._id);this.log(`[${e._name}:${String(e._id)}] disposeBloc called. Isolated: ${String(r.isolated)}`),e._dispose(),this.plugins.notifyBlocDisposed(e),r.isolated?(this.unregisterIsolatedBlocInstance(e),this.blocInstanceMap.delete(n)):this.unregisterBlocInstance(e),this.log("dispatched bloc",e)});i(this,"activateBloc",e=>{if(e._disposalState!==y.ACTIVE){this.log(`[${e._name}:${String(e._id)}] activateBloc called on disposed bloc. Ignoring.`);return}const t=e.constructor;(e.isIsolated?this.findIsolatedBlocInstance(t,e._id):this.findRegisteredBlocInstance(t,e._id))||(this.log(`[${e._name}:${String(e._id)}] activateBloc called. Isolated: ${String(e.isIsolated)}`),e.isIsolated?this.registerIsolatedBlocInstance(e):this.registerBlocInstance(e))});i(this,"getBloc",(e,t={})=>{const{id:s,forceNewInstance:r}=t,n=e,o=s??e.name;if(this.log(`[${e.name}:${String(o)}] (getBloc) Called:`,{options:t,base:n}),!r)if(n.isolated){const l=this.findIsolatedBlocInstance(e,t.instanceRef??o);if(l)return l;if(t.throwIfNotFound)throw new Error(`Isolated bloc ${e.name} not found`)}else{const l=this.findRegisteredBlocInstance(e,o);if(l)return l;if(t.throwIfNotFound)throw new Error(`Registered bloc ${e.name} not found`)}const a=this.createNewBlocInstance(e,o,t);if(this.log(`[${e.name}:${String(o)}] (getBloc) No existing instance found. Creating new one.`,t,a),!a)throw new Error(`[getBloc] Failed to create bloc instance for ${e.name}. This should never happen.`);return a});i(this,"getBlocOrThrow",(e,t={})=>{const s=e.isolated,r=t.id||e.name,n=s?this.findIsolatedBlocInstance(e,r):this.findRegisteredBlocInstance(e,r);if(n)return n;throw new Error(`Bloc ${e.name} not found`)});i(this,"getAllBlocs",(e,t={})=>{const s=[];if(this.blocInstanceMap.forEach(r=>{r.constructor===e&&s.push(r)}),t.searchIsolated!==!1){const r=this.isolatedBlocMap.get(e);r&&s.push(...r.map(n=>n))}return s});i(this,"disposeKeepAliveBlocs",e=>{const t=[];for(const s of this.keepAliveBlocs)(!e||s.constructor===e)&&t.push(s);t.forEach(s=>s._dispose())});i(this,"disposeBlocs",e=>{const t=[];for(const s of this.blocInstanceMap.values())e(s)&&t.push(s);for(const s of this.isolatedBlocMap.values())for(const r of s)e(r)&&t.push(r);t.forEach(s=>s._dispose())});i(this,"getMemoryStats",()=>({totalBlocs:this.uidRegistry.size,registeredBlocs:this.blocInstanceMap.size,isolatedBlocs:Array.from(this.isolatedBlocMap.values()).reduce((e,t)=>e+t.length,0),keepAliveBlocs:this.keepAliveBlocs.size,isolatedBlocTypes:this.isolatedBlocMap.size}));i(this,"validateConsumers",()=>{for(const e of this.uidRegistry.values())e._validateConsumers(),e._consumers.size===0&&!e._keepAlive&&e._disposalState===y.ACTIVE&&setTimeout(()=>{e._consumers.size===0&&!e._keepAlive&&e._disposalState===y.ACTIVE&&this.disposeBloc(e)},1e3)});const{__unsafe_ignore_singleton:t=!1}=e;if(!t)return h.instance;S.setInstance(this),this.plugins.bootstrap()}static get instance(){return S.getInstance()}static get getAllBlocs(){return h.instance.getAllBlocs}static get config(){return{...this._config}}static setConfig(e){if(e.proxyDependencyTracking!==void 0&&typeof e.proxyDependencyTracking!="boolean")throw new Error("BlacConfig.proxyDependencyTracking must be a boolean");if(e.exposeBlacInstance!==void 0&&typeof e.exposeBlacInstance!="boolean")throw new Error("BlacConfig.exposeBlacInstance must be a boolean");this._config={...this._config,...e},this.enableLog&&this.instance.log("Blac config updated:",this._config)}static get log(){return h.instance.log}static getInstance(){return S.getInstance()}static get warn(){return h.instance.warn}static get error(){return h.instance.error}static get disposeBloc(){return h.instance.disposeBloc}createBlocInstanceMapKey(e,t){return`${e}:${String(t)}`}unregisterBlocInstance(e){const t=this.createBlocInstanceMapKey(e._name,e._id);this.blocInstanceMap.delete(t),this.uidRegistry.delete(e.uid),this.keepAliveBlocs.delete(e)}registerBlocInstance(e){const t=this.createBlocInstanceMapKey(e._name,e._id);this.blocInstanceMap.set(t,e),this.uidRegistry.set(e.uid,e),e._keepAlive&&this.keepAliveBlocs.add(e)}findRegisteredBlocInstance(e,t){if(e.isolated)return;const r=this.createBlocInstanceMapKey(e.name,t);return this.blocInstanceMap.get(r)}registerIsolatedBlocInstance(e){const t=e.constructor,s=this.isolatedBlocMap.get(t);s?s.push(e):this.isolatedBlocMap.set(t,[e]),this.isolatedBlocIndex.set(e.uid,e),this.uidRegistry.set(e.uid,e),e._keepAlive&&this.keepAliveBlocs.add(e)}unregisterIsolatedBlocInstance(e){const t=e.constructor,s=this.isolatedBlocMap.get(t);let r=!1;if(s){const o=s.findIndex(a=>a.uid===e.uid);o!==-1&&(s.splice(o,1),r=!0),s.length===0&&this.isolatedBlocMap.delete(t)}const n=this.isolatedBlocIndex.delete(e.uid);this.uidRegistry.delete(e.uid),this.keepAliveBlocs.delete(e),r!==n&&this.warn(`[Blac] Inconsistent state detected during isolated bloc cleanup for ${e._name}:${e.uid}. Map removal: ${r}, Index removal: ${n}`)}findIsolatedBlocInstance(e,t){if(!e.isolated)return;const r=this.isolatedBlocMap.get(e);return r?r.find(o=>o._id===t):void 0}findIsolatedBlocInstanceByUid(e){return this.isolatedBlocIndex.get(e)}createNewBlocInstance(e,t,s={}){const{props:r,instanceRef:n}=s,o=new e(r);return o._instanceRef=n,o.props=r||null,o._updateId(t),o._setDisposalHandler(a=>this.disposeBloc(a)),o.isIsolated?this.registerIsolatedBlocInstance(o):this.registerBlocInstance(o),o._activatePlugins(),this.plugins.notifyBlocCreated(o),o}static get activateBloc(){return h.instance.activateBloc}static get getBloc(){return h.instance.getBloc}static get getBlocOrThrow(){return h.instance.getBlocOrThrow}static get disposeKeepAliveBlocs(){return h.instance.disposeKeepAliveBlocs}static get disposeBlocs(){return h.instance.disposeBlocs}static get getMemoryStats(){return h.instance.getMemoryStats}static get validateConsumers(){return h.instance.validateConsumers}bootstrap(){this.plugins.bootstrap()}shutdown(){this.plugins.shutdown();for(const e of this.blocInstanceMap.values())e._keepAlive||this.disposeBloc(e);for(const e of this.isolatedBlocMap.values())for(const t of e)t._keepAlive||this.disposeBloc(t)}};i(h,"_config",{exposeBlacInstance:!1,proxyDependencyTracking:!0}),i(h,"enableLog",!1),i(h,"logLevel","warn"),i(h,"logSpy",null),i(h,"resetInstance",()=>{S.resetInstance()});let u=h;class H extends w{constructor(){super(...arguments);i(this,"eventHandlers",new Map);i(this,"_eventQueue",[]);i(this,"_isProcessingEvent",!1);i(this,"add",async t=>{let s=t;try{s=this._plugins.transformEvent(t)}catch(r){console.error("Error transforming event:",r)}if(s!==null){try{this._plugins.notifyEvent(s)}catch(r){console.error("Error notifying plugins of event:",r)}u.instance.plugins.notifyEventAdded(this,s),this._eventQueue.push(s),this._isProcessingEvent||await this._processEventQueue()}})}on(t,s){this.eventHandlers.has(t)&&u.warn(`[Bloc ${this._name}:${String(this._id)}] Handler for event '${t.name}' already registered. It will be overwritten.`),this.eventHandlers.set(t,s)}async _processEventQueue(){if(!this._isProcessingEvent){this._isProcessingEvent=!0;try{for(;this._eventQueue.length>0;){const t=this._eventQueue.shift();await this._processEvent(t)}}finally{this._isProcessingEvent=!1}}}async _processEvent(t){const s=t.constructor,r=this.eventHandlers.get(s);if(r){const n=o=>{const a=this.state;this._pushState(o,a,t)};try{await r(t,n)}catch(o){const a=t.constructor.name||"UnnamedConstructor",l={blocName:this._name,blocId:String(this._id),eventType:a,currentState:this.state,action:t,timestamp:new Date().toISOString()};if(u.error(`[Bloc ${this._name}:${String(this._id)}] Error in event handler for '${a}':`,o,"Context:",l),o instanceof Error)try{this._plugins.notifyError(o,{phase:"event-processing",operation:"handler",metadata:{event:t}}),u.instance.plugins.notifyError(o,this,{phase:"event-processing",operation:"handler",metadata:{event:t}})}catch(d){console.error("Error notifying plugins:",d)}if(o instanceof Error&&o.name==="CriticalError")throw o}}else{const n=t.constructor.name||"UnnamedConstructor";u.warn(`[Bloc ${this._name}:${String(this._id)}] No handler registered for action type: '${n}'.`,"Registered handlers:",Array.from(this.eventHandlers.keys()).map(o=>o.name),"Action was:",t)}}}class U extends w{_updateProps(e){var s;const t=this.props;this.props=e,(s=this.onPropsChanged)==null||s.call(this,t,e)}emit(e){if(Object.is(e,this.state))return;const t=this.state,s=e;this._pushState(s,t)}patch(e,t=!1){if(typeof this.state!="object"||this.state===null){u.warn("Cubit.patch: was called on a cubit where the state is not an object. This is a no-op.");return}let s=!1;if(t)s=!0;else for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){const o=this.state[r];if(!Object.is(e[r],o)){s=!0;break}}s&&this.emit({...this.state,...e})}}class V{constructor(e){this.props=e}}function L(c,e){if(Object.is(c,e))return!0;if(typeof c!="object"||c===null||typeof e!="object"||e===null)return!1;const t=Object.keys(c),s=Object.keys(e);if(t.length!==s.length)return!1;for(let r=0;r<t.length;r++){const n=t[r];if(!Object.prototype.hasOwnProperty.call(e,n)||!Object.is(c[n],e[n]))return!1}return!0}class j{static setUp(){this.originalInstance=u.instance,u.resetInstance(),u.enableLog=!1}static tearDown(){u.resetInstance()}static createBloc(e,...t){const s=new e(...t);return u.activateBloc(s),s}static async waitForState(e,t,s=5e3){return new Promise((r,n)=>{const o=setTimeout(()=>{n(new Error(`Timeout waiting for state matching predicate after ${s}ms`))},s),a=e._observer.subscribe({id:`test-waiter-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,fn:l=>{t(l)&&(clearTimeout(o),a(),r(l))}});t(e.state)&&(clearTimeout(o),a(),r(e.state))})}static async expectStates(e,t,s=5e3){const r=[];return new Promise((n,o)=>{const a=setTimeout(()=>{o(new Error(`Timeout waiting for states. Expected: ${JSON.stringify(t)}, Received: ${JSON.stringify(r)}`))},s),l=e._observer.subscribe({id:`test-expecter-${crypto.randomUUID()}`,fn:d=>{if(r.push(d),r.length===t.length){clearTimeout(a),l();for(let f=0;f<t.length;f++){const m=t[f],v=r[f];if(JSON.stringify(m)!==JSON.stringify(v)){o(new Error(`State mismatch at index ${f}. Expected: ${JSON.stringify(m)}, Received: ${JSON.stringify(v)}`));return}}n()}}})})}}i(j,"originalInstance");class F extends H{constructor(t){super(t);i(this,"mockHandlers",new Map)}mockEventHandler(t,s){this.on(t,s)}getHandlerCount(){return this.eventHandlers.size}hasHandler(t){return this.eventHandlers.has(t)}}class W extends U{constructor(t){super(t);i(this,"stateHistory",[]);this.stateHistory.push(t)}emit(t){this.stateHistory.push(t),super.emit(t)}getStateHistory(){return[...this.stateHistory]}clearStateHistory(){this.stateHistory=[this.state]}}class G{constructor(){i(this,"initialStats");this.initialStats=u.getMemoryStats()}checkForLeaks(){const e=u.getMemoryStats(),t=e.registeredBlocs>this.initialStats.registeredBlocs||e.isolatedBlocs>this.initialStats.isolatedBlocs||e.keepAliveBlocs>this.initialStats.keepAliveBlocs,s=`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var u=(r=>(r.ACTIVE="active",r.DISPOSAL_REQUESTED="disposal_requested",r.DISPOSING="disposing",r.DISPOSED="disposed",r))(u||{});class C{disposalState="active";disposalLock=!1;disposalTimer;disposalHandler;get currentState(){return this.disposalState}get isDisposed(){return this.disposalState==="disposed"}atomicStateTransition(e,t){if(this.disposalLock)return{success:!1,currentState:this.disposalState,previousState:this.disposalState};this.disposalLock=!0;try{if(this.disposalState!==e)return{success:!1,currentState:this.disposalState,previousState:this.disposalState};const s=this.disposalState;return this.disposalState=t,{success:!0,currentState:t,previousState:s}}finally{this.disposalLock=!1}}scheduleDisposal(e,t,s){this.disposalTimer&&(clearTimeout(this.disposalTimer),this.disposalTimer=void 0),this.atomicStateTransition("active","disposal_requested").success&&(this.disposalTimer=setTimeout(()=>{t()&&this.disposalState==="disposal_requested"?s():this.atomicStateTransition("disposal_requested","active")},e))}cancelDisposal(){return this.disposalState==="disposal_requested"?(this.disposalTimer&&(clearTimeout(this.disposalTimer),this.disposalTimer=void 0),this.atomicStateTransition("disposal_requested","active").success):!1}setDisposalHandler(e){this.disposalHandler=e}getDisposalHandler(){return this.disposalHandler}clearDisposalTimer(){this.disposalTimer&&(clearTimeout(this.disposalTimer),this.disposalTimer=void 0)}}class E{plugins=new Map;metrics=new Map;executionOrder=[];add(e){if(this.plugins.has(e.name))throw new Error(`Plugin '${e.name}' is already registered`);this.plugins.set(e.name,e),this.executionOrder.push(e.name),this.initializeMetrics(e.name)}remove(e){return this.plugins.get(e)?(this.plugins.delete(e),this.metrics.delete(e),this.executionOrder=this.executionOrder.filter(s=>s!==e),!0):!1}get(e){return this.plugins.get(e)}getAll(){return this.executionOrder.map(e=>this.plugins.get(e))}clear(){this.plugins.clear(),this.metrics.clear(),this.executionOrder=[]}executeHook(e,t,s){for(const i of this.executionOrder){const n=this.plugins.get(i),a=n[e];if(typeof a!="function")continue;const c=performance.now();try{a.apply(n,t),this.recordSuccess(i,e,c)}catch(l){this.recordError(i,e,l),s?s(l,n):console.error(`Plugin '${i}' error in hook '${e}':`,l)}}}bootstrap(){this.executeHook("beforeBootstrap",[]),this.executeHook("afterBootstrap",[])}shutdown(){this.executeHook("beforeShutdown",[]),this.executeHook("afterShutdown",[])}notifyBlocCreated(e){this.executeHook("onBlocCreated",[e])}notifyBlocDisposed(e){this.executeHook("onBlocDisposed",[e])}notifyStateChanged(e,t,s){this.executeHook("onStateChanged",[e,t,s])}notifyEventAdded(e,t){this.executeHook("onEventAdded",[e,t])}notifyError(e,t,s){this.executeHook("onError",[e,t,s],(i,n)=>{console.error(`Plugin '${n.name}' error handler failed:`,i)})}notifyAdapterCreated(e,t){this.executeHook("onAdapterCreated",[e,t])}notifyAdapterMount(e,t){this.executeHook("onAdapterMount",[e,t])}notifyAdapterUnmount(e,t){this.executeHook("onAdapterUnmount",[e,t])}notifyAdapterRender(e,t){this.executeHook("onAdapterRender",[e,t])}notifyAdapterDisposed(e,t){this.executeHook("onAdapterDisposed",[e,t])}getMetrics(e){return this.metrics.get(e)}initializeMetrics(e){this.metrics.set(e,new Map)}recordSuccess(e,t,s){const i=this.metrics.get(e),n=i.get(t)||{executionTime:0,executionCount:0,errorCount:0},a=performance.now()-s;i.set(t,{...n,executionTime:n.executionTime+a,executionCount:n.executionCount+1,lastExecutionTime:a})}recordError(e,t,s){const i=this.metrics.get(e),n=i.get(t)||{executionTime:0,executionCount:0,errorCount:0};i.set(t,{...n,errorCount:n.errorCount+1,lastError:s})}}var S=(r=>(r.LIFECYCLE="LIFECYCLE",r.STATE="STATE",r.PLUGIN="PLUGIN",r.VALIDATION="VALIDATION",r.DISPOSAL="DISPOSAL",r.CONSUMER="CONSUMER",r))(S||{}),m=(r=>(r.FATAL="FATAL",r.ERROR="ERROR",r.WARNING="WARNING",r.INFO="INFO",r))(m||{});class y extends Error{constructor(e,t,s,i,n){super(e),this.category=t,this.severity=s,this.context=i,this.cause=n,this.name="BlacError",Object.setPrototypeOf(this,y.prototype)}toString(){const e=this.context?` [${Object.entries(this.context).filter(([t,s])=>s!==void 0).map(([t,s])=>`${t}: ${s}`).join(", ")}]`:"";return`${this.name} [${this.severity}/${this.category}]: ${this.message}${e}`}}const w={shouldPropagate:r=>r.severity==="FATAL",shouldLog:r=>r.severity!=="INFO",handle:r=>{w.shouldLog(r)&&console.error(r.toString(),r.cause)}};class g{static instance;handlers=new Set;strategy=w;static getInstance(){return g.instance||(g.instance=new g),g.instance}setStrategy(e){this.strategy=e}addHandler(e){this.handlers.add(e)}removeHandler(e){this.handlers.delete(e)}handle(e){if(this.handlers.forEach(t=>{try{t(e)}catch(s){console.error("Error in error handler:",s)}}),this.strategy.handle(e),this.strategy.shouldPropagate(e))throw e}wrap(e,t){try{return e()}catch(s){const i=t(s);this.handle(i);return}}async wrapAsync(e,t){try{return await e()}catch(s){const i=t(s);this.handle(i);return}}}class f{static _instance;getInstance(){return f._instance||(f._instance=new o({__unsafe_ignore_singleton:!0})),f._instance}setInstance(e){f._instance=e}resetInstance(){const e=f._instance;if(f._instance=new o({__unsafe_ignore_singleton:!0}),e)for(const t of e.keepAliveBlocs)f._instance.keepAliveBlocs.add(t),f._instance.uidRegistry.set(t.uid,t)}}let b=new f;function N(r){b=r}class o{static get instance(){return b.getInstance()}createdAt=Date.now();errorManager=g.getInstance();static get getAllBlocs(){return o.instance.getAllBlocs}static _config={proxyDependencyTracking:!0};static get config(){return{...this._config}}static setConfig(e){if(e.proxyDependencyTracking!==void 0&&typeof e.proxyDependencyTracking!="boolean"){const t=new y("BlacConfig.proxyDependencyTracking must be a boolean",S.VALIDATION,m.FATAL);this.instance.errorManager.handle(t)}this._config={...this._config,...e},this.enableLog&&this.instance.log("Blac config updated:",this._config)}blocInstanceMap=new Map;isolatedBlocMap=new Map;isolatedBlocIndex=new Map;uidRegistry=new Map;keepAliveBlocs=new Set;postChangesToDocument=!1;plugins=new E;constructor(e={}){const{__unsafe_ignore_singleton:t=!1}=e;if(!t)return o.instance;b.setInstance(this),this.plugins.bootstrap()}static enableLog=!1;static logLevel="warn";static logSpy=null;log=(...e)=>{o.logSpy&&o.logSpy(e),o.enableLog&&o.logLevel,o.enableLog&&o.logLevel};static get log(){return o.instance.log}static getInstance(){return b.getInstance()}warn=(e,...t)=>{console.warn(e,...t)};static get warn(){return o.instance.warn}error=(e,...t)=>{o.enableLog&&console.error(e,...t)};static get error(){return o.instance.error}resetInstance=()=>{this.log("Reset Blac instance");const e=new Map(this.blocInstanceMap),t=new Map(this.isolatedBlocMap);e.forEach(s=>{!s._keepAlive&&s._disposalState===u.ACTIVE&&this.disposeBloc(s)}),t.forEach(s=>{s.forEach(i=>{!i._keepAlive&&i._disposalState===u.ACTIVE&&this.disposeBloc(i)})}),this.blocInstanceMap.clear(),this.isolatedBlocMap.clear(),this.isolatedBlocIndex.clear(),b.resetInstance()};static resetInstance=()=>{b.resetInstance()};disposeBloc=e=>{const t=e._disposalState;if(![u.ACTIVE,u.DISPOSAL_REQUESTED].includes(t)){this.log(`[${e._name}:${String(e._id)}] disposeBloc called on bloc in invalid state: ${t}`);return}const i=e.constructor,n=this.createBlocInstanceMapKey(e._name,e._id);this.log(`[${e._name}:${String(e._id)}] disposeBloc called. Isolated: ${String(i.isolated)}`),e.dispose(),this.plugins.notifyBlocDisposed(e),i.isolated?(this.unregisterIsolatedBlocInstance(e),this.blocInstanceMap.delete(n)):this.unregisterBlocInstance(e),this.log("dispatched bloc",e)};static get disposeBloc(){return o.instance.disposeBloc}createBlocInstanceMapKey(e,t){return`${e}:${String(t)}`}unregisterBlocInstance(e){const t=this.createBlocInstanceMapKey(e._name,e._id);this.blocInstanceMap.delete(t),this.uidRegistry.delete(e.uid),this.keepAliveBlocs.delete(e)}registerBlocInstance(e){const t=this.createBlocInstanceMapKey(e._name,e._id);this.blocInstanceMap.set(t,e),this.uidRegistry.set(e.uid,e),e._keepAlive&&this.keepAliveBlocs.add(e)}findRegisteredBlocInstance(e,t){if(e.isolated)return;const i=this.createBlocInstanceMapKey(e.name,t),n=this.blocInstanceMap.get(i);if(!(n&&n.isDisposed))return n}registerIsolatedBlocInstance(e){const t=e.constructor,s=this.isolatedBlocMap.get(t);s?s.push(e):this.isolatedBlocMap.set(t,[e]),this.isolatedBlocIndex.set(e.uid,e),this.uidRegistry.set(e.uid,e),e._keepAlive&&this.keepAliveBlocs.add(e)}unregisterIsolatedBlocInstance(e){const t=e.constructor,s=this.isolatedBlocMap.get(t);let i=!1;if(s){const a=s.findIndex(c=>c.uid===e.uid);a!==-1&&(s.splice(a,1),i=!0),s.length===0&&this.isolatedBlocMap.delete(t)}const n=this.isolatedBlocIndex.delete(e.uid);this.uidRegistry.delete(e.uid),this.keepAliveBlocs.delete(e),i!==n&&this.warn(`[Blac] Inconsistent state detected during isolated bloc cleanup for ${e._name}:${e.uid}. Map removal: ${i}, Index removal: ${n}`)}findIsolatedBlocInstance(e,t){if(!e.isolated)return;const i=this.isolatedBlocMap.get(e);return i?i.find(a=>a._id===t&&!a.isDisposed):void 0}findIsolatedBlocInstanceByUid(e){return this.isolatedBlocIndex.get(e)}createNewBlocInstance(e,t,s={}){const{constructorParams:i,instanceRef:n}=s,a=new e(i);return a.blacInstance=this,a._instanceRef=n,a._id=t,a.setDisposalHandler(c=>this.disposeBloc(c)),a.isIsolated?this.registerIsolatedBlocInstance(a):this.registerBlocInstance(a),this.plugins.notifyBlocCreated(a),a}activateBloc=e=>{if(e._disposalState!==u.ACTIVE){this.log(`[${e._name}:${String(e._id)}] activateBloc called on disposed bloc. Ignoring.`);return}const t=e.constructor;(e.isIsolated?this.findIsolatedBlocInstance(t,e._id):this.findRegisteredBlocInstance(t,e._id))||(this.log(`[${e._name}:${String(e._id)}] activateBloc called. Isolated: ${String(e.isIsolated)}`),e.isIsolated?this.registerIsolatedBlocInstance(e):this.registerBlocInstance(e))};static get activateBloc(){return o.instance.activateBloc}getBloc=(e,t={})=>{const{id:s,forceNewInstance:i}=t,n=e,a=s??e.name;if(this.log(`[${e.name}:${String(a)}] (getBloc) Called:`,{options:t,base:n}),!i)if(n.isolated){const l=this.findIsolatedBlocInstance(e,t.instanceRef??a);if(l)return l;if(t.throwIfNotFound)throw new Error(`Isolated bloc ${e.name} not found`)}else{const l=this.findRegisteredBlocInstance(e,a);if(l)return l;if(t.throwIfNotFound)throw new Error(`Registered bloc ${e.name} not found`)}const c=this.createNewBlocInstance(e,a,t);if(this.log(`[${e.name}:${String(a)}] (getBloc) No existing instance found. Creating new one.`,t,c),!c)throw new Error(`[getBloc] Failed to create bloc instance for ${e.name}. This should never happen.`);return c};static get getBloc(){return o.instance.getBloc}getAllBlocs=(e,t={})=>{const s=[];if(this.blocInstanceMap.forEach(i=>{i.constructor===e&&s.push(i)}),t.searchIsolated!==!1){const i=this.isolatedBlocMap.get(e);i&&s.push(...i.map(n=>n))}return s};disposeKeepAliveBlocs=e=>{const t=[];for(const s of this.keepAliveBlocs)(!e||s.constructor===e)&&t.push(s);t.forEach(s=>s.dispose())};static get disposeKeepAliveBlocs(){return o.instance.disposeKeepAliveBlocs}disposeBlocs=e=>{const t=[];for(const s of this.blocInstanceMap.values())e(s)&&t.push(s);for(const s of this.isolatedBlocMap.values())for(const i of s)e(i)&&t.push(i);t.forEach(s=>s.dispose())};static get disposeBlocs(){return o.instance.disposeBlocs}getMemoryStats=()=>({totalBlocs:this.uidRegistry.size,registeredBlocs:this.blocInstanceMap.size,isolatedBlocs:Array.from(this.isolatedBlocMap.values()).reduce((e,t)=>e+t.length,0),keepAliveBlocs:this.keepAliveBlocs.size,isolatedBlocTypes:this.isolatedBlocMap.size});static get getMemoryStats(){return o.instance.getMemoryStats}validateConsumers=()=>{for(const e of this.uidRegistry.values())e.subscriptionCount===0&&!e._keepAlive&&e._disposalState===u.ACTIVE&&setTimeout(()=>{e.subscriptionCount===0&&!e._keepAlive&&e._disposalState===u.ACTIVE&&this.disposeBloc(e)},1e3)};static get validateConsumers(){return o.instance.validateConsumers}bootstrap(){this.plugins.bootstrap()}shutdown(){this.plugins.shutdown();for(const e of this.blocInstanceMap.values())e._keepAlive||this.disposeBloc(e);for(const e of this.isolatedBlocMap.values())for(const t of e)t._keepAlive||this.disposeBloc(t)}}function A(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}const k={fatal:(r,e,t,s)=>{const i=new y(r,e,m.FATAL,t,s);throw g.getInstance().handle(i),i},error:(r,e,t,s)=>{const i=new y(r,e,m.ERROR,t,s);g.getInstance().handle(i)},warn:(r,e,t,s)=>{const i=new y(r,e,m.WARNING,t,s);g.getInstance().handle(i)},info:(r,e,t)=>{const s=new y(r,e,m.INFO,t);g.getInstance().handle(s)},wrap:(r,e,t,s=m.ERROR)=>{try{return r()}catch(i){const n=i instanceof Error?i.message:String(i),a=new y(n,e,s,t,i);g.getInstance().handle(a);return}},wrapAsync:async(r,e,t,s=m.ERROR)=>{try{return await r()}catch(i){const n=i instanceof Error?i.message:String(i),a=new y(n,e,s,t,i);g.getInstance().handle(a);return}}};class x{plugins=new Map;executionOrder=[];attached=!1;add(e){if(this.plugins.has(e.name))throw new Error(`Plugin '${e.name}' is already registered`);e.capabilities&&this.validateCapabilities(e),this.plugins.set(e.name,e),this.executionOrder.push(e.name)}remove(e){const t=this.plugins.get(e);return t?(this.attached&&t.onDetach&&k.wrap(()=>t.onDetach(),S.PLUGIN,{pluginName:e,operation:"onDetach"}),this.plugins.delete(e),this.executionOrder=this.executionOrder.filter(s=>s!==e),!0):!1}get(e){return this.plugins.get(e)}getAll(){return this.executionOrder.map(e=>this.plugins.get(e))}clear(){if(this.attached)for(const e of this.getAll())e.onDetach&&k.wrap(()=>e.onDetach(),S.PLUGIN,{pluginName:e.name,operation:"onDetach"});this.plugins.clear(),this.executionOrder=[],this.attached=!1}attach(e){if(this.attached)throw new Error("Plugins are already attached");for(const t of this.getAll())if(t.onAttach)try{t.onAttach(e)}catch(s){console.error(`Plugin '${t.name}' error in onAttach:`,s),this.remove(t.name)}this.attached=!0}transformState(e,t){let s=t;for(const i of this.getAll())if(i.transformState&&this.canTransformState(i))try{s=i.transformState(e,s)}catch(n){console.error(`Plugin '${i.name}' error in transformState:`,n)}return s}transformEvent(e){let t=e;for(const s of this.getAll()){if(t===null)break;if(s.transformEvent&&this.canInterceptEvents(s))try{t=s.transformEvent(t)}catch(i){console.error(`Plugin '${s.name}' error in transformEvent:`,i)}}return t}notifyStateChange(e,t){for(const s of this.getAll())if(s.onStateChange&&this.canReadState(s))try{s.onStateChange(e,t)}catch(i){console.error(`Plugin '${s.name}' error in onStateChange:`,i)}}notifyEvent(e){for(const t of this.getAll())if(t.onEvent&&this.canReadState(t))try{t.onEvent(e)}catch(s){console.error(`Plugin '${t.name}' error in onEvent:`,s)}}notifyError(e,t){for(const s of this.getAll())if(s.onError)try{s.onError(e,t)}catch(i){console.error(`Plugin '${s.name}' error in onError:`,i)}}validateCapabilities(e){const t=e.capabilities;if(t.transformState&&!t.readState)throw new Error(`Plugin '${e.name}': transformState requires readState capability`);if(t.interceptEvents&&!t.readState)throw new Error(`Plugin '${e.name}': interceptEvents requires readState capability`)}canReadState(e){return!e.capabilities||e.capabilities.readState!==!1}canTransformState(e){return!e.capabilities||e.capabilities.transformState===!0}canInterceptEvents(e){return!e.capabilities||e.capabilities.interceptEvents===!0}}class T{constructor(e){this.bloc=e}subscriptions=new Map;pathToSubscriptions=new Map;weakRefCleanupScheduled=!1;totalNotifications=0;subscribe(e){const t=`${e.type}-${A()}`,s={id:t,type:e.type,selector:e.selector,equalityFn:e.equalityFn||Object.is,notify:e.notify,priority:e.priority??0,weakRef:e.weakRef,dependencies:new Set,metadata:{lastNotified:Date.now(),hasRendered:!1,accessCount:0,firstAccessTime:Date.now()}};if(s.selector)try{s.lastValue=s.selector(this.bloc.state,this.bloc)}catch(i){o.error(`SubscriptionManager: Error in selector for ${t}:`,i)}return this.subscriptions.set(t,s),o.log(`[${this.bloc._name}:${this.bloc._id}] Subscription added: ${t}. Total: ${this.subscriptions.size}`),this.bloc._cancelDisposalIfRequested(),()=>this.unsubscribe(t)}unsubscribe(e){const t=this.subscriptions.get(e);if(t){if(t.dependencies)for(const s of t.dependencies){const i=this.pathToSubscriptions.get(s);i&&(i.delete(e),i.size===0&&this.pathToSubscriptions.delete(s))}this.subscriptions.delete(e),o.log(`[${this.bloc._name}:${this.bloc._id}] Subscription removed: ${e}. Remaining: ${this.subscriptions.size}`),this.bloc.checkDisposal()}}notify(e,t,s){this.cleanupDeadReferences();const i=Array.from(this.subscriptions.values()).sort((n,a)=>(a.priority??0)-(n.priority??0));for(const n of i){if(n.weakRef&&!n.weakRef.deref()){this.scheduleWeakRefCleanup();continue}let a=!1,c,l;if(n.selector)try{c=n.selector(e,this.bloc),l=n.lastValue,a=!(n.equalityFn||Object.is)(l,c),a&&(n.lastValue=c)}catch(h){o.error(`SubscriptionManager: Error in selector for ${n.id}:`,h);continue}else{if(n.dependencies&&n.dependencies.size>0){const h=this.getChangedPaths(t,e);a=this.shouldNotifyForPaths(n.id,h),o.config.logLevel==="debug"&&(o.log(`[SubscriptionManager] Subscription ${n.id} dependencies:`,Array.from(n.dependencies)),o.log("[SubscriptionManager] Changed paths:",Array.from(h)),o.log("[SubscriptionManager] Should notify:",a))}else a=!0;c=e,l=t}if(a)try{n.notify(c,l,s),this.totalNotifications++,n.metadata&&(n.metadata.lastNotified=Date.now(),n.metadata.hasRendered=!0)}catch(h){o.error(`SubscriptionManager: Error in notify for ${n.id}:`,h)}}}trackAccess(e,t,s){const i=this.subscriptions.get(e);if(!i)return;i.dependencies||(i.dependencies=new Set),i.dependencies.add(t);let n=this.pathToSubscriptions.get(t);n||(n=new Set,this.pathToSubscriptions.set(t,n)),n.add(e),i.metadata&&(i.metadata.accessCount=(i.metadata.accessCount||0)+1,i.metadata.lastAccessTime=Date.now())}getChangedPaths(e,t,s=""){const i=new Set;if(e===t)return i;if(typeof e!="object"||typeof t!="object"||e===null||t===null)return s&&i.add(s),i;const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const a of n){const c=s?`${s}.${a}`:a,l=e[a],h=t[a];l!==h&&(i.add(c),typeof l=="object"&&typeof h=="object"&&l!==null&&h!==null&&this.getChangedPaths(l,h,c).forEach(v=>i.add(v)))}return i}shouldNotifyForPaths(e,t){const s=this.subscriptions.get(e);if(!s||!s.dependencies)return!0;for(const i of s.dependencies){if(i.startsWith("_class.")){if(t.size>0)return!0;continue}if(t.has(i))return!0;for(const n of t)if(n.startsWith(i+".")||i.startsWith(n+"."))return!0}return!1}getStats(){let e=0,t=0;for(const s of this.subscriptions.values())s.type==="consumer"?e++:t++;return{activeSubscriptions:this.subscriptions.size,consumerCount:e,observerCount:t,totalNotifications:this.totalNotifications,trackedDependencies:this.pathToSubscriptions.size}}clear(){this.subscriptions.clear(),this.pathToSubscriptions.clear()}getSubscription(e){return this.subscriptions.get(e)}get hasSubscriptions(){return this.subscriptions.size>0}get size(){return this.subscriptions.size}cleanupDeadReferences(){if(!this.weakRefCleanupScheduled)return;const e=[];for(const[t,s]of this.subscriptions)s.weakRef&&!s.weakRef.deref()&&e.push(t);for(const t of e)this.unsubscribe(t);this.weakRefCleanupScheduled=!1}scheduleWeakRefCleanup(){this.weakRefCleanupScheduled||(this.weakRefCleanupScheduled=!0,queueMicrotask(()=>this.cleanupDeadReferences()))}}class L{pendingUpdates=[];isBatching=!1;batchUpdates(e,t){if(this.isBatching){e();return}this.isBatching=!0,this.pendingUpdates=[];try{if(e(),this.pendingUpdates.length>0){const s=this.pendingUpdates[this.pendingUpdates.length-1];t(s)}}finally{this.isBatching=!1,this.pendingUpdates=[]}}addUpdate(e){this.isBatching&&this.pendingUpdates.push(e)}get isCurrentlyBatching(){return this.isBatching}}class B{uid=A();blacInstance;static isolated=!1;get isIsolated(){return this._isolated}static keepAlive=!1;get isKeepAlive(){return this._keepAlive}_isolated=!1;_id;_instanceRef;_name;_subscriptionManager;_state;_lifecycleManager=new C;_batchingManager=new L;_keepAlive=!1;lastUpdate;_plugins=new x;onDispose;constructor(e){this._state=e,this._id=this.constructor.name,this._name=this.constructor.name,this._subscriptionManager=new T(this);const t=this.constructor;if(this._keepAlive=typeof t.keepAlive=="boolean"?t.keepAlive:!1,this._isolated=typeof t.isolated=="boolean"?t.isolated:!1,this._plugins=new x,t.plugins&&Array.isArray(t.plugins))for(const s of t.plugins)this._plugins.add(s);this._plugins.attach(this)}get state(){return this._lifecycleManager.isDisposed?this._state:this._state}subscribe(e){return this._subscriptionManager.subscribe({type:"observer",notify:t=>e(t)})}subscribeWithSelector(e,t,s){return this._subscriptionManager.subscribe({type:"consumer",selector:e,equalityFn:s,notify:i=>t(i)})}subscribeComponent(e,t){return this._subscriptionManager.subscribe({type:"consumer",weakRef:e,notify:t})}get subscriptionCount(){return this._subscriptionManager.size}trackAccess(e,t,s){this._subscriptionManager.trackAccess(e,t,s)}emit(e,t){this._pushState(e,this._state,t)}_pushState(e,t,s){if(this._lifecycleManager.currentState!==u.ACTIVE){this.blacInstance?.error(`[${this._name}:${this._id}] Attempted state update on ${this._lifecycleManager.currentState} bloc. Update ignored.`);return}if(e===void 0)return;this._state=e;const i=this._plugins.transformState(t,e);if(this._state=i,this._plugins.notifyStateChange(t,i),this.blacInstance?.plugins.notifyStateChanged(this,t,i),this._batchingManager.isCurrentlyBatching){this._batchingManager.addUpdate({newState:i,oldState:t,action:s});return}this._subscriptionManager.notify(i,t,s),this.lastUpdate=Date.now()}_batchUpdates(e){this._batchingManager.batchUpdates(e,t=>{this._subscriptionManager.notify(t.newState,t.oldState,t.action)})}addPlugin(e){if(this._plugins.add(e),this._plugins.attached&&e.onAttach)try{e.onAttach(this)}catch(t){console.error(`Plugin '${e.name}' error in onAttach:`,t)}}removePlugin(e){this._plugins.remove(e.name)}get plugins(){return this._plugins.getAll()}get isDisposed(){return this._lifecycleManager.isDisposed}_atomicStateTransition(e,t){return this._lifecycleManager.atomicStateTransition(e,t)}async dispose(){if(!this._lifecycleManager.atomicStateTransition(u.ACTIVE,u.DISPOSING).success)if(this._lifecycleManager.currentState===u.DISPOSAL_REQUESTED)this._lifecycleManager.atomicStateTransition(u.DISPOSAL_REQUESTED,u.DISPOSING);else return;try{this._subscriptionManager.clear(),this.onDispose&&this.onDispose();for(const s of this._plugins.getAll())try{"onDispose"in s&&typeof s.onDispose=="function"&&s.onDispose(this)}catch(i){console.error("Plugin disposal error:",i)}const t=this._lifecycleManager.getDisposalHandler();t&&t(this)}finally{this._lifecycleManager.atomicStateTransition(u.DISPOSING,u.DISPOSED)}}_scheduleDisposal(){this._subscriptionManager.size===0&&!this._keepAlive&&this._lifecycleManager.scheduleDisposal(16,()=>this._subscriptionManager.size===0&&!this._keepAlive,()=>this.dispose())}setDisposalHandler(e){this._lifecycleManager.setDisposalHandler(e)}checkDisposal(){this._subscriptionManager.size===0&&!this._keepAlive&&this._lifecycleManager.currentState===u.ACTIVE&&this._scheduleDisposal()}_cancelDisposalIfRequested(){this.blacInstance?.log(`[${this._name}:${this._id}] _cancelDisposalIfRequested called. Current state: ${this._lifecycleManager.currentState}`),this._lifecycleManager.cancelDisposal()?this.blacInstance?.log(`[${this._name}:${this._id}] Disposal cancelled - new subscription added`):this._lifecycleManager.currentState===u.DISPOSAL_REQUESTED?this.blacInstance?.warn(`[${this._name}:${this._id}] Failed to cancel disposal. Current state: ${this._lifecycleManager.currentState}`):this._lifecycleManager.isDisposed&&this.blacInstance?.error(`[${this._name}:${this._id}] Cannot cancel disposal - bloc is already disposed`)}}class D extends B{eventHandlers=new Map;_eventQueue=[];_isProcessingEvent=!1;on(e,t){this.eventHandlers.has(e)&&o.warn(`[Bloc ${this._name}:${String(this._id)}] Handler for event '${e.name}' already registered. It will be overwritten.`),this.eventHandlers.set(e,t)}add=async e=>{let t=e;try{t=this._plugins.transformEvent(e)}catch(s){console.error("Error transforming event:",s)}if(t!==null){try{this._plugins.notifyEvent(t)}catch(s){console.error("Error notifying plugins of event:",s)}o.instance.plugins.notifyEventAdded(this,t),this._eventQueue.push(t),this._isProcessingEvent||await this._processEventQueue()}};async _processEventQueue(){if(!this._isProcessingEvent){this._isProcessingEvent=!0;try{for(;this._eventQueue.length>0;){const e=this._eventQueue.shift();await this._processEvent(e)}}finally{this._isProcessingEvent=!1}}}async _processEvent(e){const t=e.constructor,s=this.eventHandlers.get(t);if(s){const i=n=>{const a=this.state;this._pushState(n,a,e)};try{await s(e,i)}catch(n){const a=e.constructor.name||"UnnamedConstructor",c={blocName:this._name,blocId:String(this._id),eventType:a,currentState:this.state,action:e,timestamp:new Date().toISOString()};if(o.error(`[Bloc ${this._name}:${String(this._id)}] Error in event handler for '${a}':`,n,"Context:",c),n instanceof Error)try{this._plugins.notifyError(n,{phase:"event-processing",operation:"handler",metadata:{event:e}}),o.instance.plugins.notifyError(n,this,{phase:"event-processing",operation:"handler",metadata:{event:e}})}catch(l){console.error("Error notifying plugins:",l)}if(n instanceof Error&&n.name==="CriticalError")throw n}}else{const i=e.constructor.name||"UnnamedConstructor";o.warn(`[Bloc ${this._name}:${String(this._id)}] No handler registered for action type: '${i}'.`,"Registered handlers:",Array.from(this.eventHandlers.keys()).map(n=>n.name),"Action was:",e)}}}class R extends B{emit(e){if(Object.is(e,this.state))return;const t=this.state,s=e;this._pushState(s,t)}patch(e,t=!1){if(typeof this.state!="object"||this.state===null){o.warn("Cubit.patch: was called on a cubit where the state is not an object. This is a no-op.");return}let s=!1;if(t)s=!0;else for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const a=this.state[i];if(!Object.is(e[i],a)){s=!0;break}}s&&this.emit({...this.state,...e})}}class U{constructor(e){this.props=e}}function H(r,e){if(Object.is(r,e))return!0;if(typeof r!="object"||r===null||typeof e!="object"||e===null)return!1;const t=Object.keys(r),s=Object.keys(e);if(t.length!==s.length)return!1;for(let i=0;i<t.length;i++){const n=t[i];if(!Object.prototype.hasOwnProperty.call(e,n)||!Object.is(r[n],e[n]))return!1}return!0}function O(r){if(!r||typeof r!="object")return;const e=[];for(const[s,i]of Object.entries(r)){const n=typeof i;(n==="string"||n==="number"||n==="boolean"||i===null||i===void 0)&&e.push([s,i])}if(e.length===0)return;e.sort(([s],[i])=>s.localeCompare(i));const t=[];for(const[s,i]of e)i===null?t.push(`${s}:null`):i===void 0?t.push(`${s}:undefined`):t.push(`${s}:${String(i)}`);return t.join("|")}class V{static componentRenderCounts=new Map;static lastRenderTimestamps=new Map;static groupedLogs=new Map;static groupTimeouts=new Map;static logRerender(e){const t=o._config?.rerenderLogging;if(!t)return;const s=this.parseConfig(t);if(!s.enabled||s.filter&&!s.filter({componentName:e.componentName,blocName:e.blocName}))return;const i=`${e.componentName}-${e.blocId}`,n=this.componentRenderCounts.get(i)||0;this.componentRenderCounts.set(i,n+1),e.renderCount=n+1;const a=this.lastRenderTimestamps.get(i);a&&(e.duration=e.timestamp-a),this.lastRenderTimestamps.set(i,e.timestamp),s.includeStackTrace&&s.level==="detailed"&&(e.stackTrace=new Error().stack),s.groupRerenders?this.logGrouped(e,s):this.logImmediate(e,s)}static parseConfig(e){return e===!0?{enabled:!0,level:"normal"}:typeof e=="string"?{enabled:!0,level:e==="minimal"?"minimal":"detailed"}:{enabled:e.enabled,level:e.level||"normal",filter:e.filter,includeStackTrace:e.includeStackTrace,groupRerenders:e.groupRerenders}}static logImmediate(e,t){const s=this.formatMessage(e,t.level);t.level==="detailed"?(console.group(s.header),s.details&&console.log(s.details),s.values&&console.table(s.values),e.stackTrace&&console.log("Stack trace:",e.stackTrace),console.groupEnd()):console.log(s.header,s.details||"")}static logGrouped(e,t){const s=`${e.componentName}-${e.blocId}`,i=this.groupTimeouts.get(s);i&&clearTimeout(i);const n=this.groupedLogs.get(s)||[];n.push(e),this.groupedLogs.set(s,n);const a=setTimeout(()=>{const c=this.groupedLogs.get(s)||[];this.groupedLogs.delete(s),this.groupTimeouts.delete(s),c.length===1?this.logImmediate(c[0],t):(console.group(`🔄 ${e.componentName} rendered ${c.length} times (${e.blocName})`),c.forEach((l,h)=>{const p=this.formatMessage(l,t.level);console.log(` ${h+1}. ${p.details||p.header}`)}),console.groupEnd())},50);this.groupTimeouts.set(s,a)}static formatMessage(e,t){const s=this.getReasonEmoji(e.reason.type);if(t==="minimal")return{header:`${s} ${e.componentName} #${e.renderCount}`,details:null,values:null};const i=`${s} ${e.componentName} rerender #${e.renderCount} (${e.blocName})`;let n=`Reason: ${e.reason.description||e.reason.type}`;e.duration!==void 0&&(n+=` | Time since last: ${e.duration}ms`),t==="normal"&&e.reason.changedPaths&&e.reason.changedPaths.length>0&&(n+=` | Changed: ${e.reason.changedPaths.join(", ")}`);let a=null;return t==="detailed"&&e.reason.changedPaths&&e.reason.changedPaths.length>0&&(a={},e.reason.changedPaths.forEach(c=>{a[c]={old:e.reason.oldValues?.[c],new:e.reason.newValues?.[c]}}),Object.keys(a).length===0&&(a=null)),{header:i,details:n,values:a}}static getReasonEmoji(e){switch(e){case"state-change":return"📊";case"dependency-change":return"🔗";case"mount":return"🚀";case"props-change":return"📦";default:return"🔄"}}static clear(){this.componentRenderCounts.clear(),this.lastRenderTimestamps.clear(),this.groupedLogs.clear(),this.groupTimeouts.forEach(e=>clearTimeout(e)),this.groupTimeouts.clear()}static getRenderCount(e,t){return this.componentRenderCounts.get(`${e}-${t}`)||0}}class F{static originalInstance;static setUp(){this.originalInstance=o.instance,o.resetInstance(),o.enableLog=!1}static tearDown(){o.resetInstance()}static createBloc(e,...t){const s=new e(...t);return o.activateBloc(s),s}static async waitForState(e,t,s=5e3){return new Promise((i,n)=>{const a=setTimeout(()=>{n(new Error(`Timeout waiting for state matching predicate after ${s}ms`))},s),c=e.subscribe(l=>{t(l)&&(clearTimeout(a),c(),i(l))});t(e.state)&&(clearTimeout(a),c(),i(e.state))})}static async expectStates(e,t,s=5e3){const i=[];return new Promise((n,a)=>{const c=setTimeout(()=>{a(new Error(`Timeout waiting for states. Expected: ${JSON.stringify(t)}, Received: ${JSON.stringify(i)}`))},s),l=e.subscribe(h=>{if(i.push(h),i.length===t.length){clearTimeout(c),l();for(let p=0;p<t.length;p++){const v=t[p],$=i[p];if(JSON.stringify(v)!==JSON.stringify($)){a(new Error(`State mismatch at index ${p}. Expected: ${JSON.stringify(v)}, Received: ${JSON.stringify($)}`));return}}n()}})})}}class j extends D{mockHandlers=new Map;constructor(e){super(e)}mockEventHandler(e,t){this.on(e,t)}getHandlerCount(){return this.eventHandlers.size}hasHandler(e){return this.eventHandlers.has(e)}}class z extends R{stateHistory=[];constructor(e){super(e),this.stateHistory.push(e)}emit(e){this.stateHistory.push(e),super.emit(e)}getStateHistory(){return[...this.stateHistory]}clearStateHistory(){this.stateHistory=[this.state]}}class q{initialStats;constructor(){this.initialStats=o.getMemoryStats()}checkForLeaks(){const e=o.getMemoryStats(),t=e.registeredBlocs>this.initialStats.registeredBlocs||e.isolatedBlocs>this.initialStats.isolatedBlocs||e.keepAliveBlocs>this.initialStats.keepAliveBlocs,s=`
|
|
2
2
|
Memory Leak Detection Report:
|
|
3
3
|
- Initial registered blocs: ${this.initialStats.registeredBlocs}
|
|
4
4
|
- Current registered blocs: ${e.registeredBlocs}
|
|
@@ -7,5 +7,5 @@ Memory Leak Detection Report:
|
|
|
7
7
|
- Initial keep-alive blocs: ${this.initialStats.keepAliveBlocs}
|
|
8
8
|
- Current keep-alive blocs: ${e.keepAliveBlocs}
|
|
9
9
|
- Potential leaks detected: ${t?"YES":"NO"}
|
|
10
|
-
`.trim();return{hasLeaks:t,report:s,stats:e}}}
|
|
10
|
+
`.trim();return{hasLeaks:t,report:s,stats:e}}}const I=new WeakMap,d={stateProxiesCreated:0,classProxiesCreated:0,cacheHits:0,cacheMisses:0,totalProxiesCreated:0},_=(r,e,t,s="")=>{if(!e||!t||typeof r!="object"||r===null)return r;if(!s){let n=I.get(r);n||(n=new WeakMap,I.set(r,n));const a=n.get(e);if(a)return d.cacheHits++,a;d.cacheMisses++}const i=new Proxy(r,{get(n,a){if(typeof a=="symbol"||a==="constructor")return Reflect.get(n,a);const c=s?`${s}.${a}`:a,l=Reflect.get(n,a),h=l&&typeof l=="object";return t.trackAccess(e,"state",c,h?void 0:l),h&&(Array.isArray(l)||Object.getPrototypeOf(l)===Object.prototype)?_(l,e,t,c):l},set:()=>!1,deleteProperty:()=>!1});return s||(I.get(r).set(e,i),d.stateProxiesCreated++,d.totalProxiesCreated++),i},M=(r,e,t)=>{if(!e||!t)return r;let s=I.get(r);s||(s=new WeakMap,I.set(r,s));const i=s.get(e);if(i)return d.cacheHits++,i;d.cacheMisses++;const n=new Proxy(r,{get(a,c){const l=Reflect.get(a,c);if(W(a,c)?.get){const p=l!==null&&typeof l!="object";t.trackAccess(e,"class",String(c),p?l:void 0)}return l}});return s.set(e,n),d.classProxiesCreated++,d.totalProxiesCreated++,n},W=(r,e,t=10)=>{let s=r,i=0;for(;s&&i<t;){const n=Object.getOwnPropertyDescriptor(s,e);if(n)return n;s=Object.getPrototypeOf(s),i++}},P={createStateProxy:r=>_(r.target,r.consumerRef,r.consumerTracker,r.path),createClassProxy:r=>M(r.target,r.consumerRef,r.consumerTracker),getProxyState:r=>_(r.state,r.consumerRef,r.consumerTracker),getProxyBlocInstance:r=>M(r.blocInstance,r.consumerRef,r.consumerTracker),getStats:()=>({...d,propertyAccesses:0,nestedProxiesCreated:0,cacheEfficiency:d.cacheHits+d.cacheMisses>0?`${(d.cacheHits/(d.cacheHits+d.cacheMisses)*100).toFixed(1)}%`:"N/A",lifetime:"0ms",proxiesPerSecond:"N/A"}),resetStats:()=>{d.stateProxiesCreated=0,d.classProxiesCreated=0,d.cacheHits=0,d.cacheMisses=0,d.totalProxiesCreated=0}};class G{id=`adapter-${A()}`;blocConstructor;componentRef={current:{}};blocInstance;unmountTime=0;mountTime=0;subscriptionId;unsubscribe;dependencyValues;isUsingDependencies=!1;trackedPaths=new Set;pendingTrackedPaths=new Set;cachedStateProxy;cachedBlocProxy;lastProxiedState;hasMounted=!1;mountCount=0;lastState;lastDependencyValues;componentName;renderCount=0;lastDependenciesFn;options;constructor(e,t){this.options=t,this.blocConstructor=e.blocConstructor,this.componentRef=e.componentRef,this.isUsingDependencies=!!t?.dependencies,this.updateBlocInstance(),this.isUsingDependencies&&t?.dependencies&&(this.dependencyValues=t.dependencies(this.blocInstance));const s=this.getAdapterMetadata();o.getInstance().plugins.notifyAdapterCreated(this,s)}trackAccess(e,t,s,i){const n=t==="class"?`_class.${s}`:s;this.trackedPaths.add(n),this.subscriptionId?this.blocInstance.trackAccess(this.subscriptionId,n,i):(this.pendingTrackedPaths.add(n),o.config.logLevel==="debug"&&o.log(`[BlacAdapter] trackAccess storing pending path: ${s}`))}updateBlocInstance(){let e=this.options?.instanceId;if(!e&&this.options?.staticProps){const t=O(this.options.staticProps);t&&(e=t)}return this.blocInstance=o.instance.getBloc(this.blocConstructor,{constructorParams:this.options?.staticProps,id:e,instanceRef:this.id}),this.blocInstance}createSubscription=e=>{if(this.isUsingDependencies&&this.options?.dependencies)this.unsubscribe=this.blocInstance.subscribeWithSelector(t=>this.options.dependencies(this.blocInstance),t=>{this.hasDependencyValuesChanged(this.dependencyValues,t)&&(this.dependencyValues=t,e.onChange())});else{const t=new WeakRef(this.componentRef.current);this.unsubscribe=this.blocInstance.subscribeComponent(t,e.onChange);const s=this.blocInstance._subscriptionManager.subscriptions;if(this.subscriptionId=Array.from(s.keys()).pop(),this.subscriptionId&&this.pendingTrackedPaths.size>0){for(const i of this.pendingTrackedPaths)this.blocInstance.trackAccess(this.subscriptionId,i);this.pendingTrackedPaths.clear()}}return()=>{this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0,this.subscriptionId=void 0)}};hasDependencyValuesChanged=(e,t)=>{if(!e||e.length!==t.length)return!0;for(let s=0;s<e.length;s++)if(!Object.is(e[s],t[s]))return!0;return!1};getStateProxy=()=>{if(this.isUsingDependencies||!o.config.proxyDependencyTracking)return this.blocInstance.state;const e=this.blocInstance.state;return this.cachedStateProxy&&this.lastProxiedState===e?this.cachedStateProxy:(this.lastProxiedState=e,this.cachedStateProxy=this.createStateProxy({target:e}),this.cachedStateProxy)};getBlocProxy=()=>this.isUsingDependencies||!o.config.proxyDependencyTracking?this.blocInstance:this.cachedBlocProxy?this.cachedBlocProxy:(this.cachedBlocProxy=this.createClassProxy({target:this.blocInstance}),this.cachedBlocProxy);createStateProxy=e=>P.createStateProxy({target:e.target,consumerRef:this.componentRef.current,consumerTracker:this});createClassProxy=e=>P.createClassProxy({target:e.target,consumerRef:this.componentRef.current,consumerTracker:this});mount=()=>{this.hasMounted=!0,this.mountCount++,this.mountTime=Date.now(),this.options?.onMount&&this.options.onMount(this.blocInstance),this.isUsingDependencies&&this.options?.dependencies&&(this.dependencyValues=this.options.dependencies(this.blocInstance));const e=this.getAdapterMetadata();o.getInstance().plugins.notifyAdapterMount(this,e)};unmount=()=>{if(this.unmountTime=Date.now(),this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0,this.subscriptionId=void 0),this.options?.onUnmount)try{this.options.onUnmount(this.blocInstance)}catch(t){console.error("Error in onUnmount hook:",t)}const e=this.getAdapterMetadata();o.getInstance().plugins.notifyAdapterUnmount(this,e)};resetTracking(){if(this.trackedPaths.clear(),this.pendingTrackedPaths.clear(),this.subscriptionId){const e=this.blocInstance._subscriptionManager.subscriptions.get(this.subscriptionId);e&&e.dependencies&&e.dependencies.clear()}}setComponentName(e){this.componentName=e}notifyRender(){this.renderCount++,this.isUsingDependencies&&this.options?.dependencies&&(this.lastDependencyValues=this.dependencyValues,this.dependencyValues=this.options.dependencies(this.blocInstance));const e=this.getAdapterMetadata();o.getInstance().plugins.notifyAdapterRender(this,e)}getAdapterMetadata(){return{componentName:this.componentName,blocInstance:this.blocInstance,renderCount:this.renderCount,trackedPaths:Array.from(this.trackedPaths),isUsingDependencies:this.isUsingDependencies,lastState:this.lastState,lastDependencyValues:this.lastDependencyValues,currentDependencyValues:this.dependencyValues}}getValueAtPath(e,t){const s=t.split(".");let i=e;for(const n of s){if(i==null)return;i=i[n]}return i}getStateChangedPaths(e,t){const s=[];if(this.trackedPaths.size>0)for(const i of this.trackedPaths){if(i.startsWith("_class."))continue;const n=this.getValueAtPath(e,i),a=this.getValueAtPath(t,i);Object.is(n,a)||s.push(i)}else if(e!==t){const i=this.getDeepChangedPaths(e,t);if(i.length>0)return i;s.push("(entire state)")}return s}getDeepChangedPaths(e,t,s=""){const i=[];if(e===t)return i;if(e==null||t==null)return i.push(s||"(root)"),i;if(typeof e!="object"||typeof t!="object")return e!==t&&i.push(s||"(root)"),i;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return i.push(s||"(root)"),i;for(let a=0;a<e.length;a++){const c=s?`${s}[${a}]`:`[${a}]`;i.push(...this.getDeepChangedPaths(e[a],t[a],c))}return i}const n=new Set([...Object.keys(e),...Object.keys(t)]);for(const a of n){const c=s?`${s}.${a}`:a;if(!(a in e))i.push(`${c} (added)`);else if(!(a in t))i.push(`${c} (removed)`);else{const l=e[a],h=t[a];if(!Object.is(l,h))if(typeof l!="object"||typeof h!="object"||l===null||h===null)i.push(c);else{const p=this.getDeepChangedPaths(l,h,c);p.length>0?i.push(...p):i.push(c)}}}return i}getLastRerenderReason(){}}exports.Blac=o;exports.BlacAdapter=G;exports.BlacError=y;exports.Bloc=D;exports.BlocBase=B;exports.BlocLifecycleManager=C;exports.BlocLifecycleState=u;exports.BlocPluginRegistry=x;exports.BlocTest=F;exports.Cubit=R;exports.DefaultErrorStrategy=w;exports.ErrorCategory=S;exports.ErrorManager=g;exports.ErrorSeverity=m;exports.MemoryLeakDetector=q;exports.MockBloc=j;exports.MockCubit=z;exports.PropsUpdated=U;exports.ProxyFactory=P;exports.RerenderLogger=V;exports.SubscriptionManager=T;exports.SystemPluginRegistry=E;exports.createBlocProxy=M;exports.createStateProxy=_;exports.generateInstanceIdFromProps=O;exports.generateUUID=A;exports.handleError=k;exports.setBlacInstanceManager=N;exports.shallowEqual=H;
|
|
11
11
|
//# sourceMappingURL=index.cjs.js.map
|