@factset/frontgate-js-sdk 6.9.1 → 6.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/lib/esnext/FrontgateClient.js +16 -14
  3. package/dist/lib/esnext/FrontgateClient.js.map +1 -1
  4. package/dist/lib/esnext/mixins/AuthTokenRequestMixin.js +5 -0
  5. package/dist/lib/esnext/mixins/AuthTokenRequestMixin.js.map +1 -1
  6. package/dist/lib/esnext/mixins/PingMixin.js +31 -0
  7. package/dist/lib/esnext/mixins/PingMixin.js.map +1 -0
  8. package/dist/lib/esnext/mixins/auth/index.js +1 -0
  9. package/dist/lib/esnext/mixins/auth/index.js.map +1 -1
  10. package/dist/lib/esnext/mixins/index.js +1 -0
  11. package/dist/lib/esnext/mixins/index.js.map +1 -1
  12. package/dist/lib/esnext/version.js +1 -1
  13. package/dist/lib/esnext/version.js.map +1 -1
  14. package/dist/lib/node/FrontgateClient.js +16 -14
  15. package/dist/lib/node/FrontgateClient.js.map +1 -1
  16. package/dist/lib/node/mixins/AuthTokenRequestMixin.js +5 -0
  17. package/dist/lib/node/mixins/AuthTokenRequestMixin.js.map +1 -1
  18. package/dist/lib/node/mixins/PingMixin.js +35 -0
  19. package/dist/lib/node/mixins/PingMixin.js.map +1 -0
  20. package/dist/lib/node/mixins/auth/index.js +1 -0
  21. package/dist/lib/node/mixins/auth/index.js.map +1 -1
  22. package/dist/lib/node/mixins/index.js +1 -0
  23. package/dist/lib/node/mixins/index.js.map +1 -1
  24. package/dist/lib/node/version.js +1 -1
  25. package/dist/lib/node/version.js.map +1 -1
  26. package/dist/lib/types/mixins/AuthTokenRequestMixin.d.ts +3 -0
  27. package/dist/lib/types/mixins/PingMixin.d.ts +17 -0
  28. package/dist/lib/types/mixins/index.d.ts +2 -1
  29. package/dist/lib/umd/mdg2.client.min.umd.js +5 -5
  30. package/dist/lib/umd/mdg2.client.umd.js +53 -16
  31. package/package.json +1 -1
@@ -1,12 +1,12 @@
1
- (function(d,G){typeof exports=="object"&&typeof module<"u"?G(exports):typeof define=="function"&&define.amd?define(["exports"],G):(d=typeof globalThis<"u"?globalThis:d||self,G(d.fdsg={}))})(this,function(d){"use strict";var Us=d=>{throw TypeError(d)};var hr=(d,G,Q)=>G.has(d)||Us("Cannot "+Q);var v=(d,G,Q)=>(hr(d,G,"read from private field"),Q?Q.call(d):G.get(d)),k=(d,G,Q)=>G.has(d)?Us("Cannot add the same private member more than once"):G instanceof WeakSet?G.add(d):G.set(d,Q),R=(d,G,Q,ot)=>(hr(d,G,"write to private field"),ot?ot.call(d,Q):G.set(d,Q),Q),H=(d,G,Q)=>(hr(d,G,"access private method"),Q);var $s=(d,G,Q,ot)=>({set _(Rt){R(d,G,Rt,Q)},get _(){return v(d,G,ot)}});var Le,Mt,St,He,qe,Ge,Re,ke,ae,Vs,Ys,Ks,Qs,Xs;class Rt{constructor(e,t=-1){if(!Number.isInteger(e))throw new TypeError(`idApplication is not an integer number. Given: ${e} (${typeof e})`);if(this.idApplication=e,!Number.isInteger(t))throw new TypeError(`idUser is not an integer number. Given: ${t} (${typeof t})`);this.idUser=t}peerInfoFromMessage(e){if(e.Message==="Foundation::DisconnectionMessage"){const t=e;throw new Error(`Disconnection Message: ${t.details}`)}if(e.Message==="Foundation::AuthenticationByTokenResponse"||e.Message==="Foundation::ConfigurationResponse"){const t=e;return this.serverInfo=this.parseServerInfo(t),{uuid:t.server_info.uuid,description:t.server_info.description,software:t.server_info.software,os:t.server_info.os,maximumIdleInterval:parseInt(t.maximum_idle_interval,10),maximumReceivableMessageSize:t.maximum_receivable_message_size}}throw new Error("Could not extract server_info from unknown message type.")}parseServerInfo(e){const t=e,r=Number(BigInt(t.time_at_server.microseconds))/1e3,s=Math.ceil(Date.now()-r);return{description:t.server_info.description,software:t.server_info.software,os:t.server_info.os,time:new Date(r),offsetInMs:s}}getServerInfo(){return this.serverInfo}}var y=(n=>(n[n.TRACE=10]="TRACE",n[n.DEBUG=20]="DEBUG",n[n.INFO=30]="INFO",n[n.WARN=40]="WARN",n[n.ERROR=50]="ERROR",n[n.FATAL=60]="FATAL",n[n.SILENT=100]="SILENT",n))(y||{});const Oe=class Oe{constructor(e=""){this.defaultLevel=40,this.noop=()=>null,this.name=e,this.setDefaultLevelFromLocalStorage(),Object.assign(Oe.loggers,{[e]:this})}getName(){return this.name}setLevel(e){this.level=e}getLevel(){return typeof this.level=="number"&&isFinite(this.level)&&Math.floor(this.level)===this.level?this.level:this.defaultLevel}shouldLog(e){switch(this.getLevel()){case 100:return!1;case 60:return e==="fatal";case 50:return e==="fatal"||e==="error";case 40:return e==="fatal"||e==="error"||e==="warn";case 30:return e==="fatal"||e==="error"||e==="warn"||e==="info";case 20:return e==="fatal"||e==="error"||e==="warn"||e==="info"||e==="debug";case 10:default:return!0}}setDefaultLevelFromLocalStorage(){let e;try{if(!(typeof localStorage=="object"))return;const r=localStorage.getItem("loglevel");if(!r)return;e=r}catch{return}e&&this.setLevel(Oe.getLogLevel(e))}static getLogLevel(e){const t=e.toLowerCase();switch(t){case"silent":return 100;case"fatal":return 60;case"error":return 50;case"warn":return 40;case"info":return 30;case"debug":return 20;case"trace":return 10;default:throw new Error(`Invalid log level: ${t}`)}}static getLogger(e,t){if(Object.prototype.hasOwnProperty.call(Oe.loggers,e))return Oe.loggers[e];const r=new t(e);return Oe.loggers[e]=r,r}};Oe.loggers={};let Ee=Oe;class Zs{static getLogLevel(e){const t=e.toLowerCase();switch(t){case"silent":return y.SILENT;case"fatal":return y.FATAL;case"error":return y.ERROR;case"warn":return y.WARN;case"info":return y.INFO;case"debug":return y.DEBUG;case"trace":return y.TRACE;default:throw new Error(`Invalid log level: ${t}`)}}}class an extends Ee{constructor(){super(...arguments),this.trace=this.getLogMethod("trace"),this.debug=this.getLogMethod("debug"),this.info=this.getLogMethod("info"),this.warn=this.getLogMethod("warn"),this.error=this.getLogMethod("error"),this.fatal=this.getLogMethod("fatal")}setLevel(e){this.level=e,this.trace=this.getLogMethod("trace"),this.debug=this.getLogMethod("debug"),this.info=this.getLogMethod("info"),this.warn=this.getLogMethod("warn"),this.error=this.getLogMethod("error"),this.fatal=this.getLogMethod("fatal")}getLogMethod(e){if(this.shouldLog(e)){const t=e==="debug"||e==="fatal"?"log":e,r=this.name?`${this.name}: [${e.toUpperCase()}] `:`-----> [${e.toUpperCase()}] `;return Function.prototype.bind.call(console[t],console,r)}return this.noop}static getLogger(e=""){return super.getLogger(e,an)}}const eo={silent:0,fatal:1,error:2,warn:3,info:4,debug:5,trace:6};class to extends Ee{constructor(e,t=""){super(t),this.name=t,this.logger=e,this.trace=Function.prototype.bind.call(e.trace,e),this.debug=Function.prototype.bind.call(e.debug,e),this.info=Function.prototype.bind.call(e.info,e),this.warn=Function.prototype.bind.call(e.warn,e),this.error=Function.prototype.bind.call(e.error,e),this.fatal=Function.prototype.bind.call(e.error,e)}setLevel(e){this.level=e,this.logger&&(this.logger.level=y[e].toLowerCase())}static getLogger(e=""){return Object.prototype.hasOwnProperty.call(Ee.loggers,e)?Ee.loggers[e]:null}}class it extends Ee{constructor(){super(...arguments),this.trace=this.noop,this.debug=this.noop,this.info=this.noop,this.warn=this.noop,this.error=this.noop}static getLogger(e=""){return super.getLogger(e,it)}}var q=Uint8Array,te=Uint16Array,cn=Int32Array,kt=new q([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Pt=new q([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),un=new q([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),pr=function(n,e){for(var t=new te(31),r=0;r<31;++r)t[r]=e+=1<<n[r-1];for(var s=new cn(t[30]),r=1;r<30;++r)for(var o=t[r];o<t[r+1];++o)s[o]=o-t[r]<<5|r;return{b:t,r:s}},gr=pr(kt,2),vr=gr.b,hn=gr.r;vr[28]=258,hn[258]=28;for(var br=pr(Pt,0),no=br.b,mr=br.r,ln=new te(32768),U=0;U<32768;++U){var Te=(U&43690)>>1|(U&21845)<<1;Te=(Te&52428)>>2|(Te&13107)<<2,Te=(Te&61680)>>4|(Te&3855)<<4,ln[U]=((Te&65280)>>8|(Te&255)<<8)>>1}for(var de=function(n,e,t){for(var r=n.length,s=0,o=new te(e);s<r;++s)n[s]&&++o[n[s]-1];var i=new te(e);for(s=1;s<e;++s)i[s]=i[s-1]+o[s-1]<<1;var a;if(t){a=new te(1<<e);var c=15-e;for(s=0;s<r;++s)if(n[s])for(var h=s<<4|n[s],u=e-n[s],l=i[n[s]-1]++<<u,b=l|(1<<u)-1;l<=b;++l)a[ln[l]>>c]=h}else for(a=new te(r),s=0;s<r;++s)n[s]&&(a[s]=ln[i[n[s]-1]++]>>15-n[s]);return a},Me=new q(288),U=0;U<144;++U)Me[U]=8;for(var U=144;U<256;++U)Me[U]=9;for(var U=256;U<280;++U)Me[U]=7;for(var U=280;U<288;++U)Me[U]=8;for(var at=new q(32),U=0;U<32;++U)at[U]=5;var ro=de(Me,9,0),so=de(Me,9,1),oo=de(at,5,0),io=de(at,5,1),fn=function(n){for(var e=n[0],t=1;t<n.length;++t)n[t]>e&&(e=n[t]);return e},ce=function(n,e,t){var r=e/8|0;return(n[r]|n[r+1]<<8)>>(e&7)&t},dn=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},pn=function(n){return(n+7)/8|0},Ne=function(n,e,t){return(e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length),new q(n.subarray(e,t))},ao=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],W=function(n,e,t){var r=new Error(e||ao[n]);if(r.code=n,Error.captureStackTrace&&Error.captureStackTrace(r,W),!t)throw r;return r},co=function(n,e,t,r){var s=n.length,o=0;if(!s||e.f&&!e.l)return t||new q(0);var i=!t,a=i||e.i!=2,c=e.i;i&&(t=new q(s*3));var h=function(At){var Ct=t.length;if(At>Ct){var st=new q(Math.max(Ct*2,At));st.set(t),t=st}},u=e.f||0,l=e.p||0,b=e.b||0,f=e.l,T=e.d,_=e.m,A=e.n,w=s*8;do{if(!f){u=ce(n,l,1);var m=ce(n,l+1,3);if(l+=3,m)if(m==1)f=so,T=io,_=9,A=5;else if(m==2){var C=ce(n,l,31)+257,N=ce(n,l+10,15)+4,g=C+ce(n,l+5,31)+1;l+=14;for(var p=new q(g),I=new q(19),O=0;O<N;++O)I[un[O]]=ce(n,l+O*3,7);l+=N*3;for(var x=fn(I),z=(1<<x)-1,P=de(I,x,1),O=0;O<g;){var F=P[ce(n,l,z)];l+=F&15;var E=F>>4;if(E<16)p[O++]=E;else{var j=0,L=0;for(E==16?(L=3+ce(n,l,3),l+=2,j=p[O-1]):E==17?(L=3+ce(n,l,7),l+=3):E==18&&(L=11+ce(n,l,127),l+=7);L--;)p[O++]=j}}var V=p.subarray(0,C),$=p.subarray(C);_=fn(V),A=fn($),f=de(V,_,1),T=de($,A,1)}else W(1);else{var E=pn(l)+4,M=n[E-4]|n[E-3]<<8,S=E+M;if(S>s){c&&W(0);break}a&&h(b+M),t.set(n.subarray(E,S),b),e.b=b+=M,e.p=l=S*8,e.f=u;continue}if(l>w){c&&W(0);break}}a&&h(b+131072);for(var Be=(1<<_)-1,ee=(1<<A)-1,fe=l;;fe=l){var j=f[dn(n,l)&Be],Y=j>>4;if(l+=j&15,l>w){c&&W(0);break}if(j||W(2),Y<256)t[b++]=Y;else if(Y==256){fe=l,f=null;break}else{var J=Y-254;if(Y>264){var O=Y-257,D=kt[O];J=ce(n,l,(1<<D)-1)+vr[O],l+=D}var ie=T[dn(n,l)&ee],me=ie>>4;ie||W(3),l+=ie&15;var $=no[me];if(me>3){var D=Pt[me];$+=dn(n,l)&(1<<D)-1,l+=D}if(l>w){c&&W(0);break}a&&h(b+131072);var Pe=b+J;if(b<$){var _e=o-$,Je=Math.min($,Pe);for(_e+b<0&&W(3);b<Je;++b)t[b]=r[_e+b]}for(;b<Pe;++b)t[b]=t[b-$]}}e.l=f,e.p=fe,e.b=b,e.f=u,f&&(u=1,e.m=_,e.d=T,e.n=A)}while(!u);return b!=t.length&&i?Ne(t,0,b):t.subarray(0,b)},ye=function(n,e,t){t<<=e&7;var r=e/8|0;n[r]|=t,n[r+1]|=t>>8},ct=function(n,e,t){t<<=e&7;var r=e/8|0;n[r]|=t,n[r+1]|=t>>8,n[r+2]|=t>>16},gn=function(n,e){for(var t=[],r=0;r<n.length;++r)n[r]&&t.push({s:r,f:n[r]});var s=t.length,o=t.slice();if(!s)return{t:Er,l:0};if(s==1){var i=new q(t[0].s+1);return i[t[0].s]=1,{t:i,l:1}}t.sort(function(S,C){return S.f-C.f}),t.push({s:-1,f:25001});var a=t[0],c=t[1],h=0,u=1,l=2;for(t[0]={s:-1,f:a.f+c.f,l:a,r:c};u!=s-1;)a=t[t[h].f<t[l].f?h++:l++],c=t[h!=u&&t[h].f<t[l].f?h++:l++],t[u++]={s:-1,f:a.f+c.f,l:a,r:c};for(var b=o[0].s,r=1;r<s;++r)o[r].s>b&&(b=o[r].s);var f=new te(b+1),T=vn(t[u-1],f,0);if(T>e){var r=0,_=0,A=T-e,w=1<<A;for(o.sort(function(C,N){return f[N.s]-f[C.s]||C.f-N.f});r<s;++r){var m=o[r].s;if(f[m]>e)_+=w-(1<<T-f[m]),f[m]=e;else break}for(_>>=A;_>0;){var E=o[r].s;f[E]<e?_-=1<<e-f[E]++-1:++r}for(;r>=0&&_;--r){var M=o[r].s;f[M]==e&&(--f[M],++_)}T=e}return{t:new q(f),l:T}},vn=function(n,e,t){return n.s==-1?Math.max(vn(n.l,e,t+1),vn(n.r,e,t+1)):e[n.s]=t},yr=function(n){for(var e=n.length;e&&!n[--e];);for(var t=new te(++e),r=0,s=n[0],o=1,i=function(c){t[r++]=c},a=1;a<=e;++a)if(n[a]==s&&a!=e)++o;else{if(!s&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(s),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(s);o=1,s=n[a]}return{c:t.subarray(0,r),n:e}},ut=function(n,e){for(var t=0,r=0;r<e.length;++r)t+=n[r]*e[r];return t},wr=function(n,e,t){var r=t.length,s=pn(e+2);n[s]=r&255,n[s+1]=r>>8,n[s+2]=n[s]^255,n[s+3]=n[s+1]^255;for(var o=0;o<r;++o)n[s+o+4]=t[o];return(s+4+r)*8},_r=function(n,e,t,r,s,o,i,a,c,h,u){ye(e,u++,t),++s[256];for(var l=gn(s,15),b=l.t,f=l.l,T=gn(o,15),_=T.t,A=T.l,w=yr(b),m=w.c,E=w.n,M=yr(_),S=M.c,C=M.n,N=new te(19),g=0;g<m.length;++g)++N[m[g]&31];for(var g=0;g<S.length;++g)++N[S[g]&31];for(var p=gn(N,7),I=p.t,O=p.l,x=19;x>4&&!I[un[x-1]];--x);var z=h+5<<3,P=ut(s,Me)+ut(o,at)+i,F=ut(s,b)+ut(o,_)+i+14+3*x+ut(N,I)+2*N[16]+3*N[17]+7*N[18];if(c>=0&&z<=P&&z<=F)return wr(e,u,n.subarray(c,c+h));var j,L,V,$;if(ye(e,u,1+(F<P)),u+=2,F<P){j=de(b,f,0),L=b,V=de(_,A,0),$=_;var Be=de(I,O,0);ye(e,u,E-257),ye(e,u+5,C-1),ye(e,u+10,x-4),u+=14;for(var g=0;g<x;++g)ye(e,u+3*g,I[un[g]]);u+=3*x;for(var ee=[m,S],fe=0;fe<2;++fe)for(var Y=ee[fe],g=0;g<Y.length;++g){var J=Y[g]&31;ye(e,u,Be[J]),u+=I[J],J>15&&(ye(e,u,Y[g]>>5&127),u+=Y[g]>>12)}}else j=ro,L=Me,V=oo,$=at;for(var g=0;g<a;++g){var D=r[g];if(D>255){var J=D>>18&31;ct(e,u,j[J+257]),u+=L[J+257],J>7&&(ye(e,u,D>>23&31),u+=kt[J]);var ie=D&31;ct(e,u,V[ie]),u+=$[ie],ie>3&&(ct(e,u,D>>5&8191),u+=Pt[ie])}else ct(e,u,j[D]),u+=L[D]}return ct(e,u,j[256]),u+L[256]},uo=new cn([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Er=new q(0),ho=function(n,e,t,r,s,o){var i=o.z||n.length,a=new q(r+i+5*(1+Math.ceil(i/7e3))+s),c=a.subarray(r,a.length-s),h=o.l,u=(o.r||0)&7;if(e){u&&(c[0]=o.r>>3);for(var l=uo[e-1],b=l>>13,f=l&8191,T=(1<<t)-1,_=o.p||new te(32768),A=o.h||new te(T+1),w=Math.ceil(t/3),m=2*w,E=function(ur){return(n[ur]^n[ur+1]<<w^n[ur+2]<<m)&T},M=new cn(25e3),S=new te(288),C=new te(32),N=0,g=0,p=o.i||0,I=0,O=o.w||0,x=0;p+2<i;++p){var z=E(p),P=p&32767,F=A[z];if(_[P]=F,A[z]=P,O<=p){var j=i-p;if((N>7e3||I>24576)&&(j>423||!h)){u=_r(n,c,0,M,S,C,g,I,x,p-x,u),I=N=g=0,x=p;for(var L=0;L<286;++L)S[L]=0;for(var L=0;L<30;++L)C[L]=0}var V=2,$=0,Be=f,ee=P-F&32767;if(j>2&&z==E(p-ee))for(var fe=Math.min(b,j)-1,Y=Math.min(32767,p),J=Math.min(258,j);ee<=Y&&--Be&&P!=F;){if(n[p+V]==n[p+V-ee]){for(var D=0;D<J&&n[p+D]==n[p+D-ee];++D);if(D>V){if(V=D,$=ee,D>fe)break;for(var ie=Math.min(ee,D-2),me=0,L=0;L<ie;++L){var Pe=p-ee+L&32767,_e=_[Pe],Je=Pe-_e&32767;Je>me&&(me=Je,F=Pe)}}}P=F,F=_[P],ee+=P-F&32767}if($){M[I++]=268435456|hn[V]<<18|mr[$];var At=hn[V]&31,Ct=mr[$]&31;g+=kt[At]+Pt[Ct],++S[257+At],++C[Ct],O=p+V,++N}else M[I++]=n[p],++S[n[p]]}}for(p=Math.max(p,O);p<i;++p)M[I++]=n[p],++S[n[p]];u=_r(n,c,h,M,S,C,g,I,x,p-x,u),h||(o.r=u&7|c[u/8|0]<<3,u-=7,o.h=A,o.p=_,o.i=p,o.w=O)}else{for(var p=o.w||0;p<i+h;p+=65535){var st=p+65535;st>=i&&(c[u/8|0]=h,st=i),u=wr(c,u+1,n.subarray(p,st))}o.i=i}return Ne(a,0,r+pn(u)+s)},Tr=function(){var n=1,e=0;return{p:function(t){for(var r=n,s=e,o=t.length|0,i=0;i!=o;){for(var a=Math.min(i+2655,o);i<a;++i)s+=r+=t[i];r=(r&65535)+15*(r>>16),s=(s&65535)+15*(s>>16)}n=r,e=s},d:function(){return n%=65521,e%=65521,(n&255)<<24|(n&65280)<<8|(e&255)<<8|e>>8}}},Mr=function(n,e,t,r,s){if(!s&&(s={l:1},e.dictionary)){var o=e.dictionary.subarray(-32768),i=new q(o.length+n.length);i.set(o),i.set(n,o.length),n=i,s.w=o.length}return ho(n,e.level==null?6:e.level,e.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(n.length)))*1.5):20:12+e.mem,t,r,s)},Sr=function(n,e,t){for(;t;++e)n[e]=t,t>>>=8},lo=function(n,e){var t=e.level,r=t==0?0:t<6?1:t==9?3:2;if(n[0]=120,n[1]=r<<6|(e.dictionary&&32),n[1]|=31-(n[0]<<8|n[1])%31,e.dictionary){var s=Tr();s.p(e.dictionary),Sr(n,2,s.d())}},fo=function(n,e){return((n[0]&15)!=8||n[0]>>4>7||(n[0]<<8|n[1])%31)&&W(6,"invalid zlib data"),(n[1]>>5&1)==+!e&&W(6,"invalid zlib data: "+(n[1]&32?"need":"unexpected")+" dictionary"),(n[1]>>3&4)+2},bn=function(){function n(e,t){if(typeof e=="function"&&(t=e,e={}),this.ondata=t,this.o=e||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new q(98304),this.o.dictionary){var r=this.o.dictionary.subarray(-32768);this.b.set(r,32768-r.length),this.s.i=32768-r.length}}return n.prototype.p=function(e,t){this.ondata(Mr(e,this.o,0,0,this.s),t)},n.prototype.push=function(e,t){this.ondata||W(5),this.s.l&&W(4);var r=e.length+this.s.z;if(r>this.b.length){if(r>2*this.b.length-32768){var s=new q(r&-32768);s.set(this.b.subarray(0,this.s.z)),this.b=s}var o=this.b.length-this.s.z;this.b.set(e.subarray(0,o),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(e.subarray(o),32768),this.s.z=e.length-o+32768,this.s.i=32766,this.s.w=32768}else this.b.set(e,this.s.z),this.s.z+=e.length;this.s.l=t&1,(this.s.z>this.s.w+8191||t)&&(this.p(this.b,t||!1),this.s.w=this.s.i,this.s.i-=2)},n.prototype.flush=function(){this.ondata||W(5),this.s.l&&W(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2},n}(),mn=function(){function n(e,t){typeof e=="function"&&(t=e,e={}),this.ondata=t;var r=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:r?r.length:0},this.o=new q(32768),this.p=new q(0),r&&this.o.set(r)}return n.prototype.e=function(e){if(this.ondata||W(5),this.d&&W(4),!this.p.length)this.p=e;else if(e.length){var t=new q(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}},n.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,r=co(this.p,this.s,this.o);this.ondata(Ne(r,t,this.s.b),this.d),this.o=Ne(r,this.s.b-32768),this.s.b=this.o.length,this.p=Ne(this.p,this.s.p/8|0),this.s.p&=7},n.prototype.push=function(e,t){this.e(e),this.c(t)},n}(),po=function(){function n(e,t){this.c=Tr(),this.v=1,bn.call(this,e,t)}return n.prototype.push=function(e,t){this.c.p(e),bn.prototype.push.call(this,e,t)},n.prototype.p=function(e,t){var r=Mr(e,this.o,this.v&&(this.o.dictionary?6:2),t&&4,this.s);this.v&&(lo(r,this.o),this.v=0),t&&Sr(r,r.length-4,this.c.d()),this.ondata(r,t)},n.prototype.flush=function(){bn.prototype.flush.call(this)},n}(),go=function(){function n(e,t){mn.call(this,e,t),this.v=e&&e.dictionary?2:1}return n.prototype.push=function(e,t){if(mn.prototype.e.call(this,e),this.v){if(this.p.length<6&&!t)return;this.p=this.p.subarray(fo(this.p,this.v-1)),this.v=0}t&&(this.p.length<4&&W(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),mn.prototype.c.call(this,t)},n}(),Ir=typeof TextEncoder<"u"&&new TextEncoder,yn=typeof TextDecoder<"u"&&new TextDecoder,vo=0;try{yn.decode(Er,{stream:!0}),vo=1}catch{}var bo=function(n){for(var e="",t=0;;){var r=n[t++],s=(r>127)+(r>223)+(r>239);if(t+s>n.length)return{s:e,r:Ne(n,t-1)};s?s==3?(r=((r&15)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,e+=String.fromCharCode(55296|r>>10,56320|r&1023)):s&1?e+=String.fromCharCode((r&31)<<6|n[t++]&63):e+=String.fromCharCode((r&15)<<12|(n[t++]&63)<<6|n[t++]&63):e+=String.fromCharCode(r)}};function mo(n,e){var t;if(Ir)return Ir.encode(n);for(var r=n.length,s=new q(n.length+(n.length>>1)),o=0,i=function(h){s[o++]=h},t=0;t<r;++t){if(o+5>s.length){var a=new q(o+8+(r-t<<1));a.set(s),s=a}var c=n.charCodeAt(t);c<128||e?i(c):c<2048?(i(192|c>>6),i(128|c&63)):c>55295&&c<57344?(c=65536+(c&1047552)|n.charCodeAt(++t)&1023,i(240|c>>18),i(128|c>>12&63),i(128|c>>6&63),i(128|c&63)):(i(224|c>>12),i(128|c>>6&63),i(128|c&63))}return Ne(s,0,o)}function yo(n,e){var t;if(yn)return yn.decode(n);var r=bo(n),s=r.s,t=r.r;return t.length&&W(8),s}const wo=n=>{if(n.length===1)return n[0];const e=new Uint8Array(n.reduce((t,r)=>t+r.length,0));for(let t=0,r=0;t<n.length;++t)e.set(n[t],r),r+=n[t].length;return e};class Ar{constructor(){this.reset()}reset(){this.compressor=null,this.decompressor=null}compress(e){this.compressor||(this.compressor=new po({mem:4}));const t=[];return this.compressor.ondata=r=>{t.push(r)},this.compressor.push(mo(e)),this.compressor.flush(),wo(t)}decompress(e){this.decompressor||(this.decompressor=new go);let t;this.decompressor.ondata=r=>{t=r};try{if(this.decompressor.push(e),t===void 0)throw new Error("invalid block type")}catch(r){throw new Error(`Decompression error: ${r.message}, length: ${e.length}, data: [${e.toString()}]`)}return yo(t)}}const we=class we{static isSupportedEncoding(e){return we.SUPPORTED_ENCODINGS.includes(e)}static isPlainJson(e){return we.PLAIN_JSON_ENCODINGS.includes(e)}static isCompressedJson(e){return we.COMPRESSED_ENCODINGS.includes(e)}};we.SUPPORTED_ENCODINGS=["jsjson-v2","jsjsonc-v2"],we.PLAIN_JSON_ENCODINGS=["jsjson-v2"],we.COMPRESSED_ENCODINGS=we.SUPPORTED_ENCODINGS.filter(e=>e.includes("jsonc"));let Se=we;const _o="Mdg2Client",Cr="BST",wn=6e3,Or=3e3,Eo=9e3,Rr=3,To=!1,Mo=9e3,kr=!1,Pr=512;function So(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var _n,Nr;function Io(){if(Nr)return _n;Nr=1;var n=function(m){return e(m)&&!t(m)};function e(w){return!!w&&typeof w=="object"}function t(w){var m=Object.prototype.toString.call(w);return m==="[object RegExp]"||m==="[object Date]"||o(w)}var r=typeof Symbol=="function"&&Symbol.for,s=r?Symbol.for("react.element"):60103;function o(w){return w.$$typeof===s}function i(w){return Array.isArray(w)?[]:{}}function a(w,m){return m.clone!==!1&&m.isMergeableObject(w)?_(i(w),w,m):w}function c(w,m,E){return w.concat(m).map(function(M){return a(M,E)})}function h(w,m){if(!m.customMerge)return _;var E=m.customMerge(w);return typeof E=="function"?E:_}function u(w){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(w).filter(function(m){return Object.propertyIsEnumerable.call(w,m)}):[]}function l(w){return Object.keys(w).concat(u(w))}function b(w,m){try{return m in w}catch{return!1}}function f(w,m){return b(w,m)&&!(Object.hasOwnProperty.call(w,m)&&Object.propertyIsEnumerable.call(w,m))}function T(w,m,E){var M={};return E.isMergeableObject(w)&&l(w).forEach(function(S){M[S]=a(w[S],E)}),l(m).forEach(function(S){f(w,S)||(b(w,S)&&E.isMergeableObject(m[S])?M[S]=h(S,E)(w[S],m[S],E):M[S]=a(m[S],E))}),M}function _(w,m,E){E=E||{},E.arrayMerge=E.arrayMerge||c,E.isMergeableObject=E.isMergeableObject||n,E.cloneUnlessOtherwiseSpecified=a;var M=Array.isArray(m),S=Array.isArray(w),C=M===S;return C?M?E.arrayMerge(w,m,E):T(w,m,E):a(m,E)}_.all=function(m,E){if(!Array.isArray(m))throw new Error("first argument should be an array");return m.reduce(function(M,S){return _(M,S,E)},{})};var A=_;return _n=A,_n}var Ao=Io();const jr=So(Ao);class Co extends Error{constructor(e="Service Unavailable",t){super(e,{cause:t}),this.name="ServiceUnavailableError",this.code=503}}class Oo extends Error{constructor(e="Internal Server Error",t){super(e,{cause:t}),this.name="InternalServerError",this.code=500}}class Dr extends Error{constructor(e="Timeout",t){super(e,{cause:t}),this.name="TimeoutError",this.code=408}}class Ro extends Error{constructor(e="Unauthorized",t){super(e,{cause:t}),this.name="UnauthorizedError",this.code=401}}class ko extends Error{constructor(e="Bad Request",t){super(e,{cause:t}),this.name="BadRequestError",this.code=400}}class Po extends Error{constructor(e,t){super(e,{cause:t}),this.name="ResponseError",this.response=t}}function No(n){return!!n&&typeof n=="object"}function jo(...n){const e=n.filter(No);return jr.all(e,{arrayMerge:(t,r)=>r})}function En(n){return n.replace(/[=]/g,"").replace(/\//g,"_").replace(/\+/g,"-")}function Do(n){return/^[A-Za-z0-9_-]*$/.test(n)}function xo(n){let e=n.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4!==0;)e+="=";switch(e.length%4){case 0:break;case 1:e+="===";break;case 2:e+="==";break;case 3:e+="=";break}return e}const Tn=n=>{var r,s,o,i;let e="Unknown",t=500;if(n.name==="Foundation::PermissionDeniedResponse")t=403,e=`Permission Denied. Job ID: ${n.jobId} failed with status code ${t} `;else if(n.name==="Foundation::ErrorResponse"&&n.reason){const a=n.reason.startsWith("{"),c=a?JSON.parse(n.reason)||{}:n.reason;a&&((r=c.errors)!=null&&r[0].details)?e=c.errors[0].details:typeof c=="string"&&(e=c),t=parseInt(((o=(s=c==null?void 0:c.meta)==null?void 0:s.status)==null?void 0:o.code)??((i=n.msg.reason)==null?void 0:i.value)??500,10)}return new Po(`${e} (${t})`,n)},Fo=async n=>new Promise(e=>{setTimeout(e,n)}),Uo=()=>typeof window>"u",et=class et{constructor(){this._timeAtSender=Date.now()}getPtlMessage(){return{Message:et.NAME,Version:et.VERSION,time_at_sender:{microseconds:this._timeAtSender*1e3}}}resetTimeAtSender(){this._timeAtSender=Date.now()}get timeAtSender(){return this._timeAtSender}};et.NAME="PingRequest",et.VERSION=3;let ht=et;var xr=(n=>(n.MAXIMUM_STRING="9223372036854775807",n.MINIMUM_STRING="-9223372036854775807",n))(xr||{});function Nt(n){return n.toString().slice(0,-3)}const tt=class tt{constructor(e){if(e.Message!==tt.NAME)throw new Error(`Unsupported message=${e.Message}`);if(e.Version!==tt.VERSION)throw new Error(`Unsupported version=${e.Version} for message=${e.Message}`);this._timeReceivedResponse=Date.now(),this._timeAtSender=Number(Nt(e.time_at_sender.microseconds)),this._timeFromRequest=Number(Nt(e.time_from_request.microseconds))}get timeAtPeer(){return this._timeAtSender}get timeOfRequest(){return this._timeFromRequest}get timeOfResponse(){return this._timeReceivedResponse}get latencyTotal(){return this._timeReceivedResponse-this._timeFromRequest}get latencyAtPeer(){return this._timeAtSender-this._timeFromRequest}};tt.NAME="Foundation::PingResponse",tt.VERSION=2;let We=tt;var Ie=(n=>(n[n.DISCONNECTED=0]="DISCONNECTED",n[n.CONNECTING=1]="CONNECTING",n[n.AUTHENTICATED=2]="AUTHENTICATED",n[n.RECONNECTING=3]="RECONNECTING",n))(Ie||{}),Fr=(n=>(n[n.production=40]="production",n[n.preproduction=35]="preproduction",n[n.show=30]="show",n[n.testing=20]="testing",n))(Fr||{}),Ur=(n=>(n.production="frontgate-eu.factsetdigitalsolutions.com",n.show="frontgate-eu.show.factsetdigitalsolutions.com",n))(Ur||{});const nn=class nn{constructor(e,t){if(this.reconnectDelays=[1e3,2e3,4e3,8e3,16e3,32e3],this.reconnectCounter=0,this.connectionCounter=0,this.onConnect=null,this.onMessage=null,this.onClose=null,this.onError=null,this.onAuthentication=null,this.onCleanupRequests=null,this.onCleanupSubscriptions=null,this.onClearPendingSubscription=null,this.onReceiveTimeout=null,this.restartSubscriptions=null,this.options={...nn.DEFAULT_OPTIONS,...t},this.auth=e,this.state=0,this.options.logger&&(this.logger=this.options.logger),this.timestampOfLastMessageSent=0,this.jobId=0,this.peerInfo=null,this.compressor=new Ar,this.keepAliveIntervalHandle=null,this.hasActiveSession=!1,this.options.loglevel&&this.logger.setLevel(this.options.loglevel),!Se.isSupportedEncoding(this.options.encoding))throw new Error(`Unknown or unsupported encoding: ${this.options.encoding}`);this.messageProcessors={},this.setMessageProcessor("Foundation::LoadNotificationMessage",this.handleLoadNotificationMessage.bind(this)),this.setMessageProcessor("Foundation::KeepAliveMessage",this.handleKeepAliveMessage.bind(this)),this.setMessageProcessor("Foundation::PingResponse",this.handlePingResponseMessage.bind(this)),this.setMessageProcessor("Foundation::DisconnectionMessage",this.handleDisconnectionMessage.bind(this))}setMessageProcessor(e,t){this.messageProcessors[e]=t}removeMessageProcessor(e){this.messageProcessors[e]!==void 0&&(this.messageProcessors[e]=void 0)}async close(){if(!this.isAuthenticated()){this.logger.warn("Cannot close gracefully. Connection not open. Proceeding to handleClose."),await this.handleClose("Unauthenticated connection");return}try{await this.sendDisconnectionMessage()}catch(e){await this.handleClose(e.message)}}setPeerInfo(e){this.peerInfo={...this.peerInfo,...e}}isAuthenticated(){return this.state===2}isConnecting(){return this.state===1}clearPendingConnection(){this.pendingConnection=null}isPendingConnection(){return this.pendingConnection instanceof Promise}handleLoadNotificationMessage(e){return this.peerInfo&&(this.peerInfo.loadStatus=e.load),!1}handleKeepAliveMessage(){return!1}handlePingResponseMessage(e){const t=new We(e);return this.logger.debug(`Time in ms: Request=${t.timeOfRequest} Peer=${t.timeAtPeer} Response=${t.timeOfResponse}`),this.logger.debug(`Latency in ms: Total=${t.latencyTotal} Peer=${t.latencyAtPeer}`),!1}async handleDisconnectionMessage(e){await this.handleClose(`DisconnectionMessage received: '${e.details}`),this.onClose&&this.onClose(e.details)}handleAuthentication(){this.state=2;const e=1e3;this.keepAliveIntervalHandle=setInterval(()=>{this.sendKeepAliveMessage()},e),this.onAuthentication&&this.onAuthentication()}handleReceiveTimeout(){this.messageReceiveTimeout&&clearTimeout(this.messageReceiveTimeout),this.onReceiveTimeout&&this.onReceiveTimeout()}resetReceiveTimeout(){var t;if(!((t=this.peerInfo)!=null&&t.maximumIdleInterval))return;const e=this.peerInfo.maximumIdleInterval/1e3*2;this.messageReceiveTimeout&&clearTimeout(this.messageReceiveTimeout),this.messageReceiveTimeout=setTimeout(()=>{this.handleReceiveTimeout()},e)}handleStandardMessage(e){return this.onMessage&&this.onMessage(e),!0}handleMessage(e){if(!e.Message)return;this.resetReceiveTimeout();const t=this.messageProcessors[e.Message];if(t!==void 0){if(!t(e))return}else this.handleStandardMessage(e);return e}async handleClose(e){if(typeof e=="string")this.logger.warn(`Handling connection close event. Reason: ${e}`);else{const{code:s,reason:o,wasClean:i,type:a}=e;this.logger.warn("Handling connection close event.",{code:s,reason:o,wasClean:i,type:a})}this.onCleanupRequests&&this.onCleanupRequests(),!this.shouldRestartSubscriptions&&this.onCleanupSubscriptions&&this.onCleanupSubscriptions(),this.keepAliveIntervalHandle&&(clearInterval(this.keepAliveIntervalHandle),this.keepAliveIntervalHandle=null),this.state=0,this.compressor.reset(),this.peerInfo=null,this.messageReceiveTimeout&&(clearTimeout(this.messageReceiveTimeout),this.messageReceiveTimeout=null),typeof e=="string"&&e.includes("DisconnectionMessage")&&(this.logger.debug("Disconnect message received. Preventing reconnect. Potential authentication failure."),this.options.shouldReconnectOnConnectionLoss=!1),this.auth.reconnectable&&this.options.shouldReconnectOnConnectionLoss?(this.onMessage=null,await this.reconnect()):(this.onClose&&this.onClose(e),this.onMessage=null,this.onClose=null,this.onError=null)}async reconnect(){for(;!this.isAuthenticated();){this.compressor.reset(),this.peerInfo=null,this.state=3;try{const e=this.reconnectDelays.length-1;let t=this.reconnectDelays[this.reconnectCounter]??this.reconnectDelays[e];t+=Math.floor(Math.random()*50);const r=this.reconnectCounter?`(${this.reconnectCounter} attempts)`:"";this.logger.warn(`Trying to reconnect. Waiting ${t} ms ${r}`),this.reconnectCounter++,await this.open(t),this.shouldRestartSubscriptions&&this.restartSubscriptions&&this.restartSubscriptions()}catch(e){this.logger.error("Failed to reconnect",e)}}this.reconnectCounter=0}handleWsError(e){this.close().then(()=>{this.logger.error("Connection closed due to WebSocket error")}),this.logger.error("WebSocket error: ",e),this.onError&&this.onError(e)}preSubmit(e){if(e.Message){const t=this.returnAndAssignJobIdToMessage(e);return this.logger.trace("PreSubmit",{message:e.Message,jobId:t}),t}throw new TypeError("Expected message type. Must be JSON message object or Array of JSON message objects")}async sendKeepAliveMessage(){const e=Date.now()-this.timestampOfLastMessageSent,t=this.options.maximum_idle_interval/1e3/2;if(!(this.timestampOfLastMessageSent>0&&e>t))return;const s=this.options.enablePingPongKeepalive??Uo()?new ht().getPtlMessage():{Message:"KeepAliveMessage",Version:2};await this.submit(s)}async sendDisconnectionMessage(e="client shutdown",t=64){const r={Message:"Foundation::DisconnectionMessage",Version:3,reason:{value:t},details:e};await this.submit(r),await this.handleClose("Disconnected by User.")}returnAndAssignJobIdToMessage(e){if(typeof e!="object")throw new TypeError(`expected object, not ${typeof e}`);if(typeof e.Message>"u")throw new TypeError("expected object to have a 'Message' member");return!/Request$/.exec(e.Message)||typeof e.header>"u"?null:(e.header.id_job||(this.jobId=this.jobId>=Number.MAX_SAFE_INTEGER?1:this.jobId+1,e.header.id_job=this.jobId),e.header.id_job)}setLogger(e){this.logger=e}};nn.DEFAULT_OPTIONS={payload_content:"foundation",deployment_stage:30,logger:it.getLogger(_o),loglevel:y.WARN,maximum_idle_interval:45e6,host:"frontgate-eu.show.factsetdigitalsolutions.com",port:443,tls:!0,path_prefix:"",encoding:"jsjsonc-v2",split_authentication_token_second_factor:void 0,shouldReconnectOnConnectionLoss:!0,connectionTimeoutInMs:Eo,sessionHandling:!1};let jt=nn;var pe=null;typeof WebSocket<"u"?pe=WebSocket:typeof MozWebSocket<"u"?pe=MozWebSocket:typeof global<"u"?pe=global.WebSocket||global.MozWebSocket:typeof window<"u"?pe=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(pe=self.WebSocket||self.MozWebSocket);class ze{constructor(){this.promiseFinally=async(e,t)=>{const r=o=>(t(),o),s=async o=>(t(),Promise.reject(o));return Promise.resolve(e).then(r,s)},this._id=null,this._delay=null}static async wrap(e,t,r=""){return new ze().wrap(e,t,r)}get id(){return this._id}get delay(){return this._delay}async set(e,t=""){return new Promise((r,s)=>{this.clear();const o=t?()=>{s(new Dr(t))}:r;this._id=setTimeout(o,e),this._delay=e})}async wrap(e,t,r=""){const s=this.promiseFinally(e,()=>{this.clear()}),o=this.set(t,r);return Promise.race([s,o])}clear(){this._id&&clearTimeout(this._id)}}class lt extends jt{constructor(e,t){if(typeof pe>"u")throw new Oo("WebSocketClient not supported, WebSocket() missing in JavaScript environment");super(e,lt.sanitizeOptions(t)),this.ws=null;const{encoding:r}=this.options;if(!Se.isSupportedEncoding(r))throw new ko(`Unknown or unsupported encoding: ${r}`);this.onReceiveTimeout=()=>{this.logger.debug("onReceiveTimeout: Closing connection"),super.close().then(()=>{var s;(s=this.ws)==null||s.close()})}}async openConnection(){this.state===Ie.RECONNECTING&&this.auth.onReconnect&&await this.auth.onReconnect(),this.logger.info("Opening new connection",{host:this.options.host});try{await this.openWebSocket()}catch(e){throw this.logger.error("Problem opening connection",e),new Co(e.message,e)}this.logger.info(`Performing ${this.auth.constructor.name}`);try{await this.performAuthentication(),this.logger.debug("WebSocket authenticated")}catch(e){throw this.logger.error("Authentication problem occurred:",e),new Ro(e.message,e)}this.ws&&(this.ws.onclose=this.handleClose.bind(this),this.ws.onerror=this.handleWsError.bind(this))}async performAuthentication(){await new Promise((e,t)=>{this.ws?(this.ws.onclose=()=>{this.state=Ie.DISCONNECTED,t(new Error("Connection closed by server. Check credentials."))},this.ws.onerror=r=>{this.close(),t(new Error(`WebSocket error during authentication: ${r.message}`))},this.auth.authenticate(this).then(e).catch(t)):t(new Error("WebSocket not initialized"))}),this.handleAuthentication()}async open(e){this.onConnect&&(this.logger.trace("onConnect()"),this.onConnect());const t=this.options.connectionTimeoutInMs,r=`Connection timeout after ${t} ms`,s=async o=>o instanceof Dr&&!this.pendingConnection?Promise.resolve():Promise.reject(o);if(this.isPendingConnection()&&this.pendingConnection){this.connectionCounter++;const o=Date.now();return this.logger.warn(`Waiting for pending connection (${this.connectionCounter}) with a timeout of ${t} ms`),ze.wrap(this.pendingConnection,t,r).catch(s).then(()=>{const i=Date.now()-o;this.logger.warn(`Pending connection (${this.connectionCounter}) resolved after ${i} ms`)})}return e?(this.logger.debug(`Opening ${e} ms delayed connection with a timeout of ${t} ms`),this.pendingConnection=Fo(e).then(async()=>ze.wrap(this.openConnection(),t,r)).catch(s).finally(()=>{this.clearPendingConnection()}),this.pendingConnection):(this.logger.debug(`Opening connection with a timeout of ${t} ms `),this.pendingConnection=ze.wrap(this.openConnection(),t,r).catch(s).finally(()=>{this.clearPendingConnection()}),this.pendingConnection)}async close(e=!1,t=!1){this.logger.info("Closing connection explicitly"),this.options.shouldReconnectOnConnectionLoss=e,await super.close(),this.ws&&(this.clearPendingConnection(),this.ws.onclose=this.handleClose.bind(this),this.ws.close(),this.state=Ie.DISCONNECTED),t&&!e&&this.options.sessionHandling&&this.hasActiveSession&&(this.logger.info("Session logout"),await this.openWebSocket(!0))}send(e){const t=this.preSubmit(e),r=this.submit(e);return r.idJob=t,r}async submit(e){this.timestampOfLastMessageSent=Date.now();const t=new Promise(r=>{switch(this.logger.debug(`Sending ${e.Message}`,{...e}),this.sendMessage(e),this.resolveOnMessage=r,e.Message){case"Foundation::DisconnectionMessage":case"Foundation::KeepAliveMessage":case"Foundation::PingRequest":r({Message:"This message does not have a response",Version:1});break}});return t.catch(r=>{const s=new Date(this.timestampOfLastMessageSent);this.logger.error(`Failed sending ${e.Message}`,r,{request:e,lastMsgDate:s})}),t}sendMessage(e){var r;let t=JSON.stringify(e);Se.isCompressedJson(this.options.encoding)&&(t=this.compressor.compress(t)),(r=this.ws)==null||r.send(t)}async openWebSocket(e=!1){return this.logger.debug("Open WebSocket"),new Promise((t,r)=>{const{encoding:s,tls:o,host:i,port:a,path_prefix:c,frontgateSplitAuthenticationTokenSecondFactor:h,webSocketClientOptions:u,sessionHandling:l,frontgateAuthenticationToken:b}=this.options,T=`${o?"wss":"ws"}://${i}:${a}${c}/ws`,[_,A]=s.split("-"),m=[`${A?`${A}.`:""}ws-${_}.mdgms.com`];h?(m.push(`mdg2auth-${h}`),this.options.frontgateSplitAuthenticationTokenSecondFactor=null):l&&(e?m.push("mdg2wstoken-0"):this.clientOptions.otpToken?(m.push(`mdg2wstoken-${En(this.clientOptions.otpToken)}`),this.clientOptions.otpToken=""):b?typeof window<"u"&&m.push(`mdg2wstoken-${En(b)}`):m.push("mdg2wstoken-1")),this.state=Ie.CONNECTING,u?this.ws=new pe(T,m,u):this.ws=new pe(T,m),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{this.logger.info("WebSocket connected",{wsUrl:T,subProtocols:m}),e&&(this.logger.info("User logged out"),this.ws&&this.ws.close()),this.hasActiveSession=!e&&l,t()},this.ws.onclose=E=>{this.state=Ie.DISCONNECTED;const M=E.reason?`: ${E.reason}`:"";r(new Error(`Connection closed while trying to connect${M}`))},this.ws.onerror=this.handleWsError.bind(this),this.ws.onmessage=this.onWebSocketMessage.bind(this)})}onWebSocketMessage(e){if(this.state===Ie.DISCONNECTED){this.logger.warn("onWebSocketMessage while state is disconnected",{data:e.data});return}const t=this.decodeMessage(e.data),r=this.handleMessage(t);this.logger.debug(`Received ${t.Message}`,t),r&&this.resolveOnMessage(r)}decodeMessage(e){const{encoding:t}=this.options;try{if(e instanceof ArrayBuffer&&Se.isCompressedJson(t)){const r=this.compressor.decompress(new Uint8Array(e));return JSON.parse(r)}if(typeof e=="string"&&Se.isPlainJson(t))return JSON.parse(e)}catch(r){this.logger.error("Decoding message failed",r)}return String(e.constructor.name)==="Buffer"?e:(this.logger.error(`Could not decode Message of type "${typeof e}" with encoding "${t}".`),{Message:`Invalid Message Type ${typeof e}`,Version:1})}static sanitizeOptions(e={}){return e.frontgateHost&&(e.host=e.frontgateHost),e.frontgatePathPrefix&&(e.path_prefix=e.frontgatePathPrefix),e.frontgateSplitAuthenticationTokenSecondFactor&&(e.split_authentication_token_second_factor=e.frontgateSplitAuthenticationTokenSecondFactor),e.frontgateWebsocketProtocol&&(e.encoding=e.frontgateWebsocketProtocol),e.deploymentStage&&(e.deployment_stage=e.deploymentStage),e}handleWsError(e){typeof process<"u"&&this.close(this.options.shouldReconnectOnConnectionLoss).then(()=>{this.logger.error("Connection closed due to WebSocket error")}),this.logger.error("WebSocket error: ",e),this.onError&&this.onError(e)}}var $r=(n=>(n.FRONTGATE_HOST="frontgate-host",n.FRONTGATE_PATH_PREFIX="frontgate-path-prefix",n.FRONTGATE_SPLIT_AUTHENTICATION_TOKEN_SECOND_FACTOR="frontgate-split-authentication-token-second-factor",n.FRONTGATE_AUTHENTICATION_TYPE="frontgate-authentication-type",n.FRONTGATE_AUTHENTICATION_TOKEN="frontgate-authentication-token",n.FRONTGATE_WEBSOCKET_PROTOCOL="frontgate-websocket-protocol",n))($r||{});function $o(n){const e=[];if(n)for(let t=0;t<n.length;t++)e.push(n.readInt8(t));return e}function Lr(n){const e={},t=Object.keys(n);return["frontgate-host","frontgate-path-prefix","frontgate-split-authentication-token-second-factor","frontgate-authentication-type","frontgate-authentication-token","frontgate-websocket-protocol"].forEach(r=>{t.includes(r)&&(e[r.replace(/-([a-z])/g,s=>s[1].toUpperCase())]=n[r])}),e}function Hr(n){const e={};return n.forEach((t,r)=>{e[r]=t}),e}async function Dt(n,e){const t=await fetch(n,e),r=Hr(t.headers);return{config:Lr(r),response:t}}function qr(n={},e,t){const r=n.frontgateAuthenticationType==="token"?new Cn(n.frontgateAuthenticationToken):new On;return r.setFetchConfiguration(e,t),new lt(r,n)}function Gr({frontgateHost:n,frontgateWebsocketProtocol:e}){localStorage.setItem("mdg2config",JSON.stringify({frontgateHost:n,frontgateWebsocketProtocol:e}))}function Br(){const n=localStorage.getItem("mdg2config");return n?JSON.parse(n):null}function Jr(n){return n.name==="Foundation::ErrorResponse"}function Wr(n){return n.name==="Foundation::PermissionDeniedResponse"}function zr(n){return n.name==="Foundation::HighLevelResponse"}function Vr(n){return n.Message==="Foundation::HighLevelResponse"}function Yr(n){return n.name==="Foundation::RejectResponse"}function xt(n){return n.name==="Foundation::HighLevelUpdate"}function Kr(n){return n.name==="Foundation::SubscriptionLossMessage"}const Qr={version:"6.9.1",package:"@factset/frontgate-js-sdk"};function Lo(){const n=Ho();return{userAgent:n.userAgent,platform:n.platform,version:Qr.version,package:Qr.package,mobile:/Mobi/i.test(n.userAgent)}}function Ho(){return typeof navigator<"u"?navigator:typeof process<"u"?{userAgent:`node.js/io.js, ${process.version}`,platform:`${process.platform}_${process.arch}`}:{userAgent:"unknown",platform:"unknown"}}const qo=n=>{const e=[18,20,9],t=r=>{for(let s=r.length;s>r.length-16;s-=2){let o=parseInt(r.substring(s-2,s),16);o>127&&(o-=256),e.push(o)}};return t(n.traceId),e.push(17),t(n.spanId),e.push(24),e.push(0),e},Go=async(n,e)=>new Promise((t,r)=>{setTimeout(()=>{r(e)},n)}),ge=async(n,e,t)=>Promise.race([Go(n,e),t]),Xr=n=>n+Math.random()*100,ue=class ue{constructor(){this.headerMembers={dataset:{id_dataset:0},id_job:0,flags_r2:0,resend_counter:0,timeout:wn,authentication_identifiers:{id_application:0,id_user:0},cache_key:{value:[]},previous_response_hash:{value:[]},tracing:{value:{value:[]}}},this.flags=[]}getPtlMessage(){return this.headerMembers}getQuality(){return Object.keys(ue.PRICE_QUALITY).find(t=>ue.PRICE_QUALITY[t]===this.headerMembers.dataset.id_dataset)}setQuality(e){this.headerMembers.dataset.id_dataset=ue.PRICE_QUALITY[e]}setIdApplication(e,t=!1){(this.headerMembers.authentication_identifiers.id_application===0||t)&&(this.headerMembers.authentication_identifiers.id_application=e)}setIdUser(e,t=!1){(this.headerMembers.authentication_identifiers.id_user===0||t)&&(this.headerMembers.authentication_identifiers.id_user=e)}setFlag(e,t=!0){const r=this.flags.indexOf(e);t&&r===-1&&this.flags.push(e),!t&&r>-1&&this.flags.splice(r,1),this.headerMembers.flags_r2=this.getFlagsValue()}getFlagsValue(){return this.flags.reduce((e,t)=>e+ue.FLAG_VALUE[t],0)}isFlagValueSet(e){return this.flags.find(t=>t===e)!==void 0}setJobId(e){this.headerMembers.id_job=e}getJobId(){return this.headerMembers.id_job}countResend(){this.headerMembers.resend_counter++}getResendCounter(){return this.headerMembers.resend_counter}setTimeout(e){if(e>0){this.headerMembers.timeout=e;return}throw new Error(`Attempted to set the timeout to "${e}". The timeout must be greater than 0.`)}getTimeout(){return this.headerMembers.timeout}setTracing(e){/^0+$/.test(e.traceId)||(this.headerMembers.tracing.value.value=qo(e))}static getDataSet(e){return Object.prototype.hasOwnProperty.call(ue.PRICE_QUALITY,e)?ue.PRICE_QUALITY[e]:ue.PRICE_QUALITY.DLY}};ue.PRICE_QUALITY={RLT:129,DLY:0,EOD:130},ue.FLAG_VALUE={add_subscription:1,no_merge:2,support_caching:4,permission_denied_response:8,internal_client:16,current_state_refresh:32,subscription_use_pull_permissions:64,allow_chunked_response:128};let ft=ue;class Ve{constructor(e,t){this.header=new ft,this.coreMembers={Message:e,Version:t},this.members={}}getPtlMessage(){const e={header:this.header.getPtlMessage()};return jo(this.coreMembers,e,this.members)}}class dt{constructor(e,t){this.token=e,this.maximumIdleInterval=t}toJson(){const e=Lo();return{Message:"AuthenticationByTokenRequest",Version:1,token:{value:this.token},software:JSON.stringify(e),os:e.platform,feature_flags_wanted:{value:0},maximum_idle_interval:this.maximumIdleInterval,maximum_receivable_message_size:1048576,flags:0,cache_authentication_salt:{value:[]},cache_authentication_encrypted_secret:{encrypted_secret:[]}}}}const he=class he extends Ve{constructor(e,t,r,s,o=!1){super(he.NAME,he.VERSION),t&&this.header.setIdUser(t),r&&this.header.setIdApplication(r),s&&this.header.setTimeout(s),this.members.flags=o?he.FLAG_SINGLE_USAGE:0,this.members.lifetime_seconds_r2=e??he.LIFETIME_SECONDS_DEFAULT,this.header.setFlag("no_merge")}};he.NAME="AuthenticationTokenRequest",he.VERSION=6,he.LIFETIME_SECONDS_DEFAULT=-1,he.LIFETIME_SECONDS_MAXIMUM=-2,he.FLAG_SINGLE_USAGE=1;let je=he;const nt=class nt extends Ve{constructor(e){super(nt.NAME,nt.VERSION),this.members.id_job_subscription=e}};nt.NAME="CancelSubscriptionRequest",nt.VERSION=6;let Ae=nt;const le=class le extends Ve{constructor(e,t,r={},s){super(le.NAME,le.VERSION),this.members.accept="application/json",this.members.content_type="application/json",this.members.body={value:[]},this.members.query="",this.members.path=t,this.setMethod(e),Object.keys(r).length>0&&(e==="POST"?this.setBody(r):this.setQuery(r)),s&&this.setOptions(s)}setOptions(e){Object.hasOwnProperty.call(e,"accept")&&(this.members.accept=e.accept),Object.hasOwnProperty.call(e,"content_type")&&(this.members.content_type=e.content_type),Object.hasOwnProperty.call(e,"subscribe")&&e.subscribe&&this.header.setFlag("add_subscription"),Object.hasOwnProperty.call(e,"no_merge")&&e.no_merge&&this.header.setFlag("no_merge"),Object.hasOwnProperty.call(e,"allowChunkedResponse")&&e.allowChunkedResponse&&this.header.setFlag("allow_chunked_response"),Object.hasOwnProperty.call(e,"idApplication")&&e.idApplication&&this.header.setIdApplication(e.idApplication),Object.hasOwnProperty.call(e,"idUser")&&e.idUser&&this.header.setIdUser(e.idUser)}setMethod(e){const t=e==="POST"?le.METHOD.POST:le.METHOD.GET;this.members.method={value:t}}setBody(e={}){e instanceof Array?this.members.body={value:e}:this.members.body={value:JSON.stringify(e)}}getData(){return this.members.method.value===le.METHOD.POST?le.ptlToJsonData(this.members.body.value):this.members.query}setQuery(e={}){this.members.query=Object.keys(e).map(t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`).join("&")}static ptlToJsonData(e){if(typeof e=="string")return JSON.parse(e);if(e instanceof Array&&e.length>0){let t="";return e.forEach(r=>{t+=String.fromCharCode(r)}),JSON.parse(t)}}};le.NAME="HighLevelRequest",le.VERSION=3,le.METHOD={GET:1,POST:2};let ve=le;const oe=class oe extends Ve{constructor(e,t,r){super(oe.NAME,oe.VERSION),this.members.request={headers:{values:[{key:"accept",value:"application/json"},{key:"content-type",value:"application/json"}]},protocol:{value:oe.PROTOCOL.HTTPS},host:"",port:0,path:t,query:"",body:{value:[]}},this.setQuery(),this.setMethod(e),r&&this.setOptions(r)}setOptions(e){e.no_merge&&this.header.setFlag("no_merge"),e.idApplication&&this.header.setIdApplication(e.idApplication),e.idUser&&this.header.setIdUser(e.idUser),e.protocol&&(this.members.request.protocol=e.protocol.toUpperCase()==="HTTP"?{value:oe.PROTOCOL.HTTP}:{value:oe.PROTOCOL.HTTPS}),e.method&&(this.members.request.method={value:oe.METHOD[e.method]}),e.host&&(this.members.request.host=e.host),e.port&&(this.members.request.port=e.port),e.path&&(this.members.request.path=e.path),e.query&&(this.members.request.query=typeof e.query=="string"?e.query:Object.keys(e.query).map(t=>`${encodeURIComponent(t)}=${encodeURIComponent(e.query[t])}`).join("&")),e.body&&this.setBody(e.body),e.headers&&this.setHeaders(e.headers)}setHeaders(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const r=e[t],s=this.members.request.headers.values.findIndex(i=>i.key===t);s!==-1&&this.members.request.headers.values.splice(s,1),this.members.request.headers.values.push({key:t,value:r})}}setQuery(){if(this.members.request.path.includes("?")){const e=this.members.request.path.split("?");this.members.request.path=e[0],this.members.request.query=e[1]}}setMethod(e){this.members.request.method={value:oe.METHOD[e]}}setBody(e={}){return e instanceof Array||typeof e=="string"?this.members.request.body={value:e}:this.members.request.body={value:JSON.stringify(e)},this}getData(){var e;if((e=this.members.request.body)!=null&&e.value)return ve.ptlToJsonData(this.members.request.body.value)}};oe.NAME="HTTPProxyRequest",oe.VERSION=2,oe.PROTOCOL={HTTP:1,HTTPS:2},oe.METHOD={GET:1,POST:2,OPTIONS:3,HEAD:4,PUT:5,DELETE:6,TRACE:7,CONNECT:8};let Ye=oe;class Zr extends Ve{constructor(e){super(e.Message,e.version?e.version:e.Version),this._extractRequestAttributes(e)}_extractRequestAttributes(e){for(const t of Object.keys(this.coreMembers))delete e[t];this.members=jr(this.members,e)}}class Mn{static createFromString(e){return Mn.createFromObject(JSON.parse(e))}static createFromObject(e){const{header:t}=e;return t&&(t.id_job&&delete t.id_job,t.resend_counter&&delete t.resend_counter),new Zr(e)}}class ne{constructor(e){this.raw=e}get msg(){return this.raw}get name(){return this.raw.Message}get jobId(){return this.raw.header.id_job}get serviceId(){return this.raw.header.id_service}isUpdateMessage(){return Object.hasOwnProperty.call(this.raw,"header")&&(Object.hasOwnProperty.call(this.raw.header,"id_service")||Object.hasOwnProperty.call(this.raw.header,"id_job"))&&this.raw.Message.endsWith("Update")}isLossMessage(){return Object.hasOwnProperty.call(this.raw,"header")&&(Object.hasOwnProperty.call(this.raw.header,"id_service")||Object.hasOwnProperty.call(this.raw.header,"id_job"))&&(this.raw.Message.endsWith("LossMessage")||this.raw.Message.endsWith("Loss"))}}class Sn extends ne{constructor(e){if(super(e),!this.raw.token.value.b64)throw new Error("Token not set in AuthenticationTokenResponse");if(!this.raw.expiry.microseconds)throw new Error("Expiry not set in AuthenticationTokenResponse");this.token=this.raw.token.value.b64,this.expiry=parseInt(Nt(this.raw.expiry.microseconds),10)}getToken(){return this.token}getExpiry(){return this.expiry}}class es extends ne{}class X extends ne{get reason(){return this.raw.details}get jobId(){return this.raw.id_job}}class In extends ne{constructor(e){super(e);try{this.responseData=JSON.parse(this.raw.body.value)}catch(t){throw new Error(`Could not parse HighLevelResponse: ${t.message}`)}}get data(){return this.responseData.data}get meta(){return this.responseData.meta}get status(){return this.meta.status}get statusCode(){return this.status.code}}class An extends ne{constructor(e){super(e);try{const t=this.raw.response.body.value,r=t.substr(0,1)==="{";this.responseData=r?JSON.parse(t):t}catch(t){throw new Error(`Could not parse HTTPProxyResponse: ${t}`)}this.responseInfo=this.raw.info,this.statusReason=this.raw.response.status_reason,this.statusCode=this.raw.response.status_code.value}get data(){return this.responseData}get meta(){return this.responseData.meta}get status(){return{code:this.statusCode,reason:this.statusReason}}}class ts extends ne{get reason(){return this.raw.details}}class ns extends ne{get reason(){return this.raw.details}get jobId(){return this.raw.id_job}}const Bo=Object.freeze(Object.defineProperty({__proto__:null,AuthenticationTokenResponse:Sn,CancelSubscriptionResponse:es,ErrorResponse:X,HTTPProxyResponse:An,HighLevelResponse:In,Mdg2Response:ne,PermissionDeniedResponse:ts,PingResponse:We,RejectResponse:ns},Symbol.toStringTag,{value:"Module"}));class Ft extends ne{constructor(e){if(super(e),typeof this.raw.body.value!="string")throw new Error("Incorrect response type in HighLevelUpdate");try{this.responseData=JSON.parse(this.raw.body.value)}catch(t){throw new Error(`Could not parse HighLevelUpdate: ${t.message}`)}}get data(){return this.responseData}}class Ut extends ne{constructor(e){super(e),this.reason=e.reason}get reasonValue(){return this.reason.value}}const Jo=Object.freeze(Object.defineProperty({__proto__:null,HighLevelUpdate:Ft,SubscriptionLossMessage:Ut},Symbol.toStringTag,{value:"Module"}));class Cn extends Rt{constructor(e,t=!0){if(super(-2,-2),t&&(!e||e.length<80))throw new Error("Invalid token passed to TokenAuthentication");this.setToken(e)}setToken(e){this.token=Do(e)?xo(e):e}setFetchConfiguration(e,t){this.fetchConfigurationInput=e,this.fetchConfigurationConfig=t}async authenticate(e){this.connection=e;const t=await this.sendAuthenticationByTokenRequest(),r=this.peerInfoFromMessage(t);this.connection.setPeerInfo(r)}async sendAuthenticationByTokenRequest(){const e={b64:this.token},t=new dt(e,this.connection.options.maximum_idle_interval);return await this.connection.submit(t.toJson())}get reconnectable(){return!!this.fetchConfigurationInput}async onReconnect(){if(this.fetchConfigurationInput){const{config:e}=await Dt(this.fetchConfigurationInput,this.fetchConfigurationConfig);e.frontgateAuthenticationType==="token"&&e.frontgateAuthenticationToken&&this.setToken(e.frontgateAuthenticationToken)}}}class On extends Cn{constructor(){super("",!1)}getEncodedToken(){return[]}async onReconnect(){if(this.fetchConfigurationInput){const{config:e}=await Dt(this.fetchConfigurationInput,this.fetchConfigurationConfig);e.frontgateSplitAuthenticationTokenSecondFactor&&(this.connection.options.frontgateSplitAuthenticationTokenSecondFactor=e.frontgateSplitAuthenticationTokenSecondFactor)}}}class rs{constructor(e){const t=En(e),r=Math.ceil(t.length/2);this.firstFactor=t.substring(0,r),this.secondFactor=t.substring(r)}getFirstFactor(){return this.firstFactor}getSecondFactor(){return this.secondFactor}}const rn=class rn{constructor(e,t){this.cb=e,this.conn=t,this.isRequestPending=!1,this.request=new ht}start(e){if(this.timeout!==void 0)throw new Error("LatencyTracker already running!");this.conn.setMessageProcessor("Foundation::PingResponse",this.handlePingResponse.bind(this)),this.timeout=setInterval(()=>{if(!this.conn.isAuthenticated()){this.cb(void 0,void 0,void 0,"Skipping ping request, connection not authenticated!");return}if(this.isRequestPending){if(Date.now()-this.request.timeAtSender<rn.MAX_RESPONSE_LATENCY_MS){this.cb(this.request.timeAtSender,void 0,void 0,"Skipping ping request, previous request pending!");return}this.cb(this.request.timeAtSender,void 0,void 0,"Clearing ping request, previous request exceeded timeout!")}this.isRequestPending=!0,this.request.resetTimeAtSender(),this.conn.send(this.request.getPtlMessage())},e),typeof window>"u"&&this.timeout.unref()}stop(){clearInterval(this.timeout),this.timeout=void 0,this.isRequestPending=!1,this.conn.removeMessageProcessor("Foundation::PingResponse")}handlePingResponse(e){const t=new We(e);return this.cb(t.timeOfRequest,t.latencyTotal,t.latencyAtPeer,void 0),this.isRequestPending=!1,!1}};rn.MAX_RESPONSE_LATENCY_MS=60*1e3;let Rn=rn;const Wo=()=>Z(e=>class extends e{async requestAuthenticationToken(t=30,r=0,s=0,o=this.defaultTimeoutInMs){const a={message:new je(t,r,s,o).getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",a);const c=new Promise((u,l)=>{this.hooks.hookOnce(`frontgateConnection:response:${a.callbackId}`,b=>{if(!b.Message.includes("AuthenticationTokenResponse")){l(JSON.stringify(b));return}const f=new Sn(b);u({token:f.getToken(),expiry:f.getExpiry()})})}),h=`Request timeout reached (${o} ms) for ${a.message.Message}`;return ge(o,h,c)}},{featureName:"AuthTokenRequest",featureGroups:["Misc"]}),$t=8,ss={...Bo,...Jo},rt=class rt{static createMessage(e){if(!e)throw new Error(`Could not create message because msg is "${e}"`);if(!e.Message||typeof e.Message!="string")throw new Error(`Could not create message because msg.Message is "${e.Message}"`);const t=e.Message.indexOf(rt.msgNameSeparator);if(t===-1)throw new Error(`Could not create message for invalid msg.Message "${e.Message}"`);if(!(e!=null&&e.header))throw new Error("Could not create message because the header is missing in the msg");try{const r=e.Message.substring(t+rt.msgNameSeparatorLength);return ss[r]?new ss[r](e):new ne(e)}catch(r){throw new Error(`Could not create message "${e.Message}": ${r.message}`)}}static hasNextChunk(e){var t;return((((t=e.header)==null?void 0:t.flags)??0)&$t)===$t}};rt.msgNameSeparator="::",rt.msgNameSeparatorLength=2;let Lt=rt;const zo=n=>Z(t=>{var r,Ls,o;return o=class extends t{constructor(){super(...arguments);k(this,r)}async requestEndpoint(a,c,h,u,l=this.defaultTimeoutInMs){const b=new ve(a,c,h,{...u,allowChunkedResponse:!(n!=null&&n.disableChunkedResponse)});b.header.setTimeout(l),n!=null&&n.allowPermissionDeniedResponse&&b.header.setFlag("permission_denied_response");const f={message:b.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",f);const T=new Promise((A,w)=>{const m=[],E=()=>{this.hooks.hookOnce(`frontgateConnection:response:${f.callbackId}`,M=>{var S,C,N,g;try{if(!M.Message.includes("HighLevelResponse")){w(JSON.stringify(M));return}if(H(this,r,Ls).call(this,M))m.push({body:((N=M.body)==null?void 0:N.value)??"",processingTime:((g=M.header)==null?void 0:g.processingTime)??0}),E();else{m.push({body:((S=M.body)==null?void 0:S.value)??"",processingTime:((C=M.header)==null?void 0:C.processingTime)??0});const p=new In({...M,body:{value:m.map(I=>I.body).join("")},header:{...M.header,processingTime:m.reduce((I,O)=>I+O.processingTime,0)}});A({response:p,data:p.data})}}catch(p){w(p)}})};E()}),_=`Request timeout reached (${l} ms) for ${f.message.Message}`;return ge(l,_,T)}},r=new WeakSet,Ls=function(a){var c;return((((c=a.header)==null?void 0:c.flags)??0)&$t)===$t},o},{featureName:"EndpointRequest",featureGroups:["Misc"]}),os=n=>Z(t=>{var r,s,o,i,a,c,h,u,on,b,f,Hs,qs,Ot,lr,Gs,fr,Bs,Js,C;return C=class extends t{constructor(...g){super(...g);k(this,u);k(this,r);k(this,s);k(this,o,"disconnected");k(this,i);k(this,a,0);k(this,c);k(this,h);k(this,b);k(this,f,[]);R(this,c,-2),R(this,h,-1),n&&(this.conf=n),this.hooks.hook("frontgateConnection:setIdApp",p=>{R(this,c,p)}),this.hooks.hook("frontgateConnection:setIdUser",p=>{R(this,h,p)}),this.hooks.hook("frontgateConnection:sendMessage",p=>{if(p.callbackType==="job"){const I=H(this,u,Gs).call(this,p.message);p.callbackId=`${I}`,H(this,u,fr).call(this,p.message)}if(v(this,u,on)==="connected"&&p.callbackType==="response")H(this,u,Ot).call(this,p.message);else if(v(this,u,on)==="authenticated")H(this,u,Ot).call(this,p.message);else{if(v(this,f).length>=v(this,b))throw new Error("Message buffer is full");v(this,f).push(p)}}),this.hooks.hook("frontgateConnection:authenticated",()=>{if(!v(this,s))throw new Error("No connection configuration set");for(this.log(y.DEBUG,"Draining message buffer");v(this,f).length>0;){const p=v(this,f).shift();p&&(H(this,u,fr).call(this,p.message),H(this,u,Ot).call(this,p.message))}R(this,i,setInterval(()=>{this.log(y.DEBUG,"Sending keepalive"),this.hooks.callHook("frontgateConnection:sendMessage",{message:H(this,u,qs).call(this),callbackType:"response",callbackId:"KeepAliveMessage"})},v(this,s).maximumIdleIntervalInS/2*1e3))}),this.hooks.hook("reconnect:attempt",async()=>{clearInterval(v(this,i)),this.log(y.DEBUG,"Reconnecting"),await this.hooks.callHook("frontgateConnection:reset");try{await this.connect(),await this.hooks.callHook("reconnect:success")}catch(p){this.log(y.ERROR,"Reconnect failed",p),await this.hooks.callHook("reconnect:failed",p)}})}set conf(g){const p=H(this,u,Js).call(this,g);R(this,b,p.messageBufferSize),R(this,s,p)}async connect(){if(!v(this,s))throw new Error("No connection configuration set");if(v(this,u,on)!=="disconnected")throw new Error("Client is already connected or is connecting right now");const{host:g,port:p,tls:I,pathPrefix:O}=v(this,s);R(this,o,"connecting");const z=`${I?"wss":"ws"}://${g}:${p}${O??""}/ws`,P={encoding:"jsjson-v2"};await this.hooks.callHook("frontgateConnection:afterSetEncoding",P);const[F,j]=P.encoding.split("-"),V=[`${j?`${j}.`:""}ws-${F}.mdgms.com`],$={url:z,subProtocols:V};await this.hooks.callHook("frontgateConnection:beforeConnect",$),this.log(y.DEBUG,`Connecting to ${$.url} with subprotocols ${$.subProtocols}`);const Be=new Promise((fe,Y)=>{if(!v(this,s))throw new Error("No connection configuration set");v(this,s).wsClientOptions&&typeof window>"u"?R(this,r,new pe($.url,$.subProtocols,v(this,s).wsClientOptions)):R(this,r,new pe($.url,$.subProtocols)),v(this,r).binaryType="arraybuffer";let J;v(this,r).onopen=()=>{R(this,o,"connected"),this.log(y.DEBUG,"Connected"),this.hooks.callHook("frontgateConnection:connected",v(this,s)).catch(Y),J=this.hooks.hookOnce("frontgateConnection:authenticated",()=>{R(this,o,"authenticated"),this.log(y.DEBUG,"Authenticated"),fe()})},v(this,r).onclose=D=>{J==null||J(),this.log(y.DEBUG,"Disconnected",D),this.hooks.callHook("frontgateConnection:disconnected",D),(v(this,o)==="connecting"||v(this,o)==="connected")&&Y(JSON.stringify(D)),clearInterval(v(this,i)),R(this,o,"disconnected")},v(this,r).onerror=D=>{J==null||J(),this.log(y.ERROR,"Error:",D),this.hooks.callHook("frontgateConnection:error",D),(v(this,o)==="connecting"||v(this,o)==="connected")&&Y(new Error("Websocket error")),clearInterval(v(this,i)),R(this,o,"disconnected")},v(this,r).onmessage=D=>{const{data:ie}=D;this.log(y.DEBUG,"Received data:",ie);const me={msg:ie};this.hooks.callHook("frontgateConnection:afterReceiveMessage",me).then(()=>{var Je;this.log(y.DEBUG,"Received message",me.msg);const Pe=me.msg.toString("utf-8"),_e=JSON.parse(Pe);if(this.hooks.callHook("frontgateConnection:message",_e),_e.Message==="Foundation::DisconnectionMessage"){(Je=v(this,r))==null||Je.close(),this.hooks.callHook("frontgateConnection:disconnected",_e);return}H(this,u,lr).call(this,_e)})}}),ee=`Timeout reached (${this.defaultTimeoutInMs} ms) for connection to ${z}`;return ge(this.defaultTimeoutInMs,ee,Be)}async disconnect(){return new Promise(g=>{H(this,u,Ot).call(this,H(this,u,Hs).call(this)),this.hooks.hookOnce("frontgateConnection:disconnected",()=>{var p;(p=v(this,r))==null||p.close(),g()})})}isConnected(){return v(this,o)==="authenticated"}isDisconnected(){return v(this,o)!=="authenticated"}isReadyToConnect(){return v(this,o)==="disconnected"}},r=new WeakMap,s=new WeakMap,o=new WeakMap,i=new WeakMap,a=new WeakMap,c=new WeakMap,h=new WeakMap,u=new WeakSet,on=function(){return v(this,r)&&v(this,r).readyState<2?v(this,o):"disconnected"},b=new WeakMap,f=new WeakMap,Hs=function(){return{Message:"Foundation::DisconnectionMessage",Version:3,reason:{value:64},details:"client shutdown"}},qs=function(){return{Message:"KeepAliveMessage",Version:2}},Ot=async function(g){var I;await this.hooks.callHook("frontgateConnection:beforeSerializeMessage",g);const p={msg:JSON.stringify(g)};await this.hooks.callHook("frontgateConnection:beforeSendMessage",p),this.log(y.DEBUG,"Sending message:",g),this.log(y.TRACE,"Sending data:",p.msg);try{(I=v(this,r))==null||I.send(p.msg)}catch(O){const x=H(this,u,Bs).call(this,O,g);H(this,u,lr).call(this,x.msg)}},lr=function(g){var p,I;if(typeof((p=g.header)==null?void 0:p.id_job)<"u"){this.hooks.callHook(`frontgateConnection:response:${g.header.id_job}`,g);return}if(typeof((I=g.header)==null?void 0:I.id_service)<"u"&&typeof g.id_notation<"u"){this.hooks.callHook(`frontgateConnection:response:${g.header.id_service}-${g.id_notation}`,g);return}if(typeof g.id_job<"u"){this.hooks.callHook(`frontgateConnection:response:${g.id_job}`,g);return}typeof g.Message=="string"&&this.hooks.callHook(`frontgateConnection:response:${g.Message.replace("Foundation::","")}`,g)},Gs=function(g){R(this,a,v(this,a)+1);const p=v(this,a);return g.header={...g.header,id_job:p},v(this,a)},fr=function(g){var p,I;g.header||(g.header={authentication_identifiers:{id_application:void 0,id_user:void 0}}),g.header.authentication_identifiers||(g.header={...g.header,authentication_identifiers:{id_application:void 0,id_user:void 0}}),(p=g.header.authentication_identifiers).id_application||(p.id_application=v(this,c)),(I=g.header.authentication_identifiers).id_user||(I.id_user=v(this,h))},Bs=function(g,p){var I;return new X({Message:"Foundation::ErrorResponse",Version:1,id_job:(I=p.header)==null?void 0:I.id_job,reason:8,details:g})},Js=function(g){const p=g.maximumIdleIntervalInS??60,I=g.maximumIdleInterval??p*1e6;return{...g,payloadContent:g.payloadContent??"foundation",maximumIdleIntervalInS:p,maximumIdleInterval:I,tls:g.tls??!0,messageBufferSize:g.messageBufferSize??512}},C},{featureName:"WSConnection",disabledFeatureGroups:["Connection"]}),Vo=(n,e)=>(e&&n.setLevel(e),Z(r=>class extends r{constructor(...s){super(...s),this.logger=n}},{featureName:"Logger",featureGroups:["Misc"]})),Yo=()=>Z(e=>{var t,r;return r=class extends e{constructor(...o){super(...o);k(this,t);R(this,t,new Ar),this.hooks.hook("frontgateConnection:reset",()=>{v(this,t).reset()}),this.hooks.hook("frontgateConnection:afterSetEncoding",i=>{i.encoding="jsjsonc-v2"}),this.hooks.hook("frontgateConnection:beforeSendMessage",i=>{const a=v(this,t).compress(i.msg);i.msg=a}),this.hooks.hook("frontgateConnection:afterReceiveMessage",i=>{const a=v(this,t).decompress(new Uint8Array(i.msg));i.msg=a})}},t=new WeakMap,r},{featureName:"MessageCompressor",featureGroups:["Misc"]}),Ko=()=>Z(e=>class extends e{async request(t,r=this.defaultTimeoutInMs){t.header.setTimeout(r);const s={message:t.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",s);const o=new Promise(a=>{this.hooks.hookOnce(`frontgateConnection:response:${s.callbackId}`,c=>{const h=new ne(c);a(h)})}),i=`Request timeout reached (${r} ms) for ${s.message.Message}`;return ge(r,i,o)}},{featureName:"Request",featureGroups:["Misc"]}),Qo=n=>Z(t=>{var s,o;const r={...n};return o=class extends t{constructor(){super(...arguments);k(this,s,new Map)}async observeEndpoint(a,c,h,u){const l=`${a}:${c}:${JSON.stringify(h)}:${JSON.stringify(u??{})}`,b=r.timeout??this.defaultTimeoutInMs,f=r.subscriptionResubscribeTimeout??1e3;if(v(this,s).has(l)){const m=v(this,s).get(l);if(m)return m.count++,this.log(y.INFO,`Reusing existing subscription for ${l}`),m.observer}this.log(y.INFO,`Creating new subscription for ${l}`);const T=new ve(a,c,h,{...u,subscribe:!0});T.header.setTimeout(b);const _={message:T.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",_);const A=new Promise((m,E)=>{this.hooks.hookOnce(`frontgateConnection:response:${_.callbackId}`,M=>{if(!M.Message.includes("HighLevelResponse")){this.log(y.ERROR,`Unexpected response: ${M.Message}`),E(new X(JSON.stringify(M)));return}let S;try{S=JSON.parse(M.body.value)}catch(I){this.log(y.ERROR,`Failed to parse response: ${M.body.value}`),this.log(y.ERROR,I),E(I);return}const C=new is(M.header.id_job,S);let N=this.hooks.hook(`frontgateConnection:response:${_.callbackId}`,I=>{if(!I.Message.includes("HighLevelUpdate")){if(I.Message.includes("SubscriptionLoss")){this.log(y.DEBUG,`Received: ${I.Message}`),setTimeout(()=>{g()},Xr(f)),N();return}this.log(y.ERROR,`Unexpected response: ${M.Message}`),C.pushError(new X(JSON.stringify(I))),N();return}let O;try{O=new Ft(I)}catch(x){this.log(y.ERROR,`Failed to parse response: ${I.body.value}`),C.pushError(x);return}C.pushPatchData(O.data)});const g=async()=>{N(),this.log(y.INFO,`Resubscribing to ${l} due to reconnect`),await this.hooks.callHook("frontgateConnection:sendMessage",_);const I=new Promise((O,x)=>{this.hooks.hookOnce(`frontgateConnection:response:${_.callbackId}`,z=>{if(!M.Message.includes("HighLevelResponse")){const P=new X(z);this.log(y.ERROR,`Unexpected response: ${z.Message}`),N(),x(P);return}this.log(y.INFO,`Resubscribed to ${l} with ${z.header.id_job}`),C.idJob=z.header.id_job,N=this.hooks.hook(`frontgateConnection:response:${z.header.id_job}`,P=>{if(!P.Message.includes("HighLevelUpdate")){if(P.Message.includes("SubscriptionLoss")){this.log(y.DEBUG,`Received: ${P.Message}`),setTimeout(()=>{g()},Xr(f));return}this.log(y.ERROR,`Unexpected response: ${P.Message}`);const j=new X(P);C.pushError(j);return}let F;try{F=new Ft(P)}catch(j){this.log(y.ERROR,`Failed to parse response: ${P.body.value}`),C.pushError(j);return}C.unsubscribe=()=>{const j=v(this,s).get(l);if(j){if(j.count--,j.count>0){this.log(y.INFO,`Not unsubscribing from ${l} as there are still ${j.count} subscribers`);return}v(this,s).delete(l)}this.log(y.INFO,`Unsubscribing from ${l}`);const V={message:new Ae(M.header.id_job).getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",V),N(),p()},C.pushPatchData(F.data)}),O()})});try{await ge(b,"Request timeout reached",I)}catch(O){C.pushError(new X({Message:"Reconnect failed",Error:O}))}},p=this.hooks.hook("reconnect:success",g);C.unsubscribe=()=>{const I=v(this,s).get(l);if(I){if(I.count--,I.count>0){this.log(y.INFO,`Not unsubscribing from ${l} as there are still ${I.count} subscribers`);return}v(this,s).delete(l)}this.log(y.INFO,`Unsubscribing from ${l}`);const x={message:new Ae(M.header.id_job).getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",x),N(),p()},v(this,s).set(l,{observer:C,count:1}),m(C)})}),w=`Request timeout reached (${b} ms) for ${_.message.Message}`;return ge(b,w,A)}},s=new WeakMap,o},{featureName:"EndpointSubscriptions",featureGroups:["Misc"]}),Xo=()=>Z(e=>{var t,r,dr,o;return o=class extends e{constructor(){super(...arguments);k(this,r);k(this,t,new Map)}async observe(a,c=this.defaultTimeoutInMs){return H(this,r,dr).call(this,a,"job",void 0,c)}async observeConnectionBased(a,c,h=this.defaultTimeoutInMs){return H(this,r,dr).call(this,a,"connection",c,h)}},t=new WeakMap,r=new WeakSet,dr=async function(a,c,h,u=this.defaultTimeoutInMs){const l=JSON.stringify(a.getPtlMessage());if(v(this,t).has(l)){const A=v(this,t).get(l);if(A)return A.count++,this.log(y.INFO,`Reusing existing subscription for ${l}`),A.observer}this.log(y.INFO,`Creating new subscription for ${l}`);const f={message:a.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",f);const T=new Promise((A,w)=>{this.hooks.hookOnce(`frontgateConnection:response:${f.callbackId}`,m=>{if(m.Message.includes("Error")||m.Message.includes("PermissionDenied")){this.log(y.ERROR,`Unexpected response: ${m.Message}`),w(new Error(`Unexpected response: ${m.Message}`));return}const E=c==="connection"?`${m.header.id_service}-${a.getPtlMessage().id_notation}`:m.header.id_job,M=typeof h>"u"?new Ae(m.header.id_job):new h(m.header.id_service,a.getPtlMessage().id_notation),S=new Pn(m.header.id_job,m);let C=this.hooks.hook(`frontgateConnection:response:${E}`,g=>{if(g.Message.includes("Error")||g.Message.includes("PermissionDenied")){this.log(y.ERROR,`Unexpected response: ${m.Message}`),S.pushError(new X(JSON.stringify(g)));return}S.pushData(g)});const N=this.hooks.hook("reconnect:success",async()=>{C(),this.log(y.INFO,`Resubscribing to ${l} due to reconnect`),await this.hooks.callHook("frontgateConnection:sendMessage",f);const g=new Promise((p,I)=>{this.hooks.hookOnce(`frontgateConnection:response:${f.callbackId}`,O=>{if(O.Message.includes("Error")||O.Message.includes("PermissionDenied")){const P=new X(O);this.log(y.ERROR,`Unexpected resp: ${O.Message}`),I(P);return}const x=c==="connection"?`${O.header.id_service}-${a.getPtlMessage().id_notation}`:O.header.id_job,z=typeof h>"u"?new Ae(O.header.id_job):new h(O.header.id_service,a.getPtlMessage().id_notation);S.idJob=O.header.id_job,C=this.hooks.hook(`frontgateConnection:response:${x}`,P=>{if(P.Message.includes("Error")||P.Message.includes("PermissionDenied")){this.log(y.ERROR,`Unexpected response: ${P.Message}`);const F=new X(P);S.pushError(F);return}S.unsubscribe=()=>{const F=v(this,t).get(l);if(F){if(F.count--,F.count>0){this.log(y.INFO,`Not unsubscribing from ${l} as there are still ${F.count} subscribers`);return}v(this,t).delete(l)}this.log(y.INFO,`Unsubscribing from ${l}`);const j={message:z.getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",j),C(),N()},S.pushData(P)}),p()})});try{await ge(u,"Request timeout reached",g)}catch(p){S.pushError(new X({Message:"Reconnect failed",Error:p}))}});S.unsubscribe=()=>{const g=v(this,t).get(l);if(g){if(g.count--,g.count>0){this.log(y.INFO,`Not unsubscribing from ${l} as there are still ${g.count} subscribers`);return}v(this,t).delete(l)}this.log(y.INFO,`Unsubscribing from ${l}`);const p={message:M.getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",p),C(),N()},v(this,t).set(l,{observer:S,count:1}),A(S)})}),_=`Request timeout reached (${u} ms) for ${f.message.Message}`;return ge(u,_,T)},o},{featureName:"RawSubscriptions",featureGroups:["Misc"]}),kn=(n,e)=>{const t=e.split("/").slice(1);let r=n;for(let s=0;s<t.length-1;s++){const o=decodeURIComponent(t[s]);if(!(o in r))throw new Error(`Path not found: ${e}`);r=r[o]}return[r,decodeURIComponent(t[t.length-1])]},Zo=(n,e,t)=>{const[r,s]=kn(n,e);r[s]=t},ei="-",ti=(n,e,t)=>{const[r,s]=kn(n,e);Array.isArray(r)?s===ei?r.push(t):r.splice(parseInt(s,10),0,t):r[s]=t},ni=(n,e)=>{const[t,r]=kn(n,e);Array.isArray(t)?t.splice(parseInt(r,10),1):delete t[r]};function ri(n,e){return e.forEach(t=>{switch(t.op){case"replace":Zo(n,t.path,t.value);break;case"add":ti(n,t.path,t.value);break;case"remove":ni(n,t.path);break;case"move":case"copy":case"test":default:throw new Error(`Unsupported op: ${t.op}`)}}),n}class Pn{constructor(e,t){k(this,Le);k(this,Mt,[]);k(this,St,[]);R(this,Le,t),this.idJob=e}get data(){return v(this,Le)}subscribe({next:e,error:t}){e(v(this,Le)),t&&v(this,St).push(t),v(this,Mt).push(e)}pushData(e){R(this,Le,e),v(this,Mt).forEach(t=>{t(e)})}pushError(e){v(this,St).forEach(t=>{t(e)})}}Le=new WeakMap,Mt=new WeakMap,St=new WeakMap;class is extends Pn{pushPatchData(e){try{const t=ri(this.data,e);super.pushData(t)}catch(t){super.pushError(new X(t.message))}}}const si=n=>Z(t=>class extends t{constructor(...r){super(...r),this.hooks.hook("frontgateConnection:beforeConnect",o=>{this.hooks.callHook("frontgateConnection:setIdApp",-2),this.hooks.callHook("frontgateConnection:setIdUser",-2),this.log(y.DEBUG,"Adding mdg2auth subprotocol"),o.subProtocols.push(`mdg2auth-${n}`)});const s=async o=>{this.hooks.callHook("frontgateConnection:setIdApp",-2),this.hooks.callHook("frontgateConnection:setIdUser",-2);const i={maximum_idle_interval:o.maximumIdleInterval},a={b64:""},h=new dt(a,i.maximum_idle_interval).toJson();this.log(y.INFO,"Sending message",h);const u={message:h,callbackType:"response",callbackId:h.Message.replace("Request","Response")};await this.hooks.callHook("frontgateConnection:sendMessage",u),this.hooks.hookOnce(`frontgateConnection:response:${u.callbackId}`,l=>{this.log(y.INFO,"Received response",l),this.hooks.callHook("frontgateConnection:authenticated")})};this.hooks.hookOnce("frontgateConnection:connected",s)}},{featureName:"CookieTokenAuth",featureGroups:["Auth"],disabledFeatureGroups:["Auth"]}),oi=n=>Z(t=>{var r,s;return s=class extends t{constructor(...i){super(...i);k(this,r);R(this,r,n??"");const a=async c=>{this.hooks.callHook("frontgateConnection:setIdApp",-2),this.hooks.callHook("frontgateConnection:setIdUser",-2);const h={maximum_idle_interval:c.maximumIdleInterval},u={b64:v(this,r)},b=new dt(u,h.maximum_idle_interval).toJson();this.log(y.INFO,"Sending message",b);const f={message:b,callbackType:"response",callbackId:b.Message.replace("Request","Response")};await this.hooks.callHook("frontgateConnection:sendMessage",f),this.hooks.hookOnce(`frontgateConnection:response:${f.callbackId}`,T=>{this.log(y.INFO,"Received response",T),this.hooks.callHook("frontgateConnection:authenticated")})};this.hooks.hook("frontgateConnection:connected",a)}set token(i){R(this,r,i)}},r=new WeakMap,s},{featureName:"TokenAuth",featureGroups:["Auth"],disabledFeatureGroups:["Auth"]}),ii=(n,e,t)=>Z(s=>{var o,i,a,c,h,Ws,l;return l=class extends os({host:"",pathPrefix:"",port:0,tls:!0,maximumIdleIntervalInS:n.maximumIdleIntervalInS})(s){constructor(...f){super(...f);k(this,h);k(this,o,"");k(this,i,"");k(this,a);k(this,c);R(this,a,e),R(this,c,t),this.hooks.hook("frontgateConnection:beforeConnect",async _=>{this.hooks.callHook("frontgateConnection:setIdApp",-2),this.hooks.callHook("frontgateConnection:setIdUser",-2),this.log(y.DEBUG,"Fetching connection configuration");const A=await H(this,h,Ws).call(this);if(this.log(y.DEBUG,"Connection configuration received",n),_.url=A.url,A.authtenticationType==="token"&&A.authenticationToken)R(this,o,A.authenticationToken);else if(A.splitAuthenticationTokenSecondFactor)R(this,i,A.splitAuthenticationTokenSecondFactor);else throw new Error("Invalid authentication configuration");this.log(y.DEBUG,"Adding mdg2auth subprotocol"),v(this,i)!==""&&_.subProtocols.push(`mdg2auth-${v(this,i)}`)});const T=async _=>{this.hooks.callHook("frontgateConnection:setIdApp",-2),this.hooks.callHook("frontgateConnection:setIdUser",-2);const A={maximum_idle_interval:_.maximumIdleInterval},w={b64:v(this,o)},E=new dt(w,A.maximum_idle_interval).toJson();this.log(y.INFO,"Sending message",E);const M={message:E,callbackType:"response",callbackId:E.Message.replace("Request","Response")};await this.hooks.callHook("frontgateConnection:sendMessage",M),this.hooks.hookOnce(`frontgateConnection:response:${M.callbackId}`,S=>{this.log(y.INFO,"Received response",S),this.hooks.callHook("frontgateConnection:authenticated")})};this.hooks.hook("frontgateConnection:connected",T)}},o=new WeakMap,i=new WeakMap,a=new WeakMap,c=new WeakMap,h=new WeakSet,Ws=async function(){const f=await fetch(v(this,a),v(this,c));if(!f.ok)throw new Error(`Failed to fetch connection configuration: ${f.status} ${f.statusText}`);const{headers:T}=f,_=T.get("frontgate-host"),A=T.get("frontgate-path-prefix"),w=T.get("frontgate-split-authentication-token-second-factor"),m=T.get("frontgate-authentication-type"),E=T.get("frontgate-authentication-token"),M=T.get("frontgate-websocket-port")??"443",S=`wss://${_}:${M}${A??""}/ws`;if(m==="token"&&!E)throw new Error("Authentication token is required for token authentication");if(m!=="token"&&!w)throw new Error("Split authentication token second factor is required");return{url:S,authtenticationType:m,authenticationToken:E,splitAuthenticationTokenSecondFactor:w}},l},{featureName:"FetchAuth",featureGroups:["Auth","Connection"],disabledFeatureGroups:["Auth","Connection"]}),ai=(n,e)=>({options:n,submit:async t=>{e.log(y.INFO,"Sending message",t);const r={message:t,callbackType:"response",callbackId:t.Message.replace("Request","Response")};await e.hooks.callHook("frontgateConnection:sendMessage",r);let s;return new Promise((o,i)=>{const a=e.hooks.hookOnce(`frontgateConnection:response:${r.callbackId}`,c=>{clearTimeout(s),e.log(y.INFO,"Received response",c),o(c)});s=setTimeout(()=>{a(),i(new Error("Authentication message timeout"))},3e3)})},setPeerInfo:t=>{e.log(y.INFO,"Peer info:",t)}}),ci=()=>Z(e=>{var t,r,s,o;return o=class extends e{constructor(...a){super(...a);k(this,t,0);k(this,r,[1e3,2e3,4e3,8e3,16e3,32e3]);k(this,s);const c=h=>{if(h.code!==1e3){v(this,s)&&(this.log(y.WARN,"Aborting previous reconnect attempt"),clearTimeout(v(this,s)),R(this,t,0));let u=v(this,t);v(this,t)>v(this,r).length&&(u=v(this,r).length-1);const l=v(this,r)[u];R(this,s,setTimeout(()=>{this.log(y.INFO,`Reconnecting... Attempt ${v(this,t)}`);const b=this.hooks.hookOnce("reconnect:failed",c);this.hooks.callHook("reconnect:attempt",h).then(b).catch(()=>{this.log(y.ERROR,"Failed to reconnect")}),R(this,s,void 0)},l)),$s(this,t)._++}};this.hooks.hookOnce("frontgateConnection:disconnected",c),this.hooks.hook("reconnect:success",()=>{clearTimeout(v(this,s)),R(this,s,void 0),R(this,t,0),this.log(y.INFO,"Reconnected"),this.hooks.hookOnce("frontgateConnection:disconnected",c)})}},t=new WeakMap,r=new WeakMap,s=new WeakMap,o},{featureName:"Reconnect",featureGroups:["Misc"],disabledFeatures:["TokenAuth","CookieTokenAuth"]});var ui=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},De="1.9.0",as=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function hi(n){var e=new Set([n]),t=new Set,r=n.match(as);if(!r)return function(){return!1};var s={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(s.prerelease!=null)return function(c){return c===n};function o(a){return t.add(a),!1}function i(a){return e.add(a),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var h=c.match(as);if(!h)return o(c);var u={major:+h[1],minor:+h[2],patch:+h[3],prerelease:h[4]};return u.prerelease!=null||s.major!==u.major?o(c):s.major===0?s.minor===u.minor&&s.patch<=u.patch?i(c):o(c):s.minor<=u.minor?i(c):o(c)}}var li=hi(De),fi=De.split(".")[0],pt=Symbol.for("opentelemetry.js.api."+fi),gt=ui;function vt(n,e,t,r){var s;r===void 0&&(r=!1);var o=gt[pt]=(s=gt[pt])!==null&&s!==void 0?s:{version:De};if(!r&&o[n]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+n);return t.error(i.stack||i.message),!1}if(o.version!==De){var i=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+n+" does not match previously registered API v"+De);return t.error(i.stack||i.message),!1}return o[n]=e,t.debug("@opentelemetry/api: Registered a global for "+n+" v"+De+"."),!0}function xe(n){var e,t,r=(e=gt[pt])===null||e===void 0?void 0:e.version;if(!(!r||!li(r)))return(t=gt[pt])===null||t===void 0?void 0:t[n]}function bt(n,e){e.debug("@opentelemetry/api: Unregistering a global for "+n+" v"+De+".");var t=gt[pt];t&&delete t[n]}var di=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return o},pi=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},gi=function(){function n(e){this._namespace=e.namespace||"DiagComponentLogger"}return n.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return mt("debug",this._namespace,e)},n.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return mt("error",this._namespace,e)},n.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return mt("info",this._namespace,e)},n.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return mt("warn",this._namespace,e)},n.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return mt("verbose",this._namespace,e)},n}();function mt(n,e,t){var r=xe("diag");if(r)return t.unshift(e),r[n].apply(r,pi([],di(t),!1))}var re;(function(n){n[n.NONE=0]="NONE",n[n.ERROR=30]="ERROR",n[n.WARN=50]="WARN",n[n.INFO=60]="INFO",n[n.DEBUG=70]="DEBUG",n[n.VERBOSE=80]="VERBOSE",n[n.ALL=9999]="ALL"})(re||(re={}));function vi(n,e){n<re.NONE?n=re.NONE:n>re.ALL&&(n=re.ALL),e=e||{};function t(r,s){var o=e[r];return typeof o=="function"&&n>=s?o.bind(e):function(){}}return{error:t("error",re.ERROR),warn:t("warn",re.WARN),info:t("info",re.INFO),debug:t("debug",re.DEBUG),verbose:t("verbose",re.VERBOSE)}}var bi=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return o},mi=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},yi="diag",be=function(){function n(){function e(s){return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];var a=xe("diag");if(a)return a[s].apply(a,mi([],bi(o),!1))}}var t=this,r=function(s,o){var i,a,c;if(o===void 0&&(o={logLevel:re.INFO}),s===t){var h=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((i=h.stack)!==null&&i!==void 0?i:h.message),!1}typeof o=="number"&&(o={logLevel:o});var u=xe("diag"),l=vi((a=o.logLevel)!==null&&a!==void 0?a:re.INFO,s);if(u&&!o.suppressOverrideMessage){var b=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+b),l.warn("Current logger will overwrite one already registered from "+b)}return vt("diag",l,t,!0)};t.setLogger=r,t.disable=function(){bt(yi,t)},t.createComponentLogger=function(s){return new gi(s)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return n.instance=function(){return this._instance||(this._instance=new n),this._instance},n}(),wi=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return o},_i=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Ei=function(){function n(e){this._entries=e?new Map(e):new Map}return n.prototype.getEntry=function(e){var t=this._entries.get(e);if(t)return Object.assign({},t)},n.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var t=wi(e,2),r=t[0],s=t[1];return[r,s]})},n.prototype.setEntry=function(e,t){var r=new n(this._entries);return r._entries.set(e,t),r},n.prototype.removeEntry=function(e){var t=new n(this._entries);return t._entries.delete(e),t},n.prototype.removeEntries=function(){for(var e,t,r=[],s=0;s<arguments.length;s++)r[s]=arguments[s];var o=new n(this._entries);try{for(var i=_i(r),a=i.next();!a.done;a=i.next()){var c=a.value;o._entries.delete(c)}}catch(h){e={error:h}}finally{try{a&&!a.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}return o},n.prototype.clear=function(){return new n},n}();be.instance();function Ti(n){return n===void 0&&(n={}),new Ei(new Map(Object.entries(n)))}function cs(n){return Symbol.for(n)}var Mi=function(){function n(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(r){return t._currentContext.get(r)},t.setValue=function(r,s){var o=new n(t._currentContext);return o._currentContext.set(r,s),o},t.deleteValue=function(r){var s=new n(t._currentContext);return s._currentContext.delete(r),s}}return n}(),Si=new Mi,Fe=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),Ii=function(){function n(){}return n.prototype.createGauge=function(e,t){return xi},n.prototype.createHistogram=function(e,t){return Fi},n.prototype.createCounter=function(e,t){return Di},n.prototype.createUpDownCounter=function(e,t){return Ui},n.prototype.createObservableGauge=function(e,t){return Li},n.prototype.createObservableCounter=function(e,t){return $i},n.prototype.createObservableUpDownCounter=function(e,t){return Hi},n.prototype.addBatchObservableCallback=function(e,t){},n.prototype.removeBatchObservableCallback=function(e){},n}(),Ht=function(){function n(){}return n}(),Ai=function(n){Fe(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.add=function(t,r){},e}(Ht),Ci=function(n){Fe(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.add=function(t,r){},e}(Ht),Oi=function(n){Fe(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.record=function(t,r){},e}(Ht),Ri=function(n){Fe(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.record=function(t,r){},e}(Ht),Nn=function(){function n(){}return n.prototype.addCallback=function(e){},n.prototype.removeCallback=function(e){},n}(),ki=function(n){Fe(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e}(Nn),Pi=function(n){Fe(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e}(Nn),Ni=function(n){Fe(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e}(Nn),ji=new Ii,Di=new Ai,xi=new Oi,Fi=new Ri,Ui=new Ci,$i=new ki,Li=new Pi,Hi=new Ni,qi={get:function(n,e){if(n!=null)return n[e]},keys:function(n){return n==null?[]:Object.keys(n)}},Gi={set:function(n,e,t){n!=null&&(n[e]=t)}},Bi=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return o},Ji=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},Wi=function(){function n(){}return n.prototype.active=function(){return Si},n.prototype.with=function(e,t,r){for(var s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return t.call.apply(t,Ji([r],Bi(s),!1))},n.prototype.bind=function(e,t){return t},n.prototype.enable=function(){return this},n.prototype.disable=function(){return this},n}(),zi=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return o},Vi=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},jn="context",Yi=new Wi,qt=function(){function n(){}return n.getInstance=function(){return this._instance||(this._instance=new n),this._instance},n.prototype.setGlobalContextManager=function(e){return vt(jn,e,be.instance())},n.prototype.active=function(){return this._getContextManager().active()},n.prototype.with=function(e,t,r){for(var s,o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return(s=this._getContextManager()).with.apply(s,Vi([e,t,r],zi(o),!1))},n.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},n.prototype._getContextManager=function(){return xe(jn)||Yi},n.prototype.disable=function(){this._getContextManager().disable(),bt(jn,be.instance())},n}(),Dn;(function(n){n[n.NONE=0]="NONE",n[n.SAMPLED=1]="SAMPLED"})(Dn||(Dn={}));var us="0000000000000000",hs="00000000000000000000000000000000",Ki={traceId:hs,spanId:us,traceFlags:Dn.NONE},yt=function(){function n(e){e===void 0&&(e=Ki),this._spanContext=e}return n.prototype.spanContext=function(){return this._spanContext},n.prototype.setAttribute=function(e,t){return this},n.prototype.setAttributes=function(e){return this},n.prototype.addEvent=function(e,t){return this},n.prototype.addLink=function(e){return this},n.prototype.addLinks=function(e){return this},n.prototype.setStatus=function(e){return this},n.prototype.updateName=function(e){return this},n.prototype.end=function(e){},n.prototype.isRecording=function(){return!1},n.prototype.recordException=function(e,t){},n}(),xn=cs("OpenTelemetry Context Key SPAN");function Fn(n){return n.getValue(xn)||void 0}function Qi(){return Fn(qt.getInstance().active())}function Un(n,e){return n.setValue(xn,e)}function Xi(n){return n.deleteValue(xn)}function Zi(n,e){return Un(n,new yt(e))}function ls(n){var e;return(e=Fn(n))===null||e===void 0?void 0:e.spanContext()}var ea=/^([0-9a-f]{32})$/i,ta=/^[0-9a-f]{16}$/i;function na(n){return ea.test(n)&&n!==hs}function ra(n){return ta.test(n)&&n!==us}function fs(n){return na(n.traceId)&&ra(n.spanId)}function sa(n){return new yt(n)}var $n=qt.getInstance(),ds=function(){function n(){}return n.prototype.startSpan=function(e,t,r){r===void 0&&(r=$n.active());var s=!!(t!=null&&t.root);if(s)return new yt;var o=r&&ls(r);return oa(o)&&fs(o)?new yt(o):new yt},n.prototype.startActiveSpan=function(e,t,r,s){var o,i,a;if(!(arguments.length<2)){arguments.length===2?a=t:arguments.length===3?(o=t,a=r):(o=t,i=r,a=s);var c=i??$n.active(),h=this.startSpan(e,o,c),u=Un(c,h);return $n.with(u,a,void 0,h)}},n}();function oa(n){return typeof n=="object"&&typeof n.spanId=="string"&&typeof n.traceId=="string"&&typeof n.traceFlags=="number"}var ia=new ds,aa=function(){function n(e,t,r,s){this._provider=e,this.name=t,this.version=r,this.options=s}return n.prototype.startSpan=function(e,t,r){return this._getTracer().startSpan(e,t,r)},n.prototype.startActiveSpan=function(e,t,r,s){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},n.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):ia},n}(),ca=function(){function n(){}return n.prototype.getTracer=function(e,t,r){return new ds},n}(),ua=new ca,ps=function(){function n(){}return n.prototype.getTracer=function(e,t,r){var s;return(s=this.getDelegateTracer(e,t,r))!==null&&s!==void 0?s:new aa(this,e,t,r)},n.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:ua},n.prototype.setDelegate=function(e){this._delegate=e},n.prototype.getDelegateTracer=function(e,t,r){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,t,r)},n}();qt.getInstance(),be.instance();var ha=function(){function n(){}return n.prototype.getMeter=function(e,t,r){return ji},n}(),la=new ha,Ln="metrics",fa=function(){function n(){}return n.getInstance=function(){return this._instance||(this._instance=new n),this._instance},n.prototype.setGlobalMeterProvider=function(e){return vt(Ln,e,be.instance())},n.prototype.getMeterProvider=function(){return xe(Ln)||la},n.prototype.getMeter=function(e,t,r){return this.getMeterProvider().getMeter(e,t,r)},n.prototype.disable=function(){bt(Ln,be.instance())},n}();fa.getInstance();var da=function(){function n(){}return n.prototype.inject=function(e,t){},n.prototype.extract=function(e,t){return e},n.prototype.fields=function(){return[]},n}(),Hn=cs("OpenTelemetry Baggage Key");function gs(n){return n.getValue(Hn)||void 0}function pa(){return gs(qt.getInstance().active())}function ga(n,e){return n.setValue(Hn,e)}function va(n){return n.deleteValue(Hn)}var qn="propagation",ba=new da,ma=function(){function n(){this.createBaggage=Ti,this.getBaggage=gs,this.getActiveBaggage=pa,this.setBaggage=ga,this.deleteBaggage=va}return n.getInstance=function(){return this._instance||(this._instance=new n),this._instance},n.prototype.setGlobalPropagator=function(e){return vt(qn,e,be.instance())},n.prototype.inject=function(e,t,r){return r===void 0&&(r=Gi),this._getGlobalPropagator().inject(e,t,r)},n.prototype.extract=function(e,t,r){return r===void 0&&(r=qi),this._getGlobalPropagator().extract(e,t,r)},n.prototype.fields=function(){return this._getGlobalPropagator().fields()},n.prototype.disable=function(){bt(qn,be.instance())},n.prototype._getGlobalPropagator=function(){return xe(qn)||ba},n}();ma.getInstance();var Gn="trace",ya=function(){function n(){this._proxyTracerProvider=new ps,this.wrapSpanContext=sa,this.isSpanContextValid=fs,this.deleteSpan=Xi,this.getSpan=Fn,this.getActiveSpan=Qi,this.getSpanContext=ls,this.setSpan=Un,this.setSpanContext=Zi}return n.getInstance=function(){return this._instance||(this._instance=new n),this._instance},n.prototype.setGlobalTracerProvider=function(e){var t=vt(Gn,this._proxyTracerProvider,be.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},n.prototype.getTracerProvider=function(){return xe(Gn)||this._proxyTracerProvider},n.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},n.prototype.disable=function(){bt(Gn,be.instance()),this._proxyTracerProvider=new ps},n}(),vs=ya.getInstance();const wa=()=>Z(e=>{var t,zs,s;return s=class extends e{constructor(...i){super(...i);k(this,t);this.hooks.hook("frontgateConnection:beforeSerializeMessage",a=>{a.header&&vs.getTracer("frontgate-js-sdk").startActiveSpan("frontgateConnection:sendMessage",c=>{const h=H(this,t,zs).call(this,c.spanContext());h&&(a.header={...a.header,...h}),c.end()})})}},t=new WeakSet,zs=function(i){if(!/^0+$/.test(i.traceId))return{tracing:{value:{value:bs(i)}}}},s},{featureName:"OpenTelemetry",featureGroups:["Misc"]}),bs=n=>{const e=[18,20,9],t=r=>{for(let s=r.length;s>r.length-16;s-=2){let o=parseInt(r.substring(s-2,s),16);o>127&&(o-=256),e.push(o)}};return t(n.traceId),e.push(17),t(n.spanId),e.push(24),e.push(0),e},_a=()=>Z(e=>class extends e{async requestProxyEndpoint(t,r,s,o,i=this.defaultTimeoutInMs){const a=new Ye(t,r,o);s&&a.setBody(s),a.header.setTimeout(i);const c={message:a.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",c);const h=new Promise((l,b)=>{this.hooks.hookOnce(`frontgateConnection:response:${c.callbackId}`,f=>{try{if(!f.Message.includes("HTTPProxyResponse")){b(JSON.stringify(f));return}const T=new An(f);l({response:T,data:T.data})}catch(T){b(T)}})}),u=`Request timeout reached (${i} ms) for ${c.message.Message}`;return ge(i,u,h)}},{featureName:"HTTPProxyRequest",featureGroups:["Misc"]}),Z=(n,e)=>{const t=n;return t.featureName=e.featureName,t.featureGroups=e.featureGroups,t.disabledFeatures=e.disabledFeatures,t.disabledFeatureGroups=e.disabledFeatureGroups,t};var Bn=function(n,e){return Bn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=r[s])},Bn(n,e)};function Ke(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Bn(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Ea(n,e,t,r){function s(o){return o instanceof t?o:new t(function(i){i(o)})}return new(t||(t=Promise))(function(o,i){function a(u){try{h(r.next(u))}catch(l){i(l)}}function c(u){try{h(r.throw(u))}catch(l){i(l)}}function h(u){u.done?o(u.value):s(u.value).then(a,c)}h((r=r.apply(n,e||[])).next())})}function ms(n,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,s,o,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(h){return function(u){return c([h,u])}}function c(h){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,h[0]&&(t=0)),t;)try{if(r=1,s&&(o=h[0]&2?s.return:h[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,h[1])).done)return o;switch(s=0,o&&(h=[h[0]&2,o.value]),h[0]){case 0:case 1:o=h;break;case 4:return t.label++,{value:h[1],done:!1};case 5:t.label++,s=h[1],h=[0];continue;case 7:h=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(h[0]===6||h[0]===2)){t=0;continue}if(h[0]===3&&(!o||h[1]>o[0]&&h[1]<o[3])){t.label=h[1];break}if(h[0]===6&&t.label<o[1]){t.label=o[1],o=h;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(h);break}o[2]&&t.ops.pop(),t.trys.pop();continue}h=e.call(n,t)}catch(u){h=[6,u],s=0}finally{r=o=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}}function Qe(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Gt(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return o}function Bt(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))}function Xe(n){return this instanceof Xe?(this.v=n,this):new Xe(n)}function Ta(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,e||[]),s,o=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),s[Symbol.asyncIterator]=function(){return this},s;function i(f){return function(T){return Promise.resolve(T).then(f,l)}}function a(f,T){r[f]&&(s[f]=function(_){return new Promise(function(A,w){o.push([f,_,A,w])>1||c(f,_)})},T&&(s[f]=T(s[f])))}function c(f,T){try{h(r[f](T))}catch(_){b(o[0][3],_)}}function h(f){f.value instanceof Xe?Promise.resolve(f.value.v).then(u,l):b(o[0][2],f)}function u(f){c("next",f)}function l(f){c("throw",f)}function b(f,T){f(T),o.shift(),o.length&&c(o[0][0],o[0][1])}}function Ma(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof Qe=="function"?Qe(n):n[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(o){t[o]=n[o]&&function(i){return new Promise(function(a,c){i=n[o](i),s(a,c,i.done,i.value)})}}function s(o,i,a,c){Promise.resolve(c).then(function(h){o({value:h,done:a})},i)}}typeof SuppressedError=="function"&&SuppressedError;function K(n){return typeof n=="function"}function ys(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Jn=ys(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
1
+ (function(d,G){typeof exports=="object"&&typeof module<"u"?G(exports):typeof define=="function"&&define.amd?define(["exports"],G):(d=typeof globalThis<"u"?globalThis:d||self,G(d.fdsg={}))})(this,function(d){"use strict";var Us=d=>{throw TypeError(d)};var lr=(d,G,X)=>G.has(d)||Us("Cannot "+X);var v=(d,G,X)=>(lr(d,G,"read from private field"),X?X.call(d):G.get(d)),O=(d,G,X)=>G.has(d)?Us("Cannot add the same private member more than once"):G instanceof WeakSet?G.add(d):G.set(d,X),R=(d,G,X,it)=>(lr(d,G,"write to private field"),it?it.call(d,X):G.set(d,X),X),q=(d,G,X)=>(lr(d,G,"access private method"),X);var $s=(d,G,X,it)=>({set _(Rt){R(d,G,Rt,X)},get _(){return v(d,G,it)}});var qe,Mt,St,He,Ge,Be,Re,Oe,ae,Vs,Ys,Ks,Qs,Xs;class Rt{constructor(e,t=-1){if(!Number.isInteger(e))throw new TypeError(`idApplication is not an integer number. Given: ${e} (${typeof e})`);if(this.idApplication=e,!Number.isInteger(t))throw new TypeError(`idUser is not an integer number. Given: ${t} (${typeof t})`);this.idUser=t}peerInfoFromMessage(e){if(e.Message==="Foundation::DisconnectionMessage"){const t=e;throw new Error(`Disconnection Message: ${t.details}`)}if(e.Message==="Foundation::AuthenticationByTokenResponse"||e.Message==="Foundation::ConfigurationResponse"){const t=e;return this.serverInfo=this.parseServerInfo(t),{uuid:t.server_info.uuid,description:t.server_info.description,software:t.server_info.software,os:t.server_info.os,maximumIdleInterval:parseInt(t.maximum_idle_interval,10),maximumReceivableMessageSize:t.maximum_receivable_message_size}}throw new Error("Could not extract server_info from unknown message type.")}parseServerInfo(e){const t=e,r=Number(BigInt(t.time_at_server.microseconds))/1e3,s=Math.ceil(Date.now()-r);return{description:t.server_info.description,software:t.server_info.software,os:t.server_info.os,time:new Date(r),offsetInMs:s}}getServerInfo(){return this.serverInfo}}var y=(n=>(n[n.TRACE=10]="TRACE",n[n.DEBUG=20]="DEBUG",n[n.INFO=30]="INFO",n[n.WARN=40]="WARN",n[n.ERROR=50]="ERROR",n[n.FATAL=60]="FATAL",n[n.SILENT=100]="SILENT",n))(y||{});const Ce=class Ce{constructor(e=""){this.defaultLevel=40,this.noop=()=>null,this.name=e,this.setDefaultLevelFromLocalStorage(),Object.assign(Ce.loggers,{[e]:this})}getName(){return this.name}setLevel(e){this.level=e}getLevel(){return typeof this.level=="number"&&isFinite(this.level)&&Math.floor(this.level)===this.level?this.level:this.defaultLevel}shouldLog(e){switch(this.getLevel()){case 100:return!1;case 60:return e==="fatal";case 50:return e==="fatal"||e==="error";case 40:return e==="fatal"||e==="error"||e==="warn";case 30:return e==="fatal"||e==="error"||e==="warn"||e==="info";case 20:return e==="fatal"||e==="error"||e==="warn"||e==="info"||e==="debug";case 10:default:return!0}}setDefaultLevelFromLocalStorage(){let e;try{if(!(typeof localStorage=="object"))return;const r=localStorage.getItem("loglevel");if(!r)return;e=r}catch{return}e&&this.setLevel(Ce.getLogLevel(e))}static getLogLevel(e){const t=e.toLowerCase();switch(t){case"silent":return 100;case"fatal":return 60;case"error":return 50;case"warn":return 40;case"info":return 30;case"debug":return 20;case"trace":return 10;default:throw new Error(`Invalid log level: ${t}`)}}static getLogger(e,t){if(Object.prototype.hasOwnProperty.call(Ce.loggers,e))return Ce.loggers[e];const r=new t(e);return Ce.loggers[e]=r,r}};Ce.loggers={};let Te=Ce;class Zs{static getLogLevel(e){const t=e.toLowerCase();switch(t){case"silent":return y.SILENT;case"fatal":return y.FATAL;case"error":return y.ERROR;case"warn":return y.WARN;case"info":return y.INFO;case"debug":return y.DEBUG;case"trace":return y.TRACE;default:throw new Error(`Invalid log level: ${t}`)}}}class an extends Te{constructor(){super(...arguments),this.trace=this.getLogMethod("trace"),this.debug=this.getLogMethod("debug"),this.info=this.getLogMethod("info"),this.warn=this.getLogMethod("warn"),this.error=this.getLogMethod("error"),this.fatal=this.getLogMethod("fatal")}setLevel(e){this.level=e,this.trace=this.getLogMethod("trace"),this.debug=this.getLogMethod("debug"),this.info=this.getLogMethod("info"),this.warn=this.getLogMethod("warn"),this.error=this.getLogMethod("error"),this.fatal=this.getLogMethod("fatal")}getLogMethod(e){if(this.shouldLog(e)){const t=e==="debug"||e==="fatal"?"log":e,r=this.name?`${this.name}: [${e.toUpperCase()}] `:`-----> [${e.toUpperCase()}] `;return Function.prototype.bind.call(console[t],console,r)}return this.noop}static getLogger(e=""){return super.getLogger(e,an)}}const eo={silent:0,fatal:1,error:2,warn:3,info:4,debug:5,trace:6};class to extends Te{constructor(e,t=""){super(t),this.name=t,this.logger=e,this.trace=Function.prototype.bind.call(e.trace,e),this.debug=Function.prototype.bind.call(e.debug,e),this.info=Function.prototype.bind.call(e.info,e),this.warn=Function.prototype.bind.call(e.warn,e),this.error=Function.prototype.bind.call(e.error,e),this.fatal=Function.prototype.bind.call(e.error,e)}setLevel(e){this.level=e,this.logger&&(this.logger.level=y[e].toLowerCase())}static getLogger(e=""){return Object.prototype.hasOwnProperty.call(Te.loggers,e)?Te.loggers[e]:null}}class at extends Te{constructor(){super(...arguments),this.trace=this.noop,this.debug=this.noop,this.info=this.noop,this.warn=this.noop,this.error=this.noop}static getLogger(e=""){return super.getLogger(e,at)}}var H=Uint8Array,te=Uint16Array,cn=Int32Array,Ot=new H([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Pt=new H([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),un=new H([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),gr=function(n,e){for(var t=new te(31),r=0;r<31;++r)t[r]=e+=1<<n[r-1];for(var s=new cn(t[30]),r=1;r<30;++r)for(var o=t[r];o<t[r+1];++o)s[o]=o-t[r]<<5|r;return{b:t,r:s}},vr=gr(Ot,2),br=vr.b,hn=vr.r;br[28]=258,hn[258]=28;for(var mr=gr(Pt,0),no=mr.b,yr=mr.r,ln=new te(32768),U=0;U<32768;++U){var Ee=(U&43690)>>1|(U&21845)<<1;Ee=(Ee&52428)>>2|(Ee&13107)<<2,Ee=(Ee&61680)>>4|(Ee&3855)<<4,ln[U]=((Ee&65280)>>8|(Ee&255)<<8)>>1}for(var pe=function(n,e,t){for(var r=n.length,s=0,o=new te(e);s<r;++s)n[s]&&++o[n[s]-1];var i=new te(e);for(s=1;s<e;++s)i[s]=i[s-1]+o[s-1]<<1;var a;if(t){a=new te(1<<e);var c=15-e;for(s=0;s<r;++s)if(n[s])for(var h=s<<4|n[s],u=e-n[s],l=i[n[s]-1]++<<u,b=l|(1<<u)-1;l<=b;++l)a[ln[l]>>c]=h}else for(a=new te(r),s=0;s<r;++s)n[s]&&(a[s]=ln[i[n[s]-1]++]>>15-n[s]);return a},Me=new H(288),U=0;U<144;++U)Me[U]=8;for(var U=144;U<256;++U)Me[U]=9;for(var U=256;U<280;++U)Me[U]=7;for(var U=280;U<288;++U)Me[U]=8;for(var ct=new H(32),U=0;U<32;++U)ct[U]=5;var ro=pe(Me,9,0),so=pe(Me,9,1),oo=pe(ct,5,0),io=pe(ct,5,1),fn=function(n){for(var e=n[0],t=1;t<n.length;++t)n[t]>e&&(e=n[t]);return e},ce=function(n,e,t){var r=e/8|0;return(n[r]|n[r+1]<<8)>>(e&7)&t},dn=function(n,e){var t=e/8|0;return(n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},pn=function(n){return(n+7)/8|0},Ne=function(n,e,t){return(e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length),new H(n.subarray(e,t))},ao=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],W=function(n,e,t){var r=new Error(e||ao[n]);if(r.code=n,Error.captureStackTrace&&Error.captureStackTrace(r,W),!t)throw r;return r},co=function(n,e,t,r){var s=n.length,o=0;if(!s||e.f&&!e.l)return t||new H(0);var i=!t,a=i||e.i!=2,c=e.i;i&&(t=new H(s*3));var h=function(At){var kt=t.length;if(At>kt){var ot=new H(Math.max(kt*2,At));ot.set(t),t=ot}},u=e.f||0,l=e.p||0,b=e.b||0,f=e.l,E=e.d,_=e.m,A=e.n,w=s*8;do{if(!f){u=ce(n,l,1);var m=ce(n,l+1,3);if(l+=3,m)if(m==1)f=so,E=io,_=9,A=5;else if(m==2){var k=ce(n,l,31)+257,N=ce(n,l+10,15)+4,g=k+ce(n,l+5,31)+1;l+=14;for(var p=new H(g),I=new H(19),C=0;C<N;++C)I[un[C]]=ce(n,l+C*3,7);l+=N*3;for(var x=fn(I),z=(1<<x)-1,P=pe(I,x,1),C=0;C<g;){var F=P[ce(n,l,z)];l+=F&15;var T=F>>4;if(T<16)p[C++]=T;else{var j=0,L=0;for(T==16?(L=3+ce(n,l,3),l+=2,j=p[C-1]):T==17?(L=3+ce(n,l,7),l+=3):T==18&&(L=11+ce(n,l,127),l+=7);L--;)p[C++]=j}}var V=p.subarray(0,k),$=p.subarray(k);_=fn(V),A=fn($),f=pe(V,_,1),E=pe($,A,1)}else W(1);else{var T=pn(l)+4,M=n[T-4]|n[T-3]<<8,S=T+M;if(S>s){c&&W(0);break}a&&h(b+M),t.set(n.subarray(T,S),b),e.b=b+=M,e.p=l=S*8,e.f=u;continue}if(l>w){c&&W(0);break}}a&&h(b+131072);for(var Je=(1<<_)-1,ee=(1<<A)-1,de=l;;de=l){var j=f[dn(n,l)&Je],Y=j>>4;if(l+=j&15,l>w){c&&W(0);break}if(j||W(2),Y<256)t[b++]=Y;else if(Y==256){de=l,f=null;break}else{var J=Y-254;if(Y>264){var C=Y-257,D=Ot[C];J=ce(n,l,(1<<D)-1)+br[C],l+=D}var ie=E[dn(n,l)&ee],me=ie>>4;ie||W(3),l+=ie&15;var $=no[me];if(me>3){var D=Pt[me];$+=dn(n,l)&(1<<D)-1,l+=D}if(l>w){c&&W(0);break}a&&h(b+131072);var Pe=b+J;if(b<$){var _e=o-$,We=Math.min($,Pe);for(_e+b<0&&W(3);b<We;++b)t[b]=r[_e+b]}for(;b<Pe;++b)t[b]=t[b-$]}}e.l=f,e.p=de,e.b=b,e.f=u,f&&(u=1,e.m=_,e.d=E,e.n=A)}while(!u);return b!=t.length&&i?Ne(t,0,b):t.subarray(0,b)},ye=function(n,e,t){t<<=e&7;var r=e/8|0;n[r]|=t,n[r+1]|=t>>8},ut=function(n,e,t){t<<=e&7;var r=e/8|0;n[r]|=t,n[r+1]|=t>>8,n[r+2]|=t>>16},gn=function(n,e){for(var t=[],r=0;r<n.length;++r)n[r]&&t.push({s:r,f:n[r]});var s=t.length,o=t.slice();if(!s)return{t:Er,l:0};if(s==1){var i=new H(t[0].s+1);return i[t[0].s]=1,{t:i,l:1}}t.sort(function(S,k){return S.f-k.f}),t.push({s:-1,f:25001});var a=t[0],c=t[1],h=0,u=1,l=2;for(t[0]={s:-1,f:a.f+c.f,l:a,r:c};u!=s-1;)a=t[t[h].f<t[l].f?h++:l++],c=t[h!=u&&t[h].f<t[l].f?h++:l++],t[u++]={s:-1,f:a.f+c.f,l:a,r:c};for(var b=o[0].s,r=1;r<s;++r)o[r].s>b&&(b=o[r].s);var f=new te(b+1),E=vn(t[u-1],f,0);if(E>e){var r=0,_=0,A=E-e,w=1<<A;for(o.sort(function(k,N){return f[N.s]-f[k.s]||k.f-N.f});r<s;++r){var m=o[r].s;if(f[m]>e)_+=w-(1<<E-f[m]),f[m]=e;else break}for(_>>=A;_>0;){var T=o[r].s;f[T]<e?_-=1<<e-f[T]++-1:++r}for(;r>=0&&_;--r){var M=o[r].s;f[M]==e&&(--f[M],++_)}E=e}return{t:new H(f),l:E}},vn=function(n,e,t){return n.s==-1?Math.max(vn(n.l,e,t+1),vn(n.r,e,t+1)):e[n.s]=t},wr=function(n){for(var e=n.length;e&&!n[--e];);for(var t=new te(++e),r=0,s=n[0],o=1,i=function(c){t[r++]=c},a=1;a<=e;++a)if(n[a]==s&&a!=e)++o;else{if(!s&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(s),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(s);o=1,s=n[a]}return{c:t.subarray(0,r),n:e}},ht=function(n,e){for(var t=0,r=0;r<e.length;++r)t+=n[r]*e[r];return t},_r=function(n,e,t){var r=t.length,s=pn(e+2);n[s]=r&255,n[s+1]=r>>8,n[s+2]=n[s]^255,n[s+3]=n[s+1]^255;for(var o=0;o<r;++o)n[s+o+4]=t[o];return(s+4+r)*8},Tr=function(n,e,t,r,s,o,i,a,c,h,u){ye(e,u++,t),++s[256];for(var l=gn(s,15),b=l.t,f=l.l,E=gn(o,15),_=E.t,A=E.l,w=wr(b),m=w.c,T=w.n,M=wr(_),S=M.c,k=M.n,N=new te(19),g=0;g<m.length;++g)++N[m[g]&31];for(var g=0;g<S.length;++g)++N[S[g]&31];for(var p=gn(N,7),I=p.t,C=p.l,x=19;x>4&&!I[un[x-1]];--x);var z=h+5<<3,P=ht(s,Me)+ht(o,ct)+i,F=ht(s,b)+ht(o,_)+i+14+3*x+ht(N,I)+2*N[16]+3*N[17]+7*N[18];if(c>=0&&z<=P&&z<=F)return _r(e,u,n.subarray(c,c+h));var j,L,V,$;if(ye(e,u,1+(F<P)),u+=2,F<P){j=pe(b,f,0),L=b,V=pe(_,A,0),$=_;var Je=pe(I,C,0);ye(e,u,T-257),ye(e,u+5,k-1),ye(e,u+10,x-4),u+=14;for(var g=0;g<x;++g)ye(e,u+3*g,I[un[g]]);u+=3*x;for(var ee=[m,S],de=0;de<2;++de)for(var Y=ee[de],g=0;g<Y.length;++g){var J=Y[g]&31;ye(e,u,Je[J]),u+=I[J],J>15&&(ye(e,u,Y[g]>>5&127),u+=Y[g]>>12)}}else j=ro,L=Me,V=oo,$=ct;for(var g=0;g<a;++g){var D=r[g];if(D>255){var J=D>>18&31;ut(e,u,j[J+257]),u+=L[J+257],J>7&&(ye(e,u,D>>23&31),u+=Ot[J]);var ie=D&31;ut(e,u,V[ie]),u+=$[ie],ie>3&&(ut(e,u,D>>5&8191),u+=Pt[ie])}else ut(e,u,j[D]),u+=L[D]}return ut(e,u,j[256]),u+L[256]},uo=new cn([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Er=new H(0),ho=function(n,e,t,r,s,o){var i=o.z||n.length,a=new H(r+i+5*(1+Math.ceil(i/7e3))+s),c=a.subarray(r,a.length-s),h=o.l,u=(o.r||0)&7;if(e){u&&(c[0]=o.r>>3);for(var l=uo[e-1],b=l>>13,f=l&8191,E=(1<<t)-1,_=o.p||new te(32768),A=o.h||new te(E+1),w=Math.ceil(t/3),m=2*w,T=function(hr){return(n[hr]^n[hr+1]<<w^n[hr+2]<<m)&E},M=new cn(25e3),S=new te(288),k=new te(32),N=0,g=0,p=o.i||0,I=0,C=o.w||0,x=0;p+2<i;++p){var z=T(p),P=p&32767,F=A[z];if(_[P]=F,A[z]=P,C<=p){var j=i-p;if((N>7e3||I>24576)&&(j>423||!h)){u=Tr(n,c,0,M,S,k,g,I,x,p-x,u),I=N=g=0,x=p;for(var L=0;L<286;++L)S[L]=0;for(var L=0;L<30;++L)k[L]=0}var V=2,$=0,Je=f,ee=P-F&32767;if(j>2&&z==T(p-ee))for(var de=Math.min(b,j)-1,Y=Math.min(32767,p),J=Math.min(258,j);ee<=Y&&--Je&&P!=F;){if(n[p+V]==n[p+V-ee]){for(var D=0;D<J&&n[p+D]==n[p+D-ee];++D);if(D>V){if(V=D,$=ee,D>de)break;for(var ie=Math.min(ee,D-2),me=0,L=0;L<ie;++L){var Pe=p-ee+L&32767,_e=_[Pe],We=Pe-_e&32767;We>me&&(me=We,F=Pe)}}}P=F,F=_[P],ee+=P-F&32767}if($){M[I++]=268435456|hn[V]<<18|yr[$];var At=hn[V]&31,kt=yr[$]&31;g+=Ot[At]+Pt[kt],++S[257+At],++k[kt],C=p+V,++N}else M[I++]=n[p],++S[n[p]]}}for(p=Math.max(p,C);p<i;++p)M[I++]=n[p],++S[n[p]];u=Tr(n,c,h,M,S,k,g,I,x,p-x,u),h||(o.r=u&7|c[u/8|0]<<3,u-=7,o.h=A,o.p=_,o.i=p,o.w=C)}else{for(var p=o.w||0;p<i+h;p+=65535){var ot=p+65535;ot>=i&&(c[u/8|0]=h,ot=i),u=_r(c,u+1,n.subarray(p,ot))}o.i=i}return Ne(a,0,r+pn(u)+s)},Mr=function(){var n=1,e=0;return{p:function(t){for(var r=n,s=e,o=t.length|0,i=0;i!=o;){for(var a=Math.min(i+2655,o);i<a;++i)s+=r+=t[i];r=(r&65535)+15*(r>>16),s=(s&65535)+15*(s>>16)}n=r,e=s},d:function(){return n%=65521,e%=65521,(n&255)<<24|(n&65280)<<8|(e&255)<<8|e>>8}}},Sr=function(n,e,t,r,s){if(!s&&(s={l:1},e.dictionary)){var o=e.dictionary.subarray(-32768),i=new H(o.length+n.length);i.set(o),i.set(n,o.length),n=i,s.w=o.length}return ho(n,e.level==null?6:e.level,e.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(n.length)))*1.5):20:12+e.mem,t,r,s)},Ir=function(n,e,t){for(;t;++e)n[e]=t,t>>>=8},lo=function(n,e){var t=e.level,r=t==0?0:t<6?1:t==9?3:2;if(n[0]=120,n[1]=r<<6|(e.dictionary&&32),n[1]|=31-(n[0]<<8|n[1])%31,e.dictionary){var s=Mr();s.p(e.dictionary),Ir(n,2,s.d())}},fo=function(n,e){return((n[0]&15)!=8||n[0]>>4>7||(n[0]<<8|n[1])%31)&&W(6,"invalid zlib data"),(n[1]>>5&1)==+!e&&W(6,"invalid zlib data: "+(n[1]&32?"need":"unexpected")+" dictionary"),(n[1]>>3&4)+2},bn=function(){function n(e,t){if(typeof e=="function"&&(t=e,e={}),this.ondata=t,this.o=e||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new H(98304),this.o.dictionary){var r=this.o.dictionary.subarray(-32768);this.b.set(r,32768-r.length),this.s.i=32768-r.length}}return n.prototype.p=function(e,t){this.ondata(Sr(e,this.o,0,0,this.s),t)},n.prototype.push=function(e,t){this.ondata||W(5),this.s.l&&W(4);var r=e.length+this.s.z;if(r>this.b.length){if(r>2*this.b.length-32768){var s=new H(r&-32768);s.set(this.b.subarray(0,this.s.z)),this.b=s}var o=this.b.length-this.s.z;this.b.set(e.subarray(0,o),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(e.subarray(o),32768),this.s.z=e.length-o+32768,this.s.i=32766,this.s.w=32768}else this.b.set(e,this.s.z),this.s.z+=e.length;this.s.l=t&1,(this.s.z>this.s.w+8191||t)&&(this.p(this.b,t||!1),this.s.w=this.s.i,this.s.i-=2)},n.prototype.flush=function(){this.ondata||W(5),this.s.l&&W(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2},n}(),mn=function(){function n(e,t){typeof e=="function"&&(t=e,e={}),this.ondata=t;var r=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:r?r.length:0},this.o=new H(32768),this.p=new H(0),r&&this.o.set(r)}return n.prototype.e=function(e){if(this.ondata||W(5),this.d&&W(4),!this.p.length)this.p=e;else if(e.length){var t=new H(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}},n.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,r=co(this.p,this.s,this.o);this.ondata(Ne(r,t,this.s.b),this.d),this.o=Ne(r,this.s.b-32768),this.s.b=this.o.length,this.p=Ne(this.p,this.s.p/8|0),this.s.p&=7},n.prototype.push=function(e,t){this.e(e),this.c(t)},n}(),po=function(){function n(e,t){this.c=Mr(),this.v=1,bn.call(this,e,t)}return n.prototype.push=function(e,t){this.c.p(e),bn.prototype.push.call(this,e,t)},n.prototype.p=function(e,t){var r=Sr(e,this.o,this.v&&(this.o.dictionary?6:2),t&&4,this.s);this.v&&(lo(r,this.o),this.v=0),t&&Ir(r,r.length-4,this.c.d()),this.ondata(r,t)},n.prototype.flush=function(){bn.prototype.flush.call(this)},n}(),go=function(){function n(e,t){mn.call(this,e,t),this.v=e&&e.dictionary?2:1}return n.prototype.push=function(e,t){if(mn.prototype.e.call(this,e),this.v){if(this.p.length<6&&!t)return;this.p=this.p.subarray(fo(this.p,this.v-1)),this.v=0}t&&(this.p.length<4&&W(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),mn.prototype.c.call(this,t)},n}(),Ar=typeof TextEncoder<"u"&&new TextEncoder,yn=typeof TextDecoder<"u"&&new TextDecoder,vo=0;try{yn.decode(Er,{stream:!0}),vo=1}catch{}var bo=function(n){for(var e="",t=0;;){var r=n[t++],s=(r>127)+(r>223)+(r>239);if(t+s>n.length)return{s:e,r:Ne(n,t-1)};s?s==3?(r=((r&15)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,e+=String.fromCharCode(55296|r>>10,56320|r&1023)):s&1?e+=String.fromCharCode((r&31)<<6|n[t++]&63):e+=String.fromCharCode((r&15)<<12|(n[t++]&63)<<6|n[t++]&63):e+=String.fromCharCode(r)}};function mo(n,e){var t;if(Ar)return Ar.encode(n);for(var r=n.length,s=new H(n.length+(n.length>>1)),o=0,i=function(h){s[o++]=h},t=0;t<r;++t){if(o+5>s.length){var a=new H(o+8+(r-t<<1));a.set(s),s=a}var c=n.charCodeAt(t);c<128||e?i(c):c<2048?(i(192|c>>6),i(128|c&63)):c>55295&&c<57344?(c=65536+(c&1047552)|n.charCodeAt(++t)&1023,i(240|c>>18),i(128|c>>12&63),i(128|c>>6&63),i(128|c&63)):(i(224|c>>12),i(128|c>>6&63),i(128|c&63))}return Ne(s,0,o)}function yo(n,e){var t;if(yn)return yn.decode(n);var r=bo(n),s=r.s,t=r.r;return t.length&&W(8),s}const wo=n=>{if(n.length===1)return n[0];const e=new Uint8Array(n.reduce((t,r)=>t+r.length,0));for(let t=0,r=0;t<n.length;++t)e.set(n[t],r),r+=n[t].length;return e};class kr{constructor(){this.reset()}reset(){this.compressor=null,this.decompressor=null}compress(e){this.compressor||(this.compressor=new po({mem:4}));const t=[];return this.compressor.ondata=r=>{t.push(r)},this.compressor.push(mo(e)),this.compressor.flush(),wo(t)}decompress(e){this.decompressor||(this.decompressor=new go);let t;this.decompressor.ondata=r=>{t=r};try{if(this.decompressor.push(e),t===void 0)throw new Error("invalid block type")}catch(r){throw new Error(`Decompression error: ${r.message}, length: ${e.length}, data: [${e.toString()}]`)}return yo(t)}}const we=class we{static isSupportedEncoding(e){return we.SUPPORTED_ENCODINGS.includes(e)}static isPlainJson(e){return we.PLAIN_JSON_ENCODINGS.includes(e)}static isCompressedJson(e){return we.COMPRESSED_ENCODINGS.includes(e)}};we.SUPPORTED_ENCODINGS=["jsjson-v2","jsjsonc-v2"],we.PLAIN_JSON_ENCODINGS=["jsjson-v2"],we.COMPRESSED_ENCODINGS=we.SUPPORTED_ENCODINGS.filter(e=>e.includes("jsonc"));let Se=we;const _o="Mdg2Client",Cr="BST",wn=6e3,Rr=3e3,To=9e3,Or=3,Eo=!1,Mo=9e3,Pr=!1,Nr=512;function So(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var _n,jr;function Io(){if(jr)return _n;jr=1;var n=function(m){return e(m)&&!t(m)};function e(w){return!!w&&typeof w=="object"}function t(w){var m=Object.prototype.toString.call(w);return m==="[object RegExp]"||m==="[object Date]"||o(w)}var r=typeof Symbol=="function"&&Symbol.for,s=r?Symbol.for("react.element"):60103;function o(w){return w.$$typeof===s}function i(w){return Array.isArray(w)?[]:{}}function a(w,m){return m.clone!==!1&&m.isMergeableObject(w)?_(i(w),w,m):w}function c(w,m,T){return w.concat(m).map(function(M){return a(M,T)})}function h(w,m){if(!m.customMerge)return _;var T=m.customMerge(w);return typeof T=="function"?T:_}function u(w){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(w).filter(function(m){return Object.propertyIsEnumerable.call(w,m)}):[]}function l(w){return Object.keys(w).concat(u(w))}function b(w,m){try{return m in w}catch{return!1}}function f(w,m){return b(w,m)&&!(Object.hasOwnProperty.call(w,m)&&Object.propertyIsEnumerable.call(w,m))}function E(w,m,T){var M={};return T.isMergeableObject(w)&&l(w).forEach(function(S){M[S]=a(w[S],T)}),l(m).forEach(function(S){f(w,S)||(b(w,S)&&T.isMergeableObject(m[S])?M[S]=h(S,T)(w[S],m[S],T):M[S]=a(m[S],T))}),M}function _(w,m,T){T=T||{},T.arrayMerge=T.arrayMerge||c,T.isMergeableObject=T.isMergeableObject||n,T.cloneUnlessOtherwiseSpecified=a;var M=Array.isArray(m),S=Array.isArray(w),k=M===S;return k?M?T.arrayMerge(w,m,T):E(w,m,T):a(m,T)}_.all=function(m,T){if(!Array.isArray(m))throw new Error("first argument should be an array");return m.reduce(function(M,S){return _(M,S,T)},{})};var A=_;return _n=A,_n}var Ao=Io();const Dr=So(Ao);class ko extends Error{constructor(e="Service Unavailable",t){super(e,{cause:t}),this.name="ServiceUnavailableError",this.code=503}}class Co extends Error{constructor(e="Internal Server Error",t){super(e,{cause:t}),this.name="InternalServerError",this.code=500}}class xr extends Error{constructor(e="Timeout",t){super(e,{cause:t}),this.name="TimeoutError",this.code=408}}class Ro extends Error{constructor(e="Unauthorized",t){super(e,{cause:t}),this.name="UnauthorizedError",this.code=401}}class Oo extends Error{constructor(e="Bad Request",t){super(e,{cause:t}),this.name="BadRequestError",this.code=400}}class Po extends Error{constructor(e,t){super(e,{cause:t}),this.name="ResponseError",this.response=t}}function No(n){return!!n&&typeof n=="object"}function jo(...n){const e=n.filter(No);return Dr.all(e,{arrayMerge:(t,r)=>r})}function Tn(n){return n.replace(/[=]/g,"").replace(/\//g,"_").replace(/\+/g,"-")}function Do(n){return/^[A-Za-z0-9_-]*$/.test(n)}function xo(n){let e=n.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4!==0;)e+="=";switch(e.length%4){case 0:break;case 1:e+="===";break;case 2:e+="==";break;case 3:e+="=";break}return e}const En=n=>{var r,s,o,i;let e="Unknown",t=500;if(n.name==="Foundation::PermissionDeniedResponse")t=403,e=`Permission Denied. Job ID: ${n.jobId} failed with status code ${t} `;else if(n.name==="Foundation::ErrorResponse"&&n.reason){const a=n.reason.startsWith("{"),c=a?JSON.parse(n.reason)||{}:n.reason;a&&((r=c.errors)!=null&&r[0].details)?e=c.errors[0].details:typeof c=="string"&&(e=c),t=parseInt(((o=(s=c==null?void 0:c.meta)==null?void 0:s.status)==null?void 0:o.code)??((i=n.msg.reason)==null?void 0:i.value)??500,10)}return new Po(`${e} (${t})`,n)},Fo=async n=>new Promise(e=>{setTimeout(e,n)}),Uo=()=>typeof window>"u",tt=class tt{constructor(){this._timeAtSender=Date.now()}getPtlMessage(){return{Message:tt.NAME,Version:tt.VERSION,time_at_sender:{microseconds:this._timeAtSender*1e3}}}resetTimeAtSender(){this._timeAtSender=Date.now()}get timeAtSender(){return this._timeAtSender}};tt.NAME="PingRequest",tt.VERSION=3;let ze=tt;var Fr=(n=>(n.MAXIMUM_STRING="9223372036854775807",n.MINIMUM_STRING="-9223372036854775807",n))(Fr||{});function Nt(n){return n.toString().slice(0,-3)}const nt=class nt{constructor(e){if(e.Message!==nt.NAME)throw new Error(`Unsupported message=${e.Message}`);if(e.Version!==nt.VERSION)throw new Error(`Unsupported version=${e.Version} for message=${e.Message}`);this._timeReceivedResponse=Date.now(),this._timeAtSender=Number(Nt(e.time_at_sender.microseconds)),this._timeFromRequest=Number(Nt(e.time_from_request.microseconds))}get timeAtPeer(){return this._timeAtSender}get timeOfRequest(){return this._timeFromRequest}get timeOfResponse(){return this._timeReceivedResponse}get latencyTotal(){return this._timeReceivedResponse-this._timeFromRequest}get latencyAtPeer(){return this._timeAtSender-this._timeFromRequest}};nt.NAME="Foundation::PingResponse",nt.VERSION=2;let je=nt;var Ie=(n=>(n[n.DISCONNECTED=0]="DISCONNECTED",n[n.CONNECTING=1]="CONNECTING",n[n.AUTHENTICATED=2]="AUTHENTICATED",n[n.RECONNECTING=3]="RECONNECTING",n))(Ie||{}),Ur=(n=>(n[n.production=40]="production",n[n.preproduction=35]="preproduction",n[n.show=30]="show",n[n.testing=20]="testing",n))(Ur||{}),$r=(n=>(n.production="frontgate-eu.factsetdigitalsolutions.com",n.show="frontgate-eu.show.factsetdigitalsolutions.com",n))($r||{});const nn=class nn{constructor(e,t){if(this.reconnectDelays=[1e3,2e3,4e3,8e3,16e3,32e3],this.reconnectCounter=0,this.connectionCounter=0,this.onConnect=null,this.onMessage=null,this.onClose=null,this.onError=null,this.onAuthentication=null,this.onCleanupRequests=null,this.onCleanupSubscriptions=null,this.onClearPendingSubscription=null,this.onReceiveTimeout=null,this.restartSubscriptions=null,this.options={...nn.DEFAULT_OPTIONS,...t},this.auth=e,this.state=0,this.options.logger&&(this.logger=this.options.logger),this.timestampOfLastMessageSent=0,this.jobId=0,this.peerInfo=null,this.compressor=new kr,this.keepAliveIntervalHandle=null,this.hasActiveSession=!1,this.options.loglevel&&this.logger.setLevel(this.options.loglevel),!Se.isSupportedEncoding(this.options.encoding))throw new Error(`Unknown or unsupported encoding: ${this.options.encoding}`);this.messageProcessors={},this.setMessageProcessor("Foundation::LoadNotificationMessage",this.handleLoadNotificationMessage.bind(this)),this.setMessageProcessor("Foundation::KeepAliveMessage",this.handleKeepAliveMessage.bind(this)),this.setMessageProcessor("Foundation::PingResponse",this.handlePingResponseMessage.bind(this)),this.setMessageProcessor("Foundation::DisconnectionMessage",this.handleDisconnectionMessage.bind(this))}setMessageProcessor(e,t){this.messageProcessors[e]=t}removeMessageProcessor(e){this.messageProcessors[e]!==void 0&&(this.messageProcessors[e]=void 0)}async close(){if(!this.isAuthenticated()){this.logger.warn("Cannot close gracefully. Connection not open. Proceeding to handleClose."),await this.handleClose("Unauthenticated connection");return}try{await this.sendDisconnectionMessage()}catch(e){await this.handleClose(e.message)}}setPeerInfo(e){this.peerInfo={...this.peerInfo,...e}}isAuthenticated(){return this.state===2}isConnecting(){return this.state===1}clearPendingConnection(){this.pendingConnection=null}isPendingConnection(){return this.pendingConnection instanceof Promise}handleLoadNotificationMessage(e){return this.peerInfo&&(this.peerInfo.loadStatus=e.load),!1}handleKeepAliveMessage(){return!1}handlePingResponseMessage(e){const t=new je(e);return this.logger.debug(`Time in ms: Request=${t.timeOfRequest} Peer=${t.timeAtPeer} Response=${t.timeOfResponse}`),this.logger.debug(`Latency in ms: Total=${t.latencyTotal} Peer=${t.latencyAtPeer}`),!1}async handleDisconnectionMessage(e){await this.handleClose(`DisconnectionMessage received: '${e.details}`),this.onClose&&this.onClose(e.details)}handleAuthentication(){this.state=2;const e=1e3;this.keepAliveIntervalHandle=setInterval(()=>{this.sendKeepAliveMessage()},e),this.onAuthentication&&this.onAuthentication()}handleReceiveTimeout(){this.messageReceiveTimeout&&clearTimeout(this.messageReceiveTimeout),this.onReceiveTimeout&&this.onReceiveTimeout()}resetReceiveTimeout(){var t;if(!((t=this.peerInfo)!=null&&t.maximumIdleInterval))return;const e=this.peerInfo.maximumIdleInterval/1e3*2;this.messageReceiveTimeout&&clearTimeout(this.messageReceiveTimeout),this.messageReceiveTimeout=setTimeout(()=>{this.handleReceiveTimeout()},e)}handleStandardMessage(e){return this.onMessage&&this.onMessage(e),!0}handleMessage(e){if(!e.Message)return;this.resetReceiveTimeout();const t=this.messageProcessors[e.Message];if(t!==void 0){if(!t(e))return}else this.handleStandardMessage(e);return e}async handleClose(e){if(typeof e=="string")this.logger.warn(`Handling connection close event. Reason: ${e}`);else{const{code:s,reason:o,wasClean:i,type:a}=e;this.logger.warn("Handling connection close event.",{code:s,reason:o,wasClean:i,type:a})}this.onCleanupRequests&&this.onCleanupRequests(),!this.shouldRestartSubscriptions&&this.onCleanupSubscriptions&&this.onCleanupSubscriptions(),this.keepAliveIntervalHandle&&(clearInterval(this.keepAliveIntervalHandle),this.keepAliveIntervalHandle=null),this.state=0,this.compressor.reset(),this.peerInfo=null,this.messageReceiveTimeout&&(clearTimeout(this.messageReceiveTimeout),this.messageReceiveTimeout=null),typeof e=="string"&&e.includes("DisconnectionMessage")&&(this.logger.debug("Disconnect message received. Preventing reconnect. Potential authentication failure."),this.options.shouldReconnectOnConnectionLoss=!1),this.auth.reconnectable&&this.options.shouldReconnectOnConnectionLoss?(this.onMessage=null,await this.reconnect()):(this.onClose&&this.onClose(e),this.onMessage=null,this.onClose=null,this.onError=null)}async reconnect(){for(;!this.isAuthenticated();){this.compressor.reset(),this.peerInfo=null,this.state=3;try{const e=this.reconnectDelays.length-1;let t=this.reconnectDelays[this.reconnectCounter]??this.reconnectDelays[e];t+=Math.floor(Math.random()*50);const r=this.reconnectCounter?`(${this.reconnectCounter} attempts)`:"";this.logger.warn(`Trying to reconnect. Waiting ${t} ms ${r}`),this.reconnectCounter++,await this.open(t),this.shouldRestartSubscriptions&&this.restartSubscriptions&&this.restartSubscriptions()}catch(e){this.logger.error("Failed to reconnect",e)}}this.reconnectCounter=0}handleWsError(e){this.close().then(()=>{this.logger.error("Connection closed due to WebSocket error")}),this.logger.error("WebSocket error: ",e),this.onError&&this.onError(e)}preSubmit(e){if(e.Message){const t=this.returnAndAssignJobIdToMessage(e);return this.logger.trace("PreSubmit",{message:e.Message,jobId:t}),t}throw new TypeError("Expected message type. Must be JSON message object or Array of JSON message objects")}async sendKeepAliveMessage(){const e=Date.now()-this.timestampOfLastMessageSent,t=this.options.maximum_idle_interval/1e3/2;if(!(this.timestampOfLastMessageSent>0&&e>t))return;const s=this.options.enablePingPongKeepalive??Uo()?new ze().getPtlMessage():{Message:"KeepAliveMessage",Version:2};await this.submit(s)}async sendDisconnectionMessage(e="client shutdown",t=64){const r={Message:"Foundation::DisconnectionMessage",Version:3,reason:{value:t},details:e};await this.submit(r),await this.handleClose("Disconnected by User.")}returnAndAssignJobIdToMessage(e){if(typeof e!="object")throw new TypeError(`expected object, not ${typeof e}`);if(typeof e.Message>"u")throw new TypeError("expected object to have a 'Message' member");return!/Request$/.exec(e.Message)||typeof e.header>"u"?null:(e.header.id_job||(this.jobId=this.jobId>=Number.MAX_SAFE_INTEGER?1:this.jobId+1,e.header.id_job=this.jobId),e.header.id_job)}setLogger(e){this.logger=e}};nn.DEFAULT_OPTIONS={payload_content:"foundation",deployment_stage:30,logger:at.getLogger(_o),loglevel:y.WARN,maximum_idle_interval:45e6,host:"frontgate-eu.show.factsetdigitalsolutions.com",port:443,tls:!0,path_prefix:"",encoding:"jsjsonc-v2",split_authentication_token_second_factor:void 0,shouldReconnectOnConnectionLoss:!0,connectionTimeoutInMs:To,sessionHandling:!1};let jt=nn;var ge=null;typeof WebSocket<"u"?ge=WebSocket:typeof MozWebSocket<"u"?ge=MozWebSocket:typeof global<"u"?ge=global.WebSocket||global.MozWebSocket:typeof window<"u"?ge=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(ge=self.WebSocket||self.MozWebSocket);class Ve{constructor(){this.promiseFinally=async(e,t)=>{const r=o=>(t(),o),s=async o=>(t(),Promise.reject(o));return Promise.resolve(e).then(r,s)},this._id=null,this._delay=null}static async wrap(e,t,r=""){return new Ve().wrap(e,t,r)}get id(){return this._id}get delay(){return this._delay}async set(e,t=""){return new Promise((r,s)=>{this.clear();const o=t?()=>{s(new xr(t))}:r;this._id=setTimeout(o,e),this._delay=e})}async wrap(e,t,r=""){const s=this.promiseFinally(e,()=>{this.clear()}),o=this.set(t,r);return Promise.race([s,o])}clear(){this._id&&clearTimeout(this._id)}}class lt extends jt{constructor(e,t){if(typeof ge>"u")throw new Co("WebSocketClient not supported, WebSocket() missing in JavaScript environment");super(e,lt.sanitizeOptions(t)),this.ws=null;const{encoding:r}=this.options;if(!Se.isSupportedEncoding(r))throw new Oo(`Unknown or unsupported encoding: ${r}`);this.onReceiveTimeout=()=>{this.logger.debug("onReceiveTimeout: Closing connection"),super.close().then(()=>{var s;(s=this.ws)==null||s.close()})}}async openConnection(){this.state===Ie.RECONNECTING&&this.auth.onReconnect&&await this.auth.onReconnect(),this.logger.info("Opening new connection",{host:this.options.host});try{await this.openWebSocket()}catch(e){throw this.logger.error("Problem opening connection",e),new ko(e.message,e)}this.logger.info(`Performing ${this.auth.constructor.name}`);try{await this.performAuthentication(),this.logger.debug("WebSocket authenticated")}catch(e){throw this.logger.error("Authentication problem occurred:",e),new Ro(e.message,e)}this.ws&&(this.ws.onclose=this.handleClose.bind(this),this.ws.onerror=this.handleWsError.bind(this))}async performAuthentication(){await new Promise((e,t)=>{this.ws?(this.ws.onclose=()=>{this.state=Ie.DISCONNECTED,t(new Error("Connection closed by server. Check credentials."))},this.ws.onerror=r=>{this.close(),t(new Error(`WebSocket error during authentication: ${r.message}`))},this.auth.authenticate(this).then(e).catch(t)):t(new Error("WebSocket not initialized"))}),this.handleAuthentication()}async open(e){this.onConnect&&(this.logger.trace("onConnect()"),this.onConnect());const t=this.options.connectionTimeoutInMs,r=`Connection timeout after ${t} ms`,s=async o=>o instanceof xr&&!this.pendingConnection?Promise.resolve():Promise.reject(o);if(this.isPendingConnection()&&this.pendingConnection){this.connectionCounter++;const o=Date.now();return this.logger.warn(`Waiting for pending connection (${this.connectionCounter}) with a timeout of ${t} ms`),Ve.wrap(this.pendingConnection,t,r).catch(s).then(()=>{const i=Date.now()-o;this.logger.warn(`Pending connection (${this.connectionCounter}) resolved after ${i} ms`)})}return e?(this.logger.debug(`Opening ${e} ms delayed connection with a timeout of ${t} ms`),this.pendingConnection=Fo(e).then(async()=>Ve.wrap(this.openConnection(),t,r)).catch(s).finally(()=>{this.clearPendingConnection()}),this.pendingConnection):(this.logger.debug(`Opening connection with a timeout of ${t} ms `),this.pendingConnection=Ve.wrap(this.openConnection(),t,r).catch(s).finally(()=>{this.clearPendingConnection()}),this.pendingConnection)}async close(e=!1,t=!1){this.logger.info("Closing connection explicitly"),this.options.shouldReconnectOnConnectionLoss=e,await super.close(),this.ws&&(this.clearPendingConnection(),this.ws.onclose=this.handleClose.bind(this),this.ws.close(),this.state=Ie.DISCONNECTED),t&&!e&&this.options.sessionHandling&&this.hasActiveSession&&(this.logger.info("Session logout"),await this.openWebSocket(!0))}send(e){const t=this.preSubmit(e),r=this.submit(e);return r.idJob=t,r}async submit(e){this.timestampOfLastMessageSent=Date.now();const t=new Promise(r=>{switch(this.logger.debug(`Sending ${e.Message}`,{...e}),this.sendMessage(e),this.resolveOnMessage=r,e.Message){case"Foundation::DisconnectionMessage":case"Foundation::KeepAliveMessage":case"Foundation::PingRequest":r({Message:"This message does not have a response",Version:1});break}});return t.catch(r=>{const s=new Date(this.timestampOfLastMessageSent);this.logger.error(`Failed sending ${e.Message}`,r,{request:e,lastMsgDate:s})}),t}sendMessage(e){var r;let t=JSON.stringify(e);Se.isCompressedJson(this.options.encoding)&&(t=this.compressor.compress(t)),(r=this.ws)==null||r.send(t)}async openWebSocket(e=!1){return this.logger.debug("Open WebSocket"),new Promise((t,r)=>{const{encoding:s,tls:o,host:i,port:a,path_prefix:c,frontgateSplitAuthenticationTokenSecondFactor:h,webSocketClientOptions:u,sessionHandling:l,frontgateAuthenticationToken:b}=this.options,E=`${o?"wss":"ws"}://${i}:${a}${c}/ws`,[_,A]=s.split("-"),m=[`${A?`${A}.`:""}ws-${_}.mdgms.com`];h?(m.push(`mdg2auth-${h}`),this.options.frontgateSplitAuthenticationTokenSecondFactor=null):l&&(e?m.push("mdg2wstoken-0"):this.clientOptions.otpToken?(m.push(`mdg2wstoken-${Tn(this.clientOptions.otpToken)}`),this.clientOptions.otpToken=""):b?typeof window<"u"&&m.push(`mdg2wstoken-${Tn(b)}`):m.push("mdg2wstoken-1")),this.state=Ie.CONNECTING,u?this.ws=new ge(E,m,u):this.ws=new ge(E,m),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{this.logger.info("WebSocket connected",{wsUrl:E,subProtocols:m}),e&&(this.logger.info("User logged out"),this.ws&&this.ws.close()),this.hasActiveSession=!e&&l,t()},this.ws.onclose=T=>{this.state=Ie.DISCONNECTED;const M=T.reason?`: ${T.reason}`:"";r(new Error(`Connection closed while trying to connect${M}`))},this.ws.onerror=this.handleWsError.bind(this),this.ws.onmessage=this.onWebSocketMessage.bind(this)})}onWebSocketMessage(e){if(this.state===Ie.DISCONNECTED){this.logger.warn("onWebSocketMessage while state is disconnected",{data:e.data});return}const t=this.decodeMessage(e.data),r=this.handleMessage(t);this.logger.debug(`Received ${t.Message}`,t),r&&this.resolveOnMessage(r)}decodeMessage(e){const{encoding:t}=this.options;try{if(e instanceof ArrayBuffer&&Se.isCompressedJson(t)){const r=this.compressor.decompress(new Uint8Array(e));return JSON.parse(r)}if(typeof e=="string"&&Se.isPlainJson(t))return JSON.parse(e)}catch(r){this.logger.error("Decoding message failed",r)}return String(e.constructor.name)==="Buffer"?e:(this.logger.error(`Could not decode Message of type "${typeof e}" with encoding "${t}".`),{Message:`Invalid Message Type ${typeof e}`,Version:1})}static sanitizeOptions(e={}){return e.frontgateHost&&(e.host=e.frontgateHost),e.frontgatePathPrefix&&(e.path_prefix=e.frontgatePathPrefix),e.frontgateSplitAuthenticationTokenSecondFactor&&(e.split_authentication_token_second_factor=e.frontgateSplitAuthenticationTokenSecondFactor),e.frontgateWebsocketProtocol&&(e.encoding=e.frontgateWebsocketProtocol),e.deploymentStage&&(e.deployment_stage=e.deploymentStage),e}handleWsError(e){typeof process<"u"&&this.close(this.options.shouldReconnectOnConnectionLoss).then(()=>{this.logger.error("Connection closed due to WebSocket error")}),this.logger.error("WebSocket error: ",e),this.onError&&this.onError(e)}}var Lr=(n=>(n.FRONTGATE_HOST="frontgate-host",n.FRONTGATE_PATH_PREFIX="frontgate-path-prefix",n.FRONTGATE_SPLIT_AUTHENTICATION_TOKEN_SECOND_FACTOR="frontgate-split-authentication-token-second-factor",n.FRONTGATE_AUTHENTICATION_TYPE="frontgate-authentication-type",n.FRONTGATE_AUTHENTICATION_TOKEN="frontgate-authentication-token",n.FRONTGATE_WEBSOCKET_PROTOCOL="frontgate-websocket-protocol",n))(Lr||{});function $o(n){const e=[];if(n)for(let t=0;t<n.length;t++)e.push(n.readInt8(t));return e}function qr(n){const e={},t=Object.keys(n);return["frontgate-host","frontgate-path-prefix","frontgate-split-authentication-token-second-factor","frontgate-authentication-type","frontgate-authentication-token","frontgate-websocket-protocol"].forEach(r=>{t.includes(r)&&(e[r.replace(/-([a-z])/g,s=>s[1].toUpperCase())]=n[r])}),e}function Hr(n){const e={};return n.forEach((t,r)=>{e[r]=t}),e}async function Dt(n,e){const t=await fetch(n,e),r=Hr(t.headers);return{config:qr(r),response:t}}function Gr(n={},e,t){const r=n.frontgateAuthenticationType==="token"?new kn(n.frontgateAuthenticationToken):new Cn;return r.setFetchConfiguration(e,t),new lt(r,n)}function Br({frontgateHost:n,frontgateWebsocketProtocol:e}){localStorage.setItem("mdg2config",JSON.stringify({frontgateHost:n,frontgateWebsocketProtocol:e}))}function Jr(){const n=localStorage.getItem("mdg2config");return n?JSON.parse(n):null}function Wr(n){return n.name==="Foundation::ErrorResponse"}function zr(n){return n.name==="Foundation::PermissionDeniedResponse"}function Vr(n){return n.name==="Foundation::HighLevelResponse"}function Yr(n){return n.Message==="Foundation::HighLevelResponse"}function Kr(n){return n.name==="Foundation::RejectResponse"}function xt(n){return n.name==="Foundation::HighLevelUpdate"}function Qr(n){return n.name==="Foundation::SubscriptionLossMessage"}const Xr={version:"6.10.0",package:"@factset/frontgate-js-sdk"};function Lo(){const n=qo();return{userAgent:n.userAgent,platform:n.platform,version:Xr.version,package:Xr.package,mobile:/Mobi/i.test(n.userAgent)}}function qo(){return typeof navigator<"u"?navigator:typeof process<"u"?{userAgent:`node.js/io.js, ${process.version}`,platform:`${process.platform}_${process.arch}`}:{userAgent:"unknown",platform:"unknown"}}const Ho=n=>{const e=[18,20,9],t=r=>{for(let s=r.length;s>r.length-16;s-=2){let o=parseInt(r.substring(s-2,s),16);o>127&&(o-=256),e.push(o)}};return t(n.traceId),e.push(17),t(n.spanId),e.push(24),e.push(0),e},Go=async(n,e)=>new Promise((t,r)=>{setTimeout(()=>{r(e)},n)}),ue=async(n,e,t)=>Promise.race([Go(n,e),t]),Zr=n=>n+Math.random()*100,he=class he{constructor(){this.headerMembers={dataset:{id_dataset:0},id_job:0,flags_r2:0,resend_counter:0,timeout:wn,authentication_identifiers:{id_application:0,id_user:0},cache_key:{value:[]},previous_response_hash:{value:[]},tracing:{value:{value:[]}}},this.flags=[]}getPtlMessage(){return this.headerMembers}getQuality(){return Object.keys(he.PRICE_QUALITY).find(t=>he.PRICE_QUALITY[t]===this.headerMembers.dataset.id_dataset)}setQuality(e){this.headerMembers.dataset.id_dataset=he.PRICE_QUALITY[e]}setIdApplication(e,t=!1){(this.headerMembers.authentication_identifiers.id_application===0||t)&&(this.headerMembers.authentication_identifiers.id_application=e)}setIdUser(e,t=!1){(this.headerMembers.authentication_identifiers.id_user===0||t)&&(this.headerMembers.authentication_identifiers.id_user=e)}setFlag(e,t=!0){const r=this.flags.indexOf(e);t&&r===-1&&this.flags.push(e),!t&&r>-1&&this.flags.splice(r,1),this.headerMembers.flags_r2=this.getFlagsValue()}getFlagsValue(){return this.flags.reduce((e,t)=>e+he.FLAG_VALUE[t],0)}isFlagValueSet(e){return this.flags.find(t=>t===e)!==void 0}setJobId(e){this.headerMembers.id_job=e}getJobId(){return this.headerMembers.id_job}countResend(){this.headerMembers.resend_counter++}getResendCounter(){return this.headerMembers.resend_counter}setTimeout(e){if(e>0){this.headerMembers.timeout=e;return}throw new Error(`Attempted to set the timeout to "${e}". The timeout must be greater than 0.`)}getTimeout(){return this.headerMembers.timeout}setTracing(e){/^0+$/.test(e.traceId)||(this.headerMembers.tracing.value.value=Ho(e))}static getDataSet(e){return Object.prototype.hasOwnProperty.call(he.PRICE_QUALITY,e)?he.PRICE_QUALITY[e]:he.PRICE_QUALITY.DLY}};he.PRICE_QUALITY={RLT:129,DLY:0,EOD:130},he.FLAG_VALUE={add_subscription:1,no_merge:2,support_caching:4,permission_denied_response:8,internal_client:16,current_state_refresh:32,subscription_use_pull_permissions:64,allow_chunked_response:128};let ft=he;class Ye{constructor(e,t){this.header=new ft,this.coreMembers={Message:e,Version:t},this.members={}}getPtlMessage(){const e={header:this.header.getPtlMessage()};return jo(this.coreMembers,e,this.members)}}class dt{constructor(e,t){this.token=e,this.maximumIdleInterval=t}toJson(){const e=Lo();return{Message:"AuthenticationByTokenRequest",Version:1,token:{value:this.token},software:JSON.stringify(e),os:e.platform,feature_flags_wanted:{value:0},maximum_idle_interval:this.maximumIdleInterval,maximum_receivable_message_size:1048576,flags:0,cache_authentication_salt:{value:[]},cache_authentication_encrypted_secret:{encrypted_secret:[]}}}}const le=class le extends Ye{constructor(e,t,r,s,o=!1){super(le.NAME,le.VERSION),t&&this.header.setIdUser(t),r&&this.header.setIdApplication(r),s&&this.header.setTimeout(s),this.members.flags=o?le.FLAG_SINGLE_USAGE:0,this.members.lifetime_seconds_r2=e??le.LIFETIME_SECONDS_DEFAULT,this.header.setFlag("no_merge")}};le.NAME="AuthenticationTokenRequest",le.VERSION=6,le.LIFETIME_SECONDS_DEFAULT=-1,le.LIFETIME_SECONDS_MAXIMUM=-2,le.FLAG_SINGLE_USAGE=1;let De=le;const rt=class rt extends Ye{constructor(e){super(rt.NAME,rt.VERSION),this.members.id_job_subscription=e}};rt.NAME="CancelSubscriptionRequest",rt.VERSION=6;let Ae=rt;const fe=class fe extends Ye{constructor(e,t,r={},s){super(fe.NAME,fe.VERSION),this.members.accept="application/json",this.members.content_type="application/json",this.members.body={value:[]},this.members.query="",this.members.path=t,this.setMethod(e),Object.keys(r).length>0&&(e==="POST"?this.setBody(r):this.setQuery(r)),s&&this.setOptions(s)}setOptions(e){Object.hasOwnProperty.call(e,"accept")&&(this.members.accept=e.accept),Object.hasOwnProperty.call(e,"content_type")&&(this.members.content_type=e.content_type),Object.hasOwnProperty.call(e,"subscribe")&&e.subscribe&&this.header.setFlag("add_subscription"),Object.hasOwnProperty.call(e,"no_merge")&&e.no_merge&&this.header.setFlag("no_merge"),Object.hasOwnProperty.call(e,"allowChunkedResponse")&&e.allowChunkedResponse&&this.header.setFlag("allow_chunked_response"),Object.hasOwnProperty.call(e,"idApplication")&&e.idApplication&&this.header.setIdApplication(e.idApplication),Object.hasOwnProperty.call(e,"idUser")&&e.idUser&&this.header.setIdUser(e.idUser)}setMethod(e){const t=e==="POST"?fe.METHOD.POST:fe.METHOD.GET;this.members.method={value:t}}setBody(e={}){e instanceof Array?this.members.body={value:e}:this.members.body={value:JSON.stringify(e)}}getData(){return this.members.method.value===fe.METHOD.POST?fe.ptlToJsonData(this.members.body.value):this.members.query}setQuery(e={}){this.members.query=Object.keys(e).map(t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`).join("&")}static ptlToJsonData(e){if(typeof e=="string")return JSON.parse(e);if(e instanceof Array&&e.length>0){let t="";return e.forEach(r=>{t+=String.fromCharCode(r)}),JSON.parse(t)}}};fe.NAME="HighLevelRequest",fe.VERSION=3,fe.METHOD={GET:1,POST:2};let ve=fe;const oe=class oe extends Ye{constructor(e,t,r){super(oe.NAME,oe.VERSION),this.members.request={headers:{values:[{key:"accept",value:"application/json"},{key:"content-type",value:"application/json"}]},protocol:{value:oe.PROTOCOL.HTTPS},host:"",port:0,path:t,query:"",body:{value:[]}},this.setQuery(),this.setMethod(e),r&&this.setOptions(r)}setOptions(e){e.no_merge&&this.header.setFlag("no_merge"),e.idApplication&&this.header.setIdApplication(e.idApplication),e.idUser&&this.header.setIdUser(e.idUser),e.protocol&&(this.members.request.protocol=e.protocol.toUpperCase()==="HTTP"?{value:oe.PROTOCOL.HTTP}:{value:oe.PROTOCOL.HTTPS}),e.method&&(this.members.request.method={value:oe.METHOD[e.method]}),e.host&&(this.members.request.host=e.host),e.port&&(this.members.request.port=e.port),e.path&&(this.members.request.path=e.path),e.query&&(this.members.request.query=typeof e.query=="string"?e.query:Object.keys(e.query).map(t=>`${encodeURIComponent(t)}=${encodeURIComponent(e.query[t])}`).join("&")),e.body&&this.setBody(e.body),e.headers&&this.setHeaders(e.headers)}setHeaders(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)){const r=e[t],s=this.members.request.headers.values.findIndex(i=>i.key===t);s!==-1&&this.members.request.headers.values.splice(s,1),this.members.request.headers.values.push({key:t,value:r})}}setQuery(){if(this.members.request.path.includes("?")){const e=this.members.request.path.split("?");this.members.request.path=e[0],this.members.request.query=e[1]}}setMethod(e){this.members.request.method={value:oe.METHOD[e]}}setBody(e={}){return e instanceof Array||typeof e=="string"?this.members.request.body={value:e}:this.members.request.body={value:JSON.stringify(e)},this}getData(){var e;if((e=this.members.request.body)!=null&&e.value)return ve.ptlToJsonData(this.members.request.body.value)}};oe.NAME="HTTPProxyRequest",oe.VERSION=2,oe.PROTOCOL={HTTP:1,HTTPS:2},oe.METHOD={GET:1,POST:2,OPTIONS:3,HEAD:4,PUT:5,DELETE:6,TRACE:7,CONNECT:8};let Ke=oe;class es extends Ye{constructor(e){super(e.Message,e.version?e.version:e.Version),this._extractRequestAttributes(e)}_extractRequestAttributes(e){for(const t of Object.keys(this.coreMembers))delete e[t];this.members=Dr(this.members,e)}}class Mn{static createFromString(e){return Mn.createFromObject(JSON.parse(e))}static createFromObject(e){const{header:t}=e;return t&&(t.id_job&&delete t.id_job,t.resend_counter&&delete t.resend_counter),new es(e)}}class ne{constructor(e){this.raw=e}get msg(){return this.raw}get name(){return this.raw.Message}get jobId(){return this.raw.header.id_job}get serviceId(){return this.raw.header.id_service}isUpdateMessage(){return Object.hasOwnProperty.call(this.raw,"header")&&(Object.hasOwnProperty.call(this.raw.header,"id_service")||Object.hasOwnProperty.call(this.raw.header,"id_job"))&&this.raw.Message.endsWith("Update")}isLossMessage(){return Object.hasOwnProperty.call(this.raw,"header")&&(Object.hasOwnProperty.call(this.raw.header,"id_service")||Object.hasOwnProperty.call(this.raw.header,"id_job"))&&(this.raw.Message.endsWith("LossMessage")||this.raw.Message.endsWith("Loss"))}}class Sn extends ne{constructor(e){if(super(e),!this.raw.token.value.b64)throw new Error("Token not set in AuthenticationTokenResponse");if(!this.raw.expiry.microseconds)throw new Error("Expiry not set in AuthenticationTokenResponse");this.token=this.raw.token.value.b64,this.expiry=parseInt(Nt(this.raw.expiry.microseconds),10)}getToken(){return this.token}getExpiry(){return this.expiry}}class ts extends ne{}class Z extends ne{get reason(){return this.raw.details}get jobId(){return this.raw.id_job}}class In extends ne{constructor(e){super(e);try{this.responseData=JSON.parse(this.raw.body.value)}catch(t){throw new Error(`Could not parse HighLevelResponse: ${t.message}`)}}get data(){return this.responseData.data}get meta(){return this.responseData.meta}get status(){return this.meta.status}get statusCode(){return this.status.code}}class An extends ne{constructor(e){super(e);try{const t=this.raw.response.body.value,r=t.substr(0,1)==="{";this.responseData=r?JSON.parse(t):t}catch(t){throw new Error(`Could not parse HTTPProxyResponse: ${t}`)}this.responseInfo=this.raw.info,this.statusReason=this.raw.response.status_reason,this.statusCode=this.raw.response.status_code.value}get data(){return this.responseData}get meta(){return this.responseData.meta}get status(){return{code:this.statusCode,reason:this.statusReason}}}class ns extends ne{get reason(){return this.raw.details}}class rs extends ne{get reason(){return this.raw.details}get jobId(){return this.raw.id_job}}const Bo=Object.freeze(Object.defineProperty({__proto__:null,AuthenticationTokenResponse:Sn,CancelSubscriptionResponse:ts,ErrorResponse:Z,HTTPProxyResponse:An,HighLevelResponse:In,Mdg2Response:ne,PermissionDeniedResponse:ns,PingResponse:je,RejectResponse:rs},Symbol.toStringTag,{value:"Module"}));class Ft extends ne{constructor(e){if(super(e),typeof this.raw.body.value!="string")throw new Error("Incorrect response type in HighLevelUpdate");try{this.responseData=JSON.parse(this.raw.body.value)}catch(t){throw new Error(`Could not parse HighLevelUpdate: ${t.message}`)}}get data(){return this.responseData}}class Ut extends ne{constructor(e){super(e),this.reason=e.reason}get reasonValue(){return this.reason.value}}const Jo=Object.freeze(Object.defineProperty({__proto__:null,HighLevelUpdate:Ft,SubscriptionLossMessage:Ut},Symbol.toStringTag,{value:"Module"}));class kn extends Rt{constructor(e,t=!0){if(super(-2,-2),t&&(!e||e.length<80))throw new Error("Invalid token passed to TokenAuthentication");this.setToken(e)}setToken(e){this.token=Do(e)?xo(e):e}setFetchConfiguration(e,t){this.fetchConfigurationInput=e,this.fetchConfigurationConfig=t}async authenticate(e){this.connection=e;const t=await this.sendAuthenticationByTokenRequest(),r=this.peerInfoFromMessage(t);this.connection.setPeerInfo(r)}async sendAuthenticationByTokenRequest(){const e={b64:this.token},t=new dt(e,this.connection.options.maximum_idle_interval);return await this.connection.submit(t.toJson())}get reconnectable(){return!!this.fetchConfigurationInput}async onReconnect(){if(this.fetchConfigurationInput){const{config:e}=await Dt(this.fetchConfigurationInput,this.fetchConfigurationConfig);e.frontgateAuthenticationType==="token"&&e.frontgateAuthenticationToken&&this.setToken(e.frontgateAuthenticationToken)}}}class Cn extends kn{constructor(){super("",!1)}getEncodedToken(){return[]}async onReconnect(){if(this.fetchConfigurationInput){const{config:e}=await Dt(this.fetchConfigurationInput,this.fetchConfigurationConfig);e.frontgateSplitAuthenticationTokenSecondFactor&&(this.connection.options.frontgateSplitAuthenticationTokenSecondFactor=e.frontgateSplitAuthenticationTokenSecondFactor)}}}class Rn{constructor(e){const t=Tn(e),r=Math.ceil(t.length/2);this.firstFactor=t.substring(0,r),this.secondFactor=t.substring(r)}getFirstFactor(){return this.firstFactor}getSecondFactor(){return this.secondFactor}}const rn=class rn{constructor(e,t){this.cb=e,this.conn=t,this.isRequestPending=!1,this.request=new ze}start(e){if(this.timeout!==void 0)throw new Error("LatencyTracker already running!");this.conn.setMessageProcessor("Foundation::PingResponse",this.handlePingResponse.bind(this)),this.timeout=setInterval(()=>{if(!this.conn.isAuthenticated()){this.cb(void 0,void 0,void 0,"Skipping ping request, connection not authenticated!");return}if(this.isRequestPending){if(Date.now()-this.request.timeAtSender<rn.MAX_RESPONSE_LATENCY_MS){this.cb(this.request.timeAtSender,void 0,void 0,"Skipping ping request, previous request pending!");return}this.cb(this.request.timeAtSender,void 0,void 0,"Clearing ping request, previous request exceeded timeout!")}this.isRequestPending=!0,this.request.resetTimeAtSender(),this.conn.send(this.request.getPtlMessage())},e),typeof window>"u"&&this.timeout.unref()}stop(){clearInterval(this.timeout),this.timeout=void 0,this.isRequestPending=!1,this.conn.removeMessageProcessor("Foundation::PingResponse")}handlePingResponse(e){const t=new je(e);return this.cb(t.timeOfRequest,t.latencyTotal,t.latencyAtPeer,void 0),this.isRequestPending=!1,!1}};rn.MAX_RESPONSE_LATENCY_MS=60*1e3;let On=rn;const Wo=()=>K(e=>class extends e{async requestAuthenticationToken(t=30,r=0,s=0,o=this.defaultTimeoutInMs){const a={message:new De(t,r,s,o).getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",a);const c=new Promise((u,l)=>{this.hooks.hookOnce(`frontgateConnection:response:${a.callbackId}`,b=>{if(!b.Message.includes("AuthenticationTokenResponse")){l(JSON.stringify(b));return}const f=new Sn(b);u({token:f.getToken(),expiry:f.getExpiry()})})}),h=`Request timeout reached (${o} ms) for ${a.message.Message}`;return ue(o,h,c)}async requestAuthenticationTokenForCookieTokenAuthentication(t=30,r=0,s=0,o=this.defaultTimeoutInMs){const i=await this.requestAuthenticationToken(t,r,s,o);return new Rn(i.token)}},{featureName:"AuthTokenRequest",featureGroups:["Misc"]}),$t=8,ss={...Bo,...Jo},st=class st{static createMessage(e){if(!e)throw new Error(`Could not create message because msg is "${e}"`);if(!e.Message||typeof e.Message!="string")throw new Error(`Could not create message because msg.Message is "${e.Message}"`);const t=e.Message.indexOf(st.msgNameSeparator);if(t===-1)throw new Error(`Could not create message for invalid msg.Message "${e.Message}"`);if(!(e!=null&&e.header))throw new Error("Could not create message because the header is missing in the msg");try{const r=e.Message.substring(t+st.msgNameSeparatorLength);return ss[r]?new ss[r](e):new ne(e)}catch(r){throw new Error(`Could not create message "${e.Message}": ${r.message}`)}}static hasNextChunk(e){var t;return((((t=e.header)==null?void 0:t.flags)??0)&$t)===$t}};st.msgNameSeparator="::",st.msgNameSeparatorLength=2;let Lt=st;const zo=n=>K(t=>{var r,Ls,o;return o=class extends t{constructor(){super(...arguments);O(this,r)}async requestEndpoint(a,c,h,u,l=this.defaultTimeoutInMs){const b=new ve(a,c,h,{...u,allowChunkedResponse:!(n!=null&&n.disableChunkedResponse)});b.header.setTimeout(l),n!=null&&n.allowPermissionDeniedResponse&&b.header.setFlag("permission_denied_response");const f={message:b.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",f);const E=new Promise((A,w)=>{const m=[],T=()=>{this.hooks.hookOnce(`frontgateConnection:response:${f.callbackId}`,M=>{var S,k,N,g;try{if(!M.Message.includes("HighLevelResponse")){w(JSON.stringify(M));return}if(q(this,r,Ls).call(this,M))m.push({body:((N=M.body)==null?void 0:N.value)??"",processingTime:((g=M.header)==null?void 0:g.processingTime)??0}),T();else{m.push({body:((S=M.body)==null?void 0:S.value)??"",processingTime:((k=M.header)==null?void 0:k.processingTime)??0});const p=new In({...M,body:{value:m.map(I=>I.body).join("")},header:{...M.header,processingTime:m.reduce((I,C)=>I+C.processingTime,0)}});A({response:p,data:p.data})}}catch(p){w(p)}})};T()}),_=`Request timeout reached (${l} ms) for ${f.message.Message}`;return ue(l,_,E)}},r=new WeakSet,Ls=function(a){var c;return((((c=a.header)==null?void 0:c.flags)??0)&$t)===$t},o},{featureName:"EndpointRequest",featureGroups:["Misc"]}),os=n=>K(t=>{var r,s,o,i,a,c,h,u,on,b,f,qs,Hs,Ct,fr,Gs,dr,Bs,Js,k;return k=class extends t{constructor(...g){super(...g);O(this,u);O(this,r);O(this,s);O(this,o,"disconnected");O(this,i);O(this,a,0);O(this,c);O(this,h);O(this,b);O(this,f,[]);R(this,c,-2),R(this,h,-1),n&&(this.conf=n),this.hooks.hook("frontgateConnection:setIdApp",p=>{R(this,c,p)}),this.hooks.hook("frontgateConnection:setIdUser",p=>{R(this,h,p)}),this.hooks.hook("frontgateConnection:sendMessage",p=>{if(p.callbackType==="job"){const I=q(this,u,Gs).call(this,p.message);p.callbackId=`${I}`,q(this,u,dr).call(this,p.message)}if(v(this,u,on)==="connected"&&p.callbackType==="response")q(this,u,Ct).call(this,p.message);else if(v(this,u,on)==="authenticated")q(this,u,Ct).call(this,p.message);else{if(v(this,f).length>=v(this,b))throw new Error("Message buffer is full");v(this,f).push(p)}}),this.hooks.hook("frontgateConnection:authenticated",()=>{if(!v(this,s))throw new Error("No connection configuration set");for(this.log(y.DEBUG,"Draining message buffer");v(this,f).length>0;){const p=v(this,f).shift();p&&(q(this,u,dr).call(this,p.message),q(this,u,Ct).call(this,p.message))}R(this,i,setInterval(()=>{this.log(y.DEBUG,"Sending keepalive"),this.hooks.callHook("frontgateConnection:sendMessage",{message:q(this,u,Hs).call(this),callbackType:"response",callbackId:"KeepAliveMessage"})},v(this,s).maximumIdleIntervalInS/2*1e3))}),this.hooks.hook("reconnect:attempt",async()=>{clearInterval(v(this,i)),this.log(y.DEBUG,"Reconnecting"),await this.hooks.callHook("frontgateConnection:reset");try{await this.connect(),await this.hooks.callHook("reconnect:success")}catch(p){this.log(y.ERROR,"Reconnect failed",p),await this.hooks.callHook("reconnect:failed",p)}})}set conf(g){const p=q(this,u,Js).call(this,g);R(this,b,p.messageBufferSize),R(this,s,p)}async connect(){if(!v(this,s))throw new Error("No connection configuration set");if(v(this,u,on)!=="disconnected")throw new Error("Client is already connected or is connecting right now");const{host:g,port:p,tls:I,pathPrefix:C}=v(this,s);R(this,o,"connecting");const z=`${I?"wss":"ws"}://${g}:${p}${C??""}/ws`,P={encoding:"jsjson-v2"};await this.hooks.callHook("frontgateConnection:afterSetEncoding",P);const[F,j]=P.encoding.split("-"),V=[`${j?`${j}.`:""}ws-${F}.mdgms.com`],$={url:z,subProtocols:V};await this.hooks.callHook("frontgateConnection:beforeConnect",$),this.log(y.DEBUG,`Connecting to ${$.url} with subprotocols ${$.subProtocols}`);const Je=new Promise((de,Y)=>{if(!v(this,s))throw new Error("No connection configuration set");v(this,s).wsClientOptions&&typeof window>"u"?R(this,r,new ge($.url,$.subProtocols,v(this,s).wsClientOptions)):R(this,r,new ge($.url,$.subProtocols)),v(this,r).binaryType="arraybuffer";let J;v(this,r).onopen=()=>{R(this,o,"connected"),this.log(y.DEBUG,"Connected"),this.hooks.callHook("frontgateConnection:connected",v(this,s)).catch(Y),J=this.hooks.hookOnce("frontgateConnection:authenticated",()=>{R(this,o,"authenticated"),this.log(y.DEBUG,"Authenticated"),de()})},v(this,r).onclose=D=>{J==null||J(),this.log(y.DEBUG,"Disconnected",D),this.hooks.callHook("frontgateConnection:disconnected",D),(v(this,o)==="connecting"||v(this,o)==="connected")&&Y(JSON.stringify(D)),clearInterval(v(this,i)),R(this,o,"disconnected")},v(this,r).onerror=D=>{J==null||J(),this.log(y.ERROR,"Error:",D),this.hooks.callHook("frontgateConnection:error",D),(v(this,o)==="connecting"||v(this,o)==="connected")&&Y(new Error("Websocket error")),clearInterval(v(this,i)),R(this,o,"disconnected")},v(this,r).onmessage=D=>{const{data:ie}=D;this.log(y.DEBUG,"Received data:",ie);const me={msg:ie};this.hooks.callHook("frontgateConnection:afterReceiveMessage",me).then(()=>{var We;this.log(y.DEBUG,"Received message",me.msg);const Pe=me.msg.toString("utf-8"),_e=JSON.parse(Pe);if(this.hooks.callHook("frontgateConnection:message",_e),_e.Message==="Foundation::DisconnectionMessage"){(We=v(this,r))==null||We.close(),this.hooks.callHook("frontgateConnection:disconnected",_e);return}q(this,u,fr).call(this,_e)})}}),ee=`Timeout reached (${this.defaultTimeoutInMs} ms) for connection to ${z}`;return ue(this.defaultTimeoutInMs,ee,Je)}async disconnect(){return new Promise(g=>{q(this,u,Ct).call(this,q(this,u,qs).call(this)),this.hooks.hookOnce("frontgateConnection:disconnected",()=>{var p;(p=v(this,r))==null||p.close(),g()})})}isConnected(){return v(this,o)==="authenticated"}isDisconnected(){return v(this,o)!=="authenticated"}isReadyToConnect(){return v(this,o)==="disconnected"}},r=new WeakMap,s=new WeakMap,o=new WeakMap,i=new WeakMap,a=new WeakMap,c=new WeakMap,h=new WeakMap,u=new WeakSet,on=function(){return v(this,r)&&v(this,r).readyState<2?v(this,o):"disconnected"},b=new WeakMap,f=new WeakMap,qs=function(){return{Message:"Foundation::DisconnectionMessage",Version:3,reason:{value:64},details:"client shutdown"}},Hs=function(){return{Message:"KeepAliveMessage",Version:2}},Ct=async function(g){var I;await this.hooks.callHook("frontgateConnection:beforeSerializeMessage",g);const p={msg:JSON.stringify(g)};await this.hooks.callHook("frontgateConnection:beforeSendMessage",p),this.log(y.DEBUG,"Sending message:",g),this.log(y.TRACE,"Sending data:",p.msg);try{(I=v(this,r))==null||I.send(p.msg)}catch(C){const x=q(this,u,Bs).call(this,C,g);q(this,u,fr).call(this,x.msg)}},fr=function(g){var p,I;if(typeof((p=g.header)==null?void 0:p.id_job)<"u"){this.hooks.callHook(`frontgateConnection:response:${g.header.id_job}`,g);return}if(typeof((I=g.header)==null?void 0:I.id_service)<"u"&&typeof g.id_notation<"u"){this.hooks.callHook(`frontgateConnection:response:${g.header.id_service}-${g.id_notation}`,g);return}if(typeof g.id_job<"u"){this.hooks.callHook(`frontgateConnection:response:${g.id_job}`,g);return}typeof g.Message=="string"&&this.hooks.callHook(`frontgateConnection:response:${g.Message.replace("Foundation::","")}`,g)},Gs=function(g){R(this,a,v(this,a)+1);const p=v(this,a);return g.header={...g.header,id_job:p},v(this,a)},dr=function(g){var p,I;g.header||(g.header={authentication_identifiers:{id_application:void 0,id_user:void 0}}),g.header.authentication_identifiers||(g.header={...g.header,authentication_identifiers:{id_application:void 0,id_user:void 0}}),(p=g.header.authentication_identifiers).id_application||(p.id_application=v(this,c)),(I=g.header.authentication_identifiers).id_user||(I.id_user=v(this,h))},Bs=function(g,p){var I;return new Z({Message:"Foundation::ErrorResponse",Version:1,id_job:(I=p.header)==null?void 0:I.id_job,reason:8,details:g})},Js=function(g){const p=g.maximumIdleIntervalInS??60,I=g.maximumIdleInterval??p*1e6;return{...g,payloadContent:g.payloadContent??"foundation",maximumIdleIntervalInS:p,maximumIdleInterval:I,tls:g.tls??!0,messageBufferSize:g.messageBufferSize??512}},k},{featureName:"WSConnection",disabledFeatureGroups:["Connection"]}),Vo=(n,e)=>(e&&n.setLevel(e),K(r=>class extends r{constructor(...s){super(...s),this.logger=n}},{featureName:"Logger",featureGroups:["Misc"]})),Yo=()=>K(e=>{var t,r;return r=class extends e{constructor(...o){super(...o);O(this,t);R(this,t,new kr),this.hooks.hook("frontgateConnection:reset",()=>{v(this,t).reset()}),this.hooks.hook("frontgateConnection:afterSetEncoding",i=>{i.encoding="jsjsonc-v2"}),this.hooks.hook("frontgateConnection:beforeSendMessage",i=>{const a=v(this,t).compress(i.msg);i.msg=a}),this.hooks.hook("frontgateConnection:afterReceiveMessage",i=>{const a=v(this,t).decompress(new Uint8Array(i.msg));i.msg=a})}},t=new WeakMap,r},{featureName:"MessageCompressor",featureGroups:["Misc"]}),Ko=()=>K(e=>class extends e{async request(t,r=this.defaultTimeoutInMs){t.header.setTimeout(r);const s={message:t.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",s);const o=new Promise(a=>{this.hooks.hookOnce(`frontgateConnection:response:${s.callbackId}`,c=>{const h=new ne(c);a(h)})}),i=`Request timeout reached (${r} ms) for ${s.message.Message}`;return ue(r,i,o)}},{featureName:"Request",featureGroups:["Misc"]}),Qo=n=>K(t=>{var s,o;const r={...n};return o=class extends t{constructor(){super(...arguments);O(this,s,new Map)}async observeEndpoint(a,c,h,u){const l=`${a}:${c}:${JSON.stringify(h)}:${JSON.stringify(u??{})}`,b=r.timeout??this.defaultTimeoutInMs,f=r.subscriptionResubscribeTimeout??1e3;if(v(this,s).has(l)){const m=v(this,s).get(l);if(m)return m.count++,this.log(y.INFO,`Reusing existing subscription for ${l}`),m.observer}this.log(y.INFO,`Creating new subscription for ${l}`);const E=new ve(a,c,h,{...u,subscribe:!0});E.header.setTimeout(b);const _={message:E.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",_);const A=new Promise((m,T)=>{this.hooks.hookOnce(`frontgateConnection:response:${_.callbackId}`,M=>{if(!M.Message.includes("HighLevelResponse")){this.log(y.ERROR,`Unexpected response: ${M.Message}`),T(new Z(JSON.stringify(M)));return}let S;try{S=JSON.parse(M.body.value)}catch(I){this.log(y.ERROR,`Failed to parse response: ${M.body.value}`),this.log(y.ERROR,I),T(I);return}const k=new is(M.header.id_job,S);let N=this.hooks.hook(`frontgateConnection:response:${_.callbackId}`,I=>{if(!I.Message.includes("HighLevelUpdate")){if(I.Message.includes("SubscriptionLoss")){this.log(y.DEBUG,`Received: ${I.Message}`),setTimeout(()=>{g()},Zr(f)),N();return}this.log(y.ERROR,`Unexpected response: ${M.Message}`),k.pushError(new Z(JSON.stringify(I))),N();return}let C;try{C=new Ft(I)}catch(x){this.log(y.ERROR,`Failed to parse response: ${I.body.value}`),k.pushError(x);return}k.pushPatchData(C.data)});const g=async()=>{N(),this.log(y.INFO,`Resubscribing to ${l} due to reconnect`),await this.hooks.callHook("frontgateConnection:sendMessage",_);const I=new Promise((C,x)=>{this.hooks.hookOnce(`frontgateConnection:response:${_.callbackId}`,z=>{if(!M.Message.includes("HighLevelResponse")){const P=new Z(z);this.log(y.ERROR,`Unexpected response: ${z.Message}`),N(),x(P);return}this.log(y.INFO,`Resubscribed to ${l} with ${z.header.id_job}`),k.idJob=z.header.id_job,N=this.hooks.hook(`frontgateConnection:response:${z.header.id_job}`,P=>{if(!P.Message.includes("HighLevelUpdate")){if(P.Message.includes("SubscriptionLoss")){this.log(y.DEBUG,`Received: ${P.Message}`),setTimeout(()=>{g()},Zr(f));return}this.log(y.ERROR,`Unexpected response: ${P.Message}`);const j=new Z(P);k.pushError(j);return}let F;try{F=new Ft(P)}catch(j){this.log(y.ERROR,`Failed to parse response: ${P.body.value}`),k.pushError(j);return}k.unsubscribe=()=>{const j=v(this,s).get(l);if(j){if(j.count--,j.count>0){this.log(y.INFO,`Not unsubscribing from ${l} as there are still ${j.count} subscribers`);return}v(this,s).delete(l)}this.log(y.INFO,`Unsubscribing from ${l}`);const V={message:new Ae(M.header.id_job).getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",V),N(),p()},k.pushPatchData(F.data)}),C()})});try{await ue(b,"Request timeout reached",I)}catch(C){k.pushError(new Z({Message:"Reconnect failed",Error:C}))}},p=this.hooks.hook("reconnect:success",g);k.unsubscribe=()=>{const I=v(this,s).get(l);if(I){if(I.count--,I.count>0){this.log(y.INFO,`Not unsubscribing from ${l} as there are still ${I.count} subscribers`);return}v(this,s).delete(l)}this.log(y.INFO,`Unsubscribing from ${l}`);const x={message:new Ae(M.header.id_job).getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",x),N(),p()},v(this,s).set(l,{observer:k,count:1}),m(k)})}),w=`Request timeout reached (${b} ms) for ${_.message.Message}`;return ue(b,w,A)}},s=new WeakMap,o},{featureName:"EndpointSubscriptions",featureGroups:["Misc"]}),Xo=()=>K(e=>{var t,r,pr,o;return o=class extends e{constructor(){super(...arguments);O(this,r);O(this,t,new Map)}async observe(a,c=this.defaultTimeoutInMs){return q(this,r,pr).call(this,a,"job",void 0,c)}async observeConnectionBased(a,c,h=this.defaultTimeoutInMs){return q(this,r,pr).call(this,a,"connection",c,h)}},t=new WeakMap,r=new WeakSet,pr=async function(a,c,h,u=this.defaultTimeoutInMs){const l=JSON.stringify(a.getPtlMessage());if(v(this,t).has(l)){const A=v(this,t).get(l);if(A)return A.count++,this.log(y.INFO,`Reusing existing subscription for ${l}`),A.observer}this.log(y.INFO,`Creating new subscription for ${l}`);const f={message:a.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",f);const E=new Promise((A,w)=>{this.hooks.hookOnce(`frontgateConnection:response:${f.callbackId}`,m=>{if(m.Message.includes("Error")||m.Message.includes("PermissionDenied")){this.log(y.ERROR,`Unexpected response: ${m.Message}`),w(new Error(`Unexpected response: ${m.Message}`));return}const T=c==="connection"?`${m.header.id_service}-${a.getPtlMessage().id_notation}`:m.header.id_job,M=typeof h>"u"?new Ae(m.header.id_job):new h(m.header.id_service,a.getPtlMessage().id_notation),S=new Nn(m.header.id_job,m);let k=this.hooks.hook(`frontgateConnection:response:${T}`,g=>{if(g.Message.includes("Error")||g.Message.includes("PermissionDenied")){this.log(y.ERROR,`Unexpected response: ${m.Message}`),S.pushError(new Z(JSON.stringify(g)));return}S.pushData(g)});const N=this.hooks.hook("reconnect:success",async()=>{k(),this.log(y.INFO,`Resubscribing to ${l} due to reconnect`),await this.hooks.callHook("frontgateConnection:sendMessage",f);const g=new Promise((p,I)=>{this.hooks.hookOnce(`frontgateConnection:response:${f.callbackId}`,C=>{if(C.Message.includes("Error")||C.Message.includes("PermissionDenied")){const P=new Z(C);this.log(y.ERROR,`Unexpected resp: ${C.Message}`),I(P);return}const x=c==="connection"?`${C.header.id_service}-${a.getPtlMessage().id_notation}`:C.header.id_job,z=typeof h>"u"?new Ae(C.header.id_job):new h(C.header.id_service,a.getPtlMessage().id_notation);S.idJob=C.header.id_job,k=this.hooks.hook(`frontgateConnection:response:${x}`,P=>{if(P.Message.includes("Error")||P.Message.includes("PermissionDenied")){this.log(y.ERROR,`Unexpected response: ${P.Message}`);const F=new Z(P);S.pushError(F);return}S.unsubscribe=()=>{const F=v(this,t).get(l);if(F){if(F.count--,F.count>0){this.log(y.INFO,`Not unsubscribing from ${l} as there are still ${F.count} subscribers`);return}v(this,t).delete(l)}this.log(y.INFO,`Unsubscribing from ${l}`);const j={message:z.getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",j),k(),N()},S.pushData(P)}),p()})});try{await ue(u,"Request timeout reached",g)}catch(p){S.pushError(new Z({Message:"Reconnect failed",Error:p}))}});S.unsubscribe=()=>{const g=v(this,t).get(l);if(g){if(g.count--,g.count>0){this.log(y.INFO,`Not unsubscribing from ${l} as there are still ${g.count} subscribers`);return}v(this,t).delete(l)}this.log(y.INFO,`Unsubscribing from ${l}`);const p={message:M.getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",p),k(),N()},v(this,t).set(l,{observer:S,count:1}),A(S)})}),_=`Request timeout reached (${u} ms) for ${f.message.Message}`;return ue(u,_,E)},o},{featureName:"RawSubscriptions",featureGroups:["Misc"]}),Pn=(n,e)=>{const t=e.split("/").slice(1);let r=n;for(let s=0;s<t.length-1;s++){const o=decodeURIComponent(t[s]);if(!(o in r))throw new Error(`Path not found: ${e}`);r=r[o]}return[r,decodeURIComponent(t[t.length-1])]},Zo=(n,e,t)=>{const[r,s]=Pn(n,e);r[s]=t},ei="-",ti=(n,e,t)=>{const[r,s]=Pn(n,e);Array.isArray(r)?s===ei?r.push(t):r.splice(parseInt(s,10),0,t):r[s]=t},ni=(n,e)=>{const[t,r]=Pn(n,e);Array.isArray(t)?t.splice(parseInt(r,10),1):delete t[r]};function ri(n,e){return e.forEach(t=>{switch(t.op){case"replace":Zo(n,t.path,t.value);break;case"add":ti(n,t.path,t.value);break;case"remove":ni(n,t.path);break;case"move":case"copy":case"test":default:throw new Error(`Unsupported op: ${t.op}`)}}),n}class Nn{constructor(e,t){O(this,qe);O(this,Mt,[]);O(this,St,[]);R(this,qe,t),this.idJob=e}get data(){return v(this,qe)}subscribe({next:e,error:t}){e(v(this,qe)),t&&v(this,St).push(t),v(this,Mt).push(e)}pushData(e){R(this,qe,e),v(this,Mt).forEach(t=>{t(e)})}pushError(e){v(this,St).forEach(t=>{t(e)})}}qe=new WeakMap,Mt=new WeakMap,St=new WeakMap;class is extends Nn{pushPatchData(e){try{const t=ri(this.data,e);super.pushData(t)}catch(t){super.pushError(new Z(t.message))}}}const si=n=>K(t=>class extends t{constructor(...r){super(...r),this.hooks.hook("frontgateConnection:beforeConnect",o=>{this.hooks.callHook("frontgateConnection:setIdApp",-2),this.hooks.callHook("frontgateConnection:setIdUser",-2),this.log(y.DEBUG,"Adding mdg2auth subprotocol"),o.subProtocols.push(`mdg2auth-${n}`)});const s=async o=>{this.hooks.callHook("frontgateConnection:setIdApp",-2),this.hooks.callHook("frontgateConnection:setIdUser",-2);const i={maximum_idle_interval:o.maximumIdleInterval},a={b64:""},h=new dt(a,i.maximum_idle_interval).toJson();this.log(y.INFO,"Sending message",h);const u={message:h,callbackType:"response",callbackId:h.Message.replace("Request","Response")};await this.hooks.callHook("frontgateConnection:sendMessage",u),this.hooks.hookOnce(`frontgateConnection:response:${u.callbackId}`,l=>{this.log(y.INFO,"Received response",l),this.hooks.callHook("frontgateConnection:authenticated")})};this.hooks.hookOnce("frontgateConnection:connected",s)}},{featureName:"CookieTokenAuth",featureGroups:["Auth"],disabledFeatureGroups:["Auth"]}),oi=n=>K(t=>{var r,s;return s=class extends t{constructor(...i){super(...i);O(this,r);R(this,r,n??"");const a=async c=>{this.hooks.callHook("frontgateConnection:setIdApp",-2),this.hooks.callHook("frontgateConnection:setIdUser",-2);const h={maximum_idle_interval:c.maximumIdleInterval},u={b64:v(this,r)},b=new dt(u,h.maximum_idle_interval).toJson();this.log(y.INFO,"Sending message",b);const f={message:b,callbackType:"response",callbackId:b.Message.replace("Request","Response")};await this.hooks.callHook("frontgateConnection:sendMessage",f),this.hooks.hookOnce(`frontgateConnection:response:${f.callbackId}`,E=>{this.log(y.INFO,"Received response",E),this.hooks.callHook("frontgateConnection:authenticated")})};this.hooks.hook("frontgateConnection:connected",a)}set token(i){R(this,r,i)}},r=new WeakMap,s},{featureName:"TokenAuth",featureGroups:["Auth"],disabledFeatureGroups:["Auth"]}),ii=(n,e,t)=>K(s=>{var o,i,a,c,h,Ws,l;return l=class extends os({host:"",pathPrefix:"",port:0,tls:!0,maximumIdleIntervalInS:n.maximumIdleIntervalInS})(s){constructor(...f){super(...f);O(this,h);O(this,o,"");O(this,i,"");O(this,a);O(this,c);R(this,a,e),R(this,c,t),this.hooks.hook("frontgateConnection:beforeConnect",async _=>{this.hooks.callHook("frontgateConnection:setIdApp",-2),this.hooks.callHook("frontgateConnection:setIdUser",-2),this.log(y.DEBUG,"Fetching connection configuration");const A=await q(this,h,Ws).call(this);if(this.log(y.DEBUG,"Connection configuration received",n),_.url=A.url,A.authtenticationType==="token"&&A.authenticationToken)R(this,o,A.authenticationToken);else if(A.splitAuthenticationTokenSecondFactor)R(this,i,A.splitAuthenticationTokenSecondFactor);else throw new Error("Invalid authentication configuration");this.log(y.DEBUG,"Adding mdg2auth subprotocol"),v(this,i)!==""&&_.subProtocols.push(`mdg2auth-${v(this,i)}`)});const E=async _=>{this.hooks.callHook("frontgateConnection:setIdApp",-2),this.hooks.callHook("frontgateConnection:setIdUser",-2);const A={maximum_idle_interval:_.maximumIdleInterval},w={b64:v(this,o)},T=new dt(w,A.maximum_idle_interval).toJson();this.log(y.INFO,"Sending message",T);const M={message:T,callbackType:"response",callbackId:T.Message.replace("Request","Response")};await this.hooks.callHook("frontgateConnection:sendMessage",M),this.hooks.hookOnce(`frontgateConnection:response:${M.callbackId}`,S=>{this.log(y.INFO,"Received response",S),this.hooks.callHook("frontgateConnection:authenticated")})};this.hooks.hook("frontgateConnection:connected",E)}},o=new WeakMap,i=new WeakMap,a=new WeakMap,c=new WeakMap,h=new WeakSet,Ws=async function(){const f=await fetch(v(this,a),v(this,c));if(!f.ok)throw new Error(`Failed to fetch connection configuration: ${f.status} ${f.statusText}`);const{headers:E}=f,_=E.get("frontgate-host"),A=E.get("frontgate-path-prefix"),w=E.get("frontgate-split-authentication-token-second-factor"),m=E.get("frontgate-authentication-type"),T=E.get("frontgate-authentication-token"),M=E.get("frontgate-websocket-port")??"443",S=`wss://${_}:${M}${A??""}/ws`;if(m==="token"&&!T)throw new Error("Authentication token is required for token authentication");if(m!=="token"&&!w)throw new Error("Split authentication token second factor is required");return{url:S,authtenticationType:m,authenticationToken:T,splitAuthenticationTokenSecondFactor:w}},l},{featureName:"FetchAuth",featureGroups:["Auth","Connection"],disabledFeatureGroups:["Auth","Connection"]}),ai=(n,e)=>({options:n,submit:async t=>{e.log(y.INFO,"Sending message",t);const r={message:t,callbackType:"response",callbackId:t.Message.replace("Request","Response")};await e.hooks.callHook("frontgateConnection:sendMessage",r);let s;return new Promise((o,i)=>{const a=e.hooks.hookOnce(`frontgateConnection:response:${r.callbackId}`,c=>{clearTimeout(s),e.log(y.INFO,"Received response",c),o(c)});s=setTimeout(()=>{a(),i(new Error("Authentication message timeout"))},3e3)})},setPeerInfo:t=>{e.log(y.INFO,"Peer info:",t)},auth:{}}),ci=()=>K(e=>{var t,r,s,o;return o=class extends e{constructor(...a){super(...a);O(this,t,0);O(this,r,[1e3,2e3,4e3,8e3,16e3,32e3]);O(this,s);const c=h=>{if(h.code!==1e3){v(this,s)&&(this.log(y.WARN,"Aborting previous reconnect attempt"),clearTimeout(v(this,s)),R(this,t,0));let u=v(this,t);v(this,t)>v(this,r).length&&(u=v(this,r).length-1);const l=v(this,r)[u];R(this,s,setTimeout(()=>{this.log(y.INFO,`Reconnecting... Attempt ${v(this,t)}`);const b=this.hooks.hookOnce("reconnect:failed",c);this.hooks.callHook("reconnect:attempt",h).then(b).catch(()=>{this.log(y.ERROR,"Failed to reconnect")}),R(this,s,void 0)},l)),$s(this,t)._++}};this.hooks.hookOnce("frontgateConnection:disconnected",c),this.hooks.hook("reconnect:success",()=>{clearTimeout(v(this,s)),R(this,s,void 0),R(this,t,0),this.log(y.INFO,"Reconnected"),this.hooks.hookOnce("frontgateConnection:disconnected",c)})}},t=new WeakMap,r=new WeakMap,s=new WeakMap,o},{featureName:"Reconnect",featureGroups:["Misc"],disabledFeatures:["TokenAuth","CookieTokenAuth"]});var ui=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},xe="1.9.0",as=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function hi(n){var e=new Set([n]),t=new Set,r=n.match(as);if(!r)return function(){return!1};var s={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(s.prerelease!=null)return function(c){return c===n};function o(a){return t.add(a),!1}function i(a){return e.add(a),!0}return function(c){if(e.has(c))return!0;if(t.has(c))return!1;var h=c.match(as);if(!h)return o(c);var u={major:+h[1],minor:+h[2],patch:+h[3],prerelease:h[4]};return u.prerelease!=null||s.major!==u.major?o(c):s.major===0?s.minor===u.minor&&s.patch<=u.patch?i(c):o(c):s.minor<=u.minor?i(c):o(c)}}var li=hi(xe),fi=xe.split(".")[0],pt=Symbol.for("opentelemetry.js.api."+fi),gt=ui;function vt(n,e,t,r){var s;r===void 0&&(r=!1);var o=gt[pt]=(s=gt[pt])!==null&&s!==void 0?s:{version:xe};if(!r&&o[n]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+n);return t.error(i.stack||i.message),!1}if(o.version!==xe){var i=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+n+" does not match previously registered API v"+xe);return t.error(i.stack||i.message),!1}return o[n]=e,t.debug("@opentelemetry/api: Registered a global for "+n+" v"+xe+"."),!0}function Fe(n){var e,t,r=(e=gt[pt])===null||e===void 0?void 0:e.version;if(!(!r||!li(r)))return(t=gt[pt])===null||t===void 0?void 0:t[n]}function bt(n,e){e.debug("@opentelemetry/api: Unregistering a global for "+n+" v"+xe+".");var t=gt[pt];t&&delete t[n]}var di=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return o},pi=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},gi=function(){function n(e){this._namespace=e.namespace||"DiagComponentLogger"}return n.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return mt("debug",this._namespace,e)},n.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return mt("error",this._namespace,e)},n.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return mt("info",this._namespace,e)},n.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return mt("warn",this._namespace,e)},n.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return mt("verbose",this._namespace,e)},n}();function mt(n,e,t){var r=Fe("diag");if(r)return t.unshift(e),r[n].apply(r,pi([],di(t),!1))}var re;(function(n){n[n.NONE=0]="NONE",n[n.ERROR=30]="ERROR",n[n.WARN=50]="WARN",n[n.INFO=60]="INFO",n[n.DEBUG=70]="DEBUG",n[n.VERBOSE=80]="VERBOSE",n[n.ALL=9999]="ALL"})(re||(re={}));function vi(n,e){n<re.NONE?n=re.NONE:n>re.ALL&&(n=re.ALL),e=e||{};function t(r,s){var o=e[r];return typeof o=="function"&&n>=s?o.bind(e):function(){}}return{error:t("error",re.ERROR),warn:t("warn",re.WARN),info:t("info",re.INFO),debug:t("debug",re.DEBUG),verbose:t("verbose",re.VERBOSE)}}var bi=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return o},mi=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},yi="diag",be=function(){function n(){function e(s){return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];var a=Fe("diag");if(a)return a[s].apply(a,mi([],bi(o),!1))}}var t=this,r=function(s,o){var i,a,c;if(o===void 0&&(o={logLevel:re.INFO}),s===t){var h=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((i=h.stack)!==null&&i!==void 0?i:h.message),!1}typeof o=="number"&&(o={logLevel:o});var u=Fe("diag"),l=vi((a=o.logLevel)!==null&&a!==void 0?a:re.INFO,s);if(u&&!o.suppressOverrideMessage){var b=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+b),l.warn("Current logger will overwrite one already registered from "+b)}return vt("diag",l,t,!0)};t.setLogger=r,t.disable=function(){bt(yi,t)},t.createComponentLogger=function(s){return new gi(s)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return n.instance=function(){return this._instance||(this._instance=new n),this._instance},n}(),wi=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return o},_i=function(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Ti=function(){function n(e){this._entries=e?new Map(e):new Map}return n.prototype.getEntry=function(e){var t=this._entries.get(e);if(t)return Object.assign({},t)},n.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var t=wi(e,2),r=t[0],s=t[1];return[r,s]})},n.prototype.setEntry=function(e,t){var r=new n(this._entries);return r._entries.set(e,t),r},n.prototype.removeEntry=function(e){var t=new n(this._entries);return t._entries.delete(e),t},n.prototype.removeEntries=function(){for(var e,t,r=[],s=0;s<arguments.length;s++)r[s]=arguments[s];var o=new n(this._entries);try{for(var i=_i(r),a=i.next();!a.done;a=i.next()){var c=a.value;o._entries.delete(c)}}catch(h){e={error:h}}finally{try{a&&!a.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}return o},n.prototype.clear=function(){return new n},n}();be.instance();function Ei(n){return n===void 0&&(n={}),new Ti(new Map(Object.entries(n)))}function cs(n){return Symbol.for(n)}var Mi=function(){function n(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(r){return t._currentContext.get(r)},t.setValue=function(r,s){var o=new n(t._currentContext);return o._currentContext.set(r,s),o},t.deleteValue=function(r){var s=new n(t._currentContext);return s._currentContext.delete(r),s}}return n}(),Si=new Mi,Ue=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[o]=s[o])},n(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),Ii=function(){function n(){}return n.prototype.createGauge=function(e,t){return xi},n.prototype.createHistogram=function(e,t){return Fi},n.prototype.createCounter=function(e,t){return Di},n.prototype.createUpDownCounter=function(e,t){return Ui},n.prototype.createObservableGauge=function(e,t){return Li},n.prototype.createObservableCounter=function(e,t){return $i},n.prototype.createObservableUpDownCounter=function(e,t){return qi},n.prototype.addBatchObservableCallback=function(e,t){},n.prototype.removeBatchObservableCallback=function(e){},n}(),qt=function(){function n(){}return n}(),Ai=function(n){Ue(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.add=function(t,r){},e}(qt),ki=function(n){Ue(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.add=function(t,r){},e}(qt),Ci=function(n){Ue(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.record=function(t,r){},e}(qt),Ri=function(n){Ue(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.record=function(t,r){},e}(qt),jn=function(){function n(){}return n.prototype.addCallback=function(e){},n.prototype.removeCallback=function(e){},n}(),Oi=function(n){Ue(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e}(jn),Pi=function(n){Ue(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e}(jn),Ni=function(n){Ue(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e}(jn),ji=new Ii,Di=new Ai,xi=new Ci,Fi=new Ri,Ui=new ki,$i=new Oi,Li=new Pi,qi=new Ni,Hi={get:function(n,e){if(n!=null)return n[e]},keys:function(n){return n==null?[]:Object.keys(n)}},Gi={set:function(n,e,t){n!=null&&(n[e]=t)}},Bi=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return o},Ji=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},Wi=function(){function n(){}return n.prototype.active=function(){return Si},n.prototype.with=function(e,t,r){for(var s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return t.call.apply(t,Ji([r],Bi(s),!1))},n.prototype.bind=function(e,t){return t},n.prototype.enable=function(){return this},n.prototype.disable=function(){return this},n}(),zi=function(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return o},Vi=function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))},Dn="context",Yi=new Wi,Ht=function(){function n(){}return n.getInstance=function(){return this._instance||(this._instance=new n),this._instance},n.prototype.setGlobalContextManager=function(e){return vt(Dn,e,be.instance())},n.prototype.active=function(){return this._getContextManager().active()},n.prototype.with=function(e,t,r){for(var s,o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return(s=this._getContextManager()).with.apply(s,Vi([e,t,r],zi(o),!1))},n.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},n.prototype._getContextManager=function(){return Fe(Dn)||Yi},n.prototype.disable=function(){this._getContextManager().disable(),bt(Dn,be.instance())},n}(),xn;(function(n){n[n.NONE=0]="NONE",n[n.SAMPLED=1]="SAMPLED"})(xn||(xn={}));var us="0000000000000000",hs="00000000000000000000000000000000",Ki={traceId:hs,spanId:us,traceFlags:xn.NONE},yt=function(){function n(e){e===void 0&&(e=Ki),this._spanContext=e}return n.prototype.spanContext=function(){return this._spanContext},n.prototype.setAttribute=function(e,t){return this},n.prototype.setAttributes=function(e){return this},n.prototype.addEvent=function(e,t){return this},n.prototype.addLink=function(e){return this},n.prototype.addLinks=function(e){return this},n.prototype.setStatus=function(e){return this},n.prototype.updateName=function(e){return this},n.prototype.end=function(e){},n.prototype.isRecording=function(){return!1},n.prototype.recordException=function(e,t){},n}(),Fn=cs("OpenTelemetry Context Key SPAN");function Un(n){return n.getValue(Fn)||void 0}function Qi(){return Un(Ht.getInstance().active())}function $n(n,e){return n.setValue(Fn,e)}function Xi(n){return n.deleteValue(Fn)}function Zi(n,e){return $n(n,new yt(e))}function ls(n){var e;return(e=Un(n))===null||e===void 0?void 0:e.spanContext()}var ea=/^([0-9a-f]{32})$/i,ta=/^[0-9a-f]{16}$/i;function na(n){return ea.test(n)&&n!==hs}function ra(n){return ta.test(n)&&n!==us}function fs(n){return na(n.traceId)&&ra(n.spanId)}function sa(n){return new yt(n)}var Ln=Ht.getInstance(),ds=function(){function n(){}return n.prototype.startSpan=function(e,t,r){r===void 0&&(r=Ln.active());var s=!!(t!=null&&t.root);if(s)return new yt;var o=r&&ls(r);return oa(o)&&fs(o)?new yt(o):new yt},n.prototype.startActiveSpan=function(e,t,r,s){var o,i,a;if(!(arguments.length<2)){arguments.length===2?a=t:arguments.length===3?(o=t,a=r):(o=t,i=r,a=s);var c=i??Ln.active(),h=this.startSpan(e,o,c),u=$n(c,h);return Ln.with(u,a,void 0,h)}},n}();function oa(n){return typeof n=="object"&&typeof n.spanId=="string"&&typeof n.traceId=="string"&&typeof n.traceFlags=="number"}var ia=new ds,aa=function(){function n(e,t,r,s){this._provider=e,this.name=t,this.version=r,this.options=s}return n.prototype.startSpan=function(e,t,r){return this._getTracer().startSpan(e,t,r)},n.prototype.startActiveSpan=function(e,t,r,s){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},n.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):ia},n}(),ca=function(){function n(){}return n.prototype.getTracer=function(e,t,r){return new ds},n}(),ua=new ca,ps=function(){function n(){}return n.prototype.getTracer=function(e,t,r){var s;return(s=this.getDelegateTracer(e,t,r))!==null&&s!==void 0?s:new aa(this,e,t,r)},n.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:ua},n.prototype.setDelegate=function(e){this._delegate=e},n.prototype.getDelegateTracer=function(e,t,r){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,t,r)},n}();Ht.getInstance(),be.instance();var ha=function(){function n(){}return n.prototype.getMeter=function(e,t,r){return ji},n}(),la=new ha,qn="metrics",fa=function(){function n(){}return n.getInstance=function(){return this._instance||(this._instance=new n),this._instance},n.prototype.setGlobalMeterProvider=function(e){return vt(qn,e,be.instance())},n.prototype.getMeterProvider=function(){return Fe(qn)||la},n.prototype.getMeter=function(e,t,r){return this.getMeterProvider().getMeter(e,t,r)},n.prototype.disable=function(){bt(qn,be.instance())},n}();fa.getInstance();var da=function(){function n(){}return n.prototype.inject=function(e,t){},n.prototype.extract=function(e,t){return e},n.prototype.fields=function(){return[]},n}(),Hn=cs("OpenTelemetry Baggage Key");function gs(n){return n.getValue(Hn)||void 0}function pa(){return gs(Ht.getInstance().active())}function ga(n,e){return n.setValue(Hn,e)}function va(n){return n.deleteValue(Hn)}var Gn="propagation",ba=new da,ma=function(){function n(){this.createBaggage=Ei,this.getBaggage=gs,this.getActiveBaggage=pa,this.setBaggage=ga,this.deleteBaggage=va}return n.getInstance=function(){return this._instance||(this._instance=new n),this._instance},n.prototype.setGlobalPropagator=function(e){return vt(Gn,e,be.instance())},n.prototype.inject=function(e,t,r){return r===void 0&&(r=Gi),this._getGlobalPropagator().inject(e,t,r)},n.prototype.extract=function(e,t,r){return r===void 0&&(r=Hi),this._getGlobalPropagator().extract(e,t,r)},n.prototype.fields=function(){return this._getGlobalPropagator().fields()},n.prototype.disable=function(){bt(Gn,be.instance())},n.prototype._getGlobalPropagator=function(){return Fe(Gn)||ba},n}();ma.getInstance();var Bn="trace",ya=function(){function n(){this._proxyTracerProvider=new ps,this.wrapSpanContext=sa,this.isSpanContextValid=fs,this.deleteSpan=Xi,this.getSpan=Un,this.getActiveSpan=Qi,this.getSpanContext=ls,this.setSpan=$n,this.setSpanContext=Zi}return n.getInstance=function(){return this._instance||(this._instance=new n),this._instance},n.prototype.setGlobalTracerProvider=function(e){var t=vt(Bn,this._proxyTracerProvider,be.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},n.prototype.getTracerProvider=function(){return Fe(Bn)||this._proxyTracerProvider},n.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},n.prototype.disable=function(){bt(Bn,be.instance()),this._proxyTracerProvider=new ps},n}(),vs=ya.getInstance();const wa=()=>K(e=>{var t,zs,s;return s=class extends e{constructor(...i){super(...i);O(this,t);this.hooks.hook("frontgateConnection:beforeSerializeMessage",a=>{a.header&&vs.getTracer("frontgate-js-sdk").startActiveSpan("frontgateConnection:sendMessage",c=>{const h=q(this,t,zs).call(this,c.spanContext());h&&(a.header={...a.header,...h}),c.end()})})}},t=new WeakSet,zs=function(i){if(!/^0+$/.test(i.traceId))return{tracing:{value:{value:bs(i)}}}},s},{featureName:"OpenTelemetry",featureGroups:["Misc"]}),bs=n=>{const e=[18,20,9],t=r=>{for(let s=r.length;s>r.length-16;s-=2){let o=parseInt(r.substring(s-2,s),16);o>127&&(o-=256),e.push(o)}};return t(n.traceId),e.push(17),t(n.spanId),e.push(24),e.push(0),e},_a=()=>K(e=>class extends e{async requestProxyEndpoint(t,r,s,o,i=this.defaultTimeoutInMs){const a=new Ke(t,r,o);s&&a.setBody(s),a.header.setTimeout(i);const c={message:a.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",c);const h=new Promise((l,b)=>{this.hooks.hookOnce(`frontgateConnection:response:${c.callbackId}`,f=>{try{if(!f.Message.includes("HTTPProxyResponse")){b(JSON.stringify(f));return}const E=new An(f);l({response:E,data:E.data})}catch(E){b(E)}})}),u=`Request timeout reached (${i} ms) for ${c.message.Message}`;return ue(i,u,h)}},{featureName:"HTTPProxyRequest",featureGroups:["Misc"]}),Ta=()=>K(e=>class extends e{async ping(t=this.defaultTimeoutInMs){const s={message:new ze().getPtlMessage(),callbackType:"response",callbackId:"PingResponse"};await this.hooks.callHook("frontgateConnection:sendMessage",s);const o=new Promise(a=>{this.hooks.hookOnce(`frontgateConnection:response:${s.callbackId}`,c=>{const h=new je(c);a(h)})}),i=`Request timeout reached (${t} ms) for ${s.message.Message}`;return ue(t,i,o)}},{featureName:"Pingable",featureGroups:["Misc"]}),K=(n,e)=>{const t=n;return t.featureName=e.featureName,t.featureGroups=e.featureGroups,t.disabledFeatures=e.disabledFeatures,t.disabledFeatureGroups=e.disabledFeatureGroups,t};var Jn=function(n,e){return Jn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=r[s])},Jn(n,e)};function Qe(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Jn(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function Ea(n,e,t,r){function s(o){return o instanceof t?o:new t(function(i){i(o)})}return new(t||(t=Promise))(function(o,i){function a(u){try{h(r.next(u))}catch(l){i(l)}}function c(u){try{h(r.throw(u))}catch(l){i(l)}}function h(u){u.done?o(u.value):s(u.value).then(a,c)}h((r=r.apply(n,e||[])).next())})}function ms(n,e){var t={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,s,o,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(h){return function(u){return c([h,u])}}function c(h){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,h[0]&&(t=0)),t;)try{if(r=1,s&&(o=h[0]&2?s.return:h[0]?s.throw||((o=s.return)&&o.call(s),0):s.next)&&!(o=o.call(s,h[1])).done)return o;switch(s=0,o&&(h=[h[0]&2,o.value]),h[0]){case 0:case 1:o=h;break;case 4:return t.label++,{value:h[1],done:!1};case 5:t.label++,s=h[1],h=[0];continue;case 7:h=t.ops.pop(),t.trys.pop();continue;default:if(o=t.trys,!(o=o.length>0&&o[o.length-1])&&(h[0]===6||h[0]===2)){t=0;continue}if(h[0]===3&&(!o||h[1]>o[0]&&h[1]<o[3])){t.label=h[1];break}if(h[0]===6&&t.label<o[1]){t.label=o[1],o=h;break}if(o&&t.label<o[2]){t.label=o[2],t.ops.push(h);break}o[2]&&t.ops.pop(),t.trys.pop();continue}h=e.call(n,t)}catch(u){h=[6,u],s=0}finally{r=o=0}if(h[0]&5)throw h[1];return{value:h[0]?h[1]:void 0,done:!0}}}function Xe(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Gt(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(a){i={error:a}}finally{try{s&&!s.done&&(t=r.return)&&t.call(r)}finally{if(i)throw i.error}}return o}function Bt(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))}function Ze(n){return this instanceof Ze?(this.v=n,this):new Ze(n)}function Ma(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,e||[]),s,o=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),s[Symbol.asyncIterator]=function(){return this},s;function i(f){return function(E){return Promise.resolve(E).then(f,l)}}function a(f,E){r[f]&&(s[f]=function(_){return new Promise(function(A,w){o.push([f,_,A,w])>1||c(f,_)})},E&&(s[f]=E(s[f])))}function c(f,E){try{h(r[f](E))}catch(_){b(o[0][3],_)}}function h(f){f.value instanceof Ze?Promise.resolve(f.value.v).then(u,l):b(o[0][2],f)}function u(f){c("next",f)}function l(f){c("throw",f)}function b(f,E){f(E),o.shift(),o.length&&c(o[0][0],o[0][1])}}function Sa(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof Xe=="function"?Xe(n):n[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(o){t[o]=n[o]&&function(i){return new Promise(function(a,c){i=n[o](i),s(a,c,i.done,i.value)})}}function s(o,i,a,c){Promise.resolve(c).then(function(h){o({value:h,done:a})},i)}}typeof SuppressedError=="function"&&SuppressedError;function Q(n){return typeof n=="function"}function ys(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Wn=ys(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
2
2
  `+t.map(function(r,s){return s+1+") "+r.toString()}).join(`
3
- `):"",this.name="UnsubscriptionError",this.errors=t}});function Wn(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var wt=function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,s,o;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=Qe(i),c=a.next();!c.done;c=a.next()){var h=c.value;h.remove(this)}}catch(_){e={error:_}}finally{try{c&&!c.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else i.remove(this);var u=this.initialTeardown;if(K(u))try{u()}catch(_){o=_ instanceof Jn?_.errors:[_]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var b=Qe(l),f=b.next();!f.done;f=b.next()){var T=f.value;try{Es(T)}catch(_){o=o??[],_ instanceof Jn?o=Bt(Bt([],Gt(o)),Gt(_.errors)):o.push(_)}}}catch(_){r={error:_}}finally{try{f&&!f.done&&(s=b.return)&&s.call(b)}finally{if(r)throw r.error}}}if(o)throw new Jn(o)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Es(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Wn(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&Wn(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=function(){var e=new n;return e.closed=!0,e}(),n}(),ws=wt.EMPTY;function _s(n){return n instanceof wt||n&&"closed"in n&&K(n.remove)&&K(n.add)&&K(n.unsubscribe)}function Es(n){K(n)?n():n.unsubscribe()}var Sa={Promise:void 0},Ia={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,Bt([n,e],Gt(t)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Ts(n){Ia.setTimeout(function(){throw n})}function Ms(){}function Jt(n){n()}var zn=function(n){Ke(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,_s(t)&&t.add(r)):r.destination=Oa,r}return e.create=function(t,r,s){return new _t(t,r,s)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(wt),Aa=function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){Wt(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){Wt(r)}else Wt(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Wt(t)}},n}(),_t=function(n){Ke(e,n);function e(t,r,s){var o=n.call(this)||this,i;return K(t)||!t?i={next:t??void 0,error:r??void 0,complete:s??void 0}:i=t,o.destination=new Aa(i),o}return e}(zn);function Wt(n){Ts(n)}function Ca(n){throw n}var Oa={closed:!0,next:Ms,error:Ca,complete:Ms},Vn=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Ss(n){return n}function Ra(n){return n.length===0?Ss:n.length===1?n[0]:function(t){return n.reduce(function(r,s){return s(r)},t)}}var Ce=function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var s=this,o=Pa(e)?e:new _t(e,t,r);return Jt(function(){var i=s,a=i.operator,c=i.source;o.add(a?a.call(o,c):c?s._subscribe(o):s._trySubscribe(o))}),o},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=Is(t),new t(function(s,o){var i=new _t({next:function(a){try{e(a)}catch(c){o(c),i.unsubscribe()}},error:o,complete:s});r.subscribe(i)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[Vn]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ra(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=Is(e),new e(function(r,s){var o;t.subscribe(function(i){return o=i},function(i){return s(i)},function(){return r(o)})})},n.create=function(e){return new n(e)},n}();function Is(n){var e;return(e=n??Sa.Promise)!==null&&e!==void 0?e:Promise}function ka(n){return n&&K(n.next)&&K(n.error)&&K(n.complete)}function Pa(n){return n&&n instanceof zn||ka(n)&&_s(n)}function Na(n){return K(n==null?void 0:n.lift)}function zt(n){return function(e){if(Na(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function Vt(n,e,t,r,s){return new ja(n,e,t,r,s)}var ja=function(n){Ke(e,n);function e(t,r,s,o,i,a){var c=n.call(this,t)||this;return c.onFinalize=i,c.shouldUnsubscribe=a,c._next=r?function(h){try{r(h)}catch(u){t.error(u)}}:n.prototype._next,c._error=o?function(h){try{o(h)}catch(u){t.error(u)}finally{this.unsubscribe()}}:n.prototype._error,c._complete=s?function(){try{s()}catch(h){t.error(h)}finally{this.unsubscribe()}}:n.prototype._complete,c}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(zn),Da=ys(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Et=function(n){Ke(e,n);function e(){var t=n.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new As(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new Da},e.prototype.next=function(t){var r=this;Jt(function(){var s,o;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var i=Qe(r.currentObservers),a=i.next();!a.done;a=i.next()){var c=a.value;c.next(t)}}catch(h){s={error:h}}finally{try{a&&!a.done&&(o=i.return)&&o.call(i)}finally{if(s)throw s.error}}}})},e.prototype.error=function(t){var r=this;Jt(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var s=r.observers;s.length;)s.shift().error(t)}})},e.prototype.complete=function(){var t=this;Jt(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,s=this,o=s.hasError,i=s.isStopped,a=s.observers;return o||i?ws:(this.currentObservers=null,a.push(t),new wt(function(){r.currentObservers=null,Wn(a,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,s=r.hasError,o=r.thrownError,i=r.isStopped;s?t.error(o):i&&t.complete()},e.prototype.asObservable=function(){var t=new Ce;return t.source=this,t},e.create=function(t,r){return new As(t,r)},e}(Ce),As=function(n){Ke(e,n);function e(t,r){var s=n.call(this)||this;return s.destination=t,s.source=r,s}return e.prototype.next=function(t){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.next)===null||s===void 0||s.call(r,t)},e.prototype.error=function(t){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.error)===null||s===void 0||s.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,s;return(s=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&s!==void 0?s:ws},e}(Et),Cs={now:function(){return(Cs.delegate||Date).now()},delegate:void 0},Yt=function(n){Ke(e,n);function e(t,r,s){t===void 0&&(t=1/0),r===void 0&&(r=1/0),s===void 0&&(s=Cs);var o=n.call(this)||this;return o._bufferSize=t,o._windowTime=r,o._timestampProvider=s,o._buffer=[],o._infiniteTimeWindow=!0,o._infiniteTimeWindow=r===1/0,o._bufferSize=Math.max(1,t),o._windowTime=Math.max(1,r),o}return e.prototype.next=function(t){var r=this,s=r.isStopped,o=r._buffer,i=r._infiniteTimeWindow,a=r._timestampProvider,c=r._windowTime;s||(o.push(t),!i&&o.push(a.now()+c)),this._trimBuffer(),n.prototype.next.call(this,t)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(t),s=this,o=s._infiniteTimeWindow,i=s._buffer,a=i.slice(),c=0;c<a.length&&!t.closed;c+=o?1:2)t.next(a[c]);return this._checkFinalizedStatuses(t),r},e.prototype._trimBuffer=function(){var t=this,r=t._bufferSize,s=t._timestampProvider,o=t._buffer,i=t._infiniteTimeWindow,a=(i?1:2)*r;if(r<1/0&&a<o.length&&o.splice(0,o.length-a),!i){for(var c=s.now(),h=0,u=1;u<o.length&&o[u]<=c;u+=2)h=u;h&&o.splice(0,h+1)}},e}(Et),xa=function(n){return n&&typeof n.length=="number"&&typeof n!="function"};function Fa(n){return K(n==null?void 0:n.then)}function Ua(n){return K(n[Vn])}function $a(n){return Symbol.asyncIterator&&K(n==null?void 0:n[Symbol.asyncIterator])}function La(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Ha(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var qa=Ha();function Ga(n){return K(n==null?void 0:n[qa])}function Ba(n){return Ta(this,arguments,function(){var t,r,s,o;return ms(this,function(i){switch(i.label){case 0:t=n.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,Xe(t.read())];case 3:return r=i.sent(),s=r.value,o=r.done,o?[4,Xe(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,Xe(s)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Ja(n){return K(n==null?void 0:n.getReader)}function Yn(n){if(n instanceof Ce)return n;if(n!=null){if(Ua(n))return Wa(n);if(xa(n))return za(n);if(Fa(n))return Va(n);if($a(n))return Os(n);if(Ga(n))return Ya(n);if(Ja(n))return Ka(n)}throw La(n)}function Wa(n){return new Ce(function(e){var t=n[Vn]();if(K(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function za(n){return new Ce(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function Va(n){return new Ce(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,Ts)})}function Ya(n){return new Ce(function(e){var t,r;try{for(var s=Qe(n),o=s.next();!o.done;o=s.next()){var i=o.value;if(e.next(i),e.closed)return}}catch(a){t={error:a}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}e.complete()})}function Os(n){return new Ce(function(e){Qa(n,e).catch(function(t){return e.error(t)})})}function Ka(n){return Os(Ba(n))}function Qa(n,e){var t,r,s,o;return Ea(this,void 0,void 0,function(){var i,a;return ms(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),t=Ma(n),c.label=1;case 1:return[4,t.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),s={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(o=t.return)?[4,o.call(t)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(s)throw s.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Xa(n,e){return zt(function(t,r){var s=0;t.subscribe(Vt(r,function(o){r.next(n.call(e,o,s++))}))})}function Za(n,e){return zt(function(t,r){var s=0;t.subscribe(Vt(r,function(o){return n.call(e,o,s++)&&r.next(o)}))})}function ec(n){n===void 0&&(n={});var e=n.connector,t=e===void 0?function(){return new Et}:e,r=n.resetOnError,s=r===void 0?!0:r,o=n.resetOnComplete,i=o===void 0?!0:o,a=n.resetOnRefCountZero,c=a===void 0?!0:a;return function(h){var u,l,b,f=0,T=!1,_=!1,A=function(){l==null||l.unsubscribe(),l=void 0},w=function(){A(),u=b=void 0,T=_=!1},m=function(){var E=u;w(),E==null||E.unsubscribe()};return zt(function(E,M){f++,!_&&!T&&A();var S=b=b??t();M.add(function(){f--,f===0&&!_&&!T&&(l=Kn(m,c))}),S.subscribe(M),!u&&f>0&&(u=new _t({next:function(C){return S.next(C)},error:function(C){_=!0,A(),l=Kn(w,s,C),S.error(C)},complete:function(){T=!0,A(),l=Kn(w,i),S.complete()}}),Yn(E).subscribe(u))})(h)}}function Kn(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];if(e===!0){n();return}if(e!==!1){var s=new _t({next:function(){s.unsubscribe(),n()}});return Yn(e.apply(void 0,Bt([],Gt(t)))).subscribe(s)}}function Rs(n,e,t){var r,s=!1;return r=n,ec({connector:function(){return new Yt(r,e,t)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:s})}function tc(n,e){return zt(function(t,r){var s=null,o=0,i=!1,a=function(){return i&&!s&&r.complete()};t.subscribe(Vt(r,function(c){s==null||s.unsubscribe();var h=0,u=o++;Yn(n(c,u)).subscribe(s=Vt(r,function(l){return r.next(e?e(c,l,u,h++):l)},function(){s=null,a()}))},function(){i=!0,a()}))})}function nc(){return tc(Ss)}const rc={defaultTimeoutInMs:wn,defaultTimeoutTokenInMs:Or,maxTimeoutsBeforeReconnect:Rr,flagPermissionDenied:kr,replaySubjectBufferSize:Pr};class Kt{constructor(e,t,r=rc){this.getConnection=e,this.logger=t,this.options=r,this.rejectResponsesTimeout=[50,100,200,400,800,1600,3200],this.timeoutCounter=0,this.subscription=wt.EMPTY,this.chunks=new Map,this.replaySubjectBufferSize=r.replaySubjectBufferSize,this.requestSubject=new Yt(this.replaySubjectBufferSize),this.jobs=new Map}setLogger(e){this.logger=e}reset(){this.logger.trace("requestModule.reset()"),this.requestSubject.complete(),this.requestSubject=new Yt(this.replaySubjectBufferSize),this.chunks.clear()}async requestWithQuality(e,t,r=this.options.defaultTimeoutInMs){return t==="BST"?this.requestBestQuality(e,r):(t&&Object.keys(ft.PRICE_QUALITY).includes(t)&&e.header.setQuality(t),this.request(e,r))}async requestEndpoint(e,t,r,s,o=this.options.defaultTimeoutInMs){const i=new ve(e,t,r,s);try{const a=await this.request(i,o);return this.logger.info(`Endpoint Response: [${e}] ${t}`,{request:r,response:a.data}),{response:a,data:a.data}}catch(a){const c=Tn(a);throw this.logger.warn(`Endpoint Request Failed. ${c.message}`,a),c}}async requestProxyEndpoint(e,t,r,s,o=this.options.defaultTimeoutInMs){const i=new Ye(e,t,s);r&&i.setBody(r);try{const a=await this.request(i,o);return this.logger.info(`Proxy Endpoint Response: [${e}] ${t}`,{request:r,response:a.data}),{response:a,data:a.data}}catch(a){const c=Tn(a);throw this.logger.warn(`Proxy Endpoint Request Failed. ${c.message}`,a),c}}async requestAuthenticationToken(e,t,r,s=this.options.defaultTimeoutTokenInMs){const o=new je(e,t,r,s);return(await this.request(o,s)).getToken()}async requestAuthenticationTokenExpiry(e,t,r,s=this.options.defaultTimeoutTokenInMs,o=!1){const i=new je(e,t,r,s,o),a=await this.request(i,s),c=a.getToken(),h=a.getExpiry();return{token:c,expiry:h}}async requestAuthenticationTokenFactorsForCookieAuthentication(e,t,r,s=this.options.defaultTimeoutTokenInMs){const o=await this.requestAuthenticationToken(e,t,r,s);return new rs(o)}onConnection(){const e=this.getConnection();if(!e)throw new Error("Runtime error: Please assign a connection to the client instance.");this.subscription.closed&&(e.onMessage=this.handleMessage.bind(this),this.subscription=this.requestSubject.subscribe(this.sendRequest.bind(this)),this.logger.trace("onConnection"))}setUpdateMessageHandler(e){this.updateMessageHandler=e}setLossMessageHandler(e){this.lossMessageHandler=e}async request(e,t=this.options.defaultTimeoutInMs){const r=this.getConnection();if(!r)throw new Error("Runtime error: Please assign a connection to the client instance.");return Kt.supportedPermissionDeniedResponseMessages(e)&&this.options.flagPermissionDenied&&e.header.setFlag("permission_denied_response"),Kt.supportsChunkedResponse(e)&&e.header.setFlag("allow_chunked_response"),e.header.setTimeout(t),vs.getTracer("MDG2Client").startActiveSpan("RequestModule.request",async s=>{e.header.setTracing(s.spanContext());const o=`Request timeout reached (${t} ms) for ${e.getPtlMessage().Message}`,i=new Promise((a,c)=>{this.requestSubject.next({msg:e,insertedAt:Date.now(),resolve:a,reject:c})});return ze.wrap(i,t,o).then(a=>(this.logger.trace("Reset timeout counter"),this.timeoutCounter=0,a)).catch(a=>{if(a.code===408){this.timeoutCounter++,this.logger.trace(`Increment timeout counter to ${this.timeoutCounter}`);const c=this.options.maxTimeoutsBeforeReconnect;this.timeoutCounter===c&&(this.logger.warn(`Closing connection due to max number of timeouts reached (${c})`),r.close(!0).catch(h=>{this.logger.error("Error while closing connection",h)}),this.timeoutCounter=0)}else{const c=Tn(a);this.logger.trace(`Endpoint Request Failed. ${c.message}`)}throw a}).finally(()=>{s.end()})})}reRequest(e){this.requestSubject.next({msg:e.msg,resolve:e.resolve,reject:e.reject})}async requestBestQuality(e,t=this.options.defaultTimeoutInMs){const r=["RLT","DLY","EOD"];for(let s=0;s<r.length;s++){e.header.setQuality(r[s]);const o=this.request(e,t);try{return await o}catch(i){this.logger.debug(`Failed to perform request in "${r[s]}" quality.`,i,e)}if(s===r.length-1)return o}return{Message:"Should never happen",Version:1}}prependCollectedChunks(e){const t=this.chunks.get(e.header.id_job);if(t===void 0)return;this.logger.trace("Prepending previous chunks to message",e);let r="";t.forEach(s=>{this.logger.trace("Prepending previous chunk to message",s),r+=s.body.value,e.header.processingTime+=s.header.processingTime}),r+=e.body.value,e.body.value=r,this.chunks.delete(e.header.id_job)}collectChunk(e){var t;this.chunks.has(e.header.id_job)?(t=this.chunks.get(e.header.id_job))==null||t.push(e):this.chunks.set(e.header.id_job,[e])}handleMessage(e){let t;if(Vr(e)){if(Lt.hasNextChunk(e)){this.logger.trace("Received message chunk",e),this.collectChunk(e);return}this.prependCollectedChunks(e)}try{t=Lt.createMessage(e)}catch(o){this.logger.error("Problem while creating message",o,e);return}const{jobId:r}=t,s=this.jobs.get(r);if(t.isUpdateMessage()&&this.updateMessageHandler){this.updateMessageHandler(t,r);return}if(t.isLossMessage()&&this.lossMessageHandler){this.lossMessageHandler(t,r),this.jobs.delete(r);return}if(!s){this.logger.error(`Could not find idJob ${r}`,e);return}if(Yr(t)){this.logger.debug(`RejectResponse received for idJob ${r}`,e),this.rejectResponseHandler(s);return}if(Jr(t)||Wr(t)){const o={request:s.request,response:t};this.logger.warn(`Received ${t.name} with idJob: ${r}`,o),s.reject(t),this.jobs.delete(r);return}this.logger.trace(`Received ${t.name} with idJob: ${r}`,t),this.jobs.delete(r),s.resolve(t)}rejectResponseHandler(e){const t=this.getRejectResponseTimeout(e.msg.header.getResendCounter()),r=e.expirationTime-Date.now()-t;if(r<1){const s=`Timeout for idJob ${e.msg.header.getJobId()}`;this.logger.error(s),e.reject(new X({Message:"Foundation::ErrorResponse",Version:1,id_job:e.msg.header.getJobId(),reason:8,details:s}))}this.logger.debug(`Retry request after ${t}ms for idJob ${e.msg.header.getJobId()}`),setTimeout(()=>{e.msg.header.setTimeout(r),e.msg.header.countResend(),this.reRequest(e)},t)}getRejectResponseTimeout(e=0){const t=this.rejectResponsesTimeout.length-1;return this.rejectResponsesTimeout[e]??this.rejectResponsesTimeout[t]}async sendRequest(e){const t=this.getConnection();if(!t){e.reject("Runtime error: Please assign a connection to the client instance.");return}for(;!t.isAuthenticated();){if(e.insertedAt&&e.insertedAt+e.msg.header.getTimeout()<Date.now()){e.reject("sendRequest timeout reached");return}await new Promise(a=>{setTimeout(()=>{a("Timeout reached")},1e3)})}e.msg.header.setIdApplication(t.auth.idApplication),e.msg.header.setIdUser(t.auth.idUser);const r=e.msg.getPtlMessage(),s=t.send(r).idJob;e.msg.header.setJobId(s);const o={json:r};(r.Message===ve.NAME||r.Message===Ye.NAME)&&typeof e.msg.getData=="function"&&(o.data=e.msg.getData());const i={msg:e.msg,expirationTime:Date.now()+e.msg.header.getTimeout(),resolve:e.resolve,reject:e.reject,request:o};this.jobs.set(s,i),this.logger.trace(`Sending ${r.Message} with idJob: ${s}`,o)}clearPendingRequests(){this.jobs.forEach((e,t)=>{const r=new X({Message:"Foundation::ErrorResponse",header:{id_job:t,id_service:"0"},reason:{value:1001}});e.reject(r)}),this.jobs.clear(),this.reset()}static supportedPermissionDeniedResponseMessages(e){const t=[ve];for(const r of t)if(e instanceof r)return!0;return!1}static supportsChunkedResponse(e){return e instanceof ve&&!e.header.isFlagValueSet("add_subscription")}}/*!
3
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function zn(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var wt=function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,s,o;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=Xe(i),c=a.next();!c.done;c=a.next()){var h=c.value;h.remove(this)}}catch(_){e={error:_}}finally{try{c&&!c.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else i.remove(this);var u=this.initialTeardown;if(Q(u))try{u()}catch(_){o=_ instanceof Wn?_.errors:[_]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var b=Xe(l),f=b.next();!f.done;f=b.next()){var E=f.value;try{Ts(E)}catch(_){o=o??[],_ instanceof Wn?o=Bt(Bt([],Gt(o)),Gt(_.errors)):o.push(_)}}}catch(_){r={error:_}}finally{try{f&&!f.done&&(s=b.return)&&s.call(b)}finally{if(r)throw r.error}}}if(o)throw new Wn(o)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Ts(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&zn(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&zn(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=function(){var e=new n;return e.closed=!0,e}(),n}(),ws=wt.EMPTY;function _s(n){return n instanceof wt||n&&"closed"in n&&Q(n.remove)&&Q(n.add)&&Q(n.unsubscribe)}function Ts(n){Q(n)?n():n.unsubscribe()}var Ia={Promise:void 0},Aa={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];return setTimeout.apply(void 0,Bt([n,e],Gt(t)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Es(n){Aa.setTimeout(function(){throw n})}function Ms(){}function Jt(n){n()}var Vn=function(n){Qe(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,_s(t)&&t.add(r)):r.destination=Ra,r}return e.create=function(t,r,s){return new _t(t,r,s)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(wt),ka=function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){Wt(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){Wt(r)}else Wt(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){Wt(t)}},n}(),_t=function(n){Qe(e,n);function e(t,r,s){var o=n.call(this)||this,i;return Q(t)||!t?i={next:t??void 0,error:r??void 0,complete:s??void 0}:i=t,o.destination=new ka(i),o}return e}(Vn);function Wt(n){Es(n)}function Ca(n){throw n}var Ra={closed:!0,next:Ms,error:Ca,complete:Ms},Yn=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function Ss(n){return n}function Oa(n){return n.length===0?Ss:n.length===1?n[0]:function(t){return n.reduce(function(r,s){return s(r)},t)}}var ke=function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var s=this,o=Na(e)?e:new _t(e,t,r);return Jt(function(){var i=s,a=i.operator,c=i.source;o.add(a?a.call(o,c):c?s._subscribe(o):s._trySubscribe(o))}),o},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=Is(t),new t(function(s,o){var i=new _t({next:function(a){try{e(a)}catch(c){o(c),i.unsubscribe()}},error:o,complete:s});r.subscribe(i)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[Yn]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Oa(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=Is(e),new e(function(r,s){var o;t.subscribe(function(i){return o=i},function(i){return s(i)},function(){return r(o)})})},n.create=function(e){return new n(e)},n}();function Is(n){var e;return(e=n??Ia.Promise)!==null&&e!==void 0?e:Promise}function Pa(n){return n&&Q(n.next)&&Q(n.error)&&Q(n.complete)}function Na(n){return n&&n instanceof Vn||Pa(n)&&_s(n)}function ja(n){return Q(n==null?void 0:n.lift)}function zt(n){return function(e){if(ja(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function Vt(n,e,t,r,s){return new Da(n,e,t,r,s)}var Da=function(n){Qe(e,n);function e(t,r,s,o,i,a){var c=n.call(this,t)||this;return c.onFinalize=i,c.shouldUnsubscribe=a,c._next=r?function(h){try{r(h)}catch(u){t.error(u)}}:n.prototype._next,c._error=o?function(h){try{o(h)}catch(u){t.error(u)}finally{this.unsubscribe()}}:n.prototype._error,c._complete=s?function(){try{s()}catch(h){t.error(h)}finally{this.unsubscribe()}}:n.prototype._complete,c}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(Vn),xa=ys(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),Tt=function(n){Qe(e,n);function e(){var t=n.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new As(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new xa},e.prototype.next=function(t){var r=this;Jt(function(){var s,o;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var i=Xe(r.currentObservers),a=i.next();!a.done;a=i.next()){var c=a.value;c.next(t)}}catch(h){s={error:h}}finally{try{a&&!a.done&&(o=i.return)&&o.call(i)}finally{if(s)throw s.error}}}})},e.prototype.error=function(t){var r=this;Jt(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var s=r.observers;s.length;)s.shift().error(t)}})},e.prototype.complete=function(){var t=this;Jt(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,s=this,o=s.hasError,i=s.isStopped,a=s.observers;return o||i?ws:(this.currentObservers=null,a.push(t),new wt(function(){r.currentObservers=null,zn(a,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,s=r.hasError,o=r.thrownError,i=r.isStopped;s?t.error(o):i&&t.complete()},e.prototype.asObservable=function(){var t=new ke;return t.source=this,t},e.create=function(t,r){return new As(t,r)},e}(ke),As=function(n){Qe(e,n);function e(t,r){var s=n.call(this)||this;return s.destination=t,s.source=r,s}return e.prototype.next=function(t){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.next)===null||s===void 0||s.call(r,t)},e.prototype.error=function(t){var r,s;(s=(r=this.destination)===null||r===void 0?void 0:r.error)===null||s===void 0||s.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,s;return(s=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&s!==void 0?s:ws},e}(Tt),ks={now:function(){return(ks.delegate||Date).now()},delegate:void 0},Yt=function(n){Qe(e,n);function e(t,r,s){t===void 0&&(t=1/0),r===void 0&&(r=1/0),s===void 0&&(s=ks);var o=n.call(this)||this;return o._bufferSize=t,o._windowTime=r,o._timestampProvider=s,o._buffer=[],o._infiniteTimeWindow=!0,o._infiniteTimeWindow=r===1/0,o._bufferSize=Math.max(1,t),o._windowTime=Math.max(1,r),o}return e.prototype.next=function(t){var r=this,s=r.isStopped,o=r._buffer,i=r._infiniteTimeWindow,a=r._timestampProvider,c=r._windowTime;s||(o.push(t),!i&&o.push(a.now()+c)),this._trimBuffer(),n.prototype.next.call(this,t)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(t),s=this,o=s._infiniteTimeWindow,i=s._buffer,a=i.slice(),c=0;c<a.length&&!t.closed;c+=o?1:2)t.next(a[c]);return this._checkFinalizedStatuses(t),r},e.prototype._trimBuffer=function(){var t=this,r=t._bufferSize,s=t._timestampProvider,o=t._buffer,i=t._infiniteTimeWindow,a=(i?1:2)*r;if(r<1/0&&a<o.length&&o.splice(0,o.length-a),!i){for(var c=s.now(),h=0,u=1;u<o.length&&o[u]<=c;u+=2)h=u;h&&o.splice(0,h+1)}},e}(Tt),Fa=function(n){return n&&typeof n.length=="number"&&typeof n!="function"};function Ua(n){return Q(n==null?void 0:n.then)}function $a(n){return Q(n[Yn])}function La(n){return Symbol.asyncIterator&&Q(n==null?void 0:n[Symbol.asyncIterator])}function qa(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Ha(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Ga=Ha();function Ba(n){return Q(n==null?void 0:n[Ga])}function Ja(n){return Ma(this,arguments,function(){var t,r,s,o;return ms(this,function(i){switch(i.label){case 0:t=n.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,Ze(t.read())];case 3:return r=i.sent(),s=r.value,o=r.done,o?[4,Ze(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,Ze(s)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function Wa(n){return Q(n==null?void 0:n.getReader)}function Kn(n){if(n instanceof ke)return n;if(n!=null){if($a(n))return za(n);if(Fa(n))return Va(n);if(Ua(n))return Ya(n);if(La(n))return Cs(n);if(Ba(n))return Ka(n);if(Wa(n))return Qa(n)}throw qa(n)}function za(n){return new ke(function(e){var t=n[Yn]();if(Q(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Va(n){return new ke(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function Ya(n){return new ke(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,Es)})}function Ka(n){return new ke(function(e){var t,r;try{for(var s=Xe(n),o=s.next();!o.done;o=s.next()){var i=o.value;if(e.next(i),e.closed)return}}catch(a){t={error:a}}finally{try{o&&!o.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}e.complete()})}function Cs(n){return new ke(function(e){Xa(n,e).catch(function(t){return e.error(t)})})}function Qa(n){return Cs(Ja(n))}function Xa(n,e){var t,r,s,o;return Ea(this,void 0,void 0,function(){var i,a;return ms(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),t=Sa(n),c.label=1;case 1:return[4,t.next()];case 2:if(r=c.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),s={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(o=t.return)?[4,o.call(t)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(s)throw s.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Za(n,e){return zt(function(t,r){var s=0;t.subscribe(Vt(r,function(o){r.next(n.call(e,o,s++))}))})}function ec(n,e){return zt(function(t,r){var s=0;t.subscribe(Vt(r,function(o){return n.call(e,o,s++)&&r.next(o)}))})}function tc(n){n===void 0&&(n={});var e=n.connector,t=e===void 0?function(){return new Tt}:e,r=n.resetOnError,s=r===void 0?!0:r,o=n.resetOnComplete,i=o===void 0?!0:o,a=n.resetOnRefCountZero,c=a===void 0?!0:a;return function(h){var u,l,b,f=0,E=!1,_=!1,A=function(){l==null||l.unsubscribe(),l=void 0},w=function(){A(),u=b=void 0,E=_=!1},m=function(){var T=u;w(),T==null||T.unsubscribe()};return zt(function(T,M){f++,!_&&!E&&A();var S=b=b??t();M.add(function(){f--,f===0&&!_&&!E&&(l=Qn(m,c))}),S.subscribe(M),!u&&f>0&&(u=new _t({next:function(k){return S.next(k)},error:function(k){_=!0,A(),l=Qn(w,s,k),S.error(k)},complete:function(){E=!0,A(),l=Qn(w,i),S.complete()}}),Kn(T).subscribe(u))})(h)}}function Qn(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];if(e===!0){n();return}if(e!==!1){var s=new _t({next:function(){s.unsubscribe(),n()}});return Kn(e.apply(void 0,Bt([],Gt(t)))).subscribe(s)}}function Rs(n,e,t){var r,s=!1;return r=n,tc({connector:function(){return new Yt(r,e,t)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:s})}function nc(n,e){return zt(function(t,r){var s=null,o=0,i=!1,a=function(){return i&&!s&&r.complete()};t.subscribe(Vt(r,function(c){s==null||s.unsubscribe();var h=0,u=o++;Kn(n(c,u)).subscribe(s=Vt(r,function(l){return r.next(e?e(c,l,u,h++):l)},function(){s=null,a()}))},function(){i=!0,a()}))})}function rc(){return nc(Ss)}const sc={defaultTimeoutInMs:wn,defaultTimeoutTokenInMs:Rr,maxTimeoutsBeforeReconnect:Or,flagPermissionDenied:Pr,replaySubjectBufferSize:Nr};class Kt{constructor(e,t,r=sc){this.getConnection=e,this.logger=t,this.options=r,this.rejectResponsesTimeout=[50,100,200,400,800,1600,3200],this.timeoutCounter=0,this.subscription=wt.EMPTY,this.chunks=new Map,this.replaySubjectBufferSize=r.replaySubjectBufferSize,this.requestSubject=new Yt(this.replaySubjectBufferSize),this.jobs=new Map}setLogger(e){this.logger=e}reset(){this.logger.trace("requestModule.reset()"),this.requestSubject.complete(),this.requestSubject=new Yt(this.replaySubjectBufferSize),this.chunks.clear()}async requestWithQuality(e,t,r=this.options.defaultTimeoutInMs){return t==="BST"?this.requestBestQuality(e,r):(t&&Object.keys(ft.PRICE_QUALITY).includes(t)&&e.header.setQuality(t),this.request(e,r))}async requestEndpoint(e,t,r,s,o=this.options.defaultTimeoutInMs){const i=new ve(e,t,r,s);try{const a=await this.request(i,o);return this.logger.info(`Endpoint Response: [${e}] ${t}`,{request:r,response:a.data}),{response:a,data:a.data}}catch(a){const c=En(a);throw this.logger.warn(`Endpoint Request Failed. ${c.message}`,a),c}}async requestProxyEndpoint(e,t,r,s,o=this.options.defaultTimeoutInMs){const i=new Ke(e,t,s);r&&i.setBody(r);try{const a=await this.request(i,o);return this.logger.info(`Proxy Endpoint Response: [${e}] ${t}`,{request:r,response:a.data}),{response:a,data:a.data}}catch(a){const c=En(a);throw this.logger.warn(`Proxy Endpoint Request Failed. ${c.message}`,a),c}}async requestAuthenticationToken(e,t,r,s=this.options.defaultTimeoutTokenInMs){const o=new De(e,t,r,s);return(await this.request(o,s)).getToken()}async requestAuthenticationTokenExpiry(e,t,r,s=this.options.defaultTimeoutTokenInMs,o=!1){const i=new De(e,t,r,s,o),a=await this.request(i,s),c=a.getToken(),h=a.getExpiry();return{token:c,expiry:h}}async requestAuthenticationTokenFactorsForCookieAuthentication(e,t,r,s=this.options.defaultTimeoutTokenInMs){const o=await this.requestAuthenticationToken(e,t,r,s);return new Rn(o)}onConnection(){const e=this.getConnection();if(!e)throw new Error("Runtime error: Please assign a connection to the client instance.");this.subscription.closed&&(e.onMessage=this.handleMessage.bind(this),this.subscription=this.requestSubject.subscribe(this.sendRequest.bind(this)),this.logger.trace("onConnection"))}setUpdateMessageHandler(e){this.updateMessageHandler=e}setLossMessageHandler(e){this.lossMessageHandler=e}async request(e,t=this.options.defaultTimeoutInMs){const r=this.getConnection();if(!r)throw new Error("Runtime error: Please assign a connection to the client instance.");return Kt.supportedPermissionDeniedResponseMessages(e)&&this.options.flagPermissionDenied&&e.header.setFlag("permission_denied_response"),Kt.supportsChunkedResponse(e)&&e.header.setFlag("allow_chunked_response"),e.header.setTimeout(t),vs.getTracer("MDG2Client").startActiveSpan("RequestModule.request",async s=>{e.header.setTracing(s.spanContext());const o=`Request timeout reached (${t} ms) for ${e.getPtlMessage().Message}`,i=new Promise((a,c)=>{this.requestSubject.next({msg:e,insertedAt:Date.now(),resolve:a,reject:c})});return Ve.wrap(i,t,o).then(a=>(this.logger.trace("Reset timeout counter"),this.timeoutCounter=0,a)).catch(a=>{if(a.code===408){this.timeoutCounter++,this.logger.trace(`Increment timeout counter to ${this.timeoutCounter}`);const c=this.options.maxTimeoutsBeforeReconnect;this.timeoutCounter===c&&(this.logger.warn(`Closing connection due to max number of timeouts reached (${c})`),r.close(!0).catch(h=>{this.logger.error("Error while closing connection",h)}),this.timeoutCounter=0)}else{const c=En(a);this.logger.trace(`Endpoint Request Failed. ${c.message}`)}throw a}).finally(()=>{s.end()})})}reRequest(e){this.requestSubject.next({msg:e.msg,resolve:e.resolve,reject:e.reject})}async requestBestQuality(e,t=this.options.defaultTimeoutInMs){const r=["RLT","DLY","EOD"];for(let s=0;s<r.length;s++){e.header.setQuality(r[s]);const o=this.request(e,t);try{return await o}catch(i){this.logger.debug(`Failed to perform request in "${r[s]}" quality.`,i,e)}if(s===r.length-1)return o}return{Message:"Should never happen",Version:1}}prependCollectedChunks(e){const t=this.chunks.get(e.header.id_job);if(t===void 0)return;this.logger.trace("Prepending previous chunks to message",e);let r="";t.forEach(s=>{this.logger.trace("Prepending previous chunk to message",s),r+=s.body.value,e.header.processingTime+=s.header.processingTime}),r+=e.body.value,e.body.value=r,this.chunks.delete(e.header.id_job)}collectChunk(e){var t;this.chunks.has(e.header.id_job)?(t=this.chunks.get(e.header.id_job))==null||t.push(e):this.chunks.set(e.header.id_job,[e])}handleMessage(e){let t;if(Yr(e)){if(Lt.hasNextChunk(e)){this.logger.trace("Received message chunk",e),this.collectChunk(e);return}this.prependCollectedChunks(e)}try{t=Lt.createMessage(e)}catch(o){this.logger.error("Problem while creating message",o,e);return}const{jobId:r}=t,s=this.jobs.get(r);if(t.isUpdateMessage()&&this.updateMessageHandler){this.updateMessageHandler(t,r);return}if(t.isLossMessage()&&this.lossMessageHandler){this.lossMessageHandler(t,r),this.jobs.delete(r);return}if(!s){this.logger.error(`Could not find idJob ${r}`,e);return}if(Kr(t)){this.logger.debug(`RejectResponse received for idJob ${r}`,e),this.rejectResponseHandler(s);return}if(Wr(t)||zr(t)){const o={request:s.request,response:t};this.logger.warn(`Received ${t.name} with idJob: ${r}`,o),s.reject(t),this.jobs.delete(r);return}this.logger.trace(`Received ${t.name} with idJob: ${r}`,t),this.jobs.delete(r),s.resolve(t)}rejectResponseHandler(e){const t=this.getRejectResponseTimeout(e.msg.header.getResendCounter()),r=e.expirationTime-Date.now()-t;if(r<1){const s=`Timeout for idJob ${e.msg.header.getJobId()}`;this.logger.error(s),e.reject(new Z({Message:"Foundation::ErrorResponse",Version:1,id_job:e.msg.header.getJobId(),reason:8,details:s}))}this.logger.debug(`Retry request after ${t}ms for idJob ${e.msg.header.getJobId()}`),setTimeout(()=>{e.msg.header.setTimeout(r),e.msg.header.countResend(),this.reRequest(e)},t)}getRejectResponseTimeout(e=0){const t=this.rejectResponsesTimeout.length-1;return this.rejectResponsesTimeout[e]??this.rejectResponsesTimeout[t]}async sendRequest(e){const t=this.getConnection();if(!t){e.reject("Runtime error: Please assign a connection to the client instance.");return}for(;!t.isAuthenticated();){if(e.insertedAt&&e.insertedAt+e.msg.header.getTimeout()<Date.now()){e.reject("sendRequest timeout reached");return}await new Promise(a=>{setTimeout(()=>{a("Timeout reached")},1e3)})}e.msg.header.setIdApplication(t.auth.idApplication),e.msg.header.setIdUser(t.auth.idUser);const r=e.msg.getPtlMessage(),s=t.send(r).idJob;e.msg.header.setJobId(s);const o={json:r};(r.Message===ve.NAME||r.Message===Ke.NAME)&&typeof e.msg.getData=="function"&&(o.data=e.msg.getData());const i={msg:e.msg,expirationTime:Date.now()+e.msg.header.getTimeout(),resolve:e.resolve,reject:e.reject,request:o};this.jobs.set(s,i),this.logger.trace(`Sending ${r.Message} with idJob: ${s}`,o)}clearPendingRequests(){this.jobs.forEach((e,t)=>{const r=new Z({Message:"Foundation::ErrorResponse",header:{id_job:t,id_service:"0"},reason:{value:1001}});e.reject(r)}),this.jobs.clear(),this.reset()}static supportedPermissionDeniedResponseMessages(e){const t=[ve];for(const r of t)if(e instanceof r)return!0;return!1}static supportsChunkedResponse(e){return e instanceof ve&&!e.header.isFlagValueSet("add_subscription")}}/*!
4
4
  * https://github.com/Starcounter-Jack/JSON-Patch
5
5
  * (c) 2017-2022 Joachim Wester
6
6
  * MIT licensed
7
- */var sc=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)s.hasOwnProperty(o)&&(r[o]=s[o])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),oc=Object.prototype.hasOwnProperty;function Qn(n,e){return oc.call(n,e)}function Xn(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var s in n)Qn(n,s)&&r.push(s);return r}function se(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}function Zn(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function Ue(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}function ks(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}function er(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(er(n[e]))return!0}else if(typeof n=="object"){for(var r=Xn(n),s=r.length,o=0;o<s;o++)if(er(n[r[o]]))return!0}}return!1}function Ps(n,e){var t=[n];for(var r in e){var s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&t.push(r+": "+s)}return t.join(`
8
- `)}var Ns=function(n){sc(e,n);function e(t,r,s,o,i){var a=this.constructor,c=n.call(this,Ps(t,{name:r,index:s,operation:o,tree:i}))||this;return c.name=r,c.index=s,c.operation=o,c.tree=i,Object.setPrototypeOf(c,a.prototype),c.message=Ps(t,{name:r,index:s,operation:o,tree:i}),c}return e}(Error),B=Ns,ic=se,Ze={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Qt(t,this.path);r&&(r=se(r));var s=$e(t,{op:"remove",path:this.from}).removed;return $e(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Qt(t,this.from);return $e(t,{op:"add",path:this.path,value:se(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:Tt(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},ac={add:function(n,e,t){return Zn(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:Ze.move,copy:Ze.copy,test:Ze.test,_get:Ze._get};function Qt(n,e){if(e=="")return n;var t={op:"_get",path:e};return $e(n,t),t.value}function $e(n,e,t,r,s,o){if(t===void 0&&(t=!1),r===void 0&&(r=!0),s===void 0&&(s=!0),o===void 0&&(o=0),t&&(typeof t=="function"?t(e,0,n,e.path):Zt(e,0)),e.path===""){var i={newDocument:n};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=n,i;if(e.op==="move"||e.op==="copy")return i.newDocument=Qt(n,e.from),e.op==="move"&&(i.removed=n),i;if(e.op==="test"){if(i.test=Tt(n,e.value),i.test===!1)throw new B("Test operation failed","TEST_OPERATION_FAILED",o,e,n);return i.newDocument=n,i}else{if(e.op==="remove")return i.removed=n,i.newDocument=null,i;if(e.op==="_get")return e.value=n,i;if(t)throw new B("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,e,n);return i}}else{r||(n=se(n));var a=e.path||"",c=a.split("/"),h=n,u=1,l=c.length,b=void 0,f=void 0,T=void 0;for(typeof t=="function"?T=t:T=Zt;;){if(f=c[u],f&&f.indexOf("~")!=-1&&(f=ks(f)),s&&(f=="__proto__"||f=="prototype"&&u>0&&c[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&b===void 0&&(h[f]===void 0?b=c.slice(0,u).join("/"):u==l-1&&(b=e.path),b!==void 0&&T(e,0,n,b)),u++,Array.isArray(h)){if(f==="-")f=h.length;else{if(t&&!Zn(f))throw new B("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",o,e,n);Zn(f)&&(f=~~f)}if(u>=l){if(t&&e.op==="add"&&f>h.length)throw new B("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,e,n);var i=ac[e.op].call(e,h,f,n);if(i.test===!1)throw new B("Test operation failed","TEST_OPERATION_FAILED",o,e,n);return i}}else if(u>=l){var i=Ze[e.op].call(e,h,f,n);if(i.test===!1)throw new B("Test operation failed","TEST_OPERATION_FAILED",o,e,n);return i}if(h=h[f],t&&u<l&&(!h||typeof h!="object"))throw new B("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,e,n)}}}function Xt(n,e,t,r,s){if(r===void 0&&(r=!0),s===void 0&&(s=!0),t&&!Array.isArray(e))throw new B("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=se(n));for(var o=new Array(e.length),i=0,a=e.length;i<a;i++)o[i]=$e(n,e[i],t,!0,s,i),n=o[i].newDocument;return o.newDocument=n,o}function cc(n,e,t){var r=$e(n,e);if(r.test===!1)throw new B("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}function Zt(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new B("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(Ze[n.op]){if(typeof n.path!="string")throw new B("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new B('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new B("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new B("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&er(n.value))throw new B("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,o=r.split("/").length;if(s!==o+1&&s!==o)throw new B("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new B("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var i={op:"_get",path:n.from,value:void 0},a=js([i],t);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new B("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new B("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}function js(n,e,t){try{if(!Array.isArray(n))throw new B("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Xt(se(e),se(n),t||!0);else{t=t||Zt;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof B)return s;throw s}}function Tt(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,o,i;if(t&&r){if(o=n.length,o!=e.length)return!1;for(s=o;s--!==0;)if(!Tt(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var a=Object.keys(n);if(o=a.length,o!==Object.keys(e).length)return!1;for(s=o;s--!==0;)if(!e.hasOwnProperty(a[s]))return!1;for(s=o;s--!==0;)if(i=a[s],!Tt(n[i],e[i]))return!1;return!0}return n!==n&&e!==e}const uc=Object.freeze(Object.defineProperty({__proto__:null,JsonPatchError:B,_areEquals:Tt,applyOperation:$e,applyPatch:Xt,applyReducer:cc,deepClone:ic,getValueByPointer:Qt,validate:js,validator:Zt},Symbol.toStringTag,{value:"Module"}));/*!
7
+ */var oc=function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var o in s)s.hasOwnProperty(o)&&(r[o]=s[o])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}}(),ic=Object.prototype.hasOwnProperty;function Xn(n,e){return ic.call(n,e)}function Zn(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var s in n)Xn(n,s)&&r.push(s);return r}function se(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}function er(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function $e(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}function Os(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}function tr(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(tr(n[e]))return!0}else if(typeof n=="object"){for(var r=Zn(n),s=r.length,o=0;o<s;o++)if(tr(n[r[o]]))return!0}}return!1}function Ps(n,e){var t=[n];for(var r in e){var s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&t.push(r+": "+s)}return t.join(`
8
+ `)}var Ns=function(n){oc(e,n);function e(t,r,s,o,i){var a=this.constructor,c=n.call(this,Ps(t,{name:r,index:s,operation:o,tree:i}))||this;return c.name=r,c.index=s,c.operation=o,c.tree=i,Object.setPrototypeOf(c,a.prototype),c.message=Ps(t,{name:r,index:s,operation:o,tree:i}),c}return e}(Error),B=Ns,ac=se,et={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Qt(t,this.path);r&&(r=se(r));var s=Le(t,{op:"remove",path:this.from}).removed;return Le(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Qt(t,this.from);return Le(t,{op:"add",path:this.path,value:se(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:Et(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},cc={add:function(n,e,t){return er(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:et.move,copy:et.copy,test:et.test,_get:et._get};function Qt(n,e){if(e=="")return n;var t={op:"_get",path:e};return Le(n,t),t.value}function Le(n,e,t,r,s,o){if(t===void 0&&(t=!1),r===void 0&&(r=!0),s===void 0&&(s=!0),o===void 0&&(o=0),t&&(typeof t=="function"?t(e,0,n,e.path):Zt(e,0)),e.path===""){var i={newDocument:n};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=n,i;if(e.op==="move"||e.op==="copy")return i.newDocument=Qt(n,e.from),e.op==="move"&&(i.removed=n),i;if(e.op==="test"){if(i.test=Et(n,e.value),i.test===!1)throw new B("Test operation failed","TEST_OPERATION_FAILED",o,e,n);return i.newDocument=n,i}else{if(e.op==="remove")return i.removed=n,i.newDocument=null,i;if(e.op==="_get")return e.value=n,i;if(t)throw new B("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,e,n);return i}}else{r||(n=se(n));var a=e.path||"",c=a.split("/"),h=n,u=1,l=c.length,b=void 0,f=void 0,E=void 0;for(typeof t=="function"?E=t:E=Zt;;){if(f=c[u],f&&f.indexOf("~")!=-1&&(f=Os(f)),s&&(f=="__proto__"||f=="prototype"&&u>0&&c[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&b===void 0&&(h[f]===void 0?b=c.slice(0,u).join("/"):u==l-1&&(b=e.path),b!==void 0&&E(e,0,n,b)),u++,Array.isArray(h)){if(f==="-")f=h.length;else{if(t&&!er(f))throw new B("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",o,e,n);er(f)&&(f=~~f)}if(u>=l){if(t&&e.op==="add"&&f>h.length)throw new B("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,e,n);var i=cc[e.op].call(e,h,f,n);if(i.test===!1)throw new B("Test operation failed","TEST_OPERATION_FAILED",o,e,n);return i}}else if(u>=l){var i=et[e.op].call(e,h,f,n);if(i.test===!1)throw new B("Test operation failed","TEST_OPERATION_FAILED",o,e,n);return i}if(h=h[f],t&&u<l&&(!h||typeof h!="object"))throw new B("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,e,n)}}}function Xt(n,e,t,r,s){if(r===void 0&&(r=!0),s===void 0&&(s=!0),t&&!Array.isArray(e))throw new B("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=se(n));for(var o=new Array(e.length),i=0,a=e.length;i<a;i++)o[i]=Le(n,e[i],t,!0,s,i),n=o[i].newDocument;return o.newDocument=n,o}function uc(n,e,t){var r=Le(n,e);if(r.test===!1)throw new B("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}function Zt(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new B("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(et[n.op]){if(typeof n.path!="string")throw new B("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new B('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new B("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new B("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&tr(n.value))throw new B("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,o=r.split("/").length;if(s!==o+1&&s!==o)throw new B("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new B("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var i={op:"_get",path:n.from,value:void 0},a=js([i],t);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new B("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new B("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}function js(n,e,t){try{if(!Array.isArray(n))throw new B("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Xt(se(e),se(n),t||!0);else{t=t||Zt;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof B)return s;throw s}}function Et(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,o,i;if(t&&r){if(o=n.length,o!=e.length)return!1;for(s=o;s--!==0;)if(!Et(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var a=Object.keys(n);if(o=a.length,o!==Object.keys(e).length)return!1;for(s=o;s--!==0;)if(!e.hasOwnProperty(a[s]))return!1;for(s=o;s--!==0;)if(i=a[s],!Et(n[i],e[i]))return!1;return!0}return n!==n&&e!==e}const hc=Object.freeze(Object.defineProperty({__proto__:null,JsonPatchError:B,_areEquals:Et,applyOperation:Le,applyPatch:Xt,applyReducer:uc,deepClone:ac,getValueByPointer:Qt,validate:js,validator:Zt},Symbol.toStringTag,{value:"Module"}));/*!
9
9
  * https://github.com/Starcounter-Jack/JSON-Patch
10
10
  * (c) 2017-2021 Joachim Wester
11
11
  * MIT license
12
- */var tr=new WeakMap,hc=function(){function n(e){this.observers=new Map,this.obj=e}return n}(),lc=function(){function n(e,t){this.callback=e,this.observer=t}return n}();function fc(n){return tr.get(n)}function dc(n,e){return n.observers.get(e)}function pc(n,e){n.observers.delete(e.callback)}function gc(n,e){e.unobserve()}function vc(n,e){var t=[],r,s=fc(n);if(!s)s=new hc(n),tr.set(n,s);else{var o=dc(s,e);r=o&&o.observer}if(r)return r;if(r={},s.value=se(n),e){r.callback=e,r.next=null;var i=function(){nr(r)},a=function(){clearTimeout(r.next),r.next=setTimeout(i)};typeof window<"u"&&(window.addEventListener("mouseup",a),window.addEventListener("keyup",a),window.addEventListener("mousedown",a),window.addEventListener("keydown",a),window.addEventListener("change",a))}return r.patches=t,r.object=n,r.unobserve=function(){nr(r),clearTimeout(r.next),pc(s,r),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},s.observers.set(e,new lc(e,r)),r}function nr(n,e){e===void 0&&(e=!1);var t=tr.get(n.object);rr(t.value,n.object,n.patches,"",e),n.patches.length&&Xt(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}function rr(n,e,t,r,s){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=Xn(e),i=Xn(n),a=!1,c=i.length-1;c>=0;c--){var h=i[c],u=n[h];if(Qn(e,h)&&!(e[h]===void 0&&u!==void 0&&Array.isArray(e)===!1)){var l=e[h];typeof u=="object"&&u!=null&&typeof l=="object"&&l!=null&&Array.isArray(u)===Array.isArray(l)?rr(u,l,t,r+"/"+Ue(h),s):u!==l&&(s&&t.push({op:"test",path:r+"/"+Ue(h),value:se(u)}),t.push({op:"replace",path:r+"/"+Ue(h),value:se(l)}))}else Array.isArray(n)===Array.isArray(e)?(s&&t.push({op:"test",path:r+"/"+Ue(h),value:se(u)}),t.push({op:"remove",path:r+"/"+Ue(h)}),a=!0):(s&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}))}if(!(!a&&o.length==i.length))for(var c=0;c<o.length;c++){var h=o[c];!Qn(n,h)&&e[h]!==void 0&&t.push({op:"add",path:r+"/"+Ue(h),value:se(e[h])})}}}function bc(n,e,t){t===void 0&&(t=!1);var r=[];return rr(n,e,r,"",t),r}Object.assign({},uc,Object.freeze(Object.defineProperty({__proto__:null,compare:bc,generate:nr,observe:vc,unobserve:gc},Symbol.toStringTag,{value:"Module"})),{JsonPatchError:Ns,deepClone:se,escapePathComponent:Ue,unescapePathComponent:ks});const It=class It{constructor(e,t,r){this.resultMapper=Xa(s=>{if(xt(s)){const o=this.applyEndpointJsonPatchUpdate(s.jobId,s.data);return{response:o,data:o.data}}return{response:s,data:s.data}}),this.requestToJobMapper=new Map,this.requestModule=e,this.subjectManager=t,this.responses={},this.logger=r}setLogger(e){this.logger=e}observe(e,t,r,s,o){this.validateOptions(s);const i=new Et,a=new Yt(1),c=a.pipe(nc()),h=i.asObservable().pipe(It.highLevelResponseFilter,this.resultMapper.bind(this));return this.requestModule.requestEndpoint(e,t,r,{...o,subscribe:!0}).then(u=>{this.subjectManager.registerJobSubject(u.response.jobId,i),this.registerEndpointRequest(u.response.jobId,a,c,e,t,r,s),this.registerEndpointResponse(u.response.jobId,u.response),h.idJob=u.response.jobId,a.next(h.pipe(Rs(1))),c.idJob=u.response.jobId,i.next(u.response)}).catch(u=>{this.logger.warn("Subscription request failed.",u),a.error(u)}),c}async unobserve(e){if(!this.subjectManager.hasJobSubject(e)){this.logger.warn(`Could not find subscription for idJob "${e}".`);return}await this.requestModule.request(new Ae(e)),this.requestToJobMapper.delete(e.toString()),this.subjectManager.removeJobSubject(e)}findSubject(e){return this.subjectManager.getJobSubject(e)}registerEndpointResponse(e,t){this.responses[e]=t}registerEndpointRequest(e,t,r,s,o,i,a,c){this.requestToJobMapper.set(e.toString(),{path:o,subject:t,observable:r,data:i,method:s,options:a,requestOptions:c})}applyEndpointJsonPatchUpdate(e,t){const r=this.responses[e],s=Xt(r,t).newDocument;return this.responses[e]=s,s}restartSubscriptions(){const e=Array.from(this.subjectManager.jobs.keys()),t=new Map(this.requestToJobMapper);this.requestToJobMapper.clear(),this.subjectManager.jobs.clear(),e.forEach(r=>{const s=t.get(r);s&&this.resubscribe(s)})}restartSubscription(e){const t=new Map(this.requestToJobMapper);if(this.requestToJobMapper.clear(),e){const r=t.get(e.toString());r&&setTimeout(()=>{this.resubscribe(r)},Mo)}}resubscribe(e){this.validateOptions(e.options);const t=new Et,r=t.asObservable().pipe(It.highLevelResponseFilter,this.resultMapper.bind(this));this.requestModule.requestEndpoint(e.method,e.path,e.data,{...e.requestOptions,subscribe:!0}).then(s=>{this.subjectManager.registerJobSubject(s.response.jobId,t),this.registerEndpointResponse(s.response.jobId,s.response),e.observable.idJob=s.response.jobId,e.subject.next(r.pipe(Rs(1))),t.next(s.response),this.registerEndpointRequest(s.response.jobId,e.subject,e.observable,e.method,e.path,e.data,e.options,e.requestOptions)}).catch(s=>{this.logger.warn("Request failed during initial request for restarting endpoint subscription",s)})}validateOptions(e){({...en.defaultObserveOptions,...e}).minInterval&&this.logger.warn("Option `minInterval` is deprecated. Use _subscriptionMinimumInterval (GET) or meta.subscription.minimumInterval (POST) for server side throttling.")}};It.highLevelResponseFilter=Za(e=>zr(e)||xt(e));let sr=It;class mc{constructor(e){this.job=new Map,this.logger=e}hasJobSubject(e){return this.job.has(String(e))}registerJobSubject(e,t){const r=String(e);this.job.set(r,t)}findJobSubject(e){const t=String(e);if(!this.job.has(t))throw new Error(`could not find job subject for id=${e}`);return this.job.get(t)}removeJobSubject(e){const t=String(e);if(!this.job.has(t)){this.logger.warn(`No subject found for idJob ${t}`);return}this.job.delete(t)}getJobSubject(e){const t=String(e);if(!this.job.has(t)){this.logger.warn(`No subject found for idJob ${t}`);return}return this.job.get(t)}get jobs(){return this.job}}const yc={shouldRestartSubscriptions:!1},cr=class cr{constructor(e,t,r=yc){this.logger=t,this.options=r,this.subjectManager=new mc(this.logger),this.handler={endpoint:new sr(e,this.subjectManager,this.logger)},e.setUpdateMessageHandler(this.updateHandler.bind(this)),e.setLossMessageHandler(this.lossHandler.bind(this))}setLogger(e){this.logger=e,this.handler.endpoint.setLogger(e)}observeEndpoint(e,t,r,s,o){return this.handler.endpoint.observe(e,t,r,s,o)}async unobserveEndpoint(e){return this.handler.endpoint.unobserve(e)}restartSubscriptions(){this.handler.endpoint.restartSubscriptions()}clearPendingSubscriptions(){this.subjectManager.jobs.forEach((e,t)=>{const r=new Ut({Message:"Foundation::SubscriptionLossMessage",Version:2,header:{id_job:parseInt(t,10),id_service:0},reason:{value:1}});e.error(r)}),this.subjectManager.jobs.clear()}clearPendingSubscription(e){this.subjectManager.jobs.forEach((t,r)=>{if(e===Number(r)){const s=new Ut({Message:"Foundation::SubscriptionLossMessage",Version:2,header:{id_job:parseInt(r,10),id_service:0},reason:{value:1}});t.error(s)}}),this.subjectManager.jobs.delete(e.toString())}lossHandler(e){try{const t=this.findSubject(e),{jobId:r}=e;this.logger.debug(`Received Loss Message ${e.name}`,e),t.error(`Subscription lost: ${JSON.stringify(e)}`),this.options.shouldRestartSubscriptions&&this.handler.endpoint.restartSubscription(r)}catch{this.logger.warn("Received Loss Message but could not find corresponding subject",e)}}updateHandler(e){try{const t=this.findSubject(e);this.logger.debug(`Received Update Message ${e.name}`,e),t.next(e)}catch{this.logger.warn("Received Update Message but could not find corresponding subject",e)}}findSubject(e){if(xt(e)||Kr(e)){const t=this.subjectManager.findJobSubject(e.jobId);if(t)return t}throw new Error(`Received unknown message: ${e.name}`)}};cr.defaultObserveOptions={quality:Cr};let en=cr;class tn{constructor(e,t={}){this.options=t,this.flagPermissionDenied=t.flagPermissionDenied??kr,this.shouldRestartSubscriptions=t.shouldRestartSubscriptions??!0,this.defaultTimeoutInMs=t.defaultTimeoutInMs??wn,this.defaultTimeoutTokenInMs=t.defaultTimeoutTokenInMs??Or,this.maxTimeoutsBeforeReconnect=t.maxTimeoutsBeforeReconnect??Rr,this.enableSessionHandling=t.enableSessionHandling??To,this.replaySubjectBufferSize=t.replaySubjectBufferSize??Pr,this.requestModule=new Kt(this.getConnection.bind(this),this.logger,{defaultTimeoutInMs:this.defaultTimeoutInMs,defaultTimeoutTokenInMs:this.defaultTimeoutTokenInMs,flagPermissionDenied:this.flagPermissionDenied,maxTimeoutsBeforeReconnect:this.maxTimeoutsBeforeReconnect,replaySubjectBufferSize:this.replaySubjectBufferSize}),this.subscriptionModule=new en(this.requestModule,this.logger,{shouldRestartSubscriptions:this.shouldRestartSubscriptions}),this.sessionConnect=!1,t.onConnectCallback&&(this.onConnectCallback=t.onConnectCallback),e?this.setConnection(e):this.logger=new it}async connect(){if(!this.connection)throw new Error("No connection defined. please set a connection before trying to connect.");return this.sessionConnect?Promise.resolve():this.connection.open()}async connectSession(e=!1){if(!this.connection)throw new Error("No connection defined. please set a connection before trying to connect.");const{connection:t}=this,r=new On,s=new lt(r,{...this.connection.options,sessionHandling:!0});this.setConnection(s);try{await this.connection.open()}catch(o){if(this.setConnection(t),e)throw o;return!1}return!0}async disconnect(e=!1){if(!this.connection)throw new Error("No connection defined. please set a connection before trying to disconnect.");await this.connection.close(!1,e)}async request(e,t=this.defaultTimeoutInMs){return this.requestModule.request(e,t)}restartSubscriptions(){this.subscriptionModule.restartSubscriptions()}async requestWithQuality(e,t=Cr,r=this.defaultTimeoutInMs){return this.requestModule.requestWithQuality(e,t,r)}async requestEndpoint(e,t,r,s,o=this.defaultTimeoutInMs){return this.requestModule.requestEndpoint(e,t,r,s,o)}async requestProxyEndpoint(e,t,r,s,o=this.defaultTimeoutInMs){return this.requestModule.requestProxyEndpoint(e,t,r,s,o)}async requestAuthenticationToken(e,t,r,s=this.defaultTimeoutTokenInMs){return this.requestModule.requestAuthenticationToken(e,t,r,s)}async requestAuthenticationTokenExpiry(e,t,r,s=this.defaultTimeoutTokenInMs,o=!1){return this.requestModule.requestAuthenticationTokenExpiry(e,t,r,s,o)}async requestOtpAuthenticationTokenForSessionHandling(e=je.LIFETIME_SECONDS_MAXIMUM,t=-2,r=-2,s=this.defaultTimeoutTokenInMs){const{token:o,expiry:i}=await this.requestModule.requestAuthenticationTokenExpiry(e,t,r,s,!0);this.options.otpToken=o,this.options.otpTokenExpiry=i}async requestAuthenticationTokenForCookieTokenAuthentication(e,t,r,s=this.defaultTimeoutTokenInMs){return this.requestModule.requestAuthenticationTokenFactorsForCookieAuthentication(e,t,r,s)}observeEndpoint(e,t,r,s,o){return this.subscriptionModule.observeEndpoint(e,t,r,s,o)}async unobserveEndpoint(e){return this.subscriptionModule.unobserveEndpoint(e)}setConnection(e){e.options.logger&&this.setLogger(e.options.logger),this.isConnected&&this.logger.warn("Cannot modify an open connection. Disconnect first, before trying to set the connection."),this.connection=e,this.connection.clientOptions=this.options,this.connection.shouldRestartSubscriptions=this.shouldRestartSubscriptions,this.connection.onAuthentication=this.requestModule.onConnection.bind(this.requestModule),this.connection.onCleanupRequests=this.requestModule.clearPendingRequests.bind(this.requestModule),this.connection.onCleanupSubscriptions=this.subscriptionModule.clearPendingSubscriptions.bind(this.subscriptionModule),this.connection.onClearPendingSubscription=t=>{this.subscriptionModule.clearPendingSubscription(t)},this.connection.restartSubscriptions=this.subscriptionModule.restartSubscriptions.bind(this.subscriptionModule),this.connection.onConnect=this.onConnectCallback}getConnection(){return this.connection}async setConnectionFromFetchConfiguration(e,t,r){if(this.enableSessionHandling&&this.setConnectionFromSavedConfig()&&await this.connectSession())return this.sessionConnect=!0,Promise.resolve();const{config:s,response:o}=await Dt(e,t);return this.enableSessionHandling&&Gr(s),this.setConnection(tn.createConnection({...s,logger:this.logger,loglevel:this.logger.getLevel(),shouldReconnectOnConnectionLoss:r},e,t)),o}static createConnection(e,t,r){return qr(e,t,r)}setLogger(e){this.logger=e,this.requestModule.setLogger(e),this.subscriptionModule.setLogger(e),this.connection&&this.connection.setLogger(e)}getLogger(){return this.logger}get isConnected(){var e;return((e=this.connection)==null?void 0:e.isAuthenticated())??!1}get isConnecting(){var e;return((e=this.connection)==null?void 0:e.isConnecting())??!1}getServerInfo(){var e;return(e=this.connection)==null?void 0:e.auth.getServerInfo()}setConnectionFromSavedConfig(){const e=Br();return e?(this.setConnection(tn.createConnection({...e,logger:this.logger,loglevel:this.logger.getLevel()})),!0):!1}}function or(n,e={},t){for(const r in n){const s=n[r],o=t?`${t}:${r}`:r;typeof s=="object"&&s!==null?or(s,e,o):typeof s=="function"&&(e[o]=s)}return e}const wc={run:n=>n()},_c=()=>wc,Ds=typeof console.createTask<"u"?console.createTask:_c;function Ec(n,e){const t=e.shift(),r=Ds(t);return n.reduce((s,o)=>s.then(()=>r.run(()=>o(...e))),Promise.resolve())}function Tc(n,e){const t=e.shift(),r=Ds(t);return Promise.all(n.map(s=>r.run(()=>s(...e))))}function ir(n,e){for(const t of[...n])t(e)}class Mc{constructor(){this._hooks={},this._before=void 0,this._after=void 0,this._deprecatedMessages=void 0,this._deprecatedHooks={},this.hook=this.hook.bind(this),this.callHook=this.callHook.bind(this),this.callHookWith=this.callHookWith.bind(this)}hook(e,t,r={}){if(!e||typeof t!="function")return()=>{};const s=e;let o;for(;this._deprecatedHooks[e];)o=this._deprecatedHooks[e],e=o.to;if(o&&!r.allowDeprecated){let i=o.message;i||(i=`${s} hook has been deprecated`+(o.to?`, please use ${o.to}`:"")),this._deprecatedMessages||(this._deprecatedMessages=new Set),this._deprecatedMessages.has(i)||(console.warn(i),this._deprecatedMessages.add(i))}if(!t.name)try{Object.defineProperty(t,"name",{get:()=>"_"+e.replace(/\W+/g,"_")+"_hook_cb",configurable:!0})}catch{}return this._hooks[e]=this._hooks[e]||[],this._hooks[e].push(t),()=>{t&&(this.removeHook(e,t),t=void 0)}}hookOnce(e,t){let r,s=(...o)=>(typeof r=="function"&&r(),r=void 0,s=void 0,t(...o));return r=this.hook(e,s),r}removeHook(e,t){if(this._hooks[e]){const r=this._hooks[e].indexOf(t);r!==-1&&this._hooks[e].splice(r,1),this._hooks[e].length===0&&delete this._hooks[e]}}deprecateHook(e,t){this._deprecatedHooks[e]=typeof t=="string"?{to:t}:t;const r=this._hooks[e]||[];delete this._hooks[e];for(const s of r)this.hook(e,s)}deprecateHooks(e){Object.assign(this._deprecatedHooks,e);for(const t in e)this.deprecateHook(t,e[t])}addHooks(e){const t=or(e),r=Object.keys(t).map(s=>this.hook(s,t[s]));return()=>{for(const s of r.splice(0,r.length))s()}}removeHooks(e){const t=or(e);for(const r in t)this.removeHook(r,t[r])}removeAllHooks(){for(const e in this._hooks)delete this._hooks[e]}callHook(e,...t){return t.unshift(e),this.callHookWith(Ec,e,...t)}callHookParallel(e,...t){return t.unshift(e),this.callHookWith(Tc,e,...t)}callHookWith(e,t,...r){const s=this._before||this._after?{name:t,args:r,context:{}}:void 0;this._before&&ir(this._before,s);const o=e(t in this._hooks?[...this._hooks[t]]:[],r);return o instanceof Promise?o.finally(()=>{this._after&&s&&ir(this._after,s)}):(this._after&&s&&ir(this._after,s),o)}beforeEach(e){return this._before=this._before||[],this._before.push(e),()=>{if(this._before!==void 0){const t=this._before.indexOf(e);t!==-1&&this._before.splice(t,1)}}}afterEach(e){return this._after=this._after||[],this._after.push(e),()=>{if(this._after!==void 0){const t=this._after.indexOf(e);t!==-1&&this._after.splice(t,1)}}}}function Sc(){return new Mc}const xs=typeof window<"u";function Ic(n,e={}){const t={inspect:xs,group:xs,filter:()=>!0,...e},r=t.filter,s=typeof r=="string"?u=>u.startsWith(r):r,o=t.tag?`[${t.tag}] `:"",i=u=>o+u.name+"".padEnd(u._id,"\0"),a={},c=n.beforeEach(u=>{s!==void 0&&!s(u.name)||(a[u.name]=a[u.name]||0,u._id=a[u.name]++,console.time(i(u)))}),h=n.afterEach(u=>{s!==void 0&&!s(u.name)||(t.group&&console.groupCollapsed(u.name),t.inspect?console.timeLog(i(u),u.args):console.timeEnd(i(u)),t.group&&console.groupEnd(),a[u.name]--)});return{close:()=>{c(),h()}}}class Fs{constructor(e){k(this,He);this.hooks=Sc(),R(this,He,1e4),e!=null&&e.hookDebug&&Ic(this.hooks,{tag:"hooks"}),e!=null&&e.defaultRequestTimeout&&R(this,He,e.defaultRequestTimeout)}get defaultTimeoutInMs(){return v(this,He)}set defaultTimeoutInMs(e){R(this,He,e)}log(e,...t){if(this.hooks.callHook("base:log",t),this.logger)switch(e){case y.TRACE:this.logger.trace(t);break;case y.DEBUG:this.logger.debug(t);break;case y.INFO:this.logger.info(t);break;case y.WARN:this.logger.warn(t);break;case y.ERROR:this.logger.error(t);break;case y.FATAL:this.logger.fatal(t);break}}}He=new WeakMap;const sn=class sn{constructor(e,t=[],r=[],s=[]){k(this,ae);k(this,qe);k(this,Ge,[]);k(this,Re,[]);k(this,ke,[]);R(this,qe,e),R(this,Ge,t),R(this,Re,r),R(this,ke,s)}static create(){return new sn(Fs)}with(e){const{featureName:t,disabledFeatures:r,disabledFeatureGroups:s,featureGroups:o}=e;if(!t)throw new Error("Feature name is missing");if(H(this,ae,Vs).call(this,t),H(this,ae,Ys).call(this,t),v(this,Ge).push(t),o&&o.length>0)for(const a of o)H(this,ae,Ks).call(this,a);if(r&&r.length>0)for(const a of r)H(this,ae,Qs).call(this,t,a);if(s&&s.length>0)for(const a of s)H(this,ae,Xs).call(this,t,a);const i=e(v(this,qe));return new sn(i,v(this,Ge),v(this,Re),v(this,ke))}build(e){return new(v(this,qe))(e)}getClientConstructor(){return v(this,qe)}};qe=new WeakMap,Ge=new WeakMap,Re=new WeakMap,ke=new WeakMap,ae=new WeakSet,Vs=function(e){if(v(this,Ge).includes(e))throw new Error(`Feature "${e}" has already been used.`)},Ys=function(e){for(const t of v(this,Re))if(t.feature===e)throw new Error(`Feature "${e}" has been disabled by ${t.disabler.join(",")}.`)},Ks=function(e){for(const t of v(this,ke))if(t.feature===e)throw new Error(`Group "${e}" has been disabled by ${t.disabler.join(",")}.`)},Qs=function(e,t){for(const r of v(this,Re))if(r.feature===t){r.disabler.push(e);return}v(this,Re).push({disabler:[e],feature:t})},Xs=function(e,t){for(const r of v(this,ke))if(r.feature===t){r.disabler.push(e);return}v(this,ke).push({disabler:[e],feature:t})};let ar=sn;d.AbstractAuthentication=Rt,d.AbstractFrontgateConnection=jt,d.AbstractLogger=Ee,d.AbstractMdg2Request=Ve,d.AuthenticationByTokenRequest=dt,d.AuthenticationTokenRequest=je,d.AuthenticationTokenResponse=Sn,d.CancelSubscriptionRequest=Ae,d.CancelSubscriptionResponse=es,d.ConnectionState=Ie,d.ConsoleLogger=an,d.CookieTokenAuthentication=On,d.CookieTokenAuthenticationFactors=rs,d.DefaultHosts=Ur,d.DeploymentStage=Fr,d.Encoding=Se,d.ErrorResponse=X,d.FetchConnectionConfigurationResponseHeaders=$r,d.FrontgateClient=Fs,d.FrontgateClientBuilder=ar,d.FrontgateClientDataObserver=Pn,d.FrontgateClientEndpointDataObserver=is,d.FrontgateWSConnection=lt,d.HTTPProxyRequest=Ye,d.HTTPProxyResponse=An,d.HighLevelRequest=ve,d.HighLevelResponse=In,d.HighLevelUpdate=Ft,d.ID_APP_AUTHENTICATED=-2,d.ID_USER_AUTHENTICATED=-2,d.ID_USER_NONE=-1,d.LatencyTracker=Rn,d.LogLevel=y,d.LoggerHelper=Zs,d.Mdg2Client=tn,d.Mdg2Response=ne,d.NullLogger=it,d.PermissionDeniedResponse=ts,d.PingRequest=ht,d.PingResponse=We,d.RawRequest=Zr,d.RawRequestFactory=Mn,d.RejectResponse=ns,d.SubscriptionLossMessage=Ut,d.TimeOptions=xr,d.TokenAuthentication=Cn,d.TransportLayerClientRequestHeader=ft,d.WinstonLogger=to,d.authTokenRequest=Wo,d.cookieTokenAuth=si,d.createConnection=qr,d.createConnectionInterface=ai,d.createExtendedMixinFactory=Z,d.encodeSpanContext=bs,d.endpointRequest=zo,d.endpointSubscriptions=Qo,d.fetchAuth=ii,d.fetchConnectionConfiguration=Dt,d.getBytesFromBuffer=$o,d.getConnectionConfiguration=Br,d.httpProxyRequest=_a,d.isErrorResponse=Jr,d.isHighLevelResponse=zr,d.isHighLevelResponseMessage=Vr,d.isHighLevelUpdate=xt,d.isPermissionDeniedResponse=Wr,d.isRejectResponse=Yr,d.isSubscriptionLossMessage=Kr,d.levels=eo,d.logger=Vo,d.messageCompressor=Yo,d.objectFromFetchHeaders=Hr,d.openTelemetry=wa,d.parseConnectionConfiguration=Lr,d.rawSubscriptions=Xo,d.reconnect=ci,d.requests=Ko,d.setConnectionConfiguration=Gr,d.timeToMilliseconds=Nt,d.tokenAuth=oi,d.useTimeout=ge,d.wsConnection=os,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})});
12
+ */var nr=new WeakMap,lc=function(){function n(e){this.observers=new Map,this.obj=e}return n}(),fc=function(){function n(e,t){this.callback=e,this.observer=t}return n}();function dc(n){return nr.get(n)}function pc(n,e){return n.observers.get(e)}function gc(n,e){n.observers.delete(e.callback)}function vc(n,e){e.unobserve()}function bc(n,e){var t=[],r,s=dc(n);if(!s)s=new lc(n),nr.set(n,s);else{var o=pc(s,e);r=o&&o.observer}if(r)return r;if(r={},s.value=se(n),e){r.callback=e,r.next=null;var i=function(){rr(r)},a=function(){clearTimeout(r.next),r.next=setTimeout(i)};typeof window<"u"&&(window.addEventListener("mouseup",a),window.addEventListener("keyup",a),window.addEventListener("mousedown",a),window.addEventListener("keydown",a),window.addEventListener("change",a))}return r.patches=t,r.object=n,r.unobserve=function(){rr(r),clearTimeout(r.next),gc(s,r),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},s.observers.set(e,new fc(e,r)),r}function rr(n,e){e===void 0&&(e=!1);var t=nr.get(n.object);sr(t.value,n.object,n.patches,"",e),n.patches.length&&Xt(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}function sr(n,e,t,r,s){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=Zn(e),i=Zn(n),a=!1,c=i.length-1;c>=0;c--){var h=i[c],u=n[h];if(Xn(e,h)&&!(e[h]===void 0&&u!==void 0&&Array.isArray(e)===!1)){var l=e[h];typeof u=="object"&&u!=null&&typeof l=="object"&&l!=null&&Array.isArray(u)===Array.isArray(l)?sr(u,l,t,r+"/"+$e(h),s):u!==l&&(s&&t.push({op:"test",path:r+"/"+$e(h),value:se(u)}),t.push({op:"replace",path:r+"/"+$e(h),value:se(l)}))}else Array.isArray(n)===Array.isArray(e)?(s&&t.push({op:"test",path:r+"/"+$e(h),value:se(u)}),t.push({op:"remove",path:r+"/"+$e(h)}),a=!0):(s&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}))}if(!(!a&&o.length==i.length))for(var c=0;c<o.length;c++){var h=o[c];!Xn(n,h)&&e[h]!==void 0&&t.push({op:"add",path:r+"/"+$e(h),value:se(e[h])})}}}function mc(n,e,t){t===void 0&&(t=!1);var r=[];return sr(n,e,r,"",t),r}Object.assign({},hc,Object.freeze(Object.defineProperty({__proto__:null,compare:mc,generate:rr,observe:bc,unobserve:vc},Symbol.toStringTag,{value:"Module"})),{JsonPatchError:Ns,deepClone:se,escapePathComponent:$e,unescapePathComponent:Os});const It=class It{constructor(e,t,r){this.resultMapper=Za(s=>{if(xt(s)){const o=this.applyEndpointJsonPatchUpdate(s.jobId,s.data);return{response:o,data:o.data}}return{response:s,data:s.data}}),this.requestToJobMapper=new Map,this.requestModule=e,this.subjectManager=t,this.responses={},this.logger=r}setLogger(e){this.logger=e}observe(e,t,r,s,o){this.validateOptions(s);const i=new Tt,a=new Yt(1),c=a.pipe(rc()),h=i.asObservable().pipe(It.highLevelResponseFilter,this.resultMapper.bind(this));return this.requestModule.requestEndpoint(e,t,r,{...o,subscribe:!0}).then(u=>{this.subjectManager.registerJobSubject(u.response.jobId,i),this.registerEndpointRequest(u.response.jobId,a,c,e,t,r,s),this.registerEndpointResponse(u.response.jobId,u.response),h.idJob=u.response.jobId,a.next(h.pipe(Rs(1))),c.idJob=u.response.jobId,i.next(u.response)}).catch(u=>{this.logger.warn("Subscription request failed.",u),a.error(u)}),c}async unobserve(e){if(!this.subjectManager.hasJobSubject(e)){this.logger.warn(`Could not find subscription for idJob "${e}".`);return}await this.requestModule.request(new Ae(e)),this.requestToJobMapper.delete(e.toString()),this.subjectManager.removeJobSubject(e)}findSubject(e){return this.subjectManager.getJobSubject(e)}registerEndpointResponse(e,t){this.responses[e]=t}registerEndpointRequest(e,t,r,s,o,i,a,c){this.requestToJobMapper.set(e.toString(),{path:o,subject:t,observable:r,data:i,method:s,options:a,requestOptions:c})}applyEndpointJsonPatchUpdate(e,t){const r=this.responses[e],s=Xt(r,t).newDocument;return this.responses[e]=s,s}restartSubscriptions(){const e=Array.from(this.subjectManager.jobs.keys()),t=new Map(this.requestToJobMapper);this.requestToJobMapper.clear(),this.subjectManager.jobs.clear(),e.forEach(r=>{const s=t.get(r);s&&this.resubscribe(s)})}restartSubscription(e){const t=new Map(this.requestToJobMapper);if(this.requestToJobMapper.clear(),e){const r=t.get(e.toString());r&&setTimeout(()=>{this.resubscribe(r)},Mo)}}resubscribe(e){this.validateOptions(e.options);const t=new Tt,r=t.asObservable().pipe(It.highLevelResponseFilter,this.resultMapper.bind(this));this.requestModule.requestEndpoint(e.method,e.path,e.data,{...e.requestOptions,subscribe:!0}).then(s=>{this.subjectManager.registerJobSubject(s.response.jobId,t),this.registerEndpointResponse(s.response.jobId,s.response),e.observable.idJob=s.response.jobId,e.subject.next(r.pipe(Rs(1))),t.next(s.response),this.registerEndpointRequest(s.response.jobId,e.subject,e.observable,e.method,e.path,e.data,e.options,e.requestOptions)}).catch(s=>{this.logger.warn("Request failed during initial request for restarting endpoint subscription",s)})}validateOptions(e){({...en.defaultObserveOptions,...e}).minInterval&&this.logger.warn("Option `minInterval` is deprecated. Use _subscriptionMinimumInterval (GET) or meta.subscription.minimumInterval (POST) for server side throttling.")}};It.highLevelResponseFilter=ec(e=>Vr(e)||xt(e));let or=It;class yc{constructor(e){this.job=new Map,this.logger=e}hasJobSubject(e){return this.job.has(String(e))}registerJobSubject(e,t){const r=String(e);this.job.set(r,t)}findJobSubject(e){const t=String(e);if(!this.job.has(t))throw new Error(`could not find job subject for id=${e}`);return this.job.get(t)}removeJobSubject(e){const t=String(e);if(!this.job.has(t)){this.logger.warn(`No subject found for idJob ${t}`);return}this.job.delete(t)}getJobSubject(e){const t=String(e);if(!this.job.has(t)){this.logger.warn(`No subject found for idJob ${t}`);return}return this.job.get(t)}get jobs(){return this.job}}const wc={shouldRestartSubscriptions:!1},ur=class ur{constructor(e,t,r=wc){this.logger=t,this.options=r,this.subjectManager=new yc(this.logger),this.handler={endpoint:new or(e,this.subjectManager,this.logger)},e.setUpdateMessageHandler(this.updateHandler.bind(this)),e.setLossMessageHandler(this.lossHandler.bind(this))}setLogger(e){this.logger=e,this.handler.endpoint.setLogger(e)}observeEndpoint(e,t,r,s,o){return this.handler.endpoint.observe(e,t,r,s,o)}async unobserveEndpoint(e){return this.handler.endpoint.unobserve(e)}restartSubscriptions(){this.handler.endpoint.restartSubscriptions()}clearPendingSubscriptions(){this.subjectManager.jobs.forEach((e,t)=>{const r=new Ut({Message:"Foundation::SubscriptionLossMessage",Version:2,header:{id_job:parseInt(t,10),id_service:0},reason:{value:1}});e.error(r)}),this.subjectManager.jobs.clear()}clearPendingSubscription(e){this.subjectManager.jobs.forEach((t,r)=>{if(e===Number(r)){const s=new Ut({Message:"Foundation::SubscriptionLossMessage",Version:2,header:{id_job:parseInt(r,10),id_service:0},reason:{value:1}});t.error(s)}}),this.subjectManager.jobs.delete(e.toString())}lossHandler(e){try{const t=this.findSubject(e),{jobId:r}=e;this.logger.debug(`Received Loss Message ${e.name}`,e),t.error(`Subscription lost: ${JSON.stringify(e)}`),this.options.shouldRestartSubscriptions&&this.handler.endpoint.restartSubscription(r)}catch{this.logger.warn("Received Loss Message but could not find corresponding subject",e)}}updateHandler(e){try{const t=this.findSubject(e);this.logger.debug(`Received Update Message ${e.name}`,e),t.next(e)}catch{this.logger.warn("Received Update Message but could not find corresponding subject",e)}}findSubject(e){if(xt(e)||Qr(e)){const t=this.subjectManager.findJobSubject(e.jobId);if(t)return t}throw new Error(`Received unknown message: ${e.name}`)}};ur.defaultObserveOptions={quality:Cr};let en=ur;class tn{constructor(e,t={}){this.options=t,this.flagPermissionDenied=t.flagPermissionDenied??Pr,this.shouldRestartSubscriptions=t.shouldRestartSubscriptions??!0,this.defaultTimeoutInMs=t.defaultTimeoutInMs??wn,this.defaultTimeoutTokenInMs=t.defaultTimeoutTokenInMs??Rr,this.maxTimeoutsBeforeReconnect=t.maxTimeoutsBeforeReconnect??Or,this.enableSessionHandling=t.enableSessionHandling??Eo,this.replaySubjectBufferSize=t.replaySubjectBufferSize??Nr,this.requestModule=new Kt(this.getConnection.bind(this),this.logger,{defaultTimeoutInMs:this.defaultTimeoutInMs,defaultTimeoutTokenInMs:this.defaultTimeoutTokenInMs,flagPermissionDenied:this.flagPermissionDenied,maxTimeoutsBeforeReconnect:this.maxTimeoutsBeforeReconnect,replaySubjectBufferSize:this.replaySubjectBufferSize}),this.subscriptionModule=new en(this.requestModule,this.logger,{shouldRestartSubscriptions:this.shouldRestartSubscriptions}),this.sessionConnect=!1,t.onConnectCallback&&(this.onConnectCallback=t.onConnectCallback),e?this.setConnection(e):this.logger=new at}async connect(){if(!this.connection)throw new Error("No connection defined. please set a connection before trying to connect.");return this.sessionConnect?Promise.resolve():this.connection.open()}async connectSession(e=!1){if(!this.connection)throw new Error("No connection defined. please set a connection before trying to connect.");const{connection:t}=this,r=new Cn,s=new lt(r,{...this.connection.options,sessionHandling:!0});this.setConnection(s);try{await this.connection.open()}catch(o){if(this.setConnection(t),e)throw o;return!1}return!0}async disconnect(e=!1){if(!this.connection)throw new Error("No connection defined. please set a connection before trying to disconnect.");await this.connection.close(!1,e)}async request(e,t=this.defaultTimeoutInMs){return this.requestModule.request(e,t)}restartSubscriptions(){this.subscriptionModule.restartSubscriptions()}async requestWithQuality(e,t=Cr,r=this.defaultTimeoutInMs){return this.requestModule.requestWithQuality(e,t,r)}async requestEndpoint(e,t,r,s,o=this.defaultTimeoutInMs){return this.requestModule.requestEndpoint(e,t,r,s,o)}async requestProxyEndpoint(e,t,r,s,o=this.defaultTimeoutInMs){return this.requestModule.requestProxyEndpoint(e,t,r,s,o)}async requestAuthenticationToken(e,t,r,s=this.defaultTimeoutTokenInMs){return this.requestModule.requestAuthenticationToken(e,t,r,s)}async requestAuthenticationTokenExpiry(e,t,r,s=this.defaultTimeoutTokenInMs,o=!1){return this.requestModule.requestAuthenticationTokenExpiry(e,t,r,s,o)}async requestOtpAuthenticationTokenForSessionHandling(e=De.LIFETIME_SECONDS_MAXIMUM,t=-2,r=-2,s=this.defaultTimeoutTokenInMs){const{token:o,expiry:i}=await this.requestModule.requestAuthenticationTokenExpiry(e,t,r,s,!0);this.options.otpToken=o,this.options.otpTokenExpiry=i}async requestAuthenticationTokenForCookieTokenAuthentication(e,t,r,s=this.defaultTimeoutTokenInMs){return this.requestModule.requestAuthenticationTokenFactorsForCookieAuthentication(e,t,r,s)}observeEndpoint(e,t,r,s,o){return this.subscriptionModule.observeEndpoint(e,t,r,s,o)}async unobserveEndpoint(e){return this.subscriptionModule.unobserveEndpoint(e)}setConnection(e){e.options.logger&&this.setLogger(e.options.logger),this.isConnected&&this.logger.warn("Cannot modify an open connection. Disconnect first, before trying to set the connection."),this.connection=e,this.connection.clientOptions=this.options,this.connection.shouldRestartSubscriptions=this.shouldRestartSubscriptions,this.connection.onAuthentication=this.requestModule.onConnection.bind(this.requestModule),this.connection.onCleanupRequests=this.requestModule.clearPendingRequests.bind(this.requestModule),this.connection.onCleanupSubscriptions=this.subscriptionModule.clearPendingSubscriptions.bind(this.subscriptionModule),this.connection.onClearPendingSubscription=t=>{this.subscriptionModule.clearPendingSubscription(t)},this.connection.restartSubscriptions=this.subscriptionModule.restartSubscriptions.bind(this.subscriptionModule),this.connection.onConnect=this.onConnectCallback}getConnection(){return this.connection}async setConnectionFromFetchConfiguration(e,t,r){if(this.enableSessionHandling&&this.setConnectionFromSavedConfig()&&await this.connectSession())return this.sessionConnect=!0,Promise.resolve();const{config:s,response:o}=await Dt(e,t);return this.enableSessionHandling&&Br(s),this.setConnection(tn.createConnection({...s,logger:this.logger,loglevel:this.logger.getLevel(),shouldReconnectOnConnectionLoss:r},e,t)),o}static createConnection(e,t,r){return Gr(e,t,r)}setLogger(e){this.logger=e,this.requestModule.setLogger(e),this.subscriptionModule.setLogger(e),this.connection&&this.connection.setLogger(e)}getLogger(){return this.logger}get isConnected(){var e;return((e=this.connection)==null?void 0:e.isAuthenticated())??!1}get isConnecting(){var e;return((e=this.connection)==null?void 0:e.isConnecting())??!1}getServerInfo(){var e;return(e=this.connection)==null?void 0:e.auth.getServerInfo()}setConnectionFromSavedConfig(){const e=Jr();return e?(this.setConnection(tn.createConnection({...e,logger:this.logger,loglevel:this.logger.getLevel()})),!0):!1}}function ir(n,e={},t){for(const r in n){const s=n[r],o=t?`${t}:${r}`:r;typeof s=="object"&&s!==null?ir(s,e,o):typeof s=="function"&&(e[o]=s)}return e}const _c={run:n=>n()},Tc=()=>_c,Ds=typeof console.createTask<"u"?console.createTask:Tc;function Ec(n,e){const t=e.shift(),r=Ds(t);return n.reduce((s,o)=>s.then(()=>r.run(()=>o(...e))),Promise.resolve())}function Mc(n,e){const t=e.shift(),r=Ds(t);return Promise.all(n.map(s=>r.run(()=>s(...e))))}function ar(n,e){for(const t of[...n])t(e)}class Sc{constructor(){this._hooks={},this._before=void 0,this._after=void 0,this._deprecatedMessages=void 0,this._deprecatedHooks={},this.hook=this.hook.bind(this),this.callHook=this.callHook.bind(this),this.callHookWith=this.callHookWith.bind(this)}hook(e,t,r={}){if(!e||typeof t!="function")return()=>{};const s=e;let o;for(;this._deprecatedHooks[e];)o=this._deprecatedHooks[e],e=o.to;if(o&&!r.allowDeprecated){let i=o.message;i||(i=`${s} hook has been deprecated`+(o.to?`, please use ${o.to}`:"")),this._deprecatedMessages||(this._deprecatedMessages=new Set),this._deprecatedMessages.has(i)||(console.warn(i),this._deprecatedMessages.add(i))}if(!t.name)try{Object.defineProperty(t,"name",{get:()=>"_"+e.replace(/\W+/g,"_")+"_hook_cb",configurable:!0})}catch{}return this._hooks[e]=this._hooks[e]||[],this._hooks[e].push(t),()=>{t&&(this.removeHook(e,t),t=void 0)}}hookOnce(e,t){let r,s=(...o)=>(typeof r=="function"&&r(),r=void 0,s=void 0,t(...o));return r=this.hook(e,s),r}removeHook(e,t){if(this._hooks[e]){const r=this._hooks[e].indexOf(t);r!==-1&&this._hooks[e].splice(r,1),this._hooks[e].length===0&&delete this._hooks[e]}}deprecateHook(e,t){this._deprecatedHooks[e]=typeof t=="string"?{to:t}:t;const r=this._hooks[e]||[];delete this._hooks[e];for(const s of r)this.hook(e,s)}deprecateHooks(e){Object.assign(this._deprecatedHooks,e);for(const t in e)this.deprecateHook(t,e[t])}addHooks(e){const t=ir(e),r=Object.keys(t).map(s=>this.hook(s,t[s]));return()=>{for(const s of r.splice(0,r.length))s()}}removeHooks(e){const t=ir(e);for(const r in t)this.removeHook(r,t[r])}removeAllHooks(){for(const e in this._hooks)delete this._hooks[e]}callHook(e,...t){return t.unshift(e),this.callHookWith(Ec,e,...t)}callHookParallel(e,...t){return t.unshift(e),this.callHookWith(Mc,e,...t)}callHookWith(e,t,...r){const s=this._before||this._after?{name:t,args:r,context:{}}:void 0;this._before&&ar(this._before,s);const o=e(t in this._hooks?[...this._hooks[t]]:[],r);return o instanceof Promise?o.finally(()=>{this._after&&s&&ar(this._after,s)}):(this._after&&s&&ar(this._after,s),o)}beforeEach(e){return this._before=this._before||[],this._before.push(e),()=>{if(this._before!==void 0){const t=this._before.indexOf(e);t!==-1&&this._before.splice(t,1)}}}afterEach(e){return this._after=this._after||[],this._after.push(e),()=>{if(this._after!==void 0){const t=this._after.indexOf(e);t!==-1&&this._after.splice(t,1)}}}}function Ic(){return new Sc}const xs=typeof window<"u";function Ac(n,e={}){const t={inspect:xs,group:xs,filter:()=>!0,...e},r=t.filter,s=typeof r=="string"?u=>u.startsWith(r):r,o=t.tag?`[${t.tag}] `:"",i=u=>o+u.name+"".padEnd(u._id,"\0"),a={},c=n.beforeEach(u=>{s!==void 0&&!s(u.name)||(a[u.name]=a[u.name]||0,u._id=a[u.name]++,console.time(i(u)))}),h=n.afterEach(u=>{s!==void 0&&!s(u.name)||(t.group&&console.groupCollapsed(u.name),t.inspect?console.timeLog(i(u),u.args):console.timeEnd(i(u)),t.group&&console.groupEnd(),a[u.name]--)});return{close:()=>{c(),h()}}}class Fs{constructor(e){O(this,He);this.hooks=Ic(),R(this,He,1e4),e!=null&&e.hookDebug&&Ac(this.hooks,{tag:"hooks"}),e!=null&&e.defaultRequestTimeout&&R(this,He,e.defaultRequestTimeout)}get defaultTimeoutInMs(){return v(this,He)}set defaultTimeoutInMs(e){R(this,He,e)}log(e,...t){if(this.hooks.callHook("base:log",t),this.logger)switch(e){case y.TRACE:this.logger.trace(t);break;case y.DEBUG:this.logger.debug(t);break;case y.INFO:this.logger.info(t);break;case y.WARN:this.logger.warn(t);break;case y.ERROR:this.logger.error(t);break;case y.FATAL:this.logger.fatal(t);break}}}He=new WeakMap;const sn=class sn{constructor(e,t=[],r=[],s=[]){O(this,ae);O(this,Ge);O(this,Be,[]);O(this,Re,[]);O(this,Oe,[]);R(this,Ge,e),R(this,Be,t),R(this,Re,r),R(this,Oe,s)}static create(){return new sn(Fs)}with(e){const{featureName:t,disabledFeatures:r,disabledFeatureGroups:s,featureGroups:o}=e;if(!t)throw new Error("Feature name is missing");if(t!=="Custom"){if(q(this,ae,Vs).call(this,t),q(this,ae,Ys).call(this,t),v(this,Be).push(t),o&&o.length>0)for(const a of o)q(this,ae,Ks).call(this,a);if(r&&r.length>0)for(const a of r)q(this,ae,Qs).call(this,t,a);if(s&&s.length>0)for(const a of s)q(this,ae,Xs).call(this,t,a)}const i=e(v(this,Ge));return new sn(i,v(this,Be),v(this,Re),v(this,Oe))}build(e){return new(v(this,Ge))(e)}getClientConstructor(){return v(this,Ge)}};Ge=new WeakMap,Be=new WeakMap,Re=new WeakMap,Oe=new WeakMap,ae=new WeakSet,Vs=function(e){if(v(this,Be).includes(e))throw new Error(`Feature "${e}" has already been used.`)},Ys=function(e){for(const t of v(this,Re))if(t.feature===e)throw new Error(`Feature "${e}" has been disabled by ${t.disabler.join(",")}.`)},Ks=function(e){for(const t of v(this,Oe))if(t.feature===e)throw new Error(`Group "${e}" has been disabled by ${t.disabler.join(",")}.`)},Qs=function(e,t){for(const r of v(this,Re))if(r.feature===t){r.disabler.push(e);return}v(this,Re).push({disabler:[e],feature:t})},Xs=function(e,t){for(const r of v(this,Oe))if(r.feature===t){r.disabler.push(e);return}v(this,Oe).push({disabler:[e],feature:t})};let cr=sn;d.AbstractAuthentication=Rt,d.AbstractFrontgateConnection=jt,d.AbstractLogger=Te,d.AbstractMdg2Request=Ye,d.AuthenticationByTokenRequest=dt,d.AuthenticationTokenRequest=De,d.AuthenticationTokenResponse=Sn,d.CancelSubscriptionRequest=Ae,d.CancelSubscriptionResponse=ts,d.ConnectionState=Ie,d.ConsoleLogger=an,d.CookieTokenAuthentication=Cn,d.CookieTokenAuthenticationFactors=Rn,d.DefaultHosts=$r,d.DeploymentStage=Ur,d.Encoding=Se,d.ErrorResponse=Z,d.FetchConnectionConfigurationResponseHeaders=Lr,d.FrontgateClient=Fs,d.FrontgateClientBuilder=cr,d.FrontgateClientDataObserver=Nn,d.FrontgateClientEndpointDataObserver=is,d.FrontgateWSConnection=lt,d.HTTPProxyRequest=Ke,d.HTTPProxyResponse=An,d.HighLevelRequest=ve,d.HighLevelResponse=In,d.HighLevelUpdate=Ft,d.ID_APP_AUTHENTICATED=-2,d.ID_USER_AUTHENTICATED=-2,d.ID_USER_NONE=-1,d.LatencyTracker=On,d.LogLevel=y,d.LoggerHelper=Zs,d.Mdg2Client=tn,d.Mdg2Response=ne,d.NullLogger=at,d.PermissionDeniedResponse=ns,d.PingRequest=ze,d.PingResponse=je,d.RawRequest=es,d.RawRequestFactory=Mn,d.RejectResponse=rs,d.SubscriptionLossMessage=Ut,d.TimeOptions=Fr,d.TokenAuthentication=kn,d.TransportLayerClientRequestHeader=ft,d.WinstonLogger=to,d.authTokenRequest=Wo,d.cookieTokenAuth=si,d.createConnection=Gr,d.createConnectionInterface=ai,d.createExtendedMixinFactory=K,d.encodeSpanContext=bs,d.endpointRequest=zo,d.endpointSubscriptions=Qo,d.fetchAuth=ii,d.fetchConnectionConfiguration=Dt,d.getBytesFromBuffer=$o,d.getConnectionConfiguration=Jr,d.httpProxyRequest=_a,d.isErrorResponse=Wr,d.isHighLevelResponse=Vr,d.isHighLevelResponseMessage=Yr,d.isHighLevelUpdate=xt,d.isPermissionDeniedResponse=zr,d.isRejectResponse=Kr,d.isSubscriptionLossMessage=Qr,d.levels=eo,d.logger=Vo,d.messageCompressor=Yo,d.objectFromFetchHeaders=Hr,d.openTelemetry=wa,d.parseConnectionConfiguration=qr,d.pingRequests=Ta,d.rawSubscriptions=Xo,d.reconnect=ci,d.requests=Ko,d.setConnectionConfiguration=Br,d.timeToMilliseconds=Nt,d.tokenAuth=oi,d.useTimeout=ue,d.wsConnection=os,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})});