UNPKG

signalforge

Version:

Fine-grained reactive state management with automatic dependency tracking - Ultra-optimized, zero dependencies

52 lines (49 loc) 88 kB
var je=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var ln=(t,e)=>()=>(t&&(e=t(t=0)),e);function ur(){return`signal_${++dr}_${Date.now()}`}function dt(t){if(J.some(e=>e.name===t.name))throw new Error(`Plugin "${t.name}" is already registered`);if(J.push(t),t.onRegister)try{t.onRegister()}catch(e){console.error(`Error in plugin "${t.name}" onRegister:`,e)}`${t.name}`}function We(t){let e=typeof t=="string"?t:t.name,n=J.findIndex(o=>o.name===e);if(n===-1)return!1;let r=J[n];if(r.onUnregister)try{r.onUnregister()}catch(o){console.error(`Error in plugin "${r.name}" onUnregister:`,o)}return J.splice(n,1),`${r.name}`,!0}function gr(){return[...J]}function pr(){let t=J.map(e=>e.name);J.forEach(e=>{if(e.onUnregister)try{e.onUnregister()}catch(n){console.error(`Error in plugin "${e.name}" onUnregister:`,n)}}),J.length=0,`${t.length}`}function fr(){Te=!0}function mr(){Te=!1}function yr(){return Te}function cn(t,e,n){let r={id:ur(),type:t,createdAt:Date.now(),label:n};if(qe.set(r.id,r),Te){for(let o of J)if(o.onSignalCreate)try{o.onSignalCreate(r,e)}catch(s){console.error(`Error in plugin "${o.name}" onSignalCreate:`,s)}}return r}function dn(t,e,n,r="set"){if(!Te)return;let o=qe.get(t);if(!o)return;let s={signal:o,oldValue:e,newValue:n,timestamp:Date.now(),source:r};for(let i of J)if(i.onSignalUpdate)try{i.onSignalUpdate(s)}catch(a){console.error(`Error in plugin "${i.name}" onSignalUpdate:`,a)}}function un(t){if(!Te)return;let e=qe.get(t);if(e){for(let n of J)if(n.onSignalDestroy)try{n.onSignalDestroy(e)}catch(r){console.error(`Error in plugin "${n.name}" onSignalDestroy:`,r)}qe.delete(t)}}function hr(t={}){let{verbose:e=!1,logCreates:n=!0,logUpdates:r=!0,logDestroys:o=!0}=t;return{name:"logger",version:"1.0.0",onRegister(){},onSignalCreate(s,i){n&&`${s.type}${s.label||s.id}`},onSignalUpdate(s){r&&(`${s.signal.type}${s.signal.label||s.signal.id}`,e||`${s.oldValue}${s.newValue}`)},onSignalDestroy(s){o&&`${s.type}${s.label||s.id}`},onUnregister(){}}}function br(t={}){let{maxHistory:e=50}=t,n=[],r=[];return{plugin:{name:"time-travel",version:"1.0.0",onRegister(){},onSignalUpdate(s){n.push({signalId:s.signal.id,oldValue:s.oldValue,newValue:s.newValue,timestamp:s.timestamp}),r.length=0,n.length>e&&n.shift()},onUnregister(){n.length=0,r.length=0}},undo(){if(n.length===0)return!1;let s=n.pop();return r.push(s),`${s.newValue}${s.oldValue}`,!0},redo(){if(r.length===0)return!1;let s=r.pop();return n.push(s),`${s.oldValue}${s.newValue}`,!0},getHistory(){return[...n]},clear(){n.length=0,r.length=0},get historySize(){return n.length},get futureSize(){return r.length}}}function vr(){let t={totalUpdates:0,updatesBySignal:new Map,averageUpdateTime:0,slowestUpdate:null},e=0,n=new Map;return{plugin:{name:"performance",version:"1.0.0",onRegister(){},onBeforeUpdate(o){return n.set(o.signal.id,performance.now()),o.newValue},onSignalUpdate(o){let s=n.get(o.signal.id);if(s!==void 0){let i=performance.now()-s;e+=i,n.delete(o.signal.id),t.totalUpdates++,t.updatesBySignal.set(o.signal.id,(t.updatesBySignal.get(o.signal.id)||0)+1),t.averageUpdateTime=e/t.totalUpdates,(!t.slowestUpdate||i>t.slowestUpdate.duration)&&(t.slowestUpdate={signalId:o.signal.label||o.signal.id,duration:i})}},onUnregister(){}},getMetrics(){return{...t,updatesBySignal:new Map(t.updatesBySignal)}},reset(){t.totalUpdates=0,t.updatesBySignal.clear(),t.averageUpdateTime=0,t.slowestUpdate=null,e=0},printMetrics(){"=".repeat(50),`${t.totalUpdates}`,`${t.averageUpdateTime.toFixed(3)}`,t.slowestUpdate&&`${t.slowestUpdate.signalId}${t.slowestUpdate.duration.toFixed(3)}`,t.updatesBySignal.forEach((o,s)=>{`${s}${o}`}),"=".repeat(50)+""}}}function Sr(t){return{name:"validation",version:"1.0.0",onRegister(){},onBeforeUpdate(e){let n=e.signal.label;if(n&&t[n]&&!t[n](e.newValue)){console.error(`[Validation] \u274C Invalid value for signal "${n}":`,e.newValue);return}return e.newValue},onUnregister(){}}}var J,qe,dr,Te,Ke=ln(()=>{"use strict";J=[],qe=new Map,dr=0,Te=!0});async function Jr(){return new Promise(t=>{kt?Un.push(()=>t()):(kt=!0,t())})}function Xr(){let t=Un.shift();t?t():kt=!1}async function Be(t){await Jr();try{return await t()}finally{Xr()}}function Yr(t,e){let n=()=>I.get(t);return{name:e.name,version:e.version,onRegister(){if(e.onRegister)try{e.onRegister()}catch(r){console.error(`[PluginManager] Error in "${t}" onRegister:`,r);let o=n();o&&o.metadata.errorCount++}},onUnregister(){if(e.onUnregister)try{e.onUnregister()}catch(r){console.error(`[PluginManager] Error in "${t}" onUnregister:`,r);let o=n();o&&o.metadata.errorCount++}},onSignalCreate(r,o){let s=n();if(s?.enabled&&e.onSignalCreate)try{e.onSignalCreate(r,o)}catch(i){console.error(`[PluginManager] Error in "${t}" onSignalCreate:`,i),s.metadata.errorCount++}},onBeforeUpdate(r){let o=n();if(!o?.enabled)return r.newValue;if(e.onBeforeUpdate)try{return e.onBeforeUpdate(r)}catch(s){return console.error(`[PluginManager] Error in "${t}" onBeforeUpdate:`,s),o.metadata.errorCount++,r.newValue}return r.newValue},onSignalUpdate(r){let o=n();if(o?.enabled&&e.onSignalUpdate)try{e.onSignalUpdate(r)}catch(s){console.error(`[PluginManager] Error in "${t}" onSignalUpdate:`,s),o.metadata.errorCount++}},onSignalDestroy(r){let o=n();if(o?.enabled&&e.onSignalDestroy)try{e.onSignalDestroy(r)}catch(s){console.error(`[PluginManager] Error in "${t}" onSignalDestroy:`,s),o.metadata.errorCount++}}}}async function Qr(t,e,n={}){await Be(()=>{if(I.has(t))throw new Error(`[PluginManager] Plugin "${t}" is already registered`);let r=n.enabled!==!1,o=Date.now(),s={plugin:e,enabled:r,registeredAt:o,enabledAt:r?o:null,disabledAt:r?null:o,metadata:{enableCount:r?1:0,disableCount:r?0:1,errorCount:0}};I.set(t,s);let i=Yr(t,e);dt(i),`${t}`})}async function Zr(t){return Be(()=>{let e=I.get(t);return e?e.enabled?(`${t}`,!1):(e.enabled=!0,e.enabledAt=Date.now(),e.metadata.enableCount++,`${t}`,!0):(`${t}`,!1)})}async function eo(t){return Be(()=>{let e=I.get(t);return e?e.enabled?(e.enabled=!1,e.disabledAt=Date.now(),e.metadata.disableCount++,`${t}`,!0):(`${t}`,!1):(`${t}`,!1)})}async function to(t){return Be(()=>{let e=I.get(t);return e?(We(e.plugin.name),I.delete(t),`${t}`,!0):(`${t}`,!1)})}function no(t){return I.get(t)?.plugin}function ro(t){return I.get(t)?.enabled??!1}function oo(){return Array.from(I.entries()).map(([t,e])=>({name:t,plugin:e.plugin,enabled:e.enabled,registeredAt:e.registeredAt,enabledAt:e.enabledAt,disabledAt:e.disabledAt,metadata:{...e.metadata}}))}function $n(){let t=0,e=0,n=0;for(let r of I.values())r.enabled?t++:e++,n+=r.metadata.errorCount;return{total:I.size,enabled:t,disabled:e,totalErrors:n}}async function so(){await Be(()=>{let t=Array.from(I.keys());for(let e of t){let n=I.get(e);n&&We(n.plugin.name)}I.clear(),`${t.length}`})}function io(){"=".repeat(60);let t=$n();if(`${t.total}`,`${t.enabled}`,`${t.disabled}`,`${t.totalErrors}`,I.size>0)for(let[e,n]of I.entries()){let r=n.enabled?"\u2705 Enabled":"\u23F8\uFE0F Disabled",o=n.plugin.version?` v${n.plugin.version}`:"",s=n.metadata.errorCount>0?` (${n.metadata.errorCount} errors)`:"";`${r}${e}${o}${s}`}"=".repeat(60)+""}var I,kt,Un,Dt,_t,Fn=ln(()=>{"use strict";Ke();I=new Map,kt=!1,Un=[];Dt=class{constructor(e={}){this.verbose=e.verbose??!1,this.logCreates=e.logCreates??!0,this.logUpdates=e.logUpdates??!0,this.logDestroys=e.logDestroys??!0,this.startTime=Date.now()}getElapsedTime(){return`+${Date.now()-this.startTime}ms`}formatTimestamp(e){return new Date(e).toISOString()}getPlugin(){return{name:"logger",version:"2.0.0",onRegister:()=>{`${this.formatTimestamp(Date.now())}`,this.startTime=Date.now()},onSignalCreate:(e,n)=>{if(!this.logCreates)return;let r=e.label||e.id;`${this.getElapsedTime()}${e.type}${r}`,this.verbose?this.formatTimestamp(e.createdAt):`${JSON.stringify(n)}`},onSignalUpdate:e=>{if(!this.logUpdates)return;let n=e.signal.label||e.signal.id,r=e.source?`[${e.source}]`:"";`${this.getElapsedTime()}${e.signal.type}${n}${r}`,this.verbose?this.formatTimestamp(e.timestamp):`${JSON.stringify(e.oldValue)}${JSON.stringify(e.newValue)}`},onSignalDestroy:e=>{if(!this.logDestroys)return;let n=e.label||e.id;`${this.getElapsedTime()}${e.type}${n}`},onUnregister:()=>{`${this.getElapsedTime()}`}}}},_t=class{constructor(e={}){this.history=[];this.future=[];this.snapshots=new Map;this.maxHistory=e.maxHistory??50}getPlugin(){return{name:"time-travel",version:"2.0.0",onRegister:()=>{`${this.maxHistory}`},onSignalUpdate:e=>{this.history.push({...e}),this.future=[],this.history.length>this.maxHistory&&this.history.shift()},onUnregister:()=>{`${this.history.length}`,this.clear()}}}undo(){if(this.history.length===0)return!1;let e=this.history.pop();return this.future.push(e),`${e.signal.label||e.signal.id}${JSON.stringify(e.newValue)}${JSON.stringify(e.oldValue)}`,!0}redo(){if(this.future.length===0)return!1;let e=this.future.pop();return this.history.push(e),`${e.signal.label||e.signal.id}${JSON.stringify(e.oldValue)}${JSON.stringify(e.newValue)}`,!0}getHistory(){return this.history.map(e=>({...e}))}getHistoryForSignal(e){return this.history.filter(n=>n.signal.id===e).map(n=>({...n}))}createSnapshot(e){this.snapshots.set(e,[...this.history]),`${e}${this.history.length}`}restoreSnapshot(e){let n=this.snapshots.get(e);return n?(this.history=[...n],this.future=[],`${e}`,!0):(`${e}`,!1)}listSnapshots(){return Array.from(this.snapshots.keys())}clear(){this.history=[],this.future=[]}getStats(){return{historySize:this.history.length,futureSize:this.future.length,snapshotCount:this.snapshots.size,maxHistory:this.maxHistory}}printHistory(e=10){"=".repeat(60);let n=this.getStats();`${n.historySize}${n.maxHistory}`,`${n.futureSize}`,`${n.snapshotCount}`,this.history.length>0&&(`${Math.min(e,this.history.length)}`,this.history.slice(-e).forEach((o,s)=>{let i=o.signal.label||o.signal.id,a=new Date(o.timestamp).toISOString();s+1,`${a}${i}${JSON.stringify(o.oldValue)}${JSON.stringify(o.newValue)}`})),"=".repeat(60)+""}}});Ke();var de=1,gt=2,ut=4,pt=8,gn=16,pn=1e4,fn=new Array(pn),Xe=0;function Tr(t){Xe<pn&&(t.value=void 0,t.subscribers=null,t.listeners=null,t.dependencies=null,t.computeFn=null,t.flags=0,fn[Xe++]=t)}var Je=new WeakMap,ft=new Map;function mn(t){return ft.get(t)}var ht=1e4,yn=new Array(ht),xe=0,De=0,mt=!1;function xr(t){if(t.flags&gt)return;let e=(De+1)%ht;e===xe&&(console.error("[SignalForge] Batch queue overflow \u2192 forcing flush"),yt()),t.flags|=gt,yn[De]=t,De=e,mt||(mt=!0,queueMicrotask(yt))}function yt(){for(mt=!1;xe!==De;){let t=yn[xe];xe=(xe+1)%ht,t.flags&=~gt,t.flags&de&&_e(t)}}var hn=new Array(100),bn=0,W=null;function Pr(t){hn[bn++]=W,W=t}function Cr(){W=hn[--bn]}var wr=function(){return this._node.value},Er=function(t){this._node.subscribers||(this._node.subscribers=new Set),this._node.subscribers.add(t)},Rr=function(t){this._node.subscribers&&this._node.subscribers.delete(t)};function bt(t,e=null){let n=Xe>0?fn[--Xe]:{value:void 0,subscribers:null,listeners:null,dependencies:null,computeFn:null,flags:0};return n.value=t,n.computeFn=e,n.flags=e?gn|de:0,e&&_e(n),n}function vn(t,e){return W?(W!==t&&(Sn(t,W),kr(W,e)),t.flags&de&&t.computeFn&&_e(t),t.value):(t.flags&de&&t.computeFn&&_e(t),t.value)}function Lr(t,e,n){if(t.flags&gn)throw new Error("Cannot set computed signal");if(typeof n=="function"&&(n=n(t.value)),Object.is(n,t.value))return;let r=t.value;t.value=n;let o=Je.get(e);o&&dn(o,r,n,"set"),xn(t)}function Sn(t,e){t.subscribers||(t.subscribers=new Set),t.subscribers.add(e)}function Mr(t,e){t.subscribers&&t.subscribers.delete(e)}function kr(t,e){t.dependencies||(t.dependencies=new Set),t.dependencies.has(e)||(t.dependencies.add(e),Sn(e._node,t))}function Tn(t){if(t.dependencies){for(let e of t.dependencies)Mr(e._node,t);t.dependencies.clear()}}function vt(t){if(!(t.flags&de)&&(t.flags|=de,xr(t),t.subscribers))for(let e of t.subscribers)vt(e)}function _e(t){if(t.computeFn&&!(t.flags&ut)){t.flags|=ut,Tn(t),Pr(t);try{let e=t.computeFn();t.flags&=~de,t.flags&=~ut,Object.is(e,t.value)||(t.value=e,xn(t))}finally{Cr()}}}function xn(t){if(t.subscribers)for(let e of t.subscribers)vt(e);if(t.flags&pt&&t.listeners)for(let e of t.listeners)e(t.value)}function Pn(t,e){return t.listeners||(t.listeners=new Set),t.listeners.add(e),t.flags|=pt,()=>{t.listeners.delete(e),t.listeners.size===0&&(t.flags&=~pt)}}function St(t){Tn(t),t.subscribers&&t.subscribers.clear(),t.listeners&&t.listeners.clear(),Tr(t)}function F(t){let e=bt(t,null),n={get:()=>vn(e,n),set:o=>Lr(e,n,o),subscribe:o=>Pn(e,o),destroy:()=>{let o=Je.get(n);o&&(un(o),ft.delete(o),Je.delete(n)),St(e)},_node:e,_peek:wr,_addSubscriber:Er,_removeSubscriber:Rr},r=cn("signal",t);return Je.set(n,r.id),ft.set(r.id,n),n}function te(t){let e,n=W;W=null;try{e=t()}finally{W=n}let r=bt(e,t),o={get:()=>vn(r,o),set:()=>{throw new Error("Cannot set a computed signal")},subscribe:s=>Pn(r,s),destroy:()=>St(r),_node:r,_peek:()=>r.value,_addSubscriber:s=>{r.subscribers||(r.subscribers=new Set),r.subscribers.add(s)},_removeSubscriber:s=>{r.subscribers&&r.subscribers.delete(s)},_markDirty:()=>vt(r),_recompute:()=>_e(r)};return o}function oe(t){let e=bt(void 0,t);return()=>St(e)}function Tt(t){let e=t();return Cn(),e}function Cn(){xe!==De&&yt()}function Dr(t){let e=W;W=null;try{return t()}finally{W=e}}var _r=Cn;var X=!1,Ae=null,En=0,ue=new Map,se=[],Ye=new Map,Ie=new Map,ne={maxSamplesPerSignal:100,maxBatchRecords:50,autoComputeStats:!1,emitEvents:!0};function xt(t){X||(ne={...ne,...t},X=!0,Ae=performance.now())}function Pt(){X&&(X=!1)}function ge(){return X}function Ct(){ue.clear(),se.length=0,Ye.clear(),Ie.clear(),Ae=X?performance.now():null,En=0}function Ar(t){ne={...ne,...t}}function Ir(t,e){X&&Ye.set(t,{startTime:performance.now(),subscriberCount:e})}function Br(t,e,n){if(!X)return;let r=Ye.get(t);if(!r)return;let o=performance.now(),s=o-r.startTime,i={signalId:t,type:e,startTime:r.startTime,endTime:o,latency:s,subscriberCount:r.subscriberCount,skipped:n},a=ue.get(t);a||(a=[],ue.set(t,a)),a.push(i),a.length>ne.maxSamplesPerSignal&&a.shift(),Ye.delete(t),ne.emitEvents}function wt(t){if(!X)return-1;let e=++En;return Ie.set(e,{startTime:performance.now(),operationCount:0,affectedSignals:new Set,depth:t}),e}function Et(t,e){if(!X||t===-1)return;let n=Ie.get(t);n&&(n.operationCount++,n.affectedSignals.add(e))}function Rt(t){if(!X||t===-1)return;let e=Ie.get(t);if(!e)return;let n=performance.now(),r=n-e.startTime,o={batchId:t,startTime:e.startTime,endTime:n,duration:r,operationCount:e.operationCount,affectedSignals:Array.from(e.affectedSignals),depth:e.depth};se.push(o),se.length>ne.maxBatchRecords&&se.shift(),Ie.delete(t),ne.emitEvents}function Pe(){let t=performance.now(),e=Ae?t-Ae:0,n=new Map,r=0;for(let[s,i]of ue.entries()){if(i.length===0)continue;let a=Rn(s,i);n.set(s,a),r+=i.length}let o=Ln(se);return{enabled:X,startedAt:Ae,duration:e,signalStats:n,batchRecords:[...se],batchStats:o,totalSamples:r,totalSignals:ue.size}}function Ur(t){let e=ue.get(t);return!e||e.length===0?null:Rn(t,e)}function $r(){return Ln(se)}function Fr(t){return ue.get(t)||[]}function Or(){return[...se]}function Rn(t,e){if(e.length===0)return{signalId:t,type:"signal",sampleCount:0,min:0,max:0,mean:0,median:0,p95:0,p99:0,stdDev:0,avgSubscribers:0,skippedCount:0};let n=e[0].type,r=e.map(E=>E.latency),o=[...r].sort((E,k)=>E-k),s=o[0],i=o[o.length-1],l=r.reduce((E,k)=>E+k,0)/r.length,c=Math.floor(o.length/2),p=o.length%2===0?(o[c-1]+o[c])/2:o[c],S=wn(o,.95),x=wn(o,.99),A=r.map(E=>Math.pow(E-l,2)).reduce((E,k)=>E+k,0)/r.length,M=Math.sqrt(A),$=e.reduce((E,k)=>E+k.subscriberCount,0)/e.length,ee=e.filter(E=>E.skipped).length;return{signalId:t,type:n,sampleCount:e.length,min:s,max:i,mean:l,median:p,p95:S,p99:x,stdDev:M,avgSubscribers:$,skippedCount:ee}}function Ln(t){if(t.length===0)return{totalBatches:0,avgDuration:0,minDuration:0,maxDuration:0,avgOperationsPerBatch:0,totalOperations:0};let e=t.map(c=>c.duration),n=t.map(c=>c.operationCount),r=t.length,o=e.reduce((c,p)=>c+p,0)/r,s=Math.min(...e),i=Math.max(...e),a=n.reduce((c,p)=>c+p,0),l=a/r;return{totalBatches:r,avgDuration:o,minDuration:s,maxDuration:i,avgOperationsPerBatch:l,totalOperations:a}}function wn(t,e){if(t.length===0)return 0;let n=e*(t.length-1),r=Math.floor(n),o=Math.ceil(n),s=n-r;return r===o?t[r]:t[r]*(1-s)+t[o]*s}var Nr="[SignalForge]",Lt={BATCH_MISMATCH:"endBatch called without matching startBatch",MAX_BATCH_DEPTH:"Maximum batch depth (1000) exceeded",MAX_DEPENDENCY_DEPTH:"Maximum dependency depth (100) exceeded - possible circular dependency",INVALID_SIGNAL:"Invalid signal provided",PLUGIN_NOT_FOUND:"Plugin not found",PLUGIN_ALREADY_REGISTERED:"Plugin with this name is already registered",STORAGE_NOT_AVAILABLE:"Storage backend not available",DEVTOOLS_CONNECTION_FAILED:"Failed to connect to DevTools"};var Mn="3.0.0";function kn(t,e,n){return Math.min(Math.max(t,e),n)}function Dn(t){return t===void 0?100:kn(t,10,1e4)}function _n(t){return t===void 0?1e3:kn(t,100,1e4)}function An(t,e=100){return t.length<=e?t:t.substring(0,e-3)+"..."}function Mt(t){return`${Nr} ${t}`}var K=0,Ce=-1,pe=new Set,Qe=!1;function Bn(){Qe||(Qe=!0,typeof queueMicrotask<"u"?queueMicrotask(In):Promise.resolve().then(In))}function In(){if(Qe=!1,K>0)return;let t=Array.from(pe);pe.clear();for(let e of t)try{e()}catch(n){console.error("Error in batch callback:",n)}}function zr(){if(K>=1e3)throw new Error(Mt(Lt.MAX_BATCH_DEPTH));K++,K===1&&ge()&&(Ce=wt(K))}function Hr(){if(K<=0)throw new Error(Mt(Lt.BATCH_MISMATCH));K--,K===0&&ge()&&Ce!==-1&&(Rt(Ce),Ce=-1),K===0&&pe.size>0&&Bn()}function Gr(t,e){pe.add(t),K>0&&ge()&&Ce!==-1&&e&&Et(Ce,e),K===0&&Bn()}function jr(){Qe=!1;let t=Array.from(pe);pe.clear();for(let e of t)try{e()}catch(n){console.error("Error in batch callback:",n)}}function qr(){return K}function Wr(){return pe.size}function Kr(){return K>0}Ke();Fn();import{useState as At,useEffect as On}from"react";function ao(){if(typeof At!="function"||typeof On!="function")throw new Error(`[SignalForge] React hooks unavailable. Possible duplicate React instance or invalid bundler resolution. Troubleshooting: 1. Ensure only one react copy: node_modules/react (no nested copy under library). 2. Clear Metro cache: npx react-native start --reset-cache. 3. Verify metro.config.js extraNodeModules maps react to example app node_modules.`)}ao();function Nn(t){let[e,n]=At(()=>t.get());return On(()=>(n(t.get()),t.subscribe(()=>n(t.get()))),[t]),e}function lo(t){let[e]=At(()=>{let r=typeof t=="function"?t():t;return F(r)});return[Nn(e),e.set.bind(e)]}import{useEffect as co,useRef as It}from"react";var Ze=new WeakMap;function uo(t,e=[]){let n=It({}),r=It(null),o=It(null);co(()=>{let s=()=>{if(!Ze.get(n.current)){Ze.set(n.current,!0);try{r.current&&(r.current(),r.current=null);let i=t();typeof i=="function"&&(r.current=i)}finally{Ze.set(n.current,!1)}}};return o.current=oe(s),()=>{r.current&&r.current(),o.current&&o.current(),Ze.delete(n.current)}},e)}function rt(){let t=typeof global<"u"?global:void 0,e=typeof window<"u"?window:void 0;return typeof navigator<"u"&&navigator.product==="ReactNative"||e?.navigator?.product==="ReactNative"||t?.HermesInternal||t?.__fbBatchedBridgeConfig||t?.nativeModuleProxy||t?.__turboModuleProxy?"react-native":e?.localStorage||t?.localStorage?"web":"node"}function ot(t,e=!1){let n=new WeakSet;try{return JSON.stringify(t,(r,o)=>{if(o===void 0)return"__undefined__";if(o===null)return null;if(typeof o=="function")return e&&`${r}`,"__function__";if(o instanceof Date)return{__type__:"Date",value:o.toISOString()};if(o instanceof RegExp)return{__type__:"RegExp",value:o.toString()};if(typeof o=="object"&&o!==null){if(n.has(o))return e&&`${r}`,"__circular__";n.add(o)}return o})}catch(r){e&&console.error("[StorageAdapter] Serialization error:",r);try{return JSON.stringify(t)}catch{return"{}"}}}function st(t,e=!1){try{return JSON.parse(t,(n,r)=>{if(r!=="__undefined__"&&r!=="__function__"){if(r==="__circular__")return null;if(r&&typeof r=="object"){if(r.__type__==="Date")return new Date(r.value);if(r.__type__==="RegExp"){let o=r.value.match(/^\/(.+)\/([gimuy]*)$/);if(o)return new RegExp(o[1],o[2])}}return r}})}catch(n){return e&&console.error("[StorageAdapter] Deserialization error:",n),null}}var et=class{constructor(e={}){this.prefix=e.prefix||"signalforge_",this.devMode=e.devMode??$t,this.serialize=e.serialize||(n=>ot(n,this.devMode)),this.deserialize=e.deserialize||(n=>st(n,this.devMode))}getKey(e){return`${this.prefix}${e}`}async load(e){try{let n=localStorage.getItem(this.getKey(e));return n===null?null:this.deserialize(n)}catch(n){return this.devMode&&console.error(`[StorageAdapter] Failed to load "${e}":`,n),null}}async save(e,n){try{let r=this.serialize(n);localStorage.setItem(this.getKey(e),r)}catch(r){throw this.devMode&&console.error(`[StorageAdapter] Failed to save "${e}":`,r),r}}async clear(e){try{localStorage.removeItem(this.getKey(e))}catch(n){throw this.devMode&&console.error(`[StorageAdapter] Failed to clear "${e}":`,n),n}}isAvailable(){try{let e="__storage_test__";return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch{return!1}}async getAllKeys(){try{let e=[];for(let n=0;n<localStorage.length;n++){let r=localStorage.key(n);r&&r.startsWith(this.prefix)&&e.push(r.slice(this.prefix.length))}return e}catch(e){return this.devMode&&console.error("[StorageAdapter] Failed to get all keys:",e),[]}}async clearAll(){try{let e=await this.getAllKeys();for(let n of e)await this.clear(n)}catch(e){throw this.devMode&&console.error("[StorageAdapter] Failed to clear all:",e),e}}},tt=class{constructor(e={}){this.prefix=e.prefix||"signalforge_",this.devMode=e.devMode??$t,this.serialize=e.serialize||(n=>ot(n,this.devMode)),this.deserialize=e.deserialize||(n=>st(n,this.devMode));try{this.AsyncStorage=je("@react-native-async-storage/async-storage").default}catch{try{this.AsyncStorage=je("react-native").AsyncStorage}catch{this.devMode&&console.error("[StorageAdapter] AsyncStorage not found. Install @react-native-async-storage/async-storage"),this.AsyncStorage=null}}}getKey(e){return`${this.prefix}${e}`}async load(e){if(!this.AsyncStorage)return this.devMode,null;try{let n=await this.AsyncStorage.getItem(this.getKey(e));return n===null?null:this.deserialize(n)}catch(n){return this.devMode&&console.error(`[StorageAdapter] Failed to load "${e}":`,n),null}}async save(e,n){if(!this.AsyncStorage){this.devMode;return}try{let r=this.serialize(n);await this.AsyncStorage.setItem(this.getKey(e),r)}catch(r){throw this.devMode&&console.error(`[StorageAdapter] Failed to save "${e}":`,r),r}}async clear(e){if(!this.AsyncStorage){this.devMode;return}try{await this.AsyncStorage.removeItem(this.getKey(e))}catch(n){throw this.devMode&&console.error(`[StorageAdapter] Failed to clear "${e}":`,n),n}}isAvailable(){return this.AsyncStorage!==null}async getAllKeys(){if(!this.AsyncStorage)return[];try{return(await this.AsyncStorage.getAllKeys()).filter(n=>n.startsWith(this.prefix)).map(n=>n.slice(this.prefix.length))}catch(e){return this.devMode&&console.error("[StorageAdapter] Failed to get all keys:",e),[]}}async clearAll(){if(this.AsyncStorage)try{let n=(await this.getAllKeys()).map(r=>this.getKey(r));await this.AsyncStorage.multiRemove(n)}catch(e){throw this.devMode&&console.error("[StorageAdapter] Failed to clear all:",e),e}}},nt=class{constructor(e={}){this.storage=new Map;this.prefix=e.prefix||"signalforge_",this.devMode=e.devMode??$t,this.devMode}getKey(e){return`${this.prefix}${e}`}async load(e){let n=this.storage.get(this.getKey(e));return n!==void 0?n:null}async save(e,n){let r=JSON.parse(JSON.stringify(n));this.storage.set(this.getKey(e),r)}async clear(e){this.storage.delete(this.getKey(e))}isAvailable(){return!0}async getAllKeys(){let e=[];for(let n of this.storage.keys())n.startsWith(this.prefix)&&e.push(n.slice(this.prefix.length));return e}async clearAll(){let e=await this.getAllKeys();for(let n of e)this.storage.delete(this.getKey(n))}},fe=null;function Bt(t={}){if(fe)return fe;switch(rt()){case"web":fe=new et(t);break;case"react-native":fe=new tt(t);break;case"node":case"unknown":default:fe=new nt(t);break}return fe}function Vn(){fe=null}function zn(t=rt(),e={}){switch(t){case"web":return new et(e);case"react-native":return new tt(e);case"node":case"unknown":default:return new nt(e)}}function Ut(t,e={}){let n=e.adapter||Bt(),r=e.key||`signal_${Math.random().toString(36).slice(2)}`,o=e.serialize||(l=>l),s=e.deserialize||(l=>l);n.load(r).then(l=>{if(l!==null)try{let c=s(l);t.set(c)}catch(c){e.onError&&e.onError(c)}}).catch(l=>{e.onError&&e.onError(l)});let i,a=oe(()=>{let l=t.get(),c=()=>{try{let p=o(l);n.save(r,p).catch(S=>{e.onError&&e.onError(S)})}catch(p){e.onError&&e.onError(p)}};e.debounce?(i!==void 0&&clearTimeout(i),i=setTimeout(c,e.debounce)):c()});return()=>{a(),i!==void 0&&clearTimeout(i)}}function Hn(t,e,n={}){let r=F(e);return Ut(r,{...n,key:t}),r}var $t=typeof globalThis.__DEV__<"u"?globalThis.__DEV__:process.env.NODE_ENV!=="production";var _=[];function Y(){return typeof performance<"u"&&performance.now?performance.now():Date.now()}function Nt(t){console.time("SignalForge: Sequential Updates");let e=Y(),n=F(0),r=te(()=>n.get()*2),o=0;for(let p=0;p<t;p++)n.set(p),o=r.get();let s=Y();console.timeEnd("SignalForge: Sequential Updates");let i=s-e,a=i/t,l=t/i*1e3,c={name:"SignalForge Sequential Updates",iterations:t,totalTime:i,averageTime:a,opsPerSecond:l,metadata:{lastValue:o}};return _.push(c),c}function Vt(t){console.time("SignalForge: Batched Updates");let e=Y(),n=Array.from({length:t},()=>F(0)),r=te(()=>n.reduce((p,S)=>p+S.get(),0));Tt(()=>{for(let p=0;p<t;p++)n[p].set(p)});let o=r.get(),s=Y();console.timeEnd("SignalForge: Batched Updates");let i=s-e,a=i/t,l=t/i*1e3,c={name:"SignalForge Batched Updates",iterations:t,totalTime:i,averageTime:a,opsPerSecond:l,metadata:{computedValue:o}};return _.push(c),c}var Ft=class{constructor(e){this.listeners=new Set;this.state=e}getState(){return this.state}dispatch(e){e.type==="INCREMENT"?this.state={count:this.state.count+1}:e.type==="SET"&&(this.state={count:e.payload}),this.listeners.forEach(n=>n())}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};function zt(t=1e4){console.time("Redux-like: Sequential Updates");let e=Y(),n=new Ft({count:0}),r=0;n.subscribe(()=>{r=n.getState().count*2});for(let c=0;c<t;c++)n.dispatch({type:"SET",payload:c});let o=Y();console.timeEnd("Redux-like: Sequential Updates");let s=o-e,i=s/t,a=t/s*1e3,l={name:"Redux-like Sequential Updates",iterations:t,totalTime:s,averageTime:i,opsPerSecond:a,metadata:{lastValue:r}};return _.push(l),l}var Ot=class{constructor(e){this.listeners=new Set;this.state=e}getState(){return this.state}setState(e){this.state={...this.state,...e},this.listeners.forEach(n=>n())}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};function Ht(t=1e4){console.time("Zustand-like: Sequential Updates");let e=Y(),n=new Ot({count:0}),r=0;n.subscribe(()=>{r=n.getState().count*2});for(let c=0;c<t;c++)n.setState({count:c});let o=Y();console.timeEnd("Zustand-like: Sequential Updates");let s=o-e,i=s/t,a=t/s*1e3,l={name:"Zustand-like Sequential Updates",iterations:t,totalTime:s,averageTime:i,opsPerSecond:a,metadata:{lastValue:r}};return _.push(l),l}function Gt(t){let e=typeof performance<"u"&&performance.memory,n=e?performance.memory.usedJSHeapSize:0,r=Y(),o=Array.from({length:t},(S,x)=>F(x));typeof global<"u"&&global.gc&&global.gc();let s=Y(),i=e?performance.memory.usedJSHeapSize:0,a=s-r,l=i-n,c=l/t,p={name:"Memory Usage",iterations:t,totalTime:a,averageTime:a/t,opsPerSecond:t/a*1e3,metadata:{memoryUsedBytes:l,memoryUsedKB:l/1024,memoryUsedMB:l/(1024*1024),bytesPerSignal:c,hasMemoryAPI:e,signalCount:o.length}};return _.push(p),p}function Gn(t=1e4){return _.length=0,Nt(t),Vt(Math.floor(t/10)),zt(t),Ht(t),Gt(1e3),_}function jn(){if(_.length===0)return;"=".repeat(100),""+"Benchmark Name".padEnd(35)+"Iterations".padEnd(12)+"Total (ms)".padEnd(12)+"Avg (ms)".padEnd(12)+"Ops/sec".padEnd(15),"=".repeat(100);for(let s of _)""+s.name.padEnd(35)+s.iterations.toLocaleString().padEnd(12)+s.totalTime.toFixed(2).padEnd(12)+s.averageTime.toFixed(4).padEnd(12)+s.opsPerSecond.toLocaleString(void 0,{maximumFractionDigits:0}).padEnd(15);"=".repeat(100);let t=_.find(s=>s.name==="SignalForge Sequential Updates"),e=_.find(s=>s.name==="Redux-like Sequential Updates"),n=_.find(s=>s.name==="Zustand-like Sequential Updates");if(t&&e){let s=e.totalTime/t.totalTime;`${s.toFixed(2)}`,s>1}if(t&&n){let s=n.totalTime/t.totalTime;`${s.toFixed(2)}`,s>1}let r=_.find(s=>s.name==="SignalForge Batched Updates");t&&r&&`${(t.averageTime/r.averageTime).toFixed(2)}`;let o=_.find(s=>s.name==="Memory Usage");o&&o.metadata?.hasMemoryAPI&&(`${o.metadata.memoryUsedKB.toFixed(2)}${o.iterations}`,`${o.metadata.bytesPerSignal.toFixed(0)}`)}function qn(){return[..._]}function Wn(){_.length=0}function Kn(){return JSON.stringify(_,null,2)}function Jn(t,e,n=1e3){console.time(t);let r=Y();for(let c=0;c<n;c++)e();let o=Y();console.timeEnd(t);let s=o-r,i=s/n,a=n/s*1e3,l={name:t,iterations:n,totalTime:s,averageTime:i,opsPerSecond:a};return _.push(l),l}function go(t,e){return te(()=>{let n=t.map(r=>r.get());return e(...n)})}function po(t){return te(()=>t.map(e=>e.get()))}function fo(t,e){return te(()=>e(t.get()))}function mo(t,e,n){return te(()=>{let r=t.get();return e(r)?r:n})}function yo(t,e=Object.is){let n=t._peek?t._peek():t.get();return te(()=>{let r=t.get();return e(r,n)||(n=r),n})}function ho(t){let e=F({status:"pending",data:void 0,error:void 0});return t().then(n=>{e.set({status:"success",data:n,error:void 0})}).catch(n=>{e.set({status:"error",data:void 0,error:n})}),e}function bo(t,e){let n=F(t._peek?t._peek():t.get()),r;return oe(()=>{let o=t.get();r!==void 0&&clearTimeout(r),r=setTimeout(()=>{n.set(o)},e)}),n}function vo(t,e){let n=F(t._peek?t._peek():t.get()),r=0,o,s;return oe(()=>{let i=t.get(),a=Date.now(),l=a-r;l>=e?(n.set(i),r=a,o=void 0):(o=i,s===void 0&&(s=setTimeout(()=>{o!==void 0&&(n.set(o),r=Date.now(),o=void 0),s=void 0},e-l)))}),n}function So(t=[]){let e=F(t);return{...e,push(...n){e.set(r=>[...r,...n])},pop(){let n;return e.set(r=>{let o=[...r];return n=o.pop(),o}),n},filter(n){e.set(r=>r.filter(n))},map(n){return e.get().map(n)},find(n){return e.get().find(n)},remove(n){e.set(r=>r.filter(o=>o!==n))},clear(){e.set([])},get length(){return e.get().length}}}function To(t={}){let e=F(t);return{...e,setKey(n,r){e.set(o=>({...o,[n]:r}))},deleteKey(n){e.set(r=>{let o={...r};return delete o[n],o})},hasKey(n){return n in e.get()},getKey(n){return e.get()[n]},keys(){return Object.keys(e.get())},values(){return Object.values(e.get())},entries(){return Object.entries(e.get())},clear(){e.set({})}}}function xo(t,e){let n=0,r=0,o=0,s=0;return{get(){let i=performance.now(),a=t.get(),l=performance.now()-i;return n++,o+=l,n%100===0&&`${e}${n}${(o/n).toFixed(3)}`,a},set(i){let a=performance.now();t.set(i);let l=performance.now()-a;r++,s+=l,`${e}${r}${l.toFixed(3)}`},subscribe:t.subscribe.bind(t),destroy:t.destroy.bind(t),_node:t._node,_addSubscriber:t._addSubscriber?t._addSubscriber.bind(t):void 0,_removeSubscriber:t._removeSubscriber?t._removeSubscriber.bind(t):void 0,_peek:t._peek?t._peek.bind(t):void 0}}var it=!1,O={enabled:!1,trackPerformance:!0,logToConsole:!1,maxPerformanceSamples:1e3,flipperEnabled:!1},N=new Map,ae=new WeakMap,me=[],Po=0,ie=null;function Co(t={}){it=!0,Object.assign(O,t),O.enabled=!0,O.logToConsole,O.flipperEnabled&&Bo()}function wo(){it=!1,O.enabled=!1,ie&&Uo()}function V(){return it&&O.enabled}function Eo(t,e,n){if(!V())return"";let r=`${e}_${++Po}`,o;if(typeof Error<"u")try{throw new Error}catch(i){o=i.stack?.split(` `).slice(2,6).join(` `)}let s={id:r,type:e,value:we(n),subscriberCount:0,dependencies:[],subscribers:[],createdAt:Date.now(),updatedAt:Date.now(),updateCount:0,creationStack:o};return N.set(r,s),ae.set(t,r),O.logToConsole&&`${e}${r}`,qt("signalRegistered",s),r}function Ro(t){if(!V())return;let e=ae.get(t);e&&(N.delete(e),ae.delete(t),O.logToConsole&&`${e}`,qt("signalUnregistered",{id:e}))}function Lo(t,e,n){if(!V()){e();return}let r=ae.get(t);if(!r){e();return}let o=N.get(r);if(!o){e();return}let s=performance.now(),i=!1,a;try{e(),a=t._peek?t._peek():t.get(),i=Object.is(n,a)}catch(l){throw console.error(`[SignalForge] Error updating signal "${r}"`,l),l}finally{let c=performance.now()-s;if(o.value=we(a),o.updatedAt=Date.now(),i||o.updateCount++,O.trackPerformance){let p={signalId:r,type:o.type,timestamp:s,duration:c,skipped:i,previousValue:we(n),newValue:we(a)};Fo(p),O.logToConsole&&c>16&&`${r}${c.toFixed(2)}`}qt("signalUpdated",{id:r,value:o.value,duration:c,skipped:i})}}function Mo(t,e){if(!V())return;let n=ae.get(t),r=ae.get(e);if(!n||!r)return;let o=N.get(n),s=N.get(r);!o||!s||(o.dependencies.includes(r)||o.dependencies.push(r),s.subscribers.includes(n)||s.subscribers.push(n),s.subscriberCount=s.subscribers.length)}function ko(t,e){if(!V())return;let n=ae.get(t),r=ae.get(e);if(!n||!r)return;let o=N.get(n),s=N.get(r);!o||!s||(o.dependencies=o.dependencies.filter(i=>i!==r),s.subscribers=s.subscribers.filter(i=>i!==n),s.subscriberCount=s.subscribers.length)}function le(){return V()?Array.from(N.values()).sort((t,e)=>t.createdAt-e.createdAt):[]}function jt(t){if(V())return N.get(t)}function Do(t){return V()?N.get(t)?.dependencies||[]:[]}function _o(t){return V()?N.get(t)?.subscribers||[]:[]}function ce(){if(!V())return[];let t=[],e=new Map,n=(r,o=0)=>{let s=e.get(r);if(s!==void 0)return Math.max(s,o);e.set(r,o);let i=N.get(r);if(i)for(let a of i.subscribers)n(a,o+1);return o};for(let[r,o]of N)o.dependencies.length===0&&n(r,0);for(let[r,o]of N)t.push({id:r,type:o.type,dependencies:o.dependencies,subscribers:o.subscribers,depth:e.get(r)||0});return t.sort((r,o)=>r.depth-o.depth)}function Ao(t){return V()?Array.from(N.values()).filter(e=>e.type===t):[]}function Ee(t){if(!V())return[];let e=[...me];return t?e.slice(-t):e}function at(){if(!V())return{totalUpdates:0,totalDuration:0,averageDuration:0,slowestUpdate:null,updatesByType:{}};let t=0,e=null,n={signal:0,computed:0,effect:0};for(let s of me)s.skipped||(t+=s.duration,n[s.type]++,(!e||s.duration>e.duration)&&(e=s));let r=me.filter(s=>!s.skipped).length,o=r>0?t/r:0;return{totalUpdates:r,totalDuration:t,averageDuration:o,slowestUpdate:e,updatesByType:n}}function Io(){me.length=0}function Bo(){try{typeof global<"u"&&global.__FLIPPER__&&(ie=global.__FLIPPER__.addPlugin({getId:()=>"signalforge-inspector",onConnect:e=>{e.send("initialState",{signals:le(),graph:ce(),config:O}),e.receive("getSignals",()=>{e.send("signals",le())}),e.receive("getGraph",()=>{e.send("graph",ce())}),e.receive("getPerformance",()=>{e.send("performance",{metrics:Ee(100),summary:at()})})},onDisconnect:()=>{ie=null}}))}catch(t){}}function Uo(){if(ie){try{ie.disconnect()}catch(t){}ie=null}}function qt(t,e){if(ie&&O.flipperEnabled)try{ie.send(t,e)}catch{}}function $o(){if(typeof window>"u"||typeof document>"u")return{show:()=>{},hide:()=>{},destroy:()=>{}};let t=document.createElement("div");t.id="signalforge-devtools-overlay",t.style.cssText=` position: fixed; top: 0; right: 0; width: 400px; height: 100vh; background: rgba(0, 0, 0, 0.95); color: #fff; font-family: monospace; font-size: 12px; padding: 16px; overflow-y: auto; z-index: 999999; display: none; box-shadow: -2px 0 10px rgba(0, 0, 0, 0.5); `,document.body.appendChild(t);let e=()=>{let r=le(),o=at();t.innerHTML=` <h2 style="margin: 0 0 16px 0; color: #61dafb;">SignalForge DevTools</h2> <div style="margin-bottom: 16px;"> <h3 style="margin: 0 0 8px 0;">Performance</h3> <div>Total Updates: ${o.totalUpdates}</div> <div>Avg Duration: ${o.averageDuration.toFixed(2)}ms</div> <div>Total Time: ${o.totalDuration.toFixed(2)}ms</div> </div> <div style="margin-bottom: 16px;"> <h3 style="margin: 0 0 8px 0;">Signals (${r.length})</h3> ${r.map(s=>` <div style="margin-bottom: 8px; padding: 8px; background: rgba(255,255,255,0.1); border-radius: 4px;"> <div style="color: #61dafb;">${s.id}</div> <div style="color: #999; font-size: 10px;">${s.type}</div> <div>Value: ${JSON.stringify(s.value)}</div> <div style="font-size: 10px; color: #999;"> Deps: ${s.dependencies.length} | Subs: ${s.subscriberCount} | Updates: ${s.updateCount} </div> </div> `).join("")} </div> <button onclick="document.getElementById('signalforge-devtools-overlay').style.display='none'" style="padding: 8px 16px; background: #61dafb; color: #000; border: none; border-radius: 4px; cursor: pointer;" > Close </button> `},n;return{show:()=>{t.style.display="block",e(),n=setInterval(e,1e3)},hide:()=>{t.style.display="none",n&&clearInterval(n)},destroy:()=>{n&&clearInterval(n),t.remove()}}}function we(t){try{if(t===null||typeof t>"u"||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(typeof t=="function")return`[Function: ${t.name||"anonymous"}]`;if(t instanceof Date)return t.toISOString();if(Array.isArray(t))return t.slice(0,10).map(we);if(typeof t=="object"){let e=Object.keys(t).slice(0,10),n={};for(let r of e)n[r]=we(t[r]);return n}return String(t)}catch{return"[Unserializable]"}}function Fo(t){me.push(t),me.length>O.maxPerformanceSamples&&me.shift()}function Oo(){return{timestamp:Date.now(),config:{...O},signals:le(),graph:ce(),performance:{metrics:Ee(),summary:at()}}}function No(){if(!V())return;let t=ce();console.group("SignalForge Dependency Graph");for(let e of t){let n=" ".repeat(e.depth),r=e.dependencies.length>0?` \u2190 [${e.dependencies.join(", ")}]`:"",o=e.subscribers.length>0?` \u2192 [${e.subscribers.join(", ")}]`:"";`${n}${e.id}${e.type}${r}${o}`}console.groupEnd()}import{useEffect as Zn,useRef as Kt,useState as er,useCallback as $e}from"react";var Wt=class{constructor(){this.listeners=new Map;this.sequence=0}on(e,n){let r=e;return this.listeners.has(r)||this.listeners.set(r,new Set),this.listeners.get(r).add(n),()=>this.off(e,n)}off(e,n){let r=e,o=this.listeners.get(r);o&&(o.delete(n),o.size===0&&this.listeners.delete(r))}emit(e,n){let r={type:e,payload:n,timestamp:Date.now(),sequence:++this.sequence},o=this.listeners.get(e);if(o)for(let i of o)try{i(r)}catch(a){console.error(`[DevTools] Error in listener for ${e}:`,a)}let s=this.listeners.get("*");if(s)for(let i of s)try{i(r)}catch(a){console.error("[DevTools] Error in wildcard listener:",a)}}removeAllListeners(){this.listeners.clear(),this.sequence=0}getListenerCount(e){if(e)return this.listeners.get(e)?.size||0;let n=0;for(let r of this.listeners.values())n+=r.size;return n}},Xn=typeof process<"u"?process.env.NODE_ENV!=="production":!0,Ue={enabled:!1,trackPerformance:!0,logToConsole:!1,maxPerformanceSamples:1e3,slowUpdateThreshold:16,emitPerformanceWarnings:!0},Vo=new Map;var zo=new Wt;function Yn(t={}){Xn=!0,Object.assign(Ue,t),Ue.enabled=!0,Ue.logToConsole}function ye(){return Xn&&Ue.enabled}function Qn(){return ye()?Array.from(Vo.values()).sort((t,e)=>t.createdAt-e.createdAt):[]}function Re(t,e){return zo.on(t,e)}import{Fragment as Go,jsx as P,jsxs as R}from"react/jsx-runtime";var Jt=class{constructor(e,n){this.repulsionForce=3e3;this.attractionForce=.01;this.centerForce=.01;this.damping=.9;this.minDistance=50;this.nodes=new Map,this.edges=[],this.width=e,this.height=n}setGraph(e,n){this.nodes=e,this.edges=n}tick(){for(let e of this.nodes.values())e.fx=0,e.fy=0;this.applyRepulsion(),this.applyAttraction(),this.applyCenterForce(),this.updatePositions()}applyRepulsion(){let e=Array.from(this.nodes.values());for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++){let o=e[n],s=e[r],i=s.x-o.x,a=s.y-o.y,l=i*i+a*a,c=Math.sqrt(l)||1;if(c<this.minDistance){let p=this.repulsionForce/(this.minDistance*this.minDistance),S=i/c*p,x=a/c*p;o.fx-=S,o.fy-=x,s.fx+=S,s.fy+=x}else{let p=this.repulsionForce/l,S=i/c*p,x=a/c*p;o.fx-=S,o.fy-=x,s.fx+=S,s.fy+=x}}}applyAttraction(){for(let e of this.edges){let n=this.nodes.get(e.source),r=this.nodes.get(e.target);if(!n||!r)continue;let o=r.x-n.x,s=r.y-n.y,i=Math.sqrt(o*o+s*s)||1,a=i*this.attractionForce,l=o/i*a,c=s/i*a;n.fx+=l,n.fy+=c,r.fx-=l,r.fy-=c}}applyCenterForce(){let e=this.width/2,n=this.height/2;for(let r of this.nodes.values()){let o=e-r.x,s=n-r.y;r.fx+=o*this.centerForce,r.fy+=s*this.centerForce}}updatePositions(){for(let e of this.nodes.values()){e.vx=(e.vx+e.fx)*this.damping,e.vy=(e.vy+e.fy)*this.damping,e.x+=e.vx,e.y+=e.vy;let n=50;e.x<n?(e.x=n,e.vx*=-.5):e.x>this.width-n&&(e.x=this.width-n,e.vx*=-.5),e.y<n?(e.y=n,e.vy*=-.5):e.y>this.height-n&&(e.y=this.height-n,e.vy*=-.5)}}initializePositions(){let e=this.width/2,n=this.height/2,r=Math.min(this.width,this.height)/4;for(let o of this.nodes.values())if(o.x===0&&o.y===0){let s=Math.random()*Math.PI*2,i=Math.random()*r;o.x=e+Math.cos(s)*i,o.y=n+Math.sin(s)*i,o.vx=0,o.vy=0}}},Ho=({width:t=800,height:e=600,showLabels:n=!0,animate:r=!0,updateInterval:o=50,enablePhysics:s=!0,nodeRadius:i=20,highlightDuration:a=1e3})=>{let[l,c]=er({nodes:new Map,edges:[]}),[p,S]=er(null),x=Kt(new Jt(t,e)),U=Kt(null),A=Kt(Date.now()),M=$e(()=>{if(!ye())return{nodes:new Map,edges:[]};let d=Qn(),v=new Map,y=[];for(let g of d){let T=l.nodes.get(g.id);v.set(g.id,{id:g.id,type:g.type,value:g.value,label:g.name||g.id.split("_")[0],x:T?.x||0,y:T?.y||0,vx:T?.vx||0,vy:T?.vy||0,fx:0,fy:0,isUpdating:T?.isUpdating||!1,lastUpdate:g.updatedAt,subscriberCount:g.subscriberCount,dependencies:g.dependencies,subscribers:g.subscribers})}for(let g of v.values())for(let T of g.dependencies)v.has(T)&&y.push({source:g.id,target:T});return{nodes:v,edges:y}},[l.nodes]),$=$e(d=>{c(v=>{let y=M();return x.current.setGraph(y.nodes,y.edges),x.current.initializePositions(),y})},[M]),ee=$e(d=>{let{id:v}=d.payload;c(y=>{let g=y.nodes.get(v);return g&&(g.isUpdating=!0,g.lastUpdate=d.timestamp,setTimeout(()=>{c(T=>{let q=T.nodes.get(v);return q&&(q.isUpdating=!1),{...T}})},a)),{...y}})},[a]),E=$e(d=>{c(v=>{let y=M();return x.current.setGraph(y.nodes,y.edges),y})},[M]),k=$e(d=>{c(v=>{let y=M();return x.current.setGraph(y.nodes,y.edges),y})},[M]);Zn(()=>{if(!ye())return;let d=M();c(d),x.current.setGraph(d.nodes,d.edges),x.current.initializePositions();let v=[Re("signal-created",$),Re("signal-updated",ee),Re("signal-destroyed",E),Re("dependency-added",k),Re("dependency-removed",k)];return()=>{v.forEach(y=>y())}},[M,$,ee,E,k]),Zn(()=>{if(!r||!s)return;let d=()=>{let v=Date.now();v-A.current>=o&&(x.current.tick(),c(y=>({...y})),A.current=v),U.current=requestAnimationFrame(d)};return U.current=requestAnimationFrame(d),()=>{U.current&&cancelAnimationFrame(U.current)}},[r,s,o]);let j=d=>{if(d.isUpdating)return"#ff4444";switch(d.type){case"signal":return"#4CAF50";case"computed":return"#2196F3";case"effect":return"#FF9800";default:return"#9E9E9E"}},u=d=>p===d.id?"#FFD700":"#ffffff",w=d=>new Date(d).toLocaleTimeString(),D=d=>{if(d===null)return"null";if(d===void 0)return"undefined";if(typeof d=="object")try{return JSON.stringify(d).slice(0,50)}catch{return"[Object]"}return String(d).slice(0,50)};return ye()?R("div",{style:{position:"relative",width:t,height:e,background:"#1e1e1e",borderRadius:8},children:[R("svg",{width:t,height:e,children:[P("defs",{children:P("marker",{id:"arrowhead",markerWidth:"10",markerHeight:"10",refX:"9",refY:"3",orient:"auto",markerUnits:"strokeWidth",children:P("path",{d:"M0,0 L0,6 L9,3 z",fill:"#666"})})}),P("g",{className:"edges",children:l.edges.map((d,v)=>{let y=l.nodes.get(d.source),g=l.nodes.get(d.target);if(!y||!g)return null;let T=g.x-y.x,q=g.y-y.y,Se=Math.sqrt(T*T+q*q)||1,sn=T/Se*i,an=q/Se*i;return P("line",{x1:y.x+sn,y1:y.y+an,x2:g.x-sn,y2:g.y-an,stroke:"#666",strokeWidth:2,markerEnd:"url(#arrowhead)",opacity:p===y.id||p===g.id?1:.3},`${d.source}-${d.target}-${v}`)})}),P("g",{className:"nodes",children:Array.from(l.nodes.values()).map(d=>R("g",{onMouseEnter:()=>S(d.id),onMouseLeave:()=>S(null),style:{cursor:"pointer"},children:[P("circle",{cx:d.x,cy:d.y,r:i,fill:j(d),stroke:u(d),strokeWidth:p===d.id?3:1,opacity:p&&p!==d.id?.5:1}),n&&P("text",{x:d.x,y:d.y+i+15,textAnchor:"middle",fill:"#ffffff",fontSize:"12",fontFamily:"monospace",children:d.label}),d.isUpdating&&R("circle",{cx:d.x,cy:d.y,r:i,fill:"none",stroke:"#ff4444",strokeWidth:2,opacity:.6,children:[P("animate",{attributeName:"r",from:i,to:i*2,dur:"0.5s",repeatCount:"indefinite"}),P("animate",{attributeName:"opacity",from:"0.6",to:"0",dur:"0.5s",repeatCount:"indefinite"})]})]},d.id))})]}),p&&l.nodes.has(p)&&P("div",{style:{position:"absolute",top:10,right:10,background:"rgba(0, 0, 0, 0.9)",color:"#fff",padding:15,borderRadius:8,fontSize:12,fontFamily:"monospace",maxWidth:300,border:"2px solid #FFD700"},children:(()=>{let d=l.nodes.get(p);return R(Go,{children:[P("div",{style:{fontWeight:"bold",marginBottom:8,fontSize:14},children:d.label}),R("div",{style:{marginBottom:4},children:[P("strong",{children:"Type:"})," ",d.type]}),R("div",{style:{marginBottom:4},children:[P("strong",{children:"ID:"})," ",d.id]}),R("div",{style:{marginBottom:4},children:[P("strong",{children:"Value:"})," ",D(d.value)]}),R("div",{style:{marginBottom:4},children:[P("strong",{children:"Last Update:"})," ",w(d.lastUpdate)]}),R("div",{style:{marginBottom:4},children:[P("strong",{children:"Subscribers:"})," ",d.subscriberCount]}),d.dependencies.length>0&&R("div",{style:{marginBottom:4},children:[P("strong",{children:"Dependencies:"}),P("ul",{style:{margin:"4px 0",paddingLeft:20},children:d.dependencies.map(v=>{let y=l.nodes.get(v);return P("li",{children:y?.label||v},v)})})]}),d.subscribers.length>0&&R("div",{children:[P("strong",{children:"Subscribers:"}),R("ul",{style:{margin:"4px 0",paddingLeft:20},children:[d.subscribers.slice(0,5).map(v=>{let y=l.nodes.get(v);return P("li",{children:y?.label||v},v)}),d.subscribers.length>5&&R("li",{children:["... and ",d.subscribers.length-5," more"]})]})]})]})})()}),R("div",{style:{position:"absolute",bottom:10,left:10,background:"rgba(0, 0, 0, 0.8)",color:"#fff",padding:10,borderRadius:8,fontSize:11,fontFamily:"sans-serif"},children:[P("div",{style:{marginBottom:5,fontWeight:"bold"},children:"Legend"}),R("div",{style:{display:"flex",alignItems:"center",marginBottom:3},children:[P("div",{style:{width:12,height:12,background:"#4CAF50",borderRadius:"50%",marginRight:6}}),"Signal"]}),R("div",{style:{display:"flex",alignItems:"center",marginBottom:3},children:[P("div",{style:{width:12,height:12,background:"#2196F3",borderRadius:"50%",marginRight:6}}),"Computed"]}),R("div",{style:{display:"flex",alignItems:"center",marginBottom:3},children:[P("div",{style:{width:12,height:12,background:"#FF9800",borderRadius:"50%",marginRight:6}}),"Effect"]}),R("div",{style:{display:"flex",alignItems:"center"},children:[P("div",{style:{width:12,height:12,background:"#ff4444",borderRadius:"50%",marginRight:6}}),"Updating"]})]}),R("div",{style:{position:"absolute",top:10,left:10,background:"rgba(0, 0, 0, 0.8)",color:"#fff",padding:10,borderRadius:8,fontSize:11,fontFamily:"monospace"},children:[R("div",{children:["Signals: ",l.nodes.size]}),R("div",{children:["Edges: ",l.edges.length]})]})]}):R("div",{style:{padding:20,color:"#ff0000"},children:["DevTools is not enabled. Call ",P("code",{children:"enableDevTools()"})," to use the visualizer."]})};import{useState as Fe,useEffect as tr,useMemo as jo}from"react";import{jsx as f,jsxs as h}from"react/jsx-runtime";var qo=({refreshInterval:t=1e3,maxBatchRecords:e=20,showDetails:n=!0,className:r="",style:o={}})=>{let[s,i]=Fe(null),[a,l]=Fe(null),[c,p]=Fe("mean"),[S,x]=Fe("desc"),[U,A]=Fe(ge()),M=()=>{let u=Pe();i(u)};tr(()=>{if(t>0){let u=setInterval(M,t);return()=>clearInterval(u)}},[t]),tr(()=>{M()},[]);let $=()=>{U?Pt():xt(),A(!U),M()},ee=()=>{Ct(),M()},E=()=>{if(!s)return;let u=JSON.stringify(s,(v,y)=>y instanceof Map?Object.fromEntries(y):y,2),w=new Blob([u],{type:"application/json"}),D=URL.createObjectURL(w),d=document.createElement("a");d.href=D,d.download=`signalforge-performance-${Date.now()}.json`,d.click(),URL.revokeObjectURL(D)},k=jo(()=>s?Array.from(s.signalStats.values()).sort((w,D)=>{let d=w[c],v=D[c],y=d<v?-1:d>v?1:0;return S==="asc"?y:-y}):[],[s,c,S]),j=u=>{c===u?x(S==="asc"?"desc":"asc"):(p(u),x("desc"))};return s?h("div",{className:`performance-tab ${r}`,style:{padding:"20px",fontFamily:"system-ui, sans-serif",...o},children:[h("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"20px"},children:[f("h2",{style:{margin:0},children:"Performance Profiler"}),h("div",{style:{display:"flex",gap:"10px"},children:[f("button",{onClick:$,style:Oe,children:U?"\u23F8\uFE0F Pause":"\u25B6\uFE0F Start"}),f("button",{onClick:ee,style:Oe,children:"\u{1F504} Reset"}),f("button",{onClick:E,style:Oe,children:"\u{1F4E5} Export"}),f("button",{onClick:M,style:Oe,children:"\u27F3 Refresh"})]})]}),h("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:"15px",marginBottom:"30px"},children:[f(Le,{title:"Total Signals",value:s.totalSignals,icon:"\u{1F4CA}"}),f(Le,{title:"Total Samples",value:s.totalSamples,icon:"\u{1F4C8}"}),f(Le,{title:"Total Batches",value:s.batchStats.totalBatches,icon:"\u{1F500}"}),f(Le,{title:"Avg Batch Duration",value:`${s.batchStats.avgDuration.toFixed(2)}ms`,icon:"\u23F1\uFE0F"}),f(Le,{title:"Session Duration",value:`${(s.duration/1e3).toFixed(1)}s`,icon:"\u23F3"}),f(Le,{title:"Status",value:U?"Running":"Paused",icon:U?"\u2705":"\u23F8\uFE0F"})]}),h("section",{style:{marginBottom:"30px"},children:[f("h3",{children:"Signal Latency Statistics"}),k.length===0?f("p",{style:{color:"#666"},children:"No signals profiled yet. Start using signals to see data."}):h("table",{style:nr,children:[f("thead",{children: