@blac/core 2.0.0-rc-8 → 2.0.0-rc-11
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 +27 -0
- package/dist/index.cjs.js +2 -2
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +224 -14
- package/dist/index.es.js +1122 -556
- package/dist/index.es.js.map +1 -1
- package/package.json +5 -4
- package/src/Blac.ts +109 -47
- package/src/BlacObserver.ts +58 -24
- package/src/Bloc.ts +120 -160
- package/src/BlocBase.ts +266 -90
- package/src/Cubit.ts +15 -1
- package/src/__tests__/Blac.config.test.ts +86 -0
- package/src/__tests__/Bloc.event.test.ts +419 -0
- package/src/__tests__/BlocBase.lifecycle.test.ts +441 -0
- package/src/__tests__/Cubit.test.ts +473 -0
- package/src/__tests__/props.test.ts +256 -0
- package/src/adapter/BlacAdapter.ts +327 -0
- package/src/adapter/ConsumerTracker.ts +241 -0
- package/src/adapter/ProxyFactory.ts +308 -0
- package/src/adapter/__tests__/BlacAdapter.test.ts +561 -0
- package/src/adapter/__tests__/ConsumerTracker.test.ts +562 -0
- package/src/adapter/__tests__/ProxyFactory.test.ts +655 -0
- package/src/adapter/index.ts +3 -0
- package/src/events.ts +3 -0
- package/src/index.ts +4 -1
- package/src/testing.ts +60 -47
- package/src/types.ts +12 -13
- package/src/utils/shallowEqual.ts +40 -0
- package/src/utils/uuid.ts +4 -4
- package/src/BlacEvent.ts +0 -5
package/README.md
CHANGED
|
@@ -25,6 +25,33 @@ yarn add @blac/core
|
|
|
25
25
|
npm install @blac/core
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
+
## Configuration
|
|
29
|
+
|
|
30
|
+
BlaC provides global configuration options to customize its behavior:
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
import { Blac } from '@blac/core';
|
|
34
|
+
|
|
35
|
+
// Configure BlaC before using it
|
|
36
|
+
Blac.setConfig({
|
|
37
|
+
// Enable/disable automatic dependency tracking for optimized re-renders
|
|
38
|
+
proxyDependencyTracking: true, // default: true
|
|
39
|
+
|
|
40
|
+
// Expose Blac instance globally for debugging
|
|
41
|
+
exposeBlacInstance: false // default: false
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// Read current configuration
|
|
45
|
+
const config = Blac.config;
|
|
46
|
+
console.log(config.proxyDependencyTracking); // true
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### Configuration Options
|
|
50
|
+
|
|
51
|
+
- **`proxyDependencyTracking`**: When enabled (default), BlaC automatically tracks which state properties your components access and only triggers re-renders when those specific properties change. Disable this for simpler behavior where any state change triggers re-renders.
|
|
52
|
+
|
|
53
|
+
- **`exposeBlacInstance`**: When enabled, exposes the BlaC instance globally (useful for debugging). Not recommended for production.
|
|
54
|
+
|
|
28
55
|
## Testing
|
|
29
56
|
|
|
30
57
|
Blac provides comprehensive testing utilities to make testing your state management logic simple and powerful:
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var k=Object.defineProperty;var $=(d,e,t)=>e in d?k(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t;var i=(d,e,t)=>$(d,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=class u{getInstance(){return u._instance||(u._instance=new l({__unsafe_ignore_singleton:!0})),u._instance}setInstance(e){u._instance=e}resetInstance(){const e=u._instance;if(u._instance=new l({__unsafe_ignore_singleton:!0}),e)for(const t of e.keepAliveBlocs)u._instance.keepAliveBlocs.add(t),u._instance.uidRegistry.set(t.uid,t)}};i(u,"_instance");let v=u,g=new v;function M(d){g=d}const r=class r{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,"log",(...e)=>{r.enableLog&&r.logLevel==="warn"&&console.warn(`☢️ [Blac ${this.createdAt.toString()}]`,...e),r.enableLog&&r.logLevel==="log"&&console.log(`☢️ [Blac ${this.createdAt.toString()}]`,...e)});i(this,"warn",(e,...t)=>{r.enableLog&&console.warn(`🚨 [Blac ${String(r.instance.createdAt)}]`,e,...t)});i(this,"error",(e,...t)=>{r.enableLog&&console.error(`🚨 [Blac ${String(r.instance.createdAt)}]`,e,...t)});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==="active"&&this.disposeBloc(s)}),t.forEach(s=>{s.forEach(n=>{!n._keepAlive&&n._disposalState==="active"&&this.disposeBloc(n)})}),this.blocInstanceMap.clear(),this.isolatedBlocMap.clear(),this.isolatedBlocIndex.clear(),g.resetInstance()});i(this,"disposeBloc",e=>{if(e._disposalState!=="active"){this.log(`[${e._name}:${String(e._id)}] disposeBloc called on already disposed bloc`);return}const t=e.constructor,s=this.createBlocInstanceMapKey(e._name,e._id);this.log(`[${e._name}:${String(e._id)}] disposeBloc called. Isolated: ${String(t.isolated)}`),e._dispose(),t.isolated?(this.unregisterIsolatedBlocInstance(e),this.blocInstanceMap.delete(s)):this.unregisterBlocInstance(e),this.log("dispatched bloc",e)});i(this,"activateBloc",e=>{if(e._disposalState!=="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}=t,n=e,o=s??e.name;if(n.isolated){const c=this.findIsolatedBlocInstance(e,o);if(c)return c;if(t.throwIfNotFound)throw new Error(`Isolated bloc ${e.name} not found`)}else{const c=this.findRegisteredBlocInstance(e,o);if(c)return c;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,n=t.id||e.name,o=s?this.findIsolatedBlocInstance(e,n):this.findRegisteredBlocInstance(e,n);if(o)return o;throw new Error(`Bloc ${e.name} not found`)});i(this,"getAllBlocs",(e,t={})=>{const s=[];if(this.blocInstanceMap.forEach(n=>{n.constructor===e&&s.push(n)}),t.searchIsolated!==!1){const n=this.isolatedBlocMap.get(e);n&&s.push(...n.map(o=>o))}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 n of s)e(n)&&t.push(n);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==="active"&&setTimeout(()=>{e._consumers.size===0&&!e._keepAlive&&e._disposalState==="active"&&this.disposeBloc(e)},1e3)});const{__unsafe_ignore_singleton:t=!1}=e;if(!t)return r.instance;g.setInstance(this)}static get instance(){return g.getInstance()}static get getAllBlocs(){return r.instance.getAllBlocs}static get log(){return r.instance.log}static getInstance(){return g.getInstance()}static get warn(){return r.instance.warn}static get error(){return r.instance.error}static get disposeBloc(){return r.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 n=this.createBlocInstanceMapKey(e.name,t);return this.blocInstanceMap.get(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 n=!1;if(s){const a=s.findIndex(c=>c.uid===e.uid);a!==-1&&(s.splice(a,1),n=!0),s.length===0&&this.isolatedBlocMap.delete(t)}const o=this.isolatedBlocIndex.delete(e.uid);this.uidRegistry.delete(e.uid),this.keepAliveBlocs.delete(e),n!==o&&this.warn(`[Blac] Inconsistent state detected during isolated bloc cleanup for ${e._name}:${e.uid}. Map removal: ${n}, Index removal: ${o}`)}findIsolatedBlocInstance(e,t){if(!e.isolated)return;const n=this.isolatedBlocMap.get(e);return n?n.find(a=>a._id===t):void 0}findIsolatedBlocInstanceByUid(e){return this.isolatedBlocIndex.get(e)}createNewBlocInstance(e,t,s={}){const{props:n,instanceRef:o}=s,a=new e(n);return a._instanceRef=o,a.props=n||null,a._updateId(t),a._setDisposalHandler(c=>this.disposeBloc(c)),a.isIsolated?(this.registerIsolatedBlocInstance(a),a):(this.registerBlocInstance(a),a)}static get activateBloc(){return r.instance.activateBloc}static get getBloc(){return r.instance.getBloc}static get getBlocOrThrow(){return r.instance.getBlocOrThrow}static get disposeKeepAliveBlocs(){return r.instance.disposeKeepAliveBlocs}static get disposeBlocs(){return r.instance.disposeBlocs}static get getMemoryStats(){return r.instance.getMemoryStats}static get validateConsumers(){return r.instance.validateConsumers}};i(r,"enableLog",!1),i(r,"logLevel","warn"),i(r,"resetInstance",()=>{g.resetInstance()});let l=r;class I{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){return l.log("BlacObservable.subscribe: Subscribing observer.",this.bloc,e),this._observers.add(e),()=>{l.log("BlacObservable.subscribe: Unsubscribing observer.",this.bloc,e),this.unsubscribe(e)}}unsubscribe(e){this._observers.delete(e),this.size===0&&(l.log("BlacObservable.unsubscribe: No observers left.",this.bloc),this.bloc._consumers.size===0&&!this.bloc._keepAlive&&this.bloc._disposalState==="active"&&(l.log(`[${this.bloc._name}:${this.bloc._id}] No observers or consumers left. Scheduling disposal.`),this.bloc._scheduleDisposal()))}notify(e,t,s){this._observers.forEach(n=>{let o=!1;if(n.dependencyArray){const a=n.lastState,c=n.dependencyArray(e,t);if(!a)o=!0;else if(a.length!==c.length)o=!0;else for(let h=0;h<c.length;h++){const B=a[h]||[],p=c[h]||[];if(B.length!==p.length){o=!0;break}for(let f=0;f<p.length;f++)if(!Object.is(B[f],p[f])){o=!0;break}if(o)break}n.lastState=c}else o=!0;o&&n.fn(e,t,s)})}clear(){this._observers.clear()}}function y(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(d){const e=Math.random()*16|0;return(d==="x"?e:e&3|8).toString(16)})}class _{constructor(e){i(this,"uid",y());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,"_state");i(this,"_oldState");i(this,"props",null);i(this,"_batchingLock",!1);i(this,"_pendingUpdates",[]);i(this,"_consumerRefs",new Map);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;this._disposalState==="active"&&(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}`)))});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){console.warn("BlocBase._pushState: newState is undefined",this);return}if(s!==void 0&&typeof s!="object"&&typeof s!="function"){console.warn("BlocBase._pushState: Invalid action type",this,s);return}if(this._batchingEnabled){this._pendingUpdates.push({newState:e,oldState:t,action:s}),this._oldState=t,this._state=e;return}this._oldState=t,this._state=e,this._observer.notify(e,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 I(this),this._id=this.constructor.name;const t=this.constructor;this._keepAlive=typeof t.keepAlive=="boolean"?t.keepAlive:!1,this._isolated=typeof t.isolated=="boolean"?t.isolated:!1}get isIsolated(){return this._isolated}get isKeepAlive(){return this._keepAlive}get state(){return this._state}get _name(){return this.constructor.name}_dispose(){var e;this._disposalState==="active"&&(this._disposalState="disposing",this._consumers.clear(),this._consumerRefs.clear(),this._observer.clear(),(e=this.onDispose)==null||e.call(this),this._disposalState="disposed")}_setDisposalHandler(e){this._disposalHandler=e}_scheduleDisposal(){this._disposalState==="active"&&this._consumers.size===0&&!this._keepAlive&&(this._disposalHandler?this._disposalHandler(this):this._dispose())}}i(_,"isolated",!1),i(_,"keepAlive",!1);class b extends _{constructor(){super(...arguments);i(this,"eventHandlers",new Map);i(this,"_eventQueue",[]);i(this,"_isProcessingEvent",!1);i(this,"add",async t=>{this._eventQueue.push(t),this._isProcessingEvent||await this._processEventQueue()})}on(t,s){this.eventHandlers.has(t)&&l.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,n=this.eventHandlers.get(s);if(n){const o=a=>{const c=this.state;this._pushState(a,c,t)};try{await n(t,o)}catch(a){const c=t.constructor.name||"UnnamedConstructor",h={blocName:this._name,blocId:String(this._id),eventType:c,currentState:this.state,action:t,timestamp:new Date().toISOString()};if(l.error(`[Bloc ${this._name}:${String(this._id)}] Error in event handler for '${c}':`,a,"Context:",h),a instanceof Error&&a.name==="CriticalError")throw a}}else{const o=t.constructor.name||"UnnamedConstructor";l.warn(`[Bloc ${this._name}:${String(this._id)}] No handler registered for action type: '${o}'.`,"Registered handlers:",Array.from(this.eventHandlers.keys()).map(a=>a.name),"Action was:",t)}}}class w extends _{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){l.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 n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const a=this.state[n];if(!Object.is(e[n],a)){s=!0;break}}s&&this.emit({...this.state,...e})}}class S{static setUp(){this.originalInstance=l.instance,l.resetInstance(),l.enableLog=!1}static tearDown(){l.resetInstance()}static createBloc(e,...t){const s=new e(...t);return l.activateBloc(s),s}static async waitForState(e,t,s=5e3){return new Promise((n,o)=>{const a=setTimeout(()=>{o(new Error(`Timeout waiting for state matching predicate after ${s}ms`))},s),c=e._observer.subscribe({id:`test-waiter-${crypto.randomUUID()}`,fn:h=>{t(h)&&(clearTimeout(a),c(),n(h))}});t(e.state)&&(clearTimeout(a),c(),n(e.state))})}static async expectStates(e,t,s=5e3){const n=[];return new Promise((o,a)=>{const c=setTimeout(()=>{a(new Error(`Timeout waiting for states. Expected: ${JSON.stringify(t)}, Received: ${JSON.stringify(n)}`))},s),h=e._observer.subscribe({id:`test-expecter-${crypto.randomUUID()}`,fn:B=>{if(n.push(B),n.length===t.length){clearTimeout(c),h();for(let p=0;p<t.length;p++){const f=t[p],m=n[p];if(JSON.stringify(f)!==JSON.stringify(m)){a(new Error(`State mismatch at index ${p}. Expected: ${JSON.stringify(f)}, Received: ${JSON.stringify(m)}`));return}}o()}}})})}}i(S,"originalInstance");class x extends b{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 A extends w{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 E{constructor(){i(this,"initialStats");this.initialStats=l.getMemoryStats()}checkForLeaks(){const e=l.getMemoryStats(),t=e.registeredBlocs>this.initialStats.registeredBlocs||e.isolatedBlocs>this.initialStats.isolatedBlocs||e.keepAliveBlocs>this.initialStats.keepAliveBlocs,s=`
|
|
1
|
+
"use strict";var j=Object.defineProperty;var z=(c,e,t)=>e in c?j(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var i=(c,e,t)=>z(c,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class ${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===_.DISPOSED||t===_.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===_.DISPOSAL_REQUESTED&&(u.log("BlacObservable.subscribe: Cancelling disposal due to new subscription.",this.bloc),this.bloc._atomicStateTransition(_.DISPOSAL_REQUESTED,_.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===_.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(n=>{let r=!1;if(n.dependencyArray){const o=n.lastState,a=n.dependencyArray(e,t,this.bloc);if(!o)r=!0;else if(o.length!==a.length)r=!0;else for(let d=0;d<a.length;d++)if(!Object.is(o[d],a[d])){r=!0;break}n.lastState=a}else r=!0;r&&n.fn(e,t,s)})}clear(){this._observers.clear()}}function P(){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)})}var _=(c=>(c.ACTIVE="active",c.DISPOSAL_REQUESTED="disposal_requested",c.DISPOSING="disposing",c.DISPOSED="disposed",c))(_||{});class w{constructor(e){i(this,"uid",P());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,"_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")){if(this._batchingEnabled){this._pendingUpdates.push({newState:e,oldState:t,action:s}),this._oldState=t,this._state=e;return}this._oldState=t,this._state=e,this._observer.notify(e,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 $(this),this._id=this.constructor.name;const t=this.constructor;this._keepAlive=typeof t.keepAlive=="boolean"?t.keepAlive:!1,this._isolated=typeof t.isolated=="boolean"?t.isolated:!1}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,n,r,o;if(this._disposalState===e){const a=this._disposalState;return this._disposalState=t,(s=globalThis.Blac)!=null&&s.enableLog&&((n=globalThis.Blac)==null||n.log(`[${this._name}:${this._id}] State transition: ${a} -> ${t} (SUCCESS)`)),{success:!0,currentState:t,previousState:a}}return(r=globalThis.Blac)!=null&&r.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")})}}i(w,"isolated",!1),i(w,"keepAlive",!1);const y=class y{getInstance(){return y._instance||(y._instance=new u({__unsafe_ignore_singleton:!0})),y._instance}setInstance(e){y._instance=e}resetInstance(){const e=y._instance;if(y._instance=new u({__unsafe_ignore_singleton:!0}),e)for(const t of e.keepAliveBlocs)y._instance.keepAliveBlocs.add(t),y._instance.uidRegistry.set(t.uid,t)}};i(y,"_instance");let C=y,B=new C;function q(c){B=c}const l=class l{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,"log",(...e)=>{l.logSpy&&l.logSpy(e),l.enableLog&&l.logLevel,l.enableLog&&l.logLevel});i(this,"warn",(e,...t)=>{l.enableLog});i(this,"error",(e,...t)=>{l.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===_.ACTIVE&&this.disposeBloc(s)}),t.forEach(s=>{s.forEach(n=>{!n._keepAlive&&n._disposalState===_.ACTIVE&&this.disposeBloc(n)})}),this.blocInstanceMap.clear(),this.isolatedBlocMap.clear(),this.isolatedBlocIndex.clear(),B.resetInstance()});i(this,"disposeBloc",e=>{const t=e._disposalState;if(![_.ACTIVE,_.DISPOSAL_REQUESTED].includes(t)){this.log(`[${e._name}:${String(e._id)}] disposeBloc called on bloc in invalid state: ${t}`);return}const n=e.constructor,r=this.createBlocInstanceMapKey(e._name,e._id);this.log(`[${e._name}:${String(e._id)}] disposeBloc called. Isolated: ${String(n.isolated)}`),e._dispose(),n.isolated?(this.unregisterIsolatedBlocInstance(e),this.blocInstanceMap.delete(r)):this.unregisterBlocInstance(e),this.log("dispatched bloc",e)});i(this,"activateBloc",e=>{if(e._disposalState!==_.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:n}=t,r=e,o=s??e.name;if(this.log(`[${e.name}:${String(o)}] (getBloc) Called:`,{options:t,base:r}),!n)if(r.isolated){const d=this.findIsolatedBlocInstance(e,t.instanceRef??o);if(d)return d;if(t.throwIfNotFound)throw new Error(`Isolated bloc ${e.name} not found`)}else{const d=this.findRegisteredBlocInstance(e,o);if(d)return d;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,n=t.id||e.name,r=s?this.findIsolatedBlocInstance(e,n):this.findRegisteredBlocInstance(e,n);if(r)return r;throw new Error(`Bloc ${e.name} not found`)});i(this,"getAllBlocs",(e,t={})=>{const s=[];if(this.blocInstanceMap.forEach(n=>{n.constructor===e&&s.push(n)}),t.searchIsolated!==!1){const n=this.isolatedBlocMap.get(e);n&&s.push(...n.map(r=>r))}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 n of s)e(n)&&t.push(n);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===_.ACTIVE&&setTimeout(()=>{e._consumers.size===0&&!e._keepAlive&&e._disposalState===_.ACTIVE&&this.disposeBloc(e)},1e3)});const{__unsafe_ignore_singleton:t=!1}=e;if(!t)return l.instance;B.setInstance(this)}static get instance(){return B.getInstance()}static get getAllBlocs(){return l.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 l.instance.log}static getInstance(){return B.getInstance()}static get warn(){return l.instance.warn}static get error(){return l.instance.error}static get disposeBloc(){return l.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 n=this.createBlocInstanceMapKey(e.name,t);return this.blocInstanceMap.get(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 n=!1;if(s){const o=s.findIndex(a=>a.uid===e.uid);o!==-1&&(s.splice(o,1),n=!0),s.length===0&&this.isolatedBlocMap.delete(t)}const r=this.isolatedBlocIndex.delete(e.uid);this.uidRegistry.delete(e.uid),this.keepAliveBlocs.delete(e),n!==r&&this.warn(`[Blac] Inconsistent state detected during isolated bloc cleanup for ${e._name}:${e.uid}. Map removal: ${n}, Index removal: ${r}`)}findIsolatedBlocInstance(e,t){if(!e.isolated)return;const n=this.isolatedBlocMap.get(e);return n?n.find(o=>o._id===t):void 0}findIsolatedBlocInstanceByUid(e){return this.isolatedBlocIndex.get(e)}createNewBlocInstance(e,t,s={}){const{props:n,instanceRef:r}=s,o=new e(n);return o._instanceRef=r,o.props=n||null,o._updateId(t),o._setDisposalHandler(a=>this.disposeBloc(a)),o.isIsolated?(this.registerIsolatedBlocInstance(o),o):(this.registerBlocInstance(o),o)}static get activateBloc(){return l.instance.activateBloc}static get getBloc(){return l.instance.getBloc}static get getBlocOrThrow(){return l.instance.getBlocOrThrow}static get disposeKeepAliveBlocs(){return l.instance.disposeKeepAliveBlocs}static get disposeBlocs(){return l.instance.disposeBlocs}static get getMemoryStats(){return l.instance.getMemoryStats}static get validateConsumers(){return l.instance.validateConsumers}};i(l,"_config",{exposeBlacInstance:!1,proxyDependencyTracking:!0}),i(l,"enableLog",!1),i(l,"logLevel","warn"),i(l,"logSpy",null),i(l,"resetInstance",()=>{B.resetInstance()});let u=l;class E extends w{constructor(){super(...arguments);i(this,"eventHandlers",new Map);i(this,"_eventQueue",[]);i(this,"_isProcessingEvent",!1);i(this,"add",async t=>{this._eventQueue.push(t),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,n=this.eventHandlers.get(s);if(n){const r=o=>{const a=this.state;this._pushState(o,a,t)};try{await n(t,r)}catch(o){const a=t.constructor.name||"UnnamedConstructor",d={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:",d),o instanceof Error&&o.name==="CriticalError")throw o}}else{const r=t.constructor.name||"UnnamedConstructor";u.warn(`[Bloc ${this._name}:${String(this._id)}] No handler registered for action type: '${r}'.`,"Registered handlers:",Array.from(this.eventHandlers.keys()).map(o=>o.name),"Action was:",t)}}}class O 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 n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const o=this.state[n];if(!Object.is(e[n],o)){s=!0;break}}s&&this.emit({...this.state,...e})}}class U{constructor(e){this.props=e}}function V(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 n=0;n<t.length;n++){const r=t[n];if(!Object.prototype.hasOwnProperty.call(e,r)||!Object.is(c[r],e[r]))return!1}return!0}class H{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((n,r)=>{const o=setTimeout(()=>{r(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:d=>{t(d)&&(clearTimeout(o),a(),n(d))}});t(e.state)&&(clearTimeout(o),a(),n(e.state))})}static async expectStates(e,t,s=5e3){const n=[];return new Promise((r,o)=>{const a=setTimeout(()=>{o(new Error(`Timeout waiting for states. Expected: ${JSON.stringify(t)}, Received: ${JSON.stringify(n)}`))},s),d=e._observer.subscribe({id:`test-expecter-${crypto.randomUUID()}`,fn:p=>{if(n.push(p),n.length===t.length){clearTimeout(a),d();for(let h=0;h<t.length;h++){const m=t[h],I=n[h];if(JSON.stringify(m)!==JSON.stringify(I)){o(new Error(`State mismatch at index ${h}. Expected: ${JSON.stringify(m)}, Received: ${JSON.stringify(I)}`));return}}r()}}})})}}i(H,"originalInstance");class K extends E{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 Q extends O{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 W{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=`
|
|
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}}}exports.Blac=
|
|
10
|
+
`.trim();return{hasLeaks:t,report:s,stats:e}}}class N{constructor(){i(this,"consumers",new WeakMap);i(this,"registrationCount",0);i(this,"activeConsumers",0)}register(e,t){this.registrationCount++,this.consumers.get(e)||this.activeConsumers++,this.consumers.set(e,{id:t,lastNotified:Date.now(),hasRendered:!1,stateAccesses:new Set,classAccesses:new Set,stateValues:new Map,classValues:new Map,accessCount:0,lastAccessTime:0,firstAccessTime:0})}unregister(e){e&&this.consumers.get(e)&&(this.consumers.delete(e),this.activeConsumers=Math.max(0,this.activeConsumers-1))}trackAccess(e,t,s,n){const r=this.consumers.get(e);if(!r)return;const o=Date.now();r.firstAccessTime||(r.firstAccessTime=o),r.accessCount++,r.lastAccessTime=o,t==="state"?(r.stateAccesses.add(s),n!==void 0&&r.stateValues.set(s,{value:n,lastAccessTime:o})):(r.classAccesses.add(s),n!==void 0&&r.classValues.set(s,{value:n,lastAccessTime:o}))}resetTracking(e){const t=this.consumers.get(e);t&&(t.stateAccesses.clear(),t.classAccesses.clear(),t.stateValues.clear(),t.classValues.clear(),t.accessCount=0,t.firstAccessTime=0)}getDependencies(e){const t=this.consumers.get(e);return t?{statePaths:Array.from(t.stateAccesses),classPaths:Array.from(t.classAccesses)}:null}hasValuesChanged(e,t,s){const n=this.consumers.get(e);if(!n)return!0;let r=!1;const o=Date.now();if(n.stateValues.size===0&&n.classValues.size===0&&(n.stateAccesses.size>0||n.classAccesses.size>0))return!0;for(const[a,d]of n.stateValues)try{const p=this.getValueAtPath(t,a);p!==d.value&&(n.stateValues.set(a,{value:p,lastAccessTime:o}),r=!0)}catch{r=!0}for(const[a,d]of n.classValues)try{const p=this.getValueAtPath(s,a);p!==d.value&&(n.classValues.set(a,{value:p,lastAccessTime:o}),r=!0)}catch{r=!0}return r}shouldNotifyConsumer(e,t){const s=this.consumers.get(e);if(!s)return!1;for(const n of t){if(s.stateAccesses.has(n)||s.classAccesses.has(n))return!0;for(const r of s.stateAccesses)if(n.startsWith(r+".")||r.startsWith(n+"."))return!0}return!1}updateLastNotified(e){const t=this.consumers.get(e);t&&(t.lastNotified=Date.now())}getConsumerInfo(e){return this.consumers.get(e)}setHasRendered(e,t){const s=this.consumers.get(e);s&&(s.hasRendered=t)}hasConsumer(e){return this.consumers.has(e)}getStats(){return{totalRegistrations:this.registrationCount,activeConsumers:this.activeConsumers}}getValueAtPath(e,t){const s=t.split(".");let n=e;for(const r of s){if(n==null)return;n=n[r]}return n}}const A=new WeakMap;let f={stateProxiesCreated:0,classProxiesCreated:0,cacheHits:0,cacheMisses:0,propertyAccesses:0,nestedProxiesCreated:0,totalProxiesCreated:0,createdAt:Date.now()};class v{static createStateProxy(e){const{target:t,consumerRef:s,consumerTracker:n,path:r=""}=e;if(!s||!n||typeof t!="object"||t===null)return t;let o=A.get(t);o||(o=new WeakMap,A.set(t,o));const a=o.get(s);if(a)return f.cacheHits++,a;f.cacheMisses++;const d={get(h,m){if(typeof m=="symbol"||m==="constructor")return Reflect.get(h,m);const I=r?`${r}.${m}`:m;f.propertyAccesses++;const g=Reflect.get(h,m),k=g&&typeof g==="object"&&g!==null?void 0:g;if(n.trackAccess(s,"state",I,k),g&&typeof g=="object"&&g!==null){const S=Object.getPrototypeOf(g)===Object.prototype,R=Array.isArray(g);if(S||R)return f.nestedProxiesCreated++,v.createStateProxy({target:g,consumerRef:s,consumerTracker:n,path:I})}return g},has(h,m){return m in h},ownKeys(h){return Reflect.ownKeys(h)},getOwnPropertyDescriptor(h,m){return Reflect.getOwnPropertyDescriptor(h,m)},set(){return!1},deleteProperty(){return!1}},p=new Proxy(t,d);return o.set(s,p),f.stateProxiesCreated++,f.totalProxiesCreated++,p}static createClassProxy(e){const{target:t,consumerRef:s,consumerTracker:n}=e;if(!s||!n)return t;let r=A.get(t);r||(r=new WeakMap,A.set(t,r));const o=r.get(s);if(o)return f.cacheHits++,o;f.cacheMisses++;const a={get(p,h){const m=Reflect.get(p,h);let I=!1,g=p;const x=new WeakSet,M=10;let k=0;for(;g&&!I&&k<M&&!x.has(g);){x.add(g);try{const T=Object.getOwnPropertyDescriptor(g,h);if(T&&T.get){I=!0;break}g=Object.getPrototypeOf(g),k++}catch{break}}if(!I)return m;f.propertyAccesses++;const S=m,L=S!==null&&typeof S!="object"?S:void 0;return n.trackAccess(s,"class",String(h),L),m},has(p,h){return h in p},ownKeys(p){return Reflect.ownKeys(p)},getOwnPropertyDescriptor(p,h){return Reflect.getOwnPropertyDescriptor(p,h)}},d=new Proxy(t,a);return r.set(s,d),f.classProxiesCreated++,f.totalProxiesCreated++,d}static getProxyState(e){return v.createStateProxy({target:e.state,consumerRef:e.consumerRef,consumerTracker:e.consumerTracker})}static getProxyBlocInstance(e){return v.createClassProxy({target:e.blocInstance,consumerRef:e.consumerRef,consumerTracker:e.consumerTracker})}static getStats(){const e=Date.now()-f.createdAt;return{...f,totalProxies:f.stateProxiesCreated+f.classProxiesCreated,cacheEfficiency:f.cacheHits+f.cacheMisses>0?`${(f.cacheHits/(f.cacheHits+f.cacheMisses)*100).toFixed(1)}%`:"N/A",lifetime:`${e}ms`,proxiesPerSecond:e>0?(f.totalProxiesCreated/(e/1e3)).toFixed(2):"N/A"}}static resetStats(){f={stateProxiesCreated:0,classProxiesCreated:0,cacheHits:0,cacheMisses:0,propertyAccesses:0,nestedProxiesCreated:0,totalProxiesCreated:0,createdAt:Date.now()}}}const b=class b{constructor(e,t){i(this,"id",`consumer-${P()}`);i(this,"blocConstructor");i(this,"componentRef",{current:{}});i(this,"blocInstance");i(this,"consumerTracker");i(this,"lastProps");i(this,"unmountTime",0);i(this,"mountTime",0);i(this,"dependencyValues");i(this,"isUsingDependencies",!1);i(this,"hasMounted",!1);i(this,"mountCount",0);i(this,"options");i(this,"createStateProxy",e=>v.createStateProxy({target:e.target,consumerRef:this.componentRef.current,consumerTracker:this}));i(this,"createClassProxy",e=>v.createClassProxy({target:e.target,consumerRef:this.componentRef.current,consumerTracker:this}));i(this,"createSubscription",e=>this.blocInstance._observer.subscribe({id:this.id,fn:(s,n)=>{var r;if(this.isUsingDependencies&&((r=this.options)!=null&&r.dependencies)){const o=this.options.dependencies(this.blocInstance);if(!this.hasDependencyValuesChanged(this.dependencyValues,o))return;this.dependencyValues=o}else if(u.config.proxyDependencyTracking){const o=this.consumerTracker.getConsumerInfo(this.componentRef.current);if(o&&o.hasRendered&&!this.consumerTracker.hasValuesChanged(this.componentRef.current,s,this.blocInstance))return}else{e.onChange();return}e.onChange()}}));i(this,"mount",()=>{var e,t;if(this.isUsingDependencies&&((e=this.options)!=null&&e.dependencies)&&(this.dependencyValues=this.options.dependencies(this.blocInstance)),this.mountCount++,this.blocInstance._addConsumer(this.id,this.componentRef.current),!this.hasMounted&&(this.hasMounted=!0,this.mountTime=Date.now(),(t=this.options)!=null&&t.onMount))try{this.options.onMount(this.blocInstance)}catch(s){throw s}});i(this,"unmount",()=>{var e;if(this.unmountTime=Date.now(),this.consumerTracker.unregister(this.componentRef.current),this.blocInstance._removeConsumer(this.id),b.propsOwners.get(this.blocInstance)===this.id&&b.propsOwners.delete(this.blocInstance),(e=this.options)!=null&&e.onUnmount)try{this.options.onUnmount(this.blocInstance)}catch{}});i(this,"getProxyState",e=>this.isUsingDependencies||!u.config.proxyDependencyTracking?e:v.getProxyState({state:e,consumerRef:this.componentRef.current,consumerTracker:this}));i(this,"getProxyBlocInstance",()=>this.isUsingDependencies||!u.config.proxyDependencyTracking?this.blocInstance:v.getProxyBlocInstance({blocInstance:this.blocInstance,consumerRef:this.componentRef.current,consumerTracker:this}));this.options=t,this.blocConstructor=e.blocConstructor,this.componentRef=e.componentRef,this.isUsingDependencies=!!(t!=null&&t.dependencies),this.consumerTracker=new N,this.blocInstance=this.updateBlocInstance(),this.consumerTracker.register(e.componentRef.current,this.id),this.isUsingDependencies&&(t!=null&&t.dependencies)&&(this.dependencyValues=t.dependencies(this.blocInstance)),(t==null?void 0:t.props)!==void 0&&this.updateProps(t.props)}trackAccess(e,t,s,n){this.consumerTracker.trackAccess(e,t,s,n)}getConsumerDependencies(e){return this.consumerTracker.getDependencies(e)}shouldNotifyConsumer(e,t){const s=this.consumerTracker.getConsumerInfo(e);return!s||!s.hasRendered?!0:this.consumerTracker.shouldNotifyConsumer(e,t)}updateLastNotified(e){this.consumerTracker.updateLastNotified(e),this.consumerTracker.setHasRendered(e,!0)}resetConsumerTracking(){this.consumerTracker.resetTracking(this.componentRef.current)}updateBlocInstance(){var e,t;return this.blocInstance=u.instance.getBloc(this.blocConstructor,{props:(e=this.options)==null?void 0:e.props,id:(t=this.options)==null?void 0:t.id,instanceRef:this.id}),this.blocInstance}get calledOnMount(){return this.hasMounted}updateProps(e){const t=this.blocInstance;if(b.propsOwners.has(t)||b.propsOwners.set(t,this.id),b.propsOwners.get(t)!==this.id){u.warn(`[BlacAdapter] Attempted to set props on ${t.constructor.name} from non-owner adapter`);return}t._disposalState===_.DISPOSED||t._disposalState===_.DISPOSING||V(this.lastProps,e)||("add"in t&&typeof t.add=="function"?t.add(new U(e)):"_updateProps"in t&&typeof t._updateProps=="function"&&t._updateProps(e),this.lastProps=e)}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}};i(b,"propsOwners",new WeakMap);let D=b;exports.Blac=u;exports.BlacAdapter=D;exports.BlacObservable=$;exports.Bloc=E;exports.BlocBase=w;exports.BlocLifecycleState=_;exports.BlocTest=H;exports.ConsumerTracker=N;exports.Cubit=O;exports.MemoryLeakDetector=W;exports.MockBloc=K;exports.MockCubit=Q;exports.PropsUpdated=U;exports.ProxyFactory=v;exports.generateUUID=P;exports.setBlacInstanceManager=q;exports.shallowEqual=V;
|
|
11
11
|
//# sourceMappingURL=index.cjs.js.map
|