easyproctor 2.3.2 → 2.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -264,6 +264,12 @@ const {
264
264
  });
265
265
  ```
266
266
 
267
+ ## Release Note V 2.3.3
268
+ - Correção do reset no startSession
269
+
270
+ ## Release Note V 2.3.2
271
+ - Melhorias no fluxo da câmera externa (reset e goToExternalCameraPositionStep)
272
+
267
273
  ## Release Note V 2.3.1
268
274
  - Implementação da funcionalidade de transmissão com câmera externa
269
275
 
package/esm/index.js CHANGED
@@ -17770,8 +17770,8 @@ var _ExternalCameraChecker = class _ExternalCameraChecker {
17770
17770
  try {
17771
17771
  this.onQrCodeReadedCallback = onQrCodeReadedCallback;
17772
17772
  if (this.connection)
17773
- this.disconnectWebSocket();
17774
- this.initializeWebSocketConnection();
17773
+ await this.disconnectWebSocket();
17774
+ await this.initializeWebSocketConnection();
17775
17775
  await this.reset();
17776
17776
  const response = await this.backend.externalCameraStartSession();
17777
17777
  this.externalSessionId = response.externalSessionId;
package/index.js CHANGED
@@ -33019,8 +33019,8 @@ var _ExternalCameraChecker = class _ExternalCameraChecker {
33019
33019
  try {
33020
33020
  this.onQrCodeReadedCallback = onQrCodeReadedCallback;
33021
33021
  if (this.connection)
33022
- this.disconnectWebSocket();
33023
- this.initializeWebSocketConnection();
33022
+ await this.disconnectWebSocket();
33023
+ await this.initializeWebSocketConnection();
33024
33024
  await this.reset();
33025
33025
  const response = await this.backend.externalCameraStartSession();
33026
33026
  this.externalSessionId = response.externalSessionId;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easyproctor",
3
- "version": "2.3.2",
3
+ "version": "2.3.3",
4
4
  "description": "Modulo web de gravação do EasyProctor",
5
5
  "main": "./index.js",
6
6
  "module": "./esm/index.js",
@@ -301,7 +301,7 @@ registerProcessor("audio-processor", AudioProcessor);
301
301
  0% { transform: rotate(0deg); }
302
302
  100% { transform: rotate(360deg); }
303
303
  }
304
- `,o=document.createElement("style");o.innerHTML=n,document.head.appendChild(o)}};var ot=class extends Error{constructor(t,r){let n=new.target.prototype;super(`${t}: Status code '${r}'`),this.statusCode=r,this.__proto__=n}},Or=class extends Error{constructor(t="A timeout occurred."){let r=new.target.prototype;super(t),this.__proto__=r}},xe=class extends Error{constructor(t="An abort occurred."){let r=new.target.prototype;super(t),this.__proto__=r}},ec=class extends Error{constructor(t,r){let n=new.target.prototype;super(t),this.transport=r,this.errorType="UnsupportedTransportError",this.__proto__=n}},tc=class extends Error{constructor(t,r){let n=new.target.prototype;super(t),this.transport=r,this.errorType="DisabledTransportError",this.__proto__=n}},rc=class extends Error{constructor(t,r){let n=new.target.prototype;super(t),this.transport=r,this.errorType="FailedToStartTransportError",this.__proto__=n}},yi=class extends Error{constructor(t){let r=new.target.prototype;super(t),this.errorType="FailedToNegotiateWithServerError",this.__proto__=r}},nc=class extends Error{constructor(t,r){let n=new.target.prototype;super(t),this.innerErrors=r,this.__proto__=n}};var po=class{constructor(t,r,n){this.statusCode=t,this.statusText=r,this.content=n}},qt=class{get(t,r){return this.send({...r,method:"GET",url:t})}post(t,r){return this.send({...r,method:"POST",url:t})}delete(t,r){return this.send({...r,method:"DELETE",url:t})}getCookieString(t){return""}};var m;(function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"})(m||(m={}));var Gt=class{constructor(){}log(t,r){}};Gt.instance=new Gt;var W0="9.0.6";var $=class{static isRequired(t,r){if(t==null)throw new Error(`The '${r}' argument is required.`)}static isNotEmpty(t,r){if(!t||t.match(/^\s*$/))throw new Error(`The '${r}' argument should not be empty.`)}static isIn(t,r,n){if(!(t in r))throw new Error(`Unknown ${n} value: ${t}.`)}},q=class e{static get isBrowser(){return!e.isNode&&typeof window=="object"&&typeof window.document=="object"}static get isWebWorker(){return!e.isNode&&typeof self=="object"&&"importScripts"in self}static get isReactNative(){return!e.isNode&&typeof window=="object"&&typeof window.document>"u"}static get isNode(){return typeof process<"u"&&process.release&&process.release.name==="node"}};function Br(e,t){let r="";return Bt(e)?(r=`Binary data of length ${e.byteLength}`,t&&(r+=`. Content: '${sw(e)}'`)):typeof e=="string"&&(r=`String data of length ${e.length}`,t&&(r+=`. Content: '${e}'`)),r}function sw(e){let t=new Uint8Array(e),r="";return t.forEach(n=>{let o=n<16?"0":"";r+=`0x${o}${n.toString(16)} `}),r.substr(0,r.length-1)}function Bt(e){return e&&typeof ArrayBuffer<"u"&&(e instanceof ArrayBuffer||e.constructor&&e.constructor.name==="ArrayBuffer")}async function ic(e,t,r,n,o,i){let s={},[a,c]=Kt();s[a]=c,e.log(m.Trace,`(${t} transport) sending data. ${Br(o,i.logMessageContent)}.`);let l=Bt(o)?"arraybuffer":"text",h=await r.post(n,{content:o,headers:{...s,...i.headers},responseType:l,timeout:i.timeout,withCredentials:i.withCredentials});e.log(m.Trace,`(${t} transport) request complete. Response status: ${h.statusCode}.`)}function q0(e){return e===void 0?new an(m.Information):e===null?Gt.instance:e.log!==void 0?e:new an(e)}var oc=class{constructor(t,r){this._subject=t,this._observer=r}dispose(){let t=this._subject.observers.indexOf(this._observer);t>-1&&this._subject.observers.splice(t,1),this._subject.observers.length===0&&this._subject.cancelCallback&&this._subject.cancelCallback().catch(r=>{})}},an=class{constructor(t){this._minLevel=t,this.out=console}log(t,r){if(t>=this._minLevel){let n=`[${new Date().toISOString()}] ${m[t]}: ${r}`;switch(t){case m.Critical:case m.Error:this.out.error(n);break;case m.Warning:this.out.warn(n);break;case m.Information:this.out.info(n);break;default:this.out.log(n);break}}}};function Kt(){let e="X-SignalR-User-Agent";return q.isNode&&(e="User-Agent"),[e,aw(W0,cw(),hw(),lw())]}function aw(e,t,r,n){let o="Microsoft SignalR/",i=e.split(".");return o+=`${i[0]}.${i[1]}`,o+=` (${e}; `,t&&t!==""?o+=`${t}; `:o+="Unknown OS; ",o+=`${r}`,n?o+=`; ${n}`:o+="; Unknown Runtime Version",o+=")",o}function cw(){if(q.isNode)switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}else return""}function lw(){if(q.isNode)return process.versions.node}function hw(){return q.isNode?"NodeJS":"Browser"}function sc(e){return e.stack?e.stack:e.message?e.message:`${e}`}function G0(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("could not find global")}var ac=class extends qt{constructor(t){if(super(),this._logger=t,typeof fetch>"u"||q.isNode){let r=typeof __webpack_require__=="function"?__non_webpack_require__:mn;this._jar=new(r("tough-cookie")).CookieJar,typeof fetch>"u"?this._fetchType=r("node-fetch"):this._fetchType=fetch,this._fetchType=r("fetch-cookie")(this._fetchType,this._jar)}else this._fetchType=fetch.bind(G0());if(typeof AbortController>"u"){let r=typeof __webpack_require__=="function"?__non_webpack_require__:mn;this._abortControllerType=r("abort-controller")}else this._abortControllerType=AbortController}async send(t){if(t.abortSignal&&t.abortSignal.aborted)throw new xe;if(!t.method)throw new Error("No method defined.");if(!t.url)throw new Error("No url defined.");let r=new this._abortControllerType,n;t.abortSignal&&(t.abortSignal.onabort=()=>{r.abort(),n=new xe});let o=null;if(t.timeout){let c=t.timeout;o=setTimeout(()=>{r.abort(),this._logger.log(m.Warning,"Timeout from HTTP request."),n=new Or},c)}t.content===""&&(t.content=void 0),t.content&&(t.headers=t.headers||{},Bt(t.content)?t.headers["Content-Type"]="application/octet-stream":t.headers["Content-Type"]="text/plain;charset=UTF-8");let i;try{i=await this._fetchType(t.url,{body:t.content,cache:"no-cache",credentials:t.withCredentials===!0?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...t.headers},method:t.method,mode:"cors",redirect:"follow",signal:r.signal})}catch(c){throw n||(this._logger.log(m.Warning,`Error from HTTP request. ${c}.`),c)}finally{o&&clearTimeout(o),t.abortSignal&&(t.abortSignal.onabort=null)}if(!i.ok){let c=await K0(i,"text");throw new ot(c||i.statusText,i.status)}let a=await K0(i,t.responseType);return new po(i.status,i.statusText,a)}getCookieString(t){let r="";return q.isNode&&this._jar&&this._jar.getCookies(t,(n,o)=>r=o.join("; ")),r}};function K0(e,t){let r;switch(t){case"arraybuffer":r=e.arrayBuffer();break;case"text":r=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:r=e.text();break}return r}var cc=class extends qt{constructor(t){super(),this._logger=t}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new xe):t.method?t.url?new Promise((r,n)=>{let o=new XMLHttpRequest;o.open(t.method,t.url,!0),o.withCredentials=t.withCredentials===void 0?!0:t.withCredentials,o.setRequestHeader("X-Requested-With","XMLHttpRequest"),t.content===""&&(t.content=void 0),t.content&&(Bt(t.content)?o.setRequestHeader("Content-Type","application/octet-stream"):o.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));let i=t.headers;i&&Object.keys(i).forEach(s=>{o.setRequestHeader(s,i[s])}),t.responseType&&(o.responseType=t.responseType),t.abortSignal&&(t.abortSignal.onabort=()=>{o.abort(),n(new xe)}),t.timeout&&(o.timeout=t.timeout),o.onload=()=>{t.abortSignal&&(t.abortSignal.onabort=null),o.status>=200&&o.status<300?r(new po(o.status,o.statusText,o.response||o.responseText)):n(new ot(o.response||o.responseText||o.statusText,o.status))},o.onerror=()=>{this._logger.log(m.Warning,`Error from HTTP request. ${o.status}: ${o.statusText}.`),n(new ot(o.statusText,o.status))},o.ontimeout=()=>{this._logger.log(m.Warning,"Timeout from HTTP request."),n(new Or)},o.send(t.content)}):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}};var lc=class extends qt{constructor(t){if(super(),typeof fetch<"u"||q.isNode)this._httpClient=new ac(t);else if(typeof XMLHttpRequest<"u")this._httpClient=new cc(t);else throw new Error("No usable HttpClient found.")}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new xe):t.method?t.url?this._httpClient.send(t):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(t){return this._httpClient.getCookieString(t)}};var it=class e{static write(t){return`${t}${e.RecordSeparator}`}static parse(t){if(t[t.length-1]!==e.RecordSeparator)throw new Error("Message is incomplete.");let r=t.split(e.RecordSeparator);return r.pop(),r}};it.RecordSeparatorCode=30;it.RecordSeparator=String.fromCharCode(it.RecordSeparatorCode);var hc=class{writeHandshakeRequest(t){return it.write(JSON.stringify(t))}parseHandshakeResponse(t){let r,n;if(Bt(t)){let a=new Uint8Array(t),c=a.indexOf(it.RecordSeparatorCode);if(c===-1)throw new Error("Message is incomplete.");let l=c+1;r=String.fromCharCode.apply(null,Array.prototype.slice.call(a.slice(0,l))),n=a.byteLength>l?a.slice(l).buffer:null}else{let a=t,c=a.indexOf(it.RecordSeparator);if(c===-1)throw new Error("Message is incomplete.");let l=c+1;r=a.substring(0,l),n=a.length>l?a.substring(l):null}let o=it.parse(r),i=JSON.parse(o[0]);if(i.type)throw new Error("Expected a handshake response from the server.");return[n,i]}};var D;(function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close",e[e.Ack=8]="Ack",e[e.Sequence=9]="Sequence"})(D||(D={}));var uc=class{constructor(){this.observers=[]}next(t){for(let r of this.observers)r.next(t)}error(t){for(let r of this.observers)r.error&&r.error(t)}complete(){for(let t of this.observers)t.complete&&t.complete()}subscribe(t){return this.observers.push(t),new oc(this,t)}};var dc=class{constructor(t,r,n){this._bufferSize=1e5,this._messages=[],this._totalMessageCount=0,this._waitForSequenceMessage=!1,this._nextReceivingSequenceId=1,this._latestReceivedSequenceId=0,this._bufferedByteCount=0,this._reconnectInProgress=!1,this._protocol=t,this._connection=r,this._bufferSize=n}async _send(t){let r=this._protocol.writeMessage(t),n=Promise.resolve();if(this._isInvocationMessage(t)){this._totalMessageCount++;let o=()=>{},i=()=>{};Bt(r)?this._bufferedByteCount+=r.byteLength:this._bufferedByteCount+=r.length,this._bufferedByteCount>=this._bufferSize&&(n=new Promise((s,a)=>{o=s,i=a})),this._messages.push(new Gu(r,this._totalMessageCount,o,i))}try{this._reconnectInProgress||await this._connection.send(r)}catch{this._disconnected()}await n}_ack(t){let r=-1;for(let n=0;n<this._messages.length;n++){let o=this._messages[n];if(o._id<=t.sequenceId)r=n,Bt(o._message)?this._bufferedByteCount-=o._message.byteLength:this._bufferedByteCount-=o._message.length,o._resolver();else if(this._bufferedByteCount<this._bufferSize)o._resolver();else break}r!==-1&&(this._messages=this._messages.slice(r+1))}_shouldProcessMessage(t){if(this._waitForSequenceMessage)return t.type!==D.Sequence?!1:(this._waitForSequenceMessage=!1,!0);if(!this._isInvocationMessage(t))return!0;let r=this._nextReceivingSequenceId;return this._nextReceivingSequenceId++,r<=this._latestReceivedSequenceId?(r===this._latestReceivedSequenceId&&this._ackTimer(),!1):(this._latestReceivedSequenceId=r,this._ackTimer(),!0)}_resetSequence(t){if(t.sequenceId>this._nextReceivingSequenceId){this._connection.stop(new Error("Sequence ID greater than amount of messages we've received."));return}this._nextReceivingSequenceId=t.sequenceId}_disconnected(){this._reconnectInProgress=!0,this._waitForSequenceMessage=!0}async _resend(){let t=this._messages.length!==0?this._messages[0]._id:this._totalMessageCount+1;await this._connection.send(this._protocol.writeMessage({type:D.Sequence,sequenceId:t}));let r=this._messages;for(let n of r)await this._connection.send(n._message);this._reconnectInProgress=!1}_dispose(t){t??(t=new Error("Unable to reconnect to server."));for(let r of this._messages)r._rejector(t)}_isInvocationMessage(t){switch(t.type){case D.Invocation:case D.StreamItem:case D.Completion:case D.StreamInvocation:case D.CancelInvocation:return!0;case D.Close:case D.Sequence:case D.Ping:case D.Ack:return!1}}_ackTimer(){this._ackTimerHandle===void 0&&(this._ackTimerHandle=setTimeout(async()=>{try{this._reconnectInProgress||await this._connection.send(this._protocol.writeMessage({type:D.Ack,sequenceId:this._latestReceivedSequenceId}))}catch{}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0},1e3))}},Gu=class{constructor(t,r,n,o){this._message=t,this._id=r,this._resolver=n,this._rejector=o}};var uw=30*1e3,dw=15*1e3,pw=1e5,re;(function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"})(re||(re={}));var pc=class e{static create(t,r,n,o,i,s,a){return new e(t,r,n,o,i,s,a)}constructor(t,r,n,o,i,s,a){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(m.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},$.isRequired(t,"connection"),$.isRequired(r,"logger"),$.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=i??uw,this.keepAliveIntervalInMilliseconds=s??dw,this._statefulReconnectBufferSize=a??pw,this._logger=r,this._protocol=n,this.connection=t,this._reconnectPolicy=o,this._handshakeProtocol=new hc,this.connection.onreceive=c=>this._processIncomingData(c),this.connection.onclose=c=>this._connectionClosed(c),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=re.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:D.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(t){if(this._connectionState!==re.Disconnected&&this._connectionState!==re.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!t)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=t}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==re.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=re.Connecting,this._logger.log(m.Debug,"Starting HubConnection.");try{await this._startInternal(),q.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=re.Connected,this._connectionStarted=!0,this._logger.log(m.Debug,"HubConnection connected successfully.")}catch(t){return this._connectionState=re.Disconnected,this._logger.log(m.Debug,`HubConnection failed to start successfully because of error '${t}'.`),Promise.reject(t)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;let t=new Promise((r,n)=>{this._handshakeResolver=r,this._handshakeRejecter=n});await this.connection.start(this._protocol.transferFormat);try{let r=this._protocol.version;this.connection.features.reconnect||(r=1);let n={protocol:this._protocol.name,version:r};if(this._logger.log(m.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(n)),this._logger.log(m.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await t,this._stopDuringStartError)throw this._stopDuringStartError;(this.connection.features.reconnect||!1)&&(this._messageBuffer=new dc(this._protocol,this.connection,this._statefulReconnectBufferSize),this.connection.features.disconnected=this._messageBuffer._disconnected.bind(this._messageBuffer),this.connection.features.resend=()=>{if(this._messageBuffer)return this._messageBuffer._resend()}),this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(r){throw this._logger.log(m.Debug,`Hub handshake failed with error '${r}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(r),r}}async stop(){let t=this._startPromise;this.connection.features.reconnect=!1,this._stopPromise=this._stopInternal(),await this._stopPromise;try{await t}catch{}}_stopInternal(t){if(this._connectionState===re.Disconnected)return this._logger.log(m.Debug,`Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===re.Disconnecting)return this._logger.log(m.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;let r=this._connectionState;return this._connectionState=re.Disconnecting,this._logger.log(m.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(m.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(r===re.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=t||new xe("The connection was stopped before the hub handshake could complete."),this.connection.stop(t))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(t,...r){let[n,o]=this._replaceStreamingParams(r),i=this._createStreamInvocation(t,r,o),s,a=new uc;return a.cancelCallback=()=>{let c=this._createCancelInvocation(i.invocationId);return delete this._callbacks[i.invocationId],s.then(()=>this._sendWithProtocol(c))},this._callbacks[i.invocationId]=(c,l)=>{if(l){a.error(l);return}else c&&(c.type===D.Completion?c.error?a.error(new Error(c.error)):a.complete():a.next(c.item))},s=this._sendWithProtocol(i).catch(c=>{a.error(c),delete this._callbacks[i.invocationId]}),this._launchStreams(n,s),a}_sendMessage(t){return this._resetKeepAliveInterval(),this.connection.send(t)}_sendWithProtocol(t){return this._messageBuffer?this._messageBuffer._send(t):this._sendMessage(this._protocol.writeMessage(t))}send(t,...r){let[n,o]=this._replaceStreamingParams(r),i=this._sendWithProtocol(this._createInvocation(t,r,!0,o));return this._launchStreams(n,i),i}invoke(t,...r){let[n,o]=this._replaceStreamingParams(r),i=this._createInvocation(t,r,!1,o);return new Promise((a,c)=>{this._callbacks[i.invocationId]=(h,u)=>{if(u){c(u);return}else h&&(h.type===D.Completion?h.error?c(new Error(h.error)):a(h.result):c(new Error(`Unexpected message type: ${h.type}`)))};let l=this._sendWithProtocol(i).catch(h=>{c(h),delete this._callbacks[i.invocationId]});this._launchStreams(n,l)})}on(t,r){!t||!r||(t=t.toLowerCase(),this._methods[t]||(this._methods[t]=[]),this._methods[t].indexOf(r)===-1&&this._methods[t].push(r))}off(t,r){if(!t)return;t=t.toLowerCase();let n=this._methods[t];if(n)if(r){let o=n.indexOf(r);o!==-1&&(n.splice(o,1),n.length===0&&delete this._methods[t])}else delete this._methods[t]}onclose(t){t&&this._closedCallbacks.push(t)}onreconnecting(t){t&&this._reconnectingCallbacks.push(t)}onreconnected(t){t&&this._reconnectedCallbacks.push(t)}_processIncomingData(t){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(t=this._processHandshakeResponse(t),this._receivedHandshakeResponse=!0),t){let r=this._protocol.parseMessages(t,this._logger);for(let n of r)if(!(this._messageBuffer&&!this._messageBuffer._shouldProcessMessage(n)))switch(n.type){case D.Invocation:this._invokeClientMethod(n).catch(o=>{this._logger.log(m.Error,`Invoke client method threw error: ${sc(o)}`)});break;case D.StreamItem:case D.Completion:{let o=this._callbacks[n.invocationId];if(o){n.type===D.Completion&&delete this._callbacks[n.invocationId];try{o(n)}catch(i){this._logger.log(m.Error,`Stream callback threw error: ${sc(i)}`)}}break}case D.Ping:break;case D.Close:{this._logger.log(m.Information,"Close message received from server.");let o=n.error?new Error("Server returned an error on close: "+n.error):void 0;n.allowReconnect===!0?this.connection.stop(o):this._stopPromise=this._stopInternal(o);break}case D.Ack:this._messageBuffer&&this._messageBuffer._ack(n);break;case D.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(n);break;default:this._logger.log(m.Warning,`Invalid message type: ${n.type}.`);break}}this._resetTimeoutPeriod()}_processHandshakeResponse(t){let r,n;try{[n,r]=this._handshakeProtocol.parseHandshakeResponse(t)}catch(o){let i="Error parsing handshake response: "+o;this._logger.log(m.Error,i);let s=new Error(i);throw this._handshakeRejecter(s),s}if(r.error){let o="Server returned handshake error: "+r.error;this._logger.log(m.Error,o);let i=new Error(o);throw this._handshakeRejecter(i),i}else this._logger.log(m.Debug,"Server handshake complete.");return this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=new Date().getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if((!this.connection.features||!this.connection.features.inherentKeepAlive)&&(this._timeoutHandle=setTimeout(()=>this.serverTimeout(),this.serverTimeoutInMilliseconds),this._pingServerHandle===void 0)){let t=this._nextKeepAlive-new Date().getTime();t<0&&(t=0),this._pingServerHandle=setTimeout(async()=>{if(this._connectionState===re.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}},t)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(t){let r=t.target.toLowerCase(),n=this._methods[r];if(!n){this._logger.log(m.Warning,`No client method with the name '${r}' found.`),t.invocationId&&(this._logger.log(m.Warning,`No result given for '${r}' method and invocation ID '${t.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(t.invocationId,"Client didn't provide a result.",null)));return}let o=n.slice(),i=!!t.invocationId,s,a,c;for(let l of o)try{let h=s;s=await l.apply(this,t.arguments),i&&s&&h&&(this._logger.log(m.Error,`Multiple results provided for '${r}'. Sending error to server.`),c=this._createCompletionMessage(t.invocationId,"Client provided multiple results.",null)),a=void 0}catch(h){a=h,this._logger.log(m.Error,`A callback for the method '${r}' threw error '${h}'.`)}c?await this._sendWithProtocol(c):i?(a?c=this._createCompletionMessage(t.invocationId,`${a}`,null):s!==void 0?c=this._createCompletionMessage(t.invocationId,null,s):(this._logger.log(m.Warning,`No result given for '${r}' method and invocation ID '${t.invocationId}'.`),c=this._createCompletionMessage(t.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(c)):s&&this._logger.log(m.Error,`Result given for '${r}' method but server is not expecting a result.`)}_connectionClosed(t){this._logger.log(m.Debug,`HubConnection.connectionClosed(${t}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||t||new xe("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(t||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===re.Disconnecting?this._completeClose(t):this._connectionState===re.Connected&&this._reconnectPolicy?this._reconnect(t):this._connectionState===re.Connected&&this._completeClose(t)}_completeClose(t){if(this._connectionStarted){this._connectionState=re.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(t??new Error("Connection closed.")),this._messageBuffer=void 0),q.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach(r=>r.apply(this,[t]))}catch(r){this._logger.log(m.Error,`An onclose callback called with error '${t}' threw error '${r}'.`)}}}async _reconnect(t){let r=Date.now(),n=0,o=t!==void 0?t:new Error("Attempting to reconnect due to a unknown error."),i=this._getNextRetryDelay(n++,0,o);if(i===null){this._logger.log(m.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),this._completeClose(t);return}if(this._connectionState=re.Reconnecting,t?this._logger.log(m.Information,`Connection reconnecting because of error '${t}'.`):this._logger.log(m.Information,"Connection reconnecting."),this._reconnectingCallbacks.length!==0){try{this._reconnectingCallbacks.forEach(s=>s.apply(this,[t]))}catch(s){this._logger.log(m.Error,`An onreconnecting callback called with error '${t}' threw error '${s}'.`)}if(this._connectionState!==re.Reconnecting){this._logger.log(m.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");return}}for(;i!==null;){if(this._logger.log(m.Information,`Reconnect attempt number ${n} will start in ${i} ms.`),await new Promise(s=>{this._reconnectDelayHandle=setTimeout(s,i)}),this._reconnectDelayHandle=void 0,this._connectionState!==re.Reconnecting){this._logger.log(m.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");return}try{if(await this._startInternal(),this._connectionState=re.Connected,this._logger.log(m.Information,"HubConnection reconnected successfully."),this._reconnectedCallbacks.length!==0)try{this._reconnectedCallbacks.forEach(s=>s.apply(this,[this.connection.connectionId]))}catch(s){this._logger.log(m.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${s}'.`)}return}catch(s){if(this._logger.log(m.Information,`Reconnect attempt failed because of error '${s}'.`),this._connectionState!==re.Reconnecting){this._logger.log(m.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),this._connectionState===re.Disconnecting&&this._completeClose();return}o=s instanceof Error?s:new Error(s.toString()),i=this._getNextRetryDelay(n++,Date.now()-r,o)}}this._logger.log(m.Information,`Reconnect retries have been exhausted after ${Date.now()-r} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(t,r,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:r,previousRetryCount:t,retryReason:n})}catch(o){return this._logger.log(m.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${t}, ${r}) threw error '${o}'.`),null}}_cancelCallbacksWithError(t){let r=this._callbacks;this._callbacks={},Object.keys(r).forEach(n=>{let o=r[n];try{o(null,t)}catch(i){this._logger.log(m.Error,`Stream 'error' callback called with '${t}' threw error: ${sc(i)}`)}})}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(t,r,n,o){if(n)return o.length!==0?{target:t,arguments:r,streamIds:o,type:D.Invocation}:{target:t,arguments:r,type:D.Invocation};{let i=this._invocationId;return this._invocationId++,o.length!==0?{target:t,arguments:r,invocationId:i.toString(),streamIds:o,type:D.Invocation}:{target:t,arguments:r,invocationId:i.toString(),type:D.Invocation}}}_launchStreams(t,r){if(t.length!==0){r||(r=Promise.resolve());for(let n in t)t[n].subscribe({complete:()=>{r=r.then(()=>this._sendWithProtocol(this._createCompletionMessage(n)))},error:o=>{let i;o instanceof Error?i=o.message:o&&o.toString?i=o.toString():i="Unknown error",r=r.then(()=>this._sendWithProtocol(this._createCompletionMessage(n,i)))},next:o=>{r=r.then(()=>this._sendWithProtocol(this._createStreamItemMessage(n,o)))}})}}_replaceStreamingParams(t){let r=[],n=[];for(let o=0;o<t.length;o++){let i=t[o];if(this._isObservable(i)){let s=this._invocationId;this._invocationId++,r[s]=i,n.push(s.toString()),t.splice(o,1)}}return[r,n]}_isObservable(t){return t&&t.subscribe&&typeof t.subscribe=="function"}_createStreamInvocation(t,r,n){let o=this._invocationId;return this._invocationId++,n.length!==0?{target:t,arguments:r,invocationId:o.toString(),streamIds:n,type:D.StreamInvocation}:{target:t,arguments:r,invocationId:o.toString(),type:D.StreamInvocation}}_createCancelInvocation(t){return{invocationId:t,type:D.CancelInvocation}}_createStreamItemMessage(t,r){return{invocationId:t,item:r,type:D.StreamItem}}_createCompletionMessage(t,r,n){return r?{error:r,invocationId:t,type:D.Completion}:{invocationId:t,result:n,type:D.Completion}}_createCloseMessage(){return{type:D.Close}}};var fw=[0,2e3,1e4,3e4,null],bi=class{constructor(t){this._retryDelays=t!==void 0?[...t,null]:fw}nextRetryDelayInMilliseconds(t){return this._retryDelays[t.previousRetryCount]}};var Mt=class{};Mt.Authorization="Authorization";Mt.Cookie="Cookie";var fc=class extends qt{constructor(t,r){super(),this._innerClient=t,this._accessTokenFactory=r}async send(t){let r=!0;this._accessTokenFactory&&(!this._accessToken||t.url&&t.url.indexOf("/negotiate?")>0)&&(r=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(t);let n=await this._innerClient.send(t);return r&&n.statusCode===401&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(t),await this._innerClient.send(t)):n}_setAuthorizationHeader(t){t.headers||(t.headers={}),this._accessToken?t.headers[Mt.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&t.headers[Mt.Authorization]&&delete t.headers[Mt.Authorization]}getCookieString(t){return this._innerClient.getCookieString(t)}};var ie;(function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"})(ie||(ie={}));var ue;(function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"})(ue||(ue={}));var mc=class{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}};var wi=class{get pollAborted(){return this._pollAbort.aborted}constructor(t,r,n){this._httpClient=t,this._logger=r,this._pollAbort=new mc,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(t,r){if($.isRequired(t,"url"),$.isRequired(r,"transferFormat"),$.isIn(r,ue,"transferFormat"),this._url=t,this._logger.log(m.Trace,"(LongPolling transport) Connecting."),r===ue.Binary&&typeof XMLHttpRequest<"u"&&typeof new XMLHttpRequest().responseType!="string")throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");let[n,o]=Kt(),i={[n]:o,...this._options.headers},s={abortSignal:this._pollAbort.signal,headers:i,timeout:1e5,withCredentials:this._options.withCredentials};r===ue.Binary&&(s.responseType="arraybuffer");let a=`${t}&_=${Date.now()}`;this._logger.log(m.Trace,`(LongPolling transport) polling: ${a}.`);let c=await this._httpClient.get(a,s);c.statusCode!==200?(this._logger.log(m.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ot(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,s)}async _poll(t,r){try{for(;this._running;)try{let n=`${t}&_=${Date.now()}`;this._logger.log(m.Trace,`(LongPolling transport) polling: ${n}.`);let o=await this._httpClient.get(n,r);o.statusCode===204?(this._logger.log(m.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):o.statusCode!==200?(this._logger.log(m.Error,`(LongPolling transport) Unexpected response code: ${o.statusCode}.`),this._closeError=new ot(o.statusText||"",o.statusCode),this._running=!1):o.content?(this._logger.log(m.Trace,`(LongPolling transport) data received. ${Br(o.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(o.content)):this._logger.log(m.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(n){this._running?n instanceof Or?this._logger.log(m.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=n,this._running=!1):this._logger.log(m.Trace,`(LongPolling transport) Poll errored after shutdown: ${n.message}`)}}finally{this._logger.log(m.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(t){return this._running?ic(this._logger,"LongPolling",this._httpClient,this._url,t,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(m.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(m.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);let t={},[r,n]=Kt();t[r]=n;let o={headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials},i;try{await this._httpClient.delete(this._url,o)}catch(s){i=s}i?i instanceof ot&&(i.statusCode===404?this._logger.log(m.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(m.Trace,`(LongPolling transport) Error sending a DELETE request: ${i}`)):this._logger.log(m.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(m.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let t="(LongPolling transport) Firing onclose event.";this._closeError&&(t+=" Error: "+this._closeError),this._logger.log(m.Trace,t),this.onclose(this._closeError)}}};var gc=class{constructor(t,r,n,o){this._httpClient=t,this._accessToken=r,this._logger=n,this._options=o,this.onreceive=null,this.onclose=null}async connect(t,r){return $.isRequired(t,"url"),$.isRequired(r,"transferFormat"),$.isIn(r,ue,"transferFormat"),this._logger.log(m.Trace,"(SSE transport) Connecting."),this._url=t,this._accessToken&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise((n,o)=>{let i=!1;if(r!==ue.Text){o(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));return}let s;if(q.isBrowser||q.isWebWorker)s=new this._options.EventSource(t,{withCredentials:this._options.withCredentials});else{let a=this._httpClient.getCookieString(t),c={};c.Cookie=a;let[l,h]=Kt();c[l]=h,s=new this._options.EventSource(t,{withCredentials:this._options.withCredentials,headers:{...c,...this._options.headers}})}try{s.onmessage=a=>{if(this.onreceive)try{this._logger.log(m.Trace,`(SSE transport) data received. ${Br(a.data,this._options.logMessageContent)}.`),this.onreceive(a.data)}catch(c){this._close(c);return}},s.onerror=a=>{i?this._close():o(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},s.onopen=()=>{this._logger.log(m.Information,`SSE connected to ${this._url}`),this._eventSource=s,i=!0,n()}}catch(a){o(a);return}})}async send(t){return this._eventSource?ic(this._logger,"SSE",this._httpClient,this._url,t,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(t){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(t))}};var yc=class{constructor(t,r,n,o,i,s){this._logger=n,this._accessTokenFactory=r,this._logMessageContent=o,this._webSocketConstructor=i,this._httpClient=t,this.onreceive=null,this.onclose=null,this._headers=s}async connect(t,r){$.isRequired(t,"url"),$.isRequired(r,"transferFormat"),$.isIn(r,ue,"transferFormat"),this._logger.log(m.Trace,"(WebSockets transport) Connecting.");let n;return this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise((o,i)=>{t=t.replace(/^http/,"ws");let s,a=this._httpClient.getCookieString(t),c=!1;if(q.isNode||q.isReactNative){let l={},[h,u]=Kt();l[h]=u,n&&(l[Mt.Authorization]=`Bearer ${n}`),a&&(l[Mt.Cookie]=a),s=new this._webSocketConstructor(t,void 0,{headers:{...l,...this._headers}})}else n&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);s||(s=new this._webSocketConstructor(t)),r===ue.Binary&&(s.binaryType="arraybuffer"),s.onopen=l=>{this._logger.log(m.Information,`WebSocket connected to ${t}.`),this._webSocket=s,c=!0,o()},s.onerror=l=>{let h=null;typeof ErrorEvent<"u"&&l instanceof ErrorEvent?h=l.error:h="There was an error with the transport",this._logger.log(m.Information,`(WebSockets transport) ${h}.`)},s.onmessage=l=>{if(this._logger.log(m.Trace,`(WebSockets transport) data received. ${Br(l.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(l.data)}catch(h){this._close(h);return}},s.onclose=l=>{if(c)this._close(l);else{let h=null;typeof ErrorEvent<"u"&&l instanceof ErrorEvent?h=l.error:h="WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",i(new Error(h))}}})}send(t){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(m.Trace,`(WebSockets transport) sending data. ${Br(t,this._logMessageContent)}.`),this._webSocket.send(t),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(t){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(m.Trace,"(WebSockets transport) socket closed."),this.onclose&&(this._isCloseEvent(t)&&(t.wasClean===!1||t.code!==1e3)?this.onclose(new Error(`WebSocket closed with status code: ${t.code} (${t.reason||"no reason given"}).`)):t instanceof Error?this.onclose(t):this.onclose())}_isCloseEvent(t){return t&&typeof t.wasClean=="boolean"&&typeof t.code=="number"}};var X0=100,bc=class{constructor(t,r={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,$.isRequired(t,"url"),this._logger=q0(r.logger),this.baseUrl=this._resolveUrl(t),r=r||{},r.logMessageContent=r.logMessageContent===void 0?!1:r.logMessageContent,typeof r.withCredentials=="boolean"||r.withCredentials===void 0)r.withCredentials=r.withCredentials===void 0?!0:r.withCredentials;else throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");r.timeout=r.timeout===void 0?100*1e3:r.timeout;let n=null,o=null;if(q.isNode&&typeof mn<"u"){let i=typeof __webpack_require__=="function"?__non_webpack_require__:mn;n=i("ws"),o=i("eventsource")}!q.isNode&&typeof WebSocket<"u"&&!r.WebSocket?r.WebSocket=WebSocket:q.isNode&&!r.WebSocket&&n&&(r.WebSocket=n),!q.isNode&&typeof EventSource<"u"&&!r.EventSource?r.EventSource=EventSource:q.isNode&&!r.EventSource&&typeof o<"u"&&(r.EventSource=o),this._httpClient=new fc(r.httpClient||new lc(this._logger),r.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=r,this.onreceive=null,this.onclose=null}async start(t){if(t=t||ue.Binary,$.isIn(t,ue,"transferFormat"),this._logger.log(m.Debug,`Starting connection with transfer format '${ue[t]}'.`),this._connectionState!=="Disconnected")return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(t),await this._startInternalPromise,this._connectionState==="Disconnecting"){let r="Failed to start the HttpConnection before stop() was called.";return this._logger.log(m.Error,r),await this._stopPromise,Promise.reject(new xe(r))}else if(this._connectionState!=="Connected"){let r="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(m.Error,r),Promise.reject(new xe(r))}this._connectionStarted=!0}send(t){return this._connectionState!=="Connected"?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new Ku(this.transport)),this._sendQueue.send(t))}async stop(t){if(this._connectionState==="Disconnected")return this._logger.log(m.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnected state.`),Promise.resolve();if(this._connectionState==="Disconnecting")return this._logger.log(m.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;this._connectionState="Disconnecting",this._stopPromise=new Promise(r=>{this._stopPromiseResolver=r}),await this._stopInternal(t),await this._stopPromise}async _stopInternal(t){this._stopError=t;try{await this._startInternalPromise}catch{}if(this.transport){try{await this.transport.stop()}catch(r){this._logger.log(m.Error,`HttpConnection.transport.stop() threw error '${r}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(m.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(t){let r=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation)if(this._options.transport===ie.WebSockets)this.transport=this._constructTransport(ie.WebSockets),await this._startTransport(r,t);else throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");else{let n=null,o=0;do{if(n=await this._getNegotiationResponse(r),this._connectionState==="Disconnecting"||this._connectionState==="Disconnected")throw new xe("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(r=n.url),n.accessToken){let i=n.accessToken;this._accessTokenFactory=()=>i,this._httpClient._accessToken=i,this._httpClient._accessTokenFactory=void 0}o++}while(n.url&&o<X0);if(o===X0&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(r,this._options.transport,n,t)}this.transport instanceof wi&&(this.features.inherentKeepAlive=!0),this._connectionState==="Connecting"&&(this._logger.log(m.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(n){return this._logger.log(m.Error,"Failed to start the connection: "+n),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(n)}}async _getNegotiationResponse(t){let r={},[n,o]=Kt();r[n]=o;let i=this._resolveNegotiateUrl(t);this._logger.log(m.Debug,`Sending negotiation request: ${i}.`);try{let s=await this._httpClient.post(i,{content:"",headers:{...r,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(s.statusCode!==200)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${s.statusCode}'`));let a=JSON.parse(s.content);return(!a.negotiateVersion||a.negotiateVersion<1)&&(a.connectionToken=a.connectionId),a.useStatefulReconnect&&this._options._useStatefulReconnect!==!0?Promise.reject(new yi("Client didn't negotiate Stateful Reconnect but the server did.")):a}catch(s){let a="Failed to complete negotiation with the server: "+s;return s instanceof ot&&s.statusCode===404&&(a=a+" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(m.Error,a),Promise.reject(new yi(a))}}_createConnectUrl(t,r){return r?t+(t.indexOf("?")===-1?"?":"&")+`id=${r}`:t}async _createTransport(t,r,n,o){let i=this._createConnectUrl(t,n.connectionToken);if(this._isITransport(r)){this._logger.log(m.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=r,await this._startTransport(i,o),this.connectionId=n.connectionId;return}let s=[],a=n.availableTransports||[],c=n;for(let l of a){let h=this._resolveTransportOrError(l,r,o,c?.useStatefulReconnect===!0);if(h instanceof Error)s.push(`${l.transport} failed:`),s.push(h);else if(this._isITransport(h)){if(this.transport=h,!c){try{c=await this._getNegotiationResponse(t)}catch(u){return Promise.reject(u)}i=this._createConnectUrl(t,c.connectionToken)}try{await this._startTransport(i,o),this.connectionId=c.connectionId;return}catch(u){if(this._logger.log(m.Error,`Failed to start the transport '${l.transport}': ${u}`),c=void 0,s.push(new rc(`${l.transport} failed: ${u}`,ie[l.transport])),this._connectionState!=="Connecting"){let p="Failed to select transport before stop() was called.";return this._logger.log(m.Debug,p),Promise.reject(new xe(p))}}}}return s.length>0?Promise.reject(new nc(`Unable to connect to the server with any of the available transports. ${s.join(" ")}`,s)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(t){switch(t){case ie.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new yc(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case ie.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new gc(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case ie.LongPolling:return new wi(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${t}.`)}}_startTransport(t,r){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async n=>{let o=!1;if(this.features.reconnect)try{this.features.disconnected(),await this.transport.connect(t,r),await this.features.resend()}catch{o=!0}else{this._stopConnection(n);return}o&&this._stopConnection(n)}:this.transport.onclose=n=>this._stopConnection(n),this.transport.connect(t,r)}_resolveTransportOrError(t,r,n,o){let i=ie[t.transport];if(i==null)return this._logger.log(m.Debug,`Skipping transport '${t.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${t.transport}' because it is not supported by this client.`);if(mw(r,i))if(t.transferFormats.map(a=>ue[a]).indexOf(n)>=0){if(i===ie.WebSockets&&!this._options.WebSocket||i===ie.ServerSentEvents&&!this._options.EventSource)return this._logger.log(m.Debug,`Skipping transport '${ie[i]}' because it is not supported in your environment.'`),new ec(`'${ie[i]}' is not supported in your environment.`,i);this._logger.log(m.Debug,`Selecting transport '${ie[i]}'.`);try{return this.features.reconnect=i===ie.WebSockets?o:void 0,this._constructTransport(i)}catch(a){return a}}else return this._logger.log(m.Debug,`Skipping transport '${ie[i]}' because it does not support the requested transfer format '${ue[n]}'.`),new Error(`'${ie[i]}' does not support ${ue[n]}.`);else return this._logger.log(m.Debug,`Skipping transport '${ie[i]}' because it was disabled by the client.`),new tc(`'${ie[i]}' is disabled by the client.`,i)}_isITransport(t){return t&&typeof t=="object"&&"connect"in t}_stopConnection(t){if(this._logger.log(m.Debug,`HttpConnection.stopConnection(${t}) called while in state ${this._connectionState}.`),this.transport=void 0,t=this._stopError||t,this._stopError=void 0,this._connectionState==="Disconnected"){this._logger.log(m.Debug,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is already in the disconnected state.`);return}if(this._connectionState==="Connecting")throw this._logger.log(m.Warning,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${t}) was called while the connection is still in the connecting state.`);if(this._connectionState==="Disconnecting"&&this._stopPromiseResolver(),t?this._logger.log(m.Error,`Connection disconnected with error '${t}'.`):this._logger.log(m.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch(r=>{this._logger.log(m.Error,`TransportSendQueue.stop() threw error '${r}'.`)}),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(t)}catch(r){this._logger.log(m.Error,`HttpConnection.onclose(${t}) threw error '${r}'.`)}}}_resolveUrl(t){if(t.lastIndexOf("https://",0)===0||t.lastIndexOf("http://",0)===0)return t;if(!q.isBrowser)throw new Error(`Cannot resolve '${t}'.`);let r=window.document.createElement("a");return r.href=t,this._logger.log(m.Information,`Normalizing '${t}' to '${r.href}'.`),r.href}_resolveNegotiateUrl(t){let r=new URL(t);r.pathname.endsWith("/")?r.pathname+="negotiate":r.pathname+="/negotiate";let n=new URLSearchParams(r.searchParams);return n.has("negotiateVersion")||n.append("negotiateVersion",this._negotiateVersion.toString()),n.has("useStatefulReconnect")?n.get("useStatefulReconnect")==="true"&&(this._options._useStatefulReconnect=!0):this._options._useStatefulReconnect===!0&&n.append("useStatefulReconnect","true"),r.search=n.toString(),r.toString()}};function mw(e,t){return!e||(t&e)!==0}var Ku=class e{constructor(t){this._transport=t,this._buffer=[],this._executing=!0,this._sendBufferedData=new fo,this._transportResult=new fo,this._sendLoopPromise=this._sendLoop()}send(t){return this._bufferData(t),this._transportResult||(this._transportResult=new fo),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(t){if(this._buffer.length&&typeof this._buffer[0]!=typeof t)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof t}`);this._buffer.push(t),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new fo;let t=this._transportResult;this._transportResult=void 0;let r=typeof this._buffer[0]=="string"?this._buffer.join(""):e._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(r),t.resolve()}catch(n){t.reject(n)}}}static _concatBuffers(t){let r=t.map(i=>i.byteLength).reduce((i,s)=>i+s),n=new Uint8Array(r),o=0;for(let i of t)n.set(new Uint8Array(i),o),o+=i.byteLength;return n.buffer}},fo=class{constructor(){this.promise=new Promise((t,r)=>[this._resolver,this._rejecter]=[t,r])}resolve(){this._resolver()}reject(t){this._rejecter(t)}};var gw="json",wc=class{constructor(){this.name=gw,this.version=2,this.transferFormat=ue.Text}parseMessages(t,r){if(typeof t!="string")throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!t)return[];r===null&&(r=Gt.instance);let n=it.parse(t),o=[];for(let i of n){let s=JSON.parse(i);if(typeof s.type!="number")throw new Error("Invalid payload.");switch(s.type){case D.Invocation:this._isInvocationMessage(s);break;case D.StreamItem:this._isStreamItemMessage(s);break;case D.Completion:this._isCompletionMessage(s);break;case D.Ping:break;case D.Close:break;case D.Ack:this._isAckMessage(s);break;case D.Sequence:this._isSequenceMessage(s);break;default:r.log(m.Information,"Unknown message type '"+s.type+"' ignored.");continue}o.push(s)}return o}writeMessage(t){return it.write(JSON.stringify(t))}_isInvocationMessage(t){this._assertNotEmptyString(t.target,"Invalid payload for Invocation message."),t.invocationId!==void 0&&this._assertNotEmptyString(t.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(t){if(this._assertNotEmptyString(t.invocationId,"Invalid payload for StreamItem message."),t.item===void 0)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(t){if(t.result&&t.error)throw new Error("Invalid payload for Completion message.");!t.result&&t.error&&this._assertNotEmptyString(t.error,"Invalid payload for Completion message."),this._assertNotEmptyString(t.invocationId,"Invalid payload for Completion message.")}_isAckMessage(t){if(typeof t.sequenceId!="number")throw new Error("Invalid SequenceId for Ack message.")}_isSequenceMessage(t){if(typeof t.sequenceId!="number")throw new Error("Invalid SequenceId for Sequence message.")}_assertNotEmptyString(t,r){if(typeof t!="string"||t==="")throw new Error(r)}};var yw={trace:m.Trace,debug:m.Debug,info:m.Information,information:m.Information,warn:m.Warning,warning:m.Warning,error:m.Error,critical:m.Critical,none:m.None};function bw(e){let t=yw[e.toLowerCase()];if(typeof t<"u")return t;throw new Error(`Unknown log level: ${e}`)}var vi=class{configureLogging(t){if($.isRequired(t,"logging"),ww(t))this.logger=t;else if(typeof t=="string"){let r=bw(t);this.logger=new an(r)}else this.logger=new an(t);return this}withUrl(t,r){return $.isRequired(t,"url"),$.isNotEmpty(t,"url"),this.url=t,typeof r=="object"?this.httpConnectionOptions={...this.httpConnectionOptions,...r}:this.httpConnectionOptions={...this.httpConnectionOptions,transport:r},this}withHubProtocol(t){return $.isRequired(t,"protocol"),this.protocol=t,this}withAutomaticReconnect(t){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return t?Array.isArray(t)?this.reconnectPolicy=new bi(t):this.reconnectPolicy=t:this.reconnectPolicy=new bi,this}withServerTimeout(t){return $.isRequired(t,"milliseconds"),this._serverTimeoutInMilliseconds=t,this}withKeepAliveInterval(t){return $.isRequired(t,"milliseconds"),this._keepAliveIntervalInMilliseconds=t,this}withStatefulReconnect(t){return this.httpConnectionOptions===void 0&&(this.httpConnectionOptions={}),this.httpConnectionOptions._useStatefulReconnect=!0,this._statefulReconnectBufferSize=t?.bufferSize,this}build(){let t=this.httpConnectionOptions||{};if(t.logger===void 0&&(t.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");let r=new bc(this.url,t);return pc.create(r,this.logger||Gt.instance,this.protocol||new wc,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}};function ww(e){return e.log!==void 0}var J2=Od(X2());var vo=class{},Y2=(s=>(s[s.WAITING=-1]="WAITING",s[s.STARTED=0]="STARTED",s[s.QR_CODE=1]="QR_CODE",s[s.POSITION=2]="POSITION",s[s.FINISHED=3]="FINISHED",s[s.ERROR=9]="ERROR",s))(Y2||{}),Rc=class e{constructor(t,r){this.proctoringId="";this.capturePhotoUrl="";this.qrCodeBase64Image="";this.transmissionOk=!1;this.waitingPositionValidation=!1;this.externalSessionId=null;this.currentStep=0;this.connection=null;this.context=t,this.onRealtimeAlertsCallback=r,console.log("context -> ",t),this.backend=new ft({type:t?.type||"prod",token:t.token}),this.currentStep=-1}static{this.isModalOpen=!1}getExternalCameraSessionId(){return""+this.externalSessionId}async checkTransmission(){try{this.transmissionOk=!1;let t=await this.backend.externalCameraCheckTransmission(""+this.externalSessionId);console.log(t);let r=0;for(;!this.transmissionOk&&r<=5;)await new Promise(n=>setTimeout(n,2e3)),r=r+1;if(!this.transmissionOk)throw new Error("Timed out na checagem da transmiss\xE3o!")}catch(t){throw console.error("Erro ao checar a transmiss\xE3o:",t),new Error("N\xE3o foi poss\xEDvel checar a transmiss\xE3o."+t)}}async startTransmission(t){try{this.proctoringId=t;let r=await this.backend.externalCameraStartTransmission(""+this.externalSessionId,t);console.log(r)}catch(r){throw console.error("Erro ao iniciar transmiss\xE3o:",r),new Error("N\xE3o foi poss\xEDvel iniciar a transmiss\xE3o.")}}async goToPositionGuide(){if(this.connection){let t=new vo;t.command="Position_Guide",console.log("Enviando comando 'Position_Guide' para o aplicativo..."),this.connection.invoke("SendAction",this.externalSessionId,t)}}async reset(){if(this.connection){let t=new vo;t.command="Reset",console.log("Enviando comando 'Reset' para o aplicativo..."),this.connection.invoke("SendAction",this.externalSessionId,t)}}async takePicture(t,r){if(this.connection){this.waitingPositionValidation=t,this.onTakePictureCallback=r;let n=new vo;n.command="Capture",console.log("Enviando comando 'Capture' para o aplicativo..."),this.connection.invoke("SendAction",this.externalSessionId,n)}else throw new Error("N\xE3o existe conex\xE3o de camera externa ativa.")}async startSession(t){try{this.onQrCodeReadedCallback=t,this.connection&&this.disconnectWebSocket(),this.initializeWebSocketConnection(),await this.reset();let r=await this.backend.externalCameraStartSession();this.externalSessionId=r.externalSessionId,console.log(this.externalSessionId),this.currentStep=0;let n={externalSessionId:this.externalSessionId,token:this.context.token,ambient:this.context.type},o=JSON.stringify(n);return this.qrCodeBase64Image=await J2.default.toDataURL(o),console.log(this.qrCodeBase64Image),this.qrCodeBase64Image}catch(r){return this.disconnectWebSocket(),Promise.reject(r)}}async checkExternalCamera(){if(this.currentStep=0,e.isModalOpen)return Promise.reject("O modal de verifica\xE7\xE3o j\xE1 est\xE1 aberto.");e.isModalOpen=!0;try{return await this.startSession(()=>{}),await this.buildInterface()}catch(t){return console.error("Erro ao iniciar verifica\xE7\xE3o:",t),this.closeCheckExternalCamera(),Promise.reject(t)}}buildInterface(){return new Promise((t,r)=>{this.resolvePromise=t;let n=document.createElement("div");n.setAttribute("id","externalCameraCheck"),this.applyStyles(n,{backgroundColor:"rgba(0,0,0,0.4)",zIndex:"1000",position:"fixed",top:"0",left:"0",height:"100vh",width:"100%",display:"flex",alignItems:"center",justifyContent:"center"});let o=document.createElement("div");this.applyStyles(o,{backgroundColor:"#fff",zIndex:"1001",width:"500px",borderRadius:"10px",display:"flex",flexDirection:"column",alignItems:"center"});let i=document.createElement("h3");i.innerText="Conectar dispositivo m\xF3vel",this.applyStyles(i,{color:"rgba(0, 0, 0, .7)",fontWeight:"bold",fontSize:"20px",marginBottom:"15px",padding:"20px 0px",borderBottom:"2px solid rgba(0, 0, 0, .1)",width:"100%",textAlign:"center"});let s=document.createElement("div");s.id="external-camera-content",this.applyStyles(s,{width:"100%",padding:"20px 40px",boxSizing:"border-box",minHeight:"300px",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center"});let a=document.createElement("div");this.applyStyles(a,{width:"100%",display:"flex",alignItems:"center",justifyContent:"center",borderTop:"2px solid rgba(0, 0, 0, .1)"});let c=document.createElement("button");c.innerText="Cancelar",this.applyStyles(c,{width:"100%",height:"70px",backgroundColor:"#FFF",border:"none",color:"rgba(0, 0, 0, .7)",fontWeight:"bold",borderRadius:"0 0 0 10px",cursor:"pointer"}),c.addEventListener("click",()=>{let h=new vo;h.command="Cancel",console.log("Enviando comando 'Cancel' para o aplicativo..."),this.connection?.invoke("SendAction",this.externalSessionId,h),this.closeCheckExternalCamera(),t({result:!1})});let l=document.createElement("button");l.innerText="Continuar",l.id="external-camera-continue",this.applyStyles(l,{width:"100%",height:"70px",backgroundColor:"#FFF",border:"none",color:"rgba(0, 0, 0, .7)",fontWeight:"bold",borderRadius:"0 0 10px 0",cursor:"pointer",borderLeft:"2px solid rgba(0, 0, 0, .1)"}),a.appendChild(c),a.appendChild(l),o.appendChild(i),o.appendChild(s),o.appendChild(a),n.appendChild(o),document.body.appendChild(n),this.renderCurrentStep()})}renderCurrentStep(){let t=document.getElementById("external-camera-content");if(t)switch(t.innerHTML="",this.currentStep){case 0:this.renderQRCodeStep(t);break;case 1:this.renderPhotoStep(t);break;case 2:this.renderImageStep(t);break;default:break}}renderQRCodeStep(t){let r=document.createElement("canvas");r.id="qr-code-canvas";let n=document.createElement("p");n.innerText="Aponte a c\xE2mera do seu celular para o QR Code para iniciar a verifica\xE7\xE3o do ambiente.",this.applyStyles(n,{textAlign:"center",color:"#555",marginTop:"20px"});let o=r.getContext("2d"),i=new Image;i.onload=()=>{let c=250/i.width,l=i.height*c;r.width=250,r.height=l,o&&o.drawImage(i,0,0,250,l)},i.src=this.qrCodeBase64Image,t.appendChild(r),t.appendChild(n);let s=document.getElementById("external-camera-continue");s.disabled=!0,this.applyStyles(s,{color:"#ccc",cursor:"not-allowed"})}renderPhotoStep(t){let r=document.createElement("p");r.id="photo-message",r.innerText="Clique no bot\xE3o abaixo para realizar a captura da foto do ambiente.",this.applyStyles(r,{textAlign:"center",color:"#555",marginBottom:"20px",fontSize:"14px",display:"-webkit-box",overflow:"hidden",textOverflow:"ellipsis"}),r.style.webkitLineClamp="3",r.style.webkitBoxOrient="vertical",t.appendChild(r);let n=document.createElement("div");n.id="photo-error-banner",n.innerText="Foto fora do padr\xE3o esperado.",this.applyStyles(n,{backgroundColor:"#FEE2E2",color:"#DC2626",padding:"12px 15px",borderRadius:"8px",textAlign:"center",fontSize:"12px",fontWeight:"400",marginBottom:"15px",display:"none"}),t.appendChild(n);let o=document.createElement("div");this.applyStyles(o,{backgroundColor:"#fff",borderRadius:"8px",padding:"20px",display:"flex",gap:"20px",alignItems:"flex-start",border:"1px solid #e5e5e5",marginBottom:"20px"});let i=document.createElement("div");if(i.id="photo-icon-container",this.applyStyles(i,{backgroundColor:"#f5f5f5",borderRadius:"8px",width:"120px",height:"160px",minWidth:"120px",minHeight:"160px",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:"0",overflow:"hidden"}),this.capturePhotoUrl&&this.capturePhotoUrl.trim()!==""){let g=document.createElement("img");g.id="img-photo";let b=this.capturePhotoUrl.startsWith("data:")?this.capturePhotoUrl:"data:image/jpeg;base64,"+this.capturePhotoUrl;g.src=b,this.applyStyles(g,{width:"100%",height:"100%",objectFit:"contain",objectPosition:"center",borderRadius:"8px",display:"block"}),i.appendChild(g)}else{let g=document.createElement("div");g.innerHTML=`
304
+ `,o=document.createElement("style");o.innerHTML=n,document.head.appendChild(o)}};var ot=class extends Error{constructor(t,r){let n=new.target.prototype;super(`${t}: Status code '${r}'`),this.statusCode=r,this.__proto__=n}},Or=class extends Error{constructor(t="A timeout occurred."){let r=new.target.prototype;super(t),this.__proto__=r}},xe=class extends Error{constructor(t="An abort occurred."){let r=new.target.prototype;super(t),this.__proto__=r}},ec=class extends Error{constructor(t,r){let n=new.target.prototype;super(t),this.transport=r,this.errorType="UnsupportedTransportError",this.__proto__=n}},tc=class extends Error{constructor(t,r){let n=new.target.prototype;super(t),this.transport=r,this.errorType="DisabledTransportError",this.__proto__=n}},rc=class extends Error{constructor(t,r){let n=new.target.prototype;super(t),this.transport=r,this.errorType="FailedToStartTransportError",this.__proto__=n}},yi=class extends Error{constructor(t){let r=new.target.prototype;super(t),this.errorType="FailedToNegotiateWithServerError",this.__proto__=r}},nc=class extends Error{constructor(t,r){let n=new.target.prototype;super(t),this.innerErrors=r,this.__proto__=n}};var po=class{constructor(t,r,n){this.statusCode=t,this.statusText=r,this.content=n}},qt=class{get(t,r){return this.send({...r,method:"GET",url:t})}post(t,r){return this.send({...r,method:"POST",url:t})}delete(t,r){return this.send({...r,method:"DELETE",url:t})}getCookieString(t){return""}};var m;(function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"})(m||(m={}));var Gt=class{constructor(){}log(t,r){}};Gt.instance=new Gt;var W0="9.0.6";var $=class{static isRequired(t,r){if(t==null)throw new Error(`The '${r}' argument is required.`)}static isNotEmpty(t,r){if(!t||t.match(/^\s*$/))throw new Error(`The '${r}' argument should not be empty.`)}static isIn(t,r,n){if(!(t in r))throw new Error(`Unknown ${n} value: ${t}.`)}},q=class e{static get isBrowser(){return!e.isNode&&typeof window=="object"&&typeof window.document=="object"}static get isWebWorker(){return!e.isNode&&typeof self=="object"&&"importScripts"in self}static get isReactNative(){return!e.isNode&&typeof window=="object"&&typeof window.document>"u"}static get isNode(){return typeof process<"u"&&process.release&&process.release.name==="node"}};function Br(e,t){let r="";return Bt(e)?(r=`Binary data of length ${e.byteLength}`,t&&(r+=`. Content: '${sw(e)}'`)):typeof e=="string"&&(r=`String data of length ${e.length}`,t&&(r+=`. Content: '${e}'`)),r}function sw(e){let t=new Uint8Array(e),r="";return t.forEach(n=>{let o=n<16?"0":"";r+=`0x${o}${n.toString(16)} `}),r.substr(0,r.length-1)}function Bt(e){return e&&typeof ArrayBuffer<"u"&&(e instanceof ArrayBuffer||e.constructor&&e.constructor.name==="ArrayBuffer")}async function ic(e,t,r,n,o,i){let s={},[a,c]=Kt();s[a]=c,e.log(m.Trace,`(${t} transport) sending data. ${Br(o,i.logMessageContent)}.`);let l=Bt(o)?"arraybuffer":"text",h=await r.post(n,{content:o,headers:{...s,...i.headers},responseType:l,timeout:i.timeout,withCredentials:i.withCredentials});e.log(m.Trace,`(${t} transport) request complete. Response status: ${h.statusCode}.`)}function q0(e){return e===void 0?new an(m.Information):e===null?Gt.instance:e.log!==void 0?e:new an(e)}var oc=class{constructor(t,r){this._subject=t,this._observer=r}dispose(){let t=this._subject.observers.indexOf(this._observer);t>-1&&this._subject.observers.splice(t,1),this._subject.observers.length===0&&this._subject.cancelCallback&&this._subject.cancelCallback().catch(r=>{})}},an=class{constructor(t){this._minLevel=t,this.out=console}log(t,r){if(t>=this._minLevel){let n=`[${new Date().toISOString()}] ${m[t]}: ${r}`;switch(t){case m.Critical:case m.Error:this.out.error(n);break;case m.Warning:this.out.warn(n);break;case m.Information:this.out.info(n);break;default:this.out.log(n);break}}}};function Kt(){let e="X-SignalR-User-Agent";return q.isNode&&(e="User-Agent"),[e,aw(W0,cw(),hw(),lw())]}function aw(e,t,r,n){let o="Microsoft SignalR/",i=e.split(".");return o+=`${i[0]}.${i[1]}`,o+=` (${e}; `,t&&t!==""?o+=`${t}; `:o+="Unknown OS; ",o+=`${r}`,n?o+=`; ${n}`:o+="; Unknown Runtime Version",o+=")",o}function cw(){if(q.isNode)switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}else return""}function lw(){if(q.isNode)return process.versions.node}function hw(){return q.isNode?"NodeJS":"Browser"}function sc(e){return e.stack?e.stack:e.message?e.message:`${e}`}function G0(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("could not find global")}var ac=class extends qt{constructor(t){if(super(),this._logger=t,typeof fetch>"u"||q.isNode){let r=typeof __webpack_require__=="function"?__non_webpack_require__:mn;this._jar=new(r("tough-cookie")).CookieJar,typeof fetch>"u"?this._fetchType=r("node-fetch"):this._fetchType=fetch,this._fetchType=r("fetch-cookie")(this._fetchType,this._jar)}else this._fetchType=fetch.bind(G0());if(typeof AbortController>"u"){let r=typeof __webpack_require__=="function"?__non_webpack_require__:mn;this._abortControllerType=r("abort-controller")}else this._abortControllerType=AbortController}async send(t){if(t.abortSignal&&t.abortSignal.aborted)throw new xe;if(!t.method)throw new Error("No method defined.");if(!t.url)throw new Error("No url defined.");let r=new this._abortControllerType,n;t.abortSignal&&(t.abortSignal.onabort=()=>{r.abort(),n=new xe});let o=null;if(t.timeout){let c=t.timeout;o=setTimeout(()=>{r.abort(),this._logger.log(m.Warning,"Timeout from HTTP request."),n=new Or},c)}t.content===""&&(t.content=void 0),t.content&&(t.headers=t.headers||{},Bt(t.content)?t.headers["Content-Type"]="application/octet-stream":t.headers["Content-Type"]="text/plain;charset=UTF-8");let i;try{i=await this._fetchType(t.url,{body:t.content,cache:"no-cache",credentials:t.withCredentials===!0?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...t.headers},method:t.method,mode:"cors",redirect:"follow",signal:r.signal})}catch(c){throw n||(this._logger.log(m.Warning,`Error from HTTP request. ${c}.`),c)}finally{o&&clearTimeout(o),t.abortSignal&&(t.abortSignal.onabort=null)}if(!i.ok){let c=await K0(i,"text");throw new ot(c||i.statusText,i.status)}let a=await K0(i,t.responseType);return new po(i.status,i.statusText,a)}getCookieString(t){let r="";return q.isNode&&this._jar&&this._jar.getCookies(t,(n,o)=>r=o.join("; ")),r}};function K0(e,t){let r;switch(t){case"arraybuffer":r=e.arrayBuffer();break;case"text":r=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`);default:r=e.text();break}return r}var cc=class extends qt{constructor(t){super(),this._logger=t}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new xe):t.method?t.url?new Promise((r,n)=>{let o=new XMLHttpRequest;o.open(t.method,t.url,!0),o.withCredentials=t.withCredentials===void 0?!0:t.withCredentials,o.setRequestHeader("X-Requested-With","XMLHttpRequest"),t.content===""&&(t.content=void 0),t.content&&(Bt(t.content)?o.setRequestHeader("Content-Type","application/octet-stream"):o.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));let i=t.headers;i&&Object.keys(i).forEach(s=>{o.setRequestHeader(s,i[s])}),t.responseType&&(o.responseType=t.responseType),t.abortSignal&&(t.abortSignal.onabort=()=>{o.abort(),n(new xe)}),t.timeout&&(o.timeout=t.timeout),o.onload=()=>{t.abortSignal&&(t.abortSignal.onabort=null),o.status>=200&&o.status<300?r(new po(o.status,o.statusText,o.response||o.responseText)):n(new ot(o.response||o.responseText||o.statusText,o.status))},o.onerror=()=>{this._logger.log(m.Warning,`Error from HTTP request. ${o.status}: ${o.statusText}.`),n(new ot(o.statusText,o.status))},o.ontimeout=()=>{this._logger.log(m.Warning,"Timeout from HTTP request."),n(new Or)},o.send(t.content)}):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}};var lc=class extends qt{constructor(t){if(super(),typeof fetch<"u"||q.isNode)this._httpClient=new ac(t);else if(typeof XMLHttpRequest<"u")this._httpClient=new cc(t);else throw new Error("No usable HttpClient found.")}send(t){return t.abortSignal&&t.abortSignal.aborted?Promise.reject(new xe):t.method?t.url?this._httpClient.send(t):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(t){return this._httpClient.getCookieString(t)}};var it=class e{static write(t){return`${t}${e.RecordSeparator}`}static parse(t){if(t[t.length-1]!==e.RecordSeparator)throw new Error("Message is incomplete.");let r=t.split(e.RecordSeparator);return r.pop(),r}};it.RecordSeparatorCode=30;it.RecordSeparator=String.fromCharCode(it.RecordSeparatorCode);var hc=class{writeHandshakeRequest(t){return it.write(JSON.stringify(t))}parseHandshakeResponse(t){let r,n;if(Bt(t)){let a=new Uint8Array(t),c=a.indexOf(it.RecordSeparatorCode);if(c===-1)throw new Error("Message is incomplete.");let l=c+1;r=String.fromCharCode.apply(null,Array.prototype.slice.call(a.slice(0,l))),n=a.byteLength>l?a.slice(l).buffer:null}else{let a=t,c=a.indexOf(it.RecordSeparator);if(c===-1)throw new Error("Message is incomplete.");let l=c+1;r=a.substring(0,l),n=a.length>l?a.substring(l):null}let o=it.parse(r),i=JSON.parse(o[0]);if(i.type)throw new Error("Expected a handshake response from the server.");return[n,i]}};var D;(function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close",e[e.Ack=8]="Ack",e[e.Sequence=9]="Sequence"})(D||(D={}));var uc=class{constructor(){this.observers=[]}next(t){for(let r of this.observers)r.next(t)}error(t){for(let r of this.observers)r.error&&r.error(t)}complete(){for(let t of this.observers)t.complete&&t.complete()}subscribe(t){return this.observers.push(t),new oc(this,t)}};var dc=class{constructor(t,r,n){this._bufferSize=1e5,this._messages=[],this._totalMessageCount=0,this._waitForSequenceMessage=!1,this._nextReceivingSequenceId=1,this._latestReceivedSequenceId=0,this._bufferedByteCount=0,this._reconnectInProgress=!1,this._protocol=t,this._connection=r,this._bufferSize=n}async _send(t){let r=this._protocol.writeMessage(t),n=Promise.resolve();if(this._isInvocationMessage(t)){this._totalMessageCount++;let o=()=>{},i=()=>{};Bt(r)?this._bufferedByteCount+=r.byteLength:this._bufferedByteCount+=r.length,this._bufferedByteCount>=this._bufferSize&&(n=new Promise((s,a)=>{o=s,i=a})),this._messages.push(new Gu(r,this._totalMessageCount,o,i))}try{this._reconnectInProgress||await this._connection.send(r)}catch{this._disconnected()}await n}_ack(t){let r=-1;for(let n=0;n<this._messages.length;n++){let o=this._messages[n];if(o._id<=t.sequenceId)r=n,Bt(o._message)?this._bufferedByteCount-=o._message.byteLength:this._bufferedByteCount-=o._message.length,o._resolver();else if(this._bufferedByteCount<this._bufferSize)o._resolver();else break}r!==-1&&(this._messages=this._messages.slice(r+1))}_shouldProcessMessage(t){if(this._waitForSequenceMessage)return t.type!==D.Sequence?!1:(this._waitForSequenceMessage=!1,!0);if(!this._isInvocationMessage(t))return!0;let r=this._nextReceivingSequenceId;return this._nextReceivingSequenceId++,r<=this._latestReceivedSequenceId?(r===this._latestReceivedSequenceId&&this._ackTimer(),!1):(this._latestReceivedSequenceId=r,this._ackTimer(),!0)}_resetSequence(t){if(t.sequenceId>this._nextReceivingSequenceId){this._connection.stop(new Error("Sequence ID greater than amount of messages we've received."));return}this._nextReceivingSequenceId=t.sequenceId}_disconnected(){this._reconnectInProgress=!0,this._waitForSequenceMessage=!0}async _resend(){let t=this._messages.length!==0?this._messages[0]._id:this._totalMessageCount+1;await this._connection.send(this._protocol.writeMessage({type:D.Sequence,sequenceId:t}));let r=this._messages;for(let n of r)await this._connection.send(n._message);this._reconnectInProgress=!1}_dispose(t){t??(t=new Error("Unable to reconnect to server."));for(let r of this._messages)r._rejector(t)}_isInvocationMessage(t){switch(t.type){case D.Invocation:case D.StreamItem:case D.Completion:case D.StreamInvocation:case D.CancelInvocation:return!0;case D.Close:case D.Sequence:case D.Ping:case D.Ack:return!1}}_ackTimer(){this._ackTimerHandle===void 0&&(this._ackTimerHandle=setTimeout(async()=>{try{this._reconnectInProgress||await this._connection.send(this._protocol.writeMessage({type:D.Ack,sequenceId:this._latestReceivedSequenceId}))}catch{}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0},1e3))}},Gu=class{constructor(t,r,n,o){this._message=t,this._id=r,this._resolver=n,this._rejector=o}};var uw=30*1e3,dw=15*1e3,pw=1e5,re;(function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"})(re||(re={}));var pc=class e{static create(t,r,n,o,i,s,a){return new e(t,r,n,o,i,s,a)}constructor(t,r,n,o,i,s,a){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(m.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},$.isRequired(t,"connection"),$.isRequired(r,"logger"),$.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=i??uw,this.keepAliveIntervalInMilliseconds=s??dw,this._statefulReconnectBufferSize=a??pw,this._logger=r,this._protocol=n,this.connection=t,this._reconnectPolicy=o,this._handshakeProtocol=new hc,this.connection.onreceive=c=>this._processIncomingData(c),this.connection.onclose=c=>this._connectionClosed(c),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=re.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:D.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(t){if(this._connectionState!==re.Disconnected&&this._connectionState!==re.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!t)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=t}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==re.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=re.Connecting,this._logger.log(m.Debug,"Starting HubConnection.");try{await this._startInternal(),q.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=re.Connected,this._connectionStarted=!0,this._logger.log(m.Debug,"HubConnection connected successfully.")}catch(t){return this._connectionState=re.Disconnected,this._logger.log(m.Debug,`HubConnection failed to start successfully because of error '${t}'.`),Promise.reject(t)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;let t=new Promise((r,n)=>{this._handshakeResolver=r,this._handshakeRejecter=n});await this.connection.start(this._protocol.transferFormat);try{let r=this._protocol.version;this.connection.features.reconnect||(r=1);let n={protocol:this._protocol.name,version:r};if(this._logger.log(m.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(n)),this._logger.log(m.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await t,this._stopDuringStartError)throw this._stopDuringStartError;(this.connection.features.reconnect||!1)&&(this._messageBuffer=new dc(this._protocol,this.connection,this._statefulReconnectBufferSize),this.connection.features.disconnected=this._messageBuffer._disconnected.bind(this._messageBuffer),this.connection.features.resend=()=>{if(this._messageBuffer)return this._messageBuffer._resend()}),this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(r){throw this._logger.log(m.Debug,`Hub handshake failed with error '${r}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(r),r}}async stop(){let t=this._startPromise;this.connection.features.reconnect=!1,this._stopPromise=this._stopInternal(),await this._stopPromise;try{await t}catch{}}_stopInternal(t){if(this._connectionState===re.Disconnected)return this._logger.log(m.Debug,`Call to HubConnection.stop(${t}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===re.Disconnecting)return this._logger.log(m.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;let r=this._connectionState;return this._connectionState=re.Disconnecting,this._logger.log(m.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(m.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(r===re.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=t||new xe("The connection was stopped before the hub handshake could complete."),this.connection.stop(t))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(t,...r){let[n,o]=this._replaceStreamingParams(r),i=this._createStreamInvocation(t,r,o),s,a=new uc;return a.cancelCallback=()=>{let c=this._createCancelInvocation(i.invocationId);return delete this._callbacks[i.invocationId],s.then(()=>this._sendWithProtocol(c))},this._callbacks[i.invocationId]=(c,l)=>{if(l){a.error(l);return}else c&&(c.type===D.Completion?c.error?a.error(new Error(c.error)):a.complete():a.next(c.item))},s=this._sendWithProtocol(i).catch(c=>{a.error(c),delete this._callbacks[i.invocationId]}),this._launchStreams(n,s),a}_sendMessage(t){return this._resetKeepAliveInterval(),this.connection.send(t)}_sendWithProtocol(t){return this._messageBuffer?this._messageBuffer._send(t):this._sendMessage(this._protocol.writeMessage(t))}send(t,...r){let[n,o]=this._replaceStreamingParams(r),i=this._sendWithProtocol(this._createInvocation(t,r,!0,o));return this._launchStreams(n,i),i}invoke(t,...r){let[n,o]=this._replaceStreamingParams(r),i=this._createInvocation(t,r,!1,o);return new Promise((a,c)=>{this._callbacks[i.invocationId]=(h,u)=>{if(u){c(u);return}else h&&(h.type===D.Completion?h.error?c(new Error(h.error)):a(h.result):c(new Error(`Unexpected message type: ${h.type}`)))};let l=this._sendWithProtocol(i).catch(h=>{c(h),delete this._callbacks[i.invocationId]});this._launchStreams(n,l)})}on(t,r){!t||!r||(t=t.toLowerCase(),this._methods[t]||(this._methods[t]=[]),this._methods[t].indexOf(r)===-1&&this._methods[t].push(r))}off(t,r){if(!t)return;t=t.toLowerCase();let n=this._methods[t];if(n)if(r){let o=n.indexOf(r);o!==-1&&(n.splice(o,1),n.length===0&&delete this._methods[t])}else delete this._methods[t]}onclose(t){t&&this._closedCallbacks.push(t)}onreconnecting(t){t&&this._reconnectingCallbacks.push(t)}onreconnected(t){t&&this._reconnectedCallbacks.push(t)}_processIncomingData(t){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(t=this._processHandshakeResponse(t),this._receivedHandshakeResponse=!0),t){let r=this._protocol.parseMessages(t,this._logger);for(let n of r)if(!(this._messageBuffer&&!this._messageBuffer._shouldProcessMessage(n)))switch(n.type){case D.Invocation:this._invokeClientMethod(n).catch(o=>{this._logger.log(m.Error,`Invoke client method threw error: ${sc(o)}`)});break;case D.StreamItem:case D.Completion:{let o=this._callbacks[n.invocationId];if(o){n.type===D.Completion&&delete this._callbacks[n.invocationId];try{o(n)}catch(i){this._logger.log(m.Error,`Stream callback threw error: ${sc(i)}`)}}break}case D.Ping:break;case D.Close:{this._logger.log(m.Information,"Close message received from server.");let o=n.error?new Error("Server returned an error on close: "+n.error):void 0;n.allowReconnect===!0?this.connection.stop(o):this._stopPromise=this._stopInternal(o);break}case D.Ack:this._messageBuffer&&this._messageBuffer._ack(n);break;case D.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(n);break;default:this._logger.log(m.Warning,`Invalid message type: ${n.type}.`);break}}this._resetTimeoutPeriod()}_processHandshakeResponse(t){let r,n;try{[n,r]=this._handshakeProtocol.parseHandshakeResponse(t)}catch(o){let i="Error parsing handshake response: "+o;this._logger.log(m.Error,i);let s=new Error(i);throw this._handshakeRejecter(s),s}if(r.error){let o="Server returned handshake error: "+r.error;this._logger.log(m.Error,o);let i=new Error(o);throw this._handshakeRejecter(i),i}else this._logger.log(m.Debug,"Server handshake complete.");return this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=new Date().getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if((!this.connection.features||!this.connection.features.inherentKeepAlive)&&(this._timeoutHandle=setTimeout(()=>this.serverTimeout(),this.serverTimeoutInMilliseconds),this._pingServerHandle===void 0)){let t=this._nextKeepAlive-new Date().getTime();t<0&&(t=0),this._pingServerHandle=setTimeout(async()=>{if(this._connectionState===re.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}},t)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(t){let r=t.target.toLowerCase(),n=this._methods[r];if(!n){this._logger.log(m.Warning,`No client method with the name '${r}' found.`),t.invocationId&&(this._logger.log(m.Warning,`No result given for '${r}' method and invocation ID '${t.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(t.invocationId,"Client didn't provide a result.",null)));return}let o=n.slice(),i=!!t.invocationId,s,a,c;for(let l of o)try{let h=s;s=await l.apply(this,t.arguments),i&&s&&h&&(this._logger.log(m.Error,`Multiple results provided for '${r}'. Sending error to server.`),c=this._createCompletionMessage(t.invocationId,"Client provided multiple results.",null)),a=void 0}catch(h){a=h,this._logger.log(m.Error,`A callback for the method '${r}' threw error '${h}'.`)}c?await this._sendWithProtocol(c):i?(a?c=this._createCompletionMessage(t.invocationId,`${a}`,null):s!==void 0?c=this._createCompletionMessage(t.invocationId,null,s):(this._logger.log(m.Warning,`No result given for '${r}' method and invocation ID '${t.invocationId}'.`),c=this._createCompletionMessage(t.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(c)):s&&this._logger.log(m.Error,`Result given for '${r}' method but server is not expecting a result.`)}_connectionClosed(t){this._logger.log(m.Debug,`HubConnection.connectionClosed(${t}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||t||new xe("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(t||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===re.Disconnecting?this._completeClose(t):this._connectionState===re.Connected&&this._reconnectPolicy?this._reconnect(t):this._connectionState===re.Connected&&this._completeClose(t)}_completeClose(t){if(this._connectionStarted){this._connectionState=re.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(t??new Error("Connection closed.")),this._messageBuffer=void 0),q.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach(r=>r.apply(this,[t]))}catch(r){this._logger.log(m.Error,`An onclose callback called with error '${t}' threw error '${r}'.`)}}}async _reconnect(t){let r=Date.now(),n=0,o=t!==void 0?t:new Error("Attempting to reconnect due to a unknown error."),i=this._getNextRetryDelay(n++,0,o);if(i===null){this._logger.log(m.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),this._completeClose(t);return}if(this._connectionState=re.Reconnecting,t?this._logger.log(m.Information,`Connection reconnecting because of error '${t}'.`):this._logger.log(m.Information,"Connection reconnecting."),this._reconnectingCallbacks.length!==0){try{this._reconnectingCallbacks.forEach(s=>s.apply(this,[t]))}catch(s){this._logger.log(m.Error,`An onreconnecting callback called with error '${t}' threw error '${s}'.`)}if(this._connectionState!==re.Reconnecting){this._logger.log(m.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");return}}for(;i!==null;){if(this._logger.log(m.Information,`Reconnect attempt number ${n} will start in ${i} ms.`),await new Promise(s=>{this._reconnectDelayHandle=setTimeout(s,i)}),this._reconnectDelayHandle=void 0,this._connectionState!==re.Reconnecting){this._logger.log(m.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");return}try{if(await this._startInternal(),this._connectionState=re.Connected,this._logger.log(m.Information,"HubConnection reconnected successfully."),this._reconnectedCallbacks.length!==0)try{this._reconnectedCallbacks.forEach(s=>s.apply(this,[this.connection.connectionId]))}catch(s){this._logger.log(m.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${s}'.`)}return}catch(s){if(this._logger.log(m.Information,`Reconnect attempt failed because of error '${s}'.`),this._connectionState!==re.Reconnecting){this._logger.log(m.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),this._connectionState===re.Disconnecting&&this._completeClose();return}o=s instanceof Error?s:new Error(s.toString()),i=this._getNextRetryDelay(n++,Date.now()-r,o)}}this._logger.log(m.Information,`Reconnect retries have been exhausted after ${Date.now()-r} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(t,r,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:r,previousRetryCount:t,retryReason:n})}catch(o){return this._logger.log(m.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${t}, ${r}) threw error '${o}'.`),null}}_cancelCallbacksWithError(t){let r=this._callbacks;this._callbacks={},Object.keys(r).forEach(n=>{let o=r[n];try{o(null,t)}catch(i){this._logger.log(m.Error,`Stream 'error' callback called with '${t}' threw error: ${sc(i)}`)}})}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(t,r,n,o){if(n)return o.length!==0?{target:t,arguments:r,streamIds:o,type:D.Invocation}:{target:t,arguments:r,type:D.Invocation};{let i=this._invocationId;return this._invocationId++,o.length!==0?{target:t,arguments:r,invocationId:i.toString(),streamIds:o,type:D.Invocation}:{target:t,arguments:r,invocationId:i.toString(),type:D.Invocation}}}_launchStreams(t,r){if(t.length!==0){r||(r=Promise.resolve());for(let n in t)t[n].subscribe({complete:()=>{r=r.then(()=>this._sendWithProtocol(this._createCompletionMessage(n)))},error:o=>{let i;o instanceof Error?i=o.message:o&&o.toString?i=o.toString():i="Unknown error",r=r.then(()=>this._sendWithProtocol(this._createCompletionMessage(n,i)))},next:o=>{r=r.then(()=>this._sendWithProtocol(this._createStreamItemMessage(n,o)))}})}}_replaceStreamingParams(t){let r=[],n=[];for(let o=0;o<t.length;o++){let i=t[o];if(this._isObservable(i)){let s=this._invocationId;this._invocationId++,r[s]=i,n.push(s.toString()),t.splice(o,1)}}return[r,n]}_isObservable(t){return t&&t.subscribe&&typeof t.subscribe=="function"}_createStreamInvocation(t,r,n){let o=this._invocationId;return this._invocationId++,n.length!==0?{target:t,arguments:r,invocationId:o.toString(),streamIds:n,type:D.StreamInvocation}:{target:t,arguments:r,invocationId:o.toString(),type:D.StreamInvocation}}_createCancelInvocation(t){return{invocationId:t,type:D.CancelInvocation}}_createStreamItemMessage(t,r){return{invocationId:t,item:r,type:D.StreamItem}}_createCompletionMessage(t,r,n){return r?{error:r,invocationId:t,type:D.Completion}:{invocationId:t,result:n,type:D.Completion}}_createCloseMessage(){return{type:D.Close}}};var fw=[0,2e3,1e4,3e4,null],bi=class{constructor(t){this._retryDelays=t!==void 0?[...t,null]:fw}nextRetryDelayInMilliseconds(t){return this._retryDelays[t.previousRetryCount]}};var Mt=class{};Mt.Authorization="Authorization";Mt.Cookie="Cookie";var fc=class extends qt{constructor(t,r){super(),this._innerClient=t,this._accessTokenFactory=r}async send(t){let r=!0;this._accessTokenFactory&&(!this._accessToken||t.url&&t.url.indexOf("/negotiate?")>0)&&(r=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(t);let n=await this._innerClient.send(t);return r&&n.statusCode===401&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(t),await this._innerClient.send(t)):n}_setAuthorizationHeader(t){t.headers||(t.headers={}),this._accessToken?t.headers[Mt.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&t.headers[Mt.Authorization]&&delete t.headers[Mt.Authorization]}getCookieString(t){return this._innerClient.getCookieString(t)}};var ie;(function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"})(ie||(ie={}));var ue;(function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"})(ue||(ue={}));var mc=class{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}};var wi=class{get pollAborted(){return this._pollAbort.aborted}constructor(t,r,n){this._httpClient=t,this._logger=r,this._pollAbort=new mc,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(t,r){if($.isRequired(t,"url"),$.isRequired(r,"transferFormat"),$.isIn(r,ue,"transferFormat"),this._url=t,this._logger.log(m.Trace,"(LongPolling transport) Connecting."),r===ue.Binary&&typeof XMLHttpRequest<"u"&&typeof new XMLHttpRequest().responseType!="string")throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");let[n,o]=Kt(),i={[n]:o,...this._options.headers},s={abortSignal:this._pollAbort.signal,headers:i,timeout:1e5,withCredentials:this._options.withCredentials};r===ue.Binary&&(s.responseType="arraybuffer");let a=`${t}&_=${Date.now()}`;this._logger.log(m.Trace,`(LongPolling transport) polling: ${a}.`);let c=await this._httpClient.get(a,s);c.statusCode!==200?(this._logger.log(m.Error,`(LongPolling transport) Unexpected response code: ${c.statusCode}.`),this._closeError=new ot(c.statusText||"",c.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,s)}async _poll(t,r){try{for(;this._running;)try{let n=`${t}&_=${Date.now()}`;this._logger.log(m.Trace,`(LongPolling transport) polling: ${n}.`);let o=await this._httpClient.get(n,r);o.statusCode===204?(this._logger.log(m.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):o.statusCode!==200?(this._logger.log(m.Error,`(LongPolling transport) Unexpected response code: ${o.statusCode}.`),this._closeError=new ot(o.statusText||"",o.statusCode),this._running=!1):o.content?(this._logger.log(m.Trace,`(LongPolling transport) data received. ${Br(o.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(o.content)):this._logger.log(m.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(n){this._running?n instanceof Or?this._logger.log(m.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=n,this._running=!1):this._logger.log(m.Trace,`(LongPolling transport) Poll errored after shutdown: ${n.message}`)}}finally{this._logger.log(m.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(t){return this._running?ic(this._logger,"LongPolling",this._httpClient,this._url,t,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(m.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(m.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);let t={},[r,n]=Kt();t[r]=n;let o={headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials},i;try{await this._httpClient.delete(this._url,o)}catch(s){i=s}i?i instanceof ot&&(i.statusCode===404?this._logger.log(m.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(m.Trace,`(LongPolling transport) Error sending a DELETE request: ${i}`)):this._logger.log(m.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(m.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let t="(LongPolling transport) Firing onclose event.";this._closeError&&(t+=" Error: "+this._closeError),this._logger.log(m.Trace,t),this.onclose(this._closeError)}}};var gc=class{constructor(t,r,n,o){this._httpClient=t,this._accessToken=r,this._logger=n,this._options=o,this.onreceive=null,this.onclose=null}async connect(t,r){return $.isRequired(t,"url"),$.isRequired(r,"transferFormat"),$.isIn(r,ue,"transferFormat"),this._logger.log(m.Trace,"(SSE transport) Connecting."),this._url=t,this._accessToken&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise((n,o)=>{let i=!1;if(r!==ue.Text){o(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));return}let s;if(q.isBrowser||q.isWebWorker)s=new this._options.EventSource(t,{withCredentials:this._options.withCredentials});else{let a=this._httpClient.getCookieString(t),c={};c.Cookie=a;let[l,h]=Kt();c[l]=h,s=new this._options.EventSource(t,{withCredentials:this._options.withCredentials,headers:{...c,...this._options.headers}})}try{s.onmessage=a=>{if(this.onreceive)try{this._logger.log(m.Trace,`(SSE transport) data received. ${Br(a.data,this._options.logMessageContent)}.`),this.onreceive(a.data)}catch(c){this._close(c);return}},s.onerror=a=>{i?this._close():o(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},s.onopen=()=>{this._logger.log(m.Information,`SSE connected to ${this._url}`),this._eventSource=s,i=!0,n()}}catch(a){o(a);return}})}async send(t){return this._eventSource?ic(this._logger,"SSE",this._httpClient,this._url,t,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(t){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(t))}};var yc=class{constructor(t,r,n,o,i,s){this._logger=n,this._accessTokenFactory=r,this._logMessageContent=o,this._webSocketConstructor=i,this._httpClient=t,this.onreceive=null,this.onclose=null,this._headers=s}async connect(t,r){$.isRequired(t,"url"),$.isRequired(r,"transferFormat"),$.isIn(r,ue,"transferFormat"),this._logger.log(m.Trace,"(WebSockets transport) Connecting.");let n;return this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise((o,i)=>{t=t.replace(/^http/,"ws");let s,a=this._httpClient.getCookieString(t),c=!1;if(q.isNode||q.isReactNative){let l={},[h,u]=Kt();l[h]=u,n&&(l[Mt.Authorization]=`Bearer ${n}`),a&&(l[Mt.Cookie]=a),s=new this._webSocketConstructor(t,void 0,{headers:{...l,...this._headers}})}else n&&(t+=(t.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);s||(s=new this._webSocketConstructor(t)),r===ue.Binary&&(s.binaryType="arraybuffer"),s.onopen=l=>{this._logger.log(m.Information,`WebSocket connected to ${t}.`),this._webSocket=s,c=!0,o()},s.onerror=l=>{let h=null;typeof ErrorEvent<"u"&&l instanceof ErrorEvent?h=l.error:h="There was an error with the transport",this._logger.log(m.Information,`(WebSockets transport) ${h}.`)},s.onmessage=l=>{if(this._logger.log(m.Trace,`(WebSockets transport) data received. ${Br(l.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(l.data)}catch(h){this._close(h);return}},s.onclose=l=>{if(c)this._close(l);else{let h=null;typeof ErrorEvent<"u"&&l instanceof ErrorEvent?h=l.error:h="WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",i(new Error(h))}}})}send(t){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(m.Trace,`(WebSockets transport) sending data. ${Br(t,this._logMessageContent)}.`),this._webSocket.send(t),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(t){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(m.Trace,"(WebSockets transport) socket closed."),this.onclose&&(this._isCloseEvent(t)&&(t.wasClean===!1||t.code!==1e3)?this.onclose(new Error(`WebSocket closed with status code: ${t.code} (${t.reason||"no reason given"}).`)):t instanceof Error?this.onclose(t):this.onclose())}_isCloseEvent(t){return t&&typeof t.wasClean=="boolean"&&typeof t.code=="number"}};var X0=100,bc=class{constructor(t,r={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,$.isRequired(t,"url"),this._logger=q0(r.logger),this.baseUrl=this._resolveUrl(t),r=r||{},r.logMessageContent=r.logMessageContent===void 0?!1:r.logMessageContent,typeof r.withCredentials=="boolean"||r.withCredentials===void 0)r.withCredentials=r.withCredentials===void 0?!0:r.withCredentials;else throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");r.timeout=r.timeout===void 0?100*1e3:r.timeout;let n=null,o=null;if(q.isNode&&typeof mn<"u"){let i=typeof __webpack_require__=="function"?__non_webpack_require__:mn;n=i("ws"),o=i("eventsource")}!q.isNode&&typeof WebSocket<"u"&&!r.WebSocket?r.WebSocket=WebSocket:q.isNode&&!r.WebSocket&&n&&(r.WebSocket=n),!q.isNode&&typeof EventSource<"u"&&!r.EventSource?r.EventSource=EventSource:q.isNode&&!r.EventSource&&typeof o<"u"&&(r.EventSource=o),this._httpClient=new fc(r.httpClient||new lc(this._logger),r.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=r,this.onreceive=null,this.onclose=null}async start(t){if(t=t||ue.Binary,$.isIn(t,ue,"transferFormat"),this._logger.log(m.Debug,`Starting connection with transfer format '${ue[t]}'.`),this._connectionState!=="Disconnected")return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(t),await this._startInternalPromise,this._connectionState==="Disconnecting"){let r="Failed to start the HttpConnection before stop() was called.";return this._logger.log(m.Error,r),await this._stopPromise,Promise.reject(new xe(r))}else if(this._connectionState!=="Connected"){let r="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(m.Error,r),Promise.reject(new xe(r))}this._connectionStarted=!0}send(t){return this._connectionState!=="Connected"?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new Ku(this.transport)),this._sendQueue.send(t))}async stop(t){if(this._connectionState==="Disconnected")return this._logger.log(m.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnected state.`),Promise.resolve();if(this._connectionState==="Disconnecting")return this._logger.log(m.Debug,`Call to HttpConnection.stop(${t}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;this._connectionState="Disconnecting",this._stopPromise=new Promise(r=>{this._stopPromiseResolver=r}),await this._stopInternal(t),await this._stopPromise}async _stopInternal(t){this._stopError=t;try{await this._startInternalPromise}catch{}if(this.transport){try{await this.transport.stop()}catch(r){this._logger.log(m.Error,`HttpConnection.transport.stop() threw error '${r}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(m.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(t){let r=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation)if(this._options.transport===ie.WebSockets)this.transport=this._constructTransport(ie.WebSockets),await this._startTransport(r,t);else throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");else{let n=null,o=0;do{if(n=await this._getNegotiationResponse(r),this._connectionState==="Disconnecting"||this._connectionState==="Disconnected")throw new xe("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(r=n.url),n.accessToken){let i=n.accessToken;this._accessTokenFactory=()=>i,this._httpClient._accessToken=i,this._httpClient._accessTokenFactory=void 0}o++}while(n.url&&o<X0);if(o===X0&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(r,this._options.transport,n,t)}this.transport instanceof wi&&(this.features.inherentKeepAlive=!0),this._connectionState==="Connecting"&&(this._logger.log(m.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(n){return this._logger.log(m.Error,"Failed to start the connection: "+n),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(n)}}async _getNegotiationResponse(t){let r={},[n,o]=Kt();r[n]=o;let i=this._resolveNegotiateUrl(t);this._logger.log(m.Debug,`Sending negotiation request: ${i}.`);try{let s=await this._httpClient.post(i,{content:"",headers:{...r,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(s.statusCode!==200)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${s.statusCode}'`));let a=JSON.parse(s.content);return(!a.negotiateVersion||a.negotiateVersion<1)&&(a.connectionToken=a.connectionId),a.useStatefulReconnect&&this._options._useStatefulReconnect!==!0?Promise.reject(new yi("Client didn't negotiate Stateful Reconnect but the server did.")):a}catch(s){let a="Failed to complete negotiation with the server: "+s;return s instanceof ot&&s.statusCode===404&&(a=a+" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(m.Error,a),Promise.reject(new yi(a))}}_createConnectUrl(t,r){return r?t+(t.indexOf("?")===-1?"?":"&")+`id=${r}`:t}async _createTransport(t,r,n,o){let i=this._createConnectUrl(t,n.connectionToken);if(this._isITransport(r)){this._logger.log(m.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=r,await this._startTransport(i,o),this.connectionId=n.connectionId;return}let s=[],a=n.availableTransports||[],c=n;for(let l of a){let h=this._resolveTransportOrError(l,r,o,c?.useStatefulReconnect===!0);if(h instanceof Error)s.push(`${l.transport} failed:`),s.push(h);else if(this._isITransport(h)){if(this.transport=h,!c){try{c=await this._getNegotiationResponse(t)}catch(u){return Promise.reject(u)}i=this._createConnectUrl(t,c.connectionToken)}try{await this._startTransport(i,o),this.connectionId=c.connectionId;return}catch(u){if(this._logger.log(m.Error,`Failed to start the transport '${l.transport}': ${u}`),c=void 0,s.push(new rc(`${l.transport} failed: ${u}`,ie[l.transport])),this._connectionState!=="Connecting"){let p="Failed to select transport before stop() was called.";return this._logger.log(m.Debug,p),Promise.reject(new xe(p))}}}}return s.length>0?Promise.reject(new nc(`Unable to connect to the server with any of the available transports. ${s.join(" ")}`,s)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(t){switch(t){case ie.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new yc(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case ie.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new gc(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case ie.LongPolling:return new wi(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${t}.`)}}_startTransport(t,r){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async n=>{let o=!1;if(this.features.reconnect)try{this.features.disconnected(),await this.transport.connect(t,r),await this.features.resend()}catch{o=!0}else{this._stopConnection(n);return}o&&this._stopConnection(n)}:this.transport.onclose=n=>this._stopConnection(n),this.transport.connect(t,r)}_resolveTransportOrError(t,r,n,o){let i=ie[t.transport];if(i==null)return this._logger.log(m.Debug,`Skipping transport '${t.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${t.transport}' because it is not supported by this client.`);if(mw(r,i))if(t.transferFormats.map(a=>ue[a]).indexOf(n)>=0){if(i===ie.WebSockets&&!this._options.WebSocket||i===ie.ServerSentEvents&&!this._options.EventSource)return this._logger.log(m.Debug,`Skipping transport '${ie[i]}' because it is not supported in your environment.'`),new ec(`'${ie[i]}' is not supported in your environment.`,i);this._logger.log(m.Debug,`Selecting transport '${ie[i]}'.`);try{return this.features.reconnect=i===ie.WebSockets?o:void 0,this._constructTransport(i)}catch(a){return a}}else return this._logger.log(m.Debug,`Skipping transport '${ie[i]}' because it does not support the requested transfer format '${ue[n]}'.`),new Error(`'${ie[i]}' does not support ${ue[n]}.`);else return this._logger.log(m.Debug,`Skipping transport '${ie[i]}' because it was disabled by the client.`),new tc(`'${ie[i]}' is disabled by the client.`,i)}_isITransport(t){return t&&typeof t=="object"&&"connect"in t}_stopConnection(t){if(this._logger.log(m.Debug,`HttpConnection.stopConnection(${t}) called while in state ${this._connectionState}.`),this.transport=void 0,t=this._stopError||t,this._stopError=void 0,this._connectionState==="Disconnected"){this._logger.log(m.Debug,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is already in the disconnected state.`);return}if(this._connectionState==="Connecting")throw this._logger.log(m.Warning,`Call to HttpConnection.stopConnection(${t}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${t}) was called while the connection is still in the connecting state.`);if(this._connectionState==="Disconnecting"&&this._stopPromiseResolver(),t?this._logger.log(m.Error,`Connection disconnected with error '${t}'.`):this._logger.log(m.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch(r=>{this._logger.log(m.Error,`TransportSendQueue.stop() threw error '${r}'.`)}),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(t)}catch(r){this._logger.log(m.Error,`HttpConnection.onclose(${t}) threw error '${r}'.`)}}}_resolveUrl(t){if(t.lastIndexOf("https://",0)===0||t.lastIndexOf("http://",0)===0)return t;if(!q.isBrowser)throw new Error(`Cannot resolve '${t}'.`);let r=window.document.createElement("a");return r.href=t,this._logger.log(m.Information,`Normalizing '${t}' to '${r.href}'.`),r.href}_resolveNegotiateUrl(t){let r=new URL(t);r.pathname.endsWith("/")?r.pathname+="negotiate":r.pathname+="/negotiate";let n=new URLSearchParams(r.searchParams);return n.has("negotiateVersion")||n.append("negotiateVersion",this._negotiateVersion.toString()),n.has("useStatefulReconnect")?n.get("useStatefulReconnect")==="true"&&(this._options._useStatefulReconnect=!0):this._options._useStatefulReconnect===!0&&n.append("useStatefulReconnect","true"),r.search=n.toString(),r.toString()}};function mw(e,t){return!e||(t&e)!==0}var Ku=class e{constructor(t){this._transport=t,this._buffer=[],this._executing=!0,this._sendBufferedData=new fo,this._transportResult=new fo,this._sendLoopPromise=this._sendLoop()}send(t){return this._bufferData(t),this._transportResult||(this._transportResult=new fo),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(t){if(this._buffer.length&&typeof this._buffer[0]!=typeof t)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof t}`);this._buffer.push(t),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new fo;let t=this._transportResult;this._transportResult=void 0;let r=typeof this._buffer[0]=="string"?this._buffer.join(""):e._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(r),t.resolve()}catch(n){t.reject(n)}}}static _concatBuffers(t){let r=t.map(i=>i.byteLength).reduce((i,s)=>i+s),n=new Uint8Array(r),o=0;for(let i of t)n.set(new Uint8Array(i),o),o+=i.byteLength;return n.buffer}},fo=class{constructor(){this.promise=new Promise((t,r)=>[this._resolver,this._rejecter]=[t,r])}resolve(){this._resolver()}reject(t){this._rejecter(t)}};var gw="json",wc=class{constructor(){this.name=gw,this.version=2,this.transferFormat=ue.Text}parseMessages(t,r){if(typeof t!="string")throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!t)return[];r===null&&(r=Gt.instance);let n=it.parse(t),o=[];for(let i of n){let s=JSON.parse(i);if(typeof s.type!="number")throw new Error("Invalid payload.");switch(s.type){case D.Invocation:this._isInvocationMessage(s);break;case D.StreamItem:this._isStreamItemMessage(s);break;case D.Completion:this._isCompletionMessage(s);break;case D.Ping:break;case D.Close:break;case D.Ack:this._isAckMessage(s);break;case D.Sequence:this._isSequenceMessage(s);break;default:r.log(m.Information,"Unknown message type '"+s.type+"' ignored.");continue}o.push(s)}return o}writeMessage(t){return it.write(JSON.stringify(t))}_isInvocationMessage(t){this._assertNotEmptyString(t.target,"Invalid payload for Invocation message."),t.invocationId!==void 0&&this._assertNotEmptyString(t.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(t){if(this._assertNotEmptyString(t.invocationId,"Invalid payload for StreamItem message."),t.item===void 0)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(t){if(t.result&&t.error)throw new Error("Invalid payload for Completion message.");!t.result&&t.error&&this._assertNotEmptyString(t.error,"Invalid payload for Completion message."),this._assertNotEmptyString(t.invocationId,"Invalid payload for Completion message.")}_isAckMessage(t){if(typeof t.sequenceId!="number")throw new Error("Invalid SequenceId for Ack message.")}_isSequenceMessage(t){if(typeof t.sequenceId!="number")throw new Error("Invalid SequenceId for Sequence message.")}_assertNotEmptyString(t,r){if(typeof t!="string"||t==="")throw new Error(r)}};var yw={trace:m.Trace,debug:m.Debug,info:m.Information,information:m.Information,warn:m.Warning,warning:m.Warning,error:m.Error,critical:m.Critical,none:m.None};function bw(e){let t=yw[e.toLowerCase()];if(typeof t<"u")return t;throw new Error(`Unknown log level: ${e}`)}var vi=class{configureLogging(t){if($.isRequired(t,"logging"),ww(t))this.logger=t;else if(typeof t=="string"){let r=bw(t);this.logger=new an(r)}else this.logger=new an(t);return this}withUrl(t,r){return $.isRequired(t,"url"),$.isNotEmpty(t,"url"),this.url=t,typeof r=="object"?this.httpConnectionOptions={...this.httpConnectionOptions,...r}:this.httpConnectionOptions={...this.httpConnectionOptions,transport:r},this}withHubProtocol(t){return $.isRequired(t,"protocol"),this.protocol=t,this}withAutomaticReconnect(t){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return t?Array.isArray(t)?this.reconnectPolicy=new bi(t):this.reconnectPolicy=t:this.reconnectPolicy=new bi,this}withServerTimeout(t){return $.isRequired(t,"milliseconds"),this._serverTimeoutInMilliseconds=t,this}withKeepAliveInterval(t){return $.isRequired(t,"milliseconds"),this._keepAliveIntervalInMilliseconds=t,this}withStatefulReconnect(t){return this.httpConnectionOptions===void 0&&(this.httpConnectionOptions={}),this.httpConnectionOptions._useStatefulReconnect=!0,this._statefulReconnectBufferSize=t?.bufferSize,this}build(){let t=this.httpConnectionOptions||{};if(t.logger===void 0&&(t.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");let r=new bc(this.url,t);return pc.create(r,this.logger||Gt.instance,this.protocol||new wc,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}};function ww(e){return e.log!==void 0}var J2=Od(X2());var vo=class{},Y2=(s=>(s[s.WAITING=-1]="WAITING",s[s.STARTED=0]="STARTED",s[s.QR_CODE=1]="QR_CODE",s[s.POSITION=2]="POSITION",s[s.FINISHED=3]="FINISHED",s[s.ERROR=9]="ERROR",s))(Y2||{}),Rc=class e{constructor(t,r){this.proctoringId="";this.capturePhotoUrl="";this.qrCodeBase64Image="";this.transmissionOk=!1;this.waitingPositionValidation=!1;this.externalSessionId=null;this.currentStep=0;this.connection=null;this.context=t,this.onRealtimeAlertsCallback=r,console.log("context -> ",t),this.backend=new ft({type:t?.type||"prod",token:t.token}),this.currentStep=-1}static{this.isModalOpen=!1}getExternalCameraSessionId(){return""+this.externalSessionId}async checkTransmission(){try{this.transmissionOk=!1;let t=await this.backend.externalCameraCheckTransmission(""+this.externalSessionId);console.log(t);let r=0;for(;!this.transmissionOk&&r<=5;)await new Promise(n=>setTimeout(n,2e3)),r=r+1;if(!this.transmissionOk)throw new Error("Timed out na checagem da transmiss\xE3o!")}catch(t){throw console.error("Erro ao checar a transmiss\xE3o:",t),new Error("N\xE3o foi poss\xEDvel checar a transmiss\xE3o."+t)}}async startTransmission(t){try{this.proctoringId=t;let r=await this.backend.externalCameraStartTransmission(""+this.externalSessionId,t);console.log(r)}catch(r){throw console.error("Erro ao iniciar transmiss\xE3o:",r),new Error("N\xE3o foi poss\xEDvel iniciar a transmiss\xE3o.")}}async goToPositionGuide(){if(this.connection){let t=new vo;t.command="Position_Guide",console.log("Enviando comando 'Position_Guide' para o aplicativo..."),this.connection.invoke("SendAction",this.externalSessionId,t)}}async reset(){if(this.connection){let t=new vo;t.command="Reset",console.log("Enviando comando 'Reset' para o aplicativo..."),this.connection.invoke("SendAction",this.externalSessionId,t)}}async takePicture(t,r){if(this.connection){this.waitingPositionValidation=t,this.onTakePictureCallback=r;let n=new vo;n.command="Capture",console.log("Enviando comando 'Capture' para o aplicativo..."),this.connection.invoke("SendAction",this.externalSessionId,n)}else throw new Error("N\xE3o existe conex\xE3o de camera externa ativa.")}async startSession(t){try{this.onQrCodeReadedCallback=t,this.connection&&await this.disconnectWebSocket(),await this.initializeWebSocketConnection(),await this.reset();let r=await this.backend.externalCameraStartSession();this.externalSessionId=r.externalSessionId,console.log(this.externalSessionId),this.currentStep=0;let n={externalSessionId:this.externalSessionId,token:this.context.token,ambient:this.context.type},o=JSON.stringify(n);return this.qrCodeBase64Image=await J2.default.toDataURL(o),console.log(this.qrCodeBase64Image),this.qrCodeBase64Image}catch(r){return this.disconnectWebSocket(),Promise.reject(r)}}async checkExternalCamera(){if(this.currentStep=0,e.isModalOpen)return Promise.reject("O modal de verifica\xE7\xE3o j\xE1 est\xE1 aberto.");e.isModalOpen=!0;try{return await this.startSession(()=>{}),await this.buildInterface()}catch(t){return console.error("Erro ao iniciar verifica\xE7\xE3o:",t),this.closeCheckExternalCamera(),Promise.reject(t)}}buildInterface(){return new Promise((t,r)=>{this.resolvePromise=t;let n=document.createElement("div");n.setAttribute("id","externalCameraCheck"),this.applyStyles(n,{backgroundColor:"rgba(0,0,0,0.4)",zIndex:"1000",position:"fixed",top:"0",left:"0",height:"100vh",width:"100%",display:"flex",alignItems:"center",justifyContent:"center"});let o=document.createElement("div");this.applyStyles(o,{backgroundColor:"#fff",zIndex:"1001",width:"500px",borderRadius:"10px",display:"flex",flexDirection:"column",alignItems:"center"});let i=document.createElement("h3");i.innerText="Conectar dispositivo m\xF3vel",this.applyStyles(i,{color:"rgba(0, 0, 0, .7)",fontWeight:"bold",fontSize:"20px",marginBottom:"15px",padding:"20px 0px",borderBottom:"2px solid rgba(0, 0, 0, .1)",width:"100%",textAlign:"center"});let s=document.createElement("div");s.id="external-camera-content",this.applyStyles(s,{width:"100%",padding:"20px 40px",boxSizing:"border-box",minHeight:"300px",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center"});let a=document.createElement("div");this.applyStyles(a,{width:"100%",display:"flex",alignItems:"center",justifyContent:"center",borderTop:"2px solid rgba(0, 0, 0, .1)"});let c=document.createElement("button");c.innerText="Cancelar",this.applyStyles(c,{width:"100%",height:"70px",backgroundColor:"#FFF",border:"none",color:"rgba(0, 0, 0, .7)",fontWeight:"bold",borderRadius:"0 0 0 10px",cursor:"pointer"}),c.addEventListener("click",()=>{let h=new vo;h.command="Cancel",console.log("Enviando comando 'Cancel' para o aplicativo..."),this.connection?.invoke("SendAction",this.externalSessionId,h),this.closeCheckExternalCamera(),t({result:!1})});let l=document.createElement("button");l.innerText="Continuar",l.id="external-camera-continue",this.applyStyles(l,{width:"100%",height:"70px",backgroundColor:"#FFF",border:"none",color:"rgba(0, 0, 0, .7)",fontWeight:"bold",borderRadius:"0 0 10px 0",cursor:"pointer",borderLeft:"2px solid rgba(0, 0, 0, .1)"}),a.appendChild(c),a.appendChild(l),o.appendChild(i),o.appendChild(s),o.appendChild(a),n.appendChild(o),document.body.appendChild(n),this.renderCurrentStep()})}renderCurrentStep(){let t=document.getElementById("external-camera-content");if(t)switch(t.innerHTML="",this.currentStep){case 0:this.renderQRCodeStep(t);break;case 1:this.renderPhotoStep(t);break;case 2:this.renderImageStep(t);break;default:break}}renderQRCodeStep(t){let r=document.createElement("canvas");r.id="qr-code-canvas";let n=document.createElement("p");n.innerText="Aponte a c\xE2mera do seu celular para o QR Code para iniciar a verifica\xE7\xE3o do ambiente.",this.applyStyles(n,{textAlign:"center",color:"#555",marginTop:"20px"});let o=r.getContext("2d"),i=new Image;i.onload=()=>{let c=250/i.width,l=i.height*c;r.width=250,r.height=l,o&&o.drawImage(i,0,0,250,l)},i.src=this.qrCodeBase64Image,t.appendChild(r),t.appendChild(n);let s=document.getElementById("external-camera-continue");s.disabled=!0,this.applyStyles(s,{color:"#ccc",cursor:"not-allowed"})}renderPhotoStep(t){let r=document.createElement("p");r.id="photo-message",r.innerText="Clique no bot\xE3o abaixo para realizar a captura da foto do ambiente.",this.applyStyles(r,{textAlign:"center",color:"#555",marginBottom:"20px",fontSize:"14px",display:"-webkit-box",overflow:"hidden",textOverflow:"ellipsis"}),r.style.webkitLineClamp="3",r.style.webkitBoxOrient="vertical",t.appendChild(r);let n=document.createElement("div");n.id="photo-error-banner",n.innerText="Foto fora do padr\xE3o esperado.",this.applyStyles(n,{backgroundColor:"#FEE2E2",color:"#DC2626",padding:"12px 15px",borderRadius:"8px",textAlign:"center",fontSize:"12px",fontWeight:"400",marginBottom:"15px",display:"none"}),t.appendChild(n);let o=document.createElement("div");this.applyStyles(o,{backgroundColor:"#fff",borderRadius:"8px",padding:"20px",display:"flex",gap:"20px",alignItems:"flex-start",border:"1px solid #e5e5e5",marginBottom:"20px"});let i=document.createElement("div");if(i.id="photo-icon-container",this.applyStyles(i,{backgroundColor:"#f5f5f5",borderRadius:"8px",width:"120px",height:"160px",minWidth:"120px",minHeight:"160px",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:"0",overflow:"hidden"}),this.capturePhotoUrl&&this.capturePhotoUrl.trim()!==""){let g=document.createElement("img");g.id="img-photo";let b=this.capturePhotoUrl.startsWith("data:")?this.capturePhotoUrl:"data:image/jpeg;base64,"+this.capturePhotoUrl;g.src=b,this.applyStyles(g,{width:"100%",height:"100%",objectFit:"contain",objectPosition:"center",borderRadius:"8px",display:"block"}),i.appendChild(g)}else{let g=document.createElement("div");g.innerHTML=`
305
305
  <svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
306
306
  <path d="M23 19C23 19.5304 22.7893 20.0391 22.4142 20.4142C22.0391 20.7893 21.5304 21 21 21H3C2.46957 21 1.96086 20.7893 1.58579 20.4142C1.21071 20.0391 1 19.5304 1 19V8C1 7.46957 1.21071 6.96086 1.58579 6.58579C1.96086 6.21071 2.46957 6 3 6H7L9 4H15L17 6H21C21.5304 6 22.0391 6.21071 22.4142 6.58579C22.7893 6.96086 23 7.46957 23 8V19Z" stroke="#666" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
307
307
  <path d="M12 17C14.2091 17 16 15.2091 16 13C16 10.7909 14.2091 9 12 9C9.79086 9 8 10.7909 8 13C8 15.2091 9.79086 17 12 17Z" stroke="#666" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>