@beterdichtbij/component-library 0.66.0-alpha.4 → 0.66.0-alpha.6
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.
|
@@ -2161,4 +2161,4 @@ a=fingerprint:sha-256 34:DF:5C:15:60:FF:28:3E:E8:96:4B:F8:85:61:E4:C0:57:D1:60:8
|
|
|
2161
2161
|
}
|
|
2162
2162
|
|
|
2163
2163
|
registerProcessor('player-processor', PlayerProcessor);
|
|
2164
|
-
`],{type:`application/javascript`}),r=URL.createObjectURL(t);await this._playerAudioContext.audioWorklet.addModule(r);let i=new AudioWorkletNode(this._playerAudioContext,`player-processor`,{numberOfOutputs:1,outputChannelCount:[1]});this._logger.log(`Started Audio worklet.`),i.port.onmessage=async t=>{if(t.data.type===`startedProcessing`)this._logger.log(`Player audio buffer started processing audio.`),this.sendTelemetryEvent(+new Date-n,{step:X5.AUDIO_WORKLET_STARTED_PROCESSING,timestampInfo:{attemptTimestamp:n}},[`Success`],200),e(i);else if(t.data.type===`finished`){let e=+new Date;try{if(t.data.value.shutDownType===`speedUpBuffer`){if(!this._playerWorkletNode)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYERAUDIOBUFFER_UNDEFINED_CANNOT_DISCONNECT_FOR_SPEEDUP});if(!this._playerAudioDestinationNode)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYERAUDIOBUFFERNODE_UNDEFINED_FOR_SPEEDUP});this._logger.log(`Speeding up the rest of the audio buffer and shutting down player worklet node`);let n=t.data.value.restOfBufferToSpeedUp,r=n.reduce(((e,t)=>e+t[0].length),0);this._speedUpAudioBuffer=this._playerAudioContext.createBuffer(1,r,this._playerAudioContext.sampleRate);let i=0,a=new Float32Array(r),o=0;for(let e of n)i+=e[0].byteLength??0,a.set(e[0],o),o+=e[0].length;this._speedUpAudioBuffer.copyToChannel(a,0),this._playerWorkletNode.disconnect(),this._speedUpAudioBufferSourceNode=this._playerAudioContext.createBufferSource(),this._speedUpAudioBufferSourceNode.buffer=this._speedUpAudioBuffer,this._speedUpAudioBufferSourceNode.playbackRate.value=c.speedUpRate,this._speedUpAudioBufferSourceNode.connect(this._playerAudioDestinationNode),this.sendTelemetryEvent(+new Date-e,{step:X5.SET_SPEEDUP_AUDIO_STREAM,timestampInfo:{attemptTimestamp:e}},[`Success`],200),this._speedUpAudioBufferSourceNode.onended=()=>{this._storeRecording&&(this._recording?.stop(),this._recording=void 0);let n=+new Date;this._isFinished=!0,this._logger.log(`Finished speeding up the reset of the audio buffer and shut down player audio worklet. Will now switch to microphone.`);let r=t.data.value.playTimestamp,a=e-t.data.value.playTimestamp,o=n-e,s=n-t.data.value.playTimestamp,c=t.data.value.totalRawBytesBuffered,l=t.data.value.rawBytesPlayedNormalSpeed;this._statsReport.playTimestamp=r,this._statsReport.playNormalSpeedDurationInMs=a,this._statsReport.playSpeedUpDurationInMs=o,this._statsReport.totalPlayDurationInMs=s,this._statsReport.totalRawBytesBuffered=c,this._statsReport.rawBytesPlayedNormalSpeed=l,this._statsReport.rawBytesPlayedSpedUp=i,this.sendTelemetryEvent(n-e,{step:X5.SHUTDOWN_FINISHED_SPEEDING_UP_REST_OF_BUFFER,timestampInfo:{attemptTimestamp:e},playTimestamp:r,playNormalSpeedDurationInMs:a,playSpeedUpDurationInMs:o,totalPlayDurationInMs:s,totalRawBytesBuffered:c,rawBytesPlayedNormalSpeed:l,rawBytesPlayedSpedUp:i},[`Success`],200),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature after preAudio finished speeding up`)})),this._switchToRealTimeMic()},this._speedUpAudioBufferSourceNode.start()}}catch(t){this._logger.error(`Error handling finished event from player worklet`,t),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature when handling audio buffer speed up error`)})),this._switchToRealTimeMic();let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYERAUDIOBUFFER_FINISHED_EVENT_FAIL,originalError:t});this._logger.error(n.message),this.sendTelemetryEvent(+new Date-e,{step:X5.SHUTDOWN_FINISHED_SPEEDING_UP_REST_OF_BUFFER,timestampInfo:{attemptTimestamp:e},...J3(n)},n.resultCategories,500)}}},this._logger.log(`Audio worklet initialized successfully`),this.sendTelemetryEvent(+new Date-n,{step:X5.START_AUDIO_WORKLET,timestampInfo:{attemptTimestamp:n}},[`Success`],200),e(i)}catch(e){this._logger.error(`Error initializing audio worklet`,e);let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYER_AUDIO_BUFFER_INIT_FAIL,originalError:e});this._logger.error(n.message),t(n)}})),u=new Promise((async(e,t)=>{try{this._deviceManager=await this.mediaClient.getDeviceManager();let t=+new Date;if(this._deviceManager.shouldEnumerateDevices){if((await this._deviceManager.getMicrophones())[0]?.id===`microphone:`){this.sendTelemetryEvent(+new Date,{step:X5.AUDIO_PERMISSION_ASKED,timestampInfo:{attemptTimestamp:+new Date}},[`Success`],200);let e=await this._deviceManager.getAskDevicePermissionPromise({audio:!0,video:!1},C3.PreAudio);if(i=+new Date-t,!e.audio)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.AUDIO_NO_PERMISSION})}this.sendTelemetryEvent(+new Date-t,{step:X5.AUDIO_PERMISSION_GRANTED,timestampInfo:{attemptTimestamp:t}},[`Success`],200)}else this._logger.info(`Device enumeration disabled, skipping getMicrophones permission check`);let n=+new Date;this._micLocalAudioStream=await Z5(this._deviceManager,this._logger),this._logger.log(`Got selected or default microphone`),this.sendTelemetryEvent(+new Date-n,{step:X5.SELECT_MICROPHONE,timestampInfo:{attemptTimestamp:n}},[`Success`],200);let r=+new Date;try{this._audioEffectsFeature=this._micLocalAudioStream.feature(B3(s8));let e=r8().engine;await this._audioEffectsFeature.startEffects({noiseSuppression:e===`Chromium`?this._noiseSuppression:e===`Safari`?void 0:`BrowserNoiseSuppression`,echoCancellation:e===`Chromium`?this._echoCancellation:`BrowserEchoCancellation`}),this.sendTelemetryEvent(+new Date-r,{step:X5.SET_NOISE_SUPPRESSION,timestampInfo:{attemptTimestamp:r}},[`Success`],200)}catch(e){this._logger.error(`Failed to start effects sdk noise suppression`,e);let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.START_EFFECTS_FAIL,originalError:e});throw this._logger.error(t.message),t}this._logger.log(`Effects applied to mic stream with audio effects feature`);let a=+new Date,o;this._micIRawStream=this._deviceManager.getRawDeviceMediaStream(0),this._micIRawStream.changed((async()=>{let e=+new Date;try{this._logger.log(`Microphone raw stream changed`);try{this._micRawMediaStream=await this._micIRawStream?.getMediaStream(!0)}catch(e){this._logger.error(`Failed to get updated raw mic media stream from dm on changed event`,e);let t=K3(e,!0,new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.MICROPHONE_RAW_MEDIASTREAM_CHANGED_FAIL,originalError:e}));throw this._logger.error(t.message),t}this._logger.log(`Got updated raw mic stream from dm on changed event`),this._mediaStreamSession&&this._micRawMediaStream&&this._mediaStreamSession.updateOutboundAudioStream(this._micRawMediaStream),this.sendTelemetryEvent(+new Date-e,{step:X5.MICROPHONE_RAW_MEDIASTREAM_CHANGED,timestampInfo:{attemptTimestamp:e}},[`Success`],200)}catch(t){this._logger.error(`Error handling microphone raw stream changed event`,t);let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.MICROPHONE_RAW_MEDIASTREAM_CHANGED_FAIL,originalError:t});this._logger.error(n.message),this.sendTelemetryEvent(+new Date-e,{step:X5.START_RECORD_AUDIO,timestampInfo:{attemptTimestamp:e},...J3(n)},n.resultCategories,500)}}));try{o=await this._micIRawStream.getMediaStream(!0)}catch(e){this._logger.error(`Failed to get raw mic media stream from dm`,e);let t=K3(e,!0,new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.GET_MIC_STREAM_FAIL,originalError:e}));throw this._logger.error(t.message),t}this._logger.log(`Got raw mic stream from dm`),this.sendTelemetryEvent(+new Date-a,{step:X5.GET_MIC_STREAM,timestampInfo:{attemptTimestamp:a}},[`Success`],200),e(o)}catch(e){this._logger.error(`Error getting microphone media stream`,e);let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.GET_MIC_STREAM_FAIL,originalError:e});this._logger.error(n.message),t(n)}})),[d,f]=await Promise.all([l,u]);this._playerWorkletNode=d,this._micRawMediaStream=f;let p=+new Date,m;try{this._playerAudioSourceNode=this._playerAudioContext.createMediaStreamSource(this._micRawMediaStream),this._playerAudioSourceNode.connect(this._playerWorkletNode),m=this._playerAudioContext.createAnalyser(),m.fftSize=2048,this._playerAudioSourceNode.connect(m),this._playerAudioDestinationNode=this._playerAudioContext.createMediaStreamDestination(),this._playerWorkletNode.connect(this._playerAudioDestinationNode),this._playerRawMediaStream=this._playerAudioDestinationNode.stream,this._playerAudioStream=new f8(this._playerRawMediaStream),this._logger.log(`Created local audio stream from player media stream`),c.getMicStreamSettleTimeInMs>0&&await new Promise((e=>{setTimeout((()=>{this._logger.log(`Mic stream settled`),e()}),c.getMicStreamSettleTimeInMs)})),this._logger.log(`Connected microphone media stream to player worklet node`),this.sendTelemetryEvent(+new Date-p,{step:X5.CONNECT_MIC_TO_PLAYERWORKLET,timestampInfo:{attemptTimestamp:p}},[`Success`],200)}catch(e){this._logger.error(`Failed to connect microphone media stream to player worklet node`,e);let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.CONNECT_MIC_TO_PLAYERAUDIOBUFFER_FAIL,originalError:e});throw this._logger.error(t.message),t}let h=!1,g=null,_=null,v=performance.now(),y=+new Date,b;this._logger.log(`Start time of silence detection: ${y}`);let x=c.speechTimeoutInSec,S=c.rmsThreshold,C=n?c.speechDurationThresholdForPreheated:c.speechDurationThreshold,w=c.silenceDurationThreshold;this._logger.log(`Will use the following thresholds for silence detection:\n Speech Timeout: ${x} seconds,\n RMS Threshold: ${S},\n Speech Duration Threshold: ${C} seconds,\n Silence Duration Threshold: ${w} seconds\n `);let T=0,E=c.logging.rmsLogIntervalInMs,ee=0,D=0,O=c.logging.silenceLogIntervalInMs,k=0,A=c.logging.speechLogIntervalInMs;this._statsReport.rmsMaxDetected={rmsLogIntervalInMs:E,rmsIntervals:[]};let j=async()=>{let e=new Uint8Array(m.fftSize);m.getByteTimeDomainData(e);let t=Math.round(1e4*Math.sqrt(e.reduce(((e,t)=>e+(t-128)**2),0)/e.length))/1e4,n=Math.round((performance.now()-v)/1e3*100)/100;t>ee&&(ee=t);let r=performance.now();if(r-T>=E&&(this._logger.log(`RMS: ${ee}, Seconds past silence detection start: ${n}`),this._statsReport.rmsMaxDetected?.rmsIntervals.push({secondsPastSilenceDetectionsStart:n,maxRms:ee}),T=r,ee=0),n>x&&h)return this._logger.log(`PreAudio silence detection timed out after ${x} seconds. Will shut down player audio worklet, speed up rest of the buffer, and then switch to microphone`),this._statsReport.finishType=X5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SPEEDUP_AFTER_TIMEOUT,this._statsReport.speechSilenceDetectionDurationInMs=+new Date-y,this._playerWorkletNode?.port.postMessage({type:`shutDown`,value:{shutDownType:`speedUpBuffer`}}),void this.sendTelemetryEvent(+new Date-y,{step:X5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SPEEDUP_AFTER_TIMEOUT,timestampInfo:{attemptTimestamp:y},rmsMaxDetected:this._statsReport.rmsMaxDetected},[`Success`],200);if(this._isFinished||!h&&(this._play||n>x)){let e,t;this._isFinished?(this._logger.log(`PreAudio already finished, will not do any silence detection and will shutdown player audio worklet`),e=X5.SHUTDOWN_ALREADY_FINISHED):!h&&this._play?(this._logger.log(`No speech detected when play was called. Will switch to real-time microphone, and shut down player audio worklet async`),t=`Failed to dispose PreAudio feature after preAudio finished due to no speech detected`,e=X5.SHUTDOWN_NO_SPEECH_DETECTED):!h&&n>x&&(this._logger.log(`PreAudio silence detection timed out after ${x} seconds and no speech was detected. Will shut down player audio worklet and switch to real-time microphone`),t=`Failed to dispose PreAudio feature when no speech was detected after timeout`,e=X5.SHUTDOWN_PLAYERAUDIOWORKLET_NOSPEECHDETECTED_AFTER_TIMEOUT),this._isFinished=!0,this._statsReport.finishType=e,this._statsReport.speechSilenceDetectionDurationInMs=+new Date-y,this.disposeInternal().catch((()=>{this._logger.error(t)})),this.sendTelemetryEvent(+new Date-y,{step:e,timestampInfo:{attemptTimestamp:y},rmsMaxDetected:this._statsReport.rmsMaxDetected},[`Success`],200),this._switchToRealTimeMic();return}if(t>S){if(_===null&&(this._logger.log(`Starting speech timer at ${n} seconds past start`),_=performance.now(),b=Date.now()),g=null,(performance.now()-_)/1e3>=C){h=!0;let e=performance.now();e-k>=A&&(this._logger.log(`Speech detected for at least a duration of ${C} seconds at ${n} seconds past start`),k=e),this._pendingSpeechStartEpoch===void 0&&(this._pendingSpeechStartEpoch=b,this._logger.log(`Captured pending first speech epoch: ${this._pendingSpeechStartEpoch}`),this.applyPendingSpeechStartTimestampToSession(`post-detection`))}}else if(g===null&&(this._logger.log(`Starting silence timer at ${n} seconds past start`),g=performance.now()),(performance.now()-g)/1e3>=w){if(h){this._logger.log(`Silence detected for a duration of at least 1 second at ${n} seconds past start`),this._playerWorkletNode?.port.postMessage({type:`shutDown`,value:{shutDownType:`speedUpBuffer`}});let e=+new Date-y;this._statsReport.totalRtcAudioBufferedDurationInMs=e,this._statsReport.finishType=X5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SILENCE_DETECTED_AFTER_SPEECH,this._statsReport.speechSilenceDetectionDurationInMs=+new Date-y,this.sendTelemetryEvent(e,{step:X5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SILENCE_DETECTED_AFTER_SPEECH,timestampInfo:{attemptTimestamp:y},rmsMaxDetected:this._statsReport.rmsMaxDetected,totalRtcAudioBufferedDurationInMs:e},[`Success`],200);return}let e=performance.now();e-D>=O&&(this._logger.log(`Silence detected for at least 1 second, but no speech detected yet. RMS: ${t}. Seconds past start: ${n}`),D=e),_=null,b=void 0}requestAnimationFrame(j)};j(),this._logger.log(`Audio recording started successfully`);let te=+new Date-i;this._statsReport.recordAudioSuccessTimestamp=te,this.sendTelemetryEvent(te-o,{step:X5.START_RECORD_AUDIO,timestampInfo:{attemptTimestamp:o,successTimestamp:te,createMediaSdkStackBaseDuration:a,adpDuration:i}},[`Success`],200)}catch(e){this._recordAudioFailed=!0,this._logger.error(`Audio recording failed`,e),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature when handling audio recording error`)})),this._switchToRealTimeMic();let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.FAILED_TO_RECORD,originalError:e});throw this._logger.error(t.message),this.sendTelemetryEvent(+new Date-o,{step:X5.START_RECORD_AUDIO,timestampInfo:{attemptTimestamp:o},createMediaSdkStackBaseDuration:a,adpDuration:i,...J3(t)},t.resultCategories,500),t}finally{this._recordAudioFinished=!0}}play(){let e=+new Date;try{this._storeRecording&&this._playerRawMediaStream&&(this._recording=new MediaRecorder(this._playerRawMediaStream,{mimeType:this._recordingMimeType}),this._recordingChunks=[],this._recording.ondataavailable=e=>{e.data.size&&(this._logger.log(`Got preaudio recording data`),this._recordingChunks.push(e.data))},this._recording.start()),this._play=!0,this._playerWorkletNode?.port.postMessage({type:`play`,value:!0}),this._logger.log(`Audio playback started`),this.sendTelemetryEvent(+new Date-e,{step:X5.START_PLAY_AUDIO,timestampInfo:{attemptTimestamp:e}},[`Success`],200)}catch(t){this._logger.error(`Audio playback failed`,t),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature when handling audio playback error`)}));let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.FAILED_TO_PLAY,originalError:t});throw this._logger.error(n.message),this.sendTelemetryEvent(+new Date-e,{timestampInfo:{attemptTimestamp:e},step:X5.START_PLAY_AUDIO,...J3(n)},n.resultCategories,500),n}}downloadRecording(){if(!this._storeRecording||!this._recordingMimeType)return;let e=this._recordingMimeType?.includes(`ogg`)?`ogg`:this._recordingMimeType?.includes(`mp4`)?`m4a`:`webm`,t=new Blob(this._recordingChunks,{type:this._recordingMimeType}),n=document.createElement(`a`);n.href=URL.createObjectURL(t),n.download=`preAudio_recording_${+new Date}.${e}`,n.click(),URL.revokeObjectURL(n.href)}async dispose(){return await this.disposeInternal(!1)}_switchToRealTimeMic(){this._internalDisposed&&this._switchToRealTimeMicCallBack?.()}};function Q5(e,t,n,r,i,a){let o=a?J3(a):void 0;r&&i&&V3({featureName:`activeCallTransfer`,featureDetails:{name:`activeCallTransfer`,step:t},featureType:`callAgent`,localParticipantId:e,callId:n?.callId??``,correlationId:``,initializationType:`OnFeatureAccess`,additionalDetails:o},r,i)}var lIe=class{constructor(e,t,n,r){this._skypeConversationObjectMaps=new Map,this._callAgent=e,this._tsCallRegistry=t,this._clientLogger=r}async transferActiveCall(e,t,n){let r,i,a=mTe(e);if(r=this._skypeConversationObjectMaps.get(e.callId),!r)throw this._clientLogger.error(`No SkypeConversationObject found for active call with callId: ${e.callId}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.CONVERSATION_NOT_FOUND});if(a){let t=e.meetingLocator.organizerId;r={...r,groupCallInitiator:t},i=2}else i=0;let o={skypeConversationObject:r,mediaPeerType:i},s=n?.joinCallOptions?.videoOptions?.localVideoStreams&&n.joinCallOptions.videoOptions.localVideoStreams.length>0,c=!0!==n?.joinCallOptions?.audioOptions?.muted,l={shouldResurrect:`resurrect`,...o},u,d=J0(),f=PG();try{u=await this._tsCallRegistry.createCallAsync({causeId:f,localParticipantId:d,type:`ThreadId`,callId:e.callId,threadId:a?e.meetingLocator.threadId:``});let i=t.createNewCall(e.callId,u);if(mTe(e)?await u.joinWithMeetingData(f,r,l):await u.join(r,l,f),i.bindTsCall(),s&&n?.joinCallOptions?.videoOptions?.localVideoStreams&&i.startVideo(n.joinCallOptions.videoOptions.localVideoStreams[0]),!1===c&&this._callAgent.deviceManager.selectedMicrophone){this._callAgent.deviceManager.selectedMicrophone;let e=new f8(this._callAgent.deviceManager.selectedMicrophone);i.startAudio(e)}if(this._callAgent.addToCallArray(i),this._callAgent.handleCallState(i),n?.isTransfer){let e=u.endpointId;try{await u.removeParticipant(this._callAgent.getUserMri(),f,e,1)}catch(e){throw this._clientLogger.error(`Failed to remove participant from call during transfer: ${e}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.FAILED_TO_REMOVE_PARTICIPANT,originalError:e})}}return Q5(this._callAgent.getUserMri(),$.success,e),i}catch(e){throw this._clientLogger.error(`Active call transfer failed: ${e}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.ACTIVE_CALL_TRANSFER_FAILURE,originalError:e})}}async getActiveCallDetails(e){let t=this._callAgent.getHttpRequestHelper(),n=this._callAgent.getUserMri(),r={headers:{"Content-Type":`application/json`,"X-SkypeToken":e.jwtToken},method:`GET`},i=Z().calling.activeCallTransfer.callStoreUrl,a=await t.send(i+`${n}/conversations`,JSON.stringify({}),r,3),o=await t.extractPayload(a);if(o&&a.status===200){let e=o,t=e[0];e.length>1&&e.forEach((e=>{e.userJoinTime&&t.userJoinTime&&e.userJoinTime>t.userJoinTime&&(t=e)}));let n=e.map((e=>{if(this._skypeConversationObjectMaps.set(e.correlationId,{conversationUrl:e.conversationController,conversationId:e.correlationId}),`meetingInfo`in e)return this._clientLogger.info(`Found active meeting for client with callId: ${e.correlationId}, threadId: ${e.groupContext.threadId}`),{callId:e.correlationId,meetingLocator:{threadId:e.groupContext.threadId,organizerId:e.meetingInfo.organizerId,tenantId:e.meetingInfo.tenantId,messageId:e.meetingInfo.replyChainMessageId??``},userJoinTime:new Date(e.userJoinTime)};{let t=e.participants.map((e=>q2(e)));return{callId:e.correlationId,participants:t,userJoinTime:new Date(e.userJoinTime)}}}));return this._clientLogger.log(`[ActiveCallTransfer] activeCallList:`,n),n}if(o&&a.status>=400)throw this._clientLogger.error(`Failed to get active calls for client with error: ${o.message}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.GET_ACTIVE_CALL_DETAILS_INVALID_TOKEN,originalError:Error(o.message)});this._clientLogger.info(`No active calls found for the client`)}},uIe=class extends LEe{initialize(e,t){if(t.info(`Initializing ActiveCallTransferFeatureImpl`),this._logger=t,this._tsCallRegistry=this._callAgent.getInternalCallRegistry(),this._telemetryLogger=e.telemetryLogManager,this._tsCallRegistry?.on(`proxiedPushNotification`,this.handleProxiedNotification),!this._tsCallRegistry||!this._telemetryLogger)throw this._logger?.error(`Failed to initialize ActiveCallTransferFeatureImpl: TS Call Registry or Telemetry Logger is undefined`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.CALLAGENT_NOT_INITIALIZED});this._activeCallTransferManager=new lIe(this._callAgent,this._tsCallRegistry,this._telemetryLogger,this._logger)}constructor(e){super(e),this.name=`ActiveCallTransfer`,this.handleProxiedNotification=async e=>{let t,n=this._callAgent._caConfigBag.parsedTokenCredential;if(n){if(e.eventId===115&&this._activeCallTransferManager)this._logger?.log(`Received proxied notification with eventId 115`,e),t=await this._activeCallTransferManager?.getActiveCallDetails(n),t&&t.length>0?(this._logger?.log(`Active call found, emitting activeCallsUpdated event`),Q5(this._callAgent.getUserMri(),$.success,t[0],this._telemetryLogger,this._logger),this.emitNewActiveCallDetailsEvent(t)):this._logger?.log(`No active call found, not emitting activeCallsUpdated event`);else if(e.eventId===116&&this._activeCallTransferManager){if(this._logger?.log(`Received proxied notification with eventId 116`,e),t=await this._activeCallTransferManager?.getActiveCallDetails(n),t&&t.length>0)return this._logger?.log(`Active call found on eventId 116, emitting activeCallsUpdated event, forgoing noActiveCalls event`),Q5(this._callAgent.getUserMri(),$.success,t[0],this._telemetryLogger,this._logger),void this.emitNewActiveCallDetailsEvent(t);this._logger?.log(`No active call found on eventId 116, emitting noActiveCalls event`),Q5(this._callAgent.getUserMri(),$.success,void 0,this._telemetryLogger,this._logger),this.emitNoActiveCallsEvent()}}else this._logger?.error(`No valid token found, cannot process active call details`)},this._callAgent=e.callAgent}async activeCallTransfer(e,t){let n;Q5(this._callAgent.getUserMri(),$.attempt,e,this._telemetryLogger,this._logger);try{if(!this._activeCallTransferManager){let t=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.MANAGER_UNDEFINED,originalError:Error(`ActiveCallTransferManager not initialized`)});throw Q5(this._callAgent.getUserMri(),$.failure,e,this._telemetryLogger,this._logger,t),t}n=await this._activeCallTransferManager.transferActiveCall(e,this._callAgent,t),this._callAgent.handleActiveCallTransfer(n)}catch(t){this._logger?.error(`Failed to handle active call transfer`,t);let n=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.ACTIVE_CALL_TRANSFER_FAILURE,originalError:t});throw Q5(this._callAgent.getUserMri(),$.failure,e,this._telemetryLogger,this._logger,n),n}return Q5(this._callAgent.getUserMri(),$.success,e,this._telemetryLogger,this._logger),n}async getActiveCallDetails(){Q5(this._callAgent.getUserMri(),$.attempt,void 0,this._telemetryLogger,this._logger);let e=this._callAgent._caConfigBag.parsedTokenCredential;if(!this._activeCallTransferManager||!e){this._logger?.error(`Failed to get active call details: ActiveCallTransferManager not initialized or token is invalid`);let e=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.MANAGER_TOKEN_UNDEFINED,originalError:Error(`ActiveCallTransferManager not initialized or token is invalid`)});throw Q5(this._callAgent.getUserMri(),$.failure,void 0,this._telemetryLogger,this._logger,e),e}let t;try{t=await this._activeCallTransferManager?.getActiveCallDetails(e)}catch(e){this._logger?.error(`Failed to get active call details`,e);let t=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.GET_ACTIVE_CALL_DETAILS_FAILURE,originalError:e});throw Q5(this._callAgent.getUserMri(),$.failure,void 0,this._telemetryLogger,this._logger,t),t}return Q5(this._callAgent.getUserMri(),$.success,void 0,this._telemetryLogger,this._logger),t}dispose(){this.eventEmitter.removeAllListeners()}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}emitNewActiveCallDetailsEvent(e){this.eventEmitter.emit(`activeCallsUpdated`,{activeCallDetails:e})}emitNoActiveCallsEvent(){this.eventEmitter.emit(`noActiveCalls`)}},$5={Recording:R3(COe),Transfer:R3(FOe),Transcription:R3(kOe),Captions:R3(sDe),Copilot:R3(dDe),RaiseHand:R3(pDe),LocalRecording:R3(EOe),Reaction:R3($Pe),Spotlight:R3(FAe),PPTLive:R3(rFe),BreakoutRooms:R3(wFe),Capabilities:R3(wDe),DominantSpeakers:R3(BDe),LiveStream:R3(Dke),ComposedStream:R3(Ake),CallSurvey:R3(LAe),UserFacingDiagnostics:R3(FDe),MediaStats:R3(SOe,{activationEvent:`OnExtendedObjectConstructor`}),DebugInfo:GEe(jDe,{activationEvent:`OnExtendedObjectConstructor`}),PreCallDiagnostics:GEe(yke),VideoEffects:qEe(q6),AudioEffects:B3(s8),DataChannel:R3(PAe),OptimalVideoCount:R3(BAe),UnmixedAudio:R3(rje),AudioZones:R3(RAe),TeamsMeetingAudioConferencing:R3(ije),TogetherMode:R3(mFe),MediaAccess:R3(e6),RealTimeText:R3(EFe),DataChannelSession:z3($Fe,{activationEvent:`OnExtendedObjectConstructor`}),MediaStatsSession:z3(rIe,{activationEvent:`OnExtendedObjectConstructor`}),UserFacingDiagnosticsSession:z3(iIe,{activationEvent:`OnExtendedObjectConstructor`}),PreAudioSession:KEe(cIe),ActiveCallTransfer:WEe(uIe)};function e7(e){switch(e){case k3.CallClientFeature:return Object.entries($5).filter((e=>!0===e[1].isCallClientFeature)).map((e=>e[1]));case k3.CallAgentFeature:return Object.entries($5).filter((e=>!0===e[1].isCallAgentFeature)).map((e=>e[1]));case k3.CallFeature:return Object.entries($5).filter((e=>!0===e[1].isCallFeature)).map((e=>e[1]));case k3.MediaClientFeature:return Object.entries($5).filter((e=>!0===e[1].isMediaClientFeature)).map((e=>e[1]));case k3.SessionFeature:return Object.entries($5).filter((e=>!0===e[1].isSessionFeature)).map((e=>e[1]))}}var dIe=class{constructor(e,t){this._eventBag=[],this.resetEventBag=()=>{this._eventBag=[]},this._logger=e.createChild(`CallStats`),this._telemetryLogManager=t}recordEvent(e){try{if(Z()?.telemetry?.callStatsFlushTimeout<0||Z()?.telemetry?.blockedEvents?.indexOf(e.name)>-1)return;let t={timestamp:+new Date,...e};this._logger.debug(`CallStat recorded=${e.name}`),this._eventBag.push(t),this.scheduleTelemetryFlush()}catch{this._logger.debug(`Failed to record call stats`)}}flushEvents(){if(this._logger.debug(`CallStats sending telemetry, number of events=${this._eventBag.length}`),this._eventBag.length!==0)try{let e=this._eventBag.reduce(((e,t)=>(e[t.localParticipantId]?e[t.localParticipantId].events.push({name:t.name,timestamp:t.timestamp,...t.data}):e[t.localParticipantId]={callId:t.callId,localParticipantId:t.localParticipantId,events:[{name:t.name,timestamp:t.timestamp,...t.data}]},e)),{});Object.keys(e).forEach((t=>{this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_stats,tenant:p2,properties:{...e[t]}})})),this.resetEventBag()}catch{this._logger.debug(`Failed to send call stats`)}}scheduleTelemetryFlush(){this._callStatSendTimeout||=window.setTimeout((()=>{this.flushEvents(),this._callStatSendTimeout=void 0}),Z().telemetry.callStatsFlushTimeout)}};function t7(e,t){if(t===`Connected`)return;let n;if(e==c4.MuteAllRemoteParticipants)n=J.CALL.MUTE_ALL_PARTICIPANTS_CALL_NOT_CONNECTED;else if(e==c4.StopAudio)n=J.CALL.STOP_AUDIO_STREAM_CALL_NOT_CONNECTED;else if(e==c4.AddParticipant)n=J.CALL.ADD_PARTICIPANT_CALL_NOT_CONNECTED;else{if(e!=c4.RemoveParticipant)return;n=J.CALL.REMOVE_PARTICIPANT_CALL_NOT_CONNECTED}throw new Y({defaultError:n})}var fIe=class{constructor(e){this._volumeIndicator=e,this._eventEmitter=new D3}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get level(){return this._volumeIndicator.level}async setSource(e){this._mediaStream!==e&&(this._mediaStream&&this._volumeIndicator.dispose(),e&&(this._mediaStream=e,await this._volumeIndicator.getVolumeIndicator(e),this._volumeIndicator.on(`levelChanged`,(()=>{this._eventEmitter.emit(`levelChanged`)}))))}dispose(){this._eventEmitter.removeAllListeners()}},pIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},mIe=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},hIe=class{constructor(e,t,n,r){this._workQueue=Promise.resolve();let i=ZW(`ACS-calling`);this.logger=new V6(i,[()=>`RemoteAudioStream for media stream`]),this._source=e,this._disposed=!1,this._volumeIndicator=new Q6(this.logger,`RemoteAudioStream`,t,n,r),e.changed((async()=>{this._volumeProxy&&(this._workQueue=this._workQueue.then((async()=>{await this._volumeProxy?.setSource(await this._source.getMediaStream())})).catch((e=>{this.logger.log(`source changed but failed to update volume indicator: ${e?.message??`unknown error`}`)})))})),this.logger.info(`created`)}async getMediaStream(){return await this._source.getMediaStream()}get source(){return this._source}dispose(){this.logger.log(`dispose`),this._disposed?this.logger.log(`already disposed`):(this._volumeIndicator.dispose(),this._disposed=!0)}async getVolume(){if(!this._volumeProxy){let e=new fIe(this._volumeIndicator),t=this._workQueue.then((async()=>{await e.setSource(await this._source.getMediaStream())}));this._workQueue=t.catch(M4),await t,this._volumeProxy=e}return this._volumeProxy}};pIe([UG,mIe(`design:type`,Object)],hIe.prototype,`logger`,void 0);var gIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},_Ie=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},vIe=class{get currentVideoConstraints(){return this._currentVideoConstraints}constructor(e,t,n){this._tsCall=e,this._currentVideoConstraints={send:{frameHeight:{max:void 0},frameRate:{max:void 0},bitrate:{max:void 0}}},this._logger=t.createChild(`MediaConstraintsManager`),this._telemetryLogManager=n}async setVideoConstraints(e,t,n,r){let i=this.getTelemetryPayload({video:e}),a=e=>{let i=e?{failureReason:e?e.message:void 0,code:e?e.code:void 0,...J3(e)}:void 0;V3({correlationId:n,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:`SetConstraints`,featureType:`Call`,initializationType:`None`,timestampInfo:{deltaTimeInMs:+new Date-r},featureDetails:{name:`setConstraints`,step:e?$.failure:$.success,stage:t},additionalDetails:{constraints:this.getTelemetryPayload({video:this._currentVideoConstraints}),...i}},this._telemetryLogManager,this._logger)};try{if(V3({correlationId:n,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:`SetConstraints`,featureType:`Call`,initializationType:`None`,timestampInfo:``,featureDetails:{name:`setConstraints`,step:$.attempt,stage:t},additionalDetails:{constraints:i}},this._telemetryLogManager,this._logger),!Z().calling.constraints.enabled)throw this._logger.error(`Setting call constraints is disabled`),new Y({defaultError:J.CALL.MEDIA_CONSTRAINTS_DISABLED});this._updateVideoConstraintsCache(e);let r={outgoingVideoLimit:{maxResolution:this._currentVideoConstraints.send?.frameHeight?.max,maxFramerate:this._currentVideoConstraints.send?.frameRate?.max,maxBitrate:this._currentVideoConstraints.send?.bitrate?.max}},o=this._tsCall.setCallConstraints?.(r);if(t!==`mid-call`)o?.then((()=>{this._logger.info(`Successfully set call constraints at call ${t} - ${JSON.stringify(this._currentVideoConstraints)}`),a()})).catch((e=>{this._logger.error(`Error setting call constraints at call ${t}`),a(new Y({defaultError:J.CALL.SET_CONSTRAINTS_START_OR_ACCEPT,defaultErrorMessageArgs:[t],originalError:e}))}));else try{await o,this._logger.info(`Successfully set call constraints during ${t} - ${JSON.stringify(this._currentVideoConstraints)}`),a()}catch(e){throw new Y({defaultError:J.CALL.SET_CONSTRAINTS_MID_CALL,originalError:e})}return this._currentVideoConstraints}catch(e){let n=new Y({defaultError:J.CALL.SET_CONSTRAINTS,defaultErrorMessageArgs:[t],originalError:e});throw a(n),n}}getTelemetryPayload(e){return{video:{send:{frameHeight:{max:e.video?.send?.frameHeight?.max},frameRate:{max:e.video?.send?.frameRate?.max},bitrate:{max:e.video?.send?.bitrate?.max}}}}}_updateVideoConstraintsCache(e){let t=Z(),n=t.calling.constraints.maxOutgoingResolution,r=t.calling.constraints.maxOutgoingFrameRate,i=t.calling.constraints.maxOutgoingVideoBitrate,a=e?.send?.frameHeight?.max??this._currentVideoConstraints.send?.frameHeight?.max,o=e?.send?.frameRate?.max??this._currentVideoConstraints.send?.frameRate?.max,s=e?.send?.bitrate?.max??this._currentVideoConstraints.send?.bitrate?.max;this._currentVideoConstraints={send:{frameHeight:{max:this._getConstraintValue(n,`maxOutgoingResolution`,a)},frameRate:{max:this._getConstraintValue(r,`maxOutgoingFrameRate`,o)},bitrate:{max:this._getConstraintValue(i,`maxOutgoingBitrate`,s)}}}}_getConstraintValue(e,t,n){return typeof n==`number`?n<1?void this._logger.info(`Received ${t} as 0 or less, removing ${t} constraint`):(e>0&&n>e&&(this._logger.info(`${t} value ${n} is larger than ${e}, resetting to ${e}`),n=e),n):void this._logger.warn(`Received invalid ${t} value, removing ${t} constraint`)}};gIe([UG,_Ie(`design:type`,Object)],vIe.prototype,`_logger`,void 0);var n7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},r7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},i7=class{constructor(e,t,n,r){this.logger=n.createChild(`Lobby`),this._tsCall=e,this._eventEmitter=new w6(this.logger),this._participants=new Map,this._call=t,this._telemetryLogManager=r,this._lobbySupportedConversationTypes=Z().calling.lobbyAdmitAndReject.supportedConversationTypes,this._isLobbyEnabled=Z().calling.lobbyAdmitAndReject.enabled,this._hasExpectedError=!1,this._isLobbyEnabled&&(this.getInLobbyParticipants(t.remoteParticipants),this._remoteParticipantUpdatedListener=e=>{if(e.added.length!==0&&e.added.forEach((e=>{e.state===`InLobby`&&this.addLobbyParticipant(e),e.on(`stateChanged`,(()=>{e.state===`InLobby`?this.addLobbyParticipant(e):e.state===`Connected`&&this.removeLobbyParticipant(e)}))})),e.removed.length!==0){if(this._call.remoteParticipants.length===0)return void this.removeAllLobbyParticipants();e.removed.forEach((e=>{this.removeLobbyParticipant(e)}))}},this._call.on(`remoteParticipantsUpdated`,this._remoteParticipantUpdatedListener))}on(e,t){if(e!==`lobbyParticipantsUpdated`)throw new Y({defaultError:J.LOBBY.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`lobbyParticipantsUpdated`)throw new Y({defaultError:J.LOBBY.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}async admit(e,t){if(!this._isLobbyEnabled)return void this.logger.warn(`Lobby is not enabled`);let n=J0(),r=+new Date;this._sendLobbyAdmitAndRejectUsage(`Start admit participant`,u3.lobbyAdmit,n,$.attempt,void 0);try{Y2(e),this.validateLobbyOperation(e),await this._tsCall.admitParticipant(K2(e));let t=+new Date;this._sendLobbyAdmitAndRejectUsage(`Lobby participant admitted successfully`,u3.lobbyAdmit,n,$.success,t-r)}catch(e){let t=f3.Unexpected;this._hasExpectedError&&=(t=f3.Expected,!1),this.handleLobbyAdmitAndRejectFailure(`Failed to admit participant from lobby`,e,n,r,u3.lobbyAdmit,t)}}async reject(e,t){if(!this._isLobbyEnabled)return void this.logger.warn(`Lobby is not enabled`);let n=J0(),r=+new Date;this._sendLobbyAdmitAndRejectUsage(`Start reject participant`,u3.lobbyReject,n,$.attempt,void 0);try{Y2(e),this.validateLobbyOperation(e),await this._tsCall.removeParticipant(K2(e));let t=+new Date;this._sendLobbyAdmitAndRejectUsage(`Lobby participant rejected successfully`,u3.lobbyReject,n,$.success,t-r)}catch(e){let t=f3.Unexpected;this._hasExpectedError&&=(t=f3.Expected,!1),this.handleLobbyAdmitAndRejectFailure(`Failed to reject participant from lobby`,e,n,r,u3.lobbyReject,t)}}async admitAll(e){let t=J0(),n=+new Date,r,i=0,a=0;if(!this._isLobbyEnabled)return this.logger.warn(`Lobby is not enabled`),{successCount:i,failureCount:a};this._sendLobbyAdmitAndRejectUsage(`Start admit all participants`,u3.lobbyAdmitAll,t,$.attempt,void 0);try{this.validateLobbyOperation(),await this._tsCall.admit({scope:`all`},PG()).then((e=>{if(r=e,e.result){let t=JSON.parse(e.result);i=t.successCount,a=t.failureCount}}));let e=+new Date;if(a!==0)return this._sendLobbyAdmitAndRejectUsage(`${i} participants are admitted successfully, ${a} participants admit failed. TransactionEnd: ${r}`,u3.lobbyAdmitAll,t,$.success,e-n),{successCount:i,failureCount:a};this._sendLobbyAdmitAndRejectUsage(`All participants are admitted successfully`,u3.lobbyAdmitAll,t,$.success,e-n)}catch(e){let r=f3.Unexpected;this._hasExpectedError&&=(r=f3.Expected,!1),this.handleLobbyAdmitAndRejectFailure(`Failed to admit all participants from lobby`,e,t,n,u3.lobbyAdmitAll,r)}return{successCount:i,failureCount:a}}get participants(){return this._isLobbyEnabled?Array.from(this._participants.values()):(this.logger.warn(`Lobby is not enabled`),[])}getInLobbyParticipants(e){e.forEach((e=>{if(e.state===`InLobby`){let t=K2(e.identifier);this._participants.set(t,e)}}))}removeAllLobbyParticipants(){if(this._participants.size===0)return;let e=Array.from(this._participants.values());this._participants.clear(),this.logger.info(`All participants are removed from lobby`),this._eventEmitter.emit(`lobbyParticipantsUpdated`,{added:[],removed:e})}removeLobbyParticipant(e){let t=K2(e.identifier);this._participants.has(t)&&(this.logger.info(`${OG(e.identifier).kind} is removed from lobby`),this._participants.delete(t),this._eventEmitter.emit(`lobbyParticipantsUpdated`,{added:[],removed:[e]}))}addLobbyParticipant(e){let t=K2(e.identifier);this._participants.has(t)||(this.logger.info(`${OG(e.identifier).kind} is added to lobby`),this._participants.set(t,e),this._eventEmitter.emit(`lobbyParticipantsUpdated`,{added:[e],removed:[]}))}validateLobbyOperation(e){let t=this._tsCall.conversationType?this._tsCall.conversationType:`oneToOneCall`;if(this.logger.info(`Current conversation type is: `,t),!this._lobbySupportedConversationTypes.find((e=>e===t)))throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.CONV_UNSUPPORTED});if(e){let t=this._call.remoteParticipants.find((t=>K2(t.identifier)===K2(e)));if(t&&t.state===`Connected`)throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.ALREADY_IN_MEETING,defaultErrorMessageArgs:[OG(e).kind]});if(t&&t.state!==`InLobby`||!t)throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.NOT_IN_LOBBY,defaultErrorMessageArgs:[OG(e).kind]})}if(this._call.role!==z2.Presenter&&this._call.role!==z2.Organizer&&this._call.role!==z2.Coorganizer)throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.UNAUTHORIZED_ADMIT_REJECT})}handleLobbyAdmitAndRejectFailure(e,t,n,r,i,a){let o=+new Date,s=rDe(this.logger,t,e);throw this._sendLobbyAdmitAndRejectUsage(s.message,i,n,$.failure,o-r,a,t),s}_sendLobbyAdmitAndRejectUsage(e,t,n,r,i,a,o){r===$.failure?this.logger.error(e):this.logger.info(e),this.sendLobbyAdmitAndRejectEvent({eventName:Q.acs_calling_lobby_events,callId:this._call.id,localParticipantId:this._tsCall.participantId,correlationId:n,kindOfEvent:r,operation:t,isExpected:a??``,timestampInfo:i?{deltaTimeInMs:i}:``,additionalDetails:o?{failureReason:o.message,code:o.code,subCode:o.subCode,...J3(o)}:``})}sendLobbyAdmitAndRejectEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send lobby admit and reject telemetry`)}}};function yIe(){let e=window.navigator.mediaDevices;if(e?.isRemote){let t=e?.MSRDC_MMR_Shim?.remoteObjectManager?.isConnected;if(!0===t)return`connected`;if(!1===t)return`disconnected`}return``}function a7(){let e=window.navigator.mediaDevices,t={isMMREnabled:e?.isRemote??!1};return t.isMMREnabled&&(e?.mmrClientVersion&&(t.mmrClientVersion=e.mmrClientVersion),e?.mmrExtensionVersion&&(t.mmrExtensionVersion=e.mmrExtensionVersion),e?.mmrHostVersion&&(t.mmrHostVersion=e.mmrHostVersion),e?.activityId&&(t.mmrActivityId=e.activityId),e?.connectionId&&(t.mmrConnectionId=e.connectionId),t.mmrRdpState=yIe()),t}n7([UG,r7(`design:type`,Object)],i7.prototype,`logger`,void 0),n7([YG(c4.LobbyAdmitParticipant),r7(`design:type`,Function),r7(`design:paramtypes`,[Object,Object]),r7(`design:returntype`,Promise)],i7.prototype,`admit`,null),n7([YG(c4.LobbyRejectParticipant),r7(`design:type`,Function),r7(`design:paramtypes`,[Object,Object]),r7(`design:returntype`,Promise)],i7.prototype,`reject`,null),n7([YG(c4.LobbyAdmitAll),r7(`design:type`,Function),r7(`design:paramtypes`,[Object]),r7(`design:returntype`,Promise)],i7.prototype,`admitAll`,null);var bIe=class{constructor(e){this._lastState=``,this._callback=e=>{let t=e?.detail?.state??``;t?t!==this._lastState&&(this._logger.info(`connection state is ${t}`),this._eventEmitter.emit(`stateChange`,t),this._lastState=t):this._logger.info(`connection state is unknown`)},this._logger=e.createChild(`MmrRdpConnectionManager`),this._eventEmitter=new E3.EventEmitter;let t=window.navigator.mediaDevices;t?.isRemote&&(t?.addEventListener(`rdpClientConnectionStateChanged`,this._callback),this._logger.info(`listener registered`))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get state(){return yIe()}dispose(){let e=window.navigator.mediaDevices;e?.isRemote&&(e?.removeEventListener(`rdpClientConnectionStateChanged`,this._callback),this._logger.info(`event listener unregistered`)),this._eventEmitter.removeAllListeners()}},xIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},o7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},s7=class extends v8{constructor(e,t,n,r,i,a,o){let s=i.id;super(e,t,n,s,a,`RemoteVideoStream`),this._remoteParticipantIdentifier=o,this._isAvailable=!1,this.setIsAvailable=e=>{e!==this._isAvailable&&(this._isAvailable=!!e,this.logger.log(`isAvailable changed to ${this._isAvailable}`),this._eventEmitter.emit(`isAvailableChanged`,this._isAvailable),this.call.isHandlingLargeMeetingVideoRendering&&this.call.handleDominantSpeakersVideos(),super.sendRemoteVideoStreamTelemetry())};let c=()=>{if(this.mediaStreamType===`Video`&&n.isHandlingLargeMeetingVideoRendering){for(let e of n.getTopNDominantSpeakersWithVideoOn())if(this.tsStream.isAvailable&&K2(e.identifier)===K2(this._remoteParticipantIdentifier))return void this.setIsAvailable(!0);this.setIsAvailable(!1)}else i.state===7?this.setIsAvailable(!1):(i.state===3&&l.dispose(),this.setIsAvailable(this.tsStream.isAvailable))};this._streamChangedHandler=this.tsStream.changed((()=>{c()}));let l=i.changed((()=>{c()}));c()}on(e,t){if(e!==`isAvailableChanged`&&e!==`sizeChanged`&&e!==`isReceivingChanged`)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`isAvailableChanged`&&e!==`sizeChanged`&&e!==`isReceivingChanged`)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}get isAvailable(){return this._isAvailable}async getMediaStream(){let e=J0(),t=+new Date,n=this.tsStream.negotiationTag??``,r={correlationId:e,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId,negotiationTag:n},operation:y3.getMediaStream,mediaType:this.getMediaType(),streamType:v3.Remote,timestampInfo:{attemptTimestamp:t},kindOfEvent:$.attempt,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};this.sendMediaStreamEvent(r);try{if(!this.tsStream.getRawStream)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.GET_RAW_MEDIA_STREAM});if(!this.tsStream.isAvailable)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.RAWMEDIA_LVS_NOT_AVAILABLE});let r=this.tsStream.getRawStream(),i=await new Promise((async(e,t)=>{let n=setTimeout((()=>{i.dispose(),t(new Y({defaultError:J.REMOTE_VIDEO_STREAM.SUBSCRIBE_MEDIA_STREAM_TIMEOUT}))}),Z().rendering.remoteVideo.getMediaStreamTimeout),i=r.changed((()=>{a()})),a=async()=>{try{let t=await r.getMediaStream();if(!t)return void this.logger.warn(`MediaStream is not yet ready.`);clearTimeout(n),i.dispose(),e(t)}catch(e){this.logger.warn(`MediaStream is not yet ready, error=${e?.message||`unknown`}`)}};a()})),a=i.getVideoTracks()[0];if(!a)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.GET_TRACK});await new Promise(((e,t)=>{let n=()=>{a.removeEventListener(`unmute`,n,!1),e()};a.addEventListener(`unmute`,n,!1),a.muted?setTimeout((()=>{a.removeEventListener(`unmute`,n,!1),t(new Y({defaultError:J.REMOTE_VIDEO_STREAM.TRACK_UNMUTED_TIMEOUT}))}),Z().rendering.remoteVideo.getMediaStreamTimeout):n()}));let o={correlationId:e,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId,negotiationTag:n},operation:y3.getMediaStream,mediaType:this.getMediaType(),streamType:v3.Remote,timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:$.success,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};return this.sendMediaStreamEvent(o),i}catch(r){let i={correlationId:e,operation:y3.getMediaStream,mediaType:this.getMediaType(),streamType:v3.Remote,additionalDetails:{failureReason:r?.message||``,code:r.code||BG,...J3(r),remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId,negotiationTag:n},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:$.failure,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};throw this.sendMediaStreamEvent(i),new Y({defaultError:J.REMOTE_VIDEO_STREAM.GET_MEDIA_STREAM,originalError:r})}}getStreamMetadata(){return{callId:this.call?.id,streamType:this.mediaStreamType,localParticipantId:this.call.tsCall.participantId,remoteParticipantId:this.remoteParticipantId,sourceId:this.id,source:`remote`,rank:this.tsStream.rank,isAvailable:this.tsStream.isAvailable,acsIsAvailable:this._isAvailable,isReceiving:this._isReceiving,isStreaming:this.tsStream.isStreaming,viewIdsRegistered:this._renderers.map((e=>e.viewId)).join(`, `),height:this._size.height,width:this._size.width,isDisposed:this._disposed,optimalVideoCount:this.call?.tsCall.optimalVideoCount||1,currentNumberOfVideosRendered:this.call?.activeRemoteVideoStreamViews?.size||0}}dispose(){this.setIsAvailable(!1),super.dispose()}getMediaType(){return this.mediaStreamType===`ScreenSharing`?_3.ScreenSharingRaw:_3.VideoRaw}sendMediaStreamEvent(e){this.telemetryLogManager.sendEvent({name:Q.acs_calling_media_stream,tenant:p2,properties:{timestampInfo:e.timestampInfo,correlationId:e.correlationId,additionalDetails:e.additionalDetails||``,kindOfEvent:e.kindOfEvent||``,mediaType:e.mediaType,streamType:e.streamType,operation:e.operation,localParticipantId:e.localParticipantId||``,callId:e.callId||``}})}};xIe([YG(Awe.GetMediaStream),o7(`design:type`,Function),o7(`design:paramtypes`,[]),o7(`design:returntype`,Promise)],s7.prototype,`getMediaStream`,null);var c7={2:`#050505`,4:`#0a0a0a`,6:`#0f0f0f`,8:`#141414`,10:`#1a1a1a`,12:`#1f1f1f`,14:`#242424`,16:`#292929`,18:`#2e2e2e`,20:`#333333`,22:`#383838`,24:`#3d3d3d`,26:`#424242`,28:`#474747`,30:`#4d4d4d`,32:`#525252`,34:`#575757`,36:`#5c5c5c`,38:`#616161`,40:`#666666`,42:`#6b6b6b`,44:`#707070`,46:`#757575`,48:`#7a7a7a`,50:`#808080`,52:`#858585`,54:`#8a8a8a`,56:`#8f8f8f`,58:`#949494`,60:`#999999`,62:`#9e9e9e`,64:`#a3a3a3`,66:`#a8a8a8`,68:`#adadad`,70:`#b3b3b3`,72:`#b8b8b8`,74:`#bdbdbd`,76:`#c2c2c2`,78:`#c7c7c7`,80:`#cccccc`,82:`#d1d1d1`,84:`#d6d6d6`,86:`#dbdbdb`,88:`#e0e0e0`,90:`#e6e6e6`,92:`#ebebeb`,94:`#f0f0f0`,96:`#f5f5f5`,98:`#fafafa`},l7={5:`rgba(255, 255, 255, 0.05)`,10:`rgba(255, 255, 255, 0.1)`,20:`rgba(255, 255, 255, 0.2)`,30:`rgba(255, 255, 255, 0.3)`,40:`rgba(255, 255, 255, 0.4)`,50:`rgba(255, 255, 255, 0.5)`,60:`rgba(255, 255, 255, 0.6)`,70:`rgba(255, 255, 255, 0.7)`,80:`rgba(255, 255, 255, 0.8)`,90:`rgba(255, 255, 255, 0.9)`},u7={5:`rgba(0, 0, 0, 0.05)`,10:`rgba(0, 0, 0, 0.1)`,20:`rgba(0, 0, 0, 0.2)`,30:`rgba(0, 0, 0, 0.3)`,40:`rgba(0, 0, 0, 0.4)`,50:`rgba(0, 0, 0, 0.5)`,60:`rgba(0, 0, 0, 0.6)`,70:`rgba(0, 0, 0, 0.7)`,80:`rgba(0, 0, 0, 0.8)`,90:`rgba(0, 0, 0, 0.9)`},d7=`#ffffff`,SIe=`#000000`,CIe={shade50:`#200205`,shade40:`#3b0509`,shade30:`#6e0811`,shade20:`#960b18`,shade10:`#b10e1c`,primary:`#c50f1f`,tint10:`#cc2635`,tint20:`#d33f4c`,tint30:`#dc626d`,tint40:`#eeacb2`,tint50:`#f6d1d5`,tint60:`#fdf3f4`},wIe={shade50:`#031403`,shade40:`#052505`,shade30:`#094509`,shade20:`#0c5e0c`,shade10:`#0e700e`,primary:`#107c10`,tint10:`#218c21`,tint20:`#359b35`,tint30:`#54b054`,tint40:`#9fd89f`,tint50:`#c9eac9`,tint60:`#f1faf1`},f7={red:{shade50:`#210809`,shade40:`#3f1011`,shade30:`#751d1f`,shade20:`#9f282b`,shade10:`#bc2f32`,primary:`#d13438`,tint10:`#d7494c`,tint20:`#dc5e62`,tint30:`#e37d80`,tint40:`#f1bbbc`,tint50:`#f8dadb`,tint60:`#fdf6f6`},green:wIe,darkOrange:{shade50:`#230900`,shade40:`#411200`,shade30:`#7a2101`,shade20:`#a62d01`,shade10:`#c43501`,primary:`#da3b01`,tint10:`#de501c`,tint20:`#e36537`,tint30:`#e9835e`,tint40:`#f4bfab`,tint50:`#f9dcd1`,tint60:`#fdf6f3`},yellow:{shade50:`#282400`,shade40:`#4c4400`,shade30:`#817400`,shade20:`#c0ad00`,shade10:`#e4cc00`,primary:`#fde300`,tint10:`#fde61e`,tint20:`#fdea3d`,tint30:`#feee66`,tint40:`#fef7b2`,tint50:`#fffad6`,tint60:`#fffef5`},berry:{shade50:`#1f091d`,shade40:`#3a1136`,shade30:`#6d2064`,shade20:`#932b88`,shade10:`#af33a1`,primary:`#c239b3`,tint10:`#c94cbc`,tint20:`#d161c4`,tint30:`#da7ed0`,tint40:`#edbbe7`,tint50:`#f5daf2`,tint60:`#fdf5fc`},lightGreen:{shade50:`#031a02`,shade40:`#063004`,shade30:`#0b5a08`,shade20:`#0e7a0b`,shade10:`#11910d`,primary:`#13a10e`,tint10:`#27ac22`,tint20:`#3db838`,tint30:`#5ec75a`,tint40:`#a7e3a5`,tint50:`#cef0cd`,tint60:`#f2fbf2`},marigold:{shade50:`#251a00`,shade40:`#463100`,shade30:`#835b00`,shade20:`#b27c00`,shade10:`#d39300`,primary:`#eaa300`,tint10:`#edad1c`,tint20:`#efb839`,tint30:`#f2c661`,tint40:`#f9e2ae`,tint50:`#fcefd3`,tint60:`#fefbf4`}},p7={darkRed:{shade50:`#130204`,shade40:`#230308`,shade30:`#420610`,shade20:`#590815`,shade10:`#690a19`,primary:`#750b1c`,tint10:`#861b2c`,tint20:`#962f3f`,tint30:`#ac4f5e`,tint40:`#d69ca5`,tint50:`#e9c7cd`,tint60:`#f9f0f2`},cranberry:CIe,pumpkin:{shade50:`#200d03`,shade40:`#3d1805`,shade30:`#712d09`,shade20:`#9a3d0c`,shade10:`#b6480e`,primary:`#ca5010`,tint10:`#d06228`,tint20:`#d77440`,tint30:`#df8e64`,tint40:`#efc4ad`,tint50:`#f7dfd2`,tint60:`#fdf7f4`},peach:{shade50:`#291600`,shade40:`#4d2a00`,shade30:`#8f4e00`,shade20:`#c26a00`,shade10:`#e67e00`,primary:`#ff8c00`,tint10:`#ff9a1f`,tint20:`#ffa83d`,tint30:`#ffba66`,tint40:`#ffddb3`,tint50:`#ffedd6`,tint60:`#fffaf5`},gold:{shade50:`#1f1900`,shade40:`#3a2f00`,shade30:`#6c5700`,shade20:`#937700`,shade10:`#ae8c00`,primary:`#c19c00`,tint10:`#c8a718`,tint20:`#d0b232`,tint30:`#dac157`,tint40:`#ecdfa5`,tint50:`#f5eece`,tint60:`#fdfbf2`},brass:{shade50:`#181202`,shade40:`#2e2103`,shade30:`#553e06`,shade20:`#745408`,shade10:`#89640a`,primary:`#986f0b`,tint10:`#a47d1e`,tint20:`#b18c34`,tint30:`#c1a256`,tint40:`#e0cea2`,tint50:`#efe4cb`,tint60:`#fbf8f2`},brown:{shade50:`#170e07`,shade40:`#2b1a0e`,shade30:`#50301a`,shade20:`#6c4123`,shade10:`#804d29`,primary:`#8e562e`,tint10:`#9c663f`,tint20:`#a97652`,tint30:`#bb8f6f`,tint40:`#ddc3b0`,tint50:`#edded3`,tint60:`#faf7f4`},forest:{shade50:`#0c1501`,shade40:`#162702`,shade30:`#294903`,shade20:`#376304`,shade10:`#427505`,primary:`#498205`,tint10:`#599116`,tint20:`#6ba02b`,tint30:`#85b44c`,tint40:`#bdd99b`,tint50:`#dbebc7`,tint60:`#f6faf0`},seafoam:{shade50:`#002111`,shade40:`#003d20`,shade30:`#00723b`,shade20:`#009b51`,shade10:`#00b85f`,primary:`#00cc6a`,tint10:`#19d279`,tint20:`#34d889`,tint30:`#5ae0a0`,tint40:`#a8f0cd`,tint50:`#cff7e4`,tint60:`#f3fdf8`},darkGreen:{shade50:`#021102`,shade40:`#032003`,shade30:`#063b06`,shade20:`#085108`,shade10:`#0a5f0a`,primary:`#0b6a0b`,tint10:`#1a7c1a`,tint20:`#2d8e2d`,tint30:`#4da64d`,tint40:`#9ad29a`,tint50:`#c6e7c6`,tint60:`#f0f9f0`},lightTeal:{shade50:`#001d1f`,shade40:`#00373a`,shade30:`#00666d`,shade20:`#008b94`,shade10:`#00a5af`,primary:`#00b7c3`,tint10:`#18bfca`,tint20:`#32c8d1`,tint30:`#58d3db`,tint40:`#a6e9ed`,tint50:`#cef3f5`,tint60:`#f2fcfd`},teal:{shade50:`#001516`,shade40:`#012728`,shade30:`#02494c`,shade20:`#026467`,shade10:`#037679`,primary:`#038387`,tint10:`#159195`,tint20:`#2aa0a4`,tint30:`#4cb4b7`,tint40:`#9bd9db`,tint50:`#c7ebec`,tint60:`#f0fafa`},steel:{shade50:`#000f12`,shade40:`#001b22`,shade30:`#00333f`,shade20:`#004555`,shade10:`#005265`,primary:`#005b70`,tint10:`#0f6c81`,tint20:`#237d92`,tint30:`#4496a9`,tint40:`#94c8d4`,tint50:`#c3e1e8`,tint60:`#eff7f9`},blue:{shade50:`#001322`,shade40:`#002440`,shade30:`#004377`,shade20:`#005ba1`,shade10:`#006cbf`,primary:`#0078d4`,tint10:`#1a86d9`,tint20:`#3595de`,tint30:`#5caae5`,tint40:`#a9d3f2`,tint50:`#d0e7f8`,tint60:`#f3f9fd`},royalBlue:{shade50:`#000c16`,shade40:`#00172a`,shade30:`#002c4e`,shade20:`#003b6a`,shade10:`#00467e`,primary:`#004e8c`,tint10:`#125e9a`,tint20:`#286fa8`,tint30:`#4a89ba`,tint40:`#9abfdc`,tint50:`#c7dced`,tint60:`#f0f6fa`},cornflower:{shade50:`#0d1126`,shade40:`#182047`,shade30:`#2c3c85`,shade20:`#3c51b4`,shade10:`#4760d5`,primary:`#4f6bed`,tint10:`#637cef`,tint20:`#778df1`,tint30:`#93a4f4`,tint40:`#c8d1fa`,tint50:`#e1e6fc`,tint60:`#f7f9fe`},navy:{shade50:`#00061d`,shade40:`#000c36`,shade30:`#001665`,shade20:`#001e89`,shade10:`#0023a2`,primary:`#0027b4`,tint10:`#173bbd`,tint20:`#3050c6`,tint30:`#546fd2`,tint40:`#a3b2e8`,tint50:`#ccd5f3`,tint60:`#f2f4fc`},lavender:{shade50:`#120f25`,shade40:`#221d46`,shade30:`#3f3682`,shade20:`#5649b0`,shade10:`#6656d1`,primary:`#7160e8`,tint10:`#8172eb`,tint20:`#9184ee`,tint30:`#a79cf1`,tint40:`#d2ccf8`,tint50:`#e7e4fb`,tint60:`#f9f8fe`},purple:{shade50:`#0f0717`,shade40:`#1c0e2b`,shade30:`#341a51`,shade20:`#46236e`,shade10:`#532982`,primary:`#5c2e91`,tint10:`#6b3f9e`,tint20:`#7c52ab`,tint30:`#9470bd`,tint40:`#c6b1de`,tint50:`#e0d3ed`,tint60:`#f7f4fb`},grape:{shade50:`#160418`,shade40:`#29072e`,shade30:`#4c0d55`,shade20:`#671174`,shade10:`#7a1589`,primary:`#881798`,tint10:`#952aa4`,tint20:`#a33fb1`,tint30:`#b55fc1`,tint40:`#d9a7e0`,tint50:`#eaceef`,tint60:`#faf2fb`},lilac:{shade50:`#1c0b1f`,shade40:`#35153a`,shade30:`#63276d`,shade20:`#863593`,shade10:`#9f3faf`,primary:`#b146c2`,tint10:`#ba58c9`,tint20:`#c36bd1`,tint30:`#cf87da`,tint40:`#e6bfed`,tint50:`#f2dcf5`,tint60:`#fcf6fd`},pink:{shade50:`#24091b`,shade40:`#441232`,shade30:`#80215d`,shade20:`#ad2d7e`,shade10:`#cd3595`,primary:`#e43ba6`,tint10:`#e750b0`,tint20:`#ea66ba`,tint30:`#ef85c8`,tint40:`#f7c0e3`,tint50:`#fbddf0`,tint60:`#fef6fb`},magenta:{shade50:`#1f0013`,shade40:`#390024`,shade30:`#6b0043`,shade20:`#91005a`,shade10:`#ac006b`,primary:`#bf0077`,tint10:`#c71885`,tint20:`#ce3293`,tint30:`#d957a8`,tint40:`#eca5d1`,tint50:`#f5cee6`,tint60:`#fcf2f9`},plum:{shade50:`#13000c`,shade40:`#240017`,shade30:`#43002b`,shade20:`#5a003b`,shade10:`#6b0045`,primary:`#77004d`,tint10:`#87105d`,tint20:`#98246f`,tint30:`#ad4589`,tint40:`#d696c0`,tint50:`#e9c4dc`,tint60:`#faf0f6`},beige:{shade50:`#141313`,shade40:`#252323`,shade30:`#444241`,shade20:`#5d5958`,shade10:`#6e6968`,primary:`#7a7574`,tint10:`#8a8584`,tint20:`#9a9594`,tint30:`#afabaa`,tint40:`#d7d4d4`,tint50:`#eae8e8`,tint60:`#faf9f9`},mink:{shade50:`#0f0e0e`,shade40:`#1c1b1a`,shade30:`#343231`,shade20:`#474443`,shade10:`#54514f`,primary:`#5d5a58`,tint10:`#706d6b`,tint20:`#84817e`,tint30:`#9e9b99`,tint40:`#cecccb`,tint50:`#e5e4e3`,tint60:`#f8f8f8`},platinum:{shade50:`#111314`,shade40:`#1f2426`,shade30:`#3b4447`,shade20:`#505c60`,shade10:`#5f6d71`,primary:`#69797e`,tint10:`#79898d`,tint20:`#89989d`,tint30:`#a0adb2`,tint40:`#cdd6d8`,tint50:`#e4e9ea`,tint60:`#f8f9fa`},anchor:{shade50:`#090a0b`,shade40:`#111315`,shade30:`#202427`,shade20:`#2b3135`,shade10:`#333a3f`,primary:`#394146`,tint10:`#4d565c`,tint20:`#626c72`,tint30:`#808a90`,tint40:`#bcc3c7`,tint50:`#dbdfe1`,tint60:`#f6f7f8`}},m7={cranberry:CIe,green:wIe,orange:{shade50:`#271002`,shade40:`#4a1e04`,shade30:`#8a3707`,shade20:`#bc4b09`,shade10:`#de590b`,primary:`#f7630c`,tint10:`#f87528`,tint20:`#f98845`,tint30:`#faa06b`,tint40:`#fdcfb4`,tint50:`#fee5d7`,tint60:`#fff9f5`}},TIe=`darkRed.cranberry.pumpkin.peach.gold.brass.brown.forest.seafoam.darkGreen.lightTeal.teal.steel.blue.royalBlue.cornflower.navy.lavender.purple.grape.lilac.pink.magenta.plum.beige.mink.platinum.anchor`.split(`.`),h7={success:`green`,warning:`orange`,danger:`cranberry`},g7=[`red`,`green`,`darkOrange`,`yellow`,`berry`,`lightGreen`,`marigold`].reduce(((e,t)=>{let n=t.slice(0,1).toUpperCase()+t.slice(1),r={[`colorPalette${n}Background1`]:f7[t].tint60,[`colorPalette${n}Background2`]:f7[t].tint40,[`colorPalette${n}Background3`]:f7[t].primary,[`colorPalette${n}Foreground1`]:f7[t].shade10,[`colorPalette${n}Foreground2`]:f7[t].shade30,[`colorPalette${n}Foreground3`]:f7[t].primary,[`colorPalette${n}BorderActive`]:f7[t].primary,[`colorPalette${n}Border1`]:f7[t].tint40,[`colorPalette${n}Border2`]:f7[t].primary};return Object.assign(e,r)}),{});g7.colorPaletteYellowForeground1=f7.yellow.shade30,g7.colorPaletteRedForegroundInverted=f7.red.tint20,g7.colorPaletteGreenForegroundInverted=f7.green.tint20,g7.colorPaletteYellowForegroundInverted=f7.yellow.tint40;var EIe=TIe.reduce(((e,t)=>{let n=t.slice(0,1).toUpperCase()+t.slice(1),r={[`colorPalette${n}Background2`]:p7[t].tint40,[`colorPalette${n}Foreground2`]:p7[t].shade30,[`colorPalette${n}BorderActive`]:p7[t].primary};return Object.assign(e,r)}),{}),DIe={...g7,...EIe},_7=Object.entries(h7).reduce(((e,[t,n])=>{let r=t.slice(0,1).toUpperCase()+t.slice(1),i={[`colorStatus${r}Background1`]:m7[n].tint60,[`colorStatus${r}Background2`]:m7[n].tint40,[`colorStatus${r}Background3`]:m7[n].primary,[`colorStatus${r}Foreground1`]:m7[n].shade10,[`colorStatus${r}Foreground2`]:m7[n].shade30,[`colorStatus${r}Foreground3`]:m7[n].primary,[`colorStatus${r}ForegroundInverted`]:m7[n].tint30,[`colorStatus${r}BorderActive`]:m7[n].primary,[`colorStatus${r}Border1`]:m7[n].tint40,[`colorStatus${r}Border2`]:m7[n].primary};return Object.assign(e,i)}),{});_7.colorStatusDangerBackground3Hover=m7[h7.danger].shade10,_7.colorStatusDangerBackground3Pressed=m7[h7.danger].shade20,_7.colorStatusWarningForeground1=m7[h7.warning].shade20,_7.colorStatusWarningForeground3=m7[h7.warning].shade20,_7.colorStatusWarningBorder2=m7[h7.warning].shade20;var OIe=e=>({colorNeutralForeground1:c7[14],colorNeutralForeground1Hover:c7[14],colorNeutralForeground1Pressed:c7[14],colorNeutralForeground1Selected:c7[14],colorNeutralForeground2:c7[26],colorNeutralForeground2Hover:c7[14],colorNeutralForeground2Pressed:c7[14],colorNeutralForeground2Selected:c7[14],colorNeutralForeground2BrandHover:e[80],colorNeutralForeground2BrandPressed:e[70],colorNeutralForeground2BrandSelected:e[80],colorNeutralForeground3:c7[38],colorNeutralForeground3Hover:c7[26],colorNeutralForeground3Pressed:c7[26],colorNeutralForeground3Selected:c7[26],colorNeutralForeground3BrandHover:e[80],colorNeutralForeground3BrandPressed:e[70],colorNeutralForeground3BrandSelected:e[80],colorNeutralForeground4:c7[44],colorNeutralForegroundDisabled:c7[74],colorNeutralForegroundInvertedDisabled:l7[40],colorBrandForegroundLink:e[70],colorBrandForegroundLinkHover:e[60],colorBrandForegroundLinkPressed:e[40],colorBrandForegroundLinkSelected:e[70],colorNeutralForeground2Link:c7[26],colorNeutralForeground2LinkHover:c7[14],colorNeutralForeground2LinkPressed:c7[14],colorNeutralForeground2LinkSelected:c7[14],colorCompoundBrandForeground1:e[80],colorCompoundBrandForeground1Hover:e[70],colorCompoundBrandForeground1Pressed:e[60],colorBrandForeground1:e[80],colorBrandForeground2:e[70],colorBrandForeground2Hover:e[60],colorBrandForeground2Pressed:e[30],colorNeutralForeground1Static:c7[14],colorNeutralForegroundStaticInverted:d7,colorNeutralForegroundInverted:d7,colorNeutralForegroundInvertedHover:d7,colorNeutralForegroundInvertedPressed:d7,colorNeutralForegroundInvertedSelected:d7,colorNeutralForegroundInverted2:d7,colorNeutralForegroundOnBrand:d7,colorNeutralForegroundInvertedLink:d7,colorNeutralForegroundInvertedLinkHover:d7,colorNeutralForegroundInvertedLinkPressed:d7,colorNeutralForegroundInvertedLinkSelected:d7,colorBrandForegroundInverted:e[100],colorBrandForegroundInvertedHover:e[110],colorBrandForegroundInvertedPressed:e[100],colorBrandForegroundOnLight:e[80],colorBrandForegroundOnLightHover:e[70],colorBrandForegroundOnLightPressed:e[50],colorBrandForegroundOnLightSelected:e[60],colorNeutralBackground1:d7,colorNeutralBackground1Hover:c7[96],colorNeutralBackground1Pressed:c7[88],colorNeutralBackground1Selected:c7[92],colorNeutralBackground2:c7[98],colorNeutralBackground2Hover:c7[94],colorNeutralBackground2Pressed:c7[86],colorNeutralBackground2Selected:c7[90],colorNeutralBackground3:c7[96],colorNeutralBackground3Hover:c7[92],colorNeutralBackground3Pressed:c7[84],colorNeutralBackground3Selected:c7[88],colorNeutralBackground4:c7[94],colorNeutralBackground4Hover:c7[98],colorNeutralBackground4Pressed:c7[96],colorNeutralBackground4Selected:d7,colorNeutralBackground5:c7[92],colorNeutralBackground5Hover:c7[96],colorNeutralBackground5Pressed:c7[94],colorNeutralBackground5Selected:c7[98],colorNeutralBackground6:c7[90],colorNeutralBackgroundInverted:c7[16],colorNeutralBackgroundStatic:c7[20],colorNeutralBackgroundAlpha:l7[50],colorNeutralBackgroundAlpha2:l7[80],colorSubtleBackground:`transparent`,colorSubtleBackgroundHover:c7[96],colorSubtleBackgroundPressed:c7[88],colorSubtleBackgroundSelected:c7[92],colorSubtleBackgroundLightAlphaHover:l7[70],colorSubtleBackgroundLightAlphaPressed:l7[50],colorSubtleBackgroundLightAlphaSelected:`transparent`,colorSubtleBackgroundInverted:`transparent`,colorSubtleBackgroundInvertedHover:u7[10],colorSubtleBackgroundInvertedPressed:u7[30],colorSubtleBackgroundInvertedSelected:u7[20],colorTransparentBackground:`transparent`,colorTransparentBackgroundHover:`transparent`,colorTransparentBackgroundPressed:`transparent`,colorTransparentBackgroundSelected:`transparent`,colorNeutralBackgroundDisabled:c7[94],colorNeutralBackgroundInvertedDisabled:l7[10],colorNeutralStencil1:c7[90],colorNeutralStencil2:c7[98],colorNeutralStencil1Alpha:u7[10],colorNeutralStencil2Alpha:u7[5],colorBackgroundOverlay:u7[40],colorScrollbarOverlay:u7[50],colorBrandBackground:e[80],colorBrandBackgroundHover:e[70],colorBrandBackgroundPressed:e[40],colorBrandBackgroundSelected:e[60],colorCompoundBrandBackground:e[80],colorCompoundBrandBackgroundHover:e[70],colorCompoundBrandBackgroundPressed:e[60],colorBrandBackgroundStatic:e[80],colorBrandBackground2:e[160],colorBrandBackground2Hover:e[150],colorBrandBackground2Pressed:e[130],colorBrandBackground3Static:e[60],colorBrandBackground4Static:e[40],colorBrandBackgroundInverted:d7,colorBrandBackgroundInvertedHover:e[160],colorBrandBackgroundInvertedPressed:e[140],colorBrandBackgroundInvertedSelected:e[150],colorNeutralCardBackground:c7[98],colorNeutralCardBackgroundHover:d7,colorNeutralCardBackgroundPressed:c7[96],colorNeutralCardBackgroundSelected:c7[92],colorNeutralCardBackgroundDisabled:c7[94],colorNeutralStrokeAccessible:c7[38],colorNeutralStrokeAccessibleHover:c7[34],colorNeutralStrokeAccessiblePressed:c7[30],colorNeutralStrokeAccessibleSelected:e[80],colorNeutralStroke1:c7[82],colorNeutralStroke1Hover:c7[78],colorNeutralStroke1Pressed:c7[70],colorNeutralStroke1Selected:c7[74],colorNeutralStroke2:c7[88],colorNeutralStroke3:c7[94],colorNeutralStrokeSubtle:c7[88],colorNeutralStrokeOnBrand:d7,colorNeutralStrokeOnBrand2:d7,colorNeutralStrokeOnBrand2Hover:d7,colorNeutralStrokeOnBrand2Pressed:d7,colorNeutralStrokeOnBrand2Selected:d7,colorBrandStroke1:e[80],colorBrandStroke2:e[140],colorBrandStroke2Hover:e[120],colorBrandStroke2Pressed:e[80],colorBrandStroke2Contrast:e[140],colorCompoundBrandStroke:e[80],colorCompoundBrandStrokeHover:e[70],colorCompoundBrandStrokePressed:e[60],colorNeutralStrokeDisabled:c7[88],colorNeutralStrokeInvertedDisabled:l7[40],colorTransparentStroke:`transparent`,colorTransparentStrokeInteractive:`transparent`,colorTransparentStrokeDisabled:`transparent`,colorNeutralStrokeAlpha:u7[5],colorNeutralStrokeAlpha2:l7[20],colorStrokeFocus1:d7,colorStrokeFocus2:SIe,colorNeutralShadowAmbient:`rgba(0,0,0,0.12)`,colorNeutralShadowKey:`rgba(0,0,0,0.14)`,colorNeutralShadowAmbientLighter:`rgba(0,0,0,0.06)`,colorNeutralShadowKeyLighter:`rgba(0,0,0,0.07)`,colorNeutralShadowAmbientDarker:`rgba(0,0,0,0.20)`,colorNeutralShadowKeyDarker:`rgba(0,0,0,0.24)`,colorBrandShadowAmbient:`rgba(0,0,0,0.30)`,colorBrandShadowKey:`rgba(0,0,0,0.25)`}),kIe={borderRadiusNone:`0`,borderRadiusSmall:`2px`,borderRadiusMedium:`4px`,borderRadiusLarge:`6px`,borderRadiusXLarge:`8px`,borderRadiusCircular:`10000px`},AIe={curveAccelerateMax:`cubic-bezier(0.9,0.1,1,0.2)`,curveAccelerateMid:`cubic-bezier(1,0,1,1)`,curveAccelerateMin:`cubic-bezier(0.8,0,0.78,1)`,curveDecelerateMax:`cubic-bezier(0.1,0.9,0.2,1)`,curveDecelerateMid:`cubic-bezier(0,0,0,1)`,curveDecelerateMin:`cubic-bezier(0.33,0,0.1,1)`,curveEasyEaseMax:`cubic-bezier(0.8,0,0.2,1)`,curveEasyEase:`cubic-bezier(0.33,0,0.67,1)`,curveLinear:`cubic-bezier(0,0,1,1)`},jIe={durationUltraFast:`50ms`,durationFaster:`100ms`,durationFast:`150ms`,durationNormal:`200ms`,durationGentle:`250ms`,durationSlow:`300ms`,durationSlower:`400ms`,durationUltraSlow:`500ms`},MIe={fontSizeBase100:`10px`,fontSizeBase200:`12px`,fontSizeBase300:`14px`,fontSizeBase400:`16px`,fontSizeBase500:`20px`,fontSizeBase600:`24px`,fontSizeHero700:`28px`,fontSizeHero800:`32px`,fontSizeHero900:`40px`,fontSizeHero1000:`68px`},NIe={lineHeightBase100:`14px`,lineHeightBase200:`16px`,lineHeightBase300:`20px`,lineHeightBase400:`22px`,lineHeightBase500:`28px`,lineHeightBase600:`32px`,lineHeightHero700:`36px`,lineHeightHero800:`40px`,lineHeightHero900:`52px`,lineHeightHero1000:`92px`},PIe={fontWeightRegular:400,fontWeightMedium:500,fontWeightSemibold:600,fontWeightBold:700},FIe={fontFamilyBase:`'Segoe UI', 'Segoe UI Web (West European)', -apple-system, BlinkMacSystemFont, Roboto, 'Helvetica Neue', sans-serif`,fontFamilyMonospace:`Consolas, 'Courier New', Courier, monospace`,fontFamilyNumeric:`Bahnschrift, 'Segoe UI', 'Segoe UI Web (West European)', -apple-system, BlinkMacSystemFont, Roboto, 'Helvetica Neue', sans-serif`},v7={none:`0`,xxs:`2px`,xs:`4px`,sNudge:`6px`,s:`8px`,mNudge:`10px`,m:`12px`,l:`16px`,xl:`20px`,xxl:`24px`,xxxl:`32px`},IIe={spacingHorizontalNone:v7.none,spacingHorizontalXXS:v7.xxs,spacingHorizontalXS:v7.xs,spacingHorizontalSNudge:v7.sNudge,spacingHorizontalS:v7.s,spacingHorizontalMNudge:v7.mNudge,spacingHorizontalM:v7.m,spacingHorizontalL:v7.l,spacingHorizontalXL:v7.xl,spacingHorizontalXXL:v7.xxl,spacingHorizontalXXXL:v7.xxxl},LIe={spacingVerticalNone:v7.none,spacingVerticalXXS:v7.xxs,spacingVerticalXS:v7.xs,spacingVerticalSNudge:v7.sNudge,spacingVerticalS:v7.s,spacingVerticalMNudge:v7.mNudge,spacingVerticalM:v7.m,spacingVerticalL:v7.l,spacingVerticalXL:v7.xl,spacingVerticalXXL:v7.xxl,spacingVerticalXXXL:v7.xxxl},RIe={strokeWidthThin:`1px`,strokeWidthThick:`2px`,strokeWidthThicker:`3px`,strokeWidthThickest:`4px`};function zIe(e,t,n=``){return{[`shadow2${n}`]:`0 0 2px ${e}, 0 1px 2px ${t}`,[`shadow4${n}`]:`0 0 2px ${e}, 0 2px 4px ${t}`,[`shadow8${n}`]:`0 0 2px ${e}, 0 4px 8px ${t}`,[`shadow16${n}`]:`0 0 2px ${e}, 0 8px 16px ${t}`,[`shadow28${n}`]:`0 0 8px ${e}, 0 14px 28px ${t}`,[`shadow64${n}`]:`0 0 8px ${e}, 0 32px 64px ${t}`}}var BIe=(e=>{let t=OIe(e);return{...kIe,...MIe,...NIe,...FIe,...PIe,...RIe,...IIe,...LIe,...jIe,...AIe,...t,...DIe,..._7,...zIe(t.colorNeutralShadowAmbient,t.colorNeutralShadowKey),...zIe(t.colorBrandShadowAmbient,t.colorBrandShadowKey,`Brand`)}})({10:`#061724`,20:`#082338`,30:`#0a2e4a`,40:`#0c3b5e`,50:`#0e4775`,60:`#0f548c`,70:`#115ea3`,80:`#0f6cbd`,90:`#2886de`,100:`#479ef5`,110:`#62abf5`,120:`#77b7f7`,130:`#96c6fa`,140:`#b4d6fa`,150:`#cfe4fa`,160:`#ebf3fc`}),VIe=1,HIe=class{constructor(e,t,n,r,i){this._container=e,this._videoStream=t,this._viewId=n,this._streamTelemetryEventSender=i,this._watermarkCapability=null,this.WATERMARK_TEXT_COMMON_STYLES={fontFamily:BIe.fontFamilyBase,fontWeight:`bold`,stroke:`black`,strokeOpacity:`0.1`,fill:BIe.colorNeutralStrokeOnBrand2},this.WATERMARK_CONTAINER_STYLES={position:`absolute`,pointerEvents:`none`,width:`100%`,height:`100%`,top:`0`,left:`0`},this.TEXT_ROTATION=30,this.SHADOW_OPACITY_RATIO=3,this.RANGE_MAX=100,this.BORDER_SIZE=18,this.BORDER_SIZE_FRAC=1/this.BORDER_SIZE,this.SPACE_USE=.9,this.MAX_BORDER=2,this.SINGLE_PATTERN_FONT_SIZE_FACTOR=.07,this._svgContainerHidden=``,this._svgWatermarkUseTextScale=0,this._svgWatermarkUseTextBorderSize=0,this._svgTextTiledScaledSize=0,this._svgTextTiledScaledStrokeWidth=0,this._svgFirstPatternWidth=0,this._svgFirstPatternHeight=0,this._svgSecondPatternWidth=0,this._svgSecondPatternHeight=0,this._svgSecondPatternOffsetX=0,this._svgSecondPatternOffsetY=0,this._computeTextDiagonal=wwe(this.TEXT_ROTATION),this._isApple=!1,this._getScaledPatternDimensions=(e,t,n,r)=>({width:e*(n+1.1),height:t*(r+1.1)}),this._call=this._videoStream.call,this._logger=r.createChild(`WatermarkOverlayProvider`+ VIe++);let a=this._call.getMeetingCapabilitiesInternal();if(!a){this._logger.warn(`No watermark capabilities found. Likely not received from service.`);let e=new Y({defaultError:J.VIEW.NO_WATERMARK_CAPABILITY_RECEIVED}),t=J0();this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:y3.watermark,kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{failureReason:e.message,code:e.code,...J3(e),watermark:{...this._getWatermarkUsageTelemetryPayload()}}});return}this._watermarkCapability=a.waterMarkCapability;let o=this._call.deviceManager.getOSNameInternal();this._isApple=o===`ios`||o===`mac`,this._resizeObserver=new ResizeObserver((e=>{for(let t of e)if(t.contentRect?.width>1){let e=t.contentRect.width,n=t.contentRect.height;this._updateWatermarkScalingValues(e,n)}})),this._resizeObserver.observe(this._container)}attach(){let e=J0(),t=Date.now();try{if(!this._watermarkCapability)return void this._logger.warn(`No watermark capabilities found. No-op.`);if(this._videoStream.mediaStreamType!==`Video`&&this._videoStream.mediaStreamType!==`ScreenSharing`)throw Error(`Unsupported media type for watermark`);this._watermarkIsReceivingSub=()=>{this._videoStream.isReceiving&&(this._generateWatermark(this._videoStream.mediaStreamType,e),this._updateWatermarkScalingValues(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height))},this._videoStream.on(`isReceivingChanged`,this._watermarkIsReceivingSub)}catch(n){let r=new Y({defaultError:J.VIEW.WATERMARK_ATTACH_FAIL,originalError:n});throw this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:e,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-t},operation:y3.watermark,kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{failureReason:r.message,code:r.code,...J3(r),watermark:{...this._getWatermarkUsageTelemetryPayload()}}}),r}}dispose(){this._resizeObserver&&this._resizeObserver.disconnect(),this._mutationObserver&&this._mutationObserver.disconnect(),this._audioOnlyCallback&&this._call.offWatermarkAudioOnlyFallbackTriggeredChanged(`watermarkAudioOnlyFallbackTriggeredChanged`,this._audioOnlyCallback),this._svgContainer&&(this._container.removeChild(this._svgContainer),this._svgContainer=void 0,this._svgContainerHidden=``),this._watermarkIsReceivingSub&&this._videoStream.off(`isReceivingChanged`,this._watermarkIsReceivingSub),this._logger.info(`watermark overlay provider disposed for viewid: ${this._viewId}`)}_updateWatermarkScalingValues(e,t){this._getSelectedWatermarkPattern()===`Single`?this._updateWatermarkUseTextScalingSingle(e,t):this._getSelectedWatermarkPattern()===`Tiled`&&this._updateWatermarkPatternScalingTiled(e,t)}_generateWatermark(e,t){let n=Date.now();try{if(!this._watermarkCapability)return void this._logger.warn(`No watermark capabilities found. No-op.`);if(this._call.watermarkAudioOnlyFallbackTriggered)return this._logger.warn(`Watermark audio only fallback was triggered, disposing remote stream`),void this._videoStream.dispose();let r;if(e===`Video`&&this._watermarkCapability.enabledForVideo)r=this._watermarkCapability.videoSettings;else{if(e!==`ScreenSharing`||!this._watermarkCapability.enabledForVbss)return void this._logger.info(`No watermark operations to be done on viewId: ${this._viewId}`);r=this._watermarkCapability.vbssSettings}if(this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:n},operation:y3.watermark,kindOfEvent:$.attempt,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}}),!r||!r.opacity||!r.pattern||typeof r.opacity!=`number`||typeof r.pattern!=`string`)throw this._logger.debug(`Unexpected watermark settings`),new Y({defaultError:J.VIEW.WATERMARK_UNEXPECTED_VALUES});let i=this._getClampedUsername(),a;if(r.pattern===`Single`)a=this._generateSinglePatternWatermark(i,r);else{if(r.pattern!==`Tiled`)throw this._logger.debug(`Unexpected watermark pattern setting`),new Y({defaultError:J.VIEW.WATERMARK_UNEXPECTED_VALUES});a=this._generateTiledPatternWatermark(i,r)}this._svgContainerHidden=a.outerHTML,this._container.appendChild(a),this._audioOnlyCallback=()=>{this._call.watermarkAudioOnlyFallbackTriggered&&(this._logger.debug(`Watermark audio only fallback triggered by one of the renderers`),this._logger.debug(`Disposing remote stream with viewId ${this._viewId}`),this._videoStream.dispose(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:y3.watermark,kindOfEvent:$.event,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}}))},this._call.onWatermarkAudioOnlyFallbackTriggeredChanged(`watermarkAudioOnlyFallbackTriggeredChanged`,this._audioOnlyCallback),this._mutationObserver=new MutationObserver((e=>{this._svgContainer?.outerHTML!==this._svgContainerHidden&&(this._logger.debug(`watermark mutation detected, falling back to audio only!`),this._triggerAudioOnlyFallback(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:y3.watermark,kindOfEvent:$.event,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload(this._viewId)}}}))})),this._mutationObserver.observe(this._container,{attributes:!0,subtree:!0,childList:!0}),this._logger.info(`watermark attached for viewId: ${this._viewId}`),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-n},operation:y3.watermark,kindOfEvent:$.success,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}})}catch(e){let r=new Y({defaultError:J.VIEW.WATERMARK_ATTACH_FAIL,originalError:e});throw this._triggerAudioOnlyFallback(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-n},operation:y3.watermark,kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{failureReason:r.message,code:r.code,...J3(r),watermark:{...this._getWatermarkUsageTelemetryPayload(this._viewId)}}}),r}}_triggerAudioOnlyFallback(){this._logger.debug(`audio only fallback triggered by viewId ${this._viewId}`),this._logger.debug(`Disposing remote stream with viewId ${this._viewId}`),this._videoStream.dispose(),this._call.setWatermarkAudioOnlyFallbackTriggered(!0)}_addStyleAttributesToSvgElement(e,t){for(let[n,r]of Object.entries(t))e.style[`${n}`]=r}_generateSinglePatternWatermark(e,t){let n=this._getWatermarkContainer(t);this._svgContainer=n;let r=t.opacity/this.RANGE_MAX,i=r/this.SHADOW_OPACITY_RATIO,a=J0(),o=`url(#${a})`,s=document.createElementNS(`http://www.w3.org/2000/svg`,`defs`),c=this._getSvgFilter(a,i),l=document.createElementNS(`http://www.w3.org/2000/svg`,`text`);l.id=J0(),this._addStyleAttributesToSvgElement(l,this.WATERMARK_TEXT_COMMON_STYLES),l.setAttribute(`filter`,o),l.setAttribute(`text-anchor`,`middle`),l.setAttribute(`dominant-baseline`,`middle`),l.setAttribute(`fill-opacity`,`${r}`),l.style.transform=`rotate(-30deg)`;let u=document.createTextNode(e);l.appendChild(u),this._svgTextDefElement=l,s.appendChild(c),s.appendChild(l);let d=document.createElementNS(`http://www.w3.org/2000/svg`,`use`);return d.id=J0(),this._svgWatermarkUseTagSinglePattern=d,d.setAttribute(`href`,`#${this._svgTextDefElement.id}`),d.setAttribute(`x`,`50%`),d.setAttribute(`y`,`50%`),d.setAttribute(`width`,`100%`),d.setAttribute(`height`,`100%`),d.setAttribute(`font-size`,`${this._svgWatermarkUseTextScale}`),d.setAttribute(`stroke-width`,`${this._svgWatermarkUseTextBorderSize}`),n.appendChild(s),n.appendChild(d),this._updateWatermarkUseTextScalingSingle(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height),n}_updateWatermarkUseTextScalingSingle(e,t){if(this._svgContainer&&this._svgWatermarkUseTagSinglePattern){let n=this._computeTextDiagonal(e,t);this._svgWatermarkUseTextScale=this.SPACE_USE*n*this.SINGLE_PATTERN_FONT_SIZE_FACTOR,this._svgWatermarkUseTextBorderSize=Math.max(1,Math.min(this.MAX_BORDER,this._svgWatermarkUseTextScale*this.BORDER_SIZE_FRAC)),this._svgWatermarkUseTagSinglePattern.setAttribute(`font-size`,`${this._svgWatermarkUseTextScale}`),this._svgWatermarkUseTagSinglePattern.setAttribute(`stroke-width`,`${this._svgWatermarkUseTextBorderSize}`),this._svgContainerHidden=this._svgContainer.outerHTML;return}this._logger.warn(`svg watermark element missing, cannot update`)}_updateWatermarkPatternScalingTiled(e,t){if(this._svgContainer&&this._svgTextDefElement&&this._svgFirstPattern&&this._svgSecondPattern){let n=Cwe(e,t,this._isApple);this._svgTextTiledScaledSize=n.scaledFontSize,this._svgTextTiledScaledStrokeWidth=n.scaledBorderSize,this._svgTextDefElement.setAttribute(`font-size`,`${this._svgTextTiledScaledSize}`),this._svgTextDefElement.setAttribute(`stroke-width`,`${this._svgTextTiledScaledStrokeWidth}`);let r=this._svgTextDefElement.getBoundingClientRect().width,i=this._svgTextDefElement.getBoundingClientRect().height,{width:a,height:o}=this._getScaledPatternDimensions(r,i,n.scaledHorizontalGap,n.scaledVerticalGap),s=.5*a,c=.5*o;this._svgFirstPatternWidth=a,this._svgFirstPatternHeight=o,this._svgSecondPatternWidth=a,this._svgSecondPatternHeight=o,this._svgSecondPatternOffsetX=s,this._svgSecondPatternOffsetY=c,this._svgFirstPattern.setAttribute(`width`,`${this._svgFirstPatternWidth}`),this._svgFirstPattern.setAttribute(`height`,`${this._svgFirstPatternHeight}`),this._svgSecondPattern.setAttribute(`width`,`${this._svgSecondPatternWidth}`),this._svgSecondPattern.setAttribute(`height`,`${this._svgSecondPatternHeight}`),this._svgSecondPattern.setAttribute(`x`,`${this._svgSecondPatternOffsetX}`),this._svgSecondPattern.setAttribute(`y`,`${this._svgSecondPatternOffsetY}`),this._svgContainerHidden=this._svgContainer.outerHTML;return}this._logger.warn(`svg watermark element missing, cannot update`)}_generateTiledPatternWatermark(e,t){let n=this._getWatermarkContainer(t);this._svgContainer=n;let r=t.opacity/this.RANGE_MAX,i=r/this.SHADOW_OPACITY_RATIO,a=J0(),o=J0(),s=J0(),c=`url(#${a})`,l=document.createElementNS(`http://www.w3.org/2000/svg`,`defs`),u=this._getSvgFilter(a,i),d=document.createElementNS(`http://www.w3.org/2000/svg`,`text`);this._svgTextDefElement=d,d.id=J0(),this._addStyleAttributesToSvgElement(d,this.WATERMARK_TEXT_COMMON_STYLES),d.setAttribute(`filter`,c),d.setAttribute(`dominant-baseline`,`hanging`),d.setAttribute(`fill-opacity`,`${r}`),d.setAttribute(`font-size`,`${this._svgTextTiledScaledSize}`),d.setAttribute(`stroke-width`,`${this._svgTextTiledScaledStrokeWidth}`);let f=document.createTextNode(e);d.appendChild(f);let p=document.createElementNS(`http://www.w3.org/2000/svg`,`pattern`);this._svgFirstPattern=p,p.id=o,p.setAttribute(`patternUnits`,`userSpaceOnUse`),p.setAttribute(`patternTransform`,`rotate(-30)`),p.setAttribute(`width`,`${this._svgFirstPatternWidth}`),p.setAttribute(`height`,`${this._svgFirstPatternHeight}`);let m=document.createElementNS(`http://www.w3.org/2000/svg`,`use`);m.setAttribute(`href`,`#${this._svgTextDefElement.id}`),p.appendChild(m);let h=document.createElementNS(`http://www.w3.org/2000/svg`,`pattern`);this._svgSecondPattern=h,h.id=s,h.setAttribute(`patternUnits`,`userSpaceOnUse`),h.setAttribute(`patternTransform`,`rotate(-30)`),h.setAttribute(`width`,`${this._svgSecondPatternWidth}`),h.setAttribute(`height`,`${this._svgSecondPatternHeight}`),h.setAttribute(`x`,`${this._svgSecondPatternOffsetX}`),h.setAttribute(`y`,`${this._svgSecondPatternOffsetY}`);let g=m.cloneNode(!0);h.appendChild(g),l.appendChild(u),l.appendChild(d),l.appendChild(p),l.appendChild(h);let _=this._getRect(0,0,100,100,o),v=this._getRect(0,0,100,100,s);return n.appendChild(l),n.appendChild(_),n.appendChild(v),this._updateWatermarkPatternScalingTiled(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height),n}_getWatermarkContainer(e){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return this._addStyleAttributesToSvgElement(t,this.WATERMARK_CONTAINER_STYLES),t.setAttribute(`xmlns`,`http://www.w3.org/2000/svg`),t}_getSvgFilter(e,t){let n=document.createElementNS(`http://www.w3.org/2000/svg`,`filter`);n.id=e;let r=document.createElementNS(`http://www.w3.org/2000/svg`,`feDropShadow`);return r.setAttribute(`dx`,`0.5`),r.setAttribute(`dy`,`0.5`),r.setAttribute(`stdDeviation`,`1`),r.setAttribute(`flood-color`,`black`),r.setAttribute(`flood-opacity`,`${t}`),n.appendChild(r),n}_getRect(e,t,n,r,i){let a=document.createElementNS(`http://www.w3.org/2000/svg`,`rect`);return a.setAttribute(`x`,`${e}%`),a.setAttribute(`y`,`${t}%`),a.setAttribute(`width`,`${n}%`),a.setAttribute(`height`,`${r}%`),a.setAttribute(`fill`,`url(#${i})`),a}_getClampedUsername(){let e=``,t=this._call.callAgent,n=Z().calling.watermark,r=n.watermarkMaxUsernameLength,i=n.watermarkEmptyDisplayNamePlaceholder;if(t?.isEnterpriseUser()){let n=t.getUserProperties()?.sipUri;n&&typeof n==`string`&&(e=n.replace(`sip:`,``))}else e=t?.displayName??``,e||=i;return Swe(e,r)}_getSelectedWatermarkPattern(){return this._videoStream.mediaStreamType===`Video`&&this._watermarkCapability?.enabledForVideo&&this._watermarkCapability?.videoSettings?.pattern?this._watermarkCapability.videoSettings.pattern:this._videoStream.mediaStreamType===`ScreenSharing`&&this._watermarkCapability?.enabledForVbss&&this._watermarkCapability?.vbssSettings?.pattern?this._watermarkCapability.vbssSettings.pattern:``}_getWatermarkUsageTelemetryPayload(e=``){return{endpointSupportsWatermark:this._call.callAgent.isWatermarkSupported(),audioOnlyFallbackTriggered:this._call.watermarkAudioOnlyFallbackTriggered,audioOnlyFallbackTriggeredByViewId:e,watermarkUsage:{video:{enabled:this._watermarkCapability?.enabledForVideo,opacity:this._watermarkCapability?.videoSettings.opacity,pattern:this._watermarkCapability?.videoSettings.pattern},screenshare:{enabled:this._watermarkCapability?.enabledForVbss,opacity:this._watermarkCapability?.vbssSettings.opacity,pattern:this._watermarkCapability?.vbssSettings.pattern}},viewId:this._viewId}}},y7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},b7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},UIe=1,x7=class{get isRendering(){return this._isRendering}get scalingMode(){return this._scalingMode}get isMirrored(){return this._isMirrored}get target(){return this._target}get viewId(){return this._viewId}get isDisposed(){return this._disposed}get retryErrorEvents(){return this._retryErrorEvents}get size(){return{height:this._size.height,width:this._size.width}}constructor(e,t,n,r,i,a,o){this._target=e,this._viewId=t,this._videoStream=n,this._onDisposedCallback=i,this._createViewSteps=a,this._eventEmitter=new E3.EventEmitter,this._isRendering=!1,this._scalingMode=`Stretch`,this._isMirrored=!1,this._createViewResolvedOnPlayEvent=!1,this._hasRenderingEvent=!1,this._hasPlayEvent=!1,this._size={height:0,width:0},this._disposed=!1,this.resolveRenderingPendingPromise=(e=!1)=>{this._renderingDeferred?.isPending()&&(this._renderingDeferred.resolve(),e&&(this.logger.log(`video element play event was fired and promise was resolved and isRendering is: ${this._tsRenderer?.isRendering}`),this._createViewResolvedOnPlayEvent=!0)),e?this._hasPlayEvent||(this._hasPlayEvent=!0,this._createViewSteps.isPlayedTimestamp=Date.now(),this._createViewSteps.isPlayedTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.isPlayedTimestamp-this._createViewSteps.attemptTimestamp):!this._hasRenderingEvent&&this._isRendering&&(this._hasRenderingEvent=!0,this._createViewSteps.isRenderedTimestamp=Date.now(),this._createViewSteps.isRenderedTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.isRenderedTimestamp-this._createViewSteps.attemptTimestamp)},this._handleTsRendererChanged=e=>{if(this.logger.debug(`rendering state is ${this._isRendering}, changed to ${this._tsRenderer?.isRendering}`),this._tsRenderer)if(this._tsRenderer.isRendering!==this._isRendering&&(this._isRendering=this._tsRenderer.isRendering,this._videoStream.updateIsReceiving(),this._isRendering&&this.resolveRenderingPendingPromise(),e.log(`isRendering change to ${this._isRendering}`)),this._tsRenderer.isRendering){let e=this._tsRenderer.streamSize?.height||f2.HEIGHT,t=this._tsRenderer.streamSize?.width||f2.WIDTH;e===this._size.height&&t===this._size.width||this.setAndUpdateSize(),this.resolveRenderingPendingPromise()}else this._size.height=0,this._size.width=0,this._videoStream.updateSize();this.sendRendererTelemetry()},this.sendRendererTelemetry=()=>{if(this._tsRenderer)try{let e={isRendering:this._tsRenderer.isRendering,streamWidth:this._tsRenderer.streamSize.width,streamHeight:this._tsRenderer.streamSize.height,isVideoAttached:this._target.isConnected,rendererWidth:this._target?.offsetWidth,rendererHeight:this._target?.offsetHeight};if(this.previousStats){if(Kwe(this.previousStats,e))return}else this.previousStats=e;this.previousStats=e;let{callId:t,localParticipantId:n,isDisposed:r,viewIdsRegistered:i,height:a,width:o,...s}=this._videoStream.getStreamMetadata(),c={...e,...s,viewId:this._viewId,disposed:this._disposed};this._videoStream.call.stats.recordEvent({name:l3.remote_view,callId:t,localParticipantId:n,data:c})}catch{}},this._unsubscribeAvailabilityCallback=()=>{this._availableCallback&&=(this._videoStream.kind===`RemoteVideoStream`&&this._videoStream?.off(`isAvailableChanged`,this._availableCallback),void 0)},this._disposeTsRendererChangedObservable=()=>{this._tsRendererChanged&&=(this._tsRendererChanged.dispose(),void 0)},this._attemptToDisposeTsRenderer=()=>{if(this._tsRenderer){this.logger.debug(`disposing underlying remote renderer`);try{this._tsRenderer?.dispose(),this._tsRenderer=void 0}catch(e){throw this.logger.warn(`underlying remote renderer dispose failed with ${e?.message} error`),new Y({defaultError:J.VIEW.REMOTE_RENDERER_DISPOSE_FAIL})}}},this.logger=r.createChild(`RemoteStreamRenderer`+ UIe++),this.logger.log(`created`),o?.scalingMode!==void 0&&(this._scalingMode=o.scalingMode),o?.isMirrored!==void 0&&(this._isMirrored=o.isMirrored),this._remoteStreamTelemetryEventSender=new U6(this._videoStream.telemetryLogManager),this._watermarkOverlayProvider=new HIe(this._target,this._videoStream,this._viewId,this.logger,this._remoteStreamTelemetryEventSender),this._watermarkOverlayProvider.attach(),this._retryErrorEvents=new Set([J.VIEW.TIMEOUT.subCode,J.VIEW.SUBSCRIBE.subCode])}async start(){let e=J0(),t=+new Date,n=this.logger.createFnLogger(g4.Start),r={timestampInfo:{attemptTimestamp:t},correlationId:e,operation:y3.render,kindOfEvent:$.attempt,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote};if(this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(r),this._disposed)throw this.logger.warn(`already disposed`),new Y({defaultError:J.VIEW.START_ALREADY_DISPOSED});this._createViewTimeout&&=(clearTimeout(this._createViewTimeout),void 0);try{n.info(`scalingMode=${O4(this._scalingMode)}`),this._videoStream.registerRenderer(this),this._renderingDeferred=n3(),this._renderingDeferred.promise.catch(M4),this._videoStream.kind===`RemoteVideoStream`&&(this._availableCallback=()=>{this._videoStream.isAvailable||(n.warn(`stream isAvailable changed to false, attempting to reject operation`),this._renderingDeferred?.isPending()&&!this._disposed&&this._renderingDeferred?.reject(new Y({defaultError:J.VIEW.STREAM_BECAME_UNAVAILABLE})))},this._videoStream.on(`isAvailableChanged`,this._availableCallback)),this._createViewSteps.startSubscriptionTimestamp=Date.now(),this._createViewSteps.startSubscriptionTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.startSubscriptionTimestamp-this._createViewSteps.attemptTimestamp,this._videoStream.tsStream.start(this._target,{scalingMode:O4(this._scalingMode),transparent:!1}).then((e=>{if(this._createViewSteps.rendererIsAvailableTimestamp=Date.now(),this._createViewSteps.rendererIsAvailableTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.rendererIsAvailableTimestamp-this._createViewSteps.attemptTimestamp,this._isMirrored&&(this._target.style.transform=`rotateY(180deg)`,this._target.style.webkitTransform=`rotateY(180deg)`),this._tsRenderer=e,this.logger.info(`subscribed to video, waiting for the first frame`),this._disposed)throw this.logger.warn(`already disposed, dispose underlying renderer`),this._attemptToDisposeTsRenderer(),new Y({defaultError:J.VIEW.START_ALREADY_DISPOSED});if(this.logger.info(`current state of rendering is ${this._tsRenderer.isRendering}`),this.sendRendererTelemetry(),Z().rendering.remoteVideo.createViewTimeout!==-1&&(this._createViewTimeout=setTimeout((()=>{if(this._renderingDeferred?.isPending())try{this._renderingDeferred.reject(new Y({defaultError:J.VIEW.TIMEOUT})),this._createViewTimeout&&=(clearTimeout(this._createViewTimeout),void 0)}catch{}}),Z().rendering.remoteVideo.createViewTimeout)),Z().rendering.remoteVideo.speedupCreateViewWithPlayEvent){let e=this._target&&this._target.children.length>0&&this._target.children[0];e?e.addEventListener(`play`,this.videoPlayEventListener.bind(this)):this.logger.warn(`video element was not found while trying to listen to play event`)}this._tsRendererChanged=this._tsRenderer.changed((()=>this._handleTsRendererChanged(n))),this._tsRenderer.isRendering&&(this._isRendering=!0,this._videoStream.updateIsReceiving(),this.setAndUpdateSize(),this.resolveRenderingPendingPromise())})).catch((e=>{if(this.logger.info(`Failed to subscribe to video`),this._renderingDeferred?.isPending()){let t=new Y({defaultError:J.VIEW.SUBSCRIBE,originalError:e});this._renderingDeferred.reject(t)}})),await this._renderingDeferred.promise,this._videoStream.flushIsReceiving(),this._unsubscribeAvailabilityCallback(),Z().rendering.remoteVideo.forceCheckIfVideoWasAttachedToDom&&this._checkIfVideoWasAttachedToDom();let r={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:y3.render,kindOfEvent:$.success,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,createViewResolvedOnPlayEvent:this._createViewResolvedOnPlayEvent};return this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(r),this}catch(n){this.logger.warn(`Failed to render, message=${n}`);try{this._retryErrorEvents.has(n?.subCode)||this.dispose()}catch(e){this.logger.warn(`dispose failed with ${e?.message} error`)}let r=new Y({defaultError:J.VIEW.START,originalError:n});if(r.message!==J.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&r.message!==J.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){let n={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:y3.render,additionalDetails:{failureReason:r.message,code:zG,...J3(r)},kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,createViewResolvedOnPlayEvent:this._createViewResolvedOnPlayEvent};this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(n)}throw r}}videoPlayEventListener(){this.logger.log(`video element play event was fired`),this.resolveRenderingPendingPromise(!0)}setAndUpdateSize(){try{this._size.width=this._tsRenderer?.streamSize.width||f2.WIDTH,this._size.height=this._tsRenderer?.streamSize.height||f2.HEIGHT,this._videoStream.updateSize()}catch(e){this.logger.error(`Failed to update video stream size with error ${e}`)}}async setScalingMode(e){if(!this._tsRenderer)throw new Y({defaultError:J.VIEW.SCALING_MODE});await this._tsRenderer.setScalingMode(O4(e)),this._scalingMode=e}_clearTimeouts(){this._checkIfVideoWasAttachedToDomTimeout&&=(clearTimeout(this._checkIfVideoWasAttachedToDomTimeout),void 0),this._createViewTimeout&&=(clearTimeout(this._createViewTimeout),void 0)}dispose(e=S3.Public_App){if(this._disposed)throw new Y({defaultError:J.VIEW.RENDERER_DISPOSE_ALREADY_DISPOSED});if(this._disposed=!0,this._disposeTsRendererChangedObservable(),this._unsubscribeAvailabilityCallback(),this._attemptToDisposeTsRenderer(),this._renderingDeferred?.isPending()){let t;switch(e){case S3.Internal_LargeMeetingVideoRendering:t=J.VIEW.LARGE_MEETING_VIEW_DISPOSED;break;case S3.Internal_RemoteVideoStreamDisposed:t=J.VIEW.REMOTE_VIDEO_STREAM_DISPOSED;break;default:t=J.VIEW.APP_VIEW_DISPOSED}this._renderingDeferred.reject(new Y({defaultError:t}))}if(this._target){let e=this._target.children&&this._target.children.length>0&&this._target.children[0];e&&e.removeEventListener(`play`,this.videoPlayEventListener),this._target.remove()}try{e!==S3.Public_App&&this._onDisposedCallback(e)}catch(e){this.logger.debug(`dispose callback failed with ${e?.message} error`)}this._watermarkOverlayProvider.dispose(),this._videoStream.unregisterRenderer(this),this._size.height=0,this._size.width=0,this._videoStream.updateSize(),this._isRendering=!1,this._videoStream.updateIsReceiving(),this._eventEmitter.removeAllListeners(),this._renderingDeferred=void 0,this._clearTimeouts()}_checkIfVideoWasAttachedToDom(){if(this._checkIfVideoWasAttachedToDomTimeout&&=(clearTimeout(this._checkIfVideoWasAttachedToDomTimeout),void 0),Z().rendering.remoteVideo.checkIfVideoAttachedToDom_poll){let e=Z().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalMaxTries,t=()=>{this._target.isConnected||e<=0?this.sendRendererTelemetry():(e--,e>=0&&(this._checkIfVideoWasAttachedToDomTimeout=setTimeout((()=>t()),Z().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalTime)))};t()}else this._checkIfVideoWasAttachedToDomTimeout=setTimeout((()=>{this._target.isConnected&&this.sendRendererTelemetry()}),Z().rendering.remoteVideo.checkIfVideoAttachedToDom_timeout)}};y7([UG,b7(`design:type`,Object)],x7.prototype,`logger`,void 0),y7([YG(g4.Start),b7(`design:type`,Function),b7(`design:paramtypes`,[]),b7(`design:returntype`,Promise)],x7.prototype,`start`,null),y7([JG(g4.Dispose),b7(`design:type`,Function),b7(`design:paramtypes`,[String]),b7(`design:returntype`,void 0)],x7.prototype,`dispose`,null);var S7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},C7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},w7=class{get isRendering(){return this._isRendering}get scalingMode(){return this._scalingMode}get isMirrored(){return this._isMirrored}get target(){return this._target}get isDisposed(){return this._disposed}constructor(e,t,n,r,i){this._target=e,this._videoStream=t,this._onDisposed=r,this._eventEmitter=new E3.EventEmitter,this._isRendering=!1,this._scalingMode=`Stretch`,this._isMirrored=!0,this._disposed=!1,this.logger=n.createChild(`LocalStreamRenderer`),this.logger.log(`created`),i?.scalingMode!==void 0&&(this._scalingMode=i.scalingMode),i?.isMirrored===void 0?this._videoStream.mediaStreamType===`ScreenSharing`&&(this._isMirrored=!1):this._isMirrored=i.isMirrored,this._localStreamTelemetryEventSender=new U6(this._videoStream.telemetryLogManager)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}async start(){let e=J0(),t=this.logger.createFnLogger(g4.Start),n=+new Date,r={timestampInfo:{attemptTimestamp:n},correlationId:e,operation:y3.render,kindOfEvent:$.attempt,mediaType:this._videoStream.mediaStreamType,streamType:v3.Local};this._localStreamTelemetryEventSender.sendMediaStreamEvent(r);try{if(t.info(`attempting to select new device as a source`),this._videoStream.source instanceof z6&&this._videoStream.mediaStreamType===`Video`){let e=this._videoStream.source.deviceManager.getTsDeviceManager();e.selectDevices({camera:this._videoStream.source.id}),t.info(`device selected`),t.info(`creating preview`),this._tsRenderer=await e.createPreview(this._target,{kind:`camera`},{scalingMode:O4(this._scalingMode),transparent:!1,ignoreMirroring:!1,disposeRendererWhenStreamisNotAvailable:()=>!0})}else{if(this._videoStream.mediaStreamType!==`RawMedia`&&this._videoStream.mediaStreamType!==`ScreenSharing`)throw new Y({defaultError:J.VIEW.UNKNOWN_STREAM_TYPE});{this._rawMediaOrSS_previewVideo=document.createElement(`video`),this._rawMediaOrSS_previewVideo.style.width=`100%`,this._rawMediaOrSS_previewVideo.style.height=`100%`,this._rawMediaOrSS_previewVideo.style.objectFit=`contain`,this._rawMediaOrSS_previewVideo.setAttribute(`playsinline`,`true`),this._rawMediaOrSS_previewVideo.disablePictureInPicture=!0,this._rawMediaOrSS_previewVideo.autoplay=!0;let e=await this._videoStream.getMediaStream(),t=new MediaStream(e.getVideoTracks());this._rawMediaOrSS_previewVideo.srcObject=t,this._rawMediaOrSS_previewVideo.play(),this._target.appendChild(this._rawMediaOrSS_previewVideo)}}this._isMirrored&&(this._target.style.transform=`rotateY(180deg)`,this._target.style.webkitTransform=`rotateY(180deg)`),this._videoStream.registerRenderer(this);let r={timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:e,operation:y3.render,kindOfEvent:$.success,mediaType:this._videoStream.mediaStreamType,streamType:v3.Local};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),this}catch(r){this.dispose();let i=G3(t,r),a={timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:e,operation:y3.render,additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,...J3(i)},kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:v3.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(a),i}}setScalingMode(e){if(this._tsRenderer)this._tsRenderer.setScalingMode(O4(e)),this._scalingMode=e;else{if(!this._rawMediaOrSS_previewVideo)throw new Y({defaultError:J.VIEW.SCALING_MODE});switch(e){case`Stretch`:this._rawMediaOrSS_previewVideo.style.objectFit=`fill`;break;case`Crop`:this._rawMediaOrSS_previewVideo.style.objectFit=`cover`;break;default:this._rawMediaOrSS_previewVideo.style.objectFit=`contain`}}}setSourceObject(e){this.disposeScreenSharingMediaStream();let t=this._target.querySelector(`video`);t&&(t.srcObject=e,t.play())}dispose(){if(!this._disposed){if(this._tsRenderer)try{this.logger.log(`disposing underlying local renderer`),this._tsRenderer.dispose(),this._tsRenderer=void 0}catch(e){throw this.logger.warn(`underlying local renderer dispose failed with ${e?.message} error`),new Y({defaultError:J.VIEW.LOCAL_RENDERER_DISPOSE_FAIL})}this.disposeScreenSharingMediaStream(),this._target.remove(),this._onDisposed&&this._onDisposed(this),this._eventEmitter.removeAllListeners(),this._disposed=!0}}disposeScreenSharingMediaStream(){if(this._videoStream.getCall()?.localScreenSharingStream){let e=this._target.querySelector(`video`),t=e?.srcObject;t&&(t.getVideoTracks().forEach((e=>{e.stop()})),e.srcObject=null,this.logger.info(`disposed of ScreenSharing MediaStream`))}}};S7([UG,C7(`design:type`,Object)],w7.prototype,`logger`,void 0),S7([YG(_4.Start),C7(`design:type`,Function),C7(`design:paramtypes`,[]),C7(`design:returntype`,Promise)],w7.prototype,`start`,null),S7([JG(_4.SetScalingMode),C7(`design:type`,Function),C7(`design:paramtypes`,[String]),C7(`design:returntype`,void 0)],w7.prototype,`setScalingMode`,null),S7([JG(_4.SetSourceObject),C7(`design:type`,Function),C7(`design:paramtypes`,[MediaStream]),C7(`design:returntype`,void 0)],w7.prototype,`setSourceObject`,null),S7([JG(_4.Dispose),C7(`design:type`,Function),C7(`design:paramtypes`,[]),C7(`design:returntype`,void 0)],w7.prototype,`dispose`,null);var T7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},E7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},WIe=1,D7=class e{get scalingMode(){return this._streamRenderer.scalingMode}get isMirrored(){return this._streamRenderer.isMirrored}get disposed(){return this._disposed}constructor(e,t,n,r,i){if(this._videoStream=e,this._viewId=n,this._options=i,this._disposed=!1,this._isRetryErrorSubCode=e=>`retryErrorEvents`in this._streamRenderer&&this._streamRenderer.retryErrorEvents.has(e.subCode),this._deleteActiveRemoteVideoStreamView=(e,t)=>{if(e.call.activeRemoteVideoStreamViews?.has(e.id)){let n=e.call.activeRemoteVideoStreamViews?.get(e.id);n?.delete(t),n?.size==0&&e.call.activeRemoteVideoStreamViews?.delete(e.id)}},this.logger=t.createChild(`VideoStreamRendererView`+ WIe++),this.target=document.createElement(`div`),this.target.style.width=`100%`,this.target.style.height=`100%`,this._videoStream instanceof v8)this._streamRenderer=new x7(this.target,this._viewId,this._videoStream,this.logger,(e=>{this._disposed||this.dispose(e)}),r,this._options);else{if(!(this._videoStream instanceof X6))throw new Y({defaultError:J.VIEW.VIEW_WRONG_STREAM_TYPE});this._streamRenderer=new w7(this.target,this._videoStream,this.logger,(()=>this.dispose),this._options)}this._telemetryLogManager=this._videoStream.telemetryLogManager,this.logger.info(`created`)}async render(){let e=this.logger.createFnLogger(this._videoStream instanceof v8?f4.RenderRemoteStream:f4.RenderLocalStream);if(this._disposed)throw e.log(`failed, stream disposed!`),new Y({defaultError:J.VIEW.RENDER_FAIL_STREAM_DISPOSED});let t=Z().rendering.remoteVideo.maxRendererRetries,n=1,r=(e,t)=>e().catch((i=>{if(t>0&&this._isRetryErrorSubCode(i))return n+=1,r(e,t-1);throw this._streamRenderer.isDisposed||this._streamRenderer.dispose(),i})),i=()=>this._streamRenderer.start();try{await r(i,t-1)}catch(t){throw e.error(`Failed to render stream ${this._viewId} after ${n} retries.`),this._isRetryErrorSubCode(t)&&n>1&&(t.message+=`\nFailed to render stream ${this._viewId} after ${n} retries.`),t}return n}async updateScalingMode(e){if(this._disposed)throw new Y({defaultError:J.VIEW.SCALING_MODE_DISPOSED});if(e!==`Crop`&&e!==`Fit`&&e!==`Stretch`)throw new Y({defaultError:J.VIEW.SCALING_MODE_WRONG_VAL});try{await this._streamRenderer.setScalingMode(e)}catch(e){throw new Y({defaultError:J.VIEW.SCALING_MODE,originalError:e})}}dispose(t=S3.Public_App){if(this._disposed)throw new Y({defaultError:J.VIEW.VIEW_ALREADY_DISPOSED});this._disposed=!0;let n=+new Date,r=J0();try{t===S3.Public_App&&this.sendDisposeViewEvent({eventName:Q.acs_calling_dispose_view_attempt,correlationId:r,timestampInfo:{attemptTimestamp:n}}),this.logger.debug(`attempt to dispose stream renderer`),this._streamRenderer.dispose(t),this.target?.remove(),this._videoStream instanceof s7&&(this._deleteActiveRemoteVideoStreamView(this._videoStream,this._viewId),Z()?.rendering.remoteVideo.decrementOvcOnRemoteSsRendering&&this._videoStream.mediaStreamType===`ScreenSharing`&&(e.remoteScreenSharingViews.delete(this._viewId),e.remoteScreenSharingViews.size<=0&&this._videoStream.call.setIsRenderingRemoteScreenShare(!1)));let i=+new Date;t===S3.Public_App&&this.sendDisposeViewEvent({eventName:Q.acs_calling_dispose_view_success,correlationId:r,timestampInfo:{deltaTimeInMs:i-n}})}catch(e){let i=new Y({defaultError:J.VIEW.DISPOSE_FAIL,originalError:e});if(t===S3.Public_App){let e=+new Date;this.sendDisposeViewEvent({eventName:Q.acs_calling_dispose_view_failure,correlationId:r,timestampInfo:{deltaTimeInMS:e-n}},i)}throw i}}sendDisposeViewEvent(e,t){try{let n,r;t&&(n=typeof t?.message==`string`?t?.message:``,r={...J3(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:{...this._videoStream.getStreamMetadata(),viewId:this._viewId,correlationId:e.correlationId,timestampInfo:e.timestampInfo,failureReason:n,additionalDetails:r}})}catch{this.logger.debug(`Unable to send telemtery`)}}};D7.remoteScreenSharingViews=new Map,T7([UG,E7(`design:type`,Object)],D7.prototype,`logger`,void 0),T7([YG(f4.Render),E7(`design:type`,Function),E7(`design:paramtypes`,[]),E7(`design:returntype`,Promise)],D7.prototype,`render`,null),T7([YG(f4.UpdateScalingMode),E7(`design:type`,Function),E7(`design:paramtypes`,[String]),E7(`design:returntype`,Promise)],D7.prototype,`updateScalingMode`,null),T7([JG(f4.Dispose),E7(`design:type`,Function),E7(`design:paramtypes`,[String]),E7(`design:returntype`,void 0)],D7.prototype,`dispose`,null);var GIe=U5();function KIe(e,t,n,r){let i=[`audioBitrate`,`videoBitrate`,`downloadBitrate`,`bufferLengthInMs`,`videoHeight`,`videoWidth`,`currentPlayPosition`],a=t[n.toString()];a!==void 0&&i.forEach((t=>{let n=t,i=t;if(a[n]!==void 0){let t=a[n];e[i]===void 0?e[i]=[t]:(e[i]?.length>=r&&e[i]?.shift(),e[i]?.push(t))}}))}var qIe=class{get createViewStats(){return this._createViewStats}get initialCreateViewStats(){return this._initialCreateViewStats}constructor(e,t,n,r,i){this._statsCollector=e,this._streamId=t,this._logger=n,this._call=r,this._attemptTimestamp=i,this._createViewFailureStats={},this._createViewStats={},this._initialCreateViewStats={},this._statsCollector.on(`sampleReported`,(e=>{vke(this.createViewStats,this.initialCreateViewStats,e,this._streamId)}))}getCreateViewFailureStats(){try{let e=0,t=NaN;this.createViewStats.video?.framesDropped!==void 0&&this.initialCreateViewStats.video?.framesDropped!==void 0&&(e=this.createViewStats.video?.framesDropped.length,t=this.createViewStats.video?.framesDropped[e-1]-this.initialCreateViewStats.video?.framesDropped[0]);let n=NaN;this.createViewStats.video?.framesReceived!==void 0&&this.initialCreateViewStats.video?.framesReceived!==void 0&&(e=this.createViewStats.video.framesReceived.length,n=this.createViewStats.video.framesReceived[e-1]-this.initialCreateViewStats.video?.framesReceived[0]);let r=NaN;this.createViewStats.video?.framesDecoded!==void 0&&this.initialCreateViewStats.video?.framesDecoded!==void 0&&(e=this.createViewStats.video.framesDecoded.length,r=this.createViewStats.video.framesDecoded[e-1]-this.initialCreateViewStats.video?.framesDecoded[0]);let i=NaN;this.createViewStats.video?.keyFramesDecoded!==void 0&&this.initialCreateViewStats.video?.keyFramesDecoded!==void 0&&(e=this.createViewStats.video.keyFramesDecoded.length,i=this.createViewStats.video.keyFramesDecoded[e-1]-this.initialCreateViewStats.video?.keyFramesDecoded[0]);let a=0;!isNaN(t)&&n>0&&(a=Number((t/n*100).toFixed(7)));let o=!1;n>0&&r===0&&(o=!0);let s=!1;!isNaN(r)&&!isNaN(i)&&r>0&&r===i&&(s=!0);let c=[],l=this._call.networkQualityUfdEventDetails,u=Z().rendering.remoteVideo.createViewFailureNetworkUfdCheckWindowInMs;l.forEach((e=>{Math.abs(e.timestampInfo-this._attemptTimestamp)<=u&&c.push(e)}));let d=n===0;this._createViewFailureStats.video={framesDroppedPercentage:a,framesReceivedButNothingDecoded:o,onlyKeyFramesDecoded:s,networkQualityEventsDuringAttempt:c,zeroFramesReceived:d}}catch{this._logger.debug(`Error calculating create view failure stats!`)}return this._createViewFailureStats}},JIe=class{constructor(e,t){this._liveStreamStatsCollector=e,this._streamId=t,this._liveStreamStats={},this._initialLiveStreamStats={};let n=Z()?.rendering.remoteVideo.createViewSendMediaStatsMaxLength;this._liveStreamStatsCollector.on(`sampleReported`,(e=>{KIe(this._liveStreamStats,e,this._streamId,n),e4.isEmpty(this._initialLiveStreamStats)&&(this._initialLiveStreamStats=this._liveStreamStats)}))}get initialCreateViewLiveStreamStats(){return this._initialLiveStreamStats}get createViewLiveStreamStats(){return this._liveStreamStats}},O7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},k7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},A7=class{get _createViewStats(){return this._videoStream.kind!==`RemoteVideoStream`&&this._videoStream.kind!==`ComposedVideoStream`||!this._createViewTelemetryHelper?this._videoStream.kind===`LiveVideoStream`&&this._createViewLiveStreamTelemetryHelper?this._createViewLiveStreamTelemetryHelper.createViewLiveStreamStats:{}:this._createViewTelemetryHelper.createViewStats}constructor(e){if(this.size={height:0,width:0},this.views=new Map,this.disposed=!1,this._attemptToDisposeView=e=>{try{e?.dispose()}catch(e){this.logger.warn(e?.message||`Failed to dispose, unknown error`)}},this._addActiveRemoteVideoStreamView=(e,t,n)=>{if(e.call.activeRemoteVideoStreamViews?.has(e.id)){let r=e.call.activeRemoteVideoStreamViews?.get(e.id);r&&r.set(t,n)}else{let r=new Map;r.set(t,n),e.call.activeRemoteVideoStreamViews?.set(e.id,r)}},!(e instanceof X6||e instanceof v8||e instanceof s7))throw new Y({defaultError:J.VIEW.RENDERER_WRONG_STREAM_TYPE});let t=ZW(`ACS`);this._videoStream=e,this._telemetryLogManager=e.telemetryLogManager,this.logger=new V6(t,e instanceof X6?[()=>`VideoStreamRenderer:LocalVideoStream:${GIe.pii.Omit(e?.source?.id)}`]:[()=>`VideoStreamRenderer:${e.kind}:${e?.id}`]),this.logger.info(`created`)}async createView(e){if(this.disposed)throw new Y({defaultError:J.VIEW.RENDERER_DISPOSED});let t={},n=+new Date,r=J0(),i=J0(),a,o;try{let s=1;if(t.attemptTimestamp=n,this.sendCreateViewEvent({eventName:Q.acs_calling_create_view_attempt,viewId:r,correlationId:i,timestampInfo:{attemptTimestamp:n},isMirrored:e?.isMirrored,scalingMode:e?.scalingMode,stepsInfo:t}),this._videoStream.kind===`RemoteVideoStream`&&!this._videoStream.isAvailable)throw new Y({defaultError:J.VIEW.ISAVAILABLE_FALSE});let c=Z(),l=E4();if(this._videoStream.kind===`RemoteVideoStream`&&this._videoStream.mediaStreamType!==`ScreenSharing`&&c?.calling.applyViewLimit&&l?.numVideoChannelsGvc){let e=l?.numVideoChannelsGvc,t=this._videoStream;if(!t.call.activeRemoteVideoStreamViews?.has(t.id)&&t.call.activeRemoteVideoStreamViews?.size>=e)throw new Y({defaultError:J.VIEW.MAX_NUM_OF_VIEWS_REACHED,defaultErrorMessageArgs:[e]})}if(c?.rendering.remoteVideo.createViewSendMediaStats){if(this._videoStream.kind===`RemoteVideoStream`||this._videoStream.kind===`ComposedVideoStream`){let e=this._videoStream,t=e.call;o=e.call.feature($5.MediaStats).createCollector();let r=e.id;this._createViewTelemetryHelper=new qIe(o,r,this.logger,t,n)}else if(this._videoStream.kind===`LiveVideoStream`){let e=this._videoStream;o=e.call.feature($5.LiveStream).createStatsCollector();let t=e.id;this._createViewLiveStreamTelemetryHelper=new JIe(o,t)}}a=new D7(this._videoStream,this.logger,r,t,e),this.views.set(r,a),s=await a.render(),this._videoStream.kind===`RemoteVideoStream`&&this._videoStream.mediaStreamType!==`ScreenSharing`&&this._addActiveRemoteVideoStreamView(this._videoStream,r,a),this._videoStream.kind===`RemoteVideoStream`&&this._videoStream.mediaStreamType===`ScreenSharing`&&c?.rendering.remoteVideo.decrementOvcOnRemoteSsRendering&&(this._videoStream.call.setIsRenderingRemoteScreenShare(!0),D7.remoteScreenSharingViews.set(r,a));let u=+new Date;return this.sendCreateViewEvent({eventName:Q.acs_calling_create_view_success,viewId:r,correlationId:i,timestampInfo:{deltaTimeInMs:u-n},additionalProperties:{isRetry:!!s&&s>1,attemptNumber:s},stepsInfo:t}),a}catch(e){let o=new Y({defaultError:J.VIEW.CREATE_VIEW_FAILED,originalError:e});if(this.views.delete(r),this._attemptToDisposeView(a),o.message!==J.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&o.message!==J.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){let e=Date.now();this.sendCreateViewEvent({eventName:Q.acs_calling_create_view_failure,viewId:r,correlationId:i,timestampInfo:{deltaTimeInMs:e-n},stepsInfo:t},o)}throw o}finally{o?.dispose()}}async sendCreateViewEvent(e,t){try{let n={},r={},i={};if(Z()?.rendering.remoteVideo.createViewSendMediaStats&&(e.eventName===Q.acs_calling_create_view_failure||e.eventName===Q.acs_calling_create_view_success)){if(this._videoStream.kind===`RemoteVideoStream`){let t=this._videoStream.call,r=await t.tsCall.getMediaSessionStatsAsync?.();n={isRetry:e.additionalProperties?.isRetry??!1,attemptNumber:e.additionalProperties?.attemptNumber??1,videoSubscriptionEvents:r?.extensions?.Video_SubscriptionEvents,screenSharingSubscriptionEvents:r?.extensions?.Sharing_SubscriptionEvents,videoSendMaxCapabilities:r?.extensions?.Video_send_MaxCapabilities,screenSharingSendMaxCapabilities:r?.extensions?.Sharing_send_MaxCapabilities,iceConnectedStateTime:r?.metrics?.IceConnectedStateTime,relayCandidate:r?.extensions?.RelayCandidate,videoRecvTimeToFirstFrame:r?.extensions?.Video_recv_TimeToFirstFrame,screenSharingRecvTimeToFirstFrame:r?.extensions?.Sharing_recv_TimeToFirstFrame,optimalVideoCount:t.tsCall.optimalVideoCount||1,currentNumberOfVideosRendered:t.activeRemoteVideoStreamViews?.size||0}}e.eventName===Q.acs_calling_create_view_failure&&(i=this._createViewTelemetryHelper?.getCreateViewFailureStats()??{},r=this._createViewStats)}n.visibilityState=document.visibilityState,e.isMirrored!==void 0&&(n.isMirrored=e.isMirrored),e.scalingMode!==void 0&&(n.scalingMode=e.scalingMode),e.eventName!==Q.acs_calling_create_view_failure&&e.eventName!==Q.acs_calling_create_view_success||this._videoStream.kind!==`RemoteVideoStream`&&this._videoStream.kind!==`ComposedVideoStream`||e4.forOwn(e.stepsInfo,((e,t)=>{e!==void 0&&(n[t]=e)}));let a=``,o={};t&&(a=typeof t?.message==`string`?t?.message:``,o={...J3(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:{viewId:e.viewId,correlationId:e.correlationId,timestampInfo:e.timestampInfo,...this._videoStream.getStreamMetadata(),failureReason:a,additionalProperties:n,additionalDetails:o,stats:r,createViewFailureDebugStats:i,videoStreamKind:this._videoStream.kind}})}catch{this.logger.debug(`Unable to send telemtery`)}}dispose(){if(this.disposed)throw new Y({defaultError:J.VIEW.RENDERER_ALREADY_DISPOSED});this.disposed=!0,this.views.forEach(this._attemptToDisposeView),this.views.clear()}};O7([UG,k7(`design:type`,Object)],A7.prototype,`logger`,void 0),O7([YG(p4.CreateView),k7(`design:type`,Function),k7(`design:paramtypes`,[Object]),k7(`design:returntype`,Promise)],A7.prototype,`createView`,null),O7([JG(p4.Dispose),k7(`design:type`,Function),k7(`design:paramtypes`,[]),k7(`design:returntype`,void 0)],A7.prototype,`dispose`,null);var YIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},j7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},M7=class{get identifier(){return this._identifier}get endpointDetails(){return this._tsParticipant?.endpoints?.endpointDetails.map((e=>({participantId:e.participantId,deviceType:e.deviceType,clientEndpointCapabilities:e.clientEndpointCapabilities,endpointMetadata:e.endpointMetadata})))||[]}get state(){return this._state}get videoStreams(){return[...this._mappedStreams.values()]}get isMuted(){return this._isMuted}get isSpeaking(){return this._isSpeaking}get callEndReason(){return this._callEndReason}get displayName(){return this._displayName}get hasDisplayNameChanged(){return this._hasDisplayNameChanged}get role(){return this._role}constructor(e,t,n,r,i){this._mappedStreams=new Map,this._state=`Idle`,this._lastTsParticipantState=0,this._isMuted=!1,this._isSpeaking=!1,this._displayName=``,this._realDisplayName=``,this._hasDisplayNameChanged=!1,this._role=`Unknown`,this.acsToTsStreamType=e=>e===`Video`?0:e===`ScreenSharing`?1:void 0,this.getParticipantDisplayNameOverride=()=>this._tsParticipant?.propertyBag?.displayNameOverride?.value?.displayNameOverrideValue,this._identifier=e,this.logger=t.createChild((()=>`RemoteParticipant{${this._identifier.kind}}`)),this._telemetryLogManager=i,this._eventEmitter=new w6(this.logger),this._callAgent=r,this._call=n,this.logger.log(`created`),this._renderers={Video:{renderingState:{}},ScreenSharing:{renderingState:{}}}}on(e,t){if(e!==`stateChanged`&&e!==`isMutedChanged`&&e!==`isSpeakingChanged`&&e!==`displayNameChanged`&&e!==`roleChanged`&&e!==`videoStreamsUpdated`)throw new Y({defaultError:J.REMOTE_PARTICIPANT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`stateChanged`&&e!==`isMutedChanged`&&e!==`isSpeakingChanged`&&e!==`displayNameChanged`&&e!==`roleChanged`&&e!==`videoStreamsUpdated`)throw new Y({defaultError:J.REMOTE_PARTICIPANT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}async mute(){let e=Z();if(!e.calling.enableMuteOthers)throw new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_DISABLED});if(!this._call.tsCall.conversationType&&this._call.callInfo.context===b4.TwoParty)throw new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_1_TO_1_UNSUPPORTED});if(![`Connected`,`Hold`].some((e=>e===this._state)))throw new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_NONCONNECTED_UNSUPPORTED});let t=this.logger.createFnLogger(l4.Mute),n=+new Date,r=J0();if(this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:d3.MuteSpecificParticipant,timestampInfo:{attemptTimestamp:n},correlationId:r,step:`mid-call`}),!e.calling.allowMutePstnRemoteParticipant&&this._identifier.kind===`phoneNumber`){let e=+new Date,i=J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_PSTN_UNSUPPORTED;t.warn(i.message);let a=new Y({defaultError:i});throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:d3.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:e-n},correlationId:r,step:`mid-call`},a),a}try{t.info(`remote mute specific`),this._tsParticipant===void 0?t.warn(`no participant to mute in attempt to mute specific remote participant`):await this._call.tsCall.muteParticipants(1,[this._tsParticipant]),t.info(`remote mute specific success`);let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:d3.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:e-n},correlationId:r,step:`mid-call`})}catch(e){let i=new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_FAILED,originalError:e});t.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:d3.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:a-n},correlationId:r,step:`mid-call`},i),i}}_dispose(){this.logger.log(`dispose`),this._participantChangedHandler&&this._participantChangedHandler.dispose(),this._mappedStreams.forEach((e=>e.dispose())),this._eventEmitter.emit(`stateChanged`,this._state),this._eventEmitter.removeAllListeners(),this._disposeVideo(0),this._disposeVideo(1)}get tsRemoteParticipant(){return this._tsParticipant}get kind(){return`RemoteParticipant`}setCallEndReason(e){this._callEndReason=e}observeParticipant(e){if(this._tsParticipant)return;let t=Z();this._tsParticipant=e,this._displayName=e.displayName,this._realDisplayName=e.displayName,this._isMuted=e.isServerMuted;let n=this.getParticipantDisplayNameOverride();t.calling.rename.enableShowEditedDisplayName&&n&&n!==this._displayName&&(this._displayName=n,this._hasDisplayNameChanged=!0),this._participantChangedHandler=this._tsParticipant.changed((()=>{this._tsParticipant&&this._tsParticipant.state!==this._lastTsParticipantState&&(this._lastTsParticipantState=this._tsParticipant.state,this._mapTsParticipantState(this._tsParticipant.state)),this._mapStreams(),this._tsParticipant&&this._tsParticipant.isServerMuted!==this._isMuted&&(this._isMuted=this._tsParticipant.isServerMuted,this._eventEmitter.emit(`isMutedChanged`));let n=this.getParticipantDisplayNameOverride();if(t.calling.rename.enableShowEditedDisplayName&&n&&n!==this._displayName){let e=J0(),t=this._displayName;this._displayName=n,this._hasDisplayNameChanged=n!==this._realDisplayName,this.logger.log(`display name changed ${t}=>${n}, correlationId=${e}`),this._eventEmitter.emit(`displayNameChanged`,{newValue:this._displayName,oldValue:t,reason:`editedDisplayName`}),this.sendDisplayNameOverrideEvent(e)}else if((!n||!t.calling.rename.enableShowEditedDisplayName)&&this._tsParticipant?.displayName&&this._tsParticipant.displayName!==this._displayName){let t=this._displayName;this._displayName=e.displayName,this._realDisplayName=e.displayName,this._eventEmitter.emit(`displayNameChanged`,{newValue:this._displayName,oldValue:t})}if(this._tsParticipant&&this._tsParticipant.advancedMeetingRole!==this._lastTsParticipantAdvancedRole&&(this._lastTsParticipantAdvancedRole=e.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole)),this._tsParticipant){let e=this._tsParticipant.voiceLevel!==0;e!==this._isSpeaking&&(this._isSpeaking=e,this._eventEmitter.emit(`isSpeakingChanged`))}})),this._mapTsParticipantState(this._tsParticipant.state),this._mapStreams(),this._lastTsParticipantAdvancedRole=this._tsParticipant.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole),this._displayName||!DG(this._identifier)&&!EG(this._identifier)||this.getRemoteParticipantProperties().then((e=>{e?.displayName&&(this._displayName=e.displayName,this._eventEmitter.emit(`displayNameChanged`))})).catch((e=>{this.logger.error(`Failed to get remote participant properties: ${e}`)}))}setParticipantState(e){e!==this._state&&(this.logger.log(`state changed ${this._state}=>${this.state}`),this._state=e,this._state==`Disconnected`?this._dispose():this._eventEmitter.emit(`stateChanged`,this._state))}async stopRenderingVideo(){this._disposeVideo(0)}async renderVideo(e,t){return typeof e==`function`?this._updateRenderingState(e,`Video`,t):await this._renderStreamForParticipant(e,0,t)}async _updateRenderingState(e,t,n){if(typeof e==`function`){let r,i=t===`Video`?0:1;this._tsParticipant&&(r=n?.stream?n.stream:new s7(this._tsParticipant.streams[i][0],this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier),r.on(`isReceivingChanged`,(()=>{this._renderers[t].renderingState.isFrozen=!r.isReceiving,e(this._renderers[t].renderingState)})),r.on(`isAvailableChanged`,(async()=>{this._renderers[t].renderingState.isStreaming!==r?.isAvailable&&(this._renderers[t].renderingState.isStreaming=r.isAvailable,this._renderers[t].renderingState.isStreaming&&!this._renderers[t].renderer&&(this._renderers[t].renderer=this._renderers[t]?.renderer?this._renderers[t].renderer:new A7(r),this._renderers[t].view||(this._renderers[t].view=await this._renderers[t].renderer?.createView(n?.viewOptions)),this._renderers[t].renderingState.videoTarget=this._renderers[t].view?.target)),e(this._renderers[t].renderingState)})))}}async renderScreenShare(e,t){return typeof e==`function`?this._updateRenderingState(e,`ScreenSharing`,t):this._renderStreamForParticipant(e,1,t)}async _renderStreamForParticipant(e,t,n){if(this._tsParticipant){let r=t===0?`Video`:`ScreenSharing`,i=n?.stream?n.stream:new s7(this._tsParticipant.streams[t][0],this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier);return i.isAvailable&&(this._renderers[r].view=await this._appendVideo(e,t,i,n?.viewOptions)),i.on(`isAvailableChanged`,(async()=>{i.isAvailable?this._renderers[r].view=await this._appendVideo(e,t,i,n?.viewOptions):this._renderers[r]?.view&&this._renderers[r].view?.target&&this._renderers[r].view?.target.parentNode?.removeChild(this._renderers[r].view?.target)})),Promise.resolve({stream:i,view:this._renderers[r]?.view})}return Promise.reject()}async _appendVideo(e,t,n,r){try{let i=t===0?`Video`:`ScreenSharing`;if(t===0&&(this._renderers[i]?.renderer||(this._renderers[i].renderer=this._renderers[i]?.renderer?this._renderers[i].renderer:new A7(n),this._renderers[i].view=await this._renderers[i].renderer?.createView(r)),this._renderers[i].view))return e.appendChild(this._renderers[i].view?.target||document.createElement(`emptyNode`)),Promise.resolve(this._renderers[i].view)}catch(e){return Promise.reject(e)}return Promise.reject()}async _disposeVideo(e){let t=e===0?`Video`:`ScreenSharing`;this._renderers[t].view?.dispose(),this._renderers[t].renderer?.dispose(),this._renderers[t]={renderingState:{}}}_setParticipantRole(e){let t=iTe(Z(),e);t===`Unknown`?this.logger.log(`tsParticipant advancedMeetingRole=${e} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${e}=>${t}`),this._role!=t&&(this.logger.log(`role changed ${this._role}=>${e}`),this._role=t,this._eventEmitter.emit(`roleChanged`))}_mapTsParticipantState(e){let t,n={0:`Idle`,1:`Connecting`,2:`Ringing`,3:`Connected`,4:`Disconnected`,5:`Hold`,7:`InLobby`,6:`EarlyMedia`};n[e]?(t=n[e],this.logger.log(`mapped tsParticipant ${e}=>${this._state}`),this.setParticipantState(t)):this.logger.log(`unable to map tsCall state=${e} to call state`)}_mapStreams(){let e=[],t=[],n=e=>{this._mappedStreams.set(e.id,e)},r=e=>{let t=this._mappedStreams.get(e.id);t&&(this.logger.log(`stream removed, type==${t.mediaStreamType} id=${e.id}`),this._mappedStreams.delete(e.id),t.dispose())},i=n=>{if(this._tsParticipant)if(this._tsParticipant.streams&&ywe(this._tsParticipant.streams[n])){let r=[];this._tsParticipant&&(r=this._tsParticipant.streams[n]),r.forEach((t=>{if(!this._mappedStreams.get(t.id)){let n=new s7(t,this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier);this.logger.log(`stream created, type==${n.mediaStreamType} id=${t.id}`),e.push(n)}})),this._mappedStreams.forEach((e=>{this.acsToTsStreamType(e.mediaStreamType)===n&&(r.some((t=>t.id===e.id))||t.push(e))}))}else this._mappedStreams.forEach((e=>{this.acsToTsStreamType(e.mediaStreamType)===n&&t.push(e)}))};i(0),i(1),(e.length>0||t.length>0)&&(e.forEach(n),t.forEach(r),this._eventEmitter.emit(`videoStreamsUpdated`,{added:e,removed:t}))}sendAudioEvent(e,t){try{let n,r;t&&(n=t.message,r=J3(t));let i={callId:this._call.id,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||``,failureReason:n||``,additionalDetails:{...r}};e.eventType!==void 0&&(i.eventType=e.eventType),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:i})}catch{this.logger.debug(`Unable to send mute others audio telemetry`)}}sendDisplayNameOverrideEvent(e){if(this._telemetryLogManager)try{let t={callId:this._call.id,timestampInfo:{attemptTimestamp:+new Date},correlationId:e,step:`event`};this._telemetryLogManager.sendEvent({name:Q.acs_calling_edited_display_name,tenant:p2,properties:t})}catch{this.logger.debug(`Unable to send display name override event telemetry`)}}getRemoteParticipantProperties(){return new Promise((e=>{let t={policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`TeamsMeetingPolicy`],userProperties:[`displayName`]};this._callAgent.mtPolicyService.requestUserPoliciesFromAcsMiddleTier(this._call.id,K2(this.identifier),t,this._callAgent.getUserMri()).then((t=>{e(t.userAggregatedPolicySettingData?.userProperties)}))}))}};YIe([UG,j7(`design:type`,Object)],M7.prototype,`logger`,void 0),YIe([YG(l4.Mute),j7(`design:type`,Function),j7(`design:paramtypes`,[]),j7(`design:returntype`,Promise)],M7.prototype,`mute`,null);var XIe=class{constructor(e){this._deviceManager=e,this._eventEmitter=new E3.EventEmitter,this._selectedDeviceListeners=new Map,this._selectedDevices=new Map,this._deviceInfoMapper=this._deviceManager.deviceInfoMapper;let t=e=>()=>{let t=this._selectedDevices.get(e),n=e===`Speaker`?this._deviceManager.selectedSpeaker:e===`Microphone`?this._deviceManager.selectedMicrophone:void 0,r=n===void 0?void 0:{id:this._deviceInfoMapper.getDeviceId(n.id),name:this._deviceInfoMapper.scrubDeviceLabel(n.name)};this._selectedDevices.set(e,r),this._eventEmitter.emit(`selectedDeviceChanged`,{selectedDeviceType:e,oldDevice:t,newDevice:r})},n=t(`Speaker`);this._selectedDeviceListeners.set(`Speaker`,n),this._deviceManager.on(`selectedSpeakerChanged`,n),n();let r=t(`Microphone`);this._selectedDeviceListeners.set(`Microphone`,r),this._deviceManager.on(`selectedMicrophoneChanged`,r),r()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}selectedDevice(e){return this._selectedDevices.get(e)}dispose(){let e=this._selectedDeviceListeners.get(`Speaker`);e&&this._deviceManager.off(`selectedSpeakerChanged`,e);let t=this._selectedDeviceListeners.get(`Microphone`);t&&this._deviceManager.off(`selectedMicrophoneChanged`,t),this._eventEmitter.removeAllListeners()}};function N7(e,t,n,r){let i=r===R2.RoomCall||e.kind===GG.Call&&e.direction==`Incoming`&&!e.tsCall.groupId&&!!e.tsCall.meetingData?.meetingCode&&!e.tsCall.threadId,a=!i&&r===R2.TeamsMeetingLink||r===R2.TeamsMeetingId||r===R2.TeamsCoordinates||e.direction==`Incoming`&&!e.tsCall.groupId&&!!e.tsCall.meetingData&&!!e.tsCall.threadId,o={audio:``,video:``},s=e.localAudioStreams?.[0];s&&(o.audio=s.getEffectsCurrentStateRecord()??``);let c=e.localVideoStreams?.[0];return c&&(o.video=c.getEffectsCurrentStateRecord()??``),{timestampInfo:{attemptTimestamp:+new Date},correlationId:n,localParticipantId:e.tsCall.participantId||``,isAcsTeamsCall:e.isAcsTeamsCall,callId:e.tsCall.callId||``,callType:e.tsCall.callType||``,callDirection:e.direction,state:e.state===`Ringing`?`Ringing`:$Ee[e.tsCall.state],groupJoin:!!e.tsCall.groupId,roomJoin:i,meetingJoin:a,callEndDiagnosticsInfo:e.tsCall.callEndDiagnosticsInfo||{},isSupportedEnvironment:t?.runningEnvironmentInfo?.isSupportedEnvironment,effectsStateInfo:o,hostRegion:e.tsCall.region||``,diagnosticInfo:{...e.tsCall.callEndDiagnosticsInfo,telemetryPayloadBytesOriginal:m3.telemetryPayloadBytesOriginal,telemetryPayloadBytesCompressed:m3.telemetryPayloadBytesCompressed}}}function P7(e,t,n){try{n.step===`state-changed`&&n.newState===`Connecting`&&(m3.telemetryPayloadBytesOriginal=0,m3.telemetryPayloadBytesCompressed=0),e.sendEvent({name:Q.acs_calling_call_progress,tenant:p2,properties:n})}catch{t.error(`Failed to send event: ${Q.acs_calling_call_progress} step: ${n.step}`)}}var ZIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},F7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},I7=class{get threadId(){return this._threadId}get roomId(){return this._roomId}get groupId(){return this._groupId}get participantId(){return this._tsCall.participantId}get isPstnInterop(){return this._isPstnInterop}get isTeamsInterop(){return this._isTeamsInterop}get callScenario(){if(this._tsCall.callQueueInfo)return y4.CallQueue;if(this.transferorKind!==`unknown`){if(this._tsCall.incomingCallType===`transfer`)return y4.TransferToParticipant;if(this._tsCall.incomingCallType===`replaces`)return y4.TransferToCall}return this.direction===`Incoming`?`AcceptCall`:this.direction===`Outgoing`&&this.context==`Rooms`?y4.JoinRoom:this.direction===`Outgoing`&&this.context==`TeamsMeeting`?y4.JoinTeamMeeting:this.direction===`Outgoing`&&this.context==`GroupIdCall`?y4.JoinWithGroupId:y4.PlaceCall}get context(){return this._tsCall.callType==1||this._currentCallContext==b4.TwoParty?b4.TwoParty:this._tsCall.groupId?b4.GroupIdCall:this._tsCall.conversationType==`groupCall`||this._currentCallContext==b4.MultiParty?b4.MultiParty:this._config?.roomId||this._roomId||this._tsCall.meetingData?.meetingCode?.startsWith(`994`)||this._tsCall.meetingData?.meetingCode?.startsWith(`995`)||this._tsCall.meetingData?.meetingCode?.startsWith(`996`)?b4.Rooms:this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.passcode||this._tsCall.conversationType==`scheduledMeeting`?b4.TeamsMeeting:(this._tsCall.callType,b4.MultiParty)}get transferorKind(){return this._tsCall.transferorMri?q2(this._tsCall.transferorMri||``).kind:``}get direction(){return this._config?.isIncoming?a4.Incoming:a4.Outgoing}get initiatorKind(){return q2(this._tsCall.callerMri?this._tsCall.callerMri:``).kind}get targetKind(){return this._tsCall.groupId?this._tsCall.groupId:this._config?.roomId?this._config.roomId:this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.meetingCode?`TeamsMeetingJoinLink`:this._tsCall.transferorMri?`Transferee`:this._tsCall.participants.length===1?q2(this._tsCall.participants[0].id).kind:this._tsCall.participants.filter((e=>e.id!==this._tsCall.callerMri)).map((e=>q2(e.id).kind)).toString()}constructor(e,t={}){this._tsCall=e,this._threadId=this._tsCall.threadId;let n=this._tsCall.groupId;this._groupId=!n||n.startsWith(`19:`)||n.startsWith(`99:`)?void 0:n,this._roomId=t?.config?.roomId,this._config=t.config,this._isPstnInterop=!1,this._isTeamsInterop=!1}setThreadId(e){this._threadId=e}initialize(e,t,n){this._logger=t,this._eventEmitter=e,this._threadId=this._tsCall.threadId,this._tsCallChangedListener=this._tsCall.changed((()=>this.threadIdChanged(this._tsCall))),this._p2pCallListener=this._tsCall.changed((()=>this.p2pCallHandler())),this._isPstnInterop=this.isPSTNUserInCall,this._isTeamsInterop=this.isTeamsUserInCall,this._participantUpdatedListener=this._tsCall.on(`participantCountsUpdated`,(()=>{this.interoperabilityChangeHandler(),this.p2pCallEscalationHandler()}))}async getServerCallId(){let e=JSON.parse(await this._tsCall.getJoinBlob())?.conversationUrl;if(!e)throw new Y({defaultError:J.CALL.GET_SERVER_CALL_ID});return xFe(e)}p2pCallHandler(){this._currentCallContext==null&&this._tsCall.callType==1&&(this._currentCallContext=b4.TwoParty)}p2pCallEscalationHandler(){this._currentCallContext==b4.TwoParty&&L4(this._tsCall)>2&&(this._currentCallContext=b4.MultiParty,this._eventEmitter.emit(`callInfoChanged`),this._p2pCallListener?.dispose())}get isTeamsUserInCall(){if(!this._tsCall.participants)return!1;for(let e of this._tsCall.participants)if(q2(e.id).kind===`microsoftTeamsUser`)return!0;return!1}get isPSTNUserInCall(){if(!this._tsCall.participants)return!1;for(let e of this._tsCall.participants)if(q2(e.id).kind===`phoneNumber`)return!0;return!1}interoperabilityChangeHandler(){!this._isPstnInterop&&this.isPSTNUserInCall&&(this._isPstnInterop=!0,this._eventEmitter.emit(`callInfoChanged`)),!this._isTeamsInterop&&this.isTeamsUserInCall&&(this._isTeamsInterop=!0,this._eventEmitter.emit(`callInfoChanged`))}threadIdChanged(e){this._tsCall.threadId!==this._threadId&&(this._logger.log(`threadId changed from ${this._threadId} to ${e?.threadId}`),this._threadId=this._tsCall.threadId,this._eventEmitter.emit(`threadIdChanged`))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}onCallInfoChanged(e,t){this._eventEmitter.on(e,t)}offCallInfoChanged(e,t){this._eventEmitter.off(e,t)}dispose(){this._tsCallChangedListener?.dispose(),this._eventEmitter.removeAllListeners(),this._p2pCallListener?.dispose(),this._participantUpdatedListener?.dispose()}};ZIe([YG(Owe.GetServerCallId),F7(`design:type`,Function),F7(`design:paramtypes`,[]),F7(`design:returntype`,Promise)],I7.prototype,`getServerCallId`,null);var QIe=class e{constructor(){this.CAUSE_ID_TO_NETWORK_INFO={}}static getInstance(){return this.instance||=new e,this.instance}deleteNetworkInfo(e){delete this.CAUSE_ID_TO_NETWORK_INFO[e]}ifCauseIdExistsRemoveNetworkInfo(e){return this.CAUSE_ID_TO_NETWORK_INFO[e]&&this.CAUSE_ID_TO_NETWORK_INFO[e].length===0?!!this.getRemoveCauseIdToNetworkInfo(e):!!this.CAUSE_ID_TO_NETWORK_INFO[e]}getRemoveCauseIdToNetworkInfo(e){if(!Z().telemetry.sendNetworkInfo)return;let t=this.CAUSE_ID_TO_NETWORK_INFO[e];return t&&this.deleteNetworkInfo(e),t}setCauseIdToNetworkInfo(e,t){Object.keys(this.CAUSE_ID_TO_NETWORK_INFO).length>100&&(this.CAUSE_ID_TO_NETWORK_INFO={}),t?this.CAUSE_ID_TO_NETWORK_INFO[e]?this.CAUSE_ID_TO_NETWORK_INFO[e].push({url:t.url,statusCode:t.statusCode,start:t.start,end:t.end,deltaTimeInMs:t.deltaTimeInMs,causeId:t.causeId}):this.CAUSE_ID_TO_NETWORK_INFO[e]=[{url:t.url,statusCode:t.statusCode,start:t.start,end:t.end,deltaTimeInMs:t.deltaTimeInMs,causeId:t.causeId}]:this.CAUSE_ID_TO_NETWORK_INFO[e]=[]}};QIe.instance=null;var L7=QIe.getInstance(),$Ie=class e{constructor(e,t,n,r){this._recordingConsentEnabled=!1,this._consentActivelyRequired=!1,this._localParticipantConsentPublishState=!1,this._isExplicitConsentEnabled=!1,this._isInitialized=!1,this._isExplicitConsentEnabled=Z().calling.explicitConsentFeatureEnabled.enabled,this.initialize(e,t,n,r)}dispose(){this._isInitialized=!1,this._recordingConsentEnabled=!1,this._consentActivelyRequired=!1,this._localParticipantConsentPublishState=!1,e.instance=null}isConsentRequiredInCall(){if(!this._isExplicitConsentEnabled)return!1;let e=this._recordingConsentEnabled&&!this._localParticipantConsentPublishState;return this._logger.info(`ExplicitConsentCallStateManager: isConsentRequiredInCall: Recording Consent Enabled: `+this._recordingConsentEnabled+` Local Participant Consent Publish State: `+this._localParticipantConsentPublishState),this._logger.log(`ExplicitConsentCallStateManager: isConsentRequiredInCall: `+e),e}async consent(e){if(this._isExplicitConsentEnabled){if(e.context===b4.TwoParty)throw this._logger.warn(`Consent for recording is not supported for 1:1 calls`),new Y({defaultError:J.CALL.CONSENT_NOT_SUPPORTED_1TO1});if(!this.isConsentRequiredInCall())throw new Y({defaultError:J.CALL.CONSENT_ALREADY_SET_OR_NOT_REQUIRED});try{if(!await this._tsCall.publishState({level:`user`,type:`consentToRecording`,content:`{}`},PG()))throw this._logger.error(`Consent failure to set publish state for user`),new Y({defaultError:J.CALL.FAILED_TO_SET_CONSENT});this._logger.log(`ExplicitConsentCallStateManager: Consent for the call provided successfully`)}catch(e){throw this._logger.error(`Consent failure to set publish state for user on service side`),e}}}areCoreCapabilitiesConsentRestricted(){if(!this._isExplicitConsentEnabled)return!1;let e=this._consentActivelyRequired&&!this._localParticipantConsentPublishState;return this._logger.info(`ExplicitConsentCallStateManager: areCoreCapabilitiesConsentRestricted: Consent Actively Required: `+this._consentActivelyRequired+` Local Participant Consent Publish State: `+this._localParticipantConsentPublishState),this._logger.log(`ExplicitConsentCallStateManager: areCoreCapabilitiesConsentRestricted: `+e),e}offConsentRestrictionChanged(e,t){if(e!==`consentRestrictionChanged`)throw Error(`ExplicitConsentCallStateManager: OffConsentRestrictionChanged - Invalid event`);this._logger.log(`ExplicitConsentCallStateManager: Unsubscribing to consentRestrictionChanged event`),this._eventEmitter.off(e,t)}onConsentRestrictionChanged(e,t){if(e!==`consentRestrictionChanged`)throw Error(`ExplicitConsentCallStateManager: onConsentRestrictionChanged - Invalid event`);this._logger.log(`ExplicitConsentCallStateManager: Subscribing to consentRestrictionChanged event`),this._eventEmitter.on(e,t)}initialize(e,t,n,r){this._isExplicitConsentEnabled&&(this._isInitialized||=(this._logger=r.createChild((()=>`Explicit Consent::Call(id='${e.callId}', state='${e.state}')`)),this._tsCall=e,this._callAgent=t,this._eventEmitter=n,e.changed((()=>{if(!0===e.meetingDetails?.recordingConsentDetails?.explicitRecordingConsentEnabled){this._recordingConsentEnabled=!0;let t=!0===e.meetingDetails?.recordingConsentDetails?.consentActivelyRequired;t!==this._consentActivelyRequired&&(this._consentActivelyRequired=t,this._eventEmitter.emit(`consentRestrictionChanged`))}})),e.on(`publishedStatesChanged`,(async e=>{this._localParticipantConsentPublishState=!1,this._handleConsentStateChange(e)})),!0))}_handleConsentStateChange(e){if(!0!==this._localParticipantConsentPublishState){let n=this._callAgent.getUserMri();var t=!1;e&&this._getPublishedState(e).forEach((e=>{e.participantStates.forEach((e=>{if(e.id===n)return this._logger.log(`ExplicitConsentCallStateManager: Handle Consent State changes: Local participant has provided the consent`),void(t=!0)}))})),this._localParticipantConsentPublishState=t,t&&this._eventEmitter.emit(`consentRestrictionChanged`)}}_getPublishedState(e){return e.typeStates.filter((e=>[`consentToRecording`].includes(e.type)))}};$Ie.instance=null;var eLe=class{constructor(e,t){this._interval=0,this._ufds=new Map,this._interval=t,e.forEach((e=>{this._ufds.set(e,{_lastRecovered:new Date,_shouldNotifyError:!0,_shouldNotifyRecovery:!0})}))}updateLastRecoveredTime(e,t){let n=this._ufds.get(e);n&&(n._lastRecovered=new Date(t.getTime()+this._interval),n._shouldNotifyError=!0,n._shouldNotifyRecovery=!1)}shouldLogError(e,t){let n=this._ufds.get(e);if(n){let e=n._lastRecovered<=t&&n._shouldNotifyError;return e&&(n._shouldNotifyError=!1,n._shouldNotifyRecovery=!0),e}return!0}shouldLogRecovery(e,t){let n=this._ufds.get(e);if(n){let r=n._shouldNotifyRecovery;return r&&this.updateLastRecoveredTime(e,t),r}return!0}},tLe,R7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},z7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},B7=class e{get id(){return this._id}get callerInfo(){return{identifier:this._callerIdentity,displayName:this._callerDisplayName}}get transferorInfo(){if(this._transferorIdentity)return{identifier:this._transferorIdentity,displayName:this._transferorDisplayName}}get state(){return this._state}get role(){return this._role}get callEndReason(){return this._callEndReason}get kind(){return this._kind}get direction(){return this._direction}get isMuted(){return this._isMuted}get isScreenSharingOn(){return this._isScreenSharingOn}get isLocalVideoStarted(){return this._isLocalVideoStarted}get localVideoStreams(){return this._localVideoStreams}get localAudioStreams(){return this._localAudioStreams}get isIncomingAudioMuted(){return this._isIncomingAudioMuted}get remoteParticipants(){return this._remoteParticipants}get totalParticipantCount(){return this._totalParticipantCount}get lobby(){return this._lobby}get isAcsTeamsCall(){return this._isAcsTeamsCall}get isIPAudioEnabled(){return this.callInfo.context===b4.TwoParty||this._allowIPAudio}get isIPVideoEnabled(){return this.callInfo.context===b4.TwoParty||this._allowIPVideo}get isEnterpriseTeamsCall(){return this._isEnterpriseTeamsCall}subscribeToGetRemoteAudioStream(){if(!this._rawAudioStreamChangedSubscription)try{let e=this.tsCall.getIncomingRawAudioStream(),t=async()=>{try{if(this._remoteAudioStreams.length===0){if(!await e.getMediaStream())throw new Y({defaultError:J.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_UNDEFINED});this._remoteAudioStreams.push(new hIe(e,this._telemetryLogManager,this.id,this.tsCall.participantId)),this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:this._remoteAudioStreams,removed:[]})}else if(await e.getMediaStream())this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:[],removed:[]});else{let e=this._remoteAudioStreams[0];e.dispose(),this._remoteAudioStreams=[],this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:[],removed:[e]})}}catch(e){throw new Y({defaultError:J.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_RETURNED_ERROR,originalError:e})}};this._rawAudioStreamChangedSubscription=e.changed((()=>{this.logger.info(`Changed fired ${this.tsCall.state}, ${this.state}`),t().catch(M4)})),t().catch((()=>{this.logger.info(`Failed to update remote audio stream collection, retrying on changed`)}))}catch{this.logger.info(`Failed to get raw audio stream from the stack`)}}get remoteAudioStreams(){if(!Z().calling.allowAccessRawMediaStream)throw new Y({defaultError:J.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_DISABLED});return this._remoteAudioStreams}get deviceManager(){return this._callAgent.deviceManager}get mediaConstraintsManager(){return this._mediaConstraintsManager}get isHandlingLargeMeetingVideoRendering(){return this._isHandlingLargeMeetingVideoRendering}get callInfo(){return this._callInfo}get networkQualityUfdEventDetails(){return this._networkQualityUfdEventDetails}get acsProxy(){return this._callAgent.acsProxy}get acsCustomRelayManager(){return this._callAgent.acsCustomRelayManager}get audioEffectsProcessorStats(){return this._audioEffectsProcessorStats}get callAgent(){return this._callAgent}get iceServers(){return this._getIceServersCalledOnce||(this._getIceServersCalledOnce=!0,this._iceServers=this.tsCall.getMediaSessionStats()?.extensions?.IceServers),this._iceServers}get watermarkAudioOnlyFallbackTriggered(){return this._watermarkAudioOnlyFallbackTriggered}constructor(e,t,n,r,i,a){this._callAgent=t,this._isMuted=!1,this._isMuted_correlationIdCache=J0(),this._isIncomingAudioMuted=!1,this._isIncomingAudioMuted_correlationIdCache=J0(),this._isScreenSharingOn=!1,this._isLocalVideoStarted=!1,this._localVideoStreams=[],this._localAudioStreams=[],this._remoteAudioStreams=[],this._totalParticipantCount=1,this._isDeviceNotFunctioningMuted=!1,this.__attemptedToRecoverMicNotFunctioningBySDK=!1,this._isMicrophoneMuted=!1,this._disposed=!1,this._lastTsCallState=0,this._isSpeakerMuted=!1,this._callMode=0,this._role=E2,this._lastTsCallMeetingDetails={},this._isHandlingLargeMeetingVideoRendering=!1,this._joinContextDescription=R2.Unknown,this._remoteParticipantsChangedListeners=[],this._localRingingStateSet=!1,this._networkQualityUfdEventDetails=[],this._audioEffectsProcessorStats=null,this._getIceServersCalledOnce=!1,this._watermarkAudioOnlyFallbackTriggered=!1,this._transportStateTimestamp=new Map,this._setOrUpdateDeviceEventsTask=Promise.resolve(),this._isAcsTeamsCall=!1,this._isEnterpriseTeamsCall=this._callAgent.isEnterpriseUser(),this._isTeamsExtensionUser=this._callAgent.isTeamsExtensionUser(),this._mriToRemoteParticipantMap=new Map,this._remoteParticipants=[],this._state=`None`,this._transportState=`None`,this._allowIPAudio=!0,this._allowIPVideo=!0,this.localVideoStream=void 0,this.localScreenSharingStream=void 0,this.isRenderingRemoteScreenShare=!1,this._handleMuteChanges=()=>{let e=[b4.Rooms,b4.GroupIdCall,b4.MultiParty,b4.TeamsMeeting].some((e=>e===this._callInfo.context)),t=this.tsCall.conversationType||e?!!(this.tsCall.isMuted||this.tsCall.state!==10&&this.tsCall.isServerMuted||this._isDeviceNotFunctioningMuted):!(!this.tsCall.isMuted&&!this._isDeviceNotFunctioningMuted);if(this._isMuted!=t){this.logger.info(`isMuted changed from ${this._isMuted} to ${t}`);let e=[];this.tsCall.isMuted&&e.push(`isMicrophoneMuted`),this.tsCall.isServerMuted&&(e.push(`isServerMuted`),[3,4,5].some((e=>e===this.tsCall.state))&&this._eventEmitter.emit(`mutedByOthers`),this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()&&this.handleConsentCapabilitiesChanges()),this._isDeviceNotFunctioningMuted&&e.push(`isDeviceNotFunctioningMuted`);let n=``;e.length>=1&&(n=e.join(`, `)),t&&(this._isMuted_correlationIdCache=J0()),P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,this._isMuted_correlationIdCache,this._joinContextDescription),step:`isMuted-changed`,oldIsMuted:this._isMuted,newIsMuted:t,reason:n}),this._isMuted=t,this._eventEmitter.emit(`isMutedChanged`)}},this.audioSourceChanged=async e=>{this._telemetryLogManager.sendEvent({name:Q.acs_calling_local_audio_source_changed,tenant:p2,properties:{callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:+new Date,correlationId:J0(),localAudioStream:e.source?.source instanceof MediaStream?`MediaStream`:`Device`}}),e.source instanceof Z6?(this.localAudioStreams[0]&&this.localAudioStreams[0].mediaStreamType===`RawMedia`&&this.stopAudioInternal(!0),await(await this._callAgent.tsStack?.getDeviceManagerAsync?.())?.selectDevicesAsync?.({microphone:e.source.id})):await this.startAudioInternal(e.source,!0)},this._handleIncomingAudioMuteChanges=()=>{let e=this._isSpeakerMuted;this._isIncomingAudioMuted!=e&&(this.logger.info(`newIncomingAudioMuted changed from ${this._isIncomingAudioMuted} to ${e}`),e&&(this._isIncomingAudioMuted_correlationIdCache=J0()),P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,this._isIncomingAudioMuted_correlationIdCache,this._joinContextDescription),step:`isIncomingAudioMuted-changed`,oldIsMuted:this._isIncomingAudioMuted,newIsMuted:e,reason:``}),this._isIncomingAudioMuted=e,this._eventEmitter.emit(`isIncomingAudioMutedChanged`))},this._id=e.callId,this.tsCall=n,this._direction=e.isIncoming?`Incoming`:`Outgoing`,this._config=e,this.logger=this._callAgent.logger.createChild((()=>`Call:${this._id}:${this._state}`)),this._telemetryLogManager=r,this.stats=new dIe(this.logger,this._telemetryLogManager),this._eventEmitter=new w6(this.logger),this.activeRemoteVideoStreamViews=new Map,this.isSubscribedCall=!1,this.isBreakoutRoomCall=!1,this._mediaMetricsDeviceEvents={},this._kind=i,this._optimalVideoCount=1,this._ufdsCorrelationIdCache=dTe(),this._callInfo=new I7(n,{config:e}),this._callInfo.initialize(this._eventEmitter,this.logger,this._telemetryLogManager),this._ufdLogThrottler=new eLe([27],Z().telemetry.speakingWhileMutedThrottleInterval),Z().calling.mediaMetricsDeviceEventsEnabled&&(async()=>{let e=await this._callAgent.tsStack?.getDeviceManagerAsync?.();e&&(this._dmDevicesChangedSub=e.on(`devicesChanged`,(()=>{this._setOrUpdateDeviceEventsTask=this._setOrUpdateDeviceEventsTask.then((()=>this.setOrUpdateMediaMetricsDeviceEvents().catch(M4)))})))})().catch((e=>{this.logger.error(`Failed to register devicesChanged event: ${e}`)})),this._extensibleApi=new F3(this.logger,{call:this,callAgent:this._callAgent,callInfo:this._callInfo},{tsCall:this.tsCall,callAgent:this._callAgent,call:this,telemetryLogManager:this._telemetryLogManager}),this.explicitConsentStateImp=new $Ie(this.tsCall,t,this._eventEmitter,this.logger),this._capabilityResolver=new CDe(this._eventEmitter,this.logger,this,this._callInfo,t,n),this._lobby=new i7(this.tsCall,this,this.logger,this._telemetryLogManager);let o=e7(k3.CallFeature);for(let e of o)e.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(e);this._mmrRdpConnectionManager=new bIe(this.logger),Z().telemetry.sendNetworkChangedTelemetry&&this._sendNetworkChangedTelemetry(),Z().telemetry.deviceChangedEvents.enabled&&(this._selectedDeviceManager=new XIe(this.deviceManager),this._setupSelectedDeviceChangedTelemetry()),this._mediaConstraintsManager=new vIe(this.tsCall,this.logger,this._telemetryLogManager),this._isAcsTeamsCall=a??!1,this.feature($5.MediaAccess).on(`localParticipantMediaAccessChanged`,(e=>{this.logger.info(`Call common, time when received localParticipantMediaAccessChanged event: ${new Date().getTime()}, isAudioPermitted=${e.mediaAccess.isAudioPermitted}, isVideoPermitted=${e.mediaAccess.isVideoPermitted}`),!1===e.mediaAccess.isVideoPermitted&&this.localVideoStream&&this.stopVideo(this.localVideoStream)})),this.explicitConsentStateImp.onConsentRestrictionChanged(`consentRestrictionChanged`,(()=>{this.logger.info(`Call common, time when received explicitConsentStateChanged event:=\n ${this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()}`),this.handleConsentCapabilitiesChanges()}))}async accept(e={}){let t=e.audioOptions?.muted??!1,n=this.getLocalVideoStreamFromCallOptions(e),r=this.getLocalAudioStreamFromCallOptions(e),i=+new Date,a=this._callAgent.getEcsConfigIds(),o=fTe(this.tsCall),s=J0(),c=FG(s),l=this.createVideoNegotiationTag(s,`Video`),u={joinContextDescription:``,additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this._isEmergencyCall,trouterState:this._callAgent.getTrouterState(),muted:t,withVideo:this.isIPVideoEnabled&&!!n,withAudio:this.isIPAudioEnabled&&r?.mediaStreamType?r?.mediaStreamType:``,...a7(),AcsCallingSDKWeb_ecsConfigId:a.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:a.SkypeWebMedia,customContext:{userToUserPresent:!!o?.userToUser,xHeadersPresent:!!o?.xHeaders&&o.xHeaders.length>0},mediaModalities:this.getMediaModalityTelemetry(e?.mediaModalities),negotiationTag:l,causeId:c},additionalDetails:{}},d=(e,t,a)=>{let o=+new Date,d={...u},f;if(t){let t={message:J.CALL.ACCEPT_INCOMING_CALL.message,code:J.CALL.ACCEPT_INCOMING_CALL.code,subCode:J.CALL.ACCEPT_INCOMING_CALL.subCode,resultCategories:J.CALL.ACCEPT_INCOMING_CALL.resultCategories},{callEndReason:n,callingCommunicationError:r,hasDiagnosticsInfo:i}=U3(this,e,t);i?d.additionalDetails.callEndReason=n:d.additionalDetails.communicationServicesError=J3(r).communicationServicesError,f=r}else f=new Y({defaultError:J.CALL.ACCEPT_INCOMING_CALL,originalError:e}),d.additionalDetails.communicationServicesError=J3(f).communicationServicesError;if(this.sendCallStageEvent({eventName:Q.acs_calling_call_accept_failed,correlationId:s,timestampInfo:{deltaTimeInMs:o-i},additionalPayload:d},f,void 0,a?L7.getRemoveCauseIdToNetworkInfo(a):void 0),n){let e=+new Date;f=new Y({defaultError:J.LOCAL_VIDEO_STREAM.CALL_NOT_FOUND}),this.logger.error(f.message),this.sendVideoEvent({correlationId:s,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:e-i},localVideoStream:n,step:`accept`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:l,causeId:c}},f),this.removeLocalVideoStream(n)}return r&&this.removeLocalAudioStream(r),f};try{if(e?.videoOptions?.constraints){let t=this._mediaConstraintsManager.getTelemetryPayload({video:e?.videoOptions?.constraints});u.additionalProperties.constraints=t}u.additionalProperties.negotiationTag=l,u.additionalProperties.causeId=c,this.sendCallStageEvent({eventName:Q.acs_calling_call_accept_attempt,correlationId:s,timestampInfo:{attemptTimestamp:i},additionalPayload:u});let a={...u};if(n&&this.setLocalVideoStream(n),this.setLocalAudioStream(r),n&&this.sendVideoEvent({eventName:Q.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:i},correlationId:s,step:`accept`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:l,causeId:c}}),this.tsCall.state!==1)throw new Y({defaultError:J.CALL.ACCEPT_NOT_RINGING});try{if(e?.videoOptions?.constraints){let t=await this._mediaConstraintsManager.setVideoConstraints(e?.videoOptions?.constraints,`accept`,s,i),n=this._mediaConstraintsManager.getTelemetryPayload({video:t});a.additionalProperties.constraints=n}}catch(e){let t=new Y({defaultError:J.CALL.ACCEPT_VIDEO_CONSTRAINTS,originalError:e});this.logger.error(`${t.message}`)}let o={withVideo:!!n&&this.isIPVideoEnabled,muted:t};if(t&&(o.muteFlags=1),o.sendMediaModalities=this.setMediaModalities(e?.mediaModalities),Z()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(o.mediaConfiguration={connectionType:`NoDirectConnection`}),r&&await this.startAudioInternal(r,!0).catch((e=>{this.logger.error(`Failed to start localAudioStream, message=${e?.message}`)})),n?.mediaStreamType===`RawMedia`)try{await this._setRawStream(n,1)}catch(e){let t=+new Date,r=new Y({defaultError:J.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:e});this.sendVideoEvent({correlationId:s,eventName:Q.acs_calling_media_stream,timestampInfo:{deltaTimeInMs:t-i},localVideoStream:n,step:`accept`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:l,causeId:c}},r),this.removeLocalVideoStream(n)}let f=PG();return L7.setCauseIdToNetworkInfo(f),this.tsCall.accept(o,f).then((async()=>{let e=+new Date;n&&this.shallRemoveLvsAfterConnectedSuccessfully(n,`accept`,s,e,i,l,c),r&&this.shallRemoveLasAfterConnectedSuccessfully(r,`accept`,s,e,i),a.additionalProperties.negotiationTag=l,a.additionalProperties.causeId=c,this.sendCallStageEvent({eventName:Q.acs_calling_call_accept_connected,correlationId:s,timestampInfo:{deltaTimeInMs:e-i},additionalPayload:a},void 0,void 0,L7.getRemoveCauseIdToNetworkInfo(f))})).catch((e=>{d(e,!0,f)})),this}catch(e){throw d(e,!1)}}async reject(){let e=+new Date,t=J0();this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_attempt,correlationId:t,timestampInfo:{attemptTimestamp:e}});let n=this._callAgent.getEcsConfigIds(),r={additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this._isEmergencyCall,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:n.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:n.SkypeWebMedia},additionalDetails:{}};if(this.tsCall.state!==1){let n=new Y({defaultError:J.CALL.REJECT_NOT_RINGING});r.additionalDetails.communicationServicesError=J3(n).communicationServicesError;let i=+new Date;throw this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_failed,correlationId:t,timestampInfo:{deltaTimeInMs:i-e},additionalPayload:r},n),n}let i=PG();return L7.setCauseIdToNetworkInfo(i),this.tsCall.reject(i).then((()=>{let n=+new Date;this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_success,correlationId:t,timestampInfo:{deltaTimeInMs:n-e}},void 0,void 0,L7.getRemoveCauseIdToNetworkInfo(i))})).catch((n=>{let a=+new Date,o={message:J.CALL.REJECT_CALL_FAILED.message,code:J.CALL.REJECT_CALL_FAILED.code,subCode:J.CALL.REJECT_CALL_FAILED.subCode,resultCategories:J.CALL.REJECT_CALL_FAILED.resultCategories},{callEndReason:s,callingCommunicationError:c,hasDiagnosticsInfo:l}=U3(this,n,o);throw l?r.additionalDetails.callEndReason=s:r.additionalDetails.communicationServicesError=J3(c).communicationServicesError,this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_failed,correlationId:t,timestampInfo:{deltaTimeInMs:a-e},additionalPayload:r},c,void 0,L7.getRemoveCauseIdToNetworkInfo(i)),c}))}dispose(){this._disposed||=(this._dmDevicesChangedSub&&this._dmDevicesChangedSub.dispose(),this._dmDevicesChangedSub=void 0,this._extensibleApi.dispose(),this._eventEmitter.removeAllListeners(),this._onlineListener&&window.removeEventListener(`online`,this._onlineListener),this._offlineListener&&window.removeEventListener(`offline`,this._offlineListener),this._trouterStateChangedListener&&this._callAgent.offTrouterStateChanged(this._trouterStateChangedListener),this._mmrRdpConnectionManager.dispose(),this._selectedDeviceManager?.dispose(),this.explicitConsentStateImp.dispose(),!0)}async startAudioInternal(e,t=!1){let n=J0(),r=+new Date,i=PG();L7.setCauseIdToNetworkInfo(i);try{if(this.isInternalApiCallWithoutRawMedia(e,t))return;this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.attempt,isInternal:t,timestampInfo:``,additionalDetails:``}),this.validateRawMedia(e,J.CALL.START_AUDIO_LAS_NOT_RAW_MEDIA),this._userProvidedLocalAudioStreamCache=e;let a=await this.createMediaStream(e),o=await this._callAgent.tsStack?.getDeviceManagerAsync?.();if(!Z()?.calling?.allowAccessRawMediaStream||!o?.setRawMediaStream)throw new Y({defaultError:J.CALL.LOCAL_AUDIO_SET_MEDIA_STREAM});o?.setRawMediaStream(a,0),this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream(e);let s=+new Date;this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.success,isInternal:t,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:s-r},additionalDetails:{networkInfo:L7.getRemoveCauseIdToNetworkInfo(i)}})}catch(e){let a=new Y({defaultError:J.CALL.START_AUDIO_STREAM_FAILED,originalError:e});this.logger.error(`Failed to start raw media audio: ${a.message}`);let o=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,isInternal:t,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-r},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...J3(a),networkInfo:L7.getRemoveCauseIdToNetworkInfo(i)}}),a}}isInternalApiCallWithoutRawMedia(e,t){return!(e?.mediaStreamType===`RawMedia`||!t)&&(this.logger.info(`startAudioInternal internal call: LocalAudioStream media type is raw media, skipping raw audio startAudioInternal`),!0)}validateRawMedia(e,t){if(e?.mediaStreamType!==`RawMedia`)throw new Y({defaultError:t})}async createMediaStream(e){let t;try{t=await e.getMediaStream()}catch(e){throw new Y({defaultError:J.CALL.LOCAL_AUDIO_GET_MEDIA_STREAM,originalError:e})}return new MediaStream(t)}stopAudioInternal(e=!1){let t=J0(),n=+new Date,r=PG();L7.setCauseIdToNetworkInfo(r);try{let i=this._localAudioStreams[0];if(this.isInternalApiCallWithoutRawMedia(i,e))return;this.sendRawMediaEvent({eventName:Q.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:$.attempt,isInternal:e,timestampInfo:``,additionalDetails:``}),e||t7(c4.StopAudio,this.state),this.validateRawMedia(i,J.CALL.STOP_AUDIO_LAS_NOT_RAW_MEDIA);let a=this._callAgent.tsStack?.getDeviceManager();if(!Z()?.calling?.allowAccessRawMediaStream||!a?.unsetRawMediaStream)throw new Y({defaultError:J.CALL.LOCAL_AUDIO_UNSET_MEDIA_STREAM});a.unsetRawMediaStream(0),this._userProvidedLocalAudioStreamCache=void 0,this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream();let o=+new Date;this.sendRawMediaEvent({eventName:Q.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:$.success,isInternal:e,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{networkInfo:L7.getRemoveCauseIdToNetworkInfo(r)}})}catch(i){let a=new Y({defaultError:J.CALL.STOP_AUDIO_STREAM_FAILED,originalError:i});this.logger.error(`Failed to stop raw media audio: ${a.message}`);let o=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,isInternal:e,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...J3(a),networkInfo:L7.getRemoveCauseIdToNetworkInfo(r)}}),a}}bindTsCall(){let e=[];this.tsCall.callerMri!==void 0&&(this._callerIdentity=q2(this.tsCall.callerMri),this._callerDisplayName=this.tsCall.participants.find((e=>e.id===this.tsCall.callerMri))?.displayName),this._lastTsCallState=this.tsCall.state,this.mapTsCallState(this.tsCall.state),this._setCallRole(this.tsCall.advancedMeetingRole),this.tsCall.callQueueInfo?(this._callerIdentity=q2(this.tsCall.callQueueInfo.onBehalfOf.id),this._callerDisplayName=this.tsCall.callQueueInfo.onBehalfOf.displayName?this.tsCall.callQueueInfo.onBehalfOf.displayName:this.tsCall.participants.find((e=>e.id===this.tsCall.callQueueInfo?.details.id))?.displayName,this._transferorIdentity=q2(this.tsCall.callQueueInfo.details.id),this._transferorDisplayName=this.tsCall.callQueueInfo.details.displayName?this.tsCall.callQueueInfo.details.displayName:this.tsCall.participants.find((e=>e.id===this.tsCall.callQueueInfo?.details.id))?.displayName):this.tsCall.transferorMri&&(this._transferorIdentity=q2(this.tsCall.transferorMri),this._transferorDisplayName=this.tsCall.transferorDisplayName),this.updateCallMode(),e.push(this.tsCall.changed((()=>{this.tsCall.callId!==this._id&&(this.logger.log(`tsCall callId changed from ${this._id} to ${this.tsCall.callId}`),P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`id-changed`,isAcsTeamsCall:this.isAcsTeamsCall,oldCallId:this._id,newCallId:this.tsCall.callId}),this._id=this.tsCall.callId,this._eventEmitter.emit(`idChanged`)),this.tsCall.state!==this._lastTsCallState&&(this.logger.log(`tsCall state changed=${this.tsCall.state}`),this._lastTsCallState=this.tsCall.state,this.mapTsCallState(this.tsCall.state),this._handleMuteChanges()),this._isScreenSharingOn!==this.tsCall.isScreenSharingOn&&(this.logger.log(`tsCall isScreenSharingOn changed=${this.tsCall.isScreenSharingOn}`),this._isScreenSharingOn=this.tsCall.isScreenSharingOn,this._isScreenSharingOn||this.removeScreenSharingStream(),this._eventEmitter.emit(`isScreenSharingOnChanged`)),this._isMicrophoneMuted!==this.tsCall.isMuted&&(this.logger.log(`tsCall isMuted changed=${this.tsCall.isMuted}`),this._isMicrophoneMuted=this.tsCall.isMuted,this._handleMuteChanges()),this._isSpeakerMuted!==this.tsCall.isSpeakerMuted&&(this.logger.log(`tsCall _isSpeakerMuted changed=${this.tsCall.isSpeakerMuted}`),this._isSpeakerMuted=this.tsCall.isSpeakerMuted,this._handleIncomingAudioMuteChanges()),this.tsCall.advancedMeetingRole!==this._lastTsCallAdvancedMeetingRole&&(this.logger.log(`tsCall advancedMeetingRole changed=${this.tsCall.advancedMeetingRole}`),this._setCallRole(this.tsCall.advancedMeetingRole)),(this.tsCall.meetingData?.meetingUrl||this.tsCall.meetingData?.passcode||this.tsCall.conversationType==`scheduledMeeting`)&&this.tsCall.meetingDetails&&aTe(this.tsCall.meetingDetails,this._lastTsCallMeetingDetails)&&this._setMeetingCapabilities(this.tsCall.meetingDetails),this.updateCallMode()}))),e.push(this.tsCall.on(`optimalVideoReceiversCountChanged`,this.optimalVideoCountChanged)),e.push(this.tsCall.on(`serverMutedChanged`,(()=>{this.logger.log(`tsCall isServerMuted changed=${this.tsCall.isServerMuted}`),this._handleMuteChanges()}))),this._totalParticipantCount=L4(this.tsCall),e.push(this.tsCall.on(`participantCountsUpdated`,(()=>{let e=L4(this.tsCall);if(this._totalParticipantCount!==e){let t=this._totalParticipantCount;this._totalParticipantCount=e,this.logger.log(`tsCall totalParticipantCount changed from ${t} to ${this._totalParticipantCount}`),Z().rendering.remoteVideo.largeMeeting.handleVideoRendering&&this._enableOrDisable_largeMeeting_videoRendering(),this._eventEmitter.emit(`totalParticipantCountChanged`);try{this.stats.recordEvent({name:l3.number_of_participants,callId:this.id,localParticipantId:this.tsCall.participantId,data:{totalParticipantCount:this._totalParticipantCount,participantCounts:this.tsCall.participantCounts||{},previousParticipantCount:t}})}catch{this.logger.error(`failed to send participant count change telemetry`)}}})));let t=(e,t)=>{if(e!==t){this.logger.log(`transportState changed from ${this._transportState} to ${t}`);let n=this._transportStateTimestamp.get(`Connected`)===void 0?this._connectedTimestamp:void 0;this._transportStateTimestamp.delete(t);let r=e4.omitBy({connectedTimetamp:n,transportConnectedTimestamp:this._transportStateTimestamp.get(`Connected`),transportDisconnectedTimestamp:this._transportStateTimestamp.get(`Disconnected`),transportFailedTimestamp:this._transportStateTimestamp.get(`Failed`)},e4.isUndefined),i=e4.merge(N7(this,this._callAgent,J0(),this._joinContextDescription),{timestampInfo:r});P7(this._telemetryLogManager,this.logger,{...i,step:`transportState-changed`,oldState:e,newState:t}),this._transportStateTimestamp.set(t,Date.now()),this._transportState=t}};e.push(this.tsCall.on(`transportConnected`,(()=>{t(this._transportState,`Connected`)}))),e.push(this.tsCall.on(`transportDisconnected`,(()=>{t(this._transportState,`Disconnected`)}))),e.push(this.tsCall.on(`transportFailed`,(()=>{t(this._transportState,`Failed`)}))),e.push(this.tsCall.on(`callQualityChanged`,(async e=>{try{let t;e.type===5||e.type===32||e.type===2||e.type===1||e.type===37?(t=l3.network_quality,this._trackNetworkQualityUfdEventDetails(e.type)):t=e.type===44||e.type===43||e.type===9||e.type===25||e.type===45||e.type===33||e.type===34||e.type===55||e.type===26||e.type===47||e.type===27?l3.video_device_issue:l3.other_diagnostic,e.value===3||e.value===2?(this._ufdLogThrottler.shouldLogError(e.type,new Date)&&this.logger.warn(`Ufd error raised!, ufd=${e.type}, value=${e.value}, kind=${t}`),t===l3.network_quality&&window.dispatchEvent(new CustomEvent(`online`,{detail:!1}))):(this._ufdLogThrottler.shouldLogRecovery(e.type,new Date)&&this.logger.warn(`Ufd error recovered!, ufd=${e.type}, value=${e.value}, kind=${t}`),t===l3.network_quality&&window.dispatchEvent(new CustomEvent(`online`,{detail:!0})));let n=``,r=this._ufdsCorrelationIdCache[e.type][e.mediaType];e.value==3||e.value==2?r?n=r:(n=J0(),this._ufdsCorrelationIdCache[e.type][e.mediaType]=n):(r&&(n=r),this._ufdsCorrelationIdCache[e.type][e.mediaType]=void 0);let i={type:e.type.toString(),level:e.value,mediaType:e.mediaType,correlationId:n};if(this.stats.recordEvent({name:t,callId:this.id,localParticipantId:this.tsCall.participantId,data:i}),this.shallStopVideo(e)){let t=+new Date,n=J0();this.logger.warn(`Attempting to stop video gracefully due to video ufd being raised.UFD: ${e.type}, value: ${e.value}, call direction: ${this._direction}`),this.sendAudioEvent({eventName:Q.acs_calling_stop_video_on_ufd_attempt,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{this.localVideoStream&&this.stopVideo(this.localVideoStream)}catch{let t=`Failed to stop video on video device start failed or capture mute event ${e.type} with value ${e.value}`;this.logger.error(t)}}if(this.shallRemoveLocalVideoStreamOnBadUfd(e)){let t=new Y({defaultError:J.CALL.REMOVE_LOCAL_VIDEO_ON_BAD_UFD,defaultErrorMessageArgs:[e.type,e.value,this._direction]});if(this.localVideoStream){let e=FG(n),r=this.createVideoNegotiationTag(n,`Video`);this.sendVideoEvent({eventName:Q.acs_calling_start_video_failure,correlationId:J0(),timestampInfo:{attemptTimestamp:+new Date},step:`start`,additionalDetails:{...J3(t),negotiationTag:r,causeId:e},localVideoStream:this.localVideoStream,isScreenSharingOnFlag:this.isScreenSharingOn},t),this.removeLocalVideoStream(this.localVideoStream)}this.logger.error(t.message)}if(this.shallStopAudio(e)){let t=+new Date,n=J0();if(Z()?.calling?.allowMuteOnBadUfd&&!this.tsCall.isMuted){this.sendAudioEvent({eventName:Q.acs_calling_mute_on_ufd_attempt,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.mute()}catch{let t=`Failed to mute on microphone device not functioning or capture mute event ${e.type} with value ${e.value}`;this.logger.error(t)}}if(Z()?.calling?.preventStopAudio)return this.sendAudioEvent({eventName:Q.acs_calling_prevent_stop_audio,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`}),void(!Z()?.calling?.preventFakeMute&&this.markCallMuted());this.sendAudioEvent({eventName:Q.acs_calling_stop_audio_attempt,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.tsCall.stopAudio(),this.markCallMuted();let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_stop_audio_success,timestampInfo:{deltaTimeInMs:e-t},correlationId:n,step:`mid-call`})}catch(r){let i=new Y({defaultError:J.CALL.STOP_AUDIO_ON_BAD_UFD,defaultErrorMessageArgs:[e.type,e.value],originalError:r});this.logger.error(i.message);let a=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_stop_audio_failure,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`},i)}}this.muteUnmuteOnMicrophoneNotFunctioningUfd(e),this.audioDidAutoRecover(e)&&(this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges())}catch{this.logger.error(`Failed to send ufd telemetry`)}}))),e.push(this.tsCall.on(`participantAdded`,(async e=>{this.logger.debug(`tsCall participant added`);let t=[];e.endpoints?.endpointDetails.forEach((e=>t.push(e.participantId))),t.length===0&&t.push(`remoteParticipantId unavailable`);let n=q2(e.id);if(this._isEnterpriseTeamsCall=this._isEnterpriseTeamsCall||n.kind===`microsoftTeamsUser`,this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:`added`,kindOfEvent:$.event}),R4(e))this.logger.info(`Add participant: Handle hidden calling application`);else{this.checkAndUpdateCopilotDisplayName(e),this._handleLocalRingingCallState(e);try{let t=this.getOrCreateRemoteParticipant(n,e);this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[t],removed:[]})}catch{this.logger.log(`unable to map call participant to ACS user`)}}}))),this.logger.debug(`tsCall current participant count=${this.tsCall?.participants?.length}`);let n=e=>{let t=q2(e.id);this._isEnterpriseTeamsCall=this._isEnterpriseTeamsCall||t.kind===`microsoftTeamsUser`;let n=this.getOrCreateRemoteParticipant(t,e);this._handleLocalRingingCallState(e),n.on(`displayNameChanged`,(()=>{this._callerIdentity&&K2(this._callerIdentity)===K2(n.identifier)&&(this._callerDisplayName=n.displayName,this._eventEmitter.emit(`callerInfoChanged`)),this._transferorIdentity&&K2(this._transferorIdentity)===K2(n.identifier)&&(this._transferorDisplayName=n.displayName,this._eventEmitter.emit(`transferorInfoChanged`))}))},r=[];this.tsCall.participants.forEach((e=>{Z().calling.checkHiddenBotOnCallStart&&R4(e)||n(e);try{e.endpoints?.endpointDetails.forEach((e=>r.push(e.participantId)))}catch{this.logger.error(`Unable to get participantId from from remote participant`)}}));try{this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:r,participantAddedOrRemoved:`added`,kindOfEvent:$.initialize})}catch{this.logger.error(`Unable to send participant added telemtery`)}return e.push(this.tsCall.on(`participantRemoved`,(async e=>{this.logger.debug(`tsCall participant removed`);let t=[];if(e.endpoints?.endpointDetails.forEach((e=>t.push(e.participantId))),t.length===0&&t.push(`remoteParticipantId unavailable`),R4(e))return this.logger.info(`Remove participant: Ignore calling application`),void this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:`removed`,kindOfEvent:$.event});let n=e.id;if(n){let r=this._remoteParticipants.find((e=>K2(e.identifier)===n));if(r){let{callEndReason:n}=W3(this,e);r.setCallEndReason(n),this.deleteRemoteParticipant(r),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:[r]}),this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:`removed`,kindOfEvent:$.event,additionalDetails:{...Y3(n)}})}else this.logger.log(`unable to find participant to remove`)}}))),e}_trackNetworkQualityUfdEventDetails(e){let t=+new Date,n=``;switch(e){case 5:n=i6;break;case 32:n=s6;break;case 2:n=a6;break;case 1:n=o6;break;case 37:n=c6}this._networkQualityUfdEventDetails.push({eventName:n,timestampInfo:t})}async muteUnmuteOnMicrophoneNotFunctioningUfd(e){try{let t=Z().calling;if(!t.muteUnmuteOnMicrophoneNotFunctioning||this._isMuted||e.type!==9||e.value!==3)return;this.__attemptedToRecoverMicNotFunctioningBySDK=!0,await this.mute(),t.unmuteDelayForMicrophoneNotFunctioningInMs>=0&&await r3(t.unmuteDelayForMicrophoneNotFunctioningInMs),await this.unmute()}catch(e){this.logger.info(`Unable to perform mute and unmute to recover microphoneNotFunctioning`,e)}finally{this.__attemptedToRecoverMicNotFunctioningBySDK=!1}}updateCallMode(){this.tsCall.callMode&&this._callMode!==this.tsCall.callMode&&(this.logger.log(`tsCall callMode changed from ${this._callMode} to ${this.tsCall.callMode}`),P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`callMode-changed`,oldState:eDe[this._callMode],newState:eDe[this.tsCall.callMode]}),this._callMode=this.tsCall.callMode)}checkAndUpdateCopilotDisplayName(e){this.tsCall.meetingDetails&&(K2(e)!==g2||e.displayName!==``&&e.displayName!==void 0||(e.displayName=y2))}async startCallInternal(e,t,n,r,i,a){let o=!!e?.audioOptions?.muted,s=this.getLocalVideoStreamFromCallOptions(e),c=this.getLocalAudioStreamFromCallOptions(e),l,u=i?.attemptTimestamp??+new Date,d=J0();this._joinContextDescription=nTe(n);let f=this._callAgent.getEcsConfigIds(),p=this.tsCall.participants.length===1&&!this.tsCall.threadId&&!t,m=!!p||this._allowIPAudio,h=!!p||this._allowIPVideo,g=G6(this.tsCall),_=i?.correlationId??J0(),v=FG(_),y=this.createVideoNegotiationTag(_,`Video`),b={joinContextDescription:this._joinContextDescription,additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:r?.isEmergency||!1,dialedEmergencyNumber:r?.isEmergency?this.tsCall.participants?.[0]?.id:void 0,trouterState:this._callAgent.getTrouterState(),muted:o,withVideo:h&&!!s,withAudio:m&&c?.mediaStreamType?c.mediaStreamType:``,...a7(),AcsCallingSDKWeb_ecsConfigId:f.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:f.SkypeWebMedia,customContext:{userToUserPresent:!!e?.customContext?.userToUser,xHeadersPresent:!!e?.customContext?.xHeaders&&e.customContext.xHeaders.length>0},firstPartyOptions:{isDeviceTypeEnabled:Z().calling.setDeviceType,deviceType:this._callAgent.getDeviceType(),isImmersiveMode:e?.firstPartyOptions?.isImmersiveMode,accessToImmersiveEvents:e?.firstPartyOptions?.accessToImmersiveEvents},mediaModalities:this.getMediaModalityTelemetry(e?.mediaModalities),negotiationTag:y,causeId:v},additionalDetails:{}};e?.videoOptions?.constraints&&(b.additionalProperties.constraints=this._mediaConstraintsManager.getTelemetryPayload({video:e?.videoOptions?.constraints})),r?.meetingInfo?.tenantId&&(this._teamsMeetingTenantId=r.meetingInfo.tenantId,b.additionalProperties.teamsMeetingTenantId=r.meetingInfo.tenantId),r?.threadId&&(this._teamsMeetingThreadId=r.threadId,b.additionalProperties.teamsMeetingThreadId=r.threadId),r?.onBehalfOf&&(b.additionalProperties.onBehalfOfProvided=!0,b.additionalProperties.onBehalfOfIdKind=q2(r.onBehalfOf).kind,this.logger.info(`onBehalfOf provided kind: ${b.additionalProperties.onBehalfOfIdKind}`));let x={...b},S={...b};this.sendCallStageEvent({eventName:Q.acs_calling_call_attempt,correlationId:_,timestampInfo:{attemptTimestamp:u},additionalPayload:b},void 0,void 0,void 0,`attempt`);try{this._isMicrophoneMuted=o,e?.alternateCallerId&&(l=K2(e.alternateCallerId)),s&&this.setLocalVideoStream(s),this.setLocalAudioStream(c)}catch(e){a?.reject(e);let t=+new Date,n=new Y({defaultError:J.CALL.INSTANTIATE_CALL,originalError:e});throw x.additionalDetails.communicationServicesError=J3(n).communicationServicesError,this.sendCallStageEvent({eventName:Q.acs_calling_call_failed,correlationId:_,timestampInfo:{deltaTimeInMs:t-u},additionalPayload:x},n,void 0,void 0,`failure`),this.logger.error(n.message),n}let C=PG();L7.setCauseIdToNetworkInfo(C);try{let n={...r};!Z().calling.setDeviceType||this._callAgent.getDeviceType()!==`mesh`&&this._callAgent.getDeviceType()!==`meshV2`||(n.endpointMetadata=JSON.stringify({meshapp:!0})),g?(await this.tsCall.initAsync?.(n),a?.resolve()):this.tsCall.init(n),s&&this.sendVideoEvent({correlationId:d,eventName:Q.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:u},localVideoStream:s,step:`start`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:y,causeId:v}});try{if(e?.videoOptions?.constraints){let t=await this._mediaConstraintsManager.setVideoConstraints(e?.videoOptions?.constraints,`start`,d,u),n=this._mediaConstraintsManager.getTelemetryPayload({video:t});S.additionalProperties.constraints=n}}catch(e){let t=new Y({defaultError:J.CALL.CALLSTART_VIDEO_CONSTRAINTS,originalError:e});this.logger.error(`${t.message}`)}let i=this.setClientCallStartOptions(e);if(Z()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(i.mediaConfiguration={connectionType:`NoDirectConnection`}),o&&(i.muteFlags=1),e?.firstPartyOptions?.disableAudioMixing&&(i.muteFlags===void 0?i.muteFlags=2:i.muteFlags|=2),e?.firstPartyOptions?.enableSpatialAudio!==void 0&&(i.mediaConfiguration=i.mediaConfiguration||{},i.mediaConfiguration.enableSpatialAudio=e.firstPartyOptions.enableSpatialAudio,this._callAgent.tsStack?await this._callAgent.tsStack.setMediaConfig({enableSpatialAudio:e.firstPartyOptions.enableSpatialAudio}):this.logger.error(`Could not set enableSpatialAudio to ${e.firstPartyOptions.enableSpatialAudio} since this._callAgent.tsStack is null`)),i.customHeaderContext=U4(e),c&&await this.startAudioInternal(c,!0).catch((e=>{this.logger.error(`Failed to start localAudioStream, message=${e?.message}`)})),s?.mediaStreamType===`RawMedia`)try{await this._setRawStream(s,1)}catch(e){let t=+new Date,n=new Y({defaultError:J.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:e});this.sendVideoEvent({correlationId:d,eventName:Q.acs_calling_media_stream,timestampInfo:{deltaTimeInMs:t-u},localVideoStream:s,step:`start`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:y}},n),this.removeLocalVideoStream(s)}t?await this.tsCall.startWithMeetingData(C,{withVideo:!!s&&this.isIPVideoEnabled,muted:o,ringOthers:!0,alternateId:l,shouldResurrect:`resurrect`,...i}):(i.negotiationTag=this.createVideoNegotiationTag(_,`Video`),await this.tsCall.start({withVideo:!!s&&this.isIPVideoEnabled,muted:o,ringOthers:!0,alternateId:l,...i},C)),S.additionalProperties.negotiationTag=y,S.additionalProperties.causeId=v;let f=+new Date;this.sendCallStageEvent({eventName:Q.acs_calling_call_connected,correlationId:_,timestampInfo:{deltaTimeInMs:f-u},additionalPayload:S},void 0,void 0,L7.getRemoveCauseIdToNetworkInfo(C),`success`),c&&this.shallRemoveLasAfterConnectedSuccessfully(c,`start`,_,f,u),s&&this.shallRemoveLvsAfterConnectedSuccessfully(s,`start`,_,f,u,y,v),this._handleAudioEffectsOperations()}catch(e){a?.reject(e);let t=+new Date,{callEndReason:n,callingCommunicationError:r}=U3(this,e);if(s){let n=new Y({defaultError:J.LOCAL_VIDEO_STREAM.CALL_NOT_FOUND,originalError:e});this.sendVideoEvent({correlationId:d,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:t-u},localVideoStream:s,step:`start`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:y,causeId:v}},n),this.removeLocalVideoStream(s)}throw c&&this.removeLocalAudioStream(c),x.additionalDetails.callEndReason=Y3(n).callEndReason,x.additionalProperties.negotiationTag=y,x.additionalProperties.causeId=v,this.sendCallStageEvent({eventName:Q.acs_calling_call_failed,correlationId:_,timestampInfo:{deltaTimeInMs:t-u},additionalPayload:x},r,void 0,L7.getRemoveCauseIdToNetworkInfo(C),`failure`),this.logger.error(`Failed to start the call, message=${n?.message}, code=${n?.code}, subCode=${n?.subCode}, resultCategories=${n?.resultCategories}`),r}}getMediaModalityTelemetry(e){return e?{audio:e.audio,video:e.video,screenShare:e.screenShare}:void 0}getTopNDominantSpeakersWithVideoOn(){if(this._internalDominantSpeakersListener){let e=this._internalDominantSpeakersListener.dominantSpeakers.speakersList.map((e=>this._mriToRemoteParticipantMap.get(K2(e)))).filter((e=>!!e)).filter((e=>!!e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).find((e=>e.tsStream.isAvailable))));if(this.logger.info(`There are currently ${e.length} top-n dominant speakers with video on in the large meeting where topCount is ${Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount}`),e.length<Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount){let t=this._remoteParticipants.filter((e=>!!e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).find((e=>e.tsStream.isAvailable)))).filter((t=>!e.includes(t)));t.sort(((e,t)=>{let n=e.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((e=>e.type===`audio`)).map((e=>e.sourceId))??[],r=n.length>0?Math.min(...n):void 0,i=t.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((e=>e.type===`audio`)).map((e=>e.sourceId))??[],a=i.length>0?Math.min(...i):void 0;return r!==void 0&&a!=null?r-a:0}));for(let n of t){if(e.length===Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount)break;e.push(n)}}else e.splice(Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount);return e}return[]}getParticipantCapabilities(){let e=this._capabilityResolver.getCapabilities();return this.logger.log(`participant capabilities are ${e}`),e}getMeetingCapabilitiesInternal(){let e=this._capabilityResolver.getMeetingsCapabilitiesInternal();return this.logger.info(`meeting capabilities are ${e}`),e}feature(e){return this._extensibleApi.getApiObjectInstance(e.callApiCtor)}async hangUp(e){let t=+new Date,n=J0(),r=PG();return L7.setCauseIdToNetworkInfo(r),this.sendCallStageEvent({eventName:Q.acs_calling_call_hangup_attempt,correlationId:n,timestampInfo:{attemptTimestamp:t}}),this.tsCall.stop(e?.forEveryone,r).then((()=>{let e=+new Date;this.sendCallStageEvent({eventName:Q.acs_calling_call_hangup_success,correlationId:n,timestampInfo:{deltaTimeInMs:e-t}},void 0,void 0,L7.getRemoveCauseIdToNetworkInfo(r))})).catch((e=>{let i=+new Date,{callEndReason:a,callingCommunicationError:o,hasDiagnosticsInfo:s}=U3(this,e),c=this._callAgent.getEcsConfigIds(),l={additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this._isEmergencyCall,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:c.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:c.SkypeWebMedia},additionalDetails:{}};if(s)l.additionalDetails={...Y3(a)};else{let t=new Y({defaultError:J.CALL.OPERATION_FAILED,originalError:e});l.additionalDetails.communicationServicesError=J3(t).communicationServicesError}throw this.sendCallStageEvent({eventName:Q.acs_calling_call_hangup_failure,correlationId:n,timestampInfo:{deltaTimeInMs:i-t},additionalPayload:l},o,void 0,L7.getRemoveCauseIdToNetworkInfo(r)),o}))}async mute(){let e=this.logger.createFnLogger(c4.Mute),t=+new Date,n=J0(),r=PG();L7.setCauseIdToNetworkInfo(r),this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:d3.MuteMicrophone,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK});try{e.info(`mute`),await this.tsCall.mute(r),e.info(`mute success`);let i=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:d3.MuteMicrophone,timestampInfo:{deltaTimeInMs:i-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:L7.getRemoveCauseIdToNetworkInfo(r)})}catch(i){let a=new Y({defaultError:J.CALL.MIC_MUTE,originalError:i});e.error(`Failed to mute microphone`);let o=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:d3.MuteMicrophone,timestampInfo:{deltaTimeInMs:o-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:L7.getRemoveCauseIdToNetworkInfo(r)},a),a}}async unmute(){let e=this.logger.createFnLogger(c4.Unmute),t=+new Date,n=J0(),r=!1,i=PG();if(L7.setCauseIdToNetworkInfo(i),this.sendAudioEvent({eventName:Q.acs_calling_unmute_attempt,eventType:d3.UnmuteMicrophone,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK}),!this.isAudioPermitted()){let t=`cannot unmute as microphone is disabled`;throw e.error(t),new Y({defaultError:J.CALL.MIC_DISABLED,originalError:t})}if(!this.isIPAudioEnabled){let t=`cannot unmute as IP audio in Teams Meeting Policy is disabled`;throw e.error(t),new Y({defaultError:J.CALL.IP_AUDIO_NOT_ALLOWED,originalError:t})}if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){let t=`cannot unmute as consent is required to be recorded or transcribed`;throw e.error(t),new Y({defaultError:J.CALL.UNMUTE_CONSENT_RESTRICTED,originalError:t})}try{e.info(`unmute`),await this.tsCall.unmute(i),e.info(`unmute success`);let a=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_unmute_success,eventType:d3.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:L7.getRemoveCauseIdToNetworkInfo(i)});let o=+new Date;if(!Z()?.calling?.preventStopAudio&&this._isDeviceNotFunctioningMuted){this.sendAudioEvent({eventName:Q.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:o},correlationId:n,step:`mid-call`,networkInfo:L7.getRemoveCauseIdToNetworkInfo(i)}),r=!0,e.info(`start audio`),await this.tsCall.startAudio(),e.info(`start audio success`);let t=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:Q.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:t-o},correlationId:n,step:`mid-call`,networkInfo:L7.getRemoveCauseIdToNetworkInfo(i)})}this.setLocalAudioStream()}catch(a){let o=r?J.CALL.MIC_UNMUTE_AND_STARTAUDIO:J.CALL.MIC_UNMUTE,s=new Y({defaultError:o,originalError:a});e.error(o.message);let c=+new Date;throw this.sendAudioEvent({eventName:r?Q.acs_calling_start_audio_failure:Q.acs_calling_unmute_failure,eventType:r?void 0:d3.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:c-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK&&!r,networkInfo:L7.getRemoveCauseIdToNetworkInfo(i)},s),s}}async muteAllRemoteParticipants(){let e=Z();if(!e.calling.enableMuteOthers)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_DISABLED});if(!this.tsCall.conversationType&&this._callInfo.context===b4.TwoParty)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_1_TO_1_UNSUPPORTED});let t=this.logger.createFnLogger(c4.MuteAllRemoteParticipants),n=+new Date,r=J0();this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:d3.MuteAllRemoteParticipants,timestampInfo:{attemptTimestamp:n},correlationId:r,step:`mid-call`});try{t.info(`mute all others`),t7(c4.MuteAllRemoteParticipants,this.state);let i=[];if(this._remoteParticipants.length!==0){let n=!1,r=!1,a=``;if(this._remoteParticipants.map((o=>{let s=o.tsRemoteParticipant;e.calling.allowMutePstnRemoteParticipant||o.identifier.kind!==`phoneNumber`?[3,5].some((e=>e===s?.state))?s!==void 0&&(i.push(s),a+=K2(o.identifier)+`, `):(t.warn(`non-connected participants cannot be muted by others`),r=!0):(t.warn(`PSTN participants cannot be muted by others`),n=!0)})),i.length===0?t.error(`all remote participants are not supported to be muted by others`):(await this.tsCall.muteParticipants(1,i),t.info(`called mute function on the following participants: ${a}`)),n){if(!this._isTeamsExtensionUser||!Z().calling.teamsExtensionSettings.enableServerMutePSTNParticipant)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_PSTN_UNSUPPORTED});t.info(`Enable server muting of PSTN participant for TeamsExtension user`)}if(r)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_NONCONNECTED_UNSUPPORTED})}else t.info(`no participants to mute in attempt to mute all remote participants`);t.info(`mute all others success`);let a=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:d3.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:a-n},correlationId:r,step:`mid-call`})}catch(e){let i=new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS,originalError:e});t.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:d3.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:a-n},correlationId:r,step:`mid-call`},i),i}}async muteIncomingAudio(){let e=this.logger.createFnLogger(c4.MuteIncomingAudio),t=+new Date,n=J0();this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:d3.MuteIncomingAudio,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.tsCall.muteSpeaker();let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:d3.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:e-t},correlationId:n,step:`mid-call`})}catch(r){let i=new Y({defaultError:J.CALL.MUTE_INCOMING_AUDIO,originalError:r});e.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:d3.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`},i),i}}async unmuteIncomingAudio(){let e=this.logger.createFnLogger(c4.MuteIncomingAudio),t=+new Date,n=J0();this.sendAudioEvent({eventName:Q.acs_calling_unmute_attempt,eventType:d3.UnmuteIncomingAudio,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.tsCall.unmuteSpeaker();let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_unmute_success,eventType:d3.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:e-t},correlationId:n,step:`mid-call`})}catch(r){let i=new Y({defaultError:J.CALL.UNMUTE_INCOMING_AUDIO,originalError:r});e.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_unmute_failure,eventType:d3.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`},i),i}}async sendDtmf(e){let t=tDe(e);return this.tsCall.sendDtmfTone(t).catch((e=>{throw this.logger.error(`Failed to send DTMF tone`),new Y({defaultError:J.CALL.DTMF_TONE})}))}async startVideo(e){let t=this.logger.createFnLogger(c4.StartVideo),n=+new Date,r=Z()?.calling?.preventStopAudio,i=J0(),a=FG(i),o=this.createVideoNegotiationTag(i,`Video`);if(this.sendVideoEvent({eventName:Q.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:n},localVideoStream:e,correlationId:i,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:o,causeId:a}}),!this.isVideoPermitted()){let e=`cannot start video as camera is disabled by the Presenter or Organizer of the meeting`;throw t.error(e),new Y({defaultError:J.CALL.CAMERA_DISABLED,originalError:e})}if(!this.isIPVideoEnabled){let e=`cannot start video as IP video is not allowed`;throw t.error(e),new Y({defaultError:J.CALL.IP_VIDEO_NOT_ALLOWED,originalError:e})}if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){let e=`cannot start video as consent is restricted`;throw t.error(e),new Y({defaultError:J.CALL.VIDEOSTART_CONSENT_RESTRICTED,originalError:e})}if(this._isDeviceNotFunctioningMuted&&!r){this.sendAudioEvent({eventName:Q.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:n},correlationId:i,step:`mid-call`});try{t.info(`start audio before starting video`),await this.tsCall.startAudio(),t.info(`start audio success before starting video`);let e=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:Q.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:e-n},correlationId:i,step:`mid-call`})}catch(e){let r=new Y({defaultError:J.CALL.START_AUDIO_BEFORE_VIDEO,originalError:e});t.error(`Failed to start audio before starting video`);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_start_audio_failure,timestampInfo:{deltaTimeInMs:a-n},correlationId:i,step:`mid-call`},r),r}}try{if(!e)throw new Y({defaultError:J.CALL.STREAM_NULL});if(!(e instanceof X6))throw new Y({defaultError:J.CALL.STREAM_IS_NOT_LVS});if(this.tsCall.isVideoOn)throw new Y({defaultError:J.CALL.VIDEO_ALREADY_ON});e?.mediaStreamType===`RawMedia`&&await this._setRawStream(e,1),this.setLocalVideoStream(e)}catch(t){let r=new Y({defaultError:J.CALL.START_VIDEO,originalError:t});throw this.sendVideoEvent({correlationId:i,eventName:Q.acs_calling_start_video_failure,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:o,causeId:a}},r),r}L7.setCauseIdToNetworkInfo(a);try{t.info(`start video`),await this.tsCall.startVideo(o,a);let r=+new Date;this.sendVideoEvent({correlationId:i,eventName:Q.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:r-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:L7.getRemoveCauseIdToNetworkInfo(a),additionalDetails:{negotiationTag:o,causeId:a}}),t.info(`video started`)}catch(r){let s=+new Date,c=G3(t,r);throw this.sendVideoEvent({correlationId:i,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:s-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:L7.getRemoveCauseIdToNetworkInfo(a),additionalDetails:{negotiationTag:o,causeId:a}},c),this.removeLocalVideoStream(e),c}}async stopVideo(e){let t=this.logger.createFnLogger(c4.StopVideo),n=+new Date,r=J0(),i=FG(r),a=this.createVideoNegotiationTag(r,`Video`);this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_attempt,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:i}});let o=this.tsCall.state===4||this.tsCall.state===5;if(!o&&!this.tsCall.isVideoOn||o&&!this.localVideoStream){let t=new Y({defaultError:J.CALL.VIDEO_ALREADY_OFF});throw this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:i}},t),t}if(this.localVideoStream!==void 0&&this.localVideoStream!==e){let t=new Y({defaultError:J.CALL.STOP_WRONG_STREAM});throw this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:i}},t),t}let s=()=>{try{if(Z().calling.allowAccessRawMediaStream&&e.mediaStreamType===`RawMedia`){let e=this._callAgent.tsStack?.getDeviceManager();e&&e.unsetRawMediaStream&&e.unsetRawMediaStream(1)}}catch(e){this.logger.info(`Unset raw video stream: ${e?.message??`Unkown error`}`)}};L7.setCauseIdToNetworkInfo(i);try{t.info(`stop video`),await this.tsCall.stopVideo(a,i),s();let o=+new Date;this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_success,timestampInfo:{deltaTimeInMs:o-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:L7.getRemoveCauseIdToNetworkInfo(i),additionalDetails:{negotiationTag:a,causeId:i}}),t.info(`video stopped`),this.removeLocalVideoStream(e)}catch(o){s();let c=+new Date,l=G3(t,o,!0);throw this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_failure,timestampInfo:{deltaTimeInMs:c-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:L7.getRemoveCauseIdToNetworkInfo(i),additionalDetails:{negotiationTag:a,causeId:i}},l),l}}startAudio(e){return this.startAudioInternal(e)}stopAudio(){return this.stopAudioInternal()}async hold(){let e=+new Date,t=J0(),n=PG();L7.setCauseIdToNetworkInfo(n);try{this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Hold,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:S4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),Z().calling.turnOffScreenShareBeforeHold&&this.tsCall.isScreenSharingOn&&await this.tsCall.stopScreenSharing().then((()=>{this.logger.log(`Successfully turned off screen sharing before hold`)})).catch((()=>{this.logger.error(`Failed to turn off screensharing before hold`)})),await this.tsCall.hold(void 0,n),this.removeLocalAudioStream(this._localAudioStreams[0]);let r=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Hold,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{holdType:S4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn},networkInfo:L7.getRemoveCauseIdToNetworkInfo(n)})}catch{let r=+new Date,i=new Y({defaultError:J.CALL.HOLD_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Hold,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,holdType:S4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...J3(i)},networkInfo:L7.getRemoveCauseIdToNetworkInfo(n)}),i}}async resume(){let e=+new Date,t=J0(),n=PG();L7.setCauseIdToNetworkInfo(n);try{this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Resume,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:S4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),await this.tsCall.unhold(void 0,n),this.setLocalAudioStream();let r=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Resume,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,holdType:S4.Standard},networkInfo:L7.getRemoveCauseIdToNetworkInfo(n)})}catch{let r=+new Date,i=new Y({defaultError:J.CALL.RESUME_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Resume,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,holdType:S4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...J3(i)},networkInfo:L7.getRemoveCauseIdToNetworkInfo(n)}),i}}async startScreenSharing(e){let t=this.logger.createFnLogger(c4.StartScreenShare),n=+new Date,r=J0(),i=FG(r),a=this.createVideoNegotiationTag(r,`ScreenSharing`);try{if(this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.attempt,timestampInfo:``,isVideoOn:this._isLocalVideoStarted,localVideoStream:e,additionalDetails:{negotiationTag:a,causeId:i}}),this.tsCall.state!==3)throw new Y({defaultError:J.CALL.START_SS_CALL_NOT_CONNECTED});if(this.tsCall.isScreenSharingOn)throw new Y({defaultError:J.CALL.SS_ALREADY_ON});if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){let e=`screen sharing cannot be started as consent is required to be recorded or transcribed`;throw t.error(e),new Y({defaultError:J.CALL.SCREENSHARE_CONSENT_RESTRICTED,originalError:e})}if(e){if(!(e instanceof X6))throw new Y({defaultError:J.CALL.SS_RAW_STREAM_IS_NOT_LVS});if(e.mediaStreamType!==`RawMedia`)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_LVS_IS_NOT_RAW_MEDIA});let t=await e.getMediaStream();if(!t||t.getVideoTracks().length===0)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_IS_NOT_VALID_STREAM});if(!1===t.active)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_IS_NOT_ACTIVE_STREAM});t.getTracks().forEach((e=>{e.stop()})),await this._setRawStream(e,2),this.localScreenSharingStream=e}else this.localScreenSharingStream=new X6(new z6(swe.ScreenSharing,J0(),swe.ScreenSharing,this._callAgent.deviceManager))}catch(e){let t=+new Date;this.removeScreenSharingStream();let o=new Y({defaultError:J.CALL.START_SS,originalError:e});throw this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:t-n},additionalDetails:{failureReason:o.message,code:o.code,subCode:o.subCode,...J3(o),negotiationTag:a,causeId:i},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),o}return this.tsCall.startScreenSharing(void 0,void 0,a).then((()=>{let e=+new Date;this.localScreenSharingStream&&this._localVideoStreams.indexOf(this.localScreenSharingStream)===-1&&(this.localScreenSharingStream.addCall(this),this._localVideoStreams.push(this.localScreenSharingStream),this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[this.localScreenSharingStream],removed:[]})),this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:e-n},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream,additionalDetails:{negotiationTag:a,causeId:i}})})).catch((e=>{let o=+new Date;this.removeScreenSharingStream();let s=G3(t,e);throw this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{failureReason:s.message,code:s.code,subCode:s.subCode,...J3(s),negotiationTag:a,causeId:i},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),s}))}async stopScreenSharing(){let e=this.logger.createFnLogger(c4.StopScreenShare),t=+new Date,n=J0(),r=FG(n),i=this.createVideoNegotiationTag(n,`ScreenSharing`);if(this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.attempt,timestampInfo:``,isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream,additionalDetails:{negotiationTag:i,causeId:r}}),this.tsCall.state!==3)throw new Y({defaultError:J.CALL.STOP_SS_CALL_NOT_CONNECTED});if(!this.tsCall.isScreenSharingOn){let e=+new Date,a=new Y({defaultError:J.CALL.SS_ALREADY_OFF});throw this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:e-t},additionalDetails:{failureReason:a.message,code:a.code,subCode:a.subCode,...J3(a),negotiationTag:i,causeId:r},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),a}return this.tsCall.stopScreenSharing(void 0,i).then((()=>{let e=+new Date,a=e4.cloneDeep(this.localScreenSharingStream);this.removeScreenSharingStream(),this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:e-t},isVideoOn:this._isLocalVideoStarted,localVideoStream:a,additionalDetails:{negotiationTag:i,causeId:r}})})).catch((a=>{let o=+new Date,s=G3(e,a,!0),c=typeof s?.message==`string`?s?.message:void 0;throw this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-t},additionalDetails:{failureReason:c||``,code:s.code,subCode:s.subCode,...J3(s),negotiationTag:i,causeId:r},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),s}))}async setConstraints(e){let t=+new Date,n=J0();try{let r=await this._mediaConstraintsManager.setVideoConstraints(e?.video,`mid-call`,n,t);this.logger.info(`Video constraints set - ${JSON.stringify(r)}`)}catch(e){throw new Y({defaultError:J.CALL.SET_VIDEO_CONSTRAINTS,originalError:e})}}on(e,t){if(e!==`stateChanged`&&e!==`idChanged`&&e!==`isMutedChanged`&&e!==`isIncomingAudioMutedChanged`&&e!==`isScreenSharingOnChanged`&&e!==`isLocalVideoStartedChanged`&&e!==`remoteParticipantsUpdated`&&e!==`localVideoStreamsUpdated`&&e!==`localAudioStreamsUpdated`&&e!==`remoteAudioStreamsUpdated`&&e!==`totalParticipantCountChanged`&&e!==`roleChanged`&&e!==`mutedByOthers`&&e!==`callerInfoChanged`&&e!==`transferorInfoChanged`)throw new Y({defaultError:J.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`stateChanged`&&e!==`idChanged`&&e!==`isMutedChanged`&&e!=`isIncomingAudioMutedChanged`&&e!==`isScreenSharingOnChanged`&&e!==`isLocalVideoStartedChanged`&&e!==`remoteParticipantsUpdated`&&e!==`localVideoStreamsUpdated`&&e!==`localAudioStreamsUpdated`&&e!==`remoteAudioStreamsUpdated`&&e!==`totalParticipantCountChanged`&&e!==`roleChanged`&&e!==`mutedByOthers`&&e!==`callerInfoChanged`&&e!==`transferorInfoChanged`)throw new Y({defaultError:J.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}onMeetingCapabilitiesChanged(e,t){if(e!==`meetingCapabilitiesChanged`)throw new Y({defaultError:J.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}offMeetingCapabilitiesChanged(e,t){if(e!=`meetingCapabilitiesChanged`)throw new Y({defaultError:J.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}onParticipantCapabilitiesChanged(e,t){this.logger.log(`participant capabilities change event listener registered`),this._eventEmitter.on(e,t)}offParticipantCapabilitiesChanged(e,t){this.logger.log(`participant capabilities change event listener unregistered`),this._eventEmitter.off(e,t)}setWatermarkAudioOnlyFallbackTriggered(e){this._watermarkAudioOnlyFallbackTriggered=e,this._eventEmitter.emit(`watermarkAudioOnlyFallbackTriggeredChanged`)}onWatermarkAudioOnlyFallbackTriggeredChanged(e,t){this.logger.log(`watermark audio only fallback triggered listener registered`),this._eventEmitter.on(e,t)}offWatermarkAudioOnlyFallbackTriggeredChanged(e,t){this.logger.log(`watermark audio only fallback triggered listener unregistered`),this._eventEmitter.off(e,t)}setIsRenderingRemoteScreenShare(e){this.isRenderingRemoteScreenShare!==e&&(this.isRenderingRemoteScreenShare=e,this._eventEmitter.emit(`isRenderingRemoteScreenShareChanged`))}onIsRenderingRemoteScreenShareChanged(e,t){this._eventEmitter.on(e,t)}offIsRenderingRemoteScreenShareChanged(e,t){this._eventEmitter.off(e,t)}getOrCreateRemoteParticipant(e,t){let n=this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)));return n||(n=new M7(e,this.logger,this,this._callAgent,this._telemetryLogManager),this._remoteParticipants.push(n),this._mriToRemoteParticipantMap.set(K2(n.identifier),n)),t&&n.observeParticipant(t),n}deleteRemoteParticipant(e){let t=!0;return this._remoteParticipants.splice(this._remoteParticipants.indexOf(e),1).length!==1&&(this.logger.warn(`Deleted remote participant array is not 1`),t=!1),this._mriToRemoteParticipantMap.delete(K2(e.identifier))||(this.logger.warn(`Deleted remote participant was not found in mri-to-remoteparticipant map`),t=!1),t}sendCallOnHoldAndResumedEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send call hold or resume telemetry`)}}sendVideoEvent(e,t){try{let n,r;try{n=e.localVideoStream?.getStreamMetadata()}catch{this.logger.error(`Unable to get stream meta data on send video event`)}t&&(r=typeof t?.message==`string`?t?.message:void 0,(e.additionalDetails??{}).communicationServicesError=J3(t).communicationServicesError),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:{...n,callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||``,failureReason:r||``,isScreenSharingOnFlag:e.isScreenSharingOnFlag,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]}})}catch{this.logger.debug(`Unable to send video telemetry`)}}sendScreenShareEvent(e){let t;try{t=e.localVideoStream?.getStreamMetadata()}catch{this.logger.error(`Unable to get stream meta data on send video event`)}try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:{...t,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:e.correlationId,kindOfEvent:e.kindOfEvent,timestampInfo:e.timestampInfo,additionalDetails:e.additionalDetails,isVideoOn:e.isVideoOn}})}catch{this.logger.debug(`Unable to send screen share telemetry`)}}sendRawMediaEvent(e){let t={...e};t.localAudioStream=e.localAudioStream?.source instanceof MediaStream?`MediaStream`:`Device`;try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:t})}catch{this.logger.debug(`Unable to send raw media telemetry`)}}sendAudioEvent(e,t){try{let n;t&&(n=typeof t?.message==`string`?t?.message:void 0,e.additionalDetails={...J3(t)});let r={callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||``,failureReason:n||``,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]};e.eventType!==void 0&&(r.eventType=e.eventType),e.initiatedBySdk&&(r.initiatedBySdk=!0),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:r})}catch{this.logger.debug(`Unable to send audio telemetry`)}}sendCallStageEvent(e,t,n,r,i){try{let a,o=``;t&&(a=this?.tsCall?.callEndDiagnosticsInfo||n||{},o=t.message);let s=this._joinContextDescription===R2.RoomCall||this.kind===GG.Call&&this._direction===`Incoming`&&!this.tsCall.groupId&&!!this.tsCall.meetingData?.meetingCode&&!this.tsCall.threadId,c=!s&&this._joinContextDescription===R2.TeamsMeetingLink||this._joinContextDescription===R2.TeamsMeetingId||this._joinContextDescription===R2.TeamsCoordinates||this._direction==`Incoming`&&!this.tsCall.groupId&&!!this.tsCall.meetingData&&!!this.tsCall.threadId,l={localParticipantId:this?.tsCall?.participantId||``,callId:this?.tsCall?.callId||``,callType:this?.tsCall?.callType||``,callDirection:this._direction,failureReason:o,callEndDiagnosticsInfo:a,calleeIdentityType:this.getParticipantIdentityType(),groupJoin:!!this?.tsCall?.groupId,roomJoin:s,meetingJoin:c,hostRegion:this?.tsCall?.region||``,correlationId:e.correlationId,timestampInfo:e.timestampInfo,...e.additionalPayload,networkInfo:r||[],negotiationTag:e.additionalPayload?.additionalProperties.negotiationTag??``,causeId:e.additionalPayload?.additionalProperties.causeId??``};this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:l},void 0,i)}catch{}}getParticipantIdentityType(){if(this.tsCall?.participants.length>1)return G2.group;if(this.tsCall?.participants.length===0)return G2.unknown;let e=this.tsCall?.participants[0];return q2(e.id).kind}optimalVideoCountChanged(e,t){let n=this._optimalVideoCount,r=e||this.tsCall.optimalVideoCount,i=Z().telemetry.progressEvents.enableOvcChangedEvent;if(r&&n!==r&&i)try{P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`optimalVideoCount-changed`,previousOptimalVideoCount:n,newOptimalVideoCount:r,changeReason:t,currentNumberOfVideosRendered:this.activeRemoteVideoStreamViews?.size||0})}catch{this.logger.error(`Failed to send optimal video count change telemetry`)}finally{this._optimalVideoCount=r??1}}_sendNetworkChangedTelemetry(){try{let e=(e,t,n)=>{P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`network-changed`,trouterState:e,onLine:t,rdpState:n})};this._trouterStateChangedListener=t=>{e(t,navigator.onLine,this._mmrRdpConnectionManager.state)},this._callAgent.onTrouterStateChanged(this._trouterStateChangedListener),this._onlineListener=t=>{e(this._callAgent.getTrouterState(),!0,this._mmrRdpConnectionManager.state)},window.addEventListener(`online`,this._onlineListener),this._offlineListener=t=>{e(this._callAgent.getTrouterState(),!1,this._mmrRdpConnectionManager.state)},window.addEventListener(`offline`,this._offlineListener),this._mmrRdpConnectionManager.on(`stateChange`,(t=>{e(this._callAgent.getTrouterState(),!1,t)})),e(this._callAgent.getTrouterState(),navigator.onLine,this._mmrRdpConnectionManager.state)}catch{this.logger.warn(`Failed to subscribe to network changed`)}}_setupSelectedDeviceChangedTelemetry(){try{let e=e=>{P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`selectedDevice-changed`,selectedDeviceType:e.selectedDeviceType,oldDevice:e.oldDevice,newDevice:e.newDevice})};if(this._selectedDeviceManager){this._selectedDeviceManager.on(`selectedDeviceChanged`,e);let t=this._selectedDeviceManager.selectedDevice(`Speaker`),n=this._selectedDeviceManager.selectedDevice(`Microphone`);e({selectedDeviceType:`Speaker`,oldDevice:void 0,newDevice:t}),e({selectedDeviceType:`Microphone`,oldDevice:void 0,newDevice:n})}}catch{this.logger.warn(`Failed to subscribe to selectedDevice changed`)}}setLocalVideoStream(e){if(!this._callAgent.tsStack)throw new Y({defaultError:J.CALL.VIDEO_UNDEFINED_STACK});if(!this.localVideoStream&&e&&!this._localVideoStreams.find((t=>t===e))){this.localVideoStream=e,this._localVideoStreams.push(this.localVideoStream),this.localVideoStream.mediaStreamType!==`RawMedia`&&this._callAgent.tsStack.getDeviceManager()?.selectDevices({camera:e.source.id}),this.localVideoStream.addCall(this);try{this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[this.localVideoStream],removed:[]})}catch{this.logger.warn(`Application threw on emit localVideoStreamsUpdated added`)}this.logger.log(`isLocalVideoStarted changed=true`),this._isLocalVideoStarted=!0,this._eventEmitter.emit(`isLocalVideoStartedChanged`)}}removeLocalVideoStream(e){if(this.localVideoStream&&e===this.localVideoStream&&this.localVideoStreams.find((e=>e===this.localVideoStream))){if(this.logger.log(`Attempting to remove local video stream`),this._localVideoStreams.splice(this._localVideoStreams.indexOf(this.localVideoStream),1).length===0)return void this.logger.warn(`Stream not found, failed to remove stream from localVideoStreams collection`);this.logger.log(`Local video stream removed successfully`),this.localVideoStream.removeCall(this),this.localVideoStream.autoDisposeOnCallEnd&&this.localVideoStream.dispose();let e=this.localVideoStream;this.localVideoStream=void 0;try{this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[],removed:[e]})}catch{this.logger.warn(`Application threw on emit localVideoStreamsUpdated removed`)}this.logger.log(`isLocalVideoStarted changed=false`),this._isLocalVideoStarted=!1,this._eventEmitter.emit(`isLocalVideoStartedChanged`)}}setLocalAudioStream(e){if(!this._callAgent.tsStack)throw new Y({defaultError:J.CALL.LOCAL_AUDIO_UNDEFINED_STACK});if(e)e.on(`audioSourceChanged`,this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]});else if(this._localAudioStreams.length===0){if(this._userProvidedLocalAudioStreamCache)return(e=this._userProvidedLocalAudioStreamCache).on(`audioSourceChanged`,this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),void this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]});let t=this.deviceManager?.selectedMicrophone;if(t){let e=new f8(t);e.on(`audioSourceChanged`,this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]})}else this.logger.warn(`Could not get current selected microphone to update localAudioStreams collection`)}else this.logger.warn(`No localAudioStream provided and the collection is not empty, doing nothing`)}removeLocalAudioStream(e){if(e){if(this.logger.log(`Attempting to remove local audio stream`),e.off(`audioSourceChanged`,this.audioSourceChanged),e.autoDisposeOnCallEnd&&e.dispose(),this._localAudioStreams.splice(this._localAudioStreams.indexOf(e),1).length===0)return void this.logger.warn(`Stream not found, failed to remove stream from localAudioStreams collection`);e.removeCall(this),this.logger.log(`Local audio stream removed successfully`),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[e]})}}_handleAudioEffectsOperations(){try{let e=this._localAudioStreams?.[0];if(!e)return void this.logger.debug(`No LocalAudioStream found in the call, cannot handle call audio effects operations`);this._audioEffectsStatsListener=e=>{this._audioEffectsProcessorStats=e},e.feature($5.AudioEffects)?.on(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener)}catch(e){this.logger.warn(`Error handling audio effects operations during call start: ${e}`)}}isAudioPermitted(){return!!this.feature($5.MediaAccess)?.getLocalParticipantMediaAccess().isAudioPermitted}isVideoPermitted(){return!!this.feature($5.MediaAccess)?.getLocalParticipantMediaAccess().isVideoPermitted}removeScreenSharingStream(){if(this.localScreenSharingStream&&this.localVideoStreams.find((e=>e===this.localScreenSharingStream))){if(Z()?.calling?.allowAccessRawMediaStream&&this.localScreenSharingStream?.mediaStreamType===`RawMedia`){let e=this._callAgent.tsStack?.getDeviceManager();e?.unsetRawMediaStream&&e.unsetRawMediaStream(2)}this.localScreenSharingStream.dispose(),this.localScreenSharingStream.removeCall(this);let e=this._localVideoStreams.indexOf(this.localScreenSharingStream);this._localVideoStreams.splice(e,1);let t=this.localScreenSharingStream;this.localScreenSharingStream=void 0,this._isScreenSharingOn=!1,this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[],removed:[t]})}}mapTsCallState(e){let t=$Ee[e];switch(t){case`Unknown`:case void 0:this.logger.log(`Ignored tsCall state \`${e}\``);break;case`Disconnected`:{this._callEndReason=U3(this).callEndReason,this._remoteParticipants.forEach((e=>{e.setCallEndReason(W3(this,e.tsRemoteParticipant).callEndReason),e.setParticipantState(`Disconnected`)}));let n=this._remoteParticipants.map((e=>e));this._remoteParticipants=[],this._mriToRemoteParticipantMap.clear(),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:n}),this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream),this.localAudioStreams[0]&&this.removeLocalAudioStream(this.localAudioStreams[0]),this._rawAudioStreamChangedSubscription?.dispose&&this._rawAudioStreamChangedSubscription.dispose(),Z().calling.allowAccessRawMediaStream&&this.remoteAudioStreams[0]&&this.removeRemoteAudioStream(this.remoteAudioStreams[0]),this._userProvidedLocalAudioStreamCache=void 0,this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._setCallState(t),this._telemetryLogManager.flushAllEvents(this.id).then((()=>{this.logger.log(`Telemetry flushed`)})).catch((e=>{this.logger.warn(`Failed to flush telemetry log manager events`)}));break}case`Connected`:this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._remoteParticipantsChangedListeners.forEach((e=>{e.dispose()})),this._setCallState(t),this._setOrUpdateDeviceEventsTask=this._setOrUpdateDeviceEventsTask.then((()=>this.setOrUpdateMediaMetricsDeviceEvents().catch(M4))),Z().calling.allowAccessRawMediaStream&&this.subscribeToGetRemoteAudioStream();break;case`Incoming Call`:{this.logger.log(`state changed from ${this._state} to 'Incoming Call'`);let e=new I7(this.tsCall,{config:this._config});P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`state-changed`,oldState:this._state,newState:`Incoming Call`,callTypeInfo:{initiatorKind:e.initiatorKind,targetKind:e.targetKind,transferor:e.transferorKind,context:e.context,callScenario:e.callScenario,direction:e.direction},teamsMeetingTenantId:this._teamsMeetingTenantId||``,teamsMeetingThreadId:this._teamsMeetingThreadId||``,callDurationInSeconds:this.tsCall.callStartedAt?Math.floor((Date.now()-this.tsCall.callStartedAt?.getTime())/1e3):-1});break}default:this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._setCallState(t)}}shallStopVideo(e){let t=Z()?.calling?.deviceNotFunctioningMuted,n=Z()?.calling?.deviceCaptureMutedVideo,r=Z()?.calling?.preventStopVideo,i=e.type===25&&e.value===3,a=i&&e.mediaType===1,o=e.type===33&&e.value===3,s=r8(),c=i8()===`ios`&&s.engine===`Safari`,l=i8()===`android`,u=this.tsCall.state===3;return r?u&&this.tsCall.isVideoOn&&o:t&&u&&this.tsCall.isVideoOn&&(o||c&&i||n&&l&&a)}shallRemoveLocalVideoStreamOnBadUfd(e){let t=this.tsCall.localMediaStreams.find((e=>e.mediaType===1)),n=e.mediaType===1&&e.value===3&&e.type===25,r=this.tsCall.state==4||this.tsCall.state===5;if(r8().formFactor===`Mobile`&&(n||document.visibilityState==`hidden`)&&this.localVideoStream&&r&&!t||!Z()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return!1;let i=this.tsCall.state===3;return e.mediaType===1&&e.value===3&&(e.type===33||e.type===25||e.type===34)&&!!this.localVideoStream&&!i&&!t}shallStopAudio(e){let t=Z()?.calling?.deviceNotFunctioningMuted,n=Z()?.calling?.osAutoRecoverAudio,r=e.type===25&&e.value===3&&e.mediaType===0,i=e.type===9&&e.value===3,a=r8(),o=i8()===`ios`&&a.engine===`Safari`,s=this.tsCall.state===3;return n?t&&s&&i:t&&!this._isDeviceNotFunctioningMuted&&s&&(i||o&&r)}markCallMuted(){this._isDeviceNotFunctioningMuted=!0,this._handleMuteChanges()}audioDidAutoRecover(e){let t=Z()?.calling?.deviceCaptureMuteRecover&&!Z()?.calling?.preventFakeMute,n=e.type===25&&e.value===1&&e.mediaType===0,r=this.tsCall.state===3,i=r8(),a=i8()===`ios`&&i.engine===`Safari`,o=e.type===9&&e.value===1;return t&&this._isDeviceNotFunctioningMuted&&r&&(o||a&&n)}sendParticipantAddedOrRemovedEvent(e){try{this._telemetryLogManager.sendEvent({name:Q.acs_calling_participant_added_or_removed,tenant:p2,properties:{callId:this.id,remotePerticipantId:Array.isArray(e?.remoteParticipantIds)?e?.remoteParticipantIds.slice(0,Z().telemetry.maxExistingReportedParticipants):[],participantAddedOrRemoved:e.participantAddedOrRemoved,localParticipantId:this.tsCall.participantId,kindOfEvent:e.kindOfEvent,correlationId:e.correlationId||``,timestampInfo:e.timestampInfo||``,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]}})}catch{this.logger.debug(`Unable to send participant added or removed telemtery`)}}_handleLocalRingingCallState(e){this._state===`Connected`||this._direction!==`Outgoing`||this._localRingingStateSet||this._remoteParticipantsChangedListeners.push(e.changed((()=>{e.state!==2||this._state===`Connected`||this._localRingingStateSet||(this._setCallState(`Ringing`),this._localRingingStateSet=!0,this._remoteParticipantsChangedListeners.forEach((e=>{e.dispose()})))})))}_setCallState(e){if(e!==this._state){let t=this._state,n=e,r=new I7(this.tsCall,{config:this._config});this.logger.log(`state changed from ${t} to ${n}`),this._state=n,n===`Connected`&&(this._connectedTimestamp=Date.now()),this._eventEmitter.emit(`stateChanged`),P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`state-changed`,oldState:t,newState:n,callTypeInfo:{initiatorKind:r.initiatorKind,targetKind:r.targetKind,transferor:r.transferorKind,context:r.context,callScenario:r.callScenario,direction:r.direction},teamsMeetingTenantId:this._teamsMeetingTenantId||``,teamsMeetingThreadId:this._teamsMeetingThreadId||``,callDurationInSeconds:this.tsCall.callStartedAt?Math.floor((Date.now()-this.tsCall.callStartedAt?.getTime())/1e3):-1,additionalDetails:this._state===`Disconnected`&&this._callEndReason?{...Y3(this._callEndReason)}:void 0})}}_setCallRole(e){if(e!==this._lastTsCallAdvancedMeetingRole){let t=iTe(Z(),e);t===E2?this.logger.log(`tsParticipant advancedMeetingRole=${this._role} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${e}=>${t}`),P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`role-changed`,oldAcsRole:this._role,newAcsRole:t,serviceRole:e||``}),this._role!=t&&(this.logger.log(`self-role changed ${this._role}=>${e}`),this._role=t,this._lastTsCallAdvancedMeetingRole=e,this._capabilityResolver.resolveCapabilitiesBasedOnRole(),this._eventEmitter.emit(`roleChanged`))}}_setMeetingCapabilities(e){oTe(e,this._lastTsCallMeetingDetails)&&(P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`meetingCapabilities-changed`,oldMeetingDetails:this._lastTsCallMeetingDetails,newMeetingDetails:e}),this.logger.log(`Core Meeting Capabilities has changed to: ${JSON.stringify(e)}`),this._capabilityResolver.resolveCapabilitiesBasedOnMeetingCapabilities(),this._eventEmitter.emit(`meetingCapabilitiesChanged`)),Object.assign(this._lastTsCallMeetingDetails,e)}removeRemoteAudioStream(e){if(e){if(this.logger.log(`Attempting to remove remote audio stream`),this._remoteAudioStreams.splice(this._remoteAudioStreams.indexOf(e),1).length===0)return void this.logger.warn(`Stream not found, failed to remove stream from remoteAudioStreams collection`);this.logger.log(`remote audio stream removed successfully`),this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:[],removed:[e]})}}async setOrUpdateMediaMetricsDeviceEvents(){if(Z().calling.mediaMetricsDeviceEventsEnabled)try{let e=await this.tsCall.getMediaSessionStatsAsync?.();if(e?.metrics?.DeviceEvents!==void 0){let t=JSON.parse(e.metrics.DeviceEvents),n=rTe(this._mediaMetricsDeviceEvents||{},t);n.length>0&&(this._mediaMetricsDeviceEvents=t,this.stats.recordEvent({name:l3.media_metrics_device_events,callId:this.id,localParticipantId:this.tsCall.participantId,data:{metricsDeviceEvents:n||{},metricsDevicesChangeCount:t?.metrics_DevicesChangeCount||0,metricsDevicesCount:t?.metrics_DevicesCount||{}}}))}else this.logger.info(`Failed to set media metrics device events telemetry: no valid events data`)}catch{this.logger.error(`Failed to set media metrics device events telemetry`)}}setClientCallStartOptions(e){let t={},n=0;return e?.firstPartyOptions?.isImmersiveMode&&(n|=32768),e?.firstPartyOptions?.accessToImmersiveEvents&&(n|=2097152),Z()?.calling?.supportLiveStreaming&&(n|=32),Z()?.calling.sharedLineAppearance.enabled&&(n|=128),Z()?.reaction?.enableReactionsThroughNGC&&(n|=524288),this._allowBreakoutRoomJoin&&(n|=4098),n>0&&(t.clientEndpointCapabilities=n),t.sendMediaModalities=this.setMediaModalities(e?.mediaModalities),t}setMediaModalities(e){if(e){let t={mediaStates:[]};return e.audio&&t.mediaStates.push({mediaType:0}),e.video?t.mediaStates.push({mediaType:1}):t.mediaStates.push({mediaType:1,isDisabled:!0}),e.screenShare||t.mediaStates.push({mediaType:2,isDisabled:!0}),t}}getLocalVideoStreamFromCallOptions(e){let t;if(Array.isArray(e?.videoOptions?.localVideoStreams)){if(e?.videoOptions?.localVideoStreams.length!==1)throw new Y({defaultError:J.CALL.ONLY_SINGLE_VIDEO_STREAM});if(t=e?.videoOptions?.localVideoStreams[0],!(t instanceof X6))throw new Y({defaultError:J.CALL.NOT_INSTANCE_OF_LVS})}return t}getLocalAudioStreamFromCallOptions(e){let t;if(Array.isArray(e?.audioOptions?.localAudioStreams)){if(e?.audioOptions?.localAudioStreams.length!==1)throw new Y({defaultError:J.CALL.ONLY_SINGLE_AUDIO_STREAM});if(t=e?.audioOptions?.localAudioStreams[0],!(t instanceof f8))throw new Y({defaultError:J.CALL.NOT_INSTANCE_OF_LAS})}return t&&(this._userProvidedLocalAudioStreamCache=t),t}async _setRawStream(e,t){if(!Z().calling.allowAccessRawMediaStream)throw new Y({defaultError:J.CALL.ACCESS_RAW_MEDIA_STREAM_DISABLED});let n=await this._callAgent.tsStack?.getDeviceManagerAsync?.();if(!n?.setRawMediaStream)throw new Y({defaultError:J.CALL.ACCESS_RAW_MEDIA_STREAM_UNDEFINED_FUNC});try{let r=await e.getMediaStream();if(!r)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_UNDEFINED});n.setRawMediaStream(r,t)}catch(e){if(t===1)throw new Y({defaultError:J.CALL.VIDEO_SET_MEDIA_STREAM,originalError:e});if(t===2)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_SET,originalError:e})}}shallRemoveLvsAfterConnectedSuccessfully(e,t,n,r,i,a,o){if(this.tsCall.localMediaStreams.find((e=>e.mediaType===1)))this.sendVideoEvent({correlationId:n,eventName:Q.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:r-i},localVideoStream:e,step:t,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:o}});else{if(!Z()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return;this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream);let r=+new Date,s=new Y({defaultError:J.CALL.VIDEO_FAILED_TO_START,defaultErrorMessageArgs:[t]});this.logger.error(s.message),this.sendVideoEvent({correlationId:n,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:r-i},localVideoStream:e,step:t,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:o}},s)}}shallRemoveLasAfterConnectedSuccessfully(e,t,n,r,i){if(this.tsCall.localMediaStreams.find((e=>e.mediaType===0)))this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.success,localAudioStream:e,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:``});else{if(!Z().calling.removeLocalAudioStreamCheckOnCallStartAndCallAccept)return;this.removeLocalAudioStream(this.localAudioStreams[0]);let r=+new Date;this.logger.error(`Removing local audio stream because audio failed to start during call-${t} process.`);let a=new Y({defaultError:J.CALL.AUDIO_FAILED_TO_START,defaultErrorMessageArgs:[t]});this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,localAudioStream:e,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...J3(a)}})}}createVideoNegotiationTag(t,n){let r=0,i=``;return n===`Video`?(r=++e.videoId,i=`v`):(r=++e.screenShareVideoId,i=`ss`),`${t};${i}_${r}`}_enableOrDisable_largeMeeting_videoRendering(){try{!this._isHandlingLargeMeetingVideoRendering&&this._totalParticipantCount-1>=Z().rendering.remoteVideo.largeMeeting.participantCountThreshold?(this._isHandlingLargeMeetingVideoRendering=!0,this._internalDominantSpeakersListener=new VDe(new w6(this.logger.createChild((()=>`DominanSpeakersFeatureInternal:: Call(id=${this.tsCall.callId})`)))),this._internalDominantSpeakersListener.initialize(this.tsCall,this._callAgent,this._telemetryLogManager,this.logger,!0),this.logger.info(`Initialized internal dominant speakers listener`),this._internalDominantSpeakersListener.on(`dominantSpeakersChanged`,(()=>{this.handleDominantSpeakersVideos()})),this.handleDominantSpeakersVideos(),this.logger.info(`Initialized large meeting video rendering handler`)):this._isHandlingLargeMeetingVideoRendering&&(this._totalParticipantCount-1>=Z().rendering.remoteVideo.largeMeeting.participantCountThreshold?this.handleDominantSpeakersVideos():(this._isHandlingLargeMeetingVideoRendering=!1,this._internalDominantSpeakersListener?.dispose(),this._internalDominantSpeakersListener=void 0,this.logger.info(`Disposed of internal dominant speakers listener`),this.remoteParticipants.forEach((e=>{e.videoStreams.forEach((e=>{e.setIsAvailable(e.tsStream.isAvailable)}))})),this.logger.info(`All remote streams isAvailable flags were reset`),this.logger.info(`Disposed large meeting video rendering handler`)))}catch(e){this.logger.error(`Failed to handle large meeting video rendering`,e)}}async handleConsentCapabilitiesChanges(){this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()&&(this.isMuted||this.mute().then((()=>{this.logger.log(`ExplicitConsentCallStateManager: Handle Capabilities changes: Mic is turned off :`,this.isMuted)})).catch((e=>{this.logger.error(`ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping mic`,e)})),this.isLocalVideoStarted&&this.localVideoStream&&this.stopVideo(this.localVideoStream).then((()=>{this.logger.log(`ExplicitConsentCallStateManager: Handle Capabilities changes: Video is turned off :`,this.isLocalVideoStarted)})).catch((e=>{this.logger.error(`ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping video`,e)})),this.isScreenSharingOn&&this.stopScreenSharing().then((()=>{this.logger.log(`ExplicitConsentCallStateManager: Handle Capabilities changes: Screenshare is turned off :`,this.isScreenSharingOn)})).catch((e=>{this.logger.error(`ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping screenshare`,e)})))}handleDominantSpeakersVideos(){this.logger.info(`Dominant speakers changed during large meeting`);let e=this.getTopNDominantSpeakersWithVideoOn();this.logger.info(`There are currently ${e.length} top-n speakers with video on in the large meeting`),e.forEach((e=>{e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).forEach((e=>{e.setIsAvailable(e.tsStream.isAvailable)}))})),this._remoteParticipants.filter((t=>!e.includes(t))).forEach((e=>{e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).forEach((e=>{try{e.setIsAvailable(!1)}catch(e){let t=new Y({defaultError:J.CALL.LARGE_MEETING_FORCE_ISAVAILABLE,originalError:e});this.logger.warn(t.message)}let t=this.activeRemoteVideoStreamViews.get(e.id);t&&t.forEach((e=>{try{e.disposed||(e.dispose(S3.Internal_LargeMeetingVideoRendering),this.logger.info(`Successfully disposed of view during large meeting`))}catch(e){let t=new Y({defaultError:J.CALL.LARGE_MEETING_DISPOSE_VIEW,originalError:e});this.logger.warn(t.message)}}))}))}))}};B7.videoId=0,B7.screenShareVideoId=0,R7([UG,z7(`design:type`,Object)],B7.prototype,`logger`,void 0),R7([JG(c4.BindToCall),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Array)],B7.prototype,`bindTsCall`,null),R7([JG(c4.Feature),z7(`design:type`,Function),z7(`design:paramtypes`,[Object]),z7(`design:returntype`,typeof(tLe=typeof TFeature<`u`&&TFeature)==`function`?tLe:Object)],B7.prototype,`feature`,null),R7([YG(c4.HangUp),z7(`design:type`,Function),z7(`design:paramtypes`,[Object]),z7(`design:returntype`,Promise)],B7.prototype,`hangUp`,null),R7([YG(c4.Mute),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`mute`,null),R7([YG(c4.Unmute),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`unmute`,null),R7([YG(c4.MuteAllRemoteParticipants),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`muteAllRemoteParticipants`,null),R7([YG(c4.MuteIncomingAudio),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`muteIncomingAudio`,null),R7([YG(c4.UnmuteIncomingAudio),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`unmuteIncomingAudio`,null),R7([YG(c4.SendDtmf),z7(`design:type`,Function),z7(`design:paramtypes`,[String]),z7(`design:returntype`,Promise)],B7.prototype,`sendDtmf`,null),R7([YG(c4.StartVideo),z7(`design:type`,Function),z7(`design:paramtypes`,[X6]),z7(`design:returntype`,Promise)],B7.prototype,`startVideo`,null),R7([YG(c4.StopVideo),z7(`design:type`,Function),z7(`design:paramtypes`,[X6]),z7(`design:returntype`,Promise)],B7.prototype,`stopVideo`,null),R7([YG(c4.StartAudio),z7(`design:type`,Function),z7(`design:paramtypes`,[f8]),z7(`design:returntype`,Promise)],B7.prototype,`startAudio`,null),R7([XG(c4.Hold),YG(c4.Hold),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`hold`,null),R7([XG(c4.Resume),YG(c4.Resume),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`resume`,null),R7([YG(c4.StartScreenShare),z7(`design:type`,Function),z7(`design:paramtypes`,[X6]),z7(`design:returntype`,Promise)],B7.prototype,`startScreenSharing`,null),R7([YG(c4.StopScreenShare),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`stopScreenSharing`,null),R7([YG(c4.SetConstraints),z7(`design:type`,Function),z7(`design:paramtypes`,[Object]),z7(`design:returntype`,Promise)],B7.prototype,`setConstraints`,null);var nLe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},V7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},H7=class extends B7{get info(){return this._info}constructor(e,t,n,r,i){super(e,t,n,r,GG.Call,i),this._info=this.callInfo,this._allowBreakoutRoomJoin=Z().calling.breakoutRooms.enabled}dispose(){super.dispose(),this._extensibleApi.dispose()}addParticipant(e,t){let n,r,i=t,a=t,o=t,s=+new Date,c=J0();if(this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{attemptTimestamp:s},additionalDetails:{customContext:{userToUserPresent:!!i?.customContext?.userToUser,xHeadersPresent:!!i?.customContext?.xHeaders&&i?.customContext.xHeaders.length>0}}}),this._callAgent.isEnterpriseUser())switch(this.validateThreadId(e,t),OG(e).kind){case`communicationUser`:r=i.threadId;break;case`microsoftTeamsUser`:r=o.threadId;break;case`phoneNumber`:r=a.threadId;break;default:{let e=new Y({defaultError:J.CALL.ADD_UNKNOWN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:e.code,failureReason:e.message,...J3(e)}}),e}}let l;a?.alternateCallerId&&(Y2(a.alternateCallerId),n=K2(a.alternateCallerId));try{if(t7(c4.AddParticipant,this.state),l=Y2(e),!B4(this.acsProxy,this.acsCustomRelayManager,!1,l))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}catch(e){throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:e.code,failureReason:e.message,...J3(e)}}),e}if(this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)))){let t=new Y({defaultError:J.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[OG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:t.code,failureReason:t.message,...J3(t)}}),t}let u=[...this.remoteParticipants.values()].map((e=>e.identifier));this._isAcsTeamsCall=V4([...u,e],this._callAgent.kind),Z().calling.enableSmePassFakeConversation&&this._isAcsTeamsCall&&!r&&(r=this.tsCall.threadId||H4());let d=sTe(lTe(this),OG(e));Z().calling.enableOpsSmePassFakeConversation&&d&&!r&&(r=this.tsCall.threadId||H4());let f=PG();L6.setCauseIdToNetworkInfo(f);let p=this.getOrCreateRemoteParticipant(q2(K2(e)));return this.tsCall.addParticipant(K2(e),{alternateId:n,threadId:r,customHeaderContext:U4(a)},f).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},networkInfo:L6.getRemoveCauseIdToNetworkInfo(f)})})).catch((t=>{let{callEndReason:n}=W3(this,p.tsRemoteParticipant,t);p.callEndReason||p.setCallEndReason(n);let r=Y3(n);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:r?.callEndReason.code,subCode:r?.callEndReason.subCode,failureReason:r?.callEndReason.message,...r},networkInfo:L6.getRemoveCauseIdToNetworkInfo(f)}),this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)))&&(this.deleteRemoteParticipant(p),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:[p]}))})),p}async removeParticipant(e,t){let n=+new Date,r=J0();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{attemptTimestamp:n}});try{t7(c4.RemoveParticipant,this.state),Y2(e)}catch(e){let t=new Y({defaultError:J.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...J3(t)}}),t}let i=this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)));if(!i){let t=new Y({defaultError:J.CALL.PARTICIPANT_NOT_IN_CALL,defaultErrorMessageArgs:[OG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:t.code,subCode:t.subCode,failureReason:t.message,...J3(t)}}),t}let a=PG();L6.setCauseIdToNetworkInfo(a);try{await this.tsCall.removeParticipant(K2(e)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},networkInfo:L6.getRemoveCauseIdToNetworkInfo(a)})}catch(e){let t=W3(this,i.tsRemoteParticipant,e).callEndReason;i.callEndReason||i.setCallEndReason(t);let o=Y3(t);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:o?.callEndReason.code,subCode:o?.callEndReason.subCode,failureReason:o?.callEndReason.message,...o},networkInfo:L6.getRemoveCauseIdToNetworkInfo(a)}),new Y({defaultError:{message:t.message,code:t.code,subCode:t.subCode||0,resultCategories:t.resultCategories},originalError:e})}}validateThreadId(e,t){if(!t?.threadId)throw new Y({defaultError:J.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID})}};nLe([JG(c4.AddParticipant),V7(`design:type`,Function),V7(`design:paramtypes`,[Object,Object]),V7(`design:returntype`,Object)],H7.prototype,`addParticipant`,null),nLe([YG(c4.RemoveParticipant),V7(`design:type`,Function),V7(`design:paramtypes`,[Object,Object]),V7(`design:returntype`,Promise)],H7.prototype,`removeParticipant`,null);var rLe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},U7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},W7=class{get kind(){return this._kind}get id(){return this._callCommon.id}get callerInfo(){return this._callCommon.callerInfo}get transferorInfo(){return this._callCommon.transferorInfo}get callEndReason(){return this._callCommon.callEndReason}get customContext(){return this._customContext}constructor(e,t){this._callCommon=e,this._eventEmitter=new E3.EventEmitter,this._kind=t,this._callConnected=this._callCommon.state===`Connected`,this._customContext=fTe(this._callCommon.tsCall),this._callCommon.on(`stateChanged`,(()=>{this._callCommon.state===`Connected`?this._callConnected=!0:this._callCommon.state!==`Disconnected`||this._callConnected||this._eventEmitter.emit(`callEnded`,{callEndReason:this._callCommon.callEndReason})})),this._callCommon.on(`callerInfoChanged`,(()=>{this._eventEmitter.emit(`callerInfoChanged`)})),this._callCommon.on(`transferorInfoChanged`,(()=>{this._eventEmitter.emit(`transferorInfoChanged`)}))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}reject(){return this._callCommon.reject()}};rLe([YG(),U7(`design:type`,Function),U7(`design:paramtypes`,[]),U7(`design:returntype`,Promise)],W7.prototype,`reject`,null);var iLe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},G7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},aLe=class extends W7{get info(){return this._call.info}constructor(e){super(e,KG.IncomingCall),this._call=e}async accept(e){if(this.info?.initiatorKind===`microsoftTeamsUser`&&!B4(this._call.acsProxy,this._call.acsCustomRelayManager,!0))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._call.accept(e),this._call}};iLe([YG(c4.Accept),G7(`design:type`,Function),G7(`design:paramtypes`,[Object]),G7(`design:returntype`,Promise)],aLe.prototype,`accept`,null);var K7={callNotification:`callNotification`,conversationInvitation:`conversationInvitation`,debugContent:`debugContent`,groupContext:`groupContext`},oLe=class{get callId(){return this._callId}get localParticipantId(){return this._localParticipantId}constructor(e,t,n){if(this._callId=``,this._localParticipantId=``,this._logger=n.createChild(`IncomingCallPushNotificationHandler`),!e.incomingCallContext)throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD_NO_CONTEXT_PROVIDED});if(Object.keys(e).length>1)throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_PAYLOAD_TOO_MANY_KEYS});if(this._payload=e,this._incomingCallContext=this._payload.incomingCallContext,this._tsCallRegistry=t,this._gp=JSON.parse(t3.inflate(atob(this._incomingCallContext),{to:`string`})),!(this._gp.hasOwnProperty(K7.callNotification)&&this._gp.hasOwnProperty(K7.conversationInvitation)&&this._gp.hasOwnProperty(K7.debugContent)&&this._gp.hasOwnProperty(K7.groupContext)))throw this._logger.error(`Missing incoming call context data. Found: ${Object.keys(this._gp)}`),new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD});this._callId=this._gp.debugContent.callId,this._localParticipantId=this._gp.debugContent.participantId}async process(){try{if(this._tsCallRegistry.calls.some((e=>e.callId==this._callId)))throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_ALREADY_PROCESSED});let e=n3(),t=t=>{let n=()=>{t.callId===this._callId&&t.participantId===this._localParticipantId&&t.state===1&&e.resolve()};this._tsCallStateSub=t.on(`callStateChanged`,n),n()};this._tsCallRegistrySub=this._tsCallRegistry.on(`callAdded`,t);let n={eventId:ZCe,body:{gp:this._gp}};if(!this._tsCallRegistry.incomingCallMessageHandler.handleMessage(n))throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_FAILED_TO_PROCESS});setTimeout((()=>{e.isPending()&&e.reject(new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_CALL_MISSED}))}),5e3),await e.promise}catch(e){throw e}finally{this._tsCallRegistrySub?.dispose(),this._tsCallStateSub?.dispose()}}},q7=0,sLe=220004,cLe=220005,lLe=220006,uLe=220007,dLe=class{constructor(e){this._httpRequestHelper=e,this._isPolicyFetchApplicable=!1,this._policySettingData={},this._threadIdData={};let t=ZW(`ACS`);this._logger=new V6(t)}initialize(e){this._localParticipant=e.localParticipant,this._jwtTokenProvider=e.jwtTokenProvider,this._telemetryLogManager=e.telemetryLogManager}userDialedNumber(e){this._userDialedPstnNumber=e,this._emergencyNumber=this._userDialedPstnNumber}async CreateChatThreadId(e,t){this._callId=e;let n=+new Date,r=t?.createThreadIdSuffix??Z().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix;this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.attempt});let i=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(),a=new URL(r,Z().MiddleTier.baseServiceUrl);t?.participants.push({id:this._localParticipant});let o={Participants:t?.participants};try{let e=await this._httpRequestHelper.send(a.toString(),o,{method:L3.POST,headers:i},Z().MiddleTier.maxRetry);if(this._threadIdData=await this._httpRequestHelper.extractPayload(e),!this._threadIdData)throw Error(`ThreadIdData is null or undefined`);return this._logger.info(`Successfully created chat thread using ACS MiddleTier Service.`),this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{phrase:`Thread Id was successfully created from ACS MiddleTier Service`,code:q7,subCode:lLe}}),Promise.resolve(this._threadIdData.threadId)}catch{this._logger.error(`Error creating thread Id from ACS MiddleTier Service`);let e=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...J3(e)}}),e}}async AddParticipantsToThread(e,t){this._callId=e;let n=+new Date,r=t?.addParticipantsSuffix??Z().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix;this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.attempt});let i=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(),a=new URL(r,Z().MiddleTier.baseServiceUrl),o={threadId:t?.threadId,Participants:t?.participants};try{let e=await this._httpRequestHelper.send(a.toString(),o,{method:L3.POST,headers:i},Z().MiddleTier.maxRetry),t=await this._httpRequestHelper.extractPayload(e);if(!t)throw Error(`AddParticipantToThreadResponseData is null or undefined`);if(this._logger.info(`Call to add participants to chat thread using ACS MiddleTier Service`),t!==null){if(!t.isSuccess)throw new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});t.multipleStatus.length>0&&t.multipleStatus[0].statusCode==735&&this._logger.info(`Trying to add the same participant to the thread id`)}return this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{phrase:`Successfully add participants from ACS MiddleTier Service`,code:q7,subCode:uLe}}),Promise.resolve(t.isSuccess)}catch{this._logger.error(`Fail to add participant error from ACS MiddleTier Service`);let e=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...J3(e)}}),e}}async fetchUserPoliciesFromAcsMiddleTier(e,t,n){this._policySettingData=await this.requestUserPoliciesFromAcsMiddleTier(e,t,n)}async requestUserPoliciesFromAcsMiddleTier(e,t,n,r){this._callId=e;let i=+new Date;if(this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.attempt},t),!t){let e=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMS_USER_ID_NOT_PROVIDED});throw this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-i},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...J3(e)}}),e}let a,o={},s=Z().MiddleTier.baseServiceUrl;n?(a=new URL(n.policyUrlSuffix,s),o={id:t,dialstring:this._userDialedPstnNumber,userPolicies:n.userPolicies,userProperties:n.userProperties}):(a=new URL(Z().MiddleTier.policyUrlSuffix,s),o={id:t});let c=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(r);try{let e=await this._httpRequestHelper.send(a.toString(),o,{method:L3.POST,headers:c},Z().MiddleTier.maxRetry);this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-i},additionalDetails:{phrase:`Teams user policy was fetched successfully from ACS MiddleTier Service`,code:q7,subCode:sLe}},t);let n=await this._httpRequestHelper.extractPayload(e);if(!n)throw Error(`PolicySettingsData is null or undefined`);return n}catch(e){let n=iDe(e,J.CTE_MID_TIER_POLICY_SERVICE.FETCH_POLICY);throw this._logger.error(n.message),this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-i},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...J3(n)}},t),n}}isEvEnabled(){return this._policySettingData?.userAggregatedPolicySettingData?.userProperties?.evEnabled||!1}isMoHEnabled(){let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsCallingPolicy?.musicOnHoldEnabledType;return this._logger.info(`Checking Music on Hold Policy, Enabled Type is: `+e),e===(x4.Enabled||x4.UserOverride)}isBreakoutRoomsAllowed(){let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy?.allowBreakoutRooms;return this._logger.info(`Allow Breakout rooms from Teams meeting policy is `+e),e??=!0,e}isIPAudioAllowed(){if(!Z().calling.mediaAccess.ipMediaPolicyEnabled)return this._logger.info(`Allow IP audio is true as feature flag ipAudioVideoPolicyEnabled is false`),!0;let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy?.ipAudioMode!==C4.Disabled;return this._logger.info(`Allow IP audio from Teams meeting policy is `+e),e}isIPVideoAllowed(){if(!Z().calling.mediaAccess.ipMediaPolicyEnabled)return this._logger.info(`Allow IP video is true as feature flag ipAudioVideoPolicyEnabled is false`),!0;let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy?.ipVideoMode!==C4.Disabled;return this._logger.info(`Allow IP video from Teams meeting policy is `+e),e}getTeamsUserCaptionsPoliciesData(){let e=+new Date,t=``;this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.attempt});let n=this._policySettingData.userAggregatedPolicySettingData,r=n?.userPolicies,i=n?.userProperties;if(!r?.teamsCallingPolicy){let t=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_CALLINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}})}if(!r?.teamsMeetingPolicy){let t=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_MEETINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}})}if(!i?.featureTypes){let t=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_FEATURETYPE_TEAMSPROMGMT_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}})}return(r?.teamsCallingPolicy||r?.teamsMeetingPolicy||i?.featureTypes?.includes(U2.TeamsProMgmt))&&(t=JSON.stringify({isLiveCaptionsEnabledForCalling:r?.teamsCallingPolicy?.liveCaptionsEnabledTypeForCalling===W2.DisabledUserOverride,isLiveCaptionsEnabledForMeeting:r?.teamsMeetingPolicy?.liveCaptionsEnabledType===W2.DisabledUserOverride,isTeamsProMgmtSkuAvailable:i?.featureTypes?.includes(U2.TeamsProMgmt)??!1}),this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{phrase:`Fetching Captions policy from ACS MiddleTier Service response was successful`,code:q7}}),this._logger.info(`Fetching user's captions policy content = ${t}`)),t}getEmergencyContent(){let e=+new Date;this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_emergency_content,kindOfEvent:$.attempt});let t=``;try{let n=this._policySettingData.userAggregatedPolicySettingData,r=n?.userPolicies,i=this.getEmergencyPolicyDetails(r,this._userDialedPstnNumber,n);i.foundEmergencyNumberMatch&&(t=JSON.stringify(i.emergencyContent));let a=i.foundEmergencyNumberMatch?`Created Emergency policy using ${i.logInfo}`:`This is NOT an emergency call`;return this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_emergency_content,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{phrase:`Deriving Emergency policy from ACS MiddleTier Service response was successful`,code:q7,subCode:cLe}}),this._logger.info(`Deriving emergency policy message = ${a}. Emergency Content = ${t}`),t}catch(t){let n=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.DERIVE_EMERGENCY_POLICY,originalError:t});throw this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_emergency_content,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...J3(n)}}),n}}isEmergencyNumber(e,t){if(!t)return this._logger.info(`Not an emergency number, no participants`),!1;if(!this.isFetchUserPoliciesAndSettingsApplicable(e,t))return this._logger.info(`Fetch user policies and settings not applicable`),!1;let n=Array.isArray(t)&&t.length>0?t[0].phoneNumber:t.phoneNumber,r=this._policySettingData.userAggregatedPolicySettingData,i=r?.userPolicies,a=this.getEmergencyPolicyDetails(i,n,r);return this._logger.info(`Emergency number check result: ${a.foundEmergencyNumberMatch}`),a.foundEmergencyNumberMatch}getEmergencyPolicyDetails(e,t,n){let r=!1,i=``,a={};if(e?.locationPolicy?.emergencyNumbers){let o=e.locationPolicy.emergencyNumbers||[];this.isPhoneNumberInLocationPolicy(o,t)&&(r=!0,a={enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:n?.userProperties.region,locationPolicyTag:e?.locationPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:e?.teamsEmergencyCallingPolicy?.policyDocument},i=`LocationPolicy`)}if(!r&&e?.teamsEmergencyCallRoutingPolicy){let o=e?.teamsEmergencyCallRoutingPolicy?.emergencyNumbers||[];this.isPhoneNumberInTeamsEmergenencyRoutingPolicy(o,t)&&(r=!0,a={enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:n?.userProperties.region,teamsEmergencyCallRoutingPolicyTag:e?.teamsEmergencyCallRoutingPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:e?.teamsEmergencyCallingPolicy?.policyDocument},i=`TeamsEmergencyCallingRoutingPolicy`)}return{foundEmergencyNumberMatch:r,logInfo:i,emergencyContent:a}}isFetchUserPoliciesAndSettingsApplicable(e,t){return r4(e)||r4(t)||(this._isPolicyFetchApplicable=this.verifyFetchUserPoliciesSettings(e,t)),this._isPolicyFetchApplicable}getEmergencyNumber(){return this._emergencyNumber}getUserDialedPstnNumber(){return this._userDialedPstnNumber}getUserPolicy(){return this._policySettingData.userAggregatedPolicySettingData?.userPolicies}getUserProperties(){return this._policySettingData.userAggregatedPolicySettingData?.userProperties}isPhoneNumberInLocationPolicy(e,t){if(!r4(e)&&t){for(let n of e)if(n.dialString===t||!r4(n.dialMask?.split(`;`).find((e=>e===t))))return this._emergencyNumber=n.dialString,!0}return!1}isPhoneNumberInTeamsEmergenencyRoutingPolicy(e,t){if(!r4(e&&t)){for(let n of e)if(n.emergencyDialString===t||!r4(n.emergencyDialMask?.split(`;`).find((e=>e===t))))return this._emergencyNumber=n.emergencyDialString,!0}return!1}verifyFetchUserPoliciesSettings(e,t){let n=Z().MiddleTier;return n.enabled?n.userPolicySettingsApi?e?Array.isArray(t)&&(t.length>1||!TG(t[0]))?(this._logger.info(`Target particpant (Callee) is not a PSTN Number`),!1):Array.isArray(t)||TG(t)?(this._logger.info(`Teams user is eligible to fetch policies and settings from MiddleTier Service `),!0):(this._logger.info(`Target particpant (Callee) is not a PSTN Number`),!1):(this._logger.info(`Originator (Caller) is not a Teams User`),!1):(this._logger.info(`ACS MiddleTier Policy API is disabled`),n.userPolicySettingsApi):(this._logger.info(`ACS MiddleTier service is disabled`),n.enabled)}isSecurityDeskEnabled(){let e=this._policySettingData.userAggregatedPolicySettingData?.userPolicies?.teamsEmergencyCallingPolicy;return!(r4(e?.notificationGroup)&&r4(e?.notificationDialOutNumber)||e?.notificationGroup?.trim().length==0&&e?.notificationDialOutNumber?.trim().length==0)}async getAcsMiddletierServiceRequestHeader(){return{"Content-Type":`application/json`,"X-Skypetoken":this._jwtTokenProvider?await this._jwtTokenProvider():``,"Access-Control-Allow-Origin":`*`,"X-Microsoft-Skype-Chain-ID":this._callId}}async getAcsMiddletierServiceRequestHeaderForThreadApi(e){let t={};return t=await this.getAcsMiddletierServiceRequestHeader(),t.onbehalfOfUser=e??this._localParticipant,t}sendMiddleTierPolicyEvent(e,t){try{this.setDefaultEventData(e,t),this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this._logger.debug(`Unable to send AcsMiddleTierPolicyService telemetry`)}}sendMiddleTierApiEvent(e){try{this.setDefaultEventData(e),this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this._logger.debug(`Unable to send MiddleTier Api telemetry`)}}setDefaultEventData(e,t){e.callId=this._callId,e.localParticipantId=this._localParticipant,e.requestedParticipantMRI=t??this._localParticipant,e.timestampInfo=e.timestampInfo??``,e.additionalDetails=e.additionalDetails??``}},fLe=class{constructor(e){this._logger=e}get gpu(){let e={};try{let t=document.createElement(`canvas`),n=t.getContext(`webgl`)||t.getContext(`experimental-webgl`);if(n){let t=n.getExtension(`WEBGL_debug_renderer_info`);t?(e.vendor=n.getParameter(t.UNMASKED_VENDOR_WEBGL),e.renderer=n.getParameter(t.UNMASKED_RENDERER_WEBGL)):this._logger?.info(`Unable to get GPU info: debug renderer info is not supported`)}else this._logger?.info(`Unable to get GPU info: WebGL is not supported`)}catch(e){this._logger?.info(`Unable to get GPU info: ${e}`)}return e}get hardwareConcurrency(){return navigator.hardwareConcurrency}},J7;(function(e){e.deviceSelection=`deviceSelection`,e.createCallAgent=`createCallAgent`,e.createTeamsCallAgent=`createTeamsCallAgent`,e.disposeCallAgent=`disposeCallAgent`,e.disposeTeamsCallAgent=`disposeTeamsCallAgent`,e.disposeCallClient=`disposeCallClient`,e.handleIncomingCall=`handleIncomingCall`,e.startPreheatDevices=`startPreheatDevices`,e.stopPreheatDevices=`stopPreheatDevices`})(J7||={});var pLe,Y7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},X7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},mLe=1,Z7=class{get customContext(){return this._customContext}get kind(){return this._kind}get connectionState(){return this._connectionState}constructor(e,t,n,r,i,a,o){this._callClient=e,this._customContext={callId:``,customContext:{}},this._pushHandlingDeltaTimeInMs=new Map,this._disposed=!1,this.tokenProvider=async e=>{let t=+new Date,n;try{if(this.sendTokenChangedEvent({kindOfEvent:`attempt`,timestampInfo:{attemptTimestamp:t},oldTokenExpiration:this._oldTokenExpiration}),!this._communicationTokenCredential)throw new Y({defaultError:J.CALL_AGENT.GET_TOKEN_BEFORE_INIT});n=await P4(this._communicationTokenCredential,Z().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),n.acsResourceId===this._parsedTokenCredential?.acsResourceId&&n.identityMri===this._parsedTokenCredential?.identityMri||j4(J.CALL_AGENT.REFRESHED_TOKEN_INVALID_USERID,this.logger),e?this._tokenFetchTries+=1:this._tokenFetchTries=0,this._tokenFetchTries>this._maxNmberOfRetries&&(this.updateConnectionState(`invalidToken`),this._disposed||await this.dispose(),j4(J.CALL_AGENT.REFRESHED_TOKEN_RETRIES,this.logger));let r=+new Date;return this.sendTokenChangedEvent({kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:r-t},oldTokenExpiration:this._oldTokenExpiration,newTokenExpiration:n.exp,isTokenChanged:this._oldToken!==n.jwtToken}),this._oldToken=n.jwtToken,this._oldTokenExpiration=n.exp,n.jwtToken}catch(e){let r={kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-t},oldTokenExpiration:this._oldTokenExpiration};throw n&&(r.newTokenExpiration=n.exp,r.isTokenChanged=this._oldToken!==n.jwtToken,this._oldToken=n.jwtToken,this._oldTokenExpiration=n.exp),this.sendTokenChangedEvent(r,e),e}},this.sendTokenChangedEvent=(e,t)=>{try{let n={kindOfEvent:e.kindOfEvent,timestampInfo:e.timestampInfo,oldTokenExpiration:e.oldTokenExpiration};e.newTokenExpiration!==void 0&&(n.newTokenExpiration=e.newTokenExpiration),e.isTokenChanged!==void 0&&(n.isTokenChanged=e.isTokenChanged),t&&(n={...n,...J3(t)}),this._telemetryLogManager.sendEvent({name:Q.acs_calling_token_expiration_changed,tenant:p2,properties:n})}catch{this.logger.debug(`Unable to send token change telemetry`)}},this.pushHandlingStarted=e=>{let t=J0();this._pushHandlingDeltaTimeInMs.set(e,{correlationId:t,timestamp:+new Date}),this.logger.log(`Incoming call state started`,e),L6.setCauseIdToNetworkInfo(e),this.sendIncomingNotificationEvent({eventName:Q.acs_calling_client_operations,operation:J7.handleIncomingCall,networkInfo:[],kindOfEvent:`attempt`,timestampInfo:{deltaTimeInMs:void 0},correlationId:t,additionalDetails:{},callId:``,participantId:``})},this.pushNotificationParsed=(e,t)=>{if(this.logger.debug(`pushNotificationParsed event received ${e}`),t.customContext.sipHeaders||t.customContext.voipHeaders){let{sipHeaders:e,voipHeaders:n}=t.customContext,r={sipHeaders:W4(e),voipHeaders:W4(n)},i=e=>`sipHeaders: ${e?.sipHeaders?.length||0}, voipHeaders: ${e?.voipHeaders?.length||0}`;if(!e4.isEqual(this._customContext.customContext,r)){this.sendCallAgentInfoEvent({eventName:Q.acs_calling_call_agent,additionalDetails:{step:`customContext-changed`,callId:t.callId,oldState:i(this._customContext.customContext),newState:i(r)}});let e={...this._customContext};this._customContext={callId:t.callId,customContext:r},this._eventEmitter.emit(`customContextChanged`,{oldValue:e,newValue:{...this._customContext}})}}},this.pushHandlingEnded=(e,t)=>{let n=t?.code!==void 0&&[0,200].includes(t?.code),r=e=>{if(n)return new Y({defaultError:{code:e?.code??0,subCode:e?.subCode??0,message:`Success`,resultCategories:[`Success`]}});let t=[J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_INVALID_NOTIFICATION_PAYLOAD,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_FAILED_TO_EXTRACT_PAYLOAD,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_ALREADY_HANDLED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_IGNORING_DUPLICATE_NOTIFICATION,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_FAILED_TO_HANDLE_NOTIFICATION_FOR_GROUPID_CALL,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_BAD_NOTIFICATION_PAYLOAD,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_SUCCEEDED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_FAILED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_BAD_NOTIFICATION_EVENT_TYPE,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_ALREADY_EXISTS,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CANNOT_CONNECT,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_NO_SIGNALING,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CONFLICT,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_PUSH_IGNORED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_ANSWERED_ELSEWHERE,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CALL_ALREADY_ENDED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_IN_PROGRESS];return new Y({defaultError:e4.find(t,(t=>t.subCode===e?.subCode))??J.CALL_AGENT.INVALID_PUSH_NOTIFICATION_DATA})};this.logger.log(`Incoming call state ended`,e,t);let i=L6.getRemoveCauseIdToNetworkInfo(e),a=this._pushHandlingDeltaTimeInMs.get(e)?.correlationId||`unknown`,o=r(t);this.sendIncomingNotificationEvent({eventName:Q.acs_calling_client_operations,operation:J7.handleIncomingCall,networkInfo:i||[],kindOfEvent:n?`success`:`failure`,timestampInfo:{deltaTimeInMs:this._pushHandlingDeltaTimeInMs.has(e)?+new Date-this._pushHandlingDeltaTimeInMs.get(e)?.timestamp:void 0},correlationId:a,additionalDetails:{...J3(o)},callId:t.callId||``,participantId:t.participantId||``}),this._pushHandlingDeltaTimeInMs.delete(e),this._eventEmitter.emit(`handleIncomingCall`,{callId:t.callId||``,participantId:t.participantId||``,...Y3({code:o.code,subCode:o.subCode,message:o.message,resultCategories:o.resultCategories})})},this.logger=t.createChild(`CallAgent`+ mLe++),this._telemetryLogManager=r,this._kind=a,this._connectionState=`Disconnected`,this._eventEmitter=new w6(this.logger),this._internalEventEmitter=new E3.EventEmitter,this.clientId=n,this._abortController=new AbortController,this._maxDisplayNameLength=Z()?.calling?.maxDisplayNameLength||XCe,this._oldToken=``,this._oldTokenExpiration=0,this._tokenFetchTries=0,this._maxNmberOfRetries=Z()?.calling?.maxNumberOfTokenFetchRetries||zCe,this._callStack=i,this.callClient=this._callClient,this.deviceManager=o,this.acsProxy=this.callClient.acsProxy,this.acsCustomRelayManager=this.callClient.acsCustomRelayManager,this._httpRequestHelper=new UEe(this.logger,this.acsProxy),this.mtPolicyService=new dLe(this._httpRequestHelper),this._parsedTokenCredential=eTe(),this._caConfigBag={clientId:``,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?t2.Enterprise:t2.Consumer,region:this._parsedTokenCredential.region,emergencyCountryCode:void 0,IsUserEmergencyCountryCode:!1,mriType:this._parsedTokenCredential.mriType,parsedTokenCredential:this._parsedTokenCredential},this._extensibleApi=new F3(this.logger,{callClient:this.callClient,callAgent:this},{tsStack:this.tsStack,callAgent:this,telemetryLogManager:this._telemetryLogManager});let s=e7(k3.CallAgentFeature);for(let e of s)e.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(e);this._trouterStateChangeCallback=e=>{this.logger.log(`Callback Trouter state changed to ${e}`),this.updateConnectionState(`trouterChanged`)},this._registrarStateChangeCallback=e=>{this.logger.log(`Callback Registrar state changed to ${e}`),this.updateConnectionState(`registrarChanged`)}}getHttpRequestHelper(){return this._httpRequestHelper}getTrouterState(){return this._callStack?this._callStack.getTrouterState():`Unknown`}onTrouterStateChanged(e){return this._callStack.onTrouterStateChanged(e)}offTrouterStateChanged(e){return this._callStack.offTrouterStateChanged(e)}onDisposed(e){this._internalEventEmitter.on(`disposed`,e)}getAcsResourceId(){return this._parsedTokenCredential?.acsResourceId||``}getUserMri(){return`8:${this._parsedTokenCredential?.identityMri}`||``}getUserPolicy(){return this._userPolicies}getUserProperties(){return this._userProperties}getInternalCallRegistry(){return this._tsCallRegistry}async initialize(e,t){let n=+new Date,r=new fLe(this.logger),i={gpu:r.gpu,hardwareConcurrency:r.hardwareConcurrency};try{if(this.sendCallAgentInitializiedEvent(Q.acs_calling_call_agent_init_attempt,{attemptTimestamp:n},i),this._communicationTokenCredential=e,this._parsedTokenCredential=await P4(e,Z().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),this._kind!==WG.TeamsCallAgent||this._parsedTokenCredential.isEnterpriseUser?this._kind===WG.CallAgent&&this._parsedTokenCredential.isEnterpriseUser&&j4(J.CALL_AGENT.ACS_CALLAGENT_TOKEN_ONLY,this.logger):j4(J.CALL_AGENT.TEAMS_CALLAGENT_TOKEN_ONLY,this.logger),t?.displayName){if(this._parsedTokenCredential.isEnterpriseUser)throw new Y({defaultError:J.CALL_AGENT.ENTERPRISE_DISPLAY_NAME});if(t?.displayName.length>this._maxDisplayNameLength)throw new Y({defaultError:J.CALL_AGENT.DISPLAY_NAME_TOO_LONG})}if(this._parsedTokenCredential.cloudType===X0.Public&&(!this._parsedTokenCredential.region||this._parsedTokenCredential.region===``)){try{let e=+new Date-n;this._telemetryLogManager.sendEvent({name:Q.acs_calling_token_has_no_data_location,tenant:p2,properties:{deltaTimeInMs:e}})}catch{this.logger.debug(`Unable to send token has no data location assigned`)}this._parsedTokenCredential.region=this._parsedTokenCredential.rgnClaimExists?wSe[0]:r2[0],this.logger.info(`Used default data location because token has no data location assigned`)}this._caConfigBag={clientId:this.clientId,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?t2.Enterprise:t2.Consumer,emergencyCountryCode:t?.emergencyCallOptions?.countryCode,region:this._parsedTokenCredential.region,IsUserEmergencyCountryCode:!!t?.emergencyCallOptions?.countryCode,mriType:this._parsedTokenCredential.mriType,parsedTokenCredential:this._parsedTokenCredential},this.addToCallAgentsMap(this._parsedTokenCredential),this._disposed=!1;try{this.runningEnvironmentInfo=await this.callClient.getEnvironmentInfoInternal()}catch{this.logger.debug(`Unable to get the running environment info`)}if(this.tsStack=await this._callStack.initializeStackForUser(this.tokenProvider,this._caConfigBag),this._parsedTokenCredential.rgnClaimExists)try{await this.updateParsedTokenCredentials(e)}catch(e){this.logger.debug(`Failed to update parsed token credentials. Error message = ${e?.message||``}`)}await this.setUserPoliciesOnAgentInitialization(),this.isEnterpriseUser()&&(t={...t,displayName:this._userProperties?.displayName??void 0}),this._telemetryLogManager.initialize(this._caConfigBag),this._tsCallRegistry=await this.initializeCallRegistry(this.tsStack,t),this.registerConnectionStateEventHandlers();let r=+new Date;this.sendCallAgentInitializiedEvent(Q.acs_calling_call_agent_init_success,{deltaTimeInMs:r-n},i)}catch(e){this._caConfigBag&&!this._telemetryLogManager.isInitialized()&&this._telemetryLogManager.initialize(this._caConfigBag);let t=new Y({defaultError:J.CALL_AGENT.INIT_FAIL,originalError:e});this.removeFromCallAgentsMap(this._parsedTokenCredential);let r=+new Date;throw this.sendCallAgentInitializiedEvent(Q.acs_calling_call_agent_init_failure,{deltaTimeInMs:r-n},i,t),t}}handleActiveCallTransfer(e){this.logger.info(`CallAgent handling active call transfer for callId=${e.id}`),this._eventEmitter.emit(`callsUpdated`,{added:[e],removed:[]})}async setUserPoliciesOnAgentInitialization(){this.mtPolicyService.initialize({localParticipant:this.getUserMri(),jwtTokenProvider:this.tokenProvider,telemetryLogManager:this._telemetryLogManager})}isEnterpriseUser(){return this._parsedTokenCredential?.isEnterpriseUser!==void 0&&this._parsedTokenCredential?.isEnterpriseUser}isTeamsExtensionUser(){return this._parsedTokenCredential?.mriType!==void 0&&this._parsedTokenCredential?.mriType==n2.TeamsExtensionUser}getClientId(){return this.clientId}getCallByCallId(e,t){return t?this._tsCallRegistry.getCall(e,t):this._tsCallRegistry.calls.filter((t=>t.callId===e))?.[0]}async createTransferTargetCall(e){let t=PG(),n=J0(),r=J0(),i=await this._tsCallRegistry.createCallAsync({callId:n,localParticipantId:r,causeId:t,type:`ThreadId`,threadId:``}),a=this.createNewCall(n,i);return this.addToCallArray(a),this.handleCallState(a),i.addParticipant(e.targetMri).catch((()=>{this.logger.error(`Failed to add participant for transer call`)})),G6(i)?await Promise.all(a.bindTsCall()):a.bindTsCall(),this._eventEmitter.emit(`callsUpdated`,{added:[a],removed:[]}),a}async subscribeCallWithoutModality(e){let t=PG(),n=await this._tsCallRegistry.createCallAsync({callId:e.callId,localParticipantId:e.participantId,causeId:t,type:`ThreadId`,threadId:e.threadId,messageId:e.messageId}),r=this.createNewCall(e.callId,n),i={conversationUrl:e.meetingUrl,conversationId:e.callId};return this.addToCallArray(r),this.handleCallState(r),n.joinCallWithoutCallModality(i,{},t).then((()=>{this.logger.info(`Successfully joined call without modalities`)})).catch((e=>{throw this.logger.error(`Error while joining call without modalities`,e),new Y({defaultError:J.CALL_AGENT.INVALID_JOIN_LOCATOR,originalError:e})})),G6(n)?await Promise.all(r.bindTsCall()):r.bindTsCall(),r}getEcsConfigIds(){return this._callStack.getEcsConfigIds()}getDeviceType(){let e=this.callClient?.firstPartyOptions?.acsDeviceType;return e?iwe[e]:`default`}isWatermarkSupported(){return this.isEnterpriseUser()?Z().calling.watermark.watermarkEnabledForCteUsers:Z().calling.watermark.watermarkEnabledForAcsUsers}feature(e){return this._extensibleApi.getApiObjectInstance(e.callAgentApiCtor)}async handlePushNotification(e){let t=J0(),n=+new Date,r;try{if(this.sendHandlePushNotificationEvent({eventName:Q.acs_calling_handle_push_notification,correlationId:t,featureName:`handlePushNotification`,operationName:`handleIncomingCallPushNotification`,callId:``,localParticipantId:``,kindOfEvent:`attempt`,timestampInfo:``,additionalDetails:``}),!e.incomingCallContext)throw new Y({defaultError:J.CALL_AGENT.INVALID_PUSH_NOTIFICATION_DATA});r=new oLe(e,this._tsCallRegistry,this.logger),await r.process(),this.sendHandlePushNotificationEvent({eventName:Q.acs_calling_handle_push_notification,correlationId:t,featureName:`handlePushNotification`,operationName:`handleIncomingCallPushNotification`,callId:r.callId,localParticipantId:r.localParticipantId,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:``})}catch(e){let i=new Y({defaultError:J.CALL_AGENT.PUSH_NOTIFICATION_FAIL,originalError:e});throw this.sendHandlePushNotificationEvent({eventName:Q.acs_calling_handle_push_notification,correlationId:t,featureName:`handlePushNotification`,operationName:`handleIncomingCallPushNotification`,callId:r?.callId||``,localParticipantId:r?.localParticipantId||``,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{failureReason:i.message,code:i.code,...J3(i)}}),i}}sendCallAgentDisposeEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send CallClient dispose telemetry event`)}}trackCallEndTimeToStopTelemetry(e){e.length===0?m3.callEndTimestamp=Date.now():m3.callEndTimestamp=2**53-1}updateConnectionState(e){let t=this.getCallAgentConnectionState(),n=this.getTrouterState(),r=this._callStack?.isRegistered()?`Connected`:`Disconnected`,i=t===`Connected`?void 0:e==`invalidToken`?`invalidToken`:`connectionIssue`;if(this.sendCallAgentInfoEvent({eventName:Q.acs_calling_call_agent,additionalDetails:{step:`connectionState-changed`,oldState:this._connectionState,newState:t,trouterState:n,registrarState:r,reason:i,connectionStateSource:e}}),t!==this._connectionState||i!==this._connectionStateReason){let e={oldValue:this._connectionState,newValue:t,reason:i};this._connectionState=t,this._connectionStateReason=i,this._eventEmitter.emit(`connectionStateChanged`,e)}}sendCallAgentInfoEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:{...e.additionalDetails}})}catch(e){this.logger.debug(`Failed to send connection state changed event`,e)}}sendCallAgentInitializiedEvent(e,t,n,r){try{let i=typeof r?.message==`string`?r?.message:void 0;e!==Q.acs_calling_call_agent_init_failure&&(i=void 0);let a=r?J3(r):void 0,o=this.getEcsConfigIds(),s=e===Q.acs_calling_call_agent_init_attempt?void 0:this._callStack?.getVdi3StateInfo(),c=a7();this._telemetryLogManager.sendEvent({name:e,tenant:p2,properties:{...t,isSupportedEnvironment:this.runningEnvironmentInfo?.isSupportedEnvironment,failureReason:i,additionalProperties:{AcsCallingSDKWeb_ecsConfigIds:o.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigIds:o.SkypeWebMedia},additionalInformation:{trouterState:this.getTrouterState(),hardwareInfo:n},additionalDetails:{...a,firstPartyOptions:{isDeviceTypeEnabled:Z().calling.setDeviceType,deviceTypeRawStrlen:this.callClient?.firstPartyOptions?.acsDeviceType?.length,deviceType:this.getDeviceType()},aadPftClaimExists:this._parsedTokenCredential.aadpftClaimExists,...s?{vdi3StateInfo:s}:{},...c.isMMREnabled?{mmrInfo:c}:{}}}})}catch{this.logger.debug(`Unable to send telemtery`)}}sendHandlePushNotificationEvent(e){try{this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send handle push notification telemetry`)}}async initializeCallRegistry(e,t){let n=t?.displayName,r=await this.getCallRegistry(e,this._parsedTokenCredential,this.tokenProvider,n);return this.logger.info(`registry created for version number=${Z2()}`),r}async getCallRegistry(e,t,n,r){let i={id:t.identityMri,displayName:r||``,tokenProvider:n},a=await e.createCallRegistry(i);await a.login(i);let o=(this._callClient?.firstPartyOptions?.ring??Z()?.tsCalling?.accountConfiguration?.ring)||void 0,s=t.isEnterpriseUser?t2.Enterprise:t2.Consumer,c=t.acsResourceId,l=t.region,u={acsResourceId:c,clientType:s,ring:o};if(Z().calling.setDeviceType)u.deviceType=this.getDeviceType();else if(this.callClient.firstPartyOptions?.acsDeviceType)throw new Y({defaultError:J.CALL_AGENT.SET_DEVICE_TYPE_NOT_ALLOWED});let d=Z().calling.eudb;return d.isEnabled&&d.sendRegionToNgc&&(d.isRgnClaimEnabledForACS||t.isEnterpriseUser)&&(u={...u,region:l}),Z()?.calling.supportLiveStreaming&&(u.clientSupportsUms=!0),u.clientSupportsWatermark=this.isWatermarkSupported(),await a.setConfiguration(u),a.on(`callAdded`,this.handleCallAdded),a.on(`callRemoved`,this.handleCallRemoved),a.on(`pushHandlingStarted`,this.pushHandlingStarted),a.on(`pushHandlingEnded`,this.pushHandlingEnded),a.on(`pushNotificationParsed`,this.pushNotificationParsed),r&&await a.updateDisplayName(r),a}async updateParsedTokenCredentials(e){this._parsedTokenCredential=await P4(e,Z().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),this._caConfigBag.region=this._parsedTokenCredential.region,this._caConfigBag.parsedTokenCredential=this._parsedTokenCredential}registerConnectionStateEventHandlers(){this._callStack.onRegisteredChanged(this._registrarStateChangeCallback),this.onTrouterStateChanged(this._trouterStateChangeCallback)}getCallAgentConnectionState(){return this._callStack?.isRegistered()&&this.getTrouterState()===`Connected`?`Connected`:`Disconnected`}sendIncomingNotificationEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send incoming call notification telemetry`)}}};Y7([UG,X7(`design:type`,Object)],Z7.prototype,`logger`,void 0),Y7([YG(s4.Initialize),X7(`design:type`,Function),X7(`design:paramtypes`,[Object,Object]),X7(`design:returntype`,Promise)],Z7.prototype,`initialize`,null),Y7([JG(s4.Feature),X7(`design:type`,Function),X7(`design:paramtypes`,[Object]),X7(`design:returntype`,typeof(pLe=typeof TFeature<`u`&&TFeature)==`function`?pLe:Object)],Z7.prototype,`feature`,null),Y7([YG(s4.HandlePushNotification),X7(`design:type`,Function),X7(`design:paramtypes`,[Object]),X7(`design:returntype`,Promise)],Z7.prototype,`handlePushNotification`,null);var hLe=class{constructor(e){this._call=e}setTarget(e){this._call=e}getTarget(){return this._call}startVideo(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopVideo(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}startScreenSharing(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopScreenSharing(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setConstraints(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}};function Q7(e){let t=new hLe(e);return new Proxy({},{get:(e,n)=>{let r,i,a=t.getTarget();if(n in t)r=t[n],i=t;else{if(a===void 0)throw new Y({defaultError:J.FEATURES.VDI3.CALL_INITIALIZING});if(!(n in a))return;r=a[n],i=a}return typeof r==`function`?function(...e){return r.apply(i,e)}:r},has:(e,n)=>{let r=t.getTarget();return n in t||r!==void 0&&n in r}})}var $7,e9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},t9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},n9=class e extends Z7{get calls(){return this._calls}constructor(e,t,n,r,i,a,o){super(e,t,r,i,n,WG.CallAgent,a),this._calls=[],this.handleCallRemoved=e=>{this.logger.info(`removing callId=${e.callId}`);let t=this._calls.find((t=>t.id===e.callId));if(t){if(t.isBreakoutRoomCall){let e=Z().calling.breakoutRooms.hangUpCallDelayInMilliSeconds;setTimeout((()=>{this.disposeCall(t)}),e)}else this.disposeCall(t);this._eventEmitter.emit(`callsUpdated`,{added:[],removed:[t]}),this.logger.info(`call removed`)}},this.handleCallAdded=e=>{if(!this._calls.find((t=>t.id===e.callId))){let t=e.on(`callStateChanged`,(async()=>{if(e.state===1){let n=G6(e),r=e.callId;t.dispose();let i=new H7({callId:r,isIncoming:!0},this,e,this._telemetryLogManager);n&&(i=Q7(i));let a=new aLe(i);this.handleCallState(i),n?await Promise.all(i.bindTsCall()):i.bindTsCall(),this._eventEmitter.emit(`incomingCall`,{incomingCall:a})}}))}},this.handleCallState=e=>{e.on(`stateChanged`,(async()=>{try{e.state===`Disconnected`?this.tsStack?(await this._tsCallRegistry.deleteCallAsync?.(e.tsCall)||this.logger.info(`The call has been removed from registry, call id: ${e.id}`),e.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(e.id).catch((()=>{this.logger.error(`Failed to flush telemetry log manager events`)}))):this.logger.info(`Unable to remove call from registry`):e.state===`Connecting`&&e.direction==`Incoming`&&(this.addToCallArray(e),this._eventEmitter.emit(`callsUpdated`,{added:[e],removed:[]}))}catch{this.logger.error(`Failed to handle call state changed event`)}}))},this.displayName=o?.displayName}addToCallAgentsMap(t){e.callAgents.get(t?.identityMri)&&j4(J.CALL_AGENT.ACS_CALLAGENT_ALREADY_EXSISTS,this.logger),e.callAgents.set(t?.identityMri,this)}removeFromCallAgentsMap(t){t?.identityMri&&e.callAgents.get(t?.identityMri)===this&&e.callAgents.delete(t?.identityMri)}disposeCall(e){let t=this._calls.indexOf(e);t!==-1&&this._calls.splice(t,1),e.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls)}async getExistingCallAgentWithToken(t){try{let n=await P4(t,Z().calling.eudb.isRgnClaimEnabledForACS);return e.callAgents.get(n.identityMri)}catch(e){throw new Y({defaultError:J.CALL_AGENT.PARSE_ACCESSTOKEN,originalError:e})}}createNewCall(e,t){let n=new H7({callId:e},this,t,this._telemetryLogManager);return G6(t)?Q7(n):n}addToCallArray(e){this._calls.push(e),this.trackCallEndTimeToStopTelemetry(this._calls)}async disposeInternal(t){let n=+new Date,r=J0();this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});try{if(this._disposed)throw new Y({defaultError:J.CALL_AGENT.ACS_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&e.callAgents.delete(this._parsedTokenCredential?.identityMri);for(let e of this._calls)e.state!==`Disconnected`&&await e.hangUp().catch((()=>{this.logger.error(`Failed to hangup call during call agent dispose`)}));await this._tsCallRegistry?.dispose();let t=this._tokenFetchTries>this._maxNmberOfRetries;await this._callStack.disposeUserStack(t),this.offTrouterStateChanged(this._trouterStateChangeCallback),this._callStack.offRegisteredChanged(this._registrarStateChangeCallback),this._eventEmitter.removeAllListeners(),this._internalEventEmitter.emit(`disposed`),this._internalEventEmitter.removeAllListeners(),this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:``})}catch(e){let t=new Y({defaultError:J.CALL_AGENT.DISPOSE_FAIL,originalError:e});throw this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}}),t}finally{t&&this._telemetryLogManager.clearTelemetryLoggers()}}startCall(e,t){let n=J0(),r=+new Date,i={correlationId:n,timestampInfo:{attemptTimestamp:r}};this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_attempt,tenant:p2,properties:i},void 0,`attempt`);try{if(this.assertCallUserIds(e),t?.alternateCallerId&&Y2(t.alternateCallerId),e.find((e=>K2(e)===this.getUserMri())))throw new Y({defaultError:J.CALL_AGENT.CANT_CALL_YOURSELF});let i=t?.audioOptions?.muted;return i===void 0&&(i=!1),this.logger.info(`startCall with video=${!!t?.videoOptions},muted=${i}`),this.createCall({participants:e,startCallOptions:t},{correlationId:n,attemptTimestamp:r})}catch(e){let t,i;throw e instanceof Y&&(t=typeof e?.message==`string`?e?.message:void 0,i={...J3(e)}),this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_failed,tenant:p2,properties:{correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-r},failureReason:t||``,additionalDetails:i||{}}},void 0,`failure`),e}finally{this._telemetryLogManager.deleteEventMapByCorrelationId(n)}}join(e,t){if(!B4(this.acsProxy,this.acsCustomRelayManager,!1,void 0,e))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});this.assertCallContext(e);let n=t?.audioOptions?.muted;return n===void 0&&(n=!1),this.logger.info(`join with video=${!!t?.videoOptions},muted=${n}`),this.createCall({callContext:e,startCallOptions:t})}async dispose(){await this.disposeInternal(!0)}on(e,t){if(e!==`handleIncomingCall`&&e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`handleIncomingCall`&&e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}createCall(e,t){if(e?.startCallOptions?.firstPartyOptions?.isImmersiveMode&&this.getDeviceType()!==`meshV2`)throw new Y({defaultError:J.CALL_AGENT.MESH_DEVICETYPE_V2});if(!this.tsStack)throw new Y({defaultError:J.CALL_AGENT.STACK_NOT_INIT});let n,r,i,a=e?.callContext?.threadId||e?.startCallOptions?.threadId,o=!1,s=e?.callContext?.groupId,c=e?.callContext?.roomId,l=e?.callContext?.meetingLink,u=e?.callContext?.meetingId,d=e?.callContext?.passcode||``;if(s&&s.startsWith(`19:`)&&(a=s,s=``),l)if(vFe(l))r=P5(l);else{if(!yFe(l,this.logger))throw new Y({defaultError:J.CALL_AGENT.INVALID_MEETING_LINK});if(bFe(l.trim().toLocaleLowerCase(),Z().calling.tfl.hosts)&&!Z().calling.tfl.isEnabled)throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TFL_MEETING_JOIN});o=!0}e?.callContext?.threadId&&e?.callContext?.organizerId&&e?.callContext?.tenantId&&(r={threadId:e?.callContext?.threadId,messageId:e?.callContext?.messageId?e?.callContext?.messageId.toString():`0`,organizerId:e?.callContext?.organizerId,tenantId:e?.callContext?.tenantId}),r&&(i={meetingType:r.messageId===`0`?1:2,tenantId:r.tenantId,organizerId:r.organizerId,replyChainMessageId:r.messageId},a=r.threadId,n=r.messageId);let f=PG(),p=J0(),m=J0(),h={threadId:a||``,messageId:n||``,meetingInfo:i,mediaPeerType:2},g=!1;if(G6(this._tsCallRegistry)){let r=Q7();return(async()=>{let i;s?i=await this._tsCallRegistry.createCallAsync({type:`GroupId`,groupId:s,callId:p,localParticipantId:m,causeId:f}):u?i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`MeetingData`,meetingData:{meetingCode:u,passcode:d,threadId:a}}):c?i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`MeetingData`,meetingData:{meetingCode:c}}):o?i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`MeetingData`,meetingData:{meetingUrl:l}}):(g=!!e?.participants&&e.participants.length>=2&&V4(e.participants,this.kind),Z().calling.enableSmePassFakeConversation&&!a&&g&&(a=`${VG}${J0()}`),i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`ThreadId`,threadId:a||``,messageId:n}));let _=new H7({callId:p,roomId:c},this,i,this._telemetryLogManager,g);r.setTarget(_),this.addToCallArray(r),this.handleCallState(r),e?.participants&&e?.participants.forEach((e=>{i.addParticipant(K2(e)).catch((()=>{this.logger.error(`Failed to add participant during call start`)}))}));let v=n3();_.startCallInternal(e?.startCallOptions,!!u||!!c,e?.callContext,h,t,v).catch(M4),await Promise.all(_.bindTsCall()),await v.promise,this._eventEmitter.emit(`callsUpdated`,{added:[r],removed:[]})})().catch((e=>{})),r}{let r,i=!1;s?r=this._tsCallRegistry.createCallWithGroupId(s,p,m,f):u?r=this._tsCallRegistry.createCallWithMeetingData({meetingCode:u,passcode:d,threadId:a},p,m,f):c?r=this._tsCallRegistry.createCallWithMeetingData({meetingCode:c},p,m,f):o?r=this._tsCallRegistry.createCallWithMeetingData({meetingUrl:l},p,m,f):(i=!!e?.participants&&e.participants.length>=2&&V4(e.participants,this.kind),Z().calling.enableSmePassFakeConversation&&!a&&i&&(a=`${VG}${J0()}`),r=this._tsCallRegistry.createCall(a||``,p,m,n,f));let g=new H7({callId:p,roomId:c},this,r,this._telemetryLogManager,i);return this.addToCallArray(g),this.handleCallState(g),e?.participants&&e?.participants.forEach((e=>{r.addParticipant(K2(e)).catch((()=>{this.logger.error(`Failed to add participant during call start`)}))})),g.startCallInternal(e?.startCallOptions,!!u||!!c,e?.callContext,h,t).catch(M4),g.bindTsCall(),this._eventEmitter.emit(`callsUpdated`,{added:[g],removed:[]}),g}}assertCallContext(e){if(!e||this.checkForAtLeastOneValidCallConfig(e)||this.checkIfMultiplesConfigsWereSpecified(e)||this.checkForInvalidTeamsMeetingCoordinates(e))throw new Y({defaultError:J.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(e){return!(e.threadId||e.meetingLink||e.groupId||e.meetingId||e.roomId)}checkIfMultiplesConfigsWereSpecified(e){return e.threadId&&e.groupId||e.groupId&&e.meetingLink}checkForInvalidTeamsMeetingCoordinates(e){return!e.threadId&&e.tenantId&&e.organizerId||e.threadId&&(e.organizerId&&!e.tenantId||!e.organizerId&&e.tenantId)}assertCallUserIds(e){Ywe(e,J.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),Jwe(e,J.CALL_AGENT.USERIDS_CANNOT_BE_NULL),dwe(e),e.forEach((e=>{let t=Y2(e);if(!B4(this.acsProxy,this.acsCustomRelayManager,!1,t))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}))}};n9.callAgents=new Map,e9([JG(s4.StartCall),t9(`design:type`,Function),t9(`design:paramtypes`,[Array,Object]),t9(`design:returntype`,Object)],n9.prototype,`startCall`,null),e9([JG(s4.Join),t9(`design:type`,Function),t9(`design:paramtypes`,[Object,Object]),t9(`design:returntype`,Object)],n9.prototype,`join`,null),e9([YG(s4.Dispose),t9(`design:type`,Function),t9(`design:paramtypes`,[]),t9(`design:returntype`,Promise)],n9.prototype,`dispose`,null),function(e){e.alpha=`alpha`,e.beta=`beta`,e.stable=`stable`,e.unknown=`unknown`}($7||={});var gLe=class{constructor(){this.browserInfo=r8();let e=X2();e.includes(`alpha`)||e.includes(`alpharc`)?this.sdkFlavor=$7.alpha:e.includes(`beta`)||e.includes(`betarc`)?this.sdkFlavor=$7.beta:e.includes(`stable`)||e.includes(`stablerc`)?this.sdkFlavor=$7.stable:this.sdkFlavor=$7.alpha}getInitialJamaSettings(){let e=t4.merge({},MSe),t=this.getFormFactorBaseSettings();e=t4.merge(e,t);let n=this.getSdkFlavorBaseSettings();e=t4.merge(e,n);let r=this.getSdkFlavorFormFactorSettings();e=t4.merge(e,r);let i=this.getBrowserEngineSpecificSettings();return e=t4.merge(e,i),e}getFormFactorBaseSettings(){switch(this.browserInfo.formFactor){case`Desktop`:return NSe;case`Mobile`:return ISe;default:return MSe}}getSdkFlavorBaseSettings(){switch(this.sdkFlavor){case $7.stable:return BSe;case $7.beta:return zSe;case $7.alpha:default:return RSe}}getSdkFlavorFormFactorSettings(){let e=this.browserInfo.formFactor;if(this.sdkFlavor===$7.stable)switch(e){case`Desktop`:return USe;case`Mobile`:return KSe;default:return BSe}else if(this.sdkFlavor===$7.beta)switch(e){case`Desktop`:return HSe;case`Mobile`:return GSe;default:return zSe}else switch(e){case`Desktop`:return VSe;case`Mobile`:return WSe;default:return RSe}}getBrowserEngineSpecificSettings(){let e=this.browserInfo.engine,t=i8(),n=this.browserInfo.formFactor;return t===`ios`&&e===`Safari`?LSe:n===`Desktop`&&e===`Chromium`?PSe:e===`Firefox`?FSe:{}}},r9=class{constructor(e,t,n){this.setConfigOrDefault=(e,t)=>{e&&Object.keys(e).forEach((n=>{e[n]!==void 0&&(t[n]=e[n])}))},this._logger=e,this.sdkDiagnosticInformation=t,this._acsProxy=n,this._jamaSettingsProvider=new gLe;let r=Z().calling.applicationSettingsUrls,i=Z().calling.pnhTemplateVersion;this._trouterSettings={version:`${d2()}/${X2()}`,productName:`AcsWeb`,trouterServiceUrl:r.Public_TrouterServiceUrl,registrarServiceUrl:r.Public_RegistrarServiceUrl,maxRegistrationTimeInMs:36e5,pnhAppId:`AcsWeb`,pnhTemplate:i,environment:`Prod`,platform:n8()},this._JsCsaConfig={languageCode:`en`,emergencyCallCountry:``,autoResolveConflictedCall:!1,handleRosterFromCreateAndJoin:!0,conversationServiceUrl:n.proxyfyUrl(r.Public_ConversationServiceUrl),useInternalHttpDispatcher:!0,supportsHostlessGroupCalls:!0,doHostlessCalling:!0,shouldServiceSendCallEventMessages:!0,shouldServiceSendNGCUpgradeMessages:!0,supportsCompressedServicePayload:!0,handleNewOfferRequest:!0,handleMediaOfferFromPushNotification:!0,isWebRtcEnabled:!0,supportsSynchronousTrouterResponse:!0,autoJoinOnConflict:!0,brokerEnabledOutgoing:!0,brokerEnabledIncoming:!0,brokerExclusively:!1,brokerRequestBatching:!0,isGVCOutgoingEnabled:!0,isGVCJoiningEnabled:!0,enableTokenCache:!1,nullifyAuthTokenManagerOnReset:!1},this._JamaSettings=this._jamaSettingsProvider.getInitialJamaSettings(),this._MDNTrapSettings={Service:{url:n.proxyfyUrl(r.Public_MdnTrapServiceUrl),tokenUrl:n.proxyfyUrl(r.Public_MdnTrapServiceTokenUrl)},Relay:{Skype:{addresses:[],fqdns:[r.Public_MdnTrapRelaySkypeFqdns],tcpPort:443,udpPort:3478},Turn:{addresses:[],fqdns:[r.Public_MdnTrapRelayTurnFqdns],tcpPort:443,udpPort:3478,url:r.Public_MdnTrapRelayTurnUrl}},Http:{connectionTimeout:30,requestTimeout:60},Token:{earlyRefreshMinutes:1080,earlyRefreshPercentage:25}},this._TrouterJScriptClient={TelemetryEnabled:!1,ClientTelemetryEventEnabled:{trouter_js_client_connected:!1,trouter_js_client_disconnected:!1,trouter_js_client_error:!1,trouter_js_client_progress:!1,trouter_js_client_response:!1,trouter_js_client_check_connection:!1,trouter_js_client_registration:!1,trouter_js_client_unregistration:!1,logHealthCheckError:!1,logSendPingError:!1,numberOfStepsToMaintain:0,sendProgressTimeoutSecs:0}}}getTrouterTelemetryConfig(){return{enabled:this._TrouterJScriptClient.TelemetryEnabled,...this._TrouterJScriptClient.ClientTelemetryEventEnabled}}getJamaSettings(){return this._JamaSettings}getClientInformation(){let e=Z().telemetry.reportSdkUaToService,t=Z().telemetry.reportEnvToService;return`ACSWeb(${d2()}/${X2()})`+(t?`/${cke()}`:``)+(e?`/(${this.sdkDiagnosticInformation})`:``)}getJsCsaConfig(){return this._JsCsaConfig.useInternalHttpDispatcher=!(this._acsProxy.hasProxyUrl()||Z().telemetry.sendNetworkInfo),{...this._JsCsaConfig,clientInformation:this.getClientInformation()}}getMdnTrapSettings(){return this._MDNTrapSettings}getTrouterSettings(){return this._trouterSettings}setConfig(e,t){this._logger.info(`Update ECS settings`);let n=Z().calling.applicationSettingsUrls,r=Z().calling.applicationSettingsEudbUrls,i=e&&N4(e.identityType,e.region);if(e?.identityType==t2.Enterprise)i?(this._trouterSettings.trouterServiceUrl=r.Enterprise_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(r.Enterprise_RegistrarServiceUrl_EUDB)):(this._trouterSettings.trouterServiceUrl=n.Enterprise_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Enterprise_RegistrarServiceUrl));else switch(e?.cloudType){case X0.Public:i&&(this._trouterSettings.trouterServiceUrl=r.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(r.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(r.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[r.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[r.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=r.Public_MdnTrapRelayTurnUrl_EUDB);break;case X0.GccHigh:this._trouterSettings.trouterServiceUrl=n.GccHigh_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.GccHigh_RegistrarServiceUrl);break;case X0.Dod:this._trouterSettings.trouterServiceUrl=n.Dod_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Dod_RegistrarServiceUrl);break;case X0.AirGap08:this._trouterSettings.trouterServiceUrl=n.AirGap08_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap08_RegistrarServiceUrl);break;case X0.AirGap09:this._trouterSettings.trouterServiceUrl=n.AirGap09_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap09_RegistrarServiceUrl)}if(t)this.setConfigOrDefault(t?.SkypeCalling,this._JsCsaConfig),this.setConfigOrDefault(t?.MDN_TRAP,this._MDNTrapSettings),this.setConfigOrDefault(t?.SkypeWebMedia?.mediaAgent,this._JamaSettings),this.setConfigOrDefault(t?.TrouterJScriptClient,this._TrouterJScriptClient);else if(e?.identityType===t2.Enterprise)i?(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(r.Enterprise_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(r.Enterprise_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(r.Enterprise_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[r.Enterprise_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[r.Enterprise_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=r.Enterprise_MdnTrapRelayTurnUrl_EUDB):(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Enterprise_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Enterprise_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Enterprise_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Enterprise_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Enterprise_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=n.Enterprise_MdnTrapRelayTurnUrl);else switch(e?.cloudType){case X0.Public:i&&(this._trouterSettings.trouterServiceUrl=r.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(r.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(r.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[r.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[r.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=r.Public_MdnTrapRelayTurnUrl_EUDB);break;case X0.GccHigh:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.GccHigh_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.GccHigh_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.GccHigh_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[n.GccHigh_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[n.GccHigh_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=n.GccHigh_MdnTrapRelayTurnUrl;break;case X0.Dod:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Dod_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Dod_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Dod_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Dod_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Dod_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=n.Dod_MdnTrapRelayTurnUrl;break;case X0.AirGap08:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap08_ConversationServiceUrl);break;case X0.AirGap09:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap09_ConversationServiceUrl)}}static assertConfigs(e){let t=[];if(e?.SkypeCalling||t.push(`SkypeCalling`),e?.MDN_TRAP||t.push(`MDN_TRAP`),e?.SkypeWebMedia?e?.SkypeWebMedia?.mediaAgent||t.push(`SkypeWebMedia.mediaAgent`):t.push(`SkypeWebMedia`),e?.TrouterJScriptClient||t.push(`TrouterJScriptClient`),t.length>0)throw new Y({defaultError:J.CALL_STACK.FOUND_UNDEFINED_CONFIGS,defaultErrorMessageArgs:[t.join(`, `)]})}},_Le,i9={exports:{}},a9={exports:{}};a9.exports;function vLe(){return _Le||(_Le=1,e=a9,a9.exports,t=()=>{return e={659:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toJson=t.fetchWithTimeout=void 0,t.fetchWithTimeout=function(e,t){var n,r=new Promise((function(t,r){fetch(e).then((function(e){n!==void 0&&clearTimeout(n),t(e)})).catch((function(e){n!==void 0&&clearTimeout(n),r(e)}))}));if(t!==0){var i=new Promise((function(r,i){n=setTimeout(i,t,Error(`Fetch for '${e.url}' timed out`))}));return Promise.race([r,i])}return r},t.toJson=function(e){try{return JSON.stringify(e)}catch{return`Unable to serialize object of type ${typeof e}`}}},912:function(e,t,n){var r,i=this&&this.__extends||(r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},r(e,t)},function(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);function n(){this.constructor=e}r(e,t),e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}),a=this&&this.__assign||function(){return a=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},a.apply(this,arguments)},o=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},s=this&&this.__generator||function(e,t){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){o=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(s[0]===6&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.createRegistrarClient=t.RegistrarClient=void 0;var c=n(659),l=[`skype`,`aad`,`cae`],u=function(e){function t(t){var n=e.call(this,t)||this;return n.name=`CancelationError`,n}return i(t,e),t}(Error),d=function(){function e(t,n,r){this.logger=t,this.maxBackoffInMs=n,this.initialDelay=r,this.backoffCount=0,this.id=++e.idCounter}return e.prototype.delay=function(e){var t=this;if(this.timerHandle!==void 0)throw Error(`Retry sequence logical failure`);if(this.backoffCount===-1)return new Promise((function(e,t){t(new u(`Cancelled`))}));var n=this.calculateNextBackoffMs();return this.backoffCount++,this.logger.info(`[RegistrarClient] Backing off ${e} for ${n} milliseconds with ID ${this.id}`),new Promise((function(r,i){t.cancelFunc=i,t.timerHandle=setTimeout((function(){t.logger.info(`[RegistrarClient] Back off for ${e} with ID ${t.id} complete`),t.timerHandle=void 0,r()}),n)}))},e.prototype.cancel=function(){this.timerHandle!==void 0&&(this.logger.debug(`Resetting back off`),clearTimeout(this.timerHandle),this.cancelFunc!==void 0&&this.cancelFunc(new u(`Cancelled`))),this.backoffCount=-1},e.prototype.calculateNextBackoffMs=function(){var e=1+.4*(Math.random()-.5),t=this.initialDelay*2**this.backoffCount*e;return t=Math.round(t),Math.min(this.maxBackoffInMs,t)},e.idCounter=0,e}(),f=function(){function e(e,t,n){this.logger=e,this.tokenProvider=t,this.options=n,this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN=15,this.DEFAULT_MAX_BACKOFF_TIME_IN_MS=3e5,this.backoffs={},this.maxBackOffTime=this.options.maxRetryDelayMs>0?this.options.maxRetryDelayMs:this.DEFAULT_MAX_BACKOFF_TIME_IN_MS,this.maxRetriesForGetToken=n.maxRetriesForGetToken===void 0||n.maxRetriesForGetToken===null?this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN:n.maxRetriesForGetToken,this.proxyUrlRewrite=n.proxyUrlRewrite??function(e){return e}}return e.prototype.register=function(e,t){return o(this,void 0,void 0,(function(){return s(this,(function(n){switch(n.label){case 0:return[4,this.performRegistration(e,t)];case 1:return n.sent(),this.cachedRegistrationParams=[e,t],[2]}}))}))},e.prototype.unregister=function(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return this.logger.info(`[RegistrarClient] sending unregister request`),e=new Request(this.proxyUrlRewrite(`${this.options.registrarUrl}/${this.options.registrationId}`),{method:`DELETE`,mode:`cors`,headers:new Headers(a(a({},this.options.extraRegistrationHeaders),{accept:`application/json, text/javascript`}))}),[4,this.callRegistrar(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.cancelPendingRequests=function(){var e=this;Object.keys(this.backoffs).forEach((function(t){e.backoffs[t].cancel()})),this.backoffs={}},e.prototype.resendRegistration=function(){return o(this,void 0,void 0,(function(){return s(this,(function(e){switch(e.label){case 0:if(!this.cachedRegistrationParams)throw Error(`Re-registration failed because there is no registration parameters cached`);return[4,this.performRegistration(this.cachedRegistrationParams[0],this.cachedRegistrationParams[1])];case 1:return e.sent(),[2]}}))}))},e.prototype.performRegistration=function(e,t){return o(this,void 0,void 0,(function(){var n,r;return s(this,(function(i){switch(i.label){case 0:return this.logger.info(`[RegistrarClient] Sending register request`),n={clientDescription:e,registrationId:this.options.registrationId,nodeId:``,transports:t},r=new Request(this.proxyUrlRewrite(this.options.registrarUrl),{method:`POST`,mode:`cors`,headers:new Headers(a(a({},this.options.extraRegistrationHeaders),{"content-type":`application/json`,accept:`application/json, text/javascript`})),body:(0,c.toJson)(n)}),[4,this.callRegistrar(r)];case 1:return i.sent(),[2]}}))}))},e.prototype.startBackoff=function(){var e=new d(this.logger,this.maxBackOffTime,this.options.initialRetryDelayMs);return this.backoffs[e.id]=e,e},e.prototype.stopBackoff=function(e){e.cancel(),delete this.backoffs[e.id]},e.prototype.getToken=function(e){return o(this,void 0,void 0,(function(){var t,n,r,i,a,o,c;return s(this,(function(s){switch(s.label){case 0:t=this.startBackoff(),n=0,s.label=1;case 1:return s.trys.push([1,3,,8]),this.logger.info(`[RegistrarClient] Asking for a new token`),[4,this.tokenProvider({needFresh:!0,supportedTokenTypes:l,wwwAuthenticateHeader:e,purpose:`registrar`})];case 2:return r=s.sent(),this.stopBackoff(t),[2,r];case 3:i=s.sent(),s.label=4;case 4:return s.trys.push([4,6,,7]),n++,a=JSON.stringify(i),n>this.maxRetriesForGetToken?(o=`[RegistrarClient] getToken retry limit hit. Will not retry now. Error: ${a}`,this.logger.error(o),this.stopBackoff(t),[2,Promise.reject(o)]):(this.logger.warn(`[RegistrarClient] Retrying for a new token. Retry Count: ${n} Error: ${a}`),[4,t.delay(`Fetching a new token`)]);case 5:return s.sent(),[3,8];case 6:throw c=s.sent(),this.stopBackoff(t),c;case 7:return[3,8];case 8:return[3,1];case 9:return[2]}}))}))},e.prototype.callRegistrar=function(e){return o(this,void 0,void 0,(function(){var t,n,r,i,a,o,u,d,f,p,m,h,g,_,v;return s(this,(function(s){switch(s.label){case 0:return t=this.startBackoff(),[4,this.tokenProvider({needFresh:!1,supportedTokenTypes:l,wwwAuthenticateHeader:void 0,purpose:`registrar`})];case 1:n=s.sent(),this.setTokenHeader(e,n),r=0,s.label=2;case 2:i=void 0,s.label=3;case 3:return s.trys.push([3,10,,15]),a=e.clone(),[4,(0,c.fetchWithTimeout)(a,this.options.requestTimeoutMs)];case 4:return(i=s.sent()).status===401?++r>this.maxRetriesForGetToken?(o=`[RegistrarClient] getSkypeToken retry limit hit. Will not retry now. Request '${e.url}' failed with ${i.status} ${i.statusText}`,this.logger.error(o),this.stopBackoff(t),[2,Promise.reject(o)]):(this.logger.warn(`[RegistrarClient] Retry Count ${r}. Request '${e.url}' failed with ${i.status} ${i.statusText}`),u=i.headers?.get(`www-authenticate`)??void 0,d=this.setTokenHeader,f=[e],[4,this.getToken(u)]):[3,8];case 5:return d.apply(this,f.concat([s.sent()])),r>1?[4,t.delay(`Registrar call retry after 401`)]:[3,7];case 6:s.sent(),s.label=7;case 7:return[3,21];case 8:if(i.status>=500&&i.status<600)throw Error(`Fetch for '${e.url}' failed with ${i.status} ${i.statusText}`);s.label=9;case 9:return[3,15];case 10:p=s.sent(),this.logger.error(`[RegistrarClient] Request failed with ${p}`),s.label=11;case 11:return s.trys.push([11,13,,14]),[4,t.delay(`Registrar call retry`)];case 12:return s.sent(),[3,21];case 13:throw m=s.sent(),this.logger.error(`[RegistrarClient] Request cancelled`),this.stopBackoff(t),m;case 14:return[3,15];case 15:return this.stopBackoff(t),i.ok?[2,i]:[3,16];case 16:h=void 0,s.label=17;case 17:return s.trys.push([17,19,,20]),_=(g=JSON).stringify,[4,i.json()];case 18:return h=_.apply(g,[s.sent()]),[3,20];case 19:return s.sent(),h=`no details`,[3,20];case 20:throw v=`Fetch for '${e.url}' failed with ${i.status} ${i.statusText} (${h}, MS-CV: ${i.headers?.get(`MS-CV`)})`,this.logger.error(`[RegistrarClient] ${v}`),Error(v);case 21:return[3,2];case 22:return[2]}}))}))},e.prototype.setTokenHeader=function(e,t){switch(e.headers.delete(`X-Skypetoken`),e.headers.delete(`Authorization`),e.headers.delete(`X-MS-Migration`),t.tokenType.toLowerCase()){case`skype`:e.headers.set(`X-Skypetoken`,t.token);break;case`aad`:case`cae`:e.headers.set(`Authorization`,`Bearer ${t.token}`);break;default:throw Error(`unsupported token type: ${t.tokenType}`)}!1===this.options.usingLegacyTokenApi&&e.headers.set(`X-MS-Migration`,`True`)},e}();t.RegistrarClient=f,t.createRegistrarClient=function(e,t,n){return new f(e,t,n)}}},t={},function n(r){var i=t[r];if(i!==void 0)return i.exports;var a=t[r]={exports:{}};return e[r].call(a.exports,a,a.exports,n),a.exports}(912);var e,t},e.exports=t()),a9.exports;var e,t}var yLe;i9.exports;function bLe(){return yLe||(yLe=1,e=i9,i9.exports,t=e=>(()=>{var t={10:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManagerFsm=void 0;var r=n(234),i=n(423),a=n(642),o=n(573);t.TrouterManagerFsm=function(){function e(e,t){this.worker=t,this.state=i.TrouterManagerState.Unknown,this.logger=new a.Logger(`ManagerFsm`,e)}return e.prototype.start=function(){this.state===i.TrouterManagerState.Unknown?(this.setState(i.TrouterManagerState.Disconnected),this.worker.forceStopLingeringConnection(),this.worker.startFirstConnection()):(this.logger.info(`start called in state '${i.TrouterManagerState[this.state]}', expediting pending backoffs, if any`),this.worker.expediteBackoffOnConnections())},e.prototype.stop=function(e){this.state===i.TrouterManagerState.Unknown?this.showIgnored(`stop`):(this.setState(i.TrouterManagerState.Unknown),this.worker.stopFirstConnection(!0===e),this.worker.stopSecondConnection(!0===e))},e.prototype.getState=function(){switch(this.state){case i.TrouterManagerState.Unknown:case i.TrouterManagerState.Connected:case i.TrouterManagerState.Disconnected:case i.TrouterManagerState.Switching:return this.state;case i.TrouterManagerState.TerminalError:return r.TrouterState.Disconnected}},e.prototype.getInternalState=function(){return this.state},e.prototype.onConnected=function(e){this.state===i.TrouterManagerState.Disconnected&&e?this.worker.doesSecondConnectionExist()?this.setState(i.TrouterManagerState.Switching):(this.setState(i.TrouterManagerState.Connected),this.worker.dispatchConnected()):this.showIgnored(`onConnected(${e})`)},e.prototype.onRegistered=function(e){this.state!==i.TrouterManagerState.Disconnected||e?this.state!==i.TrouterManagerState.Switching||e?this.state===i.TrouterManagerState.Disconnected&&e&&(this.setState(i.TrouterManagerState.Connected),this.worker.dispatchConnected()):(this.setState(i.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnectionDelayed(),this.worker.dispatchConnected()):(this.setState(i.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnection(!0),this.worker.dispatchConnected()),this.worker.dispatchRegistrationState(!0)},e.prototype.onUnregistered=function(e){e&&this.worker.dispatchRegistrationState(!1)},e.prototype.onReconnecting=function(e){this.state!==i.TrouterManagerState.Connected&&this.state!==i.TrouterManagerState.Switching||!e?this.showIgnored(`onReconnecting(${e})`):(this.setState(i.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected())},e.prototype.onReconnectionRequired=function(e,t,n){this.state===i.TrouterManagerState.Connected&&e?(this.setState(i.TrouterManagerState.Switching),this.worker.startSecondConnection(t)):this.state===i.TrouterManagerState.Disconnected&&e?this.worker.startSecondConnection(t):this.state===i.TrouterManagerState.Switching&&e&&n===o.ReconnectReason.Configuration?(this.logger.debug(`onReconnectionRequired: switch requested while already in Switching state`),this.worker.stopSecondConnection(!0),this.worker.startSecondConnection(t)):this.showIgnored(`onReconnectionRequired(${e})`)},e.prototype.onDisconnected=function(e){this.state==i.TrouterManagerState.Unknown&&e?this.worker.dispatchDisconnected():this.state==i.TrouterManagerState.Switching&&e?(this.worker.switchConnections(),this.worker.stopSecondConnection(!1),this.setState(i.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected()):this.showIgnored(`onDisconnected(${e})`)},e.prototype.onTerminalError=function(){this.setState(i.TrouterManagerState.TerminalError),this.worker.dispatchTerminalError()},e.prototype.showIgnored=function(e){this.logger.info(`Ignoring event '${e}' in state '${i.TrouterManagerState[this.state]}'`)},e.prototype.setState=function(e){this.logger.info(`Switching from state '${i.TrouterManagerState[this.state]}' to state '${i.TrouterManagerState[e]}'`),this.state===e?this.logger.error(`Attempt to switch to the current state '${i.TrouterManagerState[e]}'`):this.state=e},e}()},107:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExponentialBackoff=void 0,t.ExponentialBackoff=function(){function e(e,t,n){n===void 0&&(n={tolerance:2,minimumWaitMs:1e4}),this.logger=e,this.maxBackoffInMs=t,this.gapDetectionSettings=n,this.backoffId=0,this.backoffCount=0}return e.calculateNextBackoffMs=function(e,t){var n=1+.4*(Math.random()-.5),r=1e3*2**e*n;return r=Math.round(r),Math.min(t,r)},e.prototype.setMaxBackoffMs=function(e){this.maxBackoffInMs=e},e.prototype.backoff=function(t,n){var r=this;if(this.timerHandle!==void 0&&(this.logger.debug(`Clearing current back off`),clearTimeout(this.timerHandle),this.timerHandle=void 0),this.previousCompleteTime!==void 0){var i=Date.now()-this.previousCompleteTime;i>this.maxBackoffInMs*this.gapDetectionSettings.tolerance&&i>this.gapDetectionSettings.minimumWaitMs&&(this.logger.info(`Back off for ${t} with ID ${this.backoffId} will be reset due to a lot of time having passed since the previous backoff (${i} ms)`),this.backoffCount=0,this.previousCompleteTime=void 0)}var a=e.calculateNextBackoffMs(this.backoffCount,this.maxBackoffInMs);this.backoffId++,this.backoffCount++,this.logger.info(`Backing off ${t} for ${a} milliseconds with ID ${this.backoffId}`),this.callback=function(e,i){(function(e,t,n){if(e===void 0||t===void 0)return!1;var r=Date.now()-e;return r>t*n.tolerance&&r>n.minimumWaitMs})(e,i,r.gapDetectionSettings)&&(r.logger.info(`Back off for ${t} with ID ${r.backoffId} will be reset due to the wait (${Date.now()-(e??0)} ms) being longer than expected (${i} ms)`),r.backoffCount=0),r.logger.info(`Back off for ${t} with ID ${r.backoffId} complete, invoking handler`),r.timerHandle=void 0,r.callback=void 0,r.previousCompleteTime=Date.now(),n()};var o=Date.now();this.timerHandle=setTimeout((function(){return r.callback?.call(r,o,a)}),a)},e.prototype.reset=function(){this.timerHandle!==void 0&&(this.logger.debug(`Resetting back off with ID ${this.backoffId}`),clearTimeout(this.timerHandle),this.timerHandle=void 0,this.callback=void 0),this.backoffCount=0},e.prototype.expediteIfPending=function(){if(this.backoffCount=0,this.timerHandle!==void 0){this.logger.debug(`Expediting back off with ID ${this.backoffId}`),clearTimeout(this.timerHandle),this.timerHandle=void 0;var e=this.callback;this.callback=void 0,e&&e()}},e}()},220:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.addCacheAsBackupTo=function(e){var t,i=this;return function(a){return n(i,void 0,void 0,(function(){return r(this,(function(n){return a&&(t=void 0),[2,new Promise((function(n,r){e(a).then((function(e){t=e,n(e)})).catch((function(e){t!==void 0&&t.length>0&&n(t),r(e)}))}))]}))}))}}},234:(e,t)=>{var n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterState=t.UserActivityState=void 0,function(e){e[e.Unknown=0]=`Unknown`,e[e.Active=1]=`Active`,e[e.Inactive=2]=`Inactive`}(n||(t.UserActivityState=n={})),function(e){e[e.Unknown=0]=`Unknown`,e[e.Connected=2]=`Connected`,e[e.Disconnected=3]=`Disconnected`,e[e.Switching=9]=`Switching`}(r||(t.TrouterState=r={}))},235:function(e,t,n){var r=this&&this.__spreadArray||function(e,t,n){if(n||arguments.length===2)for(var r,i=0,a=t.length;i<a;i++)!r&&i in t||(r||=Array.prototype.slice.call(t,0,i),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.LoggingManagerConsumer=t.RegistrationEnforcer=void 0;var i=n(335);t.RegistrationEnforcer=function(){function e(e,t,n){this.wrapped=e,this.shouldConnectionDependOnRegistration=t,this.shouldHoldBackEvents=n,this.isRegistered=!1,this.heldBackEvents=[]}return e.prototype.onDownstreamRequest=function(e,t,n){this.passIfRegisteredOrNotNeeded(`onDownstreamRequest`,e,t,n)},e.prototype.onConnected=function(e){this.passIfRegisteredOrNotNeeded(`onConnected`,e)},e.prototype.onRegistered=function(e){this.isRegistered=!0,this.wrapped.onRegistered(e),this.fireHeldBackEvents()},e.prototype.onUnregistered=function(e){var t=this.isRegistered;this.isRegistered=!1,this.wrapped.onUnregistered(e),t&&e.getState()===i.State.Connected&&this.shouldConnectionDependOnRegistration()&&e.forceReconnectDueToNoRegistration()},e.prototype.onReconnecting=function(e){this.wrapped.onReconnecting(e)},e.prototype.onReconnectIsRequired=function(e,t,n){this.wrapped.onReconnectIsRequired(e,t,n)},e.prototype.onDisconnected=function(e){this.isRegistered=!1,this.dropHeldBackEvents(),this.wrapped.onDisconnected(e)},e.prototype.onTerminalError=function(e){this.wrapped.onTerminalError(e)},e.prototype.onConnectionParametersUpdated=function(e){this.wrapped.onConnectionParametersUpdated(e)},e.prototype.onTrouterMessageLost=function(e){this.passIfRegisteredOrNotNeeded(`onTrouterMessageLost`,e)},e.prototype.onUserActivityStateAccepted=function(e){this.passIfRegisteredOrNotNeeded(`onUserActivityStateAccepted`,e)},e.prototype.onAudiencesSetResolved=function(e,t){this.passIfRegisteredOrNotNeeded(`onAudiencesSetResolved`,e,t)},e.prototype.getState=function(){return this.wrapped.getState()},e.prototype.holdBackEvent=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.heldBackEvents.push({kind:e,args:t})},e.prototype.passIfRegisteredOrNotNeeded=function(e){for(var t,n=[],i=1;i<arguments.length;i++)n[i-1]=arguments[i];var a=this.shouldConnectionDependOnRegistration(),o=this.shouldHoldBackEvents();a&&o||this.fireHeldBackEvents(a?function(e){return e.kind!==`onConnected`}:void 0),this.isRegistered||!a||!1===o&&e!==`onConnected`?(t=this.wrapped)[e].apply(t,n):this.holdBackEvent.apply(this,r([e],n,!1))},e.prototype.fireHeldBackEvents=function(e){for(var t,n=0,r=this.heldBackEvents;n<r.length;n++){var i=r[n];(e===void 0||e(i))&&(t=this.wrapped)[i.kind].apply(t,i.args)}this.heldBackEvents=e===void 0?[]:this.heldBackEvents.filter((function(t){return!e(t)}))},e.prototype.dropHeldBackEvents=function(){this.heldBackEvents=[]},e}(),t.LoggingManagerConsumer=function(){function e(e,t,n,r){this.wrapped=e,this.prefix=t,this.logger=n,this.onEventAction=r}return e.prototype.onEvent=function(e,t){this.onEventAction===void 0?(this.logger??console).log(`${this.prefix} TracingEnforcer: ${e}(${t})`):this.onEventAction(e,t)},e.prototype.onDownstreamRequest=function(e,t,n){this.onEvent(`onDownstreamRequest`,JSON.stringify({request:t,response:n})),this.wrapped.onDownstreamRequest(e,t,n)},e.prototype.onConnected=function(e){this.onEvent(`onConnected`,e.getState().toString()),this.wrapped.onConnected(e)},e.prototype.onRegistered=function(e){this.onEvent(`onRegistered`,e.getState().toString()),this.wrapped.onRegistered(e)},e.prototype.onUnregistered=function(e){this.onEvent(`onUnregistered`,e.getState().toString()),this.wrapped.onUnregistered(e)},e.prototype.onReconnecting=function(e){this.onEvent(`onReconnecting`,e.getState().toString()),this.wrapped.onReconnecting(e)},e.prototype.onReconnectIsRequired=function(e,t,n){this.onEvent(`onReconnectIsRequired`,JSON.stringify({connection:e.getState().toString(),useConnectParamsFromCache:t,reason:n})),this.wrapped.onReconnectIsRequired(e,t,n)},e.prototype.onDisconnected=function(e){this.onEvent(`onDisconnected`,e.getState().toString()),this.wrapped.onDisconnected(e)},e.prototype.onTerminalError=function(e){this.onEvent(`onTerminalError`,JSON.stringify({connection:e})),this.wrapped.onTerminalError(e)},e.prototype.onConnectionParametersUpdated=function(e){this.onEvent(`onConnectionParametersUpdated`,JSON.stringify({connectParams:e})),this.wrapped.onConnectionParametersUpdated(e)},e.prototype.onTrouterMessageLost=function(e){this.onEvent(`onTrouterMessageLost`,JSON.stringify({flowTags:e})),this.wrapped.onTrouterMessageLost(e)},e.prototype.onUserActivityStateAccepted=function(e){this.onEvent(`onUserActivityStateAccepted`,JSON.stringify({cv:e})),this.wrapped.onUserActivityStateAccepted(e)},e.prototype.onAudiencesSetResolved=function(e,t){this.onEvent(`onAudiencesSetResolved`,JSON.stringify({audienceSubscriptionsResponse:e,cv:t})),this.wrapped.onAudiencesSetResolved(e,t)},e.prototype.getState=function(){return this.wrapped.getState()},e}()},335:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterFsm=t.State=void 0;var r,i,a=n(423),o=n(642),s=n(902);(function(e){e[e.Initial=0]=`Initial`,e[e.RetrievingToken=1]=`RetrievingToken`,e[e.Allocating=2]=`Allocating`,e[e.Handshaking=3]=`Handshaking`,e[e.Connecting=4]=`Connecting`,e[e.AnonymousConnecting=5]=`AnonymousConnecting`,e[e.WebsocketAuthenticating=6]=`WebsocketAuthenticating`,e[e.Connected=7]=`Connected`,e[e.Unregistering=8]=`Unregistering`,e[e.TerminalError=9]=`TerminalError`})(r||(t.State=r={})),function(e){e[e.Initial=0]=`Initial`,e[e.Registering=1]=`Registering`,e[e.RegisteringButResendPending=2]=`RegisteringButResendPending`,e[e.Retrying=3]=`Retrying`,e[e.Registered=4]=`Registered`,e[e.RegistrationDisabled=5]=`RegistrationDisabled`}(i||={}),t.TrouterFsm=function(){function e(e,t,n,a){this.worker=t,this.incallModeEnabled=n,this.protocolSelector=a,this.state=r.Initial,this.autoReconnect=!0,this.logger=new o.Logger(`ConnectionFsm`,e),this.registrationState=i.Initial}return e.prototype.getState=function(){return this.state},e.prototype.isActive=function(){return this.state===r.Allocating||this.state===r.Connected||this.state===r.Handshaking||this.state===r.Connecting||this.state===r.RetrievingToken||this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating},e.prototype.isConnecting=function(){return this.state===r.Allocating||this.state===r.Handshaking||this.state===r.Connecting||this.state===r.AnonymousConnecting},e.prototype.start=function(){return this.state===r.Initial?(this.setState(r.RetrievingToken),this.worker.getToken(!0,!1,void 0),!0):(this.showIgnored(`start`),!1)},e.prototype.stop=function(e,t){e&&(this.registrationState=i.Initial),this.worker.isIncallMode()&&this.worker.exitIncallMode(),this.worker.resetTokenBackoff(),this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.state===r.Connected&&this.worker.sendDisconnectTelemetryEvent(`connection stopped`),this.registrationState!==i.Registered&&this.registrationState!==i.Registering&&this.registrationState!==i.RegisteringButResendPending||this.state===r.Unregistering?t?(this.setState(r.TerminalError),this.worker.dispatchTerminalError()):(this.setState(r.Initial),this.worker.dispatchDisconnected()):(this.registrationState=i.Initial,this.setState(r.Unregistering),this.worker.sendUnregisterRequest())},e.prototype.onTokenReceived=function(e,t,n){this.state===r.RetrievingToken?(0,s.usedProtocolAfterFallback)(this.protocolSelector(e.tokenType,n),t)===`v4c`?(this.setState(r.AnonymousConnecting),this.worker.startConnectionTimer(),this.worker.connectV4c(e,t)):(this.setState(r.Allocating),this.worker.startConnectionTimer(),this.worker.sendAllocateRequest(e)):this.showIgnored(`onTokenReceived`)},e.prototype.checkConnection=function(e){e&&this.onPingInterval()},e.prototype.onAllocationSucceed=function(e){return this.state===r.Allocating&&this.registrationState===i.Registered&&this.worker.dispatchUnregistered(),this.state===r.Allocating?(this.setState(r.Handshaking),this.registrationState=i.Initial,this.worker.startSocketIo(e),!0):(this.showIgnored(`onAllocationSucceed`),!1)},e.prototype.onAllocationFailed=function(e,t){this.state===r.Allocating?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!e,claimsChallenge:t}):this.showIgnored(`onAllocationFailed`)},e.prototype.onV4cConnectivityCheckFailed=function(){this.state===r.AnonymousConnecting?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0}):this.showIgnored(`onV4cConnectivityCheckFailed`)},e.prototype.onV4cException=function(){this.state!==r.AnonymousConnecting&&this.state!==r.WebsocketAuthenticating||(this.logger.error(`v4c exception, falling back to longpoll`),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`v4c-websocket-failure`}}))},e.prototype.onConnectingTimeout=function(){this.state===r.Allocating||this.state===r.Connecting||this.state===r.Handshaking||this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating?this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0}):this.showIgnored(`onConnectingTimeout`)},e.prototype.onConnecting=function(){this.state===r.Handshaking?this.setState(r.Connecting):this.showIgnored(`onConnecting`)},e.prototype.onSocketConnect=function(e){this.state===r.AnonymousConnecting?(this.setState(r.WebsocketAuthenticating),this.worker.sendV4cAuthenticationEvent(e)):this.showIgnored(`onSocketConnect`)},e.prototype.onConnectingFailed=function(){this.state===r.Connecting?this.onConnectingTimeout():this.state===r.Handshaking?(this.logger.error(`Unexpected error in Socket.io - no valid transports`),this.onConnectingTimeout()):this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating?(this.logger.info(`/v4/c falling back to longpoll`),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`v4c-websocket-failure`}})):this.showIgnored(`onConnectingFailed`)},e.prototype.onSocketDisconnect=function(e){this.state===r.Handshaking||this.state===r.Connected||this.state===r.WebsocketAuthenticating?(this.state===r.Connected&&this.worker.sendDisconnectTelemetryEvent(e?.toTelemetryString()),this.state===r.WebsocketAuthenticating&&this.worker.countDisconnectBeforeConnectionEstablishment(),e?.reason===`skypetoken-deprecated`?(this.logger.error(`Skypetoken deprecated response, not retrying any further`),this.onTerminalError()):this.cleanUpAndInitiateReconnect({backoff:this.state!==r.Connected&&e?.reason!==`dup`,allowCachedToken:e?.reason!==`unauthorized`,claimsChallenge:e?.claims})):this.showIgnored(`onSocketDisconnect`)},e.prototype.onTrouterConnected=function(){this.state===r.Connecting||this.state===r.WebsocketAuthenticating?(this.setState(r.Connected),this.worker.resetTokenBackoff(),this.worker.stopConnectionTimer(),this.worker.sendUserActivityState(a.UserActivityEventReason.Connected,!0),this.worker.startPingTimer(),this.worker.dispatchConnected(),this.worker.shouldSkipRegistration()?(this.registrationState=i.RegistrationDisabled,this.worker.dispatchRegistered()):(this.registrationState=i.Registering,this.worker.sendRegisterRequest())):this.showIgnored(`onTrouterConnected`)},e.prototype.onReconnectRequired=function(e,t,n){this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating?n===void 0||n.target!==`host`||n.url===void 0||n.url===``?(this.logger.error(`unexpected reconnect arguments: ${n?.target} ${n?.url}, reconnecting without cache`),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`redirect-no-host`}})):this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`redirect`,host:n.url}}):this.worker.dispatchReconnectIsRequired(e,t)},e.prototype.disableAutoReconnect=function(){this.autoReconnect=!1},e.prototype.onDownstreamRequest=function(e){this.state===r.Connected?(this.switchToIncallModeIfEnabled(),this.worker.dispatchDownstreamRequest(e)):this.showIgnored(`onDownstreamRequest`)},e.prototype.onTrouterMessageLost=function(e){this.state===r.Connected?this.worker.dispatchTrouterMessageLost(e):this.showIgnored(`onTrouterMessageLost`)},e.prototype.onPingInterval=function(){this.state===r.Connected?this.worker.sendPingRequest():this.showIgnored(`onPingInterval`)},e.prototype.onPingResponseTimeout=function(){this.onMissedResponse(`onPingResponseTimeout`)},e.prototype.onPingResponse=function(){this.state===r.Connected||this.showIgnored(`onPingResponse`)},e.prototype.onRegistrationFailed=function(){this.state===r.Connected&&this.registrationState===i.Registering?(this.worker.dispatchUnregistered(),this.registrationState=i.Retrying,this.worker.startRegistrationRetryTimer()):this.state===r.Connected&&this.registrationState===i.RegisteringButResendPending?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRegistrationFailed`)},e.prototype.onRetryRegistration=function(){this.state===r.Connected&&this.registrationState===i.Retrying?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRetryRegistration`)},e.prototype.onRegistrationSucceeded=function(){this.state===r.Connected&&this.registrationState===i.Registering?(this.registrationState=i.Registered,this.worker.dispatchRegistered(),this.worker.startRegistrationTimer()):this.state===r.Connected&&this.registrationState===i.RegisteringButResendPending?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRegistrationSucceeded`)},e.prototype.onRegistrationNearExpiry=function(){this.state===r.Connected&&this.registrationState===i.Registered?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRegistrationNearExpiry`)},e.prototype.onUnregistrationDone=function(){this.state===r.Unregistering?(this.setState(r.Initial),this.worker.dispatchUnregistered(),this.worker.dispatchDisconnected()):this.showIgnored(`onUnregistrationDone`)},e.prototype.onResendRegistration=function(){this.worker.dispatchUnregistered(),this.state===r.Connected&&this.registrationState===i.Registered?(this.registrationState=i.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.state===r.Connected&&this.registrationState===i.Registering&&(this.registrationState=i.RegisteringButResendPending)},e.prototype.onExtraTransportsUpdated=function(){this.state===r.Connected?this.registrationState===i.Registered?(this.registrationState=i.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.registrationState===i.Registering&&(this.registrationState=i.RegisteringButResendPending):this.state===r.Unregistering||this.state===r.Initial?this.logger.warn(`onExtraTransportsUpdated called while Trouter is stopped, will not be applied until it is next started`):(this.logger.info(`extra transports will be registered when Trouter successfully connects`),this.showIgnored(`onExtraTransportsUpdated`))},e.prototype.onIncallModeTimer=function(){this.worker.exitIncallMode(),this.state===r.Connected?(this.worker.stopPingTimer(),this.worker.startPingTimer()):this.showIgnored(`onIncallModeTimer`)},e.prototype.onSetNewUserActivityState=function(){this.worker.sendUserActivityState(a.UserActivityEventReason.Modified,this.state===r.Connected)},e.prototype.onActivityStateResponseTimeout=function(){this.onMissedResponse(`onActivityStateResponseTimeout`)},e.prototype.forceReconnect=function(e){this.state===r.Connected&&this.worker.sendDisconnectTelemetryEvent(e),this.worker.resetTokenBackoff(),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})},e.prototype.onTerminalError=function(){this.logger.error(`Cannot proceed, reached terminal state. Switching from state '${r[this.state]}' to ${r[r.TerminalError]}`),this.stop(!0,!0),this.setState(r.TerminalError)},e.prototype.onMissedResponse=function(e){this.state===r.Connected?(this.worker.sendDisconnectTelemetryEvent(e),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})):this.showIgnored(e)},e.prototype.showIgnored=function(e){this.logger.debug(`Ignoring event '${e}' in state '${r[this.state]}'`)},e.prototype.setState=function(e){this.logger.info(`Switching from state '${r[this.state]}' to state '${r[e]}'`),this.state===e?this.logger.error(`Attempt to switch to the current state '${r[e]}'`):this.state=e},e.prototype.switchToIncallModeIfEnabled=function(){this.incallModeEnabled&&(this.worker.isIncallMode()||(this.worker.enterIncallMode(),this.worker.stopPingTimer(),this.worker.startPingTimer()),this.worker.restartIncallModeTimer())},e.prototype.cleanUpAndInitiateReconnect=function(e){if(!this.autoReconnect)return this.logger.info(`Automatic reconnect is disabled, stopping this connection`),void this.stop(!0);this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.setState(r.RetrievingToken),this.worker.dispatchReconnecting(),this.worker.getToken(e.allowCachedToken,e.backoff,e.claimsChallenge,e.fallbackReason)},e}()},396:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionTracker=t.Properties=t.TrackerStep=t.ClientEventName=t.ResponseData=void 0;var r,i=n(659),a=n(509),o=n(642);t.ResponseData=function(e){this.id=e,this.status=200,this.headers={},this.body=``},function(e){e.Connected=`trouter_js_client_connected`,e.Disconnected=`trouter_js_client_disconnected`,e.Error=`trouter_js_client_error`,e.Progress=`trouter_js_client_progress`,e.Response=`trouter_js_client_response`,e.CheckConnection=`trouter_js_client_check_connection`}(r||(t.ClientEventName=r={}));var s=function(e,t,n,r,i){this.stepName=e,this.operation=t,this.delta=n,this.ts=r,this.error=i};t.TrackerStep=s,t.Properties=function(){};var c=function(){this.numberOfPingReplies=0,this.connectedTimestamp=0,this.isNewUrl=!1,this.transportType=``,this.connectionNumber=0},l=function(){this.enabled=!1,this.numberOfStepsToMaintain=40,this.logHealthCheckError=!1,this.sendProgressTimeoutSecs=55,this.logSendPingError=!1,this.maxBackoffInMs=12e4,this.trouter_js_client_connected=!1,this.trouter_js_client_disconnected=!1,this.trouter_js_client_error=!1,this.trouter_js_client_progress=!1,this.trouter_js_client_response=!1,this.trouter_js_client_request=!1,this.trouter_js_client_registration=!1,this.trouter_js_client_unregistration=!1,this.trouter_js_client_check_connection=!0};t.ConnectionTracker=function(){function e(e,t,n,r,a,s,u){this.clientId=t,this.clientInfo=n,this.getServerState=r,this.endpointId=a,this.clientCorrelationID=s,this.environment=u,this.logger=new o.Logger(`ConnectionTracker`,e),this.clientCorrelationID=s===void 0?``:s,this.steps=[],this.connectionAttempt=0,this.totalStepCount=0,this.beginTimestamp=new i.Timespan,this.eventLogSettings=new l,this.connectedInfo=new c}return e.prototype.enable=function(e){this.eventLogSettings.enabled=!0,this.eventLogger=e},e.prototype.disable=function(){this.eventLogSettings.enabled=!1},e.prototype.sendProgress=function(e){this.steps.length>0&&this.sendTelemetry(r.Progress,e,this.steps)},e.prototype.cancelProgressTimer=function(){this.progressTimeout!==void 0&&(clearTimeout(this.progressTimeout),this.progressTimeout=void 0)},e.prototype.resetProgressSendTimer=function(){var e=this;this.cancelProgressTimer(),this.eventLogSettings.sendProgressTimeoutSecs!==void 0&&this.eventLogSettings.sendProgressTimeoutSecs>0&&(this.progressTimeout=setTimeout((function(){e.sendProgress({reason:`timeout`,timeoutSecs:e.eventLogSettings.sendProgressTimeoutSecs})}),1e3*this.eventLogSettings.sendProgressTimeoutSecs))},e.prototype.setConnectedInfo=function(e,t){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=Date.now(),this.connectedInfo.isNewUrl=e,this.connectedInfo.transportType=t,++this.connectedInfo.connectionNumber},e.prototype.clearConnectedInfo=function(){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=0,this.connectedInfo.isNewUrl=!0,this.connectedInfo.transportType=``},e.prototype.copyProperties=function(e,t){for(var n=0,r=Object.keys(t);n<r.length;n++){var i=r[n];t[i]!==void 0&&(e[i.replace(/-/g,`_`)]={value:t[i]})}},e.prototype.increasePingResponseCount=function(){++this.connectedInfo.numberOfPingReplies},e.prototype.sendTelemetry=function(e,t,n){try{if(!0===this.eventLogSettings.enabled&&!0===this.eventLogSettings[e]&&this.eventLogger!==void 0){var r=this.getServerState(),o={name:e,properties:{connectionAttempt:{value:this.connectionAttempt},epid:{value:this.endpointId},clientCorrelationID:{value:this.clientCorrelationID},steps:{value:(0,i.toJson)(n)},clientID:{value:this.clientId},eventVersion:{value:3},environment:{value:this.environment},cv:{value:a.CLIENT_VERSION},ua:{value:this.clientInfo.ua},connectionId:{value:r.connectionId},connectedClientId:{value:r.connectedClientId},domId:{value:r.domId},url:{value:r.url},ttlInSecs:{value:r.getRemainingTtlInSec()},numberOfPingReplies:{value:this.connectedInfo.numberOfPingReplies},connectedTimestamp:{value:this.connectedInfo.connectedTimestamp},isNewUrl:{value:this.connectedInfo.isNewUrl},transportType:{value:this.connectedInfo.transportType},connectionNumber:{value:this.connectedInfo.connectionNumber}}};this.copyProperties(o.properties,t),this.eventLogger.logEvent(o)}}catch(t){this.logger.warn(`error in sending event ${e}: ${(0,i.toJson)(t)}`)}},e.prototype.createStep=function(e,t,n){return new s(e,t,this.beginTimestamp.duration,Date.now(),n)},e.prototype.addStep=function(e,t,n){if(!1!==this.eventLogSettings.enabled&&(this.steps.length===0&&this.beginTimestamp.reset(),this.steps.push(this.createStep(e,t,n)),++this.totalStepCount,this.eventLogSettings.numberOfStepsToMaintain!==void 0&&this.steps.length>this.eventLogSettings.numberOfStepsToMaintain)){var i=this.steps.slice(0);this.steps.length=0,this.sendTelemetry(r.Progress,{reason:`flush`},i)}},e.prototype.trackStart=function(e){this.addStep(e,`start`)},e.prototype.trackEnd=function(e){this.addStep(e,`end`)},e.prototype.trackError=function(e,t,n,i){n===void 0&&(n=!0),e===`health`&&!0!==this.eventLogSettings.logHealthCheckError||e===`ping`&&!1===this.eventLogSettings.logSendPingError||(i===void 0&&(i=`error`),!0===n&&this.addStep(e,i,t),this.sendTelemetry(r.Error,{},[this.createStep(e,i,t)]))},e.prototype.trackProgress=function(e,t){this.addStep(e,t)},e.prototype.trackConnected=function(e,t){this.setConnectedInfo(e,t);var n=this.steps.slice(0),i=this.totalStepCount,a=this.beginTimestamp.duration;this.steps.length=0,this.totalStepCount=0,this.sendTelemetry(r.Connected,{stepCount:n.length,totalStepCount:i,connectionEstablishmentMs_Total:a},n),this.cancelProgressTimer()},e.prototype.getSessionLength=function(){return Date.now()-this.connectedInfo.connectedTimestamp},e.prototype.trackDisconnected=function(e){e.sessionLengthMS=this.getSessionLength(),this.sendTelemetry(r.Disconnected,e,[]),this.resetProgressSendTimer()},e.prototype.trackNewConnection=function(){++this.connectionAttempt},e.prototype.trackResponse=function(e,t,n,a){var o={};a!==void 0&&(o.hasError=!0,o.error=a);try{o.responseTimestamp=n===void 0?Date.now():n.sentTS,e&&(o.requestID=e.id,o.httpMethod=e.method,o.shortUrl=(0,i.anonymizeShortUrl)(e.shortUrl),o.correlationVector=e.correlationVector,o.requestHeaders=(0,i.headersToLog)(e.headers)),n&&(o.latencyMS=t,o.responseCode=n.status,o.responseLength=n.body.length)}catch(e){o.hasError=!0,o.error=`${o.error} error creating response context ${(0,i.toJson)(e)}`}this.sendTelemetry(r.Response,o,[])},e.prototype.sendResponseError=function(e,t,n){this.trackResponse(t,void 0,n,e)},e.prototype.close=function(){this.sendProgress({reason:`closed`}),this.steps.length=0,this.cancelProgressTimer()},e.prototype.mergeSettings=function(e){if(e){this.eventLogSettings.numberOfStepsToMaintain=Math.min(40,Math.max(10,e.numberOfStepsToMaintain===void 0?0:e.numberOfStepsToMaintain));var t=Math.min(3600,Math.max(55,e.sendProgressTimeoutSecs===void 0?0:e.sendProgressTimeoutSecs));this.eventLogSettings.logHealthCheckError=e.logHealthCheckError,this.eventLogSettings.logSendPingError=e.logSendPingError;for(var n=0,i=Object.keys(r).map((function(e){return r[e]}));n<i.length;n++){var a=i[n];e[a]!==void 0&&(this.eventLogSettings[a]=e[a])}this.eventLogSettings.sendProgressTimeoutSecs!==t&&(this.eventLogSettings.sendProgressTimeoutSecs=t,this.resetProgressSendTimer())}},e}()},423:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManagerState=t.UserActivityEventReason=t.ServerState=void 0;var r,i,a=n(659);t.ServerState=function(){function e(e,t,n,r,i,a){this.connectionId=e,this.connectedClientId=t,this.domId=n,this.url=r,this.c2cUrlBase=i,this.expirationTsSec=a}return e.prototype.getRemainingTtlInSec=function(){return(0,a.calculateTtlInSec)(this.expirationTsSec)},e}(),function(e){e[e.Unknown=0]=`Unknown`,e[e.Modified=1]=`Modified`,e[e.Snapshot=2]=`Snapshot`,e[e.Connected=3]=`Connected`}(r||(t.UserActivityEventReason=r={})),function(e){e[e.Unknown=0]=`Unknown`,e[e.Connected=2]=`Connected`,e[e.Disconnected=3]=`Disconnected`,e[e.Switching=9]=`Switching`,e[e.TerminalError=10]=`TerminalError`}(i||(t.TrouterManagerState=i={}))},509:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.USER_AUTHENTICATE_EVENT_NAME=t.SUPPORTED_TOKEN_TYPES=t.FAILED_MESSAGE_ACK=t.UNHANDLED_MESSAGE_ACK=t.HANDLED_MESSAGE_ACK=t.CLIENT_VERSION=t.constants=void 0,t.constants={TROUTER_INIT:`trouterinit`,TROUTER_READY_EVENT:`trouterReadyEvent`,TROUTER_READY_TIMEOUT:`trouterReadyTimeout`,TROUTER_TOKEN_REQUEST:`trouterTokenRequest`,TROUTER_TOKEN_GET_SUCCEEDED:`trouterTokenGetSucceeded`,TROUTER_TOKEN_GET_FAILED:`trouterTokenGetFailed`,TROUTER_RECONNECTING:`trouterReconnecting`,RENEWAL:`renewal`,NEW_CONNECTION:`newConnection`,ENDPOINT_REGISTRATION_FAILED:`endpointRegistrationFailed`,SUBSCRIPTIONS_DEFAULT_SCOPE:`defaultScope`},t.CLIENT_VERSION=`2026.03.01.8`,t.HANDLED_MESSAGE_ACK=200,t.UNHANDLED_MESSAGE_ACK=404,t.FAILED_MESSAGE_ACK=500,t.SUPPORTED_TOKEN_TYPES=[`skype`,`aad`,`cae`],t.USER_AUTHENTICATE_EVENT_NAME=`user.authenticate`},573:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},a=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterConnection=t.ReconnectReason=void 0;var o,s=n(673),c=n(659),l=n(396),u=n(509),d=n(764),f=n(107),p=n(234),m=n(423),h=n(642),g=n(902),_=n(335),v=n(705),y=n(983),b=function(){this.cv=u.CLIENT_VERSION,this.ua=``,this.hr=``,this.v=``},x=function(){function e(){this[`force new connection`]=!0,this.reconnect=!1,this.query=``,this.ackTimeoutMs=5e3}return e.prototype.rewriteUrlForProxy=function(e){return e},e}(),S=`MS-CV`,C=function(){function e(e,t){this.logger=t,this.cvCounter=0;var n=JSON.parse(e);this.startTS=this.safeJsonNumber(n,`startTS`,0),this.url=this.safeJsonString(n,`url`,``),this.shortUrl=this.safeJsonString(n,`shortUrl`,``),this.body=this.safeJsonString(n,`body`,``),this.headers=this.safeJsonRecord(n,`headers`,{}),this.id=this.safeJsonNumber(n,`id`,-1),this.method=this.safeJsonString(n,`method`,``),this.replied=!1,this.timedout=!1,this.receivedCv=this.headers[S],this.updateCvHeader()}return Object.defineProperty(e.prototype,"correlationVector",{get:function(){return this.receivedCv?`${this.receivedCv}.${this.cvCounter}`:``},enumerable:!1,configurable:!0}),e.prototype.on=function(e,t){e===`data`?this.dataCallback=t:e===`end`&&(typeof this.dataCallback==`function`&&this.dataCallback(this.body),t())},e.prototype.incrementCorrelationVector=function(){++this.cvCounter,this.updateCvHeader()},e.prototype.updateCvHeader=function(){var e=this.correlationVector;e&&(this.headers[S]=e)},e.prototype.safeJsonNumber=function(e,t,n){var r;if(e!=null&&Object.prototype.hasOwnProperty.call(e,t)){var i=e;if(typeof i[t]==`number`)return i[t];if(typeof i[t]==`string`)return parseFloat(i[t]);(r=this.logger)==null||r.warn(`unexpected type of '${t}': ${typeof i[t]}`)}return n},e.prototype.safeJsonString=function(e,t,n){var r;if(e!=null&&Object.prototype.hasOwnProperty.call(e,t)){var i=e;if(typeof i[t]==`string`)return i[t];(r=this.logger)==null||r.warn(`unexpected type of '${t}': ${typeof i[t]}`)}return n},e.prototype.safeJsonRecord=function(e,t,n){var r;if(e!=null&&Object.prototype.hasOwnProperty.call(e,t)){var i=e;if(typeof i[t]==`object`)return i[t];(r=this.logger)==null||r.warn(`unexpected type of '${t}': ${typeof i[t]}`)}return n},e}(),w=function(){function e(e,t,n){this.request=e,this.responseData=t,this.sendResponse=n}return e.prototype.writeHead=function(e,t){this.responseData.status=e,this.responseData.headers=t},e.prototype.write=function(e){this.responseData.body+=e},e.prototype.end=function(e){return e&&(this.responseData.body+=e),this.sendResponse(this.request,this.responseData)},e}(),T=function(e){this.name=e,this.args={},this.timeoutTimerId=0};(function(e){e[e.Configuration=0]=`Configuration`,e[e.ServerInitiated=1]=`ServerInitiated`})(o||(t.ReconnectReason=o={}));var E=function(){function e(e,t,n,r,i,a,o,c){var d,p=this;this.logProvider=e,this.options=t,this.manager=n,this.tokenProvider=r,this.usingLegacyTokenApi=i,this.protocolSelector=o,this.audienceSubscriptionState=c,this.WEBSOCKET_TRANSPORT_NAME=`websocket`,this.XHR_POLLING_TRANSPORT_NAME=`xhr-polling`,this.AUDIENCE_SUBSCRIPTION_RESULT_ERROR=`Error`,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED=`Unsubscribed`,this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT=`Timeout`,this.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST=`BadRequest`,this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX=/&audienceSubscriptionState=[^&]*|^audienceSubscriptionState=[^&]*&?/,this.USER_ACTIVITY_QUERY_PARAM_REGEX=/userActivity=[^&]*/,this.connectionId=``,this.inIncallMode=!1,this.connectionAttempt=0,this.connectedClientId=``,this.isNavigatorOnline=!0,this.onNavigatorOnlineStatusUpdateBound=this.onNavigatorOnlineStatusUpdate.bind(this),this.c2cUrlBase=``,this.connectingErrorsInRow=0,this.connectivityCheckFailuresInARow=0,this.unauthorizedErrorCount=0,this.pendingSentEventTimers={},this.extraTransports={},this.clientDescriptionOverride={},this.lastDisconnectReason=``,this.UNKNOWN_TRANSPORT=`unknown_transport`,this.connectingErrorsThreshold=3,this.pendingAudienceSubscription=void 0,this.areSubscriptionsEqual=function(e,t){if(e.length!==t.length)return!1;e=e.sort((function(e,t){return e.id.localeCompare(t.id)})),t=t.sort((function(e,t){return e.id.localeCompare(t.id)}));for(var n=0;n<e.length;n++)if(e[n].id!==t[n].id)return!1;return!0},this.logger=new h.Logger(`Connection`,e),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff=new f.ExponentialBackoff(this.logger,this.timeoutOptions.maxBackoffMs),this.clientID=Date.now(),typeof window<`u`&&window.location&&(this.domId=window.location.hostname);var m=new b;m.cv=u.CLIENT_VERSION,m.ua=``,(d=this.options)!=null&&d.clientInfo&&(m.ua=this.safeString(this.options.clientInfo.ua),m.v=this.safeString(this.options.clientInfo.v)),this.clientInfo=m,this.connectionTracker=new l.ConnectionTracker(e,this.clientID,this.clientInfo,(function(){return p.getServerState()}),this.options.endpointId,this.options.clientCorrelationID,this.options.environment),this.applyConnectionTrackerOptions(t);var g=this.options.incallModeTimeoutMs>0;if(this.fsm=new _.TrouterFsm(e,this,g,this.protocolSelector),t.registration&&!t.registration.useRegistrarUrlFromAllocate){var v={registrarUrl:t.registration.registrarUrl,proxyUrlRewrite:t.rewriteUrlForProxy,registrationId:t.registration.registrationId,requestTimeoutMs:t.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:t.timeoutOptions.maxBackoffMs,usingLegacyTokenApi:this.usingLegacyTokenApi,maxRetriesForGetToken:t.retryLimitOnTokenFetch,extraRegistrationHeaders:t.extraConnectionHeaders};this.registrarClient=(0,s.createRegistrarClient)(e,this.tokenProvider,v)}this.userActivityState=a}return e.prototype.start=function(e,t,n){this.logger.info(`Starting`),this.reconnectParams=e,this.extraTransports=t??{},this.clientDescriptionOverride=n??{},typeof window<`u`&&window.navigator&&window.addEventListener?(this.isNavigatorOnline=window.navigator.onLine,window.addEventListener(`online`,this.onNavigatorOnlineStatusUpdateBound),window.addEventListener(`offline`,this.onNavigatorOnlineStatusUpdateBound),this.logger.debug(`Registered for browser online notifications - current state: ${this.isNavigatorOnline}`)):this.isNavigatorOnline=!0,this.fsm.start()},e.prototype.stop=function(e){this.logger.info(`Stopping`),typeof window<`u`&&window.navigator&&(window.removeEventListener(`online`,this.onNavigatorOnlineStatusUpdateBound),window.removeEventListener(`offline`,this.onNavigatorOnlineStatusUpdateBound)),this.fsm.stop(e),this.connectionTracker.close()},e.prototype.configure=function(e){var t=this.options.trouterUrl!==e.trouterUrl;this.options=e,this.applyConnectionTrackerOptions(e),t&&(this.logger.info(`Configuration changed. Reconnection required.`),this.fsm.onReconnectRequired(!1,o.Configuration))},e.prototype.checkConnection=function(e){this.logger.info(`checkConnection called with ${e}`),this.fsm.checkConnection(e),e&&this.connectionTracker.sendTelemetry(l.ClientEventName.CheckConnection,{disconnectDetected:e},[])},e.prototype.disableRegistrationsAndAutoReconnect=function(){this.stopRegistrationTimer(),this.cancelPendingRegistrationRequests(),this.fsm.disableAutoReconnect()},e.prototype.getServerState=function(){return new m.ServerState(this.connectionId,this.connectedClientId,this.domId?this.domId:``,this.allocateResult?this.allocateResult.surl:``,this.c2cUrlBase,this.connectionExpireTimestampInSecs)},e.prototype.getState=function(){return this.fsm.getState()},e.prototype.getToken=function(e,t,n,r,i){var a=this;i===void 0&&(i=0),this.logger.info(`Getting token ${t?`with backoff`:`without backoff`}`);var o=function(){a.connectionTracker.trackStart(`token`);var t={needFresh:!e,wwwAuthenticateHeader:n,supportedTokenTypes:u.SUPPORTED_TOKEN_TYPES,purpose:`trouter`};a.logger.info(`Requesting token: needFresh=${t.needFresh} types=[${u.SUPPORTED_TOKEN_TYPES}], wwwAuthenticateHeader is ${t.wwwAuthenticateHeader?`non empty`:`empty`}`),a.tokenProvider(t).then((function(e){a.logger.debug(`${e.tokenType} token is received`),a.connectionTracker.trackEnd(`token`),a.fsm.onTokenReceived(e,r,a.reconnectParams)})).catch((function(t){var o=(0,c.toJson)(t.stack);if(a.logger.error(`Getting token failed, will retry after timeout. Error: ${o}`),a.connectionTracker.trackError(`token`,o),!a.canRetryTokenFetchRequest(i+a.unauthorizedErrorCount))return a.connectionTracker.trackError(`token`,`getToken retry limit hit, reached terminal error state`),a.resetTokenBackoff(),void a.fsm.onTerminalError();a.getToken(e,!0,n,r,i+1)}))};t?this.tokenBackoff.backoff(`getting token`,o):(this.resetTokenBackoff(),o())},e.prototype.startConnectionTimer=function(){var e=this;this.stopConnectionTimer(),this.logger.debug(`Starting connection timeout for ${this.timeoutOptions.connectionTimeoutMs} ms`),this.connectionTimeoutId=setTimeout((function(){e.logger.info(`Connection timeout is fired`),e.fsm.onConnectingTimeout()}),this.timeoutOptions.connectionTimeoutMs)},e.prototype.stopConnectionTimer=function(){this.connectionTimeoutId&&=(this.logger.debug(`Stopping connection timeout`),clearTimeout(this.connectionTimeoutId),void 0)},e.prototype.startPingTimer=function(){var e=this;this.transportTypeName===`websocket`?(this.logger.debug(`Starting ping timeout for ${this.timeoutOptions.pingTimeoutMs} ms`),this.pingTimerId=setInterval((function(){e.logger.info(`Ping interval fired`),e.fsm.onPingInterval()}),this.timeoutOptions.pingTimeoutMs)):this.logger.debug(`Not starting ping for transport ${this.transportTypeName}`)},e.prototype.stopPingTimer=function(){this.pingTimerId&&=(this.logger.debug(`Stopping ping timeout`),this.clearPingResponseTimer(),clearInterval(this.pingTimerId),void 0)},e.prototype.shouldSkipRegistration=function(){return this.options.registration===void 0},e.prototype.hasCustomRegistrationTtl=function(){return this.options.registration?.registrarTtlSec!==void 0&&this.options.registration?.registrarTtlSec!==0},e.prototype.startRegistrationTimer=function(){var e=this;this.stopRegistrationTimer();var t=this.getRegistrationTtl(),n=t[0],r=t[1];if(n<=30||!r)return this.logger.debug(`Starting registration expiration timer (TTL ${n} sec)`),void(this.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.logger.warn(`Registration expired but the connection is still alive. Should never happen`),e.dispatchUnregistered()}),1e3*n));var i=n-30;this.logger.debug(`Starting registration extension timer for ${i} sec`),this.registrationTimerId=setTimeout((function(){e.logger.info(`Registration extension timer fired`),e.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.logger.debug(`Registration extension did not happen in time`),e.dispatchUnregistered()}),3e4),e.fsm.onRegistrationNearExpiry()}),1e3*i)},e.prototype.startRegistrationRetryTimer=function(){var e=this;this.stopRegistrationTimer(),this.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.fsm.onRetryRegistration()}),123e3)},e.prototype.stopRegistrationTimer=function(){this.registrationTimerId&&=(this.logger.debug(`Stopping registration timeout`),clearTimeout(this.registrationTimerId),void 0)},e.prototype.resendRegistration=function(){if(!this.registrarClient)throw Error(`Trouter Client not configured to handle registrations`);return this.fsm.onResendRegistration(),Promise.resolve()},e.prototype.registerExtraTransports=function(e,t){this.logger.info(`Registering ${Object.keys(e).length} extra transports`),this.extraTransports=e,this.clientDescriptionOverride=t??{},this.fsm.onExtraTransportsUpdated()},e.prototype.buildSocketIoUrlParams=function(e,t){if(!this.allocateResult)throw Error(`Allocate result is undefined in buildSocketIoUrlParams()`);for(var n={},r=this.allocateResult.connectparams,i=0,a=Object.keys(r);i<a.length;i++){var o=a[i];if(r[o]!==void 0){var s=r[o];typeof s==`string`||typeof s==`number`?n[o]=s:this.logger.error(`signatureData[${o}] has unsupported type ${typeof s}`)}}return n.v=`v4`,n.tc=encodeURI((0,c.toJson)(this.clientInfo)),n.timeout=this.timeoutOptions.pingTimeoutMs/1e3,n.auth=`true`,this.options.endpointId&&(n.epid=this.options.endpointId),e&&(n.userActivity=encodeURIComponent((0,c.toJson)(e))),t&&(n.audienceSubscriptionState=encodeURIComponent((0,c.toJson)(t))),this.appendConnectedClientIds(this.buildQuery(n),!0)},e.prototype.startSocketIo=function(e){if(this.logger.debug(`Starting socket io`),this.connectionTracker.trackStart(`connectSocket`),!this.allocateResult)throw Error(`Allocate result is undefined in startSocketIo()`);var t=this.options.ioOptions?r({},this.options.ioOptions):new x,n=this.userActivityState.state===p.UserActivityState.Unknown?void 0:this.userActivityState.increaseCvAndGetEventObject(),i=this.audienceSubscriptionState?.increaseCvAndGetEventObject();if(t[`force new connection`]=!0,t.reconnect=!1,t.rewriteUrlForProxy=this.options.rewriteUrlForProxy,t.requestHeaders=r(r({},this.options.extraConnectionHeaders),ee(e,this.usingLegacyTokenApi)),t.query=this.buildSocketIoUrlParams(n,i),this.logger.info(`connecting to ${this.allocateResult.socketio}`),this.stopSocketIo(),this.socket=(this.options.io??y).connect(this.allocateResult.socketio,t),this.socket===void 0)throw Error(`Can't create Socket.io object`);this.attachSocketIoHandlers(this.socket,e,n,i)},e.prototype.stopSocketIo=function(){if(this.socket){this.logger.debug(`clearing socket.io`);try{for(var e=0,t=[`connecting`,`connect`,`connect_failed`,`close_during_connecting`,`disconnect`,`reconnect`,`reconnect_failed`,`reconnecting`,`error`,`message`,`trouter.connected`,`trouter.reconnect`,`trouter.message_loss`,`audience.subscriptionresult`];e<t.length;e++){var n=t[e];this.socket.removeAllListeners(n)}this.socket.disconnect(),this.logger.debug(`cleared socket`),this.socket=void 0}catch(e){this.logger.error(`exception in disconnecting previous socket. Error: ${D(e)}`)}}},e.prototype.dispatchConnected=function(){this.logger.info(`dispatching connected`),this.manager.onConnected(this)},e.prototype.dispatchRegistered=function(){this.logger.info(`dispatching registered`),this.manager.onRegistered(this)},e.prototype.dispatchUnregistered=function(){this.logger.info(`dispatching unregistered`),this.manager.onUnregistered(this)},e.prototype.dispatchDownstreamRequest=function(e){var t=this;this.logger.debug(`dispatching downstream request`);try{var n=new w(e,new l.ResponseData(e.id),(function(e,n){return t.logger.debug(`sending response to downstream`),t.sendResponse(e,n)}));this.manager.onDownstreamRequest(this,e,n)}catch(e){this.logger.error(`exception in socket.on message. Error : ${D(e)}`)}},e.prototype.dispatchReconnecting=function(){this.logger.info(`dispatching reconnecting`),this.manager.onReconnecting(this)},e.prototype.dispatchReconnectIsRequired=function(e,t){this.logger.info(`dispatching reconnect is required by server`),this.manager.onReconnectIsRequired(this,e,t)},e.prototype.dispatchDisconnected=function(){this.logger.info(`dispatching disconnected`),this.manager.onDisconnected(this)},e.prototype.dispatchTerminalError=function(){this.logger.info(`dispatching terminal error`),this.manager.onTerminalError(this)},e.prototype.dispatchTrouterMessageLost=function(e){this.logger.info(`dispatching trouter message lost`),this.manager.onTrouterMessageLost(e)},e.prototype.countDisconnectBeforeConnectionEstablishment=function(){this.logger.warn(`counting disconnect before connection was fully established as a connection failure`),this.connectingErrorsInRow++,this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold()},e.prototype.sendProcessedDroppedIndicators=function(e){var t=this;try{this.logger.debug(`emitting processed flow tags to the server`);var n=new T(`trouter.processed_message_loss`);n.args={droppedIndicators:e},this.sendDownstreamEvent(n,(function(){t.logger.info(`emitted processed flow tags to the server`)}))}catch(e){var r=D(e);this.logger.error(`unable to send processed message loss event. Error: ${r}`),this.connectionTracker.trackError(`trouter.processed_message_loss`,r,!1)}},e.prototype.sendAllocateRequest=function(e){var t=this;this.connectionAttempt++,this.connectionTracker.trackNewConnection();var n,i=this.options.trouterUrl,a=this.reconnectParams,o=typeof a?.se==`string`?parseInt(a.se,10):typeof a?.se==`number`?a.se:void 0;o&&o<=Date.now()+36e5&&(this.logger.warn(`Dropping expired cached connection parameters: ${new Date(o)}`),this.reconnectParams=a=void 0),a&&a.serviceUrl!==i&&(this.logger.warn(`Dropping cached connection parameters for a different environment (${a.serviceUrl}, now ${i})`),this.reconnectParams=a=void 0),a!=null&&a.reconnectUrl&&(i=a.reconnectUrl),n=a?r(r({},a),{serviceUrl:void 0,reconnectUrl:void 0}):null,i=(0,g.adaptUrl)(i,`v4a`),i=this.appendCorrelationIds(i,!1),i=this.appendEndpointId(i,!1);var s=i=this.appendClientInfo(i,!1);n&&(i+=`&${this.buildQuery(n)}`,n.v||(i+=`&v=v4`)),i=this.options.rewriteUrlForProxy(i);var l=new Request(i,{method:`POST`,mode:`cors`,headers:new Headers(r(r({"Content-Type":`text/plain`},this.options.extraConnectionHeaders),ee(e,this.usingLegacyTokenApi)))});this.logger.info(`sendAllocateRequest: POST ${this.options.rewriteUrlForProxy(s)} (connectparams redacted)}`),this.connectionTracker.trackStart(`allocation`);var u,d=Date.now(),f=-1,p=!1;(0,c.fetchWithTimeout)(l,this.timeoutOptions.fetchTimeoutMs).then((function(e){if(f=e.status,!e.ok)throw u=e.headers.get(`www-authenticate`)??void 0,p=e.headers.get(`x-trouter-skypetoken-deprecated`)===`1`,t.logger.warn(`Allocation request got response status ${e.status}, www-authenticate header was ${u?`not empty`:`empty`}`),Error(e.statusText);var n=e.headers.get(`content-type`);if(!n||n!==`application/json`&&!n.startsWith(`application/json;`))throw Error(`Content-type '${n}' is unexpected`);return t.connectionTracker.trackEnd(`allocation`),e.json()})).then((function(n){t.unauthorizedErrorCount=0,t.onAllocationResponse(n,e)})).catch((function(e){t.connectingErrorsInRow++;var n=`${e}${f>=0?`, status code ${f}`:``}`;if(t.logger.error(`${t.connectingErrorsInRow} failed connecting attempt(s) in a row. ${n}`),t.connectionTracker.trackError(`allocation`,n),p){var r=`Skypetoken deprecated response, not retrying any further`;t.logger.error(r),t.connectionTracker.trackError(`allocation`,r),t.fsm.onTerminalError();return}if(f===401&&t.unauthorizedErrorCount++,!t.canRetryTokenFetchRequest(t.unauthorizedErrorCount))return r=`getToken retry limit hit, reached terminal error state`,t.connectionTracker.trackError(`allocation`,r),void t.fsm.onTerminalError();if(f!==-1||t.isNavigatorOnline){if(t.reconnectParams&&t.connectingErrorsInRow>=t.connectingErrorsThreshold){if(f>=400&&f<=599)t.resetReconnectParamsOnErrorThreshold();else if(t.reconnectParams.reconnectUrl&&t.connectingErrorsInRow%3==0){t.logger.warn(`${t.connectingErrorsInRow} connection attempts, testing nominal service URL`);var i=Math.min(t.timeoutOptions.connectionTimeoutMs-(Date.now()-d)-500,t.timeoutOptions.fetchTimeoutMs);t.testNominalUrlConnectivity(i).then((function(e){t.connectionTracker.trackProgress(`nomcheck`,e?`ok`:`failed`),e?(t.logger.warn(`Nominal service URL is reachable, erasing cached reconnect URL`),t.reconnectParams&&delete t.reconnectParams.reconnectUrl):t.logger.warn(`Nominal service URL is not reachable either, keeping cached reconnect URL`),t.fsm.onAllocationFailed(!1,void 0)}),(function(){t.fsm.onAllocationFailed(!1,void 0)}));return}}}else t.logger.info(`Expected failure, the browser says it is not online at the moment`);t.fsm.onAllocationFailed(f===401,u)}))},e.prototype.testNominalUrlConnectivity=function(e){var t,n=this;if(e<1e3)return this.logger.warn(`There is no time left to reasonably perform the nominal service URL connectivity check (${e} ms), falling back to assuming that the connectivity is fine`),Promise.resolve(!0);try{var r=new URL(this.options.trouterUrl);r.pathname=r.pathname.replace(/\/v4\/.*/,`/`),r.search=`?`+this.buildQuery({check:Date.now(),cor_id:encodeURIComponent(this.options.clientCorrelationID),epid:encodeURIComponent(this.options.endpointId?this.options.endpointId:``),tc:encodeURIComponent((0,c.toJson)(this.clientInfo))}),r.protocol===`wss:`&&(r.protocol=`https:`),t=new Request(this.options.rewriteUrlForProxy(r.toString()),{method:`GET`,headers:{Accept:`text/plain`}})}catch(e){return this.logger.warn(`Nominal service URL connectivity test request could not be created (${e}), falling back to assuming that the connectivity is fine`),Promise.resolve(!0)}return(0,c.fetchWithTimeout)(t,e).then((function(e){if(e.status!==200)throw Error(`Not 200 OK: ${e.status} ${e.statusText}`);return e.text()})).then((function(e){if(e!==`Trouter`)throw Error(`Not "Trouter": ${e.substring(0,16)}${e.length>16?`...`:``}`);return!0})).catch((function(e){return n.logger.error(`Nominal service URL connectivity test failed: ${e}`),!1}))},e.prototype.sendPingRequest=function(){var e=this;if(this.socket&&this.pingResponseTimerId===void 0)try{this.logger.debug(`emitting ping event`);var t=!1;this.socket.emit(`ping`,(function(){!0!==t&&e.onPingResponse()})),this.pingResponseTimerId=setTimeout((function(){e.logger.error(`Ping response timeout is fired`),t=!0,e.clearPingResponseTimer(),e.fsm.onPingResponseTimeout()}),this.timeoutOptions.pongTimeoutMs)}catch(e){var n=D(e);this.logger.error(`unable to send ping. Error: ${n}`),this.connectionTracker.trackError(`ping`,n,!1)}},e.prototype.connectV4c=function(e,t){return i(this,void 0,void 0,(function(){var n,i,o,s,c;return a(this,(function(a){switch(a.label){case 0:return[4,this.performV4cInitialConnectivityCheck()];case 1:if(!1===a.sent())return[2];(n=this.options.ioOptions?r({},this.options.ioOptions):new x)[`force new connection`]=!0,n.reconnect=!1,(c=this.reconnectParams)!=null&&c.serviceUrl&&(0,g.adaptUrl)(this.reconnectParams.serviceUrl,`v4c`)!==(0,g.adaptUrl)(this.options.trouterUrl,`v4c`)&&(this.logger.warn(`Dropping cached connection parameters for a different environment (${this.reconnectParams.serviceUrl}, now ${this.options.trouterUrl})`),this.reconnectParams=void 0),i=(0,g.redirectUrlIfPresent)(t)??(t?.kind===`redirect-no-host`?void 0:this.reconnectParams?.reconnectUrl)??this.options.trouterUrl,o=(0,g.adaptUrl)(i,`v4c`),n[`skipped handshake data`]={timeout:70,websocketUrl:o},n.query=this.buildV4cUrlParams(),n.rewriteUrlForProxy=this.options.rewriteUrlForProxy;try{if(this.stopSocketIo(),this.transportTypeName=`websocket`,this.socket=(this.options.io??y).connect(this.options.trouterUrl,n),this.socket===void 0)throw Error(`failed to create Socket.io object`);s=this.audienceSubscriptionState?.increaseCvAndGetEventObject(),this.attachSocketIoHandlers(this.socket,e,void 0,s)}catch(e){this.logger.error(`${e}`),this.connectionTracker.trackError(`v4c`,`${e}`),this.fsm.onV4cException()}return[2]}}))}))},e.prototype.performV4cInitialConnectivityCheck=function(){return i(this,void 0,void 0,(function(){return a(this,(function(e){switch(e.label){case 0:return this.options.initialConnectivityCheck?(this.logger.info(`checking connectivity to configured URL (go URL) before a connection attempt`),[4,this.testNominalUrlConnectivity(3e3)]):[2,!0];case 1:return e.sent()?(this.connectivityCheckFailuresInARow=0,[2,!0]):this.connectivityCheckFailuresInARow>=3?(this.connectivityCheckFailuresInARow=0,this.logger.error(`three connectivity checks failed in a row, will attempt with the fallback protocol`),this.fsm.onV4cException(),[2,!1]):(this.logger.warn(`connectivity check failed, will retry after backoff`),this.connectivityCheckFailuresInARow++,this.fsm.onV4cConnectivityCheckFailed(),[2,!1])}}))}))},e.prototype.sendV4cAuthenticationEvent=function(e){var t,n={headers:r(r({},this.options.extraConnectionHeaders),ee(e,this.usingLegacyTokenApi)),connectparams:(0,g.reconnectParamsWithoutUrls)(this.reconnectParams)};(t=this.socket)==null||t.emit(u.USER_AUTHENTICATE_EVENT_NAME,n)},e.prototype.setUserActivityState=function(e){var t=e.state!==this.userActivityState.state;this.userActivityState=e,t?(this.logger.info(`Changing user activity state to '${e.toEventJSON()}'`),this.fsm.onSetNewUserActivityState()):(this.logger.debug(`Not changing the same user activity state '${e.toEventJSON()}'`),this.manager.onUserActivityStateAccepted(e.correlationVector.value()))},e.prototype.sendUserActivityState=function(e,t){if(this.userActivityState.state!==p.UserActivityState.Unknown){if(this.options.updateUserActivityDuringConnectionAttempt&&this.socket){var n=this.userActivityState.toEventObject(),r=this.socket.socket.options.query;if(r){var i=`userActivity=${encodeURIComponent((0,c.toJson)(n))}`;r.search(this.USER_ACTIVITY_QUERY_PARAM_REGEX)==-1?this.socket.socket.options.query=r.concat(`&`,i):this.socket.socket.options.query=r.replace(this.USER_ACTIVITY_QUERY_PARAM_REGEX,i)}}this.transportTypeName===`websocket`&&t?e===m.UserActivityEventReason.Connected?this.sendUserActivityStateMultiple(2):this.sendUserActivityStateMultiple(1):this.transportTypeName===`xhr-polling`&&e===m.UserActivityEventReason.Modified&&this.fsm.forceReconnect(`user activity/force reconnect`)}},e.prototype.setAudienceSubscriptionsAsync=function(e,t){var n=this.audienceSubscriptionState;if(this.audienceSubscriptionState=e,this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME)return this.setAudienceSubscriptionsInternalAsync(e.increaseCvAndGetEventObject(),t);if(this.transportTypeName===this.XHR_POLLING_TRANSPORT_NAME){var r=this.setAudienceSubscriptionsLongpollInternalAsync(e.increaseCvAndGetEventObject(),t,n);return this.fsm.forceReconnect(`set audience subscription force reconnect`),r}throw Error(`set audience subscription executed on an unknown transport`)},e.prototype.setAudienceSubscriptionsUnsafeAsync=function(e){if(e)return this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME?this.setAudienceSubscriptionsInternalAsync(e,15e3):void 0},e.prototype.onAudienceSubscriptionResult=function(e){if(this.logger.info(`onAudienceSubscriptionResult`),this.pendingAudienceSubscription)return clearTimeout(this.pendingAudienceSubscription.timeoutId),this.pendingAudienceSubscription.audienceSetResolve(e),void(this.pendingAudienceSubscription=void 0);if(this.audienceSubscriptionState&&this.transportTypeName===this.XHR_POLLING_TRANSPORT_NAME){var t=new Set(this.audienceSubscriptionState.toListOfSubscriptions().map((function(e){return e.id}))??[]),n=this.audienceSubscriptionState.correlationVector.value();this.cleanPollingAudienceSubscriptionStateQueryParam(t,e,n),this.manager.onAudiencesSetResolved(e,n)}},e.prototype.setAudienceSubscriptionsInternalAsync=function(e,t){return i(this,void 0,void 0,(function(){var n,r,i=this;return a(this,(function(a){switch(a.label){case 0:return this.logger.info(`[WebSocket] Audience subscription set requested.`),(n=new T(`audience.subscribe`)).args=e,[4,new Promise((function(r){var a=!1,o=setTimeout((function(){return a=!0,r(i.buildAudienceSubscriptionsTimeoutResponse(e))}),t);i.sendDownstreamEvent(n,(function(e,t){a||(clearTimeout(o),i.logger.debug(`[Websocket] Audience subscription response: ${t}`),i.pendingAudienceSubscription&&i.onAudienceSubscriptionResult(t),r(t))}))}))];case 1:return r=a.sent(),this.manager.onAudiencesSetResolved(r,e.cv),[2,r]}}))}))},e.prototype.setAudienceSubscriptionsLongpollInternalAsync=function(e,t,n){return i(this,void 0,void 0,(function(){var r,i,o,s,c=this;return a(this,(function(a){switch(a.label){case 0:return this.logger.info(`[XHR Polling] Audience subscription set requested.`),this.pendingAudienceSubscription&&(this.logger.error(`Racing audience subscriptions occured. This situation resolves into undefined scenario and/or nasal demons.`),clearTimeout(this.pendingAudienceSubscription.timeoutId)),[4,new Promise((function(n){c.pendingAudienceSubscription={audienceSetResolve:n,timeoutId:setTimeout((function(){return c.pendingAudienceSubscription=void 0,n(c.buildAudienceSubscriptionsTimeoutResponse(e))}),t)}}))];case 1:return r=a.sent(),this.manager.getState()===p.TrouterState.Unknown||this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME||(this.logger.debug(`[XHR Polling] Audience subscription response: ${r}`),i=new Set(e.audiences.map((function(e){return e.id}))??[]),this.cleanPollingAudienceSubscriptionStateQueryParam(i,r,e.cv),o=this.handleAudienceUnsubscribeLongpoll(e,n),(s=r.responses).push.apply(s,o),this.manager.onAudiencesSetResolved(r,e.cv)),[2,r]}}))}))},e.prototype.cleanPollingAudienceSubscriptionStateQueryParam=function(e,t,n){var r=this,i=t.responses.filter((function(t){return t.result.audienceSubscriptionState===r.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST&&e.has(t.audienceId)})),a=t.responses.filter((function(t){return t.result.audienceSubscriptionState===r.AUDIENCE_SUBSCRIPTION_RESULT_ERROR&&e.has(t.audienceId)})),o=t.responses.filter((function(t){return t.result.audienceSubscriptionState===r.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT&&e.has(t.audienceId)})),s=i.map((function(e){return e.audienceId})),c=a.map((function(e){return e.audienceId})),l=o.map((function(e){return e.audienceId})),u=Array.from(e).filter((function(e){return s.indexOf(e)===-1&&c.indexOf(e)===-1&&l.indexOf(e)===-1})).map((function(e){return{id:e}}));u.length===0?this.clearAudienceSubscriptionStateQueryParam():this.updateAudienceSubscriptionStateQueryParam(u,n)},e.prototype.clearAudienceSubscriptionStateQueryParam=function(){var e;(e=this.socket?.socket?.options)!=null&&e.query&&(this.socket.socket.options.query=this.socket.socket.options.query.replace(this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX,``))},e.prototype.updateAudienceSubscriptionStateQueryParam=function(e,t){if(this.socket?.socket?.options?.query){var n=encodeURIComponent(JSON.stringify({audiences:e,cv:t})),r=this.socket.socket.options.query,i=(0,v.updateAudienceSubscriptionQuery)(r,n);this.socket.socket.options.query=i}},e.prototype.handleAudienceUnsubscribeLongpoll=function(e,t){var n=[],r=t?.toListOfSubscriptions()??[],i=!this.areSubscriptionsEqual(r,e.audiences);if(r.length>0&&i&&t){var a=r.filter((function(t){return e.audiences.find((function(e){return e.id===t.id}))===void 0})),o=this.mapToSyntheticAudienceSubscriptionResponses(a,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED,200);n.push.apply(n,o)}return n},e.prototype.buildAudienceSubscriptionsTimeoutResponse=function(e){return this.logger.error(`Audience subscription attempt has timed out.`),{responses:this.mapToSyntheticAudienceSubscriptionResponses(e.audiences,this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT)}},e.prototype.mapToSyntheticAudienceSubscriptionResponses=function(e,t,n){return e===void 0?[]:e.map((function(e){return{audienceId:e.id,result:{audienceSubscriptionState:t,responseStatus:n}}}))},e.prototype.expediteBackoff=function(){this.tokenBackoff.expediteIfPending()},e.prototype.sendRegisterRequest=function(){var e=this;if(!this.options.registration)throw Error(`Internal error - options.registration is undefined`);if(!this.allocateResult)throw Error(`Allocate result is undefined in sendRegisterRequest()`);if(this.options.registration.useRegistrarUrlFromAllocate&&!this.registrarClient){if(!this.allocateResult.registrarUrl)throw Error(`Internal error - useRegistrarUrlFromAllocate is true, but allocateResult did not include registrarUrl`);var t={registrarUrl:this.allocateResult.registrarUrl,proxyUrlRewrite:this.options.rewriteUrlForProxy,registrationId:this.options.registration.registrationId,requestTimeoutMs:this.options.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:this.options.timeoutOptions.maxBackoffMs,usingLegacyTokenApi:this.usingLegacyTokenApi,maxRetriesForGetToken:this.options.retryLimitOnTokenFetch,extraRegistrationHeaders:this.options.extraConnectionHeaders};this.registrarClient=(0,s.createRegistrarClient)(this.logProvider,this.tokenProvider,t)}if(!this.registrarClient)throw Error(`Internal error - registrarClient is undefined`);this.logger.info(`sending register request with ${1+Object.keys(this.extraTransports).length} transports and ${Object.keys(this.clientDescriptionOverride).length} overridden client description properties`),this.connectionTracker.trackStart(`registration`);var n=this.getRegistrationTtl()[0];this.registrarClient.register(r({appId:this.options.registration.pnhAppId,aesKey:``,languageId:`en-US`,platform:this.options.registration.platform,templateKey:this.options.registration.pnhTemplateKey,platformUIVersion:this.options.registration.platformUIVersion,productContext:this.options.registration.productContext},this.clientDescriptionOverride),r({TROUTER:[{context:this.options.registration.context,path:this.allocateResult.surl,ttl:n}]},this.extraTransports)).then((function(){e.logger.info(`Register request successful`),e.connectionTracker.trackEnd(`registration`),e.fsm.onRegistrationSucceeded()})).catch((function(t){e.logger.error(`Register request failed. Error: ${t}`),e.connectionTracker.trackError(`registration`,O(t)),e.fsm.onRegistrationFailed()}))},e.prototype.sendUnregisterRequest=function(){var e=this;if(Object.keys(this.extraTransports).length>0&&this.logger.warn(`explicit unregister called while there are extra transports`),this.logger.info(`sending unregister request`),!this.options.registration||!this.registrarClient)throw Error(`Internal error - options.registration is undefined`);this.connectionTracker.trackStart(`unregistration`),this.registrarClient.unregister().then((function(){e.logger.info(`Unregister request successful`),e.connectionTracker.trackEnd(`unregistration`),e.fsm.onUnregistrationDone()})).catch((function(t){e.logger.error(`Unregister request failed. Error: ${t}`),e.connectionTracker.trackError(`unregistration`,O(t)),e.fsm.onUnregistrationDone()}))},e.prototype.resetTokenBackoff=function(){this.tokenBackoff.reset()},e.prototype.cancelPendingRegistrationRequests=function(){this.registrarClient&&this.registrarClient.cancelPendingRequests()},e.prototype.clearSentEventTimers=function(){var e=Object.keys(this.pendingSentEventTimers);if(e.length>0){this.logger.debug(`Clearing all pending downstream events related timers`);for(var t=0,n=e;t<n.length;t++){var r=n[t];this.clearSentEventTimer(Number(r))}}},e.prototype.restartIncallModeTimer=function(){var e=this;this.clearIncallModeTimerId(),this.logger.debug(`Restarting incall mode timer`),this.incallModeTimerId=setTimeout((function(){e.logger.info(`Call mode timer fired`),e.fsm.onIncallModeTimer()}),this.options.incallModeTimeoutMs)},e.prototype.enterIncallMode=function(){this.logger.info(`Entering incall mode`),this.timeoutOptions=this.options.incallTimeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!0},e.prototype.exitIncallMode=function(){this.logger.info(`Exiting incall mode`),this.clearIncallModeTimerId(),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!1},e.prototype.isIncallMode=function(){return this.inIncallMode},e.prototype.sendDisconnectTelemetryEvent=function(e){var t={reason:e,serverClosed:!this.fsm.isActive()};this.connectionTracker.trackDisconnected(t),this.connectionTracker.clearConnectedInfo()},e.prototype.forceReconnectDueToNoRegistration=function(){this.fsm.forceReconnect(`force reconnect due to no registration`)},e.prototype.resetReconnectParamsOnErrorThreshold=function(){this.logger.warn(`${this.connectingErrorsInRow} connection attempts, server-side failure: erasing cached connection parameters`),this.reconnectParams=void 0},e.prototype.onSocketConnecting=function(e){this.logger.info(`onSocketConnecting(${e})`),this.transportTypeName=e,this.connectionTracker.trackProgress(`connecting`,this.transportTypeName),this.fsm.onConnecting()},e.prototype.onSocketConnect=function(e){this.logger.info(`onSocketConnect`),this.fsm.onSocketConnect(e)},e.prototype.onSocketConnectFailed=function(e){this.logger.error(`onSocketConnectFailed`),this.connectionTracker.trackError(`connect_failed`,e,!0,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),this.fsm.onConnectingFailed()},e.prototype.onSocketDisconnect=function(e){var t=this.connectionTracker.getSessionLength()||0,n=d.DisconnectReason.fromRawReason(e);this.logger.error(`onSocketDisconnect, reason: ${n.reason}`),n.reason===`dup`&&this.lastDisconnectReason===`dup`&&t<this.options.duplicateDisconnectThresholdMs&&(this.logger.warn(`Socket was closed by server as Duplicate for the second time in a row after ${t} ms which is below the threshold of ${this.options.duplicateDisconnectThresholdMs} ms. Resetting cached connection parameters and making a new allocation.`),this.reconnectParams=void 0),this.lastDisconnectReason=n.reason,this.fsm.onSocketDisconnect(n),this.connectionExpireTimestampInSecs=void 0},e.prototype.onSocketReconnect=function(){this.logger.error(`onSocketReconnect`),this.fsm.onTrouterConnected()},e.prototype.onSocketReconnectFailed=function(e){this.logger.error(`onSocketReconnectFailed with '${e}'`),this.fsm.onSocketDisconnect(d.DisconnectReason.fromSocketIoEventData(`reconnecterror`,e))},e.prototype.onSocketReconnecting=function(){this.logger.error(`onSocketReconnecting`)},e.prototype.onSocketError=function(e){var t;this.logger.error(`onSocketError with '${(0,c.toJson)(e)}'`),this.fsm.isConnecting()&&(this.connectingErrorsInRow++,this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold()),this.connectionTracker.trackError(`connectSocket`,(t=e)!=null&&typeof t.toString==`function`?t.toString():`[${typeof t}]`),this.fsm.onSocketDisconnect(d.DisconnectReason.fromSocketIoEventData(`socketerror`,e))},e.prototype.onSocketMessage=function(e){var t,n=this;this.logger.debug(`onSocketMessage`);try{var r=(t=new C(e,this.logger)).headers?.[`X-Microsoft-Skype-Chain-ID`],i=r?` Chain-Id ${r}`:``;this.logger.info(`Received request N ${t.id}${i} CV ${t.correlationVector} to '${t.url}'`),t.startTS=Date.now(),t.url&&this.urlPath&&t.url.startsWith(this.urlPath)&&(t.shortUrl=t.url.substring(this.urlPath.length))}catch(e){var a=D(e);this.logger.error(`unable to parse request. Error: ${a}`),this.connectionTracker.sendResponseError(`unable to parse request, error: ${e}`);return}t.timeoutTimerId=setTimeout((function(){if(!t.replied){n.logger.error(`Request ${t.id} timed out`);var e=new l.ResponseData(t.id);e.status=504,e.headers={"Trouter-Responder":`ClientLib`},n.sendResponse(t,e),t.timedout=!0}}),this.timeoutOptions.requestTimeoutMs);try{this.fsm.onDownstreamRequest(t)}catch(e){this.logger.error(`exception in socket.on message. Error: ${D(e)}`),this.connectionTracker.sendResponseError(O(e),t,void 0)}},e.prototype.onTrouterConnected=function(e,t,n){var i,a,o=this;if((0,g.isV4ConnectEvent)(e)){var s=e;this.allocateResult=r(r({},s),{ttl:e.ttl.toString()}),this.populateAndCacheReconnectParams(s,s.reconnectUrl),this.populateConnectionStateFields(s)}else if(!this.allocateResult)return void this.logger.error(`Invalid internal state - received onTrouterConnected while allocateResult is not set`);this.connectingErrorsInRow=0,this.logger.info(`onTrouterConnected: ${this.allocateResult.surl}`),this.options.updateUserActivityDuringConnectionAttempt?this.transportTypeName===`xhr-polling`&&((t?.state??`unknown`)===this.userActivityState.getStateString()?t&&this.manager.onUserActivityStateAccepted(t.cv):(this.logger.info(`XHR user activity changed during connection attempt, from '${(0,c.toJson)(t)}' to '${this.userActivityState.toEventJSON()}', updating`),this.sendUserActivityStateIgnoreResponse())):this.transportTypeName===`xhr-polling`&&t&&this.manager.onUserActivityStateAccepted(t.cv),(i=this.socket?.socket?.options)!=null&&i.query&&(this.socket.socket.options.query+=`&connected=true`),this.urlPath=this.allocateResult.surl.replace(/https?:\/\/([A-z0-9\:\$\-\_\.\+\!\*\"\(\)\,]*)\//,`/`);var l=this.connectedUrl!==this.allocateResult.surl;this.connectedUrl=this.allocateResult.surl,this.connectionExpireTimestampInSecs=(0,c.calculateExpireTsInSec)((0,g.ensureNumber)(e.ttl)),this.connectionTracker.trackEnd(`connectSocket`),this.connectionTracker.trackConnected(l,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),(a=this.setAudienceSubscriptionsUnsafeAsync(n))==null||a.catch((function(e){return o.logger.error(`Re-subscribe to audiences has failed with ${e}`)})),this.fsm.onTrouterConnected()},e.prototype.onTrouterReconnect=function(e){var t=e.target;this.logger.info(`onTrouterReconnect target: ${t}`),t===`self`?this.fsm.onReconnectRequired(!0,o.ServerInitiated):this.fsm.onReconnectRequired(!1,o.ServerInitiated,e)},e.prototype.onTrouterMessageLoss=function(e){this.logger.debug(`onTrouterMessageLoss`),this.fsm.onTrouterMessageLost(e.droppedIndicators)},e.prototype.buildV4cUrlParams=function(){var e={};return e.tc=encodeURI((0,c.toJson)(this.clientInfo)),e.timeout=Math.floor(this.timeoutOptions.pingTimeoutMs/1e3),this.options.endpointId&&(e.epid=this.options.endpointId),this.appendConnectedClientIds(this.buildQuery(e),!0)},e.prototype.attachSocketIoHandlers=function(e,t,n,r){var i=this;e.on(`connecting`,(function(e){i.onSocketConnecting(e)})),e.on(`connect`,(function(){i.onSocketConnect(t)})),e.on(`connect_failed`,(function(e){i.onSocketConnectFailed(e)})),e.on(`close_during_connecting`,(function(e){i.onSocketConnectFailed(e)})),e.on(`disconnect`,(function(e){i.onSocketDisconnect(e)})),e.on(`reconnect`,(function(){i.onSocketReconnect()})),e.on(`reconnect_failed`,(function(e){i.onSocketReconnectFailed(e)})),e.on(`reconnecting`,(function(){i.onSocketReconnecting()})),e.on(`error`,(function(e){i.onSocketError(e)})),e.on(`message`,(function(e){i.onSocketMessage(e)})),e.on(`trouter.connected`,(function(e){i.onTrouterConnected(e,n,r)})),e.on(`trouter.reconnect`,(function(e){i.onTrouterReconnect(e)})),e.on(`trouter.message_loss`,(function(e){i.onTrouterMessageLoss(e)})),e.on(`audience.subscriptionresult`,(function(e,t){i.onAudienceSubscriptionResult(t)}))},e.prototype.onNavigatorOnlineStatusUpdate=function(){var e=window.navigator.onLine;this.logger.debug(`Browser online status update - new state: ${e}, previously: ${this.isNavigatorOnline}`),e&&!this.isNavigatorOnline?(this.isNavigatorOnline=!0,this.tokenBackoff.expediteIfPending(),this.connectionTracker.trackProgress(`browserNet`,`online`)):!e&&this.isNavigatorOnline&&(this.isNavigatorOnline=!1,this.connectionTracker.trackProgress(`browserNet`,`offline`))},e.prototype.onAllocationResponse=function(e,t){this.logger.info(`Received allocation response ${JSON.stringify(r(r({},e),{connectparams:void 0}))} (connectparams redacted)`),this.allocateResult=e,this.populateAndCacheReconnectParams(this.allocateResult,`${this.allocateResult.socketio}v4/a`),this.populateConnectionStateFields(this.allocateResult),this.fsm.onAllocationSucceed(t)},e.prototype.populateAndCacheReconnectParams=function(e,t){this.reconnectParams=r({serviceUrl:this.options.trouterUrl,reconnectUrl:t},e.connectparams),this.manager.onConnectionParametersUpdated(this.reconnectParams)},e.prototype.populateConnectionStateFields=function(e){var t=typeof e.ttl==`string`?parseInt(e.ttl,10):e.ttl;if(this.connectionExpireTimestampInSecs=(0,c.calculateExpireTsInSec)(t),this.connectionId=e.id??``,this.connectedClientId=e.ccid,this.logger.debug(`connected client id set {connectedClientId:${this.connectedClientId}}`),this.c2cUrlBase=e.curlb??``,this.c2cUrlBase===``){var n=e.surl.indexOf(`://`);n>=0&&(n=e.surl.indexOf(`/`,n+3))>=5&&e.surl.substr(n-5,5)===`:3443`&&(this.c2cUrlBase=e.surl.substr(0,n-5))}},e.prototype.onPingResponse=function(){this.logger.debug(`onPingResponse`),this.connectionTracker.increasePingResponseCount(),this.clearPingResponseTimer(),this.fsm.onPingResponse()},e.prototype.clearPingResponseTimer=function(){this.pingResponseTimerId!==void 0&&(clearTimeout(this.pingResponseTimerId),this.pingResponseTimerId=void 0)},e.prototype.buildQuery=function(e){for(var t=[],n=0,r=Object.keys(e);n<r.length;n++){var i=r[n];e[i]!==void 0&&t.push(`${i}=${e[i]}`)}return t.join(`&`)},e.prototype.appendConnectedClientIds=function(e,t){var n=``;e.includes(`ccid=`)||(n=`ccid=${this.connectedClientId}&`),this.domId&&(n+=`dom=${this.domId}&`),n.length>0&&(n=n.slice(0,-1));var r=t||e.includes(`?`)?`&`:`?`;return this.appendCorrelationIds(e+r+n,t)},e.prototype.appendEndpointId=function(e,t){var n=t||e.includes(`?`)?`&`:`?`;return!e.includes(`epid`)&&this.options.endpointId?`${e}${n}epid=${this.options.endpointId}`:e},e.prototype.appendCorrelationIds=function(e,t){var n=t||e.includes(`?`)?`&`:`?`;return e.includes(`cor_id`)?e:`${e}${n}cor_id=${this.options.clientCorrelationID}&con_num=${this.clientID}_${this.connectionAttempt}`},e.prototype.appendClientInfo=function(e,t){var n=t||e.includes(`?`)?`&`:`?`,r=encodeURIComponent((0,c.toJson)(this.clientInfo));return e.includes(`tc=`)?e:`${e}${n}tc=${r}`},e.prototype.safeString=function(e){return typeof e==`string`?e:``},e.prototype.sendResponse=function(e,t){var n,r;if(e.timedout)return this.logger.error(`Request ${e.id} already timed out`),1;if(e.replied)return this.logger.error(`Response for request ${e.id} already sent`),2;clearTimeout(e.timeoutTimerId),e.timeoutTimerId=void 0,e.replied=!0,t.headers=t.headers??{};var i=e.correlationVector;this.logger.info(`Sending response N ${e.id} CV ${i} with status ${t.status}`),i&&(t.headers[S]=i),(n=e.headers)!=null&&n[`trouter-request`]&&(t.headers[`trouter-request`]=e.headers[`trouter-request`]);var a=Date.now()-e.startTS;if(t.headers[`trouter-client`]=(0,c.toJson)({cd:a}),(r=e.headers)!=null&&r[`trouter-is-broadcast`]&&(t.headers[`trouter-is-broadcast`]=e.headers[`trouter-is-broadcast`]),!this.socket)return this.connectionTracker.sendResponseError(`no socket`,e,t),4;try{return this.socket.send((0,c.toJson)(t)),t.sentTS=Date.now(),e.incrementCorrelationVector(),this.connectionTracker.trackResponse(e,a,t),this.transportTypeName===`websocket`&&this.sendPingRequest(),0}catch(n){var o=`unable to send data on response.end. Error: ${D(n)}`;return this.logger.error(o),this.connectionTracker.sendResponseError(o,e,t),4}},e.prototype.sendUserActivityStateMultiple=function(e){var t=this,n=new T(`user.activity`),r=this.userActivityState.increaseCvAndGetEventObject();n.args=r,this.logger.debug(`Sending user activity '${this.userActivityState.toEventJSON()}', remaining ${e-1}`);var i=!1;this.sendDownstreamEvent(n,(function(){if(!0!==i&&(t.logger.info(`User activity state: ${r.state}, cv: ${r.cv} accepted`),t.manager.onUserActivityStateAccepted(r.cv),t.clearSentEventTimer(n.timeoutTimerId),e>1)){var a=setTimeout((function(){t.clearSentEventTimer(a),t.sendUserActivityStateMultiple(e-1)}),t.options.userActivitySecondResendDelayMs);t.registerSentEventTimer(a,`user.activity/resend`)}})),n.timeoutTimerId=setTimeout((function(){t.logger.error(`Activity state response timeout is fired`),i=!0,t.fsm.onActivityStateResponseTimeout(),t.clearSentEventTimer(n.timeoutTimerId)}),this.timeoutOptions.userActivityResponseTimeoutMs),this.registerSentEventTimer(n.timeoutTimerId,`user.activity/response`)},e.prototype.sendUserActivityStateIgnoreResponse=function(){var e=new T(`user.activity`),t=this.userActivityState.toEventObject();e.args=t,this.socket&&(this.logger.info(`Sending user activity after XHR connect, ${t.state}, cv: ${t.cv}, treating it as accepted`),this.socket.emit(e.name,e.args),this.manager.onUserActivityStateAccepted(t.cv))},e.prototype.sendDownstreamEvent=function(e,t){this.logger.debug(`Sending downstream event ${e.name}`),this.socket&&this.socket.emit(e.name,e.args,t)},e.prototype.registerSentEventTimer=function(e,t){this.logger.debug(`registering timer ${e} -> ${t}`),this.pendingSentEventTimers[e]=t},e.prototype.clearSentEventTimer=function(e){var t=this.pendingSentEventTimers[e];this.logger.debug(`clearing timer ${e} -> ${t}`),delete this.pendingSentEventTimers[e],clearTimeout(e)},e.prototype.getRegistrationTtl=function(){var e=(0,c.calculateTtlInSec)(this.connectionExpireTimestampInSecs);if(this.logger.debug(`Current connectionID will expire in ${e} seconds`),this.options.registration?.registrarTtlSec&&e>0){var t=this.options.registration.registrarTtlSec<e;return[Math.min(this.options.registration.registrarTtlSec,e),t]}return this.options.registration?.registrarTtlSec?[this.options.registration.registrarTtlSec,!1]:e>0?[e,!1]:[3600,!1]},e.prototype.clearIncallModeTimerId=function(){this.incallModeTimerId!==void 0&&(this.logger.debug(`Clearing in-call mode timer`),clearTimeout(this.incallModeTimerId),this.incallModeTimerId=void 0)},e.prototype.applyConnectionTrackerOptions=function(e){try{e.eventLogger&&typeof e.eventLogger.logEvent==`function`?(this.connectionTracker.mergeSettings(e.telemetrySettings),this.connectionTracker.enable(e.eventLogger)):this.logger.warn(`Trouter client event logging disabled due to invalid configuration.`)}catch(e){this.logger.warn(`Trouter client event logging disabled. Error: ${D(e)}`),this.connectionTracker.disable()}},e.prototype.canRetryTokenFetchRequest=function(e){var t=this.options.retryLimitOnTokenFetch;return t==null||e<t||(this.logger.warn(`Reached limit on maximum number of token fetch request. Current count: ${e}, retry limit: ${t}`),!1)},e}();function ee(e,t){var n=t?void 0:{"X-MS-Migration":`True`};switch(e.tokenType.toLowerCase()){case`skype`:return r({"X-Skypetoken":e.token},n);case`aad`:case`cae`:return r({Authorization:`Bearer ${e.token}`},n);default:throw Error(`unsupported token type: ${e.tokenType}`)}}function D(e){return typeof e==`object`&&e&&e.stack!==void 0?(0,c.toJson)(e.stack):`"(no error.stack)"`}function O(e){return typeof e==`object`&&e&&typeof e.message==`string`?e.message:`(no error.message)`}t.TrouterConnection=E},616:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterUrlPromise=void 0;var r=n(642);t.TrouterUrlPromise=function(){function e(e){this.logger=new r.Logger(`UrlPromise`,e)}return e.prototype.getPromise=function(){var e=this;return this.url===void 0?(this.pendingPromise===void 0?(this.logger.debug(`creating and returning promise`),this.pendingPromise=new Promise((function(t,n){e.pendingPromiseResolveRef=t,e.pendingPromiseRejectRef=n}))):this.logger.debug(`returning existing promise`),this.pendingPromise):(this.logger.debug(`returning previously resolved url: ${this.url}`),Promise.resolve(this.url))},e.prototype.resolveUrl=function(e){this.url=e,this.logger.debug(`got url: ${this.url}`);var t=this.pendingPromiseResolveRef;this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,t!==void 0&&(this.logger.debug(`resolving promise`),t(e))},e.prototype.rejectUrl=function(e){this.logger.debug(`aborting`);var t=this.pendingPromiseRejectRef;this.url=void 0,this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,t!==void 0&&(this.logger.debug(`rejecting promise`),t(e))},e.prototype.resetUrl=function(){this.logger.debug(`resetting url`),this.url=void 0},e}()},619:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MessageHandlerRegistry=void 0;var r=n(509),i=n(642);t.MessageHandlerRegistry=function(){function e(e){this.messageHandlers=[],this.logger=new i.Logger(`MessageHandlers`,e)}return e.prototype.register=function(e){if(this.messageHandlers.some((function(t){return t===e})))throw Error(`Registering the same handler twice is not allowed`);this.messageHandlers.push(e)},e.prototype.clear=function(){this.logger.debug(`Clearing message handlers`),this.messageHandlers=[]},e.prototype.active=function(){return this.messageHandlers.length>0},e.prototype.handleMessage=function(e){for(var t={resultCode:r.UNHANDLED_MESSAGE_ACK,isHandled:!1},n=0,i=this.messageHandlers;n<i.length;n++){var a=i[n],o=this.safeExecuteHandle(a,e);if(o!==void 0&&(o.isHandled===void 0||o.isHandled))return o.resultCode===void 0&&(o.resultCode=r.HANDLED_MESSAGE_ACK),o}return t},e.prototype.safeExecuteHandle=function(e,t){try{return e.handleMessage(t)}catch(e){this.logger.warn(`Trouter message handler threw an exception: ${e}`);return}},e}()},634:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManager=t.AudienceSubscriptionState=t.UserActivityObject=void 0;var a=n(659),o=n(234),s=n(423),c=n(642),l=n(902),u=n(235),d=n(573),f=n(335),p=n(10),m=n(509),h=function(){function e(e,t){this.state=e,this.correlationVector=t===void 0?a.CorrelationVector.extend():t}return e.prototype.getStateString=function(){switch(this.state){case o.UserActivityState.Active:return`active`;case o.UserActivityState.Inactive:return`inactive`;case o.UserActivityState.Unknown:return`unknown`;default:return`undefined`}},e.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},e.prototype.toEventObject=function(){return{state:this.getStateString(),cv:this.correlationVector.value()}},e.prototype.toEventJSON=function(){return(0,a.toJson)(this.toEventObject())},e}();t.UserActivityObject=h;var g=function(){function e(e,t){t===void 0&&(t=a.CorrelationVector.extend()),this.subscirpitonsPerScope=e,this.correlationVector=t}return e.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},e.prototype.toEventObject=function(){return{audiences:this.toListOfSubscriptions(),cv:this.correlationVector.value()}},e.prototype.toEventJSON=function(){return(0,a.toJson)(this.toEventObject())},e.prototype.toListOfSubscriptions=function(){for(var e=[],t=0,n=Object.keys(this.subscirpitonsPerScope);t<n.length;t++){var r=n[t];e.push.apply(e,this.subscirpitonsPerScope[r])}return e},e}();t.AudienceSubscriptionState=g;var _=`extraTransports`;t.TrouterManager=function(){function e(e,t,n,r,i,s){this.logFunc=e,this.options=t,this.tokenProvider=n,this.usingLegacyTokenApi=r,this.listener=i,this.extraTransportVersionWithinProcess=0,this.logger=new c.Logger(`Manager`,e),this.logger.info(`Created TrouterManager with options ${(0,a.toJson)(this.options)}`),this.fsm=new p.TrouterManagerFsm(e,this),this.baseEndpointUrl=``,this.processedMessageLoss={},this.userActivityObject=new h(o.UserActivityState.Unknown),this.protocolSelector=s??this.tokenTypeProtocolSelector.bind(this)}return e.prototype.start=function(){this.fsm.start()},e.prototype.stop=function(e){this.fsm.stop(e)},e.prototype.configure=function(e){this.options=e,this.firstConnection!==void 0&&this.firstConnection.configure(e),this.secondConnection!==void 0&&this.secondConnection.configure(e),this.logger.info(`Reconfigured TrouterManager with options ${(0,a.toJson)(this.options)}`)},e.prototype.checkConnection=function(e){this.firstConnection!==void 0&&this.firstConnection.checkConnection(e),this.secondConnection!==void 0&&this.secondConnection.checkConnection(e)},e.prototype.resendRegistration=function(){return r(this,void 0,void 0,(function(){return i(this,(function(e){return this.secondConnection===void 0?this.firstConnection===void 0?(this.logger.info(`No connection to resend registration on, will be done upon (re)connect`),[2]):(this.logger.info(`Resending registration on the first/current connection`),[2,this.firstConnection.resendRegistration()]):(this.logger.info(`Resending registration on the second/new connection`),[2,this.secondConnection.resendRegistration()])}))}))},e.prototype.registerExtraTransports=function(e,t){var n,r=this;this.extraTransportsState={transports:e,clientDescriptionOverride:t},this.extraTransportVersionWithinProcess++,(n=this.options.keyValueCache)==null||n.setCacheForKey(_,JSON.stringify(this.extraTransportsState)).catch((function(){r.logger.error(`Failed to store extra transports in cache`)})),this.secondConnection===void 0?this.firstConnection===void 0?this.logger.warn(`No connection to register extra transports on, will be done upon (re)connect`):(this.logger.info(`Registering extra transports ${JSON.stringify(Object.keys(e))} and ${Object.keys(t??{}).length} overridden client description properties on the first/current connection`),this.firstConnection.registerExtraTransports(e,t)):(this.logger.info(`Registering extra transports ${JSON.stringify(Object.keys(e))} and ${Object.keys(t??{}).length} overridden client description properties on the second/new connection`),this.secondConnection.registerExtraTransports(e,t))},e.prototype.getServerState=function(){if(this.firstConnection!==void 0)return this.firstConnection.getServerState()},e.prototype.getState=function(){return this.fsm.getState()},e.prototype.isInTerminalState=function(){return this.fsm.getInternalState()===s.TrouterManagerState.TerminalError},e.prototype.reportStateInfo=function(){var e=this.firstConnection?f.State[this.firstConnection.getState()]:`Unknown`,t=s.TrouterManagerState[this.fsm.getInternalState()];return this.secondConnection?`Manager ${t}; 1st ${e}; 2nd ${f.State[this.secondConnection.getState()]}`:`Manager ${t}; Connection ${e}`},e.prototype.startFirstConnection=function(){var e=this,t=new d.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.firstConnection=t,Promise.all([this.getConnectionCache(),this.fetchExtraTransportsCache()]).then((function(n){var r=n[0];t.start(r,e.extraTransportsState?.transports,e.extraTransportsState?.clientDescriptionOverride)})).catch((function(){e.logger.error(`unexpected error while starting first connection (wrapped cache read functions should never throw)`)}))},e.prototype.startSecondConnection=function(e){var t=this,n=new d.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.secondConnection=n,this.firstConnection!==void 0&&this.firstConnection.disableRegistrationsAndAutoReconnect(),e?Promise.all([this.getConnectionCache(),this.fetchExtraTransportsCache()]).then((function(e){var r=e[0];n.start(r,t.extraTransportsState?.transports,t.extraTransportsState?.clientDescriptionOverride)})).catch((function(){t.logger.error(`unexpected error while starting second connection (wrapped cache read functions should never throw)`)})):this.fetchExtraTransportsCache().then((function(){n.start(void 0,t.extraTransportsState?.transports,t.extraTransportsState?.clientDescriptionOverride)})).catch((function(){t.logger.error(`unexpected error while starting second connection (wrapped cache read functions should never throw)`)}))},e.prototype.stopFirstConnection=function(e){this.firstConnection!==void 0&&(this.storedFirstConnection=this.firstConnection,this.firstConnection.stop(e),this.firstConnection=void 0)},e.prototype.stopSecondConnection=function(e){this.secondConnection!==void 0&&(this.secondConnection.stop(e),this.secondConnection=void 0)},e.prototype.stopSecondConnectionDelayed=function(){if(this.secondConnection!==void 0){var e=this.secondConnection;this.secondConnection=void 0,this.logger.info(`Closing an inactive connection in ${Math.round(this.options.lingeringConnectionDelayMs/1e3)}s`),setTimeout((function(){e.stop(!0)}),this.options.lingeringConnectionDelayMs)}},e.prototype.forceStopLingeringConnection=function(){this.storedFirstConnection&&=(this.storedFirstConnection.stop(!1),void 0)},e.prototype.switchConnections=function(){var e=this.firstConnection;this.firstConnection=this.secondConnection,this.secondConnection=e},e.prototype.doesSecondConnectionExist=function(){return this.secondConnection!==void 0},e.prototype.dispatchConnected=function(){if(this.firstConnection!==void 0){var e=this.firstConnection.getServerState(),t=e.url.endsWith(`/`)?e.url.slice(0,-1):e.url,n={baseEndpointUrl:t,newEndpointUrl:t!==this.baseEndpointUrl,c2cUrlBase:e.c2cUrlBase,clientId:e.connectedClientId,connectionId:e.connectionId,connectionTtlSec:e.getRemainingTtlInSec()};this.baseEndpointUrl=t,this.listener.onTrouterConnected(e.url,n)}},e.prototype.dispatchDisconnected=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},e.prototype.dispatchTerminalError=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},e.prototype.dispatchRegistrationState=function(e){this.options.registrationStateCallback&&this.options.registrationStateCallback(e)},e.prototype.expediteBackoffOnConnections=function(){this.lastExpediteBackoffCallAt!==void 0&&Date.now()-this.lastExpediteBackoffCallAt<(this.options.expediteBackoffOnStartMinimumDelayMs??1e4)?this.logger.info(`Expedite backoff due to start() too frequent, skipping`):(this.lastExpediteBackoffCallAt=Date.now(),this.firstConnection!==void 0&&this.firstConnection.expediteBackoff(),this.secondConnection!==void 0&&this.secondConnection.expediteBackoff())},e.prototype.onDownstreamRequest=function(e,t,n){var r={id:t.id,method:t.method,path:`/${t.shortUrl}`,body:t.body,headers:t.headers},i={id:t.id,status:0,headers:{},body:``,send:function(){return i.status<=100||i.status>=999?3:(n.writeHead(i.status,i.headers),n.end(i.body))}};this.listener.onTrouterRequest(r,i)},e.prototype.onConnected=function(e){this.fsm.onConnected(e===this.firstConnection)},e.prototype.onRegistered=function(e){this.fsm.onRegistered(e===this.firstConnection)},e.prototype.onUnregistered=function(e){this.fsm.onUnregistered(e===this.firstConnection||e===this.storedFirstConnection)},e.prototype.onReconnecting=function(e){this.fsm.onReconnecting(e===this.firstConnection)},e.prototype.onReconnectIsRequired=function(e,t,n){this.fsm.onReconnectionRequired(e===this.firstConnection,t,n)},e.prototype.onDisconnected=function(e){this.fsm.onDisconnected(e===this.firstConnection||e==this.storedFirstConnection),this.storedFirstConnection=void 0},e.prototype.onTerminalError=function(){this.fsm.onTerminalError(),this.storedFirstConnection=void 0},e.prototype.onUserActivityStateAccepted=function(e){this.listener.onTrouterUserActivityStateAccepted&&this.listener.onTrouterUserActivityStateAccepted(e)},e.prototype.onAudiencesSetResolved=function(e,t){var n,r;(r=(n=this.listener).onAudiencesSetResolved)==null||r.call(n,e,t)},e.prototype.onConnectionParametersUpdated=function(e){this.setConnectionCache(e)},e.prototype.setUserActivityState=function(e,t){this.userActivityObject=new h(e,a.CorrelationVector.extend(t)),this.secondConnection===void 0?this.firstConnection!==void 0&&(this.logger.info(`Setting user activity ${this.userActivityObject.toEventJSON()} on the first/current connection`),this.firstConnection.setUserActivityState(this.userActivityObject)):(this.logger.info(`Setting user activity ${this.userActivityObject.toEventJSON()} on the second/new connection`),this.secondConnection.setUserActivityState(this.userActivityObject))},e.prototype.setAudienceSubscriptionsAsync=function(e,t,n){var r=e.scope??m.constants.SUBSCRIPTIONS_DEFAULT_SCOPE,i=this.GetUpdatedAsState(e,r);if(this.audienceSubscriptionState=new g(i,a.CorrelationVector.extend(n)),this.secondConnection)return this.logger.info(`Setting audience subscriptions ${this.audienceSubscriptionState.toEventJSON()} on second/new connection`),this.secondConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,t);if(this.firstConnection)return this.logger.info(`Setting audience subscriptions ${this.audienceSubscriptionState.toEventJSON()} on first/current connection`),this.firstConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,t);throw Error(`No connection found`)},e.prototype.GetUpdatedAsState=function(e,t){var n={};return this.audienceSubscriptionState!==void 0&&(n=structuredClone(this.audienceSubscriptionState.subscirpitonsPerScope)),n[t]=e.audienceSubscriptions,n},e.prototype.onTrouterMessageLost=function(e){var t=this;if(this.listener.onTrouterMessageLoss)if(e?.length){var n=e.filter((function(e){return t.processedMessageLoss[`${e.tag}-${e.etag}`]!==void 0}));if(n.length&&(this.logger.info(`onTrouterMessageLoss - immediately acknowledging ${n.length} seen dropped indicators`),this.sendProcessedDroppedIndicators(n),!(e=e.filter((function(e){return t.processedMessageLoss[`${e.tag}-${e.etag}`]===void 0}))).length))return void this.logger.info(`onTrouterMessageLoss - all declared dropped indicators have been seen before`);if(!this.listener.onTrouterMessageLoss(e.map((function(e){return e.tag}))))return void this.logger.warn(`onTrouterMessageLoss - some flow tag(s) have not been processed by listeners`);e.forEach((function(e){t.processedMessageLoss[`${e.tag}-${e.etag}`]=``})),this.sendProcessedDroppedIndicators(e)}else this.logger.warn(`onTrouterMessageLoss - no flow tags have been provided`)},e.prototype.getConnectionCache=function(){var e=this;return this.options.connectionCache?(this.logger.debug(`Querying host's connection cache`),this.options.connectionCache.onGetTrouterConnectionCache().then((function(e){var t=e?JSON.parse(e):void 0;return typeof t==`object`?t:void 0})).catch((function(t){return e.logger.warn(`Invalid connection cache content provided: ${t}`),e.connectionCache}))):Promise.resolve(this.connectionCache)},e.prototype.fetchExtraTransportsCache=function(){var e=this,t=this.extraTransportVersionWithinProcess;return this.options.keyValueCache&&this.extraTransportsState===void 0?this.options.keyValueCache.getCacheForKey(_).then((function(n){if(t===e.extraTransportVersionWithinProcess){if(n){var r=JSON.parse(n);typeof r==`object`&&r&&(Object.prototype.hasOwnProperty.call(r,`transports`)?e.extraTransportsState=r:e.extraTransportsState={transports:r,clientDescriptionOverride:void 0}),e.extraTransportVersionWithinProcess++}}else e.logger.info(`Extra transports cache was updated while fetching it, returning the current state`)})).catch((function(){e.logger.error(`Failed to retrieve extra transports from cache`)})):Promise.resolve()},e.prototype.setConnectionCache=function(e){if(this.connectionCache=e,this.options.connectionCache)try{this.options.connectionCache.onSetTrouterConnectionCache(JSON.stringify(e))}catch(e){this.logger.warn(`Error setting external connection cache: ${e}`)}},e.prototype.sendProcessedDroppedIndicators=function(e){this.firstConnection===void 0?this.secondConnection===void 0||this.secondConnection.sendProcessedDroppedIndicators(e):this.firstConnection.sendProcessedDroppedIndicators(e)},e.prototype.configuredTrouterManager=function(){return new u.RegistrationEnforcer(this,this.options.connectionDependsOnRegistration,this.options.delayEventsUntilRegistered)},e.prototype.tokenTypeProtocolSelector=function(e,t){return this.options.forceV4aProtocol||this.options.forceV4aProtocolForSkypetoken&&e===`skype`&&(0,l.safeToString)(t?.scae)!==`1`?`v4a`:`v4c`},e}()},642:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0,t.Logger=function(){function e(e,t){this.name=e,this.logger=t}return e.prototype.debug=function(e){this.logger.debug(`[${this.name}] ${e}`)},e.prototype.info=function(e){this.logger.info(`[${this.name}] ${e}`)},e.prototype.warn=function(e){this.logger.warn(`[${this.name}] ${e}`)},e.prototype.error=function(e){this.logger.error(`[${this.name}] ${e}`)},e}()},659:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};function i(e){try{return JSON.stringify(e)}catch{return`Unable to serialize object of type ${typeof e}`}}Object.defineProperty(t,"__esModule",{value:!0}),t.Timespan=t.CorrelationVector=void 0,t.toJson=i,t.anonymizeShortUrl=function(e){var t=/^(TeamsUnifiedPresenceService|acceptance|addParticipant\w*|balanceUpdate|call(Agent)?|controlVideoStreaming|conversation\w*|dominantSpeakerInfo|end|join|media\w*|messaging|progress|rejection|retargetCompletion|rosterUpdate|update|ups)$/i;return e.split(`/`).map((function(e){return!e||t.test(e)||e.length<3?e:`${e.slice(0,2)}...`})).join(`/`)},t.headersToLog=function(e){for(var t=/^(Host|User-Agent|Content-Length|Content-Type|X-Microsoft-Skype-\S+|(X-)?Trouter.*|X-CallingProxy|MS-CV|traceparent|Priority)$/i,n={},r=0,a=Object.keys(e);r<a.length;r++){var o=a[r];t.test(o)&&(n[o]=e[o])}return i(n)},t.calculateTtlInSec=function(e){var t=Math.round(new Date().getTime()/1e3);return e!==void 0&&e>t?e-t:0},t.calculateExpireTsInSec=function(e){return Math.round(new Date().getTime()/1e3)+e},t.fetchWithTimeout=function(e,t){return n(this,void 0,void 0,(function(){var n,i,a;return r(this,(function(r){return i=new Promise((function(t,r){fetch(e).then((function(e){clearTimeout(n),t(e)})).catch((function(e){clearTimeout(n),r(e)}))})),t===0?[2,i]:(a=new Promise((function(r,i){var a=new URL(e.url),o=Error(`${e.method} ${a.origin}${a.pathname} timed out`);n=setTimeout(i,t,o)})),[2,Promise.race([i,a])])}))}))},t.CorrelationVector=function(){function e(e){this.base=e===void 0?this.createCorrelationVectorBase():e,this.extension=0}return e.extend=function(t){return new e(t)},e.prototype.increase=function(){this.extension++},e.prototype.value=function(){return`${this.base}.${this.extension}`},e.prototype.createCorrelationVectorBase=function(){for(var e=``,t=0;t<21;t++)e+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0987654321/+`.charAt(Math.floor(64*Math.random()));return e+`AQgw`.charAt(Math.floor(4*Math.random()))},e}(),t.Timespan=function(){function e(){this.start=Date.now()}return Object.defineProperty(e.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this.start=Date.now()},e}()},673:t=>{t.exports=e},705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateAudienceSubscriptionQuery=function(e,t){return e.replace(/([?&]audienceSubscriptionState=)[^&]*/,`\$1${t}`)}},764:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DisconnectReason=void 0,t.DisconnectReason=function(){function e(e,t,n){this.reason=e,this.claims=t,this.details=n}return e.fromRawReason=function(t,n){if(t===``||t===`dup`)return new e(t);try{var r=JSON.parse(t);return typeof r!=`object`||r.reason===void 0?(n?.error(`invalid disconnect reason format`),new e(`unknown`,void 0,t)):new e(r.reason,r.claims,r.details)}catch{return new e(`disconnect`,void 0,t)}},e.fromSocketIoEventData=function(t,n){return typeof n==`string`?new e(t,void 0,n):void 0},e.prototype.toTelemetryString=function(){return this.reason===`socketerror`||this.reason===`reconnecterror`||this.reason===`disconnect`?this.details:this.reason},e}()},882:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},a=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterService=t.UserActivityState=t.TrouterState=void 0,t.createTrouterService=function(e){return new h(e)},t.getTrouterServiceVersion=function(){return o.CLIENT_VERSION},t.replaceTrouterUrlBase=function(e,t){var n=e.indexOf(`://`);if(n>=0){var r=e.indexOf(`/`,n+3);if(r>=0)return t+e.substr(r)}return``};var o=n(509),s=n(234);Object.defineProperty(t,"TrouterState",{enumerable:!0,get:function(){return s.TrouterState}}),Object.defineProperty(t,"UserActivityState",{enumerable:!0,get:function(){return s.UserActivityState}});var c=n(642),l=n(619),u=n(220),d=n(634),f=n(616);function p(e,t){if(!t)return e;var n=r(r({},e),{enabled:t.TelemetryEnabled});return t.ClientTelemetryEventEnabled!==void 0&&(n=r(r({},n),t.ClientTelemetryEventEnabled)),n}function m(e,t,n){var i,a,o,s=function(n){return e.proxyUrlRewrite?(t.info(`Using rewritten URL for proxy`),e.proxyUrlRewrite(n)):n};return{clientInfo:{ua:e.trouterSettings.productName,v:e.trouterSettings.version},ioOptions:{ackTimeoutMs:5e3,rewriteUrlForProxy:s},clientCorrelationID:e.trouterSettings.sessionId,environment:e.trouterSettings.environment,telemetrySettings:p(e.telemetryConfig.settings,n),eventLogger:e.telemetryConfig.eventLogger,endpointId:e.trouterSettings.registrationId,trouterUrl:n?.TrouterConnectionUrl||e.trouterSettings.trouterServiceUrl,registration:e.trouterSettings.registrarServiceUrl||e.trouterSettings.useRegistrarUrlFromAllocate?{registrarUrl:e.trouterSettings.registrarServiceUrl??``,useRegistrarUrlFromAllocate:(i=e.trouterSettings.useRegistrarUrlFromAllocate)!=null&&i,registrationId:e.trouterSettings.registrationId??``,pnhAppId:e.trouterSettings.pnhAppId??``,platform:e.trouterSettings.platform??``,pnhTemplateKey:e.trouterSettings.pnhTemplate??``,platformUIVersion:e.trouterSettings.platformUIVersion??``,productContext:e.trouterSettings.pnhProductContext||void 0,context:e.trouterSettings.pnhContext??``,registrarTtlSec:(e.trouterSettings.maxRegistrationTimeInMs??0)/1e3}:void 0,connectionDependsOnRegistration:e.trouterSettings.registrarServiceUrl===void 0?function(){return!1}:e.trouterSettings.connectionDependsOnRegistration??function(){return!1},delayEventsUntilRegistered:e.trouterSettings.delayEventsUntilRegistered??function(){return!1},timeoutOptions:r({connectionTimeoutMs:e.trouterSettings.trouterConnectTimeoutInMs||3e4,fetchTimeoutMs:1e4,pingTimeoutMs:4e4,pongTimeoutMs:5e3,maxBackoffMs:e.trouterSettings.productName===`TeamsCDL`?3e5:3e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},e.trouterSettings.timeoutOptions),incallTimeoutOptions:r({connectionTimeoutMs:1e4,fetchTimeoutMs:5e3,pingTimeoutMs:5e3,pongTimeoutMs:2e3,maxBackoffMs:e.trouterSettings.productName===`TeamsCDL`?3e5:1e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},e.trouterSettings.incallTimeoutOptions),incallModeTimeoutMs:e.trouterSettings.incallModeTimeoutMs??0,lingeringConnectionDelayMs:6e4,userActivitySecondResendDelayMs:e.trouterSettings.userActivitySecondResendDelayMs||1e4,duplicateDisconnectThresholdMs:1e4,connectionCache:e.connectionCache,keyValueCache:e.keyValueCache,registrationStateCallback:e.registrationStateCallbackForAcsDoNotUse,rewriteUrlForProxy:s,retryLimitOnTokenFetch:e.trouterSettings.retryLimitOnTokenFetch,extraConnectionHeaders:e.trouterSettings.extraConnectionHeaders,expediteBackoffOnStartMinimumDelayMs:1e4,updateUserActivityDuringConnectionAttempt:(a=e.trouterSettings.updateUserActivityDuringConnectionAttempt)==null||a,initialConnectivityCheck:(o=e.trouterSettings.initialConnectivityCheck)==null||o,toJSON:function(){return r(r({},this),{connectionCache:this.connectionCache?{}:this.connectionCache,keyValueCache:this.keyValueCache?{}:this.keyValueCache})}}}var h=function(){function e(e){this.logProvider=e,this.stateChangedListeners=[],this.logger=new c.Logger(`Trouter`,e),this.trouterUrlPromise=new f.TrouterUrlPromise(e),this.messageHandlers=new l.MessageHandlerRegistry(e),this.listeners={},this.connectionInfo=null,this.logger.info(`Created TrouterService version ${o.CLIENT_VERSION}`)}return e.prototype.start=function(e){if(this.logger.info(`Start`),!e.skypeTokenProvider&&!e.authTokenProvider)throw Error(`no token provider has been configured, either skypeTokenProvider or authTokenProvider must be populated`);e.skypeTokenProvider&&!e.trouterSettings.disableInternalSkypeTokenCache&&(e.skypeTokenProvider=(0,u.addCacheAsBackupTo)(e.skypeTokenProvider)),this.trouterCfg=e;var t=m(e,this.logger,this.ecsCfg);!1===e.internalEnableV4cProtocol&&(t.forceV4aProtocol=!0),!1===e.internalUseV4aForSkypetoken&&(t.forceV4aProtocolForSkypetoken=!0);var n=function(e,t){var n,r=this;return function(o){return i(r,void 0,void 0,(function(){var r,i,s;return a(this,(function(a){switch(a.label){case 0:r=new Date,i=setInterval((function(){var t=Math.round((Date.now()-r.getTime())/6e4);e.warn(`Note: Trouter auth token request promise from ${r.toISOString()} has not been resolved for ${t} minutes. The client is blocked from operating properly`)}),3e5),a.label=1;case 1:return a.trys.push([1,,3,4]),[4,t(o)];case 2:return s=a.sent(),o.needFresh&&s.token===n&&e.error(`API violation: Trouter auth token provider got a request with needRefresh=true, but returned the same token as last time anyway. Please fix the host app`),n=s.token,[2,s];case 3:return clearInterval(i),[7];case 4:return[2]}}))}))}}(this.logger,e.authTokenProvider??function(e){var t=this;return function(n){return i(t,void 0,void 0,(function(){var t;return a(this,(function(r){switch(r.label){case 0:return t={},[4,e(n.needFresh)];case 1:return[2,(t.token=r.sent(),t.tokenType=`skype`,t)]}}))}))}}(e.skypeTokenProvider));this.trouterServer===void 0&&(this.trouterServer=new d.TrouterManager(this.logProvider,t,n,e.authTokenProvider===void 0,this)),this.pendingActivityState!==void 0&&(this.trouterServer.setUserActivityState(this.pendingActivityState[0],this.pendingActivityState[1]),this.pendingActivityState=void 0),this.pendingExtraTransports!==void 0&&(this.trouterServer.registerExtraTransports(this.pendingExtraTransports.transports,this.pendingExtraTransports.clientDescriptionOverride),this.pendingExtraTransports=void 0),this.trouterServer.start()},e.prototype.stop=function(e){this.logger.info(`close connection`),this.trouterUrlPromise.rejectUrl(Error(`TrouterService is stopped`)),this.trouterServer!==void 0&&this.trouterServer.stop(e)},e.prototype.setEcsConfig=function(e){return i(this,void 0,void 0,(function(){var t=this;return a(this,(function(n){return[2,new Promise((function(n){if(t.ecsCfg=e.TrouterJScriptClient,t.logger.info(`Setting ECS configuration to ${JSON.stringify(t.ecsCfg)}`),t.trouterServer!==void 0&&t.trouterCfg!==void 0){var r=m(t.trouterCfg,t.logger,t.ecsCfg);t.trouterServer.configure(r)}n()}))]}))}))},e.prototype.checkConnection=function(e){this.trouterServer!==void 0&&this.trouterServer.checkConnection(e!=null&&e)},e.prototype.resendRegistration=function(){return i(this,void 0,void 0,(function(){return a(this,(function(e){if(!this.trouterServer)throw Error(`resendRegistration called too early`);return[2,this.trouterServer.resendRegistration()]}))}))},e.prototype.registerExtraTransports=function(e,t){if(this.trouterServer===void 0)return this.pendingExtraTransports={transports:e,clientDescriptionOverride:t},void this.logger.warn(`registerExtraTransports called before start()`);this.logger.info(`registerExtraTransports called`),this.pendingExtraTransports=void 0,this.trouterServer.registerExtraTransports(e,t)},e.prototype.registerListener=function(e,t){return t===``||!t.startsWith(`/`)||t.includes(`?`)||t.includes(`#`)?(this.logger.error(`Listener path '${t}' is not valid`),!1):this.listeners[t]?(this.logger.error(`Another listener is already registered for path '${t}'`),!1):(this.listeners[t]=e,this.logger.debug(`Listener for path '${t}' registered`),this.connectionInfo&&e.onTrouterConnected(this.connectionInfo.baseEndpointUrl+t,this.connectionInfo),!0)},e.prototype.unregisterListener=function(e){for(var t=[],n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n];this.listeners[i]===e&&t.push(i)}if(t.length===0)return!1;for(var a=0,o=t;a<o.length;a++)i=o[a],delete this.listeners[i];return this.logger.debug(`Listener for path(s) '${t.join(`', '`)}' unregistered`),!0},e.prototype.onTrouterConnected=function(e,t){this.logger.debug(`Trouter is now connected`);for(var n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n];try{this.listeners[i].onTrouterConnected(t.baseEndpointUrl+i,t)}catch(e){this.logger.error(`Listener '${i}' threw an exception from onTrouterConnected(): ${e}`)}}this.connectionInfo=t,this.trouterUrlPromise.resolveUrl(e),this.notifyStateChanged(s.TrouterState.Connected,{url:e,getRemainingTtlInSec:function(){return t.connectionTtlSec}})},e.prototype.onTrouterDisconnected=function(){this.logger.debug(`Trouter is now disconnected`),this.connectionInfo=null;for(var e=0,t=Object.keys(this.listeners);e<t.length;e++){var n=t[e],r=this.listeners[n];if(r.onTrouterDisconnected)try{r.onTrouterDisconnected()}catch(e){this.logger.error(`Listener '${n}' threw an exception from onTrouterDisconnected(): ${e}`)}}this.notifyStateChanged(s.TrouterState.Disconnected)},e.prototype.onTrouterRequest=function(e,t){for(var n=``,r=0,i=Object.keys(this.listeners);r<i.length;r++){var a=i[r];e.path.startsWith(a)&&a.length>n.length&&(n=a)}if(n===``)this.tryMessageHandlers(e,t)||(t.status=404,t.headers={"Trouter-Responder":`ClientLib`},t.send());else try{this.listeners[n].onTrouterRequest(e,t)}catch(e){this.logger.error(`Listener '${n}' threw an exception from onTrouterRequest(): ${e}`),t.status=500,t.headers={"Trouter-Responder":`ClientLib`},t.send()}},e.prototype.onTrouterMessageLoss=function(e){this.logger.info(`onTrouterMessageLoss called with tags [${e}]`);for(var t=!0,n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n],a=this.listeners[i];if(a.onTrouterMessageLoss)try{(t=a.onTrouterMessageLoss(e)&&t)===void 0&&(this.logger.error(`Listener '${i}' did not return a boolean value from onTrouterMessageLoss()`),t=!1)}catch(e){this.logger.error(`Listener '${i}' threw an exception from onTrouterMessageLoss(): ${e}`),t=!1}}return t},e.prototype.onTrouterUserActivityStateAccepted=function(e){this.logger.debug(`onTrouterUserActivityStateAccepted cv: ${e}`);for(var t=0,n=Object.keys(this.listeners);t<n.length;t++){var r=n[t],i=this.listeners[r];if(i.onTrouterUserActivityStateAccepted)try{i.onTrouterUserActivityStateAccepted(e)}catch(e){this.logger.error(`Listener '${r}' threw an exception from onTrouterUserActivityStateAccepted(): ${e}`)}}},e.prototype.onAudiencesSetResolved=function(e,t){this.logger.debug(`onAudiencesSetResolved cv: ${t}`);for(var n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n],a=this.listeners[i];if(a.onAudiencesSetResolved)try{a.onAudiencesSetResolved(e,t)}catch(e){this.logger.error(`Listener '${i}' threw an exception from onAudienceSubscribed(): ${e}`)}}},e.prototype.setUserActivityState=function(e,t){if(e!==s.UserActivityState.Active&&e!==s.UserActivityState.Inactive)throw Error(`setUserActivityState called with unsupported value ${e}`);this.logger.info(`setUserActivityState called with value ${s.UserActivityState[e]}`),this.trouterServer&&this.state()!==s.TrouterState.Unknown?this.trouterServer.setUserActivityState(e,t):(this.pendingActivityState=[e,t],this.logger.warn(`setUserActivityState called before start() or after stop()`))},e.prototype.setAudienceSubscriptions=function(e,t){if(this.trouterServer&&this.state()!==s.TrouterState.Unknown)return this.trouterServer.setAudienceSubscriptionsAsync(e,15e3,t);throw Error(`audience subscribe called before start() or after stop()`)},e.prototype.state=function(){return this.trouterServer===void 0?s.TrouterState.Unknown:this.trouterServer.getState()},e.prototype.isInTerminalState=function(){return this.trouterServer!==void 0&&this.trouterServer.isInTerminalState()},e.prototype.reportStateInfo=function(){return this.trouterServer===void 0?``:this.trouterServer.reportStateInfo()},e.prototype.getServerState=function(){if(this.trouterServer!==void 0)return this.trouterServer.getServerState()},e.prototype.getTrouterUrlAsync=function(){return this.trouterServer===void 0?Promise.reject(Error(`TrouterService has not been started`)):this.trouterUrlPromise.getPromise()},e.prototype.onStateChanged=function(e){if(this.logger.info(`onStateChanged called`),e===void 0)this.stateChangedListeners=this.stateChangedListeners.filter((function(e){return e.wrappedCallback===void 0}));else{this.offStateChanged(e);var t=function(t,n){e(t,n?n.url:``)};t.wrappedCallback=e,this.stateChangedListeners.push(t)}},e.prototype.offStateChanged=function(e){this.logger.info(`offStateChanged called`);var t=this.stateChangedListeners.length;return this.stateChangedListeners=this.stateChangedListeners.filter((function(t){return t.wrappedCallback!==e})),t>this.stateChangedListeners.length},e.prototype.addCallback=function(e){this.logger.info(`addListener called`),this.stateChangedListeners.indexOf(e,0)===-1&&e!==void 0&&this.stateChangedListeners.push(e)},e.prototype.removeCallback=function(e){this.logger.info(`removeListener called`);var t=this.stateChangedListeners.indexOf(e,0);return t>-1&&(this.stateChangedListeners.splice(t,1),!0)},e.prototype.registerMessageHandler=function(e){this.logger.info(`registerMessageHandler is called`),this.messageHandlers.register(e)},e.prototype.clearMessageHandlers=function(){this.logger.info(`clearMessageHandlers is called`),this.messageHandlers.clear()},e.prototype.notifyStateChanged=function(e,t){var n=this;this.logger.info(`notifyStateChanged called, will forward to ${this.stateChangedListeners.length} listeners`),this.stateChangedListeners.forEach((function(r){try{r(e,t)}catch(e){n.logger.error(`Error in callback ${e}`)}}))},e.prototype.tryMessageHandlers=function(e,t){if(!this.messageHandlers.active())return!1;var n,r=null;try{r=(n=JSON.parse(e.body))&&(n.evt||n.eventId)||null}catch{}var i={eventId:r,url:(this.connectionInfo?this.connectionInfo.baseEndpointUrl:``)+e.path,body:n,rawBody:e.body,headers:e.headers},a=this.messageHandlers.handleMessage(i);return!!a.isHandled&&(t.status=a.resultCode,a.responseHeaders&&(t.headers=a.responseHeaders),a.responseBody&&(t.body=a.responseBody),t.send(),!0)},e}();t.TrouterService=h},902:function(e,t){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.safeToString=function(e){return typeof e==`string`?e:typeof e==`number`?e.toString():void 0},t.usedProtocolAfterFallback=function(e,t){return t?.kind===`v4c-websocket-failure`?`v4a`:e},t.isV4ConnectEvent=function(e){return Object.prototype.hasOwnProperty.call(e,`connectparams`)},t.adaptUrl=function(e,t){return t===`v4a`?e.replace(/\/v4\/c\b/,`/v4/a`).replace(`wss://`,`https://`).replace(`ws://`,`http://`):e.replace(/\/v4\/a\b/,`/v4/c`).replace(`https://`,`wss://`).replace(`http://`,`ws://`)},t.reconnectParamsWithoutUrls=function(e){if(e!==void 0)return n(n({},e),{reconnectUrl:void 0,serviceUrl:void 0})},t.ensureNumber=function(e){return typeof e==`string`?parseInt(e,10):e},t.redirectUrlIfPresent=function(e){if(e?.kind===`redirect`&&e.host!==void 0){var t=e.host;return t.endsWith(`/`)&&(t=t.substring(0,t.length-1)),t.endsWith(`/v4/c`)||t.endsWith(`/v4/a`)||(t+=`/v4/c`),t}}},983:(e,t,n)=>{(function(e,t){var n=e;n.version=`0.9.6`,n.protocol=1,n.transports=[],n.j=[],n.sockets={},n.connect=function(e,r){var i,a,o=n.util.parseUri(e);t&&t.location&&(o.protocol=o.protocol||t.location.protocol.slice(0,-1),o.host=o.host||(t.document?t.document.domain:t.location.hostname),o.port=o.port||t.location.port),i=n.util.uniqueUri(o);var s={host:o.host,secure:o.protocol==`https`,port:o.port||(o.protocol==`https`?443:80),query:o.query||``};return n.util.merge(s,r),!s[`force new connection`]&&n.sockets[i]||(a=new n.Socket(s)),!s[`force new connection`]&&a&&(n.sockets[i]=a),a||=n.sockets[i],s[`skipped handshake data`]?a.of(``):a.of(o.path.length>1?o.path:``)}})((e=n.nmd(e)).exports,MG===void 0?window:MG);var r=e.exports;(function(e,t){var n=e.util={},r=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,i=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];n.parseUri=function(e){for(var t=r.exec(e||``),n={},a=14;a--;)n[i[a]]=t[a]||``;return n},n.uniqueUri=function(e){var n=e.protocol,r=e.host,i=e.port;return`document`in t?(r||=document.domain,i||=n==`https`&&document.location.protocol!==`https:`?443:document.location.port):(r||=`localhost`,i||n!=`https`||(i=443)),(n||`http`)+`://`+r+`:`+(i||80)},n.query=function(e,t){var r=n.chunkQuery(e||``),i=[];for(var a in n.merge(r,n.chunkQuery(t||``)),r)r.hasOwnProperty(a)&&i.push(a+`=`+r[a]);return i.length?`?`+i.join(`&`):``},n.chunkQuery=function(e){for(var t,n={},r=e.split(`&`),i=0,a=r.length;i<a;++i)(t=r[i].split(`=`))[0]&&(n[t[0]]=t[1]);return n};var a=!1;n.load=function(e){if(`document`in t&&document.readyState===`complete`||a)return e();n.on(t,`load`,e,!1)},n.on=function(e,t,n,r){e.attachEvent?e.attachEvent(`on`+t,n):e.addEventListener&&e.addEventListener(t,n,r)},n.request=function(e){if(e&&typeof XDomainRequest<`u`)return new XDomainRequest;if(typeof XMLHttpRequest<`u`&&(!e||n.ua.hasCORS))return new XMLHttpRequest;if(!e)try{return new window[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}return null},typeof window<`u`&&n.load((function(){a=!0})),n.defer=function(e){if(!n.ua.webkit||typeof importScripts<`u`)return e();n.load((function(){setTimeout(e,100)}))},n.merge=function(e,t,r,i){var a,o=i||[],s=r===void 0?2:r;for(a in t)t.hasOwnProperty(a)&&n.indexOf(o,a)<0&&(typeof e[a]==`object`&&s?n.merge(e[a],t[a],s-1,o):(e[a]=t[a],o.push(t[a])));return e},n.mixin=function(e,t){n.merge(e.prototype,t.prototype)},n.inherit=function(e,t){function n(){}n.prototype=t.prototype,e.prototype=new n},n.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)===`[object Array]`},n.intersect=function(e,t){for(var r=[],i=e.length>t.length?e:t,a=e.length>t.length?t:e,o=0,s=a.length;o<s;o++)~n.indexOf(i,a[o])&&r.push(a[o]);return r},n.indexOf=function(e,t,n){var r=e.length;for(n=n<0?n+r<0?0:n+r:n||0;n<r&&e[n]!==t;n++);return r<=n?-1:n},n.toArray=function(e){for(var t=[],n=0,r=e.length;n<r;n++)t.push(e[n]);return t},n.ua={},n.ua.hasCORS=typeof XMLHttpRequest<`u`&&function(){try{var e=new XMLHttpRequest}catch{return!1}return e.withCredentials!=null}(),n.ua.webkit=typeof navigator<`u`&&/webkit/i.test(navigator.userAgent)})(r===void 0?e.exports:r,MG===void 0?window:MG),function(e,t){function n(){}e.EventEmitter=n,n.prototype.on=function(e,n){return this.$events||={},this.$events[e]?t.util.isArray(this.$events[e])?this.$events[e].push(n):this.$events[e]=[this.$events[e],n]:this.$events[e]=n,this},n.prototype.addListener=n.prototype.on,n.prototype.once=function(e,t){var n=this;function r(){n.removeListener(e,r),t.apply(this,arguments)}return r.listener=t,this.on(e,r),this},n.prototype.removeListener=function(e,n){if(this.$events&&this.$events[e]){var r=this.$events[e];if(t.util.isArray(r)){for(var i=-1,a=0,o=r.length;a<o;a++)if(r[a]===n||r[a].listener&&r[a].listener===n){i=a;break}if(i<0)return this;r.splice(i,1),r.length||delete this.$events[e]}else (r===n||r.listener&&r.listener===n)&&delete this.$events[e]}return this},n.prototype.removeAllListeners=function(e){return this.$events&&this.$events[e]&&(this.$events[e]=null),this},n.prototype.listeners=function(e){return this.$events||={},this.$events[e]||(this.$events[e]=[]),t.util.isArray(this.$events[e])||(this.$events[e]=[this.$events[e]]),this.$events[e]},n.prototype.emit=function(e){if(!this.$events)return!1;var n=this.$events[e];if(!n)return!1;var r=Array.prototype.slice.call(arguments,1);if(typeof n==`function`)n.apply(this,r);else{if(!t.util.isArray(n))return!1;for(var i=n.slice(),a=0,o=i.length;a<o;a++)i[a].apply(this,r)}return!0}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t){if(t&&t.parse)return e.JSON={parse:t.parse,stringify:t.stringify};throw Error(`JSON not available`)}(r===void 0?e.exports:r,typeof JSON<`u`?JSON:void 0),function(e,t){var n=e.parser={},r=n.packets=[`disconnect`,`connect`,`heartbeat`,`message`,`json`,`event`,`ack`,`error`,`noop`],i=n.reasons=[`transport not supported`,`client not handshaken`,`unauthorized`],a=n.advice=[`reconnect`],o=t.JSON,s=t.util.indexOf;n.encodePacket=function(e){var t=s(r,e.type),n=e.id||``,c=e.endpoint||``,l=e.ack,u=null;switch(e.type){case`error`:var d=e.reason?s(i,e.reason):``,f=e.advice?s(a,e.advice):``;d===``&&f===``||(u=d+(f===``?``:`+`+f));break;case`message`:e.data!==``&&(u=e.data);break;case`event`:var p={name:e.name};e.args&&e.args.length&&(p.args=e.args),u=o.stringify(p);break;case`json`:u=o.stringify(e.data);break;case`connect`:e.qs&&(u=e.qs);break;case`ack`:u=e.ackId+(e.args&&e.args.length?`+`+o.stringify(e.args):``)}var m=[t,n+(l==`data`?`+`:``),c];return u!=null&&m.push(u),m.join(`:`)},n.encodePayload=function(e){var t=``;if(e.length==1)return e[0];for(var n=0,r=e.length;n<r;n++)t+=`�`+e[n].length+`�`+e[n];return t};var c=/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;n.decodePacket=function(e){if(!(s=e.match(c)))return{};var t=s[2]||``,n=(e=s[5]||``,{type:r[s[1]],endpoint:s[4]||``});switch(t&&(n.id=t,s[3]?n.ack=`data`:n.ack=!0),n.type){case`error`:var s=e.split(`+`);n.reason=i[s[0]]||``,n.advice=a[s[1]]||``;break;case`message`:n.data=e||``;break;case`event`:try{var l=o.parse(e);n.name=l.name,n.args=l.args}catch{}n.args=n.args||[];break;case`json`:try{n.data=o.parse(e)}catch{}break;case`connect`:n.qs=e||``;break;case`ack`:if((s=e.match(/^([0-9]+)(\+)?(.*)/))&&(n.ackId=s[1],n.args=[],s[3]))try{n.args=s[3]?o.parse(s[3]):[]}catch{}break;case`disconnect`:n.reason=e}return n},n.decodePayload=function(e){if(e.charAt(0)==`�`){for(var t=[],r=1,i=``;r<e.length;r++)e.charAt(r)==`�`?(t.push(n.decodePacket(e.substr(r+1).substr(0,i))),r+=Number(i)+1,i=``):i+=e.charAt(r);return t}return[n.decodePacket(e)]}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t){function n(e,t){this.socket=e,this.sessid=t,this.connectErrorCallback=void 0,this.isOpened=!1}e.Transport=n,t.util.mixin(n,t.EventEmitter),n.prototype.onData=function(e){if(this.clearCloseTimeout(),(this.socket.connected||this.socket.connecting||this.socket.reconnecting)&&this.setCloseTimeout(),e!==``){var n=t.parser.decodePayload(e);if(n&&n.length)for(var r=0,i=n.length;r<i;r++)this.onPacket(n[r])}return this},n.prototype.onPacket=function(e){return this.socket.setHeartbeatTimeout(),e.type==`heartbeat`?this.onHeartbeat():(e.type==`connect`&&e.endpoint==``&&this.onConnect(),e.type==`error`&&e.advice==`reconnect`&&(this.isOpened=!1),this.socket.onPacket(e),this)},n.prototype.setCloseTimeout=function(){if(!this.closeTimeout){var e=this;this.closeTimeout=setTimeout((function(){e.onDisconnect()}),this.socket.closeTimeout)}},n.prototype.onDisconnect=function(){return this.close&&this.isOpened&&this.close(),this.clearTimeouts(),this.socket.onDisconnect(),this},n.prototype.onConnect=function(){return this.socket.onConnect(),this.connectErrorCallback=void 0,this},n.prototype.clearCloseTimeout=function(){this.closeTimeout&&=(clearTimeout(this.closeTimeout),null)},n.prototype.clearTimeouts=function(){this.clearCloseTimeout(),this.reopenTimeout&&clearTimeout(this.reopenTimeout)},n.prototype.packet=function(e){this.send(t.parser.encodePacket(e))},n.prototype.onHeartbeat=function(e){this.packet({type:`heartbeat`})},n.prototype.onOpen=function(){this.isOpened=!0,this.clearCloseTimeout(),this.socket.onOpen()},n.prototype.onClose=function(){this.isOpened=!1,this.socket.onClose(),this.onDisconnect()},n.prototype.prepareUrl=function(e){var n=this.socket.options;if(n[`skipped handshake data`])return n.rewriteUrlForProxy(n[`skipped handshake data`].websocketUrl+(e||``));var r=this.scheme()+`://`+n.host+`:`+n.port+`/`+n.resource+`/`+t.protocol+`/`+this.name+`/`+this.sessid+(e||``);return n.rewriteUrlForProxy(r)},n.prototype.ready=function(e,t){t.call(this)},n.prototype.clearEventHandlers=function(){return this}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t,n){function r(e){if(this.options={port:80,secure:!1,document:`document`in n&&document,resource:`socket.io`,transports:t.transports.slice(),"connect timeout":1e4,"try multiple transports":!0,reconnect:!0,"reconnection delay":500,"reconnection limit":1/0,"reopen delay":3e3,"max reconnection attempts":10,"sync disconnect on unload":!0,"auto connect":!0,"flash policy port":10843},t.util.merge(this.options,e),this.connected=!1,this.open=!1,this.connecting=!1,this.reconnecting=!1,this.namespaces={},this.buffer=[],this.doBuffer=!1,this.disconnected=!1,this.options[`sync disconnect on unload`]&&(!this.isXDomain()||t.util.ua.hasCORS)){var r=this;t.util.on(n,`unload`,(function(){r.disconnectSync()}),!1)}this.options[`auto connect`]&&this.connect()}function i(){}e.Socket=r,t.util.mixin(r,t.EventEmitter),r.prototype.of=function(e){return this.namespaces[e]||(this.namespaces[e]=new t.SocketNamespace(this,e),e!==``&&this.namespaces[e].packet({type:`connect`})),this.namespaces[e]},r.prototype.publish=function(){var e;for(var t in this.emit.apply(this,arguments),this.namespaces)this.namespaces.hasOwnProperty(t)&&(e=this.of(t)).$emit.apply(e,arguments)},r.prototype.handshake=function(e){var n=this,r=this.options;if(!n.disconnected){var a=r.rewriteUrlForProxy([`http`+(r.secure?`s`:``)+`:/`,r.host+`:`+r.port,r.resource,t.protocol,t.util.query(this.options.query,`t=`+ +new Date)].join(`/`));if(this.isXDomain()&&!t.util.ua.hasCORS){var o=document.getElementsByTagName(`script`)[0],s=document.createElement(`script`);s.src=a+`&jsonp=`+t.j.length,o.parentNode.insertBefore(s,o),t.j.push((function(e){u(e),s.parentNode.removeChild(s)}))}else{var c=t.util.request();c.open(`GET`,a,!0);var l=this.options.requestHeaders;l!==void 0&&Object.keys(l).forEach((function(e){c.setRequestHeader(e,l[e])})),c.onreadystatechange=function(){c.readyState==4&&(c.onreadystatechange=i,c.status==200?u(c.responseText):!n.reconnecting&&n.onError(c.responseText))},c.send(null)}}function u(t){t instanceof Error?n.onError(t.message):e.apply(null,t.split(`:`))}},r.prototype.getTransport=function(e){for(var n,r=e||this.transports,i=0;n=r[i];i++)if(t.Transport[n]&&t.Transport[n].check(this)&&(!this.isXDomain()||t.Transport[n].xdomainCheck()))return new t.Transport[n](this,this.sessionid);return null},r.prototype.connect=function(e){if(this.connecting||this.disconnected)return this;var n=this,r=function(r,i,a,o){function s(){if(!n.connected&&!n.disconnected)if(n.connecting=!1,clearTimeout(n.connectTimeoutTimer),n.options[`try multiple transports`]){for(;n.remainingTransports.length>0&&n.remainingTransports.splice(0,1)[0]!=n.transport.name;);n.remainingTransports.length?c(n.remainingTransports):n.publish(`connect_failed`)}else n.publish(`connect_failed`)}function c(e){if(n.transport&&(n.transport.clearTimeouts(),n.transport.clearEventHandlers()),n.transport=n.getTransport(e),!n.transport||n.disconnected)return n.publish(`connect_failed`);n.transport.ready(n,(function(){n.connecting=!0,n.publish(`connecting`,n.transport.name),n.transport.open(s),n.options[`connect timeout`]&&(n.connectTimeoutTimer=setTimeout((function(){s()}),n.options[`connect timeout`]))}))}n.sessionid=r,n.closeTimeout=1e3*a+2e3,n.heartbeatTimeout=1e3*i+2e3,n.transports=o?t.util.intersect(o.split(`,`),n.options.transports):n.options.transports,n.setHeartbeatTimeout(),n.remainingTransports=n.transports.slice(0),c(n.transports),n.once(`connect`,(function(){clearTimeout(n.connectTimeoutTimer),e&&typeof e==`function`&&e()}))};if(this.options[`skipped handshake data`]){var i=this.options[`skipped handshake data`];r(`v4c-`+new Date().getTime(),i.timeout,i.timeout,`websocket`)}else this.handshake(r);return this},r.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);var e=this;this.heartbeatTimeoutTimer=setTimeout((function(){e.transport.onClose()}),this.heartbeatTimeout)},r.prototype.packet=function(e){return this.connected&&!this.doBuffer?this.transport.packet(e):this.buffer.push(e),this},r.prototype.setBuffer=function(e){this.doBuffer=e,!e&&this.connected&&this.buffer.length&&(this.transport.payload(this.buffer),this.buffer=[])},r.prototype.disconnect=function(){return(this.connected||this.connecting)&&(this.open&&this.of(``).packet({type:`disconnect`}),this.onDisconnect(`booted`)),this.disconnected=!0,this},r.prototype.disconnectSync=function(){var e=t.util.request(),n=this.resource+`/`+t.protocol+`/`+this.sessionid;e.open(`GET`,n,!0),this.onDisconnect(`booted`)},r.prototype.isXDomain=function(){var e=n.location.port||(n.location.protocol==`https:`?443:80);return this.options.host!==n.location.hostname||this.options.port!=e},r.prototype.onConnect=function(){this.connected||(this.connected=!0,this.connecting=!1,this.doBuffer||this.setBuffer(!1),this.emit(`connect`))},r.prototype.onOpen=function(){this.open=!0},r.prototype.onClose=function(){this.open=!1,clearTimeout(this.heartbeatTimeoutTimer)},r.prototype.onPacket=function(e){this.of(e.endpoint).onPacket(e)},r.prototype.onError=function(e){e&&e.advice&&e.advice===`reconnect`&&(this.connected||this.connecting)&&(this.disconnect(),this.options.reconnect&&this.reconnect()),this.publish(`error`,e&&e.reason?e.reason:e)},r.prototype.onDisconnect=function(e){var t=this.connected,n=this.connecting;this.connected=!1,this.connecting=!1,this.open=!1,(t||n)&&(this.transport.close(),this.transport.clearTimeouts(),t?(this.publish(`disconnect`,e),e!=`booted`&&this.options.reconnect&&!this.reconnecting&&this.reconnect()):this.publish(`close_during_connecting`,e))},r.prototype.reconnect=function(){this.reconnecting=!0,this.reconnectionAttempts=0,this.reconnectionDelay=this.options[`reconnection delay`];var e=this,t=this.options[`max reconnection attempts`],n=this.options[`try multiple transports`],r=this.options[`reconnection limit`];function i(){if(e.connected){for(var t in e.namespaces)e.namespaces.hasOwnProperty(t)&&t!==``&&e.namespaces[t].packet({type:`connect`});e.publish(`reconnect`,e.transport.name,e.reconnectionAttempts)}clearTimeout(e.reconnectionTimer),e.removeListener(`connect_failed`,a),e.removeListener(`connect`,a),e.reconnecting=!1,delete e.reconnectionAttempts,delete e.reconnectionDelay,delete e.reconnectionTimer,delete e.redoTransports,e.options[`try multiple transports`]=n}function a(){if(e.reconnecting)return e.connected?i():e.connecting&&e.reconnecting?e.reconnectionTimer=setTimeout(a,1e3):void(e.reconnectionAttempts++>=t?e.redoTransports?(e.publish(`reconnect_failed`),i()):(e.on(`connect_failed`,a),e.options[`try multiple transports`]=!0,e.transport=e.getTransport(),e.redoTransports=!0,e.connect()):(e.reconnectionDelay<r&&(e.reconnectionDelay*=2),e.connect(),e.publish(`reconnecting`,e.reconnectionDelay,e.reconnectionAttempts),e.reconnectionTimer=setTimeout(a,e.reconnectionDelay)))}this.options[`try multiple transports`]=!1,this.reconnectionTimer=setTimeout(a,this.reconnectionDelay),this.on(`connect`,a)}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r,MG===void 0?window:MG),function(e,t){function n(e,t){this.socket=e,this.name=t||``,this.flags={},this.json=new r(this,`json`),this.ackPackets=0,this.acks={}}function r(e,t){this.namespace=e,this.name=t}e.SocketNamespace=n,t.util.mixin(n,t.EventEmitter),n.prototype.$emit=t.EventEmitter.prototype.emit,n.prototype.of=function(){return this.socket.of.apply(this.socket,arguments)},n.prototype.packet=function(e){return e.endpoint=this.name,this.socket.packet(e),this.flags={},this},n.prototype.send=function(e,t){var n={type:this.flags.json?`json`:`message`,data:e};return typeof t==`function`&&(n.id=++this.ackPackets,n.ack=!0,this.acks[n.id]=t),this.packet(n)},n.prototype.emit=function(e){var t=Array.prototype.slice.call(arguments,1),n=t[t.length-1],r={type:`event`,name:e};return typeof n==`function`&&(r.id=++this.ackPackets,r.ack=`data`,this.acks[r.id]=n,t=t.slice(0,t.length-1)),r.args=t,this.packet(r)},n.prototype.disconnect=function(){return this.name===``?this.socket.disconnect():(this.packet({type:`disconnect`}),this.$emit(`disconnect`)),this},n.prototype.onPacket=function(e){var n=this;function r(){n.packet({type:`ack`,args:t.util.toArray(arguments),ackId:e.id})}switch(e.type){case`connect`:this.$emit(`connect`);break;case`disconnect`:this.name===``?this.socket.onDisconnect(e.reason||`booted`):this.$emit(`disconnect`,e.reason||``);break;case`message`:case`json`:var i=[`message`,e.data];e.ack==`data`?i.push(r):e.ack&&this.packet({type:`ack`,ackId:e.id}),this.$emit.apply(this,i);break;case`event`:i=[e.name].concat(e.args),e.ack==`data`&&i.push(r),this.$emit.apply(this,i);break;case`ack`:this.acks[e.ackId]&&(this.acks[e.ackId].apply(this,e.args),delete this.acks[e.ackId]);break;case`error`:e.advice?this.socket.onError(e):e.reason==`unauthorized`?this.$emit(`connect_failed`,e.reason):this.$emit(`error`,e.reason)}},r.prototype.send=function(){this.namespace.flags[this.name]=!0,this.namespace.send.apply(this.namespace,arguments)},r.prototype.emit=function(){this.namespace.flags[this.name]=!0,this.namespace.emit.apply(this.namespace,arguments)}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t,n){function r(e){t.Transport.apply(this,arguments)}function i(){}e.websocket=r,t.util.inherit(r,t.Transport),r.prototype.name=`websocket`,r.prototype.open=function(e){var r,i=t.util.query(this.socket.options.query),a=this;return this.connectErrorCallback=e,r||=n.MozWebSocket||n.WebSocket,this.websocket=new r(this.prepareUrl(i)),this.websocket.onopen=function(){a.onOpen(),a.socket.setBuffer(!1)},this.websocket.onmessage=function(e){a.onData(e.data)},this.websocket.onclose=function(){a.onClose(),a.socket.setBuffer(!0)},this.websocket.onerror=function(e){a.onError(e)},this},r.prototype.send=function(e){return this.websocket.send(e),this},r.prototype.payload=function(e){for(var t=0,n=e.length;t<n;t++)this.packet(e[t]);return this},r.prototype.close=function(){return this.websocket.close(),this},r.prototype.onError=function(e){this.connectErrorCallback!==void 0&&(this.connectErrorCallback(),this.connectErrorCallback=void 0),this.socket.onError(e)},r.prototype.scheme=function(){return this.socket.options.secure?`wss`:`ws`},r.check=function(){return`WebSocket`in n&&!(`__addTask`in WebSocket)||`MozWebSocket`in n},r.xdomainCheck=function(){return!0},r.prototype.clearEventHandlers=function(){return this.websocket&&(this.websocket.onopen=this.websocket.onmessage=this.websocket.onclose=this.websocket.onerror=i),this},t.transports.push(`websocket`)}(r===void 0?e.exports:r.Transport,r===void 0?e.parent.exports:r,MG===void 0?window:MG),function(e,t,n){function r(e){e&&t.Transport.apply(this,arguments)}function i(){}e.XHR=r,t.util.inherit(r,t.Transport),r.prototype.open=function(){return this.socket.setBuffer(!1),this.onOpen(),this.get(),this.setCloseTimeout(),this},r.prototype.payload=function(e){for(var n=[],r=0,i=e.length;r<i;r++)n.push(t.parser.encodePacket(e[r]));this.send(t.parser.encodePayload(n))},r.prototype.send=function(e){return this.post(e),this},r.prototype.post=function(e){var t=this;this.socket.setBuffer(!0),this.sendXHR=this.request(`POST`),n.XDomainRequest&&this.sendXHR instanceof XDomainRequest?this.sendXHR.onload=this.sendXHR.onerror=function(){this.onload=i,t.socket.setBuffer(!1)}:this.sendXHR.onreadystatechange=function(){this.readyState==4&&(this.onreadystatechange=i,this.status==200?(clearTimeout(this.ackTimeoutTimer),t.socket.setBuffer(!1)):t.onClose())},this.sendXHR.send(e),t.sendXHR.ackTimeoutTimer=setTimeout((function(){t.onClose()}),t.socket.options.ackTimeoutMs)},r.prototype.close=function(){return this.onClose(),this},r.prototype.request=function(e){var n=t.util.request(this.socket.isXDomain()),r=t.util.query(this.socket.options.query,`t=`+ +new Date);n.open(e||`GET`,this.prepareUrl(r),!0);var i=this.socket.options.requestHeaders;if(i!==void 0&&Object.keys(i).forEach((function(e){n.setRequestHeader(e,i[e])})),e==`POST`)try{n.setRequestHeader?n.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`):n.contentType=`text/plain`}catch{}return n},r.prototype.scheme=function(){return this.socket.options.secure?`https`:`http`},r.check=function(e,r){try{var i=t.util.request(r),a=n.XDomainRequest&&i instanceof XDomainRequest,o=(e&&e.options&&e.options.secure?`https:`:`http:`)!=n.location.protocol;if(i&&(!a||!o))return!0}catch{}return!1},r.xdomainCheck=function(){return r.check(null,!0)},r.prototype.clearEventHandlers=function(){return this.sendXHR&&(this.sendXHR.onreadystatechange=this.sendXHR.onload=i),this}}(r===void 0?e.exports:r.Transport,r===void 0?e.parent.exports:r,MG===void 0?window:MG),function(e,t,n){function r(){t.Transport.XHR.apply(this,arguments)}function i(){}e[`xhr-polling`]=r,t.util.inherit(r,t.Transport.XHR),t.util.merge(r,t.Transport.XHR),r.prototype.name=`xhr-polling`,r.prototype.open=function(e){return this.connectErrorCallback=e,t.Transport.XHR.prototype.open.call(this),!1},r.prototype.get=function(){if(this.isOpened){var e=this;this.xhr=this.request(),n.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=function(){e.connectErrorCallback=void 0,this.onload=i,this.onerror=i,e.onData(this.responseText),e.get()},this.xhr.onerror=function(){e.onClose(),e.connectErrorCallback!==void 0&&(e.connectErrorCallback(),e.connectErrorCallback=void 0)}):this.xhr.onreadystatechange=function(){this.readyState==4&&(this.onreadystatechange=i,this.status==200?(e.connectErrorCallback=void 0,e.onData(this.responseText),e.get()):(e.onClose(),e.connectErrorCallback!==void 0&&(e.connectErrorCallback(),e.connectErrorCallback=void 0)))},this.xhr.send(null)}},r.prototype.onClose=function(){if(t.Transport.XHR.prototype.onClose.call(this),this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=i;try{this.xhr.abort()}catch{}this.xhr=null}},r.prototype.ready=function(e,n){var r=this;t.util.defer((function(){n.call(r)}))},r.prototype.clearEventHandlers=function(){return t.Transport.XHR.prototype.clearEventHandlers.call(this),this.xhr&&(this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=i),this},t.transports.push(`xhr-polling`)}(r===void 0?e.exports:r.Transport,r===void 0?e.parent.exports:r,MG===void 0?window:MG),t.io=r}},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={id:e,loaded:!1,exports:{}};return t[e].call(a.exports,a,a.exports,r),a.loaded=!0,a.exports}return r.nmd=e=>(e.paths=[],e.children||=[],e),r(882)})(),e.exports=t(vLe())),i9.exports;var e,t}var o9,xLe,s9=bLe(),SLe=class{constructor(e,t){this.logEvent=e=>{this._logger.debug(e),this._telemetryLogManager.sendEvent({name:e.name,tenant:DCe,properties:{...e.properties}})},this._logger=e.createChild(`TelemetrySender`),this._telemetryLogManager=t}};function CLe(e){return{registrationId:J0(),registrarServiceUrl:e.getTrouterSettings().registrarServiceUrl,registrarTtlInSeconds:e.getTrouterSettings().registrarTtlInSeconds,maxRegistrationTimeInMs:e.getTrouterSettings().maxRegistrationTimeInMs,registrarRefreshTimeoutInMs:e.getTrouterSettings().registrarRefreshTimeoutInMs,pnhAppId:e.getTrouterSettings().pnhAppId,pnhTemplate:e.getTrouterSettings().pnhTemplate,platform:e.getTrouterSettings().platform,platformUIVersion:e.getTrouterSettings().version,trouterServiceUrl:e.getTrouterSettings().trouterServiceUrl,version:e.getTrouterSettings().version,trouterConnectTimeoutInMs:e.getTrouterSettings().trouterConnectTimeoutInMs,productName:e.getTrouterSettings().productName,sessionId:J0(),environment:e.getTrouterSettings().environment,timeoutOptions:e.getTrouterSettings().timeoutOptions}}var wLe=class{constructor(e,t,n,r,i){this._ecsProvider=t,this._tokenProvider=n,this._isRegistered=!1,this._registeredChangedListeners=[],this._logger=e.createChild(`Trouter`),this._logger.info(`init`),this._initialRegistrationCompleteDefer=n3(),this._telemetryLogManager=r,this._acsProxy=i}async start(e){let t;if(this._trouterService)throw this._logger.error(`Trouterservice already initialized`),new Y({defaultError:J.CALL_STACK.SIGNALING_SERVICE_ALREADY_INITIALIZED});{let n=new Promise((async(t,n)=>{try{if(this._logger.info(`Trouterservice start`),this._trouterService=s9.createTrouterService(this._logger),!this._trouterService)throw this._logger.error(`Failed to create trouter service`),new Y({defaultError:J.CALL_STACK.SIGNALING_SERVICE_CREATE_FAIL});this._options=this._getTrouterConfig(this._logger,this._tokenProvider),e&&(this._options.trouterSettings.environment=e.environment||``,this._options.trouterSettings.sessionId=e.sessionId);let n,r,i=+new Date;this._trouterService.start(this._options),this._trouterService.onStateChanged(((e,t)=>{e===s9.TrouterState.Connected&&(n=+new Date)})),await this._initialRegistrationCompleteDefer.promise;let a=+new Date;n??=+new Date,r=n,t({trouterRequestCompletionTimeDeltaMs:Math.max(0,n-i),registrarRequestCompletionTimeDeltaMs:Math.max(0,a-r)})}catch(e){n(e)}}));try{t=await i3((()=>n),ZSe)}catch(e){throw e.code===408?(this._logger.error(`Signaling init timeout`),new Y({defaultError:J.CALL_STACK.SIGNALING_SERVICE_CREATE_TIMEOUT,defaultErrorMessageArgs:[ZSe]})):(this._logger.error(`Signaling init failed`),new Y({defaultError:J.CALL_STACK.SIGNALING_INIT_FAIL}))}}return t}isRegistered(){return this._isRegistered}onRegisteredChanged(e){this._logger.info(`TrouterService onRegisteredChanged`),this._registeredChangedListeners.push(e)}offRegisteredChanged(e){let t=this._registeredChangedListeners.indexOf(e);this._logger.info(`TrouterService offRegisteredChanged: ${t}`),t>-1&&this._registeredChangedListeners.splice(t,1)}stop(e){this._logger.info(`Trouterservice stop`),this._trouterService?(this._trouterService.onStateChanged(void 0),this._trouterService.stop(e),this._trouterService=void 0):this._logger.error(`Trouterservice not inited`)}registerMessageHandler(e){this._logger.info(`Trouterservice registerMessageHandler`),this._trouterService&&this._trouterService.registerMessageHandler(e)}clearMessageHandlers(){this._trouterService&&this._trouterService.clearMessageHandlers()}checkConnection(){this._trouterService&&this._trouterService.checkConnection()}state(){return this._logger.info(`Trouterservice state`),this._trouterService?this._trouterService.state():s9.TrouterState.Unknown}onStateChanged(e){this._logger.info(`Trouterservice onStateChanged`),this._trouterService&&this._trouterService.onStateChanged(e)}offStateChanged(e){this._logger.info(`Trouterservice offStateChanged`),this._trouterService&&this._trouterService.offStateChanged(e)}getTrouterUrlAsync(){return this._trouterService?(this._logger.info(`getTrouterUrlAsync called`),this._trouterService.getTrouterUrlAsync()):Promise.reject(`Trouterservice not started yet`)}getTrouterSettings(){return this._options.trouterSettings}_getSettings(){return CLe(this._ecsProvider)}_createTrouterTelemetryConfig(e){return{eventLogger:new SLe(e.createChild(`TrouterTelemetry`),this._telemetryLogManager),settings:{enabled:this._ecsProvider.getTrouterTelemetryConfig().enabled,logHealthCheckError:this._ecsProvider.getTrouterTelemetryConfig().logHealthCheckError,trouter_js_client_connected:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_connected,trouter_js_client_disconnected:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_disconnected,trouter_js_client_error:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_error,trouter_js_client_progress:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_progress,trouter_js_client_response:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_response,numberOfStepsToMaintain:this._ecsProvider.getTrouterTelemetryConfig().numberOfStepsToMaintain,sendProgressTimeoutSecs:this._ecsProvider.getTrouterTelemetryConfig().sendProgressTimeoutSecs}}}_getTrouterConfig(e,t){return{trouterSettings:this._getSettings(),proxyUrlRewrite:this._acsProxy.hasProxyUrl()?e=>this._acsProxy.proxyfyUrl(e):void 0,skypeTokenProvider:t,telemetryConfig:this._createTrouterTelemetryConfig(e),registrationStateCallbackForAcsDoNotUse:e=>{this._logger.info(`TrouterService registrationStateCallbackForAcs: ${e}`),this._isRegistered=e,this._initialRegistrationCompleteDefer.isPending()&&this._isRegistered?this._initialRegistrationCompleteDefer.resolve():this._isRegistered?this._logger.info(`Signaling service is currently registered`):this._logger.error(`Signaling service is currently not registered. Unable to receive incoming calls`),this._onRegisteredChanged(e)}}}_onRegisteredChanged(e){this._logger.info(`TrouterService onRegisteredChanged: ${e}`),this._registeredChangedListeners.forEach((t=>{t(e)}))}},TLe=class{constructor(e){this._eventToTenantId={skypecosi_concore_web_csa_conversation_httprequest:m2,skypecosi_concore_web_ts_calling_in_call_session:m2,skypecosi_concore_web_ts_calling_call_setup_session:m2,skypecosi_concore_native_ts_calling_in_call_session:m2,skypecosi_concore_native_ts_calling_call_setup_session:m2,skypecosi_concore_web_pluginless_call_session:m2,skypecosi_concore_web_pluginless_modality_session:m2,skypecosi_concore_web_csa_conversation_callmodality:m2,skypecosi_concore_web_ts_calling_registry:m2,mdsc_webrtc_session:h2,mdsc_webrtc_session_initial:h2,live_events:ECe,mdsc_ortc_reports:h2,mdsc_ortc_reports_initial:h2,mdsc_rt_log:h2},this.getTenant=e=>this._eventToTenantId[e]?this._eventToTenantId[e]:``,this.getCallingAdapter=()=>({sendEvent:(e,t)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e),name:e,properties:t})}}),this.getGenericTelemetryLogger=e=>({sendEvent:e=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e.eventName),name:e.eventName,properties:e.props})}}),this.getMediaAdapter=()=>({sendEvent:(e,t)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e),name:e,properties:t})}}),this.sendEvents=e=>(e.forEach((e=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e.eventName),name:e.eventName,properties:e.props})})),Promise.resolve()),this._telemetryLogManager=e}},ELe=class{constructor(){this._timedVideoEffectProviderPromise=qwe(cue),this._timedModelConfigPromise=qwe(cue)}get videoEffectProviderDeferredPromise(){return this._timedVideoEffectProviderPromise.deferredPromise}get modelConfigDeferredPromise(){return this._timedModelConfigPromise.deferredPromise}async getVideoEffectProvider(){return this._timedVideoEffectProviderPromise.timerStart(),this._timedVideoEffectProviderPromise.deferredPromise.promise}async getModelConfig(){return this._timedModelConfigPromise.deferredPromise.resolve({modelUrl:``,weightPathPrefix:``}),this._timedModelConfigPromise.deferredPromise.promise}},DLe=class{constructor(e){this._encodedStreamsJsPath=e}async getWorkerUrl(){return this._encodedStreamsJsPath}},OLe=class{constructor(e,t){t||typeof e.createChild!=`function`?this.logger=e:this.logger=e.createChild(`HttpRequestDispatcher::`),this.proxy=t}getRequestOptions(e,t,n,r,i){return{headers:t||{},timeout:r,payload:n||null,responseType:i}}getAsync(e,t){return this.send(e,t,L3.GET)}postAsync(e,t){return this.send(e,t,L3.POST)}putAsync(e,t){return this.send(e,t,L3.PUT)}removeAsync(e,t){return this.send(e,t,L3.DELETE)}async send(e,t={headers:{}},n){let r=this.logger.createChild(`[${t.causeId||J0()}] HttpRequestDispatcher::`),i=J0();r.info(`Send, httpRequestId: ${i}, ${n} ${e}`),this.proxy&&(e=this.proxy.proxyfyUrl(e));let a=new AbortController,o=()=>{r.info(`Send, httpRequestId: ${i}, aborting`),a.abort()};r.info(`Send, httpRequestId: ${i}, responseType: ${t.responseType}`),t.headers=t.headers||{};let s=t.headers;s[`Content-Type`]||=t.contentType||`application/json`;let c={method:n,headers:t.headers,credentials:t.withCredentials?`include`:`same-origin`,keepalive:t.keepAlive||!1,signal:a.signal},l=Date.now(),u={url:e,start:new Date(l).toISOString(),end:``,statusCode:0,deltaTimeInMs:0,causeId:``},d=Z().telemetry.apiCauseIdHeader;try{n!==`GET`&&(c.body=t.payload||``);let a=fetch(e,c);if(typeof t.timeout==`number`&&t.timeout>0){let e=setTimeout((()=>o()),t.timeout);a=a.finally((()=>clearTimeout(e)))}bwe(t.timeout)&&t.timeout.then((()=>{o()}),(()=>{r.info(`Send, httpRequestId: ${i}, timeout promise rejected`)}));let s=await a;if(r.info(`Send, httpRequestId: ${i}, \n response status: ${s.status}`),t.headers[d]){let e=t.headers[d].split(`-`)[0];L6.getRemoveCauseIdToNetworkInfo(e)&&this.setCauseIdToNetworkInfo(u,s.status,e)}let f;try{f=await this.extractPayload(s,i,r)}catch(e){r.error(`Send, httpRequestId: ${i}, failed to parse response, error: ${e.message}`)}let p={};return s.headers.forEach(((e,t)=>{p[t]=e})),{response:f,request:{status:s.status,statusText:s.statusText,headers:p,responseURL:s.url,response:f,withCredentials:t.withCredentials},duration:Date.now()-l}}catch(n){if(r.error(`Send, httpRequestId: ${i}, \n failed ${c.method} ${e}, error: ${n.message}`),t.headers[d]){let e=t.headers[d].split(`-`)[0];L6.ifCauseIdExistsRemoveNetworkInfo(e)&&this.setCauseIdToNetworkInfo(u,n.code,e)}throw n.name===`AbortError`?(r.warn(`Send, httpRequestId: ${i}, aborted`),{aborted:!0}):(n.response?r.warn(`Send, httpRequestId: ${i}, \n response: ${i4(n.response)}`):n.request?r.warn(`Send, httpRequestId: ${i}, \n no response, request: ${i4(n.request)}`):r.warn(`Send, httpRequestId: ${i}, \n request not made, error: ${i4(n)}`),n||Error(`HttpRequestId: ${i}, failed`))}}async extractPayload(e,t,n){let r=this.getHeader(e,`content-type`,n),i=this.getHeader(e,`content-length`,n);switch(n.info(`ExtractPayload, httpRequestId: ${t}, \n parsing content type: ${r}, content length: ${i}`),r){case`application/json`:return i?await e.json():{};case`application/text`:return i?await e.text():``;case`application/octet-stream`:return i?await e.blob():new Blob;case`application/arraybuffer`:return i?await e.arrayBuffer():new ArrayBuffer(0);default:return e.json().catch((()=>{throw Error(`HttpRequestId: ${t}, unsupported content type: ${r}`)}))}}getHeader(e,t,n){n.info(`GetHeader, header: ${t}`);let r=e.headers.get(t.toLowerCase()),i;return r!==null&&(i=r),i}setCauseIdToNetworkInfo(e,t,n){e={...e,end:new Date().toISOString(),statusCode:t,deltaTimeInMs:Date.now()-new Date(e.start).getTime(),causeId:n},L6.setCauseIdToNetworkInfo(n,e)}},kLe=class{constructor(){this._activeEffects=[],this.eventEmitter=new E3.EventEmitter}on(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.VIDEO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.VIDEO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getActiveEffects(){return this._activeEffects}setActiveEffects(e){let t=this._activeEffects;this._activeEffects=e,this.eventEmitter.emit(`statusChanged`,t,this._activeEffects)}},ALe=class{constructor(){this._activeEffects={echoCancellation:[],noiseSuppression:[],autoGainControl:[]},this.eventEmitter=new E3.EventEmitter}on(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.AUDIO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.AUDIO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getActiveEffects(){return this._activeEffects}setActiveEffects(e,t){let n={...this._activeEffects};this._activeEffects={...e},this.eventEmitter.emit(`statusChanged`,n,this._activeEffects,t)}},jLe=class{constructor(){this._providerValue=null}get providerValue(){return this._providerValue}set providerValue(e){this._providerValue=e}async getAudioEffectProvider(){return this.providerValue}};function MLe(){if(xLe)return o9;xLe=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,i=(i,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of n(a))r.call(i,c)||c===o||e(i,c,{get:()=>a[c],enumerable:!(s=t(a,c))||s.enumerable});return i},a=t=>i(e({},`__esModule`,{value:!0}),t),o={};function s(e){return new Promise((t=>setTimeout(t,e)))}((t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:!0})})(o,{mmrAdapter:()=>f}),o9=a(o);var c=class{constructor(){this.observers=new Set}subscribe(e){return typeof e==`function`&&(e={next:e}),this.observers.add(e),{unsubscribe:()=>{this.observers.delete(e)}}}},l=class extends c{constructor(e){super(),this.logger=e,this._state=3}get state(){return this._state}handleMessage(e){this.observers.forEach((t=>{t.next?.(e)}))}},u=`config`,d=class extends l{constructor(e,t){super(e),this.config=t,this.waitForChannel()}get tsCallingChannel(){return window.navigator.mediaDevices?.tsCallingChannel}getConfig(){return this.config}next(e){this.tsCallingChannel?this.tsCallingChannel.sendTsCallingMessage(e):this.logger.error(`tsCallingChannel is not available.`)}async waitForChannel(){do this.initializeTsCallingChannel(),await s(500);while(this.state!==1)}initializeTsCallingChannel(){if(!this.tsCallingChannel)return;this._state=1,this.tsCallingChannel.addEventListener(`messagerecv`,(e=>{e.detail?.message&&this.handleMessage(e.detail.message)}));let e=this.createConnectionURL();this.logger.log(`connectionUrl: ${e}`),this.tsCallingChannel.sendTsCallingMessage({WebViewRemotingControlChannel:{url:e.toString()}})}createConnectionURL(){let{loaderUrl:e,...t}=this.config;if(!e)throw this.logger.error(`loaderUrl was not passed in config.`),Error(`loaderUrl was not passed in config.`);try{let n=new URL(e);return n.searchParams.set(u,JSON.stringify(t)),n}catch(e){throw this.logger.error(`Failed to create connection URL`,e),e}}},f=(e,t)=>new d(e,t);return o9}var NLe=MLe();function PLe(){return!!navigator.mediaDevices?.tsCallingChannel}function FLe(e,t){let n=Z().vdi3,r=window.vdi3Debug??{},i=r.cdnUrl??n.cdnUrl;if(!i){let e=n.customTsVersion||W5.stackFactory.getVersion().build;if(e.includes(`_`))throw new Y({defaultError:J.FEATURES.VDI3.INVALID_CDN_URL});i=`${n.cdnBaseUrl}${e}/`}let a=r.connectionUrl??new URL(n.loaderHtmlPath,i).toString(),o=r.pluginlessUrl??new URL(n.pluginlessJsPath,i).toString();return{vdi3Config:{transport:NLe.mmrAdapter(e,{staleTimeout:n.transportConnectionTimeoutInMs,executionTimeout:n.remoteExecutionTimeoutInMs,messageChunkSize:n.chunkSize,writeLogToConsole:r.writeLogToConsole??t?.writeLogToConsole??n.writeLogToConsole,loaderUrl:a}),trouterSettings:{},pluginlessUrl:o,cdnUrl:i}}}var ILe={AcsCallingSDKWeb:{telemetry:{telemetryFlushTimeout:1e4,mediaStatsConfig:{enableVideoLeakInformation:!1,enableRenderCountCheck:!1}},calling:{allowAccessRawMediaStream:!1,deviceSelectionTimeoutInMs:1e4}},SkypeWebMedia:{mediaAgent:{useOneDsLogger:!0}}},LLe=class{constructor(){this._mapping=new WeakMap,this._eventEmitter=new D3,this._isRemoteStackActive=!0}get(e){return this._mapping.get(e)?.deref()}create(e){let t=this._createProxy(e);if(t===void 0)throw Error(`The type is not supported for proxy`);return this._mapping.set(e,new WeakRef(t)),t}replaceProxyToRaw(e){if(typeof e==`object`){if(Array.isArray(e))return e.map((e=>this.replaceProxyToRaw(e)));if(W6 in e)return e[W6]}return e}replaceRawToProxy(e,t){if(t===void 0&&(t=new Map),typeof e==`object`){if(e===null)return e;if(t.has(e))return t.get(e);if(W6 in e)return e;if(Array.isArray(e)){let n=e.map((e=>this.replaceRawToProxy(e,t)));return t.set(e,n),n}if(e instanceof Promise)return e.then((e=>this.replaceRawToProxy(e,t)));if(e instanceof ArrayBuffer||e instanceof Uint8Array||e instanceof Date||e instanceof RegExp)return e;if(this.isSupportedType(e)){let n=this.get(e);return n===void 0&&(n=this.create(e)),t.set(e,n),n}if(HOe(e))return t.set(e,e),e;let n={};t.set(e,n);for(let[r,i]of Object.entries(e))n[r]=this.replaceRawToProxy(i,t);return n[W6]=e,n}return e}on(e,t){this._eventEmitter.on(e,t)}once(e,t){this._eventEmitter.once(e,t)}dispose(){this._eventEmitter.removeAllListeners()}};function c9(e,t,n,r={}){return new Proxy(e,{get:(i,a)=>{let o,s;if(a===W6)return e;if(a in t)o=t[a],s=t;else{if(!(a in e))return;o=e[a],s=e}let c=r[a]??{input:!0,output:!0};if(typeof o==`function`){if(!n.isRemoteStackActive()&&s===e)throw new Y({defaultError:J.FEATURES.VDI3.REMOTE_STACK_TERMINATED});return new Proxy(o,{apply:(e,t,r)=>{let i=r.map((e=>typeof e==`function`?(...t)=>e.apply(null,n.replaceRawToProxy(t)):c.input?n.replaceProxyToRaw(e):e)),a=Reflect.apply(e,s,i);return c.output?n.replaceRawToProxy(a):a}})}return c.output?n.replaceRawToProxy(o):o},has:(n,r)=>r===W6||r in t||r in e})}var l9=class{constructor(e,t){this._proxyReferenceManager=e,this._tsObject=t,this._eventEmitter=new D3,this._handles=new Map,this._skipEvents=[`optimalVideoReceiversCountChanged`]}_proxyCall(e,t){let n=this._tsObject[e];if(n!==void 0)return n.apply(this._tsObject,t)}get instance(){return this._tsObject}changed(e){let t=`changed`,n=this._handles.get(t);n===void 0&&(n=this._proxyCall(`changedAsync`,[(...e)=>{this._eventEmitter.emit(t,...e)}]),this._handles.set(t,n));let r=(...t)=>{e.apply(null,t)};return this._eventEmitter.on(t,r),{dispose:()=>{this._eventEmitter.off(t,r),this._eventEmitter.listenerCount(t)===0&&(n?.then((e=>e.disposeAsync?.())).catch(M4),this._handles.delete(t))}}}on(e,t){if(this._skipEvents.includes(e))return{dispose:M4};let n=`on_${e}`,r=this._handles.get(n);r===void 0&&(r=this._proxyCall(`onAsync`,[e,(...e)=>{this._eventEmitter.emit(n,...e)}]),this._handles.set(n,r));let i=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(n,i),{dispose:()=>{this._eventEmitter.off(n,i),this._eventEmitter.listenerCount(n)===0&&(r?.then((e=>e.disposeAsync?.())).catch(M4),this._handles.delete(n))}}}once(e,t){if(this._skipEvents.includes(e))return{dispose:M4};let n=`once_${e}`,r=this._handles.get(n);r===void 0&&(r=this._proxyCall(`onceAsync`,[e,(...e)=>{this._eventEmitter.emit(n,...e)}]),this._handles.set(n,r));let i=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(n,i),{dispose:()=>{this._eventEmitter.off(n,i),this._eventEmitter.listenerCount(n)===0&&(r?.then((e=>e.disposeAsync?.())).catch(M4),this._handles.delete(n))}}}async changedAsync(e){let t=`changed`,n=this._handles.get(t);n===void 0&&(n=this._proxyCall(`changedAsync`,[(...e)=>{this._eventEmitter.emit(t,...e)}]),this._handles.set(t,n));let r=(...t)=>{e.apply(null,t)};return this._eventEmitter.on(t,r),await n,{dispose:()=>{this._eventEmitter.off(t,r),this._eventEmitter.listenerCount(t)===0&&(n?.then((e=>e.disposeAsync?.())).catch(M4),this._handles.delete(t))}}}async onAsync(e,t){if(this._skipEvents.includes(e))return{dispose:M4};let n=`on_${e}`,r=this._handles.get(n);r===void 0&&(r=this._proxyCall(`onAsync`,[e,(...e)=>{this._eventEmitter.emit(n,...e)}]),this._handles.set(n,r));let i=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(n,i),await r,{dispose:()=>{this._eventEmitter.off(n,i),this._eventEmitter.listenerCount(n)===0&&(r?.then((e=>e.disposeAsync?.())).catch(M4),this._handles.delete(n))}}}},RLe=class extends l9{constructor(e,t){super(e,t),e.once(`remoteStackTerminated`,(()=>{this._eventEmitter.emit(`changed`),this._eventEmitter.emit(`on_callStateChanged`)}))}get state(){return this._proxyReferenceManager.isRemoteStackActive()?this._tsObject.state:7}get callEndDiagnosticsInfo(){return this._proxyReferenceManager.isRemoteStackActive()||this._tsObject.state===7?this._tsObject.callEndDiagnosticsInfo:{callControllerCode:0,callControllerSubCode:4521,phrase:`call ended due to RDP disconnection`,resultCategories:[`ExpectedError`]}}get ptzHandler(){throw new Y({defaultError:J.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}get broadcastMeeting(){throw new Y({defaultError:J.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}get videoLayout(){throw new Y({defaultError:J.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}getIncomingRawAudioStream(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getUnmixedAudioProvider(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}init(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setDeviceManager(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}forceUpdate(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}startVideo(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopVideo(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}startScreenSharing(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}changeCropRegion(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopScreenSharing(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}callSafeTransfer(e,t,n){return n===void 0&&(n={disableForwardingAndUnanswered:!1}),this._tsObject.callSafeTransfer(e,t,n)}setPlatformCallConstraints(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createStageAsync(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createStage(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendLastKnownStats(){this._proxyReferenceManager.isRemoteStackActive()&&this._tsObject.sendLastKnownStats().catch((e=>{}))}},zLe=class extends l9{constructor(e,t){super(e,t)}getSourceIdForMediaType(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDiagnosticData(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},BLe=class extends l9{constructor(e,t){super(e,t)}getRawStream(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}start(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stop(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}selectVideoTrack(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setVideoStreamConfig(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDiagnosticData(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getStats(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},VLe=class extends l9{constructor(e,t){super(e,t),this._deletedCalls=[]}get calls(){return e4.difference(this._tsObject.calls,this._deletedCalls)}updateSkypeToken(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSetup(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCall(e,t,n){return this._tsObject.calls.find((t=>t.callId===e))}createDownloader(e,t,n,r,i){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCall(e,t,n,r,i){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCallWithGroupId(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCallWithMeetingData(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}deleteCall(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}async deleteCallAsync(e,t,n){return this._proxyReferenceManager.isRemoteStackActive()?await this._tsObject.deleteCallAsync?.apply(this._tsObject,arguments)??!1:!(!e||!this._tsObject.calls.includes(e))&&(this._deletedCalls.push(e),this._eventEmitter.emit(`on_callRemoved`,e),!0)}enableWindowUninitEventHandler(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}disableWindowUninitEventHandler(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},HLe=class extends l9{constructor(e,t){super(e,t)}getPermissionState(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}selectDevices(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSelectedDevices(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createPreview(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createPreviewRenderer(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createScreenSharingPreviewRenderer(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setBackgroundImageAsync(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getImagePropertyAsync(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}transformImageAsync(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendMessageDeviceVideoEffectsAsync(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendMessageDeviceVideoExtensibilityAsync(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setVideoCaptureConfigAsync(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}captureVideoFrameWithoutEffectsAsync(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getRawDeviceMediaStream(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setRawMediaStream(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}unsetRawMediaStream(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createAudioRenderer(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getPersonalizedNoiseSuppression(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setAudioProcessingFlags(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},ULe=class extends l9{constructor(e,t){super(e,t)}getPlatformSupportLevel(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setPlatformCallConstraints(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCompositor(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCallRegistry(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}cancelOperation(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDeviceManager(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createDeviceManager(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getScreenSharingManager(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSetup(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getEcsProvider(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCallFeedback(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getAiMdp(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getVersion(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getMediaStatus(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getVideoCapabilityLimits(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}fireIntent(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setAllowPrivacySensitiveApis(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getLiveStreamClient(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getUmsStream(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createVoipCallCoordinator(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDebugDump(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createAiCameraManager(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},u9=class e extends LLe{constructor(e){super(),this._logger=e.createChild(`TsProxyReferenceManager`),this._mmrRdpConnectionManager=new bIe(this._logger),this._mmrRdpConnectionManager.on(`stateChange`,(e=>{e==`disconnected`&&this._remoteStackTerminated(`MMR RDP connection disconnected`)}))}static create(t){let n=new e(t);return this.proxyReferenceManagers.add(n),n}static notifyRemoteStackTermination(e){this.proxyReferenceManagers.forEach((t=>{t._remoteStackTerminated(e)}))}dispose(){this._mmrRdpConnectionManager.dispose(),e.proxyReferenceManagers.delete(this),super.dispose()}_remoteStackTerminated(e){!1!==this._isRemoteStackActive&&(this._logger.warn(`remote stack is terminated: ${e}`),this._isRemoteStackActive=!1,this._eventEmitter.emit(`remoteStackTerminated`))}_createProxy(e){let t=VOe(e);if(t!==H6.None){if(t===H6.ICall)return c9(e,new RLe(this,e),this);if(t===H6.ICallParticipant)return c9(e,new zLe(this,e),this);if(t===H6.ICallParticipantStream)return c9(e,new BLe(this,e),this);if(t===H6.ICallRegistry)return c9(e,new VLe(this,e),this);if(t===H6.IPluginlessCallingStack)return c9(e,new ULe(this,e),this);if(t===H6.IDeviceManager)return c9(e,new HLe(this,e),this)}}isSupportedType(e){return VOe(e)!==H6.None}isRemoteStackActive(){return!!this._isRemoteStackActive}};u9.proxyReferenceManagers=new Set,W5.monitor.onConnectionTerminated((()=>{u9.notifyRemoteStackTermination(`Disconnection detected by monitor`)}));var WLe=class{constructor(){this._eventEmitter=new E3.EventEmitter,this._shellTrouter=new W5.ShellTrouter,this._state=s9.TrouterState.Unknown,this._registeredState=!1,this._disposeAsync=[]}async initialize(){let e=(e,t)=>{this._state=e,this._eventEmitter.emit(`stateChanged`,e,t)},t=e=>{this._registeredState=e,this._eventEmitter.emit(`registeredChanged`,e)};await this._shellTrouter.onStateChanged(e),await this._shellTrouter.onRegisteredStateChanged(t),this._disposeAsync.push((async()=>{await this._shellTrouter.offStateChanged(e),await this._shellTrouter.offRegisteredStateChanged(t)}))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}async dispose(){for(let e of this._disposeAsync)await e().catch((e=>{}));this._eventEmitter.removeAllListeners()}state(){return this._state}registeredState(){return this._registeredState}get instance(){return this._shellTrouter}},GLe,d9={},f9={};function KLe(){if(GLe)return f9;GLe=1,Object.defineProperty(f9,"__esModule",{value:!0});var e=B5();return f9.default=function(){function t(){this._isAllowed=!1}return t.prototype.putBackgroundFetchAllowed=function(e){if(this._isAllowed=e,this.isBackgroundFetchAllowed()&&this._isAllowedDeferral){var t=this._isAllowedDeferral;this._isAllowedDeferral=void 0,t.resolve(void 0)}},t.prototype.isBackgroundFetchAllowed=function(){return this._isAllowed},t.prototype.waitForBackgroundFetchAllowed=function(){return this.isBackgroundFetchAllowed()?e.Resolved():(this._isAllowedDeferral||=e.Defer(),this._isAllowedDeferral.promise())},t}(),f9}var qLe,p9={};function JLe(){if(qLe)return p9;qLe=1,Object.defineProperty(p9,"__esModule",{value:!0});var e=B5();return p9.default=function(){function t(){this._isActive=!1}return t.prototype.putAppActive=function(e){if(this._isActive=e,this.isAppActive()&&this._appActiveDeferral){var t=this._appActiveDeferral;this._appActiveDeferral=void 0,t.resolve(void 0)}},t.prototype.isAppActive=function(){return this._isActive},t.prototype.waitForAppActive=function(){return this.isAppActive()?e.Resolved():(this._appActiveDeferral||=e.Defer(),this._appActiveDeferral.promise())},t}(),p9}var YLe,XLe,m9={},ZLe=function(){function e(e,t){this._event=e,this._callback=t}return e.prototype.unsubscribe=function(){this._event.unsubscribe(this._callback)},e}(),QLe=function(){function e(e){e===void 0&&(e=!1);var t=this;this._allowStopPropagation=e,this.fire=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];for(var r=t._subscribers,i=r.length-1;i>=0;i--){var a=r[i].apply(null,e);if(t._allowStopPropagation&&a)return!0}return!1},this._subscribers=[]}return e.prototype.dispose=function(){this._subscribers=[]},e.prototype.subscribe=function(e){return this._subscribers=this._subscribers.concat(e),new ZLe(this,e)},e.prototype.unsubscribe=function(e){this._subscribers=this._subscribers.filter((function(t){return t!==e}))},e}(),h9=$le(Object.freeze({__proto__:null,SubscriptionToken:ZLe,default:QLe})),$Le={};function g9(){return YLe||(YLe=1,e=$Le,Object.defineProperty(e,"__esModule",{value:!0}),(t=e.EcsConfigType||={})[t.Default=0]=`Default`,t[t.User=1]=`User`),$Le;var e,t}function eRe(){if(XLe)return m9;XLe=1,Object.defineProperty(m9,"__esModule",{value:!0});var e=h9,t=B5(),n=g9();return m9.default=function(){function r(t){this._config=t,this.configUpdated=new e.default,this._cachedConfigs={}}return r.prototype.initialize=function(){return this.updateConfigsToFetch()},r.prototype.updateConfigsToFetch=function(){var e=this,n=this._config.getConfig(),r=n.databaseInterface,i=n.configsToFetch;if(!r)return t.Resolved();for(var a=[],o=function(n){if(s._cachedConfigs[n])return`continue`;a.push(r.getData(n).then((function(t){t&&(e._cachedConfigs[n]=t)})).catch((function(){return t.Resolved()})))},s=this,c=0,l=i;c<l.length;c++)o(l[c]);return t.all(a).then((function(){a.length>0&&e.configUpdated.fire()}))},r.prototype.getEcsConfig=function(){return this._cachedConfigs[n.EcsConfigType.User]||this._cachedConfigs[n.EcsConfigType.Default]},r.prototype.getEcsConfigByType=function(e){return this._cachedConfigs[e]},r.prototype.putConfig=function(e){var n=this.getEcsConfig();this._cachedConfigs[e.configType]=e;var r=this.getEcsConfig();(r&&r.configType===e.configType||n&&r&&n.configType!==r.configType)&&this.configUpdated.fire();var i=this._config.getConfig().databaseInterface;return i?i.putData(e.configType,e):t.Resolved()},r}(),m9}var tRe,_9={};function nRe(){if(tRe)return _9;tRe=1;var e=_9&&_9.__assign||function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.apply(this,arguments)};return Object.defineProperty(_9,"__esModule",{value:!0}),_9.default=function(){function t(){}return t.prototype.initialize=function(e){if(this._config)throw Error(`ECS Configuration already initialized`);this._config=e},t.prototype.getConfig=function(){if(!this._config)throw Error(`ECS Configuration not yet initialized`);return this._config},t.prototype.setConfigsToFetch=function(t){if(!this._config)throw Error(`ECS Configuration not yet initialized`);this._config=e(e({},this._config),{configsToFetch:t})},t.prototype.setFetchTimeout=function(t){if(!this._config)throw Error(`ECS Configuration not yet initialized`);this._config=e(e({},this._config),{fetchTimeout:t})},t}(),_9}var rRe,iRe,v9={},y9={},aRe={},oRe={},b9={};function x9(){return rRe||(rRe=1,e=b9,t=b9&&b9.__assign||function(){return t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},t.apply(this,arguments)},Object.defineProperty(e,"__esModule",{value:!0}),e.assert=function(e,t){if(!e)throw Error(t)},e.isObject=function(e){return typeof e==`object`&&!!e},e.isString=function(e){return typeof e==`string`},e.attempt=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];try{return e.apply(void 0,t)}catch(e){return Error(e)}},e.remove=function(e,t){for(var n=e.length-1;n>=0;n--)e[n]===t&&e.splice(n,1)},e.clone=function(n){return Array.isArray(n)?n.map(e.clone):e.isObject(n)?Object.keys(n).reduce((function(r,i){var a;return t(t({},r),((a={})[i]=e.clone(n[i]),a))}),{}):n}),b9;var e,t}function sRe(){return iRe||(iRe=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=x9();e.DEFAULT_TIME_GROW_FACTOR=2.718281828459045,e.DEFAULT_TIME_JITTER=.11962656472,e.ExponentialTime=function(){function n(n,r,i,a){i===void 0&&(i=e.DEFAULT_TIME_GROW_FACTOR),a===void 0&&(a=e.DEFAULT_TIME_JITTER),this._initialTime=n,this._maxTime=r,this._growFactor=i,this._jitterFactor=a,t.assert(this._initialTime>0,`Initial delay must be positive`),t.assert(this._maxTime>0,`Delay upper bound must be positive`),t.assert(this._growFactor>=0,`Ratio must be non-negative`),t.assert(this._jitterFactor>=0,`Jitter factor must be non-negative`),this.reset()}return n.prototype.reset=function(){this._incrementCount=0,this._currentTime=Math.round(this._initialTime*(1+Math.random()*this._jitterFactor))},n.prototype.getTime=function(){return this._currentTime},n.prototype.getIncrementCount=function(){return this._incrementCount},n.prototype.calculateNext=function(){var e=this._currentTime*this._growFactor;return e>this._maxTime&&(e=this._maxTime),this._jitterFactor<1e-5?this._currentTime=e:this._currentTime=Math.round(Math.random()*e*this._jitterFactor+e),this._currentTime<this._initialTime&&(this._currentTime=this._initialTime),this._currentTime>this._maxTime&&(this._currentTime=this._maxTime),this._incrementCount++,this._currentTime},n.prototype.getTimeAndCalculateNext=function(){var e=this.getTime();return this.calculateNext(),e},n}()}(oRe)),oRe}var cRe,lRe,uRe,dRe,fRe,S9={},C9={};function pRe(){return cRe||(cRe=1,function(e){var t,n=C9&&C9.__extends||(t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},t(e,n)},function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}),r=C9&&C9.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var i,a,o=B5(),s=x9(),c=sRe();function l(e){return!!e&&e.indexOf(`application/json`)===0}function u(e){return!!e&&e.indexOf(`application/x-www-form-urlencoded`)===0}function d(e){return!!e&&e.indexOf(`multipart/form-data`)===0}function f(e,t){return t.canceled||!t.statusCode||t.statusCode>=400&&t.statusCode<600?a.DoNotRetry:a.RetryCountedWithBackoff}(function(e){e[e.DontCare=0]=`DontCare`,e[e.Low=1]=`Low`,e[e.Normal=2]=`Normal`,e[e.High=3]=`High`,e[e.Critical=4]=`Critical`})(i=e.WebRequestPriority||={}),function(e){e[e.DoNotRetry=0]=`DoNotRetry`,e[e.RetryUncountedImmediately=1]=`RetryUncountedImmediately`,e[e.RetryUncountedWithBackoff=2]=`RetryUncountedWithBackoff`,e[e.RetryCountedWithBackoff=3]=`RetryCountedWithBackoff`,e[e.PauseUntilResumed=4]=`PauseUntilResumed`}(a=e.ErrorHandlingType||={}),e.DefaultOptions={priority:i.Normal},e.SimpleWebRequestOptions={MaxSimultaneousRequests:5,HungRequestCleanupIntervalMs:1e4,setTimeout:function(e,t){return setTimeout(e,t)},clearTimeout:function(e){return clearTimeout(e)}},e.DefaultErrorHandler=f;var p,m=[],h=[],g=[],_=0,v=0,y=function(){function t(t,n,i,a,o){this._action=t,this._url=n,this.options=i,this._getHeaders=a,this._blockRequestUntil=o,this._aborted=!1,this._timedOut=!1,this._paused=!1,this._created=Date.now(),this._finishHandled=!1,this._retryExponentialTime=new c.ExponentialTime(1e3,3e5),this._options=r(r({},e.DefaultOptions),i)}return t.prototype.getPriority=function(){return this._options.priority||i.DontCare},t.checkQueueProcessing=function(){for(var t=function(){var t=m.shift();h.push(t),(t._blockRequestUntil&&t._blockRequestUntil()||o.Resolved()).finally((function(){s.remove(h,t)})).then((function(){g.length<e.SimpleWebRequestOptions.MaxSimultaneousRequests&&!t._aborted?(g.push(t),b._scheduleHungRequestCleanupIfNeeded(),t._fire()):t._enqueue()}),(function(e){t._respond(`_blockRequestUntil rejected: `+e)}))};m.length>0&&g.length<e.SimpleWebRequestOptions.MaxSimultaneousRequests;)t()},t._scheduleHungRequestCleanupIfNeeded=function(){g.length>0&&p===void 0?p=e.SimpleWebRequestOptions.setTimeout(this._hungRequestCleanupTimerCallback,e.SimpleWebRequestOptions.HungRequestCleanupIntervalMs):g.length===0&&p&&(e.SimpleWebRequestOptions.clearTimeout(p),p=void 0)},t.prototype._removeFromQueue=function(){s.remove(g,this),s.remove(m,this)},t.prototype._assertAndClean=function(e,t){e||(this._removeFromQueue(),console.error(t),s.assert(e,t))},t.prototype._fire=function(){var n=this;this._xhr=new XMLHttpRequest,this._xhrRequestHeaders={};var r=s.attempt((function(){n._xhr.open(n._action,n._url,!0)}));if(r)this._respond(r.toString());else{if(this._options.timeout){var i=v;i!==3&&(this._assertAndClean(!this._requestTimeoutTimer,`Double-fired requestTimeoutTimer`),this._requestTimeoutTimer=e.SimpleWebRequestOptions.setTimeout((function(){n._requestTimeoutTimer=void 0,n._timedOut=!0,n.abort()}),this._options.timeout)),(i===3||i<=1)&&(this._xhr.timeout=this._options.timeout,this._xhr.ontimeout=function(){v=3,i===3&&(n._timedOut=!0,n._aborted=!0,n._respond(`TimedOut`))})}var a=_;a===3?this._options.streamingDownloadProgress&&(this._xhr.onreadystatechange=function(){n._xhr&&n._xhr.readyState===3&&n._options.streamingDownloadProgress&&!n._aborted&&n._options.streamingDownloadProgress(n._xhr.responseText)}):(a===0&&(_=1),this._xhr.onreadystatechange=function(){n._xhr&&(n._xhr.readyState!==3||!n._options.streamingDownloadProgress||n._aborted?n._xhr.readyState===4&&(a===0&&_===1&&e.SimpleWebRequestOptions.setTimeout((function(){_!==3&&(_=2)}),1e4),n._respond()):n._options.streamingDownloadProgress(n._xhr.responseText))}),a!==2&&(this._xhr.onload=function(){_=3,a===3&&n._respond()},this._xhr.onerror=function(){_=3,a===3&&n._respond()}),this._xhr.onabort=function(){n._aborted=!0,n._respond(`Aborted`)},this._xhr.upload&&this._options.onProgress&&(this._xhr.upload.onprogress=this._options.onProgress);var o=this._options.acceptType||`json`,c=this._options.customResponseType||t._getResponseType(o),l=s.attempt((function(){n._xhr.responseType=c}));if(l&&c!==`json`)throw l;b._setRequestHeader(this._xhr,this._xhrRequestHeaders,`Accept`,t.mapContentType(o)),this._xhr.withCredentials=!!this._options.withCredentials;var u=this.getRequestHeaders(),d={};if(Object.keys(u).forEach((function(e){var t=u[e],r=e.toLowerCase();r===`content-type`?n._assertAndClean(!1,`Don't set Content-Type with options.headers -- use it with the options.contentType property`):r===`accept`?n._assertAndClean(!1,`Don't set Accept with options.headers -- use it with the options.acceptType property`):(n._assertAndClean(!d[r],`Setting duplicate header key: `+d[r]+` and `+e),t==null?console.warn(`Tried to set header "`+e+`" on request with "`+t+`" value, header will be dropped`):(d[r]=!0,b._setRequestHeader(n._xhr,n._xhrRequestHeaders,e,t)))})),this._options.sendData){var f=t.mapContentType(this._options.contentType||`json`);b._setRequestHeader(this._xhr,this._xhrRequestHeaders,`Content-Type`,f);var p=t.mapBody(this._options.sendData,f);this._xhr.send(p)}else this._xhr.send()}},t._setRequestHeader=function(e,t,n,r){e.setRequestHeader(n,r),t[n]=r},t.mapContentType=function(e){return e===`json`?`application/json`:e===`form`?`application/x-www-form-urlencoded`:e},t.mapBody=function(e,t){if(l(t)){if(!s.isString(e))return JSON.stringify(e)}else if(u(t)){if(!s.isString(e)&&s.isObject(e)){var n=e;return Object.keys(n).map((function(e){return encodeURIComponent(e)+(n[e]?`=`+encodeURIComponent(n[e].toString()):``)})).join(`&`)}}else if(d(t)){if(s.isObject(e)){var r=new FormData,i=e;return Object.keys(i).forEach((function(e){return r.append(e,i[e])})),r}s.assert(!1,`contentType multipart/form-data must include an object as sendData`)}return e},t.prototype.setUrl=function(e){this._url=e},t.prototype.setHeader=function(e,t){this._options.augmentHeaders||(this._options.augmentHeaders={}),t?this._options.augmentHeaders[e]=t:delete this._options.augmentHeaders[e]},t.prototype.getRequestHeaders=function(){var e={};return!this._getHeaders||this._options.overrideGetHeaders||this._options.headers||(e=r(r({},e),this._getHeaders())),this._options.overrideGetHeaders&&(e=r(r({},e),this._options.overrideGetHeaders)),this._options.headers&&(e=r(r({},e),this._options.headers)),this._options.augmentHeaders&&(e=r(r({},e),this._options.augmentHeaders)),e},t.prototype.getOptions=function(){return s.clone(this._options)},t.prototype.setPriority=function(e){this._options.priority!==e&&(this._options.priority=e,this._paused||this._xhr||(s.remove(m,this),this._enqueue()))},t.prototype.resumeRetrying=function(){this._paused?(this._paused=!1,this._enqueue()):s.assert(!1,`resumeRetrying() called but not paused!`)},t.prototype._enqueue=function(){var e=this;if(!this._aborted&&!(g.indexOf(this)>=0||h.indexOf(this)>=0||m.indexOf(this)>=0)){var n=m.findIndex((function(t){return t.getPriority()===e.getPriority()&&t._created>e._created||t.getPriority()<e.getPriority()}));n>-1?m.splice(n,0,this):m.push(this),t.checkQueueProcessing()}},t._getResponseType=function(e){return e===`blob`?`arraybuffer`:e===`text/xml`||e===`application/xml`?`document`:e===`text/plain`?`text`:`json`},t._hungRequestCleanupTimerCallback=function(){p=void 0,g.filter((function(e){return!(!e._xhr||e._xhr.readyState!==4)&&(console.warn(`SimpleWebRequests found a completed XHR that hasn't invoked it's callback functions, manually responding`),!0)})).forEach((function(e){e._respond()})),b._scheduleHungRequestCleanupIfNeeded()},t}();e.SimpleWebRequestBase=y;var b=function(t){function r(e,n,r,i,a){return t.call(this,e,n,r,i,a)||this}return n(r,t),r.prototype.abort=function(){this._aborted?s.assert(!1,`Already aborted `+this._action+` request to `+this._url):(this._aborted=!0,this._retryTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._retryTimer),void 0),this._requestTimeoutTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),void 0),this._deferred?(this._respond(`Aborted`),this._xhr&&this._xhr.abort()):s.assert(!1,`Haven't even fired start() yet -- can't abort`))},r.prototype.start=function(){var e=this;return this._deferred?(s.assert(!1,`WebRequest already started`),o.Rejected(`WebRequest already started`)):(this._deferred=o.Defer(),this._deferred.onCancel((function(){e.abort()})),this._enqueue(),this._deferred.promise())},r.prototype._respond=function(t){var n=this;if(!this._finishHandled){this._finishHandled=!0,this._removeFromQueue(),this._retryTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._retryTimer),void 0),this._requestTimeoutTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),void 0);var r,i=0;if(this._xhr)try{i=this._xhr.status,r=this._xhr.statusText||t}catch{}else r=t||`Browser Error - Possible CORS or Connectivity Issue`;var o,c,u={};if(this._xhr){if((this._xhr.getAllResponseHeaders()||``).split(/\r?\n/).forEach((function(e){if(e.length!==0){var t=e.indexOf(`:`);t===-1?u[e]=``:u[e.substr(0,t).toLowerCase()]=e.substr(t+1).trim()}})),!u[`content-type`]){var d=this._xhr.getResponseHeader(`content-type`);d&&(u[`content-type`]=d)}if(o=this._xhr.response,u[`content-type`]&&l(u[`content-type`])&&(!o||!s.isObject(o))&&(this._xhr.responseType===`text`||this._xhr.responseType===``)&&this._xhr.responseText)try{o=JSON.parse(this._xhr.responseText)}catch(e){c=e,console.warn(`Failed to parse XHR JSON response`)}}if(this._xhr&&this._xhr.readyState===4&&(i>=200&&i<300||i===304)){var p={url:this._xhr.responseURL||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:i,statusText:r,headers:u,body:o,responseParsingException:c};this._deferred.resolve(p)}else{var m={url:(this._xhr?this._xhr.responseURL:void 0)||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:i,statusText:r,headers:u,body:o,canceled:this._aborted,timedOut:this._timedOut,responseParsingException:c};this._options.augmentErrorResponse&&this._options.augmentErrorResponse(m);var h=this._options.customErrorHandler?this._options.customErrorHandler(this,m):f(this,m);h!==a.DoNotRetry&&(this._options.retries&&this._options.retries>0||h===a.PauseUntilResumed||h===a.RetryUncountedImmediately||h===a.RetryUncountedWithBackoff)?(h===a.RetryCountedWithBackoff&&this._options.retries--,this._requestTimeoutTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),void 0),this._aborted=!1,this._timedOut=!1,this._finishHandled=!1,this._xhr&&(this._xhr.onabort=null,this._xhr.onerror=null,this._xhr.onload=null,this._xhr.onprogress=null,this._xhr.onreadystatechange=null,this._xhr.ontimeout=null,this._xhr=void 0,this._xhrRequestHeaders=void 0),h===a.PauseUntilResumed?this._paused=!0:h===a.RetryUncountedImmediately?this._enqueue():this._retryTimer=e.SimpleWebRequestOptions.setTimeout((function(){n._retryTimer=void 0,n._enqueue()}),this._retryExponentialTime.getTimeAndCalculateNext())):this._deferred.reject(m)}y.checkQueueProcessing()}},r}(y);e.SimpleWebRequest=b}(C9)),C9}function mRe(){if(lRe)return S9;lRe=1;var e=S9&&S9.__assign||function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.apply(this,arguments)};Object.defineProperty(S9,"__esModule",{value:!0});var t=x9(),n=pRe();return S9.GenericRestClient=function(){function r(e){this._defaultOptions={excludeEndpointUrl:!1,withCredentials:!1,retries:0},this._endpointUrl=e}return r.prototype._performApiCall=function(r,i,a,o){var s=this;o===void 0&&(o={});var c=e(e({},this._defaultOptions),o);a&&(c.sendData=a),c.eTag&&(c.augmentHeaders||={},c.augmentHeaders[`If-None-Match`]=c.eTag),c.contentType||=t.isString(c.sendData)?`form`:`json`;var l=c.excludeEndpointUrl?r:this._endpointUrl+r;return new n.SimpleWebRequest(i,l,c,(function(){return s._getHeaders(c)}),(function(){return s._blockRequestUntil(c)})).start().then((function(e){return s._processSuccessResponse(e),e}))},r.prototype._getHeaders=function(e){return{}},r.prototype._blockRequestUntil=function(e){},r.prototype._processSuccessResponse=function(e){},r.prototype.performApiGet=function(e,t){return this.performApiGetDetailed(e,t).then((function(e){return e.body}))},r.prototype.performApiGetDetailed=function(e,t){return this._performApiCall(e,`GET`,void 0,t)},r.prototype.performApiPost=function(e,t,n){return this.performApiPostDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiPostDetailed=function(e,t,n){return this._performApiCall(e,`POST`,t,n)},r.prototype.performApiPatch=function(e,t,n){return this.performApiPatchDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiPatchDetailed=function(e,t,n){return this._performApiCall(e,`PATCH`,t,n)},r.prototype.performApiPut=function(e,t,n){return this.performApiPutDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiPutDetailed=function(e,t,n){return this._performApiCall(e,`PUT`,t,n)},r.prototype.performApiDelete=function(e,t,n){return this.performApiDeleteDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiDeleteDetailed=function(e,t,n){return this._performApiCall(e,`DELETE`,t,n)},r}(),S9}function hRe(){return uRe||(uRe=1,function(e){function t(t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}Object.defineProperty(e,"__esModule",{value:!0}),t(sRe()),t(mRe()),t(pRe())}(aRe)),aRe}function gRe(){return fRe?dRe:(fRe=1,dRe=hRe())}var _Re,vRe,yRe,bRe,w9={},T9={};function xRe(){return _Re?T9:(_Re=1,Object.defineProperty(T9,"__esModule",{value:!0}),T9.TelemetryEventBase=function(){function e(){}return e.prototype.getAttributes=function(){return{Source:`ecs_client`}},e}(),T9)}function SRe(){if(vRe)return w9;vRe=1;var e,t=w9&&w9.__extends||(e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)},function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)});return Object.defineProperty(w9,"__esModule",{value:!0}),w9.EcsConfigFetchResponse=function(e){function n(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){var v=e.call(this)||this;return v._responseTime=t,v._responseCode=n,v._fetchAttempts=r,v._hasValidToken=i,v._serverEndpoint=a,v._fetchDurationValid=o,v._cacheAvailable=s,v._responseSize=c,v._configAge=l,v._configExpired=u,v._fetchStart=d,v._fetchEnd=f,v._isUserConfig=p,v._etag=m,v._timedOut=h,v._responseParsingException=g,v._errorMessage=_,v}return t(n,e),n.prototype.getEventName=function(){return`ecs_tsclient_fetch_config`},n.prototype.getAttributes=function(){var t=e.prototype.getAttributes.call(this);return t.fetch_delay_ms=this._responseTime,t.fetch_response_code=this._responseCode,t.fetch_attempts=this._fetchAttempts,t.authenticated_user=this._hasValidToken,t.url=this._serverEndpoint,t.fetch_duration_valid=this._fetchDurationValid,t.cache_available=this._cacheAvailable,t.response_size=this._responseSize,t.config_age=this._configAge,t.config_expired=this._configExpired,t.fetch_start=this._fetchStart,t.fetch_end=this._fetchEnd,t.is_user_config=this._isUserConfig,this._etag&&(t.fetched_etag=this._etag),this._timedOut!==void 0&&(t.fetch_timed_out=this._timedOut),this._responseParsingException&&(t.fetch_response_parsing_error=this._responseParsingException.message),this._errorMessage&&(t.fetch_error_message=this._errorMessage),t},n}(xRe().TelemetryEventBase),w9}function CRe(){if(yRe)return y9;yRe=1;var e,t=y9&&y9.__extends||(e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)},function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}),n=y9&&y9.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)};Object.defineProperty(y9,"__esModule",{value:!0});var r,i,a=gRe(),o=B5(),s=g9(),c=SRe(),l=1728e5,u=18e5,d=31536e6,f=3e4,p=function(e){function n(t,n,r,i,a,o,s,c){var l=e.call(this,t)||this;l._config=n,l._skypeTokenData=r,l._appActiveData=i,l._allowBackgroundFetchData=a,l._etag=o,l._getUserConfig=s;var u=l._config.getConfig();if(l._apiPath=u.clientTeam?`/config/v1/`+u.clientName+`/`+u.clientVersion+`/`+u.clientTeam:`/config/v1/`+u.clientName+`/`+u.clientVersion,c){var d=Object.keys(c).map((function(e){return encodeURIComponent(e)+`=`+encodeURIComponent(c[e].toString())}));d&&(l._apiPath+=`?`+d.join(`&`))}return l}return t(n,e),n.prototype._blockRequestUntil=function(e){var t=this;if(this._getUserConfig&&!this._skypeTokenData.isSkypeTokenValid()&&console.log(`ECS - Delaying User config fetch until we have a valid SkypeToken`),!this._appActiveData.isAppActive()&&!this._allowBackgroundFetchData.isBackgroundFetchAllowed()){var n=this._getUserConfig?`User config`:`config`;console.log(`ECS - Delaying `+n+` fetch until the app is active (or background fetch is allowed)`)}return o.race([this._appActiveData.waitForAppActive(),this._allowBackgroundFetchData.waitForBackgroundFetchAllowed()]).then((function(){if(t._getUserConfig)return t._skypeTokenData.waitForValidSkypeToken()})).then((function(){i=Date.now()}))},n.prototype._getHeaders=function(){var e={};return this._etag&&(e[`If-None-Match`]=this._etag),this._getUserConfig&&(e.Authorization=this._skypeTokenData.getSkypeToken()),e},n.prototype.getConfig=function(){var t=this._config.getConfig().fetchTimeout;return t!==void 0&&(t<0?t=0:t>0&&t<f&&(t=f)),e.prototype.performApiGetDetailed.call(this,this._apiPath,{timeout:t})},n}(a.GenericRestClient);return y9.default=function(){function e(e,t,n,r,i){this._config=e,this._skypeTokenData=t,this._appActiveData=n,this._allowBackgroundFetchData=r,this._telemetryManager=i,this._ecsFailureBackoffTimer=new a.ExponentialTime(1e3,3e5),this._cacheMaxAgeRegex=/.*max-age=(\d+).*/gi,this._serverIndex=NaN}return e.prototype.getConfig=function(e,t,r){var a=this,l=this._config.getConfig().hosts;if((isNaN(this._serverIndex)||this._serverIndex>l.length-1)&&(this._serverIndex=Math.floor(Math.random()*l.length)),!l||!l.length)return o.Rejected(Error(`no configuration service endpoint`));var u=o.Defer(),d=0,f=function(){var m=e&&e.eTag?e.eTag:void 0,h=new p(l[a._serverIndex],a._config,a._skypeTokenData,a._appActiveData,a._allowBackgroundFetchData,m,t,r);d++,h.getConfig().then((function(r){var f=r.headers.etag,p=r.headers.expires;r.body&&r.body.Headers&&(f||=r.body.Headers.ETag,p||=r.body.Headers.Expires);var h=a._calculateResponseTimeInfo(e);if(!f||!p)return console.warn(`ECS - Service returned an empty ETag or Expiration header: `+JSON.stringify(r)),o.Rejected({timedOut:!1,responseParsingException:Error(`ECS Service returned empty ETag or Expiration header`),responseCode:r.statusCode});var g,_=new Date(a._calculateExpirationDate(r.headers)).getTime();if(r.statusCode===304&&e)(g=n({},e)).configType=t?s.EcsConfigType.User:s.EcsConfigType.Default,g.eTag=f,g.expiration=_,g.cacheUpdateTime=h.lastResponseTime,g.lastFetchTokenHash=a._skypeTokenData.getSkypeTokenHash(r.requestHeaders.Authorization);else{if(typeof r.body!=`object`)return console.warn(`ECS - Service returned invalid response `+JSON.stringify(r)),o.Rejected({timedOut:!1,responseParsingException:Error(`ECS Service returned invalid response body`),responseCode:r.statusCode});g={config:r.body,configType:t?s.EcsConfigType.User:s.EcsConfigType.Default,eTag:f,expiration:_,cacheUpdateTime:i,lastFetchTokenHash:a._skypeTokenData.getSkypeTokenHash(r.requestHeaders.Authorization),appVersion:a._config.getConfig().clientVersion}}a._telemetryManager.sendTelemetryEvent(new c.EcsConfigFetchResponse(h.fetchDelayMs,r.statusCode,d,a._skypeTokenData.isSkypeTokenValid(),l[a._serverIndex],h.fetchDurationValid,!!m,JSON.stringify(r).length,h.cacheAge,!(e&&e.expiration-Date.now()>0),i,h.lastResponseTime,t,f)),a._ecsFailureBackoffTimer.reset(),u.resolve(g)})).catch((function(n){var r={timedOut:n&&n.timedOut||!1,responseParseError:n&&n.responseParsingException,responseCode:n&&n.statusCode||0,message:a._getErrorMessage(n)};console.error(`ECS - Service request failed to return a response (timedOut: `+r.timedOut+`, responseParseError: `+r.responseParseError+`)`);var o=a._calculateResponseTimeInfo(e);a._telemetryManager.sendTelemetryEvent(new c.EcsConfigFetchResponse(o.fetchDelayMs,r.responseCode,d,a._skypeTokenData.isSkypeTokenValid(),l[a._serverIndex],o.fetchDurationValid,!!m,0,o.cacheAge,!(e&&e.expiration-Date.now()>0),i,o.lastResponseTime,t,void 0,r.timedOut,r.responseParseError,r.message));var s=a._config.getConfig().fetchAttemptMax;s&&d>s||setTimeout((function(){f()}),a._ecsFailureBackoffTimer.getTimeAndCalculateNext())}))};return f(),u.promise()},e.prototype._calculateExpirationDate=function(e){var t=Date.now()+l;if(e.date&&e.expires){var n=new Date(e.date).getTime(),r=Date.now()-n,i=new Date(e.expires).getTime();return isNaN(i)?t:Math.min(t,i+r)}var a=this._cacheMaxAgeRegex.exec(e[`cache-control`]);return this._cacheMaxAgeRegex.lastIndex=0,a&&a.length===2?Math.min(t,Date.now()+1e3*Number(a[1])):Date.now()+u},e.prototype._calculateResponseTimeInfo=function(e){var t=(r=Date.now())-i;return{lastResponseTime:r,fetchDelayMs:t,fetchDurationValid:!(t<0||t>d),cacheAge:e?r-e.cacheUpdateTime:0}},e.prototype._getErrorMessage=function(e){if(e)return typeof e==`string`?e:typeof e==`object`&&(e.statusText||e.message)?e.statusText||e.message:void 0},e}(),y9}function wRe(){if(bRe)return v9;bRe=1,Object.defineProperty(v9,"__esModule",{value:!0});var e=g9(),t=CRe();return v9.default=function(){function n(n,r,i,a,o,s){var c=this;this._config=n,this._skypeTokenData=r,this._cache=i,this._isFetchingSettings={},this._pendingFetch={},this._pendingTimers={},this._subscriptionToken=null,this._paused=!1,this._fetchEcsSettingsIfNeeded=function(t){var n=c._config.getConfig(),r=c._cache.getEcsConfigByType(t);if(n.configsToFetch.indexOf(t)!==-1&&!c._isFetchingSettings[t])if(r||!c._pendingFetch[t]){var i=r?r.expiration-Date.now():-1;i<=0||r&&t===e.EcsConfigType.User&&c._skypeTokenData.isSkypeTokenValid()&&r.lastFetchTokenHash!==c._skypeTokenData.getSkypeTokenHash(c._skypeTokenData.getSkypeToken())?c._fetchSkypeEcsSettings(t):n.Killswitches?.isSkypeTokenDataLeakFixEnabled?(c._pendingTimers[t]>0&&clearTimeout(c._pendingTimers[t]),c._pendingTimers[t]=window.setTimeout((function(){return c._fetchEcsSettingsIfNeeded(t)}),i)):window.setTimeout((function(){return c._fetchEcsSettingsIfNeeded(t)}),i)}else c._fetchSkypeEcsSettings(t)},this._fetchSkypeEcsSettings=function(t,n){n===void 0&&(n=!1),c._isFetchingSettings[t]||c._paused&&!n?c._pendingFetch[t]=!0:(c._pendingFetch[t]=!1,c._isFetchingSettings[t]=!0,c._config.getConfig().getEcsParameters().catch((function(){return console.warn(`ECS - Failed to fetch ECS fetching parameters`),{}})).then((function(n){return c._ecsClient.getConfig(c._cache.getEcsConfig(),t===e.EcsConfigType.User,n)})).then((function(e){console.log(`ECS - Config fetch complete`),c._isFetchingSettings[t]=!1,c._cache.putConfig(e),c._fetchEcsSettingsIfNeeded(t)})))},this._ecsClient=new t.default(this._config,this._skypeTokenData,a,o,s)}return n.prototype.initialize=function(){var t=this;this.updateConfigsToFetch(),this._subscriptionToken=this._skypeTokenData.skypeTokenChanged.subscribe((function(){return t._fetchEcsSettingsIfNeeded(e.EcsConfigType.User)}))},n.prototype.dispose=function(){var e,t=this._config.getConfig();if(t.Killswitches?.isSkypeTokenDataLeakFixEnabled){for(var n=0,r=t.configsToFetch;n<r.length;n++){var i=r[n];clearTimeout(this._pendingTimers[i]),this._pendingTimers[i]=0}(e=this._subscriptionToken)==null||e.unsubscribe(),this._subscriptionToken=null,this._skypeTokenData.skypeTokenChanged.dispose()}},n.prototype.updateConfigsToFetch=function(){for(var e=this._config.getConfig(),t=0,n=e.configsToFetch;t<n.length;t++)(a=n[t])in this._isFetchingSettings||(this._isFetchingSettings[a]=!1),a in this._isFetchingSettings||(this._pendingFetch[a]=!1);for(var r=0,i=e.configsToFetch;r<i.length;r++){var a=i[r],o=this._cache.getEcsConfigByType(a);!o||o.appVersion&&o.appVersion!==e.clientVersion?this._fetchSkypeEcsSettings(a,!0):this._fetchEcsSettingsIfNeeded(a)}},n.prototype.requestUpdate=function(){for(var e=0,t=this._config.getConfig().configsToFetch;e<t.length;e++){var n=t[e];this._fetchSkypeEcsSettings(n)}},n.prototype.pause=function(){this._paused=!0},n.prototype.resume=function(){this._paused=!1;for(var e=0,t=this._config.getConfig().configsToFetch;e<t.length;e++){var n=t[e];this._fetchEcsSettingsIfNeeded(n)}},n}(),v9}var TRe,E9={};function ERe(){if(TRe)return E9;TRe=1,Object.defineProperty(E9,"__esModule",{value:!0});var e=h9,t=B5();return E9.default=function(){function n(){this.skypeTokenChanged=new e.default}return n.prototype.putSkypeTokenData=function(e){if(this._data=e,this.isSkypeTokenValid()&&this.skypeTokenChanged.fire(),this.isSkypeTokenValid()&&this._validSkypeTokenDeferral){var t=this._validSkypeTokenDeferral;this._validSkypeTokenDeferral=void 0,t.resolve(void 0)}},n.prototype.isSkypeTokenValid=function(){var e=this._data;return!!e&&!!e.skypeToken&&e.skypeTokenExpiration>Date.now()},n.prototype.getSkypeToken=function(){var e=this._data;if(!e||!e.skypeToken)throw Error(`No Skype Token provided`);return e.skypeToken},n.prototype.getSkypeTokenHash=function(e){return e===void 0?0:e.split(``).reduce((function(e,t){return(101*e+t.charCodeAt(0))%999727999}),e.length)},n.prototype.waitForValidSkypeToken=function(){return this.isSkypeTokenValid()?t.Resolved():(this._validSkypeTokenDeferral||=t.Defer(),this._validSkypeTokenDeferral.promise())},n}(),E9}var DRe,ORe,D9={};function kRe(){if(DRe)return D9;DRe=1,Object.defineProperty(D9,"__esModule",{value:!0});var e=h9;return D9.default=function(){function t(t){this._cache=t,this.telemetryEventAdded=new e.default}return t.prototype.sendTelemetryEvent=function(e){var n=e.getEventName(),r=e.getAttributes(),i=!1,a=this._cache.getEcsConfig();if(a){if(t._containsEcsClientTelemetryConfig(a.config)){var o=a.config.ECSCONFIG;o&&o.ecsClientTelemetry&&(i=!!o.ecsClientTelemetry[n])}}else console.warn(`No previously cached ECS telemetry config exists - fallback to sending event`),i=!0;i&&this.telemetryEventAdded.fire(n,r)},t._containsEcsClientTelemetryConfig=function(e){return!!e&&!!e.ECSCONFIG&&!!e.ECSCONFIG.ecsClientTelemetry},t}(),D9}function ARe(){if(ORe)return d9;ORe=1,Object.defineProperty(d9,"__esModule",{value:!0});var e=KLe(),t=JLe(),n=eRe(),r=nRe();d9.Models=g9();var i=wRe(),a=ERe(),o=kRe();return d9.default=function(){function s(){this._allowBackgroundFetchData=new e.default,this._appActiveData=new t.default,this._config=new r.default,this._cache=new n.default(this._config),this._skypeTokenData=new a.default,this._telemetryManager=new o.default(this._cache),this._scheduler=new i.default(this._config,this._skypeTokenData,this._cache,this._appActiveData,this._allowBackgroundFetchData,this._telemetryManager),this.telemetryEventAdded=this._telemetryManager.telemetryEventAdded,this.configUpdated=this._cache.configUpdated}return s.prototype.initialize=function(e){var t=this;return this._config.initialize(e),this._skypeTokenData.putSkypeTokenData(e.initialSkypeTokenData),this._appActiveData.putAppActive(e.initialAppActiveState),this._cache.initialize().then((function(){t._scheduler.initialize()}))},s.prototype.dispose=function(){var e;(e=this._config.getConfig().Killswitches)!=null&&e.isSkypeTokenDataLeakFixEnabled&&this._scheduler.dispose()},s.prototype.getConfig=function(){return this._cache.getEcsConfig()},s.prototype.getConfigType=function(){var e=this._cache.getEcsConfig();if(e)return e.configType},s.prototype.requestUpdate=function(){this._scheduler.requestUpdate()},s.prototype.pause=function(){this._scheduler.pause()},s.prototype.resume=function(){this._scheduler.resume()},s.prototype.setAllowBackgroundFetch=function(e){this._allowBackgroundFetchData.putBackgroundFetchAllowed(e)},s.prototype.useSkypeToken=function(e,t){this._skypeTokenData.putSkypeTokenData({skypeToken:e,skypeTokenExpiration:t})},s.prototype.setAppActive=function(e){this._appActiveData.putAppActive(e)},s.prototype.setConfigsToFetch=function(e){var t=this;return this._config.setConfigsToFetch(e),this._cache.updateConfigsToFetch().then((function(){t._scheduler.updateConfigsToFetch()}))},s.prototype.setFetchTimeout=function(e){this._config.setFetchTimeout(e)},s}(),d9}var O9,k9=ARe(),jRe=NG(k9),MRe=B5();function NRe(e,t){let n={},r=e.OsName??``,i=e.OsVer??``,a=r&&i?`${r}-${i}`:``;return n.CLRelease=`${e.CLRelease??``}`,n.BrowserName=e4.toLower(`${e.BrowserName??``}`),n.BrowserEngine=`${e.BrowserEngine??``}`,n.BrowserVersion=`${e.BrowserVersion??``}`,n.FormFactor=`${e.FormFactor??``}`,n.IdentityType=t2.Consumer,n.Cloud=X0.Public,n.OSVer=e4.toLower(a),n.BrowserName===`edge`&&(n.BrowserName=`edgeanaheim`),t&&(n.Cloud=t.cloudType,n.IdentityType=t.identityType),e4.omitBy(n,(e=>e==null||e===``))}function PRe(e,t){let n={[X0.Public]:$0.Public_EcsServer_Url,[X0.Dod]:$0.Dod_EcsServer_Url,[X0.GccHigh]:$0.GccHigh_EcsServer_Url,[X0.AirGap08]:$0.AirGap08_EcsServer_Url,[X0.AirGap09]:$0.AirGap09_EcsServer_Url},r=$0.Public_EcsServer_Url;return t&&(r=t.identityType===t2.Enterprise?$0.Enterprise_Ecs_ServerUrl:n[t.cloudType]??$0.Public_EcsServer_Url),e?.proxyfyUrl(r)??r}(function(e){e.Default=`Default`,e.User=`User`})(O9||={});var FRe=class{constructor(e,t,n,r){this._isWBMediaClient=e,this._acsProxy=n,this._sourceTag=r,this._throttlingTimeoutHandle=0,this._eventEmitter=new E3.EventEmitter,this._logger=t.createChild(`EcsClient`)}_resetThrottlingTimeout(){this._throttlingTimeoutHandle&&=(window.clearTimeout(this._throttlingTimeoutHandle),0)}_resetEcsClient(){this._ecsClient&&=(this._ecsClient.configUpdated.dispose(),void 0)}async _fetchConfig(e){this._resetEcsClient(),this._resetThrottlingTimeout();let t=new jRe,n=n3();try{await t.initialize(e);let r=[],i=!1,a=0;t.configUpdated.subscribe((()=>{if(n.isPending())n.resolve();else{r.push(Date.now());let e=t.getConfig();if(e?.config){let t=e?.configType===k9.Models.EcsConfigType.User?O9.User:O9.Default;this._cachedConfig=e,this._eventEmitter.emit(`configUpdated`,{config:e?.config,fetchType:t,sourceTag:this._sourceTag})}let n=Z().ecsClient.throttling;r.length>n.triggerCount&&(r=r.slice(r.length-n.triggerCount));let o=r[r.length-1]-r[0];i?(r.length<n.triggerCount||o>=n.coolDownDuration)&&(i=!1,a=0,r=[],this._resetThrottlingTimeout()):r.length===n.triggerCount&&o<n.triggerDuration&&(i=!0),i&&(a=a===0?n.startingDelay:Math.min(Math.ceil(a*n.delayFactor),n.maxDelay),t.pause(),this._throttlingTimeoutHandle=window.setTimeout((()=>{this._throttlingTimeoutHandle=0,t.resume()}),a))}})),this._ecsClient=t,await i3((()=>n.promise),OCe);let o=t.getConfig();if(!o?.config)throw new Y({defaultError:J.INTERNAL.ECS_CONFIG_EMPTY});return this._cachedConfig=o,o.config}catch(e){throw n.reject(e),this._logger.error(`${e}`),e}}async fetchDefaultConfig(e,t){let n=`${this._isWBMediaClient?l2:c2}_${X2()}`,r={hosts:[PRe(this._acsProxy,t)],clientName:bSe,clientVersion:n,configsToFetch:[k9.Models.EcsConfigType.Default],getEcsParameters:()=>MRe.Resolved(e),initialAppActiveState:!0};return this._fetchConfig(r)}async fetchUserConfig(e,t,n){let r=`${this._isWBMediaClient?l2:c2}_${X2()}`,i=await n(),a=1e3*Xwe(i).exp,o={hosts:[PRe(this._acsProxy,t)],clientName:bSe,clientVersion:r,configsToFetch:[k9.Models.EcsConfigType.User],getEcsParameters:()=>MRe.Resolved(e),initialAppActiveState:!0,initialSkypeTokenData:{skypeToken:i,skypeTokenExpiration:a}};return this._fetchConfig(o)}get eTag(){return this._cachedConfig?.eTag??``}get sourceTag(){return this._sourceTag}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._eventEmitter.removeAllListeners(),this._resetThrottlingTimeout(),this._resetEcsClient()}getConfigIds(e){return(this._cachedConfig?.config)?.ConfigIDs?.[e]}},IRe=class{constructor(e){this._telemetryLogManager=e,this._seq=0}sendAttemptEvent(e,t,n){this._seq++,this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_attempt,tenant:p2,properties:{attemptTimestamp:e,ecsFetchType:t,correlationId:n,eventSeq:this._seq}})}sendSuccessEvent(e,t,n,r){let i=Date.now();this._seq++;let a=e===void 0?0:i-e;this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_success,tenant:p2,properties:{...e===void 0?void 0:{attemptTimestamp:e},successTimestamp:i,deltaTimeInMs:a,ecsFetchType:t,correlationId:n,eventSeq:this._seq,ecsConfigIds_AcsCallingSDKWeb:r?.AcsCallingSDKWeb||``,ecsConfigIds_SkypeWebMedia:r?.SkypeWebMedia||``}})}sendFailureEvent(e,t,n,r){let i=Date.now();this._seq++;let a=e===void 0?0:i-e,o=r.message,s=J3(r);this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_failure,tenant:p2,properties:{...e===void 0?void 0:{attemptTimestamp:e},failureTimestamp:i,deltaTimeInMs:a,ecsFetchType:t,correlationId:n,eventSeq:this._seq,failureReason:o,additionalDetails:{...s}}})}};function LRe(e,...t){e4.merge(e,...t)}function RRe(e,t){let n={};try{n.CLRelease=W5.stackFactory.getVersion().build;let e=r8();n.BrowserName=e.name,n.BrowserEngine=e.engine,n.BrowserVersion=e.version,n.FormFactor=e.formFactor,n.IdentityType=t2.Consumer,n.Cloud=X0.Public,n.OSVer=`${i8()}-${lke()}`,t&&(n.Cloud=t.cloudType,n.IdentityType=t.identityType),n.CLRelease===`_TS_BUILD_VERSION_`?n.CLRelease=`9999.99`:n.CLRelease.match(/^\d+\.\d+\.\d+\.\d+$/)||delete n.CLRelease}catch(t){throw e.error(t),new Y({defaultError:J.CALL_STACK.SET_STACK_PARAMS,originalError:t})}return n}var A9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},j9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},M9=class{constructor(e,t,n,r,i,a,o,s,c=!1){if(this._baseStackDisposed=!1,this._userStackDisposed=!1,this._trouterStateChangedListenersRegistered=new Map,this._signalingAgentInitialized=!1,this._hardcodedEcsConfigApplied=!1,this._clientId=t,this.sdkDiagnosticInformation=r,this.logger=e.createChild(`CallStack`),this._telemetryLogManager=n,this._acsProxy=i,this._acsCustomRelayManager=a,this._vdi3Options=s,this._webcvProvider=new ELe,this._wasmvqeProvider=new jLe,this._isWBMediaClient=c,location.protocol!==`https:`&&location.protocol!==`file:`&&location.hostname!==`localhost`)throw new Y({defaultError:J.CALL_STACK.BAD_PROTOCOL});this._telemetryService=new TLe(this._telemetryLogManager),this._ecsTelemetryLogger=new IRe(n),this._ecsProvider=new r9(this.logger,this.sdkDiagnosticInformation,this._acsProxy),this._ecsClient=new FRe(this._isWBMediaClient,this.logger,this._acsProxy,`EcsClient`),this._videoEffectsStatusManager=new kLe,this._audioEffectsStatusManager=new ALe,o!==void 0&&(this._encodedStreamsWorkerProvider=new DLe(o))}getVdi3StateInfo(){return this._vdi3StateInfo}getClientId(){return this._clientId}getCaConfigBag(){return this._caConfigBag}getTrouterState(){let e=this._trouterService?.state()??this._shellTrouter?.state();return this.mapTsTrouterState(e)}getEcsConfigIds(){return this._ecsClientRdc?{AcsCallingSDKWeb:this._ecsClient?.getConfigIds(`AcsCallingSDKWeb`)??``,SkypeWebMedia:this._ecsClientRdc?.getConfigIds(`SkypeWebMedia`)??``}:{AcsCallingSDKWeb:this._ecsClient?.getConfigIds(`AcsCallingSDKWeb`)??``,SkypeWebMedia:this._ecsClient?.getConfigIds(`SkypeWebMedia`)??``}}isRegistered(){return this._trouterService?.isRegistered()??this._shellTrouter?.registeredState()??!1}onRegisteredChanged(e){this._trouterService?.onRegisteredChanged(e),this._shellTrouter?.on(`registeredChanged`,e)}offRegisteredChanged(e){this._trouterService?.offRegisteredChanged(e),this._shellTrouter?.off(`registeredChanged`,e)}onTrouterStateChanged(e){let t=(t,n)=>{e(this.mapTsTrouterState(t))};return this._trouterService?.onStateChanged(t),this._shellTrouter?.on(`stateChanged`,t),this._trouterStateChangedListenersRegistered.set(e,t),{listener:e,tsTrouterStateChangedListener:t}}offTrouterStateChanged(e){let t=this._trouterStateChangedListenersRegistered.get(e);if(t)return this._trouterService?.offStateChanged(t),this._shellTrouter?.off(`stateChanged`,t),this._trouterStateChangedListenersRegistered.delete(e),{listener:e,tsTrouterStateChangedListener:t}}mapTsTrouterState(e){let t=`Uninitialized`;if(e!==void 0)switch(e){case 0:t=`Unknown`;break;case 2:t=`Connected`;break;case 3:t=`Disconnected`;break;case 9:t=`Switching`}return t}get webcvProvider(){return this._webcvProvider}get wasmvqeProvider(){return this._wasmvqeProvider}get videoEffectsStatusManager(){return this._videoEffectsStatusManager}get audioEffectsStatusManager(){return this._audioEffectsStatusManager}async applyHardcodedEcsConfigAndSetStack(e,t){if(this._hardcodedEcsConfigApplied)return void this.logger.info(`Hardcoded ECS config already applied, skipping`);let n=Hwe();await this.updateConfig(n,t);let r=+new Date;await this._setStackConfig();let i=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:e,durationInMs:i,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),this._hardcodedEcsConfigApplied=!0}async createStackBase(e){if(this._createStackBaseWaitPromise)return this._createStackBaseWaitPromise;this._baseStackDisposed=!1;let t=new Promise((async(t,n)=>{try{let n=this._getBaseStackConfig();if(this._vdi3StateInfo={supported:PLe(),requested:!1,enabled:!1},this._vdi3StateInfo.supported&&!0===this._vdi3Options?.enabled){this._vdi3StateInfo.requested=!0,this._shellTrouter&&await this._shellTrouter.dispose(),this._shellTrouter=new WLe;let e=FLe(this.logger,this._vdi3Options);e.vdi3Config&&(e.vdi3Config.shellTrouter=this._shellTrouter.instance);let t=await W5.stackFactory.buildBaseStack({stackType:1,...n,...e});if(this._proxyReferenceManager=u9.create(this.logger),this._tsStack=this._proxyReferenceManager.create(t),this._vdi3StateInfo.enabled=!0,Z().vdi3.fetchEcs)try{let e=await this._tsStack?.getEcsProviderAsync?.();this._ecsQueryParametersRdc=JSON.parse(await e?.getEcsQueryParameters()??`null`)||void 0,this._ecsQueryParametersRdc&&(this._ecsQueryParametersRdc=NRe(this._ecsQueryParametersRdc),this._ecsClientRdc=new FRe(this._isWBMediaClient,this.logger,this._acsProxy,`EcsClientRdc`))}catch(e){this.logger.error(`Failed to get query parameters ${e}`)}}else this._tsStack=await W5.stackFactory.buildBaseStack({stackType:0,...n});let r=async(e,t,n)=>{if(e!==void 0||t!==void 0)try{if(e!==void 0&&e===t){await this.updateConfig(e,this._caConfigBag);let t=Z();qG.updateConfig(t?.errors,this.logger)}else await this.updateConfigForVdi(e,t,this._caConfigBag);t!==void 0&&(await this._setStackConfig(),this._checkEcsConfigValue(t,{attemptTimestamp:void 0,ecsFetchType:n,correlationId:``})),this._ecsTelemetryLogger.sendSuccessEvent(void 0,n,``,this.getEcsConfigIds())}catch(e){let t=new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e});this._ecsTelemetryLogger.sendFailureEvent(void 0,n,``,t)}};this._ecsClientRdc?(this._ecsClient.on(`configUpdated`,(async e=>{await r(e.config,void 0,e.fetchType)})),this._ecsClientRdc.on(`configUpdated`,(async e=>{await r(void 0,e.config,e.fetchType)}))):this._ecsClient.on(`configUpdated`,(async e=>{await r(e.config,e.config,e.fetchType)})),await this.initializeEcsBase(e),await this._setStackConfig(),t(this._tsStack)}catch(e){n(e)}}));try{this._createStackBaseWaitPromise=i3((()=>t),YSe);let e=await this._createStackBaseWaitPromise;return this.logger.log(`Base stack init success`),e}catch(e){throw await this.disposeBaseStack(),e.code===RG?new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_TIMEOUT}):new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_FAILED,originalError:e})}}async createMediaSdkStackBase(e,t,n){if(this._createMediaSdkStackBaseWaitPromise)return this._createMediaSdkStackBaseWaitPromise;this._baseStackDisposed=!1;let r=new Promise((async(r,i)=>{try{let i=this._getMediaStackConfig(e),a=+new Date;this._tsStack=await W5.stackFactory.build(i);let o=+new Date-a;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`BuildMediaStack`,durationInMs:o,operationPayload:{},resultCategories:[`Success`],resultSignature:200});let s=async(e,t,n)=>{if(e!==void 0||t!==void 0)try{e!==void 0&&e===t?await this.updateConfig(e,this._caConfigBag):await this.updateConfigForVdi(e,t,this._caConfigBag),t!==void 0&&(await this._setStackConfig(),this._checkEcsConfigValue(t,{attemptTimestamp:void 0,ecsFetchType:n,correlationId:``})),this._ecsTelemetryLogger.sendSuccessEvent(void 0,n,``,this.getEcsConfigIds())}catch(e){let t=new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e});this._ecsTelemetryLogger.sendFailureEvent(void 0,n,``,t)}};if(this._ecsClient.on(`configUpdated`,(async e=>{await s(e.config,e.config,e.fetchType)})),!n){await this.applyHardcodedEcsConfigAndSetStack(`SetStackConfigBase`,t);let e=+new Date;this.initializeEcsBase(t).then((async()=>{let t=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`InitializeEcsBase`,durationInMs:t,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),Z().waimeabay.backgroundEcsFetchTsStackSet&&await this._setStackConfig()})).catch((t=>{let n=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`InitializeEcsBase`,durationInMs:n,operationPayload:{},resultCategories:[`Failure`],resultSignature:500}),this.logger.warn(`Background ECS fetch failed`,t)}))}r(this._tsStack)}catch(e){i(e)}}));try{this._createMediaSdkStackBaseWaitPromise=i3((()=>r),YSe);let e=await this._createMediaSdkStackBaseWaitPromise;return this.logger.log(`Base stack init success`),e}catch(e){throw await this.disposeBaseStack(),e.code===RG?new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_TIMEOUT}):new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_FAILED,originalError:e})}}async initializeStackForUser(e,t){if(this._initializeStackForUserWaitPromise)return this._initializeStackForUserWaitPromise;this._caConfigBag=t,this._tsStack=await this.createStackBase(t),this._userStackDisposed=!1;let n=new Promise((async(n,o)=>{try{this._tsStack?(this._ecsProvider=new r9(this.logger,this.sdkDiagnosticInformation,this._acsProxy),await this.initializeEcsForUser(t,e),V6.overrideDefaultLogDump(),G6(this._tsStack)||(Z().calling.doNotWaitForTrouter?this._initTrouter(e).then((()=>{this.logger.log(`Signaling initialized successfully.`)})).catch((()=>{this.logger.warn(J.CALL_STACK.SIGNALING_UNINITIALIZED.message)})):(await this._initTrouter(e),this.logger.log(`Signaling initialized successfully.`))),await r(e,this._tsStack),await i(e,this._tsStack),await a(this._tsStack),n(this._tsStack)):(this.logger.error(`Base stack failed to create`),o(new Y({defaultError:J.CALL_STACK.USER_STACK_NO_BASE_STACK})))}catch(e){o(e)}})),r=async(e,t)=>{try{if(await t.initializeMediaAgent({httpRequestDispatcher:this.getRequestDispatcher(),tokenProvider:e,relayManager:this.getCustomRelayManager(),configProvider:{getSkypeConfig:()=>Promise.resolve({}),getRelayConfig:()=>{let e=this._ecsProvider.getMdnTrapSettings();return Promise.resolve(e)}},appStateProvider:this._getAppStateProvider(),clientInformation:this._ecsProvider.getJsCsaConfig().clientInformation}),Z().calling.platformSupportValidation&&await t.getPlatformSupportLevelAsync()===0){let e=new Y({defaultError:J.CALL_STACK.USER_STACK_MEDIA_INIT_FAILED_PLATFORM_NOT_SUPPORTED});throw this.logger.error(e.message),e}}catch(e){throw this.logger.error(`Failed to initialize media stack`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_MEDIA_INIT_FAILED,originalError:e})}},i=async(e,t)=>{try{let n=G6(t),r={signalingAgentConfig:this._getSignalingConfig(e),...n?{trouterSettings:CLe(this._ecsProvider),trouterService:{}}:{trouterService:this._trouterService}};this._signalingAgentInitialized?(await t.updateSignalingAgentProviderConfig(r),this.logger.log(`Signaling agent updated successfully`)):(await t.initializeSignalingAgentProvider(r),this._signalingAgentInitialized=!0,this.logger.log(`Signaling agent initialized successfully`)),n&&(await this._shellTrouter?.initialize(),this.logger.log(`Signaling initialized successfully for VDI3.`))}catch(e){throw this.logger.error(`Failed to initialize signaling agent`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_SIGNALING_INIT_FAILED,originalError:e})}},a=async e=>{try{await e.init(),await this._setStackConfig()}catch(e){throw this.logger.error(`Failed to initialize calling stack`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INTERNAL_INIT_FAILED,originalError:e})}};try{this._initializeStackForUserWaitPromise=i3((()=>n),XSe);let e=await this._initializeStackForUserWaitPromise;return this.sendStackInitEvent(!0),this.logger.log(`User stack init success`),e}catch(e){throw await this.disposeUserStack(),e.code===RG?(this.sendStackInitEvent(!1,`User stack init timeout`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_TIMEOUT})):!(e instanceof Y)&&this.getTrouterState()===`Uninitialized`?new Y({defaultError:J.CALL_STACK.SIGNALING_UNINITIALIZED,originalError:e}):(this.sendStackInitEvent(!1,`User stack init failed`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_FAILED,originalError:e}))}}async initializeMediaSdkStackForUser(e,t){if(this._caConfigBag=t,this._initializeMediaStackForUserWaitPromise)return this._initializeMediaStackForUserWaitPromise;this._tsStack=await this.createMediaSdkStackBase(e,t,!0);let n=this._getMediaStackConfig(e);this._tsStack.initializeMediaAgent(n.mediaAgentFactoryConfig),this._userStackDisposed=!1;let r=new Promise((async(n,r)=>{try{if(this._tsStack){await this.applyHardcodedEcsConfigAndSetStack(`SetStackConfigUser`,t);let r=+new Date;this.initializeEcsForUser(t,e).then((async()=>{let e=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`InitializeEcsForUser`,durationInMs:e,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),V6.overrideDefaultLogDump(),Z().waimeabay.backgroundEcsFetchTsStackSet&&await this._setStackConfig()})).catch((e=>{let t=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`InitializeEcsForUser`,durationInMs:t,operationPayload:{},resultCategories:[`Failure`],resultSignature:500}),this.logger.warn(`Background user ECS fetch failed`,e)})),this.logger.log(`ECS initialized successfully.`);let a=+new Date;await i(this._tsStack);let o=+new Date-a;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`InitializeTsStack`,durationInMs:o,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),n(this._tsStack)}else this.logger.error(`Media SDK Base stack failed to create`),r(new Y({defaultError:J.CALL_STACK.USER_STACK_NO_BASE_STACK}))}catch(e){r(e)}})),i=async e=>{try{await e.init(),await this._setStackConfig()}catch(e){throw this.logger.error(`Failed to initialize Media SDK stack`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INTERNAL_INIT_FAILED,originalError:e})}};try{this._initializeMediaStackForUserWaitPromise=i3((()=>r),XSe);let e=await this._initializeMediaStackForUserWaitPromise;return this.sendStackInitEvent(!0),this.logger.log(`Media SDK User stack init success`),e}catch(e){throw await this.disposeUserStack(),e.code===RG?(this.sendStackInitEvent(!1,`Media SDK user stack init timeout`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_TIMEOUT})):(this.sendStackInitEvent(!1,`Media SDK user stack init failed`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_FAILED,originalError:e}))}}getRequestDispatcher(){return this._acsProxy.hasProxyUrl()?(this.logger.info(`Using custom proxy for network requests (non media)`),new OLe(this.logger,this._acsProxy)):Z().telemetry.sendNetworkInfo?new OLe(this.logger):new W5.HttpRequestDispatcherImplementation(this.logger)}async updateConfig(e,t){e?.Headers?.CountryCode&&this.updateEmergencyCallCountry(e?.Headers?.CountryCode);try{Vwe(e),this._ecsProvider.setConfig(t,e),Uwe(this._ecsProvider.getJamaSettings()),this._fetchedEcsConfigValue=e;let n=Z();qG.updateConfig(n?.errors,this.logger)}catch(e){throw this.logger.warn(`Unable to update ECS configuration ${e}`),new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e})}}async updateConfigForVdi(e,t,n){e?.Headers?.CountryCode&&this.updateEmergencyCallCountry(e?.Headers?.CountryCode);let r=t=>{LRe(t,ILe);let n=e?.AcsCallingSDKWeb?.vdi3?.customEcsConfig;if(n)try{LRe(e,JSON.parse(n))}catch(e){this.logger.error(`Failed to parse customEcsConfig: ${e}`)}};try{e&&(r(e),Vwe(e)),t&&(r(t),this._ecsProvider.setConfig(n,t),Uwe(this._ecsProvider.getJamaSettings()),this._fetchedEcsConfigValue=t)}catch(e){throw this.logger.warn(`Unable to update ECS configuration ${e}`),new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e})}}async _setStackConfig(){let e=Date.now();try{this._tsStack&&this._fetchedEcsConfigValue&&Object.keys(this._fetchedEcsConfigValue).length>0&&(this.logger.info(`Setting ECS configuration on the calling stack.`),await(await this._tsStack?.getEcsProviderAsync?.())?.setEcsConfig({ecsBlob:JSON.stringify(this._fetchedEcsConfigValue),userIdentity:``,etag:this._ecsClient.eTag}))}catch(t){let n=new Y({defaultError:J.CALL_STACK.SET_STACK_PARAMS,originalError:t}),r=Date.now(),i=e===void 0?0:r-e,a=n.message,o=J3(n);this.logger.warn(`Unable to set ECS configuration on the calling stack`),this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_failure,tenant:p2,properties:{...e===void 0?void 0:{attemptTimestamp:e},failureTimestamp:r,deltaTimeInMs:i,failureReason:a,additionalDetails:{...o}}})}}_checkEcsConfigValue(e,t){let{attemptTimestamp:n,correlationId:r,ecsFetchType:i}=t;try{r9.assertConfigs(e)}catch(e){this.logger.error(`ECS config assertion failed: ${e?.message??`Unknown error`}`),this._ecsTelemetryLogger.sendFailureEvent(n,i,r,e)}}async initializeEcsBase(e){let t=Date.now(),n=J0();this._ecsTelemetryLogger.sendAttemptEvent(t,O9.Default,n);let r=J.CALL_STACK.FETCH_CONFIG;try{let i=await this._ecsClient.fetchDefaultConfig(RRe(this.logger,e),e);this.logger.info(`Fetched base settings from ECS.`);let a=i;if(G6(this._tsStack)&&this._ecsClientRdc&&this._ecsQueryParametersRdc){let t=await this._ecsClientRdc.fetchDefaultConfig(this._ecsQueryParametersRdc,e);a=t,r=J.CALL_STACK.PARSE_CONFIG,await this.updateConfigForVdi(i,t,e)}else r=J.CALL_STACK.PARSE_CONFIG,await this.updateConfig(i,e);this._ecsTelemetryLogger.sendSuccessEvent(t,O9.Default,n,this.getEcsConfigIds()),this._checkEcsConfigValue(a,{attemptTimestamp:t,correlationId:n,ecsFetchType:O9.Default})}catch(i){this.logger.warn(`Failed to fetch base settings. Stack will initialize with default settings`,i),this._ecsProvider.setConfig(e,void 0);let a=new Y({defaultError:r,originalError:i});this._ecsTelemetryLogger.sendFailureEvent(t,O9.Default,n,a)}}async initializeEcsForUser(e,t){let n=Date.now(),r=J0();this._ecsTelemetryLogger.sendAttemptEvent(n,O9.User,r);let i=J.CALL_STACK.FETCH_CONFIG;try{let a=await this._ecsClient.fetchUserConfig(RRe(this.logger,e),e,t);this.logger.info(`Fetched user settings from ECS.`);let o=a;if(G6(this._tsStack)&&this._ecsClientRdc&&this._ecsQueryParametersRdc){let n=await this._ecsClientRdc.fetchUserConfig(this._ecsQueryParametersRdc,e,t);o=n,i=J.CALL_STACK.PARSE_CONFIG,await this.updateConfigForVdi(a,n,e)}else i=J.CALL_STACK.PARSE_CONFIG,await this.updateConfig(a,e),this._ecsTelemetryLogger.sendSuccessEvent(n,O9.User,r,this.getEcsConfigIds());this._ecsTelemetryLogger.sendSuccessEvent(n,O9.User,r,this.getEcsConfigIds()),this._checkEcsConfigValue(o,{attemptTimestamp:n,correlationId:r,ecsFetchType:O9.User})}catch(e){this.logger.warn(`Failed to fetch user settings.`,e);let t=new Y({defaultError:i,originalError:e});this._ecsTelemetryLogger.sendFailureEvent(n,O9.User,r,t)}}async getDeviceManager(){if(this._createMediaSdkStackBaseWaitPromise){let e=await this._createMediaSdkStackBaseWaitPromise;return this.logger.info(`Getting ts device manager from media sdk stack`),e.getDeviceManagerAsync()}if(this._createStackBaseWaitPromise){let e=await this._createStackBaseWaitPromise;return this.logger.info(`Getting ts device manager from stack`),e.getDeviceManagerAsync()}throw new Y({defaultError:J.CALL_STACK.GET_DM})}async disposeBaseStack(){if(!this._baseStackDisposed){if(this._tsStack)try{await this._tsStack.dispose(),this._tsStack=void 0}catch{this.logger.error(`Failed to dispose calling stack`)}this._proxyReferenceManager?.dispose(),this._ecsClient.dispose(),this._ecsClientRdc?.dispose(),this._createStackBaseWaitPromise=void 0,this._baseStackDisposed=!0,this.logger.info(`Base call stack disposed`)}}async disposeUserStack(e){if(!this._userStackDisposed){if(this._trouterService)try{this._trouterService.clearMessageHandlers(),this._trouterService.stop(e),this._trouterService=void 0}catch{this.logger.error(`Failed to dispose signaling`)}if(this._shellTrouter)try{await this._shellTrouter.dispose(),this._shellTrouter=void 0}catch{this.logger.error(`Failed to dispose shellTrouter`)}try{await this._tsStack?.disposeMediaAgent(J0())}catch{this.logger.error(`Failed to dispose media agent`)}this._initializeStackForUserWaitPromise=void 0,this._userStackDisposed=!0,this.logger.info(`User calling stack disposed`)}}updateEmergencyCallCountry(e){this._caConfigBag&&!this._caConfigBag.emergencyCountryCode&&!this._caConfigBag.IsUserEmergencyCountryCode&&e&&(this._caConfigBag.emergencyCountryCode=e)}async _initTrouter(e){let t=+new Date;try{this._trouterService=new wLe(this.logger,this._ecsProvider,(t=>e(t)),this._telemetryLogManager,this._acsProxy),t=+new Date;let n=await this._trouterService.start(),r=this._trouterService.getTrouterSettings();this.sendSignalingInitEvent(!0,+new Date-t,r.registrationId??``,r.sessionId,n.trouterRequestCompletionTimeDeltaMs,n.registrarRequestCompletionTimeDeltaMs);return}catch(e){throw this.sendSignalingInitEvent(!1,+new Date-t,``,``,void 0,void 0,e),e}}_getBaseStackConfig(){let e=this._getMediaProviderConfig(),t={clientInformation:this._ecsProvider.getClientInformation(),logger:this.logger,mediaSettings:e.mediaSettings,platformType:n8(),callSettings:{useLwjForAllCalls:!1},usePlatformSupportApi:!0,telemetryTenants:{media:`mediaAgent`,signaling:`signalingAgent`,tlePlayer:YCe},telemetryService:this._telemetryService,webcvProvider:this._webcvProvider,wasmVqeProvider:this._wasmvqeProvider};return this._encodedStreamsWorkerProvider!==void 0&&(t.encodedStreamsWorkerProvider=this._encodedStreamsWorkerProvider),t}_getMediaStackConfig(e){return{stackType:2,mediaAgentFactoryConfig:{logger:this.logger,tokenProvider:e,configProvider:{getSkypeConfig:()=>Promise.resolve({}),getRelayConfig:()=>{let e=this._ecsProvider.getMdnTrapSettings();return Promise.resolve(e)}},settings:this._getMediaAgentConfig(),wasmVqeProvider:this._wasmvqeProvider,appStateProvider:this._getAppStateProvider()},signalingAgentConfig:this._getSignalingConfig(e),logger:this.logger,telemetryService:this._telemetryService,platformType:n8()}}_getSignalingConfig(e){let t={...this._ecsProvider.getJsCsaConfig(),httpRequestDispatcher:this.getRequestDispatcher(),telemetryManager:this._telemetryService.getCallingAdapter(),logger:this.logger,skypeToken:e,trouterServiceProvider:this._trouterService,ecsEtag:this._ecsClient.eTag};return this._caConfigBag?.emergencyCountryCode&&(t.emergencyCallCountry=this._caConfigBag?.emergencyCountryCode),t}_getMediaProviderConfig(){return{logger:this.logger,mediaSettings:this._getMediaAgentConfig()}}_getMediaAgentConfig(){return{...this._ecsProvider.getJamaSettings(),useOneDsLogger:!0,collectorUrl:Y0.Public,telemetryTenants:{signaling:m2,gtcAudit:m2,media:h2,realtimeMedia:TCe,tlePlayer:ECe}}}_getAppStateProvider(){return{isOnline:()=>!0}}sendStackInitEvent(e,t,n){try{let r,i;n&&(r=n.message,i=J3(n)),this._telemetryLogManager.sendEvent({name:Q.acs_calling_stack_init,tenant:p2,properties:{success:e,reason:t,failureReason:r||`unknown`,additionalDetails:{...i}}})}catch{}}sendSignalingInitEvent(e,t,n,r,i,a,o){try{let s,c;o&&(s=o.message,c=J3(o)),this._telemetryLogManager.sendEvent({name:Q.acs_calling_signaling_init,tenant:p2,properties:{success:e,failureReason:s||`unknown`,timestampInfo:{deltaTimeInMs:t,deltaTimeInMsTrouterRequest:i,deltaTimeInMsRegistrarRequest:a},additionalDetails:{...c,registrationId:n,sessionId:r}}})}catch{}}getCustomRelayManager(){if(this._tsCustomRelayManager=this._acsCustomRelayManager.getTsRelayManager(),this._tsCustomRelayManager&&Z().calling.enableCustomTurnUsage)return this.logger.info(`Using custom relays for media traffic`),this._acsCustomRelayManager.customRelayManagerInUse=!0,this._tsCustomRelayManager}};A9([UG,j9(`design:type`,Object)],M9.prototype,`logger`,void 0),A9([YG(u4.CreateStackBase),j9(`design:type`,Function),j9(`design:paramtypes`,[Object]),j9(`design:returntype`,Promise)],M9.prototype,`createStackBase`,null),A9([YG(u4.CreateStackBase),j9(`design:type`,Function),j9(`design:paramtypes`,[Function,Object,Boolean]),j9(`design:returntype`,Promise)],M9.prototype,`createMediaSdkStackBase`,null),A9([YG(u4.InitializeStackForUser),j9(`design:type`,Function),j9(`design:paramtypes`,[Function,Object]),j9(`design:returntype`,Promise)],M9.prototype,`initializeStackForUser`,null),A9([YG(u4.InitializeMediaSdkStackForUser),j9(`design:type`,Function),j9(`design:paramtypes`,[Function,Object]),j9(`design:returntype`,Promise)],M9.prototype,`initializeMediaSdkStackForUser`,null),A9([YG(u4.GetDeviceManager),j9(`design:type`,Function),j9(`design:paramtypes`,[]),j9(`design:returntype`,Promise)],M9.prototype,`getDeviceManager`,null);var zRe=class{constructor(){this._eventEmitter=new E3.EventEmitter}notifyAll(e){this._eventEmitter.emit(e)}waitFor(e,t){return new Promise(((n,r)=>{let i=0,a=()=>{n(),clearTimeout(i)};this._eventEmitter.once(e,a),i=window.setTimeout((()=>{this._eventEmitter.off(e,a),r(Error(`timeout`))}),t)}))}},BRe=class{constructor(){this._deviceIdMapping=new Map,this._deviceId=1,this._keywords=Z().telemetry.deviceChangedEvents.piiSafeWords}getDeviceId(e){let t=this._deviceIdMapping.get(e);return t===void 0?(++this._deviceId,t=`${e.split(`:`)[0]??``}:${this._deviceId}`,this._deviceIdMapping.set(e,t),t):t}scrubDeviceLabel(e){return VRe(e,this._keywords)}};function VRe(e,t){if(!e)return``;if(e.length<3)return e;let n=[],r=e.match(/\(([0-9a-zA-Z]+:[0-9a-zA-Z]+)\)/);r&&n.push(r[1]);try{if(!t?.length)return`no_keywords`;{let r=RegExp(`(${t.join(`|`)})`,`gi`),i=r.exec(e);for(;i;)n.push(i[1]),i=r.exec(e)}}catch(e){n.push(`Error: ${(e=>e4.isString(e)?e:e?.message??``)(e)}`)}return n.length===0?`unknown`:n.join(` `)}var N9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},P9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},F9=class{constructor(e,t,n,r=!1,i){this._callStack=t,this._isWBMediaClient=r,this._videoDevices=[],this._audioDevices=[],this._disposed=!1,this._tsDeviceTypeToAudioDeviceType={2:`Microphone`,3:`Speaker`,4:`CompositeAudioDevice`},this.logger=e.createChild(`DeviceManager`),this._telemetryLogManager=n,this._eventEmitter=new w6(this.logger),this._browserInfo=r8(),this._safariVideoPermissionState=`unknown`,this._combinedDevicePermission=new Map,this._deviceInfoMapper=new BRe,this._deviceSelectionNotifications=new zRe,this._permissionChangedTasks=Promise.resolve(),this._shouldEnumerateDevices=i??!0}get telemetryLogManager(){return this._telemetryLogManager}get isWBMediaClient(){return this._isWBMediaClient}get shouldEnumerateDevices(){return this._shouldEnumerateDevices}getRawDeviceMediaStream(e){let t=J0(),n=+new Date;if(this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`attempt`,mediaType:e,timestampInfo:``,additionalDetails:``}),!this._tsDeviceManager?.getRawDeviceMediaStream){let r=new Y({defaultError:J.DEVICE_MANAGER.GET_MEDIA_STREAM_TRACK});this.logger.error(`Failed to get raw device stream track`);let i=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`failure`,mediaType:e,timestampInfo:{deltaTimeInMs:i-n},additionalDetails:{failureReason:r.message||``,code:r.code,subCode:r.subCode,...J3(r)}}),r}let r;try{r=this._tsDeviceManager?.getRawDeviceMediaStream(e);let i=+new Date;return this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`success`,mediaType:e,timestampInfo:{deltaTimeInMs:i-n},additionalDetails:``}),r}catch(r){let i=new Y({defaultError:J.DEVICE_MANAGER.GET_MEDIA_STREAM_DEVICE_UNAVAILABLE,originalError:r}),a=K3(r,this.isWBMediaClient,i);this.logger.error(`Failed to get raw device stream: `,a.message);let o=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`failure`,mediaType:e,timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...J3(a)}}),a}}getClientId(){return this._callStack.getClientId()}async getDeviceManager(){if(this._tsDeviceManager)return this._tsDeviceManager;let e=+new Date,t=J0();try{this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`attempt`,timestampInfo:``,additionalDetails:``});let n=+new Date;if(this.isWBMediaClient){await this._callStack.createMediaSdkStackBase();let e=+new Date-n;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`CreateMediaStackBase`,durationInMs:e,operationPayload:{},resultCategories:[`Success`],resultSignature:200})}else await this._callStack.createStackBase();let r=+new Date;if(this._tsDeviceManager=await this._callStack.getDeviceManager(),this.isWBMediaClient){let e=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`GetTsDeviceManager`,durationInMs:e,operationPayload:{},resultCategories:[`Success`],resultSignature:200})}if(this._shouldEnumerateDevices){let e=+new Date;try{let t=await this.enumerateDevicesAsync();if(this.isWBMediaClient){let n=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`EnumerateDevices`,durationInMs:n,operationPayload:{deviceCount:t.length},resultCategories:[`Success`],resultSignature:200})}this.logger.info(`tsDevicesList:${JSON.stringify(t)}`),t.forEach((e=>{if(e.kind===1){let t=e;this._videoDevices.push(new z6(t.label,t.id,`UsbCamera`,this))}else if(e.kind===2||e.kind===3){let t=e,n=new Z6(t.label,t.id,t.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[t.kind],this);this._audioDevices.push(n)}}))}catch(t){if(this.isWBMediaClient){let n=+new Date-e,r=new Y({defaultError:J.DEVICE_MANAGER.DEVICE_ENUMERATING_FAIL,originalError:t});this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`EnumerateDevices`,durationInMs:n,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500})}if(!1===Z().calling.ignoreEnumerateDevicesError)throw`Ignore enumerateDevicesError ${t}`}let t=+new Date,n=await this._tsDeviceManager.getSelectedDevicesAsync?.();if(this.isWBMediaClient){let e=+new Date-t;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`GetSelectedDevices`,durationInMs:e,operationPayload:{hasMicrophone:!!n?.microphone,hasSpeaker:!!n?.speaker},resultCategories:[`Success`],resultSignature:200})}n&&(this._selectedMicrophone=this._audioDevices.find((e=>e.id===n.microphone)),this._selectedSpeaker=this._audioDevices.find((e=>e.id===n.speaker)))}else this.logger.info(`Skipping device enumeration (enumerateDevices is disabled)`);if(this._dmDevicesChangedSub=this._tsDeviceManager.on(`devicesChanged`,(async()=>{try{await this.syncDeviceList(await this.enumerateDevicesAsync()),await this.checkForSelectedDevicesChanges()}catch(t){this.logger.warn(`Unable to handle devicesChanged, error=${t?.message}, code=${t?.code}`);let n=+new Date;this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:t?.message,code:t?.code,...J3(t),context:`devicesChanged`}})}})),Z().calling.devicePermissions.getCurrentState){let e=+new Date,t=await this._tsDeviceManager?.getPermissionStateAsync?.(`microphone`,``),n=await this._tsDeviceManager?.getPermissionStateAsync?.(`camera`,``);if(this.isWBMediaClient){let r=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`GetPermissionState`,durationInMs:r,operationPayload:{microphoneState:String(t??`undefined`),cameraState:String(n??`undefined`)},resultCategories:[`Success`],resultSignature:200})}this._audioDevicePermission=I4(t,this.logger),this._videoDevicePermission=I4(n,this.logger)}this.logger.info(`Initial permission state audio:`,this._audioDevicePermission,`video:`,this._videoDevicePermission),this._dmDevicesPermissionChangedSub=this._tsDeviceManager.on(`onPermissionStateChanged`,(()=>{this._permissionChangedTasks=this._permissionChangedTasks.then((()=>this.permissionsChanged().catch(M4)))}));let i=+new Date-e;this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:i},additionalDetails:``}),this.isWBMediaClient&&this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`GetDeviceManager`,durationInMs:i,operationPayload:{videoDeviceCount:this._videoDevices.length,audioDeviceCount:this._audioDevices.length},resultCategories:[`Success`],resultSignature:200})}catch(n){let r=new Y({defaultError:J.DEVICE_MANAGER.GET_DM,originalError:n});this.logger.error(r.message);let i=+new Date-e;throw this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:i},additionalDetails:{failureReason:r.message,code:r.code,...J3(r)}}),this.isWBMediaClient&&this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`GetDeviceManager`,durationInMs:i,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500}),r}return this._tsDeviceManager}getTsDeviceManager(){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});return this._tsDeviceManager}getSafariPermissionState(){return this._browserInfo.engine===`Safari`?this._safariVideoPermissionState:`unknown`}getAcsResourceId(){return this._callStack?.getCaConfigBag()?.acsResourceId}getAudioDevicePermission(){return this._audioDevicePermission}getVideoDevicePermission(){return this._videoDevicePermission}get callStackWebCvProvider(){return this._callStack.webcvProvider}get callStackWasmVqeProvider(){return this._callStack.wasmvqeProvider}get callStackVideoEffectsStatusManager(){return this._callStack.videoEffectsStatusManager}get callStackAudioEffectsStatusManager(){return this._callStack.audioEffectsStatusManager}get deviceInfoMapper(){return this._deviceInfoMapper}getEnvironmentInfoInternal(){return this._environmentInfo||=hke(),this._environmentInfo}getOSNameInternal(){return i8()}dispose(){this._disposed=!0,this._dmDevicesChangedSub&&this._dmDevicesChangedSub.dispose(),this._dmDevicesPermissionChangedSub&&this._dmDevicesPermissionChangedSub.dispose(),this._dmDevicesPermissionChangedSub=void 0,this._dmDevicesChangedSub=void 0,this._eventEmitter.removeAllListeners(),this._tsDeviceManager=void 0}on(e,t){if(e!==`videoDevicesUpdated`&&e!==`audioDevicesUpdated`&&e!==`selectedMicrophoneChanged`&&e!==`selectedSpeakerChanged`)throw new Y({defaultError:J.DEVICE_MANAGER.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`videoDevicesUpdated`&&e!==`audioDevicesUpdated`&&e!==`selectedMicrophoneChanged`&&e!==`selectedSpeakerChanged`)throw new Y({defaultError:J.DEVICE_MANAGER.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}sendRawMediaEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send raw media telemetry`)}}sendGetDeviceManagerEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send get_device_manager telemetry`)}}async permissionsChanged(e,t){let n=this._audioDevicePermission,r=this._videoDevicePermission,i,a;if(Z().calling.devicePermissions.getCurrentState){let e=await this._tsDeviceManager?.getPermissionStateAsync?.(`microphone`,``),t=await this._tsDeviceManager?.getPermissionStateAsync?.(`camera`,``);i=I4(e,this.logger),a=I4(t,this.logger)}else i=n,a=r;this._audioDevicePermission=i||!!e?.audio,this._videoDevicePermission=a||!!e?.video,t&&(t.audio&&(this._audioDevicePermission=e?.audio??!1),t.video&&(this._videoDevicePermission=e?.video??!1)),n===this._audioDevicePermission&&r===this._videoDevicePermission||(this.logger.info(`permission state changed from audio: ${n}, video: ${r}\n to audio: ${this._audioDevicePermission}, video: ${this._videoDevicePermission}`),this._telemetryLogManager.sendEvent({name:Q.acs_calling_device_permission_changed,tenant:p2,properties:{previousAudioDevicePermission:this.nullHandler(n),previousVideoDevicePermission:this.nullHandler(r),newAudioDevicePermission:this.nullHandler(this._audioDevicePermission),newVideoDevicePermission:this.nullHandler(this._videoDevicePermission)}}))}async checkForSelectedDevicesChanges(){if(this.logger.info(`checkForSelectedDevicesChanges`),this._tsDeviceManager){let e=await this._tsDeviceManager.getSelectedDevicesAsync?.();e&&(e.microphone!==this._selectedMicrophone?.id&&(this._selectedMicrophone=this._audioDevices.find((t=>t.id===e.microphone)),this._eventEmitter.emit(`selectedMicrophoneChanged`),e.microphone!==void 0&&this._deviceSelectionNotifications.notifyAll(e.microphone)),e.speaker!==this._selectedSpeaker?.id&&(this._selectedSpeaker=this._audioDevices.find((t=>t.id===e.speaker)),this._eventEmitter.emit(`selectedSpeakerChanged`),e.speaker!==void 0&&this._deviceSelectionNotifications.notifyAll(e.speaker)))}else this.logger.warn(`DeviceManager is undefined, Unable to check selected devices`)}isACSDeviceEqualToTSDevice(e,t){return e.id===t.id}async syncDeviceList(e){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});if(this.logger.info(`syncDeviceList`),!this._shouldEnumerateDevices)return void this.logger.info(`Device enumeration disabled, skipping syncDeviceList`);e===void 0&&(e=await this.enumerateDevicesAsync());let t=[],n=[],r=[],i=[];e.map((e=>{if(e.kind===1){let n=this._videoDevices.find((t=>this.isACSDeviceEqualToTSDevice(t,e)));if(n)n.setName(e.label),n.setId(e.id),n.setDeviceType(`UsbCamera`);else{let n=new z6(e.label,e.id,`UsbCamera`,this);t.push(n),this._videoDevices.push(n)}}else if(e.kind===2||e.kind===3){let t=this._audioDevices.find((t=>this.isACSDeviceEqualToTSDevice(t,e)));if(t){let n=e;t.setName(n.label),t.setId(n.id),t.setIsSystemDefault(n.isSystemDefault),t.setDeviceType(this._tsDeviceTypeToAudioDeviceType[n.kind])}else{let t=new Z6(e.label,e.id,e.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[e.kind],this);r.push(t),this._audioDevices.push(t)}}}));let a=t=>{let n=t.filter((t=>!e.find((e=>this.isACSDeviceEqualToTSDevice(t,e)))));return n.map((e=>{t.splice(t.indexOf(e),1)})),n};n=a(this._videoDevices),i=a(this._audioDevices),(t.length>0||n.length>0)&&this._eventEmitter.emit(`videoDevicesUpdated`,{added:t,removed:n}),(r.length>0||i.length>0)&&this._eventEmitter.emit(`audioDevicesUpdated`,{added:r,removed:i})}async enumerateDevicesAsync(){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});try{return await this._tsDeviceManager.enumerateDevicesAsync()}catch{throw new Y({defaultError:J.DEVICE_MANAGER.DEVICE_ENUMERATING_FAIL})}}get isSpeakerSelectionAvailable(){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});return this._tsDeviceManager.isAudioOutputSelectionSupported}get selectedMicrophone(){return this._selectedMicrophone}get selectedSpeaker(){return this._selectedSpeaker}async getCameras(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});return await this.syncDeviceList(),this._videoDevices}async getMicrophones(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});return await this.syncDeviceList(),this._audioDevices.filter((e=>e.deviceType===`Microphone`))}async getSpeakers(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});if(this.isSpeakerSelectionAvailable)return await this.syncDeviceList(),this._audioDevices.filter((e=>e.deviceType===`Speaker`));throw new Y({defaultError:J.DEVICE_MANAGER.SPEAKER_ENUMERATION_UNSUPPORTED})}async selectMicrophone(e){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});if(!e||!e.id)throw new Y({defaultError:J.DEVICE_MANAGER.INVALID_DEVICE});if(e.id===`microphone:`)throw new Y({defaultError:J.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(this.logger.info(`selectMicrophone called`),this._selectedMicrophone?.id!==e.id){let t=Z().calling.deviceSelectionTimeoutInMs,n=this._deviceSelectionNotifications.waitFor(e.id,t),r=this._deviceInfoMapper.getDeviceId(e.id),i=this._deviceInfoMapper.scrubDeviceLabel(e.name),a=J0(),o=(e,t,n)=>{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.deviceSelection,kindOfEvent:e,correlationId:a,timestampInfo:t===void 0?{}:{deltaTimeInMs:t},additionalDetails:n===void 0?``:{failureReason:n.message,code:n.code,...J3(n)},deviceSelection:{deviceId:r,deviceName:i,deviceType:`Microphone`}})};o(`attempt`);let s=Date.now();try{await this._tsDeviceManager.selectDevicesAsync?.({microphone:e.id}),await n.catch((t=>{if(this._selectedMicrophone?.id!==e.id)throw t})),o(`success`,Date.now()-s)}catch(e){let t;throw t=new Y(e?.message===`timeout`?{defaultError:J.DEVICE_MANAGER.SELECT_MICROPHONE_TIMEOUT}:{defaultError:J.DEVICE_MANAGER.SELECT_MICROPHONE_FAIL,originalError:e}),o(`failure`,Date.now()-s,t),t}}else this.logger.warn(`microphoneDevice is already active`)}async selectSpeaker(e){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let t=this.logger.createFnLogger(d4.SelectSpeaker);if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});if(!this.isSpeakerSelectionAvailable)throw new Y({defaultError:J.DEVICE_MANAGER.SPEAKER_SELECTION_UNSUPPORTED});if(!e||!e.id)throw new Y({defaultError:J.DEVICE_MANAGER.INVALID_DEVICE});if(e.id===`speaker:`)throw new Y({defaultError:J.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(t.info(`selectSpeaker called`),this._selectedSpeaker?.id!==e.id){let t=Z().calling.deviceSelectionTimeoutInMs,n=this._deviceSelectionNotifications.waitFor(e.id,t),r=this._deviceInfoMapper.getDeviceId(e.id),i=this._deviceInfoMapper.scrubDeviceLabel(e.name),a=J0(),o=(e,t,n)=>{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.deviceSelection,kindOfEvent:e,correlationId:a,timestampInfo:t===void 0?{}:{deltaTimeInMs:t},additionalDetails:n===void 0?``:{failureReason:n.message,code:n.code,...J3(n)},deviceSelection:{deviceId:r,deviceName:i,deviceType:`Speaker`}})};o(`attempt`);let s=Date.now();try{await this._tsDeviceManager.selectDevicesAsync?.({speaker:e.id}),await n.catch((t=>{if(this._selectedSpeaker?.id!==e.id)throw t})),o(`success`,Date.now()-s)}catch(e){let t;throw t=new Y(e?.message===`timeout`?{defaultError:J.DEVICE_MANAGER.SELECT_SPEAKER_TIMEOUT}:{defaultError:J.DEVICE_MANAGER.SELECT_SPEAKER_FAIL,originalError:e}),o(`failure`,Date.now()-s,t),t}}else t.warn(`device is already selected`)}async askDevicePermission(e){return this.getAskDevicePermissionPromise(e,C3.Public_App)}async startPreheatDevices(e){let{audio:t,video:n}=e,r=Date.now(),i=J0(),a=(e,a)=>{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.startPreheatDevices,kindOfEvent:`failure`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...J3(e),context:a},correlationId:i})};try{if(this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.startPreheatDevices,kindOfEvent:`attempt`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{},additionalDetails:{},correlationId:i}),this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});if(!Z().calling.devicePermissions.isPreheatEnabled)throw new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_DISABLED});if(!t?.preheat&&!n?.preheat||t?.preheat&&typeof t?.preheat!=`boolean`||n?.preheat&&typeof n?.preheat!=`boolean`||t?.timeoutInSec&&!t.preheat||n?.timeoutInSec&&!n?.preheat||t?.timeoutInSec&&isNaN(t?.timeoutInSec)||t?.timeoutInSec&&t?.timeoutInSec<=0||n?.timeoutInSec&&isNaN(n?.timeoutInSec)||n?.timeoutInSec&&n?.timeoutInSec<=0)throw new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_INVALID_CONFIG});if(t?.preheat&&this._tsRawAudioStream)throw new Y({defaultError:J.DEVICE_MANAGER.AUDIO_ALREADY_PREHEATED});if(n?.preheat&&this._tsRawVideoStream)throw new Y({defaultError:J.DEVICE_MANAGER.VIDEO_ALREADY_PREHEATED})}catch(e){let a=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_FAIL,originalError:e});throw this.logger.error(a.message),this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.startPreheatDevices,kindOfEvent:`failure`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{failureReason:a.message,code:a.code,subCode:a.subCode,...J3(a)},correlationId:i}),a}try{if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});let e=[];try{e=await this._tsDeviceManager.enumerateDevicesAsync()}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREAHEAT_ENUMERATE_DEVICES_FAIL,originalError:e});throw this.logger.error(t.message),t}let o=!1,s=!1;if(t?.preheat){let t=e.filter((e=>e.kind===2)),n=e.filter((e=>e.kind===3));t[0]?.id!==`microphone:`&&n[0]?.id!==`speaker:`||(o=!0)}if(n?.preheat&&e.filter((e=>e.kind===1))[0]?.id===`camera:`&&(s=!0),o||s){let e=await this.getAskDevicePermissionPromise({audio:o,video:s},C3.StartPreheatDevices);if(o&&!e.audio)throw new Y({defaultError:J.DEVICE_MANAGER.AUDIO_PREHEAT_NO_PERMISSION});if(s&&!e.video)throw new Y({defaultError:J.DEVICE_MANAGER.VIDEO_PREHEAT_NO_PERMISSION})}if(t?.preheat){try{this._tsRawAudioStream=this.getRawDeviceMediaStream(0)}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_DM_AUDIO_STREAM_FAIL,originalError:e});throw this.logger.error(t.message),t}this._tsRawAudioStream?.changed((()=>{this._tsRawAudioStream?.getMediaStream().catch((e=>{let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_AUDIO_STREAM_FAIL,originalError:e}),n=K3(e,this.isWBMediaClient,t);this.logger.error(n.message),a(n,`changed event`)}))}));try{await this._tsRawAudioStream?.getMediaStream()}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_AUDIO_STREAM_FAIL,originalError:e}),n=K3(e,this.isWBMediaClient,t);throw this.logger.error(n.message),n}t?.timeoutInSec&&t.timeoutInSec>0&&(this._preheatedAudioStreamTimeout=setTimeout((()=>{this._tsRawAudioStream?.dispose(),this._tsRawAudioStream=void 0}),1e3*t?.timeoutInSec))}if(n?.preheat){try{this._tsRawVideoStream=this.getRawDeviceMediaStream(1)}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_DM_VIDEO_STREAM_FAIL,originalError:e});throw this.logger.error(t.message),t}this._tsRawVideoStream?.changed((()=>{this._tsRawVideoStream?.getMediaStream().catch((e=>{let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_VIDEO_STREAM_FAIL,originalError:e});this.logger.error(t.message),a(t,`changed event`)}))}));try{await this._tsRawVideoStream?.getMediaStream()}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_VIDEO_STREAM_FAIL,originalError:e});throw this.logger.error(t.message),t}n?.timeoutInSec&&n?.timeoutInSec>0&&(this._preheatedVideoStreamTimeout=setTimeout((()=>{this._tsRawVideoStream?.dispose(),this._tsRawVideoStream=void 0}),1e3*n?.timeoutInSec))}this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.startPreheatDevices,kindOfEvent:`success`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{},correlationId:i})}catch(e){if(t?.preheat)try{this._tsRawAudioStream?.dispose()}catch{}finally{this._tsRawAudioStream=void 0,this._preheatedAudioStreamTimeout&&=(clearTimeout(this._preheatedAudioStreamTimeout),void 0)}if(n?.preheat)try{this._tsRawVideoStream?.dispose()}catch{}finally{this._tsRawVideoStream=void 0,this._preheatedVideoStreamTimeout&&=(clearTimeout(this._preheatedVideoStreamTimeout),void 0)}let r=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_FAIL,originalError:e});throw this.logger.error(r.message),a(r,`api call`),r}}stopPreheatDevices(e){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let{audio:t,video:n}=e,r=Date.now(),i=J0();try{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.stopPreheatDevices,kindOfEvent:`attempt`,audio:t||!1,video:n||!1,timestampInfo:{},additionalDetails:{},correlationId:i}),t&&(this._tsRawAudioStream?.dispose(),this._tsRawAudioStream=void 0,this._preheatedAudioStreamTimeout&&=(clearTimeout(this._preheatedAudioStreamTimeout),void 0)),n&&(this._tsRawVideoStream?.dispose(),this._tsRawVideoStream=void 0,this._preheatedVideoStreamTimeout&&=(clearTimeout(this._preheatedVideoStreamTimeout),void 0)),this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.stopPreheatDevices,kindOfEvent:`success`,audio:t||!1,video:n||!1,timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{},correlationId:i})}catch(e){let a=new Y({defaultError:J.DEVICE_MANAGER.STOP_PREHEAT_FAIL,originalError:e});throw this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.stopPreheatDevices,kindOfEvent:`failure`,audio:t||!1,video:n||!1,timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{failureReason:a.message,code:a.code,subCode:a.subCode,...J3(a)},correlationId:i}),a}}getAskDevicePermissionPromise(e,t){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let n={audio:!!e.audio,video:!!e.video};if(!e.audio&&!e.video)throw new Y({defaultError:J.DEVICE_MANAGER.ONE_PERMISSION_ATLEAST});let r=this.getKeyForConstrains(n),i=this._combinedDevicePermission.get(r);return i?this.logger.info(`askDevicePermission attempt: audio:${n.audio}, video:${n.video} on pending existing request ${F4(i)}`):(i=this.askDevicePermissionInternal(n,t),this._combinedDevicePermission.set(r,i),i.finally((()=>{this._combinedDevicePermission.delete(r)}))),i}getKeyForConstrains(e){return Object.keys(e).filter((t=>e[t])).toString()}async askDevicePermissionInternal(e,t){this.logger.info(`askDevicePermission attempt: audio:${e.audio}, video:${e.video}`);let n=J0(),r=+new Date;this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_attempt,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,cause:t});try{if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});let i=[];if(Z().calling.devicePermissions.splitAskAudioVideo){this.logger.info(`askDevicePermission, split permission check`);let t=[];e.audio&&(this.logger.info(`askDevicePermission, split permission audio`),t.push(this._tsDeviceManager.askDevicePermission({audio:e.audio,video:!1}))),e.video&&t.push((async t=>new Promise(((n,r)=>{let i=async()=>{if(this.logger.info(`askDevicePermission, split permission video`),!this._tsDeviceManager){let e=`askDevicePermission, split permission video failed device manager not found`;this.logger.error(e),r(e);return}try{n(await this._tsDeviceManager.askDevicePermission({audio:!1,video:e.video}))}catch(e){r(e)}};t?window.setTimeout(i,t):i()})))(Z().calling.devicePermissions.timeoutInBetween));let n=await Promise.allSettled(t),r={audio:!1,video:!1};n.forEach((e=>{e.status===`fulfilled`&&e?.value&&(r={audio:r.audio||!!e?.value?.audio,video:r.video||!!e?.value?.video}),e.status===`rejected`&&e?.reason&&i.push(e.reason)}));let a=this._permissionChangedTasks.then((()=>this.permissionsChanged(r,e)));this._permissionChangedTasks=a,this._permissionChangedTasks.catch(M4),await a,this._safariVideoPermissionState=this._videoDevicePermission?`granted`:`denied`}else{let t=await this._tsDeviceManager.askDevicePermission({audio:e.audio,video:e.video}),n=this._permissionChangedTasks.then((()=>this.permissionsChanged(t,e)));this._permissionChangedTasks=n,this._permissionChangedTasks.catch(M4),await n}if(e?.audio&&!this._audioDevicePermission||e?.video&&!this._videoDevicePermission)this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_failure,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,cause:t},new Y({defaultError:J.DEVICE_MANAGER.PERMISSION_NOT_GRANTED_OR_FAILED,defaultErrorMessageArgs:[F4(i)]}));else{let i=+new Date;this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_success,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:i-r,cause:t})}}catch(i){let a=new Y({defaultError:J.DEVICE_MANAGER.ADP_FAIL,originalError:i}),o=+new Date;this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_failure,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:o-r,cause:t},a)}return{audio:!!this._audioDevicePermission,video:!!this._videoDevicePermission}}sendAskDevicePermissionEvent(e,t){try{let n,r,i;t&&(n=typeof t?.message==`string`?t?.message:void 0,r=J3(t)),e.deltaTimeInMs&&(i=e.deltaTimeInMs>25e3),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:{audioPermissionGranted:this.nullHandler(e.audioPermissionGranted),videoPermissionGranted:this.nullHandler(e.videoPermissionGranted),audioPermissionRequested:e.audioPermissionRequested,videoPermissionRequested:e.videoPermissionRequested,correlationId:e.correlationId||``,failureReason:n||``,deltaTimeInMs:e.deltaTimeInMs||``,deltaTimeGreaterThanJAMATimeout:this.nullHandler(i),cause:e.cause||``,additionalDetails:{...r}}})}catch{this.logger.debug(`Unable to send audio video permission failure success telemtery`)}}sendDeviceManagerEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send device selection telemetry`)}}nullHandler(e){return e===void 0?``:e}};N9([UG,P9(`design:type`,Object)],F9.prototype,`logger`,void 0),N9([YG(d4.GetCameras),P9(`design:type`,Function),P9(`design:paramtypes`,[]),P9(`design:returntype`,Promise)],F9.prototype,`getCameras`,null),N9([YG(d4.GetMicrophones),P9(`design:type`,Function),P9(`design:paramtypes`,[]),P9(`design:returntype`,Promise)],F9.prototype,`getMicrophones`,null),N9([JG(d4.GetSpeakers),P9(`design:type`,Function),P9(`design:paramtypes`,[]),P9(`design:returntype`,Promise)],F9.prototype,`getSpeakers`,null),N9([YG(d4.SelectMicrophone),P9(`design:type`,Function),P9(`design:paramtypes`,[Object]),P9(`design:returntype`,Promise)],F9.prototype,`selectMicrophone`,null),N9([YG(d4.SelectSpeaker),P9(`design:type`,Function),P9(`design:paramtypes`,[Object]),P9(`design:returntype`,Promise)],F9.prototype,`selectSpeaker`,null),N9([YG(d4.AskDevicePermission),P9(`design:type`,Function),P9(`design:paramtypes`,[Object]),P9(`design:returntype`,Promise)],F9.prototype,`askDevicePermission`,null),N9([YG(d4.StartPreheatDevices),P9(`design:type`,Function),P9(`design:paramtypes`,[Object]),P9(`design:returntype`,Promise)],F9.prototype,`startPreheatDevices`,null),N9([JG(d4.StopPreheatDevices),P9(`design:type`,Function),P9(`design:paramtypes`,[Object]),P9(`design:returntype`,void 0)],F9.prototype,`stopPreheatDevices`,null);var HRe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},I9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},URe=class extends W7{get info(){return this._teamsCall.info}constructor(e){super(e,KG.TeamsIncomingCall),this._teamsCall=e}async accept(e){if(!B4(this._teamsCall.acsProxy,this._teamsCall.acsCustomRelayManager,!0))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._teamsCall.accept(e),this._teamsCall}};HRe([YG(c4.Accept),I9(`design:type`,Function),I9(`design:paramtypes`,[Object]),I9(`design:returntype`,Promise)],URe.prototype,`accept`,null);var L9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},R9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},z9=class extends B7{get info(){return this._info}constructor(e,t,n,r){super(e,t,n,r,GG.TeamsCall),this._musicOnHoldEnabled=!1,this._hasFetchedPolicies=!1,this._info=this.callInfo,this._isEmergencyCall=e.isEmergencyNumber,this._mtPolicyService=t.mtPolicyService}async startCallInternal(e,t,n,r,i,a,o){if(this.logger.info(`==> Emergency startCallInternal:TeamsCall.ts`),this._mtPolicyService&&this._mtPolicyService.isFetchUserPoliciesAndSettingsApplicable(!0,o)){this._mtPolicyService.userDialedNumber(Array.isArray(o)?o[0].phoneNumber:o.phoneNumber);let e=``,t=!0;try{this.logger.info(`Fetching Teams User policy from MiddleTier Service`);let e={policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`EmergencyPolicies`],userProperties:[`evEnabled`,`PoliciesMetadata`]};await this._mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(this.tsCall.callId,this._callAgent.getUserMri(),e)}catch(e){t=!1,this.logger.warn(`Fetching Teams user policy from ACS MiddleTier Service failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.\n Proceeding as normal pstn call`)}if(t){try{this.enforcePolicyAndLicenseRestrictions()}catch(e){this.handlePolicyAndLicenseRestrictionsFailure(e);return}try{this.logger.info(`Deriving emergency content from fetched policies and settings`),e=this._mtPolicyService.getEmergencyContent()}catch(e){this.logger.warn(`Error deriving emergency content from fetched policies and settings. \n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}. Proceeding as normal pstn call`)}r&&(r.emergencyContent=e||``,r.isEmergency=e?.trim().length>0||!1,this._isEmergencyCall=r.isEmergency)}}if(o){let t=[];Array.isArray(o)?t=o:t.push(o),this._isEmergencyCall&&t.length==1&&(this.logger.info(`user dialed number (${t[0].phoneNumber}) resolved to actual emergency number (${this._mtPolicyService.getEmergencyNumber()} during startCall`),t[0]={phoneNumber:this._mtPolicyService.getEmergencyNumber()}),t.length>1&&await this.setupThreadIdWhenStartingGroupCall(t,e,r),t.forEach((e=>{this.tsCall.addParticipant(K2(e)).catch((()=>{this.logger.error(`Failed to add participant during call start`)}))})),this.logger.info(`Paticipant added during startCall`)}return this._allowBreakoutRoomJoin=Z().calling.breakoutRooms.enabled&&this._mtPolicyService.isBreakoutRoomsAllowed()&&!!n,this._allowIPAudio=this._mtPolicyService.isIPAudioAllowed(),this._allowIPVideo=this._mtPolicyService.isIPVideoAllowed(),super.startCallInternal(e,t,n,r,i,a)}dispose(){super.dispose(),this._extensibleApi.dispose()}get isEmergencyCall(){return this._isEmergencyCall}addParticipant(e,t){let n=+new Date,r=J0();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{attemptTimestamp:n},additionalDetails:{customContext:{userToUserPresent:!!t?.customContext?.userToUser,xHeadersPresent:!!t?.customContext?.xHeaders&&t?.customContext.xHeaders.length>0}}});try{t7(c4.AddParticipant,this.state),Y2(e)}catch(e){let t=new Y({defaultError:J.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...J3(t)}}),t}if(!B4(this.acsProxy,this.acsCustomRelayManager,!0)){let e=new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...J3(e)}}),e}if(this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)))){let t=new Y({defaultError:J.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[OG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:t.code,failureReason:t.message,...J3(t)}}),t}if(this.tsCall.threadId&&cTe(this.tsCall.threadId))try{if(this.IsTargetUserAllowed(e))throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TARGET_TYPE})}catch(e){throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...J3(e)}}),this.logger.error(e),e}let i=this.getOrCreateRemoteParticipant(q2(K2(e))),a=``;return this.GetOrCreateGroupChatThread(!!t?.threadId,e,t).then((o=>{o&&((t??={}).threadId=o,a=o,this._info.setThreadId(o)),this.addParticipantToTsCall(e,a,t,i,r,n)})).catch((e=>{throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...J3(e)}}),e})),i}async removeParticipant(e){let t=+new Date,n=J0();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{attemptTimestamp:t}});try{t7(c4.RemoveParticipant,this.state),Y2(e)}catch(e){let r=new Y({defaultError:J.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:e.code,failureReason:e.message,...J3(r)}}),r}let r=this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)));if(!r){let r=new Y({defaultError:J.CALL.PARTICIPANT_NOT_IN_CALL,originalError:[OG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:r.code,subCode:r.subCode,failureReason:r.message,...J3(r)}}),r}try{await this.tsCall.removeParticipant(K2(e)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t}})}catch(e){let{callEndReason:i}=W3(this,r.tsRemoteParticipant,e);r.callEndReason||r.setCallEndReason(i);let a=Y3(i);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:a?.callEndReason.code,subCode:a?.callEndReason.subCode,failureReason:a?.callEndReason.message,...a}}),new Y({defaultError:{message:i.message,code:i.code,subCode:i.subCode||0,resultCategories:i.resultCategories},originalError:e})}}async mute(){super.mute()}async unmute(){super.unmute()}async hold(){if(this.tsCall.state===4)return void this.logger.info(`Call already on hold`);if(!Z().calling.musicOnHoldEnabled)return this.logger.warn(`Music on Hold is not enabled`),super.hold();let e=+new Date,t=J0();if(this._causeId=PG(),this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Hold,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:S4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),!this._hasFetchedPolicies)try{this.logger.info(`Fetching Teams Calling Policy from Azure Communication Services`),await this._mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(this.tsCall.callId,this._callAgent.getUserMri(),{policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`TeamsCallingPolicy`]}),this._hasFetchedPolicies=!0,this._isTeamsExtensionUser&&!Z().calling.teamsExtensionSettings.enableMoh?(this._musicOnHoldEnabled=!1,this.logger.info(`Music on Hold is disabled for Teams Extension User`)):this._musicOnHoldEnabled=this._mtPolicyService.isMoHEnabled(),this.logger.info(`Music on Hold is `+(this._musicOnHoldEnabled?`enabled`:`disabled`))}catch(e){this.logger.warn(`Fetching Teams Calling Policy from Azure Communication Services failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.`)}return this._musicOnHoldEnabled?(Z().calling.turnOffScreenShareBeforeHold&&this.tsCall.isScreenSharingOn&&await this.tsCall.stopScreenSharing().then((()=>{this.logger.log(`Successfully turned off screen sharing before hold`)})).catch((()=>{this.logger.error(`Failed to turn off screensharing before hold`)})),await this.tsCall.hold(void 0,this._causeId,{isLocal:!0},1).then((async()=>{this.logger.info(`Successfully detached devices as part of Hold`),await this.tsCall.park(3,this._causeId).then((()=>{let n=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Hold,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{holdType:S4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),this.logger.info(`Successful park() as part of hold, Music on Hold completed successfully`)}))})).catch((()=>{let n=+new Date,r=new Y({defaultError:J.CALL.HOLD_CALL});throw this.logger.warn(`Attempting to perform Music on Hold failed.\n Error message = ${r.message}, code = ${r.code}, subcode = ${r.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Hold,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,holdType:S4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...J3(r)}}),r}))):(this.logger.info(`Fetching of Teams Calling Policy failed or Music on Hold Disabled, proceeding with standard hold`),super.hold())}async resume(){if(this._musicOnHoldEnabled){let e=+new Date,t=J0();return this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Resume,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:S4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),await this.tsCall.unpark(3,this._causeId).then((async()=>{this.logger.info(`Successful unpark() as part of resume`),await this.tsCall.unhold(void 0,this._causeId).then((()=>{let n=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Resume,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{holdType:S4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),this.logger.info(`Successful unhold() as part of resume, resume completed successfully`)}))})).catch((()=>{let n=+new Date,r=new Y({defaultError:J.CALL.RESUME_CALL});throw this.logger.warn(`Attempting to perform resume from Music on Hold failed.\n Error message = ${r.message}, code = ${r.code}, subcode = ${r.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Resume,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,holdType:S4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...J3(r)}}),r}))}return this.logger.info(`Music on Hold Disabled, proceeding with standard resume`),super.resume()}validateAndSetThreadId(e,t){if(!t?.threadId){let e=new Y({defaultError:J.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});throw this.logger.error(`Error Message = ${e.message}, code = ${e.code}, subcode = ${e.subCode}`),e}return this.validateThreadIdFormat(t?.threadId),t?.threadId}validateThreadIdFormat(e){if(!e.startsWith(`19`)){let e=new Y({defaultError:J.CALL.TEAMS_INVALID_THREAD_ID});throw this.logger.error(`Error Message = ${e.message}, code = ${e.code}, subcode = ${e.subCode}`),e}}enforcePolicyAndLicenseRestrictions(){let e=+new Date;if(!this._mtPolicyService.isEvEnabled()){let t=+new Date,n=new Y({defaultError:J.CALL.CTE_VOICE_NOT_ENABLED});this.logger.error(`Error Message = ${n.message}, code = ${n.code}, subcode = ${n.subCode}`);let r=this._callAgent.getEcsConfigIds();throw this.sendCallStageEvent({eventName:Q.acs_calling_call_failed,correlationId:J0(),timestampInfo:{deltaTimeInMs:t-e},additionalPayload:{additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this.isEmergencyCall,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:r.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:r.SkypeWebMedia},additionalDetails:{...J3(n)}}},n,{code:n.code,subCode:n.subCode,phrase:n.message}),n}}handlePolicyAndLicenseRestrictionsFailure(e){this._callEndReason={message:`Unknown`,code:e?.code,subCode:e?.subCode,resultCategories:e?.resultCategories},this._state=`Disconnected`,this._eventEmitter.emit(`stateChanged`),this._callAgent.handleCallRemoved(this.tsCall)}async setupThreadIdWhenStartingGroupCall(e,t,n){if(t&&t.threadId&&(this.validateThreadIdFormat(t.threadId),this.logger.info(`ThreadId is already provided in the options parameter: `+JSON.stringify(t))),t===void 0||!t.threadId){let r=[];e.forEach((e=>{r.push({id:K2(e)})}));try{let e=await this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:Z().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:r});t||={},t.threadId=e,e&&this._info.setThreadId(e),n&&e&&(n.threadId=e)}catch(e){if(!Z().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(`Failed to create thread Id for Teams group call `+e)}}}async GetOrCreateGroupChatThread(e,t,n){let r=``;if(Yle(t))return this.logger.info(`Adding TeamsExtensionUserIdentifierto call`),Promise.resolve(r);if(e)return this.logger.info(`Customer provided threadId in options: `+JSON.stringify(n)),r=this.validateAndSetThreadId(t,n),Promise.resolve(r);let i=sTe(lTe(this),OG(t));if(Z().calling.enableOpsSmePassFakeConversation&&i)return r=this.tsCall.threadId||H4(),Promise.resolve(r);if(!Z().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation)throw new Y({defaultError:J.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});if(this._info.threadId!==null&&this._info.threadId!==void 0){r=this._info.threadId;let e=[];return e.push({id:K2(t)}),await this._mtPolicyService.AddParticipantsToThread(this.tsCall.callId,{threadId:r,addParticipantsSuffix:Z().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix,participants:e}).catch((t=>{this.logger.warn(`Error when adding participants `+JSON.stringify(e)+` to thread. `+t)})),Promise.resolve(r)}{let e=[];return this._remoteParticipants.forEach((t=>{e.push({id:K2(t.identifier)})})),e.push({id:K2(t)}),await this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:Z().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:e}).then((e=>{r=e,this.logger.info(`Add participant into 1on1 call to convert it into Teams group call. Create thread id: `+r)})).catch((e=>{let n=`Error when adding participants `+K2(t)+` to thread to create a Teams group call. `;if(!Z().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(n+e)})),Promise.resolve(r)}}addParticipantToTsCall(e,t,n,r,i,a){this.tsCall.addParticipant(K2(e),{threadId:t,customHeaderContext:U4(n)}).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`add`,correlationId:i,timestampInfo:{deltaTimeInMs:+new Date-a}})})).catch((t=>{let{callEndReason:n}=W3(this,r.tsRemoteParticipant,t);r.callEndReason||r.setCallEndReason(n);let o=Y3(n);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:i,timestampInfo:{deltaTimeInMs:+new Date-a},additionalDetails:{code:o?.callEndReason.code,subCode:o?.callEndReason.subCode,failureReason:o?.callEndReason.message,...o}}),this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)))&&(this.deleteRemoteParticipant(r),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:[r]}))}))}IsTargetUserAllowed(e){return Xle(e)||TG(e)||wG(e)}};L9([XG(c4.AddParticipant),JG(c4.AddParticipant),R9(`design:type`,Function),R9(`design:paramtypes`,[Object,Object]),R9(`design:returntype`,Object)],z9.prototype,`addParticipant`,null),L9([XG(c4.RemoveParticipant),YG(c4.RemoveParticipant),R9(`design:type`,Function),R9(`design:paramtypes`,[Object]),R9(`design:returntype`,Promise)],z9.prototype,`removeParticipant`,null),L9([XG(c4.Mute),R9(`design:type`,Function),R9(`design:paramtypes`,[]),R9(`design:returntype`,Promise)],z9.prototype,`mute`,null),L9([XG(c4.Unmute),R9(`design:type`,Function),R9(`design:paramtypes`,[]),R9(`design:returntype`,Promise)],z9.prototype,`unmute`,null),L9([XG(c4.Hold),YG(c4.Hold),R9(`design:type`,Function),R9(`design:paramtypes`,[]),R9(`design:returntype`,Promise)],z9.prototype,`hold`,null),L9([XG(c4.Resume),YG(c4.Resume),R9(`design:type`,Function),R9(`design:paramtypes`,[]),R9(`design:returntype`,Promise)],z9.prototype,`resume`,null);var B9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},V9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},H9=class e extends Z7{get calls(){return this._calls}constructor(e,t,n,r,i,a){super(e,t,r,i,n,WG.TeamsCallAgent,a),this._calls=[],this.handleCallAdded=e=>{if(!this._calls.find((t=>t.id===e.callId))){let t=e.on(`callStateChanged`,(async()=>{if(e.state===1){let n=G6(e),r=e.callId;t.dispose();let i=new z9({callId:r,isIncoming:!0},this,e,this._telemetryLogManager);n&&(i=Q7(i));let a=new URe(i);this.handleCallState(i),n?await Promise.all(i.bindTsCall()):i.bindTsCall(),this._eventEmitter.emit(`incomingCall`,{incomingCall:a})}}))}},this.handleCallRemoved=e=>{this.logger.info(`removing callId=${e.callId}`);let t=this._calls.find((t=>t.id===e.callId));if(t){if(t.isBreakoutRoomCall){let e=Z().calling.breakoutRooms.hangUpCallDelayInMilliSeconds;setTimeout((()=>{this.disposeCall(t)}),e)}else this.disposeCall(t);this._eventEmitter.emit(`callsUpdated`,{added:[],removed:[t]}),this.logger.info(`call removed`)}},this.handleCallState=e=>{e.on(`stateChanged`,(async()=>{try{e.state===`Disconnected`?this.tsStack?(await this._tsCallRegistry.deleteCallAsync?.(e.tsCall)||this.logger.info(`The call has been removed from registry, call id: ${e.id}`),e.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(e.id).catch((()=>{this.logger.error(`Failed to flush telemetry log manager events`)}))):this.logger.info(`Unable to remove call from registry`):e.state===`Connecting`&&e.direction==`Incoming`&&(this.addToCallArray(e),this._eventEmitter.emit(`callsUpdated`,{added:[e],removed:[]}))}catch{this.logger.error(`Failed to handle call state changed event`)}}))},this.logger=t}createNewCall(e,t){let n=new z9({callId:e},this,t,this._telemetryLogManager);return G6(t)?Q7(n):n}addToCallArray(e){this._calls.push(e),this.trackCallEndTimeToStopTelemetry(this._calls)}addToCallAgentsMap(t){e.teamsCallAgents.get(t?.identityMri)&&j4(J.CALL_AGENT.TEAMS_CALLAGENT_ALREADY_EXSISTS,this.logger),e.teamsCallAgents.set(t?.identityMri,this)}removeFromCallAgentsMap(t){t?.identityMri&&e.teamsCallAgents.get(t?.identityMri)===this&&e.teamsCallAgents.delete(t?.identityMri)}disposeCall(e){let t=this._calls.indexOf(e);t!==-1&&this._calls.splice(t,1),e.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls)}getMiddleTierServiceInstance(){return this.mtPolicyService}async setUserPoliciesOnAgentInitialization(){super.setUserPoliciesOnAgentInitialization();try{if(this.isEnterpriseUser()){let e=J0();this.logger.info(`ACS MiddleTier service called on Teams Call Agent initialization with call Id=${e}`),await this.mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(e,this.getUserMri(),{policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`EmergencyPolicies`,`TeamsCallingPolicy`,`TeamsMeetingPolicy`],userProperties:[`FeatureTypes`,`PoliciesMetadata`,`phoneNumber`,`sipUri`,`hostType`,`accountEnabled`,`useTeamsCalling`,`evEnabled`,`region`,`routingType`,`preferredDataLocation`,`featureTypes`,`displayName`]}),this._userPolicies=this.mtPolicyService.getUserPolicy(),this._userProperties=this.mtPolicyService.getUserProperties(),this.logger.info(`****User policy initialized to ${JSON.stringify(this._userPolicies)}`),this.logger.info(`****User properties initialized to ${JSON.stringify(this._userProperties)}`)}}catch(e){this.logger.warn(`Fetching Teams user policy and Properties from ACS MiddleTier Service failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.`)}}async disposeInternal(t){let n=+new Date,r=J0();this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeTeamsCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});try{if(this._disposed)throw new Y({defaultError:J.CALL_AGENT.CTE_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&e.teamsCallAgents.delete(this._parsedTokenCredential?.identityMri);for(let e of this._calls)e.state!==`Disconnected`&&await e.hangUp().catch((()=>{this.logger.error(`Failed to hangup call during Teams call agent dispose`)}));await this._tsCallRegistry?.dispose();let t=this._tokenFetchTries>this._maxNmberOfRetries;await this._callStack.disposeUserStack(t),this.offTrouterStateChanged(this._trouterStateChangeCallback),this._callStack.offRegisteredChanged(this._registrarStateChangeCallback),this._eventEmitter.removeAllListeners(),this._internalEventEmitter.emit(`disposed`),this._internalEventEmitter.removeAllListeners(),this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:``})}catch(e){let t=new Y({defaultError:J.CALL_AGENT.TEAMS_DISPOSE_FAIL,originalError:e});throw this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeTeamsCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}}),t}finally{t&&this._telemetryLogManager.clearTelemetryLoggers()}}startCall(e,t){let n=J0(),r=+new Date,i={correlationId:n,timestampInfo:{attemptTimestamp:r}};this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_attempt,tenant:p2,properties:i},void 0,`attempt`);try{let i;if(this.assertParticipants(e),Array.isArray(e)){if(this.isTeamsExtensionUser()&&!Z().calling.teamsExtensionSettings.enableJoinCall)throw new Y({defaultError:J.FEATURES.ONE_PHONE_SYSTEM.CALL_CANNOT_BE_STARTED});if(i=t,e.length>1&&!Z().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation&&!i?.threadId)throw new Y({defaultError:J.CALL_AGENT.GROUPCALL_THREADID});if(e.length==1&&i?.threadId)throw new Y({defaultError:J.CALL_AGENT.ONE_TO_ONE_THREADID})}else{if(this.isTeamsExtensionUser()&&!Z().calling.teamsExtensionSettings.enableStartCall)throw new Y({defaultError:J.FEATURES.ONE_PHONE_SYSTEM.CALL_CANNOT_BE_STARTED});i=t}if(Z().calling.enableSmePassFakeConversation&&this.isAcsToTeamsInteropCall(e)&&!this.isTeamsExtensionUser())throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TARGET_TYPE});let a=i?.audioOptions?.muted;return a===void 0&&(a=!1),this.logger.info(`startCall with video=${!!i?.videoOptions},muted=${a}`),this.createCall({participants:e,startCallOptions:i},{correlationId:n,attemptTimestamp:r})}catch(e){let t,i;throw e instanceof Y&&(t=typeof e?.message==`string`?e?.message:void 0,i={...J3(e)}),this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_failed,tenant:p2,properties:{correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-r},failureReason:t||``,additionalDetails:i||{}}},void 0,`failure`),e}finally{this._telemetryLogManager.deleteEventMapByCorrelationId(n)}}join(e,t){this.assertCallContext(e);let n=!!t?.audioOptions?.muted;return this.logger.info(`join with video=${!!t?.videoOptions},muted=${n}`),this.createCall({teamsCallContext:e,startCallOptions:t})}async dispose(){await this.disposeInternal(!0)}on(e,t){if(e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}createCall(e,t){if(!this.tsStack)throw new Y({defaultError:J.CALL_AGENT.STACK_NOT_INIT});let n,r,i,a=e?.teamsCallContext?.threadId,o=!1,s=e?.teamsCallContext?.meetingLink,c=e?.teamsCallContext?.meetingId,l=e?.teamsCallContext?.passcode||``,u=!!e?.participants&&Array.isArray(e?.participants)&&e?.participants.length>1;if(this.isEnterpriseUser()&&u&&(a=(e?.startCallOptions).threadId),!B4(this.acsProxy,this.acsCustomRelayManager,!0))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});if(s)if(vFe(s))r=P5(s);else{if(!yFe(s,this.logger))throw new Y({defaultError:J.CALL_AGENT.INVALID_MEETING_LINK});if(bFe(s.trim().toLocaleLowerCase(),Z().calling.tfl.hosts))throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TFL_MEETING_JOIN});o=!0}e?.teamsCallContext?.threadId&&e?.teamsCallContext?.organizerId&&e?.teamsCallContext?.tenantId&&(r={threadId:e?.teamsCallContext?.threadId,messageId:e?.teamsCallContext?.messageId?e?.teamsCallContext?.messageId.toString():`0`,organizerId:e?.teamsCallContext?.organizerId,tenantId:e?.teamsCallContext?.tenantId}),r&&(i={meetingType:r.messageId===`0`?1:2,tenantId:r.tenantId,organizerId:r.organizerId,replyChainMessageId:r.messageId},a=r.threadId,n=r.messageId);let d=this.mtPolicyService.isEmergencyNumber(this.isEnterpriseUser(),e?.participants),f=this.getOnBehalfOfMri(e,u,d),p={threadId:a||``,messageId:n||``,meetingInfo:i,mediaPeerType:2,onBehalfOf:f},m=G6(this._tsCallRegistry),h=PG(),g=J0(),_=J0();if(m){let r=Q7();return(async()=>{let i;i=c?await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:_,causeId:h,type:`MeetingData`,meetingData:{meetingCode:c,passcode:l,threadId:a}}):o?await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:_,causeId:h,type:`MeetingData`,meetingData:{meetingUrl:s}}):await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:_,causeId:h,type:`ThreadId`,threadId:a||``,messageId:n});let u=new z9({callId:g,isEmergencyNumber:d},this,i,this._telemetryLogManager);r.setTarget(u),this.addToCallArray(r),this.handleCallState(r);let f=n3();u.startCallInternal(e?.startCallOptions,!!c,e?.teamsCallContext,p,t,f,e?.participants).catch(M4),await Promise.all(u.bindTsCall()),await f.promise,this._eventEmitter.emit(`callsUpdated`,{added:[r],removed:[]})})().catch((e=>{})),r}{let r;r=c?this._tsCallRegistry.createCallWithMeetingData({meetingCode:c,passcode:l,threadId:a},g,_,h):o?this._tsCallRegistry.createCallWithMeetingData({meetingUrl:s},g,_,h):this._tsCallRegistry.createCall(a||``,g,_,n,h);let i=new z9({callId:g,isEmergencyNumber:d},this,r,this._telemetryLogManager);return this.addToCallArray(i),this.handleCallState(i),i.startCallInternal(e?.startCallOptions,!!c,e?.teamsCallContext,p,t,void 0,e?.participants).catch(M4),i.bindTsCall(),this._eventEmitter.emit(`callsUpdated`,{added:[i],removed:[]}),i}}getOnBehalfOfMri(e,t,n){let r=e?.startCallOptions?.onBehalfOfOptions?.userId;if(r){if(!Z().calling.sharedLineAppearance.enabled)throw this.logger.error(`SharedLineAppearance is disabled by ECS flag`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED});if((e?.startCallOptions).customContext&&!Z().calling.teamsExtensionSettings.enableCustomContext)throw new Y({defaultError:J.FEATURES.ONE_PHONE_SYSTEM.CUSTOM_CONTEXT_NOT_SUPPORTED});if(t)throw new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.GROUP_CALLS_NOT_SUPPORTED});if(!n){if(DG(r)&&!Z().calling.sharedLineAppearance.appOnBehalfOfEnabled)throw this.logger.error(`Start Teams call with onBehalfOf MicrosoftTeamsAppIdentifier is disabled by ECS flag`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED_FOR_APPLICATIONS});if(EG(r)){if(!Z().calling.sharedLineAppearance.userOnBehalfOfEnabled)throw this.logger.error(`Start Teams call with onBehalfOf MicrosoftTeamsUserIdentifier is disabled by ECS flag`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED});if(!this.getUserPolicy()?.teamsCallingPolicy?.allowDelegation)throw this.logger.error(`Start Teams call with onBehalfOf MicrosoftTeamsUserIdentifier is disabled by Teams calling policy`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED_BY_CALLING_POLICY})}return Zle(r)}this.logger.warn(`Emergency call cannot be made on behalf of another user, dropping the onBehalfOf options`)}}assertParticipants(e){Ywe(e,J.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),Jwe(e,J.CALL_AGENT.USERIDS_CANNOT_BE_NULL)}assertCallContext(e){if(!e||this.checkForAtLeastOneValidCallConfig(e)||this.checkForInvalidTeamsMeetingCoordinates(e))throw new Y({defaultError:J.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(e){return!e.threadId&&!e.meetingLink&&!e.meetingId}checkForInvalidTeamsMeetingCoordinates(e){return!e.threadId&&e.tenantId&&e.organizerId||e.threadId&&(e.organizerId&&!e.tenantId||!e.organizerId&&e.tenantId)}isAcsToTeamsInteropCall(e){let t=!1;return this.isEnterpriseUser()&&(Array.isArray(e)?e.length>=1&&e.find((e=>wG(e)))&&(t=!0):wG(e)&&(t=!0)),t}};H9.teamsCallAgents=new Map,B9([JG(s4.StartCall),V9(`design:type`,Function),V9(`design:paramtypes`,[Object,Object]),V9(`design:returntype`,Object)],H9.prototype,`startCall`,null),B9([JG(s4.Join),V9(`design:type`,Function),V9(`design:paramtypes`,[Object,Object]),V9(`design:returntype`,Object)],H9.prototype,`join`,null),B9([YG(s4.Dispose),V9(`design:type`,Function),V9(`design:paramtypes`,[]),V9(`design:returntype`,Promise)],H9.prototype,`dispose`,null);var WRe=class{constructor(){this._proxyInUse=!1;let e=ZW(`ACS-calling`);this.logger=new V6(e,[()=>`AcsProxy`])}get proxyInUse(){return this._proxyInUse}set proxyInUse(e){this._proxyInUse=e}get proxyUrl(){return this._proxyUrl?.toString()||``}set proxyUrl(e){if(e.length<4)throw new Y({defaultError:J.CALL_CLIENT.PROXY_SHORT_URL});e.slice(-1)!==`/`&&(e=e.concat(``,`/`));try{let t=new URL(e);if(t.protocol!==`https:`&&t.protocol!==`http:`)throw new Y({defaultError:J.CALL_CLIENT.PROXY_PROTOCOL});this._proxyUrl=t}catch(t){let n=new Y({defaultError:J.CALL_CLIENT.SETUP_PROXY,defaultErrorMessageArgs:[e],originalError:t});throw this.logger.error(n.message),n}}hasProxyUrl(){return!!this._proxyUrl}proxyfyUrl(e){let t=e;if(!this._proxyUrl)return this.logger.info(`Proxy url not defined, return original ${n4(t)}`),t;try{let e=new URL(t);t=`${`${e.protocol}//${this._proxyUrl.host}${this._proxyUrl.pathname}`}${e.host}${e.pathname}${e.search}`,this.logger.info(`Proxyfing url from ${n4(e)} to ${n4(t)}`)}catch(e){let t=`Failed proxyfy url with error: ${JSON.stringify(e)}, returning original`;this.logger.error(t)}return this._proxyInUse=!0,t}},GRe=class{constructor(){this._hasCustomRelay=!1,this._customRelayManagerInUse=!1;let e=ZW(`ACS-calling`);this._logger=new V6(e,[()=>`AcsCustomRelayManager`])}getRelayConfig(){return this._relayConfig}setRelayConfig(e){this._relayConfig={...e},this._logger.info(`Custom relay config provided`),this._hasCustomRelay=!0,this._createTsRelayManager()}get hasRelayConfig(){return this._hasCustomRelay}get customRelayManagerInUse(){return this._customRelayManagerInUse}set customRelayManagerInUse(e){this._customRelayManagerInUse=e}getTsRelayManager(){return this._tsRelayManager}_createTsRelayManager(){if(!this._hasCustomRelay||!this._relayConfig||this._relayConfig.iceServers.length<1)return void this._logger.warn(`No relay config provided. No op.`);let e=[];this._relayConfig.iceServers.forEach((t=>{t.urls.forEach((n=>{let r=this._getIndividualRelay(n,t?.username,t?.credential);e.push(r)}))})),this._tsRelayManager={initialize(){},queryRelaysAsync:t=>Promise.resolve(e)}}_getIndividualRelay(e,t,n){let r=3478,i=[],a=[],o=[b3.turn,b3.turns,b3.stun],s=[x3.tcp,x3.tls,x3.udp],c;try{c=new URL(e)}catch(t){throw new Y({defaultError:J.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[e],originalError:t})}let l=c.protocol.replace(`:`,``);if(!o.includes(l))throw new Y({defaultError:J.CALL_CLIENT.RELAY_UNRECOGNIZED_SCHEMA});let u,d=``;try{d=c.href.replace(/((turn)s?|stun):/,`https:`),u=new URL(d)}catch(e){throw new Y({defaultError:J.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[d],originalError:e})}let f=u.searchParams.get(`transport`)??``;s.includes(f)||(this._logger.warn(`Unknown transport protocol detected for the provided turn, defaulting to ${x3.udp}`),f=x3.udp);let p=u.port===``?this._extractPortFromUrl(c):Number(u.port);p||=(this._logger.warn(`Could not read port from relay url, defaulting to ${r}`),r);let m=u.hostname;return xwe(m)?i.push(m):a.push(m),{addresses:i,udpPort:f===x3.udp?p:void 0,tcpPort:f===x3.tcp?p:void 0,tlsPort:f===x3.tls?p:void 0,username:t??``,password:n??``,type:`turn`,fqdns:a}}_extractPortFromUrl(e){let t=e.href.match(owe)?.[0];return Number(t?.replace(`:`,``))}},KRe=class{constructor(e,t,n){this._eventEmitter=new E3.EventEmitter,this._removeListeners=[];let r=(e,r)=>{n()&&t.sendEvent({name:Q.acs_calling_page_hidden,tenant:p2,properties:{eventName:e,pageHidden:r}})},i=()=>{document.visibilityState===`hidden`?(e.debug(`Visibility changed to hidden`),r(`visibilityChange`,!0),this._eventEmitter.emit(`visibilityChange`,!0)):(e.debug(`Visibility changed to visible`),r(`visibilityChange`,!1),this._eventEmitter.emit(`visibilityChange`,!0))},a=()=>{e.debug(`Page show`),r(`pageShow`,!1),this._eventEmitter.emit(`pageShow`)},o=()=>{e.debug(`Page hide`),r(`pageHide`,!0),this._eventEmitter.emit(`pageHide`)};window.addEventListener(`visibilitychange`,i),this._removeListeners.push((()=>window.removeEventListener(`visibilitychange`,i))),window.addEventListener(`pageshow`,a),this._removeListeners.push((()=>window.removeEventListener(`pageshow`,a))),window.addEventListener(`pagehide`,o),this._removeListeners.push((()=>window.removeEventListener(`pagehide`,o)));let s=(e,r)=>{n()&&t.sendEvent({name:Q.acs_calling_orientation_changed,tenant:p2,properties:{orientation:e,isInitial:r}})},c=()=>{let t=screen.orientation.type;e.debug(`Orientation changed to ${t}`),s(t,!1),this._eventEmitter.emit(`orientationChanged`,t)},l=()=>window.innerHeight>window.innerWidth?`portrait-primary`:`landscape-primary`,u=``,d=()=>{let t=l();u!==t&&(e.debug(`Orientation changed to ${t}`),u=t,s(t,!1),this._eventEmitter.emit(`orientationChanged`,t))};screen?.orientation?.type?(screen.orientation.addEventListener(`change`,c),this._removeListeners.push((()=>screen.orientation.removeEventListener(`change`,c))),s(screen.orientation.type,!0)):(window.addEventListener(`resize`,d),this._removeListeners.push((()=>window.removeEventListener(`resize`,d))),s(l(),!0))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._eventEmitter.removeAllListeners(),this._removeListeners.forEach((e=>e()))}},qRe,U9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},W9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},JRe=1,G9=class e{get callAgent(){return this._callAgent}get teamsCallAgent(){return this._teamsCallAgent}get sdkDiagnosticInformation(){return this._sdkDiagnosticInformation}get telemetryLogManager(){return this._telemetryLogManager}setCallAgent(e){this._callAgent=e}setTeamsCallAgent(e){this._teamsCallAgent=e}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}constructor(e){this._disposed=!1,this._customProxyAndTurnInformation={proxy:null,turn:null},this.sendTelemetry=()=>{try{if(Z().telemetry.telemetryBeforeUnload&&this._callAgent&&this._callAgent._calls)for(let e of this._callAgent._calls)e.tsCall.sendLastKnownStats()}catch(e){this.logger.debug(`Error logging telemetry`,e)}};let t=+new Date;this.clientId=J0();let n=e?.logger||ZW(`ACS-calling`),r=JRe++;if(this._acsProxy=new WRe,this._acsCustomRelayManager=new GRe,this._vdi3Options=e?.vdi3,e?.networkConfiguration){e.networkConfiguration.proxy?.url&&(this._customProxyAndTurnInformation.proxy={...e.networkConfiguration.proxy},this._acsProxy.proxyUrl=this._customProxyAndTurnInformation.proxy.url),e.networkConfiguration.turn&&(this._customProxyAndTurnInformation.turn={...e.networkConfiguration.turn},this._acsCustomRelayManager.setRelayConfig(this._customProxyAndTurnInformation.turn));let t=this.getTelemetryTag();e.diagnostics?e.diagnostics.tags?e.diagnostics.tags.push(t):e.diagnostics.tags=[t]:e.diagnostics={tags:[t]}}this.logger=new V6(n,[()=>`CallClient${r}[${this.clientId}]`]),this._eventEmitter=new w6(this.logger),this._sdkDiagnosticInformation=tTe(Z2(),this.logger,e),this.diagnosticOptions=e?.diagnostics,this.firstPartyOptions=e?.firstPartyOptions,this._telemetryLogManager=new m3(this.logger,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager);try{this.sendCallClientInitEvent({eventName:Q.acs_calling_call_client_init,kindOfEvent:`attempt`,timestampInfo:``,additionalDetails:``}),Object.defineProperty(globalThis,C2,{value:r,writable:!0,enumerable:!1}),r===1&&Object.defineProperty(globalThis,S2,{value:this._telemetryLogManager,writable:!1,enumerable:!1}),this.logger.info(`created`),this._callStack=new M9(this.logger,this.clientId,this._telemetryLogManager,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager,this.firstPartyOptions?.encodedStreamsJsPath,this._vdi3Options),this._deviceManager=new F9(this.logger,this._callStack,this._telemetryLogManager),window.addEventListener(`beforeunload`,this.sendTelemetry),this._screenDeviceManager=new KRe(this.logger,this._telemetryLogManager,(()=>this._callAgent?.calls?this._callAgent.calls.length>0:!!this._teamsCallAgent?.calls&&this._teamsCallAgent.calls.length>0)),this._screenDeviceManager.on(`visibilityChange`,(e=>{if(e)try{r8().formFactor===`Mobile`&&Z().calling.hangUpCallOnPageHide&&(this._callAgent?.calls.forEach((e=>e.hangUp())),this._teamsCallAgent?.calls.forEach((e=>e.hangUp())))}catch(e){this.logger.error(`Unable to hangup call on page hide due to ${e}`)}})),this._extensibleApi=new F3(this.logger,{callClient:this},{callClient:this,telemetryLogManager:this._telemetryLogManager});let e=e7(k3.CallClientFeature);for(let t of e)t.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(t);this.sendCallClientInitEvent({eventName:Q.acs_calling_call_client_init,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:``})}catch(e){let n=new Y({defaultError:J.CALL_CLIENT.INIT_CALL_CLIENT,originalError:e});throw this.sendCallClientInitEvent({eventName:Q.acs_calling_call_client_init,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...J3(n)}}),n}}createInstance(t){return new e(t)}get acsProxy(){return this._acsProxy}get acsCustomRelayManager(){return this._acsCustomRelayManager}getSDKVersion(){return Z2()}async getEnvironmentInfoInternal(){return this._environmentInfos||=(await this._callStack.createStackBase(),hke()),this._environmentInfos}feature(e){return this._extensibleApi.getApiObjectInstance(e.callClientApiCtor)}async createCallAgent(e,t){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let n=+new Date,r=J0();this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});let{identityMri:i}=await P4(e);if(this._callAgent?._caConfigBag?.identityMri===i)return this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS CallAgent already exists in this call client for the given identity.`}}),this._callAgent;if(this._callAgent||this._teamsCallAgent){let e=new Y({defaultError:J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT});this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS CallAgent already exists in this call client.`,failureReason:e.message,code:e.code,subCode:e.subCode,...J3(e)}}),j4(J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger)}if(this._callAgent=n9.callAgents.get(i),this._callAgent)return this._callAgent.onDisposed((()=>{this._callAgent=void 0})),this._eventEmitter.emit(`callAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS Call Agent already exists for the given identity. Maybe have been created by another call client instance.`}}),this._callAgent;this.validateEmergencyCountryCode(t);try{return this._callAgent=new n9(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager,t),await this._callAgent.initialize(e,t),this._callAgent.onDisposed((()=>{this._callAgent=void 0})),this._eventEmitter.emit(`callAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS CallAgent created and initialized successfully.`}}),this._callAgent}catch(e){this._callAgent=void 0;let t=new Y({defaultError:J.CALL_CLIENT.CREATE_CALL_AGENT,originalError:e});throw this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}}),this._telemetryLogManager.clearTelemetryLoggers(),t}}async createTeamsCallAgent(e,t){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let n=+new Date,r=J0();this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createTeamsCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});let{identityMri:i,mriType:a}=await P4(e);if(a==n2.TeamsExtensionUser?this.logger.info(`TeamsCallAgent is TeamsExtensionUser type`):this.logger.info(`TeamsCallAgent is not TeamsUser type`),this._teamsCallAgent?._caConfigBag?.identityMri===i)return this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`Teams Call Agent already exists in this call client for the given identity.`}}),this._teamsCallAgent;if(this._callAgent||this._teamsCallAgent){let e=new Y({defaultError:J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT});this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createTeamsCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`Teams Call Agent already exists in this call client.`,failureReason:e.message,code:e.code,subCode:e.subCode,...J3(e)}}),j4(J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger)}if(this._teamsCallAgent=H9.teamsCallAgents.get(i),this._teamsCallAgent)return this._teamsCallAgent.onDisposed((()=>{this._teamsCallAgent=void 0})),this._eventEmitter.emit(`teamsCallAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`Teams Call Agent already exists for the given identity. Maybe have been created by another call client instance.`}}),this._teamsCallAgent;try{return this._teamsCallAgent=new H9(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager),await this._teamsCallAgent.initialize(e,t),this._teamsCallAgent.onDisposed((()=>{this._teamsCallAgent=void 0})),this._eventEmitter.emit(`teamsCallAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`TeamsCallAgent created and initialized successfully.`}}),this._teamsCallAgent}catch(e){this._teamsCallAgent=void 0;let t=new Y({defaultError:J.CALL_CLIENT.CREATE_TEAMS_CALL_AGENT,originalError:e});throw this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createTeamsCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}}),this._telemetryLogManager.clearTelemetryLoggers(),t}}async getDeviceManager(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});return this._callAgent&&this._callAgent?.callClient!==this?(await this._callAgent?.deviceManager.getDeviceManager(),this._callAgent?.deviceManager):(await this._deviceManager.getDeviceManager(),this._deviceManager)}async dispose(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let e=+new Date,t=J0();try{this._disposed=!0,this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeCallClient,kindOfEvent:`attempt`,timestampInfo:{},correlationId:t,additionalDetails:``});try{this._deviceManager.dispose(),this.logger.info(`Device Manager disposed`)}catch{this.logger.error(`Call Client failed to dispose Device Manager`)}try{this._callAgent?await this._callAgent.disposeInternal(!1).then((()=>{this.logger.info(`ACS Call Agent disposed`)})):this._teamsCallAgent&&await this._teamsCallAgent.disposeInternal(!1).then((()=>{this.logger.info(`Teams Call Agent disposed`)}))}catch(e){e.subCode!==J.CALL_AGENT.ACS_ALREADY_DISPOSED.subCode&&e.subCode!==J.CALL_AGENT.CTE_ALREADY_DISPOSED.subCode||this.logger.debug(`Call Client failed to dispose Call Agent as it is already disposed`),this.logger.error(`Call Client failed to dispose Call Agent`)}try{this._screenDeviceManager.dispose()}catch{this.logger.error(`Call Client failed to dispose ScreenDevice Manager`)}try{await this._callStack.disposeBaseStack(),this.logger.info(`Base call stack disposed`)}catch{this.logger.error(`Call Client failed to dispose base call stack`)}this._eventEmitter.removeAllListeners(),window.removeEventListener(`beforeunload`,this.sendTelemetry),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeCallClient,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-e},correlationId:t,additionalDetails:``})}catch(n){let r=new Y({defaultError:J.CALL_CLIENT.DISPOSE_FAIL,originalError:n});throw this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeCallClient,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-e},correlationId:t,additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,...J3(r)}}),r}finally{this._telemetryLogManager.clearTelemetryLoggers()}}validateEmergencyCountryCode(e){e?.emergencyCallOptions?.countryCode&&e.emergencyCallOptions?.countryCode.length>kCe&&j4(J.CALL_CLIENT.EMERGENCY_CODE_TOO_LONG,this.logger)}sendCallClientInitEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send CallClient initialized telemetry event`)}}sendCallClientOperationEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send CallClient dispose telemetry event`)}}getTelemetryTag(){return this._customProxyAndTurnInformation.proxy&&this._customProxyAndTurnInformation.turn?B2.usedProxyAndNonMsftTurn:this._customProxyAndTurnInformation.proxy?B2.onlyUsedProxy:this._customProxyAndTurnInformation.turn?B2.onlyUsedNonMsftTurn:``}};U9([UG,W9(`design:type`,Object)],G9.prototype,`logger`,void 0),U9([JG(o4.Feature),W9(`design:type`,Function),W9(`design:paramtypes`,[Object]),W9(`design:returntype`,typeof(qRe=typeof TFeature<`u`&&TFeature)==`function`?qRe:Object)],G9.prototype,`feature`,null),U9([YG(o4.CreateCallAgent),W9(`design:type`,Function),W9(`design:paramtypes`,[Object,Object]),W9(`design:returntype`,Promise)],G9.prototype,`createCallAgent`,null),U9([YG(o4.CreateTeamsCallAgent),W9(`design:type`,Function),W9(`design:paramtypes`,[Object,Object]),W9(`design:returntype`,Promise)],G9.prototype,`createTeamsCallAgent`,null),U9([YG(o4.GetDeviceManager),W9(`design:type`,Function),W9(`design:paramtypes`,[]),W9(`design:returntype`,Promise)],G9.prototype,`getDeviceManager`,null),U9([YG(o4.Dispose),W9(`design:type`,Function),W9(`design:paramtypes`,[]),W9(`design:returntype`,Promise)],G9.prototype,`dispose`,null);var YRe=class{constructor(e,t,n,r,i){if(this._width=0,this._height=0,this._eventEmitter=new E3.EventEmitter,this._loopId=0,this._isDisposed=!1,e.getVideoTracks().length===0)throw Error(`Video stream must have at least one video track`);this._videoStream=e.clone(),this._refreshInterval=r,this._logger=i.createChild(`VideoStreamCanvasEncoder`),this._video=document.createElement(`video`),this._canvas=document.createElement(`canvas`),this._video.srcObject=this._videoStream,this._video.addEventListener(`resize`,(()=>{let e=this._video.videoWidth||t,r=this._video.videoHeight||n;this._width===e&&this._height===r||(this._width=e,this._height=r,this._canvas.width=e,this._canvas.height=r,this._logger.info(`Video stream resized to ${e}x${r}`))})),this._video.addEventListener(`play`,(()=>{this._loopId||=window.setInterval((()=>{if(!this._isDisposed&&!this._video.paused&&!this._video.ended){this._context.drawImage(this._video,0,0,this._width,this._height);let e=Uint8Array.from(this._canvas.toDataURL(`image/jpeg`),(e=>e.charCodeAt(0)));this._eventEmitter.emit(`data`,e)}}),this._refreshInterval)})),this._video.addEventListener(`pause`,(()=>{this._loopId&&=(clearInterval(this._loopId),0)})),this._video.play().catch((e=>{this._logger.error(`Error playing video stream: ${e}`)})),this._context=this._canvas.getContext(`2d`)}on(e,t){this._eventEmitter.on(e,t)}dispose(){this._isDisposed||(this._isDisposed=!0,this._loopId&&=(clearInterval(this._loopId),0),this._video.pause(),this._video.srcObject=null,this._videoStream.getTracks().forEach((e=>{e.stop()})),this._eventEmitter.removeAllListeners())}},XRe=3,ZRe=class{constructor(e,t,n){this._eventEmitter=new E3.EventEmitter,this._loopId=0,this._isDisposed=!1,this._dataQueue=[],this._timeoutCounter=0,this._timeoutCount=0,this._canvas=document.createElement(`canvas`),this._canvas.width=0,this._canvas.height=0,this._context=this._canvas.getContext(`2d`),this._logger=t.createChild(`VideoStreamCanvasDecoder`),this._mediaStream=this._canvas.captureStream(Math.max(1,Math.ceil(1e3/e))),this._timeoutCount=n;let r=e=>new Promise(((t,n)=>{try{let r=new TextDecoder().decode(e),i=new Image;i.onload=()=>{i.width===this._canvas.width&&i.height===this._canvas.height||(this._canvas.width=i.width,this._canvas.height=i.height),this._context.drawImage(i,0,0,this._canvas.width,this._canvas.height),t(new VideoFrame(this._canvas,{timestamp:0}))},i.onerror=e=>{n(e)},i.src=r}catch(e){n(e)}})),i=async()=>{let t=performance.now();if(this._dataQueue.length>0){this._timeoutCounter=0;let e=this._dataQueue.shift();if(e)try{let t=await r(e);this._eventEmitter.emit(`frame`,t),t.close()}catch{this._logger.error(`Error decoding frame`)}}else if(this._timeoutCounter++,this._timeoutCounter>this._timeoutCount)return this._logger.warn(`No data to decode, stopping video stream`),this._eventEmitter.emit(`dispose`),void this.dispose();let n=performance.now(),a=Math.max(e-(n-t),0);this._loopId=window.setTimeout(i,a)};i()}on(e,t){this._eventEmitter.on(e,t)}decode(e){this._isDisposed||(this._dataQueue.length>XRe&&(this._logger.warn(`Data queue is full, dropping oldest frame`),this._dataQueue.shift()),this._dataQueue.push(e))}getMediaStream(){if(this._isDisposed)throw Error(`VideoStreamCanvasDecoder has been disposed`);return this._mediaStream}dispose(){this._isDisposed||(this._isDisposed=!0,this._loopId&&=(clearTimeout(this._loopId),0),this._eventEmitter.removeAllListeners())}},K9;function q9(e,t){let n=t?t.length:0,r=performance.now(),i=new ArrayBuffer(9+n),a=new DataView(i);if(a.setUint8(0,e),a.setFloat64(1,r),t){let e=new Uint8Array(i,9);for(let n=0;n<t.length;n++)e[n]=t[n]}return new Uint8Array(i)}function QRe(e){let t=new DataView(e.buffer);return{messageType:t.getUint8(0),timestamp:t.getFloat64(1),data:new Uint8Array(e.buffer,9,e.length-9)}}(function(e){e[e.VideoFrame=1]=`VideoFrame`,e[e.StopVideo=2]=`StopVideo`})(K9||={});var $Re=class{constructor(e,t,n,r){this.audioContext=null,this.analyserNode=null,this.sourceNode=null,this.dataArray=null,this.processingIntervalId=null,this.isCurrentlySpeaking=!1,this.consecutiveSpeechSamples=0,this.consecutiveSilenceSamples=0,this.lastSpeechActivityTimestamp=-1/0,this.callbackFiredForCurrentSegment=!1,this.processAudio=()=>{if(!this.analyserNode||!this.dataArray)return void(this.processingIntervalId!==null&&(clearInterval(this.processingIntervalId),this.processingIntervalId=null,this.logger.warn(`AudioAnalyzer stopped due to missing nodes.`)));this.analyserNode.getByteTimeDomainData(this.dataArray);let e=0;for(let t=0;t<this.dataArray.length;t++){let n=(this.dataArray[t]-128)/128;e+=n*n}let t=Math.sqrt(e/this.dataArray.length),n=this.options.speechConfirmSamples,r=this.options.silenceConfirmSamples,i=this.options.minCallbackIntervalMs;if(t>this.options.silenceThreshold){if(this.consecutiveSpeechSamples++,this.consecutiveSilenceSamples=0,this.consecutiveSpeechSamples>=n){let e=Date.now(),n=e-this.lastSpeechActivityTimestamp;!this.callbackFiredForCurrentSegment&&n>i&&(this.logger.info(`AudioAnalyzer: First audio render callback fired. Silence duration: ${n}ms`),this.onSpeechStartCallback(),this.callbackFiredForCurrentSegment=!0),this.lastSpeechActivityTimestamp=e,this.isCurrentlySpeaking||(this.isCurrentlySpeaking=!0,this.logger.info(`AudioAnalyzer: Speech confirmed after ${this.consecutiveSpeechSamples} consecutive samples, avgVolume: ${t.toFixed(4)}, threshold: ${this.options.silenceThreshold}.`))}}else this.consecutiveSilenceSamples++,this.consecutiveSpeechSamples=0,this.consecutiveSilenceSamples>=r&&this.isCurrentlySpeaking&&(this.isCurrentlySpeaking=!1,this.callbackFiredForCurrentSegment=!1,this.logger.debug(`AudioAnalyzer: Silence confirmed after ${this.consecutiveSilenceSamples} consecutive samples. Ready for next turn.`))},this.stream=e,this.logger=t,this.onSpeechStartCallback=n;let i=Z().waimeabay.audioAnalyzer;this.options={...i,...r},this.stream.getAudioTracks().length?this.initialize():this.logger.warn(`AudioAnalyzer: No audio tracks found in the provided stream.`)}initialize(){try{this.audioContext=new AudioContext,this.analyserNode=this.audioContext.createAnalyser(),this.analyserNode.fftSize=this.options.fftSize,this.analyserNode.smoothingTimeConstant=this.options.smoothingTimeConstant,this.sourceNode=this.audioContext.createMediaStreamSource(this.stream),this.sourceNode.connect(this.analyserNode),this.dataArray=new Uint8Array(this.analyserNode.fftSize),this.logger.info(`AudioAnalyzer initialized.`)}catch(e){this.logger.error(`AudioAnalyzer initialization failed: ${e}`),this.dispose()}}start(){this.audioContext&&this.analyserNode&&this.dataArray?this.processingIntervalId===null&&(this.logger.info(`AudioAnalyzer started monitoring with interval ${this.options.processingIntervalMs}ms.`),this.processingIntervalId=window.setInterval(this.processAudio,this.options.processingIntervalMs)):this.logger.warn(`AudioAnalyzer cannot start, not properly initialized.`)}stop(){this.processingIntervalId!==null&&(clearInterval(this.processingIntervalId),this.processingIntervalId=null,this.logger.info(`AudioAnalyzer stopped monitoring.`))}dispose(){this.stop();try{this.sourceNode?.disconnect(),this.analyserNode?.disconnect(),this.audioContext?.close().catch((e=>this.logger.error(`Error closing AudioContext: ${e}`)))}catch(e){this.logger.error(`AudioAnalyzer dispose error: ${e}`)}finally{this.audioContext=null,this.analyserNode=null,this.sourceNode=null,this.dataArray=null,this.consecutiveSpeechSamples=0,this.consecutiveSilenceSamples=0,this.callbackFiredForCurrentSegment=!1,this.logger.info(`AudioAnalyzer disposed.`)}}};function J9(e){return isNaN(e)?e:Math.round(10*e)/10}var Y9=class e{static get instance(){return e._instance||=new e,e._instance}register(e,t){this._requests.set(e,{...t,requestTime:performance.now()})}unregister(e){this._requests.delete(e)}constructor(){this._requests=new Map,globalThis.PerformanceObserver!==void 0&&(this._observer=new PerformanceObserver((e=>{e.getEntries().forEach((e=>{if(e.entryType===`resource`){let t=e;if((t.requestStart??0)<=0)return;let n=e.name,r=this._requests.get(n);if(r){let e=r.path;this.unregister(n);let i={path:e,duration:J9(t.duration),initiatorType:t.initiatorType,nextHopProtocol:t.nextHopProtocol,fetchStart:J9(t.fetchStart),domainLookupStart:J9(t.domainLookupStart),domainLookupEnd:J9(t.domainLookupEnd),connectStart:J9(t.connectStart),secureConnectionStart:J9(t.secureConnectionStart),connectEnd:J9(t.connectEnd),requestStart:J9(t.requestStart),responseStart:J9(t.responseStart),responseEnd:J9(t.responseEnd),transferSize:t.transferSize,encodedBodySize:t.encodedBodySize,responseStatus:t.responseStatus};r.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r.correlationId,operationName:`FetchTimingInfo`,durationInMs:i.duration,operationPayload:{...i},resultCategories:[`Success`],resultSignature:200,sessionId:r.sessionId,endpointId:r.endpointId})}}}))})),this._observer.observe({type:`resource`,buffered:!1}))}dispose(){e._instance&&=(this._requests.clear(),this._observer?.disconnect(),null)}};Y9._instance=null;var eze,tze=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},X9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},nze=e=>{try{return new URL(e)}catch{return}},rze=e=>{let t=`Request`;if(e instanceof URL)return{href:e.toString(),pathname:e.pathname??``};if(typeof Request<`u`&&e instanceof Request)return rze(e.url);if(typeof e==`string`){let n=nze(e);return n?{href:n.href,pathname:n.pathname??``}:{href:e||t,pathname:``}}return{href:t,pathname:``}},ize=class{constructor(e){this._params=e,this._state=jG.Connecting,this._initializeRefTime=0,this._isMuted=!1,this._remoteAudioStreams=new Map,this._remoteVideoStreams=new Map,this._joinSessionDefer=n3(),this._feedViewDefer=n3(),this._audioRenderers=new Map,this._audioAnalyzers=new Map,this._endpointId=``,this._wbSessionStats={localCandidateType:``,relayCandidateCount:0},this._localAudioStreams=new Set,this._localVideoStreams=new Set,this._audioEffectsProcessorStats=[],this._audioEffectsStatsListener=null,this._audioEffectsSubscribedStream=null,this._videoChannel=void 0,this._videoStreamEncoder=void 0,this._videoStreamDecoder=new Map,this._telemetryChannel=void 0,this._telemetryChannelInitializationPromise=void 0,this._sessionConnectedTimestamp=void 0,this._sessionConnectedSignalSent=!1,this.startAudio=async(e,t)=>{let n=performance.now(),r=J0();try{if(this._params.logger.debug(`SessionImpl: startAudio called`),this._joinSessionDefer&&(setTimeout((()=>{if(this._joinSessionDefer?.isPending())return this._joinSessionDefer.reject(new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STARTAUDIO_SESSION_TIMEDOUT}))}),Z().waimeabay.audio.startAudioSessionTimeoutMs),await this._joinSessionDefer.promise),this._outboundAudio&&this._outgoingMediaStream&&!this._isMuted)try{let e=this._outgoingMediaStream.getAudioTracks()[0];e&&(this._outboundAudio.setMediaSource(e),this._params.logger.info(`Applied pending outbound audio stream with stream ID: ${this._outgoingMediaStream.id}`))}catch(e){this._params.logger.error(`Failed to apply pending outbound audio stream: ${e instanceof Error?e.message:String(e)}`)}let i=!1,a=async()=>{i=!0,this._params.logger.debug(`Use normal real-time LocalAudioStream in session`);let e=this._params.options?.localAudioStream?this._params.options?.localAudioStream:await Z5(this._params.deviceManagerInternal,this._params.logger);await this.handleLocalAudioStream(e,!0,r,t)};try{this._preAudioFeature=e;let t=+new Date;if(this._preAudioFeature)if(this._preAudioFeature.recordAudioFailed||!this._preAudioFeature.recordAudioFinished){let e=+new Date,t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.USE_NORMALMIC_OR_RAWAUDIO_BECAUSE_RECORDAUDIO_FAILED});this._preAudioFeature.recordAudioFinished||(t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.USE_NORMALMIC_OR_RAWAUDIO_BECAUSE_RECORDAUDIO_FAILED})),this._preAudioFeature.logger.error(t.message),await this._preAudioFeature?.disposeInternal(),await this._preAudioFeature?.disposeRtcMic(),await a(),this._preAudioFeature.sendTelemetryEvent(+new Date-e,{timestampInfo:{attemptTimestamp:e},...J3(t)},t.resultCategories,500)}else{let{micLocalAudioStream:e,micRawMediaStream:n}=this._preAudioFeature.getMicMediaStream();if(this._preAudioFeature.isFinished){if(this._preAudioFeature.logger.debug(`PreAudio already finished, will use it's real-time mic for session start`),this._sessionConnectedTimestamp===void 0){let e=this._preAudioFeature.getFirstSpeechTimestamp();e!==void 0&&(this.setFirstClientAudioTimestamp(e),this._params.logger.debug(`Applied finished preAudio speech timestamp ${e}`))}await this.handleLocalAudioStream(e)}else{this._params.logger.debug(`Get PreAudio's player audio stream to use for session start`);let t=await this._preAudioFeature.getPlayerLocalAudioStream(this,(async()=>{let r=+new Date;try{if(!this._preAudioFeature)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.SWITCH_TO_RTCMIC_FAIL_PREAUDIO_UNDEFINED});this._preAudioFeature.logger.debug(`PreAudio player mediastream finished flushing`),this._preAudioFeature.logger.debug(`Now switching to real-time microphone in session`),this._preAudioFeature.disposeInternal().catch((()=>{this._preAudioFeature?.logger.error(`Failed to dispose PreAudio feature after preAudio finished and got called back.`)})),this._localAudioStreams.delete(t),await this.handleLocalAudioStream(e,!1),this.updateOutboundAudioStream(n),n.getAudioTracks().forEach((e=>{e.enabled=!0})),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[t]}),this._preAudioFeature.logger.debug(`Switched to default real-time microphone in session`),this._preAudioFeature.sendTelemetryEvent(+new Date-r,{step:X5.SWITCHED_TO_REALTIME_MIC,timestampInfo:{attemptTimestamp:r}},[`Success`],200)}catch(e){this._preAudioFeature?.logger.error(`Failed to switch to default real-time microphone after preAudio player mediastream finished flushing`,e);let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.SWITCH_TO_RTC_MIC_FAIL,originalError:e});this._preAudioFeature?this._preAudioFeature.sendTelemetryEvent(+new Date-r,{timestampInfo:{attemptTimestamp:r},...J3(t)},[`Failure`],500):this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:``,operationName:`PreAudio`,durationInMs:+new Date-r,operationPayload:{timestampInfo:{attemptTimestamp:r},...J3(t)},resultCategories:[`Failure`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})}}));await this.handleLocalAudioStream(t)}this._preAudioFeature.setEchoRefStream(this),this.subscribeToAudioEffectsStats(e),this._preAudioFeature.logger.debug(`Set PreAudio's ${this._preAudioFeature.isFinished?`real-time mic`:`player audio stream`} for session start`),this._preAudioFeature.sendTelemetryEvent(+new Date-t,{step:this._preAudioFeature.isFinished?X5.START_SESSION_WITH_RTC_MIC:X5.START_SESSION_WITH_PLAYER_AUDIO_STREAM,timestampInfo:{attemptTimestamp:t}},[`Success`],200)}else await a()}catch(e){if(i)throw e;await a()}this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartAudio`,durationInMs:performance.now()-n,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_AUDIO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: startAudio error`,t),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartAudio`,durationInMs:performance.now()-n,operationPayload:{...J3(t).communicationServicesError},resultCategories:t.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),t}},this.createIncomingAudioHandler=async e=>{e.inboundAudio.getAllSourceMedia().firesAll((e=>{let{isLocal:t,endpointId:n,sourceId:r}=e.metadata;if(this._params.logger.debug(`Inbound firesAll media received from ${n}, isLocal: ${t}`),!t)try{e.provider.acquire().fires((e=>{try{if(e.track){this._sessionConnectedTimestamp===void 0&&(this._sessionConnectedTimestamp=Date.now(),this._params.logger.info(`SessionConnectedTimestamp set on first remote audio track arrival: ${this._sessionConnectedTimestamp}`));let t=new MediaStream;t.addTrack(e.track);let i=this._params.tsStack.getDeviceManager().createAudioRenderer?.();if(i?.play(t),this._audioRenderers.set(n,i),Z().waimeabay.sendTelemetrySignal){this._sessionConnectedSignalSent||this._sessionConnectedTimestamp===void 0||(this.sendTelemetrySignal(w4.SessionConnected,this._sessionConnectedTimestamp),this._sessionConnectedSignalSent=!0);let e=new $Re(t,this._params.logger,(()=>{this.sendTelemetrySignal(w4.FirstAudioRender)}));e.start(),this._audioAnalyzers.set(n,e)}let a={sourceId:r,endpointId:n,type:`Audio`,mediaStream:t};this._remoteAudioStreams.set(n,a),this.sendStreamsUpdatedTelemetry(a,`added`),this._eventEmitter.emit(`streamsUpdated`,{added:[a],removed:[]})}}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error handling media track event from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`added`,failureType:`mediaTrackEvent`,failureReason:t})}}))}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error acquiring audio track queue from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`added`,failureType:`acquireMediaTrackQueue`,failureReason:t})}try{let t=e.provider.acquire();(async()=>{try{let e=await t;for(;!e.done;)e=await e.next;let r=this._remoteAudioStreams.get(n),i=this._audioRenderers.get(n),a=this._audioAnalyzers.get(n);a&&(a.dispose(),this._audioAnalyzers.delete(n)),t.dispose(),i&&(i.dispose(),this._audioRenderers.delete(n)),r&&(this._remoteAudioStreams.delete(n),this.sendStreamsUpdatedTelemetry(r,`removed`),this._eventEmitter.emit(`streamsUpdated`,{added:[],removed:[r]}))}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error processing audio track queue from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`removed`,failureType:`processMediaTrackQueue`,failureReason:t})}})()}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error acquiring audio track queue from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`removed`,failureType:`acquireMediaTrackQueue`,failureReason:t})}}))},this.handleLocalAudioStream=async(e,t=!0,n,r)=>{if(this._localAudioStreams.add(e),e.addSession(this),r&&e.mediaStreamType===`Audio`){let t=!1;try{await this.startAudioEffects(e,r)}catch{this._params.logger.error(`Failed to start effects for normal audio.`),t=!0}if(!t)try{this.subscribeToAudioEffectsStats(e)}catch{this._params.logger.error(`Failed to subscribe to audio effects stats for normal audio.`)}}if(t){let t;if(e.mediaStreamType===`RawMedia`)t=await e.getMediaStream();else{let e=async(e,t=!1)=>{let r=+new Date;try{let n=await e.getMediaStream(!0);if(!n)throw t?new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_FIRSTATTEMPT_ONCHANGED}):new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_FIRSTATTEMPT});return n}catch(i){let a=K3(i,!0,new Y({defaultError:J.WB_MEDIA_SDK.SESSION.FAILED_TO_GETMEDIASTREAM,originalError:i}));this._params.logger.error(`Error getting media stream, trying again`,a.message),this.sendHandleLocalAudioStreamFailureTelemetry(a,r,{...J3(a).communicationServicesError},n);try{let n=await e.getMediaStream();if(!n)throw t?new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_SECONDATTEMPT_ONCHANGED}):new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_SECONDATTEMPT});return n}catch(e){let t=K3(e,!0,new Y({defaultError:J.WB_MEDIA_SDK.SESSION.FAILED_TO_GETMEDIASTREAM,originalError:e}));throw this._params.logger.error(`Error getting media stream on second attempt`,t.message),t}}},r=async()=>{let t=+new Date;try{if(!this._tsRawStream){let e=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.NO_TS_RAW_STREAM_PRESENT_ONCHANGED});throw this._params.logger.error(e.message),e}{let t=await e(this._tsRawStream,!0);this.updateOutboundAudioStream(t),this._isMuted&&(this._isMuted=!1,this.mute())}}catch(e){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.FAILED_TO_GETMEDIASTREAM_ONCHANGED,originalError:e});this.sendHandleLocalAudioStreamFailureTelemetry(r,t,{...J3(r).communicationServicesError},n)}};this._tsRawStream=this._params.deviceManagerInternal.getRawDeviceMediaStream(0),this._tsRawStream.changed((()=>{this._params.logger.log(`RawDeviceMediaStream changed`),r()})),t=await e(this._tsRawStream)}this.updateOutboundAudioStream(t)}this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]})},this.createVideoHandler=async()=>{let e=Z().waimeabay.video,t=new K5(this,{payloadType:e.payloadType,transmissionMode:q5.PartiallyReliable,isLargeData:!0},this._params.logger,this._params.telemetryLogManager);await t.initialize(),t.on(`message`,(e=>{let{data:t,endpointId:n}=e;this._params.logger.log(`video data received: ${t.length} bytes from ${n}`);let r=QRe(t);if(r.messageType!==K9.StopVideo){if(r.messageType===K9.VideoFrame){if(!this._videoStreamDecoder.has(n)){let e=Z().waimeabay.video.timeoutCount,t=new ZRe(1e3,this._params.logger,e),r={sourceId:0,endpointId:n,type:`Video`,mediaStream:t.getMediaStream()};this._remoteVideoStreams.set(n,r),t.on(`dispose`,(()=>{this._videoStreamDecoder.delete(n),this._remoteVideoStreams.delete(n),this.sendStreamsUpdatedTelemetry(r,`removed`),this._eventEmitter.emit(`streamsUpdated`,{added:[],removed:[r]})})),this.sendStreamsUpdatedTelemetry(r,`added`),this._eventEmitter.emit(`streamsUpdated`,{added:[r],removed:[]}),t.on(`frame`,(e=>{this._params.logger.log(`video frame received: ${e.displayWidth}x${e.displayHeight} from ${n}`)})),this._videoStreamDecoder.set(n,t)}this._videoStreamDecoder.get(n).decode(r.data)}}else{let e=this._videoStreamDecoder.get(n);if(e){e.dispose(),this._videoStreamDecoder.delete(n);let t=this._remoteVideoStreams.get(n);t&&(this._remoteVideoStreams.delete(n),this.sendStreamsUpdatedTelemetry(t,`removed`),this._eventEmitter.emit(`streamsUpdated`,{added:[],removed:[t]}))}}})),this._videoChannel=t},this.sendHandleLocalAudioStreamFailureTelemetry=(e,t,n,r)=>{this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r||``,operationName:`StartAudio`,durationInMs:+new Date-t,operationPayload:{...J3(e).communicationServicesError},resultCategories:e.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})},e.logger.debug(`SessionImpl: constructor called with sessionId: ${e.sessionId}, localAudioSteam: ${!!e.options?.localAudioStream}, localVideoStream: ${!!e.options?.localVideoStream}`),this._eventEmitter=new w6(this._params.logger),this._extensibleApi=new F3(e.logger,{session:this,sessionAgent:e.sessionAgent},{tsSession:e.tsWbSession,sessionAgent:e.sessionAgent,session:this,telemetryLogManager:e.telemetryLogManager})}get audioEffectsProcessorStats(){return this._audioEffectsProcessorStats}clearAudioEffectsProcessorStats(){this._audioEffectsProcessorStats=[]}feature(e){return this._extensibleApi.getApiObjectInstance(e.sessionApiCtor)}get localAudioStreams(){return Array.from(this._localAudioStreams)}get localVideoStreams(){return Array.from(this._localVideoStreams)}get state(){return this._state}get isMuted(){return this._isMuted}get remoteAudioStreams(){return Array.from(this._remoteAudioStreams.values())}get remoteVideoStreams(){return Array.from(this._remoteVideoStreams.values())}get endpointId(){return this._endpointId}get sessionId(){return this._params.sessionId}get feedSession(){return this._session}mute(){let e=performance.now(),t=J0();try{this._params.logger.debug(`SessionImpl: mute called`,t),this.validateSessionState(c4.Mute),this._preAudioFeature&&!this._preAudioFeature.isFinished?(this._preAudioFeature.muteRtcMic(),this._isMuted=!0):this._isMuted||this.toggleAudioMuteState(),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Mute`,durationInMs:performance.now()-e,operationPayload:{wasMuted:this._isMuted},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.MUTE_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: mute error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Mute`,durationInMs:performance.now()-e,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}unmute(){let e=performance.now(),t=J0();try{this._params.logger.debug(`SessionImpl: unmute called`,t),this.validateSessionState(c4.Unmute),this._preAudioFeature&&!this._preAudioFeature.isFinished?(this._preAudioFeature.unmuteRtcMic(),this._isMuted=!1):this._isMuted&&this.toggleAudioMuteState(),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Unmute`,durationInMs:performance.now()-e,operationPayload:{wasMuted:!this._isMuted},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.UNMUTE_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: unmute error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Unmute`,durationInMs:performance.now()-e,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}async startRawAudio(e){try{if(this.validateSessionState(c4.StartAudio),this._params.logger.debug(`SessionImpl: startAudio called`),e?.mediaStreamType!==`RawMedia`)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_RAW_AUDIO_LAS_NOT_RAW_MEDIA});this._outboundAudio&&this._outboundAudio.clearMediaSource();let t=Array.from(this._localAudioStreams)[0];t&&(this._localAudioStreams.delete(t),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[t]}),this._cachedLocalAudioStreamBeforeRawAudioStarted=t),await this.handleLocalAudioStream(e),this.sendTelemetrySignal(w4.StartRawAudio)}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_RAW_AUDIO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: startAudio error`,e),t}}async stopRawAudio(){try{this.validateSessionState(c4.StopAudio),this._params.logger.debug(`SessionImpl: stopAudio called`);let e=Array.from(this._localAudioStreams)[0];if(e?.mediaStreamType!==`RawMedia`)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STOP_RAW_AUDIO_LAS_NOT_RAW_MEDIA});this._outboundAudio&&this._outboundAudio.clearMediaSource(),this._localAudioStreams.delete(e),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[e]});let t=this._cachedLocalAudioStreamBeforeRawAudioStarted||await Z5(this._params.deviceManagerInternal,this._params.logger);await this.handleLocalAudioStream(t),this._cachedLocalAudioStreamBeforeRawAudioStarted=void 0,this.sendTelemetrySignal(w4.StopRawAudio)}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STOP_RAW_AUDIO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: stopAudio error`,e),t}}muteIncomingAudio(){let e=performance.now(),t=J0();try{this._params.logger.debug(`SessionImpl: muteIncomingAudio called`,t),this.validateSessionState(c4.MuteIncomingAudio),this._audioRenderers.forEach((e=>e.setMuted(!0))),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{audioRenderersCount:this._audioRenderers.size},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.MUTE_INCOMING_AUDIO_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: muteIncomingAudio error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}unmuteIncomingAudio(){let e=performance.now(),t=J0();try{this._params.logger.debug(`SessionImpl: unmuteIncomingAudio called`,t),this.validateSessionState(c4.UnmuteIncomingAudio),this._audioRenderers.forEach((e=>e.setMuted(!1))),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`UnmuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{audioRenderersCount:this._audioRenderers.size},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.UNMUTE_INCOMING_AUDIO_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: unmuteIncomingAudio error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`UnmuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}async startVideo(e){try{if(this.validateSessionState(c4.StartVideo),this._videoStreamEncoder){let e=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.VIDEO_ALREADY_STARTED});throw this._params.logger.error(e.message),e}this._localVideoStreams.add(e);let t=await e.getMediaStream(),n=Z().waimeabay.video.defaultWidth,r=Z().waimeabay.video.defaultHeight,i=Z().waimeabay.video.refreshInterval;this._videoStreamEncoder=new YRe(t,n,r,i,this._params.logger),this._videoStreamEncoder.on(`data`,(e=>{this._videoChannel?.send(q9(K9.VideoFrame,e))})),e.mediaStreamType===`Video`&&e.disposeRawStream()}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_VIDEO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: startVideo error`,e),t}}stopVideo(){try{this._videoStreamEncoder&&(this._videoStreamEncoder.dispose(),this._videoStreamEncoder=void 0,this._videoChannel?.send(q9(K9.StopVideo))),Array.from(this._localVideoStreams.values()).forEach((e=>{this._localVideoStreams.delete(e)}))}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STOP_VIDEO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: stopVideo error`,e),t}}cleanup(){try{this._joinSessionDefer&&this._joinSessionDefer.dispose(),this._joinSessionDefer=void 0,this._audioRenderers.forEach((e=>e.dispose())),this._audioRenderers.clear(),this._audioAnalyzers.forEach((e=>e.dispose())),this._audioAnalyzers.clear(),this._videoStreamEncoder&&(this._videoStreamEncoder.dispose(),this._videoStreamEncoder=void 0,this._videoChannel?.send(q9(K9.StopVideo))),this.localVideoStreams.forEach((e=>{e.autoDisposeOnCallEnd&&e.dispose(),this._localVideoStreams.delete(e)})),this._params.sessionAgent.removeSession({sessionId:this._params.sessionId}),this._outboundAudio?.dispose(),this._feedView?.dispose();let e=this._state;if(this._state=jG.Disconnected,e!==this._state){let t=this._initializeRefTime>0?performance.now()-this._initializeRefTime:0,n=J0();this.logTelemetryWithEndpointId(n,t,e),this._params.logger.info(`Session state changed from ${e} to ${this._state}`),this._eventEmitter.emit(`stateChanged`)}this._eventEmitter.removeAllListeners(),this._extensibleApi.dispose()}catch(e){this._params.logger.error(`SessionImpl: Failed to cleanup with error: ${e instanceof Error?e.message:String(e)}`)}}disconnectInternal(e){let t=J0(),n=performance.now();this._params.logger.debug(`SessionImpl: hangUp called`,t);try{if(this._audioEffectsStatsListener&&this._audioEffectsSubscribedStream){try{this._audioEffectsSubscribedStream.feature($5.AudioEffects)?.off(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener)}catch(e){this._params.logger.warn(`Error cleaning up audio effects stats subscription on disconnect: ${e}`)}this._audioEffectsStatsListener=null}this._audioEffectsProcessorStats=[],this._audioEffectsSubscribedStream=null,this.localAudioStreams.forEach((e=>{e.removeSession(this),e.autoDisposeOnCallEnd&&e.dispose()})),this._localAudioStreams.clear(),this._tsRawStream&&=(this._tsRawStream.dispose(),void 0),this._preAudioFeature?.disposeRtcMic().catch((e=>{this._params.logger.error(`Error disposing rtc mic in preAudioFeature`,e)})),this._telemetryChannel&&=(this._telemetryChannel.dispose(),void 0),this._sessionConnectedTimestamp=void 0,this._sessionConnectedSignalSent=!1,this._session?.dispose(),this.cleanup(),this._params.logger.debug(`SessionImpl: hangUp success`,t),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`DisconnectSession`,durationInMs:performance.now()-n,operationPayload:{source:e},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(r){let i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.DISCONNECT_FAILED,originalError:r});throw this._params.logger.error(`SessionImpl: hangUp error`,r),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`DisconnectSession`,durationInMs:performance.now()-n,operationPayload:{...J3(i).communicationServicesError,source:e},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),i}}disconnect(){this.disconnectInternal(`client`)}disconnectFromUnload(e){this.disconnectInternal(e)}on(e,t){this._params.logger.debug(`Raising event: ${e}`),e!==`stateChanged`&&e!==`streamsUpdated`&&e!==`configureRequest`&&e!==`localAudioStreamsUpdated`||this._eventEmitter.on(e,t)}off(e,t){this._params.logger.debug(`Unsubscribing from event: ${e}`),e!==`stateChanged`&&e!==`streamsUpdated`&&e!==`configureRequest`&&e!==`localAudioStreamsUpdated`||this._eventEmitter.off(e,t)}async createDataChannel(e,t){let n=e.payloadType,r;switch(this._feedView||await this._feedViewDefer.promise,this._feedView.setInboundDataConfig(n,{maxStreams:Z().waimeabay.dataChannel.maxStreams,messageDeserializer:e=>e}).getInboundData(n).getAllSourceMedia().firesAll((({metadata:e,onMessageEvent:n,onDispose:r})=>{let i=e.endpointId;n.fires((e=>{t(i,e)})),r.then((()=>{this._params.logger.log(`Data stream got disposed`,i)}))})),e.transmissionMode){case q5.Realtime:r=W5.MediaTransmissionMode.REALTIME;break;case q5.PartiallyReliable:r=W5.MediaTransmissionMode.PARTIALLY_RELIABLE;break;default:r=void 0}return this._session.createOutboundData({payloadType:n,messageSerializer:e=>e,initialState:new Uint8Array,...r===void 0?{}:{transmissionMode:r}}).setFeedIds(Z().waimeabay.feedId)}async initialize(e){try{await this._internalInitialize(e)}catch(e){throw this._feedView?this._feedViewDefer.resolve():this._feedViewDefer.reject(e),e}}async _internalInitialize(e){let t=performance.now();this._initializeRefTime=t;let n=J0();this._params.logger.debug(`SessionImpl: initialize called`,n),this._params.tsWbSession.on(`callQualityChanged`,(e=>{this._params.logger.debug(`SessionQualityChanged: ${JSON.stringify(e)}`)}));let r={sendEvent:e=>{this._params.telemetryLogManager.sendWbEvent({...this._endpointId?{endpointId:this._endpointId}:{},sessionId:this._params.sessionId,eventData:e})}},i=performance.now();try{this._session=await this._params.tsWbSession.createFeedSession({serviceOrigin:this.getServiceOrigin(),telemetryLogger:r,authorizationHeaderProvider:async()=>`Bearer `+await this._params.sessionAgent.tokenProvider(),httpFetch:async(e,t)=>{let r=performance.now(),{href:i,pathname:a}=rze(e),o=(e,t)=>{let o=performance.now()-r,s=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e.error}),c=e.headers?.get(`X-Azure-Ref`),l=e.headers?.get(`x-ms-request-id`),u=e.headers?.get(`x-cache`),d=e.headers?.get(`ms-region-name`),f=e.headers?.get(`ms-stamp-name`),p=e.headers?.get(`ms-ring-name`);this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`HTTPRequest`,durationInMs:o,operationPayload:{...e.status===void 0?{}:{status:e.status},...e.statusText===void 0?{}:{statusText:e.statusText},...c?{"X-Azure-Ref":c}:{},...l?{xMsRequestId:l}:{},...u?{xCache:u}:{},...d?{msRegionName:d}:{},...f?{msStampName:f}:{},...p?{msRingName:p}:{},pathName:a,...J3(s).communicationServicesError},resultCategories:s.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId});let m=e.status===void 0?e.error:`status ${e.status}`;if(this._params.logger.error(`HTTP fetch failed for ${i}:`,m),t)throw s},s=(e,t,o)=>{let s=performance.now()-r,c=o.get(`X-Azure-Ref`),l=o.get(`x-ms-request-id`),u=o.get(`x-cache`),d=o.get(`ms-region-name`),f=o.get(`ms-stamp-name`),p=o.get(`ms-ring-name`);this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`HTTPRequest`,durationInMs:s,operationPayload:{status:e,statusText:t,...c?{"X-Azure-Ref":c}:{},...l?{xMsRequestId:l}:{},...u?{xCache:u}:{},...d?{msRegionName:d}:{},...f?{msStampName:f}:{},...p?{msRingName:p}:{},pathName:a},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.debug(`HTTP fetch succeeded for ${i} - Status: ${e}`)},c={...t?.headers instanceof Headers?(()=>{let e={};return t.headers.forEach(((t,n)=>{e[n]=t})),e})():t?.headers,"X-Microsoft-Skype-Chain-ID":this._params.sessionId};try{Y9.instance.register(i,{path:a,correlationId:n,sessionId:this._params.sessionId,endpointId:this._endpointId,telemetryLogManager:this._params.telemetryLogManager});let r=await globalThis.fetch(e,{...t,headers:c});return this._params.logger.debug(`HTTP fetch to ${e} - Status: ${r.status}`),r.ok?s(r.status,r.statusText,r.headers):o({error:Error(`HTTP request failed with status ${r.status}`),status:r.status,statusText:r.statusText,headers:r.headers},!1),r}catch(e){return o({error:e},!0)}},applicationInfo:this._params.clientTypeInfo}),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`CreateFeedSession`,durationInMs:performance.now()-i,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(e){let t=performance.now()-i,r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e});throw this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`CreateFeedSession`,durationInMs:t,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`CreateFeedSession failed`,r),r}let a=e=>{if(this._connectionState===e)return;let r=performance.now()-t,i=e=>{if(e===void 0)return`Initial`;switch(e){case W5.SessionConnectionState.CONNECTING:return`Connecting`;case W5.SessionConnectionState.CONNECTED:return`Connected`;case W5.SessionConnectionState.FAILOVER:return`Failover`;case W5.SessionConnectionState.DISCONNECTED:return`Disconnected`;default:return`UNKNOWN`}},a=i(this._connectionState),o=i(e);this._connectionState=e,this._params.logger.info(`Session transport state changed: ${a} -> ${o}`);let s={eventName:Q.acs_wb_session_events,operationId:n,operationName:`TransportStateChanged`,durationInMs:r,operationPayload:{oldState:a,newState:o,...this._wbSessionStats},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId};this._params.telemetryLogManager.sendWbSessionEvent(s)},o,s;this._session.stats.fires((e=>{let t=e.localCandidateType??``;this._wbSessionStats.localCandidateType!==t&&(this._wbSessionStats.localCandidateType=t,this._params.logger.info(`Local candidate type of active connection is ${this._wbSessionStats.localCandidateType}`)),this._wbSessionStats.relayCandidateCount=e.relayCandidateCount??0})),this._session.connectionState.fires((e=>{a(e)})),a(this._session.connectionState.value),this._session.metadata.then((e=>{let r=performance.now()-t;this._joinSessionDefer&&this._joinSessionDefer.resolve(this._session),this._endpointId=e.endpointId,this._params.logger.debug(`Session metadata received in ${r} ms for endpointId ${this._endpointId} `),this._params.tsWbSession.setAdditionalTelemetryFields({WB_SessionId:this._params.sessionId,WB_EndpointId:this._endpointId,WB_RoomId:this._params.sessionId}),this._params.logger.debug(`MediaStreamSession: setAdditionalTelemetryFields on _tsWbSession with sessionId: ${this._params.sessionId}, endpointId: ${this._endpointId}`),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`AllocateSession`,durationInMs:r,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),this.emitConfigureRequest(e)})).catch((e=>{let r=performance.now()-t,i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e});this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`AllocateSession`,durationInMs:r,operationPayload:{...J3(i).communicationServicesError},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`Session metadata error`,i)})),this._feedView=this._session.createFeedView().setFeedId(Z().waimeabay.feedId).setInboundAudioConfig({maxStreams:Z().waimeabay.audio.maxStreams,reflectionMode:W5.MediaReflectionMode.NONE}),this._feedViewDefer.resolve(),this._session.onConnect.then((async()=>{let r=performance.now()-t;if(this._params.logger.debug(`WB Connected in ${r} ms for endpointId ${this._endpointId} `),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`JoinSession`,durationInMs:r,operationPayload:{feedId:Z().waimeabay.feedId,isPreheated:!!e,isDisconnected:this._state===jG.Disconnected},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._state!==jG.Disconnected){let t=this._state;this._state=e&&t!==jG.Connected?jG.Preheated:jG.Connected,this.logTelemetryWithEndpointId(n,r,t),t!==this._state&&(this._params.logger.info(`Session state changed from ${t} to ${this._state}`),this._eventEmitter.emit(`stateChanged`))}})).catch((e=>{let r=performance.now()-t,i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e});this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`AllocateSession`,durationInMs:r,operationPayload:{...J3(i).communicationServicesError},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`Session connection error`,i),this._joinSessionDefer&&this._joinSessionDefer.isPending()&&this._joinSessionDefer.reject(e)})),this._session.onDisconnect.then((e=>{o=e})).catch((e=>{let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Session disconnected with an error: ${t}`),s={...o,errorMessage:t}})).finally((()=>{let e=performance.now()-t;this._params.logger.debug(`Session disconnected in ${e} ms, cause: ${JSON.stringify(o)}`),setTimeout((async()=>{let e=await this._params.tsWbSession.getMediaTelemetry();this._params.logger.info(`WBStats mediaTelemetry ${JSON.stringify(e)}`),this._params.tsWbSession.reportMediaTelemetry(),this._params.logger.info(`reportMediaTelemetry called on disconnect.`)}),3e3);let r=this._state;r!==jG.Disconnected&&(this._state=jG.Disconnected,this.logTelemetryWithEndpointId(n,e,r,s||o),this._params.logger.info(`Session state changed from ${r} to ${this._state}`),this._eventEmitter.emit(`stateChanged`),this.cleanup())}));let c=e7(k3.SessionFeature);for(let e of c)e.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(e);if(e||await this.startMedia(!1),Z().waimeabay.sendTelemetrySignal)try{await this.initializeTelemetryChannel(),this._params.logger.info(`Initialize: TelemetryChannel initialized successfully by main initialize flow!`)}catch(e){this._params.logger.error(`Initialize: Main initialize flow failed to initialize TelemetryChannel: ${e instanceof Error?e.message:String(e)}`)}}async startMedia(e,t){let n=performance.now(),r=J0();if(this._state===jG.Disconnected)return this._params.logger.error(`SessionImpl: startMedia called in invalid state: ${this._state}`),void this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartMedia`,durationInMs:performance.now()-n,operationPayload:{isPreheated:!!e},resultCategories:[`UnexpectedClientError`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId});t&&this._params.setOptions(t);try{this.createIncomingAudioHandler(this._feedView),this._outboundAudio||=this._session.createOutboundAudio().setFeedIds(Z().waimeabay.feedId);let t=this._state;this._state=jG.Connected;let i=performance.now()-n;this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartMedia`,durationInMs:i,operationPayload:{isPreheated:!!e,state:this._state},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),e&&this.logTelemetryWithEndpointId(r,i,t),t!==this._state&&(this._params.logger.info(`Session state changed from ${t} to ${this._state}`),this._eventEmitter.emit(`stateChanged`)),Z().waimeabay.enableVideoHandler&&await this.createVideoHandler()}catch(t){let i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_MEDIA_FAILED,originalError:t});throw this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartMedia`,durationInMs:performance.now()-n,operationPayload:{isPreheated:!!e,state:this._state,...J3(i).communicationServicesError},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`Failed to create audio/video handler: ${t instanceof Error?t.message:String(t)}`),i}}updateOutboundAudioStream(e){let t=this.localAudioStreams[0];if(t){let n=e.clone();t.setWBMediaStream(n)}if(this._outgoingMediaStream=e,this._outboundAudio)if(this._outboundAudio.clearMediaSource(),this._isMuted)this._params.logger.debug(`updateOutboundAudioStream: stream ${e.id} set while muted; track not attached until unmute.`);else{let t=e.getAudioTracks()[0];t&&this._outboundAudio.setMediaSource(t),this._params.logger.info(`Updated outbound audio stream with stream ID: ${e.id}`)}else this._params.logger.debug(`updateOutboundAudioStream: _outboundAudio not created yet, stream ${e.id} will be set when startMedia is called`)}logTelemetryWithEndpointId(e,t,n,r){this._endpointId===``&&this._params.logger.error(`Session metadata error the endpointId is empty, cannot log telemetry with endpointId yet.`);let i=n===jG.Connecting&&this._state===jG.Disconnected,a=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED}),o={eventName:Q.acs_wb_session_events,operationId:e,operationName:`StateChanged`,durationInMs:t,operationPayload:{oldState:n,newState:this._state,disconnectedCause:r??``},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId};i&&(o.resultSignature=500,o.resultCategories=a.resultCategories,o.operationPayload={...o.operationPayload,...J3(a).communicationServicesError},this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:e,operationName:`JoinSession`,durationInMs:t,operationPayload:{feedId:Z().waimeabay.feedId,...J3(a).communicationServicesError,disconnectedCause:r?{...r}:``},resultCategories:a.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})),this._params.telemetryLogManager.sendWbSessionEvent(o)}emitConfigureRequest(e){let t={feedId:Z().waimeabay.feedId,sessionId:this._params.sessionId,endpointId:this._endpointId,endpointSecret:e.secretToken,activationUrl:this.getServiceOrigin()+Z().waimeabay.activationPath},n=J0(),r=performance.now();this._eventEmitter.emit(`configureRequest`,t,((e,t)=>{if(e)this._params.logger.debug(`SessionImpl: configureRequest success`),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`ConfigureRequest`,durationInMs:performance.now()-r,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId});else{let e=t||`Unknown error`;this._params.logger.error(`SessionImpl: configureRequest failed: ${e}`);let i=new Y({defaultError:J.CALL.OPERATION_FAILED,defaultErrorMessageArgs:[`ConfigureRequest`]});this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`ConfigureRequest`,durationInMs:performance.now()-r,operationPayload:{configurationFailureReason:e,...J3(i).communicationServicesError},resultCategories:[`UnexpectedClientError`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})}}))}getServiceOrigin(){return this._params.serviceOrigin&&this._params.serviceOrigin.trim()!==``?this._params.serviceOrigin:Z().waimeabay.origin}async startAudioEffects(e,t){let n=e.feature($5.AudioEffects),r=r8().engine;await n.startEffects({noiseSuppression:r===`Chromium`?t.noiseSuppression:r===`Safari`?void 0:`BrowserNoiseSuppression`,echoCancellation:r===`Chromium`?t.echoCancellation:`BrowserEchoCancellation`})}async subscribeToAudioEffectsStats(e){try{if(this._params.logger.debug(`MediaStreamSession: subscribeToAudioEffectsStats - effectsStarted event received, waiting briefly for internal stats subscription to be set up`),await new Promise((e=>setTimeout(e,100))),this._params.logger.debug(`MediaStreamSession: subscribeToAudioEffectsStats - Setting up audio effects stats subscription after delay`),!e||this._audioEffectsSubscribedStream===e&&this._audioEffectsStatsListener)return;if(this._audioEffectsStatsListener&&this._audioEffectsSubscribedStream&&this._audioEffectsSubscribedStream!==e)try{this._audioEffectsSubscribedStream.feature($5.AudioEffects)?.off(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener)}catch(e){this._params.logger.warn(`MediaStreamSession: subscribeToAudioEffectsStats - Error cleaning up existing audio effects stats subscription: ${e}`)}let t=e.feature($5.AudioEffects);if(!this._audioEffectsStatsListener||this._audioEffectsSubscribedStream!==e){this._audioEffectsStatsListener=e=>{e&&this._audioEffectsProcessorStats.push(e)},t?.on(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener);let n=t?.audioEffectsProcessorStats;n&&this._audioEffectsProcessorStats.push(n),this._audioEffectsSubscribedStream=e}}catch(e){this._params.logger.warn(`MediaStreamSession: subscribeToAudioEffectsStats - Error handling audio effects stats subscription: ${e}`)}}initializeTelemetryChannel(){if(this._telemetryChannelInitializationPromise)return this._telemetryChannelInitializationPromise;let e=Z().waimeabay.telemetry;return this._telemetryChannelInitializationPromise=(async()=>{try{if(this._telemetryChannel)return;this._telemetryChannel=new K5(this,{payloadType:e.payloadType,...e.mode===1?{isLargeData:!1,transmissionMode:q5.Realtime}:e.mode===2?{isLargeData:!1,transmissionMode:q5.PartiallyReliable}:{isLargeData:!0,transmissionMode:q5.Realtime}},this._params.logger,this._params.telemetryLogManager),await this._telemetryChannel.initialize(),this._params.logger.info(`initializeTelemetryChannel: DataChannelAdapter initialized.`),this._telemetryChannel.on(`message`,(e=>{try{let t=Lwe(e.data);this._params.logger.info(`MediaStreamSession: Telemetry data received from endpoint ${e.endpointId}: `,JSON.stringify(t))}catch(t){this._params.logger.error(`MediaStreamSession: Error decoding telemetry message from ${e.endpointId}: ${t instanceof Error?t.message:String(t)}`)}}))}catch(e){this._params.logger.error(`initializeTelemetryChannel: Failed to initialize: ${e instanceof Error?e.message:String(e)}`),this._telemetryChannel=void 0,this._telemetryChannelInitializationPromise=void 0}})(),this._telemetryChannelInitializationPromise}async sendTelemetrySignal(e,t){let n=t===void 0?Date.now():t;if(Z().waimeabay.sendTelemetrySignal)try{if(await this.initializeTelemetryChannel(),!this._telemetryChannel)return void this._params.logger.warn(`sendTelemetrySignal: Telemetry channel is not available after attempting initialization.`);if(this._telemetryChannel.state<A8.Initialized)return void this._params.logger.warn(`sendTelemetrySignal: Telemetry channel adapter state is ${this._telemetryChannel.state}, not ready to send signal ${e}.`);let t=Fwe(e,n),r=Iwe(t);this._telemetryChannel.send(r),this._params.logger.info(`sendTelemetrySignal: Successfully sent signal: ${e}, message: ${JSON.stringify(t)}`)}catch(t){this._params.logger.error(`sendTelemetrySignal: Failed to send telemetry signal ${e}: ${t instanceof Error?t.message:String(t)}`,t)}}toggleAudioMuteState(){if(this._isMuted=!this._isMuted,this._isMuted)this._outboundAudio&&this._outboundAudio.clearMediaSource();else try{this._outboundAudio&&this._outboundAudio.setMediaSource(this._outgoingMediaStream.getAudioTracks()[0])}catch(e){this._params.logger.error(`Failed to unmute audio: ${e instanceof Error?e.message:String(e)}`)}}validateSessionState(e){if(this._state!==jG.Connected&&(this._state!==jG.Connecting||e!=c4.Mute&&e!=c4.Unmute)){if(this._state===jG.Disconnected)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.DISCONNECTED_JOIN_AGAIN,defaultErrorMessageArgs:[e]});if(this._state===jG.Connecting)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.CONNECTING_WAIT,defaultErrorMessageArgs:[e]})}}async sendStreamsUpdatedTelemetry(e,t){this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:``,operationName:`StreamsUpdated`,durationInMs:0,operationPayload:{sourceId:e.sourceId,remoteEndpointId:e.endpointId,type:e.type,action:t},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}async sendStreamsUpdatedFailureTelemetry(e){this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:``,operationName:`StreamsUpdated`,durationInMs:0,operationPayload:{sourceId:e.sourceId,remoteEndpointId:e.endpointId,type:e.type,action:e.action,failureType:e.failureType,failureReason:e.failureReason},resultCategories:[`UnexpectedClientError`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})}setFirstClientAudioTimestamp(e){this._sessionConnectedTimestamp===void 0&&(this._sessionConnectedTimestamp=e,this._params.logger.info(`SessionConnectedTimestamp set via setFirstClientAudioTimestamp: ${e}`))}};tze([JG(Dwe.Feature),X9(`design:type`,Function),X9(`design:paramtypes`,[Object]),X9(`design:returntype`,typeof(eze=typeof TFeature<`u`&&TFeature)==`function`?eze:Object)],ize.prototype,`feature`,null);var aze=class e{static create(){return new e}setTsStack(e){return this._tsStack=e,this}setDeviceManagerInternal(e){return this._deviceManagerInternal=e,this}setClientTypeInfo(e){return this._clientTypeInfo=e,this}setTsWbSession(e){return this._tsWbSession=e,this}setLogger(e){return this._logger=e,this}setTelemetryLogManager(e){return this._telemetryLogManager=e,this}setClientId(e){return this._clientId=e,this}setServiceOrigin(e){return this._serviceOrigin=e,this}setSessionId(e){return this._sessionId=e,this}setOptions(e){return this._options=e,this}setSessionAgent(e){return this._sessionAgent=e,this}get sessionAgent(){return this._sessionAgent}get tsStack(){return this._tsStack}get deviceManagerInternal(){return this._deviceManagerInternal}get clientTypeInfo(){return this._clientTypeInfo}get tsWbSession(){return this._tsWbSession}get logger(){return this._logger}get telemetryLogManager(){return this._telemetryLogManager}get clientId(){return this._clientId}get serviceOrigin(){return this._serviceOrigin}get sessionId(){return this._sessionId}get options(){return this._options}},oze=class{constructor(e,t,n,r,i,a,o,s){this._logger=e,this._telemetryLogManager=t,this._clientId=n,this._tokenCredential=r,this._callStack=i,this._deviceManagerInternal=a,this._clientTypeInfo=o,this._options=s,this._tokenFetchTries=0,this._sessionMap=new Map,this.tokenProvider=async e=>{if(!this._tokenCredential)throw new Y({defaultError:J.CALL_AGENT.GET_TOKEN_BEFORE_INIT});let t=await P4(this._tokenCredential,Z().calling.eudb.isRgnClaimEnabledForACS);return t.acsResourceId===this._parsedTokenCredential?.acsResourceId&&t.identityMri===this._parsedTokenCredential?.identityMri||j4(J.CALL_AGENT.REFRESHED_TOKEN_INVALID_USERID,this._logger),e?this._tokenFetchTries+=1:this._tokenFetchTries=0,this._tokenFetchTries>this._maxNumberOfRetries&&j4(J.CALL_AGENT.REFRESHED_TOKEN_RETRIES,this._logger),t.jwtToken},this._logger.debug(`MediaSessionAgentImpl: constructor called token: ${!!this._tokenCredential} options: ${JSON.stringify(this._options)}`),this._parsedTokenCredential=eTe(),this._maxNumberOfRetries=Z().calling.maxNumberOfTokenFetchRetries||zCe;let c=new TLe(this._telemetryLogManager);this._telemetryLogger=c.getGenericTelemetryLogger(`waimeabay`),s?.sessionAgentConfig?.allowDisconnectOnBeforeUnload&&(window.addEventListener(`beforeunload`,(()=>{this._disconnectAllSessions(`unload`)})),this._logger.debug(`MediaSessionAgent: Page unload listener registered (beforeunload)`))}_getSessionParams(e,t,n,r){let i=n?.sessionId??J0(),a=aze.create().setTsStack(this._tsWbStack).setDeviceManagerInternal(this._deviceManagerInternal).setClientTypeInfo(this._clientTypeInfo).setTsWbSession(t);return a.setClientId(this._clientId).setSessionAgent(this).setLogger(this._logger).setTelemetryLogManager(this._telemetryLogManager).setSessionId(i),e||a.setOptions(r),this._options?.serviceOrigin&&a.setServiceOrigin(this._options.serviceOrigin),a}_getOrCreateMediaSession(e,t,n){if(!this._tsWbStack)throw Error(`MediaSessionAgent is not initialized`);let r=this._getSessionKey(t),i=this._sessionMap.get(r);if(i)return this._logger.debug(`MediaSessionAgentImpl: Returning existing session for key: ${r}, total sessions: ${this._sessionMap.size}`),e||i.session.state!==jG.Preheated&&i.session.state!==jG.Connecting||i.session.startMedia(!0,n),i.session;let a=this._tsWbStack.getWBSessionObject(r,{media:this._telemetryLogger});if(!a)throw new Y({defaultError:J.WB_MEDIA_SDK.AGENT.TS_STACK_FAILD_TO_GET_WB_SESSION});let o=new ize(this._getSessionParams(!1,a,t,n)),s=performance.now(),c=J0();return o.initialize(e).then((()=>{this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:c,operationName:`MediaSessionInit`,durationInMs:performance.now()-s,operationPayload:{},resultCategories:[`Success`],resultSignature:200})})).catch((e=>{this._logger.error(`Session initialization failed: ${e}`);let t=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:e});this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:c,operationName:`MediaSessionInit`,durationInMs:performance.now()-s,operationPayload:{...J3(t).communicationServicesError},resultCategories:t.resultCategories,resultSignature:500})})),this._sessionMap.set(r,{session:o,tsWbSession:a}),this._logger.debug(`MediaSessionAgentImpl: Created and stored new session for key: ${r}, total sessions: ${this._sessionMap.size}`),o}joinSession(e,t){return this._getOrCreateMediaSession(!1,e,t)}preheatSession(e){return this._getOrCreateMediaSession(!0,e)}async initialize(){let e=performance.now(),t=J0();try{this._parsedTokenCredential=await P4(this._tokenCredential,Z().calling.eudb.isRgnClaimEnabledForACS);let n={clientId:this._clientId,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?t2.Enterprise:t2.Consumer,region:this._parsedTokenCredential.region,IsUserEmergencyCountryCode:!1,mriType:this._parsedTokenCredential.mriType};this._tsWbStack=await this._callStack.initializeMediaSdkStackForUser(this.tokenProvider,n),this._telemetryLogManager.initialize(n),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MediaSessionAgentInit`,durationInMs:performance.now()-e,operationPayload:{serviceOrigin:this._options?.serviceOrigin??``},resultCategories:[`Success`],resultSignature:200})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:n});throw this._logger.error(`MediaClient: Error initializing CallStack: ${r}`),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MediaSessionAgentInit`,durationInMs:performance.now()-e,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500}),r}}_getSessionKey(e){return e&&e.sessionId?e.sessionId:`default`}getSession(e){let t=this._getSessionKey(e);return this._sessionMap.get(t)?.session}removeSession(e){let t=this._getSessionKey(e),n=this._sessionMap.get(t),r=!!n;return n&&(this._clearTsWbSession(n.tsWbSession,t),r=this._sessionMap.delete(t),this._logger.debug(`MediaSessionAgentImpl: Removed session for key: ${t}, remaining sessions: ${this._sessionMap.size}`)),r}get sessions(){return Array.from(this._sessionMap.values()).map((e=>e.session))}_clearAllSessions(){this._sessionMap.clear(),this._logger.debug(`MediaSessionAgentImpl: Cleared all sessions from map`)}_clearTsWbSession(e,t){if(e)try{e.dispose(),this._tsWbStack.mediaAgent.disposeSession(t),this._logger.debug(`MediaSessionAgentImpl: Disposed tsWbSession after last session removed`)}catch(e){this._logger.error(`MediaSessionAgentImpl: Error disposing tsWbSession: ${e}`)}}_disconnectAllSessions(e){if(this._sessionMap.size===0)return;let t=Array.from(this._sessionMap.values());for(let n of t)try{n.session.disconnectFromUnload(e)}catch(e){this._logger.error(`MediaSessionAgent: Error disconnecting session: ${e}`)}}dispose(){this._logger.debug(`MediaSessionAgentImpl: Disposing agent and all sessions`),this._disconnectAllSessions(`dispose`),this._tsWbStack.dispose(),this._telemetryLogManager.clearTelemetryLoggers(),this._clearAllSessions(),Y9.instance.dispose()}},sze=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},cze=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},lze=1,uze=class{get initializedDeviceManager(){return this._initializedDeviceManager}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}constructor(e){this._initializedDeviceManager=!1,qSe(u2.MediaStreaming);let t=performance.now();this._clientId=J0();let n=lze++,r=e?.logger||ZW(`ACS-calling`);this.logger=new V6(r,[()=>`MediaClient${n}[${this._clientId}]`]),this._mediaSdkDiagnosticInformation=tTe(Z2(),this.logger,e),this._clientTypeInfo={name:sue,version:Z2(),details:this._mediaSdkDiagnosticInformation},this._eventEmitter=new w6(this.logger),this._telemetryLogManager=new m3(this.logger,this._mediaSdkDiagnosticInformation);try{this._callStack=new M9(this.logger,this._clientId,this._telemetryLogManager,this._mediaSdkDiagnosticInformation,new WRe,new GRe,void 0,void 0,!1),this._deviceManager=new F9(this.logger,this._callStack,this._telemetryLogManager,!0,e?.enumerateDevices??!1),this._extensibleApi=new F3(this.logger,{mediaClient:this},{mediaClient:this,telemetryLogManager:this._telemetryLogManager,callStack:this._callStack}),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`MediaClientInit`,durationInMs:performance.now()-t,operationPayload:{},resultCategories:[`Success`],resultSignature:200})}catch(e){let n=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:e});throw this.logger.error(`MediaClient: Error initializing CallStack: ${n}`),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`MediaClientInit`,durationInMs:performance.now()-t,operationPayload:{...J3(n).communicationServicesError},resultCategories:n.resultCategories,resultSignature:500}),n}}feature(e){return this._extensibleApi.getApiObjectInstance(e.mediaClientApiCtor)}async createSessionAgent(e,t){let n=new oze(this.logger,this._telemetryLogManager,this._clientId,e,this._callStack,this._deviceManager,this._clientTypeInfo,t);return await n.initialize(),n}async getDeviceManager(){return await this._deviceManager.getDeviceManager(),this._initializedDeviceManager=!0,this._eventEmitter.emit(`initializedDeviceManager`),this._deviceManager}getSdkVersion(){return Z2()}async checkDevicePermissions(e){let t=new Map,n=performance.now();e.forEach((e=>{t.set(e,AG.Prompt)}));try{if(!navigator.permissions||typeof navigator.permissions.query!=`function`){let e={};return t.forEach(((t,n)=>{e[n]=t})),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`DevicePermissionAccess`,durationInMs:performance.now()-n,operationPayload:e,resultCategories:[`Success`],resultSignature:200}),t}for(let n of e)try{let e=await navigator.permissions.query({name:n});t.set(n,e.state)}catch(e){this.logger.warn(`Failed to query ${n} permission: ${e}`),t.set(n,AG.Prompt)}let r={};return t.forEach(((e,t)=>{r[t]=e})),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`DevicePermissionAccess`,durationInMs:performance.now()-n,operationPayload:r,resultCategories:[`Success`],resultSignature:200}),t}catch(e){let r=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:e});return this.logger.error(`MediaClient::checkDevicePermissions, error checking device permissions ${r}`),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`DevicePermissionAccess`,durationInMs:performance.now()-n,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500}),t}}};sze([UG,cze(`design:type`,Object)],uze.prototype,`logger`,void 0);var dze={class:`video-call-template`},fze={key:0,class:`card`},pze={key:0,class:`permissions-denied__audio`},mze={class:`permissions-denied__audio-disabled`},hze={key:1,class:`permissions-denied__video`},gze={class:`permissions-denied__video-disabled`},_ze={key:1,class:`card`},vze={class:`incoming__settings`},yze={class:`side`},bze={class:`outgoing`},xze={class:`card`},Sze={key:0,class:`outgoing__video`},Cze={class:`outgoing__available-cameras-count text-center`},wze={key:3,class:`permissions-denied__video`},Tze={class:`permissions-denied__video-disabled`},Eze={class:`settings`},Dze={class:`settings__help`},Oze=[`href`],kze={href:`https://www.beterdichtbij.nl/service-contact/`,target:`blank`,rel:`noopener noreferrer`},Aze=`hangedUp`,Z9=`declined`,jze=`connected`,Q9=`loading`,$9=`devicePermissionDenied`,Mze=2e3,Nze={__name:`BDVideoCallTemplate`,props:{messageWhenLoading:String,participant:{type:Object,default:null},isCallee:{type:Boolean,default:!1},videoTestUrl:{type:String,default:``}},emits:[`ready`,`end-video-call`],setup(e,{expose:n,emit:r}){let i=e,a=r,{tm:o}=zu(),s=(0,t.ref)([]),c=navigator.userAgent.indexOf(`Firefox`)>-1,l=(0,t.computed)(()=>o(`template.videoCall`)),u=(0,t.ref)(!1),d=(0,t.ref)(!1),f=(0,t.ref)(!1),g=(0,t.ref)(2),_=(0,t.ref)({}),v=(0,t.ref)(Q9),y=(0,t.ref)(null),b=(0,t.reactive)({client:null,agent:null,deviceManager:null,incomingCall:null,call:null}),x=(0,t.ref)(null),S=(0,t.ref)(null),C=(0,t.ref)(null),w=(0,t.ref)(null),T=(0,t.ref)(0),E=(0,t.ref)(0),ee=(0,t.ref)(null),D=(0,t.computed)(()=>i.videoTestUrl||void 0),O=(0,t.computed)(()=>{switch(T.value){case 0:return l.value.hasNoAvailableCamera;case 1:return l.value.hasOneAvailableCamera;default:return l.value.hasMultipleAvailableCameras}}),k=(0,t.computed)(()=>{let e=navigator.userAgent;return/Mobi/.test(e)&&!u.value}),A=(0,t.computed)(()=>{let e=navigator.userAgent,t=e.indexOf(`Android`)!==-1,n=/Mobi/.test(e),r=/iPad|iPhone|iPod/.test(e)&&!window.MSStream;return!(t&&n||r)}),j=(0,t.computed)(()=>!_.value?.video&&de.value),te=(0,t.computed)(()=>!_.value?.audio&&de.value),ne=(0,t.computed)(()=>v.value===Z9?`incoming--declined`:`incoming--loading`),re=(0,t.computed)(()=>{switch(g.value){case 0:return`weak`;case 1:return`steady`;case 2:return`strong`;default:return null}}),ie=(0,t.computed)(()=>{switch(g.value){case 0:return l.value.signalStrength.weak;case 1:return l.value.signalStrength.steady;case 2:return l.value.signalStrength.strong;default:return null}}),ae=(0,t.computed)(()=>u.value?l.value.stopSharingScreen:l.value.shareScreen),M=(0,t.computed)(()=>l.value.placeholderSettingsHelpTitle),oe=(0,t.computed)(()=>l.value.placeholderSettingsHelpMessage),se=(0,t.computed)(()=>v.value===Z9),ce=(0,t.computed)(()=>v.value===Aze),le=(0,t.computed)(()=>v.value===jze),ue=(0,t.computed)(()=>!le.value),de=(0,t.computed)(()=>v.value===$9),fe=(0,t.computed)(()=>ce.value?l.value.messageWhenVideoCallHangedUp:se.value?l.value.messageWhenVideoCallDeclined:de.value?l.value.messageWhenDevicePermissionDenied:i.messageWhenLoading),N=(0,t.computed)(()=>f.value?`.incoming__screenshare`:`.incoming__video`);(0,t.onMounted)(()=>{Me()}),(0,t.onUnmounted)(()=>{ee.value&&window.clearInterval(ee.value),V()});function pe(){v.value=Z9}function me(){}function he(){v.value!==$9&&F()}async function ge(){v.value=Aze,_.value.video&&Ae()}async function _e(e){b.client=(0,t.markRaw)(new G9);let n=await new Jle(e);b.agent=(0,t.markRaw)(await b.client.createCallAgent(n)),b.deviceManager=await b.client.getDeviceManager(),_.value=await b.deviceManager.askDevicePermission({video:!0,audio:!0}),ee.value=window.setInterval(Ae,5e3),(!_.value.audio||!_.value.video)&&(v.value=$9),i.isCallee&&(b.agent.on(`incomingCall`,P),a(`ready`))}async function P(e){try{b.incomingCall=e.incomingCall,ye()}catch{console.log(`error occured during starting call`)}}async function ve(){let e=await be();return e?{localVideoStreams:[e]}:void 0}async function F(){try{let e=await ve(),t={communicationUserId:i.participant.videoCallIdentityId};b.call=b.agent.startCall([t],{videoOptions:e}),L(),I()}catch(e){console.error(e)}}async function ye(){let e=await ve();b.call=await b.incomingCall.accept({videoOptions:e}),L(),I()}async function be(){let e=(await b.deviceManager.getCameras())[0];if(e)return new X6(e);console.error(`No camera device found on the system`)}function I(){b.call.on(`stateChanged`,R),b.call.on(`localVideoStreamsUpdated`,e=>{e.added.forEach(Se),e.removed.forEach(z)}),b.call.remoteParticipants.forEach(we),b.call.on(`remoteParticipantsUpdated`,e=>{e.added.forEach(we)}),b.call.on(`isScreenSharingOnChanged`,()=>{u.value=b.call.isScreenSharingOn})}function L(){y.value=b.call.feature($5.UserFacingDiagnostics),y.value.media.on(`diagnosticChanged`,xe),y.value.network.on(`diagnosticChanged`,xe)}function xe(e){(e.diagnostic===`networkReceiveQuality`||e.diagnostic===`networkSendQuality`)&&(e.value===n6.Bad?(console.error(`${e.diagnostic} is bad quality`),g.value=0):e.value===n6.Poor?(console.error(`${e.diagnostic} is poor quality`),g.value=1):g.value=2)}function R(){switch(b.call.state){case`EarlyMedia`:v.value=Q9;break;case`Ringing`:v.value=Q9;break;case`Connected`:v.value=jze;break;case`Disconnected`:ge();break}}async function z(e){if(!e||e.mediaStreamType!==`ScreenSharing`||!w.value)return;w.value.dispose();let t=document.querySelector(`.outgoing__screenshare`);t.style.display=`none`;let n=document.querySelector(`.outgoing__video`);n.style.display=`flex`}async function Se(e){if(!e||e.mediaStreamType!==`ScreenSharing`)return;w.value=await new A7(e).createView();let t=document.querySelector(`.outgoing__screenshare`);t.replaceChildren(w.value.target),t.style.display=`flex`;let n=document.querySelector(`.outgoing__video`);n.style.display=`none`;let r=t.querySelector(`video`);r.style.objectFit=`contain`}async function Ce(e){if(e&&e.source&&x.value&&x.value.source&&x.value.source.id==e.source.id)return!0;try{S.value=new A7(e);let t=await S.value.createView(),n=document.querySelector(`.outgoing__video`);n.querySelector(`video`)&&(n.innerHTML=``),n.hidden=!1,n.replaceChildren(t.target)}catch{return!1}return x.value=e,!0}async function we(e){e.videoStreams.forEach(Te),e.on(`videoStreamsUpdated`,e=>{e.added.forEach(Te)})}async function Te(e){if(e.mediaStreamType===`Video`&&(await Ee(e),e.on(`isAvailableChanged`,async()=>await Ee(e))),e.mediaStreamType===`ScreenSharing`&&e.on(`isAvailableChanged`,Oe),e.mediaStreamType===`ScreenSharing`&&e.isAvailable){C.value=new A7(e);let t=await C.value.createView(),n=document.querySelector(`.incoming__screenshare`);De(!0),f.value=!0,B(`.incoming__screenshare`),n.replaceChildren(t.target)}}async function Ee(e){if(!e.isAvailable)return;C.value=new A7(e);let t=await C.value.createView(),n=document.querySelector(`.incoming__video`);n.hidden=!1,n.replaceChildren(t.target),B(`.incoming__video`),De(!1)}function De(e){let t=document.querySelector(`.incoming__video`),n=document.querySelector(`.incoming__screenshare`);t.style.display=e?`none`:`block`,n.style.display=e?`flex`:`none`}function Oe(){f.value=!1,De(!1)}async function ke(){Ae(!0)}async function Ae(e=!1){let t=(await b.deviceManager.getCameras()).filter(e=>e.name!=`OBS Virtual Camera`);T.value=t.length;for(let n=0;n<T.value;n++){(e||n!=0)&&(E.value=(E.value+1)%T.value);let r=t[E.value];if(await Ce(new X6(r)))break}}function B(e){let t=document.querySelector(e);if(!t)return;let n=t.querySelector(`video`);n&&(n.style.objectFit=`contain`,n.disablePictureInPicture=!1)}async function V(){b.call&&b.call.state!==`Disconnected`&&(await b.call.hangUp({forEveryone:!0}),await b.agent.dispose()),a(`end-video-call`),window.close()}function je(){window.close()}function Me(){Sae(`verbose`),XW.log=(...e)=>{let t=[...e];s.value=s.value.splice(1-Mze).concat(t)}}function Ne(){document.querySelector(N.value).querySelector(`video`).requestFullscreen()}function Pe(){let e=document.querySelector(N.value).querySelector(`video`);document.pictureInPictureElement?e.exitPictureInPicture():document.pictureInPictureEnabled&&e.requestPictureInPicture()}async function Fe(){b.call&&b.call.isScreenSharingOn?await b.call.stopScreenSharing():await b.call.startScreenSharing()}return n({CallDeclined:pe,CallAnswered:me,CallStartVideoCall:he,CallHangUp:ge,InitializeAcsConnection:_e}),(n,r)=>{let i=(0,t.resolveComponent)(`BDLoader`);return(0,t.openBlock)(),(0,t.createElementBlock)(`div`,dze,[(0,t.createVNode)(m,null,{default:(0,t.withCtx)(()=>[(0,t.createVNode)(h,null,{default:(0,t.withCtx)(()=>[(0,t.createVNode)(p,null,{default:(0,t.withCtx)(()=>[(0,t.createVNode)(tU,{smallState:!0,contactInfo:e.participant.contact},null,8,[`contactInfo`])]),_:1})]),_:1}),(0,t.createVNode)(h,null,{default:(0,t.withCtx)(()=>[(0,t.createVNode)(p,{sm:`12`,lg:se.value?`12`:`8`},{default:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`div`,{class:(0,t.normalizeClass)([`incoming`,ne.value])},[ue.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,fze,[(0,t.createVNode)(i,{size:`lg`,message:fe.value,stopAnimation:se.value||ce.value||de.value},null,8,[`message`,`stopAnimation`]),te.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,pze,[(0,t.createElementVNode)(`div`,mze,[(0,t.createVNode)(jr,{class:`icon-xl icon-state-error`})]),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(l.value.permissionDeniedForAudio),1)])):(0,t.createCommentVNode)(``,!0),j.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,hze,[(0,t.createElementVNode)(`div`,gze,[(0,t.createVNode)(Zi,{class:`icon-xl icon-state-error`})]),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(l.value.permissionDeniedForVideo),1)])):(0,t.createCommentVNode)(``,!0),se.value||ce.value||de.value?((0,t.openBlock)(),(0,t.createBlock)(_a,{key:2,variant:`primary`,class:`text-center`,onClick:je},{default:(0,t.withCtx)(()=>[(0,t.createTextVNode)((0,t.toDisplayString)(l.value.closeWindow),1)]),_:1})):(0,t.createCommentVNode)(``,!0)])):((0,t.openBlock)(),(0,t.createElementBlock)(`div`,_ze,[r[0]||=(0,t.createElementVNode)(`div`,{class:`incoming__video`},null,-1),r[1]||=(0,t.createElementVNode)(`div`,{class:`incoming__screenshare`},null,-1),(0,t.createElementVNode)(`div`,vze,[(0,t.createVNode)(_a,{variant:`primary`,class:`text-center`,onClick:Ne},{default:(0,t.withCtx)(()=>[(0,t.createVNode)(pi),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(l.value.fullScreen),1)]),_:1}),!c&&!d.value?((0,t.openBlock)(),(0,t.createBlock)(_a,{key:0,variant:`primary`,class:`text-center`,onClick:Pe},{default:(0,t.withCtx)(()=>[(0,t.createVNode)(pi),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(l.value.miniPlayer),1)]),_:1})):(0,t.createCommentVNode)(``,!0)])]))],2)]),_:1},8,[`lg`]),se.value?(0,t.createCommentVNode)(``,!0):((0,t.openBlock)(),(0,t.createBlock)(p,{key:0,sm:`12`,lg:`4`},{default:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`div`,yze,[(0,t.createElementVNode)(`div`,null,[(0,t.createElementVNode)(`div`,bze,[(0,t.createElementVNode)(`div`,xze,[de.value?(0,t.createCommentVNode)(``,!0):((0,t.openBlock)(),(0,t.createElementBlock)(`div`,Sze)),r[2]||=(0,t.createElementVNode)(`div`,{class:`outgoing__screenshare`},null,-1),A.value&&!de.value&&!d.value&&!ue.value?((0,t.openBlock)(),(0,t.createBlock)(_a,{key:1,variant:u.value?`danger`:`primary`,class:`text-center`,onClick:Fe},{default:(0,t.withCtx)(()=>[(0,t.createVNode)(pi),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(ae.value),1)]),_:1},8,[`variant`])):(0,t.createCommentVNode)(``,!0),k.value?((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,{key:2},[(0,t.createVNode)(_a,{class:`text-center`,onClick:ke},{default:(0,t.withCtx)(()=>[(0,t.createTextVNode)((0,t.toDisplayString)(l.value.switchCamera),1)]),_:1}),(0,t.createElementVNode)(`p`,Cze,(0,t.toDisplayString)(O.value),1)],64)):(0,t.createCommentVNode)(``,!0),j.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,wze,[(0,t.createElementVNode)(`div`,Tze,[(0,t.createVNode)(Zi,{class:`icon-xxl icon-state-error`})]),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(l.value.permissionDeniedForVideo),1)])):(0,t.createCommentVNode)(``,!0)])]),(0,t.createElementVNode)(`div`,Eze,[(0,t.createElementVNode)(`div`,{class:(0,t.normalizeClass)([`settings__signal`,re.value])},[r[3]||=(0,t.createElementVNode)(`ul`,{class:`indicator`},[(0,t.createElementVNode)(`li`),(0,t.createElementVNode)(`li`),(0,t.createElementVNode)(`li`)],-1),(0,t.createElementVNode)(`p`,null,(0,t.toDisplayString)(ie.value),1)],2),(0,t.createElementVNode)(`div`,Dze,[(0,t.createElementVNode)(`p`,null,[(0,t.createElementVNode)(`b`,null,(0,t.toDisplayString)(M.value),1)]),(0,t.createElementVNode)(`p`,null,(0,t.toDisplayString)(oe.value),1),(0,t.createElementVNode)(`p`,null,[(0,t.createElementVNode)(`a`,{href:D.value,target:`blank`,rel:`noopener noreferrer`},(0,t.toDisplayString)(l.value.testCall),9,Oze),r[4]||=(0,t.createTextVNode)(` • `,-1),(0,t.createElementVNode)(`a`,kze,(0,t.toDisplayString)(l.value.serviceDesk),1)])])])]),!ce.value&&!de.value?((0,t.openBlock)(),(0,t.createBlock)(_a,{key:0,variant:`danger`,class:`text-center w-100`,onClick:V},{default:(0,t.withCtx)(()=>[(0,t.createVNode)(Mt),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(l.value.endCall),1)]),_:1})):(0,t.createCommentVNode)(``,!0)])]),_:1}))]),_:1})]),_:1})])}}},Pze={class:`template not-found-template`},Fze={class:`center-screen`},Ize={class:`container-warning`},Lze=[`textContent`],Rze=[`textContent`],zze=(0,t.defineComponent)({__name:`BDNotFoundTemplate`,props:{buttonText:{type:String}},emits:[`navigate`],setup(e,{emit:n}){let{t:r}=zu(),i=e,a=n,o=(0,t.computed)(()=>i.buttonText||r(`notFoundTemplate.buttonDefault`)),s=(0,t.computed)(()=>r(`notFoundTemplate.title`)),c=(0,t.computed)(()=>r(`notFoundTemplate.description`)),l=()=>a(`navigate`);return(e,n)=>((0,t.openBlock)(),(0,t.createElementBlock)(`main`,Pze,[(0,t.createVNode)(m,{class:`container-xl`},{default:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`div`,Fze,[(0,t.createElementVNode)(`div`,Ize,[(0,t.createVNode)(Bi),(0,t.createElementVNode)(`h5`,{textContent:(0,t.toDisplayString)(s.value)},null,8,Lze),(0,t.createElementVNode)(`p`,{textContent:(0,t.toDisplayString)(c.value)},null,8,Rze),(0,t.createVNode)(_a,{onClick:l,variant:`primary`,type:`button`,textContent:(0,t.toDisplayString)(o.value)},null,8,[`textContent`])])])]),_:1})]))}});e.BDAlert=ca,e.BDArticle=da,e.BDAssignConversationModal=UU,e.BDAttachmentPreviewList=P_,e.BDAttachmentUploadModal=WU,e.BDBadge=ma,e.BDButton=_a,e.BDCard=Ea,e.BDChangePasswordTemplate=AW,e.BDChatCloud=iv,e.BDCol=p,e.BDCollapsableCard=Aa,e.BDConfirmationModal=GU,e.BDContainer=m,e.BDContentLibraryModal=Aie,e.BDContentLibrarySplitButton=Oh,e.BDContentLibraryTemplate=bW,e.BDConversationToTextModal=wW,e.BDDate=qh,e.BDDropdown=vU,e.BDDropdownItem=av,e.BDFileUpload=uO,e.BDForm=Jh,e.BDFormCheckbox=fg,e.BDFormInput=Pg,e.BDFormInvalidFeedback=mg,e.BDFormMultipleCheckbox=mO,e.BDFormSelect=zg,e.BDHeader=wU,e.BDImageAttachmentModal=EW,e.BDImageAttachmentPreviewList=U_,e.BDInputGroup=Hg,e.BDLink=ga,e.BDLoader=Xg,e.BDLogo=$g,e.BDMarkdownEditor=JH,e.BDMessageTemplateFormModal=DW,e.BDMobileMenu=ZH,e.BDModal=DU,e.BDNotFoundTemplate=zze,e.BDPagination=o_,e.BDPhoneNumberEditModal=NU,e.BDPill=p_,e.BDPractitionerHeader=BU,e.BDProfileImage=g_,e.BDRow=h,e.BDSessionTimeOutModal=HU,e.BDSmallConversationCard=tU,e.BDTable=aU,e.BDToast=x_,e.BDUser=lU,e.BDUserInformation=E_,e.BDVideoCallConfirmationModal=OW,e.BDVideoCallTemplate=Nze,e.BDVideoCallToast=_U,e.BDZoomslider=k_,e.CopyChatMessageToClipboard=zie,e.CopyChatMessagesToClipboard=CW,e.CopyHl7MessagesToClipboard=Bie,e.CreateHyperlinkParagraph=(e,t)=>`<p><a href="${e}" title="${t}" target="_blank" rel="noopener noreferrer">${t}</a></p>`,e.CreateThumbnailUri=q_,e.IconAcademy=b,e.IconArrowDown=w,e.IconArrowUp=D,e.IconAttachment=j,e.IconBold=ie,e.IconBulletList=se,e.IconCalendar=de,e.IconCall=me,e.IconCallReject=P,e.IconCardView=be,e.IconCaretDown=R,e.IconCaretLeft=we,e.IconCaretRight=Oe,e.IconCheck=V,e.IconClipboard=Pe,e.IconClose=Re,e.IconComment=He,e.IconCommentActive=Ke,e.IconCommentStatic=Xe,e.IconCommonFileEmpty=et,e.IconCommonFileWarning=it,e.IconContactPerson=ct,e.IconCopy=ft,e.IconDelete=gt,e.IconDoubleCheck=bt,e.IconDownloadImage=wt,e.IconEdit=Ot,e.IconEndCall=Mt,e.IconError=It,e.IconExternal=Bt,e.IconEyeShow=Wt,e.IconEyeSlash=Jt,e.IconFile=Qt,e.IconFileAdded=nn,e.IconForward=sn,e.IconHix=dn,e.IconHyperlink=hn,e.IconImageFileLandscape=yn,e.IconImageFileWarning=Cn,e.IconInbox=Dn,e.IconInfo=An,e.IconInformationCircle=Pn,e.IconItalic=Rn,e.IconListView=Hn,e.IconLock=Kn,e.IconLusciiEscalated=Xn,e.IconLusciiLogo=er,e.IconLusciiOpen=ir,e.IconLusciiPriorityHigh=cr,e.IconLusciiPriorityLow=fr,e.IconLusciiPriorityMedium=gr,e.IconMenu=br,e.IconMessage=wr,e.IconMessageForward=Or,e.IconMicrophoneSlash=jr,e.IconMicrosoftTeams=U,e.IconMin=Rr,e.IconOrderedList=Hr,e.IconPlus=Kr,e.IconRefresh=Xr,e.IconRemove=ei,e.IconSananetLogo=ai,e.IconService=li,e.IconShareScreen=pi,e.IconSingleNeutral=gi,e.IconSort=bi,e.IconSortAsc=wi,e.IconSortDesc=Oi,e.IconSortNone=Mi,e.IconTriangleDown=Ii,e.IconTriangleExclamation=Bi,e.IconUnderline=Wi,e.IconVideoDisabled=Zi,e.IconVideocall=Ji,e.IconWarning=ta,e.IconZorgkaart=aa,e.MapAttachmentsForApi=W_,e.MapToAttachmentObjects=X_,e.TransformHyperlinks=e=>{let t=/<a\b[^>]*>.*?<\/a>/gi,n=[],r;for(;(r=t.exec(e))!==null;)n.push({start:r.index,end:r.index+r[0].length});return e.replace(/(https?:\/\/[^\s<>"',]+|www\.[^\s<>"',]+)/g,(e,t,r)=>n.some(e=>r>=e.start&&r<e.end)?e:`<a href="${e.startsWith(`www.`)?`http://${e}`:e}" target="_blank" rel="noopener noreferrer">${e}</a>`)},e.ValidateUrl=e=>e.startsWith(`http://`)||e.startsWith(`https://`),e.default={install:e=>{e.component(`BDAlert`,ca),e.component(`BDArticle`,da),e.component(`BDAssignConversationModal`,UU),e.component(`BDAttachmentPreviewList`,P_),e.component(`BDAttachmentUploadModal`,WU),e.component(`BDBadge`,ma),e.component(`BDButton`,_a),e.component(`BDCard`,Ea),e.component(`BDChangePasswordTemplate`,AW),e.component(`BDChatCloud`,iv),e.component(`BDCol`,p),e.component(`BDCollapsableCard`,Aa),e.component(`BDConfirmationModal`,GU),e.component(`BDContainer`,m),e.component(`BDContentLibraryModal`,Aie),e.component(`BDContentLibrarySplitButton`,Oh),e.component(`BDContentLibraryTemplate`,bW),e.component(`BDConversationToTextModal`,wW),e.component(`BDDate`,qh),e.component(`BDDropdown`,vU),e.component(`BDDropdownItem`,av),e.component(`BDFileUpload`,uO),e.component(`BDForm`,Jh),e.component(`BDFormCheckbox`,fg),e.component(`BDFormInput`,Pg),e.component(`BDFormInvalidFeedback`,mg),e.component(`BDFormMultipleCheckbox`,mO),e.component(`BDFormSelect`,zg),e.component(`BDHeader`,wU),e.component(`BDImageAttachmentModal`,EW),e.component(`BDImageAttachmentPreviewList`,U_),e.component(`BDInputGroup`,Hg),e.component(`BDLink`,ga),e.component(`BDLoader`,Xg),e.component(`BDLogo`,$g),e.component(`BDMarkdownEditor`,JH),e.component(`BDMessageTemplateFormModal`,DW),e.component(`BDMobileMenu`,ZH),e.component(`BDModal`,DU),e.component(`BDNotFoundTemplate`,zze),e.component(`BDPagination`,o_),e.component(`BDPhoneNumberEditModal`,NU),e.component(`BDPill`,p_),e.component(`BDPractitionerHeader`,BU),e.component(`BDProfileImage`,g_),e.component(`BDRow`,h),e.component(`BDSessionTimeOutModal`,HU),e.component(`BDSmallConversationCard`,tU),e.component(`BDTable`,aU),e.component(`BDToast`,x_),e.component(`BDUser`,lU),e.component(`BDUserInformation`,E_),e.component(`BDVideoCallConfirmationModal`,OW),e.component(`BDVideoCallTemplate`,Nze),e.component(`BDVideoCallToast`,_U),e.component(`BDZoomslider`,k_),e.component(`IconAcademy`,b),e.component(`IconArrowDown`,w),e.component(`IconArrowUp`,D),e.component(`IconAttachment`,j),e.component(`IconBold`,ie),e.component(`IconBulletList`,se),e.component(`IconCalendar`,de),e.component(`IconCall`,me),e.component(`IconCallReject`,P),e.component(`IconCardView`,be),e.component(`IconCaretDown`,R),e.component(`IconCaretLeft`,we),e.component(`IconCaretRight`,Oe),e.component(`IconCheck`,V),e.component(`IconClipboard`,Pe),e.component(`IconClose`,Re),e.component(`IconComment`,He),e.component(`IconCommentActive`,Ke),e.component(`IconCommentStatic`,Xe),e.component(`IconCommonFileEmpty`,et),e.component(`IconCommonFileWarning`,it),e.component(`IconContactPerson`,ct),e.component(`IconCopy`,ft),e.component(`IconDelete`,gt),e.component(`IconDoubleCheck`,bt),e.component(`IconDownloadImage`,wt),e.component(`IconEdit`,Ot),e.component(`IconEndCall`,Mt),e.component(`IconError`,It),e.component(`IconExternal`,Bt),e.component(`IconEyeShow`,Wt),e.component(`IconEyeSlash`,Jt),e.component(`IconFile`,Qt),e.component(`IconFileAdded`,nn),e.component(`IconForward`,sn),e.component(`IconHix`,dn),e.component(`IconHyperlink`,hn),e.component(`IconImageFileLandscape`,yn),e.component(`IconImageFileWarning`,Cn),e.component(`IconInbox`,Dn),e.component(`IconInfo`,An),e.component(`IconInformationCircle`,Pn),e.component(`IconItalic`,Rn),e.component(`IconListView`,Hn),e.component(`IconLock`,Kn),e.component(`IconLusciiEscalated`,Xn),e.component(`IconLusciiLogo`,er),e.component(`IconLusciiOpen`,ir),e.component(`IconLusciiPriorityHigh`,cr),e.component(`IconLusciiPriorityLow`,fr),e.component(`IconLusciiPriorityMedium`,gr),e.component(`IconMenu`,br),e.component(`IconMessage`,wr),e.component(`IconMessageForward`,Or),e.component(`IconMicrophoneSlash`,jr),e.component(`IconMicrosoftTeams`,U),e.component(`IconMin`,Rr),e.component(`IconOrderedList`,Hr),e.component(`IconPlus`,Kr),e.component(`IconRefresh`,Xr),e.component(`IconRemove`,ei),e.component(`IconSananetLogo`,ai),e.component(`IconService`,li),e.component(`IconShareScreen`,pi),e.component(`IconSingleNeutral`,gi),e.component(`IconSort`,bi),e.component(`IconSortAsc`,wi),e.component(`IconSortDesc`,Oi),e.component(`IconSortNone`,Mi),e.component(`IconTriangleDown`,Ii),e.component(`IconTriangleExclamation`,Bi),e.component(`IconUnderline`,Wi),e.component(`IconVideoDisabled`,Zi),e.component(`IconVideocall`,Ji),e.component(`IconWarning`,ta),e.component(`IconZorgkaart`,aa),e.directive(`bd-tooltip`,WH)}},e.getDisplayDateNumeric=Gh,e.getDisplayDateTextual=Hh,e.getDisplayDateTimeNumeric=Wh,e.getDisplayDateTimeTextual=Uh,e.useModal=OU,e.usePopover=LU,e.useServerErrors=AU,e.useSessionTimeOut=VU,e.useToaster=oO,e.useValidation=kW,e.useWindow=FU,e.useZoom=TW,e.vBdTooltip=WH});
|
|
2164
|
+
`],{type:`application/javascript`}),r=URL.createObjectURL(t);await this._playerAudioContext.audioWorklet.addModule(r);let i=new AudioWorkletNode(this._playerAudioContext,`player-processor`,{numberOfOutputs:1,outputChannelCount:[1]});this._logger.log(`Started Audio worklet.`),i.port.onmessage=async t=>{if(t.data.type===`startedProcessing`)this._logger.log(`Player audio buffer started processing audio.`),this.sendTelemetryEvent(+new Date-n,{step:X5.AUDIO_WORKLET_STARTED_PROCESSING,timestampInfo:{attemptTimestamp:n}},[`Success`],200),e(i);else if(t.data.type===`finished`){let e=+new Date;try{if(t.data.value.shutDownType===`speedUpBuffer`){if(!this._playerWorkletNode)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYERAUDIOBUFFER_UNDEFINED_CANNOT_DISCONNECT_FOR_SPEEDUP});if(!this._playerAudioDestinationNode)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYERAUDIOBUFFERNODE_UNDEFINED_FOR_SPEEDUP});this._logger.log(`Speeding up the rest of the audio buffer and shutting down player worklet node`);let n=t.data.value.restOfBufferToSpeedUp,r=n.reduce(((e,t)=>e+t[0].length),0);this._speedUpAudioBuffer=this._playerAudioContext.createBuffer(1,r,this._playerAudioContext.sampleRate);let i=0,a=new Float32Array(r),o=0;for(let e of n)i+=e[0].byteLength??0,a.set(e[0],o),o+=e[0].length;this._speedUpAudioBuffer.copyToChannel(a,0),this._playerWorkletNode.disconnect(),this._speedUpAudioBufferSourceNode=this._playerAudioContext.createBufferSource(),this._speedUpAudioBufferSourceNode.buffer=this._speedUpAudioBuffer,this._speedUpAudioBufferSourceNode.playbackRate.value=c.speedUpRate,this._speedUpAudioBufferSourceNode.connect(this._playerAudioDestinationNode),this.sendTelemetryEvent(+new Date-e,{step:X5.SET_SPEEDUP_AUDIO_STREAM,timestampInfo:{attemptTimestamp:e}},[`Success`],200),this._speedUpAudioBufferSourceNode.onended=()=>{this._storeRecording&&(this._recording?.stop(),this._recording=void 0);let n=+new Date;this._isFinished=!0,this._logger.log(`Finished speeding up the reset of the audio buffer and shut down player audio worklet. Will now switch to microphone.`);let r=t.data.value.playTimestamp,a=e-t.data.value.playTimestamp,o=n-e,s=n-t.data.value.playTimestamp,c=t.data.value.totalRawBytesBuffered,l=t.data.value.rawBytesPlayedNormalSpeed;this._statsReport.playTimestamp=r,this._statsReport.playNormalSpeedDurationInMs=a,this._statsReport.playSpeedUpDurationInMs=o,this._statsReport.totalPlayDurationInMs=s,this._statsReport.totalRawBytesBuffered=c,this._statsReport.rawBytesPlayedNormalSpeed=l,this._statsReport.rawBytesPlayedSpedUp=i,this.sendTelemetryEvent(n-e,{step:X5.SHUTDOWN_FINISHED_SPEEDING_UP_REST_OF_BUFFER,timestampInfo:{attemptTimestamp:e},playTimestamp:r,playNormalSpeedDurationInMs:a,playSpeedUpDurationInMs:o,totalPlayDurationInMs:s,totalRawBytesBuffered:c,rawBytesPlayedNormalSpeed:l,rawBytesPlayedSpedUp:i},[`Success`],200),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature after preAudio finished speeding up`)})),this._switchToRealTimeMic()},this._speedUpAudioBufferSourceNode.start()}}catch(t){this._logger.error(`Error handling finished event from player worklet`,t),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature when handling audio buffer speed up error`)})),this._switchToRealTimeMic();let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYERAUDIOBUFFER_FINISHED_EVENT_FAIL,originalError:t});this._logger.error(n.message),this.sendTelemetryEvent(+new Date-e,{step:X5.SHUTDOWN_FINISHED_SPEEDING_UP_REST_OF_BUFFER,timestampInfo:{attemptTimestamp:e},...J3(n)},n.resultCategories,500)}}},this._logger.log(`Audio worklet initialized successfully`),this.sendTelemetryEvent(+new Date-n,{step:X5.START_AUDIO_WORKLET,timestampInfo:{attemptTimestamp:n}},[`Success`],200),e(i)}catch(e){this._logger.error(`Error initializing audio worklet`,e);let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.PLAYER_AUDIO_BUFFER_INIT_FAIL,originalError:e});this._logger.error(n.message),t(n)}})),u=new Promise((async(e,t)=>{try{this._deviceManager=await this.mediaClient.getDeviceManager();let t=+new Date;if(this._deviceManager.shouldEnumerateDevices){if((await this._deviceManager.getMicrophones())[0]?.id===`microphone:`){this.sendTelemetryEvent(+new Date,{step:X5.AUDIO_PERMISSION_ASKED,timestampInfo:{attemptTimestamp:+new Date}},[`Success`],200);let e=await this._deviceManager.getAskDevicePermissionPromise({audio:!0,video:!1},C3.PreAudio);if(i=+new Date-t,!e.audio)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.AUDIO_NO_PERMISSION})}this.sendTelemetryEvent(+new Date-t,{step:X5.AUDIO_PERMISSION_GRANTED,timestampInfo:{attemptTimestamp:t}},[`Success`],200)}else this._logger.info(`Device enumeration disabled, skipping getMicrophones permission check`);let n=+new Date;this._micLocalAudioStream=await Z5(this._deviceManager,this._logger),this._logger.log(`Got selected or default microphone`),this.sendTelemetryEvent(+new Date-n,{step:X5.SELECT_MICROPHONE,timestampInfo:{attemptTimestamp:n}},[`Success`],200);let r=+new Date;try{this._audioEffectsFeature=this._micLocalAudioStream.feature(B3(s8));let e=r8().engine;await this._audioEffectsFeature.startEffects({noiseSuppression:e===`Chromium`?this._noiseSuppression:e===`Safari`?void 0:`BrowserNoiseSuppression`,echoCancellation:e===`Chromium`?this._echoCancellation:`BrowserEchoCancellation`}),this.sendTelemetryEvent(+new Date-r,{step:X5.SET_NOISE_SUPPRESSION,timestampInfo:{attemptTimestamp:r}},[`Success`],200)}catch(e){this._logger.error(`Failed to start effects sdk noise suppression`,e);let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.START_EFFECTS_FAIL,originalError:e});throw this._logger.error(t.message),t}this._logger.log(`Effects applied to mic stream with audio effects feature`);let a=+new Date,o;this._micIRawStream=this._deviceManager.getRawDeviceMediaStream(0),this._micIRawStream.changed((async()=>{let e=+new Date;try{this._logger.log(`Microphone raw stream changed`);try{this._micRawMediaStream=await this._micIRawStream?.getMediaStream(!0)}catch(e){this._logger.error(`Failed to get updated raw mic media stream from dm on changed event`,e);let t=K3(e,!0,new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.MICROPHONE_RAW_MEDIASTREAM_CHANGED_FAIL,originalError:e}));throw this._logger.error(t.message),t}this._logger.log(`Got updated raw mic stream from dm on changed event`),this._mediaStreamSession&&this._micRawMediaStream&&this._mediaStreamSession.updateOutboundAudioStream(this._micRawMediaStream),this.sendTelemetryEvent(+new Date-e,{step:X5.MICROPHONE_RAW_MEDIASTREAM_CHANGED,timestampInfo:{attemptTimestamp:e}},[`Success`],200)}catch(t){this._logger.error(`Error handling microphone raw stream changed event`,t);let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.MICROPHONE_RAW_MEDIASTREAM_CHANGED_FAIL,originalError:t});this._logger.error(n.message),this.sendTelemetryEvent(+new Date-e,{step:X5.START_RECORD_AUDIO,timestampInfo:{attemptTimestamp:e},...J3(n)},n.resultCategories,500)}}));try{o=await this._micIRawStream.getMediaStream(!0)}catch(e){this._logger.error(`Failed to get raw mic media stream from dm`,e);let t=K3(e,!0,new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.GET_MIC_STREAM_FAIL,originalError:e}));throw this._logger.error(t.message),t}this._logger.log(`Got raw mic stream from dm`),this.sendTelemetryEvent(+new Date-a,{step:X5.GET_MIC_STREAM,timestampInfo:{attemptTimestamp:a}},[`Success`],200),e(o)}catch(e){this._logger.error(`Error getting microphone media stream`,e);let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.GET_MIC_STREAM_FAIL,originalError:e});this._logger.error(n.message),t(n)}})),[d,f]=await Promise.all([l,u]);this._playerWorkletNode=d,this._micRawMediaStream=f;let p=+new Date,m;try{this._playerAudioSourceNode=this._playerAudioContext.createMediaStreamSource(this._micRawMediaStream),this._playerAudioSourceNode.connect(this._playerWorkletNode),m=this._playerAudioContext.createAnalyser(),m.fftSize=2048,this._playerAudioSourceNode.connect(m),this._playerAudioDestinationNode=this._playerAudioContext.createMediaStreamDestination(),this._playerWorkletNode.connect(this._playerAudioDestinationNode),this._playerRawMediaStream=this._playerAudioDestinationNode.stream,this._playerAudioStream=new f8(this._playerRawMediaStream),this._logger.log(`Created local audio stream from player media stream`),c.getMicStreamSettleTimeInMs>0&&await new Promise((e=>{setTimeout((()=>{this._logger.log(`Mic stream settled`),e()}),c.getMicStreamSettleTimeInMs)})),this._logger.log(`Connected microphone media stream to player worklet node`),this.sendTelemetryEvent(+new Date-p,{step:X5.CONNECT_MIC_TO_PLAYERWORKLET,timestampInfo:{attemptTimestamp:p}},[`Success`],200)}catch(e){this._logger.error(`Failed to connect microphone media stream to player worklet node`,e);let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.CONNECT_MIC_TO_PLAYERAUDIOBUFFER_FAIL,originalError:e});throw this._logger.error(t.message),t}let h=!1,g=null,_=null,v=performance.now(),y=+new Date,b;this._logger.log(`Start time of silence detection: ${y}`);let x=c.speechTimeoutInSec,S=c.rmsThreshold,C=n?c.speechDurationThresholdForPreheated:c.speechDurationThreshold,w=c.silenceDurationThreshold;this._logger.log(`Will use the following thresholds for silence detection:\n Speech Timeout: ${x} seconds,\n RMS Threshold: ${S},\n Speech Duration Threshold: ${C} seconds,\n Silence Duration Threshold: ${w} seconds\n `);let T=0,E=c.logging.rmsLogIntervalInMs,ee=0,D=0,O=c.logging.silenceLogIntervalInMs,k=0,A=c.logging.speechLogIntervalInMs;this._statsReport.rmsMaxDetected={rmsLogIntervalInMs:E,rmsIntervals:[]};let j=async()=>{let e=new Uint8Array(m.fftSize);m.getByteTimeDomainData(e);let t=Math.round(1e4*Math.sqrt(e.reduce(((e,t)=>e+(t-128)**2),0)/e.length))/1e4,n=Math.round((performance.now()-v)/1e3*100)/100;t>ee&&(ee=t);let r=performance.now();if(r-T>=E&&(this._logger.log(`RMS: ${ee}, Seconds past silence detection start: ${n}`),this._statsReport.rmsMaxDetected?.rmsIntervals.push({secondsPastSilenceDetectionsStart:n,maxRms:ee}),T=r,ee=0),n>x&&h)return this._logger.log(`PreAudio silence detection timed out after ${x} seconds. Will shut down player audio worklet, speed up rest of the buffer, and then switch to microphone`),this._statsReport.finishType=X5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SPEEDUP_AFTER_TIMEOUT,this._statsReport.speechSilenceDetectionDurationInMs=+new Date-y,this._playerWorkletNode?.port.postMessage({type:`shutDown`,value:{shutDownType:`speedUpBuffer`}}),void this.sendTelemetryEvent(+new Date-y,{step:X5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SPEEDUP_AFTER_TIMEOUT,timestampInfo:{attemptTimestamp:y},rmsMaxDetected:this._statsReport.rmsMaxDetected},[`Success`],200);if(this._isFinished||!h&&(this._play||n>x)){let e,t;this._isFinished?(this._logger.log(`PreAudio already finished, will not do any silence detection and will shutdown player audio worklet`),e=X5.SHUTDOWN_ALREADY_FINISHED):!h&&this._play?(this._logger.log(`No speech detected when play was called. Will switch to real-time microphone, and shut down player audio worklet async`),t=`Failed to dispose PreAudio feature after preAudio finished due to no speech detected`,e=X5.SHUTDOWN_NO_SPEECH_DETECTED):!h&&n>x&&(this._logger.log(`PreAudio silence detection timed out after ${x} seconds and no speech was detected. Will shut down player audio worklet and switch to real-time microphone`),t=`Failed to dispose PreAudio feature when no speech was detected after timeout`,e=X5.SHUTDOWN_PLAYERAUDIOWORKLET_NOSPEECHDETECTED_AFTER_TIMEOUT),this._isFinished=!0,this._statsReport.finishType=e,this._statsReport.speechSilenceDetectionDurationInMs=+new Date-y,this.disposeInternal().catch((()=>{this._logger.error(t)})),this.sendTelemetryEvent(+new Date-y,{step:e,timestampInfo:{attemptTimestamp:y},rmsMaxDetected:this._statsReport.rmsMaxDetected},[`Success`],200),this._switchToRealTimeMic();return}if(t>S){if(_===null&&(this._logger.log(`Starting speech timer at ${n} seconds past start`),_=performance.now(),b=Date.now()),g=null,(performance.now()-_)/1e3>=C){h=!0;let e=performance.now();e-k>=A&&(this._logger.log(`Speech detected for at least a duration of ${C} seconds at ${n} seconds past start`),k=e),this._pendingSpeechStartEpoch===void 0&&(this._pendingSpeechStartEpoch=b,this._logger.log(`Captured pending first speech epoch: ${this._pendingSpeechStartEpoch}`),this.applyPendingSpeechStartTimestampToSession(`post-detection`))}}else if(g===null&&(this._logger.log(`Starting silence timer at ${n} seconds past start`),g=performance.now()),(performance.now()-g)/1e3>=w){if(h){this._logger.log(`Silence detected for a duration of at least 1 second at ${n} seconds past start`),this._playerWorkletNode?.port.postMessage({type:`shutDown`,value:{shutDownType:`speedUpBuffer`}});let e=+new Date-y;this._statsReport.totalRtcAudioBufferedDurationInMs=e,this._statsReport.finishType=X5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SILENCE_DETECTED_AFTER_SPEECH,this._statsReport.speechSilenceDetectionDurationInMs=+new Date-y,this.sendTelemetryEvent(e,{step:X5.SHUTTINGDOWN_PLAYERAUDIOWORKLET_SILENCE_DETECTED_AFTER_SPEECH,timestampInfo:{attemptTimestamp:y},rmsMaxDetected:this._statsReport.rmsMaxDetected,totalRtcAudioBufferedDurationInMs:e},[`Success`],200);return}let e=performance.now();e-D>=O&&(this._logger.log(`Silence detected for at least 1 second, but no speech detected yet. RMS: ${t}. Seconds past start: ${n}`),D=e),_=null,b=void 0}requestAnimationFrame(j)};j(),this._logger.log(`Audio recording started successfully`);let te=+new Date-i;this._statsReport.recordAudioSuccessTimestamp=te,this.sendTelemetryEvent(te-o,{step:X5.START_RECORD_AUDIO,timestampInfo:{attemptTimestamp:o,successTimestamp:te,createMediaSdkStackBaseDuration:a,adpDuration:i}},[`Success`],200)}catch(e){this._recordAudioFailed=!0,this._logger.error(`Audio recording failed`,e),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature when handling audio recording error`)})),this._switchToRealTimeMic();let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.FAILED_TO_RECORD,originalError:e});throw this._logger.error(t.message),this.sendTelemetryEvent(+new Date-o,{step:X5.START_RECORD_AUDIO,timestampInfo:{attemptTimestamp:o},createMediaSdkStackBaseDuration:a,adpDuration:i,...J3(t)},t.resultCategories,500),t}finally{this._recordAudioFinished=!0}}play(){let e=+new Date;try{this._storeRecording&&this._playerRawMediaStream&&(this._recording=new MediaRecorder(this._playerRawMediaStream,{mimeType:this._recordingMimeType}),this._recordingChunks=[],this._recording.ondataavailable=e=>{e.data.size&&(this._logger.log(`Got preaudio recording data`),this._recordingChunks.push(e.data))},this._recording.start()),this._play=!0,this._playerWorkletNode?.port.postMessage({type:`play`,value:!0}),this._logger.log(`Audio playback started`),this.sendTelemetryEvent(+new Date-e,{step:X5.START_PLAY_AUDIO,timestampInfo:{attemptTimestamp:e}},[`Success`],200)}catch(t){this._logger.error(`Audio playback failed`,t),this.disposeInternal().catch((()=>{this._logger.error(`Failed to dispose PreAudio feature when handling audio playback error`)}));let n=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.FAILED_TO_PLAY,originalError:t});throw this._logger.error(n.message),this.sendTelemetryEvent(+new Date-e,{timestampInfo:{attemptTimestamp:e},step:X5.START_PLAY_AUDIO,...J3(n)},n.resultCategories,500),n}}downloadRecording(){if(!this._storeRecording||!this._recordingMimeType)return;let e=this._recordingMimeType?.includes(`ogg`)?`ogg`:this._recordingMimeType?.includes(`mp4`)?`m4a`:`webm`,t=new Blob(this._recordingChunks,{type:this._recordingMimeType}),n=document.createElement(`a`);n.href=URL.createObjectURL(t),n.download=`preAudio_recording_${+new Date}.${e}`,n.click(),URL.revokeObjectURL(n.href)}async dispose(){return await this.disposeInternal(!1)}_switchToRealTimeMic(){this._internalDisposed&&this._switchToRealTimeMicCallBack?.()}};function Q5(e,t,n,r,i,a){let o=a?J3(a):void 0;r&&i&&V3({featureName:`activeCallTransfer`,featureDetails:{name:`activeCallTransfer`,step:t},featureType:`callAgent`,localParticipantId:e,callId:n?.callId??``,correlationId:``,initializationType:`OnFeatureAccess`,additionalDetails:o},r,i)}var lIe=class{constructor(e,t,n,r){this._skypeConversationObjectMaps=new Map,this._callAgent=e,this._tsCallRegistry=t,this._clientLogger=r}async transferActiveCall(e,t,n){let r,i,a=mTe(e);if(r=this._skypeConversationObjectMaps.get(e.callId),!r)throw this._clientLogger.error(`No SkypeConversationObject found for active call with callId: ${e.callId}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.CONVERSATION_NOT_FOUND});if(a){let t=e.meetingLocator.organizerId;r={...r,groupCallInitiator:t},i=2}else i=0;let o={skypeConversationObject:r,mediaPeerType:i},s=n?.joinCallOptions?.videoOptions?.localVideoStreams&&n.joinCallOptions.videoOptions.localVideoStreams.length>0,c=!0!==n?.joinCallOptions?.audioOptions?.muted,l={shouldResurrect:`resurrect`,...o},u,d=J0(),f=PG();try{u=await this._tsCallRegistry.createCallAsync({causeId:f,localParticipantId:d,type:`ThreadId`,callId:e.callId,threadId:a?e.meetingLocator.threadId:``});let i=t.createNewCall(e.callId,u);if(mTe(e)?await u.joinWithMeetingData(f,r,l):await u.join(r,l,f),i.bindTsCall(),s&&n?.joinCallOptions?.videoOptions?.localVideoStreams&&i.startVideo(n.joinCallOptions.videoOptions.localVideoStreams[0]),!1===c&&this._callAgent.deviceManager.selectedMicrophone){this._callAgent.deviceManager.selectedMicrophone;let e=new f8(this._callAgent.deviceManager.selectedMicrophone);i.startAudio(e)}if(this._callAgent.addToCallArray(i),this._callAgent.handleCallState(i),n?.isTransfer){let e=u.endpointId;try{await u.removeParticipant(this._callAgent.getUserMri(),f,e,1)}catch(e){throw this._clientLogger.error(`Failed to remove participant from call during transfer: ${e}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.FAILED_TO_REMOVE_PARTICIPANT,originalError:e})}}return Q5(this._callAgent.getUserMri(),$.success,e),i}catch(e){throw this._clientLogger.error(`Active call transfer failed: ${e}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.ACTIVE_CALL_TRANSFER_FAILURE,originalError:e})}}async getActiveCallDetails(e){let t=this._callAgent.getHttpRequestHelper(),n=this._callAgent.getUserMri(),r={headers:{"Content-Type":`application/json`,"X-SkypeToken":e.jwtToken},method:`GET`},i=Z().calling.activeCallTransfer.callStoreUrl,a=await t.send(i+`${n}/conversations`,JSON.stringify({}),r,3),o=await t.extractPayload(a);if(o&&a.status===200){let e=o,t=e[0];e.length>1&&e.forEach((e=>{e.userJoinTime&&t.userJoinTime&&e.userJoinTime>t.userJoinTime&&(t=e)}));let n=e.map((e=>{if(this._skypeConversationObjectMaps.set(e.correlationId,{conversationUrl:e.conversationController,conversationId:e.correlationId}),`meetingInfo`in e)return this._clientLogger.info(`Found active meeting for client with callId: ${e.correlationId}, threadId: ${e.groupContext.threadId}`),{callId:e.correlationId,meetingLocator:{threadId:e.groupContext.threadId,organizerId:e.meetingInfo.organizerId,tenantId:e.meetingInfo.tenantId,messageId:e.meetingInfo.replyChainMessageId??``},userJoinTime:new Date(e.userJoinTime)};{let t=e.participants.map((e=>q2(e)));return{callId:e.correlationId,participants:t,userJoinTime:new Date(e.userJoinTime)}}}));return this._clientLogger.log(`[ActiveCallTransfer] activeCallList:`,n),n}if(o&&a.status>=400)throw this._clientLogger.error(`Failed to get active calls for client with error: ${o.message}`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.GET_ACTIVE_CALL_DETAILS_INVALID_TOKEN,originalError:Error(o.message)});this._clientLogger.info(`No active calls found for the client`)}},uIe=class extends LEe{initialize(e,t){if(t.info(`Initializing ActiveCallTransferFeatureImpl`),this._logger=t,this._tsCallRegistry=this._callAgent.getInternalCallRegistry(),this._telemetryLogger=e.telemetryLogManager,this._tsCallRegistry?.on(`proxiedPushNotification`,this.handleProxiedNotification),!this._tsCallRegistry||!this._telemetryLogger)throw this._logger?.error(`Failed to initialize ActiveCallTransferFeatureImpl: TS Call Registry or Telemetry Logger is undefined`),new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.CALLAGENT_NOT_INITIALIZED});this._activeCallTransferManager=new lIe(this._callAgent,this._tsCallRegistry,this._telemetryLogger,this._logger)}constructor(e){super(e),this.name=`ActiveCallTransfer`,this.handleProxiedNotification=async e=>{let t,n=this._callAgent._caConfigBag.parsedTokenCredential;if(n){if(e.eventId===115&&this._activeCallTransferManager)this._logger?.log(`Received proxied notification with eventId 115`,e),t=await this._activeCallTransferManager?.getActiveCallDetails(n),t&&t.length>0?(this._logger?.log(`Active call found, emitting activeCallsUpdated event`),Q5(this._callAgent.getUserMri(),$.success,t[0],this._telemetryLogger,this._logger),this.emitNewActiveCallDetailsEvent(t)):this._logger?.log(`No active call found, not emitting activeCallsUpdated event`);else if(e.eventId===116&&this._activeCallTransferManager){if(this._logger?.log(`Received proxied notification with eventId 116`,e),t=await this._activeCallTransferManager?.getActiveCallDetails(n),t&&t.length>0)return this._logger?.log(`Active call found on eventId 116, emitting activeCallsUpdated event, forgoing noActiveCalls event`),Q5(this._callAgent.getUserMri(),$.success,t[0],this._telemetryLogger,this._logger),void this.emitNewActiveCallDetailsEvent(t);this._logger?.log(`No active call found on eventId 116, emitting noActiveCalls event`),Q5(this._callAgent.getUserMri(),$.success,void 0,this._telemetryLogger,this._logger),this.emitNoActiveCallsEvent()}}else this._logger?.error(`No valid token found, cannot process active call details`)},this._callAgent=e.callAgent}async activeCallTransfer(e,t){let n;Q5(this._callAgent.getUserMri(),$.attempt,e,this._telemetryLogger,this._logger);try{if(!this._activeCallTransferManager){let t=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.MANAGER_UNDEFINED,originalError:Error(`ActiveCallTransferManager not initialized`)});throw Q5(this._callAgent.getUserMri(),$.failure,e,this._telemetryLogger,this._logger,t),t}n=await this._activeCallTransferManager.transferActiveCall(e,this._callAgent,t),this._callAgent.handleActiveCallTransfer(n)}catch(t){this._logger?.error(`Failed to handle active call transfer`,t);let n=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.ACTIVE_CALL_TRANSFER_FAILURE,originalError:t});throw Q5(this._callAgent.getUserMri(),$.failure,e,this._telemetryLogger,this._logger,n),n}return Q5(this._callAgent.getUserMri(),$.success,e,this._telemetryLogger,this._logger),n}async getActiveCallDetails(){Q5(this._callAgent.getUserMri(),$.attempt,void 0,this._telemetryLogger,this._logger);let e=this._callAgent._caConfigBag.parsedTokenCredential;if(!this._activeCallTransferManager||!e){this._logger?.error(`Failed to get active call details: ActiveCallTransferManager not initialized or token is invalid`);let e=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.MANAGER_TOKEN_UNDEFINED,originalError:Error(`ActiveCallTransferManager not initialized or token is invalid`)});throw Q5(this._callAgent.getUserMri(),$.failure,void 0,this._telemetryLogger,this._logger,e),e}let t;try{t=await this._activeCallTransferManager?.getActiveCallDetails(e)}catch(e){this._logger?.error(`Failed to get active call details`,e);let t=new Y({defaultError:J.FEATURES.ACTIVE_CALL_TRANSFER.GET_ACTIVE_CALL_DETAILS_FAILURE,originalError:e});throw Q5(this._callAgent.getUserMri(),$.failure,void 0,this._telemetryLogger,this._logger,t),t}return Q5(this._callAgent.getUserMri(),$.success,void 0,this._telemetryLogger,this._logger),t}dispose(){this.eventEmitter.removeAllListeners()}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}emitNewActiveCallDetailsEvent(e){this.eventEmitter.emit(`activeCallsUpdated`,{activeCallDetails:e})}emitNoActiveCallsEvent(){this.eventEmitter.emit(`noActiveCalls`)}},$5={Recording:R3(COe),Transfer:R3(FOe),Transcription:R3(kOe),Captions:R3(sDe),Copilot:R3(dDe),RaiseHand:R3(pDe),LocalRecording:R3(EOe),Reaction:R3($Pe),Spotlight:R3(FAe),PPTLive:R3(rFe),BreakoutRooms:R3(wFe),Capabilities:R3(wDe),DominantSpeakers:R3(BDe),LiveStream:R3(Dke),ComposedStream:R3(Ake),CallSurvey:R3(LAe),UserFacingDiagnostics:R3(FDe),MediaStats:R3(SOe,{activationEvent:`OnExtendedObjectConstructor`}),DebugInfo:GEe(jDe,{activationEvent:`OnExtendedObjectConstructor`}),PreCallDiagnostics:GEe(yke),VideoEffects:qEe(q6),AudioEffects:B3(s8),DataChannel:R3(PAe),OptimalVideoCount:R3(BAe),UnmixedAudio:R3(rje),AudioZones:R3(RAe),TeamsMeetingAudioConferencing:R3(ije),TogetherMode:R3(mFe),MediaAccess:R3(e6),RealTimeText:R3(EFe),DataChannelSession:z3($Fe,{activationEvent:`OnExtendedObjectConstructor`}),MediaStatsSession:z3(rIe,{activationEvent:`OnExtendedObjectConstructor`}),UserFacingDiagnosticsSession:z3(iIe,{activationEvent:`OnExtendedObjectConstructor`}),PreAudioSession:KEe(cIe),ActiveCallTransfer:WEe(uIe)};function e7(e){switch(e){case k3.CallClientFeature:return Object.entries($5).filter((e=>!0===e[1].isCallClientFeature)).map((e=>e[1]));case k3.CallAgentFeature:return Object.entries($5).filter((e=>!0===e[1].isCallAgentFeature)).map((e=>e[1]));case k3.CallFeature:return Object.entries($5).filter((e=>!0===e[1].isCallFeature)).map((e=>e[1]));case k3.MediaClientFeature:return Object.entries($5).filter((e=>!0===e[1].isMediaClientFeature)).map((e=>e[1]));case k3.SessionFeature:return Object.entries($5).filter((e=>!0===e[1].isSessionFeature)).map((e=>e[1]))}}var dIe=class{constructor(e,t){this._eventBag=[],this.resetEventBag=()=>{this._eventBag=[]},this._logger=e.createChild(`CallStats`),this._telemetryLogManager=t}recordEvent(e){try{if(Z()?.telemetry?.callStatsFlushTimeout<0||Z()?.telemetry?.blockedEvents?.indexOf(e.name)>-1)return;let t={timestamp:+new Date,...e};this._logger.debug(`CallStat recorded=${e.name}`),this._eventBag.push(t),this.scheduleTelemetryFlush()}catch{this._logger.debug(`Failed to record call stats`)}}flushEvents(){if(this._logger.debug(`CallStats sending telemetry, number of events=${this._eventBag.length}`),this._eventBag.length!==0)try{let e=this._eventBag.reduce(((e,t)=>(e[t.localParticipantId]?e[t.localParticipantId].events.push({name:t.name,timestamp:t.timestamp,...t.data}):e[t.localParticipantId]={callId:t.callId,localParticipantId:t.localParticipantId,events:[{name:t.name,timestamp:t.timestamp,...t.data}]},e)),{});Object.keys(e).forEach((t=>{this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_stats,tenant:p2,properties:{...e[t]}})})),this.resetEventBag()}catch{this._logger.debug(`Failed to send call stats`)}}scheduleTelemetryFlush(){this._callStatSendTimeout||=window.setTimeout((()=>{this.flushEvents(),this._callStatSendTimeout=void 0}),Z().telemetry.callStatsFlushTimeout)}};function t7(e,t){if(t===`Connected`)return;let n;if(e==c4.MuteAllRemoteParticipants)n=J.CALL.MUTE_ALL_PARTICIPANTS_CALL_NOT_CONNECTED;else if(e==c4.StopAudio)n=J.CALL.STOP_AUDIO_STREAM_CALL_NOT_CONNECTED;else if(e==c4.AddParticipant)n=J.CALL.ADD_PARTICIPANT_CALL_NOT_CONNECTED;else{if(e!=c4.RemoveParticipant)return;n=J.CALL.REMOVE_PARTICIPANT_CALL_NOT_CONNECTED}throw new Y({defaultError:n})}var fIe=class{constructor(e){this._volumeIndicator=e,this._eventEmitter=new D3}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get level(){return this._volumeIndicator.level}async setSource(e){this._mediaStream!==e&&(this._mediaStream&&this._volumeIndicator.dispose(),e&&(this._mediaStream=e,await this._volumeIndicator.getVolumeIndicator(e),this._volumeIndicator.on(`levelChanged`,(()=>{this._eventEmitter.emit(`levelChanged`)}))))}dispose(){this._eventEmitter.removeAllListeners()}},pIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},mIe=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},hIe=class{constructor(e,t,n,r){this._workQueue=Promise.resolve();let i=ZW(`ACS-calling`);this.logger=new V6(i,[()=>`RemoteAudioStream for media stream`]),this._source=e,this._disposed=!1,this._volumeIndicator=new Q6(this.logger,`RemoteAudioStream`,t,n,r),e.changed((async()=>{this._volumeProxy&&(this._workQueue=this._workQueue.then((async()=>{await this._volumeProxy?.setSource(await this._source.getMediaStream())})).catch((e=>{this.logger.log(`source changed but failed to update volume indicator: ${e?.message??`unknown error`}`)})))})),this.logger.info(`created`)}async getMediaStream(){return await this._source.getMediaStream()}get source(){return this._source}dispose(){this.logger.log(`dispose`),this._disposed?this.logger.log(`already disposed`):(this._volumeIndicator.dispose(),this._disposed=!0)}async getVolume(){if(!this._volumeProxy){let e=new fIe(this._volumeIndicator),t=this._workQueue.then((async()=>{await e.setSource(await this._source.getMediaStream())}));this._workQueue=t.catch(M4),await t,this._volumeProxy=e}return this._volumeProxy}};pIe([UG,mIe(`design:type`,Object)],hIe.prototype,`logger`,void 0);var gIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},_Ie=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},vIe=class{get currentVideoConstraints(){return this._currentVideoConstraints}constructor(e,t,n){this._tsCall=e,this._currentVideoConstraints={send:{frameHeight:{max:void 0},frameRate:{max:void 0},bitrate:{max:void 0}}},this._logger=t.createChild(`MediaConstraintsManager`),this._telemetryLogManager=n}async setVideoConstraints(e,t,n,r){let i=this.getTelemetryPayload({video:e}),a=e=>{let i=e?{failureReason:e?e.message:void 0,code:e?e.code:void 0,...J3(e)}:void 0;V3({correlationId:n,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:`SetConstraints`,featureType:`Call`,initializationType:`None`,timestampInfo:{deltaTimeInMs:+new Date-r},featureDetails:{name:`setConstraints`,step:e?$.failure:$.success,stage:t},additionalDetails:{constraints:this.getTelemetryPayload({video:this._currentVideoConstraints}),...i}},this._telemetryLogManager,this._logger)};try{if(V3({correlationId:n,callId:this._tsCall.callId,localParticipantId:this._tsCall.participantId,featureName:`SetConstraints`,featureType:`Call`,initializationType:`None`,timestampInfo:``,featureDetails:{name:`setConstraints`,step:$.attempt,stage:t},additionalDetails:{constraints:i}},this._telemetryLogManager,this._logger),!Z().calling.constraints.enabled)throw this._logger.error(`Setting call constraints is disabled`),new Y({defaultError:J.CALL.MEDIA_CONSTRAINTS_DISABLED});this._updateVideoConstraintsCache(e);let r={outgoingVideoLimit:{maxResolution:this._currentVideoConstraints.send?.frameHeight?.max,maxFramerate:this._currentVideoConstraints.send?.frameRate?.max,maxBitrate:this._currentVideoConstraints.send?.bitrate?.max}},o=this._tsCall.setCallConstraints?.(r);if(t!==`mid-call`)o?.then((()=>{this._logger.info(`Successfully set call constraints at call ${t} - ${JSON.stringify(this._currentVideoConstraints)}`),a()})).catch((e=>{this._logger.error(`Error setting call constraints at call ${t}`),a(new Y({defaultError:J.CALL.SET_CONSTRAINTS_START_OR_ACCEPT,defaultErrorMessageArgs:[t],originalError:e}))}));else try{await o,this._logger.info(`Successfully set call constraints during ${t} - ${JSON.stringify(this._currentVideoConstraints)}`),a()}catch(e){throw new Y({defaultError:J.CALL.SET_CONSTRAINTS_MID_CALL,originalError:e})}return this._currentVideoConstraints}catch(e){let n=new Y({defaultError:J.CALL.SET_CONSTRAINTS,defaultErrorMessageArgs:[t],originalError:e});throw a(n),n}}getTelemetryPayload(e){return{video:{send:{frameHeight:{max:e.video?.send?.frameHeight?.max},frameRate:{max:e.video?.send?.frameRate?.max},bitrate:{max:e.video?.send?.bitrate?.max}}}}}_updateVideoConstraintsCache(e){let t=Z(),n=t.calling.constraints.maxOutgoingResolution,r=t.calling.constraints.maxOutgoingFrameRate,i=t.calling.constraints.maxOutgoingVideoBitrate,a=e?.send?.frameHeight?.max??this._currentVideoConstraints.send?.frameHeight?.max,o=e?.send?.frameRate?.max??this._currentVideoConstraints.send?.frameRate?.max,s=e?.send?.bitrate?.max??this._currentVideoConstraints.send?.bitrate?.max;this._currentVideoConstraints={send:{frameHeight:{max:this._getConstraintValue(n,`maxOutgoingResolution`,a)},frameRate:{max:this._getConstraintValue(r,`maxOutgoingFrameRate`,o)},bitrate:{max:this._getConstraintValue(i,`maxOutgoingBitrate`,s)}}}}_getConstraintValue(e,t,n){return typeof n==`number`?n<1?void this._logger.info(`Received ${t} as 0 or less, removing ${t} constraint`):(e>0&&n>e&&(this._logger.info(`${t} value ${n} is larger than ${e}, resetting to ${e}`),n=e),n):void this._logger.warn(`Received invalid ${t} value, removing ${t} constraint`)}};gIe([UG,_Ie(`design:type`,Object)],vIe.prototype,`_logger`,void 0);var n7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},r7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},i7=class{constructor(e,t,n,r){this.logger=n.createChild(`Lobby`),this._tsCall=e,this._eventEmitter=new w6(this.logger),this._participants=new Map,this._call=t,this._telemetryLogManager=r,this._lobbySupportedConversationTypes=Z().calling.lobbyAdmitAndReject.supportedConversationTypes,this._isLobbyEnabled=Z().calling.lobbyAdmitAndReject.enabled,this._hasExpectedError=!1,this._isLobbyEnabled&&(this.getInLobbyParticipants(t.remoteParticipants),this._remoteParticipantUpdatedListener=e=>{if(e.added.length!==0&&e.added.forEach((e=>{e.state===`InLobby`&&this.addLobbyParticipant(e),e.on(`stateChanged`,(()=>{e.state===`InLobby`?this.addLobbyParticipant(e):e.state===`Connected`&&this.removeLobbyParticipant(e)}))})),e.removed.length!==0){if(this._call.remoteParticipants.length===0)return void this.removeAllLobbyParticipants();e.removed.forEach((e=>{this.removeLobbyParticipant(e)}))}},this._call.on(`remoteParticipantsUpdated`,this._remoteParticipantUpdatedListener))}on(e,t){if(e!==`lobbyParticipantsUpdated`)throw new Y({defaultError:J.LOBBY.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`lobbyParticipantsUpdated`)throw new Y({defaultError:J.LOBBY.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}async admit(e,t){if(!this._isLobbyEnabled)return void this.logger.warn(`Lobby is not enabled`);let n=J0(),r=+new Date;this._sendLobbyAdmitAndRejectUsage(`Start admit participant`,u3.lobbyAdmit,n,$.attempt,void 0);try{Y2(e),this.validateLobbyOperation(e),await this._tsCall.admitParticipant(K2(e));let t=+new Date;this._sendLobbyAdmitAndRejectUsage(`Lobby participant admitted successfully`,u3.lobbyAdmit,n,$.success,t-r)}catch(e){let t=f3.Unexpected;this._hasExpectedError&&=(t=f3.Expected,!1),this.handleLobbyAdmitAndRejectFailure(`Failed to admit participant from lobby`,e,n,r,u3.lobbyAdmit,t)}}async reject(e,t){if(!this._isLobbyEnabled)return void this.logger.warn(`Lobby is not enabled`);let n=J0(),r=+new Date;this._sendLobbyAdmitAndRejectUsage(`Start reject participant`,u3.lobbyReject,n,$.attempt,void 0);try{Y2(e),this.validateLobbyOperation(e),await this._tsCall.removeParticipant(K2(e));let t=+new Date;this._sendLobbyAdmitAndRejectUsage(`Lobby participant rejected successfully`,u3.lobbyReject,n,$.success,t-r)}catch(e){let t=f3.Unexpected;this._hasExpectedError&&=(t=f3.Expected,!1),this.handleLobbyAdmitAndRejectFailure(`Failed to reject participant from lobby`,e,n,r,u3.lobbyReject,t)}}async admitAll(e){let t=J0(),n=+new Date,r,i=0,a=0;if(!this._isLobbyEnabled)return this.logger.warn(`Lobby is not enabled`),{successCount:i,failureCount:a};this._sendLobbyAdmitAndRejectUsage(`Start admit all participants`,u3.lobbyAdmitAll,t,$.attempt,void 0);try{this.validateLobbyOperation(),await this._tsCall.admit({scope:`all`},PG()).then((e=>{if(r=e,e.result){let t=JSON.parse(e.result);i=t.successCount,a=t.failureCount}}));let e=+new Date;if(a!==0)return this._sendLobbyAdmitAndRejectUsage(`${i} participants are admitted successfully, ${a} participants admit failed. TransactionEnd: ${r}`,u3.lobbyAdmitAll,t,$.success,e-n),{successCount:i,failureCount:a};this._sendLobbyAdmitAndRejectUsage(`All participants are admitted successfully`,u3.lobbyAdmitAll,t,$.success,e-n)}catch(e){let r=f3.Unexpected;this._hasExpectedError&&=(r=f3.Expected,!1),this.handleLobbyAdmitAndRejectFailure(`Failed to admit all participants from lobby`,e,t,n,u3.lobbyAdmitAll,r)}return{successCount:i,failureCount:a}}get participants(){return this._isLobbyEnabled?Array.from(this._participants.values()):(this.logger.warn(`Lobby is not enabled`),[])}getInLobbyParticipants(e){e.forEach((e=>{if(e.state===`InLobby`){let t=K2(e.identifier);this._participants.set(t,e)}}))}removeAllLobbyParticipants(){if(this._participants.size===0)return;let e=Array.from(this._participants.values());this._participants.clear(),this.logger.info(`All participants are removed from lobby`),this._eventEmitter.emit(`lobbyParticipantsUpdated`,{added:[],removed:e})}removeLobbyParticipant(e){let t=K2(e.identifier);this._participants.has(t)&&(this.logger.info(`${OG(e.identifier).kind} is removed from lobby`),this._participants.delete(t),this._eventEmitter.emit(`lobbyParticipantsUpdated`,{added:[],removed:[e]}))}addLobbyParticipant(e){let t=K2(e.identifier);this._participants.has(t)||(this.logger.info(`${OG(e.identifier).kind} is added to lobby`),this._participants.set(t,e),this._eventEmitter.emit(`lobbyParticipantsUpdated`,{added:[e],removed:[]}))}validateLobbyOperation(e){let t=this._tsCall.conversationType?this._tsCall.conversationType:`oneToOneCall`;if(this.logger.info(`Current conversation type is: `,t),!this._lobbySupportedConversationTypes.find((e=>e===t)))throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.CONV_UNSUPPORTED});if(e){let t=this._call.remoteParticipants.find((t=>K2(t.identifier)===K2(e)));if(t&&t.state===`Connected`)throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.ALREADY_IN_MEETING,defaultErrorMessageArgs:[OG(e).kind]});if(t&&t.state!==`InLobby`||!t)throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.NOT_IN_LOBBY,defaultErrorMessageArgs:[OG(e).kind]})}if(this._call.role!==z2.Presenter&&this._call.role!==z2.Organizer&&this._call.role!==z2.Coorganizer)throw this._hasExpectedError=!0,new Y({defaultError:J.LOBBY.UNAUTHORIZED_ADMIT_REJECT})}handleLobbyAdmitAndRejectFailure(e,t,n,r,i,a){let o=+new Date,s=rDe(this.logger,t,e);throw this._sendLobbyAdmitAndRejectUsage(s.message,i,n,$.failure,o-r,a,t),s}_sendLobbyAdmitAndRejectUsage(e,t,n,r,i,a,o){r===$.failure?this.logger.error(e):this.logger.info(e),this.sendLobbyAdmitAndRejectEvent({eventName:Q.acs_calling_lobby_events,callId:this._call.id,localParticipantId:this._tsCall.participantId,correlationId:n,kindOfEvent:r,operation:t,isExpected:a??``,timestampInfo:i?{deltaTimeInMs:i}:``,additionalDetails:o?{failureReason:o.message,code:o.code,subCode:o.subCode,...J3(o)}:``})}sendLobbyAdmitAndRejectEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send lobby admit and reject telemetry`)}}};function yIe(){let e=window.navigator.mediaDevices;if(e?.isRemote){let t=e?.MSRDC_MMR_Shim?.remoteObjectManager?.isConnected;if(!0===t)return`connected`;if(!1===t)return`disconnected`}return``}function a7(){let e=window.navigator.mediaDevices,t={isMMREnabled:e?.isRemote??!1};return t.isMMREnabled&&(e?.mmrClientVersion&&(t.mmrClientVersion=e.mmrClientVersion),e?.mmrExtensionVersion&&(t.mmrExtensionVersion=e.mmrExtensionVersion),e?.mmrHostVersion&&(t.mmrHostVersion=e.mmrHostVersion),e?.activityId&&(t.mmrActivityId=e.activityId),e?.connectionId&&(t.mmrConnectionId=e.connectionId),t.mmrRdpState=yIe()),t}n7([UG,r7(`design:type`,Object)],i7.prototype,`logger`,void 0),n7([YG(c4.LobbyAdmitParticipant),r7(`design:type`,Function),r7(`design:paramtypes`,[Object,Object]),r7(`design:returntype`,Promise)],i7.prototype,`admit`,null),n7([YG(c4.LobbyRejectParticipant),r7(`design:type`,Function),r7(`design:paramtypes`,[Object,Object]),r7(`design:returntype`,Promise)],i7.prototype,`reject`,null),n7([YG(c4.LobbyAdmitAll),r7(`design:type`,Function),r7(`design:paramtypes`,[Object]),r7(`design:returntype`,Promise)],i7.prototype,`admitAll`,null);var bIe=class{constructor(e){this._lastState=``,this._callback=e=>{let t=e?.detail?.state??``;t?t!==this._lastState&&(this._logger.info(`connection state is ${t}`),this._eventEmitter.emit(`stateChange`,t),this._lastState=t):this._logger.info(`connection state is unknown`)},this._logger=e.createChild(`MmrRdpConnectionManager`),this._eventEmitter=new E3.EventEmitter;let t=window.navigator.mediaDevices;t?.isRemote&&(t?.addEventListener(`rdpClientConnectionStateChanged`,this._callback),this._logger.info(`listener registered`))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}get state(){return yIe()}dispose(){let e=window.navigator.mediaDevices;e?.isRemote&&(e?.removeEventListener(`rdpClientConnectionStateChanged`,this._callback),this._logger.info(`event listener unregistered`)),this._eventEmitter.removeAllListeners()}},xIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},o7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},s7=class extends v8{constructor(e,t,n,r,i,a,o){let s=i.id;super(e,t,n,s,a,`RemoteVideoStream`),this._remoteParticipantIdentifier=o,this._isAvailable=!1,this.setIsAvailable=e=>{e!==this._isAvailable&&(this._isAvailable=!!e,this.logger.log(`isAvailable changed to ${this._isAvailable}`),this._eventEmitter.emit(`isAvailableChanged`,this._isAvailable),this.call.isHandlingLargeMeetingVideoRendering&&this.call.handleDominantSpeakersVideos(),super.sendRemoteVideoStreamTelemetry())};let c=()=>{if(this.mediaStreamType===`Video`&&n.isHandlingLargeMeetingVideoRendering){for(let e of n.getTopNDominantSpeakersWithVideoOn())if(this.tsStream.isAvailable&&K2(e.identifier)===K2(this._remoteParticipantIdentifier))return void this.setIsAvailable(!0);this.setIsAvailable(!1)}else i.state===7?this.setIsAvailable(!1):(i.state===3&&l.dispose(),this.setIsAvailable(this.tsStream.isAvailable))};this._streamChangedHandler=this.tsStream.changed((()=>{c()}));let l=i.changed((()=>{c()}));c()}on(e,t){if(e!==`isAvailableChanged`&&e!==`sizeChanged`&&e!==`isReceivingChanged`)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`isAvailableChanged`&&e!==`sizeChanged`&&e!==`isReceivingChanged`)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}get isAvailable(){return this._isAvailable}async getMediaStream(){let e=J0(),t=+new Date,n=this.tsStream.negotiationTag??``,r={correlationId:e,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId,negotiationTag:n},operation:y3.getMediaStream,mediaType:this.getMediaType(),streamType:v3.Remote,timestampInfo:{attemptTimestamp:t},kindOfEvent:$.attempt,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};this.sendMediaStreamEvent(r);try{if(!this.tsStream.getRawStream)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.GET_RAW_MEDIA_STREAM});if(!this.tsStream.isAvailable)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.RAWMEDIA_LVS_NOT_AVAILABLE});let r=this.tsStream.getRawStream(),i=await new Promise((async(e,t)=>{let n=setTimeout((()=>{i.dispose(),t(new Y({defaultError:J.REMOTE_VIDEO_STREAM.SUBSCRIBE_MEDIA_STREAM_TIMEOUT}))}),Z().rendering.remoteVideo.getMediaStreamTimeout),i=r.changed((()=>{a()})),a=async()=>{try{let t=await r.getMediaStream();if(!t)return void this.logger.warn(`MediaStream is not yet ready.`);clearTimeout(n),i.dispose(),e(t)}catch(e){this.logger.warn(`MediaStream is not yet ready, error=${e?.message||`unknown`}`)}};a()})),a=i.getVideoTracks()[0];if(!a)throw new Y({defaultError:J.REMOTE_VIDEO_STREAM.GET_TRACK});await new Promise(((e,t)=>{let n=()=>{a.removeEventListener(`unmute`,n,!1),e()};a.addEventListener(`unmute`,n,!1),a.muted?setTimeout((()=>{a.removeEventListener(`unmute`,n,!1),t(new Y({defaultError:J.REMOTE_VIDEO_STREAM.TRACK_UNMUTED_TIMEOUT}))}),Z().rendering.remoteVideo.getMediaStreamTimeout):n()}));let o={correlationId:e,additionalDetails:{remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId,negotiationTag:n},operation:y3.getMediaStream,mediaType:this.getMediaType(),streamType:v3.Remote,timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:$.success,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};return this.sendMediaStreamEvent(o),i}catch(r){let i={correlationId:e,operation:y3.getMediaStream,mediaType:this.getMediaType(),streamType:v3.Remote,additionalDetails:{failureReason:r?.message||``,code:r.code||BG,...J3(r),remoteStreamMetadata:this.getStreamMetadata(),mediaSourceId:this.tsStream.mediaSourceId,negotiationTag:n},timestampInfo:{deltaTimeInMs:+new Date-t},kindOfEvent:$.failure,localParticipantId:this.call.tsCall.participantId,callId:this.call.id};throw this.sendMediaStreamEvent(i),new Y({defaultError:J.REMOTE_VIDEO_STREAM.GET_MEDIA_STREAM,originalError:r})}}getStreamMetadata(){return{callId:this.call?.id,streamType:this.mediaStreamType,localParticipantId:this.call.tsCall.participantId,remoteParticipantId:this.remoteParticipantId,sourceId:this.id,source:`remote`,rank:this.tsStream.rank,isAvailable:this.tsStream.isAvailable,acsIsAvailable:this._isAvailable,isReceiving:this._isReceiving,isStreaming:this.tsStream.isStreaming,viewIdsRegistered:this._renderers.map((e=>e.viewId)).join(`, `),height:this._size.height,width:this._size.width,isDisposed:this._disposed,optimalVideoCount:this.call?.tsCall.optimalVideoCount||1,currentNumberOfVideosRendered:this.call?.activeRemoteVideoStreamViews?.size||0}}dispose(){this.setIsAvailable(!1),super.dispose()}getMediaType(){return this.mediaStreamType===`ScreenSharing`?_3.ScreenSharingRaw:_3.VideoRaw}sendMediaStreamEvent(e){this.telemetryLogManager.sendEvent({name:Q.acs_calling_media_stream,tenant:p2,properties:{timestampInfo:e.timestampInfo,correlationId:e.correlationId,additionalDetails:e.additionalDetails||``,kindOfEvent:e.kindOfEvent||``,mediaType:e.mediaType,streamType:e.streamType,operation:e.operation,localParticipantId:e.localParticipantId||``,callId:e.callId||``}})}};xIe([YG(Awe.GetMediaStream),o7(`design:type`,Function),o7(`design:paramtypes`,[]),o7(`design:returntype`,Promise)],s7.prototype,`getMediaStream`,null);var c7={2:`#050505`,4:`#0a0a0a`,6:`#0f0f0f`,8:`#141414`,10:`#1a1a1a`,12:`#1f1f1f`,14:`#242424`,16:`#292929`,18:`#2e2e2e`,20:`#333333`,22:`#383838`,24:`#3d3d3d`,26:`#424242`,28:`#474747`,30:`#4d4d4d`,32:`#525252`,34:`#575757`,36:`#5c5c5c`,38:`#616161`,40:`#666666`,42:`#6b6b6b`,44:`#707070`,46:`#757575`,48:`#7a7a7a`,50:`#808080`,52:`#858585`,54:`#8a8a8a`,56:`#8f8f8f`,58:`#949494`,60:`#999999`,62:`#9e9e9e`,64:`#a3a3a3`,66:`#a8a8a8`,68:`#adadad`,70:`#b3b3b3`,72:`#b8b8b8`,74:`#bdbdbd`,76:`#c2c2c2`,78:`#c7c7c7`,80:`#cccccc`,82:`#d1d1d1`,84:`#d6d6d6`,86:`#dbdbdb`,88:`#e0e0e0`,90:`#e6e6e6`,92:`#ebebeb`,94:`#f0f0f0`,96:`#f5f5f5`,98:`#fafafa`},l7={5:`rgba(255, 255, 255, 0.05)`,10:`rgba(255, 255, 255, 0.1)`,20:`rgba(255, 255, 255, 0.2)`,30:`rgba(255, 255, 255, 0.3)`,40:`rgba(255, 255, 255, 0.4)`,50:`rgba(255, 255, 255, 0.5)`,60:`rgba(255, 255, 255, 0.6)`,70:`rgba(255, 255, 255, 0.7)`,80:`rgba(255, 255, 255, 0.8)`,90:`rgba(255, 255, 255, 0.9)`},u7={5:`rgba(0, 0, 0, 0.05)`,10:`rgba(0, 0, 0, 0.1)`,20:`rgba(0, 0, 0, 0.2)`,30:`rgba(0, 0, 0, 0.3)`,40:`rgba(0, 0, 0, 0.4)`,50:`rgba(0, 0, 0, 0.5)`,60:`rgba(0, 0, 0, 0.6)`,70:`rgba(0, 0, 0, 0.7)`,80:`rgba(0, 0, 0, 0.8)`,90:`rgba(0, 0, 0, 0.9)`},d7=`#ffffff`,SIe=`#000000`,CIe={shade50:`#200205`,shade40:`#3b0509`,shade30:`#6e0811`,shade20:`#960b18`,shade10:`#b10e1c`,primary:`#c50f1f`,tint10:`#cc2635`,tint20:`#d33f4c`,tint30:`#dc626d`,tint40:`#eeacb2`,tint50:`#f6d1d5`,tint60:`#fdf3f4`},wIe={shade50:`#031403`,shade40:`#052505`,shade30:`#094509`,shade20:`#0c5e0c`,shade10:`#0e700e`,primary:`#107c10`,tint10:`#218c21`,tint20:`#359b35`,tint30:`#54b054`,tint40:`#9fd89f`,tint50:`#c9eac9`,tint60:`#f1faf1`},f7={red:{shade50:`#210809`,shade40:`#3f1011`,shade30:`#751d1f`,shade20:`#9f282b`,shade10:`#bc2f32`,primary:`#d13438`,tint10:`#d7494c`,tint20:`#dc5e62`,tint30:`#e37d80`,tint40:`#f1bbbc`,tint50:`#f8dadb`,tint60:`#fdf6f6`},green:wIe,darkOrange:{shade50:`#230900`,shade40:`#411200`,shade30:`#7a2101`,shade20:`#a62d01`,shade10:`#c43501`,primary:`#da3b01`,tint10:`#de501c`,tint20:`#e36537`,tint30:`#e9835e`,tint40:`#f4bfab`,tint50:`#f9dcd1`,tint60:`#fdf6f3`},yellow:{shade50:`#282400`,shade40:`#4c4400`,shade30:`#817400`,shade20:`#c0ad00`,shade10:`#e4cc00`,primary:`#fde300`,tint10:`#fde61e`,tint20:`#fdea3d`,tint30:`#feee66`,tint40:`#fef7b2`,tint50:`#fffad6`,tint60:`#fffef5`},berry:{shade50:`#1f091d`,shade40:`#3a1136`,shade30:`#6d2064`,shade20:`#932b88`,shade10:`#af33a1`,primary:`#c239b3`,tint10:`#c94cbc`,tint20:`#d161c4`,tint30:`#da7ed0`,tint40:`#edbbe7`,tint50:`#f5daf2`,tint60:`#fdf5fc`},lightGreen:{shade50:`#031a02`,shade40:`#063004`,shade30:`#0b5a08`,shade20:`#0e7a0b`,shade10:`#11910d`,primary:`#13a10e`,tint10:`#27ac22`,tint20:`#3db838`,tint30:`#5ec75a`,tint40:`#a7e3a5`,tint50:`#cef0cd`,tint60:`#f2fbf2`},marigold:{shade50:`#251a00`,shade40:`#463100`,shade30:`#835b00`,shade20:`#b27c00`,shade10:`#d39300`,primary:`#eaa300`,tint10:`#edad1c`,tint20:`#efb839`,tint30:`#f2c661`,tint40:`#f9e2ae`,tint50:`#fcefd3`,tint60:`#fefbf4`}},p7={darkRed:{shade50:`#130204`,shade40:`#230308`,shade30:`#420610`,shade20:`#590815`,shade10:`#690a19`,primary:`#750b1c`,tint10:`#861b2c`,tint20:`#962f3f`,tint30:`#ac4f5e`,tint40:`#d69ca5`,tint50:`#e9c7cd`,tint60:`#f9f0f2`},cranberry:CIe,pumpkin:{shade50:`#200d03`,shade40:`#3d1805`,shade30:`#712d09`,shade20:`#9a3d0c`,shade10:`#b6480e`,primary:`#ca5010`,tint10:`#d06228`,tint20:`#d77440`,tint30:`#df8e64`,tint40:`#efc4ad`,tint50:`#f7dfd2`,tint60:`#fdf7f4`},peach:{shade50:`#291600`,shade40:`#4d2a00`,shade30:`#8f4e00`,shade20:`#c26a00`,shade10:`#e67e00`,primary:`#ff8c00`,tint10:`#ff9a1f`,tint20:`#ffa83d`,tint30:`#ffba66`,tint40:`#ffddb3`,tint50:`#ffedd6`,tint60:`#fffaf5`},gold:{shade50:`#1f1900`,shade40:`#3a2f00`,shade30:`#6c5700`,shade20:`#937700`,shade10:`#ae8c00`,primary:`#c19c00`,tint10:`#c8a718`,tint20:`#d0b232`,tint30:`#dac157`,tint40:`#ecdfa5`,tint50:`#f5eece`,tint60:`#fdfbf2`},brass:{shade50:`#181202`,shade40:`#2e2103`,shade30:`#553e06`,shade20:`#745408`,shade10:`#89640a`,primary:`#986f0b`,tint10:`#a47d1e`,tint20:`#b18c34`,tint30:`#c1a256`,tint40:`#e0cea2`,tint50:`#efe4cb`,tint60:`#fbf8f2`},brown:{shade50:`#170e07`,shade40:`#2b1a0e`,shade30:`#50301a`,shade20:`#6c4123`,shade10:`#804d29`,primary:`#8e562e`,tint10:`#9c663f`,tint20:`#a97652`,tint30:`#bb8f6f`,tint40:`#ddc3b0`,tint50:`#edded3`,tint60:`#faf7f4`},forest:{shade50:`#0c1501`,shade40:`#162702`,shade30:`#294903`,shade20:`#376304`,shade10:`#427505`,primary:`#498205`,tint10:`#599116`,tint20:`#6ba02b`,tint30:`#85b44c`,tint40:`#bdd99b`,tint50:`#dbebc7`,tint60:`#f6faf0`},seafoam:{shade50:`#002111`,shade40:`#003d20`,shade30:`#00723b`,shade20:`#009b51`,shade10:`#00b85f`,primary:`#00cc6a`,tint10:`#19d279`,tint20:`#34d889`,tint30:`#5ae0a0`,tint40:`#a8f0cd`,tint50:`#cff7e4`,tint60:`#f3fdf8`},darkGreen:{shade50:`#021102`,shade40:`#032003`,shade30:`#063b06`,shade20:`#085108`,shade10:`#0a5f0a`,primary:`#0b6a0b`,tint10:`#1a7c1a`,tint20:`#2d8e2d`,tint30:`#4da64d`,tint40:`#9ad29a`,tint50:`#c6e7c6`,tint60:`#f0f9f0`},lightTeal:{shade50:`#001d1f`,shade40:`#00373a`,shade30:`#00666d`,shade20:`#008b94`,shade10:`#00a5af`,primary:`#00b7c3`,tint10:`#18bfca`,tint20:`#32c8d1`,tint30:`#58d3db`,tint40:`#a6e9ed`,tint50:`#cef3f5`,tint60:`#f2fcfd`},teal:{shade50:`#001516`,shade40:`#012728`,shade30:`#02494c`,shade20:`#026467`,shade10:`#037679`,primary:`#038387`,tint10:`#159195`,tint20:`#2aa0a4`,tint30:`#4cb4b7`,tint40:`#9bd9db`,tint50:`#c7ebec`,tint60:`#f0fafa`},steel:{shade50:`#000f12`,shade40:`#001b22`,shade30:`#00333f`,shade20:`#004555`,shade10:`#005265`,primary:`#005b70`,tint10:`#0f6c81`,tint20:`#237d92`,tint30:`#4496a9`,tint40:`#94c8d4`,tint50:`#c3e1e8`,tint60:`#eff7f9`},blue:{shade50:`#001322`,shade40:`#002440`,shade30:`#004377`,shade20:`#005ba1`,shade10:`#006cbf`,primary:`#0078d4`,tint10:`#1a86d9`,tint20:`#3595de`,tint30:`#5caae5`,tint40:`#a9d3f2`,tint50:`#d0e7f8`,tint60:`#f3f9fd`},royalBlue:{shade50:`#000c16`,shade40:`#00172a`,shade30:`#002c4e`,shade20:`#003b6a`,shade10:`#00467e`,primary:`#004e8c`,tint10:`#125e9a`,tint20:`#286fa8`,tint30:`#4a89ba`,tint40:`#9abfdc`,tint50:`#c7dced`,tint60:`#f0f6fa`},cornflower:{shade50:`#0d1126`,shade40:`#182047`,shade30:`#2c3c85`,shade20:`#3c51b4`,shade10:`#4760d5`,primary:`#4f6bed`,tint10:`#637cef`,tint20:`#778df1`,tint30:`#93a4f4`,tint40:`#c8d1fa`,tint50:`#e1e6fc`,tint60:`#f7f9fe`},navy:{shade50:`#00061d`,shade40:`#000c36`,shade30:`#001665`,shade20:`#001e89`,shade10:`#0023a2`,primary:`#0027b4`,tint10:`#173bbd`,tint20:`#3050c6`,tint30:`#546fd2`,tint40:`#a3b2e8`,tint50:`#ccd5f3`,tint60:`#f2f4fc`},lavender:{shade50:`#120f25`,shade40:`#221d46`,shade30:`#3f3682`,shade20:`#5649b0`,shade10:`#6656d1`,primary:`#7160e8`,tint10:`#8172eb`,tint20:`#9184ee`,tint30:`#a79cf1`,tint40:`#d2ccf8`,tint50:`#e7e4fb`,tint60:`#f9f8fe`},purple:{shade50:`#0f0717`,shade40:`#1c0e2b`,shade30:`#341a51`,shade20:`#46236e`,shade10:`#532982`,primary:`#5c2e91`,tint10:`#6b3f9e`,tint20:`#7c52ab`,tint30:`#9470bd`,tint40:`#c6b1de`,tint50:`#e0d3ed`,tint60:`#f7f4fb`},grape:{shade50:`#160418`,shade40:`#29072e`,shade30:`#4c0d55`,shade20:`#671174`,shade10:`#7a1589`,primary:`#881798`,tint10:`#952aa4`,tint20:`#a33fb1`,tint30:`#b55fc1`,tint40:`#d9a7e0`,tint50:`#eaceef`,tint60:`#faf2fb`},lilac:{shade50:`#1c0b1f`,shade40:`#35153a`,shade30:`#63276d`,shade20:`#863593`,shade10:`#9f3faf`,primary:`#b146c2`,tint10:`#ba58c9`,tint20:`#c36bd1`,tint30:`#cf87da`,tint40:`#e6bfed`,tint50:`#f2dcf5`,tint60:`#fcf6fd`},pink:{shade50:`#24091b`,shade40:`#441232`,shade30:`#80215d`,shade20:`#ad2d7e`,shade10:`#cd3595`,primary:`#e43ba6`,tint10:`#e750b0`,tint20:`#ea66ba`,tint30:`#ef85c8`,tint40:`#f7c0e3`,tint50:`#fbddf0`,tint60:`#fef6fb`},magenta:{shade50:`#1f0013`,shade40:`#390024`,shade30:`#6b0043`,shade20:`#91005a`,shade10:`#ac006b`,primary:`#bf0077`,tint10:`#c71885`,tint20:`#ce3293`,tint30:`#d957a8`,tint40:`#eca5d1`,tint50:`#f5cee6`,tint60:`#fcf2f9`},plum:{shade50:`#13000c`,shade40:`#240017`,shade30:`#43002b`,shade20:`#5a003b`,shade10:`#6b0045`,primary:`#77004d`,tint10:`#87105d`,tint20:`#98246f`,tint30:`#ad4589`,tint40:`#d696c0`,tint50:`#e9c4dc`,tint60:`#faf0f6`},beige:{shade50:`#141313`,shade40:`#252323`,shade30:`#444241`,shade20:`#5d5958`,shade10:`#6e6968`,primary:`#7a7574`,tint10:`#8a8584`,tint20:`#9a9594`,tint30:`#afabaa`,tint40:`#d7d4d4`,tint50:`#eae8e8`,tint60:`#faf9f9`},mink:{shade50:`#0f0e0e`,shade40:`#1c1b1a`,shade30:`#343231`,shade20:`#474443`,shade10:`#54514f`,primary:`#5d5a58`,tint10:`#706d6b`,tint20:`#84817e`,tint30:`#9e9b99`,tint40:`#cecccb`,tint50:`#e5e4e3`,tint60:`#f8f8f8`},platinum:{shade50:`#111314`,shade40:`#1f2426`,shade30:`#3b4447`,shade20:`#505c60`,shade10:`#5f6d71`,primary:`#69797e`,tint10:`#79898d`,tint20:`#89989d`,tint30:`#a0adb2`,tint40:`#cdd6d8`,tint50:`#e4e9ea`,tint60:`#f8f9fa`},anchor:{shade50:`#090a0b`,shade40:`#111315`,shade30:`#202427`,shade20:`#2b3135`,shade10:`#333a3f`,primary:`#394146`,tint10:`#4d565c`,tint20:`#626c72`,tint30:`#808a90`,tint40:`#bcc3c7`,tint50:`#dbdfe1`,tint60:`#f6f7f8`}},m7={cranberry:CIe,green:wIe,orange:{shade50:`#271002`,shade40:`#4a1e04`,shade30:`#8a3707`,shade20:`#bc4b09`,shade10:`#de590b`,primary:`#f7630c`,tint10:`#f87528`,tint20:`#f98845`,tint30:`#faa06b`,tint40:`#fdcfb4`,tint50:`#fee5d7`,tint60:`#fff9f5`}},TIe=`darkRed.cranberry.pumpkin.peach.gold.brass.brown.forest.seafoam.darkGreen.lightTeal.teal.steel.blue.royalBlue.cornflower.navy.lavender.purple.grape.lilac.pink.magenta.plum.beige.mink.platinum.anchor`.split(`.`),h7={success:`green`,warning:`orange`,danger:`cranberry`},g7=[`red`,`green`,`darkOrange`,`yellow`,`berry`,`lightGreen`,`marigold`].reduce(((e,t)=>{let n=t.slice(0,1).toUpperCase()+t.slice(1),r={[`colorPalette${n}Background1`]:f7[t].tint60,[`colorPalette${n}Background2`]:f7[t].tint40,[`colorPalette${n}Background3`]:f7[t].primary,[`colorPalette${n}Foreground1`]:f7[t].shade10,[`colorPalette${n}Foreground2`]:f7[t].shade30,[`colorPalette${n}Foreground3`]:f7[t].primary,[`colorPalette${n}BorderActive`]:f7[t].primary,[`colorPalette${n}Border1`]:f7[t].tint40,[`colorPalette${n}Border2`]:f7[t].primary};return Object.assign(e,r)}),{});g7.colorPaletteYellowForeground1=f7.yellow.shade30,g7.colorPaletteRedForegroundInverted=f7.red.tint20,g7.colorPaletteGreenForegroundInverted=f7.green.tint20,g7.colorPaletteYellowForegroundInverted=f7.yellow.tint40;var EIe=TIe.reduce(((e,t)=>{let n=t.slice(0,1).toUpperCase()+t.slice(1),r={[`colorPalette${n}Background2`]:p7[t].tint40,[`colorPalette${n}Foreground2`]:p7[t].shade30,[`colorPalette${n}BorderActive`]:p7[t].primary};return Object.assign(e,r)}),{}),DIe={...g7,...EIe},_7=Object.entries(h7).reduce(((e,[t,n])=>{let r=t.slice(0,1).toUpperCase()+t.slice(1),i={[`colorStatus${r}Background1`]:m7[n].tint60,[`colorStatus${r}Background2`]:m7[n].tint40,[`colorStatus${r}Background3`]:m7[n].primary,[`colorStatus${r}Foreground1`]:m7[n].shade10,[`colorStatus${r}Foreground2`]:m7[n].shade30,[`colorStatus${r}Foreground3`]:m7[n].primary,[`colorStatus${r}ForegroundInverted`]:m7[n].tint30,[`colorStatus${r}BorderActive`]:m7[n].primary,[`colorStatus${r}Border1`]:m7[n].tint40,[`colorStatus${r}Border2`]:m7[n].primary};return Object.assign(e,i)}),{});_7.colorStatusDangerBackground3Hover=m7[h7.danger].shade10,_7.colorStatusDangerBackground3Pressed=m7[h7.danger].shade20,_7.colorStatusWarningForeground1=m7[h7.warning].shade20,_7.colorStatusWarningForeground3=m7[h7.warning].shade20,_7.colorStatusWarningBorder2=m7[h7.warning].shade20;var OIe=e=>({colorNeutralForeground1:c7[14],colorNeutralForeground1Hover:c7[14],colorNeutralForeground1Pressed:c7[14],colorNeutralForeground1Selected:c7[14],colorNeutralForeground2:c7[26],colorNeutralForeground2Hover:c7[14],colorNeutralForeground2Pressed:c7[14],colorNeutralForeground2Selected:c7[14],colorNeutralForeground2BrandHover:e[80],colorNeutralForeground2BrandPressed:e[70],colorNeutralForeground2BrandSelected:e[80],colorNeutralForeground3:c7[38],colorNeutralForeground3Hover:c7[26],colorNeutralForeground3Pressed:c7[26],colorNeutralForeground3Selected:c7[26],colorNeutralForeground3BrandHover:e[80],colorNeutralForeground3BrandPressed:e[70],colorNeutralForeground3BrandSelected:e[80],colorNeutralForeground4:c7[44],colorNeutralForegroundDisabled:c7[74],colorNeutralForegroundInvertedDisabled:l7[40],colorBrandForegroundLink:e[70],colorBrandForegroundLinkHover:e[60],colorBrandForegroundLinkPressed:e[40],colorBrandForegroundLinkSelected:e[70],colorNeutralForeground2Link:c7[26],colorNeutralForeground2LinkHover:c7[14],colorNeutralForeground2LinkPressed:c7[14],colorNeutralForeground2LinkSelected:c7[14],colorCompoundBrandForeground1:e[80],colorCompoundBrandForeground1Hover:e[70],colorCompoundBrandForeground1Pressed:e[60],colorBrandForeground1:e[80],colorBrandForeground2:e[70],colorBrandForeground2Hover:e[60],colorBrandForeground2Pressed:e[30],colorNeutralForeground1Static:c7[14],colorNeutralForegroundStaticInverted:d7,colorNeutralForegroundInverted:d7,colorNeutralForegroundInvertedHover:d7,colorNeutralForegroundInvertedPressed:d7,colorNeutralForegroundInvertedSelected:d7,colorNeutralForegroundInverted2:d7,colorNeutralForegroundOnBrand:d7,colorNeutralForegroundInvertedLink:d7,colorNeutralForegroundInvertedLinkHover:d7,colorNeutralForegroundInvertedLinkPressed:d7,colorNeutralForegroundInvertedLinkSelected:d7,colorBrandForegroundInverted:e[100],colorBrandForegroundInvertedHover:e[110],colorBrandForegroundInvertedPressed:e[100],colorBrandForegroundOnLight:e[80],colorBrandForegroundOnLightHover:e[70],colorBrandForegroundOnLightPressed:e[50],colorBrandForegroundOnLightSelected:e[60],colorNeutralBackground1:d7,colorNeutralBackground1Hover:c7[96],colorNeutralBackground1Pressed:c7[88],colorNeutralBackground1Selected:c7[92],colorNeutralBackground2:c7[98],colorNeutralBackground2Hover:c7[94],colorNeutralBackground2Pressed:c7[86],colorNeutralBackground2Selected:c7[90],colorNeutralBackground3:c7[96],colorNeutralBackground3Hover:c7[92],colorNeutralBackground3Pressed:c7[84],colorNeutralBackground3Selected:c7[88],colorNeutralBackground4:c7[94],colorNeutralBackground4Hover:c7[98],colorNeutralBackground4Pressed:c7[96],colorNeutralBackground4Selected:d7,colorNeutralBackground5:c7[92],colorNeutralBackground5Hover:c7[96],colorNeutralBackground5Pressed:c7[94],colorNeutralBackground5Selected:c7[98],colorNeutralBackground6:c7[90],colorNeutralBackgroundInverted:c7[16],colorNeutralBackgroundStatic:c7[20],colorNeutralBackgroundAlpha:l7[50],colorNeutralBackgroundAlpha2:l7[80],colorSubtleBackground:`transparent`,colorSubtleBackgroundHover:c7[96],colorSubtleBackgroundPressed:c7[88],colorSubtleBackgroundSelected:c7[92],colorSubtleBackgroundLightAlphaHover:l7[70],colorSubtleBackgroundLightAlphaPressed:l7[50],colorSubtleBackgroundLightAlphaSelected:`transparent`,colorSubtleBackgroundInverted:`transparent`,colorSubtleBackgroundInvertedHover:u7[10],colorSubtleBackgroundInvertedPressed:u7[30],colorSubtleBackgroundInvertedSelected:u7[20],colorTransparentBackground:`transparent`,colorTransparentBackgroundHover:`transparent`,colorTransparentBackgroundPressed:`transparent`,colorTransparentBackgroundSelected:`transparent`,colorNeutralBackgroundDisabled:c7[94],colorNeutralBackgroundInvertedDisabled:l7[10],colorNeutralStencil1:c7[90],colorNeutralStencil2:c7[98],colorNeutralStencil1Alpha:u7[10],colorNeutralStencil2Alpha:u7[5],colorBackgroundOverlay:u7[40],colorScrollbarOverlay:u7[50],colorBrandBackground:e[80],colorBrandBackgroundHover:e[70],colorBrandBackgroundPressed:e[40],colorBrandBackgroundSelected:e[60],colorCompoundBrandBackground:e[80],colorCompoundBrandBackgroundHover:e[70],colorCompoundBrandBackgroundPressed:e[60],colorBrandBackgroundStatic:e[80],colorBrandBackground2:e[160],colorBrandBackground2Hover:e[150],colorBrandBackground2Pressed:e[130],colorBrandBackground3Static:e[60],colorBrandBackground4Static:e[40],colorBrandBackgroundInverted:d7,colorBrandBackgroundInvertedHover:e[160],colorBrandBackgroundInvertedPressed:e[140],colorBrandBackgroundInvertedSelected:e[150],colorNeutralCardBackground:c7[98],colorNeutralCardBackgroundHover:d7,colorNeutralCardBackgroundPressed:c7[96],colorNeutralCardBackgroundSelected:c7[92],colorNeutralCardBackgroundDisabled:c7[94],colorNeutralStrokeAccessible:c7[38],colorNeutralStrokeAccessibleHover:c7[34],colorNeutralStrokeAccessiblePressed:c7[30],colorNeutralStrokeAccessibleSelected:e[80],colorNeutralStroke1:c7[82],colorNeutralStroke1Hover:c7[78],colorNeutralStroke1Pressed:c7[70],colorNeutralStroke1Selected:c7[74],colorNeutralStroke2:c7[88],colorNeutralStroke3:c7[94],colorNeutralStrokeSubtle:c7[88],colorNeutralStrokeOnBrand:d7,colorNeutralStrokeOnBrand2:d7,colorNeutralStrokeOnBrand2Hover:d7,colorNeutralStrokeOnBrand2Pressed:d7,colorNeutralStrokeOnBrand2Selected:d7,colorBrandStroke1:e[80],colorBrandStroke2:e[140],colorBrandStroke2Hover:e[120],colorBrandStroke2Pressed:e[80],colorBrandStroke2Contrast:e[140],colorCompoundBrandStroke:e[80],colorCompoundBrandStrokeHover:e[70],colorCompoundBrandStrokePressed:e[60],colorNeutralStrokeDisabled:c7[88],colorNeutralStrokeInvertedDisabled:l7[40],colorTransparentStroke:`transparent`,colorTransparentStrokeInteractive:`transparent`,colorTransparentStrokeDisabled:`transparent`,colorNeutralStrokeAlpha:u7[5],colorNeutralStrokeAlpha2:l7[20],colorStrokeFocus1:d7,colorStrokeFocus2:SIe,colorNeutralShadowAmbient:`rgba(0,0,0,0.12)`,colorNeutralShadowKey:`rgba(0,0,0,0.14)`,colorNeutralShadowAmbientLighter:`rgba(0,0,0,0.06)`,colorNeutralShadowKeyLighter:`rgba(0,0,0,0.07)`,colorNeutralShadowAmbientDarker:`rgba(0,0,0,0.20)`,colorNeutralShadowKeyDarker:`rgba(0,0,0,0.24)`,colorBrandShadowAmbient:`rgba(0,0,0,0.30)`,colorBrandShadowKey:`rgba(0,0,0,0.25)`}),kIe={borderRadiusNone:`0`,borderRadiusSmall:`2px`,borderRadiusMedium:`4px`,borderRadiusLarge:`6px`,borderRadiusXLarge:`8px`,borderRadiusCircular:`10000px`},AIe={curveAccelerateMax:`cubic-bezier(0.9,0.1,1,0.2)`,curveAccelerateMid:`cubic-bezier(1,0,1,1)`,curveAccelerateMin:`cubic-bezier(0.8,0,0.78,1)`,curveDecelerateMax:`cubic-bezier(0.1,0.9,0.2,1)`,curveDecelerateMid:`cubic-bezier(0,0,0,1)`,curveDecelerateMin:`cubic-bezier(0.33,0,0.1,1)`,curveEasyEaseMax:`cubic-bezier(0.8,0,0.2,1)`,curveEasyEase:`cubic-bezier(0.33,0,0.67,1)`,curveLinear:`cubic-bezier(0,0,1,1)`},jIe={durationUltraFast:`50ms`,durationFaster:`100ms`,durationFast:`150ms`,durationNormal:`200ms`,durationGentle:`250ms`,durationSlow:`300ms`,durationSlower:`400ms`,durationUltraSlow:`500ms`},MIe={fontSizeBase100:`10px`,fontSizeBase200:`12px`,fontSizeBase300:`14px`,fontSizeBase400:`16px`,fontSizeBase500:`20px`,fontSizeBase600:`24px`,fontSizeHero700:`28px`,fontSizeHero800:`32px`,fontSizeHero900:`40px`,fontSizeHero1000:`68px`},NIe={lineHeightBase100:`14px`,lineHeightBase200:`16px`,lineHeightBase300:`20px`,lineHeightBase400:`22px`,lineHeightBase500:`28px`,lineHeightBase600:`32px`,lineHeightHero700:`36px`,lineHeightHero800:`40px`,lineHeightHero900:`52px`,lineHeightHero1000:`92px`},PIe={fontWeightRegular:400,fontWeightMedium:500,fontWeightSemibold:600,fontWeightBold:700},FIe={fontFamilyBase:`'Segoe UI', 'Segoe UI Web (West European)', -apple-system, BlinkMacSystemFont, Roboto, 'Helvetica Neue', sans-serif`,fontFamilyMonospace:`Consolas, 'Courier New', Courier, monospace`,fontFamilyNumeric:`Bahnschrift, 'Segoe UI', 'Segoe UI Web (West European)', -apple-system, BlinkMacSystemFont, Roboto, 'Helvetica Neue', sans-serif`},v7={none:`0`,xxs:`2px`,xs:`4px`,sNudge:`6px`,s:`8px`,mNudge:`10px`,m:`12px`,l:`16px`,xl:`20px`,xxl:`24px`,xxxl:`32px`},IIe={spacingHorizontalNone:v7.none,spacingHorizontalXXS:v7.xxs,spacingHorizontalXS:v7.xs,spacingHorizontalSNudge:v7.sNudge,spacingHorizontalS:v7.s,spacingHorizontalMNudge:v7.mNudge,spacingHorizontalM:v7.m,spacingHorizontalL:v7.l,spacingHorizontalXL:v7.xl,spacingHorizontalXXL:v7.xxl,spacingHorizontalXXXL:v7.xxxl},LIe={spacingVerticalNone:v7.none,spacingVerticalXXS:v7.xxs,spacingVerticalXS:v7.xs,spacingVerticalSNudge:v7.sNudge,spacingVerticalS:v7.s,spacingVerticalMNudge:v7.mNudge,spacingVerticalM:v7.m,spacingVerticalL:v7.l,spacingVerticalXL:v7.xl,spacingVerticalXXL:v7.xxl,spacingVerticalXXXL:v7.xxxl},RIe={strokeWidthThin:`1px`,strokeWidthThick:`2px`,strokeWidthThicker:`3px`,strokeWidthThickest:`4px`};function zIe(e,t,n=``){return{[`shadow2${n}`]:`0 0 2px ${e}, 0 1px 2px ${t}`,[`shadow4${n}`]:`0 0 2px ${e}, 0 2px 4px ${t}`,[`shadow8${n}`]:`0 0 2px ${e}, 0 4px 8px ${t}`,[`shadow16${n}`]:`0 0 2px ${e}, 0 8px 16px ${t}`,[`shadow28${n}`]:`0 0 8px ${e}, 0 14px 28px ${t}`,[`shadow64${n}`]:`0 0 8px ${e}, 0 32px 64px ${t}`}}var BIe=(e=>{let t=OIe(e);return{...kIe,...MIe,...NIe,...FIe,...PIe,...RIe,...IIe,...LIe,...jIe,...AIe,...t,...DIe,..._7,...zIe(t.colorNeutralShadowAmbient,t.colorNeutralShadowKey),...zIe(t.colorBrandShadowAmbient,t.colorBrandShadowKey,`Brand`)}})({10:`#061724`,20:`#082338`,30:`#0a2e4a`,40:`#0c3b5e`,50:`#0e4775`,60:`#0f548c`,70:`#115ea3`,80:`#0f6cbd`,90:`#2886de`,100:`#479ef5`,110:`#62abf5`,120:`#77b7f7`,130:`#96c6fa`,140:`#b4d6fa`,150:`#cfe4fa`,160:`#ebf3fc`}),VIe=1,HIe=class{constructor(e,t,n,r,i){this._container=e,this._videoStream=t,this._viewId=n,this._streamTelemetryEventSender=i,this._watermarkCapability=null,this.WATERMARK_TEXT_COMMON_STYLES={fontFamily:BIe.fontFamilyBase,fontWeight:`bold`,stroke:`black`,strokeOpacity:`0.1`,fill:BIe.colorNeutralStrokeOnBrand2},this.WATERMARK_CONTAINER_STYLES={position:`absolute`,pointerEvents:`none`,width:`100%`,height:`100%`,top:`0`,left:`0`},this.TEXT_ROTATION=30,this.SHADOW_OPACITY_RATIO=3,this.RANGE_MAX=100,this.BORDER_SIZE=18,this.BORDER_SIZE_FRAC=1/this.BORDER_SIZE,this.SPACE_USE=.9,this.MAX_BORDER=2,this.SINGLE_PATTERN_FONT_SIZE_FACTOR=.07,this._svgContainerHidden=``,this._svgWatermarkUseTextScale=0,this._svgWatermarkUseTextBorderSize=0,this._svgTextTiledScaledSize=0,this._svgTextTiledScaledStrokeWidth=0,this._svgFirstPatternWidth=0,this._svgFirstPatternHeight=0,this._svgSecondPatternWidth=0,this._svgSecondPatternHeight=0,this._svgSecondPatternOffsetX=0,this._svgSecondPatternOffsetY=0,this._computeTextDiagonal=wwe(this.TEXT_ROTATION),this._isApple=!1,this._getScaledPatternDimensions=(e,t,n,r)=>({width:e*(n+1.1),height:t*(r+1.1)}),this._call=this._videoStream.call,this._logger=r.createChild(`WatermarkOverlayProvider`+ VIe++);let a=this._call.getMeetingCapabilitiesInternal();if(!a){this._logger.warn(`No watermark capabilities found. Likely not received from service.`);let e=new Y({defaultError:J.VIEW.NO_WATERMARK_CAPABILITY_RECEIVED}),t=J0();this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:y3.watermark,kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{failureReason:e.message,code:e.code,...J3(e),watermark:{...this._getWatermarkUsageTelemetryPayload()}}});return}this._watermarkCapability=a.waterMarkCapability;let o=this._call.deviceManager.getOSNameInternal();this._isApple=o===`ios`||o===`mac`,this._resizeObserver=new ResizeObserver((e=>{for(let t of e)if(t.contentRect?.width>1){let e=t.contentRect.width,n=t.contentRect.height;this._updateWatermarkScalingValues(e,n)}})),this._resizeObserver.observe(this._container)}attach(){let e=J0(),t=Date.now();try{if(!this._watermarkCapability)return void this._logger.warn(`No watermark capabilities found. No-op.`);if(this._videoStream.mediaStreamType!==`Video`&&this._videoStream.mediaStreamType!==`ScreenSharing`)throw Error(`Unsupported media type for watermark`);this._watermarkIsReceivingSub=()=>{this._videoStream.isReceiving&&(this._generateWatermark(this._videoStream.mediaStreamType,e),this._updateWatermarkScalingValues(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height))},this._videoStream.on(`isReceivingChanged`,this._watermarkIsReceivingSub)}catch(n){let r=new Y({defaultError:J.VIEW.WATERMARK_ATTACH_FAIL,originalError:n});throw this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:e,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-t},operation:y3.watermark,kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{failureReason:r.message,code:r.code,...J3(r),watermark:{...this._getWatermarkUsageTelemetryPayload()}}}),r}}dispose(){this._resizeObserver&&this._resizeObserver.disconnect(),this._mutationObserver&&this._mutationObserver.disconnect(),this._audioOnlyCallback&&this._call.offWatermarkAudioOnlyFallbackTriggeredChanged(`watermarkAudioOnlyFallbackTriggeredChanged`,this._audioOnlyCallback),this._svgContainer&&(this._container.removeChild(this._svgContainer),this._svgContainer=void 0,this._svgContainerHidden=``),this._watermarkIsReceivingSub&&this._videoStream.off(`isReceivingChanged`,this._watermarkIsReceivingSub),this._logger.info(`watermark overlay provider disposed for viewid: ${this._viewId}`)}_updateWatermarkScalingValues(e,t){this._getSelectedWatermarkPattern()===`Single`?this._updateWatermarkUseTextScalingSingle(e,t):this._getSelectedWatermarkPattern()===`Tiled`&&this._updateWatermarkPatternScalingTiled(e,t)}_generateWatermark(e,t){let n=Date.now();try{if(!this._watermarkCapability)return void this._logger.warn(`No watermark capabilities found. No-op.`);if(this._call.watermarkAudioOnlyFallbackTriggered)return this._logger.warn(`Watermark audio only fallback was triggered, disposing remote stream`),void this._videoStream.dispose();let r;if(e===`Video`&&this._watermarkCapability.enabledForVideo)r=this._watermarkCapability.videoSettings;else{if(e!==`ScreenSharing`||!this._watermarkCapability.enabledForVbss)return void this._logger.info(`No watermark operations to be done on viewId: ${this._viewId}`);r=this._watermarkCapability.vbssSettings}if(this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:n},operation:y3.watermark,kindOfEvent:$.attempt,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}}),!r||!r.opacity||!r.pattern||typeof r.opacity!=`number`||typeof r.pattern!=`string`)throw this._logger.debug(`Unexpected watermark settings`),new Y({defaultError:J.VIEW.WATERMARK_UNEXPECTED_VALUES});let i=this._getClampedUsername(),a;if(r.pattern===`Single`)a=this._generateSinglePatternWatermark(i,r);else{if(r.pattern!==`Tiled`)throw this._logger.debug(`Unexpected watermark pattern setting`),new Y({defaultError:J.VIEW.WATERMARK_UNEXPECTED_VALUES});a=this._generateTiledPatternWatermark(i,r)}this._svgContainerHidden=a.outerHTML,this._container.appendChild(a),this._audioOnlyCallback=()=>{this._call.watermarkAudioOnlyFallbackTriggered&&(this._logger.debug(`Watermark audio only fallback triggered by one of the renderers`),this._logger.debug(`Disposing remote stream with viewId ${this._viewId}`),this._videoStream.dispose(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:y3.watermark,kindOfEvent:$.event,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}}))},this._call.onWatermarkAudioOnlyFallbackTriggeredChanged(`watermarkAudioOnlyFallbackTriggeredChanged`,this._audioOnlyCallback),this._mutationObserver=new MutationObserver((e=>{this._svgContainer?.outerHTML!==this._svgContainerHidden&&(this._logger.debug(`watermark mutation detected, falling back to audio only!`),this._triggerAudioOnlyFallback(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{attemptTimestamp:Date.now()},operation:y3.watermark,kindOfEvent:$.event,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload(this._viewId)}}}))})),this._mutationObserver.observe(this._container,{attributes:!0,subtree:!0,childList:!0}),this._logger.info(`watermark attached for viewId: ${this._viewId}`),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-n},operation:y3.watermark,kindOfEvent:$.success,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{watermark:{...this._getWatermarkUsageTelemetryPayload()}}})}catch(e){let r=new Y({defaultError:J.VIEW.WATERMARK_ATTACH_FAIL,originalError:e});throw this._triggerAudioOnlyFallback(),this._streamTelemetryEventSender.sendMediaStreamEvent({correlationId:t,callId:this._call.id,timestampInfo:{deltaTimeInMs:Date.now()-n},operation:y3.watermark,kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,additionalDetails:{failureReason:r.message,code:r.code,...J3(r),watermark:{...this._getWatermarkUsageTelemetryPayload(this._viewId)}}}),r}}_triggerAudioOnlyFallback(){this._logger.debug(`audio only fallback triggered by viewId ${this._viewId}`),this._logger.debug(`Disposing remote stream with viewId ${this._viewId}`),this._videoStream.dispose(),this._call.setWatermarkAudioOnlyFallbackTriggered(!0)}_addStyleAttributesToSvgElement(e,t){for(let[n,r]of Object.entries(t))e.style[`${n}`]=r}_generateSinglePatternWatermark(e,t){let n=this._getWatermarkContainer(t);this._svgContainer=n;let r=t.opacity/this.RANGE_MAX,i=r/this.SHADOW_OPACITY_RATIO,a=J0(),o=`url(#${a})`,s=document.createElementNS(`http://www.w3.org/2000/svg`,`defs`),c=this._getSvgFilter(a,i),l=document.createElementNS(`http://www.w3.org/2000/svg`,`text`);l.id=J0(),this._addStyleAttributesToSvgElement(l,this.WATERMARK_TEXT_COMMON_STYLES),l.setAttribute(`filter`,o),l.setAttribute(`text-anchor`,`middle`),l.setAttribute(`dominant-baseline`,`middle`),l.setAttribute(`fill-opacity`,`${r}`),l.style.transform=`rotate(-30deg)`;let u=document.createTextNode(e);l.appendChild(u),this._svgTextDefElement=l,s.appendChild(c),s.appendChild(l);let d=document.createElementNS(`http://www.w3.org/2000/svg`,`use`);return d.id=J0(),this._svgWatermarkUseTagSinglePattern=d,d.setAttribute(`href`,`#${this._svgTextDefElement.id}`),d.setAttribute(`x`,`50%`),d.setAttribute(`y`,`50%`),d.setAttribute(`width`,`100%`),d.setAttribute(`height`,`100%`),d.setAttribute(`font-size`,`${this._svgWatermarkUseTextScale}`),d.setAttribute(`stroke-width`,`${this._svgWatermarkUseTextBorderSize}`),n.appendChild(s),n.appendChild(d),this._updateWatermarkUseTextScalingSingle(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height),n}_updateWatermarkUseTextScalingSingle(e,t){if(this._svgContainer&&this._svgWatermarkUseTagSinglePattern){let n=this._computeTextDiagonal(e,t);this._svgWatermarkUseTextScale=this.SPACE_USE*n*this.SINGLE_PATTERN_FONT_SIZE_FACTOR,this._svgWatermarkUseTextBorderSize=Math.max(1,Math.min(this.MAX_BORDER,this._svgWatermarkUseTextScale*this.BORDER_SIZE_FRAC)),this._svgWatermarkUseTagSinglePattern.setAttribute(`font-size`,`${this._svgWatermarkUseTextScale}`),this._svgWatermarkUseTagSinglePattern.setAttribute(`stroke-width`,`${this._svgWatermarkUseTextBorderSize}`),this._svgContainerHidden=this._svgContainer.outerHTML;return}this._logger.warn(`svg watermark element missing, cannot update`)}_updateWatermarkPatternScalingTiled(e,t){if(this._svgContainer&&this._svgTextDefElement&&this._svgFirstPattern&&this._svgSecondPattern){let n=Cwe(e,t,this._isApple);this._svgTextTiledScaledSize=n.scaledFontSize,this._svgTextTiledScaledStrokeWidth=n.scaledBorderSize,this._svgTextDefElement.setAttribute(`font-size`,`${this._svgTextTiledScaledSize}`),this._svgTextDefElement.setAttribute(`stroke-width`,`${this._svgTextTiledScaledStrokeWidth}`);let r=this._svgTextDefElement.getBoundingClientRect().width,i=this._svgTextDefElement.getBoundingClientRect().height,{width:a,height:o}=this._getScaledPatternDimensions(r,i,n.scaledHorizontalGap,n.scaledVerticalGap),s=.5*a,c=.5*o;this._svgFirstPatternWidth=a,this._svgFirstPatternHeight=o,this._svgSecondPatternWidth=a,this._svgSecondPatternHeight=o,this._svgSecondPatternOffsetX=s,this._svgSecondPatternOffsetY=c,this._svgFirstPattern.setAttribute(`width`,`${this._svgFirstPatternWidth}`),this._svgFirstPattern.setAttribute(`height`,`${this._svgFirstPatternHeight}`),this._svgSecondPattern.setAttribute(`width`,`${this._svgSecondPatternWidth}`),this._svgSecondPattern.setAttribute(`height`,`${this._svgSecondPatternHeight}`),this._svgSecondPattern.setAttribute(`x`,`${this._svgSecondPatternOffsetX}`),this._svgSecondPattern.setAttribute(`y`,`${this._svgSecondPatternOffsetY}`),this._svgContainerHidden=this._svgContainer.outerHTML;return}this._logger.warn(`svg watermark element missing, cannot update`)}_generateTiledPatternWatermark(e,t){let n=this._getWatermarkContainer(t);this._svgContainer=n;let r=t.opacity/this.RANGE_MAX,i=r/this.SHADOW_OPACITY_RATIO,a=J0(),o=J0(),s=J0(),c=`url(#${a})`,l=document.createElementNS(`http://www.w3.org/2000/svg`,`defs`),u=this._getSvgFilter(a,i),d=document.createElementNS(`http://www.w3.org/2000/svg`,`text`);this._svgTextDefElement=d,d.id=J0(),this._addStyleAttributesToSvgElement(d,this.WATERMARK_TEXT_COMMON_STYLES),d.setAttribute(`filter`,c),d.setAttribute(`dominant-baseline`,`hanging`),d.setAttribute(`fill-opacity`,`${r}`),d.setAttribute(`font-size`,`${this._svgTextTiledScaledSize}`),d.setAttribute(`stroke-width`,`${this._svgTextTiledScaledStrokeWidth}`);let f=document.createTextNode(e);d.appendChild(f);let p=document.createElementNS(`http://www.w3.org/2000/svg`,`pattern`);this._svgFirstPattern=p,p.id=o,p.setAttribute(`patternUnits`,`userSpaceOnUse`),p.setAttribute(`patternTransform`,`rotate(-30)`),p.setAttribute(`width`,`${this._svgFirstPatternWidth}`),p.setAttribute(`height`,`${this._svgFirstPatternHeight}`);let m=document.createElementNS(`http://www.w3.org/2000/svg`,`use`);m.setAttribute(`href`,`#${this._svgTextDefElement.id}`),p.appendChild(m);let h=document.createElementNS(`http://www.w3.org/2000/svg`,`pattern`);this._svgSecondPattern=h,h.id=s,h.setAttribute(`patternUnits`,`userSpaceOnUse`),h.setAttribute(`patternTransform`,`rotate(-30)`),h.setAttribute(`width`,`${this._svgSecondPatternWidth}`),h.setAttribute(`height`,`${this._svgSecondPatternHeight}`),h.setAttribute(`x`,`${this._svgSecondPatternOffsetX}`),h.setAttribute(`y`,`${this._svgSecondPatternOffsetY}`);let g=m.cloneNode(!0);h.appendChild(g),l.appendChild(u),l.appendChild(d),l.appendChild(p),l.appendChild(h);let _=this._getRect(0,0,100,100,o),v=this._getRect(0,0,100,100,s);return n.appendChild(l),n.appendChild(_),n.appendChild(v),this._updateWatermarkPatternScalingTiled(this._container.getBoundingClientRect().width,this._container.getBoundingClientRect().height),n}_getWatermarkContainer(e){let t=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return this._addStyleAttributesToSvgElement(t,this.WATERMARK_CONTAINER_STYLES),t.setAttribute(`xmlns`,`http://www.w3.org/2000/svg`),t}_getSvgFilter(e,t){let n=document.createElementNS(`http://www.w3.org/2000/svg`,`filter`);n.id=e;let r=document.createElementNS(`http://www.w3.org/2000/svg`,`feDropShadow`);return r.setAttribute(`dx`,`0.5`),r.setAttribute(`dy`,`0.5`),r.setAttribute(`stdDeviation`,`1`),r.setAttribute(`flood-color`,`black`),r.setAttribute(`flood-opacity`,`${t}`),n.appendChild(r),n}_getRect(e,t,n,r,i){let a=document.createElementNS(`http://www.w3.org/2000/svg`,`rect`);return a.setAttribute(`x`,`${e}%`),a.setAttribute(`y`,`${t}%`),a.setAttribute(`width`,`${n}%`),a.setAttribute(`height`,`${r}%`),a.setAttribute(`fill`,`url(#${i})`),a}_getClampedUsername(){let e=``,t=this._call.callAgent,n=Z().calling.watermark,r=n.watermarkMaxUsernameLength,i=n.watermarkEmptyDisplayNamePlaceholder;if(t?.isEnterpriseUser()){let n=t.getUserProperties()?.sipUri;n&&typeof n==`string`&&(e=n.replace(`sip:`,``))}else e=t?.displayName??``,e||=i;return Swe(e,r)}_getSelectedWatermarkPattern(){return this._videoStream.mediaStreamType===`Video`&&this._watermarkCapability?.enabledForVideo&&this._watermarkCapability?.videoSettings?.pattern?this._watermarkCapability.videoSettings.pattern:this._videoStream.mediaStreamType===`ScreenSharing`&&this._watermarkCapability?.enabledForVbss&&this._watermarkCapability?.vbssSettings?.pattern?this._watermarkCapability.vbssSettings.pattern:``}_getWatermarkUsageTelemetryPayload(e=``){return{endpointSupportsWatermark:this._call.callAgent.isWatermarkSupported(),audioOnlyFallbackTriggered:this._call.watermarkAudioOnlyFallbackTriggered,audioOnlyFallbackTriggeredByViewId:e,watermarkUsage:{video:{enabled:this._watermarkCapability?.enabledForVideo,opacity:this._watermarkCapability?.videoSettings.opacity,pattern:this._watermarkCapability?.videoSettings.pattern},screenshare:{enabled:this._watermarkCapability?.enabledForVbss,opacity:this._watermarkCapability?.vbssSettings.opacity,pattern:this._watermarkCapability?.vbssSettings.pattern}},viewId:this._viewId}}},y7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},b7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},UIe=1,x7=class{get isRendering(){return this._isRendering}get scalingMode(){return this._scalingMode}get isMirrored(){return this._isMirrored}get target(){return this._target}get viewId(){return this._viewId}get isDisposed(){return this._disposed}get retryErrorEvents(){return this._retryErrorEvents}get size(){return{height:this._size.height,width:this._size.width}}constructor(e,t,n,r,i,a,o){this._target=e,this._viewId=t,this._videoStream=n,this._onDisposedCallback=i,this._createViewSteps=a,this._eventEmitter=new E3.EventEmitter,this._isRendering=!1,this._scalingMode=`Stretch`,this._isMirrored=!1,this._createViewResolvedOnPlayEvent=!1,this._hasRenderingEvent=!1,this._hasPlayEvent=!1,this._size={height:0,width:0},this._disposed=!1,this.resolveRenderingPendingPromise=(e=!1)=>{this._renderingDeferred?.isPending()&&(this._renderingDeferred.resolve(),e&&(this.logger.log(`video element play event was fired and promise was resolved and isRendering is: ${this._tsRenderer?.isRendering}`),this._createViewResolvedOnPlayEvent=!0)),e?this._hasPlayEvent||(this._hasPlayEvent=!0,this._createViewSteps.isPlayedTimestamp=Date.now(),this._createViewSteps.isPlayedTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.isPlayedTimestamp-this._createViewSteps.attemptTimestamp):!this._hasRenderingEvent&&this._isRendering&&(this._hasRenderingEvent=!0,this._createViewSteps.isRenderedTimestamp=Date.now(),this._createViewSteps.isRenderedTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.isRenderedTimestamp-this._createViewSteps.attemptTimestamp)},this._handleTsRendererChanged=e=>{if(this.logger.debug(`rendering state is ${this._isRendering}, changed to ${this._tsRenderer?.isRendering}`),this._tsRenderer)if(this._tsRenderer.isRendering!==this._isRendering&&(this._isRendering=this._tsRenderer.isRendering,this._videoStream.updateIsReceiving(),this._isRendering&&this.resolveRenderingPendingPromise(),e.log(`isRendering change to ${this._isRendering}`)),this._tsRenderer.isRendering){let e=this._tsRenderer.streamSize?.height||f2.HEIGHT,t=this._tsRenderer.streamSize?.width||f2.WIDTH;e===this._size.height&&t===this._size.width||this.setAndUpdateSize(),this.resolveRenderingPendingPromise()}else this._size.height=0,this._size.width=0,this._videoStream.updateSize();this.sendRendererTelemetry()},this.sendRendererTelemetry=()=>{if(this._tsRenderer)try{let e={isRendering:this._tsRenderer.isRendering,streamWidth:this._tsRenderer.streamSize.width,streamHeight:this._tsRenderer.streamSize.height,isVideoAttached:this._target.isConnected,rendererWidth:this._target?.offsetWidth,rendererHeight:this._target?.offsetHeight};if(this.previousStats){if(Kwe(this.previousStats,e))return}else this.previousStats=e;this.previousStats=e;let{callId:t,localParticipantId:n,isDisposed:r,viewIdsRegistered:i,height:a,width:o,...s}=this._videoStream.getStreamMetadata(),c={...e,...s,viewId:this._viewId,disposed:this._disposed};this._videoStream.call.stats.recordEvent({name:l3.remote_view,callId:t,localParticipantId:n,data:c})}catch{}},this._unsubscribeAvailabilityCallback=()=>{this._availableCallback&&=(this._videoStream.kind===`RemoteVideoStream`&&this._videoStream?.off(`isAvailableChanged`,this._availableCallback),void 0)},this._disposeTsRendererChangedObservable=()=>{this._tsRendererChanged&&=(this._tsRendererChanged.dispose(),void 0)},this._attemptToDisposeTsRenderer=()=>{if(this._tsRenderer){this.logger.debug(`disposing underlying remote renderer`);try{this._tsRenderer?.dispose(),this._tsRenderer=void 0}catch(e){throw this.logger.warn(`underlying remote renderer dispose failed with ${e?.message} error`),new Y({defaultError:J.VIEW.REMOTE_RENDERER_DISPOSE_FAIL})}}},this.logger=r.createChild(`RemoteStreamRenderer`+ UIe++),this.logger.log(`created`),o?.scalingMode!==void 0&&(this._scalingMode=o.scalingMode),o?.isMirrored!==void 0&&(this._isMirrored=o.isMirrored),this._remoteStreamTelemetryEventSender=new U6(this._videoStream.telemetryLogManager),this._watermarkOverlayProvider=new HIe(this._target,this._videoStream,this._viewId,this.logger,this._remoteStreamTelemetryEventSender),this._watermarkOverlayProvider.attach(),this._retryErrorEvents=new Set([J.VIEW.TIMEOUT.subCode,J.VIEW.SUBSCRIBE.subCode])}async start(){let e=J0(),t=+new Date,n=this.logger.createFnLogger(g4.Start),r={timestampInfo:{attemptTimestamp:t},correlationId:e,operation:y3.render,kindOfEvent:$.attempt,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote};if(this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(r),this._disposed)throw this.logger.warn(`already disposed`),new Y({defaultError:J.VIEW.START_ALREADY_DISPOSED});this._createViewTimeout&&=(clearTimeout(this._createViewTimeout),void 0);try{n.info(`scalingMode=${O4(this._scalingMode)}`),this._videoStream.registerRenderer(this),this._renderingDeferred=n3(),this._renderingDeferred.promise.catch(M4),this._videoStream.kind===`RemoteVideoStream`&&(this._availableCallback=()=>{this._videoStream.isAvailable||(n.warn(`stream isAvailable changed to false, attempting to reject operation`),this._renderingDeferred?.isPending()&&!this._disposed&&this._renderingDeferred?.reject(new Y({defaultError:J.VIEW.STREAM_BECAME_UNAVAILABLE})))},this._videoStream.on(`isAvailableChanged`,this._availableCallback)),this._createViewSteps.startSubscriptionTimestamp=Date.now(),this._createViewSteps.startSubscriptionTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.startSubscriptionTimestamp-this._createViewSteps.attemptTimestamp,this._videoStream.tsStream.start(this._target,{scalingMode:O4(this._scalingMode),transparent:!1}).then((e=>{if(this._createViewSteps.rendererIsAvailableTimestamp=Date.now(),this._createViewSteps.rendererIsAvailableTimeDeltaSinceAttemptMs=this._createViewSteps.attemptTimestamp===void 0?0:this._createViewSteps.rendererIsAvailableTimestamp-this._createViewSteps.attemptTimestamp,this._isMirrored&&(this._target.style.transform=`rotateY(180deg)`,this._target.style.webkitTransform=`rotateY(180deg)`),this._tsRenderer=e,this.logger.info(`subscribed to video, waiting for the first frame`),this._disposed)throw this.logger.warn(`already disposed, dispose underlying renderer`),this._attemptToDisposeTsRenderer(),new Y({defaultError:J.VIEW.START_ALREADY_DISPOSED});if(this.logger.info(`current state of rendering is ${this._tsRenderer.isRendering}`),this.sendRendererTelemetry(),Z().rendering.remoteVideo.createViewTimeout!==-1&&(this._createViewTimeout=setTimeout((()=>{if(this._renderingDeferred?.isPending())try{this._renderingDeferred.reject(new Y({defaultError:J.VIEW.TIMEOUT})),this._createViewTimeout&&=(clearTimeout(this._createViewTimeout),void 0)}catch{}}),Z().rendering.remoteVideo.createViewTimeout)),Z().rendering.remoteVideo.speedupCreateViewWithPlayEvent){let e=this._target&&this._target.children.length>0&&this._target.children[0];e?e.addEventListener(`play`,this.videoPlayEventListener.bind(this)):this.logger.warn(`video element was not found while trying to listen to play event`)}this._tsRendererChanged=this._tsRenderer.changed((()=>this._handleTsRendererChanged(n))),this._tsRenderer.isRendering&&(this._isRendering=!0,this._videoStream.updateIsReceiving(),this.setAndUpdateSize(),this.resolveRenderingPendingPromise())})).catch((e=>{if(this.logger.info(`Failed to subscribe to video`),this._renderingDeferred?.isPending()){let t=new Y({defaultError:J.VIEW.SUBSCRIBE,originalError:e});this._renderingDeferred.reject(t)}})),await this._renderingDeferred.promise,this._videoStream.flushIsReceiving(),this._unsubscribeAvailabilityCallback(),Z().rendering.remoteVideo.forceCheckIfVideoWasAttachedToDom&&this._checkIfVideoWasAttachedToDom();let r={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:y3.render,kindOfEvent:$.success,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,createViewResolvedOnPlayEvent:this._createViewResolvedOnPlayEvent};return this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(r),this}catch(n){this.logger.warn(`Failed to render, message=${n}`);try{this._retryErrorEvents.has(n?.subCode)||this.dispose()}catch(e){this.logger.warn(`dispose failed with ${e?.message} error`)}let r=new Y({defaultError:J.VIEW.START,originalError:n});if(r.message!==J.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&r.message!==J.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){let n={timestampInfo:{deltaTimeInMs:+new Date-t},correlationId:e,operation:y3.render,additionalDetails:{failureReason:r.message,code:zG,...J3(r)},kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:v3.Remote,createViewResolvedOnPlayEvent:this._createViewResolvedOnPlayEvent};this._remoteStreamTelemetryEventSender.sendMediaStreamEvent(n)}throw r}}videoPlayEventListener(){this.logger.log(`video element play event was fired`),this.resolveRenderingPendingPromise(!0)}setAndUpdateSize(){try{this._size.width=this._tsRenderer?.streamSize.width||f2.WIDTH,this._size.height=this._tsRenderer?.streamSize.height||f2.HEIGHT,this._videoStream.updateSize()}catch(e){this.logger.error(`Failed to update video stream size with error ${e}`)}}async setScalingMode(e){if(!this._tsRenderer)throw new Y({defaultError:J.VIEW.SCALING_MODE});await this._tsRenderer.setScalingMode(O4(e)),this._scalingMode=e}_clearTimeouts(){this._checkIfVideoWasAttachedToDomTimeout&&=(clearTimeout(this._checkIfVideoWasAttachedToDomTimeout),void 0),this._createViewTimeout&&=(clearTimeout(this._createViewTimeout),void 0)}dispose(e=S3.Public_App){if(this._disposed)throw new Y({defaultError:J.VIEW.RENDERER_DISPOSE_ALREADY_DISPOSED});if(this._disposed=!0,this._disposeTsRendererChangedObservable(),this._unsubscribeAvailabilityCallback(),this._attemptToDisposeTsRenderer(),this._renderingDeferred?.isPending()){let t;switch(e){case S3.Internal_LargeMeetingVideoRendering:t=J.VIEW.LARGE_MEETING_VIEW_DISPOSED;break;case S3.Internal_RemoteVideoStreamDisposed:t=J.VIEW.REMOTE_VIDEO_STREAM_DISPOSED;break;default:t=J.VIEW.APP_VIEW_DISPOSED}this._renderingDeferred.reject(new Y({defaultError:t}))}if(this._target){let e=this._target.children&&this._target.children.length>0&&this._target.children[0];e&&e.removeEventListener(`play`,this.videoPlayEventListener),this._target.remove()}try{e!==S3.Public_App&&this._onDisposedCallback(e)}catch(e){this.logger.debug(`dispose callback failed with ${e?.message} error`)}this._watermarkOverlayProvider.dispose(),this._videoStream.unregisterRenderer(this),this._size.height=0,this._size.width=0,this._videoStream.updateSize(),this._isRendering=!1,this._videoStream.updateIsReceiving(),this._eventEmitter.removeAllListeners(),this._renderingDeferred=void 0,this._clearTimeouts()}_checkIfVideoWasAttachedToDom(){if(this._checkIfVideoWasAttachedToDomTimeout&&=(clearTimeout(this._checkIfVideoWasAttachedToDomTimeout),void 0),Z().rendering.remoteVideo.checkIfVideoAttachedToDom_poll){let e=Z().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalMaxTries,t=()=>{this._target.isConnected||e<=0?this.sendRendererTelemetry():(e--,e>=0&&(this._checkIfVideoWasAttachedToDomTimeout=setTimeout((()=>t()),Z().rendering.remoteVideo.checkIfVideoAttachedToDom_intervalTime)))};t()}else this._checkIfVideoWasAttachedToDomTimeout=setTimeout((()=>{this._target.isConnected&&this.sendRendererTelemetry()}),Z().rendering.remoteVideo.checkIfVideoAttachedToDom_timeout)}};y7([UG,b7(`design:type`,Object)],x7.prototype,`logger`,void 0),y7([YG(g4.Start),b7(`design:type`,Function),b7(`design:paramtypes`,[]),b7(`design:returntype`,Promise)],x7.prototype,`start`,null),y7([JG(g4.Dispose),b7(`design:type`,Function),b7(`design:paramtypes`,[String]),b7(`design:returntype`,void 0)],x7.prototype,`dispose`,null);var S7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},C7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},w7=class{get isRendering(){return this._isRendering}get scalingMode(){return this._scalingMode}get isMirrored(){return this._isMirrored}get target(){return this._target}get isDisposed(){return this._disposed}constructor(e,t,n,r,i){this._target=e,this._videoStream=t,this._onDisposed=r,this._eventEmitter=new E3.EventEmitter,this._isRendering=!1,this._scalingMode=`Stretch`,this._isMirrored=!0,this._disposed=!1,this.logger=n.createChild(`LocalStreamRenderer`),this.logger.log(`created`),i?.scalingMode!==void 0&&(this._scalingMode=i.scalingMode),i?.isMirrored===void 0?this._videoStream.mediaStreamType===`ScreenSharing`&&(this._isMirrored=!1):this._isMirrored=i.isMirrored,this._localStreamTelemetryEventSender=new U6(this._videoStream.telemetryLogManager)}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}async start(){let e=J0(),t=this.logger.createFnLogger(g4.Start),n=+new Date,r={timestampInfo:{attemptTimestamp:n},correlationId:e,operation:y3.render,kindOfEvent:$.attempt,mediaType:this._videoStream.mediaStreamType,streamType:v3.Local};this._localStreamTelemetryEventSender.sendMediaStreamEvent(r);try{if(t.info(`attempting to select new device as a source`),this._videoStream.source instanceof z6&&this._videoStream.mediaStreamType===`Video`){let e=this._videoStream.source.deviceManager.getTsDeviceManager();e.selectDevices({camera:this._videoStream.source.id}),t.info(`device selected`),t.info(`creating preview`),this._tsRenderer=await e.createPreview(this._target,{kind:`camera`},{scalingMode:O4(this._scalingMode),transparent:!1,ignoreMirroring:!1,disposeRendererWhenStreamisNotAvailable:()=>!0})}else{if(this._videoStream.mediaStreamType!==`RawMedia`&&this._videoStream.mediaStreamType!==`ScreenSharing`)throw new Y({defaultError:J.VIEW.UNKNOWN_STREAM_TYPE});{this._rawMediaOrSS_previewVideo=document.createElement(`video`),this._rawMediaOrSS_previewVideo.style.width=`100%`,this._rawMediaOrSS_previewVideo.style.height=`100%`,this._rawMediaOrSS_previewVideo.style.objectFit=`contain`,this._rawMediaOrSS_previewVideo.setAttribute(`playsinline`,`true`),this._rawMediaOrSS_previewVideo.disablePictureInPicture=!0,this._rawMediaOrSS_previewVideo.autoplay=!0;let e=await this._videoStream.getMediaStream(),t=new MediaStream(e.getVideoTracks());this._rawMediaOrSS_previewVideo.srcObject=t,this._rawMediaOrSS_previewVideo.play(),this._target.appendChild(this._rawMediaOrSS_previewVideo)}}this._isMirrored&&(this._target.style.transform=`rotateY(180deg)`,this._target.style.webkitTransform=`rotateY(180deg)`),this._videoStream.registerRenderer(this);let r={timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:e,operation:y3.render,kindOfEvent:$.success,mediaType:this._videoStream.mediaStreamType,streamType:v3.Local};return this._localStreamTelemetryEventSender.sendMediaStreamEvent(r),this}catch(r){this.dispose();let i=G3(t,r),a={timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:e,operation:y3.render,additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,...J3(i)},kindOfEvent:$.failure,mediaType:this._videoStream.mediaStreamType,streamType:v3.Local};throw this._localStreamTelemetryEventSender.sendMediaStreamEvent(a),i}}setScalingMode(e){if(this._tsRenderer)this._tsRenderer.setScalingMode(O4(e)),this._scalingMode=e;else{if(!this._rawMediaOrSS_previewVideo)throw new Y({defaultError:J.VIEW.SCALING_MODE});switch(e){case`Stretch`:this._rawMediaOrSS_previewVideo.style.objectFit=`fill`;break;case`Crop`:this._rawMediaOrSS_previewVideo.style.objectFit=`cover`;break;default:this._rawMediaOrSS_previewVideo.style.objectFit=`contain`}}}setSourceObject(e){this.disposeScreenSharingMediaStream();let t=this._target.querySelector(`video`);t&&(t.srcObject=e,t.play())}dispose(){if(!this._disposed){if(this._tsRenderer)try{this.logger.log(`disposing underlying local renderer`),this._tsRenderer.dispose(),this._tsRenderer=void 0}catch(e){throw this.logger.warn(`underlying local renderer dispose failed with ${e?.message} error`),new Y({defaultError:J.VIEW.LOCAL_RENDERER_DISPOSE_FAIL})}this.disposeScreenSharingMediaStream(),this._target.remove(),this._onDisposed&&this._onDisposed(this),this._eventEmitter.removeAllListeners(),this._disposed=!0}}disposeScreenSharingMediaStream(){if(this._videoStream.getCall()?.localScreenSharingStream){let e=this._target.querySelector(`video`),t=e?.srcObject;t&&(t.getVideoTracks().forEach((e=>{e.stop()})),e.srcObject=null,this.logger.info(`disposed of ScreenSharing MediaStream`))}}};S7([UG,C7(`design:type`,Object)],w7.prototype,`logger`,void 0),S7([YG(_4.Start),C7(`design:type`,Function),C7(`design:paramtypes`,[]),C7(`design:returntype`,Promise)],w7.prototype,`start`,null),S7([JG(_4.SetScalingMode),C7(`design:type`,Function),C7(`design:paramtypes`,[String]),C7(`design:returntype`,void 0)],w7.prototype,`setScalingMode`,null),S7([JG(_4.SetSourceObject),C7(`design:type`,Function),C7(`design:paramtypes`,[MediaStream]),C7(`design:returntype`,void 0)],w7.prototype,`setSourceObject`,null),S7([JG(_4.Dispose),C7(`design:type`,Function),C7(`design:paramtypes`,[]),C7(`design:returntype`,void 0)],w7.prototype,`dispose`,null);var T7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},E7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},WIe=1,D7=class e{get scalingMode(){return this._streamRenderer.scalingMode}get isMirrored(){return this._streamRenderer.isMirrored}get disposed(){return this._disposed}constructor(e,t,n,r,i){if(this._videoStream=e,this._viewId=n,this._options=i,this._disposed=!1,this._isRetryErrorSubCode=e=>`retryErrorEvents`in this._streamRenderer&&this._streamRenderer.retryErrorEvents.has(e.subCode),this._deleteActiveRemoteVideoStreamView=(e,t)=>{if(e.call.activeRemoteVideoStreamViews?.has(e.id)){let n=e.call.activeRemoteVideoStreamViews?.get(e.id);n?.delete(t),n?.size==0&&e.call.activeRemoteVideoStreamViews?.delete(e.id)}},this.logger=t.createChild(`VideoStreamRendererView`+ WIe++),this.target=document.createElement(`div`),this.target.style.width=`100%`,this.target.style.height=`100%`,this._videoStream instanceof v8)this._streamRenderer=new x7(this.target,this._viewId,this._videoStream,this.logger,(e=>{this._disposed||this.dispose(e)}),r,this._options);else{if(!(this._videoStream instanceof X6))throw new Y({defaultError:J.VIEW.VIEW_WRONG_STREAM_TYPE});this._streamRenderer=new w7(this.target,this._videoStream,this.logger,(()=>this.dispose),this._options)}this._telemetryLogManager=this._videoStream.telemetryLogManager,this.logger.info(`created`)}async render(){let e=this.logger.createFnLogger(this._videoStream instanceof v8?f4.RenderRemoteStream:f4.RenderLocalStream);if(this._disposed)throw e.log(`failed, stream disposed!`),new Y({defaultError:J.VIEW.RENDER_FAIL_STREAM_DISPOSED});let t=Z().rendering.remoteVideo.maxRendererRetries,n=1,r=(e,t)=>e().catch((i=>{if(t>0&&this._isRetryErrorSubCode(i))return n+=1,r(e,t-1);throw this._streamRenderer.isDisposed||this._streamRenderer.dispose(),i})),i=()=>this._streamRenderer.start();try{await r(i,t-1)}catch(t){throw e.error(`Failed to render stream ${this._viewId} after ${n} retries.`),this._isRetryErrorSubCode(t)&&n>1&&(t.message+=`\nFailed to render stream ${this._viewId} after ${n} retries.`),t}return n}async updateScalingMode(e){if(this._disposed)throw new Y({defaultError:J.VIEW.SCALING_MODE_DISPOSED});if(e!==`Crop`&&e!==`Fit`&&e!==`Stretch`)throw new Y({defaultError:J.VIEW.SCALING_MODE_WRONG_VAL});try{await this._streamRenderer.setScalingMode(e)}catch(e){throw new Y({defaultError:J.VIEW.SCALING_MODE,originalError:e})}}dispose(t=S3.Public_App){if(this._disposed)throw new Y({defaultError:J.VIEW.VIEW_ALREADY_DISPOSED});this._disposed=!0;let n=+new Date,r=J0();try{t===S3.Public_App&&this.sendDisposeViewEvent({eventName:Q.acs_calling_dispose_view_attempt,correlationId:r,timestampInfo:{attemptTimestamp:n}}),this.logger.debug(`attempt to dispose stream renderer`),this._streamRenderer.dispose(t),this.target?.remove(),this._videoStream instanceof s7&&(this._deleteActiveRemoteVideoStreamView(this._videoStream,this._viewId),Z()?.rendering.remoteVideo.decrementOvcOnRemoteSsRendering&&this._videoStream.mediaStreamType===`ScreenSharing`&&(e.remoteScreenSharingViews.delete(this._viewId),e.remoteScreenSharingViews.size<=0&&this._videoStream.call.setIsRenderingRemoteScreenShare(!1)));let i=+new Date;t===S3.Public_App&&this.sendDisposeViewEvent({eventName:Q.acs_calling_dispose_view_success,correlationId:r,timestampInfo:{deltaTimeInMs:i-n}})}catch(e){let i=new Y({defaultError:J.VIEW.DISPOSE_FAIL,originalError:e});if(t===S3.Public_App){let e=+new Date;this.sendDisposeViewEvent({eventName:Q.acs_calling_dispose_view_failure,correlationId:r,timestampInfo:{deltaTimeInMS:e-n}},i)}throw i}}sendDisposeViewEvent(e,t){try{let n,r;t&&(n=typeof t?.message==`string`?t?.message:``,r={...J3(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:{...this._videoStream.getStreamMetadata(),viewId:this._viewId,correlationId:e.correlationId,timestampInfo:e.timestampInfo,failureReason:n,additionalDetails:r}})}catch{this.logger.debug(`Unable to send telemtery`)}}};D7.remoteScreenSharingViews=new Map,T7([UG,E7(`design:type`,Object)],D7.prototype,`logger`,void 0),T7([YG(f4.Render),E7(`design:type`,Function),E7(`design:paramtypes`,[]),E7(`design:returntype`,Promise)],D7.prototype,`render`,null),T7([YG(f4.UpdateScalingMode),E7(`design:type`,Function),E7(`design:paramtypes`,[String]),E7(`design:returntype`,Promise)],D7.prototype,`updateScalingMode`,null),T7([JG(f4.Dispose),E7(`design:type`,Function),E7(`design:paramtypes`,[String]),E7(`design:returntype`,void 0)],D7.prototype,`dispose`,null);var GIe=U5();function KIe(e,t,n,r){let i=[`audioBitrate`,`videoBitrate`,`downloadBitrate`,`bufferLengthInMs`,`videoHeight`,`videoWidth`,`currentPlayPosition`],a=t[n.toString()];a!==void 0&&i.forEach((t=>{let n=t,i=t;if(a[n]!==void 0){let t=a[n];e[i]===void 0?e[i]=[t]:(e[i]?.length>=r&&e[i]?.shift(),e[i]?.push(t))}}))}var qIe=class{get createViewStats(){return this._createViewStats}get initialCreateViewStats(){return this._initialCreateViewStats}constructor(e,t,n,r,i){this._statsCollector=e,this._streamId=t,this._logger=n,this._call=r,this._attemptTimestamp=i,this._createViewFailureStats={},this._createViewStats={},this._initialCreateViewStats={},this._statsCollector.on(`sampleReported`,(e=>{vke(this.createViewStats,this.initialCreateViewStats,e,this._streamId)}))}getCreateViewFailureStats(){try{let e=0,t=NaN;this.createViewStats.video?.framesDropped!==void 0&&this.initialCreateViewStats.video?.framesDropped!==void 0&&(e=this.createViewStats.video?.framesDropped.length,t=this.createViewStats.video?.framesDropped[e-1]-this.initialCreateViewStats.video?.framesDropped[0]);let n=NaN;this.createViewStats.video?.framesReceived!==void 0&&this.initialCreateViewStats.video?.framesReceived!==void 0&&(e=this.createViewStats.video.framesReceived.length,n=this.createViewStats.video.framesReceived[e-1]-this.initialCreateViewStats.video?.framesReceived[0]);let r=NaN;this.createViewStats.video?.framesDecoded!==void 0&&this.initialCreateViewStats.video?.framesDecoded!==void 0&&(e=this.createViewStats.video.framesDecoded.length,r=this.createViewStats.video.framesDecoded[e-1]-this.initialCreateViewStats.video?.framesDecoded[0]);let i=NaN;this.createViewStats.video?.keyFramesDecoded!==void 0&&this.initialCreateViewStats.video?.keyFramesDecoded!==void 0&&(e=this.createViewStats.video.keyFramesDecoded.length,i=this.createViewStats.video.keyFramesDecoded[e-1]-this.initialCreateViewStats.video?.keyFramesDecoded[0]);let a=0;!isNaN(t)&&n>0&&(a=Number((t/n*100).toFixed(7)));let o=!1;n>0&&r===0&&(o=!0);let s=!1;!isNaN(r)&&!isNaN(i)&&r>0&&r===i&&(s=!0);let c=[],l=this._call.networkQualityUfdEventDetails,u=Z().rendering.remoteVideo.createViewFailureNetworkUfdCheckWindowInMs;l.forEach((e=>{Math.abs(e.timestampInfo-this._attemptTimestamp)<=u&&c.push(e)}));let d=n===0;this._createViewFailureStats.video={framesDroppedPercentage:a,framesReceivedButNothingDecoded:o,onlyKeyFramesDecoded:s,networkQualityEventsDuringAttempt:c,zeroFramesReceived:d}}catch{this._logger.debug(`Error calculating create view failure stats!`)}return this._createViewFailureStats}},JIe=class{constructor(e,t){this._liveStreamStatsCollector=e,this._streamId=t,this._liveStreamStats={},this._initialLiveStreamStats={};let n=Z()?.rendering.remoteVideo.createViewSendMediaStatsMaxLength;this._liveStreamStatsCollector.on(`sampleReported`,(e=>{KIe(this._liveStreamStats,e,this._streamId,n),e4.isEmpty(this._initialLiveStreamStats)&&(this._initialLiveStreamStats=this._liveStreamStats)}))}get initialCreateViewLiveStreamStats(){return this._initialLiveStreamStats}get createViewLiveStreamStats(){return this._liveStreamStats}},O7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},k7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},A7=class{get _createViewStats(){return this._videoStream.kind!==`RemoteVideoStream`&&this._videoStream.kind!==`ComposedVideoStream`||!this._createViewTelemetryHelper?this._videoStream.kind===`LiveVideoStream`&&this._createViewLiveStreamTelemetryHelper?this._createViewLiveStreamTelemetryHelper.createViewLiveStreamStats:{}:this._createViewTelemetryHelper.createViewStats}constructor(e){if(this.size={height:0,width:0},this.views=new Map,this.disposed=!1,this._attemptToDisposeView=e=>{try{e?.dispose()}catch(e){this.logger.warn(e?.message||`Failed to dispose, unknown error`)}},this._addActiveRemoteVideoStreamView=(e,t,n)=>{if(e.call.activeRemoteVideoStreamViews?.has(e.id)){let r=e.call.activeRemoteVideoStreamViews?.get(e.id);r&&r.set(t,n)}else{let r=new Map;r.set(t,n),e.call.activeRemoteVideoStreamViews?.set(e.id,r)}},!(e instanceof X6||e instanceof v8||e instanceof s7))throw new Y({defaultError:J.VIEW.RENDERER_WRONG_STREAM_TYPE});let t=ZW(`ACS`);this._videoStream=e,this._telemetryLogManager=e.telemetryLogManager,this.logger=new V6(t,e instanceof X6?[()=>`VideoStreamRenderer:LocalVideoStream:${GIe.pii.Omit(e?.source?.id)}`]:[()=>`VideoStreamRenderer:${e.kind}:${e?.id}`]),this.logger.info(`created`)}async createView(e){if(this.disposed)throw new Y({defaultError:J.VIEW.RENDERER_DISPOSED});let t={},n=+new Date,r=J0(),i=J0(),a,o;try{let s=1;if(t.attemptTimestamp=n,this.sendCreateViewEvent({eventName:Q.acs_calling_create_view_attempt,viewId:r,correlationId:i,timestampInfo:{attemptTimestamp:n},isMirrored:e?.isMirrored,scalingMode:e?.scalingMode,stepsInfo:t}),this._videoStream.kind===`RemoteVideoStream`&&!this._videoStream.isAvailable)throw new Y({defaultError:J.VIEW.ISAVAILABLE_FALSE});let c=Z(),l=E4();if(this._videoStream.kind===`RemoteVideoStream`&&this._videoStream.mediaStreamType!==`ScreenSharing`&&c?.calling.applyViewLimit&&l?.numVideoChannelsGvc){let e=l?.numVideoChannelsGvc,t=this._videoStream;if(!t.call.activeRemoteVideoStreamViews?.has(t.id)&&t.call.activeRemoteVideoStreamViews?.size>=e)throw new Y({defaultError:J.VIEW.MAX_NUM_OF_VIEWS_REACHED,defaultErrorMessageArgs:[e]})}if(c?.rendering.remoteVideo.createViewSendMediaStats){if(this._videoStream.kind===`RemoteVideoStream`||this._videoStream.kind===`ComposedVideoStream`){let e=this._videoStream,t=e.call;o=e.call.feature($5.MediaStats).createCollector();let r=e.id;this._createViewTelemetryHelper=new qIe(o,r,this.logger,t,n)}else if(this._videoStream.kind===`LiveVideoStream`){let e=this._videoStream;o=e.call.feature($5.LiveStream).createStatsCollector();let t=e.id;this._createViewLiveStreamTelemetryHelper=new JIe(o,t)}}a=new D7(this._videoStream,this.logger,r,t,e),this.views.set(r,a),s=await a.render(),this._videoStream.kind===`RemoteVideoStream`&&this._videoStream.mediaStreamType!==`ScreenSharing`&&this._addActiveRemoteVideoStreamView(this._videoStream,r,a),this._videoStream.kind===`RemoteVideoStream`&&this._videoStream.mediaStreamType===`ScreenSharing`&&c?.rendering.remoteVideo.decrementOvcOnRemoteSsRendering&&(this._videoStream.call.setIsRenderingRemoteScreenShare(!0),D7.remoteScreenSharingViews.set(r,a));let u=+new Date;return this.sendCreateViewEvent({eventName:Q.acs_calling_create_view_success,viewId:r,correlationId:i,timestampInfo:{deltaTimeInMs:u-n},additionalProperties:{isRetry:!!s&&s>1,attemptNumber:s},stepsInfo:t}),a}catch(e){let o=new Y({defaultError:J.VIEW.CREATE_VIEW_FAILED,originalError:e});if(this.views.delete(r),this._attemptToDisposeView(a),o.message!==J.VIEW.LARGE_MEETING_VIEW_DISPOSED.message&&o.message!==J.VIEW.REMOTE_VIDEO_STREAM_DISPOSED.message){let e=Date.now();this.sendCreateViewEvent({eventName:Q.acs_calling_create_view_failure,viewId:r,correlationId:i,timestampInfo:{deltaTimeInMs:e-n},stepsInfo:t},o)}throw o}finally{o?.dispose()}}async sendCreateViewEvent(e,t){try{let n={},r={},i={};if(Z()?.rendering.remoteVideo.createViewSendMediaStats&&(e.eventName===Q.acs_calling_create_view_failure||e.eventName===Q.acs_calling_create_view_success)){if(this._videoStream.kind===`RemoteVideoStream`){let t=this._videoStream.call,r=await t.tsCall.getMediaSessionStatsAsync?.();n={isRetry:e.additionalProperties?.isRetry??!1,attemptNumber:e.additionalProperties?.attemptNumber??1,videoSubscriptionEvents:r?.extensions?.Video_SubscriptionEvents,screenSharingSubscriptionEvents:r?.extensions?.Sharing_SubscriptionEvents,videoSendMaxCapabilities:r?.extensions?.Video_send_MaxCapabilities,screenSharingSendMaxCapabilities:r?.extensions?.Sharing_send_MaxCapabilities,iceConnectedStateTime:r?.metrics?.IceConnectedStateTime,relayCandidate:r?.extensions?.RelayCandidate,videoRecvTimeToFirstFrame:r?.extensions?.Video_recv_TimeToFirstFrame,screenSharingRecvTimeToFirstFrame:r?.extensions?.Sharing_recv_TimeToFirstFrame,optimalVideoCount:t.tsCall.optimalVideoCount||1,currentNumberOfVideosRendered:t.activeRemoteVideoStreamViews?.size||0}}e.eventName===Q.acs_calling_create_view_failure&&(i=this._createViewTelemetryHelper?.getCreateViewFailureStats()??{},r=this._createViewStats)}n.visibilityState=document.visibilityState,e.isMirrored!==void 0&&(n.isMirrored=e.isMirrored),e.scalingMode!==void 0&&(n.scalingMode=e.scalingMode),e.eventName!==Q.acs_calling_create_view_failure&&e.eventName!==Q.acs_calling_create_view_success||this._videoStream.kind!==`RemoteVideoStream`&&this._videoStream.kind!==`ComposedVideoStream`||e4.forOwn(e.stepsInfo,((e,t)=>{e!==void 0&&(n[t]=e)}));let a=``,o={};t&&(a=typeof t?.message==`string`?t?.message:``,o={...J3(t)}),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:{viewId:e.viewId,correlationId:e.correlationId,timestampInfo:e.timestampInfo,...this._videoStream.getStreamMetadata(),failureReason:a,additionalProperties:n,additionalDetails:o,stats:r,createViewFailureDebugStats:i,videoStreamKind:this._videoStream.kind}})}catch{this.logger.debug(`Unable to send telemtery`)}}dispose(){if(this.disposed)throw new Y({defaultError:J.VIEW.RENDERER_ALREADY_DISPOSED});this.disposed=!0,this.views.forEach(this._attemptToDisposeView),this.views.clear()}};O7([UG,k7(`design:type`,Object)],A7.prototype,`logger`,void 0),O7([YG(p4.CreateView),k7(`design:type`,Function),k7(`design:paramtypes`,[Object]),k7(`design:returntype`,Promise)],A7.prototype,`createView`,null),O7([JG(p4.Dispose),k7(`design:type`,Function),k7(`design:paramtypes`,[]),k7(`design:returntype`,void 0)],A7.prototype,`dispose`,null);var YIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},j7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},M7=class{get identifier(){return this._identifier}get endpointDetails(){return this._tsParticipant?.endpoints?.endpointDetails.map((e=>({participantId:e.participantId,deviceType:e.deviceType,clientEndpointCapabilities:e.clientEndpointCapabilities,endpointMetadata:e.endpointMetadata})))||[]}get state(){return this._state}get videoStreams(){return[...this._mappedStreams.values()]}get isMuted(){return this._isMuted}get isSpeaking(){return this._isSpeaking}get callEndReason(){return this._callEndReason}get displayName(){return this._displayName}get hasDisplayNameChanged(){return this._hasDisplayNameChanged}get role(){return this._role}constructor(e,t,n,r,i){this._mappedStreams=new Map,this._state=`Idle`,this._lastTsParticipantState=0,this._isMuted=!1,this._isSpeaking=!1,this._displayName=``,this._realDisplayName=``,this._hasDisplayNameChanged=!1,this._role=`Unknown`,this.acsToTsStreamType=e=>e===`Video`?0:e===`ScreenSharing`?1:void 0,this.getParticipantDisplayNameOverride=()=>this._tsParticipant?.propertyBag?.displayNameOverride?.value?.displayNameOverrideValue,this._identifier=e,this.logger=t.createChild((()=>`RemoteParticipant{${this._identifier.kind}}`)),this._telemetryLogManager=i,this._eventEmitter=new w6(this.logger),this._callAgent=r,this._call=n,this.logger.log(`created`),this._renderers={Video:{renderingState:{}},ScreenSharing:{renderingState:{}}}}on(e,t){if(e!==`stateChanged`&&e!==`isMutedChanged`&&e!==`isSpeakingChanged`&&e!==`displayNameChanged`&&e!==`roleChanged`&&e!==`videoStreamsUpdated`)throw new Y({defaultError:J.REMOTE_PARTICIPANT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`stateChanged`&&e!==`isMutedChanged`&&e!==`isSpeakingChanged`&&e!==`displayNameChanged`&&e!==`roleChanged`&&e!==`videoStreamsUpdated`)throw new Y({defaultError:J.REMOTE_PARTICIPANT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}async mute(){let e=Z();if(!e.calling.enableMuteOthers)throw new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_DISABLED});if(!this._call.tsCall.conversationType&&this._call.callInfo.context===b4.TwoParty)throw new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_1_TO_1_UNSUPPORTED});if(![`Connected`,`Hold`].some((e=>e===this._state)))throw new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_NONCONNECTED_UNSUPPORTED});let t=this.logger.createFnLogger(l4.Mute),n=+new Date,r=J0();if(this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:d3.MuteSpecificParticipant,timestampInfo:{attemptTimestamp:n},correlationId:r,step:`mid-call`}),!e.calling.allowMutePstnRemoteParticipant&&this._identifier.kind===`phoneNumber`){let e=+new Date,i=J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_PSTN_UNSUPPORTED;t.warn(i.message);let a=new Y({defaultError:i});throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:d3.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:e-n},correlationId:r,step:`mid-call`},a),a}try{t.info(`remote mute specific`),this._tsParticipant===void 0?t.warn(`no participant to mute in attempt to mute specific remote participant`):await this._call.tsCall.muteParticipants(1,[this._tsParticipant]),t.info(`remote mute specific success`);let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:d3.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:e-n},correlationId:r,step:`mid-call`})}catch(e){let i=new Y({defaultError:J.REMOTE_PARTICIPANT.MUTE_PARTICIPANT_FAILED,originalError:e});t.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:d3.MuteSpecificParticipant,timestampInfo:{deltaTimeInMs:a-n},correlationId:r,step:`mid-call`},i),i}}_dispose(){this.logger.log(`dispose`),this._participantChangedHandler&&this._participantChangedHandler.dispose(),this._mappedStreams.forEach((e=>e.dispose())),this._eventEmitter.emit(`stateChanged`,this._state),this._eventEmitter.removeAllListeners(),this._disposeVideo(0),this._disposeVideo(1)}get tsRemoteParticipant(){return this._tsParticipant}get kind(){return`RemoteParticipant`}setCallEndReason(e){this._callEndReason=e}observeParticipant(e){if(this._tsParticipant)return;let t=Z();this._tsParticipant=e,this._displayName=e.displayName,this._realDisplayName=e.displayName,this._isMuted=e.isServerMuted;let n=this.getParticipantDisplayNameOverride();t.calling.rename.enableShowEditedDisplayName&&n&&n!==this._displayName&&(this._displayName=n,this._hasDisplayNameChanged=!0),this._participantChangedHandler=this._tsParticipant.changed((()=>{this._tsParticipant&&this._tsParticipant.state!==this._lastTsParticipantState&&(this._lastTsParticipantState=this._tsParticipant.state,this._mapTsParticipantState(this._tsParticipant.state)),this._mapStreams(),this._tsParticipant&&this._tsParticipant.isServerMuted!==this._isMuted&&(this._isMuted=this._tsParticipant.isServerMuted,this._eventEmitter.emit(`isMutedChanged`));let n=this.getParticipantDisplayNameOverride();if(t.calling.rename.enableShowEditedDisplayName&&n&&n!==this._displayName){let e=J0(),t=this._displayName;this._displayName=n,this._hasDisplayNameChanged=n!==this._realDisplayName,this.logger.log(`display name changed ${t}=>${n}, correlationId=${e}`),this._eventEmitter.emit(`displayNameChanged`,{newValue:this._displayName,oldValue:t,reason:`editedDisplayName`}),this.sendDisplayNameOverrideEvent(e)}else if((!n||!t.calling.rename.enableShowEditedDisplayName)&&this._tsParticipant?.displayName&&this._tsParticipant.displayName!==this._displayName){let t=this._displayName;this._displayName=e.displayName,this._realDisplayName=e.displayName,this._eventEmitter.emit(`displayNameChanged`,{newValue:this._displayName,oldValue:t})}if(this._tsParticipant&&this._tsParticipant.advancedMeetingRole!==this._lastTsParticipantAdvancedRole&&(this._lastTsParticipantAdvancedRole=e.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole)),this._tsParticipant){let e=this._tsParticipant.voiceLevel!==0;e!==this._isSpeaking&&(this._isSpeaking=e,this._eventEmitter.emit(`isSpeakingChanged`))}})),this._mapTsParticipantState(this._tsParticipant.state),this._mapStreams(),this._lastTsParticipantAdvancedRole=this._tsParticipant.advancedMeetingRole,this._setParticipantRole(this._tsParticipant.advancedMeetingRole),this._displayName||!DG(this._identifier)&&!EG(this._identifier)||this.getRemoteParticipantProperties().then((e=>{e?.displayName&&(this._displayName=e.displayName,this._eventEmitter.emit(`displayNameChanged`))})).catch((e=>{this.logger.error(`Failed to get remote participant properties: ${e}`)}))}setParticipantState(e){e!==this._state&&(this.logger.log(`state changed ${this._state}=>${this.state}`),this._state=e,this._state==`Disconnected`?this._dispose():this._eventEmitter.emit(`stateChanged`,this._state))}async stopRenderingVideo(){this._disposeVideo(0)}async renderVideo(e,t){return typeof e==`function`?this._updateRenderingState(e,`Video`,t):await this._renderStreamForParticipant(e,0,t)}async _updateRenderingState(e,t,n){if(typeof e==`function`){let r,i=t===`Video`?0:1;this._tsParticipant&&(r=n?.stream?n.stream:new s7(this._tsParticipant.streams[i][0],this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier),r.on(`isReceivingChanged`,(()=>{this._renderers[t].renderingState.isFrozen=!r.isReceiving,e(this._renderers[t].renderingState)})),r.on(`isAvailableChanged`,(async()=>{this._renderers[t].renderingState.isStreaming!==r?.isAvailable&&(this._renderers[t].renderingState.isStreaming=r.isAvailable,this._renderers[t].renderingState.isStreaming&&!this._renderers[t].renderer&&(this._renderers[t].renderer=this._renderers[t]?.renderer?this._renderers[t].renderer:new A7(r),this._renderers[t].view||(this._renderers[t].view=await this._renderers[t].renderer?.createView(n?.viewOptions)),this._renderers[t].renderingState.videoTarget=this._renderers[t].view?.target)),e(this._renderers[t].renderingState)})))}}async renderScreenShare(e,t){return typeof e==`function`?this._updateRenderingState(e,`ScreenSharing`,t):this._renderStreamForParticipant(e,1,t)}async _renderStreamForParticipant(e,t,n){if(this._tsParticipant){let r=t===0?`Video`:`ScreenSharing`,i=n?.stream?n.stream:new s7(this._tsParticipant.streams[t][0],this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier);return i.isAvailable&&(this._renderers[r].view=await this._appendVideo(e,t,i,n?.viewOptions)),i.on(`isAvailableChanged`,(async()=>{i.isAvailable?this._renderers[r].view=await this._appendVideo(e,t,i,n?.viewOptions):this._renderers[r]?.view&&this._renderers[r].view?.target&&this._renderers[r].view?.target.parentNode?.removeChild(this._renderers[r].view?.target)})),Promise.resolve({stream:i,view:this._renderers[r]?.view})}return Promise.reject()}async _appendVideo(e,t,n,r){try{let i=t===0?`Video`:`ScreenSharing`;if(t===0&&(this._renderers[i]?.renderer||(this._renderers[i].renderer=this._renderers[i]?.renderer?this._renderers[i].renderer:new A7(n),this._renderers[i].view=await this._renderers[i].renderer?.createView(r)),this._renderers[i].view))return e.appendChild(this._renderers[i].view?.target||document.createElement(`emptyNode`)),Promise.resolve(this._renderers[i].view)}catch(e){return Promise.reject(e)}return Promise.reject()}async _disposeVideo(e){let t=e===0?`Video`:`ScreenSharing`;this._renderers[t].view?.dispose(),this._renderers[t].renderer?.dispose(),this._renderers[t]={renderingState:{}}}_setParticipantRole(e){let t=iTe(Z(),e);t===`Unknown`?this.logger.log(`tsParticipant advancedMeetingRole=${e} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${e}=>${t}`),this._role!=t&&(this.logger.log(`role changed ${this._role}=>${e}`),this._role=t,this._eventEmitter.emit(`roleChanged`))}_mapTsParticipantState(e){let t,n={0:`Idle`,1:`Connecting`,2:`Ringing`,3:`Connected`,4:`Disconnected`,5:`Hold`,7:`InLobby`,6:`EarlyMedia`};n[e]?(t=n[e],this.logger.log(`mapped tsParticipant ${e}=>${this._state}`),this.setParticipantState(t)):this.logger.log(`unable to map tsCall state=${e} to call state`)}_mapStreams(){let e=[],t=[],n=e=>{this._mappedStreams.set(e.id,e)},r=e=>{let t=this._mappedStreams.get(e.id);t&&(this.logger.log(`stream removed, type==${t.mediaStreamType} id=${e.id}`),this._mappedStreams.delete(e.id),t.dispose())},i=n=>{if(this._tsParticipant)if(this._tsParticipant.streams&&ywe(this._tsParticipant.streams[n])){let r=[];this._tsParticipant&&(r=this._tsParticipant.streams[n]),r.forEach((t=>{if(!this._mappedStreams.get(t.id)){let n=new s7(t,this.logger,this._call,this._callAgent,this._tsParticipant,this._telemetryLogManager,this._identifier);this.logger.log(`stream created, type==${n.mediaStreamType} id=${t.id}`),e.push(n)}})),this._mappedStreams.forEach((e=>{this.acsToTsStreamType(e.mediaStreamType)===n&&(r.some((t=>t.id===e.id))||t.push(e))}))}else this._mappedStreams.forEach((e=>{this.acsToTsStreamType(e.mediaStreamType)===n&&t.push(e)}))};i(0),i(1),(e.length>0||t.length>0)&&(e.forEach(n),t.forEach(r),this._eventEmitter.emit(`videoStreamsUpdated`,{added:e,removed:t}))}sendAudioEvent(e,t){try{let n,r;t&&(n=t.message,r=J3(t));let i={callId:this._call.id,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||``,failureReason:n||``,additionalDetails:{...r}};e.eventType!==void 0&&(i.eventType=e.eventType),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:i})}catch{this.logger.debug(`Unable to send mute others audio telemetry`)}}sendDisplayNameOverrideEvent(e){if(this._telemetryLogManager)try{let t={callId:this._call.id,timestampInfo:{attemptTimestamp:+new Date},correlationId:e,step:`event`};this._telemetryLogManager.sendEvent({name:Q.acs_calling_edited_display_name,tenant:p2,properties:t})}catch{this.logger.debug(`Unable to send display name override event telemetry`)}}getRemoteParticipantProperties(){return new Promise((e=>{let t={policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`TeamsMeetingPolicy`],userProperties:[`displayName`]};this._callAgent.mtPolicyService.requestUserPoliciesFromAcsMiddleTier(this._call.id,K2(this.identifier),t,this._callAgent.getUserMri()).then((t=>{e(t.userAggregatedPolicySettingData?.userProperties)}))}))}};YIe([UG,j7(`design:type`,Object)],M7.prototype,`logger`,void 0),YIe([YG(l4.Mute),j7(`design:type`,Function),j7(`design:paramtypes`,[]),j7(`design:returntype`,Promise)],M7.prototype,`mute`,null);var XIe=class{constructor(e){this._deviceManager=e,this._eventEmitter=new E3.EventEmitter,this._selectedDeviceListeners=new Map,this._selectedDevices=new Map,this._deviceInfoMapper=this._deviceManager.deviceInfoMapper;let t=e=>()=>{let t=this._selectedDevices.get(e),n=e===`Speaker`?this._deviceManager.selectedSpeaker:e===`Microphone`?this._deviceManager.selectedMicrophone:void 0,r=n===void 0?void 0:{id:this._deviceInfoMapper.getDeviceId(n.id),name:this._deviceInfoMapper.scrubDeviceLabel(n.name)};this._selectedDevices.set(e,r),this._eventEmitter.emit(`selectedDeviceChanged`,{selectedDeviceType:e,oldDevice:t,newDevice:r})},n=t(`Speaker`);this._selectedDeviceListeners.set(`Speaker`,n),this._deviceManager.on(`selectedSpeakerChanged`,n),n();let r=t(`Microphone`);this._selectedDeviceListeners.set(`Microphone`,r),this._deviceManager.on(`selectedMicrophoneChanged`,r),r()}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}selectedDevice(e){return this._selectedDevices.get(e)}dispose(){let e=this._selectedDeviceListeners.get(`Speaker`);e&&this._deviceManager.off(`selectedSpeakerChanged`,e);let t=this._selectedDeviceListeners.get(`Microphone`);t&&this._deviceManager.off(`selectedMicrophoneChanged`,t),this._eventEmitter.removeAllListeners()}};function N7(e,t,n,r){let i=r===R2.RoomCall||e.kind===GG.Call&&e.direction==`Incoming`&&!e.tsCall.groupId&&!!e.tsCall.meetingData?.meetingCode&&!e.tsCall.threadId,a=!i&&r===R2.TeamsMeetingLink||r===R2.TeamsMeetingId||r===R2.TeamsCoordinates||e.direction==`Incoming`&&!e.tsCall.groupId&&!!e.tsCall.meetingData&&!!e.tsCall.threadId,o={audio:``,video:``},s=e.localAudioStreams?.[0];s&&(o.audio=s.getEffectsCurrentStateRecord()??``);let c=e.localVideoStreams?.[0];return c&&(o.video=c.getEffectsCurrentStateRecord()??``),{timestampInfo:{attemptTimestamp:+new Date},correlationId:n,localParticipantId:e.tsCall.participantId||``,isAcsTeamsCall:e.isAcsTeamsCall,callId:e.tsCall.callId||``,callType:e.tsCall.callType||``,callDirection:e.direction,state:e.state===`Ringing`?`Ringing`:$Ee[e.tsCall.state],groupJoin:!!e.tsCall.groupId,roomJoin:i,meetingJoin:a,callEndDiagnosticsInfo:e.tsCall.callEndDiagnosticsInfo||{},isSupportedEnvironment:t?.runningEnvironmentInfo?.isSupportedEnvironment,effectsStateInfo:o,hostRegion:e.tsCall.region||``,diagnosticInfo:{...e.tsCall.callEndDiagnosticsInfo,telemetryPayloadBytesOriginal:m3.telemetryPayloadBytesOriginal,telemetryPayloadBytesCompressed:m3.telemetryPayloadBytesCompressed}}}function P7(e,t,n){try{n.step===`state-changed`&&n.newState===`Connecting`&&(m3.telemetryPayloadBytesOriginal=0,m3.telemetryPayloadBytesCompressed=0),e.sendEvent({name:Q.acs_calling_call_progress,tenant:p2,properties:n})}catch{t.error(`Failed to send event: ${Q.acs_calling_call_progress} step: ${n.step}`)}}var ZIe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},F7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},I7=class{get threadId(){return this._threadId}get roomId(){return this._roomId}get groupId(){return this._groupId}get participantId(){return this._tsCall.participantId}get isPstnInterop(){return this._isPstnInterop}get isTeamsInterop(){return this._isTeamsInterop}get callScenario(){if(this._tsCall.callQueueInfo)return y4.CallQueue;if(this.transferorKind!==`unknown`){if(this._tsCall.incomingCallType===`transfer`)return y4.TransferToParticipant;if(this._tsCall.incomingCallType===`replaces`)return y4.TransferToCall}return this.direction===`Incoming`?`AcceptCall`:this.direction===`Outgoing`&&this.context==`Rooms`?y4.JoinRoom:this.direction===`Outgoing`&&this.context==`TeamsMeeting`?y4.JoinTeamMeeting:this.direction===`Outgoing`&&this.context==`GroupIdCall`?y4.JoinWithGroupId:y4.PlaceCall}get context(){return this._tsCall.callType==1||this._currentCallContext==b4.TwoParty?b4.TwoParty:this._tsCall.groupId?b4.GroupIdCall:this._tsCall.conversationType==`groupCall`||this._currentCallContext==b4.MultiParty?b4.MultiParty:this._config?.roomId||this._roomId||this._tsCall.meetingData?.meetingCode?.startsWith(`994`)||this._tsCall.meetingData?.meetingCode?.startsWith(`995`)||this._tsCall.meetingData?.meetingCode?.startsWith(`996`)?b4.Rooms:this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.passcode||this._tsCall.conversationType==`scheduledMeeting`?b4.TeamsMeeting:(this._tsCall.callType,b4.MultiParty)}get transferorKind(){return this._tsCall.transferorMri?q2(this._tsCall.transferorMri||``).kind:``}get direction(){return this._config?.isIncoming?a4.Incoming:a4.Outgoing}get initiatorKind(){return q2(this._tsCall.callerMri?this._tsCall.callerMri:``).kind}get targetKind(){return this._tsCall.groupId?this._tsCall.groupId:this._config?.roomId?this._config.roomId:this._tsCall.meetingData?.meetingUrl||this._tsCall.meetingData?.meetingCode?`TeamsMeetingJoinLink`:this._tsCall.transferorMri?`Transferee`:this._tsCall.participants.length===1?q2(this._tsCall.participants[0].id).kind:this._tsCall.participants.filter((e=>e.id!==this._tsCall.callerMri)).map((e=>q2(e.id).kind)).toString()}constructor(e,t={}){this._tsCall=e,this._threadId=this._tsCall.threadId;let n=this._tsCall.groupId;this._groupId=!n||n.startsWith(`19:`)||n.startsWith(`99:`)?void 0:n,this._roomId=t?.config?.roomId,this._config=t.config,this._isPstnInterop=!1,this._isTeamsInterop=!1}setThreadId(e){this._threadId=e}initialize(e,t,n){this._logger=t,this._eventEmitter=e,this._threadId=this._tsCall.threadId,this._tsCallChangedListener=this._tsCall.changed((()=>this.threadIdChanged(this._tsCall))),this._p2pCallListener=this._tsCall.changed((()=>this.p2pCallHandler())),this._isPstnInterop=this.isPSTNUserInCall,this._isTeamsInterop=this.isTeamsUserInCall,this._participantUpdatedListener=this._tsCall.on(`participantCountsUpdated`,(()=>{this.interoperabilityChangeHandler(),this.p2pCallEscalationHandler()}))}async getServerCallId(){let e=JSON.parse(await this._tsCall.getJoinBlob())?.conversationUrl;if(!e)throw new Y({defaultError:J.CALL.GET_SERVER_CALL_ID});return xFe(e)}p2pCallHandler(){this._currentCallContext==null&&this._tsCall.callType==1&&(this._currentCallContext=b4.TwoParty)}p2pCallEscalationHandler(){this._currentCallContext==b4.TwoParty&&L4(this._tsCall)>2&&(this._currentCallContext=b4.MultiParty,this._eventEmitter.emit(`callInfoChanged`),this._p2pCallListener?.dispose())}get isTeamsUserInCall(){if(!this._tsCall.participants)return!1;for(let e of this._tsCall.participants)if(q2(e.id).kind===`microsoftTeamsUser`)return!0;return!1}get isPSTNUserInCall(){if(!this._tsCall.participants)return!1;for(let e of this._tsCall.participants)if(q2(e.id).kind===`phoneNumber`)return!0;return!1}interoperabilityChangeHandler(){!this._isPstnInterop&&this.isPSTNUserInCall&&(this._isPstnInterop=!0,this._eventEmitter.emit(`callInfoChanged`)),!this._isTeamsInterop&&this.isTeamsUserInCall&&(this._isTeamsInterop=!0,this._eventEmitter.emit(`callInfoChanged`))}threadIdChanged(e){this._tsCall.threadId!==this._threadId&&(this._logger.log(`threadId changed from ${this._threadId} to ${e?.threadId}`),this._threadId=this._tsCall.threadId,this._eventEmitter.emit(`threadIdChanged`))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}onCallInfoChanged(e,t){this._eventEmitter.on(e,t)}offCallInfoChanged(e,t){this._eventEmitter.off(e,t)}dispose(){this._tsCallChangedListener?.dispose(),this._eventEmitter.removeAllListeners(),this._p2pCallListener?.dispose(),this._participantUpdatedListener?.dispose()}};ZIe([YG(Owe.GetServerCallId),F7(`design:type`,Function),F7(`design:paramtypes`,[]),F7(`design:returntype`,Promise)],I7.prototype,`getServerCallId`,null);var QIe=class e{constructor(){this.CAUSE_ID_TO_NETWORK_INFO={}}static getInstance(){return this.instance||=new e,this.instance}deleteNetworkInfo(e){delete this.CAUSE_ID_TO_NETWORK_INFO[e]}ifCauseIdExistsRemoveNetworkInfo(e){return this.CAUSE_ID_TO_NETWORK_INFO[e]&&this.CAUSE_ID_TO_NETWORK_INFO[e].length===0?!!this.getRemoveCauseIdToNetworkInfo(e):!!this.CAUSE_ID_TO_NETWORK_INFO[e]}getRemoveCauseIdToNetworkInfo(e){if(!Z().telemetry.sendNetworkInfo)return;let t=this.CAUSE_ID_TO_NETWORK_INFO[e];return t&&this.deleteNetworkInfo(e),t}setCauseIdToNetworkInfo(e,t){Object.keys(this.CAUSE_ID_TO_NETWORK_INFO).length>100&&(this.CAUSE_ID_TO_NETWORK_INFO={}),t?this.CAUSE_ID_TO_NETWORK_INFO[e]?this.CAUSE_ID_TO_NETWORK_INFO[e].push({url:t.url,statusCode:t.statusCode,start:t.start,end:t.end,deltaTimeInMs:t.deltaTimeInMs,causeId:t.causeId}):this.CAUSE_ID_TO_NETWORK_INFO[e]=[{url:t.url,statusCode:t.statusCode,start:t.start,end:t.end,deltaTimeInMs:t.deltaTimeInMs,causeId:t.causeId}]:this.CAUSE_ID_TO_NETWORK_INFO[e]=[]}};QIe.instance=null;var L7=QIe.getInstance(),$Ie=class e{constructor(e,t,n,r){this._recordingConsentEnabled=!1,this._consentActivelyRequired=!1,this._localParticipantConsentPublishState=!1,this._isExplicitConsentEnabled=!1,this._isInitialized=!1,this._isExplicitConsentEnabled=Z().calling.explicitConsentFeatureEnabled.enabled,this.initialize(e,t,n,r)}dispose(){this._isInitialized=!1,this._recordingConsentEnabled=!1,this._consentActivelyRequired=!1,this._localParticipantConsentPublishState=!1,e.instance=null}isConsentRequiredInCall(){if(!this._isExplicitConsentEnabled)return!1;let e=this._recordingConsentEnabled&&!this._localParticipantConsentPublishState;return this._logger.info(`ExplicitConsentCallStateManager: isConsentRequiredInCall: Recording Consent Enabled: `+this._recordingConsentEnabled+` Local Participant Consent Publish State: `+this._localParticipantConsentPublishState),this._logger.log(`ExplicitConsentCallStateManager: isConsentRequiredInCall: `+e),e}async consent(e){if(this._isExplicitConsentEnabled){if(e.context===b4.TwoParty)throw this._logger.warn(`Consent for recording is not supported for 1:1 calls`),new Y({defaultError:J.CALL.CONSENT_NOT_SUPPORTED_1TO1});if(!this.isConsentRequiredInCall())throw new Y({defaultError:J.CALL.CONSENT_ALREADY_SET_OR_NOT_REQUIRED});try{if(!await this._tsCall.publishState({level:`user`,type:`consentToRecording`,content:`{}`},PG()))throw this._logger.error(`Consent failure to set publish state for user`),new Y({defaultError:J.CALL.FAILED_TO_SET_CONSENT});this._logger.log(`ExplicitConsentCallStateManager: Consent for the call provided successfully`)}catch(e){throw this._logger.error(`Consent failure to set publish state for user on service side`),e}}}areCoreCapabilitiesConsentRestricted(){if(!this._isExplicitConsentEnabled)return!1;let e=this._consentActivelyRequired&&!this._localParticipantConsentPublishState;return this._logger.info(`ExplicitConsentCallStateManager: areCoreCapabilitiesConsentRestricted: Consent Actively Required: `+this._consentActivelyRequired+` Local Participant Consent Publish State: `+this._localParticipantConsentPublishState),this._logger.log(`ExplicitConsentCallStateManager: areCoreCapabilitiesConsentRestricted: `+e),e}offConsentRestrictionChanged(e,t){if(e!==`consentRestrictionChanged`)throw Error(`ExplicitConsentCallStateManager: OffConsentRestrictionChanged - Invalid event`);this._logger.log(`ExplicitConsentCallStateManager: Unsubscribing to consentRestrictionChanged event`),this._eventEmitter.off(e,t)}onConsentRestrictionChanged(e,t){if(e!==`consentRestrictionChanged`)throw Error(`ExplicitConsentCallStateManager: onConsentRestrictionChanged - Invalid event`);this._logger.log(`ExplicitConsentCallStateManager: Subscribing to consentRestrictionChanged event`),this._eventEmitter.on(e,t)}initialize(e,t,n,r){this._isExplicitConsentEnabled&&(this._isInitialized||=(this._logger=r.createChild((()=>`Explicit Consent::Call(id='${e.callId}', state='${e.state}')`)),this._tsCall=e,this._callAgent=t,this._eventEmitter=n,e.changed((()=>{if(!0===e.meetingDetails?.recordingConsentDetails?.explicitRecordingConsentEnabled){this._recordingConsentEnabled=!0;let t=!0===e.meetingDetails?.recordingConsentDetails?.consentActivelyRequired;t!==this._consentActivelyRequired&&(this._consentActivelyRequired=t,this._eventEmitter.emit(`consentRestrictionChanged`))}})),e.on(`publishedStatesChanged`,(async e=>{this._localParticipantConsentPublishState=!1,this._handleConsentStateChange(e)})),!0))}_handleConsentStateChange(e){if(!0!==this._localParticipantConsentPublishState){let n=this._callAgent.getUserMri();var t=!1;e&&this._getPublishedState(e).forEach((e=>{e.participantStates.forEach((e=>{if(e.id===n)return this._logger.log(`ExplicitConsentCallStateManager: Handle Consent State changes: Local participant has provided the consent`),void(t=!0)}))})),this._localParticipantConsentPublishState=t,t&&this._eventEmitter.emit(`consentRestrictionChanged`)}}_getPublishedState(e){return e.typeStates.filter((e=>[`consentToRecording`].includes(e.type)))}};$Ie.instance=null;var eLe=class{constructor(e,t){this._interval=0,this._ufds=new Map,this._interval=t,e.forEach((e=>{this._ufds.set(e,{_lastRecovered:new Date,_shouldNotifyError:!0,_shouldNotifyRecovery:!0})}))}updateLastRecoveredTime(e,t){let n=this._ufds.get(e);n&&(n._lastRecovered=new Date(t.getTime()+this._interval),n._shouldNotifyError=!0,n._shouldNotifyRecovery=!1)}shouldLogError(e,t){let n=this._ufds.get(e);if(n){let e=n._lastRecovered<=t&&n._shouldNotifyError;return e&&(n._shouldNotifyError=!1,n._shouldNotifyRecovery=!0),e}return!0}shouldLogRecovery(e,t){let n=this._ufds.get(e);if(n){let r=n._shouldNotifyRecovery;return r&&this.updateLastRecoveredTime(e,t),r}return!0}},tLe,R7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},z7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},B7=class e{get id(){return this._id}get callerInfo(){return{identifier:this._callerIdentity,displayName:this._callerDisplayName}}get transferorInfo(){if(this._transferorIdentity)return{identifier:this._transferorIdentity,displayName:this._transferorDisplayName}}get state(){return this._state}get role(){return this._role}get callEndReason(){return this._callEndReason}get kind(){return this._kind}get direction(){return this._direction}get isMuted(){return this._isMuted}get isScreenSharingOn(){return this._isScreenSharingOn}get isLocalVideoStarted(){return this._isLocalVideoStarted}get localVideoStreams(){return this._localVideoStreams}get localAudioStreams(){return this._localAudioStreams}get isIncomingAudioMuted(){return this._isIncomingAudioMuted}get remoteParticipants(){return this._remoteParticipants}get totalParticipantCount(){return this._totalParticipantCount}get lobby(){return this._lobby}get isAcsTeamsCall(){return this._isAcsTeamsCall}get isIPAudioEnabled(){return this.callInfo.context===b4.TwoParty||this._allowIPAudio}get isIPVideoEnabled(){return this.callInfo.context===b4.TwoParty||this._allowIPVideo}get isEnterpriseTeamsCall(){return this._isEnterpriseTeamsCall}subscribeToGetRemoteAudioStream(){if(!this._rawAudioStreamChangedSubscription)try{let e=this.tsCall.getIncomingRawAudioStream(),t=async()=>{try{if(this._remoteAudioStreams.length===0){if(!await e.getMediaStream())throw new Y({defaultError:J.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_UNDEFINED});this._remoteAudioStreams.push(new hIe(e,this._telemetryLogManager,this.id,this.tsCall.participantId)),this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:this._remoteAudioStreams,removed:[]})}else if(await e.getMediaStream())this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:[],removed:[]});else{let e=this._remoteAudioStreams[0];e.dispose(),this._remoteAudioStreams=[],this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:[],removed:[e]})}}catch(e){throw new Y({defaultError:J.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_RETURNED_ERROR,originalError:e})}};this._rawAudioStreamChangedSubscription=e.changed((()=>{this.logger.info(`Changed fired ${this.tsCall.state}, ${this.state}`),t().catch(M4)})),t().catch((()=>{this.logger.info(`Failed to update remote audio stream collection, retrying on changed`)}))}catch{this.logger.info(`Failed to get raw audio stream from the stack`)}}get remoteAudioStreams(){if(!Z().calling.allowAccessRawMediaStream)throw new Y({defaultError:J.CALL.REMOTE_AUDIO_GET_MEDIA_STREAM_DISABLED});return this._remoteAudioStreams}get deviceManager(){return this._callAgent.deviceManager}get mediaConstraintsManager(){return this._mediaConstraintsManager}get isHandlingLargeMeetingVideoRendering(){return this._isHandlingLargeMeetingVideoRendering}get callInfo(){return this._callInfo}get networkQualityUfdEventDetails(){return this._networkQualityUfdEventDetails}get acsProxy(){return this._callAgent.acsProxy}get acsCustomRelayManager(){return this._callAgent.acsCustomRelayManager}get audioEffectsProcessorStats(){return this._audioEffectsProcessorStats}get callAgent(){return this._callAgent}get iceServers(){return this._getIceServersCalledOnce||(this._getIceServersCalledOnce=!0,this._iceServers=this.tsCall.getMediaSessionStats()?.extensions?.IceServers),this._iceServers}get watermarkAudioOnlyFallbackTriggered(){return this._watermarkAudioOnlyFallbackTriggered}constructor(e,t,n,r,i,a){this._callAgent=t,this._isMuted=!1,this._isMuted_correlationIdCache=J0(),this._isIncomingAudioMuted=!1,this._isIncomingAudioMuted_correlationIdCache=J0(),this._isScreenSharingOn=!1,this._isLocalVideoStarted=!1,this._localVideoStreams=[],this._localAudioStreams=[],this._remoteAudioStreams=[],this._totalParticipantCount=1,this._isDeviceNotFunctioningMuted=!1,this.__attemptedToRecoverMicNotFunctioningBySDK=!1,this._isMicrophoneMuted=!1,this._disposed=!1,this._lastTsCallState=0,this._isSpeakerMuted=!1,this._callMode=0,this._role=E2,this._lastTsCallMeetingDetails={},this._isHandlingLargeMeetingVideoRendering=!1,this._joinContextDescription=R2.Unknown,this._remoteParticipantsChangedListeners=[],this._localRingingStateSet=!1,this._networkQualityUfdEventDetails=[],this._audioEffectsProcessorStats=null,this._getIceServersCalledOnce=!1,this._watermarkAudioOnlyFallbackTriggered=!1,this._transportStateTimestamp=new Map,this._setOrUpdateDeviceEventsTask=Promise.resolve(),this._isAcsTeamsCall=!1,this._isEnterpriseTeamsCall=this._callAgent.isEnterpriseUser(),this._isTeamsExtensionUser=this._callAgent.isTeamsExtensionUser(),this._mriToRemoteParticipantMap=new Map,this._remoteParticipants=[],this._state=`None`,this._transportState=`None`,this._allowIPAudio=!0,this._allowIPVideo=!0,this.localVideoStream=void 0,this.localScreenSharingStream=void 0,this.isRenderingRemoteScreenShare=!1,this._handleMuteChanges=()=>{let e=[b4.Rooms,b4.GroupIdCall,b4.MultiParty,b4.TeamsMeeting].some((e=>e===this._callInfo.context)),t=this.tsCall.conversationType||e?!!(this.tsCall.isMuted||this.tsCall.state!==10&&this.tsCall.isServerMuted||this._isDeviceNotFunctioningMuted):!(!this.tsCall.isMuted&&!this._isDeviceNotFunctioningMuted);if(this._isMuted!=t){this.logger.info(`isMuted changed from ${this._isMuted} to ${t}`);let e=[];this.tsCall.isMuted&&e.push(`isMicrophoneMuted`),this.tsCall.isServerMuted&&(e.push(`isServerMuted`),[3,4,5].some((e=>e===this.tsCall.state))&&this._eventEmitter.emit(`mutedByOthers`),this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()&&this.handleConsentCapabilitiesChanges()),this._isDeviceNotFunctioningMuted&&e.push(`isDeviceNotFunctioningMuted`);let n=``;e.length>=1&&(n=e.join(`, `)),t&&(this._isMuted_correlationIdCache=J0()),P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,this._isMuted_correlationIdCache,this._joinContextDescription),step:`isMuted-changed`,oldIsMuted:this._isMuted,newIsMuted:t,reason:n}),this._isMuted=t,this._eventEmitter.emit(`isMutedChanged`)}},this.audioSourceChanged=async e=>{this._telemetryLogManager.sendEvent({name:Q.acs_calling_local_audio_source_changed,tenant:p2,properties:{callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:+new Date,correlationId:J0(),localAudioStream:e.source?.source instanceof MediaStream?`MediaStream`:`Device`}}),e.source instanceof Z6?(this.localAudioStreams[0]&&this.localAudioStreams[0].mediaStreamType===`RawMedia`&&this.stopAudioInternal(!0),await(await this._callAgent.tsStack?.getDeviceManagerAsync?.())?.selectDevicesAsync?.({microphone:e.source.id})):await this.startAudioInternal(e.source,!0)},this._handleIncomingAudioMuteChanges=()=>{let e=this._isSpeakerMuted;this._isIncomingAudioMuted!=e&&(this.logger.info(`newIncomingAudioMuted changed from ${this._isIncomingAudioMuted} to ${e}`),e&&(this._isIncomingAudioMuted_correlationIdCache=J0()),P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,this._isIncomingAudioMuted_correlationIdCache,this._joinContextDescription),step:`isIncomingAudioMuted-changed`,oldIsMuted:this._isIncomingAudioMuted,newIsMuted:e,reason:``}),this._isIncomingAudioMuted=e,this._eventEmitter.emit(`isIncomingAudioMutedChanged`))},this._id=e.callId,this.tsCall=n,this._direction=e.isIncoming?`Incoming`:`Outgoing`,this._config=e,this.logger=this._callAgent.logger.createChild((()=>`Call:${this._id}:${this._state}`)),this._telemetryLogManager=r,this.stats=new dIe(this.logger,this._telemetryLogManager),this._eventEmitter=new w6(this.logger),this.activeRemoteVideoStreamViews=new Map,this.isSubscribedCall=!1,this.isBreakoutRoomCall=!1,this._mediaMetricsDeviceEvents={},this._kind=i,this._optimalVideoCount=1,this._ufdsCorrelationIdCache=dTe(),this._callInfo=new I7(n,{config:e}),this._callInfo.initialize(this._eventEmitter,this.logger,this._telemetryLogManager),this._ufdLogThrottler=new eLe([27],Z().telemetry.speakingWhileMutedThrottleInterval),Z().calling.mediaMetricsDeviceEventsEnabled&&(async()=>{let e=await this._callAgent.tsStack?.getDeviceManagerAsync?.();e&&(this._dmDevicesChangedSub=e.on(`devicesChanged`,(()=>{this._setOrUpdateDeviceEventsTask=this._setOrUpdateDeviceEventsTask.then((()=>this.setOrUpdateMediaMetricsDeviceEvents().catch(M4)))})))})().catch((e=>{this.logger.error(`Failed to register devicesChanged event: ${e}`)})),this._extensibleApi=new F3(this.logger,{call:this,callAgent:this._callAgent,callInfo:this._callInfo},{tsCall:this.tsCall,callAgent:this._callAgent,call:this,telemetryLogManager:this._telemetryLogManager}),this.explicitConsentStateImp=new $Ie(this.tsCall,t,this._eventEmitter,this.logger),this._capabilityResolver=new CDe(this._eventEmitter,this.logger,this,this._callInfo,t,n),this._lobby=new i7(this.tsCall,this,this.logger,this._telemetryLogManager);let o=e7(k3.CallFeature);for(let e of o)e.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(e);this._mmrRdpConnectionManager=new bIe(this.logger),Z().telemetry.sendNetworkChangedTelemetry&&this._sendNetworkChangedTelemetry(),Z().telemetry.deviceChangedEvents.enabled&&(this._selectedDeviceManager=new XIe(this.deviceManager),this._setupSelectedDeviceChangedTelemetry()),this._mediaConstraintsManager=new vIe(this.tsCall,this.logger,this._telemetryLogManager),this._isAcsTeamsCall=a??!1,this.feature($5.MediaAccess).on(`localParticipantMediaAccessChanged`,(e=>{this.logger.info(`Call common, time when received localParticipantMediaAccessChanged event: ${new Date().getTime()}, isAudioPermitted=${e.mediaAccess.isAudioPermitted}, isVideoPermitted=${e.mediaAccess.isVideoPermitted}`),!1===e.mediaAccess.isVideoPermitted&&this.localVideoStream&&this.stopVideo(this.localVideoStream)})),this.explicitConsentStateImp.onConsentRestrictionChanged(`consentRestrictionChanged`,(()=>{this.logger.info(`Call common, time when received explicitConsentStateChanged event:=\n ${this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()}`),this.handleConsentCapabilitiesChanges()}))}async accept(e={}){let t=e.audioOptions?.muted??!1,n=this.getLocalVideoStreamFromCallOptions(e),r=this.getLocalAudioStreamFromCallOptions(e),i=+new Date,a=this._callAgent.getEcsConfigIds(),o=fTe(this.tsCall),s=J0(),c=FG(s),l=this.createVideoNegotiationTag(s,`Video`),u={joinContextDescription:``,additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this._isEmergencyCall,trouterState:this._callAgent.getTrouterState(),muted:t,withVideo:this.isIPVideoEnabled&&!!n,withAudio:this.isIPAudioEnabled&&r?.mediaStreamType?r?.mediaStreamType:``,...a7(),AcsCallingSDKWeb_ecsConfigId:a.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:a.SkypeWebMedia,customContext:{userToUserPresent:!!o?.userToUser,xHeadersPresent:!!o?.xHeaders&&o.xHeaders.length>0},mediaModalities:this.getMediaModalityTelemetry(e?.mediaModalities),negotiationTag:l,causeId:c},additionalDetails:{}},d=(e,t,a)=>{let o=+new Date,d={...u},f;if(t){let t={message:J.CALL.ACCEPT_INCOMING_CALL.message,code:J.CALL.ACCEPT_INCOMING_CALL.code,subCode:J.CALL.ACCEPT_INCOMING_CALL.subCode,resultCategories:J.CALL.ACCEPT_INCOMING_CALL.resultCategories},{callEndReason:n,callingCommunicationError:r,hasDiagnosticsInfo:i}=U3(this,e,t);i?d.additionalDetails.callEndReason=n:d.additionalDetails.communicationServicesError=J3(r).communicationServicesError,f=r}else f=new Y({defaultError:J.CALL.ACCEPT_INCOMING_CALL,originalError:e}),d.additionalDetails.communicationServicesError=J3(f).communicationServicesError;if(this.sendCallStageEvent({eventName:Q.acs_calling_call_accept_failed,correlationId:s,timestampInfo:{deltaTimeInMs:o-i},additionalPayload:d},f,void 0,a?L7.getRemoveCauseIdToNetworkInfo(a):void 0),n){let e=+new Date;f=new Y({defaultError:J.LOCAL_VIDEO_STREAM.CALL_NOT_FOUND}),this.logger.error(f.message),this.sendVideoEvent({correlationId:s,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:e-i},localVideoStream:n,step:`accept`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:l,causeId:c}},f),this.removeLocalVideoStream(n)}return r&&this.removeLocalAudioStream(r),f};try{if(e?.videoOptions?.constraints){let t=this._mediaConstraintsManager.getTelemetryPayload({video:e?.videoOptions?.constraints});u.additionalProperties.constraints=t}u.additionalProperties.negotiationTag=l,u.additionalProperties.causeId=c,this.sendCallStageEvent({eventName:Q.acs_calling_call_accept_attempt,correlationId:s,timestampInfo:{attemptTimestamp:i},additionalPayload:u});let a={...u};if(n&&this.setLocalVideoStream(n),this.setLocalAudioStream(r),n&&this.sendVideoEvent({eventName:Q.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:i},correlationId:s,step:`accept`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:l,causeId:c}}),this.tsCall.state!==1)throw new Y({defaultError:J.CALL.ACCEPT_NOT_RINGING});try{if(e?.videoOptions?.constraints){let t=await this._mediaConstraintsManager.setVideoConstraints(e?.videoOptions?.constraints,`accept`,s,i),n=this._mediaConstraintsManager.getTelemetryPayload({video:t});a.additionalProperties.constraints=n}}catch(e){let t=new Y({defaultError:J.CALL.ACCEPT_VIDEO_CONSTRAINTS,originalError:e});this.logger.error(`${t.message}`)}let o={withVideo:!!n&&this.isIPVideoEnabled,muted:t};if(t&&(o.muteFlags=1),o.sendMediaModalities=this.setMediaModalities(e?.mediaModalities),Z()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(o.mediaConfiguration={connectionType:`NoDirectConnection`}),r&&await this.startAudioInternal(r,!0).catch((e=>{this.logger.error(`Failed to start localAudioStream, message=${e?.message}`)})),n?.mediaStreamType===`RawMedia`)try{await this._setRawStream(n,1)}catch(e){let t=+new Date,r=new Y({defaultError:J.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:e});this.sendVideoEvent({correlationId:s,eventName:Q.acs_calling_media_stream,timestampInfo:{deltaTimeInMs:t-i},localVideoStream:n,step:`accept`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:l,causeId:c}},r),this.removeLocalVideoStream(n)}let f=PG();return L7.setCauseIdToNetworkInfo(f),this.tsCall.accept(o,f).then((async()=>{let e=+new Date;n&&this.shallRemoveLvsAfterConnectedSuccessfully(n,`accept`,s,e,i,l,c),r&&this.shallRemoveLasAfterConnectedSuccessfully(r,`accept`,s,e,i),a.additionalProperties.negotiationTag=l,a.additionalProperties.causeId=c,this.sendCallStageEvent({eventName:Q.acs_calling_call_accept_connected,correlationId:s,timestampInfo:{deltaTimeInMs:e-i},additionalPayload:a},void 0,void 0,L7.getRemoveCauseIdToNetworkInfo(f))})).catch((e=>{d(e,!0,f)})),this}catch(e){throw d(e,!1)}}async reject(){let e=+new Date,t=J0();this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_attempt,correlationId:t,timestampInfo:{attemptTimestamp:e}});let n=this._callAgent.getEcsConfigIds(),r={additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this._isEmergencyCall,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:n.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:n.SkypeWebMedia},additionalDetails:{}};if(this.tsCall.state!==1){let n=new Y({defaultError:J.CALL.REJECT_NOT_RINGING});r.additionalDetails.communicationServicesError=J3(n).communicationServicesError;let i=+new Date;throw this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_failed,correlationId:t,timestampInfo:{deltaTimeInMs:i-e},additionalPayload:r},n),n}let i=PG();return L7.setCauseIdToNetworkInfo(i),this.tsCall.reject(i).then((()=>{let n=+new Date;this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_success,correlationId:t,timestampInfo:{deltaTimeInMs:n-e}},void 0,void 0,L7.getRemoveCauseIdToNetworkInfo(i))})).catch((n=>{let a=+new Date,o={message:J.CALL.REJECT_CALL_FAILED.message,code:J.CALL.REJECT_CALL_FAILED.code,subCode:J.CALL.REJECT_CALL_FAILED.subCode,resultCategories:J.CALL.REJECT_CALL_FAILED.resultCategories},{callEndReason:s,callingCommunicationError:c,hasDiagnosticsInfo:l}=U3(this,n,o);throw l?r.additionalDetails.callEndReason=s:r.additionalDetails.communicationServicesError=J3(c).communicationServicesError,this.sendCallStageEvent({eventName:Q.acs_calling_call_reject_failed,correlationId:t,timestampInfo:{deltaTimeInMs:a-e},additionalPayload:r},c,void 0,L7.getRemoveCauseIdToNetworkInfo(i)),c}))}dispose(){this._disposed||=(this._dmDevicesChangedSub&&this._dmDevicesChangedSub.dispose(),this._dmDevicesChangedSub=void 0,this._extensibleApi.dispose(),this._eventEmitter.removeAllListeners(),this._onlineListener&&window.removeEventListener(`online`,this._onlineListener),this._offlineListener&&window.removeEventListener(`offline`,this._offlineListener),this._trouterStateChangedListener&&this._callAgent.offTrouterStateChanged(this._trouterStateChangedListener),this._mmrRdpConnectionManager.dispose(),this._selectedDeviceManager?.dispose(),this.explicitConsentStateImp.dispose(),!0)}async startAudioInternal(e,t=!1){let n=J0(),r=+new Date,i=PG();L7.setCauseIdToNetworkInfo(i);try{if(this.isInternalApiCallWithoutRawMedia(e,t))return;this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.attempt,isInternal:t,timestampInfo:``,additionalDetails:``}),this.validateRawMedia(e,J.CALL.START_AUDIO_LAS_NOT_RAW_MEDIA),this._userProvidedLocalAudioStreamCache=e;let a=await this.createMediaStream(e),o=await this._callAgent.tsStack?.getDeviceManagerAsync?.();if(!Z()?.calling?.allowAccessRawMediaStream||!o?.setRawMediaStream)throw new Y({defaultError:J.CALL.LOCAL_AUDIO_SET_MEDIA_STREAM});o?.setRawMediaStream(a,0),this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream(e);let s=+new Date;this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.success,isInternal:t,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:s-r},additionalDetails:{networkInfo:L7.getRemoveCauseIdToNetworkInfo(i)}})}catch(e){let a=new Y({defaultError:J.CALL.START_AUDIO_STREAM_FAILED,originalError:e});this.logger.error(`Failed to start raw media audio: ${a.message}`);let o=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,isInternal:t,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-r},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...J3(a),networkInfo:L7.getRemoveCauseIdToNetworkInfo(i)}}),a}}isInternalApiCallWithoutRawMedia(e,t){return!(e?.mediaStreamType===`RawMedia`||!t)&&(this.logger.info(`startAudioInternal internal call: LocalAudioStream media type is raw media, skipping raw audio startAudioInternal`),!0)}validateRawMedia(e,t){if(e?.mediaStreamType!==`RawMedia`)throw new Y({defaultError:t})}async createMediaStream(e){let t;try{t=await e.getMediaStream()}catch(e){throw new Y({defaultError:J.CALL.LOCAL_AUDIO_GET_MEDIA_STREAM,originalError:e})}return new MediaStream(t)}stopAudioInternal(e=!1){let t=J0(),n=+new Date,r=PG();L7.setCauseIdToNetworkInfo(r);try{let i=this._localAudioStreams[0];if(this.isInternalApiCallWithoutRawMedia(i,e))return;this.sendRawMediaEvent({eventName:Q.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:$.attempt,isInternal:e,timestampInfo:``,additionalDetails:``}),e||t7(c4.StopAudio,this.state),this.validateRawMedia(i,J.CALL.STOP_AUDIO_LAS_NOT_RAW_MEDIA);let a=this._callAgent.tsStack?.getDeviceManager();if(!Z()?.calling?.allowAccessRawMediaStream||!a?.unsetRawMediaStream)throw new Y({defaultError:J.CALL.LOCAL_AUDIO_UNSET_MEDIA_STREAM});a.unsetRawMediaStream(0),this._userProvidedLocalAudioStreamCache=void 0,this.removeLocalAudioStream(this.localAudioStreams[0]),this.setLocalAudioStream();let o=+new Date;this.sendRawMediaEvent({eventName:Q.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,kindOfEvent:$.success,isInternal:e,localAudioStream:this.localAudioStreams[0],timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{networkInfo:L7.getRemoveCauseIdToNetworkInfo(r)}})}catch(i){let a=new Y({defaultError:J.CALL.STOP_AUDIO_STREAM_FAILED,originalError:i});this.logger.error(`Failed to stop raw media audio: ${a.message}`);let o=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_stop_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,isInternal:e,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...J3(a),networkInfo:L7.getRemoveCauseIdToNetworkInfo(r)}}),a}}bindTsCall(){let e=[];this.tsCall.callerMri!==void 0&&(this._callerIdentity=q2(this.tsCall.callerMri),this._callerDisplayName=this.tsCall.participants.find((e=>e.id===this.tsCall.callerMri))?.displayName),this._lastTsCallState=this.tsCall.state,this.mapTsCallState(this.tsCall.state),this._setCallRole(this.tsCall.advancedMeetingRole),this.tsCall.callQueueInfo?(this._callerIdentity=q2(this.tsCall.callQueueInfo.onBehalfOf.id),this._callerDisplayName=this.tsCall.callQueueInfo.onBehalfOf.displayName?this.tsCall.callQueueInfo.onBehalfOf.displayName:this.tsCall.participants.find((e=>e.id===this.tsCall.callQueueInfo?.details.id))?.displayName,this._transferorIdentity=q2(this.tsCall.callQueueInfo.details.id),this._transferorDisplayName=this.tsCall.callQueueInfo.details.displayName?this.tsCall.callQueueInfo.details.displayName:this.tsCall.participants.find((e=>e.id===this.tsCall.callQueueInfo?.details.id))?.displayName):this.tsCall.transferorMri&&(this._transferorIdentity=q2(this.tsCall.transferorMri),this._transferorDisplayName=this.tsCall.transferorDisplayName),this.updateCallMode(),e.push(this.tsCall.changed((()=>{this.tsCall.callId!==this._id&&(this.logger.log(`tsCall callId changed from ${this._id} to ${this.tsCall.callId}`),P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`id-changed`,isAcsTeamsCall:this.isAcsTeamsCall,oldCallId:this._id,newCallId:this.tsCall.callId}),this._id=this.tsCall.callId,this._eventEmitter.emit(`idChanged`)),this.tsCall.state!==this._lastTsCallState&&(this.logger.log(`tsCall state changed=${this.tsCall.state}`),this._lastTsCallState=this.tsCall.state,this.mapTsCallState(this.tsCall.state),this._handleMuteChanges()),this._isScreenSharingOn!==this.tsCall.isScreenSharingOn&&(this.logger.log(`tsCall isScreenSharingOn changed=${this.tsCall.isScreenSharingOn}`),this._isScreenSharingOn=this.tsCall.isScreenSharingOn,this._isScreenSharingOn||this.removeScreenSharingStream(),this._eventEmitter.emit(`isScreenSharingOnChanged`)),this._isMicrophoneMuted!==this.tsCall.isMuted&&(this.logger.log(`tsCall isMuted changed=${this.tsCall.isMuted}`),this._isMicrophoneMuted=this.tsCall.isMuted,this._handleMuteChanges()),this._isSpeakerMuted!==this.tsCall.isSpeakerMuted&&(this.logger.log(`tsCall _isSpeakerMuted changed=${this.tsCall.isSpeakerMuted}`),this._isSpeakerMuted=this.tsCall.isSpeakerMuted,this._handleIncomingAudioMuteChanges()),this.tsCall.advancedMeetingRole!==this._lastTsCallAdvancedMeetingRole&&(this.logger.log(`tsCall advancedMeetingRole changed=${this.tsCall.advancedMeetingRole}`),this._setCallRole(this.tsCall.advancedMeetingRole)),(this.tsCall.meetingData?.meetingUrl||this.tsCall.meetingData?.passcode||this.tsCall.conversationType==`scheduledMeeting`)&&this.tsCall.meetingDetails&&aTe(this.tsCall.meetingDetails,this._lastTsCallMeetingDetails)&&this._setMeetingCapabilities(this.tsCall.meetingDetails),this.updateCallMode()}))),e.push(this.tsCall.on(`optimalVideoReceiversCountChanged`,this.optimalVideoCountChanged)),e.push(this.tsCall.on(`serverMutedChanged`,(()=>{this.logger.log(`tsCall isServerMuted changed=${this.tsCall.isServerMuted}`),this._handleMuteChanges()}))),this._totalParticipantCount=L4(this.tsCall),e.push(this.tsCall.on(`participantCountsUpdated`,(()=>{let e=L4(this.tsCall);if(this._totalParticipantCount!==e){let t=this._totalParticipantCount;this._totalParticipantCount=e,this.logger.log(`tsCall totalParticipantCount changed from ${t} to ${this._totalParticipantCount}`),Z().rendering.remoteVideo.largeMeeting.handleVideoRendering&&this._enableOrDisable_largeMeeting_videoRendering(),this._eventEmitter.emit(`totalParticipantCountChanged`);try{this.stats.recordEvent({name:l3.number_of_participants,callId:this.id,localParticipantId:this.tsCall.participantId,data:{totalParticipantCount:this._totalParticipantCount,participantCounts:this.tsCall.participantCounts||{},previousParticipantCount:t}})}catch{this.logger.error(`failed to send participant count change telemetry`)}}})));let t=(e,t)=>{if(e!==t){this.logger.log(`transportState changed from ${this._transportState} to ${t}`);let n=this._transportStateTimestamp.get(`Connected`)===void 0?this._connectedTimestamp:void 0;this._transportStateTimestamp.delete(t);let r=e4.omitBy({connectedTimetamp:n,transportConnectedTimestamp:this._transportStateTimestamp.get(`Connected`),transportDisconnectedTimestamp:this._transportStateTimestamp.get(`Disconnected`),transportFailedTimestamp:this._transportStateTimestamp.get(`Failed`)},e4.isUndefined),i=e4.merge(N7(this,this._callAgent,J0(),this._joinContextDescription),{timestampInfo:r});P7(this._telemetryLogManager,this.logger,{...i,step:`transportState-changed`,oldState:e,newState:t}),this._transportStateTimestamp.set(t,Date.now()),this._transportState=t}};e.push(this.tsCall.on(`transportConnected`,(()=>{t(this._transportState,`Connected`)}))),e.push(this.tsCall.on(`transportDisconnected`,(()=>{t(this._transportState,`Disconnected`)}))),e.push(this.tsCall.on(`transportFailed`,(()=>{t(this._transportState,`Failed`)}))),e.push(this.tsCall.on(`callQualityChanged`,(async e=>{try{let t;e.type===5||e.type===32||e.type===2||e.type===1||e.type===37?(t=l3.network_quality,this._trackNetworkQualityUfdEventDetails(e.type)):t=e.type===44||e.type===43||e.type===9||e.type===25||e.type===45||e.type===33||e.type===34||e.type===55||e.type===26||e.type===47||e.type===27?l3.video_device_issue:l3.other_diagnostic,e.value===3||e.value===2?(this._ufdLogThrottler.shouldLogError(e.type,new Date)&&this.logger.warn(`Ufd error raised!, ufd=${e.type}, value=${e.value}, kind=${t}`),t===l3.network_quality&&window.dispatchEvent(new CustomEvent(`online`,{detail:!1}))):(this._ufdLogThrottler.shouldLogRecovery(e.type,new Date)&&this.logger.warn(`Ufd error recovered!, ufd=${e.type}, value=${e.value}, kind=${t}`),t===l3.network_quality&&window.dispatchEvent(new CustomEvent(`online`,{detail:!0})));let n=``,r=this._ufdsCorrelationIdCache[e.type][e.mediaType];e.value==3||e.value==2?r?n=r:(n=J0(),this._ufdsCorrelationIdCache[e.type][e.mediaType]=n):(r&&(n=r),this._ufdsCorrelationIdCache[e.type][e.mediaType]=void 0);let i={type:e.type.toString(),level:e.value,mediaType:e.mediaType,correlationId:n};if(this.stats.recordEvent({name:t,callId:this.id,localParticipantId:this.tsCall.participantId,data:i}),this.shallStopVideo(e)){let t=+new Date,n=J0();this.logger.warn(`Attempting to stop video gracefully due to video ufd being raised.UFD: ${e.type}, value: ${e.value}, call direction: ${this._direction}`),this.sendAudioEvent({eventName:Q.acs_calling_stop_video_on_ufd_attempt,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{this.localVideoStream&&this.stopVideo(this.localVideoStream)}catch{let t=`Failed to stop video on video device start failed or capture mute event ${e.type} with value ${e.value}`;this.logger.error(t)}}if(this.shallRemoveLocalVideoStreamOnBadUfd(e)){let t=new Y({defaultError:J.CALL.REMOVE_LOCAL_VIDEO_ON_BAD_UFD,defaultErrorMessageArgs:[e.type,e.value,this._direction]});if(this.localVideoStream){let e=FG(n),r=this.createVideoNegotiationTag(n,`Video`);this.sendVideoEvent({eventName:Q.acs_calling_start_video_failure,correlationId:J0(),timestampInfo:{attemptTimestamp:+new Date},step:`start`,additionalDetails:{...J3(t),negotiationTag:r,causeId:e},localVideoStream:this.localVideoStream,isScreenSharingOnFlag:this.isScreenSharingOn},t),this.removeLocalVideoStream(this.localVideoStream)}this.logger.error(t.message)}if(this.shallStopAudio(e)){let t=+new Date,n=J0();if(Z()?.calling?.allowMuteOnBadUfd&&!this.tsCall.isMuted){this.sendAudioEvent({eventName:Q.acs_calling_mute_on_ufd_attempt,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.mute()}catch{let t=`Failed to mute on microphone device not functioning or capture mute event ${e.type} with value ${e.value}`;this.logger.error(t)}}if(Z()?.calling?.preventStopAudio)return this.sendAudioEvent({eventName:Q.acs_calling_prevent_stop_audio,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`}),void(!Z()?.calling?.preventFakeMute&&this.markCallMuted());this.sendAudioEvent({eventName:Q.acs_calling_stop_audio_attempt,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.tsCall.stopAudio(),this.markCallMuted();let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_stop_audio_success,timestampInfo:{deltaTimeInMs:e-t},correlationId:n,step:`mid-call`})}catch(r){let i=new Y({defaultError:J.CALL.STOP_AUDIO_ON_BAD_UFD,defaultErrorMessageArgs:[e.type,e.value],originalError:r});this.logger.error(i.message);let a=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_stop_audio_failure,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`},i)}}this.muteUnmuteOnMicrophoneNotFunctioningUfd(e),this.audioDidAutoRecover(e)&&(this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges())}catch{this.logger.error(`Failed to send ufd telemetry`)}}))),e.push(this.tsCall.on(`participantAdded`,(async e=>{this.logger.debug(`tsCall participant added`);let t=[];e.endpoints?.endpointDetails.forEach((e=>t.push(e.participantId))),t.length===0&&t.push(`remoteParticipantId unavailable`);let n=q2(e.id);if(this._isEnterpriseTeamsCall=this._isEnterpriseTeamsCall||n.kind===`microsoftTeamsUser`,this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:`added`,kindOfEvent:$.event}),R4(e))this.logger.info(`Add participant: Handle hidden calling application`);else{this.checkAndUpdateCopilotDisplayName(e),this._handleLocalRingingCallState(e);try{let t=this.getOrCreateRemoteParticipant(n,e);this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[t],removed:[]})}catch{this.logger.log(`unable to map call participant to ACS user`)}}}))),this.logger.debug(`tsCall current participant count=${this.tsCall?.participants?.length}`);let n=e=>{let t=q2(e.id);this._isEnterpriseTeamsCall=this._isEnterpriseTeamsCall||t.kind===`microsoftTeamsUser`;let n=this.getOrCreateRemoteParticipant(t,e);this._handleLocalRingingCallState(e),n.on(`displayNameChanged`,(()=>{this._callerIdentity&&K2(this._callerIdentity)===K2(n.identifier)&&(this._callerDisplayName=n.displayName,this._eventEmitter.emit(`callerInfoChanged`)),this._transferorIdentity&&K2(this._transferorIdentity)===K2(n.identifier)&&(this._transferorDisplayName=n.displayName,this._eventEmitter.emit(`transferorInfoChanged`))}))},r=[];this.tsCall.participants.forEach((e=>{Z().calling.checkHiddenBotOnCallStart&&R4(e)||n(e);try{e.endpoints?.endpointDetails.forEach((e=>r.push(e.participantId)))}catch{this.logger.error(`Unable to get participantId from from remote participant`)}}));try{this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:r,participantAddedOrRemoved:`added`,kindOfEvent:$.initialize})}catch{this.logger.error(`Unable to send participant added telemtery`)}return e.push(this.tsCall.on(`participantRemoved`,(async e=>{this.logger.debug(`tsCall participant removed`);let t=[];if(e.endpoints?.endpointDetails.forEach((e=>t.push(e.participantId))),t.length===0&&t.push(`remoteParticipantId unavailable`),R4(e))return this.logger.info(`Remove participant: Ignore calling application`),void this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:`removed`,kindOfEvent:$.event});let n=e.id;if(n){let r=this._remoteParticipants.find((e=>K2(e.identifier)===n));if(r){let{callEndReason:n}=W3(this,e);r.setCallEndReason(n),this.deleteRemoteParticipant(r),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:[r]}),this.sendParticipantAddedOrRemovedEvent({remoteParticipantIds:t,participantAddedOrRemoved:`removed`,kindOfEvent:$.event,additionalDetails:{...Y3(n)}})}else this.logger.log(`unable to find participant to remove`)}}))),e}_trackNetworkQualityUfdEventDetails(e){let t=+new Date,n=``;switch(e){case 5:n=i6;break;case 32:n=s6;break;case 2:n=a6;break;case 1:n=o6;break;case 37:n=c6}this._networkQualityUfdEventDetails.push({eventName:n,timestampInfo:t})}async muteUnmuteOnMicrophoneNotFunctioningUfd(e){try{let t=Z().calling;if(!t.muteUnmuteOnMicrophoneNotFunctioning||this._isMuted||e.type!==9||e.value!==3)return;this.__attemptedToRecoverMicNotFunctioningBySDK=!0,await this.mute(),t.unmuteDelayForMicrophoneNotFunctioningInMs>=0&&await r3(t.unmuteDelayForMicrophoneNotFunctioningInMs),await this.unmute()}catch(e){this.logger.info(`Unable to perform mute and unmute to recover microphoneNotFunctioning`,e)}finally{this.__attemptedToRecoverMicNotFunctioningBySDK=!1}}updateCallMode(){this.tsCall.callMode&&this._callMode!==this.tsCall.callMode&&(this.logger.log(`tsCall callMode changed from ${this._callMode} to ${this.tsCall.callMode}`),P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`callMode-changed`,oldState:eDe[this._callMode],newState:eDe[this.tsCall.callMode]}),this._callMode=this.tsCall.callMode)}checkAndUpdateCopilotDisplayName(e){this.tsCall.meetingDetails&&(K2(e)!==g2||e.displayName!==``&&e.displayName!==void 0||(e.displayName=y2))}async startCallInternal(e,t,n,r,i,a){let o=!!e?.audioOptions?.muted,s=this.getLocalVideoStreamFromCallOptions(e),c=this.getLocalAudioStreamFromCallOptions(e),l,u=i?.attemptTimestamp??+new Date,d=J0();this._joinContextDescription=nTe(n);let f=this._callAgent.getEcsConfigIds(),p=this.tsCall.participants.length===1&&!this.tsCall.threadId&&!t,m=!!p||this._allowIPAudio,h=!!p||this._allowIPVideo,g=G6(this.tsCall),_=i?.correlationId??J0(),v=FG(_),y=this.createVideoNegotiationTag(_,`Video`),b={joinContextDescription:this._joinContextDescription,additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:r?.isEmergency||!1,dialedEmergencyNumber:r?.isEmergency?this.tsCall.participants?.[0]?.id:void 0,trouterState:this._callAgent.getTrouterState(),muted:o,withVideo:h&&!!s,withAudio:m&&c?.mediaStreamType?c.mediaStreamType:``,...a7(),AcsCallingSDKWeb_ecsConfigId:f.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:f.SkypeWebMedia,customContext:{userToUserPresent:!!e?.customContext?.userToUser,xHeadersPresent:!!e?.customContext?.xHeaders&&e.customContext.xHeaders.length>0},firstPartyOptions:{isDeviceTypeEnabled:Z().calling.setDeviceType,deviceType:this._callAgent.getDeviceType(),isImmersiveMode:e?.firstPartyOptions?.isImmersiveMode,accessToImmersiveEvents:e?.firstPartyOptions?.accessToImmersiveEvents},mediaModalities:this.getMediaModalityTelemetry(e?.mediaModalities),negotiationTag:y,causeId:v},additionalDetails:{}};e?.videoOptions?.constraints&&(b.additionalProperties.constraints=this._mediaConstraintsManager.getTelemetryPayload({video:e?.videoOptions?.constraints})),r?.meetingInfo?.tenantId&&(this._teamsMeetingTenantId=r.meetingInfo.tenantId,b.additionalProperties.teamsMeetingTenantId=r.meetingInfo.tenantId),r?.threadId&&(this._teamsMeetingThreadId=r.threadId,b.additionalProperties.teamsMeetingThreadId=r.threadId),r?.onBehalfOf&&(b.additionalProperties.onBehalfOfProvided=!0,b.additionalProperties.onBehalfOfIdKind=q2(r.onBehalfOf).kind,this.logger.info(`onBehalfOf provided kind: ${b.additionalProperties.onBehalfOfIdKind}`));let x={...b},S={...b};this.sendCallStageEvent({eventName:Q.acs_calling_call_attempt,correlationId:_,timestampInfo:{attemptTimestamp:u},additionalPayload:b},void 0,void 0,void 0,`attempt`);try{this._isMicrophoneMuted=o,e?.alternateCallerId&&(l=K2(e.alternateCallerId)),s&&this.setLocalVideoStream(s),this.setLocalAudioStream(c)}catch(e){a?.reject(e);let t=+new Date,n=new Y({defaultError:J.CALL.INSTANTIATE_CALL,originalError:e});throw x.additionalDetails.communicationServicesError=J3(n).communicationServicesError,this.sendCallStageEvent({eventName:Q.acs_calling_call_failed,correlationId:_,timestampInfo:{deltaTimeInMs:t-u},additionalPayload:x},n,void 0,void 0,`failure`),this.logger.error(n.message),n}let C=PG();L7.setCauseIdToNetworkInfo(C);try{let n={...r};!Z().calling.setDeviceType||this._callAgent.getDeviceType()!==`mesh`&&this._callAgent.getDeviceType()!==`meshV2`||(n.endpointMetadata=JSON.stringify({meshapp:!0})),g?(await this.tsCall.initAsync?.(n),a?.resolve()):this.tsCall.init(n),s&&this.sendVideoEvent({correlationId:d,eventName:Q.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:u},localVideoStream:s,step:`start`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:y,causeId:v}});try{if(e?.videoOptions?.constraints){let t=await this._mediaConstraintsManager.setVideoConstraints(e?.videoOptions?.constraints,`start`,d,u),n=this._mediaConstraintsManager.getTelemetryPayload({video:t});S.additionalProperties.constraints=n}}catch(e){let t=new Y({defaultError:J.CALL.CALLSTART_VIDEO_CONSTRAINTS,originalError:e});this.logger.error(`${t.message}`)}let i=this.setClientCallStartOptions(e);if(Z()?.calling?.enableCustomTurnUsage&&this.acsCustomRelayManager?.customRelayManagerInUse&&(i.mediaConfiguration={connectionType:`NoDirectConnection`}),o&&(i.muteFlags=1),e?.firstPartyOptions?.disableAudioMixing&&(i.muteFlags===void 0?i.muteFlags=2:i.muteFlags|=2),e?.firstPartyOptions?.enableSpatialAudio!==void 0&&(i.mediaConfiguration=i.mediaConfiguration||{},i.mediaConfiguration.enableSpatialAudio=e.firstPartyOptions.enableSpatialAudio,this._callAgent.tsStack?await this._callAgent.tsStack.setMediaConfig({enableSpatialAudio:e.firstPartyOptions.enableSpatialAudio}):this.logger.error(`Could not set enableSpatialAudio to ${e.firstPartyOptions.enableSpatialAudio} since this._callAgent.tsStack is null`)),i.customHeaderContext=U4(e),c&&await this.startAudioInternal(c,!0).catch((e=>{this.logger.error(`Failed to start localAudioStream, message=${e?.message}`)})),s?.mediaStreamType===`RawMedia`)try{await this._setRawStream(s,1)}catch(e){let t=+new Date,n=new Y({defaultError:J.LOCAL_VIDEO_STREAM.VIDEO_GET_MEDIA_STREAM,originalError:e});this.sendVideoEvent({correlationId:d,eventName:Q.acs_calling_media_stream,timestampInfo:{deltaTimeInMs:t-u},localVideoStream:s,step:`start`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:y}},n),this.removeLocalVideoStream(s)}t?await this.tsCall.startWithMeetingData(C,{withVideo:!!s&&this.isIPVideoEnabled,muted:o,ringOthers:!0,alternateId:l,shouldResurrect:`resurrect`,...i}):(i.negotiationTag=this.createVideoNegotiationTag(_,`Video`),await this.tsCall.start({withVideo:!!s&&this.isIPVideoEnabled,muted:o,ringOthers:!0,alternateId:l,...i},C)),S.additionalProperties.negotiationTag=y,S.additionalProperties.causeId=v;let f=+new Date;this.sendCallStageEvent({eventName:Q.acs_calling_call_connected,correlationId:_,timestampInfo:{deltaTimeInMs:f-u},additionalPayload:S},void 0,void 0,L7.getRemoveCauseIdToNetworkInfo(C),`success`),c&&this.shallRemoveLasAfterConnectedSuccessfully(c,`start`,_,f,u),s&&this.shallRemoveLvsAfterConnectedSuccessfully(s,`start`,_,f,u,y,v),this._handleAudioEffectsOperations()}catch(e){a?.reject(e);let t=+new Date,{callEndReason:n,callingCommunicationError:r}=U3(this,e);if(s){let n=new Y({defaultError:J.LOCAL_VIDEO_STREAM.CALL_NOT_FOUND,originalError:e});this.sendVideoEvent({correlationId:d,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:t-u},localVideoStream:s,step:`start`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:y,causeId:v}},n),this.removeLocalVideoStream(s)}throw c&&this.removeLocalAudioStream(c),x.additionalDetails.callEndReason=Y3(n).callEndReason,x.additionalProperties.negotiationTag=y,x.additionalProperties.causeId=v,this.sendCallStageEvent({eventName:Q.acs_calling_call_failed,correlationId:_,timestampInfo:{deltaTimeInMs:t-u},additionalPayload:x},r,void 0,L7.getRemoveCauseIdToNetworkInfo(C),`failure`),this.logger.error(`Failed to start the call, message=${n?.message}, code=${n?.code}, subCode=${n?.subCode}, resultCategories=${n?.resultCategories}`),r}}getMediaModalityTelemetry(e){return e?{audio:e.audio,video:e.video,screenShare:e.screenShare}:void 0}getTopNDominantSpeakersWithVideoOn(){if(this._internalDominantSpeakersListener){let e=this._internalDominantSpeakersListener.dominantSpeakers.speakersList.map((e=>this._mriToRemoteParticipantMap.get(K2(e)))).filter((e=>!!e)).filter((e=>!!e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).find((e=>e.tsStream.isAvailable))));if(this.logger.info(`There are currently ${e.length} top-n dominant speakers with video on in the large meeting where topCount is ${Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount}`),e.length<Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount){let t=this._remoteParticipants.filter((e=>!!e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).find((e=>e.tsStream.isAvailable)))).filter((t=>!e.includes(t)));t.sort(((e,t)=>{let n=e.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((e=>e.type===`audio`)).map((e=>e.sourceId))??[],r=n.length>0?Math.min(...n):void 0,i=t.tsRemoteParticipant?.endpoints?.endpointDetails[0]?.mediaStreams?.filter((e=>e.type===`audio`)).map((e=>e.sourceId))??[],a=i.length>0?Math.min(...i):void 0;return r!==void 0&&a!=null?r-a:0}));for(let n of t){if(e.length===Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount)break;e.push(n)}}else e.splice(Z().rendering.remoteVideo.largeMeeting.dominantSpeakersWithVideoOn_topCount);return e}return[]}getParticipantCapabilities(){let e=this._capabilityResolver.getCapabilities();return this.logger.log(`participant capabilities are ${e}`),e}getMeetingCapabilitiesInternal(){let e=this._capabilityResolver.getMeetingsCapabilitiesInternal();return this.logger.info(`meeting capabilities are ${e}`),e}feature(e){return this._extensibleApi.getApiObjectInstance(e.callApiCtor)}async hangUp(e){let t=+new Date,n=J0(),r=PG();return L7.setCauseIdToNetworkInfo(r),this.sendCallStageEvent({eventName:Q.acs_calling_call_hangup_attempt,correlationId:n,timestampInfo:{attemptTimestamp:t}}),this.tsCall.stop(e?.forEveryone,r).then((()=>{let e=+new Date;this.sendCallStageEvent({eventName:Q.acs_calling_call_hangup_success,correlationId:n,timestampInfo:{deltaTimeInMs:e-t}},void 0,void 0,L7.getRemoveCauseIdToNetworkInfo(r))})).catch((e=>{let i=+new Date,{callEndReason:a,callingCommunicationError:o,hasDiagnosticsInfo:s}=U3(this,e),c=this._callAgent.getEcsConfigIds(),l={additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this._isEmergencyCall,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:c.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:c.SkypeWebMedia},additionalDetails:{}};if(s)l.additionalDetails={...Y3(a)};else{let t=new Y({defaultError:J.CALL.OPERATION_FAILED,originalError:e});l.additionalDetails.communicationServicesError=J3(t).communicationServicesError}throw this.sendCallStageEvent({eventName:Q.acs_calling_call_hangup_failure,correlationId:n,timestampInfo:{deltaTimeInMs:i-t},additionalPayload:l},o,void 0,L7.getRemoveCauseIdToNetworkInfo(r)),o}))}async mute(){let e=this.logger.createFnLogger(c4.Mute),t=+new Date,n=J0(),r=PG();L7.setCauseIdToNetworkInfo(r),this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:d3.MuteMicrophone,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK});try{e.info(`mute`),await this.tsCall.mute(r),e.info(`mute success`);let i=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:d3.MuteMicrophone,timestampInfo:{deltaTimeInMs:i-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:L7.getRemoveCauseIdToNetworkInfo(r)})}catch(i){let a=new Y({defaultError:J.CALL.MIC_MUTE,originalError:i});e.error(`Failed to mute microphone`);let o=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:d3.MuteMicrophone,timestampInfo:{deltaTimeInMs:o-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:L7.getRemoveCauseIdToNetworkInfo(r)},a),a}}async unmute(){let e=this.logger.createFnLogger(c4.Unmute),t=+new Date,n=J0(),r=!1,i=PG();if(L7.setCauseIdToNetworkInfo(i),this.sendAudioEvent({eventName:Q.acs_calling_unmute_attempt,eventType:d3.UnmuteMicrophone,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK}),!this.isAudioPermitted()){let t=`cannot unmute as microphone is disabled`;throw e.error(t),new Y({defaultError:J.CALL.MIC_DISABLED,originalError:t})}if(!this.isIPAudioEnabled){let t=`cannot unmute as IP audio in Teams Meeting Policy is disabled`;throw e.error(t),new Y({defaultError:J.CALL.IP_AUDIO_NOT_ALLOWED,originalError:t})}if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){let t=`cannot unmute as consent is required to be recorded or transcribed`;throw e.error(t),new Y({defaultError:J.CALL.UNMUTE_CONSENT_RESTRICTED,originalError:t})}try{e.info(`unmute`),await this.tsCall.unmute(i),e.info(`unmute success`);let a=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_unmute_success,eventType:d3.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK,networkInfo:L7.getRemoveCauseIdToNetworkInfo(i)});let o=+new Date;if(!Z()?.calling?.preventStopAudio&&this._isDeviceNotFunctioningMuted){this.sendAudioEvent({eventName:Q.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:o},correlationId:n,step:`mid-call`,networkInfo:L7.getRemoveCauseIdToNetworkInfo(i)}),r=!0,e.info(`start audio`),await this.tsCall.startAudio(),e.info(`start audio success`);let t=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:Q.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:t-o},correlationId:n,step:`mid-call`,networkInfo:L7.getRemoveCauseIdToNetworkInfo(i)})}this.setLocalAudioStream()}catch(a){let o=r?J.CALL.MIC_UNMUTE_AND_STARTAUDIO:J.CALL.MIC_UNMUTE,s=new Y({defaultError:o,originalError:a});e.error(o.message);let c=+new Date;throw this.sendAudioEvent({eventName:r?Q.acs_calling_start_audio_failure:Q.acs_calling_unmute_failure,eventType:r?void 0:d3.UnmuteMicrophone,timestampInfo:{deltaTimeInMs:c-t},correlationId:n,step:`mid-call`,initiatedBySdk:this.__attemptedToRecoverMicNotFunctioningBySDK&&!r,networkInfo:L7.getRemoveCauseIdToNetworkInfo(i)},s),s}}async muteAllRemoteParticipants(){let e=Z();if(!e.calling.enableMuteOthers)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_DISABLED});if(!this.tsCall.conversationType&&this._callInfo.context===b4.TwoParty)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_1_TO_1_UNSUPPORTED});let t=this.logger.createFnLogger(c4.MuteAllRemoteParticipants),n=+new Date,r=J0();this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:d3.MuteAllRemoteParticipants,timestampInfo:{attemptTimestamp:n},correlationId:r,step:`mid-call`});try{t.info(`mute all others`),t7(c4.MuteAllRemoteParticipants,this.state);let i=[];if(this._remoteParticipants.length!==0){let n=!1,r=!1,a=``;if(this._remoteParticipants.map((o=>{let s=o.tsRemoteParticipant;e.calling.allowMutePstnRemoteParticipant||o.identifier.kind!==`phoneNumber`?[3,5].some((e=>e===s?.state))?s!==void 0&&(i.push(s),a+=K2(o.identifier)+`, `):(t.warn(`non-connected participants cannot be muted by others`),r=!0):(t.warn(`PSTN participants cannot be muted by others`),n=!0)})),i.length===0?t.error(`all remote participants are not supported to be muted by others`):(await this.tsCall.muteParticipants(1,i),t.info(`called mute function on the following participants: ${a}`)),n){if(!this._isTeamsExtensionUser||!Z().calling.teamsExtensionSettings.enableServerMutePSTNParticipant)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_PSTN_UNSUPPORTED});t.info(`Enable server muting of PSTN participant for TeamsExtension user`)}if(r)throw new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS_NONCONNECTED_UNSUPPORTED})}else t.info(`no participants to mute in attempt to mute all remote participants`);t.info(`mute all others success`);let a=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:d3.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:a-n},correlationId:r,step:`mid-call`})}catch(e){let i=new Y({defaultError:J.CALL.MUTE_ALL_PARTICIPANTS,originalError:e});t.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:d3.MuteAllRemoteParticipants,timestampInfo:{deltaTimeInMs:a-n},correlationId:r,step:`mid-call`},i),i}}async muteIncomingAudio(){let e=this.logger.createFnLogger(c4.MuteIncomingAudio),t=+new Date,n=J0();this.sendAudioEvent({eventName:Q.acs_calling_mute_attempt,eventType:d3.MuteIncomingAudio,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.tsCall.muteSpeaker();let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_mute_success,eventType:d3.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:e-t},correlationId:n,step:`mid-call`})}catch(r){let i=new Y({defaultError:J.CALL.MUTE_INCOMING_AUDIO,originalError:r});e.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_mute_failure,eventType:d3.MuteIncomingAudio,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`},i),i}}async unmuteIncomingAudio(){let e=this.logger.createFnLogger(c4.MuteIncomingAudio),t=+new Date,n=J0();this.sendAudioEvent({eventName:Q.acs_calling_unmute_attempt,eventType:d3.UnmuteIncomingAudio,timestampInfo:{attemptTimestamp:t},correlationId:n,step:`mid-call`});try{await this.tsCall.unmuteSpeaker();let e=+new Date;this.sendAudioEvent({eventName:Q.acs_calling_unmute_success,eventType:d3.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:e-t},correlationId:n,step:`mid-call`})}catch(r){let i=new Y({defaultError:J.CALL.UNMUTE_INCOMING_AUDIO,originalError:r});e.error(i.message);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_unmute_failure,eventType:d3.UnmuteIncomingAudio,timestampInfo:{deltaTimeInMs:a-t},correlationId:n,step:`mid-call`},i),i}}async sendDtmf(e){let t=tDe(e);return this.tsCall.sendDtmfTone(t).catch((e=>{throw this.logger.error(`Failed to send DTMF tone`),new Y({defaultError:J.CALL.DTMF_TONE})}))}async startVideo(e){let t=this.logger.createFnLogger(c4.StartVideo),n=+new Date,r=Z()?.calling?.preventStopAudio,i=J0(),a=FG(i),o=this.createVideoNegotiationTag(i,`Video`);if(this.sendVideoEvent({eventName:Q.acs_calling_start_video_attempt,timestampInfo:{attemptTimestamp:n},localVideoStream:e,correlationId:i,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:o,causeId:a}}),!this.isVideoPermitted()){let e=`cannot start video as camera is disabled by the Presenter or Organizer of the meeting`;throw t.error(e),new Y({defaultError:J.CALL.CAMERA_DISABLED,originalError:e})}if(!this.isIPVideoEnabled){let e=`cannot start video as IP video is not allowed`;throw t.error(e),new Y({defaultError:J.CALL.IP_VIDEO_NOT_ALLOWED,originalError:e})}if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){let e=`cannot start video as consent is restricted`;throw t.error(e),new Y({defaultError:J.CALL.VIDEOSTART_CONSENT_RESTRICTED,originalError:e})}if(this._isDeviceNotFunctioningMuted&&!r){this.sendAudioEvent({eventName:Q.acs_calling_start_audio_attempt,timestampInfo:{attemptTimestamp:n},correlationId:i,step:`mid-call`});try{t.info(`start audio before starting video`),await this.tsCall.startAudio(),t.info(`start audio success before starting video`);let e=+new Date;this._isDeviceNotFunctioningMuted=!1,this._handleMuteChanges(),this.sendAudioEvent({eventName:Q.acs_calling_start_audio_success,timestampInfo:{deltaTimeInMs:e-n},correlationId:i,step:`mid-call`})}catch(e){let r=new Y({defaultError:J.CALL.START_AUDIO_BEFORE_VIDEO,originalError:e});t.error(`Failed to start audio before starting video`);let a=+new Date;throw this.sendAudioEvent({eventName:Q.acs_calling_start_audio_failure,timestampInfo:{deltaTimeInMs:a-n},correlationId:i,step:`mid-call`},r),r}}try{if(!e)throw new Y({defaultError:J.CALL.STREAM_NULL});if(!(e instanceof X6))throw new Y({defaultError:J.CALL.STREAM_IS_NOT_LVS});if(this.tsCall.isVideoOn)throw new Y({defaultError:J.CALL.VIDEO_ALREADY_ON});e?.mediaStreamType===`RawMedia`&&await this._setRawStream(e,1),this.setLocalVideoStream(e)}catch(t){let r=new Y({defaultError:J.CALL.START_VIDEO,originalError:t});throw this.sendVideoEvent({correlationId:i,eventName:Q.acs_calling_start_video_failure,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:o,causeId:a}},r),r}L7.setCauseIdToNetworkInfo(a);try{t.info(`start video`),await this.tsCall.startVideo(o,a);let r=+new Date;this.sendVideoEvent({correlationId:i,eventName:Q.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:r-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:L7.getRemoveCauseIdToNetworkInfo(a),additionalDetails:{negotiationTag:o,causeId:a}}),t.info(`video started`)}catch(r){let s=+new Date,c=G3(t,r);throw this.sendVideoEvent({correlationId:i,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:s-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:L7.getRemoveCauseIdToNetworkInfo(a),additionalDetails:{negotiationTag:o,causeId:a}},c),this.removeLocalVideoStream(e),c}}async stopVideo(e){let t=this.logger.createFnLogger(c4.StopVideo),n=+new Date,r=J0(),i=FG(r),a=this.createVideoNegotiationTag(r,`Video`);this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_attempt,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:i}});let o=this.tsCall.state===4||this.tsCall.state===5;if(!o&&!this.tsCall.isVideoOn||o&&!this.localVideoStream){let t=new Y({defaultError:J.CALL.VIDEO_ALREADY_OFF});throw this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:i}},t),t}if(this.localVideoStream!==void 0&&this.localVideoStream!==e){let t=new Y({defaultError:J.CALL.STOP_WRONG_STREAM});throw this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_failure,timestampInfo:{attemptTimestamp:n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:i}},t),t}let s=()=>{try{if(Z().calling.allowAccessRawMediaStream&&e.mediaStreamType===`RawMedia`){let e=this._callAgent.tsStack?.getDeviceManager();e&&e.unsetRawMediaStream&&e.unsetRawMediaStream(1)}}catch(e){this.logger.info(`Unset raw video stream: ${e?.message??`Unkown error`}`)}};L7.setCauseIdToNetworkInfo(i);try{t.info(`stop video`),await this.tsCall.stopVideo(a,i),s();let o=+new Date;this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_success,timestampInfo:{deltaTimeInMs:o-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:L7.getRemoveCauseIdToNetworkInfo(i),additionalDetails:{negotiationTag:a,causeId:i}}),t.info(`video stopped`),this.removeLocalVideoStream(e)}catch(o){s();let c=+new Date,l=G3(t,o,!0);throw this.sendVideoEvent({correlationId:r,eventName:Q.acs_calling_stop_video_failure,timestampInfo:{deltaTimeInMs:c-n},localVideoStream:e,step:`mid-call`,isScreenSharingOnFlag:this._isScreenSharingOn,networkInfo:L7.getRemoveCauseIdToNetworkInfo(i),additionalDetails:{negotiationTag:a,causeId:i}},l),l}}startAudio(e){return this.startAudioInternal(e)}stopAudio(){return this.stopAudioInternal()}async hold(){let e=+new Date,t=J0(),n=PG();L7.setCauseIdToNetworkInfo(n);try{this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Hold,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:S4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),Z().calling.turnOffScreenShareBeforeHold&&this.tsCall.isScreenSharingOn&&await this.tsCall.stopScreenSharing().then((()=>{this.logger.log(`Successfully turned off screen sharing before hold`)})).catch((()=>{this.logger.error(`Failed to turn off screensharing before hold`)})),await this.tsCall.hold(void 0,n),this.removeLocalAudioStream(this._localAudioStreams[0]);let r=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Hold,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{holdType:S4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn},networkInfo:L7.getRemoveCauseIdToNetworkInfo(n)})}catch{let r=+new Date,i=new Y({defaultError:J.CALL.HOLD_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Hold,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,holdType:S4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...J3(i)},networkInfo:L7.getRemoveCauseIdToNetworkInfo(n)}),i}}async resume(){let e=+new Date,t=J0(),n=PG();L7.setCauseIdToNetworkInfo(n);try{this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Resume,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:S4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),await this.tsCall.unhold(void 0,n),this.setLocalAudioStream();let r=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Resume,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,holdType:S4.Standard},networkInfo:L7.getRemoveCauseIdToNetworkInfo(n)})}catch{let r=+new Date,i=new Y({defaultError:J.CALL.RESUME_CALL});throw this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Resume,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:r-e},additionalDetails:{failureReason:i.message,code:i.code,subCode:i.subCode,holdType:S4.Standard,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...J3(i)},networkInfo:L7.getRemoveCauseIdToNetworkInfo(n)}),i}}async startScreenSharing(e){let t=this.logger.createFnLogger(c4.StartScreenShare),n=+new Date,r=J0(),i=FG(r),a=this.createVideoNegotiationTag(r,`ScreenSharing`);try{if(this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.attempt,timestampInfo:``,isVideoOn:this._isLocalVideoStarted,localVideoStream:e,additionalDetails:{negotiationTag:a,causeId:i}}),this.tsCall.state!==3)throw new Y({defaultError:J.CALL.START_SS_CALL_NOT_CONNECTED});if(this.tsCall.isScreenSharingOn)throw new Y({defaultError:J.CALL.SS_ALREADY_ON});if(this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()){let e=`screen sharing cannot be started as consent is required to be recorded or transcribed`;throw t.error(e),new Y({defaultError:J.CALL.SCREENSHARE_CONSENT_RESTRICTED,originalError:e})}if(e){if(!(e instanceof X6))throw new Y({defaultError:J.CALL.SS_RAW_STREAM_IS_NOT_LVS});if(e.mediaStreamType!==`RawMedia`)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_LVS_IS_NOT_RAW_MEDIA});let t=await e.getMediaStream();if(!t||t.getVideoTracks().length===0)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_IS_NOT_VALID_STREAM});if(!1===t.active)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_IS_NOT_ACTIVE_STREAM});t.getTracks().forEach((e=>{e.stop()})),await this._setRawStream(e,2),this.localScreenSharingStream=e}else this.localScreenSharingStream=new X6(new z6(swe.ScreenSharing,J0(),swe.ScreenSharing,this._callAgent.deviceManager))}catch(e){let t=+new Date;this.removeScreenSharingStream();let o=new Y({defaultError:J.CALL.START_SS,originalError:e});throw this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:t-n},additionalDetails:{failureReason:o.message,code:o.code,subCode:o.subCode,...J3(o),negotiationTag:a,causeId:i},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),o}return this.tsCall.startScreenSharing(void 0,void 0,a).then((()=>{let e=+new Date;this.localScreenSharingStream&&this._localVideoStreams.indexOf(this.localScreenSharingStream)===-1&&(this.localScreenSharingStream.addCall(this),this._localVideoStreams.push(this.localScreenSharingStream),this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[this.localScreenSharingStream],removed:[]})),this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:e-n},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream,additionalDetails:{negotiationTag:a,causeId:i}})})).catch((e=>{let o=+new Date;this.removeScreenSharingStream();let s=G3(t,e);throw this.sendScreenShareEvent({eventName:Q.acs_calling_start_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{failureReason:s.message,code:s.code,subCode:s.subCode,...J3(s),negotiationTag:a,causeId:i},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),s}))}async stopScreenSharing(){let e=this.logger.createFnLogger(c4.StopScreenShare),t=+new Date,n=J0(),r=FG(n),i=this.createVideoNegotiationTag(n,`ScreenSharing`);if(this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.attempt,timestampInfo:``,isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream,additionalDetails:{negotiationTag:i,causeId:r}}),this.tsCall.state!==3)throw new Y({defaultError:J.CALL.STOP_SS_CALL_NOT_CONNECTED});if(!this.tsCall.isScreenSharingOn){let e=+new Date,a=new Y({defaultError:J.CALL.SS_ALREADY_OFF});throw this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:e-t},additionalDetails:{failureReason:a.message,code:a.code,subCode:a.subCode,...J3(a),negotiationTag:i,causeId:r},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),a}return this.tsCall.stopScreenSharing(void 0,i).then((()=>{let e=+new Date,a=e4.cloneDeep(this.localScreenSharingStream);this.removeScreenSharingStream(),this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:e-t},isVideoOn:this._isLocalVideoStarted,localVideoStream:a,additionalDetails:{negotiationTag:i,causeId:r}})})).catch((a=>{let o=+new Date,s=G3(e,a,!0),c=typeof s?.message==`string`?s?.message:void 0;throw this.sendScreenShareEvent({eventName:Q.acs_calling_stop_screen_share,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:o-t},additionalDetails:{failureReason:c||``,code:s.code,subCode:s.subCode,...J3(s),negotiationTag:i,causeId:r},isVideoOn:this._isLocalVideoStarted,localVideoStream:this.localScreenSharingStream}),s}))}async setConstraints(e){let t=+new Date,n=J0();try{let r=await this._mediaConstraintsManager.setVideoConstraints(e?.video,`mid-call`,n,t);this.logger.info(`Video constraints set - ${JSON.stringify(r)}`)}catch(e){throw new Y({defaultError:J.CALL.SET_VIDEO_CONSTRAINTS,originalError:e})}}on(e,t){if(e!==`stateChanged`&&e!==`idChanged`&&e!==`isMutedChanged`&&e!==`isIncomingAudioMutedChanged`&&e!==`isScreenSharingOnChanged`&&e!==`isLocalVideoStartedChanged`&&e!==`remoteParticipantsUpdated`&&e!==`localVideoStreamsUpdated`&&e!==`localAudioStreamsUpdated`&&e!==`remoteAudioStreamsUpdated`&&e!==`totalParticipantCountChanged`&&e!==`roleChanged`&&e!==`mutedByOthers`&&e!==`callerInfoChanged`&&e!==`transferorInfoChanged`)throw new Y({defaultError:J.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`stateChanged`&&e!==`idChanged`&&e!==`isMutedChanged`&&e!=`isIncomingAudioMutedChanged`&&e!==`isScreenSharingOnChanged`&&e!==`isLocalVideoStartedChanged`&&e!==`remoteParticipantsUpdated`&&e!==`localVideoStreamsUpdated`&&e!==`localAudioStreamsUpdated`&&e!==`remoteAudioStreamsUpdated`&&e!==`totalParticipantCountChanged`&&e!==`roleChanged`&&e!==`mutedByOthers`&&e!==`callerInfoChanged`&&e!==`transferorInfoChanged`)throw new Y({defaultError:J.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}onMeetingCapabilitiesChanged(e,t){if(e!==`meetingCapabilitiesChanged`)throw new Y({defaultError:J.CALL.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}offMeetingCapabilitiesChanged(e,t){if(e!=`meetingCapabilitiesChanged`)throw new Y({defaultError:J.CALL.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}onParticipantCapabilitiesChanged(e,t){this.logger.log(`participant capabilities change event listener registered`),this._eventEmitter.on(e,t)}offParticipantCapabilitiesChanged(e,t){this.logger.log(`participant capabilities change event listener unregistered`),this._eventEmitter.off(e,t)}setWatermarkAudioOnlyFallbackTriggered(e){this._watermarkAudioOnlyFallbackTriggered=e,this._eventEmitter.emit(`watermarkAudioOnlyFallbackTriggeredChanged`)}onWatermarkAudioOnlyFallbackTriggeredChanged(e,t){this.logger.log(`watermark audio only fallback triggered listener registered`),this._eventEmitter.on(e,t)}offWatermarkAudioOnlyFallbackTriggeredChanged(e,t){this.logger.log(`watermark audio only fallback triggered listener unregistered`),this._eventEmitter.off(e,t)}setIsRenderingRemoteScreenShare(e){this.isRenderingRemoteScreenShare!==e&&(this.isRenderingRemoteScreenShare=e,this._eventEmitter.emit(`isRenderingRemoteScreenShareChanged`))}onIsRenderingRemoteScreenShareChanged(e,t){this._eventEmitter.on(e,t)}offIsRenderingRemoteScreenShareChanged(e,t){this._eventEmitter.off(e,t)}getOrCreateRemoteParticipant(e,t){let n=this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)));return n||(n=new M7(e,this.logger,this,this._callAgent,this._telemetryLogManager),this._remoteParticipants.push(n),this._mriToRemoteParticipantMap.set(K2(n.identifier),n)),t&&n.observeParticipant(t),n}deleteRemoteParticipant(e){let t=!0;return this._remoteParticipants.splice(this._remoteParticipants.indexOf(e),1).length!==1&&(this.logger.warn(`Deleted remote participant array is not 1`),t=!1),this._mriToRemoteParticipantMap.delete(K2(e.identifier))||(this.logger.warn(`Deleted remote participant was not found in mri-to-remoteparticipant map`),t=!1),t}sendCallOnHoldAndResumedEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send call hold or resume telemetry`)}}sendVideoEvent(e,t){try{let n,r;try{n=e.localVideoStream?.getStreamMetadata()}catch{this.logger.error(`Unable to get stream meta data on send video event`)}t&&(r=typeof t?.message==`string`?t?.message:void 0,(e.additionalDetails??{}).communicationServicesError=J3(t).communicationServicesError),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:{...n,callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||``,failureReason:r||``,isScreenSharingOnFlag:e.isScreenSharingOnFlag,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]}})}catch{this.logger.debug(`Unable to send video telemetry`)}}sendScreenShareEvent(e){let t;try{t=e.localVideoStream?.getStreamMetadata()}catch{this.logger.error(`Unable to get stream meta data on send video event`)}try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:{...t,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:e.correlationId,kindOfEvent:e.kindOfEvent,timestampInfo:e.timestampInfo,additionalDetails:e.additionalDetails,isVideoOn:e.isVideoOn}})}catch{this.logger.debug(`Unable to send screen share telemetry`)}}sendRawMediaEvent(e){let t={...e};t.localAudioStream=e.localAudioStream?.source instanceof MediaStream?`MediaStream`:`Device`;try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:t})}catch{this.logger.debug(`Unable to send raw media telemetry`)}}sendAudioEvent(e,t){try{let n;t&&(n=typeof t?.message==`string`?t?.message:void 0,e.additionalDetails={...J3(t)});let r={callId:this.id,localParticipantId:this.tsCall.participantId,timestampInfo:e.timestampInfo,correlationId:e.correlationId,step:e.step||``,failureReason:n||``,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]};e.eventType!==void 0&&(r.eventType=e.eventType),e.initiatedBySdk&&(r.initiatedBySdk=!0),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:r})}catch{this.logger.debug(`Unable to send audio telemetry`)}}sendCallStageEvent(e,t,n,r,i){try{let a,o=``;t&&(a=this?.tsCall?.callEndDiagnosticsInfo||n||{},o=t.message);let s=this._joinContextDescription===R2.RoomCall||this.kind===GG.Call&&this._direction===`Incoming`&&!this.tsCall.groupId&&!!this.tsCall.meetingData?.meetingCode&&!this.tsCall.threadId,c=!s&&this._joinContextDescription===R2.TeamsMeetingLink||this._joinContextDescription===R2.TeamsMeetingId||this._joinContextDescription===R2.TeamsCoordinates||this._direction==`Incoming`&&!this.tsCall.groupId&&!!this.tsCall.meetingData&&!!this.tsCall.threadId,l={localParticipantId:this?.tsCall?.participantId||``,callId:this?.tsCall?.callId||``,callType:this?.tsCall?.callType||``,callDirection:this._direction,failureReason:o,callEndDiagnosticsInfo:a,calleeIdentityType:this.getParticipantIdentityType(),groupJoin:!!this?.tsCall?.groupId,roomJoin:s,meetingJoin:c,hostRegion:this?.tsCall?.region||``,correlationId:e.correlationId,timestampInfo:e.timestampInfo,...e.additionalPayload,networkInfo:r||[],negotiationTag:e.additionalPayload?.additionalProperties.negotiationTag??``,causeId:e.additionalPayload?.additionalProperties.causeId??``};this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:l},void 0,i)}catch{}}getParticipantIdentityType(){if(this.tsCall?.participants.length>1)return G2.group;if(this.tsCall?.participants.length===0)return G2.unknown;let e=this.tsCall?.participants[0];return q2(e.id).kind}optimalVideoCountChanged(e,t){let n=this._optimalVideoCount,r=e||this.tsCall.optimalVideoCount,i=Z().telemetry.progressEvents.enableOvcChangedEvent;if(r&&n!==r&&i)try{P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`optimalVideoCount-changed`,previousOptimalVideoCount:n,newOptimalVideoCount:r,changeReason:t,currentNumberOfVideosRendered:this.activeRemoteVideoStreamViews?.size||0})}catch{this.logger.error(`Failed to send optimal video count change telemetry`)}finally{this._optimalVideoCount=r??1}}_sendNetworkChangedTelemetry(){try{let e=(e,t,n)=>{P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`network-changed`,trouterState:e,onLine:t,rdpState:n})};this._trouterStateChangedListener=t=>{e(t,navigator.onLine,this._mmrRdpConnectionManager.state)},this._callAgent.onTrouterStateChanged(this._trouterStateChangedListener),this._onlineListener=t=>{e(this._callAgent.getTrouterState(),!0,this._mmrRdpConnectionManager.state)},window.addEventListener(`online`,this._onlineListener),this._offlineListener=t=>{e(this._callAgent.getTrouterState(),!1,this._mmrRdpConnectionManager.state)},window.addEventListener(`offline`,this._offlineListener),this._mmrRdpConnectionManager.on(`stateChange`,(t=>{e(this._callAgent.getTrouterState(),!1,t)})),e(this._callAgent.getTrouterState(),navigator.onLine,this._mmrRdpConnectionManager.state)}catch{this.logger.warn(`Failed to subscribe to network changed`)}}_setupSelectedDeviceChangedTelemetry(){try{let e=e=>{P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`selectedDevice-changed`,selectedDeviceType:e.selectedDeviceType,oldDevice:e.oldDevice,newDevice:e.newDevice})};if(this._selectedDeviceManager){this._selectedDeviceManager.on(`selectedDeviceChanged`,e);let t=this._selectedDeviceManager.selectedDevice(`Speaker`),n=this._selectedDeviceManager.selectedDevice(`Microphone`);e({selectedDeviceType:`Speaker`,oldDevice:void 0,newDevice:t}),e({selectedDeviceType:`Microphone`,oldDevice:void 0,newDevice:n})}}catch{this.logger.warn(`Failed to subscribe to selectedDevice changed`)}}setLocalVideoStream(e){if(!this._callAgent.tsStack)throw new Y({defaultError:J.CALL.VIDEO_UNDEFINED_STACK});if(!this.localVideoStream&&e&&!this._localVideoStreams.find((t=>t===e))){this.localVideoStream=e,this._localVideoStreams.push(this.localVideoStream),this.localVideoStream.mediaStreamType!==`RawMedia`&&this._callAgent.tsStack.getDeviceManager()?.selectDevices({camera:e.source.id}),this.localVideoStream.addCall(this);try{this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[this.localVideoStream],removed:[]})}catch{this.logger.warn(`Application threw on emit localVideoStreamsUpdated added`)}this.logger.log(`isLocalVideoStarted changed=true`),this._isLocalVideoStarted=!0,this._eventEmitter.emit(`isLocalVideoStartedChanged`)}}removeLocalVideoStream(e){if(this.localVideoStream&&e===this.localVideoStream&&this.localVideoStreams.find((e=>e===this.localVideoStream))){if(this.logger.log(`Attempting to remove local video stream`),this._localVideoStreams.splice(this._localVideoStreams.indexOf(this.localVideoStream),1).length===0)return void this.logger.warn(`Stream not found, failed to remove stream from localVideoStreams collection`);this.logger.log(`Local video stream removed successfully`),this.localVideoStream.removeCall(this),this.localVideoStream.autoDisposeOnCallEnd&&this.localVideoStream.dispose();let e=this.localVideoStream;this.localVideoStream=void 0;try{this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[],removed:[e]})}catch{this.logger.warn(`Application threw on emit localVideoStreamsUpdated removed`)}this.logger.log(`isLocalVideoStarted changed=false`),this._isLocalVideoStarted=!1,this._eventEmitter.emit(`isLocalVideoStartedChanged`)}}setLocalAudioStream(e){if(!this._callAgent.tsStack)throw new Y({defaultError:J.CALL.LOCAL_AUDIO_UNDEFINED_STACK});if(e)e.on(`audioSourceChanged`,this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]});else if(this._localAudioStreams.length===0){if(this._userProvidedLocalAudioStreamCache)return(e=this._userProvidedLocalAudioStreamCache).on(`audioSourceChanged`,this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),void this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]});let t=this.deviceManager?.selectedMicrophone;if(t){let e=new f8(t);e.on(`audioSourceChanged`,this.audioSourceChanged),this._localAudioStreams.push(e),e.addCall(this),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]})}else this.logger.warn(`Could not get current selected microphone to update localAudioStreams collection`)}else this.logger.warn(`No localAudioStream provided and the collection is not empty, doing nothing`)}removeLocalAudioStream(e){if(e){if(this.logger.log(`Attempting to remove local audio stream`),e.off(`audioSourceChanged`,this.audioSourceChanged),e.autoDisposeOnCallEnd&&e.dispose(),this._localAudioStreams.splice(this._localAudioStreams.indexOf(e),1).length===0)return void this.logger.warn(`Stream not found, failed to remove stream from localAudioStreams collection`);e.removeCall(this),this.logger.log(`Local audio stream removed successfully`),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[e]})}}_handleAudioEffectsOperations(){try{let e=this._localAudioStreams?.[0];if(!e)return void this.logger.debug(`No LocalAudioStream found in the call, cannot handle call audio effects operations`);this._audioEffectsStatsListener=e=>{this._audioEffectsProcessorStats=e},e.feature($5.AudioEffects)?.on(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener)}catch(e){this.logger.warn(`Error handling audio effects operations during call start: ${e}`)}}isAudioPermitted(){return!!this.feature($5.MediaAccess)?.getLocalParticipantMediaAccess().isAudioPermitted}isVideoPermitted(){return!!this.feature($5.MediaAccess)?.getLocalParticipantMediaAccess().isVideoPermitted}removeScreenSharingStream(){if(this.localScreenSharingStream&&this.localVideoStreams.find((e=>e===this.localScreenSharingStream))){if(Z()?.calling?.allowAccessRawMediaStream&&this.localScreenSharingStream?.mediaStreamType===`RawMedia`){let e=this._callAgent.tsStack?.getDeviceManager();e?.unsetRawMediaStream&&e.unsetRawMediaStream(2)}this.localScreenSharingStream.dispose(),this.localScreenSharingStream.removeCall(this);let e=this._localVideoStreams.indexOf(this.localScreenSharingStream);this._localVideoStreams.splice(e,1);let t=this.localScreenSharingStream;this.localScreenSharingStream=void 0,this._isScreenSharingOn=!1,this._eventEmitter.emit(`localVideoStreamsUpdated`,{added:[],removed:[t]})}}mapTsCallState(e){let t=$Ee[e];switch(t){case`Unknown`:case void 0:this.logger.log(`Ignored tsCall state \`${e}\``);break;case`Disconnected`:{this._callEndReason=U3(this).callEndReason,this._remoteParticipants.forEach((e=>{e.setCallEndReason(W3(this,e.tsRemoteParticipant).callEndReason),e.setParticipantState(`Disconnected`)}));let n=this._remoteParticipants.map((e=>e));this._remoteParticipants=[],this._mriToRemoteParticipantMap.clear(),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:n}),this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream),this.localAudioStreams[0]&&this.removeLocalAudioStream(this.localAudioStreams[0]),this._rawAudioStreamChangedSubscription?.dispose&&this._rawAudioStreamChangedSubscription.dispose(),Z().calling.allowAccessRawMediaStream&&this.remoteAudioStreams[0]&&this.removeRemoteAudioStream(this.remoteAudioStreams[0]),this._userProvidedLocalAudioStreamCache=void 0,this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._setCallState(t),this._telemetryLogManager.flushAllEvents(this.id).then((()=>{this.logger.log(`Telemetry flushed`)})).catch((e=>{this.logger.warn(`Failed to flush telemetry log manager events`)}));break}case`Connected`:this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._remoteParticipantsChangedListeners.forEach((e=>{e.dispose()})),this._setCallState(t),this._setOrUpdateDeviceEventsTask=this._setOrUpdateDeviceEventsTask.then((()=>this.setOrUpdateMediaMetricsDeviceEvents().catch(M4))),Z().calling.allowAccessRawMediaStream&&this.subscribeToGetRemoteAudioStream();break;case`Incoming Call`:{this.logger.log(`state changed from ${this._state} to 'Incoming Call'`);let e=new I7(this.tsCall,{config:this._config});P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`state-changed`,oldState:this._state,newState:`Incoming Call`,callTypeInfo:{initiatorKind:e.initiatorKind,targetKind:e.targetKind,transferor:e.transferorKind,context:e.context,callScenario:e.callScenario,direction:e.direction},teamsMeetingTenantId:this._teamsMeetingTenantId||``,teamsMeetingThreadId:this._teamsMeetingThreadId||``,callDurationInSeconds:this.tsCall.callStartedAt?Math.floor((Date.now()-this.tsCall.callStartedAt?.getTime())/1e3):-1});break}default:this.logger.log(`Mapped tsCall state:${e} to ${t}`),this._setCallState(t)}}shallStopVideo(e){let t=Z()?.calling?.deviceNotFunctioningMuted,n=Z()?.calling?.deviceCaptureMutedVideo,r=Z()?.calling?.preventStopVideo,i=e.type===25&&e.value===3,a=i&&e.mediaType===1,o=e.type===33&&e.value===3,s=r8(),c=i8()===`ios`&&s.engine===`Safari`,l=i8()===`android`,u=this.tsCall.state===3;return r?u&&this.tsCall.isVideoOn&&o:t&&u&&this.tsCall.isVideoOn&&(o||c&&i||n&&l&&a)}shallRemoveLocalVideoStreamOnBadUfd(e){let t=this.tsCall.localMediaStreams.find((e=>e.mediaType===1)),n=e.mediaType===1&&e.value===3&&e.type===25,r=this.tsCall.state==4||this.tsCall.state===5;if(r8().formFactor===`Mobile`&&(n||document.visibilityState==`hidden`)&&this.localVideoStream&&r&&!t||!Z()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return!1;let i=this.tsCall.state===3;return e.mediaType===1&&e.value===3&&(e.type===33||e.type===25||e.type===34)&&!!this.localVideoStream&&!i&&!t}shallStopAudio(e){let t=Z()?.calling?.deviceNotFunctioningMuted,n=Z()?.calling?.osAutoRecoverAudio,r=e.type===25&&e.value===3&&e.mediaType===0,i=e.type===9&&e.value===3,a=r8(),o=i8()===`ios`&&a.engine===`Safari`,s=this.tsCall.state===3;return n?t&&s&&i:t&&!this._isDeviceNotFunctioningMuted&&s&&(i||o&&r)}markCallMuted(){this._isDeviceNotFunctioningMuted=!0,this._handleMuteChanges()}audioDidAutoRecover(e){let t=Z()?.calling?.deviceCaptureMuteRecover&&!Z()?.calling?.preventFakeMute,n=e.type===25&&e.value===1&&e.mediaType===0,r=this.tsCall.state===3,i=r8(),a=i8()===`ios`&&i.engine===`Safari`,o=e.type===9&&e.value===1;return t&&this._isDeviceNotFunctioningMuted&&r&&(o||a&&n)}sendParticipantAddedOrRemovedEvent(e){try{this._telemetryLogManager.sendEvent({name:Q.acs_calling_participant_added_or_removed,tenant:p2,properties:{callId:this.id,remotePerticipantId:Array.isArray(e?.remoteParticipantIds)?e?.remoteParticipantIds.slice(0,Z().telemetry.maxExistingReportedParticipants):[],participantAddedOrRemoved:e.participantAddedOrRemoved,localParticipantId:this.tsCall.participantId,kindOfEvent:e.kindOfEvent,correlationId:e.correlationId||``,timestampInfo:e.timestampInfo||``,additionalDetails:e.additionalDetails||{},networkInfo:e.networkInfo||[]}})}catch{this.logger.debug(`Unable to send participant added or removed telemtery`)}}_handleLocalRingingCallState(e){this._state===`Connected`||this._direction!==`Outgoing`||this._localRingingStateSet||this._remoteParticipantsChangedListeners.push(e.changed((()=>{e.state!==2||this._state===`Connected`||this._localRingingStateSet||(this._setCallState(`Ringing`),this._localRingingStateSet=!0,this._remoteParticipantsChangedListeners.forEach((e=>{e.dispose()})))})))}_setCallState(e){if(e!==this._state){let t=this._state,n=e,r=new I7(this.tsCall,{config:this._config});this.logger.log(`state changed from ${t} to ${n}`),this._state=n,n===`Connected`&&(this._connectedTimestamp=Date.now()),this._eventEmitter.emit(`stateChanged`),P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`state-changed`,oldState:t,newState:n,callTypeInfo:{initiatorKind:r.initiatorKind,targetKind:r.targetKind,transferor:r.transferorKind,context:r.context,callScenario:r.callScenario,direction:r.direction},teamsMeetingTenantId:this._teamsMeetingTenantId||``,teamsMeetingThreadId:this._teamsMeetingThreadId||``,callDurationInSeconds:this.tsCall.callStartedAt?Math.floor((Date.now()-this.tsCall.callStartedAt?.getTime())/1e3):-1,additionalDetails:this._state===`Disconnected`&&this._callEndReason?{...Y3(this._callEndReason)}:void 0})}}_setCallRole(e){if(e!==this._lastTsCallAdvancedMeetingRole){let t=iTe(Z(),e);t===E2?this.logger.log(`tsParticipant advancedMeetingRole=${this._role} had no mapping`):this.logger.log(`mapped tsParticipant advancedMeetingRole=${e}=>${t}`),P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`role-changed`,oldAcsRole:this._role,newAcsRole:t,serviceRole:e||``}),this._role!=t&&(this.logger.log(`self-role changed ${this._role}=>${e}`),this._role=t,this._lastTsCallAdvancedMeetingRole=e,this._capabilityResolver.resolveCapabilitiesBasedOnRole(),this._eventEmitter.emit(`roleChanged`))}}_setMeetingCapabilities(e){oTe(e,this._lastTsCallMeetingDetails)&&(P7(this._telemetryLogManager,this.logger,{...N7(this,this._callAgent,J0(),this._joinContextDescription),step:`meetingCapabilities-changed`,oldMeetingDetails:this._lastTsCallMeetingDetails,newMeetingDetails:e}),this.logger.log(`Core Meeting Capabilities has changed to: ${JSON.stringify(e)}`),this._capabilityResolver.resolveCapabilitiesBasedOnMeetingCapabilities(),this._eventEmitter.emit(`meetingCapabilitiesChanged`)),Object.assign(this._lastTsCallMeetingDetails,e)}removeRemoteAudioStream(e){if(e){if(this.logger.log(`Attempting to remove remote audio stream`),this._remoteAudioStreams.splice(this._remoteAudioStreams.indexOf(e),1).length===0)return void this.logger.warn(`Stream not found, failed to remove stream from remoteAudioStreams collection`);this.logger.log(`remote audio stream removed successfully`),this._eventEmitter.emit(`remoteAudioStreamsUpdated`,{added:[],removed:[e]})}}async setOrUpdateMediaMetricsDeviceEvents(){if(Z().calling.mediaMetricsDeviceEventsEnabled)try{let e=await this.tsCall.getMediaSessionStatsAsync?.();if(e?.metrics?.DeviceEvents!==void 0){let t=JSON.parse(e.metrics.DeviceEvents),n=rTe(this._mediaMetricsDeviceEvents||{},t);n.length>0&&(this._mediaMetricsDeviceEvents=t,this.stats.recordEvent({name:l3.media_metrics_device_events,callId:this.id,localParticipantId:this.tsCall.participantId,data:{metricsDeviceEvents:n||{},metricsDevicesChangeCount:t?.metrics_DevicesChangeCount||0,metricsDevicesCount:t?.metrics_DevicesCount||{}}}))}else this.logger.info(`Failed to set media metrics device events telemetry: no valid events data`)}catch{this.logger.error(`Failed to set media metrics device events telemetry`)}}setClientCallStartOptions(e){let t={},n=0;return e?.firstPartyOptions?.isImmersiveMode&&(n|=32768),e?.firstPartyOptions?.accessToImmersiveEvents&&(n|=2097152),Z()?.calling?.supportLiveStreaming&&(n|=32),Z()?.calling.sharedLineAppearance.enabled&&(n|=128),Z()?.reaction?.enableReactionsThroughNGC&&(n|=524288),this._allowBreakoutRoomJoin&&(n|=4098),n>0&&(t.clientEndpointCapabilities=n),t.sendMediaModalities=this.setMediaModalities(e?.mediaModalities),t}setMediaModalities(e){if(e){let t={mediaStates:[]};return e.audio&&t.mediaStates.push({mediaType:0}),e.video?t.mediaStates.push({mediaType:1}):t.mediaStates.push({mediaType:1,isDisabled:!0}),e.screenShare||t.mediaStates.push({mediaType:2,isDisabled:!0}),t}}getLocalVideoStreamFromCallOptions(e){let t;if(Array.isArray(e?.videoOptions?.localVideoStreams)){if(e?.videoOptions?.localVideoStreams.length!==1)throw new Y({defaultError:J.CALL.ONLY_SINGLE_VIDEO_STREAM});if(t=e?.videoOptions?.localVideoStreams[0],!(t instanceof X6))throw new Y({defaultError:J.CALL.NOT_INSTANCE_OF_LVS})}return t}getLocalAudioStreamFromCallOptions(e){let t;if(Array.isArray(e?.audioOptions?.localAudioStreams)){if(e?.audioOptions?.localAudioStreams.length!==1)throw new Y({defaultError:J.CALL.ONLY_SINGLE_AUDIO_STREAM});if(t=e?.audioOptions?.localAudioStreams[0],!(t instanceof f8))throw new Y({defaultError:J.CALL.NOT_INSTANCE_OF_LAS})}return t&&(this._userProvidedLocalAudioStreamCache=t),t}async _setRawStream(e,t){if(!Z().calling.allowAccessRawMediaStream)throw new Y({defaultError:J.CALL.ACCESS_RAW_MEDIA_STREAM_DISABLED});let n=await this._callAgent.tsStack?.getDeviceManagerAsync?.();if(!n?.setRawMediaStream)throw new Y({defaultError:J.CALL.ACCESS_RAW_MEDIA_STREAM_UNDEFINED_FUNC});try{let r=await e.getMediaStream();if(!r)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_UNDEFINED});n.setRawMediaStream(r,t)}catch(e){if(t===1)throw new Y({defaultError:J.CALL.VIDEO_SET_MEDIA_STREAM,originalError:e});if(t===2)throw new Y({defaultError:J.CALL.SS_RAW_STREAM_SET,originalError:e})}}shallRemoveLvsAfterConnectedSuccessfully(e,t,n,r,i,a,o){if(this.tsCall.localMediaStreams.find((e=>e.mediaType===1)))this.sendVideoEvent({correlationId:n,eventName:Q.acs_calling_start_video_success,timestampInfo:{deltaTimeInMs:r-i},localVideoStream:e,step:t,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:o}});else{if(!Z()?.calling?.removeLvsCheckOnCallStartAndCallAccept)return;this.localVideoStream&&this.removeLocalVideoStream(this.localVideoStream);let r=+new Date,s=new Y({defaultError:J.CALL.VIDEO_FAILED_TO_START,defaultErrorMessageArgs:[t]});this.logger.error(s.message),this.sendVideoEvent({correlationId:n,eventName:Q.acs_calling_start_video_failure,timestampInfo:{deltaTimeInMs:r-i},localVideoStream:e,step:t,isScreenSharingOnFlag:this._isScreenSharingOn,additionalDetails:{negotiationTag:a,causeId:o}},s)}}shallRemoveLasAfterConnectedSuccessfully(e,t,n,r,i){if(this.tsCall.localMediaStreams.find((e=>e.mediaType===0)))this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,kindOfEvent:$.success,localAudioStream:e,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:``});else{if(!Z().calling.removeLocalAudioStreamCheckOnCallStartAndCallAccept)return;this.removeLocalAudioStream(this.localAudioStreams[0]);let r=+new Date;this.logger.error(`Removing local audio stream because audio failed to start during call-${t} process.`);let a=new Y({defaultError:J.CALL.AUDIO_FAILED_TO_START,defaultErrorMessageArgs:[t]});this.sendRawMediaEvent({eventName:Q.acs_calling_start_audio_stream_track,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:n,localAudioStream:e,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:r-i},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...J3(a)}})}}createVideoNegotiationTag(t,n){let r=0,i=``;return n===`Video`?(r=++e.videoId,i=`v`):(r=++e.screenShareVideoId,i=`ss`),`${t};${i}_${r}`}_enableOrDisable_largeMeeting_videoRendering(){try{!this._isHandlingLargeMeetingVideoRendering&&this._totalParticipantCount-1>=Z().rendering.remoteVideo.largeMeeting.participantCountThreshold?(this._isHandlingLargeMeetingVideoRendering=!0,this._internalDominantSpeakersListener=new VDe(new w6(this.logger.createChild((()=>`DominanSpeakersFeatureInternal:: Call(id=${this.tsCall.callId})`)))),this._internalDominantSpeakersListener.initialize(this.tsCall,this._callAgent,this._telemetryLogManager,this.logger,!0),this.logger.info(`Initialized internal dominant speakers listener`),this._internalDominantSpeakersListener.on(`dominantSpeakersChanged`,(()=>{this.handleDominantSpeakersVideos()})),this.handleDominantSpeakersVideos(),this.logger.info(`Initialized large meeting video rendering handler`)):this._isHandlingLargeMeetingVideoRendering&&(this._totalParticipantCount-1>=Z().rendering.remoteVideo.largeMeeting.participantCountThreshold?this.handleDominantSpeakersVideos():(this._isHandlingLargeMeetingVideoRendering=!1,this._internalDominantSpeakersListener?.dispose(),this._internalDominantSpeakersListener=void 0,this.logger.info(`Disposed of internal dominant speakers listener`),this.remoteParticipants.forEach((e=>{e.videoStreams.forEach((e=>{e.setIsAvailable(e.tsStream.isAvailable)}))})),this.logger.info(`All remote streams isAvailable flags were reset`),this.logger.info(`Disposed large meeting video rendering handler`)))}catch(e){this.logger.error(`Failed to handle large meeting video rendering`,e)}}async handleConsentCapabilitiesChanges(){this.explicitConsentStateImp.areCoreCapabilitiesConsentRestricted()&&(this.isMuted||this.mute().then((()=>{this.logger.log(`ExplicitConsentCallStateManager: Handle Capabilities changes: Mic is turned off :`,this.isMuted)})).catch((e=>{this.logger.error(`ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping mic`,e)})),this.isLocalVideoStarted&&this.localVideoStream&&this.stopVideo(this.localVideoStream).then((()=>{this.logger.log(`ExplicitConsentCallStateManager: Handle Capabilities changes: Video is turned off :`,this.isLocalVideoStarted)})).catch((e=>{this.logger.error(`ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping video`,e)})),this.isScreenSharingOn&&this.stopScreenSharing().then((()=>{this.logger.log(`ExplicitConsentCallStateManager: Handle Capabilities changes: Screenshare is turned off :`,this.isScreenSharingOn)})).catch((e=>{this.logger.error(`ExplicitConsentCallStateManager: Handle Capabilities changes: Error stopping screenshare`,e)})))}handleDominantSpeakersVideos(){this.logger.info(`Dominant speakers changed during large meeting`);let e=this.getTopNDominantSpeakersWithVideoOn();this.logger.info(`There are currently ${e.length} top-n speakers with video on in the large meeting`),e.forEach((e=>{e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).forEach((e=>{e.setIsAvailable(e.tsStream.isAvailable)}))})),this._remoteParticipants.filter((t=>!e.includes(t))).forEach((e=>{e.videoStreams.filter((e=>e.mediaStreamType===`Video`)).forEach((e=>{try{e.setIsAvailable(!1)}catch(e){let t=new Y({defaultError:J.CALL.LARGE_MEETING_FORCE_ISAVAILABLE,originalError:e});this.logger.warn(t.message)}let t=this.activeRemoteVideoStreamViews.get(e.id);t&&t.forEach((e=>{try{e.disposed||(e.dispose(S3.Internal_LargeMeetingVideoRendering),this.logger.info(`Successfully disposed of view during large meeting`))}catch(e){let t=new Y({defaultError:J.CALL.LARGE_MEETING_DISPOSE_VIEW,originalError:e});this.logger.warn(t.message)}}))}))}))}};B7.videoId=0,B7.screenShareVideoId=0,R7([UG,z7(`design:type`,Object)],B7.prototype,`logger`,void 0),R7([JG(c4.BindToCall),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Array)],B7.prototype,`bindTsCall`,null),R7([JG(c4.Feature),z7(`design:type`,Function),z7(`design:paramtypes`,[Object]),z7(`design:returntype`,typeof(tLe=typeof TFeature<`u`&&TFeature)==`function`?tLe:Object)],B7.prototype,`feature`,null),R7([YG(c4.HangUp),z7(`design:type`,Function),z7(`design:paramtypes`,[Object]),z7(`design:returntype`,Promise)],B7.prototype,`hangUp`,null),R7([YG(c4.Mute),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`mute`,null),R7([YG(c4.Unmute),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`unmute`,null),R7([YG(c4.MuteAllRemoteParticipants),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`muteAllRemoteParticipants`,null),R7([YG(c4.MuteIncomingAudio),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`muteIncomingAudio`,null),R7([YG(c4.UnmuteIncomingAudio),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`unmuteIncomingAudio`,null),R7([YG(c4.SendDtmf),z7(`design:type`,Function),z7(`design:paramtypes`,[String]),z7(`design:returntype`,Promise)],B7.prototype,`sendDtmf`,null),R7([YG(c4.StartVideo),z7(`design:type`,Function),z7(`design:paramtypes`,[X6]),z7(`design:returntype`,Promise)],B7.prototype,`startVideo`,null),R7([YG(c4.StopVideo),z7(`design:type`,Function),z7(`design:paramtypes`,[X6]),z7(`design:returntype`,Promise)],B7.prototype,`stopVideo`,null),R7([YG(c4.StartAudio),z7(`design:type`,Function),z7(`design:paramtypes`,[f8]),z7(`design:returntype`,Promise)],B7.prototype,`startAudio`,null),R7([XG(c4.Hold),YG(c4.Hold),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`hold`,null),R7([XG(c4.Resume),YG(c4.Resume),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`resume`,null),R7([YG(c4.StartScreenShare),z7(`design:type`,Function),z7(`design:paramtypes`,[X6]),z7(`design:returntype`,Promise)],B7.prototype,`startScreenSharing`,null),R7([YG(c4.StopScreenShare),z7(`design:type`,Function),z7(`design:paramtypes`,[]),z7(`design:returntype`,Promise)],B7.prototype,`stopScreenSharing`,null),R7([YG(c4.SetConstraints),z7(`design:type`,Function),z7(`design:paramtypes`,[Object]),z7(`design:returntype`,Promise)],B7.prototype,`setConstraints`,null);var nLe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},V7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},H7=class extends B7{get info(){return this._info}constructor(e,t,n,r,i){super(e,t,n,r,GG.Call,i),this._info=this.callInfo,this._allowBreakoutRoomJoin=Z().calling.breakoutRooms.enabled}dispose(){super.dispose(),this._extensibleApi.dispose()}addParticipant(e,t){let n,r,i=t,a=t,o=t,s=+new Date,c=J0();if(this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{attemptTimestamp:s},additionalDetails:{customContext:{userToUserPresent:!!i?.customContext?.userToUser,xHeadersPresent:!!i?.customContext?.xHeaders&&i?.customContext.xHeaders.length>0}}}),this._callAgent.isEnterpriseUser())switch(this.validateThreadId(e,t),OG(e).kind){case`communicationUser`:r=i.threadId;break;case`microsoftTeamsUser`:r=o.threadId;break;case`phoneNumber`:r=a.threadId;break;default:{let e=new Y({defaultError:J.CALL.ADD_UNKNOWN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:e.code,failureReason:e.message,...J3(e)}}),e}}let l;a?.alternateCallerId&&(Y2(a.alternateCallerId),n=K2(a.alternateCallerId));try{if(t7(c4.AddParticipant,this.state),l=Y2(e),!B4(this.acsProxy,this.acsCustomRelayManager,!1,l))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}catch(e){throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:e.code,failureReason:e.message,...J3(e)}}),e}if(this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)))){let t=new Y({defaultError:J.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[OG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:t.code,failureReason:t.message,...J3(t)}}),t}let u=[...this.remoteParticipants.values()].map((e=>e.identifier));this._isAcsTeamsCall=V4([...u,e],this._callAgent.kind),Z().calling.enableSmePassFakeConversation&&this._isAcsTeamsCall&&!r&&(r=this.tsCall.threadId||H4());let d=sTe(lTe(this),OG(e));Z().calling.enableOpsSmePassFakeConversation&&d&&!r&&(r=this.tsCall.threadId||H4());let f=PG();L6.setCauseIdToNetworkInfo(f);let p=this.getOrCreateRemoteParticipant(q2(K2(e)));return this.tsCall.addParticipant(K2(e),{alternateId:n,threadId:r,customHeaderContext:U4(a)},f).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},networkInfo:L6.getRemoveCauseIdToNetworkInfo(f)})})).catch((t=>{let{callEndReason:n}=W3(this,p.tsRemoteParticipant,t);p.callEndReason||p.setCallEndReason(n);let r=Y3(n);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:c,timestampInfo:{deltaTimeInMs:+new Date-s},additionalDetails:{code:r?.callEndReason.code,subCode:r?.callEndReason.subCode,failureReason:r?.callEndReason.message,...r},networkInfo:L6.getRemoveCauseIdToNetworkInfo(f)}),this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)))&&(this.deleteRemoteParticipant(p),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:[p]}))})),p}async removeParticipant(e,t){let n=+new Date,r=J0();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{attemptTimestamp:n}});try{t7(c4.RemoveParticipant,this.state),Y2(e)}catch(e){let t=new Y({defaultError:J.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...J3(t)}}),t}let i=this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)));if(!i){let t=new Y({defaultError:J.CALL.PARTICIPANT_NOT_IN_CALL,defaultErrorMessageArgs:[OG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:t.code,subCode:t.subCode,failureReason:t.message,...J3(t)}}),t}let a=PG();L6.setCauseIdToNetworkInfo(a);try{await this.tsCall.removeParticipant(K2(e)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},networkInfo:L6.getRemoveCauseIdToNetworkInfo(a)})}catch(e){let t=W3(this,i.tsRemoteParticipant,e).callEndReason;i.callEndReason||i.setCallEndReason(t);let o=Y3(t);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:o?.callEndReason.code,subCode:o?.callEndReason.subCode,failureReason:o?.callEndReason.message,...o},networkInfo:L6.getRemoveCauseIdToNetworkInfo(a)}),new Y({defaultError:{message:t.message,code:t.code,subCode:t.subCode||0,resultCategories:t.resultCategories},originalError:e})}}validateThreadId(e,t){if(!t?.threadId)throw new Y({defaultError:J.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID})}};nLe([JG(c4.AddParticipant),V7(`design:type`,Function),V7(`design:paramtypes`,[Object,Object]),V7(`design:returntype`,Object)],H7.prototype,`addParticipant`,null),nLe([YG(c4.RemoveParticipant),V7(`design:type`,Function),V7(`design:paramtypes`,[Object,Object]),V7(`design:returntype`,Promise)],H7.prototype,`removeParticipant`,null);var rLe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},U7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},W7=class{get kind(){return this._kind}get id(){return this._callCommon.id}get callerInfo(){return this._callCommon.callerInfo}get transferorInfo(){return this._callCommon.transferorInfo}get callEndReason(){return this._callCommon.callEndReason}get customContext(){return this._customContext}constructor(e,t){this._callCommon=e,this._eventEmitter=new E3.EventEmitter,this._kind=t,this._callConnected=this._callCommon.state===`Connected`,this._customContext=fTe(this._callCommon.tsCall),this._callCommon.on(`stateChanged`,(()=>{this._callCommon.state===`Connected`?this._callConnected=!0:this._callCommon.state!==`Disconnected`||this._callConnected||this._eventEmitter.emit(`callEnded`,{callEndReason:this._callCommon.callEndReason})})),this._callCommon.on(`callerInfoChanged`,(()=>{this._eventEmitter.emit(`callerInfoChanged`)})),this._callCommon.on(`transferorInfoChanged`,(()=>{this._eventEmitter.emit(`transferorInfoChanged`)}))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}reject(){return this._callCommon.reject()}};rLe([YG(),U7(`design:type`,Function),U7(`design:paramtypes`,[]),U7(`design:returntype`,Promise)],W7.prototype,`reject`,null);var iLe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},G7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},aLe=class extends W7{get info(){return this._call.info}constructor(e){super(e,KG.IncomingCall),this._call=e}async accept(e){if(this.info?.initiatorKind===`microsoftTeamsUser`&&!B4(this._call.acsProxy,this._call.acsCustomRelayManager,!0))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._call.accept(e),this._call}};iLe([YG(c4.Accept),G7(`design:type`,Function),G7(`design:paramtypes`,[Object]),G7(`design:returntype`,Promise)],aLe.prototype,`accept`,null);var K7={callNotification:`callNotification`,conversationInvitation:`conversationInvitation`,debugContent:`debugContent`,groupContext:`groupContext`},oLe=class{get callId(){return this._callId}get localParticipantId(){return this._localParticipantId}constructor(e,t,n){if(this._callId=``,this._localParticipantId=``,this._logger=n.createChild(`IncomingCallPushNotificationHandler`),!e.incomingCallContext)throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD_NO_CONTEXT_PROVIDED});if(Object.keys(e).length>1)throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_PAYLOAD_TOO_MANY_KEYS});if(this._payload=e,this._incomingCallContext=this._payload.incomingCallContext,this._tsCallRegistry=t,this._gp=JSON.parse(t3.inflate(atob(this._incomingCallContext),{to:`string`})),!(this._gp.hasOwnProperty(K7.callNotification)&&this._gp.hasOwnProperty(K7.conversationInvitation)&&this._gp.hasOwnProperty(K7.debugContent)&&this._gp.hasOwnProperty(K7.groupContext)))throw this._logger.error(`Missing incoming call context data. Found: ${Object.keys(this._gp)}`),new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_INVALID_PAYLOAD});this._callId=this._gp.debugContent.callId,this._localParticipantId=this._gp.debugContent.participantId}async process(){try{if(this._tsCallRegistry.calls.some((e=>e.callId==this._callId)))throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_ALREADY_PROCESSED});let e=n3(),t=t=>{let n=()=>{t.callId===this._callId&&t.participantId===this._localParticipantId&&t.state===1&&e.resolve()};this._tsCallStateSub=t.on(`callStateChanged`,n),n()};this._tsCallRegistrySub=this._tsCallRegistry.on(`callAdded`,t);let n={eventId:ZCe,body:{gp:this._gp}};if(!this._tsCallRegistry.incomingCallMessageHandler.handleMessage(n))throw new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_FAILED_TO_PROCESS});setTimeout((()=>{e.isPending()&&e.reject(new Y({defaultError:J.CALL_AGENT.INCOMING_PUSH_NOTIFICATION_CALL_MISSED}))}),5e3),await e.promise}catch(e){throw e}finally{this._tsCallRegistrySub?.dispose(),this._tsCallStateSub?.dispose()}}},q7=0,sLe=220004,cLe=220005,lLe=220006,uLe=220007,dLe=class{constructor(e){this._httpRequestHelper=e,this._isPolicyFetchApplicable=!1,this._policySettingData={},this._threadIdData={};let t=ZW(`ACS`);this._logger=new V6(t)}initialize(e){this._localParticipant=e.localParticipant,this._jwtTokenProvider=e.jwtTokenProvider,this._telemetryLogManager=e.telemetryLogManager}userDialedNumber(e){this._userDialedPstnNumber=e,this._emergencyNumber=this._userDialedPstnNumber}async CreateChatThreadId(e,t){this._callId=e;let n=+new Date,r=t?.createThreadIdSuffix??Z().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix;this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.attempt});let i=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(),a=new URL(r,Z().MiddleTier.baseServiceUrl);t?.participants.push({id:this._localParticipant});let o={Participants:t?.participants};try{let e=await this._httpRequestHelper.send(a.toString(),o,{method:L3.POST,headers:i},Z().MiddleTier.maxRetry);if(this._threadIdData=await this._httpRequestHelper.extractPayload(e),!this._threadIdData)throw Error(`ThreadIdData is null or undefined`);return this._logger.info(`Successfully created chat thread using ACS MiddleTier Service.`),this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{phrase:`Thread Id was successfully created from ACS MiddleTier Service`,code:q7,subCode:lLe}}),Promise.resolve(this._threadIdData.threadId)}catch{this._logger.error(`Error creating thread Id from ACS MiddleTier Service`);let e=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...J3(e)}}),e}}async AddParticipantsToThread(e,t){this._callId=e;let n=+new Date,r=t?.addParticipantsSuffix??Z().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix;this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.attempt});let i=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(),a=new URL(r,Z().MiddleTier.baseServiceUrl),o={threadId:t?.threadId,Participants:t?.participants};try{let e=await this._httpRequestHelper.send(a.toString(),o,{method:L3.POST,headers:i},Z().MiddleTier.maxRetry),t=await this._httpRequestHelper.extractPayload(e);if(!t)throw Error(`AddParticipantToThreadResponseData is null or undefined`);if(this._logger.info(`Call to add participants to chat thread using ACS MiddleTier Service`),t!==null){if(!t.isSuccess)throw new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});t.multipleStatus.length>0&&t.multipleStatus[0].statusCode==735&&this._logger.info(`Trying to add the same participant to the thread id`)}return this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{phrase:`Successfully add participants from ACS MiddleTier Service`,code:q7,subCode:uLe}}),Promise.resolve(t.isSuccess)}catch{this._logger.error(`Fail to add participant error from ACS MiddleTier Service`);let e=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.ADD_PARTICIPANTS_TO_THREAD_FAILED});throw this.sendMiddleTierApiEvent({eventName:Q.acs_calling_middletier_gateway_api,suffix:r,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-n},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...J3(e)}}),e}}async fetchUserPoliciesFromAcsMiddleTier(e,t,n){this._policySettingData=await this.requestUserPoliciesFromAcsMiddleTier(e,t,n)}async requestUserPoliciesFromAcsMiddleTier(e,t,n,r){this._callId=e;let i=+new Date;if(this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.attempt},t),!t){let e=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMS_USER_ID_NOT_PROVIDED});throw this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-i},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...J3(e)}}),e}let a,o={},s=Z().MiddleTier.baseServiceUrl;n?(a=new URL(n.policyUrlSuffix,s),o={id:t,dialstring:this._userDialedPstnNumber,userPolicies:n.userPolicies,userProperties:n.userProperties}):(a=new URL(Z().MiddleTier.policyUrlSuffix,s),o={id:t});let c=await this.getAcsMiddletierServiceRequestHeaderForThreadApi(r);try{let e=await this._httpRequestHelper.send(a.toString(),o,{method:L3.POST,headers:c},Z().MiddleTier.maxRetry);this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-i},additionalDetails:{phrase:`Teams user policy was fetched successfully from ACS MiddleTier Service`,code:q7,subCode:sLe}},t);let n=await this._httpRequestHelper.extractPayload(e);if(!n)throw Error(`PolicySettingsData is null or undefined`);return n}catch(e){let n=iDe(e,J.CTE_MID_TIER_POLICY_SERVICE.FETCH_POLICY);throw this._logger.error(n.message),this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_policy,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-i},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...J3(n)}},t),n}}isEvEnabled(){return this._policySettingData?.userAggregatedPolicySettingData?.userProperties?.evEnabled||!1}isMoHEnabled(){let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsCallingPolicy?.musicOnHoldEnabledType;return this._logger.info(`Checking Music on Hold Policy, Enabled Type is: `+e),e===(x4.Enabled||x4.UserOverride)}isBreakoutRoomsAllowed(){let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy?.allowBreakoutRooms;return this._logger.info(`Allow Breakout rooms from Teams meeting policy is `+e),e??=!0,e}isIPAudioAllowed(){if(!Z().calling.mediaAccess.ipMediaPolicyEnabled)return this._logger.info(`Allow IP audio is true as feature flag ipAudioVideoPolicyEnabled is false`),!0;let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy?.ipAudioMode!==C4.Disabled;return this._logger.info(`Allow IP audio from Teams meeting policy is `+e),e}isIPVideoAllowed(){if(!Z().calling.mediaAccess.ipMediaPolicyEnabled)return this._logger.info(`Allow IP video is true as feature flag ipAudioVideoPolicyEnabled is false`),!0;let e=this._policySettingData?.userAggregatedPolicySettingData?.userPolicies?.teamsMeetingPolicy?.ipVideoMode!==C4.Disabled;return this._logger.info(`Allow IP video from Teams meeting policy is `+e),e}getTeamsUserCaptionsPoliciesData(){let e=+new Date,t=``;this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.attempt});let n=this._policySettingData.userAggregatedPolicySettingData,r=n?.userPolicies,i=n?.userProperties;if(!r?.teamsCallingPolicy){let t=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_CALLINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}})}if(!r?.teamsMeetingPolicy){let t=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_MEETINGPOLICY_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}})}if(!i?.featureTypes){let t=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.TEAMSUSER_FEATURETYPE_TEAMSPROMGMT_FETCHING_FAILED});this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}})}return(r?.teamsCallingPolicy||r?.teamsMeetingPolicy||i?.featureTypes?.includes(U2.TeamsProMgmt))&&(t=JSON.stringify({isLiveCaptionsEnabledForCalling:r?.teamsCallingPolicy?.liveCaptionsEnabledTypeForCalling===W2.DisabledUserOverride,isLiveCaptionsEnabledForMeeting:r?.teamsMeetingPolicy?.liveCaptionsEnabledType===W2.DisabledUserOverride,isTeamsProMgmtSkuAvailable:i?.featureTypes?.includes(U2.TeamsProMgmt)??!1}),this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_fetch_user_policies_for_captions,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{phrase:`Fetching Captions policy from ACS MiddleTier Service response was successful`,code:q7}}),this._logger.info(`Fetching user's captions policy content = ${t}`)),t}getEmergencyContent(){let e=+new Date;this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_emergency_content,kindOfEvent:$.attempt});let t=``;try{let n=this._policySettingData.userAggregatedPolicySettingData,r=n?.userPolicies,i=this.getEmergencyPolicyDetails(r,this._userDialedPstnNumber,n);i.foundEmergencyNumberMatch&&(t=JSON.stringify(i.emergencyContent));let a=i.foundEmergencyNumberMatch?`Created Emergency policy using ${i.logInfo}`:`This is NOT an emergency call`;return this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_emergency_content,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{phrase:`Deriving Emergency policy from ACS MiddleTier Service response was successful`,code:q7,subCode:cLe}}),this._logger.info(`Deriving emergency policy message = ${a}. Emergency Content = ${t}`),t}catch(t){let n=new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.DERIVE_EMERGENCY_POLICY,originalError:t});throw this.sendMiddleTierPolicyEvent({eventName:Q.acs_calling_middletier_gateway_emergency_content,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:new Date().getTime()-e},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...J3(n)}}),n}}isEmergencyNumber(e,t){if(!t)return this._logger.info(`Not an emergency number, no participants`),!1;if(!this.isFetchUserPoliciesAndSettingsApplicable(e,t))return this._logger.info(`Fetch user policies and settings not applicable`),!1;let n=Array.isArray(t)&&t.length>0?t[0].phoneNumber:t.phoneNumber,r=this._policySettingData.userAggregatedPolicySettingData,i=r?.userPolicies,a=this.getEmergencyPolicyDetails(i,n,r);return this._logger.info(`Emergency number check result: ${a.foundEmergencyNumberMatch}`),a.foundEmergencyNumberMatch}getEmergencyPolicyDetails(e,t,n){let r=!1,i=``,a={};if(e?.locationPolicy?.emergencyNumbers){let o=e.locationPolicy.emergencyNumbers||[];this.isPhoneNumberInLocationPolicy(o,t)&&(r=!0,a={enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:n?.userProperties.region,locationPolicyTag:e?.locationPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:e?.teamsEmergencyCallingPolicy?.policyDocument},i=`LocationPolicy`)}if(!r&&e?.teamsEmergencyCallRoutingPolicy){let o=e?.teamsEmergencyCallRoutingPolicy?.emergencyNumbers||[];this.isPhoneNumberInTeamsEmergenencyRoutingPolicy(o,t)&&(r=!0,a={enableSecurityMemberNotifications:this.isSecurityDeskEnabled(),callerLocation:n?.userProperties.region,teamsEmergencyCallRoutingPolicyTag:e?.teamsEmergencyCallRoutingPolicy?.policyDocument,teamsEmergencyCallingPolicyTag:e?.teamsEmergencyCallingPolicy?.policyDocument},i=`TeamsEmergencyCallingRoutingPolicy`)}return{foundEmergencyNumberMatch:r,logInfo:i,emergencyContent:a}}isFetchUserPoliciesAndSettingsApplicable(e,t){return r4(e)||r4(t)||(this._isPolicyFetchApplicable=this.verifyFetchUserPoliciesSettings(e,t)),this._isPolicyFetchApplicable}getEmergencyNumber(){return this._emergencyNumber}getUserDialedPstnNumber(){return this._userDialedPstnNumber}getUserPolicy(){return this._policySettingData.userAggregatedPolicySettingData?.userPolicies}getUserProperties(){return this._policySettingData.userAggregatedPolicySettingData?.userProperties}isPhoneNumberInLocationPolicy(e,t){if(!r4(e)&&t){for(let n of e)if(n.dialString===t||!r4(n.dialMask?.split(`;`).find((e=>e===t))))return this._emergencyNumber=n.dialString,!0}return!1}isPhoneNumberInTeamsEmergenencyRoutingPolicy(e,t){if(!r4(e&&t)){for(let n of e)if(n.emergencyDialString===t||!r4(n.emergencyDialMask?.split(`;`).find((e=>e===t))))return this._emergencyNumber=n.emergencyDialString,!0}return!1}verifyFetchUserPoliciesSettings(e,t){let n=Z().MiddleTier;return n.enabled?n.userPolicySettingsApi?e?Array.isArray(t)&&(t.length>1||!TG(t[0]))?(this._logger.info(`Target particpant (Callee) is not a PSTN Number`),!1):Array.isArray(t)||TG(t)?(this._logger.info(`Teams user is eligible to fetch policies and settings from MiddleTier Service `),!0):(this._logger.info(`Target particpant (Callee) is not a PSTN Number`),!1):(this._logger.info(`Originator (Caller) is not a Teams User`),!1):(this._logger.info(`ACS MiddleTier Policy API is disabled`),n.userPolicySettingsApi):(this._logger.info(`ACS MiddleTier service is disabled`),n.enabled)}isSecurityDeskEnabled(){let e=this._policySettingData.userAggregatedPolicySettingData?.userPolicies?.teamsEmergencyCallingPolicy;return!(r4(e?.notificationGroup)&&r4(e?.notificationDialOutNumber)||e?.notificationGroup?.trim().length==0&&e?.notificationDialOutNumber?.trim().length==0)}async getAcsMiddletierServiceRequestHeader(){return{"Content-Type":`application/json`,"X-Skypetoken":this._jwtTokenProvider?await this._jwtTokenProvider():``,"Access-Control-Allow-Origin":`*`,"X-Microsoft-Skype-Chain-ID":this._callId}}async getAcsMiddletierServiceRequestHeaderForThreadApi(e){let t={};return t=await this.getAcsMiddletierServiceRequestHeader(),t.onbehalfOfUser=e??this._localParticipant,t}sendMiddleTierPolicyEvent(e,t){try{this.setDefaultEventData(e,t),this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this._logger.debug(`Unable to send AcsMiddleTierPolicyService telemetry`)}}sendMiddleTierApiEvent(e){try{this.setDefaultEventData(e),this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this._logger.debug(`Unable to send MiddleTier Api telemetry`)}}setDefaultEventData(e,t){e.callId=this._callId,e.localParticipantId=this._localParticipant,e.requestedParticipantMRI=t??this._localParticipant,e.timestampInfo=e.timestampInfo??``,e.additionalDetails=e.additionalDetails??``}},fLe=class{constructor(e){this._logger=e}get gpu(){let e={};try{let t=document.createElement(`canvas`),n=t.getContext(`webgl`)||t.getContext(`experimental-webgl`);if(n){let t=n.getExtension(`WEBGL_debug_renderer_info`);t?(e.vendor=n.getParameter(t.UNMASKED_VENDOR_WEBGL),e.renderer=n.getParameter(t.UNMASKED_RENDERER_WEBGL)):this._logger?.info(`Unable to get GPU info: debug renderer info is not supported`)}else this._logger?.info(`Unable to get GPU info: WebGL is not supported`)}catch(e){this._logger?.info(`Unable to get GPU info: ${e}`)}return e}get hardwareConcurrency(){return navigator.hardwareConcurrency}},J7;(function(e){e.deviceSelection=`deviceSelection`,e.createCallAgent=`createCallAgent`,e.createTeamsCallAgent=`createTeamsCallAgent`,e.disposeCallAgent=`disposeCallAgent`,e.disposeTeamsCallAgent=`disposeTeamsCallAgent`,e.disposeCallClient=`disposeCallClient`,e.handleIncomingCall=`handleIncomingCall`,e.startPreheatDevices=`startPreheatDevices`,e.stopPreheatDevices=`stopPreheatDevices`})(J7||={});var pLe,Y7=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},X7=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},mLe=1,Z7=class{get customContext(){return this._customContext}get kind(){return this._kind}get connectionState(){return this._connectionState}constructor(e,t,n,r,i,a,o){this._callClient=e,this._customContext={callId:``,customContext:{}},this._pushHandlingDeltaTimeInMs=new Map,this._disposed=!1,this.tokenProvider=async e=>{let t=+new Date,n;try{if(this.sendTokenChangedEvent({kindOfEvent:`attempt`,timestampInfo:{attemptTimestamp:t},oldTokenExpiration:this._oldTokenExpiration}),!this._communicationTokenCredential)throw new Y({defaultError:J.CALL_AGENT.GET_TOKEN_BEFORE_INIT});n=await P4(this._communicationTokenCredential,Z().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),n.acsResourceId===this._parsedTokenCredential?.acsResourceId&&n.identityMri===this._parsedTokenCredential?.identityMri||j4(J.CALL_AGENT.REFRESHED_TOKEN_INVALID_USERID,this.logger),e?this._tokenFetchTries+=1:this._tokenFetchTries=0,this._tokenFetchTries>this._maxNmberOfRetries&&(this.updateConnectionState(`invalidToken`),this._disposed||await this.dispose(),j4(J.CALL_AGENT.REFRESHED_TOKEN_RETRIES,this.logger));let r=+new Date;return this.sendTokenChangedEvent({kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:r-t},oldTokenExpiration:this._oldTokenExpiration,newTokenExpiration:n.exp,isTokenChanged:this._oldToken!==n.jwtToken}),this._oldToken=n.jwtToken,this._oldTokenExpiration=n.exp,n.jwtToken}catch(e){let r={kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-t},oldTokenExpiration:this._oldTokenExpiration};throw n&&(r.newTokenExpiration=n.exp,r.isTokenChanged=this._oldToken!==n.jwtToken,this._oldToken=n.jwtToken,this._oldTokenExpiration=n.exp),this.sendTokenChangedEvent(r,e),e}},this.sendTokenChangedEvent=(e,t)=>{try{let n={kindOfEvent:e.kindOfEvent,timestampInfo:e.timestampInfo,oldTokenExpiration:e.oldTokenExpiration};e.newTokenExpiration!==void 0&&(n.newTokenExpiration=e.newTokenExpiration),e.isTokenChanged!==void 0&&(n.isTokenChanged=e.isTokenChanged),t&&(n={...n,...J3(t)}),this._telemetryLogManager.sendEvent({name:Q.acs_calling_token_expiration_changed,tenant:p2,properties:n})}catch{this.logger.debug(`Unable to send token change telemetry`)}},this.pushHandlingStarted=e=>{let t=J0();this._pushHandlingDeltaTimeInMs.set(e,{correlationId:t,timestamp:+new Date}),this.logger.log(`Incoming call state started`,e),L6.setCauseIdToNetworkInfo(e),this.sendIncomingNotificationEvent({eventName:Q.acs_calling_client_operations,operation:J7.handleIncomingCall,networkInfo:[],kindOfEvent:`attempt`,timestampInfo:{deltaTimeInMs:void 0},correlationId:t,additionalDetails:{},callId:``,participantId:``})},this.pushNotificationParsed=(e,t)=>{if(this.logger.debug(`pushNotificationParsed event received ${e}`),t.customContext.sipHeaders||t.customContext.voipHeaders){let{sipHeaders:e,voipHeaders:n}=t.customContext,r={sipHeaders:W4(e),voipHeaders:W4(n)},i=e=>`sipHeaders: ${e?.sipHeaders?.length||0}, voipHeaders: ${e?.voipHeaders?.length||0}`;if(!e4.isEqual(this._customContext.customContext,r)){this.sendCallAgentInfoEvent({eventName:Q.acs_calling_call_agent,additionalDetails:{step:`customContext-changed`,callId:t.callId,oldState:i(this._customContext.customContext),newState:i(r)}});let e={...this._customContext};this._customContext={callId:t.callId,customContext:r},this._eventEmitter.emit(`customContextChanged`,{oldValue:e,newValue:{...this._customContext}})}}},this.pushHandlingEnded=(e,t)=>{let n=t?.code!==void 0&&[0,200].includes(t?.code),r=e=>{if(n)return new Y({defaultError:{code:e?.code??0,subCode:e?.subCode??0,message:`Success`,resultCategories:[`Success`]}});let t=[J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_INVALID_NOTIFICATION_PAYLOAD,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_FAILED_TO_EXTRACT_PAYLOAD,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_ALREADY_HANDLED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_IGNORING_DUPLICATE_NOTIFICATION,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_FAILED_TO_HANDLE_NOTIFICATION_FOR_GROUPID_CALL,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_BAD_NOTIFICATION_PAYLOAD,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_SUCCEEDED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_FAILED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_BAD_NOTIFICATION_EVENT_TYPE,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_ALREADY_EXISTS,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CANNOT_CONNECT,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_NO_SIGNALING,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CONFLICT,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_PUSH_IGNORED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_ANSWERED_ELSEWHERE,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_FAILED_CALL_ALREADY_ENDED,J.CALL_AGENT_RTC.INCOMING_CALL_HANDLING_CALL_SETUP_IN_PROGRESS];return new Y({defaultError:e4.find(t,(t=>t.subCode===e?.subCode))??J.CALL_AGENT.INVALID_PUSH_NOTIFICATION_DATA})};this.logger.log(`Incoming call state ended`,e,t);let i=L6.getRemoveCauseIdToNetworkInfo(e),a=this._pushHandlingDeltaTimeInMs.get(e)?.correlationId||`unknown`,o=r(t);this.sendIncomingNotificationEvent({eventName:Q.acs_calling_client_operations,operation:J7.handleIncomingCall,networkInfo:i||[],kindOfEvent:n?`success`:`failure`,timestampInfo:{deltaTimeInMs:this._pushHandlingDeltaTimeInMs.has(e)?+new Date-this._pushHandlingDeltaTimeInMs.get(e)?.timestamp:void 0},correlationId:a,additionalDetails:{...J3(o)},callId:t.callId||``,participantId:t.participantId||``}),this._pushHandlingDeltaTimeInMs.delete(e),this._eventEmitter.emit(`handleIncomingCall`,{callId:t.callId||``,participantId:t.participantId||``,...Y3({code:o.code,subCode:o.subCode,message:o.message,resultCategories:o.resultCategories})})},this.logger=t.createChild(`CallAgent`+ mLe++),this._telemetryLogManager=r,this._kind=a,this._connectionState=`Disconnected`,this._eventEmitter=new w6(this.logger),this._internalEventEmitter=new E3.EventEmitter,this.clientId=n,this._abortController=new AbortController,this._maxDisplayNameLength=Z()?.calling?.maxDisplayNameLength||XCe,this._oldToken=``,this._oldTokenExpiration=0,this._tokenFetchTries=0,this._maxNmberOfRetries=Z()?.calling?.maxNumberOfTokenFetchRetries||zCe,this._callStack=i,this.callClient=this._callClient,this.deviceManager=o,this.acsProxy=this.callClient.acsProxy,this.acsCustomRelayManager=this.callClient.acsCustomRelayManager,this._httpRequestHelper=new UEe(this.logger,this.acsProxy),this.mtPolicyService=new dLe(this._httpRequestHelper),this._parsedTokenCredential=eTe(),this._caConfigBag={clientId:``,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?t2.Enterprise:t2.Consumer,region:this._parsedTokenCredential.region,emergencyCountryCode:void 0,IsUserEmergencyCountryCode:!1,mriType:this._parsedTokenCredential.mriType,parsedTokenCredential:this._parsedTokenCredential},this._extensibleApi=new F3(this.logger,{callClient:this.callClient,callAgent:this},{tsStack:this.tsStack,callAgent:this,telemetryLogManager:this._telemetryLogManager});let s=e7(k3.CallAgentFeature);for(let e of s)e.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(e);this._trouterStateChangeCallback=e=>{this.logger.log(`Callback Trouter state changed to ${e}`),this.updateConnectionState(`trouterChanged`)},this._registrarStateChangeCallback=e=>{this.logger.log(`Callback Registrar state changed to ${e}`),this.updateConnectionState(`registrarChanged`)}}getHttpRequestHelper(){return this._httpRequestHelper}getTrouterState(){return this._callStack?this._callStack.getTrouterState():`Unknown`}onTrouterStateChanged(e){return this._callStack.onTrouterStateChanged(e)}offTrouterStateChanged(e){return this._callStack.offTrouterStateChanged(e)}onDisposed(e){this._internalEventEmitter.on(`disposed`,e)}getAcsResourceId(){return this._parsedTokenCredential?.acsResourceId||``}getUserMri(){return`8:${this._parsedTokenCredential?.identityMri}`||``}getUserPolicy(){return this._userPolicies}getUserProperties(){return this._userProperties}getInternalCallRegistry(){return this._tsCallRegistry}async initialize(e,t){let n=+new Date,r=new fLe(this.logger),i={gpu:r.gpu,hardwareConcurrency:r.hardwareConcurrency};try{if(this.sendCallAgentInitializiedEvent(Q.acs_calling_call_agent_init_attempt,{attemptTimestamp:n},i),this._communicationTokenCredential=e,this._parsedTokenCredential=await P4(e,Z().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),this._kind!==WG.TeamsCallAgent||this._parsedTokenCredential.isEnterpriseUser?this._kind===WG.CallAgent&&this._parsedTokenCredential.isEnterpriseUser&&j4(J.CALL_AGENT.ACS_CALLAGENT_TOKEN_ONLY,this.logger):j4(J.CALL_AGENT.TEAMS_CALLAGENT_TOKEN_ONLY,this.logger),t?.displayName){if(this._parsedTokenCredential.isEnterpriseUser)throw new Y({defaultError:J.CALL_AGENT.ENTERPRISE_DISPLAY_NAME});if(t?.displayName.length>this._maxDisplayNameLength)throw new Y({defaultError:J.CALL_AGENT.DISPLAY_NAME_TOO_LONG})}if(this._parsedTokenCredential.cloudType===X0.Public&&(!this._parsedTokenCredential.region||this._parsedTokenCredential.region===``)){try{let e=+new Date-n;this._telemetryLogManager.sendEvent({name:Q.acs_calling_token_has_no_data_location,tenant:p2,properties:{deltaTimeInMs:e}})}catch{this.logger.debug(`Unable to send token has no data location assigned`)}this._parsedTokenCredential.region=this._parsedTokenCredential.rgnClaimExists?wSe[0]:r2[0],this.logger.info(`Used default data location because token has no data location assigned`)}this._caConfigBag={clientId:this.clientId,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?t2.Enterprise:t2.Consumer,emergencyCountryCode:t?.emergencyCallOptions?.countryCode,region:this._parsedTokenCredential.region,IsUserEmergencyCountryCode:!!t?.emergencyCallOptions?.countryCode,mriType:this._parsedTokenCredential.mriType,parsedTokenCredential:this._parsedTokenCredential},this.addToCallAgentsMap(this._parsedTokenCredential),this._disposed=!1;try{this.runningEnvironmentInfo=await this.callClient.getEnvironmentInfoInternal()}catch{this.logger.debug(`Unable to get the running environment info`)}if(this.tsStack=await this._callStack.initializeStackForUser(this.tokenProvider,this._caConfigBag),this._parsedTokenCredential.rgnClaimExists)try{await this.updateParsedTokenCredentials(e)}catch(e){this.logger.debug(`Failed to update parsed token credentials. Error message = ${e?.message||``}`)}await this.setUserPoliciesOnAgentInitialization(),this.isEnterpriseUser()&&(t={...t,displayName:this._userProperties?.displayName??void 0}),this._telemetryLogManager.initialize(this._caConfigBag),this._tsCallRegistry=await this.initializeCallRegistry(this.tsStack,t),this.registerConnectionStateEventHandlers();let r=+new Date;this.sendCallAgentInitializiedEvent(Q.acs_calling_call_agent_init_success,{deltaTimeInMs:r-n},i)}catch(e){this._caConfigBag&&!this._telemetryLogManager.isInitialized()&&this._telemetryLogManager.initialize(this._caConfigBag);let t=new Y({defaultError:J.CALL_AGENT.INIT_FAIL,originalError:e});this.removeFromCallAgentsMap(this._parsedTokenCredential);let r=+new Date;throw this.sendCallAgentInitializiedEvent(Q.acs_calling_call_agent_init_failure,{deltaTimeInMs:r-n},i,t),t}}handleActiveCallTransfer(e){this.logger.info(`CallAgent handling active call transfer for callId=${e.id}`),this._eventEmitter.emit(`callsUpdated`,{added:[e],removed:[]})}async setUserPoliciesOnAgentInitialization(){this.mtPolicyService.initialize({localParticipant:this.getUserMri(),jwtTokenProvider:this.tokenProvider,telemetryLogManager:this._telemetryLogManager})}isEnterpriseUser(){return this._parsedTokenCredential?.isEnterpriseUser!==void 0&&this._parsedTokenCredential?.isEnterpriseUser}isTeamsExtensionUser(){return this._parsedTokenCredential?.mriType!==void 0&&this._parsedTokenCredential?.mriType==n2.TeamsExtensionUser}getClientId(){return this.clientId}getCallByCallId(e,t){return t?this._tsCallRegistry.getCall(e,t):this._tsCallRegistry.calls.filter((t=>t.callId===e))?.[0]}async createTransferTargetCall(e){let t=PG(),n=J0(),r=J0(),i=await this._tsCallRegistry.createCallAsync({callId:n,localParticipantId:r,causeId:t,type:`ThreadId`,threadId:``}),a=this.createNewCall(n,i);return this.addToCallArray(a),this.handleCallState(a),i.addParticipant(e.targetMri).catch((()=>{this.logger.error(`Failed to add participant for transer call`)})),G6(i)?await Promise.all(a.bindTsCall()):a.bindTsCall(),this._eventEmitter.emit(`callsUpdated`,{added:[a],removed:[]}),a}async subscribeCallWithoutModality(e){let t=PG(),n=await this._tsCallRegistry.createCallAsync({callId:e.callId,localParticipantId:e.participantId,causeId:t,type:`ThreadId`,threadId:e.threadId,messageId:e.messageId}),r=this.createNewCall(e.callId,n),i={conversationUrl:e.meetingUrl,conversationId:e.callId};return this.addToCallArray(r),this.handleCallState(r),n.joinCallWithoutCallModality(i,{},t).then((()=>{this.logger.info(`Successfully joined call without modalities`)})).catch((e=>{throw this.logger.error(`Error while joining call without modalities`,e),new Y({defaultError:J.CALL_AGENT.INVALID_JOIN_LOCATOR,originalError:e})})),G6(n)?await Promise.all(r.bindTsCall()):r.bindTsCall(),r}getEcsConfigIds(){return this._callStack.getEcsConfigIds()}getDeviceType(){let e=this.callClient?.firstPartyOptions?.acsDeviceType;return e?iwe[e]:`default`}isWatermarkSupported(){return this.isEnterpriseUser()?Z().calling.watermark.watermarkEnabledForCteUsers:Z().calling.watermark.watermarkEnabledForAcsUsers}feature(e){return this._extensibleApi.getApiObjectInstance(e.callAgentApiCtor)}async handlePushNotification(e){let t=J0(),n=+new Date,r;try{if(this.sendHandlePushNotificationEvent({eventName:Q.acs_calling_handle_push_notification,correlationId:t,featureName:`handlePushNotification`,operationName:`handleIncomingCallPushNotification`,callId:``,localParticipantId:``,kindOfEvent:`attempt`,timestampInfo:``,additionalDetails:``}),!e.incomingCallContext)throw new Y({defaultError:J.CALL_AGENT.INVALID_PUSH_NOTIFICATION_DATA});r=new oLe(e,this._tsCallRegistry,this.logger),await r.process(),this.sendHandlePushNotificationEvent({eventName:Q.acs_calling_handle_push_notification,correlationId:t,featureName:`handlePushNotification`,operationName:`handleIncomingCallPushNotification`,callId:r.callId,localParticipantId:r.localParticipantId,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:``})}catch(e){let i=new Y({defaultError:J.CALL_AGENT.PUSH_NOTIFICATION_FAIL,originalError:e});throw this.sendHandlePushNotificationEvent({eventName:Q.acs_calling_handle_push_notification,correlationId:t,featureName:`handlePushNotification`,operationName:`handleIncomingCallPushNotification`,callId:r?.callId||``,localParticipantId:r?.localParticipantId||``,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{failureReason:i.message,code:i.code,...J3(i)}}),i}}sendCallAgentDisposeEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send CallClient dispose telemetry event`)}}trackCallEndTimeToStopTelemetry(e){e.length===0?m3.callEndTimestamp=Date.now():m3.callEndTimestamp=2**53-1}updateConnectionState(e){let t=this.getCallAgentConnectionState(),n=this.getTrouterState(),r=this._callStack?.isRegistered()?`Connected`:`Disconnected`,i=t===`Connected`?void 0:e==`invalidToken`?`invalidToken`:`connectionIssue`;if(this.sendCallAgentInfoEvent({eventName:Q.acs_calling_call_agent,additionalDetails:{step:`connectionState-changed`,oldState:this._connectionState,newState:t,trouterState:n,registrarState:r,reason:i,connectionStateSource:e}}),t!==this._connectionState||i!==this._connectionStateReason){let e={oldValue:this._connectionState,newValue:t,reason:i};this._connectionState=t,this._connectionStateReason=i,this._eventEmitter.emit(`connectionStateChanged`,e)}}sendCallAgentInfoEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:{...e.additionalDetails}})}catch(e){this.logger.debug(`Failed to send connection state changed event`,e)}}sendCallAgentInitializiedEvent(e,t,n,r){try{let i=typeof r?.message==`string`?r?.message:void 0;e!==Q.acs_calling_call_agent_init_failure&&(i=void 0);let a=r?J3(r):void 0,o=this.getEcsConfigIds(),s=e===Q.acs_calling_call_agent_init_attempt?void 0:this._callStack?.getVdi3StateInfo(),c=a7();this._telemetryLogManager.sendEvent({name:e,tenant:p2,properties:{...t,isSupportedEnvironment:this.runningEnvironmentInfo?.isSupportedEnvironment,failureReason:i,additionalProperties:{AcsCallingSDKWeb_ecsConfigIds:o.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigIds:o.SkypeWebMedia},additionalInformation:{trouterState:this.getTrouterState(),hardwareInfo:n},additionalDetails:{...a,firstPartyOptions:{isDeviceTypeEnabled:Z().calling.setDeviceType,deviceTypeRawStrlen:this.callClient?.firstPartyOptions?.acsDeviceType?.length,deviceType:this.getDeviceType()},aadPftClaimExists:this._parsedTokenCredential.aadpftClaimExists,...s?{vdi3StateInfo:s}:{},...c.isMMREnabled?{mmrInfo:c}:{}}}})}catch{this.logger.debug(`Unable to send telemtery`)}}sendHandlePushNotificationEvent(e){try{this._telemetryLogManager?.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send handle push notification telemetry`)}}async initializeCallRegistry(e,t){let n=t?.displayName,r=await this.getCallRegistry(e,this._parsedTokenCredential,this.tokenProvider,n);return this.logger.info(`registry created for version number=${Z2()}`),r}async getCallRegistry(e,t,n,r){let i={id:t.identityMri,displayName:r||``,tokenProvider:n},a=await e.createCallRegistry(i);await a.login(i);let o=(this._callClient?.firstPartyOptions?.ring??Z()?.tsCalling?.accountConfiguration?.ring)||void 0,s=t.isEnterpriseUser?t2.Enterprise:t2.Consumer,c=t.acsResourceId,l=t.region,u={acsResourceId:c,clientType:s,ring:o};if(Z().calling.setDeviceType)u.deviceType=this.getDeviceType();else if(this.callClient.firstPartyOptions?.acsDeviceType)throw new Y({defaultError:J.CALL_AGENT.SET_DEVICE_TYPE_NOT_ALLOWED});let d=Z().calling.eudb;return d.isEnabled&&d.sendRegionToNgc&&(d.isRgnClaimEnabledForACS||t.isEnterpriseUser)&&(u={...u,region:l}),Z()?.calling.supportLiveStreaming&&(u.clientSupportsUms=!0),u.clientSupportsWatermark=this.isWatermarkSupported(),await a.setConfiguration(u),a.on(`callAdded`,this.handleCallAdded),a.on(`callRemoved`,this.handleCallRemoved),a.on(`pushHandlingStarted`,this.pushHandlingStarted),a.on(`pushHandlingEnded`,this.pushHandlingEnded),a.on(`pushNotificationParsed`,this.pushNotificationParsed),r&&await a.updateDisplayName(r),a}async updateParsedTokenCredentials(e){this._parsedTokenCredential=await P4(e,Z().calling.eudb.isRgnClaimEnabledForACS,{abortSignal:this._abortController.signal}),this._caConfigBag.region=this._parsedTokenCredential.region,this._caConfigBag.parsedTokenCredential=this._parsedTokenCredential}registerConnectionStateEventHandlers(){this._callStack.onRegisteredChanged(this._registrarStateChangeCallback),this.onTrouterStateChanged(this._trouterStateChangeCallback)}getCallAgentConnectionState(){return this._callStack?.isRegistered()&&this.getTrouterState()===`Connected`?`Connected`:`Disconnected`}sendIncomingNotificationEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send incoming call notification telemetry`)}}};Y7([UG,X7(`design:type`,Object)],Z7.prototype,`logger`,void 0),Y7([YG(s4.Initialize),X7(`design:type`,Function),X7(`design:paramtypes`,[Object,Object]),X7(`design:returntype`,Promise)],Z7.prototype,`initialize`,null),Y7([JG(s4.Feature),X7(`design:type`,Function),X7(`design:paramtypes`,[Object]),X7(`design:returntype`,typeof(pLe=typeof TFeature<`u`&&TFeature)==`function`?pLe:Object)],Z7.prototype,`feature`,null),Y7([YG(s4.HandlePushNotification),X7(`design:type`,Function),X7(`design:paramtypes`,[Object]),X7(`design:returntype`,Promise)],Z7.prototype,`handlePushNotification`,null);var hLe=class{constructor(e){this._call=e}setTarget(e){this._call=e}getTarget(){return this._call}startVideo(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopVideo(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}startScreenSharing(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopScreenSharing(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setConstraints(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}};function Q7(e){let t=new hLe(e);return new Proxy({},{get:(e,n)=>{let r,i,a=t.getTarget();if(n in t)r=t[n],i=t;else{if(a===void 0)throw new Y({defaultError:J.FEATURES.VDI3.CALL_INITIALIZING});if(!(n in a))return;r=a[n],i=a}return typeof r==`function`?function(...e){return r.apply(i,e)}:r},has:(e,n)=>{let r=t.getTarget();return n in t||r!==void 0&&n in r}})}var $7,e9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},t9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},n9=class e extends Z7{get calls(){return this._calls}constructor(e,t,n,r,i,a,o){super(e,t,r,i,n,WG.CallAgent,a),this._calls=[],this.handleCallRemoved=e=>{this.logger.info(`removing callId=${e.callId}`);let t=this._calls.find((t=>t.id===e.callId));if(t){if(t.isBreakoutRoomCall){let e=Z().calling.breakoutRooms.hangUpCallDelayInMilliSeconds;setTimeout((()=>{this.disposeCall(t)}),e)}else this.disposeCall(t);this._eventEmitter.emit(`callsUpdated`,{added:[],removed:[t]}),this.logger.info(`call removed`)}},this.handleCallAdded=e=>{if(!this._calls.find((t=>t.id===e.callId))){let t=e.on(`callStateChanged`,(async()=>{if(e.state===1){let n=G6(e),r=e.callId;t.dispose();let i=new H7({callId:r,isIncoming:!0},this,e,this._telemetryLogManager);n&&(i=Q7(i));let a=new aLe(i);this.handleCallState(i),n?await Promise.all(i.bindTsCall()):i.bindTsCall(),this._eventEmitter.emit(`incomingCall`,{incomingCall:a})}}))}},this.handleCallState=e=>{e.on(`stateChanged`,(async()=>{try{e.state===`Disconnected`?this.tsStack?(await this._tsCallRegistry.deleteCallAsync?.(e.tsCall)||this.logger.info(`The call has been removed from registry, call id: ${e.id}`),e.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(e.id).catch((()=>{this.logger.error(`Failed to flush telemetry log manager events`)}))):this.logger.info(`Unable to remove call from registry`):e.state===`Connecting`&&e.direction==`Incoming`&&(this.addToCallArray(e),this._eventEmitter.emit(`callsUpdated`,{added:[e],removed:[]}))}catch{this.logger.error(`Failed to handle call state changed event`)}}))},this.displayName=o?.displayName}addToCallAgentsMap(t){e.callAgents.get(t?.identityMri)&&j4(J.CALL_AGENT.ACS_CALLAGENT_ALREADY_EXSISTS,this.logger),e.callAgents.set(t?.identityMri,this)}removeFromCallAgentsMap(t){t?.identityMri&&e.callAgents.get(t?.identityMri)===this&&e.callAgents.delete(t?.identityMri)}disposeCall(e){let t=this._calls.indexOf(e);t!==-1&&this._calls.splice(t,1),e.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls)}async getExistingCallAgentWithToken(t){try{let n=await P4(t,Z().calling.eudb.isRgnClaimEnabledForACS);return e.callAgents.get(n.identityMri)}catch(e){throw new Y({defaultError:J.CALL_AGENT.PARSE_ACCESSTOKEN,originalError:e})}}createNewCall(e,t){let n=new H7({callId:e},this,t,this._telemetryLogManager);return G6(t)?Q7(n):n}addToCallArray(e){this._calls.push(e),this.trackCallEndTimeToStopTelemetry(this._calls)}async disposeInternal(t){let n=+new Date,r=J0();this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});try{if(this._disposed)throw new Y({defaultError:J.CALL_AGENT.ACS_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&e.callAgents.delete(this._parsedTokenCredential?.identityMri);for(let e of this._calls)e.state!==`Disconnected`&&await e.hangUp().catch((()=>{this.logger.error(`Failed to hangup call during call agent dispose`)}));await this._tsCallRegistry?.dispose();let t=this._tokenFetchTries>this._maxNmberOfRetries;await this._callStack.disposeUserStack(t),this.offTrouterStateChanged(this._trouterStateChangeCallback),this._callStack.offRegisteredChanged(this._registrarStateChangeCallback),this._eventEmitter.removeAllListeners(),this._internalEventEmitter.emit(`disposed`),this._internalEventEmitter.removeAllListeners(),this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:``})}catch(e){let t=new Y({defaultError:J.CALL_AGENT.DISPOSE_FAIL,originalError:e});throw this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}}),t}finally{t&&this._telemetryLogManager.clearTelemetryLoggers()}}startCall(e,t){let n=J0(),r=+new Date,i={correlationId:n,timestampInfo:{attemptTimestamp:r}};this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_attempt,tenant:p2,properties:i},void 0,`attempt`);try{if(this.assertCallUserIds(e),t?.alternateCallerId&&Y2(t.alternateCallerId),e.find((e=>K2(e)===this.getUserMri())))throw new Y({defaultError:J.CALL_AGENT.CANT_CALL_YOURSELF});let i=t?.audioOptions?.muted;return i===void 0&&(i=!1),this.logger.info(`startCall with video=${!!t?.videoOptions},muted=${i}`),this.createCall({participants:e,startCallOptions:t},{correlationId:n,attemptTimestamp:r})}catch(e){let t,i;throw e instanceof Y&&(t=typeof e?.message==`string`?e?.message:void 0,i={...J3(e)}),this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_failed,tenant:p2,properties:{correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-r},failureReason:t||``,additionalDetails:i||{}}},void 0,`failure`),e}finally{this._telemetryLogManager.deleteEventMapByCorrelationId(n)}}join(e,t){if(!B4(this.acsProxy,this.acsCustomRelayManager,!1,void 0,e))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});this.assertCallContext(e);let n=t?.audioOptions?.muted;return n===void 0&&(n=!1),this.logger.info(`join with video=${!!t?.videoOptions},muted=${n}`),this.createCall({callContext:e,startCallOptions:t})}async dispose(){await this.disposeInternal(!0)}on(e,t){if(e!==`handleIncomingCall`&&e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`handleIncomingCall`&&e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}createCall(e,t){if(e?.startCallOptions?.firstPartyOptions?.isImmersiveMode&&this.getDeviceType()!==`meshV2`)throw new Y({defaultError:J.CALL_AGENT.MESH_DEVICETYPE_V2});if(!this.tsStack)throw new Y({defaultError:J.CALL_AGENT.STACK_NOT_INIT});let n,r,i,a=e?.callContext?.threadId||e?.startCallOptions?.threadId,o=!1,s=e?.callContext?.groupId,c=e?.callContext?.roomId,l=e?.callContext?.meetingLink,u=e?.callContext?.meetingId,d=e?.callContext?.passcode||``;if(s&&s.startsWith(`19:`)&&(a=s,s=``),l)if(vFe(l))r=P5(l);else{if(!yFe(l,this.logger))throw new Y({defaultError:J.CALL_AGENT.INVALID_MEETING_LINK});if(bFe(l.trim().toLocaleLowerCase(),Z().calling.tfl.hosts)&&!Z().calling.tfl.isEnabled)throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TFL_MEETING_JOIN});o=!0}e?.callContext?.threadId&&e?.callContext?.organizerId&&e?.callContext?.tenantId&&(r={threadId:e?.callContext?.threadId,messageId:e?.callContext?.messageId?e?.callContext?.messageId.toString():`0`,organizerId:e?.callContext?.organizerId,tenantId:e?.callContext?.tenantId}),r&&(i={meetingType:r.messageId===`0`?1:2,tenantId:r.tenantId,organizerId:r.organizerId,replyChainMessageId:r.messageId},a=r.threadId,n=r.messageId);let f=PG(),p=J0(),m=J0(),h={threadId:a||``,messageId:n||``,meetingInfo:i,mediaPeerType:2},g=!1;if(G6(this._tsCallRegistry)){let r=Q7();return(async()=>{let i;s?i=await this._tsCallRegistry.createCallAsync({type:`GroupId`,groupId:s,callId:p,localParticipantId:m,causeId:f}):u?i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`MeetingData`,meetingData:{meetingCode:u,passcode:d,threadId:a}}):c?i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`MeetingData`,meetingData:{meetingCode:c}}):o?i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`MeetingData`,meetingData:{meetingUrl:l}}):(g=!!e?.participants&&e.participants.length>=2&&V4(e.participants,this.kind),Z().calling.enableSmePassFakeConversation&&!a&&g&&(a=`${VG}${J0()}`),i=await this._tsCallRegistry.createCallAsync({callId:p,localParticipantId:m,causeId:f,type:`ThreadId`,threadId:a||``,messageId:n}));let _=new H7({callId:p,roomId:c},this,i,this._telemetryLogManager,g);r.setTarget(_),this.addToCallArray(r),this.handleCallState(r),e?.participants&&e?.participants.forEach((e=>{i.addParticipant(K2(e)).catch((()=>{this.logger.error(`Failed to add participant during call start`)}))}));let v=n3();_.startCallInternal(e?.startCallOptions,!!u||!!c,e?.callContext,h,t,v).catch(M4),await Promise.all(_.bindTsCall()),await v.promise,this._eventEmitter.emit(`callsUpdated`,{added:[r],removed:[]})})().catch((e=>{})),r}{let r,i=!1;s?r=this._tsCallRegistry.createCallWithGroupId(s,p,m,f):u?r=this._tsCallRegistry.createCallWithMeetingData({meetingCode:u,passcode:d,threadId:a},p,m,f):c?r=this._tsCallRegistry.createCallWithMeetingData({meetingCode:c},p,m,f):o?r=this._tsCallRegistry.createCallWithMeetingData({meetingUrl:l},p,m,f):(i=!!e?.participants&&e.participants.length>=2&&V4(e.participants,this.kind),Z().calling.enableSmePassFakeConversation&&!a&&i&&(a=`${VG}${J0()}`),r=this._tsCallRegistry.createCall(a||``,p,m,n,f));let g=new H7({callId:p,roomId:c},this,r,this._telemetryLogManager,i);return this.addToCallArray(g),this.handleCallState(g),e?.participants&&e?.participants.forEach((e=>{r.addParticipant(K2(e)).catch((()=>{this.logger.error(`Failed to add participant during call start`)}))})),g.startCallInternal(e?.startCallOptions,!!u||!!c,e?.callContext,h,t).catch(M4),g.bindTsCall(),this._eventEmitter.emit(`callsUpdated`,{added:[g],removed:[]}),g}}assertCallContext(e){if(!e||this.checkForAtLeastOneValidCallConfig(e)||this.checkIfMultiplesConfigsWereSpecified(e)||this.checkForInvalidTeamsMeetingCoordinates(e))throw new Y({defaultError:J.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(e){return!(e.threadId||e.meetingLink||e.groupId||e.meetingId||e.roomId)}checkIfMultiplesConfigsWereSpecified(e){return e.threadId&&e.groupId||e.groupId&&e.meetingLink}checkForInvalidTeamsMeetingCoordinates(e){return!e.threadId&&e.tenantId&&e.organizerId||e.threadId&&(e.organizerId&&!e.tenantId||!e.organizerId&&e.tenantId)}assertCallUserIds(e){Ywe(e,J.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),Jwe(e,J.CALL_AGENT.USERIDS_CANNOT_BE_NULL),dwe(e),e.forEach((e=>{let t=Y2(e);if(!B4(this.acsProxy,this.acsCustomRelayManager,!1,t))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN})}))}};n9.callAgents=new Map,e9([JG(s4.StartCall),t9(`design:type`,Function),t9(`design:paramtypes`,[Array,Object]),t9(`design:returntype`,Object)],n9.prototype,`startCall`,null),e9([JG(s4.Join),t9(`design:type`,Function),t9(`design:paramtypes`,[Object,Object]),t9(`design:returntype`,Object)],n9.prototype,`join`,null),e9([YG(s4.Dispose),t9(`design:type`,Function),t9(`design:paramtypes`,[]),t9(`design:returntype`,Promise)],n9.prototype,`dispose`,null),function(e){e.alpha=`alpha`,e.beta=`beta`,e.stable=`stable`,e.unknown=`unknown`}($7||={});var gLe=class{constructor(){this.browserInfo=r8();let e=X2();e.includes(`alpha`)||e.includes(`alpharc`)?this.sdkFlavor=$7.alpha:e.includes(`beta`)||e.includes(`betarc`)?this.sdkFlavor=$7.beta:e.includes(`stable`)||e.includes(`stablerc`)?this.sdkFlavor=$7.stable:this.sdkFlavor=$7.alpha}getInitialJamaSettings(){let e=t4.merge({},MSe),t=this.getFormFactorBaseSettings();e=t4.merge(e,t);let n=this.getSdkFlavorBaseSettings();e=t4.merge(e,n);let r=this.getSdkFlavorFormFactorSettings();e=t4.merge(e,r);let i=this.getBrowserEngineSpecificSettings();return e=t4.merge(e,i),e}getFormFactorBaseSettings(){switch(this.browserInfo.formFactor){case`Desktop`:return NSe;case`Mobile`:return ISe;default:return MSe}}getSdkFlavorBaseSettings(){switch(this.sdkFlavor){case $7.stable:return BSe;case $7.beta:return zSe;case $7.alpha:default:return RSe}}getSdkFlavorFormFactorSettings(){let e=this.browserInfo.formFactor;if(this.sdkFlavor===$7.stable)switch(e){case`Desktop`:return USe;case`Mobile`:return KSe;default:return BSe}else if(this.sdkFlavor===$7.beta)switch(e){case`Desktop`:return HSe;case`Mobile`:return GSe;default:return zSe}else switch(e){case`Desktop`:return VSe;case`Mobile`:return WSe;default:return RSe}}getBrowserEngineSpecificSettings(){let e=this.browserInfo.engine,t=i8(),n=this.browserInfo.formFactor;return t===`ios`&&e===`Safari`?LSe:n===`Desktop`&&e===`Chromium`?PSe:e===`Firefox`?FSe:{}}},r9=class{constructor(e,t,n){this.setConfigOrDefault=(e,t)=>{e&&Object.keys(e).forEach((n=>{e[n]!==void 0&&(t[n]=e[n])}))},this._logger=e,this.sdkDiagnosticInformation=t,this._acsProxy=n,this._jamaSettingsProvider=new gLe;let r=Z().calling.applicationSettingsUrls,i=Z().calling.pnhTemplateVersion;this._trouterSettings={version:`${d2()}/${X2()}`,productName:`AcsWeb`,trouterServiceUrl:r.Public_TrouterServiceUrl,registrarServiceUrl:r.Public_RegistrarServiceUrl,maxRegistrationTimeInMs:36e5,pnhAppId:`AcsWeb`,pnhTemplate:i,environment:`Prod`,platform:n8()},this._JsCsaConfig={languageCode:`en`,emergencyCallCountry:``,autoResolveConflictedCall:!1,handleRosterFromCreateAndJoin:!0,conversationServiceUrl:n.proxyfyUrl(r.Public_ConversationServiceUrl),useInternalHttpDispatcher:!0,supportsHostlessGroupCalls:!0,doHostlessCalling:!0,shouldServiceSendCallEventMessages:!0,shouldServiceSendNGCUpgradeMessages:!0,supportsCompressedServicePayload:!0,handleNewOfferRequest:!0,handleMediaOfferFromPushNotification:!0,isWebRtcEnabled:!0,supportsSynchronousTrouterResponse:!0,autoJoinOnConflict:!0,brokerEnabledOutgoing:!0,brokerEnabledIncoming:!0,brokerExclusively:!1,brokerRequestBatching:!0,isGVCOutgoingEnabled:!0,isGVCJoiningEnabled:!0,enableTokenCache:!1,nullifyAuthTokenManagerOnReset:!1},this._JamaSettings=this._jamaSettingsProvider.getInitialJamaSettings(),this._MDNTrapSettings={Service:{url:n.proxyfyUrl(r.Public_MdnTrapServiceUrl),tokenUrl:n.proxyfyUrl(r.Public_MdnTrapServiceTokenUrl)},Relay:{Skype:{addresses:[],fqdns:[r.Public_MdnTrapRelaySkypeFqdns],tcpPort:443,udpPort:3478},Turn:{addresses:[],fqdns:[r.Public_MdnTrapRelayTurnFqdns],tcpPort:443,udpPort:3478,url:r.Public_MdnTrapRelayTurnUrl}},Http:{connectionTimeout:30,requestTimeout:60},Token:{earlyRefreshMinutes:1080,earlyRefreshPercentage:25}},this._TrouterJScriptClient={TelemetryEnabled:!1,ClientTelemetryEventEnabled:{trouter_js_client_connected:!1,trouter_js_client_disconnected:!1,trouter_js_client_error:!1,trouter_js_client_progress:!1,trouter_js_client_response:!1,trouter_js_client_check_connection:!1,trouter_js_client_registration:!1,trouter_js_client_unregistration:!1,logHealthCheckError:!1,logSendPingError:!1,numberOfStepsToMaintain:0,sendProgressTimeoutSecs:0}}}getTrouterTelemetryConfig(){return{enabled:this._TrouterJScriptClient.TelemetryEnabled,...this._TrouterJScriptClient.ClientTelemetryEventEnabled}}getJamaSettings(){return this._JamaSettings}getClientInformation(){let e=Z().telemetry.reportSdkUaToService,t=Z().telemetry.reportEnvToService;return`ACSWeb(${d2()}/${X2()})`+(t?`/${cke()}`:``)+(e?`/(${this.sdkDiagnosticInformation})`:``)}getJsCsaConfig(){return this._JsCsaConfig.useInternalHttpDispatcher=!(this._acsProxy.hasProxyUrl()||Z().telemetry.sendNetworkInfo),{...this._JsCsaConfig,clientInformation:this.getClientInformation()}}getMdnTrapSettings(){return this._MDNTrapSettings}getTrouterSettings(){return this._trouterSettings}setConfig(e,t){this._logger.info(`Update ECS settings`);let n=Z().calling.applicationSettingsUrls,r=Z().calling.applicationSettingsEudbUrls,i=e&&N4(e.identityType,e.region);if(e?.identityType==t2.Enterprise)i?(this._trouterSettings.trouterServiceUrl=r.Enterprise_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(r.Enterprise_RegistrarServiceUrl_EUDB)):(this._trouterSettings.trouterServiceUrl=n.Enterprise_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Enterprise_RegistrarServiceUrl));else switch(e?.cloudType){case X0.Public:i&&(this._trouterSettings.trouterServiceUrl=r.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(r.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(r.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[r.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[r.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=r.Public_MdnTrapRelayTurnUrl_EUDB);break;case X0.GccHigh:this._trouterSettings.trouterServiceUrl=n.GccHigh_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.GccHigh_RegistrarServiceUrl);break;case X0.Dod:this._trouterSettings.trouterServiceUrl=n.Dod_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.Dod_RegistrarServiceUrl);break;case X0.AirGap08:this._trouterSettings.trouterServiceUrl=n.AirGap08_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap08_RegistrarServiceUrl);break;case X0.AirGap09:this._trouterSettings.trouterServiceUrl=n.AirGap09_TrouterServiceUrl,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap09_RegistrarServiceUrl)}if(t)this.setConfigOrDefault(t?.SkypeCalling,this._JsCsaConfig),this.setConfigOrDefault(t?.MDN_TRAP,this._MDNTrapSettings),this.setConfigOrDefault(t?.SkypeWebMedia?.mediaAgent,this._JamaSettings),this.setConfigOrDefault(t?.TrouterJScriptClient,this._TrouterJScriptClient);else if(e?.identityType===t2.Enterprise)i?(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(r.Enterprise_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(r.Enterprise_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(r.Enterprise_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[r.Enterprise_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[r.Enterprise_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=r.Enterprise_MdnTrapRelayTurnUrl_EUDB):(this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Enterprise_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Enterprise_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Enterprise_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Enterprise_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Enterprise_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=n.Enterprise_MdnTrapRelayTurnUrl);else switch(e?.cloudType){case X0.Public:i&&(this._trouterSettings.trouterServiceUrl=r.Public_TrouterServiceUrl_EUDB,this._trouterSettings.registrarServiceUrl=this._acsProxy.proxyfyUrl(r.Public_RegistrarServiceUrl_EUDB),this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(r.Public_ConversationServiceUrl_EUDB),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceUrl_EUDB),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(r.Public_MdnTrapServiceTokenUrl_EUDB),this._MDNTrapSettings.Relay.Skype.fqdns=[r.Public_MdnTrapRelaySkypeFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.fqdns=[r.Public_MdnTrapRelayTurnFqdns_EUDB],this._MDNTrapSettings.Relay.Turn.url=r.Public_MdnTrapRelayTurnUrl_EUDB);break;case X0.GccHigh:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.GccHigh_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.GccHigh_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.GccHigh_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[n.GccHigh_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[n.GccHigh_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=n.GccHigh_MdnTrapRelayTurnUrl;break;case X0.Dod:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.Dod_ConversationServiceUrl),this._MDNTrapSettings.Service.url=this._acsProxy.proxyfyUrl(n.Dod_MdnTrapServiceUrl),this._MDNTrapSettings.Service.tokenUrl=this._acsProxy.proxyfyUrl(n.Dod_MdnTrapServiceTokenUrl),this._MDNTrapSettings.Relay.Skype.fqdns=[n.Dod_MdnTrapRelaySkypeFqdns],this._MDNTrapSettings.Relay.Turn.fqdns=[n.Dod_MdnTrapRelayTurnFqdns],this._MDNTrapSettings.Relay.Turn.url=n.Dod_MdnTrapRelayTurnUrl;break;case X0.AirGap08:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap08_ConversationServiceUrl);break;case X0.AirGap09:this._JsCsaConfig.conversationServiceUrl=this._acsProxy.proxyfyUrl(n.AirGap09_ConversationServiceUrl)}}static assertConfigs(e){let t=[];if(e?.SkypeCalling||t.push(`SkypeCalling`),e?.MDN_TRAP||t.push(`MDN_TRAP`),e?.SkypeWebMedia?e?.SkypeWebMedia?.mediaAgent||t.push(`SkypeWebMedia.mediaAgent`):t.push(`SkypeWebMedia`),e?.TrouterJScriptClient||t.push(`TrouterJScriptClient`),t.length>0)throw new Y({defaultError:J.CALL_STACK.FOUND_UNDEFINED_CONFIGS,defaultErrorMessageArgs:[t.join(`, `)]})}},_Le,i9={exports:{}},a9={exports:{}};a9.exports;function vLe(){return _Le||(_Le=1,e=a9,a9.exports,t=()=>{return e={659:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toJson=t.fetchWithTimeout=void 0,t.fetchWithTimeout=function(e,t){var n,r=new Promise((function(t,r){fetch(e).then((function(e){n!==void 0&&clearTimeout(n),t(e)})).catch((function(e){n!==void 0&&clearTimeout(n),r(e)}))}));if(t!==0){var i=new Promise((function(r,i){n=setTimeout(i,t,Error(`Fetch for '${e.url}' timed out`))}));return Promise.race([r,i])}return r},t.toJson=function(e){try{return JSON.stringify(e)}catch{return`Unable to serialize object of type ${typeof e}`}}},912:function(e,t,n){var r,i=this&&this.__extends||(r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},r(e,t)},function(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);function n(){this.constructor=e}r(e,t),e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}),a=this&&this.__assign||function(){return a=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},a.apply(this,arguments)},o=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},s=this&&this.__generator||function(e,t){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},typeof Symbol==`function`&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){o=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(s[0]===6&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.createRegistrarClient=t.RegistrarClient=void 0;var c=n(659),l=[`skype`,`aad`,`cae`],u=function(e){function t(t){var n=e.call(this,t)||this;return n.name=`CancelationError`,n}return i(t,e),t}(Error),d=function(){function e(t,n,r){this.logger=t,this.maxBackoffInMs=n,this.initialDelay=r,this.backoffCount=0,this.id=++e.idCounter}return e.prototype.delay=function(e){var t=this;if(this.timerHandle!==void 0)throw Error(`Retry sequence logical failure`);if(this.backoffCount===-1)return new Promise((function(e,t){t(new u(`Cancelled`))}));var n=this.calculateNextBackoffMs();return this.backoffCount++,this.logger.info(`[RegistrarClient] Backing off ${e} for ${n} milliseconds with ID ${this.id}`),new Promise((function(r,i){t.cancelFunc=i,t.timerHandle=setTimeout((function(){t.logger.info(`[RegistrarClient] Back off for ${e} with ID ${t.id} complete`),t.timerHandle=void 0,r()}),n)}))},e.prototype.cancel=function(){this.timerHandle!==void 0&&(this.logger.debug(`Resetting back off`),clearTimeout(this.timerHandle),this.cancelFunc!==void 0&&this.cancelFunc(new u(`Cancelled`))),this.backoffCount=-1},e.prototype.calculateNextBackoffMs=function(){var e=1+.4*(Math.random()-.5),t=this.initialDelay*2**this.backoffCount*e;return t=Math.round(t),Math.min(this.maxBackoffInMs,t)},e.idCounter=0,e}(),f=function(){function e(e,t,n){this.logger=e,this.tokenProvider=t,this.options=n,this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN=15,this.DEFAULT_MAX_BACKOFF_TIME_IN_MS=3e5,this.backoffs={},this.maxBackOffTime=this.options.maxRetryDelayMs>0?this.options.maxRetryDelayMs:this.DEFAULT_MAX_BACKOFF_TIME_IN_MS,this.maxRetriesForGetToken=n.maxRetriesForGetToken===void 0||n.maxRetriesForGetToken===null?this.DEFAULT_MAX_RETRIES_FOR_GET_TOKEN:n.maxRetriesForGetToken,this.proxyUrlRewrite=n.proxyUrlRewrite??function(e){return e}}return e.prototype.register=function(e,t){return o(this,void 0,void 0,(function(){return s(this,(function(n){switch(n.label){case 0:return[4,this.performRegistration(e,t)];case 1:return n.sent(),this.cachedRegistrationParams=[e,t],[2]}}))}))},e.prototype.unregister=function(){return o(this,void 0,void 0,(function(){var e;return s(this,(function(t){switch(t.label){case 0:return this.logger.info(`[RegistrarClient] sending unregister request`),e=new Request(this.proxyUrlRewrite(`${this.options.registrarUrl}/${this.options.registrationId}`),{method:`DELETE`,mode:`cors`,headers:new Headers(a(a({},this.options.extraRegistrationHeaders),{accept:`application/json, text/javascript`}))}),[4,this.callRegistrar(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.cancelPendingRequests=function(){var e=this;Object.keys(this.backoffs).forEach((function(t){e.backoffs[t].cancel()})),this.backoffs={}},e.prototype.resendRegistration=function(){return o(this,void 0,void 0,(function(){return s(this,(function(e){switch(e.label){case 0:if(!this.cachedRegistrationParams)throw Error(`Re-registration failed because there is no registration parameters cached`);return[4,this.performRegistration(this.cachedRegistrationParams[0],this.cachedRegistrationParams[1])];case 1:return e.sent(),[2]}}))}))},e.prototype.performRegistration=function(e,t){return o(this,void 0,void 0,(function(){var n,r;return s(this,(function(i){switch(i.label){case 0:return this.logger.info(`[RegistrarClient] Sending register request`),n={clientDescription:e,registrationId:this.options.registrationId,nodeId:``,transports:t},r=new Request(this.proxyUrlRewrite(this.options.registrarUrl),{method:`POST`,mode:`cors`,headers:new Headers(a(a({},this.options.extraRegistrationHeaders),{"content-type":`application/json`,accept:`application/json, text/javascript`})),body:(0,c.toJson)(n)}),[4,this.callRegistrar(r)];case 1:return i.sent(),[2]}}))}))},e.prototype.startBackoff=function(){var e=new d(this.logger,this.maxBackOffTime,this.options.initialRetryDelayMs);return this.backoffs[e.id]=e,e},e.prototype.stopBackoff=function(e){e.cancel(),delete this.backoffs[e.id]},e.prototype.getToken=function(e){return o(this,void 0,void 0,(function(){var t,n,r,i,a,o,c;return s(this,(function(s){switch(s.label){case 0:t=this.startBackoff(),n=0,s.label=1;case 1:return s.trys.push([1,3,,8]),this.logger.info(`[RegistrarClient] Asking for a new token`),[4,this.tokenProvider({needFresh:!0,supportedTokenTypes:l,wwwAuthenticateHeader:e,purpose:`registrar`})];case 2:return r=s.sent(),this.stopBackoff(t),[2,r];case 3:i=s.sent(),s.label=4;case 4:return s.trys.push([4,6,,7]),n++,a=JSON.stringify(i),n>this.maxRetriesForGetToken?(o=`[RegistrarClient] getToken retry limit hit. Will not retry now. Error: ${a}`,this.logger.error(o),this.stopBackoff(t),[2,Promise.reject(o)]):(this.logger.warn(`[RegistrarClient] Retrying for a new token. Retry Count: ${n} Error: ${a}`),[4,t.delay(`Fetching a new token`)]);case 5:return s.sent(),[3,8];case 6:throw c=s.sent(),this.stopBackoff(t),c;case 7:return[3,8];case 8:return[3,1];case 9:return[2]}}))}))},e.prototype.callRegistrar=function(e){return o(this,void 0,void 0,(function(){var t,n,r,i,a,o,u,d,f,p,m,h,g,_,v;return s(this,(function(s){switch(s.label){case 0:return t=this.startBackoff(),[4,this.tokenProvider({needFresh:!1,supportedTokenTypes:l,wwwAuthenticateHeader:void 0,purpose:`registrar`})];case 1:n=s.sent(),this.setTokenHeader(e,n),r=0,s.label=2;case 2:i=void 0,s.label=3;case 3:return s.trys.push([3,10,,15]),a=e.clone(),[4,(0,c.fetchWithTimeout)(a,this.options.requestTimeoutMs)];case 4:return(i=s.sent()).status===401?++r>this.maxRetriesForGetToken?(o=`[RegistrarClient] getSkypeToken retry limit hit. Will not retry now. Request '${e.url}' failed with ${i.status} ${i.statusText}`,this.logger.error(o),this.stopBackoff(t),[2,Promise.reject(o)]):(this.logger.warn(`[RegistrarClient] Retry Count ${r}. Request '${e.url}' failed with ${i.status} ${i.statusText}`),u=i.headers?.get(`www-authenticate`)??void 0,d=this.setTokenHeader,f=[e],[4,this.getToken(u)]):[3,8];case 5:return d.apply(this,f.concat([s.sent()])),r>1?[4,t.delay(`Registrar call retry after 401`)]:[3,7];case 6:s.sent(),s.label=7;case 7:return[3,21];case 8:if(i.status>=500&&i.status<600)throw Error(`Fetch for '${e.url}' failed with ${i.status} ${i.statusText}`);s.label=9;case 9:return[3,15];case 10:p=s.sent(),this.logger.error(`[RegistrarClient] Request failed with ${p}`),s.label=11;case 11:return s.trys.push([11,13,,14]),[4,t.delay(`Registrar call retry`)];case 12:return s.sent(),[3,21];case 13:throw m=s.sent(),this.logger.error(`[RegistrarClient] Request cancelled`),this.stopBackoff(t),m;case 14:return[3,15];case 15:return this.stopBackoff(t),i.ok?[2,i]:[3,16];case 16:h=void 0,s.label=17;case 17:return s.trys.push([17,19,,20]),_=(g=JSON).stringify,[4,i.json()];case 18:return h=_.apply(g,[s.sent()]),[3,20];case 19:return s.sent(),h=`no details`,[3,20];case 20:throw v=`Fetch for '${e.url}' failed with ${i.status} ${i.statusText} (${h}, MS-CV: ${i.headers?.get(`MS-CV`)})`,this.logger.error(`[RegistrarClient] ${v}`),Error(v);case 21:return[3,2];case 22:return[2]}}))}))},e.prototype.setTokenHeader=function(e,t){switch(e.headers.delete(`X-Skypetoken`),e.headers.delete(`Authorization`),e.headers.delete(`X-MS-Migration`),t.tokenType.toLowerCase()){case`skype`:e.headers.set(`X-Skypetoken`,t.token);break;case`aad`:case`cae`:e.headers.set(`Authorization`,`Bearer ${t.token}`);break;default:throw Error(`unsupported token type: ${t.tokenType}`)}!1===this.options.usingLegacyTokenApi&&e.headers.set(`X-MS-Migration`,`True`)},e}();t.RegistrarClient=f,t.createRegistrarClient=function(e,t,n){return new f(e,t,n)}}},t={},function n(r){var i=t[r];if(i!==void 0)return i.exports;var a=t[r]={exports:{}};return e[r].call(a.exports,a,a.exports,n),a.exports}(912);var e,t},e.exports=t()),a9.exports;var e,t}var yLe;i9.exports;function bLe(){return yLe||(yLe=1,e=i9,i9.exports,t=e=>(()=>{var t={10:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManagerFsm=void 0;var r=n(234),i=n(423),a=n(642),o=n(573);t.TrouterManagerFsm=function(){function e(e,t){this.worker=t,this.state=i.TrouterManagerState.Unknown,this.logger=new a.Logger(`ManagerFsm`,e)}return e.prototype.start=function(){this.state===i.TrouterManagerState.Unknown?(this.setState(i.TrouterManagerState.Disconnected),this.worker.forceStopLingeringConnection(),this.worker.startFirstConnection()):(this.logger.info(`start called in state '${i.TrouterManagerState[this.state]}', expediting pending backoffs, if any`),this.worker.expediteBackoffOnConnections())},e.prototype.stop=function(e){this.state===i.TrouterManagerState.Unknown?this.showIgnored(`stop`):(this.setState(i.TrouterManagerState.Unknown),this.worker.stopFirstConnection(!0===e),this.worker.stopSecondConnection(!0===e))},e.prototype.getState=function(){switch(this.state){case i.TrouterManagerState.Unknown:case i.TrouterManagerState.Connected:case i.TrouterManagerState.Disconnected:case i.TrouterManagerState.Switching:return this.state;case i.TrouterManagerState.TerminalError:return r.TrouterState.Disconnected}},e.prototype.getInternalState=function(){return this.state},e.prototype.onConnected=function(e){this.state===i.TrouterManagerState.Disconnected&&e?this.worker.doesSecondConnectionExist()?this.setState(i.TrouterManagerState.Switching):(this.setState(i.TrouterManagerState.Connected),this.worker.dispatchConnected()):this.showIgnored(`onConnected(${e})`)},e.prototype.onRegistered=function(e){this.state!==i.TrouterManagerState.Disconnected||e?this.state!==i.TrouterManagerState.Switching||e?this.state===i.TrouterManagerState.Disconnected&&e&&(this.setState(i.TrouterManagerState.Connected),this.worker.dispatchConnected()):(this.setState(i.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnectionDelayed(),this.worker.dispatchConnected()):(this.setState(i.TrouterManagerState.Connected),this.worker.switchConnections(),this.worker.stopSecondConnection(!0),this.worker.dispatchConnected()),this.worker.dispatchRegistrationState(!0)},e.prototype.onUnregistered=function(e){e&&this.worker.dispatchRegistrationState(!1)},e.prototype.onReconnecting=function(e){this.state!==i.TrouterManagerState.Connected&&this.state!==i.TrouterManagerState.Switching||!e?this.showIgnored(`onReconnecting(${e})`):(this.setState(i.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected())},e.prototype.onReconnectionRequired=function(e,t,n){this.state===i.TrouterManagerState.Connected&&e?(this.setState(i.TrouterManagerState.Switching),this.worker.startSecondConnection(t)):this.state===i.TrouterManagerState.Disconnected&&e?this.worker.startSecondConnection(t):this.state===i.TrouterManagerState.Switching&&e&&n===o.ReconnectReason.Configuration?(this.logger.debug(`onReconnectionRequired: switch requested while already in Switching state`),this.worker.stopSecondConnection(!0),this.worker.startSecondConnection(t)):this.showIgnored(`onReconnectionRequired(${e})`)},e.prototype.onDisconnected=function(e){this.state==i.TrouterManagerState.Unknown&&e?this.worker.dispatchDisconnected():this.state==i.TrouterManagerState.Switching&&e?(this.worker.switchConnections(),this.worker.stopSecondConnection(!1),this.setState(i.TrouterManagerState.Disconnected),this.worker.dispatchDisconnected()):this.showIgnored(`onDisconnected(${e})`)},e.prototype.onTerminalError=function(){this.setState(i.TrouterManagerState.TerminalError),this.worker.dispatchTerminalError()},e.prototype.showIgnored=function(e){this.logger.info(`Ignoring event '${e}' in state '${i.TrouterManagerState[this.state]}'`)},e.prototype.setState=function(e){this.logger.info(`Switching from state '${i.TrouterManagerState[this.state]}' to state '${i.TrouterManagerState[e]}'`),this.state===e?this.logger.error(`Attempt to switch to the current state '${i.TrouterManagerState[e]}'`):this.state=e},e}()},107:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExponentialBackoff=void 0,t.ExponentialBackoff=function(){function e(e,t,n){n===void 0&&(n={tolerance:2,minimumWaitMs:1e4}),this.logger=e,this.maxBackoffInMs=t,this.gapDetectionSettings=n,this.backoffId=0,this.backoffCount=0}return e.calculateNextBackoffMs=function(e,t){var n=1+.4*(Math.random()-.5),r=1e3*2**e*n;return r=Math.round(r),Math.min(t,r)},e.prototype.setMaxBackoffMs=function(e){this.maxBackoffInMs=e},e.prototype.backoff=function(t,n){var r=this;if(this.timerHandle!==void 0&&(this.logger.debug(`Clearing current back off`),clearTimeout(this.timerHandle),this.timerHandle=void 0),this.previousCompleteTime!==void 0){var i=Date.now()-this.previousCompleteTime;i>this.maxBackoffInMs*this.gapDetectionSettings.tolerance&&i>this.gapDetectionSettings.minimumWaitMs&&(this.logger.info(`Back off for ${t} with ID ${this.backoffId} will be reset due to a lot of time having passed since the previous backoff (${i} ms)`),this.backoffCount=0,this.previousCompleteTime=void 0)}var a=e.calculateNextBackoffMs(this.backoffCount,this.maxBackoffInMs);this.backoffId++,this.backoffCount++,this.logger.info(`Backing off ${t} for ${a} milliseconds with ID ${this.backoffId}`),this.callback=function(e,i){(function(e,t,n){if(e===void 0||t===void 0)return!1;var r=Date.now()-e;return r>t*n.tolerance&&r>n.minimumWaitMs})(e,i,r.gapDetectionSettings)&&(r.logger.info(`Back off for ${t} with ID ${r.backoffId} will be reset due to the wait (${Date.now()-(e??0)} ms) being longer than expected (${i} ms)`),r.backoffCount=0),r.logger.info(`Back off for ${t} with ID ${r.backoffId} complete, invoking handler`),r.timerHandle=void 0,r.callback=void 0,r.previousCompleteTime=Date.now(),n()};var o=Date.now();this.timerHandle=setTimeout((function(){return r.callback?.call(r,o,a)}),a)},e.prototype.reset=function(){this.timerHandle!==void 0&&(this.logger.debug(`Resetting back off with ID ${this.backoffId}`),clearTimeout(this.timerHandle),this.timerHandle=void 0,this.callback=void 0),this.backoffCount=0},e.prototype.expediteIfPending=function(){if(this.backoffCount=0,this.timerHandle!==void 0){this.logger.debug(`Expediting back off with ID ${this.backoffId}`),clearTimeout(this.timerHandle),this.timerHandle=void 0;var e=this.callback;this.callback=void 0,e&&e()}},e}()},220:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.addCacheAsBackupTo=function(e){var t,i=this;return function(a){return n(i,void 0,void 0,(function(){return r(this,(function(n){return a&&(t=void 0),[2,new Promise((function(n,r){e(a).then((function(e){t=e,n(e)})).catch((function(e){t!==void 0&&t.length>0&&n(t),r(e)}))}))]}))}))}}},234:(e,t)=>{var n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterState=t.UserActivityState=void 0,function(e){e[e.Unknown=0]=`Unknown`,e[e.Active=1]=`Active`,e[e.Inactive=2]=`Inactive`}(n||(t.UserActivityState=n={})),function(e){e[e.Unknown=0]=`Unknown`,e[e.Connected=2]=`Connected`,e[e.Disconnected=3]=`Disconnected`,e[e.Switching=9]=`Switching`}(r||(t.TrouterState=r={}))},235:function(e,t,n){var r=this&&this.__spreadArray||function(e,t,n){if(n||arguments.length===2)for(var r,i=0,a=t.length;i<a;i++)!r&&i in t||(r||=Array.prototype.slice.call(t,0,i),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.LoggingManagerConsumer=t.RegistrationEnforcer=void 0;var i=n(335);t.RegistrationEnforcer=function(){function e(e,t,n){this.wrapped=e,this.shouldConnectionDependOnRegistration=t,this.shouldHoldBackEvents=n,this.isRegistered=!1,this.heldBackEvents=[]}return e.prototype.onDownstreamRequest=function(e,t,n){this.passIfRegisteredOrNotNeeded(`onDownstreamRequest`,e,t,n)},e.prototype.onConnected=function(e){this.passIfRegisteredOrNotNeeded(`onConnected`,e)},e.prototype.onRegistered=function(e){this.isRegistered=!0,this.wrapped.onRegistered(e),this.fireHeldBackEvents()},e.prototype.onUnregistered=function(e){var t=this.isRegistered;this.isRegistered=!1,this.wrapped.onUnregistered(e),t&&e.getState()===i.State.Connected&&this.shouldConnectionDependOnRegistration()&&e.forceReconnectDueToNoRegistration()},e.prototype.onReconnecting=function(e){this.wrapped.onReconnecting(e)},e.prototype.onReconnectIsRequired=function(e,t,n){this.wrapped.onReconnectIsRequired(e,t,n)},e.prototype.onDisconnected=function(e){this.isRegistered=!1,this.dropHeldBackEvents(),this.wrapped.onDisconnected(e)},e.prototype.onTerminalError=function(e){this.wrapped.onTerminalError(e)},e.prototype.onConnectionParametersUpdated=function(e){this.wrapped.onConnectionParametersUpdated(e)},e.prototype.onTrouterMessageLost=function(e){this.passIfRegisteredOrNotNeeded(`onTrouterMessageLost`,e)},e.prototype.onUserActivityStateAccepted=function(e){this.passIfRegisteredOrNotNeeded(`onUserActivityStateAccepted`,e)},e.prototype.onAudiencesSetResolved=function(e,t){this.passIfRegisteredOrNotNeeded(`onAudiencesSetResolved`,e,t)},e.prototype.getState=function(){return this.wrapped.getState()},e.prototype.holdBackEvent=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];this.heldBackEvents.push({kind:e,args:t})},e.prototype.passIfRegisteredOrNotNeeded=function(e){for(var t,n=[],i=1;i<arguments.length;i++)n[i-1]=arguments[i];var a=this.shouldConnectionDependOnRegistration(),o=this.shouldHoldBackEvents();a&&o||this.fireHeldBackEvents(a?function(e){return e.kind!==`onConnected`}:void 0),this.isRegistered||!a||!1===o&&e!==`onConnected`?(t=this.wrapped)[e].apply(t,n):this.holdBackEvent.apply(this,r([e],n,!1))},e.prototype.fireHeldBackEvents=function(e){for(var t,n=0,r=this.heldBackEvents;n<r.length;n++){var i=r[n];(e===void 0||e(i))&&(t=this.wrapped)[i.kind].apply(t,i.args)}this.heldBackEvents=e===void 0?[]:this.heldBackEvents.filter((function(t){return!e(t)}))},e.prototype.dropHeldBackEvents=function(){this.heldBackEvents=[]},e}(),t.LoggingManagerConsumer=function(){function e(e,t,n,r){this.wrapped=e,this.prefix=t,this.logger=n,this.onEventAction=r}return e.prototype.onEvent=function(e,t){this.onEventAction===void 0?(this.logger??console).log(`${this.prefix} TracingEnforcer: ${e}(${t})`):this.onEventAction(e,t)},e.prototype.onDownstreamRequest=function(e,t,n){this.onEvent(`onDownstreamRequest`,JSON.stringify({request:t,response:n})),this.wrapped.onDownstreamRequest(e,t,n)},e.prototype.onConnected=function(e){this.onEvent(`onConnected`,e.getState().toString()),this.wrapped.onConnected(e)},e.prototype.onRegistered=function(e){this.onEvent(`onRegistered`,e.getState().toString()),this.wrapped.onRegistered(e)},e.prototype.onUnregistered=function(e){this.onEvent(`onUnregistered`,e.getState().toString()),this.wrapped.onUnregistered(e)},e.prototype.onReconnecting=function(e){this.onEvent(`onReconnecting`,e.getState().toString()),this.wrapped.onReconnecting(e)},e.prototype.onReconnectIsRequired=function(e,t,n){this.onEvent(`onReconnectIsRequired`,JSON.stringify({connection:e.getState().toString(),useConnectParamsFromCache:t,reason:n})),this.wrapped.onReconnectIsRequired(e,t,n)},e.prototype.onDisconnected=function(e){this.onEvent(`onDisconnected`,e.getState().toString()),this.wrapped.onDisconnected(e)},e.prototype.onTerminalError=function(e){this.onEvent(`onTerminalError`,JSON.stringify({connection:e})),this.wrapped.onTerminalError(e)},e.prototype.onConnectionParametersUpdated=function(e){this.onEvent(`onConnectionParametersUpdated`,JSON.stringify({connectParams:e})),this.wrapped.onConnectionParametersUpdated(e)},e.prototype.onTrouterMessageLost=function(e){this.onEvent(`onTrouterMessageLost`,JSON.stringify({flowTags:e})),this.wrapped.onTrouterMessageLost(e)},e.prototype.onUserActivityStateAccepted=function(e){this.onEvent(`onUserActivityStateAccepted`,JSON.stringify({cv:e})),this.wrapped.onUserActivityStateAccepted(e)},e.prototype.onAudiencesSetResolved=function(e,t){this.onEvent(`onAudiencesSetResolved`,JSON.stringify({audienceSubscriptionsResponse:e,cv:t})),this.wrapped.onAudiencesSetResolved(e,t)},e.prototype.getState=function(){return this.wrapped.getState()},e}()},335:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterFsm=t.State=void 0;var r,i,a=n(423),o=n(642),s=n(902);(function(e){e[e.Initial=0]=`Initial`,e[e.RetrievingToken=1]=`RetrievingToken`,e[e.Allocating=2]=`Allocating`,e[e.Handshaking=3]=`Handshaking`,e[e.Connecting=4]=`Connecting`,e[e.AnonymousConnecting=5]=`AnonymousConnecting`,e[e.WebsocketAuthenticating=6]=`WebsocketAuthenticating`,e[e.Connected=7]=`Connected`,e[e.Unregistering=8]=`Unregistering`,e[e.TerminalError=9]=`TerminalError`})(r||(t.State=r={})),function(e){e[e.Initial=0]=`Initial`,e[e.Registering=1]=`Registering`,e[e.RegisteringButResendPending=2]=`RegisteringButResendPending`,e[e.Retrying=3]=`Retrying`,e[e.Registered=4]=`Registered`,e[e.RegistrationDisabled=5]=`RegistrationDisabled`}(i||={}),t.TrouterFsm=function(){function e(e,t,n,a){this.worker=t,this.incallModeEnabled=n,this.protocolSelector=a,this.state=r.Initial,this.autoReconnect=!0,this.logger=new o.Logger(`ConnectionFsm`,e),this.registrationState=i.Initial}return e.prototype.getState=function(){return this.state},e.prototype.isActive=function(){return this.state===r.Allocating||this.state===r.Connected||this.state===r.Handshaking||this.state===r.Connecting||this.state===r.RetrievingToken||this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating},e.prototype.isConnecting=function(){return this.state===r.Allocating||this.state===r.Handshaking||this.state===r.Connecting||this.state===r.AnonymousConnecting},e.prototype.start=function(){return this.state===r.Initial?(this.setState(r.RetrievingToken),this.worker.getToken(!0,!1,void 0),!0):(this.showIgnored(`start`),!1)},e.prototype.stop=function(e,t){e&&(this.registrationState=i.Initial),this.worker.isIncallMode()&&this.worker.exitIncallMode(),this.worker.resetTokenBackoff(),this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.state===r.Connected&&this.worker.sendDisconnectTelemetryEvent(`connection stopped`),this.registrationState!==i.Registered&&this.registrationState!==i.Registering&&this.registrationState!==i.RegisteringButResendPending||this.state===r.Unregistering?t?(this.setState(r.TerminalError),this.worker.dispatchTerminalError()):(this.setState(r.Initial),this.worker.dispatchDisconnected()):(this.registrationState=i.Initial,this.setState(r.Unregistering),this.worker.sendUnregisterRequest())},e.prototype.onTokenReceived=function(e,t,n){this.state===r.RetrievingToken?(0,s.usedProtocolAfterFallback)(this.protocolSelector(e.tokenType,n),t)===`v4c`?(this.setState(r.AnonymousConnecting),this.worker.startConnectionTimer(),this.worker.connectV4c(e,t)):(this.setState(r.Allocating),this.worker.startConnectionTimer(),this.worker.sendAllocateRequest(e)):this.showIgnored(`onTokenReceived`)},e.prototype.checkConnection=function(e){e&&this.onPingInterval()},e.prototype.onAllocationSucceed=function(e){return this.state===r.Allocating&&this.registrationState===i.Registered&&this.worker.dispatchUnregistered(),this.state===r.Allocating?(this.setState(r.Handshaking),this.registrationState=i.Initial,this.worker.startSocketIo(e),!0):(this.showIgnored(`onAllocationSucceed`),!1)},e.prototype.onAllocationFailed=function(e,t){this.state===r.Allocating?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!e,claimsChallenge:t}):this.showIgnored(`onAllocationFailed`)},e.prototype.onV4cConnectivityCheckFailed=function(){this.state===r.AnonymousConnecting?this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0}):this.showIgnored(`onV4cConnectivityCheckFailed`)},e.prototype.onV4cException=function(){this.state!==r.AnonymousConnecting&&this.state!==r.WebsocketAuthenticating||(this.logger.error(`v4c exception, falling back to longpoll`),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`v4c-websocket-failure`}}))},e.prototype.onConnectingTimeout=function(){this.state===r.Allocating||this.state===r.Connecting||this.state===r.Handshaking||this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating?this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0}):this.showIgnored(`onConnectingTimeout`)},e.prototype.onConnecting=function(){this.state===r.Handshaking?this.setState(r.Connecting):this.showIgnored(`onConnecting`)},e.prototype.onSocketConnect=function(e){this.state===r.AnonymousConnecting?(this.setState(r.WebsocketAuthenticating),this.worker.sendV4cAuthenticationEvent(e)):this.showIgnored(`onSocketConnect`)},e.prototype.onConnectingFailed=function(){this.state===r.Connecting?this.onConnectingTimeout():this.state===r.Handshaking?(this.logger.error(`Unexpected error in Socket.io - no valid transports`),this.onConnectingTimeout()):this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating?(this.logger.info(`/v4/c falling back to longpoll`),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`v4c-websocket-failure`}})):this.showIgnored(`onConnectingFailed`)},e.prototype.onSocketDisconnect=function(e){this.state===r.Handshaking||this.state===r.Connected||this.state===r.WebsocketAuthenticating?(this.state===r.Connected&&this.worker.sendDisconnectTelemetryEvent(e?.toTelemetryString()),this.state===r.WebsocketAuthenticating&&this.worker.countDisconnectBeforeConnectionEstablishment(),e?.reason===`skypetoken-deprecated`?(this.logger.error(`Skypetoken deprecated response, not retrying any further`),this.onTerminalError()):this.cleanUpAndInitiateReconnect({backoff:this.state!==r.Connected&&e?.reason!==`dup`,allowCachedToken:e?.reason!==`unauthorized`,claimsChallenge:e?.claims})):this.showIgnored(`onSocketDisconnect`)},e.prototype.onTrouterConnected=function(){this.state===r.Connecting||this.state===r.WebsocketAuthenticating?(this.setState(r.Connected),this.worker.resetTokenBackoff(),this.worker.stopConnectionTimer(),this.worker.sendUserActivityState(a.UserActivityEventReason.Connected,!0),this.worker.startPingTimer(),this.worker.dispatchConnected(),this.worker.shouldSkipRegistration()?(this.registrationState=i.RegistrationDisabled,this.worker.dispatchRegistered()):(this.registrationState=i.Registering,this.worker.sendRegisterRequest())):this.showIgnored(`onTrouterConnected`)},e.prototype.onReconnectRequired=function(e,t,n){this.state===r.AnonymousConnecting||this.state===r.WebsocketAuthenticating?n===void 0||n.target!==`host`||n.url===void 0||n.url===``?(this.logger.error(`unexpected reconnect arguments: ${n?.target} ${n?.url}, reconnecting without cache`),this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`redirect-no-host`}})):this.cleanUpAndInitiateReconnect({backoff:!0,allowCachedToken:!0,fallbackReason:{kind:`redirect`,host:n.url}}):this.worker.dispatchReconnectIsRequired(e,t)},e.prototype.disableAutoReconnect=function(){this.autoReconnect=!1},e.prototype.onDownstreamRequest=function(e){this.state===r.Connected?(this.switchToIncallModeIfEnabled(),this.worker.dispatchDownstreamRequest(e)):this.showIgnored(`onDownstreamRequest`)},e.prototype.onTrouterMessageLost=function(e){this.state===r.Connected?this.worker.dispatchTrouterMessageLost(e):this.showIgnored(`onTrouterMessageLost`)},e.prototype.onPingInterval=function(){this.state===r.Connected?this.worker.sendPingRequest():this.showIgnored(`onPingInterval`)},e.prototype.onPingResponseTimeout=function(){this.onMissedResponse(`onPingResponseTimeout`)},e.prototype.onPingResponse=function(){this.state===r.Connected||this.showIgnored(`onPingResponse`)},e.prototype.onRegistrationFailed=function(){this.state===r.Connected&&this.registrationState===i.Registering?(this.worker.dispatchUnregistered(),this.registrationState=i.Retrying,this.worker.startRegistrationRetryTimer()):this.state===r.Connected&&this.registrationState===i.RegisteringButResendPending?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRegistrationFailed`)},e.prototype.onRetryRegistration=function(){this.state===r.Connected&&this.registrationState===i.Retrying?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRetryRegistration`)},e.prototype.onRegistrationSucceeded=function(){this.state===r.Connected&&this.registrationState===i.Registering?(this.registrationState=i.Registered,this.worker.dispatchRegistered(),this.worker.startRegistrationTimer()):this.state===r.Connected&&this.registrationState===i.RegisteringButResendPending?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRegistrationSucceeded`)},e.prototype.onRegistrationNearExpiry=function(){this.state===r.Connected&&this.registrationState===i.Registered?(this.registrationState=i.Registering,this.worker.sendRegisterRequest()):this.showIgnored(`onRegistrationNearExpiry`)},e.prototype.onUnregistrationDone=function(){this.state===r.Unregistering?(this.setState(r.Initial),this.worker.dispatchUnregistered(),this.worker.dispatchDisconnected()):this.showIgnored(`onUnregistrationDone`)},e.prototype.onResendRegistration=function(){this.worker.dispatchUnregistered(),this.state===r.Connected&&this.registrationState===i.Registered?(this.registrationState=i.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.state===r.Connected&&this.registrationState===i.Registering&&(this.registrationState=i.RegisteringButResendPending)},e.prototype.onExtraTransportsUpdated=function(){this.state===r.Connected?this.registrationState===i.Registered?(this.registrationState=i.Registering,this.worker.stopRegistrationTimer(),this.worker.sendRegisterRequest()):this.registrationState===i.Registering&&(this.registrationState=i.RegisteringButResendPending):this.state===r.Unregistering||this.state===r.Initial?this.logger.warn(`onExtraTransportsUpdated called while Trouter is stopped, will not be applied until it is next started`):(this.logger.info(`extra transports will be registered when Trouter successfully connects`),this.showIgnored(`onExtraTransportsUpdated`))},e.prototype.onIncallModeTimer=function(){this.worker.exitIncallMode(),this.state===r.Connected?(this.worker.stopPingTimer(),this.worker.startPingTimer()):this.showIgnored(`onIncallModeTimer`)},e.prototype.onSetNewUserActivityState=function(){this.worker.sendUserActivityState(a.UserActivityEventReason.Modified,this.state===r.Connected)},e.prototype.onActivityStateResponseTimeout=function(){this.onMissedResponse(`onActivityStateResponseTimeout`)},e.prototype.forceReconnect=function(e){this.state===r.Connected&&this.worker.sendDisconnectTelemetryEvent(e),this.worker.resetTokenBackoff(),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})},e.prototype.onTerminalError=function(){this.logger.error(`Cannot proceed, reached terminal state. Switching from state '${r[this.state]}' to ${r[r.TerminalError]}`),this.stop(!0,!0),this.setState(r.TerminalError)},e.prototype.onMissedResponse=function(e){this.state===r.Connected?(this.worker.sendDisconnectTelemetryEvent(e),this.cleanUpAndInitiateReconnect({backoff:!1,allowCachedToken:!0})):this.showIgnored(e)},e.prototype.showIgnored=function(e){this.logger.debug(`Ignoring event '${e}' in state '${r[this.state]}'`)},e.prototype.setState=function(e){this.logger.info(`Switching from state '${r[this.state]}' to state '${r[e]}'`),this.state===e?this.logger.error(`Attempt to switch to the current state '${r[e]}'`):this.state=e},e.prototype.switchToIncallModeIfEnabled=function(){this.incallModeEnabled&&(this.worker.isIncallMode()||(this.worker.enterIncallMode(),this.worker.stopPingTimer(),this.worker.startPingTimer()),this.worker.restartIncallModeTimer())},e.prototype.cleanUpAndInitiateReconnect=function(e){if(!this.autoReconnect)return this.logger.info(`Automatic reconnect is disabled, stopping this connection`),void this.stop(!0);this.worker.cancelPendingRegistrationRequests(),this.worker.stopConnectionTimer(),this.worker.stopPingTimer(),this.worker.clearSentEventTimers(),this.worker.stopRegistrationTimer(),this.worker.stopSocketIo(),this.setState(r.RetrievingToken),this.worker.dispatchReconnecting(),this.worker.getToken(e.allowCachedToken,e.backoff,e.claimsChallenge,e.fallbackReason)},e}()},396:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectionTracker=t.Properties=t.TrackerStep=t.ClientEventName=t.ResponseData=void 0;var r,i=n(659),a=n(509),o=n(642);t.ResponseData=function(e){this.id=e,this.status=200,this.headers={},this.body=``},function(e){e.Connected=`trouter_js_client_connected`,e.Disconnected=`trouter_js_client_disconnected`,e.Error=`trouter_js_client_error`,e.Progress=`trouter_js_client_progress`,e.Response=`trouter_js_client_response`,e.CheckConnection=`trouter_js_client_check_connection`}(r||(t.ClientEventName=r={}));var s=function(e,t,n,r,i){this.stepName=e,this.operation=t,this.delta=n,this.ts=r,this.error=i};t.TrackerStep=s,t.Properties=function(){};var c=function(){this.numberOfPingReplies=0,this.connectedTimestamp=0,this.isNewUrl=!1,this.transportType=``,this.connectionNumber=0},l=function(){this.enabled=!1,this.numberOfStepsToMaintain=40,this.logHealthCheckError=!1,this.sendProgressTimeoutSecs=55,this.logSendPingError=!1,this.maxBackoffInMs=12e4,this.trouter_js_client_connected=!1,this.trouter_js_client_disconnected=!1,this.trouter_js_client_error=!1,this.trouter_js_client_progress=!1,this.trouter_js_client_response=!1,this.trouter_js_client_request=!1,this.trouter_js_client_registration=!1,this.trouter_js_client_unregistration=!1,this.trouter_js_client_check_connection=!0};t.ConnectionTracker=function(){function e(e,t,n,r,a,s,u){this.clientId=t,this.clientInfo=n,this.getServerState=r,this.endpointId=a,this.clientCorrelationID=s,this.environment=u,this.logger=new o.Logger(`ConnectionTracker`,e),this.clientCorrelationID=s===void 0?``:s,this.steps=[],this.connectionAttempt=0,this.totalStepCount=0,this.beginTimestamp=new i.Timespan,this.eventLogSettings=new l,this.connectedInfo=new c}return e.prototype.enable=function(e){this.eventLogSettings.enabled=!0,this.eventLogger=e},e.prototype.disable=function(){this.eventLogSettings.enabled=!1},e.prototype.sendProgress=function(e){this.steps.length>0&&this.sendTelemetry(r.Progress,e,this.steps)},e.prototype.cancelProgressTimer=function(){this.progressTimeout!==void 0&&(clearTimeout(this.progressTimeout),this.progressTimeout=void 0)},e.prototype.resetProgressSendTimer=function(){var e=this;this.cancelProgressTimer(),this.eventLogSettings.sendProgressTimeoutSecs!==void 0&&this.eventLogSettings.sendProgressTimeoutSecs>0&&(this.progressTimeout=setTimeout((function(){e.sendProgress({reason:`timeout`,timeoutSecs:e.eventLogSettings.sendProgressTimeoutSecs})}),1e3*this.eventLogSettings.sendProgressTimeoutSecs))},e.prototype.setConnectedInfo=function(e,t){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=Date.now(),this.connectedInfo.isNewUrl=e,this.connectedInfo.transportType=t,++this.connectedInfo.connectionNumber},e.prototype.clearConnectedInfo=function(){this.connectedInfo.numberOfPingReplies=0,this.connectedInfo.connectedTimestamp=0,this.connectedInfo.isNewUrl=!0,this.connectedInfo.transportType=``},e.prototype.copyProperties=function(e,t){for(var n=0,r=Object.keys(t);n<r.length;n++){var i=r[n];t[i]!==void 0&&(e[i.replace(/-/g,`_`)]={value:t[i]})}},e.prototype.increasePingResponseCount=function(){++this.connectedInfo.numberOfPingReplies},e.prototype.sendTelemetry=function(e,t,n){try{if(!0===this.eventLogSettings.enabled&&!0===this.eventLogSettings[e]&&this.eventLogger!==void 0){var r=this.getServerState(),o={name:e,properties:{connectionAttempt:{value:this.connectionAttempt},epid:{value:this.endpointId},clientCorrelationID:{value:this.clientCorrelationID},steps:{value:(0,i.toJson)(n)},clientID:{value:this.clientId},eventVersion:{value:3},environment:{value:this.environment},cv:{value:a.CLIENT_VERSION},ua:{value:this.clientInfo.ua},connectionId:{value:r.connectionId},connectedClientId:{value:r.connectedClientId},domId:{value:r.domId},url:{value:r.url},ttlInSecs:{value:r.getRemainingTtlInSec()},numberOfPingReplies:{value:this.connectedInfo.numberOfPingReplies},connectedTimestamp:{value:this.connectedInfo.connectedTimestamp},isNewUrl:{value:this.connectedInfo.isNewUrl},transportType:{value:this.connectedInfo.transportType},connectionNumber:{value:this.connectedInfo.connectionNumber}}};this.copyProperties(o.properties,t),this.eventLogger.logEvent(o)}}catch(t){this.logger.warn(`error in sending event ${e}: ${(0,i.toJson)(t)}`)}},e.prototype.createStep=function(e,t,n){return new s(e,t,this.beginTimestamp.duration,Date.now(),n)},e.prototype.addStep=function(e,t,n){if(!1!==this.eventLogSettings.enabled&&(this.steps.length===0&&this.beginTimestamp.reset(),this.steps.push(this.createStep(e,t,n)),++this.totalStepCount,this.eventLogSettings.numberOfStepsToMaintain!==void 0&&this.steps.length>this.eventLogSettings.numberOfStepsToMaintain)){var i=this.steps.slice(0);this.steps.length=0,this.sendTelemetry(r.Progress,{reason:`flush`},i)}},e.prototype.trackStart=function(e){this.addStep(e,`start`)},e.prototype.trackEnd=function(e){this.addStep(e,`end`)},e.prototype.trackError=function(e,t,n,i){n===void 0&&(n=!0),e===`health`&&!0!==this.eventLogSettings.logHealthCheckError||e===`ping`&&!1===this.eventLogSettings.logSendPingError||(i===void 0&&(i=`error`),!0===n&&this.addStep(e,i,t),this.sendTelemetry(r.Error,{},[this.createStep(e,i,t)]))},e.prototype.trackProgress=function(e,t){this.addStep(e,t)},e.prototype.trackConnected=function(e,t){this.setConnectedInfo(e,t);var n=this.steps.slice(0),i=this.totalStepCount,a=this.beginTimestamp.duration;this.steps.length=0,this.totalStepCount=0,this.sendTelemetry(r.Connected,{stepCount:n.length,totalStepCount:i,connectionEstablishmentMs_Total:a},n),this.cancelProgressTimer()},e.prototype.getSessionLength=function(){return Date.now()-this.connectedInfo.connectedTimestamp},e.prototype.trackDisconnected=function(e){e.sessionLengthMS=this.getSessionLength(),this.sendTelemetry(r.Disconnected,e,[]),this.resetProgressSendTimer()},e.prototype.trackNewConnection=function(){++this.connectionAttempt},e.prototype.trackResponse=function(e,t,n,a){var o={};a!==void 0&&(o.hasError=!0,o.error=a);try{o.responseTimestamp=n===void 0?Date.now():n.sentTS,e&&(o.requestID=e.id,o.httpMethod=e.method,o.shortUrl=(0,i.anonymizeShortUrl)(e.shortUrl),o.correlationVector=e.correlationVector,o.requestHeaders=(0,i.headersToLog)(e.headers)),n&&(o.latencyMS=t,o.responseCode=n.status,o.responseLength=n.body.length)}catch(e){o.hasError=!0,o.error=`${o.error} error creating response context ${(0,i.toJson)(e)}`}this.sendTelemetry(r.Response,o,[])},e.prototype.sendResponseError=function(e,t,n){this.trackResponse(t,void 0,n,e)},e.prototype.close=function(){this.sendProgress({reason:`closed`}),this.steps.length=0,this.cancelProgressTimer()},e.prototype.mergeSettings=function(e){if(e){this.eventLogSettings.numberOfStepsToMaintain=Math.min(40,Math.max(10,e.numberOfStepsToMaintain===void 0?0:e.numberOfStepsToMaintain));var t=Math.min(3600,Math.max(55,e.sendProgressTimeoutSecs===void 0?0:e.sendProgressTimeoutSecs));this.eventLogSettings.logHealthCheckError=e.logHealthCheckError,this.eventLogSettings.logSendPingError=e.logSendPingError;for(var n=0,i=Object.keys(r).map((function(e){return r[e]}));n<i.length;n++){var a=i[n];e[a]!==void 0&&(this.eventLogSettings[a]=e[a])}this.eventLogSettings.sendProgressTimeoutSecs!==t&&(this.eventLogSettings.sendProgressTimeoutSecs=t,this.resetProgressSendTimer())}},e}()},423:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManagerState=t.UserActivityEventReason=t.ServerState=void 0;var r,i,a=n(659);t.ServerState=function(){function e(e,t,n,r,i,a){this.connectionId=e,this.connectedClientId=t,this.domId=n,this.url=r,this.c2cUrlBase=i,this.expirationTsSec=a}return e.prototype.getRemainingTtlInSec=function(){return(0,a.calculateTtlInSec)(this.expirationTsSec)},e}(),function(e){e[e.Unknown=0]=`Unknown`,e[e.Modified=1]=`Modified`,e[e.Snapshot=2]=`Snapshot`,e[e.Connected=3]=`Connected`}(r||(t.UserActivityEventReason=r={})),function(e){e[e.Unknown=0]=`Unknown`,e[e.Connected=2]=`Connected`,e[e.Disconnected=3]=`Disconnected`,e[e.Switching=9]=`Switching`,e[e.TerminalError=10]=`TerminalError`}(i||(t.TrouterManagerState=i={}))},509:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.USER_AUTHENTICATE_EVENT_NAME=t.SUPPORTED_TOKEN_TYPES=t.FAILED_MESSAGE_ACK=t.UNHANDLED_MESSAGE_ACK=t.HANDLED_MESSAGE_ACK=t.CLIENT_VERSION=t.constants=void 0,t.constants={TROUTER_INIT:`trouterinit`,TROUTER_READY_EVENT:`trouterReadyEvent`,TROUTER_READY_TIMEOUT:`trouterReadyTimeout`,TROUTER_TOKEN_REQUEST:`trouterTokenRequest`,TROUTER_TOKEN_GET_SUCCEEDED:`trouterTokenGetSucceeded`,TROUTER_TOKEN_GET_FAILED:`trouterTokenGetFailed`,TROUTER_RECONNECTING:`trouterReconnecting`,RENEWAL:`renewal`,NEW_CONNECTION:`newConnection`,ENDPOINT_REGISTRATION_FAILED:`endpointRegistrationFailed`,SUBSCRIPTIONS_DEFAULT_SCOPE:`defaultScope`},t.CLIENT_VERSION=`2026.03.01.8`,t.HANDLED_MESSAGE_ACK=200,t.UNHANDLED_MESSAGE_ACK=404,t.FAILED_MESSAGE_ACK=500,t.SUPPORTED_TOKEN_TYPES=[`skype`,`aad`,`cae`],t.USER_AUTHENTICATE_EVENT_NAME=`user.authenticate`},573:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},a=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterConnection=t.ReconnectReason=void 0;var o,s=n(673),c=n(659),l=n(396),u=n(509),d=n(764),f=n(107),p=n(234),m=n(423),h=n(642),g=n(902),_=n(335),v=n(705),y=n(983),b=function(){this.cv=u.CLIENT_VERSION,this.ua=``,this.hr=``,this.v=``},x=function(){function e(){this[`force new connection`]=!0,this.reconnect=!1,this.query=``,this.ackTimeoutMs=5e3}return e.prototype.rewriteUrlForProxy=function(e){return e},e}(),S=`MS-CV`,C=function(){function e(e,t){this.logger=t,this.cvCounter=0;var n=JSON.parse(e);this.startTS=this.safeJsonNumber(n,`startTS`,0),this.url=this.safeJsonString(n,`url`,``),this.shortUrl=this.safeJsonString(n,`shortUrl`,``),this.body=this.safeJsonString(n,`body`,``),this.headers=this.safeJsonRecord(n,`headers`,{}),this.id=this.safeJsonNumber(n,`id`,-1),this.method=this.safeJsonString(n,`method`,``),this.replied=!1,this.timedout=!1,this.receivedCv=this.headers[S],this.updateCvHeader()}return Object.defineProperty(e.prototype,"correlationVector",{get:function(){return this.receivedCv?`${this.receivedCv}.${this.cvCounter}`:``},enumerable:!1,configurable:!0}),e.prototype.on=function(e,t){e===`data`?this.dataCallback=t:e===`end`&&(typeof this.dataCallback==`function`&&this.dataCallback(this.body),t())},e.prototype.incrementCorrelationVector=function(){++this.cvCounter,this.updateCvHeader()},e.prototype.updateCvHeader=function(){var e=this.correlationVector;e&&(this.headers[S]=e)},e.prototype.safeJsonNumber=function(e,t,n){var r;if(e!=null&&Object.prototype.hasOwnProperty.call(e,t)){var i=e;if(typeof i[t]==`number`)return i[t];if(typeof i[t]==`string`)return parseFloat(i[t]);(r=this.logger)==null||r.warn(`unexpected type of '${t}': ${typeof i[t]}`)}return n},e.prototype.safeJsonString=function(e,t,n){var r;if(e!=null&&Object.prototype.hasOwnProperty.call(e,t)){var i=e;if(typeof i[t]==`string`)return i[t];(r=this.logger)==null||r.warn(`unexpected type of '${t}': ${typeof i[t]}`)}return n},e.prototype.safeJsonRecord=function(e,t,n){var r;if(e!=null&&Object.prototype.hasOwnProperty.call(e,t)){var i=e;if(typeof i[t]==`object`)return i[t];(r=this.logger)==null||r.warn(`unexpected type of '${t}': ${typeof i[t]}`)}return n},e}(),w=function(){function e(e,t,n){this.request=e,this.responseData=t,this.sendResponse=n}return e.prototype.writeHead=function(e,t){this.responseData.status=e,this.responseData.headers=t},e.prototype.write=function(e){this.responseData.body+=e},e.prototype.end=function(e){return e&&(this.responseData.body+=e),this.sendResponse(this.request,this.responseData)},e}(),T=function(e){this.name=e,this.args={},this.timeoutTimerId=0};(function(e){e[e.Configuration=0]=`Configuration`,e[e.ServerInitiated=1]=`ServerInitiated`})(o||(t.ReconnectReason=o={}));var E=function(){function e(e,t,n,r,i,a,o,c){var d,p=this;this.logProvider=e,this.options=t,this.manager=n,this.tokenProvider=r,this.usingLegacyTokenApi=i,this.protocolSelector=o,this.audienceSubscriptionState=c,this.WEBSOCKET_TRANSPORT_NAME=`websocket`,this.XHR_POLLING_TRANSPORT_NAME=`xhr-polling`,this.AUDIENCE_SUBSCRIPTION_RESULT_ERROR=`Error`,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED=`Unsubscribed`,this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT=`Timeout`,this.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST=`BadRequest`,this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX=/&audienceSubscriptionState=[^&]*|^audienceSubscriptionState=[^&]*&?/,this.USER_ACTIVITY_QUERY_PARAM_REGEX=/userActivity=[^&]*/,this.connectionId=``,this.inIncallMode=!1,this.connectionAttempt=0,this.connectedClientId=``,this.isNavigatorOnline=!0,this.onNavigatorOnlineStatusUpdateBound=this.onNavigatorOnlineStatusUpdate.bind(this),this.c2cUrlBase=``,this.connectingErrorsInRow=0,this.connectivityCheckFailuresInARow=0,this.unauthorizedErrorCount=0,this.pendingSentEventTimers={},this.extraTransports={},this.clientDescriptionOverride={},this.lastDisconnectReason=``,this.UNKNOWN_TRANSPORT=`unknown_transport`,this.connectingErrorsThreshold=3,this.pendingAudienceSubscription=void 0,this.areSubscriptionsEqual=function(e,t){if(e.length!==t.length)return!1;e=e.sort((function(e,t){return e.id.localeCompare(t.id)})),t=t.sort((function(e,t){return e.id.localeCompare(t.id)}));for(var n=0;n<e.length;n++)if(e[n].id!==t[n].id)return!1;return!0},this.logger=new h.Logger(`Connection`,e),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff=new f.ExponentialBackoff(this.logger,this.timeoutOptions.maxBackoffMs),this.clientID=Date.now(),typeof window<`u`&&window.location&&(this.domId=window.location.hostname);var m=new b;m.cv=u.CLIENT_VERSION,m.ua=``,(d=this.options)!=null&&d.clientInfo&&(m.ua=this.safeString(this.options.clientInfo.ua),m.v=this.safeString(this.options.clientInfo.v)),this.clientInfo=m,this.connectionTracker=new l.ConnectionTracker(e,this.clientID,this.clientInfo,(function(){return p.getServerState()}),this.options.endpointId,this.options.clientCorrelationID,this.options.environment),this.applyConnectionTrackerOptions(t);var g=this.options.incallModeTimeoutMs>0;if(this.fsm=new _.TrouterFsm(e,this,g,this.protocolSelector),t.registration&&!t.registration.useRegistrarUrlFromAllocate){var v={registrarUrl:t.registration.registrarUrl,proxyUrlRewrite:t.rewriteUrlForProxy,registrationId:t.registration.registrationId,requestTimeoutMs:t.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:t.timeoutOptions.maxBackoffMs,usingLegacyTokenApi:this.usingLegacyTokenApi,maxRetriesForGetToken:t.retryLimitOnTokenFetch,extraRegistrationHeaders:t.extraConnectionHeaders};this.registrarClient=(0,s.createRegistrarClient)(e,this.tokenProvider,v)}this.userActivityState=a}return e.prototype.start=function(e,t,n){this.logger.info(`Starting`),this.reconnectParams=e,this.extraTransports=t??{},this.clientDescriptionOverride=n??{},typeof window<`u`&&window.navigator&&window.addEventListener?(this.isNavigatorOnline=window.navigator.onLine,window.addEventListener(`online`,this.onNavigatorOnlineStatusUpdateBound),window.addEventListener(`offline`,this.onNavigatorOnlineStatusUpdateBound),this.logger.debug(`Registered for browser online notifications - current state: ${this.isNavigatorOnline}`)):this.isNavigatorOnline=!0,this.fsm.start()},e.prototype.stop=function(e){this.logger.info(`Stopping`),typeof window<`u`&&window.navigator&&(window.removeEventListener(`online`,this.onNavigatorOnlineStatusUpdateBound),window.removeEventListener(`offline`,this.onNavigatorOnlineStatusUpdateBound)),this.fsm.stop(e),this.connectionTracker.close()},e.prototype.configure=function(e){var t=this.options.trouterUrl!==e.trouterUrl;this.options=e,this.applyConnectionTrackerOptions(e),t&&(this.logger.info(`Configuration changed. Reconnection required.`),this.fsm.onReconnectRequired(!1,o.Configuration))},e.prototype.checkConnection=function(e){this.logger.info(`checkConnection called with ${e}`),this.fsm.checkConnection(e),e&&this.connectionTracker.sendTelemetry(l.ClientEventName.CheckConnection,{disconnectDetected:e},[])},e.prototype.disableRegistrationsAndAutoReconnect=function(){this.stopRegistrationTimer(),this.cancelPendingRegistrationRequests(),this.fsm.disableAutoReconnect()},e.prototype.getServerState=function(){return new m.ServerState(this.connectionId,this.connectedClientId,this.domId?this.domId:``,this.allocateResult?this.allocateResult.surl:``,this.c2cUrlBase,this.connectionExpireTimestampInSecs)},e.prototype.getState=function(){return this.fsm.getState()},e.prototype.getToken=function(e,t,n,r,i){var a=this;i===void 0&&(i=0),this.logger.info(`Getting token ${t?`with backoff`:`without backoff`}`);var o=function(){a.connectionTracker.trackStart(`token`);var t={needFresh:!e,wwwAuthenticateHeader:n,supportedTokenTypes:u.SUPPORTED_TOKEN_TYPES,purpose:`trouter`};a.logger.info(`Requesting token: needFresh=${t.needFresh} types=[${u.SUPPORTED_TOKEN_TYPES}], wwwAuthenticateHeader is ${t.wwwAuthenticateHeader?`non empty`:`empty`}`),a.tokenProvider(t).then((function(e){a.logger.debug(`${e.tokenType} token is received`),a.connectionTracker.trackEnd(`token`),a.fsm.onTokenReceived(e,r,a.reconnectParams)})).catch((function(t){var o=(0,c.toJson)(t.stack);if(a.logger.error(`Getting token failed, will retry after timeout. Error: ${o}`),a.connectionTracker.trackError(`token`,o),!a.canRetryTokenFetchRequest(i+a.unauthorizedErrorCount))return a.connectionTracker.trackError(`token`,`getToken retry limit hit, reached terminal error state`),a.resetTokenBackoff(),void a.fsm.onTerminalError();a.getToken(e,!0,n,r,i+1)}))};t?this.tokenBackoff.backoff(`getting token`,o):(this.resetTokenBackoff(),o())},e.prototype.startConnectionTimer=function(){var e=this;this.stopConnectionTimer(),this.logger.debug(`Starting connection timeout for ${this.timeoutOptions.connectionTimeoutMs} ms`),this.connectionTimeoutId=setTimeout((function(){e.logger.info(`Connection timeout is fired`),e.fsm.onConnectingTimeout()}),this.timeoutOptions.connectionTimeoutMs)},e.prototype.stopConnectionTimer=function(){this.connectionTimeoutId&&=(this.logger.debug(`Stopping connection timeout`),clearTimeout(this.connectionTimeoutId),void 0)},e.prototype.startPingTimer=function(){var e=this;this.transportTypeName===`websocket`?(this.logger.debug(`Starting ping timeout for ${this.timeoutOptions.pingTimeoutMs} ms`),this.pingTimerId=setInterval((function(){e.logger.info(`Ping interval fired`),e.fsm.onPingInterval()}),this.timeoutOptions.pingTimeoutMs)):this.logger.debug(`Not starting ping for transport ${this.transportTypeName}`)},e.prototype.stopPingTimer=function(){this.pingTimerId&&=(this.logger.debug(`Stopping ping timeout`),this.clearPingResponseTimer(),clearInterval(this.pingTimerId),void 0)},e.prototype.shouldSkipRegistration=function(){return this.options.registration===void 0},e.prototype.hasCustomRegistrationTtl=function(){return this.options.registration?.registrarTtlSec!==void 0&&this.options.registration?.registrarTtlSec!==0},e.prototype.startRegistrationTimer=function(){var e=this;this.stopRegistrationTimer();var t=this.getRegistrationTtl(),n=t[0],r=t[1];if(n<=30||!r)return this.logger.debug(`Starting registration expiration timer (TTL ${n} sec)`),void(this.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.logger.warn(`Registration expired but the connection is still alive. Should never happen`),e.dispatchUnregistered()}),1e3*n));var i=n-30;this.logger.debug(`Starting registration extension timer for ${i} sec`),this.registrationTimerId=setTimeout((function(){e.logger.info(`Registration extension timer fired`),e.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.logger.debug(`Registration extension did not happen in time`),e.dispatchUnregistered()}),3e4),e.fsm.onRegistrationNearExpiry()}),1e3*i)},e.prototype.startRegistrationRetryTimer=function(){var e=this;this.stopRegistrationTimer(),this.registrationTimerId=setTimeout((function(){e.registrationTimerId=void 0,e.fsm.onRetryRegistration()}),123e3)},e.prototype.stopRegistrationTimer=function(){this.registrationTimerId&&=(this.logger.debug(`Stopping registration timeout`),clearTimeout(this.registrationTimerId),void 0)},e.prototype.resendRegistration=function(){if(!this.registrarClient)throw Error(`Trouter Client not configured to handle registrations`);return this.fsm.onResendRegistration(),Promise.resolve()},e.prototype.registerExtraTransports=function(e,t){this.logger.info(`Registering ${Object.keys(e).length} extra transports`),this.extraTransports=e,this.clientDescriptionOverride=t??{},this.fsm.onExtraTransportsUpdated()},e.prototype.buildSocketIoUrlParams=function(e,t){if(!this.allocateResult)throw Error(`Allocate result is undefined in buildSocketIoUrlParams()`);for(var n={},r=this.allocateResult.connectparams,i=0,a=Object.keys(r);i<a.length;i++){var o=a[i];if(r[o]!==void 0){var s=r[o];typeof s==`string`||typeof s==`number`?n[o]=s:this.logger.error(`signatureData[${o}] has unsupported type ${typeof s}`)}}return n.v=`v4`,n.tc=encodeURI((0,c.toJson)(this.clientInfo)),n.timeout=this.timeoutOptions.pingTimeoutMs/1e3,n.auth=`true`,this.options.endpointId&&(n.epid=this.options.endpointId),e&&(n.userActivity=encodeURIComponent((0,c.toJson)(e))),t&&(n.audienceSubscriptionState=encodeURIComponent((0,c.toJson)(t))),this.appendConnectedClientIds(this.buildQuery(n),!0)},e.prototype.startSocketIo=function(e){if(this.logger.debug(`Starting socket io`),this.connectionTracker.trackStart(`connectSocket`),!this.allocateResult)throw Error(`Allocate result is undefined in startSocketIo()`);var t=this.options.ioOptions?r({},this.options.ioOptions):new x,n=this.userActivityState.state===p.UserActivityState.Unknown?void 0:this.userActivityState.increaseCvAndGetEventObject(),i=this.audienceSubscriptionState?.increaseCvAndGetEventObject();if(t[`force new connection`]=!0,t.reconnect=!1,t.rewriteUrlForProxy=this.options.rewriteUrlForProxy,t.requestHeaders=r(r({},this.options.extraConnectionHeaders),ee(e,this.usingLegacyTokenApi)),t.query=this.buildSocketIoUrlParams(n,i),this.logger.info(`connecting to ${this.allocateResult.socketio}`),this.stopSocketIo(),this.socket=(this.options.io??y).connect(this.allocateResult.socketio,t),this.socket===void 0)throw Error(`Can't create Socket.io object`);this.attachSocketIoHandlers(this.socket,e,n,i)},e.prototype.stopSocketIo=function(){if(this.socket){this.logger.debug(`clearing socket.io`);try{for(var e=0,t=[`connecting`,`connect`,`connect_failed`,`close_during_connecting`,`disconnect`,`reconnect`,`reconnect_failed`,`reconnecting`,`error`,`message`,`trouter.connected`,`trouter.reconnect`,`trouter.message_loss`,`audience.subscriptionresult`];e<t.length;e++){var n=t[e];this.socket.removeAllListeners(n)}this.socket.disconnect(),this.logger.debug(`cleared socket`),this.socket=void 0}catch(e){this.logger.error(`exception in disconnecting previous socket. Error: ${D(e)}`)}}},e.prototype.dispatchConnected=function(){this.logger.info(`dispatching connected`),this.manager.onConnected(this)},e.prototype.dispatchRegistered=function(){this.logger.info(`dispatching registered`),this.manager.onRegistered(this)},e.prototype.dispatchUnregistered=function(){this.logger.info(`dispatching unregistered`),this.manager.onUnregistered(this)},e.prototype.dispatchDownstreamRequest=function(e){var t=this;this.logger.debug(`dispatching downstream request`);try{var n=new w(e,new l.ResponseData(e.id),(function(e,n){return t.logger.debug(`sending response to downstream`),t.sendResponse(e,n)}));this.manager.onDownstreamRequest(this,e,n)}catch(e){this.logger.error(`exception in socket.on message. Error : ${D(e)}`)}},e.prototype.dispatchReconnecting=function(){this.logger.info(`dispatching reconnecting`),this.manager.onReconnecting(this)},e.prototype.dispatchReconnectIsRequired=function(e,t){this.logger.info(`dispatching reconnect is required by server`),this.manager.onReconnectIsRequired(this,e,t)},e.prototype.dispatchDisconnected=function(){this.logger.info(`dispatching disconnected`),this.manager.onDisconnected(this)},e.prototype.dispatchTerminalError=function(){this.logger.info(`dispatching terminal error`),this.manager.onTerminalError(this)},e.prototype.dispatchTrouterMessageLost=function(e){this.logger.info(`dispatching trouter message lost`),this.manager.onTrouterMessageLost(e)},e.prototype.countDisconnectBeforeConnectionEstablishment=function(){this.logger.warn(`counting disconnect before connection was fully established as a connection failure`),this.connectingErrorsInRow++,this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold()},e.prototype.sendProcessedDroppedIndicators=function(e){var t=this;try{this.logger.debug(`emitting processed flow tags to the server`);var n=new T(`trouter.processed_message_loss`);n.args={droppedIndicators:e},this.sendDownstreamEvent(n,(function(){t.logger.info(`emitted processed flow tags to the server`)}))}catch(e){var r=D(e);this.logger.error(`unable to send processed message loss event. Error: ${r}`),this.connectionTracker.trackError(`trouter.processed_message_loss`,r,!1)}},e.prototype.sendAllocateRequest=function(e){var t=this;this.connectionAttempt++,this.connectionTracker.trackNewConnection();var n,i=this.options.trouterUrl,a=this.reconnectParams,o=typeof a?.se==`string`?parseInt(a.se,10):typeof a?.se==`number`?a.se:void 0;o&&o<=Date.now()+36e5&&(this.logger.warn(`Dropping expired cached connection parameters: ${new Date(o)}`),this.reconnectParams=a=void 0),a&&a.serviceUrl!==i&&(this.logger.warn(`Dropping cached connection parameters for a different environment (${a.serviceUrl}, now ${i})`),this.reconnectParams=a=void 0),a!=null&&a.reconnectUrl&&(i=a.reconnectUrl),n=a?r(r({},a),{serviceUrl:void 0,reconnectUrl:void 0}):null,i=(0,g.adaptUrl)(i,`v4a`),i=this.appendCorrelationIds(i,!1),i=this.appendEndpointId(i,!1);var s=i=this.appendClientInfo(i,!1);n&&(i+=`&${this.buildQuery(n)}`,n.v||(i+=`&v=v4`)),i=this.options.rewriteUrlForProxy(i);var l=new Request(i,{method:`POST`,mode:`cors`,headers:new Headers(r(r({"Content-Type":`text/plain`},this.options.extraConnectionHeaders),ee(e,this.usingLegacyTokenApi)))});this.logger.info(`sendAllocateRequest: POST ${this.options.rewriteUrlForProxy(s)} (connectparams redacted)}`),this.connectionTracker.trackStart(`allocation`);var u,d=Date.now(),f=-1,p=!1;(0,c.fetchWithTimeout)(l,this.timeoutOptions.fetchTimeoutMs).then((function(e){if(f=e.status,!e.ok)throw u=e.headers.get(`www-authenticate`)??void 0,p=e.headers.get(`x-trouter-skypetoken-deprecated`)===`1`,t.logger.warn(`Allocation request got response status ${e.status}, www-authenticate header was ${u?`not empty`:`empty`}`),Error(e.statusText);var n=e.headers.get(`content-type`);if(!n||n!==`application/json`&&!n.startsWith(`application/json;`))throw Error(`Content-type '${n}' is unexpected`);return t.connectionTracker.trackEnd(`allocation`),e.json()})).then((function(n){t.unauthorizedErrorCount=0,t.onAllocationResponse(n,e)})).catch((function(e){t.connectingErrorsInRow++;var n=`${e}${f>=0?`, status code ${f}`:``}`;if(t.logger.error(`${t.connectingErrorsInRow} failed connecting attempt(s) in a row. ${n}`),t.connectionTracker.trackError(`allocation`,n),p){var r=`Skypetoken deprecated response, not retrying any further`;t.logger.error(r),t.connectionTracker.trackError(`allocation`,r),t.fsm.onTerminalError();return}if(f===401&&t.unauthorizedErrorCount++,!t.canRetryTokenFetchRequest(t.unauthorizedErrorCount))return r=`getToken retry limit hit, reached terminal error state`,t.connectionTracker.trackError(`allocation`,r),void t.fsm.onTerminalError();if(f!==-1||t.isNavigatorOnline){if(t.reconnectParams&&t.connectingErrorsInRow>=t.connectingErrorsThreshold){if(f>=400&&f<=599)t.resetReconnectParamsOnErrorThreshold();else if(t.reconnectParams.reconnectUrl&&t.connectingErrorsInRow%3==0){t.logger.warn(`${t.connectingErrorsInRow} connection attempts, testing nominal service URL`);var i=Math.min(t.timeoutOptions.connectionTimeoutMs-(Date.now()-d)-500,t.timeoutOptions.fetchTimeoutMs);t.testNominalUrlConnectivity(i).then((function(e){t.connectionTracker.trackProgress(`nomcheck`,e?`ok`:`failed`),e?(t.logger.warn(`Nominal service URL is reachable, erasing cached reconnect URL`),t.reconnectParams&&delete t.reconnectParams.reconnectUrl):t.logger.warn(`Nominal service URL is not reachable either, keeping cached reconnect URL`),t.fsm.onAllocationFailed(!1,void 0)}),(function(){t.fsm.onAllocationFailed(!1,void 0)}));return}}}else t.logger.info(`Expected failure, the browser says it is not online at the moment`);t.fsm.onAllocationFailed(f===401,u)}))},e.prototype.testNominalUrlConnectivity=function(e){var t,n=this;if(e<1e3)return this.logger.warn(`There is no time left to reasonably perform the nominal service URL connectivity check (${e} ms), falling back to assuming that the connectivity is fine`),Promise.resolve(!0);try{var r=new URL(this.options.trouterUrl);r.pathname=r.pathname.replace(/\/v4\/.*/,`/`),r.search=`?`+this.buildQuery({check:Date.now(),cor_id:encodeURIComponent(this.options.clientCorrelationID),epid:encodeURIComponent(this.options.endpointId?this.options.endpointId:``),tc:encodeURIComponent((0,c.toJson)(this.clientInfo))}),r.protocol===`wss:`&&(r.protocol=`https:`),t=new Request(this.options.rewriteUrlForProxy(r.toString()),{method:`GET`,headers:{Accept:`text/plain`}})}catch(e){return this.logger.warn(`Nominal service URL connectivity test request could not be created (${e}), falling back to assuming that the connectivity is fine`),Promise.resolve(!0)}return(0,c.fetchWithTimeout)(t,e).then((function(e){if(e.status!==200)throw Error(`Not 200 OK: ${e.status} ${e.statusText}`);return e.text()})).then((function(e){if(e!==`Trouter`)throw Error(`Not "Trouter": ${e.substring(0,16)}${e.length>16?`...`:``}`);return!0})).catch((function(e){return n.logger.error(`Nominal service URL connectivity test failed: ${e}`),!1}))},e.prototype.sendPingRequest=function(){var e=this;if(this.socket&&this.pingResponseTimerId===void 0)try{this.logger.debug(`emitting ping event`);var t=!1;this.socket.emit(`ping`,(function(){!0!==t&&e.onPingResponse()})),this.pingResponseTimerId=setTimeout((function(){e.logger.error(`Ping response timeout is fired`),t=!0,e.clearPingResponseTimer(),e.fsm.onPingResponseTimeout()}),this.timeoutOptions.pongTimeoutMs)}catch(e){var n=D(e);this.logger.error(`unable to send ping. Error: ${n}`),this.connectionTracker.trackError(`ping`,n,!1)}},e.prototype.connectV4c=function(e,t){return i(this,void 0,void 0,(function(){var n,i,o,s,c;return a(this,(function(a){switch(a.label){case 0:return[4,this.performV4cInitialConnectivityCheck()];case 1:if(!1===a.sent())return[2];(n=this.options.ioOptions?r({},this.options.ioOptions):new x)[`force new connection`]=!0,n.reconnect=!1,(c=this.reconnectParams)!=null&&c.serviceUrl&&(0,g.adaptUrl)(this.reconnectParams.serviceUrl,`v4c`)!==(0,g.adaptUrl)(this.options.trouterUrl,`v4c`)&&(this.logger.warn(`Dropping cached connection parameters for a different environment (${this.reconnectParams.serviceUrl}, now ${this.options.trouterUrl})`),this.reconnectParams=void 0),i=(0,g.redirectUrlIfPresent)(t)??(t?.kind===`redirect-no-host`?void 0:this.reconnectParams?.reconnectUrl)??this.options.trouterUrl,o=(0,g.adaptUrl)(i,`v4c`),n[`skipped handshake data`]={timeout:70,websocketUrl:o},n.query=this.buildV4cUrlParams(),n.rewriteUrlForProxy=this.options.rewriteUrlForProxy;try{if(this.stopSocketIo(),this.transportTypeName=`websocket`,this.socket=(this.options.io??y).connect(this.options.trouterUrl,n),this.socket===void 0)throw Error(`failed to create Socket.io object`);s=this.audienceSubscriptionState?.increaseCvAndGetEventObject(),this.attachSocketIoHandlers(this.socket,e,void 0,s)}catch(e){this.logger.error(`${e}`),this.connectionTracker.trackError(`v4c`,`${e}`),this.fsm.onV4cException()}return[2]}}))}))},e.prototype.performV4cInitialConnectivityCheck=function(){return i(this,void 0,void 0,(function(){return a(this,(function(e){switch(e.label){case 0:return this.options.initialConnectivityCheck?(this.logger.info(`checking connectivity to configured URL (go URL) before a connection attempt`),[4,this.testNominalUrlConnectivity(3e3)]):[2,!0];case 1:return e.sent()?(this.connectivityCheckFailuresInARow=0,[2,!0]):this.connectivityCheckFailuresInARow>=3?(this.connectivityCheckFailuresInARow=0,this.logger.error(`three connectivity checks failed in a row, will attempt with the fallback protocol`),this.fsm.onV4cException(),[2,!1]):(this.logger.warn(`connectivity check failed, will retry after backoff`),this.connectivityCheckFailuresInARow++,this.fsm.onV4cConnectivityCheckFailed(),[2,!1])}}))}))},e.prototype.sendV4cAuthenticationEvent=function(e){var t,n={headers:r(r({},this.options.extraConnectionHeaders),ee(e,this.usingLegacyTokenApi)),connectparams:(0,g.reconnectParamsWithoutUrls)(this.reconnectParams)};(t=this.socket)==null||t.emit(u.USER_AUTHENTICATE_EVENT_NAME,n)},e.prototype.setUserActivityState=function(e){var t=e.state!==this.userActivityState.state;this.userActivityState=e,t?(this.logger.info(`Changing user activity state to '${e.toEventJSON()}'`),this.fsm.onSetNewUserActivityState()):(this.logger.debug(`Not changing the same user activity state '${e.toEventJSON()}'`),this.manager.onUserActivityStateAccepted(e.correlationVector.value()))},e.prototype.sendUserActivityState=function(e,t){if(this.userActivityState.state!==p.UserActivityState.Unknown){if(this.options.updateUserActivityDuringConnectionAttempt&&this.socket){var n=this.userActivityState.toEventObject(),r=this.socket.socket.options.query;if(r){var i=`userActivity=${encodeURIComponent((0,c.toJson)(n))}`;r.search(this.USER_ACTIVITY_QUERY_PARAM_REGEX)==-1?this.socket.socket.options.query=r.concat(`&`,i):this.socket.socket.options.query=r.replace(this.USER_ACTIVITY_QUERY_PARAM_REGEX,i)}}this.transportTypeName===`websocket`&&t?e===m.UserActivityEventReason.Connected?this.sendUserActivityStateMultiple(2):this.sendUserActivityStateMultiple(1):this.transportTypeName===`xhr-polling`&&e===m.UserActivityEventReason.Modified&&this.fsm.forceReconnect(`user activity/force reconnect`)}},e.prototype.setAudienceSubscriptionsAsync=function(e,t){var n=this.audienceSubscriptionState;if(this.audienceSubscriptionState=e,this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME)return this.setAudienceSubscriptionsInternalAsync(e.increaseCvAndGetEventObject(),t);if(this.transportTypeName===this.XHR_POLLING_TRANSPORT_NAME){var r=this.setAudienceSubscriptionsLongpollInternalAsync(e.increaseCvAndGetEventObject(),t,n);return this.fsm.forceReconnect(`set audience subscription force reconnect`),r}throw Error(`set audience subscription executed on an unknown transport`)},e.prototype.setAudienceSubscriptionsUnsafeAsync=function(e){if(e)return this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME?this.setAudienceSubscriptionsInternalAsync(e,15e3):void 0},e.prototype.onAudienceSubscriptionResult=function(e){if(this.logger.info(`onAudienceSubscriptionResult`),this.pendingAudienceSubscription)return clearTimeout(this.pendingAudienceSubscription.timeoutId),this.pendingAudienceSubscription.audienceSetResolve(e),void(this.pendingAudienceSubscription=void 0);if(this.audienceSubscriptionState&&this.transportTypeName===this.XHR_POLLING_TRANSPORT_NAME){var t=new Set(this.audienceSubscriptionState.toListOfSubscriptions().map((function(e){return e.id}))??[]),n=this.audienceSubscriptionState.correlationVector.value();this.cleanPollingAudienceSubscriptionStateQueryParam(t,e,n),this.manager.onAudiencesSetResolved(e,n)}},e.prototype.setAudienceSubscriptionsInternalAsync=function(e,t){return i(this,void 0,void 0,(function(){var n,r,i=this;return a(this,(function(a){switch(a.label){case 0:return this.logger.info(`[WebSocket] Audience subscription set requested.`),(n=new T(`audience.subscribe`)).args=e,[4,new Promise((function(r){var a=!1,o=setTimeout((function(){return a=!0,r(i.buildAudienceSubscriptionsTimeoutResponse(e))}),t);i.sendDownstreamEvent(n,(function(e,t){a||(clearTimeout(o),i.logger.debug(`[Websocket] Audience subscription response: ${t}`),i.pendingAudienceSubscription&&i.onAudienceSubscriptionResult(t),r(t))}))}))];case 1:return r=a.sent(),this.manager.onAudiencesSetResolved(r,e.cv),[2,r]}}))}))},e.prototype.setAudienceSubscriptionsLongpollInternalAsync=function(e,t,n){return i(this,void 0,void 0,(function(){var r,i,o,s,c=this;return a(this,(function(a){switch(a.label){case 0:return this.logger.info(`[XHR Polling] Audience subscription set requested.`),this.pendingAudienceSubscription&&(this.logger.error(`Racing audience subscriptions occured. This situation resolves into undefined scenario and/or nasal demons.`),clearTimeout(this.pendingAudienceSubscription.timeoutId)),[4,new Promise((function(n){c.pendingAudienceSubscription={audienceSetResolve:n,timeoutId:setTimeout((function(){return c.pendingAudienceSubscription=void 0,n(c.buildAudienceSubscriptionsTimeoutResponse(e))}),t)}}))];case 1:return r=a.sent(),this.manager.getState()===p.TrouterState.Unknown||this.transportTypeName===this.WEBSOCKET_TRANSPORT_NAME||(this.logger.debug(`[XHR Polling] Audience subscription response: ${r}`),i=new Set(e.audiences.map((function(e){return e.id}))??[]),this.cleanPollingAudienceSubscriptionStateQueryParam(i,r,e.cv),o=this.handleAudienceUnsubscribeLongpoll(e,n),(s=r.responses).push.apply(s,o),this.manager.onAudiencesSetResolved(r,e.cv)),[2,r]}}))}))},e.prototype.cleanPollingAudienceSubscriptionStateQueryParam=function(e,t,n){var r=this,i=t.responses.filter((function(t){return t.result.audienceSubscriptionState===r.AUDIENCE_SUBSCRIPTION_RESULT_BAD_REQUEST&&e.has(t.audienceId)})),a=t.responses.filter((function(t){return t.result.audienceSubscriptionState===r.AUDIENCE_SUBSCRIPTION_RESULT_ERROR&&e.has(t.audienceId)})),o=t.responses.filter((function(t){return t.result.audienceSubscriptionState===r.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT&&e.has(t.audienceId)})),s=i.map((function(e){return e.audienceId})),c=a.map((function(e){return e.audienceId})),l=o.map((function(e){return e.audienceId})),u=Array.from(e).filter((function(e){return s.indexOf(e)===-1&&c.indexOf(e)===-1&&l.indexOf(e)===-1})).map((function(e){return{id:e}}));u.length===0?this.clearAudienceSubscriptionStateQueryParam():this.updateAudienceSubscriptionStateQueryParam(u,n)},e.prototype.clearAudienceSubscriptionStateQueryParam=function(){var e;(e=this.socket?.socket?.options)!=null&&e.query&&(this.socket.socket.options.query=this.socket.socket.options.query.replace(this.AUDIENCE_SUBSCRIPTION_STATE_QUERY_PARAM_REGEX,``))},e.prototype.updateAudienceSubscriptionStateQueryParam=function(e,t){if(this.socket?.socket?.options?.query){var n=encodeURIComponent(JSON.stringify({audiences:e,cv:t})),r=this.socket.socket.options.query,i=(0,v.updateAudienceSubscriptionQuery)(r,n);this.socket.socket.options.query=i}},e.prototype.handleAudienceUnsubscribeLongpoll=function(e,t){var n=[],r=t?.toListOfSubscriptions()??[],i=!this.areSubscriptionsEqual(r,e.audiences);if(r.length>0&&i&&t){var a=r.filter((function(t){return e.audiences.find((function(e){return e.id===t.id}))===void 0})),o=this.mapToSyntheticAudienceSubscriptionResponses(a,this.AUDIENCE_SUBSCRIPTION_RESULT_UNSUBSCRIBED,200);n.push.apply(n,o)}return n},e.prototype.buildAudienceSubscriptionsTimeoutResponse=function(e){return this.logger.error(`Audience subscription attempt has timed out.`),{responses:this.mapToSyntheticAudienceSubscriptionResponses(e.audiences,this.AUDIENCE_SUBSCRIPTION_RESULT_TIMEOUT)}},e.prototype.mapToSyntheticAudienceSubscriptionResponses=function(e,t,n){return e===void 0?[]:e.map((function(e){return{audienceId:e.id,result:{audienceSubscriptionState:t,responseStatus:n}}}))},e.prototype.expediteBackoff=function(){this.tokenBackoff.expediteIfPending()},e.prototype.sendRegisterRequest=function(){var e=this;if(!this.options.registration)throw Error(`Internal error - options.registration is undefined`);if(!this.allocateResult)throw Error(`Allocate result is undefined in sendRegisterRequest()`);if(this.options.registration.useRegistrarUrlFromAllocate&&!this.registrarClient){if(!this.allocateResult.registrarUrl)throw Error(`Internal error - useRegistrarUrlFromAllocate is true, but allocateResult did not include registrarUrl`);var t={registrarUrl:this.allocateResult.registrarUrl,proxyUrlRewrite:this.options.rewriteUrlForProxy,registrationId:this.options.registration.registrationId,requestTimeoutMs:this.options.timeoutOptions.fetchTimeoutMs,initialRetryDelayMs:1e3,maxRetryDelayMs:this.options.timeoutOptions.maxBackoffMs,usingLegacyTokenApi:this.usingLegacyTokenApi,maxRetriesForGetToken:this.options.retryLimitOnTokenFetch,extraRegistrationHeaders:this.options.extraConnectionHeaders};this.registrarClient=(0,s.createRegistrarClient)(this.logProvider,this.tokenProvider,t)}if(!this.registrarClient)throw Error(`Internal error - registrarClient is undefined`);this.logger.info(`sending register request with ${1+Object.keys(this.extraTransports).length} transports and ${Object.keys(this.clientDescriptionOverride).length} overridden client description properties`),this.connectionTracker.trackStart(`registration`);var n=this.getRegistrationTtl()[0];this.registrarClient.register(r({appId:this.options.registration.pnhAppId,aesKey:``,languageId:`en-US`,platform:this.options.registration.platform,templateKey:this.options.registration.pnhTemplateKey,platformUIVersion:this.options.registration.platformUIVersion,productContext:this.options.registration.productContext},this.clientDescriptionOverride),r({TROUTER:[{context:this.options.registration.context,path:this.allocateResult.surl,ttl:n}]},this.extraTransports)).then((function(){e.logger.info(`Register request successful`),e.connectionTracker.trackEnd(`registration`),e.fsm.onRegistrationSucceeded()})).catch((function(t){e.logger.error(`Register request failed. Error: ${t}`),e.connectionTracker.trackError(`registration`,O(t)),e.fsm.onRegistrationFailed()}))},e.prototype.sendUnregisterRequest=function(){var e=this;if(Object.keys(this.extraTransports).length>0&&this.logger.warn(`explicit unregister called while there are extra transports`),this.logger.info(`sending unregister request`),!this.options.registration||!this.registrarClient)throw Error(`Internal error - options.registration is undefined`);this.connectionTracker.trackStart(`unregistration`),this.registrarClient.unregister().then((function(){e.logger.info(`Unregister request successful`),e.connectionTracker.trackEnd(`unregistration`),e.fsm.onUnregistrationDone()})).catch((function(t){e.logger.error(`Unregister request failed. Error: ${t}`),e.connectionTracker.trackError(`unregistration`,O(t)),e.fsm.onUnregistrationDone()}))},e.prototype.resetTokenBackoff=function(){this.tokenBackoff.reset()},e.prototype.cancelPendingRegistrationRequests=function(){this.registrarClient&&this.registrarClient.cancelPendingRequests()},e.prototype.clearSentEventTimers=function(){var e=Object.keys(this.pendingSentEventTimers);if(e.length>0){this.logger.debug(`Clearing all pending downstream events related timers`);for(var t=0,n=e;t<n.length;t++){var r=n[t];this.clearSentEventTimer(Number(r))}}},e.prototype.restartIncallModeTimer=function(){var e=this;this.clearIncallModeTimerId(),this.logger.debug(`Restarting incall mode timer`),this.incallModeTimerId=setTimeout((function(){e.logger.info(`Call mode timer fired`),e.fsm.onIncallModeTimer()}),this.options.incallModeTimeoutMs)},e.prototype.enterIncallMode=function(){this.logger.info(`Entering incall mode`),this.timeoutOptions=this.options.incallTimeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!0},e.prototype.exitIncallMode=function(){this.logger.info(`Exiting incall mode`),this.clearIncallModeTimerId(),this.timeoutOptions=this.options.timeoutOptions,this.tokenBackoff.setMaxBackoffMs(this.timeoutOptions.maxBackoffMs),this.inIncallMode=!1},e.prototype.isIncallMode=function(){return this.inIncallMode},e.prototype.sendDisconnectTelemetryEvent=function(e){var t={reason:e,serverClosed:!this.fsm.isActive()};this.connectionTracker.trackDisconnected(t),this.connectionTracker.clearConnectedInfo()},e.prototype.forceReconnectDueToNoRegistration=function(){this.fsm.forceReconnect(`force reconnect due to no registration`)},e.prototype.resetReconnectParamsOnErrorThreshold=function(){this.logger.warn(`${this.connectingErrorsInRow} connection attempts, server-side failure: erasing cached connection parameters`),this.reconnectParams=void 0},e.prototype.onSocketConnecting=function(e){this.logger.info(`onSocketConnecting(${e})`),this.transportTypeName=e,this.connectionTracker.trackProgress(`connecting`,this.transportTypeName),this.fsm.onConnecting()},e.prototype.onSocketConnect=function(e){this.logger.info(`onSocketConnect`),this.fsm.onSocketConnect(e)},e.prototype.onSocketConnectFailed=function(e){this.logger.error(`onSocketConnectFailed`),this.connectionTracker.trackError(`connect_failed`,e,!0,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),this.fsm.onConnectingFailed()},e.prototype.onSocketDisconnect=function(e){var t=this.connectionTracker.getSessionLength()||0,n=d.DisconnectReason.fromRawReason(e);this.logger.error(`onSocketDisconnect, reason: ${n.reason}`),n.reason===`dup`&&this.lastDisconnectReason===`dup`&&t<this.options.duplicateDisconnectThresholdMs&&(this.logger.warn(`Socket was closed by server as Duplicate for the second time in a row after ${t} ms which is below the threshold of ${this.options.duplicateDisconnectThresholdMs} ms. Resetting cached connection parameters and making a new allocation.`),this.reconnectParams=void 0),this.lastDisconnectReason=n.reason,this.fsm.onSocketDisconnect(n),this.connectionExpireTimestampInSecs=void 0},e.prototype.onSocketReconnect=function(){this.logger.error(`onSocketReconnect`),this.fsm.onTrouterConnected()},e.prototype.onSocketReconnectFailed=function(e){this.logger.error(`onSocketReconnectFailed with '${e}'`),this.fsm.onSocketDisconnect(d.DisconnectReason.fromSocketIoEventData(`reconnecterror`,e))},e.prototype.onSocketReconnecting=function(){this.logger.error(`onSocketReconnecting`)},e.prototype.onSocketError=function(e){var t;this.logger.error(`onSocketError with '${(0,c.toJson)(e)}'`),this.fsm.isConnecting()&&(this.connectingErrorsInRow++,this.connectingErrorsInRow>=this.connectingErrorsThreshold&&this.resetReconnectParamsOnErrorThreshold()),this.connectionTracker.trackError(`connectSocket`,(t=e)!=null&&typeof t.toString==`function`?t.toString():`[${typeof t}]`),this.fsm.onSocketDisconnect(d.DisconnectReason.fromSocketIoEventData(`socketerror`,e))},e.prototype.onSocketMessage=function(e){var t,n=this;this.logger.debug(`onSocketMessage`);try{var r=(t=new C(e,this.logger)).headers?.[`X-Microsoft-Skype-Chain-ID`],i=r?` Chain-Id ${r}`:``;this.logger.info(`Received request N ${t.id}${i} CV ${t.correlationVector} to '${t.url}'`),t.startTS=Date.now(),t.url&&this.urlPath&&t.url.startsWith(this.urlPath)&&(t.shortUrl=t.url.substring(this.urlPath.length))}catch(e){var a=D(e);this.logger.error(`unable to parse request. Error: ${a}`),this.connectionTracker.sendResponseError(`unable to parse request, error: ${e}`);return}t.timeoutTimerId=setTimeout((function(){if(!t.replied){n.logger.error(`Request ${t.id} timed out`);var e=new l.ResponseData(t.id);e.status=504,e.headers={"Trouter-Responder":`ClientLib`},n.sendResponse(t,e),t.timedout=!0}}),this.timeoutOptions.requestTimeoutMs);try{this.fsm.onDownstreamRequest(t)}catch(e){this.logger.error(`exception in socket.on message. Error: ${D(e)}`),this.connectionTracker.sendResponseError(O(e),t,void 0)}},e.prototype.onTrouterConnected=function(e,t,n){var i,a,o=this;if((0,g.isV4ConnectEvent)(e)){var s=e;this.allocateResult=r(r({},s),{ttl:e.ttl.toString()}),this.populateAndCacheReconnectParams(s,s.reconnectUrl),this.populateConnectionStateFields(s)}else if(!this.allocateResult)return void this.logger.error(`Invalid internal state - received onTrouterConnected while allocateResult is not set`);this.connectingErrorsInRow=0,this.logger.info(`onTrouterConnected: ${this.allocateResult.surl}`),this.options.updateUserActivityDuringConnectionAttempt?this.transportTypeName===`xhr-polling`&&((t?.state??`unknown`)===this.userActivityState.getStateString()?t&&this.manager.onUserActivityStateAccepted(t.cv):(this.logger.info(`XHR user activity changed during connection attempt, from '${(0,c.toJson)(t)}' to '${this.userActivityState.toEventJSON()}', updating`),this.sendUserActivityStateIgnoreResponse())):this.transportTypeName===`xhr-polling`&&t&&this.manager.onUserActivityStateAccepted(t.cv),(i=this.socket?.socket?.options)!=null&&i.query&&(this.socket.socket.options.query+=`&connected=true`),this.urlPath=this.allocateResult.surl.replace(/https?:\/\/([A-z0-9\:\$\-\_\.\+\!\*\"\(\)\,]*)\//,`/`);var l=this.connectedUrl!==this.allocateResult.surl;this.connectedUrl=this.allocateResult.surl,this.connectionExpireTimestampInSecs=(0,c.calculateExpireTsInSec)((0,g.ensureNumber)(e.ttl)),this.connectionTracker.trackEnd(`connectSocket`),this.connectionTracker.trackConnected(l,this.transportTypeName?this.transportTypeName:this.UNKNOWN_TRANSPORT),(a=this.setAudienceSubscriptionsUnsafeAsync(n))==null||a.catch((function(e){return o.logger.error(`Re-subscribe to audiences has failed with ${e}`)})),this.fsm.onTrouterConnected()},e.prototype.onTrouterReconnect=function(e){var t=e.target;this.logger.info(`onTrouterReconnect target: ${t}`),t===`self`?this.fsm.onReconnectRequired(!0,o.ServerInitiated):this.fsm.onReconnectRequired(!1,o.ServerInitiated,e)},e.prototype.onTrouterMessageLoss=function(e){this.logger.debug(`onTrouterMessageLoss`),this.fsm.onTrouterMessageLost(e.droppedIndicators)},e.prototype.buildV4cUrlParams=function(){var e={};return e.tc=encodeURI((0,c.toJson)(this.clientInfo)),e.timeout=Math.floor(this.timeoutOptions.pingTimeoutMs/1e3),this.options.endpointId&&(e.epid=this.options.endpointId),this.appendConnectedClientIds(this.buildQuery(e),!0)},e.prototype.attachSocketIoHandlers=function(e,t,n,r){var i=this;e.on(`connecting`,(function(e){i.onSocketConnecting(e)})),e.on(`connect`,(function(){i.onSocketConnect(t)})),e.on(`connect_failed`,(function(e){i.onSocketConnectFailed(e)})),e.on(`close_during_connecting`,(function(e){i.onSocketConnectFailed(e)})),e.on(`disconnect`,(function(e){i.onSocketDisconnect(e)})),e.on(`reconnect`,(function(){i.onSocketReconnect()})),e.on(`reconnect_failed`,(function(e){i.onSocketReconnectFailed(e)})),e.on(`reconnecting`,(function(){i.onSocketReconnecting()})),e.on(`error`,(function(e){i.onSocketError(e)})),e.on(`message`,(function(e){i.onSocketMessage(e)})),e.on(`trouter.connected`,(function(e){i.onTrouterConnected(e,n,r)})),e.on(`trouter.reconnect`,(function(e){i.onTrouterReconnect(e)})),e.on(`trouter.message_loss`,(function(e){i.onTrouterMessageLoss(e)})),e.on(`audience.subscriptionresult`,(function(e,t){i.onAudienceSubscriptionResult(t)}))},e.prototype.onNavigatorOnlineStatusUpdate=function(){var e=window.navigator.onLine;this.logger.debug(`Browser online status update - new state: ${e}, previously: ${this.isNavigatorOnline}`),e&&!this.isNavigatorOnline?(this.isNavigatorOnline=!0,this.tokenBackoff.expediteIfPending(),this.connectionTracker.trackProgress(`browserNet`,`online`)):!e&&this.isNavigatorOnline&&(this.isNavigatorOnline=!1,this.connectionTracker.trackProgress(`browserNet`,`offline`))},e.prototype.onAllocationResponse=function(e,t){this.logger.info(`Received allocation response ${JSON.stringify(r(r({},e),{connectparams:void 0}))} (connectparams redacted)`),this.allocateResult=e,this.populateAndCacheReconnectParams(this.allocateResult,`${this.allocateResult.socketio}v4/a`),this.populateConnectionStateFields(this.allocateResult),this.fsm.onAllocationSucceed(t)},e.prototype.populateAndCacheReconnectParams=function(e,t){this.reconnectParams=r({serviceUrl:this.options.trouterUrl,reconnectUrl:t},e.connectparams),this.manager.onConnectionParametersUpdated(this.reconnectParams)},e.prototype.populateConnectionStateFields=function(e){var t=typeof e.ttl==`string`?parseInt(e.ttl,10):e.ttl;if(this.connectionExpireTimestampInSecs=(0,c.calculateExpireTsInSec)(t),this.connectionId=e.id??``,this.connectedClientId=e.ccid,this.logger.debug(`connected client id set {connectedClientId:${this.connectedClientId}}`),this.c2cUrlBase=e.curlb??``,this.c2cUrlBase===``){var n=e.surl.indexOf(`://`);n>=0&&(n=e.surl.indexOf(`/`,n+3))>=5&&e.surl.substr(n-5,5)===`:3443`&&(this.c2cUrlBase=e.surl.substr(0,n-5))}},e.prototype.onPingResponse=function(){this.logger.debug(`onPingResponse`),this.connectionTracker.increasePingResponseCount(),this.clearPingResponseTimer(),this.fsm.onPingResponse()},e.prototype.clearPingResponseTimer=function(){this.pingResponseTimerId!==void 0&&(clearTimeout(this.pingResponseTimerId),this.pingResponseTimerId=void 0)},e.prototype.buildQuery=function(e){for(var t=[],n=0,r=Object.keys(e);n<r.length;n++){var i=r[n];e[i]!==void 0&&t.push(`${i}=${e[i]}`)}return t.join(`&`)},e.prototype.appendConnectedClientIds=function(e,t){var n=``;e.includes(`ccid=`)||(n=`ccid=${this.connectedClientId}&`),this.domId&&(n+=`dom=${this.domId}&`),n.length>0&&(n=n.slice(0,-1));var r=t||e.includes(`?`)?`&`:`?`;return this.appendCorrelationIds(e+r+n,t)},e.prototype.appendEndpointId=function(e,t){var n=t||e.includes(`?`)?`&`:`?`;return!e.includes(`epid`)&&this.options.endpointId?`${e}${n}epid=${this.options.endpointId}`:e},e.prototype.appendCorrelationIds=function(e,t){var n=t||e.includes(`?`)?`&`:`?`;return e.includes(`cor_id`)?e:`${e}${n}cor_id=${this.options.clientCorrelationID}&con_num=${this.clientID}_${this.connectionAttempt}`},e.prototype.appendClientInfo=function(e,t){var n=t||e.includes(`?`)?`&`:`?`,r=encodeURIComponent((0,c.toJson)(this.clientInfo));return e.includes(`tc=`)?e:`${e}${n}tc=${r}`},e.prototype.safeString=function(e){return typeof e==`string`?e:``},e.prototype.sendResponse=function(e,t){var n,r;if(e.timedout)return this.logger.error(`Request ${e.id} already timed out`),1;if(e.replied)return this.logger.error(`Response for request ${e.id} already sent`),2;clearTimeout(e.timeoutTimerId),e.timeoutTimerId=void 0,e.replied=!0,t.headers=t.headers??{};var i=e.correlationVector;this.logger.info(`Sending response N ${e.id} CV ${i} with status ${t.status}`),i&&(t.headers[S]=i),(n=e.headers)!=null&&n[`trouter-request`]&&(t.headers[`trouter-request`]=e.headers[`trouter-request`]);var a=Date.now()-e.startTS;if(t.headers[`trouter-client`]=(0,c.toJson)({cd:a}),(r=e.headers)!=null&&r[`trouter-is-broadcast`]&&(t.headers[`trouter-is-broadcast`]=e.headers[`trouter-is-broadcast`]),!this.socket)return this.connectionTracker.sendResponseError(`no socket`,e,t),4;try{return this.socket.send((0,c.toJson)(t)),t.sentTS=Date.now(),e.incrementCorrelationVector(),this.connectionTracker.trackResponse(e,a,t),this.transportTypeName===`websocket`&&this.sendPingRequest(),0}catch(n){var o=`unable to send data on response.end. Error: ${D(n)}`;return this.logger.error(o),this.connectionTracker.sendResponseError(o,e,t),4}},e.prototype.sendUserActivityStateMultiple=function(e){var t=this,n=new T(`user.activity`),r=this.userActivityState.increaseCvAndGetEventObject();n.args=r,this.logger.debug(`Sending user activity '${this.userActivityState.toEventJSON()}', remaining ${e-1}`);var i=!1;this.sendDownstreamEvent(n,(function(){if(!0!==i&&(t.logger.info(`User activity state: ${r.state}, cv: ${r.cv} accepted`),t.manager.onUserActivityStateAccepted(r.cv),t.clearSentEventTimer(n.timeoutTimerId),e>1)){var a=setTimeout((function(){t.clearSentEventTimer(a),t.sendUserActivityStateMultiple(e-1)}),t.options.userActivitySecondResendDelayMs);t.registerSentEventTimer(a,`user.activity/resend`)}})),n.timeoutTimerId=setTimeout((function(){t.logger.error(`Activity state response timeout is fired`),i=!0,t.fsm.onActivityStateResponseTimeout(),t.clearSentEventTimer(n.timeoutTimerId)}),this.timeoutOptions.userActivityResponseTimeoutMs),this.registerSentEventTimer(n.timeoutTimerId,`user.activity/response`)},e.prototype.sendUserActivityStateIgnoreResponse=function(){var e=new T(`user.activity`),t=this.userActivityState.toEventObject();e.args=t,this.socket&&(this.logger.info(`Sending user activity after XHR connect, ${t.state}, cv: ${t.cv}, treating it as accepted`),this.socket.emit(e.name,e.args),this.manager.onUserActivityStateAccepted(t.cv))},e.prototype.sendDownstreamEvent=function(e,t){this.logger.debug(`Sending downstream event ${e.name}`),this.socket&&this.socket.emit(e.name,e.args,t)},e.prototype.registerSentEventTimer=function(e,t){this.logger.debug(`registering timer ${e} -> ${t}`),this.pendingSentEventTimers[e]=t},e.prototype.clearSentEventTimer=function(e){var t=this.pendingSentEventTimers[e];this.logger.debug(`clearing timer ${e} -> ${t}`),delete this.pendingSentEventTimers[e],clearTimeout(e)},e.prototype.getRegistrationTtl=function(){var e=(0,c.calculateTtlInSec)(this.connectionExpireTimestampInSecs);if(this.logger.debug(`Current connectionID will expire in ${e} seconds`),this.options.registration?.registrarTtlSec&&e>0){var t=this.options.registration.registrarTtlSec<e;return[Math.min(this.options.registration.registrarTtlSec,e),t]}return this.options.registration?.registrarTtlSec?[this.options.registration.registrarTtlSec,!1]:e>0?[e,!1]:[3600,!1]},e.prototype.clearIncallModeTimerId=function(){this.incallModeTimerId!==void 0&&(this.logger.debug(`Clearing in-call mode timer`),clearTimeout(this.incallModeTimerId),this.incallModeTimerId=void 0)},e.prototype.applyConnectionTrackerOptions=function(e){try{e.eventLogger&&typeof e.eventLogger.logEvent==`function`?(this.connectionTracker.mergeSettings(e.telemetrySettings),this.connectionTracker.enable(e.eventLogger)):this.logger.warn(`Trouter client event logging disabled due to invalid configuration.`)}catch(e){this.logger.warn(`Trouter client event logging disabled. Error: ${D(e)}`),this.connectionTracker.disable()}},e.prototype.canRetryTokenFetchRequest=function(e){var t=this.options.retryLimitOnTokenFetch;return t==null||e<t||(this.logger.warn(`Reached limit on maximum number of token fetch request. Current count: ${e}, retry limit: ${t}`),!1)},e}();function ee(e,t){var n=t?void 0:{"X-MS-Migration":`True`};switch(e.tokenType.toLowerCase()){case`skype`:return r({"X-Skypetoken":e.token},n);case`aad`:case`cae`:return r({Authorization:`Bearer ${e.token}`},n);default:throw Error(`unsupported token type: ${e.tokenType}`)}}function D(e){return typeof e==`object`&&e&&e.stack!==void 0?(0,c.toJson)(e.stack):`"(no error.stack)"`}function O(e){return typeof e==`object`&&e&&typeof e.message==`string`?e.message:`(no error.message)`}t.TrouterConnection=E},616:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterUrlPromise=void 0;var r=n(642);t.TrouterUrlPromise=function(){function e(e){this.logger=new r.Logger(`UrlPromise`,e)}return e.prototype.getPromise=function(){var e=this;return this.url===void 0?(this.pendingPromise===void 0?(this.logger.debug(`creating and returning promise`),this.pendingPromise=new Promise((function(t,n){e.pendingPromiseResolveRef=t,e.pendingPromiseRejectRef=n}))):this.logger.debug(`returning existing promise`),this.pendingPromise):(this.logger.debug(`returning previously resolved url: ${this.url}`),Promise.resolve(this.url))},e.prototype.resolveUrl=function(e){this.url=e,this.logger.debug(`got url: ${this.url}`);var t=this.pendingPromiseResolveRef;this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,t!==void 0&&(this.logger.debug(`resolving promise`),t(e))},e.prototype.rejectUrl=function(e){this.logger.debug(`aborting`);var t=this.pendingPromiseRejectRef;this.url=void 0,this.pendingPromise=void 0,this.pendingPromiseResolveRef=void 0,this.pendingPromiseRejectRef=void 0,t!==void 0&&(this.logger.debug(`rejecting promise`),t(e))},e.prototype.resetUrl=function(){this.logger.debug(`resetting url`),this.url=void 0},e}()},619:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MessageHandlerRegistry=void 0;var r=n(509),i=n(642);t.MessageHandlerRegistry=function(){function e(e){this.messageHandlers=[],this.logger=new i.Logger(`MessageHandlers`,e)}return e.prototype.register=function(e){if(this.messageHandlers.some((function(t){return t===e})))throw Error(`Registering the same handler twice is not allowed`);this.messageHandlers.push(e)},e.prototype.clear=function(){this.logger.debug(`Clearing message handlers`),this.messageHandlers=[]},e.prototype.active=function(){return this.messageHandlers.length>0},e.prototype.handleMessage=function(e){for(var t={resultCode:r.UNHANDLED_MESSAGE_ACK,isHandled:!1},n=0,i=this.messageHandlers;n<i.length;n++){var a=i[n],o=this.safeExecuteHandle(a,e);if(o!==void 0&&(o.isHandled===void 0||o.isHandled))return o.resultCode===void 0&&(o.resultCode=r.HANDLED_MESSAGE_ACK),o}return t},e.prototype.safeExecuteHandle=function(e,t){try{return e.handleMessage(t)}catch(e){this.logger.warn(`Trouter message handler threw an exception: ${e}`);return}},e}()},634:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterManager=t.AudienceSubscriptionState=t.UserActivityObject=void 0;var a=n(659),o=n(234),s=n(423),c=n(642),l=n(902),u=n(235),d=n(573),f=n(335),p=n(10),m=n(509),h=function(){function e(e,t){this.state=e,this.correlationVector=t===void 0?a.CorrelationVector.extend():t}return e.prototype.getStateString=function(){switch(this.state){case o.UserActivityState.Active:return`active`;case o.UserActivityState.Inactive:return`inactive`;case o.UserActivityState.Unknown:return`unknown`;default:return`undefined`}},e.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},e.prototype.toEventObject=function(){return{state:this.getStateString(),cv:this.correlationVector.value()}},e.prototype.toEventJSON=function(){return(0,a.toJson)(this.toEventObject())},e}();t.UserActivityObject=h;var g=function(){function e(e,t){t===void 0&&(t=a.CorrelationVector.extend()),this.subscirpitonsPerScope=e,this.correlationVector=t}return e.prototype.increaseCvAndGetEventObject=function(){return this.correlationVector.increase(),this.toEventObject()},e.prototype.toEventObject=function(){return{audiences:this.toListOfSubscriptions(),cv:this.correlationVector.value()}},e.prototype.toEventJSON=function(){return(0,a.toJson)(this.toEventObject())},e.prototype.toListOfSubscriptions=function(){for(var e=[],t=0,n=Object.keys(this.subscirpitonsPerScope);t<n.length;t++){var r=n[t];e.push.apply(e,this.subscirpitonsPerScope[r])}return e},e}();t.AudienceSubscriptionState=g;var _=`extraTransports`;t.TrouterManager=function(){function e(e,t,n,r,i,s){this.logFunc=e,this.options=t,this.tokenProvider=n,this.usingLegacyTokenApi=r,this.listener=i,this.extraTransportVersionWithinProcess=0,this.logger=new c.Logger(`Manager`,e),this.logger.info(`Created TrouterManager with options ${(0,a.toJson)(this.options)}`),this.fsm=new p.TrouterManagerFsm(e,this),this.baseEndpointUrl=``,this.processedMessageLoss={},this.userActivityObject=new h(o.UserActivityState.Unknown),this.protocolSelector=s??this.tokenTypeProtocolSelector.bind(this)}return e.prototype.start=function(){this.fsm.start()},e.prototype.stop=function(e){this.fsm.stop(e)},e.prototype.configure=function(e){this.options=e,this.firstConnection!==void 0&&this.firstConnection.configure(e),this.secondConnection!==void 0&&this.secondConnection.configure(e),this.logger.info(`Reconfigured TrouterManager with options ${(0,a.toJson)(this.options)}`)},e.prototype.checkConnection=function(e){this.firstConnection!==void 0&&this.firstConnection.checkConnection(e),this.secondConnection!==void 0&&this.secondConnection.checkConnection(e)},e.prototype.resendRegistration=function(){return r(this,void 0,void 0,(function(){return i(this,(function(e){return this.secondConnection===void 0?this.firstConnection===void 0?(this.logger.info(`No connection to resend registration on, will be done upon (re)connect`),[2]):(this.logger.info(`Resending registration on the first/current connection`),[2,this.firstConnection.resendRegistration()]):(this.logger.info(`Resending registration on the second/new connection`),[2,this.secondConnection.resendRegistration()])}))}))},e.prototype.registerExtraTransports=function(e,t){var n,r=this;this.extraTransportsState={transports:e,clientDescriptionOverride:t},this.extraTransportVersionWithinProcess++,(n=this.options.keyValueCache)==null||n.setCacheForKey(_,JSON.stringify(this.extraTransportsState)).catch((function(){r.logger.error(`Failed to store extra transports in cache`)})),this.secondConnection===void 0?this.firstConnection===void 0?this.logger.warn(`No connection to register extra transports on, will be done upon (re)connect`):(this.logger.info(`Registering extra transports ${JSON.stringify(Object.keys(e))} and ${Object.keys(t??{}).length} overridden client description properties on the first/current connection`),this.firstConnection.registerExtraTransports(e,t)):(this.logger.info(`Registering extra transports ${JSON.stringify(Object.keys(e))} and ${Object.keys(t??{}).length} overridden client description properties on the second/new connection`),this.secondConnection.registerExtraTransports(e,t))},e.prototype.getServerState=function(){if(this.firstConnection!==void 0)return this.firstConnection.getServerState()},e.prototype.getState=function(){return this.fsm.getState()},e.prototype.isInTerminalState=function(){return this.fsm.getInternalState()===s.TrouterManagerState.TerminalError},e.prototype.reportStateInfo=function(){var e=this.firstConnection?f.State[this.firstConnection.getState()]:`Unknown`,t=s.TrouterManagerState[this.fsm.getInternalState()];return this.secondConnection?`Manager ${t}; 1st ${e}; 2nd ${f.State[this.secondConnection.getState()]}`:`Manager ${t}; Connection ${e}`},e.prototype.startFirstConnection=function(){var e=this,t=new d.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.firstConnection=t,Promise.all([this.getConnectionCache(),this.fetchExtraTransportsCache()]).then((function(n){var r=n[0];t.start(r,e.extraTransportsState?.transports,e.extraTransportsState?.clientDescriptionOverride)})).catch((function(){e.logger.error(`unexpected error while starting first connection (wrapped cache read functions should never throw)`)}))},e.prototype.startSecondConnection=function(e){var t=this,n=new d.TrouterConnection(this.logFunc,this.options,this.configuredTrouterManager(),this.tokenProvider,this.usingLegacyTokenApi,this.userActivityObject,this.protocolSelector,this.audienceSubscriptionState);this.secondConnection=n,this.firstConnection!==void 0&&this.firstConnection.disableRegistrationsAndAutoReconnect(),e?Promise.all([this.getConnectionCache(),this.fetchExtraTransportsCache()]).then((function(e){var r=e[0];n.start(r,t.extraTransportsState?.transports,t.extraTransportsState?.clientDescriptionOverride)})).catch((function(){t.logger.error(`unexpected error while starting second connection (wrapped cache read functions should never throw)`)})):this.fetchExtraTransportsCache().then((function(){n.start(void 0,t.extraTransportsState?.transports,t.extraTransportsState?.clientDescriptionOverride)})).catch((function(){t.logger.error(`unexpected error while starting second connection (wrapped cache read functions should never throw)`)}))},e.prototype.stopFirstConnection=function(e){this.firstConnection!==void 0&&(this.storedFirstConnection=this.firstConnection,this.firstConnection.stop(e),this.firstConnection=void 0)},e.prototype.stopSecondConnection=function(e){this.secondConnection!==void 0&&(this.secondConnection.stop(e),this.secondConnection=void 0)},e.prototype.stopSecondConnectionDelayed=function(){if(this.secondConnection!==void 0){var e=this.secondConnection;this.secondConnection=void 0,this.logger.info(`Closing an inactive connection in ${Math.round(this.options.lingeringConnectionDelayMs/1e3)}s`),setTimeout((function(){e.stop(!0)}),this.options.lingeringConnectionDelayMs)}},e.prototype.forceStopLingeringConnection=function(){this.storedFirstConnection&&=(this.storedFirstConnection.stop(!1),void 0)},e.prototype.switchConnections=function(){var e=this.firstConnection;this.firstConnection=this.secondConnection,this.secondConnection=e},e.prototype.doesSecondConnectionExist=function(){return this.secondConnection!==void 0},e.prototype.dispatchConnected=function(){if(this.firstConnection!==void 0){var e=this.firstConnection.getServerState(),t=e.url.endsWith(`/`)?e.url.slice(0,-1):e.url,n={baseEndpointUrl:t,newEndpointUrl:t!==this.baseEndpointUrl,c2cUrlBase:e.c2cUrlBase,clientId:e.connectedClientId,connectionId:e.connectionId,connectionTtlSec:e.getRemainingTtlInSec()};this.baseEndpointUrl=t,this.listener.onTrouterConnected(e.url,n)}},e.prototype.dispatchDisconnected=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},e.prototype.dispatchTerminalError=function(){this.listener.onTrouterDisconnected&&this.listener.onTrouterDisconnected()},e.prototype.dispatchRegistrationState=function(e){this.options.registrationStateCallback&&this.options.registrationStateCallback(e)},e.prototype.expediteBackoffOnConnections=function(){this.lastExpediteBackoffCallAt!==void 0&&Date.now()-this.lastExpediteBackoffCallAt<(this.options.expediteBackoffOnStartMinimumDelayMs??1e4)?this.logger.info(`Expedite backoff due to start() too frequent, skipping`):(this.lastExpediteBackoffCallAt=Date.now(),this.firstConnection!==void 0&&this.firstConnection.expediteBackoff(),this.secondConnection!==void 0&&this.secondConnection.expediteBackoff())},e.prototype.onDownstreamRequest=function(e,t,n){var r={id:t.id,method:t.method,path:`/${t.shortUrl}`,body:t.body,headers:t.headers},i={id:t.id,status:0,headers:{},body:``,send:function(){return i.status<=100||i.status>=999?3:(n.writeHead(i.status,i.headers),n.end(i.body))}};this.listener.onTrouterRequest(r,i)},e.prototype.onConnected=function(e){this.fsm.onConnected(e===this.firstConnection)},e.prototype.onRegistered=function(e){this.fsm.onRegistered(e===this.firstConnection)},e.prototype.onUnregistered=function(e){this.fsm.onUnregistered(e===this.firstConnection||e===this.storedFirstConnection)},e.prototype.onReconnecting=function(e){this.fsm.onReconnecting(e===this.firstConnection)},e.prototype.onReconnectIsRequired=function(e,t,n){this.fsm.onReconnectionRequired(e===this.firstConnection,t,n)},e.prototype.onDisconnected=function(e){this.fsm.onDisconnected(e===this.firstConnection||e==this.storedFirstConnection),this.storedFirstConnection=void 0},e.prototype.onTerminalError=function(){this.fsm.onTerminalError(),this.storedFirstConnection=void 0},e.prototype.onUserActivityStateAccepted=function(e){this.listener.onTrouterUserActivityStateAccepted&&this.listener.onTrouterUserActivityStateAccepted(e)},e.prototype.onAudiencesSetResolved=function(e,t){var n,r;(r=(n=this.listener).onAudiencesSetResolved)==null||r.call(n,e,t)},e.prototype.onConnectionParametersUpdated=function(e){this.setConnectionCache(e)},e.prototype.setUserActivityState=function(e,t){this.userActivityObject=new h(e,a.CorrelationVector.extend(t)),this.secondConnection===void 0?this.firstConnection!==void 0&&(this.logger.info(`Setting user activity ${this.userActivityObject.toEventJSON()} on the first/current connection`),this.firstConnection.setUserActivityState(this.userActivityObject)):(this.logger.info(`Setting user activity ${this.userActivityObject.toEventJSON()} on the second/new connection`),this.secondConnection.setUserActivityState(this.userActivityObject))},e.prototype.setAudienceSubscriptionsAsync=function(e,t,n){var r=e.scope??m.constants.SUBSCRIPTIONS_DEFAULT_SCOPE,i=this.GetUpdatedAsState(e,r);if(this.audienceSubscriptionState=new g(i,a.CorrelationVector.extend(n)),this.secondConnection)return this.logger.info(`Setting audience subscriptions ${this.audienceSubscriptionState.toEventJSON()} on second/new connection`),this.secondConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,t);if(this.firstConnection)return this.logger.info(`Setting audience subscriptions ${this.audienceSubscriptionState.toEventJSON()} on first/current connection`),this.firstConnection.setAudienceSubscriptionsAsync(this.audienceSubscriptionState,t);throw Error(`No connection found`)},e.prototype.GetUpdatedAsState=function(e,t){var n={};return this.audienceSubscriptionState!==void 0&&(n=structuredClone(this.audienceSubscriptionState.subscirpitonsPerScope)),n[t]=e.audienceSubscriptions,n},e.prototype.onTrouterMessageLost=function(e){var t=this;if(this.listener.onTrouterMessageLoss)if(e?.length){var n=e.filter((function(e){return t.processedMessageLoss[`${e.tag}-${e.etag}`]!==void 0}));if(n.length&&(this.logger.info(`onTrouterMessageLoss - immediately acknowledging ${n.length} seen dropped indicators`),this.sendProcessedDroppedIndicators(n),!(e=e.filter((function(e){return t.processedMessageLoss[`${e.tag}-${e.etag}`]===void 0}))).length))return void this.logger.info(`onTrouterMessageLoss - all declared dropped indicators have been seen before`);if(!this.listener.onTrouterMessageLoss(e.map((function(e){return e.tag}))))return void this.logger.warn(`onTrouterMessageLoss - some flow tag(s) have not been processed by listeners`);e.forEach((function(e){t.processedMessageLoss[`${e.tag}-${e.etag}`]=``})),this.sendProcessedDroppedIndicators(e)}else this.logger.warn(`onTrouterMessageLoss - no flow tags have been provided`)},e.prototype.getConnectionCache=function(){var e=this;return this.options.connectionCache?(this.logger.debug(`Querying host's connection cache`),this.options.connectionCache.onGetTrouterConnectionCache().then((function(e){var t=e?JSON.parse(e):void 0;return typeof t==`object`?t:void 0})).catch((function(t){return e.logger.warn(`Invalid connection cache content provided: ${t}`),e.connectionCache}))):Promise.resolve(this.connectionCache)},e.prototype.fetchExtraTransportsCache=function(){var e=this,t=this.extraTransportVersionWithinProcess;return this.options.keyValueCache&&this.extraTransportsState===void 0?this.options.keyValueCache.getCacheForKey(_).then((function(n){if(t===e.extraTransportVersionWithinProcess){if(n){var r=JSON.parse(n);typeof r==`object`&&r&&(Object.prototype.hasOwnProperty.call(r,`transports`)?e.extraTransportsState=r:e.extraTransportsState={transports:r,clientDescriptionOverride:void 0}),e.extraTransportVersionWithinProcess++}}else e.logger.info(`Extra transports cache was updated while fetching it, returning the current state`)})).catch((function(){e.logger.error(`Failed to retrieve extra transports from cache`)})):Promise.resolve()},e.prototype.setConnectionCache=function(e){if(this.connectionCache=e,this.options.connectionCache)try{this.options.connectionCache.onSetTrouterConnectionCache(JSON.stringify(e))}catch(e){this.logger.warn(`Error setting external connection cache: ${e}`)}},e.prototype.sendProcessedDroppedIndicators=function(e){this.firstConnection===void 0?this.secondConnection===void 0||this.secondConnection.sendProcessedDroppedIndicators(e):this.firstConnection.sendProcessedDroppedIndicators(e)},e.prototype.configuredTrouterManager=function(){return new u.RegistrationEnforcer(this,this.options.connectionDependsOnRegistration,this.options.delayEventsUntilRegistered)},e.prototype.tokenTypeProtocolSelector=function(e,t){return this.options.forceV4aProtocol||this.options.forceV4aProtocolForSkypetoken&&e===`skype`&&(0,l.safeToString)(t?.scae)!==`1`?`v4a`:`v4c`},e}()},642:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Logger=void 0,t.Logger=function(){function e(e,t){this.name=e,this.logger=t}return e.prototype.debug=function(e){this.logger.debug(`[${this.name}] ${e}`)},e.prototype.info=function(e){this.logger.info(`[${this.name}] ${e}`)},e.prototype.warn=function(e){this.logger.warn(`[${this.name}] ${e}`)},e.prototype.error=function(e){this.logger.error(`[${this.name}] ${e}`)},e}()},659:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};function i(e){try{return JSON.stringify(e)}catch{return`Unable to serialize object of type ${typeof e}`}}Object.defineProperty(t,"__esModule",{value:!0}),t.Timespan=t.CorrelationVector=void 0,t.toJson=i,t.anonymizeShortUrl=function(e){var t=/^(TeamsUnifiedPresenceService|acceptance|addParticipant\w*|balanceUpdate|call(Agent)?|controlVideoStreaming|conversation\w*|dominantSpeakerInfo|end|join|media\w*|messaging|progress|rejection|retargetCompletion|rosterUpdate|update|ups)$/i;return e.split(`/`).map((function(e){return!e||t.test(e)||e.length<3?e:`${e.slice(0,2)}...`})).join(`/`)},t.headersToLog=function(e){for(var t=/^(Host|User-Agent|Content-Length|Content-Type|X-Microsoft-Skype-\S+|(X-)?Trouter.*|X-CallingProxy|MS-CV|traceparent|Priority)$/i,n={},r=0,a=Object.keys(e);r<a.length;r++){var o=a[r];t.test(o)&&(n[o]=e[o])}return i(n)},t.calculateTtlInSec=function(e){var t=Math.round(new Date().getTime()/1e3);return e!==void 0&&e>t?e-t:0},t.calculateExpireTsInSec=function(e){return Math.round(new Date().getTime()/1e3)+e},t.fetchWithTimeout=function(e,t){return n(this,void 0,void 0,(function(){var n,i,a;return r(this,(function(r){return i=new Promise((function(t,r){fetch(e).then((function(e){clearTimeout(n),t(e)})).catch((function(e){clearTimeout(n),r(e)}))})),t===0?[2,i]:(a=new Promise((function(r,i){var a=new URL(e.url),o=Error(`${e.method} ${a.origin}${a.pathname} timed out`);n=setTimeout(i,t,o)})),[2,Promise.race([i,a])])}))}))},t.CorrelationVector=function(){function e(e){this.base=e===void 0?this.createCorrelationVectorBase():e,this.extension=0}return e.extend=function(t){return new e(t)},e.prototype.increase=function(){this.extension++},e.prototype.value=function(){return`${this.base}.${this.extension}`},e.prototype.createCorrelationVectorBase=function(){for(var e=``,t=0;t<21;t++)e+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0987654321/+`.charAt(Math.floor(64*Math.random()));return e+`AQgw`.charAt(Math.floor(4*Math.random()))},e}(),t.Timespan=function(){function e(){this.start=Date.now()}return Object.defineProperty(e.prototype,"duration",{get:function(){return Date.now()-this.start},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"startTime",{get:function(){return this.start},enumerable:!1,configurable:!0}),e.prototype.reset=function(){this.start=Date.now()},e}()},673:t=>{t.exports=e},705:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateAudienceSubscriptionQuery=function(e,t){return e.replace(/([?&]audienceSubscriptionState=)[^&]*/,`\$1${t}`)}},764:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DisconnectReason=void 0,t.DisconnectReason=function(){function e(e,t,n){this.reason=e,this.claims=t,this.details=n}return e.fromRawReason=function(t,n){if(t===``||t===`dup`)return new e(t);try{var r=JSON.parse(t);return typeof r!=`object`||r.reason===void 0?(n?.error(`invalid disconnect reason format`),new e(`unknown`,void 0,t)):new e(r.reason,r.claims,r.details)}catch{return new e(`disconnect`,void 0,t)}},e.fromSocketIoEventData=function(t,n){return typeof n==`string`?new e(t,void 0,n):void 0},e.prototype.toTelemetryString=function(){return this.reason===`socketerror`||this.reason===`reconnecterror`||this.reason===`disconnect`?this.details:this.reason},e}()},882:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)},i=this&&this.__awaiter||function(e,t,n,r){return new(n||=Promise)((function(i,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,s)}c((r=r.apply(e,t||[])).next())}))},a=this&&this.__generator||function(e,t){var n,r,i,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(s){return function(c){return function(s){if(n)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(a=0)),a;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!((i=(i=a.trys).length>0&&i[i.length-1])||s[0]!==6&&s[0]!==2)){a=0;continue}if(s[0]===3&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(s[0]===6&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=t.call(e,a)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.TrouterService=t.UserActivityState=t.TrouterState=void 0,t.createTrouterService=function(e){return new h(e)},t.getTrouterServiceVersion=function(){return o.CLIENT_VERSION},t.replaceTrouterUrlBase=function(e,t){var n=e.indexOf(`://`);if(n>=0){var r=e.indexOf(`/`,n+3);if(r>=0)return t+e.substr(r)}return``};var o=n(509),s=n(234);Object.defineProperty(t,"TrouterState",{enumerable:!0,get:function(){return s.TrouterState}}),Object.defineProperty(t,"UserActivityState",{enumerable:!0,get:function(){return s.UserActivityState}});var c=n(642),l=n(619),u=n(220),d=n(634),f=n(616);function p(e,t){if(!t)return e;var n=r(r({},e),{enabled:t.TelemetryEnabled});return t.ClientTelemetryEventEnabled!==void 0&&(n=r(r({},n),t.ClientTelemetryEventEnabled)),n}function m(e,t,n){var i,a,o,s=function(n){return e.proxyUrlRewrite?(t.info(`Using rewritten URL for proxy`),e.proxyUrlRewrite(n)):n};return{clientInfo:{ua:e.trouterSettings.productName,v:e.trouterSettings.version},ioOptions:{ackTimeoutMs:5e3,rewriteUrlForProxy:s},clientCorrelationID:e.trouterSettings.sessionId,environment:e.trouterSettings.environment,telemetrySettings:p(e.telemetryConfig.settings,n),eventLogger:e.telemetryConfig.eventLogger,endpointId:e.trouterSettings.registrationId,trouterUrl:n?.TrouterConnectionUrl||e.trouterSettings.trouterServiceUrl,registration:e.trouterSettings.registrarServiceUrl||e.trouterSettings.useRegistrarUrlFromAllocate?{registrarUrl:e.trouterSettings.registrarServiceUrl??``,useRegistrarUrlFromAllocate:(i=e.trouterSettings.useRegistrarUrlFromAllocate)!=null&&i,registrationId:e.trouterSettings.registrationId??``,pnhAppId:e.trouterSettings.pnhAppId??``,platform:e.trouterSettings.platform??``,pnhTemplateKey:e.trouterSettings.pnhTemplate??``,platformUIVersion:e.trouterSettings.platformUIVersion??``,productContext:e.trouterSettings.pnhProductContext||void 0,context:e.trouterSettings.pnhContext??``,registrarTtlSec:(e.trouterSettings.maxRegistrationTimeInMs??0)/1e3}:void 0,connectionDependsOnRegistration:e.trouterSettings.registrarServiceUrl===void 0?function(){return!1}:e.trouterSettings.connectionDependsOnRegistration??function(){return!1},delayEventsUntilRegistered:e.trouterSettings.delayEventsUntilRegistered??function(){return!1},timeoutOptions:r({connectionTimeoutMs:e.trouterSettings.trouterConnectTimeoutInMs||3e4,fetchTimeoutMs:1e4,pingTimeoutMs:4e4,pongTimeoutMs:5e3,maxBackoffMs:e.trouterSettings.productName===`TeamsCDL`?3e5:3e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},e.trouterSettings.timeoutOptions),incallTimeoutOptions:r({connectionTimeoutMs:1e4,fetchTimeoutMs:5e3,pingTimeoutMs:5e3,pongTimeoutMs:2e3,maxBackoffMs:e.trouterSettings.productName===`TeamsCDL`?3e5:1e4,requestTimeoutMs:5e3,userActivityResponseTimeoutMs:1e4},e.trouterSettings.incallTimeoutOptions),incallModeTimeoutMs:e.trouterSettings.incallModeTimeoutMs??0,lingeringConnectionDelayMs:6e4,userActivitySecondResendDelayMs:e.trouterSettings.userActivitySecondResendDelayMs||1e4,duplicateDisconnectThresholdMs:1e4,connectionCache:e.connectionCache,keyValueCache:e.keyValueCache,registrationStateCallback:e.registrationStateCallbackForAcsDoNotUse,rewriteUrlForProxy:s,retryLimitOnTokenFetch:e.trouterSettings.retryLimitOnTokenFetch,extraConnectionHeaders:e.trouterSettings.extraConnectionHeaders,expediteBackoffOnStartMinimumDelayMs:1e4,updateUserActivityDuringConnectionAttempt:(a=e.trouterSettings.updateUserActivityDuringConnectionAttempt)==null||a,initialConnectivityCheck:(o=e.trouterSettings.initialConnectivityCheck)==null||o,toJSON:function(){return r(r({},this),{connectionCache:this.connectionCache?{}:this.connectionCache,keyValueCache:this.keyValueCache?{}:this.keyValueCache})}}}var h=function(){function e(e){this.logProvider=e,this.stateChangedListeners=[],this.logger=new c.Logger(`Trouter`,e),this.trouterUrlPromise=new f.TrouterUrlPromise(e),this.messageHandlers=new l.MessageHandlerRegistry(e),this.listeners={},this.connectionInfo=null,this.logger.info(`Created TrouterService version ${o.CLIENT_VERSION}`)}return e.prototype.start=function(e){if(this.logger.info(`Start`),!e.skypeTokenProvider&&!e.authTokenProvider)throw Error(`no token provider has been configured, either skypeTokenProvider or authTokenProvider must be populated`);e.skypeTokenProvider&&!e.trouterSettings.disableInternalSkypeTokenCache&&(e.skypeTokenProvider=(0,u.addCacheAsBackupTo)(e.skypeTokenProvider)),this.trouterCfg=e;var t=m(e,this.logger,this.ecsCfg);!1===e.internalEnableV4cProtocol&&(t.forceV4aProtocol=!0),!1===e.internalUseV4aForSkypetoken&&(t.forceV4aProtocolForSkypetoken=!0);var n=function(e,t){var n,r=this;return function(o){return i(r,void 0,void 0,(function(){var r,i,s;return a(this,(function(a){switch(a.label){case 0:r=new Date,i=setInterval((function(){var t=Math.round((Date.now()-r.getTime())/6e4);e.warn(`Note: Trouter auth token request promise from ${r.toISOString()} has not been resolved for ${t} minutes. The client is blocked from operating properly`)}),3e5),a.label=1;case 1:return a.trys.push([1,,3,4]),[4,t(o)];case 2:return s=a.sent(),o.needFresh&&s.token===n&&e.error(`API violation: Trouter auth token provider got a request with needRefresh=true, but returned the same token as last time anyway. Please fix the host app`),n=s.token,[2,s];case 3:return clearInterval(i),[7];case 4:return[2]}}))}))}}(this.logger,e.authTokenProvider??function(e){var t=this;return function(n){return i(t,void 0,void 0,(function(){var t;return a(this,(function(r){switch(r.label){case 0:return t={},[4,e(n.needFresh)];case 1:return[2,(t.token=r.sent(),t.tokenType=`skype`,t)]}}))}))}}(e.skypeTokenProvider));this.trouterServer===void 0&&(this.trouterServer=new d.TrouterManager(this.logProvider,t,n,e.authTokenProvider===void 0,this)),this.pendingActivityState!==void 0&&(this.trouterServer.setUserActivityState(this.pendingActivityState[0],this.pendingActivityState[1]),this.pendingActivityState=void 0),this.pendingExtraTransports!==void 0&&(this.trouterServer.registerExtraTransports(this.pendingExtraTransports.transports,this.pendingExtraTransports.clientDescriptionOverride),this.pendingExtraTransports=void 0),this.trouterServer.start()},e.prototype.stop=function(e){this.logger.info(`close connection`),this.trouterUrlPromise.rejectUrl(Error(`TrouterService is stopped`)),this.trouterServer!==void 0&&this.trouterServer.stop(e)},e.prototype.setEcsConfig=function(e){return i(this,void 0,void 0,(function(){var t=this;return a(this,(function(n){return[2,new Promise((function(n){if(t.ecsCfg=e.TrouterJScriptClient,t.logger.info(`Setting ECS configuration to ${JSON.stringify(t.ecsCfg)}`),t.trouterServer!==void 0&&t.trouterCfg!==void 0){var r=m(t.trouterCfg,t.logger,t.ecsCfg);t.trouterServer.configure(r)}n()}))]}))}))},e.prototype.checkConnection=function(e){this.trouterServer!==void 0&&this.trouterServer.checkConnection(e!=null&&e)},e.prototype.resendRegistration=function(){return i(this,void 0,void 0,(function(){return a(this,(function(e){if(!this.trouterServer)throw Error(`resendRegistration called too early`);return[2,this.trouterServer.resendRegistration()]}))}))},e.prototype.registerExtraTransports=function(e,t){if(this.trouterServer===void 0)return this.pendingExtraTransports={transports:e,clientDescriptionOverride:t},void this.logger.warn(`registerExtraTransports called before start()`);this.logger.info(`registerExtraTransports called`),this.pendingExtraTransports=void 0,this.trouterServer.registerExtraTransports(e,t)},e.prototype.registerListener=function(e,t){return t===``||!t.startsWith(`/`)||t.includes(`?`)||t.includes(`#`)?(this.logger.error(`Listener path '${t}' is not valid`),!1):this.listeners[t]?(this.logger.error(`Another listener is already registered for path '${t}'`),!1):(this.listeners[t]=e,this.logger.debug(`Listener for path '${t}' registered`),this.connectionInfo&&e.onTrouterConnected(this.connectionInfo.baseEndpointUrl+t,this.connectionInfo),!0)},e.prototype.unregisterListener=function(e){for(var t=[],n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n];this.listeners[i]===e&&t.push(i)}if(t.length===0)return!1;for(var a=0,o=t;a<o.length;a++)i=o[a],delete this.listeners[i];return this.logger.debug(`Listener for path(s) '${t.join(`', '`)}' unregistered`),!0},e.prototype.onTrouterConnected=function(e,t){this.logger.debug(`Trouter is now connected`);for(var n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n];try{this.listeners[i].onTrouterConnected(t.baseEndpointUrl+i,t)}catch(e){this.logger.error(`Listener '${i}' threw an exception from onTrouterConnected(): ${e}`)}}this.connectionInfo=t,this.trouterUrlPromise.resolveUrl(e),this.notifyStateChanged(s.TrouterState.Connected,{url:e,getRemainingTtlInSec:function(){return t.connectionTtlSec}})},e.prototype.onTrouterDisconnected=function(){this.logger.debug(`Trouter is now disconnected`),this.connectionInfo=null;for(var e=0,t=Object.keys(this.listeners);e<t.length;e++){var n=t[e],r=this.listeners[n];if(r.onTrouterDisconnected)try{r.onTrouterDisconnected()}catch(e){this.logger.error(`Listener '${n}' threw an exception from onTrouterDisconnected(): ${e}`)}}this.notifyStateChanged(s.TrouterState.Disconnected)},e.prototype.onTrouterRequest=function(e,t){for(var n=``,r=0,i=Object.keys(this.listeners);r<i.length;r++){var a=i[r];e.path.startsWith(a)&&a.length>n.length&&(n=a)}if(n===``)this.tryMessageHandlers(e,t)||(t.status=404,t.headers={"Trouter-Responder":`ClientLib`},t.send());else try{this.listeners[n].onTrouterRequest(e,t)}catch(e){this.logger.error(`Listener '${n}' threw an exception from onTrouterRequest(): ${e}`),t.status=500,t.headers={"Trouter-Responder":`ClientLib`},t.send()}},e.prototype.onTrouterMessageLoss=function(e){this.logger.info(`onTrouterMessageLoss called with tags [${e}]`);for(var t=!0,n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n],a=this.listeners[i];if(a.onTrouterMessageLoss)try{(t=a.onTrouterMessageLoss(e)&&t)===void 0&&(this.logger.error(`Listener '${i}' did not return a boolean value from onTrouterMessageLoss()`),t=!1)}catch(e){this.logger.error(`Listener '${i}' threw an exception from onTrouterMessageLoss(): ${e}`),t=!1}}return t},e.prototype.onTrouterUserActivityStateAccepted=function(e){this.logger.debug(`onTrouterUserActivityStateAccepted cv: ${e}`);for(var t=0,n=Object.keys(this.listeners);t<n.length;t++){var r=n[t],i=this.listeners[r];if(i.onTrouterUserActivityStateAccepted)try{i.onTrouterUserActivityStateAccepted(e)}catch(e){this.logger.error(`Listener '${r}' threw an exception from onTrouterUserActivityStateAccepted(): ${e}`)}}},e.prototype.onAudiencesSetResolved=function(e,t){this.logger.debug(`onAudiencesSetResolved cv: ${t}`);for(var n=0,r=Object.keys(this.listeners);n<r.length;n++){var i=r[n],a=this.listeners[i];if(a.onAudiencesSetResolved)try{a.onAudiencesSetResolved(e,t)}catch(e){this.logger.error(`Listener '${i}' threw an exception from onAudienceSubscribed(): ${e}`)}}},e.prototype.setUserActivityState=function(e,t){if(e!==s.UserActivityState.Active&&e!==s.UserActivityState.Inactive)throw Error(`setUserActivityState called with unsupported value ${e}`);this.logger.info(`setUserActivityState called with value ${s.UserActivityState[e]}`),this.trouterServer&&this.state()!==s.TrouterState.Unknown?this.trouterServer.setUserActivityState(e,t):(this.pendingActivityState=[e,t],this.logger.warn(`setUserActivityState called before start() or after stop()`))},e.prototype.setAudienceSubscriptions=function(e,t){if(this.trouterServer&&this.state()!==s.TrouterState.Unknown)return this.trouterServer.setAudienceSubscriptionsAsync(e,15e3,t);throw Error(`audience subscribe called before start() or after stop()`)},e.prototype.state=function(){return this.trouterServer===void 0?s.TrouterState.Unknown:this.trouterServer.getState()},e.prototype.isInTerminalState=function(){return this.trouterServer!==void 0&&this.trouterServer.isInTerminalState()},e.prototype.reportStateInfo=function(){return this.trouterServer===void 0?``:this.trouterServer.reportStateInfo()},e.prototype.getServerState=function(){if(this.trouterServer!==void 0)return this.trouterServer.getServerState()},e.prototype.getTrouterUrlAsync=function(){return this.trouterServer===void 0?Promise.reject(Error(`TrouterService has not been started`)):this.trouterUrlPromise.getPromise()},e.prototype.onStateChanged=function(e){if(this.logger.info(`onStateChanged called`),e===void 0)this.stateChangedListeners=this.stateChangedListeners.filter((function(e){return e.wrappedCallback===void 0}));else{this.offStateChanged(e);var t=function(t,n){e(t,n?n.url:``)};t.wrappedCallback=e,this.stateChangedListeners.push(t)}},e.prototype.offStateChanged=function(e){this.logger.info(`offStateChanged called`);var t=this.stateChangedListeners.length;return this.stateChangedListeners=this.stateChangedListeners.filter((function(t){return t.wrappedCallback!==e})),t>this.stateChangedListeners.length},e.prototype.addCallback=function(e){this.logger.info(`addListener called`),this.stateChangedListeners.indexOf(e,0)===-1&&e!==void 0&&this.stateChangedListeners.push(e)},e.prototype.removeCallback=function(e){this.logger.info(`removeListener called`);var t=this.stateChangedListeners.indexOf(e,0);return t>-1&&(this.stateChangedListeners.splice(t,1),!0)},e.prototype.registerMessageHandler=function(e){this.logger.info(`registerMessageHandler is called`),this.messageHandlers.register(e)},e.prototype.clearMessageHandlers=function(){this.logger.info(`clearMessageHandlers is called`),this.messageHandlers.clear()},e.prototype.notifyStateChanged=function(e,t){var n=this;this.logger.info(`notifyStateChanged called, will forward to ${this.stateChangedListeners.length} listeners`),this.stateChangedListeners.forEach((function(r){try{r(e,t)}catch(e){n.logger.error(`Error in callback ${e}`)}}))},e.prototype.tryMessageHandlers=function(e,t){if(!this.messageHandlers.active())return!1;var n,r=null;try{r=(n=JSON.parse(e.body))&&(n.evt||n.eventId)||null}catch{}var i={eventId:r,url:(this.connectionInfo?this.connectionInfo.baseEndpointUrl:``)+e.path,body:n,rawBody:e.body,headers:e.headers},a=this.messageHandlers.handleMessage(i);return!!a.isHandled&&(t.status=a.resultCode,a.responseHeaders&&(t.headers=a.responseHeaders),a.responseBody&&(t.body=a.responseBody),t.send(),!0)},e}();t.TrouterService=h},902:function(e,t){var n=this&&this.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)};Object.defineProperty(t,"__esModule",{value:!0}),t.safeToString=function(e){return typeof e==`string`?e:typeof e==`number`?e.toString():void 0},t.usedProtocolAfterFallback=function(e,t){return t?.kind===`v4c-websocket-failure`?`v4a`:e},t.isV4ConnectEvent=function(e){return Object.prototype.hasOwnProperty.call(e,`connectparams`)},t.adaptUrl=function(e,t){return t===`v4a`?e.replace(/\/v4\/c\b/,`/v4/a`).replace(`wss://`,`https://`).replace(`ws://`,`http://`):e.replace(/\/v4\/a\b/,`/v4/c`).replace(`https://`,`wss://`).replace(`http://`,`ws://`)},t.reconnectParamsWithoutUrls=function(e){if(e!==void 0)return n(n({},e),{reconnectUrl:void 0,serviceUrl:void 0})},t.ensureNumber=function(e){return typeof e==`string`?parseInt(e,10):e},t.redirectUrlIfPresent=function(e){if(e?.kind===`redirect`&&e.host!==void 0){var t=e.host;return t.endsWith(`/`)&&(t=t.substring(0,t.length-1)),t.endsWith(`/v4/c`)||t.endsWith(`/v4/a`)||(t+=`/v4/c`),t}}},983:(e,t,n)=>{(function(e,t){var n=e;n.version=`0.9.6`,n.protocol=1,n.transports=[],n.j=[],n.sockets={},n.connect=function(e,r){var i,a,o=n.util.parseUri(e);t&&t.location&&(o.protocol=o.protocol||t.location.protocol.slice(0,-1),o.host=o.host||(t.document?t.document.domain:t.location.hostname),o.port=o.port||t.location.port),i=n.util.uniqueUri(o);var s={host:o.host,secure:o.protocol==`https`,port:o.port||(o.protocol==`https`?443:80),query:o.query||``};return n.util.merge(s,r),!s[`force new connection`]&&n.sockets[i]||(a=new n.Socket(s)),!s[`force new connection`]&&a&&(n.sockets[i]=a),a||=n.sockets[i],s[`skipped handshake data`]?a.of(``):a.of(o.path.length>1?o.path:``)}})((e=n.nmd(e)).exports,MG===void 0?window:MG);var r=e.exports;(function(e,t){var n=e.util={},r=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,i=[`source`,`protocol`,`authority`,`userInfo`,`user`,`password`,`host`,`port`,`relative`,`path`,`directory`,`file`,`query`,`anchor`];n.parseUri=function(e){for(var t=r.exec(e||``),n={},a=14;a--;)n[i[a]]=t[a]||``;return n},n.uniqueUri=function(e){var n=e.protocol,r=e.host,i=e.port;return`document`in t?(r||=document.domain,i||=n==`https`&&document.location.protocol!==`https:`?443:document.location.port):(r||=`localhost`,i||n!=`https`||(i=443)),(n||`http`)+`://`+r+`:`+(i||80)},n.query=function(e,t){var r=n.chunkQuery(e||``),i=[];for(var a in n.merge(r,n.chunkQuery(t||``)),r)r.hasOwnProperty(a)&&i.push(a+`=`+r[a]);return i.length?`?`+i.join(`&`):``},n.chunkQuery=function(e){for(var t,n={},r=e.split(`&`),i=0,a=r.length;i<a;++i)(t=r[i].split(`=`))[0]&&(n[t[0]]=t[1]);return n};var a=!1;n.load=function(e){if(`document`in t&&document.readyState===`complete`||a)return e();n.on(t,`load`,e,!1)},n.on=function(e,t,n,r){e.attachEvent?e.attachEvent(`on`+t,n):e.addEventListener&&e.addEventListener(t,n,r)},n.request=function(e){if(e&&typeof XDomainRequest<`u`)return new XDomainRequest;if(typeof XMLHttpRequest<`u`&&(!e||n.ua.hasCORS))return new XMLHttpRequest;if(!e)try{return new window[[`Active`,`Object`].join(`X`)](`Microsoft.XMLHTTP`)}catch{}return null},typeof window<`u`&&n.load((function(){a=!0})),n.defer=function(e){if(!n.ua.webkit||typeof importScripts<`u`)return e();n.load((function(){setTimeout(e,100)}))},n.merge=function(e,t,r,i){var a,o=i||[],s=r===void 0?2:r;for(a in t)t.hasOwnProperty(a)&&n.indexOf(o,a)<0&&(typeof e[a]==`object`&&s?n.merge(e[a],t[a],s-1,o):(e[a]=t[a],o.push(t[a])));return e},n.mixin=function(e,t){n.merge(e.prototype,t.prototype)},n.inherit=function(e,t){function n(){}n.prototype=t.prototype,e.prototype=new n},n.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)===`[object Array]`},n.intersect=function(e,t){for(var r=[],i=e.length>t.length?e:t,a=e.length>t.length?t:e,o=0,s=a.length;o<s;o++)~n.indexOf(i,a[o])&&r.push(a[o]);return r},n.indexOf=function(e,t,n){var r=e.length;for(n=n<0?n+r<0?0:n+r:n||0;n<r&&e[n]!==t;n++);return r<=n?-1:n},n.toArray=function(e){for(var t=[],n=0,r=e.length;n<r;n++)t.push(e[n]);return t},n.ua={},n.ua.hasCORS=typeof XMLHttpRequest<`u`&&function(){try{var e=new XMLHttpRequest}catch{return!1}return e.withCredentials!=null}(),n.ua.webkit=typeof navigator<`u`&&/webkit/i.test(navigator.userAgent)})(r===void 0?e.exports:r,MG===void 0?window:MG),function(e,t){function n(){}e.EventEmitter=n,n.prototype.on=function(e,n){return this.$events||={},this.$events[e]?t.util.isArray(this.$events[e])?this.$events[e].push(n):this.$events[e]=[this.$events[e],n]:this.$events[e]=n,this},n.prototype.addListener=n.prototype.on,n.prototype.once=function(e,t){var n=this;function r(){n.removeListener(e,r),t.apply(this,arguments)}return r.listener=t,this.on(e,r),this},n.prototype.removeListener=function(e,n){if(this.$events&&this.$events[e]){var r=this.$events[e];if(t.util.isArray(r)){for(var i=-1,a=0,o=r.length;a<o;a++)if(r[a]===n||r[a].listener&&r[a].listener===n){i=a;break}if(i<0)return this;r.splice(i,1),r.length||delete this.$events[e]}else (r===n||r.listener&&r.listener===n)&&delete this.$events[e]}return this},n.prototype.removeAllListeners=function(e){return this.$events&&this.$events[e]&&(this.$events[e]=null),this},n.prototype.listeners=function(e){return this.$events||={},this.$events[e]||(this.$events[e]=[]),t.util.isArray(this.$events[e])||(this.$events[e]=[this.$events[e]]),this.$events[e]},n.prototype.emit=function(e){if(!this.$events)return!1;var n=this.$events[e];if(!n)return!1;var r=Array.prototype.slice.call(arguments,1);if(typeof n==`function`)n.apply(this,r);else{if(!t.util.isArray(n))return!1;for(var i=n.slice(),a=0,o=i.length;a<o;a++)i[a].apply(this,r)}return!0}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t){if(t&&t.parse)return e.JSON={parse:t.parse,stringify:t.stringify};throw Error(`JSON not available`)}(r===void 0?e.exports:r,typeof JSON<`u`?JSON:void 0),function(e,t){var n=e.parser={},r=n.packets=[`disconnect`,`connect`,`heartbeat`,`message`,`json`,`event`,`ack`,`error`,`noop`],i=n.reasons=[`transport not supported`,`client not handshaken`,`unauthorized`],a=n.advice=[`reconnect`],o=t.JSON,s=t.util.indexOf;n.encodePacket=function(e){var t=s(r,e.type),n=e.id||``,c=e.endpoint||``,l=e.ack,u=null;switch(e.type){case`error`:var d=e.reason?s(i,e.reason):``,f=e.advice?s(a,e.advice):``;d===``&&f===``||(u=d+(f===``?``:`+`+f));break;case`message`:e.data!==``&&(u=e.data);break;case`event`:var p={name:e.name};e.args&&e.args.length&&(p.args=e.args),u=o.stringify(p);break;case`json`:u=o.stringify(e.data);break;case`connect`:e.qs&&(u=e.qs);break;case`ack`:u=e.ackId+(e.args&&e.args.length?`+`+o.stringify(e.args):``)}var m=[t,n+(l==`data`?`+`:``),c];return u!=null&&m.push(u),m.join(`:`)},n.encodePayload=function(e){var t=``;if(e.length==1)return e[0];for(var n=0,r=e.length;n<r;n++)t+=`�`+e[n].length+`�`+e[n];return t};var c=/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;n.decodePacket=function(e){if(!(s=e.match(c)))return{};var t=s[2]||``,n=(e=s[5]||``,{type:r[s[1]],endpoint:s[4]||``});switch(t&&(n.id=t,s[3]?n.ack=`data`:n.ack=!0),n.type){case`error`:var s=e.split(`+`);n.reason=i[s[0]]||``,n.advice=a[s[1]]||``;break;case`message`:n.data=e||``;break;case`event`:try{var l=o.parse(e);n.name=l.name,n.args=l.args}catch{}n.args=n.args||[];break;case`json`:try{n.data=o.parse(e)}catch{}break;case`connect`:n.qs=e||``;break;case`ack`:if((s=e.match(/^([0-9]+)(\+)?(.*)/))&&(n.ackId=s[1],n.args=[],s[3]))try{n.args=s[3]?o.parse(s[3]):[]}catch{}break;case`disconnect`:n.reason=e}return n},n.decodePayload=function(e){if(e.charAt(0)==`�`){for(var t=[],r=1,i=``;r<e.length;r++)e.charAt(r)==`�`?(t.push(n.decodePacket(e.substr(r+1).substr(0,i))),r+=Number(i)+1,i=``):i+=e.charAt(r);return t}return[n.decodePacket(e)]}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t){function n(e,t){this.socket=e,this.sessid=t,this.connectErrorCallback=void 0,this.isOpened=!1}e.Transport=n,t.util.mixin(n,t.EventEmitter),n.prototype.onData=function(e){if(this.clearCloseTimeout(),(this.socket.connected||this.socket.connecting||this.socket.reconnecting)&&this.setCloseTimeout(),e!==``){var n=t.parser.decodePayload(e);if(n&&n.length)for(var r=0,i=n.length;r<i;r++)this.onPacket(n[r])}return this},n.prototype.onPacket=function(e){return this.socket.setHeartbeatTimeout(),e.type==`heartbeat`?this.onHeartbeat():(e.type==`connect`&&e.endpoint==``&&this.onConnect(),e.type==`error`&&e.advice==`reconnect`&&(this.isOpened=!1),this.socket.onPacket(e),this)},n.prototype.setCloseTimeout=function(){if(!this.closeTimeout){var e=this;this.closeTimeout=setTimeout((function(){e.onDisconnect()}),this.socket.closeTimeout)}},n.prototype.onDisconnect=function(){return this.close&&this.isOpened&&this.close(),this.clearTimeouts(),this.socket.onDisconnect(),this},n.prototype.onConnect=function(){return this.socket.onConnect(),this.connectErrorCallback=void 0,this},n.prototype.clearCloseTimeout=function(){this.closeTimeout&&=(clearTimeout(this.closeTimeout),null)},n.prototype.clearTimeouts=function(){this.clearCloseTimeout(),this.reopenTimeout&&clearTimeout(this.reopenTimeout)},n.prototype.packet=function(e){this.send(t.parser.encodePacket(e))},n.prototype.onHeartbeat=function(e){this.packet({type:`heartbeat`})},n.prototype.onOpen=function(){this.isOpened=!0,this.clearCloseTimeout(),this.socket.onOpen()},n.prototype.onClose=function(){this.isOpened=!1,this.socket.onClose(),this.onDisconnect()},n.prototype.prepareUrl=function(e){var n=this.socket.options;if(n[`skipped handshake data`])return n.rewriteUrlForProxy(n[`skipped handshake data`].websocketUrl+(e||``));var r=this.scheme()+`://`+n.host+`:`+n.port+`/`+n.resource+`/`+t.protocol+`/`+this.name+`/`+this.sessid+(e||``);return n.rewriteUrlForProxy(r)},n.prototype.ready=function(e,t){t.call(this)},n.prototype.clearEventHandlers=function(){return this}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t,n){function r(e){if(this.options={port:80,secure:!1,document:`document`in n&&document,resource:`socket.io`,transports:t.transports.slice(),"connect timeout":1e4,"try multiple transports":!0,reconnect:!0,"reconnection delay":500,"reconnection limit":1/0,"reopen delay":3e3,"max reconnection attempts":10,"sync disconnect on unload":!0,"auto connect":!0,"flash policy port":10843},t.util.merge(this.options,e),this.connected=!1,this.open=!1,this.connecting=!1,this.reconnecting=!1,this.namespaces={},this.buffer=[],this.doBuffer=!1,this.disconnected=!1,this.options[`sync disconnect on unload`]&&(!this.isXDomain()||t.util.ua.hasCORS)){var r=this;t.util.on(n,`unload`,(function(){r.disconnectSync()}),!1)}this.options[`auto connect`]&&this.connect()}function i(){}e.Socket=r,t.util.mixin(r,t.EventEmitter),r.prototype.of=function(e){return this.namespaces[e]||(this.namespaces[e]=new t.SocketNamespace(this,e),e!==``&&this.namespaces[e].packet({type:`connect`})),this.namespaces[e]},r.prototype.publish=function(){var e;for(var t in this.emit.apply(this,arguments),this.namespaces)this.namespaces.hasOwnProperty(t)&&(e=this.of(t)).$emit.apply(e,arguments)},r.prototype.handshake=function(e){var n=this,r=this.options;if(!n.disconnected){var a=r.rewriteUrlForProxy([`http`+(r.secure?`s`:``)+`:/`,r.host+`:`+r.port,r.resource,t.protocol,t.util.query(this.options.query,`t=`+ +new Date)].join(`/`));if(this.isXDomain()&&!t.util.ua.hasCORS){var o=document.getElementsByTagName(`script`)[0],s=document.createElement(`script`);s.src=a+`&jsonp=`+t.j.length,o.parentNode.insertBefore(s,o),t.j.push((function(e){u(e),s.parentNode.removeChild(s)}))}else{var c=t.util.request();c.open(`GET`,a,!0);var l=this.options.requestHeaders;l!==void 0&&Object.keys(l).forEach((function(e){c.setRequestHeader(e,l[e])})),c.onreadystatechange=function(){c.readyState==4&&(c.onreadystatechange=i,c.status==200?u(c.responseText):!n.reconnecting&&n.onError(c.responseText))},c.send(null)}}function u(t){t instanceof Error?n.onError(t.message):e.apply(null,t.split(`:`))}},r.prototype.getTransport=function(e){for(var n,r=e||this.transports,i=0;n=r[i];i++)if(t.Transport[n]&&t.Transport[n].check(this)&&(!this.isXDomain()||t.Transport[n].xdomainCheck()))return new t.Transport[n](this,this.sessionid);return null},r.prototype.connect=function(e){if(this.connecting||this.disconnected)return this;var n=this,r=function(r,i,a,o){function s(){if(!n.connected&&!n.disconnected)if(n.connecting=!1,clearTimeout(n.connectTimeoutTimer),n.options[`try multiple transports`]){for(;n.remainingTransports.length>0&&n.remainingTransports.splice(0,1)[0]!=n.transport.name;);n.remainingTransports.length?c(n.remainingTransports):n.publish(`connect_failed`)}else n.publish(`connect_failed`)}function c(e){if(n.transport&&(n.transport.clearTimeouts(),n.transport.clearEventHandlers()),n.transport=n.getTransport(e),!n.transport||n.disconnected)return n.publish(`connect_failed`);n.transport.ready(n,(function(){n.connecting=!0,n.publish(`connecting`,n.transport.name),n.transport.open(s),n.options[`connect timeout`]&&(n.connectTimeoutTimer=setTimeout((function(){s()}),n.options[`connect timeout`]))}))}n.sessionid=r,n.closeTimeout=1e3*a+2e3,n.heartbeatTimeout=1e3*i+2e3,n.transports=o?t.util.intersect(o.split(`,`),n.options.transports):n.options.transports,n.setHeartbeatTimeout(),n.remainingTransports=n.transports.slice(0),c(n.transports),n.once(`connect`,(function(){clearTimeout(n.connectTimeoutTimer),e&&typeof e==`function`&&e()}))};if(this.options[`skipped handshake data`]){var i=this.options[`skipped handshake data`];r(`v4c-`+new Date().getTime(),i.timeout,i.timeout,`websocket`)}else this.handshake(r);return this},r.prototype.setHeartbeatTimeout=function(){clearTimeout(this.heartbeatTimeoutTimer);var e=this;this.heartbeatTimeoutTimer=setTimeout((function(){e.transport.onClose()}),this.heartbeatTimeout)},r.prototype.packet=function(e){return this.connected&&!this.doBuffer?this.transport.packet(e):this.buffer.push(e),this},r.prototype.setBuffer=function(e){this.doBuffer=e,!e&&this.connected&&this.buffer.length&&(this.transport.payload(this.buffer),this.buffer=[])},r.prototype.disconnect=function(){return(this.connected||this.connecting)&&(this.open&&this.of(``).packet({type:`disconnect`}),this.onDisconnect(`booted`)),this.disconnected=!0,this},r.prototype.disconnectSync=function(){var e=t.util.request(),n=this.resource+`/`+t.protocol+`/`+this.sessionid;e.open(`GET`,n,!0),this.onDisconnect(`booted`)},r.prototype.isXDomain=function(){var e=n.location.port||(n.location.protocol==`https:`?443:80);return this.options.host!==n.location.hostname||this.options.port!=e},r.prototype.onConnect=function(){this.connected||(this.connected=!0,this.connecting=!1,this.doBuffer||this.setBuffer(!1),this.emit(`connect`))},r.prototype.onOpen=function(){this.open=!0},r.prototype.onClose=function(){this.open=!1,clearTimeout(this.heartbeatTimeoutTimer)},r.prototype.onPacket=function(e){this.of(e.endpoint).onPacket(e)},r.prototype.onError=function(e){e&&e.advice&&e.advice===`reconnect`&&(this.connected||this.connecting)&&(this.disconnect(),this.options.reconnect&&this.reconnect()),this.publish(`error`,e&&e.reason?e.reason:e)},r.prototype.onDisconnect=function(e){var t=this.connected,n=this.connecting;this.connected=!1,this.connecting=!1,this.open=!1,(t||n)&&(this.transport.close(),this.transport.clearTimeouts(),t?(this.publish(`disconnect`,e),e!=`booted`&&this.options.reconnect&&!this.reconnecting&&this.reconnect()):this.publish(`close_during_connecting`,e))},r.prototype.reconnect=function(){this.reconnecting=!0,this.reconnectionAttempts=0,this.reconnectionDelay=this.options[`reconnection delay`];var e=this,t=this.options[`max reconnection attempts`],n=this.options[`try multiple transports`],r=this.options[`reconnection limit`];function i(){if(e.connected){for(var t in e.namespaces)e.namespaces.hasOwnProperty(t)&&t!==``&&e.namespaces[t].packet({type:`connect`});e.publish(`reconnect`,e.transport.name,e.reconnectionAttempts)}clearTimeout(e.reconnectionTimer),e.removeListener(`connect_failed`,a),e.removeListener(`connect`,a),e.reconnecting=!1,delete e.reconnectionAttempts,delete e.reconnectionDelay,delete e.reconnectionTimer,delete e.redoTransports,e.options[`try multiple transports`]=n}function a(){if(e.reconnecting)return e.connected?i():e.connecting&&e.reconnecting?e.reconnectionTimer=setTimeout(a,1e3):void(e.reconnectionAttempts++>=t?e.redoTransports?(e.publish(`reconnect_failed`),i()):(e.on(`connect_failed`,a),e.options[`try multiple transports`]=!0,e.transport=e.getTransport(),e.redoTransports=!0,e.connect()):(e.reconnectionDelay<r&&(e.reconnectionDelay*=2),e.connect(),e.publish(`reconnecting`,e.reconnectionDelay,e.reconnectionAttempts),e.reconnectionTimer=setTimeout(a,e.reconnectionDelay)))}this.options[`try multiple transports`]=!1,this.reconnectionTimer=setTimeout(a,this.reconnectionDelay),this.on(`connect`,a)}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r,MG===void 0?window:MG),function(e,t){function n(e,t){this.socket=e,this.name=t||``,this.flags={},this.json=new r(this,`json`),this.ackPackets=0,this.acks={}}function r(e,t){this.namespace=e,this.name=t}e.SocketNamespace=n,t.util.mixin(n,t.EventEmitter),n.prototype.$emit=t.EventEmitter.prototype.emit,n.prototype.of=function(){return this.socket.of.apply(this.socket,arguments)},n.prototype.packet=function(e){return e.endpoint=this.name,this.socket.packet(e),this.flags={},this},n.prototype.send=function(e,t){var n={type:this.flags.json?`json`:`message`,data:e};return typeof t==`function`&&(n.id=++this.ackPackets,n.ack=!0,this.acks[n.id]=t),this.packet(n)},n.prototype.emit=function(e){var t=Array.prototype.slice.call(arguments,1),n=t[t.length-1],r={type:`event`,name:e};return typeof n==`function`&&(r.id=++this.ackPackets,r.ack=`data`,this.acks[r.id]=n,t=t.slice(0,t.length-1)),r.args=t,this.packet(r)},n.prototype.disconnect=function(){return this.name===``?this.socket.disconnect():(this.packet({type:`disconnect`}),this.$emit(`disconnect`)),this},n.prototype.onPacket=function(e){var n=this;function r(){n.packet({type:`ack`,args:t.util.toArray(arguments),ackId:e.id})}switch(e.type){case`connect`:this.$emit(`connect`);break;case`disconnect`:this.name===``?this.socket.onDisconnect(e.reason||`booted`):this.$emit(`disconnect`,e.reason||``);break;case`message`:case`json`:var i=[`message`,e.data];e.ack==`data`?i.push(r):e.ack&&this.packet({type:`ack`,ackId:e.id}),this.$emit.apply(this,i);break;case`event`:i=[e.name].concat(e.args),e.ack==`data`&&i.push(r),this.$emit.apply(this,i);break;case`ack`:this.acks[e.ackId]&&(this.acks[e.ackId].apply(this,e.args),delete this.acks[e.ackId]);break;case`error`:e.advice?this.socket.onError(e):e.reason==`unauthorized`?this.$emit(`connect_failed`,e.reason):this.$emit(`error`,e.reason)}},r.prototype.send=function(){this.namespace.flags[this.name]=!0,this.namespace.send.apply(this.namespace,arguments)},r.prototype.emit=function(){this.namespace.flags[this.name]=!0,this.namespace.emit.apply(this.namespace,arguments)}}(r===void 0?e.exports:r,r===void 0?e.parent.exports:r),function(e,t,n){function r(e){t.Transport.apply(this,arguments)}function i(){}e.websocket=r,t.util.inherit(r,t.Transport),r.prototype.name=`websocket`,r.prototype.open=function(e){var r,i=t.util.query(this.socket.options.query),a=this;return this.connectErrorCallback=e,r||=n.MozWebSocket||n.WebSocket,this.websocket=new r(this.prepareUrl(i)),this.websocket.onopen=function(){a.onOpen(),a.socket.setBuffer(!1)},this.websocket.onmessage=function(e){a.onData(e.data)},this.websocket.onclose=function(){a.onClose(),a.socket.setBuffer(!0)},this.websocket.onerror=function(e){a.onError(e)},this},r.prototype.send=function(e){return this.websocket.send(e),this},r.prototype.payload=function(e){for(var t=0,n=e.length;t<n;t++)this.packet(e[t]);return this},r.prototype.close=function(){return this.websocket.close(),this},r.prototype.onError=function(e){this.connectErrorCallback!==void 0&&(this.connectErrorCallback(),this.connectErrorCallback=void 0),this.socket.onError(e)},r.prototype.scheme=function(){return this.socket.options.secure?`wss`:`ws`},r.check=function(){return`WebSocket`in n&&!(`__addTask`in WebSocket)||`MozWebSocket`in n},r.xdomainCheck=function(){return!0},r.prototype.clearEventHandlers=function(){return this.websocket&&(this.websocket.onopen=this.websocket.onmessage=this.websocket.onclose=this.websocket.onerror=i),this},t.transports.push(`websocket`)}(r===void 0?e.exports:r.Transport,r===void 0?e.parent.exports:r,MG===void 0?window:MG),function(e,t,n){function r(e){e&&t.Transport.apply(this,arguments)}function i(){}e.XHR=r,t.util.inherit(r,t.Transport),r.prototype.open=function(){return this.socket.setBuffer(!1),this.onOpen(),this.get(),this.setCloseTimeout(),this},r.prototype.payload=function(e){for(var n=[],r=0,i=e.length;r<i;r++)n.push(t.parser.encodePacket(e[r]));this.send(t.parser.encodePayload(n))},r.prototype.send=function(e){return this.post(e),this},r.prototype.post=function(e){var t=this;this.socket.setBuffer(!0),this.sendXHR=this.request(`POST`),n.XDomainRequest&&this.sendXHR instanceof XDomainRequest?this.sendXHR.onload=this.sendXHR.onerror=function(){this.onload=i,t.socket.setBuffer(!1)}:this.sendXHR.onreadystatechange=function(){this.readyState==4&&(this.onreadystatechange=i,this.status==200?(clearTimeout(this.ackTimeoutTimer),t.socket.setBuffer(!1)):t.onClose())},this.sendXHR.send(e),t.sendXHR.ackTimeoutTimer=setTimeout((function(){t.onClose()}),t.socket.options.ackTimeoutMs)},r.prototype.close=function(){return this.onClose(),this},r.prototype.request=function(e){var n=t.util.request(this.socket.isXDomain()),r=t.util.query(this.socket.options.query,`t=`+ +new Date);n.open(e||`GET`,this.prepareUrl(r),!0);var i=this.socket.options.requestHeaders;if(i!==void 0&&Object.keys(i).forEach((function(e){n.setRequestHeader(e,i[e])})),e==`POST`)try{n.setRequestHeader?n.setRequestHeader(`Content-type`,`text/plain;charset=UTF-8`):n.contentType=`text/plain`}catch{}return n},r.prototype.scheme=function(){return this.socket.options.secure?`https`:`http`},r.check=function(e,r){try{var i=t.util.request(r),a=n.XDomainRequest&&i instanceof XDomainRequest,o=(e&&e.options&&e.options.secure?`https:`:`http:`)!=n.location.protocol;if(i&&(!a||!o))return!0}catch{}return!1},r.xdomainCheck=function(){return r.check(null,!0)},r.prototype.clearEventHandlers=function(){return this.sendXHR&&(this.sendXHR.onreadystatechange=this.sendXHR.onload=i),this}}(r===void 0?e.exports:r.Transport,r===void 0?e.parent.exports:r,MG===void 0?window:MG),function(e,t,n){function r(){t.Transport.XHR.apply(this,arguments)}function i(){}e[`xhr-polling`]=r,t.util.inherit(r,t.Transport.XHR),t.util.merge(r,t.Transport.XHR),r.prototype.name=`xhr-polling`,r.prototype.open=function(e){return this.connectErrorCallback=e,t.Transport.XHR.prototype.open.call(this),!1},r.prototype.get=function(){if(this.isOpened){var e=this;this.xhr=this.request(),n.XDomainRequest&&this.xhr instanceof XDomainRequest?(this.xhr.onload=function(){e.connectErrorCallback=void 0,this.onload=i,this.onerror=i,e.onData(this.responseText),e.get()},this.xhr.onerror=function(){e.onClose(),e.connectErrorCallback!==void 0&&(e.connectErrorCallback(),e.connectErrorCallback=void 0)}):this.xhr.onreadystatechange=function(){this.readyState==4&&(this.onreadystatechange=i,this.status==200?(e.connectErrorCallback=void 0,e.onData(this.responseText),e.get()):(e.onClose(),e.connectErrorCallback!==void 0&&(e.connectErrorCallback(),e.connectErrorCallback=void 0)))},this.xhr.send(null)}},r.prototype.onClose=function(){if(t.Transport.XHR.prototype.onClose.call(this),this.xhr){this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=i;try{this.xhr.abort()}catch{}this.xhr=null}},r.prototype.ready=function(e,n){var r=this;t.util.defer((function(){n.call(r)}))},r.prototype.clearEventHandlers=function(){return t.Transport.XHR.prototype.clearEventHandlers.call(this),this.xhr&&(this.xhr.onreadystatechange=this.xhr.onload=this.xhr.onerror=i),this},t.transports.push(`xhr-polling`)}(r===void 0?e.exports:r.Transport,r===void 0?e.parent.exports:r,MG===void 0?window:MG),t.io=r}},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={id:e,loaded:!1,exports:{}};return t[e].call(a.exports,a,a.exports,r),a.loaded=!0,a.exports}return r.nmd=e=>(e.paths=[],e.children||=[],e),r(882)})(),e.exports=t(vLe())),i9.exports;var e,t}var o9,xLe,s9=bLe(),SLe=class{constructor(e,t){this.logEvent=e=>{this._logger.debug(e),this._telemetryLogManager.sendEvent({name:e.name,tenant:DCe,properties:{...e.properties}})},this._logger=e.createChild(`TelemetrySender`),this._telemetryLogManager=t}};function CLe(e){return{registrationId:J0(),registrarServiceUrl:e.getTrouterSettings().registrarServiceUrl,registrarTtlInSeconds:e.getTrouterSettings().registrarTtlInSeconds,maxRegistrationTimeInMs:e.getTrouterSettings().maxRegistrationTimeInMs,registrarRefreshTimeoutInMs:e.getTrouterSettings().registrarRefreshTimeoutInMs,pnhAppId:e.getTrouterSettings().pnhAppId,pnhTemplate:e.getTrouterSettings().pnhTemplate,platform:e.getTrouterSettings().platform,platformUIVersion:e.getTrouterSettings().version,trouterServiceUrl:e.getTrouterSettings().trouterServiceUrl,version:e.getTrouterSettings().version,trouterConnectTimeoutInMs:e.getTrouterSettings().trouterConnectTimeoutInMs,productName:e.getTrouterSettings().productName,sessionId:J0(),environment:e.getTrouterSettings().environment,timeoutOptions:e.getTrouterSettings().timeoutOptions}}var wLe=class{constructor(e,t,n,r,i){this._ecsProvider=t,this._tokenProvider=n,this._isRegistered=!1,this._registeredChangedListeners=[],this._logger=e.createChild(`Trouter`),this._logger.info(`init`),this._initialRegistrationCompleteDefer=n3(),this._telemetryLogManager=r,this._acsProxy=i}async start(e){let t;if(this._trouterService)throw this._logger.error(`Trouterservice already initialized`),new Y({defaultError:J.CALL_STACK.SIGNALING_SERVICE_ALREADY_INITIALIZED});{let n=new Promise((async(t,n)=>{try{if(this._logger.info(`Trouterservice start`),this._trouterService=s9.createTrouterService(this._logger),!this._trouterService)throw this._logger.error(`Failed to create trouter service`),new Y({defaultError:J.CALL_STACK.SIGNALING_SERVICE_CREATE_FAIL});this._options=this._getTrouterConfig(this._logger,this._tokenProvider),e&&(this._options.trouterSettings.environment=e.environment||``,this._options.trouterSettings.sessionId=e.sessionId);let n,r,i=+new Date;this._trouterService.start(this._options),this._trouterService.onStateChanged(((e,t)=>{e===s9.TrouterState.Connected&&(n=+new Date)})),await this._initialRegistrationCompleteDefer.promise;let a=+new Date;n??=+new Date,r=n,t({trouterRequestCompletionTimeDeltaMs:Math.max(0,n-i),registrarRequestCompletionTimeDeltaMs:Math.max(0,a-r)})}catch(e){n(e)}}));try{t=await i3((()=>n),ZSe)}catch(e){throw e.code===408?(this._logger.error(`Signaling init timeout`),new Y({defaultError:J.CALL_STACK.SIGNALING_SERVICE_CREATE_TIMEOUT,defaultErrorMessageArgs:[ZSe]})):(this._logger.error(`Signaling init failed`),new Y({defaultError:J.CALL_STACK.SIGNALING_INIT_FAIL}))}}return t}isRegistered(){return this._isRegistered}onRegisteredChanged(e){this._logger.info(`TrouterService onRegisteredChanged`),this._registeredChangedListeners.push(e)}offRegisteredChanged(e){let t=this._registeredChangedListeners.indexOf(e);this._logger.info(`TrouterService offRegisteredChanged: ${t}`),t>-1&&this._registeredChangedListeners.splice(t,1)}stop(e){this._logger.info(`Trouterservice stop`),this._trouterService?(this._trouterService.onStateChanged(void 0),this._trouterService.stop(e),this._trouterService=void 0):this._logger.error(`Trouterservice not inited`)}registerMessageHandler(e){this._logger.info(`Trouterservice registerMessageHandler`),this._trouterService&&this._trouterService.registerMessageHandler(e)}clearMessageHandlers(){this._trouterService&&this._trouterService.clearMessageHandlers()}checkConnection(){this._trouterService&&this._trouterService.checkConnection()}state(){return this._logger.info(`Trouterservice state`),this._trouterService?this._trouterService.state():s9.TrouterState.Unknown}onStateChanged(e){this._logger.info(`Trouterservice onStateChanged`),this._trouterService&&this._trouterService.onStateChanged(e)}offStateChanged(e){this._logger.info(`Trouterservice offStateChanged`),this._trouterService&&this._trouterService.offStateChanged(e)}getTrouterUrlAsync(){return this._trouterService?(this._logger.info(`getTrouterUrlAsync called`),this._trouterService.getTrouterUrlAsync()):Promise.reject(`Trouterservice not started yet`)}getTrouterSettings(){return this._options.trouterSettings}_getSettings(){return CLe(this._ecsProvider)}_createTrouterTelemetryConfig(e){return{eventLogger:new SLe(e.createChild(`TrouterTelemetry`),this._telemetryLogManager),settings:{enabled:this._ecsProvider.getTrouterTelemetryConfig().enabled,logHealthCheckError:this._ecsProvider.getTrouterTelemetryConfig().logHealthCheckError,trouter_js_client_connected:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_connected,trouter_js_client_disconnected:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_disconnected,trouter_js_client_error:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_error,trouter_js_client_progress:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_progress,trouter_js_client_response:this._ecsProvider.getTrouterTelemetryConfig().trouter_js_client_response,numberOfStepsToMaintain:this._ecsProvider.getTrouterTelemetryConfig().numberOfStepsToMaintain,sendProgressTimeoutSecs:this._ecsProvider.getTrouterTelemetryConfig().sendProgressTimeoutSecs}}}_getTrouterConfig(e,t){return{trouterSettings:this._getSettings(),proxyUrlRewrite:this._acsProxy.hasProxyUrl()?e=>this._acsProxy.proxyfyUrl(e):void 0,skypeTokenProvider:t,telemetryConfig:this._createTrouterTelemetryConfig(e),registrationStateCallbackForAcsDoNotUse:e=>{this._logger.info(`TrouterService registrationStateCallbackForAcs: ${e}`),this._isRegistered=e,this._initialRegistrationCompleteDefer.isPending()&&this._isRegistered?this._initialRegistrationCompleteDefer.resolve():this._isRegistered?this._logger.info(`Signaling service is currently registered`):this._logger.error(`Signaling service is currently not registered. Unable to receive incoming calls`),this._onRegisteredChanged(e)}}}_onRegisteredChanged(e){this._logger.info(`TrouterService onRegisteredChanged: ${e}`),this._registeredChangedListeners.forEach((t=>{t(e)}))}},TLe=class{constructor(e){this._eventToTenantId={skypecosi_concore_web_csa_conversation_httprequest:m2,skypecosi_concore_web_ts_calling_in_call_session:m2,skypecosi_concore_web_ts_calling_call_setup_session:m2,skypecosi_concore_native_ts_calling_in_call_session:m2,skypecosi_concore_native_ts_calling_call_setup_session:m2,skypecosi_concore_web_pluginless_call_session:m2,skypecosi_concore_web_pluginless_modality_session:m2,skypecosi_concore_web_csa_conversation_callmodality:m2,skypecosi_concore_web_ts_calling_registry:m2,mdsc_webrtc_session:h2,mdsc_webrtc_session_initial:h2,live_events:ECe,mdsc_ortc_reports:h2,mdsc_ortc_reports_initial:h2,mdsc_rt_log:h2},this.getTenant=e=>this._eventToTenantId[e]?this._eventToTenantId[e]:``,this.getCallingAdapter=()=>({sendEvent:(e,t)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e),name:e,properties:t})}}),this.getGenericTelemetryLogger=e=>({sendEvent:e=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e.eventName),name:e.eventName,properties:e.props})}}),this.getMediaAdapter=()=>({sendEvent:(e,t)=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e),name:e,properties:t})}}),this.sendEvents=e=>(e.forEach((e=>{this._telemetryLogManager.sendEvent({tenant:this.getTenant(e.eventName),name:e.eventName,properties:e.props})})),Promise.resolve()),this._telemetryLogManager=e}},ELe=class{constructor(){this._timedVideoEffectProviderPromise=qwe(cue),this._timedModelConfigPromise=qwe(cue)}get videoEffectProviderDeferredPromise(){return this._timedVideoEffectProviderPromise.deferredPromise}get modelConfigDeferredPromise(){return this._timedModelConfigPromise.deferredPromise}async getVideoEffectProvider(){return this._timedVideoEffectProviderPromise.timerStart(),this._timedVideoEffectProviderPromise.deferredPromise.promise}async getModelConfig(){return this._timedModelConfigPromise.deferredPromise.resolve({modelUrl:``,weightPathPrefix:``}),this._timedModelConfigPromise.deferredPromise.promise}},DLe=class{constructor(e){this._encodedStreamsJsPath=e}async getWorkerUrl(){return this._encodedStreamsJsPath}},OLe=class{constructor(e,t){t||typeof e.createChild!=`function`?this.logger=e:this.logger=e.createChild(`HttpRequestDispatcher::`),this.proxy=t}getRequestOptions(e,t,n,r,i){return{headers:t||{},timeout:r,payload:n||null,responseType:i}}getAsync(e,t){return this.send(e,t,L3.GET)}postAsync(e,t){return this.send(e,t,L3.POST)}putAsync(e,t){return this.send(e,t,L3.PUT)}removeAsync(e,t){return this.send(e,t,L3.DELETE)}async send(e,t={headers:{}},n){let r=this.logger.createChild(`[${t.causeId||J0()}] HttpRequestDispatcher::`),i=J0();r.info(`Send, httpRequestId: ${i}, ${n} ${e}`),this.proxy&&(e=this.proxy.proxyfyUrl(e));let a=new AbortController,o=()=>{r.info(`Send, httpRequestId: ${i}, aborting`),a.abort()};r.info(`Send, httpRequestId: ${i}, responseType: ${t.responseType}`),t.headers=t.headers||{};let s=t.headers;s[`Content-Type`]||=t.contentType||`application/json`;let c={method:n,headers:t.headers,credentials:t.withCredentials?`include`:`same-origin`,keepalive:t.keepAlive||!1,signal:a.signal},l=Date.now(),u={url:e,start:new Date(l).toISOString(),end:``,statusCode:0,deltaTimeInMs:0,causeId:``},d=Z().telemetry.apiCauseIdHeader;try{n!==`GET`&&(c.body=t.payload||``);let a=fetch(e,c);if(typeof t.timeout==`number`&&t.timeout>0){let e=setTimeout((()=>o()),t.timeout);a=a.finally((()=>clearTimeout(e)))}bwe(t.timeout)&&t.timeout.then((()=>{o()}),(()=>{r.info(`Send, httpRequestId: ${i}, timeout promise rejected`)}));let s=await a;if(r.info(`Send, httpRequestId: ${i}, \n response status: ${s.status}`),t.headers[d]){let e=t.headers[d].split(`-`)[0];L6.getRemoveCauseIdToNetworkInfo(e)&&this.setCauseIdToNetworkInfo(u,s.status,e)}let f;try{f=await this.extractPayload(s,i,r)}catch(e){r.error(`Send, httpRequestId: ${i}, failed to parse response, error: ${e.message}`)}let p={};return s.headers.forEach(((e,t)=>{p[t]=e})),{response:f,request:{status:s.status,statusText:s.statusText,headers:p,responseURL:s.url,response:f,withCredentials:t.withCredentials},duration:Date.now()-l}}catch(n){if(r.error(`Send, httpRequestId: ${i}, \n failed ${c.method} ${e}, error: ${n.message}`),t.headers[d]){let e=t.headers[d].split(`-`)[0];L6.ifCauseIdExistsRemoveNetworkInfo(e)&&this.setCauseIdToNetworkInfo(u,n.code,e)}throw n.name===`AbortError`?(r.warn(`Send, httpRequestId: ${i}, aborted`),{aborted:!0}):(n.response?r.warn(`Send, httpRequestId: ${i}, \n response: ${i4(n.response)}`):n.request?r.warn(`Send, httpRequestId: ${i}, \n no response, request: ${i4(n.request)}`):r.warn(`Send, httpRequestId: ${i}, \n request not made, error: ${i4(n)}`),n||Error(`HttpRequestId: ${i}, failed`))}}async extractPayload(e,t,n){let r=this.getHeader(e,`content-type`,n),i=this.getHeader(e,`content-length`,n);switch(n.info(`ExtractPayload, httpRequestId: ${t}, \n parsing content type: ${r}, content length: ${i}`),r){case`application/json`:return i?await e.json():{};case`application/text`:return i?await e.text():``;case`application/octet-stream`:return i?await e.blob():new Blob;case`application/arraybuffer`:return i?await e.arrayBuffer():new ArrayBuffer(0);default:return e.json().catch((()=>{throw Error(`HttpRequestId: ${t}, unsupported content type: ${r}`)}))}}getHeader(e,t,n){n.info(`GetHeader, header: ${t}`);let r=e.headers.get(t.toLowerCase()),i;return r!==null&&(i=r),i}setCauseIdToNetworkInfo(e,t,n){e={...e,end:new Date().toISOString(),statusCode:t,deltaTimeInMs:Date.now()-new Date(e.start).getTime(),causeId:n},L6.setCauseIdToNetworkInfo(n,e)}},kLe=class{constructor(){this._activeEffects=[],this.eventEmitter=new E3.EventEmitter}on(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.VIDEO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.VIDEO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getActiveEffects(){return this._activeEffects}setActiveEffects(e){let t=this._activeEffects;this._activeEffects=e,this.eventEmitter.emit(`statusChanged`,t,this._activeEffects)}},ALe=class{constructor(){this._activeEffects={echoCancellation:[],noiseSuppression:[],autoGainControl:[]},this.eventEmitter=new E3.EventEmitter}on(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.AUDIO_EFFECTS.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.on(e,t)}off(e,t){if(e!==`statusChanged`)throw new Y({defaultError:J.FEATURES.AUDIO_EFFECTS.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this.eventEmitter.off(e,t)}getActiveEffects(){return this._activeEffects}setActiveEffects(e,t){let n={...this._activeEffects};this._activeEffects={...e},this.eventEmitter.emit(`statusChanged`,n,this._activeEffects,t)}},jLe=class{constructor(){this._providerValue=null}get providerValue(){return this._providerValue}set providerValue(e){this._providerValue=e}async getAudioEffectProvider(){return this.providerValue}};function MLe(){if(xLe)return o9;xLe=1;var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,i=(i,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of n(a))r.call(i,c)||c===o||e(i,c,{get:()=>a[c],enumerable:!(s=t(a,c))||s.enumerable});return i},a=t=>i(e({},`__esModule`,{value:!0}),t),o={};function s(e){return new Promise((t=>setTimeout(t,e)))}((t,n)=>{for(var r in n)e(t,r,{get:n[r],enumerable:!0})})(o,{mmrAdapter:()=>f}),o9=a(o);var c=class{constructor(){this.observers=new Set}subscribe(e){return typeof e==`function`&&(e={next:e}),this.observers.add(e),{unsubscribe:()=>{this.observers.delete(e)}}}},l=class extends c{constructor(e){super(),this.logger=e,this._state=3}get state(){return this._state}handleMessage(e){this.observers.forEach((t=>{t.next?.(e)}))}},u=`config`,d=class extends l{constructor(e,t){super(e),this.config=t,this.waitForChannel()}get tsCallingChannel(){return window.navigator.mediaDevices?.tsCallingChannel}getConfig(){return this.config}next(e){this.tsCallingChannel?this.tsCallingChannel.sendTsCallingMessage(e):this.logger.error(`tsCallingChannel is not available.`)}async waitForChannel(){do this.initializeTsCallingChannel(),await s(500);while(this.state!==1)}initializeTsCallingChannel(){if(!this.tsCallingChannel)return;this._state=1,this.tsCallingChannel.addEventListener(`messagerecv`,(e=>{e.detail?.message&&this.handleMessage(e.detail.message)}));let e=this.createConnectionURL();this.logger.log(`connectionUrl: ${e}`),this.tsCallingChannel.sendTsCallingMessage({WebViewRemotingControlChannel:{url:e.toString()}})}createConnectionURL(){let{loaderUrl:e,...t}=this.config;if(!e)throw this.logger.error(`loaderUrl was not passed in config.`),Error(`loaderUrl was not passed in config.`);try{let n=new URL(e);return n.searchParams.set(u,JSON.stringify(t)),n}catch(e){throw this.logger.error(`Failed to create connection URL`,e),e}}},f=(e,t)=>new d(e,t);return o9}var NLe=MLe();function PLe(){return!!navigator.mediaDevices?.tsCallingChannel}function FLe(e,t){let n=Z().vdi3,r=window.vdi3Debug??{},i=r.cdnUrl??n.cdnUrl;if(!i){let e=n.customTsVersion||W5.stackFactory.getVersion().build;if(e.includes(`_`))throw new Y({defaultError:J.FEATURES.VDI3.INVALID_CDN_URL});i=`${n.cdnBaseUrl}${e}/`}let a=r.connectionUrl??new URL(n.loaderHtmlPath,i).toString(),o=r.pluginlessUrl??new URL(n.pluginlessJsPath,i).toString();return{vdi3Config:{transport:NLe.mmrAdapter(e,{staleTimeout:n.transportConnectionTimeoutInMs,executionTimeout:n.remoteExecutionTimeoutInMs,messageChunkSize:n.chunkSize,writeLogToConsole:r.writeLogToConsole??t?.writeLogToConsole??n.writeLogToConsole,loaderUrl:a}),trouterSettings:{},pluginlessUrl:o,cdnUrl:i}}}var ILe={AcsCallingSDKWeb:{telemetry:{telemetryFlushTimeout:1e4,mediaStatsConfig:{enableVideoLeakInformation:!1,enableRenderCountCheck:!1}},calling:{allowAccessRawMediaStream:!1,deviceSelectionTimeoutInMs:1e4}},SkypeWebMedia:{mediaAgent:{useOneDsLogger:!0}}},LLe=class{constructor(){this._mapping=new WeakMap,this._eventEmitter=new D3,this._isRemoteStackActive=!0}get(e){return this._mapping.get(e)?.deref()}create(e){let t=this._createProxy(e);if(t===void 0)throw Error(`The type is not supported for proxy`);return this._mapping.set(e,new WeakRef(t)),t}replaceProxyToRaw(e){if(typeof e==`object`){if(Array.isArray(e))return e.map((e=>this.replaceProxyToRaw(e)));if(W6 in e)return e[W6]}return e}replaceRawToProxy(e,t){if(t===void 0&&(t=new Map),typeof e==`object`){if(e===null)return e;if(t.has(e))return t.get(e);if(W6 in e)return e;if(Array.isArray(e)){let n=e.map((e=>this.replaceRawToProxy(e,t)));return t.set(e,n),n}if(e instanceof Promise)return e.then((e=>this.replaceRawToProxy(e,t)));if(e instanceof ArrayBuffer||e instanceof Uint8Array||e instanceof Date||e instanceof RegExp)return e;if(this.isSupportedType(e)){let n=this.get(e);return n===void 0&&(n=this.create(e)),t.set(e,n),n}if(HOe(e))return t.set(e,e),e;let n={};t.set(e,n);for(let[r,i]of Object.entries(e))n[r]=this.replaceRawToProxy(i,t);return n[W6]=e,n}return e}on(e,t){this._eventEmitter.on(e,t)}once(e,t){this._eventEmitter.once(e,t)}dispose(){this._eventEmitter.removeAllListeners()}};function c9(e,t,n,r={}){return new Proxy(e,{get:(i,a)=>{let o,s;if(a===W6)return e;if(a in t)o=t[a],s=t;else{if(!(a in e))return;o=e[a],s=e}let c=r[a]??{input:!0,output:!0};if(typeof o==`function`){if(!n.isRemoteStackActive()&&s===e)throw new Y({defaultError:J.FEATURES.VDI3.REMOTE_STACK_TERMINATED});return new Proxy(o,{apply:(e,t,r)=>{let i=r.map((e=>typeof e==`function`?(...t)=>e.apply(null,n.replaceRawToProxy(t)):c.input?n.replaceProxyToRaw(e):e)),a=Reflect.apply(e,s,i);return c.output?n.replaceRawToProxy(a):a}})}return c.output?n.replaceRawToProxy(o):o},has:(n,r)=>r===W6||r in t||r in e})}var l9=class{constructor(e,t){this._proxyReferenceManager=e,this._tsObject=t,this._eventEmitter=new D3,this._handles=new Map,this._skipEvents=[`optimalVideoReceiversCountChanged`]}_proxyCall(e,t){let n=this._tsObject[e];if(n!==void 0)return n.apply(this._tsObject,t)}get instance(){return this._tsObject}changed(e){let t=`changed`,n=this._handles.get(t);n===void 0&&(n=this._proxyCall(`changedAsync`,[(...e)=>{this._eventEmitter.emit(t,...e)}]),this._handles.set(t,n));let r=(...t)=>{e.apply(null,t)};return this._eventEmitter.on(t,r),{dispose:()=>{this._eventEmitter.off(t,r),this._eventEmitter.listenerCount(t)===0&&(n?.then((e=>e.disposeAsync?.())).catch(M4),this._handles.delete(t))}}}on(e,t){if(this._skipEvents.includes(e))return{dispose:M4};let n=`on_${e}`,r=this._handles.get(n);r===void 0&&(r=this._proxyCall(`onAsync`,[e,(...e)=>{this._eventEmitter.emit(n,...e)}]),this._handles.set(n,r));let i=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(n,i),{dispose:()=>{this._eventEmitter.off(n,i),this._eventEmitter.listenerCount(n)===0&&(r?.then((e=>e.disposeAsync?.())).catch(M4),this._handles.delete(n))}}}once(e,t){if(this._skipEvents.includes(e))return{dispose:M4};let n=`once_${e}`,r=this._handles.get(n);r===void 0&&(r=this._proxyCall(`onceAsync`,[e,(...e)=>{this._eventEmitter.emit(n,...e)}]),this._handles.set(n,r));let i=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(n,i),{dispose:()=>{this._eventEmitter.off(n,i),this._eventEmitter.listenerCount(n)===0&&(r?.then((e=>e.disposeAsync?.())).catch(M4),this._handles.delete(n))}}}async changedAsync(e){let t=`changed`,n=this._handles.get(t);n===void 0&&(n=this._proxyCall(`changedAsync`,[(...e)=>{this._eventEmitter.emit(t,...e)}]),this._handles.set(t,n));let r=(...t)=>{e.apply(null,t)};return this._eventEmitter.on(t,r),await n,{dispose:()=>{this._eventEmitter.off(t,r),this._eventEmitter.listenerCount(t)===0&&(n?.then((e=>e.disposeAsync?.())).catch(M4),this._handles.delete(t))}}}async onAsync(e,t){if(this._skipEvents.includes(e))return{dispose:M4};let n=`on_${e}`,r=this._handles.get(n);r===void 0&&(r=this._proxyCall(`onAsync`,[e,(...e)=>{this._eventEmitter.emit(n,...e)}]),this._handles.set(n,r));let i=(...e)=>{t.apply(null,e)};return this._eventEmitter.on(n,i),await r,{dispose:()=>{this._eventEmitter.off(n,i),this._eventEmitter.listenerCount(n)===0&&(r?.then((e=>e.disposeAsync?.())).catch(M4),this._handles.delete(n))}}}},RLe=class extends l9{constructor(e,t){super(e,t),e.once(`remoteStackTerminated`,(()=>{this._eventEmitter.emit(`changed`),this._eventEmitter.emit(`on_callStateChanged`)}))}get state(){return this._proxyReferenceManager.isRemoteStackActive()?this._tsObject.state:7}get callEndDiagnosticsInfo(){return this._proxyReferenceManager.isRemoteStackActive()||this._tsObject.state===7?this._tsObject.callEndDiagnosticsInfo:{callControllerCode:0,callControllerSubCode:4521,phrase:`call ended due to RDP disconnection`,resultCategories:[`ExpectedError`]}}get ptzHandler(){throw new Y({defaultError:J.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}get broadcastMeeting(){throw new Y({defaultError:J.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}get videoLayout(){throw new Y({defaultError:J.FEATURES.VDI3.PROPERTY_UNAVAILABLE})}getIncomingRawAudioStream(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getUnmixedAudioProvider(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}init(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setDeviceManager(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}forceUpdate(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}startVideo(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopVideo(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}startScreenSharing(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}changeCropRegion(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stopScreenSharing(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}callSafeTransfer(e,t,n){return n===void 0&&(n={disableForwardingAndUnanswered:!1}),this._tsObject.callSafeTransfer(e,t,n)}setPlatformCallConstraints(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createStageAsync(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createStage(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendLastKnownStats(){this._proxyReferenceManager.isRemoteStackActive()&&this._tsObject.sendLastKnownStats().catch((e=>{}))}},zLe=class extends l9{constructor(e,t){super(e,t)}getSourceIdForMediaType(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDiagnosticData(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},BLe=class extends l9{constructor(e,t){super(e,t)}getRawStream(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}start(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}stop(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}selectVideoTrack(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setVideoStreamConfig(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDiagnosticData(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getStats(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},VLe=class extends l9{constructor(e,t){super(e,t),this._deletedCalls=[]}get calls(){return e4.difference(this._tsObject.calls,this._deletedCalls)}updateSkypeToken(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSetup(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCall(e,t,n){return this._tsObject.calls.find((t=>t.callId===e))}createDownloader(e,t,n,r,i){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCall(e,t,n,r,i){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCallWithGroupId(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCallWithMeetingData(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}deleteCall(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}async deleteCallAsync(e,t,n){return this._proxyReferenceManager.isRemoteStackActive()?await this._tsObject.deleteCallAsync?.apply(this._tsObject,arguments)??!1:!(!e||!this._tsObject.calls.includes(e))&&(this._deletedCalls.push(e),this._eventEmitter.emit(`on_callRemoved`,e),!0)}enableWindowUninitEventHandler(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}disableWindowUninitEventHandler(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},HLe=class extends l9{constructor(e,t){super(e,t)}getPermissionState(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}selectDevices(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSelectedDevices(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createPreview(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createPreviewRenderer(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createScreenSharingPreviewRenderer(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setBackgroundImageAsync(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getImagePropertyAsync(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}transformImageAsync(e,t,n,r){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendMessageDeviceVideoEffectsAsync(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}sendMessageDeviceVideoExtensibilityAsync(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setVideoCaptureConfigAsync(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}captureVideoFrameWithoutEffectsAsync(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getRawDeviceMediaStream(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setRawMediaStream(e,t,n){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}unsetRawMediaStream(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createAudioRenderer(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getPersonalizedNoiseSuppression(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setAudioProcessingFlags(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},ULe=class extends l9{constructor(e,t){super(e,t)}getPlatformSupportLevel(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setPlatformCallConstraints(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createCompositor(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCallRegistry(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}cancelOperation(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDeviceManager(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createDeviceManager(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getScreenSharingManager(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getSetup(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getEcsProvider(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getCallFeedback(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getAiMdp(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getVersion(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getMediaStatus(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getVideoCapabilityLimits(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}fireIntent(e,t){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}setAllowPrivacySensitiveApis(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getLiveStreamClient(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getUmsStream(e){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createVoipCallCoordinator(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}getDebugDump(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}createAiCameraManager(){throw new Y({defaultError:J.FEATURES.VDI3.METHOD_UNAVAILABLE})}},u9=class e extends LLe{constructor(e){super(),this._logger=e.createChild(`TsProxyReferenceManager`),this._mmrRdpConnectionManager=new bIe(this._logger),this._mmrRdpConnectionManager.on(`stateChange`,(e=>{e==`disconnected`&&this._remoteStackTerminated(`MMR RDP connection disconnected`)}))}static create(t){let n=new e(t);return this.proxyReferenceManagers.add(n),n}static notifyRemoteStackTermination(e){this.proxyReferenceManagers.forEach((t=>{t._remoteStackTerminated(e)}))}dispose(){this._mmrRdpConnectionManager.dispose(),e.proxyReferenceManagers.delete(this),super.dispose()}_remoteStackTerminated(e){!1!==this._isRemoteStackActive&&(this._logger.warn(`remote stack is terminated: ${e}`),this._isRemoteStackActive=!1,this._eventEmitter.emit(`remoteStackTerminated`))}_createProxy(e){let t=VOe(e);if(t!==H6.None){if(t===H6.ICall)return c9(e,new RLe(this,e),this);if(t===H6.ICallParticipant)return c9(e,new zLe(this,e),this);if(t===H6.ICallParticipantStream)return c9(e,new BLe(this,e),this);if(t===H6.ICallRegistry)return c9(e,new VLe(this,e),this);if(t===H6.IPluginlessCallingStack)return c9(e,new ULe(this,e),this);if(t===H6.IDeviceManager)return c9(e,new HLe(this,e),this)}}isSupportedType(e){return VOe(e)!==H6.None}isRemoteStackActive(){return!!this._isRemoteStackActive}};u9.proxyReferenceManagers=new Set,W5.monitor.onConnectionTerminated((()=>{u9.notifyRemoteStackTermination(`Disconnection detected by monitor`)}));var WLe=class{constructor(){this._eventEmitter=new E3.EventEmitter,this._shellTrouter=new W5.ShellTrouter,this._state=s9.TrouterState.Unknown,this._registeredState=!1,this._disposeAsync=[]}async initialize(){let e=(e,t)=>{this._state=e,this._eventEmitter.emit(`stateChanged`,e,t)},t=e=>{this._registeredState=e,this._eventEmitter.emit(`registeredChanged`,e)};await this._shellTrouter.onStateChanged(e),await this._shellTrouter.onRegisteredStateChanged(t),this._disposeAsync.push((async()=>{await this._shellTrouter.offStateChanged(e),await this._shellTrouter.offRegisteredStateChanged(t)}))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}async dispose(){for(let e of this._disposeAsync)await e().catch((e=>{}));this._eventEmitter.removeAllListeners()}state(){return this._state}registeredState(){return this._registeredState}get instance(){return this._shellTrouter}},GLe,d9={},f9={};function KLe(){if(GLe)return f9;GLe=1,Object.defineProperty(f9,"__esModule",{value:!0});var e=B5();return f9.default=function(){function t(){this._isAllowed=!1}return t.prototype.putBackgroundFetchAllowed=function(e){if(this._isAllowed=e,this.isBackgroundFetchAllowed()&&this._isAllowedDeferral){var t=this._isAllowedDeferral;this._isAllowedDeferral=void 0,t.resolve(void 0)}},t.prototype.isBackgroundFetchAllowed=function(){return this._isAllowed},t.prototype.waitForBackgroundFetchAllowed=function(){return this.isBackgroundFetchAllowed()?e.Resolved():(this._isAllowedDeferral||=e.Defer(),this._isAllowedDeferral.promise())},t}(),f9}var qLe,p9={};function JLe(){if(qLe)return p9;qLe=1,Object.defineProperty(p9,"__esModule",{value:!0});var e=B5();return p9.default=function(){function t(){this._isActive=!1}return t.prototype.putAppActive=function(e){if(this._isActive=e,this.isAppActive()&&this._appActiveDeferral){var t=this._appActiveDeferral;this._appActiveDeferral=void 0,t.resolve(void 0)}},t.prototype.isAppActive=function(){return this._isActive},t.prototype.waitForAppActive=function(){return this.isAppActive()?e.Resolved():(this._appActiveDeferral||=e.Defer(),this._appActiveDeferral.promise())},t}(),p9}var YLe,XLe,m9={},ZLe=function(){function e(e,t){this._event=e,this._callback=t}return e.prototype.unsubscribe=function(){this._event.unsubscribe(this._callback)},e}(),QLe=function(){function e(e){e===void 0&&(e=!1);var t=this;this._allowStopPropagation=e,this.fire=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];for(var r=t._subscribers,i=r.length-1;i>=0;i--){var a=r[i].apply(null,e);if(t._allowStopPropagation&&a)return!0}return!1},this._subscribers=[]}return e.prototype.dispose=function(){this._subscribers=[]},e.prototype.subscribe=function(e){return this._subscribers=this._subscribers.concat(e),new ZLe(this,e)},e.prototype.unsubscribe=function(e){this._subscribers=this._subscribers.filter((function(t){return t!==e}))},e}(),h9=$le(Object.freeze({__proto__:null,SubscriptionToken:ZLe,default:QLe})),$Le={};function g9(){return YLe||(YLe=1,e=$Le,Object.defineProperty(e,"__esModule",{value:!0}),(t=e.EcsConfigType||={})[t.Default=0]=`Default`,t[t.User=1]=`User`),$Le;var e,t}function eRe(){if(XLe)return m9;XLe=1,Object.defineProperty(m9,"__esModule",{value:!0});var e=h9,t=B5(),n=g9();return m9.default=function(){function r(t){this._config=t,this.configUpdated=new e.default,this._cachedConfigs={}}return r.prototype.initialize=function(){return this.updateConfigsToFetch()},r.prototype.updateConfigsToFetch=function(){var e=this,n=this._config.getConfig(),r=n.databaseInterface,i=n.configsToFetch;if(!r)return t.Resolved();for(var a=[],o=function(n){if(s._cachedConfigs[n])return`continue`;a.push(r.getData(n).then((function(t){t&&(e._cachedConfigs[n]=t)})).catch((function(){return t.Resolved()})))},s=this,c=0,l=i;c<l.length;c++)o(l[c]);return t.all(a).then((function(){a.length>0&&e.configUpdated.fire()}))},r.prototype.getEcsConfig=function(){return this._cachedConfigs[n.EcsConfigType.User]||this._cachedConfigs[n.EcsConfigType.Default]},r.prototype.getEcsConfigByType=function(e){return this._cachedConfigs[e]},r.prototype.putConfig=function(e){var n=this.getEcsConfig();this._cachedConfigs[e.configType]=e;var r=this.getEcsConfig();(r&&r.configType===e.configType||n&&r&&n.configType!==r.configType)&&this.configUpdated.fire();var i=this._config.getConfig().databaseInterface;return i?i.putData(e.configType,e):t.Resolved()},r}(),m9}var tRe,_9={};function nRe(){if(tRe)return _9;tRe=1;var e=_9&&_9.__assign||function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.apply(this,arguments)};return Object.defineProperty(_9,"__esModule",{value:!0}),_9.default=function(){function t(){}return t.prototype.initialize=function(e){if(this._config)throw Error(`ECS Configuration already initialized`);this._config=e},t.prototype.getConfig=function(){if(!this._config)throw Error(`ECS Configuration not yet initialized`);return this._config},t.prototype.setConfigsToFetch=function(t){if(!this._config)throw Error(`ECS Configuration not yet initialized`);this._config=e(e({},this._config),{configsToFetch:t})},t.prototype.setFetchTimeout=function(t){if(!this._config)throw Error(`ECS Configuration not yet initialized`);this._config=e(e({},this._config),{fetchTimeout:t})},t}(),_9}var rRe,iRe,v9={},y9={},aRe={},oRe={},b9={};function x9(){return rRe||(rRe=1,e=b9,t=b9&&b9.__assign||function(){return t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},t.apply(this,arguments)},Object.defineProperty(e,"__esModule",{value:!0}),e.assert=function(e,t){if(!e)throw Error(t)},e.isObject=function(e){return typeof e==`object`&&!!e},e.isString=function(e){return typeof e==`string`},e.attempt=function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];try{return e.apply(void 0,t)}catch(e){return Error(e)}},e.remove=function(e,t){for(var n=e.length-1;n>=0;n--)e[n]===t&&e.splice(n,1)},e.clone=function(n){return Array.isArray(n)?n.map(e.clone):e.isObject(n)?Object.keys(n).reduce((function(r,i){var a;return t(t({},r),((a={})[i]=e.clone(n[i]),a))}),{}):n}),b9;var e,t}function sRe(){return iRe||(iRe=1,function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=x9();e.DEFAULT_TIME_GROW_FACTOR=2.718281828459045,e.DEFAULT_TIME_JITTER=.11962656472,e.ExponentialTime=function(){function n(n,r,i,a){i===void 0&&(i=e.DEFAULT_TIME_GROW_FACTOR),a===void 0&&(a=e.DEFAULT_TIME_JITTER),this._initialTime=n,this._maxTime=r,this._growFactor=i,this._jitterFactor=a,t.assert(this._initialTime>0,`Initial delay must be positive`),t.assert(this._maxTime>0,`Delay upper bound must be positive`),t.assert(this._growFactor>=0,`Ratio must be non-negative`),t.assert(this._jitterFactor>=0,`Jitter factor must be non-negative`),this.reset()}return n.prototype.reset=function(){this._incrementCount=0,this._currentTime=Math.round(this._initialTime*(1+Math.random()*this._jitterFactor))},n.prototype.getTime=function(){return this._currentTime},n.prototype.getIncrementCount=function(){return this._incrementCount},n.prototype.calculateNext=function(){var e=this._currentTime*this._growFactor;return e>this._maxTime&&(e=this._maxTime),this._jitterFactor<1e-5?this._currentTime=e:this._currentTime=Math.round(Math.random()*e*this._jitterFactor+e),this._currentTime<this._initialTime&&(this._currentTime=this._initialTime),this._currentTime>this._maxTime&&(this._currentTime=this._maxTime),this._incrementCount++,this._currentTime},n.prototype.getTimeAndCalculateNext=function(){var e=this.getTime();return this.calculateNext(),e},n}()}(oRe)),oRe}var cRe,lRe,uRe,dRe,fRe,S9={},C9={};function pRe(){return cRe||(cRe=1,function(e){var t,n=C9&&C9.__extends||(t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},t(e,n)},function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}),r=C9&&C9.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)};Object.defineProperty(e,"__esModule",{value:!0});var i,a,o=B5(),s=x9(),c=sRe();function l(e){return!!e&&e.indexOf(`application/json`)===0}function u(e){return!!e&&e.indexOf(`application/x-www-form-urlencoded`)===0}function d(e){return!!e&&e.indexOf(`multipart/form-data`)===0}function f(e,t){return t.canceled||!t.statusCode||t.statusCode>=400&&t.statusCode<600?a.DoNotRetry:a.RetryCountedWithBackoff}(function(e){e[e.DontCare=0]=`DontCare`,e[e.Low=1]=`Low`,e[e.Normal=2]=`Normal`,e[e.High=3]=`High`,e[e.Critical=4]=`Critical`})(i=e.WebRequestPriority||={}),function(e){e[e.DoNotRetry=0]=`DoNotRetry`,e[e.RetryUncountedImmediately=1]=`RetryUncountedImmediately`,e[e.RetryUncountedWithBackoff=2]=`RetryUncountedWithBackoff`,e[e.RetryCountedWithBackoff=3]=`RetryCountedWithBackoff`,e[e.PauseUntilResumed=4]=`PauseUntilResumed`}(a=e.ErrorHandlingType||={}),e.DefaultOptions={priority:i.Normal},e.SimpleWebRequestOptions={MaxSimultaneousRequests:5,HungRequestCleanupIntervalMs:1e4,setTimeout:function(e,t){return setTimeout(e,t)},clearTimeout:function(e){return clearTimeout(e)}},e.DefaultErrorHandler=f;var p,m=[],h=[],g=[],_=0,v=0,y=function(){function t(t,n,i,a,o){this._action=t,this._url=n,this.options=i,this._getHeaders=a,this._blockRequestUntil=o,this._aborted=!1,this._timedOut=!1,this._paused=!1,this._created=Date.now(),this._finishHandled=!1,this._retryExponentialTime=new c.ExponentialTime(1e3,3e5),this._options=r(r({},e.DefaultOptions),i)}return t.prototype.getPriority=function(){return this._options.priority||i.DontCare},t.checkQueueProcessing=function(){for(var t=function(){var t=m.shift();h.push(t),(t._blockRequestUntil&&t._blockRequestUntil()||o.Resolved()).finally((function(){s.remove(h,t)})).then((function(){g.length<e.SimpleWebRequestOptions.MaxSimultaneousRequests&&!t._aborted?(g.push(t),b._scheduleHungRequestCleanupIfNeeded(),t._fire()):t._enqueue()}),(function(e){t._respond(`_blockRequestUntil rejected: `+e)}))};m.length>0&&g.length<e.SimpleWebRequestOptions.MaxSimultaneousRequests;)t()},t._scheduleHungRequestCleanupIfNeeded=function(){g.length>0&&p===void 0?p=e.SimpleWebRequestOptions.setTimeout(this._hungRequestCleanupTimerCallback,e.SimpleWebRequestOptions.HungRequestCleanupIntervalMs):g.length===0&&p&&(e.SimpleWebRequestOptions.clearTimeout(p),p=void 0)},t.prototype._removeFromQueue=function(){s.remove(g,this),s.remove(m,this)},t.prototype._assertAndClean=function(e,t){e||(this._removeFromQueue(),console.error(t),s.assert(e,t))},t.prototype._fire=function(){var n=this;this._xhr=new XMLHttpRequest,this._xhrRequestHeaders={};var r=s.attempt((function(){n._xhr.open(n._action,n._url,!0)}));if(r)this._respond(r.toString());else{if(this._options.timeout){var i=v;i!==3&&(this._assertAndClean(!this._requestTimeoutTimer,`Double-fired requestTimeoutTimer`),this._requestTimeoutTimer=e.SimpleWebRequestOptions.setTimeout((function(){n._requestTimeoutTimer=void 0,n._timedOut=!0,n.abort()}),this._options.timeout)),(i===3||i<=1)&&(this._xhr.timeout=this._options.timeout,this._xhr.ontimeout=function(){v=3,i===3&&(n._timedOut=!0,n._aborted=!0,n._respond(`TimedOut`))})}var a=_;a===3?this._options.streamingDownloadProgress&&(this._xhr.onreadystatechange=function(){n._xhr&&n._xhr.readyState===3&&n._options.streamingDownloadProgress&&!n._aborted&&n._options.streamingDownloadProgress(n._xhr.responseText)}):(a===0&&(_=1),this._xhr.onreadystatechange=function(){n._xhr&&(n._xhr.readyState!==3||!n._options.streamingDownloadProgress||n._aborted?n._xhr.readyState===4&&(a===0&&_===1&&e.SimpleWebRequestOptions.setTimeout((function(){_!==3&&(_=2)}),1e4),n._respond()):n._options.streamingDownloadProgress(n._xhr.responseText))}),a!==2&&(this._xhr.onload=function(){_=3,a===3&&n._respond()},this._xhr.onerror=function(){_=3,a===3&&n._respond()}),this._xhr.onabort=function(){n._aborted=!0,n._respond(`Aborted`)},this._xhr.upload&&this._options.onProgress&&(this._xhr.upload.onprogress=this._options.onProgress);var o=this._options.acceptType||`json`,c=this._options.customResponseType||t._getResponseType(o),l=s.attempt((function(){n._xhr.responseType=c}));if(l&&c!==`json`)throw l;b._setRequestHeader(this._xhr,this._xhrRequestHeaders,`Accept`,t.mapContentType(o)),this._xhr.withCredentials=!!this._options.withCredentials;var u=this.getRequestHeaders(),d={};if(Object.keys(u).forEach((function(e){var t=u[e],r=e.toLowerCase();r===`content-type`?n._assertAndClean(!1,`Don't set Content-Type with options.headers -- use it with the options.contentType property`):r===`accept`?n._assertAndClean(!1,`Don't set Accept with options.headers -- use it with the options.acceptType property`):(n._assertAndClean(!d[r],`Setting duplicate header key: `+d[r]+` and `+e),t==null?console.warn(`Tried to set header "`+e+`" on request with "`+t+`" value, header will be dropped`):(d[r]=!0,b._setRequestHeader(n._xhr,n._xhrRequestHeaders,e,t)))})),this._options.sendData){var f=t.mapContentType(this._options.contentType||`json`);b._setRequestHeader(this._xhr,this._xhrRequestHeaders,`Content-Type`,f);var p=t.mapBody(this._options.sendData,f);this._xhr.send(p)}else this._xhr.send()}},t._setRequestHeader=function(e,t,n,r){e.setRequestHeader(n,r),t[n]=r},t.mapContentType=function(e){return e===`json`?`application/json`:e===`form`?`application/x-www-form-urlencoded`:e},t.mapBody=function(e,t){if(l(t)){if(!s.isString(e))return JSON.stringify(e)}else if(u(t)){if(!s.isString(e)&&s.isObject(e)){var n=e;return Object.keys(n).map((function(e){return encodeURIComponent(e)+(n[e]?`=`+encodeURIComponent(n[e].toString()):``)})).join(`&`)}}else if(d(t)){if(s.isObject(e)){var r=new FormData,i=e;return Object.keys(i).forEach((function(e){return r.append(e,i[e])})),r}s.assert(!1,`contentType multipart/form-data must include an object as sendData`)}return e},t.prototype.setUrl=function(e){this._url=e},t.prototype.setHeader=function(e,t){this._options.augmentHeaders||(this._options.augmentHeaders={}),t?this._options.augmentHeaders[e]=t:delete this._options.augmentHeaders[e]},t.prototype.getRequestHeaders=function(){var e={};return!this._getHeaders||this._options.overrideGetHeaders||this._options.headers||(e=r(r({},e),this._getHeaders())),this._options.overrideGetHeaders&&(e=r(r({},e),this._options.overrideGetHeaders)),this._options.headers&&(e=r(r({},e),this._options.headers)),this._options.augmentHeaders&&(e=r(r({},e),this._options.augmentHeaders)),e},t.prototype.getOptions=function(){return s.clone(this._options)},t.prototype.setPriority=function(e){this._options.priority!==e&&(this._options.priority=e,this._paused||this._xhr||(s.remove(m,this),this._enqueue()))},t.prototype.resumeRetrying=function(){this._paused?(this._paused=!1,this._enqueue()):s.assert(!1,`resumeRetrying() called but not paused!`)},t.prototype._enqueue=function(){var e=this;if(!this._aborted&&!(g.indexOf(this)>=0||h.indexOf(this)>=0||m.indexOf(this)>=0)){var n=m.findIndex((function(t){return t.getPriority()===e.getPriority()&&t._created>e._created||t.getPriority()<e.getPriority()}));n>-1?m.splice(n,0,this):m.push(this),t.checkQueueProcessing()}},t._getResponseType=function(e){return e===`blob`?`arraybuffer`:e===`text/xml`||e===`application/xml`?`document`:e===`text/plain`?`text`:`json`},t._hungRequestCleanupTimerCallback=function(){p=void 0,g.filter((function(e){return!(!e._xhr||e._xhr.readyState!==4)&&(console.warn(`SimpleWebRequests found a completed XHR that hasn't invoked it's callback functions, manually responding`),!0)})).forEach((function(e){e._respond()})),b._scheduleHungRequestCleanupIfNeeded()},t}();e.SimpleWebRequestBase=y;var b=function(t){function r(e,n,r,i,a){return t.call(this,e,n,r,i,a)||this}return n(r,t),r.prototype.abort=function(){this._aborted?s.assert(!1,`Already aborted `+this._action+` request to `+this._url):(this._aborted=!0,this._retryTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._retryTimer),void 0),this._requestTimeoutTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),void 0),this._deferred?(this._respond(`Aborted`),this._xhr&&this._xhr.abort()):s.assert(!1,`Haven't even fired start() yet -- can't abort`))},r.prototype.start=function(){var e=this;return this._deferred?(s.assert(!1,`WebRequest already started`),o.Rejected(`WebRequest already started`)):(this._deferred=o.Defer(),this._deferred.onCancel((function(){e.abort()})),this._enqueue(),this._deferred.promise())},r.prototype._respond=function(t){var n=this;if(!this._finishHandled){this._finishHandled=!0,this._removeFromQueue(),this._retryTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._retryTimer),void 0),this._requestTimeoutTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),void 0);var r,i=0;if(this._xhr)try{i=this._xhr.status,r=this._xhr.statusText||t}catch{}else r=t||`Browser Error - Possible CORS or Connectivity Issue`;var o,c,u={};if(this._xhr){if((this._xhr.getAllResponseHeaders()||``).split(/\r?\n/).forEach((function(e){if(e.length!==0){var t=e.indexOf(`:`);t===-1?u[e]=``:u[e.substr(0,t).toLowerCase()]=e.substr(t+1).trim()}})),!u[`content-type`]){var d=this._xhr.getResponseHeader(`content-type`);d&&(u[`content-type`]=d)}if(o=this._xhr.response,u[`content-type`]&&l(u[`content-type`])&&(!o||!s.isObject(o))&&(this._xhr.responseType===`text`||this._xhr.responseType===``)&&this._xhr.responseText)try{o=JSON.parse(this._xhr.responseText)}catch(e){c=e,console.warn(`Failed to parse XHR JSON response`)}}if(this._xhr&&this._xhr.readyState===4&&(i>=200&&i<300||i===304)){var p={url:this._xhr.responseURL||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:i,statusText:r,headers:u,body:o,responseParsingException:c};this._deferred.resolve(p)}else{var m={url:(this._xhr?this._xhr.responseURL:void 0)||this._url,method:this._action,requestOptions:this._options,requestHeaders:this._xhrRequestHeaders||{},statusCode:i,statusText:r,headers:u,body:o,canceled:this._aborted,timedOut:this._timedOut,responseParsingException:c};this._options.augmentErrorResponse&&this._options.augmentErrorResponse(m);var h=this._options.customErrorHandler?this._options.customErrorHandler(this,m):f(this,m);h!==a.DoNotRetry&&(this._options.retries&&this._options.retries>0||h===a.PauseUntilResumed||h===a.RetryUncountedImmediately||h===a.RetryUncountedWithBackoff)?(h===a.RetryCountedWithBackoff&&this._options.retries--,this._requestTimeoutTimer&&=(e.SimpleWebRequestOptions.clearTimeout(this._requestTimeoutTimer),void 0),this._aborted=!1,this._timedOut=!1,this._finishHandled=!1,this._xhr&&(this._xhr.onabort=null,this._xhr.onerror=null,this._xhr.onload=null,this._xhr.onprogress=null,this._xhr.onreadystatechange=null,this._xhr.ontimeout=null,this._xhr=void 0,this._xhrRequestHeaders=void 0),h===a.PauseUntilResumed?this._paused=!0:h===a.RetryUncountedImmediately?this._enqueue():this._retryTimer=e.SimpleWebRequestOptions.setTimeout((function(){n._retryTimer=void 0,n._enqueue()}),this._retryExponentialTime.getTimeAndCalculateNext())):this._deferred.reject(m)}y.checkQueueProcessing()}},r}(y);e.SimpleWebRequest=b}(C9)),C9}function mRe(){if(lRe)return S9;lRe=1;var e=S9&&S9.__assign||function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.apply(this,arguments)};Object.defineProperty(S9,"__esModule",{value:!0});var t=x9(),n=pRe();return S9.GenericRestClient=function(){function r(e){this._defaultOptions={excludeEndpointUrl:!1,withCredentials:!1,retries:0},this._endpointUrl=e}return r.prototype._performApiCall=function(r,i,a,o){var s=this;o===void 0&&(o={});var c=e(e({},this._defaultOptions),o);a&&(c.sendData=a),c.eTag&&(c.augmentHeaders||={},c.augmentHeaders[`If-None-Match`]=c.eTag),c.contentType||=t.isString(c.sendData)?`form`:`json`;var l=c.excludeEndpointUrl?r:this._endpointUrl+r;return new n.SimpleWebRequest(i,l,c,(function(){return s._getHeaders(c)}),(function(){return s._blockRequestUntil(c)})).start().then((function(e){return s._processSuccessResponse(e),e}))},r.prototype._getHeaders=function(e){return{}},r.prototype._blockRequestUntil=function(e){},r.prototype._processSuccessResponse=function(e){},r.prototype.performApiGet=function(e,t){return this.performApiGetDetailed(e,t).then((function(e){return e.body}))},r.prototype.performApiGetDetailed=function(e,t){return this._performApiCall(e,`GET`,void 0,t)},r.prototype.performApiPost=function(e,t,n){return this.performApiPostDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiPostDetailed=function(e,t,n){return this._performApiCall(e,`POST`,t,n)},r.prototype.performApiPatch=function(e,t,n){return this.performApiPatchDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiPatchDetailed=function(e,t,n){return this._performApiCall(e,`PATCH`,t,n)},r.prototype.performApiPut=function(e,t,n){return this.performApiPutDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiPutDetailed=function(e,t,n){return this._performApiCall(e,`PUT`,t,n)},r.prototype.performApiDelete=function(e,t,n){return this.performApiDeleteDetailed(e,t,n).then((function(e){return e.body}))},r.prototype.performApiDeleteDetailed=function(e,t,n){return this._performApiCall(e,`DELETE`,t,n)},r}(),S9}function hRe(){return uRe||(uRe=1,function(e){function t(t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}Object.defineProperty(e,"__esModule",{value:!0}),t(sRe()),t(mRe()),t(pRe())}(aRe)),aRe}function gRe(){return fRe?dRe:(fRe=1,dRe=hRe())}var _Re,vRe,yRe,bRe,w9={},T9={};function xRe(){return _Re?T9:(_Re=1,Object.defineProperty(T9,"__esModule",{value:!0}),T9.TelemetryEventBase=function(){function e(){}return e.prototype.getAttributes=function(){return{Source:`ecs_client`}},e}(),T9)}function SRe(){if(vRe)return w9;vRe=1;var e,t=w9&&w9.__extends||(e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)},function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)});return Object.defineProperty(w9,"__esModule",{value:!0}),w9.EcsConfigFetchResponse=function(e){function n(t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){var v=e.call(this)||this;return v._responseTime=t,v._responseCode=n,v._fetchAttempts=r,v._hasValidToken=i,v._serverEndpoint=a,v._fetchDurationValid=o,v._cacheAvailable=s,v._responseSize=c,v._configAge=l,v._configExpired=u,v._fetchStart=d,v._fetchEnd=f,v._isUserConfig=p,v._etag=m,v._timedOut=h,v._responseParsingException=g,v._errorMessage=_,v}return t(n,e),n.prototype.getEventName=function(){return`ecs_tsclient_fetch_config`},n.prototype.getAttributes=function(){var t=e.prototype.getAttributes.call(this);return t.fetch_delay_ms=this._responseTime,t.fetch_response_code=this._responseCode,t.fetch_attempts=this._fetchAttempts,t.authenticated_user=this._hasValidToken,t.url=this._serverEndpoint,t.fetch_duration_valid=this._fetchDurationValid,t.cache_available=this._cacheAvailable,t.response_size=this._responseSize,t.config_age=this._configAge,t.config_expired=this._configExpired,t.fetch_start=this._fetchStart,t.fetch_end=this._fetchEnd,t.is_user_config=this._isUserConfig,this._etag&&(t.fetched_etag=this._etag),this._timedOut!==void 0&&(t.fetch_timed_out=this._timedOut),this._responseParsingException&&(t.fetch_response_parsing_error=this._responseParsingException.message),this._errorMessage&&(t.fetch_error_message=this._errorMessage),t},n}(xRe().TelemetryEventBase),w9}function CRe(){if(yRe)return y9;yRe=1;var e,t=y9&&y9.__extends||(e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)},function(t,n){function r(){this.constructor=t}e(t,n),t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}),n=y9&&y9.__assign||function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)};Object.defineProperty(y9,"__esModule",{value:!0});var r,i,a=gRe(),o=B5(),s=g9(),c=SRe(),l=1728e5,u=18e5,d=31536e6,f=3e4,p=function(e){function n(t,n,r,i,a,o,s,c){var l=e.call(this,t)||this;l._config=n,l._skypeTokenData=r,l._appActiveData=i,l._allowBackgroundFetchData=a,l._etag=o,l._getUserConfig=s;var u=l._config.getConfig();if(l._apiPath=u.clientTeam?`/config/v1/`+u.clientName+`/`+u.clientVersion+`/`+u.clientTeam:`/config/v1/`+u.clientName+`/`+u.clientVersion,c){var d=Object.keys(c).map((function(e){return encodeURIComponent(e)+`=`+encodeURIComponent(c[e].toString())}));d&&(l._apiPath+=`?`+d.join(`&`))}return l}return t(n,e),n.prototype._blockRequestUntil=function(e){var t=this;if(this._getUserConfig&&!this._skypeTokenData.isSkypeTokenValid()&&console.log(`ECS - Delaying User config fetch until we have a valid SkypeToken`),!this._appActiveData.isAppActive()&&!this._allowBackgroundFetchData.isBackgroundFetchAllowed()){var n=this._getUserConfig?`User config`:`config`;console.log(`ECS - Delaying `+n+` fetch until the app is active (or background fetch is allowed)`)}return o.race([this._appActiveData.waitForAppActive(),this._allowBackgroundFetchData.waitForBackgroundFetchAllowed()]).then((function(){if(t._getUserConfig)return t._skypeTokenData.waitForValidSkypeToken()})).then((function(){i=Date.now()}))},n.prototype._getHeaders=function(){var e={};return this._etag&&(e[`If-None-Match`]=this._etag),this._getUserConfig&&(e.Authorization=this._skypeTokenData.getSkypeToken()),e},n.prototype.getConfig=function(){var t=this._config.getConfig().fetchTimeout;return t!==void 0&&(t<0?t=0:t>0&&t<f&&(t=f)),e.prototype.performApiGetDetailed.call(this,this._apiPath,{timeout:t})},n}(a.GenericRestClient);return y9.default=function(){function e(e,t,n,r,i){this._config=e,this._skypeTokenData=t,this._appActiveData=n,this._allowBackgroundFetchData=r,this._telemetryManager=i,this._ecsFailureBackoffTimer=new a.ExponentialTime(1e3,3e5),this._cacheMaxAgeRegex=/.*max-age=(\d+).*/gi,this._serverIndex=NaN}return e.prototype.getConfig=function(e,t,r){var a=this,l=this._config.getConfig().hosts;if((isNaN(this._serverIndex)||this._serverIndex>l.length-1)&&(this._serverIndex=Math.floor(Math.random()*l.length)),!l||!l.length)return o.Rejected(Error(`no configuration service endpoint`));var u=o.Defer(),d=0,f=function(){var m=e&&e.eTag?e.eTag:void 0,h=new p(l[a._serverIndex],a._config,a._skypeTokenData,a._appActiveData,a._allowBackgroundFetchData,m,t,r);d++,h.getConfig().then((function(r){var f=r.headers.etag,p=r.headers.expires;r.body&&r.body.Headers&&(f||=r.body.Headers.ETag,p||=r.body.Headers.Expires);var h=a._calculateResponseTimeInfo(e);if(!f||!p)return console.warn(`ECS - Service returned an empty ETag or Expiration header: `+JSON.stringify(r)),o.Rejected({timedOut:!1,responseParsingException:Error(`ECS Service returned empty ETag or Expiration header`),responseCode:r.statusCode});var g,_=new Date(a._calculateExpirationDate(r.headers)).getTime();if(r.statusCode===304&&e)(g=n({},e)).configType=t?s.EcsConfigType.User:s.EcsConfigType.Default,g.eTag=f,g.expiration=_,g.cacheUpdateTime=h.lastResponseTime,g.lastFetchTokenHash=a._skypeTokenData.getSkypeTokenHash(r.requestHeaders.Authorization);else{if(typeof r.body!=`object`)return console.warn(`ECS - Service returned invalid response `+JSON.stringify(r)),o.Rejected({timedOut:!1,responseParsingException:Error(`ECS Service returned invalid response body`),responseCode:r.statusCode});g={config:r.body,configType:t?s.EcsConfigType.User:s.EcsConfigType.Default,eTag:f,expiration:_,cacheUpdateTime:i,lastFetchTokenHash:a._skypeTokenData.getSkypeTokenHash(r.requestHeaders.Authorization),appVersion:a._config.getConfig().clientVersion}}a._telemetryManager.sendTelemetryEvent(new c.EcsConfigFetchResponse(h.fetchDelayMs,r.statusCode,d,a._skypeTokenData.isSkypeTokenValid(),l[a._serverIndex],h.fetchDurationValid,!!m,JSON.stringify(r).length,h.cacheAge,!(e&&e.expiration-Date.now()>0),i,h.lastResponseTime,t,f)),a._ecsFailureBackoffTimer.reset(),u.resolve(g)})).catch((function(n){var r={timedOut:n&&n.timedOut||!1,responseParseError:n&&n.responseParsingException,responseCode:n&&n.statusCode||0,message:a._getErrorMessage(n)};console.error(`ECS - Service request failed to return a response (timedOut: `+r.timedOut+`, responseParseError: `+r.responseParseError+`)`);var o=a._calculateResponseTimeInfo(e);a._telemetryManager.sendTelemetryEvent(new c.EcsConfigFetchResponse(o.fetchDelayMs,r.responseCode,d,a._skypeTokenData.isSkypeTokenValid(),l[a._serverIndex],o.fetchDurationValid,!!m,0,o.cacheAge,!(e&&e.expiration-Date.now()>0),i,o.lastResponseTime,t,void 0,r.timedOut,r.responseParseError,r.message));var s=a._config.getConfig().fetchAttemptMax;s&&d>s||setTimeout((function(){f()}),a._ecsFailureBackoffTimer.getTimeAndCalculateNext())}))};return f(),u.promise()},e.prototype._calculateExpirationDate=function(e){var t=Date.now()+l;if(e.date&&e.expires){var n=new Date(e.date).getTime(),r=Date.now()-n,i=new Date(e.expires).getTime();return isNaN(i)?t:Math.min(t,i+r)}var a=this._cacheMaxAgeRegex.exec(e[`cache-control`]);return this._cacheMaxAgeRegex.lastIndex=0,a&&a.length===2?Math.min(t,Date.now()+1e3*Number(a[1])):Date.now()+u},e.prototype._calculateResponseTimeInfo=function(e){var t=(r=Date.now())-i;return{lastResponseTime:r,fetchDelayMs:t,fetchDurationValid:!(t<0||t>d),cacheAge:e?r-e.cacheUpdateTime:0}},e.prototype._getErrorMessage=function(e){if(e)return typeof e==`string`?e:typeof e==`object`&&(e.statusText||e.message)?e.statusText||e.message:void 0},e}(),y9}function wRe(){if(bRe)return v9;bRe=1,Object.defineProperty(v9,"__esModule",{value:!0});var e=g9(),t=CRe();return v9.default=function(){function n(n,r,i,a,o,s){var c=this;this._config=n,this._skypeTokenData=r,this._cache=i,this._isFetchingSettings={},this._pendingFetch={},this._pendingTimers={},this._subscriptionToken=null,this._paused=!1,this._fetchEcsSettingsIfNeeded=function(t){var n=c._config.getConfig(),r=c._cache.getEcsConfigByType(t);if(n.configsToFetch.indexOf(t)!==-1&&!c._isFetchingSettings[t])if(r||!c._pendingFetch[t]){var i=r?r.expiration-Date.now():-1;i<=0||r&&t===e.EcsConfigType.User&&c._skypeTokenData.isSkypeTokenValid()&&r.lastFetchTokenHash!==c._skypeTokenData.getSkypeTokenHash(c._skypeTokenData.getSkypeToken())?c._fetchSkypeEcsSettings(t):n.Killswitches?.isSkypeTokenDataLeakFixEnabled?(c._pendingTimers[t]>0&&clearTimeout(c._pendingTimers[t]),c._pendingTimers[t]=window.setTimeout((function(){return c._fetchEcsSettingsIfNeeded(t)}),i)):window.setTimeout((function(){return c._fetchEcsSettingsIfNeeded(t)}),i)}else c._fetchSkypeEcsSettings(t)},this._fetchSkypeEcsSettings=function(t,n){n===void 0&&(n=!1),c._isFetchingSettings[t]||c._paused&&!n?c._pendingFetch[t]=!0:(c._pendingFetch[t]=!1,c._isFetchingSettings[t]=!0,c._config.getConfig().getEcsParameters().catch((function(){return console.warn(`ECS - Failed to fetch ECS fetching parameters`),{}})).then((function(n){return c._ecsClient.getConfig(c._cache.getEcsConfig(),t===e.EcsConfigType.User,n)})).then((function(e){console.log(`ECS - Config fetch complete`),c._isFetchingSettings[t]=!1,c._cache.putConfig(e),c._fetchEcsSettingsIfNeeded(t)})))},this._ecsClient=new t.default(this._config,this._skypeTokenData,a,o,s)}return n.prototype.initialize=function(){var t=this;this.updateConfigsToFetch(),this._subscriptionToken=this._skypeTokenData.skypeTokenChanged.subscribe((function(){return t._fetchEcsSettingsIfNeeded(e.EcsConfigType.User)}))},n.prototype.dispose=function(){var e,t=this._config.getConfig();if(t.Killswitches?.isSkypeTokenDataLeakFixEnabled){for(var n=0,r=t.configsToFetch;n<r.length;n++){var i=r[n];clearTimeout(this._pendingTimers[i]),this._pendingTimers[i]=0}(e=this._subscriptionToken)==null||e.unsubscribe(),this._subscriptionToken=null,this._skypeTokenData.skypeTokenChanged.dispose()}},n.prototype.updateConfigsToFetch=function(){for(var e=this._config.getConfig(),t=0,n=e.configsToFetch;t<n.length;t++)(a=n[t])in this._isFetchingSettings||(this._isFetchingSettings[a]=!1),a in this._isFetchingSettings||(this._pendingFetch[a]=!1);for(var r=0,i=e.configsToFetch;r<i.length;r++){var a=i[r],o=this._cache.getEcsConfigByType(a);!o||o.appVersion&&o.appVersion!==e.clientVersion?this._fetchSkypeEcsSettings(a,!0):this._fetchEcsSettingsIfNeeded(a)}},n.prototype.requestUpdate=function(){for(var e=0,t=this._config.getConfig().configsToFetch;e<t.length;e++){var n=t[e];this._fetchSkypeEcsSettings(n)}},n.prototype.pause=function(){this._paused=!0},n.prototype.resume=function(){this._paused=!1;for(var e=0,t=this._config.getConfig().configsToFetch;e<t.length;e++){var n=t[e];this._fetchEcsSettingsIfNeeded(n)}},n}(),v9}var TRe,E9={};function ERe(){if(TRe)return E9;TRe=1,Object.defineProperty(E9,"__esModule",{value:!0});var e=h9,t=B5();return E9.default=function(){function n(){this.skypeTokenChanged=new e.default}return n.prototype.putSkypeTokenData=function(e){if(this._data=e,this.isSkypeTokenValid()&&this.skypeTokenChanged.fire(),this.isSkypeTokenValid()&&this._validSkypeTokenDeferral){var t=this._validSkypeTokenDeferral;this._validSkypeTokenDeferral=void 0,t.resolve(void 0)}},n.prototype.isSkypeTokenValid=function(){var e=this._data;return!!e&&!!e.skypeToken&&e.skypeTokenExpiration>Date.now()},n.prototype.getSkypeToken=function(){var e=this._data;if(!e||!e.skypeToken)throw Error(`No Skype Token provided`);return e.skypeToken},n.prototype.getSkypeTokenHash=function(e){return e===void 0?0:e.split(``).reduce((function(e,t){return(101*e+t.charCodeAt(0))%999727999}),e.length)},n.prototype.waitForValidSkypeToken=function(){return this.isSkypeTokenValid()?t.Resolved():(this._validSkypeTokenDeferral||=t.Defer(),this._validSkypeTokenDeferral.promise())},n}(),E9}var DRe,ORe,D9={};function kRe(){if(DRe)return D9;DRe=1,Object.defineProperty(D9,"__esModule",{value:!0});var e=h9;return D9.default=function(){function t(t){this._cache=t,this.telemetryEventAdded=new e.default}return t.prototype.sendTelemetryEvent=function(e){var n=e.getEventName(),r=e.getAttributes(),i=!1,a=this._cache.getEcsConfig();if(a){if(t._containsEcsClientTelemetryConfig(a.config)){var o=a.config.ECSCONFIG;o&&o.ecsClientTelemetry&&(i=!!o.ecsClientTelemetry[n])}}else console.warn(`No previously cached ECS telemetry config exists - fallback to sending event`),i=!0;i&&this.telemetryEventAdded.fire(n,r)},t._containsEcsClientTelemetryConfig=function(e){return!!e&&!!e.ECSCONFIG&&!!e.ECSCONFIG.ecsClientTelemetry},t}(),D9}function ARe(){if(ORe)return d9;ORe=1,Object.defineProperty(d9,"__esModule",{value:!0});var e=KLe(),t=JLe(),n=eRe(),r=nRe();d9.Models=g9();var i=wRe(),a=ERe(),o=kRe();return d9.default=function(){function s(){this._allowBackgroundFetchData=new e.default,this._appActiveData=new t.default,this._config=new r.default,this._cache=new n.default(this._config),this._skypeTokenData=new a.default,this._telemetryManager=new o.default(this._cache),this._scheduler=new i.default(this._config,this._skypeTokenData,this._cache,this._appActiveData,this._allowBackgroundFetchData,this._telemetryManager),this.telemetryEventAdded=this._telemetryManager.telemetryEventAdded,this.configUpdated=this._cache.configUpdated}return s.prototype.initialize=function(e){var t=this;return this._config.initialize(e),this._skypeTokenData.putSkypeTokenData(e.initialSkypeTokenData),this._appActiveData.putAppActive(e.initialAppActiveState),this._cache.initialize().then((function(){t._scheduler.initialize()}))},s.prototype.dispose=function(){var e;(e=this._config.getConfig().Killswitches)!=null&&e.isSkypeTokenDataLeakFixEnabled&&this._scheduler.dispose()},s.prototype.getConfig=function(){return this._cache.getEcsConfig()},s.prototype.getConfigType=function(){var e=this._cache.getEcsConfig();if(e)return e.configType},s.prototype.requestUpdate=function(){this._scheduler.requestUpdate()},s.prototype.pause=function(){this._scheduler.pause()},s.prototype.resume=function(){this._scheduler.resume()},s.prototype.setAllowBackgroundFetch=function(e){this._allowBackgroundFetchData.putBackgroundFetchAllowed(e)},s.prototype.useSkypeToken=function(e,t){this._skypeTokenData.putSkypeTokenData({skypeToken:e,skypeTokenExpiration:t})},s.prototype.setAppActive=function(e){this._appActiveData.putAppActive(e)},s.prototype.setConfigsToFetch=function(e){var t=this;return this._config.setConfigsToFetch(e),this._cache.updateConfigsToFetch().then((function(){t._scheduler.updateConfigsToFetch()}))},s.prototype.setFetchTimeout=function(e){this._config.setFetchTimeout(e)},s}(),d9}var O9,k9=ARe(),jRe=NG(k9),MRe=B5();function NRe(e,t){let n={},r=e.OsName??``,i=e.OsVer??``,a=r&&i?`${r}-${i}`:``;return n.CLRelease=`${e.CLRelease??``}`,n.BrowserName=e4.toLower(`${e.BrowserName??``}`),n.BrowserEngine=`${e.BrowserEngine??``}`,n.BrowserVersion=`${e.BrowserVersion??``}`,n.FormFactor=`${e.FormFactor??``}`,n.IdentityType=t2.Consumer,n.Cloud=X0.Public,n.OSVer=e4.toLower(a),n.BrowserName===`edge`&&(n.BrowserName=`edgeanaheim`),t&&(n.Cloud=t.cloudType,n.IdentityType=t.identityType),e4.omitBy(n,(e=>e==null||e===``))}function PRe(e,t){let n={[X0.Public]:$0.Public_EcsServer_Url,[X0.Dod]:$0.Dod_EcsServer_Url,[X0.GccHigh]:$0.GccHigh_EcsServer_Url,[X0.AirGap08]:$0.AirGap08_EcsServer_Url,[X0.AirGap09]:$0.AirGap09_EcsServer_Url},r=$0.Public_EcsServer_Url;return t&&(r=t.identityType===t2.Enterprise?$0.Enterprise_Ecs_ServerUrl:n[t.cloudType]??$0.Public_EcsServer_Url),e?.proxyfyUrl(r)??r}(function(e){e.Default=`Default`,e.User=`User`})(O9||={});var FRe=class{constructor(e,t,n,r){this._isWBMediaClient=e,this._acsProxy=n,this._sourceTag=r,this._throttlingTimeoutHandle=0,this._eventEmitter=new E3.EventEmitter,this._logger=t.createChild(`EcsClient`)}_resetThrottlingTimeout(){this._throttlingTimeoutHandle&&=(window.clearTimeout(this._throttlingTimeoutHandle),0)}_resetEcsClient(){this._ecsClient&&=(this._ecsClient.configUpdated.dispose(),void 0)}async _fetchConfig(e){this._resetEcsClient(),this._resetThrottlingTimeout();let t=new jRe,n=n3();try{await t.initialize(e);let r=[],i=!1,a=0;t.configUpdated.subscribe((()=>{if(n.isPending())n.resolve();else{r.push(Date.now());let e=t.getConfig();if(e?.config){let t=e?.configType===k9.Models.EcsConfigType.User?O9.User:O9.Default;this._cachedConfig=e,this._eventEmitter.emit(`configUpdated`,{config:e?.config,fetchType:t,sourceTag:this._sourceTag})}let n=Z().ecsClient.throttling;r.length>n.triggerCount&&(r=r.slice(r.length-n.triggerCount));let o=r[r.length-1]-r[0];i?(r.length<n.triggerCount||o>=n.coolDownDuration)&&(i=!1,a=0,r=[],this._resetThrottlingTimeout()):r.length===n.triggerCount&&o<n.triggerDuration&&(i=!0),i&&(a=a===0?n.startingDelay:Math.min(Math.ceil(a*n.delayFactor),n.maxDelay),t.pause(),this._throttlingTimeoutHandle=window.setTimeout((()=>{this._throttlingTimeoutHandle=0,t.resume()}),a))}})),this._ecsClient=t,await i3((()=>n.promise),OCe);let o=t.getConfig();if(!o?.config)throw new Y({defaultError:J.INTERNAL.ECS_CONFIG_EMPTY});return this._cachedConfig=o,o.config}catch(e){throw n.reject(e),this._logger.error(`${e}`),e}}async fetchDefaultConfig(e,t){let n=`${this._isWBMediaClient?l2:c2}_${X2()}`,r={hosts:[PRe(this._acsProxy,t)],clientName:bSe,clientVersion:n,configsToFetch:[k9.Models.EcsConfigType.Default],getEcsParameters:()=>MRe.Resolved(e),initialAppActiveState:!0};return this._fetchConfig(r)}async fetchUserConfig(e,t,n){let r=`${this._isWBMediaClient?l2:c2}_${X2()}`,i=await n(),a=1e3*Xwe(i).exp,o={hosts:[PRe(this._acsProxy,t)],clientName:bSe,clientVersion:r,configsToFetch:[k9.Models.EcsConfigType.User],getEcsParameters:()=>MRe.Resolved(e),initialAppActiveState:!0,initialSkypeTokenData:{skypeToken:i,skypeTokenExpiration:a}};return this._fetchConfig(o)}get eTag(){return this._cachedConfig?.eTag??``}get sourceTag(){return this._sourceTag}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._eventEmitter.removeAllListeners(),this._resetThrottlingTimeout(),this._resetEcsClient()}getConfigIds(e){return(this._cachedConfig?.config)?.ConfigIDs?.[e]}},IRe=class{constructor(e){this._telemetryLogManager=e,this._seq=0}sendAttemptEvent(e,t,n){this._seq++,this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_attempt,tenant:p2,properties:{attemptTimestamp:e,ecsFetchType:t,correlationId:n,eventSeq:this._seq}})}sendSuccessEvent(e,t,n,r){let i=Date.now();this._seq++;let a=e===void 0?0:i-e;this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_success,tenant:p2,properties:{...e===void 0?void 0:{attemptTimestamp:e},successTimestamp:i,deltaTimeInMs:a,ecsFetchType:t,correlationId:n,eventSeq:this._seq,ecsConfigIds_AcsCallingSDKWeb:r?.AcsCallingSDKWeb||``,ecsConfigIds_SkypeWebMedia:r?.SkypeWebMedia||``}})}sendFailureEvent(e,t,n,r){let i=Date.now();this._seq++;let a=e===void 0?0:i-e,o=r.message,s=J3(r);this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_failure,tenant:p2,properties:{...e===void 0?void 0:{attemptTimestamp:e},failureTimestamp:i,deltaTimeInMs:a,ecsFetchType:t,correlationId:n,eventSeq:this._seq,failureReason:o,additionalDetails:{...s}}})}};function LRe(e,...t){e4.merge(e,...t)}function RRe(e,t){let n={};try{n.CLRelease=W5.stackFactory.getVersion().build;let e=r8();n.BrowserName=e.name,n.BrowserEngine=e.engine,n.BrowserVersion=e.version,n.FormFactor=e.formFactor,n.IdentityType=t2.Consumer,n.Cloud=X0.Public,n.OSVer=`${i8()}-${lke()}`,t&&(n.Cloud=t.cloudType,n.IdentityType=t.identityType),n.CLRelease===`_TS_BUILD_VERSION_`?n.CLRelease=`9999.99`:n.CLRelease.match(/^\d+\.\d+\.\d+\.\d+$/)||delete n.CLRelease}catch(t){throw e.error(t),new Y({defaultError:J.CALL_STACK.SET_STACK_PARAMS,originalError:t})}return n}var A9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},j9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},M9=class{constructor(e,t,n,r,i,a,o,s,c=!1){if(this._baseStackDisposed=!1,this._userStackDisposed=!1,this._trouterStateChangedListenersRegistered=new Map,this._signalingAgentInitialized=!1,this._hardcodedEcsConfigApplied=!1,this._clientId=t,this.sdkDiagnosticInformation=r,this.logger=e.createChild(`CallStack`),this._telemetryLogManager=n,this._acsProxy=i,this._acsCustomRelayManager=a,this._vdi3Options=s,this._webcvProvider=new ELe,this._wasmvqeProvider=new jLe,this._isWBMediaClient=c,location.protocol!==`https:`&&location.protocol!==`file:`&&location.hostname!==`localhost`)throw new Y({defaultError:J.CALL_STACK.BAD_PROTOCOL});this._telemetryService=new TLe(this._telemetryLogManager),this._ecsTelemetryLogger=new IRe(n),this._ecsProvider=new r9(this.logger,this.sdkDiagnosticInformation,this._acsProxy),this._ecsClient=new FRe(this._isWBMediaClient,this.logger,this._acsProxy,`EcsClient`),this._videoEffectsStatusManager=new kLe,this._audioEffectsStatusManager=new ALe,o!==void 0&&(this._encodedStreamsWorkerProvider=new DLe(o))}getVdi3StateInfo(){return this._vdi3StateInfo}getClientId(){return this._clientId}getCaConfigBag(){return this._caConfigBag}getTrouterState(){let e=this._trouterService?.state()??this._shellTrouter?.state();return this.mapTsTrouterState(e)}getEcsConfigIds(){return this._ecsClientRdc?{AcsCallingSDKWeb:this._ecsClient?.getConfigIds(`AcsCallingSDKWeb`)??``,SkypeWebMedia:this._ecsClientRdc?.getConfigIds(`SkypeWebMedia`)??``}:{AcsCallingSDKWeb:this._ecsClient?.getConfigIds(`AcsCallingSDKWeb`)??``,SkypeWebMedia:this._ecsClient?.getConfigIds(`SkypeWebMedia`)??``}}isRegistered(){return this._trouterService?.isRegistered()??this._shellTrouter?.registeredState()??!1}onRegisteredChanged(e){this._trouterService?.onRegisteredChanged(e),this._shellTrouter?.on(`registeredChanged`,e)}offRegisteredChanged(e){this._trouterService?.offRegisteredChanged(e),this._shellTrouter?.off(`registeredChanged`,e)}onTrouterStateChanged(e){let t=(t,n)=>{e(this.mapTsTrouterState(t))};return this._trouterService?.onStateChanged(t),this._shellTrouter?.on(`stateChanged`,t),this._trouterStateChangedListenersRegistered.set(e,t),{listener:e,tsTrouterStateChangedListener:t}}offTrouterStateChanged(e){let t=this._trouterStateChangedListenersRegistered.get(e);if(t)return this._trouterService?.offStateChanged(t),this._shellTrouter?.off(`stateChanged`,t),this._trouterStateChangedListenersRegistered.delete(e),{listener:e,tsTrouterStateChangedListener:t}}mapTsTrouterState(e){let t=`Uninitialized`;if(e!==void 0)switch(e){case 0:t=`Unknown`;break;case 2:t=`Connected`;break;case 3:t=`Disconnected`;break;case 9:t=`Switching`}return t}get webcvProvider(){return this._webcvProvider}get wasmvqeProvider(){return this._wasmvqeProvider}get videoEffectsStatusManager(){return this._videoEffectsStatusManager}get audioEffectsStatusManager(){return this._audioEffectsStatusManager}async applyHardcodedEcsConfigAndSetStack(e,t){if(this._hardcodedEcsConfigApplied)return void this.logger.info(`Hardcoded ECS config already applied, skipping`);let n=Hwe();await this.updateConfig(n,t);let r=+new Date;await this._setStackConfig();let i=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:e,durationInMs:i,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),this._hardcodedEcsConfigApplied=!0}async createStackBase(e){if(this._createStackBaseWaitPromise)return this._createStackBaseWaitPromise;this._baseStackDisposed=!1;let t=new Promise((async(t,n)=>{try{let n=this._getBaseStackConfig();if(this._vdi3StateInfo={supported:PLe(),requested:!1,enabled:!1},this._vdi3StateInfo.supported&&!0===this._vdi3Options?.enabled){this._vdi3StateInfo.requested=!0,this._shellTrouter&&await this._shellTrouter.dispose(),this._shellTrouter=new WLe;let e=FLe(this.logger,this._vdi3Options);e.vdi3Config&&(e.vdi3Config.shellTrouter=this._shellTrouter.instance);let t=await W5.stackFactory.buildBaseStack({stackType:1,...n,...e});if(this._proxyReferenceManager=u9.create(this.logger),this._tsStack=this._proxyReferenceManager.create(t),this._vdi3StateInfo.enabled=!0,Z().vdi3.fetchEcs)try{let e=await this._tsStack?.getEcsProviderAsync?.();this._ecsQueryParametersRdc=JSON.parse(await e?.getEcsQueryParameters()??`null`)||void 0,this._ecsQueryParametersRdc&&(this._ecsQueryParametersRdc=NRe(this._ecsQueryParametersRdc),this._ecsClientRdc=new FRe(this._isWBMediaClient,this.logger,this._acsProxy,`EcsClientRdc`))}catch(e){this.logger.error(`Failed to get query parameters ${e}`)}}else this._tsStack=await W5.stackFactory.buildBaseStack({stackType:0,...n});let r=async(e,t,n)=>{if(e!==void 0||t!==void 0)try{if(e!==void 0&&e===t){await this.updateConfig(e,this._caConfigBag);let t=Z();qG.updateConfig(t?.errors,this.logger)}else await this.updateConfigForVdi(e,t,this._caConfigBag);t!==void 0&&(await this._setStackConfig(),this._checkEcsConfigValue(t,{attemptTimestamp:void 0,ecsFetchType:n,correlationId:``})),this._ecsTelemetryLogger.sendSuccessEvent(void 0,n,``,this.getEcsConfigIds())}catch(e){let t=new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e});this._ecsTelemetryLogger.sendFailureEvent(void 0,n,``,t)}};this._ecsClientRdc?(this._ecsClient.on(`configUpdated`,(async e=>{await r(e.config,void 0,e.fetchType)})),this._ecsClientRdc.on(`configUpdated`,(async e=>{await r(void 0,e.config,e.fetchType)}))):this._ecsClient.on(`configUpdated`,(async e=>{await r(e.config,e.config,e.fetchType)})),await this.initializeEcsBase(e),await this._setStackConfig(),t(this._tsStack)}catch(e){n(e)}}));try{this._createStackBaseWaitPromise=i3((()=>t),YSe);let e=await this._createStackBaseWaitPromise;return this.logger.log(`Base stack init success`),e}catch(e){throw await this.disposeBaseStack(),e.code===RG?new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_TIMEOUT}):new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_FAILED,originalError:e})}}async createMediaSdkStackBase(e,t,n){if(this._createMediaSdkStackBaseWaitPromise)return this._createMediaSdkStackBaseWaitPromise;this._baseStackDisposed=!1;let r=new Promise((async(r,i)=>{try{let i=this._getMediaStackConfig(e),a=+new Date;this._tsStack=await W5.stackFactory.build(i);let o=+new Date-a;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`BuildMediaStack`,durationInMs:o,operationPayload:{},resultCategories:[`Success`],resultSignature:200});let s=async(e,t,n)=>{if(e!==void 0||t!==void 0)try{e!==void 0&&e===t?await this.updateConfig(e,this._caConfigBag):await this.updateConfigForVdi(e,t,this._caConfigBag),t!==void 0&&(await this._setStackConfig(),this._checkEcsConfigValue(t,{attemptTimestamp:void 0,ecsFetchType:n,correlationId:``})),this._ecsTelemetryLogger.sendSuccessEvent(void 0,n,``,this.getEcsConfigIds())}catch(e){let t=new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e});this._ecsTelemetryLogger.sendFailureEvent(void 0,n,``,t)}};if(this._ecsClient.on(`configUpdated`,(async e=>{await s(e.config,e.config,e.fetchType)})),!n){await this.applyHardcodedEcsConfigAndSetStack(`SetStackConfigBase`,t);let e=+new Date;this.initializeEcsBase(t).then((async()=>{let t=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`InitializeEcsBase`,durationInMs:t,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),Z().waimeabay.backgroundEcsFetchTsStackSet&&await this._setStackConfig()})).catch((t=>{let n=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`InitializeEcsBase`,durationInMs:n,operationPayload:{},resultCategories:[`Failure`],resultSignature:500}),this.logger.warn(`Background ECS fetch failed`,t)}))}r(this._tsStack)}catch(e){i(e)}}));try{this._createMediaSdkStackBaseWaitPromise=i3((()=>r),YSe);let e=await this._createMediaSdkStackBaseWaitPromise;return this.logger.log(`Base stack init success`),e}catch(e){throw await this.disposeBaseStack(),e.code===RG?new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_TIMEOUT}):new Y({defaultError:J.CALL_STACK.BASE_STACK_INIT_FAILED,originalError:e})}}async initializeStackForUser(e,t){if(this._initializeStackForUserWaitPromise)return this._initializeStackForUserWaitPromise;this._caConfigBag=t,this._tsStack=await this.createStackBase(t),this._userStackDisposed=!1;let n=new Promise((async(n,o)=>{try{this._tsStack?(this._ecsProvider=new r9(this.logger,this.sdkDiagnosticInformation,this._acsProxy),await this.initializeEcsForUser(t,e),V6.overrideDefaultLogDump(),G6(this._tsStack)||(Z().calling.doNotWaitForTrouter?this._initTrouter(e).then((()=>{this.logger.log(`Signaling initialized successfully.`)})).catch((()=>{this.logger.warn(J.CALL_STACK.SIGNALING_UNINITIALIZED.message)})):(await this._initTrouter(e),this.logger.log(`Signaling initialized successfully.`))),await r(e,this._tsStack),await i(e,this._tsStack),await a(this._tsStack),n(this._tsStack)):(this.logger.error(`Base stack failed to create`),o(new Y({defaultError:J.CALL_STACK.USER_STACK_NO_BASE_STACK})))}catch(e){o(e)}})),r=async(e,t)=>{try{if(await t.initializeMediaAgent({httpRequestDispatcher:this.getRequestDispatcher(),tokenProvider:e,relayManager:this.getCustomRelayManager(),configProvider:{getSkypeConfig:()=>Promise.resolve({}),getRelayConfig:()=>{let e=this._ecsProvider.getMdnTrapSettings();return Promise.resolve(e)}},appStateProvider:this._getAppStateProvider(),clientInformation:this._ecsProvider.getJsCsaConfig().clientInformation}),Z().calling.platformSupportValidation&&await t.getPlatformSupportLevelAsync()===0){let e=new Y({defaultError:J.CALL_STACK.USER_STACK_MEDIA_INIT_FAILED_PLATFORM_NOT_SUPPORTED});throw this.logger.error(e.message),e}}catch(e){throw this.logger.error(`Failed to initialize media stack`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_MEDIA_INIT_FAILED,originalError:e})}},i=async(e,t)=>{try{let n=G6(t),r={signalingAgentConfig:this._getSignalingConfig(e),...n?{trouterSettings:CLe(this._ecsProvider),trouterService:{}}:{trouterService:this._trouterService}};this._signalingAgentInitialized?(await t.updateSignalingAgentProviderConfig(r),this.logger.log(`Signaling agent updated successfully`)):(await t.initializeSignalingAgentProvider(r),this._signalingAgentInitialized=!0,this.logger.log(`Signaling agent initialized successfully`)),n&&(await this._shellTrouter?.initialize(),this.logger.log(`Signaling initialized successfully for VDI3.`))}catch(e){throw this.logger.error(`Failed to initialize signaling agent`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_SIGNALING_INIT_FAILED,originalError:e})}},a=async e=>{try{await e.init(),await this._setStackConfig()}catch(e){throw this.logger.error(`Failed to initialize calling stack`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INTERNAL_INIT_FAILED,originalError:e})}};try{this._initializeStackForUserWaitPromise=i3((()=>n),XSe);let e=await this._initializeStackForUserWaitPromise;return this.sendStackInitEvent(!0),this.logger.log(`User stack init success`),e}catch(e){throw await this.disposeUserStack(),e.code===RG?(this.sendStackInitEvent(!1,`User stack init timeout`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_TIMEOUT})):!(e instanceof Y)&&this.getTrouterState()===`Uninitialized`?new Y({defaultError:J.CALL_STACK.SIGNALING_UNINITIALIZED,originalError:e}):(this.sendStackInitEvent(!1,`User stack init failed`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_FAILED,originalError:e}))}}async initializeMediaSdkStackForUser(e,t){if(this._caConfigBag=t,this._initializeMediaStackForUserWaitPromise)return this._initializeMediaStackForUserWaitPromise;this._tsStack=await this.createMediaSdkStackBase(e,t,!0);let n=this._getMediaStackConfig(e);this._tsStack.initializeMediaAgent(n.mediaAgentFactoryConfig),this._userStackDisposed=!1;let r=new Promise((async(n,r)=>{try{if(this._tsStack){await this.applyHardcodedEcsConfigAndSetStack(`SetStackConfigUser`,t);let r=+new Date;this.initializeEcsForUser(t,e).then((async()=>{let e=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`InitializeEcsForUser`,durationInMs:e,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),V6.overrideDefaultLogDump(),Z().waimeabay.backgroundEcsFetchTsStackSet&&await this._setStackConfig()})).catch((e=>{let t=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`InitializeEcsForUser`,durationInMs:t,operationPayload:{},resultCategories:[`Failure`],resultSignature:500}),this.logger.warn(`Background user ECS fetch failed`,e)})),this.logger.log(`ECS initialized successfully.`);let a=+new Date;await i(this._tsStack);let o=+new Date-a;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`InitializeTsStack`,durationInMs:o,operationPayload:{},resultCategories:[`Success`],resultSignature:200}),n(this._tsStack)}else this.logger.error(`Media SDK Base stack failed to create`),r(new Y({defaultError:J.CALL_STACK.USER_STACK_NO_BASE_STACK}))}catch(e){r(e)}})),i=async e=>{try{await e.init(),await this._setStackConfig()}catch(e){throw this.logger.error(`Failed to initialize Media SDK stack`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INTERNAL_INIT_FAILED,originalError:e})}};try{this._initializeMediaStackForUserWaitPromise=i3((()=>r),XSe);let e=await this._initializeMediaStackForUserWaitPromise;return this.sendStackInitEvent(!0),this.logger.log(`Media SDK User stack init success`),e}catch(e){throw await this.disposeUserStack(),e.code===RG?(this.sendStackInitEvent(!1,`Media SDK user stack init timeout`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_TIMEOUT})):(this.sendStackInitEvent(!1,`Media SDK user stack init failed`,e),new Y({defaultError:J.CALL_STACK.USER_STACK_INIT_FAILED,originalError:e}))}}getRequestDispatcher(){return this._acsProxy.hasProxyUrl()?(this.logger.info(`Using custom proxy for network requests (non media)`),new OLe(this.logger,this._acsProxy)):Z().telemetry.sendNetworkInfo?new OLe(this.logger):new W5.HttpRequestDispatcherImplementation(this.logger)}async updateConfig(e,t){e?.Headers?.CountryCode&&this.updateEmergencyCallCountry(e?.Headers?.CountryCode);try{Vwe(e),this._ecsProvider.setConfig(t,e),Uwe(this._ecsProvider.getJamaSettings()),this._fetchedEcsConfigValue=e;let n=Z();qG.updateConfig(n?.errors,this.logger)}catch(e){throw this.logger.warn(`Unable to update ECS configuration ${e}`),new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e})}}async updateConfigForVdi(e,t,n){e?.Headers?.CountryCode&&this.updateEmergencyCallCountry(e?.Headers?.CountryCode);let r=t=>{LRe(t,ILe);let n=e?.AcsCallingSDKWeb?.vdi3?.customEcsConfig;if(n)try{LRe(e,JSON.parse(n))}catch(e){this.logger.error(`Failed to parse customEcsConfig: ${e}`)}};try{e&&(r(e),Vwe(e)),t&&(r(t),this._ecsProvider.setConfig(n,t),Uwe(this._ecsProvider.getJamaSettings()),this._fetchedEcsConfigValue=t)}catch(e){throw this.logger.warn(`Unable to update ECS configuration ${e}`),new Y({defaultError:J.CALL_STACK.PARSE_CONFIG,originalError:e})}}async _setStackConfig(){let e=Date.now();try{this._tsStack&&this._fetchedEcsConfigValue&&Object.keys(this._fetchedEcsConfigValue).length>0&&(this.logger.info(`Setting ECS configuration on the calling stack.`),await(await this._tsStack?.getEcsProviderAsync?.())?.setEcsConfig({ecsBlob:JSON.stringify(this._fetchedEcsConfigValue),userIdentity:``,etag:this._ecsClient.eTag}))}catch(t){let n=new Y({defaultError:J.CALL_STACK.SET_STACK_PARAMS,originalError:t}),r=Date.now(),i=e===void 0?0:r-e,a=n.message,o=J3(n);this.logger.warn(`Unable to set ECS configuration on the calling stack`),this._telemetryLogManager.sendEvent({name:Q.acs_calling_config_fetched_failure,tenant:p2,properties:{...e===void 0?void 0:{attemptTimestamp:e},failureTimestamp:r,deltaTimeInMs:i,failureReason:a,additionalDetails:{...o}}})}}_checkEcsConfigValue(e,t){let{attemptTimestamp:n,correlationId:r,ecsFetchType:i}=t;try{r9.assertConfigs(e)}catch(e){this.logger.error(`ECS config assertion failed: ${e?.message??`Unknown error`}`),this._ecsTelemetryLogger.sendFailureEvent(n,i,r,e)}}async initializeEcsBase(e){let t=Date.now(),n=J0();this._ecsTelemetryLogger.sendAttemptEvent(t,O9.Default,n);let r=J.CALL_STACK.FETCH_CONFIG;try{let i=await this._ecsClient.fetchDefaultConfig(RRe(this.logger,e),e);this.logger.info(`Fetched base settings from ECS.`);let a=i;if(G6(this._tsStack)&&this._ecsClientRdc&&this._ecsQueryParametersRdc){let t=await this._ecsClientRdc.fetchDefaultConfig(this._ecsQueryParametersRdc,e);a=t,r=J.CALL_STACK.PARSE_CONFIG,await this.updateConfigForVdi(i,t,e)}else r=J.CALL_STACK.PARSE_CONFIG,await this.updateConfig(i,e);this._ecsTelemetryLogger.sendSuccessEvent(t,O9.Default,n,this.getEcsConfigIds()),this._checkEcsConfigValue(a,{attemptTimestamp:t,correlationId:n,ecsFetchType:O9.Default})}catch(i){this.logger.warn(`Failed to fetch base settings. Stack will initialize with default settings`,i),this._ecsProvider.setConfig(e,void 0);let a=new Y({defaultError:r,originalError:i});this._ecsTelemetryLogger.sendFailureEvent(t,O9.Default,n,a)}}async initializeEcsForUser(e,t){let n=Date.now(),r=J0();this._ecsTelemetryLogger.sendAttemptEvent(n,O9.User,r);let i=J.CALL_STACK.FETCH_CONFIG;try{let a=await this._ecsClient.fetchUserConfig(RRe(this.logger,e),e,t);this.logger.info(`Fetched user settings from ECS.`);let o=a;if(G6(this._tsStack)&&this._ecsClientRdc&&this._ecsQueryParametersRdc){let n=await this._ecsClientRdc.fetchUserConfig(this._ecsQueryParametersRdc,e,t);o=n,i=J.CALL_STACK.PARSE_CONFIG,await this.updateConfigForVdi(a,n,e)}else i=J.CALL_STACK.PARSE_CONFIG,await this.updateConfig(a,e),this._ecsTelemetryLogger.sendSuccessEvent(n,O9.User,r,this.getEcsConfigIds());this._ecsTelemetryLogger.sendSuccessEvent(n,O9.User,r,this.getEcsConfigIds()),this._checkEcsConfigValue(o,{attemptTimestamp:n,correlationId:r,ecsFetchType:O9.User})}catch(e){this.logger.warn(`Failed to fetch user settings.`,e);let t=new Y({defaultError:i,originalError:e});this._ecsTelemetryLogger.sendFailureEvent(n,O9.User,r,t)}}async getDeviceManager(){if(this._createMediaSdkStackBaseWaitPromise){let e=await this._createMediaSdkStackBaseWaitPromise;return this.logger.info(`Getting ts device manager from media sdk stack`),e.getDeviceManagerAsync()}if(this._createStackBaseWaitPromise){let e=await this._createStackBaseWaitPromise;return this.logger.info(`Getting ts device manager from stack`),e.getDeviceManagerAsync()}throw new Y({defaultError:J.CALL_STACK.GET_DM})}async disposeBaseStack(){if(!this._baseStackDisposed){if(this._tsStack)try{await this._tsStack.dispose(),this._tsStack=void 0}catch{this.logger.error(`Failed to dispose calling stack`)}this._proxyReferenceManager?.dispose(),this._ecsClient.dispose(),this._ecsClientRdc?.dispose(),this._createStackBaseWaitPromise=void 0,this._baseStackDisposed=!0,this.logger.info(`Base call stack disposed`)}}async disposeUserStack(e){if(!this._userStackDisposed){if(this._trouterService)try{this._trouterService.clearMessageHandlers(),this._trouterService.stop(e),this._trouterService=void 0}catch{this.logger.error(`Failed to dispose signaling`)}if(this._shellTrouter)try{await this._shellTrouter.dispose(),this._shellTrouter=void 0}catch{this.logger.error(`Failed to dispose shellTrouter`)}try{await this._tsStack?.disposeMediaAgent(J0())}catch{this.logger.error(`Failed to dispose media agent`)}this._initializeStackForUserWaitPromise=void 0,this._userStackDisposed=!0,this.logger.info(`User calling stack disposed`)}}updateEmergencyCallCountry(e){this._caConfigBag&&!this._caConfigBag.emergencyCountryCode&&!this._caConfigBag.IsUserEmergencyCountryCode&&e&&(this._caConfigBag.emergencyCountryCode=e)}async _initTrouter(e){let t=+new Date;try{this._trouterService=new wLe(this.logger,this._ecsProvider,(t=>e(t)),this._telemetryLogManager,this._acsProxy),t=+new Date;let n=await this._trouterService.start(),r=this._trouterService.getTrouterSettings();this.sendSignalingInitEvent(!0,+new Date-t,r.registrationId??``,r.sessionId,n.trouterRequestCompletionTimeDeltaMs,n.registrarRequestCompletionTimeDeltaMs);return}catch(e){throw this.sendSignalingInitEvent(!1,+new Date-t,``,``,void 0,void 0,e),e}}_getBaseStackConfig(){let e=this._getMediaProviderConfig(),t={clientInformation:this._ecsProvider.getClientInformation(),logger:this.logger,mediaSettings:e.mediaSettings,platformType:n8(),callSettings:{useLwjForAllCalls:!1},usePlatformSupportApi:!0,telemetryTenants:{media:`mediaAgent`,signaling:`signalingAgent`,tlePlayer:YCe},telemetryService:this._telemetryService,webcvProvider:this._webcvProvider,wasmVqeProvider:this._wasmvqeProvider};return this._encodedStreamsWorkerProvider!==void 0&&(t.encodedStreamsWorkerProvider=this._encodedStreamsWorkerProvider),t}_getMediaStackConfig(e){return{stackType:2,mediaAgentFactoryConfig:{logger:this.logger,tokenProvider:e,configProvider:{getSkypeConfig:()=>Promise.resolve({}),getRelayConfig:()=>{let e=this._ecsProvider.getMdnTrapSettings();return Promise.resolve(e)}},settings:this._getMediaAgentConfig(),wasmVqeProvider:this._wasmvqeProvider,appStateProvider:this._getAppStateProvider()},signalingAgentConfig:this._getSignalingConfig(e),logger:this.logger,telemetryService:this._telemetryService,platformType:n8()}}_getSignalingConfig(e){let t={...this._ecsProvider.getJsCsaConfig(),httpRequestDispatcher:this.getRequestDispatcher(),telemetryManager:this._telemetryService.getCallingAdapter(),logger:this.logger,skypeToken:e,trouterServiceProvider:this._trouterService,ecsEtag:this._ecsClient.eTag};return this._caConfigBag?.emergencyCountryCode&&(t.emergencyCallCountry=this._caConfigBag?.emergencyCountryCode),t}_getMediaProviderConfig(){return{logger:this.logger,mediaSettings:this._getMediaAgentConfig()}}_getMediaAgentConfig(){return{...this._ecsProvider.getJamaSettings(),useOneDsLogger:!0,collectorUrl:Y0.Public,telemetryTenants:{signaling:m2,gtcAudit:m2,media:h2,realtimeMedia:TCe,tlePlayer:ECe}}}_getAppStateProvider(){return{isOnline:()=>!0}}sendStackInitEvent(e,t,n){try{let r,i;n&&(r=n.message,i=J3(n)),this._telemetryLogManager.sendEvent({name:Q.acs_calling_stack_init,tenant:p2,properties:{success:e,reason:t,failureReason:r||`unknown`,additionalDetails:{...i}}})}catch{}}sendSignalingInitEvent(e,t,n,r,i,a,o){try{let s,c;o&&(s=o.message,c=J3(o)),this._telemetryLogManager.sendEvent({name:Q.acs_calling_signaling_init,tenant:p2,properties:{success:e,failureReason:s||`unknown`,timestampInfo:{deltaTimeInMs:t,deltaTimeInMsTrouterRequest:i,deltaTimeInMsRegistrarRequest:a},additionalDetails:{...c,registrationId:n,sessionId:r}}})}catch{}}getCustomRelayManager(){if(this._tsCustomRelayManager=this._acsCustomRelayManager.getTsRelayManager(),this._tsCustomRelayManager&&Z().calling.enableCustomTurnUsage)return this.logger.info(`Using custom relays for media traffic`),this._acsCustomRelayManager.customRelayManagerInUse=!0,this._tsCustomRelayManager}};A9([UG,j9(`design:type`,Object)],M9.prototype,`logger`,void 0),A9([YG(u4.CreateStackBase),j9(`design:type`,Function),j9(`design:paramtypes`,[Object]),j9(`design:returntype`,Promise)],M9.prototype,`createStackBase`,null),A9([YG(u4.CreateStackBase),j9(`design:type`,Function),j9(`design:paramtypes`,[Function,Object,Boolean]),j9(`design:returntype`,Promise)],M9.prototype,`createMediaSdkStackBase`,null),A9([YG(u4.InitializeStackForUser),j9(`design:type`,Function),j9(`design:paramtypes`,[Function,Object]),j9(`design:returntype`,Promise)],M9.prototype,`initializeStackForUser`,null),A9([YG(u4.InitializeMediaSdkStackForUser),j9(`design:type`,Function),j9(`design:paramtypes`,[Function,Object]),j9(`design:returntype`,Promise)],M9.prototype,`initializeMediaSdkStackForUser`,null),A9([YG(u4.GetDeviceManager),j9(`design:type`,Function),j9(`design:paramtypes`,[]),j9(`design:returntype`,Promise)],M9.prototype,`getDeviceManager`,null);var zRe=class{constructor(){this._eventEmitter=new E3.EventEmitter}notifyAll(e){this._eventEmitter.emit(e)}waitFor(e,t){return new Promise(((n,r)=>{let i=0,a=()=>{n(),clearTimeout(i)};this._eventEmitter.once(e,a),i=window.setTimeout((()=>{this._eventEmitter.off(e,a),r(Error(`timeout`))}),t)}))}},BRe=class{constructor(){this._deviceIdMapping=new Map,this._deviceId=1,this._keywords=Z().telemetry.deviceChangedEvents.piiSafeWords}getDeviceId(e){let t=this._deviceIdMapping.get(e);return t===void 0?(++this._deviceId,t=`${e.split(`:`)[0]??``}:${this._deviceId}`,this._deviceIdMapping.set(e,t),t):t}scrubDeviceLabel(e){return VRe(e,this._keywords)}};function VRe(e,t){if(!e)return``;if(e.length<3)return e;let n=[],r=e.match(/\(([0-9a-zA-Z]+:[0-9a-zA-Z]+)\)/);r&&n.push(r[1]);try{if(!t?.length)return`no_keywords`;{let r=RegExp(`(${t.join(`|`)})`,`gi`),i=r.exec(e);for(;i;)n.push(i[1]),i=r.exec(e)}}catch(e){n.push(`Error: ${(e=>e4.isString(e)?e:e?.message??``)(e)}`)}return n.length===0?`unknown`:n.join(` `)}var N9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},P9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},F9=class{constructor(e,t,n,r=!1,i){this._callStack=t,this._isWBMediaClient=r,this._videoDevices=[],this._audioDevices=[],this._disposed=!1,this._tsDeviceTypeToAudioDeviceType={2:`Microphone`,3:`Speaker`,4:`CompositeAudioDevice`},this.logger=e.createChild(`DeviceManager`),this._telemetryLogManager=n,this._eventEmitter=new w6(this.logger),this._browserInfo=r8(),this._safariVideoPermissionState=`unknown`,this._combinedDevicePermission=new Map,this._deviceInfoMapper=new BRe,this._deviceSelectionNotifications=new zRe,this._permissionChangedTasks=Promise.resolve(),this._shouldEnumerateDevices=i??!0}get telemetryLogManager(){return this._telemetryLogManager}get isWBMediaClient(){return this._isWBMediaClient}get shouldEnumerateDevices(){return this._shouldEnumerateDevices}getRawDeviceMediaStream(e){let t=J0(),n=+new Date;if(this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`attempt`,mediaType:e,timestampInfo:``,additionalDetails:``}),!this._tsDeviceManager?.getRawDeviceMediaStream){let r=new Y({defaultError:J.DEVICE_MANAGER.GET_MEDIA_STREAM_TRACK});this.logger.error(`Failed to get raw device stream track`);let i=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`failure`,mediaType:e,timestampInfo:{deltaTimeInMs:i-n},additionalDetails:{failureReason:r.message||``,code:r.code,subCode:r.subCode,...J3(r)}}),r}let r;try{r=this._tsDeviceManager?.getRawDeviceMediaStream(e);let i=+new Date;return this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`success`,mediaType:e,timestampInfo:{deltaTimeInMs:i-n},additionalDetails:``}),r}catch(r){let i=new Y({defaultError:J.DEVICE_MANAGER.GET_MEDIA_STREAM_DEVICE_UNAVAILABLE,originalError:r}),a=K3(r,this.isWBMediaClient,i);this.logger.error(`Failed to get raw device stream: `,a.message);let o=+new Date;throw this.sendRawMediaEvent({eventName:Q.acs_calling_get_raw_device_media_stream,correlationId:t,kindOfEvent:`failure`,mediaType:e,timestampInfo:{deltaTimeInMs:o-n},additionalDetails:{failureReason:a.message||``,code:a.code,subCode:a.subCode,...J3(a)}}),a}}getClientId(){return this._callStack.getClientId()}async getDeviceManager(){if(this._tsDeviceManager)return this._tsDeviceManager;let e=+new Date,t=J0();try{this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`attempt`,timestampInfo:``,additionalDetails:``});let n=+new Date;if(this.isWBMediaClient){await this._callStack.createMediaSdkStackBase();let e=+new Date-n;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`CreateMediaStackBase`,durationInMs:e,operationPayload:{},resultCategories:[`Success`],resultSignature:200})}else await this._callStack.createStackBase();let r=+new Date;if(this._tsDeviceManager=await this._callStack.getDeviceManager(),this.isWBMediaClient){let e=+new Date-r;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`GetTsDeviceManager`,durationInMs:e,operationPayload:{},resultCategories:[`Success`],resultSignature:200})}if(this._shouldEnumerateDevices){let e=+new Date;try{let t=await this.enumerateDevicesAsync();if(this.isWBMediaClient){let n=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`EnumerateDevices`,durationInMs:n,operationPayload:{deviceCount:t.length},resultCategories:[`Success`],resultSignature:200})}this.logger.info(`tsDevicesList:${JSON.stringify(t)}`),t.forEach((e=>{if(e.kind===1){let t=e;this._videoDevices.push(new z6(t.label,t.id,`UsbCamera`,this))}else if(e.kind===2||e.kind===3){let t=e,n=new Z6(t.label,t.id,t.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[t.kind],this);this._audioDevices.push(n)}}))}catch(t){if(this.isWBMediaClient){let n=+new Date-e,r=new Y({defaultError:J.DEVICE_MANAGER.DEVICE_ENUMERATING_FAIL,originalError:t});this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`EnumerateDevices`,durationInMs:n,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500})}if(!1===Z().calling.ignoreEnumerateDevicesError)throw`Ignore enumerateDevicesError ${t}`}let t=+new Date,n=await this._tsDeviceManager.getSelectedDevicesAsync?.();if(this.isWBMediaClient){let e=+new Date-t;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`GetSelectedDevices`,durationInMs:e,operationPayload:{hasMicrophone:!!n?.microphone,hasSpeaker:!!n?.speaker},resultCategories:[`Success`],resultSignature:200})}n&&(this._selectedMicrophone=this._audioDevices.find((e=>e.id===n.microphone)),this._selectedSpeaker=this._audioDevices.find((e=>e.id===n.speaker)))}else this.logger.info(`Skipping device enumeration (enumerateDevices is disabled)`);if(this._dmDevicesChangedSub=this._tsDeviceManager.on(`devicesChanged`,(async()=>{try{await this.syncDeviceList(await this.enumerateDevicesAsync()),await this.checkForSelectedDevicesChanges()}catch(t){this.logger.warn(`Unable to handle devicesChanged, error=${t?.message}, code=${t?.code}`);let n=+new Date;this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:t?.message,code:t?.code,...J3(t),context:`devicesChanged`}})}})),Z().calling.devicePermissions.getCurrentState){let e=+new Date,t=await this._tsDeviceManager?.getPermissionStateAsync?.(`microphone`,``),n=await this._tsDeviceManager?.getPermissionStateAsync?.(`camera`,``);if(this.isWBMediaClient){let r=+new Date-e;this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:J0(),operationName:`GetPermissionState`,durationInMs:r,operationPayload:{microphoneState:String(t??`undefined`),cameraState:String(n??`undefined`)},resultCategories:[`Success`],resultSignature:200})}this._audioDevicePermission=I4(t,this.logger),this._videoDevicePermission=I4(n,this.logger)}this.logger.info(`Initial permission state audio:`,this._audioDevicePermission,`video:`,this._videoDevicePermission),this._dmDevicesPermissionChangedSub=this._tsDeviceManager.on(`onPermissionStateChanged`,(()=>{this._permissionChangedTasks=this._permissionChangedTasks.then((()=>this.permissionsChanged().catch(M4)))}));let i=+new Date-e;this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:i},additionalDetails:``}),this.isWBMediaClient&&this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`GetDeviceManager`,durationInMs:i,operationPayload:{videoDeviceCount:this._videoDevices.length,audioDeviceCount:this._audioDevices.length},resultCategories:[`Success`],resultSignature:200})}catch(n){let r=new Y({defaultError:J.DEVICE_MANAGER.GET_DM,originalError:n});this.logger.error(r.message);let i=+new Date-e;throw this.sendGetDeviceManagerEvent({eventName:Q.acs_calling_get_device_manager,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:i},additionalDetails:{failureReason:r.message,code:r.code,...J3(r)}}),this.isWBMediaClient&&this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`GetDeviceManager`,durationInMs:i,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500}),r}return this._tsDeviceManager}getTsDeviceManager(){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});return this._tsDeviceManager}getSafariPermissionState(){return this._browserInfo.engine===`Safari`?this._safariVideoPermissionState:`unknown`}getAcsResourceId(){return this._callStack?.getCaConfigBag()?.acsResourceId}getAudioDevicePermission(){return this._audioDevicePermission}getVideoDevicePermission(){return this._videoDevicePermission}get callStackWebCvProvider(){return this._callStack.webcvProvider}get callStackWasmVqeProvider(){return this._callStack.wasmvqeProvider}get callStackVideoEffectsStatusManager(){return this._callStack.videoEffectsStatusManager}get callStackAudioEffectsStatusManager(){return this._callStack.audioEffectsStatusManager}get deviceInfoMapper(){return this._deviceInfoMapper}getEnvironmentInfoInternal(){return this._environmentInfo||=hke(),this._environmentInfo}getOSNameInternal(){return i8()}dispose(){this._disposed=!0,this._dmDevicesChangedSub&&this._dmDevicesChangedSub.dispose(),this._dmDevicesPermissionChangedSub&&this._dmDevicesPermissionChangedSub.dispose(),this._dmDevicesPermissionChangedSub=void 0,this._dmDevicesChangedSub=void 0,this._eventEmitter.removeAllListeners(),this._tsDeviceManager=void 0}on(e,t){if(e!==`videoDevicesUpdated`&&e!==`audioDevicesUpdated`&&e!==`selectedMicrophoneChanged`&&e!==`selectedSpeakerChanged`)throw new Y({defaultError:J.DEVICE_MANAGER.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`videoDevicesUpdated`&&e!==`audioDevicesUpdated`&&e!==`selectedMicrophoneChanged`&&e!==`selectedSpeakerChanged`)throw new Y({defaultError:J.DEVICE_MANAGER.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}sendRawMediaEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send raw media telemetry`)}}sendGetDeviceManagerEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send get_device_manager telemetry`)}}async permissionsChanged(e,t){let n=this._audioDevicePermission,r=this._videoDevicePermission,i,a;if(Z().calling.devicePermissions.getCurrentState){let e=await this._tsDeviceManager?.getPermissionStateAsync?.(`microphone`,``),t=await this._tsDeviceManager?.getPermissionStateAsync?.(`camera`,``);i=I4(e,this.logger),a=I4(t,this.logger)}else i=n,a=r;this._audioDevicePermission=i||!!e?.audio,this._videoDevicePermission=a||!!e?.video,t&&(t.audio&&(this._audioDevicePermission=e?.audio??!1),t.video&&(this._videoDevicePermission=e?.video??!1)),n===this._audioDevicePermission&&r===this._videoDevicePermission||(this.logger.info(`permission state changed from audio: ${n}, video: ${r}\n to audio: ${this._audioDevicePermission}, video: ${this._videoDevicePermission}`),this._telemetryLogManager.sendEvent({name:Q.acs_calling_device_permission_changed,tenant:p2,properties:{previousAudioDevicePermission:this.nullHandler(n),previousVideoDevicePermission:this.nullHandler(r),newAudioDevicePermission:this.nullHandler(this._audioDevicePermission),newVideoDevicePermission:this.nullHandler(this._videoDevicePermission)}}))}async checkForSelectedDevicesChanges(){if(this.logger.info(`checkForSelectedDevicesChanges`),this._tsDeviceManager){let e=await this._tsDeviceManager.getSelectedDevicesAsync?.();e&&(e.microphone!==this._selectedMicrophone?.id&&(this._selectedMicrophone=this._audioDevices.find((t=>t.id===e.microphone)),this._eventEmitter.emit(`selectedMicrophoneChanged`),e.microphone!==void 0&&this._deviceSelectionNotifications.notifyAll(e.microphone)),e.speaker!==this._selectedSpeaker?.id&&(this._selectedSpeaker=this._audioDevices.find((t=>t.id===e.speaker)),this._eventEmitter.emit(`selectedSpeakerChanged`),e.speaker!==void 0&&this._deviceSelectionNotifications.notifyAll(e.speaker)))}else this.logger.warn(`DeviceManager is undefined, Unable to check selected devices`)}isACSDeviceEqualToTSDevice(e,t){return e.id===t.id}async syncDeviceList(e){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});if(this.logger.info(`syncDeviceList`),!this._shouldEnumerateDevices)return void this.logger.info(`Device enumeration disabled, skipping syncDeviceList`);e===void 0&&(e=await this.enumerateDevicesAsync());let t=[],n=[],r=[],i=[];e.map((e=>{if(e.kind===1){let n=this._videoDevices.find((t=>this.isACSDeviceEqualToTSDevice(t,e)));if(n)n.setName(e.label),n.setId(e.id),n.setDeviceType(`UsbCamera`);else{let n=new z6(e.label,e.id,`UsbCamera`,this);t.push(n),this._videoDevices.push(n)}}else if(e.kind===2||e.kind===3){let t=this._audioDevices.find((t=>this.isACSDeviceEqualToTSDevice(t,e)));if(t){let n=e;t.setName(n.label),t.setId(n.id),t.setIsSystemDefault(n.isSystemDefault),t.setDeviceType(this._tsDeviceTypeToAudioDeviceType[n.kind])}else{let t=new Z6(e.label,e.id,e.isSystemDefault,this._tsDeviceTypeToAudioDeviceType[e.kind],this);r.push(t),this._audioDevices.push(t)}}}));let a=t=>{let n=t.filter((t=>!e.find((e=>this.isACSDeviceEqualToTSDevice(t,e)))));return n.map((e=>{t.splice(t.indexOf(e),1)})),n};n=a(this._videoDevices),i=a(this._audioDevices),(t.length>0||n.length>0)&&this._eventEmitter.emit(`videoDevicesUpdated`,{added:t,removed:n}),(r.length>0||i.length>0)&&this._eventEmitter.emit(`audioDevicesUpdated`,{added:r,removed:i})}async enumerateDevicesAsync(){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});try{return await this._tsDeviceManager.enumerateDevicesAsync()}catch{throw new Y({defaultError:J.DEVICE_MANAGER.DEVICE_ENUMERATING_FAIL})}}get isSpeakerSelectionAvailable(){if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});return this._tsDeviceManager.isAudioOutputSelectionSupported}get selectedMicrophone(){return this._selectedMicrophone}get selectedSpeaker(){return this._selectedSpeaker}async getCameras(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});return await this.syncDeviceList(),this._videoDevices}async getMicrophones(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});return await this.syncDeviceList(),this._audioDevices.filter((e=>e.deviceType===`Microphone`))}async getSpeakers(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});if(this.isSpeakerSelectionAvailable)return await this.syncDeviceList(),this._audioDevices.filter((e=>e.deviceType===`Speaker`));throw new Y({defaultError:J.DEVICE_MANAGER.SPEAKER_ENUMERATION_UNSUPPORTED})}async selectMicrophone(e){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});if(!e||!e.id)throw new Y({defaultError:J.DEVICE_MANAGER.INVALID_DEVICE});if(e.id===`microphone:`)throw new Y({defaultError:J.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(this.logger.info(`selectMicrophone called`),this._selectedMicrophone?.id!==e.id){let t=Z().calling.deviceSelectionTimeoutInMs,n=this._deviceSelectionNotifications.waitFor(e.id,t),r=this._deviceInfoMapper.getDeviceId(e.id),i=this._deviceInfoMapper.scrubDeviceLabel(e.name),a=J0(),o=(e,t,n)=>{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.deviceSelection,kindOfEvent:e,correlationId:a,timestampInfo:t===void 0?{}:{deltaTimeInMs:t},additionalDetails:n===void 0?``:{failureReason:n.message,code:n.code,...J3(n)},deviceSelection:{deviceId:r,deviceName:i,deviceType:`Microphone`}})};o(`attempt`);let s=Date.now();try{await this._tsDeviceManager.selectDevicesAsync?.({microphone:e.id}),await n.catch((t=>{if(this._selectedMicrophone?.id!==e.id)throw t})),o(`success`,Date.now()-s)}catch(e){let t;throw t=new Y(e?.message===`timeout`?{defaultError:J.DEVICE_MANAGER.SELECT_MICROPHONE_TIMEOUT}:{defaultError:J.DEVICE_MANAGER.SELECT_MICROPHONE_FAIL,originalError:e}),o(`failure`,Date.now()-s,t),t}}else this.logger.warn(`microphoneDevice is already active`)}async selectSpeaker(e){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let t=this.logger.createFnLogger(d4.SelectSpeaker);if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});if(!this.isSpeakerSelectionAvailable)throw new Y({defaultError:J.DEVICE_MANAGER.SPEAKER_SELECTION_UNSUPPORTED});if(!e||!e.id)throw new Y({defaultError:J.DEVICE_MANAGER.INVALID_DEVICE});if(e.id===`speaker:`)throw new Y({defaultError:J.DEVICE_MANAGER.DEVICE_NOT_SELECTABLE});if(t.info(`selectSpeaker called`),this._selectedSpeaker?.id!==e.id){let t=Z().calling.deviceSelectionTimeoutInMs,n=this._deviceSelectionNotifications.waitFor(e.id,t),r=this._deviceInfoMapper.getDeviceId(e.id),i=this._deviceInfoMapper.scrubDeviceLabel(e.name),a=J0(),o=(e,t,n)=>{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.deviceSelection,kindOfEvent:e,correlationId:a,timestampInfo:t===void 0?{}:{deltaTimeInMs:t},additionalDetails:n===void 0?``:{failureReason:n.message,code:n.code,...J3(n)},deviceSelection:{deviceId:r,deviceName:i,deviceType:`Speaker`}})};o(`attempt`);let s=Date.now();try{await this._tsDeviceManager.selectDevicesAsync?.({speaker:e.id}),await n.catch((t=>{if(this._selectedSpeaker?.id!==e.id)throw t})),o(`success`,Date.now()-s)}catch(e){let t;throw t=new Y(e?.message===`timeout`?{defaultError:J.DEVICE_MANAGER.SELECT_SPEAKER_TIMEOUT}:{defaultError:J.DEVICE_MANAGER.SELECT_SPEAKER_FAIL,originalError:e}),o(`failure`,Date.now()-s,t),t}}else t.warn(`device is already selected`)}async askDevicePermission(e){return this.getAskDevicePermissionPromise(e,C3.Public_App)}async startPreheatDevices(e){let{audio:t,video:n}=e,r=Date.now(),i=J0(),a=(e,a)=>{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.startPreheatDevices,kindOfEvent:`failure`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{failureReason:e.message,code:e.code,subCode:e.subCode,...J3(e),context:a},correlationId:i})};try{if(this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.startPreheatDevices,kindOfEvent:`attempt`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{},additionalDetails:{},correlationId:i}),this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});if(!Z().calling.devicePermissions.isPreheatEnabled)throw new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_DISABLED});if(!t?.preheat&&!n?.preheat||t?.preheat&&typeof t?.preheat!=`boolean`||n?.preheat&&typeof n?.preheat!=`boolean`||t?.timeoutInSec&&!t.preheat||n?.timeoutInSec&&!n?.preheat||t?.timeoutInSec&&isNaN(t?.timeoutInSec)||t?.timeoutInSec&&t?.timeoutInSec<=0||n?.timeoutInSec&&isNaN(n?.timeoutInSec)||n?.timeoutInSec&&n?.timeoutInSec<=0)throw new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_INVALID_CONFIG});if(t?.preheat&&this._tsRawAudioStream)throw new Y({defaultError:J.DEVICE_MANAGER.AUDIO_ALREADY_PREHEATED});if(n?.preheat&&this._tsRawVideoStream)throw new Y({defaultError:J.DEVICE_MANAGER.VIDEO_ALREADY_PREHEATED})}catch(e){let a=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_FAIL,originalError:e});throw this.logger.error(a.message),this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.startPreheatDevices,kindOfEvent:`failure`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{failureReason:a.message,code:a.code,subCode:a.subCode,...J3(a)},correlationId:i}),a}try{if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});let e=[];try{e=await this._tsDeviceManager.enumerateDevicesAsync()}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREAHEAT_ENUMERATE_DEVICES_FAIL,originalError:e});throw this.logger.error(t.message),t}let o=!1,s=!1;if(t?.preheat){let t=e.filter((e=>e.kind===2)),n=e.filter((e=>e.kind===3));t[0]?.id!==`microphone:`&&n[0]?.id!==`speaker:`||(o=!0)}if(n?.preheat&&e.filter((e=>e.kind===1))[0]?.id===`camera:`&&(s=!0),o||s){let e=await this.getAskDevicePermissionPromise({audio:o,video:s},C3.StartPreheatDevices);if(o&&!e.audio)throw new Y({defaultError:J.DEVICE_MANAGER.AUDIO_PREHEAT_NO_PERMISSION});if(s&&!e.video)throw new Y({defaultError:J.DEVICE_MANAGER.VIDEO_PREHEAT_NO_PERMISSION})}if(t?.preheat){try{this._tsRawAudioStream=this.getRawDeviceMediaStream(0)}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_DM_AUDIO_STREAM_FAIL,originalError:e});throw this.logger.error(t.message),t}this._tsRawAudioStream?.changed((()=>{this._tsRawAudioStream?.getMediaStream().catch((e=>{let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_AUDIO_STREAM_FAIL,originalError:e}),n=K3(e,this.isWBMediaClient,t);this.logger.error(n.message),a(n,`changed event`)}))}));try{await this._tsRawAudioStream?.getMediaStream()}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_AUDIO_STREAM_FAIL,originalError:e}),n=K3(e,this.isWBMediaClient,t);throw this.logger.error(n.message),n}t?.timeoutInSec&&t.timeoutInSec>0&&(this._preheatedAudioStreamTimeout=setTimeout((()=>{this._tsRawAudioStream?.dispose(),this._tsRawAudioStream=void 0}),1e3*t?.timeoutInSec))}if(n?.preheat){try{this._tsRawVideoStream=this.getRawDeviceMediaStream(1)}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_DM_VIDEO_STREAM_FAIL,originalError:e});throw this.logger.error(t.message),t}this._tsRawVideoStream?.changed((()=>{this._tsRawVideoStream?.getMediaStream().catch((e=>{let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_VIDEO_STREAM_FAIL,originalError:e});this.logger.error(t.message),a(t,`changed event`)}))}));try{await this._tsRawVideoStream?.getMediaStream()}catch(e){let t=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_GET_VIDEO_STREAM_FAIL,originalError:e});throw this.logger.error(t.message),t}n?.timeoutInSec&&n?.timeoutInSec>0&&(this._preheatedVideoStreamTimeout=setTimeout((()=>{this._tsRawVideoStream?.dispose(),this._tsRawVideoStream=void 0}),1e3*n?.timeoutInSec))}this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.startPreheatDevices,kindOfEvent:`success`,audio:{preheat:t?.preheat||!1,timeoutInSec:t?.timeoutInSec||-1},video:{preheat:n?.preheat||!1,timeoutInSec:n?.timeoutInSec||-1},timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{},correlationId:i})}catch(e){if(t?.preheat)try{this._tsRawAudioStream?.dispose()}catch{}finally{this._tsRawAudioStream=void 0,this._preheatedAudioStreamTimeout&&=(clearTimeout(this._preheatedAudioStreamTimeout),void 0)}if(n?.preheat)try{this._tsRawVideoStream?.dispose()}catch{}finally{this._tsRawVideoStream=void 0,this._preheatedVideoStreamTimeout&&=(clearTimeout(this._preheatedVideoStreamTimeout),void 0)}let r=new Y({defaultError:J.DEVICE_MANAGER.PREHEAT_FAIL,originalError:e});throw this.logger.error(r.message),a(r,`api call`),r}}stopPreheatDevices(e){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let{audio:t,video:n}=e,r=Date.now(),i=J0();try{this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.stopPreheatDevices,kindOfEvent:`attempt`,audio:t||!1,video:n||!1,timestampInfo:{},additionalDetails:{},correlationId:i}),t&&(this._tsRawAudioStream?.dispose(),this._tsRawAudioStream=void 0,this._preheatedAudioStreamTimeout&&=(clearTimeout(this._preheatedAudioStreamTimeout),void 0)),n&&(this._tsRawVideoStream?.dispose(),this._tsRawVideoStream=void 0,this._preheatedVideoStreamTimeout&&=(clearTimeout(this._preheatedVideoStreamTimeout),void 0)),this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.stopPreheatDevices,kindOfEvent:`success`,audio:t||!1,video:n||!1,timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{},correlationId:i})}catch(e){let a=new Y({defaultError:J.DEVICE_MANAGER.STOP_PREHEAT_FAIL,originalError:e});throw this.sendDeviceManagerEvent({eventName:Q.acs_calling_client_operations,operation:J7.stopPreheatDevices,kindOfEvent:`failure`,audio:t||!1,video:n||!1,timestampInfo:{deltaTimeInMs:Date.now()-r},additionalDetails:{failureReason:a.message,code:a.code,subCode:a.subCode,...J3(a)},correlationId:i}),a}}getAskDevicePermissionPromise(e,t){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let n={audio:!!e.audio,video:!!e.video};if(!e.audio&&!e.video)throw new Y({defaultError:J.DEVICE_MANAGER.ONE_PERMISSION_ATLEAST});let r=this.getKeyForConstrains(n),i=this._combinedDevicePermission.get(r);return i?this.logger.info(`askDevicePermission attempt: audio:${n.audio}, video:${n.video} on pending existing request ${F4(i)}`):(i=this.askDevicePermissionInternal(n,t),this._combinedDevicePermission.set(r,i),i.finally((()=>{this._combinedDevicePermission.delete(r)}))),i}getKeyForConstrains(e){return Object.keys(e).filter((t=>e[t])).toString()}async askDevicePermissionInternal(e,t){this.logger.info(`askDevicePermission attempt: audio:${e.audio}, video:${e.video}`);let n=J0(),r=+new Date;this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_attempt,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,cause:t});try{if(!this._tsDeviceManager)throw new Y({defaultError:J.DEVICE_MANAGER.ACCESS_DM});let i=[];if(Z().calling.devicePermissions.splitAskAudioVideo){this.logger.info(`askDevicePermission, split permission check`);let t=[];e.audio&&(this.logger.info(`askDevicePermission, split permission audio`),t.push(this._tsDeviceManager.askDevicePermission({audio:e.audio,video:!1}))),e.video&&t.push((async t=>new Promise(((n,r)=>{let i=async()=>{if(this.logger.info(`askDevicePermission, split permission video`),!this._tsDeviceManager){let e=`askDevicePermission, split permission video failed device manager not found`;this.logger.error(e),r(e);return}try{n(await this._tsDeviceManager.askDevicePermission({audio:!1,video:e.video}))}catch(e){r(e)}};t?window.setTimeout(i,t):i()})))(Z().calling.devicePermissions.timeoutInBetween));let n=await Promise.allSettled(t),r={audio:!1,video:!1};n.forEach((e=>{e.status===`fulfilled`&&e?.value&&(r={audio:r.audio||!!e?.value?.audio,video:r.video||!!e?.value?.video}),e.status===`rejected`&&e?.reason&&i.push(e.reason)}));let a=this._permissionChangedTasks.then((()=>this.permissionsChanged(r,e)));this._permissionChangedTasks=a,this._permissionChangedTasks.catch(M4),await a,this._safariVideoPermissionState=this._videoDevicePermission?`granted`:`denied`}else{let t=await this._tsDeviceManager.askDevicePermission({audio:e.audio,video:e.video}),n=this._permissionChangedTasks.then((()=>this.permissionsChanged(t,e)));this._permissionChangedTasks=n,this._permissionChangedTasks.catch(M4),await n}if(e?.audio&&!this._audioDevicePermission||e?.video&&!this._videoDevicePermission)this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_failure,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,cause:t},new Y({defaultError:J.DEVICE_MANAGER.PERMISSION_NOT_GRANTED_OR_FAILED,defaultErrorMessageArgs:[F4(i)]}));else{let i=+new Date;this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_success,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:i-r,cause:t})}}catch(i){let a=new Y({defaultError:J.DEVICE_MANAGER.ADP_FAIL,originalError:i}),o=+new Date;this.sendAskDevicePermissionEvent({eventName:Q.acs_calling_adp_failure,correlationId:n,audioPermissionRequested:e.audio,videoPermissionRequested:e.video,audioPermissionGranted:this._audioDevicePermission,videoPermissionGranted:this._videoDevicePermission,deltaTimeInMs:o-r,cause:t},a)}return{audio:!!this._audioDevicePermission,video:!!this._videoDevicePermission}}sendAskDevicePermissionEvent(e,t){try{let n,r,i;t&&(n=typeof t?.message==`string`?t?.message:void 0,r=J3(t)),e.deltaTimeInMs&&(i=e.deltaTimeInMs>25e3),this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:{audioPermissionGranted:this.nullHandler(e.audioPermissionGranted),videoPermissionGranted:this.nullHandler(e.videoPermissionGranted),audioPermissionRequested:e.audioPermissionRequested,videoPermissionRequested:e.videoPermissionRequested,correlationId:e.correlationId||``,failureReason:n||``,deltaTimeInMs:e.deltaTimeInMs||``,deltaTimeGreaterThanJAMATimeout:this.nullHandler(i),cause:e.cause||``,additionalDetails:{...r}}})}catch{this.logger.debug(`Unable to send audio video permission failure success telemtery`)}}sendDeviceManagerEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send device selection telemetry`)}}nullHandler(e){return e===void 0?``:e}};N9([UG,P9(`design:type`,Object)],F9.prototype,`logger`,void 0),N9([YG(d4.GetCameras),P9(`design:type`,Function),P9(`design:paramtypes`,[]),P9(`design:returntype`,Promise)],F9.prototype,`getCameras`,null),N9([YG(d4.GetMicrophones),P9(`design:type`,Function),P9(`design:paramtypes`,[]),P9(`design:returntype`,Promise)],F9.prototype,`getMicrophones`,null),N9([JG(d4.GetSpeakers),P9(`design:type`,Function),P9(`design:paramtypes`,[]),P9(`design:returntype`,Promise)],F9.prototype,`getSpeakers`,null),N9([YG(d4.SelectMicrophone),P9(`design:type`,Function),P9(`design:paramtypes`,[Object]),P9(`design:returntype`,Promise)],F9.prototype,`selectMicrophone`,null),N9([YG(d4.SelectSpeaker),P9(`design:type`,Function),P9(`design:paramtypes`,[Object]),P9(`design:returntype`,Promise)],F9.prototype,`selectSpeaker`,null),N9([YG(d4.AskDevicePermission),P9(`design:type`,Function),P9(`design:paramtypes`,[Object]),P9(`design:returntype`,Promise)],F9.prototype,`askDevicePermission`,null),N9([YG(d4.StartPreheatDevices),P9(`design:type`,Function),P9(`design:paramtypes`,[Object]),P9(`design:returntype`,Promise)],F9.prototype,`startPreheatDevices`,null),N9([JG(d4.StopPreheatDevices),P9(`design:type`,Function),P9(`design:paramtypes`,[Object]),P9(`design:returntype`,void 0)],F9.prototype,`stopPreheatDevices`,null);var HRe=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},I9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},URe=class extends W7{get info(){return this._teamsCall.info}constructor(e){super(e,KG.TeamsIncomingCall),this._teamsCall=e}async accept(e){if(!B4(this._teamsCall.acsProxy,this._teamsCall.acsCustomRelayManager,!0))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});return await this._teamsCall.accept(e),this._teamsCall}};HRe([YG(c4.Accept),I9(`design:type`,Function),I9(`design:paramtypes`,[Object]),I9(`design:returntype`,Promise)],URe.prototype,`accept`,null);var L9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},R9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},z9=class extends B7{get info(){return this._info}constructor(e,t,n,r){super(e,t,n,r,GG.TeamsCall),this._musicOnHoldEnabled=!1,this._hasFetchedPolicies=!1,this._info=this.callInfo,this._isEmergencyCall=e.isEmergencyNumber,this._mtPolicyService=t.mtPolicyService}async startCallInternal(e,t,n,r,i,a,o){if(this.logger.info(`==> Emergency startCallInternal:TeamsCall.ts`),this._mtPolicyService&&this._mtPolicyService.isFetchUserPoliciesAndSettingsApplicable(!0,o)){this._mtPolicyService.userDialedNumber(Array.isArray(o)?o[0].phoneNumber:o.phoneNumber);let e=``,t=!0;try{this.logger.info(`Fetching Teams User policy from MiddleTier Service`);let e={policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`EmergencyPolicies`],userProperties:[`evEnabled`,`PoliciesMetadata`]};await this._mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(this.tsCall.callId,this._callAgent.getUserMri(),e)}catch(e){t=!1,this.logger.warn(`Fetching Teams user policy from ACS MiddleTier Service failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.\n Proceeding as normal pstn call`)}if(t){try{this.enforcePolicyAndLicenseRestrictions()}catch(e){this.handlePolicyAndLicenseRestrictionsFailure(e);return}try{this.logger.info(`Deriving emergency content from fetched policies and settings`),e=this._mtPolicyService.getEmergencyContent()}catch(e){this.logger.warn(`Error deriving emergency content from fetched policies and settings. \n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}. Proceeding as normal pstn call`)}r&&(r.emergencyContent=e||``,r.isEmergency=e?.trim().length>0||!1,this._isEmergencyCall=r.isEmergency)}}if(o){let t=[];Array.isArray(o)?t=o:t.push(o),this._isEmergencyCall&&t.length==1&&(this.logger.info(`user dialed number (${t[0].phoneNumber}) resolved to actual emergency number (${this._mtPolicyService.getEmergencyNumber()} during startCall`),t[0]={phoneNumber:this._mtPolicyService.getEmergencyNumber()}),t.length>1&&await this.setupThreadIdWhenStartingGroupCall(t,e,r),t.forEach((e=>{this.tsCall.addParticipant(K2(e)).catch((()=>{this.logger.error(`Failed to add participant during call start`)}))})),this.logger.info(`Paticipant added during startCall`)}return this._allowBreakoutRoomJoin=Z().calling.breakoutRooms.enabled&&this._mtPolicyService.isBreakoutRoomsAllowed()&&!!n,this._allowIPAudio=this._mtPolicyService.isIPAudioAllowed(),this._allowIPVideo=this._mtPolicyService.isIPVideoAllowed(),super.startCallInternal(e,t,n,r,i,a)}dispose(){super.dispose(),this._extensibleApi.dispose()}get isEmergencyCall(){return this._isEmergencyCall}addParticipant(e,t){let n=+new Date,r=J0();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{attemptTimestamp:n},additionalDetails:{customContext:{userToUserPresent:!!t?.customContext?.userToUser,xHeadersPresent:!!t?.customContext?.xHeaders&&t?.customContext.xHeaders.length>0}}});try{t7(c4.AddParticipant,this.state),Y2(e)}catch(e){let t=new Y({defaultError:J.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...J3(t)}}),t}if(!B4(this.acsProxy,this.acsCustomRelayManager,!0)){let e=new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...J3(e)}}),e}if(this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)))){let t=new Y({defaultError:J.CALL.PARTICIPANT_ALREADY_IN_CALL,defaultErrorMessageArgs:[OG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:t.code,failureReason:t.message,...J3(t)}}),t}if(this.tsCall.threadId&&cTe(this.tsCall.threadId))try{if(this.IsTargetUserAllowed(e))throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TARGET_TYPE})}catch(e){throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...J3(e)}}),this.logger.error(e),e}let i=this.getOrCreateRemoteParticipant(q2(K2(e))),a=``;return this.GetOrCreateGroupChatThread(!!t?.threadId,e,t).then((o=>{o&&((t??={}).threadId=o,a=o,this._info.setThreadId(o)),this.addParticipantToTsCall(e,a,t,i,r,n)})).catch((e=>{throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:r,timestampInfo:{deltaTimeInMs:+new Date-n},additionalDetails:{code:e.code,failureReason:e.message,...J3(e)}}),e})),i}async removeParticipant(e){let t=+new Date,n=J0();this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.attempt,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{attemptTimestamp:t}});try{t7(c4.RemoveParticipant,this.state),Y2(e)}catch(e){let r=new Y({defaultError:J.IDENTIFIER.PARSE_INVALID_IDENTIFIER,originalError:e});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:e.code,failureReason:e.message,...J3(r)}}),r}let r=this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)));if(!r){let r=new Y({defaultError:J.CALL.PARTICIPANT_NOT_IN_CALL,originalError:[OG(e).kind]});throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:r.code,subCode:r.subCode,failureReason:r.message,...J3(r)}}),r}try{await this.tsCall.removeParticipant(K2(e)),this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t}})}catch(e){let{callEndReason:i}=W3(this,r.tsRemoteParticipant,e);r.callEndReason||r.setCallEndReason(i);let a=Y3(i);throw this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`remove`,correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{code:a?.callEndReason.code,subCode:a?.callEndReason.subCode,failureReason:a?.callEndReason.message,...a}}),new Y({defaultError:{message:i.message,code:i.code,subCode:i.subCode||0,resultCategories:i.resultCategories},originalError:e})}}async mute(){super.mute()}async unmute(){super.unmute()}async hold(){if(this.tsCall.state===4)return void this.logger.info(`Call already on hold`);if(!Z().calling.musicOnHoldEnabled)return this.logger.warn(`Music on Hold is not enabled`),super.hold();let e=+new Date,t=J0();if(this._causeId=PG(),this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Hold,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:S4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),!this._hasFetchedPolicies)try{this.logger.info(`Fetching Teams Calling Policy from Azure Communication Services`),await this._mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(this.tsCall.callId,this._callAgent.getUserMri(),{policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`TeamsCallingPolicy`]}),this._hasFetchedPolicies=!0,this._isTeamsExtensionUser&&!Z().calling.teamsExtensionSettings.enableMoh?(this._musicOnHoldEnabled=!1,this.logger.info(`Music on Hold is disabled for Teams Extension User`)):this._musicOnHoldEnabled=this._mtPolicyService.isMoHEnabled(),this.logger.info(`Music on Hold is `+(this._musicOnHoldEnabled?`enabled`:`disabled`))}catch(e){this.logger.warn(`Fetching Teams Calling Policy from Azure Communication Services failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.`)}return this._musicOnHoldEnabled?(Z().calling.turnOffScreenShareBeforeHold&&this.tsCall.isScreenSharingOn&&await this.tsCall.stopScreenSharing().then((()=>{this.logger.log(`Successfully turned off screen sharing before hold`)})).catch((()=>{this.logger.error(`Failed to turn off screensharing before hold`)})),await this.tsCall.hold(void 0,this._causeId,{isLocal:!0},1).then((async()=>{this.logger.info(`Successfully detached devices as part of Hold`),await this.tsCall.park(3,this._causeId).then((()=>{let n=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Hold,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{holdType:S4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),this.logger.info(`Successful park() as part of hold, Music on Hold completed successfully`)}))})).catch((()=>{let n=+new Date,r=new Y({defaultError:J.CALL.HOLD_CALL});throw this.logger.warn(`Attempting to perform Music on Hold failed.\n Error message = ${r.message}, code = ${r.code}, subcode = ${r.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Hold,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,holdType:S4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...J3(r)}}),r}))):(this.logger.info(`Fetching of Teams Calling Policy failed or Music on Hold Disabled, proceeding with standard hold`),super.hold())}async resume(){if(this._musicOnHoldEnabled){let e=+new Date,t=J0();return this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Resume,kindOfEvent:$.attempt,timestampInfo:{deltaTimeInMs:e},additionalDetails:{holdType:S4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),await this.tsCall.unpark(3,this._causeId).then((async()=>{this.logger.info(`Successful unpark() as part of resume`),await this.tsCall.unhold(void 0,this._causeId).then((()=>{let n=+new Date;this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Resume,kindOfEvent:$.success,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{holdType:S4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn}}),this.logger.info(`Successful unhold() as part of resume, resume completed successfully`)}))})).catch((()=>{let n=+new Date,r=new Y({defaultError:J.CALL.RESUME_CALL});throw this.logger.warn(`Attempting to perform resume from Music on Hold failed.\n Error message = ${r.message}, code = ${r.code}, subcode = ${r.subCode}`),this.sendCallOnHoldAndResumedEvent({eventName:Q.acs_calling_call_hold_and_resume,callId:this.id,localParticipantId:this.tsCall.participantId,correlationId:t,operation:c4.Resume,kindOfEvent:$.failure,timestampInfo:{deltaTimeInMs:n-e},additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,holdType:S4.MusicOnHold,isScreenSharingOnFlag:this.tsCall.isScreenSharingOn,...J3(r)}}),r}))}return this.logger.info(`Music on Hold Disabled, proceeding with standard resume`),super.resume()}validateAndSetThreadId(e,t){if(!t?.threadId){let e=new Y({defaultError:J.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});throw this.logger.error(`Error Message = ${e.message}, code = ${e.code}, subcode = ${e.subCode}`),e}return this.validateThreadIdFormat(t?.threadId),t?.threadId}validateThreadIdFormat(e){if(!e.startsWith(`19`)){let e=new Y({defaultError:J.CALL.TEAMS_INVALID_THREAD_ID});throw this.logger.error(`Error Message = ${e.message}, code = ${e.code}, subcode = ${e.subCode}`),e}}enforcePolicyAndLicenseRestrictions(){let e=+new Date;if(!this._mtPolicyService.isEvEnabled()){let t=+new Date,n=new Y({defaultError:J.CALL.CTE_VOICE_NOT_ENABLED});this.logger.error(`Error Message = ${n.message}, code = ${n.code}, subcode = ${n.subCode}`);let r=this._callAgent.getEcsConfigIds();throw this.sendCallStageEvent({eventName:Q.acs_calling_call_failed,correlationId:J0(),timestampInfo:{deltaTimeInMs:t-e},additionalPayload:{additionalProperties:{EmergencyCountryCode:this._callAgent._caConfigBag?.emergencyCountryCode||``,IsUserEmergencyCountryCode:this._callAgent._caConfigBag?.IsUserEmergencyCountryCode||!1,IsEmergencyCall:this.isEmergencyCall,trouterState:this._callAgent.getTrouterState(),AcsCallingSDKWeb_ecsConfigId:r.AcsCallingSDKWeb,SkypeWebMedia_ecsConfigId:r.SkypeWebMedia},additionalDetails:{...J3(n)}}},n,{code:n.code,subCode:n.subCode,phrase:n.message}),n}}handlePolicyAndLicenseRestrictionsFailure(e){this._callEndReason={message:`Unknown`,code:e?.code,subCode:e?.subCode,resultCategories:e?.resultCategories},this._state=`Disconnected`,this._eventEmitter.emit(`stateChanged`),this._callAgent.handleCallRemoved(this.tsCall)}async setupThreadIdWhenStartingGroupCall(e,t,n){if(t&&t.threadId&&(this.validateThreadIdFormat(t.threadId),this.logger.info(`ThreadId is already provided in the options parameter: `+JSON.stringify(t))),t===void 0||!t.threadId){let r=[];e.forEach((e=>{r.push({id:K2(e)})}));try{let e=await this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:Z().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:r});t||={},t.threadId=e,e&&this._info.setThreadId(e),n&&e&&(n.threadId=e)}catch(e){if(!Z().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(`Failed to create thread Id for Teams group call `+e)}}}async GetOrCreateGroupChatThread(e,t,n){let r=``;if(Yle(t))return this.logger.info(`Adding TeamsExtensionUserIdentifierto call`),Promise.resolve(r);if(e)return this.logger.info(`Customer provided threadId in options: `+JSON.stringify(n)),r=this.validateAndSetThreadId(t,n),Promise.resolve(r);let i=sTe(lTe(this),OG(t));if(Z().calling.enableOpsSmePassFakeConversation&&i)return r=this.tsCall.threadId||H4(),Promise.resolve(r);if(!Z().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation)throw new Y({defaultError:J.CALL.CTE_ADDPARTICIPANT_NO_THREAD_ID});if(this._info.threadId!==null&&this._info.threadId!==void 0){r=this._info.threadId;let e=[];return e.push({id:K2(t)}),await this._mtPolicyService.AddParticipantsToThread(this.tsCall.callId,{threadId:r,addParticipantsSuffix:Z().MiddleTier.serverManagedThreadIdApiConfiguration.addParticipantSuffix,participants:e}).catch((t=>{this.logger.warn(`Error when adding participants `+JSON.stringify(e)+` to thread. `+t)})),Promise.resolve(r)}{let e=[];return this._remoteParticipants.forEach((t=>{e.push({id:K2(t.identifier)})})),e.push({id:K2(t)}),await this._mtPolicyService.CreateChatThreadId(this.tsCall.callId,{createThreadIdSuffix:Z().MiddleTier.serverManagedThreadIdApiConfiguration.createThreadSuffix,participants:e}).then((e=>{r=e,this.logger.info(`Add participant into 1on1 call to convert it into Teams group call. Create thread id: `+r)})).catch((e=>{let n=`Error when adding participants `+K2(t)+` to thread to create a Teams group call. `;if(!Z().MiddleTier.serverManagedThreadIdApiConfiguration.decoupleChatThreadFromCalls)throw new Y({defaultError:J.CTE_MID_TIER_POLICY_SERVICE.CREATETHREAD_FAILED});this.logger.warn(n+e)})),Promise.resolve(r)}}addParticipantToTsCall(e,t,n,r,i,a){this.tsCall.addParticipant(K2(e),{threadId:t,customHeaderContext:U4(n)}).then((()=>{this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.success,participantAddedOrRemoved:`add`,correlationId:i,timestampInfo:{deltaTimeInMs:+new Date-a}})})).catch((t=>{let{callEndReason:n}=W3(this,r.tsRemoteParticipant,t);r.callEndReason||r.setCallEndReason(n);let o=Y3(n);this.sendParticipantAddedOrRemovedEvent({kindOfEvent:$.failure,participantAddedOrRemoved:`add`,correlationId:i,timestampInfo:{deltaTimeInMs:+new Date-a},additionalDetails:{code:o?.callEndReason.code,subCode:o?.callEndReason.subCode,failureReason:o?.callEndReason.message,...o}}),this._remoteParticipants.find((t=>K2(t.identifier)===K2(e)))&&(this.deleteRemoteParticipant(r),this._eventEmitter.emit(`remoteParticipantsUpdated`,{added:[],removed:[r]}))}))}IsTargetUserAllowed(e){return Xle(e)||TG(e)||wG(e)}};L9([XG(c4.AddParticipant),JG(c4.AddParticipant),R9(`design:type`,Function),R9(`design:paramtypes`,[Object,Object]),R9(`design:returntype`,Object)],z9.prototype,`addParticipant`,null),L9([XG(c4.RemoveParticipant),YG(c4.RemoveParticipant),R9(`design:type`,Function),R9(`design:paramtypes`,[Object]),R9(`design:returntype`,Promise)],z9.prototype,`removeParticipant`,null),L9([XG(c4.Mute),R9(`design:type`,Function),R9(`design:paramtypes`,[]),R9(`design:returntype`,Promise)],z9.prototype,`mute`,null),L9([XG(c4.Unmute),R9(`design:type`,Function),R9(`design:paramtypes`,[]),R9(`design:returntype`,Promise)],z9.prototype,`unmute`,null),L9([XG(c4.Hold),YG(c4.Hold),R9(`design:type`,Function),R9(`design:paramtypes`,[]),R9(`design:returntype`,Promise)],z9.prototype,`hold`,null),L9([XG(c4.Resume),YG(c4.Resume),R9(`design:type`,Function),R9(`design:paramtypes`,[]),R9(`design:returntype`,Promise)],z9.prototype,`resume`,null);var B9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},V9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},H9=class e extends Z7{get calls(){return this._calls}constructor(e,t,n,r,i,a){super(e,t,r,i,n,WG.TeamsCallAgent,a),this._calls=[],this.handleCallAdded=e=>{if(!this._calls.find((t=>t.id===e.callId))){let t=e.on(`callStateChanged`,(async()=>{if(e.state===1){let n=G6(e),r=e.callId;t.dispose();let i=new z9({callId:r,isIncoming:!0},this,e,this._telemetryLogManager);n&&(i=Q7(i));let a=new URe(i);this.handleCallState(i),n?await Promise.all(i.bindTsCall()):i.bindTsCall(),this._eventEmitter.emit(`incomingCall`,{incomingCall:a})}}))}},this.handleCallRemoved=e=>{this.logger.info(`removing callId=${e.callId}`);let t=this._calls.find((t=>t.id===e.callId));if(t){if(t.isBreakoutRoomCall){let e=Z().calling.breakoutRooms.hangUpCallDelayInMilliSeconds;setTimeout((()=>{this.disposeCall(t)}),e)}else this.disposeCall(t);this._eventEmitter.emit(`callsUpdated`,{added:[],removed:[t]}),this.logger.info(`call removed`)}},this.handleCallState=e=>{e.on(`stateChanged`,(async()=>{try{e.state===`Disconnected`?this.tsStack?(await this._tsCallRegistry.deleteCallAsync?.(e.tsCall)||this.logger.info(`The call has been removed from registry, call id: ${e.id}`),e.stats.flushEvents(),this._telemetryLogManager.flushAllEvents(e.id).catch((()=>{this.logger.error(`Failed to flush telemetry log manager events`)}))):this.logger.info(`Unable to remove call from registry`):e.state===`Connecting`&&e.direction==`Incoming`&&(this.addToCallArray(e),this._eventEmitter.emit(`callsUpdated`,{added:[e],removed:[]}))}catch{this.logger.error(`Failed to handle call state changed event`)}}))},this.logger=t}createNewCall(e,t){let n=new z9({callId:e},this,t,this._telemetryLogManager);return G6(t)?Q7(n):n}addToCallArray(e){this._calls.push(e),this.trackCallEndTimeToStopTelemetry(this._calls)}addToCallAgentsMap(t){e.teamsCallAgents.get(t?.identityMri)&&j4(J.CALL_AGENT.TEAMS_CALLAGENT_ALREADY_EXSISTS,this.logger),e.teamsCallAgents.set(t?.identityMri,this)}removeFromCallAgentsMap(t){t?.identityMri&&e.teamsCallAgents.get(t?.identityMri)===this&&e.teamsCallAgents.delete(t?.identityMri)}disposeCall(e){let t=this._calls.indexOf(e);t!==-1&&this._calls.splice(t,1),e.dispose(),this.trackCallEndTimeToStopTelemetry(this._calls)}getMiddleTierServiceInstance(){return this.mtPolicyService}async setUserPoliciesOnAgentInitialization(){super.setUserPoliciesOnAgentInitialization();try{if(this.isEnterpriseUser()){let e=J0();this.logger.info(`ACS MiddleTier service called on Teams Call Agent initialization with call Id=${e}`),await this.mtPolicyService.fetchUserPoliciesFromAcsMiddleTier(e,this.getUserMri(),{policyUrlSuffix:Z().MiddleTier.policyUrlSuffixV2,userPolicies:[`EmergencyPolicies`,`TeamsCallingPolicy`,`TeamsMeetingPolicy`],userProperties:[`FeatureTypes`,`PoliciesMetadata`,`phoneNumber`,`sipUri`,`hostType`,`accountEnabled`,`useTeamsCalling`,`evEnabled`,`region`,`routingType`,`preferredDataLocation`,`featureTypes`,`displayName`]}),this._userPolicies=this.mtPolicyService.getUserPolicy(),this._userProperties=this.mtPolicyService.getUserProperties(),this.logger.info(`****User policy initialized to ${JSON.stringify(this._userPolicies)}`),this.logger.info(`****User properties initialized to ${JSON.stringify(this._userProperties)}`)}}catch(e){this.logger.warn(`Fetching Teams user policy and Properties from ACS MiddleTier Service failed.\n Error message = ${e?.message}, code = ${e?.code}, subcode = ${e?.subCode}.`)}}async disposeInternal(t){let n=+new Date,r=J0();this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeTeamsCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});try{if(this._disposed)throw new Y({defaultError:J.CALL_AGENT.CTE_ALREADY_DISPOSED});this._disposed=!0,this._abortController.abort(),this._extensibleApi.dispose(),this._parsedTokenCredential?.identityMri&&e.teamsCallAgents.delete(this._parsedTokenCredential?.identityMri);for(let e of this._calls)e.state!==`Disconnected`&&await e.hangUp().catch((()=>{this.logger.error(`Failed to hangup call during Teams call agent dispose`)}));await this._tsCallRegistry?.dispose();let t=this._tokenFetchTries>this._maxNmberOfRetries;await this._callStack.disposeUserStack(t),this.offTrouterStateChanged(this._trouterStateChangeCallback),this._callStack.offRegisteredChanged(this._registrarStateChangeCallback),this._eventEmitter.removeAllListeners(),this._internalEventEmitter.emit(`disposed`),this._internalEventEmitter.removeAllListeners(),this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:``})}catch(e){let t=new Y({defaultError:J.CALL_AGENT.TEAMS_DISPOSE_FAIL,originalError:e});throw this.sendCallAgentDisposeEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeTeamsCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}}),t}finally{t&&this._telemetryLogManager.clearTelemetryLoggers()}}startCall(e,t){let n=J0(),r=+new Date,i={correlationId:n,timestampInfo:{attemptTimestamp:r}};this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_attempt,tenant:p2,properties:i},void 0,`attempt`);try{let i;if(this.assertParticipants(e),Array.isArray(e)){if(this.isTeamsExtensionUser()&&!Z().calling.teamsExtensionSettings.enableJoinCall)throw new Y({defaultError:J.FEATURES.ONE_PHONE_SYSTEM.CALL_CANNOT_BE_STARTED});if(i=t,e.length>1&&!Z().MiddleTier.serverManagedThreadIdApiConfiguration.allowServerThreadCreation&&!i?.threadId)throw new Y({defaultError:J.CALL_AGENT.GROUPCALL_THREADID});if(e.length==1&&i?.threadId)throw new Y({defaultError:J.CALL_AGENT.ONE_TO_ONE_THREADID})}else{if(this.isTeamsExtensionUser()&&!Z().calling.teamsExtensionSettings.enableStartCall)throw new Y({defaultError:J.FEATURES.ONE_PHONE_SYSTEM.CALL_CANNOT_BE_STARTED});i=t}if(Z().calling.enableSmePassFakeConversation&&this.isAcsToTeamsInteropCall(e)&&!this.isTeamsExtensionUser())throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TARGET_TYPE});let a=i?.audioOptions?.muted;return a===void 0&&(a=!1),this.logger.info(`startCall with video=${!!i?.videoOptions},muted=${a}`),this.createCall({participants:e,startCallOptions:i},{correlationId:n,attemptTimestamp:r})}catch(e){let t,i;throw e instanceof Y&&(t=typeof e?.message==`string`?e?.message:void 0,i={...J3(e)}),this._telemetryLogManager.sendEvent({name:Q.acs_calling_call_failed,tenant:p2,properties:{correlationId:n,timestampInfo:{deltaTimeInMs:+new Date-r},failureReason:t||``,additionalDetails:i||{}}},void 0,`failure`),e}finally{this._telemetryLogManager.deleteEventMapByCorrelationId(n)}}join(e,t){this.assertCallContext(e);let n=!!t?.audioOptions?.muted;return this.logger.info(`join with video=${!!t?.videoOptions},muted=${n}`),this.createCall({teamsCallContext:e,startCallOptions:t})}async dispose(){await this.disposeInternal(!0)}on(e,t){if(e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_SUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.on(e,t)}off(e,t){if(e!==`incomingCall`&&e!==`callsUpdated`&&e!==`connectionStateChanged`&&e!==`customContextChanged`)throw new Y({defaultError:J.CALL_AGENT.EVENT_UNSUBSCRIBE,defaultErrorMessageArgs:[e]});this._eventEmitter.off(e,t)}createCall(e,t){if(!this.tsStack)throw new Y({defaultError:J.CALL_AGENT.STACK_NOT_INIT});let n,r,i,a=e?.teamsCallContext?.threadId,o=!1,s=e?.teamsCallContext?.meetingLink,c=e?.teamsCallContext?.meetingId,l=e?.teamsCallContext?.passcode||``,u=!!e?.participants&&Array.isArray(e?.participants)&&e?.participants.length>1;if(this.isEnterpriseUser()&&u&&(a=(e?.startCallOptions).threadId),!B4(this.acsProxy,this.acsCustomRelayManager,!0))throw new Y({defaultError:J.CALL_AGENT.PROXY_CUSTOM_TURN_FORBIDDEN});if(s)if(vFe(s))r=P5(s);else{if(!yFe(s,this.logger))throw new Y({defaultError:J.CALL_AGENT.INVALID_MEETING_LINK});if(bFe(s.trim().toLocaleLowerCase(),Z().calling.tfl.hosts))throw new Y({defaultError:J.CALL_AGENT.UNSUPPORTED_TFL_MEETING_JOIN});o=!0}e?.teamsCallContext?.threadId&&e?.teamsCallContext?.organizerId&&e?.teamsCallContext?.tenantId&&(r={threadId:e?.teamsCallContext?.threadId,messageId:e?.teamsCallContext?.messageId?e?.teamsCallContext?.messageId.toString():`0`,organizerId:e?.teamsCallContext?.organizerId,tenantId:e?.teamsCallContext?.tenantId}),r&&(i={meetingType:r.messageId===`0`?1:2,tenantId:r.tenantId,organizerId:r.organizerId,replyChainMessageId:r.messageId},a=r.threadId,n=r.messageId);let d=this.mtPolicyService.isEmergencyNumber(this.isEnterpriseUser(),e?.participants),f=this.getOnBehalfOfMri(e,u,d),p={threadId:a||``,messageId:n||``,meetingInfo:i,mediaPeerType:2,onBehalfOf:f},m=G6(this._tsCallRegistry),h=PG(),g=J0(),_=J0();if(m){let r=Q7();return(async()=>{let i;i=c?await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:_,causeId:h,type:`MeetingData`,meetingData:{meetingCode:c,passcode:l,threadId:a}}):o?await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:_,causeId:h,type:`MeetingData`,meetingData:{meetingUrl:s}}):await this._tsCallRegistry.createCallAsync({callId:g,localParticipantId:_,causeId:h,type:`ThreadId`,threadId:a||``,messageId:n});let u=new z9({callId:g,isEmergencyNumber:d},this,i,this._telemetryLogManager);r.setTarget(u),this.addToCallArray(r),this.handleCallState(r);let f=n3();u.startCallInternal(e?.startCallOptions,!!c,e?.teamsCallContext,p,t,f,e?.participants).catch(M4),await Promise.all(u.bindTsCall()),await f.promise,this._eventEmitter.emit(`callsUpdated`,{added:[r],removed:[]})})().catch((e=>{})),r}{let r;r=c?this._tsCallRegistry.createCallWithMeetingData({meetingCode:c,passcode:l,threadId:a},g,_,h):o?this._tsCallRegistry.createCallWithMeetingData({meetingUrl:s},g,_,h):this._tsCallRegistry.createCall(a||``,g,_,n,h);let i=new z9({callId:g,isEmergencyNumber:d},this,r,this._telemetryLogManager);return this.addToCallArray(i),this.handleCallState(i),i.startCallInternal(e?.startCallOptions,!!c,e?.teamsCallContext,p,t,void 0,e?.participants).catch(M4),i.bindTsCall(),this._eventEmitter.emit(`callsUpdated`,{added:[i],removed:[]}),i}}getOnBehalfOfMri(e,t,n){let r=e?.startCallOptions?.onBehalfOfOptions?.userId;if(r){if(!Z().calling.sharedLineAppearance.enabled)throw this.logger.error(`SharedLineAppearance is disabled by ECS flag`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED});if((e?.startCallOptions).customContext&&!Z().calling.teamsExtensionSettings.enableCustomContext)throw new Y({defaultError:J.FEATURES.ONE_PHONE_SYSTEM.CUSTOM_CONTEXT_NOT_SUPPORTED});if(t)throw new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.GROUP_CALLS_NOT_SUPPORTED});if(!n){if(DG(r)&&!Z().calling.sharedLineAppearance.appOnBehalfOfEnabled)throw this.logger.error(`Start Teams call with onBehalfOf MicrosoftTeamsAppIdentifier is disabled by ECS flag`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED_FOR_APPLICATIONS});if(EG(r)){if(!Z().calling.sharedLineAppearance.userOnBehalfOfEnabled)throw this.logger.error(`Start Teams call with onBehalfOf MicrosoftTeamsUserIdentifier is disabled by ECS flag`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED});if(!this.getUserPolicy()?.teamsCallingPolicy?.allowDelegation)throw this.logger.error(`Start Teams call with onBehalfOf MicrosoftTeamsUserIdentifier is disabled by Teams calling policy`),new Y({defaultError:J.FEATURES.SHAREDLINE_APPEARANCE.DISABLED_BY_CALLING_POLICY})}return Zle(r)}this.logger.warn(`Emergency call cannot be made on behalf of another user, dropping the onBehalfOf options`)}}assertParticipants(e){Ywe(e,J.CALL_AGENT.USERIDS_MUST_BE_OBJECTS),Jwe(e,J.CALL_AGENT.USERIDS_CANNOT_BE_NULL)}assertCallContext(e){if(!e||this.checkForAtLeastOneValidCallConfig(e)||this.checkForInvalidTeamsMeetingCoordinates(e))throw new Y({defaultError:J.CALL_AGENT.INVALID_JOIN_LOCATOR})}checkForAtLeastOneValidCallConfig(e){return!e.threadId&&!e.meetingLink&&!e.meetingId}checkForInvalidTeamsMeetingCoordinates(e){return!e.threadId&&e.tenantId&&e.organizerId||e.threadId&&(e.organizerId&&!e.tenantId||!e.organizerId&&e.tenantId)}isAcsToTeamsInteropCall(e){let t=!1;return this.isEnterpriseUser()&&(Array.isArray(e)?e.length>=1&&e.find((e=>wG(e)))&&(t=!0):wG(e)&&(t=!0)),t}};H9.teamsCallAgents=new Map,B9([JG(s4.StartCall),V9(`design:type`,Function),V9(`design:paramtypes`,[Object,Object]),V9(`design:returntype`,Object)],H9.prototype,`startCall`,null),B9([JG(s4.Join),V9(`design:type`,Function),V9(`design:paramtypes`,[Object,Object]),V9(`design:returntype`,Object)],H9.prototype,`join`,null),B9([YG(s4.Dispose),V9(`design:type`,Function),V9(`design:paramtypes`,[]),V9(`design:returntype`,Promise)],H9.prototype,`dispose`,null);var WRe=class{constructor(){this._proxyInUse=!1;let e=ZW(`ACS-calling`);this.logger=new V6(e,[()=>`AcsProxy`])}get proxyInUse(){return this._proxyInUse}set proxyInUse(e){this._proxyInUse=e}get proxyUrl(){return this._proxyUrl?.toString()||``}set proxyUrl(e){if(e.length<4)throw new Y({defaultError:J.CALL_CLIENT.PROXY_SHORT_URL});e.slice(-1)!==`/`&&(e=e.concat(``,`/`));try{let t=new URL(e);if(t.protocol!==`https:`&&t.protocol!==`http:`)throw new Y({defaultError:J.CALL_CLIENT.PROXY_PROTOCOL});this._proxyUrl=t}catch(t){let n=new Y({defaultError:J.CALL_CLIENT.SETUP_PROXY,defaultErrorMessageArgs:[e],originalError:t});throw this.logger.error(n.message),n}}hasProxyUrl(){return!!this._proxyUrl}proxyfyUrl(e){let t=e;if(!this._proxyUrl)return this.logger.info(`Proxy url not defined, return original ${n4(t)}`),t;try{let e=new URL(t);t=`${`${e.protocol}//${this._proxyUrl.host}${this._proxyUrl.pathname}`}${e.host}${e.pathname}${e.search}`,this.logger.info(`Proxyfing url from ${n4(e)} to ${n4(t)}`)}catch(e){let t=`Failed proxyfy url with error: ${JSON.stringify(e)}, returning original`;this.logger.error(t)}return this._proxyInUse=!0,t}},GRe=class{constructor(){this._hasCustomRelay=!1,this._customRelayManagerInUse=!1;let e=ZW(`ACS-calling`);this._logger=new V6(e,[()=>`AcsCustomRelayManager`])}getRelayConfig(){return this._relayConfig}setRelayConfig(e){this._relayConfig={...e},this._logger.info(`Custom relay config provided`),this._hasCustomRelay=!0,this._createTsRelayManager()}get hasRelayConfig(){return this._hasCustomRelay}get customRelayManagerInUse(){return this._customRelayManagerInUse}set customRelayManagerInUse(e){this._customRelayManagerInUse=e}getTsRelayManager(){return this._tsRelayManager}_createTsRelayManager(){if(!this._hasCustomRelay||!this._relayConfig||this._relayConfig.iceServers.length<1)return void this._logger.warn(`No relay config provided. No op.`);let e=[];this._relayConfig.iceServers.forEach((t=>{t.urls.forEach((n=>{let r=this._getIndividualRelay(n,t?.username,t?.credential);e.push(r)}))})),this._tsRelayManager={initialize(){},queryRelaysAsync:t=>Promise.resolve(e)}}_getIndividualRelay(e,t,n){let r=3478,i=[],a=[],o=[b3.turn,b3.turns,b3.stun],s=[x3.tcp,x3.tls,x3.udp],c;try{c=new URL(e)}catch(t){throw new Y({defaultError:J.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[e],originalError:t})}let l=c.protocol.replace(`:`,``);if(!o.includes(l))throw new Y({defaultError:J.CALL_CLIENT.RELAY_UNRECOGNIZED_SCHEMA});let u,d=``;try{d=c.href.replace(/((turn)s?|stun):/,`https:`),u=new URL(d)}catch(e){throw new Y({defaultError:J.CALL_CLIENT.RELAY_INFO,defaultErrorMessageArgs:[d],originalError:e})}let f=u.searchParams.get(`transport`)??``;s.includes(f)||(this._logger.warn(`Unknown transport protocol detected for the provided turn, defaulting to ${x3.udp}`),f=x3.udp);let p=u.port===``?this._extractPortFromUrl(c):Number(u.port);p||=(this._logger.warn(`Could not read port from relay url, defaulting to ${r}`),r);let m=u.hostname;return xwe(m)?i.push(m):a.push(m),{addresses:i,udpPort:f===x3.udp?p:void 0,tcpPort:f===x3.tcp?p:void 0,tlsPort:f===x3.tls?p:void 0,username:t??``,password:n??``,type:`turn`,fqdns:a}}_extractPortFromUrl(e){let t=e.href.match(owe)?.[0];return Number(t?.replace(`:`,``))}},KRe=class{constructor(e,t,n){this._eventEmitter=new E3.EventEmitter,this._removeListeners=[];let r=(e,r)=>{n()&&t.sendEvent({name:Q.acs_calling_page_hidden,tenant:p2,properties:{eventName:e,pageHidden:r}})},i=()=>{document.visibilityState===`hidden`?(e.debug(`Visibility changed to hidden`),r(`visibilityChange`,!0),this._eventEmitter.emit(`visibilityChange`,!0)):(e.debug(`Visibility changed to visible`),r(`visibilityChange`,!1),this._eventEmitter.emit(`visibilityChange`,!0))},a=()=>{e.debug(`Page show`),r(`pageShow`,!1),this._eventEmitter.emit(`pageShow`)},o=()=>{e.debug(`Page hide`),r(`pageHide`,!0),this._eventEmitter.emit(`pageHide`)};window.addEventListener(`visibilitychange`,i),this._removeListeners.push((()=>window.removeEventListener(`visibilitychange`,i))),window.addEventListener(`pageshow`,a),this._removeListeners.push((()=>window.removeEventListener(`pageshow`,a))),window.addEventListener(`pagehide`,o),this._removeListeners.push((()=>window.removeEventListener(`pagehide`,o)));let s=(e,r)=>{n()&&t.sendEvent({name:Q.acs_calling_orientation_changed,tenant:p2,properties:{orientation:e,isInitial:r}})},c=()=>{let t=screen.orientation.type;e.debug(`Orientation changed to ${t}`),s(t,!1),this._eventEmitter.emit(`orientationChanged`,t)},l=()=>window.innerHeight>window.innerWidth?`portrait-primary`:`landscape-primary`,u=``,d=()=>{let t=l();u!==t&&(e.debug(`Orientation changed to ${t}`),u=t,s(t,!1),this._eventEmitter.emit(`orientationChanged`,t))};screen?.orientation?.type?(screen.orientation.addEventListener(`change`,c),this._removeListeners.push((()=>screen.orientation.removeEventListener(`change`,c))),s(screen.orientation.type,!0)):(window.addEventListener(`resize`,d),this._removeListeners.push((()=>window.removeEventListener(`resize`,d))),s(l(),!0))}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}dispose(){this._eventEmitter.removeAllListeners(),this._removeListeners.forEach((e=>e()))}},qRe,U9=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},W9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},JRe=1,G9=class e{get callAgent(){return this._callAgent}get teamsCallAgent(){return this._teamsCallAgent}get sdkDiagnosticInformation(){return this._sdkDiagnosticInformation}get telemetryLogManager(){return this._telemetryLogManager}setCallAgent(e){this._callAgent=e}setTeamsCallAgent(e){this._teamsCallAgent=e}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}constructor(e){this._disposed=!1,this._customProxyAndTurnInformation={proxy:null,turn:null},this.sendTelemetry=()=>{try{if(Z().telemetry.telemetryBeforeUnload&&this._callAgent&&this._callAgent._calls)for(let e of this._callAgent._calls)e.tsCall.sendLastKnownStats()}catch(e){this.logger.debug(`Error logging telemetry`,e)}};let t=+new Date;this.clientId=J0();let n=e?.logger||ZW(`ACS-calling`),r=JRe++;if(this._acsProxy=new WRe,this._acsCustomRelayManager=new GRe,this._vdi3Options=e?.vdi3,e?.networkConfiguration){e.networkConfiguration.proxy?.url&&(this._customProxyAndTurnInformation.proxy={...e.networkConfiguration.proxy},this._acsProxy.proxyUrl=this._customProxyAndTurnInformation.proxy.url),e.networkConfiguration.turn&&(this._customProxyAndTurnInformation.turn={...e.networkConfiguration.turn},this._acsCustomRelayManager.setRelayConfig(this._customProxyAndTurnInformation.turn));let t=this.getTelemetryTag();e.diagnostics?e.diagnostics.tags?e.diagnostics.tags.push(t):e.diagnostics.tags=[t]:e.diagnostics={tags:[t]}}this.logger=new V6(n,[()=>`CallClient${r}[${this.clientId}]`]),this._eventEmitter=new w6(this.logger),this._sdkDiagnosticInformation=tTe(Z2(),this.logger,e),this.diagnosticOptions=e?.diagnostics,this.firstPartyOptions=e?.firstPartyOptions,this._telemetryLogManager=new m3(this.logger,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager);try{this.sendCallClientInitEvent({eventName:Q.acs_calling_call_client_init,kindOfEvent:`attempt`,timestampInfo:``,additionalDetails:``}),Object.defineProperty(globalThis,C2,{value:r,writable:!0,enumerable:!1}),r===1&&Object.defineProperty(globalThis,S2,{value:this._telemetryLogManager,writable:!1,enumerable:!1}),this.logger.info(`created`),this._callStack=new M9(this.logger,this.clientId,this._telemetryLogManager,this._sdkDiagnosticInformation,this._acsProxy,this._acsCustomRelayManager,this.firstPartyOptions?.encodedStreamsJsPath,this._vdi3Options),this._deviceManager=new F9(this.logger,this._callStack,this._telemetryLogManager),window.addEventListener(`beforeunload`,this.sendTelemetry),this._screenDeviceManager=new KRe(this.logger,this._telemetryLogManager,(()=>this._callAgent?.calls?this._callAgent.calls.length>0:!!this._teamsCallAgent?.calls&&this._teamsCallAgent.calls.length>0)),this._screenDeviceManager.on(`visibilityChange`,(e=>{if(e)try{r8().formFactor===`Mobile`&&Z().calling.hangUpCallOnPageHide&&(this._callAgent?.calls.forEach((e=>e.hangUp())),this._teamsCallAgent?.calls.forEach((e=>e.hangUp())))}catch(e){this.logger.error(`Unable to hangup call on page hide due to ${e}`)}})),this._extensibleApi=new F3(this.logger,{callClient:this},{callClient:this,telemetryLogManager:this._telemetryLogManager});let e=e7(k3.CallClientFeature);for(let t of e)t.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(t);this.sendCallClientInitEvent({eventName:Q.acs_calling_call_client_init,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:``})}catch(e){let n=new Y({defaultError:J.CALL_CLIENT.INIT_CALL_CLIENT,originalError:e});throw this.sendCallClientInitEvent({eventName:Q.acs_calling_call_client_init,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-t},additionalDetails:{failureReason:n.message,code:n.code,subCode:n.subCode,...J3(n)}}),n}}createInstance(t){return new e(t)}get acsProxy(){return this._acsProxy}get acsCustomRelayManager(){return this._acsCustomRelayManager}getSDKVersion(){return Z2()}async getEnvironmentInfoInternal(){return this._environmentInfos||=(await this._callStack.createStackBase(),hke()),this._environmentInfos}feature(e){return this._extensibleApi.getApiObjectInstance(e.callClientApiCtor)}async createCallAgent(e,t){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let n=+new Date,r=J0();this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});let{identityMri:i}=await P4(e);if(this._callAgent?._caConfigBag?.identityMri===i)return this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS CallAgent already exists in this call client for the given identity.`}}),this._callAgent;if(this._callAgent||this._teamsCallAgent){let e=new Y({defaultError:J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT});this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS CallAgent already exists in this call client.`,failureReason:e.message,code:e.code,subCode:e.subCode,...J3(e)}}),j4(J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger)}if(this._callAgent=n9.callAgents.get(i),this._callAgent)return this._callAgent.onDisposed((()=>{this._callAgent=void 0})),this._eventEmitter.emit(`callAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS Call Agent already exists for the given identity. Maybe have been created by another call client instance.`}}),this._callAgent;this.validateEmergencyCountryCode(t);try{return this._callAgent=new n9(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager,t),await this._callAgent.initialize(e,t),this._callAgent.onDisposed((()=>{this._callAgent=void 0})),this._eventEmitter.emit(`callAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`ACS CallAgent created and initialized successfully.`}}),this._callAgent}catch(e){this._callAgent=void 0;let t=new Y({defaultError:J.CALL_CLIENT.CREATE_CALL_AGENT,originalError:e});throw this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}}),this._telemetryLogManager.clearTelemetryLoggers(),t}}async createTeamsCallAgent(e,t){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let n=+new Date,r=J0();this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createTeamsCallAgent,kindOfEvent:`attempt`,timestampInfo:{},correlationId:r,additionalDetails:``});let{identityMri:i,mriType:a}=await P4(e);if(a==n2.TeamsExtensionUser?this.logger.info(`TeamsCallAgent is TeamsExtensionUser type`):this.logger.info(`TeamsCallAgent is not TeamsUser type`),this._teamsCallAgent?._caConfigBag?.identityMri===i)return this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`Teams Call Agent already exists in this call client for the given identity.`}}),this._teamsCallAgent;if(this._callAgent||this._teamsCallAgent){let e=new Y({defaultError:J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT});this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createTeamsCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`Teams Call Agent already exists in this call client.`,failureReason:e.message,code:e.code,subCode:e.subCode,...J3(e)}}),j4(J.CALL_CLIENT.ONE_CALL_AGENT_PER_CALL_CLIENT,this.logger)}if(this._teamsCallAgent=H9.teamsCallAgents.get(i),this._teamsCallAgent)return this._teamsCallAgent.onDisposed((()=>{this._teamsCallAgent=void 0})),this._eventEmitter.emit(`teamsCallAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`Teams Call Agent already exists for the given identity. Maybe have been created by another call client instance.`}}),this._teamsCallAgent;try{return this._teamsCallAgent=new H9(this,this.logger,this._callStack,this.clientId,this._telemetryLogManager,this._deviceManager),await this._teamsCallAgent.initialize(e,t),this._teamsCallAgent.onDisposed((()=>{this._teamsCallAgent=void 0})),this._eventEmitter.emit(`teamsCallAgentCreated`),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createTeamsCallAgent,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{context:`TeamsCallAgent created and initialized successfully.`}}),this._teamsCallAgent}catch(e){this._teamsCallAgent=void 0;let t=new Y({defaultError:J.CALL_CLIENT.CREATE_TEAMS_CALL_AGENT,originalError:e});throw this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.createTeamsCallAgent,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-n},correlationId:r,additionalDetails:{failureReason:t.message,code:t.code,subCode:t.subCode,...J3(t)}}),this._telemetryLogManager.clearTelemetryLoggers(),t}}async getDeviceManager(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});return this._callAgent&&this._callAgent?.callClient!==this?(await this._callAgent?.deviceManager.getDeviceManager(),this._callAgent?.deviceManager):(await this._deviceManager.getDeviceManager(),this._deviceManager)}async dispose(){if(this._disposed)throw new Y({defaultError:J.CALL_CLIENT.DISPOSED});let e=+new Date,t=J0();try{this._disposed=!0,this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeCallClient,kindOfEvent:`attempt`,timestampInfo:{},correlationId:t,additionalDetails:``});try{this._deviceManager.dispose(),this.logger.info(`Device Manager disposed`)}catch{this.logger.error(`Call Client failed to dispose Device Manager`)}try{this._callAgent?await this._callAgent.disposeInternal(!1).then((()=>{this.logger.info(`ACS Call Agent disposed`)})):this._teamsCallAgent&&await this._teamsCallAgent.disposeInternal(!1).then((()=>{this.logger.info(`Teams Call Agent disposed`)}))}catch(e){e.subCode!==J.CALL_AGENT.ACS_ALREADY_DISPOSED.subCode&&e.subCode!==J.CALL_AGENT.CTE_ALREADY_DISPOSED.subCode||this.logger.debug(`Call Client failed to dispose Call Agent as it is already disposed`),this.logger.error(`Call Client failed to dispose Call Agent`)}try{this._screenDeviceManager.dispose()}catch{this.logger.error(`Call Client failed to dispose ScreenDevice Manager`)}try{await this._callStack.disposeBaseStack(),this.logger.info(`Base call stack disposed`)}catch{this.logger.error(`Call Client failed to dispose base call stack`)}this._eventEmitter.removeAllListeners(),window.removeEventListener(`beforeunload`,this.sendTelemetry),this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeCallClient,kindOfEvent:`success`,timestampInfo:{deltaTimeInMs:+new Date-e},correlationId:t,additionalDetails:``})}catch(n){let r=new Y({defaultError:J.CALL_CLIENT.DISPOSE_FAIL,originalError:n});throw this.sendCallClientOperationEvent({eventName:Q.acs_calling_client_operations,operation:J7.disposeCallClient,kindOfEvent:`failure`,timestampInfo:{deltaTimeInMs:+new Date-e},correlationId:t,additionalDetails:{failureReason:r.message,code:r.code,subCode:r.subCode,...J3(r)}}),r}finally{this._telemetryLogManager.clearTelemetryLoggers()}}validateEmergencyCountryCode(e){e?.emergencyCallOptions?.countryCode&&e.emergencyCallOptions?.countryCode.length>kCe&&j4(J.CALL_CLIENT.EMERGENCY_CODE_TOO_LONG,this.logger)}sendCallClientInitEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send CallClient initialized telemetry event`)}}sendCallClientOperationEvent(e){try{this._telemetryLogManager.sendEvent({name:e.eventName,tenant:p2,properties:e})}catch{this.logger.debug(`Unable to send CallClient dispose telemetry event`)}}getTelemetryTag(){return this._customProxyAndTurnInformation.proxy&&this._customProxyAndTurnInformation.turn?B2.usedProxyAndNonMsftTurn:this._customProxyAndTurnInformation.proxy?B2.onlyUsedProxy:this._customProxyAndTurnInformation.turn?B2.onlyUsedNonMsftTurn:``}};U9([UG,W9(`design:type`,Object)],G9.prototype,`logger`,void 0),U9([JG(o4.Feature),W9(`design:type`,Function),W9(`design:paramtypes`,[Object]),W9(`design:returntype`,typeof(qRe=typeof TFeature<`u`&&TFeature)==`function`?qRe:Object)],G9.prototype,`feature`,null),U9([YG(o4.CreateCallAgent),W9(`design:type`,Function),W9(`design:paramtypes`,[Object,Object]),W9(`design:returntype`,Promise)],G9.prototype,`createCallAgent`,null),U9([YG(o4.CreateTeamsCallAgent),W9(`design:type`,Function),W9(`design:paramtypes`,[Object,Object]),W9(`design:returntype`,Promise)],G9.prototype,`createTeamsCallAgent`,null),U9([YG(o4.GetDeviceManager),W9(`design:type`,Function),W9(`design:paramtypes`,[]),W9(`design:returntype`,Promise)],G9.prototype,`getDeviceManager`,null),U9([YG(o4.Dispose),W9(`design:type`,Function),W9(`design:paramtypes`,[]),W9(`design:returntype`,Promise)],G9.prototype,`dispose`,null);var YRe=class{constructor(e,t,n,r,i){if(this._width=0,this._height=0,this._eventEmitter=new E3.EventEmitter,this._loopId=0,this._isDisposed=!1,e.getVideoTracks().length===0)throw Error(`Video stream must have at least one video track`);this._videoStream=e.clone(),this._refreshInterval=r,this._logger=i.createChild(`VideoStreamCanvasEncoder`),this._video=document.createElement(`video`),this._canvas=document.createElement(`canvas`),this._video.srcObject=this._videoStream,this._video.addEventListener(`resize`,(()=>{let e=this._video.videoWidth||t,r=this._video.videoHeight||n;this._width===e&&this._height===r||(this._width=e,this._height=r,this._canvas.width=e,this._canvas.height=r,this._logger.info(`Video stream resized to ${e}x${r}`))})),this._video.addEventListener(`play`,(()=>{this._loopId||=window.setInterval((()=>{if(!this._isDisposed&&!this._video.paused&&!this._video.ended){this._context.drawImage(this._video,0,0,this._width,this._height);let e=Uint8Array.from(this._canvas.toDataURL(`image/jpeg`),(e=>e.charCodeAt(0)));this._eventEmitter.emit(`data`,e)}}),this._refreshInterval)})),this._video.addEventListener(`pause`,(()=>{this._loopId&&=(clearInterval(this._loopId),0)})),this._video.play().catch((e=>{this._logger.error(`Error playing video stream: ${e}`)})),this._context=this._canvas.getContext(`2d`)}on(e,t){this._eventEmitter.on(e,t)}dispose(){this._isDisposed||(this._isDisposed=!0,this._loopId&&=(clearInterval(this._loopId),0),this._video.pause(),this._video.srcObject=null,this._videoStream.getTracks().forEach((e=>{e.stop()})),this._eventEmitter.removeAllListeners())}},XRe=3,ZRe=class{constructor(e,t,n){this._eventEmitter=new E3.EventEmitter,this._loopId=0,this._isDisposed=!1,this._dataQueue=[],this._timeoutCounter=0,this._timeoutCount=0,this._canvas=document.createElement(`canvas`),this._canvas.width=0,this._canvas.height=0,this._context=this._canvas.getContext(`2d`),this._logger=t.createChild(`VideoStreamCanvasDecoder`),this._mediaStream=this._canvas.captureStream(Math.max(1,Math.ceil(1e3/e))),this._timeoutCount=n;let r=e=>new Promise(((t,n)=>{try{let r=new TextDecoder().decode(e),i=new Image;i.onload=()=>{i.width===this._canvas.width&&i.height===this._canvas.height||(this._canvas.width=i.width,this._canvas.height=i.height),this._context.drawImage(i,0,0,this._canvas.width,this._canvas.height),t(new VideoFrame(this._canvas,{timestamp:0}))},i.onerror=e=>{n(e)},i.src=r}catch(e){n(e)}})),i=async()=>{let t=performance.now();if(this._dataQueue.length>0){this._timeoutCounter=0;let e=this._dataQueue.shift();if(e)try{let t=await r(e);this._eventEmitter.emit(`frame`,t),t.close()}catch{this._logger.error(`Error decoding frame`)}}else if(this._timeoutCounter++,this._timeoutCounter>this._timeoutCount)return this._logger.warn(`No data to decode, stopping video stream`),this._eventEmitter.emit(`dispose`),void this.dispose();let n=performance.now(),a=Math.max(e-(n-t),0);this._loopId=window.setTimeout(i,a)};i()}on(e,t){this._eventEmitter.on(e,t)}decode(e){this._isDisposed||(this._dataQueue.length>XRe&&(this._logger.warn(`Data queue is full, dropping oldest frame`),this._dataQueue.shift()),this._dataQueue.push(e))}getMediaStream(){if(this._isDisposed)throw Error(`VideoStreamCanvasDecoder has been disposed`);return this._mediaStream}dispose(){this._isDisposed||(this._isDisposed=!0,this._loopId&&=(clearTimeout(this._loopId),0),this._eventEmitter.removeAllListeners())}},K9;function q9(e,t){let n=t?t.length:0,r=performance.now(),i=new ArrayBuffer(9+n),a=new DataView(i);if(a.setUint8(0,e),a.setFloat64(1,r),t){let e=new Uint8Array(i,9);for(let n=0;n<t.length;n++)e[n]=t[n]}return new Uint8Array(i)}function QRe(e){let t=new DataView(e.buffer);return{messageType:t.getUint8(0),timestamp:t.getFloat64(1),data:new Uint8Array(e.buffer,9,e.length-9)}}(function(e){e[e.VideoFrame=1]=`VideoFrame`,e[e.StopVideo=2]=`StopVideo`})(K9||={});var $Re=class{constructor(e,t,n,r){this.audioContext=null,this.analyserNode=null,this.sourceNode=null,this.dataArray=null,this.processingIntervalId=null,this.isCurrentlySpeaking=!1,this.consecutiveSpeechSamples=0,this.consecutiveSilenceSamples=0,this.lastSpeechActivityTimestamp=-1/0,this.callbackFiredForCurrentSegment=!1,this.processAudio=()=>{if(!this.analyserNode||!this.dataArray)return void(this.processingIntervalId!==null&&(clearInterval(this.processingIntervalId),this.processingIntervalId=null,this.logger.warn(`AudioAnalyzer stopped due to missing nodes.`)));this.analyserNode.getByteTimeDomainData(this.dataArray);let e=0;for(let t=0;t<this.dataArray.length;t++){let n=(this.dataArray[t]-128)/128;e+=n*n}let t=Math.sqrt(e/this.dataArray.length),n=this.options.speechConfirmSamples,r=this.options.silenceConfirmSamples,i=this.options.minCallbackIntervalMs;if(t>this.options.silenceThreshold){if(this.consecutiveSpeechSamples++,this.consecutiveSilenceSamples=0,this.consecutiveSpeechSamples>=n){let e=Date.now(),n=e-this.lastSpeechActivityTimestamp;!this.callbackFiredForCurrentSegment&&n>i&&(this.logger.info(`AudioAnalyzer: First audio render callback fired. Silence duration: ${n}ms`),this.onSpeechStartCallback(),this.callbackFiredForCurrentSegment=!0),this.lastSpeechActivityTimestamp=e,this.isCurrentlySpeaking||(this.isCurrentlySpeaking=!0,this.logger.info(`AudioAnalyzer: Speech confirmed after ${this.consecutiveSpeechSamples} consecutive samples, avgVolume: ${t.toFixed(4)}, threshold: ${this.options.silenceThreshold}.`))}}else this.consecutiveSilenceSamples++,this.consecutiveSpeechSamples=0,this.consecutiveSilenceSamples>=r&&this.isCurrentlySpeaking&&(this.isCurrentlySpeaking=!1,this.callbackFiredForCurrentSegment=!1,this.logger.debug(`AudioAnalyzer: Silence confirmed after ${this.consecutiveSilenceSamples} consecutive samples. Ready for next turn.`))},this.stream=e,this.logger=t,this.onSpeechStartCallback=n;let i=Z().waimeabay.audioAnalyzer;this.options={...i,...r},this.stream.getAudioTracks().length?this.initialize():this.logger.warn(`AudioAnalyzer: No audio tracks found in the provided stream.`)}initialize(){try{this.audioContext=new AudioContext,this.analyserNode=this.audioContext.createAnalyser(),this.analyserNode.fftSize=this.options.fftSize,this.analyserNode.smoothingTimeConstant=this.options.smoothingTimeConstant,this.sourceNode=this.audioContext.createMediaStreamSource(this.stream),this.sourceNode.connect(this.analyserNode),this.dataArray=new Uint8Array(this.analyserNode.fftSize),this.logger.info(`AudioAnalyzer initialized.`)}catch(e){this.logger.error(`AudioAnalyzer initialization failed: ${e}`),this.dispose()}}start(){this.audioContext&&this.analyserNode&&this.dataArray?this.processingIntervalId===null&&(this.logger.info(`AudioAnalyzer started monitoring with interval ${this.options.processingIntervalMs}ms.`),this.processingIntervalId=window.setInterval(this.processAudio,this.options.processingIntervalMs)):this.logger.warn(`AudioAnalyzer cannot start, not properly initialized.`)}stop(){this.processingIntervalId!==null&&(clearInterval(this.processingIntervalId),this.processingIntervalId=null,this.logger.info(`AudioAnalyzer stopped monitoring.`))}dispose(){this.stop();try{this.sourceNode?.disconnect(),this.analyserNode?.disconnect(),this.audioContext?.close().catch((e=>this.logger.error(`Error closing AudioContext: ${e}`)))}catch(e){this.logger.error(`AudioAnalyzer dispose error: ${e}`)}finally{this.audioContext=null,this.analyserNode=null,this.sourceNode=null,this.dataArray=null,this.consecutiveSpeechSamples=0,this.consecutiveSilenceSamples=0,this.callbackFiredForCurrentSegment=!1,this.logger.info(`AudioAnalyzer disposed.`)}}};function J9(e){return isNaN(e)?e:Math.round(10*e)/10}var Y9=class e{static get instance(){return e._instance||=new e,e._instance}register(e,t){this._requests.set(e,{...t,requestTime:performance.now()})}unregister(e){this._requests.delete(e)}constructor(){this._requests=new Map,globalThis.PerformanceObserver!==void 0&&(this._observer=new PerformanceObserver((e=>{e.getEntries().forEach((e=>{if(e.entryType===`resource`){let t=e;if((t.requestStart??0)<=0)return;let n=e.name,r=this._requests.get(n);if(r){let e=r.path;this.unregister(n);let i={path:e,duration:J9(t.duration),initiatorType:t.initiatorType,nextHopProtocol:t.nextHopProtocol,fetchStart:J9(t.fetchStart),domainLookupStart:J9(t.domainLookupStart),domainLookupEnd:J9(t.domainLookupEnd),connectStart:J9(t.connectStart),secureConnectionStart:J9(t.secureConnectionStart),connectEnd:J9(t.connectEnd),requestStart:J9(t.requestStart),responseStart:J9(t.responseStart),responseEnd:J9(t.responseEnd),transferSize:t.transferSize,encodedBodySize:t.encodedBodySize,responseStatus:t.responseStatus};r.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r.correlationId,operationName:`FetchTimingInfo`,durationInMs:i.duration,operationPayload:{...i},resultCategories:[`Success`],resultSignature:200,sessionId:r.sessionId,endpointId:r.endpointId})}}}))})),this._observer.observe({type:`resource`,buffered:!1}))}dispose(){e._instance&&=(this._requests.clear(),this._observer?.disconnect(),null)}};Y9._instance=null;var eze,tze=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},X9=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},nze=e=>{try{return new URL(e)}catch{return}},rze=e=>{let t=`Request`;if(e instanceof URL)return{href:e.toString(),pathname:e.pathname??``};if(typeof Request<`u`&&e instanceof Request)return rze(e.url);if(typeof e==`string`){let n=nze(e);return n?{href:n.href,pathname:n.pathname??``}:{href:e||t,pathname:``}}return{href:t,pathname:``}},ize=class{constructor(e){this._params=e,this._state=jG.Connecting,this._initializeRefTime=0,this._isMuted=!1,this._remoteAudioStreams=new Map,this._remoteVideoStreams=new Map,this._joinSessionDefer=n3(),this._feedViewDefer=n3(),this._audioRenderers=new Map,this._audioAnalyzers=new Map,this._endpointId=``,this._wbSessionStats={localCandidateType:``,relayCandidateCount:0},this._localAudioStreams=new Set,this._localVideoStreams=new Set,this._audioEffectsProcessorStats=[],this._audioEffectsStatsListener=null,this._audioEffectsSubscribedStream=null,this._videoChannel=void 0,this._videoStreamEncoder=void 0,this._videoStreamDecoder=new Map,this._telemetryChannel=void 0,this._telemetryChannelInitializationPromise=void 0,this._sessionConnectedTimestamp=void 0,this._sessionConnectedSignalSent=!1,this.startAudio=async(e,t)=>{let n=performance.now(),r=J0();try{if(this._params.logger.debug(`SessionImpl: startAudio called`),this._joinSessionDefer&&(setTimeout((()=>{if(this._joinSessionDefer?.isPending())return this._joinSessionDefer.reject(new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STARTAUDIO_SESSION_TIMEDOUT}))}),Z().waimeabay.audio.startAudioSessionTimeoutMs),await this._joinSessionDefer.promise),this._outboundAudio&&this._outgoingMediaStream&&!this._isMuted)try{let e=this._outgoingMediaStream.getAudioTracks()[0];e&&(this._outboundAudio.setMediaSource(e),this._params.logger.info(`Applied pending outbound audio stream with stream ID: ${this._outgoingMediaStream.id}`))}catch(e){this._params.logger.error(`Failed to apply pending outbound audio stream: ${e instanceof Error?e.message:String(e)}`)}let i=!1,a=async()=>{i=!0,this._params.logger.debug(`Use normal real-time LocalAudioStream in session`);let e=this._params.options?.localAudioStream?this._params.options?.localAudioStream:await Z5(this._params.deviceManagerInternal,this._params.logger);await this.handleLocalAudioStream(e,!0,r,t)};try{this._preAudioFeature=e;let t=+new Date;if(this._preAudioFeature)if(this._preAudioFeature.recordAudioFailed||!this._preAudioFeature.recordAudioFinished){let e=+new Date,t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.USE_NORMALMIC_OR_RAWAUDIO_BECAUSE_RECORDAUDIO_FAILED});this._preAudioFeature.recordAudioFinished||(t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.USE_NORMALMIC_OR_RAWAUDIO_BECAUSE_RECORDAUDIO_FAILED})),this._preAudioFeature.logger.error(t.message),await this._preAudioFeature?.disposeInternal(),await this._preAudioFeature?.disposeRtcMic(),await a(),this._preAudioFeature.sendTelemetryEvent(+new Date-e,{timestampInfo:{attemptTimestamp:e},...J3(t)},t.resultCategories,500)}else{let{micLocalAudioStream:e,micRawMediaStream:n}=this._preAudioFeature.getMicMediaStream();if(this._preAudioFeature.isFinished){if(this._preAudioFeature.logger.debug(`PreAudio already finished, will use it's real-time mic for session start`),this._sessionConnectedTimestamp===void 0){let e=this._preAudioFeature.getFirstSpeechTimestamp();e!==void 0&&(this.setFirstClientAudioTimestamp(e),this._params.logger.debug(`Applied finished preAudio speech timestamp ${e}`))}await this.handleLocalAudioStream(e)}else{this._params.logger.debug(`Get PreAudio's player audio stream to use for session start`);let t=await this._preAudioFeature.getPlayerLocalAudioStream(this,(async()=>{let r=+new Date;try{if(!this._preAudioFeature)throw new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.SWITCH_TO_RTCMIC_FAIL_PREAUDIO_UNDEFINED});this._preAudioFeature.logger.debug(`PreAudio player mediastream finished flushing`),this._preAudioFeature.logger.debug(`Now switching to real-time microphone in session`),this._preAudioFeature.disposeInternal().catch((()=>{this._preAudioFeature?.logger.error(`Failed to dispose PreAudio feature after preAudio finished and got called back.`)})),this._localAudioStreams.delete(t),await this.handleLocalAudioStream(e,!1),this.updateOutboundAudioStream(n),n.getAudioTracks().forEach((e=>{e.enabled=!0})),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[t]}),this._preAudioFeature.logger.debug(`Switched to default real-time microphone in session`),this._preAudioFeature.sendTelemetryEvent(+new Date-r,{step:X5.SWITCHED_TO_REALTIME_MIC,timestampInfo:{attemptTimestamp:r}},[`Success`],200)}catch(e){this._preAudioFeature?.logger.error(`Failed to switch to default real-time microphone after preAudio player mediastream finished flushing`,e);let t=new Y({defaultError:J.WB_MEDIA_SDK.FEATURES.PRE_AUDIO.SWITCH_TO_RTC_MIC_FAIL,originalError:e});this._preAudioFeature?this._preAudioFeature.sendTelemetryEvent(+new Date-r,{timestampInfo:{attemptTimestamp:r},...J3(t)},[`Failure`],500):this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:``,operationName:`PreAudio`,durationInMs:+new Date-r,operationPayload:{timestampInfo:{attemptTimestamp:r},...J3(t)},resultCategories:[`Failure`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})}}));await this.handleLocalAudioStream(t)}this._preAudioFeature.setEchoRefStream(this),this.subscribeToAudioEffectsStats(e),this._preAudioFeature.logger.debug(`Set PreAudio's ${this._preAudioFeature.isFinished?`real-time mic`:`player audio stream`} for session start`),this._preAudioFeature.sendTelemetryEvent(+new Date-t,{step:this._preAudioFeature.isFinished?X5.START_SESSION_WITH_RTC_MIC:X5.START_SESSION_WITH_PLAYER_AUDIO_STREAM,timestampInfo:{attemptTimestamp:t}},[`Success`],200)}else await a()}catch(e){if(i)throw e;await a()}this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartAudio`,durationInMs:performance.now()-n,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_AUDIO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: startAudio error`,t),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartAudio`,durationInMs:performance.now()-n,operationPayload:{...J3(t).communicationServicesError},resultCategories:t.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),t}},this.createIncomingAudioHandler=async e=>{e.inboundAudio.getAllSourceMedia().firesAll((e=>{let{isLocal:t,endpointId:n,sourceId:r}=e.metadata;if(this._params.logger.debug(`Inbound firesAll media received from ${n}, isLocal: ${t}`),!t)try{e.provider.acquire().fires((e=>{try{if(e.track){this._sessionConnectedTimestamp===void 0&&(this._sessionConnectedTimestamp=Date.now(),this._params.logger.info(`SessionConnectedTimestamp set on first remote audio track arrival: ${this._sessionConnectedTimestamp}`));let t=new MediaStream;t.addTrack(e.track);let i=this._params.tsStack.getDeviceManager().createAudioRenderer?.();if(i?.play(t),this._audioRenderers.set(n,i),Z().waimeabay.sendTelemetrySignal){this._sessionConnectedSignalSent||this._sessionConnectedTimestamp===void 0||(this.sendTelemetrySignal(w4.SessionConnected,this._sessionConnectedTimestamp),this._sessionConnectedSignalSent=!0);let e=new $Re(t,this._params.logger,(()=>{this.sendTelemetrySignal(w4.FirstAudioRender)}));e.start(),this._audioAnalyzers.set(n,e)}let a={sourceId:r,endpointId:n,type:`Audio`,mediaStream:t};this._remoteAudioStreams.set(n,a),this.sendStreamsUpdatedTelemetry(a,`added`),this._eventEmitter.emit(`streamsUpdated`,{added:[a],removed:[]})}}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error handling media track event from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`added`,failureType:`mediaTrackEvent`,failureReason:t})}}))}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error acquiring audio track queue from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`added`,failureType:`acquireMediaTrackQueue`,failureReason:t})}try{let t=e.provider.acquire();(async()=>{try{let e=await t;for(;!e.done;)e=await e.next;let r=this._remoteAudioStreams.get(n),i=this._audioRenderers.get(n),a=this._audioAnalyzers.get(n);a&&(a.dispose(),this._audioAnalyzers.delete(n)),t.dispose(),i&&(i.dispose(),this._audioRenderers.delete(n)),r&&(this._remoteAudioStreams.delete(n),this.sendStreamsUpdatedTelemetry(r,`removed`),this._eventEmitter.emit(`streamsUpdated`,{added:[],removed:[r]}))}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error processing audio track queue from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`removed`,failureType:`processMediaTrackQueue`,failureReason:t})}})()}catch(e){let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Error acquiring audio track queue from ${n}: ${t}`),this.sendStreamsUpdatedFailureTelemetry({endpointId:n,sourceId:r,type:`Audio`,action:`removed`,failureType:`acquireMediaTrackQueue`,failureReason:t})}}))},this.handleLocalAudioStream=async(e,t=!0,n,r)=>{if(this._localAudioStreams.add(e),e.addSession(this),r&&e.mediaStreamType===`Audio`){let t=!1;try{await this.startAudioEffects(e,r)}catch{this._params.logger.error(`Failed to start effects for normal audio.`),t=!0}if(!t)try{this.subscribeToAudioEffectsStats(e)}catch{this._params.logger.error(`Failed to subscribe to audio effects stats for normal audio.`)}}if(t){let t;if(e.mediaStreamType===`RawMedia`)t=await e.getMediaStream();else{let e=async(e,t=!1)=>{let r=+new Date;try{let n=await e.getMediaStream(!0);if(!n)throw t?new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_FIRSTATTEMPT_ONCHANGED}):new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_FIRSTATTEMPT});return n}catch(i){let a=K3(i,!0,new Y({defaultError:J.WB_MEDIA_SDK.SESSION.FAILED_TO_GETMEDIASTREAM,originalError:i}));this._params.logger.error(`Error getting media stream, trying again`,a.message),this.sendHandleLocalAudioStreamFailureTelemetry(a,r,{...J3(a).communicationServicesError},n);try{let n=await e.getMediaStream();if(!n)throw t?new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_SECONDATTEMPT_ONCHANGED}):new Y({defaultError:J.WB_MEDIA_SDK.LOCAL_AUDIO_STREAM.LOCAL_AUDIO_GET_MEDIA_STREAM_UNDEFINED_SECONDATTEMPT});return n}catch(e){let t=K3(e,!0,new Y({defaultError:J.WB_MEDIA_SDK.SESSION.FAILED_TO_GETMEDIASTREAM,originalError:e}));throw this._params.logger.error(`Error getting media stream on second attempt`,t.message),t}}},r=async()=>{let t=+new Date;try{if(!this._tsRawStream){let e=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.NO_TS_RAW_STREAM_PRESENT_ONCHANGED});throw this._params.logger.error(e.message),e}{let t=await e(this._tsRawStream,!0);this.updateOutboundAudioStream(t),this._isMuted&&(this._isMuted=!1,this.mute())}}catch(e){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.FAILED_TO_GETMEDIASTREAM_ONCHANGED,originalError:e});this.sendHandleLocalAudioStreamFailureTelemetry(r,t,{...J3(r).communicationServicesError},n)}};this._tsRawStream=this._params.deviceManagerInternal.getRawDeviceMediaStream(0),this._tsRawStream.changed((()=>{this._params.logger.log(`RawDeviceMediaStream changed`),r()})),t=await e(this._tsRawStream)}this.updateOutboundAudioStream(t)}this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[e],removed:[]})},this.createVideoHandler=async()=>{let e=Z().waimeabay.video,t=new K5(this,{payloadType:e.payloadType,transmissionMode:q5.PartiallyReliable,isLargeData:!0},this._params.logger,this._params.telemetryLogManager);await t.initialize(),t.on(`message`,(e=>{let{data:t,endpointId:n}=e;this._params.logger.log(`video data received: ${t.length} bytes from ${n}`);let r=QRe(t);if(r.messageType!==K9.StopVideo){if(r.messageType===K9.VideoFrame){if(!this._videoStreamDecoder.has(n)){let e=Z().waimeabay.video.timeoutCount,t=new ZRe(1e3,this._params.logger,e),r={sourceId:0,endpointId:n,type:`Video`,mediaStream:t.getMediaStream()};this._remoteVideoStreams.set(n,r),t.on(`dispose`,(()=>{this._videoStreamDecoder.delete(n),this._remoteVideoStreams.delete(n),this.sendStreamsUpdatedTelemetry(r,`removed`),this._eventEmitter.emit(`streamsUpdated`,{added:[],removed:[r]})})),this.sendStreamsUpdatedTelemetry(r,`added`),this._eventEmitter.emit(`streamsUpdated`,{added:[r],removed:[]}),t.on(`frame`,(e=>{this._params.logger.log(`video frame received: ${e.displayWidth}x${e.displayHeight} from ${n}`)})),this._videoStreamDecoder.set(n,t)}this._videoStreamDecoder.get(n).decode(r.data)}}else{let e=this._videoStreamDecoder.get(n);if(e){e.dispose(),this._videoStreamDecoder.delete(n);let t=this._remoteVideoStreams.get(n);t&&(this._remoteVideoStreams.delete(n),this.sendStreamsUpdatedTelemetry(t,`removed`),this._eventEmitter.emit(`streamsUpdated`,{added:[],removed:[t]}))}}})),this._videoChannel=t},this.sendHandleLocalAudioStreamFailureTelemetry=(e,t,n,r)=>{this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r||``,operationName:`StartAudio`,durationInMs:+new Date-t,operationPayload:{...J3(e).communicationServicesError},resultCategories:e.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})},e.logger.debug(`SessionImpl: constructor called with sessionId: ${e.sessionId}, localAudioSteam: ${!!e.options?.localAudioStream}, localVideoStream: ${!!e.options?.localVideoStream}`),this._eventEmitter=new w6(this._params.logger),this._extensibleApi=new F3(e.logger,{session:this,sessionAgent:e.sessionAgent},{tsSession:e.tsWbSession,sessionAgent:e.sessionAgent,session:this,telemetryLogManager:e.telemetryLogManager})}get audioEffectsProcessorStats(){return this._audioEffectsProcessorStats}clearAudioEffectsProcessorStats(){this._audioEffectsProcessorStats=[]}feature(e){return this._extensibleApi.getApiObjectInstance(e.sessionApiCtor)}get localAudioStreams(){return Array.from(this._localAudioStreams)}get localVideoStreams(){return Array.from(this._localVideoStreams)}get state(){return this._state}get isMuted(){return this._isMuted}get remoteAudioStreams(){return Array.from(this._remoteAudioStreams.values())}get remoteVideoStreams(){return Array.from(this._remoteVideoStreams.values())}get endpointId(){return this._endpointId}get sessionId(){return this._params.sessionId}get feedSession(){return this._session}mute(){let e=performance.now(),t=J0();try{this._params.logger.debug(`SessionImpl: mute called`,t),this.validateSessionState(c4.Mute),this._preAudioFeature&&!this._preAudioFeature.isFinished?(this._preAudioFeature.muteRtcMic(),this._isMuted=!0):this._isMuted||this.toggleAudioMuteState(),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Mute`,durationInMs:performance.now()-e,operationPayload:{wasMuted:this._isMuted},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.MUTE_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: mute error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Mute`,durationInMs:performance.now()-e,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}unmute(){let e=performance.now(),t=J0();try{this._params.logger.debug(`SessionImpl: unmute called`,t),this.validateSessionState(c4.Unmute),this._preAudioFeature&&!this._preAudioFeature.isFinished?(this._preAudioFeature.unmuteRtcMic(),this._isMuted=!1):this._isMuted&&this.toggleAudioMuteState(),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Unmute`,durationInMs:performance.now()-e,operationPayload:{wasMuted:!this._isMuted},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.UNMUTE_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: unmute error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`Unmute`,durationInMs:performance.now()-e,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}async startRawAudio(e){try{if(this.validateSessionState(c4.StartAudio),this._params.logger.debug(`SessionImpl: startAudio called`),e?.mediaStreamType!==`RawMedia`)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_RAW_AUDIO_LAS_NOT_RAW_MEDIA});this._outboundAudio&&this._outboundAudio.clearMediaSource();let t=Array.from(this._localAudioStreams)[0];t&&(this._localAudioStreams.delete(t),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[t]}),this._cachedLocalAudioStreamBeforeRawAudioStarted=t),await this.handleLocalAudioStream(e),this.sendTelemetrySignal(w4.StartRawAudio)}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_RAW_AUDIO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: startAudio error`,e),t}}async stopRawAudio(){try{this.validateSessionState(c4.StopAudio),this._params.logger.debug(`SessionImpl: stopAudio called`);let e=Array.from(this._localAudioStreams)[0];if(e?.mediaStreamType!==`RawMedia`)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STOP_RAW_AUDIO_LAS_NOT_RAW_MEDIA});this._outboundAudio&&this._outboundAudio.clearMediaSource(),this._localAudioStreams.delete(e),this._eventEmitter.emit(`localAudioStreamsUpdated`,{added:[],removed:[e]});let t=this._cachedLocalAudioStreamBeforeRawAudioStarted||await Z5(this._params.deviceManagerInternal,this._params.logger);await this.handleLocalAudioStream(t),this._cachedLocalAudioStreamBeforeRawAudioStarted=void 0,this.sendTelemetrySignal(w4.StopRawAudio)}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STOP_RAW_AUDIO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: stopAudio error`,e),t}}muteIncomingAudio(){let e=performance.now(),t=J0();try{this._params.logger.debug(`SessionImpl: muteIncomingAudio called`,t),this.validateSessionState(c4.MuteIncomingAudio),this._audioRenderers.forEach((e=>e.setMuted(!0))),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{audioRenderersCount:this._audioRenderers.size},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.MUTE_INCOMING_AUDIO_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: muteIncomingAudio error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}unmuteIncomingAudio(){let e=performance.now(),t=J0();try{this._params.logger.debug(`SessionImpl: unmuteIncomingAudio called`,t),this.validateSessionState(c4.UnmuteIncomingAudio),this._audioRenderers.forEach((e=>e.setMuted(!1))),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`UnmuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{audioRenderersCount:this._audioRenderers.size},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.UNMUTE_INCOMING_AUDIO_FAILED,originalError:n});throw this._params.logger.error(`SessionImpl: unmuteIncomingAudio error`,n),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`UnmuteIncomingAudio`,durationInMs:performance.now()-e,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),r}}async startVideo(e){try{if(this.validateSessionState(c4.StartVideo),this._videoStreamEncoder){let e=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.VIDEO_ALREADY_STARTED});throw this._params.logger.error(e.message),e}this._localVideoStreams.add(e);let t=await e.getMediaStream(),n=Z().waimeabay.video.defaultWidth,r=Z().waimeabay.video.defaultHeight,i=Z().waimeabay.video.refreshInterval;this._videoStreamEncoder=new YRe(t,n,r,i,this._params.logger),this._videoStreamEncoder.on(`data`,(e=>{this._videoChannel?.send(q9(K9.VideoFrame,e))})),e.mediaStreamType===`Video`&&e.disposeRawStream()}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_VIDEO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: startVideo error`,e),t}}stopVideo(){try{this._videoStreamEncoder&&(this._videoStreamEncoder.dispose(),this._videoStreamEncoder=void 0,this._videoChannel?.send(q9(K9.StopVideo))),Array.from(this._localVideoStreams.values()).forEach((e=>{this._localVideoStreams.delete(e)}))}catch(e){let t=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.STOP_VIDEO_FAILED,originalError:e});throw this._params.logger.error(`SessionImpl: stopVideo error`,e),t}}cleanup(){try{this._joinSessionDefer&&this._joinSessionDefer.dispose(),this._joinSessionDefer=void 0,this._audioRenderers.forEach((e=>e.dispose())),this._audioRenderers.clear(),this._audioAnalyzers.forEach((e=>e.dispose())),this._audioAnalyzers.clear(),this._videoStreamEncoder&&(this._videoStreamEncoder.dispose(),this._videoStreamEncoder=void 0,this._videoChannel?.send(q9(K9.StopVideo))),this.localVideoStreams.forEach((e=>{e.autoDisposeOnCallEnd&&e.dispose(),this._localVideoStreams.delete(e)})),this._params.sessionAgent.removeSession({sessionId:this._params.sessionId}),this._outboundAudio?.dispose(),this._feedView?.dispose();let e=this._state;if(this._state=jG.Disconnected,e!==this._state){let t=this._initializeRefTime>0?performance.now()-this._initializeRefTime:0,n=J0();this.logTelemetryWithEndpointId(n,t,e),this._params.logger.info(`Session state changed from ${e} to ${this._state}`),this._eventEmitter.emit(`stateChanged`)}this._eventEmitter.removeAllListeners(),this._extensibleApi.dispose()}catch(e){this._params.logger.error(`SessionImpl: Failed to cleanup with error: ${e instanceof Error?e.message:String(e)}`)}}disconnectInternal(e){let t=J0(),n=performance.now();this._params.logger.debug(`SessionImpl: hangUp called`,t);try{if(this._audioEffectsStatsListener&&this._audioEffectsSubscribedStream){try{this._audioEffectsSubscribedStream.feature($5.AudioEffects)?.off(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener)}catch(e){this._params.logger.warn(`Error cleaning up audio effects stats subscription on disconnect: ${e}`)}this._audioEffectsStatsListener=null}this._audioEffectsProcessorStats=[],this._audioEffectsSubscribedStream=null,this.localAudioStreams.forEach((e=>{e.removeSession(this),e.autoDisposeOnCallEnd&&e.dispose()})),this._localAudioStreams.clear(),this._tsRawStream&&=(this._tsRawStream.dispose(),void 0),this._preAudioFeature?.disposeRtcMic().catch((e=>{this._params.logger.error(`Error disposing rtc mic in preAudioFeature`,e)})),this._telemetryChannel&&=(this._telemetryChannel.dispose(),void 0),this._sessionConnectedTimestamp=void 0,this._sessionConnectedSignalSent=!1,this._session?.dispose(),this.cleanup(),this._params.logger.debug(`SessionImpl: hangUp success`,t),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`DisconnectSession`,durationInMs:performance.now()-n,operationPayload:{source:e},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(r){let i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.DISCONNECT_FAILED,originalError:r});throw this._params.logger.error(`SessionImpl: hangUp error`,r),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`DisconnectSession`,durationInMs:performance.now()-n,operationPayload:{...J3(i).communicationServicesError,source:e},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),i}}disconnect(){this.disconnectInternal(`client`)}disconnectFromUnload(e){this.disconnectInternal(e)}on(e,t){this._params.logger.debug(`Raising event: ${e}`),e!==`stateChanged`&&e!==`streamsUpdated`&&e!==`configureRequest`&&e!==`localAudioStreamsUpdated`||this._eventEmitter.on(e,t)}off(e,t){this._params.logger.debug(`Unsubscribing from event: ${e}`),e!==`stateChanged`&&e!==`streamsUpdated`&&e!==`configureRequest`&&e!==`localAudioStreamsUpdated`||this._eventEmitter.off(e,t)}async createDataChannel(e,t){let n=e.payloadType,r;switch(this._feedView||await this._feedViewDefer.promise,this._feedView.setInboundDataConfig(n,{maxStreams:Z().waimeabay.dataChannel.maxStreams,messageDeserializer:e=>e}).getInboundData(n).getAllSourceMedia().firesAll((({metadata:e,onMessageEvent:n,onDispose:r})=>{let i=e.endpointId;n.fires((e=>{t(i,e)})),r.then((()=>{this._params.logger.log(`Data stream got disposed`,i)}))})),e.transmissionMode){case q5.Realtime:r=W5.MediaTransmissionMode.REALTIME;break;case q5.PartiallyReliable:r=W5.MediaTransmissionMode.PARTIALLY_RELIABLE;break;default:r=void 0}return this._session.createOutboundData({payloadType:n,messageSerializer:e=>e,initialState:new Uint8Array,...r===void 0?{}:{transmissionMode:r}}).setFeedIds(Z().waimeabay.feedId)}async initialize(e){try{await this._internalInitialize(e)}catch(e){throw this._feedView?this._feedViewDefer.resolve():this._feedViewDefer.reject(e),e}}async _internalInitialize(e){let t=performance.now();this._initializeRefTime=t;let n=J0();this._params.logger.debug(`SessionImpl: initialize called`,n),this._params.tsWbSession.on(`callQualityChanged`,(e=>{this._params.logger.debug(`SessionQualityChanged: ${JSON.stringify(e)}`)}));let r={sendEvent:e=>{this._params.telemetryLogManager.sendWbEvent({...this._endpointId?{endpointId:this._endpointId}:{},sessionId:this._params.sessionId,eventData:e})}},i=performance.now();try{this._session=await this._params.tsWbSession.createFeedSession({serviceOrigin:this.getServiceOrigin(),telemetryLogger:r,authorizationHeaderProvider:async()=>`Bearer `+await this._params.sessionAgent.tokenProvider(),httpFetch:async(e,t)=>{let r=performance.now(),{href:i,pathname:a}=rze(e),o=(e,t)=>{let o=performance.now()-r,s=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e.error}),c=e.headers?.get(`X-Azure-Ref`),l=e.headers?.get(`x-ms-request-id`),u=e.headers?.get(`x-cache`),d=e.headers?.get(`ms-region-name`),f=e.headers?.get(`ms-stamp-name`),p=e.headers?.get(`ms-ring-name`);this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`HTTPRequest`,durationInMs:o,operationPayload:{...e.status===void 0?{}:{status:e.status},...e.statusText===void 0?{}:{statusText:e.statusText},...c?{"X-Azure-Ref":c}:{},...l?{xMsRequestId:l}:{},...u?{xCache:u}:{},...d?{msRegionName:d}:{},...f?{msStampName:f}:{},...p?{msRingName:p}:{},pathName:a,...J3(s).communicationServicesError},resultCategories:s.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId});let m=e.status===void 0?e.error:`status ${e.status}`;if(this._params.logger.error(`HTTP fetch failed for ${i}:`,m),t)throw s},s=(e,t,o)=>{let s=performance.now()-r,c=o.get(`X-Azure-Ref`),l=o.get(`x-ms-request-id`),u=o.get(`x-cache`),d=o.get(`ms-region-name`),f=o.get(`ms-stamp-name`),p=o.get(`ms-ring-name`);this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`HTTPRequest`,durationInMs:s,operationPayload:{status:e,statusText:t,...c?{"X-Azure-Ref":c}:{},...l?{xMsRequestId:l}:{},...u?{xCache:u}:{},...d?{msRegionName:d}:{},...f?{msStampName:f}:{},...p?{msRingName:p}:{},pathName:a},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.debug(`HTTP fetch succeeded for ${i} - Status: ${e}`)},c={...t?.headers instanceof Headers?(()=>{let e={};return t.headers.forEach(((t,n)=>{e[n]=t})),e})():t?.headers,"X-Microsoft-Skype-Chain-ID":this._params.sessionId};try{Y9.instance.register(i,{path:a,correlationId:n,sessionId:this._params.sessionId,endpointId:this._endpointId,telemetryLogManager:this._params.telemetryLogManager});let r=await globalThis.fetch(e,{...t,headers:c});return this._params.logger.debug(`HTTP fetch to ${e} - Status: ${r.status}`),r.ok?s(r.status,r.statusText,r.headers):o({error:Error(`HTTP request failed with status ${r.status}`),status:r.status,statusText:r.statusText,headers:r.headers},!1),r}catch(e){return o({error:e},!0)}},applicationInfo:this._params.clientTypeInfo}),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`CreateFeedSession`,durationInMs:performance.now()-i,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}catch(e){let t=performance.now()-i,r=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e});throw this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`CreateFeedSession`,durationInMs:t,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`CreateFeedSession failed`,r),r}let a=e=>{if(this._connectionState===e)return;let r=performance.now()-t,i=e=>{if(e===void 0)return`Initial`;switch(e){case W5.SessionConnectionState.CONNECTING:return`Connecting`;case W5.SessionConnectionState.CONNECTED:return`Connected`;case W5.SessionConnectionState.FAILOVER:return`Failover`;case W5.SessionConnectionState.DISCONNECTED:return`Disconnected`;default:return`UNKNOWN`}},a=i(this._connectionState),o=i(e);this._connectionState=e,this._params.logger.info(`Session transport state changed: ${a} -> ${o}`);let s={eventName:Q.acs_wb_session_events,operationId:n,operationName:`TransportStateChanged`,durationInMs:r,operationPayload:{oldState:a,newState:o,...this._wbSessionStats},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId};this._params.telemetryLogManager.sendWbSessionEvent(s)},o,s;this._session.stats.fires((e=>{let t=e.localCandidateType??``;this._wbSessionStats.localCandidateType!==t&&(this._wbSessionStats.localCandidateType=t,this._params.logger.info(`Local candidate type of active connection is ${this._wbSessionStats.localCandidateType}`)),this._wbSessionStats.relayCandidateCount=e.relayCandidateCount??0})),this._session.connectionState.fires((e=>{a(e)})),a(this._session.connectionState.value),this._session.metadata.then((e=>{let r=performance.now()-t;this._joinSessionDefer&&this._joinSessionDefer.resolve(this._session),this._endpointId=e.endpointId,this._params.logger.debug(`Session metadata received in ${r} ms for endpointId ${this._endpointId} `),this._params.tsWbSession.setAdditionalTelemetryFields({WB_SessionId:this._params.sessionId,WB_EndpointId:this._endpointId,WB_RoomId:this._params.sessionId}),this._params.logger.debug(`MediaStreamSession: setAdditionalTelemetryFields on _tsWbSession with sessionId: ${this._params.sessionId}, endpointId: ${this._endpointId}`),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`AllocateSession`,durationInMs:r,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),this.emitConfigureRequest(e)})).catch((e=>{let r=performance.now()-t,i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e});this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`AllocateSession`,durationInMs:r,operationPayload:{...J3(i).communicationServicesError},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`Session metadata error`,i)})),this._feedView=this._session.createFeedView().setFeedId(Z().waimeabay.feedId).setInboundAudioConfig({maxStreams:Z().waimeabay.audio.maxStreams,reflectionMode:W5.MediaReflectionMode.NONE}),this._feedViewDefer.resolve(),this._session.onConnect.then((async()=>{let r=performance.now()-t;if(this._params.logger.debug(`WB Connected in ${r} ms for endpointId ${this._endpointId} `),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`JoinSession`,durationInMs:r,operationPayload:{feedId:Z().waimeabay.feedId,isPreheated:!!e,isDisconnected:this._state===jG.Disconnected},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._state!==jG.Disconnected){let t=this._state;this._state=e&&t!==jG.Connected?jG.Preheated:jG.Connected,this.logTelemetryWithEndpointId(n,r,t),t!==this._state&&(this._params.logger.info(`Session state changed from ${t} to ${this._state}`),this._eventEmitter.emit(`stateChanged`))}})).catch((e=>{let r=performance.now()-t,i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED,originalError:e});this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`AllocateSession`,durationInMs:r,operationPayload:{...J3(i).communicationServicesError},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`Session connection error`,i),this._joinSessionDefer&&this._joinSessionDefer.isPending()&&this._joinSessionDefer.reject(e)})),this._session.onDisconnect.then((e=>{o=e})).catch((e=>{let t=e instanceof Error?e.message:JSON.stringify(e);this._params.logger.error(`Session disconnected with an error: ${t}`),s={...o,errorMessage:t}})).finally((()=>{let e=performance.now()-t;this._params.logger.debug(`Session disconnected in ${e} ms, cause: ${JSON.stringify(o)}`),setTimeout((async()=>{let e=await this._params.tsWbSession.getMediaTelemetry();this._params.logger.info(`WBStats mediaTelemetry ${JSON.stringify(e)}`),this._params.tsWbSession.reportMediaTelemetry(),this._params.logger.info(`reportMediaTelemetry called on disconnect.`)}),3e3);let r=this._state;r!==jG.Disconnected&&(this._state=jG.Disconnected,this.logTelemetryWithEndpointId(n,e,r,s||o),this._params.logger.info(`Session state changed from ${r} to ${this._state}`),this._eventEmitter.emit(`stateChanged`),this.cleanup())}));let c=e7(k3.SessionFeature);for(let e of c)e.activationOptions.activationEvent===`OnExtendedObjectConstructor`&&this.feature(e);if(e||await this.startMedia(!1),Z().waimeabay.sendTelemetrySignal)try{await this.initializeTelemetryChannel(),this._params.logger.info(`Initialize: TelemetryChannel initialized successfully by main initialize flow!`)}catch(e){this._params.logger.error(`Initialize: Main initialize flow failed to initialize TelemetryChannel: ${e instanceof Error?e.message:String(e)}`)}}async startMedia(e,t){let n=performance.now(),r=J0();if(this._state===jG.Disconnected)return this._params.logger.error(`SessionImpl: startMedia called in invalid state: ${this._state}`),void this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartMedia`,durationInMs:performance.now()-n,operationPayload:{isPreheated:!!e},resultCategories:[`UnexpectedClientError`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId});t&&this._params.setOptions(t);try{this.createIncomingAudioHandler(this._feedView),this._outboundAudio||=this._session.createOutboundAudio().setFeedIds(Z().waimeabay.feedId);let t=this._state;this._state=jG.Connected;let i=performance.now()-n;this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartMedia`,durationInMs:i,operationPayload:{isPreheated:!!e,state:this._state},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId}),e&&this.logTelemetryWithEndpointId(r,i,t),t!==this._state&&(this._params.logger.info(`Session state changed from ${t} to ${this._state}`),this._eventEmitter.emit(`stateChanged`)),Z().waimeabay.enableVideoHandler&&await this.createVideoHandler()}catch(t){let i=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.START_MEDIA_FAILED,originalError:t});throw this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:r,operationName:`StartMedia`,durationInMs:performance.now()-n,operationPayload:{isPreheated:!!e,state:this._state,...J3(i).communicationServicesError},resultCategories:i.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId}),this._params.logger.error(`Failed to create audio/video handler: ${t instanceof Error?t.message:String(t)}`),i}}updateOutboundAudioStream(e){let t=this.localAudioStreams[0];if(t){let n=e.clone();t.setWBMediaStream(n)}if(this._outgoingMediaStream=e,this._outboundAudio)if(this._outboundAudio.clearMediaSource(),this._isMuted)this._params.logger.debug(`updateOutboundAudioStream: stream ${e.id} set while muted; track not attached until unmute.`);else{let t=e.getAudioTracks()[0];t&&this._outboundAudio.setMediaSource(t),this._params.logger.info(`Updated outbound audio stream with stream ID: ${e.id}`)}else this._params.logger.debug(`updateOutboundAudioStream: _outboundAudio not created yet, stream ${e.id} will be set when startMedia is called`)}logTelemetryWithEndpointId(e,t,n,r){this._endpointId===``&&this._params.logger.error(`Session metadata error the endpointId is empty, cannot log telemetry with endpointId yet.`);let i=n===jG.Connecting&&this._state===jG.Disconnected,a=new Y({defaultError:J.WB_MEDIA_SDK.SESSION.JOIN_FAILED}),o={eventName:Q.acs_wb_session_events,operationId:e,operationName:`StateChanged`,durationInMs:t,operationPayload:{oldState:n,newState:this._state,disconnectedCause:r??``},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId};i&&(o.resultSignature=500,o.resultCategories=a.resultCategories,o.operationPayload={...o.operationPayload,...J3(a).communicationServicesError},this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:e,operationName:`JoinSession`,durationInMs:t,operationPayload:{feedId:Z().waimeabay.feedId,...J3(a).communicationServicesError,disconnectedCause:r?{...r}:``},resultCategories:a.resultCategories,resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})),this._params.telemetryLogManager.sendWbSessionEvent(o)}emitConfigureRequest(e){let t={feedId:Z().waimeabay.feedId,sessionId:this._params.sessionId,endpointId:this._endpointId,endpointSecret:e.secretToken,activationUrl:this.getServiceOrigin()+Z().waimeabay.activationPath},n=J0(),r=performance.now();this._eventEmitter.emit(`configureRequest`,t,((e,t)=>{if(e)this._params.logger.debug(`SessionImpl: configureRequest success`),this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`ConfigureRequest`,durationInMs:performance.now()-r,operationPayload:{},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId});else{let e=t||`Unknown error`;this._params.logger.error(`SessionImpl: configureRequest failed: ${e}`);let i=new Y({defaultError:J.CALL.OPERATION_FAILED,defaultErrorMessageArgs:[`ConfigureRequest`]});this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:n,operationName:`ConfigureRequest`,durationInMs:performance.now()-r,operationPayload:{configurationFailureReason:e,...J3(i).communicationServicesError},resultCategories:[`UnexpectedClientError`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})}}))}getServiceOrigin(){return this._params.serviceOrigin&&this._params.serviceOrigin.trim()!==``?this._params.serviceOrigin:Z().waimeabay.origin}async startAudioEffects(e,t){let n=e.feature($5.AudioEffects),r=r8().engine;await n.startEffects({noiseSuppression:r===`Chromium`?t.noiseSuppression:r===`Safari`?void 0:`BrowserNoiseSuppression`,echoCancellation:r===`Chromium`?t.echoCancellation:`BrowserEchoCancellation`})}async subscribeToAudioEffectsStats(e){try{if(this._params.logger.debug(`MediaStreamSession: subscribeToAudioEffectsStats - effectsStarted event received, waiting briefly for internal stats subscription to be set up`),await new Promise((e=>setTimeout(e,100))),this._params.logger.debug(`MediaStreamSession: subscribeToAudioEffectsStats - Setting up audio effects stats subscription after delay`),!e||this._audioEffectsSubscribedStream===e&&this._audioEffectsStatsListener)return;if(this._audioEffectsStatsListener&&this._audioEffectsSubscribedStream&&this._audioEffectsSubscribedStream!==e)try{this._audioEffectsSubscribedStream.feature($5.AudioEffects)?.off(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener)}catch(e){this._params.logger.warn(`MediaStreamSession: subscribeToAudioEffectsStats - Error cleaning up existing audio effects stats subscription: ${e}`)}let t=e.feature($5.AudioEffects);if(!this._audioEffectsStatsListener||this._audioEffectsSubscribedStream!==e){this._audioEffectsStatsListener=e=>{e&&this._audioEffectsProcessorStats.push(e)},t?.on(`effectsProcessorStatsUpdated`,this._audioEffectsStatsListener);let n=t?.audioEffectsProcessorStats;n&&this._audioEffectsProcessorStats.push(n),this._audioEffectsSubscribedStream=e}}catch(e){this._params.logger.warn(`MediaStreamSession: subscribeToAudioEffectsStats - Error handling audio effects stats subscription: ${e}`)}}initializeTelemetryChannel(){if(this._telemetryChannelInitializationPromise)return this._telemetryChannelInitializationPromise;let e=Z().waimeabay.telemetry;return this._telemetryChannelInitializationPromise=(async()=>{try{if(this._telemetryChannel)return;this._telemetryChannel=new K5(this,{payloadType:e.payloadType,...e.mode===1?{isLargeData:!1,transmissionMode:q5.Realtime}:e.mode===2?{isLargeData:!1,transmissionMode:q5.PartiallyReliable}:{isLargeData:!0,transmissionMode:q5.Realtime}},this._params.logger,this._params.telemetryLogManager),await this._telemetryChannel.initialize(),this._params.logger.info(`initializeTelemetryChannel: DataChannelAdapter initialized.`),this._telemetryChannel.on(`message`,(e=>{try{let t=Lwe(e.data);this._params.logger.info(`MediaStreamSession: Telemetry data received from endpoint ${e.endpointId}: `,JSON.stringify(t))}catch(t){this._params.logger.error(`MediaStreamSession: Error decoding telemetry message from ${e.endpointId}: ${t instanceof Error?t.message:String(t)}`)}}))}catch(e){this._params.logger.error(`initializeTelemetryChannel: Failed to initialize: ${e instanceof Error?e.message:String(e)}`),this._telemetryChannel=void 0,this._telemetryChannelInitializationPromise=void 0}})(),this._telemetryChannelInitializationPromise}async sendTelemetrySignal(e,t){let n=t===void 0?Date.now():t;if(Z().waimeabay.sendTelemetrySignal)try{if(await this.initializeTelemetryChannel(),!this._telemetryChannel)return void this._params.logger.warn(`sendTelemetrySignal: Telemetry channel is not available after attempting initialization.`);if(this._telemetryChannel.state<A8.Initialized)return void this._params.logger.warn(`sendTelemetrySignal: Telemetry channel adapter state is ${this._telemetryChannel.state}, not ready to send signal ${e}.`);let t=Fwe(e,n),r=Iwe(t);this._telemetryChannel.send(r),this._params.logger.info(`sendTelemetrySignal: Successfully sent signal: ${e}, message: ${JSON.stringify(t)}`)}catch(t){this._params.logger.error(`sendTelemetrySignal: Failed to send telemetry signal ${e}: ${t instanceof Error?t.message:String(t)}`,t)}}toggleAudioMuteState(){if(this._isMuted=!this._isMuted,this._isMuted)this._outboundAudio&&this._outboundAudio.clearMediaSource();else try{this._outboundAudio&&this._outboundAudio.setMediaSource(this._outgoingMediaStream.getAudioTracks()[0])}catch(e){this._params.logger.error(`Failed to unmute audio: ${e instanceof Error?e.message:String(e)}`)}}validateSessionState(e){if(this._state!==jG.Connected&&(this._state!==jG.Connecting||e!=c4.Mute&&e!=c4.Unmute)){if(this._state===jG.Disconnected)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.DISCONNECTED_JOIN_AGAIN,defaultErrorMessageArgs:[e]});if(this._state===jG.Connecting)throw new Y({defaultError:J.WB_MEDIA_SDK.SESSION.CONNECTING_WAIT,defaultErrorMessageArgs:[e]})}}async sendStreamsUpdatedTelemetry(e,t){this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:``,operationName:`StreamsUpdated`,durationInMs:0,operationPayload:{sourceId:e.sourceId,remoteEndpointId:e.endpointId,type:e.type,action:t},resultCategories:[`Success`],resultSignature:200,sessionId:this._params.sessionId,endpointId:this._endpointId})}async sendStreamsUpdatedFailureTelemetry(e){this._params.telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:``,operationName:`StreamsUpdated`,durationInMs:0,operationPayload:{sourceId:e.sourceId,remoteEndpointId:e.endpointId,type:e.type,action:e.action,failureType:e.failureType,failureReason:e.failureReason},resultCategories:[`UnexpectedClientError`],resultSignature:500,sessionId:this._params.sessionId,endpointId:this._endpointId})}setFirstClientAudioTimestamp(e){this._sessionConnectedTimestamp===void 0&&(this._sessionConnectedTimestamp=e,this._params.logger.info(`SessionConnectedTimestamp set via setFirstClientAudioTimestamp: ${e}`))}};tze([JG(Dwe.Feature),X9(`design:type`,Function),X9(`design:paramtypes`,[Object]),X9(`design:returntype`,typeof(eze=typeof TFeature<`u`&&TFeature)==`function`?eze:Object)],ize.prototype,`feature`,null);var aze=class e{static create(){return new e}setTsStack(e){return this._tsStack=e,this}setDeviceManagerInternal(e){return this._deviceManagerInternal=e,this}setClientTypeInfo(e){return this._clientTypeInfo=e,this}setTsWbSession(e){return this._tsWbSession=e,this}setLogger(e){return this._logger=e,this}setTelemetryLogManager(e){return this._telemetryLogManager=e,this}setClientId(e){return this._clientId=e,this}setServiceOrigin(e){return this._serviceOrigin=e,this}setSessionId(e){return this._sessionId=e,this}setOptions(e){return this._options=e,this}setSessionAgent(e){return this._sessionAgent=e,this}get sessionAgent(){return this._sessionAgent}get tsStack(){return this._tsStack}get deviceManagerInternal(){return this._deviceManagerInternal}get clientTypeInfo(){return this._clientTypeInfo}get tsWbSession(){return this._tsWbSession}get logger(){return this._logger}get telemetryLogManager(){return this._telemetryLogManager}get clientId(){return this._clientId}get serviceOrigin(){return this._serviceOrigin}get sessionId(){return this._sessionId}get options(){return this._options}},oze=class{constructor(e,t,n,r,i,a,o,s){this._logger=e,this._telemetryLogManager=t,this._clientId=n,this._tokenCredential=r,this._callStack=i,this._deviceManagerInternal=a,this._clientTypeInfo=o,this._options=s,this._tokenFetchTries=0,this._sessionMap=new Map,this.tokenProvider=async e=>{if(!this._tokenCredential)throw new Y({defaultError:J.CALL_AGENT.GET_TOKEN_BEFORE_INIT});let t=await P4(this._tokenCredential,Z().calling.eudb.isRgnClaimEnabledForACS);return t.acsResourceId===this._parsedTokenCredential?.acsResourceId&&t.identityMri===this._parsedTokenCredential?.identityMri||j4(J.CALL_AGENT.REFRESHED_TOKEN_INVALID_USERID,this._logger),e?this._tokenFetchTries+=1:this._tokenFetchTries=0,this._tokenFetchTries>this._maxNumberOfRetries&&j4(J.CALL_AGENT.REFRESHED_TOKEN_RETRIES,this._logger),t.jwtToken},this._logger.debug(`MediaSessionAgentImpl: constructor called token: ${!!this._tokenCredential} options: ${JSON.stringify(this._options)}`),this._parsedTokenCredential=eTe(),this._maxNumberOfRetries=Z().calling.maxNumberOfTokenFetchRetries||zCe;let c=new TLe(this._telemetryLogManager);this._telemetryLogger=c.getGenericTelemetryLogger(`waimeabay`),s?.sessionAgentConfig?.allowDisconnectOnBeforeUnload&&(window.addEventListener(`beforeunload`,(()=>{this._disconnectAllSessions(`unload`)})),this._logger.debug(`MediaSessionAgent: Page unload listener registered (beforeunload)`))}_getSessionParams(e,t,n,r){let i=n?.sessionId??J0(),a=aze.create().setTsStack(this._tsWbStack).setDeviceManagerInternal(this._deviceManagerInternal).setClientTypeInfo(this._clientTypeInfo).setTsWbSession(t);return a.setClientId(this._clientId).setSessionAgent(this).setLogger(this._logger).setTelemetryLogManager(this._telemetryLogManager).setSessionId(i),e||a.setOptions(r),this._options?.serviceOrigin&&a.setServiceOrigin(this._options.serviceOrigin),a}_getOrCreateMediaSession(e,t,n){if(!this._tsWbStack)throw Error(`MediaSessionAgent is not initialized`);let r=this._getSessionKey(t),i=this._sessionMap.get(r);if(i)return this._logger.debug(`MediaSessionAgentImpl: Returning existing session for key: ${r}, total sessions: ${this._sessionMap.size}`),e||i.session.state!==jG.Preheated&&i.session.state!==jG.Connecting||i.session.startMedia(!0,n),i.session;let a=this._tsWbStack.getWBSessionObject(r,{media:this._telemetryLogger});if(!a)throw new Y({defaultError:J.WB_MEDIA_SDK.AGENT.TS_STACK_FAILD_TO_GET_WB_SESSION});let o=new ize(this._getSessionParams(!1,a,t,n)),s=performance.now(),c=J0();return o.initialize(e).then((()=>{this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:c,operationName:`MediaSessionInit`,durationInMs:performance.now()-s,operationPayload:{},resultCategories:[`Success`],resultSignature:200})})).catch((e=>{this._logger.error(`Session initialization failed: ${e}`);let t=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:e});this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:c,operationName:`MediaSessionInit`,durationInMs:performance.now()-s,operationPayload:{...J3(t).communicationServicesError},resultCategories:t.resultCategories,resultSignature:500})})),this._sessionMap.set(r,{session:o,tsWbSession:a}),this._logger.debug(`MediaSessionAgentImpl: Created and stored new session for key: ${r}, total sessions: ${this._sessionMap.size}`),o}joinSession(e,t){return this._getOrCreateMediaSession(!1,e,t)}preheatSession(e){return this._getOrCreateMediaSession(!0,e)}async initialize(){let e=performance.now(),t=J0();try{this._parsedTokenCredential=await P4(this._tokenCredential,Z().calling.eudb.isRgnClaimEnabledForACS);let n={clientId:this._clientId,acsResourceId:this._parsedTokenCredential.acsResourceId,identityMri:this._parsedTokenCredential.identityMri,cloudType:this._parsedTokenCredential.cloudType,identityType:this._parsedTokenCredential.isEnterpriseUser?t2.Enterprise:t2.Consumer,region:this._parsedTokenCredential.region,IsUserEmergencyCountryCode:!1,mriType:this._parsedTokenCredential.mriType};this._tsWbStack=await this._callStack.initializeMediaSdkStackForUser(this.tokenProvider,n),this._telemetryLogManager.initialize(n),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MediaSessionAgentInit`,durationInMs:performance.now()-e,operationPayload:{serviceOrigin:this._options?.serviceOrigin??``},resultCategories:[`Success`],resultSignature:200})}catch(n){let r=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:n});throw this._logger.error(`MediaClient: Error initializing CallStack: ${r}`),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:t,operationName:`MediaSessionAgentInit`,durationInMs:performance.now()-e,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500}),r}}_getSessionKey(e){return e&&e.sessionId?e.sessionId:`default`}getSession(e){let t=this._getSessionKey(e);return this._sessionMap.get(t)?.session}removeSession(e){let t=this._getSessionKey(e),n=this._sessionMap.get(t),r=!!n;return n&&(this._clearTsWbSession(n.tsWbSession,t),r=this._sessionMap.delete(t),this._logger.debug(`MediaSessionAgentImpl: Removed session for key: ${t}, remaining sessions: ${this._sessionMap.size}`)),r}get sessions(){return Array.from(this._sessionMap.values()).map((e=>e.session))}_clearAllSessions(){this._sessionMap.clear(),this._logger.debug(`MediaSessionAgentImpl: Cleared all sessions from map`)}_clearTsWbSession(e,t){if(e)try{e.dispose(),this._tsWbStack.mediaAgent.disposeSession(t),this._logger.debug(`MediaSessionAgentImpl: Disposed tsWbSession after last session removed`)}catch(e){this._logger.error(`MediaSessionAgentImpl: Error disposing tsWbSession: ${e}`)}}_disconnectAllSessions(e){if(this._sessionMap.size===0)return;let t=Array.from(this._sessionMap.values());for(let n of t)try{n.session.disconnectFromUnload(e)}catch(e){this._logger.error(`MediaSessionAgent: Error disconnecting session: ${e}`)}}dispose(){this._logger.debug(`MediaSessionAgentImpl: Disposing agent and all sessions`),this._disconnectAllSessions(`dispose`),this._tsWbStack.dispose(),this._telemetryLogManager.clearTelemetryLoggers(),this._clearAllSessions(),Y9.instance.dispose()}},sze=function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},cze=function(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)},lze=1,uze=class{get initializedDeviceManager(){return this._initializedDeviceManager}on(e,t){this._eventEmitter.on(e,t)}off(e,t){this._eventEmitter.off(e,t)}constructor(e){this._initializedDeviceManager=!1,qSe(u2.MediaStreaming);let t=performance.now();this._clientId=J0();let n=lze++,r=e?.logger||ZW(`ACS-calling`);this.logger=new V6(r,[()=>`MediaClient${n}[${this._clientId}]`]),this._mediaSdkDiagnosticInformation=tTe(Z2(),this.logger,e),this._clientTypeInfo={name:sue,version:Z2(),details:this._mediaSdkDiagnosticInformation},this._eventEmitter=new w6(this.logger),this._telemetryLogManager=new m3(this.logger,this._mediaSdkDiagnosticInformation);try{this._callStack=new M9(this.logger,this._clientId,this._telemetryLogManager,this._mediaSdkDiagnosticInformation,new WRe,new GRe,void 0,void 0,!1),this._deviceManager=new F9(this.logger,this._callStack,this._telemetryLogManager,!0,e?.enumerateDevices??!1),this._extensibleApi=new F3(this.logger,{mediaClient:this},{mediaClient:this,telemetryLogManager:this._telemetryLogManager,callStack:this._callStack}),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`MediaClientInit`,durationInMs:performance.now()-t,operationPayload:{},resultCategories:[`Success`],resultSignature:200})}catch(e){let n=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:e});throw this.logger.error(`MediaClient: Error initializing CallStack: ${n}`),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`MediaClientInit`,durationInMs:performance.now()-t,operationPayload:{...J3(n).communicationServicesError},resultCategories:n.resultCategories,resultSignature:500}),n}}feature(e){return this._extensibleApi.getApiObjectInstance(e.mediaClientApiCtor)}async createSessionAgent(e,t){let n=new oze(this.logger,this._telemetryLogManager,this._clientId,e,this._callStack,this._deviceManager,this._clientTypeInfo,t);return await n.initialize(),n}async getDeviceManager(){return await this._deviceManager.getDeviceManager(),this._initializedDeviceManager=!0,this._eventEmitter.emit(`initializedDeviceManager`),this._deviceManager}getSdkVersion(){return Z2()}async checkDevicePermissions(e){let t=new Map,n=performance.now();e.forEach((e=>{t.set(e,AG.Prompt)}));try{if(!navigator.permissions||typeof navigator.permissions.query!=`function`){let e={};return t.forEach(((t,n)=>{e[n]=t})),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`DevicePermissionAccess`,durationInMs:performance.now()-n,operationPayload:e,resultCategories:[`Success`],resultSignature:200}),t}for(let n of e)try{let e=await navigator.permissions.query({name:n});t.set(n,e.state)}catch(e){this.logger.warn(`Failed to query ${n} permission: ${e}`),t.set(n,AG.Prompt)}let r={};return t.forEach(((e,t)=>{r[t]=e})),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`DevicePermissionAccess`,durationInMs:performance.now()-n,operationPayload:r,resultCategories:[`Success`],resultSignature:200}),t}catch(e){let r=new Y({defaultError:J.WB_MEDIA_SDK.CLIENT.INIT,originalError:e});return this.logger.error(`MediaClient::checkDevicePermissions, error checking device permissions ${r}`),this._telemetryLogManager.sendWbSessionEvent({eventName:Q.acs_wb_session_events,operationId:this._clientId,operationName:`DevicePermissionAccess`,durationInMs:performance.now()-n,operationPayload:{...J3(r).communicationServicesError},resultCategories:r.resultCategories,resultSignature:500}),t}}};sze([UG,cze(`design:type`,Object)],uze.prototype,`logger`,void 0);var dze={class:`video-call-template`},fze={key:0,class:`card`},pze={key:0,class:`permissions-denied__audio`},mze={class:`permissions-denied__audio-disabled`},hze={key:1,class:`permissions-denied__video`},gze={class:`permissions-denied__video-disabled`},_ze={key:1,class:`card`},vze={class:`incoming__settings`},yze={class:`side`},bze={class:`outgoing`},xze={class:`card`},Sze={key:0,class:`outgoing__video`},Cze={class:`outgoing__available-cameras-count text-center`},wze={key:3,class:`permissions-denied__video`},Tze={class:`permissions-denied__video-disabled`},Eze={class:`settings`},Dze={class:`settings__help`},Oze=[`href`],kze={href:`https://www.beterdichtbij.nl/service-contact/`,target:`blank`,rel:`noopener noreferrer`},Aze=`hangedUp`,Z9=`declined`,jze=`connected`,Q9=`loading`,$9=`devicePermissionDenied`,Mze=2e3,Nze={__name:`BDVideoCallTemplate`,props:{messageWhenLoading:String,participant:{type:Object,default:null},isCallee:{type:Boolean,default:!1},videoTestUrl:{type:String,default:``}},emits:[`ready`,`end-video-call`],setup(e,{expose:n,emit:r}){let i=e,a=r,{tm:o}=zu(),s=(0,t.ref)([]),c=navigator.userAgent.indexOf(`Firefox`)>-1,l=(0,t.computed)(()=>o(`template.videoCall`)),u=(0,t.ref)(!1),d=(0,t.ref)(!1),f=(0,t.ref)(!1),g=(0,t.ref)(2),_=(0,t.ref)({}),v=(0,t.ref)(Q9),y=(0,t.ref)(null),b=(0,t.reactive)({client:null,agent:null,deviceManager:null,incomingCall:null,call:null}),x=(0,t.ref)(null),S=(0,t.ref)(null),C=(0,t.ref)(null),w=(0,t.ref)(null),T=(0,t.ref)(0),E=(0,t.ref)(0),ee=(0,t.ref)(null),D=(0,t.computed)(()=>{switch(T.value){case 0:return l.value.hasNoAvailableCamera;case 1:return l.value.hasOneAvailableCamera;default:return l.value.hasMultipleAvailableCameras}}),O=(0,t.computed)(()=>{let e=navigator.userAgent;return/Mobi/.test(e)&&!u.value}),k=(0,t.computed)(()=>{let e=navigator.userAgent,t=e.indexOf(`Android`)!==-1,n=/Mobi/.test(e),r=/iPad|iPhone|iPod/.test(e)&&!window.MSStream;return!(t&&n||r)}),A=(0,t.computed)(()=>!_.value?.video&&ue.value),j=(0,t.computed)(()=>!_.value?.audio&&ue.value),te=(0,t.computed)(()=>v.value===Z9?`incoming--declined`:`incoming--loading`),ne=(0,t.computed)(()=>{switch(g.value){case 0:return`weak`;case 1:return`steady`;case 2:return`strong`;default:return null}}),re=(0,t.computed)(()=>{switch(g.value){case 0:return l.value.signalStrength.weak;case 1:return l.value.signalStrength.steady;case 2:return l.value.signalStrength.strong;default:return null}}),ie=(0,t.computed)(()=>u.value?l.value.stopSharingScreen:l.value.shareScreen),ae=(0,t.computed)(()=>l.value.placeholderSettingsHelpTitle),M=(0,t.computed)(()=>l.value.placeholderSettingsHelpMessage),oe=(0,t.computed)(()=>v.value===Z9),se=(0,t.computed)(()=>v.value===Aze),ce=(0,t.computed)(()=>v.value===jze),le=(0,t.computed)(()=>!ce.value),ue=(0,t.computed)(()=>v.value===$9),de=(0,t.computed)(()=>se.value?l.value.messageWhenVideoCallHangedUp:oe.value?l.value.messageWhenVideoCallDeclined:ue.value?l.value.messageWhenDevicePermissionDenied:i.messageWhenLoading),fe=(0,t.computed)(()=>f.value?`.incoming__screenshare`:`.incoming__video`);(0,t.onMounted)(()=>{je()});function N(){v.value=Z9}function pe(){}function me(){v.value!==$9&&ve()}async function he(){v.value=Aze,_.value.video&&ke()}async function ge(e){b.client=(0,t.markRaw)(new G9);let n=new Jle(e);b.agent=(0,t.markRaw)(await b.client.createCallAgent(n)),b.deviceManager=await b.client.getDeviceManager(),_.value=await b.deviceManager.askDevicePermission({video:!0,audio:!0}),ee.value=window.setInterval(ke,5e3),(!_.value.audio||!_.value.video)&&(v.value=$9),i.isCallee&&(b.agent.on(`incomingCall`,_e),a(`ready`))}async function _e(e){try{b.incomingCall=e.incomingCall,F()}catch{console.log(`error occured during starting call`)}}async function P(){let e=await ye();return e?{localVideoStreams:[e]}:void 0}async function ve(){try{let e=await P(),t={communicationUserId:i.participant.videoCallIdentityId};b.call=b.agent.startCall([t],{videoOptions:e}),I(),be()}catch(e){console.error(e)}}async function F(){let e=await P();b.call=await b.incomingCall.accept({videoOptions:e}),I(),be()}async function ye(){let e=(await b.deviceManager.getCameras())[0];if(e)return new X6(e);console.error(`No camera device found on the system`)}function be(){b.call.on(`stateChanged`,xe),b.call.on(`localVideoStreamsUpdated`,e=>{e.added.forEach(z),e.removed.forEach(R)}),b.call.remoteParticipants.forEach(Ce),b.call.on(`remoteParticipantsUpdated`,e=>{e.added.forEach(Ce)}),b.call.on(`isScreenSharingOnChanged`,()=>{u.value=b.call.isScreenSharingOn})}function I(){y.value=b.call.feature($5.UserFacingDiagnostics),y.value.media.on(`diagnosticChanged`,L),y.value.network.on(`diagnosticChanged`,L)}function L(e){(e.diagnostic===`networkReceiveQuality`||e.diagnostic===`networkSendQuality`)&&(e.value===n6.Bad?(console.error(`${e.diagnostic} is bad quality`),g.value=0):e.value===n6.Poor?(console.error(`${e.diagnostic} is poor quality`),g.value=1):g.value=2)}function xe(){switch(console.log(`Call state changed to: `+b.call.state),b.call.state){case`EarlyMedia`:v.value=Q9;break;case`Ringing`:v.value=Q9;break;case`Connected`:v.value=jze;break;case`Disconnected`:he();break}}async function R(e){if(!e||e.mediaStreamType!==`ScreenSharing`||!w.value)return;w.value.dispose();let t=document.querySelector(`.outgoing__screenshare`);t.style.display=`none`;let n=document.querySelector(`.outgoing__video`);n.style.display=`flex`}async function z(e){if(!e||e.mediaStreamType!==`ScreenSharing`)return;w.value=await new A7(e).createView();let t=document.querySelector(`.outgoing__screenshare`);t.replaceChildren(w.value.target),t.style.display=`flex`;let n=document.querySelector(`.outgoing__video`);n.style.display=`none`;let r=t.querySelector(`video`);r.style.objectFit=`contain`}async function Se(e){if(e&&e.source&&x.value&&x.value.source&&x.value.source.id==e.source.id)return!0;try{S.value=new A7(e);let t=await S.value.createView(),n=document.querySelector(`.outgoing__video`);n.querySelector(`video`)&&(n.innerHTML=``),n.hidden=!1,n.replaceChildren(t.target)}catch{return!1}return x.value=e,!0}async function Ce(e){e.videoStreams.forEach(we),e.on(`videoStreamsUpdated`,e=>{e.added.forEach(we)})}async function we(e){if(e.mediaStreamType===`Video`&&(await Te(e),e.on(`isAvailableChanged`,async()=>await Te(e))),e.mediaStreamType===`ScreenSharing`&&e.on(`isAvailableChanged`,De),e.mediaStreamType===`ScreenSharing`&&e.isAvailable){C.value=new A7(e);let t=await C.value.createView(),n=document.querySelector(`.incoming__screenshare`);Ee(!0),f.value=!0,Ae(`.incoming__screenshare`),n.replaceChildren(t.target)}}async function Te(e){if(!e.isAvailable)return;C.value=new A7(e);let t=await C.value.createView(),n=document.querySelector(`.incoming__video`);n.hidden=!1,n.replaceChildren(t.target),Ae(`.incoming__video`),Ee(!1)}function Ee(e){let t=document.querySelector(`.incoming__video`),n=document.querySelector(`.incoming__screenshare`);t.style.display=e?`none`:`block`,n.style.display=e?`flex`:`none`}function De(){f.value=!1,Ee(!1)}async function Oe(){ke(!0)}async function ke(e=!1){let t=(await b.deviceManager.getCameras()).filter(e=>e.name!=`OBS Virtual Camera`);T.value=t.length;for(let n=0;n<T.value;n++){(e||n!=0)&&(E.value=(E.value+1)%T.value);let r=t[E.value];if(await Se(new X6(r)))break}}function Ae(e){let t=document.querySelector(e);if(!t)return;let n=t.querySelector(`video`);n&&(n.style.objectFit=`contain`,n.disablePictureInPicture=!1)}async function B(){b.call&&b.call.state!==`Disconnected`&&(await b.call.hangUp({forEveryone:!0}),await b.agent.dispose()),a(`end-video-call`),window.close()}function V(){window.close()}function je(){Sae(`verbose`),XW.log=(...e)=>{let t=[...e];s.value=s.value.splice(1-Mze).concat(t)}}function Me(){document.querySelector(fe.value).querySelector(`video`).requestFullscreen()}function Ne(){let e=document.querySelector(fe.value).querySelector(`video`);document.pictureInPictureElement?e.exitPictureInPicture():document.pictureInPictureEnabled&&e.requestPictureInPicture()}async function Pe(){b.call&&b.call.isScreenSharingOn?await b.call.stopScreenSharing():await b.call.startScreenSharing()}return n({CallDeclined:N,CallAnswered:pe,CallStartVideoCall:me,CallHangUp:he,InitializeAcsConnection:ge}),(n,r)=>{let a=(0,t.resolveComponent)(`BDLoader`);return(0,t.openBlock)(),(0,t.createElementBlock)(`div`,dze,[(0,t.createVNode)(m,null,{default:(0,t.withCtx)(()=>[(0,t.createVNode)(h,null,{default:(0,t.withCtx)(()=>[(0,t.createVNode)(p,null,{default:(0,t.withCtx)(()=>[(0,t.createVNode)(tU,{smallState:!0,contactInfo:e.participant.contact},null,8,[`contactInfo`])]),_:1})]),_:1}),(0,t.createVNode)(h,null,{default:(0,t.withCtx)(()=>[(0,t.createVNode)(p,{sm:`12`,lg:oe.value?`12`:`8`},{default:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`div`,{class:(0,t.normalizeClass)([`incoming`,te.value])},[le.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,fze,[(0,t.createVNode)(a,{size:`lg`,message:de.value,stopAnimation:oe.value||se.value||ue.value},null,8,[`message`,`stopAnimation`]),j.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,pze,[(0,t.createElementVNode)(`div`,mze,[(0,t.createVNode)(jr,{class:`icon-xl icon-state-error`})]),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(l.value.permissionDeniedForAudio),1)])):(0,t.createCommentVNode)(``,!0),A.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,hze,[(0,t.createElementVNode)(`div`,gze,[(0,t.createVNode)(Zi,{class:`icon-xl icon-state-error`})]),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(l.value.permissionDeniedForVideo),1)])):(0,t.createCommentVNode)(``,!0),oe.value||se.value||ue.value?((0,t.openBlock)(),(0,t.createBlock)(_a,{key:2,variant:`primary`,class:`text-center`,onClick:V},{default:(0,t.withCtx)(()=>[(0,t.createTextVNode)((0,t.toDisplayString)(l.value.closeWindow),1)]),_:1})):(0,t.createCommentVNode)(``,!0)])):((0,t.openBlock)(),(0,t.createElementBlock)(`div`,_ze,[r[0]||=(0,t.createElementVNode)(`div`,{class:`incoming__video`},null,-1),r[1]||=(0,t.createElementVNode)(`div`,{class:`incoming__screenshare`},null,-1),(0,t.createElementVNode)(`div`,vze,[(0,t.createVNode)(_a,{variant:`primary`,class:`text-center`,onClick:Me},{default:(0,t.withCtx)(()=>[(0,t.createVNode)(pi),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(l.value.fullScreen),1)]),_:1}),!c&&!d.value?((0,t.openBlock)(),(0,t.createBlock)(_a,{key:0,variant:`primary`,class:`text-center`,onClick:Ne},{default:(0,t.withCtx)(()=>[(0,t.createVNode)(pi),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(l.value.miniPlayer),1)]),_:1})):(0,t.createCommentVNode)(``,!0)])]))],2)]),_:1},8,[`lg`]),oe.value?(0,t.createCommentVNode)(``,!0):((0,t.openBlock)(),(0,t.createBlock)(p,{key:0,sm:`12`,lg:`4`},{default:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`div`,yze,[(0,t.createElementVNode)(`div`,null,[(0,t.createElementVNode)(`div`,bze,[(0,t.createElementVNode)(`div`,xze,[ue.value?(0,t.createCommentVNode)(``,!0):((0,t.openBlock)(),(0,t.createElementBlock)(`div`,Sze)),r[2]||=(0,t.createElementVNode)(`div`,{class:`outgoing__screenshare`},null,-1),k.value&&!ue.value&&!d.value&&!le.value?((0,t.openBlock)(),(0,t.createBlock)(_a,{key:1,variant:u.value?`danger`:`primary`,class:`text-center`,onClick:Pe},{default:(0,t.withCtx)(()=>[(0,t.createVNode)(pi),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(ie.value),1)]),_:1},8,[`variant`])):(0,t.createCommentVNode)(``,!0),O.value?((0,t.openBlock)(),(0,t.createElementBlock)(t.Fragment,{key:2},[(0,t.createVNode)(_a,{class:`text-center`,onClick:Oe},{default:(0,t.withCtx)(()=>[(0,t.createTextVNode)((0,t.toDisplayString)(l.value.switchCamera),1)]),_:1}),(0,t.createElementVNode)(`p`,Cze,(0,t.toDisplayString)(D.value),1)],64)):(0,t.createCommentVNode)(``,!0),A.value?((0,t.openBlock)(),(0,t.createElementBlock)(`div`,wze,[(0,t.createElementVNode)(`div`,Tze,[(0,t.createVNode)(Zi,{class:`icon-xxl icon-state-error`})]),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(l.value.permissionDeniedForVideo),1)])):(0,t.createCommentVNode)(``,!0)])]),(0,t.createElementVNode)(`div`,Eze,[(0,t.createElementVNode)(`div`,{class:(0,t.normalizeClass)([`settings__signal`,ne.value])},[r[3]||=(0,t.createElementVNode)(`ul`,{class:`indicator`},[(0,t.createElementVNode)(`li`),(0,t.createElementVNode)(`li`),(0,t.createElementVNode)(`li`)],-1),(0,t.createElementVNode)(`p`,null,(0,t.toDisplayString)(re.value),1)],2),(0,t.createElementVNode)(`div`,Dze,[(0,t.createElementVNode)(`p`,null,[(0,t.createElementVNode)(`b`,null,(0,t.toDisplayString)(ae.value),1)]),(0,t.createElementVNode)(`p`,null,(0,t.toDisplayString)(M.value),1),(0,t.createElementVNode)(`p`,null,[(0,t.createElementVNode)(`a`,{href:i.videoTestUrl,target:`blank`,rel:`noopener noreferrer`},(0,t.toDisplayString)(l.value.testCall),9,Oze),r[4]||=(0,t.createTextVNode)(` • `,-1),(0,t.createElementVNode)(`a`,kze,(0,t.toDisplayString)(l.value.serviceDesk),1)])])])]),!se.value&&!ue.value?((0,t.openBlock)(),(0,t.createBlock)(_a,{key:0,variant:`danger`,class:`text-center w-100`,onClick:B},{default:(0,t.withCtx)(()=>[(0,t.createVNode)(Mt),(0,t.createElementVNode)(`span`,null,(0,t.toDisplayString)(l.value.endCall),1)]),_:1})):(0,t.createCommentVNode)(``,!0)])]),_:1}))]),_:1})]),_:1})])}}},Pze={class:`template not-found-template`},Fze={class:`center-screen`},Ize={class:`container-warning`},Lze=[`textContent`],Rze=[`textContent`],zze=(0,t.defineComponent)({__name:`BDNotFoundTemplate`,props:{buttonText:{type:String}},emits:[`navigate`],setup(e,{emit:n}){let{t:r}=zu(),i=e,a=n,o=(0,t.computed)(()=>i.buttonText||r(`notFoundTemplate.buttonDefault`)),s=(0,t.computed)(()=>r(`notFoundTemplate.title`)),c=(0,t.computed)(()=>r(`notFoundTemplate.description`)),l=()=>a(`navigate`);return(e,n)=>((0,t.openBlock)(),(0,t.createElementBlock)(`main`,Pze,[(0,t.createVNode)(m,{class:`container-xl`},{default:(0,t.withCtx)(()=>[(0,t.createElementVNode)(`div`,Fze,[(0,t.createElementVNode)(`div`,Ize,[(0,t.createVNode)(Bi),(0,t.createElementVNode)(`h5`,{textContent:(0,t.toDisplayString)(s.value)},null,8,Lze),(0,t.createElementVNode)(`p`,{textContent:(0,t.toDisplayString)(c.value)},null,8,Rze),(0,t.createVNode)(_a,{onClick:l,variant:`primary`,type:`button`,textContent:(0,t.toDisplayString)(o.value)},null,8,[`textContent`])])])]),_:1})]))}});e.BDAlert=ca,e.BDArticle=da,e.BDAssignConversationModal=UU,e.BDAttachmentPreviewList=P_,e.BDAttachmentUploadModal=WU,e.BDBadge=ma,e.BDButton=_a,e.BDCard=Ea,e.BDChangePasswordTemplate=AW,e.BDChatCloud=iv,e.BDCol=p,e.BDCollapsableCard=Aa,e.BDConfirmationModal=GU,e.BDContainer=m,e.BDContentLibraryModal=Aie,e.BDContentLibrarySplitButton=Oh,e.BDContentLibraryTemplate=bW,e.BDConversationToTextModal=wW,e.BDDate=qh,e.BDDropdown=vU,e.BDDropdownItem=av,e.BDFileUpload=uO,e.BDForm=Jh,e.BDFormCheckbox=fg,e.BDFormInput=Pg,e.BDFormInvalidFeedback=mg,e.BDFormMultipleCheckbox=mO,e.BDFormSelect=zg,e.BDHeader=wU,e.BDImageAttachmentModal=EW,e.BDImageAttachmentPreviewList=U_,e.BDInputGroup=Hg,e.BDLink=ga,e.BDLoader=Xg,e.BDLogo=$g,e.BDMarkdownEditor=JH,e.BDMessageTemplateFormModal=DW,e.BDMobileMenu=ZH,e.BDModal=DU,e.BDNotFoundTemplate=zze,e.BDPagination=o_,e.BDPhoneNumberEditModal=NU,e.BDPill=p_,e.BDPractitionerHeader=BU,e.BDProfileImage=g_,e.BDRow=h,e.BDSessionTimeOutModal=HU,e.BDSmallConversationCard=tU,e.BDTable=aU,e.BDToast=x_,e.BDUser=lU,e.BDUserInformation=E_,e.BDVideoCallConfirmationModal=OW,e.BDVideoCallTemplate=Nze,e.BDVideoCallToast=_U,e.BDZoomslider=k_,e.CopyChatMessageToClipboard=zie,e.CopyChatMessagesToClipboard=CW,e.CopyHl7MessagesToClipboard=Bie,e.CreateHyperlinkParagraph=(e,t)=>`<p><a href="${e}" title="${t}" target="_blank" rel="noopener noreferrer">${t}</a></p>`,e.CreateThumbnailUri=q_,e.IconAcademy=b,e.IconArrowDown=w,e.IconArrowUp=D,e.IconAttachment=j,e.IconBold=ie,e.IconBulletList=se,e.IconCalendar=de,e.IconCall=me,e.IconCallReject=P,e.IconCardView=be,e.IconCaretDown=R,e.IconCaretLeft=we,e.IconCaretRight=Oe,e.IconCheck=V,e.IconClipboard=Pe,e.IconClose=Re,e.IconComment=He,e.IconCommentActive=Ke,e.IconCommentStatic=Xe,e.IconCommonFileEmpty=et,e.IconCommonFileWarning=it,e.IconContactPerson=ct,e.IconCopy=ft,e.IconDelete=gt,e.IconDoubleCheck=bt,e.IconDownloadImage=wt,e.IconEdit=Ot,e.IconEndCall=Mt,e.IconError=It,e.IconExternal=Bt,e.IconEyeShow=Wt,e.IconEyeSlash=Jt,e.IconFile=Qt,e.IconFileAdded=nn,e.IconForward=sn,e.IconHix=dn,e.IconHyperlink=hn,e.IconImageFileLandscape=yn,e.IconImageFileWarning=Cn,e.IconInbox=Dn,e.IconInfo=An,e.IconInformationCircle=Pn,e.IconItalic=Rn,e.IconListView=Hn,e.IconLock=Kn,e.IconLusciiEscalated=Xn,e.IconLusciiLogo=er,e.IconLusciiOpen=ir,e.IconLusciiPriorityHigh=cr,e.IconLusciiPriorityLow=fr,e.IconLusciiPriorityMedium=gr,e.IconMenu=br,e.IconMessage=wr,e.IconMessageForward=Or,e.IconMicrophoneSlash=jr,e.IconMicrosoftTeams=U,e.IconMin=Rr,e.IconOrderedList=Hr,e.IconPlus=Kr,e.IconRefresh=Xr,e.IconRemove=ei,e.IconSananetLogo=ai,e.IconService=li,e.IconShareScreen=pi,e.IconSingleNeutral=gi,e.IconSort=bi,e.IconSortAsc=wi,e.IconSortDesc=Oi,e.IconSortNone=Mi,e.IconTriangleDown=Ii,e.IconTriangleExclamation=Bi,e.IconUnderline=Wi,e.IconVideoDisabled=Zi,e.IconVideocall=Ji,e.IconWarning=ta,e.IconZorgkaart=aa,e.MapAttachmentsForApi=W_,e.MapToAttachmentObjects=X_,e.TransformHyperlinks=e=>{let t=/<a\b[^>]*>.*?<\/a>/gi,n=[],r;for(;(r=t.exec(e))!==null;)n.push({start:r.index,end:r.index+r[0].length});return e.replace(/(https?:\/\/[^\s<>"',]+|www\.[^\s<>"',]+)/g,(e,t,r)=>n.some(e=>r>=e.start&&r<e.end)?e:`<a href="${e.startsWith(`www.`)?`http://${e}`:e}" target="_blank" rel="noopener noreferrer">${e}</a>`)},e.ValidateUrl=e=>e.startsWith(`http://`)||e.startsWith(`https://`),e.default={install:e=>{e.component(`BDAlert`,ca),e.component(`BDArticle`,da),e.component(`BDAssignConversationModal`,UU),e.component(`BDAttachmentPreviewList`,P_),e.component(`BDAttachmentUploadModal`,WU),e.component(`BDBadge`,ma),e.component(`BDButton`,_a),e.component(`BDCard`,Ea),e.component(`BDChangePasswordTemplate`,AW),e.component(`BDChatCloud`,iv),e.component(`BDCol`,p),e.component(`BDCollapsableCard`,Aa),e.component(`BDConfirmationModal`,GU),e.component(`BDContainer`,m),e.component(`BDContentLibraryModal`,Aie),e.component(`BDContentLibrarySplitButton`,Oh),e.component(`BDContentLibraryTemplate`,bW),e.component(`BDConversationToTextModal`,wW),e.component(`BDDate`,qh),e.component(`BDDropdown`,vU),e.component(`BDDropdownItem`,av),e.component(`BDFileUpload`,uO),e.component(`BDForm`,Jh),e.component(`BDFormCheckbox`,fg),e.component(`BDFormInput`,Pg),e.component(`BDFormInvalidFeedback`,mg),e.component(`BDFormMultipleCheckbox`,mO),e.component(`BDFormSelect`,zg),e.component(`BDHeader`,wU),e.component(`BDImageAttachmentModal`,EW),e.component(`BDImageAttachmentPreviewList`,U_),e.component(`BDInputGroup`,Hg),e.component(`BDLink`,ga),e.component(`BDLoader`,Xg),e.component(`BDLogo`,$g),e.component(`BDMarkdownEditor`,JH),e.component(`BDMessageTemplateFormModal`,DW),e.component(`BDMobileMenu`,ZH),e.component(`BDModal`,DU),e.component(`BDNotFoundTemplate`,zze),e.component(`BDPagination`,o_),e.component(`BDPhoneNumberEditModal`,NU),e.component(`BDPill`,p_),e.component(`BDPractitionerHeader`,BU),e.component(`BDProfileImage`,g_),e.component(`BDRow`,h),e.component(`BDSessionTimeOutModal`,HU),e.component(`BDSmallConversationCard`,tU),e.component(`BDTable`,aU),e.component(`BDToast`,x_),e.component(`BDUser`,lU),e.component(`BDUserInformation`,E_),e.component(`BDVideoCallConfirmationModal`,OW),e.component(`BDVideoCallTemplate`,Nze),e.component(`BDVideoCallToast`,_U),e.component(`BDZoomslider`,k_),e.component(`IconAcademy`,b),e.component(`IconArrowDown`,w),e.component(`IconArrowUp`,D),e.component(`IconAttachment`,j),e.component(`IconBold`,ie),e.component(`IconBulletList`,se),e.component(`IconCalendar`,de),e.component(`IconCall`,me),e.component(`IconCallReject`,P),e.component(`IconCardView`,be),e.component(`IconCaretDown`,R),e.component(`IconCaretLeft`,we),e.component(`IconCaretRight`,Oe),e.component(`IconCheck`,V),e.component(`IconClipboard`,Pe),e.component(`IconClose`,Re),e.component(`IconComment`,He),e.component(`IconCommentActive`,Ke),e.component(`IconCommentStatic`,Xe),e.component(`IconCommonFileEmpty`,et),e.component(`IconCommonFileWarning`,it),e.component(`IconContactPerson`,ct),e.component(`IconCopy`,ft),e.component(`IconDelete`,gt),e.component(`IconDoubleCheck`,bt),e.component(`IconDownloadImage`,wt),e.component(`IconEdit`,Ot),e.component(`IconEndCall`,Mt),e.component(`IconError`,It),e.component(`IconExternal`,Bt),e.component(`IconEyeShow`,Wt),e.component(`IconEyeSlash`,Jt),e.component(`IconFile`,Qt),e.component(`IconFileAdded`,nn),e.component(`IconForward`,sn),e.component(`IconHix`,dn),e.component(`IconHyperlink`,hn),e.component(`IconImageFileLandscape`,yn),e.component(`IconImageFileWarning`,Cn),e.component(`IconInbox`,Dn),e.component(`IconInfo`,An),e.component(`IconInformationCircle`,Pn),e.component(`IconItalic`,Rn),e.component(`IconListView`,Hn),e.component(`IconLock`,Kn),e.component(`IconLusciiEscalated`,Xn),e.component(`IconLusciiLogo`,er),e.component(`IconLusciiOpen`,ir),e.component(`IconLusciiPriorityHigh`,cr),e.component(`IconLusciiPriorityLow`,fr),e.component(`IconLusciiPriorityMedium`,gr),e.component(`IconMenu`,br),e.component(`IconMessage`,wr),e.component(`IconMessageForward`,Or),e.component(`IconMicrophoneSlash`,jr),e.component(`IconMicrosoftTeams`,U),e.component(`IconMin`,Rr),e.component(`IconOrderedList`,Hr),e.component(`IconPlus`,Kr),e.component(`IconRefresh`,Xr),e.component(`IconRemove`,ei),e.component(`IconSananetLogo`,ai),e.component(`IconService`,li),e.component(`IconShareScreen`,pi),e.component(`IconSingleNeutral`,gi),e.component(`IconSort`,bi),e.component(`IconSortAsc`,wi),e.component(`IconSortDesc`,Oi),e.component(`IconSortNone`,Mi),e.component(`IconTriangleDown`,Ii),e.component(`IconTriangleExclamation`,Bi),e.component(`IconUnderline`,Wi),e.component(`IconVideoDisabled`,Zi),e.component(`IconVideocall`,Ji),e.component(`IconWarning`,ta),e.component(`IconZorgkaart`,aa),e.directive(`bd-tooltip`,WH)}},e.getDisplayDateNumeric=Gh,e.getDisplayDateTextual=Hh,e.getDisplayDateTimeNumeric=Wh,e.getDisplayDateTimeTextual=Uh,e.useModal=OU,e.usePopover=LU,e.useServerErrors=AU,e.useSessionTimeOut=VU,e.useToaster=oO,e.useValidation=kW,e.useWindow=FU,e.useZoom=TW,e.vBdTooltip=WH});
|