@yoltra/core 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/yoltra.cjs CHANGED
@@ -1,11 +1,6 @@
1
1
  /*!
2
- * @yoltra/core v0.6.0
2
+ * @yoltra/core v0.8.0
3
3
  * (c) 2026 Manu Ramirez <@pixerael>
4
- * License: MIT
5
- * Homepage: https://yoltra.dev
6
- *
7
- * This source code is licensed under the MIT license found in the
8
- * LICENSE file in the root directory of this source tree
9
- */
10
- "use strict";var G=Object.defineProperty;var J=(c,e,t)=>e in c?G(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var p=(c,e,t)=>J(c,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class B{constructor(){p(this,"handlers",new Map)}on(e,t,s){let n=this.handlers.get(e);n||(n=new Map,this.handlers.set(e,n));let r=n.get(t);return r||(r=new Set,n.set(t,r)),r.add(s),()=>this.off(e,t,s)}off(e,t,s){const n=this.handlers.get(e);if(!n)return;const r=n.get(t);r&&(r.delete(s),r.size===0&&n.delete(t),n.size===0&&this.handlers.delete(e))}emit(e,t,s,n){const r=this.handlers.get(e);if(!r)return;const o=r.get(t);if(!(!o||o.size===0))for(const d of[...o])try{d(s,n)}catch(i){console.error("EventBus handler error:",i)}}clear(){this.handlers.clear()}}class H{constructor(){p(this,"handlers",new Map);p(this,"patternHandlers",new Map);p(this,"patternIndex",new Map)}on(e,t,s){const n=String(t);if(this.isPattern(n)){const r=n;this.patternHandlers.has(e)||this.patternHandlers.set(e,new Map);const o=this.patternHandlers.get(e);return o.has(r)||(o.set(r,[]),this.indexPattern(e,r)),o.get(r).push(s),()=>this.offPattern(e,r,s)}else{const r=this.normalizeTypeKey(n);this.handlers.has(e)||this.handlers.set(e,new Map);const o=this.handlers.get(e);return o.has(r)||o.set(r,[]),o.get(r).push(s),()=>this.offExactNormalized(e,r,s)}}off(e,t,s){const n=this.normalizeTypeKey(String(t));this.offExactNormalized(e,n,s)}offExactNormalized(e,t,s){const n=this.handlers.get(e);if(!n)return;const r=n.get(t);if(!r)return;const o=r.indexOf(s);o!==-1&&r.splice(o,1),r.length===0&&n.delete(t),n.size===0&&this.handlers.delete(e)}offPattern(e,t,s){const n=this.patternHandlers.get(e);if(!n)return;const r=n.get(t);if(!r)return;const o=r.indexOf(s);o!==-1&&r.splice(o,1),r.length===0&&(n.delete(t),this.unindexPattern(e,t)),n.size===0&&(this.patternHandlers.delete(e),this.patternIndex.delete(e))}emit(e,t,s){const n=String(t),r=this.normalizeTypeKey(n),o=this.handlers.get(e)?.get(r)??[],d=this.matchingPatternHandlers(e,n),i=new Set,a=l=>{for(const u of[...l])if(!i.has(u)){i.add(u);try{u(s)}catch(f){console.error(f);continue}}};a(o);for(const l of d)a(l)}emitWith(e,t,s){const n=String(t),r=this.normalizeTypeKey(n),o=this.handlers.get(e)?.get(r)??[],d=this.matchingPatternHandlers(e,n);if(o.length===0&&d.length===0)return;const i=s(),a=new Set,l=u=>{for(const f of[...u])if(!a.has(f)){a.add(f);try{f(i)}catch(m){console.error(m);continue}}};l(o);for(const u of d)l(u)}isPattern(e){return e.includes("*")}normalizeTypeKey(e){return e.replace(/^\./,"")}splitPath(e){return this.normalizeTypeKey(e).split(".").filter(Boolean)}indexPattern(e,t){let s=this.patternIndex.get(e);s===void 0&&(s={byHead:new Map,anyHead:[]},this.patternIndex.set(e,s));const n=this.splitPath(t),r={pattern:t,segments:n},o=n[0];if(o===void 0||o==="*"||o==="**"){s.anyHead.push(r);return}const d=s.byHead.get(o);d===void 0?s.byHead.set(o,[r]):d.push(r)}unindexPattern(e,t){const s=this.patternIndex.get(e);if(s===void 0)return;const n=this.splitPath(t)[0],r=n===void 0||n==="*"||n==="**"?s.anyHead:s.byHead.get(n);if(r===void 0)return;const o=r.findIndex(d=>d.pattern===t);o!==-1&&r.splice(o,1),r.length===0&&r!==s.anyHead&&n!==void 0&&s.byHead.delete(n)}matchingPatternHandlers(e,t){const s=this.patternHandlers.get(e),n=this.patternIndex.get(e);if(s===void 0||s.size===0||n===void 0)return[];const r=this.splitPath(t),o=[],d=a=>{for(const l of a){if(!this.matchSegments(l.segments,r))continue;const u=s.get(l.pattern);u!==void 0&&o.push(u)}},i=r[0];if(i!==void 0){const a=n.byHead.get(i);a!==void 0&&d(a)}return d(n.anyHead),o}matchSegments(e,t){let s=0,n=0,r=-1,o=0;for(;n<t.length;)if(s<e.length&&(e[s]==="*"||e[s]===t[n]))s++,n++;else if(s<e.length&&e[s]==="**")r=s,o=n,s++;else if(r!==-1)s=r+1,n=++o;else return!1;for(;s<e.length&&e[s]==="**";)s++;return s===e.length}clear(){this.handlers.clear(),this.patternHandlers.clear(),this.patternIndex.clear()}__introspect(){const e=[];for(const[t,s]of this.handlers)for(const[n,r]of s)r.length>0&&e.push({channel:t,type:n,count:r.length});for(const[t,s]of this.patternHandlers)for(const[n,r]of s)r.length>0&&e.push({channel:t,type:n,count:r.length});return e}}class W{constructor(e){p(this,"_reduce");this._reduce=e}reduce(e,t){return this._reduce(e,t)}}const D=new Set;function x(c,e){const t=c?`${c}.${e}`:e;D.has(t)||(D.add(t),console.warn(`[yoltra] State key "${e}"${c?` under "${c}"`:""} contains a dot. Paths are dotted, so this key is indistinguishable from nested objects of the same name: a subscription to "${t}" may match the wrong value, and DevTools patches for it will address the wrong node. Rename the key, or nest it.`))}function T(c,e,t="",s=new Map){const n=[];return R(c,e,t,s,n),n}function R(c,e,t,s,n){if(c===e)return;if(typeof c!="object"||typeof e!="object"||c===null||e===null){if(typeof c=="number"&&Number.isNaN(c)&&Number.isNaN(e))return;n.push(t);return}if(c instanceof Date&&e instanceof Date){c.getTime()!==e.getTime()&&n.push(t);return}if(c instanceof RegExp&&e instanceof RegExp){(c.source!==e.source||e.flags!==c.flags)&&n.push(t);return}if(c instanceof Map||e instanceof Map){n.push(t);return}if(c instanceof Set||e instanceof Set){n.push(t);return}const r=c,o=e,d=s.get(r);if(d?.has(o))return;const i=d??new Set;i.add(o),d||s.set(r,i);try{const a=Array.isArray(c),l=Array.isArray(e);if(a!==l){n.push(t);return}if(a){const h=c,y=e;h.length!==y.length&&t&&n.push(t);const g=Math.min(h.length,y.length);for(let E=0;E<g;E++)h[E]!==y[E]&&R(h[E],y[E],t?`${t}.${E}`:`${E}`,s,n);for(let E=g;E<Math.max(h.length,y.length);E++)n.push(t?`${t}.${E}`:`${E}`);return}const u=Object.keys(c),f=Object.keys(e);if(u.length===0&&f.length===0){n.push(t);return}let m=u.length===f.length;if(m){for(let h=0;h<f.length;h++)if(!Object.prototype.hasOwnProperty.call(c,f[h])){m=!1;break}}if(m){for(const h of f)c[h]!==e[h]&&(process.env.NODE_ENV!=="production"&&h.includes(".")&&x(t,h),R(c[h],e[h],t?`${t}.${h}`:h,s,n));return}for(const h of f){const y=Object.prototype.hasOwnProperty.call(c,h);if(y&&c[h]===e[h])continue;process.env.NODE_ENV!=="production"&&h.includes(".")&&x(t,h);const g=t?`${t}.${h}`:h;if(!y){n.push(g);continue}R(c[h],e[h],g,s,n)}for(const h of u)Object.prototype.hasOwnProperty.call(e,h)||(process.env.NODE_ENV!=="production"&&h.includes(".")&&x(t,h),n.push(t?`${t}.${h}`:h))}finally{i.delete(o),i.size===0&&s.delete(r)}}function k(c,e=new WeakSet,t){if(c===null||typeof c!="object"||e.has(c)||(t!==void 0&&c===t.watch&&t.onFound(),Object.isFrozen(c)))return c;if(e.add(c),Array.isArray(c)){const s=c;for(let n=0;n<s.length;n++)s[n]=k(s[n],e,t);return Object.freeze(s)}for(const s of Object.getOwnPropertyNames(c)){const n=Object.getOwnPropertyDescriptor(c,s);!n||!("value"in n)||(c[s]=k(c[s],e,t))}for(const s of Object.getOwnPropertySymbols(c)){const n=Object.getOwnPropertyDescriptor(c,s);!n||!("value"in n)||(c[s]=k(c[s],e,t))}return Object.freeze(c)}const K=Symbol.for("yoltra.rejected");function q(c){return{[K]:!0,reason:c}}function F(c){return typeof c=="object"&&c!==null&&c[K]===!0}class Y{constructor(e){p(this,"highWaterMark");p(this,"buffer",[]);p(this,"takers",[]);p(this,"putters",[]);p(this,"consuming",!1);p(this,"ended",!1);p(this,"closed",!1);p(this,"dropped",0);this.highWaterMark=e}get droppedCount(){return this.dropped}beginConsuming(){this.consuming=!0}put(e){if(this.closed||this.ended)return Promise.resolve();const t=this.takers.shift();return t!==void 0?(t({value:e,done:!1}),Promise.resolve()):this.buffer.length<this.highWaterMark?(this.buffer.push(e),Promise.resolve()):this.consuming?new Promise(s=>{this.putters.push({item:e,release:s})}):(this.dropped++,Promise.resolve())}take(){this.consuming=!0;const e=this.buffer.shift();if(e!==void 0){const s=this.putters.shift();return s!==void 0&&(this.buffer.push(s.item),s.release()),Promise.resolve({value:e,done:!1})}const t=this.putters.shift();return t!==void 0?(t.release(),Promise.resolve({value:t.item,done:!1})):this.closed||this.ended?Promise.resolve({value:void 0,done:!0}):new Promise(s=>{this.takers.push(s)})}end(){if(this.ended||this.closed)return;this.ended=!0;let e=this.putters.shift();for(;e!==void 0;)this.buffer.push(e.item),e.release(),e=this.putters.shift();let t=this.takers.shift();for(;t!==void 0;){const s=this.buffer.shift();t(s!==void 0?{value:s,done:!1}:{value:void 0,done:!0}),t=this.takers.shift()}}close(){if(this.closed)return;this.closed=!0,this.buffer.length=0;let e=this.takers.shift();for(;e!==void 0;)e({value:void 0,done:!0}),e=this.takers.shift();let t=this.putters.shift();for(;t!==void 0;)t.release(),t=this.putters.shift()}}class U extends Error{constructor(t,s,n){super(`[yoltra] call to "${t}/${s}" saw no correlated reply for ${n}ms. The timeout is idle rather than total, so this means the responder went quiet, not that it was slow. Check that something handles "${t}/${s}" and that its reply is emitted through the \`emit\` it was handed — a reply emitted from an unrelated context carries no causal link, and needs an explicit correlationId instead.`);p(this,"channel");p(this,"type");p(this,"idleMs");this.name="CallTimeoutError",this.channel=t,this.type=s,this.idleMs=n}}class I extends Error{constructor(e){super(`[yoltra] call aborted: ${e}`),this.name="CallAbortedError"}}function X(c){const[e,t]=c;if(t===void 0)return{channel:e,isTerminal:()=>!0};if(typeof t=="string")return{channel:e,isTerminal:n=>n===t};const s=new Set(t);return{channel:e,isTerminal:n=>s.has(n)}}function Z(c,e,t){return c.parentId===e?!0:t===void 0?!1:c.meta?.correlationId===t}function ee(c,e){try{return structuredClone(e)}catch(t){throw new Error(`[yoltra] Initial state for slice "${String(c)}" could not be copied: ${t instanceof Error?t.message:String(t)}. State must be structured-cloneable — functions, class instances and DOM nodes are not. Keep behaviour out of state and store plain data.`)}}function O(c,e){return process.env.NODE_ENV==="production"?c:k(c,new WeakSet,e)}const z=100,te=64,A=16,ne=3e4,se=16,$=Object.freeze({committed:!1,written:!1}),re=Object.freeze({committed:!0,written:!1}),ie=Object.freeze({committed:!0,written:!0}),j=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();class P{constructor(e){p(this,"name");p(this,"middleware");p(this,"reducers");p(this,"state");p(this,"reducerBus");p(this,"connectorBus");p(this,"listeners",new Set);p(this,"effects",new Map);p(this,"patternEffects",new Set);p(this,"committedEventSubscribers",new Map);p(this,"uncommittedEventSubscribers",new Map);p(this,"writtenEventSubscribers",new Map);p(this,"allEventSubscribers",new Map);p(this,"sliceUnsubs",new Map);p(this,"patternReducers",new Map);p(this,"replayEnabled");p(this,"idFactory");p(this,"onEffectError");p(this,"onReducerError");p(this,"warnedPayloadAliases",new Set);p(this,"reduceQueue",[]);p(this,"isReducing",!1);p(this,"currentEvent",null);p(this,"transitionsThisDrain",0);p(this,"maxReduceDepth");p(this,"maxTransitionsPerDrain");p(this,"onCascade");p(this,"onRejected");p(this,"instrumentObservers",new Set);p(this,"changedPathSink",null);p(this,"stagingSink",null);p(this,"stagedRejection",null);p(this,"stagedRejectedBy","");p(this,"inFlightEffects",0);p(this,"processedEvents",new Map);p(this,"dedupCount",0);p(this,"effectMeta",new WeakMap);p(this,"dedupConfig");p(this,"eventCleanupTimer",null);if(this.name=e.name??"yoltra Store",this.reducerBus=new B,this.connectorBus=new H,this.middleware=[...e.middleware??[]],this.reducers={},this.state={},this.replayEnabled=e.devtools?.allowReplay??!1,this.idFactory=e.idFactory??(()=>crypto.randomUUID()),this.onEffectError=e.onEffectError,this.onReducerError=e.onReducerError,this.maxReduceDepth=e.maxReduceDepth??te,this.maxTransitionsPerDrain=e.maxTransitionsPerDrain??1/0,this.onCascade=e.onCascade,this.onRejected=e.onRejected,this.dedupConfig={windowMs:e.dedupWindowMs??0,maxCacheSize:1e3},Object.entries(e.reducer).forEach(([t,s])=>{this.mountSlice(t,s,{preserveState:!1})}),e.effects?.length)for(const t of e.effects)this.registerEffect(t);this.dispose=this.dispose.bind(this),this.notifyEffects=this.notifyEffects.bind(this),this.__applyExternalState=this.__applyExternalState.bind(this),this.__replayEvents=this.__replayEvents.bind(this),this.__devtoolsIntrospect=this.__devtoolsIntrospect.bind(this),this.mountSlice=this.mountSlice.bind(this),this.unmountSlice=this.unmountSlice.bind(this),this.getAtPath=this.getAtPath.bind(this),this.emit=this.emit.bind(this),this.subscribe=this.subscribe.bind(this),this.connect=this.connect.bind(this),this.onEffect=this.onEffect.bind(this),this.onEvent=this.onEvent.bind(this),this.getState=this.getState.bind(this),this.registerEffect=this.registerEffect.bind(this),this.registerMiddleware=this.registerMiddleware.bind(this),this.registerReducer=this.registerReducer.bind(this),this.replaceMiddleware=this.replaceMiddleware.bind(this),this.replaceEffects=this.replaceEffects.bind(this),this.replaceReducers=this.replaceReducers.bind(this),this.hotReplace=this.hotReplace.bind(this)}dispose(){this.eventCleanupTimer&&(clearInterval(this.eventCleanupTimer),this.eventCleanupTimer=null),this.processedEvents.clear(),this.effects.clear(),this.patternEffects.clear(),this.effectMeta=new WeakMap,this.warnedPayloadAliases.clear(),this.listeners.clear(),this.committedEventSubscribers.clear(),this.uncommittedEventSubscribers.clear(),this.writtenEventSubscribers.clear(),this.allEventSubscribers.clear(),this.instrumentObservers.clear(),this.connectorBus.clear(),this.reducerBus.clear(),this.patternReducers.clear(),this.sliceUnsubs.clear(),this.changedPathSink=null}fingerprint(e,t,s){const n=`${e}::${t}`;try{if(s==null)return`${n}::null`;if(typeof s!="object")return`${n}::${String(s)}`;const r=JSON.stringify(s);return`${n}::${r}`}catch{return`${n}::${Date.now()}::${Math.random()}`}}shouldDedupe(e,t){const s=Date.now(),n=this.processedEvents.get(e);return n!==void 0&&s-n<t?(this.dedupCount++,!0):(this.processedEvents.set(e,s),this.ensureCleanupTimer(),this.processedEvents.size>this.dedupConfig.maxCacheSize&&this.pruneProcessedEvents(s),!1)}ensureCleanupTimer(){this.eventCleanupTimer===null&&(this.eventCleanupTimer=setInterval(()=>{this.pruneProcessedEvents(Date.now())},5e3),this.eventCleanupTimer.unref?.())}pruneProcessedEvents(e){const t=Math.max(this.dedupConfig.windowMs,z),s=e-t*2;for(const[n,r]of this.processedEvents)r<s&&this.processedEvents.delete(n);this.processedEvents.size===0&&this.eventCleanupTimer!==null&&(clearInterval(this.eventCleanupTimer),this.eventCleanupTimer=null)}reportCascade(e,t,s,n,r){console.error(`[yoltra] Cascade stopped: "${s.channel}/${s.type}" would exceed ${e} (${t}). This event was refused and the chain ends here. A chain this long is almost always two consumers emitting into each other — check what reacts to "${s.channel}/${s.type}" and what that emits in turn.`+(r.length>0?` Recent causal chain: ${r.join(" → ")} → (refused).`:""));try{this.onCascade?.({limit:e,limitValue:t,event:s,depth:n,chain:r})}catch(o){console.error("onCascade handler error:",o)}}matchesWhen(e,t){return!e||"any"in e&&e.any===!0?!0:"keys"in e?e.keys.some(([s,n])=>t.channel===s&&t.type===n):"channel"in e?t.channel===e.channel:"channels"in e?e.channels.includes(t.channel):!1}getMiddlewareFunction(e){return typeof e=="function"?e:e.middleware}getMiddlewareWhen(e){if(typeof e!="function")return e.when}async notifyEffects(e){const t=this.scopedEmit(e),s=`${String(e.channel)}::${String(e.type)}`,n=this.effects.get(s);if(n&&n.size>0)for(const r of[...n])try{await r(e,this.getState,t)}catch(o){console.error("Effect error:",o),this.onEffectError?.(o,e)}for(const{effect:r,when:o}of this.patternEffects)if(this.matchesWhen(o,e))try{await r(e,this.getState,t)}catch(d){console.error("Effect error:",d),this.onEffectError?.(d,e)}}scopedEmit(e){const t={id:e.id,depth:e.depth??0,chain:[...this.currentEvent?.chain??[],e.id].slice(-A)};return((s,n,r,o)=>this.emitCaused(t,s,n,r,o))}notifyEventSubscribers(e,t){const s=`${String(e.channel)}::${String(e.type)}`,r=(t==="committed"?this.committedEventSubscribers:t==="written"?this.writtenEventSubscribers:this.uncommittedEventSubscribers).get(s);if(r?.size)for(const d of[...r])this.invokeEventSubscriber(d,e,t);if(t==="written")return;const o=this.allEventSubscribers.get(s);if(o?.size)for(const d of[...o])this.invokeEventSubscriber(d,e,t)}invokeEventSubscriber(e,t,s){try{const n=e(t,this.getState,this.emit,s);n&&typeof n.then=="function"&&n.catch(r=>console.error("Event subscription error:",r))}catch(n){console.error("Event subscription error:",n)}}stageSliceGuarded(e,t,s){try{return this.stageSlice(e,t,s)}catch(n){return console.error(`Reducer error in slice "${e}":`,n),this.onReducerError?.(n,t,e),null}}stageSlice(e,t,s){const n=this.state[e],r=this.reducers[e].reduce(n,t);if(F(r))return r;if(n===r)return null;const o=T(n,r);if(o.length===0)return null;const d=t.payload,i=process.env.NODE_ENV!=="production"&&d!==null&&typeof d=="object"?{watch:d,onFound:()=>{const a=`${e}:${t.channel}:${t.type}`;this.warnedPayloadAliases.has(a)||(this.warnedPayloadAliases.add(a),console.warn(`[yoltra] Slice "${e}" stored the payload of "${t.channel}/${t.type}" by reference. It is now frozen along with the rest of the state, so the emitter mutating it later will throw in development and silently corrupt state in production. Copy the payload in the reducer instead.`))}}:void 0;return s.push({name:e,prev:n,frozen:O(r,i),leafPaths:o}),null}commitStaged(e,t){if(e.length===0)return!1;const s={...this.state};for(const n of e)s[n.name]=n.frozen;if(this.state=s,this.changedPathSink)for(const n of e)for(const r of n.leafPaths)this.changedPathSink.push(r?`${n.name}.${r}`:n.name);for(const n of e){const r=new Set;for(const o of n.leafPaths){if(o===""){r.add("");continue}for(const d of P.buildAncestorPaths(o))r.add(d)}for(const o of r)this.connectorBus.emitWith(n.name,o,()=>({oldValue:this.getAtPath(n.prev,o),newValue:this.getAtPath(n.frozen,o),path:o,eventId:t.id,channel:t.channel,type:t.type}))}return!0}__devtoolsIntrospect(){const e=Object.keys(this.reducers).map(d=>{const i=this.patternReducers.get(d);return{name:d,when:i}}),t=[];for(const[d,i]of this.effects){if(i.size===0)continue;const[a,l]=d.split("::");for(const u of i){const f=this.effectMeta.get(u);t.push({channel:a,type:l,name:f?.name,description:f?.description})}}for(const d of this.patternEffects){const i=this.effectMeta.get(d.effect);t.push({channel:"*",type:"*",name:i?.name,description:i?.description})}const s=[];for(const d of this.middleware)typeof d=="function"?s.push({name:d.name||void 0}):s.push({name:d.meta?.name,description:d.meta?.description,when:d.when});const n=[];for(const d of this.connectorBus.__introspect())for(let i=0;i<d.count;i++)n.push({reducer:d.channel,property:d.type});const r=[];for(const[d,i]of this.committedEventSubscribers){if(i.size===0)continue;const[a,l]=d.split("::");for(let u=0;u<i.size;u++)r.push({channel:a,type:l,phase:"committed"})}for(const[d,i]of this.uncommittedEventSubscribers){if(i.size===0)continue;const[a,l]=d.split("::");for(let u=0;u<i.size;u++)r.push({channel:a,type:l,phase:"uncommitted"})}for(const[d,i]of this.allEventSubscribers){if(i.size===0)continue;const[a,l]=d.split("::");for(let u=0;u<i.size;u++)r.push({channel:a,type:l,phase:"all"})}const o=this.listeners.size;return{reducers:e,effects:t,middleware:s,atomic:n,event:r,coarse:o,dedupHits:this.dedupCount,queueDepth:this.reduceQueue.length+this.inFlightEffects}}__applyExternalState(e){if(!this.replayEnabled)throw new Error("[yoltra] External state apply (time-travel) is disabled. Enable it with createStore({ devtools: { allowReplay: true } })");const t=this.state,s=e,n={...this.state};let r=!1;Object.keys(this.reducers).forEach(o=>{const d=t?.[o],i=s?.[o];if(i===void 0){process.env.NODE_ENV!=="production"&&console.warn(`[yoltra] External state is missing slice "${String(o)}"; retaining its current value. Time-travel snapshots should contain all slices.`);return}if(d===i)return;const a=O(i);n[o]=a,r=!0;const l=T(d,i);if(l.length===0)return;const u=new Set;for(const f of l){if(f===""){u.add("");continue}for(const m of P.buildAncestorPaths(f))u.add(m)}for(const f of u){const m=this.getAtPath(d,f),h=this.getAtPath(a,f);this.connectorBus.emit(o,f,{oldValue:m,newValue:h,path:f})}}),r&&(this.state=n),r&&this.listeners.forEach(o=>o())}__replayEvents(e,t){if(!this.replayEnabled)throw new Error("[yoltra] Event replay is disabled. Enable it with createStore({ devtools: { allowReplay: true } })");this.__applyExternalState(e);for(const s of t){const n=s,r=[];this.stagingSink=r;let o=null;try{this.reducerBus.emit(n.channel,n.type,n.payload,n),o=this.stagedRejection;for(const[i,a]of this.patternReducers){if(o!==null)break;if(this.matchesWhen(a,n)){const l=this.stageSliceGuarded(i,n,r);l!==null&&(o=l)}}}finally{this.stagingSink=null,this.stagedRejection=null,this.stagedRejectedBy=""}const d=o===null&&this.commitStaged(r,n);this.notifyEventSubscribers(n,"committed"),d&&(this.notifyEventSubscribers(n,"written"),this.listeners.forEach(i=>i()))}}async emit(e,t,s,n){return this.emitCaused(null,e,t,s,n)}async emitCaused(e,t,s,n,r){const o=r?.dedupKey,d=this.dedupConfig.windowMs;if(r?.skipDedup!==!0&&(d>0||o!==void 0)){const m=o!==void 0&&d<=0?z:d,h=o!==void 0?`${t}::${s}::#${o}`:this.fingerprint(t,s,n);if(this.shouldDedupe(h,m))return $}const i=r?.id??this.idFactory(),a=this.currentEvent??e,l=a===null?0:a.depth+1;if(a!==null&&l>this.maxReduceDepth)return this.reportCascade("maxReduceDepth",this.maxReduceDepth,{channel:t,type:s,payload:n,id:i,...r?.meta!==void 0?{meta:r.meta}:{},parentId:a.id,depth:l},l,a.chain),$;let u;const f=new Promise(m=>{u=m});return this.reduceQueue.push({channel:t,type:s,payload:n,id:i,meta:r?.meta,resolve:u,...a!==null?{parentId:a.id,depth:l,chain:a.chain}:{}}),this.drainReduce(),f}drainReduce(){if(!this.isReducing){this.isReducing=!0,this.transitionsThisDrain=0;try{for(;this.reduceQueue.length>0;){const e=this.reduceQueue.shift(),{channel:t,type:s,payload:n,id:r,meta:o,resolve:d,parentId:i,depth:a,chain:l}=e,u={channel:t,type:s,payload:n,id:r,...o!==void 0?{meta:o}:{},...i!==void 0?{parentId:i,depth:a}:{}};if(i!==void 0&&++this.transitionsThisDrain>this.maxTransitionsPerDrain){this.reportCascade("maxTransitionsPerDrain",this.maxTransitionsPerDrain,u,a,l),d($);continue}this.currentEvent={id:r,depth:a??0,chain:[...l??[],r].slice(-A)};const f=this.instrumentObservers.size>0,m=f?this.state:void 0,h=f?[]:void 0;h!==void 0&&(this.changedPathSink=h);const y=f?j():0;let g=$;try{g=this.applyEventSync(u)}catch(E){console.error("Emit reduce error:",E)}finally{f&&(this.changedPathSink=null),this.currentEvent=null}f&&this.emitInstrumentation(u,g,h??[],m,j()-y),this.runEventEffects(u,g,d)}}finally{this.isReducing=!1}}}applyEventSync(e){for(const o of this.middleware){const d=this.getMiddlewareWhen(o);if(!this.matchesWhen(d,e))continue;const i=this.getMiddlewareFunction(o);let a;try{a=i(this.state,e,this.emit),process.env.NODE_ENV!=="production"&&typeof a?.then=="function"&&console.error(`[yoltra] Middleware for "${e.channel}/${e.type}" returned a Promise. Middleware is synchronous: a Promise is truthy, so this event was allowed without waiting and a "return false" inside it can never veto. Do the check synchronously, and put anything that must await in an effect.`)}catch(l){console.error("Middleware error:",l),a=!1}if(!a)return this.notifyEventSubscribers(e,"uncommitted"),$}const t=[];this.stagingSink=t;let s=null,n="";try{this.reducerBus.emit(e.channel,e.type,e.payload,e),s=this.stagedRejection,n=this.stagedRejectedBy;for(const[o,d]of this.patternReducers){if(s!==null)break;if(this.matchesWhen(d,e)){const i=this.stageSliceGuarded(o,e,t);i!==null&&(s=i,n=o)}}}finally{this.stagingSink=null,this.stagedRejection=null,this.stagedRejectedBy=""}if(s!==null)return this.onRejected?.(s,e,n),this.notifyEventSubscribers(e,"committed"),{committed:!0,written:!1,rejected:s};const r=this.commitStaged(t,e);return this.notifyEventSubscribers(e,"committed"),r&&(this.notifyEventSubscribers(e,"written"),this.listeners.forEach(o=>o())),r?ie:re}async runEventEffects(e,t,s){this.inFlightEffects++;try{t.committed&&await this.notifyEffects(e)}catch(n){console.error("Effect error:",n)}finally{this.inFlightEffects--,s(t)}}instrument(e){return this.instrumentObservers.add(e),()=>{this.instrumentObservers.delete(e)}}emitInstrumentation(e,t,s,n,r){const o={},d={};for(const a of s)o[a]=this.getAtPath(n,a),d[a]=this.getAtPath(this.state,a);const i={event:{id:e.id,channel:e.channel,type:e.type,payload:e.payload,...e.meta!==void 0?{meta:e.meta}:{}},committed:t.committed,changedPaths:s,prevValues:o,nextValues:d,reduceTimeMs:r,...t.rejected!==void 0?{rejected:t.rejected}:{}};for(const a of[...this.instrumentObservers])try{a(i)}catch(l){console.error("Instrumentation observer error:",l)}}connect(e,t,s){const n=this.connectorBus.on(e.reducer,e.property,t);if(s?.immediate===!0){const r=this.state[e.reducer],o=e.property.includes("*")?"":e.property;t({oldValue:void 0,newValue:this.getAtPath(r,o),path:o})}return n}onEvent(e,t,s,n="committed"){const r=`${e}::${String(t)}`,o=n==="committed"?this.committedEventSubscribers:n==="uncommitted"?this.uncommittedEventSubscribers:n==="written"?this.writtenEventSubscribers:this.allEventSubscribers;return o.has(r)||o.set(r,new Set),o.get(r).add(s),()=>{const d=o.get(r);d&&(d.delete(s),d.size===0&&o.delete(r))}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}getState(){return this.state}registerMiddleware(e){return this.middleware.push(e),()=>{const t=this.middleware.indexOf(e);t!==-1&&this.middleware.splice(t,1)}}registerReducer(e,t){if(Object.prototype.hasOwnProperty.call(this.reducers,e))throw new Error(`Reducer ${e} already exists`);return this.mountSlice(e,t,{preserveState:!1}),this.listeners.forEach(s=>s()),()=>{this.unmountSlice(e,{deleteState:!0}),this.listeners.forEach(s=>s())}}call(e,t,s,n){const{channel:r,isTerminal:o}=X(n.reply),d=n.timeoutMs??ne,i=new Y(n.highWaterMark??se),a=this.idFactory();let l,u,f=!1;const m=new Promise((b,S)=>{l=b,u=S});m.catch(()=>{});let h=null,y=null;const g=(b,S=!1)=>{f||(f=!0,h!==null&&clearTimeout(h),h=null,y?.(),y=null,S?i.end():i.close(),n.signal?.removeEventListener("abort",E),b())};function E(){g(()=>u(new I(String(n.signal?.reason??"signal aborted"))))}const M=()=>{h!==null&&clearTimeout(h),h=setTimeout(()=>{g(()=>u(new U(e,t,d)))},d),h.unref?.()};return y=this.registerEffect({when:{channel:r},effect:async b=>{if(!f&&Z(b,a,n.correlationId)){if(M(),o(String(b.type))){g(()=>l(b),!0);return}await i.put(b)}}}),n.signal!==void 0&&(n.signal.aborted?E():n.signal.addEventListener("abort",E,{once:!0})),M(),this.emit(e,t,s,{id:a,...n.correlationId!==void 0?{meta:{correlationId:n.correlationId}}:{}}),{then:(b,S)=>m.then(b,S),catch:b=>m.catch(b),finally:b=>m.finally(b),get dropped(){return i.droppedCount},cancel:(b="cancelled")=>{g(()=>u(new I(b)))},[Symbol.asyncIterator]:()=>(i.beginConsuming(),{next:()=>i.take(),return:async()=>(i.close(),{value:void 0,done:!0})})}}registerEffect(e){const{effect:t,meta:s,when:n}=e,r=[];if(s&&this.effectMeta.set(t,s),n&&("any"in n&&n.any===!0||"channel"in n||"channels"in n)){const i={effect:t,when:n};return this.patternEffects.add(i),()=>{this.patternEffects.delete(i)}}const d=this.normalizeEventKeys(e);if(d.length===0&&!n){const i={effect:t,when:{any:!0}};return this.patternEffects.add(i),()=>{this.patternEffects.delete(i)}}for(const[i,a]of d){const l=`${String(i)}::${String(a)}`;this.effects.has(l)||this.effects.set(l,new Set),this.effects.get(l).add(t),r.push(()=>{const u=this.effects.get(l);u&&(u.delete(t),u.size===0&&this.effects.delete(l))})}return()=>{for(const i of r)i()}}onEffect(e,t,s){const n=async(r,o,d)=>{if(r.channel!==e||r.type!==t)return;const i=r;return s(i.payload,o,d,i)};return this.registerEffect({when:{keys:[[e,t]]},effect:n})}replaceMiddleware(e){this.middleware.length=0;for(const t of e)this.middleware.push(t)}replaceEffects(e){this.effects.clear(),this.patternEffects.clear();for(const t of e)this.registerEffect(t)}replaceReducers(e,t={}){const s=t.preserveState!==!1,n=new Set(Object.keys(this.reducers)),r=Object.entries(e),o=new Set(r.map(([d])=>d));for(const d of n)o.has(d)||this.unmountSlice(d,{deleteState:!0});for(const[d,i]of r)n.has(d)?(this.unmountSlice(d,{deleteState:!1}),this.mountSlice(d,i,{preserveState:s})):this.mountSlice(d,i,{preserveState:!1})}hotReplace(e){e.middleware&&this.replaceMiddleware(e.middleware),e.effects&&this.replaceEffects(e.effects),e.reducer&&this.replaceReducers(e.reducer,{preserveState:e.preserveState})}mountSlice(e,t,s){const n=e,{reducer:r,state:o,when:d}=t;if(this.reducers[e]=new W(r),(!s.preserveState||this.state[n]===void 0)&&(this.state={...this.state,[n]:O(ee(n,o))}),d&&("any"in d&&d.any===!0||"channel"in d||"channels"in d)){this.patternReducers.set(e,d),this.sliceUnsubs.set(n,[]);return}const a=this.normalizeEventKeys(t);if(a.length===0&&!d){this.patternReducers.set(e,{any:!0}),this.sliceUnsubs.set(n,[]);return}const l=[];for(const[u,f]of a){const m=this.reducerBus.on(u,f,(h,y)=>{const g=y??{channel:u,type:f,payload:h,id:this.idFactory()};if(this.stagingSink===null)return;const E=this.stageSliceGuarded(e,g,this.stagingSink);E!==null&&this.stagedRejection===null&&(this.stagedRejection=E,this.stagedRejectedBy=e)});l.push(m)}this.sliceUnsubs.set(n,l)}unmountSlice(e,t){const s=e;this.patternReducers.delete(e);const n=this.sliceUnsubs.get(s);if(n){for(const r of n)try{r()}catch(o){console.error(`[Store error]: ${o}`)}this.sliceUnsubs.delete(s)}if(delete this.reducers[e],t.deleteState){const{[s]:r,...o}=this.state;this.state=o}}normalizeEventKeys(e){if(e.when){const t=e.when;if("keys"in t)return t.keys}return[]}getAtPath(e,t){if(!t)return e;const n=(t[0]==="."?t.slice(1):t).split(".");let r=e;for(const o of n){if(r==null)return;r=r[o]}return r}static buildAncestorPaths(e){if(!e)return[];const s=(e[0]==="."?e.slice(1):e).split("."),n=[];for(let r=0;r<s.length;r++)n.push(s.slice(0,r+1).join("."));return n}}function oe(c){return new P({...c,reducer:c.reducer??{},middleware:c.middleware??[],effects:c.effects??[]})}const ce=c=>(e,t)=>t.map(s=>[e,s]),ae=()=>c=>c,_=new Set;function de(c){const e=String(c);_.has(e)||(_.add(e),console.warn(`[yoltra] Entity id "${e}" contains a dot. Paths are dotted, so a subscription to "entities.${e}" is indistinguishable from one to a nested object of the same name. Use ids without dots.`))}function le(c,e){if(c.length!==e.length)return e;for(let t=0;t<c.length;t++)if(c[t]!==e[t])return e;return c}function ue(c={}){const e=c.selectId??(i=>i.id),{sortComparer:t}=c,s=(i,a)=>{if(t===void 0)return a;const l=[...a].sort((u,f)=>{const m=i.entities[u],h=i.entities[f];return m===void 0||h===void 0?0:t(m,h)});return le(a,l)},n=(i,a,l)=>{const u={...i,entities:a,ids:l};return{...u,ids:s(u,l)}},r=(i,a,l)=>{let u=null,f=null;for(const m of a){const h=e(m);process.env.NODE_ENV!=="production"&&String(h).includes(".")&&de(h);const y=(u??i.entities)[h];if(y!==void 0&&l==="add")continue;const g=y!==void 0&&l==="upsert"?{...y,...m}:m;u??(u={...i.entities}),u[h]=g,y===void 0&&(f??(f=[...i.ids]),f.push(h))}return u===null?i:n(i,u,f??i.ids)},o=(i,a)=>{let l=null;for(const{id:u,changes:f}of a){const m=(l??i.entities)[u];m!==void 0&&(l??(l={...i.entities}),l[u]={...m,...f})}return l===null?i:n(i,l,i.ids)},d=(i,a)=>{const l=new Set(a.filter(f=>i.entities[f]!==void 0));if(l.size===0)return i;const u={...i.entities};for(const f of l)delete u[f];return n(i,u,i.ids.filter(f=>!l.has(f)))};return{getInitialState(i){const a={ids:[],entities:{}};return i===void 0?a:{...a,...i}},addOne:(i,a)=>r(i,[a],"add"),addMany:(i,a)=>r(i,a,"add"),setOne:(i,a)=>r(i,[a],"set"),setMany:(i,a)=>r(i,a,"set"),setAll:(i,a)=>{const l={},u=[];for(const f of a){const m=e(f);l[m]===void 0&&u.push(m),l[m]=f}return n(i,l,u)},updateOne:(i,a)=>o(i,[a]),updateMany:(i,a)=>o(i,a),upsertOne:(i,a)=>r(i,[a],"upsert"),upsertMany:(i,a)=>r(i,a,"upsert"),removeOne:(i,a)=>d(i,[a]),removeMany:(i,a)=>d(i,a),removeAll:i=>i.ids.length===0?i:n(i,{},[]),selectIds:i=>i.ids,selectEntities:i=>i.entities,selectAll:i=>i.ids.map(a=>i.entities[a]),selectById:(i,a)=>i.entities[a],selectTotal:i=>i.ids.length,idsPath:"ids",pathTo:(i,a)=>a===void 0?`entities.${i}`:`entities.${i}.${a}`,anyField:i=>`entities.*.${i}`}}const w="$yoltra";function C(c,e={}){const t=e.maxNodes??1e5,s=e.sanitize,n=[],r=new Map;let o=0,d=!1;function i(l,u){if(s!==void 0&&(l=s(u,l)),o+=1,o>t)return d=!0,{[w]:"unsupported",kind:"truncated"};switch(typeof l){case"undefined":return{[w]:"undefined"};case"bigint":return{[w]:"bigint",value:l.toString()};case"number":return Number.isNaN(l)?{[w]:"nan"}:l===1/0?{[w]:"infinity",sign:1}:l===-1/0?{[w]:"infinity",sign:-1}:l;case"function":case"symbol":return n.push(u),{[w]:"unsupported",kind:typeof l};case"string":case"boolean":return l}if(l===null)return null;const f=l,m=r.get(f);if(m!==void 0)return{[w]:"ref",path:m};if(r.set(f,u),l instanceof Date)return{[w]:"date",iso:l.toISOString()};if(l instanceof RegExp)return{[w]:"regexp",source:l.source,flags:l.flags};if(l instanceof Error)return{[w]:"error",name:l.name,message:l.message};if(l instanceof Map){const y=[];let g=0;for(const[E,M]of l)y.push([i(E,`${u}/@k${g}`),i(M,`${u}/${g}`)]),g+=1;return{[w]:"map",entries:y}}if(l instanceof Set){const y=[];let g=0;for(const E of l)y.push(i(E,`${u}/${g}`)),g+=1;return{[w]:"set",values:y}}if(Array.isArray(l))return l.map((y,g)=>i(y,`${u}/${g}`));const h={};for(const[y,g]of Object.entries(l))h[y]=i(g,`${u}/${V(y)}`);return w in h?{[w]:"escaped",value:h}:h}return{value:i(c,""),report:{truncated:d,unsupported:n}}}function L(c){const e=new Map,t=[];function s(o,d){if(o===null||typeof o!="object")return o;if(Array.isArray(o)){const a=[];return e.set(d,a),o.forEach((l,u)=>{if(N(l)){t.push({target:a,key:u,path:l.path}),a[u]=void 0;return}a[u]=s(l,`${d}/${u}`)}),a}if(typeof o[w]=="string"){const a=o;switch(a[w]){case"undefined":return;case"nan":return Number.NaN;case"infinity":return a.sign===1?1/0:-1/0;case"bigint":return BigInt(a.value);case"date":return new Date(a.iso);case"regexp":return new RegExp(a.source,a.flags);case"error":{const l=new Error(a.message);return l.name=a.name,l}case"unsupported":return;case"ref":return;case"map":{const l=new Map;return e.set(d,l),a.entries.forEach(([u,f],m)=>{l.set(s(u,`${d}/@k${m}`),s(f,`${d}/${m}`))}),l}case"set":{const l=new Set;return e.set(d,l),a.values.forEach((u,f)=>l.add(s(u,`${d}/${f}`))),l}case"escaped":return n(a.value,d);default:return}}return n(o,d)}function n(o,d){const i={};e.set(d,i);for(const[a,l]of Object.entries(o)){const u=`${d}/${V(a)}`;if(N(l)){t.push({target:i,key:a,path:l.path}),i[a]=void 0;continue}i[a]=s(l,u)}return i}const r=s(c,"");e.set("",r);for(const{target:o,key:d,path:i}of t)o[d]=e.get(i);return r}function N(c){return c!==null&&typeof c=="object"&&c[w]==="ref"&&typeof c.path=="string"}function V(c){return c.replace(/~/g,"~0").replace(/\//g,"~1")}function fe(c,e,t={}){let s=t.maxNodes??1e5;for(let n=0;n<8;n+=1){const{value:r,report:o}=C(c,{...t,maxNodes:s});let d;try{d=JSON.stringify(r)?.length??0}catch{d=Number.POSITIVE_INFINITY}if(d<=e)return o.truncated?{value:r,truncated:!0,note:`State was too large to send in full; parts beyond ${s} nodes are omitted.`}:{value:r,truncated:!1};const i=Math.floor(s*e*.8/d);if(s=Math.max(1,Math.min(i,s-1)),s<=1&&n>0)break}return{value:{[w]:"unsupported",kind:"truncated"},truncated:!0,note:`State exceeds the ${e}-byte transport limit and could not be reduced to fit.`}}function v(c,e,t){c.onError?.(e,t)}async function he(c){const e={slices:{},restored:!1};let t;try{t=c.source??await c.adapter.read(c.key)}catch(n){return v(c,n,"read"),e}if(t==null||t==="")return e;let s;try{s=L(JSON.parse(t))}catch(n){return v(c,n,"decode"),e}if(s===null||typeof s!="object"||typeof s.version!="number")return v(c,new Error("persisted payload is not a recognisable envelope"),"decode"),e;if(s.version!==c.version){if(c.migrate===void 0)return v(c,new Error(`persisted state is version ${s.version}, this build expects ${c.version}, and no migrate was supplied`),"migrate"),e;try{const n=c.migrate(s.slices,s.version);return n===null?e:{slices:n,restored:!0}}catch(n){return v(c,n,"migrate"),e}}return{slices:s.slices??{},restored:!0}}function pe(c,e){if(!e.restored)return c;const t={};for(const[s,n]of Object.entries(c)){const r=e.slices[s];t[s]=r===void 0?n:{...n,state:r}}return t}function Q(c,e){const t=c??{},s=e.slices===void 0?t:Object.fromEntries(e.slices.filter(n=>n in t).map(n=>[n,t[n]]));return JSON.stringify(C({version:e.version,slices:s}).value)}function me(c,e){const t=e.throttleMs??250,s=e.slices;let n=null,r=!1;const o=()=>{if(r){r=!1;try{const a=e.adapter.write(e.key,Q(c.getState(),e));a instanceof Promise&&a.catch(l=>v(e,l,"write"))}catch(a){v(e,a,"write")}}},d=()=>{if(r=!0,t<=0){o();return}n===null&&(n=setTimeout(()=>{n=null,o()},t),n.unref?.())},i=c.instrument(a=>{if(s===void 0){d();return}(a.changedPaths??[]).some(u=>s.some(f=>u===f||u.startsWith(`${f}.`)))&&d()});return()=>{i(),n!==null&&(clearTimeout(n),n=null),o()}}function ye(c,e){return Q(c.getState(),e)}function ge(c){return{read:e=>c.getItem(e),write:(e,t)=>c.setItem(e,t),remove:e=>c.removeItem(e)}}function Ee(c){const e=new Map(Object.entries(c??{}));return{read:t=>e.get(t)??null,write:(t,s)=>{e.set(t,s)},remove:t=>{e.delete(t)}}}exports.CallAbortedError=I;exports.CallTimeoutError=U;exports.EventBus=B;exports.LooseEventBus=H;exports.Reducer=W;exports.Rejected=q;exports.Store=P;exports.createEntityAdapter=ue;exports.createMemoryAdapter=Ee;exports.createStore=oe;exports.createWebStorageAdapter=ge;exports.decodeState=L;exports.dehydrate=ye;exports.detectChangedProps=T;exports.encodeState=C;exports.encodeStateBounded=fe;exports.eventKeys=ae;exports.freezeState=k;exports.hydrate=he;exports.isRejected=F;exports.persist=me;exports.typedEvents=ce;exports.withHydration=pe;
4
+ * License: MIT */
5
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class q{handlers=new Map;on(e,t,n){let r=this.handlers.get(e);r||(r=new Map,this.handlers.set(e,r));let i=r.get(t);return i||(i=new Set,r.set(t,i)),i.add(n),()=>this.off(e,t,n)}off(e,t,n){const r=this.handlers.get(e);if(!r)return;const i=r.get(t);i&&(i.delete(n),i.size===0&&r.delete(t),r.size===0&&this.handlers.delete(e))}emit(e,t,n,r){const i=this.handlers.get(e);if(!i)return;const s=i.get(t);if(!(!s||s.size===0))for(const l of[...s])try{l(n,r)}catch(c){console.error("EventBus handler error:",c)}}clear(){this.handlers.clear()}}class Q{handlers=new Map;patternHandlers=new Map;patternIndex=new Map;on(e,t,n){const r=String(t);if(this.isPattern(r)){const i=r;this.patternHandlers.has(e)||this.patternHandlers.set(e,new Map);const s=this.patternHandlers.get(e);return s.has(i)||(s.set(i,[]),this.indexPattern(e,i)),s.get(i).push(n),()=>this.offPattern(e,i,n)}else{const i=this.normalizeTypeKey(r);this.handlers.has(e)||this.handlers.set(e,new Map);const s=this.handlers.get(e);return s.has(i)||s.set(i,[]),s.get(i).push(n),()=>this.offExactNormalized(e,i,n)}}off(e,t,n){const r=this.normalizeTypeKey(String(t));this.offExactNormalized(e,r,n)}offExactNormalized(e,t,n){const r=this.handlers.get(e);if(!r)return;const i=r.get(t);if(!i)return;const s=i.indexOf(n);s!==-1&&i.splice(s,1),i.length===0&&r.delete(t),r.size===0&&this.handlers.delete(e)}offPattern(e,t,n){const r=this.patternHandlers.get(e);if(!r)return;const i=r.get(t);if(!i)return;const s=i.indexOf(n);s!==-1&&i.splice(s,1),i.length===0&&(r.delete(t),this.unindexPattern(e,t)),r.size===0&&(this.patternHandlers.delete(e),this.patternIndex.delete(e))}emit(e,t,n){const r=String(t),i=this.normalizeTypeKey(r),s=this.handlers.get(e)?.get(i)??[],l=this.matchingPatternHandlers(e,r),c=new Set,a=d=>{for(const f of[...d])if(!c.has(f)){c.add(f);try{f(n)}catch(u){console.error(u);continue}}};a(s);for(const d of l)a(d)}emitWith(e,t,n){const r=String(t),i=this.normalizeTypeKey(r),s=this.handlers.get(e)?.get(i)??[],l=this.matchingPatternHandlers(e,r);if(s.length===0&&l.length===0)return;const c=n(),a=new Set,d=f=>{for(const u of[...f])if(!a.has(u)){a.add(u);try{u(c)}catch(p){console.error(p);continue}}};d(s);for(const f of l)d(f)}isPattern(e){return e.includes("*")}normalizeTypeKey(e){return e.replace(/^\./,"")}splitPath(e){return this.normalizeTypeKey(e).split(".").filter(Boolean)}indexPattern(e,t){let n=this.patternIndex.get(e);n===void 0&&(n={byHead:new Map,anyHead:[]},this.patternIndex.set(e,n));const r=this.splitPath(t),i={pattern:t,segments:r},s=r[0];if(s===void 0||s==="*"||s==="**"){n.anyHead.push(i);return}const l=n.byHead.get(s);l===void 0?n.byHead.set(s,[i]):l.push(i)}unindexPattern(e,t){const n=this.patternIndex.get(e);if(n===void 0)return;const r=this.splitPath(t)[0],i=r===void 0||r==="*"||r==="**"?n.anyHead:n.byHead.get(r);if(i===void 0)return;const s=i.findIndex(l=>l.pattern===t);s!==-1&&i.splice(s,1),i.length===0&&i!==n.anyHead&&r!==void 0&&n.byHead.delete(r)}matchingPatternHandlers(e,t){const n=this.patternHandlers.get(e),r=this.patternIndex.get(e);if(n===void 0||n.size===0||r===void 0)return[];const i=this.splitPath(t),s=[],l=a=>{for(const d of a){if(!this.matchSegments(d.segments,i))continue;const f=n.get(d.pattern);f!==void 0&&s.push(f)}},c=i[0];if(c!==void 0){const a=r.byHead.get(c);a!==void 0&&l(a)}return l(r.anyHead),s}matchSegments(e,t){let n=0,r=0,i=-1,s=0;for(;r<t.length;)if(n<e.length&&(e[n]==="*"||e[n]===t[r]))n++,r++;else if(n<e.length&&e[n]==="**")i=n,s=r,n++;else if(i!==-1)n=i+1,r=++s;else return!1;for(;n<e.length&&e[n]==="**";)n++;return n===e.length}clear(){this.handlers.clear(),this.patternHandlers.clear(),this.patternIndex.clear()}__introspect(){const e=[];for(const[t,n]of this.handlers)for(const[r,i]of n)i.length>0&&e.push({channel:t,type:r,count:i.length});for(const[t,n]of this.patternHandlers)for(const[r,i]of n)i.length>0&&e.push({channel:t,type:r,count:i.length});return e}}class G{_reduce;constructor(e){this._reduce=e}reduce(e,t){return this._reduce(e,t)}}const _=new Set;function I(o,e){const t=o?`${o}.${e}`:e;_.has(t)||(_.add(t),console.warn(`[yoltra] State key "${e}"${o?` under "${o}"`:""} contains a dot. Paths are dotted, so this key is indistinguishable from nested objects of the same name: a subscription to "${t}" may match the wrong value, and DevTools patches for it will address the wrong node. Rename the key, or nest it.`))}function C(o,e,t="",n=new Map){const r=[];return P(o,e,t,n,r),r}function P(o,e,t,n,r){if(o===e)return;if(typeof o!="object"||typeof e!="object"||o===null||e===null){if(typeof o=="number"&&Number.isNaN(o)&&Number.isNaN(e))return;r.push(t);return}if(o instanceof Date&&e instanceof Date){o.getTime()!==e.getTime()&&r.push(t);return}if(o instanceof RegExp&&e instanceof RegExp){(o.source!==e.source||e.flags!==o.flags)&&r.push(t);return}if(o instanceof Map||e instanceof Map){r.push(t);return}if(o instanceof Set||e instanceof Set){r.push(t);return}const i=o,s=e,l=n.get(i);if(l?.has(s))return;const c=l??new Set;c.add(s),l||n.set(i,c);try{const a=Array.isArray(o),d=Array.isArray(e);if(a!==d){r.push(t);return}if(a){const h=o,y=e;h.length!==y.length&&t&&r.push(t);const w=Math.min(h.length,y.length);for(let g=0;g<w;g++)h[g]!==y[g]&&P(h[g],y[g],t?`${t}.${g}`:`${g}`,n,r);for(let g=w;g<Math.max(h.length,y.length);g++)r.push(t?`${t}.${g}`:`${g}`);return}const f=Object.keys(o),u=Object.keys(e);if(f.length===0&&u.length===0){r.push(t);return}let p=f.length===u.length;if(p){for(let h=0;h<u.length;h++)if(!Object.prototype.hasOwnProperty.call(o,u[h])){p=!1;break}}if(p){for(const h of u)o[h]!==e[h]&&(process.env.NODE_ENV!=="production"&&h.includes(".")&&I(t,h),P(o[h],e[h],t?`${t}.${h}`:h,n,r));return}for(const h of u){const y=Object.prototype.hasOwnProperty.call(o,h);if(y&&o[h]===e[h])continue;process.env.NODE_ENV!=="production"&&h.includes(".")&&I(t,h);const w=t?`${t}.${h}`:h;if(!y){r.push(w);continue}P(o[h],e[h],w,n,r)}for(const h of f)Object.prototype.hasOwnProperty.call(e,h)||(process.env.NODE_ENV!=="production"&&h.includes(".")&&I(t,h),r.push(t?`${t}.${h}`:h))}finally{c.delete(s),c.size===0&&n.delete(i)}}function k(o,e=new WeakSet,t){if(o===null||typeof o!="object"||e.has(o)||(t!==void 0&&o===t.watch&&t.onFound(),Object.isFrozen(o))||(e.add(o),ArrayBuffer.isView(o)))return o;if(Array.isArray(o)){const n=o;for(let r=0;r<n.length;r++)n[r]=k(n[r],e,t);return Object.freeze(n)}for(const n of Object.getOwnPropertyNames(o)){const r=Object.getOwnPropertyDescriptor(o,n);!r||!("value"in r)||(o[n]=k(o[n],e,t))}for(const n of Object.getOwnPropertySymbols(o)){const r=Object.getOwnPropertyDescriptor(o,n);!r||!("value"in r)||(o[n]=k(o[n],e,t))}return Object.freeze(o)}const J=Symbol.for("yoltra.rejected");function te(o){return{[J]:!0,reason:o}}function X(o){return typeof o=="object"&&o!==null&&o[J]===!0}class Y extends Error{channel;type;idleMs;constructor(e,t,n){super(`[yoltra] call to "${e}/${t}" saw no correlated reply for ${n}ms. The timeout is idle rather than total, so this means the responder went quiet, not that it was slow. Check that something handles "${e}/${t}" and that its reply is emitted through the \`emit\` it was handed — a reply emitted from an unrelated context carries no causal link, and needs an explicit correlationId instead.`),this.name="CallTimeoutError",this.channel=e,this.type=t,this.idleMs=n}}class j extends Error{constructor(e){super(`[yoltra] call aborted: ${e}`),this.name="CallAbortedError"}}function ne(o){const[e,t]=o;if(t===void 0)return{channel:e,isTerminal:()=>!0};if(typeof t=="string")return{channel:e,isTerminal:r=>r===t};const n=new Set(t);return{channel:e,isTerminal:r=>n.has(r)}}function re(o,e,t){return o.parentId===e?!0:t===void 0?!1:o.meta?.correlationId===t}class ie{constructor(e){this.highWaterMark=e}highWaterMark;buffer=[];takers=[];putters=[];consuming=!1;ended=!1;closed=!1;dropped=0;get droppedCount(){return this.dropped}beginConsuming(){this.consuming=!0}put(e){if(this.closed||this.ended)return Promise.resolve();const t=this.takers.shift();return t!==void 0?(t({value:e,done:!1}),Promise.resolve()):this.buffer.length<this.highWaterMark?(this.buffer.push(e),Promise.resolve()):this.consuming?new Promise(n=>{this.putters.push({item:e,release:n})}):(this.dropped++,Promise.resolve())}take(){this.consuming=!0;const e=this.buffer.shift();if(e!==void 0){const n=this.putters.shift();return n!==void 0&&(this.buffer.push(n.item),n.release()),Promise.resolve({value:e,done:!1})}const t=this.putters.shift();return t!==void 0?(t.release(),Promise.resolve({value:t.item,done:!1})):this.closed||this.ended?Promise.resolve({value:void 0,done:!0}):new Promise(n=>{this.takers.push(n)})}end(){if(this.ended||this.closed)return;this.ended=!0;let e=this.putters.shift();for(;e!==void 0;)this.buffer.push(e.item),e.release(),e=this.putters.shift();let t=this.takers.shift();for(;t!==void 0;){const n=this.buffer.shift();t(n!==void 0?{value:n,done:!1}:{value:void 0,done:!0}),t=this.takers.shift()}}close(){if(this.closed)return;this.closed=!0,this.buffer.length=0;let e=this.takers.shift();for(;e!==void 0;)e({value:void 0,done:!0}),e=this.takers.shift();let t=this.putters.shift();for(;t!==void 0;)t.release(),t=this.putters.shift()}}const se=3e4,oe=16;function ce(o,e,t,n,r){const{channel:i,isTerminal:s}=ne(r.reply),l=r.timeoutMs??se,c=new ie(r.highWaterMark??oe),a=o.idFactory();let d,f,u=!1;const p=new Promise((E,O)=>{d=E,f=O});p.catch(()=>{});let h=null,y=null;const w=(E,O=!1)=>{u||(u=!0,h!==null&&clearTimeout(h),h=null,y?.(),y=null,O?c.end():c.close(),r.signal?.removeEventListener("abort",g),E())};function g(){w(()=>f(new j(String(r.signal?.reason??"signal aborted"))))}const b=()=>{h!==null&&clearTimeout(h),h=setTimeout(()=>{w(()=>f(new Y(e,t,l)))},l),h.unref?.()};return y=o.registerEffect({when:{channel:i},effect:async E=>{if(!u&&re(E,a,r.correlationId)){if(b(),s(String(E.type))){w(()=>d(E),!0);return}await c.put(E)}}}),r.signal!==void 0&&(r.signal.aborted?g():r.signal.addEventListener("abort",g,{once:!0})),b(),o.emit(e,t,n,{id:a,...r.correlationId!==void 0?{meta:{correlationId:r.correlationId}}:{}}),{then:(E,O)=>p.then(E,O),catch:E=>p.catch(E),finally:E=>p.finally(E),get dropped(){return c.droppedCount},cancel:(E="cancelled")=>{w(()=>f(new j(E)))},[Symbol.asyncIterator]:()=>(c.beginConsuming(),{next:()=>c.take(),return:async()=>(c.close(),{value:void 0,done:!0})})}}function ae(o,e){if(!e)return o;const n=(e[0]==="."?e.slice(1):e).split(".");let r=o;for(const i of n){if(r==null)return;r=r[i]}return r}function de(o){if(!o)return[];const t=(o[0]==="."?o.slice(1):o).split("."),n=[];for(let r=0;r<t.length;r++)n.push(t.slice(0,r+1).join("."));return n}const m="$yoltra",$=Object.freeze(Object.assign(Object.create(null),{Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array}));function le(o){const e=o.constructor?.name;if(e!==void 0&&Object.prototype.hasOwnProperty.call($,e))return e;if(o instanceof DataView)return"DataView";for(const t of Object.keys($)){const n=$[t];if(n!==void 0&&o instanceof n)return t}}function N(o){const e=globalThis.Buffer;if(e!==void 0)return e.from(o).toString("base64");const t=8192;let n="";for(let r=0;r<o.length;r+=t)n+=String.fromCharCode(...o.subarray(r,r+t));return btoa(n)}function fe(o){const e=globalThis.Buffer;if(e!==void 0){const r=e.from(o,"base64");return new Uint8Array(r.subarray(0,r.length))}const t=atob(o),n=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)n[r]=t.charCodeAt(r);return n}function A(o,e={}){const t=e.maxNodes??1e5,n=e.sanitize,r=[],i=new Map;let s=0,l=!1;function c(d,f){if(n!==void 0&&(d=n(f,d)),s+=1,s>t)return l=!0,{[m]:"unsupported",kind:"truncated"};switch(typeof d){case"undefined":return{[m]:"undefined"};case"bigint":return{[m]:"bigint",value:d.toString()};case"number":return Number.isNaN(d)?{[m]:"nan"}:d===1/0?{[m]:"infinity",sign:1}:d===-1/0?{[m]:"infinity",sign:-1}:d;case"function":case"symbol":return r.push(f),{[m]:"unsupported",kind:typeof d};case"string":case"boolean":return d}if(d===null)return null;const u=d,p=i.get(u);if(p!==void 0)return{[m]:"ref",path:p};if(i.set(u,f),d instanceof Date)return{[m]:"date",iso:d.toISOString()};if(d instanceof RegExp)return{[m]:"regexp",source:d.source,flags:d.flags};if(d instanceof Error)return{[m]:"error",name:d.name,message:d.message};if(d instanceof Map){const g=[];let b=0;for(const[v,E]of d)g.push([c(v,`${f}/@k${b}`),c(E,`${f}/${b}`)]),b+=1;return{[m]:"map",entries:g}}if(d instanceof Set){const g=[];let b=0;for(const v of d)g.push(c(v,`${f}/${b}`)),b+=1;return{[m]:"set",values:g}}if(Array.isArray(d))return d.map((g,b)=>c(g,`${f}/${b}`));if(d instanceof ArrayBuffer)return s+=Math.ceil(d.byteLength/64),s>t?(l=!0,{[m]:"unsupported",kind:"truncated"}):{[m]:"binary",kind:"ArrayBuffer",b64:N(new Uint8Array(d))};if(ArrayBuffer.isView(d)){const g=d;s+=Math.ceil(g.byteLength/64);const b=le(g);if(b===void 0)return r.push(f),{[m]:"unsupported",kind:g.constructor?.name??"ArrayBufferView"};const v=new Uint8Array(g.buffer,g.byteOffset,g.byteLength),E={[m]:"binary",kind:b,b64:N(v)};return g.constructor?.name!==b&&r.push(f),E}const h=Object.getPrototypeOf(d),y=d.constructor?.name;if(h!==null&&h!==Object.prototype&&y!=="Object"){r.push(f);const g={};for(const[b,v]of Object.entries(d))g[b]=c(v,`${f}/${x(b)}`);return{[m]:"unsupported",kind:y??"unknown",value:g}}const w={};for(const[g,b]of Object.entries(d))w[g]=c(b,`${f}/${x(g)}`);return m in w?{[m]:"escaped",value:w}:w}return{value:c(o,""),report:{truncated:l,unsupported:r}}}function Z(o){const e=new Map,t=[];function n(s,l){if(s===null||typeof s!="object")return s;if(Array.isArray(s)){const a=[];return e.set(l,a),s.forEach((d,f)=>{if(z(d)){t.push({target:a,key:f,path:d.path}),a[f]=void 0;return}a[f]=n(d,`${l}/${f}`)}),a}if(typeof s[m]=="string"){const a=s;switch(a[m]){case"undefined":return;case"nan":return Number.NaN;case"infinity":return a.sign===1?1/0:-1/0;case"bigint":return BigInt(a.value);case"date":return new Date(a.iso);case"regexp":return new RegExp(a.source,a.flags);case"error":{const d=new Error(a.message);return d.name=a.name,d}case"binary":{const d=fe(a.b64);if(a.kind==="ArrayBuffer"){const p=d.slice();return e.set(l,p.buffer),p.buffer}if(a.kind==="DataView"){const p=d.slice(),h=new DataView(p.buffer);return e.set(l,h),h}const f=Object.prototype.hasOwnProperty.call($,a.kind)?$[a.kind]:void 0;if(f===void 0)return;const u=new f(d.slice().buffer);return e.set(l,u),u}case"unsupported":return a.value!==void 0?r(a.value,l):void 0;case"ref":return;case"map":{const d=new Map;return e.set(l,d),a.entries.forEach(([f,u],p)=>{d.set(n(f,`${l}/@k${p}`),n(u,`${l}/${p}`))}),d}case"set":{const d=new Set;return e.set(l,d),a.values.forEach((f,u)=>d.add(n(f,`${l}/${u}`))),d}case"escaped":return r(a.value,l);default:return}}return r(s,l)}function r(s,l){const c={};e.set(l,c);for(const[a,d]of Object.entries(s)){const f=`${l}/${x(a)}`;if(z(d)){t.push({target:c,key:a,path:d.path}),c[a]=void 0;continue}c[a]=n(d,f)}return c}const i=n(o,"");e.set("",i);for(const{target:s,key:l,path:c}of t)s[l]=e.get(c);return i}function z(o){return o!==null&&typeof o=="object"&&o[m]==="ref"&&typeof o.path=="string"}function x(o){return o.replace(/~/g,"~0").replace(/\//g,"~1")}function ue(o,e,t={}){let n=t.maxNodes??1e5;for(let r=0;r<8;r+=1){const{value:i,report:s}=A(o,{...t,maxNodes:n});let l;try{l=JSON.stringify(i)?.length??0}catch{l=Number.POSITIVE_INFINITY}if(l<=e)return s.truncated?{value:i,truncated:!0,note:`State was too large to send in full; parts beyond ${n} nodes are omitted.`}:{value:i,truncated:!1};const c=Math.floor(n*e*.8/l);if(n=Math.max(1,Math.min(c,n-1)),n<=1&&r>0)break}return{value:{[m]:"unsupported",kind:"truncated"},truncated:!0,note:`State exceeds the ${e}-byte transport limit and could not be reduced to fit.`}}const he=1e4;function B(o){return o===null||typeof o!="object"?JSON.stringify(o)??"null":Array.isArray(o)?`[${o.map(B).join(",")}]`:`{${Object.entries(o).sort(([t],[n])=>t<n?-1:t>n?1:0).map(([t,n])=>`${JSON.stringify(t)}:${B(n)}`).join(",")}}`}function pe(o,e,t){const n=`${o}::${e}`;if(t===null)return`${n}::null`;if(t===void 0)return`${n}::undefined`;if(typeof t!="object")return`${n}::${typeof t}:${String(t)}`;try{const{value:r,report:i}=A(t,{maxNodes:he});return i.truncated?`${n}::${Date.now()}::${Math.random()}`:`${n}::${B(r)}`}catch{return`${n}::${Date.now()}::${Math.random()}`}}function M(o,e){return!o||"any"in o&&o.any===!0?!0:"keys"in o?o.keys.some(([t,n])=>e.channel===t&&e.type===n):"channel"in o?e.channel===o.channel:"channels"in o?o.channels.includes(e.channel):!1}function ge(o){return typeof o=="function"?o:o.middleware}function T(o){if(typeof o!="function")return o.when}function U(o){if(o.when){const e=o.when;if("keys"in e)return e.keys}return[]}function ye(o,e){try{return structuredClone(e)}catch(t){throw new Error(`[yoltra] Initial state for slice "${String(o)}" could not be copied: ${t instanceof Error?t.message:String(t)}. State must be structured-cloneable — functions, class instances and DOM nodes are not. Keep behaviour out of state and store plain data.`)}}function D(o,e){return process.env.NODE_ENV==="production"?o:k(o,new WeakSet,e)}const H=100,V=64,me=64,we=64,W=16,be=Object.freeze({committed:!1,written:!1}),Ee=Object.freeze({committed:!1,written:!1,reason:"deduped"}),F=Object.freeze({committed:!1,written:!1,reason:"cascade"}),ve=Object.freeze({committed:!0,written:!1}),Se=Object.freeze({committed:!0,written:!0}),K=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();class R{name;middleware;reducers;state;reducerBus;connectorBus;listeners=new Set;effects=new Map;patternEffects=new Set;committedEventSubscribers=new Map;uncommittedEventSubscribers=new Map;writtenEventSubscribers=new Map;allEventSubscribers=new Map;replaying=!1;sliceUnsubs=new Map;patternReducers=new Map;sliceOrigin=new Map;sliceOwner=new Map;disposedSlices=new Map;registrationObservers=new Set;pendingRegistrationChanges=null;registrationDepth=0;notifyingRegistrations=!1;queuedRegistrationBatches=[];replayEnabled;idFactory;onEffectError;onReducerError;onSubscriberError;warnedPayloadAliases=new Set;reduceQueue=[];isReducing=!1;currentEvent=null;transitionsThisDrain=0;maxReduceDepth;maxTransitionsPerDrain;onCascade;onRejected;instrumentObservers=new Set;changedPathSink=null;stagingSink=null;stagedRejection=null;stagedRejectedBy="";inFlightEffects=0;processedEvents=new Map;dedupCount=0;effectMeta=new WeakMap;dedupConfig;eventCleanupTimer=null;constructor(e){if(this.name=e.name??"yoltra Store",this.reducerBus=new q,this.connectorBus=new Q,this.middleware=(e.middleware??[]).map(t=>({input:t,origin:"spec"})),this.reducers={},this.state={},this.replayEnabled=e.devtools?.allowReplay??!1,this.idFactory=e.idFactory??(()=>crypto.randomUUID()),this.onEffectError=e.onEffectError,this.onReducerError=e.onReducerError,this.onSubscriberError=e.onSubscriberError,this.maxReduceDepth=e.maxReduceDepth??we,this.maxTransitionsPerDrain=e.maxTransitionsPerDrain??1/0,this.onCascade=e.onCascade,this.onRejected=e.onRejected,this.dedupConfig={windowMs:e.dedupWindowMs??0,maxCacheSize:1e3},Object.entries(e.reducer).forEach(([t,n])=>{this.mountSlice(t,n,{preserveState:!1})}),e.effects?.length)for(const t of e.effects)this.registerEffectWithOrigin(t,"spec");this.dispose=this.dispose.bind(this),this.notifyEffects=this.notifyEffects.bind(this),this.__applyExternalState=this.__applyExternalState.bind(this),this.__replayEvents=this.__replayEvents.bind(this),this.__devtoolsIntrospect=this.__devtoolsIntrospect.bind(this),this.mountSlice=this.mountSlice.bind(this),this.unmountSlice=this.unmountSlice.bind(this),this.getAtPath=this.getAtPath.bind(this),this.emit=this.emit.bind(this),this.subscribe=this.subscribe.bind(this),this.connect=this.connect.bind(this),this.onEffect=this.onEffect.bind(this),this.onEvent=this.onEvent.bind(this),this.getState=this.getState.bind(this),this.registerEffect=this.registerEffect.bind(this),this.registerMiddleware=this.registerMiddleware.bind(this),this.registerReducer=this.registerReducer.bind(this),this.replaceMiddleware=this.replaceMiddleware.bind(this),this.replaceEffects=this.replaceEffects.bind(this),this.replaceReducers=this.replaceReducers.bind(this),this.hotReplace=this.hotReplace.bind(this)}dispose(){this.eventCleanupTimer&&(clearInterval(this.eventCleanupTimer),this.eventCleanupTimer=null),this.processedEvents.clear(),this.effects.clear(),this.patternEffects.clear(),this.effectMeta=new WeakMap,this.warnedPayloadAliases.clear(),this.listeners.clear(),this.committedEventSubscribers.clear(),this.uncommittedEventSubscribers.clear(),this.writtenEventSubscribers.clear(),this.allEventSubscribers.clear(),this.instrumentObservers.clear(),this.connectorBus.clear(),this.reducerBus.clear(),this.patternReducers.clear(),this.sliceUnsubs.clear(),this.sliceOrigin.clear(),this.sliceOwner.clear(),this.disposedSlices.clear(),this.registrationObservers.clear(),this.pendingRegistrationChanges=null,this.queuedRegistrationBatches.length=0,this.middleware.length=0,this.changedPathSink=null}fingerprint(e,t,n){return pe(e,t,n)}shouldDedupe(e,t){const n=Date.now(),r=this.processedEvents.get(e);return r!==void 0&&n-r<t?(this.dedupCount++,!0):(this.processedEvents.set(e,n),this.ensureCleanupTimer(),this.processedEvents.size>this.dedupConfig.maxCacheSize&&this.pruneProcessedEvents(n),!1)}ensureCleanupTimer(){this.eventCleanupTimer===null&&(this.eventCleanupTimer=setInterval(()=>{this.pruneProcessedEvents(Date.now())},5e3),this.eventCleanupTimer.unref?.())}pruneProcessedEvents(e){const t=Math.max(this.dedupConfig.windowMs,H),n=e-t*2;for(const[r,i]of this.processedEvents)i<n&&this.processedEvents.delete(r);this.processedEvents.size===0&&this.eventCleanupTimer!==null&&(clearInterval(this.eventCleanupTimer),this.eventCleanupTimer=null)}reportCascade(e,t,n,r,i){console.error(`[yoltra] Cascade stopped: "${n.channel}/${n.type}" would exceed ${e} (${t}). This event was refused and the chain ends here. A chain this long is almost always two consumers emitting into each other — check what reacts to "${n.channel}/${n.type}" and what that emits in turn.`+(i.length>0?` Recent causal chain: ${i.join(" → ")} → (refused).`:""));try{this.onCascade?.({limit:e,limitValue:t,event:n,depth:r,chain:i})}catch(s){console.error("onCascade handler error:",s)}}async notifyEffects(e){const t=this.scopedEmit(e),n=`${String(e.channel)}::${String(e.type)}`,r=this.effects.get(n);if(r&&r.size>0)for(const i of[...r])try{await i.effect(e,this.getState,t)}catch(s){console.error("Effect error:",s),this.onEffectError?.(s,e)}for(const{effect:i,when:s}of this.patternEffects)if(M(s,e))try{await i(e,this.getState,t)}catch(l){console.error("Effect error:",l),this.onEffectError?.(l,e)}}scopedEmit(e){const t={id:e.id,depth:e.depth??0,chain:[...this.currentEvent?.chain??[],e.id].slice(-W)};return((n,r,i,s)=>this.emitCaused(t,n,r,i,s))}notifyEventSubscribers(e,t){const n=`${String(e.channel)}::${String(e.type)}`,i=(t==="committed"?this.committedEventSubscribers:t==="written"?this.writtenEventSubscribers:this.uncommittedEventSubscribers).get(n);if(i?.size)for(const l of[...i])this.replaying&&!l.duringReplay||this.invokeEventSubscriber(l.handler,e,t);if(t==="written")return;const s=this.allEventSubscribers.get(n);if(s?.size)for(const l of[...s])this.replaying&&!l.duringReplay||this.invokeEventSubscriber(l.handler,e,t)}invokeEventSubscriber(e,t,n){const r=i=>{console.error("Event subscription error:",i),this.onSubscriberError?.(i,t,n)};try{const i=e(t,this.getState,this.emit,n);i&&typeof i.then=="function"&&i.catch(r)}catch(i){r(i)}}stageSliceGuarded(e,t,n){try{return this.stageSlice(e,t,n)}catch(r){return console.error(`Reducer error in slice "${e}":`,r),this.onReducerError?.(r,t,e),null}}stageSlice(e,t,n){const r=this.state[e],i=this.reducers[e].reduce(r,t);if(X(i))return i;if(r===i)return null;const s=C(r,i);if(s.length===0)return null;const l=t.payload,c=process.env.NODE_ENV!=="production"&&l!==null&&typeof l=="object"?{watch:l,onFound:()=>{const a=`${e}:${t.channel}:${t.type}`;this.warnedPayloadAliases.has(a)||(this.warnedPayloadAliases.add(a),console.warn(`[yoltra] Slice "${e}" stored the payload of "${t.channel}/${t.type}" by reference. It is now frozen along with the rest of the state, so the emitter mutating it later will throw in development and silently corrupt state in production. Copy the payload in the reducer instead.`))}}:void 0;return n.push({name:e,prev:r,frozen:D(i,c),leafPaths:s}),null}commitStaged(e,t){if(e.length===0)return!1;const n={...this.state};for(const r of e)n[r.name]=r.frozen;if(this.state=n,this.changedPathSink)for(const r of e)for(const i of r.leafPaths)this.changedPathSink.push(i?`${r.name}.${i}`:r.name);for(const r of e){const i=new Set;for(const s of r.leafPaths){if(s===""){i.add("");continue}for(const l of R.buildAncestorPaths(s))i.add(l)}for(const s of i)this.connectorBus.emitWith(r.name,s,()=>({oldValue:this.getAtPath(r.prev,s),newValue:this.getAtPath(r.frozen,s),path:s,eventId:t.id,channel:t.channel,type:t.type}))}return!0}__devtoolsIntrospect(){const e=Object.keys(this.reducers).map(c=>{const a=this.patternReducers.get(c);return{name:c,when:a,origin:this.sliceOrigin.get(c)??"spec",owner:this.sliceOwner.get(c)}}),t=[];for(const[c,a]of this.effects){if(a.size===0)continue;const[d,f]=c.split("::");for(const u of a){const p=this.effectMeta.get(u.effect);t.push({channel:d,type:f,name:p?.name,description:p?.description,origin:u.origin})}}for(const c of this.patternEffects){const a=this.effectMeta.get(c.effect);t.push({channel:"*",type:"*",name:a?.name,description:a?.description,origin:c.origin})}const n=[];for(const{input:c,origin:a}of this.middleware)typeof c=="function"?n.push({name:c.name||void 0,origin:a}):n.push({name:c.meta?.name,description:c.meta?.description,when:c.when,origin:a});const r=[];for(const c of this.connectorBus.__introspect())for(let a=0;a<c.count;a++)r.push({reducer:c.channel,property:c.type});const i=[],s=(c,a)=>{for(const[d,f]of c){if(f.size===0)continue;const[u,p]=d.split("::");for(const h of f)i.push({channel:u,type:p,phase:a,duringReplay:h.duringReplay})}};s(this.committedEventSubscribers,"committed"),s(this.uncommittedEventSubscribers,"uncommitted"),s(this.writtenEventSubscribers,"written"),s(this.allEventSubscribers,"all");const l=this.listeners.size;return{reducers:e,effects:t,middleware:n,atomic:r,event:i,coarse:l,dedupHits:this.dedupCount,queueDepth:this.reduceQueue.length+this.inFlightEffects}}__applyExternalState(e){if(!this.replayEnabled)throw new Error("[yoltra] External state apply (time-travel) is disabled. Enable it with createStore({ devtools: { allowReplay: true } })");const t=this.replaying;this.replaying=!0;try{return this.applyExternalStateInner(e)}finally{this.replaying=t}}applyExternalStateInner(e){const t=this.state,n=e,r={...this.state};let i=!1;Object.keys(this.reducers).forEach(s=>{const l=t?.[s],c=n?.[s];if(c===void 0){process.env.NODE_ENV!=="production"&&(this.sliceOrigin.get(s)??"spec")==="spec"&&console.warn(`[yoltra] External state is missing slice "${String(s)}"; retaining its current value. Time-travel snapshots should contain all slices.`);return}if(l===c)return;const a=D(c);r[s]=a,i=!0;const d=C(l,c);if(d.length===0)return;const f=new Set;for(const u of d){if(u===""){f.add("");continue}for(const p of R.buildAncestorPaths(u))f.add(p)}for(const u of f){const p=this.getAtPath(l,u),h=this.getAtPath(a,u);this.connectorBus.emit(s,u,{oldValue:p,newValue:h,path:u})}}),i&&(this.state=r),i&&this.listeners.forEach(s=>s())}__replayEvents(e,t){if(!this.replayEnabled)throw new Error("[yoltra] Event replay is disabled. Enable it with createStore({ devtools: { allowReplay: true } })");const n=this.replaying;this.replaying=!0;try{this.replayEventsInner(e,t)}finally{this.replaying=n}}replayEventsInner(e,t){this.__applyExternalState(e);for(const n of t){const r=n,i=[];this.stagingSink=i;let s=null;try{this.reducerBus.emit(r.channel,r.type,r.payload,r),s=this.stagedRejection;for(const[c,a]of this.patternReducers){if(s!==null)break;if(M(a,r)){const d=this.stageSliceGuarded(c,r,i);d!==null&&(s=d)}}}finally{this.stagingSink=null,this.stagedRejection=null,this.stagedRejectedBy=""}const l=s===null&&this.commitStaged(i,r);this.notifyEventSubscribers(r,"committed"),l&&(this.notifyEventSubscribers(r,"written"),this.listeners.forEach(c=>c()))}}async emit(e,t,n,r){return this.emitCaused(null,e,t,n,r)}async emitCaused(e,t,n,r,i){const s=i?.dedupKey,l=this.dedupConfig.windowMs;if(i?.skipDedup!==!0&&(l>0||s!==void 0)){const p=s!==void 0&&l<=0?H:l,h=s!==void 0?`${t}::${n}::#${s}`:this.fingerprint(t,n,r);if(this.shouldDedupe(h,p))return Ee}const c=i?.id??this.idFactory(),a=this.currentEvent??e,d=a===null?0:a.depth+1;if(a!==null&&d>this.maxReduceDepth)return this.reportCascade("maxReduceDepth",this.maxReduceDepth,{channel:t,type:n,payload:r,id:c,...i?.meta!==void 0?{meta:i.meta}:{},parentId:a.id,depth:d},d,a.chain),F;let f;const u=new Promise(p=>{f=p});return this.reduceQueue.push({channel:t,type:n,payload:r,id:c,meta:i?.meta,resolve:f,...a!==null?{parentId:a.id,depth:d,chain:a.chain}:{}}),this.drainReduce(),u}drainReduce(){if(!this.isReducing){this.isReducing=!0,this.transitionsThisDrain=0;try{for(;this.reduceQueue.length>0;){const e=this.reduceQueue.shift(),{channel:t,type:n,payload:r,id:i,meta:s,resolve:l,parentId:c,depth:a,chain:d}=e,f={channel:t,type:n,payload:r,id:i,...s!==void 0?{meta:s}:{},...c!==void 0?{parentId:c,depth:a}:{}};if(c!==void 0&&++this.transitionsThisDrain>this.maxTransitionsPerDrain){this.reportCascade("maxTransitionsPerDrain",this.maxTransitionsPerDrain,f,a,d),l(F);continue}this.currentEvent={id:i,depth:a??0,chain:[...d??[],i].slice(-W)};const u=this.instrumentObservers.size>0,p=u?this.state:void 0,h=u?[]:void 0;h!==void 0&&(this.changedPathSink=h);const y=u?K():0;let w=be;try{w=this.applyEventSync(f)}catch(g){console.error("Emit reduce error:",g)}finally{u&&(this.changedPathSink=null),this.currentEvent=null}u&&this.emitInstrumentation(f,w,h??[],p,K()-y),this.runEventEffects(f,w,l)}}finally{this.isReducing=!1}}}applyEventSync(e){for(const{input:s}of this.middleware){const l=T(s);if(!M(l,e))continue;const c=ge(s);let a;try{a=c(this.state,e,this.emit),process.env.NODE_ENV!=="production"&&typeof a?.then=="function"&&console.error(`[yoltra] Middleware for "${e.channel}/${e.type}" returned a Promise. Middleware is synchronous: a Promise is truthy, so this event was allowed without waiting and a "return false" inside it can never veto. Do the check synchronously, and put anything that must await in an effect.`)}catch(d){console.error(`[yoltra] Middleware threw for "${e.channel}/${e.type}"; the event was vetoed and did not reach any reducer.`,d),a=!1}if(a===!1){this.notifyEventSubscribers(e,"uncommitted");const d=typeof s=="function"?s.name||void 0:s.meta?.name;return Object.freeze({committed:!1,written:!1,reason:"vetoed",...d!==void 0&&d!==""?{vetoedBy:d}:{}})}}const t=[];this.stagingSink=t;let n=null,r="";try{this.reducerBus.emit(e.channel,e.type,e.payload,e),n=this.stagedRejection,r=this.stagedRejectedBy;for(const[s,l]of this.patternReducers){if(n!==null)break;if(M(l,e)){const c=this.stageSliceGuarded(s,e,t);c!==null&&(n=c,r=s)}}}finally{this.stagingSink=null,this.stagedRejection=null,this.stagedRejectedBy=""}if(n!==null)return this.onRejected?.(n,e,r),this.notifyEventSubscribers(e,"committed"),{committed:!0,written:!1,rejected:n};const i=this.commitStaged(t,e);return this.notifyEventSubscribers(e,"committed"),i&&(this.notifyEventSubscribers(e,"written"),this.listeners.forEach(s=>s())),i?Se:ve}async runEventEffects(e,t,n){this.inFlightEffects++;try{t.committed&&await this.notifyEffects(e)}catch(r){console.error("Effect error:",r)}finally{this.inFlightEffects--,n(t)}}instrument(e){return this.instrumentObservers.add(e),()=>{this.instrumentObservers.delete(e)}}emitInstrumentation(e,t,n,r,i){const s={},l={};for(const a of n)s[a]=this.getAtPath(r,a),l[a]=this.getAtPath(this.state,a);const c={event:{id:e.id,channel:e.channel,type:e.type,payload:e.payload,...e.meta!==void 0?{meta:e.meta}:{}},committed:t.committed,changedPaths:n,prevValues:s,nextValues:l,reduceTimeMs:i,...t.rejected!==void 0?{rejected:t.rejected}:{}};for(const a of[...this.instrumentObservers])try{a(c)}catch(d){console.error("Instrumentation observer error:",d)}}connect(e,t,n){if(process.env.NODE_ENV!=="production"&&this.disposedSlices.has(e.reducer)){const i=this.disposedSlices.get(e.reducer);throw new Error(`[yoltra] Slice "${String(e.reducer)}" was unmounted by its owner${i===void 0?"":` (${i})`}. Hooks and subscriptions widened for it are no longer valid.`)}const r=this.connectorBus.on(e.reducer,e.property,t);if(n?.immediate===!0){const i=this.state[e.reducer],s=e.property.includes("*")?"":e.property;t({oldValue:void 0,newValue:this.getAtPath(i,s),path:s})}return r}onRegistrationChange(e,t){if(this.registrationObservers.add(e),t?.emitCurrent===!0){const n=this.describeCurrentRegistrations();if(n.length>0){const r=this.notifyingRegistrations;this.notifyingRegistrations=!0;try{this.invokeRegistrationObserver(e,n)}finally{this.notifyingRegistrations=r}r||this.drainQueuedRegistrationBatches()}}return()=>{this.registrationObservers.delete(e)}}describeCurrentRegistrations(){const e=[];for(const t of Object.keys(this.reducers))e.push({kind:"reducer",op:"mounted",name:t,origin:this.sliceOrigin.get(t)??"spec",owner:this.sliceOwner.get(t),when:this.patternReducers.get(t),state:"initialized",dispatch:this.patternReducers.has(t)?"pattern":"keyed"});for(const t of this.middleware){const n=typeof t.input=="function"?void 0:t.input.meta;e.push({kind:"middleware",op:"mounted",name:n?.name??(typeof t.input=="function"?t.input.name:void 0),description:n?.description,origin:t.origin,when:T(t.input),dispatch:"pattern"})}for(const[t,n]of this.effects){const[r,i]=t.split("::");for(const s of n)e.push({kind:"effect",op:"mounted",name:this.effectMeta.get(s.effect)?.name,description:this.effectMeta.get(s.effect)?.description,origin:s.origin,when:{keys:[[r,i]]},dispatch:"keyed"})}for(const t of this.patternEffects)e.push({kind:"effect",op:"mounted",name:this.effectMeta.get(t.effect)?.name,description:this.effectMeta.get(t.effect)?.description,origin:t.origin,when:t.when,dispatch:"pattern"});return e}inRegistrationTransaction(e){this.registrationDepth+=1;try{return e()}finally{this.registrationDepth-=1,this.registrationDepth===0&&this.flushRegistrationChanges()}}recordRegistrationChange(e){this.registrationObservers.size!==0&&((this.pendingRegistrationChanges??=[]).push(e()),this.registrationDepth===0&&this.flushRegistrationChanges())}flushRegistrationChanges(){const e=this.pendingRegistrationChanges;if(this.pendingRegistrationChanges=null,!(e===null||e.length===0)){if(this.notifyingRegistrations){this.queuedRegistrationBatches.push(e);return}this.notifyingRegistrations=!0;try{this.deliverRegistrationBatch(e),this.drainQueuedRegistrationBatches()}finally{this.notifyingRegistrations=!1}}}drainQueuedRegistrationBatches(){let e=0;for(;this.queuedRegistrationBatches.length>0;){if(e>=V){console.error(`[yoltra] Registration notifications exceeded ${V} rounds; dropping the rest. Two observers are most likely registering in response to each other.`),this.queuedRegistrationBatches.length=0;break}e+=1,this.deliverRegistrationBatch(this.queuedRegistrationBatches.shift())}}deliverRegistrationBatch(e){for(const t of[...this.registrationObservers])this.invokeRegistrationObserver(t,e)}invokeRegistrationObserver(e,t){try{const n=e(t);process.env.NODE_ENV!=="production"&&typeof n?.then=="function"&&console.error("[yoltra] A registration observer returned a Promise. Registration notifications are synchronous: the store has already moved on by the time it resolves. Do the work synchronously, or schedule it yourself and accept that the topology may have changed again.")}catch(n){console.error("Registration observer error:",n)}}get isReplaying(){return this.replaying}onEvent(e,t,n,r="committed",i){const s=`${e}::${String(t)}`,l=r==="committed"?this.committedEventSubscribers:r==="uncommitted"?this.uncommittedEventSubscribers:r==="written"?this.writtenEventSubscribers:this.allEventSubscribers;l.has(s)||l.set(s,new Set);const c={handler:n,duringReplay:i?.duringReplay===!0};return l.get(s).add(c),()=>{const a=l.get(s);a&&(a.delete(c),a.size===0&&l.delete(s))}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}getState(){return this.state}registerMiddleware(e){const t={input:e,origin:"dynamic"};return this.middleware.push(t),this.recordMiddlewareChange(t,"mounted"),this.asRegistration(()=>{const n=this.middleware.indexOf(t);n!==-1&&(this.middleware.splice(n,1),this.recordMiddlewareChange(t,"unmounted"))})}recordMiddlewareChange(e,t){this.recordRegistrationChange(()=>{const n=typeof e.input=="function"?void 0:e.input.meta;return{kind:"middleware",op:t,name:n?.name??(typeof e.input=="function"?e.input.name:void 0),description:n?.description,origin:e.origin,when:T(e.input),dispatch:"pattern"}})}releaseEffectMeta(e){for(const t of this.effects.values())for(const n of t)if(n.effect===e)return;for(const t of this.patternEffects)if(t.effect===e)return;this.effectMeta.delete(e)}recordEffectChange(e,t,n,r,i){this.recordRegistrationChange(()=>({kind:"effect",op:r,name:this.effectMeta.get(e)?.name,description:this.effectMeta.get(e)?.description,origin:n,when:t,dispatch:i}))}asRegistration(e){return Object.assign(e,{store:this,dispose:e})}widened(){return this}registerReducer(e,t,n){return this.registerSlice(e,t,n)}registerSlice(e,t,n){return this.inRegistrationTransaction(()=>this.registerSliceInner(e,t,n))}registerSliceInner(e,t,n){if(Object.prototype.hasOwnProperty.call(this.reducers,e))throw new Error(`Reducer ${e} already exists`);return this.mountSlice(e,t,{preserveState:!1,origin:"dynamic",owner:n?.owner}),this.listeners.forEach(r=>r()),this.announceMountedSlice(e,this.state[e]),this.asRegistration(()=>{Object.prototype.hasOwnProperty.call(this.reducers,e)&&this.inRegistrationTransaction(()=>{this.unmountSlice(e,{deleteState:!0}),this.listeners.forEach(r=>r())})})}withSlice(e,t,n){return this.registerSlice(e,t,n),this.widened()}withMiddleware(e){return this.registerMiddleware(e),this.widened()}withEffect(e){return this.registerEffect(e),this.widened()}call(e,t,n,r){return ce({idFactory:this.idFactory,registerEffect:i=>this.registerEffectWithOrigin(i,"internal"),emit:this.emit},e,t,n,r)}registerEffect(e){return this.asRegistration(this.registerEffectWithOrigin(e,"dynamic"))}registerEffectWithOrigin(e,t){const{effect:n,meta:r,when:i}=e,s=[];if(r&&this.effectMeta.set(n,r),i&&("any"in i&&i.any===!0||"channel"in i||"channels"in i)){const a={effect:n,when:i,origin:t};return this.patternEffects.add(a),this.recordEffectChange(n,i,t,"mounted","pattern"),()=>{this.recordEffectChange(n,i,t,"unmounted","pattern"),this.patternEffects.delete(a),this.releaseEffectMeta(n)}}const c=U(e);if(c.length===0&&!i){const a={any:!0},d={effect:n,when:a,origin:t};return this.patternEffects.add(d),this.recordEffectChange(n,a,t,"mounted","pattern"),()=>{this.recordEffectChange(n,a,t,"unmounted","pattern"),this.patternEffects.delete(d),this.releaseEffectMeta(n)}}for(const[a,d]of c){const f=`${String(a)}::${String(d)}`;this.effects.has(f)||this.effects.set(f,new Set);const u={effect:n,origin:t};this.effects.get(f).add(u);const p={keys:[[a,d]]};this.recordEffectChange(n,p,t,"mounted","keyed"),s.push(()=>{this.recordEffectChange(n,p,t,"unmounted","keyed");const h=this.effects.get(f);h&&(h.delete(u),h.size===0&&this.effects.delete(f))})}return()=>{for(const a of s)a();this.releaseEffectMeta(n)}}onEffect(e,t,n){const r=async(i,s,l)=>{if(i.channel!==e||i.type!==t)return;const c=i;return n(c.payload,s,l,c)};return this.registerEffect({when:{keys:[[e,t]]},effect:r})}replaceMiddleware(e,t={}){this.inRegistrationTransaction(()=>this.replaceMiddlewareInner(e,t))}replaceMiddlewareInner(e,t={}){const n=t.scope??"spec",r=this.middleware.filter(i=>n==="all"?i.origin==="internal":i.origin!=="spec");for(const i of this.middleware)r.includes(i)||this.recordMiddlewareChange(i,"unmounted");this.middleware.length=0;for(const i of e){const s={input:i,origin:"spec"};this.middleware.push(s),this.recordMiddlewareChange(s,"mounted")}for(const i of r)this.middleware.push(i);this.reportPreserved("replaceMiddleware",r.length,n)}replaceEffects(e,t={}){this.inRegistrationTransaction(()=>this.replaceEffectsInner(e,t))}replaceEffectsInner(e,t={}){const n=t.scope??"spec",r=s=>n==="all"?s==="internal":s!=="spec";let i=0;for(const[s,l]of this.effects){for(const c of[...l]){if(r(c.origin)){i+=1;continue}this.recordEffectChange(c.effect,{keys:[s.split("::")]},c.origin,"unmounted","keyed"),l.delete(c),this.releaseEffectMeta(c.effect)}l.size===0&&this.effects.delete(s)}for(const s of[...this.patternEffects]){if(r(s.origin)){i+=1;continue}this.recordEffectChange(s.effect,s.when,s.origin,"unmounted","pattern"),this.patternEffects.delete(s),this.releaseEffectMeta(s.effect)}for(const s of e)this.registerEffectWithOrigin(s,"spec");this.reportPreserved("replaceEffects",i,n)}replaceReducers(e,t={}){this.inRegistrationTransaction(()=>this.replaceReducersInner(e,t))}replaceReducersInner(e,t={}){const n=t.preserveState!==!1,r=t.scope??"spec",i=new Set(Object.keys(this.reducers)),s=Object.entries(e),l=new Set(s.map(([d])=>d));this.assertNoSliceCollision(e,r);const c=this.state;let a=0;for(const d of i){if(l.has(d))continue;const f=this.sliceOrigin.get(d)??"spec";if(!(r==="all"?f!=="internal":f==="spec")){a+=1;continue}this.unmountSlice(d,{deleteState:!0})}for(const[d,f]of s)i.has(d)?(this.unmountSlice(d,{deleteState:!1}),this.mountSlice(d,f,{preserveState:n,origin:"spec"})):this.mountSlice(d,f,{preserveState:!1,origin:"spec"});this.state!==c&&this.listeners.forEach(d=>d()),this.reportPreserved("replaceReducers",a,r)}assertNoSliceCollision(e,t){if(t!=="spec")return;const n=Object.keys(e).filter(i=>this.sliceOrigin.get(i)==="dynamic");if(n.length===0)return;const r=n.map(i=>{const s=this.sliceOwner.get(i);return s===void 0?`"${i}"`:`"${i}" (owner: ${s})`}).join(", ");throw new Error(`[yoltra] replaceReducers would take over ${n.length===1?"a slice":"slices"} mounted at runtime: ${r}. Rename the slice, or pass { scope: "all" } to replace it deliberately.`)}reportPreserved(e,t,n){t!==0&&process.env.NODE_ENV!=="production"&&console.debug(`[yoltra] ${e} preserved ${t} registration${t===1?"":"s"} made after construction.${n==="spec"?' Pass { scope: "all" } to replace them too.':""}`)}hotReplace(e){const t=e.scope;e.reducer&&this.assertNoSliceCollision(e.reducer,t??"spec"),this.inRegistrationTransaction(()=>{e.middleware&&this.replaceMiddleware(e.middleware,{scope:t}),e.effects&&this.replaceEffects(e.effects,{scope:t}),e.reducer&&this.replaceReducers(e.reducer,{preserveState:e.preserveState,scope:t})})}mountSlice(e,t,n){this.mountSliceInner(e,t,n),this.recordSliceChange(e,"mounted",n.preserveState?"preserved":"initialized")}mountSliceInner(e,t,n){const r=e;this.sliceOrigin.set(r,n.origin??"spec"),n.owner!==void 0&&this.sliceOwner.set(r,n.owner),this.disposedSlices.delete(r);const{reducer:i,state:s,when:l}=t;if(this.reducers[e]=new G(i),(!n.preserveState||this.state[r]===void 0)&&(this.state={...this.state,[r]:D(ye(r,s))}),l&&("any"in l&&l.any===!0||"channel"in l||"channels"in l)){this.patternReducers.set(e,l),this.sliceUnsubs.set(r,[]);return}const a=U(t);if(a.length===0&&!l){this.patternReducers.set(e,{any:!0}),this.sliceUnsubs.set(r,[]);return}const d=[];for(const[f,u]of a){const p=this.reducerBus.on(f,u,(h,y)=>{const w=y??{channel:f,type:u,payload:h,id:this.idFactory()};if(this.stagingSink===null)return;const g=this.stageSliceGuarded(e,w,this.stagingSink);g!==null&&this.stagedRejection===null&&(this.stagedRejection=g,this.stagedRejectedBy=e)});d.push(p)}this.sliceUnsubs.set(r,d)}recordSliceChange(e,t,n){this.recordRegistrationChange(()=>({kind:"reducer",op:t,name:e,origin:this.sliceOrigin.get(e)??"spec",owner:this.sliceOwner.get(e),when:this.patternReducers.get(e),state:n,dispatch:this.patternReducers.has(e)?"pattern":"keyed"}))}announceMountedSlice(e,t){const r=C(typeof t=="object"&&t!==null?{}:void 0,t),i=new Set([""]);for(const s of r)if(s!=="")for(const l of R.buildAncestorPaths(s))i.add(l);for(const s of i){const l=this.getAtPath(this.state[e],s);this.connectorBus.emit(e,s,{oldValue:void 0,newValue:l,path:s})}}unmountSlice(e,t){const n=e;if(this.recordSliceChange(n,"unmounted",t.deleteState?"deleted":"retained"),this.patternReducers.delete(e),process.env.NODE_ENV!=="production"){const i=this.sliceOrigin.get(n);if(i==="dynamic"||i==="internal")for(this.disposedSlices.set(n,this.sliceOwner.get(n));this.disposedSlices.size>me;)this.disposedSlices.delete(this.disposedSlices.keys().next().value)}this.sliceOrigin.delete(n),this.sliceOwner.delete(n);const r=this.sliceUnsubs.get(n);if(r){for(const i of r)try{i()}catch(s){console.error(`[Store error]: ${s}`)}this.sliceUnsubs.delete(n)}if(delete this.reducers[e],t.deleteState){const{[n]:i,...s}=this.state;this.state=s}}getAtPath(e,t){return ae(e,t)}static buildAncestorPaths(e){return de(e)}}function Re(o){return new R({...o,reducer:o.reducer??{},middleware:o.middleware??[],effects:o.effects??[]})}const Oe=o=>(e,t)=>t.map(n=>[e,n]),ke=()=>o=>o,$e=()=>o=>o,Me=()=>o=>o,Ce=()=>o=>o,L=new Set;function Pe(o){const e=String(o);L.has(e)||(L.add(e),console.warn(`[yoltra] Entity id "${e}" contains a dot. Paths are dotted, so a subscription to "entities.${e}" is indistinguishable from one to a nested object of the same name. Use ids without dots.`))}function Ae(o,e){if(o.length!==e.length)return e;for(let t=0;t<o.length;t++)if(o[t]!==e[t])return e;return o}function Ie(o={}){const e=o.selectId??(c=>c.id),{sortComparer:t}=o,n=(c,a)=>{if(t===void 0)return a;const d=[...a].sort((f,u)=>{const p=c.entities[f],h=c.entities[u];return p===void 0||h===void 0?0:t(p,h)});return Ae(a,d)},r=(c,a,d)=>{const f={...c,entities:a,ids:d};return{...f,ids:n(f,d)}},i=(c,a,d)=>{let f=null,u=null;for(const p of a){const h=e(p);process.env.NODE_ENV!=="production"&&String(h).includes(".")&&Pe(h);const y=(f??c.entities)[h];if(y!==void 0&&d==="add")continue;const w=y!==void 0&&d==="upsert"?{...y,...p}:p;f??={...c.entities},f[h]=w,y===void 0&&(u??=[...c.ids],u.push(h))}return f===null?c:r(c,f,u??c.ids)},s=(c,a)=>{let d=null;for(const{id:f,changes:u}of a){const p=(d??c.entities)[f];p!==void 0&&(d??={...c.entities},d[f]={...p,...u})}return d===null?c:r(c,d,c.ids)},l=(c,a)=>{const d=new Set(a.filter(u=>c.entities[u]!==void 0));if(d.size===0)return c;const f={...c.entities};for(const u of d)delete f[u];return r(c,f,c.ids.filter(u=>!d.has(u)))};return{getInitialState(c){const a={ids:[],entities:{}};return c===void 0?a:{...a,...c}},addOne:(c,a)=>i(c,[a],"add"),addMany:(c,a)=>i(c,a,"add"),setOne:(c,a)=>i(c,[a],"set"),setMany:(c,a)=>i(c,a,"set"),setAll:(c,a)=>{const d={},f=[];for(const u of a){const p=e(u);d[p]===void 0&&f.push(p),d[p]=u}return r(c,d,f)},updateOne:(c,a)=>s(c,[a]),updateMany:(c,a)=>s(c,a),upsertOne:(c,a)=>i(c,[a],"upsert"),upsertMany:(c,a)=>i(c,a,"upsert"),removeOne:(c,a)=>l(c,[a]),removeMany:(c,a)=>l(c,a),removeAll:c=>c.ids.length===0?c:r(c,{},[]),selectIds:c=>c.ids,selectEntities:c=>c.entities,selectAll:c=>c.ids.map(a=>c.entities[a]),selectById:(c,a)=>c.entities[a],selectTotal:c=>c.ids.length,idsPath:"ids",pathTo:(c,a)=>a===void 0?`entities.${c}`:`entities.${c}.${a}`,anyField:c=>`entities.*.${c}`}}function S(o,e,t){o.onError?.(e,t)}async function Te(o){const e={slices:{},restored:!1};let t;try{t=o.source??await o.adapter.read(o.key)}catch(r){return S(o,r,"read"),e}if(t==null||t==="")return e;let n;try{n=Z(JSON.parse(t))}catch(r){return S(o,r,"decode"),e}if(n===null||typeof n!="object"||typeof n.version!="number")return S(o,new Error("persisted payload is not a recognisable envelope"),"decode"),e;if(n.version!==o.version){if(o.migrate===void 0)return S(o,new Error(`persisted state is version ${n.version}, this build expects ${o.version}, and no migrate was supplied`),"migrate"),e;try{const r=o.migrate(n.slices,n.version);return r===null?e:{slices:r,restored:!0}}catch(r){return S(o,r,"migrate"),e}}return{slices:n.slices??{},restored:!0}}function De(o,e){if(!e.restored)return o;const t={};for(const[n,r]of Object.entries(o)){const i=e.slices[n];t[n]=i===void 0?r:{...r,state:i}}return t}function ee(o,e){const t=o??{},n=e.slices===void 0?t:Object.fromEntries(e.slices.filter(s=>s in t).map(s=>[s,t[s]])),{value:r,report:i}=A({version:e.version,slices:n});if(i.truncated||i.unsupported.length>0){const s=[];i.truncated&&s.push("state was too large to encode in full"),i.unsupported.length>0&&s.push(`values with no faithful representation at: ${i.unsupported.join(", ")}`);const l=s.join("; ");S(e,new Error(`[yoltra] Persisted state is incomplete - ${l}.`),"encode")}return JSON.stringify(r)}function je(o,e){const t=e.throttleMs??250,n=e.slices;let r=null,i=!1;const s=()=>{if(i){i=!1;try{const a=e.adapter.write(e.key,ee(o.getState(),e));a instanceof Promise&&a.catch(d=>S(e,d,"write"))}catch(a){S(e,a,"write")}}},l=()=>{if(i=!0,t<=0){s();return}r===null&&(r=setTimeout(()=>{r=null,s()},t),r.unref?.())},c=o.instrument(a=>{if(n===void 0){l();return}(a.changedPaths??[]).some(f=>n.some(u=>f===u||f.startsWith(`${u}.`)))&&l()});return()=>{c(),r!==null&&(clearTimeout(r),r=null),s()}}function xe(o,e){return ee(o.getState(),e)}function Be(o){return{read:e=>o.getItem(e),write:(e,t)=>o.setItem(e,t),remove:e=>o.removeItem(e)}}function _e(o){const e=new Map(Object.entries(o??{}));return{read:t=>e.get(t)??null,write:(t,n)=>{e.set(t,n)},remove:t=>{e.delete(t)}}}exports.CallAbortedError=j;exports.CallTimeoutError=Y;exports.EventBus=q;exports.LooseEventBus=Q;exports.Reducer=G;exports.Rejected=te;exports.Store=R;exports.createEntityAdapter=Ie;exports.createMemoryAdapter=_e;exports.createStore=Re;exports.createWebStorageAdapter=Be;exports.decodeState=Z;exports.defineEffect=Ce;exports.defineMiddleware=Me;exports.defineSlice=$e;exports.dehydrate=xe;exports.detectChangedProps=C;exports.encodeState=A;exports.encodeStateBounded=ue;exports.eventKeys=ke;exports.freezeState=k;exports.hydrate=Te;exports.isRejected=X;exports.persist=je;exports.typedEvents=Oe;exports.withHydration=De;
11
6
  //# sourceMappingURL=yoltra.cjs.map