sip-connector 28.10.7 → 28.10.8

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.
@@ -0,0 +1 @@
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`events-constructor`),u=require(`debug`);u=c(u,1);let d=require(`@krivega/timeout-requester`),f=require(`@krivega/cancelable-promise`),p=require(`xstate`),m=require(`repeated-calls`),h=require(`stack-promises`),g=require(`@krivega/jssip`),ee=require(`webrtc-mock`),te=require(`ua-parser-js`),ne=require(`sequent-promises`),re=require(`lodash`);re=c(re,1);var ie=`sip-connector`,ae=(0,u.default)(ie),oe=()=>{u.default.enable(`${ie}:*`)},se=()=>{u.default.enable(`-${ie}:*`)},_=e=>ae.extend(e),ce=`Error decline with 603`,le=1006,ue=e=>typeof e==`object`&&!!e&&`code`in e&&e.code===le,de=e=>e.message===ce,fe=function(e){return e.SPECTATOR=`SPECTATOR`,e.PARTICIPANT=`PARTICIPANT`,e}({}),v=function(e){return e.SHARE_STATE=`application/vinteo.webrtc.sharedesktop`,e.MAIN_CAM=`application/vinteo.webrtc.maincam`,e.ENTER_ROOM=`application/vinteo.webrtc.roomname`,e.MIC=`application/vinteo.webrtc.mic`,e.USE_LICENSE=`application/vinteo.webrtc.uselic`,e.PARTICIPANT_STATE=`application/vinteo.webrtc.partstate`,e.NOTIFY=`application/vinteo.webrtc.notify`,e}({}),pe=function(e){return e.SHARE_STATE=`application/vinteo.webrtc.sharedesktop`,e.MAIN_CAM=`application/vinteo.webrtc.maincam`,e.CHANNELS=`application/vinteo.webrtc.channels`,e.MEDIA_STATE=`application/vinteo.webrtc.mediastate`,e.REFUSAL=`application/vinteo.webrtc.refusal`,e.STATS=`application/vinteo.webrtc.stats`,e}({}),y=function(e){return e.PAUSE_MAIN_CAM=`PAUSEMAINCAM`,e.RESUME_MAIN_CAM=`RESUMEMAINCAM`,e.MAX_MAIN_CAM_RESOLUTION=`MAXMAINCAMRESOLUTION`,e.ADMIN_STOP_MAIN_CAM=`ADMINSTOPMAINCAM`,e.ADMIN_START_MAIN_CAM=`ADMINSTARTMAINCAM`,e}({}),me=function(e){return e.ADMIN_STOP_MIC=`ADMINSTOPMIC`,e.ADMIN_START_MIC=`ADMINSTARTMIC`,e}({}),he=function(e){return e.H264=`H264`,e.VP8=`VP8`,e.VP9=`VP9`,e.AV1=`AV1`,e}({}),b=function(e){return e.CONTENT_TYPE=`content-type`,e.CONTENT_ENTER_ROOM=`x-webrtc-enter-room`,e.CONTENT_USE_LICENSE=`x-webrtc-use-license`,e.PARTICIPANT_NAME=`x-webrtc-participant-name`,e.INPUT_CHANNELS=`x-webrtc-input-channels`,e.OUTPUT_CHANNELS=`x-webrtc-output-channels`,e.MAIN_CAM=`x-webrtc-maincam`,e.MIC=`x-webrtc-mic`,e.MEDIA_SYNC=`x-webrtc-sync`,e.MAIN_CAM_RESOLUTION=`x-webrtc-maincam-resolution`,e.MEDIA_STATE=`x-webrtc-media-state`,e.MEDIA_TYPE=`x-vinteo-media-type`,e.MAIN_CAM_STATE=`x-vinteo-maincam-state`,e.MIC_STATE=`x-vinteo-mic-state`,e.CONTENT_PARTICIPANT_STATE=`x-webrtc-partstate`,e.AUDIO_ID=`x-webrtc-audioid`,e.SPECTATOR_MODE=`x-webrtc-spectator-mode`,e.NOTIFY=`x-vinteo-notify`,e.CONTENT_ENABLE_MEDIA_DEVICE=`x-webrtc-request-enable-media-device`,e.CONTENTED_STREAM_STATE=`x-webrtc-share-state`,e.CONTENTED_STREAM_CODEC=`x-webrtc-share-codec`,e.AVAILABLE_INCOMING_BITRATE=`x-webrtc-available-incoming-bitrate`,e.AUDIO_TRACK_COUNT=`x-webrtc-audio-track-count`,e.VIDEO_TRACK_COUNT=`x-webrtc-video-track-count`,e.TRACKS_DIRECTION=`x-webrtc-tracks-direction`,e.BEARER_TOKEN=`x-bearer-token`,e.IS_DIRECT_PEER_TO_PEER=`x-webrtc-is-direct-p2p`,e}({}),ge=function(e){return e.ACK_PERMISSION_TO_START_PRESENTATION=`LETMESTARTPRESENTATION`,e.STOPPED_CLIENT_PRESENTATION=`STOPPRESENTATION`,e}(ge||{}),_e=function(e){return e.AVAILABLE_CONTENTED_STREAM=`YOUCANRECEIVECONTENT`,e.NOT_AVAILABLE_CONTENTED_STREAM=`CONTENTEND`,e.MUST_STOP_PRESENTATION=`YOUMUSTSTOPSENDCONTENT`,e}({}),ve=function(e){return e.AVAILABLE_CONTENTED_STREAM=`${b.CONTENTED_STREAM_STATE}: ${_e.AVAILABLE_CONTENTED_STREAM}`,e.NOT_AVAILABLE_CONTENTED_STREAM=`${b.CONTENTED_STREAM_STATE}: ${_e.NOT_AVAILABLE_CONTENTED_STREAM}`,e.ACK_PERMISSION_TO_START_PRESENTATION=`${b.CONTENTED_STREAM_STATE}: ${ge.ACK_PERMISSION_TO_START_PRESENTATION}`,e.STOPPED_CLIENT_PRESENTATION=`${b.CONTENTED_STREAM_STATE}: ${ge.STOPPED_CLIENT_PRESENTATION}`,e.ENABLE_MAIN_CAM=`${b.CONTENT_ENABLE_MEDIA_DEVICE}: LETMESTARTMAINCAM`,e}({}),ye=function(e){return e.ADMIN_SYNC_FORCED=`1`,e.ADMIN_SYNC_NOT_FORCED=`0`,e}({}),be=function(e){return e.SPECTATOR_MANUAL=`0`,e.BY_STATE_CAM=`1`,e.SPECTATOR_FORCED=`2`,e}({}),xe=function(e){return e.AUDIO=`AUDIO`,e.VIDEO=`VIDEO`,e.AUDIOPLUSPRESENTATION=`AUDIOPLUSPRESENTATION`,e}({}),x=e=>typeof e==`string`&&e.trim().length>0,Se=e=>typeof e==`number`&&!Number.isNaN(e)&&Number.isFinite(e),Ce=e=>typeof e==`object`&&!!e&&!Array.isArray(e),we=e=>typeof e==`boolean`,Te=e=>Array.isArray(e)&&e.every(x),S=function(e){return e.ENTER_ROOM=`enter-room`,e.MAIN_CAM_CONTROL=`main-cam-control`,e.USE_LICENSE=`use-license`,e.NEW_DTMF=`new-dtmf`,e.CONFERENCE_PARTICIPANT_TOKEN_ISSUED=`conference:participant-token-issued`,e.CONTENTED_STREAM_AVAILABLE=`contented-stream:available`,e.CONTENTED_STREAM_NOT_AVAILABLE=`contented-stream:not-available`,e.PRESENTATION_MUST_STOP=`presentation:must-stop`,e.CHANNELS_ALL=`channels:all`,e.CHANNELS_NOTIFY=`channels:notify`,e.PARTICIPANT_ADDED_TO_LIST_MODERATORS=`participant:added-to-list-moderators`,e.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS=`participant:removed-from-list-moderators`,e.PARTICIPANT_MOVE_REQUEST_TO_STREAM=`participant:move-request-to-stream`,e.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS=`participant:move-request-to-spectators`,e.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_SYNTHETIC=`participant:move-request-to-spectators-synthetic`,e.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_WITH_AUDIO_ID=`participant:move-request-to-spectators-with-audio-id`,e.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS=`participant:move-request-to-participants`,e.PARTICIPATION_ACCEPTING_WORD_REQUEST=`participation:accepting-word-request`,e.PARTICIPATION_CANCELLING_WORD_REQUEST=`participation:cancelling-word-request`,e.WEBCAST_STARTED=`webcast:started`,e.WEBCAST_STOPPED=`webcast:stopped`,e.ACCOUNT_CHANGED=`account:changed`,e.ACCOUNT_DELETED=`account:deleted`,e.ADMIN_START_MAIN_CAM=`admin:start-main-cam`,e.ADMIN_STOP_MAIN_CAM=`admin:stop-main-cam`,e.ADMIN_START_MIC=`admin:start-mic`,e.ADMIN_STOP_MIC=`admin:stop-mic`,e.ADMIN_FORCE_SYNC_MEDIA_STATE=`admin:force-sync-media-state`,e.FAILED_SEND_ROOM_DIRECT_P2P=`failed-send-room-direct-p2p`,e}(S||{}),Ee=[`${S.ENTER_ROOM}`,`${S.MAIN_CAM_CONTROL}`,`${S.USE_LICENSE}`,`${S.NEW_DTMF}`,`${S.CONFERENCE_PARTICIPANT_TOKEN_ISSUED}`,`${S.CONTENTED_STREAM_AVAILABLE}`,`${S.CONTENTED_STREAM_NOT_AVAILABLE}`,`${S.PRESENTATION_MUST_STOP}`,`${S.CHANNELS_ALL}`,`${S.CHANNELS_NOTIFY}`,`${S.PARTICIPANT_ADDED_TO_LIST_MODERATORS}`,`${S.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS}`,`${S.PARTICIPANT_MOVE_REQUEST_TO_STREAM}`,`${S.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS}`,`${S.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_SYNTHETIC}`,`${S.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_WITH_AUDIO_ID}`,`${S.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS}`,`${S.PARTICIPATION_ACCEPTING_WORD_REQUEST}`,`${S.PARTICIPATION_CANCELLING_WORD_REQUEST}`,`${S.WEBCAST_STARTED}`,`${S.WEBCAST_STOPPED}`,`${S.ACCOUNT_CHANGED}`,`${S.ACCOUNT_DELETED}`,`${S.ADMIN_START_MAIN_CAM}`,`${S.ADMIN_STOP_MAIN_CAM}`,`${S.ADMIN_START_MIC}`,`${S.ADMIN_STOP_MIC}`,`${S.ADMIN_FORCE_SYNC_MEDIA_STATE}`,`${S.FAILED_SEND_ROOM_DIRECT_P2P}`],De=()=>new l.TypedEvents(Ee),Oe=e=>!(!Ce(e)||!x(e.conference)||!x(e.participant)||!x(e.jwt)),C=(e,t)=>{let n=t.toLowerCase(),r=Object.entries(e).find(([,e])=>typeof e==`string`&&e.toLowerCase()===n);return r?r[1]:void 0},ke=e=>typeof e==`string`&&!Number.isNaN(Number(e))&&Number.isFinite(Number(e)),Ae=e=>{if(ke(e))return Number(e)},je=e=>{let t=e.toLowerCase();if(t===`true`||t===`1`)return!0;if(t===`false`||t===`0`)return!1},w=(e,t)=>{let n=e.getHeader(t.toLowerCase());if(!x(n))return;let r=n.toLowerCase();switch(t){case b.BEARER_TOKEN:return n;case b.CONTENT_ENTER_ROOM:case b.PARTICIPANT_NAME:case b.INPUT_CHANNELS:case b.OUTPUT_CHANNELS:case b.TRACKS_DIRECTION:case b.AUDIO_ID:case b.MAIN_CAM_RESOLUTION:case b.MEDIA_STATE:case b.NOTIFY:case b.CONTENT_ENABLE_MEDIA_DEVICE:return r;case b.MEDIA_TYPE:case b.MAIN_CAM_STATE:case b.MIC_STATE:case b.AVAILABLE_INCOMING_BITRATE:case b.AUDIO_TRACK_COUNT:case b.VIDEO_TRACK_COUNT:return Ae(r);case b.CONTENTED_STREAM_CODEC:return C(he,r);case b.CONTENT_TYPE:return C(v,r);case b.CONTENT_USE_LICENSE:return C(xe,r);case b.MAIN_CAM:return C(y,r);case b.MIC:return C(me,r);case b.MEDIA_SYNC:return C(ye,r);case b.CONTENT_PARTICIPANT_STATE:return C(fe,r);case b.SPECTATOR_MODE:return C(be,r);case b.CONTENTED_STREAM_STATE:return C(_e,r);case b.IS_DIRECT_PEER_TO_PEER:return je(r);default:return}},T=function(e){return e.CHANNELS=`channels`,e.WEBCAST_STARTED=`WebcastStarted`,e.WEBCAST_STOPPED=`WebcastStopped`,e.ACCOUNT_CHANGED=`accountChanged`,e.ACCOUNT_DELETED=`accountDeleted`,e.ADDED_TO_LIST_MODERATORS=`addedToListModerators`,e.REMOVED_FROM_LIST_MODERATORS=`removedFromListModerators`,e.ACCEPTING_WORD_REQUEST=`ParticipationRequestAccepted`,e.CANCELLING_WORD_REQUEST=`ParticipationRequestRejected`,e.MOVE_REQUEST_TO_STREAM=`ParticipantMovedToWebcast`,e.CONFERENCE_PARTICIPANT_TOKEN_ISSUED=`ConferenceParticipantTokenIssued`,e}({}),Me=_(`ApiManager`),Ne=class extends l.EventEmitterProxy{callManager;constructor(){super(De())}subscribe({connectionManager:e,callManager:t}){this.callManager=t,e.on(`sipEvent`,this.handleSipEvent),t.on(`newInfo`,this.handleNewInfo),t.on(`newDTMF`,({originator:e})=>{this.events.trigger(`new-dtmf`,{originator:e})})}async waitChannels(){return this.wait(`channels:all`)}async waitSyncMediaState(){return this.wait(`admin:force-sync-media-state`)}async sendDTMF(e){return new Promise((t,n)=>{let r;try{r=this.getEstablishedRTCSessionProtected()}catch(e){n(e)}r&&(this.callManager?.once(`newDTMF`,({originator:e})=>{e===`local`&&t()}),r.sendDTMF(e,{duration:120,interToneGap:600}))})}async sendChannels({inputChannels:e,outputChannels:t}){let n=this.getEstablishedRTCSessionProtected(),r=[`${b.INPUT_CHANNELS}: ${e}`,`${b.OUTPUT_CHANNELS}: ${t}`];return n.sendInfo(pe.CHANNELS,void 0,{extraHeaders:r})}sendEnterRoom(e){this.sendEnterRoomProtected(e).catch(e=>{this.events.trigger(`failed-send-room-direct-p2p`,{error:e})})}async sendMediaState({cam:e,mic:t},n={}){let r=this.getEstablishedRTCSessionProtected(),i=[`${b.MEDIA_STATE}: currentstate`,`${b.MAIN_CAM_STATE}: ${Number(e)}`,`${b.MIC_STATE}: ${Number(t)}`];return r.sendInfo(pe.MEDIA_STATE,void 0,{noTerminateWhenError:!0,...n,extraHeaders:i})}async sendStats({availableIncomingBitrate:e}){let t=this.getEstablishedRTCSessionProtected(),n=[`${b.AVAILABLE_INCOMING_BITRATE}: ${e}`];return t.sendInfo(pe.STATS,void 0,{noTerminateWhenError:!0,extraHeaders:n})}async sendRefusalToTurnOn(e,t={}){let n=this.getEstablishedRTCSessionProtected(),r=e===`mic`?0:1,i=[`${b.MEDIA_TYPE}: ${r}`];return n.sendInfo(pe.REFUSAL,void 0,{noTerminateWhenError:!0,...t,extraHeaders:i})}async sendRefusalToTurnOnMic(e={}){return this.sendRefusalToTurnOn(`mic`,{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){return this.sendRefusalToTurnOn(`cam`,{noTerminateWhenError:!0,...e})}async sendAvailableContentedStream(){await this.getEstablishedRTCSessionProtected().sendInfo(pe.SHARE_STATE,void 0,{extraHeaders:[ve.AVAILABLE_CONTENTED_STREAM]})}async askPermissionToStartPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(pe.SHARE_STATE,void 0,{extraHeaders:[ve.ACK_PERMISSION_TO_START_PRESENTATION]})}async sendStoppedPresentation(){await this.getEstablishedRTCSessionProtected().sendInfo(pe.SHARE_STATE,void 0,{extraHeaders:[ve.STOPPED_CLIENT_PRESENTATION]})}async sendNotAvailableContentedStream(){await this.getEstablishedRTCSessionProtected().sendInfo(pe.SHARE_STATE,void 0,{extraHeaders:[ve.NOT_AVAILABLE_CONTENTED_STREAM]})}async askPermissionToEnableCam(e={}){let t=this.getEstablishedRTCSessionProtected(),n=[ve.ENABLE_MAIN_CAM];return t.sendInfo(pe.MAIN_CAM,void 0,{noTerminateWhenError:!0,...e,extraHeaders:n}).catch(e=>{if(de(e))throw e})}getEstablishedRTCSessionProtected=()=>{let e=this.callManager?.getEstablishedRTCSession();if(!e)throw Error(`No rtcSession established`);return e};handleSipEvent=({request:e})=>{this.maybeHandleNotify(e)};maybeHandleNotify=e=>{try{let t=e.getHeader(b.NOTIFY);if(t){let e=JSON.parse(t);this.handleNotify(e)}}catch(e){Me(`error parse notify`,e)}};handleNotify=e=>{switch(e.cmd){case T.CHANNELS:this.triggerChannelsNotify(e);break;case T.WEBCAST_STARTED:this.triggerWebcastStartedNotify(e);break;case T.WEBCAST_STOPPED:this.triggerWebcastStoppedNotify(e);break;case T.ADDED_TO_LIST_MODERATORS:this.triggerAddedToListModeratorsNotify(e);break;case T.REMOVED_FROM_LIST_MODERATORS:this.triggerRemovedFromListModeratorsNotify(e);break;case T.ACCEPTING_WORD_REQUEST:this.triggerParticipationAcceptingWordRequest(e);break;case T.CANCELLING_WORD_REQUEST:this.triggerParticipationCancellingWordRequest(e);break;case T.MOVE_REQUEST_TO_STREAM:this.triggerParticipantMoveRequestToStream(e);break;case T.ACCOUNT_CHANGED:this.triggerAccountChangedNotify();break;case T.ACCOUNT_DELETED:this.triggerAccountDeletedNotify();break;case T.CONFERENCE_PARTICIPANT_TOKEN_ISSUED:this.maybeTriggerConferenceParticipantTokenIssued(e);break;default:Me(`unknown cmd`,e)}};handleNewInfo=e=>{let{originator:t}=e;if(t!==`remote`)return;let{request:n}=e,r=n,i=w(r,b.CONTENT_TYPE);if(i!==void 0)switch(i){case v.ENTER_ROOM:this.triggerEnterRoom(r),this.maybeTriggerChannels(r);break;case v.NOTIFY:this.maybeHandleNotify(r);break;case v.SHARE_STATE:this.triggerContentedStreamState(r);break;case v.MAIN_CAM:this.triggerMainCamControl(r);break;case v.MIC:this.triggerMicControl(r);break;case v.USE_LICENSE:this.triggerUseLicense(r);break;case v.PARTICIPANT_STATE:this.maybeTriggerParticipantMoveRequest(r);break}};triggerChannelsNotify=e=>{let t={inputChannels:e.input,outputChannels:e.output};this.events.trigger(`channels:notify`,t)};triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{let n={conference:e,type:t};this.events.trigger(`webcast:started`,n)};triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{let n={conference:e,type:t};this.events.trigger(`webcast:stopped`,n)};triggerAddedToListModeratorsNotify=({conference:e})=>{let t={conference:e};this.events.trigger(`participant:added-to-list-moderators`,t)};triggerRemovedFromListModeratorsNotify=({conference:e})=>{let t={conference:e};this.events.trigger(`participant:removed-from-list-moderators`,t)};triggerParticipationAcceptingWordRequest=({body:{conference:e}})=>{let t={conference:e};this.events.trigger(`participation:accepting-word-request`,t)};triggerParticipationCancellingWordRequest=({body:{conference:e}})=>{let t={conference:e};this.events.trigger(`participation:cancelling-word-request`,t)};triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{let t={conference:e};this.events.trigger(`participant:move-request-to-stream`,t)};triggerAccountChangedNotify=()=>{this.events.trigger(`account:changed`)};triggerAccountDeletedNotify=()=>{this.events.trigger(`account:deleted`)};maybeTriggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:n}})=>{let r={conference:e,participant:t,jwt:n};Oe(r)&&this.events.trigger(`conference:participant-token-issued`,r)};maybeTriggerChannels=e=>{let t=w(e,b.INPUT_CHANNELS),n=w(e,b.OUTPUT_CHANNELS);if(t!==void 0&&n!==void 0){let e={inputChannels:t,outputChannels:n};this.events.trigger(`channels:all`,e)}};triggerEnterRoom=e=>{let t=w(e,b.CONTENT_ENTER_ROOM),n=w(e,b.PARTICIPANT_NAME),r=w(e,b.BEARER_TOKEN),i=w(e,b.IS_DIRECT_PEER_TO_PEER);t!==void 0&&n!==void 0&&this.events.trigger(`enter-room`,{room:t,participantName:n,bearerToken:r,isDirectPeerToPeer:i})};triggerContentedStreamState=e=>{let t=w(e,b.CONTENTED_STREAM_STATE);if(t!==void 0)switch(t){case _e.AVAILABLE_CONTENTED_STREAM:{let t=w(e,b.CONTENTED_STREAM_CODEC);this.events.trigger(`contented-stream:available`,{codec:t});break}case _e.NOT_AVAILABLE_CONTENTED_STREAM:this.events.trigger(`contented-stream:not-available`);break;case _e.MUST_STOP_PRESENTATION:this.events.trigger(`presentation:must-stop`);break}};maybeTriggerParticipantMoveRequest=e=>{let t=w(e,b.CONTENT_PARTICIPANT_STATE),n=w(e,b.AUDIO_ID),r=w(e,b.SPECTATOR_MODE);if(t===fe.SPECTATOR){let e=r===be.BY_STATE_CAM;n===void 0?(this.events.trigger(`participant:move-request-to-spectators-synthetic`,{isAvailableSendingMedia:e}),this.events.trigger(`participant:move-request-to-spectators`,{isAvailableSendingMedia:e,isSynthetic:!0})):(this.events.trigger(`participant:move-request-to-spectators-with-audio-id`,{isAvailableSendingMedia:e,audioId:n}),this.events.trigger(`participant:move-request-to-spectators`,{isAvailableSendingMedia:e,isSynthetic:!1,audioId:n}))}t===fe.PARTICIPANT&&this.events.trigger(`participant:move-request-to-participants`)};triggerMainCamControl=e=>{let t=w(e,b.MAIN_CAM),n=w(e,b.MEDIA_SYNC),r=n===ye.ADMIN_SYNC_FORCED;if(t===y.ADMIN_START_MAIN_CAM){this.events.trigger(`admin:start-main-cam`,{isSyncForced:r});return}if(t===y.ADMIN_STOP_MAIN_CAM){this.events.trigger(`admin:stop-main-cam`,{isSyncForced:r});return}(t===y.RESUME_MAIN_CAM||t===y.PAUSE_MAIN_CAM)&&n!==void 0&&this.events.trigger(`admin:force-sync-media-state`,{isSyncForced:r});let i=w(e,b.MAIN_CAM_RESOLUTION);this.events.trigger(`main-cam-control`,{mainCam:t,resolutionMainCam:i})};triggerMicControl=e=>{let t=w(e,b.MIC),n=w(e,b.MEDIA_SYNC)===ye.ADMIN_SYNC_FORCED;t===me.ADMIN_START_MIC?this.events.trigger(`admin:start-mic`,{isSyncForced:n}):t===me.ADMIN_STOP_MIC&&this.events.trigger(`admin:stop-mic`,{isSyncForced:n})};triggerUseLicense=e=>{let t=w(e,b.CONTENT_USE_LICENSE);t!==void 0&&this.events.trigger(`use-license`,t)};async sendEnterRoomProtected(e){return this.getEstablishedRTCSessionProtected().sendInfo(v.ENTER_ROOM,void 0,{extraHeaders:e})}},Pe=0,Fe=30,Ie=_(`AutoConnectorManager: AttemptsState`),Le=class{countInner=Pe;initialCount=Pe;limitInner=Fe;isInProgress=!1;onStatusChange;constructor({onStatusChange:e}){this.onStatusChange=e}get count(){return this.countInner}get limit(){return this.limitInner}get isAttemptInProgress(){return this.isInProgress}hasLimitReached(){return Ie(`hasLimitReached`,{count:this.countInner,limit:this.limitInner}),this.countInner>=this.limitInner}startAttempt(){Ie(`startAttempt`,{count:this.countInner,limit:this.limitInner}),this.isInProgress||(this.isInProgress=!0,this.onStatusChange({isInProgress:this.isInProgress}))}finishAttempt(){Ie(`finishAttempt`,{count:this.countInner,limit:this.limitInner}),this.isInProgress&&(this.isInProgress=!1,this.onStatusChange({isInProgress:this.isInProgress}))}increment(){Ie(`increment`,{count:this.countInner,limit:this.limitInner}),this.count<this.limit&&(this.countInner+=1)}reset(){Ie(`reset`,{count:this.countInner,limit:this.limitInner}),this.countInner=this.initialCount,this.finishAttempt()}},Re=class{connectionManager;interval;checkTelephonyByTimeout=void 0;cancelableGetParameters=void 0;constructor({connectionManager:e,interval:t}){this.connectionManager=e,this.interval=t}start(e,{onSuccessRequest:t,onFailRequest:n}){this.stop(),this.cancelableGetParameters=new f.CancelableRequest(e),this.checkTelephonyByTimeout=(0,d.resolveRequesterByTimeout)({isDontStopOnFail:!0,requestInterval:this.interval,request:async()=>{if(!this.cancelableGetParameters)throw Error(`cancelableGetParameters is not defined`);let e=await this.cancelableGetParameters.request();return this.connectionManager.checkTelephony(e)}}),this.checkTelephonyByTimeout.start(void 0,{onFailRequest:n,onSuccessRequest:()=>{this.stop(),t()}})}stop(){this.checkTelephonyByTimeout?.stop(),this.checkTelephonyByTimeout=void 0,this.cancelableGetParameters?.cancelRequest(),this.cancelableGetParameters=void 0}},ze=15e3,Be=2,Ve=_(`AutoConnectorManager: PingServerRequester`),He=class{connectionManager;pingServerByTimeout=void 0;failRequestsCount=0;isFailRequestReported=!1;constructor({connectionManager:e}){this.connectionManager=e}start({onFailRequest:e}){Ve(`start`),this.stop(),this.pingServerByTimeout=(0,d.resolveRequesterByTimeout)({isDontStopOnFail:!0,requestInterval:ze,request:async()=>(Ve(`ping`),this.connectionManager.ping().then(()=>{Ve(`ping success`)}))}),this.pingServerByTimeout.start(void 0,{onSuccessRequest:()=>{this.resetFailRequests()},onFailRequest:()=>{if(this.failRequestsCount+=1,Ve(`failRequestsCount`,this.failRequestsCount),this.failRequestsCount<Be||this.isFailRequestReported){Ve(`failRequestsCount < MAX_FAIL_REQUESTS_COUNT || isFailRequestReported`,this.failRequestsCount,Be,this.isFailRequestReported);return}this.isFailRequestReported=!0,Ve(`isFailRequestReported`,this.isFailRequestReported),e()}})}stop(){Ve(`stop`),this.pingServerByTimeout?.stop(),this.pingServerByTimeout=void 0,this.resetFailRequests()}resetFailRequests(){this.failRequestsCount=0,this.isFailRequestReported=!1}},Ue=class{callManager;disposers=[];constructor({callManager:e}){this.callManager=e}subscribe(e){this.unsubscribe(),this.disposers.push(this.callManager.on(`call-status-changed`,()=>{this.handleCallStatusChange(e)})),this.handleCallStatusChange(e)}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[]}handleCallStatusChange({onActive:e,onInactive:t}){this.callManager.isCallActive?e?.():t()}},We=class{connectionManager;isRegistrationFailed=!1;disposers=[];notActiveCallSubscriber;constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.notActiveCallSubscriber=new Ue({callManager:t})}subscribe(e){this.unsubscribe(),this.disposers.push(this.connectionManager.on(`registrationFailed`,()=>{this.setIsRegistrationFailed()})),this.notActiveCallSubscriber.subscribe({onInactive:()=>{this.isRegistrationFailed&&e()}}),this.disposers.push(()=>{this.notActiveCallSubscriber.unsubscribe()})}unsubscribe(){this.disposers.forEach(e=>{e()}),this.disposers=[],this.resetIsRegistrationFailed()}setIsRegistrationFailed(){this.isRegistrationFailed=!0}resetIsRegistrationFailed(){this.isRegistrationFailed=!1}},Ge={baseRetryDelayMs:1e3,maxRetryDelayMs:3e4,warningThreshold:3,criticalThreshold:5},Ke={none:0,warning:1,critical:2},qe=class{failCount=0;nextRetryAtMs=0;escalationLevel=`none`;options;constructor(e){this.options={...Ge,...e}}registerFailure(){this.failCount+=1;let e=this.resolveEscalationLevel(this.failCount),t=Ke[e]>Ke[this.escalationLevel];this.escalationLevel=e;let n=Date.now(),r=Math.max(this.nextRetryAtMs-n,0);if(r>0)return{failCount:this.failCount,escalationLevel:this.escalationLevel,hasEscalated:t,shouldRequestReconnect:!1,nextRetryDelayMs:r};let i=this.resolveBackoffDelayMs(this.failCount);return this.nextRetryAtMs=n+i,{failCount:this.failCount,escalationLevel:this.escalationLevel,hasEscalated:t,shouldRequestReconnect:!0,nextRetryDelayMs:i}}reset(){this.failCount=0,this.nextRetryAtMs=0,this.escalationLevel=`none`}resolveEscalationLevel(e){return e>=this.options.criticalThreshold?`critical`:e>=this.options.warningThreshold?`warning`:`none`}resolveBackoffDelayMs(e){return Math.min(this.options.baseRetryDelayMs*2**Math.max(e-1,0),this.options.maxRetryDelayMs)}},Je={START:`start`,MANUAL_RESTART:`manual-restart`,REGISTRATION_FAILED_OUT_OF_CALL:`registration-failed-out-of-call`,TELEPHONY_DISCONNECTED:`telephony-disconnected`,TELEPHONY_CHECK_FAILED:`telephony-check-failed`,PERIODIC_PING_FAILED:`periodic-ping-failed`,NETWORK_ONLINE:`network-online`,NETWORK_CHANGE:`network-change`},Ye={[Je.START]:0,[Je.TELEPHONY_DISCONNECTED]:1,[Je.TELEPHONY_CHECK_FAILED]:1,[Je.PERIODIC_PING_FAILED]:2,[Je.REGISTRATION_FAILED_OUT_OF_CALL]:3,[Je.MANUAL_RESTART]:4,[Je.NETWORK_ONLINE]:4,[Je.NETWORK_CHANGE]:4},Xe=e=>Ye[e],E=_(`AutoConnectorManager: AutoConnectorRuntime`),Ze=3e3,Qe=15e3,$e=class{connectionManager;connectionQueueManager;checkTelephonyRequester;pingServerRequester;registrationFailedOutOfCallSubscriber;attemptsState;delayBetweenAttempts;telephonyFailPolicy;emitters;reconnectActions;constructor(e){this.connectionManager=e.connectionManager,this.connectionQueueManager=e.connectionQueueManager,this.emitters=e.emitters,this.reconnectActions=e.reconnectActions,this.checkTelephonyRequester=new Re({connectionManager:this.connectionManager,interval:e.options?.checkTelephonyRequestInterval??Qe}),this.pingServerRequester=new He({connectionManager:this.connectionManager}),this.registrationFailedOutOfCallSubscriber=new We({connectionManager:this.connectionManager,callManager:e.callManager}),this.delayBetweenAttempts=new d.DelayRequester(e.options?.timeoutBetweenAttempts??Ze),this.telephonyFailPolicy=new qe(e.options?.telephonyFailPolicy),this.attemptsState=new Le({onStatusChange:this.emitters.emitStatusChange})}async stopConnectionFlow(){E(`stopConnectionFlow`),this.stopAttempts(),this.stopConnectTriggers(),await this.connectionQueueManager.disconnect()}async connect(e){await this.connectionQueueManager.connect(e.getParameters,e.options)}async delayBeforeRetry(){await this.delayBetweenAttempts.request()}cancelPendingRetry(){this.delayBetweenAttempts.cancelRequest()}hasLimitReached(){return this.attemptsState.hasLimitReached()}shouldDisconnectBeforeAttempt(){let{isDisconnected:e,isIdle:t,isDisconnecting:n,requested:r}=this.connectionManager;return n||r?!0:!(e||t)}beforeAttempt(){E(`entryAttemptingGate`),this.emitters.emitBeforeAttempt(),this.stopConnectTriggers()}beforeConnectAttempt(){E(`entryAttemptingConnect`),this.attemptsState.startAttempt(),this.attemptsState.increment()}onLimitReached(e){E(`onLimitReachedTransition`),this.attemptsState.finishAttempt(),this.emitters.emitLimitReachedAttempts(),this.startCheckTelephony(e)}onConnectSucceeded(e){this.subscribeToConnectTriggers(e),this.emitters.emitSuccess()}emitTerminalOutcome({stopReason:e,lastError:t}){if(this.attemptsState.finishAttempt(),e===`halted`){this.emitters.emitStopAttemptsByError(t);return}if(e===`cancelled`){this.emitters.emitCancelledAttempts(t);return}if(e===`failed`){this.emitters.emitFailedAllAttempts(t);return}E(`emitTerminalOutcome without stopReason`,t)}onTelephonyStillConnected(){E(`onTelephonyStillConnected`),this.stopConnectTriggers(),this.emitters.emitSuccess()}stopConnectTriggers(){E(`stopConnectTriggers`),this.pingServerRequester.stop(),this.checkTelephonyRequester.stop(),this.registrationFailedOutOfCallSubscriber.unsubscribe()}stopAttempts(){this.attemptsState.isAttemptInProgress&&this.connectionQueueManager.stop(),this.cancelPendingRetry(),this.attemptsState.reset()}startCheckTelephony(e){E(`startCheckTelephony`),this.checkTelephonyRequester.start(async()=>e.getParameters(),{onSuccessRequest:()=>{E(`startCheckTelephony: onSuccessRequest`),this.telephonyFailPolicy.reset(),this.isConnectionUnavailable()?this.reconnectActions.requestReconnect(e,`telephony-disconnected`):this.reconnectActions.notifyTelephonyStillConnected()},onFailRequest:t=>{let n=this.telephonyFailPolicy.registerFailure();this.emitters.emitTelephonyCheckFailure({failCount:n.failCount,escalationLevel:n.escalationLevel,shouldRequestReconnect:n.shouldRequestReconnect,nextRetryDelayMs:n.nextRetryDelayMs,error:t}),n.escalationLevel!==`none`&&n.hasEscalated&&this.emitters.emitTelephonyCheckEscalated({failCount:n.failCount,escalationLevel:n.escalationLevel,error:t}),n.shouldRequestReconnect&&this.reconnectActions.requestReconnect(e,`telephony-check-failed`),E(`startCheckTelephony: onFailRequest`,t?.message)}})}subscribeToConnectTriggers(e){this.pingServerRequester.start({onFailRequest:()=>{E(`pingRequester: onFailRequest`),this.reconnectActions.requestReconnect(e,Je.PERIODIC_PING_FAILED)}}),this.registrationFailedOutOfCallSubscriber.subscribe(()=>{E(`registrationFailedOutOfCallListener callback`),this.reconnectActions.requestReconnect(e,`registration-failed-out-of-call`)})}isConnectionUnavailable(){let{isDisconnected:e,isIdle:t}=this.connectionManager;return e||t}},et=class{actor;subscriptions=[];stateChangeListeners=new Set;constructor(e){this.actor=(0,p.createActor)(e),this.actor.start(),this.addSubscription(this.subscribe(e=>{let t=e.value;this.stateChangeListeners.forEach(e=>{e(t)})}))}get state(){return this.getSnapshot().value}get context(){return this.getSnapshot().context}send(e){this.actor.send(e)}getSnapshot(){return this.actor.getSnapshot()}subscribe(e){let t=this.actor.subscribe(e);return this.addSubscription(t),t}onStateChange(e){return this.stateChangeListeners.add(e),()=>{this.stateChangeListeners.delete(e)}}stop(){this.stateChangeListeners.clear(),this.subscriptions.forEach(e=>{e()}),this.subscriptions.length=0,this.actor.stop()}addSubscription(e){let t=typeof e==`function`?e:()=>{e.unsubscribe()};return this.subscriptions.push(t),t}},tt=`Not ready for connection`,nt=e=>e instanceof Error&&e.message===tt,rt=()=>Error(tt),it=async e=>typeof e==`function`?e():e,at=_(`ConnectionManager: ConnectionFlow`),ot=3,st=class{resolveParametersRequester=new f.CancelableRequest(it);cancelableConnectWithRepeatedCalls;numberOfConnectionAttempts;dependencies;constructor(e,{numberOfConnectionAttempts:t=ot}={}){this.dependencies=e,this.numberOfConnectionAttempts=t,this.proxyEvents()}connect=async(e,t)=>(at(`connect`,e,t),this.dependencies.stateMachine.toStartConnect(),this.dependencies.events.trigger(`connect-started`,{}),this.cancelRequests(),this.resolveParametersRequester.request(e).then(e=>(this.dependencies.events.trigger(`connect-parameters-resolve-success`,e),e)).catch(e=>{throw this.dependencies.events.trigger(`connect-parameters-resolve-failed`,e),e}).then(async e=>this.connectWithDuplicatedCalls(e,t)).then(e=>(at(`connect: succeeded`,e),this.dependencies.events.trigger(`connect-succeeded`,{...e}),e)).catch(e=>{at(`connect: error`,e);let t=e??Error(`Failed to connect to server`);throw(0,f.isCanceledError)(t)||this.dependencies.events.trigger(`connect-failed`,t),t}));disconnect=async({cancelRequests:e=!0}={})=>{at(`disconnect`,{cancelRequests:e}),e&&this.cancelRequests(),this.dependencies.events.trigger(`disconnecting`,{});let t=new Promise(e=>{this.dependencies.events.once(`disconnected`,()=>{e()})}),n=this.dependencies.getUa();return n?n.stop():this.dependencies.events.trigger(`disconnected`,{socket:{},error:!1}),t.finally(()=>{n?.removeAllListeners(),this.dependencies.setUa(void 0),this.dependencies.stateMachine.reset()})};cancelRequests(){at(`cancelRequests`),this.resolveParametersRequester.cancelRequest(),this.cancelConnectWithRepeatedCalls()}connectWithDuplicatedCalls=async(e,{numberOfConnectionAttempts:t=this.numberOfConnectionAttempts}={})=>{let n=async()=>this.connectInner(e),r=t=>{let n=this.dependencies.getUa()?.isConnected()===!0&&this.hasEqualConnectionConfiguration(e),r=t!=null&&!ue(t);return n||r};return this.cancelableConnectWithRepeatedCalls=(0,m.repeatedCallsAsync)({targetFunction:n,isComplete:r,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(e=>{if(typeof e==`object`&&e&&`authorizationUser`in e)return e;throw e})};hasEqualConnectionConfiguration(e){let{configuration:t}=this.dependencies.uaFactory.createConfiguration(e),n=this.dependencies.getUa()?.configuration;return n?n.password===t.password&&n.register===t.register&&n.uri.toString()===t.uri&&n.display_name===t.display_name&&n.user_agent===t.user_agent&&n.sockets===t.sockets&&n.session_timers===t.session_timers&&n.register_expires===t.register_expires&&n.connection_recovery_min_interval===t.connection_recovery_min_interval&&n.connection_recovery_max_interval===t.connection_recovery_max_interval:!1}connectInner=async e=>this.initUa(e).then(async({configuration:e})=>this.start(e));initUa=async({user:e,password:t,sipServerIp:n,sipServerUrl:r,remoteAddress:i,iceServers:a,sessionTimers:o,registerExpires:s,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:l,userAgent:u,displayName:d=``,register:f=!1,extraHeaders:p=[]})=>{at(`initUa`),this.dependencies.getUa()&&await this.disconnect({cancelRequests:!1});let{ua:m,helpers:h}=this.dependencies.uaFactory.createUAWithConfiguration({user:e,password:t,sipServerIp:n,sipServerUrl:r,displayName:d,register:f,sessionTimers:o,registerExpires:s,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:l,userAgent:u,remoteAddress:i,extraHeaders:p},this.dependencies.events);return this.dependencies.setUa(m),this.dependencies.setGetUri(h.getUri),this.dependencies.setSocket(h.socket),{ua:m,configuration:{sipServerIp:n,sipServerUrl:r,remoteAddress:i,iceServers:a,displayName:d,authorizationUser:m.configuration.uri.user,register:f,user:e,password:t}}};start=async e=>(at(`start`,e),new Promise((t,n)=>{let r=this.dependencies.getUa();if(!r){n(Error(`this.ua is not initialized`));return}let i;i=((t,n)=>{if(e.register===!0)return this.dependencies.registrationManager.subscribeToStartEvents(t,n);let r=`connected`,i=[`disconnected`];return this.dependencies.events.on(r,t),i.forEach(e=>{this.dependencies.events.on(e,n)}),()=>{this.dependencies.events.off(r,t),i.forEach(e=>{this.dependencies.events.off(e,n)})}})(()=>{at(`start: resolveUa`),i?.(),t(e)},e=>{i?.(),n(e)}),this.dependencies.stateMachine.toStartUa(e),r.start()}));cancelConnectWithRepeatedCalls(){this.cancelableConnectWithRepeatedCalls?.cancel()}proxyEvents(){this.dependencies.events.on(`connected`,()=>{let e=this.dependencies.stateMachine.getConnectionConfiguration();e!==void 0&&this.dependencies.events.trigger(`connected-with-configuration`,e)})}},D=function(e){return e.IDLE=`connection:idle`,e.PREPARING=`connection:preparing`,e.CONNECTING=`connection:connecting`,e.CONNECTED=`connection:connected`,e.REGISTERED=`connection:registered`,e.ESTABLISHED=`connection:established`,e.DISCONNECTING=`connection:disconnecting`,e.DISCONNECTED=`connection:disconnected`,e}({}),O=function(e){return e.LOG_TRANSITION=`logTransition`,e.LOG_STATE_CHANGE=`logStateChange`,e.SET_CONNECTION_CONFIGURATION=`setConnectionConfiguration`,e.CLEAR_CONNECTION_CONFIGURATION=`clearConnectionConfiguration`,e}({}),k=function(e){return e.START_CONNECT=`START_CONNECT`,e.START_UA=`START_UA`,e.START_DISCONNECT=`START_DISCONNECT`,e.UA_CONNECTED=`UA_CONNECTED`,e.UA_CONNECTING=`UA_CONNECTING`,e.UA_REGISTERED=`UA_REGISTERED`,e.UA_UNREGISTERED=`UA_UNREGISTERED`,e.UA_DISCONNECTED=`UA_DISCONNECTED`,e.RESET=`RESET`,e}({}),ct={connectionConfiguration:void 0},lt=_(`ConnectionManager: createConnectionMachineSetup`),ut=(0,p.setup)({types:{context:ct,events:{}},guards:{canAutoEstablish:({context:e})=>e.connectionConfiguration?.register!==!0},actions:{[O.SET_CONNECTION_CONFIGURATION]:(0,p.assign)(({event:e})=>({connectionConfiguration:{...e.configuration}})),[O.CLEAR_CONNECTION_CONFIGURATION]:(0,p.assign)(()=>({connectionConfiguration:void 0})),[O.LOG_TRANSITION]:(e,t)=>{lt(`State transition: ${t.from} -> ${t.to} (${t.event})`)},[O.LOG_STATE_CHANGE]:(e,t)=>{lt(`ConnectionStateMachine state changed`,t.state)}}}).createMachine({id:`connection`,initial:D.IDLE,context:ct,states:{[D.IDLE]:{entry:[{type:O.LOG_STATE_CHANGE,params:{state:D.IDLE}},{type:O.CLEAR_CONNECTION_CONFIGURATION}],on:{[k.START_CONNECT]:{target:D.PREPARING,actions:{type:O.LOG_TRANSITION,params:{from:D.IDLE,to:D.PREPARING,event:k.START_CONNECT}}}}},[D.PREPARING]:{entry:{type:O.LOG_STATE_CHANGE,params:{state:D.PREPARING}},on:{[k.START_UA]:{target:D.CONNECTING,actions:[O.SET_CONNECTION_CONFIGURATION,{type:O.LOG_TRANSITION,params:{from:D.PREPARING,to:D.CONNECTING,event:k.START_UA}}]},[k.UA_DISCONNECTED]:{target:D.DISCONNECTED,actions:{type:O.LOG_TRANSITION,params:{from:D.PREPARING,to:D.DISCONNECTED,event:k.UA_DISCONNECTED}}}}},[D.CONNECTING]:{entry:{type:O.LOG_STATE_CHANGE,params:{state:D.CONNECTING}},on:{[k.UA_CONNECTED]:{target:D.CONNECTED,actions:{type:O.LOG_TRANSITION,params:{from:D.CONNECTING,to:D.CONNECTED,event:k.UA_CONNECTED}}},[k.UA_REGISTERED]:{target:D.REGISTERED,actions:{type:O.LOG_TRANSITION,params:{from:D.CONNECTING,to:D.REGISTERED,event:k.UA_REGISTERED}}},[k.START_DISCONNECT]:{target:D.DISCONNECTING,actions:{type:O.LOG_TRANSITION,params:{from:D.CONNECTING,to:D.DISCONNECTING,event:k.START_DISCONNECT}}},[k.UA_DISCONNECTED]:{target:D.DISCONNECTED,actions:{type:O.LOG_TRANSITION,params:{from:D.CONNECTING,to:D.DISCONNECTED,event:k.UA_DISCONNECTED}}}}},[D.CONNECTED]:{entry:{type:O.LOG_STATE_CHANGE,params:{state:D.CONNECTED}},always:{target:D.ESTABLISHED,guard:`canAutoEstablish`,actions:{type:O.LOG_TRANSITION,params:{from:D.CONNECTED,to:D.ESTABLISHED,event:`always`}}},on:{[k.UA_REGISTERED]:{target:D.REGISTERED,actions:{type:O.LOG_TRANSITION,params:{from:D.CONNECTED,to:D.REGISTERED,event:k.UA_REGISTERED}}},[k.START_DISCONNECT]:{target:D.DISCONNECTING,actions:{type:O.LOG_TRANSITION,params:{from:D.CONNECTED,to:D.DISCONNECTING,event:k.START_DISCONNECT}}},[k.UA_DISCONNECTED]:{target:D.DISCONNECTED,actions:{type:O.LOG_TRANSITION,params:{from:D.CONNECTED,to:D.DISCONNECTED,event:k.UA_DISCONNECTED}}}}},[D.REGISTERED]:{entry:{type:O.LOG_STATE_CHANGE,params:{state:D.REGISTERED}},always:{target:D.ESTABLISHED,actions:{type:O.LOG_TRANSITION,params:{from:D.REGISTERED,to:D.ESTABLISHED,event:`always`}}},on:{[k.UA_UNREGISTERED]:{target:D.CONNECTED,actions:{type:O.LOG_TRANSITION,params:{from:D.REGISTERED,to:D.CONNECTED,event:k.UA_UNREGISTERED}}},[k.START_DISCONNECT]:{target:D.DISCONNECTING,actions:{type:O.LOG_TRANSITION,params:{from:D.REGISTERED,to:D.DISCONNECTING,event:k.START_DISCONNECT}}},[k.UA_DISCONNECTED]:{target:D.DISCONNECTED,actions:{type:O.LOG_TRANSITION,params:{from:D.REGISTERED,to:D.DISCONNECTED,event:k.UA_DISCONNECTED}}}}},[D.ESTABLISHED]:{entry:{type:O.LOG_STATE_CHANGE,params:{state:D.ESTABLISHED}},on:{[k.START_DISCONNECT]:{target:D.DISCONNECTING,actions:{type:O.LOG_TRANSITION,params:{from:D.ESTABLISHED,to:D.DISCONNECTING,event:k.START_DISCONNECT}}},[k.UA_DISCONNECTED]:{target:D.DISCONNECTED,actions:{type:O.LOG_TRANSITION,params:{from:D.ESTABLISHED,to:D.DISCONNECTED,event:k.UA_DISCONNECTED}}},[k.RESET]:{target:D.IDLE,actions:{type:O.LOG_TRANSITION,params:{from:D.ESTABLISHED,to:D.IDLE,event:k.RESET}}}}},[D.DISCONNECTING]:{entry:{type:O.LOG_STATE_CHANGE,params:{state:D.DISCONNECTING}},on:{[k.UA_DISCONNECTED]:{target:D.DISCONNECTED,actions:{type:O.LOG_TRANSITION,params:{from:D.DISCONNECTING,to:D.DISCONNECTED,event:k.UA_DISCONNECTED}}}}},[D.DISCONNECTED]:{entry:{type:O.LOG_STATE_CHANGE,params:{state:D.DISCONNECTED}},on:{[k.RESET]:{target:D.IDLE,actions:[{type:O.LOG_TRANSITION,params:{from:D.DISCONNECTED,to:D.IDLE,event:k.RESET}}]},[k.START_CONNECT]:{target:D.PREPARING,actions:{type:O.LOG_TRANSITION,params:{from:D.DISCONNECTED,to:D.PREPARING,event:k.START_CONNECT}}},[k.UA_CONNECTING]:{target:D.CONNECTING,actions:{type:O.LOG_TRANSITION,params:{from:D.DISCONNECTED,to:D.CONNECTING,event:k.UA_CONNECTING}}}}}}}),dt=_(`ConnectionManager: ConnectionStateMachine`),ft=class extends et{events;unsubscribeFromEvents;constructor(e){super(ut),this.events=e,this.subscribeToEvents()}get isIdle(){return this.hasState(D.IDLE)}get isPreparing(){return this.hasState(D.PREPARING)}get isConnecting(){return this.hasState(D.CONNECTING)}get isConnected(){return this.hasState(D.CONNECTED)}get isRegistered(){return this.hasState(D.REGISTERED)}get isEstablished(){return this.hasState(D.ESTABLISHED)}get isDisconnecting(){return this.hasState(D.DISCONNECTING)}get isDisconnected(){return this.hasState(D.DISCONNECTED)}get isPending(){return this.isPreparing||this.isConnecting}get isPendingConnect(){return this.isPreparing}get isPendingInitUa(){return this.isConnecting}get isActiveConnection(){return this.isEstablished||this.isConnected||this.isRegistered}toStartConnect=()=>{this.sendEvent({type:k.START_CONNECT})};toStartUa=e=>{this.sendEvent({type:k.START_UA,configuration:e})};reset(){this.toIdle()}getConnectionConfiguration(){if(this.context.connectionConfiguration!==void 0)return{...this.context.connectionConfiguration}}isRegisterEnabled(){return this.context.connectionConfiguration?.register===!0}destroy(){this.unsubscribeFromEvents?.(),this.stop()}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){if(!this.actor.getSnapshot().can(e)){dt(`Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}this.send(e)}toStartDisconnect=()=>{this.sendEvent({type:k.START_DISCONNECT})};toConnecting=()=>{this.sendEvent({type:k.UA_CONNECTING})};toConnected=()=>{this.sendEvent({type:k.UA_CONNECTED})};toRegistered=()=>{this.sendEvent({type:k.UA_REGISTERED})};toUnregistered=()=>{this.sendEvent({type:k.UA_UNREGISTERED})};toDisconnected=()=>{this.sendEvent({type:k.UA_DISCONNECTED})};toIdle=()=>{this.sendEvent({type:k.RESET})};subscribeToEvents(){this.events.on(`connected`,this.toConnected),this.events.on(`connecting`,this.toConnecting),this.events.on(`registered`,this.toRegistered),this.events.on(`unregistered`,this.toUnregistered),this.events.on(`disconnecting`,this.toStartDisconnect),this.events.on(`disconnected`,this.toDisconnected),this.events.on(`registrationFailed`,this.toDisconnected),this.events.on(`connect-failed`,this.toDisconnected),this.unsubscribeFromEvents=()=>{this.events.off(`connected`,this.toConnected),this.events.off(`connecting`,this.toConnecting),this.events.off(`registered`,this.toRegistered),this.events.off(`unregistered`,this.toUnregistered),this.events.off(`disconnecting`,this.toStartDisconnect),this.events.off(`disconnected`,this.toDisconnected),this.events.off(`registrationFailed`,this.toDisconnected),this.events.off(`connect-failed`,this.toDisconnected)}}},A=function(e){return e.CONNECTING=`connecting`,e.CONNECTED=`connected`,e.DISCONNECTED=`disconnected`,e.DISCONNECTING=`disconnecting`,e.NEW_RTC_SESSION=`newRTCSession`,e.REGISTERED=`registered`,e.UNREGISTERED=`unregistered`,e.REGISTRATION_FAILED=`registrationFailed`,e.NEW_MESSAGE=`newMessage`,e.SIP_EVENT=`sipEvent`,e.CONNECT_STARTED=`connect-started`,e.CONNECT_SUCCEEDED=`connect-succeeded`,e.CONNECT_FAILED=`connect-failed`,e.CONNECT_PARAMETERS_RESOLVE_SUCCESS=`connect-parameters-resolve-success`,e.CONNECT_PARAMETERS_RESOLVE_FAILED=`connect-parameters-resolve-failed`,e.CONNECTED_WITH_CONFIGURATION=`connected-with-configuration`,e}(A||{}),pt=[`${A.CONNECTING}`,`${A.CONNECTED}`,`${A.DISCONNECTED}`,`${A.NEW_RTC_SESSION}`,`${A.REGISTERED}`,`${A.UNREGISTERED}`,`${A.REGISTRATION_FAILED}`,`${A.NEW_MESSAGE}`,`${A.SIP_EVENT}`],mt=[`${A.DISCONNECTING}`,`${A.CONNECT_STARTED}`,`${A.CONNECT_SUCCEEDED}`,`${A.CONNECT_FAILED}`,`${A.CONNECT_PARAMETERS_RESOLVE_SUCCESS}`,`${A.CONNECT_PARAMETERS_RESOLVE_FAILED}`,`${A.CONNECTED_WITH_CONFIGURATION}`],ht=[...pt,...mt],gt=()=>new l.TypedEvents(ht),_t=_(`ConnectionManager: RegistrationManager`),vt=class{events;getUaProtected;constructor(e){this.events=e.events,this.getUaProtected=e.getUaProtected}async register(){let e=this.getUaProtected();return new Promise((t,n)=>{e.on(`registered`,t),e.on(`registrationFailed`,n),e.register()})}async unregister(){let e=this.getUaProtected();return new Promise(t=>{e.on(`unregistered`,t),e.unregister()})}async tryRegister(){try{await this.unregister()}catch(e){_t(`tryRegister`,e)}return this.register()}subscribeToStartEvents(e,t){let n=`registered`,r=[`registrationFailed`,`disconnected`];return this.events.on(n,e),r.forEach(e=>{this.events.on(e,t)}),()=>{this.events.off(n,e),r.forEach(e=>{this.events.off(e,t)})}}},yt=1e4,bt=class{uaFactory;getUaProtected;constructor(e){this.uaFactory=e.uaFactory,this.getUaProtected=e.getUaProtected}async sendOptions(e,t,n,r){let i=this.getUaProtected();return new Promise((a,o)=>{try{i.sendOptions(e,t,{extraHeaders:n,eventHandlers:{succeeded:()=>{a()},failed:o},timeout:r})}catch(e){o(e)}})}async ping(e,t){let n=this.getUaProtected().configuration.uri;return this.sendOptions(n,e,t,yt)}async checkTelephony({userAgent:e,displayName:t,sipServerIp:n,sipServerUrl:r,remoteAddress:i,extraHeaders:a}){return new Promise((o,s)=>{let{configuration:c}=this.uaFactory.createConfiguration({sipServerUrl:r,displayName:t,userAgent:e,sipServerIp:n}),l=this.uaFactory.createUA({...c,remoteAddress:i,extraHeaders:a});l.once(`disconnected`,()=>{s(Error(`Telephony is not available`))}),l.once(`connected`,()=>{l.removeAllListeners(),l.once(`disconnected`,()=>{o()}),l.stop()}),l.start()})}};function xt(e){return t=>`sip:${t}@${e}`}var St=(e,t)=>()=>Math.floor(Math.random()*(t-e))+e,Ct=e=>e.trim().replaceAll(` `,`_`),wt=St(1e5,99999999),Tt=e=>{let t=[];return e!==void 0&&e!==``&&t.push(`X-Vinteo-Remote: ${e}`),t},Et=class e{JsSIP;constructor(e){this.JsSIP=e}static isRegisteredUA(e){return!!e&&e.isRegistered()}static validateParametersConnection({register:e,password:t,user:n,sipServerIp:r,sipServerUrl:i}){if(!r)throw Error(`sipServerIp is required`);if(!i)throw Error(`sipServerUrl is required`);if(e&&(t===void 0||t===``))throw Error(`password is required for authorized connection`);if(e&&(n===void 0||n===``))throw Error(`user is required for authorized connection`)}static resolveAuthorizationUser(e,t){return e&&t!==void 0&&t.trim()!==``?t.trim():`${wt()}`}static buildExtraHeaders(e,t){let n=e!==void 0&&e!==``?Tt(e):[];return t===void 0?n:[...n,...t]}createConfiguration({user:t,password:n,sipServerUrl:r,displayName:i=``,sipServerIp:a,register:o=!1,sessionTimers:s=!1,registerExpires:c=300,connectionRecoveryMinInterval:l=2,connectionRecoveryMaxInterval:u=6,userAgent:d}){e.validateParametersConnection({register:o,password:n,user:t,sipServerIp:a,sipServerUrl:r});let f=e.resolveAuthorizationUser(o,t),p=xt(a),m=p(f),h=new this.JsSIP.WebSocketInterface(`wss://${r}/webrtc/wss/`);return{configuration:{password:n,register:o,uri:m,display_name:Ct(i),user_agent:d,sockets:[h],session_timers:s,register_expires:c,connection_recovery_min_interval:l,connection_recovery_max_interval:u},helpers:{socket:h,getUri:p}}}createUA({remoteAddress:t,extraHeaders:n,...r}){let i=new this.JsSIP.UA(r),a=e.buildExtraHeaders(t,n);return a.length>0&&i.registrator().setExtraHeaders(a),i}createUAWithConfiguration(e,t){let{configuration:n,helpers:r}=this.createConfiguration(e),i=this.createUA({...n,remoteAddress:e.remoteAddress,extraHeaders:e.extraHeaders});return t.eachTriggers((e,t)=>{let n=pt.find(e=>e===t);n&&i.on(n,e)}),{ua:i,helpers:r}}},Dt=_(`ConnectionManager`),Ot=class extends l.EventEmitterProxy{stateMachine;ua;socket;uaFactory;registrationManager;connectionFlow;sipOperations;constructor({JsSIP:e},{numberOfConnectionAttempts:t}={}){super(gt()),this.uaFactory=new Et(e),this.registrationManager=new vt({events:this.events,getUaProtected:this.getUaProtected}),this.stateMachine=new ft(this.events),this.sipOperations=new bt({uaFactory:this.uaFactory,getUaProtected:this.getUaProtected}),this.connectionFlow=new st({events:this.events,uaFactory:this.uaFactory,stateMachine:this.stateMachine,registrationManager:this.registrationManager,getUa:this.getUa,setUa:e=>{this.ua=e},setGetUri:e=>{this.getUri=e},setSocket:e=>{this.socket=e}},{numberOfConnectionAttempts:t})}get requested(){return this.stateMachine.isPending}get isPendingConnect(){return this.stateMachine.isPendingConnect}get isPendingInitUa(){return this.stateMachine.isPendingInitUa}get isIdle(){return this.stateMachine.isIdle}get isDisconnected(){return this.stateMachine.isDisconnected}get isDisconnecting(){return this.stateMachine.isDisconnecting}get connectionState(){return this.stateMachine.state}get isRegistered(){return Et.isRegisteredUA(this.ua)}get isRegisterConfig(){return this.stateMachine.isRegisterEnabled()}connect=async(e,t)=>this.disconnect().catch(e=>{Dt(`connect: disconnect error`,e)}).then(async()=>this.connectWithProcessError(e,t));disconnect=async()=>{if(this.isConfigured()||this.requested)return this.connectionFlow.disconnect()};async register(){return this.registrationManager.register()}async unregister(){return this.registrationManager.unregister()}tryRegister=async()=>this.registrationManager.tryRegister();sendOptions=async(e,t,n)=>this.sipOperations.sendOptions(e,t,n);ping=async(e,t)=>this.sipOperations.ping(e,t);checkTelephony=async e=>this.sipOperations.checkTelephony(e);isConfigured(){return this.ua!==void 0}getConnectionConfiguration=()=>this.stateMachine.getConnectionConfiguration();destroy(){this.stateMachine.destroy()}getUri=e=>e;getUser(){try{return this.getUaProtected().configuration.uri.user}catch{return}}getUaProtected=()=>{if(!this.ua)throw Error(`UA not initialized`);return this.ua};getUa=()=>this.ua;connectWithProcessError=async(e,t)=>{if(!(t?.hasReadyForConnection?.()??!0))throw rt();return this.connectionFlow.connect(e,t).catch(async e=>{let t=e;return this.disconnect().then(()=>{throw t}).catch(()=>{throw t})})}},kt=class{connectionManager;stackPromises=(0,h.createStackPromises)({noRunIsNotActual:!0});constructor({connectionManager:e}){this.connectionManager=e}connect=async(...e)=>this.stackPromises.run(async()=>this.connectionManager.connect(...e));disconnect=async()=>(this.stop(),this.connectionManager.disconnect());stop(){this.stackPromises.stop()}},j=e=>{if(typeof e==`object`&&e&&`error`in e)return e.error},M=_(`AutoConnectorManager: createAutoConnectorMachineSetup`),At=e=>e.parameters,jt=e=>(0,p.setup)({types:{context:{},events:{}},actors:{stopConnectionFlow:(0,p.fromPromise)(async()=>{M(`stopConnectionFlow`),await e.stopConnectionFlow()}),connect:(0,p.fromPromise)(async({input:t})=>{if(M(`connect`,t),!t)throw Error(`Auto connector parameters are missing in attemptingConnect state`);await e.connect(t)}),waitBeforeRetry:(0,p.fromPromise)(async()=>{M(`waitBeforeRetry`),await e.delayBetweenAttempts()})},guards:{shouldDisconnectBeforeAttempt:()=>{let t=e.shouldDisconnectBeforeAttempt();return M(`shouldDisconnectBeforeAttempt:`,t),t},shouldGoIdleAfterDisconnect:({context:e})=>{let t=e.afterDisconnect===`idle`;return M(`shouldGoIdleAfterDisconnect:`,t),t},shouldAttemptAfterDisconnect:({context:e})=>{let t=e.afterDisconnect===`attempt`;return M(`shouldAttemptAfterDisconnect:`,t),t},isLimitReached:()=>{let t=e.hasLimitReached();return M(`isLimitReached:`,t),t},isNotReadyForConnection:({event:e})=>{let t=nt(j(e));return M(`isNotReadyForConnection:`,t),t},isNoRetryPolicy:({event:t})=>{let n=!e.canRetryOnError(j(t));return M(`isNoRetryPolicy:`,n),n},isNotActualPromise:({event:e})=>{let t=(0,h.isPromiseIsNotActualError)(j(e));return M(`isNotActualPromise:`,t),t},isWaitRetryCancelled:({event:e})=>{let t=j(e),n=(0,f.isCanceledError)(t)||(0,d.hasCanceledError)(t);return M(`isWaitRetryCancelled:`,n),n}},actions:{logRestartFailed:({event:e})=>{M(`auto connector failed to restart connection attempts:`,j(e))},assignRestart:(0,p.assign)(({event:e})=>({parameters:e.parameters,afterDisconnect:`attempt`,stopReason:void 0,lastError:void 0})),assignStop:(0,p.assign)({afterDisconnect:`idle`,stopReason:()=>{},lastError:()=>{}}),entryAttemptingGate:()=>{M(`entryAttemptingGate`),e.beforeAttempt()},entryAttemptingConnect:()=>{M(`entryAttemptingConnect`),e.beforeConnectAttempt()},onLimitReachedTransition:({context:t})=>{M(`onLimitReachedTransition`),e.onLimitReached(At(t))},onConnectDone:({context:t})=>{M(`onConnectDone`),e.onConnectSucceeded(At(t))},assignHaltedError:(0,p.assign)({stopReason:()=>`halted`,lastError:({event:e})=>{let t=j(e);return M(`assignHaltedError`,t),t}}),assignCancelledNotActualError:(0,p.assign)({stopReason:()=>`cancelled`,lastError:({event:e})=>{let t=j(e);return M(`assignCancelledNotActualError`,t),t}}),assignWaitRetryCancelledError:(0,p.assign)({stopReason:()=>`cancelled`,lastError:({event:e})=>{let t=j(e);return M(`assignWaitRetryCancelledError`,t),t}}),assignWaitRetryFailedError:(0,p.assign)({stopReason:()=>`failed`,lastError:({event:e})=>{let t=j(e);return M(`assignWaitRetryFailedError`,t),t}}),emitTerminalOutcome:({context:t})=>{M(`emitTerminalOutcome`),e.emitTerminalOutcome({stopReason:t.stopReason,lastError:t.lastError})},onTelephonyStillConnected:()=>{M(`onTelephonyStillConnected`),e.onTelephonyStillConnected()}}}),N=function(e){return e.IDLE=`idle`,e.DISCONNECTING=`disconnecting`,e.ATTEMPTING_GATE=`attemptingGate`,e.ATTEMPTING_CONNECT=`attemptingConnect`,e.WAITING_BEFORE_RETRY=`waitingBeforeRetry`,e.CONNECTED_MONITORING=`connectedMonitoring`,e.TELEPHONY_CHECKING=`telephonyChecking`,e.ERROR_TERMINAL=`errorTerminal`,e}({}),Mt=()=>({parameters:void 0,afterDisconnect:`idle`,stopReason:void 0,lastError:void 0}),Nt=()=>({"AUTO.STOP":{target:N.DISCONNECTING,actions:`assignStop`},"AUTO.RESTART":{target:N.DISCONNECTING,actions:`assignRestart`}}),Pt=e=>jt(e).createMachine({id:`autoConnector`,initial:N.IDLE,context:Mt,states:{[N.IDLE]:{on:{"AUTO.STOP":{target:N.IDLE},"AUTO.RESTART":[{guard:`shouldDisconnectBeforeAttempt`,target:N.DISCONNECTING,actions:`assignRestart`},{target:N.ATTEMPTING_GATE,actions:`assignRestart`}]}},[N.DISCONNECTING]:{invoke:{id:`stopConnectionFlow`,src:`stopConnectionFlow`,onDone:[{guard:`shouldGoIdleAfterDisconnect`,target:N.IDLE},{guard:`shouldAttemptAfterDisconnect`,target:N.ATTEMPTING_GATE}],onError:{actions:`logRestartFailed`,target:N.IDLE}},on:{"AUTO.STOP":{target:N.DISCONNECTING,reenter:!0,actions:`assignStop`},"AUTO.RESTART":{actions:`assignRestart`}}},[N.ATTEMPTING_GATE]:{entry:`entryAttemptingGate`,always:[{guard:`isLimitReached`,target:N.TELEPHONY_CHECKING,actions:`onLimitReachedTransition`},{target:N.ATTEMPTING_CONNECT}],on:Nt()},[N.ATTEMPTING_CONNECT]:{entry:`entryAttemptingConnect`,invoke:{id:`connect`,src:`connect`,input:({context:e})=>e.parameters,onDone:{target:N.CONNECTED_MONITORING,actions:`onConnectDone`},onError:[{guard:`isNotReadyForConnection`,target:`errorTerminal`,actions:`assignHaltedError`},{guard:`isNoRetryPolicy`,target:`errorTerminal`,actions:`assignHaltedError`},{guard:`isNotActualPromise`,target:`errorTerminal`,actions:`assignCancelledNotActualError`},{target:N.WAITING_BEFORE_RETRY}]},on:Nt()},[N.WAITING_BEFORE_RETRY]:{invoke:{id:`waitBeforeRetry`,src:`waitBeforeRetry`,onDone:{target:N.ATTEMPTING_GATE},onError:[{guard:`isWaitRetryCancelled`,target:`errorTerminal`,actions:`assignWaitRetryCancelledError`},{target:`errorTerminal`,actions:`assignWaitRetryFailedError`}]},on:Nt()},[N.CONNECTED_MONITORING]:{on:Nt()},[N.TELEPHONY_CHECKING]:{on:{"AUTO.STOP":{target:N.DISCONNECTING,actions:`assignStop`},"AUTO.RESTART":{target:N.DISCONNECTING,actions:`assignRestart`},"TELEPHONY.RESULT":{target:N.CONNECTED_MONITORING,actions:`onTelephonyStillConnected`}}},[N.ERROR_TERMINAL]:{entry:`emitTerminalOutcome`,on:Nt()}}}),Ft=_(`AutoConnectorManager: AutoConnectorStateMachine`),It=class extends et{constructor(e){super(e)}send(e){if(!this.actor.getSnapshot().can(e)){Ft(`[AutoConnectorStateMachine] Invalid transition: ${e.type} from ${String(this.state)}. Event cannot be processed in current state.`);return}super.send(e)}toStop(){this.send({type:`AUTO.STOP`})}toRestart(e){this.send({type:`AUTO.RESTART`,parameters:e})}toTelephonyResult(e){this.send({type:`TELEPHONY.RESULT`,outcome:e})}toTelephonyResultStillConnected(){this.toTelephonyResult(`stillConnected`)}isInIdleState(){return this.state===N.IDLE}isInConnectedMonitoringState(){return this.state===N.CONNECTED_MONITORING}isInWaitingBeforeRetryState(){return this.state===N.WAITING_BEFORE_RETRY}},Lt=e=>new It(Pt(e)),Rt=new Set([401,403]),zt=e=>typeof e==`object`&&!!e&&`response`in e,Bt=e=>{if(!zt(e))return!1;let t=e.response?.status_code;return typeof t==`number`&&Rt.has(t)},Vt=e=>!Bt(e),Ht=e=>{if(e&&Object.hasOwn(e,`windowRef`))return e.windowRef;if(!(typeof window>`u`))return window},Ut=e=>{if(e&&Object.hasOwn(e,`navigatorRef`))return e.navigatorRef;if(!(typeof navigator>`u`))return navigator},Wt=e=>{let t=Ht(e),n=Ut(e);if(!t)return;let r=[],i=()=>{r.forEach(e=>{e()}),r=[]};return{subscribe:e=>{i();let a=()=>{e.onOnline()},o=()=>{e.onOffline()},s=()=>{e.onChange()};t.addEventListener(`online`,a),t.addEventListener(`offline`,o);let c=n?.connection;c?.addEventListener(`change`,s),r=[()=>{t.removeEventListener(`online`,a)},()=>{t.removeEventListener(`offline`,o)},()=>{c?.removeEventListener(`change`,s)}]},unsubscribe:i}},Gt=`Failed to reconnect`,Kt=e=>e instanceof Error?e:Error(Gt),qt=e=>{let t=t=>e.baseCanRetryOnError(t)?e.canRetryOnError?.(t)??!0:!1,n=({stopReason:e,lastError:t})=>e===`cancelled`&&!(0,h.isPromiseIsNotActualError)(t)||e===`failed`?Kt(t):t;return{canRetryOnError:t,shouldDisconnectBeforeAttempt:()=>e.runtime.shouldDisconnectBeforeAttempt(),stopConnectionFlow:async()=>{await e.runtime.stopConnectionFlow()},connect:async t=>{await e.runtime.connect(t)},delayBetweenAttempts:async()=>{await e.runtime.delayBeforeRetry()},hasLimitReached:()=>e.runtime.hasLimitReached(),beforeAttempt:()=>{e.runtime.beforeAttempt()},beforeConnectAttempt:()=>{e.runtime.beforeConnectAttempt()},onLimitReached:t=>{e.runtime.onLimitReached(t)},onConnectSucceeded:t=>{e.runtime.onConnectSucceeded(t)},emitTerminalOutcome:({stopReason:t,lastError:r})=>{e.runtime.emitTerminalOutcome({stopReason:t,lastError:n({stopReason:t,lastError:r})})},onTelephonyStillConnected:()=>{e.runtime.onTelephonyStillConnected()}}},P=function(e){return e.BEFORE_ATTEMPT=`before-attempt`,e.SUCCESS=`success`,e.FAILED_ALL_ATTEMPTS=`failed-all-attempts`,e.CANCELLED_ATTEMPTS=`cancelled-attempts`,e.CHANGED_ATTEMPT_STATUS=`changed-attempt-status`,e.STOP_ATTEMPTS_BY_ERROR=`stop-attempts-by-error`,e.LIMIT_REACHED_ATTEMPTS=`limit-reached-attempts`,e.TELEPHONY_CHECK_FAILURE=`telephony-check-failure`,e.TELEPHONY_CHECK_ESCALATED=`telephony-check-escalated`,e}(P||{}),Jt=[`${P.BEFORE_ATTEMPT}`,`${P.SUCCESS}`,`${P.FAILED_ALL_ATTEMPTS}`,`${P.CANCELLED_ATTEMPTS}`,`${P.CHANGED_ATTEMPT_STATUS}`,`${P.STOP_ATTEMPTS_BY_ERROR}`,`${P.LIMIT_REACHED_ATTEMPTS}`,`${P.TELEPHONY_CHECK_FAILURE}`,`${P.TELEPHONY_CHECK_ESCALATED}`],Yt=()=>new l.TypedEvents(Jt),Xt=_(`AutoConnectorManager: NetworkEventsReconnector`),Zt=2e3,Qt=`probe`,$t=`network-online`,en=`network-change`,tn=class{subscriber;offlineGraceMs;onChangePolicy;onOnlinePolicy;probe;requestReconnect;stopConnection;parameters;offlineTimer;isSubscribed=!1;isProbeInFlight=!1;constructor({subscriber:e,offlineGraceMs:t,onChangePolicy:n,onOnlinePolicy:r,probe:i,requestReconnect:a,stopConnection:o}){this.subscriber=e,this.offlineGraceMs=t??Zt,this.onChangePolicy=n??Qt,this.onOnlinePolicy=r??Qt,this.probe=i,this.requestReconnect=a,this.stopConnection=o}start(e){this.parameters=e,!this.isSubscribed&&(this.subscriber.subscribe({onChange:this.handleChange,onOnline:this.handleOnline,onOffline:this.handleOffline}),this.isSubscribed=!0)}setParameters(e){this.parameters=e}stop(){this.cancelOfflineTimer(),this.isSubscribed&&(this.subscriber.unsubscribe(),this.isSubscribed=!1,this.parameters=void 0)}handleOnline=()=>{Xt(`network online`,{policy:this.onOnlinePolicy}),this.cancelOfflineTimer(),this.applyPolicy(this.onOnlinePolicy,$t)};handleChange=()=>{Xt(`network change`,{policy:this.onChangePolicy}),this.applyPolicy(this.onChangePolicy,en)};handleOffline=()=>{Xt(`network offline, scheduling disconnect`,{graceMs:this.offlineGraceMs}),this.cancelOfflineTimer(),this.offlineTimer=setTimeout(()=>{this.offlineTimer=void 0,Xt(`network offline grace window elapsed, stopping active connection`),this.stopConnection()},this.offlineGraceMs)};applyPolicy(e,t){if(e===`ignore`){Xt(`policy=ignore, skipping`,{reason:t});return}if(e===`reconnect`||!this.probe){this.requestReconnectIfAvailable(t);return}if(this.isProbeInFlight){Xt(`probe already in flight, skipping duplicate`,{reason:t});return}this.isProbeInFlight=!0,this.probe().then(e=>{Xt(`probe result`,{reason:t,isReachable:e}),e||this.requestReconnectIfAvailable(t)}).catch(e=>{Xt(`probe threw, requesting reconnect`,{reason:t,error:e}),this.requestReconnectIfAvailable(t)}).finally(()=>{this.isProbeInFlight=!1})}requestReconnectIfAvailable(e){if(!this.parameters){Xt(`skipping reconnect: no parameters`,{reason:e});return}this.requestReconnect(this.parameters,e)}cancelOfflineTimer(){this.offlineTimer!==void 0&&(clearTimeout(this.offlineTimer),this.offlineTimer=void 0)}},nn=class{generation=0;lastRequest;coalesceWindowMs;constructor({coalesceWindowMs:e}){this.coalesceWindowMs=e}register(e){let t=Date.now(),n=Xe(e),{lastRequest:r}=this;if(r!==void 0&&t-r.timestamp<this.coalesceWindowMs){let e=Xe(r.reason);if(n<=e)return{shouldRequest:!1,generation:this.generation,currentPriority:n,coalescedBy:r.reason,coalescedByPriority:e}}return this.generation+=1,this.lastRequest={reason:e,timestamp:t},{shouldRequest:!0,generation:this.generation,currentPriority:n}}reset(){this.lastRequest=void 0}},rn=250,an={LIMIT_REACHED:`Limit reached`},F=_(`AutoConnectorManager`),on=`start`,sn=`manual-restart`,cn=class extends l.EventEmitterProxy{stateMachine;stopSettledPromise;runtime;connectionManager;reconnectCoalescer=new nn({coalesceWindowMs:rn});networkEventsReconnector;constructor({connectionQueueManager:e,connectionManager:t,callManager:n},r){super(Yt()),this.connectionManager=t,this.runtime=new $e({connectionManager:t,connectionQueueManager:e,callManager:n,options:r,emitters:{emitBeforeAttempt:()=>{this.events.trigger(`before-attempt`,{})},emitLimitReachedAttempts:()=>{this.events.trigger(`limit-reached-attempts`,Error(an.LIMIT_REACHED))},emitSuccess:()=>{F(`handleSucceededAttempt`),this.events.trigger(`success`)},emitStopAttemptsByError:e=>{this.events.trigger(`stop-attempts-by-error`,e)},emitCancelledAttempts:e=>{this.events.trigger(`cancelled-attempts`,e)},emitFailedAllAttempts:e=>{this.events.trigger(`failed-all-attempts`,e)},emitTelephonyCheckFailure:e=>{this.events.trigger(`telephony-check-failure`,e)},emitTelephonyCheckEscalated:e=>{this.events.trigger(`telephony-check-escalated`,e)},emitStatusChange:({isInProgress:e})=>{this.events.trigger(`changed-attempt-status`,{isInProgress:e})}},reconnectActions:{requestReconnect:this.requestReconnect,notifyTelephonyStillConnected:()=>{this.stateMachine.toTelephonyResultStillConnected()}}}),this.stateMachine=Lt(qt({baseCanRetryOnError:Vt,runtime:this.runtime,canRetryOnError:r?.canRetryOnError}));let i=r?.networkEventsSubscriber??Wt();i&&(this.networkEventsReconnector=new tn({subscriber:i,offlineGraceMs:r?.offlineGraceMs,onChangePolicy:r?.onNetworkChangePolicy,onOnlinePolicy:r?.onNetworkOnlinePolicy,probe:this.probeServerReachability,requestReconnect:this.requestReconnect,stopConnection:()=>{this.stateMachine.toStop()}}))}async start(e){return F(`auto connector start`),this.isStarted()?(F(`auto connector start skipped: already started. Use restart() for force reconnect or stop() before next start()`),{isSuccess:!1,reason:`coalesced`}):this.requestReconnect(e,on)?(this.networkEventsReconnector?.start(e),new Promise(e=>{let t=this.events.onceRace([`success`,`failed-all-attempts`,`stop-attempts-by-error`,`limit-reached-attempts`],(n,r)=>{if(t(),r===`success`){e({isSuccess:!0,reason:`started`});return}if(r===`failed-all-attempts`){e({isSuccess:!1,reason:`failed-all-attempts`,error:n});return}if(r===`stop-attempts-by-error`){e({isSuccess:!1,reason:`stop-attempts-by-error`,error:n});return}e({isSuccess:!1,reason:`limit-reached-attempts`,error:n})})})):{isSuccess:!1,reason:`coalesced`}}restart(){F(`auto connector restart`);let{parameters:e}=this.stateMachine.context;if(!e){F(`auto connector restart skipped: no parameters in context`);return}this.requestReconnect(e,sn)}async stop(){if(this.stopSettledPromise){F(`auto connector stop skipped: already in progress`),await this.stopSettledPromise;return}this.stopSettledPromise=(async()=>{F(`auto connector stop`),this.networkEventsReconnector?.stop(),this.resetReconnectCoalescingState(),this.stateMachine.toStop(),!this.stateMachine.isInIdleState()&&await new Promise(e=>{let t=this.stateMachine.onStateChange(()=>{this.stateMachine.isInIdleState()&&(t(),e())})})})();try{await this.stopSettledPromise}finally{this.stopSettledPromise=void 0}}cancelPendingRetry(){this.runtime.cancelPendingRetry()}requestReconnect=(e,t)=>{let n=this.shouldRequestReconnect(t);return F(`auto connector requestReconnect`,{isAvailableToRestart:n,reason:t}),n?(this.networkEventsReconnector?.setParameters(e),this.stateMachine.toRestart(e),!0):!1};probeServerReachability=async()=>{if(this.stateMachine.isInConnectedMonitoringState()){F(`probeServerReachability: isInConnectedMonitoringState`);try{return await this.connectionManager.ping(),!0}catch(e){return F(`probeServerReachability: ping failed`,e),!1}}if(this.stateMachine.isInWaitingBeforeRetryState()){F(`probeServerReachability: isInWaitingBeforeRetryState`);let{parameters:e}=this.stateMachine.context;try{let t=await e.getParameters();return await this.connectionManager.checkTelephony(t),!1}catch(e){return F(`probeServerReachability: checkTelephony failed`,e),!0}}return F(`probeServerReachability: default return false`),!1};shouldRequestReconnect(e){let t=this.reconnectCoalescer.register(e);return t.shouldRequest?(F(`auto connector reconnect requested: ${e}`,{state:String(this.stateMachine.state),generation:t.generation}),!0):(F(`auto connector reconnect coalesced: ${e}`,{state:String(this.stateMachine.state),coalescedBy:t.coalescedBy,currentPriority:t.currentPriority,coalescedByPriority:t.coalescedByPriority}),!1)}resetReconnectCoalescingState(){this.reconnectCoalescer.reset()}isStarted(){return!this.stateMachine.isInIdleState()}},ln=0,un=0,dn=class{countInner=ln;initialCount=ln;limitInner;isInProgress=!1;onStatusChange;constructor(e){this.limitInner=e.limit,this.onStatusChange=e.onStatusChange}get count(){return this.countInner}get limit(){return this.limitInner}get isAttemptInProgress(){return this.isInProgress}hasLimitReached(){return this.limitInner===un?!1:this.countInner>=this.limitInner}startAttempt(){this.isInProgress||(this.isInProgress=!0,this.onStatusChange({isInProgress:this.isInProgress}))}finishAttempt(){this.isInProgress&&(this.isInProgress=!1,this.onStatusChange({isInProgress:this.isInProgress}))}increment(){this.countInner+=1}reset(){this.countInner=this.initialCount,this.finishAttempt()}},fn=1,pn=e=>e<fn?fn:e,mn=(e,t)=>{let{baseBackoffMs:n,maxBackoffMs:r,backoffFactor:i}=t,a=n*i**(pn(e)-1);return Math.min(r,a)},hn=(e,t,n)=>{if(t===`none`)return e;if(t===`full`)return n()*e;let r=e/2;return r+n()*r},gn=(e,t,n=Math.random)=>hn(mn(e,t),t.jitter,n),_n=new Set([g.C.causes.CONNECTION_ERROR,g.C.causes.REQUEST_TIMEOUT,g.C.causes.RTP_TIMEOUT,g.C.causes.ADDRESS_INCOMPLETE]),vn=e=>{let{cause:t,originator:n}=e;return n===`local`?!1:!!(_n.has(t)||t===g.C.causes.INTERNAL_ERROR&&n===`system`)},yn=e=>e??vn,bn=_(`CallReconnectRuntime`),xn={maxAttempts:5,baseBackoffMs:1e3,maxBackoffMs:3e4,backoffFactor:2,jitter:`equal`,waitSignalingTimeoutMs:2e4},Sn=e=>({maxAttempts:e?.maxAttempts??xn.maxAttempts,baseBackoffMs:e?.baseBackoffMs??xn.baseBackoffMs,maxBackoffMs:e?.maxBackoffMs??xn.maxBackoffMs,backoffFactor:e?.backoffFactor??xn.backoffFactor,jitter:e?.jitter??xn.jitter,waitSignalingTimeoutMs:e?.waitSignalingTimeoutMs??xn.waitSignalingTimeoutMs}),Cn=e=>!0,wn=class{resolvedOptions;callManager;connectionManager;attemptsState;delayRequester;performCall;isNetworkFailureFn;canRetryOnErrorFn;unsubscribeConnectionWait;constructor(e){this.resolvedOptions=Sn(e.options),this.callManager=e.callManager,this.connectionManager=e.connectionManager,this.isNetworkFailureFn=yn(e.options?.isNetworkFailure),this.canRetryOnErrorFn=e.options?.canRetryOnError??Cn,this.delayRequester=new d.DelayRequester(this.resolvedOptions.baseBackoffMs),this.performCall=new f.CancelableRequest(async e=>{let t=await e.getCallParameters();await this.callManager.startCall(this.connectionManager.getUaProtected(),this.connectionManager.getUri.bind(this.connectionManager),t)}),this.attemptsState=new dn({limit:this.resolvedOptions.maxAttempts,onStatusChange:({isInProgress:t})=>{e.emitters.emitStatusChange({isReconnecting:t})}})}isNetworkFailure(e){return this.isNetworkFailureFn(e)}canRetryOnError(e){return this.canRetryOnErrorFn(e)}isSignalingReady(){return this.connectionManager.isRegistered}hasLimitReached(){return this.attemptsState.hasLimitReached()}computeNextDelayMs(e){return gn(e,{baseBackoffMs:this.resolvedOptions.baseBackoffMs,maxBackoffMs:this.resolvedOptions.maxBackoffMs,backoffFactor:this.resolvedOptions.backoffFactor,jitter:this.resolvedOptions.jitter})}async delayBeforeAttempt(e){bn(`delayBeforeAttempt`,e),await this.delayRequester.request(e)}async waitSignalingReady(){if(this.connectionManager.isRegistered)return;let e=this.resolvedOptions.waitSignalingTimeoutMs;await new Promise((t,n)=>{let r,i,a=()=>{r!==void 0&&globalThis.clearTimeout(r),i!==void 0&&(this.connectionManager.off(`connected`,i),this.connectionManager.off(`registered`,i)),this.unsubscribeConnectionWait=void 0};i=()=>{a(),t()},r=globalThis.setTimeout(()=>{a(),n(Error(`Wait signaling ready timeout after ${e}ms`))},e),this.unsubscribeConnectionWait=a,this.connectionManager.on(`connected`,i),this.connectionManager.on(`registered`,i)})}async performAttempt(e){await this.performCall.request(e)}registerAttemptStart(){this.attemptsState.increment(),this.attemptsState.startAttempt()}registerAttemptFinish(){this.attemptsState.finishAttempt()}resetAttemptsState(){this.attemptsState.reset()}cancelAll(){bn(`cancelAll`),this.delayRequester.cancelRequest(),this.performCall.cancelRequest(),this.unsubscribeConnectionWait?.(),this.unsubscribeConnectionWait=void 0}getWaitSignalingTimeoutMs(){return this.resolvedOptions.waitSignalingTimeoutMs}},Tn=e=>{if(typeof e==`object`&&e&&`error`in e)return e.error},En=_(`CallReconnectMachine`),Dn=e=>e.parameters,On=e=>(0,p.setup)({types:{context:{},events:{}},actors:{delayBeforeAttempt:(0,p.fromPromise)(async({input:t})=>{En(`delayBeforeAttempt`,t),await e.delayBeforeAttempt(t)}),waitSignalingReady:(0,p.fromPromise)(async()=>{En(`waitSignalingReady`),await e.waitSignalingReady()}),performAttempt:(0,p.fromPromise)(async({input:t})=>{if(En(`performAttempt`),!t)throw Error(`CallReconnect parameters missing in attempting state`);await e.performAttempt(t)})},guards:{isNetworkFailure:({event:t})=>{let n=t;return e.isNetworkFailure(n.event)},isLimitReached:()=>e.hasLimitReached(),isSignalingReady:()=>e.isSignalingReady(),isNoRetryPolicy:({event:t})=>!e.canRetryOnError(Tn(t)),isAttemptCancelled:({event:e})=>{let t=Tn(e);return(0,f.isCanceledError)(t)||(0,d.hasCanceledError)(t)}},actions:{assignArm:(0,p.assign)(({event:e})=>({parameters:e.parameters,attempt:0,nextDelayMs:0,lastError:void 0,lastFailureCause:void 0,cancelledReason:void 0})),assignDisarm:(0,p.assign)(({event:e})=>({parameters:void 0,attempt:0,nextDelayMs:0,lastError:void 0,lastFailureCause:void 0,cancelledReason:e.reason??`disarm`})),assignFailureDetected:(0,p.assign)(({event:e})=>({lastFailureCause:e.event.cause})),assignNextDelay:(0,p.assign)(({context:t})=>{let n=t.attempt+1;return{nextDelayMs:e.computeNextDelayMs(n)}}),assignIncrementAttempt:(0,p.assign)(({context:e})=>({attempt:e.attempt+1})),assignResetAttempt:(0,p.assign)({attempt:()=>0,nextDelayMs:()=>0,lastError:()=>{},lastFailureCause:()=>{}}),assignAttemptError:(0,p.assign)({lastError:({event:e})=>Tn(e)}),emitArmedAction:()=>{e.emitArmed()},emitDisarmedAction:({context:t})=>{e.emitDisarmed();let{cancelledReason:n}=t;n!==void 0&&e.emitCancelled({reason:n})},emitFailureDetectedAction:({context:t,event:n})=>{let r=n;e.emitFailureDetected({cause:r.event.cause,originator:r.event.originator,attempt:t.attempt})},emitAttemptScheduledAction:({context:t})=>{e.emitAttemptScheduled({attempt:t.attempt+1,delayMs:t.nextDelayMs})},emitAttemptStartedAction:({context:t})=>{e.emitAttemptStarted({attempt:t.attempt})},emitAttemptSucceededAction:({context:t})=>{e.emitAttemptSucceeded({attempt:t.attempt})},emitAttemptFailedAction:({context:t,event:n})=>{e.emitAttemptFailed({attempt:t.attempt,error:Tn(n)})},emitWaitingSignalingAction:()=>{e.emitWaitingSignaling({timeoutMs:e.getWaitSignalingTimeoutMs()})},emitLimitReachedAction:({context:t})=>{e.emitLimitReached({attempts:t.attempt})},registerAttemptStart:()=>{e.registerAttemptStart()},registerAttemptFinish:()=>{e.registerAttemptFinish()},resetAttemptsState:()=>{e.resetAttemptsState()},cancelAll:()=>{e.cancelAll()}}}),I=function(e){return e.IDLE=`idle`,e.ARMED=`armed`,e.EVALUATING=`evaluating`,e.BACKOFF=`backoff`,e.WAITING_SIGNALING=`waitingSignaling`,e.ATTEMPTING=`attempting`,e.LIMIT_REACHED=`limitReached`,e.ERROR_TERMINAL=`errorTerminal`,e}({}),kn=()=>({parameters:void 0,attempt:0,nextDelayMs:0,lastError:void 0,lastFailureCause:void 0,cancelledReason:void 0}),An=e=>On(e).createMachine({id:`callReconnect`,initial:I.IDLE,context:kn,on:{"RECONNECT.ARM":{target:`.${I.ARMED}`,actions:[`cancelAll`,`resetAttemptsState`,`assignArm`,`emitArmedAction`]},"RECONNECT.DISARM":{target:`.${I.IDLE}`,actions:[`cancelAll`,`resetAttemptsState`,`registerAttemptFinish`,`assignDisarm`,`emitDisarmedAction`]}},states:{[I.IDLE]:{on:{"RECONNECT.DISARM":{target:I.IDLE}}},[I.ARMED]:{on:{"CALL.FAILED":{guard:`isNetworkFailure`,target:I.EVALUATING,actions:[`assignFailureDetected`,`emitFailureDetectedAction`]},"CALL.ENDED":{target:I.IDLE,actions:[`cancelAll`,`resetAttemptsState`,`assignDisarm`,`emitDisarmedAction`]}}},[I.EVALUATING]:{always:[{guard:`isLimitReached`,target:I.LIMIT_REACHED,actions:[`emitLimitReachedAction`]},{guard:`isSignalingReady`,target:I.BACKOFF,actions:[`assignNextDelay`,`emitAttemptScheduledAction`]},{target:I.WAITING_SIGNALING,actions:[`emitWaitingSignalingAction`]}]},[I.BACKOFF]:{invoke:{id:`delayBeforeAttempt`,src:`delayBeforeAttempt`,input:({context:e})=>e.nextDelayMs,onDone:{target:I.ATTEMPTING},onError:{target:I.ARMED}},on:{"CONN.DISCONNECTED":{target:I.WAITING_SIGNALING,actions:[`emitWaitingSignalingAction`]}}},[I.WAITING_SIGNALING]:{invoke:{id:`waitSignalingReady`,src:`waitSignalingReady`,onDone:{target:I.BACKOFF,actions:[`assignNextDelay`,`emitAttemptScheduledAction`]},onError:[{guard:`isAttemptCancelled`,target:I.ARMED},{target:I.ERROR_TERMINAL,actions:`assignAttemptError`}]},on:{"CONN.CONNECTED":{target:I.BACKOFF,actions:[`assignNextDelay`,`emitAttemptScheduledAction`]}}},[I.ATTEMPTING]:{entry:[`assignIncrementAttempt`,`registerAttemptStart`,`emitAttemptStartedAction`],invoke:{id:`performAttempt`,src:`performAttempt`,input:({context:e})=>Dn(e),onDone:{target:I.ARMED,actions:[`registerAttemptFinish`,`assignResetAttempt`,`resetAttemptsState`,`emitAttemptSucceededAction`]},onError:[{guard:`isAttemptCancelled`,target:I.ARMED,actions:[`registerAttemptFinish`]},{guard:`isNoRetryPolicy`,target:I.ERROR_TERMINAL,actions:[`registerAttemptFinish`,`emitAttemptFailedAction`,`assignAttemptError`]},{target:I.EVALUATING,actions:[`registerAttemptFinish`,`emitAttemptFailedAction`]}]}},[I.LIMIT_REACHED]:{on:{"RECONNECT.FORCE":{target:I.EVALUATING,actions:[`resetAttemptsState`,`assignResetAttempt`]}}},[I.ERROR_TERMINAL]:{on:{"RECONNECT.FORCE":{target:I.EVALUATING,actions:[`resetAttemptsState`,`assignResetAttempt`]}}}}}),jn=_(`CallReconnectStateMachine`),Mn=class extends et{constructor(e){super(e)}send(e){if(!this.actor.getSnapshot().can(e)){jn(`[CallReconnectStateMachine] Invalid transition: ${e.type} from ${String(this.state)}. Event cannot be processed in current state.`);return}super.send(e)}},Nn=e=>new Mn(An(e)),Pn=e=>{let{runtime:t,events:n}=e;return{isNetworkFailure:e=>t.isNetworkFailure(e),canRetryOnError:e=>t.canRetryOnError(e),isSignalingReady:()=>t.isSignalingReady(),hasLimitReached:()=>t.hasLimitReached(),computeNextDelayMs:e=>t.computeNextDelayMs(e),delayBeforeAttempt:async e=>{await t.delayBeforeAttempt(e)},waitSignalingReady:async()=>{await t.waitSignalingReady()},performAttempt:async e=>{await t.performAttempt(e)},registerAttemptStart:()=>{t.registerAttemptStart()},registerAttemptFinish:()=>{t.registerAttemptFinish()},resetAttemptsState:()=>{t.resetAttemptsState()},emitArmed:()=>{n.trigger(`armed`,{})},emitDisarmed:()=>{n.trigger(`disarmed`,{})},emitFailureDetected:e=>{n.trigger(`failure-detected`,e)},emitAttemptScheduled:e=>{n.trigger(`attempt-scheduled`,e)},emitAttemptStarted:e=>{n.trigger(`attempt-started`,e)},emitAttemptSucceeded:e=>{n.trigger(`attempt-succeeded`,e)},emitAttemptFailed:e=>{n.trigger(`attempt-failed`,e)},emitWaitingSignaling:e=>{n.trigger(`waiting-signaling`,e)},emitLimitReached:e=>{n.trigger(`limit-reached`,e)},emitCancelled:e=>{n.trigger(`cancelled`,e)},cancelAll:()=>{t.cancelAll()},getWaitSignalingTimeoutMs:()=>t.getWaitSignalingTimeoutMs()}},L=function(e){return e.ARMED=`armed`,e.DISARMED=`disarmed`,e.FAILURE_DETECTED=`failure-detected`,e.ATTEMPT_SCHEDULED=`attempt-scheduled`,e.ATTEMPT_STARTED=`attempt-started`,e.ATTEMPT_SUCCEEDED=`attempt-succeeded`,e.ATTEMPT_FAILED=`attempt-failed`,e.WAITING_SIGNALING=`waiting-signaling`,e.LIMIT_REACHED=`limit-reached`,e.CANCELLED=`cancelled`,e.STATUS_CHANGED=`status-changed`,e}(L||{}),Fn=[`${L.ARMED}`,`${L.DISARMED}`,`${L.FAILURE_DETECTED}`,`${L.ATTEMPT_SCHEDULED}`,`${L.ATTEMPT_STARTED}`,`${L.ATTEMPT_SUCCEEDED}`,`${L.ATTEMPT_FAILED}`,`${L.WAITING_SIGNALING}`,`${L.LIMIT_REACHED}`,`${L.CANCELLED}`,`${L.STATUS_CHANGED}`],In=()=>new l.TypedEvents(Fn),Ln=_(`CallReconnectManager`),Rn=class extends l.EventEmitterProxy{stateMachine;runtime;callManager;connectionManager;unsubscribes=[];constructor({callManager:e,connectionManager:t},n){super(In()),this.callManager=e,this.connectionManager=t,this.runtime=new wn({callManager:e,connectionManager:t,options:n,emitters:{emitStatusChange:e=>{this.events.trigger(`status-changed`,e)}}}),this.stateMachine=Nn(Pn({runtime:this.runtime,events:this.events})),this.subscribeToManagers()}get isReconnecting(){return this.stateMachine.state!==I.IDLE}get state(){return this.stateMachine.state}arm(e){if(Ln(`arm`),this.callManager.hasSpectator()){this.events.trigger(`cancelled`,{reason:`spectator-role`});return}this.stateMachine.send({type:`RECONNECT.ARM`,parameters:e})}disarm(e=`disarm`){Ln(`disarm`,e),this.stateMachine.send({type:`RECONNECT.DISARM`,reason:e})}forceReconnect(){Ln(`forceReconnect`),this.stateMachine.send({type:`RECONNECT.FORCE`})}cancelCurrentAttempt(){this.runtime.cancelAll()}stop(){this.unsubscribes.forEach(e=>{e()}),this.unsubscribes.length=0,this.runtime.cancelAll(),this.stateMachine.stop()}subscribeToManagers(){let e=e=>{if(this.runtime.isNetworkFailure(e)){this.stateMachine.send({type:`CALL.FAILED`,event:e});return}this.stateMachine.send({type:`CALL.ENDED`,event:e})},t=t=>{e(t)},n=t=>{e(t)},r=()=>{this.stateMachine.send({type:`CALL.ENDED`})},i=()=>{this.stateMachine.send({type:`CONN.CONNECTED`})},a=()=>{this.stateMachine.send({type:`CONN.DISCONNECTED`})};this.callManager.on(`failed`,t),this.callManager.on(`end-call`,r),this.callManager.on(`ended`,n),this.connectionManager.on(`connected`,i),this.connectionManager.on(`registered`,i),this.connectionManager.on(`disconnected`,a),this.unsubscribes.push(()=>{this.callManager.off(`failed`,t)},()=>{this.callManager.off(`end-call`,r)},()=>{this.callManager.off(`ended`,n)},()=>{this.connectionManager.off(`connected`,i)},()=>{this.connectionManager.off(`registered`,i)},()=>{this.connectionManager.off(`disconnected`,a)})}},zn=`incomingCall`,Bn=`declinedIncomingCall`,Vn=`failedIncomingCall`,Hn=`terminatedIncomingCall`,Un=`connecting`,Wn=`connected`,Gn=`disconnected`,Kn=`newRTCSession`,qn=`registered`,Jn=`unregistered`,Yn=`registrationFailed`,Xn=`newMessage`,Zn=`sipEvent`,Qn=`availableSecondRemoteStream`,$n=`notAvailableSecondRemoteStream`,er=`mustStopPresentation`,tr=`enterRoom`,nr=`useLicense`,rr=`peerconnection:confirmed`,ir=`peerconnection:ontrack`,ar=`channels`,or=`channels:notify`,sr=`ended:fromserver`,cr=`main-cam-control`,lr=`admin:stop-main-cam`,ur=`admin:start-main-cam`,dr=`admin:stop-mic`,fr=`admin:start-mic`,pr=`admin:force-sync-media-state`,mr=`participant:added-to-list-moderators`,hr=`participant:removed-from-list-moderators`,gr=`participant:move-request-to-stream`,_r=`participant:move-request-to-spectators`,vr=`participant:move-request-to-participants`,yr=`participation:accepting-word-request`,br=`participation:cancelling-word-request`,xr=`webcast:started`,Sr=`webcast:stopped`,Cr=`account:changed`,wr=`account:deleted`,Tr=`conference:participant-token-issued`,Er=`ended`,Dr=`sending`,Or=`reinvite`,kr=`replaces`,Ar=`refer`,jr=`progress`,Mr=`accepted`,Nr=`confirmed`,Pr=`peerconnection`,Fr=`failed`,Ir=`muted`,Lr=`unmuted`,Rr=`newDTMF`,zr=`newInfo`,Br=`hold`,Vr=`unhold`,Hr=`update`,Ur=`icecandidate`,Wr=`getusermediafailed`,Gr=`peerconnection:createofferfailed`,Kr=`peerconnection:createanswerfailed`,qr=`peerconnection:setlocaldescriptionfailed`,Jr=`peerconnection:setremotedescriptionfailed`,Yr=`presentation:start`,Xr=`presentation:started`,Zr=`presentation:end`,Qr=`presentation:ended`,$r=`presentation:failed`,ei=[zn,Bn,Hn,Vn,yr,br,gr,or,Tr,Cr,wr,xr,Sr,mr,hr],ti=[Un,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn],ni=[Qn,$n,er,tr,nr,rr,ir,ar,sr,cr,ur,lr,dr,fr,pr,_r,vr],ri=[Er,Un,Dr,Or,kr,Ar,jr,Mr,Nr,Pr,Fr,Ir,Lr,Rr,zr,Br,Vr,Hr,`sdp`,Ur,Wr,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,$r];[...ti,...ei],[...ri,...ni];var ii=_(`BaseSession.mock`),ai=class{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};addTransceiver=jest.fn(async(e,t,n)=>({}));constructor({originator:e=`local`,eventHandlers:t,remoteIdentity:n}){this.originator=e,this.events=new l.Events(ri),this.initEvents(t),this.remote_identity=n}get contact(){throw Error(`Method not implemented.`)}get direction(){throw Error(`Method not implemented.`)}get local_identity(){throw Error(`Method not implemented.`)}get start_time(){throw Error(`Method not implemented.`)}get end_time(){throw Error(`Method not implemented.`)}get status(){throw Error(`Method not implemented.`)}get C(){throw Error(`Method not implemented.`)}get causes(){throw Error(`Method not implemented.`)}get id(){throw Error(`Method not implemented.`)}get data(){throw Error(`Method not implemented.`)}set data(e){throw Error(`Method not implemented.`)}isInProgress(){throw Error(`Method not implemented.`)}isEnded(){throw Error(`Method not implemented.`)}isReadyToReOffer(){throw Error(`Method not implemented.`)}answer(e){throw Error(`Method not implemented.`)}terminate(e){throw Error(`Method not implemented.`)}async sendInfo(e,t,n){throw Error(`Method not implemented.`)}hold(e,t){throw Error(`Method not implemented.`)}unhold(e,t){throw Error(`Method not implemented.`)}async renegotiate(e,t){throw Error(`Method not implemented.`)}isOnHold(){throw Error(`Method not implemented.`)}mute(e){throw Error(`Method not implemented.`)}unmute(e){throw Error(`Method not implemented.`)}isMuted(){throw Error(`Method not implemented.`)}refer(e,t){return!1}resetLocalMedia(){throw Error(`Method not implemented.`)}async replaceMediaStream(e,t){throw Error(`Method not implemented.`)}addListener(e,t){throw Error(`Method not implemented.`)}once(e,t){throw Error(`Method not implemented.`)}removeListener(e,t){throw Error(`Method not implemented.`)}off(e,t){return this.events.off(e,t),this}removeAllListeners(e){return ii(`Method not implemented. Event:`,e),this}setMaxListeners(e){throw Error(`Method not implemented.`)}getMaxListeners(){throw Error(`Method not implemented.`)}listeners(e){throw Error(`Method not implemented.`)}rawListeners(e){throw Error(`Method not implemented.`)}emit(e,...t){throw Error(`Method not implemented.`)}listenerCount(e){throw Error(`Method not implemented.`)}prependListener(e,t){throw Error(`Method not implemented.`)}prependOnceListener(e,t){throw Error(`Method not implemented.`)}eventNames(){throw Error(`Method not implemented.`)}initEvents(e){e&&Object.entries(e).forEach(([e,t])=>{this.on(e,t)})}on=(e,t)=>(ri.includes(e)&&this.events.on(e,t),this);trigger(e,t){this.events.trigger(e,t)}sendDTMF(){this.trigger(`newDTMF`,{originator:this.originator})}async startPresentation(e){return this.trigger(`presentation:start`,e),this.trigger(`presentation:started`,e),e}async stopPresentation(e){return this.trigger(`presentation:end`,e),this.trigger(`presentation:ended`,e),e}isEstablished(){return!0}},oi=class{stats=new Map().set(`codec`,{mimeType:`video/h264`});dtmf=null;track=null;transport=null;transform=null;parameters={encodings:[{}],transactionId:`0`,codecs:[],headerExtensions:[],rtcp:{}};parametersGets;constructor({track:e}={}){this.track=e??null}async getStats(){return this.stats}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw Error(`Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().`);let{transactionId:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw Error(`Method not implemented.`)}},si=class{currentDirection=`sendrecv`;direction=`sendrecv`;mid=null;receiver;sender;stopped=!1;constructor(e){this.sender=e}setCodecPreferences(e){}stop(){}},ci=function(e){return e.TRACK=`track`,e}({}),li=class extends EventTarget{senders=[];receivers=[];canTrickleIceCandidates;connectionState=`new`;currentLocalDescription;currentRemoteDescription;iceConnectionState;iceGatheringState;idpErrorInfo;idpLoginUrl;localDescription;onconnectionstatechange;ondatachannel;onicecandidate;onicecandidateerror=null;oniceconnectionstatechange;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;peerIdentity=void 0;pendingLocalDescription;pendingRemoteDescription;remoteDescription;sctp=null;signalingState=`stable`;close=jest.fn();setLocalDescription=jest.fn(async e=>{this.signalingState=e.type===`rollback`?`stable`:`have-local-offer`,this.dispatchEvent(new Event(`signalingstatechange`))});setRemoteDescription=jest.fn(async e=>{this.signalingState=`stable`,this.connectionState=`connected`,this.dispatchEvent(new Event(`signalingstatechange`)),this.dispatchEvent(new Event(`connectionstatechange`))});addTransceiver=jest.fn((e,t)=>({}));createOffer=jest.fn(async(e,t,n)=>({type:`offer`,sdp:`offer-sdp`}));constructor(e,t){super(),this.receivers=t?.map(e=>({track:e}))??[]}getRemoteStreams(){throw Error(`Method not implemented.`)}async addIceCandidate(e){throw Error(`Method not implemented.`)}restartIce(){throw Error(`Method not implemented.`)}async createAnswer(e,t){throw Error(`Method not implemented.`)}createDataChannel(e,t){throw Error(`Method not implemented.`)}getConfiguration(){throw Error(`Method not implemented.`)}async getIdentityAssertion(){throw Error(`Method not implemented.`)}async getStats(e){throw Error(`Method not implemented.`)}getTransceivers(){throw Error(`Method not implemented.`)}removeTrack(e){throw Error(`Method not implemented.`)}setConfiguration(e){throw Error(`Method not implemented.`)}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=(e,...t)=>{let n=new oi({track:e}),r=new si(n);return r.mid=e.kind===`audio`?`0`:`1`,this.senders.push(n),this.dispatchTrackInternal(e,...t),n};addTrackWithMid=(e,t)=>{let n=new oi({track:e}),r=new si(n);return t===void 0?r.mid=e.kind===`audio`?`0`:`1`:r.mid=t,this.senders.push(n),this.dispatchTrackInternal(e),n};dispatchTrack(e){this.dispatchTrackInternal(new ee.MediaStreamTrackMock(e))}dispatchTrackInternal(e,...t){let n=new Event(ci.TRACK);Object.defineProperty(n,`track`,{value:e}),Object.defineProperty(n,`streams`,{value:t.length===0?[new MediaStream([e])]:t}),this.dispatchEvent(n)}};function ui(e){let t=e.match(/(purgatory)|[\d.]+/g);if(!t)throw Error(`wrong sip url`);return t[0]}var R=function(e){return e.PEER_CONNECTION=`peerconnection`,e.CONNECTING=`connecting`,e.SENDING=`sending`,e.PROGRESS=`progress`,e.ACCEPTED=`accepted`,e.CONFIRMED=`confirmed`,e.ENDED=`ended`,e.FAILED=`failed`,e.NEW_DTMF=`newDTMF`,e.NEW_INFO=`newInfo`,e.HOLD=`hold`,e.UNHOLD=`unhold`,e.MUTED=`muted`,e.UNMUTED=`unmuted`,e.REINVITE=`reinvite`,e.UPDATE=`update`,e.REFER=`refer`,e.REPLACES=`replaces`,e.SDP=`sdp`,e.ICE_CANDIDATE=`icecandidate`,e.GET_USER_MEDIA_FAILED=`getusermediafailed`,e.PEER_CONNECTION_CREATE_OFFER_FAILED=`peerconnection:createofferfailed`,e.PEER_CONNECTION_CREATE_ANSWER_FAILED=`peerconnection:createanswerfailed`,e.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED=`peerconnection:setlocaldescriptionfailed`,e.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED=`peerconnection:setremotedescriptionfailed`,e.START_PRESENTATION=`presentation:start`,e.STARTED_PRESENTATION=`presentation:started`,e.END_PRESENTATION=`presentation:end`,e.ENDED_PRESENTATION=`presentation:ended`,e.FAILED_PRESENTATION=`presentation:failed`,e.START_CALL=`start-call`,e.END_CALL=`end-call`,e.PEER_CONNECTION_CONFIRMED=`peerconnection:confirmed`,e.PEER_CONNECTION_ONTRACK=`peerconnection:ontrack`,e.ENDED_FROM_SERVER=`ended:fromserver`,e.CALL_STATUS_CHANGED=`call-status-changed`,e.REMOTE_TRACKS_CHANGED=`remote-tracks-changed`,e.REMOTE_STREAMS_CHANGED=`remote-streams-changed`,e.RECV_SESSION_STARTED=`recv-session-started`,e.RECV_SESSION_ENDED=`recv-session-ended`,e.RECV_QUALITY_CHANGED=`recv-quality-changed`,e}(R||{}),di=function(e){return e.LOCAL=`local`,e.REMOTE=`remote`,e.SYSTEM=`system`,e}({}),fi=[`${R.PEER_CONNECTION}`,`${R.CONNECTING}`,`${R.SENDING}`,`${R.PROGRESS}`,`${R.ACCEPTED}`,`${R.CONFIRMED}`,`${R.ENDED}`,`${R.FAILED}`,`${R.HOLD}`,`${R.UNHOLD}`,`${R.MUTED}`,`${R.UNMUTED}`,`${R.NEW_INFO}`,`${R.NEW_DTMF}`,`${R.START_PRESENTATION}`,`${R.STARTED_PRESENTATION}`,`${R.END_PRESENTATION}`,`${R.ENDED_PRESENTATION}`,`${R.FAILED_PRESENTATION}`,`${R.REINVITE}`,`${R.UPDATE}`,`${R.REFER}`,`${R.REPLACES}`,`${R.SDP}`,`${R.ICE_CANDIDATE}`,`${R.GET_USER_MEDIA_FAILED}`,`${R.PEER_CONNECTION_CREATE_OFFER_FAILED}`,`${R.PEER_CONNECTION_CREATE_ANSWER_FAILED}`,`${R.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED}`,`${R.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED}`],pi=[`${R.START_CALL}`,`${R.END_CALL}`,`${R.PEER_CONNECTION_CONFIRMED}`,`${R.PEER_CONNECTION_ONTRACK}`,`${R.ENDED_FROM_SERVER}`,`${R.CALL_STATUS_CHANGED}`,`${R.REMOTE_TRACKS_CHANGED}`,`${R.REMOTE_STREAMS_CHANGED}`,`${R.RECV_SESSION_STARTED}`,`${R.RECV_SESSION_ENDED}`,`${R.RECV_QUALITY_CHANGED}`],mi=[...fi,...pi],hi=()=>new l.TypedEvents(mi),gi=400,_i=`777`,vi=e=>e.getVideoTracks().length>0,yi=class e extends ai{static presentationError;static startPresentationError;static countStartPresentationError=1/0;static countStartsPresentation=0;url;status_code;renegotiate=jest.fn(async()=>!0);answer=jest.fn(({mediaStream:e})=>{if(this.originator!==`remote`)throw Error(`answer available only for remote sessions`);this.initPeerconnection(e),setTimeout(()=>{this.trigger(`connecting`),setTimeout(()=>{this.trigger(`accepted`)},100),setTimeout(()=>{this.trigger(`confirmed`)},200)},gi)});replaceMediaStream=jest.fn(async e=>{});_isReadyToReOffer=jest.fn(()=>!0);restartIce=jest.fn(async e=>!0);isEndedInner=!1;delayStartPresentation=0;timeoutStartPresentation;timeoutConnect;timeoutNewInfo;timeoutAccepted;timeoutConfirmed;constructor({eventHandlers:e,originator:t,remoteIdentity:n=new g.NameAddrHeader(new g.URI(`sip`,`caller1`,`test1.com`,5060),`Test Caller 1`),delayStartPresentation:r=0}){super({originator:t,eventHandlers:e,remoteIdentity:n}),this.delayStartPresentation=r}static get C(){return g.SessionStatus}static setPresentationError(e){this.presentationError=e}static resetPresentationError(){this.presentationError=void 0}static setStartPresentationError(e,{count:t=1/0}={}){this.startPresentationError=e,this.countStartPresentationError=t}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=1/0,this.countStartsPresentation=0}startPresentation=async t=>(e.countStartsPresentation+=1,new Promise((n,r)=>{this.timeoutStartPresentation=setTimeout(()=>{if(e.presentationError){this.trigger(`presentation:start`,t),this.trigger(`presentation:failed`,t),r(e.presentationError);return}if(e.startPresentationError&&e.countStartsPresentation<e.countStartPresentationError){this.trigger(`presentation:start`,t),this.trigger(`presentation:failed`,t),r(e.startPresentationError);return}n(super.startPresentation(t))},this.delayStartPresentation)}));stopPresentation=async t=>{if(e.presentationError)throw this.trigger(`presentation:end`,t),this.trigger(`presentation:failed`,t),e.presentationError;return super.stopPresentation(t)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){let t=(0,ee.createAudioMediaStreamTrackMock)();t.id=`mainaudio1`;let n=[t];if(vi(e)){let e=(0,ee.createVideoMediaStreamTrackMock)();e.id=`mainvideo1`,n.push(e)}this.connection=new li(void 0,n),this.trigger(`peerconnection`,{peerconnection:this.connection}),this.addStream(e)}connect(e,{mediaStream:t}={}){let n=ui(e);return this.initPeerconnection(t),this.timeoutConnect=setTimeout(()=>{e.includes(`777`)?this.trigger(`failed`,{originator:`remote`,message:`IncomingResponse`,cause:`Rejected`}):(this.trigger(`connecting`),this.timeoutNewInfo=setTimeout(()=>{this.newInfo({originator:di.REMOTE,request:{getHeader:e=>e===`content-type`?`application/vinteo.webrtc.roomname`:e===`x-webrtc-enter-room`?n:e===`x-webrtc-participant-name`?`Test Caller 1`:``}})},100),this.timeoutAccepted=setTimeout(()=>{this.trigger(`accepted`)},200),this.timeoutConfirmed=setTimeout(()=>{this.trigger(`confirmed`)},300))},gi),this.connection}terminate({status_code:e,cause:t}={}){return this.status_code=e,this.trigger(`ended`,{status_code:e,cause:t,originator:`local`}),this.isEndedInner=!1,this}async terminateAsync({status_code:e,cause:t}={}){this.terminate({status_code:e,cause:t})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger(`ended`,{status_code:e,originator:`remote`}),this}addStream(e,t=`getTracks`){e[t]().forEach(t=>this.connection.addTrack(t,e))}forEachSenders(e){let t=this.connection.getSenders();for(let n of t)e(n);return t}toggleMuteAudio(e){this.forEachSenders(({track:t})=>{t?.kind===`audio`&&(t.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:t})=>{t?.kind===`video`&&(t.enabled=!e)})}mute(e){e.audio&&(this.mutedOptions.audio=!0,this.toggleMuteAudio(this.mutedOptions.audio)),e.video&&(this.mutedOptions.video=!0,this.toggleMuteVideo(this.mutedOptions.video)),this.onmute(e)}unmute(e){e.audio&&(this.mutedOptions.audio=!1),e.video&&(this.mutedOptions.video=!1),this.trigger(`unmuted`,e)}isMuted(){return this.mutedOptions}onmute({audio:e,video:t}){this.trigger(`muted`,{audio:e,video:t})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(e){this.trigger(`newInfo`,e)}clear(){clearTimeout(this.timeoutStartPresentation),clearTimeout(this.timeoutConnect),clearTimeout(this.timeoutNewInfo),clearTimeout(this.timeoutAccepted),clearTimeout(this.timeoutConfirmed)}},bi=function(e){return e.SNAPSHOT_CHANGED=`snapshot-changed`,e}(bi||{}),xi=[`${bi.SNAPSHOT_CHANGED}`],Si=()=>new l.TypedEvents(xi),Ci=e=>e.type===`participant`,wi=e=>e.type===`spectator_synthetic`,z=e=>e.type===`spectator`,Ti=(e,t)=>z(e)&&!z(t),Ei=(e,t)=>z(t),Di=(e,t)=>{let n=z(e)||wi(e),r=z(t)||wi(t);return n&&!r},Oi=(e,t)=>{let n=z(e)||wi(e),r=z(t)||wi(t);return!n&&r},ki={type:`participant`},Ai={type:`spectator_synthetic`},ji=e=>({type:`spectator`,recvParams:e}),Mi=class{role=ki;isAvailableSendingMedia=!0;onRoleChanged;listeners=new Set;constructor(e){this.onRoleChanged=e}getRole(){return this.role}getIsAvailableSendingMedia(){return this.isAvailableSendingMedia}setCallRoleParticipant(){this.isAvailableSendingMedia=!0,this.changeRole(ki)}setCallRoleSpectatorSynthetic(e=!0){this.isAvailableSendingMedia=e,this.changeRole(Ai)}setCallRoleSpectator(e,t=!0){this.isAvailableSendingMedia=t,this.changeRole(ji(e))}changeRole(e){let t=this.role;if(t.type!==e.type){this.setRole(e);return}z(e)&&z(t)&&t.recvParams.audioId!==e.recvParams.audioId&&this.setRole(e)}reset(){this.role=ki,this.isAvailableSendingMedia=!0}hasParticipant(){return Ci(this.role)}hasSpectatorSynthetic(){return wi(this.role)}hasSpectator(){return z(this.role)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setRole(e){let t=this.role;this.role=e,this.onRoleChanged?.({previous:t,next:e}),this.listeners.forEach(n=>{n({previous:t,next:e})})}},Ni=(e,t)=>e.type===t.type?e.type===`spectator`?t.type===`spectator`&&e.recvParams.audioId===t.recvParams.audioId:!0:!1,Pi=(e,t)=>e.license===t.license&&e.isDuplexSendingMediaMode===t.isDuplexSendingMediaMode&&Ni(e.role,t.role)&&e.derived.isAvailableSendingMedia===t.derived.isAvailableSendingMedia,Fi=(e,t,n)=>{let r=e.getRole();return{license:n,isDuplexSendingMediaMode:t,role:r,derived:{isSpectatorAny:r.type===`spectator`||r.type===`spectator_synthetic`,isRecvSessionExpected:r.type===`spectator`,isAvailableSendingMedia:e.getIsAvailableSendingMedia()}}},Ii=xe.VIDEO,Li=class extends l.EventEmitterProxy{roleManager=new Mi;license=Ii;isDuplexSendingMediaMode=!1;currentSnapshot;subscriptions=[];dedupedTotal=0;constructor(){super(Si()),this.currentSnapshot=Fi(this.roleManager,this.isDuplexSendingMediaMode,this.license);let e=this.roleManager.subscribe(this.notifySubscribers);this.subscriptions.push({unsubscribe:e})}getSnapshot(){return this.currentSnapshot}subscribe(e){return this.on(`snapshot-changed`,({current:t})=>{e(t)})}subscribeRoleChanges(e){return this.roleManager.subscribe(e)}hasSpectator(){return this.roleManager.hasSpectator()}setCallRoleParticipant(){this.roleManager.setCallRoleParticipant()}setCallRoleSpectatorSynthetic(e=!0){this.roleManager.setCallRoleSpectatorSynthetic(e)}setCallRoleSpectator(e,t=!0){this.roleManager.setCallRoleSpectator(e,t)}reset(){this.roleManager.reset(),this.license=Ii,this.isDuplexSendingMediaMode=!1,this.notifySubscribers()}subscribeToApiEvents(e){let t=e.on(`use-license`,this.handleUseLicense),n=e.on(`admin:force-sync-media-state`,this.handleSyncMediaState),r=e.on(`admin:stop-main-cam`,this.handleSyncMediaState),i=e.on(`admin:stop-mic`,this.handleSyncMediaState),a=e.on(`admin:start-mic`,this.handleSyncMediaState);this.subscriptions.push({unsubscribe:t}),this.subscriptions.push({unsubscribe:n}),this.subscriptions.push({unsubscribe:r}),this.subscriptions.push({unsubscribe:i}),this.subscriptions.push({unsubscribe:a})}stop(){this.subscriptions.forEach(e=>{e.unsubscribe()}),this.events.offAll(`snapshot-changed`)}getDiagnostics(){return{emitsTotal:this.events.getEmitsTotal(`snapshot-changed`),dedupedTotal:this.dedupedTotal,subscribersCount:this.events.getSubscribersCount(`snapshot-changed`)}}notifySubscribers=()=>{let{previousSnapshot:e,currentSnapshot:t}=this.updateCurrentSnapshot();if(Pi(e,t)){this.dedupedTotal+=1;return}this.events.trigger(`snapshot-changed`,{previous:e,current:t})};updateCurrentSnapshot(){let e=this.currentSnapshot;return this.currentSnapshot=Fi(this.roleManager,this.isDuplexSendingMediaMode,this.license),{previousSnapshot:e,currentSnapshot:this.currentSnapshot}}handleUseLicense=e=>{this.license=e,this.notifySubscribers()};handleSyncMediaState=({isSyncForced:e})=>{this.isDuplexSendingMediaMode=e,this.notifySubscribers()}},Ri=(e,t)=>{let n=t.major===e.major,r=t.minor===e.minor,i=t.major>e.major,a=n&&t.minor>e.minor,o=n&&r&&t.patch>e.patch;return i||a||o},zi=e=>e.major!==void 0&&e.minor!==void 0&&e.patch!==void 0,Bi=e=>t=>zi(e)&&Ri(e,t),Vi=(e=``)=>{let t=e.split(`.`);if(t.length<=1)return{major:void 0,minor:void 0,patch:void 0};let[n,r,i]=t.map(e=>Number.parseInt(e,10));return{major:n,minor:r,patch:i}},Hi=()=>globalThis.process?.versions?.electron!==void 0,Ui=()=>{let e=new te.UAParser,{name:t,version:n}=e.getBrowser(),{name:r}=e.getOS(),{type:i}=e.getDevice(),a=Hi(),o=i===`mobile`;return{hasGreaterThanBrowserVersion:Bi(Vi(n)),isMobileDevice:o,isChrome:t===`Chrome`||a,isYandexBrowser:t===`Yandex`,isSafari:t===`Safari`,isOpera:t===`Opera`,isWindows:r===`Windows`}},Wi=e=>{let{url:t,cause:n}=e,r=t;return(n===W.BAD_MEDIA_DESCRIPTION||n===W.NOT_FOUND)&&(r=`${e.message.to.uri.user}@${e.message.to.uri.host}`),r},Gi=function(e){return e.CONNECT_SERVER_FAILED=`CONNECT_SERVER_FAILED`,e.WRONG_USER_OR_PASSWORD=`WRONG_USER_OR_PASSWORD`,e.BAD_MEDIA_ERROR=`BAD_MEDIA_ERROR`,e.NOT_FOUND_ERROR=`NOT_FOUND_ERROR`,e.WS_CONNECTION_FAILED=`WS_CONNECTION_FAILED`,e.CONNECT_SERVER_FAILED_BY_LINK=`CONNECT_SERVER_FAILED_BY_LINK`,e}({}),Ki=Error(`Unknown error`),qi=(e=Ki)=>{let{cause:t,socket:n}=e,r=Gi.CONNECT_SERVER_FAILED;switch(t){case`Forbidden`:r=Gi.WRONG_USER_OR_PASSWORD;break;case W.BAD_MEDIA_DESCRIPTION:r=Gi.BAD_MEDIA_ERROR;break;case W.NOT_FOUND:r=Gi.NOT_FOUND_ERROR;break;default:n!==void 0&&n._ws?.readyState===3?r=Gi.WS_CONNECTION_FAILED:Wi(e)!==void 0&&Wi(e)!==``&&(r=Gi.CONNECT_SERVER_FAILED_BY_LINK)}return r},Ji=_(`stringifyMessage`),Yi=e=>{let t=``;try{t=JSON.stringify(e)}catch(e){Ji(`failed to stringify message`,e)}return t},Xi=Error(`Unknown error`),Zi=(e=Xi)=>{let{code:t,cause:n,message:r}=e,i=Wi(e),a={code:``,cause:``,message:``};return typeof r==`object`&&r?a.message=Yi(r):r&&(a.message=String(r)),i!==void 0&&i!==``&&(a.link=i),t!==void 0&&t!==``&&(a.code=t),n!==void 0&&n!==``&&(a.cause=n),a},Qi=o({EErrorTypes:()=>Gi,getLinkError:()=>Wi,getTypeFromError:()=>qi,getValuesFromError:()=>Zi}),$i=({sessionId:e,remoteAddress:t,isMutedAudio:n,isMutedVideo:r,isRegistered:i,isPresentationCall:a})=>{let o=[],s=n?`0`:`1`,c=r?`0`:`1`;return o.push(`X-Vinteo-Mic-State: ${s}`,`X-Vinteo-MainCam-State: ${c}`),(i===!1||i===void 0)&&o.push(`X-Vinteo-Purgatory-Call: yes`),e!==void 0&&e!==``&&o.push(`X-Vinteo-Session: ${e}`),a===!0&&o.push(`X-Vinteo-Presentation-Call: yes`),t!==void 0&&t!==``&&o.push(`X-Vinteo-Remote: ${t}`),o},ea=`[@*!|]`,ta=`_`,na=e=>{let t=e;return t=t.replaceAll(new RegExp(ea,`g`),ta),t},ra=({appName:e,appVersion:t,browserName:n,browserVersion:r})=>{let i=`${na(e)} ${t}`;return`ChromeNew - ${n===void 0?i:`${n} ${r}, ${i}`}`},ia=({isUnifiedSdpSemantic:e,appVersion:t,browserName:n,browserVersion:r,appName:i})=>e?ra({appVersion:t,browserName:n,browserVersion:r,appName:i}):`Chrome`,aa=/^p2p.+to.+$/i,oa=e=>e!==void 0&&e.length>0&&aa.test(e),sa=`purgatory`,ca=e=>e===sa,la=(e,t)=>{e.getVideoTracks().forEach(e=>{`contentHint`in e&&e.contentHint!==t&&(e.contentHint=t)})},ua=(e,{directionVideo:t,directionAudio:n,contentHint:r}={})=>{if(!e||t===`recvonly`&&n===`recvonly`)return;let i=n===`recvonly`?[]:e.getAudioTracks(),a=t===`recvonly`?[]:e.getVideoTracks(),o=[...i,...a],s=new MediaStream(o);return s.getTracks=()=>[...s.getAudioTracks(),...s.getVideoTracks()],r&&r!==`none`&&la(s,r),s},da=e=>t=>[...t].map(t=>async()=>e(t)),fa=async({accumulatedKeys:e,sendKey:t,canRunTask:n})=>(0,ne.sequentPromises)(da(t)(e),n),pa=`api/v2/rtp2webrtc/offer`,ma=async({serverUrl:e,conferenceNumber:t,quality:n,audio:r,offer:i,token:a})=>{let o=new URL(`https://${e.replace(/\/$/,``)}/${pa}/${encodeURIComponent(t)}`);o.searchParams.set(`quality`,n),o.searchParams.set(`audio`,String(r));let s={"Content-Type":`application/json`,Authorization:`Bearer ${a}`},c=await fetch(o.toString(),{method:`POST`,headers:s,credentials:`same-origin`,body:JSON.stringify(i)});if(!c.ok)throw Error(`sendOffer failed with status ${c.status}`);let l=await c.json();return{type:l.type,sdp:l.sdp,toJSON(){return l}}},ha=(e,t)=>(e.degradationPreference=t.degradationPreference,e),ga=(e,t)=>{e.encodings??=[];for(let n=e.encodings.length;n<t;n+=1)e.encodings.push({});return e},_a=e=>(t,n)=>n!==void 0&&t!==n||n===void 0&&t!==e,va=_a(),ya=(e,t)=>{if(va(e,t))return e},ba=(e,t,{isResetAllowed:n=!1}={})=>{let r=e.maxBitrate,i=ya(t,r);return(i!==void 0||n)&&(e.maxBitrate=i??t),e},xa=1,Sa=_a(xa),Ca=(e,t)=>{let n=e===void 0?void 0:Math.max(e,xa);if(n!==void 0&&Sa(n,t))return n},wa=(e,t)=>{let n=e.scaleResolutionDownBy,r=Ca(t,n);return r!==void 0&&(e.scaleResolutionDownBy=r),e},Ta=(e,t,{isResetAllowed:n}={})=>(ga(e,t.encodings?.length??0),e.encodings.forEach((e,r)=>{let i=(t?.encodings??[])[r],a=i?.maxBitrate,o=i?.scaleResolutionDownBy;ba(e,a,{isResetAllowed:n}),wa(e,o)}),e),Ea=(e,t)=>{if(e.codecs?.length!==t.codecs?.length)return!0;for(let n=0;n<(e.codecs?.length??0);n++)if(JSON.stringify(e.codecs[n])!==JSON.stringify(t.codecs[n]))return!0;if(e.headerExtensions?.length!==t.headerExtensions?.length)return!0;for(let n=0;n<(e.headerExtensions?.length??0);n++)if(JSON.stringify(e.headerExtensions[n])!==JSON.stringify(t.headerExtensions[n]))return!0;if(e.encodings?.length!==t.encodings?.length)return!0;for(let n=0;n<(e.encodings?.length??0);n++)if(JSON.stringify(e.encodings[n])!==JSON.stringify(t.encodings[n]))return!0;return e.rtcp?.cname!==t.rtcp?.cname||e.rtcp?.reducedSize!==t.rtcp?.reducedSize||e.degradationPreference!==t.degradationPreference},Da=async(e,t,{isResetAllowed:n}={})=>{let r=e.getParameters(),i=JSON.parse(JSON.stringify(r));Ta(r,t,{isResetAllowed:n}),ha(r,t);let a=Ea(i,r);return a&&await e.setParameters(r),{parameters:r,isChanged:a}},Oa=async(e,t,n)=>{let{isChanged:r,parameters:i}=await Da(e,{encodings:[{scaleResolutionDownBy:t.scaleResolutionDownBy,maxBitrate:t.maxBitrate}]});return r&&n&&n(i),{isChanged:r,parameters:i}},ka=(e,t)=>e.find(e=>e.track!==null&&t.getTracks().includes(e.track)),Aa=async(e,t,n)=>{let r=ka(e,t);if(r)return Oa(r,{maxBitrate:n})},ja=_(`resolveOnStartMainCam`),Ma=e=>t=>(ja(`onStartMainCam`),e.on(`api:admin:start-main-cam`,t)),Na=_(`resolveOnStartMic`),Pa=e=>t=>(Na(`onStartMic`),e.on(`api:admin:start-mic`,t)),Fa=_(`resolveOnStopMainCam`),Ia=e=>t=>(Fa(`onStopMainCam`),e.on(`api:admin:stop-main-cam`,t)),La=_(`resolveOnStopMic`),Ra=e=>t=>(La(`onStopMic`),e.on(`api:admin:stop-mic`,t)),za=({sipConnector:e})=>{let t=(e,t)=>({isSyncForced:n})=>{if(n===!0){e();return}t()},n=Ma(e),r=Ia(e),i=Pa(e),a=Ra(e),o,s,c,l,u=({onStartMainCamForced:e,onStartMainCamNotForced:u,onStopMainCamForced:d,onStopMainCamNotForced:f,onStartMicForced:p,onStartMicNotForced:m,onStopMicForced:h,onStopMicNotForced:g})=>{o=n(t(e,u)),s=r(t(d,f)),c=i(t(p,m)),l=a(t(h,g))},d=()=>{o?.(),s?.(),c?.(),l?.()};return{start:e=>{u(e)},stop:()=>{d()}}},Ba=class{command=void 0;unsubscribe;options;constructor(e){this.options=e}set(e){this.cancel(),this.command=e,this.unsubscribe=this.options.subscribe(e=>{this.options.isReady(e)?(this.command!==void 0&&this.options.onExecute(this.command),this.cancel()):this.options.isCancelled(e)&&this.cancel()})}cancel(){this.unsubscribe?.(),this.unsubscribe=void 0,this.command=void 0}},Va=o({DeferredCommandRunner:()=>Ba,PURGATORY_CONFERENCE_NUMBER:()=>sa,createSyncMediaState:()=>za,createUaParser:()=>Ui,error:()=>Qi,getExtraHeaders:()=>$i,getUserAgent:()=>ia,hasPeerToPeer:()=>oa,hasPurgatory:()=>ca,prepareMediaStream:()=>ua,sendDtmfAccumulated:()=>fa,sendOffer:()=>ma,setEncodingsToSender:()=>Oa,setParametersToSender:()=>Da}),B=`evaluate`,V=function(e){return e.IDLE=`call:idle`,e.CONNECTING=`call:connecting`,e.PRESENTATION_CALL=`call:presentationCall`,e.ROOM_PENDING_AUTH=`call:roomPendingAuth`,e.PURGATORY=`call:purgatory`,e.P2P_ROOM=`call:p2pRoom`,e.DIRECT_P2P_ROOM=`call:directP2pRoom`,e.IN_ROOM=`call:inRoom`,e.DISCONNECTING=`call:disconnecting`,e}({}),Ha={raw:{},state:{}},Ua=e=>`number`in e&&x(e.number)&&we(e.answer),Wa=e=>`room`in e&&x(e.room)&&x(e.participantName)&&Se(e.startedTimestamp),Ga=e=>`token`in e&&x(e.token),Ka=e=>Ga(e)&&`conferenceForToken`in e&&x(e.conferenceForToken),qa=e=>Ua(e)&&Wa(e),Ja=e=>!Ka(e)||!Wa(e)?!1:e.conferenceForToken===e.room,Ya=({isDirectPeerToPeer:e})=>e===!0,Xa=e=>`isDirectPeerToPeer`in e&&Ya(e),Za=`x-vinteo-presentation-call: yes`,Qa=e=>Te(e)&&e.some(e=>e.trim().toLowerCase()===Za),$a=e=>`extraHeaders`in e&&Qa(e.extraHeaders)&&`isConfirmed`in e&&e.isConfirmed===!0,eo=e=>qa(e)&&!ca(e.room)&&Ka(e)&&Ja(e),to=e=>{let t=e;return{number:t.number,answer:t.answer,room:t.room,participantName:t.participantName,startedTimestamp:t.startedTimestamp}},H={[V.IDLE]:{guard:()=>!0,buildContext:()=>({})},[V.CONNECTING]:{guard:Ua,buildContext:e=>{let{number:t,answer:n,extraHeaders:r}=e;return{number:t,answer:n,extraHeaders:r}}},[V.PRESENTATION_CALL]:{guard:$a,buildContext:e=>{let{number:t,answer:n,startedTimestamp:r}=e;return{number:t,answer:n,startedTimestamp:r}}},[V.ROOM_PENDING_AUTH]:{guard:e=>qa(e)&&!ca(e.room)&&!oa(e.room)&&!Xa(e)&&!Ja(e),buildContext:to},[V.PURGATORY]:{guard:e=>qa(e)&&ca(e.room)&&!eo(e),buildContext:to},[V.P2P_ROOM]:{guard:e=>qa(e)&&oa(e.room)&&!Xa(e)&&!eo(e),buildContext:to},[V.DIRECT_P2P_ROOM]:{guard:e=>qa(e)&&Xa(e)&&!eo(e),buildContext:e=>({...to(e),isDirectPeerToPeer:!0})},[V.IN_ROOM]:{guard:eo,buildContext:e=>{let{token:t,conferenceForToken:n}=e;return{...to(e),token:t,conferenceForToken:n}}},[V.DISCONNECTING]:{guard:e=>e.pendingDisconnect===!0,buildContext:()=>({})}},no=e=>ca(e.room)||oa(e.room)||Ya(e),ro=()=>({}),io=()=>(0,p.setup)({types:{context:Ha,events:{}},actions:{setConnecting:(0,p.assign)(({event:e,context:t})=>e.type===`CALL.CONNECTING`?{raw:{...ro(),number:e.number,answer:e.answer,extraHeaders:e.extraHeaders}}:t),setRoomInfo:(0,p.assign)(({event:e,context:t})=>{if(e.type!==`CALL.ENTER_ROOM`)return t;let n={room:e.room,participantName:e.participantName};x(e.token)?(n.token=e.token,n.conferenceForToken=e.room):no(e)&&(n.token=void 0,n.conferenceForToken=void 0),we(e.isDirectPeerToPeer)&&(n.isDirectPeerToPeer=e.isDirectPeerToPeer);let r=t.raw.startedTimestamp,i=Se(r)?r:Date.now();return{raw:{...t.raw,...n,startedTimestamp:i}}}),setTokenInfo:(0,p.assign)(({event:e,context:t})=>e.type===`CALL.TOKEN_ISSUED`?{raw:{...t.raw,token:e.token,conferenceForToken:e.conferenceForToken,participantName:e.participantName}}:t),setConfirmed:(0,p.assign)(({event:e,context:t})=>{if(e.type!==`CALL.PRESENTATION_CALL`)return t;let n=t.raw.startedTimestamp,r=Se(n)?n:Date.now();return{raw:{...t.raw,isConfirmed:!0,startedTimestamp:r}}}),reset:(0,p.assign)(()=>({raw:ro()})),prepareDisconnect:(0,p.assign)(()=>({raw:{...ro(),pendingDisconnect:!0}}))}}),ao=()=>io().createMachine({id:`call`,initial:V.IDLE,context:Ha,states:{[V.IDLE]:{entry:(0,p.assign)(()=>({state:H[V.IDLE].buildContext()})),on:{"CALL.CONNECTING":{target:B,actions:`setConnecting`}}},[V.CONNECTING]:{entry:(0,p.assign)(({context:e})=>({state:H[V.CONNECTING].buildContext(e.raw)})),on:{"CALL.PRESENTATION_CALL":{target:B,actions:`setConfirmed`},"CALL.ENTER_ROOM":{target:B,actions:`setRoomInfo`},"CALL.TOKEN_ISSUED":{target:B,actions:`setTokenInfo`},"CALL.START_DISCONNECT":{target:B,actions:`prepareDisconnect`},"CALL.RESET":{target:B,actions:`reset`}}},[V.ROOM_PENDING_AUTH]:{entry:(0,p.assign)(({context:e})=>({state:H[V.ROOM_PENDING_AUTH].buildContext(e.raw)})),on:{"CALL.ENTER_ROOM":{target:B,actions:`setRoomInfo`},"CALL.TOKEN_ISSUED":{target:B,actions:`setTokenInfo`},"CALL.START_DISCONNECT":{target:B,actions:`prepareDisconnect`},"CALL.RESET":{target:B,actions:`reset`}}},[V.IN_ROOM]:{entry:(0,p.assign)(e=>({state:H[V.IN_ROOM].buildContext(e.context.raw)})),on:{"CALL.ENTER_ROOM":{target:B,actions:`setRoomInfo`},"CALL.TOKEN_ISSUED":{target:B,actions:`setTokenInfo`},"CALL.START_DISCONNECT":{target:B,actions:`prepareDisconnect`},"CALL.RESET":{target:B,actions:`reset`}}},[B]:{always:[{target:V.DISCONNECTING,guard:({context:e})=>H[V.DISCONNECTING].guard(e.raw)},{target:V.PRESENTATION_CALL,guard:({context:e})=>H[V.PRESENTATION_CALL].guard(e.raw)},{target:V.IN_ROOM,guard:({context:e})=>H[V.IN_ROOM].guard(e.raw)},{target:V.DIRECT_P2P_ROOM,guard:({context:e})=>H[V.DIRECT_P2P_ROOM].guard(e.raw)},{target:V.P2P_ROOM,guard:({context:e})=>H[V.P2P_ROOM].guard(e.raw)},{target:V.PURGATORY,guard:({context:e})=>H[V.PURGATORY].guard(e.raw)},{target:V.ROOM_PENDING_AUTH,guard:({context:e})=>H[V.ROOM_PENDING_AUTH].guard(e.raw)},{target:V.CONNECTING,guard:({context:e})=>H[V.CONNECTING].guard(e.raw)},{target:V.IDLE}]},[V.PURGATORY]:{entry:(0,p.assign)(({context:e})=>({state:H[V.PURGATORY].buildContext(e.raw)})),on:{"CALL.ENTER_ROOM":{target:B,actions:`setRoomInfo`},"CALL.TOKEN_ISSUED":{target:B,actions:`setTokenInfo`},"CALL.START_DISCONNECT":{target:B,actions:`prepareDisconnect`},"CALL.RESET":{target:B,actions:`reset`}}},[V.P2P_ROOM]:{entry:(0,p.assign)(({context:e})=>({state:H[V.P2P_ROOM].buildContext(e.raw)})),on:{"CALL.ENTER_ROOM":{target:B,actions:`setRoomInfo`},"CALL.TOKEN_ISSUED":{target:B,actions:`setTokenInfo`},"CALL.START_DISCONNECT":{target:B,actions:`prepareDisconnect`},"CALL.RESET":{target:B,actions:`reset`}}},[V.PRESENTATION_CALL]:{entry:(0,p.assign)(({context:e})=>({state:H[V.PRESENTATION_CALL].buildContext(e.raw)})),on:{"CALL.START_DISCONNECT":{target:B,actions:`prepareDisconnect`},"CALL.RESET":{target:B,actions:`reset`}}},[V.DIRECT_P2P_ROOM]:{entry:(0,p.assign)(({context:e})=>({state:H[V.DIRECT_P2P_ROOM].buildContext(e.raw)})),on:{"CALL.ENTER_ROOM":{target:B,actions:`setRoomInfo`},"CALL.TOKEN_ISSUED":{target:B,actions:`setTokenInfo`},"CALL.START_DISCONNECT":{target:B,actions:`prepareDisconnect`},"CALL.RESET":{target:B,actions:`reset`}}},[V.DISCONNECTING]:{entry:(0,p.assign)(()=>({state:H[V.DISCONNECTING].buildContext()})),on:{"CALL.RESET":{target:B,actions:`reset`}}}}});function oo(e){return e!==B}var so=_(`CallManager: CallStateMachine`),co=class extends et{constructor(e,t){super(e),this.subscribeToEvents(t)}get isIdle(){return this.state===V.IDLE}get isConnecting(){return this.state===V.CONNECTING}get isPresentationCall(){return this.state===V.PRESENTATION_CALL}get isRoomPendingAuth(){return this.state===V.ROOM_PENDING_AUTH}get isInPurgatory(){return this.state===V.PURGATORY}get isP2PRoom(){return this.state===V.P2P_ROOM}get isDirectP2PRoom(){return this.state===V.DIRECT_P2P_ROOM}get isInRoom(){return this.state===V.IN_ROOM}get isDisconnecting(){return this.state===V.DISCONNECTING}get idleContext(){if(this.state===V.IDLE)return this.context.state}get connectingContext(){if(this.state===V.CONNECTING)return this.context.state}get roomPendingAuthContext(){if(this.state===V.ROOM_PENDING_AUTH)return this.context.state}get purgatoryContext(){if(this.state===V.PURGATORY)return this.context.state}get p2pRoomContext(){if(this.state===V.P2P_ROOM)return this.context.state}get directP2pRoomContext(){if(this.state===V.DIRECT_P2P_ROOM)return this.context.state}get inRoomContext(){if(this.state===V.IN_ROOM)return this.context.state}get presentationCallContext(){if(this.state===V.PRESENTATION_CALL)return this.context.state}get disconnectingContext(){if(this.state===V.DISCONNECTING)return this.context.state}get isActive(){return this.isInRoom||this.isPresentationCall||this.isRoomPendingAuth||this.isInPurgatory||this.isP2PRoom||this.isDirectP2PRoom}get startedTimestamp(){return this.inRoomContext?.startedTimestamp??this.roomPendingAuthContext?.startedTimestamp??this.presentationCallContext?.startedTimestamp??this.purgatoryContext?.startedTimestamp??this.p2pRoomContext?.startedTimestamp??this.directP2pRoomContext?.startedTimestamp}get number(){let{raw:e}=this.context;if(`number`in e)return e.number}get token(){return this.inRoomContext?.token}get isCallInitiator(){return!this.isCallAnswerer}get isCallAnswerer(){return this.connectingContext?.answer??!1}getInRoomCredentials(){let e=this.inRoomContext;if(e!==void 0)return{token:e.token,conferenceForToken:e.conferenceForToken}}onInRoomCredentialsChange(e){let t=this.getInRoomCredentials(),n=this.subscribe(n=>{if(n.value===V.IN_ROOM){let r=n.context.state,i={token:r.token,conferenceForToken:r.conferenceForToken},a=t?.token,o=t?.conferenceForToken;(a!==i.token||o!==i.conferenceForToken)&&(t=i,e(i));return}oo(n.value)&&(t=void 0)});return()=>{n.unsubscribe()}}onInRoomConferenceForTokenChange(e){let t=this.getInRoomCredentials()?.conferenceForToken,n=this.subscribe(n=>{if(n.value===V.IN_ROOM){let r=n.context.state.conferenceForToken;t!==r&&(t=r,e({conferenceForToken:r}));return}oo(n.value)&&(t=void 0)});return()=>{n.unsubscribe()}}reset(){this.send({type:`CALL.RESET`})}send(e){if(!this.actor.getSnapshot().can(e)){so(`[CallStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeToApiEvents(e){this.addSubscription(e.on(`enter-room`,({room:e,participantName:t,bearerToken:n,isDirectPeerToPeer:r})=>{this.send({room:e,participantName:t,isDirectPeerToPeer:r,type:`CALL.ENTER_ROOM`,token:n})})),this.addSubscription(e.on(`conference:participant-token-issued`,({jwt:e,conference:t,participant:n})=>{this.send({token:e,type:`CALL.TOKEN_ISSUED`,conferenceForToken:t,participantName:n})}))}subscribeToEvents(e){this.addSubscription(e.on(`start-call`,({number:e,answer:t,extraHeaders:n})=>{this.send({type:`CALL.CONNECTING`,number:e,answer:t,extraHeaders:n})})),this.addSubscription(e.on(`confirmed`,()=>{this.send({type:`CALL.PRESENTATION_CALL`})})),this.addSubscription(e.on(`end-call`,()=>{this.send({type:`CALL.START_DISCONNECT`})})),this.addSubscription(e.on(`ended`,()=>{this.send({type:`CALL.RESET`})})),this.addSubscription(e.on(`failed`,()=>{this.send({type:`CALL.RESET`})}))}},lo=e=>new co(ao(),e),uo=e=>[...e.keys()].map(t=>e.get(t)),fo=(e,t)=>uo(e).find(e=>e?.type===t),po=async e=>e.getStats().then(e=>fo(e,`codec`)?.mimeType),mo=class{async getCodecFromSender(e){return await po(e)??``}},ho=_(`TaskQueue`),go=class{stackPromises=(0,h.createStackPromises)({noRunIsNotActual:!0});async add(e){return this.stackPromises.add(e),this.run()}stop(){this.stackPromises.stop()}async run(){return this.stackPromises().catch(e=>{ho(`TaskQueue: error`,e)})}},_o=class{taskQueue;onSetParameters;constructor(e){this.onSetParameters=e,this.taskQueue=new go}async setEncodingsToSender(e,t){return this.taskQueue.add(async()=>Oa(e,t,this.onSetParameters))}stop(){this.taskQueue.stop()}},vo=(e,t)=>e!==void 0&&t!==void 0&&e.toLowerCase().includes(t.toLowerCase()),yo=1e6,U=e=>e*yo,bo=U(.06),xo=U(4),So=e=>e<=64?bo:e<=128?U(.12):e<=256?U(.25):e<=384?U(.32):e<=426?U(.38):e<=640?U(.5):e<=848?U(.7):e<=1280?U(1):e<=1920?U(2):xo,Co=`av1`,wo=e=>vo(e,Co),To=.6,Eo=(e,t)=>wo(t)?e*To:e,Do=e=>Eo(bo,e),Oo=e=>Eo(xo,e),ko=(e,t)=>Eo(So(e),t),Ao=1,jo=({videoTrack:e,targetSize:t})=>{let n=e.getSettings(),r=n.width,i=n.height,a=r===void 0?Ao:r/t.width,o=i===void 0?Ao:i/t.height;return Math.max(a,o,Ao)},Mo=class{ignoreForCodec;senderFinder;codecProvider;parametersSetter;resultNoChanged={isChanged:!1,parameters:{encodings:[{}],transactionId:`0`,codecs:[],headerExtensions:[],rtcp:{}}};constructor({senderFinder:e,codecProvider:t,parametersSetter:n},r){this.senderFinder=e,this.codecProvider=t,this.parametersSetter=n,this.ignoreForCodec=r.ignoreForCodec}async balance(e,t){let n=e.getSenders(),r=this.senderFinder.findVideoSender(n);if(!r?.track)return{...this.resultNoChanged,sender:r};let i=await this.codecProvider.getCodecFromSender(r);if(vo(i,this.ignoreForCodec))return{...this.resultNoChanged,sender:r};let{mainCam:a,resolutionMainCam:o}=t??{};return this.processSender({mainCam:a,resolutionMainCam:o},{sender:r,codec:i,videoTrack:r.track}).then(e=>({...e,sender:r}))}async reset(e){let t=e.getSenders(),n=this.senderFinder.findVideoSender(t);if(!n?.track)return{...this.resultNoChanged,sender:n};let r=await this.codecProvider.getCodecFromSender(n);if(vo(r,this.ignoreForCodec))return{...this.resultNoChanged,sender:n};let i={sender:n,codec:r,videoTrack:n.track};return{...await this.setBitrateByTrackResolution(i),sender:n}}async processSender(e,t){let{mainCam:n,resolutionMainCam:r}=e;switch(n){case y.PAUSE_MAIN_CAM:return this.downgradeResolutionSender(t);case y.RESUME_MAIN_CAM:return this.setBitrateByTrackResolution(t);case y.MAX_MAIN_CAM_RESOLUTION:return r===void 0?this.setBitrateByTrackResolution(t):this.setResolutionSender(r,t);case y.ADMIN_STOP_MAIN_CAM:case y.ADMIN_START_MAIN_CAM:case void 0:return this.setBitrateByTrackResolution(t);default:return this.setBitrateByTrackResolution(t)}}async downgradeResolutionSender(e){let{sender:t,codec:n}=e,r={scaleResolutionDownBy:200,maxBitrate:Do(n)};return this.parametersSetter.setEncodingsToSender(t,r)}async setBitrateByTrackResolution(e){let{sender:t,videoTrack:n,codec:r}=e,i=n.getSettings().width,a=i===void 0?Oo(r):ko(i,r);return this.parametersSetter.setEncodingsToSender(t,{scaleResolutionDownBy:1,maxBitrate:a})}async setResolutionSender(e,t){let[n,r]=e.split(`x`),{sender:i,videoTrack:a,codec:o}=t,s={width:Number(n),height:Number(r)},c={scaleResolutionDownBy:jo({videoTrack:a,targetSize:s}),maxBitrate:ko(s.width,o)};return this.parametersSetter.setEncodingsToSender(i,c)}},No=e=>e.find(e=>e.track?.kind===`video`),Po=class{findVideoSender(e){return No(e)}},Fo=class{currentSender;originalReplaceTrack;lastWidth;lastHeight;maxPollIntervalMs;currentPollIntervalMs;pollIntervalMs;setTimeoutRequest;constructor({pollIntervalMs:e=1e3,maxPollIntervalMs:t}){this.pollIntervalMs=e,this.maxPollIntervalMs=t??e*16,this.currentPollIntervalMs=this.pollIntervalMs,this.setTimeoutRequest=new d.SetTimeoutRequest}subscribe(e,t){if(!e){this.detachSender();return}this.currentSender!==e&&(this.detachSender(),this.attachSender(e,t))}unsubscribe(){this.detachSender()}attachSender(e,t){this.currentSender=e;let n=e.replaceTrack.bind(e);this.originalReplaceTrack=n,e.replaceTrack=async e=>{await n(e),this.attachTrack(t,e??void 0),t()},this.attachTrack(t,e.track)}detachSender(){this.currentSender&&this.originalReplaceTrack&&(this.currentSender.replaceTrack=this.originalReplaceTrack),this.originalReplaceTrack=void 0,this.currentSender=void 0,this.detachTrack()}attachTrack(e,t){if(this.detachTrack(),!t)return;let{width:n,height:r}=t.getSettings();this.lastWidth=n,this.lastHeight=r,this.currentPollIntervalMs=this.pollIntervalMs,this.schedulePoll(t,e)}schedulePoll(e,t){let n=()=>{let{width:r,height:i}=e.getSettings();r!==this.lastWidth||i!==this.lastHeight?(this.lastWidth=r,this.lastHeight=i,this.currentPollIntervalMs=this.pollIntervalMs,t()):this.currentPollIntervalMs=Math.min(this.currentPollIntervalMs*2,this.maxPollIntervalMs),this.setTimeoutRequest.request(n,this.currentPollIntervalMs)};this.setTimeoutRequest.request(n,this.currentPollIntervalMs)}detachTrack(){this.setTimeoutRequest.cancelRequest(),this.lastWidth=void 0,this.lastHeight=void 0}},Io=class{apiManager;currentHandler;constructor(e){this.apiManager=e}subscribe(e){this.currentHandler=e,this.apiManager.on(`main-cam-control`,e)}unsubscribe(){this.currentHandler&&=(this.apiManager.off(`main-cam-control`,this.currentHandler),void 0)}},Lo=_(`VideoSendingBalancer`),Ro=class{eventHandler;senderBalancer;parametersSetterWithQueue;getConnection;serverHeaders;trackMonitor;constructor(e,t,{ignoreForCodec:n,onSetParameters:r,pollIntervalMs:i}={}){this.getConnection=t,this.eventHandler=new Io(e),this.parametersSetterWithQueue=new _o(r),this.senderBalancer=new Mo({senderFinder:new Po,codecProvider:new mo,parametersSetter:this.parametersSetterWithQueue},{ignoreForCodec:n}),this.trackMonitor=new Fo({pollIntervalMs:i})}subscribe(){this.eventHandler.subscribe(this.handleMainCamControl)}unsubscribe(){this.eventHandler.unsubscribe(),this.reset()}reset(){this.clearState();let e=this.getConnection();e?this.senderBalancer.reset(e).catch(e=>{Lo(`reset sender encodings: error`,e)}).finally(()=>{this.parametersSetterWithQueue.stop()}):this.parametersSetterWithQueue.stop()}async balance(){let e=this.getConnection();if(!e)throw Error(`connection is not exist`);let t=await this.senderBalancer.balance(e,this.serverHeaders);return this.trackMonitor.subscribe(t.sender,()=>{this.balance().catch(e=>{Lo(`balance on track change: error`,e)})}),t}clearState(){delete this.serverHeaders,this.trackMonitor.unsubscribe()}handleMainCamControl=e=>{this.serverHeaders=e,this.balance().catch(e=>{Lo(`handleMainCamControl: error`,e)})}},zo=6e3,Bo=52e4,Vo=(e,t)=>e.getSenders().filter(e=>e.track?.kind===t),Ho=(e,t)=>e===`audio`?zo:Do(t),Uo=e=>e.track!==null,Wo=class{previousBitrates=new Map;async setMinBitrateForSenders(e,t=`all`){let n=[];if(!e)return;(t===`audio`||t===`all`)&&n.push(...Vo(e,`audio`)),(t===`video`||t===`all`)&&n.push(...Vo(e,`video`));let r=n.filter(Uo).map(async e=>{let t=e.getParameters();this.saveCurrentBitrate(e,t),await Da(e,{...t,encodings:t.encodings.map(t=>({...t,maxBitrate:Ho(e.track.kind)}))})});await Promise.all(r)}async restoreBitrateForSenders(e,t=`all`){let n=[];if(!e)return;(t===`audio`||t===`all`)&&n.push(...Vo(e,`audio`)),(t===`video`||t===`all`)&&n.push(...Vo(e,`video`));let r=n.map(async e=>{let t=this.getSavedBitrate(e);if(t){let n=e.getParameters(),r=e.track?.kind===`video`,i=r?await po(e):void 0;await Da(e,{...n,encodings:t.map(e=>{let t=r?Oo(i):Bo;return{...e,maxBitrate:e.maxBitrate??t}})},{isResetAllowed:!0}),this.clearSavedBitrate(e)}});await Promise.all(r)}getSavedBitrate(e){return this.previousBitrates.get(e)}clearSavedBitrate(e){this.previousBitrates.delete(e)}clearAll(){this.previousBitrates.clear()}hasSavedBitrate(e){return this.previousBitrates.has(e)}getSavedCount(){return this.previousBitrates.size}saveCurrentBitrate(e,t){let n=t.encodings.map(e=>({...e}));this.previousBitrates.set(e,n)}},W=function(e){return e.BYE=`Terminated`,e.WEBRTC_ERROR=`WebRTC Error`,e.CANCELED=`Canceled`,e.REQUEST_TIMEOUT=`Request Timeout`,e.REJECTED=`Rejected`,e.REDIRECTED=`Redirected`,e.UNAVAILABLE=`Unavailable`,e.NOT_FOUND=`Not Found`,e.ADDRESS_INCOMPLETE=`Address Incomplete`,e.INCOMPATIBLE_SDP=`Incompatible SDP`,e.BAD_MEDIA_DESCRIPTION=`Bad Media Description`,e}({}),Go=_(`CallManager: MCUSession`),Ko=class{events;rtcSession;disposers=new Set;pcConfig;bitrateStateManager=new Wo;constructor(e){this.events=e,e.on(`failed`,this.handleEnded),e.on(`ended`,this.handleEnded)}get connection(){return this.rtcSession?.connection}get isCallActive(){return this.rtcSession?.isEstablished()===!0}getEstablishedRTCSession=()=>this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0;getPcConfig(){return this.pcConfig}async renegotiate(){if(this.rtcSession===void 0)throw Error(`No rtcSession established`);return this.rtcSession.renegotiate()}startCall=async(e,t,{number:n,mediaStream:r,extraHeaders:i=[],iceServers:a,directionVideo:o,directionAudio:s,contentHint:c,offerToReceiveAudio:l=!0,offerToReceiveVideo:u=!0,degradationPreference:d,sendEncodings:f,onAddedTransceiver:p})=>new Promise((m,h)=>{this.handleCall().then(m).catch(e=>{h(e)}),this.pcConfig={iceServers:a},this.rtcSession=e.call(t(n),{mediaStream:ua(r,{directionVideo:o,directionAudio:s,contentHint:c}),pcConfig:{iceServers:a},rtcOfferConstraints:{offerToReceiveAudio:l,offerToReceiveVideo:u},eventHandlers:this.events.triggers,extraHeaders:i,directionVideo:o,directionAudio:s,degradationPreference:d,sendEncodings:f,onAddedTransceiver:p})});async endCall(){let{rtcSession:e}=this;if(e&&!e.isEnded())return e.terminateAsync({cause:W.CANCELED})}answerToIncomingCall=async(e,{mediaStream:t,extraHeaders:n=[],iceServers:r,directionVideo:i,directionAudio:a,offerToReceiveAudio:o,offerToReceiveVideo:s,contentHint:c,degradationPreference:l,sendEncodings:u,onAddedTransceiver:d})=>new Promise((f,p)=>{try{this.rtcSession=e,this.subscribeToSessionEvents(e),this.handleCall().then(f).catch(e=>{p(e)}),this.pcConfig={iceServers:r},e.answer({pcConfig:{iceServers:r},rtcOfferConstraints:{offerToReceiveAudio:o,offerToReceiveVideo:s},mediaStream:ua(t,{directionVideo:i,directionAudio:a,contentHint:c}),extraHeaders:n,directionVideo:i,directionAudio:a,degradationPreference:l,sendEncodings:u,onAddedTransceiver:d})}catch(e){p(e)}});async replaceMediaStream(e,t){if(!this.rtcSession)throw Error(`No rtcSession established`);let{contentHint:n}=t??{},r=ua(e,{contentHint:n});if(r===void 0)throw Error(`No preparedMediaStream`);return this.rtcSession.replaceMediaStream(r,t)}async restartIce(e){if(!this.rtcSession)throw Error(`No rtcSession established`);return this.rtcSession.restartIce(e)}setMinBitrateForSenders(e=`all`){this.bitrateStateManager.setMinBitrateForSenders(this.connection,e).catch(e=>{Go(`setMinBitrateForSenders`,e)})}restoreBitrateForSenders(e=`all`){this.bitrateStateManager.restoreBitrateForSenders(this.connection,e).catch(e=>{Go(`restoreBitrateForSenders`,e)})}reset=()=>{delete this.rtcSession,delete this.pcConfig,this.unsubscribeFromSessionEvents(),this.bitrateStateManager.clearAll()};handleCall=async()=>new Promise((e,t)=>{let n=()=>{this.events.on(`peerconnection`,c),this.events.on(`confirmed`,l)},r=()=>{this.events.off(`peerconnection`,c),this.events.off(`confirmed`,l)},i=()=>{this.events.on(`failed`,o),this.events.on(`ended`,o)},a=()=>{this.events.off(`failed`,o),this.events.off(`ended`,o)},o=e=>{r(),a(),t(e)},s,c=({peerconnection:e})=>{s=e;let t=e=>{this.events.trigger(`peerconnection:ontrack`,e)};e.addEventListener(`track`,t),this.disposers.add(()=>{e.removeEventListener(`track`,t)})},l=()=>{s!==void 0&&this.events.trigger(`peerconnection:confirmed`,s),r(),a(),e(s)};n(),i()});subscribeToSessionEvents(e){this.events.eachTriggers((t,n)=>{let r=fi.find(e=>e===n);r&&(e.on(r,t),this.disposers.add(()=>{e.off(r,t)}))})}unsubscribeFromSessionEvents(){this.disposers.forEach(e=>{e()}),this.disposers.clear()}handleEnded=e=>{let{originator:t}=e;t===`remote`&&this.events.trigger(`ended:fromserver`,e)}},qo=e=>e===`auto`?`high`:e,Jo=10,Yo=500,Xo=5e3,Zo=class{cancelableSendOfferWithRepeatedCalls;currentRenegotiation;config;tools;connection;lastCallParams;constructor(e,t){let n=e.quality??`auto`;this.config={...e,quality:n,effectiveQuality:qo(n)},this.tools=t,this.connection=new RTCPeerConnection(e.pcConfig),this.addTransceivers()}get settings(){return this.config}get peerConnection(){return this.connection}getAudioChannel(){return this.config.audioChannel}getQuality(){return this.config.quality}getEffectiveQuality(){return this.config.effectiveQuality}async setQuality(e){if(!this.lastCallParams)return!1;let t=this.config.effectiveQuality,n=this.config.quality,r=qo(e);return e===n&&r===t?!1:(this.config.quality=e,this.config.effectiveQuality=r,r!==t&&await this.renegotiate(this.lastCallParams),!0)}async applyQuality(e){return{applied:await this.setQuality(e),effectiveQuality:this.getEffectiveQuality()}}close(){this.cancelSendOfferWithRepeatedCalls(),this.connection.close()}async call({conferenceNumber:e,token:t}){let n=this.waitForTracks(),r=await this.renegotiate({conferenceNumber:e,token:t});return await n,r}async renegotiate({conferenceNumber:e,token:t}){this.lastCallParams={conferenceNumber:e,token:t},this.cancelSendOfferWithRepeatedCalls();let n=this.currentRenegotiation;n&&await n.catch(()=>{});let r=this.performRenegotiate({conferenceNumber:e,token:t});this.currentRenegotiation=r;try{return await r}finally{this.currentRenegotiation===r&&(this.currentRenegotiation=void 0)}}async performRenegotiate({conferenceNumber:e,token:t}){this.hasHaveLocalOfferSignalingState()&&await this.connection.setLocalDescription({type:`rollback`}),await this.waitForPeerConnectionReady();let n=await this.createOffer(),r=async()=>this.tools.sendOffer({conferenceNumber:e,token:t,quality:this.config.effectiveQuality,audioChannel:this.config.audioChannel},n),i=e=>!(e instanceof Error);this.cancelableSendOfferWithRepeatedCalls=(0,m.repeatedCallsAsync)({targetFunction:r,isComplete:i,callLimit:Jo,delay:Yo,isRejectAsValid:!0,isCheckBeforeCall:!1});let a=await this.cancelableSendOfferWithRepeatedCalls.then(e=>e).finally(()=>{this.cancelableSendOfferWithRepeatedCalls=void 0});return await this.setRemoteDescription(a),await this.waitForPeerConnectionReady(),!0}async createOffer(){let e=await this.connection.createOffer();return await this.connection.setLocalDescription(e),e}async setRemoteDescription(e){return this.connection.setRemoteDescription(e)}hasStableSignalingState(){return this.connection.signalingState===`stable`}hasReadyConnectionState(){let e=this.connection.connectionState;return e===`connected`||e===`new`}hasTerminalConnectionState(){let e=this.connection.connectionState;return e===`failed`||e===`closed`}isStableAndReady(){return this.hasStableSignalingState()&&this.hasReadyConnectionState()}hasHaveLocalOfferSignalingState(){return this.connection.signalingState===`have-local-offer`}async waitForPeerConnectionReady(){if(this.isStableAndReady())return;let e=()=>{let e=this.connection.connectionState;return Error(`Peer connection in terminal state: ${e}. Recovery is not possible.`)},t=()=>this.hasTerminalConnectionState()?`error`:this.isStableAndReady()?`success`:`loading`;if(t()===`error`)throw e();return new Promise((n,r)=>{let i,a=!1,o=()=>{a||(a=!0,clearTimeout(i),this.connection.removeEventListener(`signalingstatechange`,c),this.connection.removeEventListener(`connectionstatechange`,c),n())},s=e=>{a||(a=!0,clearTimeout(i),this.connection.removeEventListener(`signalingstatechange`,c),this.connection.removeEventListener(`connectionstatechange`,c),r(e))};function c(){let n=t();if(n===`error`){s(e());return}n===`success`&&o()}i=setTimeout(()=>{s(Error(`Timed out waiting for stable signaling state and ready connection state`))},Xo),this.connection.addEventListener(`signalingstatechange`,c),this.connection.addEventListener(`connectionstatechange`,c),c()})}async waitForTracks(){return new Promise(e=>{let t=new Set,n=r=>{let{track:i}=r;t.add(i.kind),t.has(`audio`)&&t.has(`video`)&&(this.connection.removeEventListener(`track`,n),e())};this.connection.addEventListener(`track`,n)})}addTransceivers(){this.addRecvOnlyTransceiver(`audio`),this.addRecvOnlyTransceiver(`video`),this.addRecvOnlyTransceiver(`video`),this.addRecvOnlyTransceiver(`video`),this.addRecvOnlyTransceiver(`video`)}addRecvOnlyTransceiver(e){return this.connection.addTransceiver(e,{direction:`recvonly`})}cancelSendOfferWithRepeatedCalls(){this.cancelableSendOfferWithRepeatedCalls?.cancel()}},Qo=e=>e.getSettings(),$o=(e,t)=>{let n=Qo(e),r=t;r??=e.label;let i=n?.msid;return i??=r,i??=e.id,i},es=(e,t)=>{let n=Qo(e),r=t;return r??=n?.msid,r??=e.label,(r&&r.length>0?r:void 0)??e.id},ts=class{participantGroups=new Map;trackToGroup=new Map;trackDisposers=new Map;get mainStream(){let[e]=this.getStreams();return e}reset(){this.participantGroups.clear(),this.trackToGroup.clear(),this.trackDisposers.forEach(e=>{e()}),this.trackDisposers.clear()}addTrack(e,{onRemoved:t,streamHint:n}={}){let r=es(e,n),i=$o(e,n);if(this.trackToGroup.has(e.id))return{isAddedTrack:!1,isAddedStream:!1};let a=this.getParticipantGroups(r),o=a.get(i),s=!o,c=o;c||(c={participantId:r,groupId:i,stream:new MediaStream,trackIds:new Set},a.set(i,c)),c.stream.addTrack(e),c.trackIds.add(e.id),this.trackToGroup.set(e.id,{participantId:r,groupId:i});let l=()=>{this.disposeTrackListener(e.id);let n=this.removeTrack(e.id);n.isRemovedTrack&&t?.({participantId:r,trackId:e.id,isRemovedStream:n.isRemovedStream})};return e.addEventListener(`ended`,l),this.trackDisposers.set(e.id,()=>{e.removeEventListener(`ended`,l)}),{isAddedTrack:!0,isAddedStream:s,participantId:r}}removeTrack(e){this.disposeTrackListener(e);let t=this.trackToGroup.get(e);if(!t)return{isRemovedTrack:!1,isRemovedStream:!1};let{participantId:n,groupId:r}=t,i=this.participantGroups.get(n),a=i?.get(r);if(!a)return this.trackToGroup.delete(e),{isRemovedTrack:!1,isRemovedStream:!1};let o=a.stream.getTracks().find(t=>t.id===e);o&&a.stream.removeTrack(o),a.trackIds.delete(e),this.trackToGroup.delete(e);let s=a.trackIds.size===0;return s&&(i?.delete(r),i?.size===0&&this.participantGroups.delete(n)),{isRemovedTrack:!0,isRemovedStream:s}}removeStaleTracks(e,t){let n=this.participantGroups.get(e);if(!n)return!1;let r=!1;return[...n.values()].forEach(e=>{[...e.trackIds].filter(e=>!t.includes(e)).forEach(e=>{let t=this.removeTrack(e);r||=t.isRemovedTrack})}),r}getStreams(e){if(e!==void 0){let t=this.participantGroups.get(e);return t?[...t.values()].map(e=>e.stream):[]}return[...this.participantGroups.values()].flatMap(e=>[...e.values()]).map(e=>e.stream)}disposeTrackListener(e){let t=this.trackDisposers.get(e);t&&(t(),this.trackDisposers.delete(e))}getParticipantGroups(e){let t=this.participantGroups.get(e);if(t)return t;let n=new Map;return this.participantGroups.set(e,n),n}},ns=(e,t)=>{if(!e||!t)return e===t;let n=e.mainStream?.id,r=t.mainStream?.id,i=e.contentedStream?.id,a=t.contentedStream?.id;return n===r&&i===a},rs=class{lastEmittedStreams;hasChanged(e){return!ns(this.lastEmittedStreams,e)}updateLastEmittedStreams(e){this.lastEmittedStreams=e}getLastEmittedStreams(){return this.lastEmittedStreams}reset(){this.lastEmittedStreams=void 0}},is=`default`,as=`dual`,os=`content_`,ss=e=>`${os}${e.toLowerCase()}`,cs=e=>[...e.getTracks()].some(e=>e.label.includes(as)),ls=class{mainRemoteStreamsManager;recvRemoteStreamsManager;constructor(e,t){this.mainRemoteStreamsManager=e,this.recvRemoteStreamsManager=t}getActiveStreamsManagerTools({isSpectator:e,stateInfo:t}){return e?this.getRecvRemoteStreamsManagerTools({stateInfo:t}):this.getMainRemoteStreamsManagerTools({stateInfo:t})}getMainRemoteStreamsManagerTools({stateInfo:e}){let t=this.mainRemoteStreamsManager;return{manager:t,getRemoteStreams:()=>{let n=t.getStreams(),r=n.find(e=>!cs(e));return{mainStream:r,contentedStream:e.isAvailable?n.find(e=>e!==r):void 0}}}}getRecvRemoteStreamsManagerTools({stateInfo:e}){let t=this.recvRemoteStreamsManager;return{manager:t,getRemoteStreams:()=>({mainStream:t.getStreams(is)[0],contentedStream:this.getRecvRemoteContentedStream({stateInfo:e})})}}getRecvRemoteContentedStream({stateInfo:e}){if(!e.isAvailable||e.codec===void 0)return;let t=ss(e.codec);return this.recvRemoteStreamsManager.getStreams(t)[0]}},us=`udp`,G=_(`CallManager`),ds=e=>e.transport?.iceTransport?e.transport.iceTransport.getLocalCandidates():[],fs=e=>e.getReceivers().flatMap(ds),ps=e=>{let t=fs(e).filter(({protocol:e,port:t})=>t!==null&&us===e).map(({port:e})=>e);return[...new Set(t)]},ms=e=>e.streams[0]?.id,hs=class extends l.EventEmitterProxy{stateMachine;sessionState;isPendingCall=!1;isPendingAnswer=!1;mainRemoteStreamsManager=new ts;recvRemoteStreamsManager=new ts;streamsManagerProvider;contentedStreamManager;tools;roleManager={hasSpectator:()=>this.sessionState.hasSpectator(),reset:()=>{this.sessionState.reset()}};mcuSession;recvSession;disposeRecvSessionTrackListener;disposeInRoomCredentialsListener;deferredStartRecvSessionRunner;streamsChangeTracker=new rs;constructor({contentedStreamManager:e},t,{callSessionState:n}){super(hi()),this.contentedStreamManager=e,this.tools=t,this.mcuSession=new Ko(this.events),this.stateMachine=lo(this.events),this.sessionState=n,this.sessionState.subscribeRoleChanges(this.onRoleChanged),this.streamsManagerProvider=new ls(this.mainRemoteStreamsManager,this.recvRemoteStreamsManager),this.deferredStartRecvSessionRunner=new Ba({subscribe:e=>this.stateMachine.onStateChange(e),isReady:e=>e===V.IN_ROOM,isCancelled:e=>e===V.IDLE,onExecute:e=>{G(`startRecvSessionForced`,e),this.startRecvSessionForced({audioChannel:e.audioId}).catch(()=>{})}}),this.subscribeCallEndedStateMachine(),this.subscribeCallStatusChange(),this.subscribeMcuRemoteTrackEvents(),this.subscribeContentedStreamEvents()}get requested(){return this.isPendingCall||this.isPendingAnswer}get connection(){return this.mcuSession.connection}get isCallActive(){return this.mcuSession.isCallActive}get number(){return this.stateMachine.number}get isCallInitiator(){return this.stateMachine.isCallInitiator}get isDirectP2PRoom(){return this.stateMachine.isDirectP2PRoom}get isPresentationCall(){return this.stateMachine.isPresentationCall}get isDisconnecting(){return this.stateMachine.isDisconnecting}get localPorts(){let e=this.getActivePeerConnection();return e?ps(e):[]}getStreamsManagerProvider(){return this.streamsManagerProvider}getContentedStreamManager(){return this.contentedStreamManager}getEstablishedRTCSession=()=>this.mcuSession.getEstablishedRTCSession();subscribeToApiEvents(e){this.stateMachine.subscribeToApiEvents(e.events),this.sessionState.subscribeToApiEvents(e.events)}startCall=async(e,t,n)=>(G(`startCall`,n),this.isPendingCall=!0,this.events.emit(`start-call`,{extraHeaders:n.extraHeaders,number:n.number,answer:!1}),this.mcuSession.startCall(e,t,n).finally(()=>{this.isPendingCall=!1}));async endCall(){return G(`endCall`),this.events.emit(`end-call`),this.mcuSession.endCall()}async renegotiate(){return G(`renegotiate`),this.hasSpectator()?this.renegotiateRecvSession():this.renegotiateMcuSession()}answerToIncomingCall=async(e,t)=>{G(`answerToIncomingCall`,t),this.isPendingAnswer=!0;let n=e();return this.events.emit(`start-call`,{answer:!0,extraHeaders:t.extraHeaders,number:n.remote_identity.uri.user}),this.mcuSession.answerToIncomingCall(n,t).finally(()=>{this.isPendingAnswer=!1})};getMainRemoteStream(){let{mainStream:e}=this.getRemoteStreams();return e}getRemoteStreams(){let{getRemoteStreams:e}=this.getActiveStreamsManagerTools();return e()}getToken(){return this.stateMachine.token}getRecvQuality(){let{recvSession:e}=this;if(e===void 0)return;let t=e.getEffectiveQuality();return{quality:e.getQuality(),effectiveQuality:t}}getActivePeerConnection=()=>this.hasSpectator()?this.recvSession?.peerConnection:this.mcuSession.connection;hasSpectator(){return this.roleManager.hasSpectator()}async replaceMediaStream(e,t){return G(`replaceMediaStream`,e,t),this.mcuSession.replaceMediaStream(e,t)}async restartIce(e){return G(`restartIce`,e),this.mcuSession.restartIce(e)}async restartRecvSession(){G(`restartRecvSession`);let{recvSession:e}=this;if(!this.hasSpectator()||!e)return!1;let t=e.getAudioChannel(),n=e.getQuality(),{callResult:r}=await this.startRecvSessionForced({audioChannel:t,quality:n},{silent:!0});return r}async setRecvQuality(e){G(`setRecvQuality`,e);let{recvSession:t}=this;if(!this.hasSpectator()||!t)return!1;let n=t.getQuality(),r=t.getEffectiveQuality(),i=t.getAudioChannel(),a=qo(e);if(e===n&&a===r)return!1;if(a===r)return await t.setQuality(e),this.events.trigger(`recv-quality-changed`,{previousQuality:n,quality:e,effectiveQuality:r}),!0;let{session:o,callResult:s}=await this.startRecvSessionForced({audioChannel:i,quality:e},{silent:!0});if(s){let t=o.getEffectiveQuality();this.events.trigger(`recv-quality-changed`,{previousQuality:n,quality:e,effectiveQuality:t})}return s}async applyQuality(e){G(`applyQuality`,e);let{recvSession:t}=this;if(!this.hasSpectator()||!t)return!1;let n=t.getQuality(),r=await t.applyQuality(e);return r.applied&&this.events.trigger(`recv-quality-changed`,{previousQuality:n,quality:e,effectiveQuality:r.effectiveQuality}),r.applied}async failed(e,t){this.emitFailedCall(e,t),await this.endCall()}emitFailedCall(e,t){this.events.trigger(`failed`,{message:e,cause:t,originator:`local`})}reset=()=>{this.mainRemoteStreamsManager.reset(),this.recvRemoteStreamsManager.reset(),this.stopRecvSession(),this.deferredStartRecvSessionRunner.cancel(),this.streamsChangeTracker.reset(),this.mcuSession.reset(),this.roleManager.reset()};subscribeCallEndedStateMachine(){this.stateMachine.onStateChange(e=>{e===V.IDLE&&this.reset()})}subscribeCallStatusChange(){let e=this.createCallStatusChangeListener();this.onRace([`accepted`,`confirmed`,`ended`,`failed`],e)}createCallStatusChangeListener(){let e=this.isCallActive;return()=>{let t=this.isCallActive;t!==e&&this.events.trigger(`call-status-changed`,{isCallActive:t}),e=t}}subscribeMcuRemoteTrackEvents(){this.on(`peerconnection:ontrack`,e=>{this.addRemoteTrack(this.mainRemoteStreamsManager,e.track,ms(e))})}addRemoteTrack(e,t,n){let r=e.addTrack(t,{streamHint:n,onRemoved:t=>{this.handleChangedRemoteTracks(e,`removed`,{isRemovedStream:t.isRemovedStream,isAddedStream:!1,trackId:t.trackId,participantId:t.participantId})}});r.isAddedTrack&&this.handleChangedRemoteTracks(e,`added`,{isRemovedStream:!1,isAddedStream:r.isAddedStream,trackId:t.id,participantId:r.participantId})}handleChangedRemoteTracks(e,t,{trackId:n,participantId:r,isRemovedStream:i,isAddedStream:a}){let o=this.getActiveStreamsManagerTools();if(e!==o.manager)return;let s=o.getRemoteStreams();this.emitEventChangedRemoteTracks(s,t,{trackId:n,participantId:r}),(a||i)&&this.emitEventChangedRemoteStreams(s)}emitEventChangedRemoteTracks(e,t,{trackId:n,participantId:r}){this.events.trigger(`remote-tracks-changed`,{streams:e,changeType:t,trackId:n,participantId:r})}emitEventChangedRemoteStreamsConnected=()=>{this.emitEventChangedRemoteStreams(this.getRemoteStreams())};emitEventChangedRemoteStreams(e){this.streamsChangeTracker.hasChanged(e)&&(this.streamsChangeTracker.updateLastEmittedStreams(e),this.events.trigger(`remote-streams-changed`,{streams:e}))}getActiveStreamsManagerTools(){return this.streamsManagerProvider.getActiveStreamsManagerTools({isSpectator:this.hasSpectator(),stateInfo:this.contentedStreamManager.getStateInfo()})}attachRecvSessionTracks(e){let{peerConnection:t}=e,n=e=>{this.addRemoteTrack(this.recvRemoteStreamsManager,e.track,ms(e))};t.addEventListener(`track`,n),this.disposeRecvSessionTrackListener=()=>{t.removeEventListener(`track`,n)}}async startRecvSessionForced(e,{silent:t}={}){return G(`startRecvSessionForced`,{audioChannel:e.audioChannel,quality:e.quality,silent:t}),this.startRecvSession({audioChannel:e.audioChannel,quality:e.quality},{silent:t})}async startRecvSession({audioChannel:e,quality:t},{silent:n}={}){this.disposeInRoomCredentialsListener?.();let r=this.stateMachine.getInRoomCredentials();if(G(`startRecvSession`,{audioChannel:e,quality:t,silent:n,credentials:r}),r===void 0)return{session:void 0,callResult:!1};this.stopRecvSession({silent:n});let i=new Zo({audioChannel:e,quality:t,pcConfig:this.mcuSession.getPcConfig()},{sendOffer:this.tools.sendOffer});return this.recvSession=i,this.recvRemoteStreamsManager.reset(),this.attachRecvSessionTracks(i),i.call({conferenceNumber:r.conferenceForToken,token:r.token}).then(e=>(n!==!0&&this.events.emit(`recv-session-started`),e&&this.stateMachine.onInRoomConferenceForTokenChange(()=>{G(`onInRoomConferenceForTokenChange`),this.renegotiateRecvSession().catch(()=>{})}),{session:i,callResult:e})).catch(async e=>{this.stopRecvSession();let t=new g.IncomingResponse;t.body=e instanceof Error?e.message:String(e);let n=g.C.causes.INTERNAL_ERROR;throw await this.failed(t,n),e})}stopRecvSession({silent:e}={}){G(`stopRecvSession`,{silent:e});let t=!!this.recvSession;this.disposeInRoomCredentialsListener?.(),this.disposeInRoomCredentialsListener=void 0,this.recvSession?.close(),this.recvSession=void 0,this.disposeRecvSessionTrackListener?.(),this.disposeRecvSessionTrackListener=void 0,this.recvRemoteStreamsManager.reset(),t&&e!==!0&&this.events.emit(`recv-session-ended`)}onRoleChanged=({previous:e,next:t})=>{if(G(`onRoleChanged`,{previous:e,next:t}),Ti(e,t)&&(this.stopRecvSession(),this.deferredStartRecvSessionRunner.cancel(),this.emitEventChangedRemoteStreamsConnected()),Ei(e,t)){let e=t.recvParams;this.stateMachine.getInRoomCredentials()===void 0?this.deferredStartRecvSessionRunner.set({audioId:e.audioId}):this.startRecvSession({audioChannel:e.audioId}).catch(()=>{})}Di(e,t)&&this.mcuSession.restoreBitrateForSenders(),Oi(e,t)&&this.mcuSession.setMinBitrateForSenders()};subscribeContentedStreamEvents(){this.contentedStreamManager.on(`available`,this.emitEventChangedRemoteStreamsConnected),this.contentedStreamManager.on(`not-available`,this.emitEventChangedRemoteStreamsConnected)}async renegotiateRecvSession(){let e=this.stateMachine.getInRoomCredentials();return G(`renegotiateRecvSession`,{credentials:e}),e===void 0||this.recvSession===void 0?!1:this.recvSession.renegotiate({conferenceNumber:e.conferenceForToken,token:e.token})}async renegotiateMcuSession(){return G(`renegotiateMcuSession`),this.mcuSession.renegotiate()}},gs=e=>e instanceof Object&&(`originator`in e||`cause`in e),_s=e=>{if((0,f.isCanceledError)(e))return!0;if(!gs(e))return!1;let{originator:t,cause:n}=e;return typeof n==`string`?n===W.REQUEST_TIMEOUT||n===W.REJECTED||t===`local`&&(n===W.CANCELED||n===W.BYE):!1},vs=function(e){return e.START_PRESENTATION=`presentation:start`,e.STARTED_PRESENTATION=`presentation:started`,e.END_PRESENTATION=`presentation:end`,e.ENDED_PRESENTATION=`presentation:ended`,e.FAILED_PRESENTATION=`presentation:failed`,e}(vs||{}),ys=[`${vs.START_PRESENTATION}`,`${vs.STARTED_PRESENTATION}`,`${vs.END_PRESENTATION}`,`${vs.ENDED_PRESENTATION}`,`${vs.FAILED_PRESENTATION}`],bs=()=>new l.TypedEvents(ys),K=function(e){return e.IDLE=`presentation:idle`,e.STARTING=`presentation:starting`,e.ACTIVE=`presentation:active`,e.STOPPING=`presentation:stopping`,e.FAILED=`presentation:failed`,e}({}),q=function(e){return e.LOG_TRANSITION=`logTransition`,e.LOG_STATE_CHANGE=`logStateChange`,e.SET_ERROR=`setError`,e.CLEAR_ERROR=`clearError`,e}({}),J=function(e){return e.SCREEN_STARTING=`SCREEN.STARTING`,e.SCREEN_STARTED=`SCREEN.STARTED`,e.SCREEN_ENDING=`SCREEN.ENDING`,e.SCREEN_ENDED=`SCREEN.ENDED`,e.SCREEN_FAILED=`SCREEN.FAILED`,e.CALL_ENDED=`CALL.ENDED`,e.CALL_FAILED=`CALL.FAILED`,e.PRESENTATION_RESET=`PRESENTATION.RESET`,e}({}),xs={lastError:void 0},Ss=_(`PresentationStateMachine`),Cs=e=>e instanceof Error?e:Error(JSON.stringify(e)),ws=(0,p.setup)({types:{context:xs,events:{}},actions:{[q.LOG_TRANSITION]:(e,t)=>{Ss(`State transition: ${t.from} -> ${t.to} (${t.event})`)},[q.LOG_STATE_CHANGE]:(e,t)=>{Ss(`PresentationStateMachine state changed`,t.state)},[q.SET_ERROR]:(0,p.assign)(({event:e})=>`error`in e&&e.error!==void 0?{lastError:Cs(e.error)}:{lastError:void 0}),[q.CLEAR_ERROR]:(0,p.assign)(()=>({lastError:void 0}))}}).createMachine({id:`presentation`,initial:K.IDLE,context:xs,states:{[K.IDLE]:{entry:{type:q.LOG_STATE_CHANGE,params:{state:K.IDLE}},on:{[J.SCREEN_STARTING]:{target:K.STARTING,actions:[q.CLEAR_ERROR,{type:q.LOG_TRANSITION,params:{from:K.IDLE,to:K.STARTING,event:J.SCREEN_STARTING}}]}}},[K.STARTING]:{entry:{type:q.LOG_STATE_CHANGE,params:{state:K.STARTING}},on:{[J.SCREEN_STARTED]:{target:K.ACTIVE,actions:{type:q.LOG_TRANSITION,params:{from:K.STARTING,to:K.ACTIVE,event:J.SCREEN_STARTED}}},[J.SCREEN_FAILED]:{target:K.FAILED,actions:[q.SET_ERROR,{type:q.LOG_TRANSITION,params:{from:K.STARTING,to:K.FAILED,event:J.SCREEN_FAILED}}]},[J.SCREEN_ENDED]:{target:K.IDLE,actions:[q.CLEAR_ERROR,{type:q.LOG_TRANSITION,params:{from:K.STARTING,to:K.IDLE,event:J.SCREEN_ENDED}}]},[J.CALL_ENDED]:{target:K.IDLE,actions:[q.CLEAR_ERROR,{type:q.LOG_TRANSITION,params:{from:K.STARTING,to:K.IDLE,event:J.CALL_ENDED}}]},[J.CALL_FAILED]:{target:K.FAILED,actions:[q.SET_ERROR,{type:q.LOG_TRANSITION,params:{from:K.STARTING,to:K.FAILED,event:J.CALL_FAILED}}]}}},[K.ACTIVE]:{entry:{type:q.LOG_STATE_CHANGE,params:{state:K.ACTIVE}},on:{[J.SCREEN_ENDING]:{target:K.STOPPING,actions:{type:q.LOG_TRANSITION,params:{from:K.ACTIVE,to:K.STOPPING,event:J.SCREEN_ENDING}}},[J.SCREEN_ENDED]:{target:K.IDLE,actions:[q.CLEAR_ERROR,{type:q.LOG_TRANSITION,params:{from:K.ACTIVE,to:K.IDLE,event:J.SCREEN_ENDED}}]},[J.SCREEN_FAILED]:{target:K.FAILED,actions:[q.SET_ERROR,{type:q.LOG_TRANSITION,params:{from:K.ACTIVE,to:K.FAILED,event:J.SCREEN_FAILED}}]},[J.CALL_ENDED]:{target:K.IDLE,actions:[q.CLEAR_ERROR,{type:q.LOG_TRANSITION,params:{from:K.ACTIVE,to:K.IDLE,event:J.CALL_ENDED}}]},[J.CALL_FAILED]:{target:K.FAILED,actions:[q.SET_ERROR,{type:q.LOG_TRANSITION,params:{from:K.ACTIVE,to:K.FAILED,event:J.CALL_FAILED}}]}}},[K.STOPPING]:{entry:{type:q.LOG_STATE_CHANGE,params:{state:K.STOPPING}},on:{[J.SCREEN_ENDED]:{target:K.IDLE,actions:[q.CLEAR_ERROR,{type:q.LOG_TRANSITION,params:{from:K.STOPPING,to:K.IDLE,event:J.SCREEN_ENDED}}]},[J.SCREEN_FAILED]:{target:K.FAILED,actions:[q.SET_ERROR,{type:q.LOG_TRANSITION,params:{from:K.STOPPING,to:K.FAILED,event:J.SCREEN_FAILED}}]},[J.CALL_ENDED]:{target:K.IDLE,actions:[q.CLEAR_ERROR,{type:q.LOG_TRANSITION,params:{from:K.STOPPING,to:K.IDLE,event:J.CALL_ENDED}}]},[J.CALL_FAILED]:{target:K.FAILED,actions:[q.SET_ERROR,{type:q.LOG_TRANSITION,params:{from:K.STOPPING,to:K.FAILED,event:J.CALL_FAILED}}]}}},[K.FAILED]:{entry:{type:q.LOG_STATE_CHANGE,params:{state:K.FAILED}},on:{[J.SCREEN_STARTING]:{target:K.STARTING,actions:[q.CLEAR_ERROR,{type:q.LOG_TRANSITION,params:{from:K.FAILED,to:K.STARTING,event:J.SCREEN_STARTING}}]},[J.SCREEN_ENDED]:{target:K.IDLE,actions:[q.CLEAR_ERROR,{type:q.LOG_TRANSITION,params:{from:K.FAILED,to:K.IDLE,event:J.SCREEN_ENDED}}]},[J.PRESENTATION_RESET]:{target:K.IDLE,actions:[q.CLEAR_ERROR,{type:q.LOG_TRANSITION,params:{from:K.FAILED,to:K.IDLE,event:J.PRESENTATION_RESET}}]}}}}}),Ts=_(`PresentationStateMachine`),Es=class extends et{constructor(e){super(ws),this.subscribeCallEvents(e)}get isIdle(){return this.hasState(K.IDLE)}get isStarting(){return this.hasState(K.STARTING)}get isActive(){return this.hasState(K.ACTIVE)}get isStopping(){return this.hasState(K.STOPPING)}get isFailed(){return this.hasState(K.FAILED)}get isPending(){return this.isStarting||this.isStopping}get isActiveOrPending(){return this.isActive||this.isPending}get lastError(){return this.context.lastError}reset(){this.sendEvent({type:J.PRESENTATION_RESET})}send(e){this.sendEvent(e)}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){if(!this.actor.getSnapshot().can(e)){Ts(`[PresentationStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeCallEvents(e){this.addSubscription(e.on(`presentation:start`,()=>{this.sendEvent({type:J.SCREEN_STARTING})})),this.addSubscription(e.on(`presentation:started`,()=>{this.sendEvent({type:J.SCREEN_STARTED})})),this.addSubscription(e.on(`presentation:end`,()=>{this.sendEvent({type:J.SCREEN_ENDING})})),this.addSubscription(e.on(`presentation:ended`,()=>{this.sendEvent({type:J.SCREEN_ENDED})})),this.addSubscription(e.on(`presentation:failed`,e=>{this.sendEvent({type:J.SCREEN_FAILED,error:e})})),this.addSubscription(e.on(`ended`,()=>{this.sendEvent({type:J.CALL_ENDED})})),this.addSubscription(e.on(`failed`,e=>{this.sendEvent({type:J.CALL_FAILED,error:e})}))}},Ds=1,Os=[`presentation:start`,`presentation:started`,`presentation:end`,`presentation:ended`,`presentation:failed`],ks=e=>e instanceof Error?e:Error(String(e)),As=e=>(0,m.hasCanceledError)(e),js=class extends l.EventEmitterProxy{stateMachine;promisePendingStartPresentation;promisePendingStopPresentation;streamPresentationCurrent;maxBitrate;cancelableSendPresentationWithRepeatedCalls;callManager;constructor({callManager:e,maxBitrate:t}){super(bs()),this.callManager=e,this.maxBitrate=t,this.stateMachine=new Es(this.callManager.events),this.subscribe()}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}get isPresentationInProcess(){return!!this.streamPresentationCurrent||this.isPendingPresentation}async startPresentation(e,t,{isNeedReinvite:n,contentHint:r,sendEncodings:i,onAddedTransceiver:a}={},o){let s=this.getRtcSessionProtected();if(this.streamPresentationCurrent)throw Error(`Presentation is already started`);return this.sendPresentationWithDuplicatedCalls(e,{rtcSession:s,stream:t,presentationOptions:{isNeedReinvite:n,contentHint:r,sendEncodings:i,onAddedTransceiver:a},options:o})}async stopPresentation(e){this.cancelSendPresentationWithRepeatedCalls();let t=this.streamPresentationCurrent,n=this.promisePendingStartPresentation??Promise.resolve(void 0);this.promisePendingStartPresentation&&await this.promisePendingStartPresentation.catch(()=>{});let r=this.callManager.getEstablishedRTCSession();return r&&t?n=e().then(async()=>r.stopPresentation(t)).catch(e=>{throw this.notifyPresentationFailed(e),e}):t&&this.events.trigger(`presentation:ended`,t),this.promisePendingStopPresentation=n,n.finally(()=>{this.resetPresentation()})}async updatePresentation(e,t,{contentHint:n,sendEncodings:r,onAddedTransceiver:i}={}){let a=this.getRtcSessionProtected();if(!this.streamPresentationCurrent)throw Error(`Presentation has not started yet`);return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this.sendPresentation(e,a,t,{contentHint:n,isNeedReinvite:!1,sendEncodings:r,onAddedTransceiver:i}).then(async e=>(await this.setMaxBitrate(),e))}cancelSendPresentationWithRepeatedCalls(){this.cancelableSendPresentationWithRepeatedCalls?.stopRepeatedCalls()}subscribe(){Os.forEach(e=>{this.callManager.on(e,t=>{this.events.trigger(e,t)})}),this.callManager.on(`failed`,this.handleEnded),this.callManager.on(`ended`,this.handleEnded)}async sendPresentationWithDuplicatedCalls(e,{rtcSession:t,stream:n,presentationOptions:r,options:i={callLimit:Ds}}){let a=async()=>this.sendPresentation(e,t,n,r),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=(0,m.repeatedCallsAsync)({targetFunction:a,isComplete:o,isRejectAsValid:!0,...i}),this.cancelableSendPresentationWithRepeatedCalls.then(e=>e)}async sendPresentation(e,t,n,{isNeedReinvite:r=!0,contentHint:i=`detail`,degradationPreference:a,sendEncodings:o,onAddedTransceiver:s}){let c=ua(n,{contentHint:i});if(c===void 0)throw Error(`No streamPresentationTarget`);this.streamPresentationCurrent=c;let l=e().then(async()=>t.startPresentation(c,r,{degradationPreference:a,sendEncodings:o,onAddedTransceiver:s})).then(this.setMaxBitrate).then(()=>n).catch(e=>{throw this.removeStreamPresentationCurrent(),this.notifyPresentationFailed(e),e});return this.promisePendingStartPresentation=l,l.finally(()=>{this.promisePendingStartPresentation=void 0})}setMaxBitrate=async()=>{let{connection:e}=this.callManager,{streamPresentationCurrent:t}=this,{maxBitrate:n}=this;!e||!t||n===void 0||await Aa(e.getSenders(),t,n)};getRtcSessionProtected=()=>{let e=this.callManager.getEstablishedRTCSession();if(!e)throw Error(`No rtcSession established`);return e};handleEnded=()=>{this.reset()};reset(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}notifyPresentationFailed(e){this.events.trigger(`presentation:failed`,ks(e))}},Ms=_(`ContentedStreamStateMachine`),Ns=function(e){return e.NOT_AVAILABLE=`contented-stream:not-available`,e.AVAILABLE=`contented-stream:available`,e}({}),Ps=(0,p.setup)({types:{context:{},events:{}},actions:{setCodec:(0,p.assign)(({event:e})=>`codec`in e?{codec:e.codec}:{}),clearCodec:(0,p.assign)({codec:void 0})}}).createMachine({id:`contented-stream`,initial:Ns.NOT_AVAILABLE,context:{},states:{[Ns.NOT_AVAILABLE]:{on:{"CONTENTED_STREAM.AVAILABLE":{target:Ns.AVAILABLE,actions:`setCodec`}}},[Ns.AVAILABLE]:{on:{"CONTENTED_STREAM.NOT_AVAILABLE":{target:Ns.NOT_AVAILABLE,actions:`clearCodec`},"CONTENTED_STREAM.AVAILABLE":{target:Ns.AVAILABLE,actions:`setCodec`,reenter:!0},"CONTENTED_STREAM.RESET":{target:Ns.NOT_AVAILABLE,actions:`clearCodec`}}}}}),Fs=class extends et{constructor(){super(Ps)}get isAvailable(){return this.state===Ns.AVAILABLE}get isNotAvailable(){return this.state===Ns.NOT_AVAILABLE}get codec(){return this.getSnapshot().context.codec}getStateInfo(){return{isAvailable:this.isAvailable,codec:this.codec}}reset(){this.send({type:`CONTENTED_STREAM.RESET`})}send(e){if(!this.actor.getSnapshot().can(e)){Ms(`[ContentedStreamStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeToApiEvents(e){this.addSubscription(e.on(`contented-stream:available`,e=>{this.send({type:`CONTENTED_STREAM.AVAILABLE`,codec:e.codec})})),this.addSubscription(e.on(`contented-stream:not-available`,()=>{this.send({type:`CONTENTED_STREAM.NOT_AVAILABLE`})}))}},Is=function(e){return e.AVAILABLE=`available`,e.NOT_AVAILABLE=`not-available`,e}(Is||{}),Ls=[Is.AVAILABLE,Is.NOT_AVAILABLE],Rs=()=>new l.TypedEvents(Ls),zs=class extends l.EventEmitterProxy{stateMachine;constructor(){super(Rs()),this.stateMachine=new Fs,this.proxyEvents()}get isAvailable(){return this.stateMachine.isAvailable}get codec(){return this.stateMachine.codec}getStateInfo(){return this.stateMachine.getStateInfo()}reset(){this.stateMachine.reset()}subscribeToApiEvents(e){this.stateMachine.subscribeToApiEvents(e.events)}proxyEvents(){this.stateMachine.onStateChange(()=>{let e=this.getStateInfo();e.isAvailable?this.events.trigger(`available`,{codec:e.codec}):this.events.trigger(`not-available`,{})})}},Bs=function(e){return e.RINGING=`ringing`,e.DECLINED_INCOMING_CALL=`declinedIncomingCall`,e.TERMINATED_INCOMING_CALL=`terminatedIncomingCall`,e.FAILED_INCOMING_CALL=`failedIncomingCall`,e}(Bs||{}),Vs=[`${Bs.RINGING}`,`${Bs.DECLINED_INCOMING_CALL}`,`${Bs.TERMINATED_INCOMING_CALL}`,`${Bs.FAILED_INCOMING_CALL}`],Hs=()=>new l.TypedEvents(Vs),Y=function(e){return e.IDLE=`incoming:idle`,e.RINGING=`incoming:ringing`,e.CONSUMED=`incoming:consumed`,e.DECLINED=`incoming:declined`,e.TERMINATED=`incoming:terminated`,e.FAILED=`incoming:failed`,e}({}),X=function(e){return e.LOG_TRANSITION=`logTransition`,e.LOG_STATE_CHANGE=`logStateChange`,e.REMEMBER_INCOMING=`rememberIncoming`,e.REMEMBER_REASON=`rememberReason`,e.CLEAR_INCOMING=`clearIncoming`,e}({}),Z=function(e){return e.RINGING=`INCOMING.RINGING`,e.CONSUMED=`INCOMING.CONSUMED`,e.DECLINED=`INCOMING.DECLINED`,e.TERMINATED=`INCOMING.TERMINATED`,e.FAILED=`INCOMING.FAILED`,e.CLEAR=`INCOMING.CLEAR`,e}({}),Us={remoteCallerData:void 0,lastReason:void 0},Ws=_(`IncomingCallManager: createIncomingCallMachineSetup`),Gs=(0,p.setup)({types:{context:Us,events:{}},actions:{[X.LOG_TRANSITION]:(e,t)=>{Ws(`State transition: ${t.from} -> ${t.to} (${t.event})`)},[X.LOG_STATE_CHANGE]:(e,t)=>{Ws(`IncomingCallStateMachine state changed`,t.state)},[X.REMEMBER_INCOMING]:(0,p.assign)(({event:e})=>({remoteCallerData:e.data,lastReason:void 0})),[X.REMEMBER_REASON]:(0,p.assign)(({event:e,context:t})=>e.type===Z.CONSUMED?{remoteCallerData:t.remoteCallerData,lastReason:Y.CONSUMED}:e.type===Z.DECLINED?{remoteCallerData:e.data,lastReason:Y.DECLINED}:e.type===Z.TERMINATED?{remoteCallerData:e.data,lastReason:Y.TERMINATED}:{remoteCallerData:e.data,lastReason:Y.FAILED}),[X.CLEAR_INCOMING]:(0,p.assign)(()=>({remoteCallerData:void 0,lastReason:void 0}))}}).createMachine({id:`incoming`,initial:Y.IDLE,context:Us,states:{[Y.IDLE]:{entry:{type:X.LOG_STATE_CHANGE,params:{state:Y.IDLE}},on:{[Z.RINGING]:{target:Y.RINGING,actions:[X.REMEMBER_INCOMING,{type:X.LOG_TRANSITION,params:{from:Y.IDLE,to:Y.RINGING,event:Z.RINGING}}]},[Z.CLEAR]:{target:Y.IDLE,actions:[X.CLEAR_INCOMING,{type:X.LOG_TRANSITION,params:{from:Y.IDLE,to:Y.IDLE,event:Z.CLEAR}}]}}},[Y.RINGING]:{entry:{type:X.LOG_STATE_CHANGE,params:{state:Y.RINGING}},on:{[Z.RINGING]:{target:Y.RINGING,actions:[X.REMEMBER_INCOMING,{type:X.LOG_TRANSITION,params:{from:Y.RINGING,to:Y.RINGING,event:Z.RINGING}}]},[Z.CONSUMED]:{target:Y.CONSUMED,actions:[X.REMEMBER_REASON,{type:X.LOG_TRANSITION,params:{from:Y.RINGING,to:Y.CONSUMED,event:Z.CONSUMED}}]},[Z.DECLINED]:{target:Y.DECLINED,actions:[X.REMEMBER_REASON,{type:X.LOG_TRANSITION,params:{from:Y.RINGING,to:Y.DECLINED,event:Z.DECLINED}}]},[Z.TERMINATED]:{target:Y.TERMINATED,actions:[X.REMEMBER_REASON,{type:X.LOG_TRANSITION,params:{from:Y.RINGING,to:Y.TERMINATED,event:Z.TERMINATED}}]},[Z.FAILED]:{target:Y.FAILED,actions:[X.REMEMBER_REASON,{type:X.LOG_TRANSITION,params:{from:Y.RINGING,to:Y.FAILED,event:Z.FAILED}}]},[Z.CLEAR]:{target:Y.IDLE,actions:[X.CLEAR_INCOMING,{type:X.LOG_TRANSITION,params:{from:Y.RINGING,to:Y.IDLE,event:Z.CLEAR}}]}}},[Y.CONSUMED]:{entry:{type:X.LOG_STATE_CHANGE,params:{state:Y.CONSUMED}},on:{[Z.CLEAR]:{target:Y.IDLE,actions:[X.CLEAR_INCOMING,{type:X.LOG_TRANSITION,params:{from:Y.CONSUMED,to:Y.IDLE,event:Z.CLEAR}}]},[Z.RINGING]:{target:Y.RINGING,actions:[X.REMEMBER_INCOMING,{type:X.LOG_TRANSITION,params:{from:Y.CONSUMED,to:Y.RINGING,event:Z.RINGING}}]}}},[Y.DECLINED]:{entry:{type:X.LOG_STATE_CHANGE,params:{state:Y.DECLINED}},on:{[Z.CLEAR]:{target:Y.IDLE,actions:[X.CLEAR_INCOMING,{type:X.LOG_TRANSITION,params:{from:Y.DECLINED,to:Y.IDLE,event:Z.CLEAR}}]},[Z.RINGING]:{target:Y.RINGING,actions:[X.REMEMBER_INCOMING,{type:X.LOG_TRANSITION,params:{from:Y.DECLINED,to:Y.RINGING,event:Z.RINGING}}]}}},[Y.TERMINATED]:{entry:{type:X.LOG_STATE_CHANGE,params:{state:Y.TERMINATED}},on:{[Z.CLEAR]:{target:Y.IDLE,actions:[X.CLEAR_INCOMING,{type:X.LOG_TRANSITION,params:{from:Y.TERMINATED,to:Y.IDLE,event:Z.CLEAR}}]},[Z.RINGING]:{target:Y.RINGING,actions:[X.REMEMBER_INCOMING,{type:X.LOG_TRANSITION,params:{from:Y.TERMINATED,to:Y.RINGING,event:Z.RINGING}}]}}},[Y.FAILED]:{entry:{type:X.LOG_STATE_CHANGE,params:{state:Y.FAILED}},on:{[Z.CLEAR]:{target:Y.IDLE,actions:[X.CLEAR_INCOMING,{type:X.LOG_TRANSITION,params:{from:Y.FAILED,to:Y.IDLE,event:Z.CLEAR}}]},[Z.RINGING]:{target:Y.RINGING,actions:[X.REMEMBER_INCOMING,{type:X.LOG_TRANSITION,params:{from:Y.FAILED,to:Y.RINGING,event:Z.RINGING}}]}}}}}),Ks=_(`IncomingCallStateMachine`),qs=class extends et{constructor({incomingEvents:e,connectionEvents:t}){super(Gs),this.subscribeIncomingEvents(e),this.subscribeConnectionEvents(t)}get isIdle(){return this.hasState(Y.IDLE)}get isRinging(){return this.hasState(Y.RINGING)}get isConsumed(){return this.hasState(Y.CONSUMED)}get isDeclined(){return this.hasState(Y.DECLINED)}get isTerminated(){return this.hasState(Y.TERMINATED)}get isFailed(){return this.hasState(Y.FAILED)}get isActive(){return this.isRinging}get isFinished(){return this.isConsumed||this.isDeclined||this.isTerminated||this.isFailed}get remoteCallerData(){return this.context.remoteCallerData}get lastReason(){return this.context.lastReason}toConsumed=()=>{this.sendEvent({type:Z.CONSUMED})};reset(){this.toClearIncoming()}send(e){this.sendEvent(e)}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){if(!this.actor.getSnapshot().can(e)){Ks(`[IncomingCallStateMachine] Invalid transition: ${e.type} from ${this.state}. Event cannot be processed in current state.`);return}super.send(e)}subscribeIncomingEvents(e){this.addSubscription(e.on(`ringing`,e=>{this.sendEvent({type:Z.RINGING,data:{displayName:e.displayName,host:e.host,incomingNumber:e.incomingNumber}})})),this.addSubscription(e.on(`declinedIncomingCall`,e=>{this.sendEvent({type:Z.DECLINED,data:{displayName:e.displayName,host:e.host,incomingNumber:e.incomingNumber}})})),this.addSubscription(e.on(`terminatedIncomingCall`,e=>{this.sendEvent({type:Z.TERMINATED,data:{displayName:e.displayName,host:e.host,incomingNumber:e.incomingNumber}})})),this.addSubscription(e.on(`failedIncomingCall`,e=>{this.sendEvent({type:Z.FAILED,data:{displayName:e.displayName,host:e.host,incomingNumber:e.incomingNumber}})}))}subscribeConnectionEvents(e){this.addSubscription(e.on(`disconnected`,()=>{this.toClearIncoming()})),this.addSubscription(e.on(`registrationFailed`,()=>{this.toClearIncoming()})),this.addSubscription(e.on(`connect-failed`,()=>{this.toClearIncoming()}))}toClearIncoming=()=>{this.sendEvent({type:Z.CLEAR})}},Js=486,Ys=487,Xs=e=>({displayName:e.remote_identity.display_name,host:e.remote_identity.uri.host,incomingNumber:e.remote_identity.uri.user,rtcSession:e}),Zs=class extends l.EventEmitterProxy{stateMachine;incomingRTCSession;connectionManager;constructor(e){super(Hs()),this.connectionManager=e,this.stateMachine=new qs({incomingEvents:this.events,connectionEvents:this.connectionManager.events}),this.start()}get remoteCallerData(){if(this.incomingRTCSession)return Xs(this.incomingRTCSession)}get isAvailableIncomingCall(){return!!this.incomingRTCSession}start(){this.subscribe()}stop(){this.unsubscribe(),this.removeIncomingSession()}getIncomingRTCSession=()=>{let{incomingRTCSession:e}=this;if(!e)throw Error(`No incomingRTCSession`);return e};extractIncomingRTCSession=()=>{let e=this.getIncomingRTCSession();return this.stateMachine.toConsumed(),this.removeIncomingSession(),e};async declineToIncomingCall({statusCode:e=Ys}={}){return new Promise((t,n)=>{try{let n=this.getIncomingRTCSession(),r=Xs(n);this.removeIncomingSession(),this.events.trigger(`declinedIncomingCall`,r),n.terminate({status_code:e}),t()}catch(e){n(e)}})}async busyIncomingCall(){return this.declineToIncomingCall({statusCode:Js})}subscribe(){this.connectionManager.on(`newRTCSession`,this.handleNewRTCSession)}unsubscribe(){this.connectionManager.off(`newRTCSession`,this.handleNewRTCSession)}handleNewRTCSession=({originator:e,session:t})=>{e===`remote`&&this.setIncomingSession(t)};setIncomingSession(e){this.incomingRTCSession=e;let t=Xs(e);e.on(`failed`,e=>{this.removeIncomingSession(),e.originator===`local`?this.events.trigger(`terminatedIncomingCall`,t):this.events.trigger(`failedIncomingCall`,t)}),this.events.trigger(`ringing`,t)}removeIncomingSession(){delete this.incomingRTCSession}},Qs=class{apiManager;connectionManager;callManager;get user(){return this.connectionManager?.getUser()}get number(){return this.callManager?.number}get isCallInitiator(){return!!this.callManager?.isCallInitiator}get peerToPeerRoom(){if(!(this.user===void 0||this.number===void 0))return this.isCallInitiator?`p2p${this.user}to${this.number}`:`p2p${this.number}to${this.user}`}subscribe({apiManager:e,connectionManager:t,callManager:n}){this.apiManager=e,this.connectionManager=t,this.callManager=n,n.on(`confirmed`,this.maybeSendDirectPeerToPeerRoom)}maybeSendDirectPeerToPeerRoom=()=>{let{peerToPeerRoom:e,number:t,apiManager:n}=this;if(e===void 0||t===void 0||n===void 0)return;let r=[`${b.CONTENT_ENTER_ROOM}: ${this.peerToPeerRoom}`,`${b.PARTICIPANT_NAME}: ${this.number}`,`${b.IS_DIRECT_PEER_TO_PEER}: true`];n.sendEnterRoom(r)}},$s=function(e){return e.SNAPSHOT_CHANGED=`snapshot-changed`,e}($s||{}),ec=[`${$s.SNAPSHOT_CHANGED}`],tc=()=>new l.TypedEvents(ec),nc=(e,t)=>Object.is(e,t),rc=(e,t)=>e.connection.value===t.connection.value&&(0,re.isEqual)(e.call,t.call)&&e.incoming.value===t.incoming.value&&e.presentation.value===t.presentation.value&&e.autoConnector.value===t.autoConnector.value&&(0,re.isEqual)(e.callReconnect,t.callReconnect),ic=e=>({connection:e.connection.getSnapshot(),call:e.call.getSnapshot(),incoming:e.incoming.getSnapshot(),presentation:e.presentation.getSnapshot(),autoConnector:e.autoConnector.getSnapshot(),callReconnect:e.callReconnect.getSnapshot()}),ac=class extends l.EventEmitterProxy{machines;currentSnapshot;subscribers=new Set;actorSubscriptions=[];constructor(e){super(tc()),this.machines={connection:e.connectionManager.stateMachine,call:e.callManager.stateMachine,incoming:e.incomingCallManager.stateMachine,presentation:e.presentationManager.stateMachine,autoConnector:e.autoConnectorManager.stateMachine,callReconnect:e.callReconnectManager.stateMachine},this.currentSnapshot=ic(this.machines),this.actorSubscriptions.push(this.machines.connection.subscribe(this.notifySubscribers),this.machines.call.subscribe(this.notifySubscribers),this.machines.incoming.subscribe(this.notifySubscribers),this.machines.presentation.subscribe(this.notifySubscribers),this.machines.autoConnector.subscribe(this.notifySubscribers),this.machines.callReconnect.subscribe(this.notifySubscribers))}getSnapshot(){return this.currentSnapshot}subscribe(e,t,n){let r=typeof t==`function`,i=r?e:e=>e,a={selector:i,listener:r?t:e,equals:r?n??nc:rc,current:i(this.currentSnapshot)};return this.subscribers.add(a),()=>{this.subscribers.delete(a)}}stop(){this.subscribers.clear(),this.actorSubscriptions.forEach(e=>{e.unsubscribe()})}notifySubscribers=()=>{let e=this.currentSnapshot;this.currentSnapshot=ic(this.machines);let t=rc(e,this.currentSnapshot);for(let e of this.subscribers){let t=e.selector(this.currentSnapshot);e.equals(e.current,t)||(e.current=t,e.listener(t))}t||this.events.trigger(`snapshot-changed`,{previous:e,current:this.currentSnapshot})}},Q=function(e){return e.DISCONNECTED=`system:disconnected`,e.DISCONNECTING=`system:disconnecting`,e.CONNECTING=`system:connecting`,e.READY_TO_CALL=`system:readyToCall`,e.CALL_CONNECTING=`system:callConnecting`,e.CALL_DISCONNECTING=`system:callDisconnecting`,e.CALL_ACTIVE=`system:callActive`,e}({}),oc=e=>e.connection.value,sc=e=>e.autoConnector.value,cc=e=>e.call,lc=e=>e.call.value,uc={selectConnectionStatus:oc,selectAutoConnectorStatus:sc,selectCallState:cc,selectCallStatus:lc,selectIncomingStatus:e=>e.incoming.value,selectPresentationStatus:e=>e.presentation.value,selectIsInCall:e=>{let t=lc(e);return t===V.IN_ROOM||t===V.ROOM_PENDING_AUTH||t===V.PURGATORY||t===V.P2P_ROOM||t===V.DIRECT_P2P_ROOM||t===V.PRESENTATION_CALL},selectSystemStatus:e=>{let t=lc(e);if(t===V.IN_ROOM||t===V.ROOM_PENDING_AUTH||t===V.PURGATORY||t===V.P2P_ROOM||t===V.DIRECT_P2P_ROOM||t===V.PRESENTATION_CALL)return Q.CALL_ACTIVE;let n=oc(e),r=sc(e);if(n===D.DISCONNECTING||r===N.DISCONNECTING)return Q.DISCONNECTING;if(r===N.ATTEMPTING_CONNECT||r===N.ATTEMPTING_GATE||r===N.WAITING_BEFORE_RETRY||r===N.CONNECTED_MONITORING&&n!==D.ESTABLISHED)return Q.CONNECTING;if(n===D.IDLE||n===D.DISCONNECTED)return Q.DISCONNECTED;if(n===D.PREPARING||n===D.CONNECTING||n===D.CONNECTED||n===D.REGISTERED)return Q.CONNECTING;switch(t){case V.IDLE:return Q.READY_TO_CALL;case V.CONNECTING:return Q.CALL_CONNECTING;case V.DISCONNECTING:return Q.CALL_DISCONNECTING;default:return Q.READY_TO_CALL}}},dc=1e3,$=function(e){return e.INBOUND_RTP=`inbound-rtp`,e.REMOTE_OUTBOUND_RTP=`remote-outbound-rtp`,e.MEDIA_SOURCE=`media-source`,e.OUTBOUND_RTP=`outbound-rtp`,e.REMOTE_INBOUND_RTP=`remote-inbound-rtp`,e.CODEC=`codec`,e.CANDIDATE_PAIR=`candidate-pair`,e.CERTIFICATE=`certificate`,e.TRANSPORT=`transport`,e.LOCAL_CANDIDATE=`local-candidate`,e.REMOTE_CANDIDATE=`remote-candidate`,e}({}),fc=function(e){return e.COLLECTED=`collected`,e.STOPPED=`stopped`,e}(fc||{}),pc=[`${fc.COLLECTED}`,`${fc.STOPPED}`],mc=()=>new l.TypedEvents(pc),hc=()=>Ui().isChrome,gc=()=>`performance`in window?performance.now():Date.now(),_c=e=>[...e.keys()].reduce((t,n)=>{let r=e.get(n);return r===void 0?t:{...t,[r.type]:r}},{}),vc=e=>{if(!e)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};let t=_c(e);return{outboundRtp:t[$.OUTBOUND_RTP],codec:t[$.CODEC],mediaSource:t[$.MEDIA_SOURCE],remoteInboundRtp:t[$.REMOTE_INBOUND_RTP]}},yc=e=>{if(!e)return{outboundRtp:void 0,codec:void 0,mediaSource:void 0,remoteInboundRtp:void 0};let t=_c(e);return{outboundRtp:t[$.OUTBOUND_RTP],codec:t[$.CODEC],mediaSource:t[$.MEDIA_SOURCE],remoteInboundRtp:t[$.REMOTE_INBOUND_RTP]}},bc=({videoReceiversStats:e,synchronizationSourcesVideo:t})=>{if(!e)return{inboundRtp:void 0,codec:void 0,synchronizationSources:t};let n=_c(e);return{inboundRtp:n[$.INBOUND_RTP],codec:n[$.CODEC],synchronizationSources:t}},xc=({audioReceiverStats:e,synchronizationSourcesAudio:t})=>{if(!e)return{inboundRtp:void 0,codec:void 0,remoteOutboundRtp:void 0,synchronizationSources:t};let n=_c(e);return{inboundRtp:n[$.INBOUND_RTP],codec:n[$.CODEC],remoteOutboundRtp:n[$.REMOTE_OUTBOUND_RTP],synchronizationSources:t}},Sc=e=>{if(!e)return{candidatePair:void 0,certificate:void 0,localCandidate:void 0,remoteCandidate:void 0,transport:void 0};let t=_c(e);return{candidatePair:t[$.CANDIDATE_PAIR],certificate:t[$.CERTIFICATE],localCandidate:t[$.LOCAL_CANDIDATE],remoteCandidate:t[$.REMOTE_CANDIDATE],transport:t[$.TRANSPORT]}},Cc=({audioSenderStats:e,videoSenderFirstStats:t,videoSenderSecondStats:n})=>({video:yc(t),secondVideo:yc(n),audio:vc(e),additional:Sc(e??t??n)}),wc=({audioReceiverStats:e,videoReceiverFirstStats:t,videoReceiverSecondStats:n,synchronizationSources:r})=>({video:bc({videoReceiversStats:t,synchronizationSourcesVideo:r.video}),secondVideo:bc({videoReceiversStats:n,synchronizationSourcesVideo:r.secondVideo??r.video}),audio:xc({audioReceiverStats:e,synchronizationSourcesAudio:r.audio}),additional:Sc(e??t??n)}),Tc=({audioSenderStats:e,videoSenderFirstStats:t,videoSenderSecondStats:n,audioReceiverStats:r,videoReceiverFirstStats:i,videoReceiverSecondStats:a,synchronizationSources:o})=>({outbound:Cc({audioSenderStats:e,videoSenderFirstStats:t,videoSenderSecondStats:n}),inbound:wc({audioReceiverStats:r,videoReceiverFirstStats:i,videoReceiverSecondStats:a,synchronizationSources:o})}),Ec=async e=>{let t=`audio`,n=`video`,r=e.getSenders(),i=r.find(e=>e.track?.kind===t),a=r.filter(e=>e.track?.kind===n),o=e.getReceivers(),s=o.find(e=>e.track.kind===t),c=o.filter(e=>e.track.kind===n),l={audio:{trackIdentifier:s?.track.id,item:s?.getSynchronizationSources()[0]},video:{trackIdentifier:c[0]?.track.id,item:c[0]?.getSynchronizationSources()[0]},secondVideo:{trackIdentifier:c[1]?.track.id,item:c[1]?.getSynchronizationSources()[0]}};return Promise.all([i?.getStats()??Promise.resolve(void 0),a[0]?.getStats()??Promise.resolve(void 0),a[1]?.getStats()??Promise.resolve(void 0),s?.getStats()??Promise.resolve(void 0),c[0]?.getStats()??Promise.resolve(void 0),c[1]?.getStats()??Promise.resolve(void 0)]).then(e=>{let[t,n,r,i,a,o]=e;return{synchronizationSources:l,audioSenderStats:t,videoSenderFirstStats:n,videoSenderSecondStats:r,audioReceiverStats:i,videoReceiverFirstStats:a,videoReceiverSecondStats:o}})},Dc=_(`StatsPeerConnection`),Oc=class extends l.EventEmitterProxy{setTimeoutRequest;requesterAllStatistics=new f.CancelableRequest(Ec);constructor(){super(mc()),this.setTimeoutRequest=new d.SetTimeoutRequest}get requested(){return this.setTimeoutRequest.requested}start(e,{interval:t=dc,onError:n=Dc}={}){this.setTimeoutRequest.request(()=>{this.collectStatistics(e,{onError:n,onSuccess:t=>{this.start(e,{onError:n,interval:t.interval})}})},t)}stop({reason:e}){this.setTimeoutRequest.cancelRequest(),this.requesterAllStatistics.cancelRequest(),this.events.trigger(`stopped`,{reason:e})}collectStatistics=(e,{onError:t,onSuccess:n})=>{let r=gc();this.requestAllStatistics(e).then(e=>{this.events.trigger(`collected`,Tc(e));let t=gc()-r,i=dc;t>48?i=dc*4:t>32?i=dc*3:t>16&&(i=dc*2),n({interval:i})}).catch(e=>{t&&t(e)})};requestAllStatistics=async e=>{let t=e();if(t===void 0)throw Error(`failed to collect statistics: peerConnection is not defined`);return this.requesterAllStatistics.request(t)}},kc=_(`StatsManager`),Ac=class extends l.EventEmitterProxy{statsPeerConnection;availableStats;previousAvailableStats;callManager;apiManager;constructor({callManager:e,apiManager:t}){let n=new Oc;super(n.events),this.statsPeerConnection=n,this.callManager=e,this.apiManager=t,this.subscribe()}get availableIncomingBitrate(){return this.availableStats?.inbound.additional.candidatePair?.availableIncomingBitrate}get isInvalidInboundFrames(){return this.isEmptyInboundFrames&&this.isReceivingPackets}get isNoInboundVideoTraffic(){return this.packetsReceived===0&&this.bytesReceived===0}get isInboundVideoStalled(){if(this.packetsReceived===void 0||this.previousPacketsReceived===void 0||this.bytesReceived===void 0||this.previousBytesReceived===void 0)return!1;let e=this.previousPacketsReceived>0||this.previousBytesReceived>0,t=this.packetsReceived===this.previousPacketsReceived,n=this.bytesReceived===this.previousBytesReceived;return e&&t&&n}get isEmptyInboundFrames(){return!this.isFramesReceived||!this.isFramesDecoded}get previousAvailableIncomingBitrate(){return this.previousAvailableStats?.inbound.additional.candidatePair?.availableIncomingBitrate}get previousInboundRtp(){return this.previousAvailableStats?.inbound.video.inboundRtp}get previousFramesReceived(){return this.previousInboundRtp?.framesReceived}get previousFramesDecoded(){return this.previousInboundRtp?.framesDecoded}get inboundRtp(){return this.availableStats?.inbound.video.inboundRtp}get framesReceived(){return this.inboundRtp?.framesReceived}get framesDecoded(){return this.inboundRtp?.framesDecoded}get isFramesReceived(){let e=this.framesReceived!==void 0&&this.framesReceived>0,t=this.framesReceived!==this.previousFramesReceived;return e&&t}get isFramesDecoded(){let e=this.framesDecoded!==void 0&&this.framesDecoded>0,t=this.framesDecoded!==this.previousFramesDecoded;return e&&t}get packetsReceived(){return this.inboundRtp?.packetsReceived}get previousPacketsReceived(){return this.previousInboundRtp?.packetsReceived}get bytesReceived(){return this.inboundRtp?.bytesReceived}get previousBytesReceived(){return this.previousInboundRtp?.bytesReceived}get isReceivingPackets(){let e=this.packetsReceived!==void 0&&this.packetsReceived>=500,t=this.packetsReceived!==this.previousPacketsReceived;return e&&t}hasAvailableIncomingBitrateChangedQuarter(){let e=this.previousAvailableIncomingBitrate,t=this.availableIncomingBitrate;return e===void 0||t===void 0?!1:e===0?t>0:Math.abs(t-e)/e>=.25}subscribe(){this.callManager.on(`peerconnection:confirmed`,this.start),this.callManager.on(`recv-session-started`,this.handleRecvSessionStarted),this.callManager.on(`recv-session-ended`,this.handleRecvSessionEnded),this.callManager.on(`recv-quality-changed`,this.handleRecvQualityChanged),this.callManager.on(`failed`,this.handleEnded),this.callManager.on(`ended`,this.handleEnded),this.statsPeerConnection.on(`collected`,this.handleStatsCollected)}handleStatsCollected=e=>{this.previousAvailableStats=this.availableStats,this.availableStats=e,this.maybeSendStats()};start=()=>{this.statsPeerConnection.start(this.callManager.getActivePeerConnection)};stop=e=>{this.statsPeerConnection.stop({reason:e}),this.availableStats=void 0,this.previousAvailableStats=void 0};restart(e){this.stop(e),this.statsPeerConnection.start(this.callManager.getActivePeerConnection)}handleRecvSessionStarted=()=>{this.restart(`recv-session-started`)};handleRecvSessionEnded=()=>{this.restart(`recv-session-ended`)};handleRecvQualityChanged=()=>{this.restart(`recv-quality-changed`)};handleEnded=()=>{this.stop(`call-ended`)};maybeSendStats(){this.availableIncomingBitrate!==void 0&&this.hasAvailableIncomingBitrateChangedQuarter()&&this.apiManager.sendStats({availableIncomingBitrate:this.availableIncomingBitrate}).catch(e=>{kc(`Failed to send stats`,e)})}},jc=_(`setCodecPreferences`),Mc=(e,t)=>e.filter(e=>t.some(t=>t.clockRate===e.clockRate&&t.mimeType===e.mimeType&&t.channels===e.channels&&t.sdpFmtpLine===e.sdpFmtpLine)),Nc=e=>{let t=RTCRtpSender.getCapabilities(e),n=RTCRtpReceiver.getCapabilities(e);return Mc(t===null?[]:t.codecs,n===null?[]:n.codecs)},Pc=(e,t)=>t===void 0||t.length===0?e:e.sort((e,n)=>{let r=t.indexOf(e.mimeType),i=t.indexOf(n.mimeType);return(r===-1?Number.MAX_VALUE:r)-(i===-1?Number.MAX_VALUE:i)}),Fc=(e,t)=>t===void 0||t.length===0?e:e.filter(e=>!t.includes(e.mimeType)),Ic=(e,{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:n})=>{try{if(typeof e.setCodecPreferences==`function`&&e.sender.track?.kind===`video`&&(t!==void 0&&t.length>0||n!==void 0&&n.length>0)){let r=Pc(Fc(Nc(`video`),n),t);e.setCodecPreferences(r)}}catch(e){jc(`setCodecPreferences error`,e)}},Lc=function(e){return e.BALANCING_SCHEDULED=`balancing-scheduled`,e.BALANCING_STARTED=`balancing-started`,e.BALANCING_STOPPED=`balancing-stopped`,e.PARAMETERS_UPDATED=`parameters-updated`,e}(Lc||{}),Rc=[`${Lc.BALANCING_SCHEDULED}`,`${Lc.BALANCING_STARTED}`,`${Lc.BALANCING_STOPPED}`,`${Lc.PARAMETERS_UPDATED}`],zc=()=>new l.TypedEvents(Rc),Bc=_(`VideoSendingBalancerManager`),Vc=class extends l.EventEmitterProxy{isBalancingActive=!1;callManager;balancingStartDelay;videoSendingBalancer;startBalancingTimer;constructor(e,t,n={}){super(zc()),this.callManager=e,this.balancingStartDelay=n.balancingStartDelay??1e4,this.videoSendingBalancer=new Ro(t,()=>e.connection,{...n,onSetParameters:e=>{this.events.trigger(`parameters-updated`,e),n.onSetParameters?.(e)}}),this.subscribe()}get isBalancingScheduled(){return this.startBalancingTimer!==void 0}async startBalancing(){this.isBalancingActive||(this.clearStartTimer(),await this.videoSendingBalancer.balance(),this.videoSendingBalancer.subscribe(),this.isBalancingActive=!0,this.events.trigger(`balancing-started`,{delay:this.balancingStartDelay}))}stopBalancing(){this.clearStartTimer(),this.videoSendingBalancer.unsubscribe(),this.isBalancingActive=!1,this.events.trigger(`balancing-stopped`,{})}async balance(){return this.videoSendingBalancer.balance()}subscribe(){this.callManager.on(`peerconnection:confirmed`,this.handleCallStarted),this.callManager.on(`recv-session-started`,this.handleRecvSessionStarted),this.callManager.on(`recv-session-ended`,this.handleRecvSessionEnded),this.callManager.on(`recv-quality-changed`,this.handleRecvQualityChanged),this.callManager.on(`ended`,this.handleCallEnded),this.callManager.on(`failed`,this.handleCallEnded)}handleCallStarted=()=>{this.scheduleBalancingStart()};handleCallEnded=()=>{this.stopBalancing()};handleRecvSessionStarted=()=>{this.stopBalancing()};handleRecvSessionEnded=()=>{this.scheduleBalancingStart()};handleRecvQualityChanged=()=>{this.stopBalancing()};scheduleBalancingStart(){this.clearStartTimer(),this.startBalancingTimer=setTimeout(()=>{this.startBalancingTimer=void 0,this.startBalancing().catch(e=>{Bc(`startBalancing: error`,e)})},this.balancingStartDelay),this.events.trigger(`balancing-scheduled`,{delay:this.balancingStartDelay})}clearStartTimer(){this.startBalancingTimer&&=(clearTimeout(this.startBalancingTimer),void 0)}},Hc=`health-snapshot`,Uc=`inbound-video-problem-detected`,Wc=`inbound-video-problem-resolved`,Gc=`inbound-video-problem-reset`,Kc=[Hc,Uc,Wc,Gc],qc=()=>new l.TypedEvents(Kc),Jc=3,Yc=class e extends l.EventEmitterProxy{statsManager;callManager;minConsecutiveProblemSamplesCount;consecutiveProblemSamplesCount=0;currentProblemReason;hasEmittedCurrentProblem=!1;constructor(t,n,r=Jc){super(qc()),this.statsManager=t,this.callManager=n,e.assertValidMinConsecutiveProblemSamplesCount(r),this.minConsecutiveProblemSamplesCount=r,this.subscribe()}get mainVideoTrack(){return this.callManager.getMainRemoteStream()?.getVideoTracks()[0]}get isMutedMainVideoTrack(){let{mainVideoTrack:e}=this;return e===void 0?!1:e.muted}get isInvalidInboundFrames(){return this.statsManager.isInvalidInboundFrames}get isNoInboundVideoTraffic(){return this.statsManager.isNoInboundVideoTraffic}get isInboundVideoStalled(){return this.statsManager.isInboundVideoStalled}get healthSnapshot(){return{isMutedMainVideoTrack:this.isMutedMainVideoTrack,isInvalidInboundFrames:this.isInvalidInboundFrames,isNoInboundVideoTraffic:this.isNoInboundVideoTraffic,isInboundVideoStalled:this.isInboundVideoStalled}}static resolveProblemReason(e){if(e.isInboundVideoStalled)return`inbound-video-stalled`;if(e.isNoInboundVideoTraffic)return`no-inbound-video-traffic`;if(e.isMutedMainVideoTrack&&e.isInvalidInboundFrames)return`invalid-inbound-frames`}static assertValidMinConsecutiveProblemSamplesCount(e){if(!Number.isInteger(e)||e<1)throw Error(`minConsecutiveProblemSamplesCount should be a positive integer`)}setMinConsecutiveProblemSamplesCount(t){e.assertValidMinConsecutiveProblemSamplesCount(t),this.minConsecutiveProblemSamplesCount=t,this.resetProblemDetectionState()}handleStatsCollected=()=>{let{healthSnapshot:t}=this;this.events.trigger(Hc,t);let n=e.resolveProblemReason(t);if(n===void 0){this.maybeEmitResolvedProblem(t),this.resetProblemDetectionState();return}this.updateProblemDetectionState(n),this.consecutiveProblemSamplesCount>=this.minConsecutiveProblemSamplesCount&&!this.hasEmittedCurrentProblem&&(this.events.trigger(Uc,{...t,consecutiveProblemSamplesCount:this.consecutiveProblemSamplesCount,reason:n}),this.hasEmittedCurrentProblem=!0)};subscribe(){this.statsManager.on(`collected`,this.handleStatsCollected),this.callManager.on(`peerconnection:confirmed`,this.handleProblemReset(`peerconnection:confirmed`)),this.callManager.on(`recv-session-started`,this.handleProblemReset(`recv-session-started`)),this.callManager.on(`recv-session-ended`,this.handleProblemReset(`recv-session-ended`)),this.callManager.on(`recv-quality-changed`,this.handleProblemReset(`recv-quality-changed`)),this.callManager.on(`failed`,this.handleProblemReset(`failed`)),this.callManager.on(`ended`,this.handleProblemReset(`ended`))}updateProblemDetectionState=e=>{if(this.currentProblemReason===e){this.consecutiveProblemSamplesCount+=1;return}this.currentProblemReason=e,this.consecutiveProblemSamplesCount=1,this.hasEmittedCurrentProblem=!1};maybeEmitResolvedProblem=e=>{!this.hasEmittedCurrentProblem||this.currentProblemReason===void 0||this.events.trigger(Wc,{...e,reason:this.currentProblemReason})};handleProblemReset=e=>()=>{this.maybeEmitResetProblem(e),this.resetProblemDetectionState()};maybeEmitResetProblem=e=>{!this.hasEmittedCurrentProblem||this.currentProblemReason===void 0||this.events.trigger(Gc,{reason:this.currentProblemReason,resetCause:e})};resetProblemDetectionState=()=>{this.currentProblemReason=void 0,this.consecutiveProblemSamplesCount=0,this.hasEmittedCurrentProblem=!1}},Xc=_(`MainStreamRecovery`),Zc=4e3,Qc=class e{renegotiateRequester;renegotiateThrottled;callManager;constructor(e,t=Zc){this.callManager=e,this.renegotiateRequester=new f.CancelableRequest(e.renegotiate.bind(e)),this.renegotiateThrottled=this.createRenegotiateThrottled(t),this.subscribe()}static assertValidThrottleRecoveryTimeout(e){if(!Number.isInteger(e)||e<1)throw Error(`throttleRecoveryTimeout should be a positive integer`)}setThrottleRecoveryTimeout(t){e.assertValidThrottleRecoveryTimeout(t),this.renegotiateThrottled.cancel(),this.renegotiateThrottled=this.createRenegotiateThrottled(t)}recover(){Xc(`trying to recover main stream`),this.renegotiateThrottled()}requestRenegotiate=()=>{if(Xc(`trying to renegotiate`),this.renegotiateRequester.requested){Xc(`previous renegotiate is not finished yet`);return}this.renegotiateRequester.request().then(()=>{Xc(`renegotiate has successful`)}).catch(e=>{Xc(`failed to renegotiate main media stream`,e)})};createRenegotiateThrottled(t){return e.assertValidThrottleRecoveryTimeout(t),re.default.throttle(this.requestRenegotiate.bind(this),t)}subscribe(){this.callManager.on(`ended`,()=>{this.cancel()})}cancel(){Xc(`cancel recover main stream`),this.renegotiateThrottled.cancel(),this.renegotiateRequester.cancelRequest()}},$c=function(e){return e.VP8=`video/VP8`,e.VP9=`video/VP9`,e.H264=`video/H264`,e.AV1=`video/AV1`,e.rtx=`video/rtx`,e.red=`video/red`,e.flexfec03=`video/flexfec-03`,e}({}),el={major:25,minor:8,patch:0},tl=({isYandexBrowser:e,hasGreaterThanBrowserVersion:t})=>{let n=t(el);return e&&n},nl=()=>{if(tl(Ui()))return[$c.VP8]},rl=()=>{let{isMobileDevice:e,isSafari:t,isOpera:n,isWindows:r}=Ui();return e||t||n&&r},il;rl()&&(il=`h264`);var al={ignoreForCodec:il},ol=nl(),sl=1e6,cl=Jt.map(e=>`auto-connect:${e}`),ll=Fn.map(e=>`call-reconnect:${e}`),ul=ht.map(e=>`connection:${e}`),dl=mi.map(e=>`call:${e}`),fl=Ee.map(e=>`api:${e}`),pl=Vs.map(e=>`incoming-call:${e}`),ml=ys.map(e=>`presentation:${e}`),hl=pc.map(e=>`stats:${e}`),gl=Rc.map(e=>`video-balancer:${e}`),_l=Kc.map(e=>`main-stream-health:${e}`),vl=ec.map(e=>`session:${e}`),yl=[`disconnected-from-out-of-call`,`connected-with-configuration-from-out-of-call`,`stopped-presentation-by-server-command`],bl=[...cl,...ll,...ul,...dl,...fl,...pl,...ml,...hl,...gl,..._l,...vl,...yl],xl=()=>new l.TypedEvents(bl),Sl=_(`SipConnector`),Cl=class extends l.EventEmitterProxy{connectionManager;connectionQueueManager;contentedStreamManager;callManager;callSessionState;autoConnectorManager;callReconnectManager;apiManager;incomingCallManager;presentationManager;statsManager;videoSendingBalancerManager;sessionManager;mainStreamHealthMonitor;peerToPeerManager;mainStreamRecovery;preferredMimeTypesVideoCodecs;excludeMimeTypesVideoCodecs;constructor({JsSIP:e},{preferredMimeTypesVideoCodecs:t,excludeMimeTypesVideoCodecs:n,videoBalancerOptions:r,autoConnectorOptions:i,callReconnectOptions:a,numberOfConnectionAttempts:o,minConsecutiveProblemSamplesCount:s,throttleRecoveryTimeout:c}={}){super(xl()),this.preferredMimeTypesVideoCodecs=t??ol,this.excludeMimeTypesVideoCodecs=n,this.apiManager=new Ne,this.connectionManager=new Ot({JsSIP:e},{numberOfConnectionAttempts:o}),this.connectionQueueManager=new kt({connectionManager:this.connectionManager}),this.contentedStreamManager=new zs,this.callSessionState=new Li,this.callManager=new hs({contentedStreamManager:this.contentedStreamManager},{sendOffer:this.sendOffer},{callSessionState:this.callSessionState}),this.incomingCallManager=new Zs(this.connectionManager),this.presentationManager=new js({callManager:this.callManager,maxBitrate:sl}),this.statsManager=new Ac({callManager:this.callManager,apiManager:this.apiManager}),this.autoConnectorManager=new cn({connectionQueueManager:this.connectionQueueManager,connectionManager:this.connectionManager,callManager:this.callManager},i),this.callReconnectManager=new Rn({callManager:this.callManager,connectionManager:this.connectionManager},a),this.videoSendingBalancerManager=new Vc(this.callManager,this.apiManager,r??al),this.mainStreamHealthMonitor=new Yc(this.statsManager,this.callManager,s),this.mainStreamRecovery=new Qc(this.callManager,c),this.sessionManager=new ac({connectionManager:this.connectionManager,callManager:this.callManager,incomingCallManager:this.incomingCallManager,presentationManager:this.presentationManager,autoConnectorManager:this.autoConnectorManager,callReconnectManager:this.callReconnectManager}),this.callManager.subscribeToApiEvents(this.apiManager),this.contentedStreamManager.subscribeToApiEvents(this.apiManager),this.apiManager.subscribe({connectionManager:this.connectionManager,callManager:this.callManager}),this.peerToPeerManager=new Qs,this.peerToPeerManager.subscribe({connectionManager:this.connectionManager,callManager:this.callManager,apiManager:this.apiManager}),this.subscribe()}get requestedConnection(){return this.connectionManager.requested}get isPendingConnect(){return this.connectionManager.isPendingConnect}get isPendingInitUa(){return this.connectionManager.isPendingInitUa}get connectionState(){return this.connectionManager.connectionState}get isRegistered(){return this.connectionManager.isRegistered}get isRegisterConfig(){return this.connectionManager.isRegisterConfig}get socket(){return this.connectionManager.socket}get requestedCall(){return this.callManager.requested}get connection(){return this.callManager.connection}get isCallActive(){return this.callManager.isCallActive}get localPorts(){return this.callManager.localPorts}get remoteCallerData(){return this.incomingCallManager.remoteCallerData}get isAvailableIncomingCall(){return this.incomingCallManager.isAvailableIncomingCall}get isDirectP2PRoom(){return this.callManager.isDirectP2PRoom}get isPresentationCall(){return this.callManager.isPresentationCall}get isOptionalPresentationPermission(){return this.isDirectP2PRoom||this.isPresentationCall}connect=async(...e)=>this.connectionQueueManager.connect(...e);disconnect=async()=>this.connectionQueueManager.disconnect();register=async()=>this.connectionManager.register();unregister=async()=>this.connectionManager.unregister();tryRegister=async()=>this.connectionManager.tryRegister();sendOptions=async(e,t,n)=>this.connectionManager.sendOptions(e,t,n);ping=async(e,t)=>this.connectionManager.ping(e,t);checkTelephony=async e=>this.connectionManager.checkTelephony(e);isConfigured=()=>this.connectionManager.isConfigured();getConnectionConfiguration=()=>this.connectionManager.getConnectionConfiguration();getUri=e=>this.connectionManager.getUri(e);startAutoConnect=async(...e)=>this.autoConnectorManager.start(...e);stopAutoConnect=async()=>this.autoConnectorManager.stop();call=async(e,t={})=>{let{onAddedTransceiver:n,...r}=e,i={...r,onAddedTransceiver:this.resolveHandleAddTransceiver(n)};return t.autoRedial===!0&&this.callReconnectManager.arm({getCallParameters:async()=>i}),this.callManager.startCall(this.connectionManager.getUaProtected(),this.getUri,i)};hangUp=async()=>(this.callReconnectManager.disarm(`local-hangup`),this.callManager.endCall());armCallAutoRedial=e=>{this.callReconnectManager.arm(e)};disarmCallAutoRedial=e=>{this.callReconnectManager.disarm(e)};forceCallReconnect=()=>{this.callReconnectManager.forceReconnect()};cancelCurrentCallReconnectAttempt=()=>{this.callReconnectManager.cancelCurrentAttempt()};answerToIncomingCall=async e=>{let{onAddedTransceiver:t,...n}=e;return this.callManager.answerToIncomingCall(this.incomingCallManager.extractIncomingRTCSession,{...n,onAddedTransceiver:this.resolveHandleAddTransceiver(t)})};declineToIncomingCall=async(...e)=>this.incomingCallManager.declineToIncomingCall(...e);getEstablishedRTCSession=()=>this.callManager.getEstablishedRTCSession();getRemoteStreams=()=>this.callManager.getRemoteStreams();getRecvQuality=()=>this.callManager.getRecvQuality();setRecvQuality=async e=>this.callManager.setRecvQuality(e);applyQuality=async e=>this.callManager.applyQuality(e);replaceMediaStream=async(...e)=>this.callManager.replaceMediaStream(...e);async startPresentation(e,t={}){let{callLimit:n,onAddedTransceiver:r,...i}=t;return this.presentationManager.startPresentation(async()=>{await(this.isOptionalPresentationPermission?this.apiManager.sendAvailableContentedStream():this.apiManager.askPermissionToStartPresentation())},e,{...i,onAddedTransceiver:this.resolveHandleAddTransceiver(r)},n===void 0?void 0:{callLimit:n})}async stopPresentation(){return this.presentationManager.stopPresentation(async()=>{await(this.isOptionalPresentationPermission?this.apiManager.sendNotAvailableContentedStream():this.apiManager.sendStoppedPresentation())})}async updatePresentation(e,t={}){let{onAddedTransceiver:n,...r}=t;return this.presentationManager.updatePresentation(async()=>{await(this.isOptionalPresentationPermission?this.apiManager.sendAvailableContentedStream():this.apiManager.askPermissionToStartPresentation())},e,{...r,onAddedTransceiver:this.resolveHandleAddTransceiver(n)})}async waitChannels(...e){return this.apiManager.waitChannels(...e)}async waitSyncMediaState(...e){return this.apiManager.waitSyncMediaState(...e)}async sendDTMF(...e){return this.apiManager.sendDTMF(...e)}async sendChannels(...e){return this.apiManager.sendChannels(...e)}async sendMediaState(...e){return this.apiManager.sendMediaState(...e)}async sendRefusalToTurnOn(...e){return this.apiManager.sendRefusalToTurnOn(...e)}async sendRefusalToTurnOnMic(...e){return this.apiManager.sendRefusalToTurnOnMic(...e)}async sendRefusalToTurnOnCam(...e){return this.apiManager.sendRefusalToTurnOnCam(...e)}async askPermissionToEnableCam(...e){return this.apiManager.askPermissionToEnableCam(...e)}setMinConsecutiveProblemSamplesCount=e=>{this.mainStreamHealthMonitor.setMinConsecutiveProblemSamplesCount(e)};setThrottleRecoveryTimeout=e=>{this.mainStreamRecovery.setThrottleRecoveryTimeout(e)};subscribeDisconnectedFromOutOfCall(){this.connectionManager.on(`disconnected`,()=>{this.isCallActive||this.events.trigger(`disconnected-from-out-of-call`,{})})}subscribeConnectedWithConfigurationFromOutOfCall(){this.connectionManager.on(`connected-with-configuration`,e=>{this.isCallActive||this.events.trigger(`connected-with-configuration-from-out-of-call`,e)})}mayBeStopPresentationAndNotify(){this.presentationManager.isPresentationInProcess&&(this.stopPresentation().catch(()=>{}),this.events.trigger(`stopped-presentation-by-server-command`,{}))}subscribeToApiEvents(){this.apiManager.on(`participant:move-request-to-participants`,()=>{this.callSessionState.setCallRoleParticipant()}),this.apiManager.on(`participant:move-request-to-spectators-synthetic`,e=>{this.callSessionState.setCallRoleSpectatorSynthetic(e.isAvailableSendingMedia),this.mayBeStopPresentationAndNotify()}),this.apiManager.on(`participant:move-request-to-spectators-with-audio-id`,({audioId:e,isAvailableSendingMedia:t})=>{this.callSessionState.setCallRoleSpectator({audioId:e},t),this.mayBeStopPresentationAndNotify()}),this.apiManager.on(`presentation:must-stop`,()=>{this.mayBeStopPresentationAndNotify()}),this.apiManager.on(`failed-send-room-direct-p2p`,({error:e})=>{let t=new g.IncomingResponse;t.body=e instanceof Error?e.message:String(e);let n=g.C.causes.INTERNAL_ERROR;this.callManager.failed(t,n).catch(e=>{Sl(`Failed to end call after failed:`,e)})})}sendOffer=async(e,t)=>{let n=this.connectionManager.getConnectionConfiguration()?.sipServerUrl;if(n===void 0)throw Error(`No sipServerUrl for sendOffer`);return ma({serverUrl:n,offer:t,token:e.token,conferenceNumber:e.conferenceNumber,quality:e.quality,audio:e.audioChannel})};setCodecPreferences(e){Ic(e,{preferredMimeTypesVideoCodecs:this.preferredMimeTypesVideoCodecs,excludeMimeTypesVideoCodecs:this.excludeMimeTypesVideoCodecs})}subscribe(){this.bridgeEvents(`auto-connect`,this.autoConnectorManager),this.bridgeEvents(`call-reconnect`,this.callReconnectManager),this.bridgeEvents(`connection`,this.connectionManager),this.bridgeEvents(`call`,this.callManager),this.bridgeEvents(`api`,this.apiManager),this.bridgeEvents(`incoming-call`,this.incomingCallManager),this.bridgeEvents(`presentation`,this.presentationManager),this.bridgeEvents(`stats`,this.statsManager),this.bridgeEvents(`video-balancer`,this.videoSendingBalancerManager),this.bridgeEvents(`main-stream-health`,this.mainStreamHealthMonitor),this.bridgeEvents(`session`,this.sessionManager),this.subscribeToApiEvents(),this.subscribeDisconnectedFromOutOfCall(),this.subscribeConnectedWithConfigurationFromOutOfCall(),this.subscribeToMainStreamHealthMonitorEvents()}subscribeToMainStreamHealthMonitorEvents(){this.mainStreamHealthMonitor.on(`inbound-video-problem-detected`,({reason:e})=>{Sl(`detected inbound video problem`,{reason:e}),this.mainStreamRecovery.recover()})}bridgeEvents=(e,t)=>{t.events.eachTriggers((n,r)=>{t.on(r,t=>{this.events.trigger(`${e}:${r}`,t)})})};resolveHandleAddTransceiver=e=>async(t,n,r)=>{this.setCodecPreferences(t),await e?.(t,n,r)}};Object.defineProperty(exports,`A`,{enumerable:!0,get:function(){return Di}}),Object.defineProperty(exports,`B`,{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return ca}}),Object.defineProperty(exports,`D`,{enumerable:!0,get:function(){return wi}}),Object.defineProperty(exports,`E`,{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,`F`,{enumerable:!0,get:function(){return ti}}),Object.defineProperty(exports,`G`,{enumerable:!0,get:function(){return nt}}),Object.defineProperty(exports,`H`,{enumerable:!0,get:function(){return ft}}),Object.defineProperty(exports,`I`,{enumerable:!0,get:function(){return Fn}}),Object.defineProperty(exports,`J`,{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,`K`,{enumerable:!0,get:function(){return xe}}),Object.defineProperty(exports,`L`,{enumerable:!0,get:function(){return Nn}}),Object.defineProperty(exports,`M`,{enumerable:!0,get:function(){return _i}}),Object.defineProperty(exports,`N`,{enumerable:!0,get:function(){return yi}}),Object.defineProperty(exports,`O`,{enumerable:!0,get:function(){return Oi}}),Object.defineProperty(exports,`P`,{enumerable:!0,get:function(){return hi}}),Object.defineProperty(exports,`R`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return Va}}),Object.defineProperty(exports,`T`,{enumerable:!0,get:function(){return Ci}}),Object.defineProperty(exports,`U`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,`V`,{enumerable:!0,get:function(){return gt}}),Object.defineProperty(exports,`W`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,`X`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`Y`,{enumerable:!0,get:function(){return _}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return _s}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return lo}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return ac}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return Hs}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return hc}}),Object.defineProperty(exports,`j`,{enumerable:!0,get:function(){return Ti}}),Object.defineProperty(exports,`k`,{enumerable:!0,get:function(){return Ei}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return qs}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return Es}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return $c}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return uc}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return As}}),Object.defineProperty(exports,`q`,{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return Oc}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return Cl}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return Li}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return po}}),Object.defineProperty(exports,`z`,{enumerable:!0,get:function(){return Lt}});