@factset/frontgate-js-sdk 6.11.1 → 7.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/CHANGELOG.md +97 -40
  2. package/dist/lib/esnext/FrontgateClient.js +0 -3
  3. package/dist/lib/esnext/authentication/index.js +3 -4
  4. package/dist/lib/esnext/common/errors.js +0 -35
  5. package/dist/lib/esnext/common/functions.js +0 -84
  6. package/dist/lib/esnext/common/interfaces/index.js +0 -1
  7. package/dist/lib/esnext/compat/index.js +0 -3
  8. package/dist/lib/esnext/connection/index.js +19 -6
  9. package/dist/lib/esnext/connection/util/functions.js +0 -56
  10. package/dist/lib/esnext/index.js +0 -1
  11. package/dist/lib/esnext/message/index.js +1 -1
  12. package/dist/lib/esnext/message/interfaces/index.js +0 -1
  13. package/dist/lib/esnext/message/request/TransportLayerClientRequestHeader.js +1 -1
  14. package/dist/lib/esnext/message/request/raw/example/CreateNotationSearchRequest.js +1 -1
  15. package/dist/lib/esnext/message/request/raw/index.js +0 -1
  16. package/dist/lib/esnext/message/response/index.js +0 -5
  17. package/dist/lib/esnext/message/update/index.js +0 -1
  18. package/dist/lib/esnext/mixins/EndpointRequestMixin.js +1 -1
  19. package/dist/lib/esnext/mixins/RemoteLoggerMixin.js +29 -0
  20. package/dist/lib/esnext/mixins/auth/AppAuthMixin.js +79 -11
  21. package/dist/lib/esnext/mixins/auth/SessionAuthMixin.js +76 -36
  22. package/dist/lib/esnext/mixins/auth/UserCredentialAuthMixin.js +82 -12
  23. package/dist/lib/esnext/mixins/auth/UserPasswordAuthMixin.js +80 -13
  24. package/dist/lib/esnext/mixins/auth/index.js +0 -31
  25. package/dist/lib/esnext/mixins/index.js +1 -0
  26. package/dist/lib/esnext/mixins/subscription/EndpointSubscriptionMixin.js +149 -122
  27. package/dist/lib/esnext/version.js +1 -1
  28. package/dist/lib/node/FrontgateClient.js +0 -3
  29. package/dist/lib/node/authentication/index.js +4 -4
  30. package/dist/lib/node/common/errors.js +1 -41
  31. package/dist/lib/node/common/functions.js +0 -92
  32. package/dist/lib/node/common/interfaces/index.js +0 -1
  33. package/dist/lib/node/compat/index.js +0 -3
  34. package/dist/lib/node/connection/index.js +20 -6
  35. package/dist/lib/node/connection/util/functions.js +0 -63
  36. package/dist/lib/node/index.js +1 -3
  37. package/dist/lib/node/message/index.js +2 -1
  38. package/dist/lib/node/message/interfaces/index.js +0 -1
  39. package/dist/lib/node/message/request/TransportLayerClientRequestHeader.js +3 -3
  40. package/dist/lib/node/message/request/raw/example/CreateNotationSearchRequest.js +3 -3
  41. package/dist/lib/node/message/request/raw/index.js +0 -1
  42. package/dist/lib/node/message/response/index.js +0 -5
  43. package/dist/lib/node/message/update/index.js +0 -1
  44. package/dist/lib/node/mixins/EndpointRequestMixin.js +2 -2
  45. package/dist/lib/node/mixins/RemoteLoggerMixin.js +33 -0
  46. package/dist/lib/node/mixins/auth/AppAuthMixin.js +78 -10
  47. package/dist/lib/node/mixins/auth/SessionAuthMixin.js +75 -35
  48. package/dist/lib/node/mixins/auth/UserCredentialAuthMixin.js +80 -10
  49. package/dist/lib/node/mixins/auth/UserPasswordAuthMixin.js +78 -11
  50. package/dist/lib/node/mixins/auth/index.js +0 -33
  51. package/dist/lib/node/mixins/index.js +1 -0
  52. package/dist/lib/node/mixins/subscription/EndpointSubscriptionMixin.js +149 -122
  53. package/dist/lib/node/version.js +1 -1
  54. package/dist/lib/types/FrontgateClient.d.ts +0 -1
  55. package/dist/lib/types/authentication/index.d.ts +3 -4
  56. package/dist/lib/types/authentication/util/ChallengeResolver.d.ts +2 -1
  57. package/dist/lib/types/common/errors.d.ts +0 -21
  58. package/dist/lib/types/common/functions.d.ts +0 -8
  59. package/dist/lib/types/common/interfaces/index.d.ts +0 -1
  60. package/dist/lib/types/compat/index.d.ts +0 -3
  61. package/dist/lib/types/connection/index.d.ts +16 -6
  62. package/dist/lib/types/connection/util/functions.d.ts +0 -18
  63. package/dist/lib/types/index.d.ts +0 -1
  64. package/dist/lib/types/message/index.d.ts +1 -1
  65. package/dist/lib/types/message/interfaces/index.d.ts +0 -1
  66. package/dist/lib/types/message/request/TransportLayerClientRequestHeader.d.ts +1 -0
  67. package/dist/lib/types/message/request/raw/index.d.ts +0 -1
  68. package/dist/lib/types/message/response/index.d.ts +0 -5
  69. package/dist/lib/types/message/update/index.d.ts +0 -1
  70. package/dist/lib/types/mixins/AuthTokenRequestMixin.d.ts +1 -2
  71. package/dist/lib/types/mixins/EndpointRequestMixin.d.ts +1 -2
  72. package/dist/lib/types/mixins/HTTPProxyRequestMixin.d.ts +1 -4
  73. package/dist/lib/types/mixins/LoggerMixin.d.ts +1 -2
  74. package/dist/lib/types/mixins/MessageCompressorMixin.d.ts +1 -2
  75. package/dist/lib/types/mixins/OpenTelemetryMixin.d.ts +1 -2
  76. package/dist/lib/types/mixins/PingMixin.d.ts +1 -2
  77. package/dist/lib/types/mixins/ReconnectMixin.d.ts +1 -2
  78. package/dist/lib/types/mixins/RemoteLoggerMixin.d.ts +16 -0
  79. package/dist/lib/types/mixins/RequestMixin.d.ts +1 -2
  80. package/dist/lib/types/mixins/auth/AppAuthMixin.d.ts +15 -8
  81. package/dist/lib/types/mixins/auth/CookieTokenAuthMixin.d.ts +1 -2
  82. package/dist/lib/types/mixins/auth/FetchAuthenticationMixin.d.ts +1 -2
  83. package/dist/lib/types/mixins/auth/SessionAuthMixin.d.ts +10 -5
  84. package/dist/lib/types/mixins/auth/TokenAuthMixin.d.ts +1 -2
  85. package/dist/lib/types/mixins/auth/UserCredentialAuthMixin.d.ts +15 -8
  86. package/dist/lib/types/mixins/auth/UserPasswordAuthMixin.d.ts +15 -8
  87. package/dist/lib/types/mixins/auth/index.d.ts +0 -8
  88. package/dist/lib/types/mixins/connection/FrontgateWSMixin.d.ts +1 -2
  89. package/dist/lib/types/mixins/index.d.ts +2 -1
  90. package/dist/lib/types/mixins/subscription/EndpointSubscriptionMixin.d.ts +4 -6
  91. package/dist/lib/types/mixins/subscription/RawSubscriptionMixin.d.ts +1 -2
  92. package/dist/lib/umd/mdg2.client.min.umd.js +1 -12
  93. package/dist/lib/umd/mdg2.client.umd.js +4061 -8138
  94. package/package.json +25 -28
  95. package/dist/lib/esnext/Mdg2Client.js +0 -185
  96. package/dist/lib/esnext/authentication/AbstractAuthentication.js +0 -49
  97. package/dist/lib/esnext/authentication/AppAuthentication.js +0 -70
  98. package/dist/lib/esnext/authentication/AuthenticationInterface.js +0 -1
  99. package/dist/lib/esnext/authentication/CookieTokenAuthentication.js +0 -18
  100. package/dist/lib/esnext/authentication/TokenAuthentication.js +0 -42
  101. package/dist/lib/esnext/authentication/UserCredentialAuthentication.js +0 -73
  102. package/dist/lib/esnext/authentication/UserPasswordAuthentication.js +0 -71
  103. package/dist/lib/esnext/common/Mdg2ClientOptions.js +0 -1
  104. package/dist/lib/esnext/common/constants.js +0 -10
  105. package/dist/lib/esnext/common/interfaces/observe/ObserveOptions.js +0 -1
  106. package/dist/lib/esnext/connection/AbstractFrontgateConnection.js +0 -324
  107. package/dist/lib/esnext/connection/ConnectionInterface.js +0 -1
  108. package/dist/lib/esnext/connection/FrontgateWSConnection.js +0 -281
  109. package/dist/lib/esnext/connection/JobPromise.js +0 -2
  110. package/dist/lib/esnext/connection/LatencyHandler.js +0 -1
  111. package/dist/lib/esnext/connection/LatencyTracker.js +0 -47
  112. package/dist/lib/esnext/connection/MessageProcessor.js +0 -1
  113. package/dist/lib/esnext/connection/util/Encoding.js +0 -14
  114. package/dist/lib/esnext/core/RequestModule.js +0 -349
  115. package/dist/lib/esnext/core/SubscriptionModule.js +0 -104
  116. package/dist/lib/esnext/core/subscription/EndpointHandler.js +0 -121
  117. package/dist/lib/esnext/core/subscription/SubjectManager.js +0 -39
  118. package/dist/lib/esnext/message/MessageFactory.js +0 -36
  119. package/dist/lib/esnext/message/guards.js +0 -21
  120. package/dist/lib/esnext/message/interfaces/JobObservable.js +0 -1
  121. package/dist/lib/esnext/message/request/raw/RawRequestFactory.js +0 -18
  122. package/dist/lib/esnext/message/response/AuthenticationByTokenResponse.js +0 -1
  123. package/dist/lib/esnext/message/response/CancelSubscriptionResponse.js +0 -3
  124. package/dist/lib/esnext/message/response/LoadNotificationMessage.js +0 -1
  125. package/dist/lib/esnext/message/response/PermissionDeniedResponse.js +0 -6
  126. package/dist/lib/esnext/message/response/RejectResponse.js +0 -9
  127. package/dist/lib/esnext/message/update/SubscriptionLossMessage.js +0 -10
  128. package/dist/lib/esnext/util/TimeOutWrapper.js +0 -51
  129. package/dist/lib/node/Mdg2Client.js +0 -189
  130. package/dist/lib/node/authentication/AbstractAuthentication.js +0 -53
  131. package/dist/lib/node/authentication/AppAuthentication.js +0 -74
  132. package/dist/lib/node/authentication/AuthenticationInterface.js +0 -2
  133. package/dist/lib/node/authentication/CookieTokenAuthentication.js +0 -22
  134. package/dist/lib/node/authentication/TokenAuthentication.js +0 -46
  135. package/dist/lib/node/authentication/UserCredentialAuthentication.js +0 -77
  136. package/dist/lib/node/authentication/UserPasswordAuthentication.js +0 -75
  137. package/dist/lib/node/common/Mdg2ClientOptions.js +0 -2
  138. package/dist/lib/node/common/constants.js +0 -13
  139. package/dist/lib/node/common/interfaces/observe/ObserveOptions.js +0 -2
  140. package/dist/lib/node/connection/AbstractFrontgateConnection.js +0 -328
  141. package/dist/lib/node/connection/ConnectionInterface.js +0 -2
  142. package/dist/lib/node/connection/FrontgateWSConnection.js +0 -288
  143. package/dist/lib/node/connection/JobPromise.js +0 -6
  144. package/dist/lib/node/connection/LatencyHandler.js +0 -2
  145. package/dist/lib/node/connection/LatencyTracker.js +0 -51
  146. package/dist/lib/node/connection/MessageProcessor.js +0 -2
  147. package/dist/lib/node/connection/util/Encoding.js +0 -18
  148. package/dist/lib/node/core/RequestModule.js +0 -353
  149. package/dist/lib/node/core/SubscriptionModule.js +0 -108
  150. package/dist/lib/node/core/subscription/EndpointHandler.js +0 -125
  151. package/dist/lib/node/core/subscription/SubjectManager.js +0 -43
  152. package/dist/lib/node/message/MessageFactory.js +0 -73
  153. package/dist/lib/node/message/guards.js +0 -30
  154. package/dist/lib/node/message/interfaces/JobObservable.js +0 -2
  155. package/dist/lib/node/message/request/raw/RawRequestFactory.js +0 -22
  156. package/dist/lib/node/message/response/AuthenticationByTokenResponse.js +0 -2
  157. package/dist/lib/node/message/response/CancelSubscriptionResponse.js +0 -7
  158. package/dist/lib/node/message/response/LoadNotificationMessage.js +0 -2
  159. package/dist/lib/node/message/response/PermissionDeniedResponse.js +0 -10
  160. package/dist/lib/node/message/response/RejectResponse.js +0 -13
  161. package/dist/lib/node/message/update/SubscriptionLossMessage.js +0 -14
  162. package/dist/lib/node/util/TimeOutWrapper.js +0 -55
  163. package/dist/lib/types/Mdg2Client.d.ts +0 -52
  164. package/dist/lib/types/authentication/AbstractAuthentication.d.ts +0 -17
  165. package/dist/lib/types/authentication/AppAuthentication.d.ts +0 -12
  166. package/dist/lib/types/authentication/AuthenticationInterface.d.ts +0 -9
  167. package/dist/lib/types/authentication/CookieTokenAuthentication.d.ts +0 -6
  168. package/dist/lib/types/authentication/TokenAuthentication.d.ts +0 -14
  169. package/dist/lib/types/authentication/UserCredentialAuthentication.d.ts +0 -13
  170. package/dist/lib/types/authentication/UserPasswordAuthentication.d.ts +0 -14
  171. package/dist/lib/types/common/Mdg2ClientOptions.d.ts +0 -12
  172. package/dist/lib/types/common/constants.d.ts +0 -11
  173. package/dist/lib/types/common/interfaces/observe/ObserveOptions.d.ts +0 -5
  174. package/dist/lib/types/connection/AbstractFrontgateConnection.d.ts +0 -116
  175. package/dist/lib/types/connection/ConnectionInterface.d.ts +0 -53
  176. package/dist/lib/types/connection/FrontgateWSConnection.d.ts +0 -23
  177. package/dist/lib/types/connection/JobPromise.d.ts +0 -3
  178. package/dist/lib/types/connection/LatencyHandler.d.ts +0 -1
  179. package/dist/lib/types/connection/LatencyTracker.d.ts +0 -13
  180. package/dist/lib/types/connection/MessageProcessor.d.ts +0 -2
  181. package/dist/lib/types/connection/util/Encoding.d.ts +0 -9
  182. package/dist/lib/types/core/RequestModule.d.ts +0 -78
  183. package/dist/lib/types/core/SubscriptionModule.d.ts +0 -24
  184. package/dist/lib/types/core/subscription/EndpointHandler.d.ts +0 -37
  185. package/dist/lib/types/core/subscription/SubjectManager.d.ts +0 -21
  186. package/dist/lib/types/message/MessageFactory.d.ts +0 -29
  187. package/dist/lib/types/message/guards.d.ts +0 -11
  188. package/dist/lib/types/message/interfaces/JobObservable.d.ts +0 -4
  189. package/dist/lib/types/message/request/raw/RawRequestFactory.d.ts +0 -4
  190. package/dist/lib/types/message/response/AuthenticationByTokenResponse.d.ts +0 -20
  191. package/dist/lib/types/message/response/CancelSubscriptionResponse.d.ts +0 -3
  192. package/dist/lib/types/message/response/LoadNotificationMessage.d.ts +0 -8
  193. package/dist/lib/types/message/response/PermissionDeniedResponse.d.ts +0 -4
  194. package/dist/lib/types/message/response/RejectResponse.d.ts +0 -5
  195. package/dist/lib/types/message/update/SubscriptionLossMessage.d.ts +0 -17
  196. package/dist/lib/types/util/TimeOutWrapper.d.ts +0 -12
