hypha-debugger 0.1.11 → 0.2.1

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.
@@ -1,31 +1,40 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).hyphaDebugger={})}(this,function(exports){"use strict";var __webpack_modules__={"./src/http-client.js":
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).hyphaDebugger={})}(this,function(exports){"use strict";var __webpack_modules__={"./node_modules/tweetnacl/nacl-fast.js":
2
+ /*!*********************************************!*\
3
+ !*** ./node_modules/tweetnacl/nacl-fast.js ***!
4
+ \*********************************************/(e,t,n)=>{!function(e){var t=function(e){var t,n=new Float64Array(16);if(e)for(t=0;t<e.length;t++)n[t]=e[t];return n},r=function(){throw new Error("no PRNG")},o=new Uint8Array(16),i=new Uint8Array(32);i[0]=9;var s=t(),a=t([1]),c=t([56129,1]),l=t([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),h=t([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),d=t([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),_=t([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),u=t([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function p(e,t,n,r){e[t]=n>>24&255,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=255&n,e[t+4]=r>>24&255,e[t+5]=r>>16&255,e[t+6]=r>>8&255,e[t+7]=255&r}function f(e,t,n,r,o){var i,s=0;for(i=0;i<o;i++)s|=e[t+i]^n[r+i];return(1&s-1>>>8)-1}function g(e,t,n,r){return f(e,t,n,r,16)}function m(e,t,n,r){return f(e,t,n,r,32)}function y(e,t,n,r){!function(e,t,n,r){for(var o,i=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,c=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,l=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,h=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,d=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,_=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,u=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,p=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,f=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,g=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,m=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,y=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,w=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,b=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,v=i,k=s,E=a,x=c,S=l,T=h,C=d,R=_,I=u,A=p,P=f,j=g,D=m,O=y,U=w,M=b,$=0;$<20;$+=2)v^=(o=(D^=(o=(I^=(o=(S^=(o=v+D|0)<<7|o>>>25)+v|0)<<9|o>>>23)+S|0)<<13|o>>>19)+I|0)<<18|o>>>14,T^=(o=(k^=(o=(O^=(o=(A^=(o=T+k|0)<<7|o>>>25)+T|0)<<9|o>>>23)+A|0)<<13|o>>>19)+O|0)<<18|o>>>14,P^=(o=(C^=(o=(E^=(o=(U^=(o=P+C|0)<<7|o>>>25)+P|0)<<9|o>>>23)+U|0)<<13|o>>>19)+E|0)<<18|o>>>14,M^=(o=(j^=(o=(R^=(o=(x^=(o=M+j|0)<<7|o>>>25)+M|0)<<9|o>>>23)+x|0)<<13|o>>>19)+R|0)<<18|o>>>14,v^=(o=(x^=(o=(E^=(o=(k^=(o=v+x|0)<<7|o>>>25)+v|0)<<9|o>>>23)+k|0)<<13|o>>>19)+E|0)<<18|o>>>14,T^=(o=(S^=(o=(R^=(o=(C^=(o=T+S|0)<<7|o>>>25)+T|0)<<9|o>>>23)+C|0)<<13|o>>>19)+R|0)<<18|o>>>14,P^=(o=(A^=(o=(I^=(o=(j^=(o=P+A|0)<<7|o>>>25)+P|0)<<9|o>>>23)+j|0)<<13|o>>>19)+I|0)<<18|o>>>14,M^=(o=(U^=(o=(O^=(o=(D^=(o=M+U|0)<<7|o>>>25)+M|0)<<9|o>>>23)+D|0)<<13|o>>>19)+O|0)<<18|o>>>14;v=v+i|0,k=k+s|0,E=E+a|0,x=x+c|0,S=S+l|0,T=T+h|0,C=C+d|0,R=R+_|0,I=I+u|0,A=A+p|0,P=P+f|0,j=j+g|0,D=D+m|0,O=O+y|0,U=U+w|0,M=M+b|0,e[0]=v>>>0&255,e[1]=v>>>8&255,e[2]=v>>>16&255,e[3]=v>>>24&255,e[4]=k>>>0&255,e[5]=k>>>8&255,e[6]=k>>>16&255,e[7]=k>>>24&255,e[8]=E>>>0&255,e[9]=E>>>8&255,e[10]=E>>>16&255,e[11]=E>>>24&255,e[12]=x>>>0&255,e[13]=x>>>8&255,e[14]=x>>>16&255,e[15]=x>>>24&255,e[16]=S>>>0&255,e[17]=S>>>8&255,e[18]=S>>>16&255,e[19]=S>>>24&255,e[20]=T>>>0&255,e[21]=T>>>8&255,e[22]=T>>>16&255,e[23]=T>>>24&255,e[24]=C>>>0&255,e[25]=C>>>8&255,e[26]=C>>>16&255,e[27]=C>>>24&255,e[28]=R>>>0&255,e[29]=R>>>8&255,e[30]=R>>>16&255,e[31]=R>>>24&255,e[32]=I>>>0&255,e[33]=I>>>8&255,e[34]=I>>>16&255,e[35]=I>>>24&255,e[36]=A>>>0&255,e[37]=A>>>8&255,e[38]=A>>>16&255,e[39]=A>>>24&255,e[40]=P>>>0&255,e[41]=P>>>8&255,e[42]=P>>>16&255,e[43]=P>>>24&255,e[44]=j>>>0&255,e[45]=j>>>8&255,e[46]=j>>>16&255,e[47]=j>>>24&255,e[48]=D>>>0&255,e[49]=D>>>8&255,e[50]=D>>>16&255,e[51]=D>>>24&255,e[52]=O>>>0&255,e[53]=O>>>8&255,e[54]=O>>>16&255,e[55]=O>>>24&255,e[56]=U>>>0&255,e[57]=U>>>8&255,e[58]=U>>>16&255,e[59]=U>>>24&255,e[60]=M>>>0&255,e[61]=M>>>8&255,e[62]=M>>>16&255,e[63]=M>>>24&255}(e,t,n,r)}function w(e,t,n,r){!function(e,t,n,r){for(var o,i=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,c=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,l=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,h=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,d=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,_=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,u=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,p=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,f=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,g=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,m=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,y=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,w=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,b=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,v=0;v<20;v+=2)i^=(o=(m^=(o=(u^=(o=(l^=(o=i+m|0)<<7|o>>>25)+i|0)<<9|o>>>23)+l|0)<<13|o>>>19)+u|0)<<18|o>>>14,h^=(o=(s^=(o=(y^=(o=(p^=(o=h+s|0)<<7|o>>>25)+h|0)<<9|o>>>23)+p|0)<<13|o>>>19)+y|0)<<18|o>>>14,f^=(o=(d^=(o=(a^=(o=(w^=(o=f+d|0)<<7|o>>>25)+f|0)<<9|o>>>23)+w|0)<<13|o>>>19)+a|0)<<18|o>>>14,b^=(o=(g^=(o=(_^=(o=(c^=(o=b+g|0)<<7|o>>>25)+b|0)<<9|o>>>23)+c|0)<<13|o>>>19)+_|0)<<18|o>>>14,i^=(o=(c^=(o=(a^=(o=(s^=(o=i+c|0)<<7|o>>>25)+i|0)<<9|o>>>23)+s|0)<<13|o>>>19)+a|0)<<18|o>>>14,h^=(o=(l^=(o=(_^=(o=(d^=(o=h+l|0)<<7|o>>>25)+h|0)<<9|o>>>23)+d|0)<<13|o>>>19)+_|0)<<18|o>>>14,f^=(o=(p^=(o=(u^=(o=(g^=(o=f+p|0)<<7|o>>>25)+f|0)<<9|o>>>23)+g|0)<<13|o>>>19)+u|0)<<18|o>>>14,b^=(o=(w^=(o=(y^=(o=(m^=(o=b+w|0)<<7|o>>>25)+b|0)<<9|o>>>23)+m|0)<<13|o>>>19)+y|0)<<18|o>>>14;e[0]=i>>>0&255,e[1]=i>>>8&255,e[2]=i>>>16&255,e[3]=i>>>24&255,e[4]=h>>>0&255,e[5]=h>>>8&255,e[6]=h>>>16&255,e[7]=h>>>24&255,e[8]=f>>>0&255,e[9]=f>>>8&255,e[10]=f>>>16&255,e[11]=f>>>24&255,e[12]=b>>>0&255,e[13]=b>>>8&255,e[14]=b>>>16&255,e[15]=b>>>24&255,e[16]=d>>>0&255,e[17]=d>>>8&255,e[18]=d>>>16&255,e[19]=d>>>24&255,e[20]=_>>>0&255,e[21]=_>>>8&255,e[22]=_>>>16&255,e[23]=_>>>24&255,e[24]=u>>>0&255,e[25]=u>>>8&255,e[26]=u>>>16&255,e[27]=u>>>24&255,e[28]=p>>>0&255,e[29]=p>>>8&255,e[30]=p>>>16&255,e[31]=p>>>24&255}(e,t,n,r)}var b=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function v(e,t,n,r,o,i,s){var a,c,l=new Uint8Array(16),h=new Uint8Array(64);for(c=0;c<16;c++)l[c]=0;for(c=0;c<8;c++)l[c]=i[c];for(;o>=64;){for(y(h,l,s,b),c=0;c<64;c++)e[t+c]=n[r+c]^h[c];for(a=1,c=8;c<16;c++)a=a+(255&l[c])|0,l[c]=255&a,a>>>=8;o-=64,t+=64,r+=64}if(o>0)for(y(h,l,s,b),c=0;c<o;c++)e[t+c]=n[r+c]^h[c];return 0}function k(e,t,n,r,o){var i,s,a=new Uint8Array(16),c=new Uint8Array(64);for(s=0;s<16;s++)a[s]=0;for(s=0;s<8;s++)a[s]=r[s];for(;n>=64;){for(y(c,a,o,b),s=0;s<64;s++)e[t+s]=c[s];for(i=1,s=8;s<16;s++)i=i+(255&a[s])|0,a[s]=255&i,i>>>=8;n-=64,t+=64}if(n>0)for(y(c,a,o,b),s=0;s<n;s++)e[t+s]=c[s];return 0}function E(e,t,n,r,o){var i=new Uint8Array(32);w(i,r,o,b);for(var s=new Uint8Array(8),a=0;a<8;a++)s[a]=r[a+16];return k(e,t,n,s,i)}function x(e,t,n,r,o,i,s){var a=new Uint8Array(32);w(a,i,s,b);for(var c=new Uint8Array(8),l=0;l<8;l++)c[l]=i[l+16];return v(e,t,n,r,o,c,a)}var S=function(e){var t,n,r,o,i,s,a,c;this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0,t=255&e[0]|(255&e[1])<<8,this.r[0]=8191&t,n=255&e[2]|(255&e[3])<<8,this.r[1]=8191&(t>>>13|n<<3),r=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(n>>>10|r<<6),o=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(r>>>7|o<<9),i=255&e[8]|(255&e[9])<<8,this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,s=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(i>>>14|s<<2),a=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(s>>>11|a<<5),c=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function T(e,t,n,r,o,i){var s=new S(i);return s.update(n,r,o),s.finish(e,t),0}function C(e,t,n,r,o,i){var s=new Uint8Array(16);return T(s,0,n,r,o,i),g(e,t,s,0)}function R(e,t,n,r,o){var i;if(n<32)return-1;for(x(e,0,t,0,n,r,o),T(e,16,e,32,n-32,e),i=0;i<16;i++)e[i]=0;return 0}function I(e,t,n,r,o){var i,s=new Uint8Array(32);if(n<32)return-1;if(E(s,0,32,r,o),0!==C(t,16,t,32,n-32,s))return-1;for(x(e,0,t,0,n,r,o),i=0;i<32;i++)e[i]=0;return 0}function A(e,t){var n;for(n=0;n<16;n++)e[n]=0|t[n]}function P(e){var t,n,r=1;for(t=0;t<16;t++)n=e[t]+r+65535,r=Math.floor(n/65536),e[t]=n-65536*r;e[0]+=r-1+37*(r-1)}function j(e,t,n){for(var r,o=~(n-1),i=0;i<16;i++)r=o&(e[i]^t[i]),e[i]^=r,t[i]^=r}function D(e,n){var r,o,i,s=t(),a=t();for(r=0;r<16;r++)a[r]=n[r];for(P(a),P(a),P(a),o=0;o<2;o++){for(s[0]=a[0]-65517,r=1;r<15;r++)s[r]=a[r]-65535-(s[r-1]>>16&1),s[r-1]&=65535;s[15]=a[15]-32767-(s[14]>>16&1),i=s[15]>>16&1,s[14]&=65535,j(a,s,1-i)}for(r=0;r<16;r++)e[2*r]=255&a[r],e[2*r+1]=a[r]>>8}function O(e,t){var n=new Uint8Array(32),r=new Uint8Array(32);return D(n,e),D(r,t),m(n,0,r,0)}function U(e){var t=new Uint8Array(32);return D(t,e),1&t[0]}function M(e,t){var n;for(n=0;n<16;n++)e[n]=t[2*n]+(t[2*n+1]<<8);e[15]&=32767}function $(e,t,n){for(var r=0;r<16;r++)e[r]=t[r]+n[r]}function L(e,t,n){for(var r=0;r<16;r++)e[r]=t[r]-n[r]}function H(e,t,n){var r,o,i=0,s=0,a=0,c=0,l=0,h=0,d=0,_=0,u=0,p=0,f=0,g=0,m=0,y=0,w=0,b=0,v=0,k=0,E=0,x=0,S=0,T=0,C=0,R=0,I=0,A=0,P=0,j=0,D=0,O=0,U=0,M=n[0],$=n[1],L=n[2],H=n[3],N=n[4],F=n[5],W=n[6],B=n[7],z=n[8],q=n[9],K=n[10],V=n[11],G=n[12],Y=n[13],X=n[14],J=n[15];i+=(r=t[0])*M,s+=r*$,a+=r*L,c+=r*H,l+=r*N,h+=r*F,d+=r*W,_+=r*B,u+=r*z,p+=r*q,f+=r*K,g+=r*V,m+=r*G,y+=r*Y,w+=r*X,b+=r*J,s+=(r=t[1])*M,a+=r*$,c+=r*L,l+=r*H,h+=r*N,d+=r*F,_+=r*W,u+=r*B,p+=r*z,f+=r*q,g+=r*K,m+=r*V,y+=r*G,w+=r*Y,b+=r*X,v+=r*J,a+=(r=t[2])*M,c+=r*$,l+=r*L,h+=r*H,d+=r*N,_+=r*F,u+=r*W,p+=r*B,f+=r*z,g+=r*q,m+=r*K,y+=r*V,w+=r*G,b+=r*Y,v+=r*X,k+=r*J,c+=(r=t[3])*M,l+=r*$,h+=r*L,d+=r*H,_+=r*N,u+=r*F,p+=r*W,f+=r*B,g+=r*z,m+=r*q,y+=r*K,w+=r*V,b+=r*G,v+=r*Y,k+=r*X,E+=r*J,l+=(r=t[4])*M,h+=r*$,d+=r*L,_+=r*H,u+=r*N,p+=r*F,f+=r*W,g+=r*B,m+=r*z,y+=r*q,w+=r*K,b+=r*V,v+=r*G,k+=r*Y,E+=r*X,x+=r*J,h+=(r=t[5])*M,d+=r*$,_+=r*L,u+=r*H,p+=r*N,f+=r*F,g+=r*W,m+=r*B,y+=r*z,w+=r*q,b+=r*K,v+=r*V,k+=r*G,E+=r*Y,x+=r*X,S+=r*J,d+=(r=t[6])*M,_+=r*$,u+=r*L,p+=r*H,f+=r*N,g+=r*F,m+=r*W,y+=r*B,w+=r*z,b+=r*q,v+=r*K,k+=r*V,E+=r*G,x+=r*Y,S+=r*X,T+=r*J,_+=(r=t[7])*M,u+=r*$,p+=r*L,f+=r*H,g+=r*N,m+=r*F,y+=r*W,w+=r*B,b+=r*z,v+=r*q,k+=r*K,E+=r*V,x+=r*G,S+=r*Y,T+=r*X,C+=r*J,u+=(r=t[8])*M,p+=r*$,f+=r*L,g+=r*H,m+=r*N,y+=r*F,w+=r*W,b+=r*B,v+=r*z,k+=r*q,E+=r*K,x+=r*V,S+=r*G,T+=r*Y,C+=r*X,R+=r*J,p+=(r=t[9])*M,f+=r*$,g+=r*L,m+=r*H,y+=r*N,w+=r*F,b+=r*W,v+=r*B,k+=r*z,E+=r*q,x+=r*K,S+=r*V,T+=r*G,C+=r*Y,R+=r*X,I+=r*J,f+=(r=t[10])*M,g+=r*$,m+=r*L,y+=r*H,w+=r*N,b+=r*F,v+=r*W,k+=r*B,E+=r*z,x+=r*q,S+=r*K,T+=r*V,C+=r*G,R+=r*Y,I+=r*X,A+=r*J,g+=(r=t[11])*M,m+=r*$,y+=r*L,w+=r*H,b+=r*N,v+=r*F,k+=r*W,E+=r*B,x+=r*z,S+=r*q,T+=r*K,C+=r*V,R+=r*G,I+=r*Y,A+=r*X,P+=r*J,m+=(r=t[12])*M,y+=r*$,w+=r*L,b+=r*H,v+=r*N,k+=r*F,E+=r*W,x+=r*B,S+=r*z,T+=r*q,C+=r*K,R+=r*V,I+=r*G,A+=r*Y,P+=r*X,j+=r*J,y+=(r=t[13])*M,w+=r*$,b+=r*L,v+=r*H,k+=r*N,E+=r*F,x+=r*W,S+=r*B,T+=r*z,C+=r*q,R+=r*K,I+=r*V,A+=r*G,P+=r*Y,j+=r*X,D+=r*J,w+=(r=t[14])*M,b+=r*$,v+=r*L,k+=r*H,E+=r*N,x+=r*F,S+=r*W,T+=r*B,C+=r*z,R+=r*q,I+=r*K,A+=r*V,P+=r*G,j+=r*Y,D+=r*X,O+=r*J,b+=(r=t[15])*M,s+=38*(k+=r*L),a+=38*(E+=r*H),c+=38*(x+=r*N),l+=38*(S+=r*F),h+=38*(T+=r*W),d+=38*(C+=r*B),_+=38*(R+=r*z),u+=38*(I+=r*q),p+=38*(A+=r*K),f+=38*(P+=r*V),g+=38*(j+=r*G),m+=38*(D+=r*Y),y+=38*(O+=r*X),w+=38*(U+=r*J),i=(r=(i+=38*(v+=r*$))+(o=1)+65535)-65536*(o=Math.floor(r/65536)),s=(r=s+o+65535)-65536*(o=Math.floor(r/65536)),a=(r=a+o+65535)-65536*(o=Math.floor(r/65536)),c=(r=c+o+65535)-65536*(o=Math.floor(r/65536)),l=(r=l+o+65535)-65536*(o=Math.floor(r/65536)),h=(r=h+o+65535)-65536*(o=Math.floor(r/65536)),d=(r=d+o+65535)-65536*(o=Math.floor(r/65536)),_=(r=_+o+65535)-65536*(o=Math.floor(r/65536)),u=(r=u+o+65535)-65536*(o=Math.floor(r/65536)),p=(r=p+o+65535)-65536*(o=Math.floor(r/65536)),f=(r=f+o+65535)-65536*(o=Math.floor(r/65536)),g=(r=g+o+65535)-65536*(o=Math.floor(r/65536)),m=(r=m+o+65535)-65536*(o=Math.floor(r/65536)),y=(r=y+o+65535)-65536*(o=Math.floor(r/65536)),w=(r=w+o+65535)-65536*(o=Math.floor(r/65536)),b=(r=b+o+65535)-65536*(o=Math.floor(r/65536)),i=(r=(i+=o-1+37*(o-1))+(o=1)+65535)-65536*(o=Math.floor(r/65536)),s=(r=s+o+65535)-65536*(o=Math.floor(r/65536)),a=(r=a+o+65535)-65536*(o=Math.floor(r/65536)),c=(r=c+o+65535)-65536*(o=Math.floor(r/65536)),l=(r=l+o+65535)-65536*(o=Math.floor(r/65536)),h=(r=h+o+65535)-65536*(o=Math.floor(r/65536)),d=(r=d+o+65535)-65536*(o=Math.floor(r/65536)),_=(r=_+o+65535)-65536*(o=Math.floor(r/65536)),u=(r=u+o+65535)-65536*(o=Math.floor(r/65536)),p=(r=p+o+65535)-65536*(o=Math.floor(r/65536)),f=(r=f+o+65535)-65536*(o=Math.floor(r/65536)),g=(r=g+o+65535)-65536*(o=Math.floor(r/65536)),m=(r=m+o+65535)-65536*(o=Math.floor(r/65536)),y=(r=y+o+65535)-65536*(o=Math.floor(r/65536)),w=(r=w+o+65535)-65536*(o=Math.floor(r/65536)),b=(r=b+o+65535)-65536*(o=Math.floor(r/65536)),i+=o-1+37*(o-1),e[0]=i,e[1]=s,e[2]=a,e[3]=c,e[4]=l,e[5]=h,e[6]=d,e[7]=_,e[8]=u,e[9]=p,e[10]=f,e[11]=g,e[12]=m,e[13]=y,e[14]=w,e[15]=b}function N(e,t){H(e,t,t)}function F(e,n){var r,o=t();for(r=0;r<16;r++)o[r]=n[r];for(r=253;r>=0;r--)N(o,o),2!==r&&4!==r&&H(o,o,n);for(r=0;r<16;r++)e[r]=o[r]}function W(e,n){var r,o=t();for(r=0;r<16;r++)o[r]=n[r];for(r=250;r>=0;r--)N(o,o),1!==r&&H(o,o,n);for(r=0;r<16;r++)e[r]=o[r]}function B(e,n,r){var o,i,s=new Uint8Array(32),a=new Float64Array(80),l=t(),h=t(),d=t(),_=t(),u=t(),p=t();for(i=0;i<31;i++)s[i]=n[i];for(s[31]=127&n[31]|64,s[0]&=248,M(a,r),i=0;i<16;i++)h[i]=a[i],_[i]=l[i]=d[i]=0;for(l[0]=_[0]=1,i=254;i>=0;--i)j(l,h,o=s[i>>>3]>>>(7&i)&1),j(d,_,o),$(u,l,d),L(l,l,d),$(d,h,_),L(h,h,_),N(_,u),N(p,l),H(l,d,l),H(d,h,u),$(u,l,d),L(l,l,d),N(h,l),L(d,_,p),H(l,d,c),$(l,l,_),H(d,d,l),H(l,_,p),H(_,h,a),N(h,u),j(l,h,o),j(d,_,o);for(i=0;i<16;i++)a[i+16]=l[i],a[i+32]=d[i],a[i+48]=h[i],a[i+64]=_[i];var f=a.subarray(32),g=a.subarray(16);return F(f,f),H(g,g,f),D(e,g),0}function z(e,t){return B(e,t,i)}function q(e,t){return r(t,32),z(e,t)}function K(e,t,n){var r=new Uint8Array(32);return B(r,n,t),w(e,o,r,b)}S.prototype.blocks=function(e,t,n){for(var r,o,i,s,a,c,l,h,d,_,u,p,f,g,m,y,w,b,v,k=this.fin?0:2048,E=this.h[0],x=this.h[1],S=this.h[2],T=this.h[3],C=this.h[4],R=this.h[5],I=this.h[6],A=this.h[7],P=this.h[8],j=this.h[9],D=this.r[0],O=this.r[1],U=this.r[2],M=this.r[3],$=this.r[4],L=this.r[5],H=this.r[6],N=this.r[7],F=this.r[8],W=this.r[9];n>=16;)_=d=0,_+=(E+=8191&(r=255&e[t+0]|(255&e[t+1])<<8))*D,_+=(x+=8191&(r>>>13|(o=255&e[t+2]|(255&e[t+3])<<8)<<3))*(5*W),_+=(S+=8191&(o>>>10|(i=255&e[t+4]|(255&e[t+5])<<8)<<6))*(5*F),_+=(T+=8191&(i>>>7|(s=255&e[t+6]|(255&e[t+7])<<8)<<9))*(5*N),d=(_+=(C+=8191&(s>>>4|(a=255&e[t+8]|(255&e[t+9])<<8)<<12))*(5*H))>>>13,_&=8191,_+=(R+=a>>>1&8191)*(5*L),_+=(I+=8191&(a>>>14|(c=255&e[t+10]|(255&e[t+11])<<8)<<2))*(5*$),_+=(A+=8191&(c>>>11|(l=255&e[t+12]|(255&e[t+13])<<8)<<5))*(5*M),_+=(P+=8191&(l>>>8|(h=255&e[t+14]|(255&e[t+15])<<8)<<8))*(5*U),u=d+=(_+=(j+=h>>>5|k)*(5*O))>>>13,u+=E*O,u+=x*D,u+=S*(5*W),u+=T*(5*F),d=(u+=C*(5*N))>>>13,u&=8191,u+=R*(5*H),u+=I*(5*L),u+=A*(5*$),u+=P*(5*M),d+=(u+=j*(5*U))>>>13,u&=8191,p=d,p+=E*U,p+=x*O,p+=S*D,p+=T*(5*W),d=(p+=C*(5*F))>>>13,p&=8191,p+=R*(5*N),p+=I*(5*H),p+=A*(5*L),p+=P*(5*$),f=d+=(p+=j*(5*M))>>>13,f+=E*M,f+=x*U,f+=S*O,f+=T*D,d=(f+=C*(5*W))>>>13,f&=8191,f+=R*(5*F),f+=I*(5*N),f+=A*(5*H),f+=P*(5*L),g=d+=(f+=j*(5*$))>>>13,g+=E*$,g+=x*M,g+=S*U,g+=T*O,d=(g+=C*D)>>>13,g&=8191,g+=R*(5*W),g+=I*(5*F),g+=A*(5*N),g+=P*(5*H),m=d+=(g+=j*(5*L))>>>13,m+=E*L,m+=x*$,m+=S*M,m+=T*U,d=(m+=C*O)>>>13,m&=8191,m+=R*D,m+=I*(5*W),m+=A*(5*F),m+=P*(5*N),y=d+=(m+=j*(5*H))>>>13,y+=E*H,y+=x*L,y+=S*$,y+=T*M,d=(y+=C*U)>>>13,y&=8191,y+=R*O,y+=I*D,y+=A*(5*W),y+=P*(5*F),w=d+=(y+=j*(5*N))>>>13,w+=E*N,w+=x*H,w+=S*L,w+=T*$,d=(w+=C*M)>>>13,w&=8191,w+=R*U,w+=I*O,w+=A*D,w+=P*(5*W),b=d+=(w+=j*(5*F))>>>13,b+=E*F,b+=x*N,b+=S*H,b+=T*L,d=(b+=C*$)>>>13,b&=8191,b+=R*M,b+=I*U,b+=A*O,b+=P*D,v=d+=(b+=j*(5*W))>>>13,v+=E*W,v+=x*F,v+=S*N,v+=T*H,d=(v+=C*L)>>>13,v&=8191,v+=R*$,v+=I*M,v+=A*U,v+=P*O,E=_=8191&(d=(d=((d+=(v+=j*D)>>>13)<<2)+d|0)+(_&=8191)|0),x=u+=d>>>=13,S=p&=8191,T=f&=8191,C=g&=8191,R=m&=8191,I=y&=8191,A=w&=8191,P=b&=8191,j=v&=8191,t+=16,n-=16;this.h[0]=E,this.h[1]=x,this.h[2]=S,this.h[3]=T,this.h[4]=C,this.h[5]=R,this.h[6]=I,this.h[7]=A,this.h[8]=P,this.h[9]=j},S.prototype.finish=function(e,t){var n,r,o,i,s=new Uint16Array(10);if(this.leftover){for(i=this.leftover,this.buffer[i++]=1;i<16;i++)this.buffer[i]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(n=this.h[1]>>>13,this.h[1]&=8191,i=2;i<10;i++)this.h[i]+=n,n=this.h[i]>>>13,this.h[i]&=8191;for(this.h[0]+=5*n,n=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=n,n=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=n,s[0]=this.h[0]+5,n=s[0]>>>13,s[0]&=8191,i=1;i<10;i++)s[i]=this.h[i]+n,n=s[i]>>>13,s[i]&=8191;for(s[9]-=8192,r=(1^n)-1,i=0;i<10;i++)s[i]&=r;for(r=~r,i=0;i<10;i++)this.h[i]=this.h[i]&r|s[i];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),o=this.h[0]+this.pad[0],this.h[0]=65535&o,i=1;i<8;i++)o=(this.h[i]+this.pad[i]|0)+(o>>>16)|0,this.h[i]=65535&o;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},S.prototype.update=function(e,t,n){var r,o;if(this.leftover){for((o=16-this.leftover)>n&&(o=n),r=0;r<o;r++)this.buffer[this.leftover+r]=e[t+r];if(n-=o,t+=o,this.leftover+=o,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(n>=16&&(o=n-n%16,this.blocks(e,t,o),t+=o,n-=o),n){for(r=0;r<n;r++)this.buffer[this.leftover+r]=e[t+r];this.leftover+=n}};var V=R,G=I;var Y=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function X(e,t,n,r){for(var o,i,s,a,c,l,h,d,_,u,p,f,g,m,y,w,b,v,k,E,x,S,T,C,R,I,A=new Int32Array(16),P=new Int32Array(16),j=e[0],D=e[1],O=e[2],U=e[3],M=e[4],$=e[5],L=e[6],H=e[7],N=t[0],F=t[1],W=t[2],B=t[3],z=t[4],q=t[5],K=t[6],V=t[7],G=0;r>=128;){for(k=0;k<16;k++)E=8*k+G,A[k]=n[E+0]<<24|n[E+1]<<16|n[E+2]<<8|n[E+3],P[k]=n[E+4]<<24|n[E+5]<<16|n[E+6]<<8|n[E+7];for(k=0;k<80;k++)if(o=j,i=D,s=O,a=U,c=M,l=$,h=L,H,_=N,u=F,p=W,f=B,g=z,m=q,y=K,V,T=65535&(S=V),C=S>>>16,R=65535&(x=H),I=x>>>16,T+=65535&(S=(z>>>14|M<<18)^(z>>>18|M<<14)^(M>>>9|z<<23)),C+=S>>>16,R+=65535&(x=(M>>>14|z<<18)^(M>>>18|z<<14)^(z>>>9|M<<23)),I+=x>>>16,T+=65535&(S=z&q^~z&K),C+=S>>>16,R+=65535&(x=M&$^~M&L),I+=x>>>16,T+=65535&(S=Y[2*k+1]),C+=S>>>16,R+=65535&(x=Y[2*k]),I+=x>>>16,x=A[k%16],C+=(S=P[k%16])>>>16,R+=65535&x,I+=x>>>16,R+=(C+=(T+=65535&S)>>>16)>>>16,T=65535&(S=v=65535&T|C<<16),C=S>>>16,R=65535&(x=b=65535&R|(I+=R>>>16)<<16),I=x>>>16,T+=65535&(S=(N>>>28|j<<4)^(j>>>2|N<<30)^(j>>>7|N<<25)),C+=S>>>16,R+=65535&(x=(j>>>28|N<<4)^(N>>>2|j<<30)^(N>>>7|j<<25)),I+=x>>>16,C+=(S=N&F^N&W^F&W)>>>16,R+=65535&(x=j&D^j&O^D&O),I+=x>>>16,d=65535&(R+=(C+=(T+=65535&S)>>>16)>>>16)|(I+=R>>>16)<<16,w=65535&T|C<<16,T=65535&(S=f),C=S>>>16,R=65535&(x=a),I=x>>>16,C+=(S=v)>>>16,R+=65535&(x=b),I+=x>>>16,D=o,O=i,U=s,M=a=65535&(R+=(C+=(T+=65535&S)>>>16)>>>16)|(I+=R>>>16)<<16,$=c,L=l,H=h,j=d,F=_,W=u,B=p,z=f=65535&T|C<<16,q=g,K=m,V=y,N=w,k%16==15)for(E=0;E<16;E++)x=A[E],T=65535&(S=P[E]),C=S>>>16,R=65535&x,I=x>>>16,x=A[(E+9)%16],T+=65535&(S=P[(E+9)%16]),C+=S>>>16,R+=65535&x,I+=x>>>16,b=A[(E+1)%16],T+=65535&(S=((v=P[(E+1)%16])>>>1|b<<31)^(v>>>8|b<<24)^(v>>>7|b<<25)),C+=S>>>16,R+=65535&(x=(b>>>1|v<<31)^(b>>>8|v<<24)^b>>>7),I+=x>>>16,b=A[(E+14)%16],C+=(S=((v=P[(E+14)%16])>>>19|b<<13)^(b>>>29|v<<3)^(v>>>6|b<<26))>>>16,R+=65535&(x=(b>>>19|v<<13)^(v>>>29|b<<3)^b>>>6),I+=x>>>16,I+=(R+=(C+=(T+=65535&S)>>>16)>>>16)>>>16,A[E]=65535&R|I<<16,P[E]=65535&T|C<<16;T=65535&(S=N),C=S>>>16,R=65535&(x=j),I=x>>>16,x=e[0],C+=(S=t[0])>>>16,R+=65535&x,I+=x>>>16,I+=(R+=(C+=(T+=65535&S)>>>16)>>>16)>>>16,e[0]=j=65535&R|I<<16,t[0]=N=65535&T|C<<16,T=65535&(S=F),C=S>>>16,R=65535&(x=D),I=x>>>16,x=e[1],C+=(S=t[1])>>>16,R+=65535&x,I+=x>>>16,I+=(R+=(C+=(T+=65535&S)>>>16)>>>16)>>>16,e[1]=D=65535&R|I<<16,t[1]=F=65535&T|C<<16,T=65535&(S=W),C=S>>>16,R=65535&(x=O),I=x>>>16,x=e[2],C+=(S=t[2])>>>16,R+=65535&x,I+=x>>>16,I+=(R+=(C+=(T+=65535&S)>>>16)>>>16)>>>16,e[2]=O=65535&R|I<<16,t[2]=W=65535&T|C<<16,T=65535&(S=B),C=S>>>16,R=65535&(x=U),I=x>>>16,x=e[3],C+=(S=t[3])>>>16,R+=65535&x,I+=x>>>16,I+=(R+=(C+=(T+=65535&S)>>>16)>>>16)>>>16,e[3]=U=65535&R|I<<16,t[3]=B=65535&T|C<<16,T=65535&(S=z),C=S>>>16,R=65535&(x=M),I=x>>>16,x=e[4],C+=(S=t[4])>>>16,R+=65535&x,I+=x>>>16,I+=(R+=(C+=(T+=65535&S)>>>16)>>>16)>>>16,e[4]=M=65535&R|I<<16,t[4]=z=65535&T|C<<16,T=65535&(S=q),C=S>>>16,R=65535&(x=$),I=x>>>16,x=e[5],C+=(S=t[5])>>>16,R+=65535&x,I+=x>>>16,I+=(R+=(C+=(T+=65535&S)>>>16)>>>16)>>>16,e[5]=$=65535&R|I<<16,t[5]=q=65535&T|C<<16,T=65535&(S=K),C=S>>>16,R=65535&(x=L),I=x>>>16,x=e[6],C+=(S=t[6])>>>16,R+=65535&x,I+=x>>>16,I+=(R+=(C+=(T+=65535&S)>>>16)>>>16)>>>16,e[6]=L=65535&R|I<<16,t[6]=K=65535&T|C<<16,T=65535&(S=V),C=S>>>16,R=65535&(x=H),I=x>>>16,x=e[7],C+=(S=t[7])>>>16,R+=65535&x,I+=x>>>16,I+=(R+=(C+=(T+=65535&S)>>>16)>>>16)>>>16,e[7]=H=65535&R|I<<16,t[7]=V=65535&T|C<<16,G+=128,r-=128}return r}function J(e,t,n){var r,o=new Int32Array(8),i=new Int32Array(8),s=new Uint8Array(256),a=n;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,i[0]=4089235720,i[1]=2227873595,i[2]=4271175723,i[3]=1595750129,i[4]=2917565137,i[5]=725511199,i[6]=4215389547,i[7]=327033209,X(o,i,t,n),n%=128,r=0;r<n;r++)s[r]=t[a-n+r];for(s[n]=128,s[(n=256-128*(n<112?1:0))-9]=0,p(s,n-8,a/536870912|0,a<<3),X(o,i,s,n),r=0;r<8;r++)p(e,8*r,o[r],i[r]);return 0}function Q(e,n){var r=t(),o=t(),i=t(),s=t(),a=t(),c=t(),l=t(),d=t(),_=t();L(r,e[1],e[0]),L(_,n[1],n[0]),H(r,r,_),$(o,e[0],e[1]),$(_,n[0],n[1]),H(o,o,_),H(i,e[3],n[3]),H(i,i,h),H(s,e[2],n[2]),$(s,s,s),L(a,o,r),L(c,s,i),$(l,s,i),$(d,o,r),H(e[0],a,c),H(e[1],d,l),H(e[2],l,c),H(e[3],a,d)}function Z(e,t,n){var r;for(r=0;r<4;r++)j(e[r],t[r],n)}function ee(e,n){var r=t(),o=t(),i=t();F(i,n[2]),H(r,n[0],i),H(o,n[1],i),D(e,o),e[31]^=U(r)<<7}function te(e,t,n){var r,o;for(A(e[0],s),A(e[1],a),A(e[2],a),A(e[3],s),o=255;o>=0;--o)Z(e,t,r=n[o/8|0]>>(7&o)&1),Q(t,e),Q(e,e),Z(e,t,r)}function ne(e,n){var r=[t(),t(),t(),t()];A(r[0],d),A(r[1],_),A(r[2],a),H(r[3],d,_),te(e,r,n)}function re(e,n,o){var i,s=new Uint8Array(64),a=[t(),t(),t(),t()];for(o||r(n,32),J(s,n,32),s[0]&=248,s[31]&=127,s[31]|=64,ne(a,s),ee(e,a),i=0;i<32;i++)n[i+32]=e[i];return 0}var oe=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function ie(e,t){var n,r,o,i;for(r=63;r>=32;--r){for(n=0,o=r-32,i=r-12;o<i;++o)t[o]+=n-16*t[r]*oe[o-(r-32)],n=Math.floor((t[o]+128)/256),t[o]-=256*n;t[o]+=n,t[r]=0}for(n=0,o=0;o<32;o++)t[o]+=n-(t[31]>>4)*oe[o],n=t[o]>>8,t[o]&=255;for(o=0;o<32;o++)t[o]-=n*oe[o];for(r=0;r<32;r++)t[r+1]+=t[r]>>8,e[r]=255&t[r]}function se(e){var t,n=new Float64Array(64);for(t=0;t<64;t++)n[t]=e[t];for(t=0;t<64;t++)e[t]=0;ie(e,n)}function ae(e,n,r,o){var i,s,a=new Uint8Array(64),c=new Uint8Array(64),l=new Uint8Array(64),h=new Float64Array(64),d=[t(),t(),t(),t()];J(a,o,32),a[0]&=248,a[31]&=127,a[31]|=64;var _=r+64;for(i=0;i<r;i++)e[64+i]=n[i];for(i=0;i<32;i++)e[32+i]=a[32+i];for(J(l,e.subarray(32),r+32),se(l),ne(d,l),ee(e,d),i=32;i<64;i++)e[i]=o[i];for(J(c,e,r+64),se(c),i=0;i<64;i++)h[i]=0;for(i=0;i<32;i++)h[i]=l[i];for(i=0;i<32;i++)for(s=0;s<32;s++)h[i+s]+=c[i]*a[s];return ie(e.subarray(32),h),_}function ce(e,n,r,o){var i,c=new Uint8Array(32),h=new Uint8Array(64),d=[t(),t(),t(),t()],_=[t(),t(),t(),t()];if(r<64)return-1;if(function(e,n){var r=t(),o=t(),i=t(),c=t(),h=t(),d=t(),_=t();return A(e[2],a),M(e[1],n),N(i,e[1]),H(c,i,l),L(i,i,e[2]),$(c,e[2],c),N(h,c),N(d,h),H(_,d,h),H(r,_,i),H(r,r,c),W(r,r),H(r,r,i),H(r,r,c),H(r,r,c),H(e[0],r,c),N(o,e[0]),H(o,o,c),O(o,i)&&H(e[0],e[0],u),N(o,e[0]),H(o,o,c),O(o,i)?-1:(U(e[0])===n[31]>>7&&L(e[0],s,e[0]),H(e[3],e[0],e[1]),0)}(_,o))return-1;for(i=0;i<r;i++)e[i]=n[i];for(i=0;i<32;i++)e[i+32]=o[i];if(J(h,e,r),se(h),te(d,_,h),ne(_,n.subarray(32)),Q(d,_),ee(c,d),r-=64,m(n,0,c,0)){for(i=0;i<r;i++)e[i]=0;return-1}for(i=0;i<r;i++)e[i]=n[i+64];return r}var le=16,he=64,de=32,_e=64;function ue(e,t){if(32!==e.length)throw new Error("bad key size");if(24!==t.length)throw new Error("bad nonce size")}function pe(){for(var e=0;e<arguments.length;e++)if(!(arguments[e]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function fe(e){for(var t=0;t<e.length;t++)e[t]=0}e.lowlevel={crypto_core_hsalsa20:w,crypto_stream_xor:x,crypto_stream:E,crypto_stream_salsa20_xor:v,crypto_stream_salsa20:k,crypto_onetimeauth:T,crypto_onetimeauth_verify:C,crypto_verify_16:g,crypto_verify_32:m,crypto_secretbox:R,crypto_secretbox_open:I,crypto_scalarmult:B,crypto_scalarmult_base:z,crypto_box_beforenm:K,crypto_box_afternm:V,crypto_box:function(e,t,n,r,o,i){var s=new Uint8Array(32);return K(s,o,i),V(e,t,n,r,s)},crypto_box_open:function(e,t,n,r,o,i){var s=new Uint8Array(32);return K(s,o,i),G(e,t,n,r,s)},crypto_box_keypair:q,crypto_hash:J,crypto_sign:ae,crypto_sign_keypair:re,crypto_sign_open:ce,crypto_secretbox_KEYBYTES:32,crypto_secretbox_NONCEBYTES:24,crypto_secretbox_ZEROBYTES:32,crypto_secretbox_BOXZEROBYTES:le,crypto_scalarmult_BYTES:32,crypto_scalarmult_SCALARBYTES:32,crypto_box_PUBLICKEYBYTES:32,crypto_box_SECRETKEYBYTES:32,crypto_box_BEFORENMBYTES:32,crypto_box_NONCEBYTES:24,crypto_box_ZEROBYTES:32,crypto_box_BOXZEROBYTES:16,crypto_sign_BYTES:he,crypto_sign_PUBLICKEYBYTES:de,crypto_sign_SECRETKEYBYTES:_e,crypto_sign_SEEDBYTES:32,crypto_hash_BYTES:64,gf:t,D:l,L:oe,pack25519:D,unpack25519:M,M:H,A:$,S:N,Z:L,pow2523:W,add:Q,set25519:A,modL:ie,scalarmult:te,scalarbase:ne},e.randomBytes=function(e){var t=new Uint8Array(e);return r(t,e),t},e.secretbox=function(e,t,n){pe(e,t,n),ue(n,t);for(var r=new Uint8Array(32+e.length),o=new Uint8Array(r.length),i=0;i<e.length;i++)r[i+32]=e[i];return R(o,r,r.length,t,n),o.subarray(le)},e.secretbox.open=function(e,t,n){pe(e,t,n),ue(n,t);for(var r=new Uint8Array(le+e.length),o=new Uint8Array(r.length),i=0;i<e.length;i++)r[i+le]=e[i];return r.length<32||0!==I(o,r,r.length,t,n)?null:o.subarray(32)},e.secretbox.keyLength=32,e.secretbox.nonceLength=24,e.secretbox.overheadLength=le,e.scalarMult=function(e,t){if(pe(e,t),32!==e.length)throw new Error("bad n size");if(32!==t.length)throw new Error("bad p size");var n=new Uint8Array(32);return B(n,e,t),n},e.scalarMult.base=function(e){if(pe(e),32!==e.length)throw new Error("bad n size");var t=new Uint8Array(32);return z(t,e),t},e.scalarMult.scalarLength=32,e.scalarMult.groupElementLength=32,e.box=function(t,n,r,o){var i=e.box.before(r,o);return e.secretbox(t,n,i)},e.box.before=function(e,t){pe(e,t),function(e,t){if(32!==e.length)throw new Error("bad public key size");if(32!==t.length)throw new Error("bad secret key size")}(e,t);var n=new Uint8Array(32);return K(n,e,t),n},e.box.after=e.secretbox,e.box.open=function(t,n,r,o){var i=e.box.before(r,o);return e.secretbox.open(t,n,i)},e.box.open.after=e.secretbox.open,e.box.keyPair=function(){var e=new Uint8Array(32),t=new Uint8Array(32);return q(e,t),{publicKey:e,secretKey:t}},e.box.keyPair.fromSecretKey=function(e){if(pe(e),32!==e.length)throw new Error("bad secret key size");var t=new Uint8Array(32);return z(t,e),{publicKey:t,secretKey:new Uint8Array(e)}},e.box.publicKeyLength=32,e.box.secretKeyLength=32,e.box.sharedKeyLength=32,e.box.nonceLength=24,e.box.overheadLength=e.secretbox.overheadLength,e.sign=function(e,t){if(pe(e,t),t.length!==_e)throw new Error("bad secret key size");var n=new Uint8Array(he+e.length);return ae(n,e,e.length,t),n},e.sign.open=function(e,t){if(pe(e,t),t.length!==de)throw new Error("bad public key size");var n=new Uint8Array(e.length),r=ce(n,e,e.length,t);if(r<0)return null;for(var o=new Uint8Array(r),i=0;i<o.length;i++)o[i]=n[i];return o},e.sign.detached=function(t,n){for(var r=e.sign(t,n),o=new Uint8Array(he),i=0;i<o.length;i++)o[i]=r[i];return o},e.sign.detached.verify=function(e,t,n){if(pe(e,t,n),t.length!==he)throw new Error("bad signature size");if(n.length!==de)throw new Error("bad public key size");var r,o=new Uint8Array(he+e.length),i=new Uint8Array(he+e.length);for(r=0;r<he;r++)o[r]=t[r];for(r=0;r<e.length;r++)o[r+he]=e[r];return ce(i,o,o.length,n)>=0},e.sign.keyPair=function(){var e=new Uint8Array(de),t=new Uint8Array(_e);return re(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(pe(e),e.length!==_e)throw new Error("bad secret key size");for(var t=new Uint8Array(de),n=0;n<t.length;n++)t[n]=e[32+n];return{publicKey:t,secretKey:new Uint8Array(e)}},e.sign.keyPair.fromSeed=function(e){if(pe(e),32!==e.length)throw new Error("bad seed size");for(var t=new Uint8Array(de),n=new Uint8Array(_e),r=0;r<32;r++)n[r]=e[r];return re(t,n,!0),{publicKey:t,secretKey:n}},e.sign.publicKeyLength=de,e.sign.secretKeyLength=_e,e.sign.seedLength=32,e.sign.signatureLength=he,e.hash=function(e){pe(e);var t=new Uint8Array(64);return J(t,e,e.length),t},e.hash.hashLength=64,e.verify=function(e,t){return pe(e,t),0!==e.length&&0!==t.length&&(e.length===t.length&&0===f(e,0,t,0,e.length))},e.setPRNG=function(e){r=e},function(){var t="undefined"!=typeof self?self.crypto||self.msCrypto:null;if(t&&t.getRandomValues){e.setPRNG(function(e,n){var r,o=new Uint8Array(n);for(r=0;r<n;r+=65536)t.getRandomValues(o.subarray(r,r+Math.min(n-r,65536)));for(r=0;r<n;r++)e[r]=o[r];fe(o)})}else(t=n(/*! crypto */"?dba7"))&&t.randomBytes&&e.setPRNG(function(e,n){var r,o=t.randomBytes(n);for(r=0;r<n;r++)e[r]=o[r];fe(o)})}()}(e.exports?e.exports:self.nacl=self.nacl||{})},"./src/crypto.js":
5
+ /*!***********************!*\
6
+ !*** ./src/crypto.js ***!
7
+ \***********************/(e,t,n)=>{n.r(t),n.d(t,{decryptPayload:()=>l,encryptPayload:()=>c,generateEncryptionKeypair:()=>a,publicKeyFromHex:()=>s,publicKeyToHex:()=>i});let r=null;function o(){if(r)return r;try{return r=n(/*! tweetnacl */"./node_modules/tweetnacl/nacl-fast.js"),r.default&&(r=r.default),r}catch(e){throw new Error("The 'tweetnacl' package is required for encryption. Install it with: npm install tweetnacl")}}function i(e){return Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}function s(e){const t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substr(2*n,2),16);return t}async function a(){const e=o().box.keyPair();return{privateKey:e.secretKey,publicKey:e.publicKey}}async function c(e,t,n){const r=o(),i=r.randomBytes(r.box.nonceLength);return{nonce:i,ciphertext:r.box(n,i,t,e)}}async function l(e,t,n,r){const i=o().box.open(r,n,t,e);if(null===i)throw new Error("Decryption failed");return i}},"./src/http-client.js":
2
8
  /*!****************************!*\
3
9
  !*** ./src/http-client.js ***!
4
- \****************************/(e,t,n)=>{n.r(t),n.d(t,{HTTPStreamingRPCConnection:()=>a,_connectToServerHTTP:()=>d,connectToServerHTTP:()=>h,getRemoteServiceHTTP:()=>u,normalizeServerUrl:()=>l});var r=n(/*! ./rpc.js */"./src/rpc.js"),o=n(/*! ./utils/index.js */"./src/utils/index.js"),i=n(/*! ./utils/schema.js */"./src/utils/schema.js"),s=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs"),c=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs");class a{constructor(e,t,n=null,r=null,i=null,s=60,c=7200){(0,o.assert)(e&&t,"server_url and client_id are required"),this._server_url=e.replace(/\/$/,""),this._client_id=t,this._workspace=n,this._token=r,this._reconnection_token=i,this._timeout=s,this._token_refresh_interval=c,this._handle_message=null,this._handle_disconnected=null,this._handle_connected=null,this._closed=!1,this._enable_reconnect=!1,this._is_reconnection=!1,this.connection_info=null,this.manager_id=null,this._abort_controller=null,this._refresh_token_task=null}on_message(e){(0,o.assert)(e,"handler is required"),this._handle_message=e}on_disconnected(e){this._handle_disconnected=e}on_connected(e){this._handle_connected=e}_get_headers(e=!1){const t={"Content-Type":"application/msgpack"};return e&&(t.Accept="application/x-msgpack-stream"),this._token&&(t.Authorization=`Bearer ${this._token}`),t}async open(){console.info(`Opening HTTP streaming connection to ${this._server_url}`);const e=this._workspace||"public",t=`${this._server_url}/${e}/rpc?client_id=${this._client_id}`;this._startStreamLoop(t);const n=Date.now();for(;null===this.connection_info;){if(await new Promise(e=>setTimeout(e,100)),Date.now()-n>1e3*this._timeout)throw new Error("Timeout waiting for connection info");if(this._closed)throw new Error("Connection closed during setup")}if(this.manager_id=this.connection_info.manager_id,this._workspace){const e=this.connection_info.workspace;if(e!==this._workspace)throw new Error(`Connected to wrong workspace: ${e}, expected: ${this._workspace}`)}if(this._workspace=this.connection_info.workspace,this.connection_info.reconnection_token&&(this._reconnection_token=this.connection_info.reconnection_token),this.connection_info.reconnection_token_life_time){const e=this.connection_info.reconnection_token_life_time;this._token_refresh_interval>e/1.5&&(console.warn(`Token refresh interval (${this._token_refresh_interval}s) is too long, adjusting to ${(e/1.5).toFixed(0)}s based on token lifetime`),this._token_refresh_interval=e/1.5)}return console.info(`HTTP streaming connected to workspace: ${this._workspace}, manager_id: ${this.manager_id}`),this._token_refresh_interval>0&&this._startTokenRefresh(),this._handle_connected&&await this._handle_connected(this.connection_info),this.connection_info}_startTokenRefresh(){this._refresh_token_task&&clearInterval(this._refresh_token_task),setTimeout(()=>{this._sendRefreshToken(),this._refresh_token_task=setInterval(()=>{this._sendRefreshToken()},1e3*this._token_refresh_interval)},2e3)}async _sendRefreshToken(){if(!this._closed)try{const e=this._workspace||"public",t=`${this._server_url}/${e}/rpc?client_id=${this._client_id}`,n=(0,s.encode)({type:"refresh_token"}),r=await fetch(t,{method:"POST",headers:this._get_headers(!1),body:n});r.ok?console.debug("Token refresh requested successfully"):console.warn(`Token refresh request failed: ${r.status}`)}catch(e){console.warn(`Failed to send refresh token request: ${e.message}`)}}async _startStreamLoop(e){this._enable_reconnect=!0,this._closed=!1;let t=0;for(this._is_reconnection=!1;!this._closed&&t<1e6;){try{const e=this._workspace||"public";let n=`${this._server_url}/${e}/rpc?client_id=${this._client_id}`;this._reconnection_token&&(n+=`&reconnection_token=${encodeURIComponent(this._reconnection_token)}`),this._abort_controller=new AbortController;const r=await fetch(n,{method:"GET",headers:this._get_headers(!0),signal:this._abort_controller.signal});if(!r.ok){const e=await r.text();throw new Error(`Stream failed with status ${r.status}: ${e}`)}t=0,await this._processMsgpackStream(r)}catch(e){if(this._closed)break;if(console.error(`Connection error: ${e.message}`),!this._enable_reconnect)break}if(this._is_reconnection=!0,this._closed||!this._enable_reconnect)break;{t+=1;const e=Math.min(Math.pow(2,Math.min(t,6)),60);console.warn(`Stream disconnected, reconnecting in ${e.toFixed(1)}s (attempt ${t})`),await new Promise(t=>setTimeout(t,1e3*e))}}!this._closed&&this._handle_disconnected&&this._handle_disconnected("Stream ended")}_tryDecodeControlMessage(e){try{const t=(0,c.decode)(e);if("object"==typeof t&&null!==t&&t.type){if(["connection_info","ping","pong","reconnection_token","error"].includes(t.type))return t}return null}catch{return null}}async _processMsgpackStream(e){const t=e.body.getReader();let n=new Uint8Array(4096),r=0;for(;!this._closed;){const{done:e,value:o}=await t.read();if(e)break;const i=r+o.length;if(i>n.length){let e=n.length;for(;e<i;)e*=2;const t=new Uint8Array(e);t.set(n.subarray(0,r)),n=t}n.set(o,r),r+=o.length;let s=0;for(;r-s>=4;){const e=n[s]<<24|n[s+1]<<16|n[s+2]<<8|n[s+3];if(r-s<4+e)break;const t=n.slice(s+4,s+4+e);s+=4+e;const o=this._tryDecodeControlMessage(t);if(o){const e=o.type;if("connection_info"===e){this.connection_info=o,this._is_reconnection&&this._handleReconnection(o).catch(e=>{console.error(`Reconnection handling failed: ${e.message}`)});continue}if("ping"===e||"pong"===e)continue;if("reconnection_token"===e){this._reconnection_token=o.reconnection_token;continue}if("error"===e){console.error(`Server error: ${o.message}`);continue}}if(this._handle_message)try{await this._handle_message(t)}catch(e){console.error(`Error in message handler: ${e.message}`)}}if(s>0){const e=r-s;e>0&&n.copyWithin(0,s,r),r=e}}}async _handleReconnection(e){if(this.manager_id=e.manager_id,this._workspace=e.workspace,e.reconnection_token&&(this._reconnection_token=e.reconnection_token),e.reconnection_token_life_time){const t=e.reconnection_token_life_time;this._token_refresh_interval>t/1.5&&(this._token_refresh_interval=t/1.5)}console.warn(`Stream reconnected to workspace: ${this._workspace}, manager_id: ${this.manager_id}`),this._handle_connected&&await this._handle_connected(this.connection_info),await new Promise(e=>setTimeout(e,500))}async emit_message(e){if(this._closed)throw new Error("Connection is closed");const t=this._workspace||"public";let n=`${this._server_url}/${t}/rpc?client_id=${this._client_id}`;const r=e instanceof Uint8Array?e:new Uint8Array(e);for(let e=0;e<3;e++)try{const t=r.length<6e4,o=await fetch(n,{method:"POST",headers:this._get_headers(!1),body:r,...t&&{keepalive:!0}});if(!o.ok){const t=await o.text();if(400===o.status&&e<2){console.warn(`POST failed (attempt ${e+1}/3): ${t}, retrying...`),await new Promise(t=>setTimeout(t,500*(e+1)));continue}throw new Error(`POST failed with status ${o.status}: ${t}`)}return!0}catch(t){if(!(e<2)||this._closed)throw console.error(`Failed to send message: ${t.message}`),t;console.warn(`Failed to send message (attempt ${e+1}/3): ${t.message}, retrying...`),await new Promise(t=>setTimeout(t,500*(e+1)))}}set_reconnection(e){this._enable_reconnect=e}async disconnect(e="client disconnect"){this._closed||(this._closed=!0,this._refresh_token_task&&(clearInterval(this._refresh_token_task),this._refresh_token_task=null),this._abort_controller&&(this._abort_controller.abort(),this._abort_controller=null),this._handle_disconnected&&this._handle_disconnected(e))}}function l(e){if(!e)throw new Error("server_url is required");return e.startsWith("ws://")?e=e.replace("ws://","http://"):e.startsWith("wss://")&&(e=e.replace("wss://","https://")),e.endsWith("/ws")&&(e=e.slice(0,-3)),e.replace(/\/$/,"")}async function d(e){let t=e.clientId||e.client_id;t||(t=(0,o.randId)());const n=l(e.serverUrl||e.server_url),s=new a(n,t,e.workspace,e.token,e.reconnection_token,e.method_timeout||30,e.token_refresh_interval||7200),c=await s.open();(0,o.assert)(c,"Failed to connect to server"),await new Promise(e=>setTimeout(e,100));const d=c.workspace,h=new r.RPC(s,{client_id:t,workspace:d,default_context:{connection_type:"http_streaming"},name:e.name,method_timeout:e.method_timeout,app_id:e.app_id,server_base_url:c.public_base_url});await h.waitFor("services_registered",e.method_timeout||120);const u=await h.get_manager_service({timeout:e.method_timeout||30,case_conversion:"camel"});u.rpc=h,u.disconnect=(0,i.schemaFunction)(h.disconnect.bind(h),{name:"disconnect",description:"Disconnect from server",parameters:{properties:{},type:"object"}}),u.registerService=(0,i.schemaFunction)(h.register_service.bind(h),{name:"registerService",description:"Register a service",parameters:{properties:{service:{description:"Service to register",type:"object"}},required:["service"],type:"object"}});const p=u.getService;return u.getService=async(e,t={})=>await p(e,t),p.__schema__&&(u.getService.__schema__=p.__schema__),u.serve=(0,i.schemaFunction)(async function(){await new Promise(()=>{})},{name:"serve",description:"Run event loop forever",parameters:{type:"object",properties:{}}}),c&&(u.config=Object.assign(u.config||{},c)),s.manager_id&&h.on("force-exit",async e=>{e.from==="*/"+s.manager_id&&(console.info(`Disconnecting from server: ${e.reason}`),await h.disconnect())}),u}async function h(e={}){return await d(e)}async function u(e,t={}){const{serverUrl:n,workspace:r,clientId:i,serviceId:s,appId:c}=(0,o.parseServiceUrl)(e),a=`${r}/${i}:${s}@${c}`;if(t.serverUrl&&t.serverUrl!==n)throw new Error("server_url mismatch");t.serverUrl=n;const l=await h(t);return await l.getService(a)}},"./src/rpc.js":
10
+ \****************************/(e,t,n)=>{n.r(t),n.d(t,{HTTPStreamingRPCConnection:()=>c,_connectToServerHTTP:()=>h,connectToServerHTTP:()=>d,getRemoteServiceHTTP:()=>_,normalizeServerUrl:()=>l});var r=n(/*! ./rpc.js */"./src/rpc.js"),o=n(/*! ./utils/index.js */"./src/utils/index.js"),i=n(/*! ./utils/schema.js */"./src/utils/schema.js"),s=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs"),a=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs");class c{constructor(e,t,n=null,r=null,i=null,s=60,a=7200){(0,o.assert)(e&&t,"server_url and client_id are required"),this._server_url=e.replace(/\/$/,""),this._client_id=t,this._workspace=n,this._token=r,this._reconnection_token=i,this._timeout=s,this._token_refresh_interval=a,!this._workspace&&this._token&&(this._workspace=function(e){if(!e)return null;try{const t=e.split(".");if(3!==t.length)return null;let n=t[1].replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4;)n+="=";const r=JSON.parse(atob(n)).scope;if("string"!=typeof r)return null;const o=r.match(/(?:^|\s)wid:(\S+)/);return o?o[1]:null}catch{return null}}(this._token)),this._handle_message=null,this._handle_disconnected=null,this._handle_connected=null,this._closed=!1,this._enable_reconnect=!1,this._is_reconnection=!1,this.connection_info=null,this.manager_id=null,this._abort_controller=null,this._refresh_token_task=null}on_message(e){(0,o.assert)(e,"handler is required"),this._handle_message=e}on_disconnected(e){this._handle_disconnected=e}on_connected(e){this._handle_connected=e}_get_headers(e=!1){const t={"Content-Type":"application/msgpack"};return e&&(t.Accept="application/x-msgpack-stream"),this._token&&(t.Authorization=`Bearer ${this._token}`),t}async open(){console.info(`Opening HTTP streaming connection to ${this._server_url}`);let e=`${this._server_url}/rpc?client_id=${this._client_id}`;this._workspace&&(e+=`&workspace=${encodeURIComponent(this._workspace)}`),this._startStreamLoop(e);const t=Date.now();for(;null===this.connection_info;){if(await new Promise(e=>setTimeout(e,100)),Date.now()-t>1e3*this._timeout)throw new Error("Timeout waiting for connection info");if(this._closed)throw new Error("Connection closed during setup")}if(this.manager_id=this.connection_info.manager_id,this._workspace){const e=this.connection_info.workspace;if(e!==this._workspace)throw new Error(`Connected to wrong workspace: ${e}, expected: ${this._workspace}`)}if(this._workspace=this.connection_info.workspace,this.connection_info.reconnection_token&&(this._reconnection_token=this.connection_info.reconnection_token),this.connection_info.reconnection_token_life_time){const e=this.connection_info.reconnection_token_life_time;this._token_refresh_interval>e/1.5&&(console.warn(`Token refresh interval (${this._token_refresh_interval}s) is too long, adjusting to ${(e/1.5).toFixed(0)}s based on token lifetime`),this._token_refresh_interval=e/1.5)}return console.info(`HTTP streaming connected to workspace: ${this._workspace}, manager_id: ${this.manager_id}`),this._token_refresh_interval>0&&this._startTokenRefresh(),this._handle_connected&&await this._handle_connected(this.connection_info),this.connection_info}_startTokenRefresh(){this._refresh_token_task&&clearInterval(this._refresh_token_task),setTimeout(()=>{this._sendRefreshToken(),this._refresh_token_task=setInterval(()=>{this._sendRefreshToken()},1e3*this._token_refresh_interval)},2e3)}async _sendRefreshToken(){if(!this._closed)try{let e=`${this._server_url}/rpc?client_id=${this._client_id}`;this._workspace&&(e+=`&workspace=${encodeURIComponent(this._workspace)}`);const t=(0,s.encode)({type:"refresh_token"}),n=await fetch(e,{method:"POST",headers:this._get_headers(!1),body:t});n.ok||console.warn(`Token refresh request failed: ${n.status}`)}catch(e){console.warn(`Failed to send refresh token request: ${e.message}`)}}async _startStreamLoop(e){this._enable_reconnect=!0,this._closed=!1;let t=0;for(this._is_reconnection=!1;!this._closed&&t<1e6;){try{let e=`${this._server_url}/rpc?client_id=${this._client_id}`;this._workspace&&(e+=`&workspace=${encodeURIComponent(this._workspace)}`),this._reconnection_token&&(e+=`&reconnection_token=${encodeURIComponent(this._reconnection_token)}`),this._abort_controller=new AbortController;const n=await fetch(e,{method:"GET",headers:this._get_headers(!0),signal:this._abort_controller.signal});if(!n.ok){const e=await n.text();throw new Error(`Stream failed with status ${n.status}: ${e}`)}t=0,await this._processMsgpackStream(n)}catch(e){if(this._closed)break;if(console.error(`Connection error: ${e.message}`),!this._enable_reconnect)break}if(this._is_reconnection=!0,this._closed||!this._enable_reconnect)break;{t+=1;const e=Math.min(Math.pow(2,Math.min(t,6)),60);console.warn(`Stream disconnected, reconnecting in ${e.toFixed(1)}s (attempt ${t})`),await new Promise(t=>setTimeout(t,1e3*e))}}!this._closed&&this._handle_disconnected&&this._handle_disconnected("Stream ended")}_tryDecodeControlMessage(e){try{const t=(0,a.decode)(e);if("object"==typeof t&&null!==t&&t.type){if(["connection_info","ping","pong","reconnection_token","error"].includes(t.type))return t}return null}catch{return null}}async _processMsgpackStream(e){const t=e.body.getReader();this._reader=t;let n=new Uint8Array(4096),r=0;for(;!this._closed;){let e,o;try{e=await Promise.race([t.read(),new Promise((e,t)=>{o=setTimeout(()=>t(new Error("Stream read timeout (no data for 120s)")),12e4)})]),clearTimeout(o)}catch(e){clearTimeout(o),console.warn(`Stream read error: ${e.message}`);try{t.cancel()}catch{}break}const{done:i,value:s}=e;if(i)break;const a=r+s.length;if(a>n.length){let e=n.length;for(;e<a;)e*=2;const t=new Uint8Array(e);t.set(n.subarray(0,r)),n=t}n.set(s,r),r+=s.length;let c=0;for(;r-c>=4;){const e=n[c]<<24|n[c+1]<<16|n[c+2]<<8|n[c+3];if(r-c<4+e)break;const t=n.slice(c+4,c+4+e);c+=4+e;const o=this._tryDecodeControlMessage(t);if(o){const e=o.type;if("connection_info"===e){this.connection_info=o,this._is_reconnection&&this._handleReconnection(o).catch(e=>{console.error(`Reconnection handling failed: ${e.message}`)});continue}if("ping"===e||"pong"===e)continue;if("reconnection_token"===e){this._reconnection_token=o.reconnection_token;continue}if("error"===e){console.error(`Server error: ${o.message}`);continue}}if(this._handle_message)try{await this._handle_message(t)}catch(e){console.error(`Error in message handler: ${e.message}`)}}if(c>0){const e=r-c;e>0&&n.copyWithin(0,c,r),r=e}}this._reader=null}async _handleReconnection(e){if(this.manager_id=e.manager_id,this._workspace=e.workspace,e.reconnection_token&&(this._reconnection_token=e.reconnection_token),e.reconnection_token_life_time){const t=e.reconnection_token_life_time;this._token_refresh_interval>t/1.5&&(this._token_refresh_interval=t/1.5)}console.warn(`Stream reconnected to workspace: ${this._workspace}, manager_id: ${this.manager_id}`),this._handle_connected&&await this._handle_connected(this.connection_info),await new Promise(e=>setTimeout(e,500))}async emit_message(e){if(this._closed)throw new Error("Connection is closed");if(!this._workspace)throw new Error("Workspace not set - connection not established");let t=`${this._server_url}/rpc?client_id=${this._client_id}&workspace=${encodeURIComponent(this._workspace)}`;const n=e instanceof Uint8Array?e:new Uint8Array(e);for(let e=0;e<3;e++)try{const r=n.length<6e4,o=await fetch(t,{method:"POST",headers:this._get_headers(!1),body:n,...r&&{keepalive:!0}});if(!o.ok){const t=await o.text();if(400===o.status&&e<2){console.warn(`POST failed (attempt ${e+1}/3): ${t}, retrying...`),await new Promise(t=>setTimeout(t,500*(e+1)));continue}throw new Error(`POST failed with status ${o.status}: ${t}`)}return!0}catch(t){if(!(e<2)||this._closed)throw console.error(`Failed to send message: ${t.message}`),t;console.warn(`Failed to send message (attempt ${e+1}/3): ${t.message}, retrying...`),await new Promise(t=>setTimeout(t,500*(e+1)))}}set_reconnection(e){this._enable_reconnect=e}async disconnect(e="client disconnect"){this._closed||(this._closed=!0,this._refresh_token_task&&(clearInterval(this._refresh_token_task),this._refresh_token_task=null),this._abort_controller&&(this._abort_controller.abort(),this._abort_controller=null),this._handle_disconnected&&this._handle_disconnected(e))}}function l(e){if(!e)throw new Error("server_url is required");return e.startsWith("ws://")?e=e.replace("ws://","http://"):e.startsWith("wss://")&&(e=e.replace("wss://","https://")),e.endsWith("/ws")&&(e=e.slice(0,-3)),e.replace(/\/$/,"")}async function h(e){let t=e.clientId||e.client_id;t||(t=(0,o.randId)());const n=l(e.serverUrl||e.server_url),s=new c(n,t,e.workspace,e.token,e.reconnection_token,e.method_timeout||30,e.token_refresh_interval||7200),a=await s.open();(0,o.assert)(a,"Failed to connect to server"),await new Promise(e=>setTimeout(e,100));const h=a.workspace,d=new r.RPC(s,{client_id:t,workspace:h,default_context:{connection_type:"http_streaming"},silent:e.silent||!1,name:e.name,method_timeout:e.method_timeout,app_id:e.app_id,server_base_url:a.public_base_url,encryption:e.encryption||!1,encryption_private_key:e.encryption_private_key||null,encryption_public_key:e.encryption_public_key||null});await d.waitFor("services_registered",e.method_timeout||120);const _=await d.get_manager_service({timeout:e.method_timeout||30,case_conversion:"camel"});_.rpc=d;let u=!0;d.on("manager_refreshed",async()=>{if(u)u=!1;else try{const e=`*/${d._connection.manager_id}`;for(const t of Object.keys(_))"function"==typeof _[t]&&_[t].__rpc_object__&&(_[t].__rpc_object__._rtarget=e);console.info("Workspace manager proxy retargeted after reconnection (new manager_id:",d._connection?.manager_id+")")}catch(e){console.warn("Failed to retarget workspace manager after reconnection:",e)}}),_.disconnect=(0,i.schemaFunction)(d.disconnect.bind(d),{name:"disconnect",description:"Disconnect from server",parameters:{properties:{},type:"object"}}),_.registerService=(0,i.schemaFunction)(d.register_service.bind(d),{name:"registerService",description:"Register a service",parameters:{properties:{service:{description:"Service to register",type:"object"}},required:["service"],type:"object"}});const p=_.getService;return _.getService=async(e,t={})=>await p(e,t),p.__schema__&&(_.getService.__schema__=p.__schema__),_.serve=(0,i.schemaFunction)(async function(){await new Promise(()=>{})},{name:"serve",description:"Run event loop forever",parameters:{type:"object",properties:{}}}),a&&(_.config=Object.assign(_.config||{},a)),s.manager_id&&d.on("force-exit",async e=>{e.from==="*/"+s.manager_id&&(console.info(`Disconnecting from server: ${e.reason}`),await d.disconnect())}),_}async function d(e={}){return await h(e)}async function _(e,t={}){const{serverUrl:n,workspace:r,clientId:i,serviceId:s,appId:a}=(0,o.parseServiceUrl)(e),c=`${r}/${i}:${s}@${a}`;if(t.serverUrl&&t.serverUrl!==n)throw new Error("server_url mismatch");t.serverUrl=n;const l=await d(t);return await l.getService(c)}},"./src/rpc.js":
5
11
  /*!********************!*\
6
12
  !*** ./src/rpc.js ***!
7
- \********************/(e,t,n)=>{n.r(t),n.d(t,{API_VERSION:()=>c,RPC:()=>y});var r=n(/*! ./utils/index.js */"./src/utils/index.js"),o=n(/*! ./utils/schema.js */"./src/utils/schema.js"),i=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs"),s=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs");const c=3,a=Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;function l(e){if(null==e)return!0;const t=typeof e;return"number"===t||"string"===t||"boolean"===t}function d(e){for(let t=0;t<e.length;t++){const n=e[t];if(!l(n)&&!(n instanceof Uint8Array))if(Array.isArray(n)){if(!d(n))return!1}else{if(!n||n.constructor!==Object)return!1;if("_rtype"in n)return!1;if(!h(n))return!1}}return!0}function h(e){const t=Object.values(e);for(let e=0;e<t.length;e++){const n=t[e];if(!l(n)&&!(n instanceof Uint8Array))if(Array.isArray(n)){if(!d(n))return!1}else{if(!n||n.constructor!==Object)return!1;if("_rtype"in n)return!1;if(!h(n))return!1}}return!0}function u(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}function p(e,t,n="Operation timed out"){return new Promise((r,o)=>{const i=setTimeout(()=>{o(new Error(`TimeoutError: ${n}`))},t);e.then(e=>{clearTimeout(i),r(e)}).catch(e=>{clearTimeout(i),o(e)})})}function _(e,t){if(!t)throw new Error("undefined index");return"string"==typeof t?_(e,t.split(".")):0===t.length?e:_(e[t[0]],t.slice(1))}function f(e,t=null,n=!1){if(Array.isArray(e))return e.map((e,t)=>f(e,null,n));if("object"==typeof e&&null!==e){let t={};for(let r in e)t[r]=f(e[r],r,n);return t}if("function"==typeof e){if(e.__schema__){const r=JSON.parse(JSON.stringify(e.__schema__));if(t&&(r.name=t,e.__schema__.name=t),n&&(r.parameters&&r.parameters.properties&&delete r.parameters.properties.context,r.parameters&&r.parameters.required)){const e=r.parameters.required.indexOf("context");e>-1&&r.parameters.required.splice(e,1)}return{type:"function",function:r}}return{type:"function",function:{name:t||e.name||"function"}}}return"number"==typeof e?{type:"number"}:"string"==typeof e?{type:"string"}:"boolean"==typeof e?{type:"boolean"}:null===e?{type:"null"}:{}}class m{constructor(e,t,n,r){this._timeout=e,this._callback=t,this._args=n,this._label=r||"timer",this._task=null,this.started=!1}start(){this.started?this.reset():(this._task=setTimeout(()=>{this._callback.apply(this,this._args)},1e3*this._timeout),this.started=!0)}clear(){this._task&&this.started?(clearTimeout(this._task),this._task=null,this.started=!1):console.warn(`Clearing a timer (${this._label}) which is not started`)}reset(){this._task&&clearTimeout(this._task),this._task=setTimeout(()=>{this._callback.apply(this,this._args)},1e3*this._timeout),this.started=!0}}class g extends Object{}class y extends r.MessageEmitter{constructor(e,{client_id:t=null,default_context:n=null,name:o=null,codecs:i=null,method_timeout:s=null,max_message_buffer_size:a=0,debug:l=!1,workspace:d=null,silent:h=!1,app_id:u=null,server_base_url:_=null,long_message_chunk_size:f=null}){if(super(l),this._codecs=i||{},(0,r.assert)(t&&"string"==typeof t),(0,r.assert)(t,"client_id is required"),this._client_id=t,this._name=o,this._app_id=u||"*",this._local_workspace=d,this._silent=h,this.default_context=n||{},this._method_annotations=new WeakMap,this._max_message_buffer_size=a,this._chunk_store={},this._method_timeout=s||30,this._server_base_url=_,this._long_message_chunk_size=f||262144,this._services={},this._object_store={services:this._services},this._targetIdIndex={},this._background_tasks=new Set,this._sessionMaxAge=6e5,this._sessionSweepInterval=setInterval(()=>{this._sweepStaleSessions()},this._sessionMaxAge/2),this._unhandledRejectionHandler=e=>{const t=e.reason;if(t&&"object"==typeof t){const n=t.toString();if(n.includes("Method not found")||n.includes("Session not found")||n.includes("Method expired")||n.includes("Connection is closed")||n.includes("Client disconnected")||n.includes("RPC connection closed"))return console.debug("Ignoring expected disconnection/method error:",t),void e.preventDefault()}console.warn("Unhandled RPC promise rejection:",t)},this._unhandledRejectionNodeHandler=null,y._rejectionHandlerCount||(y._rejectionHandlerCount=0),y._rejectionHandlerCount++,1===y._rejectionHandlerCount&&("undefined"!=typeof window?window.addEventListener("unhandledrejection",this._unhandledRejectionHandler):"undefined"!=typeof process&&(this._unhandledRejectionNodeHandler=(e,t)=>{this._unhandledRejectionHandler({reason:e,promise:t,preventDefault:()=>{}})},process.on("unhandledRejection",this._unhandledRejectionNodeHandler))),e){this.add_service({id:"built-in",type:"built-in",name:`Built-in services for ${this._local_workspace}/${this._client_id}`,config:{require_context:!0,visibility:"public",api_version:c},ping:this._ping.bind(this),get_service:this.get_local_service.bind(this),message_cache:{create:this._create_message.bind(this),append:this._append_message.bind(this),set:this._set_message.bind(this),process:this._process_message.bind(this),remove:this._remove_message.bind(this)}}),this._boundHandleMethod=this._handle_method.bind(this),this._boundHandleError=console.error,this.on("method",this._boundHandleMethod),this.on("error",this._boundHandleError),(0,r.assert)(e.emit_message&&e.on_message),(0,r.assert)(void 0!==e.manager_id,"Connection must have manager_id"),this._emit_message=e.emit_message.bind(e),e.on_message(this._on_message.bind(this)),this._connection=e;const t=async e=>{if(!this._silent&&this._connection.manager_id){console.debug("Connection established, reporting services...");try{const e=await this.get_manager_service({timeout:20,case_conversion:"camel"}),t=Object.values(this._services),n=t.length;let r=0;const o=[],i=this._method_timeout||3e4;for(let n of t)try{const t=this._extract_service_info(n);await p(e.registerService(t),i,`Timeout registering service ${n.id||"unknown"}`),r++,console.debug(`Successfully registered service: ${n.id||"unknown"}`)}catch(e){o.push(n.id||"unknown"),e.message&&e.message.includes("TimeoutError")?console.error(`Timeout registering service ${n.id||"unknown"}`):console.error(`Failed to register service ${n.id||"unknown"}: ${e}`)}r===n?console.info(`Successfully registered all ${r} services with the server`):console.warn(`Only registered ${r} out of ${n} services with the server. Failed services: ${o.join(", ")}`),this._fire("services_registered",{total:n,registered:r,failed:o});try{if(e.subscribe&&"function"==typeof e.subscribe){console.debug("Subscribing to client_disconnected events");const t=async e=>{const t=e.data?.id||e.client,n=e.data?.workspace;if(t&&n){const e=`${n}/${t}`;console.debug(`Client ${e} disconnected, cleaning up sessions`),await this._handleClientDisconnected(e)}else t&&(console.debug(`Client ${t} disconnected, cleaning up sessions`),await this._handleClientDisconnected(t))};this._clientDisconnectedSubscription=await p(e.subscribe(["client_disconnected"]),i,"Timeout subscribing to client_disconnected events"),this.on("client_disconnected",t),console.debug("Successfully subscribed to client_disconnected events")}else console.debug("Manager does not support subscribe method, skipping client_disconnected handling"),this._clientDisconnectedSubscription=null}catch(e){console.debug(`Failed to subscribe to client_disconnected events: ${e}`),this._clientDisconnectedSubscription=null}}catch(e){console.error(`Failed to get manager service for registering services: ${e}`),this._fire("services_registration_failed",{error:e.toString(),total_services:Object.keys(this._services).length})}}e&&(e.public_base_url&&(this._server_base_url=e.public_base_url),this._fire("connected",e))};e.on_connected(t),"function"==typeof e.on_disconnected&&e.on_disconnected(t=>{e._enable_reconnect?console.info(`Connection lost (${t}), reconnection enabled - pending calls will be handled by timeout`):(console.warn(`Connection lost (${t}), rejecting all pending RPC calls`),this._rejectPendingCalls(`Connection lost: ${t||"unknown reason"}`))}),t()}else this._emit_message=function(){console.log("No connection to emit message")}}register_codec(e){if(!e.name||!e.encoder&&!e.decoder)throw new Error("Invalid codec format, please make sure you provide a name, type, encoder and decoder.");if(e.type)for(let t of Object.keys(this._codecs))this._codecs[t].type!==e.type&&t!==e.name||(delete this._codecs[t],console.warn("Remove duplicated codec: "+t));this._codecs[e.name]=e}async _ping(e,t){return(0,r.assert)("ping"==e),"pong"}async ping(e,t){let n=this._generate_remote_method({_rserver:this._server_base_url,_rtarget:e,_rmethod:"services.built-in.ping",_rpromise:!0,_rdoc:"Ping a remote client"});(0,r.assert)("pong"==await n("ping",t))}_create_message(e,t,n,r){if(t){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}this._object_store.message_cache||(this._object_store.message_cache={});const o=this._object_store.message_cache,i=Object.keys(o);if(i.length>=256){const e=Date.now();for(const t of i){const n=o[t];n&&n._cache_created_at&&e-n._cache_created_at>3e5&&delete o[t]}const t=Object.keys(o);t.length>=256&&t.sort((e,t)=>(o[e]._cache_created_at||0)-(o[t]._cache_created_at||0)).slice(0,t.length-256+1).forEach(e=>delete o[e])}if(!n&&o[e])throw new Error(`Message with the same key (${e}) already exists in the cache store, please use overwrite=true or remove it first.`);o[e]=[],o[e]._cache_created_at=Date.now()}_append_message(e,t,n,o){if(n){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}const i=this._object_store.message_cache;if(!i[e])throw new Error(`Message with key ${e} does not exists.`);(0,r.assert)(t instanceof a),i[e].push(t)}_set_message(e,t,n,o,i){if(o){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}const s=this._object_store.message_cache;if(!s[e])throw new Error(`Message with key ${e} does not exists.`);(0,r.assert)(n instanceof a),s[e][t]=n}_remove_message(e,t){const n=this._object_store.message_cache;if(!n[e])throw new Error(`Message with key ${e} does not exists.`);delete n[e]}_process_message(e,t,n){if(t){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}const o=this._object_store.message_cache;if((0,r.assert)(!!n,"Context is required"),!o[e])throw new Error(`Message with key ${e} does not exists.`);var s,c,a,l;o[e]=(s=o[e],c=s.map(function(e){return e.byteLength}),a=c.reduce(function(e,t){return e+t},0),l=new Uint8Array(a),c.reduce(function(e,t,n){return l.set(new Uint8Array(s[n]),e),e+t},0),l.buffer);let d=(0,i.decodeMulti)(o[e]);const{done:h,value:u}=d.next(),p=u;if(Object.assign(p,{from:n.from,to:n.to,ws:n.ws,user:n.user}),p.ctx=JSON.parse(JSON.stringify(p)),Object.assign(p.ctx,this.default_context),!h){let e=d.next();Object.assign(p,e.value)}this._fire(p.type,p),delete o[e]}_on_message(e){if("string"==typeof e){const t=JSON.parse(e);t.ctx=Object.assign({},t,this.default_context),this._fire(t.type,t)}else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){let t=(0,i.decodeMulti)(e);const{done:n,value:r}=t.next(),o=r;if(o.ctx=Object.assign({},o,this.default_context),!n){let e=t.next();Object.assign(o,e.value)}this._fire(o.type,o)}else{if("object"!=typeof e)throw new Error("Invalid message format");e.ctx=Object.assign({},e,this.default_context),this._fire(e.type,e)}}reset(){this._removeRejectionHandler(),this._event_handlers={},this._services={}}_removeRejectionHandler(){y._rejectionHandlerCount&&y._rejectionHandlerCount>0&&(y._rejectionHandlerCount--,0===y._rejectionHandlerCount&&("undefined"!=typeof window&&this._unhandledRejectionHandler?window.removeEventListener("unhandledrejection",this._unhandledRejectionHandler):"undefined"!=typeof process&&this._unhandledRejectionNodeHandler&&process.removeListener("unhandledRejection",this._unhandledRejectionNodeHandler))),this._unhandledRejectionHandler=null,this._unhandledRejectionNodeHandler=null}close(){if(this._cleanupOnDisconnect(),this._boundHandleMethod&&(this.off("method",this._boundHandleMethod),this._boundHandleMethod=null),this._boundHandleError&&(this.off("error",this._boundHandleError),this._boundHandleError=null),this._clientDisconnectedSubscription){try{"function"==typeof this._clientDisconnectedSubscription.unsubscribe&&this._clientDisconnectedSubscription.unsubscribe()}catch(e){console.debug(`Error unsubscribing client_disconnected: ${e}`)}this.off("client_disconnected"),this._clientDisconnectedSubscription=null}this._removeRejectionHandler(),this.off();try{for(const e of this._background_tasks)if(e&&"function"==typeof e.cancel)try{e.cancel()}catch(e){console.debug(`Error canceling background task: ${e}`)}this._background_tasks.clear()}catch(e){console.debug(`Error cleaning up background tasks: ${e}`)}this._sessionSweepInterval&&(clearInterval(this._sessionSweepInterval),this._sessionSweepInterval=null);try{this._connection=null,this._emit_message=function(){return console.debug("RPC connection closed, ignoring message"),Promise.reject(new Error("Connection is closed"))}}catch(e){console.debug(`Error during connection cleanup: ${e}`)}this._fire("disconnected")}async _handleClientDisconnected(e){try{console.debug(`Handling disconnection for client: ${e}`);const t=this._cleanupSessionsForClient(e);t>0&&console.debug(`Cleaned up ${t} sessions for disconnected client: ${e}`),this._fire("remote_client_disconnected",{client_id:e,sessions_cleaned:t})}catch(t){console.error(`Error handling client disconnection for ${e}: ${t}`)}}_removeFromTargetIdIndex(e){const t=e.split(".")[0],n=this._object_store[t];if(n&&"object"==typeof n){const e=n.target_id;e&&e in this._targetIdIndex&&(this._targetIdIndex[e].delete(t),0===this._targetIdIndex[e].size&&delete this._targetIdIndex[e])}}_cleanupSessionEntry(e,t=null){if(e&&"object"==typeof e){if(t&&e.reject&&"function"==typeof e.reject)try{e.reject(new Error(t))}catch(e){console.debug(`Error rejecting session: ${e}`)}if(e.heartbeat_task)try{clearInterval(e.heartbeat_task)}catch(e){}if(e.timer&&e.timer.started&&"function"==typeof e.timer.clear)try{e.timer.clear()}catch(e){}}}_cleanupSessionsForClient(e){let t=0;const n=this._targetIdIndex[e];if(!n)return 0;const r=`Client disconnected: ${e}`;for(const o of n){const n=this._object_store[o];n&&"object"==typeof n&&(n.target_id===e&&(this._cleanupSessionEntry(n,r),delete this._object_store[o],t++,console.debug(`Cleaned up session: ${o}`)))}return delete this._targetIdIndex[e],t}_rejectPendingCalls(e="Connection lost"){try{let t=0;for(const n of Object.keys(this._object_store)){if("services"===n||"message_cache"===n)continue;const r=this._object_store[n];"object"==typeof r&&null!==r&&(r.reject&&"function"==typeof r.reject&&t++,this._cleanupSessionEntry(r,e))}t>0&&console.warn(`Rejected ${t} pending RPC call(s) due to: ${e}`)}catch(e){console.error(`Error rejecting pending calls: ${e}`)}}_cleanupOnDisconnect(){try{console.debug("Cleaning up all sessions due to local RPC disconnection");const e=[];for(const t of Object.keys(this._object_store)){if("services"===t||"message_cache"===t)continue;const n=this._object_store[t];this._cleanupSessionEntry(n,"RPC connection closed"),e.push(t)}for(const t of e)delete this._object_store[t];this._targetIdIndex={}}catch(e){console.error(`Error during cleanup on disconnect: ${e}`)}}async disconnect(){const e=this._connection;if(this.close(),e)try{await e.disconnect()}catch(e){console.debug(`Error disconnecting underlying connection: ${e}`)}}async get_manager_service(e,t=20){e=e||{};let n=null;for(let r=0;r<t;r++){const o=Math.min(500*Math.pow(2,r),1e4);if(!this._connection.manager_id){if(r<t-1){console.warn(`Manager ID not set, retrying in ${o}ms (attempt ${r+1}/${t})`),await new Promise(e=>setTimeout(e,o));continue}throw new Error("Manager ID not set after maximum retries")}try{return await this.get_remote_service(`*/${this._connection.manager_id}:default`,e)}catch(e){n=e,console.warn(`Failed to get manager service (attempt ${r+1}/${t}): ${e.message}`),r<t-1&&await new Promise(e=>setTimeout(e,o))}}throw n}get_all_local_services(){return this._services}get_local_service(e,t){(0,r.assert)(e),(0,r.assert)(t,"Context is required");const[n,o]=t.to.split("/");(0,r.assert)(o===this._client_id,"Services can only be accessed locally");const i=this._services[e];if(!i)throw new Error("Service not found: "+e);if("public"==i.config.visibility||"unlisted"==i.config.visibility)return i;if(t.ws===n)return i;const s=i.config.authorized_workspaces;if(s&&s.includes(t.ws))return i;throw new Error(`Permission denied for getting protected service: ${e}, workspace mismatch: ${n} != ${t.ws}`)}async get_remote_service(e,t){let{timeout:n,case_conversion:o,kwargs_expansion:i}=t||{};n=void 0===n?this._method_timeout:n,!e&&this._connection.manager_id?e="*/"+this._connection.manager_id:e.includes(":")||(e=this._client_id+":"+e);const s=e.split(":")[0];let c=e.split(":")[1];if(c.includes("@")){c=c.split("@")[0];const t=e.split("@")[1];this._app_id&&"*"!==this._app_id&&(0,r.assert)(t===this._app_id,`Invalid app id: ${t} != ${this._app_id}`)}(0,r.assert)(s,`Invalid service uri: ${e}`);try{const t=this._generate_remote_method({_rserver:this._server_base_url,_rtarget:s,_rmethod:"services.built-in.get_service",_rpromise:!0,_rdoc:"Get a remote service"});let a=await(0,r.waitFor)(t(c),n,"Timeout Error: Failed to get remote service: "+e);return a.id=`${s}:${c}`,i&&(a=(0,r.expandKwargs)(a)),o?Object.assign(new g,(0,r.convertCase)(a,o)):Object.assign(new g,a)}catch(t){throw console.warn("Failed to get remote service: "+e,t),t}}_annotate_service_methods(e,t,n,r,o,i){if("function"==typeof e){let s=t.split(".")[1];this._method_annotations.set(e,{require_context:Array.isArray(n)?n.includes(s):!!n,run_in_executor:r,method_id:"services."+t,visibility:o,authorized_workspaces:i})}else if(e instanceof Array||e instanceof Object)for(let s of Object.keys(e)){let c=e[s];if("function"==typeof c&&c.__rpc_object__){let t=c.__rpc_object__._rtarget;if(t.includes("/")&&(t=t.split("/")[1]),this._client_id!==t)throw new Error(`Local method not found: ${c.__rpc_object__._rmethod}, client id mismatch ${this._client_id} != ${t}`);e instanceof Array&&(e=e.slice()),e[s]=_(this._object_store,c.__rpc_object__._rmethod),c=e[s]}this._annotate_service_methods(c,t+"."+s,n,r,o,i)}}add_service(e,t){if(!e||Array.isArray(e))throw new Error("Invalid service object");if(e.constructor===Object)e=Object.assign({},e);else{const t={},n=Object.getOwnPropertyNames(e).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(e)));for(let r of n)"constructor"!==r&&("function"==typeof e[r]?t[r]=e[r].bind(e):t[r]=e[r]);e.id=e.id||"default",e=t}(0,r.assert)(e.id&&"string"==typeof e.id,`Service id not found: ${e}`),e.name||(e.name=e.id),e.config||(e.config={}),e.type||(e.type="generic");let n=!1,o=!1;e.config.require_context&&(n=e.config.require_context),e.config.run_in_executor&&(o=!0);const i=e.config.visibility||"protected";(0,r.assert)(["protected","public","unlisted"].includes(i));const s=e.config.authorized_workspaces;if(void 0!==s){if("protected"!==i)throw new Error(`authorized_workspaces can only be set when visibility is 'protected', got visibility='${i}'`);if(!Array.isArray(s))throw new Error("authorized_workspaces must be an array of workspace ids");for(const e of s)if("string"!=typeof e)throw new Error("Each workspace id in authorized_workspaces must be a string, got "+typeof e)}if(this._annotate_service_methods(e,e.id,n,o,i,s),this._services[e.id]){if(!t)throw new Error(`Service already exists: ${e.id}, please specify a different id (not ${e.id}) or overwrite=true`);delete this._services[e.id]}return this._services[e.id]=e,e}_extract_service_info(e){const t=e.config||{};if(t.workspace=t.workspace||this._local_workspace||this._connection.workspace,!t.workspace)throw new Error("Workspace is not set. Please ensure the connection has a workspace or set local_workspace.");const n=t.require_context,r=["id","config","name","description","type","docs","app_id","service_schema"],o={};for(const t of Object.keys(e))r.includes(t)||(o[t]=e[t]);const i=f(o,null,n);return{config:t,id:`${t.workspace}/${this._client_id}:${e.id}`,name:e.name||e.id,description:e.description||"",type:e.type||"generic",docs:e.docs||null,app_id:this._app_id,service_schema:i}}async get_service_schema(e){return f(e,null,e.config.require_context)}async register_service(e,t){let n,{check_type:r,notify:i,overwrite:s}=t||{};if(i=void 0===i||i,r&&e.type)try{n=await this.get_manager_service({timeout:10,case_conversion:"camel"});e=function(e,t){function n(e,t,n="root"){for(let r in t)if(!e.hasOwnProperty(r))throw new Error(`Missing key '${r}' in service at path '${n}'`);for(let r in e)if("type"!==r&&!t.hasOwnProperty(r))throw new Error(`Unexpected key '${r}' in service at path '${n}'`)}return n(e,t.definition),function e(t,r,i="root"){if("object"!=typeof t||Array.isArray(t)){if(Array.isArray(t)){if(t.length!==r.length)throw new Error(`Length mismatch at path '${i}'`);t.forEach((n,s)=>{let c=`${i}[${s}]`;if("object"!=typeof n||Array.isArray(n)){if("function"==typeof n){if(!r.hasOwnProperty(s))throw new Error(`Missing schema for function at index ${s} in path '${c}'`);t[s]=(0,o.schemaFunction)(n,{name:r[s].name,description:r[s].description||"",parameters:r[s].parameters})}}else e(n,r[s],c)})}}else{n(t,r,i);for(let n in t){let s=t[n],c=`${i}.${n}`;if("object"!=typeof s||Array.isArray(s)){if("function"==typeof s){if(!r.hasOwnProperty(n))throw new Error(`Missing schema for function '${n}' at path '${c}'`);t[n]=(0,o.schemaFunction)(s,{name:r[n].name,description:r[n].description||"",parameters:r[n].parameters})}}else e(s,r[n],c)}}}(e,t.definition),e}(e,await n.get_service_type(e.type))}catch(t){throw new Error(`Failed to get service type ${e.type}, error: ${t}`)}const c=this.add_service(e,s),a=this._extract_service_info(c);if(i)try{n=n||await this.get_manager_service({timeout:10,case_conversion:"camel"}),await n.registerService(a)}catch(e){throw new Error(`Failed to notify workspace manager: ${e}`)}return a}async unregister_service(e,t){let n;if(t=void 0===t||t,n="string"==typeof e?e:e.id,(0,r.assert)(n&&"string"==typeof n,`Invalid service id: ${n}`),n.includes(":")&&(n=n.split(":")[1]),n.includes("@")&&(n=n.split("@")[0]),!this._services[n])throw new Error(`Service not found: ${n}`);if(n.startsWith("_rintf_")&&(t=!1),t){const e=await this.get_manager_service({timeout:10,case_conversion:"camel"});await e.unregisterService(n)}delete this._services[n]}_ndarray(e,t,n){const o=(0,r.typedArrayToDtype)(e);if(n&&n!==o)throw"dtype doesn't match the type of the array: "+o+" != "+n;return t=t||[e.length],{_rtype:"ndarray",_rvalue:e.buffer,_rshape:t,_rdtype:o}}_encode_callback(e,t,n,r,o,i,s){let c=`${n}.${e}`,a={_rtype:"method",_rtarget:i?`${i}/${this._client_id}`:this._client_id,_rmethod:c,_rpromise:!1};const l=this;let d=function(){try{t.apply(null,Array.prototype.slice.call(arguments))}catch(e){console.error(`Error in callback(${c}, ${s}): ${e}`)}finally{o&&o.started&&o.clear(),r&&l._object_store[n]&&("resolve"===e||"reject"===e?(l._removeFromTargetIdIndex(n),delete l._object_store[n]):l._cleanup_session_if_needed(n,e))}};return d.__name__=`callback(${c})`,[a,d]}_cleanup_session_if_needed(e,t){if(e)try{const n=this._get_session_store(e,!1);if(!n)return void console.debug(`Session ${e} not found for cleanup`);let r=!1;if(n._promise_manager)try{const o=n._promise_manager;o.should_cleanup_on_callback&&o.should_cleanup_on_callback(t)&&(o.settle&&o.settle(),r=!0,console.debug(`Promise session ${e} settled and marked for cleanup`))}catch(t){console.warn(`Error in promise manager cleanup for session ${e}:`,t)}else("resolve"===t||"reject"===t)&&n._callbacks&&Object.keys(n._callbacks).includes(t)&&(r=!0,console.debug(`Regular session ${e} marked for cleanup after ${t}`));r&&this._cleanup_session_completely(e)}catch(t){console.warn(`Error during session cleanup for ${e}:`,t)}else console.debug("Cannot cleanup session: session_id is empty")}_cleanup_session_completely(e){try{this._removeFromTargetIdIndex(e);const t=this._get_session_store(e,!1);if(!t)return void console.debug(`Session ${e} already cleaned up`);if(t.timer&&t.timer.started&&"function"==typeof t.timer.clear)try{t.timer.clear()}catch(t){console.warn(`Error clearing timer for session ${e}:`,t)}if(t.heartbeat_task&&"function"==typeof t.heartbeat_task.cancel)try{t.heartbeat_task.cancel()}catch(t){console.warn(`Error canceling heartbeat for session ${e}:`,t)}const n=e.split(".");let r=this._object_store;for(let t=0;t<n.length-1;t++){const o=n[t];if(!r[o])return void console.debug(`Session path ${e} not found at level ${o}`);r=r[o]}const o=n[n.length-1];r[o]&&(delete r[o],console.debug(`Cleaned up session ${e}`),this._cleanup_empty_containers(n.slice(0,-1)))}catch(t){console.warn(`Error in complete session cleanup for ${e}:`,t)}}_cleanup_empty_containers(e){try{for(let t=e.length-1;t>=0;t--){let n=this._object_store;for(let r=0;r<t;r++)if(n=n[e[r]],!n)return;const r=e[t],o=n[r];if(!o||"object"!=typeof o||0!==Object.keys(o).length)break;delete n[r],console.debug(`Cleaned up empty container at depth ${t}: ${e.slice(0,t+1).join(".")}`)}}catch(e){console.warn("Error cleaning up empty containers:",e)}}get_session_stats(){const e={total_sessions:0,promise_sessions:0,regular_sessions:0,sessions_with_timers:0,sessions_with_heartbeat:0,system_stores:{},session_ids:[],memory_usage:0};if(!this._object_store)return e;for(const t in this._object_store){const n=this._object_store[t];if(["services","message_cache"].includes(t))e.system_stores[t]={size:"object"==typeof n&&n?Object.keys(n).length:0};else if(n&&"object"==typeof n){Object.keys(n).length>0&&(e.total_sessions++,e.session_ids.push(t),n._promise_manager?e.promise_sessions++:e.regular_sessions++,(n._timer||n.timer)&&e.sessions_with_timers++,(n._heartbeat||n.heartbeat)&&e.sessions_with_heartbeat++,e.memory_usage+=JSON.stringify(n).length)}}return e}_force_cleanup_all_sessions(){if(!this._object_store)return void console.debug("Force cleaning up 0 sessions");let e=0;const t=[];for(const n in this._object_store)if(!["services","message_cache"].includes(n)){const r=this._object_store[n];r&&"object"==typeof r&&Object.keys(r).length>0&&(t.push(n),e++)}for(const e of t)delete this._object_store[e];this._targetIdIndex={},console.debug(`Force cleaning up ${e} sessions`)}_sweepStaleSessions(){const e=Date.now();let t=0;for(const n of Object.keys(this._object_store)){if("services"===n||"message_cache"===n)continue;const r=this._object_store[n],o=r&&(r._last_activity_at||r._created_at);if(r&&"object"==typeof r&&o&&e-o>this._sessionMaxAge&&(!r.timer||!r.timer.started)){if("function"==typeof r.resolve||"function"==typeof r.reject)continue;this._removeFromTargetIdIndex(n),r.heartbeat_task&&clearInterval(r.heartbeat_task),delete this._object_store[n],t++}}t>0&&console.debug(`Swept ${t} stale session(s)`)}_is_promise_method_call(e){const t=e.split(".")[0],n=this._get_session_store(t,!1);return n&&n._promise_manager}_create_promise_manager(){return{should_cleanup_on_callback:e=>["resolve","reject"].includes(e),settle:()=>{console.debug("Promise settled")}}}async _encode_promise(e,t,n,r,o,i,s){let c=this._get_session_store(n,!0);c||(console.warn(`Failed to create session store ${n}, session management may be impaired`),c={}),c._promise_manager=this._create_promise_manager();let a={};return o&&t&&this._method_timeout?([a.heartbeat,c.heartbeat]=this._encode_callback("heartbeat",o.reset.bind(o),n,!1,null,i),c.timer=o,a.interval=this._method_timeout/2):o=null,[a.resolve,c.resolve]=this._encode_callback("resolve",e,n,r,o,i,`resolve (${s})`),[a.reject,c.reject]=this._encode_callback("reject",t,n,r,o,i,`reject (${s})`),a}async _send_chunks(e,t,n){const o=await this.get_remote_service(`${t}:built-in`);if(!o.message_cache)throw new Error("Remote client does not support message caching for large messages.");const i=o.message_cache,s=n||(0,r.randId)(),c=e.length,a=Date.now(),l=Math.ceil(c/this._long_message_chunk_size);if(o.config.api_version>=3){await i.create(s,!!n);const t=new r.Semaphore(30),o=[];for(let r=0;r<l;r++){const c=r*this._long_message_chunk_size,a=e.slice(c,c+this._long_message_chunk_size),l=async()=>{await i.set(s,r,a,!!n)};o.push(t.run(l))}try{await Promise.all(o)}catch(e){try{await i.remove(s)}catch(e){console.error(`Failed to clean up message cache after error: ${e}`)}throw e}}else{await i.create(s,!!n);for(let t=0;t<l;t++){const r=t*this._long_message_chunk_size,o=e.slice(r,r+this._long_message_chunk_size);await i.append(s,o,!!n)}}await i.process(s,!!n),((Date.now()-a)/1e3).toFixed(2)}emit(e,t){if((0,r.assert)("object"==typeof e&&e.type,"Invalid message, must be an object with a `type` fields."),!e.to)return void this._fire(e.type,e);let n=(0,s.encode)(e);if(t){const e=(0,s.encode)(t),r=new Uint8Array(n.length+e.length);r.set(n),r.set(e,n.length),n=r}const o=n.length;return o>this._long_message_chunk_size+1024&&console.warn(`Sending large message (size=${o})`),this._emit_message(n)}_generate_remote_method(e,t,n,o,i){let c=e._rtarget;o&&!c.includes("/")&&(c.startsWith("*/")||(o!==c&&(c=o+"/"+c),e._rtarget=c));let a=e._rmethod,l=e._rpromise||!1;const d=`method: ${a}, docs: ${e._rdoc}`,h=this;function u(){return new Promise(async(e,o)=>{try{let p=(0,r.randId)();n&&(p=n+"."+p);let _=h._get_session_store(p,!0);if(!_)return void o(new Error(`Runtime Error: Failed to get session store ${p} (context: ${d})`));_.target_id=c;const f=p.split(".")[0];c in h._targetIdIndex||(h._targetIdIndex[c]=new Set),h._targetIdIndex[c].add(f);const g=await h._encode(Array.prototype.slice.call(arguments),p,i),y=g.length,w=y>0&&"object"==typeof g[y-1]&&null!==g[y-1]&&g[y-1]._rkwargs;let b;w&&delete g[y-1]._rkwargs,b=h._local_workspace?h._local_workspace+"/"+h._client_id:h._client_id;let v={type:"method",from:b,to:c,method:a},E={};g&&(E.args=g),w&&(E.with_kwargs=w),t&&(v.parent=t);let k=null;if(l){v.session=p;let t=`${c}:${a}`;const n=function(e){o(new Error(e)),h._object_store[p]&&(h._removeFromTargetIdIndex(p),delete h._object_store[p],console.debug(`Cleaned up session ${p} after timeout`))};k=new m(h._method_timeout,n,[`Method call timed out: ${t}, context: ${d}`],t);let r=!0;const s=await h._encode_promise(e,o,p,r,k,i,d);if(!0===l)E.promise=s;else{if("*"!==l)throw new Error(`Unsupported promise type: ${l}`);E.promise="*",E.t=h._method_timeout/2}}let x=(0,s.encode)(v);if(E){const e=(0,s.encode)(E),t=new Uint8Array(x.length+e.length);t.set(x),t.set(e,x.length),x=t}x.length<=h._long_message_chunk_size+1024||u.__no_chunk__?h._emit_message(x).then(function(){k&&k.start(),l||e(null)}).catch(function(e){const t=`Failed to send the request when calling method (${c}:${a}), error: ${e}`;o?o(new Error(t)):console.warn("Unhandled RPC method call error:",t),k&&k.started&&k.clear()}):h._send_chunks(x,c,t).then(function(){k&&k.start(),l||e(null)}).catch(function(e){const t=`Failed to send the request when calling method (${c}:${a}), error: ${e}`;o?o(new Error(t)):console.warn("Unhandled RPC method call error:",t),k&&k.started&&k.clear()})}catch(e){o(e)}})}u.__rpc_object__=e;const p=a.split(".");return u.__name__=e._rname||p[p.length-1],u.__name__.includes("#")&&(u.__name__=u.__name__.split("#")[1]),u.__doc__=e._rdoc||`Remote method: ${a}`,u.__schema__=e._rschema,u.__no_chunk__="services.built-in.message_cache.append"===e._rmethod,u}get_client_info(){const e=[];for(let t of Object.values(this._services))e.push(this._extract_service_info(t));return{id:this._client_id,services:e}}async _handle_method(e){let t=null,n=null,o=null;try{(0,r.assert)(e.method&&e.ctx&&e.from);const i=e.from+":"+e.method,s=e.from.split("/")[0],c=e.from.split("/")[1];let a;e.to=e.to.includes("/")?e.to:s+"/"+e.to,e.ctx.to=e.to,this._local_workspace?(this._local_workspace&&"*"!==this._local_workspace&&(0,r.assert)(e.to.split("/")[0]===this._local_workspace,"Workspace mismatch: "+e.to.split("/")[0]+" != "+this._local_workspace),a=this._local_workspace):a=e.to.split("/")[0];const l=e.parent;if(e.promise){const u=await this._decode("*"===e.promise?this._expand_promise(e):e.promise,e.session,l,s,a);if(t=u.resolve,n=u.reject,u.heartbeat&&u.interval){async function p(){try{await u.heartbeat()}catch(e){console.error(e)}}if(o=setInterval(p,1e3*u.interval),e.session){const f=this._get_session_store(e.session,!1);f&&(f.heartbeat_task=o)}}}let d,h;try{d=_(this._object_store,e.method);const m=e.method.split(".");if(m.length>1){const g=m[0];if("services"!==g&&"message_cache"!==g){const y=this._object_store[g];y&&"object"==typeof y&&(y._last_activity_at=Date.now())}}}catch(w){if(this._is_promise_method_call(e.method))return void console.debug(`Promise method ${e.method} not available (detected by session type), ignoring: ${i}`);const b=e.method.split(".");if(b.length>1){const E=b[0];return E in this._object_store?(console.debug(`Session ${E} exists but method ${e.method} not found, likely expired callback: ${i}`),void("function"==typeof n&&n(new Error(`Method expired or not found: ${i}`)))):(console.debug(`Session ${E} not found for method ${e.method}, likely cleaned up: ${i}`),void("function"==typeof n&&n(new Error(`Session not found: ${i}`))))}console.debug(`Failed to find method ${i} at ${this._client_id}`);const v=new Error(`Method not found: ${i} at ${this._client_id}`);return void("function"==typeof n?n(v):console.warn("Method not found and no reject callback:",v.message))}if((0,r.assert)(d&&"function"==typeof d,"Invalid method: "+i),this._method_annotations.has(d)){if("protected"===this._method_annotations.get(d).visibility)if(a===s);else if(this._method_annotations.get(d).authorized_workspaces&&this._method_annotations.get(d).authorized_workspaces.includes(s));else if("*"!==s||c!==this._connection.manager_id)throw new Error("Permission denied for invoking protected method "+i+", workspace mismatch: "+a+" != "+s)}else{let k=this._object_store[e.method.split(".")[0]].target_id;if(a===s&&k&&-1===k.indexOf("/")&&(k=a+"/"+k),k!==e.from)throw new Error("Access denied for method call ("+i+") from "+e.from+" to target "+k)}if(l&&!e.method.startsWith("services.")&&(0,r.assert)(null!==this._get_session_store(l,!0),"Parent session was closed: "+l),h=e.args?await this._decode(e.args,e.session,null,s,null):[],this._method_annotations.has(d)&&this._method_annotations.get(d).require_context){if(h.length+1<d.length)for(let x=h.length;x<d.length-1;x++)h.push(void 0);h.push(e.ctx)}if(e.promise){const S=d.apply(null,h);S instanceof Promise?S.then(e=>{t(e)}).catch(e=>{n(e)}).finally(()=>{clearInterval(o)}):(t(S),clearInterval(o))}else d.apply(null,h),clearInterval(o)}catch(T){n?n(T):console.error("Error during calling method: ",T),clearInterval(o)}}encode(e,t){return this._encode(e,t)}_get_session_store(e,t){if(!e)return null;let n=this._object_store;const r=e.split(".");if(t){const e=r.length-1;for(let t of r.slice(0,e))n[t]||(n[t]={}),n=n[t];if(!n[r[e]]){n[r[e]]={};const t=Date.now();n[r[e]]._created_at=t,n[r[e]]._last_activity_at=t}return n[r[e]]}for(let e of r){if(!n[e])return null;n=n[e]}return n}async _encode(e,t,n){const o=typeof e;if("number"===o||"string"===o||"boolean"===o||null==e||e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return{_rtype:"memoryview",_rvalue:new Uint8Array(e)};if(e.__rpc_object__){if((e.__rpc_object__._rserver||this._server_base_url)===this._server_base_url)return e.__rpc_object__}let i;if(e.constructor instanceof Object&&e._rtype){const c=e._rtype;return delete e._rtype,i=await this._encode(e,t,n),i._rtype=c,i}if((0,r.isGenerator)(e)||(0,r.isAsyncGenerator)(e)||(0,r.isAsyncIterator)(e)||(0,r.isSyncIterator)(e)){(0,r.assert)(t&&"string"==typeof t,"Session ID is required for generator encoding");const l=(0,r.randId)(),u=l+":close",p=this._get_session_store(t,!0);(0,r.assert)(null!==p,`Failed to create session store ${t} due to invalid parent`);const _=(0,r.isAsyncGenerator)(e)||(0,r.isAsyncIterator)(e),f=async()=>{if(_){const t=await e.next();return t.done?(delete p[l],delete p[u],{_rtype:"stop_iteration"}):t.value}{const t=e.next();return t.done?(delete p[l],delete p[u],{_rtype:"stop_iteration"}):t.value}},m=async()=>{try{"function"==typeof e.return&&(_?await e.return():e.return())}catch(e){}finally{delete p[l],delete p[u]}return!0};return p[l]=f,p[u]=m,i={_rtype:"generator",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:`${t}.${l}`,_rclose_method:`${t}.${u}`,_rpromise:"*",_rdoc:"Remote generator"},i}if("function"==typeof e){if(this._method_annotations.has(e)){let y=this._method_annotations.get(e);i={_rtype:"method",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:y.method_id,_rpromise:"*",_rname:e.name}}else{let w;(0,r.assert)("string"==typeof t),w=e.__name__?`${(0,r.randId)()}#${e.__name__}`:(0,r.randId)(),i={_rtype:"method",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:`${t}.${w}`,_rpromise:"*",_rname:e.name};let b=this._get_session_store(t,!0);(0,r.assert)(null!==b,`Failed to create session store ${t} due to invalid parent`),b[w]=e}if(i._rdoc=e.__doc__,!i._rdoc)try{const v=function(e){const t=e.toString(),n=t.match(/function\s*(\w*)/),r=n&&n[1]||"",o=t.match(/\(([^)]*)\)/);let i="";o&&(i=o[1].split(",").map(e=>e.replace(/\/\*.*?\*\//g,"").replace(/\/\/.*$/g,"")).filter(e=>e.trim().length>0).map(e=>e.trim()).join(", "));let s=t.match(/\)\s*\{\s*\/\*([\s\S]*?)\*\//);const c=s&&s[1].trim()||"";s=t.match(/\)\s*\{\s*(\/\/[\s\S]*?)\n\s*[^\s\/]/);const a=s&&s[1].split("\n").map(e=>e.replace(/^\/\/\s*/,"").trim()).join("\n")||"",l=c||a;return r&&i.length>0&&{name:r,sig:i,doc:l}}(e);v&&!i._rdoc&&(i._rdoc=`${v.doc}`)}catch(E){console.error("Failed to extract function docstring:",e)}return i._rschema=e.__schema__,i}const s=Array.isArray(e);for(let k of Object.keys(this._codecs)){const x=this._codecs[k];if(x.encoder&&e instanceof x.type){let S=await Promise.resolve(x.encoder(e));if(S&&!S._rtype&&(S._rtype=x.name),"object"==typeof S){const T=S._rtype;delete S._rtype,S=await this._encode(S,t,n),S._rtype=T}return i=S,i}}if("undefined"!=typeof tf&&tf.Tensor&&e instanceof tf.Tensor){const C=e.dataSync();i={_rtype:"ndarray",_rvalue:new Uint8Array(C.buffer),_rshape:e.shape,_rdtype:e.dtype}}else if("undefined"!=typeof nj&&nj.NdArray&&e instanceof nj.NdArray){if(!e.selection||!e.selection.data)throw new Error("Invalid NumJS array: missing selection or data");const R=(0,r.typedArrayToDtype)(e.selection.data);i={_rtype:"ndarray",_rvalue:new Uint8Array(e.selection.data.buffer),_rshape:e.shape,_rdtype:R}}else if(e instanceof Error)console.error(e),i={_rtype:"error",_rvalue:e.toString(),_rtrace:e.stack};else if(e!==Object(e)||e instanceof Boolean||e instanceof String||e instanceof Date||e instanceof RegExp||"undefined"!=typeof ImageData&&e instanceof ImageData||"undefined"!=typeof FileList&&e instanceof FileList||"undefined"!=typeof FileSystemDirectoryHandle&&e instanceof FileSystemDirectoryHandle||"undefined"!=typeof FileSystemFileHandle&&e instanceof FileSystemFileHandle||"undefined"!=typeof FileSystemHandle&&e instanceof FileSystemHandle||"undefined"!=typeof FileSystemWritableFileStream&&e instanceof FileSystemWritableFileStream)i=e;else if(e instanceof Blob){let I=0;async function j(t){let n;n=t?e.slice(I,I+t):e.slice(I);const r=new Uint8Array(await n.arrayBuffer());return I+=r.byteLength,r}function A(e){I=e}i={_rtype:"iostream",_rnative:"js:blob",type:e.type,name:e.name,size:e.size,path:e._path||e.webkitRelativePath,read:await this._encode(j,t,n),seek:await this._encode(A,t,n)}}else if(e instanceof a){const $=(0,r.typedArrayToDtype)(e);i={_rtype:"typedarray",_rvalue:new Uint8Array(e.buffer),_rdtype:$}}else if(e instanceof DataView)i={_rtype:"memoryview",_rvalue:new Uint8Array(e.buffer)};else if(e instanceof Set)i={_rtype:"set",_rvalue:await this._encode(Array.from(e),t,n)};else if(e instanceof Map)i={_rtype:"orderedmap",_rvalue:await this._encode(Array.from(e),t,n)};else{if(!(e.constructor===Object||Array.isArray(e)||e instanceof g))throw`hypha-rpc: Unsupported data type: ${e}, you can register a custom codec to encode/decode the object.`;{if(!s&&!0===e._rintf&&Object.keys(e).some(t=>!t.startsWith("_")&&"function"==typeof e[t])){const O=`_rintf_${(0,r.randId)()}`,D={id:O};for(const L of Object.keys(e))L.startsWith("_")||"function"!=typeof e[L]||(D[L]=e[L]);this.add_service(D,!0),e._rintf_service_id=O,i={};for(const U of Object.keys(e))i[U]=await this._encode(e[U],t,n);return i._rintf_service_id=O,i}if(s){if(d(e))return e}else if(!("_rtype"in e||e instanceof g)&&h(e))return e;i=s?[]:{};const P=Object.keys(e);for(let M of P)i[M]=await this._encode(e[M],t,n)}}if(!i)throw new Error("Failed to encode object");return i}async decode(e){return await this._decode(e)}async _decode(e,t,n,o,i){if(!e)return e;let s;if(e._rtype)if(this._codecs[e._rtype]&&this._codecs[e._rtype].decoder){const c=e._rtype;delete e._rtype,(e=await this._decode(e,t,n,o,i))._rtype=c,s=await Promise.resolve(this._codecs[e._rtype].decoder(e))}else if("method"===e._rtype)s=this._generate_remote_method(e,t,n,o,i);else if("generator"===e._rtype){const a=this._generate_remote_method(e,t,n,o,i);let l=null;if(e._rclose_method){const _={_rtype:"method",_rserver:e._rserver,_rtarget:e._rtarget,_rmethod:e._rclose_method,_rpromise:"*"};l=this._generate_remote_method(_,t,n,o,i)}async function*p(){let e=!1;try{for(;;){const t=await a();if(t&&"stop_iteration"===t._rtype){e=!0;break}yield t}}catch(e){throw console.error("Error in generator:",e),e}finally{if(!e&&l)try{await l()}catch(e){}}}s=p()}else if("ndarray"===e._rtype)if("undefined"!=typeof nj&&nj.array)Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(u)),s=nj.array(new Uint8(e._rvalue),e._rdtype).reshape(e._rshape);else if("undefined"!=typeof tf&&tf.Tensor){Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(u));const f=r.dtypeToTypedArray[e._rdtype];s=tf.tensor(new f(e._rvalue),e._rshape,e._rdtype)}else s=e;else if("error"===e._rtype)s=new Error("RemoteError: "+e._rvalue+"\n"+(e._rtrace||""));else if("typedarray"===e._rtype){const m=r.dtypeToTypedArray[e._rdtype];if(!m)throw new Error("unsupported dtype: "+e._rdtype);s=new m(e._rvalue.buffer.slice(e._rvalue.byteOffset,e._rvalue.byteOffset+e._rvalue.byteLength))}else if("memoryview"===e._rtype)s=e._rvalue.buffer.slice(e._rvalue.byteOffset,e._rvalue.byteOffset+e._rvalue.byteLength);else if("iostream"===e._rtype){if("js:blob"===e._rnative){const g=await this._generate_remote_method(e.read,t,n,o,i),y=await g();s=new Blob([y],{type:e.type,name:e.name})}else{s={};for(let w of Object.keys(e))w.startsWith("_")||(s[w]=await this._decode(e[w],t,n,o,i))}s.__rpc_object__=e}else if("orderedmap"===e._rtype)s=new Map(await this._decode(e._rvalue,t,n,o,i));else if("set"===e._rtype)s=new Set(await this._decode(e._rvalue,t,n,o,i));else{const b=e._rtype;delete e._rtype,s=await this._decode(e,t,n,o,i),s._rtype=b}else if(e.constructor===Object||Array.isArray(e)){const v=Array.isArray(e);if(v){if(d(e))return e}else if(h(e))return e;s=v?[]:{};for(let E of Object.keys(e))if(v||e.hasOwnProperty(E)){const k=e[E];s[E]=await this._decode(k,t,n,o,i)}}else s=e;if(void 0===s)throw new Error("Failed to decode object");return s}_expand_promise(e){return{heartbeat:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".heartbeat",_rdoc:`heartbeat callback for method: ${e.method}`},resolve:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".resolve",_rdoc:`resolve callback for method: ${e.method}`},reject:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".reject",_rdoc:`reject callback for method: ${e.method}`},interval:e.t}}}},"./src/utils/index.js":
13
+ \********************/(e,t,n)=>{n.r(t),n.d(t,{API_VERSION:()=>h,RPC:()=>E,_applyEncryptionKeyToService:()=>l,getParamNames:()=>c});var r=n(/*! ./utils/index.js */"./src/utils/index.js"),o=n(/*! ./utils/schema.js */"./src/utils/schema.js"),i=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs"),s=n(/*! @msgpack/msgpack */"./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs"),a=n(/*! ./crypto.js */"./src/crypto.js");function c(e){const t=e.toString().match(/^(?:async\s+)?(?:function\s*\w*)?\s*\(([^)]*)\)|^(?:async\s+)?(\w+)\s*=>|^(?:async\s+)?\w+\s*\(([^)]*)\)/);if(!t)return[];const n=void 0!==t[1]?t[1]:void 0!==t[2]?t[2]:t[3];return n&&n.trim()?n.split(",").map(e=>e.trim().replace(/\s*=.*$/,"").replace(/^\.\.\.\s*/,"")).filter(Boolean):[]}function l(e,t){if(e&&"object"==typeof e&&!ArrayBuffer.isView(e))for(const n of Object.keys(e)){const r=e[n];"function"==typeof r&&r.__rpc_object__?r.__rpc_object__._renc_pub=t:r&&"object"==typeof r&&!ArrayBuffer.isView(r)&&l(r,t)}}const h=3,d=Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;function _(e){if(null==e)return!0;const t=typeof e;return"number"===t||"string"===t||"boolean"===t}function u(e){for(let t=0;t<e.length;t++){const n=e[t];if(!_(n)&&!(n instanceof Uint8Array))if(Array.isArray(n)){if(!u(n))return!1}else{if(!n||n.constructor!==Object)return!1;if("_rtype"in n)return!1;if(!p(n))return!1}}return!0}function p(e){const t=Object.values(e);for(let e=0;e<t.length;e++){const n=t[e];if(!_(n)&&!(n instanceof Uint8Array))if(Array.isArray(n)){if(!u(n))return!1}else{if(!n||n.constructor!==Object)return!1;if("_rtype"in n)return!1;if(!p(n))return!1}}return!0}function f(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}function g(e,t,n="Operation timed out"){return new Promise((r,o)=>{const i=setTimeout(()=>{o(new Error(`TimeoutError: ${n}`))},t);e.then(e=>{clearTimeout(i),r(e)}).catch(e=>{clearTimeout(i),o(e)})})}function m(e,t){if(!t)throw new Error("undefined index");return"string"==typeof t?m(e,t.split(".")):0===t.length?e:m(e[t[0]],t.slice(1))}function y(e,t=null,n=!1){if(Array.isArray(e))return e.map((e,t)=>y(e,null,n));if("object"==typeof e&&null!==e){let t={};for(let r in e)t[r]=y(e[r],r,n);return t}if("function"==typeof e){if(e.__schema__){const r=JSON.parse(JSON.stringify(e.__schema__));if(t&&(r.name=t,e.__schema__.name=t),n&&(r.parameters&&r.parameters.properties&&delete r.parameters.properties.context,r.parameters&&r.parameters.required)){const e=r.parameters.required.indexOf("context");e>-1&&r.parameters.required.splice(e,1)}return{type:"function",function:r}}return{type:"function",function:{name:t||e.name||"function"}}}return"number"==typeof e?{type:"number"}:"string"==typeof e?{type:"string"}:"boolean"==typeof e?{type:"boolean"}:null===e?{type:"null"}:{}}class w{constructor(e,t,n,r){this._timeout=e,this._callback=t,this._args=n,this._label=r||"timer",this._task=null,this.started=!1}start(){this.started?this.reset():(this._task=setTimeout(()=>{this._callback.apply(this,this._args)},1e3*this._timeout),this.started=!0)}clear(){this._task&&this.started?(clearTimeout(this._task),this._task=null,this.started=!1):console.warn(`Clearing a timer (${this._label}) which is not started`)}reset(){this._task&&clearTimeout(this._task),this._task=setTimeout(()=>{this._callback.apply(this,this._args)},1e3*this._timeout),this.started=!0}}class b extends Object{}const v=["Method expired or not found","Session not found","Peer","Method not found","Connection was closed","Connection is closed"];function k(e){const t=String(e&&e.message?e.message:e);return v.some(e=>t.includes(e))}class E extends r.MessageEmitter{constructor(e,{client_id:t=null,default_context:n=null,name:o=null,codecs:i=null,method_timeout:s=null,rintf_timeout:c=null,max_message_buffer_size:l=0,debug:d=!1,workspace:_=null,silent:u=!1,logger:p,app_id:f=null,server_base_url:m=null,long_message_chunk_size:y=null,encryption:w=!1,encryption_private_key:b=null,encryption_public_key:v=null}){if(super(d),this._codecs=i||{},(0,r.assert)(t&&"string"==typeof t),(0,r.assert)(t,"client_id is required"),this._client_id=t,this._name=o,this._app_id=f||"*",this._local_workspace=_,this._silent=u,null===p||u){const e=()=>{};this._logger={debug:e,info:e,warn:e,error:e,log:e}}else this._logger=p||console;if(this.default_context=n||{},this._method_annotations=new WeakMap,this._max_message_buffer_size=l,this._chunk_store={},this._method_timeout=s||30,this._rintf_timeout=c||10,this._server_base_url=m,this._long_message_chunk_size=y||262144,this._services={},this._object_store={services:this._services},this._targetIdIndex={},this._rintfCallerIndex={},this._last_manager_id=null,this._encryption_enabled=!1,this._encryption_private_key=null,this._encryption_public_key=null,this._encryption_ready=null,w&&(b&&v?(this._encryption_private_key=b,this._encryption_public_key=v,this._encryption_enabled=!0,this._encryption_ready=Promise.resolve()):this._encryption_ready=(0,a.generateEncryptionKeypair)().then(e=>{this._encryption_private_key=e.privateKey,this._encryption_public_key=e.publicKey,this._encryption_enabled=!0})),this._background_tasks=new Set,this._sessionMaxAge=6e5,this._sessionSweepInterval=setInterval(()=>{this._sweepStaleSessions()},this._sessionMaxAge/2),this._unhandledRejectionHandler=e=>{const t=e.reason;if(t&&"object"==typeof t){const n=t.toString();if(n.includes("Method not found")||n.includes("Session not found")||n.includes("Method expired")||n.includes("Connection is closed")||n.includes("Client disconnected")||n.includes("RPC connection closed"))return void e.preventDefault()}this._logger.warn("Unhandled RPC promise rejection:",t)},this._unhandledRejectionNodeHandler=null,E._rejectionHandlerCount||(E._rejectionHandlerCount=0),E._rejectionHandlerCount++,1===E._rejectionHandlerCount&&("undefined"!=typeof window?window.addEventListener("unhandledrejection",this._unhandledRejectionHandler):"undefined"!=typeof process&&(this._unhandledRejectionNodeHandler=(e,t)=>{this._unhandledRejectionHandler({reason:e,promise:t,preventDefault:()=>{}})},process.on("unhandledRejection",this._unhandledRejectionNodeHandler))),e){this.add_service({id:"built-in",type:"built-in",name:`Built-in services for ${this._local_workspace}/${this._client_id}`,config:{require_context:!0,visibility:"public",api_version:h},ping:this._ping.bind(this),get_service:this.get_local_service.bind(this),message_cache:{create:this._create_message.bind(this),append:this._append_message.bind(this),set:this._set_message.bind(this),process:this._process_message.bind(this),remove:this._remove_message.bind(this)}}),this._boundHandleMethod=this._handle_method.bind(this),this._boundHandleError=console.error,this.on("method",this._boundHandleMethod),this.on("error",this._boundHandleError),this.on("peer_not_found",this._handlePeerNotFound.bind(this)),(0,r.assert)(e.emit_message&&e.on_message),(0,r.assert)(void 0!==e.manager_id,"Connection must have manager_id"),this._emit_message=e.emit_message.bind(e),e.on_message(this._on_message.bind(this)),this._connection=e;const t=async e=>{if(!this._silent&&this._connection.manager_id){const e=this._connection.manager_id;if(this._last_manager_id&&this._last_manager_id!==e){const e=`*/${this._last_manager_id}`,t=this._cleanupSessionsForClient(e);t>0&&this._logger.info(`Rejected ${t} stale call(s) to old manager ${this._last_manager_id}`)}this._last_manager_id=e;try{const e=await this.get_manager_service({timeout:20,case_conversion:"camel"});this._fire("manager_refreshed",{manager:e});const t=Object.values(this._services);let n=t.length,r=0;const o=[],i=1e3*(this._method_timeout||30);for(let s of t)if(s.config&&s.config._local_only)n--;else try{const t=this._extract_service_info(s);await g(e.registerService(t),i,`Timeout registering service ${s.id||"unknown"}`),r++}catch(e){o.push(s.id||"unknown"),e.message&&e.message.includes("TimeoutError")?this._logger.error(`Timeout registering service ${s.id||"unknown"}`):this._logger.error(`Failed to register service ${s.id||"unknown"}: ${e}`)}r===n?this._logger.info(`Successfully registered all ${r} services with the server`):this._logger.warn(`Only registered ${r} out of ${n} services with the server. Failed services: ${o.join(", ")}`),this._fire("services_registered",{total:n,registered:r,failed:o}),this._connection._services_registered_ok=0===o.length;try{if(e.subscribe&&"function"==typeof e.subscribe){if(this._clientDisconnectedSubscription){try{"function"==typeof this._clientDisconnectedSubscription.unsubscribe&&this._clientDisconnectedSubscription.unsubscribe()}catch(e){}this._clientDisconnectedSubscription=null}if(this._boundHandleClientDisconnected){try{this.off("client_disconnected",this._boundHandleClientDisconnected)}catch(e){}this._boundHandleClientDisconnected=null}this._boundHandleClientDisconnected=async e=>{const t=e.data?.id||e.client,n=e.data?.workspace;if(t&&n){const e=`${n}/${t}`;await this._handleClientDisconnected(e)}else t&&await this._handleClientDisconnected(t)},this._clientDisconnectedSubscription=await g(e.subscribe(["client_disconnected"]),i,"Timeout subscribing to client_disconnected events"),this.on("client_disconnected",this._boundHandleClientDisconnected)}else this._clientDisconnectedSubscription=null}catch(e){this._clientDisconnectedSubscription=null}}catch(e){this._logger.error(`Failed to get manager service for registering services: ${e}`),this._fire("services_registration_failed",{error:e.toString(),total_services:Object.keys(this._services).length}),this._connection._services_registered_ok=!1}}e&&(e.public_base_url&&(this._server_base_url=e.public_base_url),this._fire("connected",e))};e.on_connected(t),"function"==typeof e.on_disconnected&&e.on_disconnected(t=>{!e._enable_reconnect||e._closed?(this._logger.warn(`Connection lost (${t}), rejecting all pending RPC calls`),this._rejectPendingCalls(`Connection lost: ${t||"unknown reason"}`)):this._logger.info(`Connection lost (${t}), reconnection enabled - pending calls will be handled by timeout`)}),t()}else this._emit_message=function(){this._logger.log("No connection to emit message")}}getPublicKey(){return this._encryption_enabled&&this._encryption_public_key?(0,a.publicKeyToHex)(this._encryption_public_key):null}register_codec(e){if(!e.name||!e.encoder&&!e.decoder)throw new Error("Invalid codec format, please make sure you provide a name, type, encoder and decoder.");if(e.type)for(let t of Object.keys(this._codecs))this._codecs[t].type!==e.type&&t!==e.name||(delete this._codecs[t],this._logger.warn("Remove duplicated codec: "+t));this._codecs[e.name]=e}async _ping(e,t){return(0,r.assert)("ping"==e),"pong"}async ping(e,t){let n=this._generate_remote_method({_rserver:this._server_base_url,_rtarget:e,_rmethod:"services.built-in.ping",_rpromise:!0,_rdoc:"Ping a remote client"});(0,r.assert)("pong"==await n("ping",t))}_create_message(e,t,n,r){if(t){const t=this._object_store[e];if(!t)throw new Error(`session does not exist anymore: ${e}`);t.timer&&"function"==typeof t.timer.reset&&t.timer.reset()}this._object_store.message_cache||(this._object_store.message_cache={});const o=this._object_store.message_cache,i=Object.keys(o);if(i.length>=256){const e=Date.now();for(const t of i){const n=o[t];n&&n._cache_created_at&&e-n._cache_created_at>3e5&&delete o[t]}const t=Object.keys(o);t.length>=256&&t.sort((e,t)=>(o[e]._cache_created_at||0)-(o[t]._cache_created_at||0)).slice(0,t.length-256+1).forEach(e=>delete o[e])}if(!n&&o[e])throw new Error(`Message with the same key (${e}) already exists in the cache store, please use overwrite=true or remove it first.`);o[e]=[],o[e]._cache_created_at=Date.now()}_append_message(e,t,n,o){if(n){const t=this._object_store[e];if(!t)throw new Error(`session does not exist anymore: ${e}`);t.timer&&"function"==typeof t.timer.reset&&t.timer.reset()}const i=this._object_store.message_cache;if(!i[e])throw new Error(`Message with key ${e} does not exists.`);(0,r.assert)(t instanceof d),i[e].push(t)}_set_message(e,t,n,o,i){if(o){const t=this._object_store[e];if(!t)throw new Error(`session does not exist anymore: ${e}`);t.timer&&"function"==typeof t.timer.reset&&t.timer.reset()}const s=this._object_store.message_cache;if(!s[e])throw new Error(`Message with key ${e} does not exists.`);(0,r.assert)(n instanceof d),s[e][t]=n}_remove_message(e,t){const n=this._object_store.message_cache;if(!n[e])throw new Error(`Message with key ${e} does not exists.`);delete n[e]}_process_message(e,t,n){if(t){const t=this._object_store[e];if(!t)throw new Error(`session does not exist anymore: ${e}`);t.timer&&"function"==typeof t.timer.reset&&t.timer.reset()}const o=this._object_store.message_cache;if((0,r.assert)(!!n,"Context is required"),!o[e])throw new Error(`Message with key ${e} does not exists.`);var s,a,c,l;o[e]=(s=o[e],a=s.map(function(e){return e.byteLength}),c=a.reduce(function(e,t){return e+t},0),l=new Uint8Array(c),a.reduce(function(e,t,n){return l.set(new Uint8Array(s[n]),e),e+t},0),l.buffer);let h=(0,i.decodeMulti)(o[e]);const{done:d,value:_}=h.next(),u=_;if(Object.assign(u,{from:n.from,to:n.to,ws:n.ws,user:n.user}),u.ctx=JSON.parse(JSON.stringify(u)),Object.assign(u.ctx,this.default_context),!d){let e=h.next();Object.assign(u,e.value)}this._fire(u.type,u),delete o[e]}_on_message(e){if("string"==typeof e){const t=JSON.parse(e);t.ctx=Object.assign({},t,this.default_context),this._fire(t.type,t)}else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)){let t=(0,i.decodeMulti)(e);const{done:n,value:r}=t.next(),o=r;if(o.ctx=Object.assign({},o,this.default_context),!n){let e=t.next();Object.assign(o,e.value)}this._fire(o.type,o)}else{if("object"!=typeof e)throw new Error("Invalid message format");e.ctx=Object.assign({},e,this.default_context),this._fire(e.type,e)}}reset(){this._removeRejectionHandler(),this._event_handlers={},this._services={}}_removeRejectionHandler(){E._rejectionHandlerCount&&E._rejectionHandlerCount>0&&(E._rejectionHandlerCount--,0===E._rejectionHandlerCount&&("undefined"!=typeof window&&this._unhandledRejectionHandler?window.removeEventListener("unhandledrejection",this._unhandledRejectionHandler):"undefined"!=typeof process&&this._unhandledRejectionNodeHandler&&process.removeListener("unhandledRejection",this._unhandledRejectionNodeHandler))),this._unhandledRejectionHandler=null,this._unhandledRejectionNodeHandler=null}close(){if(this._cleanupOnDisconnect(),this._boundHandleMethod&&(this.off("method",this._boundHandleMethod),this._boundHandleMethod=null),this._boundHandleError&&(this.off("error",this._boundHandleError),this._boundHandleError=null),this._clientDisconnectedSubscription){try{"function"==typeof this._clientDisconnectedSubscription.unsubscribe&&this._clientDisconnectedSubscription.unsubscribe()}catch(e){}this._clientDisconnectedSubscription=null}this._boundHandleClientDisconnected&&(this.off("client_disconnected",this._boundHandleClientDisconnected),this._boundHandleClientDisconnected=null),this._removeRejectionHandler(),this.off();try{for(const e of this._background_tasks)if(e&&"function"==typeof e.cancel)try{e.cancel()}catch(e){}this._background_tasks.clear()}catch(e){}this._sessionSweepInterval&&(clearInterval(this._sessionSweepInterval),this._sessionSweepInterval=null);try{this._connection=null,this._emit_message=function(){return Promise.reject(new Error("Connection is closed"))}}catch(e){}this._fire("disconnected")}_unregisterRintfService(e,t){this._services[e]&&delete this._services[e],t&&this._rintfCallerIndex[t]&&(this._rintfCallerIndex[t].delete(e),0===this._rintfCallerIndex[t].size&&delete this._rintfCallerIndex[t])}_cleanupRintfForCaller(e){const t=this._rintfCallerIndex[e];if(!t)return 0;delete this._rintfCallerIndex[e];let n=0;for(const e of t){const t=this._services[e];if(t){if("function"==typeof t._dispose)try{t._dispose()}catch(e){}delete this._services[e],n++}}return n}async _handleClientDisconnected(e){try{const t=this._cleanupSessionsForClient(e),n=this._cleanupRintfForCaller(e);this._fire("remote_client_disconnected",{client_id:e,sessions_cleaned:t,rintf_cleaned:n})}catch(t){this._logger.error(`Error handling client disconnection for ${e}: ${t}`)}}_handlePeerNotFound(e){const t=e.session,n=e.peer_id||e.from||"unknown",r=e.error||`Peer ${n} is not connected`;if(t){const e=this._object_store[t];e&&"object"==typeof e&&(this._cleanupSessionEntry(e,r),delete this._object_store[t],this._removeFromTargetIdIndex(t))}this._cleanupSessionsForClient(n)}_removeFromTargetIdIndex(e){const t=e.split(".")[0],n=this._object_store[t];if(n&&"object"==typeof n){const e=n.target_id;e&&e in this._targetIdIndex&&(this._targetIdIndex[e].delete(t),0===this._targetIdIndex[e].size&&delete this._targetIdIndex[e])}}_cleanupSessionEntry(e,t=null){if(e&&"object"==typeof e){if(t&&e.reject&&"function"==typeof e.reject)try{e.reject(new Error(t))}catch(e){}if(e.heartbeat_task)try{clearInterval(e.heartbeat_task)}catch(e){}if(e.timer&&e.timer.started&&"function"==typeof e.timer.clear)try{e.timer.clear()}catch(e){}}}_cleanupSessionsForClient(e){let t=0;const n=this._targetIdIndex[e];if(!n)return 0;const r=`Client disconnected: ${e}`;for(const o of n){const n=this._object_store[o];n&&"object"==typeof n&&(n.target_id===e&&(this._cleanupSessionEntry(n,r),delete this._object_store[o],t++))}return delete this._targetIdIndex[e],t}_rejectPendingCalls(e="Connection lost"){try{let t=0;for(const n of Object.keys(this._object_store)){if("services"===n||"message_cache"===n)continue;const r=this._object_store[n];"object"==typeof r&&null!==r&&(r.reject&&"function"==typeof r.reject&&t++,this._cleanupSessionEntry(r,e))}t>0&&this._logger.warn(`Rejected ${t} pending RPC call(s) due to: ${e}`)}catch(e){this._logger.error(`Error rejecting pending calls: ${e}`)}}_cleanupOnDisconnect(){try{const e=[];for(const t of Object.keys(this._object_store)){if("services"===t||"message_cache"===t)continue;const n=this._object_store[t];this._cleanupSessionEntry(n,"RPC connection closed"),e.push(t)}for(const t of e)delete this._object_store[t];this._targetIdIndex={},this._rintfCallerIndex={}}catch(e){this._logger.error(`Error during cleanup on disconnect: ${e}`)}}async disconnect(){const e=this._connection;if(this.close(),e)try{await e.disconnect()}catch(e){}}async get_manager_service(e,t=20){e=e||{};let n=null;for(let r=0;r<t;r++){const o=Math.min(500*Math.pow(2,r),1e4);if(!this._connection.manager_id){if(r<t-1){this._logger.warn(`Manager ID not set, retrying in ${o}ms (attempt ${r+1}/${t})`),await new Promise(e=>setTimeout(e,o));continue}throw new Error("Manager ID not set after maximum retries")}try{return await this.get_remote_service(`*/${this._connection.manager_id}:default`,e)}catch(e){n=e,this._logger.warn(`Failed to get manager service (attempt ${r+1}/${t}): ${e.message}`),r<t-1&&await new Promise(e=>setTimeout(e,o))}}throw n}get_all_local_services(){return this._services}get_local_service(e,t){(0,r.assert)(e),(0,r.assert)(t,"Context is required");const[n,o]=t.to.split("/");(0,r.assert)(o===this._client_id,"Services can only be accessed locally");const i=this._services[e];if(!i)throw new Error("Service not found: "+e);if("public"==i.config.visibility||"unlisted"==i.config.visibility)return i;if(t.ws===n)return i;const s=i.config.authorized_workspaces;if(s&&s.includes(t.ws))return i;throw new Error(`Permission denied for getting protected service: ${e}, workspace mismatch: ${n} != ${t.ws}`)}async get_remote_service(e,t){let{timeout:n,case_conversion:o,kwargs_expansion:i,encryption_public_key:s,_no_retry:c}=t||{};n=void 0===n?this._method_timeout:n,!e&&this._connection.manager_id?e="*/"+this._connection.manager_id:e.includes(":")||(e=this._client_id+":"+e);const h=e.split(":")[0];let d=e.split(":")[1];if(d.includes("@")){d=d.split("@")[0];const t=e.split("@")[1];this._app_id&&"*"!==this._app_id&&(0,r.assert)(t===this._app_id,`Invalid app id: ${t} != ${this._app_id}`)}(0,r.assert)(h,`Invalid service uri: ${e}`);try{const _=this._generate_remote_method({_rserver:this._server_base_url,_rtarget:h,_rmethod:"services.built-in.get_service",_rpromise:!0,_rdoc:"Get a remote service"});let u=await(0,r.waitFor)(_(d),n,"Timeout Error: Failed to get remote service: "+e);if(u.id=`${h}:${d}`,s){l(u,(0,a.publicKeyFromHex)(s))}i&&(u=(0,r.expandKwargs)(u)),o&&(u=(0,r.convertCase)(u,o));const p=Object.assign(new b,u);return c||this._wrapServiceMethodsWithRetry(p,e,t||{}),p}catch(t){throw this._logger.warn("Failed to get remote service: "+e,t),t}}_wrapServiceMethodsWithRetry(e,t,n){const r=this;for(const o of Object.keys(e)){const i=e[o];if("function"!=typeof i)continue;const s=o,a=i,c=async function(...e){try{return await a(...e)}catch(o){if(k(o)){console.info(`Stale service error on ${t}:${s}, refreshing and retrying:`,o.message||o);const i={...n,_no_retry:!0},a=(await r.get_remote_service(t,i))[s];if(!a)throw o;return await a(...e)}throw o}};c.__rpc_object__=a.__rpc_object__,c.__name__=a.__name__||s,c.__doc__=a.__doc__,c.__schema__=a.__schema__,e[o]=c}}_annotate_service_methods(e,t,n,r,o,i,s,a){if("function"==typeof e){let c=t.split(".")[1];this._method_annotations.set(e,{require_context:Array.isArray(n)?n.includes(c):!!n,run_in_executor:r,method_id:"services."+t,visibility:o,authorized_workspaces:i,trusted_keys:s,rintf_allowed_caller:a})}else if(e instanceof Array||e instanceof Object)for(let c of Object.keys(e)){let l=e[c];if("function"==typeof l&&l.__rpc_object__){let t=l.__rpc_object__._rtarget;if(t.includes("/")&&(t=t.split("/")[1]),this._client_id!==t)throw new Error(`Local method not found: ${l.__rpc_object__._rmethod}, client id mismatch ${this._client_id} != ${t}`);e instanceof Array&&(e=e.slice()),e[c]=m(this._object_store,l.__rpc_object__._rmethod),l=e[c]}this._annotate_service_methods(l,t+"."+c,n,r,o,i,s,a)}}add_service(e,t){if(!e||Array.isArray(e))throw new Error("Invalid service object");if(e.constructor===Object)e=Object.assign({},e);else{const t={},n=Object.getOwnPropertyNames(e).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(e)));for(let r of n)"constructor"!==r&&("function"==typeof e[r]?t[r]=e[r].bind(e):t[r]=e[r]);e.id=e.id||"default",e=t}(0,r.assert)(e.id&&"string"==typeof e.id,`Service id not found: ${e}`),e.name||(e.name=e.id),e.config||(e.config={}),e.type||(e.type="generic");let n=!1,o=!1;e.config.require_context&&(n=e.config.require_context),e.config.run_in_executor&&(o=!0);const i=e.config.visibility||"protected";(0,r.assert)(["protected","public","unlisted"].includes(i));const s=e.config.authorized_workspaces;if(void 0!==s){if("protected"!==i)throw new Error(`authorized_workspaces can only be set when visibility is 'protected', got visibility='${i}'`);if(!Array.isArray(s))throw new Error("authorized_workspaces must be an array of workspace ids");for(const e of s)if("string"!=typeof e)throw new Error("Each workspace id in authorized_workspaces must be a string, got "+typeof e)}const a=e.config.trusted_keys;let c=null;if(a&&a.length>0){if(!Array.isArray(a))throw new Error("trusted_keys must be an array of hex-encoded public keys");c=new Set;for(const e of a){if("string"!=typeof e||64!==e.length)throw new Error(`Each trusted key must be a 64-char hex string, got: ${e}`);c.add(e)}}const l=e.config._rintf_allowed_caller||null;if(this._annotate_service_methods(e,e.id,n,o,i,s,c,l),this._services[e.id]){if(!t)throw new Error(`Service already exists: ${e.id}, please specify a different id (not ${e.id}) or overwrite=true`);delete this._services[e.id]}return this._services[e.id]=e,e}_extract_service_info(e){const t=e.config||{};if(t.workspace=t.workspace||this._local_workspace||this._connection.workspace,!t.workspace)throw new Error("Workspace is not set. Please ensure the connection has a workspace or set local_workspace.");const n=t.require_context,r=["id","config","name","description","type","docs","app_id","service_schema"],o={};for(const t of Object.keys(e))r.includes(t)||(o[t]=e[t]);const i=y(o,null,n);return{config:t,id:`${t.workspace}/${this._client_id}:${e.id}`,name:e.name||e.id,description:e.description||"",type:e.type||"generic",docs:e.docs||null,app_id:this._app_id,service_schema:i}}async get_service_schema(e){return y(e,null,e.config.require_context)}async register_service(e,t){let n,{check_type:r,notify:i,overwrite:s}=t||{};if(i=void 0===i||i,r&&e.type)try{n=await this.get_manager_service({timeout:10,case_conversion:"camel"});e=function(e,t){function n(e,t,n="root"){for(let r in t)if(!e.hasOwnProperty(r))throw new Error(`Missing key '${r}' in service at path '${n}'`);for(let r in e)if("type"!==r&&!t.hasOwnProperty(r))throw new Error(`Unexpected key '${r}' in service at path '${n}'`)}return n(e,t.definition),function e(t,r,i="root"){if("object"!=typeof t||Array.isArray(t)){if(Array.isArray(t)){if(t.length!==r.length)throw new Error(`Length mismatch at path '${i}'`);t.forEach((n,s)=>{let a=`${i}[${s}]`;if("object"!=typeof n||Array.isArray(n)){if("function"==typeof n){if(!r.hasOwnProperty(s))throw new Error(`Missing schema for function at index ${s} in path '${a}'`);t[s]=(0,o.schemaFunction)(n,{name:r[s].name,description:r[s].description||"",parameters:r[s].parameters})}}else e(n,r[s],a)})}}else{n(t,r,i);for(let n in t){let s=t[n],a=`${i}.${n}`;if("object"!=typeof s||Array.isArray(s)){if("function"==typeof s){if(!r.hasOwnProperty(n))throw new Error(`Missing schema for function '${n}' at path '${a}'`);t[n]=(0,o.schemaFunction)(s,{name:r[n].name,description:r[n].description||"",parameters:r[n].parameters})}}else e(s,r[n],a)}}}(e,t.definition),e}(e,await n.get_service_type(e.type))}catch(t){throw new Error(`Failed to get service type ${e.type}, error: ${t}`)}const a=this.add_service(e,s),c=this._extract_service_info(a);if(i)try{n=n||await this.get_manager_service({timeout:10,case_conversion:"camel"}),await n.registerService(c)}catch(e){throw new Error(`Failed to notify workspace manager: ${e}`)}return c}async unregister_service(e,t){let n;if(t=void 0===t||t,n="string"==typeof e?e:e.id,(0,r.assert)(n&&"string"==typeof n,`Invalid service id: ${n}`),n.includes(":")&&(n=n.split(":")[1]),n.includes("@")&&(n=n.split("@")[0]),!this._services[n])throw new Error(`Service not found: ${n}`);if(n.startsWith("_rintf_")){t=!1;for(const[e,t]of Object.entries(this._rintfCallerIndex))t.delete(n),0===t.size&&delete this._rintfCallerIndex[e]}if(t){const e=await this.get_manager_service({timeout:10,case_conversion:"camel"});await e.unregisterService(n)}delete this._services[n]}_ndarray(e,t,n){const o=(0,r.typedArrayToDtype)(e);if(n&&n!==o)throw"dtype doesn't match the type of the array: "+o+" != "+n;return t=t||[e.length],{_rtype:"ndarray",_rvalue:e.buffer,_rshape:t,_rdtype:o}}_encode_callback(e,t,n,r,o,i,s){let a=`${n}.${e}`,c={_rtype:"method",_rtarget:i?`${i}/${this._client_id}`:this._client_id,_rmethod:a,_rpromise:!1};const l=this;let h=function(){try{t.apply(null,Array.prototype.slice.call(arguments))}catch(e){l._logger.error(`Error in callback(${a}, ${s}): ${e}`)}finally{o&&o.started&&o.clear(),r&&l._object_store[n]&&("resolve"===e||"reject"===e?(l._removeFromTargetIdIndex(n),delete l._object_store[n]):l._cleanup_session_if_needed(n,e))}};return h.__name__=`callback(${a})`,[c,h]}_cleanup_session_if_needed(e,t){if(e)try{const n=this._get_session_store(e,!1);if(!n)return;let r=!1;if(n._promise_manager)try{const e=n._promise_manager;e.should_cleanup_on_callback&&e.should_cleanup_on_callback(t)&&(e.settle&&e.settle(),r=!0)}catch(t){this._logger.warn(`Error in promise manager cleanup for session ${e}:`,t)}else("resolve"===t||"reject"===t)&&n._callbacks&&Object.keys(n._callbacks).includes(t)&&(r=!0);r&&this._cleanup_session_completely(e)}catch(t){this._logger.warn(`Error during session cleanup for ${e}:`,t)}}_cleanup_session_completely(e){try{this._removeFromTargetIdIndex(e);const t=this._get_session_store(e,!1);if(!t)return;if(t.timer&&t.timer.started&&"function"==typeof t.timer.clear)try{t.timer.clear()}catch(t){this._logger.warn(`Error clearing timer for session ${e}:`,t)}if(t.heartbeat_task&&"function"==typeof t.heartbeat_task.cancel)try{t.heartbeat_task.cancel()}catch(t){this._logger.warn(`Error canceling heartbeat for session ${e}:`,t)}const n=e.split(".");let r=this._object_store;for(let e=0;e<n.length-1;e++){const t=n[e];if(!r[t])return;r=r[t]}const o=n[n.length-1];r[o]&&(delete r[o],this._cleanup_empty_containers(n.slice(0,-1)))}catch(t){this._logger.warn(`Error in complete session cleanup for ${e}:`,t)}}_cleanup_empty_containers(e){try{for(let t=e.length-1;t>=0;t--){let n=this._object_store;for(let r=0;r<t;r++)if(n=n[e[r]],!n)return;const r=e[t],o=n[r];if(!o||"object"!=typeof o||0!==Object.keys(o).length)break;delete n[r]}}catch(e){this._logger.warn("Error cleaning up empty containers:",e)}}get_session_stats(){const e={total_sessions:0,promise_sessions:0,regular_sessions:0,sessions_with_timers:0,sessions_with_heartbeat:0,system_stores:{},session_ids:[],memory_usage:0};if(!this._object_store)return e;for(const t in this._object_store){const n=this._object_store[t];if(["services","message_cache"].includes(t))e.system_stores[t]={size:"object"==typeof n&&n?Object.keys(n).length:0};else if(n&&"object"==typeof n){Object.keys(n).length>0&&(e.total_sessions++,e.session_ids.push(t),n._promise_manager?e.promise_sessions++:e.regular_sessions++,(n._timer||n.timer)&&e.sessions_with_timers++,(n._heartbeat||n.heartbeat)&&e.sessions_with_heartbeat++,e.memory_usage+=JSON.stringify(n).length)}}return e}_force_cleanup_all_sessions(){if(!this._object_store)return;const e=[];for(const t in this._object_store)if(!["services","message_cache"].includes(t)){const n=this._object_store[t];n&&"object"==typeof n&&Object.keys(n).length>0&&e.push(t)}for(const t of e)delete this._object_store[t];this._targetIdIndex={},this._rintfCallerIndex={}}_sweepStaleSessions(){const e=Date.now();for(const t of Object.keys(this._object_store)){if("services"===t||"message_cache"===t)continue;const n=this._object_store[t],r=n&&(n._last_activity_at||n._created_at);if(n&&"object"==typeof n&&r&&e-r>this._sessionMaxAge&&(!n.timer||!n.timer.started)){if("function"==typeof n.resolve||"function"==typeof n.reject)continue;this._removeFromTargetIdIndex(t),n.heartbeat_task&&clearInterval(n.heartbeat_task),delete this._object_store[t]}}}_is_promise_method_call(e){const t=e.split(".")[0],n=this._get_session_store(t,!1);return n&&n._promise_manager}_create_promise_manager(){return{should_cleanup_on_callback:e=>["resolve","reject"].includes(e),settle:()=>{}}}async _encode_promise(e,t,n,r,o,i,s){let a=this._get_session_store(n,!0);a||(this._logger.warn(`Failed to create session store ${n}, session management may be impaired`),a={}),a._promise_manager=this._create_promise_manager();let c={};return o&&t&&this._method_timeout?([c.heartbeat,a.heartbeat]=this._encode_callback("heartbeat",o.reset.bind(o),n,!1,null,i),a.timer=o,c.interval=this._method_timeout/2):o=null,[c.resolve,a.resolve]=this._encode_callback("resolve",e,n,r,o,i,`resolve (${s})`),[c.reject,a.reject]=this._encode_callback("reject",t,n,r,o,i,`reject (${s})`),c}async _send_chunks(e,t,n){const o=await this.get_remote_service(`${t}:built-in`);if(!o.message_cache)throw new Error("Remote client does not support message caching for large messages.");const i=o.message_cache,s=n||(0,r.randId)(),a=e.length,c=Date.now(),l=Math.ceil(a/this._long_message_chunk_size);if(o.config.api_version>=3){await i.create(s,!!n);const t=new r.Semaphore(30),o=[];for(let r=0;r<l;r++){const a=r*this._long_message_chunk_size,c=e.slice(a,a+this._long_message_chunk_size),l=async()=>{await i.set(s,r,c,!!n)};o.push(t.run(l))}try{await Promise.all(o)}catch(e){try{await i.remove(s)}catch(e){this._logger.error(`Failed to clean up message cache after error: ${e}`)}throw e}}else{await i.create(s,!!n);for(let t=0;t<l;t++){const r=t*this._long_message_chunk_size,o=e.slice(r,r+this._long_message_chunk_size);await i.append(s,o,!!n)}}await i.process(s,!!n),((Date.now()-c)/1e3).toFixed(2)}emit(e,t){if((0,r.assert)("object"==typeof e&&e.type,"Invalid message, must be an object with a `type` fields."),!e.to)return void this._fire(e.type,e);let n=(0,s.encode)(e);if(t){const e=(0,s.encode)(t),r=new Uint8Array(n.length+e.length);r.set(n),r.set(e,n.length),n=r}const o=n.length;return o>this._long_message_chunk_size+1024&&this._logger.warn(`Sending large message (size=${o})`),this._emit_message(n)}_generate_remote_method(e,t,n,o,i){let c=e._rtarget;o&&!c.includes("/")&&(c.startsWith("*/")||(o!==c&&(c=o+"/"+c),e._rtarget=c));let l=e._rmethod,h=e._rpromise||!1;const d=`method: ${l}, docs: ${e._rdoc}`,_=this;function u(){return new Promise(async(o,c)=>{try{const p=e._rtarget;let f=(0,r.randId)();n&&(f=n+"."+f);let g=_._get_session_store(f,!0);if(!g)return void c(new Error(`Runtime Error: Failed to get session store ${f} (context: ${d})`));g.target_id=p;const m=f.split(".")[0];p in _._targetIdIndex||(_._targetIdIndex[p]=new Set),_._targetIdIndex[p].add(m);const y=await _._encode(Array.prototype.slice.call(arguments),f,i),b=y.length,v=b>0&&"object"==typeof y[b-1]&&null!==y[b-1]&&y[b-1]._rkwargs;let k;v&&delete y[b-1]._rkwargs,k=_._local_workspace?_._local_workspace+"/"+_._client_id:_._client_id;let E={type:"method",from:k,to:p,method:l},x={};y&&(x.args=y),v&&(x.with_kwargs=v),t&&(E.parent=t);let S=null;if(h){E.session=f;let e=`${p}:${l}`;const t=function(e){c(new Error(e)),_._object_store[f]&&(_._removeFromTargetIdIndex(f),delete _._object_store[f])},n=l.includes("_rintf_")?_._rintf_timeout:_._method_timeout;S=new w(n,t,[`Method call timed out: ${e}, context: ${d}`],e);let r=!0;const s=await _._encode_promise(o,c,f,r,S,i,d);if(!0===h)x.promise=s;else{if("*"!==h)throw new Error(`Unsupported promise type: ${h}`);x.promise="*",x.t=n/2}}if(_._encryption_ready&&await _._encryption_ready,x&&_._encryption_enabled&&e._renc_pub){const t=(0,s.encode)(x),{nonce:n,ciphertext:r}=await(0,a.encryptPayload)(_._encryption_private_key,new Uint8Array(e._renc_pub),t);x={_enc:{v:2,pub:_._encryption_public_key,nonce:n},data:r}}let T=(0,s.encode)(E);if(x){const e=(0,s.encode)(x),t=new Uint8Array(T.length+e.length);t.set(T),t.set(e,T.length),T=t}T.length<=_._long_message_chunk_size+1024||u.__no_chunk__?_._emit_message(T).then(function(){S&&S.start(),h||o(null)}).catch(function(e){const t=`Failed to send the request when calling method (${p}:${l}), error: ${e}`;c?c(new Error(t)):_._logger.warn("Unhandled RPC method call error:",t),S&&S.started&&S.clear()}):_._send_chunks(T,p,t).then(function(){S&&S.start(),h||o(null)}).catch(function(e){const t=`Failed to send the request when calling method (${p}:${l}), error: ${e}`;c?c(new Error(t)):_._logger.warn("Unhandled RPC method call error:",t),S&&S.started&&S.clear()})}catch(e){c(e)}})}u.__rpc_object__=e;const p=l.split(".");return u.__name__=e._rname||p[p.length-1],u.__name__.includes("#")&&(u.__name__=u.__name__.split("#")[1]),u.__doc__=e._rdoc||`Remote method: ${l}`,u.__schema__=e._rschema,u.__no_chunk__="services.built-in.message_cache.append"===e._rmethod,u}get_client_info(){const e=[];for(let t of Object.values(this._services))t.config&&t.config._local_only||e.push(this._extract_service_info(t));return{id:this._client_id,services:e}}async _handle_method(e){let t=null,n=null,o=null;try{(0,r.assert)(e.method&&e.ctx&&e.from);const s=e.from+":"+e.method,l=e.from.split("/")[0],h=e.from.split("/")[1];let d;e.to=e.to.includes("/")?e.to:l+"/"+e.to,e.ctx.to=e.to,this._local_workspace?(this._local_workspace&&"*"!==this._local_workspace&&(0,r.assert)(e.to.split("/")[0]===this._local_workspace,"Workspace mismatch: "+e.to.split("/")[0]+" != "+this._local_workspace),d=this._local_workspace):d=e.to.split("/")[0];const _=e.parent;let u,p,f=null;if(e._enc&&this._encryption_enabled){const g=e._enc;if(g&&"object"==typeof g&&2===g.v){f=new Uint8Array(g.pub);const y=new Uint8Array(g.nonce),w=new Uint8Array(e.data);let b;try{b=await(0,a.decryptPayload)(this._encryption_private_key,f,y,w)}catch(E){throw new Error(`Decryption failed for method ${s}. Invalid key or tampered data.`)}const v=[];for(const x of(0,i.decodeMulti)(b))v.push(x);const k=v[0];delete e._enc,delete e.data,Object.assign(e,k),e.ctx.encryption=!0,e.ctx.caller_public_key=(0,a.publicKeyToHex)(f)}}if(e.promise){const S=await this._decode("*"===e.promise?this._expand_promise(e,f):e.promise,e.session,_,l,d);if(t=S.resolve,n=S.reject,S.heartbeat&&S.interval){const T=this;async function C(){try{await S.heartbeat()}catch(e){T._logger.error(e)}}if(o=setInterval(C,1e3*S.interval),e.session){const R=this._get_session_store(e.session,!1);R&&(R.heartbeat_task=o)}}}try{u=m(this._object_store,e.method);const I=e.method.split(".");if(I.length>1){const A=I[0];if("services"!==A&&"message_cache"!==A){const P=this._object_store[A];P&&"object"==typeof P&&(P._last_activity_at=Date.now())}}}catch(j){if(this._is_promise_method_call(e.method))return;const D=e.method.split(".");if(D.length>1){return D[0]in this._object_store?void("function"==typeof n&&n(new Error(`Method expired or not found: ${s}`))):void("function"==typeof n&&n(new Error(`Session not found: ${s}`)))}const O=new Error(`Method not found: ${s} at ${this._client_id}`);return void("function"==typeof n?n(O):this._logger.warn("Method not found and no reject callback:",O.message))}if((0,r.assert)(u&&"function"==typeof u,"Invalid method: "+s),this._method_annotations.has(u)){if("protected"===this._method_annotations.get(u).visibility)if(d===l);else if(this._method_annotations.get(u).authorized_workspaces&&this._method_annotations.get(u).authorized_workspaces.includes(l));else if("*"===l&&h===this._connection.manager_id);else{if(!this._method_annotations.get(u).rintf_allowed_caller)throw new Error("Permission denied for invoking protected method "+s+", workspace mismatch: "+d+" != "+l);{const U=this._method_annotations.get(u).rintf_allowed_caller,M=e.from||"";if(M!==U)throw new Error("Permission denied for _rintf callback "+s+", caller "+M+" is not the allowed caller "+U)}}}else{let $=this._object_store[e.method.split(".")[0]].target_id;if(d===l&&$&&-1===$.indexOf("/")&&($=d+"/"+$),$!==e.from)throw new Error("Access denied for method call ("+s+") from "+e.from+" to target "+$)}if(this._method_annotations.has(u)){const L=this._method_annotations.get(u);if(L.trusted_keys){if(!f)throw new Error(`Encryption required for method ${s} (trusted_keys is set)`);const H=(0,a.publicKeyToHex)(f);if(!L.trusted_keys.has(H))throw new Error(`Caller's public key is not in the trusted keys list for ${s}`)}}if(_&&!e.method.startsWith("services.")&&(0,r.assert)(null!==this._get_session_store(_,!0),"Parent session was closed: "+_),p=e.args?await this._decode(e.args,e.session,null,l,null):[],e.with_kwargs&&p.length>0){const N=p.pop();if("object"==typeof N&&null!==N){const F=c(u);p=F.filter(e=>"context"!==e).map(e=>N[e])}else p.push(N)}if(this._method_annotations.has(u)&&this._method_annotations.get(u).require_context){if(p.length+1<u.length)for(let W=p.length;W<u.length-1;W++)p.push(void 0);p.push(e.ctx)}if(e.promise){const B=u.apply(null,p);B instanceof Promise?B.then(e=>{t(e)}).catch(e=>{n(e)}).finally(()=>{clearInterval(o)}):(t(B),clearInterval(o))}else u.apply(null,p),clearInterval(o)}catch(z){n?n(z):this._logger.error("Error during calling method: ",z),clearInterval(o)}}encode(e,t){return this._encode(e,t)}_get_session_store(e,t){if(!e)return null;let n=this._object_store;const r=e.split(".");if(t){const e=r.length-1;for(let t of r.slice(0,e))n[t]||(n[t]={}),n=n[t];if(!n[r[e]]){n[r[e]]={};const t=Date.now();n[r[e]]._created_at=t,n[r[e]]._last_activity_at=t}return n[r[e]]}for(let e of r){if(!n[e])return null;n=n[e]}return n}async _encode(e,t,n){const o=typeof e;if("number"===o||"string"===o||"boolean"===o||null==e||e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return{_rtype:"memoryview",_rvalue:new Uint8Array(e)};if(e.__rpc_object__){if((e.__rpc_object__._rserver||this._server_base_url)===this._server_base_url)return e.__rpc_object__}let i;if(e.constructor instanceof Object&&e._rtype){const a=e._rtype;return delete e._rtype,i=await this._encode(e,t,n),i._rtype=a,i}if((0,r.isGenerator)(e)||(0,r.isAsyncGenerator)(e)||(0,r.isAsyncIterator)(e)||(0,r.isSyncIterator)(e)){(0,r.assert)(t&&"string"==typeof t,"Session ID is required for generator encoding");const c=(0,r.randId)(),l=c+":close",h=this._get_session_store(t,!0);(0,r.assert)(null!==h,`Failed to create session store ${t} due to invalid parent`);const _=(0,r.isAsyncGenerator)(e)||(0,r.isAsyncIterator)(e),f=async()=>{if(_){const t=await e.next();return t.done?(delete h[c],delete h[l],{_rtype:"stop_iteration"}):t.value}{const t=e.next();return t.done?(delete h[c],delete h[l],{_rtype:"stop_iteration"}):t.value}},g=async()=>{try{"function"==typeof e.return&&(_?await e.return():e.return())}catch(e){}finally{delete h[c],delete h[l]}return!0};return h[c]=f,h[l]=g,i={_rtype:"generator",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:`${t}.${c}`,_rclose_method:`${t}.${l}`,_rpromise:"*",_rdoc:"Remote generator"},i}if("function"==typeof e){if(this._method_annotations.has(e)){let m=this._method_annotations.get(e);i={_rtype:"method",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:m.method_id,_rpromise:"*",_rname:e.name}}else{let y;(0,r.assert)("string"==typeof t),y=e.__name__?`${(0,r.randId)()}#${e.__name__}`:(0,r.randId)(),i={_rtype:"method",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:`${t}.${y}`,_rpromise:"*",_rname:e.name},this._encryption_enabled&&(i._renc_pub=this._encryption_public_key);let w=this._get_session_store(t,!0);(0,r.assert)(null!==w,`Failed to create session store ${t} due to invalid parent`),w[y]=e}if(i._rdoc=e.__doc__,!i._rdoc)try{const v=function(e){const t=e.toString(),n=t.match(/function\s*(\w*)/),r=n&&n[1]||"",o=t.match(/\(([^)]*)\)/);let i="";o&&(i=o[1].split(",").map(e=>e.replace(/\/\*.*?\*\//g,"").replace(/\/\/.*$/g,"")).filter(e=>e.trim().length>0).map(e=>e.trim()).join(", "));let s=t.match(/\)\s*\{\s*\/\*([\s\S]*?)\*\//);const a=s&&s[1].trim()||"";s=t.match(/\)\s*\{\s*(\/\/[\s\S]*?)\n\s*[^\s\/]/);const c=s&&s[1].split("\n").map(e=>e.replace(/^\/\/\s*/,"").trim()).join("\n")||"",l=a||c;return r&&i.length>0&&{name:r,sig:i,doc:l}}(e);v&&!i._rdoc&&(i._rdoc=`${v.doc}`)}catch(k){this._logger.error("Failed to extract function docstring:",e)}return i._rschema=e.__schema__,i}const s=Array.isArray(e);for(let E of Object.keys(this._codecs)){const x=this._codecs[E];if(x.encoder&&e instanceof x.type){let S=await Promise.resolve(x.encoder(e));if(S&&!S._rtype&&(S._rtype=x.name),"object"==typeof S){const T=S._rtype;delete S._rtype,S=await this._encode(S,t,n),S._rtype=T}return i=S,i}}if("undefined"!=typeof tf&&tf.Tensor&&e instanceof tf.Tensor){const C=e.dataSync();i={_rtype:"ndarray",_rvalue:new Uint8Array(C.buffer),_rshape:e.shape,_rdtype:e.dtype}}else if("undefined"!=typeof nj&&nj.NdArray&&e instanceof nj.NdArray){if(!e.selection||!e.selection.data)throw new Error("Invalid NumJS array: missing selection or data");const R=(0,r.typedArrayToDtype)(e.selection.data);i={_rtype:"ndarray",_rvalue:new Uint8Array(e.selection.data.buffer),_rshape:e.shape,_rdtype:R}}else if(e instanceof Error)this._logger.error(e),i={_rtype:"error",_rvalue:e.toString(),_rtrace:e.stack};else if(e!==Object(e)||e instanceof Boolean||e instanceof String||e instanceof Date||e instanceof RegExp||"undefined"!=typeof ImageData&&e instanceof ImageData||"undefined"!=typeof FileList&&e instanceof FileList||"undefined"!=typeof FileSystemDirectoryHandle&&e instanceof FileSystemDirectoryHandle||"undefined"!=typeof FileSystemFileHandle&&e instanceof FileSystemFileHandle||"undefined"!=typeof FileSystemHandle&&e instanceof FileSystemHandle||"undefined"!=typeof FileSystemWritableFileStream&&e instanceof FileSystemWritableFileStream)i=e;else if(e instanceof Blob){let I=0;async function A(t){let n;n=t?e.slice(I,I+t):e.slice(I);const r=new Uint8Array(await n.arrayBuffer());return I+=r.byteLength,r}function P(e){I=e}i={_rtype:"iostream",_rnative:"js:blob",type:e.type,name:e.name,size:e.size,path:e._path||e.webkitRelativePath,read:await this._encode(A,t,n),seek:await this._encode(P,t,n)}}else if(e instanceof d){const j=(0,r.typedArrayToDtype)(e);i={_rtype:"typedarray",_rvalue:new Uint8Array(e.buffer),_rdtype:j}}else if(e instanceof DataView)i={_rtype:"memoryview",_rvalue:new Uint8Array(e.buffer)};else if(e instanceof Set)i={_rtype:"set",_rvalue:await this._encode(Array.from(e),t,n)};else if(e instanceof Map)i={_rtype:"orderedmap",_rvalue:await this._encode(Array.from(e),t,n)};else{if(!(e.constructor===Object||Array.isArray(e)||e instanceof b))throw`hypha-rpc: Unsupported data type: ${e}, you can register a custom codec to encode/decode the object.`;{if(!s&&!0===e._rintf&&Object.keys(e).some(t=>!t.startsWith("_")&&"function"==typeof e[t])){const O=`_rintf_${(0,r.randId)()}`;let U=null;if(t){const L=t.split(".")[0],H=this._object_store[L];H&&H.target_id&&(U=H.target_id)}const M={id:O,config:{visibility:"protected",_local_only:!0}};U&&(M.config._rintf_allowed_caller=U);const $=this;M._dispose=()=>{$._unregisterRintfService(O,U)};for(const N of Object.keys(e))N.startsWith("_")||"function"!=typeof e[N]||(M[N]=e[N]);this.add_service(M,!0),U&&(this._rintfCallerIndex[U]||(this._rintfCallerIndex[U]=new Set),this._rintfCallerIndex[U].add(O)),e._rintf_service_id=O,i={};for(const F of Object.keys(e))i[F]=await this._encode(e[F],t,n);return i._dispose=await this._encode(M._dispose,t,n),i._rintf_service_id=O,i}if(s){if(u(e))return e}else if(!("_rtype"in e||e instanceof b)&&p(e))return e;i=s?[]:{};const D=Object.keys(e);for(let W of D)i[W]=await this._encode(e[W],t,n)}}if(!i)throw new Error("Failed to encode object");return i}async decode(e){return await this._decode(e)}async _decode(e,t,n,o,i){if(!e)return e;let s;if(e._rtype)if(this._codecs[e._rtype]&&this._codecs[e._rtype].decoder){const a=e._rtype;delete e._rtype,(e=await this._decode(e,t,n,o,i))._rtype=a,s=await Promise.resolve(this._codecs[e._rtype].decoder(e))}else if("method"===e._rtype)s=this._generate_remote_method(e,t,n,o,i);else if("generator"===e._rtype){const c=this._logger,l=this._generate_remote_method(e,t,n,o,i);let h=null;if(e._rclose_method){const _={_rtype:"method",_rserver:e._rserver,_rtarget:e._rtarget,_rmethod:e._rclose_method,_rpromise:"*"};h=this._generate_remote_method(_,t,n,o,i)}async function*d(){let e=!1;try{for(;;){const t=await l();if(t&&"stop_iteration"===t._rtype){e=!0;break}yield t}}catch(e){throw c.error("Error in generator:",e),e}finally{if(!e&&h)try{await h()}catch(e){}}}s=d()}else if("ndarray"===e._rtype)if("undefined"!=typeof nj&&nj.array)Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(f)),s=nj.array(new Uint8(e._rvalue),e._rdtype).reshape(e._rshape);else if("undefined"!=typeof tf&&tf.Tensor){Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(f));const g=r.dtypeToTypedArray[e._rdtype];s=tf.tensor(new g(e._rvalue),e._rshape,e._rdtype)}else s=e;else if("error"===e._rtype)s=new Error("RemoteError: "+e._rvalue+"\n"+(e._rtrace||""));else if("typedarray"===e._rtype){const m=r.dtypeToTypedArray[e._rdtype];if(!m)throw new Error("unsupported dtype: "+e._rdtype);s=new m(e._rvalue.buffer.slice(e._rvalue.byteOffset,e._rvalue.byteOffset+e._rvalue.byteLength))}else if("memoryview"===e._rtype)s=e._rvalue.buffer.slice(e._rvalue.byteOffset,e._rvalue.byteOffset+e._rvalue.byteLength);else if("iostream"===e._rtype){if("js:blob"===e._rnative){const y=await this._generate_remote_method(e.read,t,n,o,i),w=await y();s=new Blob([w],{type:e.type,name:e.name})}else{s={};for(let b of Object.keys(e))b.startsWith("_")||(s[b]=await this._decode(e[b],t,n,o,i))}s.__rpc_object__=e}else if("orderedmap"===e._rtype)s=new Map(await this._decode(e._rvalue,t,n,o,i));else if("set"===e._rtype)s=new Set(await this._decode(e._rvalue,t,n,o,i));else{const v=e._rtype;delete e._rtype,s=await this._decode(e,t,n,o,i),s._rtype=v}else if(e.constructor===Object||Array.isArray(e)){const k=Array.isArray(e);if(k){if(u(e))return e}else if(p(e))return e;s=k?[]:{};for(let E of Object.keys(e))if(k||e.hasOwnProperty(E)){const x=e[E];s[E]=await this._decode(x,t,n,o,i)}}else s=e;if(void 0===s)throw new Error("Failed to decode object");return s}_expand_promise(e,t){const n=e.from.split("/")[1],r=e.session,o=e.method,i={_rtype:"method",_rtarget:n,_rmethod:`${r}.heartbeat`,_rdoc:`heartbeat callback for method: ${o}`},s={_rtype:"method",_rtarget:n,_rmethod:`${r}.resolve`,_rdoc:`resolve callback for method: ${o}`},a={_rtype:"method",_rtarget:n,_rmethod:`${r}.reject`,_rdoc:`reject callback for method: ${o}`};return t&&(i._renc_pub=t,s._renc_pub=t,a._renc_pub=t),{heartbeat:i,resolve:s,reject:a,interval:e.t}}}},"./src/utils/index.js":
8
14
  /*!****************************!*\
9
15
  !*** ./src/utils/index.js ***!
10
16
  \****************************/(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{function randId(){return Math.random().toString(36).substr(2,10)+(new Date).getTime()}function toCamelCase(e){return e.includes("_")?e.replace(/_./g,e=>e[1].toUpperCase()):e}function toSnakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function expandKwargs(e){if("object"!=typeof e||null===e)return e;const t=Array.isArray(e)?[]:{};for(const n in e)if(e.hasOwnProperty(n)){const r=e[n];"function"==typeof r?(t[n]=(...e)=>{if(0===e.length)throw new Error(`Function "${n}" expects at least one argument.`);const t=e[e.length-1];let o={};return"object"!=typeof t||null===t||Array.isArray(t)||(o={...t,_rkwarg:!0},e=e.slice(0,-1)),r(...e,o)},t[n].__name__=n,r.__schema__&&(t[n].__schema__={...r.__schema__},t[n].__schema__.name=n)):t[n]=expandKwargs(r)}return t}function convertCase(e,t){if("object"!=typeof e||null===e||!t)return e;const n=Array.isArray(e)?[]:{};for(const r in e)if(e.hasOwnProperty(r)){const o=e[r],i=toCamelCase(r),s=toSnakeCase(r);"camel"===t?(n[i]=convertCase(o,t),"function"==typeof o&&(n[i].__name__=i,o.__schema__&&(n[i].__schema__={...o.__schema__},n[i].__schema__.name=i))):"snake"===t?(n[s]=convertCase(o,t),"function"==typeof o&&(n[s].__name__=s,o.__schema__&&(n[s].__schema__={...o.__schema__},n[s].__schema__.name=s))):(t.includes("camel")&&(n[i]=convertCase(o,"camel")),t.includes("snake")&&(n[s]=convertCase(o,"snake")))}return n}function parseServiceUrl(e){e=e.replace(/\/$/,"");const t=new RegExp("^(https?:\\/\\/[^/]+)\\/([a-z0-9_-]+)\\/services\\/(?:(?<clientId>[a-zA-Z0-9_-]+):)?(?<serviceId>[a-zA-Z0-9_-]+)(?:@(?<appId>[a-zA-Z0-9_-]+))?"),n=e.match(t);if(!n)throw new Error("URL does not match the expected pattern");const r=n[1],o=n[2],i=n.groups?.clientId||"*",s=n.groups?.serviceId;return{serverUrl:r,workspace:o,clientId:i,serviceId:s,appId:n.groups?.appId||"*"}}__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{MessageEmitter:()=>MessageEmitter,Semaphore:()=>Semaphore,assert:()=>assert,cacheRequirements:()=>cacheRequirements,convertCase:()=>convertCase,dtypeToTypedArray:()=>dtypeToTypedArray,expandKwargs:()=>expandKwargs,isAsyncGenerator:()=>isAsyncGenerator,isAsyncIterator:()=>isAsyncIterator,isGenerator:()=>isGenerator,isSyncIterator:()=>isSyncIterator,loadRequirements:()=>loadRequirements,loadRequirementsInWebworker:()=>loadRequirementsInWebworker,loadRequirementsInWindow:()=>loadRequirementsInWindow,normalizeConfig:()=>normalizeConfig,parseServiceUrl:()=>parseServiceUrl,randId:()=>randId,toCamelCase:()=>toCamelCase,toSnakeCase:()=>toSnakeCase,typedArrayToDtype:()=>typedArrayToDtype,typedArrayToDtypeMapping:()=>typedArrayToDtypeMapping,urlJoin:()=>urlJoin,waitFor:()=>waitFor});const dtypeToTypedArray={int8:Int8Array,int16:Int16Array,int32:Int32Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,float32:Float32Array,float64:Float64Array,array:Array};async function loadRequirementsInWindow(e){function t(e){return new Promise((t,n)=>{var r=document.createElement("script");r.src=e,r.type="text/javascript",r.onload=t,r.onreadystatechange=function(){"loaded"!==this.readyState&&"complete"!==this.readyState||t()},r.onerror=n,document.head.appendChild(r)})}async function n(){for(var e=Array.prototype.slice.call(arguments),n=e.length,r=0;r<n;r++)await t(e[r])}if(e&&(Array.isArray(e)||"string"==typeof e))try{var r;if(e="string"==typeof e?[e]:e,!Array.isArray(e))throw"unsupported requirements definition";for(var o=0;o<e.length;o++)e[o].toLowerCase().endsWith(".css")||e[o].startsWith("css:")?(e[o].startsWith("css:")&&(e[o]=e[o].slice(4)),(r=document.createElement("link")).rel="stylesheet",r.href=e[o],document.head.appendChild(r)):e[o].toLowerCase().endsWith(".mjs")||e[o].startsWith("mjs:")?(e[o].startsWith("mjs:")&&(e[o]=e[o].slice(4)),await new Function("url","return import(url)")(e[o])):e[o].toLowerCase().endsWith(".js")||e[o].startsWith("js:")?(e[o].startsWith("js:")&&(e[o]=e[o].slice(3)),await n(e[o])):e[o].startsWith("http")?await n(e[o]):e[o].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[o])}catch(t){throw"failed to import required scripts: "+e.toString()}}async function loadRequirementsInWebworker(e){if(e&&(Array.isArray(e)||"string"==typeof e))try{Array.isArray(e)||(e=[e]);for(var t=0;t<e.length;t++){if(e[t].toLowerCase().endsWith(".css")||e[t].startsWith("css:"))throw"unable to import css in a webworker";e[t].toLowerCase().endsWith(".js")||e[t].startsWith("js:")?(e[t].startsWith("js:")&&(e[t]=e[t].slice(3)),importScripts(e[t])):e[t].startsWith("http")?importScripts(e[t]):e[t].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[t])}}catch(t){throw"failed to import required scripts: "+e.toString()}}function loadRequirements(e){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?loadRequirementsInWebworker(e):loadRequirementsInWindow(e)}function normalizeConfig(e){return e.version=e.version||"0.1.0",e.description=e.description||`[TODO: add description for ${e.name} ]`,e.type=e.type||"rpc-window",e.id=e.id||randId(),e.target_origin=e.target_origin||"*",e.allow_execution=e.allow_execution||!1,e=Object.keys(e).reduce((t,n)=>("function"!=typeof e[n]&&(t[n]=e[n]),t),{})}const typedArrayToDtypeMapping={Int8Array:"int8",Int16Array:"int16",Int32Array:"int32",Uint8Array:"uint8",Uint16Array:"uint16",Uint32Array:"uint32",Float32Array:"float32",Float64Array:"float64",Array:"array"},typedArrayToDtypeKeys=[];for(const arrType of Object.keys(typedArrayToDtypeMapping))typedArrayToDtypeKeys.push(eval(arrType));function typedArrayToDtype(e){let t=typedArrayToDtypeMapping[e.constructor.name];if(!t){const n=Object.getPrototypeOf(e);for(const e of typedArrayToDtypeKeys)if(n instanceof e){t=typedArrayToDtypeMapping[e.name];break}}return t}function cacheUrlInServiceWorker(e){return new Promise(function(t,n){const r={command:"add",url:e};if(!navigator.serviceWorker||!navigator.serviceWorker.register)return void n("Service worker is not supported.");const o=new MessageChannel;o.port1.onmessage=function(e){e.data&&e.data.error?n(e.data.error):t(e.data&&e.data.result)},navigator.serviceWorker&&navigator.serviceWorker.controller?navigator.serviceWorker.controller.postMessage(r,[o.port2]):n("Service worker controller is not available")})}async function cacheRequirements(e){e=e||[],Array.isArray(e)||(e=[e]);for(let t of e)t.startsWith("js:")&&(t=t.slice(3)),t.startsWith("css:")&&(t=t.slice(4)),t.startsWith("cache:")&&(t=t.slice(6)),t.startsWith("http")&&await cacheUrlInServiceWorker(t).catch(e=>{console.error(e)})}function assert(e,t){if(!e)throw new Error(t||"Assertion failed")}function urlJoin(...e){return e.join("/").replace(/[\/]+/g,"/").replace(/^(.+):\//,"$1://").replace(/^file:/,"file:/").replace(/\/(\?|&|#[^!])/g,"$1").replace(/\?/g,"&").replace("&","?")}function waitFor(e,t,n){let r;return Promise.race([e,new Promise((e,o)=>r=setTimeout(()=>{o(n||"Timeout Error")},1e3*t))]).finally(()=>clearTimeout(r))}class MessageEmitter{constructor(e){this._event_handlers={},this._once_handlers={},this._debug=e}emit(){throw new Error("emit is not implemented")}on(e,t){this._event_handlers[e]||(this._event_handlers[e]=[]),this._event_handlers[e].push(t)}once(e,t){t.___event_run_once=!0,this.on(e,t)}off(e,t){if(e||t){if(e&&!t)this._event_handlers[e]&&(this._event_handlers[e]=[]);else if(this._event_handlers[e]){const n=this._event_handlers[e].indexOf(t);n>=0&&this._event_handlers[e].splice(n,1)}}else this._event_handlers={}}_fire(e,t){if(this._event_handlers[e])for(var n=this._event_handlers[e].length;n--;){const r=this._event_handlers[e][n];try{r(t)}catch(e){console.error(e)}finally{r.___event_run_once&&this._event_handlers[e].splice(n,1)}}else this._debug&&console.warn("unhandled event",e,t)}waitFor(e,t){return new Promise((n,r)=>{const o=e=>{clearTimeout(i),n(e)};this.once(e,o);const i=setTimeout(()=>{this.off(e,o),r(new Error("Timeout"))},1e3*t)})}}class Semaphore{constructor(e){this.max=e,this.queue=[],this.current=0}async run(e){this.current>=this.max&&await new Promise(e=>this.queue.push(e)),this.current++;try{return await e()}finally{this.current--,this.queue.length>0&&this.queue.shift()()}}}function isGenerator(e){return!!e&&("object"==typeof e&&"function"==typeof e.next&&"function"==typeof e.throw&&"function"==typeof e.return)}function isAsyncGenerator(e){return!!e&&("object"==typeof e&&"function"==typeof e.next&&"function"==typeof e.throw&&"function"==typeof e.return&&Symbol.asyncIterator in Object(e)&&"AsyncGenerator"===e[Symbol.toStringTag])}function isAsyncIterator(e){return!(!e||isAsyncGenerator(e))&&("object"==typeof e&&Symbol.asyncIterator in Object(e)&&"function"==typeof e.next)}function isSyncIterator(e){return!(!e||isGenerator(e))&&("object"==typeof e&&Symbol.iterator in Object(e)&&"function"==typeof e.next&&!Array.isArray(e)&&"string"!=typeof e)}},"./src/utils/schema.js":
11
17
  /*!*****************************!*\
12
18
  !*** ./src/utils/schema.js ***!
13
- \*****************************/(e,t,n)=>{n.r(t),n.d(t,{schemaFunction:()=>i,z:()=>o});var r=n(/*! ./index.js */"./src/utils/index.js");const o={object:e=>({type:"object",properties:e,required:Object.keys(e).filter(t=>!e[t]._optional)}),string:()=>({type:"string",_optional:!1}),number:()=>({type:"number",_optional:!1}),integer:()=>({type:"integer",_optional:!1}),boolean:()=>({type:"boolean",_optional:!1}),array:e=>({type:"array",items:e,_optional:!1}),optional:e=>({...e,_optional:!0})};function i(e,{schema_type:t="auto",name:n=null,description:o=null,parameters:i=null}){if(!e||"function"!=typeof e)throw Error("func should be a function");(0,r.assert)("auto"===t,"schema_type should be auto");const s=n||e.name;(0,r.assert)(s,"name should not be null");let c=i;if(i&&"object"==typeof i&&"object"===i.type){c={type:"object",properties:i.properties||{},required:i.required||[]};for(const[e,t]of Object.entries(c.properties))void 0!==t._optional&&delete t._optional}return(0,r.assert)(c&&"object"===c.type,"parameters should be an object schema"),e.__schema__={name:s,description:o||"",parameters:c},e}["string","number","integer","boolean","array"].forEach(e=>{o[e]=()=>{const t={type:"integer"===e?"integer":e,_optional:!1,describe:e=>({...t,description:e})};return t}})},"./src/webrtc-client.js":
19
+ \*****************************/(e,t,n)=>{n.r(t),n.d(t,{schemaFunction:()=>i,z:()=>o});var r=n(/*! ./index.js */"./src/utils/index.js");const o={object:e=>({type:"object",properties:e,required:Object.keys(e).filter(t=>!e[t]._optional)}),string:()=>({type:"string",_optional:!1}),number:()=>({type:"number",_optional:!1}),integer:()=>({type:"integer",_optional:!1}),boolean:()=>({type:"boolean",_optional:!1}),array:e=>({type:"array",items:e,_optional:!1}),optional:e=>({...e,_optional:!0})};function i(e,{schema_type:t="auto",name:n=null,description:o=null,parameters:i=null}){if(!e||"function"!=typeof e)throw Error("func should be a function");(0,r.assert)("auto"===t,"schema_type should be auto");const s=n||e.name;(0,r.assert)(s,"name should not be null");let a=i;if(i&&"object"==typeof i&&"object"===i.type){a={type:"object",properties:i.properties||{},required:i.required||[]};for(const[e,t]of Object.entries(a.properties))void 0!==t._optional&&delete t._optional}return(0,r.assert)(a&&"object"===a.type,"parameters should be an object schema"),e.__schema__={name:s,description:o||"",parameters:a},e}["string","number","integer","boolean","array"].forEach(e=>{o[e]=()=>{const t={type:"integer"===e?"integer":e,_optional:!1,describe:e=>({...t,description:e})};return t}})},"./src/webrtc-client.js":
14
20
  /*!******************************!*\
15
21
  !*** ./src/webrtc-client.js ***!
16
- \******************************/(e,t,n)=>{n.r(t),n.d(t,{getRTCService:()=>a,registerRTCService:()=>l});var r=n(/*! ./rpc.js */"./src/rpc.js"),o=n(/*! ./utils/index.js */"./src/utils/index.js"),i=n(/*! ./utils/schema.js */"./src/utils/schema.js");class s{constructor(e){this._data_channel=e,this._handle_message=null,this._reconnection_token=null,this._handle_disconnected=null,this._handle_connected=()=>{},this.manager_id=null,this._data_channel.onopen=async()=>{this._handle_connected&&this._handle_connected({channel:this._data_channel})},this._data_channel.onmessage=async e=>{let t=e.data;t instanceof Blob&&(t=await t.arrayBuffer()),this._handle_message&&this._handle_message(t)},this._data_channel.onclose=()=>{this._handle_disconnected&&this._handle_disconnected("closed"),console.log("data channel closed"),this._data_channel=null}}on_disconnected(e){this._handle_disconnected=e}on_connected(e){this._handle_connected=e}on_message(e){(0,o.assert)(e,"handler is required"),this._handle_message=e}async emit_message(e){(0,o.assert)(this._handle_message,"No handler for message");try{this._data_channel.send(e)}catch(e){throw console.error(`Failed to send data, error: ${e}`),e}}async disconnect(e){this._data_channel=null,console.info(`data channel connection disconnected (${e})`)}}async function c(e){(0,o.assert)(e.channel,"No channel provided"),(0,o.assert)(e.workspace,"No workspace provided");const t=e.channel,n=e.client_id||(0,o.randId)(),i=new s(t);e.context=e.context||{},e.context.connection_type="webrtc",e.context.ws=e.workspace;return new r.RPC(i,{client_id:n,default_context:e.context,name:e.name,method_timeout:e.method_timeout||10,workspace:e.workspace,app_id:e.app_id,long_message_chunk_size:e.long_message_chunk_size})}async function a(e,t,n){(n=n||{}).peer_id=n.peer_id||(0,o.randId)();const r=new RTCPeerConnection({iceServers:n.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});return new Promise(async(s,a)=>{let l=!1;const d=setTimeout(()=>{l||(l=!0,r.close(),a(new Error("WebRTC Connection timeout")))},3e4);try{r.addEventListener("connectionstatechange",()=>{console.log("WebRTC Connection state: ",r.connectionState),"failed"===r.connectionState?l||(l=!0,clearTimeout(d),r.close(),a(new Error("WebRTC Connection failed"))):"closed"===r.connectionState?l||(l=!0,clearTimeout(d),a(new Error("WebRTC Connection closed"))):"connected"===r.connectionState&&console.log("WebRTC Connection established successfully")},!1),r.addEventListener("iceconnectionstatechange",()=>{console.log("ICE Connection state: ",r.iceConnectionState),"failed"===r.iceConnectionState&&(l||(l=!0,clearTimeout(d),r.close(),a(new Error("ICE Connection failed"))))}),n.on_init&&(await n.on_init(r),delete n.on_init);let h=r.createDataChannel(n.peer_id,{ordered:!0});h.binaryType="arraybuffer";const u=await r.createOffer();await r.setLocalDescription(u),await new Promise(e=>{"complete"===r.iceGatheringState?e():(r.addEventListener("icegatheringstatechange",()=>{"complete"===r.iceGatheringState&&e()}),setTimeout(e,5e3))});const p=await e.getService(t),_=await p.offer({sdp:r.localDescription.sdp,type:r.localDescription.type});h.onopen=()=>{n.channel=h,n.workspace=_.workspace,setTimeout(async()=>{if(!l)try{const e=await c(n);async function t(t,...r){return(0,o.assert)(!t.includes(":"),"WebRTC service name should not contain ':'"),(0,o.assert)(!t.includes("/"),"WebRTC service name should not contain '/'"),await e.get_remote_service(n.workspace+"/"+n.peer_id+":"+t,...r)}async function h(){await e.disconnect(),r.close()}r.rpc=e,r.getService=(0,i.schemaFunction)(t,{name:"getService",description:"Get a remote service via webrtc",parameters:{type:"object",properties:{service_id:{type:"string",description:"Service ID. This should be a service id in the format: 'workspace/service_id', 'workspace/client_id:service_id' or 'workspace/client_id:service_id@app_id'"},config:{type:"object",description:"Options for the service"}},required:["id"]}}),r.disconnect=(0,i.schemaFunction)(h,{name:"disconnect",description:"Disconnect from the webrtc connection via webrtc",parameters:{type:"object",properties:{}}}),r.registerCodec=(0,i.schemaFunction)(e.register_codec,{name:"registerCodec",description:"Register a codec for the webrtc connection",parameters:{type:"object",properties:{codec:{type:"object",description:"Codec to register",properties:{name:{type:"string"},type:{},encoder:{type:"function"},decoder:{type:"function"}}}}}}),l=!0,clearTimeout(d),s(r)}catch(u){l||(l=!0,clearTimeout(d),a(u))}},1e3)},h.onclose=()=>{l||(l=!0,clearTimeout(d),a(new Error("Data channel closed")))},h.onerror=e=>{l||(l=!0,clearTimeout(d),a(new Error(`Data channel error: ${e}`)))},await r.setRemoteDescription(new RTCSessionDescription({sdp:_.sdp,type:_.type}))}catch(e){l||(l=!0,clearTimeout(d),a(e))}})}async function l(e,t,n){const r=(n=n||{visibility:"protected",require_context:!0}).on_init;return delete n.on_init,await e.registerService({id:t,config:n,offer:(t,o)=>async function(e,t,n,r,o){n=n||{};let i=new RTCSessionDescription({sdp:e.sdp,type:e.type}),s=new RTCPeerConnection({iceServers:n.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});t&&s.addEventListener("datachannel",async e=>{const n=e.channel;let r=null;o&&o.user&&(r={user:o.user,ws:o.ws}),(await c({channel:n,client_id:n.label,workspace:t.config.workspace,context:r}))._services=t.rpc._services}),r&&await r(s),await s.setRemoteDescription(i);let a=await s.createAnswer();return await s.setLocalDescription(a),await new Promise(e=>{"complete"===s.iceGatheringState?e():(s.addEventListener("icegatheringstatechange",()=>{"complete"===s.iceGatheringState&&e()}),setTimeout(e,5e3))}),{sdp:s.localDescription.sdp,type:s.localDescription.type,workspace:t.config.workspace}}(t,e,n,r,o)})}},"./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs":
22
+ \******************************/(e,t,n)=>{n.r(t),n.d(t,{getRTCService:()=>c,registerRTCService:()=>l});var r=n(/*! ./rpc.js */"./src/rpc.js"),o=n(/*! ./utils/index.js */"./src/utils/index.js"),i=n(/*! ./utils/schema.js */"./src/utils/schema.js");class s{constructor(e){this._data_channel=e,this._handle_message=null,this._reconnection_token=null,this._handle_disconnected=null,this._handle_connected=()=>{},this.manager_id=null,this._data_channel.onopen=async()=>{this._handle_connected&&this._handle_connected({channel:this._data_channel})},this._data_channel.onmessage=async e=>{let t=e.data;t instanceof Blob&&(t=await t.arrayBuffer()),this._handle_message&&this._handle_message(t)},this._data_channel.onclose=()=>{this._handle_disconnected&&this._handle_disconnected("closed"),console.log("data channel closed"),this._data_channel=null}}on_disconnected(e){this._handle_disconnected=e}on_connected(e){this._handle_connected=e}on_message(e){(0,o.assert)(e,"handler is required"),this._handle_message=e}async emit_message(e){(0,o.assert)(this._handle_message,"No handler for message");try{this._data_channel.send(e)}catch(e){throw console.error(`Failed to send data, error: ${e}`),e}}async disconnect(e){this._data_channel=null,console.info(`data channel connection disconnected (${e})`)}}async function a(e){(0,o.assert)(e.channel,"No channel provided"),(0,o.assert)(e.workspace,"No workspace provided");const t=e.channel,n=e.client_id||(0,o.randId)(),i=new s(t);e.context=e.context||{},e.context.connection_type="webrtc",e.context.ws=e.workspace;return new r.RPC(i,{client_id:n,default_context:e.context,name:e.name,method_timeout:e.method_timeout||10,workspace:e.workspace,app_id:e.app_id,long_message_chunk_size:e.long_message_chunk_size,silent:e.silent||!1})}async function c(e,t,n){(n=n||{}).peer_id=n.peer_id||(0,o.randId)();const r=new RTCPeerConnection({iceServers:n.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});return new Promise(async(s,c)=>{let l=!1;const h=setTimeout(()=>{l||(l=!0,r.close(),c(new Error("WebRTC Connection timeout")))},3e4);try{r.addEventListener("connectionstatechange",()=>{console.log("WebRTC Connection state: ",r.connectionState),"failed"===r.connectionState?l||(l=!0,clearTimeout(h),r.close(),c(new Error("WebRTC Connection failed"))):"closed"===r.connectionState?l||(l=!0,clearTimeout(h),c(new Error("WebRTC Connection closed"))):"connected"===r.connectionState&&console.log("WebRTC Connection established successfully")},!1),r.addEventListener("iceconnectionstatechange",()=>{console.log("ICE Connection state: ",r.iceConnectionState),"failed"===r.iceConnectionState&&(l||(l=!0,clearTimeout(h),r.close(),c(new Error("ICE Connection failed"))))}),n.on_init&&(await n.on_init(r),delete n.on_init);let d=r.createDataChannel(n.peer_id,{ordered:!0});d.binaryType="arraybuffer";const _=await r.createOffer();await r.setLocalDescription(_),await new Promise(e=>{"complete"===r.iceGatheringState?e():(r.addEventListener("icegatheringstatechange",()=>{"complete"===r.iceGatheringState&&e()}),setTimeout(e,5e3))});const u=await e.getService(t),p=await u.offer({sdp:r.localDescription.sdp,type:r.localDescription.type});d.onopen=()=>{n.channel=d,n.workspace=p.workspace,setTimeout(async()=>{if(!l)try{const e=await a(n);async function t(t,...r){return(0,o.assert)(!t.includes(":"),"WebRTC service name should not contain ':'"),(0,o.assert)(!t.includes("/"),"WebRTC service name should not contain '/'"),await e.get_remote_service(n.workspace+"/"+n.peer_id+":"+t,...r)}async function d(){await e.disconnect(),r.close()}r.rpc=e,r.getService=(0,i.schemaFunction)(t,{name:"getService",description:"Get a remote service via webrtc",parameters:{type:"object",properties:{service_id:{type:"string",description:"Service ID. This should be a service id in the format: 'workspace/service_id', 'workspace/client_id:service_id' or 'workspace/client_id:service_id@app_id'"},config:{type:"object",description:"Options for the service"}},required:["id"]}}),r.disconnect=(0,i.schemaFunction)(d,{name:"disconnect",description:"Disconnect from the webrtc connection via webrtc",parameters:{type:"object",properties:{}}}),r.registerCodec=(0,i.schemaFunction)(e.register_codec,{name:"registerCodec",description:"Register a codec for the webrtc connection",parameters:{type:"object",properties:{codec:{type:"object",description:"Codec to register",properties:{name:{type:"string"},type:{},encoder:{type:"function"},decoder:{type:"function"}}}}}}),l=!0,clearTimeout(h),s(r)}catch(_){l||(l=!0,clearTimeout(h),c(_))}},1e3)},d.onclose=()=>{l||(l=!0,clearTimeout(h),c(new Error("Data channel closed")))},d.onerror=e=>{l||(l=!0,clearTimeout(h),c(new Error(`Data channel error: ${e}`)))},await r.setRemoteDescription(new RTCSessionDescription({sdp:p.sdp,type:p.type}))}catch(e){l||(l=!0,clearTimeout(h),c(e))}})}async function l(e,t,n){const r=(n=n||{visibility:"protected",require_context:!0}).on_init;return delete n.on_init,await e.registerService({id:t,config:n,offer:(t,o)=>async function(e,t,n,r,o){n=n||{};let i=new RTCSessionDescription({sdp:e.sdp,type:e.type}),s=new RTCPeerConnection({iceServers:n.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});t&&s.addEventListener("datachannel",async e=>{const n=e.channel;let r=null;o&&o.user&&(r={user:o.user,ws:o.ws}),(await a({channel:n,client_id:n.label,workspace:t.config.workspace,context:r}))._services=t.rpc._services}),r&&await r(s),await s.setRemoteDescription(i);let c=await s.createAnswer();return await s.setLocalDescription(c),await new Promise(e=>{"complete"===s.iceGatheringState?e():(s.addEventListener("icegatheringstatechange",()=>{"complete"===s.iceGatheringState&&e()}),setTimeout(e,5e3))}),{sdp:s.localDescription.sdp,type:s.localDescription.type,workspace:t.config.workspace}}(t,e,n,r,o)})}},"?dba7":
23
+ /*!************************!*\
24
+ !*** crypto (ignored) ***!
25
+ \************************/()=>{},"./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs":
17
26
  /*!*************************************************************************!*\
18
27
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs ***!
19
- \*************************************************************************/(e,t,n)=>{n.r(t),n.d(t,{CachedKeyDecoder:()=>o});var r=n(/*! ./utils/utf8.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs"),o=function(){function e(e,t){void 0===e&&(e=16),void 0===t&&(t=16),this.maxKeyLength=e,this.maxLengthPerKey=t,this.hit=0,this.miss=0,this.caches=[];for(var n=0;n<this.maxKeyLength;n++)this.caches.push([])}return e.prototype.canBeCached=function(e){return e>0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,n){e:for(var r=0,o=this.caches[n-1];r<o.length;r++){for(var i=o[r],s=i.bytes,c=0;c<n;c++)if(s[c]!==e[t+c])continue e;return i.str}return null},e.prototype.store=function(e,t){var n=this.caches[e.length-1],r={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)},e.prototype.decode=function(e,t,n){var o=this.find(e,t,n);if(null!=o)return this.hit++,o;this.miss++;var i=(0,r.utf8DecodeJs)(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,i),i},e}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs":
28
+ \*************************************************************************/(e,t,n)=>{n.r(t),n.d(t,{CachedKeyDecoder:()=>o});var r=n(/*! ./utils/utf8.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs"),o=function(){function e(e,t){void 0===e&&(e=16),void 0===t&&(t=16),this.maxKeyLength=e,this.maxLengthPerKey=t,this.hit=0,this.miss=0,this.caches=[];for(var n=0;n<this.maxKeyLength;n++)this.caches.push([])}return e.prototype.canBeCached=function(e){return e>0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,n){e:for(var r=0,o=this.caches[n-1];r<o.length;r++){for(var i=o[r],s=i.bytes,a=0;a<n;a++)if(s[a]!==e[t+a])continue e;return i.str}return null},e.prototype.store=function(e,t){var n=this.caches[e.length-1],r={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=r:n.push(r)},e.prototype.decode=function(e,t,n){var o=this.find(e,t,n);if(null!=o)return this.hit++,o;this.miss++;var i=(0,r.utf8DecodeJs)(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,i),i},e}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs":
20
29
  /*!********************************************************************!*\
21
30
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs ***!
22
31
  \********************************************************************/(e,t,n)=>{n.r(t),n.d(t,{DecodeError:()=>i});var r,o=(r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},r(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),i=function(e){function t(n){var r=e.call(this,n)||this,o=Object.create(t.prototype);return Object.setPrototypeOf(r,o),Object.defineProperty(r,"name",{configurable:!0,enumerable:!1,value:t.name}),r}return o(t,e),t}(Error)},"./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs":
23
32
  /*!****************************************************************!*\
24
33
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs ***!
25
- \****************************************************************/(e,t,n)=>{n.r(t),n.d(t,{DataViewIndexOutOfBoundsError:()=>y,Decoder:()=>v});var r=n(/*! ./utils/prettyByte.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs"),o=n(/*! ./ExtensionCodec.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs"),i=n(/*! ./utils/int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),s=n(/*! ./utils/utf8.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs"),c=n(/*! ./utils/typedArrays.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs"),a=n(/*! ./CachedKeyDecoder.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs"),l=n(/*! ./DecodeError.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs"),d=function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function s(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,c)}a((r=r.apply(e,t||[])).next())})},h=function(e,t){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}},u=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise(function(r,o){(function(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)})(r,o,(t=e[n](t)).done,t.value)})}}},p=function(e){return this instanceof p?(this.v=e,this):new p(e)},_=function(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,o=n.apply(e,t||[]),i=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(e){o[e]&&(r[e]=function(t){return new Promise(function(n,r){i.push([e,t,n,r])>1||c(e,t)})})}function c(e,t){try{(n=o[e](t)).value instanceof p?Promise.resolve(n.value.v).then(a,l):d(i[0][2],n)}catch(e){d(i[0][3],e)}var n}function a(e){c("next",e)}function l(e){c("throw",e)}function d(e,t){e(t),i.shift(),i.length&&c(i[0][0],i[0][1])}},f=function(e){var t=typeof e;return"string"===t||"number"===t},m=new DataView(new ArrayBuffer(0)),g=new Uint8Array(m.buffer),y=function(){try{m.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),w=new y("Insufficient data"),b=new a.CachedKeyDecoder,v=function(){function e(e,t,n,r,s,c,a,l){void 0===e&&(e=o.ExtensionCodec.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=i.UINT32_MAX),void 0===r&&(r=i.UINT32_MAX),void 0===s&&(s=i.UINT32_MAX),void 0===c&&(c=i.UINT32_MAX),void 0===a&&(a=i.UINT32_MAX),void 0===l&&(l=b),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=s,this.maxMapLength=c,this.maxExtLength=a,this.keyDecoder=l,this.totalPos=0,this.pos=0,this.view=m,this.bytes=g,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=(0,c.ensureUint8Array)(e),this.view=(0,c.createDataView)(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining(1)){var t=this.bytes.subarray(this.pos),n=(0,c.ensureUint8Array)(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra ".concat(t.byteLength-n," of ").concat(t.byteLength," byte(s) found at buffer[").concat(e,"]"))},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return h(this,function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}})},e.prototype.decodeAsync=function(e){var t,n,o,i;return d(this,void 0,void 0,function(){var s,c,a,l,d,p,_,f;return h(this,function(h){switch(h.label){case 0:s=!1,h.label=1;case 1:h.trys.push([1,6,7,12]),t=u(e),h.label=2;case 2:return[4,t.next()];case 3:if((n=h.sent()).done)return[3,5];if(a=n.value,s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{c=this.doDecodeSync(),s=!0}catch(e){if(!(e instanceof y))throw e}this.totalPos+=this.pos,h.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return l=h.sent(),o={error:l},[3,12];case 7:return h.trys.push([7,,10,11]),n&&!n.done&&(i=t.return)?[4,i.call(t)]:[3,9];case 8:h.sent(),h.label=9;case 9:return[3,11];case 10:if(o)throw o.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,c]}throw p=(d=this).headByte,_=d.pos,f=d.totalPos,new RangeError("Insufficient data in parsing ".concat((0,r.prettyByte)(p)," at ").concat(f," (").concat(_," in the current buffer)"))}})})},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return _(this,arguments,function(){var n,r,o,i,s,c,a,l,d;return h(this,function(h){switch(h.label){case 0:n=t,r=-1,h.label=1;case 1:h.trys.push([1,13,14,19]),o=u(e),h.label=2;case 2:return[4,p(o.next())];case 3:if((i=h.sent()).done)return[3,12];if(s=i.value,t&&0===r)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(r=this.readArraySize(),n=!1,this.complete()),h.label=4;case 4:h.trys.push([4,9,,10]),h.label=5;case 5:return[4,p(this.doDecodeSync())];case 6:return[4,h.sent()];case 7:return h.sent(),0===--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((c=h.sent())instanceof y))throw c;return[3,10];case 10:this.totalPos+=this.pos,h.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return a=h.sent(),l={error:a},[3,19];case 14:return h.trys.push([14,,17,18]),i&&!i.done&&(d=o.return)?[4,p(d.call(o))]:[3,16];case 15:h.sent(),h.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}})})},e.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!==(o=e-128)){this.pushMapState(o),this.complete();continue e}t={}}else if(e<160){if(0!==(o=e-144)){this.pushArrayState(o),this.complete();continue e}t=[]}else{var n=e-160;t=this.decodeUtf8String(n,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e){n=this.lookU8();t=this.decodeUtf8String(n,1)}else if(218===e){n=this.lookU16();t=this.decodeUtf8String(n,2)}else if(219===e){n=this.lookU32();t=this.decodeUtf8String(n,4)}else if(220===e){if(0!==(o=this.readU16())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(221===e){if(0!==(o=this.readU32())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(222===e){if(0!==(o=this.readU16())){this.pushMapState(o),this.complete();continue e}t={}}else if(223===e){if(0!==(o=this.readU32())){this.pushMapState(o),this.complete();continue e}t={}}else if(196===e){var o=this.lookU8();t=this.decodeBinary(o,1)}else if(197===e){o=this.lookU16();t=this.decodeBinary(o,2)}else if(198===e){o=this.lookU32();t=this.decodeBinary(o,4)}else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e){o=this.lookU8();t=this.decodeExtension(o,1)}else if(200===e){o=this.lookU16();t=this.decodeExtension(o,2)}else{if(201!==e)throw new l.DecodeError("Unrecognized type byte: ".concat((0,r.prettyByte)(e)));o=this.lookU32();t=this.decodeExtension(o,4)}this.complete();for(var i=this.stack;i.length>0;){var s=i[i.length-1];if(0===s.type){if(s.array[s.position]=t,s.position++,s.position!==s.size)continue e;i.pop(),t=s.array}else{if(1===s.type){if(!f(t))throw new l.DecodeError("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new l.DecodeError("The key __proto__ is not allowed");s.key=t,s.type=2;continue e}if(s.map[s.key]=t,s.readCount++,s.readCount!==s.size){s.key=null,s.type=1;continue e}i.pop(),t=s.map}}return t}},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new l.DecodeError("Unrecognized array type byte: ".concat((0,r.prettyByte)(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new l.DecodeError("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new l.DecodeError("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new l.DecodeError("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLength<this.pos+t+e)throw w;var r,o=this.pos+t;return r=this.stateIsMapKey()&&(null===(n=this.keyDecoder)||void 0===n?void 0:n.canBeCached(e))?this.keyDecoder.decode(this.bytes,o,e):e>s.TEXT_DECODER_THRESHOLD?(0,s.utf8DecodeTD)(this.bytes,o,e):(0,s.utf8DecodeJs)(this.bytes,o,e),this.pos+=t+e,r},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new l.DecodeError("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw w;var n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new l.DecodeError("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e=(0,i.getUint64)(this.view,this.pos);return this.pos+=8,e},e.prototype.readI64=function(){var e=(0,i.getInt64)(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs":
34
+ \****************************************************************/(e,t,n)=>{n.r(t),n.d(t,{DataViewIndexOutOfBoundsError:()=>y,Decoder:()=>v});var r=n(/*! ./utils/prettyByte.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs"),o=n(/*! ./ExtensionCodec.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs"),i=n(/*! ./utils/int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),s=n(/*! ./utils/utf8.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs"),a=n(/*! ./utils/typedArrays.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs"),c=n(/*! ./CachedKeyDecoder.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs"),l=n(/*! ./DecodeError.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs"),h=function(e,t,n,r){return new(n||(n=Promise))(function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(s,a)}c((r=r.apply(e,t||[])).next())})},d=function(e,t){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}},_=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise(function(r,o){(function(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)})(r,o,(t=e[n](t)).done,t.value)})}}},u=function(e){return this instanceof u?(this.v=e,this):new u(e)},p=function(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,o=n.apply(e,t||[]),i=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(e){o[e]&&(r[e]=function(t){return new Promise(function(n,r){i.push([e,t,n,r])>1||a(e,t)})})}function a(e,t){try{(n=o[e](t)).value instanceof u?Promise.resolve(n.value.v).then(c,l):h(i[0][2],n)}catch(e){h(i[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function h(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}},f=function(e){var t=typeof e;return"string"===t||"number"===t},g=new DataView(new ArrayBuffer(0)),m=new Uint8Array(g.buffer),y=function(){try{g.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),w=new y("Insufficient data"),b=new c.CachedKeyDecoder,v=function(){function e(e,t,n,r,s,a,c,l){void 0===e&&(e=o.ExtensionCodec.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=i.UINT32_MAX),void 0===r&&(r=i.UINT32_MAX),void 0===s&&(s=i.UINT32_MAX),void 0===a&&(a=i.UINT32_MAX),void 0===c&&(c=i.UINT32_MAX),void 0===l&&(l=b),this.extensionCodec=e,this.context=t,this.maxStrLength=n,this.maxBinLength=r,this.maxArrayLength=s,this.maxMapLength=a,this.maxExtLength=c,this.keyDecoder=l,this.totalPos=0,this.pos=0,this.view=g,this.bytes=m,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=(0,a.ensureUint8Array)(e),this.view=(0,a.createDataView)(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining(1)){var t=this.bytes.subarray(this.pos),n=(0,a.ensureUint8Array)(e),r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra ".concat(t.byteLength-n," of ").concat(t.byteLength," byte(s) found at buffer[").concat(e,"]"))},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return d(this,function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}})},e.prototype.decodeAsync=function(e){var t,n,o,i;return h(this,void 0,void 0,function(){var s,a,c,l,h,u,p,f;return d(this,function(d){switch(d.label){case 0:s=!1,d.label=1;case 1:d.trys.push([1,6,7,12]),t=_(e),d.label=2;case 2:return[4,t.next()];case 3:if((n=d.sent()).done)return[3,5];if(c=n.value,s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{a=this.doDecodeSync(),s=!0}catch(e){if(!(e instanceof y))throw e}this.totalPos+=this.pos,d.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return l=d.sent(),o={error:l},[3,12];case 7:return d.trys.push([7,,10,11]),n&&!n.done&&(i=t.return)?[4,i.call(t)]:[3,9];case 8:d.sent(),d.label=9;case 9:return[3,11];case 10:if(o)throw o.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,a]}throw u=(h=this).headByte,p=h.pos,f=h.totalPos,new RangeError("Insufficient data in parsing ".concat((0,r.prettyByte)(u)," at ").concat(f," (").concat(p," in the current buffer)"))}})})},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return p(this,arguments,function(){var n,r,o,i,s,a,c,l,h;return d(this,function(d){switch(d.label){case 0:n=t,r=-1,d.label=1;case 1:d.trys.push([1,13,14,19]),o=_(e),d.label=2;case 2:return[4,u(o.next())];case 3:if((i=d.sent()).done)return[3,12];if(s=i.value,t&&0===r)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(r=this.readArraySize(),n=!1,this.complete()),d.label=4;case 4:d.trys.push([4,9,,10]),d.label=5;case 5:return[4,u(this.doDecodeSync())];case 6:return[4,d.sent()];case 7:return d.sent(),0===--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=d.sent())instanceof y))throw a;return[3,10];case 10:this.totalPos+=this.pos,d.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=d.sent(),l={error:c},[3,19];case 14:return d.trys.push([14,,17,18]),i&&!i.done&&(h=o.return)?[4,u(h.call(o))]:[3,16];case 15:d.sent(),d.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}})})},e.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!==(o=e-128)){this.pushMapState(o),this.complete();continue e}t={}}else if(e<160){if(0!==(o=e-144)){this.pushArrayState(o),this.complete();continue e}t=[]}else{var n=e-160;t=this.decodeUtf8String(n,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e){n=this.lookU8();t=this.decodeUtf8String(n,1)}else if(218===e){n=this.lookU16();t=this.decodeUtf8String(n,2)}else if(219===e){n=this.lookU32();t=this.decodeUtf8String(n,4)}else if(220===e){if(0!==(o=this.readU16())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(221===e){if(0!==(o=this.readU32())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(222===e){if(0!==(o=this.readU16())){this.pushMapState(o),this.complete();continue e}t={}}else if(223===e){if(0!==(o=this.readU32())){this.pushMapState(o),this.complete();continue e}t={}}else if(196===e){var o=this.lookU8();t=this.decodeBinary(o,1)}else if(197===e){o=this.lookU16();t=this.decodeBinary(o,2)}else if(198===e){o=this.lookU32();t=this.decodeBinary(o,4)}else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e){o=this.lookU8();t=this.decodeExtension(o,1)}else if(200===e){o=this.lookU16();t=this.decodeExtension(o,2)}else{if(201!==e)throw new l.DecodeError("Unrecognized type byte: ".concat((0,r.prettyByte)(e)));o=this.lookU32();t=this.decodeExtension(o,4)}this.complete();for(var i=this.stack;i.length>0;){var s=i[i.length-1];if(0===s.type){if(s.array[s.position]=t,s.position++,s.position!==s.size)continue e;i.pop(),t=s.array}else{if(1===s.type){if(!f(t))throw new l.DecodeError("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new l.DecodeError("The key __proto__ is not allowed");s.key=t,s.type=2;continue e}if(s.map[s.key]=t,s.readCount++,s.readCount!==s.size){s.key=null,s.type=1;continue e}i.pop(),t=s.map}}return t}},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new l.DecodeError("Unrecognized array type byte: ".concat((0,r.prettyByte)(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new l.DecodeError("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new l.DecodeError("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new l.DecodeError("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLength<this.pos+t+e)throw w;var r,o=this.pos+t;return r=this.stateIsMapKey()&&(null===(n=this.keyDecoder)||void 0===n?void 0:n.canBeCached(e))?this.keyDecoder.decode(this.bytes,o,e):e>s.TEXT_DECODER_THRESHOLD?(0,s.utf8DecodeTD)(this.bytes,o,e):(0,s.utf8DecodeJs)(this.bytes,o,e),this.pos+=t+e,r},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new l.DecodeError("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw w;var n=this.pos+t,r=this.bytes.subarray(n,n+e);return this.pos+=t+e,r},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new l.DecodeError("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,n,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e=(0,i.getUint64)(this.view,this.pos);return this.pos+=8,e},e.prototype.readI64=function(){var e=(0,i.getInt64)(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs":
26
35
  /*!****************************************************************!*\
27
36
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs ***!
28
- \****************************************************************/(e,t,n)=>{n.r(t),n.d(t,{DEFAULT_INITIAL_BUFFER_SIZE:()=>a,DEFAULT_MAX_DEPTH:()=>c,Encoder:()=>l});var r=n(/*! ./utils/utf8.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs"),o=n(/*! ./ExtensionCodec.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs"),i=n(/*! ./utils/int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),s=n(/*! ./utils/typedArrays.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs"),c=100,a=2048,l=function(){function e(e,t,n,r,i,s,l,d){void 0===e&&(e=o.ExtensionCodec.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=c),void 0===r&&(r=a),void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===l&&(l=!1),void 0===d&&(d=!1),this.extensionCodec=e,this.context=t,this.maxDepth=n,this.initialBufferSize=r,this.sortKeys=i,this.forceFloat32=s,this.ignoreUndefined=l,this.forceIntegerToFloat=d,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return e.prototype.reinitializeState=function(){this.pos=0},e.prototype.encodeSharedRef=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)},e.prototype.encode=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)},e.prototype.doEncode=function(e,t){if(t>this.maxDepth)throw new Error("Too deep objects in depth ".concat(t));null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(2*t)},e.prototype.resizeBuffer=function(e){var t=new ArrayBuffer(e),n=new Uint8Array(t),r=new DataView(t);n.set(this.bytes),this.view=r,this.bytes=n},e.prototype.encodeNil=function(){this.writeU8(192)},e.prototype.encodeBoolean=function(e){!1===e?this.writeU8(194):this.writeU8(195)},e.prototype.encodeNumber=function(e){Number.isSafeInteger(e)&&!this.forceIntegerToFloat?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>r.TEXT_ENCODER_THRESHOLD){var t=(0,r.utf8Count)(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),(0,r.utf8EncodeTE)(e,this.bytes,this.pos),this.pos+=t}else{t=(0,r.utf8Count)(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),(0,r.utf8EncodeJs)(e,this.bytes,this.pos),this.pos+=t}},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: ".concat(t));this.writeU8(198),this.writeU32(t)}var n=(0,s.ensureUint8Array)(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large array: ".concat(n));this.writeU8(221),this.writeU32(n)}for(var r=0,o=e;r<o.length;r++){var i=o[r];this.doEncode(i,t+1)}},e.prototype.countWithoutUndefined=function(e,t){for(var n=0,r=0,o=t;r<o.length;r++){void 0!==e[o[r]]&&n++}return n},e.prototype.encodeMap=function(e,t){var n=Object.keys(e);this.sortKeys&&n.sort();var r=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(r<16)this.writeU8(128+r);else if(r<65536)this.writeU8(222),this.writeU16(r);else{if(!(r<4294967296))throw new Error("Too large map object: ".concat(r));this.writeU8(223),this.writeU32(r)}for(var o=0,i=n;o<i.length;o++){var s=i[o],c=e[s];this.ignoreUndefined&&void 0===c||(this.encodeString(s),this.doEncode(c,t+1))}},e.prototype.encodeExtension=function(e){var t=e.data.length;if(1===t)this.writeU8(212);else if(2===t)this.writeU8(213);else if(4===t)this.writeU8(214);else if(8===t)this.writeU8(215);else if(16===t)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large extension object: ".concat(t));this.writeU8(201),this.writeU32(t)}this.writeI8(e.type),this.writeU8a(e.data)},e.prototype.writeU8=function(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++},e.prototype.writeU8a=function(e){var t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t},e.prototype.writeI8=function(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++},e.prototype.writeU16=function(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2},e.prototype.writeI16=function(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2},e.prototype.writeU32=function(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4},e.prototype.writeI32=function(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4},e.prototype.writeF32=function(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4},e.prototype.writeF64=function(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8},e.prototype.writeU64=function(e){this.ensureBufferSizeToWrite(8),(0,i.setUint64)(this.view,this.pos,e),this.pos+=8},e.prototype.writeI64=function(e){this.ensureBufferSizeToWrite(8),(0,i.setInt64)(this.view,this.pos,e),this.pos+=8},e}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs":
37
+ \****************************************************************/(e,t,n)=>{n.r(t),n.d(t,{DEFAULT_INITIAL_BUFFER_SIZE:()=>c,DEFAULT_MAX_DEPTH:()=>a,Encoder:()=>l});var r=n(/*! ./utils/utf8.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs"),o=n(/*! ./ExtensionCodec.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs"),i=n(/*! ./utils/int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),s=n(/*! ./utils/typedArrays.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs"),a=100,c=2048,l=function(){function e(e,t,n,r,i,s,l,h){void 0===e&&(e=o.ExtensionCodec.defaultCodec),void 0===t&&(t=void 0),void 0===n&&(n=a),void 0===r&&(r=c),void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===l&&(l=!1),void 0===h&&(h=!1),this.extensionCodec=e,this.context=t,this.maxDepth=n,this.initialBufferSize=r,this.sortKeys=i,this.forceFloat32=s,this.ignoreUndefined=l,this.forceIntegerToFloat=h,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return e.prototype.reinitializeState=function(){this.pos=0},e.prototype.encodeSharedRef=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)},e.prototype.encode=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)},e.prototype.doEncode=function(e,t){if(t>this.maxDepth)throw new Error("Too deep objects in depth ".concat(t));null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(2*t)},e.prototype.resizeBuffer=function(e){var t=new ArrayBuffer(e),n=new Uint8Array(t),r=new DataView(t);n.set(this.bytes),this.view=r,this.bytes=n},e.prototype.encodeNil=function(){this.writeU8(192)},e.prototype.encodeBoolean=function(e){!1===e?this.writeU8(194):this.writeU8(195)},e.prototype.encodeNumber=function(e){Number.isSafeInteger(e)&&!this.forceIntegerToFloat?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>r.TEXT_ENCODER_THRESHOLD){var t=(0,r.utf8Count)(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),(0,r.utf8EncodeTE)(e,this.bytes,this.pos),this.pos+=t}else{t=(0,r.utf8Count)(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),(0,r.utf8EncodeJs)(e,this.bytes,this.pos),this.pos+=t}},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: ".concat(t));this.writeU8(198),this.writeU32(t)}var n=(0,s.ensureUint8Array)(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large array: ".concat(n));this.writeU8(221),this.writeU32(n)}for(var r=0,o=e;r<o.length;r++){var i=o[r];this.doEncode(i,t+1)}},e.prototype.countWithoutUndefined=function(e,t){for(var n=0,r=0,o=t;r<o.length;r++){void 0!==e[o[r]]&&n++}return n},e.prototype.encodeMap=function(e,t){var n=Object.keys(e);this.sortKeys&&n.sort();var r=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(r<16)this.writeU8(128+r);else if(r<65536)this.writeU8(222),this.writeU16(r);else{if(!(r<4294967296))throw new Error("Too large map object: ".concat(r));this.writeU8(223),this.writeU32(r)}for(var o=0,i=n;o<i.length;o++){var s=i[o],a=e[s];this.ignoreUndefined&&void 0===a||(this.encodeString(s),this.doEncode(a,t+1))}},e.prototype.encodeExtension=function(e){var t=e.data.length;if(1===t)this.writeU8(212);else if(2===t)this.writeU8(213);else if(4===t)this.writeU8(214);else if(8===t)this.writeU8(215);else if(16===t)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large extension object: ".concat(t));this.writeU8(201),this.writeU32(t)}this.writeI8(e.type),this.writeU8a(e.data)},e.prototype.writeU8=function(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++},e.prototype.writeU8a=function(e){var t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t},e.prototype.writeI8=function(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++},e.prototype.writeU16=function(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2},e.prototype.writeI16=function(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2},e.prototype.writeU32=function(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4},e.prototype.writeI32=function(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4},e.prototype.writeF32=function(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4},e.prototype.writeF64=function(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8},e.prototype.writeU64=function(e){this.ensureBufferSizeToWrite(8),(0,i.setUint64)(this.view,this.pos,e),this.pos+=8},e.prototype.writeI64=function(e){this.ensureBufferSizeToWrite(8),(0,i.setInt64)(this.view,this.pos,e),this.pos+=8},e}()},"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs":
29
38
  /*!****************************************************************!*\
30
39
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs ***!
31
40
  \****************************************************************/(e,t,n)=>{n.r(t),n.d(t,{ExtData:()=>r});var r=function(e,t){this.type=e,this.data=t}},"./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs":
@@ -40,10 +49,10 @@
40
49
  \***************************************************************/(e,t,n)=>{n.r(t),n.d(t,{encode:()=>i});var r=n(/*! ./Encoder.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs"),o={};function i(e,t){return void 0===t&&(t=o),new r.Encoder(t.extensionCodec,t.context,t.maxDepth,t.initialBufferSize,t.sortKeys,t.forceFloat32,t.ignoreUndefined,t.forceIntegerToFloat).encodeSharedRef(e)}},"./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs":
41
50
  /*!******************************************************************!*\
42
51
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs ***!
43
- \******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{EXT_TIMESTAMP:()=>i,decodeTimestampExtension:()=>u,decodeTimestampToTimeSpec:()=>h,encodeDateToTimeSpec:()=>l,encodeTimeSpecToTimestamp:()=>a,encodeTimestampExtension:()=>d,timestampExtension:()=>p});var r=n(/*! ./DecodeError.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs"),o=n(/*! ./utils/int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),i=-1,s=4294967295,c=17179869183;function a(e){var t=e.sec,n=e.nsec;if(t>=0&&n>=0&&t<=c){if(0===n&&t<=s){var r=new Uint8Array(4);return(l=new DataView(r.buffer)).setUint32(0,t),r}var i=t/4294967296,a=4294967295&t;r=new Uint8Array(8);return(l=new DataView(r.buffer)).setUint32(0,n<<2|3&i),l.setUint32(4,a),r}var l;r=new Uint8Array(12);return(l=new DataView(r.buffer)).setUint32(0,n),(0,o.setInt64)(l,4,t),r}function l(e){var t=e.getTime(),n=Math.floor(t/1e3),r=1e6*(t-1e3*n),o=Math.floor(r/1e9);return{sec:n+o,nsec:r-1e9*o}}function d(e){return e instanceof Date?a(l(e)):null}function h(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var n=t.getUint32(0);return{sec:4294967296*(3&n)+t.getUint32(4),nsec:n>>>2};case 12:return{sec:(0,o.getInt64)(t,4),nsec:t.getUint32(0)};default:throw new r.DecodeError("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}function u(e){var t=h(e);return new Date(1e3*t.sec+t.nsec/1e6)}var p={type:i,encode:d,decode:u}},"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs":
52
+ \******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{EXT_TIMESTAMP:()=>i,decodeTimestampExtension:()=>_,decodeTimestampToTimeSpec:()=>d,encodeDateToTimeSpec:()=>l,encodeTimeSpecToTimestamp:()=>c,encodeTimestampExtension:()=>h,timestampExtension:()=>u});var r=n(/*! ./DecodeError.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs"),o=n(/*! ./utils/int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),i=-1,s=4294967295,a=17179869183;function c(e){var t=e.sec,n=e.nsec;if(t>=0&&n>=0&&t<=a){if(0===n&&t<=s){var r=new Uint8Array(4);return(l=new DataView(r.buffer)).setUint32(0,t),r}var i=t/4294967296,c=4294967295&t;r=new Uint8Array(8);return(l=new DataView(r.buffer)).setUint32(0,n<<2|3&i),l.setUint32(4,c),r}var l;r=new Uint8Array(12);return(l=new DataView(r.buffer)).setUint32(0,n),(0,o.setInt64)(l,4,t),r}function l(e){var t=e.getTime(),n=Math.floor(t/1e3),r=1e6*(t-1e3*n),o=Math.floor(r/1e9);return{sec:n+o,nsec:r-1e9*o}}function h(e){return e instanceof Date?c(l(e)):null}function d(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var n=t.getUint32(0);return{sec:4294967296*(3&n)+t.getUint32(4),nsec:n>>>2};case 12:return{sec:(0,o.getInt64)(t,4),nsec:t.getUint32(0)};default:throw new r.DecodeError("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}function _(e){var t=d(e);return new Date(1e3*t.sec+t.nsec/1e6)}var u={type:i,encode:h,decode:_}},"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs":
44
53
  /*!******************************************************************!*\
45
54
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs ***!
46
- \******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{UINT32_MAX:()=>r,getInt64:()=>s,getUint64:()=>c,setInt64:()=>i,setUint64:()=>o});var r=4294967295;function o(e,t,n){var r=n/4294967296,o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function i(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function s(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}function c(e,t){return 4294967296*e.getUint32(t)+e.getUint32(t+4)}},"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs":
55
+ \******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{UINT32_MAX:()=>r,getInt64:()=>s,getUint64:()=>a,setInt64:()=>i,setUint64:()=>o});var r=4294967295;function o(e,t,n){var r=n/4294967296,o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function i(e,t,n){var r=Math.floor(n/4294967296),o=n;e.setUint32(t,r),e.setUint32(t+4,o)}function s(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}function a(e,t){return 4294967296*e.getUint32(t)+e.getUint32(t+4)}},"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs":
47
56
  /*!*************************************************************************!*\
48
57
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs ***!
49
58
  \*************************************************************************/(e,t,n)=>{function r(e){return"".concat(e<0?"-":"","0x").concat(Math.abs(e).toString(16).padStart(2,"0"))}n.r(t),n.d(t,{prettyByte:()=>r})},"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs":
@@ -52,8 +61,8 @@
52
61
  \**************************************************************************/(e,t,n)=>{function r(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e instanceof ArrayBuffer?new Uint8Array(e):Uint8Array.from(e)}function o(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=r(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}n.r(t),n.d(t,{createDataView:()=>o,ensureUint8Array:()=>r})},"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs":
53
62
  /*!*******************************************************************!*\
54
63
  !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs ***!
55
- \*******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{TEXT_DECODER_THRESHOLD:()=>m,TEXT_ENCODER_THRESHOLD:()=>h,utf8Count:()=>a,utf8DecodeJs:()=>_,utf8DecodeTD:()=>g,utf8EncodeJs:()=>l,utf8EncodeTE:()=>u});var r,o,i,s=n(/*! ./int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),c=("undefined"==typeof process||"never"!==(null===(r=null===process||void 0===process?void 0:process.env)||void 0===r?void 0:r.TEXT_ENCODING))&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function a(e){for(var t=e.length,n=0,r=0;r<t;){var o=e.charCodeAt(r++);if(4294967168&o)if(4294965248&o){if(o>=55296&&o<=56319&&r<t){var i=e.charCodeAt(r);56320==(64512&i)&&(++r,o=((1023&o)<<10)+(1023&i)+65536)}n+=4294901760&o?4:3}else n+=2;else n++}return n}function l(e,t,n){for(var r=e.length,o=n,i=0;i<r;){var s=e.charCodeAt(i++);if(4294967168&s){if(4294965248&s){if(s>=55296&&s<=56319&&i<r){var c=e.charCodeAt(i);56320==(64512&c)&&(++i,s=((1023&s)<<10)+(1023&c)+65536)}4294901760&s?(t[o++]=s>>18&7|240,t[o++]=s>>12&63|128,t[o++]=s>>6&63|128):(t[o++]=s>>12&15|224,t[o++]=s>>6&63|128)}else t[o++]=s>>6&31|192;t[o++]=63&s|128}else t[o++]=s}}var d=c?new TextEncoder:void 0,h=c?"undefined"!=typeof process&&"force"!==(null===(o=null===process||void 0===process?void 0:process.env)||void 0===o?void 0:o.TEXT_ENCODING)?200:0:s.UINT32_MAX;var u=(null==d?void 0:d.encodeInto)?function(e,t,n){d.encodeInto(e,t.subarray(n))}:function(e,t,n){t.set(d.encode(e),n)},p=4096;function _(e,t,n){for(var r=t,o=r+n,i=[],s="";r<o;){var c=e[r++];if(128&c)if(192==(224&c)){var a=63&e[r++];i.push((31&c)<<6|a)}else if(224==(240&c)){a=63&e[r++];var l=63&e[r++];i.push((31&c)<<12|a<<6|l)}else if(240==(248&c)){var d=(7&c)<<18|(a=63&e[r++])<<12|(l=63&e[r++])<<6|63&e[r++];d>65535&&(d-=65536,i.push(d>>>10&1023|55296),d=56320|1023&d),i.push(d)}else i.push(c);else i.push(c);i.length>=p&&(s+=String.fromCharCode.apply(String,i),i.length=0)}return i.length>0&&(s+=String.fromCharCode.apply(String,i)),s}var f=c?new TextDecoder:null,m=c?"undefined"!=typeof process&&"force"!==(null===(i=null===process||void 0===process?void 0:process.env)||void 0===i?void 0:i.TEXT_DECODER)?200:0:s.UINT32_MAX;function g(e,t,n){var r=e.subarray(t,t+n);return f.decode(r)}}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](n,n.exports,__webpack_require__),n.exports}__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};
64
+ \*******************************************************************/(e,t,n)=>{n.r(t),n.d(t,{TEXT_DECODER_THRESHOLD:()=>g,TEXT_ENCODER_THRESHOLD:()=>d,utf8Count:()=>c,utf8DecodeJs:()=>p,utf8DecodeTD:()=>m,utf8EncodeJs:()=>l,utf8EncodeTE:()=>_});var r,o,i,s=n(/*! ./int.mjs */"./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs"),a=("undefined"==typeof process||"never"!==(null===(r=null===process||void 0===process?void 0:process.env)||void 0===r?void 0:r.TEXT_ENCODING))&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function c(e){for(var t=e.length,n=0,r=0;r<t;){var o=e.charCodeAt(r++);if(4294967168&o)if(4294965248&o){if(o>=55296&&o<=56319&&r<t){var i=e.charCodeAt(r);56320==(64512&i)&&(++r,o=((1023&o)<<10)+(1023&i)+65536)}n+=4294901760&o?4:3}else n+=2;else n++}return n}function l(e,t,n){for(var r=e.length,o=n,i=0;i<r;){var s=e.charCodeAt(i++);if(4294967168&s){if(4294965248&s){if(s>=55296&&s<=56319&&i<r){var a=e.charCodeAt(i);56320==(64512&a)&&(++i,s=((1023&s)<<10)+(1023&a)+65536)}4294901760&s?(t[o++]=s>>18&7|240,t[o++]=s>>12&63|128,t[o++]=s>>6&63|128):(t[o++]=s>>12&15|224,t[o++]=s>>6&63|128)}else t[o++]=s>>6&31|192;t[o++]=63&s|128}else t[o++]=s}}var h=a?new TextEncoder:void 0,d=a?"undefined"!=typeof process&&"force"!==(null===(o=null===process||void 0===process?void 0:process.env)||void 0===o?void 0:o.TEXT_ENCODING)?200:0:s.UINT32_MAX;var _=(null==h?void 0:h.encodeInto)?function(e,t,n){h.encodeInto(e,t.subarray(n))}:function(e,t,n){t.set(h.encode(e),n)},u=4096;function p(e,t,n){for(var r=t,o=r+n,i=[],s="";r<o;){var a=e[r++];if(128&a)if(192==(224&a)){var c=63&e[r++];i.push((31&a)<<6|c)}else if(224==(240&a)){c=63&e[r++];var l=63&e[r++];i.push((31&a)<<12|c<<6|l)}else if(240==(248&a)){var h=(7&a)<<18|(c=63&e[r++])<<12|(l=63&e[r++])<<6|63&e[r++];h>65535&&(h-=65536,i.push(h>>>10&1023|55296),h=56320|1023&h),i.push(h)}else i.push(a);else i.push(a);i.length>=u&&(s+=String.fromCharCode.apply(String,i),i.length=0)}return i.length>0&&(s+=String.fromCharCode.apply(String,i)),s}var f=a?new TextDecoder:null,g=a?"undefined"!=typeof process&&"force"!==(null===(i=null===process||void 0===process?void 0:process.env)||void 0===i?void 0:i.TEXT_DECODER)?200:0:s.UINT32_MAX;function m(e,t,n){var r=e.subarray(t,t+n);return f.decode(r)}}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](n,n.exports,__webpack_require__),n.exports}__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};
56
65
  /*!*********************************!*\
57
66
  !*** ./src/websocket-client.js ***!
58
- \*********************************/__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{API_VERSION:()=>_rpc_js__WEBPACK_IMPORTED_MODULE_0__.API_VERSION,HTTPStreamingRPCConnection:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_4__.HTTPStreamingRPCConnection,LocalWebSocket:()=>LocalWebSocket,RPC:()=>_rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC,connectToServer:()=>connectToServer,connectToServerHTTP:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_4__.connectToServerHTTP,getRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService,getRemoteService:()=>getRemoteService,getRemoteServiceHTTP:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_4__.getRemoteServiceHTTP,hyphaWebsocketClient:()=>hyphaWebsocketClient,loadRequirements:()=>_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.loadRequirements,login:()=>login,logout:()=>logout,normalizeServerUrlHTTP:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_4__.normalizeServerUrl,registerRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.registerRTCService,schemaFunction:()=>_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction,setupLocalClient:()=>setupLocalClient});var _rpc_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! ./rpc.js */"./src/rpc.js"),_utils_index_js__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! ./utils/index.js */"./src/utils/index.js"),_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! ./utils/schema.js */"./src/utils/schema.js"),_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! ./webrtc-client.js */"./src/webrtc-client.js"),_http_client_js__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! ./http-client.js */"./src/http-client.js");const MAX_RETRY=1e6;class WebsocketRPCConnection{constructor(e,t,n,r,o=null,i=60,s=null,c=7200,a=null){(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(e&&t,"server_url and client_id are required"),this._server_url=e,this._client_id=t,this._workspace=n,this._token=r,this._reconnection_token=o,this._websocket=null,this._handle_message=null,this._handle_connected=null,this._handle_disconnected=null,this._timeout=i,this._WebSocketClass=s||WebSocket,this._closed=!1,this._legacy_auth=null,this.connection_info=null,this._enable_reconnect=!1,this._token_refresh_interval=c,this.manager_id=null,this._refresh_token_task=null,this._reconnect_timeouts=new Set,this._additional_headers=a,this._reconnecting=!1,this._disconnectedNotified=!1}_cleanup(){this._refresh_token_delay&&(clearTimeout(this._refresh_token_delay),this._refresh_token_delay=null),this._refresh_token_task&&(clearInterval(this._refresh_token_task),this._refresh_token_task=null);for(const e of this._reconnect_timeouts)clearTimeout(e);this._reconnect_timeouts.clear()}on_message(e){(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(e,"handler is required"),this._handle_message=e}on_connected(e){this._handle_connected=e}on_disconnected(e){this._handle_disconnected=e}async _attempt_connection(e,t=!0){return new Promise((n,r)=>{this._legacy_auth=!1;const o=new this._WebSocketClass(e);o.binaryType="arraybuffer",o.onopen=()=>{console.info("WebSocket connection established"),n(o)},o.onerror=e=>{console.error("WebSocket connection error:",e),r(new Error(`WebSocket connection error: ${e}`))},o.onclose=o=>{1003===o.code&&t?(console.info("Received 1003 error, attempting connection with query parameters."),this._legacy_auth=!0,this._attempt_connection_with_query_params(e).then(n).catch(r)):this._notifyDisconnected(o.reason)}})}async _attempt_connection_with_query_params(e){const t=[];this._client_id&&t.push(`client_id=${encodeURIComponent(this._client_id)}`),this._workspace&&t.push(`workspace=${encodeURIComponent(this._workspace)}`),this._token&&t.push(`token=${encodeURIComponent(this._token)}`),this._reconnection_token&&t.push(`reconnection_token=${encodeURIComponent(this._reconnection_token)}`);const n=e+(t.length>0?`?${t.join("&")}`:"");return await this._attempt_connection(n,!1)}_establish_connection(){return new Promise((e,t)=>{this._websocket.onmessage=n=>{const r=n.data,o=JSON.parse(r);if("connection_info"!=o.type){if("error"==o.type){const e="ConnectionAbortedError: "+o.message;return console.error("Failed to connect, "+e),void t(new Error(e))}return console.error("ConnectionAbortedError: Unexpected message received from the server:",r),void t(new Error("ConnectionAbortedError: Unexpected message received from the server"))}this.connection_info=o,this._workspace&&(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(this.connection_info.workspace===this._workspace,`Connected to the wrong workspace: ${this.connection_info.workspace}, expected: ${this._workspace}`),this.connection_info.reconnection_token&&(this._reconnection_token=this.connection_info.reconnection_token),this.connection_info.reconnection_token_life_time&&this._token_refresh_interval>this.connection_info.reconnection_token_life_time/1.5&&(console.warn(`Token refresh interval is too long (${this._token_refresh_interval}), setting it to 1.5 times of the token life time(${this.connection_info.reconnection_token_life_time}).`),this._token_refresh_interval=this.connection_info.reconnection_token_life_time/1.5),this.manager_id=this.connection_info.manager_id||null,console.log(`Successfully connected to the server, workspace: ${this.connection_info.workspace}, manager_id: ${this.manager_id}`),this.connection_info.announcement&&console.log(`${this.connection_info.announcement}`),e(this.connection_info)}})}async open(){console.log("Creating a new websocket connection to",this._server_url.split("?")[0]);try{if(this._websocket=await this._attempt_connection(this._server_url),this._legacy_auth)throw new Error("NotImplementedError: Legacy authentication is not supported");const e=JSON.stringify({client_id:this._client_id,workspace:this._workspace,token:this._token,reconnection_token:this._reconnection_token});return this._websocket.send(e),await(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.waitFor)(this._establish_connection(),this._timeout,"Failed to receive the first message from the server"),this._token_refresh_interval>0&&(this._refresh_token_delay=setTimeout(()=>{this._refresh_token_delay=null,this._closed||(this._send_refresh_token(),this._refresh_token_task=setInterval(()=>{this._send_refresh_token()},1e3*this._token_refresh_interval))},2e3)),this._enable_reconnect=!0,this._closed=!1,this._disconnectedNotified=!1,this._websocket.onmessage=e=>{if("string"==typeof e.data){const t=JSON.parse(e.data);"reconnection_token"===t.type?this._reconnection_token=t.reconnection_token:console.log("Received message from the server:",t)}else this._handle_message(e.data)},this._websocket.onerror=e=>{console.error("WebSocket connection error:",e),this._cleanup()},this._websocket.onclose=this._handle_close.bind(this),this._handle_connected&&this._handle_connected(this.connection_info),this.connection_info}catch(e){throw this._cleanup(),console.error("Failed to connect to",this._server_url.split("?")[0],e),e}}_send_refresh_token(){if(this._websocket&&this._websocket.readyState===WebSocket.OPEN){const e=JSON.stringify({type:"refresh_token"});this._websocket.send(e)}}_notifyDisconnected(e){this._disconnectedNotified||(this._disconnectedNotified=!0,this._handle_disconnected&&this._handle_disconnected(e))}_handle_close(e){if(!this._closed&&this._websocket&&this._websocket.readyState===WebSocket.CLOSED){if(this._cleanup(),this._disconnectedNotified=!1,this._enable_reconnect){if([1e3,1001].includes(e.code)?console.warn(`Websocket connection closed gracefully by server (code: ${e.code}): ${e.reason} - attempting reconnect`):console.warn("Websocket connection closed unexpectedly (code: %s): %s",e.code,e.reason),this._notifyDisconnected(e.reason),this._reconnecting)return void console.debug("Reconnection already in progress, skipping");this._reconnecting=!0;let t=0;const n=1e3,r=6e4,o=.1,i=async()=>{if(this._closed)return console.info("Connection was closed, stopping reconnection"),void(this._reconnecting=!1);try{console.warn(`Reconnecting to ${this._server_url.split("?")[0]} (attempt #${t})`),await this.open(),await new Promise(e=>setTimeout(e,500)),console.warn(`Successfully reconnected to server ${this._server_url} (services re-registered)`),this._reconnecting=!1}catch(e){if(`${e}`.includes("ConnectionAbortedError:"))return console.warn("Server refused to reconnect:",e),this._closed=!0,this._reconnecting=!1,void this._notifyDisconnected(`Server refused reconnection: ${e}`);if(`${e}`.includes("NotImplementedError:"))return console.error(`${e}\nIt appears that you are trying to connect to a hypha server that is older than 0.20.0, please upgrade the hypha server or use the websocket client in imjoy-rpc(https://www.npmjs.com/package/imjoy-rpc) instead`),this._closed=!0,this._reconnecting=!1,void this._notifyDisconnected(`Server too old: ${e}`);"NetworkError"===e.name||e.message.includes("network")?console.error(`Network error during reconnection: ${e.message}`):"TimeoutError"===e.name||e.message.includes("timeout")?console.error(`Connection timeout during reconnection: ${e.message}`):console.error(`Unexpected error during reconnection: ${e.message}`);const s=Math.min(n*Math.pow(2,t),r),c=(2*Math.random()-1)*o*s,a=Math.max(100,s+c);console.debug(`Waiting ${(a/1e3).toFixed(2)}s before next reconnection attempt`);const l=setTimeout(async()=>(this._reconnect_timeouts.delete(l),this._websocket&&this._websocket.readyState===WebSocket.OPEN?(console.info("Connection restored externally"),void(this._reconnecting=!1)):this._closed?(console.info("Connection was closed, stopping reconnection"),void(this._reconnecting=!1)):(t+=1,void(t<MAX_RETRY?await i():(console.error(`Failed to reconnect after ${MAX_RETRY} attempts, giving up.`),this._closed=!0,this._reconnecting=!1,this._notifyDisconnected("Max reconnection attempts exceeded"))))),a);this._reconnect_timeouts.add(l)}};i()}}else this._cleanup(),this._notifyDisconnected(e.reason)}async emit_message(e){if(this._closed)throw new Error("Connection is closed");this._websocket&&this._websocket.readyState===WebSocket.OPEN||await this.open();try{this._websocket.send(e)}catch(e){throw console.error(`Failed to send data, error: ${e}`),e}}disconnect(e){this._closed=!0,this._reconnecting=!1,this._websocket&&this._websocket.readyState!==WebSocket.CLOSED&&this._websocket.readyState!==WebSocket.CLOSING&&this._websocket.close(1e3,e),this._cleanup(),console.info(`WebSocket connection disconnected (${e})`)}}function normalizeServerUrl(e){if(!e)throw new Error("server_url is required");return e.startsWith("http://")?e=e.replace("http://","ws://").replace(/\/$/,"")+"/ws":e.startsWith("https://")&&(e=e.replace("https://","wss://").replace(/\/$/,"")+"/ws"),e}async function login(e){const t=e.login_service_id||"public/hypha-login",n=e.workspace,r=e.expires_in,o=e.login_timeout||60,i=e.login_callback,s=e.profile,c=e.additional_headers,a=e.transport||"websocket",l=await connectToServer({name:"initial login client",server_url:e.server_url,additional_headers:c,transport:a});try{const e=await l.getService(t);let c;return(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(e,`Failed to get the login service: ${t}`),c=n?await e.start({workspace:n,expires_in:r,_rkwargs:!0}):await e.start(),i?await i(c):console.log(`Please open your browser and login at ${c.login_url}`),await e.check(c.key,{timeout:o,profile:s,_rkwargs:!0})}catch(e){throw e}finally{await l.disconnect()}}async function logout(e){const t=e.login_service_id||"public/hypha-login",n=e.logout_callback,r=e.additional_headers,o=e.transport||"websocket",i=await connectToServer({name:"initial logout client",server_url:e.server_url,additional_headers:r,transport:o});try{const e=await i.getService(t);if((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(e,`Failed to get the login service: ${t}`),!e.logout)throw new Error("Logout is not supported by this server. Please upgrade the Hypha server to a version that supports logout.");const r=await e.logout({});return n?await n(r):console.log(`Please open your browser to logout at ${r.logout_url}`),r}catch(e){throw e}finally{await i.disconnect()}}async function webrtcGetService(e,t,n){const r=void 0!==(n=n||{}).webrtc?n.webrtc:"auto",o=n.webrtc_config;void 0!==n.webrtc&&delete n.webrtc,void 0!==n.webrtc_config&&delete n.webrtc_config,(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)([void 0,!0,!1,"auto"].includes(r),"webrtc must be true, false or 'auto'");const i=await e.getService(t,n);if(!0===r||"auto"===r){if(i.id.includes(":")&&i.id.includes("/"))try{const t=i.id.split(":")[0].split("/"),r=t[t.length-1],s=`${t.slice(0,-1).join("/")}/${r}-rtc`,c=await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService)(e,s,o),a=await c.getService(i.id.split(":")[1],n);return a._webrtc=!0,a._peer=c,a._service=i,a}catch(e){console.warn("Failed to get webrtc service, using websocket connection",e)}if(!0===r)throw new Error("Failed to get the service via webrtc")}return i}async function connectToServer(e){if("http"===(e.transport||"websocket"))return await(0,_http_client_js__WEBPACK_IMPORTED_MODULE_4__.connectToServerHTTP)(e);e.server&&(e.server_url=e.server_url||e.server.url,e.WebSocketClass=e.WebSocketClass||e.server.WebSocketClass);let t=e.client_id;t||(t=(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.randId)(),e.client_id=t),0===Object.keys(e).length&&("undefined"!=typeof process&&process.env?(e.server_url=process.env.HYPHA_SERVER_URL,e.token=process.env.HYPHA_TOKEN,e.client_id=process.env.HYPHA_CLIENT_ID,e.workspace=process.env.HYPHA_WORKSPACE):"undefined"!=typeof self&&self.env?(e.server_url=self.env.HYPHA_SERVER_URL,e.token=self.env.HYPHA_TOKEN,e.client_id=self.env.HYPHA_CLIENT_ID,e.workspace=self.env.HYPHA_WORKSPACE):"undefined"!=typeof globalThis&&globalThis.env&&(e.server_url=globalThis.env.HYPHA_SERVER_URL,e.token=globalThis.env.HYPHA_TOKEN,e.client_id=globalThis.env.HYPHA_CLIENT_ID,e.workspace=globalThis.env.HYPHA_WORKSPACE));let n=normalizeServerUrl(e.server_url),r=new WebsocketRPCConnection(n,t,e.workspace,e.token,e.reconnection_token,e.method_timeout||60,e.WebSocketClass,e.token_refresh_interval,e.additional_headers);const o=await r.open();if((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(o,"Failed to connect to the server, no connection info obtained. This issue is most likely due to an outdated Hypha server version. Please use `imjoy-rpc` for compatibility, or upgrade the Hypha server to the latest version."),await new Promise(e=>setTimeout(e,100)),!r.manager_id){console.warn("Manager ID not set immediately, waiting...");const e=5e3,t=100,n=Date.now();for(;!r.manager_id&&Date.now()-n<e;)await new Promise(e=>setTimeout(e,t));if(!r.manager_id)throw console.error("Manager ID still not set after waiting"),new Error("Failed to get manager ID from server");console.info(`Manager ID set after waiting: ${r.manager_id}`)}if(e.workspace&&o.workspace!==e.workspace)throw new Error(`Connected to the wrong workspace: ${o.workspace}, expected: ${e.workspace}`);const i=o.workspace,s=new _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC(r,{client_id:t,workspace:i,default_context:{connection_type:"websocket"},name:e.name,method_timeout:e.method_timeout,app_id:e.app_id,server_base_url:o.public_base_url,long_message_chunk_size:e.long_message_chunk_size});await s.waitFor("services_registered",e.method_timeout||120);const c=await s.get_manager_service({timeout:e.method_timeout,case_conversion:"camel",kwargs_expansion:e.kwargs_expansion||!1});if(c.rpc=s,o&&(c.config=Object.assign(c.config,o)),c.export=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(async function(t){t.id="default",t.name=t.name||e.name||t.id,t.description=t.description||e.description,await s.register_service(t,{overwrite:!0})},{name:"export",description:"Export the api.",parameters:{properties:{api:{description:"The api to export",type:"object"}},required:["api"],type:"object"}}),c.getApp=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(async function(e){return e=e||"*",(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!e.includes(":"),"clientId should not contain ':'"),e.includes("/")||(e=o.workspace+"/"+e),(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(2===e.split("/").length,"clientId should match pattern workspace/clientId"),await c.getService(`${e}:default`)},{name:"getApp",description:"Get the app.",parameters:{properties:{clientId:{default:"*",description:"The clientId",type:"string"}},type:"object"}}),c.listApps=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(async function(e){e=e||i,(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!e.includes(":"),"workspace should not contain ':'"),(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!e.includes("/"),"workspace should not contain '/'");const t={workspace:e,service_id:"default"};return await c.listServices(t)},{name:"listApps",description:"List the apps.",parameters:{properties:{workspace:{default:i,description:"The workspace",type:"string"}},type:"object"}}),c.disconnect=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.disconnect.bind(s),{name:"disconnect",description:"Disconnect from the server.",parameters:{type:"object",properties:{},required:[]}}),c.registerCodec=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.register_codec.bind(s),{name:"registerCodec",description:"Register a codec for the webrtc connection",parameters:{type:"object",properties:{codec:{type:"object",description:"Codec to register",properties:{name:{type:"string"},type:{},encoder:{type:"function"},decoder:{type:"function"}}}}}}),c.emit=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.emit.bind(s),{name:"emit",description:"Emit a message.",parameters:{properties:{data:{description:"The data to emit",type:"object"}},required:["data"],type:"object"}}),c.on=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.on.bind(s),{name:"on",description:"Register a message handler.",parameters:{properties:{event:{description:"The event to listen to",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.off=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.off.bind(s),{name:"off",description:"Remove a message handler.",parameters:{properties:{event:{description:"The event to remove",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.once=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.once.bind(s),{name:"once",description:"Register a one-time message handler.",parameters:{properties:{event:{description:"The event to listen to",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.getServiceSchema=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.get_service_schema,{name:"getServiceSchema",description:"Get the service schema.",parameters:{properties:{service:{description:"The service to extract schema",type:"object"}},required:["service"],type:"object"}}),c.registerService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.register_service.bind(s),{name:"registerService",description:"Register a service.",parameters:{properties:{service:{description:"The service to register",type:"object"},force:{default:!1,description:"Force to register the service",type:"boolean"}},required:["service"],type:"object"}}),c.unregisterService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(s.unregister_service.bind(s),{name:"unregisterService",description:"Unregister a service.",parameters:{properties:{service:{description:"The service id to unregister",type:"string"},notify:{default:!0,description:"Notify the workspace manager",type:"boolean"}},required:["service"],type:"object"}}),r.manager_id&&s.on("force-exit",async e=>{e.from==="*/"+r.manager_id&&(console.log("Disconnecting from server, reason:",e.reason),await s.disconnect())}),e.webrtc){await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.registerRTCService)(c,`${t}-rtc`,e.webrtc_config);const n=Object.assign({},c),r=n.getService.__schema__.description,o=n.getService.__schema__.parameters;c.getService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(webrtcGetService.bind(null,n),{name:"getService",description:r,parameters:o}),c.getRTCService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService.bind(null,c),{name:"getRTCService",description:"Get the webrtc connection, returns a peer connection.",parameters:{properties:{config:{description:"The config for the webrtc service",type:"object"}},required:["config"],type:"object"}})}else{const e=c.getService;c.getService=(t,n)=>e(t,n=n||{}),c.getService.__schema__=e.__schema__}return c.registerProbes=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(async function(e){return e.id="probes",e.name="Probes",e.config={visibility:"public"},e.type="probes",e.description=`Probes Service, visit ${n}/${i}services/probes for the available probes.`,await c.registerService(e,{overwrite:!0})},{name:"registerProbes",description:"Register probes service",parameters:{properties:{probes:{description:"The probes to register, e.g. {'liveness': {'type': 'function', 'description': 'Check the liveness of the service'}}",type:"object"}},required:["probes"],type:"object"}}),c}async function getRemoteService(e,t={}){const{serverUrl:n,workspace:r,clientId:o,serviceId:i,appId:s}=(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.parseServiceUrl)(e),c=`${r}/${o}:${i}@${s}`;if(t.serverUrl&&t.serverUrl!==n)throw new Error("server_url in config does not match the server_url in the url");t.serverUrl=n;const a=await connectToServer(t);return await a.getService(c)}class LocalWebSocket{constructor(e,t,n){this.url=e,this.onopen=()=>{},this.onmessage=()=>{},this.onclose=()=>{},this.onerror=()=>{},this.client_id=t,this.workspace=n;const r="undefined"!=typeof window?window:self,o="undefined"!=typeof window;if(this.postMessage=e=>{o?window.parent.postMessage(e,"*"):self.postMessage(e)},this.readyState=WebSocket.CONNECTING,this._context=r,this._messageListener=e=>{const{type:t,data:n,to:r}=e.data;if(r===this.client_id)switch(t){case"message":this.readyState===WebSocket.OPEN&&this.onmessage&&this.onmessage({data:n});break;case"connected":this.readyState=WebSocket.OPEN,this.onopen(e);break;case"closed":this.readyState=WebSocket.CLOSED,this.onclose(e)}},r.addEventListener("message",this._messageListener,!1),!this.client_id)throw new Error("client_id is required");if(!this.workspace)throw new Error("workspace is required");this.postMessage({type:"connect",url:this.url,from:this.client_id,workspace:this.workspace})}send(e){this.readyState===WebSocket.OPEN&&this.postMessage({type:"message",data:e,from:this.client_id,workspace:this.workspace})}close(){this.readyState=WebSocket.CLOSING,this.postMessage({type:"close",from:this.client_id,workspace:this.workspace}),this._context&&this._messageListener&&(this._context.removeEventListener("message",this._messageListener,!1),this._messageListener=null),this.onclose()}addEventListener(e,t){"message"===e&&(this.onmessage=t),"open"===e&&(this.onopen=t),"close"===e&&(this.onclose=t),"error"===e&&(this.onerror=t)}}const hyphaWebsocketClient={RPC:_rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC,API_VERSION:_rpc_js__WEBPACK_IMPORTED_MODULE_0__.API_VERSION,schemaFunction:_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction,loadRequirements:_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.loadRequirements,login:login,logout:logout,connectToServer:connectToServer,connectToServerHTTP:_http_client_js__WEBPACK_IMPORTED_MODULE_4__.connectToServerHTTP,getRemoteService:getRemoteService,getRemoteServiceHTTP:_http_client_js__WEBPACK_IMPORTED_MODULE_4__.getRemoteServiceHTTP,getRTCService:_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService,registerRTCService:_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.registerRTCService,get setupLocalClient(){return setupLocalClient},get LocalWebSocket(){return LocalWebSocket},HTTPStreamingRPCConnection:_http_client_js__WEBPACK_IMPORTED_MODULE_4__.HTTPStreamingRPCConnection,normalizeServerUrlHTTP:_http_client_js__WEBPACK_IMPORTED_MODULE_4__.normalizeServerUrl};function setupLocalClient({enable_execution:enable_execution=!1,on_ready:on_ready=null}){return new Promise((resolve,reject)=>{const context="undefined"!=typeof window?window:self,isWindow="undefined"!=typeof window;context.addEventListener("message",event=>{const{type:type,server_url:server_url,workspace:workspace,client_id:client_id,token:token,method_timeout:method_timeout,name:name,config:config}=event.data;if("initializeHyphaClient"===type){if(!server_url||!workspace||!client_id)return void console.error("server_url, workspace, and client_id are required.");if(!server_url.startsWith("https://local-hypha-server:"))return void console.error("server_url should start with https://local-hypha-server:");class FixedLocalWebSocket extends LocalWebSocket{constructor(e){super(e,client_id,workspace)}}connectToServer({server_url:server_url,workspace:workspace,client_id:client_id,token:token,method_timeout:method_timeout,name:name,WebSocketClass:FixedLocalWebSocket}).then(async server=>{globalThis.api=server;try{if(isWindow&&enable_execution){function e(e){return new Promise((t,n)=>{const r=document.createElement("script");r.innerHTML=e.content,r.lang=e.lang,r.onload=()=>t(),r.onerror=e=>n(e),document.head.appendChild(r)})}if(config.styles&&config.styles.length>0)for(const t of config.styles){const n=document.createElement("style");n.innerHTML=t.content,n.lang=t.lang,document.head.appendChild(n)}if(config.links&&config.links.length>0)for(const r of config.links){const o=document.createElement("a");o.href=r.url,o.innerText=r.text,document.body.appendChild(o)}if(config.windows&&config.windows.length>0)for(const i of config.windows){document.body.innerHTML=i.content;break}if(config.scripts&&config.scripts.length>0)for(const s of config.scripts){if("javascript"!==s.lang)throw new Error("Only javascript scripts are supported");await e(s)}}else if(!isWindow&&enable_execution&&config.scripts&&config.scripts.length>0)for(const script of config.scripts){if("javascript"!==script.lang)throw new Error("Only javascript scripts are supported");eval(script.content)}on_ready&&await on_ready(server,config),resolve(server)}catch(c){reject(c)}})}},!1),isWindow?window.parent.postMessage({type:"hyphaClientReady"},"*"):self.postMessage({type:"hyphaClientReady"})})}var __webpack_exports__API_VERSION=__webpack_exports__.API_VERSION,__webpack_exports__HTTPStreamingRPCConnection=__webpack_exports__.HTTPStreamingRPCConnection,__webpack_exports__LocalWebSocket=__webpack_exports__.LocalWebSocket,__webpack_exports__RPC=__webpack_exports__.RPC,__webpack_exports__connectToServer=__webpack_exports__.connectToServer,__webpack_exports__connectToServerHTTP=__webpack_exports__.connectToServerHTTP,__webpack_exports__getRTCService=__webpack_exports__.getRTCService,__webpack_exports__getRemoteService=__webpack_exports__.getRemoteService,__webpack_exports__getRemoteServiceHTTP=__webpack_exports__.getRemoteServiceHTTP,__webpack_exports__hyphaWebsocketClient=__webpack_exports__.hyphaWebsocketClient,__webpack_exports__loadRequirements=__webpack_exports__.loadRequirements,__webpack_exports__login=__webpack_exports__.login,__webpack_exports__logout=__webpack_exports__.logout,__webpack_exports__normalizeServerUrlHTTP=__webpack_exports__.normalizeServerUrlHTTP,__webpack_exports__registerRTCService=__webpack_exports__.registerRTCService,__webpack_exports__schemaFunction=__webpack_exports__.schemaFunction,__webpack_exports__setupLocalClient=__webpack_exports__.setupLocalClient,hyphaRpcWebsocket=Object.freeze({__proto__:null,API_VERSION:__webpack_exports__API_VERSION,HTTPStreamingRPCConnection:__webpack_exports__HTTPStreamingRPCConnection,LocalWebSocket:__webpack_exports__LocalWebSocket,RPC:__webpack_exports__RPC,connectToServer:__webpack_exports__connectToServer,connectToServerHTTP:__webpack_exports__connectToServerHTTP,getRTCService:__webpack_exports__getRTCService,getRemoteService:__webpack_exports__getRemoteService,getRemoteServiceHTTP:__webpack_exports__getRemoteServiceHTTP,hyphaWebsocketClient:__webpack_exports__hyphaWebsocketClient,loadRequirements:__webpack_exports__loadRequirements,login:__webpack_exports__login,logout:__webpack_exports__logout,normalizeServerUrlHTTP:__webpack_exports__normalizeServerUrlHTTP,registerRTCService:__webpack_exports__registerRTCService,schemaFunction:__webpack_exports__schemaFunction,setupLocalClient:__webpack_exports__setupLocalClient}),hyphaRpc=Object.freeze({__proto__:null,API_VERSION:__webpack_exports__API_VERSION,HTTPStreamingRPCConnection:__webpack_exports__HTTPStreamingRPCConnection,LocalWebSocket:__webpack_exports__LocalWebSocket,RPC:__webpack_exports__RPC,connectToServer:__webpack_exports__connectToServer,connectToServerHTTP:__webpack_exports__connectToServerHTTP,getRTCService:__webpack_exports__getRTCService,getRemoteService:__webpack_exports__getRemoteService,getRemoteServiceHTTP:__webpack_exports__getRemoteServiceHTTP,hyphaWebsocketClient:hyphaRpcWebsocket,loadRequirements:__webpack_exports__loadRequirements,login:__webpack_exports__login,logout:__webpack_exports__logout,normalizeServerUrlHTTP:__webpack_exports__normalizeServerUrlHTTP,registerRTCService:__webpack_exports__registerRTCService,schemaFunction:__webpack_exports__schemaFunction,setupLocalClient:__webpack_exports__setupLocalClient});const overlayStyles="\n :host {\n all: initial;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n }\n\n * {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n }\n\n .debugger-icon {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background: #4a90d9;\n color: white;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n transition: transform 0.15s, background 0.15s;\n user-select: none;\n font-size: 18px;\n line-height: 1;\n }\n\n .debugger-icon:hover {\n transform: scale(1.1);\n background: #357abd;\n }\n\n .debugger-icon.connected {\n background: #27ae60;\n }\n\n .debugger-icon.error {\n background: #e74c3c;\n }\n\n .debugger-panel {\n display: none;\n width: 380px;\n max-height: 520px;\n background: #1e1e2e;\n color: #cdd6f4;\n border-radius: 8px;\n border: 1px solid #45475a;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);\n overflow: hidden;\n flex-direction: column;\n position: absolute;\n bottom: 50px;\n right: 0;\n font-size: 13px;\n }\n\n .debugger-panel.open {\n display: flex;\n }\n\n .panel-header {\n background: #313244;\n padding: 8px 12px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n cursor: default;\n border-bottom: 1px solid #45475a;\n font-weight: 600;\n font-size: 12px;\n letter-spacing: 0.3px;\n text-transform: uppercase;\n color: #a6adc8;\n }\n\n .panel-header .title {\n display: flex;\n align-items: center;\n gap: 6px;\n }\n\n .panel-header .close-btn {\n cursor: pointer;\n color: #6c7086;\n font-size: 16px;\n line-height: 1;\n padding: 2px 4px;\n border-radius: 3px;\n }\n\n .panel-header .close-btn:hover {\n color: #cdd6f4;\n background: #45475a;\n }\n\n .status-dot {\n width: 8px;\n height: 8px;\n border-radius: 50%;\n display: inline-block;\n background: #6c7086;\n }\n\n .status-dot.connected {\n background: #a6e3a1;\n }\n\n .status-dot.error {\n background: #f38ba8;\n }\n\n .panel-body {\n padding: 10px 12px;\n overflow-y: auto;\n flex: 1;\n max-height: 440px;\n }\n\n .info-row {\n display: flex;\n justify-content: space-between;\n padding: 4px 0;\n border-bottom: 1px solid #313244;\n font-size: 12px;\n }\n\n .info-row .label {\n color: #6c7086;\n }\n\n .info-row .value {\n color: #cdd6f4;\n text-align: right;\n word-break: break-all;\n max-width: 180px;\n font-family: 'SF Mono', Monaco, Consolas, monospace;\n font-size: 11px;\n }\n\n .instructions-section {\n margin-top: 8px;\n padding-top: 6px;\n border-top: 1px solid #313244;\n }\n\n .instructions-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 4px;\n }\n\n .url-label {\n font-size: 11px;\n color: #6c7086;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 3px;\n }\n\n .instructions-block {\n font-family: 'SF Mono', Monaco, Consolas, monospace;\n font-size: 10px;\n color: #a6e3a1;\n background: #11111b;\n border: 1px solid #313244;\n border-radius: 4px;\n padding: 8px;\n white-space: pre-wrap;\n word-break: break-all;\n max-height: 200px;\n overflow-y: auto;\n line-height: 1.5;\n }\n\n .copy-btn {\n background: #45475a;\n color: #cdd6f4;\n border: none;\n border-radius: 3px;\n padding: 2px 8px;\n font-size: 10px;\n cursor: pointer;\n white-space: nowrap;\n flex-shrink: 0;\n }\n\n .copy-btn:hover {\n background: #585b70;\n }\n\n .log-section {\n margin-top: 8px;\n }\n\n .log-title {\n font-size: 11px;\n color: #6c7086;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 4px;\n }\n\n .log-entry {\n font-family: 'SF Mono', Monaco, Consolas, monospace;\n font-size: 11px;\n padding: 3px 6px;\n border-radius: 3px;\n background: #313244;\n margin-bottom: 2px;\n color: #a6adc8;\n word-break: break-all;\n }\n\n .log-entry.call {\n border-left: 2px solid #89b4fa;\n }\n\n .log-entry.result {\n border-left: 2px solid #a6e3a1;\n }\n\n .log-entry.error {\n border-left: 2px solid #f38ba8;\n color: #f38ba8;\n }\n";class DebugOverlay{constructor(e){this.isOpen=!1,this.isDragging=!1,this.dragOffset={x:0,y:0},this.maxLogEntries=50,this.host=document.createElement("div"),this.host.id="hypha-debugger-host",Object.assign(this.host.style,{position:"fixed",bottom:"20px",right:"20px",zIndex:"2147483647",display:"flex",flexDirection:"column",alignItems:"flex-end"}),e?.position&&(this.host.style.bottom="auto",this.host.style.right="auto",this.host.style.left=e.position.x+"px",this.host.style.top=e.position.y+"px"),this.shadow=this.host.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=overlayStyles,this.shadow.appendChild(t);const n=document.createElement("div");n.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="flex-end",this.panel=document.createElement("div"),this.panel.className="debugger-panel";const r=document.createElement("div");r.className="panel-header";const o=document.createElement("span");o.className="title",this.statusDot=document.createElement("span"),this.statusDot.className="status-dot",o.appendChild(this.statusDot),o.appendChild(document.createTextNode(" Hypha Debugger"));const i=document.createElement("span");i.className="close-btn",i.textContent="×",i.addEventListener("click",()=>this.toggle()),r.appendChild(o),r.appendChild(i);const s=document.createElement("div");s.className="panel-body",this.infoBody=document.createElement("div"),s.appendChild(this.infoBody);const c=document.createElement("div");c.className="log-section";const a=document.createElement("div");a.className="log-title",a.textContent="Remote Operations",this.logContainer=document.createElement("div"),c.appendChild(a),c.appendChild(this.logContainer),s.appendChild(c),this.panel.appendChild(r),this.panel.appendChild(s),this.icon=document.createElement("div"),this.icon.className="debugger-icon",this.icon.textContent="🐛",this.icon.addEventListener("click",e=>{this.isDragging||this.toggle()}),n.appendChild(this.panel),n.appendChild(this.icon),this.shadow.appendChild(n),document.documentElement.appendChild(this.host),this.setupDrag()}setupDrag(){let e=0,t=0,n=!1;this.icon.addEventListener("mousedown",r=>{e=r.clientX,t=r.clientY,n=!1;const o=this.host.getBoundingClientRect();this.dragOffset.x=r.clientX-o.left,this.dragOffset.y=r.clientY-o.top,r.preventDefault()}),document.addEventListener("mousemove",r=>{if(0===e&&0===t)return;const o=Math.abs(r.clientX-e),i=Math.abs(r.clientY-t);(o>3||i>3)&&(n=!0,this.isDragging=!0,this.host.style.left=r.clientX-this.dragOffset.x+"px",this.host.style.top=r.clientY-this.dragOffset.y+"px",this.host.style.right="auto",this.host.style.bottom="auto")}),document.addEventListener("mouseup",()=>{e=0,t=0,n&&setTimeout(()=>{this.isDragging=!1},50)})}toggle(){this.isOpen=!this.isOpen,this.panel.classList.toggle("open",this.isOpen)}setStatus(e){this.statusDot.className="status-dot",this.icon.className="debugger-icon","connected"===e?(this.statusDot.classList.add("connected"),this.icon.classList.add("connected")):"error"===e&&(this.statusDot.classList.add("error"),this.icon.classList.add("error"))}setInfo(e){this.infoBody.querySelectorAll(".info-row").forEach(e=>e.remove());const t=this.infoBody.firstChild;for(const[n,r]of Object.entries(e)){const e=document.createElement("div");e.className="info-row";const o=document.createElement("span");o.className="label",o.textContent=n;const i=document.createElement("span");i.className="value",i.textContent=r,i.title=r,e.appendChild(o),e.appendChild(i),this.infoBody.insertBefore(e,t)}}setInstructions(e){const t=this.infoBody.querySelector(".instructions-section");t&&t.remove();const n=document.createElement("div");n.className="instructions-section";const r=document.createElement("div");r.className="instructions-header";const o=document.createElement("span");o.className="url-label",o.textContent="Instructions";const i=document.createElement("button");i.className="copy-btn",i.textContent="Copy All",i.addEventListener("click",()=>{navigator.clipboard.writeText(e).then(()=>{i.textContent="Copied!",setTimeout(()=>{i.textContent="Copy All"},1500)})}),r.appendChild(o),r.appendChild(i),n.appendChild(r);const s=document.createElement("pre");s.className="instructions-block",s.textContent=e,n.appendChild(s),this.infoBody.appendChild(n)}addLog(e,t="call"){const n=document.createElement("div");for(n.className=`log-entry ${t}`,n.textContent=e,this.logContainer.appendChild(n);this.logContainer.children.length>this.maxLogEntries;)this.logContainer.removeChild(this.logContainer.firstChild);const r=this.panel.querySelector(".panel-body");r&&(r.scrollTop=r.scrollHeight)}destroy(){this.host.remove()}}const CURSOR_BORDER_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" fill="none"><g><path d="M 15 42 L 15 36.99 Q 15 31.99 23.7 31.99 L 28.05 31.99 Q 32.41 31.99 32.41 21.99 L 32.41 17 Q 32.41 12 41.09 16.95 L 76.31 37.05 Q 85 42 76.31 46.95 L 41.09 67.05 Q 32.41 72 32.41 62.01 L 32.41 57.01 Q 32.41 52.01 23.7 52.01 L 19.35 52.01 Q 15 52.01 15 47.01 Z" fill="none" stroke="currentColor" stroke-width="6" stroke-miterlimit="10"/></g></svg>',CURSOR_FILL_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><g style="filter: drop-shadow(rgba(0, 0, 0, 0.3) 3px 4px 4px);"><path d="M 15 42 L 15 36.99 Q 15 31.99 23.7 31.99 L 28.05 31.99 Q 32.41 31.99 32.41 21.99 L 32.41 17 Q 32.41 12 41.09 16.95 L 76.31 37.05 Q 85 42 76.31 46.95 L 41.09 67.05 Q 32.41 72 32.41 62.01 L 32.41 57.01 Q 32.41 52.01 23.7 52.01 L 19.35 52.01 Q 15 52.01 15 47.01 Z" fill="#ffffff" stroke="none"/></g></svg>',CURSOR_CSS="\n .hypha-cursor {\n position: fixed;\n width: 50px;\n height: 50px;\n pointer-events: none;\n z-index: 2147483646;\n transition: opacity 0.2s;\n opacity: 0;\n }\n .hypha-cursor.visible {\n opacity: 1;\n }\n .hypha-cursor-border {\n position: absolute;\n width: 100%;\n height: 100%;\n background: linear-gradient(45deg, rgb(57, 182, 255), rgb(189, 69, 251));\n mask-image: var(--cursor-border);\n -webkit-mask-image: var(--cursor-border);\n mask-size: 100% 100%;\n -webkit-mask-size: 100% 100%;\n mask-repeat: no-repeat;\n -webkit-mask-repeat: no-repeat;\n transform-origin: center;\n transform: rotate(-135deg) scale(1.2);\n margin-left: -10px;\n margin-top: -14px;\n }\n .hypha-cursor-fill {\n position: absolute;\n width: 100%;\n height: 100%;\n background-image: var(--cursor-fill);\n background-size: 100% 100%;\n background-repeat: no-repeat;\n transform-origin: center;\n transform: rotate(-135deg) scale(1.2);\n margin-left: -10px;\n margin-top: -14px;\n }\n .hypha-cursor-ripple {\n position: absolute;\n width: 100%;\n height: 100%;\n pointer-events: none;\n margin-left: -50%;\n margin-top: -50%;\n }\n .hypha-cursor-ripple::after {\n content: '';\n opacity: 0;\n position: absolute;\n inset: 0;\n border: 3px solid rgba(57, 182, 255, 1);\n border-radius: 50%;\n }\n .hypha-cursor.clicking .hypha-cursor-ripple::after {\n animation: hypha-cursor-ripple 400ms ease-out forwards;\n }\n @keyframes hypha-cursor-ripple {\n 0% { transform: scale(0); opacity: 1; }\n 100% { transform: scale(2.5); opacity: 0; }\n }\n";class AICursor{constructor(){this.currentX=0,this.currentY=0,this.targetX=0,this.targetY=0,this.animating=!1,this.visible=!1,this.hideTimeout=null,this.container=document.createElement("div"),this.container.id="hypha-debugger-cursor",this.container.setAttribute("data-browser-use-ignore","true"),this.container.setAttribute("data-page-agent-ignore","true");const e=document.createElement("style");e.textContent=CURSOR_CSS,this.container.appendChild(e),this.cursor=document.createElement("div"),this.cursor.className="hypha-cursor";const t='url("data:image/svg+xml,'+encodeURIComponent(CURSOR_BORDER_SVG)+'")',n='url("data:image/svg+xml,'+encodeURIComponent(CURSOR_FILL_SVG)+'")';this.cursor.style.setProperty("--cursor-border",t),this.cursor.style.setProperty("--cursor-fill",n);const r=document.createElement("div");r.className="hypha-cursor-ripple",this.cursor.appendChild(r);const o=document.createElement("div");o.className="hypha-cursor-fill",this.cursor.appendChild(o);const i=document.createElement("div");i.className="hypha-cursor-border",this.cursor.appendChild(i),this.container.appendChild(this.cursor),document.body.appendChild(this.container),window.addEventListener("HyphaDebugger::MovePointerTo",e=>{const{x:t,y:n}=e.detail;this.moveTo(t,n)}),window.addEventListener("HyphaDebugger::ClickPointer",()=>{this.triggerClickAnimation()})}moveTo(e,t){this.targetX=e,this.targetY=t,this.visible||(this.visible=!0,this.currentX=e,this.currentY=t,this.cursor.style.left=`${e}px`,this.cursor.style.top=`${t}px`,this.cursor.classList.add("visible")),this.hideTimeout&&(clearTimeout(this.hideTimeout),this.hideTimeout=null),this.animating||(this.animating=!0,this.animateLoop())}animateLoop(){const e=this.targetX-this.currentX,t=this.targetY-this.currentY;Math.abs(e)>1||Math.abs(t)>1?(this.currentX+=.18*e,this.currentY+=.18*t,this.cursor.style.left=`${this.currentX}px`,this.cursor.style.top=`${this.currentY}px`,requestAnimationFrame(()=>this.animateLoop())):(this.currentX=this.targetX,this.currentY=this.targetY,this.cursor.style.left=`${this.currentX}px`,this.cursor.style.top=`${this.currentY}px`,this.animating=!1,this.hideTimeout=setTimeout(()=>{this.visible=!1,this.cursor.classList.remove("visible")},2e3))}triggerClickAnimation(){this.cursor.classList.remove("clicking"),this.cursor.offsetHeight,this.cursor.classList.add("clicking")}destroy(){this.hideTimeout&&clearTimeout(this.hideTimeout),this.container.remove()}}function detectFrameworks(){const e=[],t=window;if(t.__REACT_DEVTOOLS_GLOBAL_HOOK__?.renderers?.size>0)e.push("react");else{const t=document.querySelector("#root, #app, [data-reactroot]");if(t){Object.keys(t).some(e=>e.startsWith("__reactFiber$")||e.startsWith("__reactInternalInstance$"))&&e.push("react")}}if(t.__VUE__||t.__VUE_DEVTOOLS_GLOBAL_HOOK__)e.push("vue");else{const t=document.querySelector("[data-v-app], #app");t&&t.__vue_app__&&e.push("vue")}return(t.ng||document.querySelector("[ng-version]"))&&e.push("angular"),document.querySelector("[class*='svelte-']")&&e.push("svelte"),t.__NEXT_DATA__&&e.push("nextjs"),e}function collectPageInfo(){const e=performance.getEntriesByType("navigation")[0];return{url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},document_size:{width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight},user_agent:navigator.userAgent,timestamp:(new Date).toISOString(),cookies_enabled:navigator.cookieEnabled,language:navigator.language,platform:navigator.platform,online:navigator.onLine,performance:{load_time_ms:e?Math.round(e.loadEventEnd-e.startTime):null,dom_content_loaded_ms:e?Math.round(e.domContentLoadedEventEnd-e.startTime):null},frameworks:detectFrameworks()}}function getPageInfo(e,t,n){const r=collectPageInfo();if(e){const e=window.__HYPHA_DEBUGGER__?.consoleLogs??[],o=t??50;let i=n?e.filter(e=>e.level===n):e;r.console_logs=i.slice(-o)}return r}function getConsoleLogs(e){const t=window.__HYPHA_DEBUGGER__?.consoleLogs??[],n=e?.level,r=e?.limit??100;return(n?t.filter(e=>e.level===n):t).slice(-r)}function installConsoleCapture(e=500){var t;const n=(t=window).__HYPHA_DEBUGGER__??(t.__HYPHA_DEBUGGER__={});if(n.consoleInstalled)return;n.consoleLogs=[],n.consoleInstalled=!0;const r=["log","warn","error","info"];for(const t of r){const r=console[t].bind(console);console[t]=(...o)=>{const i=n.consoleLogs;i.push({level:t,message:o.map(e=>{try{return"string"==typeof e?e:JSON.stringify(e)}catch{return String(e)}}).join(" "),timestamp:(new Date).toISOString()}),i.length>e&&i.splice(0,i.length-e),r(...o)}}}function elementToInfo(e){const t=e.getBoundingClientRect(),n={};for(const t of Array.from(e.attributes))n[t.name]=t.value;return{tag:e.tagName.toLowerCase(),id:e.id,classes:Array.from(e.classList),text:(e.textContent??"").trim().slice(0,500),attributes:n,bounds:{x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)},visible:t.width>0&&t.height>0&&"hidden"!==getComputedStyle(e).visibility&&"none"!==getComputedStyle(e).display,children_count:e.children.length}}function queryDom(e,t){t=t??20;const n=document.querySelectorAll(e),r=[];for(let e=0;e<Math.min(n.length,t);e++)r.push(elementToInfo(n[e]));return r}function clickElement$1(e){const t=document.querySelector(e);if(!t)return{success:!1,message:`No element found for selector: ${e}`};const n=t.getBoundingClientRect();return t.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window,clientX:n.left+n.width/2,clientY:n.top+n.height/2})),{success:!0,message:`Clicked element: ${e}`}}function fillInput(e,t){const n=document.querySelector(e);if(!n)return{success:!1,message:`No element found for selector: ${e}`};const r=n.tagName.toLowerCase();if("input"===r||"textarea"===r){const o=n,i="textarea"===r?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,s=Object.getOwnPropertyDescriptor(i,"value")?.set;return s?s.call(o,t):o.value=t,o.dispatchEvent(new Event("input",{bubbles:!0})),o.dispatchEvent(new Event("change",{bubbles:!0})),{success:!0,message:`Filled ${e} with value`}}if("select"===r){const r=n,o=Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,"value")?.set;return o?o.call(r,t):r.value=t,r.dispatchEvent(new Event("change",{bubbles:!0})),{success:!0,message:`Set ${e} to ${t}`}}return{success:!1,message:`Element ${e} is not an input/textarea/select`}}function scrollTo(e){if("string"==typeof e){const t=document.querySelector(e);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),{success:!0,message:`Scrolled to ${e}`}):{success:!1,message:`No element found for selector: ${e}`}}return window.scrollTo({left:e.x,top:e.y,behavior:"smooth"}),{success:!0,message:`Scrolled to (${e.x}, ${e.y})`}}function getComputedStyles(e,t){const n=document.querySelector(e);if(!n)return{error:`No element found for selector: ${e}`};const r=getComputedStyle(n),o={},i=t??["display","position","width","height","color","background-color","font-size","font-family","margin","padding","border","opacity","visibility","overflow","z-index"];for(const e of i)o[e]=r.getPropertyValue(e);return o}function getElementBounds(e){const t=document.querySelector(e);if(!t)return{error:`No element found for selector: ${e}`};const n=t.getBoundingClientRect();return{bounds:{x:Math.round(n.x),y:Math.round(n.y),width:Math.round(n.width),height:Math.round(n.height)},visible:n.width>0&&n.height>0&&"hidden"!==getComputedStyle(t).visibility&&"none"!==getComputedStyle(t).display}}function getHtml(e,t,n){const r=t??!0,o=n??5e4,i=e?document.querySelector(e):document.documentElement;if(!i)return{error:`No element found for selector: ${e}`};const s=r?i.outerHTML:i.innerHTML,c=s.length>o;return{html:c?s.slice(0,o):s,length:s.length,truncated:c}}function resolveUrl(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i))return e;const n=document.implementation.createHTMLDocument(),r=n.createElement("base"),o=n.createElement("a");return n.head.appendChild(r),n.body.appendChild(o),t&&(r.href=t),o.href=e,o.href}getPageInfo.__schema__={name:"getPageInfo",description:"Get information about the current web page including URL, title, viewport size, detected frameworks, and performance timing. Optionally include recent console logs.",parameters:{type:"object",properties:{include_logs:{type:"boolean",description:"If true, include recent console output in the response. Default: false."},log_limit:{type:"number",description:"Maximum number of console log entries to include (most recent). Default: 50."},log_level:{type:"string",description:'Filter console logs by level: "log", "warn", "error", "info". Omit for all levels.',enum:["log","warn","error","info"]}}}},getConsoleLogs.__schema__={name:"getConsoleLogs",description:"Retrieve captured console output (log, warn, error, info).",parameters:{type:"object",properties:{level:{type:"string",description:'Filter by log level: "log", "warn", "error", "info". Omit for all levels.',enum:["log","warn","error","info"]},limit:{type:"number",description:"Maximum number of log entries to return (most recent). Default: 100."}}}},queryDom.__schema__={name:"queryDom",description:"Query DOM elements by CSS selector. Returns tag, id, classes, text content, attributes, bounding rect, and visibility for each matching element.",parameters:{type:"object",properties:{selector:{type:"string",description:'CSS selector to query, e.g. "button.primary", "#app > div".'},limit:{type:"number",description:"Maximum number of elements to return. Default: 20."}},required:["selector"]}},clickElement$1.__schema__={name:"clickElement",description:"Click a DOM element matching the CSS selector.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element to click."}},required:["selector"]}},fillInput.__schema__={name:"fillInput",description:"Set the value of an input, textarea, or select element. Works with React controlled components.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the input element."},value:{type:"string",description:"The value to set."}},required:["selector","value"]}},scrollTo.__schema__={name:"scrollTo",description:"Scroll to a DOM element (by CSS selector) or to an absolute position {x, y}.",parameters:{type:"object",properties:{target:{description:"CSS selector string to scroll to an element, or an object {x, y} for absolute scroll position."}},required:["target"]}},getComputedStyles.__schema__={name:"getComputedStyles",description:"Get computed CSS styles for an element.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element."},properties:{type:"array",items:{type:"string"},description:'CSS property names to retrieve, e.g. ["color", "font-size"]. Omit for common defaults.'}},required:["selector"]}},getElementBounds.__schema__={name:"getElementBounds",description:"Get the bounding rectangle and visibility of a DOM element.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element."}},required:["selector"]}},getHtml.__schema__={name:"getHtml",description:"Get the HTML content of the page or a specific element. Returns outerHTML by default. Useful for understanding page structure.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element. Omit to get the full page HTML."},outer:{type:"boolean",description:"If true (default), return outerHTML (includes the element itself). If false, return innerHTML (children only)."},max_length:{type:"number",description:"Maximum character length of the returned HTML. Default: 50000. Result will be truncated if longer."}}}};const uuid=(()=>{let e=0;return()=>(e+=1,`u${`0000${(Math.random()*36**4|0).toString(36)}`.slice(-4)}${e}`)})();function toArray(e){const t=[];for(let n=0,r=e.length;n<r;n++)t.push(e[n]);return t}let styleProps=null;function getStyleProperties(e={}){return styleProps||(e.includeStyleProperties?(styleProps=e.includeStyleProperties,styleProps):(styleProps=toArray(window.getComputedStyle(document.documentElement)),styleProps))}function px(e,t){const n=(e.ownerDocument.defaultView||window).getComputedStyle(e).getPropertyValue(t);return n?parseFloat(n.replace("px","")):0}function getNodeWidth(e){const t=px(e,"border-left-width"),n=px(e,"border-right-width");return e.clientWidth+t+n}function getNodeHeight(e){const t=px(e,"border-top-width"),n=px(e,"border-bottom-width");return e.clientHeight+t+n}function getImageSize(e,t={}){return{width:t.width||getNodeWidth(e),height:t.height||getNodeHeight(e)}}function getPixelRatio(){let e,t;try{t=process}catch(e){}const n=t&&t.env?t.env.devicePixelRatio:null;return n&&(e=parseInt(n,10),Number.isNaN(e)&&(e=1)),e||window.devicePixelRatio||1}const canvasDimensionLimit=16384;function checkCanvasDimensions(e){(e.width>canvasDimensionLimit||e.height>canvasDimensionLimit)&&(e.width>canvasDimensionLimit&&e.height>canvasDimensionLimit?e.width>e.height?(e.height*=canvasDimensionLimit/e.width,e.width=canvasDimensionLimit):(e.width*=canvasDimensionLimit/e.height,e.height=canvasDimensionLimit):e.width>canvasDimensionLimit?(e.height*=canvasDimensionLimit/e.width,e.width=canvasDimensionLimit):(e.width*=canvasDimensionLimit/e.height,e.height=canvasDimensionLimit))}function createImage(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=n,r.crossOrigin="anonymous",r.decoding="async",r.src=e})}async function svgToDataURL(e){return Promise.resolve().then(()=>(new XMLSerializer).serializeToString(e)).then(encodeURIComponent).then(e=>`data:image/svg+xml;charset=utf-8,${e}`)}async function nodeToDataURL(e,t,n){const r="http://www.w3.org/2000/svg",o=document.createElementNS(r,"svg"),i=document.createElementNS(r,"foreignObject");return o.setAttribute("width",`${t}`),o.setAttribute("height",`${n}`),o.setAttribute("viewBox",`0 0 ${t} ${n}`),i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("externalResourcesRequired","true"),o.appendChild(i),i.appendChild(e),svgToDataURL(o)}const isInstanceOfElement=(e,t)=>{if(e instanceof t)return!0;const n=Object.getPrototypeOf(e);return null!==n&&(n.constructor.name===t.name||isInstanceOfElement(n,t))};function formatCSSText(e){const t=e.getPropertyValue("content");return`${e.cssText} content: '${t.replace(/'|"/g,"")}';`}function formatCSSProperties(e,t){return getStyleProperties(t).map(t=>`${t}: ${e.getPropertyValue(t)}${e.getPropertyPriority(t)?" !important":""};`).join(" ")}function getPseudoElementStyle(e,t,n,r){const o=`.${e}:${t}`,i=n.cssText?formatCSSText(n):formatCSSProperties(n,r);return document.createTextNode(`${o}{${i}}`)}function clonePseudoElement(e,t,n,r){const o=window.getComputedStyle(e,n),i=o.getPropertyValue("content");if(""===i||"none"===i)return;const s=uuid();try{t.className=`${t.className} ${s}`}catch(e){return}const c=document.createElement("style");c.appendChild(getPseudoElementStyle(s,n,o,r)),t.appendChild(c)}function clonePseudoElements(e,t,n){clonePseudoElement(e,t,":before",n),clonePseudoElement(e,t,":after",n)}const WOFF="application/font-woff",JPEG="image/jpeg",mimes={woff:WOFF,woff2:WOFF,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:JPEG,jpeg:JPEG,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function getExtension(e){const t=/\.([^./]*?)$/g.exec(e);return t?t[1]:""}function getMimeType(e){const t=getExtension(e).toLowerCase();return mimes[t]||""}function getContentFromDataUrl(e){return e.split(/,/)[1]}function isDataUrl(e){return-1!==e.search(/^(data:)/)}function makeDataUrl(e,t){return`data:${t};base64,${e}`}async function fetchAsDataURL(e,t,n){const r=await fetch(e,t);if(404===r.status)throw new Error(`Resource "${r.url}" not found`);const o=await r.blob();return new Promise((e,t)=>{const i=new FileReader;i.onerror=t,i.onloadend=()=>{try{e(n({res:r,result:i.result}))}catch(e){t(e)}},i.readAsDataURL(o)})}const cache={};function getCacheKey(e,t,n){let r=e.replace(/\?.*/,"");return n&&(r=e),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),t?`[${t}]${r}`:r}async function resourceToDataURL(e,t,n){const r=getCacheKey(e,t,n.includeQueryParams);if(null!=cache[r])return cache[r];let o;n.cacheBust&&(e+=(/\?/.test(e)?"&":"?")+(new Date).getTime());try{o=makeDataUrl(await fetchAsDataURL(e,n.fetchRequestInit,({res:e,result:n})=>(t||(t=e.headers.get("Content-Type")||""),getContentFromDataUrl(n))),t)}catch(t){o=n.imagePlaceholder||"";let r=`Failed to fetch resource: ${e}`;t&&(r="string"==typeof t?t:t.message),r&&console.warn(r)}return cache[r]=o,o}async function cloneCanvasElement(e){const t=e.toDataURL();return"data:,"===t?e.cloneNode(!1):createImage(t)}async function cloneVideoElement(e,t){if(e.currentSrc){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=e.clientWidth,t.height=e.clientHeight,null==n||n.drawImage(e,0,0,t.width,t.height);return createImage(t.toDataURL())}const n=e.poster,r=getMimeType(n);return createImage(await resourceToDataURL(n,r,t))}async function cloneIFrameElement(e,t){var n;try{if(null===(n=null==e?void 0:e.contentDocument)||void 0===n?void 0:n.body)return await cloneNode(e.contentDocument.body,t,!0)}catch(e){}return e.cloneNode(!1)}async function cloneSingleNode(e,t){return isInstanceOfElement(e,HTMLCanvasElement)?cloneCanvasElement(e):isInstanceOfElement(e,HTMLVideoElement)?cloneVideoElement(e,t):isInstanceOfElement(e,HTMLIFrameElement)?cloneIFrameElement(e,t):e.cloneNode(isSVGElement(e))}const isSlotElement=e=>null!=e.tagName&&"SLOT"===e.tagName.toUpperCase(),isSVGElement=e=>null!=e.tagName&&"SVG"===e.tagName.toUpperCase();async function cloneChildren(e,t,n){var r,o;if(isSVGElement(t))return t;let i=[];return i=isSlotElement(e)&&e.assignedNodes?toArray(e.assignedNodes()):isInstanceOfElement(e,HTMLIFrameElement)&&(null===(r=e.contentDocument)||void 0===r?void 0:r.body)?toArray(e.contentDocument.body.childNodes):toArray((null!==(o=e.shadowRoot)&&void 0!==o?o:e).childNodes),0===i.length||isInstanceOfElement(e,HTMLVideoElement)||await i.reduce((e,r)=>e.then(()=>cloneNode(r,n)).then(e=>{e&&t.appendChild(e)}),Promise.resolve()),t}function cloneCSSStyle(e,t,n){const r=t.style;if(!r)return;const o=window.getComputedStyle(e);o.cssText?(r.cssText=o.cssText,r.transformOrigin=o.transformOrigin):getStyleProperties(n).forEach(n=>{let i=o.getPropertyValue(n);if("font-size"===n&&i.endsWith("px")){const e=Math.floor(parseFloat(i.substring(0,i.length-2)))-.1;i=`${e}px`}isInstanceOfElement(e,HTMLIFrameElement)&&"display"===n&&"inline"===i&&(i="block"),"d"===n&&t.getAttribute("d")&&(i=`path(${t.getAttribute("d")})`),r.setProperty(n,i,o.getPropertyPriority(n))})}function cloneInputValue(e,t){isInstanceOfElement(e,HTMLTextAreaElement)&&(t.innerHTML=e.value),isInstanceOfElement(e,HTMLInputElement)&&t.setAttribute("value",e.value)}function cloneSelectValue(e,t){if(isInstanceOfElement(e,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(t=>e.value===t.getAttribute("value"));r&&r.setAttribute("selected","")}}function decorate(e,t,n){return isInstanceOfElement(t,Element)&&(cloneCSSStyle(e,t,n),clonePseudoElements(e,t,n),cloneInputValue(e,t),cloneSelectValue(e,t)),t}async function ensureSVGSymbols(e,t){const n=e.querySelectorAll?e.querySelectorAll("use"):[];if(0===n.length)return e;const r={};for(let o=0;o<n.length;o++){const i=n[o].getAttribute("xlink:href");if(i){const n=e.querySelector(i),o=document.querySelector(i);n||!o||r[i]||(r[i]=await cloneNode(o,t,!0))}}const o=Object.values(r);if(o.length){const t="http://www.w3.org/1999/xhtml",n=document.createElementNS(t,"svg");n.setAttribute("xmlns",t),n.style.position="absolute",n.style.width="0",n.style.height="0",n.style.overflow="hidden",n.style.display="none";const r=document.createElementNS(t,"defs");n.appendChild(r);for(let e=0;e<o.length;e++)r.appendChild(o[e]);e.appendChild(n)}return e}async function cloneNode(e,t,n){return n||!t.filter||t.filter(e)?Promise.resolve(e).then(e=>cloneSingleNode(e,t)).then(n=>cloneChildren(e,n,t)).then(n=>decorate(e,n,t)).then(e=>ensureSVGSymbols(e,t)):null}const URL_REGEX=/url\((['"]?)([^'"]+?)\1\)/g,URL_WITH_FORMAT_REGEX=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,FONT_SRC_REGEX=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function toRegex(e){const t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function parseURLs(e){const t=[];return e.replace(URL_REGEX,(e,n,r)=>(t.push(r),e)),t.filter(e=>!isDataUrl(e))}async function embed(e,t,n,r,o){try{const i=n?resolveUrl(t,n):t,s=getMimeType(t);let c;return o||(c=await resourceToDataURL(i,s,r)),e.replace(toRegex(t),`$1${c}$3`)}catch(e){}return e}function filterPreferredFontFormat(e,{preferredFontFormat:t}){return t?e.replace(FONT_SRC_REGEX,e=>{for(;;){const[n,,r]=URL_WITH_FORMAT_REGEX.exec(e)||[];if(!r)return"";if(r===t)return`src: ${n};`}}):e}function shouldEmbed(e){return-1!==e.search(URL_REGEX)}async function embedResources(e,t,n){if(!shouldEmbed(e))return e;const r=filterPreferredFontFormat(e,n);return parseURLs(r).reduce((e,r)=>e.then(e=>embed(e,r,t,n)),Promise.resolve(r))}async function embedProp(e,t,n){var r;const o=null===(r=t.style)||void 0===r?void 0:r.getPropertyValue(e);if(o){const r=await embedResources(o,null,n);return t.style.setProperty(e,r,t.style.getPropertyPriority(e)),!0}return!1}async function embedBackground(e,t){await embedProp("background",e,t)||await embedProp("background-image",e,t),await embedProp("mask",e,t)||await embedProp("-webkit-mask",e,t)||await embedProp("mask-image",e,t)||await embedProp("-webkit-mask-image",e,t)}async function embedImageNode(e,t){const n=isInstanceOfElement(e,HTMLImageElement);if((!n||isDataUrl(e.src))&&(!isInstanceOfElement(e,SVGImageElement)||isDataUrl(e.href.baseVal)))return;const r=n?e.src:e.href.baseVal,o=await resourceToDataURL(r,getMimeType(r),t);await new Promise((r,i)=>{e.onload=r,e.onerror=t.onImageErrorHandler?(...e)=>{try{r(t.onImageErrorHandler(...e))}catch(e){i(e)}}:i;const s=e;s.decode&&(s.decode=r),"lazy"===s.loading&&(s.loading="eager"),n?(e.srcset="",e.src=o):e.href.baseVal=o})}async function embedChildren(e,t){const n=toArray(e.childNodes).map(e=>embedImages(e,t));await Promise.all(n).then(()=>e)}async function embedImages(e,t){isInstanceOfElement(e,Element)&&(await embedBackground(e,t),await embedImageNode(e,t),await embedChildren(e,t))}function applyStyle(e,t){const{style:n}=e;t.backgroundColor&&(n.backgroundColor=t.backgroundColor),t.width&&(n.width=`${t.width}px`),t.height&&(n.height=`${t.height}px`);const r=t.style;return null!=r&&Object.keys(r).forEach(e=>{n[e]=r[e]}),e}const cssFetchCache={};async function fetchCSS(e){let t=cssFetchCache[e];if(null!=t)return t;const n=await fetch(e);return t={url:e,cssText:await n.text()},cssFetchCache[e]=t,t}async function embedFonts(e,t){let n=e.cssText;const r=/url\(["']?([^"')]+)["']?\)/g,o=(n.match(/url\([^)]+\)/g)||[]).map(async o=>{let i=o.replace(r,"$1");return i.startsWith("https://")||(i=new URL(i,e.url).href),fetchAsDataURL(i,t.fetchRequestInit,({result:e})=>(n=n.replace(o,`url(${e})`),[o,e]))});return Promise.all(o).then(()=>n)}function parseCSS(e){if(null==e)return[];const t=[];let n=e.replace(/(\/\*[\s\S]*?\*\/)/gi,"");const r=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const e=r.exec(n);if(null===e)break;t.push(e[0])}n=n.replace(r,"");const o=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,i=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");for(;;){let e=o.exec(n);if(null===e){if(e=i.exec(n),null===e)break;o.lastIndex=i.lastIndex}else i.lastIndex=o.lastIndex;t.push(e[0])}return t}async function getCSSRules(e,t){const n=[],r=[];return e.forEach(n=>{if("cssRules"in n)try{toArray(n.cssRules||[]).forEach((e,o)=>{if(e.type===CSSRule.IMPORT_RULE){let i=o+1;const s=fetchCSS(e.href).then(e=>embedFonts(e,t)).then(e=>parseCSS(e).forEach(e=>{try{n.insertRule(e,e.startsWith("@import")?i+=1:n.cssRules.length)}catch(t){console.error("Error inserting rule from remote css",{rule:e,error:t})}})).catch(e=>{console.error("Error loading remote css",e.toString())});r.push(s)}})}catch(o){const i=e.find(e=>null==e.href)||document.styleSheets[0];null!=n.href&&r.push(fetchCSS(n.href).then(e=>embedFonts(e,t)).then(e=>parseCSS(e).forEach(e=>{i.insertRule(e,i.cssRules.length)})).catch(e=>{console.error("Error loading remote stylesheet",e)})),console.error("Error inlining remote css file",o)}}),Promise.all(r).then(()=>(e.forEach(e=>{if("cssRules"in e)try{toArray(e.cssRules||[]).forEach(e=>{n.push(e)})}catch(t){console.error(`Error while reading CSS rules from ${e.href}`,t)}}),n))}function getWebFontRules(e){return e.filter(e=>e.type===CSSRule.FONT_FACE_RULE).filter(e=>shouldEmbed(e.style.getPropertyValue("src")))}async function parseWebFontRules(e,t){if(null==e.ownerDocument)throw new Error("Provided element is not within a Document");const n=toArray(e.ownerDocument.styleSheets);return getWebFontRules(await getCSSRules(n,t))}function normalizeFontFamily(e){return e.trim().replace(/["']/g,"")}function getUsedFonts(e){const t=new Set;return function e(n){(n.style.fontFamily||getComputedStyle(n).fontFamily).split(",").forEach(e=>{t.add(normalizeFontFamily(e))}),Array.from(n.children).forEach(t=>{t instanceof HTMLElement&&e(t)})}(e),t}async function getWebFontCSS(e,t){const n=await parseWebFontRules(e,t),r=getUsedFonts(e);return(await Promise.all(n.filter(e=>r.has(normalizeFontFamily(e.style.fontFamily))).map(e=>{const n=e.parentStyleSheet?e.parentStyleSheet.href:null;return embedResources(e.cssText,n,t)}))).join("\n")}async function embedWebFonts(e,t){const n=null!=t.fontEmbedCSS?t.fontEmbedCSS:t.skipFonts?null:await getWebFontCSS(e,t);if(n){const t=document.createElement("style"),r=document.createTextNode(n);t.appendChild(r),e.firstChild?e.insertBefore(t,e.firstChild):e.appendChild(t)}}async function toSvg(e,t={}){const{width:n,height:r}=getImageSize(e,t),o=await cloneNode(e,t,!0);await embedWebFonts(o,t),await embedImages(o,t),applyStyle(o,t);return await nodeToDataURL(o,n,r)}async function toCanvas(e,t={}){const{width:n,height:r}=getImageSize(e,t),o=await toSvg(e,t),i=await createImage(o),s=document.createElement("canvas"),c=s.getContext("2d"),a=t.pixelRatio||getPixelRatio(),l=t.canvasWidth||n,d=t.canvasHeight||r;return s.width=l*a,s.height=d*a,t.skipAutoScale||checkCanvasDimensions(s),s.style.width=`${l}`,s.style.height=`${d}`,t.backgroundColor&&(c.fillStyle=t.backgroundColor,c.fillRect(0,0,s.width,s.height)),c.drawImage(i,0,0,s.width,s.height),s}async function toPng(e,t={}){return(await toCanvas(e,t)).toDataURL()}async function toJpeg(e,t={}){return(await toCanvas(e,t)).toDataURL("image/jpeg",t.quality||1)}async function resizeDataUrl(e,t,n,r,o){return new Promise((i,s)=>{const c=new Image;c.onload=()=>{const e=c.naturalWidth,a=c.naturalHeight,l=Math.min(t/e,n/a,1),d=Math.max(1,Math.round(e*l)),h=Math.max(1,Math.round(a*l)),u=document.createElement("canvas");u.width=d,u.height=h;const p=u.getContext("2d");if(!p)return void s(new Error("Could not get 2D canvas context"));"jpeg"===r&&(p.fillStyle="#ffffff",p.fillRect(0,0,d,h)),p.drawImage(c,0,0,d,h);const _="jpeg"===r?"image/jpeg":"image/png",f=u.toDataURL(_,o);i({dataUrl:f,width:d,height:h})},c.onerror=()=>s(new Error("Failed to load image for resizing")),c.src=e})}async function takeScreenshot(e,t,n,r,o,i){const s=t??"jpeg",c=n??.75,a=r??1024,l=o??1024,d=i??!1;let h;if(e){if(h=document.querySelector(e),!h)return{error:`No element found for selector: ${e}`}}else h=d?document.documentElement:document.body;try{const t=h,n=window.innerWidth,r=window.innerHeight,o={quality:c,pixelRatio:1,cacheBust:!0,skipAutoScale:!0,filter:e=>"hypha-debugger-host"!==e.id&&"hypha-debugger-cursor"!==e.id&&"playwright-highlight-container"!==e.id};let i;e||d||(o.width=n,o.height=r),i="jpeg"===s?await toJpeg(t,o):await toPng(t,o);const u=await resizeDataUrl(i,a,l,s,c),p=Math.round(.75*u.dataUrl.length/1024);return{data:u.dataUrl,format:s,width:u.width,height:u.height,size_kb:p}}catch(e){return{error:`Screenshot failed: ${e.message??e}`}}}function autoReturn(e){const t=e.trim();if(/\breturn\b/.test(t))return t;let n=t.split("\n").map(e=>e.trim()).filter(Boolean);if(1===n.length&&n[0].includes(";")&&(n=n[0].split(";").map(e=>e.trim()).filter(Boolean)),0===n.length)return t;const r=n[n.length-1];return/^(if|for|while|switch|try|class|function |const |let |var |import |export )/.test(r)?t:(n[n.length-1]="return ("+r.replace(/;$/,"")+");",n.join(";\n"))}async function executeScript(e,t){const n=t??1e4;try{let t,r=autoReturn(e);try{t=new Function("return (async () => {"+r+"})()")}catch{t=new Function("return (async () => {"+e+"})()")}const o=await Promise.race([t(),new Promise((e,t)=>setTimeout(()=>t(new Error("Execution timed out")),n))]);let i,s=typeof o;try{void 0===o?(i=null,s="undefined"):o instanceof HTMLElement?(i={tag:o.tagName.toLowerCase(),id:o.id,className:o.className,text:(o.textContent??"").trim().slice(0,500)},s="HTMLElement"):o instanceof NodeList||o instanceof HTMLCollection?(i=Array.from(o).map(e=>({tag:e.tagName?.toLowerCase(),id:e.id,text:(e.textContent??"").trim().slice(0,200)})),s="NodeList"):i=JSON.parse(JSON.stringify(o))}catch{i=String(o),s="string (serialized)"}return{result:i,type:s}}catch(e){return{error:`Execution error: ${e.message??e}`}}}takeScreenshot.__schema__={name:"takeScreenshot",description:"Capture a screenshot of the current viewport, a specific element, or the full page. Returns a base64-encoded data URL, downscaled to fit within max_width × max_height (default 1024px) to keep the payload small enough for AI agents. Defaults to JPEG format at 0.75 quality for reasonable file size.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element to capture. Omit to capture the viewport (or full page if full_page=true)."},format:{type:"string",enum:["png","jpeg"],description:'Image format. Default: "jpeg" (much smaller than PNG). Use "png" for sharp text.'},quality:{type:"number",description:"JPEG quality (0–1). Default: 0.75. Ignored for PNG. Lower = smaller payload."},max_width:{type:"number",description:"Maximum output width in pixels. Default: 1024. Image is scaled down preserving aspect ratio."},max_height:{type:"number",description:"Maximum output height in pixels. Default: 1024. Image is scaled down preserving aspect ratio."},full_page:{type:"boolean",description:"If true, capture the entire scrollable page instead of just the viewport. Default: false."}}}},executeScript.__schema__={name:"executeScript",description:'Execute arbitrary JavaScript code in the page context. Supports async/await. The last expression is auto-returned (no need for explicit "return"). Examples: "document.title", "document.querySelectorAll(\'a\').length", "await fetch(\'/api/data\').then(r => r.json())".',parameters:{type:"object",properties:{code:{type:"string",description:'JavaScript code to execute. The last expression is automatically returned. Examples: "document.title", "document.querySelector(\'h1\').textContent".'},timeout_ms:{type:"number",description:"Maximum execution time in milliseconds. Default: 10000."}},required:["code"]}};const STORAGE_KEY$1="__hypha_debugger_config__";function getScriptUrl(){try{const e=sessionStorage.getItem(STORAGE_KEY$1);if(e){const t=JSON.parse(e);if(t.script_url)return t.script_url}}catch{}return"https://cdn.jsdelivr.net/npm/hypha-debugger/dist/hypha-debugger.min.js"}function injectLoader(e,t){const n=`<script src="${t}"><\/script>`;return e.includes("</body>")?e.replace("</body>",n+"\n</body>"):e.includes("</html>")?e.replace("</html>",n+"\n</html>"):e+"\n"+n}function softReplace(e,t){const n=getScriptUrl();fetch(e,{credentials:"same-origin",cache:"reload"}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);if(!(e.headers.get("content-type")??"").includes("text/html"))throw new Error("Not HTML");return e.text()}).then(e=>{const r=injectLoader(e,n);if(document.open(),document.write(r),document.close(),t)try{history.pushState({},"",t)}catch{}}).catch(()=>{t?window.location.href=t:window.location.reload()})}function isSameOrigin(e){try{return new URL(e,location.href).origin===location.origin}catch{return!1}}let _interceptInstalled=!1;function installNavigationInterceptor(){if(_interceptInstalled)return()=>{};_interceptInstalled=!0;const e=e=>{if(e.defaultPrevented||0!==e.button)return;if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=null,n=e.target;for(;n;){if("A"===n.tagName){t=n;break}n=n.parentElement}if(!t)return;const r=t.href;if(!r)return;if(t.target&&"_self"!==t.target)return;if(t.hasAttribute("download"))return;if(r.startsWith("javascript:")||r.startsWith("mailto:")||r.startsWith("tel:"))return;try{const e=new URL(r,location.href);if(e.origin===location.origin&&e.pathname===location.pathname&&e.search===location.search&&e.hash!==location.hash)return}catch{return}if(!isSameOrigin(r))return;e.preventDefault();const o=new URL(r,location.href).href;softReplace(o,o)},t=e=>{if(e.defaultPrevented)return;const t=e.target;if("GET"!==(t.method||"GET").toUpperCase())return;const n=t.action||location.href;if(!isSameOrigin(n))return;const r=new FormData(t),o=new URL(n,location.href);for(const[e,t]of r.entries())"string"==typeof t&&o.searchParams.set(e,t);t.target&&"_self"!==t.target||(e.preventDefault(),softReplace(o.href,o.href))},n=()=>{softReplace(location.href)};return document.addEventListener("click",e,!0),document.addEventListener("submit",t,!0),window.addEventListener("popstate",n),()=>{document.removeEventListener("click",e,!0),document.removeEventListener("submit",t,!0),window.removeEventListener("popstate",n),_interceptInstalled=!1}}function navigate(e){try{const t=new URL(e,location.href);return t.origin===location.origin?(setTimeout(()=>softReplace(t.href,t.href),150),{success:!0,message:`Navigating to ${e} (debugger will auto-reconnect)`}):(window.location.href=e,{success:!0,message:`Navigating to ${e} (cross-origin, debugger will disconnect)`})}catch(e){return{success:!1,message:`Navigation failed: ${e.message??e}`}}}function goBack(){try{return window.history.back(),{success:!0,message:"Navigated back (debugger will auto-reconnect via popstate)"}}catch(e){return{success:!1,message:`Back navigation failed: ${e.message??e}`}}}function goForward(){try{return window.history.forward(),{success:!0,message:"Navigated forward (debugger will auto-reconnect via popstate)"}}catch(e){return{success:!1,message:`Forward navigation failed: ${e.message??e}`}}}function reload(){try{return setTimeout(()=>softReplace(location.href),150),{success:!0,message:"Reloading page (debugger will auto-reconnect)"}}catch(e){return{success:!1,message:`Reload failed: ${e.message??e}`}}}function getFiberFromDOM(e){const t=Object.keys(e).find(e=>e.startsWith("__reactFiber$")||e.startsWith("__reactInternalInstance$"));return t?e[t]:null}function getComponentName(e){const{type:t}=e;if(!t)return"(unknown)";if("string"==typeof t)return t;if("function"==typeof t)return t.displayName||t.name||"Anonymous";if("object"==typeof t){if(t.displayName)return t.displayName;if(t.render)return t.render.displayName||t.render.name||"ForwardRef";if(t.type)return getComponentName({type:t.type});if("Symbol(react.memo)"===t.$$typeof?.toString())return`Memo(${getComponentName({type:t.type})})`}return"(unknown)"}function getFiberType(e){return 0===e.tag||11===e.tag||14===e.tag||15===e.tag?"function":1===e.tag?"class":5===e.tag||6===e.tag?"host":"other"}function safeSerialize(e,t=0,n=2){if(t>n)return"[max depth]";if(null==e)return e;if("function"==typeof e)return`[Function: ${e.name||"anonymous"}]`;if("object"!=typeof e)return e;if(e instanceof HTMLElement)return`[${e.tagName.toLowerCase()}#${e.id}]`;if(Array.isArray(e))return e.slice(0,10).map(e=>safeSerialize(e,t+1,n));const r={},o=Object.keys(e).slice(0,20);for(const i of o)if(!i.startsWith("_")&&!i.startsWith("$$"))try{r[i]=safeSerialize(e[i],t+1,n)}catch{r[i]="[unserializable]"}return r}function extractState(e){if(1===e.tag&&e.stateNode)return safeSerialize(e.stateNode.state);if(0===e.tag||11===e.tag||15===e.tag){const t=[];let n=e.memoizedState,r=0;for(;n&&r<20;)null!==n.queue&&void 0!==n.queue&&t.push(safeSerialize(n.memoizedState)),n=n.next,r++;return t.length>0?t:null}return null}function fiberToInfo(e,t,n){const r=getFiberType(e),o="function"===r||"class"===r,i={name:getComponentName(e),type:r,props:o?safeSerialize(e.memoizedProps):{},state:o?extractState(e):null,key:e.key,children:[]};if(t<n){let r=e.child;for(;r;){const e=fiberToInfo(r,t+1,n);e&&("host"!==e.type||e.children.length>0)&&i.children.push(e),r=r.sibling}}return i}function getReactTree(e,t){e=e??"#root";const n=t??5,r=document.querySelector(e);if(!r)return{error:`No element found for selector: ${e}`};const o=getFiberFromDOM(r);if(!o)return{error:`No React fiber found on element "${e}". Is this a React app?`};let i=o;for(;i&&3===i.tag;)i=i.child;if(!i)return{error:"Could not find root React component fiber."};const s=fiberToInfo(i,0,n);return s||{error:"Could not build React component tree."}}function generateSkillMd(e,t){const n=["---","name: web-debugger","description: Remote web page debugger. Inspect DOM, take screenshots, execute JavaScript, fill forms, click elements, and navigate pages — all via HTTP API calls.","compatibility: Requires network access to the Hypha server. Works with any HTTP client (curl, fetch, Python requests).","metadata:",' version: "0.1"',' author: "hypha-debugger"',"---"].join("\n"),r=["","# Web Debugger Skill","","This skill allows you to remotely debug and interact with a web page through HTTP API endpoints.","Pick the approach that fits your task — they can be combined freely.","","## Approaches","","### execute_script — Run Arbitrary JavaScript","","The most versatile function. Use it to read/modify page state, call APIs, query the DOM,","or do anything JavaScript can do. The last expression is auto-returned (no need for `return`).","","```bash","# Read page state","curl -X POST '{SERVICE_URL}/execute_script' \\"," -H 'Content-Type: application/json' -d '{\"code\": \"document.title\"}'","","# Query DOM","curl -X POST '{SERVICE_URL}/execute_script' \\",' -H \'Content-Type: application/json\' -d \'{"code": "document.querySelector(\\"h1\\").textContent"}\'',"","# Call an API","curl -X POST '{SERVICE_URL}/execute_script' \\",' -H \'Content-Type: application/json\' -d \'{"code": "await fetch(\\"/api/data\\").then(r => r.json())"}\'',"","# Modify the page","curl -X POST '{SERVICE_URL}/execute_script' \\",' -H \'Content-Type: application/json\' -d \'{"code": "document.getElementById(\\"name\\").value = \\"Alice\\""}\'',"```","","### get_browser_state + Index-Based Interaction","","Best for UI interaction as a user would — clicking buttons, filling forms, selecting options.","All interactive elements are detected and indexed as `[0]`, `[1]`, `[2]`, etc.","","```bash","# Step 1: See all interactive elements","curl '{SERVICE_URL}/get_browser_state'","","# Step 2: Act by index","curl -X POST '{SERVICE_URL}/click_element_by_index' \\"," -H 'Content-Type: application/json' -d '{\"index\": 2}'","","curl -X POST '{SERVICE_URL}/input_text' \\",' -H \'Content-Type: application/json\' -d \'{"index": 1, "text": "hello world"}\'',"","curl -X POST '{SERVICE_URL}/select_option' \\",' -H \'Content-Type: application/json\' -d \'{"index": 3, "option_text": "French"}\'',"","curl -X POST '{SERVICE_URL}/scroll' \\"," -H 'Content-Type: application/json' -d '{\"direction\": \"down\"}'","","# Step 3: Verify visually","curl '{SERVICE_URL}/take_screenshot'","```","","### get_react_tree — Inspect React Components","","If the page uses React, inspect component names, props, state, and hooks:","```bash","curl '{SERVICE_URL}/get_react_tree'","```","","### CSS Selector-Based Functions","","Use CSS selectors directly when you know the element:","```bash","curl -X POST '{SERVICE_URL}/click_element' \\"," -H 'Content-Type: application/json' -d '{\"selector\": \"button.submit\"}'","","curl -X POST '{SERVICE_URL}/fill_input' \\",' -H \'Content-Type: application/json\' -d \'{"selector": "#email", "value": "user@example.com"}\'',"","curl -X POST '{SERVICE_URL}/query_dom' \\"," -H 'Content-Type: application/json' -d '{\"selector\": \".product-card\"}'","```","","## How to call functions","","All functions are available as HTTP endpoints. Replace `{SERVICE_URL}` with the actual service URL.","","- **GET** for functions with no required parameters","- **POST** with JSON body for functions with parameters",""].join("\n"),o=["## Available Functions",""],i=Object.entries(e).filter(([e,t])=>t?.__schema__&&"get_skill_md"!==e);for(const[e,t]of i){const n=t.__schema__;o.push(`### \`${e}\``),o.push(""),o.push(n.description),o.push("");const r=n.parameters?.properties,i=n.parameters?.required??[];if(r&&Object.keys(r).length>0){o.push("**Parameters:**"),o.push(""),o.push("| Parameter | Type | Required | Description |"),o.push("|-----------|------|----------|-------------|");for(const[e,t]of Object.entries(r)){const n=i.includes(e);let r=t.type??"any";t.enum&&(r=t.enum.map(e=>`"${e}"`).join(" | ")),t.items&&(r=`${t.items.type}[]`),o.push(`| \`${e}\` | ${r} | ${n?"Yes":"No"} | ${t.description??""} |`)}if(o.push(""),i.length>0){const t={};for(const e of i){const n=r[e];t[e]="string"===n?.type?`<${e}>`:"number"===n?.type?"0":`<${e}>`}o.push("**Example:**"),o.push("```bash"),o.push(`curl -X POST '{SERVICE_URL}/${e}' \\`),o.push(" -H 'Content-Type: application/json' \\"),o.push(` -d '${JSON.stringify(t)}'`),o.push("```")}else o.push("**Example:**"),o.push("```bash"),o.push(`curl '{SERVICE_URL}/${e}'`),o.push("```")}else o.push("**Parameters:** None"),o.push(""),o.push("**Example:**"),o.push("```bash"),o.push(`curl '{SERVICE_URL}/${e}'`),o.push("```");o.push("")}const s=["## Tips","","- **`execute_script` is the most versatile** — use it for reading state, calling APIs, DOM queries, or anything not covered by other functions. The last expression is auto-returned.","- **`get_browser_state` is the best way to see what's on the page** — it detects all interactive elements and shows them as indexed items.","- **After each action, call `get_browser_state` again** — element indices change when the DOM updates.","- **Use `take_screenshot`** to visually verify the page state. Call `remove_highlights` first for a clean view.","- **Use `scroll`** with an element index to scroll inside a specific container (e.g. a chat window, sidebar).","- **Use `get_page_info` with `include_logs=true`** to check for JavaScript errors or debug output.","- **Use `get_react_tree`** if the page uses React — it gives you component names, props, and state without needing DevTools.","- **Use `navigate`** to go to other pages — same-origin navigation auto-reconnects the debugger.","- All POST endpoints accept JSON body with the parameter names as keys.",""].join("\n");return[n,r,o.join("\n"),s].join("\n")}function wrapFn(e){const t=e.__schema__,n=t?.parameters?.properties?Object.keys(t.parameters.properties):[];if(0===n.length)return e;const r=n.join(", "),o=n[0],i=new Function("fn","paramNames",`return async function(${r}) {\n // Detect kwargs-as-object: single argument that is a plain object\n if (arguments.length === 1 && ${o} != null && typeof ${o} === "object" && !Array.isArray(${o}) && !(${o} instanceof Date) && ${o}.constructor === Object) {\n var _kw = ${o};\n var _keys = Object.keys(_kw);\n // Empty object {} → call with no args (all defaults)\n if (_keys.length === 0) {\n return fn();\n }\n // Keys match schema params → destructure\n if (paramNames.indexOf(_keys[0]) !== -1) {\n var _args = paramNames.map(function(n) { return _kw[n]; });\n return fn.apply(null, _args);\n }\n }\n return fn(${r});\n }`)(e,n);return t&&(i.__schema__=t),i}navigate.__schema__={name:"navigate",description:"Navigate the browser to a new URL. For same-origin URLs, the debugger auto-reconnects. Cross-origin navigation will disconnect the debugger.",parameters:{type:"object",properties:{url:{type:"string",description:"The URL to navigate to."}},required:["url"]}},goBack.__schema__={name:"goBack",description:"Navigate back in browser history. The debugger auto-reconnects for same-origin pages.",parameters:{type:"object",properties:{}}},goForward.__schema__={name:"goForward",description:"Navigate forward in browser history. The debugger auto-reconnects for same-origin pages.",parameters:{type:"object",properties:{}}},reload.__schema__={name:"reload",description:"Reload the current page. The debugger auto-reconnects after reload using soft page replacement.",parameters:{type:"object",properties:{}}},getReactTree.__schema__={name:"getReactTree",description:"Inspect the React component tree starting from a DOM element. Returns component names, props, state (including hooks), and children hierarchy.",parameters:{type:"object",properties:{selector:{type:"string",description:'CSS selector of the React root element. Default: "#root".'},max_depth:{type:"number",description:"Maximum depth to traverse the component tree. Default: 5."}}}};var domTree=(e={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:t,interactiveWhitelist:n,highlightOpacity:r,highlightLabelOpacity:o}=e,{doHighlightElements:i,focusHighlightIndex:s,viewportExpansion:c,debugMode:a}=e;let l=0;const d=new WeakMap;const h={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{h.boundingRects=new WeakMap,h.clientRects=new WeakMap,h.computedStyles=new WeakMap}};function u(e){if(!e)return null;if(h.boundingRects.has(e))return h.boundingRects.get(e);const t=e.getBoundingClientRect();return t&&h.boundingRects.set(e,t),t}function p(e){if(!e)return null;if(h.computedStyles.has(e))return h.computedStyles.get(e);const t=window.getComputedStyle(e);return t&&h.computedStyles.set(e,t),t}const _={},f={current:0},m="playwright-highlight-container";function g(e,t,n=null){if(!e)return t;const i=[];let s=null,c=20,a=16,l=null;try{let d=document.getElementById(m);d||(d=document.createElement("div"),d.id=m,d.style.position="fixed",d.style.pointerEvents="none",d.style.top="0",d.style.left="0",d.style.width="100%",d.style.height="100%",d.style.zIndex="2147483640",d.style.backgroundColor="transparent",document.body.appendChild(d));const h=e.getClientRects();if(!h||0===h.length)return t;const u=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];let p=u[t%u.length];const _=p+Math.floor(255*r).toString(16).padStart(2,"0");p+=Math.floor(255*o).toString(16).padStart(2,"0");let f={x:0,y:0};if(n){const e=n.getBoundingClientRect();f.x=e.left,f.y=e.top}const g=document.createDocumentFragment();for(const e of h){if(0===e.width||0===e.height)continue;const t=document.createElement("div");t.style.position="fixed",t.style.border=`2px solid ${p}`,t.style.backgroundColor=_,t.style.pointerEvents="none",t.style.boxSizing="border-box";const n=e.top+f.y,r=e.left+f.x;t.style.top=`${n}px`,t.style.left=`${r}px`,t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,g.appendChild(t),i.push({element:t,initialRect:e})}const y=h[0];s=document.createElement("div"),s.className="playwright-highlight-label",s.style.position="fixed",s.style.background=p,s.style.color="white",s.style.padding="1px 4px",s.style.borderRadius="4px",s.style.fontSize=`${Math.min(12,Math.max(8,y.height/2))}px`,s.textContent=t.toString(),c=s.offsetWidth>0?s.offsetWidth:c,a=s.offsetHeight>0?s.offsetHeight:a;const w=y.top+f.y,b=y.left+f.x;let v=w+2,E=b+y.width-c-2;(y.width<c+4||y.height<a+4)&&(v=w-a-2,E=b+y.width-c,E<f.x&&(E=b)),v=Math.max(0,Math.min(v,window.innerHeight-a)),E=Math.max(0,Math.min(E,window.innerWidth-c)),s.style.top=`${v}px`,s.style.left=`${E}px`,g.appendChild(s);const k=(e,t)=>{let n=0;return(...r)=>{const o=performance.now();if(!(o-n<t))return n=o,e(...r)}},x=k(()=>{const t=e.getClientRects();let r={x:0,y:0};if(n){const e=n.getBoundingClientRect();r.x=e.left,r.y=e.top}if(i.forEach((e,n)=>{if(n<t.length){const o=t[n],i=o.top+r.y,s=o.left+r.x;e.element.style.top=`${i}px`,e.element.style.left=`${s}px`,e.element.style.width=`${o.width}px`,e.element.style.height=`${o.height}px`,e.element.style.display=0===o.width||0===o.height?"none":"block"}else e.element.style.display="none"}),t.length<i.length)for(let e=t.length;e<i.length;e++)i[e].element.style.display="none";if(s&&t.length>0){const e=t[0],n=e.top+r.y,o=e.left+r.x;let i=n+2,l=o+e.width-c-2;(e.width<c+4||e.height<a+4)&&(i=n-a-2,l=o+e.width-c,l<r.x&&(l=o)),i=Math.max(0,Math.min(i,window.innerHeight-a)),l=Math.max(0,Math.min(l,window.innerWidth-c)),s.style.top=`${i}px`,s.style.left=`${l}px`,s.style.display="block"}else s&&(s.style.display="none")},16);return window.addEventListener("scroll",x,!0),window.addEventListener("resize",x),l=()=>{window.removeEventListener("scroll",x,!0),window.removeEventListener("resize",x),i.forEach(e=>e.element.remove()),s&&s.remove()},d.appendChild(g),t+1}finally{l&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(l)}}function y(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return null;const t=p(e);if(!t)return null;const n=t.display;if("inline"===n||"inline-block"===n)return null;const r=t.overflowX,o=t.overflowY,i="auto"===r||"scroll"===r,s="auto"===o||"scroll"===o;if(!i&&!s)return null;const c=e.scrollWidth-e.clientWidth,a=e.scrollHeight-e.clientHeight;if(c<4&&a<4)return null;if(!s&&c<4)return null;if(!i&&a<4)return null;const l=e.scrollTop,h=e.scrollLeft,u={top:l,right:e.scrollWidth-e.clientWidth-e.scrollLeft,bottom:e.scrollHeight-e.clientHeight-e.scrollTop,left:h};return function(e,t){e&&e.nodeType===Node.ELEMENT_NODE&&d.set(e,{...d.get(e),...t})}(e,{scrollable:!0,scrollData:u}),u}function w(e){try{if(-1===c){const t=e.parentElement;if(!t)return!1;try{return t.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch(e){const n=window.getComputedStyle(t);return"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity}}const t=document.createRange();t.selectNodeContents(e);const n=t.getClientRects();if(!n||0===n.length)return!1;let r=!1,o=!1;for(const e of n)if(e.width>0&&e.height>0&&(r=!0,!(e.bottom<-c||e.top>window.innerHeight+c||e.right<-c||e.left>window.innerWidth+c))){o=!0;break}if(!r||!o)return!1;const i=e.parentElement;if(!i)return!1;try{return i.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch(e){const t=window.getComputedStyle(i);return"none"!==t.display&&"hidden"!==t.visibility&&"0"!==t.opacity}}catch(e){return console.warn("Error checking text node visibility:",e),!1}}function b(e){const t=p(e);return e.offsetWidth>0&&e.offsetHeight>0&&"hidden"!==t?.visibility&&"none"!==t?.display}function v(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;if(t.includes(e))return!1;if(n.includes(e))return!0;const r=e.tagName.toLowerCase(),o=p(e),i=new Set(["pointer","move","text","grab","grabbing","cell","copy","alias","all-scroll","col-resize","context-menu","crosshair","e-resize","ew-resize","help","n-resize","ne-resize","nesw-resize","ns-resize","nw-resize","nwse-resize","row-resize","s-resize","se-resize","sw-resize","vertical-text","w-resize","zoom-in","zoom-out"]),s=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);let c=function(e){return"html"!==e.tagName.toLowerCase()&&!(!o?.cursor||!i.has(o.cursor))}(e);if(c)return!0;const a=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),l=new Set(["disabled","readonly"]);if(a.has(r)){if(o?.cursor&&s.has(o.cursor))return!1;for(const t of l)if(e.hasAttribute(t)||"true"===e.getAttribute(t)||""===e.getAttribute(t))return!1;return!e.disabled&&(!e.readOnly&&!e.inert)}const d=e.getAttribute("role"),h=e.getAttribute("aria-role");if("true"===e.getAttribute("contenteditable")||e.isContentEditable)return!0;if(e.classList&&(e.classList.contains("button")||e.classList.contains("dropdown-toggle")||e.getAttribute("data-index")||"dropdown"===e.getAttribute("data-toggle")||"true"===e.getAttribute("aria-haspopup")))return!0;const u=new Set(["button","menu","menubar","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);if(a.has(r)||d&&u.has(d)||h&&u.has(h))return!0;try{if("function"==typeof getEventListeners){const t=getEventListeners(e),n=["click","mousedown","mouseup","dblclick"];for(const e of n)if(t[e]&&t[e].length>0)return!0}const t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if("function"==typeof t){const n=t(e),r=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const e of r)for(const t of n)if(t.type===e)return!0}const n=["onclick","onmousedown","onmouseup","ondblclick"];for(const t of n)if(e.hasAttribute(t)||"function"==typeof e[t])return!0}catch(e){}return!!y(e)}function E(e){if(-1===c)return!0;const t=function(e){if(!e)return null;if(h.clientRects.has(e))return h.clientRects.get(e);const t=e.getClientRects();return t&&h.clientRects.set(e,t),t}(e);if(!t||0===t.length)return!1;let n=!1;for(const e of t)if(e.width>0&&e.height>0&&!(e.bottom<-c||e.top>window.innerHeight+c||e.right<-c||e.left>window.innerWidth+c)){n=!0;break}if(!n)return!1;if(e.ownerDocument!==window.document)return!0;let r=Array.from(t).find(e=>e.width>0&&e.height>0);if(!r)return!1;const o=e.getRootNode();if(o instanceof ShadowRoot){const t=r.left+r.width/2,n=r.top+r.height/2;try{const r=o.elementFromPoint(t,n);if(!r)return!1;let i=r;for(;i&&i!==o;){if(i===e)return!0;i=i.parentElement}return!1}catch(e){return!0}}return[{x:r.left+r.width/2,y:r.top+r.height/2},{x:r.left+5,y:r.top+5},{x:r.right-5,y:r.bottom-5}].some(({x:t,y:n})=>{try{const r=document.elementFromPoint(t,n);if(!r)return!1;let o=r;for(;o&&o!==document.documentElement;){if(o===e)return!0;o=o.parentElement}return!1}catch(e){return!0}})}const k=new Set(["a","button","input","select","textarea","summary","details","label","option"]),x=new Set(["button","link","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);function S(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;const t=e.tagName.toLowerCase(),n=e.getAttribute("role");if("iframe"===t)return!0;if(k.has(t))return!0;if(n&&x.has(n))return!0;if(e.isContentEditable||"true"===e.getAttribute("contenteditable"))return!0;if(e.hasAttribute("data-testid")||e.hasAttribute("data-cy")||e.hasAttribute("data-test"))return!0;if(e.hasAttribute("onclick")||"function"==typeof e.onclick)return!0;try{const t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if("function"==typeof t){const n=t(e),r=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const e of r)for(const t of n)if(t.type===e)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(t=>e.hasAttribute(t)))return!0}catch(e){}return!!function(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;if(!b(e))return!1;const t=e.hasAttribute("role")||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||"function"==typeof e.onclick,n=/\b(btn|clickable|menu|item|entry|link)\b/i.test(e.className||""),r=Boolean(e.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar')),o=[...e.children].some(b),i=e.parentElement&&e.parentElement.isSameNode(document.body);return(v(e)||t||n)&&o&&r&&!i}(e)}function T(e,t,n,r){if(!e.isInteractive)return!1;let o=!1;return o=!r||!!S(t),!(!o||(e.isInViewport=function(e,t){if(-1===t)return!0;const n=e.getClientRects();if(!n||0===n.length){const n=u(e);return!(!n||0===n.width||0===n.height||n.bottom<-t||n.top>window.innerHeight+t||n.right<-t||n.left>window.innerWidth+t)}for(const e of n)if(0!==e.width&&0!==e.height&&!(e.bottom<-t||e.top>window.innerHeight+t||e.right<-t||e.left>window.innerWidth+t))return!0;return!1}(t,c),!e.isInViewport&&-1!==c||(e.highlightIndex=l++,!i)))&&(s>=0?s===e.highlightIndex&&g(t,e.highlightIndex,n):g(t,e.highlightIndex,n),!0)}const C=function e(t,n=null,r=!1){if(!t||t.id===m||t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE)return null;if(!t||t.id===m)return null;if("true"===t.dataset?.browserUseIgnore||"true"===t.dataset?.pageAgentIgnore)return null;if(t.getAttribute&&"true"===t.getAttribute("aria-hidden"))return null;if(t===document.body){const r={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const o of t.childNodes){const t=e(o,n,!1);t&&r.children.push(t)}const o=""+f.current++;return _[o]=r,o}if(t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE)return null;if(t.nodeType===Node.TEXT_NODE){const e=t.textContent?.trim();if(!e)return null;const n=t.parentElement;if(!n||"script"===n.tagName.toLowerCase())return null;const r=""+f.current++;return _[r]={type:"TEXT_NODE",text:e,isVisible:w(t)},r}if(t.nodeType===Node.ELEMENT_NODE&&!function(e){if(!e||!e.tagName)return!1;const t=new Set(["body","div","main","article","section","nav","header","footer"]),n=e.tagName.toLowerCase();return!!t.has(n)||!new Set(["svg","script","style","link","meta","noscript","template"]).has(n)}(t))return null;if(-1!==c&&!t.shadowRoot){const e=u(t),n=p(t),r=n&&("fixed"===n.position||"sticky"===n.position),o=t.offsetWidth>0||t.offsetHeight>0;if(!e||!r&&!o&&(e.bottom<-c||e.top>window.innerHeight+c||e.right<-c||e.left>window.innerWidth+c))return null}const o={tagName:t.tagName.toLowerCase(),attributes:{},children:[]};if(function(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;const t=e.tagName.toLowerCase();return!!new Set(["a","button","input","select","textarea","details","summary","label"]).has(t)||(e.hasAttribute("onclick")||e.hasAttribute("role")||e.hasAttribute("tabindex")||e.hasAttribute("aria-")||e.hasAttribute("data-action")||"true"===e.getAttribute("contenteditable"))}(t)||"iframe"===t.tagName.toLowerCase()||"body"===t.tagName.toLowerCase()){const e=t.getAttributeNames?.()||[];for(const n of e){const e=t.getAttribute(n);o.attributes[n]=e}"input"!==t.tagName.toLowerCase()||"checkbox"!==t.type&&"radio"!==t.type||(o.attributes.checked=t.checked?"true":"false")}let i=!1;if(t.nodeType===Node.ELEMENT_NODE&&(o.isVisible=b(t),o.isVisible)){o.isTopElement=E(t);const e=t.getAttribute("role"),s="menu"===e||"menubar"===e||"listbox"===e;if((o.isTopElement||s)&&(o.isInteractive=v(t),i=T(o,t,n,r),o.ref=t,o.isInteractive&&0===Object.keys(o.attributes).length)){const e=t.getAttributeNames?.()||[];for(const n of e){const e=t.getAttribute(n);o.attributes[n]=e}}}if(t.tagName){const s=t.tagName.toLowerCase();if("iframe"===s)try{const n=t.contentDocument||t.contentWindow?.document;if(n)for(const r of n.childNodes){const n=e(r,t,!1);n&&o.children.push(n)}}catch(e){console.warn("Unable to access iframe:",e)}else if(t.isContentEditable||"true"===t.getAttribute("contenteditable")||"tinymce"===t.id||t.classList.contains("mce-content-body")||"body"===s&&t.getAttribute("data-id")?.startsWith("mce_"))for(const r of t.childNodes){const t=e(r,n,i);t&&o.children.push(t)}else{if(t.shadowRoot){o.shadowRoot=!0;for(const r of t.shadowRoot.childNodes){const t=e(r,n,i);t&&o.children.push(t)}}for(const s of t.childNodes){const t=e(s,n,i||r);t&&o.children.push(t)}}}if("a"===o.tagName&&0===o.children.length&&!o.attributes.href){const e=u(t);if(!(e&&e.width>0&&e.height>0||t.offsetWidth>0||t.offsetHeight>0))return null}o.extra=d.get(t)||null;const s=""+f.current++;return _[s]=o,s}(document.body);return h.clearCache(),{rootId:C,map:_}};const DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(e){return e??DEFAULT_VIEWPORT_EXPANSION}const newElementsCache=new WeakMap;function getFlatTree(e){const t=resolveViewportExpansion(e.viewportExpansion),n=[];for(const t of e.interactiveBlacklist||[])"function"==typeof t?n.push(t()):n.push(t);const r=[];for(const t of e.interactiveWhitelist||[])"function"==typeof t?r.push(t()):r.push(t);const o=domTree({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:t,interactiveBlacklist:n,interactiveWhitelist:r,highlightOpacity:e.highlightOpacity??0,highlightLabelOpacity:e.highlightLabelOpacity??.1});for(const e in o.map){const t=o.map[e];if(t.isInteractive&&t.ref){const e=t.ref;newElementsCache.has(e)||(newElementsCache.set(e,window.location.href),t.isNew=!0)}}return o}const globRegexCache=new Map;function globToRegex(e){let t=globRegexCache.get(e);if(!t){const n=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");t=new RegExp(`^${n.replace(/\*/g,".*")}$`),globRegexCache.set(e,t)}return t}function matchAttributes(e,t){const n={};for(const r of t)if(r.includes("*")){const t=globToRegex(r);for(const r of Object.keys(e))t.test(r)&&e[r].trim()&&(n[r]=e[r].trim())}else{const t=e[r];t&&t.trim()&&(n[r]=t.trim())}return n}function flatTreeToString(e,t){const n=[...t||[],"title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","id","for","target","aria-haspopup","aria-controls","aria-owns","contenteditable"],r=t=>{const n=e.map[t];if(!n)return null;if("TEXT_NODE"===n.type){const e=n;return{type:"text",text:e.text,isVisible:e.isVisible,parent:null,children:[]}}{const e=n,t=[];if(e.children)for(const n of e.children){const e=r(n);e&&t.push(e)}return{type:"element",tagName:e.tagName,attributes:e.attributes??{},isVisible:e.isVisible??!1,isInteractive:e.isInteractive??!1,isTopElement:e.isTopElement??!1,isNew:e.isNew??!1,highlightIndex:e.highlightIndex,parent:null,children:t,extra:e.extra??{}}}},o=(e,t=null)=>{e.parent=t;for(const t of e.children)o(t,e)},i=r(e.rootId);if(!i)return"";o(i);const s=(e,t,r)=>{let o=t;const i="\t".repeat(t);if("element"===e.type){if(void 0!==e.highlightIndex){o+=1;const t=getAllTextTillNextClickableElement(e);let s="";if(n.length>0&&e.attributes){const r=matchAttributes(e.attributes,n),o=Object.keys(r);if(o.length>1){const e=new Set,t={};for(const n of o){const o=r[n];o.length>5&&(o in t?e.add(n):t[o]=n)}for(const t of e)delete r[t]}r.role===e.tagName&&delete r.role;const i=["aria-label","placeholder","title"];for(const e of i)r[e]&&r[e].toLowerCase().trim()===t.toLowerCase().trim()&&delete r[e];Object.keys(r).length>0&&(s=Object.entries(r).map(([e,t])=>`${e}=${((e,t)=>e.length>t?e.substring(0,t)+"...":e)(t,20)}`).join(" "))}let c=`${i}${e.isNew?`*[${e.highlightIndex}]`:`[${e.highlightIndex}]`}<${e.tagName??""}`;if(s&&(c+=` ${s}`),e.extra&&e.extra.scrollable){let t="";e.extra.scrollData?.left&&(t+=`left=${e.extra.scrollData.left}, `),e.extra.scrollData?.top&&(t+=`top=${e.extra.scrollData.top}, `),e.extra.scrollData?.right&&(t+=`right=${e.extra.scrollData.right}, `),e.extra.scrollData?.bottom&&(t+=`bottom=${e.extra.scrollData.bottom}`),c+=` data-scrollable="${t}"`}if(t){s||(c+=" "),c+=`>${t.trim()}`}else s||(c+=" ");c+=" />",r.push(c)}for(const t of e.children)s(t,o,r)}else if("text"===e.type){if((e=>{let t=e.parent;for(;t;){if("element"===t.type&&void 0!==t.highlightIndex)return!0;t=t.parent}return!1})(e))return;e.parent&&"element"===e.parent.type&&e.parent.isVisible&&e.parent.isTopElement&&r.push(`${i}${e.text??""}`)}},c=[];return s(i,0,c),c.join("\n")}const getAllTextTillNextClickableElement=(e,t=-1)=>{const n=[],r=(o,i)=>{if(!(-1!==t&&i>t||"element"===o.type&&o!==e&&void 0!==o.highlightIndex))if("text"===o.type&&o.text)n.push(o.text);else if("element"===o.type)for(const e of o.children)r(e,i+1)};return r(e,0),n.join("\n").trim()};function getSelectorMap(e){const t=new Map,n=Object.keys(e.map);for(const r of n){const n=e.map[r];n.isInteractive&&"number"==typeof n.highlightIndex&&t.set(n.highlightIndex,n)}return t}function getElementTextMap(e){const t=e.split("\n").map(e=>e.trim()).filter(e=>e.length>0),n=new Map;for(const e of t){const t=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(e);if(t){const r=parseInt(t[1],10);n.set(r,e)}}return n}function cleanUpHighlights(){const e=window._highlightCleanupFunctions||[];for(const t of e)"function"==typeof t&&t();window._highlightCleanupFunctions=[]}async function waitFor(e){await new Promise(t=>setTimeout(t,1e3*e))}function getElementByIndex(e,t){const n=e.get(t);if(!n)throw new Error(`No interactive element found at index ${t}`);const r=n.ref;if(!r)throw new Error(`Element at index ${t} does not have a reference`);if(!(r instanceof HTMLElement))throw new Error(`Element at index ${t} is not an HTMLElement`);return r}let lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&(lastClickedElement.blur(),lastClickedElement.dispatchEvent(new MouseEvent("mouseout",{bubbles:!0,cancelable:!0})),lastClickedElement=null)}async function scrollIntoViewIfNeeded(e){const t=e.getBoundingClientRect();t.top>=0&&t.bottom<=window.innerHeight&&t.left>=0&&t.right<=window.innerWidth||(e.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"}),await waitFor(.4))}async function movePointerToElement(e){const t=e.getBoundingClientRect(),n=t.left+t.width/2,r=t.top+t.height/2;window.dispatchEvent(new CustomEvent("HyphaDebugger::MovePointerTo",{detail:{x:n,y:r}})),await waitFor(.3)}async function clickElement(e){blurLastClickedElement(),lastClickedElement=e,await scrollIntoViewIfNeeded(e),await movePointerToElement(e),window.dispatchEvent(new CustomEvent("HyphaDebugger::ClickPointer")),await waitFor(.05),e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("mouseover",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("mousedown",{bubbles:!0,cancelable:!0})),e.focus(),e.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),await waitFor(.2)}let _nativeInputValueSetter=null,_nativeTextAreaValueSetter=null;function getNativeInputValueSetter(){return _nativeInputValueSetter||(_nativeInputValueSetter=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value").set),_nativeInputValueSetter}function getNativeTextAreaValueSetter(){return _nativeTextAreaValueSetter||(_nativeTextAreaValueSetter=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value").set),_nativeTextAreaValueSetter}async function inputTextElement(e,t){const n=e.isContentEditable;if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||n))throw new Error("Element is not an input, textarea, or contenteditable");await clickElement(e),n?(e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"deleteContent"}))&&(e.innerText="",e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"deleteContent"}))),e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t}))&&(e.innerText=t,e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"insertText",data:t}))),e.dispatchEvent(new Event("change",{bubbles:!0})),e.blur()):e instanceof HTMLTextAreaElement?getNativeTextAreaValueSetter().call(e,t):getNativeInputValueSetter().call(e,t),n||e.dispatchEvent(new Event("input",{bubbles:!0})),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(e,t){if(!(e instanceof HTMLSelectElement))throw new Error("Element is not a select element");await scrollIntoViewIfNeeded(e);const n=e.getBoundingClientRect();window.dispatchEvent(new CustomEvent("HyphaDebugger::MovePointerTo",{detail:{x:n.left+n.width/2,y:n.top+n.height/2}})),await waitFor(.3),window.dispatchEvent(new CustomEvent("HyphaDebugger::ClickPointer"));const r=Array.from(e.options).find(e=>e.textContent?.trim()===t.trim());if(!r)throw new Error(`Option with text "${t}" not found in select element`);e.value=r.value,e.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}async function scrollVertically(e,t,n){if(n){let e=n,r=!1,o=null,i=0,s=0;const c=t;for(;e&&s<10;){const t=window.getComputedStyle(e),n=/(auto|scroll|overlay)/.test(t.overflowY),a=e.scrollHeight>e.clientHeight;if(n&&a){const t=e.scrollTop,n=e.scrollHeight-e.clientHeight;let s=c/3;s=s>0?Math.min(s,n-t):Math.max(s,-t),e.scrollTop=t+s;const a=e.scrollTop-t;if(Math.abs(a)>.5){r=!0,o=e,i=a;break}}if(e===document.body||e===document.documentElement)break;e=e.parentElement,s++}return r?`Scrolled container (${o?.tagName}) by ${i}px`:`No scrollable container found for element (${n.tagName})`}const r=t,o=e=>e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowY)&&e.scrollHeight>e.clientHeight&&(e=>e.clientHeight>=.5*window.innerHeight)(e);let i=document.activeElement;for(;i&&!o(i)&&i!==document.body;)i=i.parentElement;if(i=o(i)?i:Array.from(document.querySelectorAll("*")).find(o)||document.scrollingElement||document.documentElement,i===document.scrollingElement||i===document.documentElement||i===document.body){const e=window.scrollY;window.scrollBy(0,r);const t=window.scrollY,n=t-e;if(Math.abs(n)<1)return r>0?"Already at the bottom of the page.":"Already at the top of the page.";const o=document.documentElement.scrollHeight-window.innerHeight;return r>0&&t>=o-1?`Scrolled page by ${n}px. Reached the bottom.`:r<0&&t<=1?`Scrolled page by ${n}px. Reached the top.`:`Scrolled page by ${n}px.`}{const e=i.scrollTop,t=i.scrollHeight-i.clientHeight;i.scrollBy({top:r,behavior:"smooth"}),await waitFor(.1);const n=i.scrollTop,o=n-e;if(Math.abs(o)<1)return r>0?`Already at the bottom of container (${i.tagName}).`:`Already at the top of container (${i.tagName}).`;const s=r<0&&n<=1;return r>0&&n>=t-1?`Scrolled container (${i.tagName}) by ${o}px. Reached the bottom.`:s?`Scrolled container (${i.tagName}) by ${o}px. Reached the top.`:`Scrolled container (${i.tagName}) by ${o}px.`}}async function scrollHorizontally(e,t,n){if(n){let r=n,o=!1,i=null,s=0,c=0;const a=e?t:-t;for(;r&&c<10;){const e=window.getComputedStyle(r),t=/(auto|scroll|overlay)/.test(e.overflowX),n=r.scrollWidth>r.clientWidth;if(t&&n){const e=r.scrollLeft,t=r.scrollWidth-r.clientWidth;let n=a/3;n=n>0?Math.min(n,t-e):Math.max(n,-e),r.scrollLeft=e+n;const c=r.scrollLeft-e;if(Math.abs(c)>.5){o=!0,i=r,s=c;break}}if(r===document.body||r===document.documentElement)break;r=r.parentElement,c++}return o?`Scrolled container (${i?.tagName}) horizontally by ${s}px`:`No horizontally scrollable container found for element (${n.tagName})`}const r=e?t:-t,o=e=>e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowX)&&e.scrollWidth>e.clientWidth&&(e=>e.clientWidth>=.5*window.innerWidth)(e);let i=document.activeElement;for(;i&&!o(i)&&i!==document.body;)i=i.parentElement;if(i=o(i)?i:Array.from(document.querySelectorAll("*")).find(o)||document.scrollingElement||document.documentElement,i===document.scrollingElement||i===document.documentElement||i===document.body){const e=window.scrollX,t=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(r,0);const n=window.scrollX,o=n-e;if(Math.abs(o)<1)return r>0?"Already at the right edge of the page.":"Already at the left edge of the page.";return r>0&&n>=t-1?`Scrolled page by ${o}px. Reached the right edge.`:r<0&&n<=1?`Scrolled page by ${o}px. Reached the left edge.`:`Scrolled page horizontally by ${o}px.`}{const e=i.scrollLeft,t=i.scrollWidth-i.clientWidth;i.scrollBy({left:r,behavior:"smooth"}),await waitFor(.1);const n=i.scrollLeft,o=n-e;if(Math.abs(o)<1)return r>0?`Already at the right edge of container (${i.tagName}).`:`Already at the left edge of container (${i.tagName}).`;const s=r<0&&n<=1;return r>0&&n>=t-1?`Scrolled container (${i.tagName}) by ${o}px. Reached the right edge.`:s?`Scrolled container (${i.tagName}) by ${o}px. Reached the left edge.`:`Scrolled container (${i.tagName}) horizontally by ${o}px.`}}function getPageScrollInfo(){const e=window.innerWidth,t=window.innerHeight,n=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),r=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),o=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,i=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,s=Math.max(0,r-(window.innerHeight+i)),c=Math.max(0,n-(window.innerWidth+o));return{viewport_width:e,viewport_height:t,page_width:n,page_height:r,scroll_x:o,scroll_y:i,pixels_above:i,pixels_below:s,pages_above:t>0?i/t:0,pages_below:t>0?s/t:0,total_pages:t>0?r/t:0,current_page_position:i/Math.max(1,r-t),pixels_left:o,pixels_right:c}}class PageController{constructor(e={}){this.flatTree=null,this.selectorMap=new Map,this.elementTextMap=new Map,this.simplifiedHTML="",this.isIndexed=!1,this.config=e}async getBrowserState(){const e=window.location.href,t=document.title,n=getPageScrollInfo(),r=resolveViewportExpansion(this.config.viewportExpansion);await this.updateTree();const o=this.simplifiedHTML;return{url:e,title:t,header:`${`Current Page: [${t}](${e})`}\n${`Page info: ${n.viewport_width}x${n.viewport_height}px viewport, ${n.page_width}x${n.page_height}px total, ${n.pages_above.toFixed(1)} pages above, ${n.pages_below.toFixed(1)} pages below, at ${(100*n.current_page_position).toFixed(0)}%`}\n\n${-1===r?"Interactive elements (full page):":"Interactive elements (viewport):"}\n\n${n.pixels_above>4&&-1!==r?`... ${n.pixels_above} pixels above - scroll to see more ...`:"[Start of page]"}`,content:o,footer:n.pixels_below>4&&-1!==r?`... ${n.pixels_below} pixels below - scroll to see more ...`:"[End of page]",element_count:this.selectorMap.size}}async updateTree(){return cleanUpHighlights(),this.flatTree=getFlatTree(this.config),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.includeAttributes),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.simplifiedHTML}async cleanUpHighlights(){cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw new Error("DOM tree not indexed yet. Call get_browser_state first.")}cleanUpAfterAction(){cleanUpHighlights()}async clickElement(e){try{this.assertIndexed();const t=getElementByIndex(this.selectorMap,e),n=this.elementTextMap.get(e);return this.cleanUpAfterAction(),await clickElement(t),t instanceof HTMLAnchorElement&&"_blank"===t.target?{success:!0,message:`Clicked element (${n??e}). Link opened in a new tab.`}:{success:!0,message:`Clicked element (${n??e}).`}}catch(e){return{success:!1,message:`Failed to click element: ${e}`}}}async inputText(e,t){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return this.cleanUpAfterAction(),await inputTextElement(n,t),{success:!0,message:`Input text "${t}" into element (${r??e}).`}}catch(e){return{success:!1,message:`Failed to input text: ${e}`}}}async selectOption(e,t){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return this.cleanUpAfterAction(),await selectOptionElement(n,t),{success:!0,message:`Selected option "${t}" in element (${r??e}).`}}catch(e){return{success:!1,message:`Failed to select option: ${e}`}}}async scroll(e){try{this.assertIndexed(),this.cleanUpAfterAction();const{direction:t,amount:n,index:r}=e,o=void 0!==r?getElementByIndex(this.selectorMap,r):null;let i;if("left"===t||"right"===t){const e=n??.8*window.innerWidth;i=await scrollHorizontally("right"===t,e,o)}else{const e=n??.8*window.innerHeight,r="down"===t?e:-e;i=await scrollVertically("down"===t,r,o)}return{success:!0,message:i}}catch(e){return{success:!1,message:`Failed to scroll: ${e}`}}}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="",this.isIndexed=!1}}let controller=null;function getController(){return controller||(controller=new PageController({viewportExpansion:-1,highlightOpacity:.1,highlightLabelOpacity:.5})),controller}async function getBrowserState(e){const t=getController();return void 0!==e&&(t.config.viewportExpansion=e?0:-1),t.getBrowserState()}async function clickElementByIndex(e){return getController().clickElement(e)}async function inputText(e,t){return getController().inputText(e,t)}async function selectOption(e,t){return getController().selectOption(e,t)}async function scroll(e,t,n){return getController().scroll({direction:e,amount:t,index:n})}async function removeHighlights(){return getController().cleanUpHighlights(),{success:!0,message:"Highlights removed."}}function disposeController(){controller&&(controller.dispose(),controller=null)}function randomHex(e=8){const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}getBrowserState.__schema__={name:"getBrowserState",description:"Get the current page state with all interactive elements indexed as [0], [1], [2], etc. Returns a simplified HTML representation optimized for LLM consumption. Interactive elements (buttons, links, inputs, scrollable areas) are detected via smart heuristics (CSS cursor, ARIA roles, event listeners, tag names). Use the returned indices with click_element_by_index, input_text, select_option, or scroll. Call this first to understand the page before performing any actions.",parameters:{type:"object",properties:{viewport_only:{type:"boolean",description:"If true, only return elements visible in the current viewport. Default: false (full page)."}}}},clickElementByIndex.__schema__={name:"clickElementByIndex",description:"Click an interactive element by its numeric index from get_browser_state output. Simulates a full mouse event sequence (hover, mousedown, focus, mouseup, click) to trigger all event listeners including React/Vue handlers.",parameters:{type:"object",properties:{index:{type:"number",description:"The element index from get_browser_state (e.g. 0 for [0], 5 for [5])."}},required:["index"]}},inputText.__schema__={name:"inputText",description:"Type text into an input, textarea, or contenteditable element by its index. Replaces existing content. Works with React controlled components, contenteditable editors (LinkedIn, Quill), and native inputs.",parameters:{type:"object",properties:{index:{type:"number",description:"The element index from get_browser_state."},text:{type:"string",description:"The text to type into the element."}},required:["index","text"]}},selectOption.__schema__={name:"selectOption",description:"Select a dropdown option in a <select> element by its index and the visible option text.",parameters:{type:"object",properties:{index:{type:"number",description:"The <select> element index from get_browser_state."},option_text:{type:"string",description:"The visible text of the option to select (case-sensitive, trimmed)."}},required:["index","option_text"]}},scroll.__schema__={name:"scroll",description:"Scroll the page or a specific scrollable container. If index is provided, scrolls the nearest scrollable ancestor of that element. Otherwise scrolls the page or the largest scrollable container.",parameters:{type:"object",properties:{direction:{type:"string",enum:["up","down","left","right"],description:"Scroll direction."},amount:{type:"number",description:"Scroll amount in pixels. Default: ~80% of viewport height (vertical) or width (horizontal)."},index:{type:"number",description:"Optional element index. If provided, scrolls the nearest scrollable ancestor of this element."}},required:["direction"]}},removeHighlights.__schema__={name:"removeHighlights",description:"Remove all visual element index labels/highlights from the page. Useful after taking a screenshot if you want a clean view.",parameters:{type:"object",properties:{}}};const STORAGE_KEY="__hypha_debugger_config__";class HyphaDebugger{constructor(e){this.overlay=null,this.cursor=null,this.server=null,this.serviceInfo=null,this.boundBeforeUnload=null,this.cleanupInterceptor=null;const t=e.require_token??!1;let n=e.service_id??"web-debugger";e.service_id||(n=`web-debugger-${randomHex(16)}`);const r=e.visibility??(t?"protected":"unlisted");this.config={server_url:e.server_url,workspace:e.workspace??"",token:e.token??"",service_id:n,service_name:e.service_name??"Web Debugger",show_ui:e.show_ui??!0,visibility:r,require_token:t}}async start(){installConsoleCapture();const e=window;if(e.__HYPHA_DEBUGGER__?.instance)return console.warn("[hypha-debugger] Already running, returning existing session."),e.__HYPHA_DEBUGGER__.session;this.config.show_ui&&(this.overlay=new DebugOverlay,this.overlay.setStatus("disconnected"),this.overlay.setInfo({Status:"Connecting..."}),this.cursor=new AICursor);try{"function"!=typeof Promise.prototype.finally&&(Promise.prototype.finally=function(e){return this.then(t=>Promise.resolve(e()).then(()=>t),t=>Promise.resolve(e()).then(()=>{throw t}))});const t=this.getConnectToServer(),n={server_url:this.config.server_url};this.config.workspace&&(n.workspace=this.config.workspace),this.config.token&&(n.token=this.config.token);try{this.server=await t(n)}catch(e){if(!this.config.workspace)throw e;console.warn(`[hypha-debugger] Failed to rejoin workspace "${this.config.workspace}", getting a fresh one:`,e.message??e),this.server=await t({server_url:this.config.server_url})}this.serviceInfo=await this.server.registerService(this.buildServiceDefinition());const r=await this.updateSession();return this.overlay&&this.overlay.addLog("Service registered","result"),e.__HYPHA_DEBUGGER__=e.__HYPHA_DEBUGGER__??{},e.__HYPHA_DEBUGGER__.instance=this,this.saveConfigToStorage(),this.boundBeforeUnload=()=>this.saveConfigToStorage(),window.addEventListener("beforeunload",this.boundBeforeUnload),this.cleanupInterceptor=installNavigationInterceptor(),r}catch(e){throw console.error("[hypha-debugger] Failed to start:",e),this.overlay&&(this.overlay.setStatus("error"),this.overlay.setInfo({Status:"Error",Error:e.message??String(e)})),e}}async destroy(){this.boundBeforeUnload&&(window.removeEventListener("beforeunload",this.boundBeforeUnload),this.boundBeforeUnload=null),this.cleanupInterceptor&&(this.cleanupInterceptor(),this.cleanupInterceptor=null);try{this.serviceInfo&&this.server&&await this.server.unregisterService(this.serviceInfo.id)}catch{}try{sessionStorage.removeItem(STORAGE_KEY)}catch{}disposeController(),this.cursor?.destroy(),this.cursor=null,this.overlay?.destroy(),this.overlay=null;const e=window;e.__HYPHA_DEBUGGER__&&(delete e.__HYPHA_DEBUGGER__.instance,delete e.__HYPHA_DEBUGGER__.session)}saveConfigToStorage(){try{const e={server_url:this.config.server_url,workspace:this.server?.config?.workspace??this.config.workspace,service_id:this.config.service_id,service_name:this.config.service_name,show_ui:this.config.show_ui,visibility:this.config.visibility,require_token:this.config.require_token,script_url:this.detectScriptUrl()};sessionStorage.setItem(STORAGE_KEY,JSON.stringify(e))}catch{}}detectScriptUrl(){try{const e=document.querySelectorAll("script[src]");for(const t of Array.from(e))if(t.src&&t.src.includes("hypha-debugger"))return t.src}catch{}return"https://cdn.jsdelivr.net/npm/hypha-debugger/dist/hypha-debugger.min.js"}async updateSession(e){const t=this.serviceInfo?.id??this.config.service_id,n=this.buildServiceUrl(t),r=this.server.config?.workspace??"",o=this.config.require_token?await this.server.generateToken({expires_in:86400}):"";this.overlay&&(this.overlay.setStatus("connected"),this.overlay.setInfo({Status:"Connected",Server:this.config.server_url,...e}),this.overlay.setInstructions(this.buildInstructionBlock(n,o))),console.log(`[hypha-debugger] Service URL: ${n}`),o?(console.log(`[hypha-debugger] Token: ${o}`),console.log(`[hypha-debugger] Test:\n curl '${n}/get_page_info' -H 'Authorization: Bearer ${o}'`)):console.log(`[hypha-debugger] Test:\n curl '${n}/get_page_info'`);const i={service_id:t,workspace:r,server:this.server,service_url:n,token:o,destroy:()=>this.destroy()},s=window;return s.__HYPHA_DEBUGGER__=s.__HYPHA_DEBUGGER__??{},s.__HYPHA_DEBUGGER__.session=i,i}buildServiceUrl(e){const t=this.config.server_url.replace(/\/+$/,""),n=e.indexOf("/");if(-1!==n){const r=e.substring(0,n),o=e.substring(n+1),i=o.indexOf(":");return`${t}/${r}/services/${-1!==i?o.substring(i+1):o}`}return`${t}/services/${e}`}getHyphaModule(){if(__webpack_exports__connectToServer)return hyphaRpc;if(__webpack_exports__connectToServer)return hyphaRpcWebsocket;const e=window;if(e.hyphaWebsocketClient?.connectToServer)return e.hyphaWebsocketClient;throw new Error('hypha-rpc not found. Install it via npm or load it via: <script src="https://cdn.jsdelivr.net/npm/hypha-rpc@0.20.97/dist/hypha-rpc-websocket.min.js"><\/script>')}getConnectToServer(){return this.getHyphaModule().connectToServer}buildServiceDefinition(){return{id:this.config.service_id,name:this.config.service_name,type:"debugger",description:"Remote web page debugger. Allows inspecting DOM, taking screenshots, executing JavaScript, and interacting with the page.",config:{visibility:this.config.visibility},get_page_info:this.wrapFn(getPageInfo,"get_page_info"),get_html:this.wrapFn(getHtml,"get_html"),query_dom:this.wrapFn(queryDom,"query_dom"),click_element:this.wrapFn(clickElement$1,"click_element"),fill_input:this.wrapFn(fillInput,"fill_input"),scroll_to:this.wrapFn(scrollTo,"scroll_to"),take_screenshot:this.wrapFn(takeScreenshot,"take_screenshot"),execute_script:this.wrapFn(executeScript,"execute_script"),navigate:this.wrapFn(navigate,"navigate"),get_react_tree:this.wrapFn(getReactTree,"get_react_tree"),get_browser_state:this.wrapFn(getBrowserState,"get_browser_state"),click_element_by_index:this.wrapFn(clickElementByIndex,"click_element_by_index"),input_text:this.wrapFn(inputText,"input_text"),select_option:this.wrapFn(selectOption,"select_option"),scroll:this.wrapFn(scroll,"scroll"),remove_highlights:this.wrapFn(removeHighlights,"remove_highlights"),get_skill_md:this.wrapFn(this.createGetSkillMd(),"get_skill_md")}}createGetSkillMd(){const e=()=>{const e={},t={get_page_info:getPageInfo,get_html:getHtml,query_dom:queryDom,click_element:clickElement$1,fill_input:fillInput,scroll_to:scrollTo,take_screenshot:takeScreenshot,execute_script:executeScript,navigate:navigate,get_react_tree:getReactTree,get_browser_state:getBrowserState,click_element_by_index:clickElementByIndex,input_text:inputText,select_option:selectOption,scroll:scroll,remove_highlights:removeHighlights};for(const[n,r]of Object.entries(t))r.__schema__&&(e[n]=r);return!this.serviceInfo||this.buildServiceUrl(this.serviceInfo.id??this.config.service_id),generateSkillMd(e)};return e.__schema__={name:"getSkillMd",description:"Get the SKILL.md document describing all available debugger functions, their parameters, and usage examples. Follows the agentskills.io specification.",parameters:{type:"object",properties:{}}},e}buildInstructionBlock(e,t){const n=t?' -H "Authorization: Bearer $TOKEN"':"",r=["# Hypha Remote Debugger — Web Page","# A debugger is attached to a live web page.","# You can remotely inspect, interact with, and control this page via the HTTP API below.","#","# APPROACHES (pick what fits your task):","# - execute_script: Run arbitrary JS — fastest for reading/modifying page state, DOM queries, API calls","# - get_browser_state + click/input/select by index: Visual interaction with the page as a user would","# - get_html / query_dom: Read DOM structure with CSS selectors","# - get_react_tree: Inspect React component props, state, and hooks","# - take_screenshot: Visual verification of page state","#","# All POST endpoints accept JSON body with parameter names as keys.","",`SERVICE_URL="${e}"`];return t&&r.push(`TOKEN="${t}"`),r.push("","# Execute JavaScript (most versatile — read state, call APIs, modify DOM):",`curl -X POST "$SERVICE_URL/execute_script"${n} -H "Content-Type: application/json" -d '{"code": "document.title"}'`,"","# Smart DOM analysis (indexed interactive elements for click/type/select):",`curl "$SERVICE_URL/get_browser_state"${n}`,"","# Interact by element index:",`curl -X POST "$SERVICE_URL/click_element_by_index"${n} -H "Content-Type: application/json" -d '{"index": 3}'`,`curl -X POST "$SERVICE_URL/input_text"${n} -H "Content-Type: application/json" -d '{"index": 5, "text": "hello"}'`,"","# Screenshot + React inspection:",`curl "$SERVICE_URL/take_screenshot"${n}`,`curl "$SERVICE_URL/get_react_tree"${n}`,"","# Navigate (auto-reconnects for same-origin):",`curl -X POST "$SERVICE_URL/navigate"${n} -H "Content-Type: application/json" -d '{"url": "/other-page"}'`,"","# Full API docs:",`curl "$SERVICE_URL/get_skill_md"${n}`),r.join("\n")}wrapFn(e,t){const n=this,r=async(...r)=>{n.overlay?.addLog(`${t}(${n.summarizeArgs(r)})`,"call");try{const o=await e(...r);return o&&"object"==typeof o&&"error"in o?n.overlay?.addLog(`${t}: ${o.error}`,"error"):n.overlay?.addLog(`${t} -> OK`,"result"),o}catch(e){throw n.overlay?.addLog(`${t}: ${e.message}`,"error"),e}};return e.__schema__&&(r.__schema__=e.__schema__),wrapFn(r)}summarizeArgs(e){return 0===e.length?"":e.map(e=>"string"==typeof e?e.length>40?e.slice(0,40)+"...":e:"object"==typeof e&&null!==e?"{...}":String(e)).join(", ")}}async function startDebugger(e){return new HyphaDebugger(e).start()}function autoStart(){if("undefined"==typeof window||"undefined"==typeof document)return;if(window.__HYPHA_DEBUGGER__?.instance)return;try{const e=sessionStorage.getItem("__hypha_debugger_config__");if(e){const t=JSON.parse(e);if(t.server_url)return console.log("[hypha-debugger] Reconnecting from saved session..."),void startDebugger(t).catch(e=>{console.error("[hypha-debugger] Auto-reconnect failed:",e)})}}catch{}const e=document.querySelectorAll("script[src]");let t=null;for(const n of Array.from(e))if(n.src&&n.src.includes("hypha-debugger")){t=n;break}if(t?.hasAttribute("data-manual"))return;const n={server_url:t?.getAttribute("data-server-url")??"https://hypha.aicell.io"};t?.getAttribute("data-workspace")&&(n.workspace=t.getAttribute("data-workspace")),t?.getAttribute("data-token")&&(n.token=t.getAttribute("data-token")),t?.getAttribute("data-service-id")&&(n.service_id=t.getAttribute("data-service-id")),t?.hasAttribute("data-no-ui")&&(n.show_ui=!1),t?.hasAttribute("data-require-token")&&(n.require_token=!0),startDebugger(n).catch(e=>{console.error("[hypha-debugger] Auto-start failed:",e)})}"undefined"!=typeof window&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",autoStart):autoStart()),exports.AICursor=AICursor,exports.HyphaDebugger=HyphaDebugger,exports.PageController=PageController,exports.clickElement=clickElement$1,exports.clickElementByIndex=clickElementByIndex,exports.disposeController=disposeController,exports.executeScript=executeScript,exports.fillInput=fillInput,exports.generateSkillMd=generateSkillMd,exports.getBrowserState=getBrowserState,exports.getComputedStyles=getComputedStyles,exports.getConsoleLogs=getConsoleLogs,exports.getElementBounds=getElementBounds,exports.getHtml=getHtml,exports.getPageInfo=getPageInfo,exports.getReactTree=getReactTree,exports.goBack=goBack,exports.goForward=goForward,exports.inputText=inputText,exports.installConsoleCapture=installConsoleCapture,exports.installNavigationInterceptor=installNavigationInterceptor,exports.navigate=navigate,exports.queryDom=queryDom,exports.reload=reload,exports.removeHighlights=removeHighlights,exports.scroll=scroll,exports.scrollTo=scrollTo,exports.selectOption=selectOption,exports.softReplace=softReplace,exports.startDebugger=startDebugger,exports.takeScreenshot=takeScreenshot,exports.wrapFn=wrapFn});
67
+ \*********************************/__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{API_VERSION:()=>_rpc_js__WEBPACK_IMPORTED_MODULE_0__.API_VERSION,HTTPStreamingRPCConnection:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_5__.HTTPStreamingRPCConnection,LocalWebSocket:()=>LocalWebSocket,RPC:()=>_rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC,WebsocketRPCConnection:()=>WebsocketRPCConnection,connectToServer:()=>connectToServer,connectToServerHTTP:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_5__.connectToServerHTTP,decryptPayload:()=>_crypto_js__WEBPACK_IMPORTED_MODULE_1__.decryptPayload,encryptPayload:()=>_crypto_js__WEBPACK_IMPORTED_MODULE_1__.encryptPayload,generateEncryptionKeypair:()=>_crypto_js__WEBPACK_IMPORTED_MODULE_1__.generateEncryptionKeypair,getRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_4__.getRTCService,getRemoteService:()=>getRemoteService,getRemoteServiceHTTP:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_5__.getRemoteServiceHTTP,hyphaWebsocketClient:()=>hyphaWebsocketClient,loadRequirements:()=>_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.loadRequirements,login:()=>login,logout:()=>logout,normalizeServerUrlHTTP:()=>_http_client_js__WEBPACK_IMPORTED_MODULE_5__.normalizeServerUrl,publicKeyFromHex:()=>_crypto_js__WEBPACK_IMPORTED_MODULE_1__.publicKeyFromHex,publicKeyToHex:()=>_crypto_js__WEBPACK_IMPORTED_MODULE_1__.publicKeyToHex,registerRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_4__.registerRTCService,schemaFunction:()=>_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction,setupLocalClient:()=>setupLocalClient});var _rpc_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! ./rpc.js */"./src/rpc.js"),_crypto_js__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! ./crypto.js */"./src/crypto.js"),_utils_index_js__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! ./utils/index.js */"./src/utils/index.js"),_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! ./utils/schema.js */"./src/utils/schema.js"),_webrtc_client_js__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! ./webrtc-client.js */"./src/webrtc-client.js"),_http_client_js__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__(/*! ./http-client.js */"./src/http-client.js");const MAX_RETRY=1e6;class WebsocketRPCConnection{constructor(e,t,n,r,o=null,i=60,s=null,a=7200,c=null,l=30,h=void 0){if((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.assert)(e&&t,"server_url and client_id are required"),null===h){const e=()=>{};this._logger={debug:e,info:e,warn:e,error:e,log:e}}else this._logger=h||console;this._server_url=e,this._client_id=t,this._workspace=n,this._token=r,this._reconnection_token=o,this._websocket=null,this._handle_message=null,this._handle_connected=null,this._handle_disconnected=null,this._timeout=i,this._WebSocketClass=s||WebSocket,this._closed=!1,this._legacy_auth=null,this.connection_info=null,this._enable_reconnect=!1,this._token_refresh_interval=a,this.manager_id=null,this._refresh_token_task=null,this._ping_task=null,this._ping_interval=l,this._reconnect_timeouts=new Set,this._additional_headers=c,this._reconnecting=!1,this._closedDuringReconnect=!1,this._disconnectedNotified=!1}_cleanup(){this._refresh_token_delay&&(clearTimeout(this._refresh_token_delay),this._refresh_token_delay=null),this._refresh_token_task&&(clearInterval(this._refresh_token_task),this._refresh_token_task=null),this._ping_task&&(clearInterval(this._ping_task),this._ping_task=null);for(const e of this._reconnect_timeouts)clearTimeout(e);this._reconnect_timeouts.clear()}on_message(e){(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.assert)(e,"handler is required"),this._handle_message=e}on_connected(e){this._handle_connected=e}on_disconnected(e){this._handle_disconnected=e}async _attempt_connection(e,t=!0){return new Promise((n,r)=>{this._legacy_auth=!1;const o=new this._WebSocketClass(e);o.binaryType="arraybuffer",o.onopen=()=>{this._logger.info("WebSocket connection established"),n(o)},o.onerror=e=>{this._logger.error("WebSocket connection error:",e),r(new Error(`WebSocket connection error: ${e}`))},o.onclose=o=>{1003===o.code&&t?(this._logger.info("Received 1003 error, attempting connection with query parameters."),this._legacy_auth=!0,this._attempt_connection_with_query_params(e).then(n).catch(r)):this._notifyDisconnected(o.reason)}})}async _attempt_connection_with_query_params(e){const t=[];this._client_id&&t.push(`client_id=${encodeURIComponent(this._client_id)}`),this._workspace&&t.push(`workspace=${encodeURIComponent(this._workspace)}`),this._token&&t.push(`token=${encodeURIComponent(this._token)}`),this._reconnection_token&&t.push(`reconnection_token=${encodeURIComponent(this._reconnection_token)}`);const n=e+(t.length>0?`?${t.join("&")}`:"");return await this._attempt_connection(n,!1)}_establish_connection(){return new Promise((e,t)=>{let n=!1;const r=this._websocket.onclose;this._websocket.onclose=e=>{n||(n=!0,t(new Error(`ConnectionAbortedError: WebSocket closed during handshake (code=${e.code}, reason=${e.reason||"unknown"})`))),r&&r.call(this._websocket,e)};const o=this._websocket.onerror;this._websocket.onerror=e=>{n||(n=!0,t(new Error("ConnectionAbortedError: WebSocket error during handshake"))),o&&o.call(this._websocket,e)},this._websocket.onmessage=r=>{const o=r.data;if("string"!=typeof o)return;const i=JSON.parse(o);if("connection_info"!=i.type){if("error"==i.type){n=!0;const e="ConnectionAbortedError: "+i.message;return this._logger.error("Failed to connect, "+e),void t(new Error(e))}return n=!0,this._logger.error("ConnectionAbortedError: Unexpected message received from the server:",o),void t(new Error("ConnectionAbortedError: Unexpected message received from the server"))}n=!0,this.connection_info=i,this._workspace&&(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.assert)(this.connection_info.workspace===this._workspace,`Connected to the wrong workspace: ${this.connection_info.workspace}, expected: ${this._workspace}`),this.connection_info.reconnection_token&&(this._reconnection_token=this.connection_info.reconnection_token),this.connection_info.reconnection_token_life_time&&this._token_refresh_interval>this.connection_info.reconnection_token_life_time/1.5&&(this._logger.warn(`Token refresh interval is too long (${this._token_refresh_interval}), setting it to 1.5 times of the token life time(${this.connection_info.reconnection_token_life_time}).`),this._token_refresh_interval=this.connection_info.reconnection_token_life_time/1.5),this.manager_id=this.connection_info.manager_id||null,this._logger.log(`Successfully connected to the server, workspace: ${this.connection_info.workspace}, manager_id: ${this.manager_id}`),this.connection_info.announcement&&this._logger.log(`${this.connection_info.announcement}`),e(this.connection_info)}})}async open(){this._logger.log("Creating a new websocket connection to",this._server_url.split("?")[0]);try{if(this._websocket=await this._attempt_connection(this._server_url),this._legacy_auth)throw new Error("NotImplementedError: Legacy authentication is not supported");const e=JSON.stringify({client_id:this._client_id,workspace:this._workspace,token:this._token,reconnection_token:this._reconnection_token});return this._websocket.send(e),await(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.waitFor)(this._establish_connection(),this._timeout,"Failed to receive the first message from the server"),this._token_refresh_interval>0&&(this._refresh_token_delay=setTimeout(()=>{this._refresh_token_delay=null,this._closed||(this._send_refresh_token(),this._refresh_token_task=setInterval(()=>{this._send_refresh_token()},1e3*this._token_refresh_interval))},2e3)),this._ping_interval>0&&(this._ping_task=setInterval(()=>{this._closed||this._send_ping()},1e3*this._ping_interval)),this._enable_reconnect=!0,this._closed=!1,this._disconnectedNotified=!1,this._websocket.onmessage=e=>{if("string"==typeof e.data){const t=JSON.parse(e.data);"reconnection_token"===t.type?this._reconnection_token=t.reconnection_token:"pong"===t.type||this._logger.log("Received message from the server:",t)}else this._handle_message(e.data)},this._websocket.onerror=e=>{this._logger.error("WebSocket connection error:",e),this._cleanup()},this._websocket.onclose=this._handle_close.bind(this),this._handle_connected&&await this._handle_connected(this.connection_info),this.connection_info}catch(e){throw this._cleanup(),this._logger.error("Failed to connect to",this._server_url.split("?")[0],e),e}}_send_ping(){this._websocket&&this._websocket.readyState===WebSocket.OPEN&&this._websocket.send(JSON.stringify({type:"ping"}))}_send_refresh_token(){if(this._websocket&&this._websocket.readyState===WebSocket.OPEN){const e=JSON.stringify({type:"refresh_token"});this._websocket.send(e)}}_notifyDisconnected(e){this._disconnectedNotified||(this._disconnectedNotified=!0,this._handle_disconnected&&this._handle_disconnected(e))}_handle_close(e){if(!this._closed&&this._websocket&&this._websocket.readyState===WebSocket.CLOSED){if(this._cleanup(),this._disconnectedNotified=!1,this._enable_reconnect){if([1e3,1001].includes(e.code)?this._logger.warn(`Websocket connection closed gracefully by server (code: ${e.code}): ${e.reason} - attempting reconnect`):this._logger.warn("Websocket connection closed unexpectedly (code: %s): %s",e.code,e.reason),this._notifyDisconnected(e.reason),this._reconnecting)return void(this._closedDuringReconnect=!0);this._reconnecting=!0;let t=0;const n=1e3,r=6e4,o=.1,i=async()=>{if(this._closed)return this._logger.info("Connection was closed, stopping reconnection"),void(this._reconnecting=!1);try{if(this._logger.warn(`Reconnecting to ${this._server_url.split("?")[0]} (attempt #${t})`),this._closedDuringReconnect=!1,await this.open(),await new Promise(e=>setTimeout(e,500)),this._closedDuringReconnect||!this._websocket||this._websocket.readyState!==WebSocket.OPEN)throw this._logger.warn("WebSocket closed during reconnection settle period, retrying..."),this._closedDuringReconnect=!1,new Error("Connection lost during reconnection settle");if(!1===this._services_registered_ok)throw this._logger.warn("Service re-registration failed, retrying..."),new Error("Service re-registration failed after reconnection");this._logger.warn(`Successfully reconnected to server ${this._server_url} (services re-registered)`),this._reconnecting=!1}catch(e){if(`${e}`.includes("ConnectionAbortedError:"))return this._logger.warn("Server refused to reconnect:",e),this._closed=!0,this._reconnecting=!1,void this._notifyDisconnected(`Server refused reconnection: ${e}`);if(`${e}`.includes("NotImplementedError:"))return this._logger.error(`${e}\nIt appears that you are trying to connect to a hypha server that is older than 0.20.0, please upgrade the hypha server or use the websocket client in imjoy-rpc(https://www.npmjs.com/package/imjoy-rpc) instead`),this._closed=!0,this._reconnecting=!1,void this._notifyDisconnected(`Server too old: ${e}`);const s=`${e}`;s.includes("NetworkError")||s.includes("network")?this._logger.error(`Network error during reconnection: ${s}`):s.includes("TimeoutError")||s.includes("timeout")?this._logger.error(`Connection timeout during reconnection: ${s}`):this._logger.error(`Unexpected error during reconnection: ${s}`);const a=Math.min(n*Math.pow(2,t),r),c=(2*Math.random()-1)*o*a,l=Math.max(100,a+c),h=setTimeout(async()=>(this._reconnect_timeouts.delete(h),this._websocket&&this._websocket.readyState===WebSocket.OPEN?(this._logger.info("Connection restored externally"),void(this._reconnecting=!1)):this._closed?(this._logger.info("Connection was closed, stopping reconnection"),void(this._reconnecting=!1)):(t+=1,void(t<MAX_RETRY?await i():(this._logger.error(`Failed to reconnect after ${MAX_RETRY} attempts, giving up.`),this._closed=!0,this._reconnecting=!1,this._notifyDisconnected("Max reconnection attempts exceeded"))))),l);this._reconnect_timeouts.add(h)}};i()}}else this._cleanup(),this._notifyDisconnected(e.reason)}async emit_message(e){if(this._closed)throw new Error("Connection is closed");this._websocket&&this._websocket.readyState===WebSocket.OPEN||await this.open();try{this._websocket.send(e)}catch(e){throw this._logger.error(`Failed to send data, error: ${e}`),e}}disconnect(e){this._closed=!0,this._reconnecting=!1,this._closedDuringReconnect=!1,this._websocket&&this._websocket.readyState!==WebSocket.CLOSED&&this._websocket.readyState!==WebSocket.CLOSING&&this._websocket.close(1e3,e),this._cleanup(),this._logger.info(`WebSocket connection disconnected (${e})`)}}function normalizeServerUrl(e){if(!e)throw new Error("server_url is required");return e.startsWith("http://")?e=e.replace("http://","ws://").replace(/\/$/,"")+"/ws":e.startsWith("https://")&&(e=e.replace("https://","wss://").replace(/\/$/,"")+"/ws"),e}async function login(e){const t=null===e.logger?{log(){},warn(){},error(){},info(){}}:e.logger||console,n=e.login_service_id||"public/hypha-login",r=e.workspace,o=e.expires_in,i=e.login_timeout||60,s=e.login_callback,a=e.profile,c=e.additional_headers,l=e.transport||"websocket",h=await connectToServer({name:"initial login client",server_url:e.server_url,additional_headers:c,transport:l});try{const e=await h.getService(n);let c;return(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.assert)(e,`Failed to get the login service: ${n}`),c=r?await e.start({workspace:r,expires_in:o,_rkwargs:!0}):await e.start(),s?await s(c):t.log(`Please open your browser and login at ${c.login_url}`),await e.check(c.key,{timeout:i,profile:a,_rkwargs:!0})}catch(e){throw e}finally{await h.disconnect()}}async function logout(e){const t=null===e.logger?{log(){},warn(){},error(){},info(){}}:e.logger||console,n=e.login_service_id||"public/hypha-login",r=e.logout_callback,o=e.additional_headers,i=e.transport||"websocket",s=await connectToServer({name:"initial logout client",server_url:e.server_url,additional_headers:o,transport:i});try{const e=await s.getService(n);if((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.assert)(e,`Failed to get the login service: ${n}`),!e.logout)throw new Error("Logout is not supported by this server. Please upgrade the Hypha server to a version that supports logout.");const o=await e.logout({});return r?await r(o):t.log(`Please open your browser to logout at ${o.logout_url}`),o}catch(e){throw e}finally{await s.disconnect()}}async function webrtcGetService(e,t,n,r){n=n||{};const o=null===r?{log(){},warn(){},error(){},info(){},debug(){}}:r||console,i=void 0!==n.webrtc?n.webrtc:"auto",s=n.webrtc_config,a=n.encryption_public_key;void 0!==n.webrtc&&delete n.webrtc,void 0!==n.webrtc_config&&delete n.webrtc_config,void 0!==n.encryption_public_key&&delete n.encryption_public_key,(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.assert)([void 0,!0,!1,"auto"].includes(i),"webrtc must be true, false or 'auto'");const c=await e.getService(t,n);if(a&&(0,_rpc_js__WEBPACK_IMPORTED_MODULE_0__._applyEncryptionKeyToService)(c,(0,_crypto_js__WEBPACK_IMPORTED_MODULE_1__.publicKeyFromHex)(a)),!0===i||"auto"===i){if(c.id.includes(":")&&c.id.includes("/"))try{const t=c.id.split(":")[0].split("/"),r=t[t.length-1],o=`${t.slice(0,-1).join("/")}/${r}-rtc`,i=await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_4__.getRTCService)(e,o,s),a=await i.getService(c.id.split(":")[1],n);return a._webrtc=!0,a._peer=i,a._service=c,a}catch(e){o.warn("Failed to get webrtc service, using websocket connection",e)}if(!0===i)throw new Error("Failed to get the service via webrtc")}return c}async function connectToServer(e){const t=null===e.logger?{log(){},warn(){},error(){},info(){},debug(){}}:e.logger||console;if("http"===(e.transport||"websocket"))return await(0,_http_client_js__WEBPACK_IMPORTED_MODULE_5__.connectToServerHTTP)(e);e.server&&(e.server_url=e.server_url||e.server.url,e.WebSocketClass=e.WebSocketClass||e.server.WebSocketClass);let n=e.client_id;n||(n=(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.randId)(),e.client_id=n),0===Object.keys(e).length&&("undefined"!=typeof process&&process.env?(e.server_url=process.env.HYPHA_SERVER_URL,e.token=process.env.HYPHA_TOKEN,e.client_id=process.env.HYPHA_CLIENT_ID,e.workspace=process.env.HYPHA_WORKSPACE):"undefined"!=typeof self&&self.env?(e.server_url=self.env.HYPHA_SERVER_URL,e.token=self.env.HYPHA_TOKEN,e.client_id=self.env.HYPHA_CLIENT_ID,e.workspace=self.env.HYPHA_WORKSPACE):"undefined"!=typeof globalThis&&globalThis.env&&(e.server_url=globalThis.env.HYPHA_SERVER_URL,e.token=globalThis.env.HYPHA_TOKEN,e.client_id=globalThis.env.HYPHA_CLIENT_ID,e.workspace=globalThis.env.HYPHA_WORKSPACE));let r=normalizeServerUrl(e.server_url),o=new WebsocketRPCConnection(r,n,e.workspace,e.token,e.reconnection_token,e.method_timeout||60,e.WebSocketClass,e.token_refresh_interval,e.additional_headers,e.ping_interval,e.logger);const i=await o.open();if((0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.assert)(i,"Failed to connect to the server, no connection info obtained. This issue is most likely due to an outdated Hypha server version. Please use `imjoy-rpc` for compatibility, or upgrade the Hypha server to the latest version."),await new Promise(e=>setTimeout(e,100)),!o.manager_id){t.warn("Manager ID not set immediately, waiting...");const e=5e3,n=100,r=Date.now();for(;!o.manager_id&&Date.now()-r<e;)await new Promise(e=>setTimeout(e,n));if(!o.manager_id)throw t.error("Manager ID still not set after waiting"),new Error("Failed to get manager ID from server");t.info(`Manager ID set after waiting: ${o.manager_id}`)}if(e.workspace&&i.workspace!==e.workspace)throw new Error(`Connected to the wrong workspace: ${i.workspace}, expected: ${e.workspace}`);const s=i.workspace,a=new _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC(o,{client_id:n,workspace:s,default_context:{connection_type:"websocket"},silent:e.silent||!1,logger:e.logger,name:e.name,method_timeout:e.method_timeout,rintf_timeout:e.rintf_timeout,app_id:e.app_id,server_base_url:i.public_base_url,long_message_chunk_size:e.long_message_chunk_size,encryption:e.encryption||!1,encryption_private_key:e.encryption_private_key||null,encryption_public_key:e.encryption_public_key||null});await a.waitFor("services_registered",e.method_timeout||120);const c=await a.get_manager_service({timeout:e.method_timeout,case_conversion:"camel",kwargs_expansion:e.kwargs_expansion||!1});c.rpc=a;let l=!0;if(a.on("manager_refreshed",async()=>{if(l)l=!1;else try{const e=`*/${a._connection.manager_id}`;for(const t of Object.keys(c))"function"==typeof c[t]&&c[t].__rpc_object__&&(c[t].__rpc_object__._rtarget=e);t.info("Workspace manager proxy retargeted after reconnection (new manager_id:",a._connection?.manager_id+")")}catch(e){t.warn("Failed to retarget workspace manager after reconnection:",e)}}),i&&(c.config=Object.assign(c.config,i)),c.export=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(async function(t){t.id="default",t.name=t.name||e.name||t.id,t.description=t.description||e.description,await a.register_service(t,{overwrite:!0})},{name:"export",description:"Export the api.",parameters:{properties:{api:{description:"The api to export",type:"object"}},required:["api"],type:"object"}}),c.getApp=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(async function(e){return e=e||"*",(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.assert)(!e.includes(":"),"clientId should not contain ':'"),e.includes("/")||(e=i.workspace+"/"+e),(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.assert)(2===e.split("/").length,"clientId should match pattern workspace/clientId"),await c.getService(`${e}:default`)},{name:"getApp",description:"Get the app.",parameters:{properties:{clientId:{default:"*",description:"The clientId",type:"string"}},type:"object"}}),c.listApps=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(async function(e){e=e||s,(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.assert)(!e.includes(":"),"workspace should not contain ':'"),(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.assert)(!e.includes("/"),"workspace should not contain '/'");const t={workspace:e,service_id:"default"};return await c.listServices(t)},{name:"listApps",description:"List the apps.",parameters:{properties:{workspace:{default:s,description:"The workspace",type:"string"}},type:"object"}}),c.disconnect=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(a.disconnect.bind(a),{name:"disconnect",description:"Disconnect from the server.",parameters:{type:"object",properties:{},required:[]}}),c.registerCodec=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(a.register_codec.bind(a),{name:"registerCodec",description:"Register a codec for the webrtc connection",parameters:{type:"object",properties:{codec:{type:"object",description:"Codec to register",properties:{name:{type:"string"},type:{},encoder:{type:"function"},decoder:{type:"function"}}}}}}),c.emit=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(a.emit.bind(a),{name:"emit",description:"Emit a message.",parameters:{properties:{data:{description:"The data to emit",type:"object"}},required:["data"],type:"object"}}),c.on=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(a.on.bind(a),{name:"on",description:"Register a message handler.",parameters:{properties:{event:{description:"The event to listen to",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.off=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(a.off.bind(a),{name:"off",description:"Remove a message handler.",parameters:{properties:{event:{description:"The event to remove",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.once=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(a.once.bind(a),{name:"once",description:"Register a one-time message handler.",parameters:{properties:{event:{description:"The event to listen to",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.getServiceSchema=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(a.get_service_schema,{name:"getServiceSchema",description:"Get the service schema.",parameters:{properties:{service:{description:"The service to extract schema",type:"object"}},required:["service"],type:"object"}}),c.registerService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(a.register_service.bind(a),{name:"registerService",description:"Register a service.",parameters:{properties:{service:{description:"The service to register",type:"object"},force:{default:!1,description:"Force to register the service",type:"boolean"}},required:["service"],type:"object"}}),c.unregisterService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(a.unregister_service.bind(a),{name:"unregisterService",description:"Unregister a service.",parameters:{properties:{service:{description:"The service id to unregister",type:"string"},notify:{default:!0,description:"Notify the workspace manager",type:"boolean"}},required:["service"],type:"object"}}),o.manager_id&&a.on("force-exit",async e=>{e.from==="*/"+o.manager_id&&(t.log("Disconnecting from server, reason:",e.reason),await a.disconnect())}),e.webrtc){await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_4__.registerRTCService)(c,`${n}-rtc`,e.webrtc_config);const t=Object.assign({},c),r=t.getService.__schema__.description,o=t.getService.__schema__.parameters;c.getService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(function(n,r){return webrtcGetService(t,n,r,e.logger)},{name:"getService",description:r,parameters:o}),c.getRTCService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(_webrtc_client_js__WEBPACK_IMPORTED_MODULE_4__.getRTCService.bind(null,c),{name:"getRTCService",description:"Get the webrtc connection, returns a peer connection.",parameters:{properties:{config:{description:"The config for the webrtc service",type:"object"}},required:["config"],type:"object"}})}else{const e=c.getService;c.getService=async(t,n)=>{const r=(n=n||{}).encryption_public_key;delete n.encryption_public_key;const o=await e(t,n);return r&&(0,_rpc_js__WEBPACK_IMPORTED_MODULE_0__._applyEncryptionKeyToService)(o,(0,_crypto_js__WEBPACK_IMPORTED_MODULE_1__.publicKeyFromHex)(r)),o},c.getService.__schema__=e.__schema__}return c.registerProbes=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction)(async function(e){return e.id="probes",e.name="Probes",e.config={visibility:"public"},e.type="probes",e.description=`Probes Service, visit ${r}/${s}services/probes for the available probes.`,await c.registerService(e,{overwrite:!0})},{name:"registerProbes",description:"Register probes service",parameters:{properties:{probes:{description:"The probes to register, e.g. {'liveness': {'type': 'function', 'description': 'Check the liveness of the service'}}",type:"object"}},required:["probes"],type:"object"}}),c}async function getRemoteService(e,t={}){const{serverUrl:n,workspace:r,clientId:o,serviceId:i,appId:s}=(0,_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.parseServiceUrl)(e),a=`${r}/${o}:${i}@${s}`;if(t.serverUrl&&t.serverUrl!==n)throw new Error("server_url in config does not match the server_url in the url");t.serverUrl=n;const c=await connectToServer(t);return await c.getService(a)}class LocalWebSocket{constructor(e,t,n){this.url=e,this.onopen=()=>{},this.onmessage=()=>{},this.onclose=()=>{},this.onerror=()=>{},this.client_id=t,this.workspace=n;const r="undefined"!=typeof window?window:self,o="undefined"!=typeof window;if(this.postMessage=e=>{o?window.parent.postMessage(e,"*"):self.postMessage(e)},this.readyState=WebSocket.CONNECTING,this._context=r,this._messageListener=e=>{const{type:t,data:n,to:r}=e.data;if(r===this.client_id)switch(t){case"message":this.readyState===WebSocket.OPEN&&this.onmessage&&this.onmessage({data:n});break;case"connected":this.readyState=WebSocket.OPEN,this.onopen(e);break;case"closed":this.readyState=WebSocket.CLOSED,this.onclose(e)}},r.addEventListener("message",this._messageListener,!1),!this.client_id)throw new Error("client_id is required");if(!this.workspace)throw new Error("workspace is required");this.postMessage({type:"connect",url:this.url,from:this.client_id,workspace:this.workspace})}send(e){this.readyState===WebSocket.OPEN&&this.postMessage({type:"message",data:e,from:this.client_id,workspace:this.workspace})}close(){this.readyState=WebSocket.CLOSING,this.postMessage({type:"close",from:this.client_id,workspace:this.workspace}),this._context&&this._messageListener&&(this._context.removeEventListener("message",this._messageListener,!1),this._messageListener=null),this.onclose()}addEventListener(e,t){"message"===e&&(this.onmessage=t),"open"===e&&(this.onopen=t),"close"===e&&(this.onclose=t),"error"===e&&(this.onerror=t)}}const hyphaWebsocketClient={RPC:_rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC,API_VERSION:_rpc_js__WEBPACK_IMPORTED_MODULE_0__.API_VERSION,schemaFunction:_utils_schema_js__WEBPACK_IMPORTED_MODULE_3__.schemaFunction,loadRequirements:_utils_index_js__WEBPACK_IMPORTED_MODULE_2__.loadRequirements,login:login,logout:logout,connectToServer:connectToServer,connectToServerHTTP:_http_client_js__WEBPACK_IMPORTED_MODULE_5__.connectToServerHTTP,getRemoteService:getRemoteService,getRemoteServiceHTTP:_http_client_js__WEBPACK_IMPORTED_MODULE_5__.getRemoteServiceHTTP,getRTCService:_webrtc_client_js__WEBPACK_IMPORTED_MODULE_4__.getRTCService,registerRTCService:_webrtc_client_js__WEBPACK_IMPORTED_MODULE_4__.registerRTCService,get setupLocalClient(){return setupLocalClient},get LocalWebSocket(){return LocalWebSocket},HTTPStreamingRPCConnection:_http_client_js__WEBPACK_IMPORTED_MODULE_5__.HTTPStreamingRPCConnection,normalizeServerUrlHTTP:_http_client_js__WEBPACK_IMPORTED_MODULE_5__.normalizeServerUrl};function setupLocalClient({enable_execution:enable_execution=!1,on_ready:on_ready=null}){return new Promise((resolve,reject)=>{const context="undefined"!=typeof window?window:self,isWindow="undefined"!=typeof window;context.addEventListener("message",event=>{const{type:type,server_url:server_url,workspace:workspace,client_id:client_id,token:token,method_timeout:method_timeout,name:name,config:config}=event.data;if("initializeHyphaClient"===type){if(!server_url||!workspace||!client_id)return void _logger.error("server_url, workspace, and client_id are required.");if(!server_url.startsWith("https://local-hypha-server:"))return void _logger.error("server_url should start with https://local-hypha-server:");class FixedLocalWebSocket extends LocalWebSocket{constructor(e){super(e,client_id,workspace)}}connectToServer({server_url:server_url,workspace:workspace,client_id:client_id,token:token,method_timeout:method_timeout,name:name,WebSocketClass:FixedLocalWebSocket}).then(async server=>{globalThis.api=server;try{if(isWindow&&enable_execution){function e(e){return new Promise((t,n)=>{const r=document.createElement("script");r.innerHTML=e.content,r.lang=e.lang,r.onload=()=>t(),r.onerror=e=>n(e),document.head.appendChild(r)})}if(config.styles&&config.styles.length>0)for(const t of config.styles){const n=document.createElement("style");n.innerHTML=t.content,n.lang=t.lang,document.head.appendChild(n)}if(config.links&&config.links.length>0)for(const r of config.links){const o=document.createElement("a");o.href=r.url,o.innerText=r.text,document.body.appendChild(o)}if(config.windows&&config.windows.length>0)for(const i of config.windows){document.body.innerHTML=i.content;break}if(config.scripts&&config.scripts.length>0)for(const s of config.scripts){if("javascript"!==s.lang)throw new Error("Only javascript scripts are supported");await e(s)}}else if(!isWindow&&enable_execution&&config.scripts&&config.scripts.length>0)for(const script of config.scripts){if("javascript"!==script.lang)throw new Error("Only javascript scripts are supported");eval(script.content)}on_ready&&await on_ready(server,config),resolve(server)}catch(a){reject(a)}})}},!1),isWindow?window.parent.postMessage({type:"hyphaClientReady"},"*"):self.postMessage({type:"hyphaClientReady"})})}var __webpack_exports__API_VERSION=__webpack_exports__.API_VERSION,__webpack_exports__HTTPStreamingRPCConnection=__webpack_exports__.HTTPStreamingRPCConnection,__webpack_exports__LocalWebSocket=__webpack_exports__.LocalWebSocket,__webpack_exports__RPC=__webpack_exports__.RPC,__webpack_exports__WebsocketRPCConnection=__webpack_exports__.WebsocketRPCConnection,__webpack_exports__connectToServer=__webpack_exports__.connectToServer,__webpack_exports__connectToServerHTTP=__webpack_exports__.connectToServerHTTP,__webpack_exports__decryptPayload=__webpack_exports__.decryptPayload,__webpack_exports__encryptPayload=__webpack_exports__.encryptPayload,__webpack_exports__generateEncryptionKeypair=__webpack_exports__.generateEncryptionKeypair,__webpack_exports__getRTCService=__webpack_exports__.getRTCService,__webpack_exports__getRemoteService=__webpack_exports__.getRemoteService,__webpack_exports__getRemoteServiceHTTP=__webpack_exports__.getRemoteServiceHTTP,__webpack_exports__hyphaWebsocketClient=__webpack_exports__.hyphaWebsocketClient,__webpack_exports__loadRequirements=__webpack_exports__.loadRequirements,__webpack_exports__login=__webpack_exports__.login,__webpack_exports__logout=__webpack_exports__.logout,__webpack_exports__normalizeServerUrlHTTP=__webpack_exports__.normalizeServerUrlHTTP,__webpack_exports__publicKeyFromHex=__webpack_exports__.publicKeyFromHex,__webpack_exports__publicKeyToHex=__webpack_exports__.publicKeyToHex,__webpack_exports__registerRTCService=__webpack_exports__.registerRTCService,__webpack_exports__schemaFunction=__webpack_exports__.schemaFunction,__webpack_exports__setupLocalClient=__webpack_exports__.setupLocalClient,hyphaRpcWebsocket=Object.freeze({__proto__:null,API_VERSION:__webpack_exports__API_VERSION,HTTPStreamingRPCConnection:__webpack_exports__HTTPStreamingRPCConnection,LocalWebSocket:__webpack_exports__LocalWebSocket,RPC:__webpack_exports__RPC,WebsocketRPCConnection:__webpack_exports__WebsocketRPCConnection,connectToServer:__webpack_exports__connectToServer,connectToServerHTTP:__webpack_exports__connectToServerHTTP,decryptPayload:__webpack_exports__decryptPayload,encryptPayload:__webpack_exports__encryptPayload,generateEncryptionKeypair:__webpack_exports__generateEncryptionKeypair,getRTCService:__webpack_exports__getRTCService,getRemoteService:__webpack_exports__getRemoteService,getRemoteServiceHTTP:__webpack_exports__getRemoteServiceHTTP,hyphaWebsocketClient:__webpack_exports__hyphaWebsocketClient,loadRequirements:__webpack_exports__loadRequirements,login:__webpack_exports__login,logout:__webpack_exports__logout,normalizeServerUrlHTTP:__webpack_exports__normalizeServerUrlHTTP,publicKeyFromHex:__webpack_exports__publicKeyFromHex,publicKeyToHex:__webpack_exports__publicKeyToHex,registerRTCService:__webpack_exports__registerRTCService,schemaFunction:__webpack_exports__schemaFunction,setupLocalClient:__webpack_exports__setupLocalClient}),hyphaRpc=Object.freeze({__proto__:null,API_VERSION:__webpack_exports__API_VERSION,HTTPStreamingRPCConnection:__webpack_exports__HTTPStreamingRPCConnection,LocalWebSocket:__webpack_exports__LocalWebSocket,RPC:__webpack_exports__RPC,connectToServer:__webpack_exports__connectToServer,connectToServerHTTP:__webpack_exports__connectToServerHTTP,getRTCService:__webpack_exports__getRTCService,getRemoteService:__webpack_exports__getRemoteService,getRemoteServiceHTTP:__webpack_exports__getRemoteServiceHTTP,hyphaWebsocketClient:hyphaRpcWebsocket,loadRequirements:__webpack_exports__loadRequirements,login:__webpack_exports__login,logout:__webpack_exports__logout,normalizeServerUrlHTTP:__webpack_exports__normalizeServerUrlHTTP,registerRTCService:__webpack_exports__registerRTCService,schemaFunction:__webpack_exports__schemaFunction,setupLocalClient:__webpack_exports__setupLocalClient});const overlayStyles="\n :host {\n all: initial;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n }\n\n * {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n }\n\n .debugger-icon {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background: #4a90d9;\n color: white;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n transition: transform 0.15s, background 0.15s;\n user-select: none;\n font-size: 18px;\n line-height: 1;\n }\n\n .debugger-icon:hover {\n transform: scale(1.1);\n background: #357abd;\n }\n\n .debugger-icon.connected {\n background: #27ae60;\n }\n\n .debugger-icon.error {\n background: #e74c3c;\n }\n\n .debugger-panel {\n display: none;\n width: 380px;\n max-height: 520px;\n background: #1e1e2e;\n color: #cdd6f4;\n border-radius: 8px;\n border: 1px solid #45475a;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);\n overflow: hidden;\n flex-direction: column;\n position: absolute;\n bottom: 50px;\n right: 0;\n font-size: 13px;\n }\n\n .debugger-panel.open {\n display: flex;\n }\n\n .panel-header {\n background: #313244;\n padding: 8px 12px;\n display: flex;\n align-items: center;\n justify-content: space-between;\n cursor: default;\n border-bottom: 1px solid #45475a;\n font-weight: 600;\n font-size: 12px;\n letter-spacing: 0.3px;\n text-transform: uppercase;\n color: #a6adc8;\n }\n\n .panel-header .title {\n display: flex;\n align-items: center;\n gap: 6px;\n }\n\n .panel-header .close-btn {\n cursor: pointer;\n color: #6c7086;\n font-size: 16px;\n line-height: 1;\n padding: 2px 4px;\n border-radius: 3px;\n }\n\n .panel-header .close-btn:hover {\n color: #cdd6f4;\n background: #45475a;\n }\n\n .status-dot {\n width: 8px;\n height: 8px;\n border-radius: 50%;\n display: inline-block;\n background: #6c7086;\n }\n\n .status-dot.connected {\n background: #a6e3a1;\n }\n\n .status-dot.error {\n background: #f38ba8;\n }\n\n .panel-body {\n padding: 10px 12px;\n overflow-y: auto;\n flex: 1;\n max-height: 440px;\n }\n\n .info-row {\n display: flex;\n justify-content: space-between;\n padding: 4px 0;\n border-bottom: 1px solid #313244;\n font-size: 12px;\n }\n\n .info-row .label {\n color: #6c7086;\n }\n\n .info-row .value {\n color: #cdd6f4;\n text-align: right;\n word-break: break-all;\n max-width: 180px;\n font-family: 'SF Mono', Monaco, Consolas, monospace;\n font-size: 11px;\n }\n\n .instructions-section {\n margin-top: 8px;\n padding-top: 6px;\n border-top: 1px solid #313244;\n }\n\n .instructions-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 4px;\n }\n\n .url-label {\n font-size: 11px;\n color: #6c7086;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 3px;\n }\n\n .instructions-block {\n font-family: 'SF Mono', Monaco, Consolas, monospace;\n font-size: 10px;\n color: #a6e3a1;\n background: #11111b;\n border: 1px solid #313244;\n border-radius: 4px;\n padding: 8px;\n white-space: pre-wrap;\n word-break: break-all;\n max-height: 200px;\n overflow-y: auto;\n line-height: 1.5;\n }\n\n .copy-btn {\n background: #45475a;\n color: #cdd6f4;\n border: none;\n border-radius: 3px;\n padding: 2px 8px;\n font-size: 10px;\n cursor: pointer;\n white-space: nowrap;\n flex-shrink: 0;\n }\n\n .copy-btn:hover {\n background: #585b70;\n }\n\n .log-section {\n margin-top: 8px;\n }\n\n .log-title {\n font-size: 11px;\n color: #6c7086;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n margin-bottom: 4px;\n }\n\n .log-entry {\n font-family: 'SF Mono', Monaco, Consolas, monospace;\n font-size: 11px;\n padding: 3px 6px;\n border-radius: 3px;\n background: #313244;\n margin-bottom: 2px;\n color: #a6adc8;\n word-break: break-all;\n }\n\n .log-entry.call {\n border-left: 2px solid #89b4fa;\n }\n\n .log-entry.result {\n border-left: 2px solid #a6e3a1;\n }\n\n .log-entry.error {\n border-left: 2px solid #f38ba8;\n color: #f38ba8;\n }\n";class DebugOverlay{constructor(e){this.isOpen=!1,this.isDragging=!1,this.dragOffset={x:0,y:0},this.maxLogEntries=50,this.host=document.createElement("div"),this.host.id="hypha-debugger-host",Object.assign(this.host.style,{position:"fixed",bottom:"20px",right:"20px",zIndex:"2147483647",display:"flex",flexDirection:"column",alignItems:"flex-end"}),e?.position&&(this.host.style.bottom="auto",this.host.style.right="auto",this.host.style.left=e.position.x+"px",this.host.style.top=e.position.y+"px"),this.shadow=this.host.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=overlayStyles,this.shadow.appendChild(t);const n=document.createElement("div");n.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="flex-end",this.panel=document.createElement("div"),this.panel.className="debugger-panel";const r=document.createElement("div");r.className="panel-header";const o=document.createElement("span");o.className="title",this.statusDot=document.createElement("span"),this.statusDot.className="status-dot",o.appendChild(this.statusDot),o.appendChild(document.createTextNode(" Hypha Debugger"));const i=document.createElement("span");i.className="close-btn",i.textContent="×",i.addEventListener("click",()=>this.toggle()),r.appendChild(o),r.appendChild(i);const s=document.createElement("div");s.className="panel-body",this.infoBody=document.createElement("div"),s.appendChild(this.infoBody);const a=document.createElement("div");a.className="log-section";const c=document.createElement("div");c.className="log-title",c.textContent="Remote Operations",this.logContainer=document.createElement("div"),a.appendChild(c),a.appendChild(this.logContainer),s.appendChild(a),this.panel.appendChild(r),this.panel.appendChild(s),this.icon=document.createElement("div"),this.icon.className="debugger-icon",this.icon.textContent="🐛",this.icon.addEventListener("click",e=>{this.isDragging||this.toggle()}),n.appendChild(this.panel),n.appendChild(this.icon),this.shadow.appendChild(n),document.documentElement.appendChild(this.host),this.setupDrag()}setupDrag(){let e=0,t=0,n=!1;this.icon.addEventListener("mousedown",r=>{e=r.clientX,t=r.clientY,n=!1;const o=this.host.getBoundingClientRect();this.dragOffset.x=r.clientX-o.left,this.dragOffset.y=r.clientY-o.top,r.preventDefault()}),document.addEventListener("mousemove",r=>{if(0===e&&0===t)return;const o=Math.abs(r.clientX-e),i=Math.abs(r.clientY-t);(o>3||i>3)&&(n=!0,this.isDragging=!0,this.host.style.left=r.clientX-this.dragOffset.x+"px",this.host.style.top=r.clientY-this.dragOffset.y+"px",this.host.style.right="auto",this.host.style.bottom="auto")}),document.addEventListener("mouseup",()=>{e=0,t=0,n&&setTimeout(()=>{this.isDragging=!1},50)})}toggle(){this.isOpen=!this.isOpen,this.panel.classList.toggle("open",this.isOpen)}setStatus(e){this.statusDot.className="status-dot",this.icon.className="debugger-icon","connected"===e?(this.statusDot.classList.add("connected"),this.icon.classList.add("connected")):"error"===e&&(this.statusDot.classList.add("error"),this.icon.classList.add("error"))}setInfo(e){this.infoBody.querySelectorAll(".info-row").forEach(e=>e.remove());const t=this.infoBody.firstChild;for(const[n,r]of Object.entries(e)){const e=document.createElement("div");e.className="info-row";const o=document.createElement("span");o.className="label",o.textContent=n;const i=document.createElement("span");i.className="value",i.textContent=r,i.title=r,e.appendChild(o),e.appendChild(i),this.infoBody.insertBefore(e,t)}}setInstructions(e){const t=this.infoBody.querySelector(".instructions-section");t&&t.remove();const n=document.createElement("div");n.className="instructions-section";const r=document.createElement("div");r.className="instructions-header";const o=document.createElement("span");o.className="url-label",o.textContent="Instructions";const i=document.createElement("button");i.className="copy-btn",i.textContent="Copy All",i.addEventListener("click",()=>{navigator.clipboard.writeText(e).then(()=>{i.textContent="Copied!",setTimeout(()=>{i.textContent="Copy All"},1500)})}),r.appendChild(o),r.appendChild(i),n.appendChild(r);const s=document.createElement("pre");s.className="instructions-block",s.textContent=e,n.appendChild(s),this.infoBody.appendChild(n)}addLog(e,t="call"){const n=document.createElement("div");for(n.className=`log-entry ${t}`,n.textContent=e,this.logContainer.appendChild(n);this.logContainer.children.length>this.maxLogEntries;)this.logContainer.removeChild(this.logContainer.firstChild);const r=this.panel.querySelector(".panel-body");r&&(r.scrollTop=r.scrollHeight)}destroy(){this.host.remove()}}const CURSOR_BORDER_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" fill="none"><g><path d="M 15 42 L 15 36.99 Q 15 31.99 23.7 31.99 L 28.05 31.99 Q 32.41 31.99 32.41 21.99 L 32.41 17 Q 32.41 12 41.09 16.95 L 76.31 37.05 Q 85 42 76.31 46.95 L 41.09 67.05 Q 32.41 72 32.41 62.01 L 32.41 57.01 Q 32.41 52.01 23.7 52.01 L 19.35 52.01 Q 15 52.01 15 47.01 Z" fill="none" stroke="currentColor" stroke-width="6" stroke-miterlimit="10"/></g></svg>',CURSOR_FILL_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><g style="filter: drop-shadow(rgba(0, 0, 0, 0.3) 3px 4px 4px);"><path d="M 15 42 L 15 36.99 Q 15 31.99 23.7 31.99 L 28.05 31.99 Q 32.41 31.99 32.41 21.99 L 32.41 17 Q 32.41 12 41.09 16.95 L 76.31 37.05 Q 85 42 76.31 46.95 L 41.09 67.05 Q 32.41 72 32.41 62.01 L 32.41 57.01 Q 32.41 52.01 23.7 52.01 L 19.35 52.01 Q 15 52.01 15 47.01 Z" fill="#ffffff" stroke="none"/></g></svg>',CURSOR_CSS="\n .hypha-cursor {\n position: fixed;\n width: 50px;\n height: 50px;\n pointer-events: none;\n z-index: 2147483646;\n transition: opacity 0.2s;\n opacity: 0;\n }\n .hypha-cursor.visible {\n opacity: 1;\n }\n .hypha-cursor-border {\n position: absolute;\n width: 100%;\n height: 100%;\n background: linear-gradient(45deg, rgb(57, 182, 255), rgb(189, 69, 251));\n mask-image: var(--cursor-border);\n -webkit-mask-image: var(--cursor-border);\n mask-size: 100% 100%;\n -webkit-mask-size: 100% 100%;\n mask-repeat: no-repeat;\n -webkit-mask-repeat: no-repeat;\n transform-origin: center;\n transform: rotate(-135deg) scale(1.2);\n margin-left: -10px;\n margin-top: -14px;\n }\n .hypha-cursor-fill {\n position: absolute;\n width: 100%;\n height: 100%;\n background-image: var(--cursor-fill);\n background-size: 100% 100%;\n background-repeat: no-repeat;\n transform-origin: center;\n transform: rotate(-135deg) scale(1.2);\n margin-left: -10px;\n margin-top: -14px;\n }\n .hypha-cursor-ripple {\n position: absolute;\n width: 100%;\n height: 100%;\n pointer-events: none;\n margin-left: -50%;\n margin-top: -50%;\n }\n .hypha-cursor-ripple::after {\n content: '';\n opacity: 0;\n position: absolute;\n inset: 0;\n border: 3px solid rgba(57, 182, 255, 1);\n border-radius: 50%;\n }\n .hypha-cursor.clicking .hypha-cursor-ripple::after {\n animation: hypha-cursor-ripple 400ms ease-out forwards;\n }\n @keyframes hypha-cursor-ripple {\n 0% { transform: scale(0); opacity: 1; }\n 100% { transform: scale(2.5); opacity: 0; }\n }\n";class AICursor{constructor(){this.currentX=0,this.currentY=0,this.targetX=0,this.targetY=0,this.animating=!1,this.visible=!1,this.hideTimeout=null,this.container=document.createElement("div"),this.container.id="hypha-debugger-cursor",this.container.setAttribute("data-browser-use-ignore","true"),this.container.setAttribute("data-page-agent-ignore","true");const e=document.createElement("style");e.textContent=CURSOR_CSS,this.container.appendChild(e),this.cursor=document.createElement("div"),this.cursor.className="hypha-cursor";const t='url("data:image/svg+xml,'+encodeURIComponent(CURSOR_BORDER_SVG)+'")',n='url("data:image/svg+xml,'+encodeURIComponent(CURSOR_FILL_SVG)+'")';this.cursor.style.setProperty("--cursor-border",t),this.cursor.style.setProperty("--cursor-fill",n);const r=document.createElement("div");r.className="hypha-cursor-ripple",this.cursor.appendChild(r);const o=document.createElement("div");o.className="hypha-cursor-fill",this.cursor.appendChild(o);const i=document.createElement("div");i.className="hypha-cursor-border",this.cursor.appendChild(i),this.container.appendChild(this.cursor),document.body.appendChild(this.container),window.addEventListener("HyphaDebugger::MovePointerTo",e=>{const{x:t,y:n}=e.detail;this.moveTo(t,n)}),window.addEventListener("HyphaDebugger::ClickPointer",()=>{this.triggerClickAnimation()})}moveTo(e,t){this.targetX=e,this.targetY=t,this.visible||(this.visible=!0,this.currentX=e,this.currentY=t,this.cursor.style.left=`${e}px`,this.cursor.style.top=`${t}px`,this.cursor.classList.add("visible")),this.hideTimeout&&(clearTimeout(this.hideTimeout),this.hideTimeout=null),this.animating||(this.animating=!0,this.animateLoop())}animateLoop(){const e=this.targetX-this.currentX,t=this.targetY-this.currentY;Math.abs(e)>1||Math.abs(t)>1?(this.currentX+=.18*e,this.currentY+=.18*t,this.cursor.style.left=`${this.currentX}px`,this.cursor.style.top=`${this.currentY}px`,requestAnimationFrame(()=>this.animateLoop())):(this.currentX=this.targetX,this.currentY=this.targetY,this.cursor.style.left=`${this.currentX}px`,this.cursor.style.top=`${this.currentY}px`,this.animating=!1,this.hideTimeout=setTimeout(()=>{this.visible=!1,this.cursor.classList.remove("visible")},2e3))}triggerClickAnimation(){this.cursor.classList.remove("clicking"),this.cursor.offsetHeight,this.cursor.classList.add("clicking")}destroy(){this.hideTimeout&&clearTimeout(this.hideTimeout),this.container.remove()}}function detectFrameworks(){const e=[],t=window;if(t.__REACT_DEVTOOLS_GLOBAL_HOOK__?.renderers?.size>0)e.push("react");else{const t=document.querySelector("#root, #app, [data-reactroot]");if(t){Object.keys(t).some(e=>e.startsWith("__reactFiber$")||e.startsWith("__reactInternalInstance$"))&&e.push("react")}}if(t.__VUE__||t.__VUE_DEVTOOLS_GLOBAL_HOOK__)e.push("vue");else{const t=document.querySelector("[data-v-app], #app");t&&t.__vue_app__&&e.push("vue")}return(t.ng||document.querySelector("[ng-version]"))&&e.push("angular"),document.querySelector("[class*='svelte-']")&&e.push("svelte"),t.__NEXT_DATA__&&e.push("nextjs"),e}function collectPageInfo(){const e=performance.getEntriesByType("navigation")[0];return{url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},document_size:{width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight},user_agent:navigator.userAgent,timestamp:(new Date).toISOString(),cookies_enabled:navigator.cookieEnabled,language:navigator.language,platform:navigator.platform,online:navigator.onLine,performance:{load_time_ms:e?Math.round(e.loadEventEnd-e.startTime):null,dom_content_loaded_ms:e?Math.round(e.domContentLoadedEventEnd-e.startTime):null},frameworks:detectFrameworks()}}function getPageInfo(e,t,n){const r=collectPageInfo();if(e){const e=window.__HYPHA_DEBUGGER__?.consoleLogs??[],o=t??50;let i=n?e.filter(e=>e.level===n):e;r.console_logs=i.slice(-o)}return r}function getConsoleLogs(e){const t=window.__HYPHA_DEBUGGER__?.consoleLogs??[],n=e?.level,r=e?.limit??100;return(n?t.filter(e=>e.level===n):t).slice(-r)}function installConsoleCapture(e=500){var t;const n=(t=window).__HYPHA_DEBUGGER__??(t.__HYPHA_DEBUGGER__={});if(n.consoleInstalled)return;n.consoleLogs=[],n.consoleInstalled=!0;const r=["log","warn","error","info"];for(const t of r){const r=console[t].bind(console);console[t]=(...o)=>{const i=n.consoleLogs;i.push({level:t,message:o.map(e=>{try{return"string"==typeof e?e:JSON.stringify(e)}catch{return String(e)}}).join(" "),timestamp:(new Date).toISOString()}),i.length>e&&i.splice(0,i.length-e),r(...o)}}}function elementToInfo(e){const t=e.getBoundingClientRect(),n={};for(const t of Array.from(e.attributes))n[t.name]=t.value;return{tag:e.tagName.toLowerCase(),id:e.id,classes:Array.from(e.classList),text:(e.textContent??"").trim().slice(0,500),attributes:n,bounds:{x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)},visible:t.width>0&&t.height>0&&"hidden"!==getComputedStyle(e).visibility&&"none"!==getComputedStyle(e).display,children_count:e.children.length}}function queryDom(e,t){t=t??20;const n=document.querySelectorAll(e),r=[];for(let e=0;e<Math.min(n.length,t);e++)r.push(elementToInfo(n[e]));return r}function clickElement$1(e){const t=document.querySelector(e);if(!t)return{success:!1,message:`No element found for selector: ${e}`};const n=t.getBoundingClientRect();return t.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window,clientX:n.left+n.width/2,clientY:n.top+n.height/2})),{success:!0,message:`Clicked element: ${e}`}}function fillInput(e,t){const n=document.querySelector(e);if(!n)return{success:!1,message:`No element found for selector: ${e}`};const r=n.tagName.toLowerCase();if("input"===r||"textarea"===r){const o=n,i="textarea"===r?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,s=Object.getOwnPropertyDescriptor(i,"value")?.set;return s?s.call(o,t):o.value=t,o.dispatchEvent(new Event("input",{bubbles:!0})),o.dispatchEvent(new Event("change",{bubbles:!0})),{success:!0,message:`Filled ${e} with value`}}if("select"===r){const r=n,o=Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,"value")?.set;return o?o.call(r,t):r.value=t,r.dispatchEvent(new Event("change",{bubbles:!0})),{success:!0,message:`Set ${e} to ${t}`}}return{success:!1,message:`Element ${e} is not an input/textarea/select`}}function scrollTo(e){if("string"==typeof e){const t=document.querySelector(e);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),{success:!0,message:`Scrolled to ${e}`}):{success:!1,message:`No element found for selector: ${e}`}}return window.scrollTo({left:e.x,top:e.y,behavior:"smooth"}),{success:!0,message:`Scrolled to (${e.x}, ${e.y})`}}function getComputedStyles(e,t){const n=document.querySelector(e);if(!n)return{error:`No element found for selector: ${e}`};const r=getComputedStyle(n),o={},i=t??["display","position","width","height","color","background-color","font-size","font-family","margin","padding","border","opacity","visibility","overflow","z-index"];for(const e of i)o[e]=r.getPropertyValue(e);return o}function getElementBounds(e){const t=document.querySelector(e);if(!t)return{error:`No element found for selector: ${e}`};const n=t.getBoundingClientRect();return{bounds:{x:Math.round(n.x),y:Math.round(n.y),width:Math.round(n.width),height:Math.round(n.height)},visible:n.width>0&&n.height>0&&"hidden"!==getComputedStyle(t).visibility&&"none"!==getComputedStyle(t).display}}function getHtml(e,t,n){const r=t??!0,o=n??5e4,i=e?document.querySelector(e):document.documentElement;if(!i)return{error:`No element found for selector: ${e}`};const s=r?i.outerHTML:i.innerHTML,a=s.length>o;return{html:a?s.slice(0,o):s,length:s.length,truncated:a}}function resolveUrl(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i))return e;const n=document.implementation.createHTMLDocument(),r=n.createElement("base"),o=n.createElement("a");return n.head.appendChild(r),n.body.appendChild(o),t&&(r.href=t),o.href=e,o.href}getPageInfo.__schema__={name:"getPageInfo",description:"Get information about the current web page including URL, title, viewport size, detected frameworks, and performance timing. Optionally include recent console logs.",parameters:{type:"object",properties:{include_logs:{type:"boolean",description:"If true, include recent console output in the response. Default: false."},log_limit:{type:"number",description:"Maximum number of console log entries to include (most recent). Default: 50."},log_level:{type:"string",description:'Filter console logs by level: "log", "warn", "error", "info". Omit for all levels.',enum:["log","warn","error","info"]}}}},getConsoleLogs.__schema__={name:"getConsoleLogs",description:"Retrieve captured console output (log, warn, error, info).",parameters:{type:"object",properties:{level:{type:"string",description:'Filter by log level: "log", "warn", "error", "info". Omit for all levels.',enum:["log","warn","error","info"]},limit:{type:"number",description:"Maximum number of log entries to return (most recent). Default: 100."}}}},queryDom.__schema__={name:"queryDom",description:"Query DOM elements by CSS selector. Returns tag, id, classes, text content, attributes, bounding rect, and visibility for each matching element.",parameters:{type:"object",properties:{selector:{type:"string",description:'CSS selector to query, e.g. "button.primary", "#app > div".'},limit:{type:"number",description:"Maximum number of elements to return. Default: 20."}},required:["selector"]}},clickElement$1.__schema__={name:"clickElement",description:"Click a DOM element matching the CSS selector.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element to click."}},required:["selector"]}},fillInput.__schema__={name:"fillInput",description:"Set the value of an input, textarea, or select element. Works with React controlled components.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the input element."},value:{type:"string",description:"The value to set."}},required:["selector","value"]}},scrollTo.__schema__={name:"scrollTo",description:"Scroll to a DOM element (by CSS selector) or to an absolute position {x, y}.",parameters:{type:"object",properties:{target:{description:"CSS selector string to scroll to an element, or an object {x, y} for absolute scroll position."}},required:["target"]}},getComputedStyles.__schema__={name:"getComputedStyles",description:"Get computed CSS styles for an element.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element."},properties:{type:"array",items:{type:"string"},description:'CSS property names to retrieve, e.g. ["color", "font-size"]. Omit for common defaults.'}},required:["selector"]}},getElementBounds.__schema__={name:"getElementBounds",description:"Get the bounding rectangle and visibility of a DOM element.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element."}},required:["selector"]}},getHtml.__schema__={name:"getHtml",description:"Get the HTML content of the page or a specific element. Returns outerHTML by default. Useful for understanding page structure.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element. Omit to get the full page HTML."},outer:{type:"boolean",description:"If true (default), return outerHTML (includes the element itself). If false, return innerHTML (children only)."},max_length:{type:"number",description:"Maximum character length of the returned HTML. Default: 50000. Result will be truncated if longer."}}}};const uuid=(()=>{let e=0;return()=>(e+=1,`u${`0000${(Math.random()*36**4|0).toString(36)}`.slice(-4)}${e}`)})();function toArray(e){const t=[];for(let n=0,r=e.length;n<r;n++)t.push(e[n]);return t}let styleProps=null;function getStyleProperties(e={}){return styleProps||(e.includeStyleProperties?(styleProps=e.includeStyleProperties,styleProps):(styleProps=toArray(window.getComputedStyle(document.documentElement)),styleProps))}function px(e,t){const n=(e.ownerDocument.defaultView||window).getComputedStyle(e).getPropertyValue(t);return n?parseFloat(n.replace("px","")):0}function getNodeWidth(e){const t=px(e,"border-left-width"),n=px(e,"border-right-width");return e.clientWidth+t+n}function getNodeHeight(e){const t=px(e,"border-top-width"),n=px(e,"border-bottom-width");return e.clientHeight+t+n}function getImageSize(e,t={}){return{width:t.width||getNodeWidth(e),height:t.height||getNodeHeight(e)}}function getPixelRatio(){let e,t;try{t=process}catch(e){}const n=t&&t.env?t.env.devicePixelRatio:null;return n&&(e=parseInt(n,10),Number.isNaN(e)&&(e=1)),e||window.devicePixelRatio||1}const canvasDimensionLimit=16384;function checkCanvasDimensions(e){(e.width>canvasDimensionLimit||e.height>canvasDimensionLimit)&&(e.width>canvasDimensionLimit&&e.height>canvasDimensionLimit?e.width>e.height?(e.height*=canvasDimensionLimit/e.width,e.width=canvasDimensionLimit):(e.width*=canvasDimensionLimit/e.height,e.height=canvasDimensionLimit):e.width>canvasDimensionLimit?(e.height*=canvasDimensionLimit/e.width,e.width=canvasDimensionLimit):(e.width*=canvasDimensionLimit/e.height,e.height=canvasDimensionLimit))}function createImage(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=n,r.crossOrigin="anonymous",r.decoding="async",r.src=e})}async function svgToDataURL(e){return Promise.resolve().then(()=>(new XMLSerializer).serializeToString(e)).then(encodeURIComponent).then(e=>`data:image/svg+xml;charset=utf-8,${e}`)}async function nodeToDataURL(e,t,n){const r="http://www.w3.org/2000/svg",o=document.createElementNS(r,"svg"),i=document.createElementNS(r,"foreignObject");return o.setAttribute("width",`${t}`),o.setAttribute("height",`${n}`),o.setAttribute("viewBox",`0 0 ${t} ${n}`),i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("externalResourcesRequired","true"),o.appendChild(i),i.appendChild(e),svgToDataURL(o)}const isInstanceOfElement=(e,t)=>{if(e instanceof t)return!0;const n=Object.getPrototypeOf(e);return null!==n&&(n.constructor.name===t.name||isInstanceOfElement(n,t))};function formatCSSText(e){const t=e.getPropertyValue("content");return`${e.cssText} content: '${t.replace(/'|"/g,"")}';`}function formatCSSProperties(e,t){return getStyleProperties(t).map(t=>`${t}: ${e.getPropertyValue(t)}${e.getPropertyPriority(t)?" !important":""};`).join(" ")}function getPseudoElementStyle(e,t,n,r){const o=`.${e}:${t}`,i=n.cssText?formatCSSText(n):formatCSSProperties(n,r);return document.createTextNode(`${o}{${i}}`)}function clonePseudoElement(e,t,n,r){const o=window.getComputedStyle(e,n),i=o.getPropertyValue("content");if(""===i||"none"===i)return;const s=uuid();try{t.className=`${t.className} ${s}`}catch(e){return}const a=document.createElement("style");a.appendChild(getPseudoElementStyle(s,n,o,r)),t.appendChild(a)}function clonePseudoElements(e,t,n){clonePseudoElement(e,t,":before",n),clonePseudoElement(e,t,":after",n)}const WOFF="application/font-woff",JPEG="image/jpeg",mimes={woff:WOFF,woff2:WOFF,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:JPEG,jpeg:JPEG,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function getExtension(e){const t=/\.([^./]*?)$/g.exec(e);return t?t[1]:""}function getMimeType(e){const t=getExtension(e).toLowerCase();return mimes[t]||""}function getContentFromDataUrl(e){return e.split(/,/)[1]}function isDataUrl(e){return-1!==e.search(/^(data:)/)}function makeDataUrl(e,t){return`data:${t};base64,${e}`}async function fetchAsDataURL(e,t,n){const r=await fetch(e,t);if(404===r.status)throw new Error(`Resource "${r.url}" not found`);const o=await r.blob();return new Promise((e,t)=>{const i=new FileReader;i.onerror=t,i.onloadend=()=>{try{e(n({res:r,result:i.result}))}catch(e){t(e)}},i.readAsDataURL(o)})}const cache={};function getCacheKey(e,t,n){let r=e.replace(/\?.*/,"");return n&&(r=e),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),t?`[${t}]${r}`:r}async function resourceToDataURL(e,t,n){const r=getCacheKey(e,t,n.includeQueryParams);if(null!=cache[r])return cache[r];let o;n.cacheBust&&(e+=(/\?/.test(e)?"&":"?")+(new Date).getTime());try{o=makeDataUrl(await fetchAsDataURL(e,n.fetchRequestInit,({res:e,result:n})=>(t||(t=e.headers.get("Content-Type")||""),getContentFromDataUrl(n))),t)}catch(t){o=n.imagePlaceholder||"";let r=`Failed to fetch resource: ${e}`;t&&(r="string"==typeof t?t:t.message),r&&console.warn(r)}return cache[r]=o,o}async function cloneCanvasElement(e){const t=e.toDataURL();return"data:,"===t?e.cloneNode(!1):createImage(t)}async function cloneVideoElement(e,t){if(e.currentSrc){const t=document.createElement("canvas"),n=t.getContext("2d");t.width=e.clientWidth,t.height=e.clientHeight,null==n||n.drawImage(e,0,0,t.width,t.height);return createImage(t.toDataURL())}const n=e.poster,r=getMimeType(n);return createImage(await resourceToDataURL(n,r,t))}async function cloneIFrameElement(e,t){var n;try{if(null===(n=null==e?void 0:e.contentDocument)||void 0===n?void 0:n.body)return await cloneNode(e.contentDocument.body,t,!0)}catch(e){}return e.cloneNode(!1)}async function cloneSingleNode(e,t){return isInstanceOfElement(e,HTMLCanvasElement)?cloneCanvasElement(e):isInstanceOfElement(e,HTMLVideoElement)?cloneVideoElement(e,t):isInstanceOfElement(e,HTMLIFrameElement)?cloneIFrameElement(e,t):e.cloneNode(isSVGElement(e))}const isSlotElement=e=>null!=e.tagName&&"SLOT"===e.tagName.toUpperCase(),isSVGElement=e=>null!=e.tagName&&"SVG"===e.tagName.toUpperCase();async function cloneChildren(e,t,n){var r,o;if(isSVGElement(t))return t;let i=[];return i=isSlotElement(e)&&e.assignedNodes?toArray(e.assignedNodes()):isInstanceOfElement(e,HTMLIFrameElement)&&(null===(r=e.contentDocument)||void 0===r?void 0:r.body)?toArray(e.contentDocument.body.childNodes):toArray((null!==(o=e.shadowRoot)&&void 0!==o?o:e).childNodes),0===i.length||isInstanceOfElement(e,HTMLVideoElement)||await i.reduce((e,r)=>e.then(()=>cloneNode(r,n)).then(e=>{e&&t.appendChild(e)}),Promise.resolve()),t}function cloneCSSStyle(e,t,n){const r=t.style;if(!r)return;const o=window.getComputedStyle(e);o.cssText?(r.cssText=o.cssText,r.transformOrigin=o.transformOrigin):getStyleProperties(n).forEach(n=>{let i=o.getPropertyValue(n);if("font-size"===n&&i.endsWith("px")){const e=Math.floor(parseFloat(i.substring(0,i.length-2)))-.1;i=`${e}px`}isInstanceOfElement(e,HTMLIFrameElement)&&"display"===n&&"inline"===i&&(i="block"),"d"===n&&t.getAttribute("d")&&(i=`path(${t.getAttribute("d")})`),r.setProperty(n,i,o.getPropertyPriority(n))})}function cloneInputValue(e,t){isInstanceOfElement(e,HTMLTextAreaElement)&&(t.innerHTML=e.value),isInstanceOfElement(e,HTMLInputElement)&&t.setAttribute("value",e.value)}function cloneSelectValue(e,t){if(isInstanceOfElement(e,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(t=>e.value===t.getAttribute("value"));r&&r.setAttribute("selected","")}}function decorate(e,t,n){return isInstanceOfElement(t,Element)&&(cloneCSSStyle(e,t,n),clonePseudoElements(e,t,n),cloneInputValue(e,t),cloneSelectValue(e,t)),t}async function ensureSVGSymbols(e,t){const n=e.querySelectorAll?e.querySelectorAll("use"):[];if(0===n.length)return e;const r={};for(let o=0;o<n.length;o++){const i=n[o].getAttribute("xlink:href");if(i){const n=e.querySelector(i),o=document.querySelector(i);n||!o||r[i]||(r[i]=await cloneNode(o,t,!0))}}const o=Object.values(r);if(o.length){const t="http://www.w3.org/1999/xhtml",n=document.createElementNS(t,"svg");n.setAttribute("xmlns",t),n.style.position="absolute",n.style.width="0",n.style.height="0",n.style.overflow="hidden",n.style.display="none";const r=document.createElementNS(t,"defs");n.appendChild(r);for(let e=0;e<o.length;e++)r.appendChild(o[e]);e.appendChild(n)}return e}async function cloneNode(e,t,n){return n||!t.filter||t.filter(e)?Promise.resolve(e).then(e=>cloneSingleNode(e,t)).then(n=>cloneChildren(e,n,t)).then(n=>decorate(e,n,t)).then(e=>ensureSVGSymbols(e,t)):null}const URL_REGEX=/url\((['"]?)([^'"]+?)\1\)/g,URL_WITH_FORMAT_REGEX=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,FONT_SRC_REGEX=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function toRegex(e){const t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function parseURLs(e){const t=[];return e.replace(URL_REGEX,(e,n,r)=>(t.push(r),e)),t.filter(e=>!isDataUrl(e))}async function embed(e,t,n,r,o){try{const i=n?resolveUrl(t,n):t,s=getMimeType(t);let a;return o||(a=await resourceToDataURL(i,s,r)),e.replace(toRegex(t),`$1${a}$3`)}catch(e){}return e}function filterPreferredFontFormat(e,{preferredFontFormat:t}){return t?e.replace(FONT_SRC_REGEX,e=>{for(;;){const[n,,r]=URL_WITH_FORMAT_REGEX.exec(e)||[];if(!r)return"";if(r===t)return`src: ${n};`}}):e}function shouldEmbed(e){return-1!==e.search(URL_REGEX)}async function embedResources(e,t,n){if(!shouldEmbed(e))return e;const r=filterPreferredFontFormat(e,n);return parseURLs(r).reduce((e,r)=>e.then(e=>embed(e,r,t,n)),Promise.resolve(r))}async function embedProp(e,t,n){var r;const o=null===(r=t.style)||void 0===r?void 0:r.getPropertyValue(e);if(o){const r=await embedResources(o,null,n);return t.style.setProperty(e,r,t.style.getPropertyPriority(e)),!0}return!1}async function embedBackground(e,t){await embedProp("background",e,t)||await embedProp("background-image",e,t),await embedProp("mask",e,t)||await embedProp("-webkit-mask",e,t)||await embedProp("mask-image",e,t)||await embedProp("-webkit-mask-image",e,t)}async function embedImageNode(e,t){const n=isInstanceOfElement(e,HTMLImageElement);if((!n||isDataUrl(e.src))&&(!isInstanceOfElement(e,SVGImageElement)||isDataUrl(e.href.baseVal)))return;const r=n?e.src:e.href.baseVal,o=await resourceToDataURL(r,getMimeType(r),t);await new Promise((r,i)=>{e.onload=r,e.onerror=t.onImageErrorHandler?(...e)=>{try{r(t.onImageErrorHandler(...e))}catch(e){i(e)}}:i;const s=e;s.decode&&(s.decode=r),"lazy"===s.loading&&(s.loading="eager"),n?(e.srcset="",e.src=o):e.href.baseVal=o})}async function embedChildren(e,t){const n=toArray(e.childNodes).map(e=>embedImages(e,t));await Promise.all(n).then(()=>e)}async function embedImages(e,t){isInstanceOfElement(e,Element)&&(await embedBackground(e,t),await embedImageNode(e,t),await embedChildren(e,t))}function applyStyle(e,t){const{style:n}=e;t.backgroundColor&&(n.backgroundColor=t.backgroundColor),t.width&&(n.width=`${t.width}px`),t.height&&(n.height=`${t.height}px`);const r=t.style;return null!=r&&Object.keys(r).forEach(e=>{n[e]=r[e]}),e}const cssFetchCache={};async function fetchCSS(e){let t=cssFetchCache[e];if(null!=t)return t;const n=await fetch(e);return t={url:e,cssText:await n.text()},cssFetchCache[e]=t,t}async function embedFonts(e,t){let n=e.cssText;const r=/url\(["']?([^"')]+)["']?\)/g,o=(n.match(/url\([^)]+\)/g)||[]).map(async o=>{let i=o.replace(r,"$1");return i.startsWith("https://")||(i=new URL(i,e.url).href),fetchAsDataURL(i,t.fetchRequestInit,({result:e})=>(n=n.replace(o,`url(${e})`),[o,e]))});return Promise.all(o).then(()=>n)}function parseCSS(e){if(null==e)return[];const t=[];let n=e.replace(/(\/\*[\s\S]*?\*\/)/gi,"");const r=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const e=r.exec(n);if(null===e)break;t.push(e[0])}n=n.replace(r,"");const o=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,i=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");for(;;){let e=o.exec(n);if(null===e){if(e=i.exec(n),null===e)break;o.lastIndex=i.lastIndex}else i.lastIndex=o.lastIndex;t.push(e[0])}return t}async function getCSSRules(e,t){const n=[],r=[];return e.forEach(n=>{if("cssRules"in n)try{toArray(n.cssRules||[]).forEach((e,o)=>{if(e.type===CSSRule.IMPORT_RULE){let i=o+1;const s=fetchCSS(e.href).then(e=>embedFonts(e,t)).then(e=>parseCSS(e).forEach(e=>{try{n.insertRule(e,e.startsWith("@import")?i+=1:n.cssRules.length)}catch(t){console.error("Error inserting rule from remote css",{rule:e,error:t})}})).catch(e=>{console.error("Error loading remote css",e.toString())});r.push(s)}})}catch(o){const i=e.find(e=>null==e.href)||document.styleSheets[0];null!=n.href&&r.push(fetchCSS(n.href).then(e=>embedFonts(e,t)).then(e=>parseCSS(e).forEach(e=>{i.insertRule(e,i.cssRules.length)})).catch(e=>{console.error("Error loading remote stylesheet",e)})),console.error("Error inlining remote css file",o)}}),Promise.all(r).then(()=>(e.forEach(e=>{if("cssRules"in e)try{toArray(e.cssRules||[]).forEach(e=>{n.push(e)})}catch(t){console.error(`Error while reading CSS rules from ${e.href}`,t)}}),n))}function getWebFontRules(e){return e.filter(e=>e.type===CSSRule.FONT_FACE_RULE).filter(e=>shouldEmbed(e.style.getPropertyValue("src")))}async function parseWebFontRules(e,t){if(null==e.ownerDocument)throw new Error("Provided element is not within a Document");const n=toArray(e.ownerDocument.styleSheets);return getWebFontRules(await getCSSRules(n,t))}function normalizeFontFamily(e){return e.trim().replace(/["']/g,"")}function getUsedFonts(e){const t=new Set;return function e(n){(n.style.fontFamily||getComputedStyle(n).fontFamily).split(",").forEach(e=>{t.add(normalizeFontFamily(e))}),Array.from(n.children).forEach(t=>{t instanceof HTMLElement&&e(t)})}(e),t}async function getWebFontCSS(e,t){const n=await parseWebFontRules(e,t),r=getUsedFonts(e);return(await Promise.all(n.filter(e=>r.has(normalizeFontFamily(e.style.fontFamily))).map(e=>{const n=e.parentStyleSheet?e.parentStyleSheet.href:null;return embedResources(e.cssText,n,t)}))).join("\n")}async function embedWebFonts(e,t){const n=null!=t.fontEmbedCSS?t.fontEmbedCSS:t.skipFonts?null:await getWebFontCSS(e,t);if(n){const t=document.createElement("style"),r=document.createTextNode(n);t.appendChild(r),e.firstChild?e.insertBefore(t,e.firstChild):e.appendChild(t)}}async function toSvg(e,t={}){const{width:n,height:r}=getImageSize(e,t),o=await cloneNode(e,t,!0);await embedWebFonts(o,t),await embedImages(o,t),applyStyle(o,t);return await nodeToDataURL(o,n,r)}async function toCanvas(e,t={}){const{width:n,height:r}=getImageSize(e,t),o=await toSvg(e,t),i=await createImage(o),s=document.createElement("canvas"),a=s.getContext("2d"),c=t.pixelRatio||getPixelRatio(),l=t.canvasWidth||n,h=t.canvasHeight||r;return s.width=l*c,s.height=h*c,t.skipAutoScale||checkCanvasDimensions(s),s.style.width=`${l}`,s.style.height=`${h}`,t.backgroundColor&&(a.fillStyle=t.backgroundColor,a.fillRect(0,0,s.width,s.height)),a.drawImage(i,0,0,s.width,s.height),s}async function toPng(e,t={}){return(await toCanvas(e,t)).toDataURL()}async function toJpeg(e,t={}){return(await toCanvas(e,t)).toDataURL("image/jpeg",t.quality||1)}function errorMessage(e){if(!e)return"Unknown error";if("string"==typeof e)return e;if(e.message)return e.message;if(e instanceof Event)return`Event: ${e.type}`;try{return JSON.stringify(e)}catch{return String(e)}}async function resizeDataUrl(e,t,n,r,o){return new Promise((i,s)=>{const a=new Image;a.onload=()=>{try{const e=a.naturalWidth,c=a.naturalHeight,l=Math.min(t/e,n/c,1),h=Math.max(1,Math.round(e*l)),d=Math.max(1,Math.round(c*l)),_=document.createElement("canvas");_.width=h,_.height=d;const u=_.getContext("2d");if(!u)return void s(new Error("Could not get 2D canvas context"));"jpeg"===r&&(u.fillStyle="#ffffff",u.fillRect(0,0,h,d)),u.drawImage(a,0,0,h,d);const p="jpeg"===r?"image/jpeg":"image/png",f=_.toDataURL(p,o);i({dataUrl:f,width:h,height:d})}catch(e){s(new Error(`Canvas resize failed: ${errorMessage(e)}`))}},a.onerror=e=>s(new Error("Failed to load captured image for resizing"+(e instanceof Event?` (${e.type})`:""))),a.src=e})}async function takeScreenshot(e,t,n,r,o,i){const s=t??"jpeg",a=n??.75,c=r??1024,l=o??1024,h=i??!1;let d;if(e){if(d=document.querySelector(e),!d)return{error:`No element found for selector: ${e}`}}else d=h?document.documentElement:document.body;try{const t=d,n=window.innerWidth,r=window.innerHeight,o={quality:a,pixelRatio:1,cacheBust:!0,skipAutoScale:!0,filter:e=>"hypha-debugger-host"!==e.id&&"hypha-debugger-cursor"!==e.id&&"playwright-highlight-container"!==e.id};let i;e||h||(o.width=n,o.height=r);try{i="jpeg"===s?await toJpeg(t,o):await toPng(t,o)}catch(e){return{error:`Capture failed (html-to-image): ${errorMessage(e)}`}}try{const e=await resizeDataUrl(i,c,l,s,a),t=Math.round(.75*e.dataUrl.length/1024);return{data:e.dataUrl,format:s,width:e.width,height:e.height,size_kb:t}}catch(e){const n=t.getBoundingClientRect(),r=Math.round(.75*i.length/1024);return{data:i,format:s,width:Math.round(n.width),height:Math.round(n.height),size_kb:r,warning:`Resize failed, returning original: ${errorMessage(e)}`}}}catch(e){return{error:`Screenshot failed: ${errorMessage(e)}`}}}function autoReturn(e){const t=e.trim();if(/\breturn\b/.test(t))return t;let n=t.split("\n").map(e=>e.trim()).filter(Boolean);if(1===n.length&&n[0].includes(";")&&(n=n[0].split(";").map(e=>e.trim()).filter(Boolean)),0===n.length)return t;const r=n[n.length-1];return/^(if|for|while|switch|try|class|function |const |let |var |import |export )/.test(r)?t:(n[n.length-1]="return ("+r.replace(/;$/,"")+");",n.join(";\n"))}async function executeScript(e,t){const n=t??1e4;try{let t,r=autoReturn(e);try{t=new Function("return (async () => {"+r+"})()")}catch{t=new Function("return (async () => {"+e+"})()")}const o=await Promise.race([t(),new Promise((e,t)=>setTimeout(()=>t(new Error("Execution timed out")),n))]);let i,s=typeof o;try{void 0===o?(i=null,s="undefined"):o instanceof HTMLElement?(i={tag:o.tagName.toLowerCase(),id:o.id,className:o.className,text:(o.textContent??"").trim().slice(0,500)},s="HTMLElement"):o instanceof NodeList||o instanceof HTMLCollection?(i=Array.from(o).map(e=>({tag:e.tagName?.toLowerCase(),id:e.id,text:(e.textContent??"").trim().slice(0,200)})),s="NodeList"):i=JSON.parse(JSON.stringify(o))}catch{i=String(o),s="string (serialized)"}return{result:i,type:s}}catch(e){return{error:`Execution error: ${e.message??e}`}}}takeScreenshot.__schema__={name:"takeScreenshot",description:"Capture a screenshot of the current viewport, a specific element, or the full page. Returns a base64-encoded data URL, downscaled to fit within max_width × max_height (default 1024px) to keep the payload small enough for AI agents. Defaults to JPEG format at 0.75 quality for reasonable file size.",parameters:{type:"object",properties:{selector:{type:"string",description:"CSS selector of the element to capture. Omit to capture the viewport (or full page if full_page=true)."},format:{type:"string",enum:["png","jpeg"],description:'Image format. Default: "jpeg" (much smaller than PNG). Use "png" for sharp text.'},quality:{type:"number",description:"JPEG quality (0–1). Default: 0.75. Ignored for PNG. Lower = smaller payload."},max_width:{type:"number",description:"Maximum output width in pixels. Default: 1024. Image is scaled down preserving aspect ratio."},max_height:{type:"number",description:"Maximum output height in pixels. Default: 1024. Image is scaled down preserving aspect ratio."},full_page:{type:"boolean",description:"If true, capture the entire scrollable page instead of just the viewport. Default: false."}}}},executeScript.__schema__={name:"executeScript",description:'Execute arbitrary JavaScript code in the page context. Supports async/await. The last expression is auto-returned (no need for explicit "return"). Examples: "document.title", "document.querySelectorAll(\'a\').length", "await fetch(\'/api/data\').then(r => r.json())".',parameters:{type:"object",properties:{code:{type:"string",description:'JavaScript code to execute. The last expression is automatically returned. Examples: "document.title", "document.querySelector(\'h1\').textContent".'},timeout_ms:{type:"number",description:"Maximum execution time in milliseconds. Default: 10000."}},required:["code"]}};const STORAGE_KEY$1="__hypha_debugger_config__";function getScriptUrl(){try{const e=sessionStorage.getItem(STORAGE_KEY$1);if(e){const t=JSON.parse(e);if(t.script_url)return t.script_url}}catch{}return"https://cdn.jsdelivr.net/npm/hypha-debugger/dist/hypha-debugger.min.js"}function injectLoader(e,t){const n=`<script src="${t}"><\/script>`;return e.includes("</body>")?e.replace("</body>",n+"\n</body>"):e.includes("</html>")?e.replace("</html>",n+"\n</html>"):e+"\n"+n}function softReplace(e,t){const n=getScriptUrl();fetch(e,{credentials:"same-origin",cache:"reload"}).then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);if(!(e.headers.get("content-type")??"").includes("text/html"))throw new Error("Not HTML");return e.text()}).then(e=>{const r=injectLoader(e,n);if(document.open(),document.write(r),document.close(),t)try{history.pushState({},"",t)}catch{}}).catch(()=>{t?window.location.href=t:window.location.reload()})}function isSameOrigin(e){try{return new URL(e,location.href).origin===location.origin}catch{return!1}}let _interceptInstalled=!1;function installNavigationInterceptor(){if(_interceptInstalled)return()=>{};_interceptInstalled=!0;const e=e=>{if(e.defaultPrevented||0!==e.button)return;if(e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=null,n=e.target;for(;n;){if("A"===n.tagName){t=n;break}n=n.parentElement}if(!t)return;const r=t.href;if(!r)return;if(t.target&&"_self"!==t.target)return;if(t.hasAttribute("download"))return;if(r.startsWith("javascript:")||r.startsWith("mailto:")||r.startsWith("tel:"))return;try{const e=new URL(r,location.href);if(e.origin===location.origin&&e.pathname===location.pathname&&e.search===location.search&&e.hash!==location.hash)return}catch{return}if(!isSameOrigin(r))return;e.preventDefault();const o=new URL(r,location.href).href;softReplace(o,o)},t=e=>{if(e.defaultPrevented)return;const t=e.target;if("GET"!==(t.method||"GET").toUpperCase())return;const n=t.action||location.href;if(!isSameOrigin(n))return;const r=new FormData(t),o=new URL(n,location.href);for(const[e,t]of r.entries())"string"==typeof t&&o.searchParams.set(e,t);t.target&&"_self"!==t.target||(e.preventDefault(),softReplace(o.href,o.href))},n=()=>{softReplace(location.href)};return document.addEventListener("click",e,!0),document.addEventListener("submit",t,!0),window.addEventListener("popstate",n),()=>{document.removeEventListener("click",e,!0),document.removeEventListener("submit",t,!0),window.removeEventListener("popstate",n),_interceptInstalled=!1}}function navigate(e){try{const t=new URL(e,location.href);return t.origin===location.origin?(setTimeout(()=>softReplace(t.href,t.href),150),{success:!0,message:`Navigating to ${e} (debugger will auto-reconnect)`}):(window.location.href=e,{success:!0,message:`Navigating to ${e} (cross-origin, debugger will disconnect)`})}catch(e){return{success:!1,message:`Navigation failed: ${e.message??e}`}}}function goBack(){try{return window.history.back(),{success:!0,message:"Navigated back (debugger will auto-reconnect via popstate)"}}catch(e){return{success:!1,message:`Back navigation failed: ${e.message??e}`}}}function goForward(){try{return window.history.forward(),{success:!0,message:"Navigated forward (debugger will auto-reconnect via popstate)"}}catch(e){return{success:!1,message:`Forward navigation failed: ${e.message??e}`}}}function reload(){try{return setTimeout(()=>softReplace(location.href),150),{success:!0,message:"Reloading page (debugger will auto-reconnect)"}}catch(e){return{success:!1,message:`Reload failed: ${e.message??e}`}}}function getFiberFromDOM(e){const t=Object.keys(e).find(e=>e.startsWith("__reactFiber$")||e.startsWith("__reactInternalInstance$"));return t?e[t]:null}function getComponentName(e){const{type:t}=e;if(!t)return"(unknown)";if("string"==typeof t)return t;if("function"==typeof t)return t.displayName||t.name||"Anonymous";if("object"==typeof t){if(t.displayName)return t.displayName;if(t.render)return t.render.displayName||t.render.name||"ForwardRef";if(t.type)return getComponentName({type:t.type});if("Symbol(react.memo)"===t.$$typeof?.toString())return`Memo(${getComponentName({type:t.type})})`}return"(unknown)"}function getFiberType(e){return 0===e.tag||11===e.tag||14===e.tag||15===e.tag?"function":1===e.tag?"class":5===e.tag||6===e.tag?"host":"other"}function safeSerialize(e,t=0,n=2){if(t>n)return"[max depth]";if(null==e)return e;if("function"==typeof e)return`[Function: ${e.name||"anonymous"}]`;if("object"!=typeof e)return e;if(e instanceof HTMLElement)return`[${e.tagName.toLowerCase()}#${e.id}]`;if(Array.isArray(e))return e.slice(0,10).map(e=>safeSerialize(e,t+1,n));const r={},o=Object.keys(e).slice(0,20);for(const i of o)if(!i.startsWith("_")&&!i.startsWith("$$"))try{r[i]=safeSerialize(e[i],t+1,n)}catch{r[i]="[unserializable]"}return r}function extractState(e){if(1===e.tag&&e.stateNode)return safeSerialize(e.stateNode.state);if(0===e.tag||11===e.tag||15===e.tag){const t=[];let n=e.memoizedState,r=0;for(;n&&r<20;)null!==n.queue&&void 0!==n.queue&&t.push(safeSerialize(n.memoizedState)),n=n.next,r++;return t.length>0?t:null}return null}function fiberToInfo(e,t,n){const r=getFiberType(e),o="function"===r||"class"===r,i={name:getComponentName(e),type:r,props:o?safeSerialize(e.memoizedProps):{},state:o?extractState(e):null,key:e.key,children:[]};if(t<n){let r=e.child;for(;r;){const e=fiberToInfo(r,t+1,n);e&&("host"!==e.type||e.children.length>0)&&i.children.push(e),r=r.sibling}}return i}function getReactTree(e,t){e=e??"#root";const n=t??5,r=document.querySelector(e);if(!r)return{error:`No element found for selector: ${e}`};const o=getFiberFromDOM(r);if(!o)return{error:`No React fiber found on element "${e}". Is this a React app?`};let i=o;for(;i&&3===i.tag;)i=i.child;if(!i)return{error:"Could not find root React component fiber."};const s=fiberToInfo(i,0,n);return s||{error:"Could not build React component tree."}}function generateSkillMd(e,t){const n=["---","name: web-debugger","description: Remote web page debugger. Inspect DOM, take screenshots, execute JavaScript, fill forms, click elements, and navigate pages — all via HTTP API calls.","compatibility: Requires network access to the Hypha server. Works with any HTTP client (curl, fetch, Python requests).","metadata:",' version: "0.1"',' author: "hypha-debugger"',"---"].join("\n"),r=["","# Web Debugger Skill","","This skill allows you to remotely debug and interact with a web page through HTTP API endpoints.","Pick the approach that fits your task — they can be combined freely.","","## Approaches","","### execute_script — Run Arbitrary JavaScript","","The most versatile function. Use it to read/modify page state, call APIs, query the DOM,","or do anything JavaScript can do. The last expression is auto-returned (no need for `return`).","","```bash","# Read page state","curl -X POST '{SERVICE_URL}/execute_script' \\"," -H 'Content-Type: application/json' -d '{\"code\": \"document.title\"}'","","# Query DOM","curl -X POST '{SERVICE_URL}/execute_script' \\",' -H \'Content-Type: application/json\' -d \'{"code": "document.querySelector(\\"h1\\").textContent"}\'',"","# Call an API","curl -X POST '{SERVICE_URL}/execute_script' \\",' -H \'Content-Type: application/json\' -d \'{"code": "await fetch(\\"/api/data\\").then(r => r.json())"}\'',"","# Modify the page","curl -X POST '{SERVICE_URL}/execute_script' \\",' -H \'Content-Type: application/json\' -d \'{"code": "document.getElementById(\\"name\\").value = \\"Alice\\""}\'',"```","","### get_browser_state + Index-Based Interaction","","Best for UI interaction as a user would — clicking buttons, filling forms, selecting options.","All interactive elements are detected and indexed as `[0]`, `[1]`, `[2]`, etc.","","```bash","# Step 1: See all interactive elements","curl '{SERVICE_URL}/get_browser_state'","","# Step 2: Act by index","curl -X POST '{SERVICE_URL}/click_element_by_index' \\"," -H 'Content-Type: application/json' -d '{\"index\": 2}'","","curl -X POST '{SERVICE_URL}/input_text' \\",' -H \'Content-Type: application/json\' -d \'{"index": 1, "text": "hello world"}\'',"","curl -X POST '{SERVICE_URL}/select_option' \\",' -H \'Content-Type: application/json\' -d \'{"index": 3, "option_text": "French"}\'',"","curl -X POST '{SERVICE_URL}/scroll' \\"," -H 'Content-Type: application/json' -d '{\"direction\": \"down\"}'","","# Step 3: Verify visually","curl '{SERVICE_URL}/take_screenshot'","```","","### get_react_tree — Inspect React Components","","If the page uses React, inspect component names, props, state, and hooks:","```bash","curl '{SERVICE_URL}/get_react_tree'","```","","### CSS Selector-Based Functions","","Use CSS selectors directly when you know the element:","```bash","curl -X POST '{SERVICE_URL}/click_element' \\"," -H 'Content-Type: application/json' -d '{\"selector\": \"button.submit\"}'","","curl -X POST '{SERVICE_URL}/fill_input' \\",' -H \'Content-Type: application/json\' -d \'{"selector": "#email", "value": "user@example.com"}\'',"","curl -X POST '{SERVICE_URL}/query_dom' \\"," -H 'Content-Type: application/json' -d '{\"selector\": \".product-card\"}'","```","","## How to call functions","","All functions are available as HTTP endpoints. Replace `{SERVICE_URL}` with the actual service URL.","","- **GET** for functions with no required parameters","- **POST** with JSON body for functions with parameters",""].join("\n"),o=["## Available Functions",""],i=Object.entries(e).filter(([e,t])=>t?.__schema__&&"get_skill_md"!==e);for(const[e,t]of i){const n=t.__schema__;o.push(`### \`${e}\``),o.push(""),o.push(n.description),o.push("");const r=n.parameters?.properties,i=n.parameters?.required??[];if(r&&Object.keys(r).length>0){o.push("**Parameters:**"),o.push(""),o.push("| Parameter | Type | Required | Description |"),o.push("|-----------|------|----------|-------------|");for(const[e,t]of Object.entries(r)){const n=i.includes(e);let r=t.type??"any";t.enum&&(r=t.enum.map(e=>`"${e}"`).join(" | ")),t.items&&(r=`${t.items.type}[]`),o.push(`| \`${e}\` | ${r} | ${n?"Yes":"No"} | ${t.description??""} |`)}if(o.push(""),i.length>0){const t={};for(const e of i){const n=r[e];t[e]="string"===n?.type?`<${e}>`:"number"===n?.type?"0":`<${e}>`}o.push("**Example:**"),o.push("```bash"),o.push(`curl -X POST '{SERVICE_URL}/${e}' \\`),o.push(" -H 'Content-Type: application/json' \\"),o.push(` -d '${JSON.stringify(t)}'`),o.push("```")}else o.push("**Example:**"),o.push("```bash"),o.push(`curl '{SERVICE_URL}/${e}'`),o.push("```")}else o.push("**Parameters:** None"),o.push(""),o.push("**Example:**"),o.push("```bash"),o.push(`curl '{SERVICE_URL}/${e}'`),o.push("```");o.push("")}const s=["## Tips","","- **`execute_script` is the most versatile** — use it for reading state, calling APIs, DOM queries, or anything not covered by other functions. The last expression is auto-returned.","- **`get_browser_state` is the best way to see what's on the page** — it detects all interactive elements and shows them as indexed items.","- **After each action, call `get_browser_state` again** — element indices change when the DOM updates.","- **Use `take_screenshot`** to visually verify the page state. Call `remove_highlights` first for a clean view.","- **Use `scroll`** with an element index to scroll inside a specific container (e.g. a chat window, sidebar).","- **Use `get_page_info` with `include_logs=true`** to check for JavaScript errors or debug output.","- **Use `get_react_tree`** if the page uses React — it gives you component names, props, and state without needing DevTools.","- **Use `navigate`** to go to other pages — same-origin navigation auto-reconnects the debugger.","- All POST endpoints accept JSON body with the parameter names as keys.",""].join("\n");return[n,r,o.join("\n"),s].join("\n")}function wrapFn(e){const t=e.__schema__,n=t?.parameters?.properties?Object.keys(t.parameters.properties):[];if(0===n.length)return e;const r=n.join(", "),o=n[0],i=new Function("fn","paramNames",`return async function(${r}) {\n // Detect kwargs-as-object: single argument that is a plain object\n if (arguments.length === 1 && ${o} != null && typeof ${o} === "object" && !Array.isArray(${o}) && !(${o} instanceof Date) && ${o}.constructor === Object) {\n var _kw = ${o};\n var _keys = Object.keys(_kw);\n // Empty object {} → call with no args (all defaults)\n if (_keys.length === 0) {\n return fn();\n }\n // Keys match schema params → destructure\n if (paramNames.indexOf(_keys[0]) !== -1) {\n var _args = paramNames.map(function(n) { return _kw[n]; });\n return fn.apply(null, _args);\n }\n }\n return fn(${r});\n }`)(e,n);return t&&(i.__schema__=t),i}navigate.__schema__={name:"navigate",description:"Navigate the browser to a new URL. For same-origin URLs, the debugger auto-reconnects. Cross-origin navigation will disconnect the debugger.",parameters:{type:"object",properties:{url:{type:"string",description:"The URL to navigate to."}},required:["url"]}},goBack.__schema__={name:"goBack",description:"Navigate back in browser history. The debugger auto-reconnects for same-origin pages.",parameters:{type:"object",properties:{}}},goForward.__schema__={name:"goForward",description:"Navigate forward in browser history. The debugger auto-reconnects for same-origin pages.",parameters:{type:"object",properties:{}}},reload.__schema__={name:"reload",description:"Reload the current page. The debugger auto-reconnects after reload using soft page replacement.",parameters:{type:"object",properties:{}}},getReactTree.__schema__={name:"getReactTree",description:"Inspect the React component tree starting from a DOM element. Returns component names, props, state (including hooks), and children hierarchy.",parameters:{type:"object",properties:{selector:{type:"string",description:'CSS selector of the React root element. Default: "#root".'},max_depth:{type:"number",description:"Maximum depth to traverse the component tree. Default: 5."}}}};var domTree=(e={doHighlightElements:!0,focusHighlightIndex:-1,viewportExpansion:0,debugMode:!1,interactiveBlacklist:[],interactiveWhitelist:[],highlightOpacity:.1,highlightLabelOpacity:.5})=>{const{interactiveBlacklist:t,interactiveWhitelist:n,highlightOpacity:r,highlightLabelOpacity:o}=e,{doHighlightElements:i,focusHighlightIndex:s,viewportExpansion:a,debugMode:c}=e;let l=0;const h=new WeakMap;const d={boundingRects:new WeakMap,clientRects:new WeakMap,computedStyles:new WeakMap,clearCache:()=>{d.boundingRects=new WeakMap,d.clientRects=new WeakMap,d.computedStyles=new WeakMap}};function _(e){if(!e)return null;if(d.boundingRects.has(e))return d.boundingRects.get(e);const t=e.getBoundingClientRect();return t&&d.boundingRects.set(e,t),t}function u(e){if(!e)return null;if(d.computedStyles.has(e))return d.computedStyles.get(e);const t=window.getComputedStyle(e);return t&&d.computedStyles.set(e,t),t}const p={},f={current:0},g="playwright-highlight-container";function m(e,t,n=null){if(!e)return t;const i=[];let s=null,a=20,c=16,l=null;try{let h=document.getElementById(g);h||(h=document.createElement("div"),h.id=g,h.style.position="fixed",h.style.pointerEvents="none",h.style.top="0",h.style.left="0",h.style.width="100%",h.style.height="100%",h.style.zIndex="2147483640",h.style.backgroundColor="transparent",document.body.appendChild(h));const d=e.getClientRects();if(!d||0===d.length)return t;const _=["#FF0000","#00FF00","#0000FF","#FFA500","#800080","#008080","#FF69B4","#4B0082","#FF4500","#2E8B57","#DC143C","#4682B4"];let u=_[t%_.length];const p=u+Math.floor(255*r).toString(16).padStart(2,"0");u+=Math.floor(255*o).toString(16).padStart(2,"0");let f={x:0,y:0};if(n){const e=n.getBoundingClientRect();f.x=e.left,f.y=e.top}const m=document.createDocumentFragment();for(const e of d){if(0===e.width||0===e.height)continue;const t=document.createElement("div");t.style.position="fixed",t.style.border=`2px solid ${u}`,t.style.backgroundColor=p,t.style.pointerEvents="none",t.style.boxSizing="border-box";const n=e.top+f.y,r=e.left+f.x;t.style.top=`${n}px`,t.style.left=`${r}px`,t.style.width=`${e.width}px`,t.style.height=`${e.height}px`,m.appendChild(t),i.push({element:t,initialRect:e})}const y=d[0];s=document.createElement("div"),s.className="playwright-highlight-label",s.style.position="fixed",s.style.background=u,s.style.color="white",s.style.padding="1px 4px",s.style.borderRadius="4px",s.style.fontSize=`${Math.min(12,Math.max(8,y.height/2))}px`,s.textContent=t.toString(),a=s.offsetWidth>0?s.offsetWidth:a,c=s.offsetHeight>0?s.offsetHeight:c;const w=y.top+f.y,b=y.left+f.x;let v=w+2,k=b+y.width-a-2;(y.width<a+4||y.height<c+4)&&(v=w-c-2,k=b+y.width-a,k<f.x&&(k=b)),v=Math.max(0,Math.min(v,window.innerHeight-c)),k=Math.max(0,Math.min(k,window.innerWidth-a)),s.style.top=`${v}px`,s.style.left=`${k}px`,m.appendChild(s);const E=(e,t)=>{let n=0;return(...r)=>{const o=performance.now();if(!(o-n<t))return n=o,e(...r)}},x=E(()=>{const t=e.getClientRects();let r={x:0,y:0};if(n){const e=n.getBoundingClientRect();r.x=e.left,r.y=e.top}if(i.forEach((e,n)=>{if(n<t.length){const o=t[n],i=o.top+r.y,s=o.left+r.x;e.element.style.top=`${i}px`,e.element.style.left=`${s}px`,e.element.style.width=`${o.width}px`,e.element.style.height=`${o.height}px`,e.element.style.display=0===o.width||0===o.height?"none":"block"}else e.element.style.display="none"}),t.length<i.length)for(let e=t.length;e<i.length;e++)i[e].element.style.display="none";if(s&&t.length>0){const e=t[0],n=e.top+r.y,o=e.left+r.x;let i=n+2,l=o+e.width-a-2;(e.width<a+4||e.height<c+4)&&(i=n-c-2,l=o+e.width-a,l<r.x&&(l=o)),i=Math.max(0,Math.min(i,window.innerHeight-c)),l=Math.max(0,Math.min(l,window.innerWidth-a)),s.style.top=`${i}px`,s.style.left=`${l}px`,s.style.display="block"}else s&&(s.style.display="none")},16);return window.addEventListener("scroll",x,!0),window.addEventListener("resize",x),l=()=>{window.removeEventListener("scroll",x,!0),window.removeEventListener("resize",x),i.forEach(e=>e.element.remove()),s&&s.remove()},h.appendChild(m),t+1}finally{l&&(window._highlightCleanupFunctions=window._highlightCleanupFunctions||[]).push(l)}}function y(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return null;const t=u(e);if(!t)return null;const n=t.display;if("inline"===n||"inline-block"===n)return null;const r=t.overflowX,o=t.overflowY,i="auto"===r||"scroll"===r,s="auto"===o||"scroll"===o;if(!i&&!s)return null;const a=e.scrollWidth-e.clientWidth,c=e.scrollHeight-e.clientHeight;if(a<4&&c<4)return null;if(!s&&a<4)return null;if(!i&&c<4)return null;const l=e.scrollTop,d=e.scrollLeft,_={top:l,right:e.scrollWidth-e.clientWidth-e.scrollLeft,bottom:e.scrollHeight-e.clientHeight-e.scrollTop,left:d};return function(e,t){e&&e.nodeType===Node.ELEMENT_NODE&&h.set(e,{...h.get(e),...t})}(e,{scrollable:!0,scrollData:_}),_}function w(e){try{if(-1===a){const t=e.parentElement;if(!t)return!1;try{return t.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch(e){const n=window.getComputedStyle(t);return"none"!==n.display&&"hidden"!==n.visibility&&"0"!==n.opacity}}const t=document.createRange();t.selectNodeContents(e);const n=t.getClientRects();if(!n||0===n.length)return!1;let r=!1,o=!1;for(const e of n)if(e.width>0&&e.height>0&&(r=!0,!(e.bottom<-a||e.top>window.innerHeight+a||e.right<-a||e.left>window.innerWidth+a))){o=!0;break}if(!r||!o)return!1;const i=e.parentElement;if(!i)return!1;try{return i.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0})}catch(e){const t=window.getComputedStyle(i);return"none"!==t.display&&"hidden"!==t.visibility&&"0"!==t.opacity}}catch(e){return console.warn("Error checking text node visibility:",e),!1}}function b(e){const t=u(e);return e.offsetWidth>0&&e.offsetHeight>0&&"hidden"!==t?.visibility&&"none"!==t?.display}function v(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;if(t.includes(e))return!1;if(n.includes(e))return!0;const r=e.tagName.toLowerCase(),o=u(e),i=new Set(["pointer","move","text","grab","grabbing","cell","copy","alias","all-scroll","col-resize","context-menu","crosshair","e-resize","ew-resize","help","n-resize","ne-resize","nesw-resize","ns-resize","nw-resize","nwse-resize","row-resize","s-resize","se-resize","sw-resize","vertical-text","w-resize","zoom-in","zoom-out"]),s=new Set(["not-allowed","no-drop","wait","progress","initial","inherit"]);let a=function(e){return"html"!==e.tagName.toLowerCase()&&!(!o?.cursor||!i.has(o.cursor))}(e);if(a)return!0;const c=new Set(["a","button","input","select","textarea","details","summary","label","option","optgroup","fieldset","legend"]),l=new Set(["disabled","readonly"]);if(c.has(r)){if(o?.cursor&&s.has(o.cursor))return!1;for(const t of l)if(e.hasAttribute(t)||"true"===e.getAttribute(t)||""===e.getAttribute(t))return!1;return!e.disabled&&(!e.readOnly&&!e.inert)}const h=e.getAttribute("role"),d=e.getAttribute("aria-role");if("true"===e.getAttribute("contenteditable")||e.isContentEditable)return!0;if(e.classList&&(e.classList.contains("button")||e.classList.contains("dropdown-toggle")||e.getAttribute("data-index")||"dropdown"===e.getAttribute("data-toggle")||"true"===e.getAttribute("aria-haspopup")))return!0;const _=new Set(["button","menu","menubar","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);if(c.has(r)||h&&_.has(h)||d&&_.has(d))return!0;try{if("function"==typeof getEventListeners){const t=getEventListeners(e),n=["click","mousedown","mouseup","dblclick"];for(const e of n)if(t[e]&&t[e].length>0)return!0}const t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if("function"==typeof t){const n=t(e),r=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const e of r)for(const t of n)if(t.type===e)return!0}const n=["onclick","onmousedown","onmouseup","ondblclick"];for(const t of n)if(e.hasAttribute(t)||"function"==typeof e[t])return!0}catch(e){}return!!y(e)}function k(e){if(-1===a)return!0;const t=function(e){if(!e)return null;if(d.clientRects.has(e))return d.clientRects.get(e);const t=e.getClientRects();return t&&d.clientRects.set(e,t),t}(e);if(!t||0===t.length)return!1;let n=!1;for(const e of t)if(e.width>0&&e.height>0&&!(e.bottom<-a||e.top>window.innerHeight+a||e.right<-a||e.left>window.innerWidth+a)){n=!0;break}if(!n)return!1;if(e.ownerDocument!==window.document)return!0;let r=Array.from(t).find(e=>e.width>0&&e.height>0);if(!r)return!1;const o=e.getRootNode();if(o instanceof ShadowRoot){const t=r.left+r.width/2,n=r.top+r.height/2;try{const r=o.elementFromPoint(t,n);if(!r)return!1;let i=r;for(;i&&i!==o;){if(i===e)return!0;i=i.parentElement}return!1}catch(e){return!0}}return[{x:r.left+r.width/2,y:r.top+r.height/2},{x:r.left+5,y:r.top+5},{x:r.right-5,y:r.bottom-5}].some(({x:t,y:n})=>{try{const r=document.elementFromPoint(t,n);if(!r)return!1;let o=r;for(;o&&o!==document.documentElement;){if(o===e)return!0;o=o.parentElement}return!1}catch(e){return!0}})}const E=new Set(["a","button","input","select","textarea","summary","details","label","option"]),x=new Set(["button","link","menuitem","menuitemradio","menuitemcheckbox","radio","checkbox","tab","switch","slider","spinbutton","combobox","searchbox","textbox","listbox","option","scrollbar"]);function S(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;const t=e.tagName.toLowerCase(),n=e.getAttribute("role");if("iframe"===t)return!0;if(E.has(t))return!0;if(n&&x.has(n))return!0;if(e.isContentEditable||"true"===e.getAttribute("contenteditable"))return!0;if(e.hasAttribute("data-testid")||e.hasAttribute("data-cy")||e.hasAttribute("data-test"))return!0;if(e.hasAttribute("onclick")||"function"==typeof e.onclick)return!0;try{const t=e?.ownerDocument?.defaultView?.getEventListenersForNode||window.getEventListenersForNode;if("function"==typeof t){const n=t(e),r=["click","mousedown","mouseup","keydown","keyup","submit","change","input","focus","blur"];for(const e of r)for(const t of n)if(t.type===e)return!0}if(["onmousedown","onmouseup","onkeydown","onkeyup","onsubmit","onchange","oninput","onfocus","onblur"].some(t=>e.hasAttribute(t)))return!0}catch(e){}return!!function(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;if(!b(e))return!1;const t=e.hasAttribute("role")||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||"function"==typeof e.onclick,n=/\b(btn|clickable|menu|item|entry|link)\b/i.test(e.className||""),r=Boolean(e.closest('button,a,[role="button"],.menu,.dropdown,.list,.toolbar')),o=[...e.children].some(b),i=e.parentElement&&e.parentElement.isSameNode(document.body);return(v(e)||t||n)&&o&&r&&!i}(e)}function T(e,t,n,r){if(!e.isInteractive)return!1;let o=!1;return o=!r||!!S(t),!(!o||(e.isInViewport=function(e,t){if(-1===t)return!0;const n=e.getClientRects();if(!n||0===n.length){const n=_(e);return!(!n||0===n.width||0===n.height||n.bottom<-t||n.top>window.innerHeight+t||n.right<-t||n.left>window.innerWidth+t)}for(const e of n)if(0!==e.width&&0!==e.height&&!(e.bottom<-t||e.top>window.innerHeight+t||e.right<-t||e.left>window.innerWidth+t))return!0;return!1}(t,a),!e.isInViewport&&-1!==a||(e.highlightIndex=l++,!i)))&&(s>=0?s===e.highlightIndex&&m(t,e.highlightIndex,n):m(t,e.highlightIndex,n),!0)}const C=function e(t,n=null,r=!1){if(!t||t.id===g||t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE)return null;if(!t||t.id===g)return null;if("true"===t.dataset?.browserUseIgnore||"true"===t.dataset?.pageAgentIgnore)return null;if(t.getAttribute&&"true"===t.getAttribute("aria-hidden"))return null;if(t===document.body){const r={tagName:"body",attributes:{},xpath:"/body",children:[]};for(const o of t.childNodes){const t=e(o,n,!1);t&&r.children.push(t)}const o=""+f.current++;return p[o]=r,o}if(t.nodeType!==Node.ELEMENT_NODE&&t.nodeType!==Node.TEXT_NODE)return null;if(t.nodeType===Node.TEXT_NODE){const e=t.textContent?.trim();if(!e)return null;const n=t.parentElement;if(!n||"script"===n.tagName.toLowerCase())return null;const r=""+f.current++;return p[r]={type:"TEXT_NODE",text:e,isVisible:w(t)},r}if(t.nodeType===Node.ELEMENT_NODE&&!function(e){if(!e||!e.tagName)return!1;const t=new Set(["body","div","main","article","section","nav","header","footer"]),n=e.tagName.toLowerCase();return!!t.has(n)||!new Set(["svg","script","style","link","meta","noscript","template"]).has(n)}(t))return null;if(-1!==a&&!t.shadowRoot){const e=_(t),n=u(t),r=n&&("fixed"===n.position||"sticky"===n.position),o=t.offsetWidth>0||t.offsetHeight>0;if(!e||!r&&!o&&(e.bottom<-a||e.top>window.innerHeight+a||e.right<-a||e.left>window.innerWidth+a))return null}const o={tagName:t.tagName.toLowerCase(),attributes:{},children:[]};if(function(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return!1;const t=e.tagName.toLowerCase();return!!new Set(["a","button","input","select","textarea","details","summary","label"]).has(t)||(e.hasAttribute("onclick")||e.hasAttribute("role")||e.hasAttribute("tabindex")||e.hasAttribute("aria-")||e.hasAttribute("data-action")||"true"===e.getAttribute("contenteditable"))}(t)||"iframe"===t.tagName.toLowerCase()||"body"===t.tagName.toLowerCase()){const e=t.getAttributeNames?.()||[];for(const n of e){const e=t.getAttribute(n);o.attributes[n]=e}"input"!==t.tagName.toLowerCase()||"checkbox"!==t.type&&"radio"!==t.type||(o.attributes.checked=t.checked?"true":"false")}let i=!1;if(t.nodeType===Node.ELEMENT_NODE&&(o.isVisible=b(t),o.isVisible)){o.isTopElement=k(t);const e=t.getAttribute("role"),s="menu"===e||"menubar"===e||"listbox"===e;if((o.isTopElement||s)&&(o.isInteractive=v(t),i=T(o,t,n,r),o.ref=t,o.isInteractive&&0===Object.keys(o.attributes).length)){const e=t.getAttributeNames?.()||[];for(const n of e){const e=t.getAttribute(n);o.attributes[n]=e}}}if(t.tagName){const s=t.tagName.toLowerCase();if("iframe"===s)try{const n=t.contentDocument||t.contentWindow?.document;if(n)for(const r of n.childNodes){const n=e(r,t,!1);n&&o.children.push(n)}}catch(e){console.warn("Unable to access iframe:",e)}else if(t.isContentEditable||"true"===t.getAttribute("contenteditable")||"tinymce"===t.id||t.classList.contains("mce-content-body")||"body"===s&&t.getAttribute("data-id")?.startsWith("mce_"))for(const r of t.childNodes){const t=e(r,n,i);t&&o.children.push(t)}else{if(t.shadowRoot){o.shadowRoot=!0;for(const r of t.shadowRoot.childNodes){const t=e(r,n,i);t&&o.children.push(t)}}for(const s of t.childNodes){const t=e(s,n,i||r);t&&o.children.push(t)}}}if("a"===o.tagName&&0===o.children.length&&!o.attributes.href){const e=_(t);if(!(e&&e.width>0&&e.height>0||t.offsetWidth>0||t.offsetHeight>0))return null}o.extra=h.get(t)||null;const s=""+f.current++;return p[s]=o,s}(document.body);return d.clearCache(),{rootId:C,map:p}};const DEFAULT_VIEWPORT_EXPANSION=-1;function resolveViewportExpansion(e){return e??DEFAULT_VIEWPORT_EXPANSION}const newElementsCache=new WeakMap;function getFlatTree(e){const t=resolveViewportExpansion(e.viewportExpansion),n=[];for(const t of e.interactiveBlacklist||[])"function"==typeof t?n.push(t()):n.push(t);const r=[];for(const t of e.interactiveWhitelist||[])"function"==typeof t?r.push(t()):r.push(t);const o=domTree({doHighlightElements:!0,debugMode:!0,focusHighlightIndex:-1,viewportExpansion:t,interactiveBlacklist:n,interactiveWhitelist:r,highlightOpacity:e.highlightOpacity??0,highlightLabelOpacity:e.highlightLabelOpacity??.1});for(const e in o.map){const t=o.map[e];if(t.isInteractive&&t.ref){const e=t.ref;newElementsCache.has(e)||(newElementsCache.set(e,window.location.href),t.isNew=!0)}}return o}const globRegexCache=new Map;function globToRegex(e){let t=globRegexCache.get(e);if(!t){const n=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");t=new RegExp(`^${n.replace(/\*/g,".*")}$`),globRegexCache.set(e,t)}return t}function matchAttributes(e,t){const n={};for(const r of t)if(r.includes("*")){const t=globToRegex(r);for(const r of Object.keys(e))t.test(r)&&e[r].trim()&&(n[r]=e[r].trim())}else{const t=e[r];t&&t.trim()&&(n[r]=t.trim())}return n}function flatTreeToString(e,t){const n=[...t||[],"title","type","checked","name","role","value","placeholder","data-date-format","alt","aria-label","aria-expanded","data-state","aria-checked","id","for","target","aria-haspopup","aria-controls","aria-owns","contenteditable"],r=t=>{const n=e.map[t];if(!n)return null;if("TEXT_NODE"===n.type){const e=n;return{type:"text",text:e.text,isVisible:e.isVisible,parent:null,children:[]}}{const e=n,t=[];if(e.children)for(const n of e.children){const e=r(n);e&&t.push(e)}return{type:"element",tagName:e.tagName,attributes:e.attributes??{},isVisible:e.isVisible??!1,isInteractive:e.isInteractive??!1,isTopElement:e.isTopElement??!1,isNew:e.isNew??!1,highlightIndex:e.highlightIndex,parent:null,children:t,extra:e.extra??{}}}},o=(e,t=null)=>{e.parent=t;for(const t of e.children)o(t,e)},i=r(e.rootId);if(!i)return"";o(i);const s=(e,t,r)=>{let o=t;const i="\t".repeat(t);if("element"===e.type){if(void 0!==e.highlightIndex){o+=1;const t=getAllTextTillNextClickableElement(e);let s="";if(n.length>0&&e.attributes){const r=matchAttributes(e.attributes,n),o=Object.keys(r);if(o.length>1){const e=new Set,t={};for(const n of o){const o=r[n];o.length>5&&(o in t?e.add(n):t[o]=n)}for(const t of e)delete r[t]}r.role===e.tagName&&delete r.role;const i=["aria-label","placeholder","title"];for(const e of i)r[e]&&r[e].toLowerCase().trim()===t.toLowerCase().trim()&&delete r[e];Object.keys(r).length>0&&(s=Object.entries(r).map(([e,t])=>`${e}=${((e,t)=>e.length>t?e.substring(0,t)+"...":e)(t,20)}`).join(" "))}let a=`${i}${e.isNew?`*[${e.highlightIndex}]`:`[${e.highlightIndex}]`}<${e.tagName??""}`;if(s&&(a+=` ${s}`),e.extra&&e.extra.scrollable){let t="";e.extra.scrollData?.left&&(t+=`left=${e.extra.scrollData.left}, `),e.extra.scrollData?.top&&(t+=`top=${e.extra.scrollData.top}, `),e.extra.scrollData?.right&&(t+=`right=${e.extra.scrollData.right}, `),e.extra.scrollData?.bottom&&(t+=`bottom=${e.extra.scrollData.bottom}`),a+=` data-scrollable="${t}"`}if(t){s||(a+=" "),a+=`>${t.trim()}`}else s||(a+=" ");a+=" />",r.push(a)}for(const t of e.children)s(t,o,r)}else if("text"===e.type){if((e=>{let t=e.parent;for(;t;){if("element"===t.type&&void 0!==t.highlightIndex)return!0;t=t.parent}return!1})(e))return;e.parent&&"element"===e.parent.type&&e.parent.isVisible&&e.parent.isTopElement&&r.push(`${i}${e.text??""}`)}},a=[];return s(i,0,a),a.join("\n")}const getAllTextTillNextClickableElement=(e,t=-1)=>{const n=[],r=(o,i)=>{if(!(-1!==t&&i>t||"element"===o.type&&o!==e&&void 0!==o.highlightIndex))if("text"===o.type&&o.text)n.push(o.text);else if("element"===o.type)for(const e of o.children)r(e,i+1)};return r(e,0),n.join("\n").trim()};function getSelectorMap(e){const t=new Map,n=Object.keys(e.map);for(const r of n){const n=e.map[r];n.isInteractive&&"number"==typeof n.highlightIndex&&t.set(n.highlightIndex,n)}return t}function getElementTextMap(e){const t=e.split("\n").map(e=>e.trim()).filter(e=>e.length>0),n=new Map;for(const e of t){const t=/^\[(\d+)\]<[^>]+>([^<]*)/.exec(e);if(t){const r=parseInt(t[1],10);n.set(r,e)}}return n}function cleanUpHighlights(){const e=window._highlightCleanupFunctions||[];for(const t of e)"function"==typeof t&&t();window._highlightCleanupFunctions=[]}async function waitFor(e){await new Promise(t=>setTimeout(t,1e3*e))}function getElementByIndex(e,t){const n=e.get(t);if(!n)throw new Error(`No interactive element found at index ${t}`);const r=n.ref;if(!r)throw new Error(`Element at index ${t} does not have a reference`);if(!(r instanceof HTMLElement))throw new Error(`Element at index ${t} is not an HTMLElement`);return r}let lastClickedElement=null;function blurLastClickedElement(){lastClickedElement&&(lastClickedElement.blur(),lastClickedElement.dispatchEvent(new MouseEvent("mouseout",{bubbles:!0,cancelable:!0})),lastClickedElement=null)}async function scrollIntoViewIfNeeded(e){const t=e.getBoundingClientRect();t.top>=0&&t.bottom<=window.innerHeight&&t.left>=0&&t.right<=window.innerWidth||(e.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"}),await waitFor(.4))}async function movePointerToElement(e){const t=e.getBoundingClientRect(),n=t.left+t.width/2,r=t.top+t.height/2;window.dispatchEvent(new CustomEvent("HyphaDebugger::MovePointerTo",{detail:{x:n,y:r}})),await waitFor(.3)}async function clickElement(e){blurLastClickedElement(),lastClickedElement=e,await scrollIntoViewIfNeeded(e),await movePointerToElement(e),window.dispatchEvent(new CustomEvent("HyphaDebugger::ClickPointer")),await waitFor(.05),e.dispatchEvent(new MouseEvent("mouseenter",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("mouseover",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("mousedown",{bubbles:!0,cancelable:!0})),e.focus(),e.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0})),e.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),await waitFor(.2)}let _nativeInputValueSetter=null,_nativeTextAreaValueSetter=null;function getNativeInputValueSetter(){return _nativeInputValueSetter||(_nativeInputValueSetter=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value").set),_nativeInputValueSetter}function getNativeTextAreaValueSetter(){return _nativeTextAreaValueSetter||(_nativeTextAreaValueSetter=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value").set),_nativeTextAreaValueSetter}async function inputTextElement(e,t){const n=e.isContentEditable;if(!(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||n))throw new Error("Element is not an input, textarea, or contenteditable");await clickElement(e),n?(e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"deleteContent"}))&&(e.innerText="",e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"deleteContent"}))),e.dispatchEvent(new InputEvent("beforeinput",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t}))&&(e.innerText=t,e.dispatchEvent(new InputEvent("input",{bubbles:!0,inputType:"insertText",data:t}))),e.dispatchEvent(new Event("change",{bubbles:!0})),e.blur()):e instanceof HTMLTextAreaElement?getNativeTextAreaValueSetter().call(e,t):getNativeInputValueSetter().call(e,t),n||e.dispatchEvent(new Event("input",{bubbles:!0})),await waitFor(.1),blurLastClickedElement()}async function selectOptionElement(e,t){if(!(e instanceof HTMLSelectElement))throw new Error("Element is not a select element");await scrollIntoViewIfNeeded(e);const n=e.getBoundingClientRect();window.dispatchEvent(new CustomEvent("HyphaDebugger::MovePointerTo",{detail:{x:n.left+n.width/2,y:n.top+n.height/2}})),await waitFor(.3),window.dispatchEvent(new CustomEvent("HyphaDebugger::ClickPointer"));const r=Array.from(e.options).find(e=>e.textContent?.trim()===t.trim());if(!r)throw new Error(`Option with text "${t}" not found in select element`);e.value=r.value,e.dispatchEvent(new Event("change",{bubbles:!0})),await waitFor(.1)}async function scrollVertically(e,t,n){if(n){let e=n,r=!1,o=null,i=0,s=0;const a=t;for(;e&&s<10;){const t=window.getComputedStyle(e),n=/(auto|scroll|overlay)/.test(t.overflowY),c=e.scrollHeight>e.clientHeight;if(n&&c){const t=e.scrollTop,n=e.scrollHeight-e.clientHeight;let s=a/3;s=s>0?Math.min(s,n-t):Math.max(s,-t),e.scrollTop=t+s;const c=e.scrollTop-t;if(Math.abs(c)>.5){r=!0,o=e,i=c;break}}if(e===document.body||e===document.documentElement)break;e=e.parentElement,s++}return r?`Scrolled container (${o?.tagName}) by ${i}px`:`No scrollable container found for element (${n.tagName})`}const r=t,o=e=>e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowY)&&e.scrollHeight>e.clientHeight&&(e=>e.clientHeight>=.5*window.innerHeight)(e);let i=document.activeElement;for(;i&&!o(i)&&i!==document.body;)i=i.parentElement;if(i=o(i)?i:Array.from(document.querySelectorAll("*")).find(o)||document.scrollingElement||document.documentElement,i===document.scrollingElement||i===document.documentElement||i===document.body){const e=window.scrollY;window.scrollBy(0,r);const t=window.scrollY,n=t-e;if(Math.abs(n)<1)return r>0?"Already at the bottom of the page.":"Already at the top of the page.";const o=document.documentElement.scrollHeight-window.innerHeight;return r>0&&t>=o-1?`Scrolled page by ${n}px. Reached the bottom.`:r<0&&t<=1?`Scrolled page by ${n}px. Reached the top.`:`Scrolled page by ${n}px.`}{const e=i.scrollTop,t=i.scrollHeight-i.clientHeight;i.scrollBy({top:r,behavior:"smooth"}),await waitFor(.1);const n=i.scrollTop,o=n-e;if(Math.abs(o)<1)return r>0?`Already at the bottom of container (${i.tagName}).`:`Already at the top of container (${i.tagName}).`;const s=r<0&&n<=1;return r>0&&n>=t-1?`Scrolled container (${i.tagName}) by ${o}px. Reached the bottom.`:s?`Scrolled container (${i.tagName}) by ${o}px. Reached the top.`:`Scrolled container (${i.tagName}) by ${o}px.`}}async function scrollHorizontally(e,t,n){if(n){let r=n,o=!1,i=null,s=0,a=0;const c=e?t:-t;for(;r&&a<10;){const e=window.getComputedStyle(r),t=/(auto|scroll|overlay)/.test(e.overflowX),n=r.scrollWidth>r.clientWidth;if(t&&n){const e=r.scrollLeft,t=r.scrollWidth-r.clientWidth;let n=c/3;n=n>0?Math.min(n,t-e):Math.max(n,-e),r.scrollLeft=e+n;const a=r.scrollLeft-e;if(Math.abs(a)>.5){o=!0,i=r,s=a;break}}if(r===document.body||r===document.documentElement)break;r=r.parentElement,a++}return o?`Scrolled container (${i?.tagName}) horizontally by ${s}px`:`No horizontally scrollable container found for element (${n.tagName})`}const r=e?t:-t,o=e=>e&&/(auto|scroll|overlay)/.test(getComputedStyle(e).overflowX)&&e.scrollWidth>e.clientWidth&&(e=>e.clientWidth>=.5*window.innerWidth)(e);let i=document.activeElement;for(;i&&!o(i)&&i!==document.body;)i=i.parentElement;if(i=o(i)?i:Array.from(document.querySelectorAll("*")).find(o)||document.scrollingElement||document.documentElement,i===document.scrollingElement||i===document.documentElement||i===document.body){const e=window.scrollX,t=document.documentElement.scrollWidth-window.innerWidth;window.scrollBy(r,0);const n=window.scrollX,o=n-e;if(Math.abs(o)<1)return r>0?"Already at the right edge of the page.":"Already at the left edge of the page.";return r>0&&n>=t-1?`Scrolled page by ${o}px. Reached the right edge.`:r<0&&n<=1?`Scrolled page by ${o}px. Reached the left edge.`:`Scrolled page horizontally by ${o}px.`}{const e=i.scrollLeft,t=i.scrollWidth-i.clientWidth;i.scrollBy({left:r,behavior:"smooth"}),await waitFor(.1);const n=i.scrollLeft,o=n-e;if(Math.abs(o)<1)return r>0?`Already at the right edge of container (${i.tagName}).`:`Already at the left edge of container (${i.tagName}).`;const s=r<0&&n<=1;return r>0&&n>=t-1?`Scrolled container (${i.tagName}) by ${o}px. Reached the right edge.`:s?`Scrolled container (${i.tagName}) by ${o}px. Reached the left edge.`:`Scrolled container (${i.tagName}) horizontally by ${o}px.`}}function getPageScrollInfo(){const e=window.innerWidth,t=window.innerHeight,n=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth||0),r=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight||0),o=window.scrollX||window.pageXOffset||document.documentElement.scrollLeft||0,i=window.scrollY||window.pageYOffset||document.documentElement.scrollTop||0,s=Math.max(0,r-(window.innerHeight+i)),a=Math.max(0,n-(window.innerWidth+o));return{viewport_width:e,viewport_height:t,page_width:n,page_height:r,scroll_x:o,scroll_y:i,pixels_above:i,pixels_below:s,pages_above:t>0?i/t:0,pages_below:t>0?s/t:0,total_pages:t>0?r/t:0,current_page_position:i/Math.max(1,r-t),pixels_left:o,pixels_right:a}}class PageController{constructor(e={}){this.flatTree=null,this.selectorMap=new Map,this.elementTextMap=new Map,this.simplifiedHTML="",this.isIndexed=!1,this.config=e}async getBrowserState(){const e=window.location.href,t=document.title,n=getPageScrollInfo(),r=resolveViewportExpansion(this.config.viewportExpansion);await this.updateTree();const o=this.simplifiedHTML;return{url:e,title:t,header:`${`Current Page: [${t}](${e})`}\n${`Page info: ${n.viewport_width}x${n.viewport_height}px viewport, ${n.page_width}x${n.page_height}px total, ${n.pages_above.toFixed(1)} pages above, ${n.pages_below.toFixed(1)} pages below, at ${(100*n.current_page_position).toFixed(0)}%`}\n\n${-1===r?"Interactive elements (full page):":"Interactive elements (viewport):"}\n\n${n.pixels_above>4&&-1!==r?`... ${n.pixels_above} pixels above - scroll to see more ...`:"[Start of page]"}`,content:o,footer:n.pixels_below>4&&-1!==r?`... ${n.pixels_below} pixels below - scroll to see more ...`:"[End of page]",element_count:this.selectorMap.size}}async updateTree(){return cleanUpHighlights(),this.flatTree=getFlatTree(this.config),this.simplifiedHTML=flatTreeToString(this.flatTree,this.config.includeAttributes),this.selectorMap.clear(),this.selectorMap=getSelectorMap(this.flatTree),this.elementTextMap.clear(),this.elementTextMap=getElementTextMap(this.simplifiedHTML),this.isIndexed=!0,this.simplifiedHTML}async cleanUpHighlights(){cleanUpHighlights()}assertIndexed(){if(!this.isIndexed)throw new Error("DOM tree not indexed yet. Call get_browser_state first.")}cleanUpAfterAction(){cleanUpHighlights()}async clickElement(e){try{this.assertIndexed();const t=getElementByIndex(this.selectorMap,e),n=this.elementTextMap.get(e);return this.cleanUpAfterAction(),await clickElement(t),t instanceof HTMLAnchorElement&&"_blank"===t.target?{success:!0,message:`Clicked element (${n??e}). Link opened in a new tab.`}:{success:!0,message:`Clicked element (${n??e}).`}}catch(e){return{success:!1,message:`Failed to click element: ${e}`}}}async inputText(e,t){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return this.cleanUpAfterAction(),await inputTextElement(n,t),{success:!0,message:`Input text "${t}" into element (${r??e}).`}}catch(e){return{success:!1,message:`Failed to input text: ${e}`}}}async selectOption(e,t){try{this.assertIndexed();const n=getElementByIndex(this.selectorMap,e),r=this.elementTextMap.get(e);return this.cleanUpAfterAction(),await selectOptionElement(n,t),{success:!0,message:`Selected option "${t}" in element (${r??e}).`}}catch(e){return{success:!1,message:`Failed to select option: ${e}`}}}async scroll(e){try{this.assertIndexed(),this.cleanUpAfterAction();const{direction:t,amount:n,index:r}=e,o=void 0!==r?getElementByIndex(this.selectorMap,r):null;let i;if("left"===t||"right"===t){const e=n??.8*window.innerWidth;i=await scrollHorizontally("right"===t,e,o)}else{const e=n??.8*window.innerHeight,r="down"===t?e:-e;i=await scrollVertically("down"===t,r,o)}return{success:!0,message:i}}catch(e){return{success:!1,message:`Failed to scroll: ${e}`}}}dispose(){cleanUpHighlights(),this.flatTree=null,this.selectorMap.clear(),this.elementTextMap.clear(),this.simplifiedHTML="",this.isIndexed=!1}}let controller=null;function getController(){return controller||(controller=new PageController({viewportExpansion:-1,highlightOpacity:.1,highlightLabelOpacity:.5})),controller}async function getBrowserState(e){const t=getController();return void 0!==e&&(t.config.viewportExpansion=e?0:-1),t.getBrowserState()}async function clickElementByIndex(e){return getController().clickElement(e)}async function inputText(e,t){return getController().inputText(e,t)}async function selectOption(e,t){return getController().selectOption(e,t)}async function scroll(e,t,n){return getController().scroll({direction:e,amount:t,index:n})}async function removeHighlights(){return getController().cleanUpHighlights(),{success:!0,message:"Highlights removed."}}function disposeController(){controller&&(controller.dispose(),controller=null)}function randomHex(e=8){const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}getBrowserState.__schema__={name:"getBrowserState",description:"Get the current page state with all interactive elements indexed as [0], [1], [2], etc. Returns a simplified HTML representation optimized for LLM consumption. Interactive elements (buttons, links, inputs, scrollable areas) are detected via smart heuristics (CSS cursor, ARIA roles, event listeners, tag names). Use the returned indices with click_element_by_index, input_text, select_option, or scroll. Call this first to understand the page before performing any actions.",parameters:{type:"object",properties:{viewport_only:{type:"boolean",description:"If true, only return elements visible in the current viewport. Default: false (full page)."}}}},clickElementByIndex.__schema__={name:"clickElementByIndex",description:"Click an interactive element by its numeric index from get_browser_state output. Simulates a full mouse event sequence (hover, mousedown, focus, mouseup, click) to trigger all event listeners including React/Vue handlers.",parameters:{type:"object",properties:{index:{type:"number",description:"The element index from get_browser_state (e.g. 0 for [0], 5 for [5])."}},required:["index"]}},inputText.__schema__={name:"inputText",description:"Type text into an input, textarea, or contenteditable element by its index. Replaces existing content. Works with React controlled components, contenteditable editors (LinkedIn, Quill), and native inputs.",parameters:{type:"object",properties:{index:{type:"number",description:"The element index from get_browser_state."},text:{type:"string",description:"The text to type into the element."}},required:["index","text"]}},selectOption.__schema__={name:"selectOption",description:"Select a dropdown option in a <select> element by its index and the visible option text.",parameters:{type:"object",properties:{index:{type:"number",description:"The <select> element index from get_browser_state."},option_text:{type:"string",description:"The visible text of the option to select (case-sensitive, trimmed)."}},required:["index","option_text"]}},scroll.__schema__={name:"scroll",description:"Scroll the page or a specific scrollable container. If index is provided, scrolls the nearest scrollable ancestor of that element. Otherwise scrolls the page or the largest scrollable container.",parameters:{type:"object",properties:{direction:{type:"string",enum:["up","down","left","right"],description:"Scroll direction."},amount:{type:"number",description:"Scroll amount in pixels. Default: ~80% of viewport height (vertical) or width (horizontal)."},index:{type:"number",description:"Optional element index. If provided, scrolls the nearest scrollable ancestor of this element."}},required:["direction"]}},removeHighlights.__schema__={name:"removeHighlights",description:"Remove all visual element index labels/highlights from the page. Useful after taking a screenshot if you want a clean view.",parameters:{type:"object",properties:{}}};const STORAGE_KEY="__hypha_debugger_config__";class HyphaDebugger{constructor(e){this.overlay=null,this.cursor=null,this.server=null,this.serviceInfo=null,this.boundBeforeUnload=null,this.cleanupInterceptor=null;const t=e.require_token??!1;let n=e.service_id??"web-debugger";e.service_id||(n=`web-debugger-${randomHex(16)}`);const r=e.visibility??(t?"protected":"unlisted");this.config={server_url:e.server_url,workspace:e.workspace??"",token:e.token??"",service_id:n,service_name:e.service_name??"Web Debugger",show_ui:e.show_ui??!0,visibility:r,require_token:t}}async start(){installConsoleCapture();const e=window;if(e.__HYPHA_DEBUGGER__?.instance)return console.warn("[hypha-debugger] Already running, returning existing session."),e.__HYPHA_DEBUGGER__.session;this.config.show_ui&&(this.overlay=new DebugOverlay,this.overlay.setStatus("disconnected"),this.overlay.setInfo({Status:"Connecting..."}),this.cursor=new AICursor);try{"function"!=typeof Promise.prototype.finally&&(Promise.prototype.finally=function(e){return this.then(t=>Promise.resolve(e()).then(()=>t),t=>Promise.resolve(e()).then(()=>{throw t}))});const t=this.getConnectToServer(),n={server_url:this.config.server_url};this.config.workspace&&(n.workspace=this.config.workspace),this.config.token&&(n.token=this.config.token);try{this.server=await t(n)}catch(e){if(!this.config.workspace)throw e;console.warn(`[hypha-debugger] Failed to rejoin workspace "${this.config.workspace}", getting a fresh one:`,e.message??e),this.server=await t({server_url:this.config.server_url})}this.serviceInfo=await this.server.registerService(this.buildServiceDefinition());const r=await this.updateSession();return this.overlay&&this.overlay.addLog("Service registered","result"),e.__HYPHA_DEBUGGER__=e.__HYPHA_DEBUGGER__??{},e.__HYPHA_DEBUGGER__.instance=this,this.saveConfigToStorage(),this.boundBeforeUnload=()=>this.saveConfigToStorage(),window.addEventListener("beforeunload",this.boundBeforeUnload),this.cleanupInterceptor=installNavigationInterceptor(),r}catch(e){throw console.error("[hypha-debugger] Failed to start:",e),this.overlay&&(this.overlay.setStatus("error"),this.overlay.setInfo({Status:"Error",Error:e.message??String(e)})),e}}async destroy(){this.boundBeforeUnload&&(window.removeEventListener("beforeunload",this.boundBeforeUnload),this.boundBeforeUnload=null),this.cleanupInterceptor&&(this.cleanupInterceptor(),this.cleanupInterceptor=null);try{this.serviceInfo&&this.server&&await this.server.unregisterService(this.serviceInfo.id)}catch{}try{sessionStorage.removeItem(STORAGE_KEY)}catch{}disposeController(),this.cursor?.destroy(),this.cursor=null,this.overlay?.destroy(),this.overlay=null;const e=window;e.__HYPHA_DEBUGGER__&&(delete e.__HYPHA_DEBUGGER__.instance,delete e.__HYPHA_DEBUGGER__.session)}saveConfigToStorage(){try{const e={server_url:this.config.server_url,workspace:this.server?.config?.workspace??this.config.workspace,service_id:this.config.service_id,service_name:this.config.service_name,show_ui:this.config.show_ui,visibility:this.config.visibility,require_token:this.config.require_token,script_url:this.detectScriptUrl()};sessionStorage.setItem(STORAGE_KEY,JSON.stringify(e))}catch{}}detectScriptUrl(){try{const e=document.querySelectorAll("script[src]");for(const t of Array.from(e))if(t.src&&t.src.includes("hypha-debugger"))return t.src}catch{}return"https://cdn.jsdelivr.net/npm/hypha-debugger/dist/hypha-debugger.min.js"}async updateSession(e){const t=this.serviceInfo?.id??this.config.service_id,n=this.buildServiceUrl(t),r=this.server.config?.workspace??"",o=this.config.require_token?await this.server.generateToken({expires_in:86400}):"";this.overlay&&(this.overlay.setStatus("connected"),this.overlay.setInfo({Status:"Connected",Server:this.config.server_url,...e}),this.overlay.setInstructions(this.buildInstructionBlock(n,o))),console.log(`[hypha-debugger] Service URL: ${n}`),o?(console.log(`[hypha-debugger] Token: ${o}`),console.log(`[hypha-debugger] Test:\n curl '${n}/get_page_info' -H 'Authorization: Bearer ${o}'`)):console.log(`[hypha-debugger] Test:\n curl '${n}/get_page_info'`);const i={service_id:t,workspace:r,server:this.server,service_url:n,token:o,destroy:()=>this.destroy()},s=window;return s.__HYPHA_DEBUGGER__=s.__HYPHA_DEBUGGER__??{},s.__HYPHA_DEBUGGER__.session=i,i}buildServiceUrl(e){const t=this.config.server_url.replace(/\/+$/,""),n=e.indexOf("/");if(-1!==n){const r=e.substring(0,n),o=e.substring(n+1),i=o.indexOf(":");return`${t}/${r}/services/${-1!==i?o.substring(i+1):o}`}return`${t}/services/${e}`}getHyphaModule(){if(__webpack_exports__connectToServer)return hyphaRpc;if(__webpack_exports__connectToServer)return hyphaRpcWebsocket;const e=window;if(e.hyphaWebsocketClient?.connectToServer)return e.hyphaWebsocketClient;throw new Error('hypha-rpc not found. Install it via npm or load it via: <script src="https://cdn.jsdelivr.net/npm/hypha-rpc@0.20.97/dist/hypha-rpc-websocket.min.js"><\/script>')}getConnectToServer(){return this.getHyphaModule().connectToServer}buildServiceDefinition(){return{id:this.config.service_id,name:this.config.service_name,type:"debugger",description:"Remote web page debugger. Allows inspecting DOM, taking screenshots, executing JavaScript, and interacting with the page.",config:{visibility:this.config.visibility},get_page_info:this.wrapFn(getPageInfo,"get_page_info"),get_html:this.wrapFn(getHtml,"get_html"),query_dom:this.wrapFn(queryDom,"query_dom"),click_element:this.wrapFn(clickElement$1,"click_element"),fill_input:this.wrapFn(fillInput,"fill_input"),scroll_to:this.wrapFn(scrollTo,"scroll_to"),take_screenshot:this.wrapFn(takeScreenshot,"take_screenshot"),execute_script:this.wrapFn(executeScript,"execute_script"),navigate:this.wrapFn(navigate,"navigate"),get_react_tree:this.wrapFn(getReactTree,"get_react_tree"),get_browser_state:this.wrapFn(getBrowserState,"get_browser_state"),click_element_by_index:this.wrapFn(clickElementByIndex,"click_element_by_index"),input_text:this.wrapFn(inputText,"input_text"),select_option:this.wrapFn(selectOption,"select_option"),scroll:this.wrapFn(scroll,"scroll"),remove_highlights:this.wrapFn(removeHighlights,"remove_highlights"),get_skill_md:this.wrapFn(this.createGetSkillMd(),"get_skill_md")}}createGetSkillMd(){const e=()=>{const e={},t={get_page_info:getPageInfo,get_html:getHtml,query_dom:queryDom,click_element:clickElement$1,fill_input:fillInput,scroll_to:scrollTo,take_screenshot:takeScreenshot,execute_script:executeScript,navigate:navigate,get_react_tree:getReactTree,get_browser_state:getBrowserState,click_element_by_index:clickElementByIndex,input_text:inputText,select_option:selectOption,scroll:scroll,remove_highlights:removeHighlights};for(const[n,r]of Object.entries(t))r.__schema__&&(e[n]=r);return!this.serviceInfo||this.buildServiceUrl(this.serviceInfo.id??this.config.service_id),generateSkillMd(e)};return e.__schema__={name:"getSkillMd",description:"Get the SKILL.md document describing all available debugger functions, their parameters, and usage examples. Follows the agentskills.io specification.",parameters:{type:"object",properties:{}}},e}buildInstructionBlock(e,t){const n=t?' -H "Authorization: Bearer $TOKEN"':"",r=["# Hypha Remote Debugger — Web Page","# A debugger is attached to a live web page.","# You can remotely inspect, interact with, and control this page via the HTTP API below.","#","# APPROACHES (pick what fits your task):","# - execute_script: Run arbitrary JS — fastest for reading/modifying page state, DOM queries, API calls","# - get_browser_state + click/input/select by index: Visual interaction with the page as a user would","# - get_html / query_dom: Read DOM structure with CSS selectors","# - get_react_tree: Inspect React component props, state, and hooks","# - take_screenshot: Visual verification of page state","#","# All POST endpoints accept JSON body with parameter names as keys.","",`SERVICE_URL="${e}"`];return t&&r.push(`TOKEN="${t}"`),r.push("","# Execute JavaScript (most versatile — read state, call APIs, modify DOM):",`curl -X POST "$SERVICE_URL/execute_script"${n} -H "Content-Type: application/json" -d '{"code": "document.title"}'`,"","# Smart DOM analysis (indexed interactive elements for click/type/select):",`curl "$SERVICE_URL/get_browser_state"${n}`,"","# Interact by element index:",`curl -X POST "$SERVICE_URL/click_element_by_index"${n} -H "Content-Type: application/json" -d '{"index": 3}'`,`curl -X POST "$SERVICE_URL/input_text"${n} -H "Content-Type: application/json" -d '{"index": 5, "text": "hello"}'`,"","# Screenshot + React inspection:",`curl "$SERVICE_URL/take_screenshot"${n}`,`curl "$SERVICE_URL/get_react_tree"${n}`,"","# Navigate (auto-reconnects for same-origin):",`curl -X POST "$SERVICE_URL/navigate"${n} -H "Content-Type: application/json" -d '{"url": "/other-page"}'`,"","# Full API docs:",`curl "$SERVICE_URL/get_skill_md"${n}`),r.join("\n")}wrapFn(e,t){const n=this,r=async(...r)=>{n.overlay?.addLog(`${t}(${n.summarizeArgs(r)})`,"call");try{const o=await e(...r);return o&&"object"==typeof o&&"error"in o?n.overlay?.addLog(`${t}: ${o.error}`,"error"):n.overlay?.addLog(`${t} -> OK`,"result"),o}catch(e){throw n.overlay?.addLog(`${t}: ${e.message}`,"error"),e}};return e.__schema__&&(r.__schema__=e.__schema__),wrapFn(r)}summarizeArgs(e){return 0===e.length?"":e.map(e=>"string"==typeof e?e.length>40?e.slice(0,40)+"...":e:"object"==typeof e&&null!==e?"{...}":String(e)).join(", ")}}async function startDebugger(e){return new HyphaDebugger(e).start()}function autoStart(){if("undefined"==typeof window||"undefined"==typeof document)return;if(window.__HYPHA_DEBUGGER__?.instance)return;try{const e=sessionStorage.getItem("__hypha_debugger_config__");if(e){const t=JSON.parse(e);if(t.server_url)return console.log("[hypha-debugger] Reconnecting from saved session..."),void startDebugger(t).catch(e=>{console.error("[hypha-debugger] Auto-reconnect failed:",e)})}}catch{}const e=document.querySelectorAll("script[src]");let t=null;for(const n of Array.from(e))if(n.src&&n.src.includes("hypha-debugger")){t=n;break}if(t?.hasAttribute("data-manual"))return;const n={server_url:t?.getAttribute("data-server-url")??"https://hypha.aicell.io"};t?.getAttribute("data-workspace")&&(n.workspace=t.getAttribute("data-workspace")),t?.getAttribute("data-token")&&(n.token=t.getAttribute("data-token")),t?.getAttribute("data-service-id")&&(n.service_id=t.getAttribute("data-service-id")),t?.hasAttribute("data-no-ui")&&(n.show_ui=!1),t?.hasAttribute("data-require-token")&&(n.require_token=!0),startDebugger(n).catch(e=>{console.error("[hypha-debugger] Auto-start failed:",e)})}"undefined"!=typeof window&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",autoStart):autoStart()),exports.AICursor=AICursor,exports.HyphaDebugger=HyphaDebugger,exports.PageController=PageController,exports.clickElement=clickElement$1,exports.clickElementByIndex=clickElementByIndex,exports.disposeController=disposeController,exports.executeScript=executeScript,exports.fillInput=fillInput,exports.generateSkillMd=generateSkillMd,exports.getBrowserState=getBrowserState,exports.getComputedStyles=getComputedStyles,exports.getConsoleLogs=getConsoleLogs,exports.getElementBounds=getElementBounds,exports.getHtml=getHtml,exports.getPageInfo=getPageInfo,exports.getReactTree=getReactTree,exports.goBack=goBack,exports.goForward=goForward,exports.inputText=inputText,exports.installConsoleCapture=installConsoleCapture,exports.installNavigationInterceptor=installNavigationInterceptor,exports.navigate=navigate,exports.queryDom=queryDom,exports.reload=reload,exports.removeHighlights=removeHighlights,exports.scroll=scroll,exports.scrollTo=scrollTo,exports.selectOption=selectOption,exports.softReplace=softReplace,exports.startDebugger=startDebugger,exports.takeScreenshot=takeScreenshot,exports.wrapFn=wrapFn});
59
68
  //# sourceMappingURL=hypha-debugger.min.js.map