signalforge
Version:
Fine-grained reactive state management with automatic dependency tracking - Ultra-optimized, zero dependencies
2 lines (1 loc) • 25.2 kB
JavaScript
var ot=(e,t)=>()=>(e&&(t=e(e=0)),t);function st(){return`signal_${++it}_${Date.now()}`}function Ue(e,t,r){let n={id:st(),type:e,createdAt:Date.now(),label:r};if(ee.set(n.id,n),le){for(let o of ae)if(o.onSignalCreate)try{o.onSignalCreate(n,t)}catch(i){console.error(`Error in plugin "${o.name}" onSignalCreate:`,i)}}return n}function _e(e,t,r,n="set"){if(!le)return;let o=ee.get(e);if(!o)return;let i={signal:o,oldValue:t,newValue:r,timestamp:Date.now(),source:n};for(let d of ae)if(d.onSignalUpdate)try{d.onSignalUpdate(i)}catch(f){console.error(`Error in plugin "${d.name}" onSignalUpdate:`,f)}}function Be(e){if(!le)return;let t=ee.get(e);if(t){for(let r of ae)if(r.onSignalDestroy)try{r.onSignalDestroy(t)}catch(n){console.error(`Error in plugin "${r.name}" onSignalDestroy:`,n)}ee.delete(e)}}var ae,ee,it,le,Re=ot(()=>{"use strict";ae=[],ee=new Map,it=0,le=!0});Re();var B=1,de=2,ce=4,ue=8,Le=16,Ie=1e4,Ae=new Array(Ie),ne=0;function at(e){ne<Ie&&(e.value=void 0,e.subscribers=null,e.listeners=null,e.dependencies=null,e.computeFn=null,e.flags=0,Ae[ne++]=e)}var te=new WeakMap,$e=new Map;var fe=1e4,Ve=new Array(fe),N=0,W=0,ge=!1;function lt(e){if(e.flags&de)return;let t=(W+1)%fe;t===N&&(console.error("[SignalForge] Batch queue overflow \u2192 forcing flush"),pe()),e.flags|=de,Ve[W]=e,W=t,ge||(ge=!0,queueMicrotask(pe))}function pe(){for(ge=!1;N!==W;){let e=Ve[N];N=(N+1)%fe,e.flags&=~de,e.flags&B&&H(e)}}var Ge=new Array(100),Ne=0,k=null;function ct(e){Ge[Ne++]=k,k=e}function dt(){k=Ge[--Ne]}var ut=function(){return this._node.value},gt=function(e){this._node.subscribers||(this._node.subscribers=new Set),this._node.subscribers.add(e)},pt=function(e){this._node.subscribers&&this._node.subscribers.delete(e)};function me(e,t=null){let r=ne>0?Ae[--ne]:{value:void 0,subscribers:null,listeners:null,dependencies:null,computeFn:null,flags:0};return r.value=e,r.computeFn=t,r.flags=t?Le|B:0,t&&H(r),r}function Oe(e,t){return k?(k!==e&&(ze(e,k),bt(k,t)),e.flags&B&&e.computeFn&&H(e),e.value):(e.flags&B&&e.computeFn&&H(e),e.value)}function ft(e,t,r){if(e.flags&Le)throw new Error("Cannot set computed signal");if(typeof r=="function"&&(r=r(e.value)),Object.is(r,e.value))return;let n=e.value;e.value=r;let o=te.get(t);o&&_e(o,n,r,"set"),qe(e)}function ze(e,t){e.subscribers||(e.subscribers=new Set),e.subscribers.add(t)}function mt(e,t){e.subscribers&&e.subscribers.delete(t)}function bt(e,t){e.dependencies||(e.dependencies=new Set),e.dependencies.has(t)||(e.dependencies.add(t),ze(t._node,e))}function je(e){if(e.dependencies){for(let t of e.dependencies)mt(t._node,e);e.dependencies.clear()}}function be(e){if(!(e.flags&B)&&(e.flags|=B,lt(e),e.subscribers))for(let t of e.subscribers)be(t)}function H(e){if(e.computeFn&&!(e.flags&ce)){e.flags|=ce,je(e),ct(e);try{let t=e.computeFn();e.flags&=~B,e.flags&=~ce,Object.is(t,e.value)||(e.value=t,qe(e))}finally{dt()}}}function qe(e){if(e.subscribers)for(let t of e.subscribers)be(t);if(e.flags&ue&&e.listeners)for(let t of e.listeners)t(e.value)}function We(e,t){return e.listeners||(e.listeners=new Set),e.listeners.add(t),e.flags|=ue,()=>{e.listeners.delete(t),e.listeners.size===0&&(e.flags&=~ue)}}function ye(e){je(e),e.subscribers&&e.subscribers.clear(),e.listeners&&e.listeners.clear(),at(e)}function yt(e){let t=me(e,null),r={get:()=>Oe(t,r),set:o=>ft(t,r,o),subscribe:o=>We(t,o),destroy:()=>{let o=te.get(r);o&&(Be(o),$e.delete(o),te.delete(r)),ye(t)},_node:t,_peek:ut,_addSubscriber:gt,_removeSubscriber:pt},n=Ue("signal",e);return te.set(r,n.id),$e.set(n.id,r),r}function ht(e){let t,r=k;k=null;try{t=e()}finally{k=r}let n=me(t,e),o={get:()=>Oe(n,o),set:()=>{throw new Error("Cannot set a computed signal")},subscribe:i=>We(n,i),destroy:()=>ye(n),_node:n,_peek:()=>n.value,_addSubscriber:i=>{n.subscribers||(n.subscribers=new Set),n.subscribers.add(i)},_removeSubscriber:i=>{n.subscribers&&n.subscribers.delete(i)},_markDirty:()=>be(n),_recompute:()=>H(n)};return o}function vt(e){let t=me(void 0,e);return()=>ye(t)}function St(e){let t=e();return He(),t}function He(){N!==W&&pe()}function xt(e){let t=k;k=null;try{return e()}finally{k=t}}var Tt=He;var he=!1,F={enabled:!1,trackPerformance:!0,logToConsole:!1,maxPerformanceSamples:1e3,flipperEnabled:!1},R=new Map;var re=[];var O=null;function Dt(e={}){he=!0,Object.assign(F,e),F.enabled=!0,F.logToConsole,F.flipperEnabled&&Et()}function Pt(){he=!1,F.enabled=!1,O&&Ft()}function U(){return he&&F.enabled}function oe(){return U()?Array.from(R.values()).sort((e,t)=>e.createdAt-t.createdAt):[]}function wt(e){if(U())return R.get(e)}function Ct(e){return U()?R.get(e)?.dependencies||[]:[]}function Mt(e){return U()?R.get(e)?.subscribers||[]:[]}function K(){if(!U())return[];let e=[],t=new Map,r=(n,o=0)=>{let i=t.get(n);if(i!==void 0)return Math.max(i,o);t.set(n,o);let d=R.get(n);if(d)for(let f of d.subscribers)r(f,o+1);return o};for(let[n,o]of R)o.dependencies.length===0&&r(n,0);for(let[n,o]of R)e.push({id:n,type:o.type,dependencies:o.dependencies,subscribers:o.subscribers,depth:t.get(n)||0});return e.sort((n,o)=>n.depth-o.depth)}function ve(e){if(!U())return[];let t=[...re];return e?t.slice(-e):t}function Se(){if(!U())return{totalUpdates:0,totalDuration:0,averageDuration:0,slowestUpdate:null,updatesByType:{}};let e=0,t=null,r={signal:0,computed:0,effect:0};for(let i of re)i.skipped||(e+=i.duration,r[i.type]++,(!t||i.duration>t.duration)&&(t=i));let n=re.filter(i=>!i.skipped).length,o=n>0?e/n:0;return{totalUpdates:n,totalDuration:e,averageDuration:o,slowestUpdate:t,updatesByType:r}}function kt(){re.length=0}function Et(){try{typeof global<"u"&&global.__FLIPPER__&&(O=global.__FLIPPER__.addPlugin({getId:()=>"signalforge-inspector",onConnect:t=>{t.send("initialState",{signals:oe(),graph:K(),config:F}),t.receive("getSignals",()=>{t.send("signals",oe())}),t.receive("getGraph",()=>{t.send("graph",K())}),t.receive("getPerformance",()=>{t.send("performance",{metrics:ve(100),summary:Se()})})},onDisconnect:()=>{O=null}}))}catch(e){}}function Ft(){if(O){try{O.disconnect()}catch(e){}O=null}}function Ut(){return{timestamp:Date.now(),config:{...F},signals:oe(),graph:K(),performance:{metrics:ve(),summary:Se()}}}function _t(){if(!U())return;let e=K();console.group("SignalForge Dependency Graph");for(let t of e){let r=" ".repeat(t.depth),n=t.dependencies.length>0?` \u2190 [${t.dependencies.join(", ")}]`:"",o=t.subscribers.length>0?` \u2192 [${t.subscribers.join(", ")}]`:"";`${r}${t.id}${t.type}${n}${o}`}console.groupEnd()}import{useEffect as et,useRef as Ce,useState as tt,useCallback as J}from"react";var $=!1,Y=null,Bt=0,ie=new Map,se=[],Rt=new Map,$t=new Map,xe={maxSamplesPerSignal:100,maxBatchRecords:50,autoComputeStats:!1,emitEvents:!0};function Te(e){$||(xe={...xe,...e},$=!0,Y=performance.now())}function De(){$&&($=!1)}function Ye(){return $}function Xe(){ie.clear(),se.length=0,Rt.clear(),$t.clear(),Y=$?performance.now():null,Bt=0}function Pe(){let e=performance.now(),t=Y?e-Y:0,r=new Map,n=0;for(let[i,d]of ie.entries()){if(d.length===0)continue;let f=Je(i,d);r.set(i,f),n+=d.length}let o=Qe(se);return{enabled:$,startedAt:Y,duration:t,signalStats:r,batchRecords:[...se],batchStats:o,totalSamples:n,totalSignals:ie.size}}function Lt(e){let t=ie.get(e);return!t||t.length===0?null:Je(e,t)}function It(){return Qe(se)}function Je(e,t){if(t.length===0)return{signalId:e,type:"signal",sampleCount:0,min:0,max:0,mean:0,median:0,p95:0,p99:0,stdDev:0,avgSubscribers:0,skippedCount:0};let r=t[0].type,n=t.map(T=>T.latency),o=[...n].sort((T,w)=>T-w),i=o[0],d=o[o.length-1],b=n.reduce((T,w)=>T+w,0)/n.length,u=Math.floor(o.length/2),h=o.length%2===0?(o[u-1]+o[u])/2:o[u],S=Ke(o,.95),x=Ke(o,.99),L=n.map(T=>Math.pow(T-b,2)).reduce((T,w)=>T+w,0)/n.length,D=Math.sqrt(L),I=t.reduce((T,w)=>T+w.subscriberCount,0)/t.length,A=t.filter(T=>T.skipped).length;return{signalId:e,type:r,sampleCount:t.length,min:i,max:d,mean:b,median:h,p95:S,p99:x,stdDev:D,avgSubscribers:I,skippedCount:A}}function Qe(e){if(e.length===0)return{totalBatches:0,avgDuration:0,minDuration:0,maxDuration:0,avgOperationsPerBatch:0,totalOperations:0};let t=e.map(u=>u.duration),r=e.map(u=>u.operationCount),n=e.length,o=t.reduce((u,h)=>u+h,0)/n,i=Math.min(...t),d=Math.max(...t),f=r.reduce((u,h)=>u+h,0),b=f/n;return{totalBatches:n,avgDuration:o,minDuration:i,maxDuration:d,avgOperationsPerBatch:b,totalOperations:f}}function Ke(e,t){if(e.length===0)return 0;let r=t*(e.length-1),n=Math.floor(r),o=Math.ceil(r),i=r-n;return n===o?e[n]:e[n]*(1-i)+e[o]*i}var we=class{constructor(){this.listeners=new Map;this.sequence=0}on(t,r){let n=t;return this.listeners.has(n)||this.listeners.set(n,new Set),this.listeners.get(n).add(r),()=>this.off(t,r)}off(t,r){let n=t,o=this.listeners.get(n);o&&(o.delete(r),o.size===0&&this.listeners.delete(n))}emit(t,r){let n={type:t,payload:r,timestamp:Date.now(),sequence:++this.sequence},o=this.listeners.get(t);if(o)for(let d of o)try{d(n)}catch(f){console.error(`[DevTools] Error in listener for ${t}:`,f)}let i=this.listeners.get("*");if(i)for(let d of i)try{d(n)}catch(f){console.error("[DevTools] Error in wildcard listener:",f)}}removeAllListeners(){this.listeners.clear(),this.sequence=0}getListenerCount(t){if(t)return this.listeners.get(t)?.size||0;let r=0;for(let n of this.listeners.values())r+=n.size;return r}},At=typeof process<"u"?process.env.NODE_ENV!=="production":!0,Vt={enabled:!1,trackPerformance:!0,logToConsole:!1,maxPerformanceSamples:1e3,slowUpdateThreshold:16,emitPerformanceWarnings:!0},Gt=new Map;var Nt=new we;function X(){return At&&Vt.enabled}function Ze(){return X()?Array.from(Gt.values()).sort((e,t)=>e.createdAt-t.createdAt):[]}function z(e,t){return Nt.on(e,t)}import{Fragment as zt,jsx as m,jsxs as v}from"react/jsx-runtime";var Me=class{constructor(t,r){this.repulsionForce=3e3;this.attractionForce=.01;this.centerForce=.01;this.damping=.9;this.minDistance=50;this.nodes=new Map,this.edges=[],this.width=t,this.height=r}setGraph(t,r){this.nodes=t,this.edges=r}tick(){for(let t of this.nodes.values())t.fx=0,t.fy=0;this.applyRepulsion(),this.applyAttraction(),this.applyCenterForce(),this.updatePositions()}applyRepulsion(){let t=Array.from(this.nodes.values());for(let r=0;r<t.length;r++)for(let n=r+1;n<t.length;n++){let o=t[r],i=t[n],d=i.x-o.x,f=i.y-o.y,b=d*d+f*f,u=Math.sqrt(b)||1;if(u<this.minDistance){let h=this.repulsionForce/(this.minDistance*this.minDistance),S=d/u*h,x=f/u*h;o.fx-=S,o.fy-=x,i.fx+=S,i.fy+=x}else{let h=this.repulsionForce/b,S=d/u*h,x=f/u*h;o.fx-=S,o.fy-=x,i.fx+=S,i.fy+=x}}}applyAttraction(){for(let t of this.edges){let r=this.nodes.get(t.source),n=this.nodes.get(t.target);if(!r||!n)continue;let o=n.x-r.x,i=n.y-r.y,d=Math.sqrt(o*o+i*i)||1,f=d*this.attractionForce,b=o/d*f,u=i/d*f;r.fx+=b,r.fy+=u,n.fx-=b,n.fy-=u}}applyCenterForce(){let t=this.width/2,r=this.height/2;for(let n of this.nodes.values()){let o=t-n.x,i=r-n.y;n.fx+=o*this.centerForce,n.fy+=i*this.centerForce}}updatePositions(){for(let t of this.nodes.values()){t.vx=(t.vx+t.fx)*this.damping,t.vy=(t.vy+t.fy)*this.damping,t.x+=t.vx,t.y+=t.vy;let r=50;t.x<r?(t.x=r,t.vx*=-.5):t.x>this.width-r&&(t.x=this.width-r,t.vx*=-.5),t.y<r?(t.y=r,t.vy*=-.5):t.y>this.height-r&&(t.y=this.height-r,t.vy*=-.5)}}initializePositions(){let t=this.width/2,r=this.height/2,n=Math.min(this.width,this.height)/4;for(let o of this.nodes.values())if(o.x===0&&o.y===0){let i=Math.random()*Math.PI*2,d=Math.random()*n;o.x=t+Math.cos(i)*d,o.y=r+Math.sin(i)*d,o.vx=0,o.vy=0}}},Ot=({width:e=800,height:t=600,showLabels:r=!0,animate:n=!0,updateInterval:o=50,enablePhysics:i=!0,nodeRadius:d=20,highlightDuration:f=1e3})=>{let[b,u]=tt({nodes:new Map,edges:[]}),[h,S]=tt(null),x=Ce(new Me(e,t)),E=Ce(null),L=Ce(Date.now()),D=J(()=>{if(!X())return{nodes:new Map,edges:[]};let s=Ze(),p=new Map,g=[];for(let y of s){let P=b.nodes.get(y.id);p.set(y.id,{id:y.id,type:y.type,value:y.value,label:y.name||y.id.split("_")[0],x:P?.x||0,y:P?.y||0,vx:P?.vx||0,vy:P?.vy||0,fx:0,fy:0,isUpdating:P?.isUpdating||!1,lastUpdate:y.updatedAt,subscriberCount:y.subscriberCount,dependencies:y.dependencies,subscribers:y.subscribers})}for(let y of p.values())for(let P of y.dependencies)p.has(P)&&g.push({source:y.id,target:P});return{nodes:p,edges:g}},[b.nodes]),I=J(s=>{u(p=>{let g=D();return x.current.setGraph(g.nodes,g.edges),x.current.initializePositions(),g})},[D]),A=J(s=>{let{id:p}=s.payload;u(g=>{let y=g.nodes.get(p);return y&&(y.isUpdating=!0,y.lastUpdate=s.timestamp,setTimeout(()=>{u(P=>{let G=P.nodes.get(p);return G&&(G.isUpdating=!1),{...P}})},f)),{...g}})},[f]),T=J(s=>{u(p=>{let g=D();return x.current.setGraph(g.nodes,g.edges),g})},[D]),w=J(s=>{u(p=>{let g=D();return x.current.setGraph(g.nodes,g.edges),g})},[D]);et(()=>{if(!X())return;let s=D();u(s),x.current.setGraph(s.nodes,s.edges),x.current.initializePositions();let p=[z("signal-created",I),z("signal-updated",A),z("signal-destroyed",T),z("dependency-added",w),z("dependency-removed",w)];return()=>{p.forEach(g=>g())}},[D,I,A,T,w]),et(()=>{if(!n||!i)return;let s=()=>{let p=Date.now();p-L.current>=o&&(x.current.tick(),u(g=>({...g})),L.current=p),E.current=requestAnimationFrame(s)};return E.current=requestAnimationFrame(s),()=>{E.current&&cancelAnimationFrame(E.current)}},[n,i,o]);let _=s=>{if(s.isUpdating)return"#ff4444";switch(s.type){case"signal":return"#4CAF50";case"computed":return"#2196F3";case"effect":return"#FF9800";default:return"#9E9E9E"}},l=s=>h===s.id?"#FFD700":"#ffffff",q=s=>new Date(s).toLocaleTimeString(),V=s=>{if(s===null)return"null";if(s===void 0)return"undefined";if(typeof s=="object")try{return JSON.stringify(s).slice(0,50)}catch{return"[Object]"}return String(s).slice(0,50)};return X()?v("div",{style:{position:"relative",width:e,height:t,background:"#1e1e1e",borderRadius:8},children:[v("svg",{width:e,height:t,children:[m("defs",{children:m("marker",{id:"arrowhead",markerWidth:"10",markerHeight:"10",refX:"9",refY:"3",orient:"auto",markerUnits:"strokeWidth",children:m("path",{d:"M0,0 L0,6 L9,3 z",fill:"#666"})})}),m("g",{className:"edges",children:b.edges.map((s,p)=>{let g=b.nodes.get(s.source),y=b.nodes.get(s.target);if(!g||!y)return null;let P=y.x-g.x,G=y.y-g.y,ke=Math.sqrt(P*P+G*G)||1,Ee=P/ke*d,Fe=G/ke*d;return m("line",{x1:g.x+Ee,y1:g.y+Fe,x2:y.x-Ee,y2:y.y-Fe,stroke:"#666",strokeWidth:2,markerEnd:"url(#arrowhead)",opacity:h===g.id||h===y.id?1:.3},`${s.source}-${s.target}-${p}`)})}),m("g",{className:"nodes",children:Array.from(b.nodes.values()).map(s=>v("g",{onMouseEnter:()=>S(s.id),onMouseLeave:()=>S(null),style:{cursor:"pointer"},children:[m("circle",{cx:s.x,cy:s.y,r:d,fill:_(s),stroke:l(s),strokeWidth:h===s.id?3:1,opacity:h&&h!==s.id?.5:1}),r&&m("text",{x:s.x,y:s.y+d+15,textAnchor:"middle",fill:"#ffffff",fontSize:"12",fontFamily:"monospace",children:s.label}),s.isUpdating&&v("circle",{cx:s.x,cy:s.y,r:d,fill:"none",stroke:"#ff4444",strokeWidth:2,opacity:.6,children:[m("animate",{attributeName:"r",from:d,to:d*2,dur:"0.5s",repeatCount:"indefinite"}),m("animate",{attributeName:"opacity",from:"0.6",to:"0",dur:"0.5s",repeatCount:"indefinite"})]})]},s.id))})]}),h&&b.nodes.has(h)&&m("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 s=b.nodes.get(h);return v(zt,{children:[m("div",{style:{fontWeight:"bold",marginBottom:8,fontSize:14},children:s.label}),v("div",{style:{marginBottom:4},children:[m("strong",{children:"Type:"})," ",s.type]}),v("div",{style:{marginBottom:4},children:[m("strong",{children:"ID:"})," ",s.id]}),v("div",{style:{marginBottom:4},children:[m("strong",{children:"Value:"})," ",V(s.value)]}),v("div",{style:{marginBottom:4},children:[m("strong",{children:"Last Update:"})," ",q(s.lastUpdate)]}),v("div",{style:{marginBottom:4},children:[m("strong",{children:"Subscribers:"})," ",s.subscriberCount]}),s.dependencies.length>0&&v("div",{style:{marginBottom:4},children:[m("strong",{children:"Dependencies:"}),m("ul",{style:{margin:"4px 0",paddingLeft:20},children:s.dependencies.map(p=>{let g=b.nodes.get(p);return m("li",{children:g?.label||p},p)})})]}),s.subscribers.length>0&&v("div",{children:[m("strong",{children:"Subscribers:"}),v("ul",{style:{margin:"4px 0",paddingLeft:20},children:[s.subscribers.slice(0,5).map(p=>{let g=b.nodes.get(p);return m("li",{children:g?.label||p},p)}),s.subscribers.length>5&&v("li",{children:["... and ",s.subscribers.length-5," more"]})]})]})]})})()}),v("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:[m("div",{style:{marginBottom:5,fontWeight:"bold"},children:"Legend"}),v("div",{style:{display:"flex",alignItems:"center",marginBottom:3},children:[m("div",{style:{width:12,height:12,background:"#4CAF50",borderRadius:"50%",marginRight:6}}),"Signal"]}),v("div",{style:{display:"flex",alignItems:"center",marginBottom:3},children:[m("div",{style:{width:12,height:12,background:"#2196F3",borderRadius:"50%",marginRight:6}}),"Computed"]}),v("div",{style:{display:"flex",alignItems:"center",marginBottom:3},children:[m("div",{style:{width:12,height:12,background:"#FF9800",borderRadius:"50%",marginRight:6}}),"Effect"]}),v("div",{style:{display:"flex",alignItems:"center"},children:[m("div",{style:{width:12,height:12,background:"#ff4444",borderRadius:"50%",marginRight:6}}),"Updating"]})]}),v("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:[v("div",{children:["Signals: ",b.nodes.size]}),v("div",{children:["Edges: ",b.edges.length]})]})]}):v("div",{style:{padding:20,color:"#ff0000"},children:["DevTools is not enabled. Call ",m("code",{children:"enableDevTools()"})," to use the visualizer."]})};import{useState as Q,useEffect as nt,useMemo as jt}from"react";import{jsx as a,jsxs as c}from"react/jsx-runtime";var qt=({refreshInterval:e=1e3,maxBatchRecords:t=20,showDetails:r=!0,className:n="",style:o={}})=>{let[i,d]=Q(null),[f,b]=Q(null),[u,h]=Q("mean"),[S,x]=Q("desc"),[E,L]=Q(Ye()),D=()=>{let l=Pe();d(l)};nt(()=>{if(e>0){let l=setInterval(D,e);return()=>clearInterval(l)}},[e]),nt(()=>{D()},[]);let I=()=>{E?De():Te(),L(!E),D()},A=()=>{Xe(),D()},T=()=>{if(!i)return;let l=JSON.stringify(i,(p,g)=>g instanceof Map?Object.fromEntries(g):g,2),q=new Blob([l],{type:"application/json"}),V=URL.createObjectURL(q),s=document.createElement("a");s.href=V,s.download=`signalforge-performance-${Date.now()}.json`,s.click(),URL.revokeObjectURL(V)},w=jt(()=>i?Array.from(i.signalStats.values()).sort((q,V)=>{let s=q[u],p=V[u],g=s<p?-1:s>p?1:0;return S==="asc"?g:-g}):[],[i,u,S]),_=l=>{u===l?x(S==="asc"?"desc":"asc"):(h(l),x("desc"))};return i?c("div",{className:`performance-tab ${n}`,style:{padding:"20px",fontFamily:"system-ui, sans-serif",...o},children:[c("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"20px"},children:[a("h2",{style:{margin:0},children:"Performance Profiler"}),c("div",{style:{display:"flex",gap:"10px"},children:[a("button",{onClick:I,style:Z,children:E?"\u23F8\uFE0F Pause":"\u25B6\uFE0F Start"}),a("button",{onClick:A,style:Z,children:"\u{1F504} Reset"}),a("button",{onClick:T,style:Z,children:"\u{1F4E5} Export"}),a("button",{onClick:D,style:Z,children:"\u27F3 Refresh"})]})]}),c("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:"15px",marginBottom:"30px"},children:[a(j,{title:"Total Signals",value:i.totalSignals,icon:"\u{1F4CA}"}),a(j,{title:"Total Samples",value:i.totalSamples,icon:"\u{1F4C8}"}),a(j,{title:"Total Batches",value:i.batchStats.totalBatches,icon:"\u{1F500}"}),a(j,{title:"Avg Batch Duration",value:`${i.batchStats.avgDuration.toFixed(2)}ms`,icon:"\u23F1\uFE0F"}),a(j,{title:"Session Duration",value:`${(i.duration/1e3).toFixed(1)}s`,icon:"\u23F3"}),a(j,{title:"Status",value:E?"Running":"Paused",icon:E?"\u2705":"\u23F8\uFE0F"})]}),c("section",{style:{marginBottom:"30px"},children:[a("h3",{children:"Signal Latency Statistics"}),w.length===0?a("p",{style:{color:"#666"},children:"No signals profiled yet. Start using signals to see data."}):c("table",{style:rt,children:[a("thead",{children:c("tr",{children:[c("th",{style:C,onClick:()=>_("signalId"),children:["Signal ID ",u==="signalId"&&(S==="asc"?"\u2191":"\u2193")]}),a("th",{style:C,children:"Type"}),c("th",{style:C,onClick:()=>_("sampleCount"),children:["Samples ",u==="sampleCount"&&(S==="asc"?"\u2191":"\u2193")]}),c("th",{style:C,onClick:()=>_("mean"),children:["Mean ",u==="mean"&&(S==="asc"?"\u2191":"\u2193")]}),a("th",{style:C,children:"Median"}),c("th",{style:C,onClick:()=>_("p95"),children:["P95 ",u==="p95"&&(S==="asc"?"\u2191":"\u2193")]}),c("th",{style:C,onClick:()=>_("p99"),children:["P99 ",u==="p99"&&(S==="asc"?"\u2191":"\u2193")]}),c("th",{style:C,onClick:()=>_("max"),children:["Max ",u==="max"&&(S==="asc"?"\u2191":"\u2193")]}),a("th",{style:C,children:"Skipped"})]})}),a("tbody",{children:w.map(l=>c("tr",{style:{backgroundColor:f===l.signalId?"#e3f2fd":"transparent",cursor:"pointer"},onClick:()=>b(l.signalId),children:[a("td",{style:M,children:l.signalId}),a("td",{style:M,children:l.type}),a("td",{style:M,children:l.sampleCount}),c("td",{style:M,children:[l.mean.toFixed(2),"ms"]}),c("td",{style:M,children:[l.median.toFixed(2),"ms"]}),c("td",{style:M,children:[l.p95.toFixed(2),"ms"]}),c("td",{style:M,children:[l.p99.toFixed(2),"ms"]}),c("td",{style:M,children:[l.max.toFixed(2),"ms"]}),a("td",{style:M,children:l.skippedCount})]},l.signalId))})]})]}),i.batchRecords.length>0&&c("section",{style:{marginBottom:"30px"},children:[a("h3",{children:"Recent Batch Operations"}),c("table",{style:rt,children:[a("thead",{children:c("tr",{children:[a("th",{style:C,children:"Batch ID"}),a("th",{style:C,children:"Duration"}),a("th",{style:C,children:"Operations"}),a("th",{style:C,children:"Signals Affected"}),a("th",{style:C,children:"Depth"})]})}),a("tbody",{children:i.batchRecords.slice(-t).map(l=>c("tr",{children:[c("td",{style:M,children:["#",l.batchId]}),c("td",{style:M,children:[l.duration.toFixed(2),"ms"]}),a("td",{style:M,children:l.operationCount}),a("td",{style:M,children:l.affectedSignals.length}),a("td",{style:M,children:l.depth})]},l.batchId))})]})]}),r&&f&&c("section",{style:{marginTop:"30px",padding:"15px",backgroundColor:"#f5f5f5",borderRadius:"8px"},children:[c("h3",{children:["Signal Details: ",f]}),(()=>{let l=i.signalStats.get(f);return l?c("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"10px"},children:[c("div",{children:[a("strong",{children:"Type:"})," ",l.type]}),c("div",{children:[a("strong",{children:"Sample Count:"})," ",l.sampleCount]}),c("div",{children:[a("strong",{children:"Min Latency:"})," ",l.min.toFixed(2),"ms"]}),c("div",{children:[a("strong",{children:"Max Latency:"})," ",l.max.toFixed(2),"ms"]}),c("div",{children:[a("strong",{children:"Mean Latency:"})," ",l.mean.toFixed(2),"ms"]}),c("div",{children:[a("strong",{children:"Median Latency:"})," ",l.median.toFixed(2),"ms"]}),c("div",{children:[a("strong",{children:"P95 Latency:"})," ",l.p95.toFixed(2),"ms"]}),c("div",{children:[a("strong",{children:"P99 Latency:"})," ",l.p99.toFixed(2),"ms"]}),c("div",{children:[a("strong",{children:"Std Deviation:"})," ",l.stdDev.toFixed(2),"ms"]}),c("div",{children:[a("strong",{children:"Avg Subscribers:"})," ",l.avgSubscribers.toFixed(1)]}),c("div",{children:[a("strong",{children:"Skipped Updates:"})," ",l.skippedCount]}),c("div",{children:[a("strong",{children:"Effective Updates:"})," ",l.sampleCount-l.skippedCount]})]}):null})(),a("button",{onClick:()=>b(null),style:{...Z,marginTop:"15px"},children:"Close Details"})]})]}):a("div",{className:`performance-tab ${n}`,style:{padding:"20px",...o},children:a("p",{children:"Loading profiler data..."})})},j=({title:e,value:t,icon:r})=>c("div",{style:{padding:"15px",backgroundColor:"#fff",border:"1px solid #e0e0e0",borderRadius:"8px",boxShadow:"0 2px 4px rgba(0,0,0,0.1)"},children:[a("div",{style:{fontSize:"24px",marginBottom:"5px"},children:r}),a("div",{style:{fontSize:"12px",color:"#666",marginBottom:"5px"},children:e}),a("div",{style:{fontSize:"20px",fontWeight:"bold"},children:t})]}),Z={padding:"8px 16px",backgroundColor:"#2196F3",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px"},rt={width:"100%",borderCollapse:"collapse",backgroundColor:"#fff",boxShadow:"0 2px 4px rgba(0,0,0,0.1)"},C={padding:"12px",backgroundColor:"#f5f5f5",borderBottom:"2px solid #e0e0e0",textAlign:"left",fontWeight:"bold",cursor:"pointer",userSelect:"none"},M={padding:"10px 12px",borderBottom:"1px solid #e0e0e0"};export{qt as PerformanceTab,Ot as SignalGraphVisualizer,St as batch,kt as clearPerformanceMetrics,ht as createComputed,vt as createEffect,yt as createSignal,Pt as disableDevTools,De as disableProfiler,Dt as enableDevTools,Te as enableProfiler,Ut as exportSnapshot,Tt as flushSync,It as getBatchStats,Ct as getDependencies,K as getDependencyGraph,ve as getPerformanceMetrics,Se as getPerformanceSummary,Pe as getProfilerData,wt as getSignal,Lt as getSignalLatencyStats,Mt as getSubscribers,U as isDevToolsEnabled,oe as listSignals,_t as printDependencyGraph,xt as untrack};