@@ -1,12 +1 @@
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,at)=>(lr(d,G,"write to private field"),at?at.call(d,X):G.set(d,X),X),q=(d,G,X)=>(lr(d,G,"access private method"),X);var $s=(d,G,X,at)=>({set _(Ot){R(d,G,Ot,X)},get _(){return v(d,G,at)}});var qe,St,It,He,Ge,Be,Re,Oe,ce,Vs,Ys,Ks,Qs,Xs;class Ot{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 ct 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,ct)}}var H=Uint8Array,te=Uint16Array,cn=Int32Array,Pt=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]),Nt=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(Pt,2),br=vr.b,hn=vr.r;br[28]=258,hn[258]=28;for(var mr=gr(Nt,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 ut=new H(32),U=0;U<32;++U)ut[U]=5;var ro=pe(Me,9,0),so=pe(Me,9,1),oo=pe(ut,5,0),io=pe(ut,5,1),fn=function(n){for(var e=n[0],t=1;t<n.length;++t)n[t]>e&&(e=n[t]);return e},ue=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(kt){var Ct=t.length;if(kt>Ct){var ot=new H(Math.max(Ct*2,kt));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=ue(n,l,1);var m=ue(n,l+1,3);if(l+=3,m)if(m==1)f=so,E=io,_=9,A=5;else if(m==2){var k=ue(n,l,31)+257,N=ue(n,l+10,15)+4,g=k+ue(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]]=ue(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[ue(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+ue(n,l,3),l+=2,j=p[C-1]):T==17?(L=3+ue(n,l,7),l+=3):T==18&&(L=11+ue(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,S=n[T-4]|n[T-3]<<8,M=T+S;if(M>s){c&&W(0);break}a&&h(b+S),t.set(n.subarray(T,M),b),e.b=b+=S,e.p=l=M*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,ie=l;;ie=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){ie=l,f=null;break}else{var J=Y-254;if(Y>264){var C=Y-257,D=Pt[C];J=ue(n,l,(1<<D)-1)+br[C],l+=D}var ae=E[dn(n,l)&ee],me=ae>>4;ae||W(3),l+=ae&15;var $=no[me];if(me>3){var D=Nt[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=ie,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},ht=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(M,k){return M.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 S=o[r].s;f[S]==e&&(--f[S],++_)}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}},lt=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,S=wr(_),M=S.c,k=S.n,N=new te(19),g=0;g<m.length;++g)++N[m[g]&31];for(var g=0;g<M.length;++g)++N[M[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=lt(s,Me)+lt(o,ut)+i,F=lt(s,b)+lt(o,_)+i+14+3*x+lt(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,M],ie=0;ie<2;++ie)for(var Y=ee[ie],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,$=ut;for(var g=0;g<a;++g){var D=r[g];if(D>255){var J=D>>18&31;ht(e,u,j[J+257]),u+=L[J+257],J>7&&(ye(e,u,D>>23&31),u+=Pt[J]);var ae=D&31;ht(e,u,V[ae]),u+=$[ae],ae>3&&(ht(e,u,D>>5&8191),u+=Nt[ae])}else ht(e,u,j[D]),u+=L[D]}return ht(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},S=new cn(25e3),M=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,S,M,k,g,I,x,p-x,u),I=N=g=0,x=p;for(var L=0;L<286;++L)M[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 ie=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>ie)break;for(var ae=Math.min(ee,D-2),me=0,L=0;L<ae;++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($){S[I++]=268435456|hn[V]<<18|yr[$];var kt=hn[V]&31,Ct=yr[$]&31;g+=Pt[kt]+Nt[Ct],++M[257+kt],++k[Ct],C=p+V,++N}else S[I++]=n[p],++M[n[p]]}}for(p=Math.max(p,C);p<i;++p)S[I++]=n[p],++M[n[p]];u=Tr(n,c,h,S,M,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(S){return a(S,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 S={};return T.isMergeableObject(w)&&l(w).forEach(function(M){S[M]=a(w[M],T)}),l(m).forEach(function(M){f(w,M)||(b(w,M)&&T.isMergeableObject(m[M])?S[M]=h(M,T)(w[M],m[M],T):S[M]=a(m[M],T))}),S}function _(w,m,T){T=T||{},T.arrayMerge=T.arrayMerge||c,T.isMergeableObject=T.isMergeableObject||n,T.cloneUnlessOtherwiseSpecified=a;var S=Array.isArray(m),M=Array.isArray(w),k=S===M;return k?S?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(S,M){return _(S,M,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 jt(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(jt(e.time_at_sender.microseconds)),this._timeFromRequest=Number(jt(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 rn=class rn{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={...rn.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}};rn.DEFAULT_OPTIONS={payload_content:"foundation",deployment_stage:30,logger:ct.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 Dt=rn;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 ft extends Dt{constructor(e,t){if(typeof ge>"u")throw new Co("WebSocketClient not supported, WebSocket() missing in JavaScript environment");super(e,ft.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 S=T.reason?`: ${T.reason}`:"";r(new Error(`Connection closed while trying to connect${S}`))},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 xt(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 ft(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 Ft(n){return n.name==="Foundation::HighLevelUpdate"}function Qr(n){return n.name==="Foundation::SubscriptionLossMessage"}const Xr={version:"6.11.1",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)}),he=async(n,e,t)=>Promise.race([Go(n,e),t]),Zr=n=>n+Math.random()*100,le=class le{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(le.PRICE_QUALITY).find(t=>le.PRICE_QUALITY[t]===this.headerMembers.dataset.id_dataset)}setQuality(e){this.headerMembers.dataset.id_dataset=le.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+le.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(le.PRICE_QUALITY,e)?le.PRICE_QUALITY[e]:le.PRICE_QUALITY.DLY}};le.PRICE_QUALITY={RLT:129,DLY:0,EOD:130},le.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 dt=le;class Ye{constructor(e,t){this.header=new dt,this.coreMembers={Message:e,Version:t},this.members={}}getPtlMessage(){const e={header:this.header.getPtlMessage()};return jo(this.coreMembers,e,this.members)}}class pt{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 fe=class fe extends Ye{constructor(e,t,r,s,o=!1){super(fe.NAME,fe.VERSION),t&&this.header.setIdUser(t),r&&this.header.setIdApplication(r),s&&this.header.setTimeout(s),this.members.flags=o?fe.FLAG_SINGLE_USAGE:0,this.members.lifetime_seconds_r2=e??fe.LIFETIME_SECONDS_DEFAULT,this.header.setFlag("no_merge")}};fe.NAME="AuthenticationTokenRequest",fe.VERSION=6,fe.LIFETIME_SECONDS_DEFAULT=-1,fe.LIFETIME_SECONDS_MAXIMUM=-2,fe.FLAG_SINGLE_USAGE=1;let De=fe;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 de=class de extends Ye{constructor(e,t,r={},s){super(de.NAME,de.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"?de.METHOD.POST:de.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===de.METHOD.POST?de.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)}}};de.NAME="HighLevelRequest",de.VERSION=3,de.METHOD={GET:1,POST:2};let ve=de;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(jt(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 Ut 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 $t 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:Ut,SubscriptionLossMessage:$t},Symbol.toStringTag,{value:"Module"}));class kn extends Ot{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 pt(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 xt(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 xt(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 sn=class sn{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<sn.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}};sn.MAX_RESPONSE_LATENCY_MS=60*1e3;let On=sn;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 he(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"]}),Lt=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)&Lt)===Lt}};st.msgNameSeparator="::",st.msgNameSeparatorLength=2;let qt=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}`,S=>{var M,k,N,g;try{if(!S.Message.includes("HighLevelResponse")){w(JSON.stringify(S));return}if(q(this,r,Ls).call(this,S))m.push({body:((N=S.body)==null?void 0:N.value)??"",processingTime:((g=S.header)==null?void 0:g.processingTime)??0}),T();else{m.push({body:((M=S.body)==null?void 0:M.value)??"",processingTime:((k=S.header)==null?void 0:k.processingTime)??0});const p=new In({...S,body:{value:m.map(I=>I.body).join("")},header:{...S.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 he(l,_,E)}},r=new WeakSet,Ls=function(a){var c;return((((c=a.header)==null?void 0:c.flags)??0)&Lt)===Lt},o},{featureName:"EndpointRequest",featureGroups:["Misc"]}),os=n=>K(t=>{var r,s,o,i,a,c,h,u,it,b,f,qs,Hs,Rt,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,it)==="connected"&&p.callbackType==="response")q(this,u,Rt).call(this,p.message);else if(v(this,u,it)==="authenticated")q(this,u,Rt).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,Rt).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,it)!=="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};try{await this.hooks.callHook("frontgateConnection:beforeConnect",$)}catch(ie){throw R(this,o,"disconnected"),ie}this.log(y.DEBUG,`Connecting to ${$.url} with subprotocols ${$.subProtocols}`);const Je=new Promise((ie,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"),ie()})},v(this,r).onclose=D=>{J==null||J(),this.log(y.DEBUG,"Disconnected",D),v(this,o)==="connecting"||v(this,o)==="connected"?Y(JSON.stringify(D)):this.hooks.callHook("frontgateConnection:disconnected",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:ae}=D;this.log(y.DEBUG,"Received data:",ae);const me={msg:ae};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 he(this.defaultTimeoutInMs,ee,Je)}async disconnect(){return new Promise(g=>{q(this,u,Rt).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,u,it)==="authenticated"}isDisconnected(){return v(this,o)!=="authenticated"}isReadyToConnect(){return v(this,u,it)==="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,it=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}},Rt=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 he(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}`,S=>{if(!S.Message.includes("HighLevelResponse")){this.log(y.ERROR,`Unexpected response: ${S.Message}`),T(new Z(JSON.stringify(S)));return}let M;try{M=JSON.parse(S.body.value)}catch(I){this.log(y.ERROR,`Failed to parse response: ${S.body.value}`),this.log(y.ERROR,I),T(I);return}const k=new is(S.header.id_job,M);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: ${S.Message}`),k.pushError(new Z(JSON.stringify(I))),N();return}let C;try{C=new Ut(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(!S.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 Ut(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(k.idJob).getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",V),N(),p()},k.pushPatchData(F.data)}),C()})});try{await he(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(k.idJob).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 he(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,S=typeof h>"u"?new Ae(m.header.id_job):new h(m.header.id_service,a.getPtlMessage().id_notation),M=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}`),M.pushError(new Z(JSON.stringify(g)));return}M.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);M.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);M.pushError(F);return}M.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()},M.pushData(P)}),p()})});try{await he(u,"Request timeout reached",g)}catch(p){M.pushError(new Z({Message:"Reconnect failed",Error:p}))}});M.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:S.getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",p),k(),N()},v(this,t).set(l,{observer:M,count:1}),A(M)})}),_=`Request timeout reached (${u} ms) for ${f.message.Message}`;return he(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,St,[]);O(this,It,[]);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,It).push(t),v(this,St).push(e)}pushData(e){R(this,qe,e),v(this,St).forEach(t=>{t(e)})}pushError(e){v(this,It).forEach(t=>{t(e)})}}qe=new WeakMap,St=new WeakMap,It=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 pt(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 pt(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",A),_.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 pt(w,A.maximum_idle_interval).toJson();this.log(y.INFO,"Sending message",T);const S={message:T,callbackType:"response",callbackId:T.Message.replace("Request","Response")};await this.hooks.callHook("frontgateConnection:sendMessage",S),this.hooks.hookOnce(`frontgateConnection:response:${S.callbackId}`,M=>{this.log(y.INFO,"Received response",M),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"),S=E.get("frontgate-websocket-port")??"443",M=`wss://${_}:${S}${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:M,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=n=>K(t=>{var r,s,o,i;return i=class extends t{constructor(...c){super(...c);O(this,r,0);O(this,s);O(this,o);R(this,s,n??[1e3,2e3,4e3,8e3,16e3,32e3]);const h=u=>{if(u.code!==1e3){v(this,o)&&(this.log(y.WARN,"Aborting previous reconnect attempt"),clearTimeout(v(this,o)),R(this,r,0));let l=v(this,r);v(this,r)>=v(this,s).length&&(l=v(this,s).length-1);const b=v(this,s)[l];R(this,o,setTimeout(()=>{this.log(y.INFO,`Reconnecting... Attempt ${v(this,r)}`);const f=this.hooks.hookOnce("reconnect:failed",h);this.hooks.callHook("reconnect:attempt",u).then(f).catch(()=>{this.log(y.ERROR,"Failed to reconnect")}),R(this,o,void 0)},b)),$s(this,r)._++}};this.hooks.hookOnce("frontgateConnection:disconnected",h),this.hooks.hook("reconnect:success",()=>{clearTimeout(v(this,o)),R(this,o,void 0),R(this,r,0),this.log(y.INFO,"Reconnected"),this.hooks.hookOnce("frontgateConnection:disconnected",h)})}},r=new WeakMap,s=new WeakMap,o=new WeakMap,i},{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],gt=Symbol.for("opentelemetry.js.api."+fi),vt=ui;function bt(n,e,t,r){var s;r===void 0&&(r=!1);var o=vt[gt]=(s=vt[gt])!==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=vt[gt])===null||e===void 0?void 0:e.version;if(!(!r||!li(r)))return(t=vt[gt])===null||t===void 0?void 0:t[n]}function mt(n,e){e.debug("@opentelemetry/api: Unregistering a global for "+n+" v"+xe+".");var t=vt[gt];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 yt("debug",this._namespace,e)},n.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return yt("error",this._namespace,e)},n.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return yt("info",this._namespace,e)},n.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return yt("warn",this._namespace,e)},n.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return yt("verbose",this._namespace,e)},n})();function yt(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 bt("diag",l,t,!0)};t.setLogger=r,t.disable=function(){mt(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})(),Ht=(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})(Ht),ki=(function(n){Ue(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.add=function(t,r){},e})(Ht),Ci=(function(n){Ue(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.record=function(t,r){},e})(Ht),Ri=(function(n){Ue(e,n);function e(){return n!==null&&n.apply(this,arguments)||this}return e.prototype.record=function(t,r){},e})(Ht),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,Gt=(function(){function n(){}return n.getInstance=function(){return this._instance||(this._instance=new n),this._instance},n.prototype.setGlobalContextManager=function(e){return bt(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(),mt(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},wt=(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(Gt.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 wt(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 wt(n)}var Ln=Gt.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 wt;var o=r&&ls(r);return oa(o)&&fs(o)?new wt(o):new wt},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})();Gt.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 bt(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(){mt(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(Gt.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 bt(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(){mt(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=bt(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(){mt(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 he(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 he(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 Bt(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 Jt(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
- `+t.map(function(r,s){return s+1+") "+r.toString()}).join(`
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 _t=(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=Jt(Jt([],Bt(o)),Bt(_.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=_t.EMPTY;function _s(n){return n instanceof _t||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,Jt([n,e],Bt(t)))},clearTimeout:function(n){return clearTimeout(n)},delegate:void 0};function Es(n){Aa.setTimeout(function(){throw n})}function Ms(){}function Wt(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 Tt(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})(_t),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){zt(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){zt(r)}else zt(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){zt(t)}},n})(),Tt=(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 zt(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 Tt(e,t,r);return Wt(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 Tt({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 Vt(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 Yt(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"}}),Et=(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;Wt(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;Wt(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;Wt(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 _t(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})(Et),ks={now:function(){return(ks.delegate||Date).now()},delegate:void 0},Kt=(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})(Et),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 Vt(function(t,r){var s=0;t.subscribe(Yt(r,function(o){r.next(n.call(e,o,s++))}))})}function ec(n,e){return Vt(function(t,r){var s=0;t.subscribe(Yt(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 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,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 Vt(function(T,S){f++,!_&&!E&&A();var M=b=b??t();S.add(function(){f--,f===0&&!_&&!E&&(l=Qn(m,c))}),M.subscribe(S),!u&&f>0&&(u=new Tt({next:function(k){return M.next(k)},error:function(k){_=!0,A(),l=Qn(w,s,k),M.error(k)},complete:function(){E=!0,A(),l=Qn(w,i),M.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 Tt({next:function(){s.unsubscribe(),n()}});return Kn(e.apply(void 0,Jt([],Bt(t)))).subscribe(s)}}function Rs(n,e,t){var r,s=!1;return r=n,tc({connector:function(){return new Kt(r,e,t)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:s})}function nc(n,e){return Vt(function(t,r){var s=null,o=0,i=!1,a=function(){return i&&!s&&r.complete()};t.subscribe(Yt(r,function(c){s==null||s.unsubscribe();var h=0,u=o++;Kn(n(c,u)).subscribe(s=Yt(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 Qt{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=_t.EMPTY,this.chunks=new Map,this.replaySubjectBufferSize=r.replaySubjectBufferSize,this.requestSubject=new Kt(this.replaySubjectBufferSize),this.jobs=new Map}setLogger(e){this.logger=e}reset(){this.logger.trace("requestModule.reset()"),this.requestSubject.complete(),this.requestSubject=new Kt(this.replaySubjectBufferSize),this.chunks.clear()}async requestWithQuality(e,t,r=this.options.defaultTimeoutInMs){return t==="BST"?this.requestBestQuality(e,r):(t&&Object.keys(dt.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 Qt.supportedPermissionDeniedResponseMessages(e)&&this.options.flagPermissionDenied&&e.header.setFlag("permission_denied_response"),Qt.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(qt.hasNextChunk(e)){this.logger.trace("Received message chunk",e),this.collectChunk(e);return}this.prependCollectedChunks(e)}try{t=qt.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
- * https://github.com/Starcounter-Jack/JSON-Patch
5
- * (c) 2017-2022 Joachim Wester
6
- * MIT licensed
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=Xt(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=Xt(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:Mt(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 Xt(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):en(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=Xt(n,e.from),e.op==="move"&&(i.removed=n),i;if(e.op==="test"){if(i.test=Mt(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=en;;){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 Zt(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 en(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)Zt(se(e),se(n),t||!0);else{t=t||en;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 Mt(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(!Mt(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],!Mt(n[i],e[i]))return!1;return!0}return n!==n&&e!==e}const hc=Object.freeze(Object.defineProperty({__proto__:null,JsonPatchError:B,_areEquals:Mt,applyOperation:Le,applyPatch:Zt,applyReducer:uc,deepClone:ac,getValueByPointer:Xt,validate:js,validator:en},Symbol.toStringTag,{value:"Module"}));/*!
9
- * https://github.com/Starcounter-Jack/JSON-Patch
10
- * (c) 2017-2021 Joachim Wester
11
- * MIT license
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&&Zt(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 At=class At{constructor(e,t,r){this.resultMapper=Za(s=>{if(Ft(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 Kt(1),c=a.pipe(rc()),h=i.asObservable().pipe(At.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=Zt(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(At.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){({...tn.defaultObserveOptions,...e}).minInterval&&this.logger.warn("Option `minInterval` is deprecated. Use _subscriptionMinimumInterval (GET) or meta.subscription.minimumInterval (POST) for server side throttling.")}};At.highLevelResponseFilter=ec(e=>Vr(e)||Ft(e));let or=At;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 $t({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 $t({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(Ft(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 tn=ur;class nn{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 Qt(this.getConnection.bind(this),this.logger,{defaultTimeoutInMs:this.defaultTimeoutInMs,defaultTimeoutTokenInMs:this.defaultTimeoutTokenInMs,flagPermissionDenied:this.flagPermissionDenied,maxTimeoutsBeforeReconnect:this.maxTimeoutsBeforeReconnect,replaySubjectBufferSize:this.replaySubjectBufferSize}),this.subscriptionModule=new tn(this.requestModule,this.logger,{shouldRestartSubscriptions:this.shouldRestartSubscriptions}),this.sessionConnect=!1,t.onConnectCallback&&(this.onConnectCallback=t.onConnectCallback),e?this.setConnection(e):this.logger=new ct}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 ft(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 xt(e,t);return this.enableSessionHandling&&Br(s),this.setConnection(nn.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(nn.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 on=class on{constructor(e,t=[],r=[],s=[]){O(this,ce);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 on(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,ce,Vs).call(this,t),q(this,ce,Ys).call(this,t),v(this,Be).push(t),o&&o.length>0)for(const a of o)q(this,ce,Ks).call(this,a);if(r&&r.length>0)for(const a of r)q(this,ce,Qs).call(this,t,a);if(s&&s.length>0)for(const a of s)q(this,ce,Xs).call(this,t,a)}const i=e(v(this,Ge));return new on(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,ce=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=on;d.AbstractAuthentication=Ot,d.AbstractFrontgateConnection=Dt,d.AbstractLogger=Te,d.AbstractMdg2Request=Ye,d.AuthenticationByTokenRequest=pt,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=ft,d.HTTPProxyRequest=Ke,d.HTTPProxyResponse=An,d.HighLevelRequest=ve,d.HighLevelResponse=In,d.HighLevelUpdate=Ut,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=nn,d.Mdg2Response=ne,d.NullLogger=ct,d.PermissionDeniedResponse=ns,d.PingRequest=ze,d.PingResponse=je,d.RawRequest=es,d.RawRequestFactory=Mn,d.RejectResponse=rs,d.SubscriptionLossMessage=$t,d.TimeOptions=Fr,d.TokenAuthentication=kn,d.TransportLayerClientRequestHeader=dt,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=xt,d.getBytesFromBuffer=$o,d.getConnectionConfiguration=Jr,d.httpProxyRequest=_a,d.isErrorResponse=Wr,d.isHighLevelResponse=Vr,d.isHighLevelResponseMessage=Yr,d.isHighLevelUpdate=Ft,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=jt,d.tokenAuth=oi,d.useTimeout=he,d.wsConnection=os,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(b,Ie){typeof exports=="object"&&typeof module<"u"?Ie(exports):typeof define=="function"&&define.amd?define(["exports"],Ie):(b=typeof globalThis<"u"?globalThis:b||self,Ie(b.fdsg={}))})(this,(function(b){"use strict";function Ie(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var et,Pt;function Mr(){if(Pt)return et;Pt=1;var r=function(g){return e(g)&&!t(g)};function e(l){return!!l&&typeof l=="object"}function t(l){var g=Object.prototype.toString.call(l);return g==="[object RegExp]"||g==="[object Date]"||o(l)}var n=typeof Symbol=="function"&&Symbol.for,s=n?Symbol.for("react.element"):60103;function o(l){return l.$$typeof===s}function i(l){return Array.isArray(l)?[]:{}}function c(l,g){return g.clone!==!1&&g.isMergeableObject(l)?E(i(l),l,g):l}function a(l,g,p){return l.concat(g).map(function(y){return c(y,p)})}function f(l,g){if(!g.customMerge)return E;var p=g.customMerge(l);return typeof p=="function"?p:E}function u(l){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(l).filter(function(g){return Object.propertyIsEnumerable.call(l,g)}):[]}function h(l){return Object.keys(l).concat(u(l))}function v(l,g){try{return g in l}catch{return!1}}function w(l,g){return v(l,g)&&!(Object.hasOwnProperty.call(l,g)&&Object.propertyIsEnumerable.call(l,g))}function M(l,g,p){var y={};return p.isMergeableObject(l)&&h(l).forEach(function(_){y[_]=c(l[_],p)}),h(g).forEach(function(_){w(l,_)||(v(l,_)&&p.isMergeableObject(g[_])?y[_]=f(_,p)(l[_],g[_],p):y[_]=c(g[_],p))}),y}function E(l,g,p){p=p||{},p.arrayMerge=p.arrayMerge||a,p.isMergeableObject=p.isMergeableObject||r,p.cloneUnlessOtherwiseSpecified=c;var y=Array.isArray(g),_=Array.isArray(l),R=y===_;return R?y?p.arrayMerge(l,g,p):M(l,g,p):c(g,p)}E.all=function(g,p){if(!Array.isArray(g))throw new Error("first argument should be an array");return g.reduce(function(y,_){return E(y,_,p)},{})};var k=E;return et=k,et}var Er=Mr();const xt=Ie(Er);function Tr(r){return!!r&&typeof r=="object"}function Rr(...r){const e=r.filter(Tr);return xt.all(e,{arrayMerge:(t,n)=>n})}function Ir(r){return r.replace(/[=]/g,"").replace(/\//g,"_").replace(/\+/g,"-")}class Ft{constructor(e){const t=Ir(e),n=Math.ceil(t.length/2);this.firstFactor=t.substring(0,n),this.secondFactor=t.substring(n)}getFirstFactor(){return this.firstFactor}getSecondFactor(){return this.secondFactor}}const he=-2,be=-2,$t=-1;function Cr(r){const e=[];if(r)for(let t=0;t<r.length;t++)e.push(r.readInt8(t));return e}var Ut=(r=>(r[r.DISCONNECTED=0]="DISCONNECTED",r[r.CONNECTING=1]="CONNECTING",r[r.AUTHENTICATED=2]="AUTHENTICATED",r[r.RECONNECTING=3]="RECONNECTING",r))(Ut||{}),Dt=(r=>(r[r.production=40]="production",r[r.preproduction=35]="preproduction",r[r.show=30]="show",r[r.testing=20]="testing",r))(Dt||{}),jt=(r=>(r.production="frontgate-eu.factsetdigitalsolutions.com",r.show="frontgate-eu.show.factsetdigitalsolutions.com",r))(jt||{}),Ht=(r=>(r.MAXIMUM_STRING="9223372036854775807",r.MINIMUM_STRING="-9223372036854775807",r))(Ht||{});function He(r){return r.toString().slice(0,-3)}const Gt={version:"7.0.1",package:"@factset/frontgate-js-sdk"};function Or(){const r=Ar();return{userAgent:r.userAgent,platform:r.platform,version:Gt.version,package:Gt.package,mobile:/Mobi/i.test(r.userAgent)}}function Ar(){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 Nr=r=>{const e=[18,20,9],t=n=>{for(let s=n.length;s>n.length-16;s-=2){let o=parseInt(n.substring(s-2,s),16);o>127&&(o-=256),e.push(o)}};return t(r.traceId),e.push(17),t(r.spanId),e.push(24),e.push(0),e},Sr=async(r,e)=>new Promise((t,n)=>{setTimeout(()=>{n(e)},r)}),Y=async(r,e,t)=>Promise.race([Sr(r,e),t]),qt=r=>r+Math.random()*100,Lt=6e3,X=class X{constructor(){this.headerMembers={dataset:{id_dataset:0},id_job:0,flags_r2:0,resend_counter:0,timeout:Lt,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(X.PRICE_QUALITY).find(t=>X.PRICE_QUALITY[t]===this.headerMembers.dataset.id_dataset)}setQuality(e){this.headerMembers.dataset.id_dataset=X.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 n=this.flags.indexOf(e);t&&n===-1&&this.flags.push(e),!t&&n>-1&&this.flags.splice(n,1),this.headerMembers.flags_r2=this.getFlagsValue()}getFlagsValue(){return this.flags.reduce((e,t)=>e+X.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=Nr(e))}static getDataSet(e){return Object.prototype.hasOwnProperty.call(X.PRICE_QUALITY,e)?X.PRICE_QUALITY[e]:X.PRICE_QUALITY.DLY}};X.PRICE_QUALITY={RLT:129,DLY:0,EOD:130},X.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 Ge=X;class me{constructor(e,t){this.header=new Ge,this.coreMembers={Message:e,Version:t},this.members={}}getPtlMessage(){const e={header:this.header.getPtlMessage()};return Rr(this.coreMembers,e,this.members)}}class qe{constructor(e,t){this.token=e,this.maximumIdleInterval=t}toJson(){const e=Or();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 Z=class Z extends me{constructor(e,t,n,s,o=!1){super(Z.NAME,Z.VERSION),t&&this.header.setIdUser(t),n&&this.header.setIdApplication(n),s&&this.header.setTimeout(s),this.members.flags=o?Z.FLAG_SINGLE_USAGE:0,this.members.lifetime_seconds_r2=e??Z.LIFETIME_SECONDS_DEFAULT,this.header.setFlag("no_merge")}};Z.NAME="AuthenticationTokenRequest",Z.VERSION=6,Z.LIFETIME_SECONDS_DEFAULT=-1,Z.LIFETIME_SECONDS_MAXIMUM=-2,Z.FLAG_SINGLE_USAGE=1;let Le=Z;const ke=class ke extends me{constructor(e){super(ke.NAME,ke.VERSION),this.members.id_job_subscription=e}};ke.NAME="CancelSubscriptionRequest",ke.VERSION=6;let le=ke;const ee=class ee extends me{constructor(e,t,n={},s){super(ee.NAME,ee.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(n).length>0&&(e==="POST"?this.setBody(n):this.setQuery(n)),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"?ee.METHOD.POST:ee.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===ee.METHOD.POST?ee.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(n=>{t+=String.fromCharCode(n)}),JSON.parse(t)}}};ee.NAME="HighLevelRequest",ee.VERSION=3,ee.METHOD={GET:1,POST:2};let ye=ee;const V=class V extends me{constructor(e,t,n){super(V.NAME,V.VERSION),this.members.request={headers:{values:[{key:"accept",value:"application/json"},{key:"content-type",value:"application/json"}]},protocol:{value:V.PROTOCOL.HTTPS},host:"",port:0,path:t,query:"",body:{value:[]}},this.setQuery(),this.setMethod(e),n&&this.setOptions(n)}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:V.PROTOCOL.HTTP}:{value:V.PROTOCOL.HTTPS}),e.method&&(this.members.request.method={value:V.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 n=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:n})}}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:V.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(){if(this.members.request.body?.value)return ye.ptlToJsonData(this.members.request.body.value)}};V.NAME="HTTPProxyRequest",V.VERSION=2,V.PROTOCOL={HTTP:1,HTTPS:2},V.METHOD={GET:1,POST:2,OPTIONS:3,HEAD:4,PUT:5,DELETE:6,TRACE:7,CONNECT:8};let Be=V;const _e=class _e{constructor(){this._timeAtSender=Date.now()}getPtlMessage(){return{Message:_e.NAME,Version:_e.VERSION,time_at_sender:{microseconds:this._timeAtSender*1e3}}}resetTimeAtSender(){this._timeAtSender=Date.now()}get timeAtSender(){return this._timeAtSender}};_e.NAME="PingRequest",_e.VERSION=3;let Ve=_e;class Bt extends me{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=xt(this.members,e)}}class fe{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 Vt extends fe{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(He(this.raw.expiry.microseconds),10)}getToken(){return this.token}getExpiry(){return this.expiry}}class z extends fe{get reason(){return this.raw.details}get jobId(){return this.raw.id_job}}class Wt extends fe{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 Jt extends fe{constructor(e){super(e);try{const t=this.raw.response.body.value,n=t.substr(0,1)==="{";this.responseData=n?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}}}const Me=class Me{constructor(e){if(e.Message!==Me.NAME)throw new Error(`Unsupported message=${e.Message}`);if(e.Version!==Me.VERSION)throw new Error(`Unsupported version=${e.Version} for message=${e.Message}`);this._timeReceivedResponse=Date.now(),this._timeAtSender=Number(He(e.time_at_sender.microseconds)),this._timeFromRequest=Number(He(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}};Me.NAME="Foundation::PingResponse",Me.VERSION=2;let We=Me;class tt extends fe{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}}const rt=8;var d=(r=>(r[r.TRACE=10]="TRACE",r[r.DEBUG=20]="DEBUG",r[r.INFO=30]="INFO",r[r.WARN=40]="WARN",r[r.ERROR=50]="ERROR",r[r.FATAL=60]="FATAL",r[r.SILENT=100]="SILENT",r))(d||{});const ue=class ue{constructor(e=""){this.defaultLevel=40,this.noop=()=>null,this.name=e,this.setDefaultLevelFromLocalStorage(),Object.assign(ue.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 n=localStorage.getItem("loglevel");if(!n)return;e=n}catch{return}e&&this.setLevel(ue.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(ue.loggers,e))return ue.loggers[e];const n=new t(e);return ue.loggers[e]=n,n}};ue.loggers={};let ie=ue;class Pr{static getLogLevel(e){const t=e.toLowerCase();switch(t){case"silent":return d.SILENT;case"fatal":return d.FATAL;case"error":return d.ERROR;case"warn":return d.WARN;case"info":return d.INFO;case"debug":return d.DEBUG;case"trace":return d.TRACE;default:throw new Error(`Invalid log level: ${t}`)}}}class nt extends ie{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,n=this.name?`${this.name}: [${e.toUpperCase()}] `:`-----> [${e.toUpperCase()}] `;return Function.prototype.bind.call(console[t],console,n)}return this.noop}static getLogger(e=""){return super.getLogger(e,nt)}}const xr={silent:0,fatal:1,error:2,warn:3,info:4,debug:5,trace:6};class Fr extends ie{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=d[e].toLowerCase())}static getLogger(e=""){return Object.prototype.hasOwnProperty.call(ie.loggers,e)?ie.loggers[e]:null}}class st extends ie{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,st)}}const $r=()=>H(e=>class extends e{async requestAuthenticationToken(t=30,n=0,s=0,o=this.defaultTimeoutInMs){const c={message:new Le(t,n,s,o).getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",c);const a=new Promise((u,h)=>{this.hooks.hookOnce(`frontgateConnection:response:${c.callbackId}`,v=>{if(!v.Message.includes("AuthenticationTokenResponse")){h(JSON.stringify(v));return}const w=new Vt(v);u({token:w.getToken(),expiry:w.getExpiry()})})}),f=`Request timeout reached (${o} ms) for ${c.message.Message}`;return Y(o,f,a)}async requestAuthenticationTokenForCookieTokenAuthentication(t=30,n=0,s=0,o=this.defaultTimeoutInMs){const i=await this.requestAuthenticationToken(t,n,s,o);return new Ft(i.token)}},{featureName:"AuthTokenRequest",featureGroups:["Misc"]}),Ur=r=>H(t=>class extends t{async requestEndpoint(n,s,o,i,c=this.defaultTimeoutInMs){const a=new ye(n,s,o,{...i,allowChunkedResponse:!r?.disableChunkedResponse});a.header.setTimeout(c),r?.allowPermissionDeniedResponse&&a.header.setFlag("permission_denied_response");const f={message:a.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",f);const u=new Promise((v,w)=>{const M=[],E=()=>{this.hooks.hookOnce(`frontgateConnection:response:${f.callbackId}`,k=>{try{if(!k.Message.includes("HighLevelResponse")){w(JSON.stringify(k));return}if(this.#e(k))M.push({body:k.body?.value??"",processingTime:k.header?.processingTime??0}),E();else{M.push({body:k.body?.value??"",processingTime:k.header?.processingTime??0});const l=new Wt({...k,body:{value:M.map(g=>g.body).join("")},header:{...k.header,processingTime:M.reduce((g,p)=>g+p.processingTime,0)}});v({response:l,data:l.data})}}catch(l){w(l)}})};E()}),h=`Request timeout reached (${c} ms) for ${f.message.Message}`;return Y(c,h,u)}#e(n){return((n.header?.flags??0)&rt)===rt}},{featureName:"EndpointRequest",featureGroups:["Misc"]});var we=null;typeof WebSocket<"u"?we=WebSocket:typeof MozWebSocket<"u"?we=MozWebSocket:typeof global<"u"?we=global.WebSocket||global.MozWebSocket:typeof window<"u"?we=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(we=self.WebSocket||self.MozWebSocket);const zt=we,Kt=r=>H(t=>class extends t{#e;#t;#r="disconnected";#n;#s=0;#i;#a;get#o(){return this.#e&&this.#e.readyState<2?this.#r:"disconnected"}#c;#u=[];set conf(n){const s=this.#b(n);this.#c=s.messageBufferSize,this.#t=s}constructor(...n){super(...n),this.#i=he,this.#a=$t,r&&(this.conf=r),this.hooks.hook("frontgateConnection:setIdApp",s=>{this.#i=s}),this.hooks.hook("frontgateConnection:setIdUser",s=>{this.#a=s}),this.hooks.hook("frontgateConnection:sendMessage",s=>{if(s.callbackType==="job"){const o=this.#p(s.message);s.callbackId=`${o}`,this.#f(s.message)}if(this.#o==="connected"&&s.callbackType==="response")this.#h(s.message);else if(this.#o==="authenticated")this.#h(s.message);else{if(this.#u.length>=this.#c)throw new Error("Message buffer is full");this.#u.push(s)}}),this.hooks.hook("frontgateConnection:authenticated",()=>{if(!this.#t)throw new Error("No connection configuration set");for(this.log(d.DEBUG,"Draining message buffer");this.#u.length>0;){const s=this.#u.shift();s&&(this.#f(s.message),this.#h(s.message))}this.#n=setInterval(()=>{this.log(d.DEBUG,"Sending keepalive"),this.hooks.callHook("frontgateConnection:sendMessage",{message:this.#g(),callbackType:"response",callbackId:"KeepAliveMessage"})},this.#t.maximumIdleIntervalInS/2*1e3)}),this.hooks.hook("reconnect:attempt",async()=>{clearInterval(this.#n),this.log(d.DEBUG,"Reconnecting"),await this.hooks.callHook("frontgateConnection:reset");try{await this.connect(),await this.hooks.callHook("reconnect:success")}catch(s){this.log(d.ERROR,"Reconnect failed",s),await this.hooks.callHook("reconnect:failed",s)}})}async connect(){if(!this.#t)throw new Error("No connection configuration set");if(this.#o!=="disconnected")throw new Error("Client is already connected or is connecting right now");const{host:n,port:s,tls:o,pathPrefix:i}=this.#t;this.#r="connecting";const a=`${o?"wss":"ws"}://${n}:${s}${i??""}/ws`,f={encoding:"jsjson-v2"};await this.hooks.callHook("frontgateConnection:afterSetEncoding",f);const[u,h]=f.encoding.split("-"),w=[`${h?`${h}.`:""}ws-${u}.mdgms.com`],M={url:a,subProtocols:w};try{await this.hooks.callHook("frontgateConnection:beforeConnect",M)}catch(l){throw this.#r="disconnected",l}this.log(d.DEBUG,`Connecting to ${M.url} with subprotocols ${M.subProtocols}`);const E=new Promise((l,g)=>{if(!this.#t)throw new Error("No connection configuration set");this.#t.wsClientOptions&&typeof window>"u"?this.#e=new zt(M.url,M.subProtocols,this.#t.wsClientOptions):this.#e=new zt(M.url,M.subProtocols),this.#e.binaryType="arraybuffer";let p;this.#e.onopen=()=>{this.#r="connected",this.log(d.DEBUG,"Connected"),this.hooks.callHook("frontgateConnection:connected",this.#t).catch(g),p=this.hooks.hookOnce("frontgateConnection:authenticated",()=>{this.#r="authenticated",this.log(d.DEBUG,"Authenticated"),l()})},this.#e.onclose=y=>{p?.(),this.log(d.DEBUG,"Disconnected",y),this.#r==="connecting"||this.#r==="connected"?g(JSON.stringify(y)):this.hooks.callHook("frontgateConnection:disconnected",y),clearInterval(this.#n),this.#r="disconnected"},this.#e.onerror=y=>{p?.(),this.log(d.ERROR,"Error:",y),this.hooks.callHook("frontgateConnection:error",y),(this.#r==="connecting"||this.#r==="connected")&&g(new Error("Websocket error")),clearInterval(this.#n),this.#r="disconnected"},this.#e.onmessage=y=>{const{data:_}=y;this.log(d.DEBUG,"Received data:",_);const R={msg:_};this.hooks.callHook("frontgateConnection:afterReceiveMessage",R).then(()=>{this.log(d.DEBUG,"Received message",R.msg);const N=R.msg.toString("utf-8"),T=JSON.parse(N);if(this.hooks.callHook("frontgateConnection:message",T),T.Message==="Foundation::DisconnectionMessage"){this.#e?.close(),this.hooks.callHook("frontgateConnection:disconnected",T);return}this.#l(T)})}}),k=`Timeout reached (${this.defaultTimeoutInMs} ms) for connection to ${a}`;return Y(this.defaultTimeoutInMs,k,E)}async disconnect(){return new Promise(n=>{this.#h(this.#d()),this.hooks.hookOnce("frontgateConnection:disconnected",()=>{this.#e?.close(),n()})})}#d(){return{Message:"Foundation::DisconnectionMessage",Version:3,reason:{value:64},details:"client shutdown"}}#g(){return{Message:"KeepAliveMessage",Version:2}}async#h(n){await this.hooks.callHook("frontgateConnection:beforeSerializeMessage",n);const s={msg:JSON.stringify(n)};await this.hooks.callHook("frontgateConnection:beforeSendMessage",s),this.log(d.DEBUG,"Sending message:",n),this.log(d.TRACE,"Sending data:",s.msg);try{this.#e?.send(s.msg)}catch(o){const i=this.#v(o,n);this.#l(i.msg)}}#l(n){if(typeof n.header?.id_job<"u"){this.hooks.callHook(`frontgateConnection:response:${n.header.id_job}`,n);return}if(typeof n.header?.id_service<"u"&&typeof n.id_notation<"u"){this.hooks.callHook(`frontgateConnection:response:${n.header.id_service}-${n.id_notation}`,n);return}if(typeof n.id_job<"u"){this.hooks.callHook(`frontgateConnection:response:${n.id_job}`,n);return}typeof n.Message=="string"&&this.hooks.callHook(`frontgateConnection:response:${n.Message.replace("Foundation::","")}`,n)}#p(n){this.#s+=1;const s=this.#s;return n.header={...n.header,id_job:s},this.#s}#f(n){n.header||(n.header={authentication_identifiers:{id_application:void 0,id_user:void 0}}),n.header.authentication_identifiers||(n.header={...n.header,authentication_identifiers:{id_application:void 0,id_user:void 0}}),n.header.authentication_identifiers.id_application||=this.#i,n.header.authentication_identifiers.id_user||=this.#a}#v(n,s){return new z({Message:"Foundation::ErrorResponse",Version:1,id_job:s.header?.id_job,reason:8,details:n})}#b(n){const s=n.maximumIdleIntervalInS??60,o=n.maximumIdleInterval??s*1e6;return{...n,payloadContent:n.payloadContent??"foundation",maximumIdleIntervalInS:s,maximumIdleInterval:o,tls:n.tls??!0,messageBufferSize:n.messageBufferSize??512}}isConnected(){return this.#o==="authenticated"}isDisconnected(){return this.#r!=="authenticated"}isReadyToConnect(){return this.#o==="disconnected"}},{featureName:"WSConnection",disabledFeatureGroups:["Connection"]}),Dr=(r,e)=>(e&&r.setLevel(e),H(n=>class extends n{constructor(...s){super(...s),this.logger=r}},{featureName:"Logger",featureGroups:["Misc"]}));var P=Uint8Array,L=Uint16Array,ot=Int32Array,Je=new P([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]),ze=new P([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]),it=new P([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Yt=function(r,e){for(var t=new L(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];for(var s=new ot(t[30]),n=1;n<30;++n)for(var o=t[n];o<t[n+1];++o)s[o]=o-t[n]<<5|n;return{b:t,r:s}},Qt=Yt(Je,2),Xt=Qt.b,at=Qt.r;Xt[28]=258,at[258]=28;for(var Zt=Yt(ze,0),jr=Zt.b,er=Zt.r,ct=new L(32768),A=0;A<32768;++A){var ae=(A&43690)>>1|(A&21845)<<1;ae=(ae&52428)>>2|(ae&13107)<<2,ae=(ae&61680)>>4|(ae&3855)<<4,ct[A]=((ae&65280)>>8|(ae&255)<<8)>>1}for(var te=(function(r,e,t){for(var n=r.length,s=0,o=new L(e);s<n;++s)r[s]&&++o[r[s]-1];var i=new L(e);for(s=1;s<e;++s)i[s]=i[s-1]+o[s-1]<<1;var c;if(t){c=new L(1<<e);var a=15-e;for(s=0;s<n;++s)if(r[s])for(var f=s<<4|r[s],u=e-r[s],h=i[r[s]-1]++<<u,v=h|(1<<u)-1;h<=v;++h)c[ct[h]>>a]=f}else for(c=new L(n),s=0;s<n;++s)r[s]&&(c[s]=ct[i[r[s]-1]++]>>15-r[s]);return c}),ce=new P(288),A=0;A<144;++A)ce[A]=8;for(var A=144;A<256;++A)ce[A]=9;for(var A=256;A<280;++A)ce[A]=7;for(var A=280;A<288;++A)ce[A]=8;for(var Ce=new P(32),A=0;A<32;++A)Ce[A]=5;var Hr=te(ce,9,0),Gr=te(ce,9,1),qr=te(Ce,5,0),Lr=te(Ce,5,1),ut=function(r){for(var e=r[0],t=1;t<r.length;++t)r[t]>e&&(e=r[t]);return e},Q=function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},ht=function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},lt=function(r){return(r+7)/8|0},de=function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new P(r.subarray(e,t))},Br=["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"],F=function(r,e,t){var n=new Error(e||Br[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,F),!t)throw n;return n},Vr=function(r,e,t,n){var s=r.length,o=0;if(!s||e.f&&!e.l)return t||new P(0);var i=!t,c=i||e.i!=2,a=e.i;i&&(t=new P(s*3));var f=function(De){var je=t.length;if(De>je){var Re=new P(Math.max(je*2,De));Re.set(t),t=Re}},u=e.f||0,h=e.p||0,v=e.b||0,w=e.l,M=e.d,E=e.m,k=e.n,l=s*8;do{if(!w){u=Q(r,h,1);var g=Q(r,h+1,3);if(h+=3,g)if(g==1)w=Gr,M=Lr,E=9,k=5;else if(g==2){var R=Q(r,h,31)+257,N=Q(r,h+10,15)+4,T=R+Q(r,h+5,31)+1;h+=14;for(var m=new P(T),I=new P(19),C=0;C<N;++C)I[it[C]]=Q(r,h+C*3,7);h+=N*3;for(var O=ut(I),U=(1<<O)-1,q=te(I,O,1),C=0;C<T;){var $=q[Q(r,h,U)];h+=$&15;var p=$>>4;if(p<16)m[C++]=p;else{var D=0,S=0;for(p==16?(S=3+Q(r,h,3),h+=2,D=m[C-1]):p==17?(S=3+Q(r,h,7),h+=3):p==18&&(S=11+Q(r,h,127),h+=7);S--;)m[C++]=D}}var j=m.subarray(0,R),G=m.subarray(R);E=ut(j),k=ut(G),w=te(j,E,1),M=te(G,k,1)}else F(1);else{var p=lt(h)+4,y=r[p-4]|r[p-3]<<8,_=p+y;if(_>s){a&&F(0);break}c&&f(v+y),t.set(r.subarray(p,_),v),e.b=v+=y,e.p=h=_*8,e.f=u;continue}if(h>l){a&&F(0);break}}c&&f(v+131072);for(var Ue=(1<<E)-1,K=(1<<k)-1,oe=h;;oe=h){var D=w[ht(r,h)&Ue],W=D>>4;if(h+=D&15,h>l){a&&F(0);break}if(D||F(2),W<256)t[v++]=W;else if(W==256){oe=h,w=null;break}else{var J=W-254;if(W>264){var C=W-257,x=Je[C];J=Q(r,h,(1<<x)-1)+Xt[C],h+=x}var ne=M[ht(r,h)&K],Ee=ne>>4;ne||F(3),h+=ne&15;var G=jr[Ee];if(Ee>3){var x=ze[Ee];G+=ht(r,h)&(1<<x)-1,h+=x}if(h>l){a&&F(0);break}c&&f(v+131072);var Te=v+J;if(v<G){var Xe=o-G,Ze=Math.min(G,Te);for(Xe+v<0&&F(3);v<Ze;++v)t[v]=n[Xe+v]}for(;v<Te;++v)t[v]=t[v-G]}}e.l=w,e.p=oe,e.b=v,e.f=u,w&&(u=1,e.m=E,e.d=M,e.n=k)}while(!u);return v!=t.length&&i?de(t,0,v):t.subarray(0,v)},se=function(r,e,t){t<<=e&7;var n=e/8|0;r[n]|=t,r[n+1]|=t>>8},Oe=function(r,e,t){t<<=e&7;var n=e/8|0;r[n]|=t,r[n+1]|=t>>8,r[n+2]|=t>>16},ft=function(r,e){for(var t=[],n=0;n<r.length;++n)r[n]&&t.push({s:n,f:r[n]});var s=t.length,o=t.slice();if(!s)return{t:sr,l:0};if(s==1){var i=new P(t[0].s+1);return i[t[0].s]=1,{t:i,l:1}}t.sort(function(_,R){return _.f-R.f}),t.push({s:-1,f:25001});var c=t[0],a=t[1],f=0,u=1,h=2;for(t[0]={s:-1,f:c.f+a.f,l:c,r:a};u!=s-1;)c=t[t[f].f<t[h].f?f++:h++],a=t[f!=u&&t[f].f<t[h].f?f++:h++],t[u++]={s:-1,f:c.f+a.f,l:c,r:a};for(var v=o[0].s,n=1;n<s;++n)o[n].s>v&&(v=o[n].s);var w=new L(v+1),M=dt(t[u-1],w,0);if(M>e){var n=0,E=0,k=M-e,l=1<<k;for(o.sort(function(R,N){return w[N.s]-w[R.s]||R.f-N.f});n<s;++n){var g=o[n].s;if(w[g]>e)E+=l-(1<<M-w[g]),w[g]=e;else break}for(E>>=k;E>0;){var p=o[n].s;w[p]<e?E-=1<<e-w[p]++-1:++n}for(;n>=0&&E;--n){var y=o[n].s;w[y]==e&&(--w[y],++E)}M=e}return{t:new P(w),l:M}},dt=function(r,e,t){return r.s==-1?Math.max(dt(r.l,e,t+1),dt(r.r,e,t+1)):e[r.s]=t},tr=function(r){for(var e=r.length;e&&!r[--e];);for(var t=new L(++e),n=0,s=r[0],o=1,i=function(a){t[n++]=a},c=1;c<=e;++c)if(r[c]==s&&c!=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=r[c]}return{c:t.subarray(0,n),n:e}},Ae=function(r,e){for(var t=0,n=0;n<e.length;++n)t+=r[n]*e[n];return t},rr=function(r,e,t){var n=t.length,s=lt(e+2);r[s]=n&255,r[s+1]=n>>8,r[s+2]=r[s]^255,r[s+3]=r[s+1]^255;for(var o=0;o<n;++o)r[s+o+4]=t[o];return(s+4+n)*8},nr=function(r,e,t,n,s,o,i,c,a,f,u){se(e,u++,t),++s[256];for(var h=ft(s,15),v=h.t,w=h.l,M=ft(o,15),E=M.t,k=M.l,l=tr(v),g=l.c,p=l.n,y=tr(E),_=y.c,R=y.n,N=new L(19),T=0;T<g.length;++T)++N[g[T]&31];for(var T=0;T<_.length;++T)++N[_[T]&31];for(var m=ft(N,7),I=m.t,C=m.l,O=19;O>4&&!I[it[O-1]];--O);var U=f+5<<3,q=Ae(s,ce)+Ae(o,Ce)+i,$=Ae(s,v)+Ae(o,E)+i+14+3*O+Ae(N,I)+2*N[16]+3*N[17]+7*N[18];if(a>=0&&U<=q&&U<=$)return rr(e,u,r.subarray(a,a+f));var D,S,j,G;if(se(e,u,1+($<q)),u+=2,$<q){D=te(v,w,0),S=v,j=te(E,k,0),G=E;var Ue=te(I,C,0);se(e,u,p-257),se(e,u+5,R-1),se(e,u+10,O-4),u+=14;for(var T=0;T<O;++T)se(e,u+3*T,I[it[T]]);u+=3*O;for(var K=[g,_],oe=0;oe<2;++oe)for(var W=K[oe],T=0;T<W.length;++T){var J=W[T]&31;se(e,u,Ue[J]),u+=I[J],J>15&&(se(e,u,W[T]>>5&127),u+=W[T]>>12)}}else D=Hr,S=ce,j=qr,G=Ce;for(var T=0;T<c;++T){var x=n[T];if(x>255){var J=x>>18&31;Oe(e,u,D[J+257]),u+=S[J+257],J>7&&(se(e,u,x>>23&31),u+=Je[J]);var ne=x&31;Oe(e,u,j[ne]),u+=G[ne],ne>3&&(Oe(e,u,x>>5&8191),u+=ze[ne])}else Oe(e,u,D[x]),u+=S[x]}return Oe(e,u,D[256]),u+S[256]},Wr=new ot([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),sr=new P(0),Jr=function(r,e,t,n,s,o){var i=o.z||r.length,c=new P(n+i+5*(1+Math.ceil(i/7e3))+s),a=c.subarray(n,c.length-s),f=o.l,u=(o.r||0)&7;if(e){u&&(a[0]=o.r>>3);for(var h=Wr[e-1],v=h>>13,w=h&8191,M=(1<<t)-1,E=o.p||new L(32768),k=o.h||new L(M+1),l=Math.ceil(t/3),g=2*l,p=function(St){return(r[St]^r[St+1]<<l^r[St+2]<<g)&M},y=new ot(25e3),_=new L(288),R=new L(32),N=0,T=0,m=o.i||0,I=0,C=o.w||0,O=0;m+2<i;++m){var U=p(m),q=m&32767,$=k[U];if(E[q]=$,k[U]=q,C<=m){var D=i-m;if((N>7e3||I>24576)&&(D>423||!f)){u=nr(r,a,0,y,_,R,T,I,O,m-O,u),I=N=T=0,O=m;for(var S=0;S<286;++S)_[S]=0;for(var S=0;S<30;++S)R[S]=0}var j=2,G=0,Ue=w,K=q-$&32767;if(D>2&&U==p(m-K))for(var oe=Math.min(v,D)-1,W=Math.min(32767,m),J=Math.min(258,D);K<=W&&--Ue&&q!=$;){if(r[m+j]==r[m+j-K]){for(var x=0;x<J&&r[m+x]==r[m+x-K];++x);if(x>j){if(j=x,G=K,x>oe)break;for(var ne=Math.min(K,x-2),Ee=0,S=0;S<ne;++S){var Te=m-K+S&32767,Xe=E[Te],Ze=Te-Xe&32767;Ze>Ee&&(Ee=Ze,$=Te)}}}q=$,$=E[q],K+=q-$&32767}if(G){y[I++]=268435456|at[j]<<18|er[G];var De=at[j]&31,je=er[G]&31;T+=Je[De]+ze[je],++_[257+De],++R[je],C=m+j,++N}else y[I++]=r[m],++_[r[m]]}}for(m=Math.max(m,C);m<i;++m)y[I++]=r[m],++_[r[m]];u=nr(r,a,f,y,_,R,T,I,O,m-O,u),f||(o.r=u&7|a[u/8|0]<<3,u-=7,o.h=k,o.p=E,o.i=m,o.w=C)}else{for(var m=o.w||0;m<i+f;m+=65535){var Re=m+65535;Re>=i&&(a[u/8|0]=f,Re=i),u=rr(a,u+1,r.subarray(m,Re))}o.i=i}return de(c,0,n+lt(u)+s)},or=function(){var r=1,e=0;return{p:function(t){for(var n=r,s=e,o=t.length|0,i=0;i!=o;){for(var c=Math.min(i+2655,o);i<c;++i)s+=n+=t[i];n=(n&65535)+15*(n>>16),s=(s&65535)+15*(s>>16)}r=n,e=s},d:function(){return r%=65521,e%=65521,(r&255)<<24|(r&65280)<<8|(e&255)<<8|e>>8}}},ir=function(r,e,t,n,s){if(!s&&(s={l:1},e.dictionary)){var o=e.dictionary.subarray(-32768),i=new P(o.length+r.length);i.set(o),i.set(r,o.length),r=i,s.w=o.length}return Jr(r,e.level==null?6:e.level,e.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(r.length)))*1.5):20:12+e.mem,t,n,s)},ar=function(r,e,t){for(;t;++e)r[e]=t,t>>>=8},zr=function(r,e){var t=e.level,n=t==0?0:t<6?1:t==9?3:2;if(r[0]=120,r[1]=n<<6|(e.dictionary&&32),r[1]|=31-(r[0]<<8|r[1])%31,e.dictionary){var s=or();s.p(e.dictionary),ar(r,2,s.d())}},Kr=function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&F(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&F(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2},gt=(function(){function r(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 P(98304),this.o.dictionary){var n=this.o.dictionary.subarray(-32768);this.b.set(n,32768-n.length),this.s.i=32768-n.length}}return r.prototype.p=function(e,t){this.ondata(ir(e,this.o,0,0,this.s),t)},r.prototype.push=function(e,t){this.ondata||F(5),this.s.l&&F(4);var n=e.length+this.s.z;if(n>this.b.length){if(n>2*this.b.length-32768){var s=new P(n&-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)},r.prototype.flush=function(){this.ondata||F(5),this.s.l&&F(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2},r})(),pt=(function(){function r(e,t){typeof e=="function"&&(t=e,e={}),this.ondata=t;var n=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new P(32768),this.p=new P(0),n&&this.o.set(n)}return r.prototype.e=function(e){if(this.ondata||F(5),this.d&&F(4),!this.p.length)this.p=e;else if(e.length){var t=new P(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}},r.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,n=Vr(this.p,this.s,this.o);this.ondata(de(n,t,this.s.b),this.d),this.o=de(n,this.s.b-32768),this.s.b=this.o.length,this.p=de(this.p,this.s.p/8|0),this.s.p&=7},r.prototype.push=function(e,t){this.e(e),this.c(t)},r})(),Yr=(function(){function r(e,t){this.c=or(),this.v=1,gt.call(this,e,t)}return r.prototype.push=function(e,t){this.c.p(e),gt.prototype.push.call(this,e,t)},r.prototype.p=function(e,t){var n=ir(e,this.o,this.v&&(this.o.dictionary?6:2),t&&4,this.s);this.v&&(zr(n,this.o),this.v=0),t&&ar(n,n.length-4,this.c.d()),this.ondata(n,t)},r.prototype.flush=function(){gt.prototype.flush.call(this)},r})(),Qr=(function(){function r(e,t){pt.call(this,e,t),this.v=e&&e.dictionary?2:1}return r.prototype.push=function(e,t){if(pt.prototype.e.call(this,e),this.v){if(this.p.length<6&&!t)return;this.p=this.p.subarray(Kr(this.p,this.v-1)),this.v=0}t&&(this.p.length<4&&F(6,"invalid zlib data"),this.p=this.p.subarray(0,-4)),pt.prototype.c.call(this,t)},r})(),cr=typeof TextEncoder<"u"&&new TextEncoder,vt=typeof TextDecoder<"u"&&new TextDecoder,Xr=0;try{vt.decode(sr,{stream:!0}),Xr=1}catch{}var Zr=function(r){for(var e="",t=0;;){var n=r[t++],s=(n>127)+(n>223)+(n>239);if(t+s>r.length)return{s:e,r:de(r,t-1)};s?s==3?(n=((n&15)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,e+=String.fromCharCode(55296|n>>10,56320|n&1023)):s&1?e+=String.fromCharCode((n&31)<<6|r[t++]&63):e+=String.fromCharCode((n&15)<<12|(r[t++]&63)<<6|r[t++]&63):e+=String.fromCharCode(n)}};function en(r,e){var t;if(cr)return cr.encode(r);for(var n=r.length,s=new P(r.length+(r.length>>1)),o=0,i=function(f){s[o++]=f},t=0;t<n;++t){if(o+5>s.length){var c=new P(o+8+(n-t<<1));c.set(s),s=c}var a=r.charCodeAt(t);a<128||e?i(a):a<2048?(i(192|a>>6),i(128|a&63)):a>55295&&a<57344?(a=65536+(a&1047552)|r.charCodeAt(++t)&1023,i(240|a>>18),i(128|a>>12&63),i(128|a>>6&63),i(128|a&63)):(i(224|a>>12),i(128|a>>6&63),i(128|a&63))}return de(s,0,o)}function tn(r,e){var t;if(vt)return vt.decode(r);var n=Zr(r),s=n.s,t=n.r;return t.length&&F(8),s}const rn=r=>{if(r.length===1)return r[0];const e=new Uint8Array(r.reduce((t,n)=>t+n.length,0));for(let t=0,n=0;t<r.length;++t)e.set(r[t],n),n+=r[t].length;return e};class nn{constructor(){this.reset()}reset(){this.compressor=null,this.decompressor=null}compress(e){this.compressor||(this.compressor=new Yr({mem:4}));const t=[];return this.compressor.ondata=n=>{t.push(n)},this.compressor.push(en(e)),this.compressor.flush(),rn(t)}decompress(e){this.decompressor||(this.decompressor=new Qr);let t;this.decompressor.ondata=n=>{t=n};try{if(this.decompressor.push(e),t===void 0)throw new Error("invalid block type")}catch(n){throw new Error(`Decompression error: ${n.message}, length: ${e.length}, data: [${e.toString()}]`)}return tn(t)}}const sn=()=>H(e=>class extends e{#e;constructor(...t){super(...t),this.#e=new nn,this.hooks.hook("frontgateConnection:reset",()=>{this.#e.reset()}),this.hooks.hook("frontgateConnection:afterSetEncoding",n=>{n.encoding="jsjsonc-v2"}),this.hooks.hook("frontgateConnection:beforeSendMessage",n=>{const s=this.#e.compress(n.msg);n.msg=s}),this.hooks.hook("frontgateConnection:afterReceiveMessage",n=>{const s=this.#e.decompress(new Uint8Array(n.msg));n.msg=s})}},{featureName:"MessageCompressor",featureGroups:["Misc"]}),on=()=>H(e=>class extends e{async request(t,n=this.defaultTimeoutInMs){t.header.setTimeout(n);const s={message:t.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",s);const o=new Promise(c=>{this.hooks.hookOnce(`frontgateConnection:response:${s.callbackId}`,a=>{const f=new fe(a);c(f)})}),i=`Request timeout reached (${n} ms) for ${s.message.Message}`;return Y(n,i,o)}},{featureName:"Request",featureGroups:["Misc"]}),an=r=>H(t=>{const n={...r};return class extends t{#e=new Map;#t=new Map;#r=new Map;async observeEndpoint(s,o,i,c){const a=`${s}:${o}:${JSON.stringify(i)}:${JSON.stringify(c??{})}`;if(this.#r.has(a)){const k=this.#r.get(a);this.log(d.INFO,`Catching inflight subscription for ${a}`);const l=this.#t.get(a)??0;return this.#t.set(a,l+1),k}const f=n.timeout??this.defaultTimeoutInMs,u=n.subscriptionResubscribeTimeout??1e3;if(this.#e.has(a)){const k=this.#e.get(a),l=this.#t.get(a)??0;if(k)return this.#t.set(a,l+1),this.log(d.INFO,`Reusing existing subscription for ${a}`),k}this.log(d.INFO,`Creating new subscription for ${a}`);const h=new ye(s,o,i,{...c,subscribe:!0});h.header.setTimeout(f);const v={message:h.getPtlMessage(),callbackType:"job",callbackId:""},w=new Promise((k,l)=>{this.hooks.callHook("frontgateConnection:sendMessage",v).then(()=>{this.hooks.hookOnce(`frontgateConnection:response:${v.callbackId}`,g=>{if(!g.Message.includes("HighLevelResponse")){this.log(d.ERROR,`Unexpected response: ${g.Message}`),l(new z(JSON.stringify(g)));return}let p;try{p=JSON.parse(g.body.value)}catch(m){this.log(d.ERROR,`Failed to parse response: ${g.body.value}`),this.log(d.ERROR,m),l(m);return}const y=new ur(g.header.id_job,p);let _=this.hooks.hook(`frontgateConnection:response:${v.callbackId}`,m=>{if(!m.Message.includes("HighLevelUpdate")){if(m.Message.includes("SubscriptionLoss")){this.log(d.DEBUG,`Received: ${m.Message}`),setTimeout(()=>{R()},qt(u)),_();return}this.log(d.ERROR,`Unexpected response: ${g.Message}`),y.pushError(new z(JSON.stringify(m))),_();return}let I;try{I=new tt(m)}catch(C){this.log(d.ERROR,`Failed to parse response: ${m.body.value}`),y.pushError(C);return}y.pushPatchData(I.data)});const R=async()=>{_(),this.log(d.INFO,`Resubscribing to ${a} due to reconnect`),await this.hooks.callHook("frontgateConnection:sendMessage",v);const m=new Promise((I,C)=>{this.hooks.hookOnce(`frontgateConnection:response:${v.callbackId}`,O=>{if(!g.Message.includes("HighLevelResponse")){const U=new z(O);this.log(d.ERROR,`Unexpected response: ${O.Message}`),_(),C(U);return}this.log(d.INFO,`Resubscribed to ${a} with ${O.header.id_job}`),y.idJob=O.header.id_job,_=this.hooks.hook(`frontgateConnection:response:${O.header.id_job}`,U=>{if(!U.Message.includes("HighLevelUpdate")){if(U.Message.includes("SubscriptionLoss")){this.log(d.DEBUG,`Received: ${U.Message}`),setTimeout(()=>{R()},qt(u));return}this.log(d.ERROR,`Unexpected response: ${U.Message}`);const $=new z(U);y.pushError($);return}let q;try{q=new tt(U)}catch($){this.log(d.ERROR,`Failed to parse response: ${U.body.value}`),y.pushError($);return}y.unsubscribe=()=>{if(this.#e.get(a)){const j=this.#t.get(a)??0;if(this.#t.set(a,j-1),j-1>0){this.log(d.INFO,`Not unsubscribing from ${a} as there are still ${j} subscribers`);return}this.#e.delete(a),this.#t.delete(a)}this.log(d.INFO,`Unsubscribing from ${a}`);const S={message:new le(y.idJob).getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",S),_(),N()},y.pushPatchData(q.data)}),I()})});try{await Y(f,"Request timeout reached",m)}catch(I){y.pushError(new z({Message:"Reconnect failed",Error:I}))}},N=this.hooks.hook("reconnect:success",R);y.unsubscribe=()=>{if(this.#e.get(a)){const O=this.#t.get(a)??0;if(this.#t.set(a,O-1),O-1>0){this.log(d.INFO,`Not unsubscribing from ${a} as there are still ${O} subscribers`);return}this.#e.delete(a),this.#t.delete(a)}this.log(d.INFO,`Unsubscribing from ${a}`);const C={message:new le(y.idJob).getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",C),_(),N()},this.#e.set(a,y);const T=this.#t.get(a)??0;this.#t.set(a,T+1),this.#r.delete(a),k(y)})}).catch(g=>{l(g)})}),M=`Request timeout reached (${f} ms) for ${v.message.Message}`,E=Y(f,M,w);return this.#r.set(a,E),E}}},{featureName:"EndpointSubscriptions",featureGroups:["Misc"]}),cn=()=>H(e=>class extends e{#e=new Map;async observe(t,n=this.defaultTimeoutInMs){return this.#t(t,"job",void 0,n)}async observeConnectionBased(t,n,s=this.defaultTimeoutInMs){return this.#t(t,"connection",n,s)}async#t(t,n,s,o=this.defaultTimeoutInMs){const i=JSON.stringify(t.getPtlMessage());if(this.#e.has(i)){const h=this.#e.get(i);if(h)return h.count++,this.log(d.INFO,`Reusing existing subscription for ${i}`),h.observer}this.log(d.INFO,`Creating new subscription for ${i}`);const a={message:t.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",a);const f=new Promise((h,v)=>{this.hooks.hookOnce(`frontgateConnection:response:${a.callbackId}`,w=>{if(w.Message.includes("Error")||w.Message.includes("PermissionDenied")){this.log(d.ERROR,`Unexpected response: ${w.Message}`),v(new Error(`Unexpected response: ${w.Message}`));return}const M=n==="connection"?`${w.header.id_service}-${t.getPtlMessage().id_notation}`:w.header.id_job,E=typeof s>"u"?new le(w.header.id_job):new s(w.header.id_service,t.getPtlMessage().id_notation),k=new mt(w.header.id_job,w);let l=this.hooks.hook(`frontgateConnection:response:${M}`,p=>{if(p.Message.includes("Error")||p.Message.includes("PermissionDenied")){this.log(d.ERROR,`Unexpected response: ${w.Message}`),k.pushError(new z(JSON.stringify(p)));return}k.pushData(p)});const g=this.hooks.hook("reconnect:success",async()=>{l(),this.log(d.INFO,`Resubscribing to ${i} due to reconnect`),await this.hooks.callHook("frontgateConnection:sendMessage",a);const p=new Promise((y,_)=>{this.hooks.hookOnce(`frontgateConnection:response:${a.callbackId}`,R=>{if(R.Message.includes("Error")||R.Message.includes("PermissionDenied")){const m=new z(R);this.log(d.ERROR,`Unexpected resp: ${R.Message}`),_(m);return}const N=n==="connection"?`${R.header.id_service}-${t.getPtlMessage().id_notation}`:R.header.id_job,T=typeof s>"u"?new le(R.header.id_job):new s(R.header.id_service,t.getPtlMessage().id_notation);k.idJob=R.header.id_job,l=this.hooks.hook(`frontgateConnection:response:${N}`,m=>{if(m.Message.includes("Error")||m.Message.includes("PermissionDenied")){this.log(d.ERROR,`Unexpected response: ${m.Message}`);const I=new z(m);k.pushError(I);return}k.unsubscribe=()=>{const I=this.#e.get(i);if(I){if(I.count--,I.count>0){this.log(d.INFO,`Not unsubscribing from ${i} as there are still ${I.count} subscribers`);return}this.#e.delete(i)}this.log(d.INFO,`Unsubscribing from ${i}`);const C={message:T.getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",C),l(),g()},k.pushData(m)}),y()})});try{await Y(o,"Request timeout reached",p)}catch(y){k.pushError(new z({Message:"Reconnect failed",Error:y}))}});k.unsubscribe=()=>{const p=this.#e.get(i);if(p){if(p.count--,p.count>0){this.log(d.INFO,`Not unsubscribing from ${i} as there are still ${p.count} subscribers`);return}this.#e.delete(i)}this.log(d.INFO,`Unsubscribing from ${i}`);const y={message:E.getPtlMessage(),callbackType:"job",callbackId:""};this.hooks.callHook("frontgateConnection:sendMessage",y),l(),g()},this.#e.set(i,{observer:k,count:1}),h(k)})}),u=`Request timeout reached (${o} ms) for ${a.message.Message}`;return Y(o,u,f)}},{featureName:"RawSubscriptions",featureGroups:["Misc"]}),bt=(r,e)=>{const t=e.split("/").slice(1);let n=r;for(let s=0;s<t.length-1;s++){const o=decodeURIComponent(t[s]);if(!(o in n))throw new Error(`Path not found: ${e}`);n=n[o]}return[n,decodeURIComponent(t[t.length-1])]},un=(r,e,t)=>{const[n,s]=bt(r,e);n[s]=t},hn="-",ln=(r,e,t)=>{const[n,s]=bt(r,e);Array.isArray(n)?s===hn?n.push(t):n.splice(parseInt(s,10),0,t):n[s]=t},fn=(r,e)=>{const[t,n]=bt(r,e);Array.isArray(t)?t.splice(parseInt(n,10),1):delete t[n]};function dn(r,e){return e.forEach(t=>{switch(t.op){case"replace":un(r,t.path,t.value);break;case"add":ln(r,t.path,t.value);break;case"remove":fn(r,t.path);break;case"move":case"copy":case"test":default:throw new Error(`Unsupported op: ${t.op}`)}}),r}class mt{#e;#t=[];#r=[];get data(){return this.#e}constructor(e,t){this.#e=t,this.idJob=e}subscribe({next:e,error:t}){e(this.#e),t&&this.#r.push(t),this.#t.push(e)}pushData(e){this.#e=e,this.#t.forEach(t=>{t(e)})}pushError(e){this.#r.forEach(t=>{t(e)})}}class ur extends mt{pushPatchData(e){try{const t=dn(this.data,e);super.pushData(t)}catch(t){super.pushError(new z(t.message))}}}const gn=r=>H(t=>class extends t{constructor(...n){super(...n),this.hooks.hook("frontgateConnection:beforeConnect",o=>{this.hooks.callHook("frontgateConnection:setIdApp",he),this.hooks.callHook("frontgateConnection:setIdUser",be),this.log(d.DEBUG,"Adding mdg2auth subprotocol"),o.subProtocols.push(`mdg2auth-${r}`)});const s=async o=>{this.hooks.callHook("frontgateConnection:setIdApp",he),this.hooks.callHook("frontgateConnection:setIdUser",be);const i={maximum_idle_interval:o.maximumIdleInterval},c={b64:""},f=new qe(c,i.maximum_idle_interval).toJson();this.log(d.INFO,"Sending message",f);const u={message:f,callbackType:"response",callbackId:f.Message.replace("Request","Response")};await this.hooks.callHook("frontgateConnection:sendMessage",u),this.hooks.hookOnce(`frontgateConnection:response:${u.callbackId}`,h=>{this.log(d.INFO,"Received response",h),this.hooks.callHook("frontgateConnection:authenticated")})};this.hooks.hookOnce("frontgateConnection:connected",s)}},{featureName:"CookieTokenAuth",featureGroups:["Auth"],disabledFeatureGroups:["Auth"]}),pn=r=>H(t=>class extends t{#e;constructor(...n){super(...n),this.#e=r??"";const s=async o=>{this.hooks.callHook("frontgateConnection:setIdApp",he),this.hooks.callHook("frontgateConnection:setIdUser",be);const i={maximum_idle_interval:o.maximumIdleInterval},c={b64:this.#e},f=new qe(c,i.maximum_idle_interval).toJson();this.log(d.INFO,"Sending message",f);const u={message:f,callbackType:"response",callbackId:f.Message.replace("Request","Response")};await this.hooks.callHook("frontgateConnection:sendMessage",u),this.hooks.hookOnce(`frontgateConnection:response:${u.callbackId}`,h=>{this.log(d.INFO,"Received response",h),this.hooks.callHook("frontgateConnection:authenticated")})};this.hooks.hook("frontgateConnection:connected",s)}set token(n){this.#e=n}},{featureName:"TokenAuth",featureGroups:["Auth"],disabledFeatureGroups:["Auth"]}),vn=(r,e,t)=>H(s=>class extends Kt({host:"",pathPrefix:"",port:0,tls:!0,maximumIdleIntervalInS:r.maximumIdleIntervalInS})(s){#e="";#t="";#r;#n;constructor(...o){super(...o),this.#r=e,this.#n=t,this.hooks.hook("frontgateConnection:beforeConnect",async c=>{this.hooks.callHook("frontgateConnection:setIdApp",he),this.hooks.callHook("frontgateConnection:setIdUser",be),this.log(d.DEBUG,"Fetching connection configuration");const a=await this.#s();if(this.log(d.DEBUG,"Connection configuration received",a),c.url=a.url,a.authtenticationType==="token"&&a.authenticationToken)this.#e=a.authenticationToken;else if(a.splitAuthenticationTokenSecondFactor)this.#t=a.splitAuthenticationTokenSecondFactor;else throw new Error("Invalid authentication configuration");this.log(d.DEBUG,"Adding mdg2auth subprotocol"),this.#t!==""&&c.subProtocols.push(`mdg2auth-${this.#t}`)});const i=async c=>{this.hooks.callHook("frontgateConnection:setIdApp",he),this.hooks.callHook("frontgateConnection:setIdUser",be);const a={maximum_idle_interval:c.maximumIdleInterval},f={b64:this.#e},h=new qe(f,a.maximum_idle_interval).toJson();this.log(d.INFO,"Sending message",h);const v={message:h,callbackType:"response",callbackId:h.Message.replace("Request","Response")};await this.hooks.callHook("frontgateConnection:sendMessage",v),this.hooks.hookOnce(`frontgateConnection:response:${v.callbackId}`,w=>{this.log(d.INFO,"Received response",w),this.hooks.callHook("frontgateConnection:authenticated")})};this.hooks.hook("frontgateConnection:connected",i)}async#s(){const o=await fetch(this.#r,this.#n);if(!o.ok)throw new Error(`Failed to fetch connection configuration: ${o.status} ${o.statusText}`);const{headers:i}=o,c=i.get("frontgate-host"),a=i.get("frontgate-path-prefix"),f=i.get("frontgate-split-authentication-token-second-factor"),u=i.get("frontgate-authentication-type"),h=i.get("frontgate-authentication-token"),v=i.get("frontgate-websocket-port")??"443",w=`wss://${c}:${v}${a??""}/ws`;if(u==="token"&&!h)throw new Error("Authentication token is required for token authentication");if(u!=="token"&&!f)throw new Error("Split authentication token second factor is required");return{url:w,authtenticationType:u,authenticationToken:h,splitAuthenticationTokenSecondFactor:f}}},{featureName:"FetchAuth",featureGroups:["Auth","Connection"],disabledFeatureGroups:["Auth","Connection"]}),bn=r=>H(t=>class extends t{#e=0;#t;#r;constructor(...n){super(...n),this.#t=r??[1e3,2e3,4e3,8e3,16e3,32e3];const s=o=>{if(o.code!==1e3){this.#r&&(this.log(d.WARN,"Aborting previous reconnect attempt"),clearTimeout(this.#r),this.#e=0);let i=this.#e;this.#e>=this.#t.length&&(i=this.#t.length-1);const c=this.#t[i];this.#r=setTimeout(()=>{this.log(d.INFO,`Reconnecting... Attempt ${this.#e}`);const a=this.hooks.hookOnce("reconnect:failed",s);this.hooks.callHook("reconnect:attempt",o).then(a).catch(()=>{this.log(d.ERROR,"Failed to reconnect")}),this.#r=void 0},c),this.#e++}};this.hooks.hookOnce("frontgateConnection:disconnected",s),this.hooks.hook("reconnect:success",()=>{clearTimeout(this.#r),this.#r=void 0,this.#e=0,this.log(d.INFO,"Reconnected"),this.hooks.hookOnce("frontgateConnection:disconnected",s)})}},{featureName:"Reconnect",featureGroups:["Misc"],disabledFeatures:["TokenAuth","CookieTokenAuth"]});var mn=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},ge="1.9.0",hr=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function yn(r){var e=new Set([r]),t=new Set,n=r.match(hr);if(!n)return function(){return!1};var s={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(s.prerelease!=null)return function(a){return a===r};function o(c){return t.add(c),!1}function i(c){return e.add(c),!0}return function(a){if(e.has(a))return!0;if(t.has(a))return!1;var f=a.match(hr);if(!f)return o(a);var u={major:+f[1],minor:+f[2],patch:+f[3],prerelease:f[4]};return u.prerelease!=null||s.major!==u.major?o(a):s.major===0?s.minor===u.minor&&s.patch<=u.patch?i(a):o(a):s.minor<=u.minor?i(a):o(a)}}var wn=yn(ge),kn=ge.split(".")[0],Ne=Symbol.for("opentelemetry.js.api."+kn),Se=mn;function Pe(r,e,t,n){var s;n===void 0&&(n=!1);var o=Se[Ne]=(s=Se[Ne])!==null&&s!==void 0?s:{version:ge};if(!n&&o[r]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+r);return t.error(i.stack||i.message),!1}if(o.version!==ge){var i=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+r+" does not match previously registered API v"+ge);return t.error(i.stack||i.message),!1}return o[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+ge+"."),!0}function pe(r){var e,t,n=(e=Se[Ne])===null||e===void 0?void 0:e.version;if(!(!n||!wn(n)))return(t=Se[Ne])===null||t===void 0?void 0:t[r]}function xe(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+ge+".");var t=Se[Ne];t&&delete t[r]}var _n=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(c){i={error:c}}finally{try{s&&!s.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},Mn=function(r,e,t){if(t||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return r.concat(o||Array.prototype.slice.call(e))},En=(function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fe("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fe("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fe("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fe("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Fe("verbose",this._namespace,e)},r})();function Fe(r,e,t){var n=pe("diag");if(n)return t.unshift(e),n[r].apply(n,Mn([],_n(t),!1))}var B;(function(r){r[r.NONE=0]="NONE",r[r.ERROR=30]="ERROR",r[r.WARN=50]="WARN",r[r.INFO=60]="INFO",r[r.DEBUG=70]="DEBUG",r[r.VERBOSE=80]="VERBOSE",r[r.ALL=9999]="ALL"})(B||(B={}));function Tn(r,e){r<B.NONE?r=B.NONE:r>B.ALL&&(r=B.ALL),e=e||{};function t(n,s){var o=e[n];return typeof o=="function"&&r>=s?o.bind(e):function(){}}return{error:t("error",B.ERROR),warn:t("warn",B.WARN),info:t("info",B.INFO),debug:t("debug",B.DEBUG),verbose:t("verbose",B.VERBOSE)}}var Rn=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(c){i={error:c}}finally{try{s&&!s.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},In=function(r,e,t){if(t||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return r.concat(o||Array.prototype.slice.call(e))},Cn="diag",re=(function(){function r(){function e(s){return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];var c=pe("diag");if(c)return c[s].apply(c,In([],Rn(o),!1))}}var t=this,n=function(s,o){var i,c,a;if(o===void 0&&(o={logLevel:B.INFO}),s===t){var f=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=f.stack)!==null&&i!==void 0?i:f.message),!1}typeof o=="number"&&(o={logLevel:o});var u=pe("diag"),h=Tn((c=o.logLevel)!==null&&c!==void 0?c:B.INFO,s);if(u&&!o.suppressOverrideMessage){var v=(a=new Error().stack)!==null&&a!==void 0?a:"<failed to generate stacktrace>";u.warn("Current logger will be overwritten from "+v),h.warn("Current logger will overwrite one already registered from "+v)}return Pe("diag",h,t,!0)};t.setLogger=n,t.disable=function(){xe(Cn,t)},t.createComponentLogger=function(s){return new En(s)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return r.instance=function(){return this._instance||(this._instance=new r),this._instance},r})(),On=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(c){i={error:c}}finally{try{s&&!s.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},An=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Nn=(function(){function r(e){this._entries=e?new Map(e):new Map}return r.prototype.getEntry=function(e){var t=this._entries.get(e);if(t)return Object.assign({},t)},r.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var t=On(e,2),n=t[0],s=t[1];return[n,s]})},r.prototype.setEntry=function(e,t){var n=new r(this._entries);return n._entries.set(e,t),n},r.prototype.removeEntry=function(e){var t=new r(this._entries);return t._entries.delete(e),t},r.prototype.removeEntries=function(){for(var e,t,n=[],s=0;s<arguments.length;s++)n[s]=arguments[s];var o=new r(this._entries);try{for(var i=An(n),c=i.next();!c.done;c=i.next()){var a=c.value;o._entries.delete(a)}}catch(f){e={error:f}}finally{try{c&&!c.done&&(t=i.return)&&t.call(i)}finally{if(e)throw e.error}}return o},r.prototype.clear=function(){return new r},r})();re.instance();function Sn(r){return r===void 0&&(r={}),new Nn(new Map(Object.entries(r)))}function lr(r){return Symbol.for(r)}var Pn=(function(){function r(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,s){var o=new r(t._currentContext);return o._currentContext.set(n,s),o},t.deleteValue=function(n){var s=new r(t._currentContext);return s._currentContext.delete(n),s}}return r})(),xn=new Pn,ve=(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,s){n.__proto__=s}||function(n,s){for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(n[o]=s[o])},r(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");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),Fn=(function(){function r(){}return r.prototype.createGauge=function(e,t){return Vn},r.prototype.createHistogram=function(e,t){return Wn},r.prototype.createCounter=function(e,t){return Bn},r.prototype.createUpDownCounter=function(e,t){return Jn},r.prototype.createObservableGauge=function(e,t){return Kn},r.prototype.createObservableCounter=function(e,t){return zn},r.prototype.createObservableUpDownCounter=function(e,t){return Yn},r.prototype.addBatchObservableCallback=function(e,t){},r.prototype.removeBatchObservableCallback=function(e){},r})(),Ke=(function(){function r(){}return r})(),$n=(function(r){ve(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e})(Ke),Un=(function(r){ve(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.add=function(t,n){},e})(Ke),Dn=(function(r){ve(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e})(Ke),jn=(function(r){ve(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.record=function(t,n){},e})(Ke),yt=(function(){function r(){}return r.prototype.addCallback=function(e){},r.prototype.removeCallback=function(e){},r})(),Hn=(function(r){ve(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(yt),Gn=(function(r){ve(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(yt),qn=(function(r){ve(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(yt),Ln=new Fn,Bn=new $n,Vn=new Dn,Wn=new jn,Jn=new Un,zn=new Hn,Kn=new Gn,Yn=new qn,Qn={get:function(r,e){if(r!=null)return r[e]},keys:function(r){return r==null?[]:Object.keys(r)}},Xn={set:function(r,e,t){r!=null&&(r[e]=t)}},Zn=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(c){i={error:c}}finally{try{s&&!s.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},es=function(r,e,t){if(t||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return r.concat(o||Array.prototype.slice.call(e))},ts=(function(){function r(){}return r.prototype.active=function(){return xn},r.prototype.with=function(e,t,n){for(var s=[],o=3;o<arguments.length;o++)s[o-3]=arguments[o];return t.call.apply(t,es([n],Zn(s),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r})(),rs=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),s,o=[],i;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)o.push(s.value)}catch(c){i={error:c}}finally{try{s&&!s.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},ns=function(r,e,t){if(t||arguments.length===2)for(var n=0,s=e.length,o;n<s;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return r.concat(o||Array.prototype.slice.call(e))},wt="context",ss=new ts,Ye=(function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return Pe(wt,e,re.instance())},r.prototype.active=function(){return this._getContextManager().active()},r.prototype.with=function(e,t,n){for(var s,o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return(s=this._getContextManager()).with.apply(s,ns([e,t,n],rs(o),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return pe(wt)||ss},r.prototype.disable=function(){this._getContextManager().disable(),xe(wt,re.instance())},r})(),kt;(function(r){r[r.NONE=0]="NONE",r[r.SAMPLED=1]="SAMPLED"})(kt||(kt={}));var fr="0000000000000000",dr="00000000000000000000000000000000",os={traceId:dr,spanId:fr,traceFlags:kt.NONE},$e=(function(){function r(e){e===void 0&&(e=os),this._spanContext=e}return r.prototype.spanContext=function(){return this._spanContext},r.prototype.setAttribute=function(e,t){return this},r.prototype.setAttributes=function(e){return this},r.prototype.addEvent=function(e,t){return this},r.prototype.addLink=function(e){return this},r.prototype.addLinks=function(e){return this},r.prototype.setStatus=function(e){return this},r.prototype.updateName=function(e){return this},r.prototype.end=function(e){},r.prototype.isRecording=function(){return!1},r.prototype.recordException=function(e,t){},r})(),_t=lr("OpenTelemetry Context Key SPAN");function Mt(r){return r.getValue(_t)||void 0}function is(){return Mt(Ye.getInstance().active())}function Et(r,e){return r.setValue(_t,e)}function as(r){return r.deleteValue(_t)}function cs(r,e){return Et(r,new $e(e))}function gr(r){var e;return(e=Mt(r))===null||e===void 0?void 0:e.spanContext()}var us=/^([0-9a-f]{32})$/i,hs=/^[0-9a-f]{16}$/i;function ls(r){return us.test(r)&&r!==dr}function fs(r){return hs.test(r)&&r!==fr}function pr(r){return ls(r.traceId)&&fs(r.spanId)}function ds(r){return new $e(r)}var Tt=Ye.getInstance(),vr=(function(){function r(){}return r.prototype.startSpan=function(e,t,n){n===void 0&&(n=Tt.active());var s=!!t?.root;if(s)return new $e;var o=n&&gr(n);return gs(o)&&pr(o)?new $e(o):new $e},r.prototype.startActiveSpan=function(e,t,n,s){var o,i,c;if(!(arguments.length<2)){arguments.length===2?c=t:arguments.length===3?(o=t,c=n):(o=t,i=n,c=s);var a=i??Tt.active(),f=this.startSpan(e,o,a),u=Et(a,f);return Tt.with(u,c,void 0,f)}},r})();function gs(r){return typeof r=="object"&&typeof r.spanId=="string"&&typeof r.traceId=="string"&&typeof r.traceFlags=="number"}var ps=new vr,vs=(function(){function r(e,t,n,s){this._provider=e,this.name=t,this.version=n,this.options=s}return r.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},r.prototype.startActiveSpan=function(e,t,n,s){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},r.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):ps},r})(),bs=(function(){function r(){}return r.prototype.getTracer=function(e,t,n){return new vr},r})(),ms=new bs,br=(function(){function r(){}return r.prototype.getTracer=function(e,t,n){var s;return(s=this.getDelegateTracer(e,t,n))!==null&&s!==void 0?s:new vs(this,e,t,n)},r.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:ms},r.prototype.setDelegate=function(e){this._delegate=e},r.prototype.getDelegateTracer=function(e,t,n){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getTracer(e,t,n)},r})();Ye.getInstance(),re.instance();var ys=(function(){function r(){}return r.prototype.getMeter=function(e,t,n){return Ln},r})(),ws=new ys,Rt="metrics",ks=(function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalMeterProvider=function(e){return Pe(Rt,e,re.instance())},r.prototype.getMeterProvider=function(){return pe(Rt)||ws},r.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},r.prototype.disable=function(){xe(Rt,re.instance())},r})();ks.getInstance();var _s=(function(){function r(){}return r.prototype.inject=function(e,t){},r.prototype.extract=function(e,t){return e},r.prototype.fields=function(){return[]},r})(),It=lr("OpenTelemetry Baggage Key");function mr(r){return r.getValue(It)||void 0}function Ms(){return mr(Ye.getInstance().active())}function Es(r,e){return r.setValue(It,e)}function Ts(r){return r.deleteValue(It)}var Ct="propagation",Rs=new _s,Is=(function(){function r(){this.createBaggage=Sn,this.getBaggage=mr,this.getActiveBaggage=Ms,this.setBaggage=Es,this.deleteBaggage=Ts}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalPropagator=function(e){return Pe(Ct,e,re.instance())},r.prototype.inject=function(e,t,n){return n===void 0&&(n=Xn),this._getGlobalPropagator().inject(e,t,n)},r.prototype.extract=function(e,t,n){return n===void 0&&(n=Qn),this._getGlobalPropagator().extract(e,t,n)},r.prototype.fields=function(){return this._getGlobalPropagator().fields()},r.prototype.disable=function(){xe(Ct,re.instance())},r.prototype._getGlobalPropagator=function(){return pe(Ct)||Rs},r})();Is.getInstance();var Ot="trace",Cs=(function(){function r(){this._proxyTracerProvider=new br,this.wrapSpanContext=ds,this.isSpanContextValid=pr,this.deleteSpan=as,this.getSpan=Mt,this.getActiveSpan=is,this.getSpanContext=gr,this.setSpan=Et,this.setSpanContext=cs}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalTracerProvider=function(e){var t=Pe(Ot,this._proxyTracerProvider,re.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},r.prototype.getTracerProvider=function(){return pe(Ot)||this._proxyTracerProvider},r.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},r.prototype.disable=function(){xe(Ot,re.instance()),this._proxyTracerProvider=new br},r})(),Os=Cs.getInstance();const As=()=>H(e=>class extends e{constructor(...t){super(...t),this.hooks.hook("frontgateConnection:beforeSerializeMessage",n=>{n.header&&Os.getTracer("frontgate-js-sdk").startActiveSpan("frontgateConnection:sendMessage",s=>{const o=this.#e(s.spanContext());o&&(n.header={...n.header,...o}),s.end()})})}#e(t){if(!/^0+$/.test(t.traceId))return{tracing:{value:{value:yr(t)}}}}},{featureName:"OpenTelemetry",featureGroups:["Misc"]}),yr=r=>{const e=[18,20,9],t=n=>{for(let s=n.length;s>n.length-16;s-=2){let o=parseInt(n.substring(s-2,s),16);o>127&&(o-=256),e.push(o)}};return t(r.traceId),e.push(17),t(r.spanId),e.push(24),e.push(0),e},Ns=()=>H(e=>class extends e{async requestProxyEndpoint(t,n,s,o,i=this.defaultTimeoutInMs){const c=new Be(t,n,o);s&&c.setBody(s),c.header.setTimeout(i);const a={message:c.getPtlMessage(),callbackType:"job",callbackId:""};await this.hooks.callHook("frontgateConnection:sendMessage",a);const f=new Promise((h,v)=>{this.hooks.hookOnce(`frontgateConnection:response:${a.callbackId}`,w=>{try{if(!w.Message.includes("HTTPProxyResponse")){v(JSON.stringify(w));return}const M=new Jt(w);h({response:M,data:M.data})}catch(M){v(M)}})}),u=`Request timeout reached (${i} ms) for ${a.message.Message}`;return Y(i,u,f)}},{featureName:"HTTPProxyRequest",featureGroups:["Misc"]}),Ss=()=>H(e=>class extends e{async ping(t=this.defaultTimeoutInMs){const s={message:new Ve().getPtlMessage(),callbackType:"response",callbackId:"PingResponse"};await this.hooks.callHook("frontgateConnection:sendMessage",s);const o=new Promise(c=>{this.hooks.hookOnce(`frontgateConnection:response:${s.callbackId}`,a=>{const f=new We(a);c(f)})}),i=`Request timeout reached (${t} ms) for ${s.message.Message}`;return Y(t,i,o)}},{featureName:"Pingable",featureGroups:["Misc"]}),Ps=r=>H(t=>class extends t{async logRemotely(n){const o={message:new Bt({Message:"LogMessage",timestamp:{microseconds:Date.now()*1e3},uuid:{id_1:r??0,id_2:0},level:{value:4},area:61,Version:1,message:n}).getPtlMessage(),callbackType:"job",callbackId:""};return this.hooks.callHook("frontgateConnection:sendMessage",o)}},{featureName:"RemoteLogger",featureGroups:["Misc"]}),H=(r,e)=>{const t=r;return t.featureName=e.featureName,t.featureGroups=e.featureGroups,t.disabledFeatures=e.disabledFeatures,t.disabledFeatureGroups=e.disabledFeatureGroups,t};function At(r,e={},t){for(const n in r){const s=r[n],o=t?`${t}:${n}`:n;typeof s=="object"&&s!==null?At(s,e,o):typeof s=="function"&&(e[o]=s)}return e}const xs={run:r=>r()},Fs=()=>xs,wr=typeof console.createTask<"u"?console.createTask:Fs;function $s(r,e){const t=e.shift(),n=wr(t);return r.reduce((s,o)=>s.then(()=>n.run(()=>o(...e))),Promise.resolve())}function Us(r,e){const t=e.shift(),n=wr(t);return Promise.all(r.map(s=>n.run(()=>s(...e))))}function Nt(r,e){for(const t of[...r])t(e)}class Ds{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,n={}){if(!e||typeof t!="function")return()=>{};const s=e;let o;for(;this._deprecatedHooks[e];)o=this._deprecatedHooks[e],e=o.to;if(o&&!n.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 n,s=(...o)=>(typeof n=="function"&&n(),n=void 0,s=void 0,t(...o));return n=this.hook(e,s),n}removeHook(e,t){if(this._hooks[e]){const n=this._hooks[e].indexOf(t);n!==-1&&this._hooks[e].splice(n,1),this._hooks[e].length===0&&delete this._hooks[e]}}deprecateHook(e,t){this._deprecatedHooks[e]=typeof t=="string"?{to:t}:t;const n=this._hooks[e]||[];delete this._hooks[e];for(const s of n)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=At(e),n=Object.keys(t).map(s=>this.hook(s,t[s]));return()=>{for(const s of n.splice(0,n.length))s()}}removeHooks(e){const t=At(e);for(const n in t)this.removeHook(n,t[n])}removeAllHooks(){for(const e in this._hooks)delete this._hooks[e]}callHook(e,...t){return t.unshift(e),this.callHookWith($s,e,...t)}callHookParallel(e,...t){return t.unshift(e),this.callHookWith(Us,e,...t)}callHookWith(e,t,...n){const s=this._before||this._after?{name:t,args:n,context:{}}:void 0;this._before&&Nt(this._before,s);const o=e(t in this._hooks?[...this._hooks[t]]:[],n);return o instanceof Promise?o.finally(()=>{this._after&&s&&Nt(this._after,s)}):(this._after&&s&&Nt(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 js(){return new Ds}const kr=typeof window<"u";function Hs(r,e={}){const t={inspect:kr,group:kr,filter:()=>!0,...e},n=t.filter,s=typeof n=="string"?u=>u.startsWith(n):n,o=t.tag?`[${t.tag}] `:"",i=u=>o+u.name+"".padEnd(u._id,"\0"),c={},a=r.beforeEach(u=>{s!==void 0&&!s(u.name)||(c[u.name]=c[u.name]||0,u._id=c[u.name]++,console.time(i(u)))}),f=r.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(),c[u.name]--)});return{close:()=>{a(),f()}}}class _r{constructor(e){this.hooks=js(),this.#e=1e4,e?.hookDebug&&Hs(this.hooks,{tag:"hooks"}),e?.defaultRequestTimeout&&(this.#e=e.defaultRequestTimeout)}#e;get defaultTimeoutInMs(){return this.#e}log(e,...t){if(this.hooks.callHook("base:log",t),this.logger)switch(e){case d.TRACE:this.logger.trace(t);break;case d.DEBUG:this.logger.debug(t);break;case d.INFO:this.logger.info(t);break;case d.WARN:this.logger.warn(t);break;case d.ERROR:this.logger.error(t);break;case d.FATAL:this.logger.fatal(t);break}}}class Qe{#e;#t=[];#r=[];#n=[];constructor(e,t=[],n=[],s=[]){this.#e=e,this.#t=t,this.#r=n,this.#n=s}static create(){return new Qe(_r)}#s(e){if(this.#t.includes(e))throw new Error(`Feature "${e}" has already been used.`)}#i(e){for(const t of this.#r)if(t.feature===e)throw new Error(`Feature "${e}" has been disabled by ${t.disabler.join(",")}.`)}#a(e){for(const t of this.#n)if(t.feature===e)throw new Error(`Group "${e}" has been disabled by ${t.disabler.join(",")}.`)}#o(e,t){for(const n of this.#r)if(n.feature===t){n.disabler.push(e);return}this.#r.push({disabler:[e],feature:t})}#c(e,t){for(const n of this.#n)if(n.feature===t){n.disabler.push(e);return}this.#n.push({disabler:[e],feature:t})}with(e){const{featureName:t,disabledFeatures:n,disabledFeatureGroups:s,featureGroups:o}=e;if(!t)throw new Error("Feature name is missing");if(t!=="Custom"){if(this.#s(t),this.#i(t),this.#t.push(t),o&&o.length>0)for(const c of o)this.#a(c);if(n&&n.length>0)for(const c of n)this.#o(t,c);if(s&&s.length>0)for(const c of s)this.#c(t,c)}const i=e(this.#e);return new Qe(i,this.#t,this.#r,this.#n)}build(e){return new this.#e(e)}getClientConstructor(){return this.#e}}b.AbstractLogger=ie,b.AbstractMdg2Request=me,b.AuthenticationByTokenRequest=qe,b.AuthenticationTokenRequest=Le,b.AuthenticationTokenResponse=Vt,b.CancelSubscriptionRequest=le,b.ConnectionState=Ut,b.ConsoleLogger=nt,b.CookieTokenAuthenticationFactors=Ft,b.DEFAULT_TIMEOUT_IN_MS=Lt,b.DefaultHosts=jt,b.DeploymentStage=Dt,b.ErrorResponse=z,b.FLAG_HAS_NEXT_CHUNK=rt,b.FrontgateClient=_r,b.FrontgateClientBuilder=Qe,b.FrontgateClientDataObserver=mt,b.FrontgateClientEndpointDataObserver=ur,b.HTTPProxyRequest=Be,b.HTTPProxyResponse=Jt,b.HighLevelRequest=ye,b.HighLevelResponse=Wt,b.HighLevelUpdate=tt,b.ID_APP_AUTHENTICATED=he,b.ID_USER_AUTHENTICATED=be,b.ID_USER_NONE=$t,b.LogLevel=d,b.LoggerHelper=Pr,b.Mdg2Response=fe,b.NullLogger=st,b.PingRequest=Ve,b.PingResponse=We,b.RawRequest=Bt,b.TimeOptions=Ht,b.TransportLayerClientRequestHeader=Ge,b.WinstonLogger=Fr,b.authTokenRequest=$r,b.cookieTokenAuth=gn,b.createExtendedMixinFactory=H,b.encodeSpanContext=yr,b.endpointRequest=Ur,b.endpointSubscriptions=an,b.fetchAuth=vn,b.getBytesFromBuffer=Cr,b.httpProxyRequest=Ns,b.levels=xr,b.logger=Dr,b.messageCompressor=sn,b.openTelemetry=As,b.pingRequests=Ss,b.rawSubscriptions=cn,b.reconnect=bn,b.remotelogger=Ps,b.requests=on,b.timeToMilliseconds=He,b.tokenAuth=pn,b.useTimeout=Y,b.wsConnection=Kt,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})}));