@jagreehal/workflow 1.14.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/index.cjs +5 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +5 -5
- package/dist/index.js.map +1 -1
- package/dist/visualize.cjs +27 -27
- package/dist/visualize.cjs.map +1 -1
- package/dist/visualize.d.cts +105 -2
- package/dist/visualize.d.ts +105 -2
- package/dist/visualize.js +26 -26
- package/dist/visualize.js.map +1 -1
- package/docs/pino-logging-example.md +106 -3
- package/package.json +2 -1
package/dist/visualize.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var xn=Object.create;var Fe=Object.defineProperty;var kn=Object.getOwnPropertyDescriptor;var En=Object.getOwnPropertyNames;var Tn=Object.getPrototypeOf,Rn=Object.prototype.hasOwnProperty;var In=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),zt=(e,t)=>{for(var r in t)Fe(e,r,{get:t[r],enumerable:!0})},Vt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of En(t))!Rn.call(e,n)&&n!==r&&Fe(e,n,{get:()=>t[n],enumerable:!(o=kn(t,n))||o.enumerable});return e};var Re=(e,t,r)=>(r=e!=null?xn(Tn(e)):{},Vt(t||!e||!e.__esModule?Fe(r,"default",{value:e,enumerable:!0}):r,e)),$n=e=>Vt(Fe({},"__esModule",{value:!0}),e);var Q=z((vi,fr)=>{"use strict";var dr=["nodebuffer","arraybuffer","fragments"],ur=typeof Blob<"u";ur&&dr.push("blob");fr.exports={BINARY_TYPES:dr,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ur,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ce=z((yi,Xe)=>{"use strict";var{EMPTY_BUFFER:ho}=Q(),St=Buffer[Symbol.species];function mo(e,t){if(e.length===0)return ho;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 pr(e,t,r,o,n){for(let s=0;s<n;s++)r[o+s]=e[s]^t[s&3]}function hr(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}function go(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function _t(e){if(_t.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),_t.readOnly=!1),t}Xe.exports={concat:mo,mask:pr,toArrayBuffer:go,toBuffer:_t,unmask:hr};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=require("bufferutil");Xe.exports.mask=function(t,r,o,n,s){s<48?pr(t,r,o,n,s):e.mask(t,r,o,n,s)},Xe.exports.unmask=function(t,r){t.length<32?hr(t,r):e.unmask(t,r)}}catch{}});var vr=z((wi,gr)=>{"use strict";var mr=Symbol("kDone"),xt=Symbol("kRun"),kt=class{constructor(t){this[mr]=()=>{this.pending--,this[xt]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[xt]()}[xt](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[mr])}}};gr.exports=kt});var Me=z((bi,Sr)=>{"use strict";var Le=require("zlib"),yr=Ce(),vo=vr(),{kStatusCode:wr}=Q(),yo=Buffer[Symbol.species],wo=Buffer.from([0,0,255,255]),Qe=Symbol("permessage-deflate"),ee=Symbol("total-length"),be=Symbol("callback"),ae=Symbol("buffers"),Se=Symbol("error"),Ze,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,!Ze){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ze=new vo(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[be];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){Ze.add(n=>{this._decompress(t,r,(s,i)=>{n(),o(s,i)})})}compress(t,r,o){Ze.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"?Le.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Le.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Qe]=this,this._inflate[ee]=0,this._inflate[ae]=[],this._inflate.on("error",So),this._inflate.on("data",br)}this._inflate[be]=o,this._inflate.write(t),r&&this._inflate.write(wo),this._inflate.flush(()=>{let s=this._inflate[Se];if(s){this._inflate.close(),this._inflate=null,o(s);return}let i=yr.concat(this._inflate[ae],this._inflate[ee]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ee]=0,this._inflate[ae]=[],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"?Le.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Le.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[ee]=0,this._deflate[ae]=[],this._deflate.on("data",bo)}this._deflate[be]=o,this._deflate.write(t),this._deflate.flush(Le.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=yr.concat(this._deflate[ae],this._deflate[ee]);r&&(s=new yo(s.buffer,s.byteOffset,s.length-4)),this._deflate[be]=null,this._deflate[ee]=0,this._deflate[ae]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,s)})}};Sr.exports=Et;function bo(e){this[ae].push(e),this[ee]+=e.length}function br(e){if(this[ee]+=e.length,this[Qe]._maxPayload<1||this[ee]<=this[Qe]._maxPayload){this[ae].push(e);return}this[Se]=new RangeError("Max payload size exceeded"),this[Se].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Se][wr]=1009,this.removeListener("data",br),this.reset()}function So(e){if(this[Qe]._inflate=null,this[Se]){this[be](this[Se]);return}e[wr]=1007,this[be](e)}});var _e=z((Si,et)=>{"use strict";var{isUtf8:_r}=require("buffer"),{hasBlob:_o}=Q(),xo=[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 ko(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function Tt(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 Eo(e){return _o&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}et.exports={isBlob:Eo,isValidStatusCode:ko,isValidUTF8:Tt,tokenChars:xo};if(_r)et.exports.isValidUTF8=function(e){return e.length<24?Tt(e):_r(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=require("utf-8-validate");et.exports.isValidUTF8=function(t){return t.length<32?Tt(t):e(t)}}catch{}});var Dt=z((_i,$r)=>{"use strict";var{Writable:To}=require("stream"),xr=Me(),{BINARY_TYPES:Ro,EMPTY_BUFFER:kr,kStatusCode:Io,kWebSocket:$o}=Q(),{concat:Rt,toArrayBuffer:No,unmask:Do}=Ce(),{isValidStatusCode:Oo,isValidUTF8:Er}=_e(),tt=Buffer[Symbol.species],q=0,Tr=1,Rr=2,Ir=3,It=4,$t=5,rt=6,Nt=class extends To{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||Ro[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[$o]=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=q}_write(t,r,o){if(this._opcode===8&&this._state==q)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 tt(o.buffer,o.byteOffset+t,o.length-t),new tt(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 tt(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 q:this.getInfo(t);break;case Tr:this.getPayloadLength16(t);break;case Rr:this.getPayloadLength64(t);break;case Ir:this.getMask();break;case It:this.getData(t);break;case $t:case rt: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[xr.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=Tr:this._payloadLength===127?this._state=Rr: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=Ir:this._state=It}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=It}getData(t){let r=kr;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&&Do(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[xr.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===q&&this.startLoop(r)})}dataMessage(t){if(!this._fin){this._state=q;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=Rt(o,r):this._binaryType==="arraybuffer"?n=No(Rt(o,r)):this._binaryType==="blob"?n=new Blob(o):n=o,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=q):(this._state=rt,setImmediate(()=>{this.emit("message",n,!0),this._state=q,this.startLoop(t)}))}else{let n=Rt(o,r);if(!this._skipUTF8Validation&&!Er(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=q):(this._state=rt,setImmediate(()=>{this.emit("message",n,!1),this._state=q,this.startLoop(t)}))}}controlMessage(t,r){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,kr),this.end();else{let o=t.readUInt16BE(0);if(!Oo(o)){let s=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let n=new tt(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!Er(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=q;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",t),this._state=q):(this._state=rt,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=q,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[Io]=n,i}};$r.exports=Nt});var Lt=z((ki,Or)=>{"use strict";var{Duplex:xi}=require("stream"),{randomFillSync:Co}=require("crypto"),Nr=Me(),{EMPTY_BUFFER:Lo,kWebSocket:Mo,NOOP:Bo}=Q(),{isBlob:xe,isValidStatusCode:Po}=_e(),{mask:Dr,toBuffer:pe}=Ce(),G=Symbol("kByteLength"),Wo=Buffer.alloc(4),nt=8*1024,he,ke=nt,Y=0,Ao=1,Uo=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=Y,this.onerror=Bo,this[Mo]=void 0}static frame(t,r){let o,n=!1,s=2,i=!1;r.mask&&(o=r.maskBuffer||Wo,r.generateMask?r.generateMask(o):(ke===nt&&(he===void 0&&(he=Buffer.alloc(nt)),Co(he,0,nt),ke=0),o[0]=he[ke++],o[1]=he[ke++],o[2]=he[ke++],o[3]=he[ke++]),i=(o[0]|o[1]|o[2]|o[3])===0,s=6);let l;typeof t=="string"?(!r.mask||i)&&r[G]!==void 0?l=r[G]:(t=Buffer.from(t),l=t.length):(l=t.length,n=r.mask&&r.readOnly&&!i);let d=l;l>=65536?(s+=8,d=127):l>125&&(s+=2,d=126);let a=Buffer.allocUnsafe(n?l+s:s);return a[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(a[0]|=64),a[1]=d,d===126?a.writeUInt16BE(l,2):d===127&&(a[2]=a[3]=0,a.writeUIntBE(l,4,6)),r.mask?(a[1]|=128,a[s-4]=o[0],a[s-3]=o[1],a[s-2]=o[2],a[s-1]=o[3],i?[a,t]:n?(Dr(t,o,a,s,l),[a]):(Dr(t,o,t,0,l),[a,t])):[a,t]}close(t,r,o,n){let s;if(t===void 0)s=Lo;else{if(typeof t!="number"||!Po(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 l=Buffer.byteLength(r);if(l>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+l),s.writeUInt16BE(t,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let i={[G]:s.length,fin:!0,generateMask:this._generateMask,mask:o,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Y?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):xe(t)?(n=t.size,s=!1):(t=pe(t),n=t.length,s=pe.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[G]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};xe(t)?this._state!==Y?this.enqueue([this.getBlobData,t,!1,i,o]):this.getBlobData(t,!1,i,o):this._state!==Y?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):xe(t)?(n=t.size,s=!1):(t=pe(t),n=t.length,s=pe.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[G]:n,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};xe(t)?this._state!==Y?this.enqueue([this.getBlobData,t,!1,i,o]):this.getBlobData(t,!1,i,o):this._state!==Y?this.enqueue([this.dispatch,t,!1,i,o]):this.sendFrame(e.frame(t,i),o)}send(t,r,o){let n=this._extensions[Nr.extensionName],s=r.binary?2:1,i=r.compress,l,d;typeof t=="string"?(l=Buffer.byteLength(t),d=!1):xe(t)?(l=t.size,d=!1):(t=pe(t),l=t.length,d=pe.readOnly),this._firstFragment?(this._firstFragment=!1,i&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=l>=n._threshold),this._compress=i):(i=!1,s=0),r.fin&&(this._firstFragment=!0);let a={[G]:l,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:d,rsv1:i};xe(t)?this._state!==Y?this.enqueue([this.getBlobData,t,this._compress,a,o]):this.getBlobData(t,this._compress,a,o):this._state!==Y?this.enqueue([this.dispatch,t,this._compress,a,o]):this.dispatch(t,this._compress,a,o)}getBlobData(t,r,o,n){this._bufferedBytes+=o[G],this._state=Uo,t.arrayBuffer().then(s=>{if(this._socket.destroyed){let l=new Error("The socket was closed while the blob was being read");process.nextTick(Ct,this,l,n);return}this._bufferedBytes-=o[G];let i=pe(s);r?this.dispatch(i,r,o,n):(this._state=Y,this.sendFrame(e.frame(i,o),n),this.dequeue())}).catch(s=>{process.nextTick(Fo,this,s,n)})}dispatch(t,r,o,n){if(!r){this.sendFrame(e.frame(t,o),n);return}let s=this._extensions[Nr.extensionName];this._bufferedBytes+=o[G],this._state=Ao,s.compress(t,o.fin,(i,l)=>{if(this._socket.destroyed){let d=new Error("The socket was closed while data was being compressed");Ct(this,d,n);return}this._bufferedBytes-=o[G],this._state=Y,o.readOnly=!1,this.sendFrame(e.frame(l,o),n),this.dequeue()})}dequeue(){for(;this._state===Y&&this._queue.length;){let t=this._queue.shift();this._bufferedBytes-=t[3][G],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][G],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)}};Or.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 Fo(e,t,r){Ct(e,t,r),e.onerror(t)}});var Fr=z((Ei,Ur)=>{"use strict";var{kForOnEventAttribute:Be,kListener:Mt}=Q(),Cr=Symbol("kCode"),Lr=Symbol("kData"),Mr=Symbol("kError"),Br=Symbol("kMessage"),Pr=Symbol("kReason"),Ee=Symbol("kTarget"),Wr=Symbol("kType"),Ar=Symbol("kWasClean"),te=class{constructor(t){this[Ee]=null,this[Wr]=t}get target(){return this[Ee]}get type(){return this[Wr]}};Object.defineProperty(te.prototype,"target",{enumerable:!0});Object.defineProperty(te.prototype,"type",{enumerable:!0});var me=class extends te{constructor(t,r={}){super(t),this[Cr]=r.code===void 0?0:r.code,this[Pr]=r.reason===void 0?"":r.reason,this[Ar]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Cr]}get reason(){return this[Pr]}get wasClean(){return this[Ar]}};Object.defineProperty(me.prototype,"code",{enumerable:!0});Object.defineProperty(me.prototype,"reason",{enumerable:!0});Object.defineProperty(me.prototype,"wasClean",{enumerable:!0});var Te=class extends te{constructor(t,r={}){super(t),this[Mr]=r.error===void 0?null:r.error,this[Br]=r.message===void 0?"":r.message}get error(){return this[Mr]}get message(){return this[Br]}};Object.defineProperty(Te.prototype,"error",{enumerable:!0});Object.defineProperty(Te.prototype,"message",{enumerable:!0});var Pe=class extends te{constructor(t,r={}){super(t),this[Lr]=r.data===void 0?null:r.data}get data(){return this[Lr]}};Object.defineProperty(Pe.prototype,"data",{enumerable:!0});var Ho={addEventListener(e,t,r={}){for(let n of this.listeners(e))if(!r[Be]&&n[Mt]===t&&!n[Be])return;let o;if(e==="message")o=function(s,i){let l=new Pe("message",{data:i?s:s.toString()});l[Ee]=this,ot(t,this,l)};else if(e==="close")o=function(s,i){let l=new me("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[Ee]=this,ot(t,this,l)};else if(e==="error")o=function(s){let i=new Te("error",{error:s,message:s.message});i[Ee]=this,ot(t,this,i)};else if(e==="open")o=function(){let s=new te("open");s[Ee]=this,ot(t,this,s)};else return;o[Be]=!!r[Be],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[Be]){this.removeListener(e,r);break}}};Ur.exports={CloseEvent:me,ErrorEvent:Te,Event:te,EventTarget:Ho,MessageEvent:Pe};function ot(e,t,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}});var Bt=z((Ti,Hr)=>{"use strict";var{tokenChars:We}=_e();function X(e,t,r){e[t]===void 0?e[t]=[r]:e[t].push(r)}function zo(e){let t=Object.create(null),r=Object.create(null),o=!1,n=!1,s=!1,i,l,d=-1,a=-1,c=-1,u=0;for(;u<e.length;u++)if(a=e.charCodeAt(u),i===void 0)if(c===-1&&We[a]===1)d===-1&&(d=u);else if(u!==0&&(a===32||a===9))c===-1&&d!==-1&&(c=u);else if(a===59||a===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1&&(c=u);let m=e.slice(d,c);a===44?(X(t,m,r),r=Object.create(null)):i=m,d=c=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(l===void 0)if(c===-1&&We[a]===1)d===-1&&(d=u);else if(a===32||a===9)c===-1&&d!==-1&&(c=u);else if(a===59||a===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1&&(c=u),X(r,e.slice(d,c),!0),a===44&&(X(t,i,r),r=Object.create(null),i=void 0),d=c=-1}else if(a===61&&d!==-1&&c===-1)l=e.slice(d,u),d=c=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(n){if(We[a]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1?d=u:o||(o=!0),n=!1}else if(s)if(We[a]===1)d===-1&&(d=u);else if(a===34&&d!==-1)s=!1,c=u;else if(a===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===34&&e.charCodeAt(u-1)===61)s=!0;else if(c===-1&&We[a]===1)d===-1&&(d=u);else if(d!==-1&&(a===32||a===9))c===-1&&(c=u);else if(a===59||a===44){if(d===-1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1&&(c=u);let m=e.slice(d,c);o&&(m=m.replace(/\\/g,""),o=!1),X(r,l,m),a===44&&(X(t,i,r),r=Object.create(null),i=void 0),l=void 0,d=c=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(d===-1||s||a===32||a===9)throw new SyntaxError("Unexpected end of input");c===-1&&(c=u);let p=e.slice(d,c);return i===void 0?X(t,p,r):(l===void 0?X(r,p,!0):o?X(r,l,p.replace(/\\/g,"")):X(r,l,p),X(t,i,r)),t}function Vo(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(", ")}Hr.exports={format:Vo,parse:zo}});var ct=z(($i,en)=>{"use strict";var jo=require("events"),qo=require("https"),Go=require("http"),jr=require("net"),Ko=require("tls"),{randomBytes:Yo,createHash:Jo}=require("crypto"),{Duplex:Ri,Readable:Ii}=require("stream"),{URL:Pt}=require("url"),ce=Me(),Xo=Dt(),Zo=Lt(),{isBlob:Qo}=_e(),{BINARY_TYPES:zr,CLOSE_TIMEOUT:es,EMPTY_BUFFER:st,GUID:ts,kForOnEventAttribute:Wt,kListener:rs,kStatusCode:ns,kWebSocket:A,NOOP:qr}=Q(),{EventTarget:{addEventListener:os,removeEventListener:ss}}=Fr(),{format:is,parse:as}=Bt(),{toBuffer:cs}=Ce(),Gr=Symbol("kAborted"),At=[8,13],re=["CONNECTING","OPEN","CLOSING","CLOSED"],ls=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,W=class e extends jo{constructor(t,r,o){super(),this._binaryType=zr[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=st,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]),Kr(this,t,r,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){zr.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 Xo({allowSynchronousEvents:o.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation}),s=new Zo(t,this._extensions,o.generateMask);this._receiver=n,this._sender=s,this._socket=t,n[A]=this,s[A]=this,t[A]=this,n.on("conclude",fs),n.on("drain",ps),n.on("error",hs),n.on("message",ms),n.on("ping",gs),n.on("pong",vs),s.onerror=ys,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",Xr),t.on("data",at),t.on("end",Zr),t.on("error",Qr),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[ce.extensionName]&&this._extensions[ce.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){j(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())}),Jr(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){Ut(this,t,o);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||st,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){Ut(this,t,o);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||st,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){Ut(this,t,o);return}let n={binary:typeof t!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[ce.extensionName]||(n.compress=!1),this._sender.send(t||st,n,o)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){j(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(W,"CONNECTING",{enumerable:!0,value:re.indexOf("CONNECTING")});Object.defineProperty(W.prototype,"CONNECTING",{enumerable:!0,value:re.indexOf("CONNECTING")});Object.defineProperty(W,"OPEN",{enumerable:!0,value:re.indexOf("OPEN")});Object.defineProperty(W.prototype,"OPEN",{enumerable:!0,value:re.indexOf("OPEN")});Object.defineProperty(W,"CLOSING",{enumerable:!0,value:re.indexOf("CLOSING")});Object.defineProperty(W.prototype,"CLOSING",{enumerable:!0,value:re.indexOf("CLOSING")});Object.defineProperty(W,"CLOSED",{enumerable:!0,value:re.indexOf("CLOSED")});Object.defineProperty(W.prototype,"CLOSED",{enumerable:!0,value:re.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(W.prototype,e,{enumerable:!0})});["open","error","close","message"].forEach(e=>{Object.defineProperty(W.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[Wt])return t[rs];return null},set(t){for(let r of this.listeners(e))if(r[Wt]){this.removeListener(e,r);break}typeof t=="function"&&this.addEventListener(e,t,{[Wt]:!0})}})});W.prototype.addEventListener=os;W.prototype.removeEventListener=ss;en.exports=W;function Kr(e,t,r,o){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:es,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 Pt)s=t;else try{s=new Pt(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:",l=s.protocol==="ws+unix:",d;if(s.protocol!=="ws:"&&!i&&!l?d=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:l&&!s.pathname?d="The URL's pathname is empty":s.hash&&(d="The URL contains a fragment identifier"),d){let g=new SyntaxError(d);if(e._redirects===0)throw g;it(e,g);return}let a=i?443:80,c=Yo(16).toString("base64"),u=i?qo.request:Go.request,p=new Set,m;if(n.createConnection=n.createConnection||(i?us:ds),n.defaultPort=n.defaultPort||a,n.port=s.port||a,n.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":c,Connection:"Upgrade",Upgrade:"websocket"},n.path=s.pathname+s.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(m=new ce(n.perMessageDeflate!==!0?n.perMessageDeflate:{},!1,n.maxPayload),n.headers["Sec-WebSocket-Extensions"]=is({[ce.extensionName]:m.offer()})),r.length){for(let g of r){if(typeof g!="string"||!ls.test(g)||p.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(g)}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}`),l){let g=n.path.split(":");n.socketPath=g[0],n.path=g[1]}let v;if(n.followRedirects){if(e._redirects===0){e._originalIpc=l,e._originalSecure=i,e._originalHostOrSocketPath=l?n.socketPath:s.host;let g=o&&o.headers;if(o={...o,headers:{}},g)for(let[w,$]of Object.entries(g))o.headers[w.toLowerCase()]=$}else if(e.listenerCount("redirect")===0){let g=l?e._originalIpc?n.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:s.host===e._originalHostOrSocketPath;(!g||e._originalSecure&&!i)&&(delete n.headers.authorization,delete n.headers.cookie,g||delete n.headers.host,n.auth=void 0)}n.auth&&!o.headers.authorization&&(o.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),v=e._req=u(n),e._redirects&&e.emit("redirect",e.url,v)}else v=e._req=u(n);n.timeout&&v.on("timeout",()=>{j(e,v,"Opening handshake has timed out")}),v.on("error",g=>{v===null||v[Gr]||(v=e._req=null,it(e,g))}),v.on("response",g=>{let w=g.headers.location,$=g.statusCode;if(w&&n.followRedirects&&$>=300&&$<400){if(++e._redirects>n.maxRedirects){j(e,v,"Maximum redirects exceeded");return}v.abort();let O;try{O=new Pt(w,t)}catch{let h=new SyntaxError(`Invalid URL: ${w}`);it(e,h);return}Kr(e,O,r,o)}else e.emit("unexpected-response",v,g)||j(e,v,`Unexpected server response: ${g.statusCode}`)}),v.on("upgrade",(g,w,$)=>{if(e.emit("upgrade",g),e.readyState!==W.CONNECTING)return;v=e._req=null;let O=g.headers.upgrade;if(O===void 0||O.toLowerCase()!=="websocket"){j(e,w,"Invalid Upgrade header");return}let D=Jo("sha1").update(c+ts).digest("base64");if(g.headers["sec-websocket-accept"]!==D){j(e,w,"Invalid Sec-WebSocket-Accept header");return}let h=g.headers["sec-websocket-protocol"],x;if(h!==void 0?p.size?p.has(h)||(x="Server sent an invalid subprotocol"):x="Server sent a subprotocol but none was requested":p.size&&(x="Server sent no subprotocol"),x){j(e,w,x);return}h&&(e._protocol=h);let b=g.headers["sec-websocket-extensions"];if(b!==void 0){if(!m){j(e,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let k;try{k=as(b)}catch{j(e,w,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(k);if(B.length!==1||B[0]!==ce.extensionName){j(e,w,"Server indicated an extension that was not requested");return}try{m.accept(k[ce.extensionName])}catch{j(e,w,"Invalid Sec-WebSocket-Extensions header");return}e._extensions[ce.extensionName]=m}e.setSocket(w,$,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(v,e):v.end()}function it(e,t){e._readyState=W.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function ds(e){return e.path=e.socketPath,jr.connect(e)}function us(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=jr.isIP(e.host)?"":e.host),Ko.connect(e)}function j(e,t,r){e._readyState=W.CLOSING;let o=new Error(r);Error.captureStackTrace(o,j),t.setHeader?(t[Gr]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(it,e,o)):(t.destroy(o),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Ut(e,t,r){if(t){let o=Qo(t)?t.size:cs(t).length;e._socket?e._sender._bufferedBytes+=o:e._bufferedAmount+=o}if(r){let o=new Error(`WebSocket is not open: readyState ${e.readyState} (${re[e.readyState]})`);process.nextTick(r,o)}}function fs(e,t){let r=this[A];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[A]!==void 0&&(r._socket.removeListener("data",at),process.nextTick(Yr,r._socket),e===1005?r.close():r.close(e,t))}function ps(){let e=this[A];e.isPaused||e._socket.resume()}function hs(e){let t=this[A];t._socket[A]!==void 0&&(t._socket.removeListener("data",at),process.nextTick(Yr,t._socket),t.close(e[ns])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Vr(){this[A].emitClose()}function ms(e,t){this[A].emit("message",e,t)}function gs(e){let t=this[A];t._autoPong&&t.pong(e,!this._isServer,qr),t.emit("ping",e)}function vs(e){this[A].emit("pong",e)}function Yr(e){e.resume()}function ys(e){let t=this[A];t.readyState!==W.CLOSED&&(t.readyState===W.OPEN&&(t._readyState=W.CLOSING,Jr(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Jr(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function Xr(){let e=this[A];if(this.removeListener("close",Xr),this.removeListener("data",at),this.removeListener("end",Zr),e._readyState=W.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[A]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Vr),e._receiver.on("finish",Vr))}function at(e){this[A]._receiver.write(e)||this.pause()}function Zr(){let e=this[A];e._readyState=W.CLOSING,e._receiver.end(),this.end()}function Qr(){let e=this[A];this.removeListener("error",Qr),this.on("error",qr),e&&(e._readyState=W.CLOSING,this.destroy())}});var on=z((Di,nn)=>{"use strict";var Ni=ct(),{Duplex:ws}=require("stream");function tn(e){e.emit("close")}function bs(){!this.destroyed&&this._writableState.finished&&this.destroy()}function rn(e){this.removeListener("error",rn),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function Ss(e,t){let r=!0,o=new ws({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(s,i){let l=!i&&o._readableState.objectMode?s.toString():s;o.push(l)||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(tn,o);return}let i=!1;e.once("error",function(d){i=!0,s(d)}),e.once("close",function(){i||s(n),process.nextTick(tn,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",bs),o.on("error",rn),o}nn.exports=Ss});var an=z((Oi,sn)=>{"use strict";var{tokenChars:_s}=_e();function xs(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&&_s[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 l=e.slice(r,o);if(t.has(l))throw new SyntaxError(`The "${l}" subprotocol is duplicated`);t.add(l),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}sn.exports={parse:xs}});var hn=z((Li,pn)=>{"use strict";var ks=require("events"),lt=require("http"),{Duplex:Ci}=require("stream"),{createHash:Es}=require("crypto"),cn=Bt(),ge=Me(),Ts=an(),Rs=ct(),{CLOSE_TIMEOUT:Is,GUID:$s,kWebSocket:Ns}=Q(),Ds=/^[+/0-9A-Za-z]{22}==$/,ln=0,dn=1,fn=2,Ft=class extends ks{constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Is,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Rs,...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=lt.createServer((o,n)=>{let s=lt.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=Os(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=ln}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===fn){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(Ae,this);return}if(t&&this.once("close",t),this._state!==dn)if(this._state=dn,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(Ae,this):process.nextTick(Ae,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Ae(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",un);let s=t.headers["sec-websocket-key"],i=t.headers.upgrade,l=+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||!Ds.test(s)){ve(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(l!==13&&l!==8){ve(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){Ue(r,400);return}let d=t.headers["sec-websocket-protocol"],a=new Set;if(d!==void 0)try{a=Ts.parse(d)}catch{ve(this,t,r,400,"Invalid Sec-WebSocket-Protocol header");return}let c=t.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&c!==void 0){let p=new ge(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let m=cn.parse(c);m[ge.extensionName]&&(p.accept(m[ge.extensionName]),u[ge.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[`${l===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(m,v,g,w)=>{if(!m)return Ue(r,v||401,g,w);this.completeUpgrade(u,s,a,t,r,o,n)});return}if(!this.options.verifyClient(p))return Ue(r,401)}this.completeUpgrade(u,s,a,t,r,o,n)}completeUpgrade(t,r,o,n,s,i,l){if(!s.readable||!s.writable)return s.destroy();if(s[Ns])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ln)return Ue(s,503);let a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Es("sha1").update(r+$s).digest("base64")}`],c=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&&(a.push(`Sec-WebSocket-Protocol: ${u}`),c._protocol=u)}if(t[ge.extensionName]){let u=t[ge.extensionName].params,p=cn.format({[ge.extensionName]:[u]});a.push(`Sec-WebSocket-Extensions: ${p}`),c._extensions=t}this.emit("headers",a,n),s.write(a.concat(`\r
|
|
1
|
+
"use strict";var En=Object.create;var Ue=Object.defineProperty;var Rn=Object.getOwnPropertyDescriptor;var Tn=Object.getOwnPropertyNames;var In=Object.getPrototypeOf,$n=Object.prototype.hasOwnProperty;var Nn=(e,t)=>()=>(e&&(t=e(e=0)),t);var z=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),jt=(e,t)=>{for(var r in t)Ue(e,r,{get:t[r],enumerable:!0})},qt=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Tn(t))!$n.call(e,n)&&n!==r&&Ue(e,n,{get:()=>t[n],enumerable:!(o=Rn(t,n))||o.enumerable});return e};var Te=(e,t,r)=>(r=e!=null?En(In(e)):{},qt(t||!e||!e.__esModule?Ue(r,"default",{value:e,enumerable:!0}):r,e)),Dn=e=>qt(Ue({},"__esModule",{value:!0}),e);var ne=z((Ii,hr)=>{"use strict";var fr=["nodebuffer","arraybuffer","fragments"],pr=typeof Blob<"u";pr&&fr.push("blob");hr.exports={BINARY_TYPES:fr,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:pr,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Le=z(($i,Ze)=>{"use strict";var{EMPTY_BUFFER:So}=ne(),_t=Buffer[Symbol.species];function xo(e,t){if(e.length===0)return So;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 _t(r.buffer,r.byteOffset,o):r}function mr(e,t,r,o,n){for(let s=0;s<n;s++)r[o+s]=e[s]^t[s&3]}function gr(e,t){for(let r=0;r<e.length;r++)e[r]^=t[r&3]}function _o(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function kt(e){if(kt.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new _t(e):ArrayBuffer.isView(e)?t=new _t(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),kt.readOnly=!1),t}Ze.exports={concat:xo,mask:mr,toArrayBuffer:_o,toBuffer:kt,unmask:gr};if(!process.env.WS_NO_BUFFER_UTIL)try{let e=require("bufferutil");Ze.exports.mask=function(t,r,o,n,s){s<48?mr(t,r,o,n,s):e.mask(t,r,o,n,s)},Ze.exports.unmask=function(t,r){t.length<32?gr(t,r):e.unmask(t,r)}}catch{}});var wr=z((Ni,vr)=>{"use strict";var yr=Symbol("kDone"),Et=Symbol("kRun"),Rt=class{constructor(t){this[yr]=()=>{this.pending--,this[Et]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[Et]()}[Et](){if(this.pending!==this.concurrency&&this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[yr])}}};vr.exports=Rt});var Be=z((Di,_r)=>{"use strict";var Me=require("zlib"),br=Le(),ko=wr(),{kStatusCode:Sr}=ne(),Eo=Buffer[Symbol.species],Ro=Buffer.from([0,0,255,255]),et=Symbol("permessage-deflate"),oe=Symbol("total-length"),be=Symbol("callback"),de=Symbol("buffers"),Se=Symbol("error"),Qe,Tt=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,!Qe){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Qe=new ko(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[be];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){Qe.add(n=>{this._decompress(t,r,(s,i)=>{n(),o(s,i)})})}compress(t,r,o){Qe.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"?Me.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Me.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[et]=this,this._inflate[oe]=0,this._inflate[de]=[],this._inflate.on("error",Io),this._inflate.on("data",xr)}this._inflate[be]=o,this._inflate.write(t),r&&this._inflate.write(Ro),this._inflate.flush(()=>{let s=this._inflate[Se];if(s){this._inflate.close(),this._inflate=null,o(s);return}let i=br.concat(this._inflate[de],this._inflate[oe]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[oe]=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"?Me.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Me.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[oe]=0,this._deflate[de]=[],this._deflate.on("data",To)}this._deflate[be]=o,this._deflate.write(t),this._deflate.flush(Me.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=br.concat(this._deflate[de],this._deflate[oe]);r&&(s=new Eo(s.buffer,s.byteOffset,s.length-4)),this._deflate[be]=null,this._deflate[oe]=0,this._deflate[de]=[],r&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),o(null,s)})}};_r.exports=Tt;function To(e){this[de].push(e),this[oe]+=e.length}function xr(e){if(this[oe]+=e.length,this[et]._maxPayload<1||this[oe]<=this[et]._maxPayload){this[de].push(e);return}this[Se]=new RangeError("Max payload size exceeded"),this[Se].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Se][Sr]=1009,this.removeListener("data",xr),this.reset()}function Io(e){if(this[et]._inflate=null,this[Se]){this[be](this[Se]);return}e[Sr]=1007,this[be](e)}});var xe=z((Oi,tt)=>{"use strict";var{isUtf8:kr}=require("buffer"),{hasBlob:$o}=ne(),No=[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 Do(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function It(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 Oo(e){return $o&&typeof e=="object"&&typeof e.arrayBuffer=="function"&&typeof e.type=="string"&&typeof e.stream=="function"&&(e[Symbol.toStringTag]==="Blob"||e[Symbol.toStringTag]==="File")}tt.exports={isBlob:Oo,isValidStatusCode:Do,isValidUTF8:It,tokenChars:No};if(kr)tt.exports.isValidUTF8=function(e){return e.length<24?It(e):kr(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=require("utf-8-validate");tt.exports.isValidUTF8=function(t){return t.length<32?It(t):e(t)}}catch{}});var Ct=z((Ci,Dr)=>{"use strict";var{Writable:Co}=require("stream"),Er=Be(),{BINARY_TYPES:Lo,EMPTY_BUFFER:Rr,kStatusCode:Mo,kWebSocket:Bo}=ne(),{concat:$t,toArrayBuffer:Wo,unmask:Po}=Le(),{isValidStatusCode:Ao,isValidUTF8:Tr}=xe(),rt=Buffer[Symbol.species],G=0,Ir=1,$r=2,Nr=3,Nt=4,Dt=5,nt=6,Ot=class extends Co{constructor(t={}){super(),this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||Lo[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[Bo]=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 rt(o.buffer,o.byteOffset+t,o.length-t),new rt(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 rt(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 Ir:this.getPayloadLength16(t);break;case $r:this.getPayloadLength64(t);break;case Nr:this.getMask();break;case Nt:this.getData(t);break;case Dt:case nt: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[Er.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=Ir: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=Nr:this._state=Nt}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Nt}getData(t){let r=Rr;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&&Po(r,this._mask)}if(this._opcode>7){this.controlMessage(r,t);return}if(this._compressed){this._state=Dt,this.decompress(r,t);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(t)}decompress(t,r){this._extensions[Er.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=$t(o,r):this._binaryType==="arraybuffer"?n=Wo($t(o,r)):this._binaryType==="blob"?n=new Blob(o):n=o,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=G):(this._state=nt,setImmediate(()=>{this.emit("message",n,!0),this._state=G,this.startLoop(t)}))}else{let n=$t(o,r);if(!this._skipUTF8Validation&&!Tr(n)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(s);return}this._state===Dt||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=G):(this._state=nt,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,Rr),this.end();else{let o=t.readUInt16BE(0);if(!Ao(o)){let s=this.createError(RangeError,`invalid status code ${o}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let n=new rt(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!Tr(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=nt,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[Mo]=n,i}};Dr.exports=Ot});var Bt=z((Mi,Lr)=>{"use strict";var{Duplex:Li}=require("stream"),{randomFillSync:Fo}=require("crypto"),Or=Be(),{EMPTY_BUFFER:Ho,kWebSocket:Uo,NOOP:zo}=ne(),{isBlob:_e,isValidStatusCode:Vo}=xe(),{mask:Cr,toBuffer:pe}=Le(),K=Symbol("kByteLength"),jo=Buffer.alloc(4),ot=8*1024,he,ke=ot,J=0,qo=1,Go=2,Lt=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=J,this.onerror=zo,this[Uo]=void 0}static frame(t,r){let o,n=!1,s=2,i=!1;r.mask&&(o=r.maskBuffer||jo,r.generateMask?r.generateMask(o):(ke===ot&&(he===void 0&&(he=Buffer.alloc(ot)),Fo(he,0,ot),ke=0),o[0]=he[ke++],o[1]=he[ke++],o[2]=he[ke++],o[3]=he[ke++]),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?(Cr(t,o,c,s,a),[c]):(Cr(t,o,t,0,a),[c,t])):[c,t]}close(t,r,o,n){let s;if(t===void 0)s=Ho;else{if(typeof t!="number"||!Vo(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!==J?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):_e(t)?(n=t.size,s=!1):(t=pe(t),n=t.length,s=pe.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};_e(t)?this._state!==J?this.enqueue([this.getBlobData,t,!1,i,o]):this.getBlobData(t,!1,i,o):this._state!==J?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):_e(t)?(n=t.size,s=!1):(t=pe(t),n=t.length,s=pe.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};_e(t)?this._state!==J?this.enqueue([this.getBlobData,t,!1,i,o]):this.getBlobData(t,!1,i,o):this._state!==J?this.enqueue([this.dispatch,t,!1,i,o]):this.sendFrame(e.frame(t,i),o)}send(t,r,o){let n=this._extensions[Or.extensionName],s=r.binary?2:1,i=r.compress,a,l;typeof t=="string"?(a=Buffer.byteLength(t),l=!1):_e(t)?(a=t.size,l=!1):(t=pe(t),a=t.length,l=pe.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};_e(t)?this._state!==J?this.enqueue([this.getBlobData,t,this._compress,c,o]):this.getBlobData(t,this._compress,c,o):this._state!==J?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=Go,t.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Mt,this,a,n);return}this._bufferedBytes-=o[K];let i=pe(s);r?this.dispatch(i,r,o,n):(this._state=J,this.sendFrame(e.frame(i,o),n),this.dequeue())}).catch(s=>{process.nextTick(Ko,this,s,n)})}dispatch(t,r,o,n){if(!r){this.sendFrame(e.frame(t,o),n);return}let s=this._extensions[Or.extensionName];this._bufferedBytes+=o[K],this._state=qo,s.compress(t,o.fin,(i,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Mt(this,l,n);return}this._bufferedBytes-=o[K],this._state=J,o.readOnly=!1,this.sendFrame(e.frame(a,o),n),this.dequeue()})}dequeue(){for(;this._state===J&&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)}};Lr.exports=Lt;function Mt(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 Ko(e,t,r){Mt(e,t,r),e.onerror(t)}});var zr=z((Bi,Ur)=>{"use strict";var{kForOnEventAttribute:We,kListener:Wt}=ne(),Mr=Symbol("kCode"),Br=Symbol("kData"),Wr=Symbol("kError"),Pr=Symbol("kMessage"),Ar=Symbol("kReason"),Ee=Symbol("kTarget"),Fr=Symbol("kType"),Hr=Symbol("kWasClean"),se=class{constructor(t){this[Ee]=null,this[Fr]=t}get target(){return this[Ee]}get type(){return this[Fr]}};Object.defineProperty(se.prototype,"target",{enumerable:!0});Object.defineProperty(se.prototype,"type",{enumerable:!0});var me=class extends se{constructor(t,r={}){super(t),this[Mr]=r.code===void 0?0:r.code,this[Ar]=r.reason===void 0?"":r.reason,this[Hr]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Mr]}get reason(){return this[Ar]}get wasClean(){return this[Hr]}};Object.defineProperty(me.prototype,"code",{enumerable:!0});Object.defineProperty(me.prototype,"reason",{enumerable:!0});Object.defineProperty(me.prototype,"wasClean",{enumerable:!0});var Re=class extends se{constructor(t,r={}){super(t),this[Wr]=r.error===void 0?null:r.error,this[Pr]=r.message===void 0?"":r.message}get error(){return this[Wr]}get message(){return this[Pr]}};Object.defineProperty(Re.prototype,"error",{enumerable:!0});Object.defineProperty(Re.prototype,"message",{enumerable:!0});var Pe=class extends se{constructor(t,r={}){super(t),this[Br]=r.data===void 0?null:r.data}get data(){return this[Br]}};Object.defineProperty(Pe.prototype,"data",{enumerable:!0});var Yo={addEventListener(e,t,r={}){for(let n of this.listeners(e))if(!r[We]&&n[Wt]===t&&!n[We])return;let o;if(e==="message")o=function(s,i){let a=new Pe("message",{data:i?s:s.toString()});a[Ee]=this,st(t,this,a)};else if(e==="close")o=function(s,i){let a=new me("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Ee]=this,st(t,this,a)};else if(e==="error")o=function(s){let i=new Re("error",{error:s,message:s.message});i[Ee]=this,st(t,this,i)};else if(e==="open")o=function(){let s=new se("open");s[Ee]=this,st(t,this,s)};else return;o[We]=!!r[We],o[Wt]=t,r.once?this.once(e,o):this.on(e,o)},removeEventListener(e,t){for(let r of this.listeners(e))if(r[Wt]===t&&!r[We]){this.removeListener(e,r);break}}};Ur.exports={CloseEvent:me,ErrorEvent:Re,Event:se,EventTarget:Yo,MessageEvent:Pe};function st(e,t,r){typeof e=="object"&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}});var Pt=z((Wi,Vr)=>{"use strict";var{tokenChars:Ae}=xe();function Z(e,t,r){e[t]===void 0?e[t]=[r]:e[t].push(r)}function Jo(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&&Ae[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&&Ae[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(Ae[c]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1?l=u:o||(o=!0),n=!1}else if(s)if(Ae[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&&Ae[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 Xo(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(", ")}Vr.exports={format:Xo,parse:Jo}});var lt=z((Fi,rn)=>{"use strict";var Zo=require("events"),Qo=require("https"),es=require("http"),Gr=require("net"),ts=require("tls"),{randomBytes:rs,createHash:ns}=require("crypto"),{Duplex:Pi,Readable:Ai}=require("stream"),{URL:At}=require("url"),ue=Be(),os=Ct(),ss=Bt(),{isBlob:is}=xe(),{BINARY_TYPES:jr,CLOSE_TIMEOUT:as,EMPTY_BUFFER:it,GUID:cs,kForOnEventAttribute:Ft,kListener:ls,kStatusCode:ds,kWebSocket:A,NOOP:Kr}=ne(),{EventTarget:{addEventListener:us,removeEventListener:fs}}=zr(),{format:ps,parse:hs}=Pt(),{toBuffer:ms}=Le(),Yr=Symbol("kAborted"),Ht=[8,13],ie=["CONNECTING","OPEN","CLOSING","CLOSED"],gs=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,P=class e extends Zo{constructor(t,r,o){super(),this._binaryType=jr[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=it,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]),Jr(this,t,r,o)):(this._autoPong=o.autoPong,this._closeTimeout=o.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(t){jr.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 os({allowSynchronousEvents:o.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation}),s=new ss(t,this._extensions,o.generateMask);this._receiver=n,this._sender=s,this._socket=t,n[A]=this,s[A]=this,t[A]=this,n.on("conclude",ws),n.on("drain",bs),n.on("error",Ss),n.on("message",xs),n.on("ping",_s),n.on("pong",ks),s.onerror=Es,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),r.length>0&&t.unshift(r),t.on("close",Qr),t.on("data",ct),t.on("end",en),t.on("error",tn),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){j(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())}),Zr(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){Ut(this,t,o);return}r===void 0&&(r=!this._isServer),this._sender.ping(t||it,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){Ut(this,t,o);return}r===void 0&&(r=!this._isServer),this._sender.pong(t||it,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){Ut(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||it,n,o)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){j(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:ie.indexOf("CONNECTING")});Object.defineProperty(P.prototype,"CONNECTING",{enumerable:!0,value:ie.indexOf("CONNECTING")});Object.defineProperty(P,"OPEN",{enumerable:!0,value:ie.indexOf("OPEN")});Object.defineProperty(P.prototype,"OPEN",{enumerable:!0,value:ie.indexOf("OPEN")});Object.defineProperty(P,"CLOSING",{enumerable:!0,value:ie.indexOf("CLOSING")});Object.defineProperty(P.prototype,"CLOSING",{enumerable:!0,value:ie.indexOf("CLOSING")});Object.defineProperty(P,"CLOSED",{enumerable:!0,value:ie.indexOf("CLOSED")});Object.defineProperty(P.prototype,"CLOSED",{enumerable:!0,value:ie.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[Ft])return t[ls];return null},set(t){for(let r of this.listeners(e))if(r[Ft]){this.removeListener(e,r);break}typeof t=="function"&&this.addEventListener(e,t,{[Ft]:!0})}})});P.prototype.addEventListener=us;P.prototype.removeEventListener=fs;rn.exports=P;function Jr(e,t,r,o){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:as,protocolVersion:Ht[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,!Ht.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Ht.join(", ")})`);let s;if(t instanceof At)s=t;else try{s=new At(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;at(e,m);return}let c=i?443:80,d=rs(16).toString("base64"),u=i?Qo.request:es.request,p=new Set,h;if(n.createConnection=n.createConnection||(i?vs:ys),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"]=ps({[ue.extensionName]:h.offer()})),r.length){for(let m of r){if(typeof m!="string"||!gs.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",()=>{j(e,g,"Opening handshake has timed out")}),g.on("error",m=>{g===null||g[Yr]||(g=e._req=null,at(e,m))}),g.on("response",m=>{let S=m.headers.location,$=m.statusCode;if(S&&n.followRedirects&&$>=300&&$<400){if(++e._redirects>n.maxRedirects){j(e,g,"Maximum redirects exceeded");return}g.abort();let O;try{O=new At(S,t)}catch{let v=new SyntaxError(`Invalid URL: ${S}`);at(e,v);return}Jr(e,O,r,o)}else e.emit("unexpected-response",g,m)||j(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"){j(e,S,"Invalid Upgrade header");return}let D=ns("sha1").update(d+cs).digest("base64");if(m.headers["sec-websocket-accept"]!==D){j(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){j(e,S,w);return}v&&(e._protocol=v);let b=m.headers["sec-websocket-extensions"];if(b!==void 0){if(!h){j(e,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let k;try{k=hs(b)}catch{j(e,S,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(k);if(B.length!==1||B[0]!==ue.extensionName){j(e,S,"Server indicated an extension that was not requested");return}try{h.accept(k[ue.extensionName])}catch{j(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 at(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function ys(e){return e.path=e.socketPath,Gr.connect(e)}function vs(e){return e.path=void 0,!e.servername&&e.servername!==""&&(e.servername=Gr.isIP(e.host)?"":e.host),ts.connect(e)}function j(e,t,r){e._readyState=P.CLOSING;let o=new Error(r);Error.captureStackTrace(o,j),t.setHeader?(t[Yr]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(at,e,o)):(t.destroy(o),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Ut(e,t,r){if(t){let o=is(t)?t.size:ms(t).length;e._socket?e._sender._bufferedBytes+=o:e._bufferedAmount+=o}if(r){let o=new Error(`WebSocket is not open: readyState ${e.readyState} (${ie[e.readyState]})`);process.nextTick(r,o)}}function ws(e,t){let r=this[A];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,r._socket[A]!==void 0&&(r._socket.removeListener("data",ct),process.nextTick(Xr,r._socket),e===1005?r.close():r.close(e,t))}function bs(){let e=this[A];e.isPaused||e._socket.resume()}function Ss(e){let t=this[A];t._socket[A]!==void 0&&(t._socket.removeListener("data",ct),process.nextTick(Xr,t._socket),t.close(e[ds])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function qr(){this[A].emitClose()}function xs(e,t){this[A].emit("message",e,t)}function _s(e){let t=this[A];t._autoPong&&t.pong(e,!this._isServer,Kr),t.emit("ping",e)}function ks(e){this[A].emit("pong",e)}function Xr(e){e.resume()}function Es(e){let t=this[A];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,Zr(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Zr(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function Qr(){let e=this[A];if(this.removeListener("close",Qr),this.removeListener("data",ct),this.removeListener("end",en),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[A]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",qr),e._receiver.on("finish",qr))}function ct(e){this[A]._receiver.write(e)||this.pause()}function en(){let e=this[A];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function tn(){let e=this[A];this.removeListener("error",tn),this.on("error",Kr),e&&(e._readyState=P.CLOSING,this.destroy())}});var an=z((Ui,sn)=>{"use strict";var Hi=lt(),{Duplex:Rs}=require("stream");function nn(e){e.emit("close")}function Ts(){!this.destroyed&&this._writableState.finished&&this.destroy()}function on(e){this.removeListener("error",on),this.destroy(),this.listenerCount("error")===0&&this.emit("error",e)}function Is(e,t){let r=!0,o=new Rs({...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(nn,o);return}let i=!1;e.once("error",function(l){i=!0,s(l)}),e.once("close",function(){i||s(n),process.nextTick(nn,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",Ts),o.on("error",on),o}sn.exports=Is});var ln=z((zi,cn)=>{"use strict";var{tokenChars:$s}=xe();function Ns(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&&$s[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}cn.exports={parse:Ns}});var gn=z((ji,mn)=>{"use strict";var Ds=require("events"),dt=require("http"),{Duplex:Vi}=require("stream"),{createHash:Os}=require("crypto"),dn=Pt(),ge=Be(),Cs=ln(),Ls=lt(),{CLOSE_TIMEOUT:Ms,GUID:Bs,kWebSocket:Ws}=ne(),Ps=/^[+/0-9A-Za-z]{22}==$/,un=0,fn=1,hn=2,zt=class extends Ds{constructor(t,r){if(super(),t={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Ms,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Ls,...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=dt.createServer((o,n)=>{let s=dt.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=As(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=un}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===hn){t&&this.once("close",()=>{t(new Error("The server is not running"))}),process.nextTick(Fe,this);return}if(t&&this.once("close",t),this._state!==fn)if(this._state=fn,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(Fe,this):process.nextTick(Fe,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Fe(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",pn);let s=t.headers["sec-websocket-key"],i=t.headers.upgrade,a=+t.headers["sec-websocket-version"];if(t.method!=="GET"){ye(this,t,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){ye(this,t,r,400,"Invalid Upgrade header");return}if(s===void 0||!Ps.test(s)){ye(this,t,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ye(this,t,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){He(r,400);return}let l=t.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Cs.parse(l)}catch{ye(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 ge(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let h=dn.parse(d);h[ge.extensionName]&&(p.accept(h[ge.extensionName]),u[ge.extensionName]=p)}catch{ye(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 He(r,g||401,m,S);this.completeUpgrade(u,s,c,t,r,o,n)});return}if(!this.options.verifyClient(p))return He(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[Ws])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>un)return He(s,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Os("sha1").update(r+Bs).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[ge.extensionName]){let u=t[ge.extensionName].params,p=dn.format({[ge.extensionName]:[u]});c.push(`Sec-WebSocket-Extensions: ${p}`),d._extensions=t}this.emit("headers",c,n),s.write(c.concat(`\r
|
|
2
2
|
`).join(`\r
|
|
3
|
-
`)),s.removeListener("error",
|
|
3
|
+
`)),s.removeListener("error",pn),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(Fe,this)})),a(d,n)}};mn.exports=zt;function As(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 Fe(e){e._state=hn,e.emit("close")}function pn(){this.destroy()}function He(e,t,r,o){r=r||dt.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} ${dt.STATUS_CODES[t]}\r
|
|
4
4
|
`+Object.keys(o).map(n=>`${n}: ${o[n]}`).join(`\r
|
|
5
5
|
`)+`\r
|
|
6
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 Ue(r,o,n,s)}});var wn={};zt(wn,{Receiver:()=>gn.default,Sender:()=>vn.default,WebSocket:()=>Ht.default,WebSocketServer:()=>yn.default,createWebSocketStream:()=>mn.default,default:()=>Cs});var mn,gn,vn,Ht,yn,Cs,bn=In(()=>{"use strict";mn=Re(on(),1),gn=Re(Dt(),1),vn=Re(Lt(),1),Ht=Re(ct(),1),yn=Re(hn(),1),Cs=Ht.default});var Bs={};zt(Bs,{asciiRenderer:()=>fe,createDevServer:()=>_n,createEventCollector:()=>Ms,createIRBuilder:()=>ne,createLiveVisualizer:()=>ar,createParallelDetector:()=>jt,createPerformanceAnalyzer:()=>je,createTimeTravelController:()=>Je,createVisualizer:()=>ut,defaultColorScheme:()=>Z,detectParallelGroups:()=>Ie,getHeatLevel:()=>Ve,hasChildren:()=>Cn,htmlRenderer:()=>ir,isDecisionNode:()=>ue,isParallelNode:()=>oe,isRaceNode:()=>de,isSequenceNode:()=>On,isStepNode:()=>J,mermaidRenderer:()=>Oe,renderToHTML:()=>Ke,trackDecision:()=>Ye,trackIf:()=>cr,trackSwitch:()=>lr,visualizeEvents:()=>Ls});module.exports=$n(Bs);function U(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 ft(){return`node_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function Nn(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 Ie(e,t={}){if(Nn(e))return e;let{minOverlapMs:r=0,maxGapMs:o=5}=t,n=[],s=[];for(let a=0;a<e.length;a++){let c=e[a];c.type==="step"&&c.startTs!==void 0?n.push({node:c,startTs:c.startTs,endTs:c.endTs??c.startTs+(c.durationMs??0),originalIndex:a}):s.push({node:c,originalIndex:a})}if(n.length<=1)return e;n.sort((a,c)=>a.startTs-c.startTs);let i=[],l=[n[0]];for(let a=1;a<n.length;a++){let c=n[a],u=Math.min(...l.map(w=>w.startTs)),p=Math.max(...l.map(w=>w.endTs)),m=c.startTs<=u+o,v=c.startTs<p;if(!m&&!v){i.push(l),l=[c];continue}let g=v?Math.min(c.endTs,p)-c.startTs:0;m||g>=r?l.push(c):(i.push(l),l=[c])}i.push(l);let d=[];for(let a of i){let c=Math.min(...a.map(u=>u.originalIndex));if(a.length===1)d.push({node:a[0].node,position:c});else{let u=a.map(g=>g.node),p=Math.min(...a.map(g=>g.startTs)),m=Math.max(...a.map(g=>g.endTs)),v={type:"parallel",id:`detected_parallel_${p}`,name:`${u.length} parallel steps`,state:Dn(u),mode:"all",children:u,startTs:p,endTs:m,durationMs:m-p};d.push({node:v,position:c})}}for(let{node:a,originalIndex:c}of s)d.push({node:a,position:c});return d.sort((a,c)=>a.position-c.position),d.map(a=>a.node)}function Dn(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 jt(e={}){return{detect:t=>Ie(t,e)}}function ne(e={}){let{detectParallel:t=!0,parallelDetection:r,enableSnapshots:o=!1,maxSnapshots:n=1e3}=e,s,i,l="pending",d,a,c=new Map,u=[],p=[],m=[],v=Date.now(),g=v,w={onAfterStep:new Map},$=[],O=0;function D(f){return f.stepId??f.stepKey??f.name??ft()}function h(f){if(p.length>0){let y=p[p.length-1];for(let F of y.branches.values())if(F.taken){F.children.push(f),g=Date.now();return}let S=Array.from(y.branches.values())[0];if(S){S.children.push(f),g=Date.now();return}}u.length>0?u[u.length-1].children.push(f):m.push(f),g=Date.now()}function x(f){if(!o)return;let y=L(),S=new Map;for(let[K,le]of c)S.set(K,{id:le.id,name:le.name,key:le.key,startTs:le.startTs,retryCount:le.retryCount,timedOut:le.timedOut,timeoutMs:le.timeoutMs});let F={id:`snapshot_${O}`,eventIndex:O,event:structuredClone(f),ir:structuredClone(y),timestamp:Date.now(),activeSteps:S};$.push(F),$.length>n&&$.shift(),O++}function b(f){switch(f.type){case"workflow_start":s=f.workflowId,i=f.ts,l="running",v=Date.now(),g=v,w.onAfterStep=new Map;break;case"workflow_success":l="success",a=f.durationMs,g=Date.now();break;case"workflow_error":l="error",d=f.error,a=f.durationMs,g=Date.now();break;case"step_start":{let y=D(f);c.set(y,{id:y,name:f.name,key:f.stepKey,startTs:f.ts,retryCount:0,timedOut:!1}),g=Date.now();break}case"step_success":{let y=D(f),S=c.get(y);if(S){let F={type:"step",id:S.id,name:S.name,key:S.key,state:"success",startTs:S.startTs,endTs:f.ts,durationMs:f.durationMs,...S.retryCount>0&&{retryCount:S.retryCount},...S.timedOut&&{timedOut:!0,timeoutMs:S.timeoutMs}};h(F),c.delete(y)}break}case"step_error":{let y=D(f),S=c.get(y);if(S){let F={type:"step",id:S.id,name:S.name,key:S.key,state:"error",startTs:S.startTs,endTs:f.ts,durationMs:f.durationMs,error:f.error,...S.retryCount>0&&{retryCount:S.retryCount},...S.timedOut&&{timedOut:!0,timeoutMs:S.timeoutMs}};h(F),c.delete(y)}break}case"step_aborted":{let y=D(f),S=c.get(y);if(S){let F={type:"step",id:S.id,name:S.name,key:S.key,state:"aborted",startTs:S.startTs,endTs:f.ts,durationMs:f.durationMs,...S.retryCount>0&&{retryCount:S.retryCount},...S.timedOut&&{timedOut:!0,timeoutMs:S.timeoutMs}};h(F),c.delete(y)}break}case"step_cache_hit":{let S={type:"step",id:D(f),name:f.name,key:f.stepKey,state:"cached",startTs:f.ts,endTs:f.ts,durationMs:0};h(S);break}case"step_cache_miss":break;case"step_complete":break;case"step_timeout":{let y=D(f),S=c.get(y);S&&(S.timedOut=!0,S.timeoutMs=f.timeoutMs),g=Date.now();break}case"step_retry":{let y=D(f),S=c.get(y);S&&(S.retryCount=(f.attempt??1)-1),g=Date.now();break}case"step_retries_exhausted":g=Date.now();break;case"step_skipped":{let S={type:"step",id:D(f),name:f.name,key:f.stepKey,state:"skipped",startTs:f.ts,endTs:f.ts,durationMs:0};h(S);break}case"hook_should_run":{let y={type:"shouldRun",state:"success",ts:f.ts,durationMs:f.durationMs,context:{result:f.result,skipped:f.skipped}};w.shouldRun=y,g=Date.now();break}case"hook_should_run_error":{let y={type:"shouldRun",state:"error",ts:f.ts,durationMs:f.durationMs,error:f.error};w.shouldRun=y,g=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}};w.onBeforeStart=y,g=Date.now();break}case"hook_before_start_error":{let y={type:"onBeforeStart",state:"error",ts:f.ts,durationMs:f.durationMs,error:f.error};w.onBeforeStart=y,g=Date.now();break}case"hook_after_step":{let y={type:"onAfterStep",state:"success",ts:f.ts,durationMs:f.durationMs,context:{stepKey:f.stepKey}};w.onAfterStep.set(f.stepKey,y),g=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}};w.onAfterStep.set(f.stepKey,y),g=Date.now();break}}x(f)}function k(f){if(f.type==="scope_start")u.push({id:f.scopeId,name:f.name,type:f.scopeType,startTs:f.ts,children:[]}),g=Date.now();else if(f.type==="scope_end"){let y=u.pop();if(y){let S=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"};h(S)}}}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}),g=Date.now();else if(f.type==="decision_branch"){let y=p[p.length-1];if(y&&y.id===f.decisionId){let S=f.branchLabel,F=y.branches.get(S);F?F.taken=f.taken:y.branches.set(S,{label:f.branchLabel,condition:f.condition,taken:f.taken,children:[]}),g=Date.now()}}else if(f.type==="decision_end"){let y=p.pop();if(y&&y.id===f.decisionId){let S=Array.from(y.branches.values()),F={type:"decision",id:y.id,name:y.name,state:C(S.flatMap(K=>K.taken?K.children:[])),startTs:y.startTs,endTs:f.ts,durationMs:f.durationMs,condition:y.condition,decisionValue:y.decisionValue,branchTaken:f.branchTaken??y.branchTaken,branches:S};h(F)}}}function C(f){return f.length===0?"success":f.some(K=>K.state==="error")?"error":f.every(K=>K.state==="success"||K.state==="cached")?"success":f.some(K=>K.state==="running")?"running":"pending"}function I(){let f=[...m];for(let[,y]of c)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=Ie(f,r));let y={type:"workflow",id:s??ft(),workflowId:s??"unknown",state:l,startTs:i,durationMs:a,children:f,error:d},S=w.shouldRun!==void 0||w.onBeforeStart!==void 0||w.onAfterStep.size>0;return{root:y,metadata:{createdAt:v,lastUpdatedAt:g},...S&&{hooks:w}}}function N(){s=void 0,i=void 0,l="pending",d=void 0,a=void 0,c.clear(),u.length=0,p.length=0,m=[],v=Date.now(),g=v,w={onAfterStep:new Map},$.length=0,O=0}function E(){return[...$]}function T(f){return $[f]}function R(f){return $[f]?.ir}function P(){$.length=0,O=0}return{handleEvent:b,handleScopeEvent:k,handleDecisionEvent:B,getIR:L,reset:N,getSnapshots:E,getSnapshotAt:T,getIRAt:R,clearSnapshots:P,get hasActiveSteps(){return c.size>0},get state(){return l},get snapshotCount(){return $.length},get snapshotsEnabled(){return o}}}function J(e){return e.type==="step"}function On(e){return e.type==="sequence"}function oe(e){return e.type==="parallel"}function de(e){return e.type==="race"}function ue(e){return e.type==="decision"}function Cn(e){return"children"in e||e.type==="decision"&&"branches"in e}var pt="\x1B[0m",Ln="\x1B[1m",Gt="\x1B[2m",Mn="\x1B[31m",Bn="\x1B[32m",Pn="\x1B[33m",Wn="\x1B[34m",qt="\x1B[90m",An="\x1B[37m";function se(e,t){return t?`${t}${e}${pt}`:e}function $e(e){return`${Ln}${e}${pt}`}function M(e){return`${Gt}${e}${pt}`}var Z={pending:An,running:Pn,success:Bn,error:Mn,aborted:qt,cached:Wn,skipped:Gt+qt};function Un(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=Un(e);return se(r,t[e])}function ht(e,t,r){return se(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"},ye={cold:"\x1B[34m",cool:"\x1B[36m",neutral:"",warm:"\x1B[33m",hot:"\x1B[31m",critical:"\x1B[41m"},Fn="\x1B[0m";function Hn(e){return e<.2?ye.cold:e<.4?ye.cool:e<.6?ye.neutral:e<.8?ye.warm:e<.95?ye.hot:ye.critical}function Yt(e,t){let r=Hn(t);return r?`${r}${e}${Fn}`:e}var Jt="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function zn(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 l=(i-o)/s,d=Math.floor(l*(Jt.length-1));return Jt[d]}).join("")}function mt(e,t){let r=Kt(e).length,o=Math.max(0,t-r);return e+" ".repeat(o)}function Vn(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"?se("\u2699",r.success):se("\u26A0",r.error),n=e.durationMs!==void 0?M(` [${U(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 jn(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 fe(){return{name:"ascii",supportsLive:!0,render(e,t){let r={...Z,...t.colors},o=t.terminalWidth??60,n=o-4,s=[],i=e.root.name??"workflow",l=$e(i);if(s.push(`${_.topLeft}${Vn(o-2,l)}${_.topRight}`),s.push(`${_.vertical}${" ".repeat(o-2)}${_.vertical}`),e.hooks){let a=jn(e.hooks,r);for(let c of a)s.push(`${_.vertical} ${mt(c,n)}${_.vertical}`)}let d=He(e.root.children,t,r,0,e.hooks);for(let a of d)s.push(`${_.vertical} ${mt(a,n)}${_.vertical}`);if(s.push(`${_.vertical}${" ".repeat(o-2)}${_.vertical}`),e.root.durationMs!==void 0&&t.showTimings){let a=e.root.state==="success"?"Completed":"Failed",u=`${ht(a,e.root.state,r)} in ${U(e.root.durationMs)}`;s.push(`${_.vertical} ${mt(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(gt(i,t,r,n)):oe(i)?s.push(...qn(i,t,r,o,n)):de(i)?s.push(...Gn(i,t,r,o,n)):ue(i)&&s.push(...Kn(i,t,r,o,n));return s}function gt(e,t,r,o){let n=Ne(e.state,r),s=e.name??e.key??"step",i=t,l=e.name??e.id,d=i.showHeatmap&&i.heatmapData?i.heatmapData.heat.get(e.id)??i.heatmapData.heat.get(l):void 0,a;d!==void 0?a=Yt(s,d):a=ht(s,e.state,r);let c=`${n} ${a}`;if(t.showKeys&&e.key&&(c+=M(` [key: ${e.key}]`)),e.input!==void 0){let u=typeof e.input=="string"?e.input:JSON.stringify(e.input).slice(0,30);c+=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);c+=M(` [out: ${u}${u.length>=30?"...":""}]`)}if(t.showTimings&&e.durationMs!==void 0){let u=U(e.durationMs),p=d!==void 0?Yt(`[${u}]`,d):M(`[${u}]`);c+=` ${p}`}if(i.showSparklines&&i.timingHistory){let u=i.timingHistory.get(l);u&&u.length>1&&(c+=` ${M(zn(u))}`)}if(e.retryCount!==void 0&&e.retryCount>0&&(c+=M(` [${e.retryCount} ${e.retryCount===1?"retry":"retries"}]`)),e.timedOut){let u=e.timeoutMs!==void 0?` ${e.timeoutMs}ms`:"";c+=M(` [timeout${u}]`)}if(o&&e.key&&o.onAfterStep.has(e.key)){let u=o.onAfterStep.get(e.key),p=u.state==="success"?se("\u2699",r.success):se("\u26A0",r.error),m=u.durationMs!==void 0?M(` ${U(u.durationMs)}`):"";c+=` ${p}${m}`}return c}function qn(e,t,r,o,n){let s=[],i=" ".repeat(o),l=Ne(e.state,r),d=e.name??"parallel",a=e.mode==="allSettled"?" (allSettled)":"";if(s.push(`${i}${_.teeRight}${_.teeDown}${_.horizontal} ${l} ${$e(d)}${a}`),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 u=e.children[c],m=c===e.children.length-1?`${i}${_.vertical} ${_.bottomLeft}`:`${i}${_.vertical} ${_.teeRight}`;if(J(u))s.push(`${m} ${gt(u,t,r,n)}`);else{let v=He([u],t,r,o+1,n);for(let g of v)s.push(`${i}${_.vertical} ${g}`)}}return t.showTimings&&e.durationMs!==void 0&&s.push(`${i}${_.bottomLeft}${_.horizontal}${_.horizontal} ${M(`[${U(e.durationMs)}]`)}`),s}function Gn(e,t,r,o,n){let s=[],i=" ".repeat(o),l=Ne(e.state,r),d=e.name??"race";if(s.push(`${i}${_.teeRight}\u26A1 ${l} ${$e(d)}`),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 a=0;a<e.children.length;a++){let c=e.children[a],p=a===e.children.length-1?`${i}${_.vertical} ${_.bottomLeft}`:`${i}${_.vertical} ${_.teeRight}`,v=e.winnerId&&c.id===e.winnerId?M(" (winner)"):"";if(J(c))s.push(`${p} ${gt(c,t,r,n)}${v}`);else{let g=He([c],t,r,o+1,n);for(let w of g)s.push(`${i}${_.vertical} ${w}`)}}return t.showTimings&&e.durationMs!==void 0&&s.push(`${i}${_.bottomLeft}${_.horizontal}${_.horizontal} ${M(`[${U(e.durationMs)}]`)}`),s}function Kn(e,t,r,o,n){let s=[],i=" ".repeat(o),l=Ne(e.state,r),d=e.name??"decision",a=e.condition?M(` (${e.condition})`):"",c=e.decisionValue!==void 0?M(` = ${String(e.decisionValue)}`):"",u=e.branchTaken!==void 0?M(` \u2192 ${String(e.branchTaken)}`):"";s.push(`${i}${_.teeRight}${_.teeDown}${_.horizontal} ${l} ${$e(d)}${a}${c}${u}`);for(let p=0;p<e.branches.length;p++){let m=e.branches[p],g=p===e.branches.length-1?`${i}${_.vertical} ${_.bottomLeft}`:`${i}${_.vertical} ${_.teeRight}`,w=m.taken?"\u2713":"\u2298",$=m.taken?r.success:r.skipped,O=se(`${w} ${m.label}`,$),D=m.condition?M(` (${m.condition})`):"";if(s.push(`${g} ${O}${D}`),m.children.length>0){let h=He(m.children,t,r,o+1,n);for(let x of h)s.push(`${i}${_.vertical} ${x}`)}else m.taken||s.push(`${i}${_.vertical} ${M("(skipped)")}`)}return t.showTimings&&e.durationMs!==void 0&&s.push(`${i}${_.bottomLeft}${_.horizontal}${_.horizontal} ${M(`[${U(e.durationMs)}]`)}`),s}function vt(e){let t=[];for(let r of e)if(t.push(r),"children"in r&&Array.isArray(r.children)&&t.push(...vt(r.children)),"branches"in r)for(let o of r.branches)t.push(...vt(o.children));return t}function ze(e,t){if(e.length===0)return 0;let r=Math.floor(e.length*t);return e[Math.min(r,e.length-1)]}function Ve(e){return e<.2?"cold":e<.4?"cool":e<.6?"neutral":e<.8?"warm":e<.95?"hot":"critical"}function je(){let e=new Map,t=new Map,r=new Map,o=new Map,n=[];function s(h){return h.name??h.stepKey??h.stepId??"unknown"}function i(h){let x=new Map;for(let b of h)switch(b.type){case"step_start":{let k=s(b);x.set(k,{retried:!1,timedOut:!1});break}case"step_retry":{let k=s(b),B=x.get(k);B&&(B.retried=!0);break}case"step_timeout":{let k=s(b),B=x.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=x.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),x.delete(k);break}case"step_error":{let k=s(b),B=x.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),x.delete(k);break}}}function l(h){i(h.events)}function d(h){n.push(h)}function a(h){n.length>0&&(i(n),n=[])}function c(h){let x=e.get(h);if(!x||x.length===0)return;let b=[...x].sort((E,T)=>E-T),B=b.reduce((E,T)=>E+T,0)/b.length,C=b.reduce((E,T)=>E+(T-B)**2,0)/b.length,I=t.get(h)??{retried:0,total:1},L=r.get(h)??{errors:0,total:1},N=o.get(h)??{timedOut:0,total:1};return{nodeId:h,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:ze(b,.5),p90:ze(b,.9),p95:ze(b,.95),p99:ze(b,.99)}}}function u(h){return c(h)}function p(h,x="duration"){let b=new Map,k=vt(h.root.children),B=[];for(let T of k){let R=T.name??T.id,P=c(R);if(P){let f;switch(x){case"duration":f=P.avgDurationMs;break;case"retryRate":f=P.retryRate;break;case"errorRate":f=P.errorRate;break}B.push({id:T.id,value:f})}}if(B.length===0)return{heat:b,metric:x,stats:{min:0,max:0,mean:0,threshold:0}};let C=B.map(T=>T.value),I=Math.min(...C),L=Math.max(...C),N=C.reduce((T,R)=>T+R,0)/C.length,E=L-I||1;for(let{id:T,value:R}of B)b.set(T,(R-I)/E);return{heat:b,metric:x,stats:{min:I,max:L,mean:N,threshold:N+(L-N)*.5}}}function m(){let h=new Map;for(let x of e.keys()){let b=c(x);b&&h.set(x,b)}return h}function v(h=10){return[...m().values()].sort((b,k)=>k.avgDurationMs-b.avgDurationMs).slice(0,h)}function g(h=10){return[...m().values()].filter(b=>b.errorRate>0).sort((b,k)=>k.errorRate-b.errorRate).slice(0,h)}function w(h=10){return[...m().values()].filter(b=>b.retryRate>0).sort((b,k)=>k.retryRate-b.retryRate).slice(0,h)}function $(){return JSON.stringify({timingData:Object.fromEntries(e),retryData:Object.fromEntries(t),errorData:Object.fromEntries(r),timeoutData:Object.fromEntries(o)})}function O(h){let x=JSON.parse(h);e.clear(),t.clear(),r.clear(),o.clear();for(let[b,k]of Object.entries(x.timingData??{}))e.set(b,k);for(let[b,k]of Object.entries(x.retryData??{}))t.set(b,k);for(let[b,k]of Object.entries(x.errorData??{}))r.set(b,k);for(let[b,k]of Object.entries(x.timeoutData??{}))o.set(b,k)}function D(){e.clear(),t.clear(),r.clear(),o.clear(),n=[]}return{addRun:l,addEvent:d,finalizeRun:a,getNodePerformance:u,getHeatmap:p,getSlowestNodes:v,getErrorProneNodes:g,getRetryProneNodes:w,getAllPerformance:m,exportData:$,importData:O,clear:D}}function Yn(){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 Jn(){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 Xn(e){return`heat_${e}`}function Zn(){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 Qn(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",l=r.showTimings&&e.shouldRun.durationMs!==void 0?` ${U(e.shouldRun.durationMs)}`:"",d=e.shouldRun.context?.skipped?"\\nskipped workflow":e.shouldRun.context?.result===!0?"\\nproceed":"";t.push(` ${n}[["${i} shouldRun${d}${l}"]]:::${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",l=r.showTimings&&e.onBeforeStart.durationMs!==void 0?` ${U(e.onBeforeStart.durationMs)}`:"",d=e.onBeforeStart.context?.skipped?"\\nskipped workflow":"";t.push(` ${n}[["${i} onBeforeStart${d}${l}"]]:::${s}`),o&&t.push(` ${o} --> ${n}`),o=n}return{lastHookId:o}}var Zt=0;function De(e="node"){return`${e}_${++Zt}`}function eo(){Zt=0}function V(e){return e.replace(/[{}[\]()]/g,"").replace(/[<>]/g,"").replace(/"/g,"'").trim()}function Qt(e){return V(e).replace(/[[\]]/g,"")}function Oe(){return{name:"mermaid",supportsLive:!1,render(e,t){eo();let r=[],o=t;r.push("flowchart TD");let n;e.hooks&&(n=Qn(e.hooks,r,t).lastHookId);let s="start";r.push(` ${s}(("\u25B6 Start"))`),n&&r.push(` ${n} --> ${s}`);let i=s;for(let l of e.root.children){let d=qe(l,t,r,o,e.hooks);r.push(` ${i} --> ${d.entryId}`),i=d.exitId}if(e.root.state==="success"||e.root.state==="error"){let l="finish",d=e.root.state==="success"?"\u2713":"\u2717",a=e.root.state==="success"?"Done":"Failed",c=`(("${d} ${a}"))`,u=e.root.state==="success"?":::success":":::error";r.push(` ${l}${c}${u}`),r.push(` ${i} --> ${l}`)}return r.push(""),r.push(...Yn()),o.showHeatmap&&r.push(...Jn()),e.hooks&&r.push(...Zn()),r.join(`
|
|
9
|
-
`)}}}function
|
|
7
|
+
`+r)}function ye(e,t,r,o,n,s){if(e.listenerCount("wsClientError")){let i=new Error(n);Error.captureStackTrace(i,ye),e.emit("wsClientError",i,r,t)}else He(r,o,n,s)}});var Sn={};jt(Sn,{Receiver:()=>vn.default,Sender:()=>wn.default,WebSocket:()=>Vt.default,WebSocketServer:()=>bn.default,createWebSocketStream:()=>yn.default,default:()=>Fs});var yn,vn,wn,Vt,bn,Fs,xn=Nn(()=>{"use strict";yn=Te(an(),1),vn=Te(Ct(),1),wn=Te(Bt(),1),Vt=Te(lt(),1),bn=Te(gn(),1),Fs=Vt.default});var zs={};jt(zs,{asciiRenderer:()=>re,createDevServer:()=>kn,createEventCollector:()=>Us,createIRBuilder:()=>ae,createLiveVisualizer:()=>lr,createParallelDetector:()=>Gt,createPerformanceAnalyzer:()=>qe,createTimeTravelController:()=>Xe,createVisualizer:()=>ft,defaultColorScheme:()=>te,detectParallelGroups:()=>Ie,getHeatLevel:()=>je,hasChildren:()=>Ln,htmlRenderer:()=>cr,isDecisionNode:()=>ee,isParallelNode:()=>X,isRaceNode:()=>Q,isSequenceNode:()=>ht,isStepNode:()=>q,loggerRenderer:()=>Ce,mermaidRenderer:()=>Oe,renderToHTML:()=>Ye,trackDecision:()=>Je,trackIf:()=>dr,trackSwitch:()=>ur,visualizeEvents:()=>Hs});module.exports=Dn(zs);function F(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 pt(){return`node_${Date.now()}_${Math.random().toString(36).slice(2,8)}`}function On(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 Ie(e,t={}){if(On(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:Cn(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 Cn(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 Gt(e={}){return{detect:t=>Ie(t,e)}}function ae(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??pt()}function v(f){if(p.length>0){let y=p[p.length-1];for(let H of y.branches.values())if(H.taken){H.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 H={id:`snapshot_${O}`,eventIndex:O,event:structuredClone(f),ir:structuredClone(y),timestamp:Date.now(),activeSteps:x};$.push(H),$.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 H={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(H),d.delete(y)}break}case"step_error":{let y=D(f),x=d.get(y);if(x){let H={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(H),d.delete(y)}break}case"step_aborted":{let y=D(f),x=d.get(y);if(x){let H={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(H),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,H=y.branches.get(x);H?H.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()),H={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(H)}}}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=Ie(f,r));let y={type:"workflow",id:s??pt(),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 q(e){return e.type==="step"}function ht(e){return e.type==="sequence"}function X(e){return e.type==="parallel"}function Q(e){return e.type==="race"}function ee(e){return e.type==="decision"}function Ln(e){return"children"in e||e.type==="decision"&&"branches"in e}var mt="\x1B[0m",Mn="\x1B[1m",Yt="\x1B[2m",Bn="\x1B[31m",Wn="\x1B[32m",Pn="\x1B[33m",An="\x1B[34m",Kt="\x1B[90m",Fn="\x1B[37m";function ce(e,t){return t?`${t}${e}${mt}`:e}function $e(e){return`${Mn}${e}${mt}`}function M(e){return`${Yt}${e}${mt}`}var te={pending:Fn,running:Pn,success:Wn,error:Bn,aborted:Kt,cached:An,skipped:Yt+Kt};function Hn(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=Hn(e);return ce(r,t[e])}function gt(e,t,r){return ce(e,r[t])}function Jt(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"},ve={cold:"\x1B[34m",cool:"\x1B[36m",neutral:"",warm:"\x1B[33m",hot:"\x1B[31m",critical:"\x1B[41m"},Un="\x1B[0m";function zn(e){return e<.2?ve.cold:e<.4?ve.cool:e<.6?ve.neutral:e<.8?ve.warm:e<.95?ve.hot:ve.critical}function Xt(e,t){let r=zn(t);return r?`${r}${e}${Un}`:e}var Zt="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Vn(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*(Zt.length-1));return Zt[l]}).join("")}function yt(e,t){let r=Jt(e).length,o=Math.max(0,t-r);return e+" ".repeat(o)}function jn(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 Qt(e,t,r){let o=e.state==="success"?ce("\u2699",r.success):ce("\u26A0",r.error),n=e.durationMs!==void 0?M(` [${F(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 qn(e,t){let r=[];return e.shouldRun&&r.push(Qt(e.shouldRun,"shouldRun",t)),e.onBeforeStart&&r.push(Qt(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 re(){return{name:"ascii",supportsLive:!0,render(e,t){let r={...te,...t.colors},o=t.terminalWidth??60,n=o-4,s=[],i=e.root.name??"workflow",a=$e(i);if(s.push(`${_.topLeft}${jn(o-2,a)}${_.topRight}`),s.push(`${_.vertical}${" ".repeat(o-2)}${_.vertical}`),e.hooks){let c=qn(e.hooks,r);for(let d of c)s.push(`${_.vertical} ${yt(d,n)}${_.vertical}`)}let l=ze(e.root.children,t,r,0,e.hooks);for(let c of l)s.push(`${_.vertical} ${yt(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=`${gt(c,e.root.state,r)} in ${F(e.root.durationMs)}`;s.push(`${_.vertical} ${yt(u,n)}${_.vertical}`),s.push(`${_.vertical}${" ".repeat(o-2)}${_.vertical}`)}return s.push(`${_.bottomLeft}${_.horizontal.repeat(o-2)}${_.bottomRight}`),s.join(`
|
|
8
|
+
`)}}}function ze(e,t,r,o,n){let s=[];for(let i of e)q(i)?s.push(vt(i,t,r,n)):X(i)?s.push(...Gn(i,t,r,o,n)):Q(i)?s.push(...Kn(i,t,r,o,n)):ee(i)&&s.push(...Yn(i,t,r,o,n));return s}function vt(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=Xt(s,l):c=gt(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=F(e.durationMs),p=l!==void 0?Xt(`[${u}]`,l):M(`[${u}]`);d+=` ${p}`}if(i.showSparklines&&i.timingHistory){let u=i.timingHistory.get(a);u&&u.length>1&&(d+=` ${M(Vn(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"?ce("\u2699",r.success):ce("\u26A0",r.error),h=u.durationMs!==void 0?M(` ${F(u.durationMs)}`):"";d+=` ${p}${h}`}return d}function Gn(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(q(u))s.push(`${h} ${vt(u,t,r,n)}`);else{let g=ze([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(`[${F(e.durationMs)}]`)}`),s}function Kn(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(q(d))s.push(`${p} ${vt(d,t,r,n)}${g}`);else{let m=ze([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(`[${F(e.durationMs)}]`)}`),s}function Yn(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=ce(`${S} ${h.label}`,$),D=h.condition?M(` (${h.condition})`):"";if(s.push(`${m} ${O}${D}`),h.children.length>0){let v=ze(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(`[${F(e.durationMs)}]`)}`),s}function wt(e){let t=[];for(let r of e)if(t.push(r),"children"in r&&Array.isArray(r.children)&&t.push(...wt(r.children)),"branches"in r)for(let o of r.branches)t.push(...wt(o.children));return t}function Ve(e,t){if(e.length===0)return 0;let r=Math.floor(e.length*t);return e[Math.min(r,e.length-1)]}function je(e){return e<.2?"cold":e<.4?"cool":e<.6?"neutral":e<.8?"warm":e<.95?"hot":"critical"}function qe(){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:Ve(b,.5),p90:Ve(b,.9),p95:Ve(b,.95),p99:Ve(b,.99)}}}function u(v){return d(v)}function p(v,w="duration"){let b=new Map,k=wt(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 Jn(){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 Xn(){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 Zn(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 eo(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?` ${F(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?` ${F(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 er=0;function De(e="node"){return`${e}_${++er}`}function to(){er=0}function V(e){return e.replace(/[{}[\]()]/g,"").replace(/[<>]/g,"").replace(/"/g,"'").trim()}function tr(e){return V(e).replace(/[[\]]/g,"")}function Oe(){return{name:"mermaid",supportsLive:!1,render(e,t){to();let r=[],o=t;r.push("flowchart TD");let n;e.hooks&&(n=eo(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=Ge(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(...Jn()),o.showHeatmap&&r.push(...Xn()),e.hooks&&r.push(...Qn()),r.join(`
|
|
9
|
+
`)}}}function Ge(e,t,r,o,n){if(q(e))return ro(e,t,r,o,n);if(X(e))return no(e,t,r,o,n);if(Q(e))return oo(e,t,r,o,n);if(ee(e))return so(e,t,r,o,n);let s=De("unknown");return r.push(` ${s}[Unknown Node]`),{entryId:s,exitId:s}}function ro(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=V(e.name??e.key??"Step"),u=t.showTimings&&e.durationMs!==void 0?` ${F(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"?V(e.input):V(JSON.stringify(e.input).slice(0,20));h+=`\\nin: ${v}`}if(e.output!==void 0&&e.state==="success"){let v=typeof e.output=="string"?V(e.output):V(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?` ${F(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=je(O);S=Zn(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=V(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 no(e,t,r,o,n){let s=De("parallel"),i=`${s}_fork`,a=`${s}_join`,l=tr(e.name??"Parallel"),c=e.mode==="allSettled"?" (allSettled)":"";if(e.children.length===0){let p=s,h=V(`${l}${c}`),g="operations not individually tracked",m=t.showTimings&&e.durationMs!==void 0?` ${F(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=Ge(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 oo(e,t,r,o,n){let s=De("race"),i=`${s}_start`,a=`${s}_end`,l=tr(e.name??"Race");if(e.children.length===0){let p=s,h=V(l),g="operations not individually tracked",m=t.showTimings&&e.durationMs!==void 0?` ${F(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=Ge(p,t,r,o,n),g=q(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 so(e,t,r,o,n){let s=e.key?`decision_${e.key.replace(/[^a-zA-Z0-9]/g,"_")}`:De("decision"),i=V(e.condition??"condition"),a=e.decisionValue!==void 0?` = ${V(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=V(u.label),g=u.taken?`${h} \u2713`:`${h} skipped`,m=u.taken?":::success":":::skipped";r.push(` ${p}[${g}]${m}`);let S=u.condition?`|${V(u.condition).replace(/\|/g,"")}|`:"";if(r.push(` ${s} -->${S} ${p}`),u.children.length>0){let $=p;for(let O of u.children){let D=Ge(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 io(e){return e.replace(/\x1b\[[0-9;]*m/g,"")}function ao(e){let t=[];function r(o){for(let n of o)if(q(n))t.push(n);else if(ht(n))r(n.children);else if(X(n)||Q(n))r(n.children);else if(ee(n))for(let s of n.branches)r(s.children)}return r(e),t}function co(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 lo(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 uo(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 fo(e,t){let r=e.root,o=ao(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(co),summary:lo(o)};if(e.hooks){let a=uo(e.hooks);Object.keys(a).length>0&&(i.hooks=a)}if(n){let l=re().render(e,t);s&&(l=io(l)),i.diagram=l}return i}function Ce(){return{name:"logger",supportsLive:!1,render(e,t){let o=fo(e,t);return JSON.stringify(o)}}}function rr(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
10
|
--bg: ${s.bg};
|
|
11
11
|
--bg-secondary: ${s.bgSecondary};
|
|
12
12
|
--text: ${s.text};
|
|
@@ -505,7 +505,7 @@ body {
|
|
|
505
505
|
height: auto;
|
|
506
506
|
}
|
|
507
507
|
}
|
|
508
|
-
`}function
|
|
508
|
+
`}function nr(e){return`
|
|
509
509
|
(function() {
|
|
510
510
|
'use strict';
|
|
511
511
|
|
|
@@ -1087,38 +1087,38 @@ body {
|
|
|
1087
1087
|
return (ms / 60000).toFixed(1) + 'm';
|
|
1088
1088
|
}
|
|
1089
1089
|
})();
|
|
1090
|
-
`}var we=160,
|
|
1091
|
-
<g class="wv-node wv-node--${e.state}" data-node-id="${
|
|
1090
|
+
`}var we=160,Ke=50,bt=40,po=30,U=20;function ho(e,t="TB"){let r=t==="TB"||t==="BT",o=[],n=U,s=U,i=0,a=0;for(let l of e){let c=St(l,n,s,r);o.push(c.node),r?(s+=c.height+po,i=Math.max(i,c.width),a=s):(n+=c.width+bt,a=Math.max(a,c.height),i=n)}return{nodes:o,width:i+U,height:a+U}}function St(e,t,r,o){if(q(e))return{node:{id:e.id,name:e.name??e.key??"step",type:"step",state:e.state,x:t,y:r,width:we,height:Ke,durationMs:e.durationMs},width:we,height:Ke};if(X(e)||Q(e)){let n=X(e)?"parallel":"race",s=e.name??n,i=[],a=t+U,l=r+U+20,c=0,d=0;for(let h of e.children){let g=St(h,a,l,!0);i.push(g.node),a+=g.width+bt,d=Math.max(d,g.height)}c=a-t-U;let u=Math.max(c+U,we+U*2),p=d+U*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(ee(e)){let n=e.name??"decision",s=[],i=t+U,a=r+U+20,l=0;for(let u of e.branches)for(let p of u.children){let h=St(p,i,a,!0);s.push(h.node),i+=h.width+bt,l=Math.max(l,h.height)}let c=Math.max(i-t,we+U*2),d=l+U*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:we,height:Ke},width:we,height:Ke}}function or(e,t){return e.containerType?go(e,t):mo(e,t)}function mo(e,t){let o=t&&e.durationMs!==void 0?F(e.durationMs):"";return`
|
|
1091
|
+
<g class="wv-node wv-node--${e.state}" data-node-id="${ir(e.id)}" transform="translate(${e.x}, ${e.y})">
|
|
1092
1092
|
<rect width="${e.width}" height="${e.height}" rx="8" ry="8" />
|
|
1093
|
-
<text x="${e.width/2}" y="${e.height/2-(o?4:0)}">${
|
|
1093
|
+
<text x="${e.width/2}" y="${e.height/2-(o?4:0)}">${xt(bo(e.name,20))}</text>
|
|
1094
1094
|
${o?`<text class="wv-node-timing" x="${e.width/2}" y="${e.height/2+12}">${o}</text>`:""}
|
|
1095
1095
|
</g>
|
|
1096
|
-
`}function
|
|
1096
|
+
`}function go(e,t){let o=e.children?.map(n=>or(n,t)).join(`
|
|
1097
1097
|
`)??"";return`
|
|
1098
|
-
<g class="wv-container wv-container--${e.containerType}" data-node-id="${
|
|
1098
|
+
<g class="wv-container wv-container--${e.containerType}" data-node-id="${ir(e.id)}" transform="translate(${e.x}, ${e.y})">
|
|
1099
1099
|
<rect width="${e.width}" height="${e.height}" rx="12" ry="12" />
|
|
1100
|
-
<text class="wv-container-label" x="${
|
|
1100
|
+
<text class="wv-container-label" x="${U}" y="16">${e.containerLabel}</text>
|
|
1101
1101
|
<g transform="translate(${-e.x}, ${-e.y})">
|
|
1102
1102
|
${o}
|
|
1103
1103
|
</g>
|
|
1104
1104
|
</g>
|
|
1105
|
-
`}function
|
|
1106
|
-
<path class="wv-edge" d="M ${s} ${i} L ${
|
|
1107
|
-
<polygon class="wv-edge-arrow" points="${
|
|
1105
|
+
`}function yo(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
1108
|
`)}return t.join(`
|
|
1109
|
-
`)}function
|
|
1110
|
-
`),i=
|
|
1109
|
+
`)}function sr(e,t){let r=ho(e.root.children,t.layout),o=Math.max(r.width,400),n=Math.max(r.height,300),s=r.nodes.map(d=>or(d,t.showTimings)).join(`
|
|
1110
|
+
`),i=yo(r.nodes),a=e.root.name??"Workflow",l=rr(t.theme),c=nr({wsUrl:t.wsUrl,interactive:t.interactive,timeTravel:t.timeTravel,heatmap:t.heatmap});return`<!DOCTYPE html>
|
|
1111
1111
|
<html lang="en">
|
|
1112
1112
|
<head>
|
|
1113
1113
|
<meta charset="UTF-8">
|
|
1114
1114
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1115
|
-
<title>${
|
|
1116
|
-
<style>${
|
|
1115
|
+
<title>${xt(a)} - Workflow Visualizer</title>
|
|
1116
|
+
<style>${l}</style>
|
|
1117
1117
|
</head>
|
|
1118
1118
|
<body>
|
|
1119
1119
|
<div class="workflow-visualizer">
|
|
1120
1120
|
<header class="wv-header">
|
|
1121
|
-
<h1>${
|
|
1121
|
+
<h1>${xt(a)}</h1>
|
|
1122
1122
|
<div class="wv-controls">
|
|
1123
1123
|
${t.wsUrl?'<div id="live-indicator" class="wv-live" style="display:none"><span class="wv-live-dot"></span>LIVE</div>':""}
|
|
1124
1124
|
${t.heatmap?`
|
|
@@ -1183,13 +1183,13 @@ body {
|
|
|
1183
1183
|
</div>
|
|
1184
1184
|
|
|
1185
1185
|
<script>
|
|
1186
|
-
window.__WORKFLOW_DATA__ = ${
|
|
1186
|
+
window.__WORKFLOW_DATA__ = ${wo(e)};
|
|
1187
1187
|
</script>
|
|
1188
|
-
<script>${
|
|
1188
|
+
<script>${c}</script>
|
|
1189
1189
|
</body>
|
|
1190
|
-
</html>`}function
|
|
1191
|
-
`),p=E,
|
|
1192
|
-
`).length)}function O(){u&&(
|
|
1193
|
-
`),
|
|
1194
|
-
Install with: npm install ws`),null}}function D(E){let
|
|
1190
|
+
</html>`}function vo(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 wo(e){return JSON.stringify(vo(e)).replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/&/g,"\\u0026").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function xt(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ir(e){return e.replace(/"/g,""").replace(/'/g,"'")}function bo(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}var ar={interactive:!0,timeTravel:!0,heatmap:!0,animationDuration:200,theme:"auto",layout:"TB"};function cr(){return{name:"html",supportsLive:!0,render(e,t){let r={...t,...ar,...t};return sr(e,r)}}}function Ye(e,t={}){let r={showTimings:!0,showKeys:!1,colors:{pending:"#6c757d",running:"#ffc107",success:"#198754",error:"#dc3545",aborted:"#6c757d",cached:"#0dcaf0",skipped:"#adb5bd"},...ar,...t};return sr(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 lr(e={}){let{workflowName:t,detectParallel:r=!0,showTimings:o=!0,showKeys:n=!1,colors:s,stream:i=process.stdout,updateInterval:a=100}=e,l=ae({detectParallel:r}),c=re(),d={showTimings:o,showKeys:n,terminalWidth:i.columns??80,colors:{...te,...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 Je(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 dr(e,t,r={}){let o=Je(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 ur(e,t,r={}){let o=Je(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 Xe(e={}){let{maxSnapshots:t=1e3,autoRecord:r=!0,builderOptions:o={}}=e,n=ae({...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}}var _n=require("http"),ut=require("child_process");async function kn(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=Xe({maxSnapshots:a}),c=qe(),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 Ye(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(()=>(xn(),Sn)),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"?(0,ut.execFile)("open",[E],T=>{T&&console.warn("[DevServer] Failed to open browser:",T.message)}):R==="win32"?(0,ut.execFile)("cmd.exe",["/c","start","",E],T=>{T&&console.warn("[DevServer] Failed to open browser:",T.message)}):(0,ut.execFile)("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=(0,_n.createServer)($),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 ft(e={}){let{workflowName:t,detectParallel:r=!0,showTimings:o=!0,showKeys:n=!1,colors:s}=e,i=ae({detectParallel:r}),a=new Set,l=re(),c=Oe(),d=Ce(),u={showTimings:o,showKeys:n,terminalWidth:process.stdout?.columns??80,colors:{...te,...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 Hs(e,t={}){let r=ft(t);for(let o of e)o.type.startsWith("decision_")?r.handleDecisionEvent(o):r.handleEvent(o);return r.render()}function Us(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=ft(e);for(let o of t)o.type.startsWith("decision_")?r.handleDecisionEvent(o):r.handleEvent(o);return r.render()},visualizeAs:r=>{let o=ft(e);for(let n of t)n.type.startsWith("decision_")?o.handleDecisionEvent(n):o.handleEvent(n);return o.renderAs(r)}}}0&&(module.exports={asciiRenderer,createDevServer,createEventCollector,createIRBuilder,createLiveVisualizer,createParallelDetector,createPerformanceAnalyzer,createTimeTravelController,createVisualizer,defaultColorScheme,detectParallelGroups,getHeatLevel,hasChildren,htmlRenderer,isDecisionNode,isParallelNode,isRaceNode,isSequenceNode,isStepNode,loggerRenderer,mermaidRenderer,renderToHTML,trackDecision,trackIf,trackSwitch,visualizeEvents});
|
|
1195
1195
|
//# sourceMappingURL=visualize.cjs.map
|