@jagreehal/workflow 1.13.0 → 1.15.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/visualize.js CHANGED
@@ -1,49 +1,55 @@
1
- function H(e){if(e<1e3)return`${Math.round(e)}ms`;if(e<6e4)return`${(e/1e3).toFixed(1).replace(/\.0$/,"")}s`;let r=Math.floor(e/6e4),t=Math.round(e%6e4/1e3);return t===0?`${r}m`:`${r}m ${t}s`}function le(){return`node_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Ae(e){for(let r of e)if((r.type==="parallel"||r.type==="race"||r.type==="sequence")&&!r.id.startsWith("detected_")||"decisionId"in r)return!0;return!1}function oe(e,r={}){if(Ae(e))return e;let{minOverlapMs:t=0,maxGapMs:a=5}=r,o=[],n=[];for(let u=0;u<e.length;u++){let s=e[u];s.type==="step"&&s.startTs!==void 0?o.push({node:s,startTs:s.startTs,endTs:s.endTs??s.startTs+(s.durationMs??0),originalIndex:u}):n.push({node:s,originalIndex:u})}if(o.length<=1)return e;o.sort((u,s)=>u.startTs-s.startTs);let c=[],p=[o[0]];for(let u=1;u<o.length;u++){let s=o[u],l=Math.min(...p.map(R=>R.startTs)),f=Math.max(...p.map(R=>R.endTs)),h=s.startTs<=l+a,k=s.startTs<f;if(!h&&!k){c.push(p),p=[s];continue}let v=k?Math.min(s.endTs,f)-s.startTs:0;h||v>=t?p.push(s):(c.push(p),p=[s])}c.push(p);let d=[];for(let u of c){let s=Math.min(...u.map(l=>l.originalIndex));if(u.length===1)d.push({node:u[0].node,position:s});else{let l=u.map(v=>v.node),f=Math.min(...u.map(v=>v.startTs)),h=Math.max(...u.map(v=>v.endTs)),k={type:"parallel",id:`detected_parallel_${f}`,name:`${l.length} parallel steps`,state:ze(l),mode:"all",children:l,startTs:f,endTs:h,durationMs:h-f};d.push({node:k,position:s})}}for(let{node:u,originalIndex:s}of n)d.push({node:u,position:s});return d.sort((u,s)=>u.position-s.position),d.map(u=>u.node)}function ze(e){return e.some(n=>n.state==="error")?"error":e.some(n=>n.state==="running")?"running":e.some(n=>n.state==="pending")?"pending":(e.every(n=>n.state==="success"||n.state==="cached"),"success")}function Fe(e={}){return{detect:r=>oe(r,e)}}function q(e={}){let{detectParallel:r=!0,parallelDetection:t,enableSnapshots:a=!1,maxSnapshots:o=1e3}=e,n,c,p="pending",d,u,s=new Map,l=[],f=[],h=[],k=Date.now(),v=k,R={onAfterStep:new Map},T=[],B=0;function O(i){return i.stepId??i.stepKey??i.name??le()}function g(i){if(f.length>0){let m=f[f.length-1];for(let P of m.branches.values())if(P.taken){P.children.push(i),v=Date.now();return}let b=Array.from(m.branches.values())[0];if(b){b.children.push(i),v=Date.now();return}}l.length>0?l[l.length-1].children.push(i):h.push(i),v=Date.now()}function I(i){if(!a)return;let m=M(),b=new Map;for(let[F,G]of s)b.set(F,{id:G.id,name:G.name,key:G.key,startTs:G.startTs,retryCount:G.retryCount,timedOut:G.timedOut,timeoutMs:G.timeoutMs});let P={id:`snapshot_${B}`,eventIndex:B,event:structuredClone(i),ir:structuredClone(m),timestamp:Date.now(),activeSteps:b};T.push(P),T.length>o&&T.shift(),B++}function w(i){switch(i.type){case"workflow_start":n=i.workflowId,c=i.ts,p="running",k=Date.now(),v=k,R.onAfterStep=new Map;break;case"workflow_success":p="success",u=i.durationMs,v=Date.now();break;case"workflow_error":p="error",d=i.error,u=i.durationMs,v=Date.now();break;case"step_start":{let m=O(i);s.set(m,{id:m,name:i.name,key:i.stepKey,startTs:i.ts,retryCount:0,timedOut:!1}),v=Date.now();break}case"step_success":{let m=O(i),b=s.get(m);if(b){let P={type:"step",id:b.id,name:b.name,key:b.key,state:"success",startTs:b.startTs,endTs:i.ts,durationMs:i.durationMs,...b.retryCount>0&&{retryCount:b.retryCount},...b.timedOut&&{timedOut:!0,timeoutMs:b.timeoutMs}};g(P),s.delete(m)}break}case"step_error":{let m=O(i),b=s.get(m);if(b){let P={type:"step",id:b.id,name:b.name,key:b.key,state:"error",startTs:b.startTs,endTs:i.ts,durationMs:i.durationMs,error:i.error,...b.retryCount>0&&{retryCount:b.retryCount},...b.timedOut&&{timedOut:!0,timeoutMs:b.timeoutMs}};g(P),s.delete(m)}break}case"step_aborted":{let m=O(i),b=s.get(m);if(b){let P={type:"step",id:b.id,name:b.name,key:b.key,state:"aborted",startTs:b.startTs,endTs:i.ts,durationMs:i.durationMs,...b.retryCount>0&&{retryCount:b.retryCount},...b.timedOut&&{timedOut:!0,timeoutMs:b.timeoutMs}};g(P),s.delete(m)}break}case"step_cache_hit":{let b={type:"step",id:O(i),name:i.name,key:i.stepKey,state:"cached",startTs:i.ts,endTs:i.ts,durationMs:0};g(b);break}case"step_cache_miss":break;case"step_complete":break;case"step_timeout":{let m=O(i),b=s.get(m);b&&(b.timedOut=!0,b.timeoutMs=i.timeoutMs),v=Date.now();break}case"step_retry":{let m=O(i),b=s.get(m);b&&(b.retryCount=(i.attempt??1)-1),v=Date.now();break}case"step_retries_exhausted":v=Date.now();break;case"step_skipped":{let b={type:"step",id:O(i),name:i.name,key:i.stepKey,state:"skipped",startTs:i.ts,endTs:i.ts,durationMs:0};g(b);break}case"hook_should_run":{let m={type:"shouldRun",state:"success",ts:i.ts,durationMs:i.durationMs,context:{result:i.result,skipped:i.skipped}};R.shouldRun=m,v=Date.now();break}case"hook_should_run_error":{let m={type:"shouldRun",state:"error",ts:i.ts,durationMs:i.durationMs,error:i.error};R.shouldRun=m,v=Date.now();break}case"hook_before_start":{let m={type:"onBeforeStart",state:"success",ts:i.ts,durationMs:i.durationMs,context:{result:i.result,skipped:i.skipped}};R.onBeforeStart=m,v=Date.now();break}case"hook_before_start_error":{let m={type:"onBeforeStart",state:"error",ts:i.ts,durationMs:i.durationMs,error:i.error};R.onBeforeStart=m,v=Date.now();break}case"hook_after_step":{let m={type:"onAfterStep",state:"success",ts:i.ts,durationMs:i.durationMs,context:{stepKey:i.stepKey}};R.onAfterStep.set(i.stepKey,m),v=Date.now();break}case"hook_after_step_error":{let m={type:"onAfterStep",state:"error",ts:i.ts,durationMs:i.durationMs,error:i.error,context:{stepKey:i.stepKey}};R.onAfterStep.set(i.stepKey,m),v=Date.now();break}}I(i)}function $(i){if(i.type==="scope_start")l.push({id:i.scopeId,name:i.name,type:i.scopeType,startTs:i.ts,children:[]}),v=Date.now();else if(i.type==="scope_end"){let m=l.pop();if(m){let b=m.type==="race"?{type:"race",id:m.id,name:m.name,state:C(m.children),startTs:m.startTs,endTs:i.ts,durationMs:i.durationMs,children:m.children,winnerId:i.winnerId}:{type:"parallel",id:m.id,name:m.name,state:C(m.children),startTs:m.startTs,endTs:i.ts,durationMs:i.durationMs,children:m.children,mode:m.type==="allSettled"?"allSettled":"all"};g(b)}}}function W(i){if(i.type==="decision_start")f.push({id:i.decisionId,name:i.name,condition:i.condition,decisionValue:i.decisionValue,startTs:i.ts,branches:new Map}),v=Date.now();else if(i.type==="decision_branch"){let m=f[f.length-1];if(m&&m.id===i.decisionId){let b=i.branchLabel,P=m.branches.get(b);P?P.taken=i.taken:m.branches.set(b,{label:i.branchLabel,condition:i.condition,taken:i.taken,children:[]}),v=Date.now()}}else if(i.type==="decision_end"){let m=f.pop();if(m&&m.id===i.decisionId){let b=Array.from(m.branches.values()),P={type:"decision",id:m.id,name:m.name,state:C(b.flatMap(F=>F.taken?F.children:[])),startTs:m.startTs,endTs:i.ts,durationMs:i.durationMs,condition:m.condition,decisionValue:m.decisionValue,branchTaken:i.branchTaken??m.branchTaken,branches:b};g(P)}}}function C(i){return i.length===0?"success":i.some(F=>F.state==="error")?"error":i.every(F=>F.state==="success"||F.state==="cached")?"success":i.some(F=>F.state==="running")?"running":"pending"}function D(){let i=[...h];for(let[,m]of s)i.push({type:"step",id:m.id,name:m.name,key:m.key,state:"running",startTs:m.startTs,...m.retryCount>0&&{retryCount:m.retryCount},...m.timedOut&&{timedOut:!0,timeoutMs:m.timeoutMs}});return i}function M(){let i=D();r&&(i=oe(i,t));let m={type:"workflow",id:n??le(),workflowId:n??"unknown",state:p,startTs:c,durationMs:u,children:i,error:d},b=R.shouldRun!==void 0||R.onBeforeStart!==void 0||R.onAfterStep.size>0;return{root:m,metadata:{createdAt:k,lastUpdatedAt:v},...b&&{hooks:R}}}function N(){n=void 0,c=void 0,p="pending",d=void 0,u=void 0,s.clear(),l.length=0,f.length=0,h=[],k=Date.now(),v=k,R={onAfterStep:new Map},T.length=0,B=0}function S(){return[...T]}function x(i){return T[i]}function E(i){return T[i]?.ir}function L(){T.length=0,B=0}return{handleEvent:w,handleScopeEvent:$,handleDecisionEvent:W,getIR:M,reset:N,getSnapshots:S,getSnapshotAt:x,getIRAt:E,clearSnapshots:L,get hasActiveSteps(){return s.size>0},get state(){return p},get snapshotCount(){return T.length},get snapshotsEnabled(){return a}}}function V(e){return e.type==="step"}function Ct(e){return e.type==="sequence"}function J(e){return e.type==="parallel"}function Y(e){return e.type==="race"}function X(e){return e.type==="decision"}function Ot(e){return"children"in e||e.type==="decision"&&"branches"in e}var ue="\x1B[0m",Ve="\x1B[1m",Ie="\x1B[2m",Ue="\x1B[31m",je="\x1B[32m",Ke="\x1B[33m",Ge="\x1B[34m",Ee="\x1B[90m",qe="\x1B[37m";function U(e,r){return r?`${r}${e}${ue}`:e}function te(e){return`${Ve}${e}${ue}`}function _(e){return`${Ie}${e}${ue}`}var j={pending:qe,running:Ke,success:je,error:Ue,aborted:Ee,cached:Ge,skipped:Ie+Ee};function Je(e){switch(e){case"pending":return"\u25CB";case"running":return"\u27F3";case"success":return"\u2713";case"error":return"\u2717";case"aborted":return"\u2298";case"cached":return"\u21BA";case"skipped":return"\u2298"}}function ne(e,r){let t=Je(e);return U(t,r[e])}function pe(e,r,t){return U(e,t[r])}function De(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}var y={topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502",teeRight:"\u251C",teeLeft:"\u2524",teeDown:"\u252C",teeUp:"\u2534",cross:"\u253C"},Z={cold:"\x1B[34m",cool:"\x1B[36m",neutral:"",warm:"\x1B[33m",hot:"\x1B[31m",critical:"\x1B[41m"},Ye="\x1B[0m";function Xe(e){return e<.2?Z.cold:e<.4?Z.cool:e<.6?Z.neutral:e<.8?Z.warm:e<.95?Z.hot:Z.critical}function Te(e,r){let t=Xe(r);return t?`${t}${e}${Ye}`:e}var Ne="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Ze(e,r=10){if(e.length===0)return"";let t=e.slice(-r),a=Math.min(...t),n=Math.max(...t)-a||1;return t.map(c=>{let p=(c-a)/n,d=Math.floor(p*(Ne.length-1));return Ne[d]}).join("")}function fe(e,r){let t=De(e).length,a=Math.max(0,r-t);return e+" ".repeat(a)}function Qe(e,r){if(!r)return y.horizontal.repeat(e);let t=` ${r} `,a=e-t.length;if(a<4)return y.horizontal.repeat(e);let o=2,n=a-o;return y.horizontal.repeat(o)+t+y.horizontal.repeat(n)}function Me(e,r,t){let a=e.state==="success"?U("\u2699",t.success):U("\u26A0",t.error),o=e.durationMs!==void 0?_(` [${H(e.durationMs)}]`):"",n="";e.type==="shouldRun"&&e.context?.skipped?n=_(" \u2192 workflow skipped"):e.type==="shouldRun"&&e.context?.result===!0?n=_(" \u2192 proceed"):e.type==="onBeforeStart"&&e.context?.skipped?n=_(" \u2192 workflow skipped"):e.type==="onAfterStep"&&e.context?.stepKey&&(n=_(` (${e.context.stepKey})`));let c=e.state==="error"&&e.error?_(` error: ${String(e.error)}`):"";return`${a} ${_(r)}${n}${o}${c}`}function et(e,r){let t=[];return e.shouldRun&&t.push(Me(e.shouldRun,"shouldRun",r)),e.onBeforeStart&&t.push(Me(e.onBeforeStart,"onBeforeStart",r)),t.length>0&&t.push(_("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),t}function Q(){return{name:"ascii",supportsLive:!0,render(e,r){let t={...j,...r.colors},a=r.terminalWidth??60,o=a-4,n=[],c=e.root.name??"workflow",p=te(c);if(n.push(`${y.topLeft}${Qe(a-2,p)}${y.topRight}`),n.push(`${y.vertical}${" ".repeat(a-2)}${y.vertical}`),e.hooks){let u=et(e.hooks,t);for(let s of u)n.push(`${y.vertical} ${fe(s,o)}${y.vertical}`)}let d=ie(e.root.children,r,t,0,e.hooks);for(let u of d)n.push(`${y.vertical} ${fe(u,o)}${y.vertical}`);if(n.push(`${y.vertical}${" ".repeat(a-2)}${y.vertical}`),e.root.durationMs!==void 0&&r.showTimings){let u=e.root.state==="success"?"Completed":"Failed",l=`${pe(u,e.root.state,t)} in ${H(e.root.durationMs)}`;n.push(`${y.vertical} ${fe(l,o)}${y.vertical}`),n.push(`${y.vertical}${" ".repeat(a-2)}${y.vertical}`)}return n.push(`${y.bottomLeft}${y.horizontal.repeat(a-2)}${y.bottomRight}`),n.join(`
2
- `)}}}function ie(e,r,t,a,o){let n=[];for(let c of e)V(c)?n.push(me(c,r,t,o)):J(c)?n.push(...tt(c,r,t,a,o)):Y(c)?n.push(...nt(c,r,t,a,o)):X(c)&&n.push(...rt(c,r,t,a,o));return n}function me(e,r,t,a){let o=ne(e.state,t),n=e.name??e.key??"step",c=r,p=e.name??e.id,d=c.showHeatmap&&c.heatmapData?c.heatmapData.heat.get(e.id)??c.heatmapData.heat.get(p):void 0,u;d!==void 0?u=Te(n,d):u=pe(n,e.state,t);let s=`${o} ${u}`;if(r.showKeys&&e.key&&(s+=_(` [key: ${e.key}]`)),e.input!==void 0){let l=typeof e.input=="string"?e.input:JSON.stringify(e.input).slice(0,30);s+=_(` [in: ${l}${l.length>=30?"...":""}]`)}if(e.output!==void 0&&e.state==="success"){let l=typeof e.output=="string"?e.output:JSON.stringify(e.output).slice(0,30);s+=_(` [out: ${l}${l.length>=30?"...":""}]`)}if(r.showTimings&&e.durationMs!==void 0){let l=H(e.durationMs),f=d!==void 0?Te(`[${l}]`,d):_(`[${l}]`);s+=` ${f}`}if(c.showSparklines&&c.timingHistory){let l=c.timingHistory.get(p);l&&l.length>1&&(s+=` ${_(Ze(l))}`)}if(e.retryCount!==void 0&&e.retryCount>0&&(s+=_(` [${e.retryCount} ${e.retryCount===1?"retry":"retries"}]`)),e.timedOut){let l=e.timeoutMs!==void 0?` ${e.timeoutMs}ms`:"";s+=_(` [timeout${l}]`)}if(a&&e.key&&a.onAfterStep.has(e.key)){let l=a.onAfterStep.get(e.key),f=l.state==="success"?U("\u2699",t.success):U("\u26A0",t.error),h=l.durationMs!==void 0?_(` ${H(l.durationMs)}`):"";s+=` ${f}${h}`}return s}function tt(e,r,t,a,o){let n=[],c=" ".repeat(a),p=ne(e.state,t),d=e.name??"parallel",u=e.mode==="allSettled"?" (allSettled)":"";if(n.push(`${c}${y.teeRight}${y.teeDown}${y.horizontal} ${p} ${te(d)}${u}`),e.children.length===0)n.push(`${c}${y.vertical} ${_("(operations not individually tracked)")}`),n.push(`${c}${y.vertical} ${_("(wrap each operation with step() to see individual steps)")}`);else for(let s=0;s<e.children.length;s++){let l=e.children[s],h=s===e.children.length-1?`${c}${y.vertical} ${y.bottomLeft}`:`${c}${y.vertical} ${y.teeRight}`;if(V(l))n.push(`${h} ${me(l,r,t,o)}`);else{let k=ie([l],r,t,a+1,o);for(let v of k)n.push(`${c}${y.vertical} ${v}`)}}return r.showTimings&&e.durationMs!==void 0&&n.push(`${c}${y.bottomLeft}${y.horizontal}${y.horizontal} ${_(`[${H(e.durationMs)}]`)}`),n}function nt(e,r,t,a,o){let n=[],c=" ".repeat(a),p=ne(e.state,t),d=e.name??"race";if(n.push(`${c}${y.teeRight}\u26A1 ${p} ${te(d)}`),e.children.length===0)n.push(`${c}${y.vertical} ${_("(operations not individually tracked)")}`),n.push(`${c}${y.vertical} ${_("(wrap each operation with step() to see individual steps)")}`);else for(let u=0;u<e.children.length;u++){let s=e.children[u],f=u===e.children.length-1?`${c}${y.vertical} ${y.bottomLeft}`:`${c}${y.vertical} ${y.teeRight}`,k=e.winnerId&&s.id===e.winnerId?_(" (winner)"):"";if(V(s))n.push(`${f} ${me(s,r,t,o)}${k}`);else{let v=ie([s],r,t,a+1,o);for(let R of v)n.push(`${c}${y.vertical} ${R}`)}}return r.showTimings&&e.durationMs!==void 0&&n.push(`${c}${y.bottomLeft}${y.horizontal}${y.horizontal} ${_(`[${H(e.durationMs)}]`)}`),n}function rt(e,r,t,a,o){let n=[],c=" ".repeat(a),p=ne(e.state,t),d=e.name??"decision",u=e.condition?_(` (${e.condition})`):"",s=e.decisionValue!==void 0?_(` = ${String(e.decisionValue)}`):"",l=e.branchTaken!==void 0?_(` \u2192 ${String(e.branchTaken)}`):"";n.push(`${c}${y.teeRight}${y.teeDown}${y.horizontal} ${p} ${te(d)}${u}${s}${l}`);for(let f=0;f<e.branches.length;f++){let h=e.branches[f],v=f===e.branches.length-1?`${c}${y.vertical} ${y.bottomLeft}`:`${c}${y.vertical} ${y.teeRight}`,R=h.taken?"\u2713":"\u2298",T=h.taken?t.success:t.skipped,B=U(`${R} ${h.label}`,T),O=h.condition?_(` (${h.condition})`):"";if(n.push(`${v} ${B}${O}`),h.children.length>0){let g=ie(h.children,r,t,a+1,o);for(let I of g)n.push(`${c}${y.vertical} ${I}`)}else h.taken||n.push(`${c}${y.vertical} ${_("(skipped)")}`)}return r.showTimings&&e.durationMs!==void 0&&n.push(`${c}${y.bottomLeft}${y.horizontal}${y.horizontal} ${_(`[${H(e.durationMs)}]`)}`),n}function he(e){let r=[];for(let t of e)if(r.push(t),"children"in t&&Array.isArray(t.children)&&r.push(...he(t.children)),"branches"in t)for(let a of t.branches)r.push(...he(a.children));return r}function ae(e,r){if(e.length===0)return 0;let t=Math.floor(e.length*r);return e[Math.min(t,e.length-1)]}function ge(e){return e<.2?"cold":e<.4?"cool":e<.6?"neutral":e<.8?"warm":e<.95?"hot":"critical"}function ve(){let e=new Map,r=new Map,t=new Map,a=new Map,o=[];function n(g){return g.name??g.stepKey??g.stepId??"unknown"}function c(g){let I=new Map;for(let w of g)switch(w.type){case"step_start":{let $=n(w);I.set($,{retried:!1,timedOut:!1});break}case"step_retry":{let $=n(w),W=I.get($);W&&(W.retried=!0);break}case"step_timeout":{let $=n(w),W=I.get($);W&&(W.timedOut=!0);let C=a.get($)??{timedOut:0,total:0};C.timedOut++,C.total++,a.set($,C);break}case"step_success":{let $=n(w),W=I.get($),C=e.get($)??[];C.push(w.durationMs),e.set($,C);let D=r.get($)??{retried:0,total:0};D.total++,W?.retried&&D.retried++,r.set($,D);let M=t.get($)??{errors:0,total:0};M.total++,t.set($,M),I.delete($);break}case"step_error":{let $=n(w),W=I.get($),C=e.get($)??[];C.push(w.durationMs),e.set($,C);let D=r.get($)??{retried:0,total:0};D.total++,W?.retried&&D.retried++,r.set($,D);let M=t.get($)??{errors:0,total:0};M.total++,M.errors++,t.set($,M),I.delete($);break}}}function p(g){c(g.events)}function d(g){o.push(g)}function u(g){o.length>0&&(c(o),o=[])}function s(g){let I=e.get(g);if(!I||I.length===0)return;let w=[...I].sort((S,x)=>S-x),W=w.reduce((S,x)=>S+x,0)/w.length,C=w.reduce((S,x)=>S+(x-W)**2,0)/w.length,D=r.get(g)??{retried:0,total:1},M=t.get(g)??{errors:0,total:1},N=a.get(g)??{timedOut:0,total:1};return{nodeId:g,avgDurationMs:W,minDurationMs:w[0],maxDurationMs:w[w.length-1],stdDevMs:Math.sqrt(C),samples:w.length,retryRate:D.total>0?D.retried/D.total:0,timeoutRate:N.total>0?N.timedOut/N.total:0,errorRate:M.total>0?M.errors/M.total:0,percentiles:{p50:ae(w,.5),p90:ae(w,.9),p95:ae(w,.95),p99:ae(w,.99)}}}function l(g){return s(g)}function f(g,I="duration"){let w=new Map,$=he(g.root.children),W=[];for(let x of $){let E=x.name??x.id,L=s(E);if(L){let i;switch(I){case"duration":i=L.avgDurationMs;break;case"retryRate":i=L.retryRate;break;case"errorRate":i=L.errorRate;break}W.push({id:x.id,value:i})}}if(W.length===0)return{heat:w,metric:I,stats:{min:0,max:0,mean:0,threshold:0}};let C=W.map(x=>x.value),D=Math.min(...C),M=Math.max(...C),N=C.reduce((x,E)=>x+E,0)/C.length,S=M-D||1;for(let{id:x,value:E}of W)w.set(x,(E-D)/S);return{heat:w,metric:I,stats:{min:D,max:M,mean:N,threshold:N+(M-N)*.5}}}function h(){let g=new Map;for(let I of e.keys()){let w=s(I);w&&g.set(I,w)}return g}function k(g=10){return[...h().values()].sort((w,$)=>$.avgDurationMs-w.avgDurationMs).slice(0,g)}function v(g=10){return[...h().values()].filter(w=>w.errorRate>0).sort((w,$)=>$.errorRate-w.errorRate).slice(0,g)}function R(g=10){return[...h().values()].filter(w=>w.retryRate>0).sort((w,$)=>$.retryRate-w.retryRate).slice(0,g)}function T(){return JSON.stringify({timingData:Object.fromEntries(e),retryData:Object.fromEntries(r),errorData:Object.fromEntries(t),timeoutData:Object.fromEntries(a)})}function B(g){let I=JSON.parse(g);e.clear(),r.clear(),t.clear(),a.clear();for(let[w,$]of Object.entries(I.timingData??{}))e.set(w,$);for(let[w,$]of Object.entries(I.retryData??{}))r.set(w,$);for(let[w,$]of Object.entries(I.errorData??{}))t.set(w,$);for(let[w,$]of Object.entries(I.timeoutData??{}))a.set(w,$)}function O(){e.clear(),r.clear(),t.clear(),a.clear(),o=[]}return{addRun:p,addEvent:d,finalizeRun:u,getNodePerformance:l,getHeatmap:f,getSlowestNodes:k,getErrorProneNodes:v,getRetryProneNodes:R,getAllPerformance:h,exportData:T,importData:B,clear:O}}function ot(){return[" classDef pending fill:#f3f4f6,stroke:#9ca3af,stroke-width:2px,color:#374151"," classDef running fill:#fef3c7,stroke:#f59e0b,stroke-width:3px,color:#92400e"," classDef success fill:#d1fae5,stroke:#10b981,stroke-width:3px,color:#065f46"," classDef error fill:#fee2e2,stroke:#ef4444,stroke-width:3px,color:#991b1b"," classDef aborted fill:#f3f4f6,stroke:#6b7280,stroke-width:2px,color:#4b5563,stroke-dasharray: 5 5"," classDef cached fill:#dbeafe,stroke:#3b82f6,stroke-width:3px,color:#1e40af"," classDef skipped fill:#f9fafb,stroke:#d1d5db,stroke-width:2px,color:#6b7280,stroke-dasharray: 5 5"]}function it(){return[" classDef heat_cold fill:#dbeafe,stroke:#3b82f6,stroke-width:2px,color:#1e40af"," classDef heat_cool fill:#ccfbf1,stroke:#14b8a6,stroke-width:2px,color:#0f766e"," classDef heat_neutral fill:#f3f4f6,stroke:#6b7280,stroke-width:2px,color:#374151"," classDef heat_warm fill:#fef3c7,stroke:#f59e0b,stroke-width:2px,color:#92400e"," classDef heat_hot fill:#fed7aa,stroke:#f97316,stroke-width:3px,color:#c2410c"," classDef heat_critical fill:#fecaca,stroke:#ef4444,stroke-width:3px,color:#b91c1c"]}function at(e){return`heat_${e}`}function st(){return[" classDef hook_success fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e"," classDef hook_error fill:#fef2f2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d"]}function ct(e,r,t){let a;if(e.shouldRun){let o="hook_shouldRun",n=e.shouldRun.state==="success"?"hook_success":"hook_error",c=e.shouldRun.state==="success"?"\u2699":"\u26A0",p=t.showTimings&&e.shouldRun.durationMs!==void 0?` ${H(e.shouldRun.durationMs)}`:"",d=e.shouldRun.context?.skipped?"\\nskipped workflow":e.shouldRun.context?.result===!0?"\\nproceed":"";r.push(` ${o}[["${c} shouldRun${d}${p}"]]:::${n}`),a=o}if(e.onBeforeStart){let o="hook_beforeStart",n=e.onBeforeStart.state==="success"?"hook_success":"hook_error",c=e.onBeforeStart.state==="success"?"\u2699":"\u26A0",p=t.showTimings&&e.onBeforeStart.durationMs!==void 0?` ${H(e.onBeforeStart.durationMs)}`:"",d=e.onBeforeStart.context?.skipped?"\\nskipped workflow":"";r.push(` ${o}[["${c} onBeforeStart${d}${p}"]]:::${n}`),a&&r.push(` ${a} --> ${o}`),a=o}return{lastHookId:a}}var _e=0;function re(e="node"){return`${e}_${++_e}`}function dt(){_e=0}function z(e){return e.replace(/[{}[\]()]/g,"").replace(/[<>]/g,"").replace(/"/g,"'").trim()}function Ce(e){return z(e).replace(/[[\]]/g,"")}function se(){return{name:"mermaid",supportsLive:!1,render(e,r){dt();let t=[],a=r;t.push("flowchart TD");let o;e.hooks&&(o=ct(e.hooks,t,r).lastHookId);let n="start";t.push(` ${n}(("\u25B6 Start"))`),o&&t.push(` ${o} --> ${n}`);let c=n;for(let p of e.root.children){let d=ce(p,r,t,a,e.hooks);t.push(` ${c} --> ${d.entryId}`),c=d.exitId}if(e.root.state==="success"||e.root.state==="error"){let p="finish",d=e.root.state==="success"?"\u2713":"\u2717",u=e.root.state==="success"?"Done":"Failed",s=`(("${d} ${u}"))`,l=e.root.state==="success"?":::success":":::error";t.push(` ${p}${s}${l}`),t.push(` ${c} --> ${p}`)}return t.push(""),t.push(...ot()),a.showHeatmap&&t.push(...it()),e.hooks&&t.push(...st()),t.join(`
3
- `)}}}function ce(e,r,t,a,o){if(V(e))return lt(e,r,t,a,o);if(J(e))return ut(e,r,t,a,o);if(Y(e))return pt(e,r,t,a,o);if(X(e))return ft(e,r,t,a,o);let n=re("unknown");return t.push(` ${n}[Unknown Node]`),{entryId:n,exitId:n}}function lt(e,r,t,a,o){let n=e.key?`step_${e.key.replace(/[^a-zA-Z0-9]/g,"_")}`:re("step"),c=z(e.name??e.key??"Step"),p=r.showTimings&&e.durationMs!==void 0?` ${H(e.durationMs)}`:"",d="";switch(e.state){case"success":d="\u2713 ";break;case"error":d="\u2717 ";break;case"cached":d="\u{1F4BE} ";break;case"running":d="\u23F3 ";break;case"skipped":d="\u2298 ";break}let u="";if(e.input!==void 0){let T=typeof e.input=="string"?z(e.input):z(JSON.stringify(e.input).slice(0,20));u+=`\\nin: ${T}`}if(e.output!==void 0&&e.state==="success"){let T=typeof e.output=="string"?z(e.output):z(JSON.stringify(e.output).slice(0,20));u+=`\\nout: ${T}`}let s="";if(e.retryCount!==void 0&&e.retryCount>0&&(s+=`\\n\u21BB ${e.retryCount} retr${e.retryCount===1?"y":"ies"}`),e.timedOut){let T=e.timeoutMs!==void 0?`${e.timeoutMs}ms`:"";s+=`\\n\u23F1 timeout ${T}`}let l="";if(o&&e.key&&o.onAfterStep.has(e.key)){let T=o.onAfterStep.get(e.key),B=T.state==="success"?"\u2699":"\u26A0",O=r.showTimings&&T.durationMs!==void 0?` ${H(T.durationMs)}`:"";l=`\\n${B} hook${O}`}let f=(d+c+u+s+l+p).trim(),h,k=e.name??e.id,v=a?.showHeatmap&&a.heatmapData?a.heatmapData.heat.get(e.id)??a.heatmapData.heat.get(k):void 0;if(v!==void 0){let T=ge(v);h=at(T)}else h=e.state;let R;switch(e.state){case"error":R=`{{${f}}}`;break;case"cached":R=`[(${f})]`;break;case"skipped":R=`[${f}]:::skipped`;break;default:R=`[${f}]`}return t.push(` ${n}${R}:::${h}`),{entryId:n,exitId:n}}function ut(e,r,t,a,o){let n=re("parallel"),c=`${n}_fork`,p=`${n}_join`,d=Ce(e.name??"Parallel"),u=e.mode==="allSettled"?" (allSettled)":"";if(e.children.length===0){let f=n,h=z(`${d}${u}`),k="operations not individually tracked",v=r.showTimings&&e.durationMs!==void 0?` ${H(e.durationMs)}`:"";return t.push(` ${f}[${h}${v}\\n${k}]:::${e.state}`),{entryId:f,exitId:f}}t.push(` subgraph ${n}["${d}${u}"]`),t.push(" direction TB"),t.push(` ${c}{"\u26A1 Fork"}`);let s=[];for(let f of e.children){let h=ce(f,r,t,a,o);t.push(` ${c} --> ${h.entryId}`),s.push(h.exitId)}t.push(` ${p}{"\u2713 Join"}`);for(let f of s)t.push(` ${f} --> ${p}`);t.push(" end");let l=e.state;return t.push(` class ${n} ${l}`),{entryId:c,exitId:p}}function pt(e,r,t,a,o){let n=re("race"),c=`${n}_start`,p=`${n}_end`,d=Ce(e.name??"Race");if(e.children.length===0){let f=n,h=z(d),k="operations not individually tracked",v=r.showTimings&&e.durationMs!==void 0?` ${H(e.durationMs)}`:"";return t.push(` ${f}[\u26A1 ${h}${v}\\n${k}]:::${e.state}`),{entryId:f,exitId:f}}t.push(` subgraph ${n}["\u26A1 ${d}"]`),t.push(" direction TB"),t.push(` ${c}(("\u{1F3C1} Start"))`);let u=[],s;for(let f of e.children){let h=ce(f,r,t,a,o),k=V(f)&&e.winnerId===f.id;t.push(` ${c} --> ${h.entryId}`),k&&(s=h.exitId),u.push({exitId:h.exitId,isWinner:k})}t.push(` ${p}(("\u2713 First"))`);for(let{exitId:f,isWinner:h}of u)h&&s?t.push(` ${f} ==>|\u{1F3C6} Winner| ${p}`):e.winnerId?t.push(` ${f} -. cancelled .-> ${p}`):t.push(` ${f} --> ${p}`);t.push(" end");let l=e.state;return t.push(` class ${n} ${l}`),{entryId:c,exitId:p}}function ft(e,r,t,a,o){let n=e.key?`decision_${e.key.replace(/[^a-zA-Z0-9]/g,"_")}`:re("decision"),c=z(e.condition??"condition"),p=e.decisionValue!==void 0?` = ${z(String(e.decisionValue)).slice(0,30)}`:"",d=`${c}${p}`.trim();t.push(` ${n}{${d}}`);let u=[],s;for(let l of e.branches){let f=`${n}_${l.label.replace(/[^a-zA-Z0-9]/g,"_")}`,h=z(l.label),k=l.taken?`${h} \u2713`:`${h} skipped`,v=l.taken?":::success":":::skipped";t.push(` ${f}[${k}]${v}`);let R=l.condition?`|${z(l.condition).replace(/\|/g,"")}|`:"";if(t.push(` ${n} -->${R} ${f}`),l.children.length>0){let T=f;for(let B of l.children){let O=ce(B,r,t,a,o);t.push(` ${T} --> ${O.entryId}`),T=O.exitId}u.push(T),l.taken&&(s=T)}else u.push(f),l.taken&&(s=f)}return s?{entryId:n,exitId:s}:{entryId:n,exitId:n}}function Oe(e){let r={bg:"#ffffff",bgSecondary:"#f8f9fa",text:"#212529",textMuted:"#6c757d",border:"#dee2e6",primary:"#0d6efd",success:"#198754",error:"#dc3545",warning:"#ffc107",info:"#0dcaf0",muted:"#6c757d",nodePending:"#e9ecef",nodeRunning:"#fff3cd",nodeSuccess:"#d1e7dd",nodeError:"#f8d7da",nodeAborted:"#e9ecef",nodeCached:"#cfe2ff",nodeSkipped:"#f8f9fa",heatCold:"#0d6efd",heatCool:"#0dcaf0",heatNeutral:"#6c757d",heatWarm:"#ffc107",heatHot:"#fd7e14",heatCritical:"#dc3545"},t={bg:"#212529",bgSecondary:"#343a40",text:"#f8f9fa",textMuted:"#adb5bd",border:"#495057",primary:"#0d6efd",success:"#198754",error:"#dc3545",warning:"#ffc107",info:"#0dcaf0",muted:"#6c757d",nodePending:"#495057",nodeRunning:"#664d03",nodeSuccess:"#0f5132",nodeError:"#842029",nodeAborted:"#495057",nodeCached:"#084298",nodeSkipped:"#343a40",heatCold:"#0d6efd",heatCool:"#0dcaf0",heatNeutral:"#6c757d",heatWarm:"#ffc107",heatHot:"#fd7e14",heatCritical:"#dc3545"},a=n=>`
4
- --bg: ${n.bg};
5
- --bg-secondary: ${n.bgSecondary};
6
- --text: ${n.text};
7
- --text-muted: ${n.textMuted};
8
- --border: ${n.border};
9
- --primary: ${n.primary};
10
- --success: ${n.success};
11
- --error: ${n.error};
12
- --warning: ${n.warning};
13
- --info: ${n.info};
14
- --muted: ${n.muted};
15
- --node-pending: ${n.nodePending};
16
- --node-running: ${n.nodeRunning};
17
- --node-success: ${n.nodeSuccess};
18
- --node-error: ${n.nodeError};
19
- --node-aborted: ${n.nodeAborted};
20
- --node-cached: ${n.nodeCached};
21
- --node-skipped: ${n.nodeSkipped};
22
- --heat-cold: ${n.heatCold};
23
- --heat-cool: ${n.heatCool};
24
- --heat-neutral: ${n.heatNeutral};
25
- --heat-warm: ${n.heatWarm};
26
- --heat-hot: ${n.heatHot};
27
- --heat-critical: ${n.heatCritical};
28
- `,o;return e==="auto"?o=`
1
+ var yn=Object.create;var it=Object.defineProperty;var vn=Object.getOwnPropertyDescriptor;var wn=Object.getOwnPropertyNames;var bn=Object.getPrototypeOf,Sn=Object.prototype.hasOwnProperty;var A=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var xn=(e,t)=>()=>(e&&(t=e(e=0)),t);var V=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_n=(e,t)=>{for(var r in t)it(e,r,{get:t[r],enumerable:!0})},kn=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of wn(t))!Sn.call(e,n)&&n!==r&&it(e,n,{get:()=>t[n],enumerable:!(o=vn(t,n))||o.enumerable});return e};var Ie=(e,t,r)=>(r=e!=null?yn(bn(e)):{},kn(t||!e||!e.__esModule?it(r,"default",{value:e,enumerable:!0}):r,e));var ee=V((Ei,cr)=>{"use strict";var ir=["nodebuffer","arraybuffer","fragments"],ar=typeof Blob<"u";ar&&ir.push("blob");cr.exports={BINARY_TYPES:ir,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ar,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Oe=V((Ri,Ge)=>{"use strict";var{EMPTY_BUFFER:vo}=ee(),St=Buffer[Symbol.species];function wo(e,t){if(e.length===0)return vo;if(e.length===1)return e[0];let r=Buffer.allocUnsafe(t),o=0;for(let n=0;n<e.length;n++){let s=e[n];r.set(s,o),o+=s.length}return o<t?new St(r.buffer,r.byteOffset,o):r}function lr(e,t,r,o,n){for(let s=0;s<n;s++)r[o+s]=e[s]^t[s&3]}function dr(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}function bo(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function xt(e){if(xt.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new St(e):ArrayBuffer.isView(e)?t=new St(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),xt.readOnly=!1),t}Ge.exports={concat:wo,mask:lr,toArrayBuffer:bo,toBuffer:xt,unmask:dr};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=A("bufferutil");Ge.exports.mask=function(t,r,o,n,s){s<48?lr(t,r,o,n,s):e.mask(t,r,o,n,s)},Ge.exports.unmask=function(t,r){t.length<32?dr(t,r):e.unmask(t,r)}}catch{}});var pr=V((Ti,fr)=>{"use strict";var ur=Symbol("kDone"),_t=Symbol("kRun"),kt=class{constructor(t){this[ur]=()=>{this.pending--,this[_t]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[_t]()}[_t](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[ur])}}};fr.exports=kt});var Le=V((Ii,yr)=>{"use strict";var Ce=A("zlib"),hr=Oe(),So=pr(),{kStatusCode:mr}=ee(),xo=Buffer[Symbol.species],_o=Buffer.from([0,0,255,255]),Ye=Symbol("permessage-deflate"),te=Symbol("total-length"),Se=Symbol("callback"),de=Symbol("buffers"),xe=Symbol("error"),Ke,Et=class{constructor(t,r,o){if(this._maxPayload=o|0,this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!r,this._deflate=null,this._inflate=null,this.params=null,!Ke){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ke=new So(n)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};return this._options.serverNoContextTakeover&&(t.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(t.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(t.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?t.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(t.client_max_window_bits=!0),t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let t=this._deflate[Se];this._deflate.close(),this._deflate=null,t&&t(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let r=this._options,o=t.find(n=>!(r.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>n.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!n.client_max_window_bits));if(!o)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(o.server_no_context_takeover=!0),r.clientNoContextTakeover&&(o.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(o.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?o.client_max_window_bits=r.clientMaxWindowBits:(o.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete o.client_max_window_bits,o}acceptAsClient(t){let r=t[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(t){return t.forEach(r=>{Object.keys(r).forEach(o=>{let n=r[o];if(n.length>1)throw new Error(`Parameter "${o}" must have only a single value`);if(n=n[0],o==="client_max_window_bits"){if(n!==!0){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else if(o==="server_max_window_bits"){let s=+n;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${o}": ${n}`);n=s}else if(o==="client_no_context_takeover"||o==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${o}": ${n}`)}else throw new Error(`Unknown parameter "${o}"`);r[o]=n})}),t}decompress(t,r,o){Ke.add(n=>{this._decompress(t,r,(s,i)=>{n(),o(s,i)})})}compress(t,r,o){Ke.add(n=>{this._compress(t,r,(s,i)=>{n(),o(s,i)})})}_decompress(t,r,o){let n=this._isServer?"client":"server";if(!this._inflate){let s=`${n}_max_window_bits`,i=typeof this.params[s]!="number"?Ce.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Ce.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Ye]=this,this._inflate[te]=0,this._inflate[de]=[],this._inflate.on("error",Eo),this._inflate.on("data",gr)}this._inflate[Se]=o,this._inflate.write(t),r&&this._inflate.write(_o),this._inflate.flush(()=>{let s=this._inflate[xe];if(s){this._inflate.close(),this._inflate=null,o(s);return}let i=hr.concat(this._inflate[de],this._inflate[te]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[te]=0,this._inflate[de]=[],r&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),o(null,i)})}_compress(t,r,o){let n=this._isServer?"server":"client";if(!this._deflate){let s=`${n}_max_window_bits`,i=typeof this.params[s]!="number"?Ce.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Ce.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[te]=0,this._deflate[de]=[],this._deflate.on("data",ko)}this._deflate[Se]=o,this._deflate.write(t),this._deflate.flush(Ce.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=hr.concat(this._deflate[de],this._deflate[te]);r&&(s=new xo(s.buffer,s.byteOffset,s.length-4)),this._deflate[Se]=null,this._deflate[te]=0,this._deflate[de]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,s)})}};yr.exports=Et;function ko(e){this[de].push(e),this[te]+=e.length}function gr(e){if(this[te]+=e.length,this[Ye]._maxPayload<1||this[te]<=this[Ye]._maxPayload){this[de].push(e);return}this[xe]=new RangeError("Max payload size exceeded"),this[xe].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[xe][mr]=1009,this.removeListener("data",gr),this.reset()}function Eo(e){if(this[Ye]._inflate=null,this[xe]){this[Se](this[xe]);return}e[mr]=1007,this[Se](e)}});var _e=V(($i,Je)=>{"use strict";var{isUtf8:vr}=A("buffer"),{hasBlob:Ro}=ee(),To=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Io(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function Rt(e){let t=e.length,r=0;for(;r<t;)if((e[r]&128)===0)r++;else if((e[r]&224)===192){if(r+1===t||(e[r+1]&192)!==128||(e[r]&254)===192)return!1;r+=2}else if((e[r]&240)===224){if(r+2>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||e[r]===224&&(e[r+1]&224)===128||e[r]===237&&(e[r+1]&224)===160)return!1;r+=3}else if((e[r]&248)===240){if(r+3>=t||(e[r+1]&192)!==128||(e[r+2]&192)!==128||(e[r+3]&192)!==128||e[r]===240&&(e[r+1]&240)===128||e[r]===244&&e[r+1]>143||e[r]>244)return!1;r+=4}else return!1;return!0}function $o(e){return Ro&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}Je.exports={isBlob:$o,isValidStatusCode:Io,isValidUTF8:Rt,tokenChars:To};if(vr)Je.exports.isValidUTF8=function(e){return e.length<24?Rt(e):vr(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=A("utf-8-validate");Je.exports.isValidUTF8=function(t){return t.length<32?Rt(t):e(t)}}catch{}});var Dt=V((Ni,Er)=>{"use strict";var{Writable:No}=A("stream"),wr=Le(),{BINARY_TYPES:Do,EMPTY_BUFFER:br,kStatusCode:Oo,kWebSocket:Co}=ee(),{concat:Tt,toArrayBuffer:Lo,unmask:Mo}=Oe(),{isValidStatusCode:Bo,isValidUTF8:Sr}=_e(),Xe=Buffer[Symbol.species],G=0,xr=1,_r=2,kr=3,It=4,$t=5,Ze=6,Nt=class extends No{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||Do[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[Co]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=G}_write(t,r,o){if(this._opcode===8&&this._state==G)return o();this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(o)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let o=this._buffers[0];return this._buffers[0]=new Xe(o.buffer,o.byteOffset+t,o.length-t),new Xe(o.buffer,o.byteOffset,t)}let r=Buffer.allocUnsafe(t);do{let o=this._buffers[0],n=r.length-t;t>=o.length?r.set(this._buffers.shift(),n):(r.set(new Uint8Array(o.buffer,o.byteOffset,t),n),this._buffers[0]=new Xe(o.buffer,o.byteOffset+t,o.length-t)),t-=o.length}while(t>0);return r}startLoop(t){this._loop=!0;do switch(this._state){case G:this.getInfo(t);break;case xr:this.getPayloadLength16(t);break;case _r:this.getPayloadLength64(t);break;case kr:this.getMask();break;case It:this.getData(t);break;case $t:case Ze:this._loop=!1;return}while(this._loop);this._errored||t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(n);return}let o=(r[0]&64)===64;if(o&&!this._extensions[wr.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(n);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(n);return}this._compressed=o}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(n);return}if(o){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(n);return}this._payloadLength===126?this._state=xr:this._payloadLength===127?this._state=_r:this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),o=r.readUInt32BE(0);if(o>Math.pow(2,21)-1){let n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(n);return}this._payloadLength=o*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(r);return}this._masked?this._state=kr:this._state=It}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=It}getData(t){let r=br;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Mo(r,this._mask)}if(this._opcode>7){this.controlMessage(r,t);return}if(this._compressed){this._state=$t,this.decompress(r,t);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(t)}decompress(t,r){this._extensions[wr.extensionName].decompress(t,this._fin,(n,s)=>{if(n)return r(n);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(s)}this.dataMessage(r),this._state===G&&this.startLoop(r)})}dataMessage(t){if(!this._fin){this._state=G;return}let r=this._messageLength,o=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let n;this._binaryType==="nodebuffer"?n=Tt(o,r):this._binaryType==="arraybuffer"?n=Lo(Tt(o,r)):this._binaryType==="blob"?n=new Blob(o):n=o,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=G):(this._state=Ze,setImmediate(()=>{this.emit("message",n,!0),this._state=G,this.startLoop(t)}))}else{let n=Tt(o,r);if(!this._skipUTF8Validation&&!Sr(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(s);return}this._state===$t||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=G):(this._state=Ze,setImmediate(()=>{this.emit("message",n,!1),this._state=G,this.startLoop(t)}))}}controlMessage(t,r){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,br),this.end();else{let o=t.readUInt16BE(0);if(!Bo(o)){let s=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let n=new Xe(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!Sr(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",o,n),this.end()}this._state=G;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=G):(this._state=Ze,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=G,this.startLoop(r)}))}createError(t,r,o,n,s){this._loop=!1,this._errored=!0;let i=new t(o?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=s,i[Oo]=n,i}};Er.exports=Nt});var Lt=V((Oi,Ir)=>{"use strict";var{Duplex:Di}=A("stream"),{randomFillSync:Wo}=A("crypto"),Rr=Le(),{EMPTY_BUFFER:Po,kWebSocket:Ao,NOOP:Fo}=ee(),{isBlob:ke,isValidStatusCode:Ho}=_e(),{mask:Tr,toBuffer:he}=Oe(),K=Symbol("kByteLength"),Uo=Buffer.alloc(4),Qe=8*1024,me,Ee=Qe,X=0,zo=1,Vo=2,Ot=class e{constructor(t,r,o){this._extensions=r||{},o&&(this._generateMask=o,this._maskBuffer=Buffer.alloc(4)),this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=X,this.onerror=Fo,this[Ao]=void 0}static frame(t,r){let o,n=!1,s=2,i=!1;r.mask&&(o=r.maskBuffer||Uo,r.generateMask?r.generateMask(o):(Ee===Qe&&(me===void 0&&(me=Buffer.alloc(Qe)),Wo(me,0,Qe),Ee=0),o[0]=me[Ee++],o[1]=me[Ee++],o[2]=me[Ee++],o[3]=me[Ee++]),i=(o[0]|o[1]|o[2]|o[3])===0,s=6);let a;typeof t=="string"?(!r.mask||i)&&r[K]!==void 0?a=r[K]:(t=Buffer.from(t),a=t.length):(a=t.length,n=r.mask&&r.readOnly&&!i);let l=a;a>=65536?(s+=8,l=127):a>125&&(s+=2,l=126);let c=Buffer.allocUnsafe(n?a+s:s);return c[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),r.mask?(c[1]|=128,c[s-4]=o[0],c[s-3]=o[1],c[s-2]=o[2],c[s-1]=o[3],i?[c,t]:n?(Tr(t,o,c,s,a),[c]):(Tr(t,o,t,0,a),[c,t])):[c,t]}close(t,r,o,n){let s;if(t===void 0)s=Po;else{if(typeof t!="number"||!Ho(t))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(t,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let i={[K]:s.length,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==X?this.enqueue([this.dispatch,s,!1,i,n]):this.sendFrame(e.frame(s,i),n)}ping(t,r,o){let n,s;if(typeof t=="string"?(n=Buffer.byteLength(t),s=!1):ke(t)?(n=t.size,s=!1):(t=he(t),n=t.length,s=he.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[K]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ke(t)?this._state!==X?this.enqueue([this.getBlobData,t,!1,i,o]):this.getBlobData(t,!1,i,o):this._state!==X?this.enqueue([this.dispatch,t,!1,i,o]):this.sendFrame(e.frame(t,i),o)}pong(t,r,o){let n,s;if(typeof t=="string"?(n=Buffer.byteLength(t),s=!1):ke(t)?(n=t.size,s=!1):(t=he(t),n=t.length,s=he.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[K]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ke(t)?this._state!==X?this.enqueue([this.getBlobData,t,!1,i,o]):this.getBlobData(t,!1,i,o):this._state!==X?this.enqueue([this.dispatch,t,!1,i,o]):this.sendFrame(e.frame(t,i),o)}send(t,r,o){let n=this._extensions[Rr.extensionName],s=r.binary?2:1,i=r.compress,a,l;typeof t=="string"?(a=Buffer.byteLength(t),l=!1):ke(t)?(a=t.size,l=!1):(t=he(t),a=t.length,l=he.readOnly),this._firstFragment?(this._firstFragment=!1,i&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=a>=n._threshold),this._compress=i):(i=!1,s=0),r.fin&&(this._firstFragment=!0);let c={[K]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:l,rsv1:i};ke(t)?this._state!==X?this.enqueue([this.getBlobData,t,this._compress,c,o]):this.getBlobData(t,this._compress,c,o):this._state!==X?this.enqueue([this.dispatch,t,this._compress,c,o]):this.dispatch(t,this._compress,c,o)}getBlobData(t,r,o,n){this._bufferedBytes+=o[K],this._state=Vo,t.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Ct,this,a,n);return}this._bufferedBytes-=o[K];let i=he(s);r?this.dispatch(i,r,o,n):(this._state=X,this.sendFrame(e.frame(i,o),n),this.dequeue())}).catch(s=>{process.nextTick(jo,this,s,n)})}dispatch(t,r,o,n){if(!r){this.sendFrame(e.frame(t,o),n);return}let s=this._extensions[Rr.extensionName];this._bufferedBytes+=o[K],this._state=zo,s.compress(t,o.fin,(i,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Ct(this,l,n);return}this._bufferedBytes-=o[K],this._state=X,o.readOnly=!1,this.sendFrame(e.frame(a,o),n),this.dequeue()})}dequeue(){for(;this._state===X&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][K],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][K],this._queue.push(t)}sendFrame(t,r){t.length===2?(this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],r),this._socket.uncork()):this._socket.write(t[0],r)}};Ir.exports=Ot;function Ct(e,t,r){typeof r=="function"&&r(t);for(let o=0;o<e._queue.length;o++){let n=e._queue[o],s=n[n.length-1];typeof s=="function"&&s(t)}}function jo(e,t,r){Ct(e,t,r),e.onerror(t)}});var Wr=V((Ci,Br)=>{"use strict";var{kForOnEventAttribute:Me,kListener:Mt}=ee(),$r=Symbol("kCode"),Nr=Symbol("kData"),Dr=Symbol("kError"),Or=Symbol("kMessage"),Cr=Symbol("kReason"),Re=Symbol("kTarget"),Lr=Symbol("kType"),Mr=Symbol("kWasClean"),re=class{constructor(t){this[Re]=null,this[Lr]=t}get target(){return this[Re]}get type(){return this[Lr]}};Object.defineProperty(re.prototype,"target",{enumerable:!0});Object.defineProperty(re.prototype,"type",{enumerable:!0});var ge=class extends re{constructor(t,r={}){super(t),this[$r]=r.code===void 0?0:r.code,this[Cr]=r.reason===void 0?"":r.reason,this[Mr]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[$r]}get reason(){return this[Cr]}get wasClean(){return this[Mr]}};Object.defineProperty(ge.prototype,"code",{enumerable:!0});Object.defineProperty(ge.prototype,"reason",{enumerable:!0});Object.defineProperty(ge.prototype,"wasClean",{enumerable:!0});var Te=class extends re{constructor(t,r={}){super(t),this[Dr]=r.error===void 0?null:r.error,this[Or]=r.message===void 0?"":r.message}get error(){return this[Dr]}get message(){return this[Or]}};Object.defineProperty(Te.prototype,"error",{enumerable:!0});Object.defineProperty(Te.prototype,"message",{enumerable:!0});var Be=class extends re{constructor(t,r={}){super(t),this[Nr]=r.data===void 0?null:r.data}get data(){return this[Nr]}};Object.defineProperty(Be.prototype,"data",{enumerable:!0});var qo={addEventListener(e,t,r={}){for(let n of this.listeners(e))if(!r[Me]&&n[Mt]===t&&!n[Me])return;let o;if(e==="message")o=function(s,i){let a=new Be("message",{data:i?s:s.toString()});a[Re]=this,et(t,this,a)};else if(e==="close")o=function(s,i){let a=new ge("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Re]=this,et(t,this,a)};else if(e==="error")o=function(s){let i=new Te("error",{error:s,message:s.message});i[Re]=this,et(t,this,i)};else if(e==="open")o=function(){let s=new re("open");s[Re]=this,et(t,this,s)};else return;o[Me]=!!r[Me],o[Mt]=t,r.once?this.once(e,o):this.on(e,o)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[Mt]===t&&!r[Me]){this.removeListener(e,r);break}}};Br.exports={CloseEvent:ge,ErrorEvent:Te,Event:re,EventTarget:qo,MessageEvent:Be};function et(e,t,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}});var Bt=V((Li,Pr)=>{"use strict";var{tokenChars:We}=_e();function Z(e,t,r){e[t]===void 0?e[t]=[r]:e[t].push(r)}function Go(e){let t=Object.create(null),r=Object.create(null),o=!1,n=!1,s=!1,i,a,l=-1,c=-1,d=-1,u=0;for(;u<e.length;u++)if(c=e.charCodeAt(u),i===void 0)if(d===-1&&We[c]===1)l===-1&&(l=u);else if(u!==0&&(c===32||c===9))d===-1&&l!==-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let h=e.slice(l,d);c===44?(Z(t,h,r),r=Object.create(null)):i=h,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(d===-1&&We[c]===1)l===-1&&(l=u);else if(c===32||c===9)d===-1&&l!==-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u),Z(r,e.slice(l,d),!0),c===44&&(Z(t,i,r),r=Object.create(null),i=void 0),l=d=-1}else if(c===61&&l!==-1&&d===-1)a=e.slice(l,u),l=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(n){if(We[c]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1?l=u:o||(o=!0),n=!1}else if(s)if(We[c]===1)l===-1&&(l=u);else if(c===34&&l!==-1)s=!1,d=u;else if(c===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===34&&e.charCodeAt(u-1)===61)s=!0;else if(d===-1&&We[c]===1)l===-1&&(l=u);else if(l!==-1&&(c===32||c===9))d===-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let h=e.slice(l,d);o&&(h=h.replace(/\\/g,""),o=!1),Z(r,a,h),c===44&&(Z(t,i,r),r=Object.create(null),i=void 0),a=void 0,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(l===-1||s||c===32||c===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=u);let p=e.slice(l,d);return i===void 0?Z(t,p,r):(a===void 0?Z(r,p,!0):o?Z(r,a,p.replace(/\\/g,"")):Z(r,a,p),Z(t,i,r)),t}function Ko(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(o=>[t].concat(Object.keys(o).map(n=>{let s=o[n];return Array.isArray(s)||(s=[s]),s.map(i=>i===!0?n:`${n}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Pr.exports={format:Ko,parse:Go}});var ot=V((Wi,Jr)=>{"use strict";var Yo=A("events"),Jo=A("https"),Xo=A("http"),Hr=A("net"),Zo=A("tls"),{randomBytes:Qo,createHash:es}=A("crypto"),{Duplex:Mi,Readable:Bi}=A("stream"),{URL:Wt}=A("url"),ue=Le(),ts=Dt(),rs=Lt(),{isBlob:ns}=_e(),{BINARY_TYPES:Ar,CLOSE_TIMEOUT:os,EMPTY_BUFFER:tt,GUID:ss,kForOnEventAttribute:Pt,kListener:is,kStatusCode:as,kWebSocket:F,NOOP:Ur}=ee(),{EventTarget:{addEventListener:cs,removeEventListener:ls}}=Wr(),{format:ds,parse:us}=Bt(),{toBuffer:fs}=Oe(),zr=Symbol("kAborted"),At=[8,13],ne=["CONNECTING","OPEN","CLOSING","CLOSED"],ps=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,P=class e extends Yo{constructor(t,r,o){super(),this._binaryType=Ar[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=tt,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(o=r,r=[]):r=[r]),Vr(this,t,r,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){Ar.includes(t)&&(this._binaryType=t,this._receiver&&(this._receiver._binaryType=t))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,r,o){let n=new ts({allowSynchronousEvents:o.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation}),s=new rs(t,this._extensions,o.generateMask);this._receiver=n,this._sender=s,this._socket=t,n[F]=this,s[F]=this,t[F]=this,n.on("conclude",gs),n.on("drain",ys),n.on("error",vs),n.on("message",ws),n.on("ping",bs),n.on("pong",Ss),s.onerror=xs,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",Gr),t.on("data",nt),t.on("end",Kr),t.on("error",Yr),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ue.extensionName]&&this._extensions[ue.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,r){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){q(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,r,!this._isServer,o=>{o||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),qr(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,r,o){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(o=t,t=r=void 0):typeof r=="function"&&(o=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){Ft(this,t,o);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||tt,r,o)}pong(t,r,o){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"?(o=t,t=r=void 0):typeof r=="function"&&(o=r,r=void 0),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){Ft(this,t,o);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||tt,r,o)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,r,o){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(o=r,r={}),typeof t=="number"&&(t=t.toString()),this.readyState!==e.OPEN){Ft(this,t,o);return}let n={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[ue.extensionName]||(n.compress=!1),this._sender.send(t||tt,n,o)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){q(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(P,"CONNECTING",{enumerable:!0,value:ne.indexOf("CONNECTING")});Object.defineProperty(P.prototype,"CONNECTING",{enumerable:!0,value:ne.indexOf("CONNECTING")});Object.defineProperty(P,"OPEN",{enumerable:!0,value:ne.indexOf("OPEN")});Object.defineProperty(P.prototype,"OPEN",{enumerable:!0,value:ne.indexOf("OPEN")});Object.defineProperty(P,"CLOSING",{enumerable:!0,value:ne.indexOf("CLOSING")});Object.defineProperty(P.prototype,"CLOSING",{enumerable:!0,value:ne.indexOf("CLOSING")});Object.defineProperty(P,"CLOSED",{enumerable:!0,value:ne.indexOf("CLOSED")});Object.defineProperty(P.prototype,"CLOSED",{enumerable:!0,value:ne.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[Pt])return t[is];return null},set(t){for(let r of this.listeners(e))if(r[Pt]){this.removeListener(e,r);break}typeof t=="function"&&this.addEventListener(e,t,{[Pt]:!0})}})});P.prototype.addEventListener=cs;P.prototype.removeEventListener=ls;Jr.exports=P;function Vr(e,t,r,o){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:os,protocolVersion:At[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...o,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=n.autoPong,e._closeTimeout=n.closeTimeout,!At.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${At.join(", ")})`);let s;if(t instanceof Wt)s=t;else try{s=new Wt(t)}catch{throw new SyntaxError(`Invalid URL: ${t}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),e._url=s.href;let i=s.protocol==="wss:",a=s.protocol==="ws+unix:",l;if(s.protocol!=="ws:"&&!i&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?l="The URL's pathname is empty":s.hash&&(l="The URL contains a fragment identifier"),l){let m=new SyntaxError(l);if(e._redirects===0)throw m;rt(e,m);return}let c=i?443:80,d=Qo(16).toString("base64"),u=i?Jo.request:Xo.request,p=new Set,h;if(n.createConnection=n.createConnection||(i?ms:hs),n.defaultPort=n.defaultPort||c,n.port=s.port||c,n.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},n.path=s.pathname+s.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(h=new ue(n.perMessageDeflate!==!0?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=ds({[ue.extensionName]:h.offer()})),r.length){for(let m of r){if(typeof m!="string"||!ps.test(m)||p.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(m)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(s.username||s.password)&&(n.auth=`${s.username}:${s.password}`),a){let m=n.path.split(":");n.socketPath=m[0],n.path=m[1]}let g;if(n.followRedirects){if(e._redirects===0){e._originalIpc=a,e._originalSecure=i,e._originalHostOrSocketPath=a?n.socketPath:s.host;let m=o&&o.headers;if(o={...o,headers:{}},m)for(let[S,$]of Object.entries(m))o.headers[S.toLowerCase()]=$}else if(e.listenerCount("redirect")===0){let m=a?e._originalIpc?n.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!m||e._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,m||delete n.headers.host,n.auth=void 0)}n.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),g=e._req=u(n),e._redirects&&e.emit("redirect",e.url,g)}else g=e._req=u(n);n.timeout&&g.on("timeout",()=>{q(e,g,"Opening handshake has timed out")}),g.on("error",m=>{g===null||g[zr]||(g=e._req=null,rt(e,m))}),g.on("response",m=>{let S=m.headers.location,$=m.statusCode;if(S&&n.followRedirects&&$>=300&&$<400){if(++e._redirects>n.maxRedirects){q(e,g,"Maximum redirects exceeded");return}g.abort();let O;try{O=new Wt(S,t)}catch{let v=new SyntaxError(`Invalid URL: ${S}`);rt(e,v);return}Vr(e,O,r,o)}else e.emit("unexpected-response",g,m)||q(e,g,`Unexpected server response: ${m.statusCode}`)}),g.on("upgrade",(m,S,$)=>{if(e.emit("upgrade",m),e.readyState!==P.CONNECTING)return;g=e._req=null;let O=m.headers.upgrade;if(O===void 0||O.toLowerCase()!=="websocket"){q(e,S,"Invalid Upgrade header");return}let D=es("sha1").update(d+ss).digest("base64");if(m.headers["sec-websocket-accept"]!==D){q(e,S,"Invalid Sec-WebSocket-Accept header");return}let v=m.headers["sec-websocket-protocol"],w;if(v!==void 0?p.size?p.has(v)||(w="Server sent an invalid subprotocol"):w="Server sent a subprotocol but none was requested":p.size&&(w="Server sent no subprotocol"),w){q(e,S,w);return}v&&(e._protocol=v);let b=m.headers["sec-websocket-extensions"];if(b!==void 0){if(!h){q(e,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let k;try{k=us(b)}catch{q(e,S,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(k);if(B.length!==1||B[0]!==ue.extensionName){q(e,S,"Server indicated an extension that was not requested");return}try{h.accept(k[ue.extensionName])}catch{q(e,S,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[ue.extensionName]=h}e.setSocket(S,$,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(g,e):g.end()}function rt(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function hs(e){return e.path=e.socketPath,Hr.connect(e)}function ms(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=Hr.isIP(e.host)?"":e.host),Zo.connect(e)}function q(e,t,r){e._readyState=P.CLOSING;let o=new Error(r);Error.captureStackTrace(o,q),t.setHeader?(t[zr]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(rt,e,o)):(t.destroy(o),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Ft(e,t,r){if(t){let o=ns(t)?t.size:fs(t).length;e._socket?e._sender._bufferedBytes+=o:e._bufferedAmount+=o}if(r){let o=new Error(`WebSocket is not open: readyState ${e.readyState} (${ne[e.readyState]})`);process.nextTick(r,o)}}function gs(e,t){let r=this[F];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[F]!==void 0&&(r._socket.removeListener("data",nt),process.nextTick(jr,r._socket),e===1005?r.close():r.close(e,t))}function ys(){let e=this[F];e.isPaused||e._socket.resume()}function vs(e){let t=this[F];t._socket[F]!==void 0&&(t._socket.removeListener("data",nt),process.nextTick(jr,t._socket),t.close(e[as])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Fr(){this[F].emitClose()}function ws(e,t){this[F].emit("message",e,t)}function bs(e){let t=this[F];t._autoPong&&t.pong(e,!this._isServer,Ur),t.emit("ping",e)}function Ss(e){this[F].emit("pong",e)}function jr(e){e.resume()}function xs(e){let t=this[F];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,qr(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function qr(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function Gr(){let e=this[F];if(this.removeListener("close",Gr),this.removeListener("data",nt),this.removeListener("end",Kr),e._readyState=P.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[F]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Fr),e._receiver.on("finish",Fr))}function nt(e){this[F]._receiver.write(e)||this.pause()}function Kr(){let e=this[F];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function Yr(){let e=this[F];this.removeListener("error",Yr),this.on("error",Ur),e&&(e._readyState=P.CLOSING,this.destroy())}});var en=V((Ai,Qr)=>{"use strict";var Pi=ot(),{Duplex:_s}=A("stream");function Xr(e){e.emit("close")}function ks(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Zr(e){this.removeListener("error",Zr),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function Es(e,t){let r=!0,o=new _s({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(s,i){let a=!i&&o._readableState.objectMode?s.toString():s;o.push(a)||e.pause()}),e.once("error",function(s){o.destroyed||(r=!1,o.destroy(s))}),e.once("close",function(){o.destroyed||o.push(null)}),o._destroy=function(n,s){if(e.readyState===e.CLOSED){s(n),process.nextTick(Xr,o);return}let i=!1;e.once("error",function(l){i=!0,s(l)}),e.once("close",function(){i||s(n),process.nextTick(Xr,o)}),r&&e.terminate()},o._final=function(n){if(e.readyState===e.CONNECTING){e.once("open",function(){o._final(n)});return}e._socket!==null&&(e._socket._writableState.finished?(n(),o._readableState.endEmitted&&o.destroy()):(e._socket.once("finish",function(){n()}),e.close()))},o._read=function(){e.isPaused&&e.resume()},o._write=function(n,s,i){if(e.readyState===e.CONNECTING){e.once("open",function(){o._write(n,s,i)});return}e.send(n,i)},o.on("end",ks),o.on("error",Zr),o}Qr.exports=Es});var rn=V((Fi,tn)=>{"use strict";var{tokenChars:Rs}=_e();function Ts(e){let t=new Set,r=-1,o=-1,n=0;for(n;n<e.length;n++){let i=e.charCodeAt(n);if(o===-1&&Rs[i]===1)r===-1&&(r=n);else if(n!==0&&(i===32||i===9))o===-1&&r!==-1&&(o=n);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${n}`);o===-1&&(o=n);let a=e.slice(r,o);if(t.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);t.add(a),r=o=-1}else throw new SyntaxError(`Unexpected character at index ${n}`)}if(r===-1||o!==-1)throw new SyntaxError("Unexpected end of input");let s=e.slice(r,n);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}tn.exports={parse:Ts}});var dn=V((Ui,ln)=>{"use strict";var Is=A("events"),st=A("http"),{Duplex:Hi}=A("stream"),{createHash:$s}=A("crypto"),nn=Bt(),ye=Le(),Ns=rn(),Ds=ot(),{CLOSE_TIMEOUT:Os,GUID:Cs,kWebSocket:Ls}=ee(),Ms=/^[+/0-9A-Za-z]{22}==$/,on=0,sn=1,cn=2,Ht=class extends Is{constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Os,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Ds,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null?(this._server=st.createServer((o,n)=>{let s=st.STATUS_CODES[426];n.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),n.end(s)}),this._server.listen(t.port,t.host,t.backlog,r)):t.server&&(this._server=t.server),this._server){let o=this.emit.bind(this,"connection");this._removeListeners=Bs(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,s,i)=>{this.handleUpgrade(n,s,i,o)}})}t.perMessageDeflate===!0&&(t.perMessageDeflate={}),t.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=t,this._state=on}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(t){if(this._state===cn){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(Pe,this);return}if(t&&this.once("close",t),this._state!==sn)if(this._state=sn,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Pe,this):process.nextTick(Pe,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Pe(this)})}}shouldHandle(t){if(this.options.path){let r=t.url.indexOf("?");if((r!==-1?t.url.slice(0,r):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,r,o,n){r.on("error",an);let s=t.headers["sec-websocket-key"],i=t.headers.upgrade,a=+t.headers["sec-websocket-version"];if(t.method!=="GET"){ve(this,t,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){ve(this,t,r,400,"Invalid Upgrade header");return}if(s===void 0||!Ms.test(s)){ve(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ve(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){Ae(r,400);return}let l=t.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Ns.parse(l)}catch{ve(this,t,r,400,"Invalid Sec-WebSocket-Protocol header");return}let d=t.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let p=new ye(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=nn.parse(d);h[ye.extensionName]&&(p.accept(h[ye.extensionName]),u[ye.extensionName]=p)}catch{ve(this,t,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:t.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(h,g,m,S)=>{if(!h)return Ae(r,g||401,m,S);this.completeUpgrade(u,s,c,t,r,o,n)});return}if(!this.options.verifyClient(p))return Ae(r,401)}this.completeUpgrade(u,s,c,t,r,o,n)}completeUpgrade(t,r,o,n,s,i,a){if(!s.readable||!s.writable)return s.destroy();if(s[Ls])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>on)return Ae(s,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${$s("sha1").update(r+Cs).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(o.size){let u=this.options.handleProtocols?this.options.handleProtocols(o,n):o.values().next().value;u&&(c.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(t[ye.extensionName]){let u=t[ye.extensionName].params,p=nn.format({[ye.extensionName]:[u]});c.push(`Sec-WebSocket-Extensions: ${p}`),d._extensions=t}this.emit("headers",c,n),s.write(c.concat(`\r
2
+ `).join(`\r
3
+ `)),s.removeListener("error",an),d.setSocket(s,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Pe,this)})),a(d,n)}};ln.exports=Ht;function Bs(e,t){for(let r of Object.keys(t))e.on(r,t[r]);return function(){for(let o of Object.keys(t))e.removeListener(o,t[o])}}function Pe(e){e._state=cn,e.emit("close")}function an(){this.destroy()}function Ae(e,t,r,o){r=r||st.STATUS_CODES[t],o={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...o},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${st.STATUS_CODES[t]}\r
4
+ `+Object.keys(o).map(n=>`${n}: ${o[n]}`).join(`\r
5
+ `)+`\r
6
+ \r
7
+ `+r)}function ve(e,t,r,o,n,s){if(e.listenerCount("wsClientError")){let i=new Error(n);Error.captureStackTrace(i,ve),e.emit("wsClientError",i,r,t)}else Ae(r,o,n,s)}});var mn={};_n(mn,{Receiver:()=>fn.default,Sender:()=>pn.default,WebSocket:()=>Ut.default,WebSocketServer:()=>hn.default,createWebSocketStream:()=>un.default,default:()=>Ws});var un,fn,pn,Ut,hn,Ws,gn=xn(()=>{"use strict";un=Ie(en(),1),fn=Ie(Dt(),1),pn=Ie(Lt(),1),Ut=Ie(ot(),1),hn=Ie(dn(),1),Ws=Ut.default});function H(e){if(e<1e3)return`${Math.round(e)}ms`;if(e<6e4)return`${(e/1e3).toFixed(1).replace(/\.0$/,"")}s`;let t=Math.floor(e/6e4),r=Math.round(e%6e4/1e3);return r===0?`${t}m`:`${t}m ${r}s`}function at(){return`node_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function En(e){for(let t of e)if((t.type==="parallel"||t.type==="race"||t.type==="sequence")&&!t.id.startsWith("detected_")||"decisionId"in t)return!0;return!1}function Fe(e,t={}){if(En(e))return e;let{minOverlapMs:r=0,maxGapMs:o=5}=t,n=[],s=[];for(let c=0;c<e.length;c++){let d=e[c];d.type==="step"&&d.startTs!==void 0?n.push({node:d,startTs:d.startTs,endTs:d.endTs??d.startTs+(d.durationMs??0),originalIndex:c}):s.push({node:d,originalIndex:c})}if(n.length<=1)return e;n.sort((c,d)=>c.startTs-d.startTs);let i=[],a=[n[0]];for(let c=1;c<n.length;c++){let d=n[c],u=Math.min(...a.map(S=>S.startTs)),p=Math.max(...a.map(S=>S.endTs)),h=d.startTs<=u+o,g=d.startTs<p;if(!h&&!g){i.push(a),a=[d];continue}let m=g?Math.min(d.endTs,p)-d.startTs:0;h||m>=r?a.push(d):(i.push(a),a=[d])}i.push(a);let l=[];for(let c of i){let d=Math.min(...c.map(u=>u.originalIndex));if(c.length===1)l.push({node:c[0].node,position:d});else{let u=c.map(m=>m.node),p=Math.min(...c.map(m=>m.startTs)),h=Math.max(...c.map(m=>m.endTs)),g={type:"parallel",id:`detected_parallel_${p}`,name:`${u.length} parallel steps`,state:Rn(u),mode:"all",children:u,startTs:p,endTs:h,durationMs:h-p};l.push({node:g,position:d})}}for(let{node:c,originalIndex:d}of s)l.push({node:c,position:d});return l.sort((c,d)=>c.position-d.position),l.map(c=>c.node)}function Rn(e){return e.some(s=>s.state==="error")?"error":e.some(s=>s.state==="running")?"running":e.some(s=>s.state==="pending")?"pending":(e.every(s=>s.state==="success"||s.state==="cached"),"success")}function Tn(e={}){return{detect:t=>Fe(t,e)}}function pe(e={}){let{detectParallel:t=!0,parallelDetection:r,enableSnapshots:o=!1,maxSnapshots:n=1e3}=e,s,i,a="pending",l,c,d=new Map,u=[],p=[],h=[],g=Date.now(),m=g,S={onAfterStep:new Map},$=[],O=0;function D(f){return f.stepId??f.stepKey??f.name??at()}function v(f){if(p.length>0){let y=p[p.length-1];for(let U of y.branches.values())if(U.taken){U.children.push(f),m=Date.now();return}let x=Array.from(y.branches.values())[0];if(x){x.children.push(f),m=Date.now();return}}u.length>0?u[u.length-1].children.push(f):h.push(f),m=Date.now()}function w(f){if(!o)return;let y=L(),x=new Map;for(let[Y,fe]of d)x.set(Y,{id:fe.id,name:fe.name,key:fe.key,startTs:fe.startTs,retryCount:fe.retryCount,timedOut:fe.timedOut,timeoutMs:fe.timeoutMs});let U={id:`snapshot_${O}`,eventIndex:O,event:structuredClone(f),ir:structuredClone(y),timestamp:Date.now(),activeSteps:x};$.push(U),$.length>n&&$.shift(),O++}function b(f){switch(f.type){case"workflow_start":s=f.workflowId,i=f.ts,a="running",g=Date.now(),m=g,S.onAfterStep=new Map;break;case"workflow_success":a="success",c=f.durationMs,m=Date.now();break;case"workflow_error":a="error",l=f.error,c=f.durationMs,m=Date.now();break;case"step_start":{let y=D(f);d.set(y,{id:y,name:f.name,key:f.stepKey,startTs:f.ts,retryCount:0,timedOut:!1}),m=Date.now();break}case"step_success":{let y=D(f),x=d.get(y);if(x){let U={type:"step",id:x.id,name:x.name,key:x.key,state:"success",startTs:x.startTs,endTs:f.ts,durationMs:f.durationMs,...x.retryCount>0&&{retryCount:x.retryCount},...x.timedOut&&{timedOut:!0,timeoutMs:x.timeoutMs}};v(U),d.delete(y)}break}case"step_error":{let y=D(f),x=d.get(y);if(x){let U={type:"step",id:x.id,name:x.name,key:x.key,state:"error",startTs:x.startTs,endTs:f.ts,durationMs:f.durationMs,error:f.error,...x.retryCount>0&&{retryCount:x.retryCount},...x.timedOut&&{timedOut:!0,timeoutMs:x.timeoutMs}};v(U),d.delete(y)}break}case"step_aborted":{let y=D(f),x=d.get(y);if(x){let U={type:"step",id:x.id,name:x.name,key:x.key,state:"aborted",startTs:x.startTs,endTs:f.ts,durationMs:f.durationMs,...x.retryCount>0&&{retryCount:x.retryCount},...x.timedOut&&{timedOut:!0,timeoutMs:x.timeoutMs}};v(U),d.delete(y)}break}case"step_cache_hit":{let x={type:"step",id:D(f),name:f.name,key:f.stepKey,state:"cached",startTs:f.ts,endTs:f.ts,durationMs:0};v(x);break}case"step_cache_miss":break;case"step_complete":break;case"step_timeout":{let y=D(f),x=d.get(y);x&&(x.timedOut=!0,x.timeoutMs=f.timeoutMs),m=Date.now();break}case"step_retry":{let y=D(f),x=d.get(y);x&&(x.retryCount=(f.attempt??1)-1),m=Date.now();break}case"step_retries_exhausted":m=Date.now();break;case"step_skipped":{let x={type:"step",id:D(f),name:f.name,key:f.stepKey,state:"skipped",startTs:f.ts,endTs:f.ts,durationMs:0};v(x);break}case"hook_should_run":{let y={type:"shouldRun",state:"success",ts:f.ts,durationMs:f.durationMs,context:{result:f.result,skipped:f.skipped}};S.shouldRun=y,m=Date.now();break}case"hook_should_run_error":{let y={type:"shouldRun",state:"error",ts:f.ts,durationMs:f.durationMs,error:f.error};S.shouldRun=y,m=Date.now();break}case"hook_before_start":{let y={type:"onBeforeStart",state:"success",ts:f.ts,durationMs:f.durationMs,context:{result:f.result,skipped:f.skipped}};S.onBeforeStart=y,m=Date.now();break}case"hook_before_start_error":{let y={type:"onBeforeStart",state:"error",ts:f.ts,durationMs:f.durationMs,error:f.error};S.onBeforeStart=y,m=Date.now();break}case"hook_after_step":{let y={type:"onAfterStep",state:"success",ts:f.ts,durationMs:f.durationMs,context:{stepKey:f.stepKey}};S.onAfterStep.set(f.stepKey,y),m=Date.now();break}case"hook_after_step_error":{let y={type:"onAfterStep",state:"error",ts:f.ts,durationMs:f.durationMs,error:f.error,context:{stepKey:f.stepKey}};S.onAfterStep.set(f.stepKey,y),m=Date.now();break}}w(f)}function k(f){if(f.type==="scope_start")u.push({id:f.scopeId,name:f.name,type:f.scopeType,startTs:f.ts,children:[]}),m=Date.now();else if(f.type==="scope_end"){let y=u.pop();if(y){let x=y.type==="race"?{type:"race",id:y.id,name:y.name,state:C(y.children),startTs:y.startTs,endTs:f.ts,durationMs:f.durationMs,children:y.children,winnerId:f.winnerId}:{type:"parallel",id:y.id,name:y.name,state:C(y.children),startTs:y.startTs,endTs:f.ts,durationMs:f.durationMs,children:y.children,mode:y.type==="allSettled"?"allSettled":"all"};v(x)}}}function B(f){if(f.type==="decision_start")p.push({id:f.decisionId,name:f.name,condition:f.condition,decisionValue:f.decisionValue,startTs:f.ts,branches:new Map}),m=Date.now();else if(f.type==="decision_branch"){let y=p[p.length-1];if(y&&y.id===f.decisionId){let x=f.branchLabel,U=y.branches.get(x);U?U.taken=f.taken:y.branches.set(x,{label:f.branchLabel,condition:f.condition,taken:f.taken,children:[]}),m=Date.now()}}else if(f.type==="decision_end"){let y=p.pop();if(y&&y.id===f.decisionId){let x=Array.from(y.branches.values()),U={type:"decision",id:y.id,name:y.name,state:C(x.flatMap(Y=>Y.taken?Y.children:[])),startTs:y.startTs,endTs:f.ts,durationMs:f.durationMs,condition:y.condition,decisionValue:y.decisionValue,branchTaken:f.branchTaken??y.branchTaken,branches:x};v(U)}}}function C(f){return f.length===0?"success":f.some(Y=>Y.state==="error")?"error":f.every(Y=>Y.state==="success"||Y.state==="cached")?"success":f.some(Y=>Y.state==="running")?"running":"pending"}function I(){let f=[...h];for(let[,y]of d)f.push({type:"step",id:y.id,name:y.name,key:y.key,state:"running",startTs:y.startTs,...y.retryCount>0&&{retryCount:y.retryCount},...y.timedOut&&{timedOut:!0,timeoutMs:y.timeoutMs}});return f}function L(){let f=I();t&&(f=Fe(f,r));let y={type:"workflow",id:s??at(),workflowId:s??"unknown",state:a,startTs:i,durationMs:c,children:f,error:l},x=S.shouldRun!==void 0||S.onBeforeStart!==void 0||S.onAfterStep.size>0;return{root:y,metadata:{createdAt:g,lastUpdatedAt:m},...x&&{hooks:S}}}function N(){s=void 0,i=void 0,a="pending",l=void 0,c=void 0,d.clear(),u.length=0,p.length=0,h=[],g=Date.now(),m=g,S={onAfterStep:new Map},$.length=0,O=0}function E(){return[...$]}function R(f){return $[f]}function T(f){return $[f]?.ir}function W(){$.length=0,O=0}return{handleEvent:b,handleScopeEvent:k,handleDecisionEvent:B,getIR:L,reset:N,getSnapshots:E,getSnapshotAt:R,getIRAt:T,clearSnapshots:W,get hasActiveSteps(){return d.size>0},get state(){return a},get snapshotCount(){return $.length},get snapshotsEnabled(){return o}}}function J(e){return e.type==="step"}function jt(e){return e.type==="sequence"}function Q(e){return e.type==="parallel"}function oe(e){return e.type==="race"}function se(e){return e.type==="decision"}function qs(e){return"children"in e||e.type==="decision"&&"branches"in e}var ct="\x1B[0m",In="\x1B[1m",Gt="\x1B[2m",$n="\x1B[31m",Nn="\x1B[32m",Dn="\x1B[33m",On="\x1B[34m",qt="\x1B[90m",Cn="\x1B[37m";function ie(e,t){return t?`${t}${e}${ct}`:e}function $e(e){return`${In}${e}${ct}`}function M(e){return`${Gt}${e}${ct}`}var ae={pending:Cn,running:Dn,success:Nn,error:$n,aborted:qt,cached:On,skipped:Gt+qt};function Ln(e){switch(e){case"pending":return"\u25CB";case"running":return"\u27F3";case"success":return"\u2713";case"error":return"\u2717";case"aborted":return"\u2298";case"cached":return"\u21BA";case"skipped":return"\u2298"}}function Ne(e,t){let r=Ln(e);return ie(r,t[e])}function lt(e,t,r){return ie(e,r[t])}function Kt(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}var _={topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502",teeRight:"\u251C",teeLeft:"\u2524",teeDown:"\u252C",teeUp:"\u2534",cross:"\u253C"},we={cold:"\x1B[34m",cool:"\x1B[36m",neutral:"",warm:"\x1B[33m",hot:"\x1B[31m",critical:"\x1B[41m"},Mn="\x1B[0m";function Bn(e){return e<.2?we.cold:e<.4?we.cool:e<.6?we.neutral:e<.8?we.warm:e<.95?we.hot:we.critical}function Yt(e,t){let r=Bn(t);return r?`${r}${e}${Mn}`:e}var Jt="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Wn(e,t=10){if(e.length===0)return"";let r=e.slice(-t),o=Math.min(...r),s=Math.max(...r)-o||1;return r.map(i=>{let a=(i-o)/s,l=Math.floor(a*(Jt.length-1));return Jt[l]}).join("")}function dt(e,t){let r=Kt(e).length,o=Math.max(0,t-r);return e+" ".repeat(o)}function Pn(e,t){if(!t)return _.horizontal.repeat(e);let r=` ${t} `,o=e-r.length;if(o<4)return _.horizontal.repeat(e);let n=2,s=o-n;return _.horizontal.repeat(n)+r+_.horizontal.repeat(s)}function Xt(e,t,r){let o=e.state==="success"?ie("\u2699",r.success):ie("\u26A0",r.error),n=e.durationMs!==void 0?M(` [${H(e.durationMs)}]`):"",s="";e.type==="shouldRun"&&e.context?.skipped?s=M(" \u2192 workflow skipped"):e.type==="shouldRun"&&e.context?.result===!0?s=M(" \u2192 proceed"):e.type==="onBeforeStart"&&e.context?.skipped?s=M(" \u2192 workflow skipped"):e.type==="onAfterStep"&&e.context?.stepKey&&(s=M(` (${e.context.stepKey})`));let i=e.state==="error"&&e.error?M(` error: ${String(e.error)}`):"";return`${o} ${M(t)}${s}${n}${i}`}function An(e,t){let r=[];return e.shouldRun&&r.push(Xt(e.shouldRun,"shouldRun",t)),e.onBeforeStart&&r.push(Xt(e.onBeforeStart,"onBeforeStart",t)),r.length>0&&r.push(M("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")),r}function ce(){return{name:"ascii",supportsLive:!0,render(e,t){let r={...ae,...t.colors},o=t.terminalWidth??60,n=o-4,s=[],i=e.root.name??"workflow",a=$e(i);if(s.push(`${_.topLeft}${Pn(o-2,a)}${_.topRight}`),s.push(`${_.vertical}${" ".repeat(o-2)}${_.vertical}`),e.hooks){let c=An(e.hooks,r);for(let d of c)s.push(`${_.vertical} ${dt(d,n)}${_.vertical}`)}let l=He(e.root.children,t,r,0,e.hooks);for(let c of l)s.push(`${_.vertical} ${dt(c,n)}${_.vertical}`);if(s.push(`${_.vertical}${" ".repeat(o-2)}${_.vertical}`),e.root.durationMs!==void 0&&t.showTimings){let c=e.root.state==="success"?"Completed":"Failed",u=`${lt(c,e.root.state,r)} in ${H(e.root.durationMs)}`;s.push(`${_.vertical} ${dt(u,n)}${_.vertical}`),s.push(`${_.vertical}${" ".repeat(o-2)}${_.vertical}`)}return s.push(`${_.bottomLeft}${_.horizontal.repeat(o-2)}${_.bottomRight}`),s.join(`
8
+ `)}}}function He(e,t,r,o,n){let s=[];for(let i of e)J(i)?s.push(ut(i,t,r,n)):Q(i)?s.push(...Fn(i,t,r,o,n)):oe(i)?s.push(...Hn(i,t,r,o,n)):se(i)&&s.push(...Un(i,t,r,o,n));return s}function ut(e,t,r,o){let n=Ne(e.state,r),s=e.name??e.key??"step",i=t,a=e.name??e.id,l=i.showHeatmap&&i.heatmapData?i.heatmapData.heat.get(e.id)??i.heatmapData.heat.get(a):void 0,c;l!==void 0?c=Yt(s,l):c=lt(s,e.state,r);let d=`${n} ${c}`;if(t.showKeys&&e.key&&(d+=M(` [key: ${e.key}]`)),e.input!==void 0){let u=typeof e.input=="string"?e.input:JSON.stringify(e.input).slice(0,30);d+=M(` [in: ${u}${u.length>=30?"...":""}]`)}if(e.output!==void 0&&e.state==="success"){let u=typeof e.output=="string"?e.output:JSON.stringify(e.output).slice(0,30);d+=M(` [out: ${u}${u.length>=30?"...":""}]`)}if(t.showTimings&&e.durationMs!==void 0){let u=H(e.durationMs),p=l!==void 0?Yt(`[${u}]`,l):M(`[${u}]`);d+=` ${p}`}if(i.showSparklines&&i.timingHistory){let u=i.timingHistory.get(a);u&&u.length>1&&(d+=` ${M(Wn(u))}`)}if(e.retryCount!==void 0&&e.retryCount>0&&(d+=M(` [${e.retryCount} ${e.retryCount===1?"retry":"retries"}]`)),e.timedOut){let u=e.timeoutMs!==void 0?` ${e.timeoutMs}ms`:"";d+=M(` [timeout${u}]`)}if(o&&e.key&&o.onAfterStep.has(e.key)){let u=o.onAfterStep.get(e.key),p=u.state==="success"?ie("\u2699",r.success):ie("\u26A0",r.error),h=u.durationMs!==void 0?M(` ${H(u.durationMs)}`):"";d+=` ${p}${h}`}return d}function Fn(e,t,r,o,n){let s=[],i=" ".repeat(o),a=Ne(e.state,r),l=e.name??"parallel",c=e.mode==="allSettled"?" (allSettled)":"";if(s.push(`${i}${_.teeRight}${_.teeDown}${_.horizontal} ${a} ${$e(l)}${c}`),e.children.length===0)s.push(`${i}${_.vertical} ${M("(operations not individually tracked)")}`),s.push(`${i}${_.vertical} ${M("(wrap each operation with step() to see individual steps)")}`);else for(let d=0;d<e.children.length;d++){let u=e.children[d],h=d===e.children.length-1?`${i}${_.vertical} ${_.bottomLeft}`:`${i}${_.vertical} ${_.teeRight}`;if(J(u))s.push(`${h} ${ut(u,t,r,n)}`);else{let g=He([u],t,r,o+1,n);for(let m of g)s.push(`${i}${_.vertical} ${m}`)}}return t.showTimings&&e.durationMs!==void 0&&s.push(`${i}${_.bottomLeft}${_.horizontal}${_.horizontal} ${M(`[${H(e.durationMs)}]`)}`),s}function Hn(e,t,r,o,n){let s=[],i=" ".repeat(o),a=Ne(e.state,r),l=e.name??"race";if(s.push(`${i}${_.teeRight}\u26A1 ${a} ${$e(l)}`),e.children.length===0)s.push(`${i}${_.vertical} ${M("(operations not individually tracked)")}`),s.push(`${i}${_.vertical} ${M("(wrap each operation with step() to see individual steps)")}`);else for(let c=0;c<e.children.length;c++){let d=e.children[c],p=c===e.children.length-1?`${i}${_.vertical} ${_.bottomLeft}`:`${i}${_.vertical} ${_.teeRight}`,g=e.winnerId&&d.id===e.winnerId?M(" (winner)"):"";if(J(d))s.push(`${p} ${ut(d,t,r,n)}${g}`);else{let m=He([d],t,r,o+1,n);for(let S of m)s.push(`${i}${_.vertical} ${S}`)}}return t.showTimings&&e.durationMs!==void 0&&s.push(`${i}${_.bottomLeft}${_.horizontal}${_.horizontal} ${M(`[${H(e.durationMs)}]`)}`),s}function Un(e,t,r,o,n){let s=[],i=" ".repeat(o),a=Ne(e.state,r),l=e.name??"decision",c=e.condition?M(` (${e.condition})`):"",d=e.decisionValue!==void 0?M(` = ${String(e.decisionValue)}`):"",u=e.branchTaken!==void 0?M(` \u2192 ${String(e.branchTaken)}`):"";s.push(`${i}${_.teeRight}${_.teeDown}${_.horizontal} ${a} ${$e(l)}${c}${d}${u}`);for(let p=0;p<e.branches.length;p++){let h=e.branches[p],m=p===e.branches.length-1?`${i}${_.vertical} ${_.bottomLeft}`:`${i}${_.vertical} ${_.teeRight}`,S=h.taken?"\u2713":"\u2298",$=h.taken?r.success:r.skipped,O=ie(`${S} ${h.label}`,$),D=h.condition?M(` (${h.condition})`):"";if(s.push(`${m} ${O}${D}`),h.children.length>0){let v=He(h.children,t,r,o+1,n);for(let w of v)s.push(`${i}${_.vertical} ${w}`)}else h.taken||s.push(`${i}${_.vertical} ${M("(skipped)")}`)}return t.showTimings&&e.durationMs!==void 0&&s.push(`${i}${_.bottomLeft}${_.horizontal}${_.horizontal} ${M(`[${H(e.durationMs)}]`)}`),s}function ft(e){let t=[];for(let r of e)if(t.push(r),"children"in r&&Array.isArray(r.children)&&t.push(...ft(r.children)),"branches"in r)for(let o of r.branches)t.push(...ft(o.children));return t}function Ue(e,t){if(e.length===0)return 0;let r=Math.floor(e.length*t);return e[Math.min(r,e.length-1)]}function pt(e){return e<.2?"cold":e<.4?"cool":e<.6?"neutral":e<.8?"warm":e<.95?"hot":"critical"}function ht(){let e=new Map,t=new Map,r=new Map,o=new Map,n=[];function s(v){return v.name??v.stepKey??v.stepId??"unknown"}function i(v){let w=new Map;for(let b of v)switch(b.type){case"step_start":{let k=s(b);w.set(k,{retried:!1,timedOut:!1});break}case"step_retry":{let k=s(b),B=w.get(k);B&&(B.retried=!0);break}case"step_timeout":{let k=s(b),B=w.get(k);B&&(B.timedOut=!0);let C=o.get(k)??{timedOut:0,total:0};C.timedOut++,C.total++,o.set(k,C);break}case"step_success":{let k=s(b),B=w.get(k),C=e.get(k)??[];C.push(b.durationMs),e.set(k,C);let I=t.get(k)??{retried:0,total:0};I.total++,B?.retried&&I.retried++,t.set(k,I);let L=r.get(k)??{errors:0,total:0};L.total++,r.set(k,L),w.delete(k);break}case"step_error":{let k=s(b),B=w.get(k),C=e.get(k)??[];C.push(b.durationMs),e.set(k,C);let I=t.get(k)??{retried:0,total:0};I.total++,B?.retried&&I.retried++,t.set(k,I);let L=r.get(k)??{errors:0,total:0};L.total++,L.errors++,r.set(k,L),w.delete(k);break}}}function a(v){i(v.events)}function l(v){n.push(v)}function c(v){n.length>0&&(i(n),n=[])}function d(v){let w=e.get(v);if(!w||w.length===0)return;let b=[...w].sort((E,R)=>E-R),B=b.reduce((E,R)=>E+R,0)/b.length,C=b.reduce((E,R)=>E+(R-B)**2,0)/b.length,I=t.get(v)??{retried:0,total:1},L=r.get(v)??{errors:0,total:1},N=o.get(v)??{timedOut:0,total:1};return{nodeId:v,avgDurationMs:B,minDurationMs:b[0],maxDurationMs:b[b.length-1],stdDevMs:Math.sqrt(C),samples:b.length,retryRate:I.total>0?I.retried/I.total:0,timeoutRate:N.total>0?N.timedOut/N.total:0,errorRate:L.total>0?L.errors/L.total:0,percentiles:{p50:Ue(b,.5),p90:Ue(b,.9),p95:Ue(b,.95),p99:Ue(b,.99)}}}function u(v){return d(v)}function p(v,w="duration"){let b=new Map,k=ft(v.root.children),B=[];for(let R of k){let T=R.name??R.id,W=d(T);if(W){let f;switch(w){case"duration":f=W.avgDurationMs;break;case"retryRate":f=W.retryRate;break;case"errorRate":f=W.errorRate;break}B.push({id:R.id,value:f})}}if(B.length===0)return{heat:b,metric:w,stats:{min:0,max:0,mean:0,threshold:0}};let C=B.map(R=>R.value),I=Math.min(...C),L=Math.max(...C),N=C.reduce((R,T)=>R+T,0)/C.length,E=L-I||1;for(let{id:R,value:T}of B)b.set(R,(T-I)/E);return{heat:b,metric:w,stats:{min:I,max:L,mean:N,threshold:N+(L-N)*.5}}}function h(){let v=new Map;for(let w of e.keys()){let b=d(w);b&&v.set(w,b)}return v}function g(v=10){return[...h().values()].sort((b,k)=>k.avgDurationMs-b.avgDurationMs).slice(0,v)}function m(v=10){return[...h().values()].filter(b=>b.errorRate>0).sort((b,k)=>k.errorRate-b.errorRate).slice(0,v)}function S(v=10){return[...h().values()].filter(b=>b.retryRate>0).sort((b,k)=>k.retryRate-b.retryRate).slice(0,v)}function $(){return JSON.stringify({timingData:Object.fromEntries(e),retryData:Object.fromEntries(t),errorData:Object.fromEntries(r),timeoutData:Object.fromEntries(o)})}function O(v){let w=JSON.parse(v);e.clear(),t.clear(),r.clear(),o.clear();for(let[b,k]of Object.entries(w.timingData??{}))e.set(b,k);for(let[b,k]of Object.entries(w.retryData??{}))t.set(b,k);for(let[b,k]of Object.entries(w.errorData??{}))r.set(b,k);for(let[b,k]of Object.entries(w.timeoutData??{}))o.set(b,k)}function D(){e.clear(),t.clear(),r.clear(),o.clear(),n=[]}return{addRun:a,addEvent:l,finalizeRun:c,getNodePerformance:u,getHeatmap:p,getSlowestNodes:g,getErrorProneNodes:m,getRetryProneNodes:S,getAllPerformance:h,exportData:$,importData:O,clear:D}}function zn(){return[" classDef pending fill:#f3f4f6,stroke:#9ca3af,stroke-width:2px,color:#374151"," classDef running fill:#fef3c7,stroke:#f59e0b,stroke-width:3px,color:#92400e"," classDef success fill:#d1fae5,stroke:#10b981,stroke-width:3px,color:#065f46"," classDef error fill:#fee2e2,stroke:#ef4444,stroke-width:3px,color:#991b1b"," classDef aborted fill:#f3f4f6,stroke:#6b7280,stroke-width:2px,color:#4b5563,stroke-dasharray: 5 5"," classDef cached fill:#dbeafe,stroke:#3b82f6,stroke-width:3px,color:#1e40af"," classDef skipped fill:#f9fafb,stroke:#d1d5db,stroke-width:2px,color:#6b7280,stroke-dasharray: 5 5"]}function Vn(){return[" classDef heat_cold fill:#dbeafe,stroke:#3b82f6,stroke-width:2px,color:#1e40af"," classDef heat_cool fill:#ccfbf1,stroke:#14b8a6,stroke-width:2px,color:#0f766e"," classDef heat_neutral fill:#f3f4f6,stroke:#6b7280,stroke-width:2px,color:#374151"," classDef heat_warm fill:#fef3c7,stroke:#f59e0b,stroke-width:2px,color:#92400e"," classDef heat_hot fill:#fed7aa,stroke:#f97316,stroke-width:3px,color:#c2410c"," classDef heat_critical fill:#fecaca,stroke:#ef4444,stroke-width:3px,color:#b91c1c"]}function jn(e){return`heat_${e}`}function qn(){return[" classDef hook_success fill:#e0f2fe,stroke:#0284c7,stroke-width:2px,color:#0c4a6e"," classDef hook_error fill:#fef2f2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d"]}function Gn(e,t,r){let o;if(e.shouldRun){let n="hook_shouldRun",s=e.shouldRun.state==="success"?"hook_success":"hook_error",i=e.shouldRun.state==="success"?"\u2699":"\u26A0",a=r.showTimings&&e.shouldRun.durationMs!==void 0?` ${H(e.shouldRun.durationMs)}`:"",l=e.shouldRun.context?.skipped?"\\nskipped workflow":e.shouldRun.context?.result===!0?"\\nproceed":"";t.push(` ${n}[["${i} shouldRun${l}${a}"]]:::${s}`),o=n}if(e.onBeforeStart){let n="hook_beforeStart",s=e.onBeforeStart.state==="success"?"hook_success":"hook_error",i=e.onBeforeStart.state==="success"?"\u2699":"\u26A0",a=r.showTimings&&e.onBeforeStart.durationMs!==void 0?` ${H(e.onBeforeStart.durationMs)}`:"",l=e.onBeforeStart.context?.skipped?"\\nskipped workflow":"";t.push(` ${n}[["${i} onBeforeStart${l}${a}"]]:::${s}`),o&&t.push(` ${o} --> ${n}`),o=n}return{lastHookId:o}}var Zt=0;function De(e="node"){return`${e}_${++Zt}`}function Kn(){Zt=0}function j(e){return e.replace(/[{}[\]()]/g,"").replace(/[<>]/g,"").replace(/"/g,"'").trim()}function Qt(e){return j(e).replace(/[[\]]/g,"")}function ze(){return{name:"mermaid",supportsLive:!1,render(e,t){Kn();let r=[],o=t;r.push("flowchart TD");let n;e.hooks&&(n=Gn(e.hooks,r,t).lastHookId);let s="start";r.push(` ${s}(("\u25B6 Start"))`),n&&r.push(` ${n} --> ${s}`);let i=s;for(let a of e.root.children){let l=Ve(a,t,r,o,e.hooks);r.push(` ${i} --> ${l.entryId}`),i=l.exitId}if(e.root.state==="success"||e.root.state==="error"){let a="finish",l=e.root.state==="success"?"\u2713":"\u2717",c=e.root.state==="success"?"Done":"Failed",d=`(("${l} ${c}"))`,u=e.root.state==="success"?":::success":":::error";r.push(` ${a}${d}${u}`),r.push(` ${i} --> ${a}`)}return r.push(""),r.push(...zn()),o.showHeatmap&&r.push(...Vn()),e.hooks&&r.push(...qn()),r.join(`
9
+ `)}}}function Ve(e,t,r,o,n){if(J(e))return Yn(e,t,r,o,n);if(Q(e))return Jn(e,t,r,o,n);if(oe(e))return Xn(e,t,r,o,n);if(se(e))return Zn(e,t,r,o,n);let s=De("unknown");return r.push(` ${s}[Unknown Node]`),{entryId:s,exitId:s}}function Yn(e,t,r,o,n){let s=t,i=s.showRetryEdges??!0,a=s.showErrorEdges??!0,l=s.showTimeoutEdges??!0,c=e.key?`step_${e.key.replace(/[^a-zA-Z0-9]/g,"_")}`:De("step"),d=j(e.name??e.key??"Step"),u=t.showTimings&&e.durationMs!==void 0?` ${H(e.durationMs)}`:"",p="";switch(e.state){case"success":p="\u2713 ";break;case"error":p="\u2717 ";break;case"cached":p="\u{1F4BE} ";break;case"running":p="\u23F3 ";break;case"skipped":p="\u2298 ";break}let h="";if(e.input!==void 0){let v=typeof e.input=="string"?j(e.input):j(JSON.stringify(e.input).slice(0,20));h+=`\\nin: ${v}`}if(e.output!==void 0&&e.state==="success"){let v=typeof e.output=="string"?j(e.output):j(JSON.stringify(e.output).slice(0,20));h+=`\\nout: ${v}`}let g="";if(n&&e.key&&n.onAfterStep.has(e.key)){let v=n.onAfterStep.get(e.key),w=v.state==="success"?"\u2699":"\u26A0",b=t.showTimings&&v.durationMs!==void 0?` ${H(v.durationMs)}`:"";g=`\\n${w} hook${b}`}let m=(p+d+h+g+u).trim(),S,$=e.name??e.id,O=o?.showHeatmap&&o.heatmapData?o.heatmapData.heat.get(e.id)??o.heatmapData.heat.get($):void 0;if(O!==void 0){let v=pt(O);S=jn(v)}else S=e.state;let D;switch(e.state){case"error":D=`{{${m}}}`;break;case"cached":D=`[(${m})]`;break;case"skipped":D=`[${m}]:::skipped`;break;default:D=`[${m}]`}if(r.push(` ${c}${D}:::${S}`),i&&e.retryCount!==void 0&&e.retryCount>0){let v=`\u21BB ${e.retryCount} retr${e.retryCount===1?"y":"ies"}`;r.push(` ${c} -.->|"${v}"| ${c}`)}if(a&&e.state==="error"&&e.error!==void 0){let v=`ERR_${c}`,w=j(String(e.error)).slice(0,30);r.push(` ${v}{{${w}}}`),r.push(` ${c} -->|error| ${v}`),r.push(` style ${v} fill:#fee2e2,stroke:#dc2626`)}if(l&&e.timedOut){let v=`TO_${c}`,w=e.timeoutMs!==void 0?`${e.timeoutMs}ms`:"";r.push(` ${v}{{\u23F1 Timeout ${w}}}`),r.push(` ${c} -.->|timeout| ${v}`),r.push(` style ${v} fill:#fef3c7,stroke:#f59e0b`)}return{entryId:c,exitId:c}}function Jn(e,t,r,o,n){let s=De("parallel"),i=`${s}_fork`,a=`${s}_join`,l=Qt(e.name??"Parallel"),c=e.mode==="allSettled"?" (allSettled)":"";if(e.children.length===0){let p=s,h=j(`${l}${c}`),g="operations not individually tracked",m=t.showTimings&&e.durationMs!==void 0?` ${H(e.durationMs)}`:"";return r.push(` ${p}[${h}${m}\\n${g}]:::${e.state}`),{entryId:p,exitId:p}}r.push(` subgraph ${s}["${l}${c}"]`),r.push(" direction TB"),r.push(` ${i}{"\u26A1 Fork"}`);let d=[];for(let p of e.children){let h=Ve(p,t,r,o,n);r.push(` ${i} --> ${h.entryId}`),d.push(h.exitId)}r.push(` ${a}{"\u2713 Join"}`);for(let p of d)r.push(` ${p} --> ${a}`);r.push(" end");let u=e.state;return r.push(` class ${s} ${u}`),{entryId:i,exitId:a}}function Xn(e,t,r,o,n){let s=De("race"),i=`${s}_start`,a=`${s}_end`,l=Qt(e.name??"Race");if(e.children.length===0){let p=s,h=j(l),g="operations not individually tracked",m=t.showTimings&&e.durationMs!==void 0?` ${H(e.durationMs)}`:"";return r.push(` ${p}[\u26A1 ${h}${m}\\n${g}]:::${e.state}`),{entryId:p,exitId:p}}r.push(` subgraph ${s}["\u26A1 ${l}"]`),r.push(" direction TB"),r.push(` ${i}(("\u{1F3C1} Start"))`);let c=[],d;for(let p of e.children){let h=Ve(p,t,r,o,n),g=J(p)&&e.winnerId===p.id;r.push(` ${i} --> ${h.entryId}`),g&&(d=h.exitId),c.push({exitId:h.exitId,isWinner:g})}r.push(` ${a}(("\u2713 First"))`);for(let{exitId:p,isWinner:h}of c)h&&d?r.push(` ${p} ==>|\u{1F3C6} Winner| ${a}`):e.winnerId?r.push(` ${p} -. cancelled .-> ${a}`):r.push(` ${p} --> ${a}`);r.push(" end");let u=e.state;return r.push(` class ${s} ${u}`),{entryId:i,exitId:a}}function Zn(e,t,r,o,n){let s=e.key?`decision_${e.key.replace(/[^a-zA-Z0-9]/g,"_")}`:De("decision"),i=j(e.condition??"condition"),a=e.decisionValue!==void 0?` = ${j(String(e.decisionValue)).slice(0,30)}`:"",l=`${i}${a}`.trim();r.push(` ${s}{${l}}`);let c=[],d;for(let u of e.branches){let p=`${s}_${u.label.replace(/[^a-zA-Z0-9]/g,"_")}`,h=j(u.label),g=u.taken?`${h} \u2713`:`${h} skipped`,m=u.taken?":::success":":::skipped";r.push(` ${p}[${g}]${m}`);let S=u.condition?`|${j(u.condition).replace(/\|/g,"")}|`:"";if(r.push(` ${s} -->${S} ${p}`),u.children.length>0){let $=p;for(let O of u.children){let D=Ve(O,t,r,o,n);r.push(` ${$} --> ${D.entryId}`),$=D.exitId}c.push($),u.taken&&(d=$)}else c.push(p),u.taken&&(d=p)}return d?{entryId:s,exitId:d}:{entryId:s,exitId:s}}function Qn(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function eo(e){let t=[];function r(o){for(let n of o)if(J(n))t.push(n);else if(jt(n))r(n.children);else if(Q(n)||oe(n))r(n.children);else if(se(n))for(let s of n.branches)r(s.children)}return r(e),t}function to(e){let t={id:e.id,name:e.name??e.key??e.id,state:e.state};return e.key&&(t.key=e.key),e.durationMs!==void 0&&(t.durationMs=e.durationMs),e.startTs!==void 0&&(t.startTs=e.startTs),e.endTs!==void 0&&(t.endTs=e.endTs),e.retryCount!==void 0&&e.retryCount>0&&(t.retryCount=e.retryCount),e.timedOut&&(t.timedOut=!0,e.timeoutMs!==void 0&&(t.timeoutMs=e.timeoutMs)),e.error!==void 0&&(t.error=typeof e.error=="string"?e.error:String(e.error)),t}function ro(e){let t=0,r=0,o=0,n=0,s=0,i;for(let a of e)a.state==="success"&&t++,a.state==="error"&&r++,a.state==="cached"&&o++,a.state==="skipped"&&n++,a.retryCount!==void 0&&(s+=a.retryCount),a.durationMs!==void 0&&(!i||a.durationMs>i.durationMs)&&(i={name:a.name??a.key??a.id,durationMs:a.durationMs});return{totalSteps:e.length,successCount:t,errorCount:r,cacheHits:o,skippedCount:n,totalRetries:s,slowestStep:i}}function no(e){let t={};if(e.shouldRun&&(t.shouldRun={result:e.shouldRun.context?.result,durationMs:e.shouldRun.durationMs},e.shouldRun.error&&(t.shouldRun.error=String(e.shouldRun.error))),e.onBeforeStart&&(t.onBeforeStart={durationMs:e.onBeforeStart.durationMs},e.onBeforeStart.error&&(t.onBeforeStart.error=String(e.onBeforeStart.error))),e.onAfterStep.size>0){t.onAfterStep=[];for(let[r,o]of e.onAfterStep){let n={stepKey:r};o.durationMs!==void 0&&(n.durationMs=o.durationMs),o.error&&(n.error=String(o.error)),t.onAfterStep.push(n)}}return t}function oo(e,t){let r=e.root,o=eo(r.children),n=t.includeDiagram??!0,s=t.stripAnsiColors??!0,i={workflow:{id:r.workflowId,name:r.name,state:r.state,durationMs:r.durationMs,startedAt:r.startTs,completedAt:r.endTs},steps:o.map(to),summary:ro(o)};if(e.hooks){let a=no(e.hooks);Object.keys(a).length>0&&(i.hooks=a)}if(n){let l=ce().render(e,t);s&&(l=Qn(l)),i.diagram=l}return i}function je(){return{name:"logger",supportsLive:!1,render(e,t){let o=oo(e,t);return JSON.stringify(o)}}}function er(e){let t={bg:"#ffffff",bgSecondary:"#f8f9fa",text:"#212529",textMuted:"#6c757d",border:"#dee2e6",primary:"#0d6efd",success:"#198754",error:"#dc3545",warning:"#ffc107",info:"#0dcaf0",muted:"#6c757d",nodePending:"#e9ecef",nodeRunning:"#fff3cd",nodeSuccess:"#d1e7dd",nodeError:"#f8d7da",nodeAborted:"#e9ecef",nodeCached:"#cfe2ff",nodeSkipped:"#f8f9fa",heatCold:"#0d6efd",heatCool:"#0dcaf0",heatNeutral:"#6c757d",heatWarm:"#ffc107",heatHot:"#fd7e14",heatCritical:"#dc3545"},r={bg:"#212529",bgSecondary:"#343a40",text:"#f8f9fa",textMuted:"#adb5bd",border:"#495057",primary:"#0d6efd",success:"#198754",error:"#dc3545",warning:"#ffc107",info:"#0dcaf0",muted:"#6c757d",nodePending:"#495057",nodeRunning:"#664d03",nodeSuccess:"#0f5132",nodeError:"#842029",nodeAborted:"#495057",nodeCached:"#084298",nodeSkipped:"#343a40",heatCold:"#0d6efd",heatCool:"#0dcaf0",heatNeutral:"#6c757d",heatWarm:"#ffc107",heatHot:"#fd7e14",heatCritical:"#dc3545"},o=s=>`
10
+ --bg: ${s.bg};
11
+ --bg-secondary: ${s.bgSecondary};
12
+ --text: ${s.text};
13
+ --text-muted: ${s.textMuted};
14
+ --border: ${s.border};
15
+ --primary: ${s.primary};
16
+ --success: ${s.success};
17
+ --error: ${s.error};
18
+ --warning: ${s.warning};
19
+ --info: ${s.info};
20
+ --muted: ${s.muted};
21
+ --node-pending: ${s.nodePending};
22
+ --node-running: ${s.nodeRunning};
23
+ --node-success: ${s.nodeSuccess};
24
+ --node-error: ${s.nodeError};
25
+ --node-aborted: ${s.nodeAborted};
26
+ --node-cached: ${s.nodeCached};
27
+ --node-skipped: ${s.nodeSkipped};
28
+ --heat-cold: ${s.heatCold};
29
+ --heat-cool: ${s.heatCool};
30
+ --heat-neutral: ${s.heatNeutral};
31
+ --heat-warm: ${s.heatWarm};
32
+ --heat-hot: ${s.heatHot};
33
+ --heat-critical: ${s.heatCritical};
34
+ `,n;return e==="auto"?n=`
29
35
  :root {
30
- ${a(r)}
36
+ ${o(t)}
31
37
  }
32
38
  @media (prefers-color-scheme: dark) {
33
39
  :root {
34
- ${a(t)}
40
+ ${o(r)}
35
41
  }
36
42
  }
37
- `:e==="dark"?o=`
43
+ `:e==="dark"?n=`
38
44
  :root {
39
- ${a(t)}
45
+ ${o(r)}
40
46
  }
41
- `:o=`
47
+ `:n=`
42
48
  :root {
43
- ${a(r)}
49
+ ${o(t)}
44
50
  }
45
51
  `,`
46
- ${o}
52
+ ${n}
47
53
 
48
54
  * {
49
55
  box-sizing: border-box;
@@ -499,7 +505,7 @@ body {
499
505
  height: auto;
500
506
  }
501
507
  }
502
- `}function We(e){return`
508
+ `}function tr(e){return`
503
509
  (function() {
504
510
  'use strict';
505
511
 
@@ -1081,41 +1087,41 @@ body {
1081
1087
  return (ms / 60000).toFixed(1) + 'm';
1082
1088
  }
1083
1089
  })();
1084
- `}var ee=160,de=50,we=40,mt=30,A=20;function ht(e,r="TB"){let t=r==="TB"||r==="BT",a=[],o=A,n=A,c=0,p=0;for(let d of e){let u=be(d,o,n,t);a.push(u.node),t?(n+=u.height+mt,c=Math.max(c,u.width),p=n):(o+=u.width+we,p=Math.max(p,u.height),c=o)}return{nodes:a,width:c+A,height:p+A}}function be(e,r,t,a){if(V(e))return{node:{id:e.id,name:e.name??e.key??"step",type:"step",state:e.state,x:r,y:t,width:ee,height:de,durationMs:e.durationMs},width:ee,height:de};if(J(e)||Y(e)){let o=J(e)?"parallel":"race",n=e.name??o,c=[],p=r+A,d=t+A+20,u=0,s=0;for(let h of e.children){let k=be(h,p,d,!0);c.push(k.node),p+=k.width+we,s=Math.max(s,k.height)}u=p-r-A;let l=Math.max(u+A,ee+A*2),f=s+A*2+20;return{node:{id:e.id,name:n,type:o,state:e.state,x:r,y:t,width:l,height:f,durationMs:e.durationMs,children:c,containerType:o,containerLabel:o==="parallel"?"PARALLEL":"RACE"},width:l,height:f}}if(X(e)){let o=e.name??"decision",n=[],c=r+A,p=t+A+20,d=0;for(let l of e.branches)for(let f of l.children){let h=be(f,c,p,!0);n.push(h.node),c+=h.width+we,d=Math.max(d,h.height)}let u=Math.max(c-r,ee+A*2),s=d+A*2+20;return{node:{id:e.id,name:o,type:"decision",state:e.state,x:r,y:t,width:u,height:s,durationMs:e.durationMs,children:n,containerType:"decision",containerLabel:"DECISION"},width:u,height:s}}return{node:{id:e.id,name:e.name??"unknown",type:e.type,state:e.state,x:r,y:t,width:ee,height:de},width:ee,height:de}}function Le(e,r){return e.containerType?vt(e,r):gt(e,r)}function gt(e,r){let a=r&&e.durationMs!==void 0?H(e.durationMs):"";return`
1085
- <g class="wv-node wv-node--${e.state}" data-node-id="${He(e.id)}" transform="translate(${e.x}, ${e.y})">
1090
+ `}var be=160,qe=50,mt=40,so=30,z=20;function io(e,t="TB"){let r=t==="TB"||t==="BT",o=[],n=z,s=z,i=0,a=0;for(let l of e){let c=gt(l,n,s,r);o.push(c.node),r?(s+=c.height+so,i=Math.max(i,c.width),a=s):(n+=c.width+mt,a=Math.max(a,c.height),i=n)}return{nodes:o,width:i+z,height:a+z}}function gt(e,t,r,o){if(J(e))return{node:{id:e.id,name:e.name??e.key??"step",type:"step",state:e.state,x:t,y:r,width:be,height:qe,durationMs:e.durationMs},width:be,height:qe};if(Q(e)||oe(e)){let n=Q(e)?"parallel":"race",s=e.name??n,i=[],a=t+z,l=r+z+20,c=0,d=0;for(let h of e.children){let g=gt(h,a,l,!0);i.push(g.node),a+=g.width+mt,d=Math.max(d,g.height)}c=a-t-z;let u=Math.max(c+z,be+z*2),p=d+z*2+20;return{node:{id:e.id,name:s,type:n,state:e.state,x:t,y:r,width:u,height:p,durationMs:e.durationMs,children:i,containerType:n,containerLabel:n==="parallel"?"PARALLEL":"RACE"},width:u,height:p}}if(se(e)){let n=e.name??"decision",s=[],i=t+z,a=r+z+20,l=0;for(let u of e.branches)for(let p of u.children){let h=gt(p,i,a,!0);s.push(h.node),i+=h.width+mt,l=Math.max(l,h.height)}let c=Math.max(i-t,be+z*2),d=l+z*2+20;return{node:{id:e.id,name:n,type:"decision",state:e.state,x:t,y:r,width:c,height:d,durationMs:e.durationMs,children:s,containerType:"decision",containerLabel:"DECISION"},width:c,height:d}}return{node:{id:e.id,name:e.name??"unknown",type:e.type,state:e.state,x:t,y:r,width:be,height:qe},width:be,height:qe}}function rr(e,t){return e.containerType?co(e,t):ao(e,t)}function ao(e,t){let o=t&&e.durationMs!==void 0?H(e.durationMs):"";return`
1091
+ <g class="wv-node wv-node--${e.state}" data-node-id="${or(e.id)}" transform="translate(${e.x}, ${e.y})">
1086
1092
  <rect width="${e.width}" height="${e.height}" rx="8" ry="8" />
1087
- <text x="${e.width/2}" y="${e.height/2-(a?4:0)}">${ye(kt(e.name,20))}</text>
1088
- ${a?`<text class="wv-node-timing" x="${e.width/2}" y="${e.height/2+12}">${a}</text>`:""}
1093
+ <text x="${e.width/2}" y="${e.height/2-(o?4:0)}">${yt(po(e.name,20))}</text>
1094
+ ${o?`<text class="wv-node-timing" x="${e.width/2}" y="${e.height/2+12}">${o}</text>`:""}
1089
1095
  </g>
1090
- `}function vt(e,r){let a=e.children?.map(o=>Le(o,r)).join(`
1096
+ `}function co(e,t){let o=e.children?.map(n=>rr(n,t)).join(`
1091
1097
  `)??"";return`
1092
- <g class="wv-container wv-container--${e.containerType}" data-node-id="${He(e.id)}" transform="translate(${e.x}, ${e.y})">
1098
+ <g class="wv-container wv-container--${e.containerType}" data-node-id="${or(e.id)}" transform="translate(${e.x}, ${e.y})">
1093
1099
  <rect width="${e.width}" height="${e.height}" rx="12" ry="12" />
1094
- <text class="wv-container-label" x="${A}" y="16">${e.containerLabel}</text>
1100
+ <text class="wv-container-label" x="${z}" y="16">${e.containerLabel}</text>
1095
1101
  <g transform="translate(${-e.x}, ${-e.y})">
1096
- ${a}
1102
+ ${o}
1097
1103
  </g>
1098
1104
  </g>
1099
- `}function wt(e){let r=[];for(let t=0;t<e.length-1;t++){let a=e[t],o=e[t+1],n=a.x+a.width/2,c=a.y+a.height,p=o.x+o.width/2,d=o.y;r.push(`
1100
- <path class="wv-edge" d="M ${n} ${c} L ${p} ${d-8}" />
1101
- <polygon class="wv-edge-arrow" points="${p-4},${d-8} ${p+4},${d-8} ${p},${d}" />
1102
- `)}return r.join(`
1103
- `)}function Be(e,r){let t=ht(e.root.children,r.layout),a=Math.max(t.width,400),o=Math.max(t.height,300),n=t.nodes.map(s=>Le(s,r.showTimings)).join(`
1104
- `),c=wt(t.nodes),p=e.root.name??"Workflow",d=Oe(r.theme),u=We({wsUrl:r.wsUrl,interactive:r.interactive,timeTravel:r.timeTravel,heatmap:r.heatmap});return`<!DOCTYPE html>
1105
+ `}function lo(e){let t=[];for(let r=0;r<e.length-1;r++){let o=e[r],n=e[r+1],s=o.x+o.width/2,i=o.y+o.height,a=n.x+n.width/2,l=n.y;t.push(`
1106
+ <path class="wv-edge" d="M ${s} ${i} L ${a} ${l-8}" />
1107
+ <polygon class="wv-edge-arrow" points="${a-4},${l-8} ${a+4},${l-8} ${a},${l}" />
1108
+ `)}return t.join(`
1109
+ `)}function nr(e,t){let r=io(e.root.children,t.layout),o=Math.max(r.width,400),n=Math.max(r.height,300),s=r.nodes.map(d=>rr(d,t.showTimings)).join(`
1110
+ `),i=lo(r.nodes),a=e.root.name??"Workflow",l=er(t.theme),c=tr({wsUrl:t.wsUrl,interactive:t.interactive,timeTravel:t.timeTravel,heatmap:t.heatmap});return`<!DOCTYPE html>
1105
1111
  <html lang="en">
1106
1112
  <head>
1107
1113
  <meta charset="UTF-8">
1108
1114
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1109
- <title>${ye(p)} - Workflow Visualizer</title>
1110
- <style>${d}</style>
1115
+ <title>${yt(a)} - Workflow Visualizer</title>
1116
+ <style>${l}</style>
1111
1117
  </head>
1112
1118
  <body>
1113
1119
  <div class="workflow-visualizer">
1114
1120
  <header class="wv-header">
1115
- <h1>${ye(p)}</h1>
1121
+ <h1>${yt(a)}</h1>
1116
1122
  <div class="wv-controls">
1117
- ${r.wsUrl?'<div id="live-indicator" class="wv-live" style="display:none"><span class="wv-live-dot"></span>LIVE</div>':""}
1118
- ${r.heatmap?`
1123
+ ${t.wsUrl?'<div id="live-indicator" class="wv-live" style="display:none"><span class="wv-live-dot"></span>LIVE</div>':""}
1124
+ ${t.heatmap?`
1119
1125
  <button id="heatmap-toggle" class="wv-btn">Heatmap</button>
1120
1126
  <select id="heatmap-metric" class="wv-btn">
1121
1127
  <option value="duration">Duration</option>
@@ -1123,7 +1129,7 @@ body {
1123
1129
  <option value="errorRate">Error Rate</option>
1124
1130
  </select>
1125
1131
  `:""}
1126
- ${r.interactive?`
1132
+ ${t.interactive?`
1127
1133
  <button id="zoom-out" class="wv-btn wv-btn--icon" title="Zoom out (-)">\u2212</button>
1128
1134
  <button id="zoom-reset" class="wv-btn wv-btn--icon" title="Reset zoom (0)">\u27F2</button>
1129
1135
  <button id="zoom-in" class="wv-btn wv-btn--icon" title="Zoom in (+)">+</button>
@@ -1133,15 +1139,15 @@ body {
1133
1139
 
1134
1140
  <div class="wv-main">
1135
1141
  <div id="diagram" class="wv-diagram">
1136
- <svg viewBox="0 0 ${a} ${o}" preserveAspectRatio="xMidYMid meet">
1142
+ <svg viewBox="0 0 ${o} ${n}" preserveAspectRatio="xMidYMid meet">
1137
1143
  <g class="wv-root">
1138
- ${c}
1139
- ${n}
1144
+ ${i}
1145
+ ${s}
1140
1146
  </g>
1141
1147
  </svg>
1142
1148
  </div>
1143
1149
 
1144
- ${r.interactive?`
1150
+ ${t.interactive?`
1145
1151
  <aside id="inspector" class="wv-inspector">
1146
1152
  <div class="wv-inspector-header">
1147
1153
  <h2>Inspector</h2>
@@ -1153,7 +1159,7 @@ body {
1153
1159
  `:""}
1154
1160
  </div>
1155
1161
 
1156
- ${r.timeTravel?`
1162
+ ${t.timeTravel?`
1157
1163
  <div id="timeline" class="wv-timeline">
1158
1164
  <div class="wv-timeline-track">
1159
1165
  <input type="range" id="tt-slider" min="0" max="0" value="0" style="width:100%">
@@ -1177,13 +1183,13 @@ body {
1177
1183
  </div>
1178
1184
 
1179
1185
  <script>
1180
- window.__WORKFLOW_DATA__ = ${yt(e)};
1186
+ window.__WORKFLOW_DATA__ = ${fo(e)};
1181
1187
  </script>
1182
- <script>${u}</script>
1188
+ <script>${c}</script>
1183
1189
  </body>
1184
- </html>`}function bt(e){let r={};function t(a){for(let o of a)if(r[o.id]={id:o.id,name:o.name,type:o.type,state:o.state,key:o.key,durationMs:o.durationMs,startTs:o.startTs,error:o.error?String(o.error):void 0,retryCount:o.retryCount},"children"in o&&Array.isArray(o.children)&&t(o.children),"branches"in o)for(let n of o.branches)t(n.children)}return t(e.root.children),{nodes:r}}function yt(e){return JSON.stringify(bt(e)).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function ye(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function He(e){return e.replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function kt(e,r){return e.length<=r?e:e.slice(0,r-1)+"\u2026"}var Pe={interactive:!0,timeTravel:!0,heatmap:!0,animationDuration:200,theme:"auto",layout:"TB"};function St(){return{name:"html",supportsLive:!0,render(e,r){let t={...r,...Pe,...r};return Be(e,t)}}}function ke(e,r={}){let t={showTimings:!0,showKeys:!1,colors:{pending:"#6c757d",running:"#ffc107",success:"#198754",error:"#dc3545",aborted:"#6c757d",cached:"#0dcaf0",skipped:"#adb5bd"},...Pe,...r};return Be(e,t)}var K={clearToEnd:"\x1B[J",cursorUp:e=>`\x1B[${e}A`,cursorToStart:"\x1B[G",hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",saveCursor:"\x1B[s",restoreCursor:"\x1B[u"};function xt(e={}){let{workflowName:r,detectParallel:t=!0,showTimings:a=!0,showKeys:o=!1,colors:n,stream:c=process.stdout,updateInterval:p=100}=e,d=q({detectParallel:t}),u=Q(),s={showTimings:a,showKeys:o,terminalWidth:c.columns??80,colors:{...j,...n}},l=!1,f="",h=0,k=null,v=!1;function R(N){c.writable&&c.write(N)}function T(){if(!l)return;let N=w(),S=u.render(N,s);S!==f&&(h>0&&(R(K.cursorUp(h)),R(K.cursorToStart),R(K.clearToEnd)),R(S),R(`
1185
- `),f=S,h=S.split(`
1186
- `).length)}function B(){l&&(v=!0,k===null&&(k=setTimeout(()=>{k=null,v&&(v=!1,T())},p)))}function O(N){if(N.type==="scope_start"||N.type==="scope_end"){g(N);return}d.handleEvent(N),l&&(N.type==="workflow_start"||N.type==="workflow_success"||N.type==="workflow_error"?T():B())}function g(N){d.handleScopeEvent(N),l&&B()}function I(N){d.handleDecisionEvent(N),l&&B()}function w(){let N=d.getIR();return r&&!N.root.name&&(N.root.name=r),N}function $(){return u.render(w(),s)}function W(){l||(l=!0,f="",h=0,R(K.hideCursor),T())}function C(){if(!l)return;l=!1,k!==null&&(clearTimeout(k),k=null);let N=w(),S=u.render(N,s);h>0&&(R(K.cursorUp(h)),R(K.cursorToStart),R(K.clearToEnd)),R(S),R(`
1187
- `),R(K.showCursor)}function D(){k!==null&&(clearTimeout(k),k=null),v=!1,T()}function M(){d.reset(),f="",h=0}return{handleEvent:O,handleScopeEvent:g,handleDecisionEvent:I,getIR:w,render:$,start:W,stop:C,refresh:D,reset:M}}function Se(e,r={}){let{condition:t,value:a,name:o,workflowId:n=crypto.randomUUID(),emit:c}=r,p=Date.now(),d,u=[];function s(f,h,k){u.push({label:f,condition:k,taken:h}),h&&(d=f),c?.({type:"decision_branch",workflowId:n,decisionId:e,branchLabel:f,condition:k,taken:h,ts:Date.now()})}function l(){let f=Date.now()-p;c?.({type:"decision_end",workflowId:n,decisionId:e,branchTaken:d,ts:Date.now(),durationMs:f})}return c?.({type:"decision_start",workflowId:n,decisionId:e,condition:t,decisionValue:a,name:o,ts:p}),{takeBranch:s,end:l,getBranchTaken:()=>d,getBranches:()=>[...u]}}function $t(e,r,t={}){let a=Se(e,{...t,condition:t.condition??String(r),value:t.value??r});return{...a,condition:r,then:()=>{a.takeBranch("if",!0)},else:()=>{a.takeBranch("else",!0)}}}function Rt(e,r,t={}){let a=Se(e,{...t,condition:t.condition??`switch(${String(r)})`,value:r});return{...a,value:r,case:(o,n)=>{a.takeBranch(`case '${o}'`,n,`value === '${o}'`)},default:o=>{a.takeBranch("default",o)}}}function xe(e={}){let{maxSnapshots:r=1e3,autoRecord:t=!0,builderOptions:a={}}=e,o=q({...a,enableSnapshots:!0,maxSnapshots:r}),n={snapshots:[],currentIndex:-1,isPlaying:!1,playbackSpeed:1,isRecording:t},c=new Set,p=null;function d(){let D=g();for(let M of c)M(D)}function u(){n.snapshots=o.getSnapshots(),n.isRecording&&n.snapshots.length>0&&(n.currentIndex=n.snapshots.length-1)}function s(D){o.handleEvent(D),n.isRecording&&(u(),d())}function l(D){let M=o.getSnapshots();if(!(D<0||D>=M.length))return n.currentIndex=D,n.snapshots=M,d(),M[D].ir}function f(){return l(n.currentIndex+1)}function h(){return l(n.currentIndex-1)}function k(D=1){n.playbackSpeed=D,n.isPlaying=!0,d();let M=()=>{if(!n.isPlaying)return;let N=o.getSnapshots();if(n.currentIndex<N.length-1){let S=N[n.currentIndex],L=(N[n.currentIndex+1].timestamp-S.timestamp)/n.playbackSpeed;p=setTimeout(()=>{f(),M()},Math.max(16,L))}else v()};M()}function v(){n.isPlaying=!1,p&&(clearTimeout(p),p=null),d()}function R(){let D=o.getSnapshots();return n.currentIndex>=0&&n.currentIndex<D.length?D[n.currentIndex].ir:o.getIR()}function T(D){return o.getIRAt(D)}function B(){return o.getSnapshots()}function O(D){return o.getSnapshotAt(D)}function g(){return{snapshots:o.getSnapshots(),currentIndex:n.currentIndex,isPlaying:n.isPlaying,playbackSpeed:n.playbackSpeed,isRecording:n.isRecording}}function I(D){return c.add(D),()=>c.delete(D)}function w(){n.isRecording=!0,d()}function $(){n.isRecording=!1,d()}function W(){v(),o.reset(),n={snapshots:[],currentIndex:-1,isPlaying:!1,playbackSpeed:1,isRecording:t},d()}function C(){return o}return{handleEvent:s,seek:l,stepForward:f,stepBackward:h,play:k,pause:v,getCurrentIR:R,getIRAt:T,getSnapshots:B,getSnapshotAt:O,getState:g,onStateChange:I,startRecording:w,stopRecording:$,reset:W,getBuilder:C}}import{createServer as Et}from"http";import{execFile as $e}from"child_process";async function It(e={}){let{port:r=3377,host:t="localhost",autoOpen:a=!0,workflowName:o="Workflow",timeTravel:n=!0,heatmap:c=!0,maxSnapshots:p=1e3}=e,d=xe({maxSnapshots:p}),u=ve(),s=null,l=null,f=r,h=!1;function k(S){if(!l)return;let x=JSON.stringify(S);for(let E of l.clients)E.readyState===E.OPEN&&E.send(x)}function v(S,x){try{let E=JSON.parse(typeof x=="string"?x:x.toString());switch(E.type){case"time_travel_seek":{let L=E.payload,i=d.seek(L.index);i&&S.send(JSON.stringify({type:"ir_update",payload:i}));break}case"time_travel_play":{let L=E.payload;d.play(L?.speed);break}case"time_travel_pause":d.pause();break;case"time_travel_step_forward":{let L=d.stepForward();L&&S.send(JSON.stringify({type:"ir_update",payload:L}));break}case"time_travel_step_backward":{let L=d.stepBackward();L&&S.send(JSON.stringify({type:"ir_update",payload:L}));break}case"request_snapshots":{let L=d.getSnapshots().map(i=>({id:i.id,eventIndex:i.eventIndex,timestamp:i.timestamp}));S.send(JSON.stringify({type:"snapshots_list",payload:L}));break}case"toggle_heatmap":case"set_heatmap_metric":break}}catch(E){console.error("[DevServer] Failed to handle message:",E)}}function R(){let S=d.getCurrentIR(),x=`ws://${t}:${f}`;return ke(S,{interactive:!0,timeTravel:n,heatmap:c,theme:"auto",layout:"TB",wsUrl:x})}function T(S,x){let E=S.url??"/";if(E==="/"||E==="/index.html"){x.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),x.end(R());return}if(E==="/api/snapshots"){let L=d.getSnapshots().map(i=>({id:i.id,eventIndex:i.eventIndex,timestamp:i.timestamp}));x.writeHead(200,{"Content-Type":"application/json"}),x.end(JSON.stringify(L));return}if(E==="/api/performance"){x.writeHead(200,{"Content-Type":"application/json"}),x.end(u.exportData());return}if(E==="/api/ir"){x.writeHead(200,{"Content-Type":"application/json"}),x.end(JSON.stringify(d.getCurrentIR()));return}x.writeHead(404,{"Content-Type":"text/plain"}),x.end("Not Found")}async function B(){try{let x=await import("ws"),E=x.WebSocketServer??x.default?.WebSocketServer;return E?new E({noServer:!0}):(console.warn("[DevServer] WebSocket server class not found in ws module"),null)}catch{return console.warn(`[DevServer] ws package not installed. Live updates disabled.
1188
- Install with: npm install ws`),null}}function O(S){let x=process.platform;if(!S.startsWith("http://localhost:")&&!S.startsWith("http://127.0.0.1:")){console.warn("[DevServer] Refusing to open non-localhost URL");return}x==="darwin"?$e("open",[S],E=>{E&&console.warn("[DevServer] Failed to open browser:",E.message)}):x==="win32"?$e("cmd.exe",["/c","start","",S],E=>{E&&console.warn("[DevServer] Failed to open browser:",E.message)}):$e("xdg-open",[S],E=>{E&&console.warn("[DevServer] Failed to open browser:",E.message)})}async function g(){return h?{port:f,url:`http://${t}:${f}`}:(s=Et(T),l=await B(),l&&(s.on("upgrade",(S,x,E)=>{if(!l)return;l.handleUpgrade(S,x,E,i=>{i.send(JSON.stringify({type:"ir_update",payload:d.getCurrentIR()})),i.on("message",m=>v(i,m)),i.on("error",m=>console.error("[DevServer] WS error:",m))})}),d.onStateChange(S=>{k({type:"time_travel_state",payload:S})})),new Promise((S,x)=>{if(!s){x(new Error("HTTP server not initialized"));return}s.on("error",E=>{E.code==="EADDRINUSE"?(f++,s?.listen(f,t)):x(E)}),s.on("listening",()=>{h=!0;let E=`http://${t}:${f}`;console.log(`[DevServer] Visualizer running at ${E}`),a&&O(E),S({port:f,url:E})}),s.listen(f,t)}))}async function I(){if(h)return new Promise(S=>{l&&(l.close(),l=null),s?s.close(()=>{s=null,h=!1,S()}):S()})}function w(S){d.handleEvent(S),u.addEvent(S),k({type:"ir_update",payload:d.getCurrentIR()})}function $(S){k({type:"ir_update",payload:S})}function W(S){let x={};for(let[E,L]of S.heat)x[E]=L;k({type:"performance_data",payload:{...S,heat:x}})}function C(){u.finalizeRun("current"),k({type:"workflow_complete",payload:null})}function D(){return d}function M(){return u}function N(){return d.getCurrentIR()}return{start:g,stop:I,handleEvent:w,pushUpdate:$,pushHeatmap:W,complete:C,getTimeTravel:D,getAnalyzer:M,getCurrentIR:N}}function Re(e={}){let{workflowName:r,detectParallel:t=!0,showTimings:a=!0,showKeys:o=!1,colors:n}=e,c=q({detectParallel:t}),p=new Set,d=Q(),u=se(),s={showTimings:a,showKeys:o,terminalWidth:process.stdout?.columns??80,colors:{...j,...n}};function l(){if(p.size>0){let g=c.getIR();for(let I of p)I(g)}}function f(g){if(g.type==="scope_start"||g.type==="scope_end"){h(g);return}c.handleEvent(g),g.type,l()}function h(g){c.handleScopeEvent(g),l()}function k(g){c.handleDecisionEvent(g),l()}function v(){let g=c.getIR();return r&&!g.root.name&&(g.root.name=r),g}function R(){let g=v();return d.render(g,s)}function T(g){let I=v();switch(g){case"ascii":return d.render(I,s);case"mermaid":return u.render(I,s);case"json":return JSON.stringify(I,null,2);default:throw new Error(`Unknown format: ${g}`)}}function B(){c.reset(),l()}function O(g){return p.add(g),()=>p.delete(g)}return{handleEvent:f,handleScopeEvent:h,handleDecisionEvent:k,getIR:v,render:R,renderAs:T,reset:B,onUpdate:O}}function wn(e,r={}){let t=Re(r);for(let a of e)a.type.startsWith("decision_")?t.handleDecisionEvent(a):t.handleEvent(a);return t.render()}function bn(e={}){let r=[];return{handleEvent:t=>{r.push(t)},handleDecisionEvent:t=>{r.push(t)},getEvents:()=>[...r],getWorkflowEvents:()=>r.filter(t=>!t.type.startsWith("decision_")),getDecisionEvents:()=>r.filter(t=>t.type.startsWith("decision_")),clear:()=>{r.length=0},visualize:()=>{let t=Re(e);for(let a of r)a.type.startsWith("decision_")?t.handleDecisionEvent(a):t.handleEvent(a);return t.render()},visualizeAs:t=>{let a=Re(e);for(let o of r)o.type.startsWith("decision_")?a.handleDecisionEvent(o):a.handleEvent(o);return a.renderAs(t)}}}export{Q as asciiRenderer,It as createDevServer,bn as createEventCollector,q as createIRBuilder,xt as createLiveVisualizer,Fe as createParallelDetector,ve as createPerformanceAnalyzer,xe as createTimeTravelController,Re as createVisualizer,j as defaultColorScheme,oe as detectParallelGroups,ge as getHeatLevel,Ot as hasChildren,St as htmlRenderer,X as isDecisionNode,J as isParallelNode,Y as isRaceNode,Ct as isSequenceNode,V as isStepNode,se as mermaidRenderer,ke as renderToHTML,Se as trackDecision,$t as trackIf,Rt as trackSwitch,wn as visualizeEvents};
1190
+ </html>`}function uo(e){let t={};function r(o){for(let n of o)if(t[n.id]={id:n.id,name:n.name,type:n.type,state:n.state,key:n.key,durationMs:n.durationMs,startTs:n.startTs,error:n.error?String(n.error):void 0,retryCount:n.retryCount},"children"in n&&Array.isArray(n.children)&&r(n.children),"branches"in n)for(let s of n.branches)r(s.children)}return r(e.root.children),{nodes:t}}function fo(e){return JSON.stringify(uo(e)).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function yt(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function or(e){return e.replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function po(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}var sr={interactive:!0,timeTravel:!0,heatmap:!0,animationDuration:200,theme:"auto",layout:"TB"};function ho(){return{name:"html",supportsLive:!0,render(e,t){let r={...t,...sr,...t};return nr(e,r)}}}function vt(e,t={}){let r={showTimings:!0,showKeys:!1,colors:{pending:"#6c757d",running:"#ffc107",success:"#198754",error:"#dc3545",aborted:"#6c757d",cached:"#0dcaf0",skipped:"#adb5bd"},...sr,...t};return nr(e,r)}var le={clearToEnd:"\x1B[J",cursorUp:e=>`\x1B[${e}A`,cursorToStart:"\x1B[G",hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",saveCursor:"\x1B[s",restoreCursor:"\x1B[u"};function mo(e={}){let{workflowName:t,detectParallel:r=!0,showTimings:o=!0,showKeys:n=!1,colors:s,stream:i=process.stdout,updateInterval:a=100}=e,l=pe({detectParallel:r}),c=ce(),d={showTimings:o,showKeys:n,terminalWidth:i.columns??80,colors:{...ae,...s}},u=!1,p="",h=0,g=null,m=!1;function S(N){i.writable&&i.write(N)}function $(){if(!u)return;let N=b(),E=c.render(N,d);E!==p&&(h>0&&(S(le.cursorUp(h)),S(le.cursorToStart),S(le.clearToEnd)),S(E),S(`
1191
+ `),p=E,h=E.split(`
1192
+ `).length)}function O(){u&&(m=!0,g===null&&(g=setTimeout(()=>{g=null,m&&(m=!1,$())},a)))}function D(N){if(N.type==="scope_start"||N.type==="scope_end"){v(N);return}l.handleEvent(N),u&&(N.type==="workflow_start"||N.type==="workflow_success"||N.type==="workflow_error"?$():O())}function v(N){l.handleScopeEvent(N),u&&O()}function w(N){l.handleDecisionEvent(N),u&&O()}function b(){let N=l.getIR();return t&&!N.root.name&&(N.root.name=t),N}function k(){return c.render(b(),d)}function B(){u||(u=!0,p="",h=0,S(le.hideCursor),$())}function C(){if(!u)return;u=!1,g!==null&&(clearTimeout(g),g=null);let N=b(),E=c.render(N,d);h>0&&(S(le.cursorUp(h)),S(le.cursorToStart),S(le.clearToEnd)),S(E),S(`
1193
+ `),S(le.showCursor)}function I(){g!==null&&(clearTimeout(g),g=null),m=!1,$()}function L(){l.reset(),p="",h=0}return{handleEvent:D,handleScopeEvent:v,handleDecisionEvent:w,getIR:b,render:k,start:B,stop:C,refresh:I,reset:L}}function wt(e,t={}){let{condition:r,value:o,name:n,workflowId:s=crypto.randomUUID(),emit:i}=t,a=Date.now(),l,c=[];function d(p,h,g){c.push({label:p,condition:g,taken:h}),h&&(l=p),i?.({type:"decision_branch",workflowId:s,decisionId:e,branchLabel:p,condition:g,taken:h,ts:Date.now()})}function u(){let p=Date.now()-a;i?.({type:"decision_end",workflowId:s,decisionId:e,branchTaken:l,ts:Date.now(),durationMs:p})}return i?.({type:"decision_start",workflowId:s,decisionId:e,condition:r,decisionValue:o,name:n,ts:a}),{takeBranch:d,end:u,getBranchTaken:()=>l,getBranches:()=>[...c]}}function go(e,t,r={}){let o=wt(e,{...r,condition:r.condition??String(t),value:r.value??t});return{...o,condition:t,then:()=>{o.takeBranch("if",!0)},else:()=>{o.takeBranch("else",!0)}}}function yo(e,t,r={}){let o=wt(e,{...r,condition:r.condition??`switch(${String(t)})`,value:t});return{...o,value:t,case:(n,s)=>{o.takeBranch(`case '${n}'`,s,`value === '${n}'`)},default:n=>{o.takeBranch("default",n)}}}function bt(e={}){let{maxSnapshots:t=1e3,autoRecord:r=!0,builderOptions:o={}}=e,n=pe({...o,enableSnapshots:!0,maxSnapshots:t}),s={snapshots:[],currentIndex:-1,isPlaying:!1,playbackSpeed:1,isRecording:r},i=new Set,a=null;function l(){let I=v();for(let L of i)L(I)}function c(){s.snapshots=n.getSnapshots(),s.isRecording&&s.snapshots.length>0&&(s.currentIndex=s.snapshots.length-1)}function d(I){n.handleEvent(I),s.isRecording&&(c(),l())}function u(I){let L=n.getSnapshots();if(!(I<0||I>=L.length))return s.currentIndex=I,s.snapshots=L,l(),L[I].ir}function p(){return u(s.currentIndex+1)}function h(){return u(s.currentIndex-1)}function g(I=1){s.playbackSpeed=I,s.isPlaying=!0,l();let L=()=>{if(!s.isPlaying)return;let N=n.getSnapshots();if(s.currentIndex<N.length-1){let E=N[s.currentIndex],W=(N[s.currentIndex+1].timestamp-E.timestamp)/s.playbackSpeed;a=setTimeout(()=>{p(),L()},Math.max(16,W))}else m()};L()}function m(){s.isPlaying=!1,a&&(clearTimeout(a),a=null),l()}function S(){let I=n.getSnapshots();return s.currentIndex>=0&&s.currentIndex<I.length?I[s.currentIndex].ir:n.getIR()}function $(I){return n.getIRAt(I)}function O(){return n.getSnapshots()}function D(I){return n.getSnapshotAt(I)}function v(){return{snapshots:n.getSnapshots(),currentIndex:s.currentIndex,isPlaying:s.isPlaying,playbackSpeed:s.playbackSpeed,isRecording:s.isRecording}}function w(I){return i.add(I),()=>i.delete(I)}function b(){s.isRecording=!0,l()}function k(){s.isRecording=!1,l()}function B(){m(),n.reset(),s={snapshots:[],currentIndex:-1,isPlaying:!1,playbackSpeed:1,isRecording:r},l()}function C(){return n}return{handleEvent:d,seek:u,stepForward:p,stepBackward:h,play:g,pause:m,getCurrentIR:S,getIRAt:$,getSnapshots:O,getSnapshotAt:D,getState:v,onStateChange:w,startRecording:b,stopRecording:k,reset:B,getBuilder:C}}import{createServer as Ps}from"http";import{execFile as zt}from"child_process";async function As(e={}){let{port:t=3377,host:r="localhost",autoOpen:o=!0,workflowName:n="Workflow",timeTravel:s=!0,heatmap:i=!0,maxSnapshots:a=1e3}=e,l=bt({maxSnapshots:a}),c=ht(),d=null,u=null,p=t,h=!1;function g(E){if(!u)return;let R=JSON.stringify(E);for(let T of u.clients)T.readyState===T.OPEN&&T.send(R)}function m(E,R){try{let T=JSON.parse(typeof R=="string"?R:R.toString());switch(T.type){case"time_travel_seek":{let W=T.payload,f=l.seek(W.index);f&&E.send(JSON.stringify({type:"ir_update",payload:f}));break}case"time_travel_play":{let W=T.payload;l.play(W?.speed);break}case"time_travel_pause":l.pause();break;case"time_travel_step_forward":{let W=l.stepForward();W&&E.send(JSON.stringify({type:"ir_update",payload:W}));break}case"time_travel_step_backward":{let W=l.stepBackward();W&&E.send(JSON.stringify({type:"ir_update",payload:W}));break}case"request_snapshots":{let W=l.getSnapshots().map(f=>({id:f.id,eventIndex:f.eventIndex,timestamp:f.timestamp}));E.send(JSON.stringify({type:"snapshots_list",payload:W}));break}case"toggle_heatmap":case"set_heatmap_metric":break}}catch(T){console.error("[DevServer] Failed to handle message:",T)}}function S(){let E=l.getCurrentIR(),R=`ws://${r}:${p}`;return vt(E,{interactive:!0,timeTravel:s,heatmap:i,theme:"auto",layout:"TB",wsUrl:R})}function $(E,R){let T=E.url??"/";if(T==="/"||T==="/index.html"){R.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),R.end(S());return}if(T==="/api/snapshots"){let W=l.getSnapshots().map(f=>({id:f.id,eventIndex:f.eventIndex,timestamp:f.timestamp}));R.writeHead(200,{"Content-Type":"application/json"}),R.end(JSON.stringify(W));return}if(T==="/api/performance"){R.writeHead(200,{"Content-Type":"application/json"}),R.end(c.exportData());return}if(T==="/api/ir"){R.writeHead(200,{"Content-Type":"application/json"}),R.end(JSON.stringify(l.getCurrentIR()));return}R.writeHead(404,{"Content-Type":"text/plain"}),R.end("Not Found")}async function O(){try{let R=await Promise.resolve().then(()=>(gn(),mn)),T=R.WebSocketServer??R.default?.WebSocketServer;return T?new T({noServer:!0}):(console.warn("[DevServer] WebSocket server class not found in ws module"),null)}catch{return console.warn(`[DevServer] ws package not installed. Live updates disabled.
1194
+ Install with: npm install ws`),null}}function D(E){let R=process.platform;if(!E.startsWith("http://localhost:")&&!E.startsWith("http://127.0.0.1:")){console.warn("[DevServer] Refusing to open non-localhost URL");return}R==="darwin"?zt("open",[E],T=>{T&&console.warn("[DevServer] Failed to open browser:",T.message)}):R==="win32"?zt("cmd.exe",["/c","start","",E],T=>{T&&console.warn("[DevServer] Failed to open browser:",T.message)}):zt("xdg-open",[E],T=>{T&&console.warn("[DevServer] Failed to open browser:",T.message)})}async function v(){return h?{port:p,url:`http://${r}:${p}`}:(d=Ps($),u=await O(),u&&(d.on("upgrade",(E,R,T)=>{if(!u)return;u.handleUpgrade(E,R,T,f=>{f.send(JSON.stringify({type:"ir_update",payload:l.getCurrentIR()})),f.on("message",y=>m(f,y)),f.on("error",y=>console.error("[DevServer] WS error:",y))})}),l.onStateChange(E=>{g({type:"time_travel_state",payload:E})})),new Promise((E,R)=>{if(!d){R(new Error("HTTP server not initialized"));return}d.on("error",T=>{T.code==="EADDRINUSE"?(p++,d?.listen(p,r)):R(T)}),d.on("listening",()=>{h=!0;let T=`http://${r}:${p}`;console.log(`[DevServer] Visualizer running at ${T}`),o&&D(T),E({port:p,url:T})}),d.listen(p,r)}))}async function w(){if(h)return new Promise(E=>{u&&(u.close(),u=null),d?d.close(()=>{d=null,h=!1,E()}):E()})}function b(E){l.handleEvent(E),c.addEvent(E),g({type:"ir_update",payload:l.getCurrentIR()})}function k(E){g({type:"ir_update",payload:E})}function B(E){let R={};for(let[T,W]of E.heat)R[T]=W;g({type:"performance_data",payload:{...E,heat:R}})}function C(){c.finalizeRun("current"),g({type:"workflow_complete",payload:null})}function I(){return l}function L(){return c}function N(){return l.getCurrentIR()}return{start:v,stop:w,handleEvent:b,pushUpdate:k,pushHeatmap:B,complete:C,getTimeTravel:I,getAnalyzer:L,getCurrentIR:N}}function Vt(e={}){let{workflowName:t,detectParallel:r=!0,showTimings:o=!0,showKeys:n=!1,colors:s}=e,i=pe({detectParallel:r}),a=new Set,l=ce(),c=ze(),d=je(),u={showTimings:o,showKeys:n,terminalWidth:process.stdout?.columns??80,colors:{...ae,...s}};function p(){if(a.size>0){let w=i.getIR();for(let b of a)b(w)}}function h(w){if(w.type==="scope_start"||w.type==="scope_end"){g(w);return}i.handleEvent(w),w.type,p()}function g(w){i.handleScopeEvent(w),p()}function m(w){i.handleDecisionEvent(w),p()}function S(){let w=i.getIR();return t&&!w.root.name&&(w.root.name=t),w}function $(){let w=S();return l.render(w,u)}function O(w){let b=S();switch(w){case"ascii":return l.render(b,u);case"mermaid":return c.render(b,u);case"json":return JSON.stringify(b,null,2);case"logger":return d.render(b,u);default:throw new Error(`Unknown format: ${w}`)}}function D(){i.reset(),p()}function v(w){return a.add(w),()=>a.delete(w)}return{handleEvent:h,handleScopeEvent:g,handleDecisionEvent:m,getIR:S,render:$,renderAs:O,reset:D,onUpdate:v}}function Xi(e,t={}){let r=Vt(t);for(let o of e)o.type.startsWith("decision_")?r.handleDecisionEvent(o):r.handleEvent(o);return r.render()}function Zi(e={}){let t=[];return{handleEvent:r=>{t.push(r)},handleDecisionEvent:r=>{t.push(r)},getEvents:()=>[...t],getWorkflowEvents:()=>t.filter(r=>!r.type.startsWith("decision_")),getDecisionEvents:()=>t.filter(r=>r.type.startsWith("decision_")),clear:()=>{t.length=0},visualize:()=>{let r=Vt(e);for(let o of t)o.type.startsWith("decision_")?r.handleDecisionEvent(o):r.handleEvent(o);return r.render()},visualizeAs:r=>{let o=Vt(e);for(let n of t)n.type.startsWith("decision_")?o.handleDecisionEvent(n):o.handleEvent(n);return o.renderAs(r)}}}export{ce as asciiRenderer,As as createDevServer,Zi as createEventCollector,pe as createIRBuilder,mo as createLiveVisualizer,Tn as createParallelDetector,ht as createPerformanceAnalyzer,bt as createTimeTravelController,Vt as createVisualizer,ae as defaultColorScheme,Fe as detectParallelGroups,pt as getHeatLevel,qs as hasChildren,ho as htmlRenderer,se as isDecisionNode,Q as isParallelNode,oe as isRaceNode,jt as isSequenceNode,J as isStepNode,je as loggerRenderer,ze as mermaidRenderer,vt as renderToHTML,wt as trackDecision,go as trackIf,yo as trackSwitch,Xi as visualizeEvents};
1189
1195
  //# sourceMappingURL=visualize.js.map