1import{r as bn,b as Tx,_ as $d,bs as Um,o as ar,c as to,A as ye,a as Me,dk as ji,K as Ts,i as Qv,bB as Yte,bM as la,c2 as $v,fl as eA,L as Xte,M as bi,aK as wi,R as Rx,s as tA,fm as vx,l as nA,av as Ax,aw as iA,D as Xu,F as Vm,S as rA,q as Qo,X as oA,I as Jte,p as zte,d7 as sA,au as qte,B as Cx,ag as Zte,v as Qte,fn as $te,ac as yx,w as aA,dd as ene,z as tne,E as nne}from"./index-D1ciypH--1790928518848.js";import{h as ine}from"./handleSDKErrorNotifi-D3PqJmSa-1790928518848.js";import{u as el}from"./im-DWvXmOG_-1790928518848.js";import{e as rne,I as tl,c as Ix,E as bx,m as one}from"./initwebsdk-CwxycuTF-1790928518848.js";import"./emojis-B1DAhMs_-1790928518848.js";import{E as Oi}from"./index-D_Q1T3tU-1790928518848.js";import{u as wx}from"./contacts-cLDKLyNg-1790928518848.js";import{u as Ox,b as gi}from"./groups-MoC2evLa-1790928518848.js";import{u as Ju,b as Nx,a as Dx}from"./conversation-DYU3q4dN-1790928518848.js";import{r as sne}from"./index-De2rZqby-1790928518848.js";import{C as Px}from"./index-UoqAKHSU-1790928518848.js";import{u as Lx}from"./usersProfile-DrhSNYJP-1790928518848.js";import ane from"./index-DhsNU4uM-1790928518848.js";import cne from"./index-C9NVNmWg-1790928518848.js";import dne from"./index-BEvF4l5c-1790928518848.js";import"./BenzAMRRecorder-D9zRObNz-1790928518848.js";import"./index.vue_vue_type_style_index_0_scoped_6c270f6c_lang-CnMAomNA-1790928518848.js";import"./previewSendImg-LCQPlDlE-1790928518848.js";import"./index-B4RmC0kM-1790928518848.js";import"./index-PVgdu9Xa-1790928518848.js";import"./index-CRTmRX2X-1790928518848.js";import"./index-v-7jxdCq-1790928518848.js";import"./ShareUserCard-DikmmM5t-1790928518848.js";import{C as lne,A as yr,a as Vt,b as Rs,c as xm,_ as une,u as hne,d as ua,e as pne}from"./el-checkbox-group-CFFUtsvX-1790928518848.js";import{_ as _ne}from"./index-BOgcWpJS-1790928518848.js";import"./index-Dosfr4nA-1790928518848.js";import"./axios.js";import"./assign-BX4k7dw1-1790928518848.js";import"./message-ByZU7EkM-1790928518848.js";import"./useUserInfoExt-CnUux_fu-1790928518848.js";import"./MiniInfoCard-B62YBHIW-1790928518848.js";import"./Group77-BAEojecb-1790928518848.js";import"./UserOnlineStatusCard-CqMY8kGL-1790928518848.js";import"./onLineStatus-kpvT3oM2-1790928518848.js";import"./index-DJyH9lcg-1790928518848.js";import"./createGroups-CMRXJcBe-1790928518848.js";import"./useGetUserMapInfo-DNYjUj4A-1790928518848.js";import"./jiaqun2x-zQbc5TJY-1790928518848.js";import"./filter-086A7pSX-1790928518848.js";import"./applyJoinGroups-9HjmEVVv-1790928518848.js";import"./addFriends-CT3xiU1o-1790928518848.js";import"./Logout-B_M-pKgk-1790928518848.js";import"./EditUserInfoCard-BCNtb_To-1790928518848.js";import"./index-B-75eB1d-1790928518848.js";import"./el-tooltip-l0sNRNKZ-1790928518848.js";import"./sumBy-RloWnA03-1790928518848.js";import"./index-DgXj0TPT-1790928518848.js";import"./ConversationList-DddJr2_0-1790928518848.js";import"./dateFormater-B10sNyHR-1790928518848.js";import"./inform-BA5FlnVx-1790928518848.js";import"./index-BA4dSIpC-1790928518848.js";import"./index-DAqALryG-1790928518848.js";import"./fileSizeFormat-CaYIFQ7D-1790928518848.js";import"./paseLink-C3jmh8xI-1790928518848.js";import"./reportMessage-X-aIJsDB-1790928518848.js";import"./modifyMessage-A2S-_dYQ-1790928518848.js";import"./index-CY_cSdEC-1790928518848.js";import"./audio-DhmtLNty-1790928518848.js";import"./msgQuote-Cf_dGTgz-1790928518848.js";import"./emojiContainer-DG_v44s0-1790928518848.js";import"./vue-at-textarea-Ds8ODneG-1790928518848.js";import"./index-BFWMeEqJ-1790928518848.js";import"./index-CsQ5SMut-1790928518848.js";import"./GroupDesc-D8ARmeE5-1790928518848.js";import"./GroupAnnoun-CfCqbVR4-1790928518848.js";import"./GroupMembers-D9bobWg1-1790928518848.js";import"./useSordedContactsWithPinyin-CZo0gskc-1790928518848.js";import"./GroupBlackList-BDAW7n3o-1790928518848.js";import"./GroupMuteList-mVifzOIw-1790928518848.js";import"./index-De9qgZ2I-1790928518848.js";import"./ContactsItem-DMyFVKnk-1790928518848.js";import"./JoinedGroupsItem-urBNcKIR-1790928518848.js";import"./ContactInfos-CSLHwvWI-1790928518848.js";import"./ContactsRemark-DC3t5L63-1790928518848.js";const $o={CONTACT_INVITED:"contact_invited",CONTACT_ADDED:"contact_added",CONTACT_DELETED:"contact_deleted",CONTACT_REFUSE:"contact_refuse",CONTACT_AGREED:"contact_agreed"},nl=Tx(),mne=async()=>{try{await Oi.open({username:nl.user.easemobUserName,accessToken:nl.user.easemobUserToken})}catch(gt){console.log(gt)}},kx=bn(!0),Ene=()=>{const gt=Ju(),He=wx(),dt=()=>{const{isOpenPlayRing:we,clickRing:St}=Nx();Oi.addEventHandler("connection",{onConnected:()=>{console.log(">>>>>\u73AF\u4FE1\u8FDE\u63A5\u6210\u529F"),el().changeLoginStatus(!0),we.value&&St(),Ye()},onDisconnected:()=>
1{if(console.log(">>>>>\u73AF\u4FE1\u8FDE\u63A5\u5931\u8D25\u672A\u767B\u5F55"),el().changeLoginStatus(!1),kx.value)kx.value=!1;else return;sne().then(async Tt=>{window.localStorage.setItem("EASEIM_loginUser",JSON.stringify({username:nl.user.easemobUserName,accessToken:nl.user.easemobUserToken})),await nl.setUserInfo({...nl.user,easemobUserName:Tt.easemobUserName,easemobUserToken:Tt.easemobUserToken}),mne()})},onOnline:()=>{console.log(">>>>>onOnline"),el().changeNetworkStatus(!0)},onOffline:()=>{console.log(">>>>>onOffline"),el().changeNetworkStatus(!1)},onError:Tt=>{console.log("on error",Tt),ine(Tt.type,Tt.message)}})},Ye=()=>{Ae(),re(),le(),Xe(),gt.getConversationList()},Ae=()=>{const we=Oi.user;el().getMyUserInfo(we)},re=()=>{He.fetchAllContactsListWithRemarkFromServer()},le=()=>{He.fetchBlackList()},Xe=()=>{Ox().fetchJoinedGroupListFromServer()};return{mountConnectEventListener:dt,fetchLoginUsersInitData:Ye,getMyUserInfos:Ae,fetchFriendList:re,fetchTheLoginUserBlickList:le,fetchGroupList:Xe}},fne=()=>{const gt=Dx(),He=Ju(),dt=Lx(),Ye=le=>{gt.createNewMessage(le),dt.processMessageExt({root:!0})},Ae=le=>{const{from:Xe,to:we,mid:St}=le,Tt=we===Oi.user?Xe:we,bt=we===Oi.user?Px.SINGLE:Px.GROUP;gt.changeMessageBody({type:rne.RECALL,key:Tt,mid:St}),He.updateConversationList({conversationId:Tt,chatType:bt})},re=le=>{const{from:Xe,to:we,id:St,chatType:Tt}=le;if(!we)return;const bt=we===Oi.user?Xe:we;gt.changeMessageBody({conversationId:bt,messageId:St,status:"modified"}),He.updateConversationList({conversationId:bt,chatType:Tt})};return{mountReviceMessageEventListener:()=>{Oi.addEventHandler("messageListen",{onTextMessage:function(le){Ye(le)},onEmojiMessage:function(le){Ye(le)},onImageMessage:function(le){Ye(le)},onCmdMessage:function(le){},onAudioMessage:function(le){Ye(le)},onLocationMessage:function(le){Ye(le)},onFileMessage:function(le){Ye(le)},onCustomMessage:function(le){Ye(le)},onVideoMessage:function(le){Ye(le)},onRecallMessage:function(le){Ae(le)},onModifiedMessage:function(le){re(le)}})},pushNewMessage:Ye,otherModifyMessage:re,otherRecallMessage:Ae}},gne=()=>{const gt=el(),He=dt=>{gt.handlePresenceChanges(dt)};return{mountPresenceEventListener:()=>{Oi.addEventHandler("presenceStatusChange",{onPresenceStatusChange:dt=>{He(...dt)}})}}},Sne=()=>{const gt=Ju(),He=wx(),dt=(Ae,re)=>{gt.createNewInform({fromType:Ae,informContent:re})},Ye=(Ae,re)=>{switch(console.log("onDispatchContactEvent",re),Ae){case $o.CONTACT_INVITED:dt(tl.FRIEND,re);break;case $o.CONTACT_ADDED:dt(tl.FRIEND,re),He.onAddNewContact(re);break;case $o.CONTACT_AGREED:re.type="other_person_agree",dt(tl.FRIEND,re),He.onAddNewContact(re);break;case $o.CONTACT_REFUSE:re.type="other_person_refuse",dt(tl.FRIEND,re);break;case $o.CONTACT_DELETED:dt(tl.FRIEND,re),He.onDeleteContact(re)}};return{mountContactEventListener:()=>{Oi.addEventHandler("friendListen",{onContactInvited:Ae=>{console.log("onContactInvited",Ae),Ye($o.CONTACT_INVITED,Ae)},onContactDeleted:Ae=>{console.log("onContactDeleted",Ae),Ye($o.CONTACT_DELETED,Ae)},onContactAdded:Ae=>{console.log("onContactAdded",Ae),Ye($o.CONTACT_ADDED,Ae)},onContactRefuse:Ae=>{console.log("onContactRefuse",Ae),Ye($o.CONTACT_REFUSE,Ae)},onContactAgreed:Ae=>{console.log("onContactAgreed",Ae),Ye($o.CONTACT_AGREED,Ae)}})}}},Tne=()=>{const gt=Ju(),He=Ox(),dt=Lx(),Ye=(re,le)=>{gt.createNewInform({fromType:re,informContent:le})},Ae=re=>{var St;const{operation:le,id:Xe,from:we}=re;switch(le){case gi.MEMBER_PRESENCE:{const Tt={groupId:Xe,type:"groupMemberCount",params:re.memberCount};He.updateCacheGroupInfo(Tt),He.updateGroupMembers({groupId:Xe,type:gi.MEMBER_PRESENCE,member:we})}break;case gi.MEMBER_ABSENCE:{const Tt={groupId:Xe,type:"groupMemberCount",params:re.memberCount};He.updateCacheGroupInfo(Tt),He.updateGroupMembers({groupId:Xe,type:gi.MEMBER_ABSENCE,member:we})}break;case gi.UPDATE_ANNOUNCEMENT:console.log(">>>>\u7FA4\u7EC4\u516C\u544A\u66F4\u65B0",re),He.fetchGroupDetailFromServer(Xe);break;case gi.SET_ADMIN:He.updateGroupsAdmin({type:gi.SET_ADMIN,groupId:Xe,userId:we});break;case gi.REMOVE_ADMIN:He.updateGroupsAdmin({type:gi.SET_ADMIN,groupId:Xe,userId:we});break;case gi.MUTE_MEMBER:He.fetchGroupDetailFromServer(Xe);break;case gi.UNMUTE_MEMBER:He.fetchGroupDetailFromServer(Xe);break;case gi.REMOVE_MEMBER:He.deleteJoinedGroupList({groupId:Xe});break;case gi.DESTROY:console.log(">>>>\u89E3\u6563\u5220\u9664\u7FA4\u7EC4"),He.deleteJoinedGroupList({groupId:Xe});break;case gi.UPDATE_INFO:{const{detail:Tt}=re;Tt.name?He.updateCacheGroupInfo({groupId:Xe,type:"groupName",params:Tt.name}):Tt.description&&He.updateCacheGroupInfo({groupId:Xe,type:"groupDescription",params:Tt.description})}break;case gi.ACCEPT_REQUEST:He.fetchJoinedGroupListFromServer();break;case gi.MEMBER_ATTRIBUTES_UPDATE:console.log("groupevent",re),dt.updateUserProfile({userId:we,sourceType:"group",groupId:Xe,profile:{nickName:(St=re==null?void 0:re.attributes)==null?void 0:St.nickName}});break;case gi.DIRECT_JOINED:He.fetchJoinedGroupListFromServer({startPageNum:0})}};return{mountGroupEventListener:()=>{Oi.addEventHandler("groupEvent",{onGroupEvent:re=>{console.log("groupEvent: ",re),Ye(tl.GROUP,re),Ae(re)}})}}},Rne=()=>{const gt=Dx(),He=()=>{console.log("mountReadAckEventListener"),Oi.addEventHandler("aboutReadAckMessage",{onReadMessage:Ae=>{dt(Ae)},onChannelMessage:Ae=>{Ye(Ae)}})},dt=Ae=>{const{mid:re,to:le,from:Xe}=Ae,we=le===Oi.user?Xe:le,St={id:re,key:we,type:Ix.READ_STATUS};gt.updateMessageIdsCollection(St)},Ye=Ae=>{const{to:re,from:le}=Ae,Xe={key:re===Oi.user?le:re,type:Ix.CHANLE_STATUS};gt.updateMessageIdsCollection(Xe)};return{mountReadAckEventListener:He}},vne=()=>{const{mountConnectEventListener:gt}=Ene();gt();const{mountPresenceEventListener:He}=gne();He();const{mountReviceMessageEventListener:dt}=fne();dt();const{mountContactEventListener:Ye}=Sne();Ye();const{mountGroupEventListener:Ae}=Tne();Ae();const{mountReadAckEventListener:re}=Rne();re()},Ane="/assets/mp3/ring-i6Iec9Ue.mp3";function Cne(gt,He){const{username:dt,channelName:Ye}=He,Ae=new Headers;Ae.append("authorization",`Bearer ${gt.context.accessToken}`);const re={method:"GET",headers:Ae,redirect:"follow"};return new Promise(function(le,Xe){fetch(`${gt.apiUrl}/token/rtcToken/v1?userAccount=${dt}&channelName=${Ye}&appkey=${window.encodeURIComponent(gt.appKey)}`,re).then(we=>we.text()).then(we=>{console.log("result",JSON.parse(we)),le(JSON.parse(we))}).catch(we=>{Xe(we),console.log("error",we)})})}function yne(gt,He){const{username:dt,channelName:Ye}=He,Ae=new Headers;Ae.append("authorization",`Bearer ${gt.context.accessToken}`);const re={method:"GET",headers:Ae,redirect:"follow"};return new Promise(function(le,Xe){fetch(`${gt.apiUrl}/channel/mapper?userAccount=${dt}&channelName=${Ye}&appkey=${window.encodeURIComponent(gt.appKey)}`,re).then(we=>we.text()).then(we=>{console.log("result",JSON.parse(we)),le(JSON.parse(we))}).catch(we=>{Xe(we),console.log("error",we)})})}const cA="/assets/png/[email protected]",Ine="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAA/FBMVEUAAAD///9V/6o7xIkwv38xwoYzu38yuX0wun0xuH4vuH4xuX0xuHwxuH0wt34vuH0wt34wuH0wuH0wt30wt3wvt30wt30wuH0vuH0wt3wwuHwvt3wvt30vuHwvt3wxt30zuH82uYA3uoE6uoNBvYdDvohEvolGv4pQwpFTw5NaxZdfx5piyJxlyZ5oyp9py6Bqy6Fzzqd0z6d/0q6A06+D1LGU2rub3MCn4Miq4cqt4suu48yv48y15dC25dG45tLB6dfF6trG69vJ7N3L7d7N7d/R7+LT8OPV8OTW8OXY8ebd8+ng9Ovh9Oz
1i9e3s+PP5/fv6/fz+/v7////QaJQSAAAAHnRSTlMAAQMNEBUeMztTYWJzfoCNjqWxxMvS1d/p6uzu+f4xjky/AAACE0lEQVRYw62X6XaCMBCFY60LKioVBRSnq3bf7d5q99ai3Xj/dykgtVImJhDvL85w5juQTG5mCKEoJcmKqtVNs66piiylSCRlStUmBNSsljK82clCDVDVCkmO9PliA6hqFOcZ6YmcAVNl5BLT8tMVYKqSpudndeCQnqXl503gkplH0+fKwK3yHJK/ABG0ECaUIZLKof+HiPq3DlkzKsAM7EVah8jSJ+ohUYEYqvzVZA5iKTc+P0Y8gPF7sooQU0X//DfiAhojfyhAbBU8QNh/Nh6H1tvLwyETUPP8Lxzv2Z6+WkyC65OlcLg7Atj7TEDJAVTD4TMfcMwEVB3/b4bDHR9wzgQ0U0RCwrs+YMjeB4nISLTlA+wlJkAmChZ+HeU/s79AISoWPvXyB202QCUaFt7kzQeN1NG45QCueIq5TnAvO3IA3zs8zkYBeMs4XOUB4L8Ae+4q3C1y/IJGeXPjEq59wtKURVQpb5b7LuF2xXlsP9vvFycHa/g2KjT2+odLsLahPRiV1ecBWkgy9eu2PML35eC3sO/RUpboC7TetwN6QQ8TdpzH69ANAN7Q44wZysRuvk4ALNRQMEsL1KQ1BgxxS8uwamXz1P+MJ9xUSY1dsK3dzlm3t4HbuvjFIny1CV+u4te7cIMh3uIIN1nibZ54oyne6oo328LtvvjAMYORR3zoEh/7xAfPGYy+Mxi+o43/P04SoQFYzkiwAAAAAElFTkSuQmCC",Fm="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAABF1BMVEUAAAD/////VVX/Ozv/QED/PT3/Ozv/PDf/PTj/Ojf/PDf/PDf/PDf/Ozf/PDj/PDb/Ozj/Ozb/Ozf/Ozf/Ozb/Ojf/Ozf/Ojf/Ojf/Ozb/Ojb/Ozf/Ojb/Ojb/Ojb/Pzv/QDz/Qz//RED/R0T/Tkr/WFT/WVb/Wlf/W1f/Xlv/Yl7/bGr/bWr/dHH/dXL/dnP/enf/enj/fXr/hIH/h4T/iof/j43/kI7/kpD/lJL/lZP/mJb/pKL/pqX/qqn/rq3/r63/t7b/uLf/vLv/vr3/x8b/yMf/ycj/y8r/zMr/zMv/zcz/0dD/1NP/2tn/3d3/3t3/4uH/4+L/4+P/6Oj/6un/7+//8PD/+Pf/+/v//f3//v7///9gMC4FAAAAHnRSTlMAAQMNEBUeMztTYWJzfoCNjqWxxMvS1d/p6uzu+f4xjky/AAACA0lEQVRYw61Xd1/CQAw9lFX2KLsEFdwobhEHAjIcIC4c8P0/h0hL8a5XbRven8nL6+/ukjQhRAcOwR8WE2lJSifEsF9wEFNwBWNZoJCNBV1Goxd9ceAi7ls0EG4PZEAXmYD9n3CbJwV/IuWx/RXvjMK/iDr1491JMICkWy/eK4EhSF5u+EIIDCO0wImPgAlEtAohMIWQ5vxgEsw9uCWzAhL1Fs4kmEbyVz7YomAB0VlOesASPGr9pKwJpKaVFQCLCCj1n7EqkJH7gw8swzcRiFsXiE/6HyDw0yeDGIHgWCCGEYiN+38WI5B1EAFQEIhfz5UrVi5r7V6vXbusFHN6LD8Jc+0b5dbH6Bc+WuV1LjFMRI51uzPioLPNoYokobGVukrEcNC/bzTu++9DxdAtacgJkmYshTuZ/FTdy09t+f3qs2y9LTD0NGF62e5AZr6yn1IUBjtMZ6MFclfqiTdp4qrquMrRAtQR6rMrq9ACJzNPnT4CdYkvM9q5rsAzfYnUMx6rrIcVWmCpqbqO6WekE+lMuaoj7YsfvMm+MyaRmFQ+HVO+rvO8pFu++Bw7y2wqs8V0+NTc0kv8tZvHQ00xocsZ3VDwLQ3dVNFtHf9jQf/a0D9X/O8dPWDgRxz0kIUf8/CDJn7UxQ/b6HEfv3DMYeXBL134tQ+/eM5h9Z3D8m1u/f8GKYarOyEnL8cAAAAASUVORK5CYII=",bne={class:"container"},wne={class:"alert_header"},One={class:"avatar"},Nne=["src","alt"],Dne={class:"name"},Pne={class:"alert_footer"},Lne={class:"alert_btns"},kne=["src","alt"],Mne=["src","alt"],Une={__name:"alertModal",props:{callKitStatus:{type:Object,default:()=>({})}},emits:["updateLocalStatus","handleSendAnswerMsg"],setup(gt,{emit:He}){const dt=gt,{callKitStatus:Ye}=Um(dt);console.log("callKitStatuscallKitStatus",Ye);const Ae=Qv(()=>Ye.value.channelInfos??{}),re=He,le=()=>{console.log(">>>>>\u63A5\u542C\u901A\u8BDD"),re("handleSendAnswerMsg",yr.ACCPET)},Xe=()=>{console.log(">>>>>\u62D2\u7EDD\u63A5\u542C"),re("handleSendAnswerMsg",yr.REFUSE)};return(we,St)=>(ar(),to("div",bne,[ye("div",wne,[ye("div",One,[ye("img",{src:Me(cA),alt:Me(ji)("im.call.avatarAlt")},null,8,Nne)]),ye("div",Dne,Ts(Ae.value.callerIMName||Me(ji)("im.call.unknown.caller")),1)]),ye("div",Pne,[ye("p",null,Ts(Me(ji)(Me(lne)[Ae.value.callType])||Me(ji)("im.call.unknown.type")),1),ye("div",Lne,[ye("img",{src:Me(Ine),onClick:le,alt:Me(ji)("im.call.actions.accept")},null,8,kne),ye("img",{src:Me(Fm),onClick:Xe,alt:Me(ji)("im.call.actions.hangup")},null,8,Mne)])])]))}},Vne=$d(Une,[["__scopeId","data-v-37a14dd4"]]),xne="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIIAAACCCAMAAAC93eDPAAACH1BMVEUAAAD////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////kmOy0AAAAtHRSTlMAAQIDBAUGBwgJCgsMDQ4PEBESExUWFxkaGx0eHyAhJCcqKywtMjQ1ODk6Ozw9Pj9ARUZHSEpLTE1OT1BRUlNUVldYWVpbXF5gYmRmaGpsbW9wcnN1dnd4ent/i4yNjpGSlZaXmJmam5ydnqChpqepqqusrbCxs7S1t7u+v8DCw8TFxsfIysvMzc7P0
1dPU1dbX2Nna3N3f4OHi4+Tl5ufp6uvs7e7v8fLz9PX29/j5+vv8/f6d5akhAAAHA0lEQVR42s1c618bVRCdBGiKUHmVQisvWx6itGCtgFQFyqMWLCkYrEBRgyCtCppSoAgVooCWUtOiFgLYghJeaQ1hzx/oh+yGFEKY3STLzqckv3Nnz+7eO3dm7kyIlIg+s8TYbhmZXnRsut2bjsXpEUu7sSRTT+pIWrV5fAN+ZWPcXJ0W5svHlnXOAoBgHzKbKoqyU+OjIyKi41OziypM5iG7AACznWWx4bp+TGWfE8Byf3Nhgn9EQmFz/zIAZ19lTBgI5HatAe7RlhxdYJwup2XUDax15Yb2+pFVk4BgNabw4ClGqwBMVkWGjIChYRZYasuSMybrxhIw22AIzROotwO2OtnKDHU2wF4fgidxwQZMlemUDNWVTQG2C8EagQFgplyndLiufAYYCMZU6BvX4WiKCuYeopocWG9UbDYzrEBvcrBvMrkXsGYoG1u7ivniUEzo4nms1ipZid3AYFJoVnXSIPC17CV1agIuky5UlkVncmHilLwxZxYwlx9K+/rmHBbOyBlQsILhxNDa+MRhrBTw4aVOWAwUYjFY4Czlgq9soSMMDpC+A1tXmAwEoTU8HkerILA4lG4JxnB5PUZhi/EuCpxopbBJK5wHzskzK+gIp/fZgZUD1uapBVjC6orrLVgIaKMMExg2UFjFMIyJQJfoxlwihVkS59AdYG+EK5/CLvku7LtvZqzCpEY8ZsLqPv6D3opBnRoUdIOw+p/zjZhPIlUkaR6N/n5PX0cxqSTFWE/38/MAekg16cGAn3gBjmT1KCQ7sCe+iLShiVSUJth2x1n1mIlSk0LUDOp3mU07yklVKYf9ZTvdgCmduhR0U2h4aSbMoYxUljLM+s6GKth0alPQ2VDl83USdaS61GFy50selgzqUzAsIc/7pQttdAjShi7pY8yakBWUrqwqZcOENSk3WImx4G7ntPuyonFjqBQ/9SHIwOE0tq8oGWdEn+dDrNOdIn9JJaTvyHlgu14BhRS305MrvohReSPfuH736dbuFLhwVQGHUdEidqJFxqi4azb/aXjhmnwKLegkIqJZ5PCff90S9hPhE9kUcjBLRJSGZbZxThtHIJE9H3TLSCOiGvRzR5x9FpDBI2lW134XwdTYj2oiMqOZ63T+F5DBwxMSAzd6mByaYSaicRQyF8JGQAYPju8wAL7g6SzEOJF+Q0hgoU8u+1xvc+z2rZte6QNwP8mXAQSe/5EgbOgpE3Ye4QHv9d19bx/ZZR3xa+JLDIB/T7C02pFJpRhiYWu8DO7n7TXQ4/Hix9eeS7AvWWqHUEpGmDnQiL8k1b1H9+4R1ld34pFNEfeCdQZghpHaedF0hcTgth8jknDM58slQUTe4EXZ7WRBBQf6s6jXFn0g9KYIndexbs1CIyjiBGDbohE+dzD2+KrI4SxDcRFGaBrZDGStqHWY88S+EsGfMbDZmKZFpDKQ34haKzkU3hLB3zOwqVgkB+IYyHsepdusZNgRcWE+4uz9cNAmohnIJx6lf/Cs2O8e9DMGNBqb5AZnR3F6lP7EdUsBAKscewM3k4I4yX/kUZj0oJ1MCrwXIToKv/EozHvQT5gvwoF4BvKRR+kayw1IFVfEPQY2Hg7movxB1MryMj8SwbeYi5JnmlpErZ9zKEgOZi3TNPEM9DlR6z+Mt/aOiN0+zjTQvG1KvyDqPdghi5W2dVagWgELd7Nul27tPd+AzE99RMRdaVtn5c9MaOe6LBmS97y24+ymPH5lDy7mjsTgT9bpjhlGKmE6bmZJ9VqylwH2UCh46PXvLjEdtxK2+5ri8Gh2vb/DYBeFo+8OCF4Gd3hWzI5MvhNfLgCA6wNpQT8G8O2OI3+r75fnPl7+M16+IEHY0MsIZToAuD70ZbC/rDMLqwoxLiegi7TAJc3y1JmADF6cZ8aInoCumh3WRvYwGfzNPmTzhLVygntJPg7IYPSkzOBeVopDkuv7E3h6mX9HYopDZqLnAA4Prh5TkOiRne4iIqJP91zdtdhvkllhKKW7FCX9PBxez/BKWrx8Fd6kn9LUZzP2GmiFqU+qhJWUcQiSgtUbGilOg5uig2LgkwbXwGEA5R7WkUiub+xx2AdDWjgei5w99ENCDRyVauHAWAPH5looHtBACQXRAHrVo9Drr5CE0tQtp/GbHj78oiItlFZpoMBMC2V2Wig21ELJpQYKT7VQfquFImQtlGJroSBdC2X5WmhO0EKLRhgaVfLlNqpooV0n9E1L3Uom16G3bpGnga0n+Aa2HuUNbFpo4yOi9FA0M6YH+RwPvaWTtNDYSkSGhjn57b1tS8BcQ+jMvKfJeYzf5DwW4iZnIiLKk9vqnReG3f7QG96JiCj24q62/7joiIjouF1t/xfD1vYvhb81gf78oCbcf37gNZuZpXv/AqJU4V9A/A+IA56ANl2iKgAAAABJRU5ErkJggg==";var Mx={exports:{}};(function(gt,He){var dt={};(function(Ye,Ae){gt.exports=Ae()})(la,function(){function Ye(e,t){return t.forEach(function(n){n&&typeof n!="string"&&!Array.isArray(n)&&Object.keys(n).forEach(function(i){if(i!=="default"&&!(i in e)){var r=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(e,i,r.get?r:{enumerable:!0,get:function(){return n[i]}})}})}),Object.freeze(e)}var Ae=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof la<"u"?la:typeof self<"u"?self:{};function re(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var le=function(e){try{return!!e()}catch{return!0}},Xe=!le(function(){var e=(function(){}).bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),we=Xe,St=Function.prototype,Tt=St.call,bt=we&&St.bind.bind(Tt,Tt),et=we?bt:function(e){return function(){return Tt.apply(e,arguments)}},Ee=et({}.isPrototypeOf),on=function(e){return e&&e.Math==Math&&e},be=on(typeof globalThis=="object"&&globalThis)||on(typeof window=="object"&&window)||on(typeof self=="object"&&self)||on(typeof Ae=="object"&&Ae)||function(){return this}()||Ae||Function("return this")(),kn=Xe,Yn=Function.prototype,en=Yn.apply,Xn=Yn.call,sn=typeof Reflect=="object"&&Reflect.apply||(kn?Xn.bind(en):function(){return Xn.apply(en,arguments)}),Ze=et,lt=Ze({}.toString),Wt=Ze("".slice),wn=function(e){return Wt(lt(e),8,-1)},Wi=wn,Ni=et,$n=function(e){if(Wi(e)==="Function")return Ni(e)},Ir=typeof document=="object"&&document.all,br={all:Ir,IS_HTMLDDA:Ir===void 0&&Ir!==void 0},es=br.all,Kt=br.IS_HTMLDDA?function(e){return typeof e=="function"||e===es}:function(e){return typeof e=="function"},Ke={},fe=!le(function(){return Object.defineProperty({},1,{get:function(){return 7}}
1)[1]!=7}),Xt=Xe,kt=Function.prototype.call,wt=Xt?kt.bind(kt):function(){return kt.apply(kt,arguments)},oe={},z={}.propertyIsEnumerable,Ie=Object.getOwnPropertyDescriptor,_t=Ie&&!z.call({1:2},1);oe.f=_t?function(e){var t=Ie(this,e);return!!t&&t.enumerable}:z;var it,Ki,Ht=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},fc=le,Kx=wn,Gm=Object,Hx=et("".split),qu=fc(function(){return!Gm("z").propertyIsEnumerable(0)})?function(e){return Kx(e)=="String"?Hx(e,""):Gm(e)}:Gm,gc=function(e){return e==null},Yx=gc,Xx=TypeError,ha=function(e){if(Yx(e))throw Xx("Can't call method on "+e);return e},Jx=qu,zx=ha,vs=function(e){return Jx(zx(e))},dA=Kt,qx=br.all,Hi=br.IS_HTMLDDA?function(e){return typeof e=="object"?e!==null:dA(e)||e===qx}:function(e){return typeof e=="object"?e!==null:dA(e)},cr={},jm=cr,Wm=be,Zx=Kt,lA=function(e){return Zx(e)?e:void 0},Di=function(e,t){return arguments.length<2?lA(jm[e])||lA(Wm[e]):jm[e]&&jm[e][t]||Wm[e]&&Wm[e][t]},As=typeof navigator<"u"&&String(navigator.userAgent)||"",uA=be,Km=As,hA=uA.process,pA=uA.Deno,_A=hA&&hA.versions||pA&&pA.version,mA=_A&&_A.v8;mA&&(Ki=(it=mA.split("."))[0]>0&&it[0]<4?1:+(it[0]+it[1])),!Ki&&Km&&(!(it=Km.match(/Edge\/(\d+)/))||it[1]>=74)&&(it=Km.match(/Chrome\/(\d+)/))&&(Ki=+it[1]);var pa=Ki,EA=pa,Qx=le,$x=be.String,Sc=!!Object.getOwnPropertySymbols&&!Qx(function(){var e=Symbol();return!$x(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&EA&&EA<41}),fA=Sc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",eF=Di,tF=Kt,nF=Ee,iF=Object,ol=fA?function(e){return typeof e=="symbol"}:function(e){var t=eF("Symbol");return tF(t)&&nF(t.prototype,iF(e))},rF=String,Tc=function(e){try{return rF(e)}catch{return"Object"}},oF=Kt,sF=Tc,aF=TypeError,dr=function(e){if(oF(e))return e;throw aF(sF(e)+" is not a function")},cF=dr,dF=gc,sl=function(e,t){var n=e[t];return dF(n)?void 0:cF(n)},gA=wt,SA=Kt,TA=Hi,lF=TypeError,RA={exports:{}},vA=be,uF=Object.defineProperty,hF=function(e,t){try{uF(vA,e,{value:t,configurable:!0,writable:!0})}catch{vA[e]=t}return t},AA="__core-js_shared__",Hm=be[AA]||hF(AA,{}),CA=Hm;(RA.exports=function(e,t){return CA[e]||(CA[e]=t!==void 0?t:{})})("versions",[]).push({version:"3.31.1",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.1/LICENSE",source:"https://github.com/zloirock/core-js"});var Rc=RA.exports,pF=ha,_F=Object,Io=function(e){return _F(pF(e))},mF=Io,EF=et({}.hasOwnProperty),Wn=Object.hasOwn||function(e,t){return EF(mF(e),t)},fF=et,gF=0,SF=Math.random(),TF=fF(1 .toString),Ym=function(e){return"Symbol("+(e===void 0?"":e)+")_"+TF(++gF+SF,36)},RF=Rc,yA=Wn,vF=Ym,AF=Sc,CF=fA,vc=be.Symbol,Xm=RF("wks"),yF=CF?vc.for||vc:vc&&vc.withoutSetter||vF,tn=function(e){return yA(Xm,e)||(Xm[e]=AF&&yA(vc,e)?vc[e]:yF("Symbol."+e)),Xm[e]},IF=wt,IA=Hi,bA=ol,bF=sl,wF=function(e,t){var n,i;if(SA(n=e.toString)&&!TA(i=gA(n,e))||SA(n=e.valueOf)&&!TA(i=gA(n,e)))return i;throw lF("Can't convert object to primitive value")},OF=TypeError,NF=tn("toPrimitive"),DF=function(e,t){if(!IA(e)||bA(e))return e;var n,i=bF(e,NF);if(i){if(n=IF(i,e,t),!IA(n)||bA(n))return n;throw OF("Can't convert object to primitive value")}return wF(e)},PF=ol,Zu=function(e){var t=DF(e,"string");return PF(t)?t:t+""},wA=Hi,Jm=be.document,LF=wA(Jm)&&wA(Jm.createElement),zm=function(e){return LF?Jm.createElement(e):{}},kF=zm,OA=!fe&&!le(function(){return Object.defineProperty(kF("div"),"a",{get:function(){return 7}}).a!=7}),MF=fe,UF=wt,VF=oe,xF=Ht,FF=vs,BF=Zu,GF=Wn,jF=OA,NA=Object.getOwnPropertyDescriptor;Ke.f=MF?NA:function(e,t){if(e=FF(e),t=BF(t),jF)try{return NA(e,t)}catch{}if(GF(e,t))return xF(!UF(VF.f,e,t),e[t])};var WF=le,KF=Kt,HF=/#|\.prototype\./,al=function(e,t){var n=XF[YF(e)];return n==zF||n!=JF&&(KF(t)?WF(t):!!t)},YF=al.normalize=function(e){return String(e).replace(HF,".").toLowerCase()},XF=al.data={},JF=al.NATIVE="N",zF=al.POLYFILL="P",DA=al,qF=dr,ZF=Xe,QF=$n($n.bind),Cs=function(e,t){return qF(e),t===void 0?e:ZF?QF(e,t):function(){return e.apply(t,arguments)}},wr={},PA=fe&&le(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),$F=Hi,eB=String,tB=TypeError,Si=function(e){if($F(e))return e;throw tB(eB(e)+" is not an object")},nB=fe,iB=OA,rB=PA,Qu=Si,LA=Zu,oB=TypeError,qm=Object.defineProperty,sB=Object.getOwnPropertyDescriptor,Zm="enumerable",Qm
1="configurable",$m="writable";wr.f=nB?rB?function(e,t,n){if(Qu(e),t=LA(t),Qu(n),typeof e=="function"&&t==="prototype"&&"value"in n&&$m in n&&!n[$m]){var i=sB(e,t);i&&i[$m]&&(e[t]=n.value,n={configurable:Qm in n?n[Qm]:i[Qm],enumerable:Zm in n?n[Zm]:i[Zm],writable:!1})}return qm(e,t,n)}:qm:function(e,t,n){if(Qu(e),t=LA(t),Qu(n),iB)try{return qm(e,t,n)}catch{}if("get"in n||"set"in n)throw oB("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var aB=wr,cB=Ht,ys=fe?function(e,t,n){return aB.f(e,t,cB(1,n))}:function(e,t,n){return e[t]=n,e},$u=be,dB=sn,lB=$n,uB=Kt,hB=Ke.f,pB=DA,Ac=cr,_B=Cs,Cc=ys,kA=Wn,mB=function(e){var t=function(n,i,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(n);case 2:return new e(n,i)}return new e(n,i,r)}return dB(e,this,arguments)};return t.prototype=e.prototype,t},st=function(e,t){var n,i,r,o,s,a,c,d,l,h=e.target,u=e.global,p=e.stat,E=e.proto,m=u?$u:p?$u[h]:($u[h]||{}).prototype,g=u?Ac:Ac[h]||Cc(Ac,h,{})[h],R=g.prototype;for(o in t)i=!(n=pB(u?o:h+(p?".":"#")+o,e.forced))&&m&&kA(m,o),a=g[o],i&&(c=e.dontCallGetSet?(l=hB(m,o))&&l.value:m[o]),s=i&&c?c:t[o],i&&typeof a==typeof s||(d=e.bind&&i?_B(s,$u):e.wrap&&i?mB(s):E&&uB(s)?lB(s):s,(e.sham||s&&s.sham||a&&a.sham)&&Cc(d,"sham",!0),Cc(g,o,d),E&&(kA(Ac,r=h+"Prototype")||Cc(Ac,r,{}),Cc(Ac[r],o,s),e.real&&R&&(n||!R[o])&&Cc(R,o,s)))},EB=Math.ceil,fB=Math.floor,gB=Math.trunc||function(e){var t=+e;return(t>0?fB:EB)(t)},SB=gB,eE=function(e){var t=+e;return t!=t||t===0?0:SB(t)},TB=eE,RB=Math.max,vB=Math.min,tE=function(e,t){var n=TB(e);return n<0?RB(n+t,0):vB(n,t)},AB=eE,CB=Math.min,MA=function(e){return e>0?CB(AB(e),9007199254740991):0},yB=MA,ts=function(e){return yB(e.length)},IB=vs,bB=tE,wB=ts,UA=function(e){return function(t,n,i){var r,o=IB(t),s=wB(o),a=bB(i,s);if(e&&n!=n){for(;s>a;)if((r=o[a++])!=r)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===n)return e||a||0;return!e&&-1}},nE={includes:UA(!0),indexOf:UA(!1)},OB=nE.includes;st({target:"Array",proto:!0,forced:le(function(){return!Array(1).includes()})},{includes:function(e){return OB(this,e,arguments.length>1?arguments[1]:void 0)}});var NB=cr,lr=function(e){return NB[e+"Prototype"]},DB=lr("Array").includes,PB=Hi,LB=wn,kB=tn("match"),iE=function(e){var t;return PB(e)&&((t=e[kB])!==void 0?!!t:LB(e)=="RegExp")},MB=iE,UB=TypeError,VA={};VA[tn("toStringTag")]="z";var rE=String(VA)==="[object z]",VB=rE,xB=Kt,eh=wn,FB=tn("toStringTag"),BB=Object,GB=eh(function(){return arguments}())=="Arguments",ns=VB?eh:function(e){var t,n,i;return e===void 0?"Undefined":e===null?"Null":typeof(n=function(r,o){try{return r[o]}catch{}}(t=BB(e),FB))=="string"?n:GB?eh(t):(i=eh(t))=="Object"&&xB(t.callee)?"Arguments":i},jB=ns,WB=String,Yi=function(e){if(jB(e)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return WB(e)},KB=tn("match"),HB=st,YB=function(e){if(MB(e))throw UB("The method doesn't accept regular expressions");return e},XB=ha,xA=Yi,JB=function(e){var t=/./;try{"/./"[e](t)}catch{try{return t[KB]=!1,"/./"[e](t)}catch{}}return!1},zB=et("".indexOf);HB({target:"String",proto:!0,forced:!JB("includes")},{includes:function(e){return!!~zB(xA(XB(this)),xA(YB(e)),arguments.length>1?arguments[1]:void 0)}});var qB=lr("String").includes,FA=Ee,ZB=DB,QB=qB,oE=Array.prototype,sE=String.prototype,$B=function(e){var t=e.includes;return e===oE||FA(oE,e)&&t===oE.includes?ZB:typeof e=="string"||e===sE||FA(sE,e)&&t===sE.includes?QB:t},x=re($B),e3=dr,t3=Io,n3=qu,i3=ts,r3=TypeError,o3=function(e){return function(t,n,i,r){e3(n);var o=t3(t),s=n3(o),a=i3(o),c=e?a-1:0,d=e?-1:1;if(i<2)for(;;){if(c in s){r=s[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw r3("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=d)c in s&&(r=n(r,s[c],c,o));return r}},s3={left:o3(!1)},a3=le,th=function(e,t){var n=[][e];return!!n&&a3(function(){n.call(null,t||function(){return 1},1)})},yc=typeof process<"u"&&wn(process)=="process",c3=s3.left;st({target:"Array",proto:!0,forced:!yc&&pa>79&&pa<83||!th("reduce")},{reduce:function(e){var t=arguments.length;return c3(this,e,t,t>1?arguments[1]:void 0)}});var d3=lr("Array").reduce,l3=Ee,u3=d3,aE=Array.prototype,h3=function(e){var t=e.reduce;return e===aE||l3(aE,e)&&t===aE.reduce?u3:t},BA=h3,ei=re(BA),p3=wn,cl=Array.isArray||function(e){return p3(e)=="Array"},_3=st,m3=cl,E3=et([].reverse),GA=[1,2];_3({target:"Array",proto:!0,forced:String(GA)===String(GA.reverse())},{reverse:function(){return m3(this)&&(this.length=this.length),E3(this)}});var f3=lr("Array").reverse,g3=Ee,S3=f3,cE=Array.prototype,T3=function(e){var t=e.reverse;return e===cE||g3(cE,e)&&t===cE.reverse?S3:t},jA=T3,_a=re(jA),R3=Ym,WA=Rc("keys"),nh=function(e){return WA[e]||(WA[e]=R3(e))},v3=!le(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),A3=Wn,C3=Kt,y3=Io,I3=v3,KA=nh("IE_PROTO"),dE=Object,b3=dE.prototype,lE=I3?dE.getPrototypeOf:function(e){var t=y3(e);if(A3(t,KA))return t[KA];var n=t.constructor;return C3(n)&&t instanceof n?n.prototype:t instanceof dE?b3:null},w3=et,O3=dr,N3=Kt,D3=String,P3=TypeError,L3=function(e,t,n){try{return w3(O3(Object.getOwnPropertyDescriptor(e,t)[n]))}catch{}},k3=Si,M3=function(e){if(typeof e=="object"||N3(e))return e;throw P3("Can't set "+D3(e)+" as a prototype")},U3=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,n={};try{(e=L3(Object.prototype,"__proto__","set"))(n,[]),t=n instanceof Array}catch{}return function(i,r){return k3(i),M3(r),t?e(i,r):i.__proto__=r,i}}():void 0),ih={},rh={},uE=Wn,V3=vs,x3=nE.indexOf,F3=rh,HA=et([].push),YA=function(e,t){var n,i=V3(e),r=0,o=[];for(n in i)!uE(F3,n)&&uE(i,n)&&HA(o,n);for(;t.length>r;)uE(i,n=t[r++])&&(~x3(o,n)||HA(o,n));return o},hE=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleStr
1ing","toString","valueOf"],B3=YA,G3=hE.concat("length","prototype");ih.f=Object.getOwnPropertyNames||function(e){return B3(e,G3)};var dl={};dl.f=Object.getOwnPropertySymbols;var j3=Di,W3=ih,K3=dl,H3=Si,Y3=et([].concat),X3=j3("Reflect","ownKeys")||function(e){var t=W3.f(H3(e)),n=K3.f;return n?Y3(t,n(e)):t},XA=Wn,J3=X3,z3=Ke,q3=wr,pE={},Z3=YA,Q3=hE,oh=Object.keys||function(e){return Z3(e,Q3)},$3=fe,eG=PA,tG=wr,nG=Si,iG=vs,rG=oh;pE.f=$3&&!eG?Object.defineProperties:function(e,t){nG(e);for(var n,i=iG(t),r=rG(t),o=r.length,s=0;o>s;)tG.f(e,n=r[s++],i[n]);return e};var sh,JA=Di("document","documentElement"),oG=Si,sG=pE,zA=hE,aG=rh,cG=JA,dG=zm,_E="prototype",mE="script",qA=nh("IE_PROTO"),EE=function(){},ZA=function(e){return"<"+mE+">"+e+"</"+mE+">"},QA=function(e){e.write(ZA("")),e.close();var t=e.parentWindow.Object;return e=null,t},ah=function(){try{sh=new ActiveXObject("htmlfile")}catch{}var e,t,n;ah=typeof document<"u"?document.domain&&sh?QA(sh):(t=dG("iframe"),n="java"+mE+":",t.style.display="none",cG.appendChild(t),t.src=String(n),(e=t.contentWindow.document).open(),e.write(ZA("document.F=Object")),e.close(),e.F):QA(sh);for(var i=zA.length;i--;)delete ah[_E][zA[i]];return ah()};aG[qA]=!0;var ll=Object.create||function(e,t){var n;return e!==null?(EE[_E]=oG(e),n=new EE,EE[_E]=null,n[qA]=e):n=ah(),t===void 0?n:sG.f(n,t)},lG=Hi,uG=ys,$A=Error,hG=et("".replace),pG=String($A("zxcasd").stack),eC=/\n\s*at [^:]*:[^\n]*/,_G=eC.test(pG),mG=Ht,EG=!le(function(){var e=Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",mG(1,7)),e.stack!==7)}),fG=ys,gG=function(e,t){if(_G&&typeof e=="string"&&!$A.prepareStackTrace)for(;t--;)e=hG(e,eC,"");return e},SG=EG,tC=Error.captureStackTrace,Ic={},TG=Ic,RG=tn("iterator"),vG=Array.prototype,nC=function(e){return e!==void 0&&(TG.Array===e||vG[RG]===e)},AG=ns,iC=sl,CG=gc,yG=Ic,IG=tn("iterator"),ch=function(e){if(!CG(e))return iC(e,IG)||iC(e,"@@iterator")||yG[AG(e)]},bG=wt,wG=dr,OG=Si,NG=Tc,DG=ch,PG=TypeError,fE=function(e,t){var n=arguments.length<2?DG(e):t;if(wG(n))return OG(bG(n,e));throw PG(NG(e)+" is not iterable")},LG=wt,rC=Si,kG=sl,oC=function(e,t,n){var i,r;rC(e);try{if(!(i=kG(e,"return"))){if(t==="throw")throw n;return n}i=LG(i,e)}catch(o){r=!0,i=o}if(t==="throw")throw n;if(r)throw i;return rC(i),n},MG=Cs,UG=wt,VG=Si,xG=Tc,FG=nC,BG=ts,sC=Ee,GG=fE,jG=ch,aC=oC,WG=TypeError,dh=function(e,t){this.stopped=e,this.result=t},cC=dh.prototype,ul=function(e,t,n){var i,r,o,s,a,c,d,l=n&&n.that,h=!(!n||!n.AS_ENTRIES),u=!(!n||!n.IS_RECORD),p=!(!n||!n.IS_ITERATOR),E=!(!n||!n.INTERRUPTED),m=MG(t,l),g=function(v){return i&&aC(i,"normal",v),new dh(!0,v)},R=function(v){return h?(VG(v),E?m(v[0],v[1],g):m(v[0],v[1])):E?m(v,g):m(v)};if(u)i=e.iterator;else if(p)i=e;else{if(!(r=jG(e)))throw WG(xG(e)+" is not iterable");if(FG(r)){for(o=0,s=BG(e);s>o;o++)if((a=R(e[o]))&&sC(cC,a))return a;return new dh(!1)}i=GG(e,r)}for(c=u?e.next:i.next;!(d=UG(c,i)).done;){try{a=R(d.value)}catch(v){aC(i,"throw",v)}if(typeof a=="object"&&a&&sC(cC,a))return a}return new dh(!1)},KG=Yi,HG=st,YG=Ee,XG=lE,lh=U3,JG=function(e,t,n){for(var i=J3(t),r=q3.f,o=z3.f,s=0;s<i.length;s++){var a=i[s];XA(e,a)||n&&XA(n,a)||r(e,a,o(t,a))}},dC=ll,gE=ys,SE=Ht,zG=function(e,t){lG(t)&&"cause"in t&&uG(e,"cause",t.cause)},qG=function(e,t,n,i){SG&&(tC?tC(e,t):fG(e,"stack",gG(n,i)))},ZG=ul,QG=function(e,t){return e===void 0?arguments.length<2?"":t:KG(e)},$G=tn("toStringTag"),uh=Error,ej=[].push,bc=function(e,t){var n,i=YG(TE,this);lh?n=lh(uh(),i?XG(this):TE):(n=i?this:dC(TE),gE(n,$G,"Error")),t!==void 0&&gE(n,"message",QG(t)),qG(n,bc,n.stack,1),arguments.length>2&&zG(n,arguments[2]);var r=[];return ZG(e,ej,{that:r}),gE(n,"errors",r),n};lh?lh(bc,uh):JG(bc,uh,{name:!0});var TE=bc.prototype=dC(uh.prototype,{constructor:SE(1,bc),message:SE(1,""),name:SE(1,"AggregateError")});HG({global:!0},{AggregateError:bc});var hh,hl,ph,tj=Kt,lC=be.WeakMap,nj=tj(lC)&&/native code/.test(String(lC)),uC=be,ij=Hi,rj=ys,RE=Wn,vE=Hm,oj=nh,sj=rh,hC="Object already initialized",AE=uC.TypeError,aj=uC.WeakMap;if(nj||vE.state){var bo=vE.state||(vE.state=new aj);bo.get=bo.get,bo.has=bo.has,bo.set=bo.set,hh=function(e,t){if(bo.has(e))throw AE(hC);return t.facade=e,bo.set(e,t),t},hl=function(e){return bo.get(e)||{}},ph=function(e){return bo.has(e)}}else{var wc=oj("state");sj[wc]=!0,hh=function(e,t){if(RE(e,wc))throw AE(hC);return t.facade=e,rj(e,wc,t),t},hl=function(e){return RE(e,wc)?e[wc]:{}},ph=function(e){return RE(e,wc)}}var ma,pC,_C,Ea={set:hh,get:hl,has:ph,enforce:function(e){return ph(e)?hl(e):hh(e,{})},getterFor:function(e){return function(t){var n;if(!ij(t)||(n=hl(t)).type!==e)throw AE("Incompatible receiver, "+e+" required");return n}}},CE=fe,cj=Wn,mC=Function.prototype,dj=CE&&Object.getOwnPropertyDescriptor,EC=cj(mC,"name"),fC={PROPER:EC&&(function(){}).name==="something",CONFIGURABLE:EC&&(!CE||CE&&dj(mC,"name").configurable)},lj=ys,Is=function(e,t,n,i){return i&&i.enumerable?e[t]=n:lj(e,t,n),e},uj=le,hj=Kt,pj=Hi,_j=ll,gC=lE,mj=Is,yE=tn("iterator"),SC=!1;[].keys&&("next"in(_C=[].keys())?(pC=gC(gC(_C)))!==Object.prototype&&(ma=pC):SC=!0);var Ej=!pj(ma)||uj(function(){var e={};return ma[yE].call(e)!==e});hj((ma=Ej?{}:_j(ma))[yE])||mj(ma,yE,function(){return this});var TC={IteratorPrototype:ma,BUGGY_SAFARI_ITERATORS:SC}
1,fj=ns,gj=rE?{}.toString:function(){return"[object "+fj(this)+"]"},Sj=rE,Tj=wr.f,Rj=ys,vj=Wn,Aj=gj,RC=tn("toStringTag"),bs=function(e,t,n,i){if(e){var r=n?e:e.prototype;vj(r,RC)||Tj(r,RC,{configurable:!0,value:t}),i&&!Sj&&Rj(r,"toString",Aj)}},Cj=TC.IteratorPrototype,yj=ll,Ij=Ht,bj=bs,wj=Ic,Oj=function(){return this},IE=function(e,t,n,i){var r=t+" Iterator";return e.prototype=yj(Cj,{next:Ij(+!i,n)}),bj(e,r,!1,!0),wj[r]=Oj,e},Nj=st,Dj=wt,Pj=fC,Lj=IE,kj=lE,Mj=bs,vC=Is,AC=Ic,Uj=TC,Vj=Pj.PROPER,_h=Uj.BUGGY_SAFARI_ITERATORS,bE=tn("iterator"),CC="keys",mh="values",yC="entries",xj=function(){return this},IC=function(e,t,n,i,r,o,s){Lj(n,t,i);var a,c,d,l=function(R){if(R===r&&m)return m;if(!_h&&R in p)return p[R];switch(R){case CC:case mh:case yC:return function(){return new n(this,R)}}return function(){return new n(this)}},h=t+" Iterator",u=!1,p=e.prototype,E=p[bE]||p["@@iterator"]||r&&p[r],m=!_h&&E||l(r),g=t=="Array"&&p.entries||E;if(g&&(a=kj(g.call(new e)))!==Object.prototype&&a.next&&(Mj(a,h,!0,!0),AC[h]=xj),Vj&&r==mh&&E&&E.name!==mh&&(u=!0,m=function(){return Dj(E,this)}),r)if(c={values:l(mh),keys:o?m:l(CC),entries:l(yC)},s)for(d in c)(_h||u||!(d in p))&&vC(p,d,c[d]);else Nj({target:t,proto:!0,forced:_h||u},c);return s&&p[bE]!==m&&vC(p,bE,m,{}),AC[t]=m,c},wE=function(e,t){return{value:e,done:t}},Fj=vs,bC=Ic,wC=Ea;wr.f;var Bj=IC,OC=wE,NC="Array Iterator",Gj=wC.set,jj=wC.getterFor(NC);Bj(Array,"Array",function(e,t){Gj(this,{type:NC,target:Fj(e),index:0,kind:t})},function(){var e=jj(this),t=e.target,n=e.kind,i=e.index++;return!t||i>=t.length?(e.target=void 0,OC(void 0,!0)):OC(n=="keys"?i:n=="values"?t[i]:[i,t[i]],!1)},"values"),bC.Arguments=bC.Array;var Wj=wr,Eh=function(e,t,n){return Wj.f(e,t,n)},Kj=Di,Hj=Eh,Yj=fe,DC=tn("species"),Xj=Ee,Jj=TypeError,OE=function(e,t){if(Xj(t,e))return e;throw Jj("Incorrect invocation")},zj=Kt,NE=Hm,qj=et(Function.toString);zj(NE.inspectSource)||(NE.inspectSource=function(e){return qj(e)});var PC=NE.inspectSource,Zj=et,Qj=le,LC=Kt,$j=ns,eW=PC,kC=function(){},tW=[],MC=Di("Reflect","construct"),DE=/^\s*(?:class|function)\b/,nW=Zj(DE.exec),iW=!DE.exec(kC),pl=function(e){if(!LC(e))return!1;try{return MC(kC,tW,e),!0}catch{return!1}},UC=function(e){if(!LC(e))return!1;switch($j(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return iW||!!nW(DE,eW(e))}catch{return!0}};UC.sham=!0;var _l,Oc,VC,PE,fh=!MC||Qj(function(){var e;return pl(pl.call)||!pl(Object)||!pl(function(){e=!0})||e})?UC:pl,rW=fh,oW=Tc,sW=TypeError,xC=Si,aW=function(e){if(rW(e))return e;throw sW(oW(e)+" is not a constructor")},cW=gc,dW=tn("species"),LE=function(e,t){var n,i=xC(e).constructor;return i===void 0||cW(n=xC(i)[dW])?t:aW(n)},gh=et([].slice),lW=TypeError,Nc=function(e,t){if(e<t)throw lW("Not enough arguments");return e},FC=/(?:ipad|iphone|ipod).*applewebkit/i.test(As),ur=be,uW=sn,hW=Cs,BC=Kt,pW=Wn,GC=le,jC=JA,_W=gh,WC=zm,mW=Nc,EW=FC,fW=yc,kE=ur.setImmediate,ME=ur.clearImmediate,gW=ur.process,UE=ur.Dispatch,SW=ur.Function,KC=ur.MessageChannel,TW=ur.String,VE=0,ml={},HC="onreadystatechange";GC(function(){_l=ur.location});var xE=function(e){if(pW(ml,e)){var t=ml[e];delete ml[e],t()}},FE=function(e){return function(){xE(e)}},YC=function(e){xE(e.data)},XC=function(e){ur.postMessage(TW(e),_l.protocol+"//"+_l.host)};kE&&ME||(kE=function(e){mW(arguments.length,1);var t=BC(e)?e:SW(e),n=_W(arguments,1);return ml[++VE]=function(){uW(t,void 0,n)},Oc(VE),VE},ME=function(e){delete ml[e]},fW?Oc=function(e){gW.nextTick(FE(e))}:UE&&UE.now?Oc=function(e){UE.now(FE(e))}:KC&&!EW?(PE=(VC=new KC).port2,VC.port1.onmessage=YC,Oc=hW(PE.postMessage,PE)):ur.addEventListener&&BC(ur.postMessage)&&!ur.importScripts&&_l&&_l.protocol!=="file:"&&!GC(XC)?(Oc=XC,ur.addEventListener("message",YC,!1)):Oc=HC in WC("script")?function(e){jC.appendChild(WC("script"))[HC]=function(){jC.removeChild(this),xE(e)}}:function(e){setTimeout(FE(e),0)});var Sh={set:kE,clear:ME},JC=function(){this.head=null,this.tail=null};JC.prototype={add:function(e){var t={item:e,next:null},n=this.tail;n?n.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return(this.head=e.next)===null&&(this.tail=null),e.item}};var Dc,BE,GE,jE,zC,qC=JC,RW=/ipad|iphone|ipod/i.test(As)&&typeof Pebble<"u",vW=/web0s(?!.*chrome)/i.test(As),fa=be,ZC=Cs,AW=Ke.f,WE=Sh.set,CW=qC,yW=FC,IW=RW,bW=vW,KE=yc,QC=fa.MutationObserver||fa.Web
1KitMutationObserver,$C=fa.document,ey=fa.process,Th=fa.Promise,ty=AW(fa,"queueMicrotask"),HE=ty&&ty.value;if(!HE){var Rh=new CW,vh=function(){var e,t;for(KE&&(e=ey.domain)&&e.exit();t=Rh.get();)try{t()}catch(n){throw Rh.head&&Dc(),n}e&&e.enter()};yW||KE||bW||!QC||!$C?!IW&&Th&&Th.resolve?((jE=Th.resolve(void 0)).constructor=Th,zC=ZC(jE.then,jE),Dc=function(){zC(vh)}):KE?Dc=function(){ey.nextTick(vh)}:(WE=ZC(WE,fa),Dc=function(){WE(vh)}):(BE=!0,GE=$C.createTextNode(""),new QC(vh).observe(GE,{characterData:!0}),Dc=function(){GE.data=BE=!BE}),HE=function(e){Rh.head||Dc(),Rh.add(e)}}var ny=HE,Pc=function(e){try{return{error:!1,value:e()}}catch(t){return{error:!0,value:t}}},ga=be.Promise,iy=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",wW=!iy&&!yc&&typeof window=="object"&&typeof document=="object",OW=be,El=ga,NW=Kt,DW=DA,PW=PC,LW=tn,kW=wW,MW=iy,YE=pa,ry=El&&El.prototype,UW=LW("species"),oy=NW(OW.PromiseRejectionEvent),VW=DW("Promise",function(){var e=PW(El),t=e!==String(El);if(!t&&YE===66||!ry.catch||!ry.finally)return!0;if(!YE||YE<51||!/native code/.test(e)){var n=new El(function(r){r(1)}),i=function(r){r(function(){},function(){})};if((n.constructor={})[UW]=i,!(n.then(function(){})instanceof i))return!0}return!t&&(kW||MW)&&!oy}),fl={CONSTRUCTOR:VW,REJECTION_EVENT:oy},wo={},sy=dr,xW=TypeError,FW=function(e){var t,n;this.promise=new e(function(i,r){if(t!==void 0||n!==void 0)throw xW("Bad Promise constructor");t=i,n=r}),this.resolve=sy(t),this.reject=sy(n)};wo.f=function(e){return new FW(e)};var XE,ay,BW=st,Ah=yc,ws=be,gl=wt,GW=Is,jW=bs,WW=function(e){var t=Kj(e);Yj&&t&&!t[DC]&&Hj(t,DC,{configurable:!0,get:function(){return this}})},KW=dr,JE=Kt,HW=Hi,YW=OE,XW=LE,cy=Sh.set,zE=ny,JW=function(e,t){try{arguments.length==1?console.error(e):console.error(e,t)}catch{}},zW=Pc,qW=qC,dy=Ea,qE=ga,ly=fl,uy=wo,Ch="Promise",hy=ly.CONSTRUCTOR,ZW=ly.REJECTION_EVENT,ZE=dy.getterFor(Ch),QW=dy.set,$W=qE&&qE.prototype,Sl=qE,QE=$W,py=ws.TypeError,$E=ws.document,ef=ws.process,tf=uy.f,e5=tf,t5=!!($E&&$E.createEvent&&ws.dispatchEvent),_y="unhandledrejection",my=function(e){var t;return!(!HW(e)||!JE(t=e.then))&&t},Ey=function(e,t){var n,i,r,o=t.value,s=t.state==1,a=s?e.ok:e.fail,c=e.resolve,d=e.reject,l=e.domain;try{a?(s||(t.rejection===2&&i5(t),t.rejection=1),a===!0?n=o:(l&&l.enter(),n=a(o),l&&(l.exit(),r=!0)),n===e.promise?d(py("Promise-chain cycle")):(i=my(n))?gl(i,n,c,d):c(n)):d(o)}catch(h){l&&!r&&l.exit(),d(h)}},fy=function(e,t){e.notified||(e.notified=!0,zE(function(){for(var n,i=e.reactions;n=i.get();)Ey(n,e);e.notified=!1,t&&!e.rejection&&n5(e)}))},gy=function(e,t,n){var i,r;t5?((i=$E.createEvent("Event")).promise=t,i.reason=n,i.initEvent(e,!1,!0),ws.dispatchEvent(i)):i={promise:t,reason:n},!ZW&&(r=ws["on"+e])?r(i):e===_y&&JW("Unhandled promise rejection",n)},n5=function(e){gl(cy,ws,function(){var t,n=e.facade,i=e.value;if(Sy(e)&&(t=zW(function(){Ah?ef.emit("unhandledRejection",i,n):gy(_y,n,i)}),e.rejection=Ah||Sy(e)?2:1,t.error))throw t.value})},Sy=function(e){return e.rejection!==1&&!e.parent},i5=function(e){gl(cy,ws,function(){var t=e.facade;Ah?ef.emit("rejectionHandled",t):gy("rejectionhandled",t,e.value)})},Lc=function(e,t,n){return function(i){e(t,i,n)}},kc=function(e,t,n){e.done||(e.done=!0,n&&(e=n),e.value=t,e.state=2,fy(e,!0))},nf=function(e,t,n){if(!e.done){e.done=!0,n&&(e=n);try{if(e.facade===t)throw py("Promise can't be resolved itself");var i=my(t);i?zE(function(){var r={done:!1};try{gl(i,t,Lc(nf,r,e),Lc(kc,r,e))}catch(o){kc(r,o,e)}}):(e.value=t,e.state=1,fy(e,!1))}catch(r){kc({done:!1},r,e)}}};hy&&(QE=(Sl=function(e){YW(this,QE),KW(e),gl(XE,this);var t=ZE(this);try{e(Lc(nf,t),Lc(kc,t))}catch(n){kc(t,n)}}).prototype,(XE=function(e){QW(this,{type:Ch,done:!1,notified:!1,parent:!1,reactions:new qW,rejection:!1,state:0,value:void 0})}).prototype=GW(QE,"then",function(e,t){var n=ZE(this),i=tf(XW(this,Sl));return n.parent=!0,i.ok=!JE(e)||e,i.fail=JE(t)&&t,i.domain=Ah?ef.domain:void 0,n.state==0?n.reactions.add(i):zE(function(){Ey(i,n)}),i.promise}),ay=function(){var e=new XE,t=ZE(e);this.promise=e,this.resolve=Lc(nf,t),this.reject=Lc(kc,t)},uy.f=tf=function(e){return e===Sl||e===void 0?new ay(e):e5(e)}),BW({global:!0,wrap:!0,forced:hy},{Promise:Sl}),jW(Sl,Ch,!1,!0),WW(Ch);var Ty=tn("iterator"),Ry=!1;try{var r5=0,vy={next:function(){return{done:!!r5++}},return:function(){Ry=!0}};vy[Ty]=function(){return this},Array.from(vy,function(){throw 2})}catch{}var o5=ga,s5=function(e,t){if(!Ry)return!1;var n=!1;try{var i={};i[Ty]=function(){return{next:function(){return{done:n=!0}}}},e(i)}catch{}return n},yh=fl.CONSTRUCTOR||!s5(function(e){o5.all(e).then(void 0,function(){})}),a5=wt,c5=dr,d5=wo,l5=Pc,u5=ul;st({target:"Promise",stat:!0,forced:yh},{all:function(e){var t=this,n=d5.f(t),i=n.resolve,r=n.reject,o=l5(function(){var s=c5(t.resolve),a=[],c=0,d=1;u5(e,function(l){var h=c++,u=!1;d++,a5(s,t,l).then(function(p){u||(u=!0,a[h]=p,--d||i(a))},r)}),--d||i(a)});return o.error&&r(o.value),n.promise}});var h5=st,p5=fl.CONSTRUCTOR;ga&&ga.prototype,h5({target:"Promise",proto:!0,forced:p5,real:!0},{catch:function(e){return this.then(void 0,e)}});var _5=wt,m5=dr,E5=wo,f5=Pc,g5=ul;st({target:"Promise",stat:!0,forced:yh},{race:function(e){var t=this,n=E5.f(t),i=n.reject,r=f5(function(){var o=m5(t.resolve);g5(e,function(s){_5(o,t,s).then(n.resolve,i)})});return r.error&&i(r.value),n.promise}});var S5=wt,T5=wo;st({target:"Promise",stat:!0,forced:fl.CONSTRUCTOR},{reject:function(e){var t=T5.f(this);return S5(t.reject,void 0,e),t.promise}});var R5=Si,v5=Hi,A5=wo,Ay=function(e,t){if(R5(e),v5(t)&&t.constructor===e)return t;var n=A5.f(e);return(0,n.resolve)(t),n.promise},C5=st,y5=ga,I5=fl.CONSTRUCTOR,b5=Ay,w5=Di("Promise"),O5=!I5;C5({target:"Promise",stat:!0,forced:!0},{resolve:function(e){return b5(O5&&this===w5?y5:this,e)}});var N5=wt,D5=dr,P5=wo,L5=Pc,k5=ul;st({target:"Promise",stat:!0,forced:yh},{allSettled:function(e){var t=this,n=P5.f(t),i=n.resolve,r=n.reject,o=L5(function(){var s=D5(t.resolve),a=[],c=0,d=1;k5(e,function(l){var h=c++,u=!1;d++,N5(s,t,l).then(function(p){u||(u=!0,a[h]={status:"fulfilled",value:p},--d||i(a))},function(p){u||(u=!0,a[h]={status:"rejected",reason:p},--d||i(a))})}),--d||i(a)});return o.error&&r(o.value),n.promise}});var M5=wt,U5=dr,V5=Di,x5=wo,F5=Pc,B5=ul,Cy="No one promise resolved";
1st({target:"Promise",stat:!0,forced:yh},{any:function(e){var t=this,n=V5("AggregateError"),i=x5.f(t),r=i.resolve,o=i.reject,s=F5(function(){var a=U5(t.resolve),c=[],d=0,l=1,h=!1;B5(e,function(u){var p=d++,E=!1;l++,M5(a,t,u).then(function(m){E||h||(h=!0,r(m))},function(m){E||h||(E=!0,c[p]=m,--l||o(new n(c,Cy)))})}),--l||o(new n(c,Cy))});return s.error&&o(s.value),i.promise}});var G5=st,rf=ga,j5=le,W5=Di,K5=Kt,H5=LE,yy=Ay,Y5=rf&&rf.prototype;G5({target:"Promise",proto:!0,real:!0,forced:!!rf&&j5(function(){Y5.finally.call({then:function(){}},function(){})})},{finally:function(e){var t=H5(this,W5("Promise")),n=K5(e);return this.then(n?function(i){return yy(t,e()).then(function(){return i})}:e,n?function(i){return yy(t,e()).then(function(){throw i})}:e)}});var of=et,X5=eE,J5=Yi,z5=ha,q5=of("".charAt),Iy=of("".charCodeAt),Z5=of("".slice),by=function(e){return function(t,n){var i,r,o=J5(z5(t)),s=X5(n),a=o.length;return s<0||s>=a?e?"":void 0:(i=Iy(o,s))<55296||i>56319||s+1===a||(r=Iy(o,s+1))<56320||r>57343?e?q5(o,s):i:e?Z5(o,s,s+2):r-56320+(i-55296<<10)+65536}},sf={codeAt:by(!1),charAt:by(!0)},Q5=sf.charAt,$5=Yi,wy=Ea,e4=IC,Oy=wE,Ny="String Iterator",t4=wy.set,n4=wy.getterFor(Ny);e4(String,"String",function(e){t4(this,{type:Ny,string:$5(e),index:0})},function(){var e,t=n4(this),n=t.string,i=t.index;return i>=n.length?Oy(void 0,!0):(e=Q5(n,i),t.index+=e.length,Oy(e,!1))});var i4=cr.Promise,r4={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},o4=be,s4=ns,a4=ys,Dy=Ic,Py=tn("toStringTag");for(var af in r4){var Ly=o4[af],cf=Ly&&Ly.prototype;cf&&s4(cf)!==Py&&a4(cf,Py,af),Dy[af]=Dy.Array}var ky=i4,K=re(ky),c4=lr("Array").values,d4=ns,l4=Wn,u4=Ee,h4=c4,df=Array.prototype,p4={DOMTokenList:!0,NodeList:!0},_4=function(e){var t=e.values;return e===df||u4(df,e)&&t===df.values||l4(p4,d4(e))?h4:t},ti=re(_4),My=Tc,m4=TypeError,E4=Zu,f4=wr,g4=Ht,Ih=function(e,t,n){var i=E4(t);i in e?f4.f(e,i,g4(0,n)):e[i]=n},Uy=tE,S4=ts,T4=Ih,R4=Array,v4=Math.max,lf=function(e,t,n){for(var i=S4(e),r=Uy(t,i),o=Uy(n===void 0?i:n,i),s=R4(v4(o-r,0)),a=0;r<o;r++,a++)T4(s,a,e[r]);return s.length=a,s},Vy=lf,A4=Math.floor,uf=function(e,t){var n=e.length,i=A4(n/2);return n<8?C4(e,t):y4(e,uf(Vy(e,0,i),t),uf(Vy(e,i),t),t)},C4=function(e,t){for(var n,i,r=e.length,o=1;o<r;){for(i=o,n=e[o];i&&t(e[i-1],n)>0;)e[i]=e[--i];i!==o++&&(e[i]=n)}return e},y4=function(e,t,n,i){for(var r=t.length,o=n.length,s=0,a=0;s<r||a<o;)e[s+a]=s<r&&a<o?i(t[s],n[a])<=0?t[s++]:n[a++]:s<r?t[s++]:n[a++];return e},xy=uf,Fy=As.match(/firefox\/(\d+)/i),I4=!!Fy&&+Fy[1],b4=/MSIE|Trident/.test(As),By=As.match(/AppleWebKit\/(\d+)\./),w4=!!By&&+By[1],O4=st,Gy=et,N4=dr,D4=Io,jy=ts,P4=function(e,t){if(!delete e[t])throw m4("Cannot delete property "+My(t)+" of "+My(e))},Wy=Yi,hf=le,L4=xy,k4=th,Ky=I4,M4=b4,Hy=pa,Yy=w4,Os=[],Xy=Gy(Os.sort),U4=Gy(Os.push),V4=hf(function(){Os.sort(void 0)}),x4=hf(function(){Os.sort(null)}),F4=k4("sort"),Jy=!hf(function(){if(Hy)return Hy<70;if(!(Ky&&Ky>3)){if(M4)return!0;if(Yy)return Yy<603;var e,t,n,i,r="";for(e=65;e<76;
1e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(i=0;i<47;i++)Os.push({k:t+i,v:n})}for(Os.sort(function(o,s){return s.v-o.v}),i=0;i<Os.length;i++)t=Os[i].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return r!=="DGBEFHACIJK"}});O4({target:"Array",proto:!0,forced:V4||!x4||!F4||!Jy},{sort:function(e){e!==void 0&&N4(e);var t=D4(this);if(Jy)return e===void 0?Xy(t):Xy(t,e);var n,i,r=[],o=jy(t);for(i=0;i<o;i++)i in t&&U4(r,t[i]);for(L4(r,function(s){return function(a,c){return c===void 0?-1:a===void 0?1:s!==void 0?+s(a,c)||0:Wy(a)>Wy(c)?1:-1}}(e)),n=jy(r),i=0;i<n;)t[i]=r[i++];for(;i<o;)P4(t,i++);return t}});var B4=lr("Array").sort,G4=Ee,j4=B4,pf=Array.prototype,W4=function(e){var t=e.sort;return e===pf||G4(pf,e)&&t===pf.sort?j4:t},Pi=re(W4),K4=le,H4=tn("iterator"),_f=!K4(function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,n=new URLSearchParams("a=1&a=2"),i="";return e.pathname="c%20d",t.forEach(function(r,o){t.delete("b"),i+=o+r}),n.delete("a",2),!e.toJSON||!n.has("a",1)||n.has("a",2)||!t.size&&!0||!t.sort||e.href!=="http://a/c%20d?a=1&c=3"||t.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!t[H4]||new URL("https://a@b").username!=="a"||new URLSearchParams(new URLSearchParams("a=b")).get("a")!=="b"||new URL("http://\u0442\u0435\u0441\u0442").host!=="xn--e1aybc"||new URL("http://a#\u0431").hash!=="#%D0%B1"||i!=="a1c3"||new URL("http://x",void 0).host!=="x"}),Y4=Is,mf=st,Mc=be,bh=wt,Oo=et,Uc=fe,zy=_f,qy=Is,X4=Eh,J4=function(e,t,n){for(var i in t)n&&n.unsafe&&e[i]?e[i]=t[i]:Y4(e,i,t[i],n);return e},z4=bs,q4=IE,Ef=Ea,Zy=OE,ff=Kt,Z4=Wn,Q4=Cs,$4=ns,eK=Si,Qy=Hi,Li=Yi,tK=ll,$y=Ht,gf=fE,nK=ch,Vc=Nc,iK=xy,rK=tn("iterator"),Tl="URLSearchParams",eI=Tl+"Iterator",tI=Ef.set,Or=Ef.getterFor(Tl),oK=Ef.getterFor(eI),sK=Object.getOwnPropertyDescriptor,Sf=function(e){if(!Uc)return Mc[e];var t=sK(Mc,e);return t&&t.value},nI=Sf("fetch"),wh=Sf("Request"),Rl=Sf("Headers"),Tf=wh&&wh.prototype,iI=Rl&&Rl.prototype,aK=Mc.RegExp,cK=Mc.TypeError,rI=Mc.decodeURIComponent,dK=Mc.encodeURIComponent,lK=Oo("".charAt),oI=Oo([].join),Sa=Oo([].push),Rf=Oo("".replace),uK=Oo([].shift),sI=Oo([].splice),aI=Oo("".split),hK=Oo("".slice),pK=/\+/g,cI=Array(4),_K=function(e){return cI[e-1]||(cI[e-1]=aK("((?:%[\\da-f]{2}){"+e+"})","gi"))},mK=function(e){try{return rI(e)}catch{return e}},dI=function(e){var t=Rf(e,pK," "),n=4;try{return rI(t)}catch{for(;n;)t=Rf(t,_K(n--),mK);return t}},EK=/[!'()~]|%20/g,fK={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},gK=function(e){return fK[e]},lI=function(e){return Rf(dK(e),EK,gK)},vf=q4(function(e,t){tI(this,{type:eI,iterator:gf(Or(e).entries),kind:t})},"Iterator",function(){var e=oK(this),t=e.kind,n=e.iterator.next(),i=n.value;return n.done||(n.value=t==="keys"?i.key:t==="values"?i.value:[i.key,i.value]),n},!0),uI=function(e){this.entries=[],this.url=null,e!==void 0&&(Qy(e)?this.parseObject(e):this.parseQuery(typeof e=="string"?lK(e,0)==="?"?hK(e,1):e:Li(e)))};uI.prototype={type:Tl,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,n,i,r,o,s,a,c=nK(e);if(c)for(n=(t=gf(e,c)).next;!(i=bh(n,t)).done;){if(o=(r=gf(eK(i.value))).next,(s=bh(o,r)).done||(a=bh(o,r)).done||!bh(o,r).done)throw cK("Expected sequence with length 2");Sa(this.entries,{key:Li(s.value),value:Li(a.value)})}else for(var d in e)Z4(e,d)&&Sa(this.entries,{key:d,value:Li(e[d])})},parseQuery:function(e){if(e)for(var t,n,i=aI(e,"&"),r=0;r<i.length;)(t=i[r++]).length&&(n=aI(t,"="),Sa(this.entries,{key:dI(uK(n)),value:dI(oI(n,"="))}))},serialize:function(){for(var e,t=this.entries,n=[],i=0;i<t.length;)e=t[i++],Sa(n,lI(e.key)+"="+lI(e.value));return oI(n,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var Oh=function(){Zy(this,xc);var e=tI(this,new uI(arguments.length>0?arguments[0]:void 0));Uc||(this.size=e.entries.length)},xc=Oh.prototype;if(J4(xc,{append:function(e,t){var n=Or(this);Vc(arguments.length,2),Sa(n.entries,{key:Li(e),value:Li(t)}),Uc||this.length++,n.updateURL()},delete:function(e){for(var t=Or(this),n=Vc(arguments.length,1),i=t.entries,r=Li(e),o=n<2?void 0:arguments[1],s=o===void 0?o:Li(o),a=0;a<i.length;){var c=i[a];if(c.key!==r||s!==void 0&&c.value!==s)a++;else if(sI(i,a,1),s!==void 0)break}Uc||(this.size=i.length),t.updateURL()},get:function(e){var t=Or(this).entries;Vc(arguments.length,1);for(var n=Li(e),i=0;i<t.length;i++)if(t[i].key===n)return t[i].value;return null},getAll:function(e){var t=Or(this).entries;Vc(arguments.length,1);for(var n=Li(e),i=[],r=0;r<t.length;r++)t[r].key===n&&Sa(i,t[r].value);return i},has:function(e){for(var t=Or(this).entries,n=Vc(arguments.length,1),i=Li(e),r=n<2?void 0:arguments[1],o=r===void 0?r:Li(r),s=0;s<t.length;){var a=t[s++];if(a.key===i&&(o===void 0||a.value===o))return!0}return!1},set:function(e,t){var n=Or(this);Vc(arguments.length,1);for(var i,r=n.entries,o=!1,s=Li(e),a=Li(t),c=0;c<r.length;c++)(i=r[c]).key===s&&(o?sI(r,c--,1):(o=!0,i.value=a));o||Sa(r,{key:s,value:a}),Uc||(this.size=r.length),n.updateURL()},sort:function(){var e=Or(this);iK(e.entries,function(t,n){return t.key>n.key?1:-1}),e.updateURL()}
vendor: 12,390 bytes, line 1
1,forEach:function(e){for(var t,n=Or(this).entries,i=Q4(e,arguments.length>1?arguments[1]:void 0),r=0;r<n.length;)i((t=n[r++]).value,t.key,this)},keys:function(){return new vf(this,"keys")},values:function(){return new vf(this,"values")},entries:function(){return new vf(this,"entries")}},{enumerable:!0}),qy(xc,rK,xc.entries,{}),qy(xc,"toString",function(){return Or(this).serialize()},{enumerable:!0}),Uc&&X4(xc,"size",{get:function(){return Or(this).entries.length},configurable:!0,enumerable:!0}),z4(Oh,Tl),mf({global:!0,forced:!zy},{URLSearchParams:Oh}),!zy&&ff(Rl)){var SK=Oo(iI.has),TK=Oo(iI.set),hI=function(e){if(Qy(e)){var t,n=e.body;if($4(n)===Tl)return t=e.headers?new Rl(e.headers):new Rl,SK(t,"content-type")||TK(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),tK(e,{body:$y(0,Li(n)),headers:$y(0,t)})}return e};if(ff(nI)&&mf({global:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return nI(e,arguments.length>1?hI(arguments[1]):{})}}),ff(wh)){var Af=function(e){return Zy(this,Tf),new wh(e,arguments.length>1?hI(arguments[1]):{})};Tf.constructor=Af,Af.prototype=Tf,mf({global:!0,dontCallGetSet:!0,forced:!0},{Request:Af})}}var Nr,RK={URLSearchParams:Oh,getState:Or},vK=cr.URLSearchParams,pI=fe,AK=et,CK=wt,yK=le,Cf=oh,IK=dl,bK=oe,wK=Io,OK=qu,Fc=Object.assign,_I=Object.defineProperty,NK=AK([].concat),DK=!Fc||yK(function(){if(pI&&Fc({b:1},Fc(_I({},"a",{enumerable:!0,get:function(){_I(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var e={},t={},n=Symbol(),i="abcdefghijklmnopqrst";return e[n]=7,i.split("").forEach(function(r){t[r]=r}),Fc({},e)[n]!=7||Cf(Fc({},t)).join("")!=i})?function(e,t){for(var n=wK(e),i=arguments.length,r=1,o=IK.f,s=bK.f;i>r;)for(var a,c=OK(arguments[r++]),d=o?NK(Cf(c),o(c)):Cf(c),l=d.length,h=0;l>h;)a=d[h++],pI&&!CK(s,c,a)||(n[a]=c[a]);return n}:Fc,PK=Si,LK=oC,kK=Cs,MK=wt,UK=Io,VK=function(e,t,n,i){try{return i?t(PK(n)[0],n[1]):t(n)}catch(r){LK(e,"throw",r)}},xK=nC,FK=fh,BK=ts,mI=Ih,GK=fE,jK=ch,EI=Array,Ta=et,yf=2147483647,WK=/[^\0-\u007E]/,fI=/[.\u3002\uFF0E\uFF61]/g,gI="Overflow: input needs wider integers to process",SI=RangeError,KK=Ta(fI.exec),Bc=Math.floor,If=String.fromCharCode,TI=Ta("".charCodeAt),RI=Ta([].join),Ns=Ta([].push),HK=Ta("".replace),YK=Ta("".split),XK=Ta("".toLowerCase),vI=function(e){return e+22+75*(e<26)},JK=function(e,t,n){var i=0;for(e=n?Bc(e/700):e>>1,e+=Bc(e/t);e>455;)e=Bc(e/35),i+=36;return Bc(i+36*e/(e+38))},zK=function(e){var t=[];e=function(R){for(var v=[],C=0,w=R.length;C<w;){var b=TI(R,C++);if(b>=55296&&b<=56319&&C<w){var y=TI(R,C++);(64512&y)==56320?Ns(v,((1023&b)<<10)+(1023&y)+65536):(Ns(v,b),C--)}else Ns(v,b)}return v}(e);var n,i,r=e.length,o=128,s=0,a=72;for(n=0;n<e.length;n++)(i=e[n])<128&&Ns(t,If(i));var c=t.length,d=c;for(c&&Ns(t,"-");d<r;){var l=yf;for(n=0;n<e.length;n++)(i=e[n])>=o&&i<l&&(l=i);var h=d+1;if(l-o>Bc((yf-s)/h))throw SI(gI);for(s+=(l-o)*h,o=l,n=0;n<e.length;n++){if((i=e[n])<o&&++s>yf)throw SI(gI);if(i==o){for(var u=s,p=36;;){var E=p<=a?1:p>=a+26?26:p-a;if(u<E)break;var m=u-E,g=36-E;Ns(t,If(vI(E+m%g))),u=Bc(m/g),p+=36}Ns(t,If(vI(u))),a=JK(s,h,d==c),s=0,d++}}s++,o++}return RI(t,"")},qK=st,bf=fe,ZK=_f,wf=be,AI=Cs,Dr=et,Nh=Is,Pr=Eh,QK=OE,Of=Wn,Nf=DK,Gc=function(e){var t=UK(e),n=FK(this),i=arguments.length,r=i>1?arguments[1]:void 0,o=r!==void 0;o&&(r=kK(r,i>2?arguments[2]:void 0));var s,a,c,d,l,h,u=jK(t),p=0;if(!u||this===EI&&xK(u))for(s=BK(t),a=n?new this(s):EI(s);s>p;p++)h=o?r(t[p],p):t[p],mI(a,p,h);else for(l=(d=GK(t,u)).next,a=n?new this:[];!(c=MK(l,d)).done;p++)h=o?VK(d,r,[c.value,p],!0):c.value,mI(a,p,h);return a.length=p,a},io=lf,$K=sf.codeAt,eH=function(e){var t,n,i=[],r=YK(HK(XK(e),fI,"."),".");for(t=0;t<r.length;t++)n=r[t],Ns(i,KK(WK,n)?"xn--"+zK(n):n);return RI(i,".")},is=Yi,tH=bs,nH=Nc,CI=RK,yI=Ea,iH=yI.set,Dh=yI.getterFor("URL"),rH=CI.URLSearchParams,oH=CI.getState,vl=wf.URL,Df=wf.TypeError,Ph=wf.parseInt,sH=Math.floor,II=Math.pow,Lr=Dr("".charAt),ro=Dr(/./.exec),Al=Dr([].join),aH=Dr(1 .toString),cH=Dr([].pop),jc=Dr([].push),Pf=Dr("".replace),dH=Dr([].shift),lH=Dr("".split),Cl=Dr("".slice),Lh=Dr("".toLowerCase),uH=Dr([].unshift),Lf="Invalid scheme",yl="Invalid host",bI="Invalid port",wI=/[a-z]/i,hH=/[\d+-.a-z]/i,kf=/\d/,pH=/^0x/i,_H=/^[0-7]+$/,mH=/^\d+$/,OI=/^[\da-f]+$/i,EH=/[\0\t\n\r #%/:<>?@[\\\]^|]/,fH=/[\0\t\n\r #/:<>?@[\\\]^|]/,gH=/^[\u0000-\u0020]+/,SH=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,TH=/[\t\n\r]/g,Il=function(e){var t,n,i,r;if(typeof e=="number"){for(t=[],n=0;n<4;n++)uH(t,e%256),e=sH(e/256);return Al(t,".")}if(typeof e=="object"){for(t="",i=function(o){for(var s=null,a=1,c=null,d=0,l=0;l<8;l++)o[l]!==0?(d>a&&(s=c,a=d),c=null,d=0):(c===null&&(c=l),++d);return d>a&&(s=c,a=d),s}(e),n=0;n<8;n++)r&&e[n]===0||(r&&(r=!1),i===n?(t+=n?":":"::",r=!0):(t+=aH(e[n],16),n<7&&(t+=":")));return"["+t+"]"}return e},kh={},NI=Nf({},kh,{" ":1,'"':1,"<":1,">":1,"`":1}),DI=Nf({},NI,{"#":1,"?":1,"{":1,"}":1}),Mf=Nf({},DI,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Ds=function(e,t){var n=$K(e,0);return n>32&&n<127&&!Of(t,e)?e:encodeURIComponent(e)},Mh={ftp:21,file:null,http:80,https:443,ws:80,wss:443},bl=function(e,t){var n;return e.length==2&&ro(wI,Lr(e,0))&&((n=Lr(e,1))==":"||!t&&n=="|")},PI=function(e){var t;return e.length>1&&bl(Cl(e,0,2))&&(e.length==2||(t=Lr(e,2))==="/"||t==="\\"||t==="?"||t==="#")},RH=function(e){return e==="."||Lh(e)==="%2e"},Uf={},LI={},Vf={},kI={},MI={},xf={},UI={},VI={},Uh={},Vh={},Ff={},Bf={},Gf={},jf={},xI={},Wf={},Wc={},No={},FI={},Ra={},rs={},Kf=function(e,t,n){var i,r,o,s=is(e);if(t){if(r=this.parse(s))throw Df(r);this.searchParams=null}else{if(n!==void 0&&(i=new Kf(n,!0)),r=this.parse(s,null,i))throw Df(r);(o=oH(new rH)).bindURL(this),this.searchParams=o}};Kf.prototype={type:"URL",parse:function(e,t,n){var i,r,o,s,a,c=this,d=t||Uf,l=0,h="",u=!1,p=!1,E=!1;for(e=is(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=Pf(e,gH,""),e=Pf(e,SH,"$1")),e=Pf(e,TH,""),i=Gc(e);l<=i.length;){switch(r=i[l],d){case Uf:if(!r||!ro(wI,r)){if(t)return Lf;d=Vf;continue}h+=Lh(r),d=LI;break;case LI:if(r&&(ro(hH,r)||r=="+"||r=="-"||r=="."))h+=Lh(r);else{if(r!=":"){if(t)return Lf;h="",d=Vf,l=0;continue}if(t&&(c.isSpecial()!=Of(Mh,h)||h=="file"&&(c.includesCredentials()||c.port!==null)||c.scheme=="file"&&!c.host))return;if(c.scheme=h,t)return void(c.isSpecial()&&Mh[c.scheme]==c.port&&(c.port=null));h="",c.scheme=="file"?d=jf:c.isSpecial()&&n&&n.scheme==c.scheme?d=kI:c.isSpecial()?d=VI:i[l+1]=="/"?(d=MI,l++):(c.cannotBeABaseURL=!0,jc(c.path,""),d=FI)}break;case Vf:if(!n||n.cannotBeABaseURL&&r!="#")return Lf;if(n.cannotBeABaseURL&&r=="#"){c.scheme=n.scheme,c.path=io(n.path),c.query=n.query,c.fragment="",c.cannotBeABaseURL=!0,d=rs;break}d=n.scheme=="file"?jf:xf;continue;case kI:if(r!="/"||i[l+1]!="/"){d=xf;continue}d=Uh,l++;break;case MI:if(r=="/"){d=Vh;break}d=No;continue;case xf:if(c.scheme=n.scheme,r==Nr)c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=io(n.path),c.query=n.query;else if(r=="/"||r=="\\"&&c.isSpecial())d=UI;else if(r=="?")c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=io(n.path),c.query="",d=Ra;else{if(r!="#"){c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=io(n.path),c.path.length--,d=No;continue}c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=io(n.path),c.query=n.query,c.fragment="",d=rs}break;case UI:if(!c.isSpecial()||r!="/"&&r!="\\"){if(r!="/"){c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,d=No;continue}d=Vh}else d=Uh;break;case VI:if(d=Uh,r!="/"||Lr(h,l+1)!="/")continue;l++;break;case Uh:if(r!="/"&&r!="\\"){d=Vh;continue}break;case Vh:if(r=="@"){u&&(h="%40"+h),u=!0,o=Gc(h);for(var m=0;m<o.length;m++){var g=o[m];if(g!=":"||E){var R=Ds(g,Mf);E?c.password+=R:c.username+=R}else E=!0}h=""}else if(r==Nr||r=="/"||r=="?"||r=="#"||r=="\\"&&c.isSpecial()){if(u&&h=="")return"Invalid authority";l-=Gc(h).length+1,h="",d=Ff}else h+=r;break;case Ff:case Bf:if(t&&c.scheme=="file"){d=Wf;continue}if(r!=":"||p){if(r==Nr||r=="/"||r=="?"||r=="#"||r=="\\"&&c.isSpecial()){if(c.isSpecial()&&h=="")return yl;if(t&&h==""&&(c.includesCredentials()||c.port!==null))return;if(s=c.parseHost(h))return s;if(h="",d=Wc,t)return;continue}r=="["?p=!0:r=="]"&&(p=!1),h+=r}else{if(h=="")return yl;if(s=c.parseHost(h))return s;if(h="",d=Gf,t==Bf)return}break;case Gf:if(!ro(kf,r)){if(r==Nr||r=="/"||r=="?"||r=="#"||r=="\\"&&c.isSpecial()||t){if(h!=""){var v=Ph(h,10);if(v>65535)return bI;c.port=c.isSpecial()&&v===Mh[c.scheme]?null:v,h=""}if(t)return;d=Wc;continue}return bI}h+=r;break;case jf:if(c.scheme="file",r=="/"||r=="\\")d=xI;else{if(!n||n.scheme!="file"){d=No;continue}if(r==Nr)c.host=n.host,c.path=io(n.path),c.query=n.query;else if(r=="?")c.host=n.host,c.path=io(n.path),c.query="",d=Ra;else{if(r!="#"){PI(Al(io(i,l),""))||(c.host=n.host,c.path=io(n.path),c.shortenPath()),d=No;continue}c.host=n.host,c.path=io(n.path),c.query=n.query,c.fragment="",d=rs}}break;case xI:if(r=="/"||r=="\\"){d=Wf;break}n&&n.scheme=="file"&&!PI(Al(io(i,l),""))&&(bl(n.path[0],!0)?jc(c.path,n.path[0]):c.host=n.host),d=No;continue;case Wf:if(r==Nr||r=="/"||r=="\\"||r=="?"||r=="#"){if(!t&&bl(h))d=No;else if(h==""){if(c.host="",t)return;d=Wc}else{if(s=c.parseHost(h))return s;if(c.host=="localhost"&&(c.host=""),t)return;h="",d=Wc}continue}h+=r;break;case Wc:if(c.isSpecial()){if(d=No,r!="/"&&r!="\\")continue}else if(t||r!="?")if(t||r!="#"){if(r!=Nr&&(d=No,r!="/"))continue}else c.fragment="",d=rs;else c.query="",d=Ra;break;case No:if(r==Nr||r=="/"||r=="\\"&&c.isSpecial()||!t&&(r=="?"||r=="#")){if((a=Lh(a=h))===".."||a==="%2e."||a===".%2e"||a==="%2e%2e"?(c.shortenPath(),r=="/"||r=="\\"&&c.isSpecial()||jc(c.path,"")):RH(h)?r=="/"||r=="\\"&&c.isSpecial()||jc(c.path,""):(c.scheme=="file"&&!c.path.length&&bl(h)&&(c.host&&(c.host=""),h=Lr(h,0)+":"),jc(c.path,h)),h="",c.scheme=="file"&&(r==Nr||r=="?"||r=="#"))for(;c.path.length>1&&c.path[0]==="";)dH(c.path);r=="?"?(c.query="",d=Ra):r=="#"&&(c.fragment="",d=rs)}else h+=Ds(r,DI);break;case FI:r=="?"?(c.query="",d=Ra):r=="#"?(c.fragment="",d=rs):r!=Nr&&(c.path[0]+=Ds(r,kh));break;case Ra:t||r!="#"?r!=Nr&&(r=="'"&&c.isSpecial()?c.query+="%27":c.query+=r=="#"?"%23":Ds(r,kh)):(c.fragment="",d=rs);break;case rs:r!=Nr&&(c.fragment+=Ds(r,NI))}l++}},parseHost:function(e){var t,n,i;if(Lr(e,0)=="["){if(Lr(e,e.length-1)!="]"||(t=function(r){var o,s,a,c,d,l,h,u=[0,0,0,0,0,0,0,0],p=0,E=null,m=0,g=function(){return Lr(r,m)};if(g()==":"){if(Lr(r,1)!=":")return;m+=2,E=++p}for(;g();){if(p==8)return;if(g()!=":"){for(o=s=0;s<4&&ro(OI,g());)o=16*o+Ph(g(),16),m++,s++;if(g()=="."){if(s==0||(m-=s,p>6))return;for(a=0;g();){if(c=null,a>0){if(!(g()=="."&&a<4))return;m++}if(!ro(kf,g()))return;for(;ro(kf,g());){if(d=Ph(g(),10),c===null)c=d;else{if(c==0)return;c=10*c+d}if(c>255)return;m++}u[p]=256*u[p]+c,++a!=2&&a!=4||p++}if(a!=4)return;break}if(g()==":"){if(m++,!g())return}else if(g())return;u[p++]=o}else{if(E!==null)return;m++,E=++p}}if(E!==null)for(l=p-E,p=7;p!=0&&l>0;)h=u[p],u[p--]=u[E+l-1],u[E+--l]=h;else if(p!=8)return;return u}(Cl(e,1,-1)),!t))return yl;this.host=t}else if(this.isSpecial()){if(e=eH(e),ro(EH,e)||(t=function(r){var o,s,a,c,d,l,h,u=lH(r,".");if(u.length&&u[u.length-1]==""&&u.length--,(o=u.length)>4)return r;for(s=[],a=0;a<o;a++){if((c=u[a])=="")return r;if(d=10,c.length>1&&Lr(c,0)=="0"&&(d=ro(pH,c)?16:8,c=Cl(c,d==8?1:2)),c==="")l=0;else{if(!ro(d==10?mH:d==8?_H:OI,c))return r;l=Ph(c,d)}jc(s,l)}for(a=0;a<o;a++)if(l=s[a],a==o-1){if(l>=II(256,5-o))return null}else if(l>255)return null;for(h=cH(s),a=0;a<s.length;a++)h+=s[a]*II(256,3-a);return h}(e),t===null))return yl;this.host=t}else{if(ro(fH,e))return yl;for(t="",n=Gc(e),i=0;i<n.length;i++)t+=Ds(n[i],kh);this.host=t}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||this.scheme=="file"},includesCredentials:function(){return this.username!=""||this.password!=""},isSpecial:function(){return Of(Mh,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||this.scheme=="file"&&t==1&&bl(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,n=e.username,i=e.password,r=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,d=t+":";return r!==null?(d+="//",e.includesCredentials()&&(d+=n+(i?":"+i:"")+"@"),d+=Il(r),o!==null&&(d+=":"+
1o)):t=="file"&&(d+="//"),d+=e.cannotBeABaseURL?s[0]:s.length?"/"+Al(s,"/"):"",a!==null&&(d+="?"+a),c!==null&&(d+="#"+c),d},setHref:function(e){var t=this.parse(e);if(t)throw Df(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if(e=="blob")try{return new Kc(e.path[0]).origin}catch{return"null"}return e!="file"&&this.isSpecial()?e+"://"+Il(this.host)+(t!==null?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(is(e)+":",Uf)},getUsername:function(){return this.username},setUsername:function(e){var t=Gc(is(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var n=0;n<t.length;n++)this.username+=Ds(t[n],Mf)}},getPassword:function(){return this.password},setPassword:function(e){var t=Gc(is(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var n=0;n<t.length;n++)this.password+=Ds(t[n],Mf)}},getHost:function(){var e=this.host,t=this.port;return e===null?"":t===null?Il(e):Il(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,Ff)},getHostname:function(){var e=this.host;return e===null?"":Il(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,Bf)},getPort:function(){var e=this.port;return e===null?"":is(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||((e=is(e))==""?this.port=null:this.parse(e,Gf))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+Al(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,Wc))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){(e=is(e))==""?this.query=null:(Lr(e,0)=="?"&&(e=Cl(e,1)),this.query="",this.parse(e,Ra)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){(e=is(e))!=""?(Lr(e,0)=="#"&&(e=Cl(e,1)),this.fragment="",this.parse(e,rs)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var Kc=function(e){var t=QK(this,ki),n=nH(arguments.length,1)>1?arguments[1]:void 0,i=iH(t,new Kf(e,!1,n));bf||(t.href=i.serialize(),t.origin=i.getOrigin(),t.protocol=i.getProtocol(),t.username=i.getUsername(),t.password=i.getPassword(),t.host=i.getHost(),t.hostname=i.getHostname(),t.port=i.getPort(),t.pathname=i.getPathname(),t.search=i.getSearch(),t.searchParams=i.getSearchParams(),t.hash=i.getHash())},ki=Kc.prototype,kr=function(e,t){return{get:function(){return Dh(this)[e]()},set:t&&function(n){return Dh(this)[t](n)},configurable:!0,enumerable:!0}};if(bf&&(Pr(ki,"href",kr("serialize","setHref")),Pr(ki,"origin",kr("getOrigin")),Pr(ki,"protocol",kr("getProtocol","setProtocol")),Pr(ki,"username",kr("getUsername","setUsername")),Pr(ki,"password",kr("getPassword","setPassword")),Pr(ki,"host",kr("getHost","setHost")),Pr(ki,"hostname",kr("getHostname","setHostname")),Pr(ki,"port",kr("getPort","setPort")),Pr(ki,"pathname",kr("getPathname","setPathname")),Pr(ki,"search",kr("getSearch","setSearch")),Pr(ki,"searchParams",kr("getSearchParams")),Pr(ki,"hash",kr("getHash","setHash"))),Nh(ki,"toJSON",function(){return Dh(this).serialize()},{enumerable:!0}),Nh(ki,"toString",function(){return Dh(this).serialize()},{enumerable:!0}),vl){var BI=vl.createObjectURL,GI=vl.revokeObjectURL;BI&&Nh(Kc,"createObjectURL",AI(BI,vl)),GI&&Nh(Kc,"revokeObjectURL",AI(GI,vl))}tH(Kc,"URL"),qK({global:!0,forced:!ZK,sham:!bf},{URL:Kc});var vH=st,AH=le,CH=Nc,jI=Yi,yH=_f,WI=Di("URL");vH({target:"URL",stat:!0,forced:!(yH&&AH(function(){WI.canParse()}))},{canParse:function(e){var t=CH(arguments.length,1),n=jI(e),i=t<2||arguments[1]===void 0?void 0:jI(arguments[1]);try{return!!new WI(n,i)}catch{return!1}}});var xh=re(cr.URL);let KI=!0,HI=!0;function Fh(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseInt(i[n],10)}function va(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(s,a){if(s!==t)return r.apply(this,arguments);const c=d=>{const l=n(d);l&&(a.handleEvent?a.handleEvent(l):a(l))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(a,c),r.apply(this,[s,c])};const o=i.removeEventListener;i.removeEventListener=function(s,a){if(s!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(a))return o.apply(this,arguments);const c=this._eventMap[t].get(a);return this._eventMap[t].delete(a),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,o.apply(this,[s,c])}
1,Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(s){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),s&&this.addEventListener(t,this["_on"+t]=s)},enumerable:!0,configurable:!0})}function IH(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(KI=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function bH(e){return typeof e!="boolean"?new Error("Argument type: "+typeof e+". Please use a boolean."):(HI=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function YI(){if(typeof window=="object"){if(KI)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Hf(e,t){HI&&console.warn(e+" is deprecated, please use "+t+" instead.")}function XI(e){return Object.prototype.toString.call(e)==="[object Object]"}function JI(e){var t;return XI(e)?ei(t=Object.keys(e)).call(t,function(n,i){const r=XI(e[i]),o=r?JI(e[i]):e[i],s=r&&!Object.keys(o).length;return o===void 0||s?n:Object.assign(n,{[i]:o})},{}):e}function Yf(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach(i=>{i.endsWith("Id")?Yf(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach(r=>{Yf(e,e.get(r),n)})}))}function zI(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(t===null)return r;const o=[];return e.forEach(s=>{s.type==="track"&&s.trackIdentifier===t.id&&o.push(s)}),o.forEach(s=>{e.forEach(a=>{a.type===i&&a.trackId===s.id&&Yf(e,a,r)})}),r}const qI=YI;function ZI(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(s){if(typeof s!="object"||s.mandatory||s.optional)return s;const a={};return Object.keys(s).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const d=typeof s[c]=="object"?s[c]:{ideal:s[c]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const l=function(h,u){return h?h+u.charAt(0).toUpperCase()+u.slice(1):u==="deviceId"?"sourceId":u};if(d.ideal!==void 0){a.optional=a.optional||[];let h={};typeof d.ideal=="number"?(h[l("min",c)]=d.ideal,a.optional.push(h),h={},h[l("max",c)]=d.ideal,a.optional.push(h)):(h[l("",c)]=d.ideal,a.optional.push(h))}d.exact!==void 0&&typeof d.exact!="number"?(a.mandatory=a.mandatory||{},a.mandatory[l("",c)]=d.exact):["min","max"].forEach(h=>{d[h]!==void 0&&(a.mandatory=a.mandatory||{},a.mandatory[l(h,c)]=d[h])})}),s.advanced&&(a.optional=(a.optional||[]).concat(s.advanced)),a},r=function(s,a){if(t.version>=61)return a(s);if((s=JSON.parse(JSON.stringify(s)))&&typeof s.audio=="object"){const c=function(d,l,h){l in d&&!(h in d)&&(d[h]=d[l],delete d[l])};c((s=JSON.parse(JSON.stringify(s))).audio,"autoGainControl","googAutoGainControl"),c(s.audio,"noiseSuppression","googNoiseSuppression"),s.audio=i(s.audio)}if(s&&typeof s.video=="object"){let c=s.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const d=t.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||d)){let l;if(delete s.video.facingMode,c.exact==="environment"||c.ideal==="environment"?l=["back","rear"]:c.exact!=="user"&&c.ideal!=="user"||(l=["front"]),l)return n.mediaDevices.enumerateDevices().then(h=>{h=h.filter(p=>p.kind==="videoinput");let u=h.find(p=>l.some(E=>{var m;return x(m=p.label.toLowerCase()).call(m,E)}));return!u&&h.length&&x(l).call(l,"back")&&(u=h[h.length-1]),u&&(s.video.deviceId=c.exact?{exact:u.deviceId}:{ideal:u.deviceId}),s.video=i(s.video),qI("chrome: "+JSON.stringify(s)),a(s)})}s.video=i(s.video)}return qI("chrome: "+JSON.stringify(s)),a(s)},o=function(s){return t.version>=64?s:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[s.name]||s.name,message:s.message,constraint:s.constraint||s.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(n.getUserMedia=(function(s,a,c){r(s,d=>{n.webkitGetUserMedia(d,a,l=>{c&&c(o(l))})})}).bind(n),n.mediaDevices.getUserMedia){const s=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(a){return r(a,c=>s(c).then(d=>{if(c.audio&&!d.getAudioTracks().length||c.video&&!d.getVideoTracks().length)throw d.getTracks().forEac
1h(l=>{l.stop()}),new DOMException("","NotFoundError");return d},d=>K.reject(o(d))))}}}function QI(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function $I(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(n){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=n)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(s=>s.track&&s.track.id===i.track.id):{track:i.track};const o=new Event("track");o.track=i.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)}),n.stream.getTracks().forEach(i=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(s=>s.track&&s.track.id===i.id):{track:i};const o=new Event("track");o.track=i,o.receiver=r,o.transceiver={receiver:r},o.streams=[n.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else va(e,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function eb(e){if(typeof e=="object"&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(r,o){return{track:o,get dtmf(){return this._dtmf===void 0&&(o.kind==="audio"?this._dtmf=r.createDTMFSender(o):this._dtmf=null),this._dtmf},_pc:r}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(s,a){let c=r.apply(this,arguments);return c||(c=t(this,s),this._senders.push(c)),c};const o=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(s){o.apply(this,arguments);const a=this._senders.indexOf(s);a!==-1&&this._senders.splice(a,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(o=>{this._senders.push(t(this,o))})};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],i.apply(this,[r]),r.getTracks().forEach(o=>{const s=this._senders.find(a=>a.track===o);s&&this._senders.splice(this._senders.indexOf(s),1)})}}else if(typeof e=="object"&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const n=t.apply(this,[]);return n.forEach(i=>i._pc=this),n},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function tb(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[n,i,r]=arguments;if(arguments.length>0&&typeof n=="function")return t.apply(this,arguments);if(t.length===0&&(arguments.length===0||typeof n!="function"))return t.apply(this,[]);const o=function(a){const c={};return a.result().forEach(d=>{const l={id:d.id,timestamp:d.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[d.type]||d.type};d.names().forEach(h=>{l[h]=d.stat(h)}),c[l.id]=l}),c},s=function(a){return new Map(Object.keys(a).map(c=>[c,a[c]]))};if(arguments.length>=2){const a=function(c){i(s(o(c)))};return t.apply(this,[a,n])}return new K((a,c)=>{t.apply(this,[function(d){a(s(o(d)))},c])}).then(i,r)}}function nb(e){if(!(typeof e=="object"&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const n=e.RTCPeerConnection.prototype.getSenders;n&&(e.RTCPeerConnection.prototype.getSenders=function(){const r=n.apply(this,[]);return r.forEach(o=>o._pc=this),r});const i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){const r=i.apply(this,arguments);return r._pc=this,r}),e.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(o=>zI(o,r.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const n=e.RTCPeerConnection.prototype.getReceivers;n&&(e.RTCPeerConnection.prototype.getReceivers=function(){const i=n.apply(this,[]);
vendor: 4,149 bytes, line 1
1return i.forEach(r=>r._pc=this),i}),va(e,"track",i=>(i.receiver._pc=i.srcElement,i)),e.RTCRtpReceiver.prototype.getStats=function(){const i=this;return this._pc.getStats().then(r=>zI(r,i.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const n=arguments[0];let i,r,o;return this.getSenders().forEach(s=>{s.track===n&&(i?o=!0:i=s)}),this.getReceivers().forEach(s=>(s.track===n&&(r?o=!0:r=s),s.track===n)),o||i&&r?K.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():r?r.getStats():K.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function ib(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(o,s){if(!s)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const a=t.apply(this,arguments);return this._shimmedLocalStreams[s.id]?this._shimmedLocalStreams[s.id].indexOf(a)===-1&&this._shimmedLocalStreams[s.id].push(a):this._shimmedLocalStreams[s.id]=[s,a],a};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(c=>{if(this.getSenders().find(d=>d.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const s=this.getSenders();n.apply(this,arguments);const a=this.getSenders().filter(c=>s.indexOf(c)===-1);this._shimmedLocalStreams[o.id]=[o].concat(a)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],i.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(s=>{const a=this._shimmedLocalStreams[s].indexOf(o);a!==-1&&this._shimmedLocalStreams[s].splice(a,1),this._shimmedLocalStreams[s].length===1&&delete this._shimmedLocalStreams[s]}),r.apply(this,arguments)}}function rb(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return ib(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const c=n.apply(this);return this._reverseStreams=this._reverseStreams||{},c.map(d=>this._reverseStreams[d.id])};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(c){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},c.getTracks().forEach(d=>{if(this.getSenders().find(l=>l.track===d))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[c.id]){const d=new e.MediaStream(c.getTracks());this._streams[c.id]=d,this._reverseStreams[d.id]=c,c=d}i.apply(this,[c])};const r=e.RTCPeerConnection.prototype.removeStream;function o(c,d){let l=d.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const u=c._reverseStreams[h],p=c._streams[u.id];l=l.replace(new RegExp(p.id,"g"),u.id)}),new RTCSessionDescription({type:d.type,sdp:l})}e.RTCPeerConnection.prototype.removeStream=function(c){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[c.id]||c]),delete this._reverseStreams[this._streams[c.id]?this._streams[c.id].id:c.id],delete this._streams[c.id]},e.RTCPeerConnection.prototype.addTrack=function(c,d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");
1const l=[].slice.call(arguments,1);if(l.length!==1||!l[0].getTracks().find(u=>u===c))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(u=>u.track===c))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const h=this._streams[d.id];if(h)h.addTrack(c),K.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const u=new e.MediaStream([c]);this._streams[d.id]=u,this._reverseStreams[u.id]=d,this.addStream(u)}return this.getSenders().find(u=>u.track===c)},["createOffer","createAnswer"].forEach(function(c){const d=e.RTCPeerConnection.prototype[c],l={[c](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[u=>{const p=o(this,u);h[0].apply(null,[p])},u=>{h[1]&&h[1].apply(null,u)},arguments[2]]):d.apply(this,arguments).then(u=>o(this,u))}};e.RTCPeerConnection.prototype[c]=l[c]});const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(c,d){let l=d.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const u=c._reverseStreams[h],p=c._streams[u.id];l=l.replace(new RegExp(u.id,"g"),p.id)}),new RTCSessionDescription({type:d.type,sdp:l})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const c=a.get.apply(this);return c.type===""?c:o(this,c)}}),e.RTCPeerConnection.prototype.removeTrack=function(c){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!c._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(c._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let d;this._streams=this._streams||{},Object.keys(this._streams).forEach(l=>{this._streams[l].getTracks().find(h=>c.track===h)&&(d=this._streams[l])}),d&&(d.getTracks().length===1?this.removeStream(this._reverseStreams[d.id]):d.removeTrack(c.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Xf(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(n){const i=e.RTCPeerConnection.prototype[n],r={[n](){return arguments[0]=new(n==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};e.RTCPeerConnection.prototype[n]=r[n]})}function ob(e,t){va(e,"negotiationneeded",n=>{const i=n.target;if(!(t.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")||i.signalingState==="stable")return n})}var sb=Object.freeze({__proto__:null,fixNegotiationNeeded:ob,shimAddTrackRemoveTrack:rb,shimAddTrackRemoveTrackWithNative:ib,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(typeof t=="function"?e.navigator.mediaDevices.getDisplayMedia=function(n){return t(n).then(i=>{const r=n.video&&n.video.width,o=n.video&&n.video.height,s=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:i,maxFrameRate:s||3}},r&&(n.video.mandatory.maxWidth=r),o&&(n.video.mandatory.maxHeight=o),e.navigator.mediaDevices.getUserMedia(n)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:eb,shimGetStats:tb,shimGetUserMedia:ZI,shimMediaStream:QI,shimOnTrack:$I,shimPeerConnection:Xf,shimSenderReceiverGetStats:nb});function ab(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(r,o,s){Hf("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(r).then(o,s)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const r=function(s,a,c){a in s&&!(c in s)&&(s[c]=s[a],delete s[a])},o=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(s){return typeof s=="object"&&typeof s.audio=="object"&&(s=JSON.parse(JSON.stringify(s)),r(s.audio,"autoGainControl","mozAutoGainControl"),r(s.audio,"noiseSuppression","mozNoiseSuppression")),o(s)},i&&i.prototype.getSettings){const s=i.prototype.getSettings;i.prototype.getSettings=function(){const a=s.apply(this,arguments);return r(a,"mozAutoGainControl","autoGainControl"),r(a,"mozNoiseSuppression","noiseSuppression"),a}}if(i&&i.prototype.applyConstraints){const s=i.prototype.applyConstraints;i.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a,"autoGainControl","mozAutoGainControl"),r(a,"noiseSuppression","mozNoiseSuppression")),s.apply(this,[a])}}}}function cb(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Jf(e,t){if(typeof e!="object"||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const o=e.RTCPeerConnection.prototype[r],s={[r](){return arguments[0]=new(r==="addIceCandidate"?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),o.apply(this,arguments)}};e.RTCPeerConnection.prototype[r]=s[r]});const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotec
vendor: 4,566 bytes, line 1
1andidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const[r,o,s]=arguments;return i.apply(this,[r||null]).then(a=>{if(t.version<53&&!o)try{a.forEach(c=>{c.type=n[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;a.forEach((d,l)=>{a.set(l,Object.assign({},d,{type:n[d.type]||d.type}))})}return a}).then(o,s)}}function db(e){if(typeof e!="object"||!e.RTCPeerConnection||!e.RTCRtpSender||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const i=t.apply(this,[]);return i.forEach(r=>r._pc=this),i});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const i=n.apply(this,arguments);return i._pc=this,i}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):K.resolve(new Map)}}function lb(e){if(typeof e!="object"||!e.RTCPeerConnection||!e.RTCRtpSender||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const n=t.apply(this,[]);return n.forEach(i=>i._pc=this),n}),va(e,"track",n=>(n.receiver._pc=n.srcElement,n)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ub(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(t){Hf("removeStream","removeTrack"),this.getSenders().forEach(n=>{var i;n.track&&x(i=t.getTracks()).call(i,n.track)&&this.removeTrack(n)})})}function hb(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function pb(e){if(typeof e!="object"||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const i=n.length>0;i&&n.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=t.apply(this,arguments);if(i){const{sender:o}=r,s=o.getParameters();(!("encodings"in s)||s.encodings.length===1&&Object.keys(s.encodings[0]).length===0)&&(s.encodings=n,o.sendEncodings=n,this.setParametersPromises.push(o.setParameters(s).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return r})}function _b(e){if(typeof e!="object"||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const n=t.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function mb(e){if(typeof e!="object"||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?K.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Eb(e){if(typeof e!="object"||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?K.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var fb=Object.freeze({__proto__:null,shimAddTransceiver:pb,shimCreateAnswer:Eb,shimCreateOffer:mb,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){const i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,K.reject(i)}return n.video===!0?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})},shimGetParameters:_b,shimGetUserMedia:ab,shimOnTrack:cb,shimPeerConnection:Jf,shimRTCDataChannel:hb,shimReceiverGetStats:lb,shimRemoveStream:ub,shimSenderGetStats:db});function gb(e){if(typeof e=="object"&&e.RTCPeerConnection){if("getL
1ocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(n){var i;this._localStreams||(this._localStreams=[]),x(i=this._localStreams).call(i,n)||this._localStreams.push(n),n.getAudioTracks().forEach(r=>t.call(this,r,n)),n.getVideoTracks().forEach(r=>t.call(this,r,n))},e.RTCPeerConnection.prototype.addTrack=function(n){for(var i=arguments.length,r=new Array(i>1?i-1:0),o=1;o<i;o++)r[o-1]=arguments[o];return r&&r.forEach(s=>{var a;this._localStreams?x(a=this._localStreams).call(a,s)||this._localStreams.push(s):this._localStreams=[s]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const i=t.getTracks();this.getSenders().forEach(r=>{x(i).call(i,r.track)&&this.removeTrack(r)})})}}function Sb(e){if(typeof e=="object"&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(n){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=n),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(r=>{var o;if(this._remoteStreams||(this._remoteStreams=[]),x(o=this._remoteStreams).call(o,r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(i){i.streams.forEach(r=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(r)>=0)return;n._remoteStreams.push(r);const o=new Event("addstream");o.stream=r,n.dispatchEvent(o)})}),t.apply(n,arguments)}}}function Tb(e){if(typeof e!="object"||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(c,d){const l=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[l]);return d?(h.then(c,d),K.resolve()):h},t.createAnswer=function(c,d){const l=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[l]);return d?(h.then(c,d),K.resolve()):h};let a=function(c,d,l){const h=r.apply(this,[c]);return l?(h.then(d,l),K.resolve()):h};t.setLocalDescription=a,a=function(c,d,l){const h=o.apply(this,[c]);return l?(h.then(d,l),K.resolve()):h},t.setRemoteDescription=a,a=function(c,d,l){const h=s.apply(this,[c]);return l?(h.then(d,l),K.resolve()):h},t.addIceCandidate=a}function Rb(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const n=t.mediaDevices,i=n.getUserMedia.bind(n);t.mediaDevices.getUserMedia=r=>i(vb(r))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(n,i,r){t.mediaDevices.getUserMedia(n).then(i,r)}).bind(t))}function vb(e){return e&&e.video!==void 0?Object.assign({},e,{video:JI(e.video)}):e}function Ab(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(n,i){if(n&&n.iceServers){const r=[];for(let o=0;o<n.iceServers.length;o++){let s=n.iceServers[o];!s.hasOwnProperty("urls")&&s.hasOwnProperty("url")?(Hf("RTCIceServer.url","RTCIceServer.urls"),s=JSON.parse(JSON.stringify(s)),s.urls=s.url,delete s.url,r.push(s)):r.push(n.iceServers[o])}n.iceServers=r}return new t(n,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function Cb(e){typeof e=="object"&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function yb(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(n){if(n){n.offerToReceiveAudio!==void 0&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const i=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):n.offerToReceiveAudio!==!0||i||this.addTransceiver("audio",{direction:"recvonly"}),n.offerToReceiveVideo!==void 0&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):n.offerToReceiveVideo!==!0||r||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Ib(e){typeof e!="object"||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var bb=Object.freeze({__proto__:null,shimAudioContext:Ib,shimCallbacksAPI:Tb,shimConstraints:vb,shimCreateOfferLegacy:yb,shimGetUserMedia:Rb,shimLocalStreamsAPI:gb,shimRTCIceServerUrls:Ab,shimRemoteStreamsAPI:Sb,shimTrackEventTransceiver:Cb}),wb=` 2\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`,wH=ha,OH=Yi,zf=wb,Ob=et("".replace),NH=RegExp("^["+zf+"]+"),DH=RegExp("(^|[^"+zf+"])["+zf+"]+$"),PH=function(e){return function(t){var n=OH(w
2H(t));return 1&e&&(n=Ob(n,NH,"")),2&e&&(n=Ob(n,DH,"$1")),n}},LH={trim:PH(3)},kH=fC.PROPER,MH=le,Nb=wb,UH=LH.trim;st({target:"String",proto:!0,forced:function(e){return MH(function(){return!!Nb[e]()||"\u200B\x85\u180E"[e]()!=="\u200B\x85\u180E"||kH&&Nb[e].name!==e})}("trim")},{trim:function(){return UH(this)}});var VH=lr("String").trim,xH=Ee,FH=VH,qf=String.prototype,BH=function(e){var t=e.trim;return typeof e=="string"||e===qf||xH(qf,e)&&t===qf.trim?FH:t},Mn=re(BH),Db={exports:{}};(function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(n){return n.trim().split(` 3`).map(i=>i.trim())},t.splitSections=function(n){return n.split(` 4m=`).map((i,r)=>(r>0?"m="+i:i).trim()+`\r 5`)},t.getDescription=function(n){const i=t.splitSections(n);return i&&i[0]},t.getMediaSections=function(n){const i=t.splitSections(n);return i.shift(),i},t.matchPrefix=function(n,i){return t.splitLines(n).filter(r=>r.indexOf(i)===0)},t.parseCandidate=function(n){let i;i=n.indexOf("a=candidate:")===0?n.substring(12).split(" "):n.substring(10).split(" ");const r={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let o=8;o<i.length;o+=2)switch(i[o]){case"raddr":r.relatedAddress=i[o+1];break;case"rport":r.relatedPort=parseInt(i[o+1],10);break;case"tcptype":r.tcpType=i[o+1];break;case"ufrag":r.ufrag=i[o+1],r.usernameFragment=i[o+1];break;default:r[i[o]]===void 0&&(r[i[o]]=i[o+1])}return r},t.writeCandidate=function(n){const i=[];i.push(n.foundation);const r=n.component;r==="rtp"?i.push(1):r==="rtcp"?i.push(2):i.push(r),i.push(n.protocol.toUpperCase()),i.push(n.priority),i.push(n.address||n.ip),i.push(n.port);const o=n.type;return i.push("typ"),i.push(o),o!=="host"&&n.relatedAddress&&n.relatedPort&&(i.push("raddr"),i.push(n.relatedAddress),i.push("rport"),i.push(n.relatedPort)),n.tcpType&&n.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(n.tcpType)),(n.usernameFragment||n.ufrag)&&(i.push("ufrag"),i.push(n.usernameFragment||n.ufrag)),"candidate:"+i.join(" ")},t.parseIceOptions=function(n){return n.substring(14).split(" ")},t.parseRtpMap=function(n){let i=n.substring(9).split(" ");const r={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),r.name=i[0],r.clockRate=parseInt(i[1],10),r.channels=i.length===3?parseInt(i[2],10):1,r.numChannels=r.channels,r},t.writeRtpMap=function(n){let i=n.payloadType;n.preferredPayloadType!==void 0&&(i=n.preferredPayloadType);const r=n.channels||n.numChannels||1;return"a=rtpmap:"+i+" "+n.name+"/"+n.clockRate+(r!==1?"/"+r:"")+`\r 6`},t.parseExtmap=function(n){const i=n.substring(9).split(" ");return{id:parseInt(i[0],10),direction:i[0].indexOf("/")>0?i[0].split("/")[1]:"sendrecv",uri:i[1],attributes:i.slice(2).join(" ")}},t.writeExtmap=function(n){return"a=extmap:"+(n.id||n.preferredId)+(n.direction&&n.direction!=="sendrecv"?"/"+n.direction:"")+" "+n.uri+(n.attributes?" "+n.attributes:"")+`\r 7`},t.parseFmtp=function(n){const i={};let r;const o=n.substring(n.indexOf(" ")+1).split(";");for(let s=0;s<o.length;s++)r=o[s].trim().split("="),i[r[0].trim()]=r[1];return i},t.writeFmtp=function(n){let i="",r=n.payloadType;if(n.preferredPayloadType!==void 0&&(r=n.preferredPayloadType),n.parameters&&Object.keys(n.parameters).length){const o=[];Object.keys(n.parameters).forEach(s=>{n.parameters[s]!==void 0?o.push(s+"="+n.parameters[s]):o.push(s)}),i+="a=fmtp:"+r+" "+o.join(";")+`\r 8`}return i},t.parseRtcpFb=function(n){const i=n.substring(n.indexOf(" ")+1).split(" ");return{type:i.shift(),parameter:i.join(" ")}},t.writeRtcpFb=function(n){let i="",r=n.payloadType;return n.preferredPayloadType!==void 0&&(r=n.preferredPayloadType),n.rtcpFeedback&&n.rtcpFeedback.length&&n.rtcpFeedback.forEach(o=>{i+="a=rtcp-fb:"+r+" "+o.type+(o.parameter&&o.parameter.length?" "+o.parameter:"")+`\r 9`}),i},t.parseSsrcMedia=function(n){const i=n.indexOf(" "),r={ssrc:parseInt(n.substring(7,i),10)},o=n.indexOf(":",i);return o>-1?(r.attribute=n.substring(i+1,o),r.value=n.substring(o+1)):r.attribute=n.substring(i+1),r},t.parseSsrcGroup=function(n){const i=n.substring(13).split(" ");return{semantics:i.shift(),ssrcs:i.map(r=>parseInt(r,10))}},t.getMid=function(n){const i=t.matchPrefix(n,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(n){const i=n.substring(14).split(" ");return{algorithm:i[0].toLowerCase(),value:i[1].toUpperCase()}},t.getDtlsParameters=function(n,i){return{role:"auto",fingerprints:t.matchPrefix(n+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(n,i){let r="a=setup:"+i+`\r 10`;
vendor: 7,603 bytes, lines 10-33
10return n.fingerprints.forEach(o=>{r+="a=fingerprint:"+o.algorithm+" "+o.value+`\r 11`}),r},t.parseCryptoLine=function(n){const i=n.substring(9).split(" ");return{tag:parseInt(i[0],10),cryptoSuite:i[1],keyParams:i[2],sessionParams:i.slice(3)}},t.writeCryptoLine=function(n){return"a=crypto:"+n.tag+" "+n.cryptoSuite+" "+(typeof n.keyParams=="object"?t.writeCryptoKeyParams(n.keyParams):n.keyParams)+(n.sessionParams?" "+n.sessionParams.join(" "):"")+`\r 12`},t.parseCryptoKeyParams=function(n){if(n.indexOf("inline:")!==0)return null;const i=n.substring(7).split("|");return{keyMethod:"inline",keySalt:i[0],lifeTime:i[1],mkiValue:i[2]?i[2].split(":")[0]:void 0,mkiLength:i[2]?i[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(n){return n.keyMethod+":"+n.keySalt+(n.lifeTime?"|"+n.lifeTime:"")+(n.mkiValue&&n.mkiLength?"|"+n.mkiValue+":"+n.mkiLength:"")},t.getCryptoParameters=function(n,i){return t.matchPrefix(n+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(n,i){const r=t.matchPrefix(n+i,"a=ice-ufrag:")[0],o=t.matchPrefix(n+i,"a=ice-pwd:")[0];return r&&o?{usernameFragment:r.substring(12),password:o.substring(10)}:null},t.writeIceParameters=function(n){let i="a=ice-ufrag:"+n.usernameFragment+`\r 13a=ice-pwd:`+n.password+`\r 14`;return n.iceLite&&(i+=`a=ice-lite\r 15`),i},t.parseRtpParameters=function(n){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(n)[0].split(" ");i.profile=r[2];for(let s=3;s<r.length;s++){const a=r[s],c=t.matchPrefix(n,"a=rtpmap:"+a+" ")[0];if(c){const d=t.parseRtpMap(c),l=t.matchPrefix(n,"a=fmtp:"+a+" ");switch(d.parameters=l.length?t.parseFmtp(l[0]):{},d.rtcpFeedback=t.matchPrefix(n,"a=rtcp-fb:"+a+" ").map(t.parseRtcpFb),i.codecs.push(d),d.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(d.name.toUpperCase())}}}t.matchPrefix(n,"a=extmap:").forEach(s=>{i.headerExtensions.push(t.parseExtmap(s))});const o=t.matchPrefix(n,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach(s=>{o.forEach(a=>{s.rtcpFeedback.find(c=>c.type===a.type&&c.parameter===a.parameter)||s.rtcpFeedback.push(a)})}),i},t.writeRtpDescription=function(n,i){let r="";r+="m="+n+" ",r+=i.codecs.length>0?"9":"0",r+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=i.codecs.map(s=>s.preferredPayloadType!==void 0?s.preferredPayloadType:s.payloadType).join(" ")+`\r 16`,r+=`c=IN IP4 0.0.0.0\r 17`,r+=`a=rtcp:9 IN IP4 0.0.0.0\r 18`,i.codecs.forEach(s=>{r+=t.writeRtpMap(s),r+=t.writeFmtp(s),r+=t.writeRtcpFb(s)});let o=0;return i.codecs.forEach(s=>{s.maxptime>o&&(o=s.maxptime)}),o>0&&(r+="a=maxptime:"+o+`\r 19`),i.headerExtensions&&i.headerExtensions.forEach(s=>{r+=t.writeExtmap(s)}),r},t.parseRtpEncodingParameters=function(n){const i=[],r=t.parseRtpParameters(n),o=r.fecMechanisms.indexOf("RED")!==-1,s=r.fecMechanisms.indexOf("ULPFEC")!==-1,a=t.matchPrefix(n,"a=ssrc:").map(u=>t.parseSsrcMedia(u)).filter(u=>u.attribute==="cname"),c=a.length>0&&a[0].ssrc;let d;const l=t.matchPrefix(n,"a=ssrc-group:FID").map(u=>u.substring(17).split(" ").map(p=>parseInt(p,10)));l.length>0&&l[0].length>1&&l[0][0]===c&&(d=l[0][1]),r.codecs.forEach(u=>{if(u.name.toUpperCase()==="RTX"&&u.parameters.apt){let p={ssrc:c,codecPayloadType:parseInt(u.parameters.apt,10)};c&&d&&(p.rtx={ssrc:d}),i.push(p),o&&(p=JSON.parse(JSON.stringify(p)),p.fec={ssrc:c,mechanism:s?"red+ulpfec":"red"},i.push(p))}}),i.length===0&&c&&i.push({ssrc:c});let h=t.matchPrefix(n,"b=");return h.length&&(h=h[0].indexOf("b=TIAS:")===0?parseInt(h[0].substring(7),10):h[0].indexOf("b=AS:")===0?1e3*parseInt(h[0].substring(5),10)*.95-16e3:void 0,i.forEach(u=>{u.maxBitrate=h})),i},t.parseRtcpParameters=function(n){const i={},r=t.matchPrefix(n,"a=ssrc:").map(a=>t.parseSsrcMedia(a)).filter(a=>a.attribute==="cname")[0];r&&(i.cname=r.value,i.ssrc=r.ssrc);const o=t.matchPrefix(n,"a=rtcp-rsize");i.reducedSize=o.length>0,i.compound=o.length===0;const s=t.matchPrefix(n,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(n){let i="";return n.reducedSize&&(i+=`a=rtcp-rsize\r 20`),n.mux&&(i+=`a=rtcp-mux\r 21`),n.ssrc!==void 0&&n.cname&&(i+="a=ssrc:"+n.ssrc+" cname:"+n.cname+`\r 22`),i},t.parseMsid=function(n){let i;const r=t.matchPrefix(n,"a=msid:");if(r.length===1)return i=r[0].substring(7).split(" "),{stream:i[0],track:i[1]};const o=t.matchPrefix(n,"a=ssrc:").map(s=>t.parseSsrcMedia(s)).filter(s=>s.attribute==="msid");return o.length>0?(i=o[0].value.split(" "),{stream:i[0],track:i[1]}):void 0},t.parseSctpDescription=function(n){const i=t.parseMLine(n),r=t.matchPrefix(n,"a=max-message-size:");let o;r.length>0&&(o=parseInt(r[0].substring(19),10)),isNaN(o)&&(o=65536);const s=t.matchPrefix(n,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:i.fmt,maxMessageSize:o};const a=t.matchPrefix(n,"a=sctpmap:");if(a.length>0){const c=a[0].substring(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:o}}},t.writeSctpDescription=function(n,i){let r=[];return r=n.protocol!=="DTLS/SCTP"?["m="+n.kind+" 9 "+n.protocol+" "+i.protocol+`\r 23`,`c=IN IP4 0.0.0.0\r 24`,"a=sctp-port:"+i.port+`\r 25`]:["m="+n.kind+" 9 "+n.protocol+" "+i.port+`\r 26`,`c=IN IP4 0.0.0.0\r 27`,"a=sctpmap:"+i.port+" "+i.protocol+` 65535\r 28`],i.maxMessageSize!==void 0&&r.push("a=max-message-size:"+i.maxMessageSize+`\r 29`),r.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(n,i,r){let o;const s=i!==void 0?i:2;return o=n||t.generateSessionId(),`v=0\r 30o=`+(r||"thisisadapterortc")+" "+o+" "+s+` IN IP4 127.0.0.1\r 31s=-\r 32t=0 0\r 33`},t.getDirection=function(n,i){const r=t.splitLines(n);for(let o=0;o<r.length;o++)switch(r[o]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[o].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(n){return t.splitLines(n)[0].split(" ")[0].substring(2)},t.isRejected=function(n){return n.split(" ",2)[1]==="0"},t.parseMLine=function(n){const i=t.splitLines(n)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(n){const i=t.matchPrefix(n,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},t.isValidSDP=function(n){if(typeof n!="string"||n.length===0)return!1;const i=t.splitLines(n);for(let r=0;r<i.length;r++)if(i[r].length<2||i[r].charAt(1)!=="=")return!1;return!0},e.exports=t})(Db);var Pb=Db.exports,Hc=re(Pb),GH=Ye({__proto__:null,default:Hc},[Pb]);function Bh(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&((n=JSON.parse(JSON.stringify(n))).candidate=n.candidate.substr(2)),n.candidate&&n.candidate.length){const i=new t(n),r=Hc.parseCandidate(n.candidate),o=Object.assign(i,r);return o.toJSON=function(){return{candidate:o.candidate,sdpMid:o.sdpMid,sdpMLineIndex:o.sdpMLineIndex,usernameFragment:o.usernameFragment}},o}return new t(n)},e.RTCIceCandidate.prototype=t.prototype,va(e,"icecandidate",n=>(n.candidate&&Object.defineProperty(n,"candidate",{value:new e.RTCIceCandidate(n.candidate),writable:"false"}),n))}function Zf(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||va(e,"icecandidate",t=>{if(t.candidate){const n=Hc.parseCandidate(t.candidate.candidate);n.type==="relay"&&(t.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[n.priority>>24])}return t})}function Gh(e,t){if(!e.RTCPeerConnection)return;
33"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return this._sctp===void 0?null:this._sctp}});const n=function(a){if(!a||!a.sdp)return!1;const c=Hc.splitSections(a.sdp);return c.shift(),c.some(d=>{const l=Hc.parseMLine(d);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},i=function(a){const c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const d=parseInt(c[1],10);return d!=d?-1:d},r=function(a){let c=65536;return t.browser==="firefox"&&(c=t.version<57?a===-1?16384:2147483637:t.version<60?t.version===57?65535:65536:2147483637),c},o=function(a,c){let d=65536;t.browser==="firefox"&&t.version===57&&(d=65535);const l=Hc.matchPrefix(a.sdp,"a=max-message-size:");return l.length>0?d=parseInt(l[0].substr(19),10):t.browser==="firefox"&&c!==-1&&(d=2147483637),d},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser==="chrome"&&t.version>=76){const{sdpSemantics:a}=this.getConfiguration();a==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(n(arguments[0])){const a=i(arguments[0]),c=r(a),d=o(arguments[0],a);let l;l=c===0&&d===0?Number.POSITIVE_INFINITY:c===0||d===0?Math.max(c,d):Math.min(c,d);const h={};Object.defineProperty(h,"maxMessageSize",{get:()=>l}),this._sctp=h}return s.apply(this,arguments)}}function jh(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(i,r){const o=i.send;i.send=function(){const s=arguments[0],a=s.length||s.size||s.byteLength;if(i.readyState==="open"&&r.sctp&&a>r.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+r.sctp.maxMessageSize+" bytes)");return o.apply(i,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const i=n.apply(this,arguments);return t(i,this),i},va(e,"datachannel",i=>(t(i.channel,i.target),i))}function Qf(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(n){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),n&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=n)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(n=>{const i=t[n];t[n]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const o=r.target;if(o._lastConnectionState!==o.connectionState){o._lastConnectionState=o.connectionState;const s=new Event("connectionstatechange",r);o.dispatchEvent(s)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function $f(e,t){if(!e.RTCPeerConnection||t.browser==="chrome"&&t.version>=71||t.browser==="safari"&&t.version>=605)return;const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(i){if(i&&i.sdp&&i.sdp.indexOf(` 34a=extmap-allow-mixed`)!==-1){const r=i.sdp.split(` 35`).filter(o=>Mn(o).call(o)!=="a=extmap-allow-mixed").join(` 36`);e.RTCSessionDescription&&i instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:i.type,sdp:r}):i.sdp=r}return n.apply(this,arguments)}}function Wh(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.addIceCandidate;n&&n.length!==0&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser==="chrome"&&t.version<78||t.browser==="firefox"&&t.version<68||t.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?K.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),K.resolve())})}function Kh(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.setLocalDescription;n&&n.length!==0&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return n.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer"}return i.sdp||i.type!=="offer"&&i.type!=="answer"?n.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(r=>n.apply(this,[r]))})}var jH=Object.freeze({__proto__:null,removeExtmapAllowMixed:$f,shimAddIceCandidateNullOrEmpty:Wh,shimConnectionState:Qf,shimMaxMessageSize:Gh,shimParameterlessSetLocalDescription:Kh,shimRTCIceCandidate:
36Bh,shimRTCIceCandidateRelayProtocol:Zf,shimSendThrowTypeError:jh});(function(){let{window:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=YI,i=function(o){const s={browser:null,version:null};if(o===void 0||!o.navigator)return s.browser="Not a browser.",s;const{navigator:a}=o;if(a.mozGetUserMedia)s.browser="firefox",s.version=Fh(a.userAgent,/Firefox\/(\d+)\./,1);else if(a.webkitGetUserMedia||o.isSecureContext===!1&&o.webkitRTCPeerConnection)s.browser="chrome",s.version=Fh(a.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!o.RTCPeerConnection||!a.userAgent.match(/AppleWebKit\/(\d+)\./))return s.browser="Not a supported browser.",s;s.browser="safari",s.version=Fh(a.userAgent,/AppleWebKit\/(\d+)\./,1),s.supportsUnifiedPlan=o.RTCRtpTransceiver&&"currentDirection"in o.RTCRtpTransceiver.prototype}return s}(e),r={browserDetails:i,commonShim:jH,extractVersion:Fh,disableLog:IH,disableWarnings:bH,sdp:GH};switch(i.browser){case"chrome":if(!sb||!Xf||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(i.version===null)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=sb,Wh(e,i),Kh(e),ZI(e,i),QI(e),Xf(e,i),$I(e),rb(e,i),eb(e),tb(e),nb(e),ob(e,i),Bh(e),Zf(e),Qf(e),Gh(e,i),jh(e),$f(e,i);break;case"firefox":if(!fb||!Jf||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=fb,Wh(e,i),Kh(e),ab(e,i),Jf(e,i),cb(e),ub(e),db(e),lb(e),hb(e),pb(e),_b(e),mb(e),Eb(e),Bh(e),Qf(e),Gh(e,i),jh(e);break;case"safari":if(!bb||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=bb,Wh(e,i),Kh(e),Ab(e),yb(e),Tb(e),gb(e),Sb(e),Cb(e),Rb(e),Ib(e),Bh(e),Zf(e),Gh(e,i),jh(e),$f(e,i);break;default:n("Unsupported browser!")}})({window:typeof window>"u"?void 0:window});var WH=Si,KH=wt,HH=Wn,YH=Ee,XH=function(){var e=WH(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},Lb=RegExp.prototype,eg=function(e){var t=e.flags;return t!==void 0||"flags"in Lb||HH(e,"flags")||!YH(Lb,e)?t:KH(XH,e)},tg=et,JH=Math.floor,ng=tg("".charAt),zH=tg("".replace),ig=tg("".slice),qH=/\$([$&'`]|\d{1,2})/g,ZH=st,QH=wt,rg=et,kb=ha,$H=Kt,eY=gc,tY=iE,Yc=Yi,nY=sl,iY=eg,rY=function(e,t,n,i,r,o){var s=n+e.length,a=i.length,c=qH;return zH(o,c,function(d,l){var h;switch(ng(l,0)){case"$":return"$";case"&":return e;case"`":return ig(t,0,n);case"'":return ig(t,s);case"<":h=r[ig(l,1,-1)];break;default:var u=+l;if(u===0)return d;if(u>a){var p=JH(u/10);return p===0?d:p<=a?i[p-1]===void 0?ng(l,1):i[p-1]+ng(l,1):d}h=i[u-1]}return h===void 0?"":h})},oY=tn("replace"),sY=TypeError,Mb=rg("".indexOf),aY=rg("".replace),Ub=rg("".slice),cY=Math.max,Vb=function(e,t,n){return n>e.length?-1:t===""?n:Mb(e,t,n)};ZH({target:"String",proto:!0},{replaceAll:function(e,t){var n,i,r,o,s,a,c,d,l,h=kb(this),u=0,p=0,E="";if(!eY(e)){if((n=tY(e))&&(i=Yc(kb(iY(e))),!~Mb(i,"g")))throw sY("`.replaceAll` does not allow non-global regexes");if(r=nY(e,oY))return QH(r,e,h,t);if(n)return aY(Yc(h),e,t)}for(o=Yc(h),s=Yc(e),(a=$H(t))||(t=Yc(t)),c=s.length,d=cY(1,c),u=Vb(o,s,0);u!==-1;)l=a?Yc(t(s,u,o)):rY(s,o,u,[],void 0,t),E+=Ub(o,p,u)+l,p=u+c,u=Vb(o,s,u+d);return p<o.length&&(E+=Ub(o,p)),E}});var dY=lr("String").replaceAll,lY=Ee,uY=dY,og=String.prototype,hY=function(e){var t=e.replaceAll;return typeof e=="string"||e===og||lY(og,e)&&t===og.replaceAll?uY:t},pY=re(hY),sg=be;st({global:!0,forced:sg.globalThis!==sg},{globalThis:sg});var Ps=re(be),ag={exports:{}};(function(e,t){(function(n,i){var r="function",o="undefined",s="object",a="string",c="major",d="model",l="name",h="type",u="vendor",p="version",E="architecture",m="console",g="mobile",R="tablet",v="smarttv",C="wearable",w="embedded",b="Amazon",y="Apple",N="ASUS",k="BlackBerry",U="Browser",X="Chrome",q="Firefox",se="Google",_e="Huawei",me="LG",ke="Microsoft",We="Motorola",M="Opera",F="Samsung",J="Sharp",V="Sony",f="Xiaomi",I="Zebra",O="Facebook",B="Chromium OS",ne="Mac OS",Ge=function(dn){for(var Rn={},Pt=0;Pt<dn.length;Pt++)Rn[dn[Pt].toUpperCase()]=dn[Pt];return Rn},Tn=function(dn,Rn){return typeof dn===a&&yi(Rn).indexOf(yi(dn))!==-1},yi=function(dn){return dn.toLowerCase()},Ss=function(dn,Rn){if(typeof dn===a)return dn=dn.replace(/^\s\s*/,""),typeof Rn===o?dn:dn.substring(0,350)},_c=function(dn,Rn){for(var Pt,Gi,Zo,$t,ze,Ii,da=0;da<Rn.length&&!ze;){var yo=Rn[da],Sx=Rn[da+1];for(Pt=Gi=0;Pt<yo.length&&!ze&&yo[Pt];)if(ze=yo[Pt++].exec(dn))for(Zo=0;Zo<Sx.length;Zo++)Ii=ze[++Gi],typeof($t=Sx[Zo])===s&&$t.length>0?$t.length===2?typeof $t[1]==r?this[$t[0]]=$t[1].call(this,Ii):this[$t[0]]=$t[1]:$t.length===3?typeof $t[1]!==r||$t[1].exec&&$t[1].test?this[$t[0]]=Ii?Ii.replace($t[1],$t[2]):i:this[$t[0]]=Ii?$t[1].call(this,Ii,$t[2]):i:$t.length===4&&(this[$t[0]]=Ii?$t[3].call(this,Ii.replace($t[1],$t[2])):i):this[$t]=Ii||i;da+=2}},Yu=function(dn,Rn){for(var Pt in Rn)if(typeof Rn[Pt]===s&&Rn[Pt].length>0){for(var Gi=0;Gi<Rn[Pt].length;
36Gi++)if(Tn(Rn[Pt][Gi],dn))return Pt==="?"?i:Pt}else if(Tn(Rn[Pt],dn))return Pt==="?"?i:Pt;return dn},km={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Mm={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[p,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[p,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,p],[/opios[\/ ]+([\w\.]+)/i],[p,[l,M+" Mini"]],[/\bopr\/([\w\.]+)/i],[p,[l,M]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(weibo)__([\d\.]+)/i],[l,p],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[p,[l,"UC"+U]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[p,[l,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[p,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[p,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[p,[l,"IE"]],[/yabrowser\/([\w\.]+)/i],[p,[l,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+U],p],[/\bfocus\/([\w\.]+)/i],[p,[l,q+" Focus"]],[/\bopt\/([\w\.]+)/i],[p,[l,M+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[p,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[p,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[p,[l,M+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[p,[l,"MIUI "+U]],[/fxios\/([-\w\.]+)/i],[p,[l,q]],[/\bqihu|(qi?ho?o?|360)browser/i],[[l,"360 "+U]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1 "+U],p],[/(comodo_dragon)\/([\w\.]+)/i],[[l,/_/g," "],p],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[l,p],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,O],p],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[l,p],[/\bgsa\/([\w\.]+) .*safari\//i],[p,[l,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[p,[l,X+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,X+" WebView"],p],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[p,[l,"Android "+U]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,p],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[p,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[p,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[p,Yu,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[l,p],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],p],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[p,[l,q+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[l,p],[/(cobalt)\/([\w\.]+)/i],[l,[p,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[E,"amd64"]],[/(ia32(?=;))/i],[[E,yi]],[/((?:i[346]|x)86)[;\)]/i],[[E,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[E,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[E,"armhf"]],[/windows (ce|mobile); ppc;/i],[[E,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[E,/ower/,"",yi]],[/(sun4\w)[;\)]/i],[[E,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;
vendor: 7,019 bytes, line 36
36|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[E,yi]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[d,[u,F],[h,R]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[d,[u,F],[h,g]],[/\((ip(?:hone|od)[\w ]*);/i],[d,[u,y],[h,g]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[u,y],[h,R]],[/(macintosh);/i],[d,[u,y]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[u,J],[h,g]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[u,_e],[h,R]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[u,_e],[h,g]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[d,/_/g," "],[u,f],[h,g]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[u,f],[h,R]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[u,"OPPO"],[h,g]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[u,"Vivo"],[h,g]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[d,[u,"Realme"],[h,g]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[d,[u,We],[h,g]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[u,We],[h,R]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[u,me],[h,R]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[u,me],[h,g]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[u,"Lenovo"],[h,R]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[u,"Nokia"],[h,g]],[/(pixel c)\b/i],[d,[u,se],[h,R]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[u,se],[h,g]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[d,[u,V],[h,g]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[u,V],[h,R]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[u,"OnePlus"],[h,g]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[u,b],[h,R]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[u,b],[h,g]],[/(playbook);[-\w\),; ]+(rim)/i],[d,u,[h,R]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[u,k],[h,g]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[u,N],[h,R]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[u,N],[h,g]],[/(nexus 9)/i],[d,[u,"HTC"],[h,R]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[u,[d,/_/g," "],[h,g]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[u,"Acer"],[h,R]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[u,"Meizu"],[h,g]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[u,d,[h,g]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[u,d,[h,R]],[/(surface duo)/i],[d,[u,ke],[h,R]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[u,"Fairphone"],[h,g]],[/(u304aa)/i],[d,[u,"AT&T"],[h,g]],[/\bsie-(\w*)/i],[d,[u,"Siemens"],[h,g]],[/\b(rct\w+) b/i],[d,[u,"RCA"],[h,R]],[/\b(venue[\d ]{2,7}) b/i],[d,[u,"Dell"],[h,R]],[/\b(q(?:mv|ta)\w+) b/i],[d,[u,"Verizon"],[h,R]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[u,"Barnes & Noble"],[h,R]],[/\b(tm\d{3}\w+) b/i],[d,[u,"NuVision"],[h,R]],[/\b(k88) b/i],[d,[u,"ZTE"],[h,R]],[/\b(nx\d{3}j) b/i],[d,[u,"ZTE"],[h,g]],[/\b(gen\d{3}) b.+49h/i],[d,[u,"Swiss"],[h,g]],[/\b(zur\d{3}) b/i],[d,[u,"Swiss"],[h,R]],[/\b((zeki)?tb.*\b) b/i],[d,[u,"Zeki"],[h,R]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[u,"Dragon Touch"],d,[h,R]],[/\b(ns-?\w{0,9}) b/i],[d,[u,"Insignia"],[h,R]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[u,"NextBook"],[h,R]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[u,"Voice"],d,[h,g]],[/\b(lvtel\-)?(v1[12]) b/i],[[u,"LvTel"],d,[h,g]],[/\b(ph-1) /i],[d,[u,"Essential"],[h,g]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[u,"Envizen"],[h,R]],[/\b(trio[-\w\. ]+) b/i],[d,[u,"MachSpeed"],[h,R]],[/\btu_(1491) b/i],[d,[u,"Rotor"],[h,R]],[/(shield[\w ]+) b/i],[d,[u,"Nvidia"],[h,R]],[/(sprint) (\w+)/i],[u,d,[h,g]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[u,ke],[h,g]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[u,I],[h,R]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[u,I],[h,g]],[/smart-tv.+(samsung)/i],[u,[h,v]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[u,F],[h,v]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[u,me],[h,v]],[/(apple) ?tv/i],[u,[d,y+" TV"],[h,v]],[/crkey/i],[[d,X+"cast"],[u,se],[h,v]],[/droid.+aft(\w)( bui|\))/i],[d,[u,b],[h,v]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[u,J],[h,v]],[/(bravia[\w ]+)( bui|\))/i],[d,[u,V],[h,v]],[/(mitv-\w{5}) bui/i],[d,[u,f],[h,v]],[/Hbbtv.*(technisat) (.*);/i],[u,d,[h,v]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[u,Ss],[d,Ss],[h,v]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[h,v]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[u,d,[h,m]],[/droid.+; (shield) bui/i],[d,[u,"Nvidia"],[h,m]],[/(playstation [345portablevi]+)/i],[d,[u,V],[h,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[u,ke],[h,m]],[/((pebble))app/i],[u,d,[h,C]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[u,y],[h,C]],[/droid.+; (glass) \d/i],[d,[u,se],[h,C]],[/droid.+; (wt63?0{2,3})\)/i],[d,[u,I],[h,C]],[/(quest( 2| pro)?)/i],[d,[u,O],[h,C]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[u,[h,w]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[d,[h,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[h,R]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[h,R]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[h,g]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[u,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[p,[l,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[p,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i],[l,p],[/rv\
36:([\w\.]{1,9})\b.+(gecko)/i],[p,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,p],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[l,[p,Yu,km]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[l,"Windows"],[p,Yu,km]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[p,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,ne],[p,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[p,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,p],[/\(bb(10);/i],[p,[l,k]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[p,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[p,[l,q+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[p,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[p,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[p,[l,X+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,B],p],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[l,p],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],p],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix) ?([\w\.]*)/i],[l,p]]},Cr=function(dn,Rn){if(typeof dn===s&&(Rn=dn,dn=i),!(this instanceof Cr))return new Cr(dn,Rn).getResult();var Pt=typeof n!==o&&n.navigator?n.navigator:i,Gi=dn||(Pt&&Pt.userAgent?Pt.userAgent:""),Zo=Pt&&Pt.userAgentData?Pt.userAgentData:i,$t=Rn?function(ze,Ii){var da={};for(var yo in ze)Ii[yo]&&Ii[yo].length%2==0?da[yo]=Ii[yo].concat(ze[yo]):da[yo]=ze[yo];return da}(Mm,Rn):Mm;return this.getBrowser=function(){var ze={};return ze[l]=i,ze[p]=i,_c.call(ze,Gi,$t.browser),ze[c]=function(Ii){return typeof Ii===a?Ii.replace(/[^\d\.]/g,"").split(".")[0]:i}(ze[p]),Pt&&Pt.brave&&typeof Pt.brave.isBrave==r&&(ze[l]="Brave"),ze},this.getCPU=function(){var ze={};return ze[E]=i,_c.call(ze,Gi,$t.cpu),ze},this.getDevice=function(){var ze={};return ze[u]=i,ze[d]=i,ze[h]=i,_c.call(ze,Gi,$t.device),!ze[h]&&Zo&&Zo.mobile&&(ze[h]=g),ze[d]=="Macintosh"&&Pt&&typeof Pt.standalone!==o&&Pt.maxTouchPoints&&Pt.maxTouchPoints>2&&(ze[d]="iPad",ze[h]=R),ze},this.getEngine=function(){var ze={};return ze[l]=i,ze[p]=i,_c.call(ze,Gi,$t.engine),ze},this.getOS=function(){var ze={};return ze[l]=i,ze[p]=i,_c.call(ze,Gi,$t.os),!ze[l]&&Zo&&Zo.platform!="Unknown"&&(ze[l]=Zo.platform.replace(/chrome os/i,B).replace(/macos/i,ne)),ze},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return Gi},this.setUA=function(ze){return Gi=typeof ze===a&&ze.length>350?Ss(ze,350):ze,this},this.setUA(Gi),this};Cr.VERSION="0.7.34",Cr.BROWSER=Ge([l,p,c]),Cr.CPU=Ge([E]),Cr.DEVICE=Ge([d,u,h,m,g,v,R,C,w]),Cr.ENGINE=Cr.OS=Ge([l,p]),e.exports&&(t=e.exports=Cr),t.UAParser=Cr;var ca=typeof n!==o&&(n.jQuery||n.Zepto);if(ca&&!ca.ua){var mc=new Cr;ca.ua=mc.getResult(),ca.ua.get=function(){return mc.getUA()},ca.ua.set=function(dn){mc.setUA(dn);var Rn=mc.getResult();for(var Pt in Rn)ca.ua[Pt]=Rn[Pt]}}})(typeof window=="object"?window:Ae)})(ag,ag.exports);var _Y=re(ag.exports),xb=Sh.clear;st({global:!0,bind:!0,forced:be.clearImmediate!==xb},{clearImmediate:xb});
36var mY=typeof Bun=="function"&&Bun&&typeof Bun.version=="string",Fb=be,EY=sn,fY=Kt,gY=mY,SY=As,TY=gh,RY=Nc,vY=Fb.Function,AY=/MSIE .\./.test(SY)||gY&&function(){var e=Fb.Bun.version.split(".");return e.length<3||e[0]==0&&(e[1]<3||e[1]==3&&e[2]==0)}(),CY=st,Bb=be,Gb=Sh.set,yY=function(e,t){var n=1;return AY?function(i,r){var o=RY(arguments.length,1)>n,s=fY(i)?i:vY(i),a=o?TY(arguments,n):[],c=o?function(){EY(s,this,a)}:s;return e(c)}:e},jb=Bb.setImmediate?yY(Gb):Gb;CY({global:!0,bind:!0,forced:Bb.setImmediate!==jb},{setImmediate:jb});var Wb=re(cr.setImmediate),IY=st,bY=ny,wY=dr,OY=Nc,NY=yc,DY=be.process;IY({global:!0,dontCallGetSet:!0},{queueMicrotask:function(e){OY(arguments.length,1),wY(e);var t=NY&&DY.domain;bY(t?t.bind(e):e)}});var Kb=re(cr.queueMicrotask);function Hb(e,t){return function(){return e.apply(t,arguments)}}const{toString:PY}=Object.prototype,{getPrototypeOf:cg}=Object,{iterator:Hh,toStringTag:Yb}=Symbol,Yh=(dg=Object.create(null),e=>{const t=PY.call(e);return dg[t]||(dg[t]=t.slice(8,-1).toLowerCase())});var dg;const oo=e=>(e=e.toLowerCase(),t=>Yh(t)===e),Xh=e=>t=>typeof t===e,{isArray:Xc}=Array,Jc=Xh("undefined");function wl(e){return e!==null&&!Jc(e)&&e.constructor!==null&&!Jc(e.constructor)&&Xi(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Xb=oo("ArrayBuffer"),LY=Xh("string"),Xi=Xh("function"),Jb=Xh("number"),Ol=e=>e!==null&&typeof e=="object",Jh=e=>{if(Yh(e)!=="object")return!1;const t=cg(e);return!(t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Yb in e||Hh in e)},kY=oo("Date"),MY=oo("File"),UY=oo("Blob"),VY=oo("FileList"),zb=Ps!==void 0?Ps:typeof self<"u"?self:typeof window<"u"?window:typeof la<"u"?la:{},qb=zb.FormData!==void 0?zb.FormData:void 0,xY=oo("URLSearchParams"),[FY,BY,GY,jY]=["ReadableStream","Request","Response","Headers"].map(oo);function Nl(e,t){let n,i,{allOwnKeys:r=!1}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(e!=null)if(typeof e!="object"&&(e=[e]),Xc(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(wl(e))return;const o=r?Object.getOwnPropertyNames(e):Object.keys(e),s=o.length;let a;for(n=0;n<s;n++)a=o[n],t.call(null,e[a],a,e)}}function Zb(e,t){if(wl(e))return null;t=t.toLowerCase();const n=Object.keys(e);let i,r=n.length;for(;r-- >0;)if(i=n[r],t===i.toLowerCase())return i;return null}const Aa=Ps!==void 0?Ps:typeof self<"u"?self:typeof window<"u"?window:la,Qb=e=>!Jc(e)&&e!==Aa,WY=(lg=typeof Uint8Array<"u"&&cg(Uint8Array),e=>lg&&e instanceof lg);var lg;const KY=oo("HTMLFormElement"),$b=(e=>{let{hasOwnProperty:t}=e;return(n,i)=>t.call(n,i)})(Object.prototype),HY=oo("RegExp"),e0=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};Nl(n,(r,o)=>{let s;(s=t(r,o,e))!==!1&&(i[o]=s||r)}),Object.defineProperties(e,i)},YY=oo("AsyncFunction"),t0=(n0=typeof Wb=="function",i0=Xi(Aa.postMessage),n0?Wb:i0?(ug="axios@".concat(Math.random()),zh=[],Aa.addEventListener("message",e=>{let{source:t,data:n}=e;t===Aa&&n===ug&&zh.length&&zh.shift()()},!1),e=>{zh.push(e),Aa.postMessage(ug,"*")}):e=>setTimeout(e));var n0,i0,ug,zh;const XY=Kb!==void 0?Kb.bind(Aa):typeof process<"u"&&process.nextTick||t0;var Y={isArray:Xc,isArrayBuffer:Xb,isBuffer:wl,isFormData:e=>{let t;return e&&(qb&&e instanceof qb||Xi(e.append)&&((t=Yh(e))==="formdata"||t==="object"&&Xi(e.toString)&&e.toString()==="[object FormData]"))},isArrayBufferView:function(e){let t;return t=typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Xb(e.buffer),t},isString:LY,isNumber:Jb,isBoolean:e=>e===!0||e===!1,isObject:Ol,isPlainObject:Jh,isEmptyObject:e=>{if(!Ol(e)||wl(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},isReadableStream:FY,isRequest:BY,isResponse:GY,isHeaders:jY,isUndefined:Jc,isDate:kY,isFile:MY,isReactNativeBlob:e=>!(!e||e.uri===void 0),isReactNative:e=>e&&e.getParts!==void 0,isBlob:UY,isRegExp:HY,isFunction:Xi,isStream:e=>Ol(e)&&Xi(e.pipe),isURLSearchParams:xY,isTypedArray:WY,isFileList:VY,forEach:Nl,merge:function e(){const{caseless:t,skipUndefined:n}=Qb(this)&&this||{},i={},r=(o,s)=>{if(s==="__proto__"||s==="constructor"||s==="prototype")return;const a=t&&Zb(i,s)||s;Jh(i[a])&&Jh(o)?i[a]=e(i[a],o):Jh(o)?i[a]=e({},o):Xc(o)?i[a]=o.slice():n&&Jc(o)||(i[a]=o)};for(let o=0,s=arguments.length;o<s;o++)arguments[o]&&Nl(arguments[o],r);return i},extend:function(e,t,n){let{allOwnKeys:i}=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return Nl(t,(r,o)=>{n&&Xi(r)?Object.defineProperty(e,o,{value:Hb(r,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,o,{value:r,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:i}),e},trim:e=>Mn(e)?Mn(e).call(e):e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),inherits:(e,t,n,i)=>
36{e.prototype=Object.create(t.prototype,i),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,i)=>{let r,o,s;const a={};if(t=t||{},e==null)return t;do{for(r=Object.getOwnPropertyNames(e),o=r.length;o-- >0;)s=r[o],i&&!i(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=n!==!1&&cg(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:Yh,kindOfTest:oo,endsWith:(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const i=e.indexOf(t,n);return i!==-1&&i===n},toArray:e=>{if(!e)return null;if(Xc(e))return e;let t=e.length;if(!Jb(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[Hh]).call(e);let i;for(;(i=n.next())&&!i.done;){const r=i.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let n;const i=[];for(;(n=e.exec(t))!==null;)i.push(n);return i},isHTMLForm:KY,hasOwnProperty:$b,hasOwnProp:$b,reduceDescriptors:e0,freezeMethods:e=>{e0(e,(t,n)=>{if(Xi(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const i=e[n];Xi(i)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))})},toObjectSet:(e,t)=>{const n={},i=r=>{r.forEach(o=>{n[o]=!0})};return Xc(e)?i(e):i(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,i){return n.toUpperCase()+i}),noop:()=>{},toFiniteNumber:(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t,findKey:Zb,global:Aa,isContextDefined:Qb,isSpecCompliantForm:function(e){return!!(e&&Xi(e.append)&&e[Yb]==="FormData"&&e[Hh])},toJSONObject:e=>{const t=new Array(10),n=(i,r)=>{if(Ol(i)){if(t.indexOf(i)>=0)return;if(wl(i))return i;
36if(!("toJSON"in i)){t[r]=i;const o=Xc(i)?[]:{};return Nl(i,(s,a)=>{const c=n(s,r+1);!Jc(c)&&(o[a]=c)}),t[r]=void 0,o}}return i};return n(e,0)},isAsyncFn:YY,isThenable:e=>e&&(Ol(e)||Xi(e))&&Xi(e.then)&&Xi(e.catch),setImmediate:t0,asap:XY,isIterable:e=>e!=null&&Xi(e[Hh])};class Mi extends Error{static from(t,n,i,r,o,s){const a=new Mi(t.message,n||t.code,i,r,o);return a.cause=t,a.name=t.name,t.status!=null&&a.status==null&&(a.status=t.status),s&&Object.assign(a,s),a}constructor(t,n,i,r,o){super(t),Object.defineProperty(this,"message",{value:t,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,n&&(this.code=n),i&&(this.config=i),r&&(this.request=r),o&&(this.response=o,this.status=o.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:Y.toJSONObject(this.config),code:this.code,status:this.status}}}Mi.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",Mi.ERR_BAD_OPTION="ERR_BAD_OPTION",Mi.ECONNABORTED="ECONNABORTED",Mi.ETIMEDOUT="ETIMEDOUT",Mi.ERR_NETWORK="ERR_NETWORK",Mi.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",Mi.ERR_DEPRECATED="ERR_DEPRECATED",Mi.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",Mi.ERR_BAD_REQUEST="ERR_BAD_REQUEST",Mi.ERR_CANCELED="ERR_CANCELED",Mi.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",Mi.ERR_INVALID_URL="ERR_INVALID_URL";var Ot=Mi;function hg(e){return Y.isPlainObject(e)||Y.isArray(e)}function r0(e){return Y.endsWith(e,"[]")?e.slice(0,-2):e}function pg(e,t,n){return e?e.concat(t).map(function(i,r){return i=r0(i),!n&&r?"["+i+"]":i}).join(n?".":""):t}const JY=Y.toFlatObject(Y,{},null,function(e){return/^is[A-Z]/.test(e)});function qh(e,t,n){if(!Y.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(n=Y.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(u,p){return!Y.isUndefined(p[u])})).metaTokens,r=n.visitor||d,o=n.dots,s=n.indexes,a=(n.Blob||typeof Blob<"u"&&Blob)&&Y.isSpecCompliantForm(t);if(!Y.isFunction(r))throw new TypeError("visitor must be a function");function c(u){if(u===null)return"";if(Y.isDate(u))return u.toISOString();if(Y.isBoolean(u))return u.toString();if(!a&&Y.isBlob(u))throw new Ot("Blob is not supported. Use a Buffer instead.");return Y.isArrayBuffer(u)||Y.isTypedArray(u)?a&&typeof Blob=="function"?new Blob([u]):Buffer.from(u):u}function d(u,p,E){let m=u;if(Y.isReactNative(t)&&Y.isReactNativeBlob(u))return t.append(pg(E,p,o),c(u)),!1;if(u&&!E&&typeof u=="object"){if(Y.endsWith(p,"{}"))p=i?p:p.slice(0,-2),u=JSON.stringify(u);else if(Y.isArray(u)&&function(g){return Y.isArray(g)&&!g.some(hg)}(u)||(Y.isFileList(u)||Y.endsWith(p,"[]"))&&(m=Y.toArray(u)))return p=r0(p),m.forEach(function(g,R){!Y.isUndefined(g)&&g!==null&&t.append(s===!0?pg([p],R,o):s===null?p:p+"[]",c(g))}),!1}return!!hg(u)||(t.append(pg(E,p,o),c(u)),!1)}const l=[],h=Object.assign(JY,{defaultVisitor:d,convertValue:c,isVisitable:hg});if(!Y.isObject(e))throw new TypeError("data must be an object");return function u(p,E){if(!Y.isUndefined(p)){if(l.indexOf(p)!==-1)throw Error("Circular reference detected in "+E.join("."));l.push(p),Y.forEach(p,function(m,g){(!(Y.isUndefined(m)||m===null)&&r.call(t,m,Y.isString(g)?Mn(g).call(g):g,E,h))===!0&&u(m,E?E.concat(g):[g])}),l.pop()}}(e),t}function o0(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(n){return t[n]})}function _g(e,t){this._pairs=[],e&&qh(e,this,t)}const s0=_g.prototype;function zY(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function a0(e,t,n){if(!t)return e;const i=n&&n.encode||zY,r=Y.isFunction(n)?{serialize:n}:n,o=r&&r.serialize;let s;if(s=o?o(t,r):Y.isURLSearchParams(t)?t.toString():new _g(t,r).toString(i),s){const a=e.indexOf("#");a!==-1&&(e=e.slice(0,a)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}s0.append=function(e,t){this._pairs.push([e,t])},s0.toString=function(e){const t=e?function(n){return e.call(this,n,o0)}:o0;return this._pairs.map(function(n){return t(n[0])+"="+t(n[1])},"").join("&")};var c0=class{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Y.forEach(this.handlers,function(t){t!==null&&e(t)})}},mg={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},d0={exports:{}},qY=st,ZY=fe,l0=wr.f;qY({target:"Object",stat:!0,forced:Object.defineProperty!==l0,sham:!ZY},{defineProperty:l0});var u0=cr.Object,QY=d0.exports=function(e,t,n){return u0.defineProperty(e,t,n)};u0.defineProperty.sham&&(QY.sham=!0);
36var h0=re(d0.exports),$Y=TypeError,p0=cl,e6=fh,t6=Hi,n6=tn("species"),_0=Array,i6=function(e){var t;return p0(e)&&(t=e.constructor,(e6(t)&&(t===_0||p0(t.prototype))||t6(t)&&(t=t[n6])===null)&&(t=void 0)),t===void 0?_0:t},m0=function(e,t){return new(i6(e))(t===0?0:t)},r6=le,o6=pa,s6=tn("species"),E0=function(e){return o6>=51||!r6(function(){var t=[];return(t.constructor={})[s6]=function(){return{foo:1}},t[e](Boolean).foo!==1})},a6=st,c6=le,d6=cl,l6=Hi,u6=Io,h6=ts,f0=function(e){if(e>9007199254740991)throw $Y("Maximum allowed index exceeded");return e},g0=Ih,p6=m0,_6=E0,m6=pa,S0=tn("isConcatSpreadable"),E6=m6>=51||!c6(function(){var e=[];return e[S0]=!1,e.concat()[0]!==e}),f6=function(e){if(!l6(e))return!1;var t=e[S0];return t!==void 0?!!t:d6(e)};a6({target:"Array",proto:!0,forced:!E6||!_6("concat")},{concat:function(e){var t,n,i,r,o,s=u6(this),a=p6(s,0),c=0;for(t=-1,i=arguments.length;t<i;t++)if(f6(o=t===-1?s:arguments[t]))for(r=h6(o),f0(c+r),n=0;n<r;n++,c++)n in o&&g0(a,c,o[n]);else f0(c+1),g0(a,c++,o);return a.length=c,a}});var T0={},g6=wn,S6=vs,R0=ih.f,T6=lf,v0=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];T0.f=function(e){return v0&&g6(e)=="Window"?function(t){try{return R0(t)}catch{return T6(v0)}}(e):R0(S6(e))};var zc={},R6=tn;zc.f=R6;var A0=cr,v6=Wn,A6=zc,C6=wr.f,Un=function(e){var t=A0.Symbol||(A0.Symbol={});v6(t,e)||C6(t,e,{value:A6.f(e)})},y6=wt,I6=Di,b6=tn,w6=Is,C0=function(){var e=I6("Symbol"),t=e&&e.prototype,n=t&&t.valueOf,i=b6("toPrimitive");t&&!t[i]&&w6(t,i,function(r){return y6(n,this)},{})},O6=Cs,N6=qu,D6=Io,P6=ts,L6=m0,y0=et([].push),k6=function(e){var t=e==1,n=e==2,i=e==3,r=e==4,o=e==6,s=e==7,a=e==5||o;return function(c,d,l,h){for(var u,p,E=D6(c),m=N6(E),g=O6(d,l),R=P6(m),v=0,C=h||L6,w=t?C(c,R):n||s?C(c,0):void 0;R>v;v++)if((a||v in m)&&(p=g(u=m[v],v,E),e))if(t)w[v]=p;else if(p)switch(e){case 3:return!0;case 5:return u;case 6:return v;case 2:y0(w,u)}else switch(e){case 4:return!1;case 7:y0(w,u)}return o?-1:i||r?r:w}},I0={forEach:k6(0)},Zh=st,Eg=be,fg=wt,M6=et,qc=fe,Zc=Sc,U6=le,ni=Wn,V6=Ee,gg=Si,Qh=vs,Sg=Zu,x6=Yi,Tg=Ht,Dl=ll,b0=oh,F6=ih,w0=T0,B6=dl,O0=Ke,N0=wr,G6=pE,D0=oe,P0=Is,j6=Eh,Rg=Rc,L0=rh,k0=Ym,W6=tn,K6=zc,H6=Un,Y6=C0,X6=bs,M0=Ea,$h=I0.forEach,Ji=nh("hidden"),ep="Symbol",Pl="prototype",J6=M0.set,U0=M0.getterFor(ep),so=Object[Pl],Ca=Eg.Symbol,tp=Ca&&Ca[Pl],z6=Eg.TypeError,vg=Eg.QObject,V0=O0.f,ya=N0.f,x0=w0.f,q6=D0.f,F0=M6([].push),os=Rg("symbols"),Ll=Rg("op-symbol
36s"),Z6=Rg("wks"),Ag=!vg||!vg[Pl]||!vg[Pl].findChild,Cg=qc&&U6(function(){return Dl(ya({},"a",{get:function(){return ya(this,"a",{value:7}).a}})).a!=7})?function(e,t,n){var i=V0(so,t);i&&delete so[t],ya(e,t,n),i&&e!==so&&ya(so,t,i)}:ya,yg=function(e,t){var n=os[e]=Dl(tp);return J6(n,{type:ep,tag:e,description:t}),qc||(n.description=t),n},np=function(e,t,n){e===so&&np(Ll,t,n),gg(e);var i=Sg(t);return gg(n),ni(os,i)?(n.enumerable?(ni(e,Ji)&&e[Ji][i]&&(e[Ji][i]=!1),n=Dl(n,{enumerable:Tg(0,!1)})):(ni(e,Ji)||ya(e,Ji,Tg(1,{})),e[Ji][i]=!0),Cg(e,i,n)):ya(e,i,n)},Ig=function(e,t){gg(e);var n=Qh(t),i=b0(n).concat(W0(n));return $h(i,function(r){qc&&!fg(B0,n,r)||np(e,r,n[r])}),e},B0=function(e){var t=Sg(e),n=fg(q6,this,t);return!(this===so&&ni(os,t)&&!ni(Ll,t))&&(!(n||!ni(this,t)||!ni(os,t)||ni(this,Ji)&&this[Ji][t])||n)},G0=function(e,t){var n=Qh(e),i=Sg(t);if(n!==so||!ni(os,i)||ni(Ll,i)){var r=V0(n,i);return!r||!ni(os,i)||ni(n,Ji)&&n[Ji][i]||(r.enumerable=!0),r}},j0=function(e){var t=x0(Qh(e)),n=[];return $h(t,function(i){ni(os,i)||ni(L0,i)||F0(n,i)}),n},W0=function(e){var t=e===so,n=x0(t?Ll:Qh(e)),i=[];return $h(n,function(r){!ni(os,r)||t&&!ni(so,r)||F0(i,os[r])}),i};Zc||(Ca=function(){if(V6(tp,this))throw z6("Symbol is not a constructor");var e=arguments.length&&arguments[0]!==void 0?x6(arguments[0]):void 0,t=k0(e),n=function(i){this===so&&fg(n,Ll,i),ni(this,Ji)&&ni(this[Ji],t)&&(this[Ji][t]=!1),Cg(this,t,Tg(1,i))};return qc&&Ag&&Cg(so,t,{configurable:!0,set:n}),yg(t,e)},P0(tp=Ca[Pl],"toString",function(){return U0(this).tag}),P0(Ca,"withoutSetter",function(e){return yg(k0(e),e)}),D0.f=B0,N0.f=np,G6.f=Ig,O0.f=G0,F6.f=w0.f=j0,B6.f=W0,K6.f=function(e){return yg(W6(e),e)},qc&&j6(tp,"description",{configurable:!0,get:function(){return U0(this).description}})),Zh({global:!0,wrap:!0,forced:!Zc,sham:!Zc},{Symbol:Ca}),$h(b0(Z6),function(e){H6(e)}),Zh({target:ep,stat:!0,forced:!Zc},{useSetter:function(){Ag=!0},useSimple:function(){Ag=!1}}),Zh({target:"Object",stat:!0,forced:!Zc,sham:!qc},{create:function(e,t){return t===void 0?Dl(e):Ig(Dl(e),t)},defineProperty:np,defineProperties:Ig,getOwnPropertyDescriptor:G0}),Zh({target:"Object",stat:!0,forced:!Zc},{getOwnPropertyNames:j0}),Y6(),X6(Ca,ep),L0[Ji]=!0;var K0=Sc&&!!Symbol.for&&!!Symbol.keyFor,Q6=st,$6=Di,e8=Wn,t8=Yi,H0=Rc,n8=K0,bg=H0("string-to-symbol-registry"),i8=H0("symbol-to-string-registry");Q6({target:"Symbol",stat:!0,forced:!n8},{for:function(e){var t=t8(e);if(e8(bg,t))return bg[t];var n=$6("Symbol")(t);return bg[t]=n,i8[n]=t,n}});var r8=st,o8=Wn,s8=ol,a8=Tc,c8=K0,Y0=Rc("symbol-to-string-registry");r8({target:"Symbol",stat:!0,forced:!c8},{keyFor:function(e){if(!s8(e))throw TypeError(a8(e)+" is not a symbol");if(o8(Y0,e))return Y0[e]}});var X0=cl,d8=Kt,J0=wn,l8=Yi,z0=et([].push),u8=st,q0=Di,Z0=sn,h8=wt,kl=et,Q0=le,$0=Kt,ew=ol,tw=gh,p8=function(e){if(d8(e))return e;if(X0(e)){for(var t=e.length,n=[],i=0;i<t;i++){var r=e[i];typeof r=="string"?z0(n,r):typeof r!="number"&&J0(r)!="Number"&&J0(r)!="String"||z0(n,l8(r))}var o=n.length,s=!0;return function(a,c){if(s)return s=!1,c;if(X0(this))return c;for(var d=0;d<o;d++)if(n[d]===a)return c}}},_8=Sc,m8=String,Ls=q0("JSON","stringify"),ip=kl(/./.exec),nw=kl("".charAt),E8=kl("".charCodeAt),f8=kl("".replace),g8=kl(1 .toString),S8=/[\uD800-\uDFFF]/g,iw=/^[\uD800-\uDBFF]$/,rw=/^[\uDC00-\uDFFF]$/,ow=!_8||Q0(function(){var e=q0("Symbol")();return Ls([e])!="[null]"||Ls({a:e})!="{}"||Ls(Object(e))!="{}"}),sw=Q0(function(){return Ls("\uDF06\uD834")!=='"\\udf06\\ud834"'||Ls("\uDEAD")!=='"\\udead"'}),T8=function(e,t){var n=tw(arguments),i=p8(t);if($0(i)||e!==void 0&&!ew(e))return n[1]=function(r,o){if($0(i)&&(o=h8(i,this,m8(r),o)),!ew(o))return o},Z0(Ls,null,n)},R8=function(e,t,n){var i=nw(n,t-1),r=nw(n,t+1);return ip(iw,e)&&!ip(rw,r)||ip(rw,e)&&!ip(iw,i)?"\\u"+g8(E8(e,0),16):e};Ls&&u8({target:"JSON",stat:!0,forced:ow||sw},{stringify:function(e,t,n){var i=tw(arguments),r=Z0(ow?T8:Ls,null,i);return sw&&typeof r=="string"?f8(r,S8,R8):r}});var aw=dl,v8=Io;st({target:"Object",stat:!0,forced:!Sc||le(function(){aw.f(1)})},{getOwnPropertySymbols:function(e){var t=aw.f;return t?t(v8(e)):[]}}),Un("asyncIterator"),Un("hasInstance"),Un("isConcatSpreadable"),Un("iterator"),Un("match"),Un("matchAll"),Un("replace"),Un("search"),Un("species"),Un("split");var A8=C0;Un("toPrimitive"),A8();var C8=Di,y8=bs;Un("toStringTag"),y8(C8("Symbol"),"Symbol"),Un("unscopables"),bs(be.JSON,"JSON",!0);var I8=cr.Symbol,b8=tn,w8=wr.f,cw=b8("metadata"),dw=Function.prototype;dw[cw]===void 0&&w8(dw,cw,{value:null}),Un("dispose"),Un("metadata");var O8=I8;Un("asyncDispose");var N8=et,wg=Di("Symbol"),D8=wg.keyFor,P8=N8(wg.prototype.valueOf),lw=wg.isRegisteredSymbol||function(e){try{return D8(P8(e))!==void 0}catch{return!1}};st({target:"Symbol",stat:!0},{isRegisteredSymbol:lw});for(var L8=Rc,uw=Di,k8=et,M8=ol,U8=tn,rp=uw("Symbol"),hw=rp.isWellKnownSymbol,pw=uw("Object","getOwnPropertyNames"),V8=k8(rp.prototype.valueOf),_w=L8("wks"),Og=0,mw=pw(rp),x8=mw.length;
36Og<x8;Og++)try{var Ew=mw[Og];M8(rp[Ew])&&U8(Ew)}catch{}var fw=function(e){if(hw&&hw(e))return!0;try{for(var t=V8(e),n=0,i=pw(_w),r=i.length;n<r;n++)if(_w[i[n]]==t)return!0}catch{}return!1};st({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:fw}),Un("matcher"),Un("observable"),st({target:"Symbol",stat:!0},{isRegistered:lw}),st({target:"Symbol",stat:!0,forced:!0},{isWellKnown:fw}),Un("metadataKey"),Un("patternMatch"),Un("replaceAll");var Qc=re(O8),gw=re(zc.f("iterator"));function Ml(e){return Ml=typeof Qc=="function"&&typeof gw=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Qc=="function"&&t.constructor===Qc&&t!==Qc.prototype?"symbol":typeof t},Ml(e)}var F8=re(zc.f("toPrimitive"));function B8(e){var t=function(n,i){if(Ml(n)!=="object"||n===null)return n;var r=n[F8];if(r!==void 0){var o=r.call(n,i);if(Ml(o)!=="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(i==="string"?String:Number)(n)}(e,"string");return Ml(t)==="symbol"?t:String(t)}function S(e,t,n){return(t=B8(t))in e?h0(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var Sw=re(vK),G8={isBrowser:!0,classes:{URLSearchParams:Sw!==void 0?Sw:_g,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]};const Ng=typeof window<"u"&&typeof document<"u",Dg=typeof navigator=="object"&&navigator||void 0,j8=Ng&&(!Dg||["ReactNative","NativeScript","NS"].indexOf(Dg.product)<0),W8=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",K8=Ng&&window.location.href||"http://localhost";function Tw(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Rw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Tw(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Tw(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}var Ti=Rw(Rw({},Object.freeze({__proto__:null,hasBrowserEnv:Ng,hasStandardBrowserEnv:j8,hasStandardBrowserWebWorkerEnv:W8,navigator:Dg,origin:K8})),G8);function vw(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function H8(e,t){return qh(e,new Ti.classes.URLSearchParams,function(n){for(var i=1;i<arguments.length;i++){var r=arguments[i]!=null?arguments[i]:{};i%2?vw(Object(r),!0).forEach(function(o){S(n,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(r)):vw(Object(r)).forEach(function(o){Object.defineProperty(n,o,Object.getOwnPropertyDescriptor(r,o))})}return n}({visitor:function(n,i,r,o){return Ti.isNode&&Y.isBuffer(n)?(this.append(i,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},t))}var Y8=sf.charAt,Aw=wt,X8=Si,J8=Kt,z8=wn,q8=/./.exec,Z8=TypeError,Q8=st,Cw=wt,yw=$n,$8=IE,op=wE,Iw=ha,bw=MA,Ul=Yi,e9=Si,t9=gc,n9=wn,i9=iE,ww=eg,r9=sl,o9=le,s9=LE,a9=function(e,t,n){return t+(n?Y8(e,t).length:1)},c9=function(e,t){var n=e.exec;if(J8(n)){var i=Aw(n,e,t);return i!==null&&X8(i),i}if(z8(e)==="RegExp")return Aw(q8,e,t);throw Z8("RegExp#exec called on incompatible receiver")},Ow=Ea,d9=tn("matchAll"),Nw="RegExp String",Dw=Nw+" Iterator",l9=Ow.set,u9=Ow.getterFor(Dw),h9=TypeError,Pg=yw("".indexOf),sp=yw("".matchAll),Lg=!!sp&&!o9(function(){sp("a",/./)}),p9=$8(function(e,t,n,i){l9(this,{type:Dw,regexp:e,string:t,global:n,unicode:i,done:!1})},Nw,function(){var e=u9(this);if(e.done)return op(void 0,!0);var t=e.regexp,n=e.string,i=c9(t,n);return i===null?(e.done=!0,op(void 0,!0)):e.global?(Ul(i[0])===""&&(t.lastIndex=a9(n,bw(t.lastIndex),e.unicode)),op(i,!1)):(e.done=!0,op(i,!1))}),Pw=function(e){var t,n,i,r=e9(this),o=Ul(e),s=s9(r,RegExp),a=Ul(ww(r));return t=new s(s===RegExp?r.source:r,a),n=!!~Pg(a,"g"),i=!!~Pg(a,"u"),t.lastIndex=bw(r.lastIndex),new p9(t,o,n,i)};Q8({target:"String",proto:!0,forced:Lg},{matchAll:function(e){var t,n,i,r,o=Iw(this);if(t9(e)){if(Lg)return sp(o,e)}else{if(i9(e)&&(t=Ul(Iw(ww(e))),!~Pg(t,"g")))throw h9("`.matchAll` does not allow non-global regexes");if(Lg)return sp(o,e);if((i=r9(e,d9))===void 0&&n9(e)=="RegExp"&&(i=Pw),i)return Cw(i,e,o)}return n=Ul(o),r=new RegExp(e,"g"),Cw(Pw,r,n)}});var _9=lr("String").matchAll,m9=Ee,E9=_9,kg=String.prototype,f9=function(e){var t=e.matchAll;return typeof e=="string"||e===kg||m9(kg,e)&&t===kg.matchAll?E9:t},g9=re(f9);function Lw(e){function t(n,i,r,o){let s=n[o++];if(s==="__proto__")return!0;const a=Number.isFinite(+s),c=o>=n.length;return s=!s&&Y.isArray(r)?r.length:s,c?(Y.hasOwnProp(r,s)?r[s]=[r[s],i]:r[s]=i,!a):(r[s]&&Y.isObject(r[s])||(r[s]=[]),t(n,i,r[s],o)&&Y.isArray(r[s])&&(r[s]=function(d){const l={},h=Object.keys(d);let u;const p=h.length;let E;for(u=0;
36u<p;u++)E=h[u],l[E]=d[E];return l}(r[s])),!a)}if(Y.isFormData(e)&&Y.isFunction(e.entries)){const n={};return Y.forEachEntry(e,(i,r)=>{t(function(o){return g9(Y).call(Y,/\w+|\[(\w*)]/g,o).map(s=>s[0]==="[]"?"":s[1]||s[0])}(i),r,n,0)}),n}return null}const Mg={transitional:mg,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=Y.isObject(e);if(r&&Y.isHTMLForm(e)&&(e=new FormData(e)),Y.isFormData(e))return i?JSON.stringify(Lw(e)):e;if(Y.isArrayBuffer(e)||Y.isBuffer(e)||Y.isStream(e)||Y.isFile(e)||Y.isBlob(e)||Y.isReadableStream(e))return e;if(Y.isArrayBufferView(e))return e.buffer;if(Y.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(r){if(n.indexOf("application/x-www-form-urlencoded")>-1)return H8(e,this.formSerializer).toString();if((o=Y.isFileList(e))||n.indexOf("multipart/form-data")>-1){const s=this.env&&this.env.FormData;return qh(o?{"files[]":e}:e,s&&new s,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),function(s,a,c){if(Y.isString(s))try{return(a||JSON.parse)(s),Mn(Y).call(Y,s)}catch(d){if(d.name!=="SyntaxError")throw d}return(c||JSON.stringify)(s)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Mg.transitional,n=t&&t.forcedJSONParsing,i=this.responseType==="json";if(Y.isResponse(e)||Y.isReadableStream(e))return e;if(e&&Y.isString(e)&&(n&&!this.responseType||i)){const r=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e,this.parseReviver)}catch(o){if(r)throw o.name==="SyntaxError"?Ot.from(o,Ot.ERR_BAD_RESPONSE,this,null,this.response):o}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Ti.classes.FormData,Blob:Ti.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Y.forEach(["delete","get","head","post","put","patch"],e=>{Mg.headers[e]={}});var Ug=Mg;const S9=Y.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),kw=Symbol("internals");function Vl(e){var t;return e&&Mn(t=String(e)).call(t).toLowerCase()}function ap(e){return e===!1||e==null?e:Y.isArray(e)?e.map(ap):String(e)}function Vg(e,t,n,i,r){return Y.isFunction(i)?i.call(this,t,n):(r&&(t=n),Y.isString(t)?Y.isString(i)?t.indexOf(i)!==-1:Y.isRegExp(i)?i.test(t):void 0:void 0)}class cp{constructor(t){t&&this.set(t)}set(t,n,i){const r=this;function o(c,d,l){const h=Vl(d);if(!h)throw new Error("header name must be a non-empty string");const u=Y.findKey(r,h);(!u||r[u]===void 0||l===!0||l===void 0&&r[u]!==!1)&&(r[u||d]=ap(c))}const s=(c,d)=>Y.forEach(c,(l,h)=>o(l,h,d));if(Y.isPlainObject(t)||t instanceof this.constructor)s(t,n);else if(Y.isString(t)&&(t=Mn(t).call(t))&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(Mn(a=t).call(a)))s((c=>{const d={};let l,h,u;return c&&c.split(` 37`).forEach(function(p){var E,m;u=p.indexOf(":"),l=Mn(E=p.substring(0,u)).call(E).toLowerCase(),h=Mn(m=p.substring(u+1)).call(m),!l||d[l]&&S9[l]||(l==="set-cookie"?d[l]?d[l].push(h):d[l]=[h]:d[l]=d[l]?d[l]+", "+h:h)}),d})(t),n);else if(Y.isObject(t)&&Y.isIterable(t)){let c,d,l={};for(const h of t){if(!Y.isArray(h))throw TypeError("Object iterator must return a key-value pair");l[d=h[0]]=(c=l[d])?Y.isArray(c)?[...c,h[1]]:[c,h[1]]:h[1]}s(l,n)}else t!=null&&o(n,t,i);var a;return this}get(t,n){if(t=Vl(t)){const i=Y.findKey(this,t);if(i){const r=this[i];if(!n)return r;if(n===!0)return function(o){const s=Object.create(null),a=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let c;for(;c=a.exec(o);)s[c[1]]=c[2];return s}(r);if(Y.isFunction(n))return n.call(this,r,i);if(Y.isRegExp(n))return n.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Vl(t)){const i=Y.findKey(this,t);return!(!i||this[i]===void 0||n&&!Vg(0,this[i],i,n))}return!1}delete(t,n){const i=this;let r=!1;function o(s){if(s=Vl(s)){const a=Y.findKey(i,s);!a||n&&!Vg(0,i[a],a,n)||(delete i[a],r=!0)}}return Y.isArray(t)?t.forEach(o):o(t),r}clear(t){const n=Object.keys(this);let i=n.length,r=!1;for(;i--;){const o=n[i];t&&!Vg(0,this[o],o,t,!0)||(delete this[o],r=!0)}return r}normalize(t){const n=this,i={};return Y.forEach(this,(r,o)=>{var s;const a=Y.findKey(i,o);if(a)return n[a]=ap(r),void delete n[o];const c=t?function(d){return Mn(d).call(d).toLowerCase().replace(/([a-z\d])(\w*)/g,(l,h,u)=>h.toUpperCase()+u)}
37(o):Mn(s=String(o)).call(s);c!==o&&delete n[o],n[c]=ap(r),i[c]=!0}),this}concat(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return this.constructor.concat(this,...n)}toJSON(t){const n=Object.create(null);return Y.forEach(this,(i,r)=>{i!=null&&i!==!1&&(n[r]=t&&Y.isArray(i)?i.join(", "):i)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(t=>{let[n,i]=t;return n+": "+i}).join(` 38`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t){const n=new this(t);for(var i=arguments.length,r=new Array(i>1?i-1:0),o=1;o<i;o++)r[o-1]=arguments[o];return r.forEach(s=>n.set(s)),n}static accessor(t){const n=(this[kw]=this[kw]={accessors:{}}).accessors,i=this.prototype;function r(o){const s=Vl(o);n[s]||(function(a,c){const d=Y.toCamelCase(" "+c);["get","set","has"].forEach(l=>{Object.defineProperty(a,l+d,{value:function(h,u,p){return this[l].call(this,c,h,u,p)},configurable:!0})})}(i,o),n[s]=!0)}return Y.isArray(t)?t.forEach(r):r(t),this}}cp.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Y.reduceDescriptors(cp.prototype,(e,t)=>{let{value:n}=e,i=t[0].toUpperCase()+t.slice(1);return{get:()=>n,set(r){this[i]=r}}}),Y.freezeMethods(cp);var ao=cp;function xg(e,t){const n=this||Ug,i=t||n,r=ao.from(i.headers);let o=i.data;return Y.forEach(e,function(s){o=s.call(n,o,r.normalize(),t?t.status:void 0)}),r.normalize(),o}function Mw(e){return!(!e||!e.__CANCEL__)}var xl=class extends Ot{constructor(e,t,n){super(e??"canceled",Ot.ERR_CANCELED,t,n),this.name="CanceledError",this.__CANCEL__=!0}};function Uw(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new Ot("Request failed with status code "+n.status,[Ot.ERR_BAD_REQUEST,Ot.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n)):e(n)}const dp=function(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:3,i=0;const r=function(o,s){o=o||10;const a=new Array(o),c=new Array(o);let d,l=0,h=0;return s=s!==void 0?s:1e3,function(u){const p=Date.now(),E=c[h];d||(d=p),a[l]=u,c[l]=p;let m=h,g=0;for(;m!==l;)g+=a[m++],m%=o;if(l=(l+1)%o,l===h&&(h=(h+1)%o),p-d<s)return;const R=E&&p-E;return R?Math.round(1e3*g/R):void 0}}(50,250);return function(o,s){let a,c,d=0,l=1e3/s;const h=function(u){d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Date.now(),a=null,c&&(clearTimeout(c),c=null),o(...u)};return[function(){const u=Date.now(),p=u-d;for(var E=arguments.length,m=new Array(E),g=0;g<E;g++)m[g]=arguments[g];p>=l?h(m,u):(a=m,c||(c=setTimeout(()=>{c=null,h(a)},l-p)))},()=>a&&h(a)]}(o=>{const s=o.loaded,a=o.lengthComputable?o.total:void 0,c=s-i,d=r(c);i=s,e({loaded:s,total:a,progress:a?s/a:void 0,bytes:c,rate:d||void 0,estimated:d&&a&&s<=a?(a-s)/d:void 0,event:o,lengthComputable:a!=null,[t?"download":"upload"]:!0})},n)},Vw=(e,t)=>{const n=e!=null;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},xw=e=>function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return Y.asap(()=>e(...n))};var T9=Ti.hasStandardBrowserEnv?((e,t)=>n=>(n=new xh(n,Ti.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new xh(Ti.origin),Ti.navigator&&/(msie|trident)/i.test(Ti.navigator.userAgent)):()=>!0,R9=Ti.hasStandardBrowserEnv?{write(e,t,n,i,r,o,s){if(typeof document>"u")return;const a=["".concat(e,"=").concat(encodeURIComponent(t))];Y.isNumber(n)&&a.push("expires=".concat(new Date(n).toUTCString())),Y.isString(i)&&a.push("path=".concat(i)),Y.isString(r)&&a.push("domain=".concat(r)),o===!0&&a.push("secure"),Y.isString(s)&&a.push("SameSite=".concat(s)),document.cookie=a.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};function Fw(e,t,n){let i=!function(r){return typeof r=="string"&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}(t);return e&&(i||n==0)?function(r,o){return o?r.replace(/\/?\/$/,"")+"/"+o.replace(/^\/+/,""):r}(e,t):t}function Bw(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Fg(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
38t%2?Bw(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Bw(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}const Gw=e=>e instanceof ao?Fg({},e):e;function Ia(e,t){t=t||{};const n={};function i(d,l,h,u){return Y.isPlainObject(d)&&Y.isPlainObject(l)?Y.merge.call({caseless:u},d,l):Y.isPlainObject(l)?Y.merge({},l):Y.isArray(l)?l.slice():l}function r(d,l,h,u){return Y.isUndefined(l)?Y.isUndefined(d)?void 0:i(void 0,d,0,u):i(d,l,0,u)}function o(d,l){if(!Y.isUndefined(l))return i(void 0,l)}function s(d,l){return Y.isUndefined(l)?Y.isUndefined(d)?void 0:i(void 0,d):i(void 0,l)}function a(d,l,h){return h in t?i(d,l):h in e?i(void 0,d):void 0}const c={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(d,l,h)=>r(Gw(d),Gw(l),0,!0)};return Y.forEach(Object.keys(Fg(Fg({},e),t)),function(d){if(d==="__proto__"||d==="constructor"||d==="prototype")return;const l=Y.hasOwnProp(c,d)?c[d]:r,h=l(e[d],t[d],d);Y.isUndefined(h)&&l!==a||(n[d]=h)}),n}var jw=e=>{const t=Ia({},e);let{data:n,withXSRFToken:i,xsrfHeaderName:r,xsrfCookieName:o,headers:s,auth:a}=t;if(t.headers=s=ao.from(s),t.url=a0(Fw(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&s.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),Y.isFormData(n)){if(Ti.hasStandardBrowserEnv||Ti.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(Y.isFunction(n.getHeaders)){const c=n.getHeaders(),d=["content-type","content-length"];Object.entries(c).forEach(l=>{let[h,u]=l;x(d).call(d,h.toLowerCase())&&s.set(h,u)})}}if(Ti.hasStandardBrowserEnv&&(i&&Y.isFunction(i)&&(i=i(t)),i||i!==!1&&T9(t.url))){const c=r&&o&&R9.read(o);c&&s.set(r,c)}return t},v9=typeof XMLHttpRequest<"u"&&function(e){return new K(function(t,n){const i=jw(e);let r=i.data;const o=ao.from(i.headers).normalize();let s,a,c,d,l,{responseType:h,onUploadProgress:u,onDownloadProgress:p}=i;function E(){d&&d(),l&&l(),i.cancelToken&&i.cancelToken.unsubscribe(s),i.signal&&i.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function g(){if(!m)return;const v=ao.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());Uw(function(C){t(C),E()},function(C){n(C),E()},{data:h&&h!=="text"&&h!=="json"?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:v,config:e,request:m}),m=null}m.open(i.method.toUpperCase(),i.url,!0),m.timeout=i.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&m.readyState===4&&(m.status!==0||m.responseURL&&m.responseURL.indexOf("file:")===0)&&setTimeout(g)},m.onabort=function(){m&&(n(new Ot("Request aborted",Ot.ECONNABORTED,e,m)),m=null)},m.onerror=function(v){const C=v&&v.message?v.message:"Network Error",w=new Ot(C,Ot.ERR_NETWORK,e,m);w.event=v||null,n(w),m=null},m.ontimeout=function(){let v=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const C=i.transitional||mg;i.timeoutErrorMessage&&(v=i.timeoutErrorMessage),n(new Ot(v,C.clarifyTimeoutError?Ot.ETIMEDOUT:Ot.ECONNABORTED,e,m)),m=null},r===void 0&&o.setContentType(null),"setRequestHeader"in m&&Y.forEach(o.toJSON(),function(v,C){m.setRequestHeader(C,v)}),Y.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),h&&h!=="json"&&(m.responseType=i.responseType),p&&([c,l]=dp(p,!0),m.addEventListener("progress",c)),u&&m.upload&&([a,d]=dp(u),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",d)),(i.cancelToken||i.signal)&&(s=v=>{m&&(n(!v||v.type?new xl(null,e,m):v),m.abort(),m=null)},i.cancelToken&&i.cancelToken.subscribe(s),i.signal&&(i.signal.aborted?s():i.signal.addEventListener("abort",s)));const R=function(v){const C=/^([-+\w]{1,25})(:?\/\/|:)/.exec(v);return C&&C[1]||""}(i.url);R&&Ti.protocols.indexOf(R)===-1?n(new Ot("Unsupported protocol "+R+":",Ot.ERR_BAD_REQUEST,e)):m.send(r||null)})},A9=(e,t)=>
38{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let i,r=new AbortController;const o=function(d){if(!i){i=!0,a();const l=d instanceof Error?d:this.reason;r.abort(l instanceof Ot?l:new xl(l instanceof Error?l.message:l))}};let s=t&&setTimeout(()=>{s=null,o(new Ot("timeout of ".concat(t,"ms exceeded"),Ot.ETIMEDOUT))},t);const a=()=>{e&&(s&&clearTimeout(s),s=null,e.forEach(d=>{d.unsubscribe?d.unsubscribe(o):d.removeEventListener("abort",o)}),e=null)};e.forEach(d=>d.addEventListener("abort",o));const{signal:c}=r;return c.unsubscribe=()=>Y.asap(a),c}},C9=ky,y9=wo;st({target:"Promise",stat:!0,forced:!0},{withResolvers:function(){var e=y9.f(this);return{promise:e.promise,resolve:e.resolve,reject:e.reject}}});var I9=wo,b9=Pc;st({target:"Promise",stat:!0,forced:!0},{try:function(e){var t=I9.f(this),n=b9(e);return(n.error?t.reject:t.resolve)(n.value),t.promise}});var Bg=re(C9),Ww=zc.f("asyncIterator"),w9=re(Ww);function Gg(e,t){this.v=e,this.k=t}function Fl(e){var t,n;function i(o,s){try{var a=e[o](s),c=a.value,d=c instanceof Gg;Bg.resolve(d?c.v:c).then(function(l){if(d){var h=o==="return"?"return":"next";if(!c.k||l.done)return i(h,l);l=e[h](l).value}r(a.done?"return":"normal",l)},function(l){i("throw",l)})}catch(l){r("throw",l)}}function r(o,s){switch(o){case"return":t.resolve({value:s,done:!0});break;case"throw":t.reject(s);break;default:t.resolve({value:s,done:!1})}(t=t.next)?i(t.key,t.arg):n=null}this._invoke=function(o,s){return new Bg(function(a,c){var d={key:o,arg:s,resolve:a,reject:c,next:null};n?n=n.next=d:(t=n=d,i(o,s))})},typeof e.return!="function"&&(this.return=void 0)}function di(e){return function(){return new Fl(e.apply(this,arguments))}}function ve(e){return new Gg(e,0)}function $c(e){var t={},n=!1;function i(r,o){return n=!0,{done:!1,value:new Gg(o=new Bg(function(s){s(e[r](o))}),1)}}return t[Qc!==void 0&&gw||"@@iterator"]=function(){return this},t.next=function(r){return n?(n=!1,r):i("next",r)},typeof e.throw=="function"&&(t.throw=function(r){if(n)throw n=!1,r;return i("throw",r)}),typeof e.return=="function"&&(t.return=function(r){return n?(n=!1,r):i("return",r)}),t}Fl.prototype[typeof Qc=="function"&&w9||"@@asyncIterator"]=function(){return this},Fl.prototype.next=function(e){return this._invoke("next",e)},Fl.prototype.throw=function(e){return this._invoke("throw",e)},Fl.prototype.return=function(e){return this._invoke("return",e)};var lp=re(Ww);function jg(e){var t,n,i,r=2;for(typeof Symbol<"u"&&(n=lp,i=Symbol.iterator);r--;){if(n&&(t=e[n])!=null)return t.call(e);if(i&&(t=e[i])!=null)return new up(t.call(e));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}function up(e){function t(n){if(Object(n)!==n)return K.reject(new TypeError(n+" is not an object."));var i=n.done;return K.resolve(n.value).then(function(r){return{value:r,done:i}})}return up=function(n){this.s=n,this.n=n.next},up.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(n){var i=this.s.return;return i===void 0?K.resolve({value:n,done:!0}):t(i.apply(this.s,arguments))},throw:function(n){var i=this.s.return;return i===void 0?K.reject(n):t(i.apply(this.s,arguments))}},new up(e)}const O9=function*(e,t){let n=e.byteLength;if(!t||n<t)return void(yield e);let i,r=0;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},N9=function(){var e=di(function*(t,n){var i,r=!1,o=!1;try{for(var s,a=jg(D9(t));r=!(s=yield ve(a.next())).done;r=!1){const c=s.value;yield*$c(jg(O9(c,n)))}}catch(c){o=!0,i=c}finally{try{r&&a.return!=null&&(yield ve(a.return()))}finally{if(o)throw i}}});return function(t,n){return e.apply(this,arguments)}}(),D9=function(){var e=di(function*(t){if(t[lp])return void(yield*$c(jg(t)));const n=t.getReader();try{for(;;){const{done:i,value:r}=yield ve(n.read());if(i)break;yield r}}finally{yield ve(n.cancel())}});return function(t){return e.apply(this,arguments)}}(),Kw=(e,t,n,i)=>{const r=N9(e,t);let o,s=0,a=c=>{o||(o=!0,i&&i(c))};return new ReadableStream({async pull(c){try{const{done:d,value:l}=await r.next();if(d)return a(),void c.close();let h=l.byteLength;if(n){let u=s+=h;n(u)}c.enqueue(new Uint8Array(l))}catch(d){throw a(d),d}},cancel:c=>(a(c),r.return())},{highWaterMark:2})};function Hw(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Yw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
38t%2?Hw(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Hw(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}const{isFunction:hp}=Y,P9=(e=>{let{Request:t,Response:n}=e;return{Request:t,Response:n}})(Y.global),{ReadableStream:Xw,TextEncoder:Jw}=Y.global,zw=function(e){try{for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return!!e(...n)}catch{return!1}},L9=e=>{e=Y.merge.call({skipUndefined:!0},P9,e);const{fetch:t,Request:n,Response:i}=e,r=t?hp(t):typeof fetch=="function",o=hp(n),s=hp(i);if(!r)return!1;const a=r&&hp(Xw),c=r&&(typeof Jw=="function"?(d=new Jw,E=>d.encode(E)):async E=>new Uint8Array(await new n(E).arrayBuffer()));var d;const l=o&&a&&zw(()=>{let E=!1;const m=new n(Ti.origin,{body:new Xw,method:"POST",get duplex(){return E=!0,"half"}}).headers.has("Content-Type");return E&&!m}),h=s&&a&&zw(()=>Y.isReadableStream(new i("").body)),u={stream:h&&(E=>E.body)};r&&["text","arrayBuffer","blob","formData","stream"].forEach(E=>{!u[E]&&(u[E]=(m,g)=>{let R=m&&m[E];if(R)return R.call(m);throw new Ot("Response type '".concat(E,"' is not supported"),Ot.ERR_NOT_SUPPORT,g)})});const p=async(E,m)=>Y.toFiniteNumber(E.getContentLength())??(async R=>R==null?0:Y.isBlob(R)?R.size:Y.isSpecCompliantForm(R)?(await new n(Ti.origin,{method:"POST",body:R}).arrayBuffer()).byteLength:Y.isArrayBufferView(R)||Y.isArrayBuffer(R)?R.byteLength:(Y.isURLSearchParams(R)&&(R+=""),Y.isString(R)?(await c(R)).byteLength:void 0))(m);return async E=>{let{url:m,method:g,data:R,signal:v,cancelToken:C,timeout:w,onDownloadProgress:b,onUploadProgress:y,responseType:N,headers:k,withCredentials:U="same-origin",fetchOptions:X}=jw(E),q=t||fetch;N=N?(N+"").toLowerCase():"text";let se=A9([v,C&&C.toAbortSignal()],w),_e=null;const me=se&&se.unsubscribe&&(()=>{se.unsubscribe()});let ke;try{if(y&&l&&g!=="get"&&g!=="head"&&(ke=await p(k,R))!==0){let f,I=new n(m,{method:"POST",body:R,duplex:"half"});if(Y.isFormData(R)&&(f=I.headers.get("content-type"))&&k.setContentType(f),I.body){const[O,B]=Vw(ke,dp(xw(y)));R=Kw(I.body,65536,O,B)}}Y.isString(U)||(U=U?"include":"omit");const We=o&&"credentials"in n.prototype,M=Yw(Yw({},X),{},{signal:se,method:g.toUpperCase(),headers:k.normalize().toJSON(),body:R,duplex:"half",credentials:We?U:void 0});_e=o&&new n(m,M);let F=await(o?q(_e,X):q(m,M));const J=h&&(N==="stream"||N==="response");if(h&&(b||J&&me)){const f={};["status","statusText","headers"].forEach(ne=>{f[ne]=F[ne]});const I=Y.toFiniteNumber(F.headers.get("content-length")),[O,B]=b&&Vw(I,dp(xw(b),!0))||[];F=new i(Kw(F.body,65536,O,()=>{B&&B(),me&&me()}),f)}N=N||"text";let V=await u[Y.findKey(u,N)||"text"](F,E);return!J&&me&&me(),await new K((f,I)=>{Uw(f,I,{data:V,headers:ao.from(F.headers),status:F.status,statusText:F.statusText,config:E,request:_e})})}catch(We){throw me&&me(),We&&We.name==="TypeError"&&/Load failed|fetch/i.test(We.message)?Object.assign(new Ot("Network Error",Ot.ERR_NETWORK,E,_e,We&&We.response),{cause:We.cause||We}):Ot.from(We,We&&We.code,E,_e,We&&We.response)}}},k9=new Map,qw=e=>{let t=e&&e.env||{};const{fetch:n,Request:i,Response:r}=t,o=[i,r,n];let s,a,c=o.length,d=k9;for(;c--;)s=o[c],a=d.get(s),a===void 0&&d.set(s,a=c?new Map:L9(t)),d=a;return a};qw();const Wg={http:null,xhr:v9,fetch:{get:qw}};Y.forEach(Wg,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Zw=e=>"- ".concat(e),M9=e=>Y.isFunction(e)||e===null||e===!1;var Qw={getAdapter:function(e,t){e=Y.isArray(e)?e:[e];const{length:n}=e;let i,r;const o={};for(let s=0;s<n;s++){let a;if(i=e[s],r=i,!M9(i)&&(r=Wg[(a=String(i)).toLowerCase()],r===void 0))throw new Ot("Unknown adapter '".concat(a,"'"));if(r&&(Y.isFunction(r)||(r=r.get(t))))break;o[a||"#"+s]=r}if(!r){const s=Object.entries(o).map(c=>{let[d,l]=c;return"adapter ".concat(d," ")+(l===!1?"is not supported by the environment":"is not available in the build")});let a=n?s.length>1?`since : 39`+s.map(Zw).join(` 40`):" "+Zw(s[0]):"as no adapter specified";throw new Ot("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return r},adapters:Wg};function Kg(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new xl(null,e)}function $w(e){return Kg(e),e.headers=ao.from(e.headers),e.data=xg.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Qw.getAdapter(e.adapter||Ug.adapter,e)(e).then(function(t){return Kg(e),t.data=xg.call(e,e.transformResponse,t),t.headers=ao.from(t.headers),t},function(t){return Mw(t)||(Kg(e),t&&t.response&&(t.response.data=xg.call(e,e.transformResponse,t.response),t.response.headers=ao.from(t.response.headers))),K.reject(t)})}const eO="1.13.6",pp={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{pp[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const tO={};pp.transitional=function(e,t,n){function i(r,o){return"[Axios v"+eO+"] Transitional option '"+r+"'"+o+(n?". "+n:"")}return(r,o,s)=>{if(e===!1)throw new Ot(i(o," has been removed"+(t?" in "+t:"")),Ot.ERR_DEPRECATED);return t&&!tO[o]&&(tO[o]=!0,console.warn(i(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,o,s)}},pp.spelling=function(e){return(t,n)=>(console.warn("".concat(n," is likely a misspelling of ").concat(e)),!0)};var _p={assertOptions:function(e,t,n){if(typeof e!="object")throw new Ot("options must be an object",Ot.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let r=i.length;for(;r-- >0;){const o=i[r],s=t[o];if(s){const a=e[o],c=a===void 0||s(a,o,e);if(c!==!0)throw new Ot("option "+o+" must be "+c,Ot.ERR_BAD_OPTION_VALUE)}else if(n!==!0)throw new Ot("Unknown option "+o,Ot.ERR_BAD_OPTION)}},validators:pp};const Mr=_p.validators;let mp=class{constructor(e){this.defaults=e||{},this.interceptors={request:new c0,response:new c0}}async request(e,t){try{return await this._request(e,t)}catch(n){if(n instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const r=i.stack?i.stack.replace(/^.+\n/,""):"";try{n.stack?r&&!String(n.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(n.stack+=` 41`+r):n.stack=r}catch{}}throw n}}_request(e,t){typeof e=="string"?(t=t||{}).url=e:t=e||{},t=Ia(this.defaults,t);const{transitional:n,paramsSerializer:i,headers:r}=t;n!==void 0&&_p.assertOptions(n,{silentJSONParsing:Mr.transitional(Mr.boolean),forcedJSONParsing:Mr.transitional(Mr.boolean),clarifyTimeoutError:Mr.transitional(Mr.boolean),legacyInterceptorReqResOrdering:Mr.transitional(Mr.boolean)}
41,!1),i!=null&&(Y.isFunction(i)?t.paramsSerializer={serialize:i}:_p.assertOptions(i,{encode:Mr.function,serialize:Mr.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),_p.assertOptions(t,{baseUrl:Mr.spelling("baseURL"),withXsrfToken:Mr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=r&&Y.merge(r.common,r[t.method]);r&&Y.forEach(["delete","get","head","post","put","patch","common"],p=>{delete r[p]}),t.headers=ao.concat(o,r);const s=[];let a=!0;this.interceptors.request.forEach(function(p){if(typeof p.runWhen=="function"&&p.runWhen(t)===!1)return;a=a&&p.synchronous;const E=t.transitional||mg;E&&E.legacyInterceptorReqResOrdering?s.unshift(p.fulfilled,p.rejected):s.push(p.fulfilled,p.rejected)});const c=[];let d;this.interceptors.response.forEach(function(p){c.push(p.fulfilled,p.rejected)});let l,h=0;if(!a){const p=[$w.bind(this),void 0];for(p.unshift(...s),p.push(...c),l=p.length,d=K.resolve(t);h<l;)d=d.then(p[h++],p[h++]);return d}l=s.length;let u=t;for(;h<l;){const p=s[h++],E=s[h++];try{u=p(u)}catch(m){E.call(this,m);break}}try{d=$w.call(this,u)}catch(p){return K.reject(p)}for(h=0,l=c.length;h<l;)d=d.then(c[h++],c[h++]);return d}getUri(e){return a0(Fw((e=Ia(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};Y.forEach(["delete","get","head","options"],function(e){mp.prototype[e]=function(t,n){return this.request(Ia(n||{},{method:e,url:t,data:(n||{}).data}))}}),Y.forEach(["post","put","patch"],function(e){function t(n){return function(i,r,o){return this.request(Ia(o||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:i,data:r}))}}mp.prototype[e]=t(),mp.prototype[e+"Form"]=t(!0)});var Ep=mp;class Hg{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new K(function(r){n=r});const i=this;this.promise.then(r=>{if(!i._listeners)return;let o=i._listeners.length;for(;o-- >0;)i._listeners[o](r);i._listeners=null}),this.promise.then=r=>{let o;const s=new K(a=>{i.subscribe(a),o=a}).then(r);return s.cancel=function(){i.unsubscribe(o)},s},t(function(r,o,s){i.reason||(i.reason=new xl(r,o,s),n(i.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){this.reason?t(this.reason):this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=i=>{t.abort(i)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Hg(function(n){t=n}),cancel:t}}}var U9=Hg;const Yg={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,Parti
41alContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Yg).forEach(e=>{let[t,n]=e;Yg[n]=t});var V9=Yg;const Kn=function e(t){const n=new Ep(t),i=Hb(Ep.prototype.request,n);return Y.extend(i,Ep.prototype,n,{allOwnKeys:!0}),Y.extend(i,n,null,{allOwnKeys:!0}),i.create=function(r){return e(Ia(t,r))},i}(Ug);Kn.Axios=Ep,Kn.CanceledError=xl,Kn.CancelToken=U9,Kn.isCancel=Mw,Kn.VERSION=eO,Kn.toFormData=qh,Kn.AxiosError=Ot,Kn.Cancel=Kn.CanceledError,Kn.all=function(e){return K.all(e)},Kn.spread=function(e){return function(t){return e.apply(null,t)}},Kn.isAxiosError=function(e){return Y.isObject(e)&&e.isAxiosError===!0},Kn.mergeConfig=Ia,Kn.AxiosHeaders=ao,Kn.formToJSON=e=>Lw(Y.isHTMLForm(e)?new FormData(e):e),Kn.getAdapter=Qw.getAdapter,Kn.HttpStatusCode=V9,Kn.default=Kn;var li=Kn;const x9=()=>{};function Bl(){const e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:x9};return e.promise=new K((t,n)=>{e.resolve=i=>{e.isFinished||(e.isResolved=!0,e.isFinished=!0,t(i),e.value=i)},e.reject=i=>{e.isFinished||(e.isRejected=!0,e.isFinished=!0,n(i))}}),e}const fp=new Map,gp=new Map,Do=new Map;let pn=function(e){return e.WIN_10="Windows 10",e.WIN_81="Windows 8.1",e.WIN_8="Windows 8",e.WIN_7="Windows 7",e.WIN_VISTA="Windows Vista",e.WIN_SERVER_2003="Windows Server 2003",e.WIN_XP="Windows XP",e.WIN_2000="Windows 2000",e.ANDROID="Android",e.HARMONY_OS="HarmonyOS",e.OPEN_BSD="Open BSD",e.SUN_OS="Sun OS",e.LINUX="Linux",e.IOS="iOS",e.MAC_OS="Mac OS",e.CHROMIUM_OS="Chromium OS",e.QNX="QNX",e.UNIX="UNIX",e.BEOS="BeOS",e.OS_2="OS/2",e.SEARCH_BOT="Search Bot",e}({}),je=function(e){return e.CHROME="Chrome",e.SAFARI="Safari",e.EDGE="Edge",e.FIREFOX="Firefox",e.OPERA="OPR",e.QQ="QQBrowser",e.WECHAT="MicroMessenger",e}({});const nO=new _Y;let co=nO.getResult(),Xg=null;function Fe(e){if(!Xg){co=nO.getResult();const t=function(a){if(a.engine.name==="Blink"&&a.browser.name!=="WeChat")return je.CHROME;switch(a.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return je.CHROME;case"Safari":case"Mobile Safari":return je.SAFARI;case"Edge":return je.EDGE;case"Firefox":return je.FIREFOX;case"QQ":case"QQBrowser":return je.QQ;case"Opera":return je.OPERA;case"WeChat":return je.WECHAT;default:return a.browser.name||""}}(co),n=iO(co),i=function(a){return a.os.name==="Windows"?a.os.version?a.os.name+" "+a.os.version:a.os.name:a.os.name||""}(co),r=co.os.version,o=iO(co,!1),s=co.device.type;if(!(t&&n&&i&&r))return{name:t,version:n,os:i,osVersion:r,browserVersion:o,deviceType:s};Xg={name:t,version:n,os:i,osVersion:r,browserVersion:o,deviceType:s}}return Xg}function iO(e){let t,n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return t=e.engine.name==="Blink"?e.engine.version||"":e.browser.version||"",n?t.split(".")[0]:t}function Sp(){return Fe().os}function rO(){const e=Fe();return"".concat(e.os," ").concat(e.osVersion)}function Tp(){const e=Fe();return!!(co.engine.name==="WebKit"&&e.os===pn.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==je.SAFARI||Hn()&&e.name!==je.SAFARI)}function ss(){return Fe().name===je.CHROME}function vn(){return Fe().name===je.SAFARI}function Jg(){const e=Fe();if(e.name!==je.SAFARI||!e.browserVersion)return!1;const t=e.browserVersion.split(".");return Number(t[0])>15||Number(t[0])===15&&Number(t[1])>=4}function oO(){const e=Fe();if(e.name!==je.SAFARI||!e.browserVersion)return!1;const t=e.browserVersion.split(".");return Number(t[0])>18||Number(t[0])===18&&Number(t[1])>=4}function sO(){return Fe().name===je.EDGE}function Rt(){return Fe().name===je.FIREFOX}
41function Hn(){return Fe().os===pn.IOS}function Ur(e){const t=Fe();return!(t.name!==je.CHROME||!t.osVersion)&&Number(t.version)>=e}function aO(e){const t=Fe();return!(t.name!==je.CHROME||!t.osVersion)&&Number(t.version)<e}function Rp(e,t,n){const i=Fe();return!(i.name!==e||!i.osVersion)&&(n?Number(i.version)>=t&&Number(i.version)<=n:Number(i.version)===t)}function ks(e){const t=Fe();return!(t.name!==je.EDGE||!t.osVersion)&&Number(t.version)>=e}function vp(e){const t=Fe();return!(t.name!==je.FIREFOX||!t.osVersion)&&Number(t.version)>=e}function cO(e){const t=Fe();return!(t.name!==je.SAFARI||!t.osVersion)&&Number(t.version)>=e}function zg(e,t,n){const i=Fe();if(i.os!==pn.IOS||!i.osVersion)return!1;const r=i.osVersion.split(".");return n?t&&Number(r[0])===e&&Number(r[1])>t||Number(r[0])>e:t?Number(r[0])===e&&Number(r[1])>=t||Number(r[0])>e:Number(r[0])>=e}function dO(e,t,n){const i=Fe();if(i.os!==pn.IOS||!i.osVersion)return!1;const r=i.osVersion.split(".");return n?t&&Number(r[0])===e&&Number(r[1])<t||Number(r[0])<e:t?Number(r[0])===e&&Number(r[1])<=t||Number(r[0])<e:Number(r[0])<=e}function Ap(e,t,n){const i=Fe();if(i.name!==je.SAFARI||!i.osVersion||!i.browserVersion)return!1;const r=i.browserVersion.split(".");return n?t&&Number(r[0])===e&&Number(r[1])<t||Number(r[0])<e:t?Number(r[0])===e&&Number(r[1])<=t||Number(r[0])<e:Number(r[0])<=e}function ba(e){const t=Fe();return!(t.name!==je.OPERA||!t.osVersion)&&Number(t.version)>=e}function lO(){const e=Fe();if(e.os!==pn.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])<14||Number(t[0])===14&&Number(t[1])<=6}function ed(){const e=Fe();if(e.os!==pn.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])===15}function qg(){const e=Fe();if(e.os!==pn.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])===16}function uO(){const e=Fe();if(e.os!==pn.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])===15&&Number(t[1])>=1}function Vr(){return vn()&&navigator.maxTouchPoints>0}function hO(){return Fe().name===je.WECHAT}function pO(){return window.navigator.appVersion&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)!==null&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function _O(){const e=Sp();return function(){const{deviceType:t}=Fe();return t==="mobile"||t==="tablet"}()||e===pn.ANDROID||e===pn.IOS||e===pn.HARMONY_OS}function Po(){const e=Fe();return e.name!==je.EDGE&&e.name!==je.SAFARI&&!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function Gl(){return Sp()===pn.ANDROID}function jl(){const e=Fe();return Gl()&&(e.name===je.CHROME||e.name===je.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}function F9(){var e;return!!x(e=window.navigator.userAgent).call(e,"AgoraWebView")}function ge(e,t,n){return(t=function(i){var r=function(o,s){if(typeof o!="object"||!o)return o;var a=o[Symbol.toPrimitive];if(a!==void 0){var c=a.call(o,"string");if(typeof c!="object")return c;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(o)}(i);return typeof r=="symbol"?r:r+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function mO(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function j(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?mO(Object(n),!0).forEach(function(i){ge(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mO(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}let A=function(e){return e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",e.PB_ERROR="PB_ERROR",e.TIMEOUT="TIMEOUT",e.INVALID_PARAMS="INVALID_PARAMS",e.NOT_READABLE="NOT_READABLE",e.NOT_SUPPORTED="NOT_SUPPORTED",e.INVALID_OPERATION="INVALID_OPERATION",e.OPERATION_ABORTED="OPERATION_ABORTED",e.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",e.EXCHANGE_SDP_FAILED="EXCHANGE_SDP_FAILED",e.ADD_CANDIDATE_FAILED="ADD_CANDIDATE_FAILED",e.DATACHANNEL_FAILED="DATACHANNEL_FAILED",e.NETWORK_E
41RROR="NETWORK_ERROR",e.NETWORK_TIMEOUT="NETWORK_TIMEOUT",e.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR",e.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT",e.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED",e.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",e.ELECTRON_IS_NULL="ELECTRON_IS_NULL",e.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",e.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE",e.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL",e.MEDIA_OPTION_INVALID="MEDIA_OPTION_INVALID",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED",e.TRACK_IS_DISABLED="TRACK_IS_DISABLED",e.GET_VIDEO_ELEMENT_VISIBLE_ERROR="GET_VIDEO_ELEMENT_VISIBLE_ERROR",e.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",e.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",e.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR",e.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE",e.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID",e.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER",e.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER",e.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS",e.UID_CONFLICT="UID_CONFLICT",e.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR",e.UPDATE_TICKET_FAILED="UPDATE_TICKET_FAILED",e.TOKEN_EXPIRE="TOKEN_EXPIRE",e.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK",e.INVALID_TRACK="INVALID_TRACK",e.SENDER_NOT_FOUND="SENDER_NOT_FOUND",e.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED",e.SET_ANSWER_FAILED="SET_ANSWER_FAILED",e.ICE_FAILED="ICE_FAILED",e.PC_CLOSED="PC_CLOSED",e.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED",e.GET_LOCAL_CAPABILITIES_FAILED="GET_LOCAL_CAPABILITIES_FAILED",e.GET_LOCAL_CONNECTION_PARAMS_FAILED="GET_LOCAL_CONNECTION_PARAMS_FAILED",e.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",e.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE",e.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS",e.EXIST_DISABLED_VIDEO_TRACK="EXIST_DISABLED_VIDEO_TRACK",e.INVALID_REMOTE_USER="INVALID_REMOTE_USER",e.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED",e.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED",e.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH",e.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED",e.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR",e.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED",e.WS_ABORT="WS_ABORT",e.WS_DISCONNECT="WS_DISCONNECT",e.WS_ERR="WS_ERR",e.EXTERNAL_SIGNAL_ABORT="EXTERNAL_SIGNAL_ABORT",e.LIVE_STREAMING_TASK_CONFLICT="LIVE_STREAMING_TASK_CONFLICT",e.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT",e.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR",e.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED",e.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED",e.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR",e.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM",e.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT="LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT",e.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE",e.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST",e.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR",e.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR",e.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR",e.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC",e.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST",e.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST",e.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE",e.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE",e.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR",e.INVALID_PLUGIN="INVALID_PLUGIN",e.DISCONNECT_P2P="DISCONNECT_P2P",e.CONVERTING_IMAGEDATA_TO_BLOB_FAILED="CONVERTING_IMAGEDATA_TO_BLOB_FAILED",e.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED="CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED",e.INIT_DATACHANNEL_TIMEOUT="INIT_DATACHANNEL_TIMEOUT",e.CREATE_DATACHANNEL_ERROR="CREATE_DATACHANNEL_ERROR",e.DATACHANNEL_CONNECTION_TIMEOUT="DATACHANNEL_CONNECTION_TIMEOUT",e.PROHIBITED_OPERATION="PROHIBITED_OPERATION",e.IMAGE_MODERATION_UPLOAD_FAILED="IMAGE_MODERATION_UPLOAD_FAILED",e.P2P_MESSAGE_FAILED="P2P_MESSAGE_FAILED",e}({}
41),L=class extends Error{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",n=arguments.length>2?arguments[2]:void 0;super(t),ge(this,"code",void 0),ge(this,"message",void 0),ge(this,"data",void 0),ge(this,"name","AgoraRTCException"),this.code=e,this.message="AgoraRTCError ".concat(this.code,": ").concat(t),this.data=n}toString(){return this.data?"".concat(this.message,` 42data: `).concat(JSON.stringify(this.data)):this.message}print(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"error",t=arguments.length>1?arguments[1]:void 0;return e==="error"&&(t||console).error(this.toString()),e==="warning"&&(t||console).warn(this.toString()),this}throw(e){throw this.print("error",e),this}};function xr(e,t){if(typeof e!="boolean")throw new L(A.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function nn(e,t,n){if(!x(n).call(n,e))throw new L(A.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(n)))}function ut(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1e4;if(e<n||e>i||(!(arguments.length>4&&arguments[4]!==void 0)||arguments[4])&&!function(r){return typeof r=="number"&&r%1==0}(e))throw new L(A.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(n,", ").concat(i,"]. integer only"))}function Zg(e,t){if(typeof e!="number"){if(!(e.min||e.max||e.ideal||e.exact))throw new L(A.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));e.min!==void 0&&ut(e.min,"".concat(t,".min"),0,1/0),e.max!==void 0&&ut(e.max,"".concat(t,".max"),1,1/0),e.exact!==void 0&&ut(e.exact,"".concat(t,".exact"),1,1/0),e.ideal!==void 0&&ut(e.ideal,"".concat(t,".ideal"),1,1/0)}else ut(e,t,1,1/0)}function On(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:255,r=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4];if(e==null)throw new L(A.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!EO(e,n,i,r))throw new L(A.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(n,",").concat(i,"].").concat(r?" ASCII characters only.":""))}function Lo(e,t){if(!Array.isArray(e))throw new L(A.INVALID_PARAMS,"".concat(t," should be an array"))}function xt(e){return e==null}function EO(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:255,i=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3];return typeof e=="string"&&e.length<=n&&e.length>=t&&(!i||function(r){if(typeof r!="string")return!1;for(let o=0;o<r.length;o+=1){const s=r.charCodeAt(o);if(s<0||s>255)return!1}return!0}(e))}function fO(e,t,n){if("getBigUint64"in DataView.prototype)return e.getBigUint64(t,n);const i=e.getUint32(t,n),r=e.getUint32(t+4,n),o=0,s=+!n;return BigInt(i*s+r*o)<<BigInt(32)|BigInt(i*o+r*s)}function gO(e,t,n,i){if("setBigUint64"in DataView.prototype)return e.setBigUint64(t,n,i);const r=Number(n>>BigInt(32)),o=Number(n&BigInt(4294967295));e.setUint32(t,r,i),e.setUint32(t+4,o,i)}var Wl=function(e){return e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE",e}(Wl||{}),Qg=function(e){return e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT",e}(Qg||{});const SO=new class{constructor(){ge(this,"_clientSize",null),ge(this,"getClientWidth",()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth),ge(this,"getClientHeight",()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight),ge(this,"getStyle",e=>window.getComputedStyle(e,null)),ge(this,"checkCssVisibleProperty",e=>{var t;let n=!0;const i=this.getStyle(e),{display:r,visibility:o,opacity:s,filter:a}=i;return(r==="none"||x(t=["hidden","collapse"]).call(t,o)||Number(s)<.1)&&(n=!1),!!n&&(a&&a.split(" ").filter(c=>{var d;const l=c.split("(")[0];return x(d=["brightness","blur","opacity"]).call(d,l)}).map(c=>{const[d,l]=c.split(/\(|\)/);return[d,Number(l.match(/^[0-9\.]+/))]}
42).forEach(c=>{const[d,l]=c;switch(d){case"brightness":(l<.1||l>3)&&(n=!1);break;case"blur":l>3&&(n=!1);break;case"opacity":l<.1&&(n=!1)}}),n)}),ge(this,"checkPropertyUpToAllParentNodes",(e,t)=>{let n=!0,i=!0;const r=s=>t(s);let o=e;for(;o&&i;)r(o)||(n=!1,i=!1),o=o.parentElement,o||(i=!1);return n}),ge(this,"checkActualCssVisibleIncludeInherit",e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty)),ge(this,"getSizeAboutClient",e=>{const{width:t,height:n,left:i,right:r,top:o,bottom:s}=e.getBoundingClientRect(),a=this.getClientWidth(),c=this.getClientHeight();return{width:t,height:n,left:i,right:r,top:o,bottom:s,clientWidth:a,clientHeight:c,clientMin:Math.min(a,c)}}),ge(this,"checkActualSize",()=>{const{width:e,height:t,clientMin:n}=this._clientSize;return this.checkSizeIsVisible(e,t,n)}),ge(this,"elementFromPoint",(e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null),ge(this,"checkCoverForAPoint",(e,t,n)=>{const i=this.elementFromPoint(e,t);return i!==null&&i!==n}),ge(this,"getPointPositionList",()=>{const{width:e,height:t,left:n,top:i}=this._clientSize,r=e/6,o=t/6,s=[],a=10**6;for(let c=0;c<5;c++)for(let d=0;d<5;d++){const l=(n*a+(c===0?.1:c===4?(r*c*a-1e5)/a:r*c)*a)/a,h=(i*a+(d===0?.1:d===4?(o*d*a-1e5)/a:o*d)*a)/a;s.push({x:l,y:h})}return[...s]}),ge(this,"checkElementCover",e=>this.getPointPositionList().map(t=>this.checkCoverForAPoint(t.x,t.y,e)).filter(t=>!!t).length>6),ge(this,"checkSizeIsVisible",(e,t,n)=>(e>50||n/e<=10)&&(t>50||n/t<=10)),ge(this,"checkSizeOfPartInClient",()=>{const{left:e,right:t,top:n,bottom:i,clientHeight:r,clientWidth:o,clientMin:s}=this._clientSize;let a,c,d,l;if(e<0)a=0;else{if(!(e<o))return!1;a=e}if(t<0)return!1;if(c=t<o?t:o,n<0)d=0;else{if(!(n<r))return!1;d=n}if(i<0)return!1;l=i<r?i:r;const h=c-a,u=l-d;return this.checkSizeIsVisible(h,u,s)}),ge(this,"returnHiddenResult",e=>(this._clientSize=null,{visible:!1,reason:e})),ge(this,"checkOneElementVisible",e=>{if(e instanceof HTMLElement){if(this.checkElementIsMountedOnDom(e)){if(this.checkActualCssVisibleIncludeInherit(e)){if(this._clientSize=this.getSizeAboutClient(e),this.checkElementCover(e))return this.returnHiddenResult(Wl.COVERED);{const t=this.checkActualSize(),n=this.checkSizeOfPartInClient();return t&&!n?this.returnHiddenResult(Wl.POSITION):t?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(Wl.SIZE)}}return this.returnHiddenResult(Wl.STYLE)}return this.returnHiddenResult(Qg.UNMOUNTED)}return this.returnHiddenResult(Qg.INVALID_HTML_ELEMENT)}),ge(this,"checkElementIsMountedOnDom",e=>this.checkPropertyUpToAllParentNodes(e,t=>t.nodeName.toUpperCase()!=="HTML"?t.parentElement!==null:!!document.documentElement))}};function $g(e){return new TextEncoder().encode(e)}const TO=function(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n},eS=async e=>function(t,n){let i="";return new Uint8Array(t).forEach(r=>{i+=r.toString(n).padStart(2,"0")}),i}(await crypto.subtle.digest("SHA-256",$g(e)),16);let Nt=class{constructor(){ge(this,"_events",{}),ge(this,"addListener",this.on)}getListeners(e){return this._events[e]?this._events[e].map(t=>t.listener):[]}on(e,t){this._events[e]||(this._events[e]=[]);const n=this._events[e];this._indexOfListener(n,t)===-1&&n.push({listener:t,once:!1})}once(e,t){this._events[e]||(this._events[e]=[]);const n=this._events[e];this._indexOfListener(n,t)===-1&&n.push({listener:t,once:!0})}off(e,t){if(!this._events[e])return;const n=this._events[e],i=this._indexOfListener(n,t);i!==-1&&n.splice(i,1),this._events[e].length===0&&delete this._events[e]}removeAllListeners(e){e?delete this._events[e]:this._events={}}emit(e){this._events[e]||(this._events[e]=[]);const t=this._events[e].map(o=>o);for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];for(let o=0;o<t.length;o+=1){const s=t[o];s.once&&this.off(e,s.listener),s.listener.apply(this,i||[])}}safeEmit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];[...this._events[e]||[]].forEach(r=>{r.once&&this.off(e,r.listener);try{r.listener.apply(this,n)}catch(o){console.error("safeEmit event:".concat(e," error ").concat(o==null?void 0:o.toString()))}})}_indexOfListener(e,t){let n=e.length;for(;n--;)if(e[n].listener===t)return n;return-1}},Kl=null;function RO(){if(Kl)return Kl;if(window.electron)return Kl=window.electron;if(!window.require)return null;try{return Kl=window.require("electron"),Kl}catch{return null}}let vt=function(e){return e.CREATE_CLIENT="createClient",e.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",e.SET_AREA="setArea",e.PRELOAD="PRELOAD",e.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",e.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",e.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",e.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",e.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",e.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",e.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",e.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",e.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",e.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",e.START_PROXY_SERVER="Client.startProxyServer",e.STOP_PROXY_SERVER="Client.stopProxyServer",e.SET_PROXY_SERVER="Client.setProxyServer",e.SET_TURN_SERVER="Client.setTurnServer",e.SET_CLIENT_ROLE="Client.setClientRole",e.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",e.ENABLE_DUAL_STREAM="Client.enableDualStream",e.DISABLE_DUAL_STREAM="Client.disableDualStream",e.JOIN="Client.join",e.LEAVE="Client.leave",e.PUBLISH="Client.publish",e.UNPUBLISH="Client.unpublish",e.SUBSCRIBE="Client.subscribe",e.MASS_SUBSCRIBE="Client.massSubscribe",e.MASS_UNSUBSCRIBE="Client.massUnsubscribe",e.UNSUBSCRIBE="Client.unsubscribe",e.RENEW_TOKEN="Client.renewToken",e.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",e.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",e.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",e.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",e.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",e.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",e.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",e.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",e.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",e.START_LIVE_STREAMING="Client.startLiveStreaming",e.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",e.STOP_LIVE_STREAMING="Client.stopLiveStreaming",e.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",e.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",e.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",e.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",e.SET_CONFIG_DISTRIBUTE="_configDistribute",e.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",e.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",e.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",e.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",e.LOCAL_AUDIO_TRACK_SET_
42VOLUME="LocalAudioTrack.setVolume",e.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",e.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",e.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",e.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",e.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",e.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",e.LOCAL_VIDEO_SEND_SEI_DATA="LocalVideoTrack.sendSeiData",e.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",e.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration",e.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",e.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",e.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",e.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",e.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",e.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",e.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",e.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",e.STREAM_TYPE_CHANGE="streamTypeChange",e.CONNECTION_STATE_CHANGE="connectionStateChange",e.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage",e.IMAGE_MODERATION_UPLOAD="imageModerationUpload",e.REPUB_AFTER_PC_CONNECTED="repubAfterPCConnected",e.PRELOAD_MEDIA_FAILED="preloadMediaFailed",e.MISMATCH_DTLS_PARAMETERS="mismatchDtlsParameters",e.MISMATCH_ICE_PARAMETERS="mismatchIceParameters",e.VOS_FALLBACK_CN="vosFallbackCN",e.DATACHANNEL_FAILBACK="datachannelFailback",e}({}),ht=function(e){return e.TRACER="tracer",e}({});function vO(e){return ut(e.timeout,"config.timeout",0,1e5),ut(e.timeoutFactor,"config.timeoutFactor",0,100,!1),ut(e.maxRetryCount,"config.maxRetryConfig",0,1/0),ut(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}let B9=function(e){return e[e.AUDIENCE_LEVEL_LOW_LATENCY=1]="AUDIENCE_LEVEL_LOW_LATENCY",e[e.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]="AUDIENCE_LEVEL_ULTRA_LOW_LATENCY",e[e.AUDIENCE_LEVEL_SYNC_LATENCY=3]="AUDIENCE_LEVEL_SYNC_LATENCY",e}({}),Pe=function(e){return e.LEAVE="LEAVE",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.UID_BANNED="UID_BANNED",e.FALLBACK="FALLBACK",e.IP_BANNED="IP_BANNED",e.CHANNEL_BANNED="CHANNEL_BANNED",e.LICENSE_MISSING="LICENSE_MISSING",e.LICENSE_EXPIRED="LICENSE_EXPIRED",e.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",e.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",e.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",e.LICENSE_ILLEGAL="LICENSE_ILLEGAL",e.TOKEN_EXPIRE="TOKEN_EXPIRE",e.FALLBACK_TO_HLS="FALLBACK_TO_HLS",e.UID_CONFLICT="UID_CONFLICT",e}({});function wa(e){if(!Array.isArray(e)||e.length<1)return!1;try{e.forEach(t=>{if(!t.urls)throw Error()})}catch{return!1}return!0}function AO(e){return On(e.turnServerURL,"turnServerURL"),On(e.username,"username"),On(e.password,"password"),e.udpport&&ut(e.udpport,"udpport",1,99999,!0),e.forceturn&&xr(e.forceturn,"forceturn"),e.security&&xr(e.security,"security"),e.tcpport&&ut(e.tcpport,"tcpport",1,99999,!0),!0}let td=function(e){return e[e.AUTO_SIMULCAST_STREAM=-1]="AUTO_SIMULCAST_STREAM",e[e.DISABLE_SIMULCAST_STREM=0]="DISABLE_SIMULCAST_STREM",e[e.ENABLE_SIMULCAST_STREAM=1]="ENABLE_SIMULCAST_STREAM",e}({});function tS(e){return e.level!==void 0&&nn(e.level,"level",[1,2,3]),e.delay!==void 0&&ut(e.delay,"delay",0,3e3,!0),!0}let Ce=function(e){return e.PEERCONNECTION_STATE_CHANGE="peerconnection-state-change",e.AUDIO_METADATA="audio-metadata",e.AUDIO_PTS="audio-pts",e.CONNECTION_STATE_CHANGE="connection-state-change",e.MEDIA_RECONNECT_START="media-reconnect-start",e.MEDIA_RECONNECT_END="media-reconnect-end",e.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",e.USER_JOINED="user-joined",e.USER_LEAVED="user-left",e.USER_PUBLISHED="user-published",e.USER_UNPUBLISHED="user-unpublished",e.USER_INFO_UPDATED="user-info-updated",e.CLIENT_BANNED="client-banned",e.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",e.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",e.VOLUME_INDICATOR="volume-indicator",e.CRYPT_ERROR="crypt-error",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGED="stream-type-changed",e.STREAM_FALLBACK="stream-fallback",e.RECEIVE_METADATA="receive-metadata",e.STREAM_MESSAGE="stream-message",e.LIVE_STREAMING_ERROR="live-streaming-error",e.LIVE_STREAMING_WARNING="live-streaming-warning",e.EXCEPTION="exception",e.ERROR="error",e.P2P_LOST="p2p_lost",e.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",e.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",e.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",e.PUBLISHED_USER_LIST="published-user-list",e.USER_LIST="user-list",e.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",e.CONTENT_INSPECT_ERROR="content-inspect-error",e.CONTENT_INSPECT_RESULT="content-inspect-result",e.IMAGE_MODERATION_CONNECTION_STATE_CHANGE="image-moderation-connection-state-change",e.FALLBACK_TO_HLS="fallback-to-hls",e.FIRST_VIDEO_BUFFER_READY="first-video-buffer-ready",e.FIRST_VIDEO_PRE_RENDER="first-video-pre-render",e.AV1_DECODABLE_RESULT="av1-decodable-result",e}({}),nS=function(e){return e.CONFIG="config",e.VOSERROR="vos_error",e.AP_ERROR="ap_error",e}({}
42),Vn=function(e){return e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK",e.REGIONAL_DISTRIBUTION="REGIONAL_DISTRIBUTION",e}({}),Jn=function(e){return e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({}),Oa=function(e){return e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({});function Jt(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return e.getListeners(t).length===0?K.reject(new L(A.UNEXPECTED_ERROR,"can not emit promise")):new K((o,s)=>{e.emit(t,...i,o,s)})}function mt(e,t){if(e.getListeners(t).length===0)return K.resolve();for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return Jt(e,t,...i)}function Ui(e,t){if(e.getListeners(t).length===0)return null;for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return Na(e,t,...i)}function Na(e,t){let n=null,i=null;for(var r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];if(e.emit(t,...o,a=>{n=a},a=>{i=a}),i!==null)throw i;if(n===null)throw new L(A.UNEXPECTED_ERROR,"handler is not sync");return n}const At=new class extends Nt{set networkState(e){this.emit(Oa.NETWORK_STATE_CHANGE,e,this._networkState),e===Jn.ONLINE?this.emit(Oa.ONLINE):e===Jn.OFFLINE&&(this.onlineWaiter=new K(t=>{this.once(Oa.ONLINE,()=>{this.onlineWaiter=void 0,t(Jn.ONLINE)})}),this.emit(Oa.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}get isOnline(){return this._networkState===Jn.ONLINE}constructor(){super(),ge(this,"_moduleName","network-indicator"),ge(this,"_networkState",Jn.ONLINE),ge(this,"onlineWaiter",void 0),window.addEventListener("online",()=>{this.networkState=Jn.ONLINE}),window.addEventListener("offline",()=>{this.networkState=Jn.OFFLINE})}},ui=[];for(let e=0;e<256;++e)ui.push((e+256).toString(16).slice(1));const CO=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);let iS;const G9=new Uint8Array(16);function j9(){return CO?CO():function(n,i,r){var o,s,a,c;const d=(o=(s=(n=n||{}).random)!==null&&s!==void 0?s:(a=(c=n).rng)===null||a===void 0?void 0:a.call(c))!==null&&o!==void 0?o:function(){if(!iS){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");iS=crypto.getRandomValues.bind(crypto)}return iS(G9)}();if(d.length<16)throw new Error("Random bytes length must be >= 16");if(d[6]=15&d[6]|64,d[8]=63&d[8]|128,i){if((r=r||0)<0||r+16>i.length)throw new RangeError("UUID byte range ".concat(r,":").concat(r+15," is out of buffer bounds"));for(let l=0;l<16;++l)i[r+l]=d[l];return i}return function(l){let h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return(ui[l[h+0]]+ui[l[h+1]]+ui[l[h+2]]+ui[l[h+3]]+"-"+ui[l[h+4]]+ui[l[h+5]]+"-"+ui[l[h+6]]+ui[l[h+7]]+"-"+ui[l[h+8]]+ui[l[h+9]]+"-"+ui[l[h+10]]+ui[l[h+11]]+ui[l[h+12]]+ui[l[h+13]]+ui[l[h+14]]+ui[l[h+15]]).toLowerCase()}(d)}(e,t,void 0);var e,t}function Cp(e,t){const n=e.indexOf(t);n!==-1&&e.splice(n,1)}function nd(e){const t=[];return e.forEach(n=>{t.indexOf(n)===-1&&t.push(n)}),t}function yp(e){K!==void 0?K.resolve().then(e):setTimeout(e,0)}function Ct(e){return JSON.parse(JSON.stringify(e))}function Da(e){try{return Ct(e)}catch{return e}}const yO={};function Ms(e,t){yO[t]||(yO[t]=!0,e())}function Pa(e){const t=window.atob(e),n=new Uint8Array(new ArrayBuffer(t.length));for(let i=0;i<t.length;i+=1)n[i]=t.charCodeAt(i);return n}function Us(e){let t="";for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return window.btoa(t)}function IO(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=new TextEncoder().encode(e);if(n.length>t)n=n.slice(0,t);else if(n.length<t){const i=new Uint8Array(t);i.set(n),n=i}return n}function bO(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=ei(t).call(t,(s,a)=>s+a.length,0),r=new Uint8Array(new ArrayBuffer(i));let o=0;return t.forEach(s=>{r.set(s,o),o+=s.length}),r}function ko(e){return window.TextEncoder?new TextEncoder().encode(e).length:e.length}function wO(e){let t=0;return(/DingTalk/i.test(navigator.userAgent)||/AliApp/i.test(navigator.userAgent))&&e.realFormData&&(e=e.realFormData),e.forEach(n=>{t+=typeof n=="string"?ko(n):n.size}),t+138}function W9(e){const t=new L(A.TIMEOUT,"timeout");return new K((n,i)=>{window.setTimeout(()=>i(t),e)})}function ln(e){return new K(t=>{window.setTimeout(t,e)})}function Qe(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:7,t=arguments.length>1?arguments[1]:void 0;const n=Math.random().toString(16).substr(2,e).toLowerCase();return n.length===e?"".concat(t).concat(n):"".concat(t).concat(n)+Qe(e-n.length,"")}function La(){let e,t=!1;try{var n;e=pY(n=j9()).call(n,"-","")}catch{t=!0}return!t&&e&&e.length===32||(e=Qe(32,"")),e.toUpperCase()}const Hl=()=>{},OO=new class{constructor(){ge(this,"fnMap",new Map)}throttleByKey(e,t,n,i){for(var r=arguments.length,o=new Array(r>4?r-4:0),s=4;s<r;s++)o[s-4]=arguments[s];if(this.fnMap.has(t)){const a=this.fnMap.get(t);if(a.threshold!==n){a.fn(...a.args),clearTimeout(a.timer);const c=window.setTimeout(()=>{const d=this.fnMap.get(t);d&&d.fn(...d.args),this.fnMap.delete(t)},n);this.fnMap.set(t,{fn:e,threshold:n,timer:c,args:o,skipFn:i})}else a.skipFn&&a.skipFn(...a.args),this.fnMap.set(t,j(j({},a),{},{fn:e,args:o,skipFn:i}))}else{const a=window.setTimeout(()=>{const c=this.fnMap.get(t);c&&c.fn(...c.args),this.fnMap.delete(t)},n);this.fnMap.set(t,{fn:e,threshold:n,timer:a,args:o,skipFn:i})}}},NO=OO.throttleByKey.bind(OO);function DO(e){return typeof e=="object"&&e!==null&&!(e instanceof RegExp)}function rS(e,t){if(!DO(e)||!DO(t)||Array.isArray(e)&&!Array.isArray(t)||!Array.isArray(e)&&Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e)){const n=[...e];for(let i=0;i<t.length;i++)n[i]=rS(e[i],t[i]);return n}{const n=j({},e);for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(Object.prototype.hasOwnProperty.call(e,i)?n[i]=rS(e[i],t[i]):n[i]=t[i]);return n}}function PO(e,t){let n=[0];if(n=new Array(t).fill(0),e===0)return n;let i=0;for(;e>0&&(n[i]=255&e,e>>=8,i++,i!==t););return n}function id(e){return typeof e=="number"?e:e.exact||e.ideal||e.max||e.min||0}function oS(e,t){try{return typeof e=="object"&&typeof t=="object"&&JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function sS(e){return ei(e).call(e,(t,n)=>t+n,0)}function LO(e){const t="0123456789abcdef";function n(C){let w,b="";for(w=0;w<=3;w++)b+=t.charAt(C>>8*w+4&15)+t.charAt(C>>8*w&15);return b}function i(C,w){const b=(65535&C)+(65535&w);return(C>>16)+(w>>16)+(b>>16)<<16|65535&b}function r(C,w,b,y,N,k){return i(function(U,X){return U<<X|U>>>32-X}(i(i(w,C),i(y,k)),N),b)}function o(C,w,b,y,N,k,U){return r(w&b|~w&y,C,w,N,k,U)}function s(C,w,b,y,N,k,U){return r(w&y|b&~y,C,w,N,k,U)}function a(C,w,b,y,N,k,U){return r(w^b^y,C,w,N,k,U)}function c(C,w,b,y,N,k,U){return r(b^(w|~y),C,w,N,k,U)}const d=function(C){let w;const b=1+(C.length+8>>6),y=new Array(16*b);for(w=0;w<16*b;w++)y[w]=0;for(w=0;w<C.length;w++)y[w>>2]|=C.charCodeAt(w)<<w%4*8;return y[w>>2]|=128<<w%4*8,y[16*b-2]=8*C.length,y}(e);let l,h,u,p,E,m=1732584193,g=-271733879,R=-1732584194,v=271733878;for(l=0;l<d.length;l+=16)h=m,u=g,p=R,E=v,m=o(m,g,R,v,d[l+0],7,-680876936),v=o(v,m,g,R,d[l+1],12,-389564586),R=o(R,v,m,g,d[l+2],17,606105819),g=o(g,R,v,m,d[l+3],22,-1044525330),m=o(m,g,R,v,d[l+4],7,-176418897),v=o(v,m,g,R,d[l+5],12,1200080426),R=o(R,v,m,g,d[l+6],17,-1473231341),g=o(g,R,v,m,d[l+7],22,-45705983),m=o(m,g,R,v,d[l+8],7,1770035416),v=o(v,m,g,R,d[l+9],12,-1958414417),R=o(R,v,m,g,d[l+10],17,-42063),g=o(g,R,v,m,d[l+11],22,-1990404162),m=o(m,g,R,v,d[l+12],7,1804603682),v=o(v,m,g,R,d[l+13],12,-40341101),R=o(R,v,m,g,d[l+14],17,-1502002290),g=o(g,R,v,m,d[l+15],22,1236535329),m=s(m,g,R,v,d[l+1],5,-165796510),v=s(v,m,g,R,d[l+6],9,-1069501632),R=s(R,v,m,g,d[l+11],14,643717713),g=s(g,R,v,m,d[l+0],20,-373897302),m=s(m,g,R,v,d[l+5],5,-701558691),v=s(v,m,g,R,d[l+10],9,38016083),R=s(R,v,m,g,d[l+15],14,-660478335),g=s(g,R,v,m,d[l+4],20,-405537848),m=s(m,g,R,v,d[l+9],5,568446438),v=s(v,m,g,R,d[l+14],9,-1019803690),R=s(R,v,m,g,d[l+3],14,-187363961),g=s(g,R,v,m,d[l+8],20,1163531501),m=s(m,g,R,v,d[l+13],5,-1444681467),v=s(v,m,g,R,d[l+2],9,-51403784),R=s(R,v,m,g,d[l+7],14,1735328473),g=s(g,R,v,m,d[l+12],20,-1926607734),m=a(m,g,R,v,d[l+5],4,-378558),v=a(v,m,g,R,d[l+8],11,-2022574463),R=a(R,v,m,g,d[l+11],16,1839030562),g=a(g,R,v,m,d[l+14],23,-35309556),m=a(m,g,R,v,d[l+1],4,-1530992060),v=a(v,m,g,R,d[l+4],11,1272893353),R=a(R,v,m,g,d[l+7],16,-155497632),g=a(g,R,v,m,d[l+10],23,-1094730640),m=a(m,g,R,v,d[l+13],4,681279174),v=a(v,m,g,R,d[l+0],11,-358537222),R=a(R,v,m,g,d[l+3],16,-722521979),g=a(g,R,v,m,d[l+6],23,76029189),m=a(m,g,R,v,d[l+9],4,-640364487),v=a(v,m,g,R,d[l+12],11,-421815835),R=a(R,v,m,g,d[l+15],16,530742520),g=a(g,R,v,m,d[l+2],23,-995338651),m=c(m,g,R,v,d[l+0],6,-198630844),v=c(v,m,g,R,d[l+7],10,1126891415),R=c(R,v,m,g,d[l+14],15,-1416354905),g=c(g,R,v,m,d[l+5],21,-57434055),m=c(m,g,R,v,d[l+12],6,1700485571),v=c(v,m,g,R,d[l+3],10,-1894986606),R=c(R,v,m,g,d[l+10],15,-1051523),g=c(g,R,v,m,d[l+1],21,-2054922799),m=c(m,g,R,v,d[l+8],6,1873313359),v=c(v,m,g,R,d[l+15],10,-30611744),R=c(R,v,m,g,d[l+6],15,-1560198380),g=c(g,R,v,m,d[l+13],21,1309151649),m=c(m,g,R,v,d[l+4],6,-145523070),v=c(v,m,g,R,d[l+11],10,-1120210379),R=c(R,v,m,g,d[l+2],15,718787259),g=c(g,R,v,m,d[l+9],21,-343485551),m=i(m,h),g=i(g,u),R=i(R,p),v=i(v,E);return n(m)+n(g)+n(R)+n(v)}let K9=1,kO=console,An=class{static setLogger(e){kO=e}constructor(e,t){ge(this,"id",void 0),ge(this,"lockingPromise",K.resolve()),ge(this,"locks",0),ge(this,"name",""),ge(this,"lockId",void 0),this.lockId=K9++,e&&(this.name=e),t&&(this.id=t),this.logger("created")}logger(e,t){const n=(this.id?"[".concat(this.id,"]"):"")+"[lock-".concat(this.name,"-").concat(this.lockId,"]"),i=e==="created"?"is ".concat(e,"."):"is ".concat(e,", current queue ").concat(this.locks,". ").concat(t??"");kO.debug("".concat(n," ").concat(i))}setId(e){this.id=e}get isLocked(){return this.locks>0}lock(e){let t;this.locks+=1,this.logger("locked",e);const n=new K(r=>{t=()=>{this.locks-=1,this.logger("unlocked",e),r()}}),i=this.lockingPromise.then(()=>t);return this.lockingPromise=this.lockingPromise.then(()=>n),i}};function rd(e,t){return function(n,i,r){const o=r.value;if(typeof o!="function")throw new Error("Cannot use mutex on object property.");return r.value=async function(){const s=this[t];if(!s)throw new Error("mutex property key ".concat(t," doesn't exist on ").concat(e));const a=await s.lock("From ".concat(e,".").concat(i));try{for(var c=arguments.length,d=new Array(c),l=0;l<c;l++)d[l]=arguments[l];return await o.apply(this,d)}finally{a()}},r}}const Bt={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function Ip(e,t){const n=Math.floor(t.timeout*Math.pow(t.timeoutFactor,e));return Math.min(t.maxRetryTimeout,n)}function Fr(e,t,n,i){const r=Object.assign({},Bt,i);let o=r.timeout;const s=async()=>{await function(d){return new K(l=>{window.setTimeout(l,d)})}(o),o*=r.timeoutFactor,o=Math.min(r.maxRetryTimeout,o)};let a=!1;const c=new K(async(d,l)=>{t=t||(()=>!1),n=n||(()=>!0);for(let h=0;h<r.maxRetryCount;h+=1){if(a)return l(new L(A.OPERATION_ABORTED));try{const u=await e();if(!t(u,h)||h+1===r.maxRetryCount)return d(u);await s()}catch(u){if(!n(u,h)||h+1===r.maxRetryCount)return l(u);await s()}}});return c.cancel=()=>a=!0,c}let bp,aS=class{constructor(e){ge(this,"input",[]),ge(this,"size",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}mean(){var e;
42return this.input.length===0?0:ei(e=this.input).call(e,(t,n)=>t+n)/this.input.length}},wp=0,cS=0;function dS(e,t,n,i){return new K((r,o)=>{t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),wp+=ko(t.data)):n&&(t.data.size?wp+=t.data.size:t.data instanceof FormData?wp+=wO(t.data):wp+=ko(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,li.request(t).then(s=>{typeof s.data=="string"?cS+=ko(s.data):s.data instanceof ArrayBuffer||s.data instanceof Uint8Array?cS+=s.data.byteLength:cS+=ko(JSON.stringify(s.data)),r(s.data)}).catch(s=>{li.isCancel(s)?o(new L(A.OPERATION_ABORTED,"cancel token canceled")):s.code==="ECONNABORTED"?o(new L(A.NETWORK_TIMEOUT,s.message)):s.response?o(new L(A.NETWORK_RESPONSE_ERROR,s.response.status)):o(new L(A.NETWORK_ERROR,s.message))})})}async function H9(e,t){const n=new Blob([t.data],{type:"buffer"});return await dS(e,j(j({},t),{},{data:n,headers:{"Content-Type":"application/octet-stream"}}),!0)}const MO=()=>window.isSecureContext!==void 0;function Br(e){if(Array.isArray(e))return e.map(n=>n);if(!UO(e))return e;const t={};for(const n in e){const i=e[n];UO(i)||Array.isArray(i)?t[n]=Br(i):t[n]=i}return t}function UO(e){return!(typeof e!="object"||Array.isArray(e)||!e)}let lS=class{constructor(e){ge(this,"input",[]),ge(this,"size",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}diffMean(){return this.input.length===0?0:(this.input[this.input.length-1]-this.input[0])/this.input.length}};const Gr={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},Yl={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],transport:{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0},selectedCandidatePair:{id:"unknown",localCandidate:Gr,remoteCandidate:Gr},updateInterval:0},VO={firsCount:0,nacksCount:0,plisCount:0,framesDecodeCount:0,framesDecodeInterval:0,framesDecodeFreezeTime:0,decodeFrameRate:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,qpSumPerFrame:0,framesDroppedCount:0,outputFrameRate:0,packetsDiscarded:0,framesAssembledFromMultiplePackets:0,totalProcessingDelay:0,avgDecodeMs:0,avgFramesAssembledFromMultiplePacketsMs:0,avgProcessingDelayMs:0,avgInterFrameDelayMs:0,totalAssemblyTime:0},xO={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},FO={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},BO={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packetsDiscarded:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0,totalSamplesReceived:0,silentConcealedSamples:0,concealmentEvents:0,freezeMs80:0,freezeMs200:0,freezeSamples80:0,freezeSamples200:0};let uS=class{constructor(e,t){ge(this,"onFirstVideoReceived",void 0),ge(this,"onFirstVideoDecoded",void 0),ge(this,"onFirstAudioReceived",void 0),ge(this,"onFirstVideoDecodedTimeout",void 0),ge(this,"onFirstAudioDecoded",void 0),ge(this,"onSelectedLocalCandidateChanged",void 0),ge(this,"onSelectedRemoteCandidateChanged",void 0),ge(this,"videoIsReady",!1),ge(this,"videoIsReady2",{}),ge(this,"pc",void 0),ge(this,"options",void 0),ge(this,"intervalTimer",void 0),ge(this,"stats",Br(Yl)),ge(this,"isFirstVideoReceived",{}),ge(this,"isFirstVideoDecoded",{}),ge(this,"isFirstAudioReceived",{}),ge(this,"isFirstAudioDecoded",{}),ge(this,"isFirstVideoDecodedTimeout",{}),ge(this,"lossRateWindowStats",[]),this.pc=e,this.options=t,this.intervalTimer=window.setInterval(async()=>{this.updateStats()},this.options.updateInterval)}getStats(){return this.stats}getSelectedCandidatePair(){return new K(e=>{e({local:j({},Gr),remote:j({},Gr)})})}setVideoIsReady(e){this.videoIsReady=e}setVideoIsReady2(e,t){this.videoIsReady2[e]=t}getVideoIsReady(e){return this.videoIsReady2[e]||!1}setIsFirstAudioDecoded(e){}destroy(){window.clearInterval(this.intervalTimer),this.pc=void 0}calcLossRate(e){this.lossRateWindowStats.push(e),this.lossRateWindowStats.length>this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);const t=this.lossRateWindowStats.length,n=["videoSend","audioSen
42d","videoRecv","audioRecv"];let i=0,r=0,o=0,s=0;for(const a of n)e[a].forEach((c,d)=>{if(!this.lossRateWindowStats[t-1][a][d]||!this.lossRateWindowStats[0][a][d])return;const l=this.lossRateWindowStats[t-1][a][d].packets-this.lossRateWindowStats[0][a][d].packets,h=this.lossRateWindowStats[t-1][a][d].packetsLost-this.lossRateWindowStats[0][a][d].packetsLost;a==="videoSend"||a==="audioSend"?(i+=l,o+=h):(r+=l,s+=h),Number.isNaN(l)||Number.isNaN(l)?c.packetLostRate=0:c.packetLostRate=l<=0||h<=0?0:h/(l+h)});e.sendPacketLossRate=i<=0||o<=0?0:o/(i+o),e.recvPacketLossRate=r<=0||s<=0?0:s/(r+s)}},Y9=class extends uS{constructor(){super(...arguments),ge(this,"_stats",Yl),ge(this,"lastDecodeVideoReceiverStats",new Map)}async updateStats(){const e=await this._getStats(),t=this.statsResponsesToObjects(e);this._stats=Br(Yl);const n=t.filter(r=>r.type==="ssrc");this.processSSRCStats(n);const i=t.find(r=>r.type==="VideoBwe");i&&this.processBandwidthStats(i),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}processBandwidthStats(e){this._stats.bitrate={actualEncoded:Number(e.googActualEncBitrate),targetEncoded:Number(e.googTargetEncBitrate),retransmit:Number(e.googRetransmitBitrate),transmit:Number(e.googTransmitBitrate)},this._stats.sendBandwidth=Number(e.googAvailableSendBandwidth)}processSSRCStats(e){e.forEach(t=>{var n;const i=x(n=t.id).call(n,"send");switch("".concat(t.mediaType,"_").concat(i?"send":"recv")){case"video_send":{const r=Br(xO);r.codec=t.googCodecName,r.adaptionChangeReason="none",t.googCpuLimitedResolution&&(r.adaptionChangeReason="cpu"),t.googBandwidthLimitedResolution&&(r.adaptionChangeReason="bandwidth"),r.avgEncodeMs=Number(t.googAvgEncodeMs),r.inputFrame={width:Number(t.googFrameWidthInput)||Number(t.googFrameWidthSent),height:Number(t.googFrameHeightInput)||Number(t.googFrameHeightSent),frameRate:Number(t.googFrameRateInput)},r.sentFrame={width:Number(t.googFrameWidthSent),height:Number(t.googFrameHeightSent),frameRate:Number(t.googFrameRateInput)},r.firsCount=Number(t.googFirReceived),r.nacksCount=Number(t.googNacksReceived),r.plisCount=Number(t.googPlisReceived),r.frameCount=Number(t.framesEncoded),r.bytes=Number(t.bytesSent),r.packets=Number(t.packetsSent),r.packetsLost=Number(t.packetsLost),r.ssrc=Number(t.ssrc),r.rttMs=Number(t.googRtt||0),this._stats.videoSend.push(r),this._stats.rtt=r.rttMs;break}case"video_recv":{const r=Br(VO),o=this.lastDecodeVideoReceiverStats.get(Number(t.ssrc));if(r.codec=t.googCodecName,r.targetDelayMs=Number(t.googTargetDelayMs),r.renderDelayMs=Number(t.googRenderDelayMs),r.currentDelayMs=Number(t.googCurrentDelayMs),r.minPlayoutDelayMs=Number(t.googMinPlayoutDelayMs),r.decodeMs=Number(t.googDecodeMs),r.maxDecodeMs=Number(t.googMaxDecodeMs),r.receivedFrame={width:Number(t.googFrameWidthReceived),height:Number(t.googFrameHeightReceived),frameRate:Number(t.googFrameRateReceived)},r.decodedFrame={width:Number(t.googFrameWidthReceived),height:Number(t.googFrameHeightReceived),frameRate:Number(t.googFrameRateDecoded)},r.decodeFrameRate=Number(t.googFrameRateDecoded),r.outputFrame={width:Number(t.googFrameWidthReceived),height:Number(t.googFrameHeightReceived),frameRate:Number(t.googFrameRateOutput)},r.jitterBufferMs=Number(t.googJitterBufferMs),r.firsCount=Number(t.googFirsSent),r.nacksCount=Number(t.googNacksSent),r.plisCount=Number(t.googPlisSent),r.framesDecodeCount=Number(t.framesDecoded),r.bytes=Number(t.bytesReceived),r.packets=Number(t.packetsReceived),r.packetsLost=Number(t.packetsLost),r.ssrc=Number(t.ssrc),r.packets>0&&!this.isFirstVideoReceived[r.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(r.ssrc),this.isFirstVideoReceived[r.ssrc]=!0),r.framesDecodeCount>0&&!this.isFirstVideoDecoded[r.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(r.ssrc,r.decodedFrame.width,r.decodedFrame.height),this.isFirstVideoDecoded[r.ssrc]=!0),o){const s=o.stats,a=Date.now()-o.lts;r.framesDecodeFreezeTime=s.framesDecodeFreezeTime,r.framesDecodeInterval=s.framesDecodeInterval,r.framesDecodeCount>s.framesDecodeCount&&this.isFirstVideoDecoded[r.ssrc]?(o.lts=Date.now(),r.framesDecodeInterval=a,r.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(t.ssrc,10))?r.framesDecodeFreezeTime+=r.framesDecodeInterval:this.setVideoIsReady2(parseInt(t.ssrc,10),!0))):r.framesDecodeCount<o.stats.framesDecodeCount&&(r.framesDecodeInterval=0)}this.lastDecodeVideoReceiverStats.set(r.ssrc,{stats:j({},r),lts:Date.now()}),this._stats.videoRecv.push(r);break}case"audio_recv":{const r=Br(BO);r.codec=t.googCodecName,r.outputLevel=Math.abs(Number(t.audioOutputLevel))/32767,r.decodingCNG=Number(t.googDecodingCNG),r.decodingCTN=Number(t.googDecodingCTN),r.decodingCTSG=Number(t.googDecodingCTSG),r.decodingNormal=Number(t.googDecodingNormal),r.decodingPLC=Number(t.googDecodingPLC),r.decodingPLCCNG=Number(t.googDecodingPLCCNG),r.expandRate=Number(t.googExpandRate),r.accelerateRate=Number(t.googAccelerateRate),r.preemptiveExpandRate=Number(t.googPreemptiveExpandRate),r.secondary
42DecodedRate=Number(t.googSecondaryDecodedRate),r.speechExpandRate=Number(t.googSpeechExpandRate),r.preferredJitterBufferMs=Number(t.googPreferredJitterBufferMs),r.jitterBufferMs=Number(t.googJitterBufferMs),r.jitterMs=Number(t.googJitterReceived),r.bytes=Number(t.bytesReceived),r.packets=Number(t.packetsReceived),r.packetsLost=Number(t.packetsLost),r.ssrc=Number(t.ssrc),r.receivedFrames=Number(t.googDecodingCTN)||Number(t.packetsReceived),r.droppedFrames=Number(t.googDecodingPLC)+Number(t.googDecodingPLCCNG)||Number(t.packetsLost),r.receivedFrames>0&&!this.isFirstAudioReceived[r.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(r.ssrc),this.isFirstAudioReceived[r.ssrc]=!0),r.decodingNormal>0&&!this.isFirstAudioDecoded[r.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(r.ssrc),this.isFirstAudioDecoded[r.ssrc]=!0),this._stats.audioRecv.push(r);break}case"audio_send":{const r=Br(FO);r.codec=t.googCodecName,r.inputLevel=Math.abs(Number(t.audioInputLevel))/32767,r.aecReturnLoss=Number(t.googEchoCancellationReturnLoss||0),r.aecReturnLossEnhancement=Number(t.googEchoCancellationReturnLossEnhancement||0),r.residualEchoLikelihood=Number(t.googResidualEchoLikelihood||0),r.residualEchoLikelihoodRecentMax=Number(t.googResidualEchoLikelihoodRecentMax||0),r.bytes=Number(t.bytesSent),r.packets=Number(t.packetsSent),r.packetsLost=Number(t.packetsLost),r.ssrc=Number(t.ssrc),r.rttMs=Number(t.googRtt||0),this._stats.rtt=r.rttMs,this._stats.audioSend.push(r);break}}})}_getStats(){return new K((e,t)=>{this.pc.getStats(e,t)})}statsResponsesToObjects(e){const t=[];return e.result().forEach(n=>{const i={id:n.id,timestamp:n.timestamp.valueOf().toString(),type:n.type};n.names().forEach(r=>{i[r]=n.stat(r)}),t.push(i)}),t}},od=function(e){return e.BANDWIDTH="bandwidth",e.CPU="cpu",e.NONE="none",e.OTHER="other",e}({}),Op=function(e){return e.L1T1="L1T1",e.L1T2="L1T2",e.L1T3="L1T3",e.L1T3_KEY="L1T3_KEY",e.L2T1_KEY="L2T1_KEY",e.L2T2_KEY="L2T2_KEY",e.L2T3_KEY="L2T3_KEY",e.L3T1_KEY="L3T1_KEY",e.L3T2_KEY="L3T2_KEY",e.L3T3_KEY="L3T3_KEY",e}({}),hS=function(e){return e[e.new=0]="new",e[e.connecting=1]="connecting",e[e.connected=2]="connected",e[e.disconnected=3]="disconnected",e[e.failed=4]="failed",e[e.closed=5]="closed",e}({}),zi=function(e){return e.CERTIFICATE="certificate",e.CODEC="codec",e.CANDIDATE_PAIR="candidate-pair",e.LOCAL_CANDIDATE="local-candidate",e.REMOTE_CANDIDATE="remote-candidate",e.INBOUND="inbound-rtp",e.TRACK="track",e.OUTBOUND="outbound-rtp",e.PC="peer-connection",e.REMOTE_INBOUND="remote-inbound-rtp",e.REMOTE_OUTBOUND="remote-outbound-rtp",e.TRANSPORT="transport",e.CSRC="csrc",e.DATA_CHANNEL="data-channel",e.STREAM="stream",e.SENDER="sender",e.RECEIVER="receiver",e}({});var sd=function(e){return e[e.kNone=1]="kNone",e[e.kMillisecondsFromSeconds=1e3]="kMillisecondsFromSeconds",e[e.kBytesToBits=8]="kBytesToBits",e}(sd||{});function Xl(e,t,n,i){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:sd.kNone;if(!t)return;const o=Number(t[n]);if(typeof o!="number")return;const s=Number(t[i]);if(typeof s!="number")return;if(!e)return s?o/s*r:void 0;const a=Number(e[n]);if(typeof a!="number")return;const c=Number(e[i]);if(typeof c!="number")return;const d=s-c;return d?(o-a)/d*r:void 0}let GO=class extends uS{constructor(){super(...arguments),ge(this,"_stats",Yl),ge(this,"report",void 0),ge(this,"lastDecodeVideoReceiverStats",new Map),ge(this,"lastVideoFramesRecv",new Map),ge(this,"lastVideoFramesSent",new Map),ge(this,"lastVideoFramesDecode",new Map),ge(this,"lastVideoFramesOutput",new Map),ge(this,"lastVideoJBDelay",new Map),ge(this,"lastAudioJBDelay",new Map),ge(this,"mediaBytesSent",new Map),ge(this,"mediaBytesRetransmit",new Map),ge(this,"mediaBytesTargetEncode",new Map),ge(this,"lastDecodeAudioReceiverStats",new Map),ge(this,"lastAudioConcealment",new Map),ge(this,"lastEncoderMs",new Map)}async updateStats(){this.report=await this.pc.getStats(),this._stats=Br(Yl),this.report.forEach(e=>{switch(e.type){case zi.OUTBOUND:case zi.INBOUND:{const t=e.mediaType||e.kind,n=!t&&"frameWidth"in e,i=!t&&!("frameWidth"in e);e.type===zi.OUTBOUND?t==="audio"||i?this.processAudioOutboundStats(e):(t==="video"||n)&&this.processVideoOutboundStats(e):e.type===zi.INBOUND&&(t==="audio"||i?this.processAudioInboundStats(e):(t==="video"||n)&&this.processVideoInboundStats(e));break}case zi.TRANSPORT:{this.processTransportStats(e);const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case zi.CANDIDATE_PAIR:e.selected&&this.processCandidatePairStats(e)}}),this.updateSendBitrate(),this._stats.updateInterval=Date.now()-this.stats.timestamp,this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}async getSelectedCandidatePair(){const e=await this.pc.getStats(),t={local:j({},Gr),remote:j({},Gr)};return e.forEach(n=>{let i;if(n.type===zi.TRANSPORT&&(i=e.get(n.selectedCandidatePairId)),n.type===zi.CANDIDATE_PAIR&&n.selected&&(i=n),i){const r=(o,s)=>{o.type=s.type,o.id=s.id,s.address&&(o.address=s.address),s.candidateType&&(o.candidateType=s.candidateType),s.port&&(o.port=s.port),s.priority&&(o.priority=s.priority),s.protocol&&(o.protocol=s.protocol),s.relayProtocol&&(o.relayProtocol=s.relayProtocol)};if(i.localCandidateId){const o=e.get(i.localCandidateId);o&&r(t.local,o)}if(i.remoteCandidateId){const o=e.get(i.remoteCandidateId);o&&r(t.remote,o)}}}),t}processCandidatePairStats(e){if(this._stats.sendBandwidth=e.availableOutgoingBitrate||0,e.currentRoundTripTime&&(this._stats.rtt=1e3*e.currentRoundTripTime),this._stats.videoSend.forEac
42h(t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)}),this._stats.audioSend.forEach(t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)}),this._stats.selectedCandidatePair.id=e.id,e.localCandidateId){const t=this.report.get(e.localCandidateId);t&&this.processCandidateStats(t)}if(e.remoteCandidateId){const t=this.report.get(e.remoteCandidateId);t&&this.processCandidateStats(t)}}processCandidateStats(e){let t;e.type===zi.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===zi.REMOTE_CANDIDATE&&(t=this._stats.selectedCandidatePair.remoteCandidate),t&&(t.type=e.type,t.id=e.id,e.address&&(t.address=e.address),e.candidateType&&(t.candidateType=e.candidateType),e.port&&(t.port=e.port),e.priority&&(t.priority=e.priority),e.protocol&&(t.protocol=e.protocol),e.relayProtocol&&(t.relayProtocol=e.relayProtocol),e.type===zi.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(j({},t),j({},this.stats.selectedCandidatePair.localCandidate)),e.type===zi.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(j({},t),j({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find(i=>i.ssrc===e.ssrc);t||(t=Br(BO),this._stats.audioRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.packetsDiscarded=e.packetsDiscarded,t.bytes=e.bytesReceived,t.jitterMs=1e3*e.jitter,t.retransmittedBytesReceived=e.retransmittedBytesReceived,t.retransmittedPacketsReceived=e.retransmittedPacketsReceived,t.totalProcessingDelay=e.totalProcessingDelay,t.jitterBufferEmittedCount=e.jitterBufferEmittedCount,t.estimatedPlayoutTimestamp=e.estimatedPlayoutTimestamp;const n=this.lastDecodeAudioReceiverStats.get(t.ssrc);t.avgProcessingDelayMs=Xl(n,t,"totalProcessingDelay","jitterBufferEmittedCount",sd.kMillisecondsFromSeconds),this.processAudioTrackReceiverStats(e,e.trackId,t),this.calculateAudioFreeze(t,n,e),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),t.receivedFrames||(t.receivedFrames=e.packetsReceived),t.droppedFrames||(t.droppedFrames=e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.outputLevel&&t.outputLevel>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),typeof e.concealedSamples=="number"&&(t.concealedSamples=e.concealedSamples),this.lastDecodeAudioReceiverStats.set(t.ssrc,j({},t))}calculateAudioFreeze(e,t,n){const i=this.lastAudioConcealment.get(e.ssrc);if(t!=null&&i!=null){const r=i.lts,o=n.timestamp,s=o-r;if(s<=0)return;const a=e.concealedSamples-t.concealedSamples-0,c=i.nonSilent+a,d=e.totalSamplesReceived-t.totalSamplesReceived;if(d<=0)return;const l=80*d/s,h=200*d/s,u=s/d;let p=0;e.freezeSamples80=t.freezeSamples80,e.freezeMs80=t.freezeMs80,c>l&&(i.plc80>0?(e.freezeSamples80+=a,e.freezeMs80+=Math.round(a*u)):(e.freezeSamples80+=c,e.freezeMs80+=Math.round(c*u)),p=i.plc80+1);let E=0;e.freezeSamples200=t.freezeSamples200,e.freezeMs200=t.freezeMs200,c>h&&(i.plc200>0?(e.freezeSamples200+=a,e.freezeMs200+=Math.round(a*u)):(e.freezeSamples200+=c,e.freezeMs200+=Math.round(c*u)),E=i.plc200+1),this.lastAudioConcealment.set(e.ssrc,{nonSilent:a,lts:o,plc80:p,plc200:E})}else e.freezeSamples80=0,e.freezeSamples200=0,e.freezeMs80=0,e.freezeMs200=0,this.lastAudioConcealment.set(e.ssrc,{nonSilent:0,lts:n.timestamp,plc80:0,plc200:0})}processVideoInboundStats(e){let t=this._stats.videoRecv.find(s=>s.ssrc===e.ssrc);t||(t=Br(VO),this._stats.videoRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.framesDecodeCount=e.framesDecoded,t.framesDroppedCount=e.framesDropped,t.totalInterFrameDelay=e.totalInterFrameDelay,t.totalSquaredInterFrameDelay=e.totalSquaredInterFrameDelay,t.totalFreezesDuration=e.totalFreezesDuration,t.totalProcessingDelay=e.totalProcessingDelay,t.packetsDiscarded=e.packetsDiscarded,t.framesAssembledFromMultiplePackets=e.framesAssembledFromMultiplePackets,t.totalAssemblyTime=e.totalAssemblyTime,t.keyFramesDecoded=e.keyFramesDecoded,t.retransmittedBytesReceived=e.retransmittedBytesReceived,t.retransmittedPacketsReceived=e.retransmittedPacketsReceived,t.estimatedPlayoutTimestamp=e.estimatedPlayoutTimestamp;const n=this.lastDecodeVideoReceiverStats.get(t.ssrc),i=this.lastVideoFramesDecode.get(t.
vendor: 4,625 bytes, line 42
42ssrc),r=this.lastVideoFramesOutput.get(t.ssrc),o=Date.now();if(t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]){const s=t.decodedFrame?t.decodedFrame.width:0,a=t.decodedFrame?t.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,s,a),this.isFirstVideoDecoded[t.ssrc]=!0}if(n){const s=n.stats,a=o-n.lts;t.framesDecodeFreezeTime=s.framesDecodeFreezeTime,t.framesDecodeInterval=s.framesDecodeInterval,!this.isFirstVideoDecoded[t.ssrc]&&a>this.options.firstVideoDecodedTimeout&&!this.isFirstVideoDecodedTimeout[t.ssrc]&&(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(t.ssrc),this.isFirstVideoDecodedTimeout[t.ssrc]=!0),t.framesDecodeCount>s.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(n.lts=Date.now(),t.framesDecodeInterval=a,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount<s.framesDecodeCount&&(t.framesDecodeInterval=0),e.framesDecoded&&e.qpSum&&(n.stats.framesDecodeCount>e.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-n.qpSum)/(e.framesDecoded-n.stats.framesDecodeCount))}e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime,t.avgDecodeMs=Xl(n==null?void 0:n.stats,t,"decodeMs","framesDecodeCount")),t.avgProcessingDelayMs=Xl(n==null?void 0:n.stats,t,"totalProcessingDelay","framesDecodeCount",sd.kMillisecondsFromSeconds),t.avgFramesAssembledFromMultiplePacketsMs=Xl(n==null?void 0:n.stats,t,"totalAssemblyTime","framesAssembledFromMultiplePackets",sd.kMillisecondsFromSeconds),t.avgInterFrameDelayMs=Xl(n==null?void 0:n.stats,t,"totalInterFrameDelay","framesDecodeCount",sd.kMillisecondsFromSeconds),i&&o-i.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-i.count)/((o-i.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:t.decodeFrameRate})):i?t.decodeFrameRate=i.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:0}),t.framesDroppedCount&&e.framesReceived&&(r&&o-r.lts>=800?(t.outputFrameRate=Math.round((e.framesReceived-t.framesDroppedCount-r.count)/((o-r.lts)/1e3)),this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:Math.max(t.outputFrameRate,0)})):r?t.outputFrameRate=r.rate:this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:0})),this.processVideoTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),typeof e.powerEfficientDecoder=="boolean"&&(t.powerEfficientDecoder=e.powerEfficientDecoder?1:0),e.framerateMean&&(t.framesRateFirefox=e.framerateMean),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:j({},t),lts:n?n.lts:Date.now(),qpSum:e.qpSum})}processVideoOutboundStats(e){let t=this._stats.videoSend.find(i=>i.ssrc===e.ssrc);t||(t=Br(xO),this._stats.videoSend.push(t));const n=this.mediaBytesSent.get(e.ssrc);if(n)n.add(e.bytesSent);else{const i=new lS(10);i.add(e.bytesSent),this.mediaBytesSent.set(e.ssrc,i)}if(e.retransmittedBytesSent!==void 0){const i=this.mediaBytesRetransmit.get(e.ssrc);if(i)i.add(e.retransmittedBytesSent);else{const r=new lS(10);r.add(e.retransmittedBytesSent),this.mediaBytesRetransmit.set(e.ssrc,r)}}if(e.totalEncodedBytesTarget){const i=this.mediaBytesTargetEncode.get(e.ssrc);if(i)i.add(e.totalEncodedBytesTarget);else{const r=new lS(10);r.add(e.totalEncodedBytesTarget),this.mediaBytesTargetEncode.set(e.ssrc,r)}}if(t.ssrc=e.ssrc,t.bytes=e.bytesSent,t.packets=e.packetsSent,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.frameCount=e.framesEncoded,t.adaptionChangeReason=e.qualityLimitationReason,t.scalabilityMode=e.scalabilityMode,t.retransmittedBytesSent=e.retransmittedBytesSent,t.retransmittedPacketsSent=e.retransmittedPacketsSent,t.hugeFramesSent=e.hugeFramesSent,t.keyFramesEncoded=e.keyFramesEncoded,t.targetBitrate=e.targetBitrate,e.totalEncodeTime&&e.framesEncoded){const i=this.lastEncoderMs.get(e.ssrc);if(!i||i.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else{const r=e.framesEncoded-i.lastFrameCount,o=e.totalEncodeTime-i.lastEncoderTime;t.avgEncodeMs=1e3*o/r}}if(e.framesEncoded&&e.qpSum){const i=this.lastEncoderMs.get(e.ssrc);!i||i.lastFrameCount>e.framesEncoded?t.qpSumPerFrame=e.qpSum/e.framesEncoded:t.qpSumPerFrame=(e.qpSum-i.lastQpSum)/(e.framesEncoded-i.lastFrameCount)}
42if(this.lastEncoderMs.set(e.ssrc,{lastFrameCount:e.framesEncoded,lastEncoderTime:e.totalEncodeTime,lastQpSum:e.qpSum,lts:Date.now()}),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),typeof e.powerEfficientEncoder=="boolean"&&(t.powerEfficientEncoder=e.powerEfficientEncoder?1:0),e.mediaSourceId&&this.processVideoMediaSource(e.mediaSourceId,t),this.processVideoTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const i=this.findRemoteStatsId(e.ssrc,zi.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find(n=>n.ssrc===e.ssrc);if(t||(t=Br(FO),this._stats.audioSend.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsSent,t.bytes=e.bytesSent,t.retransmittedBytesSent=e.retransmittedBytesSent,t.retransmittedPacketsSent=e.retransmittedPacketsSent,e.mediaSourceId&&this.processAudioMediaSource(e.mediaSourceId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),this.processAudioTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const n=this.findRemoteStatsId(e.ssrc,zi.REMOTE_INBOUND);n&&this.processRemoteInboundStats(n,t)}}processTransportStats(e){this._stats.transport.bytesReceived=e.bytesReceived||this._stats.transport.bytesReceived,this._stats.transport.bytesSent=e.bytesSent||this._stats.transport.bytesSent,this._stats.transport.packetsReceived=e.packetsReceived||this._stats.transport.packetsReceived,this._stats.transport.packetsSent=e.packetsSent||this._stats.transport.packetsSent}findRemoteStatsId(e,t){var n;const i=Array.from(ti(n=this.report).call(n)).find(r=>r.type===t&&r.ssrc===e);return i?i.id:null}processVideoMediaSource(e,t){const n=this.report.get(e);n&&n.width&&n.height&&n.framesPerSecond&&(t.inputFrame={width:n.width,height:n.height,frameRate:n.framesPerSecond})}processAudioMediaSource(e,t){const n=this.report.get(e);n&&(t.inputLevel=n.audioLevel)}processVideoTrackSenderStats(e,t,n){var i,r,o,s;const a=t?this.report.get(t):void 0,c=(i=a==null?void 0:a.framesSent)!==null&&i!==void 0?i:e.framesSent;if(typeof c!="number")return;let d=(r=a==null?void 0:a.frameWidth)!==null&&r!==void 0?r:e.frameWidth,l=(o=a==null?void 0:a.frameHeight)!==null&&o!==void 0?o:e.frameHeight,h=(s=a==null?void 0:a.framesPerSecond)!==null&&s!==void 0?s:e.framesPerSecond;if(typeof d=="number"&&typeof l=="number"||(d=0,l=0),h==null){const u=Date.now(),p=this.lastVideoFramesSent.get(n.ssrc);p&&u-p.lts>=800?(h=Math.round((c-p.count)/((u-p.lts)/1e3)),this.lastVideoFramesSent.set(n.ssrc,{count:c,lts:u,rate:h})):p?h=p.rate:this.lastVideoFramesSent.set(n.ssrc,{count:c,lts:u,rate:0})}n.sentFrame={width:d,height:l,frameRate:Math.max(0,h)}}processVideoTrackReceiverStats(e,t,n){var i,r,o,s,a;const c=t?this.report.get(t):void 0,d=(i=c==null?void 0:c.framesReceived)!==null&&i!==void 0?i:e.framesReceived,l=(r=c==null?void 0:c.frameWidth)!==null&&r!==void 0?r:e.frameWidth,h=(o=c==null?void 0:c.frameHeight)!==null&&o!==void 0?o:e.frameHeight,u=(s=c==null?void 0:c.jitterBufferDelay)!==null&&s!==void 0?s:e.jitterBufferDelay,p=(a=c==null?void 0:c.jitterBufferEmittedCount)!==null&&a!==void 0?a:e.jitterBufferEmittedCount;if(typeof d=="number"){const E=this.lastVideoFramesRecv.get(n.ssrc),m=Date.now();n.framesReceivedCount=d;let g=0;E&&m-E.lts>=800?(g=Math.round((d-E.count)/((m-E.lts)/1e3)),this.lastVideoFramesRecv.set(n.ssrc,{count:d,lts:m,rate:g})):E?g=E.rate:this.lastVideoFramesRecv.set(n.ssrc,{count:d,lts:m,rate:0}),n.receivedFrame={width:l||0,height:h||0,frameRate:g||0},n.decodedFrame={width:l||0,height:h||0,frameRate:n.decodeFrameRate||0},n.outputFrame={width:l||0,height:h||0,frameRate:n.outputFrameRate||n.decodeFrameRate||0}}if(u&&p){const E=this.lastVideoJBDelay.get(n.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let m=E.jitterBufferMs;const g=p-E.jitterBufferEmittedCount;g>0&&(m=1e3*(u-E.jitterBufferDelay)/g),n.jitterBufferMs=m,n.currentDelayMs=Math.round(m),this.lastVideoJBDelay.set(n.ssrc,{jitterBufferDelay:u,jitterBufferEmittedCount:p,jitterBufferMs:n.currentDelayMs})}}
42processAudioTrackSenderStats(e,t,n){var i,r,o,s;const a=t?this.report.get(t):void 0,c=(i=(r=a==null?void 0:a.echoReturnLoss)!==null&&r!==void 0?r:e.echoReturnLoss)!==null&&i!==void 0?i:0,d=(o=(s=a==null?void 0:a.echoReturnLossEnhancement)!==null&&s!==void 0?s:e.echoReturnLossEnhancement)!==null&&o!==void 0?o:0;n.aecReturnLoss=c,n.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(e,t,n){var i,r,o,s,a,c,d,l,h;const u=t?this.report.get(t):void 0,p=(i=u==null?void 0:u.removedSamplesForAcceleration)!==null&&i!==void 0?i:e.removedSamplesForAcceleration,E=(r=u==null?void 0:u.totalSamplesReceived)!==null&&r!==void 0?r:e.totalSamplesReceived,m=(o=u==null?void 0:u.jitterBufferDelay)!==null&&o!==void 0?o:e.jitterBufferDelay,g=(s=u==null?void 0:u.jitterBufferEmittedCount)!==null&&s!==void 0?s:e.jitterBufferEmittedCount,R=(a=u==null?void 0:u.audioLevel)!==null&&a!==void 0?a:e==null?void 0:e.audioLevel,v=(c=u==null?void 0:u.totalSamplesDuration)!==null&&c!==void 0?c:e==null?void 0:e.totalSamplesDuration,C=(d=u==null?void 0:u.concealedSamples)!==null&&d!==void 0?d:e.concealedSamples,w=(l=u==null?void 0:u.silentConcealedSamples)!==null&&l!==void 0?l:e.silentConcealedSamples,b=(h=u==null?void 0:u.concealmentEvents)!==null&&h!==void 0?h:e.concealmentEvents;if(typeof E=="number"&&(n.totalSamplesReceived=E),typeof w=="number"&&(n.silentConcealedSamples=w),typeof b=="number"&&(n.concealmentEvents=b),typeof C=="number"&&(n.concealedSamples=C),p&&E&&(n.accelerateRate=p/E),m&&g){const N=this.lastAudioJBDelay.get(n.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let k=N.jitterBufferMs;const U=g-N.jitterBufferEmittedCount;U>0&&(k=1e3*(m-N.jitterBufferDelay)/U),n.jitterBufferMs=Math.round(k),this.lastAudioJBDelay.set(n.ssrc,{jitterBufferDelay:m,jitterBufferEmittedCount:g,jitterBufferMs:n.jitterBufferMs})}n.outputLevel=R;let y=1920;v&&E&&(y=E/v/50,n.receivedFrames=Math.round(E/y)),C&&(n.droppedFrames=Math.round(C/y))}processRemoteInboundStats(e,t){const n=this.report.get(e);n&&(t.packetsLost=n.packetsLost,n.roundTripTime&&(t.rttMs=1e3*n.roundTripTime),n.jitter&&(t.jitterMs=1e3*n.jitter),n.timestamp&&(t.timestamp=n.timestamp))}getCodecFromCodecStats(e){const t=this.report.get(e);if(!t)return"";const n=t.mimeType.match(/\/(.*)$/);return n&&n[1]?n[1]:""}updateSendBitrate(){let e=0,t=null,n=null;this.mediaBytesSent.forEach(r=>{e+=r.diffMean()}),this.mediaBytesRetransmit.forEach(r=>{t=t===null?r.diffMean():t+r.diffMean()}),this.mediaBytesTargetEncode.forEach(r=>{n=n===null?r.diffMean():n+r.diffMean()});const i=t!==null?e-t:e;this._stats.bitrate={actualEncoded:8*i/(this.options.updateInterval/1e3),transmit:8*e/(this.options.updateInterval/1e3)},t!==null&&(this._stats.bitrate.retransmit=8*t/(this.options.updateInterval/1e3)),n!==null&&(this._stats.bitrate.targetEncoded=8*n/(this.options.updateInterval/1e3))}},X9=class extends uS{updateStats(){return K.resolve()}};function Np(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:250,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:8,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:500,r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1e4;const o=function(){const s=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return s&&s[0]?Number(s[0].split("/")[1]):null}();return o?o<76?new Y9(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r}):new GO(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r}):function(s){if(!window.RTCStatsReport)return!1;const a=s.getStats();return!!(a instanceof K||function(c){return!!c&&(typeof c=="object"||typeof c=="function")&&typeof c.then=="function"}(a))}(e)?new GO(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r}):new X9(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r})}const jO="websdk_ng_install_id";function Jl(){try{if(T("INSTALL_ID"))return T("INSTALL_ID");let e=window.localStorage.getItem(jO);return e||(e=La(),window.localStorage.setItem(jO,e)),at("INSTALL_ID",e),e}catch{return}}const qi=function(e){if(e.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return e;const t=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-([0-9]+)/);if(t&&t[1]&&t[2]){const n=t[1],i=t[2];return"".concat(n,".").concat(i)}return"4.0.0.999"}("4.24.3"),pS=function(){try{return JSON.parse("true")===!0}catch{return!0}}();let ka=function(e){return e.Default="default",e.Auto="auto",e.Relay="relay",e.SdRtn="sd-rtn",e}({});
vendor: 4,635 bytes, line 42
42const zt=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),n=["t","s","t"];n.splice(1,0,"e");const i=n.join(""),r=[];for(let a=0;a<6;a++)r.push("1");const o=r.join(""),s={};return s[e]=i,s[t]=o,Object.assign(s,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=zt;const Dp={ENABLE_PUBLISHED_USER_LIST:!0,ENABLE_USER_LIST:!1,MAX_SUBSCRIPTION:50,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,ENABLE_USER_LICENSE_CHECK:!0,DISABLE_FEC:void 0,ENABLE_NTP_REPORT:!1,ENABLE_INSTANT_VIDEO:!1,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,ENABLE_LOSSBASED_BWE:!0,ENABLE_AUT_CC:!0,FORCE_ENABLE_AUT_CC:!1,ENABLE_CC_FALLBACK:void 0,SUBSCRIBE_TWCC:!0,PUBLISH_TWCC:!1,ENABLE_SVC_DEFAULT_CODECS:["H264","VP8","VP9","AV1"],SVC:[],ENABLE_FULL_LINK_AV_SYNC:!1,SVC_MODE:null,ENABLE_AUT_FEEDBACK:!0,SVC_EXTENDED:["VP9"],ENABLE_JOIN_V4:!1,ENABLE_AP_COMPRESS:!0},_S={MIN_FRAME_RATE:1,MAX_FRAME_RATE:30,MAX_THRESHOLD_FRAMERATE:30,BITRATE_MIN_THRESHOLD:100,BITRATE_MAX_THRESHOLD:100,MAX_SCALE:5,BWE_SCALE_UP_THRESHOLD:.6,BWE_SCALE_DOWN_THRESHOLD:.6,PERF_SCALE_UP_THRESHOLD:.7,PERF_SCALE_DOWN_THRESHOLD:.6,MOTION_RESOLUTION_FACTOR:.8,MOTION_BITRATE_FACTOR:.6,DETAIL_FRAMERATE_FACTOR:.8,DETAIL_BITRATE_FACTOR:.6,BALANCE_RESOLUTION_FACTOR:.9,BALANCE_FRAMERATE_FACTOR:.9,BALANCE_BITRATE_FACTOR:.6,OVERUSE_TIMES_THRESHOLD:10,UNDERUSE_TIMES_THRESHOLD:40},mS="v4.24.3-0-g6cc16b0bb-dirty(3/16/2026, 4:35:55 PM)",ES={ENABLE_EVENT_REPORT:!0,UPLOAD_LOG:!1,ENABLE_AG_ADAPTATION:!0,FORCE_AG_HIGH_FRAMERATE:!1,FORCE_SUPPORT_AG_ADAPTATION:!1,ENCODER_CONFIG_LIMIT:{},CAMERA_CAPTURE_CONFIG:void 0,ENABLE_PRELOAD:!0,NEW_ICE_RESTART:!0,ICE_RESTART_INTERVAL:1e4,RESTART_SEQUENCE:["udp_tcp_relay","relay"],FIRST_TCP_CANDIDATE:!1,MAX_CONFIG_RETRY:10,ENABLE_CONFIG_RESTORE:!1,CONFIG_RESTORE_ERROR_API:["createClient","Client.join"],CONFIG_ERROR_MONITOR:["INVALID_OPERATION","UNEXPECTED_ERROR"],BLOCKED_CONFIG_MAX_TIME:864e5,FIRST_TCP_CANDIDATE_INTERVAL:1e3,TURN_DOMAIN:"edge.agora.io",TURN_DOMAINS:["edge.agora.io"],USE_TURN_IP:!0,NEW_TURN_MODE:4,NEW_FORCE_TURN:!1,USE_NEW_RENDER_FREEZE_TIME:!0,FLS_FALLBACK_TIMEOUT:3e4,RTE_DETAIL_REPORT_INTERVAL:6e4,ENCODE_EXCEPTION_TIMES:5,ENABLE_ENCODE_EXCEPTION:!0,ENCODE_EXCEPTION_VALIDATE_CODEC:["h264"],VIDEO_ENCODER_CONFIG_LIST:[{width:240,height:180},{width:320,height:240},{width:400,height:300},{width:480,height:360},{width:560,height:420},{width:640,height:480}],DELETE_NEQ_AFTER_USER_LEAVE:!0,UPDATE_RTP_CAP_IN_HOST:!1,IOS_BG_TAG:!0,IOS_AUTO_RESTART_BG_TAG:!0,IGNORE_UID_CHECK:!1,ENABLE_UP_SPS_PPS:!1,ENABLE_DOWN_SPS_PPS:!0,NO_EDGES_RETRY:!0,BUFFER_READY_FRAMES:3,FLS_SYNC_AV_PLAY_LIMIT:0,FLS_BUFFER_WAIT_TIME:1500,VOS_CONFIGURE:void 0,ENABLE_QUALITY_FALLBACK:!1,QUALITY_FALLBACK_REHEARSAL:!0,ENABLE_FLS_AV1_FIRST:!1,ENABLE_AP_MULTI_IP:!0,FLS_ENABLE_AV1_DETECT:!0,FLS_ENABLE_AV1_DECODE_DETECT:!0,ENABLE_SDP_ENDPOINT_LOG:!1,REMOTE_VIDEO_FREEZE_TIME_VERSION:2},tt=j(j(j(j({},ES),{},{PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:["CHINA","GLOBAL"],WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],SDP_ENDPOINT_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],SDP_ENDPOINT_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-web-2.ap.sd-rtn.com","cds-ap-web-3.agora.io","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-web-2.ap.sd-rtn.com","sua-ap-web-3.agora.io","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-ap-web-1.agora.io","uap-web-2.ap.sd-rtn.com","uap-ap-web-3.agora.io","uap-web-4.ap.sd-rtn.com"],LOG_UPLOAD_SERVER:"logservice.agora.io",EVENT_REPORT_DOMAIN:"statscollector-1.agora.io",EVENT_REPORT_BACKUP_DOMAIN:"web-2.statscollector.sd-rtn.com",GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,NOT_REPORT_EVENT:[],PING_PONG_TIME_OUT:10,WEBSOCKET_TIMEOUT_MIN:1e4,EVENT_REPORT_SEND_INTERVAL:3e3,CONFIG_DISTRIBUTE_INTERVAL:3e5,ENABLE_CONFIG_DISTRIBUTE:!0,CANDIDATE_TIMEOUT:5e3,SHOW_REPORT_INVOKER_LOG:!1,SHOW_REPORT_USER_INVOKER_LOG:!0,JOIN_EXTEND:"",PUB_EXTEND:"",SUB_EXTEND:"",FORCE_TURN:!1,TURN_ENABLE_TCP:!0,TURN_ENABLE_UDP:!0,MAX_UPLOAD_CACHE:50,UPLOAD_CACHE_INTERVAL:2e3,AJAX_REQUEST_CONCURRENT:3,REPORT_APP_SCENARIO:void 0,GATEWAY_DOMAINS:["edge.agora.io","edge.sd-rtn.com"],CONNECT_GATEWAY_WITHOUT_DOMAIN:!1,WORKER_DOMAIN:"edge.agora.io",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AU
42DIO_SOURCE_AVG_VOLUME_DURATION:3e3,AUDIO_VOLUME_INDICATION_INTERVAL:2e3,VOLUME_VOICE_WEIGHT:10,GET_VOLUME_OF_MUTED_AUDIO_TRACK:!1,STATS_UPDATE_INTERVAL:250,NORMAL_EVENT_QUEUE_CAPACITY:100,CUSTOM_REPORT:!0,CUSTOM_REPORT_LIMIT:20,PROXY_SERVER_TYPE2:"webnginx-proxy.agora.io",PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com","webrtc-cloud-proxy.agora.io"],CUSTOM_PUB_ANSWER_MODIFIER:null,CUSTOM_SUB_ANSWER_MODIFIER:null,CUSTOM_PUB_OFFER_MODIFIER:null,CUSTOM_SUB_OFFER_MODIFIER:null,DSCP_TYPE:"high",REMOVE_NEW_CODECS:!0,FRAGEMENT_LENGTH:3,WEBSOCKET_COMPRESS:!1,SIMULCAST:!1,CHECK_VIDEO_VISIBLE_INTERVAL:3e4,CHECK_LOCAL_STATS_INTERVAL:250,PROFILE_SWITCH_INTERVAL:2e3,UNSUPPORTED_VIDEO_CODEC:[],ENUMERATE_DEVICES_INTERVAL:!1,ENUMERATE_DEVICES_INTERVAL_TIME:1e4,USE_NEW_TOKEN:!1,CLOSE_AFB_FOR_LOCAL_AP:!0,JOIN_MAX_CONCURRENCY:6,JOIN_WITH_FALLBACK_SIGNAL_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE:!1,JOIN_GATEWAY_TRY_443PORT_DURATION:2e3,JOIN_GATEWAY_USE_443PORT_ONLY:!1,JOIN_GATEWAY_USE_DUAL_DOMAIN:!0,JOIN_GATEWAY_FALLBACK_PORT:443,USE_TURN_SERVER_OF_GATEWAY:!1,H264_PROFILE_LEVEL_ID:"",USE_NEW_LOG:!1,LOG_VERSION:3,MEDIA_DEVICE_CONSTRAINTS:null,ENCRYPT_PROXY_USERNAME_AND_PSW:!0,SDP_LOGGING:!1,CSP_DETECTED_HOSTNAME_LIST:["agora.io","sd-rtn.com"],REMOTE_AUDIO_TRACK_USES_WEB_AUDIO:!1,LOCAL_AUDIO_TRACK_USES_WEB_AUDIO:!1,BITRATE_ADAPTER_TYPE:"STANDARD_BITRATE",AI_DENOISER_PARAMETERS:{excludedLinks:[]},ADJUST_3A_FROM_PLUGINS:!0,RAISE_H264_BASELINE_PRIORITY:!0,FILTER_SEND_H264_BASELINE:!1,FIRST_H264_PROFILE_LEVEL_ID:"42001f",FIRST_PACKETIZATION_MODE:"",X_GOOGLE_START_BITRATE:void 0,NEW_REPORT_SERVER:!1,NEW_REPORT_SERVER_DOMAINS:["data-reporting.agora.io","data-reporting.agora.io"],VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT:3e5,VIDEO_INSPECT_INTERVAL_MINIMUM:1e3,VIDEO_INSPECT_QUALITY_RATIO:.9,VIDEO_INSPECT_WORKER_MANAGER_HOST:"edge.agora.io",VIDEO_INSPECT_WORKER_MANAGER_PORT:"",VIDEO_INSPECT_WORKER_MANAGER_WSS:"",VIDEO_INSPECT_WORKER_PORT:"",SHOW_VIDEO_INSPECT_WORKER_MESSAGE:!1,STATS_COLLECTOR_PORT:443,FORCE_TURN_TCP:!1,WEBAUDIO_INIT_OPTIONS:void 0,FILTER_VIDEO_FEC:!0,FILTER_AUDIO_FEC:!1,CHROME_DUAL_STREAM_USE_ENCODING:!0,DISABLE_DUAL_STREAM_USE_ENCODING:!1,EXTENSION_USAGE_UPLOAD_INTERVAL:1e4,ICE_RESTART:!0,FINGERPRINT:null,ENABLE_VIDEO_FRAME_CALLBACK:!0,VIDEO_FREEZE_DURATION:500,SPATIALIZER_PARAMETERS:{},UPLOAD_LOG_INTERVAL:3e3,UPLOAD_LOG_REQUEST_RETRY_INTERVAL:2e3,UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL:2e4,UPLOAD_LOG_TRY_INTERVAL_WHILE_OFF:5e3,UPLOAD_LOG_RETRY_INTERVAL_V1:1e4,UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1:200,UPLOAD_LOG_LENGTH_EACH_TIME:10,APP_TYPE:0,DISABLE_WEBAUDIO:!1,CHANNEL_MEDIA_RELAY_SERVERS:void 0,KEEP_LAST_FRAME:!0,FORWARD_P2P_CREATION:!0,SYNC_GROUP:!0,BLOCK_LOCAL_CLIENT:!1,ENABLE_AUDIO_TOPN:!1,ENABLE_AUDIO_METADATA:!1,ENABLE_AUDIO_PTS:!1,TOPN_SMOOTH_LEVEL:void 0,TOPN_NEW_SPEAKER_DELAY:void 0,TOPN_SWITCH_HOLD_MS:void 0,TOPN_AUDIO_GAIN:void 0,TOPN_SILENCE_THRESHOLD:250,AP_AREA:!0,ENABLE_ENCODED_TRANSFORM:!1,ENABLE_VIDEO_SEI:!1,IMAGE_MODERATION_WORKER_HOST:"edge.agora.io",IMAGE_MODERATION_WORKER_WSS:"",IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT:3e5,IMAGE_MODERATION_INTERVAL_MINIMUM:1e3,SHOW_IMAGE_MODERATION_WORKER_MESSAGE:!1,IMAGE_MODERATION_QUALITY_RATIO:.9,IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL:5e3,SHOW_GLOBAL_CLIENT_LIST:!1,DATASTREAM_MAX_RETRANSMITS:10,TCP_CANDIDATE_ONLY:!1,EXTERNAL_SIGNAL_REQUEST_TIMEOUT:3e3,SHOW_P2P_LOG:!1,MAX_P2P_TIMEOUT:3e4,P2P_TOKEN_INTERVAL:1e3,SHOW_DATASTREAM2_LOG:!1,RESTRICTION_SET_PLAYBACK_DEVICE:!0,USE_PURE_ENCRYPTION_MASTER_KEY:!1,ENABLE_AUDIO_RED:!1,OPUS_PTIME:void 0,AUDIO_DUPLICATE_NUM:void 0,ENABLE_ABSSENDTIME_AS_SENTTS:!0,ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6e4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1e5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,PLAYER_STATE_DEFER:2e3,SIGNAL_REQUEST_WATCH_INTERVAL:1e3,FILEPATH_LENMAX:255,DUALSTREAM_OPERATION_CHECK:!0,MEDIA_ELEMENT_EXISTS_DEPTH:3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3,STATS_FILTER:{transportId:!0,googTrackId:!0},FILTER_VIDEO_CODEC:[],SIGNAL_CHANNEL:0,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,DC_JOIN_WITH_FAILBACK:4e3,DC_CONNECTION_TIMEOUT:2e3,DC_PINGPONG_INTERVAL:2e3,DC_DEBUG_LOG:!1,UNSUPPORTED_VIDEO_UPLINK_CODEC:[],UNSUPPORTED_VIDEO_DOWNLINK_CODEC:[],USE_NEW_NETWORK_CONFIG:!1,AUTO_RESET_AUDIO_ROUTE:!1,PLUGIN_INFO:[],OVERUSE_DETECTOR_PARAMS:_S,CUSTOM_ADAPTATION_DEFAULT_MODE:"",HIDE_NO_POSTER:!1,AP_CACHE_NUM:10,AP_UPDATE_INTERVAL:12e4,AP_CACHE_LIFETIME:12e4,MAX_PRELOAD_ASYNC_LENGTH:3,DISABLE_SCREEN_SHARE_REMB:!1},Dp),{},{USE_CANDIDATE_FROM_AP_DETAIL:!1,AP_REQUEST_DETAIL:void 0,ENABLE_ROLE_SELECT_EDGE:!1,CLIENT_ROLE_OPTIONS:void 0,REMOTE_VIDEO_STREAM_TYPE:void 0,COMPATIBLE_SDP_EXTENSION:["gdpr_forbidden"],LIMIT_BITRATE:void 0,EXPERIMENTS:{},USE_PUB_RTX:!0,USE_SUB_RTX:!0,ENABLE_DATASTREAM_2:!1,USE_XR:!0,ENABLE_PREALLOC_PC:!1,ENABLE_PRE_SUB:!1,ENABLE_SVC:!1,ENABLE_FORCE_HLS:!1,MAX_WEBAUDIO_VOLUME:300,ENABLE_VOS_FALLBACK:!1,ENABLE_FALLBACK_TO_HLS:!1,ENABLE_PRE_RENDER:!1,FORCE_DISABLE_AUTO_SUB:!1,ENABLE_PRE_SUB_WITH_PRE_PC:!0,PRE_USE_LOCAL_CODECS:!0},{INSTALL_ID:""}),{},{K_MIN_RENDER_DELAY:66,USE_STANDARD_BITRATE_DEFAULT:!1,VIDEO_NEW_BITRATE_RATIO:void 0,VIDEO_STANDARD_BITRATE_VERSION:2,BASELINE_MORE_H264_BITRATE_RATIO:1.1,IGNORE_RTC_DEVICE_CHECK:!1,FLS_AUTOPLAY_EMITS:!1,ENABLE_DUAL_STREAM_FLAG:!1,FORBID_MODIFY_LOCAL_OFFER_SDP:!1,RESERVE_MID_1_MLINE:!1,PRE_SUB_NUM:1,DC_IN_ESM:!0,PRE_PLAYOUT_DELAY_HINT:void 0});function at(e,t,n){var i,r,o;x(i=Object.keys(tt)).call(i,e)&&(!n&&x(r=Object.keys(Zi)).call(r,e)||(tt[e]=t,e!=="ENABLE_VIDEO_SEI"&&e!=="ENABLE_AUDIO_TOPN"&&e!=="ENABLE_AUDIO_METADATA"&&e!=="ENABLE_AUDIO_PTS"||t!==!0||(tt.ENABLE_ENCODED_TRANSFORM=!0),e==="USE_NEW_NETWORK_CONFIG"&&t&&(o=!!t,tt.USE_NEW_NETWORK_CONFIG=o,o&&(tt.WEBCS_DOMAIN=["webrtc2-2.ap.sd-rtn.com"],tt.WEBCS_DOMAIN_BACKUP_LIST=["webrtc2-4.ap.sd-rtn.com"],tt.CDS_AP=["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],tt.ACCOUNT_REGISTER=["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],tt.EVENT_REPORT_DOMAIN="web-2.statscollector.sd-rtn.com",tt.EVENT_REPORT_BACKUP_DOMAIN="statscollector-1.agora.io",tt.GATEWAY_DOMAINS=["edge.sd-rtn.com"])),e==="ENABLE_PRE_SUB"&&t&&(tt.ENABLE_INSTANT_VIDEO=!0,tt.ENABLE_PREALLOC_PC=!0),e==="ENABLE_SVC"&&t&&(tt.ENABLE_AUT_CC=!0),e==="NEW_FORCE_TURN"&&t&&(tt.NEW_TURN_MODE||(tt.NEW_TURN_MODE=4))))}function T(e){if(e==="TURN_DOMAINS"){const t=tt.TURN_DOMAINS;return x(t).call(t,T("TURN_DOMAIN"))?t:[T("TURN_DOMAIN")].concat(t)}return tt[e]}pS||(tt.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],tt.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],tt.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],tt.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],tt.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],tt.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],tt.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",tt.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",tt.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",tt.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",tt.AREAS=["NORTH_AMERICA","OVERSEA"]);let WO=function(e){return e[e.REALTIME=1]="REALTIME",e}({});const Zi={};var pe=function(e){return e.SET_SESSION_ID="SET_SESSION_ID",e.SET_RTE_
42URL="SET_RTE_URL",e.SET_RTE_SID="SET_RTE_SID",e.SET_P2P_ID="SET_P2P_id",e.SET_DC_ID="SET_DC_id",e.SET_UID="SET_UID",e.SET_INT_UID="SET_INT_UID",e.SET_PUB_ID="SET_PUB_ID",e.SET_CLOUD_PROXY_SERVER_MODE="SET_CLOUD_PROXY_SERVER_MODE",e.KEY_METRIC_CLIENT_CREATED="KEY_METRIC_CLIENT_CREATED",e.KEY_METRIC_JOIN_START="KEY_METRIC_JOIN_START",e.KEY_METRIC_PRELOAD_START="KEY_METRIC_PRELOAD_START",e.KEY_METRIC_PRELOAD_END="KEY_METRIC_PRELOAD_END",e.KEY_METRIC_JOIN_END="KEY_METRIC_JOIN_END",e.KEY_METRIC_REQUEST_AP_START="KEY_METRIC_REQUEST_AP_START",e.KEY_METRIC_REQUEST_AP_END="KEY_METRIC_REQUEST_AP_END",e.KEY_METRIC_REQUEST_SUA_END="KEY_METRIC_REQUEST_SUA_END",e.KEY_METRIC_BEFORE_CONNECT="KEY_METRIC_BEFORE_CONNECT",e.KEY_METRIC_PEER_RECEIVER="KEY_METRIC_PEER_RECEIVER",e.KEY_METRIC_SIGNAL_CONNECTED="KEY_METRIC_SIGNAL_CONNECTED",e.KEY_METRIC_JOIN_REQ="KEY_METRIC_JOIN_REQ",e.KEY_METRIC_JOIN_REP="KEY_METRIC_JOIN_REP",e.KEY_METRIC_JOIN_GATEWAY_START="KEY_METRIC_JOIN_GATEWAY_START",e.KEY_METRIC_JOIN_GATEWAY_END="KEY_METRIC_JOIN_GATEWAY_END",e.KEY_METRIC_PEER_CONNECTION_START="KEY_METRIC_PEER_CONNECTION_START",e.KEY_METRIC_PEER_CONNECTION_END="KEY_METRIC_PEER_CONNECTION_END",e.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED="KEY_METRIC_FIRST_VIDEO_FRAME_DECODED",e.KEY_METRIC_DESCRIPTION_START="KEY_METRIC_DESCRIPTION_START",e.KEY_METRIC_ICE_CONNECTION_END="KEY_METRIC_ICE_CONNECTION_END",e.KEY_METRIC_SIGNAL_CHANNEL_OPEN="KEY_METRIC_SIGNAL_CHANNEL_OPEN",e.KEY_METRIC_PUBLISH="KEY_METRIC_PUBLISH",e.KEY_METRIC_SUBSCRIBE="KEY_METRIC_SUBSCRIBE",e.RECORD_JOIN_CHANNEL_SERVICE="RECORD_JOIN_CHANNEL_SERVICE",e.RESET_JOIN_CHANNEL_SERVICE_RECORDS="RESET_JOIN_CHANNEL_SERVICE_RECORDS",e.RESET_KEY_METRICS="RESET_KEY_METRICS",e.RESET_FIRST_VIDEO_FRAME_DECODED="RESET_FIRST_VIDEO_FRAME_DECODED",e.SET_USE_P2P="SET_USE_P2P",e.SET_TRANSPORT_TYPE="SET_TRANSPORT_TYPE",e}(pe||{});let Ma=function(e){return e.h264="h264",e.h265="h265",e.vp8="vp8",e.vp9="vp9",e.av1="av1",e}({});(function(e){e.opus="opus",e.pcma="pcma",e.pcmu="pcmu",e.g722="g722"})({});const KO=128,J9=96,HO=1e3,ad=10;let z9=0;var YO=(()=>{var e={8:(i,r,o)=>{o.r(r),o.d(r,{Parser:()=>U,Printer:()=>me,parse:()=>F,print:()=>J});const s=` 43`,a="".concat("\r").concat(s),c=" ";let d;function l(V){return V>="0"&&V<="9"}function h(V){return V>="!"&&V<="~"}function u(V){return h(V)||V>="\x80"&&V<="\xFF"}function p(V){return V==="!"||V>="#"&&V<="'"||V>="*"&&V<="+"||V>="-"&&V<="."||V>="0"&&V<="9"||V>="A"&&V<="Z"||V>="^"&&V<="~"}function E(V){return V>="1"&&V<="9"}function m(V){return V>="A"&&V<="Z"||V>="a"&&V<="z"}function g(V){return V==="d"||V==="h"||V==="m"||V==="s"}function R(V){return V>"�"&&V<" "||V>"\v"&&V<"\f"||V>"�"&&V<"\xFF"}function v(V){return m(V)||l(V)||V==="+"||V==="/"}function C(V){return l(V)||m(V)||V==="+"||V==="/"||V==="-"||V==="_"}function w(V){return m(V)||l(V)||V==="+"||V==="/"}function b(V,f){var I=Object.keys(V);if(Object.getOwnPropertySymbols){var O=Object.getOwnPropertySymbols(V);f&&(O=O.filter(function(B){return Object.getOwnPropertyDescriptor(V,B).enumerable})),I.push.apply(I,O)}return I}function y(V){for(var f=1;f<arguments.length;f++){var I=arguments[f]!=null?arguments[f]:{};f%2?b(Object(I),!0).forEach(function(O){N(V,O,I[O])}):Object.getOwnPropertyDescriptors?Object.defineProperties(V,Object.getOwnPropertyDescriptors(I)):b(Object(I)).forEach(function(O){Object.defineProperty(V,O,Object.getOwnPropertyDescriptor(I,O))})}return V}function N(V,f,I){return f in V?Object.defineProperty(V,f,{value:I,enumerable:!0,configurable:!0,writable:!0}):V[f]=I,V}(function(V){V.VERSION="v",V.ORIGIN="o",V.SESSION_NAME="s",V.INFORMATION="i",V.URI="u",V.EMAIL="e",V.PHONE="p",V.CONNECTION="c",V.BANDWIDTH="b",V.TIME="t",V.REPEAT="r",V.ZONE_ADJUSTMENTS="z",V.KEY="k",V.ATTRIBUTE="a",V.MEDIA="m"})(d||(d={}));class k{consumeText(f,I){let O=I;for(;O<f.length;){const B=f[O];if(B==="\0"||B==="\r"||B===s)break;O+=1}if(O-I==0)throw new Error("Invalid text, at ".concat(f));return O}consumeUnicastAddress(f,I,O){return this.consumeTill(f,I,c)}consumeOneOrMore(f,I,O){let B=I;for(;O(f[B]);)B++;if(B-I==0)throw new Error("Invalid rule at ".concat(I,"."));return B}consumeSpace(f,I){if(f[I]===c)return I+1;throw new Error("Invalid space at ".concat(I,"."))}consumeIP4Address(f,I){let O=I;for(let B=0;B<4;B++)if(O=this.consumeDecimalUChar(f,O),B!==3){if(f[O]!==".")throw new Error("Invalid IP4 address.");O++}return O}consumeDecimalUChar(f,I){let O=I;for(let ne=0;ne<3&&l(f[O]);ne++,O++);if(O-I==0)throw new Error("Invalid decimal uchar.");const B=parseInt(f.slice(I,O));if(B>=0&&B<=255)return O;throw new Error("Invalid decimal uchar")}consumeIP6Address(f,I){let O=this.consumeHexpart(f,I);return f[O]===":"&&(O+=1,O=this.consumeIP4Address(f,O)),O}consumeHexpart(f,I){let O=I;if(f[O]===":"&&f[O+1]===":"){O+=2;try{O=this.consumeHexseq(f,O)}catch{}return O}if(O=this.consumeHexseq(f,O),f[O]===":"&&f[O+1]===":"){O+=2;try{O=this.consumeHexseq(f,O)}catch{}return O}return O}consumeHexseq(f,I){let O=I;for(;O=this.consumeHex4(f,O),f[O]===":"&&f[O+1]!==":";)O+=1;return O}consumeHex4(f,I){let O=0;for(;O<4;O++)if(!((B=f[I+O])>="0"&&B<="9"||B>="a"&&B<="f"||B>="A"&&B<="F")){if(O===0)throw new Error("Invalid hex 4");break}var B;return I+O}consumeFQDN(f,I){let O=I;for(;l(f[O])||m(f[O])||f[O]==="-"||f[O]===".";)O+=1;if(O-I<4)throw new Error("Invalid FQDN");return O}consumeExtnAddr(f,I){return this.consumeOneOrMore(f,I,u)}consumeMulticastAddress(f,I,O){switch(O){case"IP4":case"ip4":return this.consumeIP4MulticastAddress(f,I);case"IP6":case"ip6":return this.consumeIP6MulticastAddress(f,I);default:try{return this.consumeFQDN(f,I)}catch{return this.consumeExtnAddr(f,I)}}}consumeIP6MulticastAddress(f,I){const O=this.consumeHexpart(f,I);return f[O]==="/"?this.consumeInteger(f,O+1):O}consumeIP4MulticastAddress(f,I){let O=I+3;const B=f.slice(I,O),ne=parseInt(B);if(ne<224||ne>239)throw new Error("Invalid IP4 multicast address, IPv4 multicast addresses may be in the range 224.0.0.0 to 239.255.255.255.");for(let Ge=0;Ge<3;Ge++){if(f[O]!==".")throw new Error("Invalid IP4 multicast address.");O+=1,O=this.consumeDecimalUChar(f,O)}
43return f[O]==="/"&&(O+=1),O=this.consumeTTL(f,O),f[O]==="/"&&(O=this.consumeInteger(f,O)),O}consumeInteger(f,I){if(!E(f[I]))throw new Error("Invalid integer.");for(I+=1;l(f[I]);)I+=1;return I}consumeTTL(f,I){if(f[I]==="0")return I+1;if(!E(f[I]))throw new Error("Invalid TTL.");I+=1;for(let O=0;O<2&&l(f[I]);O++)I+=1;return I}consumeToken(f,I){return this.consumeOneOrMore(f,I,p)}consumeTime(f,I){let O=I;if(f[O]==="0")return O+1;for(E(f[O])&&(O+=1);l(f[O]);)O++;if(O-I<10)throw new Error("Invalid time");return O}consumeAddress(f,I){return this.consumeTill(f,I,c)}consumeTypedTime(f,I){let O=I;return O=this.consumeOneOrMore(f,O,l),g(f[O])?O+1:O}consumeRepeatInterval(f,I){if(!E(f[I]))throw new Error("Invalid repeat interval");for(I+=1;l(f[I]);)I+=1;return g(f[I])&&(I+=1),I}consumePort(f,I){return this.consumeOneOrMore(f,I,l)}consume(f,I,O){for(let B=0;B<O.length;B++){if(I+B>=f.length)throw new Error("consume exceeding value length");if(f[I+B]!==O[B])throw new Error("consume ".concat(O," failed at ").concat(B))}return I+O.length}consumeTill(f,I,O){let B=I;for(;B<f.length&&(typeof O!="string"||f[B]!==O)&&(typeof O!="function"||!O(f[B]));)B++;return B}}class U extends k{constructor(){super(),N(this,"records",[]),N(this,"currentLine",0)}parse(f){const I=this.probeEOL(f);this.records=f.split(I).filter(mc=>!!Mn(mc).call(mc)).map(this.parseLine),this.currentLine=0;const O=this.parseVersion(),B=this.parseOrigin(),ne=this.parseSessionName(),Ge=this.parseInformation(),Tn=this.parseUri(),yi=this.parseEmail(),Ss=this.parsePhone(),_c=this.parseConnection(),Yu=this.parseBandWidth(),km=this.parseTimeFields(),Mm=this.parseKey(),Cr=this.parseSessionAttribute(),ca=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error("parsing failed, non exhaustive sdp lines.");return{version:O,origin:B,sessionName:ne,information:Ge,uri:Tn,emails:yi,phones:Ss,connection:_c,bandwidths:Yu,timeFields:km,key:Mm,attributes:Cr,mediaDescriptions:ca}}getCurrentRecord(){const f=this.records[this.currentLine];if(!f)throw new Error("Record doesn't exit.");return f}probeEOL(f){for(let I=0;I<f.length;I++)if(f[I]===s)return f[I-1]==="\r"?a:s;throw new Error("Invalid newline character.")}parseLine(f,I){if(f.length<2)throw new Error("Invalid sdp line, sdp line should be of form <type>=<value>.");const O=f[0];if(f[1]!=="=")throw new Error('Invalid sdp line, <type> should be a single character followed by an "=" sign.');return{type:O,value:f.slice(2),line:I,cur:0}}parseSessionAttribute(){const f=new q;for(;this.currentLine<this.records.length;){const I=this.getCurrentRecord();if(I.type!==d.ATTRIBUTE)break;const O={attField:this.extractOneOrMore(I,B=>p(B)&&B!==":"),_cur:0};I.value[I.cur]===":"&&(I.cur+=1,O.attValue=this.extractOneOrMore(I,R)),f.parse(O),this.currentLine++}return f.digest()}parseMediaAttributes(f){const I=new se(f);for(;this.currentLine<this.records.length;){const O=this.getCurrentRecord();if(O.type!==d.ATTRIBUTE)break;const B={attField:this.extractOneOrMore(O,ne=>p(ne)&&ne!==":"),_cur:0};O.value[O.cur]===":"&&(O.cur+=1,B.attValue=this.extractOneOrMore(O,R)),I.parse(B),this.currentLine++}return I.digest()}parseKey(){const f=this.getCurrentRecord();if(f.type===d.KEY){if(f.value==="prompt"||f.value==="clear:"||f.value==="base64:"||f.value==="uri:")return f.value;throw this.currentLine++,new Error("Invalid key.")}}parseZone(){const f=this.getCurrentRecord();if(f.type===d.ZONE_ADJUSTMENTS){const I=[];for(;;)try{const O=this.extract(f,this.consumeTime);this.consumeSpaceForRecord(f);let B=!1;f.value[f.cur]==="-"&&(B=!0,f.cur+=1);const ne=this.extract(f,this.consumeTypedTime);I.push({time:O,typedTime:ne,back:B})}catch{break}if(I.length===0)throw new Error("Invalid zone adjustments");return this.currentLine++,I}return[]}parseRepeat(){const f=[];for(;;){const I=this.getCurrentRecord();if(I.type!==d.REPEAT)break;{const O=this.extract(I,this.consumeRepeatInterval),B=this.parseTypedTime(I);f.push({repeatInterval:O,typedTimes:B}),this.currentLine++}}return f}parseTypedTime(f){const I=[];for(;;)try{this.consumeSpaceForRecord(f),I.push(this.extract(f,this.consumeTypedTime))}catch{break}if(I.length===0)throw new Error("Invalid typed time.");return I}parseTime(){const f=this.getCurrentRecord(),I=this.extract(f,this.consumeTime);this.consumeSpaceForRecord(f);const O=this.extract(f,this.consumeTime);return this.currentLine++,{startTime:I,stopTime:O}}parseBandWidth(){const f=[];for(;this.currentLine<this.records.length;){const I=this.getCurrentRecord();if(I.type!==d.BANDWIDTH)break;{const O=this.extractOneOrMore(I,p);if(I.value[I.cur]!==":")throw new Error("Invalid bandwidth field.");I.cur++;const B=this.extractOneOrMore(I,l);f.push({bwtype:O,bandwidth:B}),this.currentLine++}}return f}parseVersion(){const f=this.getCurrentRecord();if(f.type!==d.VERSION)throw new Error("first sdp record must be version");const I=f.value.slice(0,this.consumeOneOrMore(f.value,0,l));if(I.length!==f.value.length)throw new Error('invalid proto version, "v='.concat(f.value,'"'));return this.currentLine++,I}parseOrigin(){const f=this.getCurrentRecord();if(f.type!==d.ORIGIN)throw new Error("second line of sdp must be origin");const I=this.extractOneOrMore(f,u);this.consumeSpaceForRecord(f);const O=this.extractOneOrMore(f,l);this.consumeSpaceForRecord(f);const B=this.extractOneOrMore(f,l);this.consumeSpaceForRecord(f);const ne=this.extractOneOrMore(f,p);this.consumeSpaceForRecord(f);const Ge=this.extractOneOrMore(f,p);this.consumeSpaceForRecord(f);const Tn=this.extract(f,this.consumeUnicastAddress);return this.currentLine++,{username:I,sessId:O,sessVersion:B,nettype:ne,addrtype:Ge,unicastAddress:Tn}}parseSessionName(){const f=this.getCurrentRecord();if(f.type===d.SESSION_NAME){const I=this.extract(f,this.consumeText);return this.currentLine++,I}}parseInformation(){const f=this.getCurrentRecord();if(f.type!==d.INFORMATION)return;const I=this.extract(f,this.consumeText);return this.currentLine++,I}parseUri(){const f=this.getCurrentRecord();if(f.type===d.URI)return this.currentLine++,f.value}parseEmail(){const f=[];for(;;){const I=this.getCurrentRecord();if(I.type!==d.EMAIL)break;f.push(I.value),this.currentLine++}return f}parsePhone(){const f=[];for(;;){const I=this.getCurrentRecord();if(I.type!==d.PHONE)break;f.push(I.value),this.currentLine++}return f}parseConnection(){const f=this.getCurrentRecord();if(f.type===d.CONNECTION){const I=this.extractOneOrMore(f,p);this.consumeSpaceForRecord(f);const O=this.extractOneOrMore(f,p);this.consumeSpaceForRecord(f);const B=this.extract(f,this.consumeAddress);return this.currentLine++,{nettype:I,addrtype:O,address:B}}}parseMedia(){const f=this.getCurrentRecord(),I=this.extract(f,this.consumeToken);this.consumeSpaceForRecord(f);let O=this.extract(f,this.consumePort);f.value[f.cur]==="/"&&(f.cur+=1,O+=this.extract(f,this.consumeInteger)),this.consumeSpaceForRecord(f);const B=[];for(B.push(this.extract(f,this.consumeToken));f.value[f.cur]==="/";)f.cur+=1,B.push(this.extract(f,this.consumeToken));if(B.length===0)throw new Error("Invalid proto");const ne=this.parseFmt(f);return this.currentLine++,{mediaType:I,port:O,protos:B,fmts:ne}}parseTimeFields(){const f=[];for(;this.getCurrentRecord().type===d.TIME;){const I=this.parseTime(),O=this.parseRepeat(),B=this.parseZone();f.push({time:I,repeats:O,zones:B})}return f}parseMediaDescription(){const f=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===d.MEDIA;){const I=this.parseMedia(),O=this.parseInformation(),B=this.parseConnections(),ne=this.parseBandWidth(),Ge=this.parseKey(),Tn=this.parseMediaAttributes(I);f.push({media:I,information:O,connections:B,bandwidths:ne,key:Ge,attributes:Tn})}return f}parseConnections(){const f=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===d.CONNECTION;)f.push(this.parseConnection());return f}parseFmt(f){const I=[];for(;;)try{this.consumeSpaceForRecord(f),I.push(this.extract(f,this.consumeToken))}catch{break}if(I.length===0)throw new Error("Invalid fmts");return I}extract(f,I){for(var O=arguments.length,B=new Array(O>2?O-2:0),ne=2;ne<O;ne++)B[ne-2]=arguments[ne];const Ge=I.call(this,f.value,f.cur,...B),Tn=f.value.slice(f.cur,Ge);return f.cur=Ge,Tn}extractOneOrMore(f,I){const O=this.consumeOneOrMore(f.value,f.cur,I),B=f.value.slice(f.cur,O);return f.cur=O,B}consumeSpaceForRecord(f){if(f.value[f.cur]!==c)throw new Error("Invalid space at ".concat(f.cur,"."));f.cur+=1}}class X extends k{constructor(){super(...arguments),N(this,"attributes",void 0),N(this,"digested",!1)}extractOneOrMore(f,I,O){const B=this.consumeOneOrMore(f.attValue,f._cur,I),ne=f.attValue.slice(f._cur,B),[Ge,Tn]=O||[];if(typeof Ge=="number"&&ne.length<Ge)throw new Error("error in length, should be more or equal than ".concat(Ge," characters."));if(typeof Tn=="number"&&ne.length>Tn)throw new Error("error in length, should be less or equal than ".concat(Tn," characters."));return f._cur=B,ne}consumeAttributeSpace(f){if(f.attValue[f._cur]!==c)throw new Error("Invalid space at ".concat(f._cur,"."));f._cur+=1}extract(f,I){if(!f.attValue)throw new Error("Nothing to extract from attValue.");for(var O=arguments.length,B=new Array(O>2?O-2:0),ne=2;ne<O;ne++)B[ne-2]=arguments[ne];const Ge=I.call(this,f.attValue,f._cur,...B),Tn=f.attValue.slice(f._cur,Ge);return f._cur=Ge,Tn}atEnd(f){if(!f.attValue)throw new Error;return f._cur>=f.attValue.length}peekChar(f){if(!f.attValue)throw new Error;return f.attValue[f._cur]}peek(f,I){if(!f.attValue)throw new Error;for(let O=0;O<I.length;O++)if(I[O]!==f.attValue[f._cur+O])return!1;return!0}parseIceUfrag(f){if(this.attributes.iceUfrag)throw new Error("Invalid ice-ufrag, should be only a single line if 'a=ice-ufrag'");this.attributes.iceUfrag=this.extractOneOrMore(f,v,[4,256])}parseIcePwd(f){if(this.attributes.icePwd)throw new Error("Invalid ice-pwd, should be only a single line if 'a=ice-pwd'");this.attributes.icePwd=this.extractOneOrMore(f,v,[22,256])}parseIceOptions(f){if(this.attributes.iceOptions)throw new Error("Invalid ice-options, should be only one 'ice-options' line");const I=[];for(;!this.atEnd(f);){I.push(this.extractOneOrMore(f,v));try{this.consumeAttributeSpace(f)}catch(O){if(this.atEnd(f))break;throw O}}this.attributes.iceOptions=I}parseFingerprint(f){const I=this.extract(f,this.consumeToken);this.consumeAttributeSpace(f);const O=this.extract(f,this.consumeTill);this.attributes.fingerprints.push({hashFunction:I,fingerprint:O})}parseExtmap(f){const I=this.extractOneOrMore(f,l);let O;this.peekChar(f)==="/"&&(this.extract(f,this.consume,"/"),O=this.extract(f,this.consumeToken)),this.consumeAttributeSpace(f);const B=this.extract(f,this.consumeTill,c),ne=y(y({entry:parseInt(I,10)},O&&{direction:O}),{},{extensionName:B});this.peekChar(f)===c&&(this.consumeAttributeSpace(f),ne.extensionAttributes=this.extract(f,this.consumeTill)),this.attributes.extmaps.push(ne)}parseSetup(f){if(this.attributes.setup)throw new Error("must only be one single 'a=setup' line.");const I=this.extract(f,this.consumeTill);if(I!=="active"&&I!=="passive"&&I!=="actpass"&&I!=="holdconn")throw new Error("role must be one of 'active', 'passive', 'actpass', 'holdconn'.");this.attributes.setup=I}}class q extends X{constructor(){super(...arguments),N(this,"attributes",{unrecognized:[],groups:[],extmaps:[],fingerprints:[],identities:[]})}parse(f){if(this.digested)throw new Error("already digested");try{switch(f.attField){case"group":this.parseGroup(f);break;case"ice-lite":this.parseIceLite();break;case"ice-ufrag":this.parseIceUfrag(f);break;case"ice-pwd":this.parseIcePwd(f);break;case"ice-options":this.parseIceOptions(f);break;case"fingerprint":this.parseFingerprint(f);break;case"setup":this.parseSetup(f);break;case"tls-id":this.parseTlsId(f);break;case"identity":this.parseIdentity(f);break;case"extmap":this.parseExtmap(f);break;case"msid-semantic":this.parseMsidSemantic(f);break;default:f.ignored=!0,this.attributes.unrecognized.push(f)}}catch(I){throw console.error("parsing session attribute ".concat(f.attField,' error, "a=').concat(f.attField,":").concat(f.attValue,'"')),I}if(!f.ignored&&f.attValue&&!this.atEnd(f))throw new Error("attribute parsing error")}
43digest(){return this.digested=!0,this.attributes}parseGroup(f){const I=this.extract(f,this.consumeToken),O=[];for(;!this.atEnd(f)&&this.peekChar(f)===c;)this.consumeAttributeSpace(f),O.push(this.extract(f,this.consumeToken));this.attributes.groups.push({semantic:I,identificationTag:O})}parseIceLite(){if(this.attributes.iceLite)throw new Error("Invalid ice-lite, should be only a single line of 'a=ice-lite'");this.attributes.iceLite=!0}parseTlsId(f){if(this.attributes.tlsId)throw new Error("must be only one tld-id line");this.attributes.tlsId=this.extractOneOrMore(f,C)}parseIdentity(f){const I=this.extractOneOrMore(f,w),O=[];for(;!this.atEnd(f)&&this.peekChar(f)===c;){this.consumeAttributeSpace(f);const B=this.extract(f,this.consumeToken);this.extract(f,this.consume,"=");const ne=this.extractOneOrMore(f,Ge=>Ge!==c&&R(Ge));O.push({name:B,value:ne})}this.attributes.identities.push({assertionValue:I,extensions:O})}parseMsidSemantic(f){this.peekChar(f)===c&&this.consumeAttributeSpace(f);const I={semantic:this.extract(f,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(f)}catch{break}if(this.peekChar(f)==="*"){this.extract(f,this.consume,"*"),I.applyForAll=!0;break}{const O=this.extract(f,this.consumeTill,c);I.identifierList.push(O)}}this.attributes.msidSemantic=I}}class se extends X{constructor(f){super(),N(this,"attributes",void 0),f.protos.indexOf("RTP")!==-1||f.protos.indexOf("rtp"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]}}parse(f){if(this.digested)throw new Error("already digested");try{switch(f.attField){case"extmap":this.parseExtmap(f);break;case"setup":this.parseSetup(f);break;case"ice-ufrag":this.parseIceUfrag(f);break;case"ice-pwd":this.parseIcePwd(f);break;case"ice-options":this.parseIceOptions(f);break;case"candidate":this.parseCandidate(f);break;case"remote-candidate":this.parseRemoteCandidate(f);break;case"end-of-candidates":this.parseEndOfCandidates();break;case"fingerprint":this.parseFingerprint(f);break;case"rtpmap":this.parseRtpmap(f);break;case"ptime":this.parsePtime(f);break;case"maxptime":this.parseMaxPtime(f);break;case"sendrecv":case"recvonly":case"sendonly":case"inactive":this.parseDirection(f);break;case"ssrc":this.parseSSRC(f);break;case"fmtp":this.parseFmtp(f);break;case"rtcp-fb":this.parseRtcpFb(f);break;case"rtcp-mux":this.parseRTCPMux();break;case"rtcp-mux-only":this.parseRTCPMuxOnly();break;case"rtcp-rsize":this.parseRTCPRsize();break;case"rtcp":this.parseRTCP(f);break;case"mid":this.parseMid(f);break;case"msid":this.parseMsid(f);break;case"imageattr":this.parseImageAttr(f);break;case"rid":this.parseRid(f);break;case"simulcast":this.parseSimulcast(f);break;case"sctp-port":this.parseSctpPort(f);break;case"max-message-size":this.parseMaxMessageSize(f);break;case"ssrc-group":this.parseSSRCGroup(f);break;default:f.ignored=!0,this.attributes.unrecognized.push(f)}}catch(I){throw console.error("parsing media attribute ".concat(f.attField,' error, "a=').concat(f.attField,":").concat(f.attValue,'"')),I}if(!f.ignored&&f.attValue&&!this.atEnd(f))throw new Error("attribute parsing error")}parseCandidate(f){const I=this.extractOneOrMore(f,v,[1,32]);this.consumeAttributeSpace(f);const O=this.extractOneOrMore(f,l,[1,5]);this.consumeAttributeSpace(f);const B=this.extract(f,this.consumeToken);this.consumeAttributeSpace(f);const ne=this.extractOneOrMore(f,l,[1,10]);this.consumeAttributeSpace(f);const Ge=this.extract(f,this.consumeAddress);this.consumeAttributeSpace(f);const Tn=this.extract(f,this.consumePort);this.consumeAttributeSpace(f),this.extract(f,this.consume,"typ"),this.consumeAttributeSpace(f);const yi={foundation:I,componentId:O,transport:B,priority:ne,connectionAddress:Ge,port:Tn,type:this.extract(f,this.consumeToken),extension:{}};for(this.peek(f," raddr")&&(this.extract(f,this.consume," raddr"),this.consumeAttributeSpace(f),yi.relAddr=this.extract(f,this.consumeAddress)),this.peek(f," rport")&&(this.extract(f,this.consume," rport"),this.consumeAttributeSpace(f),yi.relPort=this.extract(f,this.consumePort));this.peekChar(f)===c;){this.consumeAttributeSpace(f);const Ss=this.extract(f,this.consumeToken);this.consumeAttributeSpace(f),yi.extension[Ss]=this.extractOneOrMore(f,h)}this.attributes.candidates.push(yi)}parseRemoteCandidate(f){const I=[];for(;;){const O=this.extractOneOrMore(f,l,[1,5]);this.consumeAttributeSpace(f);const B=this.extract(f,this.consumeAddress);this.consumeAttributeSpace(f);const ne=this.extract(f,this.consumePort);I.push({componentId:O,connectionAddress:B,port:ne});try{this.consumeAttributeSpace(f)}catch{break}}this.attributes.remoteCandidatesList.push(I)}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error("must be only one line of end-of-candidates");this.attributes.endOfCandidates=!0}parseRtpmap(f){const I=this.extract(f,this.consumeToken);this.consumeAttributeSpace(f);const O=this.extract(f,this.consumeTill,"/");this.extract(f,this.consume,"/");const B={encodingName:O,clockRate:this.extractOneOrMore(f,l)};this.atEnd(f)||this.peekChar(f)!=="/"||(this.extract(f,this.consume,"/"),B.encodingParameters=parseInt(this.extract(f,this.consumeTill),10));const ne=this.attributes.payloads.find(Ge=>Ge.payloadType===parseInt(I,10));ne?ne.rtpMap=B:this.attributes.payloads.push({payloadType:parseInt(I,10),rtpMap:B,rtcpFeedbacks:[]})}parsePtime(f){if(this.attributes.ptime)throw new Error("must be only one line of ptime");this.attributes.ptime=this.extract(f,this.consumeTill)}parseMaxPtime(f){if(this.attributes.maxPtime)throw new Error("must be only one line of ptime");this.attributes.maxPtime=this.extract(f,this.consumeTill)}parseDirection(f){if(this.attributes.direction)throw new Error("must be only one line of direction info");this.attributes.direction=f.attField}parseSSRC(f){const I=this.extractOneOrMore(f,l);this.consumeAttributeSpace(f);const O=this.extract(f,this.consumeTill,":");let B;this.peekChar(f)===":"&&(this.extract(f,this.consume,":"),B=this.extract(f,this.consumeTill));const ne=this.attributes.ssrcs.find(Ge=>Ge.ssrcId===parseInt(I,10));ne?ne.attributes[O]=B:this.attributes.ssrcs.push({ssrcId:parseInt(I,10),attributes:{[O]:B}})}parseFmtp(f){const I=this.extract(f,this.consumeTill,c);this.consumeAttributeSpace(f);const O=this.extract(f,this.consumeTill),B={};O.split(";").forEach(Ge=>{let[Tn,yi]=Ge.split("=");Tn=Mn(Tn).call(Tn);
43const Ss=typeof yi=="string"?Mn(yi).call(yi):null;typeof Tn=="string"&&Tn.length>0&&(B[Tn]=Ss)});const ne=this.attributes.payloads.find(Ge=>Ge.payloadType===parseInt(I,10));ne?ne.fmtp={parameters:B}:this.attributes.payloads.push({payloadType:parseInt(I,10),rtcpFeedbacks:[],fmtp:{parameters:B}})}parseFmtParameters(f){const I={},O=this.extract(f,this.consumeTill,"=");f._cur++;const B=this.extract(f,this.consumeTill,";");for(I[O]=B;f.attValue[f._cur]===";";){const ne=this.extract(f,this.consumeTill,"=");f._cur++;const Ge=this.extract(f,this.consumeTill,";");I[ne]=Ge}return I}parseRtcpFb(f){let I="";I=this.peekChar(f)==="*"?this.extract(f,this.consume,"*"):this.extract(f,this.consumeTill,c),this.consumeAttributeSpace(f);const O=this.extract(f,this.consumeTill,c);let B;if(O==="trr-int")B={type:O,interval:this.extract(f,this.consumeTill)};else{const ne={type:O};this.peekChar(f)===c&&(this.consumeAttributeSpace(f),ne.parameter=this.extract(f,this.consumeToken),this.peekChar(f)===c&&(ne.additional=this.extract(f,this.consumeTill))),B=ne}if(I==="*")this.attributes.rtcpFeedbackWildcards.push(B);else{const ne=this.attributes.payloads.find(Ge=>Ge.payloadType===parseInt(I,10));ne?ne.rtcpFeedbacks.push(B):this.attributes.payloads.push({payloadType:parseInt(I,10),rtcpFeedbacks:[B]})}}parseRTCPMux(){if(this.attributes.rtcpMux)throw new Error("must be single line of rtcp-mux");this.attributes.rtcpMux=!0}parseRTCPMuxOnly(){if(this.attributes.rtcpMuxOnly)throw new Error("must be single line of rtcp-only");this.attributes.rtcpMuxOnly=!0}parseRTCPRsize(){if(this.attributes.rtcpRsize)throw new Error("must be single line of rtcp-rsize");this.attributes.rtcpRsize=!0}parseRTCP(f){if(this.attributes.rtcp)throw new Error("must be single line of rtcp");const I={port:this.extract(f,this.consumePort)};this.peekChar(f)===c&&(this.consumeAttributeSpace(f),I.netType=this.extractOneOrMore(f,p),this.consumeAttributeSpace(f),I.addressType=this.extractOneOrMore(f,p),this.consumeAttributeSpace(f),I.address=this.extract(f,this.consumeAddress)),this.attributes.rtcp=I}parseMsid(f){const I={id:this.extractOneOrMore(f,p,[1,64])};this.peekChar(f)===c&&(this.consumeAttributeSpace(f),I.appdata=this.extractOneOrMore(f,p,[1,64])),this.attributes.msids.push(I)}parseImageAttr(f){this.attributes.imageattr.push(f.attValue)}parseRid(f){const I=this.extractOneOrMore(f,B=>m(B)||l(B)||B==="_"||B==="-");this.consumeAttributeSpace(f);const O={id:I,direction:this.extract(f,this.consumeToken),params:[]};if(this.peekChar(f)===c){if(this.consumeAttributeSpace(f),this.peek(f,"pt=")){this.extract(f,this.consume,"pt=");const B=[];for(;;){const ne=this.extract(f,this.consumeToken);B.push(ne);try{this.extract(f,this.consume,",")}catch{break}}O.payloads=B,this.peekChar(f)===c&&this.extract(f,this.consume,c)}for(;;){const B=this.extract(f,this.consumeToken);switch(B){case"depend":{const ne={type:B,rids:this.extract(f,this.consume,"=").split(",")};O.params.push(ne);break}default:{const ne={type:B};this.peekChar(f)==="="&&(this.extract(f,this.consume,"="),ne.val=this.extract(f,this.consumeTill,";")),O.params.push(ne)}}try{this.extract(f,this.consume,";")}catch{break}}}this.attributes.rids.push(O)}parseSimulcast(f){if(this.attributes.simulcast)throw new Error("must be single line of simulcast");this.attributes.simulcast=f.attValue,this.extract(f,this.consumeTill)}parseSctpPort(f){this.attributes.sctpPort=this.extractOneOrMore(f,l,[1,5])}parseMaxMessageSize(f){this.attributes.maxMessageSize=this.extractOneOrMore(f,l,[1,void 0])}digest(){return this.digested=!0,this.attributes}parseMid(f){this.attributes.mid=this.extract(f,this.consumeToken)}parseSSRCGroup(f){const I=this.extract(f,this.consumeToken),O=[];for(;;)try{this.consumeAttributeSpace(f);const B=this.extract(f,this.consumeInteger);O.push(parseInt(B,10))}catch{break}this.attributes.ssrcGroups.push({semantic:I,ssrcIds:O})}}function _e(V,f,I){return f in V?Object.defineProperty(V,f,{value:I,enumerable:!0,configurable:!0,writable:!0}):V[f]=I,V}class me{constructor(){_e(this,"eol",a)}print(f,I){let O="";return I&&(this.eol=I),O+=this.printVersion(f.version),O+=this.printOrigin(f.origin),O+=this.printSessionName(f.sessionName),O+=this.printInformation(f.information),O+=this.printUri(f.uri),O+=this.printEmail(f.emails),O+=this.printPhone(f.phones),O+=this.printConnection(f.connection),O+=this.printBandwidth(f.bandwidths),O+=this.printTimeFields(f.timeFields),O+=this.printKey(f.key),O+=this.printSessionAttributes(f.attributes),O+=this.printMediaDescription(f.mediaDescriptions),O}printVersion(f){return"v=".concat(f).concat(this.eol)}printOrigin(f){return"o=".concat(f.username," ").concat(f.sessId," ").concat(f.sessVersion," ").concat(f.nettype," ").concat(f.addrtype," ").concat(f.unicastAddress).concat(this.eol)}printSessionName(f){return f?"s=".concat(f).concat(this.eol):""}printInformation(f){return f?"i=".concat(f).concat(this.eol):""}printUri(f){return f?"u=".concat(f).concat(this.eol):""}printEmail(f){let I="";for(const O of f)I+="e=".concat(O).concat(this.eol);return I}printPhone(f){let I="";for(const O of f)I+="e=".concat(O).concat(this.eol);return I}printConnection(f){return f?"c=".concat(f.nettype," ").concat(f.addrtype," ").concat(f.address).concat(this.eol):""}printBandwidth(f){let I="";for(const O of f)I+="b=".concat(O.bwtype,":").concat(O.bandwidth).concat(this.eol);return I}printTimeFields(f){let I="";for(const O of f){I+="t=".concat(O.time.startTime," ").concat(O.time.startTime).concat(this.eol);for(const B of O.repeats)I+="r=".concat(B.repeatInterval," ").concat(B.typedTimes.join(" ")).concat(this.eol);O.zoneAdjustments&&(I+="z=",I+="z=".concat(O.zoneAdjustments.map(B=>"".concat(B.time," ").concat(B.back?"-":""," ").concat(B.typedTime)).join(" ")).concat(this.eol),I+=this.eol)}return I}printKey(f){return f?"k=".concat(f).concat(this.eol):""}printAttributes(f){let I="";for(const O of f)I+="a=".concat(O.attField).concat(O.attValue?":".concat(O.attValue):"").concat(this.eol);return I}printMediaDescription(f){let I="";for(const O of f)I+=this.printMedia(O.media),I+=this.printInformation(O.information),I+=this.printConnections(O.connections),I+=this.printBandwidth(O.bandwidths),I+=this.printKey(O.key),I+=this.printMediaAttributes(O);return I}printConnections(f){let I="";for(const O of f)I+=this.printConnection(O);return I}printMedia(f){return"m=".concat(f.mediaType," ").concat(f.port," ").concat(f.protos.join("/")," ").concat(f.fmts.join(" ")).concat(this.eol)}printSessionAttributes(f){return new We(this.eol).print(f)}printMediaAttributes(f){return new M(this.eol).print(f)}}class ke{constructor(f){_e(this,"eol",void 0),this.eol=f}printIceUfrag(f){return f===void 0?"":"a=ice-ufrag:".concat(f).concat(this.eol)}printIcePwd(f){return f===void 0?"":"a=ice-pwd:".concat(f).concat(this.eol)}printIceOptions(f){return f===void 0?"":"a=ice-options:".concat(f.join(c)).concat(this.eol)}printFingerprints(f){return f.length>0?f.map(I=>
43"a=fingerprint:".concat(I.hashFunction).concat(c).concat(I.fingerprint)).join(this.eol)+this.eol:""}printExtmap(f){return f.map(I=>"a=extmap:".concat(I.entry).concat(I.direction?"/".concat(I.direction):"").concat(c).concat(I.extensionName).concat(I.extensionAttributes?"".concat(c).concat(I.extensionAttributes):"").concat(this.eol)).join("")}printSetup(f){return f===void 0?"":"a=setup:".concat(f).concat(this.eol)}printUnrecognized(f){return f.map(I=>"a=".concat(I.attField).concat(I.attValue?":".concat(I.attValue):"").concat(this.eol)).join("")}}class We extends ke{print(f){let I="";return I+=this.printGroups(f.groups),I+=this.printMsidSemantic(f.msidSemantic),I+=this.printIceLite(f.iceLite),I+=this.printIceUfrag(f.iceUfrag),I+=this.printIcePwd(f.icePwd),I+=this.printIceOptions(f.iceOptions),I+=this.printFingerprints(f.fingerprints),I+=this.printSetup(f.setup),I+=this.printTlsId(f.tlsId),I+=this.printIdentity(f.identities),I+=this.printExtmap(f.extmaps),I+=this.printUnrecognized(f.unrecognized),I}printGroups(f){let I="";return f.length>0&&(I+=f.map(O=>"a=group:".concat(O.semantic).concat(O.identificationTag.map(B=>"".concat(c).concat(B)).join("")).concat(this.eol)).join("")),I}printIceLite(f){return f===void 0?"":"a=ice-lite"+this.eol}printTlsId(f){return f?"a=tls-id:".concat(f).concat(this.eol):""}printIdentity(f){return f.length===0?"":f.map(I=>"a=identity:".concat(I.assertionValue).concat(I.extensions.map(O=>"".concat(c).concat(O.name).concat(O.value?"=".concat(O.value):"")))).join(this.eol)+this.eol}printMsidSemantic(f){if(!f)return"";let I="a=msid-semantic:".concat(f.semantic);return f.applyForAll?I+="".concat(c,"*"):f.identifierList.length>0&&(I+=f.identifierList.map(O=>"".concat(c).concat(O))),I+this.eol}}class M extends ke{print(f){const I=f.attributes;let O="";return O+=this.printRTCP(I.rtcp),O+=this.printIceUfrag(I.iceUfrag),O+=this.printIcePwd(I.icePwd),O+=this.printIceOptions(I.iceOptions),O+=this.printCandidates(I.candidates),O+=this.printRemoteCandidatesList(I.remoteCandidatesList),O+=this.printEndOfCandidates(I.endOfCandidates),O+=this.printFingerprints(I.fingerprints),O+=this.printSetup(I.setup),O+=this.printMid(I.mid),O+=this.printExtmap(I.extmaps),O+=this.printRTPRelated(I),O+=this.printPtime(I.ptime),O+=this.printMaxPtime(I.maxPtime),O+=this.printDirection(I.direction),O+=this.printSSRCGroups(I.ssrcGroups),O+=this.printSSRC(I.ssrcs),O+=this.printRTCPMux(I.rtcpMux),O+=this.printRTCPMuxOnly(I.rtcpMuxOnly),O+=this.printRTCPRsize(I.rtcpRsize),O+=this.printMSId(I.msids),O+=this.printImageattr(I.imageattr),O+=this.printRid(I.rids),O+=this.printSimulcast(I.simulcast),O+=this.printSCTPPort(I.sctpPort),O+=this.printMaxMessageSize(I.maxMessageSize),O+=this.printUnrecognized(I.unrecognized),O}printCandidates(f){return f.map(I=>"a=candidate:".concat(I.foundation).concat(c).concat(I.componentId).concat(c).concat(I.transport).concat(c).concat(I.priority).concat(c).concat(I.connectionAddress).concat(c).concat(I.port).concat(c,"typ").concat(c).concat(I.type).concat(I.relAddr?"".concat(c,"raddr").concat(c).concat(I.relAddr):"").concat(I.relPort?"".concat(c,"rport").concat(c).concat(I.relPort):"").concat(Object.keys(I.extension).map(O=>"".concat(c).concat(O).concat(c).concat(I.extension[O])).join("")).concat(this.eol)).join("")}printRemoteCandidatesList(f){return f.map(I=>"a=remote-candidates:".concat(I.join(c)).concat(this.eol)).join("")}printEndOfCandidates(f){return f===void 0?"":"a=end-of-candidates"+this.eol}printRTPRelated(f){if(!f.payloads)return"";const I=f.payloads;let O="";O+=f.rtcpFeedbackWildcards.map(B=>this.printRTCPFeedback("*",B)).join("");for(const B of I)O+=this.printRtpMap(B.payloadType,B.rtpMap),O+=this.printFmtp(B.payloadType,B.fmtp),O+=B.rtcpFeedbacks.map(ne=>this.printRTCPFeedback(B.payloadType,ne)).join("");return O}printFmtp(f,I){if(!I)return"";const O=Object.keys(I.parameters);return O.length===1&&I.parameters[O[0]]===null?"a=fmtp:".concat(f).concat(c).concat(O[0]).concat(this.eol):"a=fmtp:".concat(f).concat(c).concat(Object.keys(I.parameters).map(B=>"".concat(B,"=").concat(I.parameters[B])).join(";")).concat(this.eol)}printRtpMap(f,I){return I?"a=rtpmap:".concat(f).concat(c).concat(I.encodingName,"/").concat(I.clockRate).concat(I.encodingParameters?"/".concat(I.encodingParameters):"").concat(this.eol):""}printRTCPFeedback(f,I){let O="a=rtcp-fb:".concat(f).concat(c),B=I;return B.type==="trr-int"?O+="ttr-int".concat(c).concat(B.interval):(O+="".concat(B.type),B.parameter&&(O+="".concat(c).concat(B.parameter),B.additional&&(O+="".concat(c).concat(B.additional)))),O+this.eol}printPtime(f){return f===void 0?"":"a=ptime:".concat(f).concat(this.eol)}printMaxPtime(f){return f===void 0?"":"a=maxptime:".concat(f).concat(this.eol)}printDirection(f){return f===void 0?"":"a=".concat(f).concat(this.eol)}printSSRC(f){return f.map(I=>Object.keys(I.attributes).map(O=>"a=ssrc:".concat(I.ssrcId.toString(10)).concat(c).concat(O).concat(I.attributes[O]?":".concat(I.attributes[O]):"").concat(this.eol)).join("")).join("")}printRTCPMux(f){return f===void 0?"":"a=rtcp-mux".concat(this.eol)}printRTCPMuxOnly(f){return f===void 0?"":"a=rtcp-mux-only".concat(this.eol)}printRTCPRsize(f){return f===void 0?"":"a=rtcp-rsize".concat(this.eol)}
43printRTCP(f){if(f===void 0)return"";let I="a=rtcp:".concat(f.port);return f.netType&&(I+="".concat(c).concat(f.netType)),f.addressType&&(I+="".concat(c).concat(f.addressType)),f.address&&(I+="".concat(c).concat(f.address)),I+this.eol}printMSId(f){return f.map(I=>"a=msid:".concat(I.id).concat(I.appdata?"".concat(c).concat(I.appdata):"").concat(this.eol)).join("")}printImageattr(f){return f.map(I=>"a=imageattr:".concat(I).concat(this.eol)).join("")}printRid(f){return f.map(I=>{let O="a=rid:".concat(I.id).concat(c).concat(I.direction);return I.payloads&&(O+="".concat(c,"pt=").concat(I.payloads.join(","))),I.params.length>0&&(O+="".concat(c).concat(I.params.map(B=>B.type==="depend"?"depend=".concat(B.rids.join(",")):"".concat(B.type,"=").concat(B.val)).join(";"))),O+this.eol}).join("")}printSimulcast(f){return f===void 0?"":"a=simulcast:".concat(f).concat(this.eol)}printSCTPPort(f){return f===void 0?"":"a=sctp-port:".concat(f).concat(this.eol)}printMaxMessageSize(f){return f===void 0?"":"a=max-message-size:".concat(f).concat(this.eol)}printMid(f){return f===void 0?"":"a=mid:".concat(f).concat(this.eol)}printSSRCGroups(f){return f.map(I=>"a=ssrc-group:".concat(I.semantic).concat(I.ssrcIds.map(O=>"".concat(c).concat(O.toString(10))).join("")).concat(this.eol)).join("")}}function F(V){return new U().parse(V)}function J(V,f){return new me().print(V,f)}}},t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={exports:{}};return e[i](r,r.exports,n),r.exports}return n.d=(i,r)=>{for(var o in r)n.o(r,o)&&!n.o(i,o)&&Object.defineProperty(i,o,{enumerable:!0,get:r[o]})},n.o=(i,r)=>Object.prototype.hasOwnProperty.call(i,r),n.r=i=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(i,"__esModule",{value:!0})},n(8)})();function ii(e){return YO.parse(e)}function as(e,t){return YO.print(e,t)}var q9=lr("Array").keys,Z9=ns,Q9=Wn,$9=Ee,eX=q9,fS=Array.prototype,tX={DOMTokenList:!0,NodeList:!0},nX=function(e){var t=e.keys;return e===fS||$9(fS,e)&&t===fS.keys||Q9(tX,Z9(e))?eX:t},_n=re(nX);function Ft(e,t,n){return(t=function(i){var r=function(o,s){if(typeof o!="object"||!o)return o;var a=o[Symbol.toPrimitive];if(a!==void 0){var c=a.call(o,"string");if(typeof c!="object")return c;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(o)}(i);return typeof r=="symbol"?r:r+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function XO(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Te(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?XO(Object(n),!0).forEach(function(i){Ft(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):XO(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function Pp(e,t){return Pp=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Pp(e,t)}function gS(){gS=function(r,o){return new n(r,void 0,o)};var e=RegExp.prototype,t=new WeakMap;function n(r,o,s){var a=RegExp(r,o);return t.set(a,s||t.get(r)),Pp(a,n.prototype)}function i(r,o){var s,a=t.get(o);return ei(s=Object.keys(a)).call(s,function(c,d){var l=a[d];if(typeof l=="number")c[d]=r[l];else{for(var h=0;r[l[h]]===void 0&&h+1<l.length;)h++;c[d]=r[l[h]]}return c},Object.create(null))}return function(r,o){if(typeof o!="function"&&o!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(o&&o.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),o&&Pp(r,o)}(n,RegExp),n.prototype.exec=function(r){var o=e.exec.call(this,r);if(o){o.groups=i(o,this);var s=o.indices;s&&(s.groups=i(s,this))}return o},n.prototype[Symbol.replace]=function(r,o){if(typeof o=="string"){var s=t.get(this);return e[Symbol.replace].call(this,r,o.replace(/\$<([^>]+)(>|$)/g,function(c,d,l){if(l==="")return c;var h=s[d];return Array.isArray(h)?"$"+h.join("$"):typeof h=="number"?"$"+h:""}))}if(typeof o=="function"){var a=this;return e[Symbol.replace].call(this,r,function(){var c=arguments;return typeof c[c.length-1]!="object"&&(c=[].slice.call(c)).push(i(c,a)),o.apply(this,c)})}return e[Symbol.replace].call(this,r,o)},gS.apply(this,arguments)}const JO=new class extends Nt{constructor(){super(...arguments),Ft(this,"currentUploadLogID",0)}reportLogUploadError(e){const{errorRange:t}=e;t[t.length-1]&&t[t.length-1]>this.currentUploadLogID&&(this.currentUploadLogID=t[t.length-1],this.emit
43("REPORT_LOG_UPLOAD",e))}};function SS(){const e=new Date;return e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}function zO(){const e=new Date,t=/((\d+:){2}\d+)/.exec(new Date().toUTCString());return t?(t==null?void 0:t[0])+":"+e.getUTCMilliseconds():e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}const hr={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},Lp=Date.now(),zl=e=>{for(const t in hr)if(Object.prototype.hasOwnProperty.call(hr,t)&&hr[t]===e)return t;return"DEFAULT"},_=new class{constructor(){Ft(this,"proxyServerURL",void 0),Ft(this,"logLevel",hr.DEBUG),Ft(this,"uploadState","collecting"),Ft(this,"uploadLogWaitingList",[]),Ft(this,"uploadLogUploadingList",[]),Ft(this,"uploadErrorCount",0),Ft(this,"currentLogID",0),Ft(this,"url",void 0),Ft(this,"extLog",(e,t)=>{this.appendLogToWaitingList(e,...t)})}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[hr.DEBUG].concat(t);this.log.apply(this,i)}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[hr.INFO].concat(t);this.log.apply(this,i)}warning(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[hr.WARNING].concat(t);this.log.apply(this,i)}warn(){this.warning(...arguments)}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[hr.ERROR].concat(t);this.log.apply(this,i)}upload(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[hr.DEBUG].concat(t);this.uploadLog.apply(this,i)}setLogLevel(e){e=Math.min(Math.max(0,e),4),this.logLevel=e}enableLogUpload(){at("UPLOAD_LOG",!0)}disableLogUpload(){at("UPLOAD_LOG",!1),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[]}setProxyServer(e){this.proxyServerURL=e}prefix(e){return new class{constructor(t){Ft(this,"logger",void 0),Ft(this,"prefixLists",[]),this.logger=t}debug(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];this.logger.debug(...this.prefixLists,...n)}info(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];this.logger.info(...this.prefixLists,...n)}warning(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];this.logger.warning(...this.prefixLists,...n)}error(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];this.logger.error(...this.prefixLists,...n)}prefix(t){return this.prefixLists.push(t),this}popPrefix(){return this.prefixLists.pop(),this}}(this).prefix(e)}log(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];if(Date.now()-Lp<100)return void setTimeout(()=>{this.log(...t)},Date.now()-Lp);const i=Math.max(0,Math.min(4,t[0]));if(t[0]=SS()+" Agora-SDK [".concat(zl(i),"]:"),this.appendLogToWaitingList(i,...t),i<this.logLevel)return;const r=SS()+" %cAgora-SDK [".concat(zl(i),"]:");let o=[];if(!T("USE_NEW_LOG"))switch(i){case hr.DEBUG:o=[r,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,o);break;case hr.INFO:o=[r,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,o);break;case hr.WARNING:o=[r,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,o);break;case hr.ERROR:o=[r,"color: #B00020; font-weight: bold;"].concat(t.slice(1)),console.error.apply(console,o)}}uploadLog(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];if(Date.now()-Lp<100)return void setTimeout(()=>{this.uploadLog(...t)},Date.now()-Lp);const i=Math.max(0,Math.min(4,t[0]));t[0]=SS()+" Agora-SDK [".concat(zl(i),"]:"),this.appendLogToWaitingList(i,...t)}appendLogToWaitingList(e){if(!T("UPLOAD_LOG"))return;for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];Array.isArray(n[0])?n[0][0]=zO()+" Agora-SDK [".concat(zl(e),"]:"):n[0]=zO()+" Agora-SDK [".concat(zl(e),"]:");let r="";n.forEach(o=>{typeof o=="object"&&(o=JSON.stringify(o)),r+="".concat(o," ")}),this.uploadLogWaitingList.push({payload_str:r,log_level:e,log_item_id:this.currentLogID++}),this.uploadState==="uploading"&&this.uploadLogUploadingList.length===0&&this.uploadLogInterval()}startUpload(){this.uploadState="uploading",this.uploadLogUploadingList.length===0&&this.uploadLogInterval()}async uploadLogs(){const e=this.uploadLogUploadingList,t={sdk_version:qi,process_id:T("PROCESS_ID"),payload:JSON.stringify(e)};return Fr(async()=>{const n=await li.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(T("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(T("LOG_UPLOAD_SERVER"),"/upload/v1")),t,{responseType:"text"});if(n.data!=="OK"){const i=new Error("unexpected upload log response");throw i.response=n,i}},()=>(this.uploadLogUploadingList=[],!1),n=>{const i={status:-1,message:n.message,errorRange:e.map(r=>r.log_item_id)};return n.response?(i.status=n.response.status,i.data=n.response.data,i.headers=n.response.headers):n.request&&(i.status=n.request.status),JO.reportLogUploadError(i),!0},{timeout:T("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:T("UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL")})}uploadLogInterval(){this.uploadLogUploadingList.length===0&&this.uploadLogWaitingList.length===0||(this.uploadLogUploadingList.length===0&&(this.uploadLogUploadingList=this.uploadLogWaitingList.splice(0,T("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then(()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout(()=>this.uploadLogInterval(),T("UPLOAD_LOG_INTERVAL"))}).catch(e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout(()=>this.uploadLogInterval(),T("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout(()=>this.uploadLogInterval(),T("UPLOAD_LOG_RETRY_INTERVAL_V1"))}))}};var qO;function iX(e){return On(e.reportId,"params.reportId",0,100,!1),On(e.category,"params.category",0,100,!1),On(e.event,"params.event",0,100,!1),On(e.label,"params.label",0,100,!1),ut(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}(qO={}).FREE="free",qO.UPLOADING="uploading",function(e){e[e.MISC=0]="MISC",e[e.INTERNAL_EVENT=1]="INTERNAL_EVENT",e[e.PUBLIC_EVENT=2]="PUBLIC_EVENT",e[e.WEB_EVENT=3]="WEB_EVENT",e[e.INTERNAL_API=4]="INTERNAL_API",e[e.WEB_API=5]="WEB_API",e[e.PUBLIC_API=6]="P
43UBLIC_API"}({});let ZO=function(e){return e[e.RECOVER=0]="RECOVER",e[e.WARNING=1]="WARNING",e[e.ERROR=2]="ERROR",e}({}),QO=function(e){return e.CONFIG_DISTRIBUTE="config-distribute-error",e}({});const rX={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};let an=function(e){return e.PUBLISH="publish",e.SUBSCRIBE="subscribe",e.WS_COMPRESSOR_INIT="ws_compressor_init",e.SESSION_INIT="session_init",e.JOIN_CHOOSE_SERVER="join_choose_server",e.RTE_DETAIL="rte_detail_stats",e.REQ_USER_ACCOUNT="req_user_account",e.JOIN_GATEWAY="join_gateway",e.REJOIN_GATEWAY="rejoin_gateway",e.STREAM_SWITCH="stream_switch",e.REQUEST_PROXY_WORKER_MANAGER="request_proxy_worker_manager",e.REQUEST_PROXY_APPCENTER="request_proxy_appcenter",e.FIRST_VIDEO_RECEIVED="first_video_received",e.FIRST_AUDIO_RECEIVED="first_audio_received",e.FIRST_VIDEO_DECODE="first_video_decode",e.FIRST_AUDIO_DECODE="first_audio_decode",e.XLA_PEER_FIRST_VIDEO_FRAME="xla_peer_first_video_frame",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_UPDATE_STREAM="on_update_stream",e.ON_REMOVE_STREAM="on_remove_stream",e.USER_ANALYTICS="req_user_analytics",e.PC_STATS="pc_stats",e.UPDATE_REMOTE_RTPCAPABILITIES="update_remote_rtpCapabilities",e.AB_TEST="ab_test",e.ALARM_STATUS_NOTIFY="alarm_status_notify",e}({}),yt=function(e){return e.SESSION="io.agora.pb.Wrtc.Session",e.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer",e.RTE_DETAIL="io.agora.pb.Wrtc.RteDetailStats",e.REQ_USER_ACCOUNT="io.agora.pb.Wrtc.ReqUserAccount",e.JOIN_GATEWAY="io.agora.pb.Wrtc.JoinGateway",e.RE_JOIN_GATEWAY="io.agora.pb.Wrtc.ReJoinGateway",e.PUBLISH="io.agora.pb.Wrtc.Publish",e.SUBSCRIBE="io.agora.pb.Wrtc.Subscribe",e.WS_COMPRESSOR_INIT="io.agora.pb.Wrtc.WsCompressorInit",e.STREAM_SWITCH="io.agora.pb.Wrtc.StreamSwitch",e.AUDIO_SENDING_STOPPED="io.agora.pb.Wrtc.AudioSendingStopped",e.VIDEO_SENDING_STOPPED="io.agora.pb.Wrtc.VideoSendingStopped",e.REQUEST_PROXY_APPCENTER="io.agora.pb.Wrtc.RequestProxyAppCenter",e.REQUEST_PROXY_WORKER_MANAGER="io.agora.pb.Wrtc.RequestProxyWorkerManager",e.API_INVOKE="io.agora.pb.Wrtc.ApiInvoke",e.FIRST_VIDEO_RECEIVED="io.agora.pb.Wrtc.FirstVideoReceived",e.FIRST_AUDIO_RECEIVED="io.agora.pb.Wrtc.FirstAudioReceived",e.FIRST_VIDEO_DECODE="io.agora.pb.Wrtc.FirstVideoDecode",e.FIRST_AUDIO_DECODE="io.agora.pb.Wrtc.FirstAudioDecode",e.XLA_PEER_FIRST_VIDEO_FRAME="io.agora.pb.Wrtc.XLAPeerFirstVideoFrame",e.ON_ADD_AUDIO_STREAM="io.agora.pb.Wrtc.OnAddAudioStream",e.ON_ADD_VIDEO_STREAM="io.agora.pb.Wrtc.OnAddVideoStream",e.ON_UPDATE_STREAM="io.agora.pb.Wrtc.OnUpdateStream",e.ON_REMOVE_STREAM="io.agora.pb.Wrtc.OnRemoveStream",e.JOIN_CHANNEL_TIMEOUT="io.agora.pb.Wrtc.JoinChannelTimeout",e.PEER_PUBLISH_STATUS="io.agora.pb.Wrtc.PeerPublishStatus",e.WORKER_EVENT="io.agora.pb.Wrtc.WorkerEvent",e.AP_WORKER_EVENT="io.agora.pb.Wrtc.APWorkerEvent",e.JOIN_WEB_PROXY_AP="io.agora.pb.Wrtc.JoinWebProxyAP",e.WEBSOCKET_QUIT="io.agora.pb.Wrtc.WebSocketQuit",e.USER_ANALYTICS="io.agora.pb.Wrtc.UserAnalytics",e.AUTOPLAY_FAILED="io.agora.pb.Wrtc.AutoplayFailed",e.PC_STATS="io.agora.pb.Wrtc.PCStats",e.UPDATE_REMOTE_RTPCAPABILITIES="io.agora.pb.Wrtc.UpdateRemoteRTPCapabilities",e.AB_TEST="io.agora.pb.Wrtc.ABTest",e.ALARM_STATUS_NOTIFY="io.agora.pb.Wrtc.AlarmStatusNotify",e}({});(function(e){e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT"})({});let oX=function(e){return e[e.SESSION=26]="SESSION",e[e.JOIN_CHOOSE_SERVER=27]="JOIN_CHOOSE_SERVER",e[e.REQ_USER_ACCOUNT=196]="REQ_USER_ACCOUNT",e[e.JOIN_GATEWAY=28]="JOIN_GATEWAY",e[e.PUBLISH=30]="PUBLISH",e[e.SUBSCRIBE=29]="SUBSCRIBE",e[e.WS_COMPRESSOR_INIT=9430]="WS_COMPRESSOR_INIT",e[e.STREAM_SWITCH=32]="STREAM_SWITCH",e[e.AUDIO_SENDING_STOPPED=33]="AUDIO_SENDING_STOPPED",e[e.VIDEO_SENDING_STOPPED=34]="VIDEO_SENDING_STOPPED",e[e.REQUEST_PROXY_APPCENTER=35]="REQUEST_PROXY_APPCENTER",e[e.REQUEST_PROXY_WORKER_MANAGER=36]="REQUEST_PROXY_WORKER_MANAGER",e[e.API_INVOKE=41]="API_INVOKE",e[e.FIRST_VIDEO_RECEIVED=348]="FIRST_VIDEO_RECEIVED",e[e.FIRST_AUDIO_RECEIVED=349]="FIRST_AUDIO_RECEIVED",e[e.FIRST_VIDEO_DECODE=350]="FIRST_VIDEO_DECODE",e[e.FIRST_AUDIO_DECODE=351]="FIRST_AUDIO_DECODE",e[e.ON_ADD_AUDIO_STREAM=352]="ON_ADD_AUDIO_STREAM",e[e.ON_ADD_VIDEO_STREAM=353]="ON_ADD_VIDEO_STREAM",e[e.ON_UPDATE_STREAM=356]="ON_UPDATE_STREAM",e[e.ON_REMOVE_STREAM=355]="ON_REMOVE_STREAM",e[e.JOIN_CHANNEL_TIMEOUT=407]="JOIN_CHANNEL_TIMEOUT",e[e.PEER_PUBLISH_STATUS=408]="PEER_PUBLISH_STATUS",e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT",e[e.JOIN_WEB_PROXY_AP=700]="JOIN_WEB_PROXY_AP",e[e.WEBSOCKET_QUIT=671]="WEBSOCKET_QUIT",e[e.USER_ANALYTICS=1e4]="USER_ANALYTICS",e[e.AUTOPLAY_FAILED=9178]="AUTOPLAY_FAILED",e}({});const jr="[config-restore]",kp="websdk_ng_",Mp=kp+"blocked_config_hashes",TS=kp+"api_failure_records",$O=kp+"global_parameter",eN=kp+"config_restore_state";function RS(e){var t;return e==null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(n=>RS(n)).join(",")+"]":"{"+Pi(t=Object.keys(e)).call(t).map(n=>JSON.stringify(n)+":"+RS(e[n])).join(",")+"}"}function tN(e){return function(t){let n=2166136261;for(let i=0;i<t.length;i++)n^=t.charCodeAt(i),n=Math.imul(n,16777619);return(n>>>0).toString(36)}(RS(e))}function Up(){try{const e=window.localStorage.getItem(eN);if(e)return JSON.parse(e)}catch{}return{currentConfigHash:"",configVerified:!1}}function nN(e){try{window.localStorage.setItem(eN,JSON.stringify(e))}catch{}}function vS(){try{const e=window.localStorage.getItem(TS);return e?JSON.parse(e):[]}catch(e){return _.debug("[error] ".concat(jr," error getting API failure records:"),e),[]}}function iN(){var e;return ei(e=vS()).call(e,(t,n)=>t+n.count,0)}function AS(){try{window.localStorage.removeItem(TS)}catch(e){_.debug("[error] ".concat(jr," error clearing API failure records:"),e)}}function sX(){try{const e=iN(),t=T("MAX_CONFIG_RETRY");if(e<t)return;const{currentConfigHash:n}=Up();_.debug("[warning] ".concat(jr," restoring config due to ").concat(e," API failures")),n&&function(r){try{const o=window.localStorage.getItem(Mp);let s=[];o&&(s=JSON.parse(o).configHashes);const a=[...new Set([...s,r])];window.localStorage.setItem(Mp,JSON.stringify({configHashes:a,timestamp:Date.now()})),_.debug("[warning] ".concat(jr," blocked config hash: ").concat(r))}catch(o){_.debug("[error] ".concat(jr," error blocking config hash:"),o)}}(n),window.localStorage.removeItem($O);const i=vS().slice(-5);(function(r,o){Z.reportAlarm(r,o)}
43)(null,{status:ZO.ERROR,type:QO.CONFIG_DISTRIBUTE,message:"Config cache cleared due to API failures",extend:{failureCount:e,maxRetry:t,blockedConfigHash:n,recentFailures:i.map(r=>({api:r.apiName,error:r.errorCode||r.errorMessage,count:r.count,lastTime:r.lastTimestamp}))}}),AS()}catch(e){_.debug("[error] ".concat(jr," error restoring config:"),e)}}function rN(e,t){try{if(!T("ENABLE_CONFIG_RESTORE"))return;if(t&&t.name==="AgoraRTCException"){const d=T("CONFIG_ERROR_MONITOR");if(!Array.isArray(d)||!x(d).call(d,t.code))return}const n=window.localStorage.getItem($O);if(!n||n.length<20)return;const{configVerified:i}=Up();if(i)return;const r=T("CONFIG_RESTORE_ERROR_API");if(!Array.isArray(r)||!x(r).call(r,e))return;let o,s;t&&(t.code&&(o=t.code),s=t.message?t.message:typeof t=="string"?t:t.toString()),function(d,l,h){try{const u=vS(),p="".concat(d,":").concat(l||""),E=u.find(R=>"".concat(R.apiName,":").concat(R.errorCode||"")===p),{currentConfigHash:m}=Up();if(E)E.count++,E.lastTimestamp=Date.now(),h&&(E.errorMessage=h),m&&(E.configHash=m);else{const R=Date.now();u.push({apiName:d,errorCode:l,errorMessage:h,count:1,firstTimestamp:R,lastTimestamp:R,configHash:m||void 0})}const g=u.length>20?u.slice(-20):u;window.localStorage.setItem(TS,JSON.stringify(g))}catch(u){_.debug("[error] ".concat(jr," error saving API failure record:"),u)}}(e,o,s);const a=iN(),c=T("MAX_CONFIG_RETRY");_.debug("".concat(jr," API failure count: ").concat(a,"/").concat(c,", API: ").concat(e,", Error: ").concat(o||s)),a>=c&&sX()}catch{}}function CS(){try{window.localStorage.removeItem(Mp)}catch(e){_.debug("[error] ".concat(jr," error resetting blocked config:"),e)}}function ue(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function(t,n,i){const r=i.value;if(typeof r=="function"){const o=e.className||t.__className__||(t.constructor.name==="AgoraRTCClient"?"Client":t.constructor.name);i.value=function(){for(var s,a=arguments.length,c=new Array(a),d=0;d<a;d++)c[d]=arguments[d];let l=c;if(e.argsMap)try{l=e.argsMap(this,...c)}catch(u){_.warning(u),l=[]}try{JSON.stringify(l)}catch{_.warning("arguments for method ".concat(o,".").concat(String(n)," not serializable for apiInvoke.")),l=[]}const h=(e.report||Z).reportApiInvoke(this._sessionId||null,{id:this._clientId||((s=this.store)===null||s===void 0?void 0:s.clientId)||this._ID,name:"".concat(o,".").concat(String(n)),options:l,tag:ht.TRACER,reportResult:e.reportResult},e.throttleTime);try{const u=r.apply(this,c);return u instanceof K?u.then(p=>(h.onSuccess(e.reportResult&&p),p)).catch(p=>{throw h.onError(p),p}):(h.onSuccess(e.reportResult&&u),u)}catch(u){throw h.onError(u),u}}}return i}}const Z=new class{constructor(){Ft(this,"baseInfoMap",new Map),Ft(this,"proxyServer",void 0),Ft(this,"eventUploadTimer",void 0),Ft(this,"setSessionIdTimer",void 0),Ft(this,"url",void 0),Ft(this,"sids",new Set),Ft(this,"backupUrl",void 0),Ft(this,"_appId",void 0),Ft(this,"_aid",0),Ft(this,"keyEventUploadPendingItems",[]),Ft(this,"normalEventUploadPendingItems",[]),Ft(this,"apiInvokeUploadPendingItems",[]),Ft(this,"apiInvokeCount",0),Ft(this,"apiInvokeLoggedCount",0),Ft(this,"ltsList",[]),Ft(this,"lastSendNormalEventTime",Date.now()),Ft(this,"customReportCounterTimer",void 0),Ft(this,"customReportCount",0),Ft(this,"extApiInvoke",async e=>{for(const t of e){const n=Te(Te({},t),{},{sid:null,invokeId:++this.apiInvokeCount,tag:ht.TRACER});this.sendApiInvoke(n)}}),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),T("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),T("EVENT_REPORT_SEND_INTERVAL"))}getBaseInfoBySessionId(e){return this.baseInfoMap.get(e)}setAppId(e){this._appId=e,this._aid=parseInt(e.replace(/[a-fA-F0-9]{8}/g,t=>{let[n,i]=t;return n+i}),16)||0}reportApiInvoke(e,t,n){t.timeout=t.timeout||6e4,t.reportResult=t.reportResult===void 0||t.reportResult;const i=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,o=!!T("SHOW_REPORT_INVOKER_LOG"),s=!!T("SHOW_REPORT_USER_INVOKER_LOG"),a=o||s&&t.id;a&&(this.apiInvokeLoggedCount+=1);const c=this.apiInvokeLoggedCount;function d(p,E){if(a){let m="[apiInvoke-".concat(c,"]");if(t.id&&(m+="[".concat(t.id,"]")),t.name&&(m+="[".concat(t.name,"]"),t.name===vt.JOIN))return _.info("".concat(m," ").concat(p));_.info("".concat(m," ").concat(p),p==="start"?t.options:E||"")}}const l=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,apiInvokeTime:i,options:t.options,states:t.states||null});d("start");let h=!1;ln(t.timeout).then(()=>{h||(this.sendApiInvoke(Te(Te({},l()),{},{error:A.API_INVOKE_TIMEOUT,success:!1})),d("timeout"),rN(t.name,new L(A.API_INVOKE_TIMEOUT)))});const u=new L(A.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:p=>{const E=()=>
43{if(h)throw u;return h=!0,this.sendApiInvoke(Te(Te({},l()),{},{success:!0},t.reportResult&&{result:p})),d("onSuccess"),p};return n?NO(E,t.name+"Success",n,()=>h=!0):E()},onError:p=>{const E=()=>{if(h)throw p;h=!0,this.sendApiInvoke(Te(Te({},l()),{},{success:!1,error:p})),rN(t.name,p),d("onFailure",p.toString())};return n?NO(E,t.name+"Error",n,()=>h=!0):E()}}}_send(e,t,n){this.send({type:e,data:t},n)}_sendApiInvoke(e){return this.sendApiInvoke(e)}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const n=Date.now(),i=this.createBaseInfo(e,n);i.cname=t.cname,i.rteUrl=t.rteUrl;const r=Object.assign({},{willUploadConsoleLog:T("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:pS?"global":"oversea",areas:T("AREAS")&&T("AREAS").join(",")},t.extend),{stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientRole:l}=t,h=Date.now(),u=Te(Te({},i),{},{eventType:an.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,buildFormat:t.buildFormat,build:mS,lts:h,elapse:h-n,extend:JSON.stringify(r),mode:t.mode,process:T("PROCESS_ID"),appType:T("APP_TYPE"),success:!0,version:qi,stringUid:o,channelProfile:s,channelMode:
43a,isABTestSuccess:c,lsid:d,clientType:F9()?42:20,clientRole:l,serviceId:T("PROCESS_ID"),extensionID:T("PLUGIN_INFO").join(",")||"",rteUrl:t.rteUrl,rteSid:t.rteSid,installId:Jl()});this.send({type:yt.SESSION,data:u},!0)}reportRteDetail(e){const t=this.baseInfoMap.get(e);if(!t)return;const n=t.info,i=Date.now(),r=Te(Te({},n),{},{eventType:an.RTE_DETAIL,lts:i,success:!0,elapse:i-t.startTime,vid:n.vid===void 0?0:Number(n.vid),ua:navigator.userAgent});this.send({type:yt.RTE_DETAIL,data:r},!0)}joinChooseServer(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info;t.vid&&(i.vid=t.vid);const r=Date.now(),o=Te(Te({},i),{},{role:t.role,eventType:an.JOIN_CHOOSE_SERVER,lts:r,eventElapse:t.elapse||r-t.lts,chooseServerAddr:t.csAddr,errorCode:t.ec,elapse:r-n.startTime,success:t.succ,chooseServerAddrList:JSON.stringify(t.serverList),uid:t.uid?parseInt(t.uid):null,cid:t.cid?parseInt(t.cid):null,chooseServerIp:t.csIp||"",opid:t.opid,unilbsServerIds:t.unilbsServerIds,extend:t.extend||void 0,isHttp3:t.isHttp3,corssRegionTagReq:t.corssRegionTagReq||void 0,corssRegionTagRes:t.corssRegionTagRes||void 0,ua:navigator.userAgent,resourceTimingInfo:t.resourceTimingInfo||void 0});this.send({type:yt.JOIN_CHOOSE_SERVER,data:o},!0)}reqUserAccount(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=Te(Te({},i),{},{eventType:an.REQ_USER_ACCOUNT,lts:r,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:t.elapse||r-n.startTime,eventElapse:r-t.lts,extend:JSON.stringify(t.extend)});this.send({type:yt.REQ_USER_ACCOUNT,data:o},!0)}joinGateway(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info;t.vid&&(i.vid=t.vid),i.uid=t.uid,i.cid=t.cid;const r=Date.now(),{firstSuccess:o,addr:s,isProxy:a}=t,c=r-n.startTime,d=Te(Te({},i),{},{eventType:an.JOIN_GATEWAY,lts:r,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,errorMsg:t.errorMsg||"",elapse:c,eventElapse:r-t.lts,firstSuccess:o,signalChannel:t.signalChannel,preload:t.preload?1:0,installId:Jl(),isABTestSuccess:t.isABTestSuccess?1:0,gatewayIp:null,gatewayPort:null,isProxy:a?1:0}),l=d.success?1:0;if(t.succ&&(n.lastJoinSuccessTime=r),s)if(d.signalChannel==="1"){const h=gS(/(\d+\.\d+\.\d+\.\d+):(\d+)/,{ip:1,port:2}),u=s.match(h);d.gatewayIp=u&&u.groups?u.groups.ip:"",d.gatewayPort=u&&u.groups?u.groups.port:""}else if(a){const h=s.match(/h=(\d{1,3}-){3}\d{1,3}/g),u=s.match(/p=[0-9]{1,6}/g);d.gatewayIp=h&&h.length?h[0].split("=")[1].replace(/-/g,"."):"",d.gatewayPort=u&&u.length?u[0].split("=")[1]:""}else{const h=s.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),u=s.match(/(:|p=)[0-9]{1,6}/g);d.gatewayIp=h&&h.length?h[0].split("//")[1].replace(/-/g,"."):"",d.gatewayPort=u&&u.length?u[0].split(/:|p=/g)[1]:""}if(o)this.send({type:yt.JOIN_GATEWAY,data:d},!0);else{const h={isSuccess:l,port:d.gatewayPort};delete d.success,delete d.eventType,delete d.firstSuccess,delete d.gatewayPort,d.vid=Number(d.vid);const u=Object.assign({},d,h,{eventType:an.REJOIN_GATEWAY});this.send({type:yt.RE_JOIN_GATEWAY,data:u},!0)}}joinChannelTimeout(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=Date.now(),r=Te(Te({},n.info),{},{lts:i,timeout:t,elapse:i-n.startTime});this.send({type:yt.JOIN_CHANNEL_TIMEOUT,data:r},!0)}publish(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=Te(Te({},i),{},{eventType:an.PUBLISH,lts:r,eventElapse:t.eventElapse,elapse:r-n.startTime,success:t.succ,errorCode:t.ec,videoName:t.videoName,audioName:t.audioName,screenName:t.screenName,screenshare:t.screenshare,audio:t.audio,video:t.video,p2pid:t.p2pid,publishRequestid:t.publishRequestid});this.send({type:yt.PUBLISH,data:o},!0)}subscribe(e,t,n){const i=this.baseInfoMap.get(e);if(!i)return;const r=i.info,o=Date.now(),s=Te(Te({},r),{},{eventType:an.SUBSCRIBE,lts:o,eventElapse:t.eventElapse,elapse:o-i.startTime,success:t.succ,errorCode:t.ec,video:t.video,audio:t.audio,subscribeRequestid:t.subscribeRequestid,p2pid:t.p2pid,preSsrc:t.preSsrc?1:0},n&&{extend:JSON.stringify({isMassSubscribe:!0})});typeof t.peerid=="string"?s.peerSuid=t.peerid:s.peer=t.peerid,this.send({type:yt.SUBSCRIBE,data:s},!0)}wsCompressorInit(e){var t;const n=[..._n(t=this.baseInfoMap).call(t)],i=n.length?n[0]:"UnableToGetSid",r=this.baseInfoMap.get(i);if(!r)return;const o=r.info,s=Date.now(),a=Te(Te({},o),{},{eventType:an.WS_COMPRESSOR_INIT,lts:s,eventElapse:e.eventElapse,elapse:s-r.startTime,status:e.status?1:2});this.send({type:yt.WS_COMPRESSOR_INIT,data:a},!0)}firstXLAPeerFirstVideoFrame(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=t.peerPubStatusMs-(n.lastJoinSuccessTime||r),s=Te(Te({},i),{},{elapse:r-n.startTime,eventType:an.XLA_PEER_FIRST_VIDEO_FRAME,lts:r,peer:t.peer,width:t.width,height:t.height,ssrc:t.ssrc,p2pid:t.p2pid,peerPublishDuration:t.peerPublishDuration,joinChannelSuccessElapse:o,peerPubStatusMs:t.peerPubStatusMs-t.joinChannelStart,availablePublish:t.peerPublishDuration>o?1:0,preloadStart:Math.max(t.preloadStart-t.joinChannelStart,0),preloadEnd:Math.max(t.preloadEnd-t.joinChannelStart,0),encrypt:Math.max(t.a
vendor: 5,553 bytes, line 43
43pStart-t.joinChannelStart,0),ap:Math.max(t.apEnd-t.joinChannelStart,0),sua:Math.max(t.suaEnd-t.joinChannelStart,0),beforeConnect:Math.max(t.beforeConnect-t.joinChannelStart,0),peerRecevier:Math.max(t.peerReceiver-t.joinChannelStart,0),ice:Math.max(t.ice-t.joinChannelStart,0),pc:Math.max(t.pc-t.joinChannelStart,0),signalConnected:Math.max(t.signalConnected-t.joinChannelStart,0),joinReq:Math.max(t.joinReq-t.joinChannelStart,0),joinRes:Math.max(t.joinRes-t.joinChannelStart,0),userJoinNotify:Math.max(t.userJoinNotify-t.joinChannelStart,0),videoSsrcNotify:Math.max(t.videoAddNotify-t.joinChannelStart,0),subscribeDelayMs:Math.max(t.subscribeStart-t.videoAddNotify,0),subscribeStart:Math.max(t.subscribeStart-t.joinChannelStart,0),subscribeEnd:Math.max(t.subscribeEnd-t.joinChannelStart,0),firstReceived:Math.max(t.firstReceived-t.joinChannelStart,0),firstDecoded:Math.max(t.firstDecoded-t.joinChannelStart,0),firstPreRender:Math.max(t.firstPreRender-t.joinChannelStart,0),firstRender:Math.max(t.firstRender-t.joinChannelStart,0),playDelayMs:Math.max(t.playStart-t.subscribeEnd,0),playStart:Math.max(t.playStart-t.joinChannelStart,0),playEnd:Math.max(t.playEnd-t.joinChannelStart,0),isPreSub:t.isPreSub?1:0,isPrePc:t.isPrePc?1:0,isPreInstantVideo:t.isPreInstantVideo?1:0,firstReceivedEncodedFrame:t.firstReceivedEncodedFrame?Math.max(t.firstReceivedEncodedFrame-t.joinChannelStart,0):void 0,frameType:t.frameType||"",rtpTimestamp:t.rtpTimestamp||0,framePayloadType:t.framePayloadType||0,frameDataLength:t.frameDataLength||0,mimeType:t.mimeType||"",sdpEndPoint:t.sdpEndPoint?1:0});this.send({type:yt.XLA_PEER_FIRST_VIDEO_FRAME,data:s},!0)}firstRemoteVideoDecode(e,t,n,i){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=Te(Te(Te({},o),i),{},{elapse:s-r.startTime,eventType:t,lts:s,firstDecodeFrame:Math.max((i.firstFrame||s)-r.startTime,0),apEnd:Math.max(i.apEnd-r.startTime,0),apStart:Math.max(i.apStart-r.startTime,0),joinGwEnd:Math.max(i.joinGwEnd-r.startTime,0),joinGwStart:Math.max(i.joinGwStart-r.startTime,0),pcEnd:Math.max(i.pcEnd-r.startTime,0),pcStart:Math.max(i.pcStart-r.startTime,0),subscriberEnd:Math.max(i.subscriberEnd-r.startTime,0),subscriberStart:Math.max(i.subscriberStart-r.startTime,0),videoAddNotify:Math.max(i.videoAddNotify-r.startTime,0)});this.send({type:n,data:a},!0)}firstRemoteFrame(e,t,n,i){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=Te(Te(Te({},o),i),{},{elapse:s-r.startTime,eventType:t,lts:s});this.send({type:n,data:a},!0)}abTest(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=Te(Te(Te({},i),t),{},{vid:i.vid===void 0?0:Number(i.vid),elapse:r-n.startTime,eventType:an.AB_TEST,lts:r});this.send({type:yt.AB_TEST,data:o},!0)}pcStats(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=Te(Te(Te({},i),t),{},{vid:i.vid===void 0?0:Number(i.vid),elapse:r-n.startTime,eventType:an.PC_STATS,lts:r,preallocation:t.preallocation?1:0});this.send({type:yt.PC_STATS,data:o},!0)}updateRemoteRTPCapabilities(e,t){if(e){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=Te(Te(Te({},i),t),{},{vid:i.vid===void 0?0:Number(i.vid),eventType:an.UPDATE_REMOTE_RTPCAPABILITIES,lts:r});this.send({type:yt.UPDATE_REMOTE_RTPCAPABILITIES,data:o},!0)}}onGatewayStream(e,t,n,i){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=Te(Te(Te({},o),i),{},{eventType:t,lts:s});this.send({type:n,data:a},!0)}streamSwitch(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=Te(Te({},i),{},{eventType:an.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-n.startTime,success:t.succ});this.send({type:yt.STREAM_SWITCH,data:o},!0)}requestProxyAppCenter(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=Te(Te({},i),{},{eventType:an.REQUEST_PROXY_APPCENTER,lts:r,eventElapse:r-t.lts,elapse:r-n.startTime,APAddr:t.APAddr,workerManagerList:t.workerManagerList,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:yt.REQUEST_PROXY_APPCENTER,data:o},!0)}requestProxyWorkerManager(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=Te(Te({},i),{},{eventType:an.REQUEST_PROXY_WORKER_MANAGER,lts:r,eventElapse:r-t.lts,elapse:r-n.startTime,workerManagerAddr:t.workerManagerAddr,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:yt.REQUEST_PROXY_WORKER_MANAGER,data:o},!0)}setProxyServer(e){this.proxyServer=e,e?_.debug("reportProxyServerurl: ".concat(e)):_.debug("disable reportProxyServerurl: ".concat(e))}peerPublishStatus(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=Te(Te({},i),{},{subscribeElapse:t.subscribeElapse,peer:t.peer,peerPublishDuration:Math.max(t.audioPublishDuration,t.videoPublishDuration),audiotag:t.audioPublishDuration>0?1:-1,videotag:t.videoPublishDuration>0?1:-1,lts:r,elapse:r-n.startTime,joinChannelSuccessElapse:r-(n.lastJoinSuccessTime||r),peerPublishDurationVideo:t.videoPublishDuration,peerPublishDurationAudio:t.audioPublishDuration});this.send({type:yt.PEER_PUBLISH_STATUS,data:o},!0)}workerEvent(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now();(function(o,s,a){const c=o[s];if(!c||typeof c!="string")return[o];o[s]="";const d=ko(JSON.stringify(o));let l=0;const h=[];let u=0;for(let p=0;p<c.length;p++)u+=c.charCodeAt(p)<=127?1:3,u<=a-d||(h[h.length]=j(j({},o),{},{[s]:c.substring(l,p)}),l=p,u=c.charCodeAt(p)<=127?1:3);return l!==c.length-1&&(h[h.length]=j(j({},o),{},{[s]:c.substring(l)}
43)),h})(Te(Te(Te({},i),t),{},{elapse:r-n.startTime,lts:r,productType:"WebRTC"}),"payload",1300).forEach(o=>this.send({type:yt.WORKER_EVENT,data:o},!0))}apworkerEvent(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=Te(Te(Te({},i),t),{},{elapse:r-n.startTime,lts:r});this.send({type:yt.AP_WORKER_EVENT,data:o},!0)}joinWebProxyAP(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=Te(Te(Te({},i),t),{},{elapse:r-n.startTime,lts:r,extend:t.extend||void 0});this.send({type:yt.JOIN_WEB_PROXY_AP,data:o},!0)}WebSocketQuit(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=Te(Te(Te({},i),t),{},{elapse:r-n.startTime,lts:r});this.send({type:yt.WEBSOCKET_QUIT,data:o},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>T("CUSTOM_REPORT_LIMIT"))throw new L(A.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval(()=>{this.customReportCount=0},5e3));const n=Date.now(),i=t.map(r=>({type:yt.USER_ANALYTICS,data:Te(Te({sid:e},r),{},{lts:n})}));try{T("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(i):await this.postDataToStatsCollector(i)}catch(r){throw _.error("send custom report message failed",r.toString()),new L(A.CUSTOM_REPORT_SEND_FAILED,r.message)}}reportAlarm(e,t){const n=e?this.baseInfoMap.get(e):void 0,i=n==null?void 0:n.info,r=Date.now(),o=Te(Te(Te({},i),t),{},{vid:(i==null?void 0:i.vid)===void 0?0:Number(i.vid),elapse:n?r-n.startTime:0,eventType:an.ALARM_STATUS_NOTIFY,lts:r,installId:Jl(),processId:T("PROCESS_ID")});this.send({type:yt.ALARM_STATUS_NOTIFY,data:o},!0)}sendApiInvoke(e){const t=T("NOT_REPORT_EVENT");if(e.tag&&x(t)&&x(t).call(t,e.tag))return!1;if(e.sid===null)return this.apiInvokeUploadPendingItems.push(e),!1;const n=this.baseInfoMap.get(e.sid);if(!n)return this.apiInvokeUploadPendingItems.push(e),!1;const{cname:i,uid:r,cid:o}=n.info;let s;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof L){const{code:c,message:d}=e.error;s=c||d||e.error.toString()}else s=e.error.toString();const a={invokeId:e.invokeId,sid:e.sid,cname:i,cid:o,uid:r,lts:e.lts,success:e.success,elapse:e.lts-n.startTime,execElapse:e.lts-e.apiInvokeTime,apiName:e.name,options:e.options?JSON.stringify(e.options):void 0,execStates:e.states?JSON.stringify(e.states):void 0,execResult:e.result?JSON.stringify(e.result):void 0,errorCode:e.error?s:void 0,errorMsg:e.error?JSON.stringify(e.error):void 0};return this.send({type:yt.API_INVOKE,data:a},!1),!0}addSid(e){this.sids.add(e)}removeSid(e){this.sids.delete(e)}appendSessionId(){const e=this.apiInvokeUploadPendingItems;if(e.length===0)return;const t=Array.from(this.sids).find(n=>n!==null);t&&e.forEach(n=>{n&&(n.sid=t,this.sendApiInvoke(Object.assign({},n)))}),e.length=0}send(e,t){if(t)return this.keyEventUploadPendingItems.push(e),void this.sendItems(this.keyEventUploadPendingItems,!0);this.normalEventUploadPendingItems.push(e),this.normalEventUploadPendingItems.length>T("NORMAL_EVENT_QUEUE_CAPACITY")&&this.normalEventUploadPendingItems.splice(0,1),this.normalEventUploadPendingItems.length>=10&&this.sendItems(this.normalEventUploadPendingItems,!1)}doSend(){this.keyEventUploadPendingItems.length>0&&this.sendItems(this.keyEventUploadPendingItems,!0),this.normalEventUploadPendingItems.length>0&&Date.now()-this.lastSendNormalEventTime>=5e3&&this.sendItems(this.normalEventUploadPendingItems,!1)}sendItems(e,t){const n=[],i=[];for(;e.length;){const o=e.shift();n.length<20?n.push(o):i.push(o)}e.push(...i);for(const o of[...n]){var r;this.ltsList.indexOf(o.data.lts)!==-1?(o.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(o.data.lts)):(this.ltsList.push(o.data.lts),Pi(r=this.ltsList).call(r,(s,a)=>s-a))}
43return t||(this.lastSendNormalEventTime=Date.now()),T("ENABLE_EVENT_REPORT")&&n.length&&(T("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(n):this.postDataToStatsCollector(n)).catch((o=>s=>{T("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(o):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(o),this.normalEventUploadPendingItems.length>T("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-T("NORMAL_EVENT_QUEUE_CAPACITY")),_.warning("report: drop normal events"))))})(n)),e}async postDataToStatsCollector2(e){At.networkState===Jn.OFFLINE&&await K.race([At.onlineWaiter,ln(2*Bt.maxRetryTimeout)]);const t=r=>{let o=new Uint8Array;return r.forEach(s=>{const a=$g(JSON.stringify(s.data)),c=new ArrayBuffer(5),d=(h=>{let u=0;return Object.entries(yt).forEach(p=>{let[E,m]=p;m===h.type&&(u=oX[E])}),u})(s),l=new DataView(c);l.setUint16(0,a.byteLength,!0),l.setUint8(2,255&d),l.setUint8(3,d>>>8&255),l.setUint8(4,d>>>16&255),o=TO(o,new Uint8Array(c)),o=TO(o,a)}),o},n="event";let i=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(T("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(n):"https://".concat(T("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(n);for(let r=0;r<2;r+=1){r===1&&(i=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(T("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(n):"https://".concat(T("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(n));try{await dS(i,{timeout:1e4,data:t(e),headers:Te(Te({biz:"webrtc",sendts:Math.round(Date.now()/1e3),debug:"false"},this._appId&&{appid:this._appId}),{},{"Content-Type":"application/octet-stream"})},!0)}catch(o){if(r===1)throw o;continue}return}}async postDataToStatsCollector(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const n=(a=>{const c=a&&a.data.sid&&this.baseInfoMap.get(a.data.sid);return c&&c.info.vid&&+c.info.vid||0})(e[0]),i=n?void 0:this._aid,r={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map(a=>JSON.stringify(a)),vid:n,aid:i};At.networkState===Jn.OFFLINE&&await K.race([At.onlineWaiter,ln(2*Bt.maxRetryTimeout)]);const o=t?"/events/proto-raws":"/events/messages";let s=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(T("EVENT_REPORT_DOMAIN"),"&p=").concat(T("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(T("EVENT_REPORT_DOMAIN"),":").concat(T("STATS_COLLECTOR_PORT")).concat(o));for(let a=0;a<2;a+=1){a===1&&(s=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(T("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(T("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(T("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(T("STATS_COLLECTOR_PORT")).concat(o)));try{t?await H9(s,{timeout:1e4,data:r}):await dS(s,{timeout:1e4,data:r})}catch(c){if(a===1)throw c;continue}return}}createBaseInfo(e,t){const n=Object.assign({},rX);return n.sid=e,this.baseInfoMap.set(e,{info:n,startTime:t}),n}reportResourceTiming(e,t){const n=performance.getEntriesByName(e),i=n[n.length-1];i&&this.reportApiInvoke(t,{name:"Client.resourceTiming",options:i,tag:ht.TRACER}).onSuccess()}};JO.on("REPORT_LOG_UPLOAD",e=>{e.networkState=At.networkState,Z.reportApiInvoke(null,{name:"logUploadError",options:e,tag:ht.TRACER}).onSuccess("logUploadError")});let D=class extends L{constructor(e){super(e,arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",arguments.length>2?arguments[2]:void 0),Ft(this,"name","AgoraRTCException")}print(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"error";return super.print(e,_)}throw(){super.throw(_)}};const mn={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1,supportRequestVideoFrameCallback:!1,supportWebCrypto:!1,supportSuppressLocalAudioPlayback:!1,supportRestrictOwnAudio:!1};function Oe(){return mn}function oN(){return"setSinkId"in HTMLAudioElement.prototype&&(!T("RESTRICTION_SET_PLAYBACK_DEVICE")||(ss()||sO())&&!_O())}function Vp(){return!mn.supportUnifiedPlan||T("CHROME_FORCE_PLAN_B")&&Po()}function sN(){return T("ENABLE_JOIN_V4")}function Ua(e){return!(Rt()||aO(87)||Vp()||!T("ENABLE_PRE_SUB")&&(e==null||!e.autoSubscribe||T("FORCE_DISABLE_AUTO_SUB")))}function yS(e){return T("ENABLE_INSTANT_VIDEO")?T("ENABLE_INSTANT_VIDEO"):!(e==null||!e.autoSubscribe||T("FORCE_DISABLE_AUTO_SUB"))}function aN(){return!!T("FORCE_ENABLE_AUT_CC")||!Vp()&&(!!T("ENABLE_AUT_CC")||void 0)}function cN(){return!!T("FORCE_ENABLE_AUT_CC")||!Vp()&&(!!T("ENABLE_AUT_FEEDBACK")||void 0)}
vendor: 6,606 bytes, line 43
43function dN(){return navigator.mediaDevices&&"getSupportedConstraints"in navigator.mediaDevices}function lN(){if(dN()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("suppressLocalAudioPlayback"in e)||!e.suppressLocalAudioPlayback)}return Ur(141)||ks(141)||ba(141)}function uN(){if(dN()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("restrictOwnAudio"in e)||!e.restrictOwnAudio)}return Ur(141)||ks(141)||ba(125)}let Nn=function(e){return e.IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",e.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",e.IOS_INTERRUPTION_START="ios-interruption-start",e.IOS_INTERRUPTION_END="ios-interruption-end",e.STATE_CHANGE="state-change",e}({});function cd(e,t,n){return{sampleRate:e,stereo:t,bitrate:n}}function Be(e,t,n,i,r){return{width:e,height:t,frameRate:n,bitrateMin:i,bitrateMax:r}}function Wr(e,t,n,i,r){return{width:{max:e},height:{max:t},frameRate:n,bitrateMin:i,bitrateMax:r}}function IS(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const aX={"90p":Be(160,90),"90p_1":Be(160,90),"120p":Be(160,120,15,30,65),"120p_1":Be(160,120,15,30,65),"120p_3":Be(120,120,15,30,50),"120p_4":Be(212,120),"180p":Be(320,180,15,30,140),"180p_1":Be(320,180,15,30,140),"180p_3":Be(180,180,15,30,100),"180p_4":Be(240,180,15,30,120),"240p":Be(320,240,15,40,200),"240p_1":Be(320,240,15,40,200),"240p_3":Be(240,240,15,40,140),"240p_4":Be(424,240,15,40,220),"360p":Be(640,360,15,80,400),"360p_1":Be(640,360,15,80,400),"360p_3":Be(360,360,15,80,260),"360p_4":Be(640,360,30,80,600),"360p_6":Be(360,360,30,80,400),"360p_7":Be(480,360,15,80,320),"360p_8":Be(480,360,30,80,490),"360p_9":Be(640,360,15,80,800),"360p_10":Be(640,360,24,80,800),"360p_11":Be(640,360,24,80,1e3),"480p":Be(640,480,15,100,500),"480p_1":Be(640,480,15,100,500),"480p_2":Be(640,480,30,100,1e3),"480p_3":Be(480,480,15,100,400),"480p_4":Be(640,480,30,100,750),"480p_6":Be(480,480,30,100,600),"480p_8":Be(848,480,15,100,610),"480p_9":Be(848,480,30,100,930),"480p_10":Be(640,480,10,100,400),"720p":Be(1280,720,15,120,1130),"720p_auto":Be(1280,720,30,900,3e3),"720p_1":Be(1280,720,15,120,1130),"720p_2":Be(1280,720,30,120,2e3),"720p_3":Be(1280,720,30,120,1710),"720p_5":Be(960,720,15,120,910),"720p_6":Be(960,720,30,120,1380),"1080p":Be(1920,1080,15,120,2080),"1080p_1":Be(1920,1080,15,120,2080),"1080p_2":Be(1920,1080,30,120,3e3),"1080p_3":Be(1920,1080,30,120,3150),"1080p_5":Be(1920,1080,60,120,4780),"1440p":Be(2560,1440,30,120,4850),"1440p_1":Be(2560,1440,30,120,4850),"1440p_2":Be(2560,1440,60,120,7350),"4k":Be(3840,2160,30,120,8910),"4k_1":Be(3840,2160,30,120,8910),"4k_3":Be(3840,2160,60,120,13500)},cX={"480p":Wr(640,480,5),"480p_1":Wr(640,480,5),"480p_2":Wr(640,480,30),"480p_3":Wr(640,480,15),"720p":Wr(1280,720,5),"720p_auto":Be(1280,720,30,900,3e3),"720p_1":Wr(1280,720,5),"720p_2":Wr(1280,720,30),"720p_3":Wr(1280,720,15),"1080p":Wr(1920,1080,5),"1080p_1":Wr(1920,1080,5),"1080p_2":Wr(1920,1080,30),"1080p_3":Wr(1920,1080,15)},dX={"1SL1TL":IS(1,1),"3SL3TL":IS(3,3),"2SL3TL":IS(2,3)};function Kr(e){return e||(e="480p_1"),typeof e=="string"?Object.assign({},aX[e]):e}function bS(e){return typeof e=="string"?Object.assign({},cX[e]):e}function xp(e){return typeof e=="string"?Object.assign({},dX[e]):e}const lX={speech_low_quality:cd(16e3,!1),speech_standard:cd(32e3,!1,18),music_standard:cd(48e3,!1),standard_stereo:cd(48e3,!0,56),high_quality:cd(48e3,!1,128),high_quality_stereo:cd(48e3,!0,192)};function Fp(e){return typeof e=="string"?Object.assign({},lX[e]):e}const Va=[];function hN(e){return nn(e,"mediaSource",["screen","window","application"]),!0}let te=function(e){return e.NEED_RENEGOTIATE="@need_renegotiate",e.NEED_REPLACE_TRACK="@need_replace_track",e.NEED_REPLACE_MIXING_TRACK="@need_replace_mixing_track",e.NEED_CLOSE="@need_close",e.NEED_ENABLE_TRACK="@need_enable_track",e.NEED_DISABLE_TRACK="@need_disable_track",e.NEED_SESSION_ID="@need_sid",e.SET_OPTIMIZATION_MODE="@set_optimization_mode",e.GET_STATS="@get_stats",e.GET_RTC_STATS="@get_rtc_stats",e.GET_LOW_VIDEO_TRACK="@get_low_video_track",e.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",e.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",e.NEED_UPDATE_VIDEO_SEND_PARAMETERS="@need_update_video_send_parameters",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track",e}({}),$e=function(e){return e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream",e.SCREEN_LOW_TRACK="screen_low_track",e}({}),dd=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),uX=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.HIGH_STREAM_LAYER1=4]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=5]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=6]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=7]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=8]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=9]="HIGH_STREAM_LAYER6",e}({}),hX=function(e){return e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY",e[e.HIGH_STREAM_LAYER1=3]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=4]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=5]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=6]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=7]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=8]="HIGH_STREAM_LAYER6",e}({}),xa=function(e){return e.TRANSCEIVER_UPDATED="transceiver-updated",e.SEI_TO_SEND="sei-to-send",e.SEI_RECEIVED="sei-received",e.TRACK_UPDATED="track-updated",e}({}),ld=function(e){return e.SOURCE_STATE_CHANGE="source-state-change",e.TRACK_ENDED="track-ended",e.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.CLOSED="closed",e}({}),pr=function(e){return e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.VIDEO_STATE_CHANGED="video-state-changed",e.PLAY_START="play-start",e.PLAY_END="play-end",e.FIRST_FRAME_RENDER="first-frame-render",e}({}),ud=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),Qi=function(e){return e.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",e.RECEIVE_TRACK_BUFFER="receive_track_buffer",e.ON_AUDIO_BUFFER="on_audio_buffer",e.UPDATE_SOURCE="update_source",e}({});(function(e){e.UPDATE_TRACK_SOURCE="update-track-source"})({});const wS={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},OS={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,send
43ResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},pN={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receivePacketsDiscarded:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},pX={uplinkNetworkQuality:0,downlinkNetworkQuality:0},_N={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};let ri=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),$i=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),ql=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),Fa=function(e){return e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",e}({}),Dn=function(e){return e.NONE="none",e.INIT="init",e.CANPLAY="canplay",e.PLAYING="playing",e.PAUSED="paused",e.SUSPEND="suspend",e.STALLED="stalled",e.WAITING="waiting",e.ERROR="error",e.DESTROYED="destroyed",e.ABORT="abort",e.ENDED="ended",e.EMPTIED="emptied",e.LOADEDDATA="loadeddata",e}({}),Mo=function(e){return e[e.VideoStateStopped=0]="VideoStateStopped",e[e.VideoStateStarting=1]="VideoStateStarting",e[e.VideoStateDecoding=2]="VideoStateDecoding",e[e.VideoStateFrozen=3]="VideoStateFrozen",e}({});const NS={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};let Bp=function(e){return e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error",e}({});function Ue(e,t,n,i,r){var o,s,a={};
43return Object.keys(i).forEach(function(c){a[c]=i[c]}),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=ei(o=_a(s=n.slice()).call(s)).call(o,function(c,d){return d(e,t,c)||c},a),r&&a.initializer!==void 0&&(a.value=a.initializer?a.initializer.call(r):void 0,a.initializer=void 0),a.initializer===void 0?(Object.defineProperty(e,t,a),null):a}function P(e,t,n){return(t=function(i){var r=function(o,s){if(typeof o!="object"||!o)return o;var a=o[Symbol.toPrimitive];if(a!==void 0){var c=a.call(o,"string");if(typeof c!="object")return c;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(o)}(i);return typeof r=="symbol"?r:r+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function mN(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function ft(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?mN(Object(n),!0).forEach(function(i){P(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mN(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}let EN=class extends Nt{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(xa.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}constructor(e,t){super(),P(this,"trackMediaType",void 0),P(this,"_ID",void 0),P(this,"_rtpTransceiver",void 0),P(this,"_lowRtpTransceiver",void 0),P(this,"_hints",[]),P(this,"_isClosed",!1),P(this,"_originMediaStreamTrack",void 0),P(this,"mediaStreamTrack",void 0),P(this,"_external",{}),this._ID=t||Qe(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,function(n){x(Va).call(Va,n)||Va.push(n)}(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||Ms(()=>{var t;Z.reportApiInvoke(null,{name:vt.GET_MEDIA_STREAM_TRACK,options:[],tag:ht.TRACER}).onSuccess(((t=this._mediaStreamTrack)===null||t===void 0?void 0:t.label)||"")},this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===dd.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,function(e){const t=Va.indexOf(e);t!==-1&&Va.splice(t,1)}(this),this.emit(ld.CLOSED),this.removeAllListeners(xa.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===dd.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(xa.TRANSCEIVER_UPDATED,e,t)}},hd=class extends EN{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}constructor(e,t){super(e,t),P(this,"_enabled",!0),P(this,"_muted",!1),P(this,"_isExternalTrack",!1),P(this,"_isClosed",!1),P(this,"_enabledMutex",void 0),P(this,"processor",void 0),P(this,"_processorContext",void 0),P(this,"_handleTrackEnded",()=>{this.onTrackEnded()}),this._enabledMutex=new An("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded)}getTrackLabel(){var e,t;return(e=(t=this._originMediaStreamTrack)===null||t===void 0?void 0:t.label)!==null&&e!==void 0?e:""}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,_.debug("[".concat(this.getTrackId(),"] close")),this.emit(te.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2];this._isExternalTrack=n,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await mt(this,te.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){_.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(ld.TRACK_ENDED)}stateCheck(e,t){if(_.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),xr(t,e),this._enabled&&this._muted&&e==="enabled"&&t===!1)throw new L(A.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",_);if(!this._enabled&&!this._muted&&e==="muted"&&t===!0)throw new L(A.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",_)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():K.resolve([])}};const fN=window.AudioContext||window.webkitAudioContext;let DS,er=null;const ct=new class extends Nt{constructor(){super(...arguments),P(this,"prevState",void 0),P(this,"cur
43State",void 0),P(this,"currentTime",void 0),P(this,"currentTimeStuckAt",void 0),P(this,"interruptDetectorTrack",void 0),P(this,"onLocalAudioTrackMute",()=>{_.info("ios15-interruption-start"),this.emit(Nn.IOS_15_16_INTERRUPTION_START)}),P(this,"onLocalAudioTrackUnmute",async()=>{_.info("ios15-interruption-end"),this.curState!=="running"||this.duringInterruption?_.info("ios15-interruption-end-canceled"):(er&&await er.suspend(),this.emit(Nn.IOS_15_16_INTERRUPTION_END))})}get duringInterruption(){return this.prevState==="running"&&this.curState==="interrupted"}bindInterruptDetectorTrack(e){_.debug("webaudio bindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=e,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(e){_.debug("webaudio unbindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}};function pd(){if(!er){if(function(){if(!fN)return void _.error("your browser is not support web audio");_.info("create audio context");const e=ft({},T("WEBAUDIO_INIT_OPTIONS"));_.debug("audio context init option:",JSON.stringify(e)),er=new fN(e),ct.curState=er.state,er.onstatechange=()=>{ct.prevState=ct.curState,ct.curState=er?er.state:void 0;const{prevState:t,curState:n}=ct,i=n==="running",r=n==="interrupted",o=t==="running",s=t==="suspended",a=t==="interrupted",c=Fe().osVersion;(Hn()||Vr())&&o&&r&&(_.info("ios".concat(c,"-interruption-start")),ct.emit(Nn.IOS_INTERRUPTION_START)),(Hn()||Vr())&&(s||a)&&i&&(_.info("ios".concat(c,"-interruption-end")),ct.emit(Nn.IOS_INTERRUPTION_END)),t!==n&&ct.emit(Nn.STATE_CHANGE,n,t)},setInterval(()=>{var t;const n=(t=er)===null||t===void 0?void 0:t.currentTime;ct.currentTime!==n?(ct.currentTimeStuckAt&&(_.debug("AudioContext current time resume at ".concat(n)),ct.currentTimeStuckAt=void 0),ct.currentTime=n):(n!==ct.currentTimeStuckAt&&(Z.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:n},tag:ht.TRACER}).onSuccess(),_.warning("AudioContext current time stuck at ".concat(n))),ct.currentTimeStuckAt=n)},5e3),async function(t){const n=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let i,r,o=!1,s=!1,a=!1;function c(R){t.state==="running"?d(!1):Hn()||Vr()?t.state==="suspended"&&(d(!0),R&&t.resume().then(l,l)):t.state!=="closed"&&(d(!0),R&&t.resume().then(l,l))}function d(R){if(o!==R){o=R;for(let v=0,C=n;v<C.length;v+=1){const w=C[v];R?window.addEventListener(w,h,{capture:!0,passive:!0}):window.removeEventListener(w,h,{capture:!0,passive:!0})}}}function l(){c(!1)}function h(){c(!0)}function u(){let R;try{R=i.play(),R?R.then(m,m):(i.addEventListener("playing",m),i.addEventListener("abort",m),i.addEventListener("error",m))}catch{m()}}function p(R){a||(i.paused?R?(E(!1),a=!0,u()):E(!0):E(!1))}function E(R){if(s!==R){s=R;for(let v=0,C=n;v<C.length;v++){const w=C[v];R?window.addEventListener(w,g,{capture:!0,passive:!0}):window.removeEventListener(w,g,{capture:!0,passive:!0})}}}function m(){i.removeEventListener("playing",m),i.removeEventListener("abort",m),i.removeEventListener("error",m),a=!1,p(!1)}function g(){p(!0)}if(Hn()&&T("IOS_BG_TAG")){const R=t.createMediaStreamDestination(),v=document.createElement("div");v.innerHTML="<audio x-webkit-airplay='deny'></audio>",i=v.children.item(0),i.controls=!1,i.disableRemotePlayback=!0,i.preload="auto",i.srcObject=R.stream,r=()=>{if(T("IOS_AUTO_RESTART_BG_TAG")&&i&&i.srcObject&&!a&&(!i.paused||s!==!0)){i.paused||i.pause();try{a=!0,u()}catch{a=!1}return!0}},p(!0)}return ct.on(Nn.STATE_CHANGE,function(){c(!0)}),c(!1),r}(er).then(t=>{DS=t})}(),!er)throw new L(A.NOT_SUPPORTED,"can not create audio context");return er}return er}function Ba(e){if(function(){if(PS!==null)return PS;const i=pd(),r=i.createBufferSource(),o=i.createGain(),s=i.createGain();r.connect(o),r.connect(s),r.disconnect(o);let a=!1;try{r.disconnect(o)}catch{a=!0}return r.disconnect(),PS=a,a}())return;const t=e.connect,n=e.disconnect;e.connect=(i,r,o)=>{var s;return e._inputNodes||(e._inputNodes=[]),x(s=e._inputNodes).call(s,i)||(i instanceof AudioNode?(e._inputNodes.push(i),t.call(e,i,r,o)):t.call(e,i,r)),e},e.disconnect=(i,r,o)=>{n.call(e),i?Cp(e._inputNodes,i):e._inputNodes=[];for(const s of e._inputNodes)t.call(e,s)}}let PS=null;function LS(e,t){let n=!1;const i=1/t;if(T("DISABLE_WEBAUDIO")){const r=window.setInterval(()=>{n?window.clearInterval(r):e(performance.now()/1e3)},1e3*i)}else{const r=pd();let o=r.createGain();o.gain.value=0,o.connect(r.destination);const s=()=>
43{if(n)return void(o=null);const a=r.createOscillator();a.onended=s,a.connect(o),a.start(0),a.stop(r.currentTime+i),e(r.currentTime)};s()}return()=>{n=!0}}let gN=class{constructor(){P(this,"context",void 0),P(this,"analyserNode",void 0),P(this,"sourceNode",void 0),this.context=pd(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4}updateSource(e){if(e!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode)}catch{}this.sourceNode=e,e==null||e.connect(this.analyserNode)}}getVolumeLevel(){if(!this.sourceNode||(!this.context||Hn()||Vr()||this.context.state!=="running"&&this.context.resume(),!this.analyserNode))return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const n=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(n);for(let i=0;i<e.length;++i)e[i]=n[i]/128-1}const t=ei(e).call(e,(n,i)=>n+i*i,0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;(e=this.sourceNode)===null||e===void 0||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,(t=this.sourceNode)===null||t===void 0||t.connect(this.analyserNode)}catch{_.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}},SN=class extends Nt{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var n;(n=this.sourceNode)===null||n===void 0||n.disconnect(this.outputNode)}catch{}(t=this._processedNode)===null||t===void 0||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),P(this,"outputNode",void 0),P(this,"outputTrack",void 0),P(this,"isPlayed",!1),P(this,"sourceNode",void 0),P(this,"context",void 0),P(this,"audioBufferNode",void 0),P(this,"destNode",void 0),P(this,"audioOutputLevel",0),P(this,"volumeLevelAnalyser",void 0),P(this,"_processedNode",void 0),P(this,"playNode",void 0),P(this,"isDestroyed",!1),P(this,"onNoAudioInput",void 0),P(this,"isNoAudioInput",!1),P(this,"_noAudioInputCount",0),this.context=pd(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),Ba(this.outputNode),this.volumeLevelAnalyser=new gN}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=t=>{this.emit(Qi.ON_AUDIO_BUFFER,function(n){for(let i=0;i<n.outputBuffer.numberOfChannels;i+=1){const r=n.outputBuffer.getChannelData(i);for(let o=0;o<r.length;o+=1)r[o]=0}return n.inputBuffer}(t))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!Oe().webAudioMediaStreamDest)throw new L(A.NOT_SUPPORTED,"your browser is not support audio processor");return this.destNode&&this.outputTrack||(this.destNode=this.context.createMediaStreamDestination(),this.outputNode.connect(this.destNode),this.outputTrack=this.destNode.stream.getAudioTracks()[0]),this.outputTrack}play(e){this.context.state!=="running"&&yp(()=>{ct.emit("autoplay-failed")}),this.isPlayed=!0,this.playNode=e||this.context.destination,this.outputNode.connect(this.playNode)}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode)}catch{}this.isPlayed=!1}getAccurateVolumeLevel(){return this.volumeLevelAnalyser.getVolumeLevel()}async checkHasAudioInput(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;Hn()||Vr()?this.context.state==="suspended"&&this.context.resume():this.context.state!=="running"&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let n;t.getFloatTimeDomainData?(n=new Float32Array(t.fftSize),t.getFloatTimeDomainData(n)):(n=new Uint8Array(t.fftSize),t.getByteTimeDomainData(n));let i=!1;for(let r=0;r<n.length;r++)n[r]!==0&&(i=!0);return i?(this.isNoAudioInput=!1,!0):(await ln(200),await this.checkHasAudioInput(e?e+1:1)&&i)}getAudioVolume(){return this.outputNode.gain.value}setVolume(e){this.outputNode.gain.setValueAtTime(e,this.context.currentTime)}destroy(){this.disconnect(),this.stop(),this.isDestroyed=!0,this.onNoAudioInput=void 0}disconnect(){var e,t;(e=this.processedNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?(e=this.processedNode)===null||e===void 0||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode),this.volumeLevelAnalyser.updateSource(this.outputNode)}},kS=class extends SN{get isFreeze(){return!1}constructor(e,t,n){var i;if(super(),P(this,"sourceNode",void 0),P(this,"track",void 0),P(this,"clonedTrack",void 0),P(this,"audioElement",void 0),P(this,"isCurrentTrackCloned",!1),P(this,"isRemoteTrack",!1),P(this,"originVolumeLevelAnalyser",void 0),P(this,"rebuildWebAudio",async()=>
43{if(_.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&await this.checkHasAudioInput(),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void _.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then(()=>_.info("resume success")),_.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const s=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?s.stop():this.isCurrentTrackCloned=!0;const a=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(a),Ba(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const c=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(c,this.context.currentTime),Ba(this.outputNode),this.emit(Qi.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=a,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()}),e.kind!=="audio")throw new L(A.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),Ba(this.sourceNode),n){const s=n.clone();s.enabled=!0,this.clonedTrack=s,_.debug("create an unmuted track ".concat(s.id," from the original track ").concat(n.id," to get the volume"));const a=this.context.createMediaStreamSource(new MediaStream([s]));Ba(a),this.originVolumeLevelAnalyser=new gN,this.originVolumeLevelAnalyser.updateSource(a)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=r;const o=Fe();t&&o.os===pn.IOS&&Number((i=o.osVersion)===null||i===void 0?void 0:i.split(".")[0])<15&&(ct.on(Nn.STATE_CHANGE,()=>{this.context.state==="suspended"?document.body.addEventListener("click",this.rebuildWebAudio,!0):this.context.state==="running"&&this.rebuildWebAudio()}),this.checkHasAudioInput().then(s=>{s||document.body.addEventListener("click",this.rebuildWebAudio,!0)}))}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),Ba(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(Qi.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),ct.off("state-change",this.rebuildWebAudio),(e=this.originVolumeLevelAnalyser)===null||e===void 0||e.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]))}updateOriginTrack(e){const t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),_.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const n=this.context.createMediaStreamSource(new MediaStream([t]));Ba(n),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(n)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}};async function TN(e,t,n){const i=(o,s)=>o?typeof o!="number"?o.max||o.exact||o.ideal||o.min||s:o:s,r={audio:!!n&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:i(t.height,1080),maxWidth:i(t.width,1920)}}};return t.frameRate&&typeof t.frameRate!="number"?(r.video.mandatory.maxFrameRate=t.frameRate.max,r.video.mandatory.minFrameRate=t.frameRate.min):typeof t.frameRate=="number"&&(r.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(r)}async function _X(e,t){const n=await RN(e.mediaSource),{sourceId:i,audio:r}=await function(o){let s=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new K((a,c)=>{const d=document.createElement("div");d.innerText="share screen",d.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");const l=document.createElement("div");l.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const h=document.createElement("div");h.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",h.setAttribute("style","height: 12%;");const u=document.createElement("div");u.setAttribute("style","width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around;
43 overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const p=document.createElement("div");p.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");const E=document.createElement("button");E.innerHTML="cancel",E.setAttribute("style","width: 85px;"),E.onclick=()=>{document.body.removeChild(R);const v=new Error("NotAllowedError");v.name="NotAllowedError",c(v)};let m=s;const g=document.createElement("div");if(s){const v=document.createElement("input");v.setAttribute("type","checkbox");const C=document.createElement("span");v.setAttribute("style","margin-right: 6px;"),C.innerText="Share audio",v.checked=m,v.onchange=()=>{m=v.checked},g.appendChild(v),g.appendChild(C)}p.appendChild(g),p.appendChild(E),l.appendChild(h),l.appendChild(u),l.appendChild(p);const R=document.createElement("div");R.setAttribute("style","position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),R.appendChild(d),R.appendChild(l),document.body.appendChild(R),o.map(v=>{if(v.id){const C=document.createElement("div");C.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let w=v.thumbnail;try{const{width:b}=w.getSize();b>1920&&(w=w.resize({width:1920}))}catch(b){throw b&&b.message.startsWith("Illegal invocation")&&console.error("Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)"),b}C.innerHTML='<div style="height: 120px; display: table-cell; vertical-align: middle;"><img style="width: 100%; background: #333333; box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);" src='+w.toDataURL()+' /></div><span style=" height: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">'+v.name.replace(/[\u00A0-\u9999<>\&]/g,function(b){return"&#"+b.charCodeAt(0)+";"})+"</span>",C.onclick=()=>{document.body.removeChild(R),a({sourceId:v.id,audio:m})},u.appendChild(C)}})})}(n,t);return await TN(i,e,r)}
43async function RN(e){let t=["window","screen"];e!=="application"&&e!=="window"||(t=["window"]),e==="screen"&&(t=["screen"]);const n=RO();if(!n)throw console.error("failed to fetch electron, please mount it to window"),new L(A.ELECTRON_IS_NULL);let i=null;try{var r;i=((r=n.desktopCapturer)===null||r===void 0?void 0:r.getSources({types:t}))||n.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch{i=null}i&&i.then||(i=new K((o,s)=>{n.desktopCapturer.getSources({types:t},(a,c)=>{a?s(a):o(c)})}));try{return await i}catch(o){throw new L(A.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,o.toString())}}const MS=new An("safari");let vN=!1,AN=!1;async function tr(e,t){let n=0,i=null;for(;n<2;)try{i=await mX(e,t,n>0);break}catch(r){if(r instanceof L)throw _.error("[".concat(t,"] ").concat(r.toString())),r;const o=Gp(r.name||r.code||r,r.message);if(o.code===A.MEDIA_OPTION_INVALID){_.debug("[".concat(t,"] detect media option invalid, retry")),n+=1,await ln(500);continue}throw _.error("[".concat(t,"] ").concat(o.toString())),o}if(!i)throw new L(A.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return i}async function mX(e,t,n){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new L(A.NOT_SUPPORTED,"can not find getUserMedia");n&&(e.video&&(delete e.video.width,delete e.video.height),e.screen&&(delete e.screen.width,delete e.screen.height));const i=Oe(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return _.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(RO())e.screen.sourceId?_d(r,await TN(e.screen.sourceId,e.screen,!!e.screenAudio)):_d(r,await _X(e.screen,!!e.screenAudio));else if(ss()&&e.screen.extensionId&&e.screen.mandatory){if(!i.getStreamFromExtension)throw new L(A.NOT_SUPPORTED,"This browser does not support screen sharing");_.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const u=await(s=e.screen.extensionId,a=t,new K((p,E)=>{try{chrome.runtime.sendMessage(s,{getStream:!0},m=>{if(!m||!m.streamId)return _.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),m),void E(new L(A.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));p(m.streamId)})}catch(m){_.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(s,")"),m.toString()),E(new L(A.CHROME_PLUGIN_NOT_INSTALL))}}));e.screen.mandatory.chromeMediaSourceId=u,_d(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(i.getDisplayMedia){var o;e.screen.mediaSource&&hN(e.screen.mediaSource);const u={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:(o=e.screen.displaySurface)!==null&&o!==void 0?o:e.screen.mediaSource==="screen"?"monitor":e.screen.mediaSource},{selfBrowserSurface:p,surfaceSwitching:E,systemAudio:m,preferCurrentTab:g,windowAudio:R,monitorTypeSurfaces:v}=e.screen,C={selfBrowserSurface:p,surfaceSwitching:E,systemAudio:m,preferCurrentTab:g,windowAudio:R,monitorTypeSurfaces:v};!p&&delete C.selfBrowserSurface,!E&&delete C.surfaceSwitching,!m&&delete C.systemAudio,!g&&delete C.preferCurrentTab,!R&&delete C.windowAudio,!v&&delete C.monitorTypeSurfaces,_.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:u,audio:e.screenAudio,controls:C})),_d(r,await navigator.mediaDevices.getDisplayMedia(ft({video:u,audio:e.screenAudio},C)))}else{if(!Rt())throw _.error("[".concat(t,"] This browser does not support screenSharing")),new L(A.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&hN(e.screen.mediaSource);const u={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};_.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(u))),_d(r,await navigator.mediaDevices.getUserMedia(u))}}var s,a;if(!e.video&&!e.audio)return r;let c={video:e.video,audio:e.audio},d=T("MEDIA_DEVICE_CONSTRAINTS");if(d)try{typeof d=="string"&&(d=JSON.parse(d)),c=rS(c,d)}catch{}_.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(c)),Fe();let l,h=null;(vn()||Hn()||Tp())&&(h=await MS.lock());try{l=await navigator.mediaDevices.getUserMedia(c)}catch(u){throw h&&h(),u}return c.audio&&(vN=!0),c.video&&(AN=!0),_d(r,l),h&&h(),r}function Gp(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new L(A.MEDIA_OPTION_INVA
43LID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new L(A.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new L(A.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new L(A.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new L(A.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new L(A.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return _.error("getUserMedia unexpected error",e),new L(A.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function _d(e,t){const n=e.getVideoTracks()[0],i=e.getAudioTracks()[0],r=t.getVideoTracks()[0],o=t.getAudioTracks()[0];o&&(i&&e.removeTrack(i),e.addTrack(o)),r&&(n&&e.removeTrack(n),e.addTrack(r))}const nr=new class extends Nt{get state(){return this._state}set state(e){e!==this._state&&(this.emit(Fa.STATE_CHANGE,e),this._state=e)}constructor(){super(),P(this,"_state",ql.IDLE),P(this,"isAccessMicrophonePermission",!1),P(this,"isAccessCameraPermission",!1),P(this,"lastAccessMicrophonePermission",!1),P(this,"lastAccessCameraPermission",!1),P(this,"checkdeviceMatched",!1),P(this,"deviceInfoMap",new Map),this.init().then(()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval(()=>{(T("ENUMERATE_DEVICES_INTERVAL")||(Gl()||Sp()===pn.HARMONY_OS)&&Po())&&this.updateDevicesInfo()},T("ENUMERATE_DEVICES_INTERVAL_TIME"))}).catch(e=>_.error(e.toString()))}async enumerateDevices(e,t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)throw new L(A.NOT_SUPPORTED,"enumerateDevices() not supported.");const i=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(i);let o=!this.isAccessMicrophonePermission&&e,s=!this.isAccessCameraPermission&&t;r.audio&&(o=!1),r.video&&(s=!1);let a=null,c=null,d=null;if(!n&&(o||s)){if(MS.isLocked&&(_.debug("[device manager] wait GUM lock"),(await MS.lock())(),_.debug("[device manager] GUM unlock")),vN&&(o=!1,this.isAccessMicrophonePermission=!0),AN&&(s=!1,this.isAccessCameraPermission=!0),_.debug("[device manager] check media device permissions",e,t,o,s),o&&s){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(l){const h=Gp(l.name||l.code||l,l.message);if(h.code===A.PERMISSION_DENIED)throw h;_.warning("getUserMedia failed in getDevices",h)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(o){try{a=await navigator.mediaDevices.getUserMedia({audio:e})}catch(l){const h=Gp(l.name||l.code||l,l.message);if(h.code===A.PERMISSION_DENIED)throw h;_.warning("getUserMedia failed in getDevices",h)}this.isAccessMicrophonePermission=!0}else if(s){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(l){const h=Gp(l.name||l.code||l,l.message);if(h.code===A.PERMISSION_DENIED)throw h;_.warning("getUserMedia failed in getDevices",h)}this.isAccessCameraPermission=!0}_.debug("[device manager] mic permission",e,"cam permission",t)}try{const l=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach(h=>h.stop()),c&&c.getTracks().forEach(h=>h.stop()),d&&d.getTracks().forEach(h=>h.stop()),a=null,c=null,d=null,l}catch(l){return a&&a.getTracks().forEach(h=>h.stop()),c&&c.getTracks().forEach(h=>h.stop()),d&&d.getTracks().forEach(h=>h.stop()),a=null,c=null,d=null,new L(A.ENUMERATE_DEVICES_FAILED,l.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter(t=>t.kind==="audioinput")}async getCamerasDevices(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter(t=>t.kind==="videoinput")}async getSpeakers(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter(t=>t.kind==="audiooutput")}
43searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach(n=>{n.device.label===e&&(t=n.device.deviceId)}),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find(n=>n.deviceId===e);if(!t)throw new L(A.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=ql.INITING;try{await this.updateDevicesInfo(),this.state=ql.INITEND}catch(e){throw this.state=ql.IDLE,(typeof isSecureContext=="boolean"?isSecureContext:location.protocol==="https:"||location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"||location.hostname==="::1")?(_.warning("Device Detection functionality cannot start properly.",e.toString()),e):new L(A.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.")}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),n=[];if(e[0]&&e[0].label&&this.checkdeviceMatched===!1){this.checkdeviceMatched=!0;const r=e.find(s=>s.kind==="audioinput"&&s.deviceId==="default"),o=e.find(s=>s.kind==="audiooutput"&&s.deviceId==="default");r&&o?o.groupId===r.groupId?_.debug("[device-check] default input ".concat(r.label," and output ").concat(o.label," is the same group")):_.debug("[device-check] default input ".concat(r.label," and output ").concat(o.label," is not the same group")):_.debug("[device-check] default input or output not found")}const i=this.checkMediaDeviceInfoIsOk(e);if(e.forEach(r=>{if(!r.deviceId)return;const o=this.deviceInfoMap.get("".concat(r.kind,"_").concat(r.deviceId));if((o?o.state:"INACTIVE")!=="ACTIVE"){const s={initAt:t,updateAt:t,device:r,state:"ACTIVE"};this.deviceInfoMap.set("".concat(r.kind,"_").concat(r.deviceId),s),n.push(s)}o&&(o.updateAt=t)}),this.deviceInfoMap.forEach((r,o)=>{r.state==="ACTIVE"&&r.updateAt!==t&&(r.state="INACTIVE",n.push(r))}),this.state!==ql.INITEND)return i.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(i.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));n.forEach(r=>{switch(r.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(Fa.RECORDING_DEVICE_CHANGED,r);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(Fa.CAMERA_DEVICE_CHANGED,r);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(Fa.PLAYOUT_DEVICE_CHANGED,r)}}),i.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),i.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter(r=>r.kind==="audioinput"),n=e.filter(r=>r.kind==="videoinput"),i={audio:!1,video:!1};for(const r of t)if(r.label&&r.deviceId){i.audio=!0;break}for(const r of n)if(r.label&&r.deviceId){i.video=!0;break}return i}};let US=!1;const hi=new class extends Nt{constructor(){super(...arguments),P(this,"onAutoplayFailed",void 0),P(this,"onAudioAutoplayFailed",void 0)}};function CN(){if(US)return T("FLS_AUTOPLAY_EMITS")?(hi.onAutoplayFailed&&hi.onAutoplayFailed(),hi.emit("autoplay-failed")):void 0;{const e=t=>{t.preventDefault(),US=!1,jl()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};US=!0,jl()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),_.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),hi.onAutoplayFailed?hi.onAutoplayFailed():hi.onAudioAutoplayFailed?_.warning(`AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed. 44 45 Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web .`):_.warning(`We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet. 46 47 It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences. 48 49 Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web .`),hi.emit
49("autoplay-failed")}}function yN(e,t,n,i){if(!e)return;const r=Z.getBaseInfoBySessionId(e);if(!r)return;const o=r.info,s=Date.now(),a=ft(ft({},o),{},{vid:o.vid===void 0?0:Number(o.vid),lts:s,elapse:s-r.startTime,cbRegistered:hi.onAutoplayFailed||hi.onAudioAutoplayFailed?1:-1,errorMsg:n,mediaType:t,trackId:i,extend:void 0});Z.send({type:yt.AUTOPLAY_FAILED,data:a},!0)}const EX=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],zn=new class{constructor(){P(this,"onAutoplayFailed",void 0),P(this,"elementMap",new Map),P(this,"elementStateMap",new Map),P(this,"elementsNeedToResume",[]),P(this,"sinkIdMap",new Map),P(this,"autoResumeAfterInterruption",e=>K.all(Array.from(this.elementMap.entries()).map(async t=>{let[n,i]=t;const r=this.elementStateMap.get(n),o=i.srcObject.getAudioTracks()[0],s=o&&o.readyState;if(_.debug("resume after interrupted, ele: ".concat(r," audio: ").concat(s," ").concat(e)),s==="live"){if(e)return i.pause(),i.play();if(ct.curState==="running")return ed()?(i.pause(),i.play()):r&&r==="paused"?i.play():void 0}}))),P(this,"autoResumeAfterInterruptionOnIOS15_16",()=>{Array.from(this.elementMap.entries()).forEach(e=>{let[t,n]=e;const i=n.srcObject.getAudioTracks()[0];i&&i.readyState==="live"&&(_.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),n.pause(),n.play())})}),this.autoResumeAudioElement(),ct.on(Nn.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),ct.on(Nn.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),ct.on(Nn.STATE_CHANGE,()=>{Hn()&&ct.prevState==="suspended"&&ct.curState==="running"&&this.autoResumeAfterInterruption()})}async setSinkID(e,t){const n=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),n)try{await n.setSinkId(t)}catch(i){throw new L(A.PERMISSION_DENIED,"can not set sink id: "+i.toString())}}play(e,t,n,i){if(this.elementMap.has(t))return;const r=document.createElement("audio");r.autoplay=!0,r.srcObject=new MediaStream([e]),this.bindAudioElementEvents(t,r),this.elementMap.set(t,r),this.elementStateMap.set(t,Dn.INIT),this.setVolume(t,n);const o=this.sinkIdMap.get(t);if(o)try{r.setSinkId(o).catch(a=>{_.warning("[".concat(t,"] set sink id failed"),a.toString())})}catch(a){_.warning("[".concat(t,"] set sink id failed"),a.toString())}const s=r.play();s&&s.then&&s.catch(a=>{i&&yN(i,"audio",a.message,t),_.warning("audio element play warning",a.toString()),this.elementMap.has(t)&&a.name==="NotAllowedError"&&(_.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),yp(()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),CN()}))})}updateTrack(e,t){const n=this.elementMap.get(e);n&&(n.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&this.elementStateMap.get(e)==="playing"}setVolume(e,t){const n=this.elementMap.get(e);n&&(t=Math.max(0,Math.min(100,t)),n.volume=t/100)}getVolume(e){const t=this.elementMap.get(e);return t?t.volume:0}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const n=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(n,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}bindAudioElementEvents(e,t){EX.forEach(n=>{t.addEventListener(n,i=>{const r=this.elementStateMap.get(e),o=i.type==="pause"?"paused":i.type;if(_.debug("[".concat(e,"] audio-element-status change ").concat(r," => ").concat(o)),i.type==="error"){const s=t==null?void 0:t.error;s&&_.error("[".concat(e,"] media error, code: ").concat(s.code,", message: ").concat(s.message))}this.elementStateMap.set(e,o)})})}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach(t=>{t.play().then(n=>{_.debug("Auto resume audio element success")}).catch(n=>{_.warning("Auto resume audio element failed!",n)})}),this.elementsNeedToResume=[]};new K(t=>{document.body?t():window.addEventListener("load",()=>t())}).then(()=>{jl()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))})}};function Gt(){return function(e,t,n){const i=n.value;return typeof i=="function"&&(n.value=function(){this._isClosed&&new L(A.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",_);for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];const a=i.apply(this,o);return a instanceof K?new K((c,d)=>{a.then(c).catch(d)}):a}),n}}let IN=class extends Nt{constructor(e){super(),P(this,"name","VideoProcessorDestination"),P(this,"ID","0"),P(this,"_source",void 0),P(this,"videoContext",void 0),P(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new L(A.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new L(A.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw new Error(`ProcessorContext passed to VideoTrack.processorDestination doesn't match it's belonging VideoTrack's context. 50Probably you are making pipeline like this: 51videoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).`);e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit
51(ri.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(ri.ON_TRACK,void 0)}},bN=class extends Nt{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),P(this,"constraintsMap",new Map),P(this,"statsRegistry",[]),P(this,"usageRegistry",[]),P(this,"trackId",void 0),P(this,"direction",void 0),P(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await Jt(this,$i.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var n;return _.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),mt(this,$i.REQUEST_UPDATE_CONSTRAINTS,Array.from(ti(n=this.constraintsMap).call(n)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return _.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),mt(this,$i.REQUEST_UPDATE_CONSTRAINTS,Array.from(ti(t=this.constraintsMap).call(t)))}registerStats(e,t,n){this.statsRegistry.find(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t)||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:n})}unregisterStats(e,t){const n=this.statsRegistry.findIndex(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t);n!==-1&&this.statsRegistry.splice(n,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:n,type:i,cb:r}of this.statsRegistry)try{const o=r();e.push({processorID:t,processorName:n,type:i,stats:o})}catch(o){_.error(new L(A.UNEXPECTED_ERROR,o.message))}return e}registerUsage(e,t){this.usageRegistry.find(n=>n.processorID===e.ID&&n.processorName===e.name)||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex(n=>n.processorID===e.ID&&n.processorName===e.name);t!==-1&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let n=t();n instanceof K&&(n=await n),e.push(ft(ft({},n),{},{direction:this.direction}))}catch(n){_.error("gather extension usage error",n)}return e}getDirection(){return this.direction}},wN=class extends Nt{constructor(e){super(),P(this,"name","AudioProcessorDestination"),P(this,"ID","0"),P(this,"inputTrack",void 0),P(this,"inputNode",void 0),P(this,"audioProcessorContext",void 0),P(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new L(A.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new L(A.NOT_SUPPORTED,"AudioProcessor cannot unpipe to any other Processor")}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(ri.ON_TRACK,void 0),this.emit(ri.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error(`ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context. 52 Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).`);e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(ri.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(ri.ON_NODE,this.inputNode))}},ON=class extends Nt{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,n){super(),P(this,"constraintsMap",new Map),P(this,"statsRegistry",[]),P(this,"audioContext",void 0),P(this,"trackId",void 0),P(this,"direction",void 0),P(this,"usageRegistry",[]),P(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=n}async getConstraints(){return Jt(this,$i.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var n;return _.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),mt(this,$i.REQUEST_UPDATE_CONSTRAINTS,Array.from(ti(n=this.constraintsMap).call(n)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),mt(this,$i.REQUEST_UPDATE_CONSTRAINTS,Array.from(ti(t=this.constraintsMap).call(t)))}
52registerStats(e,t,n){this.statsRegistry.find(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t)||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:n})}unregisterStats(e,t){const n=this.statsRegistry.findIndex(i=>i.processorID===e.ID&&i.processorName===e.name&&i.type===t);n!==-1&&this.statsRegistry.splice(n,1)}gatherStats(){const e=[];for(const{processorID:t,processorName:n,type:i,cb:r}of this.statsRegistry)try{const o=r();e.push({processorID:t,processorName:n,type:i,stats:o})}catch(o){_.error(new L(A.UNEXPECTED_ERROR,o.message))}return e}registerUsage(e,t){this.usageRegistry.find(n=>n.processorID===e.ID&&n.processorName===e.name)||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex(n=>n.processorID===e.ID&&n.processorName===e.name);t!==-1&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const{cb:t}of this.usageRegistry)try{let n=t();n instanceof K&&(n=await n),e.push(ft(ft({},n),{},{direction:this.direction}))}catch(n){_.error("gather extension usage error",n)}return e}getDirection(){return this.direction}},VS=class extends Nt{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),P(this,"context",void 0),P(this,"processSourceNode",void 0),P(this,"outputTrack",void 0),P(this,"processedNode",void 0),P(this,"clonedTrack",void 0),P(this,"outputNode",void 0),this.outputNode=new fX}setVolume(){}createOutputTrack(){throw new L(A.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}},fX=class{disconnect(){}connect(){}};function NN(e){return new K((t,n)=>{let i=!1;const r=document.createElement("video");r.setAttribute("autoplay",""),r.setAttribute("muted",""),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(r);const o=Hn()?"canplay":"playing";r.addEventListener(o,()=>{const s=r.videoWidth,a=r.videoHeight;
52!s&&Rt()||(i=!0,r.srcObject=null,r.remove(),t([s,a]))}),r.srcObject=new MediaStream([e]),r.play().catch(Hl),setTimeout(()=>{i||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))},4e3)})}function jp(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const n=Kr(e.encoderConfig);return n.width!=null&&(t.width=n.width),n.height!=null&&(t.height=n.height),!pO()&&n.frameRate&&(t.frameRate=n.frameRate),sO()&&typeof t.frameRate=="object"&&(t.frameRate.max=60),Rt()&&(t.frameRate={ideal:30,max:30}),t}function DN(e){const t={};return pO()||(e.AGC!==void 0&&(t.autoGainControl=e.AGC),e.AEC!==void 0&&(t.echoCancellation=e.AEC),e.ANS!==void 0&&(t.noiseSuppression=e.ANS,ss()&&e.ANS&&(t.googHighpassFilter=e.ANS))),t}function PN(e){const t=DN(e);if(e.encoderConfig){const n=Fp(e.encoderConfig);t.channelCount=n.stereo?2:1,t.sampleRate=n.sampleRate,t.sampleSize=n.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),Gl()&&(t.sampleRate=void 0),t}const LN=e=>{const t=e._encoderConfig;if(!t)return;const{frameRate:n,width:i,height:r}=e.getMediaStreamTrackSettings();let{frameRate:o=n,width:s=i,height:a=r}=t;if(!o||!s||!a)return;s=id(s),a=id(a),o=id(o);const{max:c,min:d}=function(p,E,m){const g=200*Math.pow(m/15,.6)*Math.pow(p*E/640/360,.75);return{min:Math.floor(g),max:Math.floor(4*g)}}(s,a,o),{bitrateMax:l,bitrateMin:h}=t||{};l||_.debug("calculate bitrate: [w: ".concat(s,", h: ").concat(a,", fps: ").concat(o,"] => [brMax: ").concat(l,", brMin: ").concat(h,"]"));const{maxFramerate:u}=T("ENCODER_CONFIG_LIMIT");return u&&typeof u=="number"&&(o=Math.min(o,u)),{frameRate:o,bitrateMax:l||c,bitrateMin:h||d,scaleResolutionDownBy:1,scale:0}},kN=async(e,t,n)=>await(async(i,r,o)=>{const s=function(d){const l=[];for(let h=0;h<d.length;h+=2)l.push(parseInt(d.slice(h,h+2),16));return Uint8Array.from(l)}(LO(""+r+o)).slice(0,16),a=s.slice(0,12),c=await window.crypto.subtle.importKey("raw",s,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:a},c,i))})(e.buffer,t,n),xS=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new K((n,i)=>{t.toBlob(async r=>{if(t.remove(),r){const o=await MN(r);n({buffer:o,width:t.width,height:t.height})}else i(new L(A.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))},e,1)})},MN=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};var UN,VN,xN,FN,BN,GN,jN,WN,KN,HN,YN,XN,JN,zN,qN,ZN,QN,$N,Mt,eD,tD,nD,iD,rD,oD,Uo,sD,aD,cD,dD,lD,uD,hD,pD,_D,mD,ED,fD,gD,xn;let jt=(UN=ue({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),VN=ue({argsMap:(e,t)=>[e.getTrackId(),t]}),xN=Gt(),FN=rd("LocalAudioTrack","_enabledMutex"),BN=ue({argsMap:(e,t)=>[e.getTrackId(),t]}),GN=Gt(),jN=rd("LocalAudioTrack","_enabledMutex"),WN=ue({argsMap:(e,t)=>[e.getTrackId(),t]}),KN=Gt(),HN=Gt(),YN=Gt(),XN=ue({argsMap:e=>[e.getTrackId()]}),JN=Gt(),zN=ue({argsMap:e=>[e.getTrackId()]}),qN=Gt(),ZN=ue({argsMap:e=>[e.getTrackId()]}),QN=ue({argsMap:(e,t)=>[e.getTrackId(),t.name]}),$N=ue({argsMap:e=>[e.getTrackId()]}),Ue((Mt=class extends hd{get _source(){return this.initWebAudio()}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext||(this._processorContext=this.initProcessor().processorContext),this._processorContext}get processorDestination(){return this._processorDestination||(this._processorDestination=this.initProcessor().processorDestination),this._processorDestination}get isPlaying(){return this._useAudioElement?zn.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,n,i){super(e,n),P(this,"trackMediaType",ud.AUDIO),P(this,"_encoderConfig",void 0),P(this,"_trackSource",void 0),P(this,"metadata",[]),P(this,"_enabled",!0),P(this,"_volume",100),P(this,"_useAudioElement",!0),P(this,"_bypassWebAudio",!1),P(this,"processor",void 0),P(this,"_processorContext",void 0),P(this,"_processorDestination",void 0),P(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!i,this._trackSource=new VS,T("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),T("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1),vn()&&!er?setTimeout(()=>this.initWebAudio()):this.initWebAudio()}setVolume(e){ut(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&zn.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void _.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const t=this._source.createOutputTrack();this._mediaStreamTrack!==t&&(this._mediaStreamTrack=t,mt(this,te.NEED_REPLACE_TRACK,this).then(()=>{_.debug("[".concat(this.getTrackId(),"] replace web audio track success"))}).catch(n=>{_.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),n)}))}catch{}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel()}async setPlaybackDevice(e){if(!this._useAudioElement||!oN())throw new L(A.NOT_SUPPORTED,"your browser does not support setting the audio output device");await zn.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,n){return this._setEnabled(e,t,n)}
52async _setEnabled(e,t,n){if(!n){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(_.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{n||(this._enabled=!0),await mt(this,te.NEED_ENABLE_TRACK,this),_.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(i){throw n||(this._enabled=!1),_.error("[".concat(this.getTrackId(),"] setEnabled to true error"),i.toString()),i}}else{this._originMediaStreamTrack.enabled=!1,n||(this._enabled=!1);try{await mt(this,te.NEED_DISABLE_TRACK,this)}catch(i){throw n||(this._enabled=!0),_.error("[".concat(this.getTrackId(),"] setEnabled to false error"),i.toString()),i}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,_.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await mt(this,te.NEED_MUTE_TRACK,this):await mt(this,te.NEED_UNMUTE_TRACK,this))}getStats(){return Ms(()=>{_.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")},"localAudioTrackGetStatsWarning"),Ui(this,te.GET_STATS)||ft({},wS)}setAudioFrameCallback(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:4096;if(!e)return this._source.removeAllListeners(Qi.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Qi.ON_AUDIO_BUFFER),this._source.on(Qi.ON_AUDIO_BUFFER,n=>e(n))}play(){_.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(_.debug("[".concat(this.getTrackId(),"] start audio playback in element")),zn.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){_.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?zn.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this._processorDestination&&this.unbindProcessorDestinationEvents(this._processorDestination),this._processorContext&&this.unbindProcessorContextEvents(this._processorContext),this.unpipe(),this._processorDestination&&this._processorDestination._source&&this._processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];_.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&zn.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this._processorContext&&this.processor.updateInput({track:e,context:this._processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await mt(this,te.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return K.resolve(void 0)}pipe(e){if(this._bypassWebAudio)throw new L(A.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new L(A.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(!this.processor)return;const t=this.processor;(e=this._source.processSourceNode)===null||e===void 0||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(e){e.on(ri.ON_TRACK,async t=>{t?t!==this._mediaStreamTrack&&(this._mediaStreamTrack=t,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(t),await mt(this,te.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await mt(this,te.NEED_REPLACE_TRACK,this))}),e.on(ri.ON_NODE,t=>{this._source.processedNode=t})}unbindProcessorDestinationEvents(e){e.removeAllListeners(ri.ON_TRACK),e.removeAllListeners(ri.ON_NODE)}bindProcessorContextEvents(e){e.on($i.REQUEST_CONSTRAINTS,async t=>{t(this._originMediaStreamTrack.getSettings())})}unbindProcessorContextEvents(e){e.removeAllListeners($i.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof VS&&(this._trackSource=new kS(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new ON(this._source.context,this.getTrackId(),"local"),t=new wN(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(Qi.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})}),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(zn.stop(this.getTrackId()),this._source.play()),mt(this,te.NEED_REPLACE_MIXING_TRACK,this).then(()=>{_.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))}).catch(n=>{_.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),n)})),{processorContext:e,processorDestination:t}}}).prototype,"setVolume",[UN],Object.getOwnPropertyDescriptor(Mt.prototype,"setVolume"),Mt.prototype),Ue(Mt.prototype,"setPlaybackDevice",[VN,xN],Object.getOwnPropertyDescriptor(Mt.prototype,"setPlaybackDevice"),Mt.prototype),Ue(Mt.prototype,"setEnabled",[FN,BN,GN],Object.getOwnPropertyDescriptor(Mt.prototype,"setEnabled"),Mt.prototype),Ue(Mt.prototype,"setMuted",[jN,WN,KN],Object.getOwnPropertyDescriptor(Mt.prototype,"setMuted"),Mt.prototype),Ue(Mt.prototype,"getStats",[HN],Object.getOwnPropertyDescriptor(Mt.prototype,"getStats"),Mt.prototype),Ue(Mt.prototype,"setAudioFrameCallback",[YN],Object.getOwnPropertyDescriptor(Mt.prototype,"setAudioFrameCallback"),Mt.prototype),Ue(Mt.prototype,"play",[XN,JN],Object.getOwnPropertyDescriptor(Mt.prototype,"play"),Mt.prototype),Ue(Mt.prototype,"stop",[zN,qN],Ob
vendor: 4,203 bytes, line 52
52ject.getOwnPropertyDescriptor(Mt.prototype,"stop"),Mt.prototype),Ue(Mt.prototype,"close",[ZN],Object.getOwnPropertyDescriptor(Mt.prototype,"close"),Mt.prototype),Ue(Mt.prototype,"pipe",[QN],Object.getOwnPropertyDescriptor(Mt.prototype,"pipe"),Mt.prototype),Ue(Mt.prototype,"unpipe",[$N],Object.getOwnPropertyDescriptor(Mt.prototype,"unpipe"),Mt.prototype),Mt),Zl=(eD=ue({argsMap:(e,t)=>[e.getTrackId(),t]}),tD=Gt(),nD=rd("MicrophoneAudioTrack","_enabledMutex"),iD=ue({argsMap:(e,t,n)=>[e.getTrackId(),t,n]}),rD=Gt(),oD=ue({argsMap:e=>[e.getTrackId()]}),Ue((Uo=class extends jt{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,n,i){super(e,t.encoderConfig?Fp(t.encoderConfig):{},i,T("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),P(this,"_config",void 0),P(this,"_deviceName","default"),P(this,"_constraints",void 0),P(this,"_originalConstraints",void 0),P(this,"_enabled",!0),this._config=t,this._constraints=n,this._originalConstraints=n,this._deviceName=e.label,typeof t.bypassWebAudio=="boolean"&&(this._bypassWebAudio=t.bypassWebAudio),(ed()||qg())&&ct.bindInterruptDetectorTrack(this)}async setDevice(e){if(_.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await nr.getDeviceById(e),n={};n.audio=ft({},this._constraints),n.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let i=null;try{i=await tr(n,this.getTrackId())}catch(r){throw _.error("[".concat(this.getTrackId(),"] setDevice failed"),r.toString()),i=await tr({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(i.getAudioTracks()[0],!1),r}await this._updateOriginMediaStreamTrack(i.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(t){throw _.error("[".concat(this.getTrackId(),"] setDevice error"),t.toString()),t}else try{const t=await nr.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(t){throw _.error("[".concat(this.getTrackId(),"] setDevice error"),t.toString()),t}_.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,n){if(t)return _.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!n){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(_.info("[".concat(this.getTrackId(),"] start setEnabled"),e),T("AUTO_RESET_AUDIO_ROUTE")&&(Hn()||Vr())){const s=navigator.audioSession;s&&(e||(s.type="playback"),s.type="auto")}if(!e){var i;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),(i=this._source.clonedTrack)===null||i===void 0||i.stop(),n||(this._enabled=!1);try{await mt(this,te.NEED_DISABLE_TRACK,this)}catch(s){throw _.error("[".concat(this.getTrackId(),"] setEnabled false failed"),s.toString()),s}return}const r=ft({},this._constraints),o=nr.searchDeviceIdByName(this._deviceName);o&&!r.deviceId&&(r.deviceId=o);try{n||(this._enabled=!0);const s=await tr({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(s.getAudioTracks()[0],!1),await mt(this,te.NEED_ENABLE_TRACK,this)}catch(s){throw n||(this._enabled=!1),_.error("[".concat(this.getTrackId(),"] setEnabled true failed"),s.toString()),s}_.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(ed()||qg())&&ct.unbindInterruptDetectorTrack(this),Va.some(e=>function(t){return"__className__"in t&&t.__className__==="MicrophoneAudioTrack"}(e))||DS&&DS()&&(Z.reportApiInvoke(null,{name:"BG_AUDIO_TAG_RESTART",options:{},tag:ht.TRACER}).onSuccess(),_.debug("restart background audio tag success"))}onTrackEnded(){if((Hn()||Vr())&&this._enabled&&!this._isClosed&&ct.duringInterruption){const e=async()=>{ct.off(Nn.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(_.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};ct.on(Nn.IOS_INTERRUPTION_END,e)}else _.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(ld.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,n=nr.searchDeviceId
52ByName(this._deviceName);if(n&&!t.deviceId&&(t.deviceId=n),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const i=await tr({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(i.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on($i.REQUEST_UPDATE_CONSTRAINTS,async(t,n,i)=>{try{const r=Object.assign({},this._originalConstraints,...t);await this.renewMediaStreamTrack(r),n()}catch(r){i(r)}})}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners($i.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,"setDevice",[eD,tD],Object.getOwnPropertyDescriptor(Uo.prototype,"setDevice"),Uo.prototype),Ue(Uo.prototype,"setEnabled",[nD,iD,rD],Object.getOwnPropertyDescriptor(Uo.prototype,"setEnabled"),Uo.prototype),Ue(Uo.prototype,"close",[oD],Object.getOwnPropertyDescriptor(Uo.prototype,"close"),Uo.prototype),Uo),gX=(sD=ue({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),aD=Gt(),cD=ue({argsMap:e=>[e.getTrackId()]}),dD=Gt(),lD=ue({argsMap:e=>[e.getTrackId()]}),uD=Gt(),hD=ue({argsMap:e=>[e.getTrackId()]}),pD=Gt(),_D=ue({argsMap:e=>[e.getTrackId()]}),mD=Gt(),ED=ue({argsMap:e=>[e.getTrackId()]}),fD=ue({argsMap:e=>[e.getTrackId()]}),gD=Gt(),Ue((xn=class extends jt{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,n,i){super(t.createOutputTrack(),n,i),P(this,"source",void 0),P(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(Qi.AUDIO_SOURCE_STATE_CHANGE,r=>{this.safeEmit(ld.SOURCE_STATE_CHANGE,r)});try{this._mediaStreamTrack=this._source.createOutputTrack()}catch{}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}get playbackSpeed(){return this._bufferSource.playbackSpeed}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(e){ut(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}).prototype,"startProcessAudioBuffer",[sD,aD],Object.getOwnPropertyDescriptor(xn.prototype,"startProcessAudioBuffer"),xn.prototype),Ue(xn.prototype,"pauseProcessAudioBuffer",[cD,dD],Object.getOwnPropertyDescriptor(xn.prototype,"pauseProcessAudioBuffer"),xn.prototype),Ue(xn.prototype,"seekAudioBuffer",[lD,uD],Object.getOwnPropertyDescriptor(xn.prototype,"seekAudioBuffer"),xn.prototype),Ue(xn.prototype,"resumeProcessAudioBuffer",[hD,pD],Object.getOwnPropertyDescriptor(xn.prototype,"resumeProcessAudioBuffer"),xn.prototype),Ue(xn.prototype,"stopProcessAudioBuffer",[_D,mD],Object.getOwnPropertyDescriptor(xn.prototype,"stopProcessAudioBuffer"),xn.prototype),Ue(xn.prototype,"close",[ED],Object.getOwnPropertyDescriptor(xn.prototype,"close"),xn.prototype),Ue(xn.prototype,"setAudioBufferPlaybackSpeed",[fD,gD],Object.getOwnPropertyDescriptor(xn.prototype,"setAudioBufferPlaybackSpeed"),xn.prototype),xn),En=class Gx extends jt{get __className__(){return"MixingAudioTrack"}get isActive(){for(const t of this.trackList)if(t._enabled&&!t._isClosed&&!t.muted)return!0;return!1}constructor(){const t=pd().createMediaStreamDestination();super(t.stream.getAudioTracks()[0],void 0,Qe(8,"track-mix-")),P(this,"trackList",void 0),P(this,"destNode",void 0),this._useAudioElement=!1;try{this._mediaStreamTrack=this._source.createOutputTrack()}catch{}this.destNode=t,this.trackList=[]}hasAudioTrack(t){return this.trackList.indexOf(t)!==-1}addAudioTrack(t){this.trackList.indexOf(t)===-1?(_.debug("add ".concat(t.getTrackId()," to mixing track")),t._source.outputNode.connect(this.destNode),this.trackList.push(t),this.updateEncoderConfig()):_.debug("track ".concat(t.getTrackId()," is already added"))}removeAudioTrack(t){if(this.trackList.indexOf(t)!==-1){_.debug("remove ".concat(t.getTrackId()," from mixing track"));try{t._source.outputNode.disconnect(this.destNode)}catch{}Cp(this.trackList,t),this.updateEncoderConfig()}}updateEncoderConfig(){const t={};this.trackList.forEach(n=>
52{n._encoderConfig&&((n._encoderConfig.bitrate||0)>(t.bitrate||0)&&(t.bitrate=n._encoderConfig.bitrate),(n._encoderConfig.sampleRate||0)>(t.sampleRate||0)&&(t.sampleRate=n._encoderConfig.sampleRate),(n._encoderConfig.sampleSize||0)>(t.sampleSize||0)&&(t.sampleSize=n._encoderConfig.sampleSize),n._encoderConfig.stereo&&(t.stereo=!0))}),this._encoderConfig=t}_updateRtpTransceiver(t){this._rtpTransceiver!==t&&(this._rtpTransceiver=t,this.trackList.forEach(n=>{n instanceof Gx?n.emit(xa.TRANSCEIVER_UPDATED,t):n._updateRtpTransceiver(t)}))}},SX=class extends SN{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(Qi.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),P(this,"audioBuffer",void 0),P(this,"sourceNode",void 0),P(this,"startPlayTime",0),P(this,"startPlayOffset",0),P(this,"pausePlayTime",0),P(this,"options",void 0),P(this,"currentLoopCount",0),P(this,"currentPlaybackSpeed",100),P(this,"_currentState","stopped"),this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0}createWebAudioDiagram(){return this.context.createGain()}get duration(){return this.audioBuffer?this.audioBuffer.duration:0}get playbackSpeed(){return this.currentPlaybackSpeed}get currentTime(){return this.audioBuffer?this.currentState==="stopped"?0:this.currentState==="paused"?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0}updateOptions(e){this.currentState==="stopped"?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):_.warning("can not set audio source options")}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState="playing"}pauseProcessAudioBuffer(){this.sourceNode&&this.currentState==="playing"&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState="paused")}seekAudioBuffer(e){this.sourceNode&&(this.sourceNode.onended=null,this.currentState==="playing"&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),this.currentState==="playing"?(this.startPlayOffset=e,this.startSourceNode()):this.currentState==="paused"&&(this.pausePlayTime=e))}resumeProcessAudioBuffer(){this.currentState==="paused"&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState="playing")}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch{}this.reset()}}destroy(){this.audioBuffer=null,super.destroy()}setAudioBufferPlaybackSpeed(e){this.sourceNode&&(this.currentState==="playing"&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=e/100),this.currentPlaybackSpeed=e}startSourceNode(){this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=this.handleSourceNodeEnded.bind(this))}createSourceNode(){const e=this.context.createBufferSource();return e.buffer=this.audioBuffer,e.loop=!!this.options.loop,e.connect(this.outputNode),e.playbackRate.value=this.currentPlaybackSpeed/100,e}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset()}reset(){this.startPlayOffset=this.options.startPlayTime||0,this.currentState="stopped",this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=void 0),this.currentLoopCount=0}};const SD=new Map;function TD(e,t){if(e.length===0||t.length===0)return 1/0;const n=sS(e),i=sS(t);return Math.floor(i/n)}let Wp=class{get rendFrameRate(){const e=Math.max(1,TD(this._render_interframe_delays_sizes,this._render_interframe_delays));return Math.floor(1e3/e)}get videoElementStatus(){return this._isInPage?this._videoElementStatus:Dn.DESTROYED}set videoElementStatus(e){e!==this._videoElementStatus&&(_.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}get videoState(){return this._videoState}set videoState(e){var t;e!==this._videoState&&(this._videoState=e,(t=this.onVideoStateChanged)===null||t===void 0||t.call(this,this.videoState))}constructor(e){P(this,"trackId",void 0),P(this,"config",void 0),P(this,"onFirstVideoFrameDecoded",void 0),P(this,"onFirstVideoFrameRen
52der",void 0),P(this,"onVideoBufferReady",void 0),P(this,"onVideoStateChanged",void 0),P(this,"freezeTimeCounterList",[]),P(this,"renderFreezeAccTime",0),P(this,"renderFreezeAccTime2",0),P(this,"totalFreezeTime",0),P(this,"isKeepLastFrame",!1),P(this,"isDestroyed",!1),P(this,"timeUpdatedCount",0),P(this,"freezeTime",0),P(this,"playbackTime",0),P(this,"lastTimeUpdatedTime",0),P(this,"autoplayFailed",!1),P(this,"videoTrack",void 0),P(this,"videoElement",void 0),P(this,"cacheVideoElement",void 0),P(this,"cancelRVFId",void 0),P(this,"internal",!1),P(this,"_render_interframe_delays",[]),P(this,"_render_interframe_delays_sizes",[]),P(this,"_videoState",Mo.VideoStateStopped),P(this,"videoElementCheckInterval",void 0),P(this,"videoElementFreezeTimeout",void 0),P(this,"_videoElementStatus",Dn.NONE),P(this,"_isInPage",!0),P(this,"isGettingVideoDimensions",!1),P(this,"startGetVideoDimensions",()=>{const t=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return _.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(t,500)};!this.isGettingVideoDimensions&&t()}),P(this,"autoResumeAfterInterruption",()=>{this.videoTrack&&this.videoTrack.readyState==="live"&&ct.curState==="running"&&(_.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(rO())),uO()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))}),P(this,"handleVideoEvents",t=>{switch(t.type){case"play":case"playing":t.type==="play"&&_.debug("[".concat(this.trackId,"] video element status: play")),this.startGetVideoDimensions(),this.videoElementStatus=Dn.PLAYING;break;case"loadeddata":if(this.videoState=Mo.VideoStateStarting,this.onFirstVideoFrameRender&&this.onFirstVideoFrameRender(),this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch{}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=Dn.CANPLAY;break;case"stalled":this.videoElementStatus=Dn.STALLED;break;case"suspend":this.videoElementStatus=Dn.SUSPEND;break;case"pause":this.videoElementStatus=Dn.PAUSED,Hn()||Vr()||vn()&&this.autoplayFailed||!this.videoTrack||this.videoTrack.readyState!=="live"||(_.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=Dn.WAITING;break;case"abort":this.videoElementStatus=Dn.ABORT;break;case"ended":this.videoElementStatus=Dn.ENDED;break;case"emptied":this.videoElementStatus=Dn.EMPTIED;break;case"error":{const n=this.videoElement.error;n&&(this.videoElementStatus=Dn.ERROR,_.error("[".concat(this.trackId,"] media error: ").concat(n.message," (").concat(n.code,")")));break}case"timeupdate":{const n=performance.now();if(this.timeUpdatedCount+=1,this.onVideoBufferReady&&this.timeUpdatedCount>T("BUFFER_READY_FRAMES")&&this.onVideoBufferReady(),this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=n);const i=n-this.lastTimeUpdatedTime,r=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=n,Vi.lastVisibleTime<Vi.lastHiddenTime||r<Vi.lastHiddenTime||r<Vi.lastVisibleTime||this.isSkipCalcRenderFreezeTime())return;for(i>T("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=i),this.playbackTime+=i;this.playbackTime>=6e3;){this.playbackTime-=6e3;const o=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(o),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}}),P(this,"autoResumeAfterInterruptionOnIOS15_16",()=>{this.videoTrack&&this.videoTrack.readyState==="live"&&(_.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(rO())),uO()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))}),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),ct.on(Nn.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),ct.on(Nn.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return(e=this.videoElement.parentElement)!==null&&e!==void 0?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(e){const t=this.videoElement.play();t&&t.catch&&t.catch(i=>{e&&yN(e,"video",i.message,this.trackId),i.name==="NotAllowedError"?(_.warning("detected video element autoplay failed",i),this.autoplayFailed=!0,this.handleAutoPlayFailed()):_.warning("[".concat(this.trackId,"] play warning: "),i)});const n=Fe();if((n.name==="Safari"&&Number(n.version)===15||ed())&&t&&t.then){const i=()=>{this.config.mirror&&!this.config.noStyle&&(this.videoElement.style.transform="rotateY(180deg)")};t.then(i).catch(i)}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return _.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const n=t.getImageData(0,0,e.width,e.height);return e.remove(),n}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;const n=document.createElement("canvas");n.width=this.videoElement.videoWidth,n.height=this.videoElement.videoHeight;const i=n.getContext("2d");return i?(i.drawImage(this.videoElement,0,0,n.width,n.height),new K((r,o)=>{n.toBlob(async s=>{if(n.remove(),s){const a=await MN(s);r({buffer:a,width:n.width,height:n.height})}else o(new L(A.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))},e,t<0?.1:t>1?1:t)})):await xS(e)}destroy(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this.isDestroyed=!0,ct.off(Nn.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),ct.off(Nn.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),e?this.videoElement.pause():this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=Mo.VideoStateStopped}initVideoElement(){if(this._videoElementStatus!==Dn.NONE&&this._videoElementStatus!==Dn.DESTROYED||(this.videoElementStatus=Dn.INIT),!this.videoElementCheckInterval&&(RD.forEac
52h(r=>{this.videoElement.addEventListener(r,this.handleVideoEvents)}),this.videoElementCheckInterval=window.setInterval(()=>{this._isInPage=function(r){return r!==document.body&&document.body.contains(r)}(this.videoElement)},1e3),T("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let r;const o=()=>{document.visibilityState==="visible"&&(document.removeEventListener("visibilitychange",o),this.videoElementFreezeTimeout=window.setTimeout(s,T("VIDEO_FREEZE_DURATION")))},s=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===Mo.VideoStateDecoding&&(document.visibilityState==="visible"?this.videoState=Mo.VideoStateFrozen:document.addEventListener("visibilitychange",o))},a=(c,d)=>{if(this.videoElementStatus===Dn.PLAYING){if(r){const u=d.presentationTime-r.presentationTime,p=d.presentedFrames-r.presentedFrames;this._render_interframe_delays_sizes.push(p),this._render_interframe_delays.push(u);const E=sS(this._render_interframe_delays_sizes),m=E-this._render_interframe_delays_sizes[0];if(E>30&&m>5&&(this._render_interframe_delays_sizes.shift(),this._render_interframe_delays.shift()),this.videoState===Mo.VideoStateStarting&&(this.videoState=Mo.VideoStateDecoding),this.videoState===Mo.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(s,T("VIDEO_FREEZE_DURATION"))),u<T("VIDEO_FREEZE_DURATION")&&this.videoState===Mo.VideoStateFrozen&&(this.videoState=Mo.VideoStateDecoding),u>T("VIDEO_FREEZE_DURATION")&&Vi.lastVisibleTime>=Vi.lastHiddenTime&&r.timestamp>Vi.lastVisibleTime&&r.timestamp>Vi.lastHiddenTime){const g=Math.min(66,TD(this._render_interframe_delays_sizes,this._render_interframe_delays)),R=Math.max(0,u-(p-1)*g),v=R>g?R:0;this.renderFreezeAccTime2+=v,this.totalFreezeTime+=v,this.renderFreezeAccTime+=u}}r=ft(ft({},d),{},{timestamp:c})}else this.isSkipCalcRenderFreezeTime()&&(r=ft(ft({},d),{},{timestamp:c}));var l,h;T("ENABLE_VIDEO_FRAME_CALLBACK")&&(this.cancelRVFId=(l=(h=this.videoElement).requestVideoFrameCallback)===null||l===void 0?void 0:l.call(h,a))};this.cancelRVFId=(e=(t=this.videoElement).requestVideoFrameCallback)===null||e===void 0?void 0:e.call(t,a)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),Gl()&&!T("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");const n=Fe();this.config.noStyle||(n.name==="Safari"&&Number(n.version)===15||ed()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover"),this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream?this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,Rt()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,Rt()&&this.videoElement.load());const i=this.videoElement.play();i!==void 0&&i.catch(r=>{_.debug("[".concat(this.trackId,"] playback interrupted"),r.toString())})}resetVideoElement(){var e,t;
52RD.forEach(n=>{this.videoElement&&this.videoElement.removeEventListener(n,this.handleVideoEvents)}),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.cancelRVFId&&this.videoElement&&((e=(t=this.videoElement).cancelVideoFrameCallback)===null||e===void 0||e.call(t,this.cancelRVFId),this.cancelRVFId=void 0),this.videoElementStatus=Dn.NONE}isSkipCalcRenderFreezeTime(){return this.videoElementStatus===Dn.DESTROYED||this.internal}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then(()=>{_.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))}).catch(n=>{_.error(n)}),this.autoplayFailed=!1,jl()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};jl()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),CN()}};const RD=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];let Kp=class extends Wp{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];super(e),P(this,"container",void 0),P(this,"slot",void 0),this.slot=e.element,this.internal=t,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;var n;!this.internal||this.slot?(t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()):(this.slot=t,t&&this.container?(this.internal=!1,this.container.id="agora-video-player-".concat(this.trackId),this.videoElement.id="video_".concat(this.trackId),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",(n=this.slot)===null||n===void 0||n.appendChild(this.container)):this.createElements())}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;(t=this.container)!==null&&t!==void 0&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return(e=this.container)!==null&&e!==void 0&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;return(t=this.container)!==null&&t!==void 0&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,n):await xS(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{var e;this.container.remove(),(e=this.slot)===null||e===void 0||e.removeChild(this.container)}catch{}this.container=void 0}}createElements(){var e;this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",T("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),(e=this.slot)===null||e===void 0||e.appendChild(this.container)}mountedVideoElement(){var e;!this.container||(e=this.container)!==null&&e!==void 0&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0"}unmountedVideoElement(){var e;if((e=this.container)!==null&&e!==void 0&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch{}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;(e=this.container)!==null&&e!==void 0&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}}
52;var vD,AD,CD,yD,ID,bD,wD,OD,ND,DD,PD,LD,kD,MD,UD,VD,xD,FD,BD,GD,jD,WD,KD,HD,YD,XD,JD,zD,Ne,qD,ZD,QD,$D,eP,tP,nP,iP,ir;let pt=(vD=ue({argsMap:(e,t,n)=>[e.getTrackId(),typeof t=="string"?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",n]}),AD=Gt(),CD=ue({argsMap:e=>[e.getTrackId()]}),yD=rd("LocalVideoTrack","_enabledMutex"),ID=ue({argsMap:(e,t)=>[e.getTrackId(),t]}),bD=Gt(),wD=rd("LocalVideoTrack","_enabledMutex"),OD=ue({argsMap:(e,t)=>[e.getTrackId(),t]}),ND=Gt(),DD=ue({argsMap:(e,t)=>[e.getTrackId(),t,e._saveEncodeBitrateRatio]}),PD=Gt(),LD=ue({argsMap:(e,t)=>[e.getTrackId(),t]}),kD=Gt(),MD=Gt(),UD=ue({argsMap:(e,t,n)=>[e.getTrackId(),t,n]}),VD=Gt(),xD=Gt(),FD=Gt(),BD=ue({argsMap:e=>[e.getTrackId()]}),GD=Gt(),jD=Gt(),WD=Gt(),KD=Gt(),HD=Gt(),YD=ue({argsMap:(e,t)=>[e.getTrackId(),t.name]}),XD=ue({argsMap:e=>[e.getTrackId()]}),JD=ue({argsMap:e=>[e.getTrackId()]}),zD=ue({argsMap:(e,t,n)=>[e.getTrackId(),t.label,n]}),Ne=class jx extends hd{get videoHeight(){if(vn()){const{height:t}=this._mediaStreamTrack.getSettings();return this._videoHeight=t,this._videoHeight}return this._videoHeight}get videoWidth(){if(vn()){const{width:t}=this._mediaStreamTrack.getSettings();return this._videoWidth=t,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==Dn.PLAYING)}get processorDestination(){return this._processorDestination}get processorContext(){return this._processorContext}set processorContext(t){this._processorContext=t}get __className__(){return"LocalVideoTrack"}constructor(t,n,i,r,o,s){if(super(t,o),P(this,"trackMediaType",ud.VIDEO),P(this,"_player",void 0),P(this,"isUseScaleResolutionDownBy",!1),P(this,"_videoVisibleTimer",null),P(this,"_previousVideoVisibleStatus",void 0),P(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),P(this,"_encoderConfig",void 0),P(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),P(this,"_optimizationMode",void 0),P(this,"_saveEncodeBitrateRatio",1),P(this,"_videoHeight",void 0),P(this,"_videoWidth",void 0),P(this,"_forceBitrateLimit",void 0),P(this,"_enabled",!0),P(this,"_processorDestination",void 0),P(this,"_processorContext",void 0),vn()){const{width:a,height:c}=t.getSettings();this._videoWidth=a,this._videoHeight=c}else this.updateMediaStreamTrackResolution();if(this._scalabilityMode=i,this._optimizationMode=r,this._hints=s||[],n&&this._hints.indexOf($e.CUSTOM_TRACK)!==-1?this._encoderConfig=Ct(n):this._encoderConfig=n,this._hints.indexOf($e.SCREEN_TRACK)===-1)this.updateBitrateFromProfile();else if(Rp(je.CHROME,115)&&Sp().indexOf("Windows")!==-1){const a=function(c,d){if("VideoFrame"in window&&"TransformStream"in window&&Oe().supportWebRTCInsertableStream){const l=new MediaStreamTrackProcessor(c),h=new MediaStreamTrackGenerator({kind:"video"});let u,p,E=Date.now();const m=()=>{g&&(clearInterval(g),g=void 0),u&&(u.close(),u=void 0),c.stop(),p=void 0,h.removeEventListener("ended",m)};let g=window.setInterval(()=>{if(p&&u&&Date.now()-E>1e3)try{h.readyState==="live"?p.enqueue(u.clone()):m()}catch{m()}},1e3);const R=new TransformStream({transform:(v,C)=>{h.readyState==="live"?(p=C,E=Date.now(),u===void 0?(u=v,C.enqueue(v.clone())):(C.enqueue(u),u=v)):v.close()}});return h.addEventListener("ended",m),l.readable.pipeThrough(R).pipeTo(h.writable),h}}(t);a&&(_.info("local screen video track begin to inject frame"),this._mediaStreamTrack=a)}n&&this._hints.indexOf($e.CUSTOM_TRACK)!==-1&&this.setEncoderConfiguration(n),this._processorContext=new bN(this.getTrackId(),"local"),this._processorDestination=new IN(this.processorContext),this.bindProcessorDestinationEvents()}play(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(typeof t=="string"){const r=document.getElementById(t);r?t=r:(_.warning("[".concat(this.getTrackId(),'] can not find "#').concat(t,'" element, use document.body')),t=document.body)}_.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(n));const i=ft(ft(ft({},this._getDefaultPlayerConfig()),n),{},{trackId:this.getTrackId(),element:t});this._player?this._player.updateConfig(i):(t instanceof HTMLVideoElement?this._player=new Wp(i):this._player=new Kp(i),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{const r=this.getVideoElementVisibleStatus();this.safeEmit(ld.VIDEO_ELEMENT_VISIBLE_STATUS,r)}catch{}},T("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,_.debug("[".concat(this.getTrackId(),"] stop video playback")))}
52async setEnabled(t,n){if(!n){if(t===this._enabled)return;this.stateCheck("enabled",t)}if(_.info("[".concat(this.getTrackId(),"] start setEnabled"),t),!t){this._originMediaStreamTrack.enabled=!1;try{await mt(this,te.NEED_DISABLE_TRACK,this)}catch(i){throw _.error("[".concat(this.getTrackId(),"] setEnabled to false error"),i.toString()),i}return n||(this._enabled=!1),void _.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await mt(this,te.NEED_ENABLE_TRACK,this)}catch(i){throw _.error("[".concat(this.getTrackId(),"] setEnabled to true error"),i.toString()),i}_.info("[".concat(this.getTrackId(),"] setEnabled to true success")),n||(this._enabled=!0)}async setMuted(t){t!==this._muted&&(this.stateCheck("muted",t),this._muted=t,this._originMediaStreamTrack.enabled=!t,_.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(t)),t?await mt(this,te.NEED_MUTE_TRACK,this):await mt(this,te.NEED_UNMUTE_TRACK,this))}async setSaveEncodeBitrateRatio(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this._saveEncodeBitrateRatio;if(this._saveEncodeBitrateRatio!==1&&this._encoderConfig&&this._encoderConfig.bitrateMax&&this._encoderConfig.bitrateMin){this._encoderConfig.bitrateMin=Math.floor(this._encoderConfig.bitrateMin*t),this._encoderConfig.bitrateMax=Math.floor(this._encoderConfig.bitrateMax*t),_.debug("[".concat(this.getTrackId(),"] set save encode bitrate ratio, ").concat(t)),this._saveEncodeBitrateRatio=1;try{await mt(this,te.NEED_UPDATE_VIDEO_ENCODER,this)}catch(n){return n.throw(_)}}}async setEncoderConfiguration(t,n){if(!this._enabled)throw new L(A.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(t=Kr(t),T("USE_STANDARD_BITRATE_DEFAULT")&&(delete t.bitrateMax,delete t.bitrateMin),this._forceBitrateLimit&&(t.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:t.bitrateMax,t.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:t.bitrateMin),t.width||t.height||t.frameRate){const i=jp({encoderConfig:t});(vn()||Hn()||Vr())&&(i.deviceId=void 0),_.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(t),JSON.stringify(i));try{await this._originMediaStreamTrack.applyConstraints(i),this.updateMediaStreamTrackResolution()}catch(r){const o=new L(A.UNEXPECTED_ERROR,r.toString());throw _.error("[".concat(this.getTrackId(),"] applyConstraints error"),o.toString()),o}}this._encoderConfig=t,this._hints.indexOf($e.SCREEN_TRACK)===-1&&this.updateBitrateFromProfile();try{await mt(this,te.NEED_UPDATE_VIDEO_ENCODER,this)}catch(i){return i.throw(_)}}getStats(){return Ms(()=>{_.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")},"localVideoTrackGetStatsWarning"),Ui(this,te.GET_STATS)||ft({},OS)}async setBeautyEffect(t){_.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect")}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameImage(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(t,n):await xS(t)}async findClosestProfile(){const{width:t,height:n,frameRate:i}=this.getMediaStreamTrackSettings(),{width:r,height:o,frameRate:s}=this._encoderConfig||{},a=id(this._videoWidth||t||r||0),c=id(this._videoHeight||n||o||0),d=function(l,h,u){if(!Array.isArray(T("VIDEO_ENCODER_CONFIG_LIST"))||T("VIDEO_ENCODER_CONFIG_LIST").length===0)return!1;const p=Math.min(l,h);return!(p>=480)&&ft(ft({},T("VIDEO_ENCODER_CONFIG_LIST").find(E=>E.height>p)),{},{frameRate:u})}(a,c,id(i||s||15));if(d)return _.debug("[".concat(this.getTrackId(),"] find closest profile, ").concat(a,"x").concat(c," => ").concat(JSON.stringify(d))),this.setEncoderConfiguration(d)}async setBitrateLimit(t){_.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(t))),t&&(this._forceBitrateLimit=t,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax<t.max_bitrate?this._encoderConfig.bitrateMax:t.max_bitrate:this._encoderConfig.bitrateMax=t.max_bitrate,this._encoderConfig.bitrateMin,this._encoderConfig.bitrateMin=t.min_bitrate))}async setOptimizationMode(t){if(t!=="motion"&&t!=="detail"&&t!=="balanced")return void _.error(A.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const n=this._optimizationMode;try{this._optimizationMode=t,await mt(this,te.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this)}catch(i){throw this._optimizationMode=n,_.error("[".concat(this.getTrackId(),"] set optimization mode failed"),i.toString()),i}_.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(t,")"))}
52setScalabiltyMode(t){if(t.numSpatialLayers===1&&t.numTemporalLayers!==1)return _.error(A.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=t,_.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(t,")"))}updateMediaStreamTrackResolution(){NN(this._originMediaStreamTrack).then(t=>{let[n,i]=t;this._videoHeight=i,this._videoWidth=n}).catch(Hl)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(t){if(!this._enabled)throw new L(A.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");_.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(t)),t=Kr(t),this._forceBitrateLimit&&(t.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:t.bitrateMax,t.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:t.bitrateMin),this._encoderConfig=t,this._hints.indexOf($e.SCREEN_TRACK)===-1&&this.updateBitrateFromProfile();try{await mt(this,te.NEED_UPDATE_VIDEO_ENCODER,this)}catch(n){return n.throw(_)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:t,height:n,frameRate:i}=this.getMediaStreamTrackSettings();if(!t||!n||!i)return;const{bitrateMax:r,bitrateMin:o}=this._encoderConfig;if(o==null||r==null){const{max:s,min:a}=function(c,d,l,h,u){const p=T("BITRATE_ADAPTER_TYPE");if(p==="DEFAULT_BITRATE")return{min:h,max:u};if(u===void 0){var E;const g=Math.floor(200*Math.pow(l/15,.6)*Math.pow(c*d/640/360,.75));u=p==="STANDARD_BITRATE"?4*g:2*g,h=(E=h)!==null&&E!==void 0?E:g}else{var m;h=(m=h)!==null&&m!==void 0?m:Math.floor(u/10)}return{min:h,max:u}}(t,n,i,o,r);if(this._encoderConfig.bitrateMin=a,this._encoderConfig.bitrateMax=s,T("VIDEO_STANDARD_BITRATE_VERSION")&&o==null&&r==null){const[c,d]=function(l,h,u){const p=4*Math.floor(2e5*Math.pow(u/15,.6)*Math.pow(l*h/230400,.75)),E=l*h,m=new Map([[19200,.9],[230400,.85],[518400,.75],[921600,.7],[2073600,.6],[3686400,.5]]),g=new Map([[230400,.95],[518400,.9],[921600,.85],[2073600,.8]]);let R=ti(m).call(m).next().value,v=1;if(m.has(E))R=m.get(E);else{var C;const X=Pi(C=Array.from(m.entries())).call(C,(se,_e)=>{let[me]=se,[ke]=_e;return me-ke}),q=X.find(se=>{let[_e]=se;return _e>E});if(q){const se=X.indexOf(q);if(se>0){const _e=X[se-1],me=(E-_e[0])/(q[0]-_e[0]);R=_e[1]+me*(q[1]-_e[1])}else R=q[1]}else R=X[X.length-1][1]}if(g.has(E))v=g.get(E);else{var w;const X=Pi(w=Array.from(g.entries())).call(w,(se,_e)=>{let[me]=se,[ke]=_e;return me-ke}),q=X.find(se=>{let[_e]=se;return _e>E});if(q){const se=X.indexOf(q);if(se>0){const _e=X[se-1],me=(E-_e[0])/(q[0]-_e[0]);v=_e[1]+me*(q[1]-_e[1])}else v=q[1]}else v=X[X.length-1][1]}const b=T("VIDEO_NEW_BITRATE_RATIO");b&&b>0&&(R=b/100);const y=Math.floor(p*R),N=Math.floor(65e4*Math.pow(l*h/230400,.5)*Math.pow(u/15,.69));let k=y;const U=T("VIDEO_STANDARD_BITRATE_VERSION");return U&&U>0&&(U===1?k=p:U===2?k=y:U===3&&(k=N)),[Math.floor(k/1e3),v]}(t,n,i);this._encoderConfig.bitrateMax=c,this._encoderConfig.bitrateMin=a?Math.min(a,c):c,this._saveEncodeBitrateRatio=d,_.debug("[".concat(this.getTrackId(),"] update new bitrate from profile, [w: ").concat(t,", h: ").concat(n,", fps: ").concat(i,"] => [brMax: ").concat(this._encoderConfig.bitrateMax,", brMin: ").concat(this._encoderConfig.bitrateMin,", save_bitrate_ratio: ").concat(this._saveEncodeBitrateRatio,"]"))}else _.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(t,", h: ").concat(n,", fps: ").concat(i,"] => [brMax: ").concat(s,", brMin: ").concat(a,"]")),this._saveEncodeBitrateRatio=1}}getVideoElementVisibleStatus(){try{var t,n;const i=this==null||(t=this._player)===null||t===void 0?void 0:t.getContainerElement(),r={track:this,element:this==null||(n=this._player)===null||n===void 0?void 0:n.getVideoElement(),slot:i==null?void 0:i.parentElement},{element:o,slot:s}=r;if(this.isPlaying&&o instanceof HTMLVideoElement&&s instanceof HTMLElement){const a=SO.checkOneElementVisible(o),c=Object.assign({},a);if(c.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=c.visible;const d=Z.reportApiInvoke(null,{tag:ht.TRACER,name:vt.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});c.visible?d.onSuccess("Video is visible"):d.onSuccess("Invisible because of ".concat(c.reason))}return c}return}catch(i){throw new L(A.GET_VIDEO_ELEMENT_VISIBLE_ERROR,i.message)}}async renewMediaStreamTrack(t){}pipe(t){if(this.processor===t)return t;if(t._source)throw new L(A.INVALID_OPERATION,"Processor ".concat(t.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=t,this.processor._source=this,t.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),t}unpipe(){if(!this.processor)return;const t=this.processor;this.processor._source=void 0,this.processor=void 0,t.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe()}clone(t){let n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],i=this._encoderConfig;t&&(i=ft(ft({},i),Kr(t))),i=Da(i);const r=Qe(8,"track-video-cloned-"),o=new jx(n?this._mediaStreamTrack.clone():this._mediaStreamTrack,i,Da(this._scalabilityMode),this._optimizationMode,r,Da(this._hints));return t&&i&&o.setEncoderConfiguration(i),_.debug("clone video track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(n)),o}async replaceTrack(t,n){if(!(t instanceof MediaStreamTrack))throw new L(A.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if(t.kind!=="video")throw new L(A.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(t,n,!0),this.updateMediaStreamTrackResolution()}sendSeiData(t){if(Ms(()=>{Z.reportApiInvoke(null,{name:vt.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:ht.TRACER}).onSuccess("")},this._mediaStreamTrack.id||this.getTrackId()),!T("ENABLE_VIDEO_SEI")||!T("ENABLE_ENCODED_TRANSFORM"))return void _.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(t instanceof Uint8Array==0)return new L(A.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const n=this.getRTCRtpTransceiver();if(!n)return void _.warning("Video track is not published, SEI can not be send");const i=n.sender.getParameters();if(i.codecs.length===0)return;const r=i.codecs[0].mimeType.toLocaleLowerCase();r==="video/h264"||r==="video/h265"?this.safeEmit("sei-to-send",t):_.warning("SEI is not supported by ".concat(r))}bindProcessorDestinationEvents(){this.processorDestination.on(ri.ON_TRACK,async t=>{t?t!==this._mediaStreamTrack&&(this._mediaStreamTrack=t,this._updatePlayerSource(),await mt(this,te.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await mt(this,te.NEED_REPLACE_TRACK,this))})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(ri.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners($i.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners($i.REQUEST_CONSTRAINTS)}},Ue(Ne.prototype,"play",[vD,AD],Object.getOwnPropertyDescriptor(Ne.prototype,"play"),Ne.prototype),Ue(Ne.prototype,"stop",[CD],Object.getOwnPropertyDescriptor(Ne.prototype,"stop"),Ne.prototype),Ue(Ne.prototype,"setEnabled",[yD,ID,bD],Object.getOwnPropertyDescriptor(Ne.prototype,"setEnabled"),Ne.prototype),Ue(Ne.prototype,"setMuted",[wD,OD,ND],Object.getOwnPropertyDescriptor(Ne.prototype,"setMuted"),Ne.prototype),Ue(Ne.prototype,"setSaveEncodeBitrateRatio",[DD,PD],Object.getOwnPropertyDescriptor(Ne.prototype,"setSaveEncodeBitrateRatio"),Ne.prototype),Ue(Ne.prototype,"setEncoderConfiguration",[LD,kD],Object.getOwnPropertyDescriptor(Ne.prototype,"setEncoderConfiguration"),Ne.prototype),Ue(Ne.prototype,"getStats",[MD],Object.getOwnPropertyDescriptor(Ne.prototype,"getStats"),Ne.prototype),Ue(Ne.prototype,"setBeautyEffect",[UD,VD],Object.getOwnPropertyDescriptor(Ne.prototype,"setBeautyEffect"),Ne.prototype),Ue(Ne.prototype,"getCurrentFrameData",[xD],Object.getOwnPropertyDescriptor(Ne.prototype,"getCurrentFrameData"),Ne.prototype),Ue(Ne.prototype,"getCurrentFrameImage",[FD],Ob
vendor: 9,520 bytes, line 52
52ject.getOwnPropertyDescriptor(Ne.prototype,"getCurrentFrameImage"),Ne.prototype),Ue(Ne.prototype,"findClosestProfile",[BD,GD],Object.getOwnPropertyDescriptor(Ne.prototype,"findClosestProfile"),Ne.prototype),Ue(Ne.prototype,"setBitrateLimit",[jD],Object.getOwnPropertyDescriptor(Ne.prototype,"setBitrateLimit"),Ne.prototype),Ue(Ne.prototype,"setOptimizationMode",[WD],Object.getOwnPropertyDescriptor(Ne.prototype,"setOptimizationMode"),Ne.prototype),Ue(Ne.prototype,"setScalabiltyMode",[KD],Object.getOwnPropertyDescriptor(Ne.prototype,"setScalabiltyMode"),Ne.prototype),Ue(Ne.prototype,"updateMediaStreamTrackResolution",[HD],Object.getOwnPropertyDescriptor(Ne.prototype,"updateMediaStreamTrackResolution"),Ne.prototype),Ue(Ne.prototype,"pipe",[YD],Object.getOwnPropertyDescriptor(Ne.prototype,"pipe"),Ne.prototype),Ue(Ne.prototype,"unpipe",[XD],Object.getOwnPropertyDescriptor(Ne.prototype,"unpipe"),Ne.prototype),Ue(Ne.prototype,"close",[JD],Object.getOwnPropertyDescriptor(Ne.prototype,"close"),Ne.prototype),Ue(Ne.prototype,"replaceTrack",[zD],Object.getOwnPropertyDescriptor(Ne.prototype,"replaceTrack"),Ne.prototype),Ne),Hp=(qD=ue({argsMap:(e,t)=>[e.getTrackId(),t]}),ZD=Gt(),QD=rd("CameraVideoTrack","_enabledMutex"),$D=ue({argsMap:(e,t)=>[e.getTrackId(),t]}),eP=Gt(),tP=ue({argsMap:(e,t)=>[e.getTrackId(),t]}),nP=Gt(),iP=ue({argsMap:e=>[e.getTrackId()]}),ir=class Wx extends pt{get __className__(){return"CameraVideoTrack"}constructor(t,n,i,r,o,s){super(t,Kr(n.encoderConfig),r,o,s),P(this,"_config",void 0),P(this,"_originalConstraints",void 0),P(this,"_constraints",void 0),P(this,"_enabled",!0),P(this,"_deviceName","default"),P(this,"tryResumeVideoForIOS15_16WeChat",async()=>{(ed()||qg())&&!function(){const a=Fe();if(a.os!==pn.IOS||!a.osVersion)return!1;const c=a.osVersion.split(".");return Number(c[0])===15&&Number(c[1])>=2}()&&hO()&&this._enabled&&!this._isClosed&&(_.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())}),this._config=n,this._originalConstraints=i,this._constraints=i,this._deviceName=t.label,this._encoderConfig=Kr(this._config.encoderConfig),ct.on(Nn.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),ct.on(Nn.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents()}async setDevice(t){return typeof t=="string"?this._setDeviceById(t):t.deviceId?this._setDeviceById(t.deviceId):t.facingMode?this._setDeviceByFacingModel(t.facingMode):void 0}async _setDeviceById(t){if(_.info("[".concat(this.getTrackId(),"] set device to ").concat(t)),this._enabled)try{const n=await nr.getDeviceById(t),i={};i.video=ft({},this._constraints),i.video.deviceId={exact:t},i.video.facingMode=void 0,this._originMediaStreamTrack.stop();let r=null;try{r=await tr(i,this.getTrackId())}catch(o){throw _.error("[".concat(this.getTrackId(),"] setDevice failed"),o.toString()),r=await tr({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!1),o}await this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=n.label,this._config.cameraId=t,this._constraints.deviceId={exact:t}}catch(n){throw _.error("[".concat(this.getTrackId(),"] setDevice error"),n.toString()),n}else try{const n=await nr.getDeviceById(t);this._deviceName=n.label,this._config.cameraId=t,this._constraints.deviceId={exact:t}}catch(n){throw _.error("[".concat(this.getTrackId(),"] setDevice error"),n.toString()),n}_.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(t){_.info("[".concat(this.getTrackId(),"] set facingMode ").concat(t));const n={video:ft(ft({},this._constraints),{},{deviceId:void 0,facingMode:{exact:t}})};if(this._enabled){this._originMediaStreamTrack.stop();let i=null;try{i=await tr(n,this.getTrackId())}catch(r){throw _.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),r.toString()),i=await tr({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(i.getVideoTracks()[0],!1),r}await this._updateOriginMediaStreamTrack(i.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution()}this._deviceName="",this._config.facingMode=t,this._config.cameraId=void 0,this._constraints=ft({},n.video),_.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(t,n){if(!n){if(t===this._enabled)return;this.stateCheck("enabled",t)}if(_.info("[".concat(this.getTrackId(),"] start setEnabled"),t),t){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const i=await tr({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(i.getVideoTracks()[0],!1)}await mt(this,te.NEED_ENABLE_TRACK,this)}catch(i){throw _.error("[".concat(this.getTrackId(),"] setEnabled true error"),i.toString()),i}this.updateMediaStreamTrackResolution(),_.info("[".concat(this.getTrackId(),"] setEnabled to true success")),n||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),n||(this._enabled=!1);try{await mt(this,te.NEED_DISABLE_TRACK,this)}catch(i){throw _.error("[".concat(this.getTrackId(),"] setEnabled to false error"),i.toString()),i}_.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(t,n){if(!this._enabled)throw new L(A.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");t=Kr(t),T("USE_STANDARD_BITRATE_DEFAULT")&&(delete t.bitrateMax,delete t.bitrateMin),this._forceBitrateLimit&&(t.bitrateMax=this._forceBitrateLimit.max_bitrate||t.bitrateMax,t.bitrateMin=this._forceBitrateLimit.min_bitrate||t.bitrateMin);const i=Ct(this._config);i.encoderConfig=t;const r=jp(i);(vn()||Hn()||Vr())&&(r.deviceId=void 0),_.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(t),JSON.stringify(r));try{await this._originMediaStreamTrack.applyConstraints(r),this.updateMediaStreamTrackResolution()}catch(o){const s=new L(A.UNEXPECTED_ERROR,o.toString());throw _.error("[".concat(this.getTrackId(),"] applyConstraints error"),s.toString()),s}this._config=i,this._constraints=r,this._originalConstraints=r,this._encoderConfig=t,this._hints.indexOf($e.SCREEN_TRACK)===-1&&this.updateBitrateFromProfile();try{await mt(this,te.NEED_UPDATE_VIDEO_ENCODER,this)}catch(o){return o.throw(_)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((Hn()||Vr())&&this._enabled&&!this._isClosed&&ct.duringInterruption){const t=async()=>{ct.off(Nn.IOS_INTERRUPTION_END,t),this._enabled&&!this._isClosed&&(_.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};ct.on(Nn.IOS_INTERRUPTION_END,t)}else _.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(ld.TRACK_ENDED)}async renewMediaStreamTrack(t){const n=t||this._constraints,i=nr.searchDeviceIdByName(this._deviceName);if(i&&!n.deviceId&&(n.deviceId={exact:i}),this._enabled){const r=await tr({video:n},this.getTrackId());this._constraints=n,await this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),ct.off(Nn.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),ct.off(Nn.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],i=this._encoderConfig;t&&(i=ft(ft({},i),Kr(t))),i=Da(i);const r=Qe(8,"track-cam-cloned-"),o=new Wx(n?this._mediaStreamTrack.clone():this._mediaStreamTrack,Da(ft(ft({},this._config),{},{encoderConfig:i})),Da(this._constraints),Da(this._scalabilityMode),this._optimizationMode,r);return t&&i&&o.setEncoderConfiguration(i),_.debug("clone track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(n)),o}bindProcessorContextEvents(){this.processorContext.on($i.REQUEST_UPDATE_CONSTRAINTS,async(t,n,i)=>{try{const r=Object.assign({},this._originalConstraints,...t);await this.renewMediaStreamTrack(r),n()}catch(r){i(r)}}),this.processorContext.on($i.REQUEST_CONSTRAINTS,async t=>{t(this._originMediaStreamTrack.getSettings())})}},Ue(ir.prototype,"setDevice",[qD,ZD],Object.getOwnPropertyDescriptor(ir.prototype,"setDevice"),ir.prototype),Ue(ir.prototype,"setEnabled",[QD,$D,eP],Object.getOwnPropertyDescriptor(ir.prototype,"setEnabled"),ir.prototype),Ue(ir.prototype,"setEncoderConfiguration",[tP,nP],Object.getOwnPropertyDescriptor(ir.prototype,"setEncoderConfiguration"),ir.prototype),Ue(ir.prototype,"close",[iP],Object.getOwnPropertyDescriptor(ir.prototype,"close"),ir.prototype),ir);function rP(e){const t=Qe(8,"track-cus-"),n=Z.reportApiInvoke(null,{id:t,tag:ht.TRACER,name:vt.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),i=new jt(e.mediaStreamTrack,e.encoderConfig?Fp(e.encoderConfig):{},t,!1);return _.info("create custom audio track success with config",e,"trackId",i.getTrackId()),n.onSuccess(i.getTrackId()),i}function FS(e,t,n,i){n.optimizationMode&&(i&&i.width&&i.height?(n.encoderConfig=ft(ft({},i),{},{bitrateMin:i.bitrateMin,bitrateMax:i.bitrateMax}),n.optimizationMode!=="motion"&&n.optimizationMode!=="detail"||(t.contentHint=n.optimizationMode,t.contentHint===n.optimizationMode?_.debug("[".concat(e,"] set content hint to"),n.optimizationMode):_.debug("[".concat(e,"] set content hint failed")))):_.w
52arning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}var oP,sP,aP,cP,_r,dP,lP,uP,hP,pP,_P,mP,Fn;let EP=class extends EN{getUserId(){return this._userId}constructor(e,t,n,i){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(i.clientId,"_").concat(Qe(5,""))),P(this,"_userId",void 0),P(this,"_uintId",void 0),P(this,"_isDestroyed",!1),P(this,"store",void 0),P(this,"processor",void 0),P(this,"processorContext",void 0),this._userId=t,this._uintId=n,this.store=i}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,_.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}},md=(oP=ue({argsMap:(e,t,n)=>[e.getTrackId(),typeof t=="string"?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",n]}),sP=ue({argsMap:e=>[e.getTrackId()]}),aP=ue({argsMap:(e,t)=>[e.getTrackId(),t.name]}),cP=ue({argsMap:e=>[e.getTrackId()]}),Ue((_r=class extends EP{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==Dn.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,n,i,r){super(e,t,n,i),P(this,"_videoVisibleTimer",null),P(this,"_previousVideoVisibleStatus",void 0),P(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),P(this,"trackMediaType",ud.VIDEO),P(this,"_videoWidth",void 0),P(this,"_videoHeight",void 0),P(this,"_player",void 0),P(this,"_prePlayer",void 0),P(this,"processorDestination",void 0),P(this,"processorContext",void 0),this._prePlayer=r,this.updateMediaStreamTrackResolution(),this.processorContext=new bN(this.getTrackId(),"remote"),this.processorDestination=new IN(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return Ms(()=>{_.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")},"remoteVideoTrackGetStatsWarning"),Ui(this,te.GET_STATS)||ft({},_N)}play(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.safeEmit(pr.PLAY_START),typeof e=="string"){const i=document.getElementById(e);i?e=i:(_.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}_.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const n=ft(ft({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});if(this._player)this._player.updateConfig(n);else{let i=!1,r=!1;const o=this._prePlayer&&!this._prePlayer.isDestroyed&&e===this._prePlayer.config.element;this._prePlayer&&!o&&(this._prePlayer.destroy(),r=!0),o?(this._player=this._prePlayer,i=this._player.videoState>0,this._player.updateConfig(n)):this._player=e instanceof HTMLVideoElement?new Wp(n):new Kp(n),this._prePlayer=void 0,this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(pr.FIRST_FRAME_DECODED),r&&this.safeEmit(pr.FIRST_FRAME_RENDER)},this._player.onVideoStateChanged=s=>{this.safeEmit(pr.VIDEO_STATE_CHANGED,s)},i&&(this._player.onFirstVideoFrameDecoded(),this._player.onVideoStateChanged(this._player.videoState))}this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{const i=this.getVideoElementVisibleStatus();this.safeEmit(pr.VIDEO_ELEMENT_VISIBLE_STATUS,i)}catch{}},T("CHECK_VIDEO_VISIBLE_INTERVAL")),this.safeEmit(pr.PLAY_END)}stop(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(e),this._player=void 0,_.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){NN(this._originMediaStreamTrack).then(e=>{let[t,n]=e;this._videoHeight=n,this._videoWidth=t}).catch(Hl)}_updatePlayerSource(){_.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const n=this==null||(e=this._player)===null||e===void 0?void 0:e.getContainerElement(),i={track:this,element:this==null||(t=this._player)===null||t===void 0?void 0:t.getVideoElement(),slot:n==null?void 0:n.parentElement},{element:r,slot:o}=i;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const s=SO.checkOneElementVisible(r),a=Object.assign({},s);if(a.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=a.visible;const c=Z.reportApiInvoke(null,{tag:ht.TRACER,name:vt.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});a.visible?c.onSuccess("Video is visible"):c.onSuccess("Invisible because of ".concat(a.reason))}return a}return}catch(n){throw new L(A.GET_VIDEO_ELEMENT_VISIBLE_ERROR,n.message)}}pipe(e){if(this.processor===e)return e;if(e._source)throw new L(A.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(ri.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(ri.ON_TRACK)}_destroy(){this._prePlayer&&(this._prePlayer.destroy(),this._prePlayer=void 0),super._destroy(),this.unbindProcessorDestinationEvents()}
52_onSei(e){this.emit(xa.SEI_RECEIVED,e)}}).prototype,"play",[oP],Object.getOwnPropertyDescriptor(_r.prototype,"play"),_r.prototype),Ue(_r.prototype,"stop",[sP],Object.getOwnPropertyDescriptor(_r.prototype,"stop"),_r.prototype),Ue(_r.prototype,"pipe",[aP],Object.getOwnPropertyDescriptor(_r.prototype,"pipe"),_r.prototype),Ue(_r.prototype,"unpipe",[cP],Object.getOwnPropertyDescriptor(_r.prototype,"unpipe"),_r.prototype),_r),Ed=(dP=ue({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),lP=ue({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),uP=ue({argsMap:(e,t)=>[e.getTrackId(),t]}),hP=ue({argsMap:e=>[e.getTrackId()]}),pP=ue({argsMap:e=>[e.getTrackId()]}),_P=ue({argsMap:(e,t)=>[e.getTrackId(),t.name]}),mP=ue({argsMap:e=>[e.getTrackId()]}),Ue((Fn=class extends EP{get isPlaying(){return this._useAudioElement?zn.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,n,i){super(e,t,n,i),P(this,"trackMediaType",ud.AUDIO),P(this,"_source",void 0),P(this,"_useAudioElement",!0),P(this,"_volume",100),P(this,"processorContext",void 0),P(this,"processorDestination",void 0),P(this,"_played",!1),P(this,"_bypassWebAudio",!1),T("DISABLE_WEBAUDIO")?(this._source=new VS,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new kS(e,!0),T("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(Qi.RECEIVE_TRACK_BUFFER,()=>{this.safeEmit(pr.FIRST_FRAME_DECODED)}),this.processorContext=new ON(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new wN(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(Qi.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})})}setAudioFrameCallback(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:4096;if(!e)return this._source.removeAllListeners(Qi.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Qi.ON_AUDIO_BUFFER),this._source.on(Qi.ON_AUDIO_BUFFER,n=>e(n))}setVolume(e){this._volume=e,this._useAudioElement?zn.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}setAmplifiedVolume(e){this._useAudioElement&&this._played&&(zn.stop(this.getTrackId()),this._source.play()),this._useAudioElement=!1,e=Math.min(e,T("MAX_WEBAUDIO_VOLUME")),this._volume=e,this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!oN())throw new L(A.NOT_SUPPORTED,"your browser does not support setting the audio output device");await zn.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getVolume(){return this._useAudioElement?zn.getVolume(this.getTrackId()):this._source instanceof kS?this._source.getAudioVolume():0}getStats(){return Ms(()=>{_.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")},"remoteAudioTrackGetStatsWarning"),Ui(this,te.GET_STATS)||ft({},pN)}play(){_.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(_.debug("[".concat(this.getTrackId(),"] use audio element to play")),zn.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):(_.debug("[".concat(this.getTrackId(),"] use audio context to play")),this._source.play())}stop(){_.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?zn.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];_.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&zn.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(e){if(this._bypassWebAudio)throw new L(A.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new L(A.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(this._bypassWebAudio)throw new L(A.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;(e=this._source.processSourceNode)===null||e===void 0||e.disconnect(),this.processor._source=!1,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(ri.ON_TRACK,async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}),this.processorDestination.on(ri.ON_NODE,e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t)})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(ri.ON_TRACK),this.processorDestination.removeAllListeners(ri.ON_NODE)}}).prototype,"setVolume",[dP],Object.getOwnPropertyDescriptor(Fn.prototype,"setVolume"),Fn.prototype),Ue(Fn.prototype,"setAmplifiedVolume",[lP],Object.getOwnPropertyDescriptor(Fn.prototype,"setAmplifiedVolume"),Fn.prototype),Ue(Fn.prototype,"setPlaybackDevice",[uP],Object.getOwnPropertyDescriptor(Fn.prototype,"setPlaybackDevice"),Fn.prototype),Ue(Fn.prototype,"play",[hP],Object.getOwnPropertyDescriptor(Fn.prototype,"play"),Fn.prototype),Ue(Fn.prototype,"stop",[pP],Object.getOwnPropertyDescriptor(Fn.prototype,"stop"),Fn.prototype),Ue(Fn.prototype,"pipe",[_P],Object.getOwnPropertyDescriptor(Fn.prototype,"pipe"),Fn.prototype),Ue(Fn.prototype,"unpipe",[mP],Object.getOwnPropertyDescriptor(Fn.prototype,"unpipe"),Fn.prototype),Fn);const Vi=new class extends Nt{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),P(this,"_lastHiddenTime",0),P(this,"_lastVisibleTime",0),P(this,"needUploadStats",[]),P(this,"isCollectingStats",!1),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),this.isCollectingStats&&this.needUploadStats.push(document.visibilityState==="visible"?1:0),_.debug("current web page is ".concat(document.visibilityState)),this.emit
52("VISIBILITY_CHANGE",document.visibilityState)})}startCollectStats(){this.isCollectingStats=!0,this.needUploadStats.push(this.visibility==="visible"?1:0)}stopCollectStats(){this.isCollectingStats=!1,this.needUploadStats.length=0}};let fP=class extends Nt{constructor(e,t){super(),P(this,"trackMediaType",ud.DATA),P(this,"_version",1),P(this,"_type",3),P(this,"_config",void 0),P(this,"_originDataChannel",void 0),P(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),P(this,"_dataStreamPacketHandler",{serialize:n=>n,deserialize:n=>n}),P(this,"_datachannelEventMap",new Map),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader()}useDataStream(e){this._dataStreamPacketHandler=e}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return T("DATASTREAM_MAX_RETRANSMITS")}get metadata(){return this._config.metadata}get readyState(){var e,t;return(e=(t=this._originDataChannel)===null||t===void 0?void 0:t.readyState)!==null&&e!==void 0?e:"connecting"}get _originDataChannelId(){var e,t;return(e=(t=this._originDataChannel)===null||t===void 0?void 0:t.id)!==null&&e!==void 0?e:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}async _waitTillOpen(){return new K((e,t)=>{if(this._originDataChannel){this._originDataChannel.readyState==="open"&&e();const n=setTimeout(()=>{var i;t(new L(A.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat((i=this._originDataChannel)===null||i===void 0?void 0:i.id)))},1e4);this._originDataChannel.onopen=()=>{clearTimeout(n),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(n),new L(A.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new L(A.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"))})}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e)}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id)}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[Bp.OPEN,Bp.CLOSE,Bp.ERROR].forEach(t=>{const n=()=>{this.emit(t)};this._datachannelEventMap.set(t,n),e.addEventListener(t,n)})}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach(t=>{let[n,i]=t;e.removeEventListener(n,i)}),this._datachannelEventMap.clear()}},TX=class extends fP{constructor(e){super(e),P(this,"_messageListener",void 0),this._messageListener=t=>{if(t.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);const n=t.data.slice(0,this._dataStreamPacketHeader.byteLength),i=new DataView(n).getUint8(3);if(i!==this.id)return void(T("SHOW_DATASTREAM2_LOG")&&_.debug("invalid datachannel id: ".concat(i," !== ").concat(this.id)));let r=t.data.slice(this._dataStreamPacketHeader.byteLength);r=this._dataStreamPacketHandler.deserialize(r),this.emit(Bp.MESSAGE,r)}}_updateDataChannelConfig(e){this._config=e}_updateOriginDataChannel(e){super._updateOriginDataChannel(e),this._bandRemoteDataChannelEvents()}_close(){this._originDataChannel&&(this._originDataChannel.removeEventListener("message",this._messageListener),super._close())}_bandRemoteDataChannelEvents(){this._originDataChannel&&this._originDataChannel.addEventListener("message",this._messageListener)}},RX=class extends fP{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);const n=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);n.set(new Uint8Array(this._dataStreamPacketHeader),0),n.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(n.buffer)}}};function Yp(){const e=new Blob([atob("Y29uc3QgdD0idmlkZW8vaDI2NCIsZT0idmlkZW8vaDI2NSI7ZnVuY3Rpb24gbih0LGUsbil7bGV0IGE9bmV3IFVpbnQ4QXJyYXkodCxlLG4pLHI9W10sbz0wO2Zvcig7ci5sZW5ndGg8bjspbyszPG4mJjA9PT1hW29dJiYwPT09YVtvKzFdJiYzPT09YVtvKzJdJiYoMD09PWFbbyszXXx8MT09PWFbbyszXXx8Mj09PWFbbyszXXx8Mz09PWFbbyszXSk/KHIucHVzaChhW29dLGFbbysxXSxhW28rM10pLG8rPTQpOihyLnB1c2goYVtvXSksbysrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkocil9ZnVuY3Rpb24gYShhLHIpe3N3aXRjaC
52hyKXtjYXNlIHQ6cmV0dXJuIGZ1bmN0aW9uKHQpe2NvbnN0IGU9bmV3IERhdGFWaWV3KHQuZGF0YSk7bGV0IGE9MDtmb3IoO2ErNDx0LmRhdGEuYnl0ZUxlbmd0aDspe2lmKDA9PT1lLmdldFVpbnQ4KGErMCkmJjA9PT1lLmdldFVpbnQ4KGErMSkmJjA9PT1lLmdldFVpbnQ4KGErMikmJjE9PT1lLmdldFVpbnQ4KGErMykmJjY9PT1lLmdldFVpbnQ4KGErNCkpe2xldCByPWErNixvPTAsaT0wO2Zvcig7MjU1PT09KGk9ZS5nZXRVaW50OChyKyspKTspbys9MjU1O28rPWk7Y29uc3Qgcz1uKHQuZGF0YSxyLG8pO3JldHVybiBuZXcgVWludDhBcnJheShzKX1hKyt9cmV0dXJuIG51bGx9KGEpO2Nhc2UgZTpyZXR1cm4gZnVuY3Rpb24odCl7Y29uc3QgZT1uZXcgRGF0YVZpZXcodC5kYXRhKTtsZXQgYT0wO2Zvcig7YSs1PHQuZGF0YS5ieXRlTGVuZ3RoOyl7aWYoMD09PWUuZ2V0VWludDgoYSswKSYmMD09PWUuZ2V0VWludDgoYSsxKSYmMD09PWUuZ2V0VWludDgoYSsyKSYmMT09PWUuZ2V0VWludDgoYSszKSYmNzg9PT1lLmdldFVpbnQ4KGErNCkmJjE9PT1lLmdldFVpbnQ4KGErNSkmJjEwMT09PWUuZ2V0VWludDgoYSs2KSl7bGV0IHI9YSs3LG89MCxpPTA7Zm9yKDsyNTU9PT0oaT1lLmdldFVpbnQ4KHIrKykpOylvKz0yNTU7bys9aTtjb25zdCBzPW4odC5kYXRhLHIsbyk7cmV0dXJuIG5ldyBVaW50OEFycmF5KHMpfWErK31yZXR1cm4gbnVsbH0oYSk7ZGVmYXVsdDpyZXR1cm4gbnVsbH19ZnVuY3Rpb24gcih0KXtjb25zdCBlPXQubGVuZ3RoO2xldCBuPVtdLGE9MDtmb3IoO2E8ZTspYSsyPGUmJjA9PT10W2FdJiYwPT09dFthKzFdJiYoMD09PXRbYSsyXXx8MT09PXRbYSsyXXx8Mj09PXRbYSsyXXx8Mz09PXRbYSsyXSk/KG4ucHVzaCh0W2FdLHRbYSsxXSwzLHRbYSsyXSksYSs9Myk6KG4ucHVzaCh0W2FdKSxhKyspO3JldHVybiBuZXcgVWludDhBcnJheShuKX1mdW5jdGlvbiBvKG4sYSxvKXtzd2l0Y2gobyl7Y2FzZSB0OnJldHVybiBmdW5jdGlvbih0LGUpe2NvbnN0IG49cihlKSxhPW4ubGVuZ3RoLG89TWF0aC5mbG9vcihhLzI1NSksaT1hJTI1NSxzPW5ldyBVaW50OEFycmF5KDYrbysxK2ErdC5ieXRlTGVuZ3RoKTtzWzBdPTAsc1sxXT0wLHNbMl09MCxzWzNdPTEsc1s0XT02LHNbNV09MTAxO2xldCBmPTA7Zm9yKDtmPG87KXNbNitmXT0yNTUsZisrO3JldHVybiBzWzYrZl09aSxmKysscy5zZXQobiw2K2YpLHMuc2V0KG5ldyBVaW50OEFycmF5KHQpLDYrZithKSxzLmJ1ZmZlcn0obixhKTtjYXNlIGU6cmV0dXJuIGZ1bmN0aW9uKHQsZSl7Y29uc3Qgbj1yKGUpLGE9bi5sZW5ndGgsbz1NYXRoLmZsb29yKGEvMjU1KSxpPWElMjU1LHM9bmV3IFVpbnQ4QXJyYXkoNytvKzErYSsxK3QuYnl0ZUxlbmd0aCk7c1swXT0wLHNbMV09MCxzWzJdPTAsc1szXT0xLHNbNF09Nzgsc1s1XT0xLHNbNl09MTAxO2xldCBmPTA7Zm9yKDtmPG87KXNbNytmXT0yNTUsZisrO3JldHVybiBzWzcrZl09aSxmKysscy5zZXQobiw3K2YpLGYrPWEsc1s3K2ZdPTEyOCxmKysscy5zZXQobmV3IFVpbnQ4QXJyYXkodCksNytmKSxzLmJ1ZmZlcn0obixhKTtkZWZhdWx0OnJldHVybiBudWxsfX1mdW5jdGlvbiBpKG4pe2lmKG4ubGVuZ3RoPDUpcmV0dXJuIiI7bGV0IGE9LTE7Zm9yKGxldCB0PTA7dDxuLmxlbmd0aC0zO3QrKyl7aWYoMD09PW5bdF0mJjA9PT1uW3QrMV0mJjE9PT1uW3QrMl0pe2E9dDticmVha31pZih0PG4ubGVuZ3RoLTQmJjA9PT1uW3RdJiYwPT09blt0KzFdJiYwPT09blt0KzJdJiYxPT09blt0KzNdKXthPXQ7YnJlYWt9fWlmKC0xPT09YSlyZXR1cm4iIjtjb25zdCByPWErKDA9PT1uW2ErMl0/NDozKTtpZihyPj1uLmxlbmd0aClyZXR1cm4iIjtjb25zdCBvPW5bcl07aWYoMTI4Jm8pcmV0dXJuIiI7aWYoKG8+PjEmNjMpPj0zMilyZXR1cm4gZTtpZihyKzE8bi5sZW5ndGgpe2lmKDA9PSgyNDgmbltyKzFdKSlyZXR1cm4gZX1yZXR1cm4oMzEmbyk8PTMxP3Q6IiJ9Y29uc3Qgcz03MSxmPTEsbD0yLHU9MSxnPTI7dmFyIGM7ZnVuY3Rpb24gZCh0LGU9ITEpe2NvbnN0IG49dC5nZXRVaW50OCgwKTtpZihuIT09cylyZXR1cm47Y29uc3QgYT10LmdldFVpbnQxNigxKSxyPWYrbCthLG89bmV3IFVpbnQ4QXJyYXkodC5ieXRlTGVuZ3RoLXIpO28uc2V0KG5ldyBVaW50OEFycmF5KHQuYnVmZmVyLHIsdC5ieXRlTGVuZ3RoLXIpKTtjb25zdCBpPXttOm4sdGx2TGVuOmEsdGx2OltdLGZyYW1lOm99O2xldCBkPWYrbDtmb3IoO2Q8cjspe2NvbnN0IG49dC5nZXRVaW50OChkKSxhPXQuZ2V0VWludDE2KGQrdSkscj11K2c7aWYobj09PWMuQVVESU9fTEVWRUwpe2xldCBvPXQuZ2V0VWludDgoZCtyKTtmb3IobGV0IGU9MTtlPGE7ZSsrKW89bzw8OHx0LmdldFVpbnQ4KGQrcitlKTtpLnRsdi5wdXNoKHt0YWc6bixsZW5ndGg6YSx2YWx1ZTplPzEyN15vPj4xOjEyNyZvfSl9ZWxzZSBpZihuPT09Yy5NRVRBREFUQXx8bj09PWMuQVVESU9fNjRfQklUX1BUUyl7Y29uc3QgZT1uZXcgVWludDhBcnJheShhKTtmb3IobGV0IG49MDtuPGE7bisrKWVbbl09dC5nZXRVaW50OChkK3Irbik7aS50bHYucHVzaCh7dGFnOm4sbGVuZ3RoOmEsdmFsdWU6ZX0pfWQrPXIrYX1yZXR1cm4gaX0hZnVuY3Rpb24odCl7dFt0LkFVRElPX0xFVkVMPTFdPSJBVURJT19MRVZFTCIsdFt0Lk1FVEFEQVRBPTJdPSJNRVRBREFUQSIsdFt0LkFVRElPXzY0X0JJVF9QVFM9M109IkFVRElPXzY0X0JJVF9QVFMifShjfHwoYz17fSkpLHNlbGYub25ydGN0cmFuc2Zvcm09dD0+e2NvbnN0IGU9dC50cmFuc2Zvcm1lcixuPVtdLHI9W107bGV0IGg9bnVsbDtlLm9wdGlvbnMucG9ydC5vbm1lc3NhZ2U9dD0+e3QuZGF0YS5zZWkmJm4ucHVzaCh0LmRhdGEuc2VpKSx0LmRhdGEubWV0YWRhdGEmJnIucHVzaCh0LmRhdGEubWV0YWRhdGEpfSxzZWxmLnBvc3RNZXNzYWdlKCJzdGFydGVkIik7Y29uc3QgcD1lLnJlYWRhYmxlLmdldFJlYWRlcigpLFU9ZS53cml0YWJsZS5nZXRXcml0ZXIoKTsic2VpLXJ4Ij09PWUub3B0aW9ucy5uYW1lP2Z1bmN0aW9uIHQoZSl7cC5yZWFkKCkudGhlbigobj0+e2lmKCFuLmRvbmUpe2lmKG4udmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkVmlkZW9GcmFtZSl7Y29uc3QgdD1pKG5ldyBVaW50OEFycmF5KG4udmFsdWUuZGF0YSkpLHI9YShuLnZhbHVlLHQpO2lmKHImJmUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHtzZWk6cn0pLCFoKXtjb25zdCB0PW4udmFsdWUuZ2V0TWV0YWRhdGEoKXx8e307aD17dHlwZTpu
52LnZhbHVlLnR5cGUscnRwVGltZXN0YW1wOm4udmFsdWUudGltZXN0YW1wLHBheWxvYWRUeXBlOnQucGF5bG9hZFR5cGV8fDAsc3NyYzp0LnN5bmNocm9uaXphdGlvblNvdXJjZXx8MCxsZW5ndGg6bi52YWx1ZS5kYXRhLmJ5dGVMZW5ndGgsLi4uIm1pbWVUeXBlImluIHQ/e21pbWVUeXBlOnQubWltZVR5cGV9Ont9fSxlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7Zmlyc3RGcmFtZUluZm86aH0pfX1VLndyaXRlKG4udmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShlKToic2VpLXR4Ij09PWUub3B0aW9ucy5uYW1lP2Z1bmN0aW9uIHQoZSl7cC5yZWFkKCkudGhlbigoYT0+e2lmKCFhLmRvbmUpe2lmKGEudmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkVmlkZW9GcmFtZSl7Y29uc3QgdD1pKG5ldyBVaW50OEFycmF5KGEudmFsdWUuZGF0YSkpLGU9bi5zaGlmdCgpO2lmKGUpe2NvbnN0IG49byhhLnZhbHVlLmRhdGEsZSx0KTtuJiYoYS52YWx1ZS5kYXRhPW4pfX1VLndyaXRlKGEudmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShlKToiYXVkaW8tbWV0YWRhdGEtcngiPT09ZS5vcHRpb25zLm5hbWU/ZnVuY3Rpb24gdChlKXtwLnJlYWQoKS50aGVuKChuPT57aWYoIW4uZG9uZSl7aWYobi52YWx1ZSBpbnN0YW5jZW9mIFJUQ0VuY29kZWRBdWRpb0ZyYW1lKXtjb25zdCB0PW5ldyBEYXRhVmlldyhuLnZhbHVlLmRhdGEpLGE9dC5nZXRVaW50OCgwKTtsZXQgcjtpZigwIT0oMTI4JmEpJiY3MSE9PWEpe2NvbnN0IGU9ZnVuY3Rpb24odCl7aWYodC5ieXRlTGVuZ3RoPD0wKXJldHVybltdO2NvbnN0IGU9W107bGV0IG49MDtmb3IoO248dC5ieXRlTGVuZ3RoOyl7Y29uc3QgYT0oMTI4JnQuZ2V0VWludDgobikpPj43LHI9MTI3JnQuZ2V0VWludDgobik7aWYoIShhJiZuKzQ8PXQuYnl0ZUxlbmd0aCkpe24rKzticmVha317Y29uc3QgYT10LmdldFVpbnQzMihuLCExKSxvPSgxNjc3NjE5MiZhKT4+MTAsaT0xMDIzJmE7ZS5wdXNoKHtwdDpyLHRzX29mZnNldDpvLGxlbmd0aDppLGRhdGE6bmV3IFVpbnQ4QXJyYXl9KSxuKz00fX1sZXQgYT10LmJ5dGVMZW5ndGgtbjtmb3IoY29uc3QgciBvZiBlKXtpZihyLmxlbmd0aD5hKXJldHVybiBjb25zb2xlLndhcm4oIkJyb2tlbiByZWQgcGF5bG9hZCIpLFtdO3IubGVuZ3RoPjAmJihyLmRhdGE9bmV3IFVpbnQ4QXJyYXkodC5idWZmZXIsdC5ieXRlT2Zmc2V0K24sci5sZW5ndGgpLG4rPXIubGVuZ3RoLGEtPXIubGVuZ3RoKX1pZihhPjApe2NvbnN0IHI9e3B0OmUubGVuZ3RoPjA/ZVtlLmxlbmd0aC0xXS5wdDowLHRzX29mZnNldDowLGxlbmd0aDphLGRhdGE6bmV3IFVpbnQ4QXJyYXkodC5idWZmZXIsdC5ieXRlT2Zmc2V0K24sYSl9O2UucHVzaChyKX1yZXR1cm4gZX0odCk7aWYoZS5sZW5ndGg+MCl7Y29uc3QgdD1mdW5jdGlvbih0KXtsZXQgZT0wO2ZvcihsZXQgbj0wO248dC5sZW5ndGg7bisrKWUrPW48dC5sZW5ndGgtMT80OjEsZSs9dFtuXS5sZW5ndGg7Y29uc3Qgbj1uZXcgVWludDhBcnJheShlKTtsZXQgYT0wO2ZvcihsZXQgZT0wO2U8dC5sZW5ndGg7ZSsrKWlmKGU8dC5sZW5ndGgtMSl7Y29uc3Qgcj0oMjE0NzQ4MzY0OHwoMTI3JnRbZV0ucHQpPDwyNHwoMjYyMTQzJnRbZV0udHNfb2Zmc2V0KTw8MTB8MTAyMyZ0W2VdLmxlbmd0aCk+Pj4wO25bYSsrXT1yPj4yNCYyNTUsblthKytdPXI+PjE2JjI1NSxuW2ErK109cj4+OCYyNTUsblthKytdPTI1NSZyfWVsc2UgblthKytdPTEyNyZ0W2VdLnB0O2Zvcihjb25zdCBlIG9mIHQpbi5zZXQoZS5kYXRhLGEpLGErPWUubGVuZ3RoO3JldHVybiBufShlLm1hcCgodD0+e2NvbnN0IGU9bmV3IFVpbnQ4QXJyYXkodC5sZW5ndGgpO2Uuc2V0KHQuZGF0YSk7Y29uc3Qgbj1kKG5ldyBEYXRhVmlldyhlLmJ1ZmZlcikpO3JldHVybiBuPy5mcmFtZSYmKHQuZGF0YT1uPy5mcmFtZSkscj1uLHR9KSkpO24udmFsdWUuZGF0YT10LmJ1ZmZlcn19ZWxzZSByPWQodCksciYmKG4udmFsdWUuZGF0YT1yLmZyYW1lLmJ1ZmZlcik7aWYocil7bGV0IHQ9ci50bHYuZmluZCgodD0+dC50YWc9PT1jLk1FVEFEQVRBKSk7aWYodCYmdC52YWx1ZSBpbnN0YW5jZW9mIFVpbnQ4QXJyYXkmJmUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHttZXRhZGF0YTp0LnZhbHVlfSksdD1yLnRsdi5maW5kKCh0PT50LnRhZz09PWMuQVVESU9fNjRfQklUX1BUUykpLHQmJnQudmFsdWUgaW5zdGFuY2VvZiBVaW50OEFycmF5JiY4PT10LnZhbHVlLmxlbmd0aCl7Y29uc3Qgbj1uZXcgRGF0YVZpZXcodC52YWx1ZS5idWZmZXIpLmdldEJpZ1VpbnQ2NCgwLCEwKTt0JiZ0LnZhbHVlIGluc3RhbmNlb2YgVWludDhBcnJheSYmZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3B0czpufSl9fX1VLndyaXRlKG4udmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShlKToiYXVkaW8tbWV0YWRhdGEtdHgiPT09ZS5vcHRpb25zLm5hbWUmJmZ1bmN0aW9uIHQoZSl7cC5yZWFkKCkudGhlbigobj0+e2lmKCFuLmRvbmUpe2lmKGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHtnZXRNZXRhZGF0YTohMH0pLG4udmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkQXVkaW9GcmFtZSl7Y29uc3QgdD1yLnNoaWZ0KCk7dCYmKG4udmFsdWUuZGF0YT1mdW5jdGlvbih0LGUsbil7Y29uc3QgYT1uLmJ5dGVMZW5ndGgscj1hK3UrZyxvPWYrbCtyLGk9bmV3IEFycmF5QnVmZmVyKHQuYnl0ZUxlbmd0aCtvKSxjPW5ldyBEYXRhVmlldyhpKTtjLnNldFVpbnQ4KDAscyksYy5zZXRVaW50MTYoMSxyKSxjLnNldFVpbnQ4KDMsZSksYy5zZXRVaW50MTYoNCxhKTtmb3IobGV0IHQ9MDt0PGE7dCsrKWMuc2V0VWludDgoNit0LG5bdF0pO2NvbnN0IGQ9bmV3IFVpbnQ4QXJyYXkoYy5idWZmZXIpO3JldHVybiBkLnNldChuZXcgVWludDhBcnJheSh0KSxvKSxkLmJ1ZmZlcn0obi52YWx1ZS5kYXRhLGMuQVVESU9fNjRfQklUX1BUUyx0KSl9VS53cml0ZShuLnZhbHVlKSxlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSx0KGUpfX0pKX0oZSl9LHNlbGYucG9zdE1lc3NhZ2UoInJlZ2lzdGVyZWQiKTsK")],{type:"text/javascript"});return setTimeout(()=>xh.revokeObjectURL(e),0),new Worker(xh.createObjectURL(e))}const gP=71,BS=1,GS=2,jS=1,SP=2;var Vs=function(e){return e[e.AUDIO_LEVEL=1]="AUDIO_LEVEL",e[e.METADATA=2]="METADATA",e[e.AUDIO_64_BIT_PTS=3]="AUDIO_64_BIT_PTS",e}(Vs||{});function WS(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const n=e.getUint8(0);if(n!==gP)return;const i=e.getUint16(1),r=BS+GS+i,o=new Uint8Array(e.byteLength-r);o.set(new Uint8Array(e.buffer,r,e.byteLength-r));const s={m:n,tlvLen:i,tlv:[],frame:o};let a=BS+GS;for(;a<r;){const c=e.getUint8(a),d=e.getUint16(a+jS),l=jS+SP;if(c===Vs.AUDIO_LEVEL){let h=e.getUint8(a+l);for(let u=1;u<d;u++)h=h<<8|e.getUint8(a+l+u);s.tlv.push({tag:c,length:d,value:t?127^h>>1:127&h})}else if(c===Vs.METADATA||c===Vs.AUDIO_64_BIT_PTS){const h=new Uint8Array(d);for(let u=0;u<d;u++)h[u]=e.getUint8(a+l+u);s.tlv.push({tag:c,length:d,value:h})}a+=l+d}return s}const Xp=new Map,Jp=127,Ga=1e-10,KS=139/13,zp=new Map;function HS(e,t,n){const i="".concat(e,"-").concat(t,"-").concat(n);let r=0;return zp.has(i)?r=zp.get(i):(r=Math.log(function(o,s){const a=o-s;s<a&&(s=a);let c=1;for(let d=o,l=1;d>s;d--,l++)c=c*d/l;return c}(t,e))+e*Math.log(.5)+(t-e)*Math.log(1-.5)-Math.log(n)+n*e,zp.set(i,r)),r<Ga&&(r=Ga),r}function TP(e,t,n){const i=t.length,r=e.length/i;let o=!1;for(let s=0,a=0;s<i;s++){let c=0;for(let d=a+r;a<d;a++)e[a]>
52n&&c++;t[s]!==c&&(t[s]=c,o=!0)}return o}window.cache=zp;let vX=0,RP=class{constructor(e){P(this,"id",void 0),P(this,"immediates",[]),P(this,"lastNonSilence",-1),P(this,"immediateSpeechActivityScore",Ga),P(this,"lastLevelChangedTime",Date.now()),P(this,"levels",[]),P(this,"longs",[]),P(this,"longSpeechActivityScore",Ga),P(this,"mediums",[]),P(this,"mediumSpeechActivityScore",Ga),P(this,"minLevel",0),P(this,"nextMinLevel",0),P(this,"nextMinLevelWindowLength",0),P(this,"energyScore",0),this.id=e||"".concat(vX++),this.immediates.length=50,this.mediums.length=10,this.longs.length=1,this.levels.length=this.immediates.length}computeImmediates(){const e=this.immediates,t=this.levels,n=this.minLevel+KS;let i=!1;for(let r=0;r<e.length;++r){let o=t[r];o<n&&(o=0);const s=Math.floor(o/KS);e[r]!==s&&(e[r]=s,i=!0)}return i}computeLongs(){return TP(this.mediums,this.longs,4)}computeMediums(){return TP(this.immediates,this.mediums,7)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=HS(this.immediates[0],13,.78)}evaluateLongSpeechActivityScore(e){this.longSpeechActivityScore=HS(this.longs[0],10,47),this.longSpeechActivityScore>Ga&&(this.lastNonSilence=e)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=HS(this.mediums[0],5,24)}evaluateSpeechActivityScores(e){this.computeImmediates()&&(this.evaluateImmediateSpeechActivityScore(),this.computeMediums()&&(this.evaluateMediumSpeechActivityScore(),this.computeLongs()&&this.evaluateLongSpeechActivityScore(e)))}getLastLevelChangedTime(){return this.lastLevelChangedTime}getLevels(){var e;return"[".concat(_a(e=[...this.levels]).call(e).join(),"]")}getSpeechActivityScore(e){switch(e){case 0:return this.immediateSpeechActivityScore;case 1:return this.mediumSpeechActivityScore;case 2:return this.longSpeechActivityScore;default:throw new Error("interval "+e)}}levelChanged(e,t){if(this.lastLevelChangedTime<=t){this.lastLevelChangedTime=t;let n=e;return e<0&&(n=0),e>Jp&&(n=Jp),this.levels.unshift(n),this.levels.length>this.immediates.length&&this.levels.pop(),this.updateMinLevel(n),n>=this.minLevel+KS?n:n/2}return-1}levelTimedOut(){this.levelChanged(0,this.lastLevelChangedTime)}updateMinLevel(e){if(e!==0){if(this.minLevel===0||this.minLevel>e)return this.minLevel=e,this.nextMinLevel=0,void(this.nextMinLevelWindowLength=0);if(this.nextMinLevel===0)return this.nextMinLevel=e,void(this.nextMinLevelWindowLength=1);if(this.nextMinLevel>e&&(this.nextMinLevel=e),this.nextMinLevelWindowLength++,this.nextMinLevelWindowLength>=750){let t=Math.sqrt(this.minLevel*this.nextMinLevel);t<0?t=0:t>Jp&&(t=Jp),this.minLevel=t,this.nextMinLevel=0,this.nextMinLevelWindowLength=0}}}},YS=class{constructor(e,t,n){P(this,"isDominant",void 0),P(this,"energyRanking",void 0),P(this,"energyScore",void 0),this.isDominant=e,this.energyRanking=t,this.energyScore=n}},AX=class extends Nt{constructor(e){super(),P(this,"dominantId",null),P(this,"lastDecisionTime",0),P(this,"lastLevelChangedTime",0),P(this,"lastLevelIdleTime",0),P(this,"relativeSpeechActivities",[]),P(this,"speakers",new Map),P(this,"enableSilence",!1),P(this,"timeoutToSilenceInterval",0),P(this,"decisionMaker",null),P(this,"loudest",[]),P(this,"numLoudestToTrack",3),P(this,"energyExpireTimeMs",250),P(this,"energyAlphaPct",50),this.timeoutToSilenceInterval=e,this.enableSilence=e>0,this.relativeSpeechActivities.length=3}setLoudestConfig(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:3,t=arguments.length>1?arguments[1]:void 0,n=arguments.length>2?arguments[2]:void 0;this.numLoudestToTrack=e,t!=null&&(this.energyExpireTimeMs=t),n!=null&&(this.energyAlphaPct=n),this.loudest.length>e&&this.loudest.splice(e)}getDominantSpeaker(){return this.dominantId}isAmongLoudest(e){return this.loudest.some(t=>t.id===e)}levelChanged(e,t){const n=Date.now(),i=this.getOrCreateSpeaker(e);this.lastLevelChangedTime<n&&(this.lastLevelChangedTime=n,this.maybeStartDecisionMaker());const r=i.levelChanged(t,n);return this.updateLoudestList(i,r,n)}runInDecisionMaker(e){return this.decisionMaker!==e||this.lastDecisionTime>0&&this.lastDecisionTime-this.lastLevelChangedTime>=15e3?-1:this._runInDecisionMaker()}decisionMakerExited(e){this.decisionMaker===e&&(this.decisionMaker=null)}destroy(){this.decisionMaker=null,this.loudest.length=0,this.speakers.clear(),this.removeAllListeners()}addSpeakers(e){e.forEach(t=>{this.speakers.has(t.id)||this.speakers.set(t.id,t)})}removeSpeakers(e){e.forEach(t=>{this.speakers.delete(t.id)})}getOrCreateSpeaker(e){let t=this.speakers.get(e);return t||(t=new RP(e),this.speakers.set(e,t),this.maybeStartDecisionMaker()),t}updateLoudestList(e,t,n){const i=e.id===this.dominantId;if(t<0){let a=0;for(;a<this.loudest.length&&this.loudest[a]!==e;)++a;return new YS(i,a,e.energyScore)}if(e.energyScore=Math.floor((this.energyAlphaPct*t+(100-this.energyAlphaPct)*e.energyScore+50)/100),this.numLoudestToTrack===0)return new YS(i,0,e.energyScore);const r=n-this.energyExpireTimeMs;let o=0;for(;o<this.loudest.length;){const a=this.loudest[o];if(a.getLastLevelChangedTime()<r&&this.loudest.length>=this.numLoudestToTrack)this.loudest.splice(o,1);else if(a.id!==e.id)++o;else if(this.loudest.splice(o,1),this.loudest.length<this.numLoudestToTrack)break}let s=0;for(;s<this.loudest.length&&!(this.loudest[s].energyScore<e.energyScore);)++s;return s<this.numLoudestToTrack&&(this.loudest.splice(s,0,e),this.loudest.length>this.numLoudestToTrack&&this.loudest.splice(this.numLoudestToTrack,1)),new YS(i,s,e.energyScore)}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new class{constructor(e){P(this,"algorithm",void 0),this.algorithm=e}execute(){let e=!this.algorithm;if(!e)try{const t=this.algorithm.runInDecisionMaker(this);t<=0?e=!0:setTimeout(this.execute.bind(this),t)}catch{e=!0}e&&this.algorithm&&this.algorithm.decisionMakerExited(this)}}(this),this.decisionMaker.execute())}makeDecision(e){let t=null,n=null;const i=this.speakers.size;let r=null;if(i===0)r=null;else if(i===1){var o;const s=ti(o=this.speakers).call(o).next().value;this.enableSilence&&s&&(r=s.id,s.evaluateSpeechActivityScores(e),e-s.lastNonSilence>this.timeoutToSilenceInterval&&(r=null))}else{let s=this.dominantId==null?null:this.speakers.get(this.dominantId);if(s==null){const d=this.speakers.entries().next();d.value&&(r=d.value[0],s=d.value[1])}else r=s.id;s==null||s.evaluateSpeechActivityScores(e);const a=this.relativeSpeechActivities;let c=2;for(const d of this.speakers.entries()){const[l,h]=d;if(h===s)continue;h.evaluateSpeechActivityScores(e);for(let m=0;m<a.length;++m){const g=s==null?Ga:s.getSpeechActivityScore(m);a[m]=Math.log(h.getSpeechActivityScore(m)/g)}const u=a[0],p=a[1],E=a[2];u>3&&p>2&&E>0&&p>c&&(c=p,r=l)}this.enableSilence&&s!=null&&r===s.id&&e-s.lastNonSilence>this.timeoutToSilenceInterval&&(r=null)}r==null&&!this.enableSilence||r===this.dominantId||(t=this.dominantId,this.dominantId=r,n=this.dominantId),n==null&&!this.enableSilence||n===t||this.emit
52("ActiveSpeakerChanged",n)}_runInDecisionMaker(){const e=Date.now(),t=300-(e-this.lastLevelIdleTime);let n=0;t<=0?(this.lastLevelIdleTime!==0&&this.timeoutIdleLevels(e),this.lastLevelIdleTime=e):n=t;let i=300-(e-this.lastDecisionTime);return i<=0&&(this.lastDecisionTime=e,this.makeDecision(e),i=300-(Date.now()-e)),i>0&&n>i&&(n=i),n}timeoutIdleLevels(e){const t=[];for(const i of ti(n=this.speakers).call(n)){var n;const r=e-i.getLastLevelChangedTime();36e5<r&&(this.dominantId==null||i.id!==this.dominantId)?t.push(i.id):300<r&&i.levelTimedOut()}t.forEach(i=>this.speakers.delete(i))}};const fd=new Map;let lo=null,qp=null;const vP=3;let ja=[];const uo=new Map,Zp=new Map;let Qp,CX=class{get samples(){return this.actives+this.inactives}get activeRate(){return this.actives/this.samples}constructor(e,t){P(this,"id",void 0),P(this,"track",void 0),P(this,"score",0),P(this,"active",!0),P(this,"muted",!1),P(this,"timer",0),P(this,"actives",0),P(this,"inactives",0),this.id=e,this.track=t,this.setActive(uo.size<3)}autoCheckActive(){this.autoSetActive(),this.autoAdjustActive(),this.resetTimer(),this.actives=0,this.inactives=0}autoSetActive(){const e=this.active;this.active=this.activeRate>=.8;const{actives:t,inactives:n}=function(){const i=[],r=[];return Array.from(ti(uo).call(uo)).forEach(o=>{o.active?i.push(o):r.push(o)}),{actives:i,inactives:r}}();if(t.length>3){let i;t.forEach(r=>{(!i||i.score>r.score)&&(i=r)}),i&&i.setActive(!1)}if(t.length<3&&n.length>0){let i;n.forEach(r=>{(!i||i.score<r.score)&&r.id!==this.id&&(i=r)}),i&&e&&!this.active&&(i.samples>40&&i.activeRate-this.activeRate>.4?i.setActive(!0):this.active=!0)}this.setMuted(!this.active)}setActive(e){this.active=e,this.resetTimer(),this.setMuted(!e)}autoAdjustActive(){this.active?this.autoSwitchToInactive():this.autoSwitchToActive()}autoSwitchToActive(){const e=function(t){let n;return Array.from(ti(uo).call(uo)).forEach(i=>{!i.active||i.id===t||i.samples<40||(!n||i.score<n.score)&&(n=i)}),n}(this.id);e&&this.activeRate-e.activeRate>.4&&(e.setActive(!1),this.setActive(!0))}autoSwitchToInactive(){const e=function(t){let n;return Array.from(ti(uo).call(uo)).forEach(i=>{i.active||i.id===t||i.samples<40||(!n||i.score>n.score)&&(n=i)}),n}(this.id);e&&e.activeRate-this.activeRate>.4&&(e.setActive(!0),this.setActive(!1))}addSample(e){e?this.actives+=1:this.inactives+=1,this.samples>66.66666666666667&&this.autoCheckActive()}setMuted(e){this.track&&(this.track.enabled=!e,this.muted=e)}resetTimer(){this.clearTimer(),this.timer=window.setTimeout(()=>{if(this.samples!==0)return this.samples<50?this.resetTimer():void this.autoCheckActive()},1e3)}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=0)}};function AP(e){const t=uo.get(e);t&&(uo.delete(e),t.clearTimer())}const $p=new Map,yX=new Map,XS="video/h264",JS="video/h265";function CP(e,t,n){let i=new Uint8Array(e,t,n),r=[],o=0;for(;r.length<n;)o+3<n&&i[o]===0&&i[o+1]===0&&i[o+2]===3&&(i[o+3]===0||i[o+3]===1||i[o+3]===2||i[o+3]===3)?(r.push(i[o],i[o+1],i[o+3]),o+=4):(r.push(i[o]),o++);return new Uint8Array(r)}function yP(e){const t=e.length;let n=[],i=0;for(;i<t;)i+2<t&&e[i]===0&&e[i+1]===0&&(e[i+2]===0||e[i+2]===1||e[i+2]===2||e[i+2]===3)?(n.push(e[i],e[i+1],3,e[i+2]),i+=3):(n.push(e[i]),i++);return new Uint8Array(n)}function IP(e){if(e.length<5)return"";let t=-1;for(let r=0;r<e.length-3;r++){if(e[r]===0&&e[r+1]===0&&e[r+2]===1){t=r;break}if(r<e.length-4&&e[r]===0&&e[r+1]===0&&e[r+2]===0&&e[r+3]===1){t=r;break}}if(t===-1)return"";const n=t+(e[t+2]===0?4:3);if(n>=e.length)return"";const i=e[n];return 128&i?"":(i>>1&63)>=32||n+1<e.length&&!(248&e[n+1])?JS:(31&i)<=31?XS:""}const e_=new Map,Ql=new Map;(function(){const e=Fe();mn.getDisplayMedia=!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia),mn.getStreamFromExtension=e.name===je.CHROME&&Number(e.version)>34,mn.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;const t=new RTCPeerConnection;let n=!1;try{t.addTransceiver("audio"),n=!0}catch{}return t.close(),n}(),mn.supportMinBitrate=e.name===je.CHROME||e.name===je.EDGE,mn.supportSetRtpSenderParameters=function(){const t=Fe();return!!(window.RTCRtpSender&&window.RTCRtpSender.prototype.setParameters&&window.RTCRtpSender.prototype.getParameters)&&(!!Po()||!(!vn()&&!Tp())||t.name===je.FIREFOX&&Number(t.version)>=64)}(),e.name===je.SAFARI&&(Number(e.version)>=14?mn.supportDualStream=!0:mn.supportDualStream=!1),mn.webAudioMediaStreamDest=function(){const t=Fe();return!(t.name===je.SAFARI&&Number(t.version)<12)}(),mn.supportReplaceTrack=!!window.RTCRtpSender&&typeof RTCRtpSender.prototype.replaceTrack=="function",mn.supportWebGL=typeof WebGLRenderingContext<"u",mn.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,Po()||(mn.webAudioWithAEC=!0),mn.supportShareAudio=function(){const t=Fe();return(t.os===pn.WIN_10||t.os===pn.WIN_81||t.os===pn.WIN_7||t.os===pn.LINUX||t.os===pn.MAC_OS||t.os===pn.CHROMIUM_OS)&&t.name===je.CHROME&&Number(t.version)>=74}(),mn.supportDataChannel=!!(Ur(76)||vp(68)||cO(14)),mn.supportPCSetConfiguration=function(){const t=window.RTCPeerConnection;return!Rt()&&!!t&&t.prototype.setConfiguration instanceof Function}(),mn.supportWebRTCEncodedTransform=Ur(87)||Jg()||vp(117),mn.supportWebRTCInsertableStream=function(){const t=Fe();return(t.name===je.CHROME||t.name===je.EDGE)&&Number(t.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),mn.supportRequestVideoFrameCallback="requestVideoFrameCallback"in HTMLVideoElement.prototype,mn.supportWebCrypto=typeof window<"u"&&window.crypto!==void 0&&window.crypto.subtle!==void 0,mn.supportSuppressLocalAudioPlayback=lN(),mn.supportRestrictOwnAudio=uN(),yp(()=>{mn.supportDualStreamEncoding=function(){const t=Fe();return!!T("DISABLE_WEBAUDIO")||t.name==="Safari"&&Number(t.version)>=14||!!(t.name==="Chrome"&&/Windows/i.test(t.os||"")&&Number(t.version)>=100&&T("CHROME_DUAL_STREAM_USE_ENCODING"))}(),_.debug("browser ua: ",navigator.userAgent),_.info("browser info: ",e),_.info("browser compatibility: ",mn)})})();const IX=["CHINA","GLOBAL"],bP=[[0,1,2,3,4,5,5],[0,2,2,3,4,5,5],[0,3,3,3,4,5,5],[0,4,4,4,4,5,5],[0,5,5,5,5,5,5]],Wa=[],gd=[];function xs(e,t){return!!t&&Wa.some(n=>n.uid===e&&n.channelName===t)}function zS(){return gd.length>0}
52var bX=I0.forEach,wP=th("forEach")?[].forEach:function(e){return bX(this,e,arguments.length>1?arguments[1]:void 0)};st({target:"Array",proto:!0,forced:[].forEach!=wP},{forEach:wP});var wX=lr("Array").forEach,OX=ns,NX=Wn,DX=Ee,PX=wX,qS=Array.prototype,LX={DOMTokenList:!0,NodeList:!0},kX=function(e){var t=e.forEach;return e===qS||DX(qS,e)&&t===qS.forEach||NX(LX,OX(e))?PX:t},MX=re(kX),UX=Io,OP=oh;st({target:"Object",stat:!0,forced:le(function(){OP(1)})},{keys:function(e){return OP(UX(e))}});var NP=re(cr.Object.keys),VX=re(BA),xX=re(jA),FX=st,DP=cl,BX=fh,GX=Hi,PP=tE,jX=ts,WX=vs,KX=Ih,HX=tn,YX=gh,XX=E0("slice"),JX=HX("species"),ZS=Array,zX=Math.max;FX({target:"Array",proto:!0,forced:!XX},{slice:function(e,t){var n,i,r,o=WX(this),s=jX(o),a=PP(e,s),c=PP(t===void 0?s:t,s);if(DP(o)&&(n=o.constructor,(BX(n)&&(n===ZS||DP(n.prototype))||GX(n)&&(n=n[JX])===null)&&(n=void 0),n===ZS||n===void 0))return YX(o,a,c);for(i=new(n===void 0?ZS:n)(zX(c-a,0)),r=0;a<c;a++,r++)a in o&&KX(i,r,o[a]);return i.length=r,i}});var qX=lr("Array").slice,ZX=Ee,QX=qX,QS=Array.prototype,$X=function(e){var t=e.slice;return e===QS||ZX(QS,e)&&t===QS.slice?QX:t},eJ=re($X);function H(e,t,n,i,r){var o,s,a,c={};return MX(o=NP(i)).call(o,function(d){c[d]=i[d]}),c.enumerable=!!c.enumerable,c.configurable=!!c.configurable,("value"in c||c.initializer)&&(c.writable=!0),c=VX(s=xX(a=eJ(n).call(n)).call(a)).call(s,function(d,l){return l(e,t,d)||d},c),r&&c.initializer!==void 0&&(c.value=c.initializer?c.initializer.call(r):void 0,c.initializer=void 0),c.initializer===void 0&&(h0(e,t,c),c=null),c}let t_=function(e){return e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR",e}({}),$S=function(e){return e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR",e}({}),mr=function(e){return e[e.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e[e.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e[e.INTERNAL_ERROR=8]="INTERNAL_ERROR",e[e.NO_AUTHORIZED=9]="NO_AUTHORIZED",e[e.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e[e.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e[e.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e[e.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e[e.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e[e.USER_OVERLOAD=16]="USER_OVERLOAD",e[e.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e[e.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND",e[e.REQ_DOWNGRADE_FALLBACK=27]="REQ_DOWNGRADE_FALLBACK",e}({}),oi=function(e){return e[e.NO_FLAG_SET=100]="NO_FLAG_SET",e[e.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",e[e.INVALID_FALG_SET=102]="INVALID_FALG_SET",e[e.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",e[e.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",e[e.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",e[e.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",e[e.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",e[e.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",e[e.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",e[e.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",e[e.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",e[e.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",e[e.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV",e}({}),ce
vendor: 3,308 bytes, line 52
52=function(e){return e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.K_VOS_FALLBACK=30]="K_VOS_FALLBACK",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_
52LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY",e}({}),Le=function(e){return e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed",e}({}),ee=function(e){return e.WS_CONNECTED="ws_connected",e.WS_RECONNECTING="ws_reconnecting",e.WS_CLOSED="ws_closed",e.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",e.ON_BINARY_DATA="on_binary_data",e.REQUEST_RECOVER="request_recover",e.REQUEST_JOIN_INFO="request_join_info",e.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE="request_pre_join_response",e.REQUEST_REJOIN_INFO="req_rejoin_info",e.IS_P2P_DISCONNECTED="is_p2p_dis",e.DISCONNECT_P2P="dis_p2p",e.ABORT_P2P_EXECUTION="abort_p2p_execution",e.NEED_RENEW_SESSION="need-sid",e.REPORT_JOIN_GATEWAY="report_join_gateway",e.REQUEST_TIMEOUT="request_timeout",e.REQUEST_SUCCESS="request_success",e.JOIN_RESPONSE="join_response",e.PRE_CONNECT_PC="pre_connect_pc",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_CONNECTING="datachannel_connecting",e.DATACHANNEL_FAILBACK="datachannel_failback",e.P2P_CONNECTION="p2p_connection",e.P2P_REMOTE_CANDIDATE_UPDATE="p2p_remote_candidate_update",e.P2P_SUBSCRIBE="p2p_subscribe",e.P2P_UNSUBSCRIBE="p2p_unsubscribe",e.P2P_EXCHANGE_SDP="p2p_exchange_sdp",e.P2P_ON_ADD_VIDEO_STREAM="p2p_on_add_video_stream",e.P2P_ON_ADD_AUDIO_STREAM="p2p_on_add_audio_stream",e.RECOVER_NOTIFICATION="recover_notification",e.VOS_FALLBACK="vos_fallback",e.VOS_FALLBACK_PROMISE="vos_fallback_promise",e}({}),ie=function(e){return e.PING="ping",e.PING_BACK="ping_back",e.JOIN="join_v3",e.REJOIN="rejoin_v3",e.LEAVE="leave",e.SET_CLIENT_ROLE="set_client_role",e.PUBLISH="publish",e.PUBLISH_DATASTREAM="publish_datastream",e.UNPUBLISH="unpublish",e.UNPUBLISH_DATASTREAM="unpublish_datastream",e.SUBSCRIBE="subscribe",e.PRE_SUBSCRIBE="pre_subscribe",e.SUBSCRIBE_DATASTREAM="subscribe_datastream",e.SUBSCRIBE_STREAMS="subscribe_streams",e.UNSUBSCRIBE="unsubscribe",e.UNSUBSCRIBE_DATASTREAM="unsubscribe_datastream",e.UNSUBSCRIBE_STREAMS="unsubscribe_streams",e.SUBSCRIBE_CHANGE="subscribe_change",e.TRAFFIC_STATS="traffic_stats",e.RENEW_TOKEN="renew_token",e.SET_DUAL_STREAM_MODE="set_dual_stream_mode",e.SWITCH_VIDEO_STREAM="switch_video_stream",e.DEFAULT_VIDEO_STREAM="default_video_stream",e.SET_FALLBACK_OPTION="set_fallback_option",e.CONFIGURE="configure",e.GATEWAY_INFO="gateway_info",e.CONTROL="control",e.SEND_METADATA="send_metadata",e.DATA_STREAM="data_stream",e.PICK_SVC_LAYER="pick_svc_layer",e.RESTART_ICE="restart_ice",e.CONNECT_PC="connect_pc",e.SET_VIDEO_PROFILE="set_video_profile",e.SET_PARAMETER="set_parameter",e.SET_RTM2_FLAG="set_rtm2_flag",e.DOWNGRADE_CODEC="downgrade_codec",e}({}),Ka=function(e){return e.WRTC_STATS="wrtc_stats",e.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",e.DENOISER_STATS="denoiser_stats",e.EXTENSION_USAGE_STATS="extension_usage_stats",e}({}),he=function(e){return e.ON_USER_ONLINE="on_user_online",e.ON_USER_OFFLINE="on_user_offline",e.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",e.ON_PUBLISH_STREAM="on_publish_stream",e.ON_UPLINK_STATS="on_uplink_stats",e.ON_P2P_LOST="on_p2p_lost",e.ON_REMOVE_STREAM="on_remove_stream",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",e.ON_USER_BANNED="on_user_banned",e.ON_USER_LICENSE_BANNED="on_user_license_banned",e.ON_NOTIFICATION="on_notification",e.ON_CRYPT_ERROR="on_crypt_error",e.MUTE_AUDIO="mute_audio",e.MUTE_VIDEO="mute_video",e.UNMUTE_AUDIO="unmute_audio",e.UNMUTE_VIDEO="unmute_video",e.ON_P2P_OK="on_p2p_ok",e.RECEIVE_METADATA="receive_metadata",e.ON_DATA_STREAM="on_data_stream",e.ON_RTP_CAPABILITY_CHANGE="on_rtp_capability_change",e.ON_REMOTE_DATASTREAM_UPDATE="on_remote_datastream_update",e.ON_REMOTE_FULL_DATASTREAM_INFO="on_remote_full_datastream_info",e.ENABLE_LOCAL_VIDEO="enable_local_video",e.DISABLE_LOCAL_VIDEO="disable_local_video",e.ENABLE_LOCAL_AUDIO="enable_local_audio",e.DISABLE_LOCAL_AUDIO="disable_local_audio",e.ON_PUBLISHED_USER_LIST="on_published_user_list",e.ENABLE_MULTI_STREAM="enable_multi_stream",e.ON_USER_LIST="on_user_list",e}({}),si=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({}),Re=function(e){return e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e.ON_FALLBACK="websocket:on_fallback",e}({});function n_(e){if(typeof e!="string"||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw _.error("Invalid Channel Name ".concat(e)),new D(A.INVA
vendor: 15,178 bytes, line 52
52LID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function $l(e){if(t=e,!(typeof t=="number"&&Math.floor(t)===t&&0<=t&&t<=4294967295||EO(e,1,255)))throw new D(A.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var t;typeof e=="string"&&_.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.")}let cs=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({});const tJ={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},eT={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function tT(e,t){On(e.url,"".concat(t,".url"),1,1e3,!1),xt(e.x)||ut(e.x,"".concat(t,".x"),0,1e4),xt(e.y)||ut(e.y,"".concat(t,".y"),0,1e4),xt(e.width)||ut(e.width,"".concat(t,".width"),0,1e4),xt(e.height)||ut(e.height,"".concat(t,".height"),0,1e4),xt(e.zOrder)||ut(e.zOrder,"".concat(t,".zOrder"),0,255),xt(e.alpha)||ut(e.alpha,"".concat(t,".alpha"),0,1,!1)}const nJ={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""};let Fs=function(e){return e.WARNING="@live_uap-warning",e.ERROR="@line_uap-error",e.PUBLISH_STREAM_STATUS="@live_uap-publish-status",e.WORKER_STATUS="@live_uap-worker-status",e.REQUEST_NEW_ADDRESS="@live_uap-request-address",e}({}),nT=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({}),un=function(e){return e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",e[e.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN",e}({});function LP(e){if(!e.channelName)throw new D(A.INVALID_PARAMS,"invalid channelName in info");if(typeof e.uid!="number")throw new D(A.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&On(e.token,"info.token",1,2047),$l(e.uid),n_(e.channelName),!0}let pi=function(e){return e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile",e}({}),ds=function(e){return e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE",e}({}),Ri=function(e){return e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE",e}({}),Sd=function(e){return e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED",e}({}),nt=function(e){return e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low",e}({}),qt=function(e){return e.DISCONNECT="disconnect",e.CONNECTION_STATE_CHANGE="connection-state-change",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGE="stream-type-change",e.IS_P2P_DISCONNECTED="is-p2p-dis",e.DISCONNECT_P2P="dis-p2p",e.REQUEST_NEW_GATEWAY_LIST="req-gate-url",e.NEED_RENEW_SESSION="need-sid",e.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",e.JOIN_RESPONSE="join-response",e.RESET_CONNECTION_EVENTS="reset-connection-events",e.PRE_CONNECT_PC="pre-connect_pc",e.UPDATE_GATEWAY_CONFIG="update-gateway-config",e.VOS_FALLBACK="vos-fallback",e.VOS_FALLBACK_PROMISE="vos-fallback-promise",e.RESET_SIGNAL="reset-signal",e.DATACHANNEL_FAILBACK="datachannel-failback",e}({}),i_=function(e){return e.P2P_DISCONNECTED="P2P_DISCONNECTED",e.A_ROUND_WS_FAILED="A_ROUND_WS_FAILED",e.TIMEOUT="TIMEOUT",e.UNKNOWN_REASON="UNKNOWN_REASON",e}({}),fn=function(e){return e[e.Nothing=0]="Nothing",e[e.Audio=1]="Audio",e[e.LowVideo=2]="LowVideo",e[e.Video=4]="Video",e[e.Data=8]="Data",e[e.DataStream0=256]="DataStream0",e[e.DataStream1=512]="DataStream1",e[e.DataStream2=1024]="DataStream2",e[e.DataStream3=2048]="DataStream3",e[e.DataStream4=4096]="DataStream4",e[e.DataStream5=8192]="DataStream5",e[e.DataStream6=16384]="DataStream6",e[e.DataStream7=32768]="DataStream7",e}({}),Je=function(e){return e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS",e}({});const kP=[Je.AFRICA,Je.ASIA,Je.CHINA,Je.EUROPE,Je.GLOBAL,Je.INDIA,Je.JAPAN,Je.NORTH_AMERICA,Je.OCEANIA,Je.OVERSEA,Je.SOUTH_AMERICA];let Bn=function(e){return e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL",e}({});const r_={CHINA:{},ASIA:{CODE:Bn.ASIA,WEBCS_DOMAIN:["ap-web-1-asia.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-asia.agora.io"],PROXY_CS:["proxy-ap-web-asia.agora.io"],CDS_AP:["cds-ap-web-asia.agora.io","cds-ap-web-asia2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-asia.agora.io","sua-ap-web-asia2.agora.io"],UAP_AP:["uap-ap-web-asia.agora.io","uap-ap-web-asia2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-asia.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-asia.agora.io"],LOG_UPLOAD_SERVER:["logservice-asia.agora.io"],PROXY_SERVER_TYPE3:["southeast-asia.webrtc-cloud-proxy.sd-rtn.com"]},NORTH_AMERICA:{CODE:Bn.NORTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-north-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-north-america.agora.io"],PROXY_CS:["proxy-ap-web-america.agora.io"],CDS_AP:["cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],UAP_AP:["uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-north-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-north-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-north-america.agora.io"],PROXY_SERVER_TYPE3:["east-usa.webrtc-cloud-proxy.sd-rtn.com"]},EUROPE:{CODE:Bn.EUROPE,WEBCS_DOMAIN:["ap-web-1-europe.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-europe.agora.io"],PROXY_CS:["proxy-ap-web-europe.agora.io"],CDS_AP:["cds-ap-web-europe.agora.io","cds-ap-web-europe2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-europe.agora.io","sua-ap-web-europe.agora.io"],UAP_AP:["uap-ap-web-europe.agora.io","uap-ap-web-europe2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-europe.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-europe.agora.io"],LOG_UPLOAD_SERVER:["logservice-europe.agora.io"],PROXY_SERVER_TYPE3:["europe.webrtc-cloud-proxy.sd-rtn.com"]},JAPAN:{CODE:Bn.JAPAN,WEBCS_DOMAIN:["ap-web-1-japan.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-japan.agora.io"],PROXY_CS:["proxy-ap-web-japan.agora.io"],CDS_AP:["cds-ap-web-japan.agora.io","cds-ap-web-japan2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-japan.agora.io","sua-ap-web-japan2.agora.io"],UAP_AP:["uap-ap-web-japan.agora.io","uap-ap-web-japan2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-japan.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-japan.agora.io"],LOG_UPLOAD_SERVER:["logservice-japan.agora.io"],PROXY_SERVER_TYPE3:["japan.webrtc-cloud-proxy.sd-rtn.com"]},INDIA:{CODE:Bn.INDIA,WEBCS_DOMAIN:["ap-web-1-india.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-india.agora.io"],PROXY_CS:["proxy-ap-web-india.agora.io"],CDS_AP:["cds-ap-web-india.agora.io","cds-ap-web-india2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-india.agora.io","sua-ap-web-india2.agora.io"],UAP_AP:["uap-ap-web-india.agora.io","uap-ap-web-india2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-india.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-india.agora.io"],LOG_UPLOAD_SERVER:["logservice-india.agora.io"],PROXY_SERVER_TYPE3:["india.webrtc-cloud-proxy.sd-rtn.com"]},KOREA:{CODE:Bn.KOREA,WEBCS_DOMAIN:["ap-web-1-korea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-korea.agora.io"],PROXY_CS:["proxy-ap-web-korea.agora.io"],CDS_AP:["cds-ap-web-korea.agora.io","cds-ap-web-korea2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-korea.agora.io","sua-ap-web-korea2.agora.io"],UAP_AP:["uap-ap-web-korea.agora.io","uap-ap-web-korea2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-korea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-korea.agora.io"],LOG_UPLOAD_SERVER:["logservice-korea.agora.io"],PROXY_SERVER_TYPE3:["korea.webrtc-cloud-proxy.sd-rtn.com"]},HKMC:{CODE:Bn.HKMC,WEBCS_DOMAIN:["ap-web-1-hkmc.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-hkmc.agora.io"],PROXY_CS:["proxy-ap-web-hkmc.agora.io"],CDS_AP:["cds-ap-web-hkmc.agora.io","cds-ap-web-hkmc2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-hkmc.agora.io","sua-ap-web-hkmc2.agora.io"],UAP_AP:["uap-ap-web-hkmc.agora.io","uap-ap-web-hkmc2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-hkmc.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-hkmc.agora.io"],LOG_UPLOAD_SERVER:["logservice-hkmc.agora.io"],PROXY_SERVER_TYPE3:["hkmc.webrtc-cloud-proxy.sd-rtn.com"]},US:{CODE:Bn.US,WEBCS_DOMAIN:["ap-web-1-us.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-us.agora.io"],PROXY_CS:["proxy-ap-web-us.agora.io"],CDS_AP:["cds-ap-web-us.agora.io","cds-ap-web-us2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-us.agora.io","sua-ap-web-us2.agora.io"],UAP_AP:["uap-ap-web-us.agora.io","uap-ap-web-us2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-us.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-us.agora.io"],LOG_UPLOAD_SERVER:["logservice-us.agora.io"],PROXY_SERVER_TYPE3:["us.webrtc-cloud-proxy.sd-rtn.com"]},OVERSEA:{CODE:Bn.OVERSEA,WEBCS_DOMAIN:["ap-web-1-oversea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oversea.agora.io"],PROXY_CS:["proxy-ap-web-oversea.agora.io"],CDS_AP:["cds-ap-web-oversea.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oversea.agora.io"],UAP_AP:["uap-ap-web-oversea.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oversea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oversea.agora.io"],LOG_UPLOAD_SERVER:["logservice-oversea.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.agora.io"]},GLOBAL:{CODE:Bn.GLOBAL,WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-ap-web-3.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-ap-web-3.agora.io"],UAP_AP:["uap-ap-web-1.agora.io","uap-ap-web-3.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2.agora.io"],LOG_UPLOAD_SERVER:["logservice.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com"]},OCEANIA:{CODE:Bn.OCEANIA,WEBCS_DOMAIN:["ap-web-1-oceania.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oceania.agora.io"],PROXY_CS:["proxy-ap-web-oceania.agora.io"],CDS_AP:["cds-ap-web-oceania.agora.io","cds-ap-web-oceania2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oceania.agora.io","sua-ap-web-oceania2.agora.io"],UAP_AP:["uap-ap-web-oceania.agora.io","uap-ap-web-oceania2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oceania.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oceania.agora.io"],LOG_UPLOAD_SERVER:["logservice-oceania.agora.io"],PROXY_SERVER_TYPE3:["oceania.webrtc-cloud-proxy.sd-rtn.com"]},SOUTH_AMERICA:{CODE:Bn.SOUTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-south-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-south-america.agora.io"],PROXY_CS:["proxy-ap-web-south-america.agora.io"],CDS_AP:["cds-ap-web-south-america.agora.io","cds-ap-web-south-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-south-america.agora.io","sua-ap-web-south-america2.agora.io"],UAP_AP:["uap-ap-web-south-america.agora.io","uap-ap-web-south-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-south-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-south-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-america.agora.io"],PROXY_SERVER_TYPE3:["south-america.webrtc-cloud-proxy.sd-rtn.com"]},AFRICA:{CODE:Bn.AFRICA,WEBCS_DOMAIN:["ap-web-1-africa.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-africa.agora.io"],PROXY_CS:["proxy-ap-web-africa.agora.io"],CDS_AP:["cds-ap-web-africa.agora.io","cds-ap-web-africa2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-africa.agora.io","sua-ap-web-africa2.agora.io"],UAP_AP:["uap-ap-web-africa.agora.io","uap-ap-web-africa2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-africa.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-africa.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-africa.agora.io"],PROXY_SERVER_TYPE3:["africa.webrtc-cloud-proxy.sd-rtn.com"]},EXTENSIONS:{}};
52pS&&(r_.CHINA={CODE:Bn.CHINA,WEBCS_DOMAIN:["webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["proxy-web.ap.sd-rtn.com"],CDS_AP:["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-web-2.ap.sd-rtn.com","uap-web-4.ap.sd-rtn.com"],EVENT_REPORT_DOMAIN:["web-3.statscollector.sd-rtn.com"],EVENT_REPORT_BACKUP_DOMAIN:["web-4.statscollector.sd-rtn.com"],LOG_UPLOAD_SERVER:["logservice-china.agora.io"],PROXY_SERVER_TYPE3:["east-cn.webrtc-cloud-proxy.sd-rtn.com"]});let ho=function(e){return e.UPDATE_BITRATE_LIMIT="update_bitrate_limit",e.UPDATE_CLIENT_ROLE_OPTIONS="update_client_role_options",e.UPDATE_REMOTE_VIDEO_STREAM_TYPE="update_remote_video_stream_type",e.FALLBACK_TO_HLS="fallback_to_hls",e.UPDATE_VOS_CONFIGURE="update_vos_configure",e}({});function MP(e){return!!e&&!(!e.uplink||!e.id)&&e.uplink.max_bitrate!==void 0&&e.uplink.min_bitrate!==void 0}class UP extends Nt{constructor(t,n){super(),S(this,"onICEConnectionStateChange",void 0),S(this,"onConnectionStateChange",void 0),S(this,"onDTLSTransportStateChange",void 0),S(this,"onDTLSTransportError",void 0),S(this,"onICETransportStateChange",void 0),S(this,"onFirstAudioReceived",void 0),S(this,"onFirstVideoReceived",void 0),S(this,"onFirstAudioDecoded",void 0),S(this,"onFirstVideoDecoded",void 0),S(this,"onFirstVideoRender",void 0),S(this,"onFirstVideoBufferReady",void 0),S(this,"onFirstVideoDecodedTimeout",void 0),S(this,"onSelectedLocalCandidateChanged",void 0),S(this,"onSelectedRemoteCandidateChanged",void 0),S(this,"onICECandidateError",void 0),S(this,"getLocalVideoStats",void 0)}}class o_ extends UP{constructor(t,n){super(t,n),S(this,"establishPromise",void 0)}}let $=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),gn=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({}),ls=function(e){return e[e.FIRST_CONNECTION=0]="FIRST_CONNECTION",e[e.UDP_TCP_RESTART=1]="UDP_TCP_RESTART",e[e.RELAY_RESTART=2]="RELAY_RESTART",e[e.TCP_RESTART=3]="TCP_RESTART",e[e.OLD_FIRST_CONNECTION=10]="OLD_FIRST_CONNECTION",e[e.OLD_RESTART=11]="OLD_RESTART",e[e.DISCONNECTED_OR_FAILED=20]="DISCONNECTED_OR_FAILED",e}({});const VP=["disconnected","failed"];let G=function(e){return e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack",e}({}),qe=function(e){return e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected",e}({}),ae=function(e){return e.AudioMetadata="audioMetadata",e.AudioPts="audioPts",e.StateChange="stateChange",e.IceConnectionStateChange="iceConnectionStateChange",e.RequestMuteLocal="requestMuteLocal",e.RequestUnmuteLocal="requestUnmuteLocal",e.RequestRePublish="requestRePublish",e.RequestRePublishDataChannel="requestRePublishDataChannel",e.RequestReSubscribe="requestReSubscribe",e.RequestUploadStats="requestUploadStats",e.RequestUpload="requestUpload",e.MediaReconnectStart="MediaReconnectStart",e.MediaReconnectEnd="MediaReconnectEnd",e.NeedSignalRTT="NeedSignalRTT",e.RequestRestartICE="RequestRestartIce",e.PeerConnectionStateChange="PeerConnectionStateChange",e.RequestReconnect="RequestReconnect",e.RequestReconnectPC="RequestReconnectPC",e.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",e.P2PLost="P2PLost",e.UpdateVideoEncoder="UpdateVideoEncoder",e.ConnectionTypeChange="ConnectionTypeChange",e.RequestLowStreamParameter="RequestLowStreamParameter",e.QueryClientConnectionState="QueryClientConnectionState",e.LocalCandidate="LocalCandidate",e.RequestP2PMuteLocal="requestP2PMuteLocal",e.RequestP2PUnPublish="RequestP2PUnPublish",e.RequestP2PUnmuteRemote="RequestP2PUnmuteRemote",e.RequestP2PMuteRemote="RequestP2PMuteRemote",e.RequestP2PRestartICE="RequestP2PRestartICE",e.FirstVideoPreRender="FirstVideoPreRender",e.FirstVideoBufferReady="FirstVideoBufferReady",e}({}),Hr=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),Yr=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({}),Cn=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}
vendor: 5,111 bytes, line 52
52),Bs=function(e){return e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK",e}({}),hn=function(e){return e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback",e.PRE_CONNECT_PC="transmitter:pre_connect_pc",e}({}),Vo=function(e){return e.CAMERA_CHANGED="camera-changed",e.MICROPHONE_CHANGED="microphone-changed",e.PLAYBACK_DEVICE_CHANGED="playback-device-changed",e.AUDIO_AUTOPLAY_FAILED="audio-autoplay-failed",e.AUTOPLAY_FAILED="autoplay-failed",e.AUDIO_CONTEXT_STATE_CHANGED="audio-context-state-changed",e.SECURITY_POLICY_VIOLATION="security-policy-violation",e}({}),Er=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),po=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),Td=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({}),Zt=function(e){return e.CALL="call",e.CANDIDATE="candidate",e.PUBLISH="publish",e.UNPUBLISH="unpublish",e.CONTROL="control",e.RESTART_ICE="restart_ice",e.ACK="ack",e.RESPONSE="response",e.JOIN="join",e.CHECK="check",e}({}),Rd=function(e){return e.ABORT="abort",e}({}),Gs=function(e){return e.MUTE_LOCAL_AUDIO="mute_local_audio",e.MUTE_LOCAL_VIDEO="mute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video",e}({}),iJ=function(e){return e.P2P_TOKEN_TIMEOUT="p2p_token_timeout",e.P2P_TOKEN_CHANGED="p2p_token_changed",e}({});const rJ={[t_.ACCESS_POINT]:{[oi.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[oi.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[oi.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[oi.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[oi.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[oi.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[oi.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[oi.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[oi.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[oi.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[oi.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[oi.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[oi.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[oi.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[oi.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[oi.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[oi.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[oi.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[t_.UNILBS]:{[mr.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[mr.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[mr.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[mr.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[mr.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[mr.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[mr.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[mr.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[mr.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[mr.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[mr.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[mr.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1},[mr.REQ_DOWNGRADE_FALLBACK]:{desc:"request downgrade fallback",retry:!1}},[t_.STRING_UID_ALLOCATOR]:{[$S.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[$S.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[$S.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function vd(e){const t=rJ[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const n=t[e%1e4];
52if(!n){if(Math.floor(e/1e4)===t_.ACCESS_POINT){const i=e%1e4;if(i.toString()[0]==="1")return{desc:e.toString(),retry:!1};if(i.toString()[0]==="2")return{desc:e.toString(),retry:!0}}return{desc:"unknown error",retry:!1}}return n}const oJ={[ce.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[ce.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[ce.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[ce.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[ce.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[ce.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[ce.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[ce.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[ce.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[ce.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[ce.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[ce.DATASTREAM2_NOT_AVAILABLE]:{desc:"DATASTREAM2_NOT_AVAILABLE",action:"quit"},[ce.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[ce.K_VOS_FALLBACK]:{desc:"K_VOS_FALLBACK",action:"tryNext"},[ce.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[ce.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[ce.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[ce.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[ce.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[ce.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[ce.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[ce.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[ce.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[ce.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[ce.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[ce.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[ce.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[ce.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[ce.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[ce.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[ce.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[ce.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[ce.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[ce.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[ce.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[ce.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[ce.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[ce.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[ce.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[ce.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[ce.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[ce.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[ce.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[ce.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[ce.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[ce.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[ce.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[ce.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[ce.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[ce.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[ce.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[ce.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[ce.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[ce.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[ce.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[ce.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[ce.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[ce.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[ce.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[ce.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[ce.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[ce.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[ce.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[ce.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[ce.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function Ha(e){return oJ[e]||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}function xP(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function iT(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
52t%2?xP(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):xP(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function rT(e,t){if(typeof e=="string")return e;const{proxy:n,host:i,port:r}=e;if(t){const o=T("JOIN_GATEWAY_FALLBACK_PORT")||443;return o===443?"wss://".concat(i,"/ws/?p=").concat(Number(r)+150):"wss://".concat(i,":").concat(o,"/ws/?p=").concat(Number(r)+150)}return n?"wss://".concat(n,"/ws/?h=").concat(i,"&p=").concat(r):"wss://".concat(i,":").concat(r)}const sJ=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,aJ=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,cJ=/wss:\/\/(.+):([0-9]+)\/?/,dJ=/wss:\/\/(.[^\/]+)\/?/;let lJ=0;class uJ{constructor(t,n){S(this,"id",0),S(this,"store",void 0),S(this,"recordIndex",void 0),S(this,"websockets",[]),S(this,"try443PortDuration",2e3),S(this,"forceCloseWSDuration",5e3),S(this,"try443PortTimeout",null),S(this,"forceCloseTimeout",null),S(this,"isTry443PortFailed",!1),S(this,"isNormalPortFailed",!1),S(this,"useDoubleDomain",!1),S(this,"useProxy",!1),S(this,"startTime",Date.now()),this.id=++lJ,this.try443PortDuration=T("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=t||5e3,this.store=n}closeAllWebsockets(){this.websockets.forEach(t=>{t.onopen=null,t.onclose=null,t.onmessage=null,t.close()}),this.websockets.length=0}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout),this.forceCloseTimeout=null,this.try443PortTimeout=null}logger(){var t;const n=Date.now()-this.startTime;for(var i=arguments.length,r=new Array(i),o=0;o<i;o++)r[o]=arguments[o];_.debug("[choose-best-ws ".concat((t=this.store)===null||t===void 0?void 0:t.clientId," ").concat(this.id,"] ").concat(n,"ms:"),...r)}createWebSocket(t,n,i){this.logger("createWebSocket:",t,{isTry443Port:n,hasTimeoutDetection:i});const r=T("GATEWAY_DOMAINS"),o=Date.now(),s=[],a=r.find(u=>{var p;return x(p=t.host).call(p,u)});a||(this.useDoubleDomain=!1);const c=[];if(this.useDoubleDomain)r.forEach(u=>{c.push(rT(iT(iT({},t),{},{host:t.host.replace(a,u)}),n))});else{const u=iT({},t);if(n&&a){const p=r.find(E=>E!==a);p&&(u.host=u.host.replace(a,p))}c.push(rT(u,n))}try{c.forEach(u=>{const p=new WebSocket(u);p.binaryType="arraybuffer",s.push(p),this.logger("ws is connecting:",p.url)})}catch(u){if(this.logger("ws create failed"),s.forEach(p=>p.close()),s.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(t,n,i);if(!n&&Number(t.port)!==443)return this.createWebSocket(t,!0,i);throw new D(A.WS_ERR,"init websocket failed! Error: ".concat(u.toString()))}const d=Bl();this.store&&this.store.recordJoinChannelService({urls:s.map(u=>u.url),service:"gateway"}
52,this.recordIndex),s.forEach(u=>{u.onopen=()=>{this.logger("onopen: ws ".concat(u.url," open cost ").concat(Date.now()-o,"ms")),this.websockets.forEach(p=>{p!==u&&(p.onopen=null,p.onclose=null,p.onmessage=null,p.close(),this.logger("close backup websocket: ".concat(p.url)))}),this.websockets.length=0,d.resolve(u)},u.onclose=p=>{this.logger("onclose: ws ".concat(u.url," closed cost ").concat(Date.now()-o,"ms state: ").concat(u.readyState));const E=s.every(m=>m.readyState===WebSocket.CLOSED||m.readyState===WebSocket.CLOSING);this.logger("".concat(n?"443":"47xx"," websocket closed, all failed: ").concat(E)),E&&(n||this.isTry443PortFailed||this.useProxy)?(this.logger("onclose: all websocket is closed, ".concat(p.reason)),d.reject({code:p.code,reason:i_.A_ROUND_WS_FAILED})):!n&&E&&!this.isNormalPortFailed&&this.try443PortTimeout&&(this.logger("all 47xx websocket is closed, try 443 port"),this.clearTimeout(),h()),n?this.isTry443PortFailed=E:this.isNormalPortFailed=E},u.onmessage=p=>this.logger("".concat(u.url," onmessage: ").concat(p.data))}),this.websockets.push(...s);const l=()=>{this.websockets.forEach(u=>u.readyState!==WebSocket.OPEN&&u.close())},h=()=>{if(d.isResolved)return l();Fe().os===pn.MAC_OS&&Rt()&&l(),this.createWebSocket(t,!0,!0).then(u=>{d.resolve(u)}).catch(u=>{this.isNormalPortFailed&&d.reject(u),this.logger("try 443 port to create ws failed")}),this.forceCloseTimeout=window.setTimeout(()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",d.isResolved),this.forceCloseTimeout=null,l()},this.forceCloseWSDuration)};return i||(()=>{if(n||this.useProxy)return this.logger("add 5s timeout at ".concat(n?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout(()=>{this.forceCloseTimeout=null,l()},this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout(()=>{this.logger("2s timeout, isWebsocket created: ",d.isResolved),this.try443PortTimeout=null,h()},this.try443PortDuration)})(),d.promise}chooseBestWebsocket(t,n,i,r){return this.useDoubleDomain=!!n,typeof t=="string"&&(t=function(o){let s,a,c;return[,s,a,c]=o.match(sJ)||[],s||([,a,c]=o.match(aJ)||[]),a&&c||([,a,c]=o.match(cJ)||[]),a&&c||([,a]=o.match(dJ)||[]),a||_.warning("un-destructible url: ",o),{proxy:s,host:a,port:c||"443"}}(t)),this.recordIndex=r,this.useProxy=!!t.proxy,i&&this.useProxy&&(_.warn("cannot use 443 only when use proxy"),i=!1),this.createWebSocket(t,!!i,!1).finally(()=>this.clearTimeout())}}function FP(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}class BP extends Nt{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}get reconnectMode(){return this._reconnectMode}set reconnectMode(t){var n;x(n=["tryNext","recover"]).call(n,t)&&this.resetReconnectCount(t),this._reconnectMode=t}get state(){return this._state}set state(t){t!==this._state&&(this._state=t,this._state==="reconnecting"?this.emit(Re.RECONNECTING,this.reconnectReason):this._state==="connected"?this.emit(Re.CONNECTED):this._state==="closed"?this.emit(Re.CLOSED):this._state==="failed"&&this.emit(Re.FAILED))}resetReconnectCount(t){_.debug("websocket reset reconnect count, reason: "+t),this.reconnectCount=0}constructor(t,n){let i=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=arguments.length>3&&arguments[3]!==void 0&&arguments[3],o=arguments.length>4&&arguments[4]!==void 0&&arguments[4],s=arguments.length>5?arguments[5]:void 0;super(),S(this,"_websocketUrl",null),S(this,"connectionID",0),S(this,"currentURLIndex",0),S(this,"urls",[]),S(this,"_reconnectMode","tryNext"),S(this,"reconnectReason",void 0),S(this,"_initMutex",void 0),S(this,"name",void 0),S(this,"_state","closed"),S(this,"reconnectInterrupter",void 0),S(this,"websocket",void 0),S(this,"retryConfig",void 0),S(this,"reconnectCount",0),S(this,"forceCloseTimeout",5e3),S(this,"onlineReconnectListener",void 0),S(this,"useCompress",void 0),S(this,"tryDoubleDomain",!1),S(this,"use443PortOnly",!1),S(this,"wsInflateLength",0),S(this,"wsDeflateLength",0),S(this,"closeEstablishingWs",()=>{}),S(this,"store",void 0),S(this,"joinGatewayRecordIndex",void 0),this.store=s,this.name=t,this.retryConfig=function(h){for(var u=1;u<arguments.length;u++){var p=arguments[u]!=null?arguments[u]:{};
52u%2?FP(Object(p),!0).forEach(function(E){S(h,E,p[E])}):Object.getOwnPropertyDescriptors?Object.defineProperties(h,Object.getOwnPropertyDescriptors(p)):FP(Object(p)).forEach(function(E){Object.defineProperty(h,E,Object.getOwnPropertyDescriptor(p,E))})}return h}({},n),this.useCompress=i,this.tryDoubleDomain=r,this.use443PortOnly=o,this._initMutex=new An("websocket",s?s.clientId:void 0);const{timeout:a,timeoutFactor:c}=n,d=Math.max(300,Math.floor(3*a/5)),l=Math.max(1.2,Math.floor(8*c)/10);Jn.ONLINE&&(this.retryConfig.timeout=d,this.retryConfig.timeoutFactor=l),At.on(Oa.NETWORK_STATE_CHANGE,(h,u)=>{h!==u&&(this.resetReconnectCount("network state change: ".concat(u," -> ").concat(h)),h===Jn.ONLINE?(this.retryConfig.timeout=d,this.retryConfig.timeoutFactor=l):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=c))})}getConnection(){return this.websocket||void 0}async init(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;const i=await this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=n,this.urls=t,this.state="connecting";try{var r;const o=Bl(),s=this.urls[this.currentURLIndex];(r=this.store)===null||r===void 0||r.beforeConnect(),(function(a){return!(Vp()||T("USE_NEW_TOKEN")||!T("ENABLE_PREALLOC_PC")&&(a==null||!a.autoSubscribe||T("FORCE_DISABLE_AUTO_SUB")))}(this.store)||T("ENABLE_JOIN_V4"))&&this.emit(hn.PRE_CONNECT_PC),this.createWebSocketConnection(s).then(o.resolve).catch(o.reject),this.once(Re.CLOSED,()=>{o.reject(new L(A.WS_DISCONNECT))}),this.once(Re.CONNECTED,o.resolve),await o.promise}catch{}finally{i()}}close(t,n){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const i=this.websocket;n?setTimeout(()=>i.close(),500):i.close(),this.websocket=void 0,this._websocketUrl=null}this.state=t?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(t,n){if(!this.websocket)return void _.warning("[".concat(this.name,"] can not reconnect, no websocket"));t!==void 0&&(this.reconnectMode=t),_.debug("[".concat(this.name,"] reconnect is triggered initiative")),typeof this.joinGatewayRecordIndex=="number"&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(n)]},this.joinGatewayRecordIndex);const i=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),i&&i.bind(this.websocket)({code:9999,reason:n})}sendMessage(t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new L(A.WS_ABORT,"websocket is not ready");try{n||(t=JSON.stringify(t)),this.websocket.send(t)}catch(i){throw new L(A.WS_ERR,"send websocket message error"+i.toString())}}setWsInflateData(t){this.wsDeflateLength=this.wsDeflateLength+t.originLength,this.wsInflateLength=this.wsInflateLength+t.compressedLength}getWsInflateData(){const t=this.wsInflateLength,n=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:t,wsDeflateLength:n}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(t){var n;const i=Bl();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const r=l=>{var h;(h=this.store)===null||h===void 0||h.signalChannelOpen(),_.debug("[".concat(this.name,"] websocket opened:"),l),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),i.resolve()},o=async l=>{var h;if(_.debug("[".concat(this.name,"] websocket close ").concat((h=this.websocket)===null||h===void 0?void 0:h.url,", code: ").concat(l.code,", reason: ").concat(l.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)i.reject(new L(A.WS_DISCONNECT,"websocket close: ".concat(l.code))),this.close();else{this.state==="connected"&&(this.reconnectReason=l.reason,this.state="reconnecting");const u=Ui(this,Re.WILL_RECONNECT,this.reconnectMode,l.reason)||this.reconnectMode,p=await this.reconnectWithAction(u);if(this.state==="closed")return void _.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!p)return i.reject(new L(A.WS_DISCONNECT,"websocket reconnect failed: ".concat(l.code))),this.close(!0);i.resolve()}},s=l=>
52{this.emit(Re.ON_MESSAGE,l)},a=l=>{_.warn("[".concat(this.connectionID,"] ws open error ").concat(l))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),T("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(t=T("GATEWAY_WSS_ADDRESS")),_.debug("[".concat(this.name,"] start connect, url:"),t);const c=(n=this.store)===null||n===void 0?void 0:n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var d;this._websocketUrl=rT(t);const l=await this.chooseBestWebsocketConnection(t);this.websocket=l,r&&r(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=s,this.websocket.onerror=a,(d=this.store)===null||d===void 0||d.recordJoinChannelService({endTs:Date.now(),status:"success"},c),this.joinGatewayRecordIndex=c}catch(l){const h=this.state==="closed",u=l instanceof L,p=u&&l.code===A.WS_ABORT,E=u&&l.code===A.WS_ERR,m=u?l.message:l&&(l.reason||l.toString());_.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(m)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:p?"aborted":"error",errors:[l]},c),h||E?(i.reject(h?new L(A.WS_DISCONNECT,"websocket is closed: ".concat(m)):new L(A.WS_ERR,"init websocket failed: ".concat(m))),E&&_.error("[".concat(this.name,"] init websocket failed: ").concat(m))):o&&o(l)}return i.promise}async reconnectWithAction(t){let n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount||this.urls.length===0||this.state==="closed")return!1;_.warning("[choose-best-ws] action: =>",t),this.onlineReconnectListener||At.isOnline||!At.onlineWaiter||(this.onlineReconnectListener=At.onlineWaiter.then(()=>{this.onlineReconnectListener=void 0}));let i=!0;if(this.reconnectInterrupter=()=>i=!1,n){const s=Ip(this.reconnectCount,this.retryConfig);_.debug("[".concat(this.name,"] wait ").concat(s,"ms to reconnect websocket, mode: ").concat(t)),await K.race([ln(s),this.onlineReconnectListener||new K(()=>{})])}if(this._state==="closed"||!i)return!1;this.reconnectCount+=1;const r=async(s,a)=>{this.emit(Re.RECONNECT_CREATE_CONNECTION,a),await this.createWebSocketConnection(s)};try{if(t==="retry")await r(this.urls[this.currentURLIndex],t);else if(t==="tryNext"){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);_.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await r(this.urls[this.currentURLIndex],t)}else t==="recover"&&(_.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await Jt(this,Re.REQUEST_NEW_URLS),this.currentURLIndex=0,await r(this.urls[this.currentURLIndex],t))}catch(s){var o;_.error("[".concat(this.name,"] reconnect failed ").concat(s&&s.toString()));const a=s==null||(o=s.data)===null||o===void 0?void 0:o.desc;if(Array.isArray(a)){if(x(a).call(a,"dynamic key expired"))return this.emit(Re.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1;if(x(a).call(a,"request downgrade fallback"))return this.emit(Re.ON_FALLBACK),!1}return this.reconnectWithAction(t,n)}return!0}}class oT extends BP{constructor(t,n){super(t,n,arguments.length>2&&arguments[2]!==void 0&&arguments[2],arguments.length>3&&arguments[3]!==void 0&&arguments[3],arguments.length>4&&arguments[4]!==void 0&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(t,n){const i=Bl(),r=function(s,a){return new uJ(s,a)}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{_.debug("[choose-best-ws] close establishing websockets"),r.closeAllWebsockets(),i.reject(new L(A.WS_ABORT,"choose best websocket aborted"))};const o=T("GATEWAY_DOMAINS");return _.debug("[choose-best-ws] currentDomain: ",t,", domains: ",o,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),r.chooseBestWebsocket(t,this.tryDoubleDomain,this.use443PortOnly,n).then(i.resolve).catch(i.reject),i.promise.finally(()=>{this.closeEstablishingWs=void 0})}}class eu extends BP{constructor(t,n){super(t,n,arguments.length>2&&arguments[2]!==void 0&&arguments[2],arguments.length>3&&arguments[3]!==void 0&&arguments[3],arguments.length>4&&arguments[4]!==void 0&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(t,n){return new K((i,r)=>{let o=!1;const s=[];this.closeEstablishingWs=()=>{_.debug("[choose-best-ws] close establishing websockets"),s.forEac
52h(E=>{E.onclose=null,E.onopen=null,E.onmessage=null,E.close()}),r(new L(A.WS_ABORT,"choose best websocket aborted"))};const a=T("GATEWAY_DOMAINS");let c;const d=t.indexOf("?h="),l=a.find(E=>d!==-1?x(t).call(t,E,d):x(t).call(t,E));_.debug("[choose-best-ws] currentDomain: ",l,", domains: ",a);let h=!this.tryDoubleDomain||!l;if(!h&&l){var u;const E=Date.now();try{a.forEach(m=>{const g=d===-1?t.replace(l,m):t.substr(0,d)+t.substr(d).replace(l,m),R=new WebSocket(g);R.binaryType="arraybuffer",s.push(R),_.debug("[choose-best-ws] ws is connecting:",R.url)})}catch{for(_.debug("[choose-best-ws] ws create failed, fallback to single url"),s.forEach(m=>m.close());s.length;)s.pop();h=!0}(u=this.store)===null||u===void 0||u.recordJoinChannelService({urls:s.map(m=>m.url),service:"gateway"},n),s.forEach(m=>{m.onopen=()=>{if(o)return;const g=Date.now()-E;_.debug("[choose-best-ws] ws open cost ".concat(g,"ms")),s.filter(R=>R!==m).forEach(R=>{_.debug("[choose-best-ws]close backup websocket: ".concat(R.url)),R.close()}),o=!0,i(m)},m.onclose=g=>{c=g,!o&&(s.find(R=>!(R.readyState===WebSocket.CLOSED||R.readyState===WebSocket.CLOSING))||(_.debug("[choose-best-ws] all websocket is closed"),o=!0,r(c)))},m.onmessage=g=>{_.debug("[choose-best-ws]".concat(m.url," onmessage: ").concat(g.data))}}),ln(this.forceCloseTimeout).then(()=>{s.forEach(m=>{m.readyState!==WebSocket.OPEN&&m.close()})})}if(h){var p;let E;_.debug("[choose-best-ws] use single url: ",t),(p=this.store)===null||p===void 0||p.recordJoinChannelService({urls:[t],service:"gateway"},n);try{E=new WebSocket(t),s.push(E),E.binaryType="arraybuffer"}catch(m){const g=new L(A.WS_ERR,"init websocket failed! Error: ".concat(m.toString()));return _.error("[".concat(this.name,"]").concat(g)),void r(g)}E.onopen=()=>{i(E)},E.onclose=m=>{r(m)},E.onmessage=m=>{_.debug("[choose-best-ws]".concat(E.url," onmessage: ").concat(m.data))},ln(this.forceCloseTimeout).then(()=>{E&&E.readyState!==WebSocket.OPEN&&E.close()})}}).then(i=>(this.closeEstablishingWs=void 0,i)).catch(i=>{throw this.closeEstablishingWs=void 0,i})}}class GP extends Nt{get connectionState(){return this._connectionState}set connectionState(t){t!==this._connectionState&&(this._connectionState=t,t===Le.CONNECTED?this.emit(ee.WS_CONNECTED):t===Le.RECONNECTING?this.emit(ee.WS_RECONNECTING,this._websocketReconnectReason):t===Le.CLOSED&&this.emit(ee.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(t,n){super(),S(this,"__name__","AgoraRTCSignal"),S(this,"_disconnectedReason",void 0),S(this,"_websocketReconnectReason",void 0),S(this,"_connectionState",Le.CLOSED),S(this,"reconnectToken",void 0),S(this,"websocket",void 0),S(this,"openConnectionTime",void 0),S(this,"clientId",void 0),S(this,"lastMsgTime",Date.now()),S(this,"uploadCache",[]),S(this,"uploadCacheInterval",void 0),S(this,"rttRolling",new aS(5)),S(this,"pingpongTimer",void 0),S(this,"wsInflateDataTimer",void 0),S(this,"pingpongTimeoutCount",0),S(this,"ortc",void 0),S(this,"joinResponse",void 0),S(this,"multiIpOption",void 0),S(this,"initError",void 0),S(this,"spec",void 0),S(this,"store",void 0),S(this,"onWebsocketMessage",i=>{if(i.data instanceof ArrayBuffer)return void this.emit(ee.ON_BINARY_DATA,i.data);const r=JSON.parse(i.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(r,"_id")){const o="res-@".concat(r._id);this.emit(o,r._result,r._message)}else if(Object.prototype.hasOwnProperty.call(r,"_type")){if(this.emit(r._type,r._message),r._type===he.ON_NOTIFICATION&&this.handleNotification(r._message),r._type===he.ON_USER_BANNED)switch(r._message.error_code){case 14:this.close(Pe.UID_BANNED);break;case 15:this.close(Pe.IP_BANNED);break;case 16:this.close(Pe.CHANNEL_BANNED)}if(r._type===he.ON_USER_LICENSE_BANNED)switch(r._message.error_code){case ce.ERR_LICENSE_MISSING:this.close(Pe.LICENSE_MISSING);break;case ce.ERR_LICENSE_EXPIRED:this.close(Pe.LICENSE_EXPIRED);break;case ce.ERR_LICENSE_MINUTES_EXCEEDED:this.close(Pe.LICENSE_MINUTES_EXCEEDED);break;case ce.ERR_LICENSE_PERIOD_INVALID:this.close(Pe.LICENSE_PERIOD_INVALID);break;case ce.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(Pe.LICENSE_MULTIPLE_SDK_SERVICE);break;case ce.ERR_LICENSE_ILLEGAL:this.close(Pe.LICENSE_ILLEGAL);break;default:this.close()}}}),this.clientId=t.clientId,this.spec=t,this.store=n,this.websocket=new oT("gateway-".concat(this.clientId),this.spec.retryConfig,!0,T("JOIN_GATEWAY_USE_DUAL_DOMAIN"),T("JOIN_GATEWAY_USE_443PORT_ONLY"),n),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===Le.CONNECTED&&this.reconnect("retry",Vn.OFFLINE)})}async request(t,n,i,r){const o=Qe(6,""),s={_id:o,_type:t,_message:n},a=this.websocket.connectionID,c=()=>new K((E,m)=>{if(this.connectionState===Le.CONNECTED)return E();const g=()=>{this.off(ee.WS_CLOSED,R),E()},R=()=>{this.off(ee.WS_CONNECTED,g),m(new D(A.WS_ABORT))};this.once(ee.WS_CONNECTED,g),this.once(ee.WS_CLOSED,R),t!==ie.PUBLISH&&t!==ie.PUBLISH_DATASTREAM&&t!==ie.SUBSCRIBE&&t!==ie.SUBSCRIBE_DATASTREAM&&t!==ie.UNSUBSCRIBE&&t!==ie.UNSUBSCRIBE_DATASTREAM&&t!==ie.UNPUBLISH&&t!==ie.UNPUBLISH_DATASTREAM&&t!==ie.CONTROL&&t!==ie.RESTART_ICE||this.once(ee.DISCONNECT_P2P,()=>{m(new D(A.DISCONNECT_P2P))}),t!==ie.PUBLISH&&t!==ie.RESTART_ICE||this.once(ee.ABORT_P2P_EXECUTION,()=>{m(new D(A.DISCONNECT_P2P))})});if(this.connectionState!==Le.CONNECTING&&this.connectionState!==Le.RECONNECTING||t===ie.JOIN||t===ie.REJOIN||await c(),this.websocket.sendMessage(s,!0),r)return;const d=new K((E,m)=>{let g=!1;const R=(C,w)=>{g=!0,E({isSuccess:C==="success",message:w||{}}),this.off(ee.WS_CLOSED,v),this.off(ee.WS_RECONNECTING,v),this.emit
52(ee.REQUEST_SUCCESS,t,n)};this.once("res-@".concat(o),R);const v=()=>{m(new D(A.WS_ABORT,"type: ".concat(t))),this.off(ee.WS_CLOSED,v),this.off(ee.WS_RECONNECTING,v),this.off("res-@".concat(o),R)};this.once(ee.WS_CLOSED,v),this.once(ee.WS_RECONNECTING,v),ln(T("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==a||g||(_.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(t)),this.emit(ee.REQUEST_TIMEOUT,t,n))})});let l=null;try{l=await d}catch(E){if(this.connectionState===Le.CLOSED||t===ie.LEAVE)throw new D(A.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?E.throw():t===ie.JOIN||t===ie.REJOIN?null:(await c(),await this.request(t,n))}if(l.isSuccess)return l.message;const h=Number(l.message.error_code||l.message.code),u=Ha(h),p=new D(A.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(l.message.error_str),{code:h,data:l.message,desc:u.desc});return u.action==="success"?l.message:(_.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(t,", error_code: ").concat(h,", message: ").concat(u.desc,", action: ").concat(u.action)),h===ce.ERR_TOO_MANY_BROADCASTERS?((t===ie.JOIN||t===ie.REJOIN)&&(this.initError=p,this.close()),p.throw()):u.action==="failed"?p.throw():u.action==="quit"?(this.initError=p,this.close(),p.throw()):(h===ce.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=l.message.option,_.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Vn.MULTI_IP)):this.reconnect(u.action,Vn.SERVER_ERROR),t===ie.JOIN||t===ie.REJOIN?null:await this.request(t,n)))}waitMessage(t,n){return new K(i=>{const r=o=>{(!n||n(o))&&(this.off(t,r),i(o))};this.on(t,r)})}uploadWRTCStats(t){if(!this.store.sessionId)return void _.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const n={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:t};this.upload(Ka.WRTC_STATS,n)}upload(t,n){const i={_type:t,_message:n};try{this.websocket.sendMessage(i)}catch{const r=T("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>r&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==Le.CONNECTED)return;const o=this.uploadCache.splice(0,1)[0];this.uploadCache.length===0&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(o._type,o._message)},T("UPLOAD_CACHE_INTERVAL")||2e3))}}send(t,n){const i={_type:t,_message:n};this.websocket.sendMessage(i)}init(t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new K((n,i)=>{this.once(ee.WS_CONNECTED,()=>n(this.joinResponse)),this.once(ee.WS_CLOSED,r=>i(this.initError||new D(A.WS_ABORT,r))),this.connectionState=Le.CONNECTING,this.websocket.init(t).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval(()=>{this.handleWsInflateData()},2e4)})}close(t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=t||Pe.LEAVE,this.connectionState=Le.CLOSED,_.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close()}async join(){if(!this.joinResponse){this.emit(ee.ABORT_P2P_EXECUTION),this.store.signalConnected();const t=await Jt(this,ee.REQUEST_JOIN_INFO);this.store.joinReq();let n=await Jt(this,ee.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE);if(n){_.debug("join response from pre join response");const i=await this.request(ie.JOIN,t);i&&"ortc"in i&&(n=i)}else _.debug("join response from request join_v3"),n=await this.request(ie.JOIN,t);if(this.ortc=t==null?void 0:t.ortc,this.store.joinRep(),!n)return this.emit(ee.REPORT_JOIN_GATEWAY,i_.TIMEOUT,this.url||""),!1;
52this.joinResponse=n,this.emit(ee.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Le.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new D(A.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const t=Na(this,ee.REQUEST_REJOIN_INFO);t.token=this.reconnectToken;const n=await this.request(ie.REJOIN,t);return!!n&&(this.connectionState=Le.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),n.peers&&n.peers.forEach(i=>{this.emit(he.ON_USER_ONLINE,{uid:i.uid}),i.audio&&this.emit(he.ON_ADD_AUDIO_STREAM,{uid:i.uid,uint_id:i.uint_id,audio:!0,ssrcId:i.audio_ssrc}),i.video&&this.emit(he.ON_ADD_VIDEO_STREAM,{uid:i.uid,uint_id:i.uint_id,video:!0,ssrcId:i.video_ssrc}),i.audio_mute?this.emit(he.MUTE_AUDIO,{uid:i.uid}):this.emit(he.UNMUTE_AUDIO,{uid:i.uid}),i.video_mute?this.emit(he.MUTE_VIDEO,{uid:i.uid}):this.emit(he.UNMUTE_VIDEO,{uid:i.uid}),i.audio_enable_local?this.emit(he.ENABLE_LOCAL_AUDIO,{uid:i.uid}):this.emit(he.DISABLE_LOCAL_AUDIO,{uid:i.uid}),i.video_enable_local?this.emit(he.ENABLE_LOCAL_VIDEO,{uid:i.uid}):this.emit(he.DISABLE_LOCAL_VIDEO,{uid:i.uid}),i.audio||i.video||this.emit(he.ON_REMOVE_STREAM,{uid:i.uid,uint_id:i.uint_id})}),!0)}reconnect(t,n){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(t,n)}async downgradeCodec(t){if(!this.ortc)return!1;const n={downgrade_codec:t,ortc:this.ortc};return!!await this.request(ie.DOWNGRADE_CODEC,n)}handleNotification(t){_.debug("[".concat(this.clientId,"] receive notification: "),t);const n=Ha(t.code);if(t.code===28&&"detail"in t&&(_.info("[".concat(this.clientId,"] receive recover notification: "),t.detail),this.emit(ee.RECOVER_NOTIFICATION,t.detail)),n.action!=="success"){if(n.action!=="failed")return n.action==="quit"?t.code===ce.ERR_REPEAT_JOIN_CHANNEL&&T("IGNORE_UID_CHECK")?void this.close(Pe.UID_CONFLICT):(n.desc==="ERR_REPEAT_JOIN_CHANNEL"&&this.close(Pe.UID_BANNED),void this.close()):t.code===ce.K_VOS_FALLBACK&&"detail"in t?(_.info("[".concat(this.clientId,"] receive vos fallback notification: "),t.detail),t.detail==="FALLBACKCN"&&T("ENABLE_QUALITY_FALLBACK")?void Jt(this,ee.VOS_FALLBACK_PROMISE,t.detail).then(()=>{this.reconnect("recover",n.desc)}).catch(i=>{_.debug("[".concat(this.clientId,"] cancel vos fallback cn, error: "),i)}):t.detail==="fallback_hls"&&T("ENABLE_FALLBACK_TO_HLS")?(this.emit(ee.VOS_FALLBACK,t.detail),void this.close(Pe.FALLBACK_TO_HLS)):this.reconnect(n.action,n.desc)):void this.reconnect(n.action,Vn.SERVER_ERROR);_.error("[".concat(this.clientId,"] ignore error: "),n.desc)}}handlePingPong(){if(!this.websocket||this.websocket.state!=="connected")return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const t=T("PING_PONG_TIME_OUT"),n=Date.now();this.pingpongTimeoutCount>=t&&(_.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(n-this.lastMsgTime,"ms")),n-this.lastMsgTime>T("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",Vn.TIMEOUT):this.request(ie.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const i=Date.now()-n;this.rttRolling.add(i),T("REPORT_STATS")&&this.send(ie.PING_BACK,{pingpongElapse:i})}).catch(i=>{})}handleWsInflateData(){const{wsInflateLength:t,wsDeflateLength:n}=this.websocket.getWsInflateData();t!==0&&n!==0&&this.upload(Ka.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:n,ws_inflate_length:t})}handleWebsocketEvents(){this.websocket.on(Re.RECONNECT_CREATE_CONNECTION,t=>{this.emit(ee.WS_RECONNECT_CREATE_CONNECTION,t)}),this.websocket.on(Re.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(Re.CLOSED,()=>{this.connectionState=Le.CLOSED}),this.websocket.on(Re.FAILED,()=>{this._disconnectedReason=Pe.NETWORK_ERROR,this.connectionState=Le.CLOSED}),this.websocket.on(Re.RECONNECTING,t=>{this._websocketReconnectReason=t,this.joinResponse=void 0,this.connectionState===Le.CONNECTED?this.connectionState=Le.RECONNECTING:this.connectionState=Le.CONNECTING}),this.websocket.on(Re.WILL_RECONNECT,(t,n,i)=>{const r=Na(this,ee.IS_P2P_DISCONNECTED),o=r||t!=="retry";r&&t==="retry"&&(_.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),t="tryNext",n=i_.P2P_DISCONNECTED),o&&(_.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(t)),this.emit
52(ee.REPORT_JOIN_GATEWAY,n||i_.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(ee.DISCONNECT_P2P)),i(t)}),this.websocket.on(Re.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(t=>{_.warning("[".concat(this.clientId,"] rejoin failed ").concat(t)),this.reconnect("tryNext",Vn.SERVER_ERROR)}):this.join().catch(t=>{if(this.emit(ee.REPORT_JOIN_GATEWAY,t,this.url||""),t instanceof D){if(t.code===A.UNEXPECTED_RESPONSE&&t.data.code===ce.ERR_NO_AUTHORIZED)return this.initError=new D(A.TOKEN_EXPIRE,"dynamic key expired"),void this.close(Pe.TOKEN_EXPIRE);_.error("[".concat(this.clientId,"] join gateway request failed"),t.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Vn.SERVER_ERROR):(this.initError=t,this.close())}})}),this.websocket.on(Re.REQUEST_NEW_URLS,(t,n)=>{Jt(this,ee.REQUEST_RECOVER,this.multiIpOption).then(t).catch(n)}),this.websocket.on(Re.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(he.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}),this.websocket.on(hn.PRE_CONNECT_PC,()=>{this.emit(ee.PRE_CONNECT_PC)}),this.websocket.on(Re.ON_FALLBACK,()=>{T("ENABLE_FALLBACK_TO_HLS")&&this.emit(ee.VOS_FALLBACK,"fallback_hls")})}}var hJ=Ee,pJ=eg,jP=RegExp.prototype,_J=function(e){return e===jP||hJ(jP,e)?pJ(e):e.flags},qn=re(_J);function Ad(e){let t=e.length;for(;--t>=0;)e[t]=0}const sT=256,WP=286,tu=30,nu=15,aT=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),s_=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),mJ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),KP=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),us=new Array(576);Ad(us);const iu=new Array(60);Ad(iu);const ru=new Array(512);Ad(ru);const ou=new Array(256);Ad(ou);const cT=new Array(29);Ad(cT);const a_=new Array(tu);function dT(e,t,n,i,r){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=i,this.max_length=r,this.has_stree=e&&e.length}let HP,YP,XP;function lT(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}Ad(a_);const JP=e=>e<256?ru[e]:ru[256+(e>>>7)],su=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},rr=(e,t,n)=>{e.bi_valid>16-n?(e.bi_buf|=t<<e.bi_valid&65535,su(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=n-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=n)},xo=(e,t,n)=>{rr(e,n[2*t],n[2*t+1])},zP=(e,t)=>{let n=0;do n|=1&e,e>>>=1,n<<=1;while(--t>0);return n>>>1},qP=(e,t,n)=>{const i=new Array(16);let r,o,s=0;for(r=1;r<=nu;r++)s=s+n[r-1]<<1,i[r]=s;for(o=0;o<=t;o++){let a=e[2*o+1];a!==0&&(e[2*o]=zP(i[a]++,a))}},ZP=e=>{let t;for(t=0;t<WP;t++)e.dyn_ltree[2*t]=0;for(t=0;t<tu;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},QP=e=>{e.bi_valid>8?su(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},$P=(e,t,n,i)=>{const r=2*t,o=2*n;return e[r]<e[o]||e[r]===e[o]&&i[t]<=i[n]},uT=(e,t,n)=>{const i=e.heap[n];let r=n<<1;for(;r<=e.heap_len&&(r<e.heap_len&&$P(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!$P(t,i,e.heap[r],e.depth));)e.heap[n]=e.heap[r],n=r,r<<=1;e.heap[n]=i},eL=(e,t,n)=>{let i,r,o,s,a=0;
52if(e.sym_next!==0)do i=255&e.pending_buf[e.sym_buf+a++],i+=(255&e.pending_buf[e.sym_buf+a++])<<8,r=e.pending_buf[e.sym_buf+a++],i===0?xo(e,r,t):(o=ou[r],xo(e,o+sT+1,t),s=aT[o],s!==0&&(r-=cT[o],rr(e,r,s)),i--,o=JP(i),xo(e,o,n),s=s_[o],s!==0&&(i-=a_[o],rr(e,i,s)));while(a<e.sym_next);xo(e,256,t)},hT=(e,t)=>{const n=t.dyn_tree,i=t.stat_desc.static_tree,r=t.stat_desc.has_stree,o=t.stat_desc.elems;let s,a,c,d=-1;for(e.heap_len=0,e.heap_max=573,s=0;s<o;s++)n[2*s]!==0?(e.heap[++e.heap_len]=d=s,e.depth[s]=0):n[2*s+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=d<2?++d:0,n[2*c]=1,e.depth[c]=0,e.opt_len--,r&&(e.static_len-=i[2*c+1]);for(t.max_code=d,s=e.heap_len>>1;s>=1;s--)uT(e,n,s);c=o;do s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],uT(e,n,1),a=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=a,n[2*c]=n[2*s]+n[2*a],e.depth[c]=(e.depth[s]>=e.depth[a]?e.depth[s]:e.depth[a])+1,n[2*s+1]=n[2*a+1]=c,e.heap[1]=c++,uT(e,n,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((l,h)=>{const u=h.dyn_tree,p=h.max_code,E=h.stat_desc.static_tree,m=h.stat_desc.has_stree,g=h.stat_desc.extra_bits,R=h.stat_desc.extra_base,v=h.stat_desc.max_length;let C,w,b,y,N,k,U=0;for(y=0;y<=nu;y++)l.bl_count[y]=0;for(u[2*l.heap[l.heap_max]+1]=0,C=l.heap_max+1;C<573;C++)w=l.heap[C],y=u[2*u[2*w+1]+1]+1,y>v&&(y=v,U++),u[2*w+1]=y,w>p||(l.bl_count[y]++,N=0,w>=R&&(N=g[w-R]),k=u[2*w],l.opt_len+=k*(y+N),m&&(l.static_len+=k*(E[2*w+1]+N)));if(U!==0){do{for(y=v-1;l.bl_count[y]===0;)y--;l.bl_count[y]--,l.bl_count[y+1]+=2,l.bl_count[v]--,U-=2}while(U>0);for(y=v;y!==0;y--)for(w=l.bl_count[y];w!==0;)b=l.heap[--C],b>p||(u[2*b+1]!==y&&(l.opt_len+=(y-u[2*b+1])*u[2*b],u[2*b+1]=y),w--)}})(e,t),qP(n,d,e.bl_count)},tL=(e,t,n)=>{let i,r,o=-1,s=t[1],a=0,c=7,d=4;for(s===0&&(c=138,d=3),t[2*(n+1)+1]=65535,i=0;i<=n;i++)r=s,s=t[2*(i+1)+1],++a<c&&r===s||(a<d?e.bl_tree[2*r]+=a:r!==0?(r!==o&&e.bl_tree[2*r]++,e.bl_tree[32]++):a<=10?e.bl_tree[34]++:e.bl_tree[36]++,a=0,o=r,s===0?(c=138,d=3):r===s?(c=6,d=3):(c=7,d=4))},nL=(e,t,n)=>{let i,r,o=-1,s=t[1],a=0,c=7,d=4;for(s===0&&(c=138,d=3),i=0;i<=n;i++)if(r=s,s=t[2*(i+1)+1],!(++a<c&&r===s)){if(a<d)do xo(e,r,e.bl_tree);while(--a!=0);else r!==0?(r!==o&&(xo(e,r,e.bl_tree),a--),xo(e,16,e.bl_tree),rr(e,a-3,2)):a<=10?(xo(e,17,e.bl_tree),rr(e,a-3,3)):(xo(e,18,e.bl_tree),rr(e,a-11,7));a=0,o=r,s===0?(c=138,d=3):r===s?(c=6,d=3):(c=7,d=4)}};let iL=!1;const rL=(e,t,n,i)=>{rr(e,0+(i?1:0),3),QP(e),su(e,n),su(e,~n),n&&e.pending_buf.set(e.window.subarray(t,t+n),e.pending),e.pending+=n};var EJ=e=>{iL||((()=>{let t,n,i,r,o;const s=new Array(16);for(i=0,r=0;r<28;r++)for(cT[r]=i,t=0;t<1<<aT[r];t++)ou[i++]=r;for(ou[i-1]=r,o=0,r=0;r<16;r++)for(a_[r]=o,t=0;t<1<<s_[r];t++)ru[o++]=r;for(o>>=7;r<tu;r++)for(a_[r]=o<<7,t=0;t<1<<s_[r]-7;t++)ru[256+o++]=r;for(n=0;n<=nu;n++)s[n]=0;for(t=0;t<=143;)us[2*t+1]=8,t++,s[8]++;for(;t<=255;)us[2*t+1]=9,t++,s[9]++;for(;t<=279;)us[2*t+1]=7,t++,s[7]++;for(;t<=287;)us[2*t+1]=8,t++,s[8]++;for(qP(us,287,s),t=0;t<tu;t++)iu[2*t+1]=5,iu[2*t]=zP(t,5);HP=new dT(us,aT,257,WP,nu),YP=new dT(iu,s_,0,tu,nu),XP=new dT(new Array(0),mJ,0,19,7)})(),iL=!0),e.l_desc=new lT(e.dyn_ltree,HP),e.d_desc=new lT(e.dyn_dtree,YP),e.bl_desc=new lT(e.bl_tree,XP),e.bi_buf=0,e.bi_valid=0,ZP(e)},fJ=(e,t,n,i)=>{let r,o,s=0;e.level>0?(e.strm.data_type===2&&(e.strm.data_type=(a=>{let c,d=4093624447;for(c=0;c<=31;c++,d>>>=1)if(1&d&&a.dyn_ltree[2*c]!==0)return 0;if(a.dyn_ltree[18]!==0||a.dyn_ltree[20]!==0||a.dyn_ltree[26]!==0)return 1;for(c=32;c<sT;c++)if(a.dyn_ltree[2*c]!==0)return 1;return 0})(e)),hT(e,e.l_desc),hT(e,e.d_desc),s=(a=>{let c;for(tL(a,a.dyn_ltree,a.l_desc.max_code),tL(a,a.dyn_dtree,a.d_desc.max_code),hT(a,a.bl_desc),c=18;c>=3&&a.bl_tree[2*KP[c]+1]===0;c--);return a.opt_len+=3*(c+1)+5+5+4,c})(e),r=e.opt_len+3+7>>>3,o=e.static_len+3+7>>>3,o<=r&&(r=o)):r=o=n+5,n+4<=r&&t!==-1?rL(e,t,n,i):e.strategy===4||o===r?(rr(e,2+(i?1:0),3),eL(e,us,iu)):(rr(e,4+(i?1:0),3),((a,c,d,l)=>{let h;for(rr(a,c-257,5),rr(a,d-1,5),rr(a,l-4,4),h=0;h<l;h++)rr(a,a.bl_tree[2*KP[h]+1],3);nL(a,a.dyn_ltree,c-1),nL(a,a.dyn_dtree,d-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,s+1),eL(e,e.dyn_ltree,e.dyn_dtree)),ZP(e),i&&QP(e)}
52,gJ=(e,t,n)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=n,t===0?e.dyn_ltree[2*n]++:(e.matches++,t--,e.dyn_ltree[2*(ou[n]+sT+1)]++,e.dyn_dtree[2*JP(t)]++),e.sym_next===e.sym_end),SJ=e=>{rr(e,2,3),xo(e,256,us),(t=>{t.bi_valid===16?(su(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(e)},TJ={_tr_init:EJ,_tr_stored_block:rL,_tr_flush_block:fJ,_tr_tally:gJ,_tr_align:SJ},au=(e,t,n,i)=>{let r=65535&e|0,o=e>>>16&65535|0,s=0;for(;n!==0;){s=n>2e3?2e3:n,n-=s;do r=r+t[i++]|0,o=o+r|0;while(--s);r%=65521,o%=65521}return r|o<<16|0};const RJ=new Uint32Array((()=>{let e,t=[];for(var n=0;n<256;n++){e=n;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t})());var ai=(e,t,n,i)=>{const r=RJ,o=i+n;e^=-1;for(let s=i;s<o;s++)e=e>>>8^r[255&(e^t[s])];return-1^e},Ya={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},c_={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:vJ,_tr_stored_block:pT,_tr_flush_block:AJ,_tr_tally:js,_tr_align:CJ}=TJ,{Z_NO_FLUSH:Ws,Z_PARTIAL_FLUSH:yJ,Z_FULL_FLUSH:IJ,Z_FINISH:Xr,Z_BLOCK:oL,Z_OK:_i,Z_STREAM_END:sL,Z_STREAM_ERROR:Fo,Z_DATA_ERROR:bJ,Z_BUF_ERROR:_T,Z_DEFAULT_COMPRESSION:wJ,Z_FILTERED:OJ,Z_HUFFMAN_ONLY:d_,Z_RLE:NJ,Z_FIXED:DJ,Z_DEFAULT_STRATEGY:PJ,Z_UNKNOWN:LJ,Z_DEFLATED:l_}=c_,mT=286,kJ=30,MJ=19,UJ=2*mT+1,VJ=15,Xa=258,Bo=262,Cd=42,Ja=113,cu=666,za=(e,t)=>(e.msg=Ya[t],t),aL=e=>2*e-(e>4?9:0),Ks=e=>{let t=e.length;for(;--t>=0;)e[t]=0},xJ=e=>{let t,n,i,r=e.w_size;t=e.hash_size,i=t;do n=e.head[--i],e.head[i]=n>=r?n-r:0;while(--t);t=r,i=t;do n=e.prev[--i],e.prev[i]=n>=r?n-r:0;while(--t)};let Hs=(e,t,n)=>(t<<e.hash_shift^n)&e.hash_mask;const fr=e=>{const t=e.state;let n=t.pending;n>e.avail_out&&(n=e.avail_out),n!==0&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+n),e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,t.pending===0&&(t.pending_out=0))},gr=(e,t)=>{AJ(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,fr(e.strm)},Yt=(e,t)=>{e.pending_buf[e.pending++]=t},du=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},ET=(e,t,n,i)=>{let r=e.avail_in;return r>i&&(r=i),r===0?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),n),e.state.wrap===1?e.adler=au(e.adler,t,r,n):e.state.wrap===2&&(e.adler=ai(e.adler,t,r,n)),e.next_in+=r,e.total_in+=r,r)},cL=(e,t)=>{let n,i,r=e.max_chain_length,o=e.strstart,s=e.prev_length,a=e.nice_match;const c=e.strstart>e.w_size-Bo?e.strstart-(e.w_size-Bo):0,d=e.window,l=e.w_mask,h=e.prev,u=e.strstart+Xa;let p=d[o+s-1],E=d[o+s];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do if(n=t,d[n+s]===E&&d[n+s-1]===p&&d[n]===d[o]&&d[++n]===d[o+1]){o+=2,n++;do;while(d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&o<u);if(i=Xa-(u-o),o=u-Xa,i>s){if(e.match_start=t,s=i,i>=a)break;p=d[o+s-1],E=d[o+s]}}while((t=h[t&l])>c&&--r!=0);return s<=e.lookahead?s:e.lookahead},yd=e=>{const t=e.w_size;let n,i,r;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Bo)&&(e.window.set(e.window.subarray(t,t+t-i),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),xJ(e),i+=t),e.strm.avail_in===0)break;if(n=ET(e.strm,e.window,e.strstart+e.lookahead,i),e.lookahead+=n,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=Hs(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=Hs(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<Bo&&e.strm.avail_in!==0)},dL=(e,t)=>{let n,i,r,o=e.pending_buf_size-5>
52e.w_size?e.w_size:e.pending_buf_size-5,s=0,a=e.strm.avail_in;do{if(n=65535,r=e.bi_valid+42>>3,e.strm.avail_out<r||(r=e.strm.avail_out-r,i=e.strstart-e.block_start,n>i+e.strm.avail_in&&(n=i+e.strm.avail_in),n>r&&(n=r),n<o&&(n===0&&t!==Xr||t===Ws||n!==i+e.strm.avail_in)))break;s=t===Xr&&n===i+e.strm.avail_in?1:0,pT(e,0,0,s),e.pending_buf[e.pending-4]=n,e.pending_buf[e.pending-3]=n>>8,e.pending_buf[e.pending-2]=~n,e.pending_buf[e.pending-1]=~n>>8,fr(e.strm),i&&(i>n&&(i=n),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+i),e.strm.next_out),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i,e.block_start+=i,n-=i),n&&(ET(e.strm,e.strm.output,e.strm.next_out,n),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n)}while(s===0);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),s?4:t!==Ws&&t!==Xr&&e.strm.avail_in===0&&e.strstart===e.block_start?2:(r=e.window_size-e.strstart,e.strm.avail_in>r&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(ET(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water<e.strstart&&(e.high_water=e.strstart),r=e.bi_valid+42>>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,o=r>e.w_size?e.w_size:r,i=e.strstart-e.block_start,(i>=o||(i||t===Xr)&&t!==Ws&&e.strm.avail_in===0&&i<=r)&&(n=i>r?r:i,s=t===Xr&&e.strm.avail_in===0&&n===i?1:0,pT(e,e.block_start,n,s),e.block_start+=n,fr(e.strm)),s?3:1)},fT=(e,t)=>{let n,i;for(;;){if(e.lookahead<Bo){if(yd(e),e.lookahead<Bo&&t===Ws)return 1;if(e.lookahead===0)break}if(n=0,e.lookahead>=3&&(e.ins_h=Hs(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),n!==0&&e.strstart-n<=e.w_size-Bo&&(e.match_length=cL(e,n)),e.match_length>=3)if(i=js(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do e.strstart++,e.ins_h=Hs(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!=0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=Hs(e,e.ins_h,e.window[e.strstart+1]);else i=js(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(gr(e,!1),e.strm.avail_out===0))return 1}return e.insert=e.strstart<2?e.strstart:2,t===Xr?(gr(e,!0),e.strm.avail_out===0?3:4):e.sym_next&&(gr(e,!1),e.strm.avail_out===0)?1:2},Id=(e,t)=>{let n,i,r;for(;;){if(e.lookahead<Bo){if(yd(e),e.lookahead<Bo&&t===Ws)return 1;if(e.lookahead===0)break}if(n=0,e.lookahead>=3&&(e.ins_h=Hs(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,n!==0&&e.prev_length<e.max_lazy_match&&e.strstart-n<=e.w_size-Bo&&(e.match_length=cL(e,n),e.match_length<=5&&(e.strategy===OJ||e.match_length===3&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,i=js(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=r&&(e.ins_h=Hs(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!=0);if(e.match_available=0,e.match_length=2,e.strstart++,i&&(gr(e,!1),e.strm.avail_out===0))return 1}else if(e.match_available){if(i=js(e,0,e.window[e.strstart-1]),i&&gr(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(i=js(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===Xr?(gr(e,!0),e.strm.avail_out===0?3:4):e.sym_next&&(gr(e,!1),e.strm.avail_out===0)?1:2};function Go(e,t,n,i,r){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=i,this.func=r}const lu=[new Go(0,0,0,0,dL),new Go(4,4,8,4,fT),new Go(4,5,16,8,fT),new Go(4,6,32,32,fT),new Go(4,4,16,16,Id),new Go(8,16,32,32,Id),new Go(8,16,128,128,Id),new Go(8,32,128,256,Id),new Go(32,128,258,1024,Id),new Go(32,258,258,4096,Id)];function FJ(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=l_,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*UJ),this.dyn_dtree=new Uint16Array(2*(2*kJ+1)),this.bl_tree=new Uint16Array(2*(2*MJ+1)),Ks(this.dyn_ltree),Ks(this.dyn_dtree),Ks(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(VJ+1),this.heap=new Uint16Array(2*mT+1),Ks(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*mT+1),Ks(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const uu=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==Cd&&t.status!==57&&t.status!==69&&t.status!==73&&t.status!==91&&t.status!==103&&t.status!==Ja&&t.status!==cu?1:0},lL=e=>{if(uu(e))return za(e,Fo);e.total_in=e.total_out=0,e.data_type=LJ;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap===2?57:t.wrap?Cd:Ja,e.adler=t.wrap===2?0:1,t.last_flush=-2,vJ(t),_i},uL=e=>{const t=lL(e);
52return t===_i&&(n=>{n.window_size=2*n.w_size,Ks(n.head),n.max_lazy_match=lu[n.level].max_lazy,n.good_match=lu[n.level].good_length,n.nice_match=lu[n.level].nice_length,n.max_chain_length=lu[n.level].max_chain,n.strstart=0,n.block_start=0,n.lookahead=0,n.insert=0,n.match_length=n.prev_length=2,n.match_available=0,n.ins_h=0})(e.state),t},hL=(e,t,n,i,r,o)=>{if(!e)return Fo;let s=1;if(t===wJ&&(t=6),i<0?(s=0,i=-i):i>15&&(s=2,i-=16),r<1||r>9||n!==l_||i<8||i>15||t<0||t>9||o<0||o>DJ||i===8&&s!==1)return za(e,Fo);i===8&&(i=9);const a=new FJ;return e.state=a,a.strm=e,a.status=Cd,a.wrap=s,a.gzhead=null,a.w_bits=i,a.w_size=1<<a.w_bits,a.w_mask=a.w_size-1,a.hash_bits=r+7,a.hash_size=1<<a.hash_bits,a.hash_mask=a.hash_size-1,a.hash_shift=~~((a.hash_bits+3-1)/3),a.window=new Uint8Array(2*a.w_size),a.head=new Uint16Array(a.hash_size),a.prev=new Uint16Array(a.w_size),a.lit_bufsize=1<<r+6,a.pending_buf_size=4*a.lit_bufsize,a.pending_buf=new Uint8Array(a.pending_buf_size),a.sym_buf=a.lit_bufsize,a.sym_end=3*(a.lit_bufsize-1),a.level=t,a.strategy=o,a.method=n,uL(e)};var BJ=(e,t)=>{if(uu(e)||t>oL||t<0)return e?za(e,Fo):Fo;const n=e.state;if(!e.output||e.avail_in!==0&&!e.input||n.status===cu&&t!==Xr)return za(e,e.avail_out===0?_T:Fo);const i=n.last_flush;if(n.last_flush=t,n.pending!==0){if(fr(e),e.avail_out===0)return n.last_flush=-1,_i}else if(e.avail_in===0&&aL(t)<=aL(i)&&t!==Xr)return za(e,_T);if(n.status===cu&&e.avail_in!==0)return za(e,_T);if(n.status===Cd&&n.wrap===0&&(n.status=Ja),n.status===Cd){let r=l_+(n.w_bits-8<<4)<<8,o=-1;if(o=n.strategy>=d_||n.level<2?0:n.level<6?1:n.level===6?2:3,r|=o<<6,n.strstart!==0&&(r|=32),r+=31-r%31,du(n,r),n.strstart!==0&&(du(n,e.adler>>>16),du(n,65535&e.adler)),e.adler=1,n.status=Ja,fr(e),n.pending!==0)return n.last_flush=-1,_i}if(n.status===57){if(e.adler=0,Yt(n,31),Yt(n,139),Yt(n,8),n.gzhead)Yt(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),Yt(n,255&n.gzhead.time),Yt(n,n.gzhead.time>>8&255),Yt(n,n.gzhead.time>>16&255),Yt(n,n.gzhead.time>>24&255),Yt(n,n.level===9?2:n.strategy>=d_||n.level<2?4:0),Yt(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(Yt(n,255&n.gzhead.extra.length),Yt(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=ai(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69;else if(Yt(n,0),Yt(n,0),Yt(n,0),Yt(n,0),Yt(n,0),Yt(n,n.level===9?2:n.strategy>=d_||n.level<2?4:0),Yt(n,3),n.status=Ja,fr(e),n.pending!==0)return n.last_flush=-1,_i}if(n.status===69){if(n.gzhead.extra){let r=n.pending,o=(65535&n.gzhead.extra.length)-n.gzindex;for(;n.pending+o>n.pending_buf_size;){let a=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+a),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>r&&(e.adler=ai(e.adler,n.pending_buf,n.pending-r,r)),n.gzindex+=a,fr(e),n.pending!==0)return n.last_flush=-1,_i;r=0,o-=a}let s=new Uint8Array(n.gzhead.extra);n.pending_buf.set(s.subarray(n.gzindex,n.gzindex+o),n.pending),n.pending+=o,n.gzhead.hcrc&&n.pending>r&&(e.adler=ai(e.adler,n.pending_buf,n.pending-r,r)),n.gzindex=0}n.status=73}if(n.status===73){if(n.gzhead.name){let r,o=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>o&&(e.adler=ai(e.adler,n.pending_buf,n.pending-o,o)),fr(e),n.pending!==0)return n.last_flush=-1,_i;o=0}r=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,Yt(n,r)}while(r!==0);n.gzhead.hcrc&&n.pending>o&&(e.adler=ai(e.adler,n.pending_buf,n.pending-o,o)),n.gzindex=0}n.status=91}if(n.status===91){if(n.gzhead.comment){let r,o=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>o&&(e.adler=ai(e.adler,n.pending_buf,n.pending-o,o)),fr(e),n.pending!==0)return n.last_flush=-1,_i;o=0}r=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,Yt(n,r)}while(r!==0);n.gzhead.hcrc&&n.pending>o&&(e.adler=ai(e.adler,n.pending_buf,n.pending-o,o))}n.status=103}if(n.status===103){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(fr(e),n.pending!==0))return n.last_flush=-1,_i;Yt(n,255&e.adler),Yt(n,e.adler>>8&255),e.adler=0}if(n.status=Ja,fr(e),n.pending!==0)return n.last_flush=-1,_i}if(e.avail_in!==0||n.lookahead!==0||t!==Ws&&n.status!==cu){let r=n.level===0?dL(n,t):n.strategy===d_?((o,s)=>{let a;for(;;){if(o.lookahead===0&&(yd(o),o.lookahead===0)){if(s===Ws)return 1;break}if(o.match_length=0,a=js(o,0,o.window[o.strstart]),o.lookahead--,o.strstart++,a&&(gr(o,!1),o.strm.avail_out===0))return 1}return o.insert=0,s===Xr?(gr(o,!0),o.strm.avail_out===0?3:4):o.sym_next&&(gr(o,!1),o.strm.avail_out===0)?1:2})(n,t):n.strategy===NJ?((o,s)=>{let a,c,d,l;const h=o.window;for(;;){if(o.lookahead<=Xa){if(yd(o),o.lookahead<=Xa&&s===Ws)return 1;if(o.lookahead===0)break}if(o.match_length=0,o.lookahead>=3&&o.strstart>0&&(d=o.strstart-1,c=h[d],c===h[++d]&&c===h[++d]&&c===h[++d])){l=o.strstart+Xa;do;while(c===h[++d]&&c===h[++d]&&c===h[++d]&&c===h[++d]&&c===h[++d]&&c===h[++d]&&c===h[++d]&&c===h[++d]&&d<l);o.match_length=Xa-(l-d),o.match_length>
52o.lookahead&&(o.match_length=o.lookahead)}if(o.match_length>=3?(a=js(o,1,o.match_length-3),o.lookahead-=o.match_length,o.strstart+=o.match_length,o.match_length=0):(a=js(o,0,o.window[o.strstart]),o.lookahead--,o.strstart++),a&&(gr(o,!1),o.strm.avail_out===0))return 1}return o.insert=0,s===Xr?(gr(o,!0),o.strm.avail_out===0?3:4):o.sym_next&&(gr(o,!1),o.strm.avail_out===0)?1:2})(n,t):lu[n.level].func(n,t);if(r!==3&&r!==4||(n.status=cu),r===1||r===3)return e.avail_out===0&&(n.last_flush=-1),_i;if(r===2&&(t===yJ?CJ(n):t!==oL&&(pT(n,0,0,!1),t===IJ&&(Ks(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),fr(e),e.avail_out===0))return n.last_flush=-1,_i}return t!==Xr?_i:n.wrap<=0?sL:(n.wrap===2?(Yt(n,255&e.adler),Yt(n,e.adler>>8&255),Yt(n,e.adler>>16&255),Yt(n,e.adler>>24&255),Yt(n,255&e.total_in),Yt(n,e.total_in>>8&255),Yt(n,e.total_in>>16&255),Yt(n,e.total_in>>24&255)):(du(n,e.adler>>>16),du(n,65535&e.adler)),fr(e),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?_i:sL)},GJ=(e,t)=>{let n=t.length;if(uu(e))return Fo;const i=e.state,r=i.wrap;if(r===2||r===1&&i.status!==Cd||i.lookahead)return Fo;if(r===1&&(e.adler=au(e.adler,t,n,0)),i.wrap=0,n>=i.w_size){r===0&&(Ks(i.head),i.strstart=0,i.block_start=0,i.insert=0);let c=new Uint8Array(i.w_size);c.set(t.subarray(n-i.w_size,n),0),t=c,n=i.w_size}const o=e.avail_in,s=e.next_in,a=e.input;for(e.avail_in=n,e.next_in=0,e.input=t,yd(i);i.lookahead>=3;){let c=i.strstart,d=i.lookahead-2;do i.ins_h=Hs(i,i.ins_h,i.window[c+3-1]),i.prev[c&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=c,c++;while(--d);i.strstart=c,i.lookahead=2,yd(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,e.next_in=s,e.input=a,e.avail_in=o,i.wrap=r,_i},hu={deflateInit:(e,t)=>hL(e,t,l_,15,8,PJ),deflateInit2:hL,deflateReset:uL,deflateResetKeep:lL,deflateSetHeader:(e,t)=>uu(e)||e.state.wrap!==2?Fo:(e.state.gzhead=t,_i),deflate:BJ,deflateEnd:e=>{if(uu(e))return Fo;const t=e.state.status;return e.state=null,t===Ja?za(e,bJ):_i},deflateSetDictionary:GJ,deflateInfo:"pako deflate (from Nodeca project)"};const jJ=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var u_={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const n=t.shift();if(n){if(typeof n!="object")throw new TypeError(n+"must be non-object");for(const i in n)jJ(n,i)&&(e[i]=n[i])}}return e},flattenChunks:e=>{let t=0;for(let i=0,r=e.length;i<r;i++)t+=e[i].length;const n=new Uint8Array(t);for(let i=0,r=0,o=e.length;i<o;i++){let s=e[i];n.set(s,r),r+=s.length}return n}};let pL=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{pL=!1}const pu=new Uint8Array(256);for(let e=0;e<256;e++)pu[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;pu[254]=pu[254]=1;var _u={string2buf:e=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(e);let t,n,i,r,o,s=e.length,a=0;for(r=0;r<s;r++)n=e.charCodeAt(r),(64512&n)==55296&&r+1<s&&(i=e.charCodeAt(r+1),(64512&i)==56320&&(n=65536+(n-55296<<10)+(i-56320),r++)),a+=n<128?1:n<2048?2:n<65536?3:4;for(t=new Uint8Array(a),o=0,r=0;o<a;r++)n=e.charCodeAt(r),(64512&n)==55296&&r+1<s&&(i=e.charCodeAt(r+1),(64512&i)==56320&&(n=65536+(n-55296<<10)+(i-56320),r++)),n<128?t[o++]=n:n<2048?(t[o++]=192|n>>>6,t[o++]=128|63&n):n<65536?(t[o++]=224|n>>>12,t[o++]=128|n>>>6&63,t[o++]=128|63&n):(t[o++]=240|n>>>18,t[o++]=128|n>>>12&63,t[o++]=128|n>>>6&63,t[o++]=128|63&n);return t},buf2string:(e,t)=>{const n=t||e.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(e.subarray(0,t));let i,r;const o=new Array(2*n);for(r=0,i=0;i<n;){let s=e[i++];if(s<128){o[r++]=s;continue}let a=pu[s];if(a>4)o[r++]=65533,i+=a-1;else{for(s&=a===2?31:a===3?15:7;a>1&&i<n;)s=s<<6|63&e[i++],a--;a>1?o[r++]=65533:s<65536?o[r++]=s:(s-=65536,o[r++]=55296|s>>10&1023,o[r++]=56320|1023&s)}}return((s,a)=>
52{if(a<65534&&s.subarray&&pL)return String.fromCharCode.apply(null,s.length===a?s:s.subarray(0,a));let c="";for(let d=0;d<a;d++)c+=String.fromCharCode(s[d]);return c})(o,r)},utf8border:(e,t)=>{(t=t||e.length)>e.length&&(t=e.length);let n=t-1;for(;n>=0&&(192&e[n])==128;)n--;return n<0||n===0?t:n+pu[e[n]]>t?n:t}},_L=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const mL=Object.prototype.toString,{Z_NO_FLUSH:WJ,Z_SYNC_FLUSH:KJ,Z_FULL_FLUSH:HJ,Z_FINISH:YJ,Z_OK:h_,Z_STREAM_END:XJ,Z_DEFAULT_COMPRESSION:JJ,Z_DEFAULT_STRATEGY:zJ,Z_DEFLATED:qJ}=c_;function p_(e){this.options=u_.assign({level:JJ,method:qJ,chunkSize:16384,windowBits:15,memLevel:8,strategy:zJ},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new _L,this.strm.avail_out=0;let n=hu.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==h_)throw new Error(Ya[n]);if(t.header&&hu.deflateSetHeader(this.strm,t.header),t.dictionary){let i;if(i=typeof t.dictionary=="string"?_u.string2buf(t.dictionary):mL.call(t.dictionary)==="[object ArrayBuffer]"?new Uint8Array(t.dictionary):t.dictionary,n=hu.deflateSetDictionary(this.strm,i),n!==h_)throw new Error(Ya[n]);this._dict_set=!0}}function EL(e,t){const n=new p_(t);if(n.push(e,!0),n.err)throw n.msg||Ya[n.err];return n.result}p_.prototype.push=function(e,t){const n=this.strm,i=this.options.chunkSize;let r,o;if(this.ended)return!1;for(o=t===~~t?t:t===!0?YJ:WJ,typeof e=="string"?n.input=_u.string2buf(e):mL.call(e)==="[object ArrayBuffer]"?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;)if(n.avail_out===0&&(n.output=new Uint8Array(i),n.next_out=0,n.avail_out=i),(o===KJ||o===HJ)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if(r=hu.deflate(n,o),r===XJ)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),r=hu.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===h_;if(n.avail_out!==0){if(o>0&&n.next_out>0)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else if(n.avail_in===0)break}else this.onData(n.output)}return!0},p_.prototype.onData=function(e){this.chunks.push(e)},p_.prototype.onEnd=function(e){e===h_&&(this.result=u_.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ZJ={deflate:EL,deflateRaw:function(e,t){return(t=t||{}).raw=!0,EL(e,t)}};const __=16209;var QJ=function(e,t){let n,i,r,o,s,a,c,d,l,h,u,p,E,m,g,R,v,C,w,b,y,N,k,U;const X=e.state;n=e.next_in,k=e.input,i=n+(e.avail_in-5),r=e.next_out,U=e.output,o=r-(t-e.avail_out),s=r+(e.avail_out-257),a=X.dmax,c=X.wsize,d=X.whave,l=X.wnext,h=X.window,u=X.hold,p=X.bits,E=X.lencode,m=X.distcode,g=(1<<X.lenbits)-1,R=(1<<X.distbits)-1;
52e:do{p<15&&(u+=k[n++]<<p,p+=8,u+=k[n++]<<p,p+=8),v=E[u&g];t:for(;;){if(C=v>>>24,u>>>=C,p-=C,C=v>>>16&255,C===0)U[r++]=65535&v;else{if(!(16&C)){if(!(64&C)){v=E[(65535&v)+(u&(1<<C)-1)];continue t}if(32&C){X.mode=16191;break e}e.msg="invalid literal/length code",X.mode=__;break e}w=65535&v,C&=15,C&&(p<C&&(u+=k[n++]<<p,p+=8),w+=u&(1<<C)-1,u>>>=C,p-=C),p<15&&(u+=k[n++]<<p,p+=8,u+=k[n++]<<p,p+=8),v=m[u&R];n:for(;;){if(C=v>>>24,u>>>=C,p-=C,C=v>>>16&255,!(16&C)){if(!(64&C)){v=m[(65535&v)+(u&(1<<C)-1)];continue n}e.msg="invalid distance code",X.mode=__;break e}if(b=65535&v,C&=15,p<C&&(u+=k[n++]<<p,p+=8,p<C&&(u+=k[n++]<<p,p+=8)),b+=u&(1<<C)-1,b>a){e.msg="invalid distance too far back",X.mode=__;break e}if(u>>>=C,p-=C,C=r-o,b>C){if(C=b-C,C>d&&X.sane){e.msg="invalid distance too far back",X.mode=__;break e}if(y=0,N=h,l===0){if(y+=c-C,C<w){w-=C;do U[r++]=h[y++];while(--C);y=r-b,N=U}}else if(l<C){if(y+=c+l-C,C-=l,C<w){w-=C;do U[r++]=h[y++];while(--C);if(y=0,l<w){C=l,w-=C;do U[r++]=h[y++];while(--C);y=r-b,N=U}}}else if(y+=l-C,C<w){w-=C;do U[r++]=h[y++];while(--C);y=r-b,N=U}for(;w>2;)U[r++]=N[y++],U[r++]=N[y++],U[r++]=N[y++],w-=3;w&&(U[r++]=N[y++],w>1&&(U[r++]=N[y++]))}else{y=r-b;do U[r++]=U[y++],U[r++]=U[y++],U[r++]=U[y++],w-=3;while(w>2);w&&(U[r++]=U[y++],w>1&&(U[r++]=U[y++]))}break}}break}}while(n<i&&r<s);w=p>>3,n-=w,p-=w<<3,u&=(1<<p)-1,e.next_in=n,e.next_out=r,e.avail_in=n<i?i-n+5:5-(n-i),e.avail_out=r<s?s-r+257:257-(r-s),X.hold=u,X.bits=p};const m_=15,$J=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),ez=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),tz=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),nz=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var mu=(e,t,n,i,r,o,s,a)=>{const c=a.bits;let d,l,h,u,p,E,m=0,g=0,R=0,v=0,C=0,w=0,b=0,y=0,N=0,k=0,U=null;const X=new Uint16Array(16),q=new Uint16Array(16);let se,_e,me,ke=null;for(m=0;m<=m_;m++)X[m]=0;for(g=0;g<i;g++)X[t[n+g]]++;for(C=c,v=m_;v>=1&&X[v]===0;v--);if(C>v&&(C=v),v===0)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(R=1;R<v&&X[R]===0;R++);for(C<R&&(C=R),y=1,m=1;m<=m_;m++)if(y<<=1,y-=X[m],y<0)return-1;if(y>0&&(e===0||v!==1))return-1;for(q[1]=0,m=1;m<m_;m++)q[m+1]=q[m]+X[m];for(g=0;g<i;g++)t[n+g]!==0&&(s[q[t[n+g]]++]=g);if(e===0?(U=ke=s,E=20):e===1?(U=$J,ke=ez,E=257):(U=tz,ke=nz,E=0),k=0,g=0,m=R,p=o,w=C,b=0,h=-1,N=1<<C,u=N-1,e===1&&N>852||e===2&&N>592)return 1;for(;;){se=m-b,s[g]+1<E?(_e=0,me=s[g]):s[g]>=E?(_e=ke[s[g]-E],me=U[s[g]-E]):(_e=96,me=0),d=1<<m-b,l=1<<w,R=l;do l-=d,r[p+(k>>b)+l]=se<<24|_e<<16|me|0;while(l!==0);for(d=1<<m-1;k&d;)d>>=1;if(d!==0?(k&=d-1,k+=d):k=0,g++,--X[m]==0){if(m===v)break;m=t[n+s[g]]}if(m>C&&(k&u)!==h){for(b===0&&(b=C),p+=R,w=m-b,y=1<<w;w+b<v&&(y-=X[w+b],!(y<=0));)w++,y<<=1;if(N+=1<<w,e===1&&N>852||e===2&&N>592)return 1;h=k&u,r[h]=C<<24|w<<16|p-o|0}}return k!==0&&(r[p+k]=m-b<<24|64<<16|0),a.bits=C,0};const{Z_FINISH:fL,Z_BLOCK:iz,Z_TREES:E_,Z_OK:qa,Z_STREAM_END:rz,Z_NEED_DICT:oz,Z_STREAM_ERROR:Jr,Z_DATA_ERROR:gL,Z_MEM_ERROR:SL,Z_BUF_ERROR:sz,Z_DEFLATED:TL}=c_,f_=16180,g_=16190,hs=16191,gT=16192,ST=16194,S_=16199,T_=16200,TT=16206,yn=16209,RL=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function az(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const Za=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode<f_||t.mode>16211?1:0},vL=e=>{if(Za(e))return Jr;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=f_,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,qa},AL=e=>{if(Za(e))return Jr;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,vL(e)},CL=(e,t)=>{let n;if(Za(e))return Jr;const i=e.state;return t<0?(n=0,t=-t):(n=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?Jr:(i.window!==null&&i.wbits!==t&&(i.window=null),i.wrap=n,i.wbits=t,AL(e))},yL=(e,t)=>{if(!e)return Jr;const n=new az;e.state=n,n.strm=e,n.window=null,n.mode=f_;const i=CL(e,t);return i!==qa&&(e.state=null),i};let RT,vT,IL=!0;const cz=e=>{if(IL){RT=new Int32Array(512),vT=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(mu(1,e.lens,0,288,RT,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;mu(2,e.lens,0,32,vT,0,e.work,{bits:5}),IL=!1}
52e.lencode=RT,e.lenbits=9,e.distcode=vT,e.distbits=5},bL=(e,t,n,i)=>{let r;const o=e.state;return o.window===null&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new Uint8Array(o.wsize)),i>=o.wsize?(o.window.set(t.subarray(n-o.wsize,n),0),o.wnext=0,o.whave=o.wsize):(r=o.wsize-o.wnext,r>i&&(r=i),o.window.set(t.subarray(n-i,n-i+r),o.wnext),(i-=r)?(o.window.set(t.subarray(n-i,n),0),o.wnext=i,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=r))),0};var dz=(e,t)=>{let n,i,r,o,s,a,c,d,l,h,u,p,E,m,g,R,v,C,w,b,y,N,k=0;const U=new Uint8Array(4);let X,q;const se=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(Za(e)||!e.output||!e.input&&e.avail_in!==0)return Jr;n=e.state,n.mode===hs&&(n.mode=gT),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,i=e.input,a=e.avail_in,d=n.hold,l=n.bits,h=a,u=c,N=qa;e:for(;;)switch(n.mode){case f_:if(n.wrap===0){n.mode=gT;break}for(;l<16;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}if(2&n.wrap&&d===35615){n.wbits===0&&(n.wbits=15),n.check=0,U[0]=255&d,U[1]=d>>>8&255,n.check=ai(n.check,U,2,0),d=0,l=0,n.mode=16181;break}if(n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&d)<<8)+(d>>8))%31){e.msg="incorrect header check",n.mode=yn;break}if((15&d)!==TL){e.msg="unknown compression method",n.mode=yn;break}if(d>>>=4,l-=4,y=8+(15&d),n.wbits===0&&(n.wbits=y),y>15||y>n.wbits){e.msg="invalid window size",n.mode=yn;break}n.dmax=1<<n.wbits,n.flags=0,e.adler=n.check=1,n.mode=512&d?16189:hs,d=0,l=0;break;case 16181:for(;l<16;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}if(n.flags=d,(255&qn(n))!==TL){e.msg="unknown compression method",n.mode=yn;break}if(57344&qn(n)){e.msg="unknown header flags set",n.mode=yn;break}n.head&&(n.head.text=d>>8&1),512&qn(n)&&4&n.wrap&&(U[0]=255&d,U[1]=d>>>8&255,n.check=ai(n.check,U,2,0)),d=0,l=0,n.mode=16182;case 16182:for(;l<32;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}n.head&&(n.head.time=d),512&qn(n)&&4&n.wrap&&(U[0]=255&d,U[1]=d>>>8&255,U[2]=d>>>16&255,U[3]=d>>>24&255,n.check=ai(n.check,U,4,0)),d=0,l=0,n.mode=16183;case 16183:for(;l<16;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}n.head&&(n.head.xflags=255&d,n.head.os=d>>8),512&qn(n)&&4&n.wrap&&(U[0]=255&d,U[1]=d>>>8&255,n.check=ai(n.check,U,2,0)),d=0,l=0,n.mode=16184;case 16184:if(1024&qn(n)){for(;l<16;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}n.length=d,n.head&&(n.head.extra_len=d),512&qn(n)&&4&n.wrap&&(U[0]=255&d,U[1]=d>>>8&255,n.check=ai(n.check,U,2,0)),d=0,l=0}else n.head&&(n.head.extra=null);n.mode=16185;case 16185:if(1024&qn(n)&&(p=n.length,p>a&&(p=a),p&&(n.head&&(y=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(i.subarray(o,o+p),y)),512&qn(n)&&4&n.wrap&&(n.check=ai(n.check,i,p,o)),a-=p,o+=p,n.length-=p),n.length))break e;n.length=0,n.mode=16186;case 16186:if(2048&qn(n)){if(a===0)break e;p=0;do y=i[o+p++],n.head&&y&&n.length<65536&&(n.head.name+=String.fromCharCode(y));while(y&&p<a);if(512&qn(n)&&4&n.wrap&&(n.check=ai(n.check,i,p,o)),a-=p,o+=p,y)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=16187;case 16187:if(4096&qn(n)){if(a===0)break e;p=0;do y=i[o+p++],n.head&&y&&n.length<65536&&(n.head.comment+=String.fromCharCode(y));while(y&&p<a);if(512&qn(n)&&4&n.wrap&&(n.check=ai(n.check,i,p,o)),a-=p,o+=p,y)break e}else n.head&&(n.head.comment=null);n.mode=16188;case 16188:if(512&qn(n)){for(;l<16;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}if(4&n.wrap&&d!==(65535&n.check)){e.msg="header crc mismatch",n.mode=yn;break}d=0,l=0}n.head&&(n.head.hcrc=qn(n)>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=hs;break;case 16189:for(;l<32;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}e.adler=n.check=RL(d),d=0,l=0,n.mode=g_;case g_:if(n.havedict===0)return e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,n.hold=d,n.bits=l,oz;e.adler=n.check=1,n.mode=hs;case hs:if(t===iz||t===E_)break e;case gT:if(n.last){d>>>=7&l,l-=7&l,n.mode=TT;break}for(;l<3;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}switch(n.last=1&d,d>>>=1,l-=1,3&d){case 0:n.mode=16193;break;case 1:if(cz(n),n.mode=S_,t===E_){d>>>=2,l-=2;break e}break;case 2:n.mode=16196;break;case 3:e.msg="invalid block type",n.mode=yn}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}if((65535&d)!=(d>>>16^65535)){e.msg="invalid stored block lengths",n.mode=yn;break}if(n.length=65535&d,d=0,l=0,n.mode=ST,t===E_)break e;case ST:n.mode=16195;case 16195:if(p=n.length,p){if(p>a&&(p=a),p>c&&(p=c),p===0)break e;r.set(i.subarray(o,o+p),s),a-=p,o+=p,c-=p,s+=p,n.length-=p;break}n.mode=hs;break;case 16196:for(;l<14;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}if(n.nlen=257+(31&d),d>>>=5,l-=5,n.ndist=1+(31&d),d>>>=5,l-=5,n.ncode=4+(15&d),d>>>=4,l-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=yn;break}n.have=0,n.mode=16197;case 16197:for(;n.have<n.ncode;){for(;l<3;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}n.lens[se[n.have++]]=7&d,d>>>=3,l-=3}for(;n.have<19;)n.lens[se[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,X={bits:n.lenbits},N=mu(0,n.lens,0,19,n.lencode,0,n.work,X),n.lenbits=X.bits,N){e.msg="invalid code lengths set",n.mode=yn;break}n.have=0,n.mode=16198;case 16198:for(;n.have<n.nlen+n.ndist;){for(;k=n.lencode[d&(1<<n.lenbits)-1],g=k>>>24,R=k>>>16&255,v=65535&k,!(g<=l);){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}if(v<16)d>>>=g,l-=g,n.lens[n.have++]=v;else{if(v===16){for(q=g+2;l<q;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}if(d>>>=g,l-=g,n.have===0){e.msg="invalid bit length repeat",n.mode=yn;break}y=n.lens[n.have-1],p=3+(3&d),d>>>=2,l-=2}else if(v===17){for(q=g+3;l<q;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}d>>>=g,l-=g,y=0,p=3+(7&d),d>>>=3,l-=3}
52else{for(q=g+7;l<q;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}d>>>=g,l-=g,y=0,p=11+(127&d),d>>>=7,l-=7}if(n.have+p>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=yn;break}for(;p--;)n.lens[n.have++]=y}}if(n.mode===yn)break;if(n.lens[256]===0){e.msg="invalid code -- missing end-of-block",n.mode=yn;break}if(n.lenbits=9,X={bits:n.lenbits},N=mu(1,n.lens,0,n.nlen,n.lencode,0,n.work,X),n.lenbits=X.bits,N){e.msg="invalid literal/lengths set",n.mode=yn;break}if(n.distbits=6,n.distcode=n.distdyn,X={bits:n.distbits},N=mu(2,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,X),n.distbits=X.bits,N){e.msg="invalid distances set",n.mode=yn;break}if(n.mode=S_,t===E_)break e;case S_:n.mode=T_;case T_:if(a>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,n.hold=d,n.bits=l,QJ(e,u),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,i=e.input,a=e.avail_in,d=n.hold,l=n.bits,n.mode===hs&&(n.back=-1);break}for(n.back=0;k=n.lencode[d&(1<<n.lenbits)-1],g=k>>>24,R=k>>>16&255,v=65535&k,!(g<=l);){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}if(R&&!(240&R)){for(C=g,w=R,b=v;k=n.lencode[b+((d&(1<<C+w)-1)>>C)],g=k>>>24,R=k>>>16&255,v=65535&k,!(C+g<=l);){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}d>>>=C,l-=C,n.back+=C}if(d>>>=g,l-=g,n.back+=g,n.length=v,R===0){n.mode=16205;break}if(32&R){n.back=-1,n.mode=hs;break}if(64&R){e.msg="invalid literal/length code",n.mode=yn;break}n.extra=15&R,n.mode=16201;case 16201:if(n.extra){for(q=n.extra;l<q;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}n.length+=d&(1<<n.extra)-1,d>>>=n.extra,l-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=16202;case 16202:for(;k=n.distcode[d&(1<<n.distbits)-1],g=k>>>24,R=k>>>16&255,v=65535&k,!(g<=l);){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}if(!(240&R)){for(C=g,w=R,b=v;k=n.distcode[b+((d&(1<<C+w)-1)>>C)],g=k>>>24,R=k>>>16&255,v=65535&k,!(C+g<=l);){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}d>>>=C,l-=C,n.back+=C}if(d>>>=g,l-=g,n.back+=g,64&R){e.msg="invalid distance code",n.mode=yn;break}n.offset=v,n.extra=15&R,n.mode=16203;case 16203:if(n.extra){for(q=n.extra;l<q;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}n.offset+=d&(1<<n.extra)-1,d>>>=n.extra,l-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=yn;break}n.mode=16204;case 16204:if(c===0)break e;if(p=u-c,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=yn;break}p>n.wnext?(p-=n.wnext,E=n.wsize-p):E=n.wnext-p,p>n.length&&(p=n.length),m=n.window}else m=r,E=s-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do r[s++]=m[E++];while(--p);n.length===0&&(n.mode=T_);break;case 16205:if(c===0)break e;r[s++]=n.length,c--,n.mode=T_;break;case TT:if(n.wrap){for(;l<32;){if(a===0)break e;a--,d|=i[o++]<<l,l+=8}if(u-=c,e.total_out+=u,n.total+=u,4&n.wrap&&u&&(e.adler=n.check=qn(n)?ai(n.check,r,u,s-u):au(n.check,r,u,s-u)),u=c,4&n.wrap&&(qn(n)?d:RL(d))!==n.check){e.msg="incorrect data check",n.mode=yn;break}d=0,l=0}n.mode=16207;case 16207:if(n.wrap&&qn(n)){for(;l<32;){if(a===0)break e;a--,d+=i[o++]<<l,l+=8}if(4&n.wrap&&d!==(4294967295&n.total)){e.msg="incorrect length check",n.mode=yn;break}d=0,l=0}n.mode=16208;case 16208:N=rz;break e;case yn:N=gL;break e;case 16210:return SL;default:return Jr}return e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,n.hold=d,n.bits=l,(n.wsize||u!==e.avail_out&&n.mode<yn&&(n.mode<TT||t!==fL))&&bL(e,e.output,e.next_out,u-e.avail_out),h-=e.avail_in,u-=e.avail_out,e.total_in+=h,e.total_out+=u,n.total+=u,4&n.wrap&&u&&(e.adler=n.check=qn(n)?ai(n.check,r,u,e.next_out-u):au(n.check,r,u,e.next_out-u)),e.data_type=n.bits+(n.last?64:0)+(n.mode===hs?128:0)+(n.mode===S_||n.mode===ST?256:0),(h===0&&u===0||t===fL)&&N===qa&&(N=sz),N},ps={inflateReset:AL,inflateReset2:CL,inflateResetKeep:vL,inflateInit:e=>yL(e,15),inflateInit2:yL,inflate:dz,inflateEnd:e=>{if(Za(e))return Jr;let t=e.state;return t.window&&(t.window=null),e.state=null,qa},inflateGetHeader:(e,t)=>{if(Za(e))return Jr;const n=e.state;return 2&n.wrap?(n.head=t,t.done=!1,qa):Jr},inflateSetDictionary:(e,t)=>{const n=t.length;let i,r,o;return Za(e)?Jr:(i=e.state,i.wrap!==0&&i.mode!==g_?Jr:i.mode===g_&&(r=1,r=au(r,t,n,0),r!==i.check)?gL:(o=bL(e,t,n,n),o?(i.mode=16210,SL):(i.havedict=1,qa)))},inflateInfo:"pako inflate (from Nodeca project)"},lz=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const wL=Object.prototype.toString,{Z_NO_FLUSH:uz,Z_FINISH:hz,Z_OK:Eu,Z_STREAM_END:AT,Z_NEED_DICT:CT,Z_STREAM_ERROR:pz,Z_DATA_ERROR:OL,Z_MEM_ERROR:_z}=c_;function R_(e){this.options=u_.assign({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new _L,this.strm.avail_out=0;let n=ps.inflateInit2(this.strm,t.windowBits);if(n!==Eu)throw new Error(Ya[n]);if(this.header=new lz,ps.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=_u.string2buf(t.dictionary):wL.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=ps.inflateSetDictionary(this.strm,t.dictionary),n!==Eu)))throw new Error(Ya[n])}function NL(e,t){const n=new R_(t);if(n.push(e),n.err)throw n.msg||Ya[n.err];return n.result}R_.prototype.push=function(e,t){const n=this.strm,i=this.options.chunkSize,r=this.options.dictionary;let o,s,a;if(this.ended)return!1;for(s=t===~~t?t:t===!0?hz:uz,wL.call(e)==="[object ArrayBuffer]"?n.input=new
52Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){for(n.avail_out===0&&(n.output=new Uint8Array(i),n.next_out=0,n.avail_out=i),o=ps.inflate(n,s),o===CT&&r&&(o=ps.inflateSetDictionary(n,r),o===Eu?o=ps.inflate(n,s):o===OL&&(o=CT));n.avail_in>0&&o===AT&&n.state.wrap>0&&e[n.next_in]!==0;)ps.inflateReset(n),o=ps.inflate(n,s);switch(o){case pz:case OL:case CT:case _z:return this.onEnd(o),this.ended=!0,!1}if(a=n.avail_out,n.next_out&&(n.avail_out===0||o===AT))if(this.options.to==="string"){let c=_u.utf8border(n.output,n.next_out),d=n.next_out-c,l=_u.buf2string(n.output,c);n.next_out=d,n.avail_out=i-d,d&&n.output.set(n.output.subarray(c,c+d),0),this.onData(l)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(o!==Eu||a!==0){if(o===AT)return o=ps.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(n.avail_in===0)break}}return!0},R_.prototype.onData=function(e){this.chunks.push(e)},R_.prototype.onEnd=function(e){e===Eu&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=u_.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var mz={inflate:NL,inflateRaw:function(e,t){return(t=t||{}).raw=!0,NL(e,t)}};const{deflate:Ez,deflateRaw:fz}=ZJ,{inflate:gz,inflateRaw:Sz}=mz;var DL,Tz=Ez,PL=fz,Rz=gz,yT=Sz,Dt=function(e){return e[e.CHOOSE_SERVER=11]="CHOOSE_SERVER",e[e.CLOUD_PROXY=18]="CLOUD_PROXY",e[e.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",e[e.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK",e}(Dt||{});function bd(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let r=e.charAt(i);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),n.push(r)}}return n.join("")}function LL(e){return e.replace(/[A-Z]/g,t=>"_"+t.toLowerCase())}const vz=new Set(["constructor","toString","toJSON","valueOf"]);function fu(e){return vz.has(e)?e+"$":e}var IT=Ps!==void 0?Ps:typeof window<"u"?window:typeof la<"u"?la:typeof self<"u"?self:{};function Ys(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Xs,v_,Sr=function(e){try{return!!e()}catch{return!0}},A_=!Sr(function(){var e=(function(){}).bind();return typeof e!="function"||e.hasOwnProperty("prototype")}),kL=A_,ML=Function.prototype,bT=ML.call,Az=kL&&ML.bind.bind(bT,bT),_o=kL?Az:function(e){return function(){return bT.apply(e,arguments)}},UL=_o,Cz=UL({}.toString),yz=UL("".slice),wd=function(e){return yz(Cz(e),8,-1)},Iz=Sr,bz=wd,wT=Object,wz=_o("".split),VL=Iz(function(){return!wT("z").propertyIsEnumerable(0)})?function(e){return bz(e)=="String"?wz(e,""):wT(e)}:wT,xL=function(e){return e==null},Oz=xL,Nz=TypeError,C_=function(e){if(Oz(e))throw Nz("Can't call method on "+e);return e},Dz=VL,Pz=C_,gu=function(e){return Dz(Pz(e))},y_=function(e){return e&&e.Math==Math&&e},Tr=y_(typeof Ps=="object"&&Ps)||y_(typeof window=="object"&&window)||y_(typeof self=="object"&&self)||y_(typeof IT=="object"&&IT)||function(){return this}()||IT||Function("return this")(),OT=typeof document=="object"&&document.all,I_={all:OT,IS_HTMLDDA:OT===void 0&&OT!==void 0},Lz=I_.all,mo=I_.IS_HTMLDDA?function(e){return typeof e=="function"||e===Lz}:function(e){return typeof e=="function"},kz=mo,FL=Tr.WeakMap,Mz=kz(FL)&&/native code/.test(String(FL)),BL=mo,Uz=I_.all,Qa=I_.IS_HTMLDDA?function(e){return typeof e=="object"?e!==null:BL(e)||e===Uz}:function(e){return typeof e=="object"?e!==null:BL(e)},$a=!Sr(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Od={},GL=Qa,NT=Tr.document,Vz=GL(NT)&&GL(NT.createElement),jL=function(e){return Vz?NT.createElement(e):{}},xz=jL,WL=!$a&&!Sr(function(){return Object.defineProperty(xz("div"),"a",{get:function(){return 7}}).a!=7}),KL=$a&&Sr(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Fz=Qa,Bz=String,Gz=TypeError,DT=function(e){if(Fz(e))return e;throw Gz(Bz(e)+" is not an object")},jz=A_,b_=Function.prototype.call,w_=jz?b_.bind(b_):function(){return b_.apply(b_,arguments)},PT={},LT=PT,kT=Tr,Wz=mo,HL=function(e){return Wz(e)?e:void 0},YL=function(e,t){return arguments.length<2?HL(LT[e])||HL(kT[e]):LT[e]&<[e][t]||kT[e]&&kT[e][t]},Js=_o({}.isPrototypeOf),O_=typeof navigator<"u"&&String(navigator.userAgent)||"",XL=Tr,MT=O_,JL=XL.process,zL=XL.Deno,qL=JL&&JL.versions||zL&&zL.version,ZL=qL&&qL.v8;ZL&&(v_=(Xs=ZL.split("."))[0]>0&&Xs[0]<4?1:+(Xs[0]+Xs[1])),!v_&&MT&&(!(Xs=MT.match(/Edge\/(\d+)/))||Xs[1]>
52=74)&&(Xs=MT.match(/Chrome\/(\d+)/))&&(v_=+Xs[1]);var N_=v_,QL=N_,Kz=Sr,Hz=Tr.String,$L=!!Object.getOwnPropertySymbols&&!Kz(function(){var e=Symbol();return!Hz(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&QL&&QL<41}),ek=$L&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Yz=YL,Xz=mo,Jz=Js,zz=Object,tk=ek?function(e){return typeof e=="symbol"}:function(e){var t=Yz("Symbol");return Xz(t)&&Jz(t.prototype,zz(e))},qz=String,nk=function(e){try{return qz(e)}catch{return"Object"}},Zz=mo,Qz=nk,$z=TypeError,D_=function(e){if(Zz(e))return e;throw $z(Qz(e)+" is not a function")},eq=D_,tq=xL,ik=w_,rk=mo,ok=Qa,nq=TypeError,sk={exports:{}},ak=Tr,iq=Object.defineProperty,ck="__core-js_shared__",dk=Tr[ck]||function(e,t){try{iq(ak,e,{value:t,configurable:!0,writable:!0})}catch{ak[e]=t}return t}(ck,{}),lk=dk;(sk.exports=function(e,t){return lk[e]||(lk[e]=t!==void 0?t:{})})("versions",[]).push({version:"3.31.1",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.1/LICENSE",source:"https://github.com/zloirock/core-js"});var uk=sk.exports,rq=C_,oq=Object,P_=function(e){return oq(rq(e))},sq=P_,aq=_o({}.hasOwnProperty),jo=Object.hasOwn||function(e,t){return aq(sq(e),t)},cq=_o,dq=0,lq=Math.random(),uq=cq(1 .toString),hk=function(e){return"Symbol("+(e===void 0?"":e)+")_"+uq(++dq+lq,36)},hq=uk,pk=jo,pq=hk,_q=$L,mq=ek,Nd=Tr.Symbol,UT=hq("wks"),Eq=mq?Nd.for||Nd:Nd&&Nd.withoutSetter||pq,_s=function(e){return pk(UT,e)||(UT[e]=_q&&pk(Nd,e)?Nd[e]:Eq("Symbol."+e)),UT[e]},fq=w_,_k=Qa,mk=tk,gq=TypeError,Sq=_s("toPrimitive"),Tq=function(e,t){if(!_k(e)||mk(e))return e;var n,i=function(r,o){var s=r[o];return tq(s)?void 0:eq(s)}(e,Sq);if(i){if(n=fq(i,e,t),!_k(n)||mk(n))return n;throw gq("Can't convert object to primitive value")}return function(r,o){var s,a;if(rk(s=r.toString)&&!ok(a=ik(s,r))||rk(s=r.valueOf)&&!ok(a=ik(s,r)))return a;throw nq("Can't convert object to primitive value")}(e)},Rq=tk,VT=function(e){var t=Tq(e,"string");return Rq(t)?t:t+""},vq=$a,Aq=WL,Cq=KL,L_=DT,Ek=VT,yq=TypeError,xT=Object.defineProperty,Iq=Object.getOwnPropertyDescriptor,FT="enumerable",BT="configurable",GT="writable";Od.f=vq?Cq?function(e,t,n){if(L_(e),t=Ek(t),L_(n),typeof e=="function"&&t==="prototype"&&"value"in n&> in n&&!n[GT]){var i=Iq(e,t);i&&i[GT]&&(e[t]=n.value,n={configurable:BT in n?n[BT]:i[BT],enumerable:FT in n?n[FT]:i[FT],writable:!1})}return xT(e,t,n)}:xT:function(e,t,n){if(L_(e),t=Ek(t),L_(n),Aq)try{return xT(e,t,n)}catch{}if("get"in n||"set"in n)throw yq("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var k_,Su,M_,U_=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},bq=Od,wq=U_,Tu=$a?function(e,t,n){return bq.f(e,t,wq(1,n))}:function(e,t,n){return e[t]=n,e},Oq=hk,fk=uk("keys"),jT=function(e){return fk[e]||(fk[e]=Oq(e))},WT={},Nq=Mz,gk=Tr,Dq=Qa,Pq=Tu,KT=jo,HT=dk,Lq=jT,kq=WT,Sk="Object already initialized",YT=gk.TypeError,Mq=gk.WeakMap;if(Nq||HT.state){var Wo=HT.state||(HT.state=new Mq);Wo.get=Wo.get,Wo.has=Wo.has,Wo.set=Wo.set,k_=function(e,t){if(Wo.has(e))throw YT(Sk);return t.facade=e,Wo.set(e,t),t},Su=function(e){return Wo.get(e)||{}},M_=function(e){return Wo.has(e)}}else{var Dd=Lq("state");kq[Dd]=!0,k_=function(e,t){if(KT(e,Dd))throw YT(Sk);return t.facade=e,Pq(e,Dd,t),t},Su=function(e){return KT(e,Dd)?e[Dd]:{}},M_=function(e){return KT(e,Dd)}}var Uq={set:k_,get:Su,has:M_,enforce:function(e){return M_(e)?Su(e):k_(e,{})},getterFor:function(e){return function(t){var n;if(!Dq(t)||(n=Su(t)).type!==e)throw YT("Incompatible receiver, "+e+" required");return n}}},Vq=A_,Tk=Function.prototype,Rk=Tk.apply,vk=Tk.call,xq=typeof Reflect=="object"&&Reflect.apply||(Vq?vk.bind(Rk):function(){return vk.apply(Rk,arguments)}),Fq=wd,Bq=_o,XT=function(e){if(Fq(e)==="Function")return Bq(e)},Ak={},Ck={},yk={}.propertyIsEnumerable,Ik=Object.getOwnPropertyDescriptor,Gq=Ik&&!yk.call({1:2},1);Ck.f=Gq?function(e){var t=Ik(this,e);return!!t&&t.enumerable}:yk;var jq=$a,Wq=w_,Kq=Ck,Hq=U_,Yq=gu,Xq=VT,Jq=jo,zq=WL,bk=Object.getOwnPropertyDescriptor;Ak.f=jq?bk:function(e,t){if(e=Yq(e),t=Xq(t),zq)try{return bk(e,t)}catch{}if(Jq(e,t))return Hq(!Wq(Kq.f,e,t),e[t])};var qq=Sr,Zq=mo,Qq=/#|\.prototype\./,Ru=function(e,t){var n=eZ[$q(e)];return n==nZ||n!=tZ&&(Zq(t)?qq(t):!!t)},$q=Ru.normalize=function(e){return String(e).replace(Qq,".").toLowerCase()},eZ=Ru.data={},tZ=Ru.NATIVE="N",nZ=Ru.POLYFILL="P",iZ=Ru,rZ=D_,oZ=A_,sZ=XT(XT.bind),V_=Tr,aZ=xq,cZ=XT,dZ=mo,lZ=Ak.f,uZ=iZ,Pd=PT,hZ=function(e,t){return rZ(e),t===void 0?e:oZ?sZ(e,t):function(){return e.apply(t,arguments)}},Ld=Tu,wk=jo,pZ=function(e){var t=function(n,i,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(n);case 2:return new e(n,i)}return new e(n,i,r)}return aZ(e,this,arguments)};return t.prototype=e.prototype,t},zs=function(e,t){var n,i,r,o,s,a,c,d,l,h=e.target,u=e.global,p=e.stat,E=e.proto,m=u?V_:p?V_[h]:(V_[h]||{}).prototype,g=u?Pd:Pd[h]||Ld(Pd,h,{})[h],R=g.prototype;for(o in t)i=!(n=uZ(u?o:h+(p?".":"#")+o,e.forced))&&m&&wk(m,o),a=g[o],i&&(c=e.dontCallGetSet?(l=lZ(m,o))&&l.value:m[o]),s=i&&c?c:t[o],i&&typeof a==typeof s||(d=e.bind&&i?hZ(s,V_):e.wrap&&i?pZ(s):E&&dZ(s)?cZ(s):s,(e.sham||s&&s.sham||a&&a.sham)&&Ld(d,"sham",!0),Ld(g,o,d),E&&(wk(Pd,r=h+"Prototype")||Ld(Pd,r,{}),Ld(Pd[r],o,s),e.real&&R&&(n||!R[o])&&Ld(R,o,s)))},JT=$a,_Z=jo,Ok=Function.prototype,mZ=JT&&Object.getOwnPropertyDescriptor,Nk=_Z(Ok,"name"),Dk={PROPER:Nk&&(function(){}).name==="something",CONFIGURABLE:Nk&&(!JT||JT&&mZ(Ok,"name").configurable)},Pk={},EZ=Math.ceil,fZ=Math.floor,gZ=Math.trunc||function(e){var t=+e;return(t>0?fZ:EZ)(t)},Lk=function(e){var t=+e;return t!=t||t===0?0:gZ(t)},SZ=Lk,TZ=Math.max,RZ=Math.min,kk=function(e,t){var n=SZ(e);return n<0?TZ(n+t,0):RZ(n,t)},vZ=Lk,AZ=Math.min,x_=function(e){return function(t){return t>0?AZ(vZ(t),9007199254740991):0}(e.length)},CZ=gu,yZ=kk,IZ=x_,Mk=function(e){return function(t,n,i){var r,o=CZ(t),s=IZ(o),a=yZ(i,s);if(e&&n!=n){for(;s>a;)if((r=o[a++])!=r)return!0}else for(;s>a;a++)if((e||a in o)&&o[a]===n)return e||a||0;return!e&&-1}},Uk={includes:Mk(!0),indexOf:Mk(!1)},zT=jo,bZ=gu,wZ=Uk.indexOf,OZ=WT,Vk=_o([].push),xk=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleStr
52ing","toString","valueOf"],NZ=xk,DZ=Object.keys||function(e){return function(t,n){var i,r=bZ(t),o=0,s=[];for(i in r)!zT(OZ,i)&&zT(r,i)&&Vk(s,i);for(;n.length>o;)zT(r,i=n[o++])&&(~wZ(s,i)||Vk(s,i));return s}(e,NZ)},PZ=$a,LZ=KL,kZ=Od,MZ=DT,UZ=gu,VZ=DZ;Pk.f=PZ&&!LZ?Object.defineProperties:function(e,t){MZ(e);for(var n,i=UZ(t),r=VZ(t),o=r.length,s=0;o>s;)kZ.f(e,n=r[s++],i[n]);return e};var F_,xZ=YL("document","documentElement"),FZ=DT,BZ=Pk,Fk=xk,GZ=WT,jZ=xZ,WZ=jL,qT="prototype",ZT="script",Bk=jT("IE_PROTO"),QT=function(){},Gk=function(e){return"<"+ZT+">"+e+"</"+ZT+">"},jk=function(e){e.write(Gk("")),e.close();var t=e.parentWindow.Object;return e=null,t},B_=function(){try{F_=new ActiveXObject("htmlfile")}catch{}var e,t,n;B_=typeof document<"u"?document.domain&&F_?jk(F_):(t=WZ("iframe"),n="java"+ZT+":",t.style.display="none",jZ.appendChild(t),t.src=String(n),(e=t.contentWindow.document).open(),e.write(Gk("document.F=Object")),e.close(),e.F):jk(F_);for(var i=Fk.length;i--;)delete B_[qT][Fk[i]];return B_()};GZ[Bk]=!0;var ec,Wk,Kk,Hk=Object.create||function(e,t){var n;return e!==null?(QT[qT]=FZ(e),n=new QT,QT[qT]=null,n[Bk]=e):n=B_(),t===void 0?n:BZ.f(n,t)},KZ=!Sr(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),HZ=jo,YZ=mo,XZ=P_,JZ=KZ,Yk=jT("IE_PROTO"),$T=Object,zZ=$T.prototype,Xk=JZ?$T.getPrototypeOf:function(e){var t=XZ(e);if(HZ(t,Yk))return t[Yk];var n=t.constructor;return YZ(n)&&t instanceof n?n.prototype:t instanceof $T?zZ:null},qZ=Tu,ZZ=function(e,t,n,i){return i&&i.enumerable?e[t]=n:qZ(e,t,n),e},QZ=Sr,$Z=mo,e7=Qa,t7=Hk,Jk=Xk,n7=ZZ,eR=_s("iterator"),zk=!1;_n([])&&("next"in(Kk=_n(DL=[]).call(DL))?(Wk=Jk(Jk(Kk)))!==Object.prototype&&(ec=Wk):zk=!0);var i7=!e7(ec)||QZ(function(){var e={};return ec[eR].call(e)!==e});$Z((ec=i7?{}:t7(ec))[eR])||n7(ec,eR,function(){return this});var qk={IteratorPrototype:ec,BUGGY_SAFARI_ITERATORS:zk},Zk={};Zk[_s("toStringTag")]="z";var tR=String(Zk)==="[object z]",r7=tR,o7=mo,G_=wd,s7=_s("toStringTag"),a7=Object,c7=G_(function(){return arguments}())=="Arguments",vu=r7?G_:function(e){var t,n,i;return e===void 0?"Undefined":e===null?"Null":typeof(n=function(r,o){try{return r[o]}catch{}}(t=a7(e),s7))=="string"?n:c7?G_(t):(i=G_(t))=="Object"&&o7(t.callee)?"Arguments":i},d7=vu,l7=tR?{}.toString:function(){return"[object "+d7(this)+"]"},u7=tR,h7=Od.f,p7=Tu,_7=jo,m7=l7,Qk=_s("toStringTag"),$k=function(e,t,n,i){if(e){var r=n?e:e.prototype;_7(r,Qk)||h7(r,Qk,{configurable:!0,value:t}),i&&!u7&&p7(r,"toString",m7)}},E7=qk.IteratorPrototype,f7=Hk,g7=U_,S7=$k,T7=zs,R7=w_,v7=Xk,A7=$k,C7=Dk.PROPER,nR=qk.BUGGY_SAFARI_ITERATORS,y7=_s("iterator"),e1="keys",j_="values",t1="entries",Cie=function(){return this},I7=gu,n1=Uq;Od.f;var i1=function(e,t){return{value:e,done:t}},r1="Array Iterator",b7=n1.set,w7=n1.getterFor(r1);(function(e,t,n,i,r,o,s){(function(g,R,v,C){var w=R+" Iterator";g.prototype=f7(E7,{next:g7(1,v)}),S7(g,w,!1,!0)})(n,t,i);var a,c,d=function(g){if(g===r&&E)return E;if(!nR&&g in u)return u[g];switch(g){case e1:case j_:case t1:return function(){return new n(this,g)}}return function(){return new n(this)}},l=t+" Iterator",h=!1,u=e.prototype,p=u[y7]||u["@@iterator"]||u[r],E=!nR&&p||d(r),m=u.entries||p;m&&(a=v7(m.call(new e)))!==Object.prototype&&a.next&&A7(a,l,!0,!0),C7&&r==j_&&p&&p.name!==j_&&(h=!0,E=function(){return R7(p,this)}),r&&(c={values:d(j_),keys:d(e1),entries:d(t1)},s||T7({target:t,proto:!0,forced:nR||h},c))})(Array,"Array",function(e,t){b7(this,{type:r1,target:I7(e),index:0,kind:t})},function(){var e=w7(this),t=e.target,n=e.kind,i=e.index++;return!t||i>=t.length?(e.target=void 0,i1(void 0,!0)):i1(n=="keys"?i:n=="values"?t[i]:[i,t[i]],!1)},"values");var O7=Tr,N7=vu,D7=Tu,o1=_s("toStringTag");for(var s1 in{CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}){var a1=O7[s1],iR=a1&&a1.prototype;iR&&N7(iR)!==o1&&D7(iR,o1,s1)}var P7=PT,qs=function(e){return P7[e+"Prototype"]},L7=ti(qs("Array")),k7=vu,M7=jo,U7=Js,V7=L7,rR=Array.prototype,x7={DOMTokenList:!0,NodeList:!0},Zn=Ys(function(e){var t=ti(e);return e===rR||U7(rR,e)&&t===ti(rR)||M7(x7,k7(e))?V7:t}),oR=Tr;zs({global:!0,forced:oR.globalThis!==oR},{globalThis:oR});var kd=Ys(Tr);function F7(){let e=0,t=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(e|=(127&r)<<i,(128&r)==0)return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,(128&n)==0)return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(t|=(127&r)<<i,(128&r)==0)return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function sR(e,t,n){for(let o=0;o<28;o+=7){const s=e>>>o,a=!(!(s>>>7)&&t==0),c=255&(a?128|s:s);if(n.push(c),!a)return}const i=e>>>28&15|(7&t)<<4,r=!!(t>>3);
52if(n.push(255&(r?128|i:i)),r){for(let o=3;o<31;o+=7){const s=t>>>o,a=!!(s>>>7),c=255&(a?128|s:s);if(n.push(c),!a)return}n.push(t>>>31&1)}}const W_=4294967296;function c1(e){const t=e[0]==="-";t&&(e=e.slice(1));const n=1e6;let i=0,r=0;function o(s,a){const c=Number(e.slice(s,a));r*=n,i=i*n+c,i>=W_&&(r+=i/W_|0,i%=W_)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?l1(i,r):aR(i,r)}function d1(e,t){if({lo:e,hi:t}=function(c,d){return{lo:c>>>0,hi:d>>>0}}(e,t),t<=2097151)return String(W_*t+e);const n=16777215&(e>>>24|t<<8),i=t>>16&65535;let r=(16777215&e)+6777216*n+6710656*i,o=n+8147497*i,s=2*i;const a=1e7;return r>=a&&(o+=Math.floor(r/a),r%=a),o>=a&&(s+=Math.floor(o/a),o%=a),s.toString()+u1(o)+u1(r)}function aR(e,t){return{lo:0|e,hi:0|t}}function l1(e,t){return t=~t,e?e=1+~e:t+=1,aR(e,t)}const u1=e=>{const t=String(e);return"0000000".slice(t.length)+t};function cR(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function B7(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,(128&e)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,(128&e)==0)return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,(128&e)==0)return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let n=5;128&e&&n<10;n++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}const In=function(){const e=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof e.getBigInt64=="function"&&typeof e.getBigUint64=="function"&&typeof e.setBigInt64=="function"&&typeof e.setBigUint64=="function"&&(kd.Deno||typeof process!="object"||typeof dt!="object"||dt.BUF_BIGINT_DISABLE!=="1")){const t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),i=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(o){const s=typeof o=="bigint"?o:BigInt(o);if(s>n||s<t)throw new Error("invalid int64: ".concat(o));return s},uParse(o){const s=typeof o=="bigint"?o:BigInt(o);if(s>r||s<i)throw new Error("invalid uint64: ".concat(o));return s},enc(o){return e.setBigInt64(0,this.parse(o),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(o){return e.setBigInt64(0,this.uParse(o),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(o,s)=>(e.setInt32(0,o,!0),e.setInt32(4,s,!0),e.getBigInt64(0,!0)),uDec:(o,s)=>(e.setInt32(0,o,!0),e.setInt32(4,s,!0),e.getBigUint64(0,!0))}}return{zero:"0",supported:!1,parse:t=>(typeof t!="string"&&(t=t.toString()),h1(t),t),uParse:t=>(typeof t!="string"&&(t=t.toString()),p1(t),t),enc:t=>(typeof t!="string"&&(t=t.toString()),h1(t),c1(t)),uEnc:t=>(typeof t!="string"&&(t=t.toString()),p1(t),c1(t)),dec:(t,n)=>function(i,r){let o=aR(i,r);const s=2147483648&o.hi;s&&(o=l1(o.lo,o.hi));const a=d1(o.lo,o.hi);return s?"-"+a:a}(t,n),uDec:(t,n)=>d1(t,n)}}();function h1(e){if(!/^-?[0-9]+$/.test(e))throw new Error("invalid int64: "+e)}function p1(e){if(!/^[0-9]+$/.test(e))throw new Error("invalid uint64: "+e)}var W;function Md(e,t){switch(e){case W.STRING:return"";case W.BOOL:return!1;case W.DOUBLE:case W.FLOAT:return 0;case W.INT64:case W.UINT64:case W.SFIXED64:case W.FIXED64:case W.SINT64:return t?"0":In.zero;case W.BYTES:return new Uint8Array(0);default:return 0}}(function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"})(W||(W={}));const _1=2,ms=Symbol.for("reflect unsafe local");function m1(e,t){const n=e[t.localName].case;return n===void 0?n:t.fields.find(i=>i.localName===n)}function Au(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==void 0}function E1(e,t){if(t.oneof){const n=e[t.oneof.localName];return n.case===t.localName?n.value:void 0}return e[t.localName]}function f1(e,t,n){t.oneof?e[t.oneof.localName]={case:t.localName,value:n}:e[t.localName]=n}function dR(e){for(const t of e.field)Au(t,"jsonName")||(t.jsonName=bd(t.name));e.nestedType.forEach(dR)}var G7=wd,j7=zs,W7=Array.isArray||function(e){return G7(e)=="Array"},K7=_o(_a([])),lR=[1,2];j7({target:"Array",proto:!0,forced:String(lR)===String(_a(lR).call(lR))},{reverse:function(){return W7(this)&&(this.length=this.length),K7(this)}});var H7=_a(qs("Array")),Y7=Js,X7=H7,uR=Array.prototype,J7=Ys(function(e){var t=_a(e);return e===uR||Y7(uR,e)&&t===_a(uR)?X7:t});function*hR(e){switch(e.kind){case"file":for(const t of e.messages)yield t,yield*hR(t);yield*e.enums,yield*e.services,yield*e.extensions;break;case"message":for(const t of e.nestedMessages)yield t,yield*hR(t);yield*e.nestedEnums,yield*e.nestedExtensions}}function g1(){const e=function(){const o=new Map,s=new Map,a=new Map;return{kind:"registry",types:o,extendees:s,[Symbol.iterator]:()=>Zn(o).call(o),get files(){return Zn(a).call(a)},addFile(c,d,l){if(a.set(c.proto.name,c),!d)for(const h of hR(c))this.add(h);if(l)for(const h of c.dependencies)this.addFile(h,d,l)},add(c){if(c.kind=="extension"){let d=s.get(c.extendee.typeName);d||s.set(c.extendee.typeName,d=new Map),d.set(c.number,c)}o.set(c.typeName,c)},get:c=>o.get(c),getFile:c=>a.get(c),getMessage(c){const d=o.get(c);return(d==null?void 0:d.kind)=="message"?d:void 0},getEnum(c){const d=o.get(c);return(d==null?void 0:d.kind)=="enum"?d:void 0},getExtension(c){const d=o.get(c);return(d==null?void 0:d.kind)=="extension"?d:void 0},getExtensionFor(c,d){var l;return(l=s.get(c.typeName))===null||l===void 0?void 0:l.get(d)},getService(c){const d=o.get(c);return(d==null?void 0:d.kind)=="service"?d:void 0}}}();for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];if(!n.length)return e;if("$typeName"in n[0]&&n[0].$typeName=="google.protobuf.FileDescriptorSet"){for(const o of n[0].file)C1(o,e);return e}if("$typeName"in n[0]){const o=n[0],s=n[1],a=new Set;for(const c of J7(r=[o,...function d(l){const h=[];for(const u of l.dependency){if(e.getFile(u)!=null||a.has(u))continue;const p=s(u);if(!p)throw new Error("Unable to resolve ".concat(u,", imported by ").concat(l.name));"kind"in p?e.addFile(p,!1,!0):(a.add(p.name),h.push(p))}return h.concat(...h.map(d))}(o)]).call(r)){var r;C1(c,e)}}else for(const o of n)for(const s of o.files)e.addFile(s);return e}const z7=998,q7=999,Z7=9,Cu=10,yu=11,Q7=12,S1=14,pR=3,$7=2,T1=1,eQ=0,R1=1,v1=2,tQ=3,nQ=1,iQ=2,rQ=1,A1={998:{fieldPresence:1,enumType:2,repeatedFieldEncoding:2,utf8Validation:3,messageEncoding:1,jsonFormat:2,enforceNamingStyle:2,defaultSymbolVisibility:1},999:{fieldPresence:2,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:2,defaultSymbolVisibility:1},1e3:{fieldPresence:1,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:2,defaultSymbolVisibility:1},1001:{fieldPresence:1,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:1,defaultSymbolVisibility:2}};function C1(e,t){var n,i;const r={kind:"file",proto:e,deprecated:(i=(n=e.options)===null||n===void 0?void 0:n.deprecated)!==null&&i!==void 0&&i,edition:aQ(e),name:e.name.replace(/\.proto$/,""),dependencies:cQ(e,t),enums:[],messages:[],extensions:[],services:[],toString:()=>"file ".concat(e.name)}
52,o=new Map,s={get:a=>o.get(a),add(a){var c;Eo(((c=a.proto.options)===null||c===void 0?void 0:c.mapEntry)===!0),o.set(a.typeName,a)}};for(const a of e.enumType)y1(a,r,void 0,t);for(const a of e.messageType)I1(a,r,void 0,t,s);for(const a of e.service)oQ(a,r,t);_R(r,t);for(const a of Zn(o).call(o))mR(a,t,s);for(const a of r.messages)mR(a,t,s),_R(a,t);t.addFile(r,!0)}function _R(e,t){switch(e.kind){case"file":for(const n of e.proto.extension){const i=ER(n,e,t);e.extensions.push(i),t.add(i)}break;case"message":for(const n of e.proto.extension){const i=ER(n,e,t);e.nestedExtensions.push(i),t.add(i)}for(const n of e.nestedMessages)_R(n,t)}}function mR(e,t,n){const i=e.proto.oneofDecl.map(o=>function(s,a){return{kind:"oneof",proto:s,deprecated:!1,parent:a,fields:[],name:s.name,localName:fu(bd(s.name)),toString(){return"oneof ".concat(a.typeName,".").concat(this.name)}}}(o,e)),r=new Set;for(const o of e.proto.field){const s=dQ(o,i),a=ER(o,e,t,s,n);e.fields.push(a),e.field[a.localName]=a,s===void 0?e.members.push(a):(s.fields.push(a),r.has(s)||(r.add(s),e.members.push(s)))}for(const o of i.filter(s=>r.has(s)))e.oneofs.push(o);for(const o of e.nestedMessages)mR(o,t,n)}function y1(e,t,n,i){var r,o,s,a,c;const d=function(h,u){const p=((E=h).substring(0,1)+E.substring(1).replace(/[A-Z]/g,m=>"_"+m)).toLowerCase()+"_";var E;for(const m of u){if(!m.name.toLowerCase().startsWith(p))return;const g=m.name.substring(p.length);if(g.length==0||/^\d/.test(g))return}return p}(e.name,e.value),l={kind:"enum",proto:e,deprecated:(o=(r=e.options)===null||r===void 0?void 0:r.deprecated)!==null&&o!==void 0&&o,file:t,parent:n,open:!0,name:e.name,typeName:K_(e,n,t),value:{},values:[],sharedPrefix:d,toString(){return"enum ".concat(this.typeName)}};l.open=function(h){var u;return rQ==Ud("enumType",{proto:h.proto,parent:(u=h.parent)!==null&&u!==void 0?u:h.file})}(l),i.add(l);for(const h of e.value){const u=h.name;Zn(l).push(l.value[h.number]={kind:"enum_value",proto:h,deprecated:(a=(s=h.options)===null||s===void 0?void 0:s.deprecated)!==null&&a!==void 0&&a,parent:l,name:u,localName:fu(d==null?u:u.substring(d.length)),number:h.number,toString:()=>"enum value ".concat(l.typeName,".").concat(u)})}((c=n==null?void 0:n.nestedEnums)!==null&&c!==void 0?c:t.enums).push(l)}function I1(e,t,n,i,r){var o,s,a,c;const d={kind:"message",proto:e,deprecated:(s=(o=e.options)===null||o===void 0?void 0:o.deprecated)!==null&&s!==void 0&&s,file:t,parent:n,name:e.name,typeName:K_(e,n,t),fields:[],field:{},oneofs:[],members:[],nestedEnums:[],nestedMessages:[],nestedExtensions:[],toString(){return"message ".concat(this.typeName)}};((a=e.options)===null||a===void 0?void 0:a.mapEntry)===!0?r.add(d):(((c=n==null?void 0:n.nestedMessages)!==null&&c!==void 0?c:t.messages).push(d),i.add(d));for(const l of e.enumType)y1(l,t,d,i);for(const l of e.nestedType)I1(l,t,d,i,r)}function oQ(e,t,n){var i,r;const o={kind:"service",proto:e,deprecated:(r=(i=e.options)===null||i===void 0?void 0:i.deprecated)!==null&&r!==void 0&&r,file:t,name:e.name,typeName:K_(e,void 0,t),methods:[],method:{},toString(){return"service ".concat(this.typeName)}};t.services.push(o),n.add(o);for(const s of e.method){const a=sQ(s,o,n);o.methods.push(a),o.method[a.localName]=a}}function sQ(e,t,n){var i,r,o,s;let a;a=e.clientStreaming&&e.serverStreaming?"bidi_streaming":e.clientStreaming?"client_streaming":e.serverStreaming?"server_streaming":"unary";const c=n.getMessage(Es(e.inputType)),d=n.getMessage(Es(e.outputType));Eo(c,"invalid MethodDescriptorProto: input_type ".concat(e.inputType," not found")),Eo(d,"invalid MethodDescriptorProto: output_type ".concat(e.inputType," not found"));const l=e.name;return{kind:"rpc",proto:e,deprecated:(r=(i=e.options)===null||i===void 0?void 0:i.deprecated)!==null&&r!==void 0&&r,parent:t,name:l,localName:fu(l.length?fu(l[0].toLowerCase()+l.substring(1)):l),methodKind:a,input:c,output:d,idempotency:(s=(o=e.options)===null||o===void 0?void 0:o.idempotencyLevel)!==null&&s!==void 0?s:eQ,toString:()=>"rpc ".concat(t.typeName,".").concat(l)}}function ER(e,t,n,i,r){var o,s,a;const c=r===void 0,d={kind:"field",proto:e,deprecated:(s=(o=e.options)===null||o===void 0?void 0:o.deprecated)!==null&&s!==void 0&&s,name:e.name,number:e.number,scalar:void 0,message:void 0,enum:void 0,presence:lQ(e,i,c,t),listKind:void 0,mapKind:void 0,mapKey:void 0,delimitedEncoding:void 0,packed:void 0,longAsString:!1,getDefaultValue:void 0};if(c){const p=t.kind=="file"?t:t.file,E=t.kind=="file"?void 0:t,m=K_(e,E,p);d.kind="extension",d.file=p,d.parent=E,d.oneof=void 0,d.typeName=m,d.jsonName="[".concat(m,"]"),d.toString=()=>"extension ".concat(m);const g=n.getMessage(Es(e.extendee));
52Eo(g,"invalid FieldDescriptorProto: extendee ".concat(e.extendee," not found")),d.extendee=g}else{const p=t;Eo(p.kind=="message"),d.parent=p,d.oneof=i,d.localName=i?bd(e.name):fu(bd(e.name)),d.jsonName=e.jsonName,d.toString=()=>"field ".concat(p.typeName,".").concat(e.name)}const l=e.label,h=e.type,u=(a=e.options)===null||a===void 0?void 0:a.jstype;if(l===pR){const p=h==yu?r==null?void 0:r.get(Es(e.typeName)):void 0;if(p){d.fieldKind="map";const{key:E,value:m}=function(g){const R=g.fields.find(C=>C.number===1),v=g.fields.find(C=>C.number===2);return Eo(R&&R.fieldKind=="scalar"&&R.scalar!=W.BYTES&&R.scalar!=W.FLOAT&&R.scalar!=W.DOUBLE&&v&&v.fieldKind!="list"&&v.fieldKind!="map"),{key:R,value:v}}(p);return d.mapKey=E.scalar,d.mapKind=m.fieldKind,d.message=m.message,d.delimitedEncoding=!1,d.enum=m.enum,d.scalar=m.scalar,d}switch(d.fieldKind="list",h){case yu:case Cu:d.listKind="message",d.message=n.getMessage(Es(e.typeName)),Eo(d.message),d.delimitedEncoding=b1(e,t);break;case S1:d.listKind="enum",d.enum=n.getEnum(Es(e.typeName)),Eo(d.enum);break;default:d.listKind="scalar",d.scalar=h,d.longAsString=u==T1}return d.packed=function(E,m){if(E.label!=pR)return!1;switch(E.type){case Z7:case Q7:case Cu:case yu:return!1}const g=E.options;return g&&Au(g,"packed")?g.packed:nQ==Ud("repeatedFieldEncoding",{proto:E,parent:m})}(e,t),d}switch(h){case yu:case Cu:d.fieldKind="message",d.message=n.getMessage(Es(e.typeName)),Eo(d.message,"invalid FieldDescriptorProto: type_name ".concat(e.typeName," not found")),d.delimitedEncoding=b1(e,t),d.getDefaultValue=()=>{};break;case S1:{const p=n.getEnum(Es(e.typeName));Eo(p!==void 0,"invalid FieldDescriptorProto: type_name ".concat(e.typeName," not found")),d.fieldKind="enum",d.enum=n.getEnum(Es(e.typeName)),d.getDefaultValue=()=>Au(e,"defaultValue")?function(E,m){const g=Zn(E).find(R=>R.name===m);if(!g)throw new Error("cannot parse ".concat(E," default value: ").concat(m));return g.number}(p,e.defaultValue):void 0;break}default:d.fieldKind="scalar",d.scalar=h,d.longAsString=u==T1,d.getDefaultValue=()=>Au(e,"defaultValue")?function(p,E){switch(p){case W.STRING:return E;case W.BYTES:{const m=function(g){const R=[],v={tail:g,c:"",next(){return this.tail.length!=0&&(this.c=this.tail[0],this.tail=this.tail.substring(1),!0)},take(C){if(this.tail.length>=C){const w=this.tail.substring(0,C);return this.tail=this.tail.substring(C),w}return!1}};for(;v.next();)if(v.c==="\\"){if(v.next())switch(v.c){case"\\":R.push(v.c.charCodeAt(0));break;case"b":R.push(8);break;case"f":R.push(12);break;case"n":R.push(10);break;case"r":R.push(13);break;case"t":R.push(9);break;case"v":R.push(11);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{const C=v.c,w=v.take(2);if(w===!1)return!1;const b=parseInt(C+w,8);if(Number.isNaN(b))return!1;R.push(b);break}case"x":{const C=v.c,w=v.take(2);if(w===!1)return!1;const b=parseInt(C+w,16);if(Number.isNaN(b))return!1;R.push(b);break}case"u":{const C=v.c,w=v.take(4);if(w===!1)return!1;const b=parseInt(C+w,16);if(Number.isNaN(b))return!1;const y=new Uint8Array(4);new DataView(y.buffer).setInt32(0,b,!0),R.push(y[0],y[1],y[2],y[3]);break}case"U":{const C=v.c,w=v.take(8);if(w===!1)return!1;const b=In.uEnc(C+w),y=new Uint8Array(8),N=new DataView(y.buffer);N.setInt32(0,b.lo,!0),N.setInt32(4,b.hi,!0),R.push(y[0],y[1],y[2],y[3],y[4],y[5],y[6],y[7]);break}}}else R.push(v.c.charCodeAt(0));return new Uint8Array(R)}(E);if(m===!1)throw new Error("cannot parse ".concat(W[p]," default value: ").concat(E));return m}case W.INT64:case W.SFIXED64:case W.SINT64:return In.parse(E);case W.UINT64:case W.FIXED64:return In.uParse(E);case W.DOUBLE:case W.FLOAT:switch(E){case"inf":return Number.POSITIVE_INFINITY;case"-inf":return Number.NEGATIVE_INFINITY;case"nan":return Number.NaN;default:return parseFloat(E)}case W.BOOL:return E==="true";case W.INT32:case W.UINT32:case W.SINT32:case W.FIXED32:case W.SFIXED32:return parseInt(E,10)}}(h,e.defaultValue):void 0}return d}function aQ(e){switch(e.syntax){case"":case"proto2":return z7;case"proto3":return q7;case"editions":if(e.edition in A1)return e.edition;throw new Error("".concat(e.name,": unsupported edition"));default:throw new Error("".concat(e.name,': unsupported syntax "').concat(e.syntax,'"'))}}function cQ(e,t){return e.dependency.map(n=>{const i=t.getFile(n);if(!i)throw new Error("Cannot find ".concat(n,", imported by ").concat(e.name));return i})}function K_(e,t,n){let i;return i=t?"".concat(t.typeName,".").concat(e.name):n.proto.package.length>0?"".concat(n.proto.package,".").concat(e.name):"".concat(e.name),i}function Es(e){return e.startsWith(".")?e.substring(1):e}function dQ(e,t){if(!Au(e,"oneofIndex")||e.proto3Optional)return;const n=t[e.oneofIndex];return Eo(n,"invalid FieldDescriptorProto: oneof #".concat(e.oneofIndex," for field #").concat(e.number," not found")),n}function lQ(e,t,n,i){if(e.label==$7)return tQ;if(e.label==pR)return v1;if(t||e.proto3Optional||n)return R1;const r=Ud("fieldPresence",{proto:e,parent:i});return r!=v1||e.type!=yu&&e.type!=Cu?r:R1}function b1(e,t){return e.type==Cu||iQ==Ud("messageEncoding",{proto:e,parent:t})}function Ud(e,t){var n,i;const r=(n=t.proto.options)===null||n===void 0?void 0:n.features;if(r){const o=r[e];if(o!=0)return o}if("kind"in t){if(t.kind=="message")return Ud(e,(i=t.parent)!==null&&i!==void 0?i:t.file);const o=A1[t.edition];if(!o)throw new Error("feature default for edition ".concat(t.edition," not found"));return o[e]}return Ud(e,t.parent)}function Eo(e,t){if(!e)throw new Error(t)}function w1(e){var t,n,i,r,o,s,a,c;return Object.assign(Object.create({visibility:0}),{$typeName:"google.protobuf.DescriptorProto",name:e.name,field:(n=(t=e.field)===null||t===void 0?void 0:t.map(uQ))!==null&&n!==void 0?n:[],extension:[],nestedType:(r=(i=e.nestedType)===null||i===void 0?void 0:i.map(w1))!==null&&r!==void 0?r:[],enumType:(s=(o=e.enumType)===null||o===void 0?void 0:o.map(O1))!==null&&s!==void 0?s:[],extensionRange:(c=(a=e.extensionRange)===null||a===void 0?void 0:a.map(d=>Object.assign({$typeName:"google.protobuf.DescriptorProto.ExtensionRange"},d)))!==null&&c!==void 0?c:[],oneofDecl:[],reservedRange:[],reservedName:[]})}function uQ(e){return Object.assign(Object.create({label:1,typeName:"",extendee:"",defaultValue:"",oneofIndex:0,jsonName:"",proto3Optional:!1}),Object.assign(Object.assign({$typeName:"google.protobuf.FieldDescriptorProto"},e),{options:e.options?hQ(e.options):void 0}))}function hQ(e){var t,n,i;return Object.assign(Object.create({ctype:0,packed:!1,jstype:0,lazy:!1,unverifiedLazy:!1,deprecated:!1,weak:!1,debugRedact:!1,retention:0}),Object.assign(Object.assign({$typeName:"google.protobuf.FieldOptions"},e),{targets:(t=e.targets)!==null&&t!==void 0?t:[],editionDefaults:(i=(n=e.editionDefaults)===null||n===void 0?void 0:n.map(r=>Object.assign({$typeName:"google.protobuf.FieldOptions.EditionDefault"},r)))!==null&&i!==void 0?i:[],uninterpretedOption:[]}))}function O1(e){return Object.assign(Object.create({visibility:0}),{$typeName:"google.protobuf.EnumDescriptorProto",name:e.name,reservedName:[],reservedRange:[],value:e.value.map(t=>Object.assign({$typeName:"google.protobuf.EnumValueDescriptorProto"},t))})}function N1(e){const t=function(){if(!Vd){Vd=[];const c=P1("std");for(let d=0;d<c.length;
52d++)Vd[c[d].charCodeAt(0)]=d;Vd[45]=c.indexOf("+"),Vd[95]=c.indexOf("/")}return Vd}();let n=3*e.length/4;e[e.length-2]=="="?n-=2:e[e.length-1]=="="&&(n-=1);let i,r=new Uint8Array(n),o=0,s=0,a=0;for(let c=0;c<e.length;c++){if(i=t[e.charCodeAt(c)],i===void 0)switch(e[c]){case"=":s=0;case` 53`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string")}switch(s){case 0:a=i,s=1;break;case 1:r[o++]=a<<2|(48&i)>>4,a=i,s=2;break;case 2:r[o++]=(15&a)<<4|(60&i)>>2,a=i,s=3;break;case 3:r[o++]=(3&a)<<6|i,s=0}}if(s==1)throw Error("invalid base64 string");return r.subarray(0,o)}let H_,D1,Vd;function P1(e){return H_||(H_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),D1=H_.slice(0,-2).concat("-","_")),e=="url"?D1:H_}var L1=nk,pQ=TypeError,_Q=vu,mQ=String,fR=function(e){if(_Q(e)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return mQ(e)},EQ=VT,fQ=Od,gQ=U_,k1=kk,SQ=x_,TQ=function(e,t,n){var i=EQ(t);i in e?fQ.f(e,i,gQ(0,n)):e[i]=n},RQ=Array,vQ=Math.max,M1=function(e,t,n){for(var i=SQ(e),r=k1(t,i),o=k1(n===void 0?i:n,i),s=RQ(vQ(o-r,0)),a=0;r<o;r++,a++)TQ(s,a,e[r]);return s.length=a,s},AQ=Math.floor,gR=function(e,t){var n=e.length,i=AQ(n/2);return n<8?CQ(e,t):yQ(e,gR(M1(e,0,i),t),gR(M1(e,i),t),t)},CQ=function(e,t){for(var n,i,r=e.length,o=1;o<r;){for(i=o,n=e[o];i&&t(e[i-1],n)>0;)e[i]=e[--i];i!==o++&&(e[i]=n)}return e},yQ=function(e,t,n,i){for(var r=t.length,o=n.length,s=0,a=0;s<r||a<o;)e[s+a]=s<r&&a<o?i(t[s],n[a])<=0?t[s++]:n[a++]:s<r?t[s++]:n[a++];return e},IQ=gR,bQ=Sr,U1=function(e,t){var n=[][e];return!!n&&bQ(function(){n.call(null,t||function(){return 1},1)})},V1=O_.match(/firefox\/(\d+)/i),wQ=!!V1&&+V1[1],OQ=/MSIE|Trident/.test(O_),x1=O_.match(/AppleWebKit\/(\d+)\./),NQ=!!x1&&+x1[1],DQ=zs,F1=_o,PQ=D_,LQ=P_,B1=x_,kQ=function(e,t){if(!delete e[t])throw pQ("Cannot delete property "+L1(t)+" of "+L1(e))},G1=fR,SR=Sr,MQ=IQ,UQ=U1,j1=wQ,VQ=OQ,W1=N_,K1=NQ,fo=[],H1=F1(Pi(fo)),xQ=F1(fo.push),FQ=SR(function(){Pi(fo).call(fo,void 0)}),BQ=SR(function(){Pi(fo).call(fo,null)}),GQ=UQ("sort"),Y1=!SR(function(){if(W1)return W1<70;if(!(j1&&j1>3)){if(VQ)return!0;if(K1)return K1<603;var e,t,n,i,r="";for(e=65;e<76;
53e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(i=0;i<47;i++)fo.push({k:t+i,v:n})}for(Pi(fo).call(fo,function(o,s){return s.v-o.v}),i=0;i<fo.length;i++)t=fo[i].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return r!=="DGBEFHACIJK"}});DQ({target:"Array",proto:!0,forced:FQ||!BQ||!GQ||!Y1},{sort:function(e){e!==void 0&&PQ(e);var t=LQ(this);if(Y1)return e===void 0?H1(t):H1(t,e);var n,i,r=[],o=B1(t);for(i=0;i<o;i++)i in t&&xQ(r,t[i]);for(MQ(r,function(s){return function(a,c){return c===void 0?-1:a===void 0?1:s!==void 0?+s(a,c)||0:G1(a)>G1(c)?1:-1}}(e)),n=B1(r),i=0;i<n;)t[i]=r[i++];for(;i<o;)kQ(t,i++);return t}});var jQ=Pi(qs("Array")),WQ=Js,KQ=jQ,TR=Array.prototype,HQ=Ys(function(e){var t=Pi(e);return e===TR||WQ(TR,e)&&t===Pi(TR)?KQ:t}),YQ=_n(qs("Array")),XQ=vu,JQ=jo,zQ=Js,qQ=YQ,RR=Array.prototype,ZQ={DOMTokenList:!0,NodeList:!0},QQ=Ys(function(e){var t=_n(e);return e===RR||zQ(RR,e)&&t===_n(RR)||JQ(ZQ,XQ(e))?qQ:t});function vR(e,t){return!(e===null||typeof e!="object"||!("$typeName"in e)||typeof e.$typeName!="string"||t!==void 0&&t.typeName!==e.$typeName)}var $Q=x(Uk);zs({target:"Array",proto:!0,forced:Sr(function(){var e;return!x(e=Array(1)).call(e)})},{includes:function(e){return $Q(this,e,arguments.length>1?arguments[1]:void 0)}});var e$=x(qs("Array")),t$=Qa,n$=wd,i$=_s("match"),r$=TypeError,o$=_s("match"),s$=zs,a$=function(e){if(function(t){var n;return t$(t)&&((n=t[i$])!==void 0?!!n:n$(t)=="RegExp")}(e))throw r$("The method doesn't accept regular expressions");return e},c$=C_,X1=fR,d$=_o("".indexOf);s$({target:"String",proto:!0,forced:!function(e){var t=/./;try{"/./"[e](t)}catch{try{return t[o$]=!1,"/./"[e](t)}catch{}}return!1}("includes")},{includes:function(e){return!!~d$(X1(c$(this)),X1(a$(e)),arguments.length>1?arguments[1]:void 0)}});var l$=x(qs("String")),J1=Js,u$=e$,h$=l$,AR=Array.prototype,CR=String.prototype,Y_=Ys(function(e){var t=x(e);return e===AR||J1(AR,e)&&t===x(AR)?u$:typeof e=="string"||e===CR||J1(CR,e)&&t===x(CR)?h$:t});const z1=["FieldValueInvalidError","FieldListRangeError","ForeignFieldError"];class Rr extends Error{constructor(t,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"FieldValueInvalidError";super(n),this.name=i,this.field=()=>t}}function Zs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function yR(e,t){var n,i,r,o;if(Zs(e)&&ms in e&&"add"in e&&"field"in e&&typeof e.field=="function"){if(t!==void 0){const s=t,a=e.field();return s.listKind==a.listKind&&s.scalar===a.scalar&&((n=s.message)===null||n===void 0?void 0:n.typeName)===((i=a.message)===null||i===void 0?void 0:i.typeName)&&((r=s.enum)===null||r===void 0?void 0:r.typeName)===((o=a.enum)===null||o===void 0?void 0:o.typeName)}return!0}return!1}function IR(e,t){var n,i,r,o;if(Zs(e)&&ms in e&&"has"in e&&"field"in e&&typeof e.field=="function"){if(t!==void 0){const s=t,a=e.field();return s.mapKey===a.mapKey&&s.mapKind==a.mapKind&&s.scalar===a.scalar&&((n=s.message)===null||n===void 0?void 0:n.typeName)===((i=a.message)===null||i===void 0?void 0:i.typeName)&&((r=s.enum)===null||r===void 0?void 0:r.typeName)===((o=a.enum)===null||o===void 0?void 0:o.typeName)}return!0}return!1}function bR(e,t){return Zs(e)&&ms in e&&"desc"in e&&Zs(e.desc)&&e.desc.kind==="message"&&(t===void 0||e.desc.typeName==t.typeName)}const wR=Symbol.for("@bufbuild/protobuf/text-encoding");function OR(){if(kd[wR]==null){const e=new kd.TextEncoder,t=new kd.TextDecoder;kd[wR]={encodeUtf8:n=>e.encode(n),decodeUtf8:n=>t.decode(n),checkUtf8(n){try{return encodeURIComponent(n),!0}catch{return!1}}}}return kd[wR]}var Gn;(function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"})(Gn||(Gn={}));const q1=34028234663852886e22,Z1=-34028234663852886e22,Q1=4294967295,$1=2147483647,eM=-2147483648;class tM{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:OR().encodeUtf8;this.encodeUtf8=t,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let t=0;for(let r=0;r<this.chunks.length;r++)t+=this.chunks[r].length;let n=new Uint8Array(t),i=0;for(let r=0;r<this.chunks.length;r++)n.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let t=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(t.byteLength),this.raw(t)}tag(t,n){return this.uint32((t<<3|n)>>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(nM(t);t>127;)this.buf.push(127&t|128),t>>>=7;return this.buf.push(t),this}int32(t){return DR(t),cR(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let n=this.encodeUtf8(t);return this.uint32(n.byteLength),this.raw(n)}float(t){(function(i){if(typeof i=="string"){const r=i;if(i=Number(i),Number.isNaN(i)&&r!=="NaN")throw new Error("invalid float32: "+r)}else if(typeof i!="number")throw new Error("invalid float32: "+typeof i);if(Number.isFinite(i)&&(i>q1||i<Z1))throw new Error("invalid float32: "+i)})(t);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,t,!0),this.raw(n)}double(t){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!0),this.raw(n)}fixed32(t){nM(t);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!0),this.raw(n)}sfixed32(t){DR(t);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,t,!0),this.raw(n)}sint32(t){return DR(t),cR(t=(t<<1^t>>31)>>>0,this.buf),this}sfixed64(t){let n=new Uint8Array(8),i=new DataView(n.buffer),r=In.enc(t);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(n)}fixed64(t){let n=new Uint8Array(8),i=new DataView(n.buffer),r=In.uEnc(t);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(n)}int64(t){let n=In.enc(t);return sR(n.lo,n.hi,this.buf),this}sint64(t){const n=In.enc(t),i=n.hi>>31;return sR(n.lo<<1^i,(n.hi<<1|n.lo>>>31)^i,this.buf),this}uint64(t){const n=In.uEnc(t);return sR(n.lo,n.hi,this.buf),this}}class NR{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:OR().decodeUtf8;this.decodeUtf8=n,this.varint64=F7,this.uint32=B7,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}tag(){let t=this.uint32(),n=t>>>3,i=7&t;if(n<=0||i<0||i>5)throw new Error("illegal tag: field no "+n+" wire type "+i);return[n,i]}skip(t,n){let i=this.pos;switch(t){case Gn.Varint:for(;128&this.buf[this.pos++];);break;case Gn.Bit64:this.pos+=4;case Gn.Bit32:this.pos+=4;break;case Gn.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Gn.StartGroup:for(;;){const[o,s]=this.tag();if(s===Gn.EndGroup){if(n!==void 0&&o!==n)throw new Error("invalid end group tag");break}this.skip(s,o)}break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let t=this.uint32();return t>>>1^-(1&t)}int64(){return In.dec(...this.varint64())}uint64(){return In.uDec(...this.varint64())}sint64(){let[t,n]=this.varint64(),i=-(1&t);return t=(t>>>1|(1&n)<<31)^i,n=n>>>1^i,In.dec(t,n)}bool(){let[t,n]=this.varint64();return t!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return In.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return In.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let t=this.uint32(),n=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(n,n+t)}string(){return this.decodeUtf8(this.bytes())}}function DR(e){if(typeof e=="string")e=Number(e);else if(typeof e!="number")throw new Error("invalid int32: "+typeof e);if(!Number.isInteger(e)||e>$1||e<eM)throw new Error("invalid int32: "+e)}function nM(e){if(typeof e=="string")e=Number(e);else if(typeof e!="number")throw new Error("invalid uint32: "+typeof e);if(!Number.isInteger(e)||e>Q1||e<0)throw new Error("invalid uint32: "+e)}function tc(e,t){const n=e.fieldKind=="list"?yR(t,e):e.fieldKind=="map"?IR(t,e):PR(e,t);if(n===!0)return;let i;switch(e.fieldKind){case"list":i="expected ".concat(sM(e),", got ").concat(ci(t));break;case"map":i="expected ".concat(aM(e),", got ").concat(ci(t));break;default:i=X_(e,t,n)}return new Rr(e,i)}function iM(e,t,n){const i=PR(e,n);if(i!==!0)return new Rr(e,"list item #".concat(t+1,": ").concat(X_(e,n,i)
53))}function PR(e,t){return e.scalar!==void 0?rM(t,e.scalar):e.enum!==void 0?e.enum.open?Number.isInteger(t):Zn(e.enum).some(n=>n.number===t):bR(t,e.message)}function rM(e,t){switch(t){case W.DOUBLE:return typeof e=="number";case W.FLOAT:return typeof e=="number"&&(!(!Number.isNaN(e)&&Number.isFinite(e))||!(e>q1||e<Z1)||"".concat(e.toFixed()," out of range"));case W.INT32:case W.SFIXED32:case W.SINT32:return!(typeof e!="number"||!Number.isInteger(e))&&(!(e>$1||e<eM)||"".concat(e.toFixed()," out of range"));case W.FIXED32:case W.UINT32:return!(typeof e!="number"||!Number.isInteger(e))&&(!(e>Q1||e<0)||"".concat(e.toFixed()," out of range"));case W.BOOL:return typeof e=="boolean";case W.STRING:return typeof e=="string"&&(OR().checkUtf8(e)||"invalid UTF8");case W.BYTES:return e instanceof Uint8Array;case W.INT64:case W.SFIXED64:case W.SINT64:if(typeof e=="bigint"||typeof e=="number"||typeof e=="string"&&e.length>0)try{return In.parse(e),!0}catch{return"".concat(e," out of range")}return!1;case W.FIXED64:case W.UINT64:if(typeof e=="bigint"||typeof e=="number"||typeof e=="string"&&e.length>0)try{return In.uParse(e),!0}catch{return"".concat(e," out of range")}return!1}}function X_(e,t,n){return n=typeof n=="string"?": ".concat(n):", got ".concat(ci(t)),e.scalar!==void 0?"expected ".concat(function(i){switch(i){case W.STRING:return"string";case W.BOOL:return"boolean";case W.INT64:case W.SINT64:case W.SFIXED64:return"bigint (int64)";case W.UINT64:case W.FIXED64:return"bigint (uint64)";case W.BYTES:return"Uint8Array";case W.DOUBLE:return"number (float64)";case W.FLOAT:return"number (float32)";case W.FIXED32:case W.UINT32:return"number (uint32)";case W.INT32:case W.SFIXED32:case W.SINT32:return"number (int32)"}}(e.scalar))+n:e.enum!==void 0?"expected ".concat(e.enum.toString())+n:"expected ".concat(oM(e.message))+n}function ci(e){switch(typeof e){case"object":return e===null?"null":e instanceof Uint8Array?"Uint8Array(".concat(e.length,")"):Array.isArray(e)?"Array(".concat(e.length,")"):yR(e)?sM(e.field()):IR(e)?aM(e.field()):bR(e)?oM(e.desc):vR(e)?"message ".concat(e.$typeName):"object";case"string":return e.length>30?"string":'"'.concat(e.split('"').join('\\"'),'"');case"boolean":case"number":return String(e);case"bigint":return String(e)+"n";default:return typeof e}}function oM(e){return"ReflectMessage (".concat(e.typeName,")")}function sM(e){switch(e.listKind){case"message":return"ReflectList (".concat(e.message.toString(),")");case"enum":return"ReflectList (".concat(e.enum.toString(),")");case"scalar":return"ReflectList (".concat(W[e.scalar],")")}}function aM(e){switch(e.mapKind){case"message":return"ReflectMap (".concat(W[e.mapKey],", ").concat(e.message.toString(),")");case"enum":return"ReflectMap (".concat(W[e.mapKey],", ").concat(e.enum.toString(),")");case"scalar":return"ReflectMap (".concat(W[e.mapKey],", ").concat(W[e.scalar],")")}}function Iu(e){const t=e.fields[0];return cM(e.typeName)&&t!==void 0&&t.fieldKind=="scalar"&&t.name=="value"&&t.number==1}function cM(e){var t;return e.startsWith("google.protobuf.")&&Y_(t=["DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue"]).call(t,e.substring(16))}const p$=999,_$=998,J_=2;function fs(e,t){if(vR(t,e))return t;const n=function(i){let r;if(function(o){switch(o.file.edition){case p$:return!1;case _$:return!0;default:return o.fields.some(s=>s.presence!=J_&&s.fieldKind!="message"&&!s.oneof)}}(i)){const o=uM.get(i);let s,a;if(o)({prototype:s,members:a}=o);else{s={},a=new Set;for(const c of i.members)c.kind!="oneof"&&(c.fieldKind!="scalar"&&c.fieldKind!="enum"||c.presence!=J_&&(a.add(c),s[c.localName]=MR(c)));uM.set(i,{prototype:s,members:a})}r=Object.create(s),r.$typeName=i.typeName;for(const c of i.members)if(!a.has(c)){if(c.kind=="field"&&(c.fieldKind=="message"||(c.fieldKind=="scalar"||c.fieldKind=="enum")&&c.presence!=J_))continue;r[c.localName]=MR(c)}}else{r={$typeName:i.typeName};for(const o of i.members)o.kind!="oneof"&&o.presence!=J_||(r[o.localName]=MR(o))}return r}(e);return t!==void 0&&function(i,r,o){for(const s of i.members){let a,c=o[s.localName];if(c!=null){if(s.kind=="oneof"){const d=m1(o,s);if(!d)continue;a=d,c=E1(o,d)}else a=s;switch(a.fieldKind){case"message":c=LR(a,c);break;case"scalar":c=dM(a,c);break;case"list":c=E$(a,c);break;case"map":c=m$(a,c)}f1(r,a,c)}}}(e,n,t),n}function dM(e,t){return e.scalar==W.BYTES?kR(t):t}
53function m$(e,t){if(Zs(t)){if(e.scalar==W.BYTES)return lM(t,kR);if(e.mapKind=="message")return lM(t,n=>LR(e,n))}return t}function E$(e,t){if(Array.isArray(t)){if(e.scalar==W.BYTES)return t.map(kR);if(e.listKind=="message")return t.map(n=>LR(e,n))}return t}function LR(e,t){if(e.fieldKind=="message"&&!e.oneof&&Iu(e.message))return dM(e.message.fields[0],t);if(Zs(t)){if(e.message.typeName=="google.protobuf.Struct"&&e.parent.typeName!=="google.protobuf.Value")return t;if(!vR(t,e.message))return fs(e.message,t)}return t}function kR(e){return Array.isArray(e)?new Uint8Array(e):e}function lM(e,t){const n={};for(const i of Object.entries(e))n[i[0]]=t(i[1]);return n}const f$=Symbol(),uM=new WeakMap;function MR(e){if(e.kind=="oneof")return{case:void 0};if(e.fieldKind=="list")return[];if(e.fieldKind=="map")return{};if(e.fieldKind=="message")return f$;const t=e.getDefaultValue();return t!==void 0?e.fieldKind=="scalar"&&e.longAsString?t.toString():t:e.fieldKind=="scalar"?Md(e.scalar,e.longAsString):Zn(e.enum)[0].number}function go(e,t){return new pM(e,t,!(arguments.length>2&&arguments[2]!==void 0)||arguments[2])}const hM=new WeakMap;class pM{get sortedFields(){var t;const n=hM.get(this.desc);if(n)return n;const i=HQ(t=this.desc.fields.concat()).call(t,(r,o)=>r.number-o.number);return hM.set(this.desc,i),i}constructor(t,n){let i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];this.lists=new Map,this.maps=new Map,this.check=i,this.desc=t,this.message=this[ms]=n??fs(t),this.fields=t.fields,this.oneofs=t.oneofs,this.members=t.members}findNumber(t){return this._fieldsByNumber||(this._fieldsByNumber=new Map(this.desc.fields.map(n=>[n.number,n]))),this._fieldsByNumber.get(t)}oneofCase(t){return bu(this.message,t),m1(this.message,t)}isSet(t){return bu(this.message,t),function(n,i){const r=i.localName;if(i.oneof)return n[i.oneof.localName].case===r;if(i.presence!=_1)return n[r]!==void 0&&Object.prototype.hasOwnProperty.call(n,r);switch(i.fieldKind){case"list":return n[r].length>0;case"map":return Object.keys(n[r]).length>0;case"scalar":return!function(o,s){switch(o){case W.BOOL:return s===!1;case W.STRING:return s==="";case W.BYTES:return s instanceof Uint8Array&&!s.byteLength;default:return s==0}}(i.scalar,n[r]);case"enum":return n[r]!==Zn(i.enum)[0].number}throw new Error("message field with implicit presence")}(this.message,t)}clear(t){bu(this.message,t),function(n,i){const r=i.localName;if(i.oneof){const o=i.oneof.localName;n[o].case===r&&(n[o]={case:void 0})}else if(i.presence!=_1)delete n[r];else switch(i.fieldKind){case"map":n[r]={};break;case"list":n[r]=[];break;case"enum":n[r]=Zn(i.enum)[0].number;break;case"scalar":n[r]=Md(i.scalar,i.longAsString)}}(this.message,t)}get(t){bu(this.message,t);const n=E1(this.message,t);switch(t.fieldKind){case"list":let i=this.lists.get(t);return i&&i[ms]===n||this.lists.set(t,i=new g$(t,n,this.check)),i;case"map":let r=this.maps.get(t);return r&&r[ms]===n||this.maps.set(t,r=new S$(t,n,this.check)),r;case"message":return VR(t,n,this.check);case"scalar":return n===void 0?Md(t.scalar,!1):BR(t,n);case"enum":return n??Zn(t.enum)[0].number}}set(t,n){if(bu(this.message,t),this.check){const r=tc(t,n);if(r)throw r}let i;i=t.fieldKind=="message"?UR(t,n):IR(n)||yR(n)?n[ms]:GR(t,n),f1(this.message,t,i)}getUnknown(){return this.message.$unknown}setUnknown(t){this.message.$unknown=t}}function bu(e,t){if(t.parent.typeName!==e.$typeName)throw new Rr(t,"cannot use ".concat(t.toString()," with message ").concat(e.$typeName),"ForeignFieldError")}class g${field(){return this._field}get size(){return this._arr.length}constructor(t,n,i){this._field=t,this._arr=this[ms]=n,this.check=i}get(t){const n=this._arr[t];return n===void 0?void 0:xR(this._field,n,this.check)}set(t,n){if(t<0||t>=this._arr.length)throw new Rr(this._field,"list item #".concat(t+1,": out of range"));if(this.check){const i=iM(this._field,t,n);if(i)throw i}this._arr[t]=_M(this._field,n)}add(t){if(this.check){const n=iM(this._field,this._arr.length,t);if(n)throw n}this._arr.push(_M(this._field,t))}clear(){this._arr.splice(0,this._arr.length)}[Symbol.iterator](){return Zn(this).call(this)}keys(){var t;return QQ(t=this._arr).call(t)}*values(){for(const t of this._arr)yield xR(this._field,t,this.check)}*entries(){for(let t=0;t<this._arr.length;t++)yield[t,xR(this._field,this._arr[t],this.check)]}}class S${constructor(t,n){let i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];this.obj=this[ms]=n??{},this.check=i,this._field=t}field(){return this._field}set(t,n){if(this.check){const i=function(r,o,s){const a=rM(o,r.mapKey);
53if(a!==!0)return new Rr(r,"invalid map key: ".concat(X_({scalar:r.mapKey},o,a)));const c=PR(r,s);return c!==!0?new Rr(r,"map entry ".concat(ci(o),": ").concat(X_(r,s,c))):void 0}(this._field,t,n);if(i)throw i}return this.obj[z_(t)]=function(i,r){return i.mapKind=="message"?UR(i,r):GR(i,r)}(this._field,n),this}delete(t){const n=z_(t),i=Object.prototype.hasOwnProperty.call(this.obj,n);return i&&delete this.obj[n],i}clear(){for(const t of Object.keys(this.obj))delete this.obj[t]}get(t){let n=this.obj[z_(t)];return n!==void 0&&(n=FR(this._field,n,this.check)),n}has(t){return Object.prototype.hasOwnProperty.call(this.obj,z_(t))}*keys(){for(const t of Object.keys(this.obj))yield mM(t,this._field.mapKey)}*entries(){for(const t of Object.entries(this.obj))yield[mM(t[0],this._field.mapKey),FR(this._field,t[1],this.check)]}[Symbol.iterator](){return this.entries()}get size(){return Object.keys(this.obj).length}*values(){for(const t of Object.values(this.obj))yield FR(this._field,t,this.check)}forEach(t,n){for(const i of this.entries())t.call(n,i[1],i[0],this)}}function UR(e,t){return bR(t)?cM(t.message.$typeName)&&!e.oneof&&e.fieldKind=="message"?t.message.value:t.desc.typeName=="google.protobuf.Struct"&&e.parent.typeName!="google.protobuf.Value"?fM(t.message):t.message:t}function VR(e,t,n){return t!==void 0&&(Iu(e.message)&&!e.oneof&&e.fieldKind=="message"?t={$typeName:e.message.typeName,value:BR(e.message.fields[0],t)}:e.message.typeName=="google.protobuf.Struct"&&e.parent.typeName!="google.protobuf.Value"&&Zs(t)&&(t=EM(t))),new pM(e.message,t,n)}function _M(e,t){return e.listKind=="message"?UR(e,t):GR(e,t)}function xR(e,t,n){return e.listKind=="message"?VR(e,t,n):BR(e,t)}function FR(e,t,n){return e.mapKind=="message"?VR(e,t,n):t}function z_(e){return typeof e=="string"||typeof e=="number"?e:String(e)}function mM(e,t){switch(t){case W.STRING:return e;case W.INT32:case W.FIXED32:case W.UINT32:case W.SFIXED32:case W.SINT32:{const n=Number.parseInt(e);if(Number.isFinite(n))return n;break}case W.BOOL:switch(e){case"true":return!0;case"false":return!1}break;case W.UINT64:case W.FIXED64:try{return In.uParse(e)}catch{}break;default:try{return In.parse(e)}catch{}}return e}function BR(e,t){switch(e.scalar){case W.INT64:case W.SFIXED64:case W.SINT64:"longAsString"in e&&e.longAsString&&typeof t=="string"&&(t=In.parse(t));break;case W.FIXED64:case W.UINT64:"longAsString"in e&&e.longAsString&&typeof t=="string"&&(t=In.uParse(t))}return t}function GR(e,t){switch(e.scalar){case W.INT64:case W.SFIXED64:case W.SINT64:"longAsString"in e&&e.longAsString?t=String(t):typeof t!="string"&&typeof t!="number"||(t=In.parse(t));break;case W.FIXED64:case W.UINT64:"longAsString"in e&&e.longAsString?t=String(t):typeof t!="string"&&typeof t!="number"||(t=In.uParse(t))}return t}function EM(e){const t={$typeName:"google.protobuf.Struct",fields:{}};if(Zs(e))for(const[n,i]of Object.entries(e))t.fields[n]=SM(i);return t}function fM(e){const t={};for(const[n,i]of Object.entries(e.fields))t[n]=gM(i);return t}function gM(e){switch(e.kind.case){case"structValue":return fM(e.kind.value);case"listValue":return Zn(e.kind.value).map(gM);case"nullValue":case void 0:return null;default:return e.kind.value}}function SM(e){const t={$typeName:"google.protobuf.Value",kind:{case:void 0}};switch(typeof e){case"number":t.kind={case:"numberValue",value:e};break;case"string":t.kind={case:"stringValue",value:e};break;case"boolean":t.kind={case:"boolValue",value:e};break;case"object":if(e===null)t.kind={case:"nullValue",value:0};else if(Array.isArray(e)){const n={$typeName:"google.protobuf.ListValue",values:[]};if(Array.isArray(e))for(const i of e)Zn(n).push(SM(i));t.kind={case:"listValue",value:n}}else t.kind={case:"structValue",value:EM(e)}}return t}const T$=3,TM={writeUnknownFields:!0};function RM(e,t,n){return q_(new tM,function(i){return i?Object.assign(Object.assign({},TM),i):TM}(n),go(e,t)).finish()}function q_(e,t,n){var i;for(const r of n.sortedFields)if(n.isSet(r))vM(e,t,n,r);else if(r.presence==T$)throw new Error("cannot encode ".concat(r," to binary: required field not set"));
53if(t.writeUnknownFields)for(const{no:r,wireType:o,data:s}of(i=n.getUnknown())!==null&&i!==void 0?i:[])e.tag(r,o).raw(s);return e}function vM(e,t,n,i){var r;switch(i.fieldKind){case"scalar":case"enum":Z_(e,n.desc.typeName,i.name,(r=i.scalar)!==null&&r!==void 0?r:W.INT32,i.number,n.get(i));break;case"list":(function(o,s,a,c){var d;if(a.listKind=="message"){for(const h of c)AM(o,s,a,h);return}const l=(d=a.scalar)!==null&&d!==void 0?d:W.INT32;if(a.packed){if(!c.size)return;o.tag(a.number,Gn.LengthDelimited).fork();for(const h of c)CM(o,a.parent.typeName,a.name,l,h);o.join()}else for(const h of c)Z_(o,a.parent.typeName,a.name,l,a.number,h)})(e,t,i,n.get(i));break;case"message":AM(e,t,i,n.get(i));break;case"map":for(const[o,s]of n.get(i))R$(e,t,i,o,s)}}function Z_(e,t,n,i,r,o){CM(e.tag(r,function(s){switch(s){case W.BYTES:case W.STRING:return Gn.LengthDelimited;case W.DOUBLE:case W.FIXED64:case W.SFIXED64:return Gn.Bit64;case W.FIXED32:case W.SFIXED32:case W.FLOAT:return Gn.Bit32;default:return Gn.Varint}}(i)),t,n,i,o)}function AM(e,t,n,i){n.delimitedEncoding?q_(e.tag(n.number,Gn.StartGroup),t,i).tag(n.number,Gn.EndGroup):q_(e.tag(n.number,Gn.LengthDelimited).fork(),t,i).join()}function R$(e,t,n,i,r){var o;switch(e.tag(n.number,Gn.LengthDelimited).fork(),Z_(e,n.parent.typeName,n.name,n.mapKey,1,i),n.mapKind){case"scalar":case"enum":Z_(e,n.parent.typeName,n.name,(o=n.scalar)!==null&&o!==void 0?o:W.INT32,2,r);break;case"message":q_(e.tag(2,Gn.LengthDelimited).fork(),t,r).join()}e.join()}function CM(e,t,n,i,r){try{switch(i){case W.STRING:e.string(r);break;case W.BOOL:e.bool(r);break;case W.DOUBLE:e.double(r);break;case W.FLOAT:e.float(r);break;case W.INT32:e.int32(r);break;case W.INT64:e.int64(r);break;case W.UINT64:e.uint64(r);break;case W.FIXED64:e.fixed64(r);break;case W.BYTES:e.bytes(r);break;case W.FIXED32:e.fixed32(r);break;case W.SFIXED32:e.sfixed32(r);break;case W.SFIXED64:e.sfixed64(r);break;case W.SINT64:e.sint64(r);break;case W.UINT32:e.uint32(r);break;case W.SINT32:e.sint32(r)}}catch(o){throw o instanceof Error?new Error("cannot encode field ".concat(t,".").concat(n," to binary: ").concat(o.message)):o}}var v$=D_,A$=P_,C$=VL,y$=x_,I$=TypeError,b$=function(e){return function(t,n,i,r){v$(n);var o=A$(t),s=C$(o),a=y$(o),c=e?a-1:0,d=e?-1:1;if(i<2)for(;;){if(c in s){r=s[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw I$("Reduce of empty array with no initial value")}for(;e?c>=0:a>c;c+=d)c in s&&(r=n(r,s[c],c,o));return r}},w$={left:b$(!1)},O$=typeof process<"u"&&wd(process)=="process",N$=w$.left;zs({target:"Array",proto:!0,forced:!O$&&N_>79&&N_<83||!U1("reduce")},{reduce:function(e){var t=arguments.length;return N$(this,e,t,t>1?arguments[1]:void 0)}});var D$=ei(qs("Array")),P$=Js,L$=D$,jR=Array.prototype,k$=Ys(function(e){var t=ei(e);return e===jR||P$(jR,e)&&t===ei(jR)?L$:t});function nc(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return k$(i).call(i,(o,s)=>o.nestedMessages[s],e.messages[t])}const M$=nc(function(e){const t=function(n){return Object.assign(Object.create({syntax:"",edition:0}),Object.assign(Object.assign({$typeName:"google.protobuf.FileDescriptorProto",dependency:[],publicDependency:[],weakDependency:[],optionDependency:[],service:[],extension:[]},n),{messageType:n.messageType.map(w1),enumType:n.enumType.map(O1)}))}(e);return t.messageType.forEach(dR),g1(t,()=>{}).getFile(t.name)}
vendor: 19,083 bytes, line 53
53({name:"google/protobuf/descriptor.proto",package:"google.protobuf",messageType:[{name:"FileDescriptorSet",field:[{name:"file",number:1,type:11,label:3,typeName:".google.protobuf.FileDescriptorProto"}],extensionRange:[{start:536e6,end:536000001}]},{name:"FileDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"package",number:2,type:9,label:1},{name:"dependency",number:3,type:9,label:3},{name:"public_dependency",number:10,type:5,label:3},{name:"weak_dependency",number:11,type:5,label:3},{name:"option_dependency",number:15,type:9,label:3},{name:"message_type",number:4,type:11,label:3,typeName:".google.protobuf.DescriptorProto"},{name:"enum_type",number:5,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto"},{name:"service",number:6,type:11,label:3,typeName:".google.protobuf.ServiceDescriptorProto"},{name:"extension",number:7,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"options",number:8,type:11,label:1,typeName:".google.protobuf.FileOptions"},{name:"source_code_info",number:9,type:11,label:1,typeName:".google.protobuf.SourceCodeInfo"},{name:"syntax",number:12,type:9,label:1},{name:"edition",number:14,type:14,label:1,typeName:".google.protobuf.Edition"}]},{name:"DescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"field",number:2,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"extension",number:6,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"nested_type",number:3,type:11,label:3,typeName:".google.protobuf.DescriptorProto"},{name:"enum_type",number:4,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto"},{name:"extension_range",number:5,type:11,label:3,typeName:".google.protobuf.DescriptorProto.ExtensionRange"},{name:"oneof_decl",number:8,type:11,label:3,typeName:".google.protobuf.OneofDescriptorProto"},{name:"options",number:7,type:11,label:1,typeName:".google.protobuf.MessageOptions"},{name:"reserved_range",number:9,type:11,label:3,typeName:".google.protobuf.DescriptorProto.ReservedRange"},{name:"reserved_name",number:10,type:9,label:3},{name:"visibility",number:11,type:14,label:1,typeName:".google.protobuf.SymbolVisibility"}],nestedType:[{name:"ExtensionRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.ExtensionRangeOptions"}]},{name:"ReservedRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1}]}]},{name:"ExtensionRangeOptions",field:[{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"},{name:"declaration",number:2,type:11,label:3,typeName:".google.protobuf.ExtensionRangeOptions.Declaration",options:{retention:2}},{name:"features",number:50,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"verification",number:3,type:14,label:1,typeName:".google.protobuf.ExtensionRangeOptions.VerificationState",defaultValue:"UNVERIFIED",options:{retention:2}}],nestedType:[{name:"Declaration",field:[{name:"number",number:1,type:5,label:1},{name:"full_name",number:2,type:9,label:1},{name:"type",number:3,type:9,label:1},{name:"reserved",number:5,type:8,label:1},{name:"repeated",number:6,type:8,label:1}]}],enumType:[{name:"VerificationState",value:[{name:"DECLARATION",number:0},{name:"UNVERIFIED",number:1}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"FieldDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"number",number:3,type:5,label:1},{name:"label",number:4,type:14,label:1,typeName:".google.protobuf.FieldDescriptorProto.Label"},{name:"type",number:5,type:14,label:1,typeName:".google.protobuf.FieldDescriptorProto.Type"},{name:"type_name",number:6,type:9,label:1},{name:"extendee",number:2,type:9,label:1},{name:"default_value",number:7,type:9,label:1},{name:"oneof_index",number:9,type:5,label:1},{name:"json_name",number:10,type:9,label:1},{name:"options",number:8,type:11,label:1,typeName:".google.protobuf.FieldOptions"},{name:"proto3_optional",number:17,type:8,label:1}],enumType:[{name:"Type",value:[{name:"TYPE_DOUBLE",number:1},{name:"TYPE_FLOAT",number:2},{name:"TYPE_INT64",number:3},{name:"TYPE_UINT64",number:4},{name:"TYPE_INT32",number:5},{name:"TYPE_FIXED64",number:6},{name:"TYPE_FIXED32",number:7},{name:"TYPE_BOOL",number:8},{name:"TYPE_STRING",number:9},{name:"TYPE_GROUP",number:10},{name:"TYPE_MESSAGE",number:11},{name:"TYPE_BYTES",number:12},{name:"TYPE_UINT32",number:13},{name:"TYPE_ENUM",number:14},{name:"TYPE_SFIXED32",number:15},{name:"TYPE_SFIXED64",number:16},{name:"TYPE_SINT32",number:17},{name:"TYPE_SINT64",number:18}]},{name:"Label",value:[{name:"LABEL_OPTIONAL",number:1},{name:"LABEL_REPEATED",number:3},{name:"LABEL_REQUIRED",number:2}]}]},{name:"OneofDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"options",number:2,type:11,label:1,typeName:".google.protobuf.OneofOptions"}]},{name:"EnumDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"value",number:2,type:11,label:3,typeName:".google.protobuf.EnumValueDescriptorProto"},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.EnumOptions"},{name:"reserved_range",number:4,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto.EnumReservedRange"},{name:"reserved_name",number:5,type:9,label:3},{name:"visibility",number:6,type:14,label:1,typeName:".google.protobuf.SymbolVisibility"}],nestedType:[{name:"EnumReservedRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1}]}]},{name:"EnumValueDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"number",number:2,type:5,label:1},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.EnumValueOptions"}]},{name:"ServiceDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"method",number:2,type:11,label:3,typeName:".google.protobuf.MethodDescriptorProto"},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.ServiceOptions"}]},{name:"MethodDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"input_type",number:2,type:9,label:1},{name:"output_type",number:3,type:9,label:1},{name:"options",number:4,type:11,label:1,typeName:".google.protobuf.MethodOptions"},{name:"client_streaming",number:5,type:8,label:1,defaultValue:"false"},{name:"server_streaming",number:6,type:8,label:1,defaultValue:"false"}]},{name:"FileOptions",field:[{name:"java_package",number:1,type:9,label:1},{name:"java_outer_classname",number:8,type:9,label:1},{name:"java_multiple_files",number:10,type:8,label:1,defaultValue:"false"},{name:"java_generate_equals_and_hash",number:20,type:8,label:1,options:{deprecated:!0}},{name:"java_string_check_utf8",number:27,type:8,label:1,defaultValue:"false"},{name:"optimize_for",number:9,type:14,label:1,typeName:".google.protobuf.FileOptions.OptimizeMode",defaultValue:"SPEED"},{name:"go_package",number:11,type:9,label:1},{name:"cc_generic_services",number:16,type:8,label:1,defaultValue:"false"},{name:"java_generic_services",number:17,type:8,label:1,defaultValue:"false"},{name:"py_generic_services",number:18,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:23,type:8,label:1,defaultValue:"false"},{name:"cc_enable_arenas",number:31,type:8,label:1,defaultValue:"true"},{name:"objc_class_prefix",number:36,type:9,label:1},{name:"csharp_namespace",number:37,type:9,label:1},{name:"swift_prefix",number:39,type:9,label:1},{name:"php_class_prefix",number:40,type:9,label:1},{name:"php_namespace",number:41,type:9,label:1},{name:"php_metadata_namespace",number:44,type:9,label:1},{name:"ruby_package",number:45,type:9,label:1},{name:"features",number:50,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],enumType:[{name:"OptimizeMode",value:[{name:"SPEED",number:1},{name:"CODE_SIZE",number:2},{name:"LITE_RUNTIME",number:3}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"MessageOptions",field:[{name:"message_set_wire_format",number:1,type:8,label:1,defaultValue:"false"},{name:"no_standard_descriptor_accessor",number:2,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"map_entry",number:7,type:8,label:1},{name:"deprecated_legacy_json_field_conflicts",number:11,type:8,label:1,options:{deprecated:!0}},{name:"features",number:12,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"FieldOptions",field:[{name:"ctype",number:1,type:14,label:1,typeName:".google.protobuf.FieldOptions.CType",defaultValue:"STRING"},{name:"packed",number:2,type:8,label:1},{name:"jstype",number:6,type:14,label:1,typeName:".google.protobuf.FieldOptions.JSType",defaultValue:"JS_NORMAL"},{name:"lazy",number:5,type:8,label:1,defaultValue:"false"},{name:"unverified_lazy",number:15,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"weak",number:10,type:8,label:1,defaultValue:"false",options:{deprecated:!0}},{name:"debug_redact",number:16,type:8,label:1,defaultValue:"false"},{name:"retention",number:17,type:14,label:1,typeName:".google.protobuf.FieldOptions.OptionRetention"},{name:"targets",number:19,type:14,label:3,typeName:".google.protobuf.FieldOptions.OptionTargetType"},{name:"edition_defaults",number:20,type:11,label:3,typeName:".google.protobuf.FieldOptions.EditionDefault"},{name:"features",number:21,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"feature_support",number:22,type:11,label:1,typeName:".google.protobuf.FieldOptions.FeatureSupport"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],nestedType:[{name:"EditionDefault",field:[{name:"edition",number:3,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"value",number:2,type:9,label:1}]},{name:"FeatureSupport",field:[{name:"edition_introduced",number:1,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"edition_deprecated",number:2,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"deprecation_warning",number:3,type:9,label:1},{name:"edition_removed",number:4,type:14,label:1,typeName:".google.protobuf.Edition"}]}],enumType:[{name:"CType",value:[{name:"STRING",number:0},{name:"CORD",number:1},{name:"STRING_PIECE",number:2}]},{name:"JSType",value:[{name:"JS_NORMAL",number:0},{name:"JS_STRING",number:1},{name:"JS_NUMBER",number:2}]},{name:"OptionRetention",value:[{name:"RETENTION_UNKNOWN",number:0},{name:"RETENTION_RUNTIME",number:1},{name:"RETENTION_SOURCE",number:2}]},{name:"OptionTargetType",value:[{name:"TARGET_TYPE_UNKNOWN",number:0},{name:"TARGET_TYPE_FILE",number:1},{name:"TARGET_TYPE_EXTENSION_RANGE",number:2},{name:"TARGET_TYPE_MESSAGE",number:3},{name:"TARGET_TYPE_FIELD",number:4},{name:"TARGET_TYPE_ONEOF",number:5},{name:"TARGET_TYPE_ENUM",number:6},{name:"TARGET_TYPE_ENUM_ENTRY",number:7},{name:"TARGET_TYPE_SERVICE",number:8},{name:"TARGET_TYPE_METHOD",number:9}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"OneofOptions",field:[{name:"features",number:1,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"EnumOptions",field:[{name:"allow_alias",number:2,type:8,label:1},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"deprecated_legacy_json_field_conflicts",number:6,type:8,label:1,options:{deprecated:!0}},{name:"features",number:7,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"EnumValueOptions",field:[{name:"deprecated",number:1,type:8,label:1,defaultValue:"false"},{name:"features",number:2,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"debug_redact",number:3,type:8,label:1,defaultValue:"false"},{name:"feature_support",number:4,type:11,label:1,typeName:".google.protobuf.FieldOptions.FeatureSupport"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"ServiceOptions",field:[{name:"features",number:34,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"deprecated",number:33,type:8,label:1,defaultValue:"false"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"MethodOptions",field:[{name:"deprecated",number:33,type:8,label:1,defaultValue:"false"},{name:"idempotency_level",number:34,type:14,label:1,typeName:".google.protobuf.MethodOptions.IdempotencyLevel",defaultValue:"IDEMPOTENCY_UNKNOWN"},{name:"features",number:35,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],enumType:[{name:"IdempotencyLevel",value:[{name:"IDEMPOTENCY_UNKNOWN",number:0},{name:"NO_SIDE_EFFECTS",number:1},{name:"IDEMPOTENT",number:2}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"UninterpretedOption",field:[{name:"name",number:2,type:11,label:3,typeName:".google.protobuf.UninterpretedOption.NamePart"},{name:"identifier_value",number:3,type:9,label:1},{name:"positive_int_value",number:4,type:4,label:1},{name:"negative_int_value",number:5,type:3,label:1},{name:"double_value",number:6,type:1,label:1},{name:"string_value",number:7,type:12,label:1},{name:"aggregate_value",number:8,type:9,label:1}],nestedType:[{name:"NamePart",field:[{name:"name_part",number:1,type:9,label:2},{name:"is_extension",number:2,type:8,label:2}]}]},{name:"FeatureSet",field:[{name:"field_presence",number:1,type:14,label:1,typeName:".google.protobuf.FeatureSet.FieldPresence",options:{retention:1,targets:[4,1],editionDefaults:[{value:"EXPLICIT",edition:900},{value:"IMPLICIT",edition:999},{value:"EXPLICIT",edition:1e3}]}},{name:"enum_type",number:2,type:14,label:1,typeName:".google.protobuf.FeatureSet.EnumType",options:{retention:1,targets:[6,1],editionDefaults:[{value:"CLOSED",edition:900},{value:"OPEN",edition:999}]}},{name:"repeated_field_encoding",number:3,type:14,label:1,typeName:".google.protobuf.FeatureSet.RepeatedFieldEncoding",options:{retention:1,targets:[4,1],editionDefaults:[{value:"EXPANDED",edition:900},{value:"PACKED",edition:999}]}},{name:"utf8_validation",number:4,type:14,label:1,typeName:".google.protobuf.FeatureSet.Utf8Validation",options:{retention:1,targets:[4,1],editionDefaults:[{value:"NONE",edition:900},{value:"VERIFY",edition:999}]}},{name:"message_encoding",number:5,type:14,label:1,typeName:".google.protobuf.FeatureSet.MessageEncoding",options:{retention:1,targets:[4,1],editionDefaults:[{value:"LENGTH_PREFIXED",edition:900}]}},{name:"json_format",number:6,type:14,label:1,typeName:".google.protobuf.FeatureSet.JsonFormat",options:{retention:1,targets:[3,6,1],editionDefaults:[{value:"LEGACY_BEST_EFFORT",edition:900},{value:"ALLOW",edition:999}]}},{name:"enforce_naming_style",number:7,type:14,label:1,typeName:".google.protobuf.FeatureSet.EnforceNamingStyle",options:{retention:2,targets:[1,2,3,4,5,6,7,8,9],editionDefaults:[{value:"STYLE_LEGACY",edition:900},{value:"STYLE2024",edition:1001}]}},{name:"default_symbol_visibility",number:8,type:14,label:1,typeName:".google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility",options:{retention:2,targets:[1],editionDefaults:[{value:"EXPORT_ALL",edition:900},{value:"EXPORT_TOP_LEVEL",edition:1001}]}}],nestedType:[{name:"VisibilityFeature",enumType:[{name:"DefaultSymbolVisibility",value:[{name:"DEFAULT_SYMBOL_VISIBILITY_UNKNOWN",number:0},{name:"EXPORT_ALL",number:1},{name:"EXPORT_TOP_LEVEL",number:2},{name:"LOCAL_ALL",number:3},{name:"STRICT",number:4}]}]}],enumType:[{name:"FieldPresence",value:[{name:"FIELD_PRESENCE_UNKNOWN",number:0},{name:"EXPLICIT",number:1},{name:"IMPLICIT",number:2},{name:"LEGACY_REQUIRED",number:3}]},{name:"EnumType",value:[{name:"ENUM_TYPE_UNKNOWN",number:0},{name:"OPEN",number:1},{name:"CLOSED",number:2}]},{name:"RepeatedFieldEncoding",value:[{name:"REPEATED_FIELD_ENCODING_UNKNOWN",number:0},{name:"PACKED",number:1},{name:"EXPANDED",number:2}]},{name:"Utf8Validation",value:[{name:"UTF8_VALIDATION_UNKNOWN",number:0},{name:"VERIFY",number:2},{name:"NONE",number:3}]},{name:"MessageEncoding",value:[{name:"MESSAGE_ENCODING_UNKNOWN",number:0},{name:"LENGTH_PREFIXED",number:1},{name:"DELIMITED",number:2}]},{name:"JsonFormat",value:[{name:"JSON_FORMAT_UNKNOWN",number:0},{name:"ALLOW",number:1},{name:"LEGACY_BEST_EFFORT",number:2}]},{name:"EnforceNamingStyle",value:[{name:"ENFORCE_NAMING_STYLE_UNKNOWN",number:0},{name:"STYLE2024",number:1},{name:"STYLE_LEGACY",number:2}]}],extensionRange:[{start:1e3,end:9995},{start:9995,end:1e4},{start:1e4,end:10001}]},{name:"FeatureSetDefaults",field:[{name:"defaults",number:1,type:11,label:3,typeName:".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault"},{name:"minimum_edition",number:4,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"maximum_edition",number:5,type:14,label:1,typeName:".google.protobuf.Edition"}],nestedType:[{name:"FeatureSetEditionDefault",field:[{name:"edition",number:3,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"overridable_features",number:4,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"fixed_features",number:5,type:11,label:1,typeName:".google.protobuf.FeatureSet"}]}]},{name:"SourceCodeInfo",field:[{name:"location",number:1,type:11,label:3,typeName:".google.protobuf.SourceCodeInfo.Location"}],nestedType:[{name:"Location",field:[{name:"path",number:1,type:5,label:3,options:{packed:!0}},{name:"span",number:2,type:5,label:3,options:{packed:!0}},{name:"leading_comments",number:3,type:9,label:1},{name:"trailing_comments",number:4,type:9,label:1},{name:"leading_detached_comments",number:6,type:9,label:3}]}],extensionRange:[{start:536e6,end:536000001}]},{name:"GeneratedCodeInfo",field:[{name:"annotation",number:1,type:11,label:3,typeName:".google.protobuf.GeneratedCodeInfo.Annotation"}],nestedType:[{name:"Annotation",field:[{name:"path",number:1,type:5,label:3,options:{packed:!0}},{name:"source_file",number:2,type:9,label:1},{name:"begin",number:3,type:5,label:1},{name:"end",number:4,type:5,label:1},{name:"semantic",number:5,type:14,label:1,typeName:".google.protobuf.GeneratedCodeInfo.Annotation.Semantic"}],enumType:[{name:"Semantic",value:[{name:"NONE",number:0},{name:"SET",number:1},{name:"ALIAS",number:2}]}]}]}],enumType:[{name:"Edition",value:[{name:"EDITION_UNKNOWN",number:0},{name:"EDITION_LEGACY",number:900},{name:"EDITION_PROTO2",number:998},{name:"EDITION_PROTO3",number:999},{name:"EDITION_2023",number:1e3},{name:"EDITION_2024",number:1001},{name:"EDITION_
53UNSTABLE",number:9999},{name:"EDITION_1_TEST_ONLY",number:1},{name:"EDITION_2_TEST_ONLY",number:2},{name:"EDITION_99997_TEST_ONLY",number:99997},{name:"EDITION_99998_TEST_ONLY",number:99998},{name:"EDITION_99999_TEST_ONLY",number:99999},{name:"EDITION_MAX",number:2147483647}]},{name:"SymbolVisibility",value:[{name:"VISIBILITY_UNSET",number:0},{name:"VISIBILITY_LOCAL",number:1},{name:"VISIBILITY_EXPORT",number:2}]}]}),1);var yM,IM,bM,wM,OM,NM,DM,PM,LM,kM,MM,UM,VM,xM,FM,BM,GM,jM,WM,KM;(function(e){e[e.DECLARATION=0]="DECLARATION",e[e.UNVERIFIED=1]="UNVERIFIED"})(yM||(yM={})),function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.GROUP=10]="GROUP",e[e.MESSAGE=11]="MESSAGE",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.ENUM=14]="ENUM",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(IM||(IM={})),function(e){e[e.OPTIONAL=1]="OPTIONAL",e[e.REPEATED=3]="REPEATED",e[e.REQUIRED=2]="REQUIRED"}(bM||(bM={})),function(e){e[e.SPEED=1]="SPEED",e[e.CODE_SIZE=2]="CODE_SIZE",e[e.LITE_RUNTIME=3]="LITE_RUNTIME"}(wM||(wM={})),function(e){e[e.STRING=0]="STRING",e[e.CORD=1]="CORD",e[e.STRING_PIECE=2]="STRING_PIECE"}(OM||(OM={})),function(e){e[e.JS_NORMAL=0]="JS_NORMAL",e[e.JS_STRING=1]="JS_STRING",e[e.JS_NUMBER=2]="JS_NUMBER"}(NM||(NM={})),function(e){e[e.RETENTION_UNKNOWN=0]="RETENTION_UNKNOWN",e[e.RETENTION_RUNTIME=1]="RETENTION_RUNTIME",e[e.RETENTION_SOURCE=2]="RETENTION_SOURCE"}(DM||(DM={})),function(e){e[e.TARGET_TYPE_UNKNOWN=0]="TARGET_TYPE_UNKNOWN",e[e.TARGET_TYPE_FILE=1]="TARGET_TYPE_FILE",e[e.TARGET_TYPE_EXTENSION_RANGE=2]="TARGET_TYPE_EXTENSION_RANGE",e[e.TARGET_TYPE_MESSAGE=3]="TARGET_TYPE_MESSAGE",e[e.TARGET_TYPE_FIELD=4]="TARGET_TYPE_FIELD",e[e.TARGET_TYPE_ONEOF=5]="TARGET_TYPE_ONEOF",e[e.TARGET_TYPE_ENUM=6]="TARGET_TYPE_ENUM",e[e.TARGET_TYPE_ENUM_ENTRY=7]="TARGET_TYPE_ENUM_ENTRY",e[e.TARGET_TYPE_SERVICE=8]="TARGET_TYPE_SERVICE",e[e.TARGET_TYPE_METHOD=9]="TARGET_TYPE_METHOD"}(PM||(PM={})),function(e){e[e.IDEMPOTENCY_UNKNOWN=0]="IDEMPOTENCY_UNKNOWN",e[e.NO_SIDE_EFFECTS=1]="NO_SIDE_EFFECTS",e[e.IDEMPOTENT=2]="IDEMPOTENT"}(LM||(LM={})),function(e){e[e.DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0]="DEFAULT_SYMBOL_VISIBILITY_UNKNOWN",e[e.EXPORT_ALL=1]="EXPORT_ALL",e[e.EXPORT_TOP_LEVEL=2]="EXPORT_TOP_LEVEL",e[e.LOCAL_ALL=3]="LOCAL_ALL",e[e.STRICT=4]="STRICT"}(kM||(kM={})),function(e){e[e.FIELD_PRESENCE_UNKNOWN=0]="FIELD_PRESENCE_UNKNOWN",e[e.EXPL
53ICIT=1]="EXPLICIT",e[e.IMPLICIT=2]="IMPLICIT",e[e.LEGACY_REQUIRED=3]="LEGACY_REQUIRED"}(MM||(MM={})),function(e){e[e.ENUM_TYPE_UNKNOWN=0]="ENUM_TYPE_UNKNOWN",e[e.OPEN=1]="OPEN",e[e.CLOSED=2]="CLOSED"}(UM||(UM={})),function(e){e[e.REPEATED_FIELD_ENCODING_UNKNOWN=0]="REPEATED_FIELD_ENCODING_UNKNOWN",e[e.PACKED=1]="PACKED",e[e.EXPANDED=2]="EXPANDED"}(VM||(VM={})),function(e){e[e.UTF8_VALIDATION_UNKNOWN=0]="UTF8_VALIDATION_UNKNOWN",e[e.VERIFY=2]="VERIFY",e[e.NONE=3]="NONE"}(xM||(xM={})),function(e){e[e.MESSAGE_ENCODING_UNKNOWN=0]="MESSAGE_ENCODING_UNKNOWN",e[e.LENGTH_PREFIXED=1]="LENGTH_PREFIXED",e[e.DELIMITED=2]="DELIMITED"}(FM||(FM={})),function(e){e[e.JSON_FORMAT_UNKNOWN=0]="JSON_FORMAT_UNKNOWN",e[e.ALLOW=1]="ALLOW",e[e.LEGACY_BEST_EFFORT=2]="LEGACY_BEST_EFFORT"}(BM||(BM={})),function(e){e[e.ENFORCE_NAMING_STYLE_UNKNOWN=0]="ENFORCE_NAMING_STYLE_UNKNOWN",e[e.STYLE2024=1]="STYLE2024",e[e.STYLE_LEGACY=2]="STYLE_LEGACY"}(GM||(GM={})),function(e){e[e.NONE=0]="NONE",e[e.SET=1]="SET",e[e.ALIAS=2]="ALIAS"}(jM||(jM={})),function(e){e[e.EDITION_UNKNOWN=0]="EDITION_UNKNOWN",e[e.EDITION_LEGACY=900]="EDITION_LEGACY",e[e.EDITION_PROTO2=998]="EDITION_PROTO2",e[e.EDITION_PROTO3=999]="EDITION_PROTO3",e[e.EDITION_2023=1e3]="EDITION_2023",e[e.EDITION_2024=1001]="EDITION_2024",e[e.EDITION_UNSTABLE=9999]="EDITION_UNSTABLE",e[e.EDITION_1_TEST_ONLY=1]="EDITION_1_TEST_ONLY",e[e.EDITION_2_TEST_ONLY=2]="EDITION_2_TEST_ONLY",e[e.EDITION_99997_TEST_ONLY=99997]="EDITION_99997_TEST_ONLY",e[e.EDITION_99998_TEST_ONLY=99998]="EDITION_99998_TEST_ONLY",e[e.EDITION_99999_TEST_ONLY=99999]="EDITION_99999_TEST_ONLY",e[e.EDITION_MAX=2147483647]="EDITION_MAX"}(WM||(WM={})),function(e){e[e.VISIBILITY_UNSET=0]="VISIBILITY_UNSET",e[e.VISIBILITY_LOCAL=1]="VISIBILITY_LOCAL",e[e.VISIBILITY_EXPORT=2]="VISIBILITY_EXPORT"}(KM||(KM={}));const HM={readUnknownFields:!0};function WR(e,t,n){const i=go(e,void 0,!1);return YM(i,new NR(t),function(r){return r?Object.assign(Object.assign({},HM),r):HM}(n),!1,t.byteLength),i.message}function YM(e,t,n,i,r){var o;const s=i?t.len:t.pos+r;let a,c;const d=(o=e.getUnknown())!==null&&o!==void 0?o:[];for(;t.pos<s&&([a,c]=t.tag(),!i||c!=Gn.EndGroup);){const l=e.findNumber(a);if(l)XM(e,t,l,c,n);else{const h=t.skip(c,a);n.readUnknownFields&&d.push({no:a,wireType:c,data:h})}}if(i&&(c!=Gn.EndGroup||a!==r))throw new Error("invalid end group tag");d.length>0&&e.setUnknown(d)}function XM(e,t,n,i,r){var o;switch(n.fieldKind){case"scalar":e.set(n,xd(t,n.scalar));break;case"enum":const s=xd(t,W.INT32);if(n.enum.open)e.set(n,s);else if(Zn(n.enum).some(a=>a.number===s))e.set(n,s);else if(r.readUnknownFields){const a=[];cR(s,a);const c=(o=e.getUnknown())!==null&&o!==void 0?o:[];c.push({no:n.number,wireType:i,data:new Uint8Array(a)}),e.setUnknown(c)}break;case"message":e.set(n,KR(t,r,n,e.get(n)));break;case"list":(function(a,c,d,l){var h;const u=d.field();if(u.listKind==="message")return void d.add(KR(a,l,u));const p=(h=u.scalar)!==null&&h!==void 0?h:W.INT32;if(!(c==Gn.LengthDelimited&&p!=W.STRING&&p!=W.BYTES))return void d.add(xd(a,p));const E=a.uint32()+a.pos;for(;a.pos<E;)d.add(xd(a,p))})(t,i,e.get(n),r);break;case"map":(function(a,c,d){const l=c.field();let h,u;const p=a.uint32(),E=a.pos+p;for(;a.pos<E;){const[m]=a.tag();switch(m){case 1:h=xd(a,l.mapKey);break;case 2:switch(l.mapKind){case"scalar":u=xd(a,l.scalar);break;case"enum":u=a.int32();break;case"message":u=KR(a,d,l)}}}if(h===void 0&&(h=Md(l.mapKey,!1)),u===void 0)switch(l.mapKind){case"scalar":u=Md(l.scalar,!1);break;case"enum":u=Zn(l.enum)[0].number;break;case"message":u=go(l.message,void 0,!1)}c.set(h,u)})(t,e.get(n),r)}}function KR(e,t,n,i){const r=n.delimitedEncoding,o=i??go(n.message,void 0,!1);return YM(o,e,t,r,r?n.number:e.uint32()),o}function xd(e,t){switch(t){case W.STRING:return e.string();case W.BOOL:return e.bool();case W.DOUBLE:return e.double();case W.FLOAT:return e.float();case W.INT32:return e.int32();case W.INT64:return e.int64();case W.UINT64:return e.uint64();case W.FIXED64:return e.fixed64();case W.BYTES:return e.bytes();case W.FIXED32:return e.fixed32();case W.SFIXED32:return e.sfixed32();case W.SFIXED64:return e.sfixed64();case W.SINT64:return e.sint64();case W.UINT32:return e.uint32();case W.SINT32:return e.sint32()}}function Q_(e,t){var n;const i=WR(M$,N1(e));return i.messageType.forEach(dR),i.dependency=(n=t==null?void 0:t.map(r=>r.proto.name))!==null&&n!==void 0?n:[],g1(i,r=>t==null?void 0:t.find(o=>o.proto.name===r)).getFile(i.name)}const U$=nc(Q_("Chlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvEg9nb29nbGUucHJvdG9idWYiJgoDQW55EhAKCHR5cGVfdXJsGAEgASgJEg0KBXZhbHVlGAIgASgMQnYKE2NvbS5nb29nbGUucHJvdG9idWZCCEFueVByb3RvUAFaLGdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2FueXBiogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM"),0);function JM(e){const t=e.lastIndexOf("/"),n=t>
53=0?e.substring(t+1):e;if(!n.length)throw new Error("invalid type url: ".concat(e));return n}const wu=Q_("Chxnb29nbGUvcHJvdG9idWYvc3RydWN0LnByb3RvEg9nb29nbGUucHJvdG9idWYihAEKBlN0cnVjdBIzCgZmaWVsZHMYASADKAsyIy5nb29nbGUucHJvdG9idWYuU3RydWN0LkZpZWxkc0VudHJ5GkUKC0ZpZWxkc0VudHJ5EgsKA2tleRgBIAEoCRIlCgV2YWx1ZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZToCOAEi6gEKBVZhbHVlEjAKCm51bGxfdmFsdWUYASABKA4yGi5nb29nbGUucHJvdG9idWYuTnVsbFZhbHVlSAASFgoMbnVtYmVyX3ZhbHVlGAIgASgBSAASFgoMc3RyaW5nX3ZhbHVlGAMgASgJSAASFAoKYm9vbF92YWx1ZRgEIAEoCEgAEi8KDHN0cnVjdF92YWx1ZRgFIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RIABIwCgpsaXN0X3ZhbHVlGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLkxpc3RWYWx1ZUgAQgYKBGtpbmQiMwoJTGlzdFZhbHVlEiYKBnZhbHVlcxgBIAMoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZSobCglOdWxsVmFsdWUSDgoKTlVMTF9WQUxVRRAAQn8KE2NvbS5nb29nbGUucHJvdG9idWZCC1N0cnVjdFByb3RvUAFaL2dvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3N0cnVjdHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM"),V$=nc(wu,0),zM=nc(wu,1),x$=nc(wu,2);var HR;(function(e){e[e.NULL_VALUE=0]="NULL_VALUE"})(HR||(HR={}));const F$=Q_("CgpvcnRjLnByb3RvEgtpby5hZ29yYS5wYiKoAQoET1JUQxILCgNpY2UYASADKAkSJQoEZHRscxgCIAMoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSIQoEc2VuZBgDIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcBIhCgRyZWN2GAQgASgLMhMuaW8uYWdvcmEucGIuUnRwQ2FwEiYKCXNlbmRfcmVjdhgFIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcCLQAQoGUnRwQ2FwEjMKDGF1ZGlvX2NvZGVjcxgBIAMoCzIdLmlvLmFnb3JhLnBiLlBheWxvYWRBdHRyaWJ1dGUSMwoMdmlkZW9fY29kZWNzGAIgAygLMh0uaW8uYWdvcmEucGIuUGF5bG9hZEF0dHJpYnV0ZRItChBhdWRpb19leHRlbnNpb25zGAMgAygLMhMuaW8uYWdvcmEucGIuRXh0bWFwEi0KEHZpZGVvX2V4dGVuc2lvbnMYBCADKAsyEy5pby5hZ29yYS5wYi5FeHRtYXAiqQEKBkV4dG1hcBINCgVlbnRyeRgBIAEoDRIuCg5leHRlbnNpb25fbmFtZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZRIWCglkaXJlY3Rpb24YAyABKAlIAIgBARIhChRleHRlbnNpb25fYXR0cmlidXRlcxgEIAEoCUgBiAEBQgwKCl9kaXJlY3Rpb25CFwoVX2V4dGVuc2lvbl9hdHRyaWJ1dGVzIp4BChBQYXlsb2FkQXR0cmlidXRlEiQKB3J0cF9tYXAYASABKAsyEy5pby5hZ29yYS5wYi5SdHBNYXASHwoEZm10cBgCIAEoCzIRLmlvLmFnb3JhLnBiLkZtdHASLQoOcnRjcF9mZWVkYmFja3MYAyADKAsyFS5pby5hZ29yYS5wYi5GZWVkYmFjaxIUCgxwYXlsb2FkX3R5cGUYBCABKA0i4gEKBlJ0cE1hcBIfChJlbnVtX2VuY29kaW5nX25hbWUYASABKA1IAIgBARIhChRzdHJpbmdfZW5jb2RpbmdfbmFtZRgCIAEoCUgBiAEBEioKCmNsb2NrX3JhdGUYAyABKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSIAoTZW5jb2RpbmdfcGFyYW1ldGVycxgEIAEoDUgCiAEBQhUKE19lbnVtX2VuY29kaW5nX25hbWVCFwoVX3N0cmluZ19lbmNvZGluZ19uYW1lQhYKFF9lbmNvZGluZ19wYXJhbWV0ZXJzIqoCCgRGbXRwEj4KD2VudW1fcGFyYW1ldGVycxgBIAMoCzIlLmlvLmFnb3JhLnBiLkZtdHAuRW51bVBhcmFtZXRlcnNFbnRyeRJCChFzdHJpbmdfcGFyYW1ldGVycxgCIAMoCzInLmlvLmFnb3JhLnBiLkZtdHAuU3RyaW5nUGFyYW1ldGVyc0VudHJ5Gk0KE0VudW1QYXJhbWV0ZXJzRW50cnkSCwoDa2V5GAEgASgNEiUKBXZhbHVlGAIgASgLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlOgI4ARpPChVTdHJpbmdQYXJhbWV0ZXJzRW50cnkSCwoDa2V5GAEgASgJEiUKBXZhbHVlGAIgASgLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlOgI4ASLMAQoIRmVlZGJhY2sSFgoJZW51bV90eXBlGAEgASgNSACIAQESGAoLc3RyaW5nX3R5cGUYAiABKAlIAYgBARIWCglwYXJhbWV0ZXIYAyABKAlIAogBARIXCgphZGRpdGlvbmFsGAQgASgJSAOIAQESFQoIaW50ZXJ2YWwYBSABKAlIBIgBAUIMCgpfZW51bV90eXBlQg4KDF9zdHJpbmdfdHlwZUIMCgpfcGFyYW1ldGVyQg0KC19hZGRpdGlvbmFsQgsKCV9pbnRlcnZhbCKBAQoRUnRwQ2FwQmVmb3JlTWVyZ2USIQoEc2VuZBgBIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcBIhCgRyZWN2GAIgASgLMhMuaW8uYWdvcmEucGIuUnRwQ2FwEiYKCXNlbmRfcmVjdhgDIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcCKrEQoPT3J0Y05lZ290aWF0aW9uEk4KE2luX291dF9hdWRpb19wdF9tYXAYASADKAsyMS5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uSW5PdXRBdWRpb1B0TWFwRW50cnkSTgoTaW5fb3V0X3ZpZGVvX3B0X21hcBgCIAMoCzIxLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5Jbk91dFZpZGVvUHRNYXBFbnRyeRJOChNvdXRfaW5fYXVkaW9fcHRfbWFwGAMgAygLMjEuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLk91dEluQXVkaW9QdE1hcEVudHJ5Ek4KE291dF9pbl92aWRlb19wdF9tYXAYBCADKAsyMS5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uT3V0SW5WaWRlb1B0TWFwRW50cnkSYwoeaW5fb3V0X2F1ZGlvX2hlYWRlcl9leHRlbnNfbWFwGAUgAygLMjsuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLkluT3V0QXVkaW9IZWFkZXJFeHRlbnNNYXBFbnRyeRJjCh5vdXRfaW5fYXVkaW9faGVhZGVyX2V4dGVuc19tYXAYBiADKAsyOy5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uT3V0SW5BdWRpb0hlYWRlckV4dGVuc01hcEVudHJ5EmMKHmluX291dF92aWRlb19oZWFkZXJfZXh0ZW5zX21hcBgHIAMoCzI7LmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5Jbk91dFZpZGVvSGVhZGVyRXh0ZW5zTWFwRW50cnkSYwoeb3V0X2luX3ZpZGVvX2hlYWRlcl9leHRlbnNfbWFwGAggAygLMjsuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLk91dEluVmlkZW9IZWFkZXJFeHRlbnNNYXBFbnRyeRJQChRydHBfcnR4X2F1ZGlvX3B0X21hcBgJIAMoCzIyLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5SdHBSdHhBdWRpb1B0TWFwRW50cnkSUAoUcnRwX3J0eF92aWRlb19wdF9tYXAYCiADKAsyMi5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uUnRwUnR4VmlkZW9QdE1hcEVudHJ5ElAKFHJ0eF9ydHBfYXVkaW9fcHRfbWFwGAsgAygLMjIuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLlJ0eFJ0cEF1
53ZGlvUHRNYXBFbnRyeRJQChRydHhfcnRwX3ZpZGVvX3B0X21hcBgMIAMoCzIyLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5SdHhSdHBWaWRlb1B0TWFwRW50cnkSRQoOcnRwX3JlZF9wdF9tYXAYDSADKAsyLS5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uUnRwUmVkUHRNYXBFbnRyeRJFCg5yZWRfcnRwX3B0X21hcBgOIAMoCzItLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5SZWRSdHBQdE1hcEVudHJ5Eg8KB2NmZ19ydHgYDyABKAgSFQoNaGFzX2F1ZGlvX3J0eBgQIAEoCBIVCg1oYXNfdmlkZW9fcnR4GBEgASgIEhAKCGNmZ19ycnRyGBIgASgIEhYKDmhhc192aWRlb19ycnRyGBMgASgIEhYKDmhhc19hdWRpb19ycnRyGBQgASgIEg8KB2NmZ19yZWQYFSABKAgSFQoNaGFzX2F1ZGlvX3JlZBgWIAEoCBIRCglpbl9yZWRfcHQYFyADKA0aNgoUSW5PdXRBdWRpb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo2ChRJbk91dFZpZGVvUHRNYXBFbnRyeRILCgNrZXkYASABKA0SDQoFdmFsdWUYAiABKA06AjgBGjYKFE91dEluQXVkaW9QdE1hcEVudHJ5EgsKA2tleRgBIAEoDRINCgV2YWx1ZRgCIAEoDToCOAEaNgoUT3V0SW5WaWRlb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5Jbk91dEF1ZGlvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5PdXRJbkF1ZGlvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5Jbk91dFZpZGVvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5PdXRJblZpZGVvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHBSdHhBdWRpb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHBSdHhWaWRlb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHhSdHBBdWRpb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHhSdHBWaWRlb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARoyChBSdHBSZWRQdE1hcEVudHJ5EgsKA2tleRgBIAEoDRINCgV2YWx1ZRgCIAEoDToCOAEaMgoQUmVkUnRwUHRNYXBFbnRyeRILCgNrZXkYASABKA0SDQoFdmFsdWUYAiABKA06AjgBKtACChJWaWRlb0V4dGVuc2lvbk5hbWUSGQoVVklERU9fRVhUX0hEUl9UT0ZGU0VUEAASGwoXVklERU9fRVhUX0FCU19TRU5EX1RJTUUQARIZChVWSURFT19FWFRfT1JJRU5UQVRJT04QAhISCg5WSURFT19FWFRfVFdDQxADEhsKF1ZJREVPX0VYVF9QTEFZT1VUX0RFTEFZEAQSGgoWVklERU9fRVhUX0NPTlRFTlRfVFlQRRAFEhoKFlZJREVPX0VYVF9WSURFT19USU1JTkcQBhIZChVWSURFT19FWFRfQ09MT1JfU1BBQ0UQBxIWChJWSURFT19FWFRfU0RFU19NSUQQCBIgChxWSURFT19FWFRfU0RFU19SVFBfU1RSRUFNX0lEEAkSKQolVklERU9fRVhUX1NERURfUkVQQUlSRURfUlRQX1NUUkVBTV9JRBAKKsQBChJBdWRpb0V4dGVuc2lvbk5hbWUSGQoVQVVESU9fRVhUX0FVRElPX0xFVkVMEAASGwoXQVVESU9fRVhUX0FCU19TRU5EX1RJTUUQARISCg5BVURJT19FWFRfVFdDQxACEhYKEkFVRElPX0VYVF9TREVTX01JRBADEiAKHEFVRElPX0VYVF9TREVTX1JUUF9TVFJFQU1fSUQQBBIoCiRBVURJT19FWFRfU0RTX1JFUEFJUkVEX1JUUF9TVFJFQU1fSUQQBSqBAwoMRW5jb2RpbmdOYW1lEh0KGUVOQ09ESU5HX05BTUVfVU5TUEVDSUZJRUQQABIVChFFTkNPRElOR19OQU1FX1ZQOBABEhUKEUVOQ09ESU5HX05BTUVfVlA5EAISFgoSRU5DT0RJTkdfTkFNRV9IMjY0EAMSFgoSRU5DT0RJTkdfTkFNRV9IMjY1EAQSFQoRRU5DT0RJTkdfTkFNRV9BVjEQBRIWChJFTkNPRElOR19OQU1FX0c3MTEQBhIWChJFTkNPRElOR19OQU1FX0c3MjIQBxIWChJFTkNPRElOR19OQU1FX09QVVMQCBIWChJFTkNPRElOR19OQU1FX1BDTVUQCRIWChJFTkNPRElOR19OQU1FX1BDTUEQChIUChBFTkNPRElOR19OQU1FX0NOEAsSIQodRU5DT0RJTkdfTkFNRV9URUxFUEhPTkVfRVZFTlQQDBIVChFFTkNPRElOR19OQU1FX1JUWBANEhUKEUVOQ09ESU5HX05BTUVfUkVEEA4qrgMKDUZtdHBQYXJhbWV0ZXISHgoaRk1UUF9QQVJBTUVURVJfVU5TUEVDSUZJRUQQABIbChdGTVRQX1BBUkFNRVRFUl9NSU5QVElNRRABEh8KG0ZNVFBfUEFSQU1FVEVSX1VTRUlOQkFOREZFQxACEhsKF0ZNVFBfUEFSQU1FVEVSX0xFVkVMX0lEEAMSHQoZRk1UUF9QQVJBTUVURVJfUFJPRklMRV9JRBAEEhwKGEZNVFBfUEFSQU1FVEVSX1RJRVJfRkxBRxAFEhoKFkZNVFBfUEFSQU1FVEVSX1RYX01PREUQBhIqCiZGTVRQX1BBUkFNRVRFUl9MRVZFTF9BU1lNTUVUUllfQUxMT1dFRBAHEiUKIUZNVFBfUEFSQU1FVEVSX1BBQ0tFVElaQVRJT05fTU9ERRAIEiMKH0ZNVFBfUEFSQU1FVEVSX1BST0ZJTEVfTEVWRUxfSUQQCRIcChhGTVRQX1BBUkFNRVRFUl9MRVZFTF9JRFgQChIaChZGTVRQX1BBUkFNRVRFUl9QUk9GSUxFEAsSFwoTRk1UUF9QQVJBTUVURVJfVElFUhAMKrEBCgxGZWVkYmFja1R5cGUSHQoZRkVFREJBQ0tfVFlQRV9VTlNQRUNJRklFRBAAEhsKF0ZFRURCQUNLX1RZUEVfR09PR19SRU1CEAESHgoaRkVFREJBQ0tfVFlQRV9UUkFOU1BPUlRfQ0MQAhIVChFGRUVEQkFDS19UWVBFX0NDTRADEhYKEkZFRURCQUNLX1RZUEVfTkFDSxAEEhYKEkZFRURCQUNLX1RZUEVfUlJUUhAFYgZwcm90bzM",[wu]);let So=function(e){return e[e.VIDEO_EXT_HDR_TOFFSET=0]="VIDEO_EXT_HDR_TOFFSET",e[e.VIDEO_EXT_ABS_SEND_TIME=1]="VIDEO_EXT_ABS_SEND_TIME",e[e.VIDEO_EXT_ORIENTATION=2]="VIDEO_EXT_ORIENTATION",e[e.VIDEO_EXT_TWCC=3]="VIDEO_EXT_TWCC",e[e.VIDEO_EXT_PLAYOUT_DELAY=4]="VIDEO_EXT_PLAYOUT_DELAY",e[e.VIDEO_EXT_CONTENT_TYPE=5]="VIDEO_EXT_CONTENT_TYPE",e[e.VIDEO_EXT_VIDEO_TIMING=6]="VIDEO_EXT_VIDEO_TIMING",e[e.VIDEO_EXT_COLOR_SPACE=7]="VIDEO_EXT_COLOR_SPACE",e[e.VIDEO_EXT_SDES_MID=8]="VIDEO_EXT_SDES_MID",e[e.VIDEO_EXT_SDES_RTP_STREAM_ID=9]="VIDEO_EXT_SDES_RTP_STREAM_ID",e[e.VIDEO_EXT_SDED_REPAIRED_RTP_STREAM_ID=10]="VIDEO_EXT_SDED_REPAIRED_RTP_STREAM_ID",e}({}),Fd=function(e){return e[e.AUDIO_EXT_AUDIO_LEVEL=0]="AUDIO_EXT_AUDIO_LEVEL",e[e.AUDIO_EXT_ABS_SEND_TIME=1]="AUDIO_EXT_ABS_SEND_TIME",e[e.AUDIO_EXT_TWCC=2]="AUDIO_EXT_TWCC",e[e.AUDIO_EXT_SDES_MID=3]="AUDIO_EXT_SDES_MID",e[e.AUDIO_EXT_SDES_RTP_STREAM_ID=4]="AUDIO_EXT_SDES_RTP_STREAM_ID",e[e.AUDIO_EXT_SDS_REPAIRED_RTP_STREAM_ID=5]="AUDIO_EXT_SDS_REPAIRED_RTP_STREAM_ID",e}({}),or=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.VP8=1]="VP8",e[e.VP9=2]="VP9",e[e.H264=3]="H264",e[e.H265=4]="H265",e[e.AV1=5]="AV1",e[e.G711=6]="G711",e[e.G722=7]="G722",e[e.OPUS=8]="OPUS",e[e.PCMU=9]="PCMU",e[e.PCMA=10]="PCMA",e[e.CN=11]="CN",e[e.TELEPHONE_EVENT=12]="TELEPHONE_EVENT",e[e.RTX=13]="RTX",e[e.RED=14]="RED",e}({}),zr=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.MINPTIME=1]="MINPTIME",e[e.USEINBANDFEC=2]="USEINBANDFEC",e[e.LEVEL_ID=3]="LEVEL_ID",e[e.PROFILE_ID=4]="PROFILE_ID",e[e.TIER_FLAG=5]="TIER_FLAG",e[e.TX_MODE=6]="TX_MODE",e[e.LEVEL_ASYMMETRY_ALLOWED=7]="LEVEL_ASYMMETRY_ALLOWED",e[e.PACKETIZATION_MODE=8]="PACKETIZATION_MODE",e[e.PROFILE_LEVEL_ID=9]="PROFILE_LEVEL_ID",e[e.LEVEL_IDX=10]="LEVEL_IDX",e[e.PROFILE=11]="PROFILE",e[e.TIER=12]="TIER",e}({}),Ou=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.GOOG_REMB=1]="GOOG_REMB",e[e.TRANSPORT_CC=2]="TRANSPORT_CC",e[e.CCM=3]="CCM",e[e.NACK=4]="NACK",e[e.RRTR=5]="RRTR",e}({});const qM=Q_
vendor: 5,185 bytes, line 53
53("CgxzaWduYWwucHJvdG8SC2lvLmFnb3JhLnBiIuUFCg5Vc2VyQXR0cmlidXRlcxIVCghmZWF0dXJlMRgBIAEoDUgAiAEBEhUKCGZlYXR1cmUyGAIgASgNSAGIAQESHAoPdG9wblNtb290aExldmVsGAMgASgNSAKIAQESIAoTdG9wbk5ld1NwZWFrZXJEZWxheRgEIAEoDUgDiAEBEh0KEHRvcG5Td2l0Y2hIb2xkTXMYBSABKA1IBIgBARIaCg10b3BuQXVkaW9HYWluGAYgASgNSAWIAQESHAoPbWF4U3Vic2NyaXB0aW9uGAcgASgNSAaIAQESJQoYc3Vic2NyaWJlQXVkaW9GaWx0ZXJUb3BOGAggASgNSAeIAQESFQoIcnRtMkZsYWcYCSABKA1ICIgBARIWCglwcmVTdWJOdW0YCiABKA1ICYgBARIpCglwcmVTdWJVaWQYCyADKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSFAoMZW5hYmxlU3ViU1ZDGAwgAygJEhkKEWVuYWJsZVN2Y0V4dGVuZGVkGA0gAygJEhsKDmF1ZGlvRHVwbGljYXRlGA4gASgNSAqIAQESGwoObnRwRml4ZWRPZmZzZXQYDyABKAVIC4gBARIxCgtleHBlcmltZW50cxgQIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RIDIgBAUILCglfZmVhdHVyZTFCCwoJX2ZlYXR1cmUyQhIKEF90b3BuU21vb3RoTGV2ZWxCFgoUX3RvcG5OZXdTcGVha2VyRGVsYXlCEwoRX3RvcG5Td2l0Y2hIb2xkTXNCEAoOX3RvcG5BdWRpb0dhaW5CEgoQX21heFN1YnNjcmlwdGlvbkIbChlfc3Vic2NyaWJlQXVkaW9GaWx0ZXJUb3BOQgsKCV9ydG0yRmxhZ0IMCgpfcHJlU3ViTnVtQhEKD19hdWRpb0R1cGxpY2F0ZUIRCg9fbnRwRml4ZWRPZmZzZXRCDgoMX2V4cGVyaW1lbnRzIrcBChZVc2VyQXR0cmlidXRlc1Jlc3BvbnNlEiwKC3ByZVN1YlNzcmNzGAEgAygLMhcuaW8uYWdvcmEucGIuUHJlU3ViU3NyYxIlChhzdWJzY3JpYmVBdWRpb0ZpbHRlclRvcE4YAiABKA1IAIgBARIrCgpleHRlbnNpb25zGAMgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdEIbChlfc3Vic2NyaWJlQXVkaW9GaWx0ZXJUb3BOInIKClByZVN1YlNzcmMSKAoDdWlkGAEgASgLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlSACIAQESCQoBYRgCIAEoDRINCgVhX3J0eBgDIAEoDRIJCgF2GAQgASgNEg0KBXZfcnR4GAUgASgNQgYKBF91aWQizwYKDVNpZ25hbFJlcXVlc3QSFAoHbGljZW5zZRgBIAEoCUgAiAEBEg4KBnAycF9pZBgCIAEoDRISCgpzZXNzaW9uX2lkGAMgASgJEg4KBmFwcF9pZBgEIAEoCRITCgtjaGFubmVsX2tleRgFIAEoCRIUCgxjaGFubmVsX25hbWUYBiABKAkSEwoLc2RrX3ZlcnNpb24YByABKAkSFAoHYnJvd3NlchgIIAEoCUgBiAEBEioKCnByb2Nlc3NfaWQYCSABKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSDAoEbW9kZRgKIAEoCRINCgVjb2RlYxgLIAEoCRIRCgRyb2xlGAwgASgJSAKIAQESIAoTaGFzX2NoYW5nZWRfZ2F0ZXdheRgNIAEoCEgDiAEBEhMKBmV4dGVuZBgOIAEoCUgEiAEBEhkKDGNzZXJ2aWNlX21hcBgPIAEoCUgFiAEBEhoKDW9wdGlvbmFsX2luZm8YECABKAlIBogBARIZCgxhcHBfc2NlbmFyaW8YESABKAlIB4gBARIvCgphdHRyaWJ1dGVzGBIgASgLMhsuaW8uYWdvcmEucGIuVXNlckF0dHJpYnV0ZXMSEgoKcmVxdWVzdF90cxgTIAEoBBIXCgpzdHJpbmdfdWlkGBQgASgJSAiIAQESFQoIYWVzX21vZGUYFSABKAlICYgBARIXCgphZXNfc2VjcmV0GBYgASgJSAqIAQESGAoLYWVzX2VuY3J5cHQYFyABKAhIC4gBARIVCghhZXNfc2FsdBgYIAEoCUgMiAEBEiEKFGRlZmF1bHRfdmlkZW9fc3RyZWFtGBkgASgNSA2IAQFCCgoIX2xpY2Vuc2VCCgoIX2Jyb3dzZXJCBwoFX3JvbGVCFgoUX2hhc19jaGFuZ2VkX2dhdGV3YXlCCQoHX2V4dGVuZEIPCg1fY3NlcnZpY2VfbWFwQhAKDl9vcHRpb25hbF9pbmZvQg8KDV9hcHBfc2NlbmFyaW9CDQoLX3N0cmluZ191aWRCCwoJX2Flc19tb2RlQg0KC19hZXNfc2VjcmV0Qg4KDF9hZXNfZW5jcnlwdEILCglfYWVzX3NhbHRCFwoVX2RlZmF1bHRfdmlkZW9fc3RyZWFtIl8KEk11bHRpVW5pbGJzUmVxdWVzdBILCgN1cmkYASABKA0SJwoGZGV0YWlsGAIgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdBITCgtzZXJ2aWNlX2lkcxgDIAMoDSKtAQoSU2RwRW5kcG9pbnRSZXF1ZXN0Ei8KBnVuaWxicxgBIAMoCzIfLmlvLmFnb3JhLnBiLk11bHRpVW5pbGJzUmVxdWVzdBILCgN1aWQYAiABKA0SDAoEb3BpZBgDIAEoBBIqCgZzaWduYWwYBCABKAsyGi5pby5hZ29yYS5wYi5TaWduYWxSZXF1ZXN0Eh8KBG9ydGMYBSABKAsyES5pby5hZ29yYS5wYi5PUlRDIvQCChNTZHBFbmRwb2ludFJlc3BvbnNlEicKBmRldGFpbBgBIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSEAoIZW50ZXJfdHMYAiABKAQSEAoIbGVhdmVfdHMYAyABKAQSDAoEb3BpZBgEIAEoBBI5Cg91bmlsYnNfcmVzcG9uc2UYBSADKAsyIC5pby5hZ29yYS5wYi5NdWx0aVVuaWxic1Jlc3BvbnNlEgsKA3VpZBgGIAEoDRJAChNhdHRyaWJ1dGVzX3Jlc3BvbnNlGAcgASgLMiMuaW8uYWdvcmEucGIuVXNlckF0dHJpYnV0ZXNSZXNwb25zZRIUCgxyZWpvaW5fdG9rZW4YCCABKAkSMAoIYWRkX29ydGMYCSABKAsyHi5pby5hZ29yYS5wYi5SdHBDYXBCZWZvcmVNZXJnZRIwCghkZWxfb3J0YxgKIAEoCzIeLmlvLmFnb3JhLnBiLlJ0cENhcEJlZm9yZU1lcmdlIq4BChNNdWx0aVVuaWxic1Jlc3BvbnNlEgwKBGNlcnQYASABKAkSCwoDY2lkGAIgASgNEgwKBGNvZGUYAyABKA0SJwoGZGV0YWlsGAQgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdBIqCghzZXJ2aWNlcxgFIAMoCzIYLmlvLmFnb3JhLnBiLlNlcnZpY2VJbmZvEgwKBGZsYWcYBiABKA0SCwoDdXJpGAcgASgNIkkKC1NlcnZpY2VJbmZvEgoKAmlwGAEgASgJEgwKBHBvcnQYAiABKA0SEwoLZmluZ2VycHJpbnQYAyABKAkSCwoDaWNlGAQgAygJIn0KCkFQUmVzcG9uc2USCwoDdWlkGAEgASgNEgsKA2NpZBgCIAEoDRIMCgRjZXJ0GAMgASgJEicKBmRldGFpbBgEIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSEwoGdGlja2V0GAUgASgJSACIAQFCCQoHX3RpY2tldCK9AQoNSm9pbkZvcndhcmRlchISCgpyZWpvaW5fa2V5GAEgASgJEioKBnNpZ25hbBgCIAEoCzIaLmlvLmFnb3JhLnBiLlNpZ25hbFJlcXVlc3QSCwoDaWNlGAMgAygJEjEKC25lZ290aWF0aW9uGAQgASgLMhwuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uEiwKC2FwX3Jlc3BvbnNlGAUgASgLMhcuaW8uYWdvcmEucGIuQVBSZXNwb25zZSrbBQoVVXNlckF0dHJpYnV0ZUZlYXR1cmUxEg8KC1VOU1BFQ0lGSUVEEAASGgoWZW5hYmxlRW5jb2RlZFRyYW5zZm9ybRABEhcKE2VuYWJsZUF1ZGlvTWV0YWRhdGEQAhISCg5lbmFibGVBdWRpb1B0cxAEEh0KGWVuYWJsZU5ldHdvcmtRdWFsaXR5UHJvYmUQCBIbChdlbmFibGVQdWJsaXNoZWRVc2VyTGlzdBAQEhwKGGVuYWJsZVB1Ymxpc2hBdWRpb0ZpbHRlchAgEhoKFmVuYWJsZVVzZXJMaWNlbnNlQ2hlY2sQQBIOCgllbmFibGVSVFgQgAESFAoPZW5hYmxlTlRQUmVwb3J0EIACEhcKEmVuYWJsZUluc3RhbnRWaWRlbxCABBIZChRlbmFibGVGdWxsbGlua0F2U3luYxCACBIWChFlbmFibGVEYXRhU3RyZWFtMhCAEBIWChFlbmFibGVBdXRGZWVkYmFjaxCAIBIhChxlbmFibGVVc2VyQXV0b1JlYmFsYW5jZUNoZWNrEIBAEg4KCGVuYWJsZVhSEICAARIYChJlbmFibGVMb3NzYmFzZWRCd2UQgIACEhEKC2VuYWJsZUF1dENDEICABBIWChBlbmFibGVDQ0ZhbGxiYWNrEICACBIWChBlbmFibGVQcmVhbGxvY1BDEICAEBITCg1lbmFibGVQdWJUV0NDEICAIBITCg1lbmFibGVTdWJUV0NDEICAQBITCgxlbmFibGVQdWJSVFgQgICAARITCgxlbmFibGVTdWJSVFgQgICAAhIcChVlbmFibGVRdWFsaXR5RmFsbGJhY2sQgICABBIcChVzZW50dHNVc2VzQWJzU2VuZFRpbWUQgICACBIbChRlbmFibGVEdWFsU3RyZWFtRmxhZxCAgIAQEhEKCmRpc2FibGVGRUMQgICAIBIYChFlbmFibGVWb3NGYWxsYmFjaxCAgIBAYgZwcm90bzM",[w
53u,F$]),ZM=nc(qM,5),QM=nc(qM,6);let $M=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.enableEncodedTransform=1]="enableEncodedTransform",e[e.enableAudioMetadata=2]="enableAudioMetadata",e[e.enableAudioPts=4]="enableAudioPts",e[e.enableNetworkQualityProbe=8]="enableNetworkQualityProbe",e[e.enablePublishedUserList=16]="enablePublishedUserList",e[e.enablePublishAudioFilter=32]="enablePublishAudioFilter",e[e.enableUserLicenseCheck=64]="enableUserLicenseCheck",e[e.enableRTX=128]="enableRTX",e[e.enableNTPReport=256]="enableNTPReport",e[e.enableInstantVideo=512]="enableInstantVideo",e[e.enableFulllinkAvSync=1024]="enableFulllinkAvSync",e[e.enableDataStream2=2048]="enableDataStream2",e[e.enableAutFeedback=4096]="enableAutFeedback",e[e.enableUserAutoRebalanceCheck=8192]="enableUserAutoRebalanceCheck",e[e.enableXR=16384]="enableXR",e[e.enableLossbasedBwe=32768]="enableLossbasedBwe",e[e.enableAutCC=65536]="enableAutCC",e[e.enableCCFallback=131072]="enableCCFallback",e[e.enablePreallocPC=262144]="enablePreallocPC",e[e.enablePubTWCC=524288]="enablePubTWCC",e[e.enableSubTWCC=1048576]="enableSubTWCC",e[e.enablePubRTX=2097152]="enablePubRTX",e[e.enableSubRTX=4194304]="enableSubRTX",e[e.enableQualityFallback=8388608]="enableQualityFallback",e[e.senttsUsesAbsSendTime=16777216]="senttsUsesAbsSendTime",e[e.enableDualStreamFlag=33554432]="enableDualStreamFlag",e[e.disableFEC=67108864]="disableFEC",e[e.enableVosFallback=134217728]="enableVosFallback",e}({});const YR={VP8:or.VP8,VP9:or.VP9,H264:or.H264,H265:or.H265,AV1:or.AV1,G711:or.G711,G722:or.G722,opus:or.OPUS,PCMU:or.PCMU,PCMA:or.PCMA,CN:or.CN,"telephone-event":or.TELEPHONE_EVENT,rtx:or.RTX,red:or.RED},XR={minptime:zr.MINPTIME,useinbandfec:zr.USEINBANDFEC,"level-id":zr.LEVEL_ID,"profile-id":zr.PROFILE_ID,"tier-flag":zr.TIER_FLAG,"tx-mode":zr.TX_MODE,"level-asymmetry-allowed":zr.LEVEL_ASYMMETRY_ALLOWED,"packetization-mode":zr.PACKETIZATION_MODE,"profile-level-id":zr.PROFILE_LEVEL_ID,"level-idx":zr.LEVEL_IDX,profile:zr.PROFILE,tier:zr.TIER},JR={"goog-remb":Ou.GOOG_REMB,"transport-cc":Ou.TRANSPORT_CC,ccm:Ou.CCM,nack:Ou.NACK,rrtr:Ou.RRTR};function B$(e){if(e)return Object.keys(JR).find(t=>JR[t]===e)}const $_={"urn:ietf:params:rtp-hdrext:toffset":So.VIDEO_EXT_HDR_TOFFSET,"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time":So.VIDEO_EXT_ABS_SEND_TIME,"urn:3gpp:video-orientation":So.VIDEO_EXT_ORIENTATION,"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01":So.VIDEO_EXT_TWCC,"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay":So.VIDEO_EXT_PLAYOUT_DELAY,"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type":So.VIDEO_EXT_CONTENT_TYPE,"http://www.webrtc.org/experiments/rtp-hdrext/video-timing":So.VIDEO_EXT_VIDEO_TIMING,"http://www.webrtc.org/experiments/rtp-hdrext/color-space":So.VIDEO_EXT_COLOR_SPACE,"urn:ietf:params:rtp-hdrext:sdes:mid":So.VIDEO_EXT_SDES_MID,"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id":So.VIDEO_EXT_SDES_RTP_STREAM_ID,"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id":So.VIDEO_EXT_SDED_REPAIRED_RTP_STREAM_ID},eU={"urn:ietf:params:rtp-hdrext:ssrc-audio-level":Fd.AUDIO_EXT_AUDIO_LEVEL,"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time":Fd.AUDIO_EXT_ABS_SEND_TIME,"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01":Fd.AUDIO_EXT_TWCC,"urn:ietf:params:rtp-hdrext:sdes:mid":Fd.AUDIO_EXT_SDES_MID,"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id":Fd.AUDIO_EXT_SDES_RTP_STREAM_ID,"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id":Fd.AUDIO_EXT_SDS_REPAIRED_RTP_STREAM_ID};function G$(e,t,n){return(t=function(i){var r=function(o,s){if(typeof o!="object"||!o)return o;var a=o[Symbol.toPrimitive];if(a!==void 0){var c=a.call(o,"string");if(typeof c!="object")return c;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(o)}(i);return typeof r=="symbol"?r:r+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function tU(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Ut(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
53t%2?tU(Object(n),!0).forEach(function(i){G$(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):tU(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function Qt(e,t){return typeof T(e)===t?T(e):void 0}function nU(){try{const e=T("EXPERIMENTS")||{};return typeof e=="string"||Array.isArray(e)?{}:Ut({},e)}catch(e){return _.debug("handle gateway attributes failed: ",e),{}}}function j$(e,t,n){var i,r;let{mode:o,codec:s,joinGatewayStartTime:a,hasChangeBGPAddress:c}=n;const d="apResponse"in t?Object.assign({},t.apResponse):void 0;let l=!1;var h,u;d&&(l=!!T("ENABLE_AP_MULTI_IP")&&((h=d.detail)===null||h===void 0?void 0:h[5])==="multi-ip",((u=d.detail)===null||u===void 0?void 0:u[3])==="CN"&&T("ENABLE_QUALITY_FALLBACK")&&T("ENABLE_QUALITY_FALLBACK"));let p=T("REPORT_APP_SCENARIO");if(typeof p!="string")try{p=JSON.stringify(p)}catch{p=void 0}p&&p.length>128&&(p=void 0);const E=t.cloudProxyServer==="proxy3"?"1":t.cloudProxyServer==="proxy5"?"2":void 0,m=function(v,C,w,b,y){var N,k,U,X;w=Object.assign({},w);const q=Ua(v),se=yS(v),_e=((N=v.preSubOptions)===null||N===void 0?void 0:N.length)||0,me=_e>0?(k=v.preSubOptions)===null||k===void 0?void 0:k.map(f=>f.uid):void 0,ke=Qt("PRE_SUB_NUM","number")||1,We=_e>ke?_e:ke,M=nU(),F=(oO()||zg(18,4,!1))&&Ap(18,6,!0)&&C==="h264"&&T("ENABLE_ABSSENDTIME_AS_SENTTS"),J=!(((U=w.detail)===null||U===void 0?void 0:U[3])!=="CN"||!T("ENABLE_QUALITY_FALLBACK"))&&T("ENABLE_QUALITY_FALLBACK"),V=Ut(Ut({enableEncodedTransform:(!!T("ENABLE_AUDIO_METADATA")||!!T("ENABLE_AUDIO_PTS"))&&zR||!!T("ENABLE_AUDIO_TOPN")&&Rp(je.CHROME,87,116)||void 0,enableAudioMetadata:!!T("ENABLE_AUDIO_METADATA")&&zR,enableAudioPts:!!T("ENABLE_AUDIO_PTS")&&zR,topnSmoothLevel:T("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:T("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:T("TOPN_SWITCH_HOLD_MS"),topnAudioGain:T("TOPN_AUDIO_GAIN"),enableNetworkQualityProbe:v.networkQualityProbe,enablePublishedUserList:T("ENABLE_PUBLISHED_USER_LIST"),enableUserList:T("ENABLE_USER_LIST"),maxSubscription:T("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:Qt("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:Qt("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:Qt("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:T("USE_PUB_RTX")===!0||T("USE_SUB_RTX")===!0||void 0,disableFEC:T("DISABLE_FEC"),enableNTPReport:!!T("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:se,enableFulllinkAvSync:!!T("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:Qt("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:cN(),rtm2Flag:typeof b=="number"?b:void 0,enableUserAutoRebalanceCheck:!!T("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:Qt("USE_XR","boolean"),enableLossbasedBwe:Qt("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:aN(),enableCCFallback:Qt("ENABLE_CC_FALLBACK","boolean"),preSubUid:q?me:void 0,preSubNum:q?We:void 0,enablePubTWCC:Qt("PUBLISH_TWCC","boolean"),enableSubTWCC:Qt("SUBSCRIBE_TWCC","boolean"),enablePubRTX:Qt("USE_PUB_RTX","boolean"),enableSubRTX:Qt("USE_SUB_RTX","boolean"),enableSubSVC:T("ENABLE_SVC")?T("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(T("SVC"))&&T("SVC").length!==0?T("SVC"):void 0,enableSvcExtended:T("ENABLE_SVC")&&Array.isArray(T("SVC_EXTENDED"))&&T("SVC_EXTENDED").length!==0?T("SVC_EXTENDED"):void 0,enableVosFallback:T("ENABLE_VOS_FALLBACK"),enableQualityFallback:J},M),{},{audioDuplicate:Qt("ENABLE_AUDIO_RED","boolean")?(X=Qt("AUDIO_DUPLICATE_NUM","number"))!==null&&X!==void 0?X:2:void 0,senttsUsesAbsSendTime:!!F||void 0,enableDualStreamFlag:Qt("ENABLE_DUAL_STREAM_FLAG","boolean")});for(const f in V)V[f]===void 0&&delete V[f],Array.isArray(V[f])&&V[f].length===0&&delete V[f],f==="enablePreallocPC"&&delete V[f];return V.enablePreallocPC=!0,V}(e,s,d,t.rtmFlag),g=Ut(Ut(Ut(Ut(Ut({},t.license?{license:t.license}:{}),{},{p2pId:e.p2pId,sessionId:t.sid,appId:t.appId,channelKey:(i=t.token)!==null&&i!==void 0?i:t.appId,channelName:t.cname,sdkVersion:qi,processId:T("PROCESS_ID"),mode:e.useP2P?"p2p":o,codec:s,role:(r=t.role)!==null&&r!==void 0?r:"audience",hasChangedGateway:l||c,extend:T("JOIN_EXTEND")},E?{cservice_map:E}:{}),t.optionalInfo?{optionalInfo:t.optionalInfo}:{}),p?{appScenario:p}:{}),{},{attributes:W$(m),requestTs:(R=a,Number(R))});var R;return t.stringUid&&(g.stringUid=t.stringUid),t.aesmode&&t.aespassword&&(g.aesMode=t.aesmode,T("ENCRYPT_AES")?(g.aesSecret=t.aespassword,g.aesEncrypt=!0):g.aesSecret=t.aespassword,t.aessalt&&(g.aesSalt=t.aessalt)),t.defaultVideoStream!==void 0&&(g.defaultVideoStream
53=t.defaultVideoStream),g}const zR=Ur(87)||Jg()||vp(117);function W$(e){const t={enableSubSVC:[],enableSvcExtended:[]},n=["topnSmoothLevel","topnNewSpeakerDelay","topnSwitchHoldMs","topnAudioGain","maxSubscription","subscribeAudioFilterTopN","rtm2Flag","preSubNum","enableSubSVC","enableSvcExtended","audioDuplicate","preSubUid"],i={};for(const a in $M){const c=$M[a];typeof c=="number"&&c!==0&&(i[a]=c)}const r=[],o={};for(const a in e){const c=e[a];if(a in i&&c===!0){const d=i[a];let l,h;for(d<4294967296?(l=0,h=d):(l=1,h=1<<Math.floor(Math.log2(d))-32);r.length<=l;)r.push(0);r[l]|=h}else x(n).call(n,a)?t[a]=c:a in i||(o[a]=c)}r.length>0&&r.forEach((a,c)=>{a!==void 0&&a!==0&&(t["feature".concat(c+1)]=a)});const s=Object.keys(o);s.length>0&&(t.experiments=o,s.forEach(a=>{a in t&&delete t[a]}));for(const a in t)t[a]===void 0&&delete t[a],Array.isArray(t[a])&&t[a].length===0&&delete t[a];return t}function Bd(e){var t,n,i,r;const o=function(u){if(u)return YR[u]||void 0}((t=e.rtpMap)===null||t===void 0?void 0:t.encodingName),s=o||(n=e.rtpMap)===null||n===void 0?void 0:n.encodingName,a=(i=e.rtpMap)===null||i===void 0?void 0:i.encodingParameters,c=(r=e.fmtp)===null||r===void 0?void 0:r.parameters;let d,l;c&&Object.keys(c).forEach(u=>{const p=function(E){if(E)return XR[E]||void 0}(u);p?(d||(d={}),d[p]=c[u]+""):(l||(l={}),l[u]=c[u]+"")});const h=d||l?Ut(Ut({},d?{enumParameters:d}:{}),l?{stringParameters:l}:{}):void 0;return Ut(Ut({payloadType:e.payloadType,rtpMap:e.rtpMap?Ut(Ut(Ut({},o?{enumEncodingName:o}:{}),s?{stringEncodingName:s}:{}),{},{clockRate:e.rtpMap.clockRate+""},a?{encodingParameters:a}:{}):void 0},h?{fmtp:h}:{}),{},{rtcpFeedbacks:e.rtcpFeedbacks.map(u=>{const p=function(m){if(m)return JR[m]||void 0}(u.type),E=Ut(Ut(Ut({},"parameter"in u&&u.parameter?{parameter:u.parameter}:{}),"additional"in u&&u.additional?{additional:u.additional}:{}),"interval"in u&&u.interval?{interval:u.interval}:{});return Ut(p?{enumType:p}:{stringType:u.type},E)})})}function Qs(e){let t;if(e.rtpMap){const{enumEncodingName:r,stringEncodingName:o,clockRate:s,encodingParameters:a}=e.rtpMap;t={encodingName:(r?function(d){if(d)return Object.keys(YR).find(l=>YR[l]===d)}(r):o)??"",clockRate:(s==null?void 0:s.kind.value)+"",encodingParameters:a}}const n={parameters:{}};if(e.fmtp){const{enumParameters:r,stringParameters:o}=e.fmtp;r&&Object.keys(r).forEach(s=>{const a=function(c){if(c)return Object.keys(XR).find(d=>XR[d]===c)}(s);a&&(n.parameters[a]=r[s].kind.value+"")}),o&&Object.keys(o).forEach(s=>{n.parameters[s]=o[s].kind.value+""})}let i=[];return e.rtcpFeedbacks&&(i=e.rtcpFeedbacks.map(r=>{const{enumType:o,stringType:s,parameter:a,additional:c,interval:d}=r,l=Ut(Ut(Ut({},a?{parameter:a}:{}),c?{additional:c}:{}),d?{interval:d}:{});return Ut(o?{type:B$(o)+""}:{type:s+""},l)})),{payloadType:e.payloadType,rtpMap:t,fmtp:n,rtcpFeedbacks:i}}function Gd(e,t){const n=function(i,r){if(i==="video"){const o=$_[r];return typeof o=="number"?o:void 0}if(i==="audio"){const o=$_[r];return typeof o=="number"?o:void 0}}(e,t.extensionName);return{entry:t.entry,extensionName:typeof n=="number"?n:t.extensionName}}function $s(e,t){var n,i;const r=function(o,s){if(s||typeof s=="number")return o==="video"?Object.keys($_).find(a=>$_[a]===s):Object.keys(eU).find(a=>eU[a]===s)}(e,Number((n=t.extensionName)===null||n===void 0?void 0:n.kind.value))||((i=t.extensionName)===null||i===void 0?void 0:i.kind.value);return{entry:t.entry,extensionName:r+""}}function K$(e){var t,n,i,r,o,s,a,c,d,l,h,u,p,E,m,g,R,v,C,w,b,y,N,k;const U={audioCodecs:(t=(n=e.rtpCapabilities.send)===null||n===void 0?void 0:n.audioCodecs.map(se=>Bd(se)))!==null&&t!==void 0?t:[],videoCodecs:(i=(r=e.rtpCapabilities.send)===null||r===void 0?void 0:r.videoCodecs.map(se=>Bd(se)))!==null&&i!==void 0?i:[],audioExtensions:(o=(s=e.rtpCapabilities.send)===null||s===void 0?void 0:s.audioExtensions.map(se=>Gd("audio",se)))!==null&&o!==void 0?o:[],videoExtensions:(a=(c=e.rtpCapabilities.send)===null||c===void 0?void 0:c.videoExtensions.map(se=>Gd("video",se)))!==null&&a!==void 0?a:[]},X={audioCodecs:(d=(l=e.rtpCapabilities.recv)===null||l===void 0?void 0:l.audioCodecs.map(se=>Bd(se)))!==null&&d!==void 0?d:[],videoCodecs:(h=(u=e.rtpCapabilities.recv)===null||u===void 0?void 0:u.videoCodecs.map(se=>Bd(se)))!==null&&h!==void 0?h:[],audioExtensions:(p=(E=e.rtpCapabilities.recv)===null||E===void 0?void 0:E.audioExtensions.map(se=>Gd("audio",se)))!==null&&p!==void 0?p:[],videoExtensions:(m=(g=e.rtpCapabilities.recv)===null||g===void 0?void 0:g.videoExtensions.map(se=>Gd("video",se)))!==null&&m!==void 0?m:[]},q={audioCodecs:(R=(v=e.rtpCapabilities.sendrecv)===null||v===void 0?void 0:v.audioCodecs.map(se=>Bd(se)))!==null&&R!==void 0?R:[],videoCodecs:(C=(w=e.rtpCapabilities.sendrecv)===null||w===void 0?void 0:w.videoCodecs.map(se=>Bd(se)))!==null&&C!==void 0?C:[],audioExtensions:(b=(y=e.rtpCapabilities.sendrecv)===null||y===void 0?void 0:y.audioExtensions.map(se=>Gd("audio",se)))!==null&&b!==void 0?b:[],videoExtensions:(N=(k=e.rtpCapabilities.sendrecv)===null||k===void 0?void 0:k.videoExtensions.map(se=>Gd("video",se)))!==null&&N!==void 0?N:[]};return{ice:[e.iceParameters.iceUfrag,e.iceParameters.icePwd],dtls:e.dtlsParameters.fingerprints.map(se=>({[se.hashFunction]:se.fingerprint})),send:U,recv:X,sendRecv:q}}function H$(e,t,n){var i,r,o,s,a,c,d,l,h,u,p,E,m,g,R,v,C,w,b,y,N,k,U,X,q,se,_e,me,ke,We,M,F;t&&t.sendRecv&&(t.send={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...((C=t.send)===null||C===void 0?void 0:C.audioCodecs)||[],...t.sendRecv.audioCodecs],videoCodecs:[...((w=t.send)===null||w===void 0?void 0:w.videoCodecs)||[],...t.sendRecv.videoCodecs],audioExtensions:[...((b=t.send)===null||b===void 0?void 0:b.audioExtensions)||[],...t.sendRecv.audioExtensions],videoExtensions:[...((y=t.send)===null||y===void 0?void 0:y.videoExtensions)||[],...t.sendRecv.videoExtensions]},t.recv={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...((N=t.recv)===null||N===void 0?void 0:N.audioCodecs)||[],...t.sendRecv.audioCodecs],videoCodecs:[...((k=t.recv)===null||k===void 0?void 0:k.videoCodecs)||[],...t.sendRecv.videoCodecs],audioExtensions:[...((U=t.recv)===null||U===void 0?void 0:U.audioExtensions)||[],...t.sendRecv.audioExtensions],videoExtensions:[...((X=t.recv)===null||X===void 0?void 0:X.videoExtensions)||[],...t.sendRecv.videoExtensions]}),n&&n.sendRecv&&(n.send={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...((q=n.send)===null||q===void 0?void 0:q.audioCodecs)||[],...n.sendRecv.audioCodecs],videoCodecs:[...((se=n.send)===null||se===void 0?void 0:se.videoCodecs)||[],...n.sendRecv.videoCodecs],audioExtensions:[...((_e=n.send)===null||_e===void 0?void 0:_e.audioExtensions)||[],...n.sendRecv.audioExtensions],videoExtensions:[...((me=n.send)===null||me===void 0?void 0:me.videoExtensions)||[],...n.sendRecv.videoExtensions]},n.recv={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...((ke=n.recv)===null||ke===void 0?void 0:ke.audioCodecs)||[],...n.sendRecv.audioCodecs],videoCodecs:[...((We=n.recv)===null||We===void 0?void 0:We.videoCodecs)||[],...n.sendRecv.videoCodecs],audioExtensions:[...((M=n.recv)===null||M===void 0?void 0:M.audioExtensions)||[],...n.sendRecv.audioExtensions],videoExtensions:[...((F=n.recv)===null||F===void 0?void 0:F.videoExtensions)||[],...n.sendRecv.videoExtensions]});const J=t?{send:{audioCodecs:((i=t.send)===null||i===void 0?void 0:i.audioCodecs.map(ne=>Qs(ne)))||[],videoCodecs:((r=t.send)===null||r===void 0?void 0:r.videoCodecs.map(ne=>Qs(ne)))||[],audioExtensions:((o=t.send)===null||o===void 0?void 0:o.audioExtensions.map(ne=>$s("audio",ne)))||[],videoExtensions:((s=t.send)===null||s===void 0?void 0:s.videoExtensions.map(ne=>$s("video",ne)))||[]},recv:{audioCodecs:((a=t.recv)===null||a===void 0?void 0:a.audioCodecs.map(ne=>Qs(ne)))||[],videoCodecs:((c=t.recv)===null||c===void 0?void 0:c.videoCodecs.map(ne=>Qs(ne)))||[],audioExtensions:((d=t.recv)===null||d===void 0?void 0:d.audioExtensions.map(ne=>$s("audio",ne)))||[],videoExtensions:((l=t.recv)===null||l===void 0?void 0:l.videoExtensions.map(ne=>$s("video",ne)))||[]}}:void 0,V=n?{send:{audioCodecs:((h=n.send)===null||h===void 0?void 0:h.audioCodecs.map(ne=>Qs(ne)))||[],videoCodecs:((u=n.send)===null||u===void 0?void 0:u.videoCodecs.map(ne=>Qs(ne)))||[],audioExtensions:((p=n.send)===null||p===void 0?void 0:p.audioExtensions.map(ne=>$s("audio",ne)))||[],videoExtensions:((E=n.send)===null||E===void 0?void 0:E.videoExtensions.map(ne=>$s("video",ne)))||[]},recv:{audioCodecs:((m=n.recv)===null||m===void 0?void 0:m.audioCodecs.map(ne=>Qs(ne)))||[],videoCodecs:((g=n.recv)===null||g===void 0?void 0:g.videoCodecs.map(ne=>Qs(ne)))||[],audioExtensions:((R=n.recv)===null||R===void 0?void 0:R.audioExtensions.map(ne=>$s("audio",ne)))||[],videoExtensions:((v=n.recv)===null||v===void 0?void 0:v.videoExtensions.map(ne=>$s("video",ne)))||[]}}:void 0,f={send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},{send:I,recv:O,sendrecv:B}=e;return I&&(f.send.audioCodecs.push(...I.audioCodecs),f.send.videoCodecs.push(...I.videoCodecs),f.send.audioExtensions.push(...I.audioExtensions),f.send.videoExtensions.push(...I.videoExtensions)),O&&(f.recv.audioCodecs.push(...O.audioCodecs),f.recv.videoCodecs.push(...O.videoCodecs),f.recv.audioExtensions.push(...O.audioExtensions),f.recv.videoExtensions.push(...O.videoExtensions)),B&&(f.send.audioCodecs.push(...B.audioCodecs),f.send.videoCodecs.push(...B.videoCodecs),f.send.audioExtensions.push(...B.audioExtensions),f.send.videoExtensions.push(...B.videoExtensions),f.recv.audioCodecs.push(...B.audioCodecs),f.recv.videoCodecs.push(...B.videoCodecs),f.recv.audioExtensions.push(...B.audioExtensions),f.recv.videoExtensions.push(...B.videoExtensions)),J&&(f.send.audioCodecs.push(...J.send.audioCodecs),f.send.videoCodecs.push(...J.send.videoCodecs),f.send.audioExtensions.push(...J.send.audioExtensions),f.send.videoExtensions.push(...J.send.videoExtensions),f.recv.audioCodecs.push(...J.recv.audioCodecs),f.recv.videoCodecs.push(...J.recv.videoCodecs),f.recv.audioExtensions.push(...J.recv.audioExtensions),f.recv.videoExtensions.push(...J.recv.videoExtensions)),V&&(V.send.audioCodecs.forEach(ne=>{f.send.audioCodecs=f.send.audioCodecs.filter(Ge=>Ge.payloadType!==ne.payloadType)}),V.send.videoCodecs.forEach(ne=>{f.send.videoCodecs=f.send.videoCodecs.filter(Ge=>Ge.payloadType!==ne.payloadType)}),V.send.audioExtensions.forEach(ne=>{f.send.audioExtensions=f.send.audioExtensions.filter(Ge=>Ge.entry!==ne.entry)}),V.send.videoExtensions.forEach(ne=>{f.send.videoExtensions=f.send.videoExtensions.filter(Ge=>Ge.entry!==ne.entry)}),V.recv.audioCodecs.forEach(ne=>{f.recv.audioCodecs=f.recv.audioCodecs.filter(Ge=>Ge.payloadType!==ne.payloadType)}),V.recv.videoCodecs.forEach(ne=>{f.recv.videoCodecs=f.recv.videoCodecs.filter(Ge=>Ge.payloadType!==ne.payloadType)})),{send:f.recv,recv:f.send}}function Y$(e,t){iU(t,e);const n=function(s,a){if(s===void 0)return[];if(a.fieldKind==="enum"||a.fieldKind==="scalar"){for(let c=s.length-1;c>=0;--c)if(s[c].no==a.number)return[s[c]];return[]}return s.filter(c=>c.no===a.number)}(e.$unknown,t),[i,r,o]=em(t);for(const s of n)XM(i,new NR(s.data),r,s.wireType,{readUnknownFields:!0});return o()}
53function X$(e,t,n){var i;iU(t,e);const r=((i=e.$unknown)!==null&&i!==void 0?i:[]).filter(d=>d.no!==t.number),[o,s]=em(t,n),a=new tM;vM(a,{writeUnknownFields:!0},o,s);const c=new NR(a.finish());for(;c.pos<c.len;){const[d,l]=c.tag(),h=c.skip(l,d);r.push({no:d,wireType:l,data:h})}e.$unknown=r}function em(e,t){const n=e.typeName,i=Object.assign(Object.assign({},e),{kind:"field",parent:e.extendee,localName:n}),r=Object.assign(Object.assign({},e.extendee),{fields:[i],members:[i],oneofs:[]}),o=fs(r,t!==void 0?{[n]:t}:void 0);return[go(r,o),i,()=>{const s=o[n];if(s===void 0){const a=e.message;return Iu(a)?Md(a.fields[0].scalar,a.fields[0].longAsString):fs(a)}return s}]}function iU(e,t){if(e.extendee.typeName!=t.$typeName)throw new Error("extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}const J$=3,z$=2,rU={alwaysEmitImplicit:!1,enumAsInteger:!1,useProtoFieldName:!1};function Nu(e,t){var n;const i=function(o,s){var a;if(o.desc.typeName.startsWith("google.protobuf."))switch(o.desc.typeName){case"google.protobuf.Any":return function(c,d){if(c.typeUrl==="")return{};const{registry:l}=d;let h,u;if(l&&(h=function(E,m){if(E.typeUrl==="")return;const g=m.kind=="message"?m:m.getMessage(JM(E.typeUrl));return g&&function(R,v){return R.typeUrl!==""&&(typeof v=="string"?v:v.typeName)===JM(R.typeUrl)}(E,g)?WR(g,E.value):void 0}(c,l),h&&(u=l.getMessage(h.$typeName))),!u||!h)throw new Error("cannot encode message ".concat(c.$typeName,' to JSON: "').concat(c.typeUrl,'" is not in the type registry'));let p=Nu(go(u,h),d);return(u.typeName.startsWith("google.protobuf.")||p===null||Array.isArray(p)||typeof p!="object")&&(p={value:p}),p["@type"]=c.typeUrl,p}(o.message,s);case"google.protobuf.Timestamp":return function(c){const d=1e3*Number(c.seconds);if(d<Date.parse("0001-01-01T00:00:00Z")||d>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode message ".concat(c.$typeName," to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive"));if(c.nanos<0)throw new Error("cannot encode message ".concat(c.$typeName," to JSON: nanos must not be negative"));if(c.nanos>999999999)throw new Error("cannot encode message ".concat(c.$typeName," to JSON: nanos must not be greater than 99999999"));let l="Z";if(c.nanos>0){const h=(c.nanos+1e9).toString().substring(1);l=h.substring(3)==="000000"?"."+h.substring(0,3)+"Z":h.substring(6)==="000"?"."+h.substring(0,6)+"Z":"."+h+"Z"}return new Date(d).toISOString().replace(".000Z",l)}(o.message);case"google.protobuf.Duration":return function(c){const d=Number(c.seconds),l=c.nanos;if(d>315576e6||d<-315576e6)throw new Error("cannot encode message ".concat(c.$typeName," to JSON: value out of range"));if(d>0&&l<0||d<0&&l>0)throw new Error("cannot encode message ".concat(c.$typeName," to JSON: nanos sign must match seconds sign"));let h=c.seconds.toString();if(l!==0){let u=Math.abs(l).toString();u="0".repeat(9-u.length)+u,u.substring(3)==="000000"?u=u.substring(0,3):u.substring(6)==="000"&&(u=u.substring(0,6)),h+="."+u,l<0&&d==0&&(h="-"+h)}return h+"s"}(o.message);case"google.protobuf.FieldMask":return(a=o.message).paths.map(c=>{if(LL(bd(c))!==c)throw new Error("cannot encode message ".concat(a.$typeName,' to JSON: lowerCamelCase of path name "').concat(c,'" is irreversible'));return bd(c)}).join(",");case"google.protobuf.Struct":return sU(o.message);case"google.protobuf.Value":return ZR(o.message);case"google.protobuf.ListValue":return aU(o.message);default:if(Iu(o.desc)){const c=o.desc.fields[0];return tm(c,o.get(c))}return}}(e,t);if(i!==void 0)return i;const r={};for(const o of e.sortedFields){if(!e.isSet(o)){if(o.presence==J$)throw new Error("cannot encode ".concat(o," to JSON: required field not set"));if(!t.alwaysEmitImplicit||o.presence!==z$)continue}const s=oU(o,e.get(o),t);s!==void 0&&(r[q$(o,t)]=s)}if(t.registry){const o=new Set;for(const{no:s}of(n=e.getUnknown())!==null&&n!==void 0?n:[])if(!o.has(s)){o.add(s);const a=t.registry.getExtensionFor(e.desc,s);if(!a)continue;const c=Y$(e.message,a),[d,l]=em(a,c),h=oU(l,d.get(l),t);h!==void 0&&(r[a.jsonName]=h)}}return r}function oU(e,t,n){switch(e.fieldKind){case"scalar":return tm(e,t);case"message":return Nu(t,n);case"enum":return qR(e.enum,t,n.enumAsInteger);case"list":return function(i,r){const o=i.field(),s=[];
53switch(o.listKind){case"scalar":for(const a of i)s.push(tm(o,a));break;case"enum":for(const a of i)s.push(qR(o.enum,a,r.enumAsInteger));break;case"message":for(const a of i)s.push(Nu(a,r))}return r.alwaysEmitImplicit||s.length>0?s:void 0}(t,n);case"map":return function(i,r){const o=i.field(),s={};switch(o.mapKind){case"scalar":for(const[a,c]of i)s[a]=tm(o,c);break;case"message":for(const[a,c]of i)s[a]=Nu(c,r);break;case"enum":for(const[a,c]of i)s[a]=qR(o.enum,c,r.enumAsInteger)}return r.alwaysEmitImplicit||i.size>0?s:void 0}(t,n)}}function qR(e,t,n){var i;if(typeof t!="number")throw new Error("cannot encode ".concat(e," to JSON: expected number, got ").concat(ci(t)));if(e.typeName=="google.protobuf.NullValue")return null;if(n)return t;const r=e.value[t];return(i=r==null?void 0:r.name)!==null&&i!==void 0?i:t}function tm(e,t){var n,i,r,o,s,a;switch(e.scalar){case W.INT32:case W.SFIXED32:case W.SINT32:case W.FIXED32:case W.UINT32:if(typeof t!="number")throw new Error("cannot encode ".concat(e," to JSON: ").concat((n=tc(e,t))===null||n===void 0?void 0:n.message));return t;case W.FLOAT:case W.DOUBLE:if(typeof t!="number")throw new Error("cannot encode ".concat(e," to JSON: ").concat((i=tc(e,t))===null||i===void 0?void 0:i.message));return Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case W.STRING:if(typeof t!="string")throw new Error("cannot encode ".concat(e," to JSON: ").concat((r=tc(e,t))===null||r===void 0?void 0:r.message));return t;case W.BOOL:if(typeof t!="boolean")throw new Error("cannot encode ".concat(e," to JSON: ").concat((o=tc(e,t))===null||o===void 0?void 0:o.message));return t;case W.UINT64:case W.FIXED64:case W.INT64:case W.SFIXED64:case W.SINT64:if(typeof t!="bigint"&&typeof t!="string")throw new Error("cannot encode ".concat(e," to JSON: ").concat((s=tc(e,t))===null||s===void 0?void 0:s.message));return t.toString();case W.BYTES:if(t instanceof Uint8Array)return function(c){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"std";const l=P1(d),h=d=="std";let u,p="",E=0,m=0;for(let g=0;g<c.length;g++)switch(u=c[g],E){case 0:p+=l[u>>2],m=(3&u)<<4,E=1;break;case 1:p+=l[m|u>>4],m=(15&u)<<2,E=2;break;case 2:p+=l[m|u>>6],p+=l[63&u],E=0}return E&&(p+=l[m],h&&(p+="=",E==1&&(p+="="))),p}(t);throw new Error("cannot encode ".concat(e," to JSON: ").concat((a=tc(e,t))===null||a===void 0?void 0:a.message))}}function q$(e,t){return t.useProtoFieldName?e.name:e.jsonName}function sU(e){const t={};for(const[n,i]of Object.entries(e.fields))t[n]=ZR(i);return t}function ZR(e){switch(e.kind.case){case"nullValue":return null;case"numberValue":if(!Number.isFinite(e.kind.value))throw new Error("".concat(e.$typeName," cannot be NaN or Infinity"));return e.kind.value;case"boolValue":case"stringValue":return e.kind.value;case"structValue":return sU(e.kind.value);case"listValue":return aU(e.kind.value);default:throw new Error("".concat(e.$typeName," must have a value"))}}function aU(e){return Zn(e).map(ZR)}var cU=` 54\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`,Z$=C_,Q$=fR,QR=cU,dU=_o("".replace),$$=RegExp("^["+QR+"]+"),eee=RegExp("(^|[^"+QR+"])["+QR+"]+$"),$R=function(e){return function(t){var n=Q$(Z$(t));return 1&e&&(n=dU(n,$$,"")),2&e&&(n=dU(n,eee,"$1")),n}},tee={start:$R(1),end:$R(2),trim:$R(3)},nee=Dk.PROPER,iee=Sr,lU=cU,ree=Mn(tee);zs({target:"String",proto:!0,forced:function(e){return iee(function(){return!!lU[e]()||"\u200B\x85\u180E"[e]()!=="\u200B\x85\u180E"||nee&&lU[e].name!==e})}("trim")},{trim:function(){return ree(this)}});var oee=Mn(qs("String")),see=Js,aee=oee,ev=String.prototype,uU=Ys(function(e){var t=Mn(e);return typeof e=="string"||e===ev||see(ev,e)&&t===Mn(ev)?aee:t});const hU={ignoreUnknownFields:!1},tv=new WeakMap;function cee(e,t){var n;if(!tv.has(e)){const i=new Map;for(const r of e.fields)i.set(r.name,r).set(r.jsonName,r);tv.set(e,i)}return(n=tv.get(e))===null||n===void 0?void 0:n.get(t)}function Du(e,t,n){var i;if(function(o,s,a){if(!o.desc.typeName.startsWith("google.protobuf."))return!1;switch(o.desc.typeName){case"google.protobuf.Any":return function(c,d,l){var h;if(d===null||Array.isArray(d)||typeof d!="object")throw new Error("cannot decode message ".concat(c.$typeName," from JSON: expected object but got ").concat(ci(d)));if(Object.keys(d).length==0)return;const u=d["@type"];if(typeof u!="string"||u=="")throw new Error("cannot decode message ".concat(c.$typeName,' from JSON: "@type" is empty'));const p=Y_(u).call(u,"/")?u.substring(u.lastIndexOf("/")+1):u;if(!p.length)throw new Error("cannot decode message ".concat(c.$typeName,' from JSON: "@type" is invali
54d'));const E=(h=l.registry)===null||h===void 0?void 0:h.getMessage(p);if(!E)throw new Error("cannot decode message ".concat(c.$typeName," from JSON: ").concat(u," is not in the type registry"));const m=go(E);if(p.startsWith("google.protobuf.")&&Object.prototype.hasOwnProperty.call(d,"value"))Du(m,d.value,l);else{const g=Object.assign({},d);delete g["@type"],Du(m,g,l)}(function(g,R,v){var C;v||(v=fs(U$)),v.value=RM(g,R),v.typeUrl=(C=R.$typeName,"type.googleapis.com/".concat(C))})(m.desc,m.message,c)}(o.message,s,a),!0;case"google.protobuf.Timestamp":return function(c,d){if(typeof d!="string")throw new Error("cannot decode message ".concat(c.$typeName," from JSON: ").concat(ci(d)));const l=d.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]{1,9}))?(?:Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!l)throw new Error("cannot decode message ".concat(c.$typeName," from JSON: invalid RFC 3339 string"));const h=Date.parse(l[1]+"-"+l[2]+"-"+l[3]+"T"+l[4]+":"+l[5]+":"+l[6]+(l[8]?l[8]:"Z"));if(Number.isNaN(h))throw new Error("cannot decode message ".concat(c.$typeName," from JSON: invalid RFC 3339 string"));if(h<Date.parse("0001-01-01T00:00:00Z")||h>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message ".concat(c.$typeName," from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive"));c.seconds=In.parse(h/1e3),c.nanos=0,l[7]&&(c.nanos=parseInt("1"+l[7]+"0".repeat(9-l[7].length))-1e9)}(o.message,s),!0;case"google.protobuf.Duration":return function(c,d){if(typeof d!="string")throw new Error("cannot decode message ".concat(c.$typeName," from JSON: ").concat(ci(d)));const l=d.match(/^(-?[0-9]+)(?:\.([0-9]+))?s/);if(l===null)throw new Error("cannot decode message ".concat(c.$typeName," from JSON: ").concat(ci(d)));const h=Number(l[1]);if(h>315576e6||h<-315576e6)throw new Error("cannot decode message ".concat(c.$typeName," from JSON: ").concat(ci(d)));if(c.seconds=In.parse(h),typeof l[2]!="string")return;const u=l[2]+"0".repeat(9-l[2].length);c.nanos=parseInt(u),(h<0||Object.is(h,-0))&&(c.nanos=-c.nanos)}(o.message,s),!0;case"google.protobuf.FieldMask":return function(c,d){if(typeof d!="string")throw new Error("cannot decode message ".concat(c.$typeName," from JSON: ").concat(ci(d)));d!==""&&(c.paths=d.split(",").map(l=>{if(Y_(l).call(l,"_"))throw new Error("cannot decode message ".concat(c.$typeName," from JSON: path names must be lowerCamelCase"));return LL(l)}))}(o.message,s),!0;case"google.protobuf.Struct":return fU(o.message,s),!0;case"google.protobuf.Value":return iv(o.message,s),!0;case"google.protobuf.ListValue":return gU(o.message,s),!0;default:if(Iu(o.desc)){const c=o.desc.fields[0];return s===null?o.clear(c):o.set(c,nv(c,s)),!0}return!1}}(e,t,n))return;if(t==null||Array.isArray(t)||typeof t!="object")throw new Error("cannot decode ".concat(e.desc," from JSON: ").concat(ci(t)));const r=new Map;for(const[o,s]of Object.entries(t)){const a=cee(e.desc,o);if(a){if(a.oneof){if(s===null&&a.fieldKind=="scalar")continue;const c=r.get(a.oneof);if(c!==void 0)throw new Rr(a.oneof,"oneof set multiple times by ".concat(c.name," and ").concat(a.name));r.set(a.oneof,a)}pU(e,a,s,n)}else{let c;if(o.startsWith("[")&&o.endsWith("]")&&(c=(i=n.registry)===null||i===void 0?void 0:i.getExtension(o.substring(1,o.length-1)))&&c.extendee.typeName===e.desc.typeName){const[d,l,h]=em(c);pU(d,l,s,n),X$(e.message,c,h())}if(!c&&!n.ignoreUnknownFields)throw new Error("cannot decode ".concat(e.desc,' from JSON: key "').concat(o,'" is unknown'))}}}function pU(e,t,n,i){switch(t.fieldKind){case"scalar":(function(r,o,s){s===null?r.clear(o):r.set(o,nv(o,s))})(e,t,n);break;case"enum":(function(r,o,s,a){if(nm(o,s))return void r.clear(o);const c=mU(o.enum,s,a.ignoreUnknownFields);c!==im&&r.set(o,c)})(e,t,n,i);break;case"message":(function(r,o,s,a){if(nm(o,s))return void r.clear(o);const c=r.isSet(o)?r.get(o):go(o.message);Du(c,s,a),r.set(o,c)})(e,t,n,i);break;case"list":(function(r,o,s){if(o===null)return;const a=r.field();if(!Array.isArray(o))throw new Rr(a,"expected Array, got "+ci(o));for(const c of o){const d=_U(a,c,s);d!==im&&r.add(d)}})(e.get(t),n,i);break;case"map":(function(r,o,s){if(o===null)return;const a=r.field();if(typeof o!="object"||Array.isArray(o))throw new Rr(a,"expected object, got "+ci(o));for(const[c,d]of Object.entries(o)){const l=dee(a.mapKey,c),h=_U(a,d,s);h!==im&&r.set(l,h)}})(e.get(t),n,i)}}
54function _U(e,t,n){if(e.scalar&&t!==null)return nv(e,t);if(e.message&&!nm(e,t)){const i=go(e.message);return Du(i,t,n),i}if(e.enum&&!nm(e,t))return mU(e.enum,t,n.ignoreUnknownFields);throw new Rr(e,"".concat(e.fieldKind==="list"?"list item":"map value"," must not be null"))}function nm(e,t){var n,i;return t===null&&((n=e.message)===null||n===void 0?void 0:n.typeName)!="google.protobuf.Value"&&((i=e.enum)===null||i===void 0?void 0:i.typeName)!="google.protobuf.NullValue"}const im=Symbol();function mU(e,t,n){if(t===null)return Zn(e)[0].number;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const i=Zn(e).find(r=>r.name===t);if(i!==void 0)return i.number;if(n)return im}throw new Error("cannot decode ".concat(e," from JSON: ").concat(ci(t)))}function nv(e,t){switch(e.scalar){case W.DOUBLE:case W.FLOAT:if(t==="NaN")return NaN;if(t==="Infinity")return Number.POSITIVE_INFINITY;if(t==="-Infinity")return Number.NEGATIVE_INFINITY;if(typeof t=="number"){if(Number.isNaN(t))throw new Rr(e,"unexpected NaN number");if(!Number.isFinite(t))throw new Rr(e,"unexpected infinite number");break}if(typeof t=="string"){if(t===""||uU(t).call(t).length!==t.length)break;const n=Number(t);if(!Number.isFinite(n))break;return n}break;case W.INT32:case W.FIXED32:case W.SFIXED32:case W.SINT32:case W.UINT32:return EU(t);case W.BYTES:if(typeof t=="string"){if(t==="")return new Uint8Array(0);try{return N1(t)}catch(n){const i=n instanceof Error?n.message:String(n);throw new Rr(e,i)}}}return t}function dee(e,t){switch(e){case W.BOOL:switch(t){case"true":return!0;case"false":return!1}return t;case W.INT32:case W.FIXED32:case W.UINT32:case W.SFIXED32:case W.SINT32:return EU(t);default:return t}}function EU(e){if(typeof e=="string"){if(e===""||uU(e).call(e).length!==e.length)return e;const t=Number(e);return Number.isNaN(t)?e:t}return e}function fU(e,t){if(typeof t!="object"||t==null||Array.isArray(t))throw new Error("cannot decode message ".concat(e.$typeName," from JSON ").concat(ci(t)));for(const[n,i]of Object.entries(t)){const r=fs(zM);iv(r,i),e.fields[n]=r}}function iv(e,t){switch(typeof t){case"number":e.kind={case:"numberValue",value:t};break;case"string":e.kind={case:"stringValue",value:t};break;case"boolean":e.kind={case:"boolValue",value:t};break;case"object":if(t===null)e.kind={case:"nullValue",value:HR.NULL_VALUE};else if(Array.isArray(t)){const n=fs(x$);gU(n,t),e.kind={case:"listValue",value:n}}else{const n=fs(V$);fU(n,t),e.kind={case:"structValue",value:n}}break;default:throw new Error("cannot decode message ".concat(e.$typeName," from JSON ").concat(ci(t)))}return e}function gU(e,t){if(!Array.isArray(t))throw new Error("cannot decode message ".concat(e.$typeName," from JSON ").concat(ci(t)));for(const n of t){const i=fs(zM);iv(i,n),Zn(e).push(i)}}function lee(e,t,n,i,r){let o,{opid:s,mode:a,codec:c,hasChangeBGPAddress:d=!1,ortc:l}=r;t.multiIP&&t.multiIP.gateway_ip&&(o=JSON.stringify({vocs_ip:[t.multiIP.uni_lbs_ip],vos_ip:[t.multiIP.gateway_ip]}));const h=t.role==="host"?"1":t.role==="audience"?"2":void 0,u={opid:s,unilbs:[{uri:22,detail:Ut(Ut(Ut(Ut(Ut(Ut({},n?{11:n,22:n}:{}),o?{5:o}:{}),T("USE_NEW_TOKEN")?{12:"1"}:{}),h?{17:h}:{}),t.apRequestDetail?{33:t.apRequestDetail}:{}),t.apRTM?{26:"RTM2"}:{}),serviceIds:i}],uid:t.uid||0,signal:j$(e,t,{mode:a,codec:c,joinGatewayStartTime:Date.now(),hasChangeBGPAddress:d}),ortc:K$(l)},p=function(g,R,v){const C=go(g);try{Du(C,R,function(b){return b?Object.assign(Object.assign({},hU),b):hU}(v))}catch(b){throw(w=b)instanceof Error&&Y_(z1).call(z1,w.name)&&"field"in w&&typeof w.field=="function"?new Error("cannot decode ".concat(b.field()," from JSON: ").concat(b.message),{cause:b}):b}var w;return C.message}(ZM,u),E=RM(ZM,p),m=T("ENABLE_AP_COMPRESS")?PL(E,{raw:!0}):E;return T("ENABLE_SDP_ENDPOINT_LOG")&&_.debug("[sdp-endpoint] request json",u," sdpEndpointRequestJson,length is ".concat(m.length)),m}function uee(e,t,n){var i,r,o;const s=T("ENABLE_AP_COMPRESS")?yT(n,{raw:!0}):n,a=WR(QM,new Uint8Array(s));T("ENABLE_SDP_ENDPOINT_LOG")&&_.debug("[sdp-endpoint] response json",function(u,p,E){return Nu(go(u,p),function(m){return m?Object.assign(Object.assign({},rU),m):rU}(E))}(QM,a)," sdpEndpointResponseJson,length is ".concat(n.byteLength));const c=((i=a.attributesResponse)===null||i===void 0?void 0:i.preSubSsrcs.map(u=>({a:u.a,a_rtx:u.aRtx,v:u.v,v_rtx:u.vRtx})))||[],d=(r=a.attributesResponse)===null||r===void 0?void 0:r.subscribeAudioFilterTopN,l=(o=a.attributesResponse)===null||o===void 0?void 0:o.extensions,h=a.unilbsResponse[0].detail?Number(a.unilbsResponse[0].detail[8]):void 0;
54return{detail:a.detail,enter_ts:Number(a.enterTs),leave_ts:Number(a.leaveTs),opid:Number(a.opid),response_body:a.unilbsResponse.map(u=>({buffer:{cert:u.cert,cid:u.cid,cname:e.cname,code:u.code,detail:u.detail||{},edges_services:u.services.map(p=>({ip:p.ip,port:p.port,fingerprint:p.fingerprint,iceUfrag:p.ice[0],icePwd:p.ice[1]})),flag:u.flag,uid:a.uid},uri:u.uri})),signalResponse:{attributes:{userAttributes:Ut(Ut({preSubSsrcs:c},typeof d=="number"?{subscribeAudioFilterTopN:d}:{}),l)},rejoin_token:a.rejoinToken,return_vosip:!1,uid:e.stringUid?e.stringUid:a.uid,intUid:a.uid,vid:h,rtpCapabilities:H$(t.rtpCapabilities,a.addOrtc,a.delOrtc)}}}function SU(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function rm(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?SU(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):SU(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}let rv=0;function qr(e){const t=T("TURN_DOMAINS");rv=(rv+1)%t.length;const n=t[rv]||"edge.agora.io";return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(n):(_.debug("Cannot recognized as ip address: ".concat(e,", use as host2")),e)}function om(e){try{const t=T("TURN_DOMAINS"),n=T("GATEWAY_DOMAINS").concat(t).find(i=>x(e).call(e,i));return n?e.split(".".concat(n))[0].replace(/-/g,"."):e}catch{return _.debug("serverUrlToIp error, fallback to url",e),e}}function Pu(e,t){e.addresses||(e.addresses=[]);const n=function(a,c){if(T("CONNECT_GATEWAY_WITHOUT_DOMAIN"))return a.map(h=>{let{ip:u,port:p}=h;return{address:"".concat(u,":").concat(p)}});const d=T("GATEWAY_DOMAINS");let l=d[1]&&x(c).call(c,d[1])?1:0;return a.map(h=>{let{domain_prefix:u,port:p,ip:E}=h;if(u)return{address:"".concat(u,".").concat(d[l++%d.length],":").concat(p)};const m=/^[\.\:\d]+$/.test(E),g=m?"".concat(E.replace(/[^\d]/g,"-"),".").concat(d[l++%d.length],":").concat(p):"".concat(E,":").concat(p);return m||_.debug("Cannot recognized as ip address: ".concat(E,", use as host3")),{ip:E,port:p,address:g}})}(e.addresses,t),i=Array.isArray(e.detail)&&e.detail[18];if(i&&typeof i=="string"){const a=i.split(";");for(let c=0;c<a.length;c++){var r;const d=Mn(r=a[c]).call(r);n[c]&&d&&(n[c].ip6=d)}}const o=e.detail&&e.detail.candidate;let s;if(o){const[a,c]=o.split(":");a&&c&&(s={port:Number(c),ip:a,address:"".concat(a,":").concat(c)})}return{gatewayAddrs:n,apGatewayAddress:s,uid:e.uid,cid:e.cid,cert:e.cert,vid:e.detail&&e.detail[8],uni_lbs_ip:e.detail&&e.detail[1],res:e,csIp:e.detail&&e.detail[502]}}function mi(e){return typeof e=="number"?e:e.exact||e.ideal||e.max||e.min||0}function TU(e){const t=e._encoderConfig;if(!t)return{};const n={resolution:t.width&&t.height?"".concat(mi(t.width),"x").concat(mi(t.height)):void 0,maxVideoBW:t.bitrateMax,minVideoBW:t.bitrateMin};return typeof t.frameRate=="number"?(n.maxFrameRate=t.frameRate,n.minFrameRate=t.frameRate):t.frameRate&&(n.maxFrameRate=t.frameRate.max||t.frameRate.ideal||t.frameRate.exact||t.frameRate.min,n.minFrameRate=t.frameRate.min||t.frameRate.ideal||t.frameRate.exact||t.frameRate.max),n}function sm(e){return e>=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0}function ic(e,t){let n,i,r;switch(t){case Dt.CHOOSE_SERVER:i=4096,r="choose server";break;case Dt.CLOUD_PROXY:i=1048576,r="proxy";break;case Dt.CLOUD_PROXY_5:i=4194304,r="proxy5";break;case Dt.CLOUD_PROXY_FALLBACK:i=4194310,r="proxy fallback";break;default:throw new D(A.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:e.detail&&e.detail[502],retry:!1})}if(e.response_body.forEach(o=>{o.buffer&&o.buffer.flag===i&&(n={code:o.buffer.code,addresses:(o.buffer.edges_services||[]).map(s=>rm(rm({},s),{},{ticket:o.buffer.cert})),server_ts:e.enter_ts,uid:o.buffer.uid,cid:o.buffer.cid,cname:o.buffer.cname,detail
54:rm(rm({},o.buffer.detail),e.detail),flag:o.buffer.flag,opid:e.opid,cert:o.buffer.cert,signalResponse:"signalResponse"in e?e.signalResponse:void 0})}),!n)throw new D(A.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return n}async function RU(e,t){return await K.all(e.addresses.map(async n=>({address:qr(n.ip),tcpport:n.port,udpport:n.port,username:t&&T("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():zt.username,password:t&&T("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await eS(t.toString()):zt.password})))}function ov(e,t){const n=t.getMediaStreamTrack(!0).getSettings(),i=t.videoHeight||n.height,r=t.videoWidth||n.width;return i&&r?Math.max(Math.min(i,r)/Math.min(mi(e.height),mi(e.width)),1):(_.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function ea(e){let{candidateType:t,relayProtocol:n,type:i,address:r,port:o,protocol:s}=e;const a={candidateType:t,relayProtocol:n,protocol:s};if(i!=="local-candidate"){const c=r.split(".");c.length>=4&&(c[1]="*",c[2]="*"),a.address=c.join("."),a.port=o}return a}function Ko(e){const t=e.split(":"),n=e.split(/[-.]/),i=x(e).call(e,"-")?"-":".";let r=e;return t.length>1?n.length>1?(n[1]="**",r=n[0]+i+"**:"+t[t.length-1]):r=t.length>2?t[0]+i+"**:"+t[t.length-1]:"**:"+t[t.length-1]:n.length>1&&(r=n[0]+i+"**"),r}function vU(e,t){return e.getTransceivers().find(n=>n.sender.track===t||n.receiver.track===t)}function Lu(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:T("SVC_MODE");if(T("ENABLE_SVC"))return function(t){return t in Op}(e)?e:Op.L1T3}const AU={[$.VIDEO]:[{key:"abs-send-time",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"},{key:"video-orientation",extensionName:"urn:3gpp:video-orientation"},{key:"draft-holmer-rmcat-transport-wide-cc-extensions-01",extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"},{key:"playout-delay",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"},{key:"video-content-type",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type"},{key:"color-space",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/color-space"},{key:"video-timing",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing"}],[$.AUDIO]:[{key:"ssrc-audio-level",extensionName:"urn:ietf:params:rtp-hdrext:ssrc-audio-level"},{key:"draft-holmer-rmcat-transport-wide-cc-extensions-01",extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"},{key:"abs-send-time",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"}]};function CU(e){e.send&&(jd($.VIDEO,e.send.videoExtensions),jd($.AUDIO,e.send.audioExtensions)),e.recv&&(jd($.VIDEO,e.recv.videoExtensions),jd($.AUDIO,e.recv.audioExtensions)),e.sendrecv&&(jd($.VIDEO,e.sendrecv.videoExtensions),jd($.AUDIO,e.sendrecv.audioExtensions))}function yU(e,t){e.send&&(am($.VIDEO,e.send.videoExtensions,t.send.videoExtensions),am($.AUDIO,e.send.audioExtensions,t.send.audioExtensions)),e.recv&&(am($.VIDEO,e.recv.videoExtensions,t.recv.videoExtensions),am($.AUDIO,e.recv.audioExtensions,t.recv.audioExtensions))}function am(e,t,n){t.forEach(i=>{var r;const o=AU[e].find(a=>{var c;let{key:d}=a;return x(c=i.extensionName).call(c,d)});if(!o)return;const s=n.find(a=>{let{extensionName:c}=a;return x(c).call(c,o.key)});s&&x(r=s.extensionName).call(r,"gdpr_forbidden")&&(i.extensionName=s.extensionName)})}function jd(e,t){t.forEach(n=>{var i;const r=AU[e].find(o=>{var s;let{key:a}=o;return x(s=n.extensionName).call(s,a)});x(i=n.extensionName).call(i,"gdpr_forbidden")&&r&&(n.extensionName=r.extensionName)})}function IU(e){return e==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"||x(e).call(e,"abs-send-time")}function cm(e){return e==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"||x(e).call(e,"draft-holmer-rmcat-transport-wide-cc-extensions-01")}function bU(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function wU(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
54t%2?bU(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):bU(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function ku(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=arguments.length>3?arguments[3]:void 0;const{filterRTX:r,filterVideoFec:o,filterAudioFec:s,filterAudioCodec:a,filterVideoCodec:c,unsupportedVideoUplinkCodec:d,unsupportedVideoDownlinkCodec:l}=t,{useXR:h}=n;let u=[],p=[],E=[],m=[],g=!1,R=!1;if(ii(e).mediaDescriptions.forEach(C=>{i&&i!==C.attributes.direction||(C.media.mediaType!=="video"||g||(p=C.attributes.payloads,m=C.attributes.extmaps,g=!0),C.media.mediaType!=="audio"||R||(u=C.attributes.payloads,E=C.attributes.extmaps,R=!0))}),!m||p.length===0)throw new Error("Cannot get video capabilities from SDP.");if(!E||u.length===0)throw new Error("Cannot get audio capabilities from SDP.");if(p.forEach(C=>{var w;(w=C.rtpMap)!==null&&w!==void 0&&w.clockRate&&(C.rtpMap.clockRate=parseInt(C.rtpMap.clockRate)),h&&C.rtcpFeedbacks.push({type:"rrtr"})}),u.forEach(C=>{var w;(w=C.rtpMap)!==null&&w!==void 0&&w.clockRate&&(C.rtpMap.clockRate=parseInt(C.rtpMap.clockRate)),h&&C.rtcpFeedbacks.push({type:"rrtr"})}),r&&(u=u.filter(C=>{var w;return((w=C.rtpMap)===null||w===void 0?void 0:w.encodingName.toLowerCase())!=="rtx"}),p=p.filter(C=>{var w;return((w=C.rtpMap)===null||w===void 0?void 0:w.encodingName.toLowerCase())!=="rtx"})),o){const C=p.filter(y=>{var N;return/(red)|(ulpfec)|(flexfec)/i.test(((N=y.rtpMap)===null||N===void 0?void 0:N.encodingName)||"")}),w=ta(C,p).map(y=>y.payloadType),b=[...C.map(y=>y.payloadType),...w];p=p.filter(y=>!x(b).call(b,y.payloadType))}if(s&&(u=u.filter(C=>{var w;return!/(red)|(ulpfec)|(flexfec)/i.test(((w=C.rtpMap)===null||w===void 0?void 0:w.encodingName)||"")})),a&&(a==null?void 0:a.length)>0&&(u=u.filter(C=>{var w;return x(a).call(a,((w=C.rtpMap)===null||w===void 0?void 0:w.encodingName.toLowerCase())||"")})),c&&(c==null?void 0:c.length)>0){const C=p.filter(w=>{var b;return x(c).call(c,((b=w.rtpMap)===null||b===void 0?void 0:b.encodingName.toLowerCase())||"")});p=C.concat(r?[]:ta(C,p))}const v=T("UNSUPPORTED_VIDEO_CODEC");if(v&&v.length>0){const C=p.filter(y=>y.rtpMap&&x(v).call(v,y.rtpMap.encodingName.toLowerCase())),w=ta(C,p),b=C.concat(w).map(y=>y.payloadType);p=p.filter(y=>!x(b).call(b,y.payloadType)),_.debug("unsupportedVideoCodec: ".concat(v,", toBeRemoved: ").concat(b))}if(d&&d.length>0&&i==="sendonly"){const C=p.filter(y=>y.rtpMap&&x(d).call(d,y.rtpMap.encodingName.toLowerCase())),w=ta(C,p),b=C.concat(w).map(y=>y.payloadType);p=p.filter(y=>!x(b).call(b,y.payloadType)),_.debug("unsupportedVideoUplinkCodec: ".concat(d,", toBeRemoved: ").concat(b))}if(l&&l.length>0&&i==="recvonly"){const C=p.filter(y=>y.rtpMap&&x(l).call(l,y.rtpMap.encodingName.toLowerCase())),w=ta(C,p),b=C.concat(w).map(y=>y.payloadType);p=p.filter(y=>!x(b).call(b,y.payloadType)),_.debug("unsupportedVideoDownlinkCodec: ".concat(l,", toBeRemoved: ").concat(b))}return{audioCodecs:u,videoCodecs:p,audioExtensions:E,videoExtensions:m}}function Ho(e){const t=ii(e);let n,i;for(const r of t.mediaDescriptions){if(!n){const o=r.attributes.iceUfrag,s=r.attributes.icePwd;if(!o||!s)throw new Error("Cannot get iceUfrag or icePwd from SDP.");n={iceUfrag:o,icePwd:s}}if(!i){const o=r.attributes.fingerprints;o.length>0&&(i={fingerprints:o})}}if(!i&&t.attributes.fingerprints.length>0&&(i={fingerprints:t.attributes.fingerprints}),!i||!n)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:n,dtlsParameters:i}}function sv(e,t){const n=[],i=e.attributes.ssrcGroups.filter(s=>s.semantic==="FID"),r=e.attributes.ssrcGroups.find(s=>s.semantic==="SIM"),o=e.attributes.ssrcs;if(r)r.ssrcIds.forEach(s=>{var a;const c=(a=i.find(d=>d.ssrcIds[0]===s))===null||a===void 0?void 0:a.ssrcIds[1];n.push({ssrcId:s,rtx:t?c:void 0})});else if(i.length>0){const s=i[0].ssrcIds[0],a=i[0].ssrcIds[1];n.push({ssrcId:s,rtx:t?a:void 0})}else{if(o.length===0)throw new Error("No ssrcs found on local media description.");n.push({ssrcId:o[0].ssrcId})}return n}function OU(e,t,n){const{cname:i}=e;let r=[];t&&(r=DU(t)),r.length===0&&(r=e.iceParameters.candidates.map(c=>({foundation:c.foundation,componentId:"1",transport:c.protocol,priority:c.priority.toString(),connectionAddress:c.ip,port:c.port.toString(),type:c.type,extension:{}})),_.debug("Using candidates from gateway."));const o={fingerprints:e.dtlsParameters.fingerprints.map(c=>({hashFunction:c.algorithm,fingerprint:c.fingerprint}))},s={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let a;
54switch(e.dtlsParameters.role){case"server":a="passive";break;case"client":a="active";break;case"auto":a="actpass"}return{dtlsParameters:o,iceParameters:s,candidates:r,rtpCapabilities:Uu(e.rtpCapabilities),setup:a,cname:i,preSSRCs:NU(n)}}function NU(e){const t=[];return Array.isArray(e)&&e.length>0&&e.forEach(n=>{t.push({kind:$.VIDEO,ssrcMsg:[{ssrcId:n.v,rtx:n.v_rtx}],mslabel:"".concat(n.v,"_").concat(n.a)},{kind:$.AUDIO,ssrcMsg:[{ssrcId:n.a}],mslabel:"".concat(n.v,"_").concat(n.a)})}),t}function DU(e){let t=[];return e.ip&&typeof e.port=="number"&&(t=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip,port:e.port.toString(),type:"host",extension:{}}],_.debug("Using remote candidate from AP ".concat(Ko(e.ip),":").concat(e.port)),e.ip6&&(t.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip6,port:e.port.toString(),type:"host",extension:{}}),_.debug("Using IPV6 remote candidate from AP ".concat(Ko(e.ip6),":").concat(e.port)))),t}function Mu(e,t,n){const i=[],r=[];return e.forEach(o=>{let{ssrcId:s,rtx:a}=o;const c=Qe(8,"track-"),d={ssrcId:s,attributes:wU({label:c,mslabel:n=n||Qe(10,""),msid:"".concat(n," ").concat(c)},t&&{cname:t})};if(i.push(d),a!==void 0){const l={ssrcId:a,attributes:wU({label:c,mslabel:n,msid:"".concat(n," ").concat(c)},t&&{cname:t})};i.push(l),r.push({semantic:"FID",ssrcIds:[s,a]})}}),e.length>1&&r.push({semantic:"SIM",ssrcIds:e.map(o=>{let{ssrcId:s}=o;return s})}),{ssrcs:i,ssrcGroups:r}}function rc(e,t){t instanceof jt&&e.attributes.payloads.forEach(n=>{var i;const r=(i=n.rtpMap)===null||i===void 0?void 0:i.encodingName.toLowerCase();if(!r||["opus","pcmu","pcma","g722"].indexOf(r)===-1)return;n.fmtp||(n.fmtp={parameters:{}}),r==="opus"&&typeof T("OPUS_PTIME")=="number"?n.fmtp.parameters.ptime=T("OPUS_PTIME"):n.fmtp.parameters.minptime="10",n.fmtp.parameters.useinbandfec="1";const o=t._encoderConfig;o&&(r!=="pcmu"&&r!=="pcma"&&r!=="g722"&&(o.bitrate&&!Rt()&&(n.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*o.bitrate))),o.sampleRate&&(n.fmtp.parameters.maxplaybackrate="".concat(o.sampleRate),n.fmtp.parameters["sprop-maxcapturerate"]="".concat(o.sampleRate)),o.stereo&&(n.fmtp.parameters.stereo="1",n.fmtp.parameters["sprop-stereo"]="1")),t instanceof Zl&&r==="opus"&&t._config.DTX&&(n.fmtp.parameters.usedtx="1"))})}function av(e){const t=e.attributes.unrecognized.findIndex(n=>n.attField==="x-google-flag"&&n.attValue==="conference");t!==-1&&e.attributes.unrecognized.splice(t,1)}function cv(e,t){var n;if(e.attributes.payloads.forEach(r=>{var o;((o=r.rtpMap)===null||o===void 0?void 0:o.encodingName.toLowerCase())==="h264"&&r.fmtp&&r.fmtp.parameters&&T("ENABLE_UP_SPS_PPS")&&(r.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")}),!(t instanceof pt&&t._encoderConfig&&t._hints.indexOf($e.SCREEN_TRACK)===-1))return;const i=t._encoderConfig;Oe().supportMinBitrate&&i.bitrateMin&&e.attributes.payloads.forEach(r=>{var o,s;x(o=["h264","h265","vp8","vp9","av1"]).call(o,((s=r.rtpMap)===null||s===void 0?void 0:s.encodingName.toLowerCase())||"")&&(r.fmtp||(r.fmtp={parameters:{}}),r.fmtp.parameters["x-google-min-bitrate"]="".concat(i.bitrateMin))}),Oe().supportMinBitrate&&!x(n=t._hints).call(n,$e.LOW_STREAM)&&i.bitrateMax&&e.attributes.payloads.forEach(r=>{var o,s;x(o=["h264","h265","vp8","vp9","av1"]).call(o,((s=r.rtpMap)===null||s===void 0?void 0:s.encodingName.toLowerCase())||"")&&(r.fmtp||(r.fmtp={parameters:{}}),r.fmtp.parameters["x-google-start-bitrate"]="".concat(T("X_GOOGLE_START_BITRATE")||Math.floor(i.bitrateMax)))})}function PU(e){if(e.media.mediaType!=="video")return;const t=Fe();if(t.name!==je.SAFARI&&t.os!==pn.IOS)return;const n=e.attributes.extmaps.findIndex(i=>/video-orientation/g.test(i.extensionName));n!==-1&&e.attributes.extmaps.splice(n,1)}function dm(e,t,n){if(!t)return;let i,r;if(e.media.mediaType==="video"?(i=n.videoExtensions,r=n.videoCodecs):(i=n.audioExtensions,r=n.audioCodecs),t.twcc===!0){const o=i.find(s=>cm(s.extensionName));if(o){const s=o.extensionName;e.attributes.extmaps.find(a=>cm(a.extensionName))||e.attributes.extmaps.push({entry:o.entry,extensionName:s}),function(a,c){return c.filter(d=>!!a.find(l=>l.payloadType===d.payloadType&&!!l.rtcpFeedbacks.find(h=>h.type==="transport-cc")))}
54(r,e.attributes.payloads).forEach(a=>{a.rtcpFeedbacks.find(c=>c.type==="transport-cc")||a.rtcpFeedbacks.push({type:"transport-cc"})})}}else if(t.twcc===!1){const o=e.attributes.extmaps.findIndex(s=>cm(s.extensionName));o!==-1&&e.attributes.extmaps.splice(o,1),e.attributes.payloads.forEach(s=>{const a=s.rtcpFeedbacks.findIndex(c=>c.type==="transport-cc");a!==-1&&s.rtcpFeedbacks.splice(a,1)})}if(t.remb===!0){const o=i.find(s=>IU(s.extensionName));if(o){const s=o.extensionName;e.attributes.extmaps.find(a=>a.extensionName===s)||e.attributes.extmaps.push({entry:o.entry,extensionName:s}),function(a,c){return c.filter(d=>!!a.find(l=>l.payloadType===d.payloadType&&!!l.rtcpFeedbacks.find(h=>h.type==="goog-remb")))}(r,e.attributes.payloads).forEach(a=>{a.rtcpFeedbacks.find(c=>c.type==="goog-remb")||a.rtcpFeedbacks.push({type:"goog-remb"})})}}else if(t.remb===!1){const o=e.attributes.extmaps.findIndex(s=>IU(s.extensionName));o!==-1&&e.attributes.extmaps.splice(o,1),e.attributes.payloads.forEach(s=>{const a=s.rtcpFeedbacks.findIndex(c=>c.type==="goog-remb");a!==-1&&s.rtcpFeedbacks.splice(a,1)})}}function dv(e,t,n){if(Rt()||e.media.mediaType!=="video"||!(t instanceof pt)||n!=="vp9"&&n!=="vp8"||n==="vp8"&&!T("SIMULCAST")||n==="vp9"&&T("ENABLE_SVC")||t._scalabilityMode===void 0||t._scalabilityMode.numSpatialLayers<=1)return;const i=n==="vp8"?2:t._scalabilityMode.numSpatialLayers,r=e.attributes.ssrcs[0],o=e.attributes.ssrcGroups.find(a=>a.semantic==="FID"&&a.ssrcIds[0]===r.ssrcId),s={semantic:"SIM",ssrcIds:[r.ssrcId]};for(let a=1;a<i;a++)e.attributes.ssrcs.push({ssrcId:r.ssrcId+a,attributes:Ct(r.attributes)}),s.ssrcIds.push(r.ssrcId+a),o&&(e.attributes.ssrcs.push({ssrcId:o.ssrcIds[1]+a,attributes:Ct(r.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[r.ssrcId+a,o.ssrcIds[1]+a]}));e.attributes.ssrcGroups.unshift(s)}async function LU(){try{const e=new RTCPeerConnection;e.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:Op.L1T3}]});const t=await e.createOffer();if(!t.sdp)return void e.close();const n=ii(t.sdp).mediaDescriptions[0];if(!n)return;const i=n.attributes.extmaps.find(r=>r.extensionName==="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension");return e.close(),i}catch{return}}async function lv(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const n=new RTCPeerConnection;n.addTransceiver("video",{direction:"sendonly"}),n.addTransceiver("audio",{direction:"sendonly"}),n.addTransceiver("video",{direction:"recvonly"}),n.addTransceiver("audio",{direction:"recvonly"});const i=(await n.createOffer()).sdp,{send:r,recv:o,sendrecv:s}=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},d=arguments.length>2?arguments[2]:void 0;const l=ku(d,a,c,"sendonly"),h=ku(d,a,c,"recvonly"),u={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},p={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},E={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Zr(l,h,"videoExtensions",u,p,E),Zr(l,h,"videoCodecs",u,p,E),Zr(l,h,"audioExtensions",u,p,E),Zr(l,h,"audioCodecs",u,p,E),T("RAISE_H264_BASELINE_PRIORITY")){const m=[],g=[];if(E.videoCodecs.forEach((R,v)=>{var C;if(((C=R.rtpMap)===null||C===void 0?void 0:C.encodingName.toLocaleLowerCase())==="h264"){var w,b;const y=E.videoCodecs[v+1],N=y&&VU(R,y),k=(w=R.fmtp)===null||w===void 0?void 0:w.parameters["profile-level-id"],U=(b=R.fmtp)===null||b===void 0?void 0:b.parameters["packetization-mode"];!k||k!==T("FIRST_H264_PROFILE_LEVEL_ID")||T("FIRST_PACKETIZATION_MODE")&&U!==T("FIRST_PACKETIZATION_MODE")?N?g.push([R,y]):g.push([R]):N?m.push([R,y]):m.push([R])}}),m.length>0&&g.length>0){_.debug("raising H264 baseline profile priority"),E.videoCodecs.forEach((v,C)=>{var w;if(((w=v.rtpMap)===null||w===void 0?void 0:w.encodingName.toLocaleLowerCase())==="h264"){const b=VU(v,E.videoCodecs[C+1]),y=m.shift()||g.shift()||[];y.length>0&&(b?E.videoCodecs.splice(C,2,...y):E.videoCodecs.splice(C,1,...y))}});const R=p.videoCodecs.filter(v=>{var C,w;return((C=v.rtpMap)===null||C===void 0?void 0:C.encodingName.toLocaleLowerCase())==="h264"&&((w=v.fmtp)===null||w===void 0?void 0:w.parameters["profile-level-id"])!==T("FIRST_H264_PROFILE_LEVEL_ID")});if(R.length>0){const v=ta(R,p.videoCodecs).map(w=>w.payloadType),C=[...R.map(w=>w.payloadType),...v];p.videoCodecs=p.videoCodecs.filter(w=>!x(C).call(C,w.payloadType))}T("FILTER_SEND_H264_BASELINE")&&(u.videoCodecs=u.videoCodecs.filter(v=>{var C,w;return!(((C=v.rtpMap)===null||C===void 0?void 0:C.encodingName.toLocaleLowerCase())==="h264"&&((w=v.fmtp)===null||w===void 0?void 0:w.parameters["profile-level-id"])!==T("FIRST_H264_PROFILE_LEVEL_ID"))}))}return{send:u,recv:p,sendrecv:E}}return{send:u,recv:p,sendrecv:E}}(e,t,i);try{n.close()}catch{}return{send:r,recv:o,sendrecv:s}}function kU(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=ku(arguments.length>2?arguments[2]:void 0,arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},"recvonly"),n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Zr(e,t,"videoExtensions",n,i,r),Zr(e,t,"videoCodecs",n,i,r),Zr(e,t,"audioExtensions",n,i,r),Zr(e,t,"audioCodecs",n,i,r),T("RAISE_H264_BASELINE_PRIORITY")){const o=r.videoCodecs.findIndex(s=>s.rtpMap&&s.rtpMap.encodingName.toLocaleLowerCase()==="h264"&&s.fmtp&&s.fmtp.parameters["profile-level-id"]==="42001f");if(o!==-1){const s=r.videoCodecs.findIndex(a=>a.rtpMap&&a.rtpMap.encodingName.toLocaleLowerCase()==="h264");if(s<o){_.debug("raising H264 baseline profile priority");const a=r.videoCodecs[o];r.videoCodecs.splice(o,1),r.videoCodecs.splice(s,0,a)}s!==-1&&(i.videoCodecs=i.videoCodecs.filter(a=>!(a.rtpMap&&a.rtpMap.encodingName.toLocaleLowerCase()==="h264"&&a.fmtp&&a.fmtp.parameters["profile-level-id"]!=="42001f")))}}return{send:n,recv:i,sendrecv:r}}function Zr(e,t,n,i,r,o){if(n==="videoExtensions"||n==="audioExtensions"){const s=[];
54return e[n].forEach(a=>{t[n].some((c,d)=>{if(a.entry===c.entry&&a.extensionName===c.extensionName)return s.push(d),!0})?o[n].push(a):i[n].push(a)}),void t[n].forEach((a,c)=>{s.indexOf(c)===-1&&r[n].push(a)})}if(n==="videoCodecs"||n==="audioCodecs"){const s=[];return e[n].forEach(a=>{t[n].some((c,d)=>{if(a.payloadType===c.payloadType&&JSON.stringify(a)===JSON.stringify(c))return s.push(d),!0})?o[n].push(a):i[n].push(a)}),void t[n].forEach((a,c)=>{s.indexOf(c)===-1&&r[n].push(a)})}}function Uu(e){const{send:t,recv:n,sendrecv:i}=e;if(!i){if(!t||!n)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:t,recv:n}}let r,o;return t?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...t.audioCodecs,...i.audioCodecs],r.videoCodecs=[...t.videoCodecs,...i.videoCodecs],r.audioExtensions=[...t.audioExtensions,...i.audioExtensions],r.videoExtensions=[...t.videoExtensions,...i.videoExtensions]):r=Ct(i),n?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...n.audioCodecs,...i.audioCodecs],o.videoCodecs=[...n.videoCodecs,...i.videoCodecs],o.audioExtensions=[...n.audioExtensions,...i.audioExtensions],o.videoExtensions=[...n.videoExtensions,...i.videoExtensions]):o=Ct(i),{send:r,recv:o}}function Wd(e){e.media.mediaType==="audio"&&e.attributes.payloads.filter(t=>{var n;return((n=t.rtpMap)===null||n===void 0?void 0:n.encodingName.toLowerCase())==="opus"}).forEach(t=>{t.fmtp||(t.fmtp={parameters:{}}),t.fmtp.parameters.stereo="1",t.fmtp.parameters["sprop-stereo"]="1"})}function Vu(e,t,n,i){let r=[];if(e===$.VIDEO){if(T("H264_PROFILE_LEVEL_ID")&&i==="h264"&&(r=t.videoCodecs.filter(o=>{var s;return x(s=o.rtpMap&&o.rtpMap.encodingName.toLowerCase()||"").call(s,i)&&o&&o.fmtp&&o.fmtp.parameters["profile-level-id"]===T("H264_PROFILE_LEVEL_ID")})),!Array.isArray(r)||r.length===0){let o=[];const s=[],a=[],c=[];if(n.videoCodecs.forEach(d=>{const l=d.rtpMap&&d.rtpMap.encodingName.toLowerCase()||"";x(l).call(l,i)?o.push(d):x(l).call(l,"vp9")?s.push(d):x(l).call(l,"vp8")?a.push(d):x(l).call(l,"h264")&&c.push(d)}),o.length===0){let d="";s.length!==0?(o=s,d="vp9"):a.length!==0?(o=a,d="vp8"):c.length!==0&&(o=c,d="h264"),_.warning("codec ".concat(i," not included in rtpCapabilities, fallback to default payloads: ").concat(d))}o.length!==0&&(r=t.videoCodecs.filter(d=>o.some(l=>l.payloadType===d.payloadType)))}if(r.length===0&&(_.warning("codec ".concat(i," not included in rtpCapabilities, fallback to default payloads: ").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),r=t.videoCodecs),T("USE_PUB_RTX")||T("USE_SUB_RTX")){const o=ta(r,t.videoCodecs);r=[...r,...o]}}else{r=t.audioCodecs.filter(s=>{var a;return x(a=s.rtpMap&&s.rtpMap.encodingName.toLowerCase()||"").call(a,i)});const o=t.audioCodecs.filter(s=>{var a;return x(a=s.rtpMap&&s.rtpMap.encodingName.toLowerCase()||"").call(a,"red")});r.length===0&&(_.warning("codec ".concat(i," not included in rtpCapabilities, fallback to opus")),r=t.audioCodecs.filter(s=>{var a;return x(a=s.rtpMap&&s.rtpMap.encodingName.toLowerCase()||"").call(a,"opus")})),T("ENABLE_AUDIO_RED")&&o.length!==0&&(r=[...o,...r])}return r}function ta(e,t){const n=e.map(i=>i.payloadType.toString());return t.filter(i=>i.rtpMap&&i.rtpMap.encodingName==="rtx"&&i.fmtp&&i.fmtp.parameters.apt&&x(n).call(n,i.fmtp&&i.fmtp.parameters.apt))}async function vi(e,t,n){const i=t.toString(),r=MU(i,"offer","remote","exchangeSDP");await e.setRemoteDescription({type:"offer",sdp:i});const o=await e.createAnswer();if(!o.sdp)throw new Error("cannot get answer sdp");let s=o.sdp;s=xu(s,n||{}),r==null||r(s||""),await e.setLocalDescription({type:"answer",sdp:s})}function xu(e,t,n){if(T("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const i=ii(e),{useXR:r}=t;return i.mediaDescriptions.forEach(o=>{var s;o.attributes.mid&&(Array.isArray(n)&&!x(n).call(n,o.attributes.mid)||(o.media.mediaType==="audio"&&Wd(o),o.media.mediaType==="video"&&function(a){a.media.mediaType==="video"&&T("ENABLE_DOWN_SPS_PPS")&&a.attributes.payloads.filter(c=>{var d;return((d=c.rtpMap)===null||d===void 0?void 0:d.encodingName.toLowerCase())==="h264"}
54).forEach(c=>{c.fmtp||(c.fmtp={parameters:{}}),c.fmtp.parameters["sps-pps-idr-in-keyframe"]="1"})}(o),r&&x(s=["audio","video"]).call(s,o.media.mediaType)&&o.attributes.payloads.forEach(a=>{a.rtcpFeedbacks.findIndex(c=>c.type==="rrtr")===-1&&a.rtcpFeedbacks.push({type:"rrtr"})})))}),as(i)}function MU(e,t,n,i){if(T("SDP_LOGGING"))return _.upload("exchanging ".concat(n," ").concat(t," SDP during P2PConnection.").concat(i,` 55`),e),t==="offer"?r=>{MU(r,"answer",n==="local"?"remote":"local",i)}:void 0}async function UU(e,t,n){try{var i;if(!Oe().supportSetRtpSenderParameters||!function(c){return c==="vp9"||c==="av1"}(e)||!T("ENABLE_SVC"))return;const r={},o={},s=t.getParameters(),a=(i=s.encodings)===null||i===void 0?void 0:i[0];o.scalabilityMode=Lu(n),a&&Object.assign(a,o),Object.assign(s,r),await t.setParameters(s),_.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(s.encodings)))}catch(r){_.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",r)}}function lm(e){const t=T("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(t)&&t.length>0)&&t.some(n=>x(e).call(e,n))}function VU(e,t){try{var n;return((n=e.fmtp)===null||n===void 0?void 0:n.parameters.apt)===t.payloadType.toString()}catch{return!1}}const xU={};function Yo(e){(!(arguments.length>1&&arguments[1]!==void 0)||arguments[1])&&_.debug("install service ".concat(e.name)),xU[e.name]=e}function To(e){const t=xU[e];if(!t)throw new L(A.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}function FU(e,t){return To("DataStream").create(e,t)}function um(){return To("InterceptFrame").create()}function uv(e,t){return!(e.length<4||e.length>256)&&!(t.length<22||t.length>256)}function BU(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Pn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?BU(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):BU(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}const hv=new Map;class hee extends Nt{get state(){return this._state}set state(t){if(t===this._state)return;const n=this._state;this._state=t,t==="DISCONNECTED"&&this._disconnectedReason?this.emit(qt.CONNECTION_STATE_CHANGE,t,n,this._disconnectedReason):this.emit(qt.CONNECTION_STATE_CHANGE,t,n)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(t){_.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(t)),this._joinGatewayStartTime=t}constructor(t,n){var i,r,o;super(),S(this,"store",void 0),S(this,"joinInfo",void 0),S(this,"key",void 0),S(this,"ntpOffset",0),S(this,"usingProxy",!1),S(this,"signal",void 0),S(this,"role",void 0),S(this,"isPreallocation",void 0),S(this,"isPreSub",void 0),S(this,"inChannelInfo",{joinAt:null,duration:0}),S(this,"spec",void 0),S(this,"_state","DISCONNECTED"),S(this,"_statsCollector",void 0),S(this,"_disconnectedReason",void 0),S(this,"isSignalRecover",!1),S(this,"hasChangeBGPAddress",!1),S(this,"trafficStatsInterval",void 0),S(this,"networkQualityInterval",void 0),S(this,"_joinGatewayStartTime",0),S(this,"_signalTimeout",!1),S(this,"_clientRoleOptions",void 0),S(this,"_isProactiveJoin",!1),this.store=t,this.spec=n,this.signal=this.store.useP2P?(i={spec:Pn(Pn({},n),{},{retryConfig:n.websocketRetryConfig}),store:t},(r=(o=To("P2PChannel")).createSubmodule)===null||r===void 0?void 0:r.call(o,i)):this.store.useDcSignal?function(s){return To("DataChannelSignal").create(s)}({spec:Pn(Pn({},n),{},{retryConfig:n.websocketRetryConfig}),store:t}):new GP(Pn(Pn({},n),{},{retryConfig:n.websocketRetryConfig}),t),this._statsCollector=n.statsCollector,this.role=n.role||"audience",this._clientRoleOptions=n.clientRoleOptions,this.handleSignalEvents()}setUsingProxy(t){this.usingProxy=t}async join(t,n,i){if(this.store.useDcSignal){let l=!1;const h=t.apResponse.addresses[0],u=h.iceUfrag||"".concat(t.apResponse.cid,"_").concat(t.apResponse.cert),p=h.icePwd||"".concat(t.apResponse.cid,"_").concat(t.apResponse.cert);t.cloudProxyServer!=="disabled"?(_.debug("[".concat(this.store.clientId,"] Dc is not supported, because cloudProxyServer are not supported (").concat(t.cloudProxyServer,")")),l=!0):uv(u,p)?t.apResponse.addresses.some(E=>E.fingerprint)||T("FINGERPRINT")||(_.debug("[".concat(this.store.clientId,"] Dc is not supported, because fingerprint does not exist")),l=!0):(_.debug("[".concat(this.store.clientId,"] Dc is not supported, because ticket length is incorrect, it has to be between 22 and 255")),l=!0),l&&this.resetSignal()}this.store.joinGatewayStart(),t.cloudProxyServer!=="disabled"&&(this.hasChangeBGPAddress=!0);const r=Date.now();let o=hv.get(t.cname);if(o||(o=new Map,hv.set(t.cname,o)),this._isProactiveJoin=!0,o.has(t.uid
55)){const l=new D(A.UID_CONFLICT);throw Z.joinGateway(t.sid,{lts:r,succ:!1,ec:l.code,addr:null,uid:t.uid,cid:t.cid,firstSuccess:this._isProactiveJoin,isProxy:!!t.proxyServer||this.usingProxy,signalChannel:this.store.useDcSignal?"1":"0",preload:t.preload}),l}o.set(t.uid,!0),this.joinInfo=t,this.key=n;let s=0;this.joinGatewayStartTime=r;const a=t.proxyServer,c=this.store.useDcSignal?"datachannel":"websocket";try{_.debug("[".concat(this.store.clientId,"] use ").concat(c," join uid ").concat(s));const l=t.gatewayAddrs.map(u=>{let{address:p}=u;const[E,m]=p.split(":"),g={host:E,port:m};return t.proxyServer&&(g.proxy=t.proxyServer),g});let h;h=this.store.useDcSignal?await this.signal.init(t.apResponse.addresses):await this.signal.init(l),s=h.uid,_.debug("[".concat(this.store.clientId,"] ").concat(c," join uid ").concat(s," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(l){var d;throw l.code===A.INIT_DATACHANNEL_TIMEOUT&&this.signal.__name__==="AgoraRTCSignal"||Z.joinGateway(t.sid,{lts:r,succ:!1,ec:((d=l.data)===null||d===void 0?void 0:d.desc)||l.code,errorMsg:l.message,addr:this.signal.url,uid:t.uid,cid:t.cid,firstSuccess:this._isProactiveJoin,isProxy:!!a||this.usingProxy,signalChannel:this.signal.__name__==="DataChannelSignal"?"1":"0",preload:t.preload}),l&&l.code===A.INIT_DATACHANNEL_TIMEOUT?(_.warning("[".concat(this.store.clientId,"] User join datachannel failed"),l.toString()),this.resetSignal(),l):(_.error("[".concat(this.store.clientId,"] User join failed"),l.toString()),o.delete(t.uid),this.signal.close(),l)}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),_.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval(()=>{this.updateTrafficStats().catch(l=>{_.warning("[".concat(this.store.clientId,"] get traffic stats error"),l.toString())})},3e3),this.networkQualityInterval=window.setInterval(()=>{navigator&&navigator.onLine!==void 0&&!navigator.onLine?this.emit(qt.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(qt.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):this.state==="CONNECTED"&&this._statsCollector.trafficStats?this.emit(qt.NETWORK_QUALITY,{uplinkNetworkQuality:sm(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:sm(this._statsCollector.trafficStats.B_dnq)}):this.emit(qt.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})},2e3),this.store.joinGatewayEnd(),s}async leave(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],n=arguments.length>1?arguments[1]:void 0;if(this.state!=="DISCONNECTED"){n!==Pe.FALLBACK&&(this.state="DISCONNECTING");try{t||this.signal.connectionState!==Le.CONNECTED||await function(i,r){return r===1/0?i:K.race([i,W9(r)])}(this.signal.request(ie.LEAVE,void 0,!0),3e3)}catch(i){_.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),i)}this.signal.close(n),n!==Pe.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(t,n,i){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const r={state:"offer",p2p_id:this.store.p2pId,ortc:n,mode:this.spec.mode,extend:T("PUB_EXTEND"),twcc:!!T("PUBLISH_TWCC"),rtx:!!T("USE_PUB_RTX")};try{return(await this.signal.request(ie.PUBLISH,r,!0))._message}catch(o){if(i&&o.data&&o.data.code===ce.ERR_PUBLISH_REQUEST_INVALID)return _.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),o.toString()),await this.tryUnpubBeforeRepub(t,n),this.publish(t,n,!1);throw o}}async publishDataChannel(t,n,i){var r;if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const o={stream_id:n.streamId,ordered:n.ordered?1:0,max_retrans_times:(r=n.maxRetransmits)!==null&&r!==void 0?r:10,channel_id:n.channelId,metadata:n.metadata};try{await this.signal.request(ie.PUBLISH_DATASTREAM,o,!0)}catch(s){if(i&&s.data&&s.data.code===ce.ERR_PUBLISH_REQUEST_INVALID)return _.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),s.toString()),await this.tryUnpubDataChannelBeforeRepub(t,n),this.publishDataChannel
55(t,n,!1);throw s}}async unpublish(t,n){try{if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(ie.UNPUBLISH,{stream_id:n,ortc:t},!0)}catch(i){_.warning("[".concat(this.store.clientId,"] unpublish warning: "),i)}}async unpublishDataChannel(t){try{if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await K.all(t.map(n=>this.signal.request(ie.UNPUBLISH_DATASTREAM,{channel_id:n},!0)))}catch(n){_.warning("unpublish datachannels warning: ",n)}}async presubscribe(t,n,i){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"can not presubscribe when connection state is ".concat(this.state));const r={stream_id:t,stream_type:n,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!T("SUBSCRIBE_TWCC"),rtx:!!T("USE_SUB_RTX")||void 0,extend:T("SUB_EXTEND"),svc:Array.isArray(T("SVC"))&&T("SVC").length!==0?T("SVC"):void 0};try{return await this.signal.request(ie.PRE_SUBSCRIBE,r,!0)}catch(o){if(i&&o.data&&o.data.code===ce.ERR_SUBSCRIBE_REQUEST_INVALID)return _.warning("[".concat(this.store.clientId,"] pre-subscribe error, retry"),o.toString()),this.presubscribe(t,n,!1);throw o}}async subscribe(t,n,i){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const r={stream_id:t,stream_type:n.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!T("SUBSCRIBE_TWCC"),rtx:!!T("USE_SUB_RTX"),extend:T("SUB_EXTEND"),ssrcId:n.ssrcId,svc:Array.isArray(T("SVC"))&&T("SVC").length!==0?T("SVC"):void 0};try{return(await this.signal.request(ie.SUBSCRIBE,r,!0))._message}catch(o){if(i&&o.data&&o.data.code===ce.ERR_SUBSCRIBE_REQUEST_INVALID)return _.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),o.toString()),await this.tryUnsubBeforeResub(t,n),await this.subscribe(t,n,!1);throw o}}async subscribeDataChannel(t,n,i){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const r={uid:t,stream_id:n.id,channel_id:n.datachannelId};try{return void await this.signal.request(ie.SUBSCRIBE_DATASTREAM,r,!0)}catch(o){if(i&&o.data&&o.data.code===ce.ERR_SUBSCRIBE_REQUEST_INVALID)return _.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),o.toString()),await this.tryUnsubDataChannelBeforeResub(t,n),await this.subscribeDataChannel(t,n,!1);throw o}}async subscribeAll(t,n){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const i={p2p_id:this.store.p2pId,users:t,dtx:!1,rtx:!!T("USE_SUB_RTX"),twcc:!!T("SUBSCRIBE_TWCC"),svc:Array.isArray(T("SVC"))&&T("SVC").length!==0?T("SVC"):void 0};try{return await this.signal.request(ie.SUBSCRIBE_STREAMS,i,!0)}catch(r){if(n&&r.data&&r.data.code===ce.ERR_SUBSCRIBE_REQUEST_INVALID)return _.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),r.toString()),await this.tryMassUnsubBeforeResub(t),await this.subscribeAll(t,!1);throw r}}async setVideoProfile(t){const n=function(i){if(!(i.bitrateMax&&i.bitrateMin&&i.frameRate&&i.height&&i.width))return;let r=i.frameRate,o=i.width,s=i.height,a=!0;return typeof r!="number"&&(r=r.exact||r.ideal||r.max||r.min||0,r||(a=!1)),typeof o!="number"&&(o=o.exact||o.ideal||o.max||o.min||0,o||(a=!1)),typeof s!="number"&&(s=s.exact||s.ideal||s.max||s.min||0,r||(a=!1)),a?{stream_type:0,width:o,height:s,fps:r,start_bps:1e3*i.bitrateMax,min_bps:1e3*i.bitrateMin,target_bps:1e3*i.bitrateMax}:void 0}(t);if(n)return this.signal.request(ie.SET_VIDEO_PROFILE,n);_.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(t,n){try{await this.signal.request(ie.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:t,stream_id:n},!0)}catch(i){_.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),i)}}
55async unsubscribeDataChannel(t,n){try{if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await K.all(t.map(i=>this.signal.request(ie.UNSUBSCRIBE_DATASTREAM,{stream_id:i,uid:n},!0)))}catch(i){_.warning("unsubscribeDataChannel warning: ",i)}}async massUnsubscribe(t){try{await this.signal.request(ie.UNSUBSCRIBE_STREAMS,t,!0)}catch(n){_.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),n)}}async reconnectPC(t){const{iceParameters:n,dtlsParameters:i,rtpCapabilities:r}=t;return{gatewayEstablishParams:await this.signal.request(ie.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:n,dtlsParameters:i,rtpCapabilities:r}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(ie.GATEWAY_INFO)}async renewToken(t){await this.signal.request(ie.RENEW_TOKEN,t),this.key=t.token}updateClientRole(t,n){n&&(this._clientRoleOptions=Object.assign({},n)),T("CLIENT_ROLE_OPTIONS")&&(_.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(T("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," ")),this._clientRoleOptions=Object.assign({},T("CLIENT_ROLE_OPTIONS"))),this.role=t}async setClientRole(t,n){if(n&&(this._clientRoleOptions=Object.assign({},n)),T("CLIENT_ROLE_OPTIONS")&&(this._clientRoleOptions=Object.assign({},T("CLIENT_ROLE_OPTIONS")),_.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(T("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," "))),this.state!=="CONNECTED")return void(this.role=t);let i,r=0;t==="audience"?this._clientRoleOptions&&this._clientRoleOptions.delay?(i=this._clientRoleOptions.delay,r=1):r=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:r=0;const o=Object.assign({},n);delete o.delay,delete o.level,await this.signal.request(ie.SET_CLIENT_ROLE,Pn(Pn({role:t,level:r,delay:i},o),{},{client_ts:Date.now()})),this.role=t}async setDualStreamMode(t,n,i){await this.signal.request(ie.SET_DUAL_STREAM_MODE,{mode:t},i,n)}async setRemoteVideoStreamType(t,n){await this.signal.request(ie.SWITCH_VIDEO_STREAM,{stream_id:t,stream_type:n})}async setDefaultRemoteVideoStreamType(t){await this.signal.request(ie.DEFAULT_VIDEO_STREAM,{stream_type:t})}async setStreamFallbackOption(t,n){await this.signal.request(ie.SET_FALLBACK_OPTION,{stream_id:t,fallback_type:n})}async pickSVCLayer(t,n){await this.signal.request(ie.PICK_SVC_LAYER,{stream_id:t,spatial_layer:n.spatialL
55ayer,temporal_layer:n.temporalLayer})}async setRTM2Flag(t){await this.signal.request(ie.SET_RTM2_FLAG,{rtm2_flag:t})}async sendExtensionMessage(t,n,i){if(this.store.useP2P)return this.signal.sendExtensionMessage(t,n,i)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),Pn({},this.inChannelInfo)}async setConfigure(t){if(t&&Array.isArray(t)&&t.length!==0)return this.signal.request(ie.CONFIGURE,t)}async getGatewayVersion(){return(await this.signal.request(ie.GATEWAY_INFO)).version}reset(){if(this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){const t=hv.get(this.joinInfo.cname);t&&t.delete(this.joinInfo.uid)}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0),this.usingProxy=!1}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const t=function(n){let i;return i=n.startsWith("dc")?n.match(/(dc\:\/\/)?([^:]+):(\d+)/):n.match(/(wss\:\/\/)?([^:]+):(\d+)/),i?{username:zt.username,password:zt.password,turnServerURL:i[2],tcpport:parseInt(i[3])+30,udpport:parseInt(i[3])+30,forceturn:!1}:null}((this.joinInfo.cloudProxyServer==="disabled"?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"");this.joinInfo.turnServer.serversFromGateway=[],t&&this.joinInfo.turnServer.mode!=="off"&&this.joinInfo.cloudProxyServer==="disabled"&&this.joinInfo.turnServer.serversFromGateway.push(Pn(Pn({},zt),{},{turnServerURL:t.turnServerURL,tcpport:t.tcpport,udpport:t.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}async updateTrafficStats(){if(this.state!=="CONNECTED")return;const t=await this.signal.request(ie.TRAFFIC_STATS,void 0,!0);t.timestamp=Date.now(),t.ntp_offset!=null&&(this.ntpOffset=t.ntp_offset),t.peer_delay.forEach(n=>{const i=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find(r=>r.peer_uid===n.peer_uid);i&&i.B_st!==n.B_st&&yp(()=>{this.emit(qt.STREAM_TYPE_CHANGE,n.peer_uid,n.B_st)})}),this._statsCollector.updateTrafficStats(t)}getJoinMessage(t){var n,i;if(!this.joinInfo||!this.key)throw new D(A.UNEXPECTED_ERROR,"can not generate join message, no join info");return this.store.hasStartJoinChannel=!0,this.store.isABTestSuccess||this.emit(qt.UPDATE_GATEWAY_CONFIG),i=this.store.clientId,x(gd).call(gd,i)||gd.push(i),function(r,o,s,a){var c,d,l,h,u;let{key:p,role:E,joinGatewayStartTime:m,hasChangeBGPAddress:g,isPreallocation:R,ortc:v,currentURLIndex:C}=a;const w=Object.assign({},o.apResponse);let b=!1;"signalResponse"in w&&w.signalResponse&&(r.p2pId===1&&(b=!0),R=!1,delete w.signalResponse);let y=T("REPORT_APP_SCENARIO");if(typeof y!="string")try{y=JSON.stringify(y)}catch{y=void 0}y&&y.length>128&&(y=void 0);const N=Ua(r),k=yS(r),U=((c=r.preSubOptions)===null||c===void 0?void 0:c.length)||0,X=U>0?(d=r.preSubOptions)===null||d===void 0?void 0:d.map(J=>J.uid):void 0,q=Qt("PRE_SUB_NUM","number")||1,se=U>q?U:q,_e=nU(),me=Ur(87)||Jg()||vp(117),ke=(oO()||zg(18,4,!1))&&Ap(18,6,!0)&&s.codec==="h264"&&T("ENABLE_ABSSENDTIME_AS_SENTTS"),We=!(((l=w.detail)===null||l===void 0?void 0:l[3])!=="CN"||!T("ENABLE_QUALITY_FALLBACK"))&&T("ENABLE_QUALITY_FALLBACK"),M=!!T("ENABLE_AP_MULTI_IP")&&((h=w.detail)===null||h===void 0?void 0:h[5])==="multi-ip",F={license:o.license,p2p_id:r.p2pId,session_id:o.sid,app_id:o.appId,channel_key:p,channel_name:o.cname,sdk_version:qi,browser:navigator.userAgent,process_id:T("PROCESS_ID"),mode:r.useP2P?"p2p":s.mode,codec:s.codec,role:E,has_changed_gateway:M||g,ap_response:w,extend:T("JOIN_EXTEND"),details:{6:o.stringUid,cservice_map:o.cloudProxyServer==="proxy3"?"1":o.cloudProxyServer==="proxy5"?"2":void 0},features:Ut({rejoin:!0},b?{multi_signaling:b}:{}),optionalInfo:o.optionalInfo,appScenario:y,attributes:{userAttributes:Ut(Ut({enableEncodedTransform:(!!T("ENABLE_AUDIO_METADATA")||!!T("ENABLE_AUDIO_PTS"))&&me||!!T("ENABLE_AUDIO_TOPN")&&Rp(je.CHROME,87,116)||void 0,enableAudioMetadata:!!T("ENABLE_AUDIO_METADATA")&&me,enableAudioPts:!!T("ENABLE_AUDIO_PTS")&&me,topnSmoothLevel:T("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:T("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:T("TOPN_SWITCH_HOLD_MS"),topnAudioGain:T("TOPN_AUDIO_GAIN"),enableNetworkQualityProbe:r.networkQualityProbe,enablePublishedUserList:T("ENABLE_PUBLISHED_USER_LIST"),enableUserList:T("ENABLE_USER_LIST"),maxSubscription:T("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:Qt("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:Qt("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:Qt("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:T("USE_PUB_RTX")===!0||T("USE_SUB_RTX")===!0||void 0,disableFEC:T("DISABLE_FEC"),enableNTPReport:!!T("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:k,enableFulllinkAvSync:!!T("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:Qt("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:cN(),rtm2Flag:typeof o.rtmFlag=="number"?o.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!T("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:Qt("USE_XR","boolean"),enableLossbasedBwe:Qt("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:aN(),enableCCF
55allback:Qt("ENABLE_CC_FALLBACK","boolean"),enablePreallocPC:R,preSubUid:N?X:void 0,preSubNum:N?se:void 0,enablePubTWCC:Qt("PUBLISH_TWCC","boolean"),enableSubTWCC:Qt("SUBSCRIBE_TWCC","boolean"),enablePubRTX:Qt("USE_PUB_RTX","boolean"),enableSubRTX:Qt("USE_SUB_RTX","boolean"),enableSubSVC:T("ENABLE_SVC")?T("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(T("SVC"))&&T("SVC").length!==0?T("SVC"):void 0,enableSvcExtended:T("ENABLE_SVC")&&Array.isArray(T("SVC_EXTENDED"))&&T("SVC_EXTENDED").length!==0?T("SVC_EXTENDED"):void 0,enableVosFallback:T("ENABLE_VOS_FALLBACK"),enableQualityFallback:We},_e),{},{audioDuplicate:Qt("ENABLE_AUDIO_RED","boolean")?(u=Qt("AUDIO_DUPLICATE_NUM","number"))!==null&&u!==void 0?u:2:void 0,senttsUsesAbsSendTime:!!ke||void 0,enableDualStreamFlag:Qt("ENABLE_DUAL_STREAM_FLAG","boolean")})},join_ts:m,ortc:v||{}};return o.stringUid&&(F.string_uid=o.stringUid),o.aesmode&&o.aespassword&&(F.aes_mode=o.aesmode,T("ENCRYPT_AES")?(F.aes_secret=o.aespassword,F.aes_encrypt=!0):F.aes_secret=o.aespassword,o.aessalt&&(F.aes_salt=o.aessalt)),w.addresses[C]&&(F.ap_response.ticket=w.addresses[C].ticket,delete w.addresses),o.defaultVideoStream!==void 0&&(F.default_video_stream=o.defaultVideoStream),F}(this.store,this.joinInfo,this.spec,{key:this.key,role:this.role,joinGatewayStartTime:this.joinGatewayStartTime,hasChangeBGPAddress:this.hasChangeBGPAddress,isPreallocation:!((n=this.isPreallocation)===null||n===void 0||!n.call(this)),ortc:t,currentURLIndex:this.signal.currentURLIndex})}getRejoinMessage(){if(!this.joinInfo)throw new D(A.UNEXPECTED_ERROR,"can not generate rejoin message, no join info");return{session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)}}handleSignalEvents(){this.signal.on(ee.WS_RECONNECT_CREATE_CONNECTION,t=>{this.joinGatewayStartTime=Date.now()}),this.signal.on(ee.WS_RECONNECTING,t=>{this.joinInfo&&Z.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t||Vn.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",Z.sessionInit(this.joinInfo.sid,{lts:new Date().getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0}
55,cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode,stringUid:this.joinInfo.stringUid,channelProfile:this.spec.mode==="live"?1:0,channelMode:0,lsid:this.joinInfo.sid,clientRole:this.role==="audience"?2:1,buildFormat:1}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())}),this.signal.on(ee.WS_CLOSED,t=>{let n;switch(t){case Pe.LEAVE:n=Vn.LEAVE;break;case Pe.UID_BANNED:case Pe.IP_BANNED:case Pe.CHANNEL_BANNED:case Pe.SERVER_ERROR:n=Vn.SERVER_ERROR;break;case Pe.FALLBACK:n=Vn.FALLBACK;break;case Pe.LICENSE_MISSING:case Pe.LICENSE_EXPIRED:case Pe.LICENSE_MINUTES_EXCEEDED:case Pe.LICENSE_PERIOD_INVALID:case Pe.LICENSE_MULTIPLE_SDK_SERVICE:case Pe.LICENSE_ILLEGAL:case Pe.TOKEN_EXPIRE:n=t;break;default:n=Vn.NETWORK_ERROR}_.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(n||"undefined -> "+Vn.NETWORK_ERROR)),this.joinInfo&&Z.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:t===Pe.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:n}),this._disconnectedReason=t,t!==Pe.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}),this.signal.on(ee.WS_CONNECTED,()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo){if(this.role==="audience"){const t=T("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;t&&(t.level||t.delay)&&(_.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(t.level,", delay: ").concat(t.delay)),this.setClientRole(this.role,t))}if(Z.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer||this.usingProxy,signalChannel:this.signal.__name__==="DataChannelSignal"?"1":"0",preload:this.joinInfo.preload,isABTestSuccess:this.store.isABTestSuccess}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&this.joinInfo.setLocalAPVersion===1){const t=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!t)return void _.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(t));at("EVENT_REPORT_DOMAIN",t[1]),at("EVENT_REPORT_BACKUP_DOMAIN",t[1]),at("LOG_UPLOAD_SERVER","".concat(t[1],":6444"))}}}),this.signal.on(he.ON_UPLINK_STATS,t=>{this._statsCollector.updateUplinkStats(t)}),this.signal.on(ee.REQUEST_RECOVER,(t,n,i)=>{if(!this.joinInfo)return i(new D(A.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));t&&(this.joinInfo.multiIP=t,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,Jt(this,qt.REQUEST_NEW_GATEWAY_LIST).then(n).catch(i)}),this.signal.on(ee.REQUEST_JOIN_INFO,async(t,n,i)=>{var r,o,s;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void t(this.getJoinMessage());const a=Ct((r=this.joinInfo)===null||r===void 0?void 0:r.turnServer);if(T("NEW_TURN_MODE")&&a&&((o=this.joinInfo)===null||o===void 0?void 0:o.cloudProxyServer)==="disabled"){var c;let u=a.servers.map(m=>"turnServerURL"in m&&T("USE_TURN_IP")?Pn(Pn({},m),{},{turnServerURL:om(m.turnServerURL)}):m),p=(c=a.serversFromGateway)===null||c===void 0?void 0:c.map(m=>T("USE_TURN_IP")?Pn(Pn({},m),{},{turnServerURL:om(m.turnServerURL)}):m);const E=this.signal.currentURLIndex;u.length>0&&(u=[u[E%u.length]],a.servers=u),Array.isArray(p)&&p.length>0&&(p=[p[0]],a.serversFromGateway=p),_.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(E))}const{iceParameters:d,dtlsParameters:l,rtpCapabilities:h}=await Jt(this,qt.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:a,cloudProxyServer:(s=this.joinInfo)===null||s===void 0?void 0:s.cloudProxyServer});try{t(this.getJoinMessage({iceParameters:d,dtlsParameters:l,rtpCapabilities:h,version:"2"}))}catch(u){n(u)}}),this.signal.on(ee.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE,(t,n)=>{if(this.joinInfo&&this.joinInfo.signalResponse){const i=this.joinInfo.apResponse.addresses[this.signal.currentURLIndex],r=this.joinInfo.signalResponse,o=T("FINGERPRINT")||i.fingerprint;if(!i.iceUfrag||!i.icePwd||!o)return _.debug("cannot get iceUfrag or icePwd or fingerprint from serverAddress"),void t(void 0);const s=Pn(Pn({},r),{},{ortc:{dtlsParameters:{role:"client",fingerprints:[{algorithm:"sha-256",fingerprint:T("FINGERPRINT")||i.fingerprint}]},iceParameters:{candidates:[],iceUfrag:i.iceUfrag,icePwd:i.icePwd},rtpCapabilities:r.rtpCapabilities,cname:"o/i14u9pJrxRKAsu"}});this.joinInfo&&delete this.joinInfo.signalResponse,t(s)}else t(void 0)}),this.signal.on(ee.REQUEST_REJOIN_INFO,t=>{t(this.getRejoinMessage())}),this.signal.on(ee.REPORT_JOIN_GATEWAY,(t,n)=>{if(!this.joinInfo)return;let i,r="";var o;t instanceof D?(i=((o=t.data)===null||o===void 0?void 0:o.desc)||t.code,r=t.message):i=t,Z.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:i,errorMsg:r,addr:n,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer||this.usingProxy,signalChannel:this.signal.__name__==="DataChannelSignal"?"1":"0",preload:this.joinInfo.preload})}),this.signal.on(ee.IS_P2P_DISCONNECTED,t=>{t(Na(this,qt.IS_P2P_DISCONNECTED))}),this.signal.on(ee.DISCONNECT_P2P,()=>
55{this.emit(qt.DISCONNECT_P2P)}),this.signal.on(ee.REQUEST_SUCCESS,()=>{this._signalTimeout=!1}),this.signal.on(ee.REQUEST_TIMEOUT,()=>{this._signalTimeout=!0}),this.signal.on(ee.JOIN_RESPONSE,t=>{const n=this.getCurrentGatewayAddress();this.emit(qt.JOIN_RESPONSE,t,n)}),this.signal.on(ee.PRE_CONNECT_PC,async(t,n)=>{if(this.joinInfo){var i,r;this.updateTurnConfigFromSignal();const s=this.getCurrentGatewayAddress(),a=Ct((i=this.joinInfo)===null||i===void 0?void 0:i.turnServer);if(T("NEW_TURN_MODE")&&a&&((r=this.joinInfo)===null||r===void 0?void 0:r.cloudProxyServer)==="disabled"){var o;let l=a.servers.map(p=>"turnServerURL"in p&&T("USE_TURN_IP")?Pn(Pn({},p),{},{turnServerURL:om(p.turnServerURL)}):p),h=(o=a.serversFromGateway)===null||o===void 0?void 0:o.map(p=>T("USE_TURN_IP")?Pn(Pn({},p),{},{turnServerURL:om(p.turnServerURL)}):p);const u=this.signal.currentURLIndex;l.length>0&&(l=[l[u%l.length]],a.servers=l),Array.isArray(h)&&h.length>0&&(h=[h[0]],a.serversFromGateway=h),_.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(u,",in pre pc"))}const c=this.joinInfo.apResponse.addresses[this.signal.currentURLIndex],d=T("FINGERPRINT")||c.fingerprint;if(s&&d){const l=DU(s);Jt(this,qt.PRE_CONNECT_PC,{candidates:l,fingerprint:d,turnServer:a,iceUfrag:c.iceUfrag,icePwd:c.icePwd}).then(h=>{t==null||t(h)}).catch(n||(()=>{}))}}}),this.signal.on(ee.RECOVER_NOTIFICATION,t=>{this.joinInfo&&typeof T("AP_REQUEST_DETAIL")=="string"&&(this.joinInfo.apRequestDetail="".concat(T("AP_REQUEST_DETAIL"),";").concat(t))}),this.signal.on(ee.VOS_FALLBACK,t=>{this.emit(qt.VOS_FALLBACK,t)}),this.signal.on(ee.DATACHANNEL_FAILBACK,t=>{_.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(qt.DATACHANNEL_FAILBACK)})}async tryUnsubBeforeResub(t,n){try{await this.signal.request(ie.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:t,ortc:[n]},!0)}catch(i){throw _.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),i),i}}async tryUnsubDataChannelBeforeResub(t,n){try{await this.signal.request(ie.UNSUBSCRIBE,{stream_id:n.id},!0)}catch(i){throw _.warning("unsubscribe datachannel warning",i),i}}async tryUnpubBeforeRepub(t,n){try{await this.signal.request(ie.UNPUBLISH,{stream_id:t,ortc:n},!0)}catch(i){throw _.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),i),i}}async tryUnpubDataChannelBeforeRepub(t,n){try{await this.signal.request(ie.UNPUBLISH_DATASTREAM,{channnel_id:n.channelId},!0)}catch(i){throw _.warning("unpublish datastream warning: ",i),i}}async tryMassUnsubBeforeResub(t){const n={users:t.map(i=>({stream_id:i.stream_id,stream_type:i.stream_type}))};try{await this.signal.request(ie.UNSUBSCRIBE_STREAMS,n,!0)}catch(i){throw _.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),i),i}}async muteLocal(t,n){const i={action:t.find(r=>r.stream_type===nt.Audio)?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:t,stream_id:n};try{await this.signal.request(ie.CONTROL,i,!0,!0)}catch(r){throw _.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),r),r}}async unmuteLocal(t,n){const i={action:t.find(r=>r.stream_type===nt.Audio)?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:t,stream_id:n};try{await this.signal.request(ie.CONTROL,i,!0,!0)}catch(r){throw _.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),r),r}}async muteRemote(t,n){const i={action:t===$.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:n};try{await this.signal.request(ie.CONTROL,i,!0,!0)}catch(r){throw _.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),r),r}}async unmuteRemote(t,n){const i={action:t===$.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:n};try{await this.signal.request(ie.CONTROL,i,!0,!0)}catch(r){throw _.warning("[".concat(this.store.clientId,"] gateway unmuteRemote warning: "),r),r}}uploadWRTCStats(t){this.signal.uploadWRTCStats(t)}upload(t,n){this.signal.upload(t,n)}getSignalRTT(){return this.signal.rtt}async restartICE(t){const n={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:t};try{return await this.signal.request(ie.RESTART_ICE,n,!0)}catch(i){throw _.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),i),i}}reconnect(t,n){this.state==="CONNECTED"&&this.signal.reconnect(t||void 0,n||Vn.P2P_FAILED)}getCurrentGatewayAddress(){var t,n;if(!T("GATEWAY_WSS_ADDRESS"))return T("USE_CANDIDATE_FROM_AP_DETAIL")&&(t=this.joinInfo)!==null&&t!==void 0&&t.apGatewayAddress?(_.debug("[".concat(this.store.clientId,"] use candidate from ap detail, ").concat(JSON.stringify(this.joinInfo.apGatewayAddress))),this.joinInfo.apGatewayAddress):(n=this.joinInfo)!==null&&n!==void 0&&n.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}async setPublishAudioFilterEnabled(t){await this.signal.request(ie.SET_PARAMETER,{enablePublishAudioFilter:t})}downgradeCodec(t){this.signal.downgradeCodec(t)}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(Pe.FALLBACK)),this.store.useDcSignal=!1,this.signal=new GP(Pn(Pn({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}
55),this.store),this.handleSignalEvents(),this.emit(qt.RESET_SIGNAL)}}let pee=function(e){return e.NATIVE_RTC="native_rtc",e.NATIVE_RTM="native_rtm",e.WEB_RTC="web_rtc",e.WEB_RTM="web_rtm",e}({}),hm=0,pv=0;function Qr(e,t,n,i){return new K((r,o)=>{t.timeout=t.timeout||T("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),hm+=ko(t.data)):n&&(t.data.size?hm+=t.data.size:t.data instanceof FormData?hm+=wO(t.data):hm+=ko(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,li.request(t).then(s=>{typeof s.data=="string"?pv+=ko(s.data):s.data instanceof ArrayBuffer||s.data instanceof Uint8Array?pv+=s.data.byteLength:pv+=ko(JSON.stringify(s.data)),i&&r({data:s.data,headers:s.headers}),r(s.data)}).catch(s=>{li.isCancel(s)?o(new D(A.OPERATION_ABORTED,"cancel token canceled")):s.code==="ECONNABORTED"?o(new D(A.NETWORK_TIMEOUT,s.message)):s.response?o(new D(A.NETWORK_RESPONSE_ERROR,s.response.status)):o(new D(A.NETWORK_ERROR,s.message))})})}/*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */(function(){var e;function t(M){var F=0;return function(){return F<M.length?{done:!1,value:M[F++]}:{done:!0}}}var n=typeof Object.defineProperties=="function"?Object.defineProperty:function(M,F,J){return M==Array.prototype||M==Object.prototype||(M[F]=J.value),M},i,r=function(M){M=[typeof globalThis=="object"&&globalThis,M,typeof window=="object"&&window,typeof self=="object"&&self,typeof Ae=="object"&&Ae];for(var F=0;F<M.length;++F){var J=M[F];if(J&&J.Math==Math)return J}throw Error("Cannot find global object")}(this);function o(M,F){if(F)e:{var J=r;M=M.split(".");for(var V=0;V<M.length-1;V++){var f=M[V];if(!(f in J))break e;J=J[f]}(F=F(V=J[M=M[M.length-1]]))!=V&&F!=null&&n(J,M,{configurable:!0,writable:!0,value:F})}}function s(M){return(M={next:M})[Symbol.iterator]=function(){return this},M}function a(M){var F=typeof Symbol<"u"&&Symbol.iterator&&M[Symbol.iterator];return F?F.call(M):{next:t(M)}}if(o("Symbol",function(M){function F(f,I){this.A=f,n(this,"description",{configurable:!0,writable:!0,value:I})}if(M)return M;F.prototype.toString=function(){return this.A};var J="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",V=0;return function f(I){if(this instanceof f)throw new TypeError("Symbol is not a constructor");return new F(J+(I||"")+"_"+V++,I)}}),o("Symbol.iterator",function(M){if(M)return M;M=Symbol("Symbol.iterator");for(var F="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),J=0;J<F.length;J++){var V=r[F[J]];typeof V=="function"&&typeof V.prototype[M]!="function"&&n(V.prototype,M,{configurable:!0,writable:!0,value:function(){return s(t(this))}})}return M}),typeof Object.setPrototypeOf=="function")i=Object.setPrototypeOf;else{var c;e:{var d={};try{d.__proto__={a:!0},c=d.a;break e}catch{}c=!1}i=c?function(M,F){if(M.__proto__=F,M.__proto__!==F)throw new TypeError(M+" is not extensible");return M}:null}var l=i;function h(){this.m=!1,this.j=null,this.v=void 0,this.h=1,this.u=this.C=0,this.l=null}function u(M){if(M.m)throw new TypeError("Generator is already running");M.m=!0}function p(M,F){return M.h=3,{value:F}}function E(M){this.g=new h,this.G=M}function m(M,F,J,V){try{var f=F.call(M.g.j,J);if(!(f instanceof Object))throw new TypeError("Iterator result "+f+" is not an object");if(!f.done)return M.g.m=!1,f;var I=f.value}catch(O){return M.g.j=null,M.g.s(O),g(M)}return M.g.j=null,V.call(M.g,I),g(M)}function g(M){for(;M.g.h;)try{var F=M.G(M.g);if(F)return M.g.m=!1,{value:F.value,done:!1}}catch(J){M.g.v=void 0,M.g.s(J)}if(M.g.m=!1,M.g.l){if(F=M.g.l,M.g.l=null,F.F)throw F.D;return{value:F.return,done:!0}}return{value:void 0,done:!0}}function R(M){this.next=function(F){return M.o(F)},this.throw=function(F){return M.s(F)},this.return=function(F){return function(J,V){u(J.g);var f=J.g.j;return f?m(J,"return"in f?f.return:function(I){return{value:I,done:!0}},V,J.g.return):(J.g.return(V),g(J))}(M,F)},this[Symbol.iterator]=function(){return this}}function v(M,F){return F=new R(new E(F)),l&&M.prototype&&l(F,M.prototype),F}if(h.prototype.o=function(M){this.v=M},h.prototype.s=function(M){this.l={D:M,F:!0},this.h=this.C||this.u},h.prototype.return=function(M){this.l={return:M},this.h=this.u},E.prototype.o=function(M){return u(this.g),this.g.j?m(this,this.g.j.next,M,this.g.o):(this.g.o(M),g(this))},E.prototype.s=function(M){return u(this.g),this.g.j?m(this,this.g.j.throw,M,this.g.o):(this.g.s(M),g(this))},o("Array.prototype.entries",function(M){return M||function(){return function(F,J){F instanceof String&&(F+="");var V=0,f=!1,I={next:function(){if(!f&&V<F.length){var O=V++;return{value:J(O,F[O]),done:!1}}return f=!0,{done:!0,value:void 0}}};return I[Symbol.iterator]=function(){return I},I}(this,function(F,J){return[F,J]})}}),typeof Blob<"u"&&(typeof FormData>"u"||!FormData.prototype.keys)){var C=function(M,F){for(var J=0;J<M.length;J++)F(M[J])},w=function(M){return M.replace(/\r?\n|\r/g,`\r 56`)},b=function(M,F,J){return F instanceof Blob?(J=J!==void 0?J+"":typeof F.name=="string"?F.name:"blob",F.name===J&&Object.prototype.toString.call(F)!=="[object Blob]"||(F=new File([F],J)),[String(M),F]):[String(M),String(F)]}
56,y=function(M,F){if(M.length<F)throw new TypeError(F+" argument required, but only "+M.length+" present.")},N=typeof globalThis=="object"?globalThis:typeof window=="object"?window:typeof self=="object"?self:this,k=N.FormData,U=N.XMLHttpRequest&&N.XMLHttpRequest.prototype.send,X=N.Request&&N.fetch,q=N.navigator&&N.navigator.sendBeacon,se=N.Element&&N.Element.prototype,_e=N.Symbol&&Symbol.toStringTag;_e&&(Blob.prototype[_e]||(Blob.prototype[_e]="Blob"),"File"in N&&!File.prototype[_e]&&(File.prototype[_e]="File"));try{new File([],"")}catch{N.File=function(M,F,J){return M=new Blob(M,J||{}),Object.defineProperties(M,{name:{value:F},lastModified:{value:+(J&&J.lastModified!==void 0?new Date(J.lastModified):new Date)},toString:{value:function(){return"[object File]"}}}),_e&&Object.defineProperty(M,_e,{value:"File"}),M}}var me=function(M){return M.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},ke=function(M){this.i=[];var F=this;M&&C(M.elements,function(J){if(J.name&&!J.disabled&&J.type!=="submit"&&J.type!=="button"&&!J.matches("form fieldset[disabled] *"))if(J.type==="file"){var V=J.files&&J.files.length?J.files:[new File([],"",{type:"application/octet-stream"})];C(V,function(f){F.append(J.name,f)})}else J.type==="select-multiple"||J.type==="select-one"?C(J.options,function(f){!f.disabled&&f.selected&&F.append(J.name,f.value)}):J.type==="checkbox"||J.type==="radio"?J.checked&&F.append(J.name,J.value):(V=J.type==="textarea"?w(J.value):J.value,F.append(J.name,V))})};if((e=ke.prototype).append=function(M,F,J){y(arguments,2),this.i.push(b(M,F,J))},e.delete=function(M){y(arguments,1);var F=[];M=String(M),C(this.i,function(J){J[0]!==M&&F.push(J)}),this.i=F},e.entries=function M(){var F,J=this;return v(M,function(V){if(V.h==1&&(F=0),V.h!=3)return F<J.i.length?V=p(V,J.i[F]):(V.h=0,V=void 0),V;F++,V.h=2})},e.forEach=function(M,F){y(arguments,1);for(var J=a(this),V=J.next();!V.done;V=J.next()){var f=a(V.value);V=f.next().value,f=f.next().value,M.call(F,f,V,this)}},e.get=function(M){y(arguments,1);var F=this.i;M=String(M);for(var J=0;J<F.length;J++)if(F[J][0]===M)return F[J][1];return null},e.getAll=function(M){y(arguments,1);var F=[];return M=String(M),C(this.i,function(J){J[0]===M&&F.push(J[1])}),F},e.has=function(M){y(arguments,1),M=String(M);for(var F=0;F<this.i.length;F++)if(this.i[F][0]===M)return!0;return!1},e.keys=function M(){var F,J,V,f,I=this;return v(M,function(O){if(O.h==1&&(F=a(I),J=F.next()),O.h!=3)return J.done?void(O.h=0):(V=J.value,f=a(V),p(O,f.next().value));J=F.next(),O.h=2})},e.set=function(M,F,J){y(arguments,2),M=String(M);var V=[],f=b(M,F,J),I=!0;C(this.i,function(O){O[0]===M?I&&(I=!V.push(f)):V.push(O)}),I&&V.push(f),this.i=V},e.values=function M(){var F,J,V,f,I=this;return v(M,function(O){if(O.h==1&&(F=a(I),J=F.next()),O.h!=3)return J.done?void(O.h=0):(V=J.value,(f=a(V)).next(),p(O,f.next().value));J=F.next(),O.h=2})},ke.prototype._asNative=function(){for(var M=new k,F=a(this),J=F.next();!J.done;J=F.next()){var V=a(J.value);J=V.next().value,V=V.next().value,M.append(J,V)}return M},ke.prototype._blob=function(){var M="----formdata-polyfill-"+Math.random(),F=[],J="--"+M+`\r 57Content-Disposition: form-data; name="`;return this.forEach(function(V,f){return typeof V=="string"?F.push(J+me(w(f))+`"\r 58\r 59`+w(V)+`\r 60`):F.push(J+me(w(f))+'"; filename="'+me(V.name)+`"\r 61Content-Type: `+(V.type||"application/octet-stream")+`\r 62\r 63`,V,`\r 64`)}),F.push("--"+M+"--"),new Blob(F,{type:"multipart/form-data; boundary="+M})},ke.prototype[Symbol.iterator]=function(){return this.entries()},ke.prototype.toString=function(){return"[object FormData]"},se&&!se.matches&&(se.matches=se.matchesSelector||se.mozMatchesSelector||se.msMatchesSelector||se.oMatchesSelector||se.webkitMatchesSelector||function(M){for(var F=(M=(this.document||this.ownerDocument).querySelectorAll(M)).length;0<=--F&&M.item(F)!==this;);return-1<F}),_e&&(ke.prototype[_e]="FormData"),U){var We=N.XMLHttpRequest.prototype.setRequestHeader;N.XMLHttpRequest.prototype.setRequestHeader=function(M,F){We.call(this,M,F),M.toLowerCase()==="content-type"&&(this.B=!0)},N.XMLHttpRequest.prototype.send=function(M){M instanceof ke?(M=M._blob(),this.B||this.setRequestHeader("Content-Type",M.type),U.call(this,M)):U.call(this,M)}}X&&(N.fetch=function(M,F){return F&&F.body&&F.body instanceof ke&&(F.body=F.body._blob()),X.call(this,M,F)}),q&&(N.navigator.sendBeacon=function(M,F){return F instanceof ke&&(F=F._asNative()),q.call(this,M,F)}),N.FormData=ke}})();const oc=()=>{const e=T("AREAS");return e.length===0&&e.push(Je.GLOBAL),ei(e).call(e,(t,n,i)=>{const r=GU(n);return r?i===0?r:"".concat(t,",").concat(r):t},"")},GU=e=>e===Je.OVERSEA?"".concat(Bn.ASIA,",").concat(Bn.EUROPE,",").concat(Bn.AFRICA,",").concat(Bn.NORTH_AMERICA,",").concat(Bn.SOUTH_AMERICA,",").concat(Bn.OCEANIA):Bn[e],_ee=e=>{const t={CODE:"",WEBCS_DOMAIN:[],WEBCS_DOMAIN_BACKUP_LIST:[],PROXY_CS:[],CDS_AP:[],ACCOUNT_REGISTER:[],UAP_AP:[],EVENT_REPORT_DOMAIN:[],EVENT_REPORT_BACKUP_DOMAIN:[],LOG_UPLOAD_SERVER:[],PROXY_SERVER_TYPE3:[]};return e.map(n=>{const i=r_[n],r=Object.keys(i);r&&r.map(o=>{o!=="CODE"&&(t[o]=t[o].concat(i[o]))})}),t},pm={GLOBAL:{ASIA:[Je.CHINA,Je.JAPAN,Je.INDIA,Je.KOREA,Je.HKMC],EUROPE:[],NORTH_AMERICA:[Je.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},_m=Object.keys(pm[Je.GLOBAL]),_v=[Je.CHINA,Je.NORTH_AMERICA,Je.EUROPE,Je.ASIA,Je.JAPAN,Je.INDIA,Je.OCEANIA,Je.SOUTH_AMERICA,Je.AFRICA,Je.KOREA,Je.HKMC,Je.US],mee=function(e,t){let n=[];if(x(e).call(e,Je.GLOBAL)){const o=[Je.GLOBAL,Je.OVERSEA],s=Object.keys(r_);
64if(t===Je.GLOBAL)throw new D(A.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===Je.CHINA)n=[Je.OVERSEA];else if(r=t,x(_m).call(_m,r)){const a=(i=t,pm[Je.GLOBAL][i]||[]),c=[...o,t,...a];n=s.filter(d=>!x(c).call(c,d))}else if(function(a){let c=!1;return _m.forEach(d=>{var l;x(l=pm[Je.GLOBAL][d]).call(l,a)&&(c=!0)}),c}(t)){const a=function(d){let l;return _m.forEach(h=>{var u;x(u=pm[Je.GLOBAL][h]).call(u,d)&&(l=h)}),l}(t),c=[...o,a,t];n=s.filter(d=>!x(c).call(c,d))}else n=e;n=function(a){const c=[];return _v.forEach(d=>{x(a).call(a,d)&&c.push(d)}),c.concat(a.filter(d=>!x(_v).call(_v,d)))}(n)}else n=e;var i,r;return n};function jU(e){var t,n;if(!e&&x(t=T("AREAS")).call(t,Je.EXTENSIONS))return _.debug("update area from ap : reset"),void mv(IX,!0);if(!x(n=T("AREAS")).call(n,Je.GLOBAL)||!e)return;let i=r_.EXTENSIONS;i&&(i={CODE:GU(Je.EXTENSIONS),WEBCS_DOMAIN:["ap-web-1-".concat(e,".agora.io")],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-".concat(e,".ap.sd-rtn.com")],PROXY_CS:["proxy-ap-web-".concat(e,".agora.io")],CDS_AP:["cds-ap-web-1-".concat(e,".agora.io"),"cds-ap-web-2-".concat(e,".ap.sd-rtn.com")],ACCOUNT_REGISTER:["sua-ap-web-1-".concat(e,".agora.io"),"sua-ap-web-2-".concat(e,".ap.sd-rtn.com")],UAP_AP:["uap-ap-web-1-".concat(e,".agora.io"),"uap-ap-web-2-".concat(e,".ap.sd-rtn.com")],EVENT_REPORT_DOMAIN:["statscollector-1-".concat(e,".agora.io")],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-".concat(e,".agora.io")],LOG_UPLOAD_SERVER:["logservice-".concat(e,".agora.io")],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy-".concat(e,".agora.io")]},_.debug("update area from ap success: ".concat(e,",config is "),i),at("AREAS",[Je.EXTENSIONS],!0),Object.keys(i).map(r=>{r==="LOG_UPLOAD_SERVER"||r==="EVENT_REPORT_DOMAIN"||r==="EVENT_REPORT_BACKUP_DOMAIN"||r==="PROXY_SERVER_TYPE3"?at(r,i[r][0]):at(r,i[r])}))}function mv(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const n=Z.reportApiInvoke(null,{name:vt.SET_AREA,options:e,tag:ht.TRACER});try{let i=[];if(typeof e=="string"&&(i=[e]),Array.isArray(e)&&(e.forEach(o=>{if(!x(kP).call(kP,o))throw new D(A.INVALID_PARAMS,"invalid area code")}),i=e),Object.prototype.toString.call(e)==="[object Object]"){const{areaCode:o,excludedArea:s}=e;if(!o)throw new D(A.INVALID_PARAMS,"area code is needed");let a=o;typeof o=="string"&&(a=[o]),i=s?mee(a,s):a}if(!t){if(Zi.AREAS){const o=new D(A.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return n.onError(o),void _.warning("setArea is prohibited because of config-distribute")}if(x(i).call(i,Je.GLOBAL)&&T("AREAS")===Je.EXTENSIONS){const o=new D(A.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return n.onError(o),void _.warning("setArea is prohibited because of ap extensions")}}at("AREAS",i,t);const r=_ee(i);Object.keys(r).map(o=>{o==="LOG_UPLOAD_SERVER"||o==="EVENT_REPORT_DOMAIN"||o==="EVENT_REPORT_BACKUP_DOMAIN"||o==="PROXY_SERVER_TYPE3"?at(o,r[o][0]):at(o,r[o])}),_.debug("set area success:",i.join(","))}catch(i){throw n.onError(i),i}n.onSuccess()}function WU(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Xo(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?WU(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):WU(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}let Ev=1;function Eee(e,t,n,i,r){Ev+=1;const o={sid:n.sid,command:"convergeAllocateEdge",uid:"666",appId:n.appId,ts:Math.floor(Date.now()/1e3),seq:Ev,requestId:Ev,version:qi,cname:n.cname},s={service_name:t,json_body:JSON.stringify(o)};let a,c,d=e[0];return Fr(async()=>{a=Date.now();const l=await Qr(d,{data:s,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-a,l.code!==0){const p=new D(A.UNEXPECTED_RESPONSE,"live streaming ap error, code"+l.code,{retry:!0,responseTime:c});throw _.error(p.toString()),p}const h=JSON.parse(l.json_body);if(h.code!==200){const p=new D(A.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(h.code,", reason: ").concat(h.reason),{code:h.c
64ode,responseTime:c});throw _.error(p.toString()),p}if(!h.servers||h.servers.length===0){const p=new D(A.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:h.code,responseTime:c});throw _.error(p.toString()),p}const u=function(p,E){return{addressList:p.servers.map(m=>"wss://".concat(m.address.replace(/\./g,"-"),".").concat(T("WORKER_DOMAIN"),":").concat(m.wss,"?serviceName=").concat(encodeURIComponent(E))),workerToken:p.workerToken,vid:p.vid}}(h,t);return T("LIVE_STREAMING_ADDRESS")&&(u.addressList=T("LIVE_STREAMING_ADDRESS")instanceof Array?T("LIVE_STREAMING_ADDRESS"):[T("LIVE_STREAMING_ADDRESS")]),Xo(Xo({},u),{},{responseTime:c})},(l,h)=>(Z.apworkerEvent(n.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(l.addressList),firstSuccess:h===0,responseTime:c,serverIp:e[h%e.length]}),!1),(l,h)=>(Z.apworkerEvent(n.sid,{success:!1,sc:l.data&&l.data.code||200,serviceName:t,responseTime:c,serverIp:e[h%e.length]}),!!(l.code!==A.OPERATION_ABORTED&&l.code!==A.UNEXPECTED_RESPONSE||l.data&&l.data.retry)&&(d=e[(h+1)%e.length],!0)),r)}let fv=1;function mm(e,t,n,i,r,o,s){let{url:a,areaCode:c}=e;const d=Date.now();let l;const h=n.role,[u,p]=gee(r,n,i,c,Array.isArray(t)?t:[t]);let E=At.networkState;return Fr(async()=>{E&&At.networkState===Jn.OFFLINE&&At.onlineWaiter&&await K.race([At.onlineWaiter,ln(s&&s.maxRetryTimeout||Bt.maxRetryTimeout)]),E=At.networkState;const{data:m,headers:g}=await Qr(a,{data:u,cancelToken:o,responseType:"arraybuffer",headers:{"Content-Type":"application/x-protobuf;"}},!0,!0);let R;l=g.http3==="1"?1:-1,Z.reportResourceTiming(a,n.sid);const v=g["content-type"]||g["Content-Type"]||"",C=x(v).call(v,"application/json");try{R=C?function(U){const X=T("ENABLE_AP_COMPRESS")?yT(U,{raw:!0}):U,q=new TextDecoder().decode(X);return JSON.parse(q)}(m):uee(n,i,m)}catch{throw new D(A.PB_ERROR,"sdp enpoint response transformer get unknown res",{retry:!1})}gv(R,a,n,d,Array.isArray(t)?t:[t],l);const w=ic(R,Dt.CHOOSE_SERVER);let b;Array.isArray(t)&&t.length>1&&(b=ic(R,n.cloudProxyServer==="proxy5"?Dt.CLOUD_PROXY_5:n.cloudProxyServer==="proxy3"||n.cloudProxyServer==="proxy4"?Dt.CLOUD_PROXY:Dt.CLOUD_PROXY_FALLBACK));const y=performance.getEntriesByName(a),N=y[y.length-1];let k;return N&&(k={name:N.name,protocol:"nextHopProtocol"in N?N.nextHopProtocol:"",dnscost:"domainLookupEnd"in N&&"domainLookupStart"in N&&typeof N.domainLookupEnd=="number"&&typeof N.domainLookupStart=="number"?N.domainLookupEnd-N.domainLookupStart:-1,tcpTlsCost:"connectEnd"in N&&"connectStart"in N&&typeof N.connectEnd=="number"&&typeof N.connectStart=="number"?N.connectEnd-N.connectStart:-1,reqCost:"requestStart"in N&&typeof N.requestStart=="number"&&"responseEnd"in N&&typeof N.responseEnd=="number"?N.responseEnd-N.requestStart:-1,handleCost:"leave_ts"in R&&"enter_ts"in R&&typeof R.leave_ts=="number"&&typeof R.enter_ts=="number"?R.leave_ts-R.enter_ts:-1}),Em(w),Array.isArray(t)?{gatewayInfo:Pu(w,a),proxyInfo:b,url:a,resourceTimingInfo:k}:Pu(w,a)},m=>{const g="gatewayInfo"in m?m.gatewayInfo:m,R="proxyInfo"in m?m.proxyInfo:void 0,v="resourceTimingInfo"in m?m.resourceTimingInfo:void 0;return g&&Z.joinChooseServer(n.sid,{role:h,lts:d,succ:!0,csAddr:a,serverList:g.gatewayAddrs.map(C=>C.address),ec:null,opid:p,cid:g.cid.toString(),uid:g.uid.toString(),csIp:g.csIp,unilbsServerIds:t.toString(),isHttp3:l,corssRegionTagReq:n.apRequestDetail,corssRegionTagRes:g.res.detail&&g.res.detail[38],vid:g==null?void 0:g.vid,resourceTimingInfo:v?JSON.stringify(v):void 0}),R&&Z.joinWebProxyAP(n.sid,{lts:d,sucess:1,apServerAddr:a,turnServerAddrList:R.addresses.map(C=>C.ip).join(","),errorCode:null,eventType:n.cloudProxyServer,unilbsServerIds:t.toString()}),!1},m=>m.code!==A.PB_ERROR&&m.code!==A.OPERATION_ABORTED&&(m.code===A.CAN_NOT_GET_GATEWAY_SERVER?m.data.retry:(Z.joinWebProxyAP(n.sid,{lts:d,sucess:0,apServerAddr:a,turnServerAddrList:null,errorCode:m.code,eventType:n.cloudProxyServer,unilbsServerIds:t.toString(),extend:JSON.stringify({networkState:E})}),_.warning("[".concat(n.clientId,"] multi unilbs network error, retry"),m),!0)),s)}function KU(e,t,n,i){let{url:r,areaCode:o}=e;const{clientId:s,sid:a}=t,c=Date.now();let d;const l=t.role,[h,u]=Sv(t,o,[Dt.CHOOSE_SERVER]);let p=At.networkState;return Fr(async()=>{p&&At.networkState===Jn.OFFLINE&&At.onlineWaiter&&await K.race([At.onlineWaiter,ln(i&&i.maxRetryTimeout||Bt.maxRetryTimeout)]),p=At.networkState;const{data:E,headers:m}=await Qr(r,{data:h,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);d=m.http3==="1"?1:-1,Z.reportResourceTiming(r,a),gv(E,r,t,c,[Dt.CHOOSE_SERVER],d);const g=ic(E,Dt.CHOOSE_SERVER);return Em(g),Pu(g,r)},E=>(E&&Z.joinChooseServer(a,{role:l,lts:c,succ:!0,csAddr:r,opid:u,serverList:E.gatewayAddrs.map(m=>m.address),ec:null,cid:E.cid.toString(),uid:E.uid.toString(),csIp:E.csIp,unilbsServerIds:[Dt.CHOOSE_SERVER].toString(),isHttp3:d,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:E.res.detail&&E.res.detail[38],vid:E.vid}),!1),E=>E.code!==A.OPERATION_ABORTED&&(E.code===A.CAN_NOT_GET_GATEWAY_SERVER?E.data.retry:(Z.joinChooseServer(a,{role:l,lts:c,succ:!1,csAddr:r,serverList:null,opid:u,ec:E.code,csIp:E.data&&E.data.csIp,unilbsServerIds:[Dt.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:p}),isHttp3:d,corssRegionTagReq:t.apRequestDetail}),_.warning("[".concat(s||"sid-".concat(a.slice(0,6)),"] Choose server network error, retry"),E),!0)),i)}function HU(e,t,n,i){let r,{url:o,areaCode:s,serviceIds:a}=e;const c=Date.now(),d=t.role,[l,h]=Sv(t,s,a);let u;return Fr(async()=>{u&&At.networkState===Jn.OFFLINE&&At.onlineWaiter&&await K.race([At.onlineWaiter,ln(i&&i.maxRetryTimeout||Bt.maxRetryTimeout)]),u=At.networkState;const{data:p,headers:E}=await Qr(o,{data:l,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);r=E.http3==="1"?1:-1,Z.reportResourceTiming(o,t.sid),gv(p,o,t,c,a,r);const m=ic(p,Dt.CHOOSE_SERVER),g=ic(p,t.cloudProxyServer==="proxy5"?Dt.CLOUD_PROXY_5:t.cloudProxyServer==="proxy3"||t.cloudProxyServer==="proxy4"?Dt.CLOUD_PROXY:Dt.CLOUD_PROXY_FALLBACK),R=performance.getEntriesByName(o),v=R[R.length-1];let C;return v&&(C={name:v.name,protocol:"nextHopProtocol"in v?v.nextHopProtocol:"",dnscost:"domainLookupEnd"in v&&"domainLookupStart"in v&&typeof v.domainLookupEnd=="number"&&typeof v.domainLookupStart=="number"?v.domainLookupEnd-v.domainLookupStart:-1,tcpTlsCost:"connectEnd"in v&&"connectStart"in v&&typeof v.connectEnd=="number"&&typeof v.connectStart=="number"?v.connectEnd-v.connectStart:-1,reqCost:"requestStart"in v&&typeof v.requestStart=="number"&&"responseEnd"in v&&typeof v.responseEnd=="number"?v.responseEnd-v.requestStart:-1,handleCost:"leave_ts"in p&&"enter_ts"in p&&typeof p.leave_ts=="number"&&typeof p.enter_ts=="number"?p.leave_ts-p.enter_ts:-1}),Em(m),{gatewayInfo:Pu(m,o),proxyInfo:g,url:o,resourceTimingInfo:C}},p=>{var E;return p.gatewayInfo&&Z.joinChooseServer(t.sid,{role:d,lts:c,succ:!0,csAddr:o,serverList:p.gatewayInfo.gatewayAddrs.map(m=>m.address),ec:null,opid:h,cid:p.gatewayInfo.cid.toString(),uid:p.gatewayInfo.uid.toString(),csIp:p.gatewayInfo.csIp,unilbsServerIds:a.toString(),isHttp3:r,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:p.gatewayInfo.res.detail&&p.gatewayInfo.res.detail[38],vid:(E=p.gatewayInfo)===null||E===void 0?void 0:E.vid,resourceTimingInfo:p.resourceTimingInfo?JSON.stringify(p.resourceTimingInfo):void 0}),p.proxyInfo&&Z.joinWebProxyAP(t.sid,{lts:c,sucess:1,apServerAddr:o,turnServerAddrList:p.proxyInfo.addresses.map(m=>m.ip).join(","),errorCode:null,eventType:t.cloudProxyServer,unilbsServerIds:a.toString()}),!1},p=>p.code!==A.OPERATION_ABORTED&&(p.code===A.CAN_NOT_GET_GATEWAY_SERVER?p.data.retry:(Z.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:o,turnServerAddrList:null,errorCode:p.code,eventType:t.cloudProxyServer,unilbsServerIds:a.toString(),extend:JSON.stringify({networkState:u})}),_.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),p),!0)),i)}const gv=(e,t,n,i,r,o)=>{const{sid:s,clientId:a,cloudProxyServer:c}=n,d=[],l=h=>{h.flag===4096?Z.joinChooseServer(s,{role:n.role,lts:i,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:h.error.message,csIp:h.error.data&&h.error.data.csIp,unilbsServerIds:r.toString(),isHttp3:o,corssRegionTagReq:n.apRequestDetail}):h.flag!==1048576&&h.flag!==4194304&&h.flag!==4194310||Z.joinWebProxyAP(s,{lts:i,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:h.error.code,eventType:c,unilbsServerIds:r.toString()})};if(e.response_body.forEach(h=>{const u=h.buffer.code;if(h.uri===23&&u===0&&!h.buffer.edges_services)if(h.buffer.flag===4194310)_.warning("no edge services in a
64p response of proxy fallback, will not set proxy in iceServers"),h.buffer.edges_services=[];else{const p={error:new D(A.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:T("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:h.buffer.flag};d.push(p),l(p)}if(u!==0){const p=vd(u),E={error:new D(A.CAN_NOT_GET_GATEWAY_SERVER,p.desc,{desc:p.desc,retry:p.retry,csIp:e.detail[502]}),flag:h.buffer.flag};h.buffer.flag===4194310?_.warning(E.error.toString()):d.push(E),l(E)}}),d.length)throw _.warning("[".concat(a||"sid-".concat(s.slice(0,6)),"] multi unilbs ").concat(t," failed, ").concat(d.map(h=>"flag: ".concat(h.flag,", message: ").concat(h.error.message,", retry: ").concat(h.error.data.retry)).join(" | "))),new D(A.CAN_NOT_GET_GATEWAY_SERVER,d.map(h=>"flag: ".concat(h.flag,", message: ").concat(h.error.message)).join(" | "),{retry:!!d.find(h=>h.error.data.retry),csIp:e.detail[502],desc:[...new Set(d.map(h=>{var u;return h==null||(u=h.error)===null||u===void 0||(u=u.data)===null||u===void 0?void 0:u.desc}).filter(h=>!!h))]})},Em=e=>{var t,n,i,r;if(e.addresses&&e.addresses.length===0&&e.code===0)throw new D(A.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});if(T("AP_AREA")&&((i=e.detail)!==null&&i!==void 0&&i[23]&&typeof((r=e.detail)===null||r===void 0?void 0:r[23])=="string"?jU(e.detail[23].toLowerCase()):jU()),(t=e.detail)!==null&&t!==void 0&&t[19]&&typeof((n=e.detail)===null||n===void 0?void 0:n[19])=="string"){const s=e.detail[19],a=s==null?void 0:s.split(";");for(let c=0;c<a.length;c++){var o;const d=Mn(o=a[c]).call(o),l=e.addresses[c];l&&a&&!l.fingerprint&&(e.addresses[c].fingerprint=d)}}if(T("GATEWAY_ADDRESS")&&T("GATEWAY_ADDRESS").length>0){_.debug("assign gateway address to",T("GATEWAY_ADDRESS"));const s=T("GATEWAY_ADDRESS").map(a=>{var c,d,l,h;const u=(c=(d=e.addresses.find(p=>p.ip===a.ip&&p.port===a.port))===null||d===void 0?void 0:d.fingerprint)!==null&&c!==void 0?c:"";return{ip:a.ip,port:a.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:u,iceUfrag:(l=e.addresses[0])===null||l===void 0?void 0:l.iceUfrag,icePwd:(h=e.addresses[0])===null||h===void 0?void 0:h.icePwd}});e.addresses=s}},fee=(e,t)=>{if(e.response_body&&e.response_body.length){const n=e.response_body[0];if(n.buffer.code!==0){const i=vd(n.buffer.code);throw new D(A.UPDATE_TICKET_FAILED,"[".concat(n.buffer.code,"]: ").concat(i.desc),{retry:i.retry})}return n.buffer.ticket}throw _.debug("update ticket request received ap response without response body:",t),new D(A.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},Sv=(e,t,n)=>{const i=Math.floor(Math.random()*1e12),r=e.role==="host"?"1":e.role==="audience"?"2":void 0,o={appid:e.appId,client_ts:Date.now(),opid:i,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:Xo(Xo(Xo({6:e.stringUid,11:t,12:T("USE_NEW_TOKEN")?"1":void 0},r?{17:r}:{}),{},{22:t},e.apRequestDetail?{33:e.apRequestDetail}:{}),e.apRTM?{26:"RTM2"}:{}),key:e.token,service_ids:n,uid:e.uid||0}}]};o.request_bodies.forEach(a=>{e.multiIP&&e.multiIP.gateway_ip&&(a.buffer.detail[5]=JSON.stringify({vocs_ip:[e.multiIP.uni_lbs_ip],vos_ip:[e.multiIP.gateway_ip]}))});const s=new FormData;return s.append("request",JSON.stringify(o)),[s,i]},gee=(e,t,n,i,r)=>{const o=Math.floor(Math.random()*1e12);return[lee(e,t,i,r,{opid:o,mode:e.mode,codec:e.codec,hasChangeBGPAddress:!1,ortc:n}),o]},See=(e,t)=>{const n=Math.floor(Math.random()*1e12),i={appid:e.appId,client_ts:Date.now(),opid:n,sid:e.sid,request_bodies:[{uri:28,buffer:{cname:e.cname,detail:{1:"",6:e.stringUid,12:"1"},token:e.token,service_ids:t,uid:e.uid||0,edges_services:e.apResponse.addresses.map(o=>({ip:o.ip,port:o.port}))}}]},r=new FormData;return r.append("request",JSON.stringify(i)),[r,n]};let Kd=0;function sc(e){return K.all(e.map(t=>t.then(n=>{throw n},n=>n))).then(t=>{throw t},t=>t)}const ac=async e=>{let{fragementLength:t,referenceList:n,asyncMapHandler:i,allFailedhandler:r,promisesCollector:o}=e,s=0;const a=t;let c,d=0;const l=async()=>{const h=(()=>{const u=s*a,p=u+a;return n.slice(u,p).map(i)})();o&&o.push(...h);try{c=await sc(h)}catch(u){if(d+=a,s++,!(d>=n.length))return void await l();r(u)}
64h.forEach(u=>u.cancel())};return await l(),c},YU=async e=>{let{referenceList:t,asyncMapHandler:n,closeFn:i}=e;const r=t.length;let o=0;const s=async()=>{const a=n(t.shift());try{return await a}catch(c){if(o++,o>=r||i!=null&&i(c))throw c;return s()}};return s()};async function Tee(){if(typeof VideoDecoder>"u")return!0;let e;const t=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,85,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,149,160,133,4,144,43,122,168,159,120,159,205,39,82,131,57,52,87,187,68,23,248,134,204,226,97,17,49,183,55,236,219,249,221,98,208,215,190,59,179,167,213,47,1,246,150,14,194,245,159,83,35,64,103,218,38,21,82,3,135,21,185,84,248,134],n=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,148,62,134,140,92,172,141,77,35,94,181,164,65,169,65,156,154,43,221,162,11,252,67,102,113,48,136,137,219,62,43,113,239,23,126,250,186,252,10,138,218,25,193,244,74,68,194,209,107,23,52,206,199,78,72,98,103,151,71,96,62,51,210,158,72,231,158],i=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,143,233,163,51,196,98,95,151,224,22,134,33,240,150,248,67,18,34,196,142,81,238,173,140,80,205,232,132,144,67,12,131,157,4,171,243,86,122,35,6,166,184,243,85,126,13,206,103,152,62,168,160,187,2,241,138,52,211,72,121,128,151,63,147,128,19,42],r=[18,0,50,138,1,48,192,64,253,248,65,17,67,192,32,0,16,0,0,0,0,0,0,0,195,12,48,144,64,32,0,209,75,61,9,204,25,115,79,226,115,63,63,208,70,210,220,153,126,241,237,37,107,195,153,1,99,112,230,189,209,169,130,10,11,22,167,215,159,205,197,7,183,162,26,48,254,141,134,103,32,16,235,45,1,15,18,119,169,110,206,251,51,115,202,60,148,1,46,39,109,25,28,86,168,15,77,211,239,2,58,43,146,26,230,184,81,48,140,226,226,250,222,146,171,133,164,13,188,180,64,122,142,146,32,208,238,170,193,35,53,44,225],o=[18,0,50,107,48,0,133,125,248,65,26,195,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,204,24,122,65,56,165,18,52,206,218,4,187,51,97,9,29,191,90,253,106,185,31,197,155,52,205,245,185,203,131,20,226,25,124,95,113,220,113,141,15,15,104,211,144,152,237,150,157,127,51,143,24,231,218,171,255,176,241,128,229,149,150,148,66,245,228,91,27,182,228,136,61,182,237,133,45,220,24,103,214,152],s=[18,0,50,122,48,1,9,253,248,65,26,67,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,198,182,231,242,220,235,163,140,12,36,36,166,46,132,210,4,71,23,218,132,27,30,17,45,244,79,31,243,195,136,100,169,76,88,142,85,204,217,121,168,29,163,198,17,251,223,73,12,212,244,139,123,151,179,75,216,96,208,136,40,229,42,59,149,10,116,228,85,99,93,221,108,255,140,248,20,30,167,122,109,206,164,108,197,110,251,23,243,133,160,63,13,207,177,12,128];return await new K((a,c)=>{let d;(async function(){e&&e.state!=="closed"||await async function(){e=new VideoDecoder({output:h=>{h.close(),clearTimeout(d),a(!0)},error:h=>{clearTimeout(d),a(!1)}}),await e.configure({codec:"av01.0.05M.08",width:160,height:90})}();const l=[t,n,i,r,o,s];for(let h=0;h<l.length;h++){const u=new EncodedVideoChunk({type:h==0?"key":"delta",timestamp:33333*h,duration:33333,data:new Uint8Array(l[h])});try{await e.decode(u)}catch{return void a(!1)}}})(),d=setTimeout(()=>{a(!1)},5e3)})}async function Fu(e,t,n,i){return{gatewayInfo:await async function(r,o,s,a){let c=null;const d=[],l=async()=>{const u=T("WEBCS_DOMAIN").slice(0,T("AJAX_REQUEST_CONCURRENT")).map(m=>({url:r.proxyServer?"https://".concat(r.proxyServer,"/ap/?url=").concat(m+"/api/v2/transpond/webrtc?v=2"):"https://".concat(m,"/api/v2/transpond/webrtc?v=2"),areaCode:oc()})),p=a.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:u.map(m=>m.url)}),E=await ac({fragementLength:T("FRAGEMENT_LENGTH"),referenceList:u,asyncMapHandler:m=>(_.debug("[".concat(r.clientId,"] Connect to choose_server:"),m.url),KU(m,r,o,s)),allFailedhandler:m=>{throw a.recordJoinChannelService({endTs:Date.now(),status:"error",errors:m},p),m[0]},promisesCollector:d});return a.recordJoinChannelService({endTs:Date.now(),status:"success"},p),E},h=async()=>{if(await ln(1e3),c!==null)return c;const u=T("WEBCS_DOMAIN_BACKUP_LIST").map(m=>({url:r.proxyServer?"https://".concat(r.proxyServer,"/ap/?url=").concat(m+"/api/v2/transpond/webrtc?v=2"):"https://".concat(m,"/api/v2/transpond/webrtc?v=2"),areaCode:oc()})),p=a.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:u.map(m=>m.url)}),E=await ac({fragementLength:T("FRAGEMENT_LENGTH"),referenceList:u,asyncMapHandler:m=>(_.debug("[".concat(r.clientId,"] Connect to backup choose_server:"),m.url),KU(m,r,o,s)),allFailedhandler:m=>{throw a.recordJoinChannelService({endTs:Date.now(),status:"error",errors:m},p),m[0]},promisesCollector:d});return a.recordJoinChannelService({endTs:Date.now(),status:"success"},p),E};try{return c=await sc([l(),h()]),d.length&&d.forEach(u=>u.cancel&&typeof u.cancel=="function"&&u.cancel()),c}catch(u){throw u[0]}}(e,t,n,i)}}async function XU(e,t,n,i,r){const o=e.cloudProxyServer;if(o==="disabled"){if(e.useLocalAccessPoint)return await Fu(e,t,n,r);if(T("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:u,proxyInfo:p}=await fm(e,t,n,r);if(e.turnServer&&e.turnServer.mode!=="auto")return{gatewayInfo:u};const E=p.map(m=>({turnServerURL:m.address,tcpport:m.tcpport||zt.tcpport,udpport:m.udpport||zt.udpport,username:m.username||zt.username,password:m.password||zt.password,forceturn:!1,security:!0}));if(r.useP2P){var s;const m=(s=e.uid)!==null&&s!==void 0?s:u.uid,g="glb:".concat(m.toString()),R=await eS(g),v=p.map(C=>({turnServerURL:C.address,tcpport:C.tcpport||zt.tcpport,udpport:C.udpport||zt.udpport,username:g,password:R,forceturn:!1,security:!0}));E.push(...v)}return e.turnServer={mode:"manual",servers:E},{gatewayInfo:u}}return await Fu(e,t,n,r)}const{proxyInfo:a,gatewayInfo:c}=await fm(e,t,n,r),d={gatewayInfo:c},l=a.map(u=>({turnServerURL:u.address,tcpport:o==="proxy3"?void 0:u.tcpport?u.tcpport:zt.tcpport,udpport:o==="proxy4"?void 0:u.udpport?u.udpport:zt.udpport,username:u.username||zt.username,password:u.password||zt.password,forceturn:o!=="proxy4",security:o==="proxy5"}));if(r.useP2P){var h;const u=(h=e.uid)!==null&&h!==void 0?h:c.uid,p="glb:".concat(u.toString()),E=await eS(p),m=a.map(g=>({turnServerURL:g.address,tcpport:o==="proxy3"?void 0:g.tcpport||zt.tcpport,udpport:o==="proxy4"?void 0:g.udpport||zt.udpport,username:p,password:E,forceturn:o!=="proxy4",security:o==="proxy5"}));l.push(...m)}return e.turnServer={mode:"manual",servers:l},_.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),d}async function Ree(e,t,n,i,r){const o=e.cloudProxyServer;if(o==="disabled"){if(e.useLocalAccessPoint)return await Fu(e,t,n,i);if(T("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:l,proxyInfo:h}=await fm(e,t,n,i,r);if(e.turnServer&&e.turnServer.mode!=="auto")return{gatewayInfo:l};const u=h.map(p=>({turnServerURL:p.address,tcpport:p.tcpport||zt.tcpport,udpport:p.udpport||zt.udpport,username:p.username||zt.username,password:p.password||zt.password,forceturn:!1,security:!0}));return e.turnServer={mode:"manual",servers:u},{gatewayInfo:l}}return{gatewayInfo:await async function(l,h,u,p,E){let m=null;const g=[],R=async()=>{const C=T("SDP_ENDPOINT_DOMAIN").slice(0,T("AJAX_REQUEST_CONCURRENT")).map(y=>({url:l.proxyServer?"https://".concat(l.proxyServer,"/ap/?url=").concat(y+"/api/v3/transpond/webrtc?v=3"):"https://".concat(y,"/api/v3/transpond/webrtc?v=3"),areaCode:oc()})),w=E.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:C.map(y=>y.url)}),b=await ac({fragementLength:T("FRAGEMENT_LENGTH"),referenceList:C,asyncMapHandler:y=>(_.debug("[".concat(l.clientId,"] Connect to choose_server:"),y.url),mm(y,Dt.CHOOSE_SERVER,l,h,E,u,p)),allFailedhandler:y=>{throw E.recordJoinChannelService({endTs:Date.now(),status:"error",errors:y},w),y[0]},promisesCollector:g});return E.recordJoinChannelService({endTs:Date.now(),status:"success"},w),b},v=async()=>
64{if(await ln(1e3),m!==null)return m;const C=T("SDP_ENDPOINT_DOMAIN_BACKUP_LIST").map(y=>({url:l.proxyServer?"https://".concat(l.proxyServer,"/ap/?url=").concat(y+"/api/v3/transpond/webrtc?v=3"):"https://".concat(y,"/api/v3/transpond/webrtc?v=3"),areaCode:oc()})),w=E.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:C.map(y=>y.url)}),b=await ac({fragementLength:T("FRAGEMENT_LENGTH"),referenceList:C,asyncMapHandler:y=>(_.debug("[".concat(l.clientId,"] Connect to backup choose_server:"),y.url),mm(y,Dt.CHOOSE_SERVER,l,h,E,u,p)),allFailedhandler:y=>{throw E.recordJoinChannelService({endTs:Date.now(),status:"error",errors:y},w),y[0]},promisesCollector:g});return E.recordJoinChannelService({endTs:Date.now(),status:"success"},w),b};try{return m=await sc([R(),v()]),g.length&&g.forEach(C=>C.cancel&&typeof C.cancel=="function"&&C.cancel()),m}catch(C){throw C[0]}}(e,r,t,n,i)}}const{proxyInfo:s,gatewayInfo:a}=await fm(e,t,n,i),c={gatewayInfo:a},d=s.map(l=>({turnServerURL:l.address,tcpport:o==="proxy3"?void 0:l.tcpport?l.tcpport:zt.tcpport,udpport:o==="proxy4"?void 0:l.udpport?l.udpport:zt.udpport,username:l.username||zt.username,password:l.password||zt.password,forceturn:o!=="proxy4",security:o==="proxy5"}));return e.turnServer={mode:"manual",servers:d},_.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),c}async function Tv(e,t,n,i,r){const o=T("ACCOUNT_REGISTER").slice(0,T("AJAX_REQUEST_CONCURRENT"));let s=[];s=t.proxyServer?o.map(c=>"https://".concat(t.proxyServer,"/ap/?url=").concat(c+"/api/v1")):o.map(c=>"https://".concat(c,"/api/v1"));const a=r==null?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:s});try{const c=await async function(d,l,h,u,p){const E=Date.now(),m={sid:h.sid,opid:10,appid:h.appId,string_uid:l};let g=d[0];const R=await Fr(()=>Qr(g+"".concat(g.indexOf("?")===-1?"?":"&","action=stringuid"),{data:m,cancelToken:u,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}}),(v,C)=>{if(v.code===0){if(v.uid<=0||v.uid>=Math.pow(2,32))throw _.error("Invalid Uint Uid ".concat(l," => ").concat(v.uid),v),Z.reqUserAccount(m.sid,{lts:E,success:!1,serverAddr:g,stringUid:m.string_uid,uid:v.uid,errorCode:A.INVALID_UINT_UID_FROM_STRING_UID,extend:m}),new D(A.INVALID_UINT_UID_FROM_STRING_UID);return Z.reqUserAccount(m.sid,{lts:E,success:!0,serverAddr:g,stringUid:m.string_uid,uid:v.uid,errorCode:null,extend:m}),!1}const w=vd(v.code);return w.retry&&(g=d[(C+1)%d.length]),Z.reqUserAccount(m.sid,{lts:E,success:!1,serverAddr:g,stringUid:m.string_uid,uid:v.uid,errorCode:w.desc,extend:m}),w.retry},(v,C)=>v.code!==A.OPERATION_ABORTED&&(Z.reqUserAccount(m.sid,{lts:E,success:!1,serverAddr:g,stringUid:m.string_uid,uid:null,errorCode:v.code,extend:m}),g=d[(C+1)%d.length],!0),p);if(R.code!==0){const v=vd(R.code);throw new D(A.UNEXPECTED_RESPONSE,v.desc)}return R}(s,e,t,n,i);return r==null||r.recordJoinChannelService({status:"success",endTs:Date.now()},a),c.uid}catch(c){throw r==null||r.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[c]},a),c}}async function vee(e,t,n){const i=T("ACCOUNT_REGISTER");let r=[];r=t.proxyServer?i.map(o=>"https://".concat(t.proxyServer,"/ap/?url=").concat(o+"/api/v1")):i.map(o=>"https://".concat(o,"/api/v1"));try{return await YU({referenceList:r,asyncMapHandler:o=>async function(s,a,c,d){const l=Date.now(),h={sid:c.sid,opid:10,appid:c.appId,string_uid:a};try{const u=await Qr(s+"".concat(s.indexOf("?")===-1?"?":"&","action=stringuid"),{data:h,cancelToken:d,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}});if(u.code!==0){const p=vd(u.code);throw new D(A.UNEXPECTED_RESPONSE,"preload sua error:".concat(p.desc),p)}if(u.uid<=0||u.uid>=Math.pow(2,32))throw new D(A.INVALID_UINT_UID_FROM_STRING_UID);return{requestTime:l,url:s,req:h,uid:u.uid,elapse:Date.now()-l}}catch(u){throw u}}(o,e,t,n),closeFn:o=>o.code===A.OPERATION_ABORTED||o.code===A.UNEXPECTED_RESPONSE&&!o.data.retry})}catch(o){throw o}}async function Aee(e,t,n){const i=T("CDS_AP").slice(0,T("AJAX_REQUEST_CONCURRENT")).map(c=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(c+"/api/v1"):"https://".concat(c,"/api/v1?action=config")),r=i.map(c=>function(d,l,h,u){const p=Fe(),E={flag:64,cipher_method:0,features:Xo(Xo(Xo(Xo(Xo({install_id:Jl(),device:p.name,system:p.os,system_general:navigator.userAgent,vendor:l.appId,version:qi,cname:l.cname,session_id:l.sid,proxyServer:l.proxyServer,sdk_type:pee.WEB_RTC,browser_name:p.name,browser_version:p.version,user_agent:navigator.userAgent,channel_name:l.cname},l.stringUid&&{string_uid:l.stringUid}),l.uid&&{uid:l.uid+""}),p.os&&{os_name:p.os}),p.osVersion&&{os_version:p.osVersion}),{},{detail:""})};return Fr(()=>Qr(d,{data:E,timeout:1e3,cancelToken:h,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}}),void 0,m=>m.code!==A.OPERATION_ABORTED,u)}(c,e,t,n));let o=null,s=null,a={};try{o=await sc(r)}
64catch(c){if(c.code===A.OPERATION_ABORTED)throw c;s=c}if(r.forEach(c=>c.cancel()),Z.reportApiInvoke(e.sid,{name:vt.REQUEST_CONFIG_DISTRIBUTE,options:{error:s,res:o}}).onSuccess(),o&&o.test_tags)try{a=function(c){if(!c.test_tags)return{};const d=c.test_tags,l=Object.keys(d),h={};return l.forEach(u=>{var p;const E=Mn(p=u.slice(4)).call(p),m=JSON.parse(d[u]),g=m[1];h[E]={tag:m[0]||"",value:g}}),h}(o)}catch{}return a}async function JU(e,t){const n=T("WEBCS_DOMAIN").concat(T("WEBCS_DOMAIN_BACKUP_LIST")).map(i=>({url:"https://".concat(i,"/api/v2/transpond/webrtc?v=2"),areaCode:oc(),serviceIds:[Dt.CHOOSE_SERVER,Dt.CLOUD_PROXY_FALLBACK]}));try{return await YU({referenceList:n,asyncMapHandler:i=>async function(r,o,s){let a,{url:c,areaCode:d,serviceIds:l}=r;const h=Date.now(),[u,p]=Sv(o,d,l);let E=At.networkState;try{E&&At.networkState===Jn.OFFLINE&&At.onlineWaiter&&await K.race([At.onlineWaiter,ln(Bt.maxRetryTimeout)]),E=At.networkState;const{data:m,headers:g}=await Qr(c,{data:u,cancelToken:s,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);a=g.http3==="1"?1:-1,(C=>{const w=[];if(C.response_body.forEach(b=>{const y=b.buffer.code;if(b.uri===23&&y===0&&!b.buffer.edges_services)if(b.buffer.flag===4194310)b.buffer.edges_services=[];else{const N={error:new D(A.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:T("NO_EDGES_RETRY"),csIp:C.detail[502]}),flag:b.buffer.flag};w.push(N)}if(y!==0){const N=vd(y),k={error:new D(A.CAN_NOT_GET_GATEWAY_SERVER,N.desc,{desc:N.desc,retry:N.retry,csIp:C.detail[502]}),flag:b.buffer.flag};b.buffer.flag===4194310?_.warning(k.error.toString()):w.push(k)}}),w.length)throw new D(A.CAN_NOT_GET_GATEWAY_SERVER,w.map(b=>"flag: ".concat(b.flag,", message: ").concat(b.error.message)).join(" | "),{retry:!!w.find(b=>b.error.data.retry),csIp:C.detail[502],desc:[...new Set(w.map(b=>{var y;return b==null||(y=b.error)===null||y===void 0||(y=y.data)===null||y===void 0?void 0:y.desc}).filter(b=>!!b))]})})(m);const R=ic(m,Dt.CHOOSE_SERVER),v=ic(m,Dt.CLOUD_PROXY_FALLBACK);return Em(R),{gatewayInfo:Pu(R,c),proxyInfo:v,opid:p,requestTime:h,url:c,isHttp3:a,elapse:Date.now()-h}}catch(m){throw m}}(i,e,t),closeFn:i=>i.code===A.OPERATION_ABORTED||i.code===A.CAN_NOT_GET_GATEWAY_SERVER&&!i.data.retry})}catch(i){throw i}}async function fm(e,t,n,i,r){const o=T("PROXY_SERVER_TYPE3"),s=(E,m,g)=>{let R=g||o;return Array.isArray(R)&&(R=m%2==0&&o[1]||o[0]),"https://".concat(R,"/ap/?url=").concat(E)};let a=null;const c=[],d=async()=>{const E=T(r?"SDP_ENDPOINT_DOMAIN":"WEBCS_DOMAIN").slice(0,T("AJAX_REQUEST_CONCURRENT")).map((R,v)=>{let C;return C=e.cloudProxyServer==="disabled"&&e.proxyServer?s("".concat(R,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),v,e.proxyServer):e.cloudProxyServer==="disabled"||e.cloudProxyServer==="fallback"?"https://".concat(R,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"):s("".concat(R,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),v),{url:C,areaCode:oc(),serviceIds:[Dt.CHOOSE_SERVER,e.cloudProxyServer==="proxy5"?Dt.CLOUD_PROXY_5:e.cloudProxyServer==="proxy3"||e.cloudProxyServer==="proxy4"?Dt.CLOUD_PROXY:Dt.CLOUD_PROXY_FALLBACK]}}),m=i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:E.map(R=>R.url)}),g=await ac({fragementLength:T("FRAGEMENT_LENGTH"),referenceList:E,asyncMapHandler:R=>(_.debug("[".concat(e.clientId,"] Connect to choose_server:"),R.url),r?mm(R,R.serviceIds,e,r,i,t,n):HU(R,e,t,n)),allFailedhandler:R=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:R},m),R[0]},promisesCollector:c});return i.recordJoinChannelService({endTs:Date.now(),status:"success"},m),g},l=async()=>{if(await ln(1e3),a!==null)return a;const E=T(T(r?"SDP_ENDPOINT_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN_BACKUP_LIST")).map((R,v)=>{let C;return C=e.cloudProxyServer==="disabled"&&e.proxyServer?s("".concat(R,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),v,e.proxyServer):e.cloudProxyServer==="disabled"||e.cloudProxyServer==="fallback"?"https://".concat(R,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"):s("".concat(R,"/").concat(r?"api/v3/transpond/webrtc?v=3":"api/v2/transpond/webrtc?v=2"),v),{url:C,areaCode:oc(),serviceIds:[Dt.CHOOSE_SERVER,e.cloudProxyServer==="proxy5"?Dt.CLOUD_PROXY_5:e.cloudProxyServer==="proxy3"||e.cloudProxyServer==="proxy4"?Dt.CLOUD_PROXY:Dt.CLOUD_PROXY_FALLBACK]}}),m=i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:E.map(R=>R.url)}),g=await ac({fragementLength:T("FRAGEMENT_LENGTH"),referenceList:E,asyncMapHandler:R=>(_.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),R.url),r?mm(R,R.serviceIds,e,r,i,t,n):HU(R,e,t,n)),allFailedhandler:R=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:R},m),R[0]},promisesCollector:c}
64);return i.recordJoinChannelService({endTs:Date.now(),status:"success"},m),g};let h,u,p;try{({gatewayInfo:h,proxyInfo:u,url:p}=await sc([d(),l()]))}catch(E){throw E[0]}if(c.length&&c.forEach(E=>E.cancel&&typeof E.cancel=="function"&&E.cancel()),!h||!u)throw new D(A.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=p,e.cloudProxyServer!=="disabled"&&Array.isArray(o)&&p){const E=/^https?:\/\/(.+?)(\/.*)?$/.exec(p)[1];x(o).call(o,E)&&(e.proxyServer=E,_.setProxyServer(E),Z.setProxyServer(E))}return a={gatewayInfo:h,proxyInfo:await RU(u,h.uid)},a}async function Cee(e,t,n){const i=T("UAP_AP").slice(0,T("AJAX_REQUEST_CONCURRENT")).map(o=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(o+"/api/v1?action=uap"):"https://".concat(o,"/api/v1?action=uap")),r=i.map(o=>function(s,a,c,d){const l={command:"convergeAllocateEdge",sid:a.sid,appId:a.appId,token:a.token,ts:Date.now(),version:qi,cname:a.cname,uid:a.uid.toString(),requestId:fv,seq:fv};fv+=1;const h={service_name:"tele_channel",json_body:JSON.stringify(l)};return Fr(async()=>{const u=await Qr(s,{data:h,cancelToken:c,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(u.code!==0){const E=new D(A.UNEXPECTED_RESPONSE,"cross channel ap error, code"+u.code,{retry:!0});throw _.error(E.toString()),E}const p=JSON.parse(u.json_body);if(p.code!==200){const E=new D(A.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(p.code,", reason: ").concat(p.reason));throw _.error(E.toString()),E}if(!p.servers||p.servers.length===0){const E=new D(A.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw _.error(E.toString()),E}return{vid:p.vid,workerToken:p.workerToken,addressList:(T("CHANNEL_MEDIA_RELAY_SERVERS")||p.servers).map(E=>"wss://".concat(E.address.replace(/\./g,"-"),".").concat(T("WORKER_DOMAIN"),":").concat(E.wss))}},void 0,u=>!!(u.code!==A.OPERATION_ABORTED&&u.code!==A.UNEXPECTED_RESPONSE||u.data&&u.data.retry),d)}(o,e,t,n));try{const o=await sc(r);return r.forEach(s=>s.cancel()),o}catch(o){throw o[0]}}async function yee(e,t,n){let i=null;const r=[],o=async s=>{const a=T(s?"WEBCS_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN").map(c=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(c+"/api/v2/transpond/webrtc?v=2"):"https://".concat(c,"/api/v2/transpond/webrtc?v=2"));return s&&(await ln(1e3),i!==null)?i:await ac({fragementLength:T("FRAGEMENT_LENGTH"),referenceList:a,asyncMapHandler:c=>(_.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(s?"backup":""," choose_server:"),c),function(d,l,h,u){const[p]=See(l,[Dt.CHOOSE_SERVER]);let E=At.networkState;return Fr(async()=>{E&&At.networkState===Jn.OFFLINE&&At.onlineWaiter&&await K.race([At.onlineWaiter,ln(u&&u.maxRetryTimeout||Bt.maxRetryTimeout)]),E=At.networkState;const m=await Qr(d,{data:p,cancelToken:h,headers:{"Content-Type":"multipart/form-data;"}},!0);return fee(m,d)},()=>!1,m=>m.code!==A.OPERATION_ABORTED&&(m.code===A.UPDATE_TICKET_FAILED?m.data.retry:(_.w
64arning("[".concat(l.clientId,"] update ticket network error, retry"),m),!0)),u)}(c,e,t,n)),allFailedhandler:c=>{throw c[0]},promisesCollector:r})};try{return i=await sc([o(!1),o(!0)]),r.length&&r.forEach(s=>s.cancel&&typeof s.cancel=="function"&&s.cancel()),i}catch(s){throw s[0]}}function zU(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Rv(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?zU(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):zU(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}class Iee extends Nt{get isSuccess(){return!!this.configs}constructor(t,n){super(),S(this,"configs",void 0),S(this,"store",void 0),S(this,"joinInfo",void 0),S(this,"cancelToken",void 0),S(this,"retryConfig",{timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4}),S(this,"interval",void 0),S(this,"mutex",void 0),S(this,"mutableParamsRead",!1),S(this,"configCache",{}),S(this,"limit_bitrate",void 0),this.mutex=new An("config-distribute",t),this.store=n}startGetConfigDistribute(t,n){this.joinInfo=t,this.cancelToken=n,this.interval&&this.stopGetConfigDistribute(),T("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval(()=>{this.updateConfigDistribute()},T("CONFIG_DISTRIBUTE_INTERVAL")))}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0,this.configs=void 0,this.limit_bitrate=void 0}async awaitConfigDistributeComplete(){this.mutex.isLocked&&(await this.mutex.lock())()}async updateConfigDistribute(){if(this.mutableParamsRead||(this.mutableParamsRead=!0,Z.reportApiInvoke(null,{options:void 0,name:vt.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:ht.TRACER}).onSuccess(JSON.stringify(Zi))),!this.joinInfo||!this.cancelToken||!this.retryConfig)return void _.debug("[config-distribute] get config distribute interrupted have no joininfo");let t;const n=await this.mutex.lock();try{t=await Aee(this.joinInfo,this.cancelToken,this.retryConfig),_.debug("[config-distribute] get config distribute",JSON.stringify(t));const i=function(r){var o;const s=Pi(o=Object.keys(r).filter(d=>/^webrtc_ng_global_parameter/.test(d))).call(o);for(let d=0;d<s.length;d++)for(let l=s.length-1;l>d;l--){const h=s[l],u=r[h].value;if(typeof u.__priority=="number"){const p=u.__priority,E=s[l-1],m=r[E].value;if(typeof m.__priority=="number"){if(!(p>m.__priority))continue;{const g=h;s[l]=s[l-1],s[l-1]=g}}else{const g=h;s[l]=s[l-1],s[l-1]=g}}}const a=Date.now(),c={};return s.forEach(d=>{const l=r[d].value.__expires;l&&l<=a||(c[d]=r[d])}),c}(t);this.cacheGlobalParameterConfig(i),this.store.hasStartJoinChannel||(this.store.isABTestSuccess=!0),this.configs=i}catch(i){const r=new D(A.NETWORK_RESPONSE_ERROR,i);_.warning("[config-distribute] ".concat(r.toString()))}finally{n()}}getBitrateLimit(){return this.limit_bitrate||void 0}handleBitrateLimit(t){MP(t)&&(this.limit_bitrate?this.limit_bitrate&&this.limit_bitrate.id!==t.id&&this.emit(ho.UPDATE_BITRATE_LIMIT,t):this.emit(ho.UPDATE_BITRATE_LIMIT,t))}getLowStreamConfigDistribute(){return this.limit_bitrate&&Rv({},this.limit_bitrate.low_stream_uplink)}handleABTestConfigDistribute(t){try{const n={},i=Object.keys(t),r=[];i.forEach(o=>{const s=t[o].value;n[o]=s;const a=s.__id;if(a&&this.configCache[o]&&this.configCache[o].__id===a)return;const c=s.__type,d=t[o].value,l=t[o].tag;let h=0;c?c===WO.REALTIME&&(h=1):Object.keys(d).some(u=>Object.prototype.hasOwnProperty.call(ES,u)||!zS()&&Object.prototype.hasOwnProperty.call(Dp,u)?(h=1,!0):void 0),r.push({tag:l,isApplied:h,feature:o,params:JSON.stringify(s)})}),r.forEach(o=>{let{tag:s,feature:a,params:c,isApplied:d}=o;this.store.sessionId&&Z.abTest(this.store.sessionId,{intSucc:1,isApplied:d,tag:s,feature:a,params:c,cid:this.store.cid,uid:this.store.intUid})}),this.configCache=n}catch(n){_.debug("handleABTestConfigDistribute error",n)}}cacheGlobalParameterConfig(t){const n=function(r){const o={};return Object.keys(r).forEach(s=>{const a=r[s].value,c=a.__expires,d=a.__type;
64Object.keys(a).forEach(l=>{l==="__id"||l==="__type"||l==="__priority"||l==="__expires"||Object.prototype.hasOwnProperty.call(o,l)||(o[l]=Rv(Rv({value:a[l]},c&&{expires:c}),d&&{type:d}))})}),o}(t);try{var i;const r=(i=n.LIMIT_BITRATE)===null||i===void 0?void 0:i.value;if(delete n.LIMIT_BITRATE,r&&MP(r)&&this.handleBitrateLimit(r),this.limit_bitrate=r,this.handleGlobalParameterConfig(n),this.handleABTestConfigDistribute(t),function(a){try{const c=Date.now();Object.keys(a).forEach(d=>{const{value:l,type:h,expires:u}=a[d];u&&u<=c||((h===WO.REALTIME||Object.prototype.hasOwnProperty.call(ES,d))&&(Zi[d]=l,tt[d]=l,_.debug("Update realtime parameters from config distribute",d,l)),h||zS()||!Object.prototype.hasOwnProperty.call(Dp,d)||(Zi[d]=l,tt[d]=l,_.debug("Update gateway parameters from config distribute",d,l)))})}catch(c){_.error("Error update config immediately: ".concat(a),c.message)}}(n),function(a){try{var c;if(!T("ENABLE_CONFIG_RESTORE"))return!1;const d=tN(a),l=window.localStorage.getItem(Mp);if(!l)return!1;const h=JSON.parse(l),u=T("BLOCKED_CONFIG_MAX_TIME");return Date.now()-h.timestamp>u?(CS(),!1):x(c=h.configHashes).call(c,d)}catch(d){return _.debug("[error] ".concat(jr," error checking blocked config:"),d),!1}}(n))return _.debug("[warning] [config-distribute] blocked config detected and skipped"),void Z.reportAlarm(this.store.sessionId||null,{type:QO.CONFIG_DISTRIBUTE,status:ZO.RECOVER,message:"Blocked config detected and skipped"});(function(a){try{const c=tN(a),d=Up();if(d.currentConfigHash&&d.currentConfigHash===c)return nN({currentConfigHash:c,configVerified:!0}),AS(),CS(),void _.debug("".concat(jr," config verified as safe, skip further checks"));nN({currentConfigHash:c,configVerified:!1}),AS(),CS()}catch(c){_.debug("[error] ".concat(jr," error on config applied:"),c)}})(n);const o=JSON.stringify(n),s=window.btoa(o);window.localStorage.setItem("websdk_ng_global_parameter",s),_.debug("Caching global parameters ".concat(o))}catch(r){_.error("Error caching global parameters:",r.message)}}handleGlobalParameterConfig(t){try{const n=Date.now();Object.keys(t).forEach(i=>{switch(i){case"CLIENT_ROLE_OPTIONS":if(Object.prototype.hasOwnProperty.call(tt,i)){const{value:o,expires:s}=t[i];if(s&&s<=n)return;oS(tt[i],o)||(Zi[i]=o,tt[i]=o,this.emit(ho.UPDATE_CLIENT_ROLE_OPTIONS,o),_.debug("Updating client role options: ".concat(JSON.stringify(o))))}break;case"REMOTE_VIDEO_STREAM_TYPE":if(Object.prototype.hasOwnProperty.call(tt,i)){var r;const{value:o,expires:s}=t[i];if(s&&s<=n)return;typeof o=="number"&&x(r=[0,1,4,5,6,7,8,9]).call(r,o)&&(Zi[i]={value:o},tt[i]=o,this.emit(ho.UPDATE_REMOTE_VIDEO_STREAM_TYPE,o),_.debug("Updating client remote stream type: ".concat(JSON.stringify(o))))}break;case"ENABLE_FORCE_HLS":if(Object.prototype.hasOwnProperty.call(tt,i)){const{value:o,expires:s}=t[i];if(s&&s<=n)return;oS(tt[i],o)||(Zi[i]=o,tt[i]=o,this.emit(ho.FALLBACK_TO_HLS,o),_.debug("Updating enable force hls: ".concat(JSON.stringify(o))))}break;case"VOS_CONFIGURE":if(Object.prototype.hasOwnProperty.call(tt,i)){const{value:o,expires:s}=t[i];if(s&&s<=n)return;oS(tt[i],o)||(Zi[i]=o,tt[i]=o,this.emit(ho.UPDATE_VOS_CONFIGURE,o),_.debug("Updating vos configure: ".concat(JSON.stringify(o))))}}})}catch(n){_.error("Error handling global parameter config:",n.message)}}}class bee extends Nt{constructor(){super(...arguments),S(this,"resultStorage",new Map)}setLocalAudioStats(t,n,i){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",t,this.checkAudioInputLevel(i,n)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",t,this.checkSendAudioBitrate(i,n))}setLocalVideoStats(t,n,i){this.record("SEND_VIDEO_BITRATE_TOO_LOW",t,this.checkSendVideoBitrate(i,n)),this.record("FRAMERATE_INPUT_TOO_LOW",t,this.checkFramerateInput(i,n)),this.record("FRAMERATE_SENT_TOO_LOW",t,this.checkFramerateSent(i)),!n.muted&&this.record("VIDEO_ENCODE_FAILED",t,this.checResolutionSent(i))}setRemoteAudioStats(t,n){const i=t.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",i,this.checkAudioOutputLevel(n))}setRemoteVideoStats(t,n){const i=t.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",i,this.checkVideoDecode(n))}record(t,n,i){if(T("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(t)||this.resultStorage.set(t,{result:[],isPrevNormal:!0});const r=this.resultStorage.get(t);if(!r)return;r.result.push(i);const o=t==="VIDEO_ENCODE_FAILED"?T("ENCODE_EXCEPTION_TIMES"):5;if(r.result.length>=o){var s;const a=x(s=r.result).call(s,!0);
64r.isPrevNormal&&!a&&this.emit("exception",vv[t],t,n),!r.isPrevNormal&&a&&this.emit("exception",vv[t]+2e3,t+"_RECOVER",n),r.isPrevNormal=a,r.result=[]}}checkAudioOutputLevel(t){return!(t.receiveBitrate>0&&t.receiveLevel===0)}checkAudioInputLevel(t,n){return n instanceof En&&!n.isActive||!!n.muted||t.sendVolumeLevel!==0}checkFramerateInput(t,n){let i=null;n._encoderConfig&&n._encoderConfig.frameRate&&(i=mi(n._encoderConfig.frameRate));const r=t.captureFrameRate;return!i||!r||!(i>10&&r<5||i<10&&i>=5&&r<=1)}checkFramerateSent(t){return!(t.captureFrameRate&&t.sendFrameRate&&t.captureFrameRate>5&&t.sendFrameRate<=1)}checResolutionSent(t){var n;return!(!t.codecType||x(n=T("ENCODE_EXCEPTION_VALIDATE_CODEC")).call(n,t.codecType.toLocaleLowerCase()))||!t.captureFrameRate||t.sendFrameRate!==0||t.sendResolutionWidth!==0||t.sendResolutionHeight!==0}checkSendVideoBitrate(t,n){return!!n.muted||t.sendBitrate!==0}checkSendAudioBitrate(t,n){return n instanceof En&&!n.isActive||!!n.muted||t.sendBitrate!==0}checkVideoDecode(t){return t.receiveBitrate===0||t.decodeFrameRate!==0}}const vv={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003,VIDEO_ENCODE_FAILED:2004},jn=new class{markSubscribeStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/subscribe-").concat(t))}markPublishStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/publish-").concat(t))}measureFromSubscribeStart(e,t){const n=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(n.length>0){const i=n[n.length-1];return Math.round(performance.now()-i.startTime)}return 0}measureFromPublishStart(e,t){const n=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(n.length>0){const i=n[n.length-1];return Math.round(performance.now()-i.startTime)}return 0}};function qU(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function cc(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?qU(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):qU(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}class Bu{constructor(t){S(this,"store",void 0),S(this,"onStatsException",void 0),S(this,"onUploadPublishDuration",void 0),S(this,"onStatsChanged",void 0),S(this,"onVideoCodecChanged",void 0),S(this,"localStats",new Map),S(this,"remoteStats",new Map),S(this,"updateStatsInterval",void 0),S(this,"trafficStats",void 0),S(this,"trafficStatsPeerList",[]),S(this,"uplinkStats",void 0),S(this,"exceptionMonitor",void 0),S(this,"p2pChannel",void 0),S(this,"scalabilityMode",Op.L1T1),S(this,"updateStats",()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))}),this.store=t,this.exceptionMonitor=new bee,this.exceptionMonitor.on("exception",(n,i,r)=>{this.onStatsException&&this.onStatsException(n,i,r)})}startUpdateStats(){this.updateStatsInterval||(this.updateStatsInterval=window.setInterval(this.updateStats,1e3))}stopUpdateStats(){this.updateStatsInterval&&(window.clearInterval(this.updateStatsInterval),this.updateStatsInterval=void 0)}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(G.LocalAudioTrack)||cc({},wS)}getLocalVideoTrackStats(){return this.localStats.get(G.LocalVideoTrack)||cc({},OS)}getRemoteAudioTrackStats(t){const n=(o,s)=>{if(!this.trafficStats)return s;const a=this.trafficStats.peer_delay.find(c=>c.peer_uid===o);return a&&(s.publishDuration=a.B_ppad+(Date.now()-this.trafficStats.timestamp)),s},i={};if(t){var r;const o=(r=this.remoteStats.get(t))===null||r===void 0?void 0:r.audioStats;o&&(i[t]=n(t,o))}
64else Array.from(this.remoteStats.entries()).forEach(o=>{let[s,{audioStats:a}]=o;a&&(i[s]=n(s,a))});return i}getRemoteNetworkQualityStats(t){const n={};if(t){var i;const r=(i=this.remoteStats.get(t))===null||i===void 0?void 0:i.networkStats;r&&(n[t]=r)}else Array.from(this.remoteStats.entries()).forEach(r=>{let[o,{networkStats:s}]=r;s&&(n[o]=s)});return n}getNetworkQuality(){let t=0,n=0;return this.trafficStats&&(t=sm(this.trafficStats.B_unq),n=sm(this.trafficStats.B_dnq)),{uplinkNetworkQuality:t,downlinkNetworkQuality:n}}getRemoteVideoTrackStats(t){const n=(o,s)=>{if(!this.trafficStats)return s;const a=this.trafficStats.peer_delay.find(c=>c.peer_uid===o);return a&&(s.publishDuration=a.B_ppvd+(Date.now()-this.trafficStats.timestamp)),s},i={};if(t){var r;const o=(r=this.remoteStats.get(t))===null||r===void 0?void 0:r.videoStats;o&&(i[t]=n(t,o))}else Array.from(this.remoteStats.entries()).forEach(o=>{let[s,{videoStats:a}]=o;a&&(i[s]=n(s,a))});return i}getRTCStats(){let t=0,n=0,i=0,r=0;const o=this.localStats.get(G.LocalAudioTrack);o&&(t+=o.sendBytes,n+=o.sendBitrate);const s=this.localStats.get(G.LocalVideoTrack);s&&(t+=s.sendBytes,n+=s.sendBitrate);const a=this.localStats.get(G.LocalVideoLowTrack);
64a&&(t+=a.sendBytes,n+=a.sendBitrate),this.remoteStats.forEach(d=>{let{audioStats:l,videoStats:h}=d;l&&(i+=l.receiveBytes,r+=l.receiveBitrate),h&&(i+=h.receiveBytes,r+=h.receiveBitrate)});let c=1;return this.trafficStats&&(c+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:c,SendBitrate:n,SendBytes:t,RecvBytes:i,RecvBitrate:r,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(t){this.localStats.set(t,void 0)}removeLocalStats(t){t?this.localStats.delete(t):this.localStats.clear()}addRemoteStats(t){this.remoteStats.set(t,{})}removeRemoteStats(t){t?this.remoteStats.delete(t):this.remoteStats.clear()}addP2PChannel(t){this.p2pChannel=t}updateTrafficStats(t){t.peer_delay=t.peer_delay.filter(n=>n.B_ppad!==void 0||n.B_ppvd!==void 0),t.peer_delay.filter(n=>this.trafficStatsPeerList.indexOf(n.peer_uid)===-1).forEach(n=>{var i;const r=(i=this.p2pChannel)===null||i===void 0?void 0:i.getRemoteMedia(n.peer_uid),o=r!=null&&r.videoSSRC?jn.measureFromSubscribeStart(this.store.clientId,r.videoSSRC):0,s=r!=null&&r.audioSSRC?jn.measureFromSubscribeStart(this.store.clientId,r.audioSSRC):0;n.B_ppad!==void 0&&n.B_ppvd!==void 0&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(n.peer_uid,n.B_ppad,n.B_ppvd,o>s?o:s),this.trafficStatsPeerList.push(n.peer_uid))}),this.trafficStats=t}updateUplinkStats(t){this.uplinkStats&&this.uplinkStats.B_fir!==t.B_fir&&_.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(t.B_fir)),this.uplinkStats=t}static isRemoteVideoFreeze(t,n,i){if(!t)return!1;const r=!!i&&n.framesDecodeFreezeTime>i.framesDecodeFreezeTime,o=!i||n.framesDecodeCount>i.framesDecodeCount;return r||!o}static isRemoteAudioFreeze(t){return!!t&&t._isFreeze()}isLocalVideoFreeze(t){return!(!t.inputFrame||!t.sentFrame)&&t.inputFrame.frameRate>5&&t.sentFrame.frameRate<3}updateLocalStats(t){Array.from(this.localStats.entries()).forEach(n=>{let[i,r]=n;switch(i){case G.LocalVideoTrack:case G.LocalVideoLowTrack:{const a=r,c=cc({},OS),d=t.getStats(),l=t.getLocalMedia(i);if(d){const h=d.videoSend.find(u=>u.ssrc===(l==null?void 0:l.ssrcs[0].ssrcId));if(h){const u=t.getLocalVideoSize(),p=t.getEncoderConfig(G.LocalVideoTrack);var o;(h.codec==="H264"||h.codec==="H265"||h.codec==="VP8"||h.codec==="VP9"||h.codec==="AV1X"||h.codec==="AV1")&&(c.codecType=h.codec,(a==null?void 0:a.codecType)!==h.codec&&((o=this.onVideoCodecChanged)===null||o===void 0||o.call(this,h.codec.toLocaleLowerCase()))),c.sendBytes=h.bytes,c.sendBitrate=a?8*Math.max(0,c.sendBytes-a.sendBytes):0,h.inputFrame?(c.captureFrameRate=h.inputFrame.frameRate,c.captureResolutionHeight=h.inputFrame.height,c.captureResolutionWidth=h.inputFrame.width):u&&(c.captureResolutionWidth=u.width,c.captureResolutionHeight=u.height),h.sentFrame?(c.sendFrameRate=h.sentFrame.frameRate,c.sendResolutionHeight=h.sentFrame.height,c.sendResolutionWidth=h.sentFrame.width):u&&(c.sendResolutionWidth=u.width,c.sendResolutionHeight=u.height),h.avgEncodeMs&&(c.encodeDelay=h.avgEncodeMs),p&&p.bitrateMax?c.targetSendBitrate=1e3*p.bitrateMax:h.targetBitrate&&(c.targetSendBitrate=h.targetBitrate),c.sendPackets=h.packets,c.sendPacketsLost=h.packetsLost,c.sendJitterMs=h.jitterMs,c.sendRttMs=h.rttMs,c.totalDuration=a?a.totalDuration+1:1,c.totalFreezeTime=a?a.totalFreezeTime:0,this.isLocalVideoFreeze(h)&&(c.totalFreezeTime+=1),h.scalabilityMode&&this.scalabilityMode!==h.scalabilityMode&&(_.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(h.scalabilityMode)),this.scalabilityMode=h.scalabilityMode)}this.trafficStats&&(c.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var s;this.localStats.set(i,c),((a==null?void 0:a.sendResolutionWidth)!==c.sendResolutionWidth||(a==null?void 0:a.sendResolutionHeight)!==c.sendResolutionHeight)&&((s=this.onStatsChanged)===null||s===void 0||s.call(this,"resolution",{width:c.sendResolutionWidth,height:c.sendResolutionHeight})),c&&l&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,l.track,c);break}case G.LocalAudioTrack:{const a=r,c=cc({},wS),d=t.getStats(),l=t.getLocalMedia(i);
64if(d){const h=d.audioSend.find(u=>u.ssrc===(l==null?void 0:l.ssrcs[0].ssrcId));if(h){if(h.codec!=="opus"&&h.codec!=="aac"&&h.codec!=="PCMU"&&h.codec!=="PCMA"&&h.codec!=="G722"||(c.codecType=h.codec),h.inputLevel)c.sendVolumeLevel=Math.round(32767*h.inputLevel);else{const u=t.getLocalAudioVolume();u&&(c.sendVolumeLevel=Math.round(32767*u))}c.sendBytes=h.bytes,c.sendPackets=h.packets,c.sendPacketsLost=h.packetsLost,c.sendJitterMs=h.jitterMs,c.sendRttMs=h.rttMs,c.sendBitrate=a?8*Math.max(0,c.sendBytes-a.sendBytes):0}}this.trafficStats&&(c.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(G.LocalAudioTrack,c),c&&l&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,l.track,c);break}}})}updateRemoteStats(t){Array.from(this.remoteStats.entries()).forEach(n=>{var i,r;let[o,{videoStats:s,audioStats:a,videoPcStats:c}]=n;const d=a,l=s,h=c,u=cc({},pN),p=cc({},_N),E=cc({},pX),{audioTrack:m,videoTrack:g,audioSSRC:R,videoSSRC:v}=t.getRemoteMedia(o);let C;C=this.store.useP2P?t.getStats(!0):t.getStats();const w=(i=C)===null||i===void 0?void 0:i.audioRecv.find(k=>k.ssrc===R),b=(r=C)===null||r===void 0?void 0:r.videoRecv.find(k=>k.ssrc===v),y=this.trafficStats&&this.trafficStats.peer_delay.find(k=>k.peer_uid===o);if(w&&(w.codec!=="opus"&&w.codec!=="aac"&&w.codec!=="PCMU"&&w.codec!=="PCMA"&&w.codec!=="G722"||(u.codecType=w.codec),w.outputLevel?u.receiveLevel=Math.round(32767*w.outputLevel):m&&(u.receiveLevel=Math.round(32767*m.getVolumeLevel())),u.receiveBytes=w.bytes,u.receivePackets=w.packets,u.receivePacketsLost=w.packetsLost,u.receivePacketsDiscarded=w.packetsDiscarded,u.packetLossRate=u.receivePacketsLost/(u.receivePackets+u.receivePacketsLost),u.receiveBitrate=d?8*Math.max(0,u.receiveBytes-d.receiveBytes):0,u.totalDuration=d?d.totalDuration+1:1,u.totalFreezeTime=d?d.totalFreezeTime:0,u.freezeRate=u.totalFreezeTime/u.totalDuration,u.receiveDelay=w.jitterBufferMs,u.totalDuration>10&&Bu.isRemoteAudioFreeze(m)&&(u.totalFreezeTime+=1)),b){b.codec!=="H264"&&b.codec!=="H265"&&b.codec!=="VP8"&&b.codec!=="VP9"&&b.codec!=="AV1X"&&b.codec!=="AV1"||(p.codecType=b.codec),p.receiveBytes=b.bytes,p.receiveBitrate=l?8*Math.max(0,p.receiveBytes-l.receiveBytes):0,p.decodeFrameRate=b.decodeFrameRate<0?0:b.decodeFrameRate,p.renderFrameRate=b.decodeFrameRate<0?0:b.decodeFrameRate,b.outputFrame&&(p.renderFrameRate=b.outputFrame.frameRate),b.receivedFrame?(p.receiveFrameRate=b.receivedFrame.frameRate,p.receiveResolutionHeight=b.receivedFrame.height,p.receiveResolutionWidth=b.receivedFrame.width):g&&(p.receiveResolutionHeight=g._videoHeight||0,p.receiveResolutionWidth=g._videoWidth||0),b.framesRateFirefox!==void 0&&(p.receiveFrameRate=Math.round(b.framesRateFirefox)),p.receivePackets=b.packets,p.receivePacketsLost=b.packetsLost,p.packetLossRate=p.receivePacketsLost/(p.receivePackets+p.receivePacketsLost),p.receiveDelay=b.jitterBufferMs||0;const k=!!v&&t.getRemoteVideoIsReady(v),U=l?l.totalFreezeTime:0,X=l?l.totalDuration:0;var N;p.totalDuration=l?l.totalDuration+1:1,T("REMOTE_VIDEO_FREEZE_TIME_VERSION")===1?g&&k&&g._player&&(p.totalFreezeTime=g._player.totalFreezeTime/1e3):(p.totalFreezeTime=(N=b.totalFreezesDuration)!==null&&N!==void 0?N:U||0,b.totalFreezesDuration===void 0&&g&&k&&Bu.isRemoteVideoFreeze(g,b,h)&&(p.totalFreezeTime+=1)),p.freezeRate=Math.max(0,Math.min((p.totalFreezeTime-U)/(p.totalDuration-X),1))}y&&(u.end2EndDelay=y.B_ad,p.end2EndDelay=y.B_vd,u.transportDelay=y.B_ed,p.transportDelay=y.B_ed,u.currentPacketLossRate=y.B_ealr4/100,p.currentPacketLossRate=y.B_evlr4/100,E.uplinkNetworkQuality=y.B_punq?y.B_punq:0,E.downlinkNetworkQuality=y.B_pdnq?y.B_pdnq:0),this.remoteStats.set(o,{audioStats:u,videoStats:p,videoPcStats:b,networkStats:E}),m&&this.exceptionMonitor.setRemoteAudioStats(m,u),g&&this.exceptionMonitor.setRemoteVideoStats(g,p)})}}class ZU{constructor(){S(this,"destChannelMediaInfos",new Map),S(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(t){LP(t),this.srcChannelMediaInfo=t}addDestChannelInfo(t){LP(t),this.destChannelMediaInfos.set(t.channelName,t)}removeDestChannelInfo(t){n_(t),this.destChannelMediaInfos.delete(t)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}
64function QU(e){if(!(e instanceof ZU))return new D(A.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw();const t=e.getSrcChannelMediaInfo(),n=e.getDestChannelMediaInfo();if(!t)return new D(A.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw();if(n.size===0)return new D(A.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}class na{get hasVideo(){return this._video_enabled_&&!this._video_muted_&&this._video_added_}get hasAudio(){return this._audio_enabled_&&!this._audio_muted_&&this._audio_added_}get audioTrack(){if(this.hasAudio||this._audio_pre_subscribed)return this._audioTrack}get videoTrack(){if(this.hasVideo||this._video_pre_subscribed)return this._videoTrack}get dataChannels(){return this._dataChannels}constructor(t,n){S(this,"uid",void 0),S(this,"_uintid",void 0),S(this,"_trust_in_room_",!0),S(this,"_trust_audio_enabled_state_",!0),S(this,"_trust_video_enabled_state_",!0),S(this,"_trust_audio_mute_state_",!0),S(this,"_trust_video_mute_state_",!0),S(this,"_audio_muted_",!1),S(this,"_video_muted_",!1),S(this,"_audio_enabled_",!0),S(this,"_video_enabled_",!0),S(this,"_audio_added_",!1),S(this,"_video_added_",!1),S(this,"_is_pre_created",!1),S(this,"_video_pre_subscribed",!1),S(this,"_audio_pre_subscribed",!1),S(this,"_trust_video_stream_added_state_",!0),S(this,"_trust_audio_stream_added_state_",!0),S(this,"_audioTrack",void 0),S(this,"_videoTrack",void 0),S(this,"_dataChannels",[]),S(this,"_audioSSRC",void 0),S(this,"_videoSSRC",void 0),S(this,"_audioOrtc",void 0),S(this,"_videoOrtc",void 0),S(this,"_cname",void 0),S(this,"_rtxSsrcId",void 0),S(this,"_videoMid",void 0),S(this,"_audioMid",void 0),this.uid=t,this._uintid=n}}function $U(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Av(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?$U(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$U(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}const wee=e=>`v=0 65o=- 0 0 IN IP4 127.0.0.1 66s=AgoraGateway 67t=0 0 68a=group:BUNDLE 0 1 2 69a=msid-semantic: WMS 70a=ice-lite`.concat(e?` 71a=extmap-allow-mixed`:"",` 72m=video 9 UDP/TLS/RTP/SAVPF 0 73c=IN IP4 127.0.0.1 74a=rtcp:9 IN IP4 0.0.0.0 75a=sendonly 76a=rtcp-mux 77a=rtcp-rsize 78a=mid:0 79m=audio 9 UDP/TLS/RTP/SAVPF 0 80c=IN IP4 127.0.0.1 81a=rtcp:9 IN IP4 0.0.0.0 82a=sendonly 83a=rtcp-mux 84a=rtcp-rsize 85a=mid:1 86m=application 9 UDP/DTLS/SCTP webrtc-datachannel 87c=IN IP4 127.0.0.1 88a=mid:2 89`),gm="9",Cv=2e4,Sm=4e4;let e2=class{get localCapabilities(){return Ct(this._localCapabilities)}get rtpCapabilities(){return Ct(this._rtpCapabilities)}get candidates(){return Ct(this._candidates)}get iceParameters(){return Ct(this._iceParameters)}get dtlsParameters(){return Ct(this._dtlsParameters)}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];S(this,"sessionDesc",void 0),S(this,"_localCapabilities",void 0),S(this,"_rtpCapabilities",void 0),S(this,"_candidates",void 0),S(this,"_originCandidates",void 0),S(this,"_iceParameters",void 0),S(this,"_isUseExtmapAllowMixed",void 0),S(this,"_isUseLocalCodecs",void 0),S(this,"_isUseDataChannel",void 0),S(this,"_dtlsParameters",void 0),S(this,"setup",void 0),S(this,"currentMidIndex",void 0),S(this,"cname",void 0),S(this,"useLocalCodecsMids",[]),S(this,"preloadSsrcs",[]),S(this,"firefoxSsrcMidMap",new Map),this._isUseExtmapAllowMixed=t,this._isUseLocalCodecs=n,this._isUseDataChannel=i,e=Ct(e);const{iceParameters:r,dtlsParameters:o,candidates:s,rtpCapabilities:a,setup:c,localCapabilities:d,cname:l}=e;this._rtpCapabilities=a,this._candidates=s,this._originCandidates=Ct(s),this._iceParameters=r,this._dtlsParameters=o,this._localCapabilities=d,this.setup=c,this.cname=l,[this.sessionDesc]=this.updateRemoteRTPCapabilities(a),this.currentMidIndex=this.sessionDesc.mediaDescriptions.length-1}checkPreloadSsrcs(e){return e.length===this.preloadSsrcs.length&&e.every(t=>{var n;return x(n=this.preloadSsrcs).call(n,t)})}preloadRemoteMedia(e){let t=0;const n=[],i=[];for(;e>0;){const r=[Av({ssrcId:Sm+t},T("USE_SUB_RTX")?{rtx:Sm+t+1}:{})],o="".concat(Sm+t,"_").concat(Cv+t),{ssrcs:s,ssrcGroups:a}=Mu(r,this.cname,T("SYNC_GROUP")?o:void 0),c=this.preCreateOrRecycleSendMedia("video",s,a,void 0),d=[{ssrcId:Cv+t}],l="".concat(Sm+t,"_").concat(Cv+t),{ssrcs:h,ssrcGroups:u}=Mu(d,this.cname,T("SYNC_GROUP")?l:void 0),p=this.preCreateOrRecycleSendMedia("audio",h,u,void 0);e--,t+=2,n.push(c,p),i.push(s[0].ssrcId,h[0].ssrcId)}return this.useLocalCodecsMids.push(...n),this.preloadSsrcs=i,{mids:n,preSSRCs:i,isAvailable:!0}}preCreateOrRecycleSendMedia(e,t,n,i){const r=this.rtpCapabilities.send.videoCodecs,o=this._isUseLocalCodecs||r.length===0?this.localCapabilities.recv:this.rtpCapabilities.send;_.debug("create or recycle send media without remote rtp capabilities, ssrcs ",t[0].ssrcId);const s=e===$.VIDEO?o.videoCodecs:o.audioCodecs,a=e===$.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:gm,protos:["UDP","TLS","RTP","SAVPF"],fmts:s.map(l=>l.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:n,rtcpFeedbackWildcards:[],payloads:s,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};return d=this.mungSendMediaDesc(d,i),this.sessionDesc.mediaDescriptions.push(d),this.updateBundleMids(),c}toString(){return as(this.sessionDesc)}send(e,t,n,i){const{ssrcs:r,ssrcGroups:o}=Mu(t,this.cname,T("SYNC_GROUP")?n:void 0),s=this.findPreloadMediaDesc(r);if(s){if(Rt()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,s.attributes.mid),i&&(i.twcc||i.remb)){const a=this.sessionDesc.mediaDescriptions.indexOf(s);return this.sessionDesc.mediaDescriptions[a]=this.mungSendMediaDesc(s,i),{mid:s.attributes.mid,needExchangeSDP:!0}}return{mid:s.attributes.mid,needExchangeSDP:!1}}{const a=this.findAvailableMediaIndex(e,r);let c;return a===-1||a===1&&(vn()||function(){const d=Fe();return!(d.name!==je.CHROME||!d.osVersion)&&Number(d.version)<=90}()||Ur(143)||ks(143)||T("RESERVE_MID_1_MLINE")||T("ENABLE_ENCODED_TRANSFORM")&&ss())||a===0&&!function(d){const l=Fe();return!(l.name!==je.FIREFOX||!l.osVersion)&&Number(l.version)===d}(138)&&T("USE_SUB_RTX")||lO()?(c=this.createOrRecycleSendMedia(e,r,o,"sendonly",i),this.updateBundleMids()):(c=Ct(this.sessionDesc.mediaDescriptions[a]),c.attributes.direction="sendonly",c.attributes.ssrcs=r,c.attributes.ssrcGroups=o,this.sessionDesc.mediaDescriptions[a]=this.mungSendMediaDesc(c,i)),Rt()&&this.firefoxSsrcMidMap.set(r[0].ssrcId,c.attributes.mid),{mid:c.attributes.mid,needExchangeSDP:!0}}}
89sendDataChannel(){const{mediaDesc:e,needExchangeSDP:t}=this.createOrRecycleDataChannel();return this.updateBundleMids(),{mid:e.attributes.mid,needExchangeSDP:t}}batchSend(e){const t=e.map(r=>{let{kind:o,ssrcMsg:s,mslabel:a}=r;return this.send(o,s,a)}),n=[];let i=!1;return t.forEach(r=>{let{mid:o,needExchangeSDP:s}=r;s&&(i=!0),n.push(o)}),{mids:n,needExchangeSDP:i}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter(n=>n.attributes.mid&&e.indexOf(n.attributes.mid)!==-1);if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach(n=>{n.attributes.mid==="0"||Rt()||lO()?n.attributes.ssrcs=[]:(n.attributes.ssrcs=[],n.attributes.direction="inactive",n.media.port="0")}),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find(n=>n.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find(n=>n.attributes.mid===e);if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(n=>x(e).call(e,n.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(n=>{n.attributes.direction="inactive"})}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(n=>x(e).call(e,n.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(n=>{n.attributes.direction="recvonly"})}receive(e,t,n,i){e.forEach((r,o)=>{this.createOrRecycleRecvMedia(r,[],"recvonly",t,n,i[o])}),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter(n=>e.indexOf(n.attributes.mid)!==-1);if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach(n=>{n.media.port="0",n.attributes.direction="inactive"}),this.updateBundleMids()}updateRemoteRTPCapabilities(e){const t=this.sessionDesc||ii((n=this._isUseExtmapAllowMixed,this._isUseDataChannel?wee(n):`v=0 90o=- 0 0 IN IP4 127.0.0.1 91s=AgoraGateway 92t=0 0 93a=group:BUNDLE 0 1 94a=msid-semantic: WMS 95a=ice-lite`.concat(n?` 96a=extmap-allow-mixed`:"",` 97m=video 9 UDP/TLS/RTP/SAVPF 0 98c=IN IP4 127.0.0.1 99a=rtcp:9 IN IP4 0.0.0.0 100a=sendonly 101a=rtcp-mux 102a=rtcp-rsize 103a=mid:0 104m=audio 9 UDP/TLS/RTP/SAVPF 0 105c=IN IP4 127.0.0.1 106a=rtcp:9 IN IP4 0.0.0.0 107a=sendonly 108a=rtcp-mux 109a=rtcp-rsize 110a=mid:1 111`)));var n;this._rtpCapabilities=e;let i=!1;const r=this.rtpCapabilities.send,o=this.localCapabilities.send,s=this.localCapabilities.recv,a=s.videoCodecs,c=s.audioCodecs,d=s.videoExtensions,l=s.audioExtensions;for(const E of t.mediaDescriptions){var h;if(E.attributes.direction!=="sendonly"||typeof E.attributes.mid!="string"||!x(h=this.useLocalCodecsMids).call(h,E.attributes.mid)){if(i=!0,E.attributes.iceUfrag=this._iceParameters.iceUfrag,E.attributes.icePwd=this._iceParameters.icePwd,E.attributes.fingerprints=this._dtlsParameters.fingerprints,E.attributes.candidates=this._candidates,E.attributes.setup=this.setup,E.media.mediaType==="application"&&(E.attributes.sctpPort="5000"),E.media.mediaType==="video")if(this._isUseLocalCodecs&&E.attributes.direction==="sendonly"){var u;E.media.fmts=a.map(g=>g.payloadType.toString(10)),E.attributes.payloads=a,E.attributes.extmaps=d;const m=E.attributes.mid;typeof m!="string"||x(u=this.useLocalCodecsMids).call(u,m)||this.useLocalCodecsMids.push(m)}else if(r.videoCodecs.length===0){const m=o.videoCodecs.filter(g=>{var R,v;return(R=g.rtpMap)===null||R===void 0?void 0:x(v=R.encodingName.toLowerCase()).call(v,"vp8")});m.length===0&&m.push(o.videoCodecs[0]),E.media.fmts=m.map(g=>g.payloadType.toString(10)),E.attributes.payloads=m,E.attributes.extmaps=[]}else E.media.fmts=r.videoCodecs.map(m=>m.payloadType.toString(10)),E.attributes.payloads=r.videoCodecs,E.attributes.extmaps=r.videoExtensions;
111if(E.media.mediaType==="audio")if(this._isUseLocalCodecs&&E.attributes.direction==="sendonly"){var p;E.media.fmts=c.map(g=>g.payloadType.toString(10)),E.attributes.payloads=c,E.attributes.extmaps=l;const m=E.attributes.mid;typeof m!="string"||x(p=this.useLocalCodecsMids).call(p,m)||this.useLocalCodecsMids.push(m)}else if(r.audioCodecs.length===0){const m=o.audioCodecs.filter(g=>{var R,v;return(R=g.rtpMap)===null||R===void 0?void 0:x(v=R.encodingName.toLowerCase()).call(v,"opus")})||[o.audioCodecs[0]];E.media.fmts=m.map(g=>g.payloadType.toString(10)),E.attributes.payloads=m,E.attributes.extmaps=[]}else E.media.fmts=r.audioCodecs.map(m=>m.payloadType.toString(10)),E.attributes.payloads=r.audioCodecs,E.attributes.extmaps=r.audioExtensions,Wd(E)}}return this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1,[this.sessionDesc,i]}updateCandidates(e){const t=this._originCandidates.filter(i=>i.transport==="udp"),n=[];if(t.forEach(i=>{n.push(Av(Av({},i),{},{foundation:"tcpcandidate",priority:Number(i.priority)-1+"",transport:"tcp",port:Number(i.port)+90+""}))}),t.length!==0){switch(e){case gn.TCP_RELAY:this._candidates=n;break;case gn.UDP_TCP_RELAY:case gn.RELAY:this._candidates=[...t,...n];break;default:this._candidates=t}for(const i of this.sessionDesc.mediaDescriptions)i.attributes.candidates=this.candidates}}restartICE(e){let t=!1;return e=Ct(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(n=>{n.attributes.iceUfrag===e.iceUfrag&&n.attributes.icePwd===e.icePwd||(t=!0),n.attributes.iceUfrag=e.iceUfrag,n.attributes.icePwd=e.icePwd}),t}predictReceivingMids(e){const t=[];for(let n=0;n<e;n++)t.push((this.currentMidIndex+n+1).toString(10));return t}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex(n=>{const i=n.media.mediaType===e&&n.media.port!=="0"&&(n.attributes.direction==="sendonly"||n.attributes.direction==="sendrecv")&&n.attributes.ssrcs.length===0;if(Rt()){if(i){const r=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(r||n.attributes.mid!=="0"&&n.attributes.mid!=="1")||!(!r||r!==n.attributes.mid)}return!1}return i})}createOrRecycleDataChannel(){for(const n of this.sessionDesc.mediaDescriptions)if(n.media.mediaType==="application")return{mediaDesc:n,needExchangeSDP:!1};this.currentMidIndex+=1;const e="".concat(this.currentMidIndex),t={media:{mediaType:"application",port:gm,protos:["UDP","DTLS","SCTP"],fmts:["webrtc-datachannel"]},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:[],fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[],rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,mid:"".concat(e),sctpPort:"5000"}};return this.sessionDesc.mediaDescriptions.push(t),{mediaDesc:t,needExchangeSDP:!0}}createOrRecycleRecvMedia(e,t,n,i,r,o){const s=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=Vu(s,a,this.localCapabilities.send,s===$.VIDEO?i:r),d=s===$.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let h={media:{mediaType:s,port:gm,protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map(p=>p.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};h=this.mungRecvMediaDsec(h,e,o);const u=this.findFirstClosedMedia(s);if(u){const p=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[p]=h}else this.sessionDesc.mediaDescriptions.push(h);return h}updateRemoteDtlsParameters(e){const t=new Set(this._dtlsParameters.fingerprints.map(r=>r.fingerprint)),n=new Set(e.map(r=>r.fingerprint));let i=!1;t.size!==n.size&&(i=!0);for(const r of t)n.has(r)||(i=!0);return i}
111updateRemoteCodec(e,t,n){const i=[...new Set(this._rtpCapabilities.recv.videoCodecs.map(h=>h.rtpMap&&h.rtpMap.encodingName.toLowerCase()||"").filter(h=>{var u;return x(u=Object.keys(Ma)).call(u,h)}))],r=new Set(t);if(i.every(h=>r.has(h)))return _.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const o=this._rtpCapabilities.recv.videoCodecs.filter(h=>t.some(u=>{var p;return x(p=h.rtpMap&&h.rtpMap.encodingName.toLowerCase()||"").call(p,u)}));if(o.length===0)return _.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(i," codecs: ").concat(t)),!1;const s=[...new Set(o.map(h=>h.rtpMap&&h.rtpMap.encodingName.toLowerCase()||""))];let a;if(_.debug("updateRemoteCodec, from ".concat(i," to ").concat(s)),e.length===0)a=this.sessionDesc.mediaDescriptions.filter(h=>h.media.mediaType==="video"&&h.attributes.direction==="recvonly");else if(a=this.sessionDesc.mediaDescriptions.filter(h=>h.attributes.mid&&h.media.mediaType==="video"&&x(e).call(e,h.attributes.mid)&&h.attributes.direction==="recvonly"),a.length!==e.length)return _.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;if(T("USE_PUB_RTX")||T("USE_SUB_RTX")){const h=ta(o,this.rtpCapabilities.recv.videoCodecs);o.push(...h)}this._rtpCapabilities.recv.videoCodecs=o;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=Vu($.VIDEO,d,c,n);return a.forEach(h=>{const u=l.map(p=>p.payloadType.toString(10));_.debug("updateRemoteCodec mid: ".concat(h.attributes.mid,", from"),h.attributes.payloads,"to",l),h.attributes.payloads=l,h.media.fmts=u}),_.debug("updateRemoteCodec success, mids: ".concat(e,", codecs: ").concat(t,", remote recv: ").concat(this._rtpCapabilities.recv.videoCodecs.length,", remote send: ").concat(this._rtpCapabilities.send.videoCodecs.length)),!0}createOrRecycleSendMedia(e,t,n,i,r){const o=this.rtpCapabilities.send.videoCodecs,s=this._isUseLocalCodecs||o.length===0?this.localCapabilities.recv:this.rtpCapabilities.send,a=e===$.VIDEO?s.videoCodecs:s.audioCodecs,c=e===$.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const d="".concat(this.currentMidIndex);let l={media:{mediaType:e,port:gm,protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map(u=>u.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:n,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungSendMediaDesc(l,r);const h=this.findFirstClosedMedia(e);if(h){const u=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[u]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(e=>e.media.port!=="0").map(e=>e.attributes.mid)}mungRecvMediaDsec(e,t,n){const i=Ct(e);return av(i),rc(i,t),cv(i,t),PU(i),dm(i,n,this.localCapabilities.send),i}mungSendMediaDesc(e,t){const n=Ct(e);return n.attributes&&n.attributes.payloads&&Array.isArray(n.attributes.payloads)&&n.attributes.payloads.length>0&&n.attributes.payloads.forEach(i=>{i.rtpMap&&i.rtpMap.encodingName.toLocaleLowerCase()==="h264"&&T("ENABLE_DOWN_SPS_PPS")&&(i.fmtp&&i.fmtp.parameters||(i.fmtp={parameters:{}}),i.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")}),dm(n,t,this.localCapabilities.recv),Wd(n),n}updateRecvMedia(e,t){const n=this.sessionDesc.mediaDescriptions.findIndex(i=>i.attributes.mid===e);if(n!==-1){const i=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],t);this.sessionDesc.mediaDescriptions[n]=i}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find(t=>Rt()?t.media.port==="0"&&t.media.mediaType===e:t.media.port==="0")}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var n;return((n=t.attributes)===null||n===void 0||(n=n.ssrcs[0])===null||n===void 0?void 0:n.ssrcId)===e[0].ssrcId})}getSSRC(e){var t;return(t=this.sessionDesc.mediaDescriptions.find(n=>n.attributes.mid===e))===null||t===void 0?void 0:t.attributes.ssrcs}};function t2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function gs(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
111t%2?t2(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):t2(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}var Hd=function(e){return e[e.DOWN=0]="DOWN",e[e.UP=1]="UP",e}(Hd||{});const Tm=new Map;function n2(e,t,n,i){let{scale:r}=e;if(r===0&&i===Hd.UP||r>=t.length-1&&i===Hd.DOWN)return e;let o=gs(gs({},e),{},{scale:i===Hd.DOWN?++r:--r});switch(n){case"maintain-framerate":o=gs(gs({},o),t[r].motion);break;case"maintain-resolution":o=gs(gs({},o),t[r].detail);break;case"balanced":o=gs(gs({},o),t[r].balanced)}return o}function i2(e,t){if(t){const n={overUse:0,underUse:0,adaptationList:r2(t)};Tm.set(e,n)}else Tm.delete(e)}function r2(e){const t=gs({},e),{bitrateMax:n,frameRate:i,scaleResolutionDownBy:r,bitrateMin:o}=t,{MIN_FRAME_RATE:s,MAX_THRESHOLD_FRAMERATE:a,MAX_SCALE:c,BITRATE_MIN_THRESHOLD:d,BITRATE_MAX_THRESHOLD:l,BWE_SCALE_UP_THRESHOLD:h,BWE_SCALE_DOWN_THRESHOLD:u,PERF_SCALE_DOWN_THRESHOLD:p,PERF_SCALE_UP_THRESHOLD:E,BALANCE_BITRATE_FACTOR:m,BALANCE_FRAMERATE_FACTOR:g,BALANCE_RESOLUTION_FACTOR:R,MOTION_RESOLUTION_FACTOR:v,MOTION_BITRATE_FACTOR:C,DETAIL_FRAMERATE_FACTOR:w,DETAIL_BITRATE_FACTOR:b}=_S,y=Math.min(t.frameRate,a),N=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(u,1)*n),bwe_up:n,fps_down:Math.round(Math.pow(p,1)*y),fps_up:i},balanced:{scaleResolutionDownBy:1,frameRate:i,bitrateMax:n,bitrateMin:o},motion:{scaleResolutionDownBy:1,frameRate:i,bitrateMax:n,bitrateMin:o},detail:{scaleResolutionDownBy:1,frameRate:i,bitrateMax:n,bitrateMin:o}}];for(let k=1;k<=c;k++){const U={bwe_up:Math.round(Math.pow(h,k)*n),bwe_down:Math.round(Math.pow(u,k+1)*n),fps_up:Math.round(Math.pow(E,k)*y),fps_down:Math.round(Math.pow(p,k+1)*y)},X={scaleResolutionDownBy:r/Math.pow(R,k),frameRate:Math.max(Math.round(Math.pow(g,k)*i),s),bitrateMax:Math.max(Math.round(Math.pow(m,k)*n),l),bitrateMin:Math.max(Math.round(Math.pow(m,k)*o),d)},q={scaleResolutionDownBy:r/Math.pow(v,k),frameRate:i,bitrateMax:Math.max(Math.round(Math.pow(C,k)*n),l),bitrateMin:Math.max(Math.round(Math.pow(C,k)*o),d)},se={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(w,k)*i),s),bitrateMax:Math.max(Math.round(Math.pow(b,k)*n),l),bitrateMin:Math.max(Math.round(Math.pow(b,k)*o),d)};N.push({scale:k,threshold:U,balanced:X,motion:q,detail:se})}return N}function Oee(e,t,n,i,r,o){const s=Tm.get(e)||{overUse:0,underUse:0,adaptationList:r2(r)},{adaptationList:a}=s;Tm.set(e,s);const{OVERUSE_TIMES_THRESHOLD:c,UNDERUSE_TIMES_THRESHOLD:d}=_S,{scale:l}=i;let h,u;return typeof t=="number"&&t>0&&function(p,E,m,g){if(E>=m.length)return!1;let{threshold:{fps_down:R}}=m[E];return T("FORCE_AG_HIGH_FRAMERATE")&&g==="maintain-framerate"&&(R=m[0].threshold.fps_down),p<R}(t,l,a,o)&&(s.overUse++,u=od.CPU,s.overUse>c)||typeof n=="number"&&n>0&&function(p,E,m){if(E>=m.length)return!1;const{threshold:{bwe_down:g}}=m[E];return p<g}(n,l,a)&&(s.overUse++,u=od.BANDWIDTH,s.overUse>c)?(s.overUse=0,s.underUse=0,h=n2(i,a,o,Hd.DOWN),[h,u]):(typeof t=="number"&&t>0&&typeof n=="number"&&n>0&&function(p,E,m,g){if(E===0)return;let{threshold:{fps_up:R}}=m[E];return T("FORCE_AG_HIGH_FRAMERATE")&&g==="maintain-framerate"&&(R=m[1].threshold.fps_up),p>R}(t,l,a,o)&&function(p,E,m){if(E===0)return;const{threshold:{bwe_up:g}}=m[E];return p>g}(n,l,a)&&(s.underUse++,s.underUse>d&&(s.overUse=0,s.underUse=0,h=n2(i,a,o,Hd.UP),h.scale===0&&(u=od.NONE))),[h,u])}function o2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function yv(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?o2(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):o2(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function s2(e){var t;return!!T("ENABLE_AG_ADAPTATION")&&!!(e instanceof Hp||x(t=e._hints).call(t,$e.CUSTOM_TRACK))&&(!!T("FORCE_SUPPORT_AG_ADAPTATION")||!!(zg(14,0,!1)&&dO(17,4,!0)||cO(14)&&Ap(17,4,!0)))}const Rm=new Map;function a2(e,t,n,i,r,o){if(Yd(e,n),r(t),i!=="balanced"&&i!=="maintain-framerate"&&i!=="maintain-resolution")return;let s=-1;i2(e,t);const a=window.setInterval(()=>{const d=Rm.get(e);if(!T("ENABLE_AG_ADAPTATION")||!d)return Yd(e,n),void r(t);const l=o();if(l.sendPackets>0&&l.OutgoingAvailableBandwidth>0){if(s===-1)return void(s=Date.now());if(Date.now()-s<1e3)return;const h=l.sendFrameRate,u=l.OutgoingAvailableBandwidth,[p,E]=Oee(e,h,u,d.adaptationConfig,t,i);E&&(n.qualityLimitationReason=E),p&&d.adaptationConfig.scale!==p.scale&&(_.debug("[".concat(e,"] applyAdaptation: ").concat(n.qualityLimitationReason,` 112 sendFps `).concat(h,", bwe ").concat(u,", switch from ").concat(d.adaptationConfig.scale," to ").concat(p.scale," ")),d.adaptationConfig=yv(yv({},d.adaptationConfig),p),r(p))}},T("CHECK_LOCAL_STATS_INTERVAL")),c=yv({},t);Rm.set(e,{timer:a,adaptationConfig:c,originConfig:t,adaptationFunc:r}),_.debug("[".concat(e,"] start adaptation, originConfig: ").concat(JSON.stringify(t),", degradationPreference: ").concat(i))}function Yd(e,t){const n=Rm.get(e);if(n){const{timer:i}=n;window.clearTimeout(i),Rm.delete(e)}t.qualityLimitationReason=od.NONE,i2(e)}function Nee(e,t){var n;let i;switch(t){case G.LocalAudioTrack:i=nt.Audio;break;case G.LocalVideoTrack:i=x(n=e._hints).call(n,$e.SCREEN_TRACK)?nt.Screen:nt.High;break;case G.LocalVideoLowTrack:i=nt.Low}return i}function Iv(e){const t=Oe();if(e.some(n=>n._bypassWebAudio))throw new L(A.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new L(A.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing")}function bv(e,t){Iv(e);const n=new En;return e.forEach(i=>
112n.addAudioTrack(i)),n}const Dee=!Oe().supportUnifiedPlan||T("CHROME_FORCE_PLAN_B")&&Po();function Pee(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(e.useDcSignal)return n={spec:t,store:e},To("DataChannelConnection").create(n);var n;return Dee?function(i){return To("PlanBConnection").create(i)}({spec:t,store:e}):new xi(t,e)}function wv(e){return e&&(e.iceConnectionState==="disconnected"||e.iceConnectionState==="checking"||e.iceConnectionState==="failed")}function Ov(e){try{if(e.iceServers)return!1;if(e.turnServer&&e.turnServer.mode!=="off"){if(wa(e.turnServer.servers))return!1;if(T("FORCE_TURN_TCP")||e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).some(t=>t.forceturn))return!0}return!1}catch{return!1}}var Ve;function c2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function vr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?c2(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):c2(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}let xi=(Ve=class Ec extends o_{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var t,n;return(t=(n=this.peerConnection.getReceivers()[0])===null||n===void 0||(n=n.transport)===null||n===void 0?void 0:n.state)!==null&&t!==void 0?t:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map(t=>t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").filter(t=>{var n;return x(n=Object.keys(Ma)).call(n,t)}))]}constructor(t,n){super(t,n),S(this,"id",Qe(5,"connection-")),S(this,"store",void 0),S(this,"peerConnection",void 0),S(this,"forceTurn",!1),S(this,"remoteSDP",void 0),S(this,"initialOffer",void 0),S(this,"transportEventReceiver",void 0),S(this,"statsFilter",void 0),S(this,"extension",{useXR:T("USE_XR")}),S(this,"localCapabilities",void 0),S(this,"remoteCodecs",void 0),S(this,"localCandidateCount",0),S(this,"allCandidatesReceived",!1),S(this,"isPreallocation",!1),S(this,"isPreRender",!1),S(this,"preMediaMap",new Map),S(this,"dataStreamChannelMap",new Map),S(this,"establishPromise",void 0),S(this,"recoveredDataChannelIds",[]),S(this,"currentDataChannelId",1),S(this,"supportAV1RtpSpec",!1),S(this,"mutex",void 0),S(this,"qualityLimitationReason",od.NONE),S(this,"isFirstConnected",!1),this.store=n,this.forceTurn=Ov(t),this.mutex=new An("P2PConnection-mutex",n.clientId),this.peerConnection=new RTCPeerConnection(Ec.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=Np(this.peerConnection,T("STATS_UPDATE_INTERVAL"),void 0,Rt()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,t.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}getPreMedia(t){return this.preMediaMap.get(t)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(t,n){if(this.remoteCodecs=n,!this.remoteSDP)return void _.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(n));if(this.remoteSDP.updateRemoteCodec(t,n,this.store.codec)){const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i);const o=this.remoteSDP.toString();r==null||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}else _.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const n=await this.peerConnection.createOffer();if(!n.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");
112const i=Ho(n.sdp),r=await lv({filterRTX:!T("USE_PUB_RTX")&&!T("USE_SUB_RTX"),filterVideoFec:T("FILTER_VIDEO_FEC"),filterAudioFec:T("FILTER_AUDIO_FEC"),filterVideoCodec:T("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:T("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:T("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=Uu(r),this.initialOffer=n,T("ENABLE_SVC")&&this.store.codec=="av1"){const s=await LU();var t;s&&(this.supportAV1RtpSpec=!0,(t=r.send)===null||t===void 0||t.videoExtensions.push(s))}let o;return n.sdp&&lm(n.sdp)&&(o=Ct(r),CU(o)),vr(vr({},i),{},{rtpCapabilities:o||r,offerSDP:n.sdp})}catch(n){throw new L(A.GET_LOCAL_CONNECTION_PARAMS_FAILED,n.toString())}}async connect(t){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");if(this.initialOffer.sdp&&lm(this.initialOffer.sdp)&&yU(t.rtpCapabilities,this.localCapabilities),this.remoteSDP=new e2(vr(vr({},t),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!T("ENABLE_PRE_SUB_WITH_PRE_PC")||!T("PRE_USE_LOCAL_CODECS"))&&Ua(this.store)),t.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec),sN()&&Ua(this.store)){var n;const r=((n=this.store.preSubOptions)===null||n===void 0?void 0:n.length)||0,o=T("PRE_SUB_NUM")||1,s=r>o?r:o,{mids:a,preSSRCs:c}=this.remoteSDP.preloadRemoteMedia(s),d=xu(this.initialOffer.sdp,this.extension),l=this.logSDPExchange(d||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),l==null||l(d),new Array(s).fill(0).forEach(()=>{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})});const h=await this.peerConnection.createOffer(),u=this.logSDPExchange(h.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(h);const p=this.remoteSDP.toString();u==null||u(p),await this.peerConnection.setRemoteDescription({type:"answer",sdp:p}),_.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media with icc/dtls, add preload ssrcs ").concat(c)),this.presetMedia(a,c);const E=this.peerConnection.getTransceivers()[0];E!=null&&E.receiver&&this.tryBindTransportEvents(E.receiver)}else{const r=this.remoteSDP.toString(),o=xu(this.initialOffer.sdp,this.extension),s=this.logSDPExchange(o||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:o}),s==null||s(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});const a=this.peerConnection.getTransceivers()[0];if(a!=null&&a.receiver&&this.tryBindTransportEvents(a.receiver),Ua(this.store))if(t.preallocation&&T("ENABLE_PRE_SUB_WITH_PRE_PC")){var i;const c=((i=this.store.preSubOptions)===null||i===void 0?void 0:i.length)||0,d=T("PRE_SUB_NUM")||1,l=c>d?c:d,{mids:h,preSSRCs:u}=this.remoteSDP.preloadRemoteMedia(l);await vi(this.peerConnection,this.remoteSDP,this.extension),_.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(u)),this.presetMedia(h,u)}else{const{preSSRCs:c=[]}=t,d=c.map(h=>h.ssrcMsg[0].ssrcId);if(c.length===0)return;const{mids:l}=this.remoteSDP.batchSend(c.map(h=>Object.assign({},h)));await vi(this.peerConnection,this.remoteSDP,this.extension),_.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(d)),this.presetMedia(l,d)}}}catch(r){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(r.toString()))}}presetMedia(t,n){t.forEach((i,r)=>{this.peerConnection.getTransceivers().forEach(o=>{if(o.mid!=null&&i===o.mid&&o.receiver.track){const c=o.receiver.track;if(T("PRE_PLAYOUT_DELAY_HINT")){const l=o.receiver;"playoutDelayHint"in l&&(l.playoutDelayHint=T("PRE_PLAYOUT_DELAY_HINT"),_.debug("[".concat(this.store.clientId,"] [P2PConnection] presetMedia set playoutDelayHint to ").concat(T("PRE_PLAYOUT_DELAY_HINT"))))}let d;if(c.kind==="video"&&T("ENABLE_PRE_RENDER")){var s,a;let l=(s=this.store.preSubOptions)===null||s===void 0||(s=s[r])===null||s===void 0?void 0:s.element;const h=((a=this.store.preSubOptions)===null||a===void 0||(a=a[r])===null||a===void 0?void 0:a.config)||{};_.debug("try to play pre sub video",typeof l=="string"?l:"element","config: ".concat(JSON.stringify(h))),typeof l=="string"&&(l=document.getElementById(l)||void 0),d=l instanceof HTMLVideoElement?new Wp(vr({trackId:"track-".concat(c.kind,"-unknown-").concat(this.store.clientId,"_").concat(Qe(5,"")),element:l},h)):new Kp(vr({trackId:"track-".concat(c.kind,"-unknown-").concat(this.store.clientId,"_").concat(Qe(5,"")),element:l}
112,h),!l),d.updateVideoTrack(c),d.onFirstVideoFrameRender=()=>{var u;d&&(d.onFirstVideoFrameRender=void 0);const p=this.preMediaMap.get(n[r]);p&&(p.firstVideoRender=Date.now()),(u=this.onFirstVideoRender)===null||u===void 0||u.call(this,n[r])},d.onVideoBufferReady=()=>{var u;(u=this.onFirstVideoBufferReady)===null||u===void 0||u.call(this,n[r])},d.play(this.store.sessionId||void 0),this.isPreRender=!0}this.preMediaMap.set(n[r],{mid:i,track:c,player:d,transceiver:o})}}),this.store.peerReceiver()})}checkDtlsParameters(t){return!!this.remoteSDP&&t.length>0&&this.remoteSDP.updateRemoteDtlsParameters(t)}checkIceParameters(t){return this.remoteSDP?this.remoteSDP.restartICE(t):!1}async updateRemoteConnect(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateRemoteConnect before remote SDP created");let n=!1;const{rtpCapabilities:i}=t;if([,n]=this.remoteSDP.updateRemoteRTPCapabilities(i),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const s=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);n=n||s}const{preSSRCs:r=[]}=t,o=r.map(s=>s.ssrcMsg[0].ssrcId);if(!this.remoteSDP.checkPreloadSsrcs(o)){const s=[],a=[];if(Array.from(this.preMediaMap.entries()).every(c=>{let[d,{mid:l,player:h,track:u}]=c;return s.push(l),a.push(d),this.preMediaMap.delete(d),h&&h.destroy(),!0}),s.length>0&&(this.remoteSDP.stopSending(s),await vi(this.peerConnection,this.remoteSDP,this.extension),_.warn("[P2PConnection.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(a)),Z.reportApiInvoke(this.store.sessionId,{name:vt.PRELOAD_MEDIA_FAILED,options:[r,a],tag:ht.TRACER}).onSuccess()),r.length>0){const{mids:c}=this.remoteSDP.batchSend(r.map(d=>Object.assign({},d)));await vi(this.peerConnection,this.remoteSDP,this.extension),_.debug("[P2PConnection.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(o)),this.presetMedia(c,o)}}n?(await vi(this.peerConnection,this.remoteSDP,this.extension),_.debug("[P2PConnection] updateRemoteConnect by exchanging SDP.")):_.debug("[P2PConnection] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(n.toString()))}}send(t,n,i){var r=this;return di(function*(){const o=yield ve(r.mutex.lock("From P2PConnection.send"));try{if(!r.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[],a=Lu();t.forEach(g=>{const R=r.peerConnection.addTransceiver(g._mediaStreamTrack,vr({direction:"sendonly"},g.trackMediaType==="video"&&r.supportAV1RtpSpec&&a?{sendEncodings:[{scalabilityMode:a}]}:{}));s.push(R),g._updateRtpTransceiver(R)}),Rt()&&T("SIMULCAST")===!0&&(yield ve(r.applySimulcastForFirefox(s,t)));const c=yield ve(r.peerConnection.createOffer()),d=r.remoteSDP.predictReceivingMids(t.length),l=r.mungSendOfferSDP(c.sdp,t,d),h=ii(l),u=d.map(g=>{const R=h.mediaDescriptions.find(v=>v.attributes.mid===g);if(!R)throw new Error("Cannot extract ssrc from mediaDescription.");return sv(R,T("USE_PUB_RTX"))});let p;try{p=yield u}catch(g){p=[],r.remoteSDP.receive(t,n,i,p);const R=r.remoteSDP.toString();throw yield ve(r.peerConnection.setLocalDescription({type:"offer",sdp:l})),yield ve(r.peerConnection.setRemoteDescription({type:"answer",sdp:R})),yield ve(r.stopSending(d,!0)),g}r.remoteSDP.receive(t,n,i,p);const E=r.remoteSDP.toString(),m=r.logSDPExchange(l,"offer","local","send");return yield ve(r.peerConnection.setLocalDescription({type:"offer",sdp:l})),yield ve(r.applySimulcastEncodings(s,t)),yield ve(r.applySendEncodings(s,t)),m==null||m(E),yield ve(r.peerConnection.setRemoteDescription({type:"answer",sdp:E})),s.map((g,R)=>{const v=d[R];return{localSSRC:u[R],id:v,transceiver:g}})}catch(s){throw s instanceof L?s:new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(s.toString()))}finally{o()}})()}async createDataChannels(t,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(t);if(i&&i.readyState==="open")_.debug("[P2PConnection] Channels are already available and can be reused directly.");else{const o=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if(typeof o!="number")throw new Error("create DataChannel error, because cannot get dc id");
112i=this.peerConnection.createDataChannel("datastream-channel",{id:o,negotiated:!0,ordered:!1,maxRetransmits:T("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(t,i)}n.forEach(o=>{o._updateOriginDataChannel(i)});const{needExchangeSDP:r}=this.remoteSDP.sendDataChannel();if(r){const o=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const s=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(s),_.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else _.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(i){throw i instanceof L?i:new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.createDataChannels failed; ".concat(i.toString()))}}async stopDataChannels(t){try{const n=this.dataStreamChannelMap.get(t);return n&&(n.id&&this.recoveredDataChannelIds.push(n.id),n.close()),void this.dataStreamChannelMap.delete(t)}catch(n){throw n instanceof L?n:new L(A.DATACHANNEL_FAILED,"P2PConnection.stopD
112ataChannels failed; ".concat(n.toString()))}}async stopSending(t,n){const i=n?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const r=this.peerConnection.getTransceivers().filter(c=>t.indexOf(c.mid)!==-1);if(r.length!==t.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");r.map(c=>{var d;Yd(this.id+c.mid,this),c.direction="inactive",(d=c.stop)===null||d===void 0||d.call(c)});const o=await this.peerConnection.createOffer(),s=this.logSDPExchange(o.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(o),this.remoteSDP.stopReceiving(t);const a=this.remoteSDP.toString();s==null||s(a),await this.peerConnection.setRemoteDescription({type:"answer",sdp:a})}catch(r){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(r.toString()))}finally{i&&i()}}async receive(t,n,i,r){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(t," before remoteSDP created."));const{mid:o,needExchangeSDP:s}=this.remoteSDP.send(t,n,i,r);s&&(await vi(this.peerConnection,this.remoteSDP,this.extension),_.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(t," by exchanging SDP.")));const a=this.peerConnection.getTransceivers().find(c=>c.mid===o);if(!a)throw new Error("Cannot get transceiver after setLocalDescription.");if(T("PRE_PLAYOUT_DELAY_HINT")){const c=a.receiver;"playoutDelayHint"in c&&(c.playoutDelayHint=T("PRE_PLAYOUT_DELAY_HINT"),_.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(t," set playoutDelayHint to ").concat(T("PRE_PLAYOUT_DELAY_HINT"))))}return{track:a.receiver.track,id:o,transceiver:a}}catch(o){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(o.toString()))}}async batchReceive(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const{mids:n,needExchangeSDP:i}=this.remoteSDP.batchSend(t);return i&&(await vi(this.peerConnection,this.remoteSDP,this.extension),_.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."))),n.map(r=>{const o=this.peerConnection.getTransceivers().find(s=>s.mid===r);if(!o)throw new Error("Cannot get transceiver after setLocalDescription.");if(T("PRE_PLAYOUT_DELAY_HINT")){const s=o.receiver;"playoutDelayHint"in s&&(s.playoutDelayHint=T("PRE_PLAYOUT_DELAY_HINT"),_.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(s.track.kind," set playoutDelayHint to ").concat(T("PRE_PLAYOUT_DELAY_HINT"))))}return{track:o.receiver.track,id:r,transceiver:o}})}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(n.toString()))}}async stopReceiving(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");t.forEach(o=>{Array.from(this.preMediaMap.entries()).some(s=>{let[a,{mid:c,player:d}]=s;if(c===o)return this.preMediaMap.delete(a),d&&d.destroy(),!0})}),this.remoteSDP.stopSending(t);const n=this.remoteSDP.toString(),i=this.logSDPExchange(n,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const r=await this.peerConnection.createAnswer();i==null||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(n.toString()))}}async muteRemote(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteRemote mid=".concat(t," before remote SDP created."));this.remoteSDP.mute(t);const n=this.remoteSDP.toString(),i=this.logSDPExchange(n,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const r=await this.peerConnection.createAnswer();i==null||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(n.toString()))}}async unmuteRemote(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteRemote mid=".concat(t," before remote SDP created."));this.remoteSDP.unmute(t);const n=this.remoteSDP.toString(),i=this.logSDPExchange(n,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const r=await this.peerConnection.createAnswer();i==null||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(n.toString()))}}async muteLocal(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const n=this.peerConnection.getTransceivers().filter(s=>s.mid&&t.indexOf(s.mid)!==-1);if(n.length!==t.length)throw new Error("Transceivers' length doesn't match mids' length.");n.map(s=>{s.direction="inactive"});const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(t);const o=this.remoteSDP.toString();r==null||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(n.toString()))}}async unmuteLocal(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const n=this.peerConnection.getTransceivers().filter(s=>s.mid&&t.indexOf(s.mid)!==-1);if(n.length!==t.length)throw new Error("Transceivers' length doesn't match mids' length.");n.map(async(s,a)=>{s.direction="sendonly"});const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(t),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(t,this.remoteCodecs,this.store.codec);const o=this.remoteSDP.toString();r==null||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(n.toString()))}}restartICE(t){var n=this;return di(function*(){const i=yield ve(n.mutex.lock("From P2PConnection.restartICE"));try{if(!n.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const r=Oe().supportPCSetConfiguration,o=T("FORCE_TURN_TCP")||n.forceTurn;if(t===gn.RELAY&&!r)return;if(r&&!o){const h=t===gn.RELAY?"relay":"all",u=n.peerConnection.getConfiguration();u.iceTransportPolicy!==h&&(_.debug("[".concat(n.store.clientId,"] restartICE change iceTransportPolicy from [").concat(u.iceTransportPolicy,"] to [").concat(h,"]")),u.iceTransportPolicy=h,n.peerConnection.setConfiguration(u))}n.remoteSDP.updateCandidates(t);const s=yield ve(n.peerConnection.createOffer({iceRestart:!0}));if(!s.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const a=Ho(s.sdp),{remoteIceParameters:c}=yield a.iceParameters;n.remoteSDP.restartICE(c);const d=n.remoteSDP.toString(),l=n.logSDPExchange(s.sdp||"","offer","local","restartICE");n.store.descriptionStart(),yield ve(n.peerConnection.setLocalDescription(s)),l==null||l(d),yield ve(n.peerConnection.setRemoteDescription({type:"answer",sdp:d}))}catch(r){_.warning("[".concat(n.store.clientId,"] restart ICE failed, abort operation"),r)}finally{i()}})()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const t=await this.mutex.lock("From P2PConnection.extendCandidate");try{this.remoteSDP.updateCandidates(gn.TCP_RELAY),await vi(this.peerConnection,this.remoteSDP,this.extension)}catch(n){_.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),n)}finally{t()}}close(){var t;
112this.peerConnection.getTransceivers().forEach(n=>{Yd(this.id+n.mid,this)}),this.preMediaMap.forEach(n=>{let{player:i}=n;i&&i.destroy()}),this.preMediaMap.clear(),this.peerConnection.close(),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return vr(vr({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(t){return this.statsFilter.getVideoIsReady(t)}async updateEncoderConfig(t,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),r=this.mungSendOfferSDP(i.sdp,[n],[t]);this.remoteSDP.updateRecvMedia(t,n);const o=this.remoteSDP.toString(),s=this.logSDPExchange(r,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:r}),s==null||s(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(i){throw new L(A.EXCHANGE_SDP_FAILED,i.toString())}}async updateSendParameters(t,n){const i=this.peerConnection.getTransceivers().filter(r=>r.mid===t);i.length===1&&(this.isVP8Simulcast(n)?Rt()||await this.applySimulcastEncodings(i,[n]):await this.applySendEncodings(i,[n]))}setStatsRemoteVideoIsReady(t,n){this.statsFilter.setVideoIsReady2(t,n)}async replaceTrack(t,n){const i=this.peerConnection.getTransceivers().find(r=>r.mid===n);i&&await i.sender.replaceTrack(t._mediaStreamTrack)}async getSelectedCandidatePair(){const t=this.peerConnection.getReceivers();if(t.length>0&&t[0].transport&&t[0].transport.iceTransport&&t[0].transport.iceTransport.getSelectedCandidatePair&&t[0].transport.iceTransport.getSelectedCandidatePair()){const n=t[0].transport.iceTransport,{local:i,remote:r}=n.getSelectedCandidatePair();return{local:vr(vr({},Gr),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:vr(vr({},Gr),{},{candidateType:r.type,protocol:r.protocol,address:r.address,port:r.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var t;(t=this.onICEConnectionStateChange)===null||t===void 0||t.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var t;this.peerConnection.connectionState==="connected"&&(this.isFirstConnected=!0),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=t=>{if(t&&(t.errorCode||t.errorText)){var n;const i="code: ".concat(t.errorCode,", message: ").concat(t.errorText),r=t.port?"local: ".concat(t.port):"",o=Ko(t.url||"");_.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(i,"), url: ").concat(o||"",", host_candidate:").concat(r)),(n=this.onICECandidateError)===null||n===void 0||n.call(this,i)}},this.peerConnection.onicegatheringstatechange=t=>{t&&t.target&&"iceGatheringState"in t.target&&_.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(t.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=t=>{t.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,_.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,_.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},T("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const n={iceServers:[]},i=t.cloudProxyServer||"disabled";return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&(wa(t.turnServer.servers)?n.iceServers=t.turnServer.servers:T("NEW_TURN_MODE")&&n.iceServers&&i==="disabled"?(T("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&n.iceServers.push(...Ec.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):n.iceServers.push(...Ec.newTurnServerConfigToIceServers(t.turnServer.servers)),T("NEW_FORCE_TURN")&&(n.iceTransportPolicy="relay")):t.turnServer.mode!=="off"&&(n.iceServers&&n.iceServers.push(...Ec.turnServerConfigToIceServers(t.turnServer.servers)),T("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...Ec.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),T("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEac
112h(r=>{r.forceturn&&(n.iceTransportPolicy="relay")}))),T("ENABLE_ENCODED_TRANSFORM")&&Oe().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}static turnServerConfigToIceServers(t){const n=[];return t.forEach(i=>{i.security?i.tcpport&&n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turns:".concat(qr(i.turnServerURL),":").concat(i.tcpport,"?transport=tcp")}):(i.udpport&&!T("FORCE_TURN_TCP")&&n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":").concat(i.udpport,"?transport=udp")}),i.tcpport&&n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":").concat(i.tcpport,"?transport=tcp")}))}),n}static newTurnServerConfigToIceServers(t){const n=[];return t.forEach(i=>{const r=T("NEW_TURN_MODE");r===1?n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":3478?transport=udp")}):r===2?n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":3478?transport=tcp")}):r===3?n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turns:".concat(qr(i.turnServerURL),":443?transport=tcp")}):r===4&&(n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":3478?transport=udp")}),n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":3478?transport=tcp")}),n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turns:".concat(qr(i.turnServerURL),":443?transport=tcp")}))}),n}tryBindTransportEvents(t){const n=t.transport;if(n){this.transportEventReceiver=t,n.onstatechange=()=>{var r;n!=null&&n.state&&((r=this.onDTLSTransportStateChange)===null||r===void 0||r.call(this,n.state))},n.onerror=r=>{var o;(o=this.onDTLSTransportError)===null||o===void 0||o.call(this,"error"in r?r.error:r)};const i=n.iceTransport;i&&(i.onstatechange=()=>{const r=n==null?void 0:n.iceTransport.state;var o;r&&((o=this.onICETransportStateChange)===null||o===void 0||o.call(this,r))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const{local:r,remote:o}=i.getSelectedCandidatePair()||{};if(r&&o){const s=r.address+":"+r.port,a=o.address+":"+o.port;_.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(Ko(s)),", remote ").concat(JSON.stringify(Ko(a))))}}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(t,n){var i,r;if(n||(n=this.peerConnection.getSenders().find(m=>m.track===t._mediaStreamTrack)),!n)return _.warn("[".concat(t.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(t))return _.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!Oe().supportSetRtpSenderParameters)return _.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const o={},s={};switch(t._optimizationMode){case"motion":o.degradationPreference="maintain-framerate";break;case"detail":o.degradationPreference="maintain-resolution";break;case"balanced":o.degradationPreference="balanced"}const a=vU(this.peerConnection,t._mediaStreamTrack),c=LN(t);if(s2(t)&&a&&n&&c&&this.getLocalVideoStats&&x(i=["vp8","vp9"]).call(i,this.store.codec)){var d;const m=o.degradationPreference||(x(d=t._hints).call(d,$e.CUSTOM_TRACK)?T("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");a2(this.id+a.mid,c,this,m,g=>{n&&this.updateAdaptation(n,g)},this.getLocalVideoStats.bind(this))}if(t._encoderConfig){var l;const{bitrateMax:m,frameRate:g,scaleResolutionDownBy:R}=t._encoderConfig;m&&(s.maxBitrate=1e3*m),(x(l=t._hints).call(l,$e.LOW_STREAM)||t.isUseScaleResolutionDownBy)&&(g&&(s.maxFramerate=mi(g)),R&&R>=1&&(s.scaleResolutionDownBy=R))}const{maxFramerate:h}=T("ENCODER_CONFIG_LIMIT");if(h&&typeof h=="number"&&(s.maxFramerate=s.maxFramerate?Math.min(s.maxFramerate,h):h),T("DSCP_TYPE")&&Po()){var u;const m=T("DSCP_TYPE");x(u=["very-low","low","medium","high"]).call(u,m)&&(s.networkPriority=m)}const p=n.getParameters(),E=(r=p.encodings)===null||r===void 0?void 0:r[0];
112Rt()&&!E&&(o.encodings=[s]),E&&Object.assign(E,s),Object.assign(p,o),_.debug("[".concat(t.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(p.encodings))),await n.setParameters(p),await UU(this.store.codec,n,T("SVC_MODE"))}async updateAdaptation(t,n){var i,r;if(!t)return _.debug("[updateAdaptation] no rtpSender found");if(!Oe().supportSetRtpSenderParameters)return _.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const o={},{bitrateMax:s,frameRate:a,scaleResolutionDownBy:c}=n;s&&(o.maxBitrate=1e3*s),a&&(o.maxFramerate=mi(a)),c&&c>=1&&x(i=["vp8","vp9"]).call(i,this.store.codec)&&(o.scaleResolutionDownBy=c);const d=t.getParameters(),l=(r=d.encodings)===null||r===void 0?void 0:r[0];l&&Object.assign(l,o),Object.assign(d,{});try{await t.setParameters(d),_.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(d.encodings)))}catch(h){!("transport"in t)||t.transport&&t.transport.state==="connected"?this.peerConnectionState!=="connected"?_.debug("[updateAdaptation] peerConnection not connected}"):_.debug("[updateAdaptation] updateRtpSenderEncodings failed",h):_.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(t,n){try{if(!Oe().supportSetRtpSenderParameters||t.length!==n.length)return;for(let i=0;i<t.length;i++){const r=t[i],o=n[i];o instanceof pt&&!this.isVP8Simulcast(o)&&await this.updateRtpSenderEncodings(o,r.sender)}}catch{_.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(t,n,i){if(T("FORBID_MODIFY_LOCAL_OFFER_SDP"))return t;const r=ii(t);return n.forEach((o,s)=>{const a=i[s],c=r.mediaDescriptions.find(d=>d.attributes.mid===a);c&&(rc(c,o),dv(c,o,this.store.codec))}),as(r)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=t=>{var n;(n=this.onFirstAudioReceived)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstVideoReceived=t=>{var n;(n=this.onFirstVideoReceived)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstAudioDecoded=t=>{var n;(n=this.onFirstAudioDecoded)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstVideoDecoded=(t,n,i)=>{var r;(r=this.onFirstVideoDecoded)===null||r===void 0||r.call(this,t,n,i)},this.statsFilter.onSelectedLocalCandidateChanged=(t,n)=>{var i;(i=this.onSelectedLocalCandidateChanged)===null||i===void 0||i.call(this,t,n)},this.statsFilter.onSelectedRemoteCandidateChanged=(t,n)=>{var i;(i=this.onSelectedRemoteCandidateChanged)===null||i===void 0||i.call(this,t,n)},this.statsFilter.onFirstVideoDecodedTimeout=t=>{var n;(n=this.onFirstVideoDecodedTimeout)===null||n===void 0||n.call(this,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(t,n){if(t.length===n.length)for(let c=0;c<t.length;c++){var i,r,o,s,a;const d=t[c],l=n[c];if(l instanceof pt&&!x(i=l._hints).call(i,$e.LOW_STREAM)&&(r=l._encoderConfig)!==null&&r!==void 0&&r.bitrateMax&&((o=l._encoderConfig)===null||o===void 0?void 0:o.bitrateMax)>200&&(s=l._scalabilityMode)!==null&&s!==void 0&&s.numSpatialLayers&&((a=l._scalabilityMode)===null||a===void 0?void 0:a.numSpatialLayers)>1&&this.store.codec==="vp8"){const h={},u={high:1e3*(l._encoderConfig.bitrateMax-50),medium:5e4};h.encodings=[{rid:"m",active:!0,maxBitrate:u.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:u.high}];const p=d.sender.getParameters();await d.sender.setParameters(Object.assign(p,h))}}}
112async applySimulcastEncodings(t,n){if(!Rt()&&t.length===n.length)for(let i=0;i<t.length;i++){const r=n[i];if(r instanceof pt&&this.isVP8Simulcast(r)){const o=t[i],s={},a={high:1e3*(r._encoderConfig.bitrateMax-50),medium:5e4};s.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:a.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:a.medium,scaleResolutionDownBy:4}];const c=o.sender.getParameters();await o.sender.setParameters(Object.assign(c,s))}}}isVP8Simulcast(t){var n,i,r,o,s;return!!(t instanceof pt&&T("SIMULCAST")&&this.store.codec==="vp8"&&!x(n=t._hints).call(n,$e.LOW_STREAM)&&(i=t._encoderConfig)!==null&&i!==void 0&&i.bitrateMax&&((r=t._encoderConfig)===null||r===void 0?void 0:r.bitrateMax)>200&&(o=t._scalabilityMode)!==null&&o!==void 0&&o.numSpatialLayers&&((s=t._scalabilityMode)===null||s===void 0?void 0:s.numSpatialLayers)>1)}logSDPExchange(t,n,i,r){if(T("SDP_LOGGING"))return _.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(n," SDP during P2PConnection.").concat(r,` 113`),t),n==="offer"?o=>{this.logSDPExchange(o,"answer",i==="local"?"remote":"local",r)}:void 0}async getRemoteSSRC(t){if(!this.remoteSDP)return;const n=this.remoteSDP.getSSRC(t);return n&&n.length!==0?n[0].ssrcId:void 0}setConfiguration(t){if(Oe().supportPCSetConfiguration){const n=Ec.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}t.isPreallocation&&(this.isPreallocation=!0)}},H(Ve.prototype,"updateRemoteRTPCapabilities",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"updateRemoteRTPCapabilities"),Ve.prototype),H(Ve.prototype,"connect",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"connect"),Ve.prototype),H(Ve.prototype,"updateRemoteConnect",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"updateRemoteConnect"),Ve.prototype),H(Ve.prototype,"createDataChannels",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"createDataChannels"),Ve.prototype),H(Ve.prototype,"receive",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"receive"),Ve.prototype),H(Ve.prototype,"batchReceive",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"batchReceive"),Ve.prototype),H(Ve.prototype,"stopReceiving",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"stopReceiving"),Ve.prototype),H(Ve.prototype,"muteRemote",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"muteRemote"),Ve.prototype),H(Ve.prototype,"unmuteRemote",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"unmuteRemote"),Ve.prototype),H(Ve.prototype,"muteLocal",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"muteLocal"),Ve.prototype),H(Ve.prototype,"unmuteLocal",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"unmuteLocal"),Ve.prototype),H(Ve.prototype,"close",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"close"),Ve.prototype),H(Ve.prototype,"updateEncoderConfig",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"updateEncoderConfig"),Ve.prototype),H(Ve.prototype,"updateSendParameters",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"updateSendParameters"),Ve.prototype),H(Ve.prototype,"replaceTrack",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"replaceTrack"),Ve.prototype),H(Ve.prototype,"updateAdaptation",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"updateAdaptation"),Ve.prototype),H(Ve.prototype,"getRemoteSSRC",[Ei],Object.getOwnPropertyDescriptor(Ve.prototype,"getRemoteSSRC"),Ve.prototype),Ve);function Ei(e,t,n){const i=e[t];if(typeof i!="function")throw new Error("Cannot use mutex on object property.");return n.value=async function(){const r=this.mutex,o=await r.lock("From P2PConnection.".concat(t));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return await i.apply(this,a)}finally{o()}},n}function Nv(e,t){let n=document.createElement("video"),i=document.createElement("canvas");n.setAttribute("style","display:none"),i.setAttribute("style","display:none"),n.setAttribute("muted",""),n.muted=!0,n.setAttribute("autoplay",""),n.autoplay=!0,n.setAttribute("playsinline",""),i.width=mi(t.width),i.height=mi(t.height);const r=mi(t.framerate||15);document.body.append(n),document.body.append(i);let o=e._mediaStreamTrack;
vendor: 9,788 bytes, line 113
113n.srcObject=new MediaStream([o]),n.play().catch(Hl);const s=i.getContext("2d");if(!s)throw new D(A.UNEXPECTED_ERROR,"can not get canvas context");const a=Oe(),c=i.captureStream(a.supportRequestFrame?0:r).getVideoTracks()[0];c.canvas||(c.canvas=i),i.startCapture=()=>{if(!n)return i.stopCapture&&i.stopCapture();if(n.paused&&n.play(),n.videoHeight>2&&n.videoWidth>2){const l=n.videoWidth,h=n.videoHeight/l,u=i.width*h;Math.abs(u-i.height)>=2&&(_.debug("adjust low stream resolution","".concat(i.width,"x").concat(i.height," -> ").concat(i.width,"x").concat(u)),i.height=u)}s.drawImage(n,0,0,i.width,i.height),c.requestFrame&&c.requestFrame(),o!==e._mediaStreamTrack&&(o=e._mediaStreamTrack,n.srcObject=new MediaStream([o]))},i.stopCapture=LS(()=>i.startCapture&&i.startCapture(),r);const d=c.stop;return c.stop=()=>{d.call(c),n&&(n.remove(),n.srcObject=null,n=null),i&&(i.width=0,i.remove(),i.stopCapture&&i.stopCapture(),i.startCapture=void 0,i.stopCapture=void 0,i=null),_.debug("clean low stream renderer")},c}var d2=function(e){return e[e.Video_Send_Type=190]="Video_Send_Type",e}(d2||{}),Fi=function(e){return e[e.Video_Send_Qp_Sum=2143]="Video_Send_Qp_Sum",e[e.Video_Send_Freeze=2082]="Video_Send_Freeze",e[e.Video_Send_Codec=2240]="Video_Send_Codec",e[e.Video_Send_Power_Efficient_Encoder=2241]="Video_Send_Power_Efficient_Encoder",e[e.Video_Recv_Qp_Sum=2144]="Video_Recv_Qp_Sum",e[e.Video_Recv_Freeze=2084]="Video_Recv_Freeze",e[e.Video_Recv_Codec=2242]="Video_Recv_Codec",e[e.Video_Recv_Power_Efficient_Decoder=2243]="Video_Recv_Power_Efficient_Decoder",e[e.Video_Render_Freeze_Time=2109]="Video_Render_Freeze_Time",e[e.Video_Render_Freeze_Time_Render=2147]="Video_Render_Freeze_Time_Render",e[e.Video_Render_Freeze_Time_Render2=2223]="Video_Render_Freeze_Time_Render2",e[e.Audio_Recv_Freeze=2083]="Audio_Recv_Freeze",e}(Fi||{}),Se=function(e){return e[e.Video_Send_Retransmit=2062]="Video_Send_Retransmit",e[e.Video_Send_Target_Encoded=2064]="Video_Send_Target_Encoded",e[e.Video_Send_Actual_Encoded=2060]="Video_Send_Actual_Encoded",e[e.Video_Send_Transmit=2066]="Video_Send_Transmit",e[e.Video_Send_Bandwidth=2061]="Video_Send_Bandwidth",e[e.Video_Capture_Height=2033]="Video_Capture_Height",e[e.Video_Capture_Width=2035]="Video_Capture_Width",e[e.Video_Capture_Frame_Rate=2034]="Video_Capture_Frame_Rate",e[e.Video_Send_Low_Height=2073]="Video_Send_Low_Height",e[e.Video_Send_Low_Frame_Rate=2075]="Video_Send_Low_Frame_Rate",e[e.Video_Send_Low_Width=2077]="Video_Send_Low_Width",e[e.Video_Send_Low_Bitrate=2069]="Video_Send_Low_Bitrate",e[e.Video_Send_Low_Package_Lost=2070]="Video_Send_Low_Package_Lost",e[e.Video_Send_Low_Package_Rate=2071]="Video_Send_Low_Package_Rate",e[e.Video_Send_Frame_Rate=2002]="Video_Send_Frame_Rate",e[e.Video_Send_Width=2003]="Video_Send_Width",e[e.Video_Send_Height=2004]="Video_Send_Height",e[e.Video_Send_Disabled=2095]="Video_Send_Disabled",e[e.Video_Send_Adaptation=2032]="Video_Send_Adaptation",e[e.Video_Send_Player_Status=2128]="Video_Send_Player_Status",e[e.Video_Send_Nacks=2009]="Video_Send_Nacks",e[e.Video_Send_Plis=2010]="Video_Send_Plis",e[e.Video_Send_Firs=2011]="Video_Send_Firs",e[e.Video_Send_Avg_Encode=2007]="Video_Send_Avg_Encode",e[e.Video_Send_Huge_Frame_Sent=2174]="Video_Send_Huge_Frame_Sent",e[e.Video_Send_Bytes_Retransmit=2173]="Video_Send_Bytes_Retransmit",e[e.Video_Send_Packages_Retransmit=2172]="Video_Send_Packages_Retransmit",e[e.Video_Send_Key_Frames_Encoded=2207]="Video_Send_Key_Frames_Encoded",e[e.Video_Send_Bitrate=2012]="Video_Send_Bitrate",e[e.Video_Send_Package_Rate=2031]="Video_Send_Package_Rate",e[e.Video_Send_Package_Lost=2005]="Video_Send_Package_Lost",e[e.Audio_Capture_PCM_Level=2104]="Audio_Capture_PCM_Level",e[e.Audio_Send_Level=2038]="Audio_Send_Level",e[e.Audio_Send_Bitrate=2039]="Audio_Send_Bitrate",e[e.Audio_Send_Package_Rate=2040]="Audio_Send_Package_Rate",e[e.Audio_Send_AEC_Return_Loss=2041]="Audio_Send_AEC_Return_Loss",e[e.Audio_Send_AEC_Return_Loss_Enhancement=2042]="Audio_Send_AEC_Return_Loss_Enhancement",e[e.Audio_Send_Freeze=2081]="Audio_Send_Freeze",e[e.Audio_Send_Disabled=2096]="Audio_Send_Disabled",e[e.Audio_Send_Bytes_Retransmit=2179]="Audio_Send_Bytes_Retransmit",e[e.Audio_Send_Packages_Retransmit=2180]="Audio_Send_Packages_Retransmit",e[e.Video_Recv_Height=2019]="Video_Recv_Height",e[e.Video_Recv_Width=2018]="Video_Recv_Width",e[e.Video_Recv_Frame_Rate_Output=2155]="Video_Recv_Frame_Rate_Output",e[e.Video_Recv_Jitter_Buffer=2023]="Video_Recv_Jitter_Buffer",e[e.Video_Recv_Current_Delay=2024]="Video_Recv_Current_Delay",e[e.Video_Recv_Nacks=2026]="Video_Recv_Nacks",e[e.Video_Recv_Plis=2027]="Video_Recv_Plis",e[e.Video_Recv_Firs=2028]="Video_Recv_Firs",e[e.Video_Recv_Disabled=2101]="Video_Recv_Disabled",e[e.Video_Recv_Player_Status=2129]="Video_Recv_Player_Status",e[e.Video_Recv_I_Frame_Delay=2149]="Video_Recv_I_Frame_Delay",e[e.Video_Render_Frame_Rate_Render=2022]="Video_Render_Frame_Rate_Render",e[e.Video_Render_Freeze_Duration=2156]="Video_Render_Freeze_Duration",e[e.Audio_Render_Level=2043]="Audio_Render_Level",e[e.Audio_Render_Freeze_Time_80ms=2226]="Audio_Render_Freeze_Time_80ms",e[e.Audio_Render_Freeze_Time_200ms=2227]="Audio_Render_Freeze_Time_200ms",e[e.Audio_Render_Freeze_Samples_80ms=2228]="Audio_Render_Freeze_Samples_80ms",e[e.Audio_Render_Freeze_Samples_200ms=2229]="Audio_Render_Freeze_Samples_200ms",e[e.Audio_Recv_PCM_Level=2105]="Audio_Recv_PCM_Level",e[e.Audio_Recv_Disabled=2102]="Audio_Recv_Disabled",e[e.Audio_Recv_Jitter_Buffer=2054]="Audio_Recv_Jitter_Buffer",e[e.Audio_Recv_Current_Delay=2047]="Audio_Recv_Current_Delay",e[e.Audio_Recv_Player_Status=2130]="Audio_Recv_Player_Status",e[e.Audio_Recv_Bitrate=2044]="Audio_Recv_Bitrate",e[e.Audio_Recv_Concealed_Samples=2148]="Audio_Recv_Concealed_Samples",e[e.Audio_Recv_Total_Samples_Received=2224]="Audio_Recv_Total_Samples_Received",e}(Se||{}),Sn=function(e){return e[e.Video_Render_Frame_Rate_Decode=2021]="Video_Render_Frame_Rate_Decode",e[e.Video_Recv_Frame_Rate=2020]="Video_Recv_Frame_Rate",e[e.Video_Recv_Frame_Dropped=2181]="Video_Recv_Frame_Dropped",e[e.Video_Recv_Bytes_Retransmit=2175]="Video_Recv_Bytes_Retransmit",e[e.Video_Recv_Packages_Retransmit=2176]="Video_Recv_Packages_Retransmit",e[e.Video_Recv_Packages_Discarded=2198]="Video_Recv_Packages_Discarded",e[e.Video_Recv_Avg_Decode=2200]="Video_Recv_Avg_Decode",e[e.Video_Recv_Avg_Processing_Delay=2202]="Video_Recv_Avg_Processing_Delay",e[e.Video_Recv_Avg_Assembly_Time=2203]="Video_Recv_Avg_Assembly_Time",e[e.Video_Recv_Avg_Inter_Frame_Delay=2204]="Video_Recv_Avg_Inter_Frame_Delay",e[e.Video_Recv_Key_Frames_Decoded=2206]="Video_Recv_Key_Frames_Decoded",e[e.Video_Recv_Package_Lost=2014]="Video_Recv_Package_Lost",e[e.Video_Recv_Bitrate=2029]="Video_Recv_Bitrate",e[e.Video_Recv_Package_Rate=2078]="Video_Recv_Package_Rate",e[e.Audio_Recv_Jitter=2055]="Audio_Recv_Jitter",e[e.Audio_Recv_Bytes_Retransmit=2178]="Audio_Recv_Bytes_Retransmit",e[e.Audio_Recv_Packages_Retransmit=2177]="Audio_Recv_Packages_Retransmit",e[e.Audio_Recv_Packages_Discarded=2199]="Audio_Recv_Packages_Discarded",e[e.Audio_Recv_Avg_Processing_Delay=2201]="Audio_Recv_Avg_Processing_Delay",e[e.Audio_Recv_Package_Rate=2046]="Audio_Recv_Package_Rate",e[e.Audio_Recv_Package_Lost=2045]="Audio_Recv_Package_Lost",e[e.Audio_Recv_AV_Sync_TIME=2237]="Audio_Recv_AV_Sync_TIME",e}(Sn||{}),Ln=function(e){return e[e.RTT=2006]="RTT",e[e.CONN_TYPE=801]="CONN_TYPE",e[e.STATS_UPDATE_INTERVAL=2205]="STATS_UPDATE_INTERVAL",e}(Ln||{}),Xd=function(e){return e[e.RTC_PEER_CONNECTION_STATE=2219]="RTC_PEER_CONNECTION_STATE",e[e.PAGE_VISIBILITY=2233]="PAGE_VISIBILITY",e}(Xd||{}),Dv=function(e){return e[e.Transport_Send_Bitrate=2234]="Transport_Send_Bitrate",e[e.Transport_Recv_Bitrate=2235]="Transport_Recv_Bitrate",e}(Dv||{});const dc=1e3,vm=6,Gu=3,Lee=Math.max(vm,Gu,60);function l2(e){return e=e.toLowerCase(),x(e).call(e,"vp8")?1:x(e).call(e,"h264")?2:x(e).call(e,"vp9")?3:x(e).call(e,"av1")?4:x(e).call(e,"h265")?5:0}function de(e,t,n){n!=null&&Number.isFinite(n)&&(e[t]=Math.round(Math.max(0,n)))}function u2(e){const t={[Ln.CONN_TYPE]:0,[Ln.RTT]:e.rtt,[Ln.STATS_UPDATE_INTERVAL]:e.updateInterval?Math.round(Math.max(0,e.updateInterval)):void 0};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const n=e.selectedCandidatePair.localCandidate.relayProtocol;n==="udp"&&(t[Ln.CONN_TYPE]=1),n==="tcp"&&(t[Ln.CONN_TYPE]=3),n==="tls"&&(t[Ln.CONN_TYPE]=4);break}case"srflx":t[Ln.CONN_TYPE]=2;break;case"unknown":t[Ln.CONN_TYPE]=5;break;default:t[Ln.CONN_TYPE]=0}return t}function h2(e){let t=0;switch(e){case"none":t=0;break;case"cpu":t=1;break;case"bandwidth":t=2;break;case"other":t=3}return t}class p2 extends Nt{constructor(t){super(),S(this,"store",void 0),S(this,"uploadWRTCStatsTimer",void 0),S(this,"uploadOutboundDenoiserStatsTimer",void 0),S(this,"uploadExtStatsTimer",void 0),S(this,"uploadExtUsageStatsTimer",void 0),S(this,"uploadInboundExtStatsTimer",void 0),S(this,"requestStats",void 0),S(this,"requestTransportStats",void 0),S(this,"requestLocalMedia",void 0),S(this,"requestRemoteMedia",void 0),S(this,"requestAllTracks",void 0),S(this,"requestVideoIsReady",void 0),S(this,"requestUploadStats",void 0),S(this,"requestUpload",void 0),S(this,"uploadOutboundStarted",!1),S(this,"uploadInboundStarted",!1),S(this,"uploadTransportStarted",!1),S(this,"uploadBaseStatsStarted",!1),S(this,"uploadExtensionUsageStarted",!1),S(this,"lastRecvStats",void 0),S(this,"lastSendStats",void 0),S(this,"lastRefRecvStats",void 0),S(this,"lastRefSendStats",void 0),S(this,"lastNormalRecvStats",void 0),S(this,"lastNormalSendStats",void 0),S(this,"lastExtendStats",{}),S(this,"needUploadStats",{}),S(this,"needUploadRenderFreezeTime",!0),S(this,"lastUploadCompensateTime",-1),S(this,"uploadCompensateDeltaTime",0),this.store=t}
113uploadWRTCStats(t){if(!this.requestStats||!this.requestUploadStats)return;const n=t%Gu==0,i=t%vm==0,r=t%60==0;let o,s;if(this.uploadTransportStarted&&(o=this.requestStats(),this.store.useP2P&&(s=this.requestStats(!0))),!o&&this.uploadOutboundStarted&&(o=this.requestStats()),!s&&this.uploadInboundStarted&&(s=this.requestStats(!0)),o||s){var a;const c={};if(this.uploadTransportStarted&&o){const l=this.getTransportStats(o,n?this.lastRefSendStats:void 0,s,n);l&&(c.misc=[l])}if(this.uploadOutboundStarted&&o){const l=this.getOutboundStats(o,i?this.lastNormalSendStats:void 0,n?this.lastRefSendStats:void 0,this.lastSendStats,r);l&&(c.outbound=[l])}if(this.uploadInboundStarted&&s){this.uploadCompensateStats(t);const l=this.getInboundStats(s,i?this.lastNormalRecvStats:void 0,n?this.lastRefRecvStats:void 0,this.lastRecvStats);l&&(c.inbound=l)}const d=(a=this.requestTransportStats)===null||a===void 0?void 0:a.call(this).connectState;if(d&&(Array.isArray(c.misc)?c.misc[0]&&c.misc[0].addition&&(c.misc[0].addition[Xd.RTC_PEER_CONNECTION_STATE]=hS[d]):c.misc=[{addition:{[Xd.RTC_PEER_CONNECTION_STATE]:hS[d]}}]),Vi.needUploadStats.length>0||i){const l=Vi.needUploadStats.shift()||(Vi.visibility==="visible"?1:0);Array.isArray(c.misc)?c.misc[0]&&c.misc[0].addition&&(c.misc[0].addition[Xd.PAGE_VISIBILITY]=l):c.misc=[{addition:{[Xd.PAGE_VISIBILITY]:l}}]}this.needUploadStats.sendType&&(Array.isArray(c.outbound)&&c.outbound[0]&&c.outbound[0].high&&(c.outbound[0].high[d2.Video_Send_Type]=this.needUploadStats.sendType),this.needUploadStats.sendType=void 0),this.requestUploadStats(c)}this.lastRecvStats=s,this.lastSendStats=o,i&&(this.lastNormalRecvStats=s,this.lastNormalSendStats=o),n&&(this.lastRefRecvStats=s,this.lastRefSendStats=o)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;this.uploadBaseStatsStarted=!0,Vi.startCollectStats();let t=1;this.uploadWRTCStatsTimer=window.setInterval(()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted){if(this.uploadBaseStatsStarted){var n,i;const r=(n=this.requestTransportStats)===null||n===void 0?void 0:n.call(this);return void(r&&((i=this.requestUploadStats)===null||i===void 0||i.call(this,{misc:[{addition:{[Xd.RTC_PEER_CONNECTION_STATE]:hS[r.connectState]}}]})))}return this.stopUploadWRTCStats()}this.uploadWRTCStats(t),++t===Lee+1&&(t=1)},dc)}uploadCompensateStats(t){if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const n=t%Gu==0&&this.needUploadRenderFreezeTime;if(!this.uploadInboundStarted||!n)return;if(this.lastUploadCompensateTime===-1)return void(this.lastUploadCompensateTime=Date.now());const i=Math.max(-6e3,Date.now()-this.lastUploadCompensateTime-6e3);if(this.uploadCompensateDeltaTime+=i,this.lastUploadCompensateTime=Date.now(),this.uploadCompensateDeltaTime<6e3)return;const r=Math.min(Math.floor(this.uploadCompensateDeltaTime/6e3),10);this.uploadCompensateDeltaTime-=6e3*r;const o=this.requestStats(!0);new Array(r).fill(0).forEach(()=>{if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const s={};if(this.uploadInboundStarted&&o){const a=this.requestRemoteMedia()||[],c=[];a.forEach(d=>{let[l,h]=d;const u={peer:l.uid};if(l._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(l._videoSSRC)&&h.has($.VIDEO)&&l.videoTrack){const p=function(E,m,g){if(!m.videoRecv.find(v=>v.ssrc===E))return;const R={};if(g&&g._player){const v=g._player,{renderFreezeAccTime2:C,videoElementStatus:w}=v;if(Vi.visibility==="visible"&&w===Dn.PLAYING&&Oe().supportRequestVideoFrameCallback){const b=Math.min(6e3,C);v.renderFreezeAccTime2=Math.max(0,C-b),de(R,Fi.Video_Render_Freeze_Time_Render2,b),T("USE_NEW_RENDER_FREEZE_TIME")&&de(R,Fi.Video_Render_Freeze_Time_Render,b)}}return R}(l._videoSSRC,o,l.videoTrack);p&&(u.video=p)}u.video&&c.push(u)}),c.length>0&&(s.inbound=c,this.requestUploadStats(s))}})}stopUploadWRTCStats(){window.clearInterval(this.uploadWRTCStatsTimer),this.uploadWRTCStatsTimer=void 0,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSen
113d=[],this.lastRefSendStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0}getTransportStats(t,n,i,r){if(!this.requestStats)return;if(!r)return t.rtt==null?void 0:{addition:{[Ln.RTT]:t.rtt,[Ln.CONN_TYPE]:void 0,[Ln.STATS_UPDATE_INTERVAL]:t.updateInterval||void 0}};const o=u2(t);if(this.store.useP2P){if(i){const s=u2(i);o[Ln.CONN_TYPE]&&s[Ln.CONN_TYPE]&&(o[Ln.CONN_TYPE]+=s[Ln.CONN_TYPE]<<3)}o[Ln.CONN_TYPE]?o[Ln.CONN_TYPE]+=110:o[Ln.CONN_TYPE]=110}else{o[Ln.CONN_TYPE]?o[Ln.CONN_TYPE]+=100:o[Ln.CONN_TYPE]=100;const s=function(a,c){return c?[Math.ceil(8*(a.transport.bytesSent-c.transport.bytesSent)/(a.timestamp-c.timestamp)),Math.ceil(8*(a.transport.bytesReceived-c.transport.bytesReceived)/(a.timestamp-c.timestamp))]:[0,0]}(t,n);o[Dv.Transport_Send_Bitrate]=s[0],o[Dv.Transport_Recv_Bitrate]=s[1]}return{addition:o}}getOutboundStats(t,n,i,r,o){if(!this.requestUploadStats||!this.requestLocalMedia)return;const s=this.requestLocalMedia();if(!s||s.length===0)return;let a,c,d;return s.forEach(l=>{let[h,{track:u,ssrcs:p}]=l;switch(h){case G.LocalVideoLowTrack:case G.LocalVideoTrack:if(h===G.LocalVideoTrack){var E;const m=function(C,w,b,y,N,k){const U=w.videoSend.find(_e=>_e.ssrc===C);if(!U)return;const X={},{sentFrame:q,inputFrame:se}=U;if(y&&(de(X,Fi.Video_Send_Qp_Sum,U.qpSumPerFrame),U.codec&&de(X,Fi.Video_Send_Codec,l2(U.codec)),typeof U.powerEfficientEncoder=="number"&&de(X,Fi.Video_Send_Power_Efficient_Encoder,U.powerEfficientEncoder),se&&q)){const _e=se.frameRate,me=q.frameRate;X[Fi.Video_Send_Freeze]=function(ke,We){let M=!0;return M=!(ke<=5)&&(ke<=10?We<3:ke<=20?We<4:We<5),M}(_e,me)?1:0}if(N){switch(q&&(de(X,Se.Video_Send_Height,q.height),de(X,Se.Video_Send_Width,q.width),de(X,Se.Video_Send_Frame_Rate,q.frameRate)),X[Se.Video_Send_Disabled]=b._originMediaStreamTrack&&!b._originMediaStreamTrack.enabled||b._mediaStreamTrack&&!b._mediaStreamTrack.enabled?1:0,U.adaptionChangeReason){case"none":X[Se.Video_Send_Adaptation]=0;break;case"cpu":X[Se.Video_Send_Adaptation]=1;break;case"bandwidth":X[Se.Video_Send_Adaptation]=2;break;case"other":X[Se.Video_Send_Adaptation]=3}let _e=0;U.adaptionChangeReason&&(_e+=h2(U.adaptionChangeReason)),w.qualityLimitationReason&&(_e+=h2(w.qualityLimitationReason)<<3),X[Se.Video_Send_Adaptation]=_e,X[Se.Video_Send_Player_Status]=NS[b._player?b._player.videoElementStatus:"uninit"],de(X,Se.Video_Send_Nacks,U.nacksCount),de(X,Se.Video_Send_Plis,U.plisCount),de(X,Se.Video_Send_Firs,U.firsCount),de(X,Se.Video_Send_Avg_Encode,U.avgEncodeMs),de(X,Se.Video_Send_Huge_Frame_Sent,U.hugeFramesSent),de(X,Se.Video_Send_Bytes_Retransmit,U.retransmittedBytesSent),de(X,Se.Video_Send_Packages_Retransmit,U.retransmittedPacketsSent),de(X,Se.Video_Send_Key_Frames_Encoded,U.keyFramesEncoded);const me=N.videoSend.find(ke=>ke.ssrc===C);if(me){let ke=dc*Gu;me.timestamp&&U.timestamp&&(ke=U.timestamp-me.timestamp),me.packets!=null&&U.packets!=null&&de(X,Se.Video_Send_Package_Rate,1e3*(U.packets-me.packets)/ke),U.packetsLost!=null&&me.packetsLost!=null&&de(X,Se.Video_Send_Package_Lost,U.packetsLost-me.packetsLost),me.bytes!=null&&U.bytes!=null&&de(X,Se.Video_Send_Bitrate,8*(U.bytes-me.bytes)/ke)}}return X}(p[0].ssrcId,t,u,n,i),g=u.__className__==="CameraVideoTrack"?3:x(E=u._hints).call(E,$e.SCREEN_TRACK)?7:10;(this.lastExtendStats.sendType!==g||o)&&(this.needUploadStats={sendType:g},this.lastExtendStats.sendType=g);const R=u&&function(C,w,b,y){const N=w.videoSend.find(U=>U.ssrc===C);if(!N)return null;const k={};if(y){const U=N.inputFrame,X=U&&U.height||b.videoHeight||0,q=U&&U.width||b.videoWidth||0,se=U&&U.frameRate||0;de(k,Se.Video_Capture_Height,X),de(k,Se.Video_Capture_Width,q),de(k,Se.Video_Capture_Frame_Rate,se)}return k}(p[0].ssrcId,t,u,!!i),v=function(C,w){const b={};return w&&(de(b,Se.Video_Send_Retransmit,C.bitrate.retransmit),de(b,Se.Video_Send_Target_Encoded,C.bitrate.targetEncoded),de(b,Se.Video_Send_Actual_Encoded,C.bitrate.actualEncoded),de(b,Se.Video_Send_Transmit,C.bitrate.transmit),de(b,Se.Video_Send_Bandwidth,C.sendBandwidth)),b}(t,!!i);c=Object.assign({},m,R,v)}else d=function(m,g,R,v,C){const w=g.videoSend.find(y=>y.ssrc===m);if(!w)return;const b={};if(v){const y=w.sentFrame;y&&(de(b,Se.Video_Send_Low_Height,y.height),de(b,Se.Video_Send_Low_Width,y.width),de(b,Se.Video_Send_Low_Frame_Rate,y.frameRate));const N=v.videoSend.find(k=>k.ssrc===m);if(N){let k=dc*vm;N.timestamp&&w.timestamp&&(k=w.timestamp-N.timestamp),N.packets!=null&&w.packets!=null&&de(b,Se.Video_Send_Low_Package_Rate,1e3*(w.packets-N.packets)/k),w.packetsLost!=null&&N.packetsLost!=null&&de(b,Se.Video_Send_Low_Package_Lost,w.packetsLost-N.packetsLost),N.bytes!=null&&w.bytes!=null&&de(b,Se.Video_Send_Low_Bitrate,8*(w.bytes-N.bytes)/k)}}return b}(p[0].ssrcId,t,0,i);break;case G.LocalAudioTrack:a=u&&function(m,g,R,v,C,w){const b=g.audioSen
113d.find(N=>N.ssrc===m);if(!b)return;const y={};if(C){y[Se.Audio_Send_Disabled]=R._originMediaStreamTrack&&!R._originMediaStreamTrack.enabled||R._mediaStreamTrack&&!R._mediaStreamTrack.enabled?1:0;const N=100*R._source.getAccurateVolumeLevel(),k=b.inputLevel;if(k!=null){const X=Math.ceil(50*Math.log10(100*k+1));de(y,Se.Audio_Send_Level,X)}de(y,Se.Audio_Capture_PCM_Level,N),de(y,Se.Audio_Send_AEC_Return_Loss,b.aecReturnLoss),de(y,Se.Audio_Send_AEC_Return_Loss_Enhancement,b.aecReturnLossEnhancement),de(y,Se.Audio_Send_Bytes_Retransmit,b.retransmittedBytesSent),de(y,Se.Audio_Send_Packages_Retransmit,b.retransmittedPacketsSent),y[Se.Audio_Send_Freeze]=0;const U=C.audioSend.find(X=>X.ssrc===m);if(U){let X=dc*vm;U.timestamp&&b.timestamp&&(X=b.timestamp-U.timestamp),U.bytes!=null&&b.bytes!=null&&de(y,Se.Audio_Send_Bitrate,8*(b.bytes-U.bytes)/X),U.packets!=null&&b.packets!=null&&de(y,Se.Audio_Send_Package_Rate,1e3*(b.packets-U.packets)/X)}}return y}(p[0].ssrcId,t,u,0,i)}}),{high:c,low:d,audio:a}}getInboundStats(t,n,i,r){if(!this.requestRemoteMedia)return;const o=this.requestRemoteMedia()||[],s=[];return o.forEach(a=>{let[c,d]=a;const l={peer:c.uid};let h;if(d.has($.VIDEO)&&c.videoTrack){const u=c._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(c._videoSSRC)||!1,p=c.videoTrack?function(E,m,g,R,v,C,w,b){const y=m.videoRecv.find(me=>me.ssrc===E);if(!y)return;const N={},{receivedFrame:k,outputFrame:U,decodeFrameRate:X}=y;de(N,Sn.Video_Render_Frame_Rate_Decode,X),y.framesRateFirefox&&de(N,Sn.Video_Recv_Frame_Rate,y.framesRateFirefox),k&&de(N,Sn.Video_Recv_Frame_Rate,k.frameRate),de(N,Sn.Video_Recv_Frame_Dropped,y.framesDroppedCount),de(N,Sn.Video_Recv_Bytes_Retransmit,y.retransmittedBytesReceived),de(N,Sn.Video_Recv_Packages_Retransmit,y.retransmittedPacketsReceived),de(N,Sn.Video_Recv_Packages_Discarded,y.packetsDiscarded),de(N,Sn.Video_Recv_Avg_Decode,y.avgDecodeMs),de(N,Sn.Video_Recv_Avg_Processing_Delay,y.avgProcessingDelayMs),de(N,Sn.Video_Recv_Avg_Assembly_Time,y.avgFramesAssembledFromMultiplePacketsMs),de(N,Sn.Video_Recv_Avg_Inter_Frame_Delay,y.avgInterFrameDelayMs),de(N,Sn.Video_Recv_Key_Frames_Decoded,y.keyFramesDecoded);const q=b&&b.videoRecv.find(me=>me.ssrc===E);if(q){const me=m.timestamp-b.timestamp||dc;y.packetsLost!=null&&q.packetsLost!=null&&de(N,Sn.Video_Recv_Package_Lost,y.packetsLost-q.packetsLost),q.bytes!=null&&y.bytes!=null&&de(N,Sn.Video_Recv_Bitrate,8*(y.bytes-q.bytes)/me),q.packets!=null&&y.packets!=null&&de(N,Sn.Video_Recv_Package_Rate,1e3*(y.packets-q.packets)/me)}const se=C&&C.videoRecv.find(me=>me.ssrc===E);if(se&&(de(N,Fi.Video_Recv_Qp_Sum,y.qpSumPerFrame),y.codec&&de(N,Fi.Video_Recv_Codec,l2(y.codec)),typeof y.powerEfficientDecoder=="number"&&de(N,Fi.Video_Recv_Power_Efficient_Decoder,y.powerEfficientDecoder),N[Fi.Video_Recv_Freeze]=R&&Bu.isRemoteVideoFreeze(g,y,se)?1:0),w){var _e;const me=w.videoRecv.find(We=>We.ssrc===E);k?(de(N,Se.Video_Recv_Height,k.height),de(N,Se.Video_Recv_Width,k.width)):g&&(de(N,Se.Video_Recv_Height,g._videoHeight||0),de(N,Se.Video_Recv_Width,g._videoWidth||0)),U&&de(N,Se.Video_Recv_Frame_Rate_Output,U.frameRate);const ke=(_e=g._player)===null||_e===void 0?void 0:_e.rendFrameRate.toFixed(0);if(ke&&de(N,Se.Video_Render_Frame_Rate_Render,+ke),de(N,Se.Video_Recv_Jitter_Buffer,y.jitterBufferMs),de(N,Se.Video_Recv_Current_Delay,y.currentDelayMs),de(N,Se.Video_Recv_Firs,y.firsCount),de(N,Se.Video_Recv_Nacks,y.nacksCount),de(N,Se.Video_Recv_Plis,y.plisCount),g){N[Se.Video_Recv_Disabled]=g._originMediaStreamTrack.enabled&&g._mediaStreamTrack.enabled?0:1;const We=g._player;if(We){const{freezeTimeCounterList:M,renderFreezeAccTime:F,renderFreezeAccTime2:J,videoElementStatus:V}=We;if(M&&M.length>0&&de(N,Fi.Video_Render_Freeze_Time,M.splice(0,1)[0]),v&&Vi.visibility==="visible"&&V===Dn.PLAYING&&Oe().supportRequestVideoFrameCallback){const f=Math.min(6e3,J);We.renderFreezeAccTime2=Math.max(0,J-f),de(N,Fi.Video_Render_Freeze_Time_Render2,f);const I=Math.min(6e3,F);We.renderFreezeAccTime=Math.max(0,F-I),de(N,Fi.Video_Render_Freeze_Time_Render,T("USE_NEW_RENDER_FREEZE_TIME")?f:I)}if(typeof y.totalFreezesDuration=="number"){const f=me&&me.totalFreezesDuration?y.totalFreezesDuration-me.totalFreezesDuration:y.totalFreezesDuration;de(N,Se.Video_Render_Freeze_Duration,1e3*f)}}}if(N[Se.Video_Recv_Player_Status]=NS[g._player?g._player.videoElementStatus:"uninit"],me&&y.totalInterFrameDelay!==void 0&&y.totalSquaredInterFrameDelay!==void 0&&me.totalInterFrameDelay!==void 0&&me.totalSquaredInterFrameDelay!==void 0){const We=y.totalInterFrameDelay-me.totalInterFrameDelay,M=y.totalSquaredInterFrameDelay-me.totalSquaredInterFrameDelay,F=y.framesDecodeCount-me.framesDecodeCount,J=We/F*1e3,V=Math.round(1e3*Math.sqrt((M-Math.pow(We,2)/F)/F));!isNaN(V)&&J+V>Math.max(3*J,J+150)&&(N[Se.Video_Recv_I_Frame_Delay]=V)}}return N}(c._videoSSRC,t,c.videoTrack,u===!0,this.needUploadRenderFreezeTime,n,i,r):void 0;if(p&&(l.video=p),c.videoTrack){const E=t.videoRecv.find(m=>m.ssrc===c._videoSSRC);E&&E.estimatedPlayoutTimestamp&&(h=E.estimatedPlayoutTimestamp)}}if(d.has($.AUDIO)&&c.audioTrack){const u=!c.hasAudio,p=c.audioTrack?function(E,m,g,R,v,C){let w=arguments.length>6&&arguments[6]!==void 0&&arguments[6];const b=m.audioRecv.find(U=>U.ssrc===E);if(!b)return;const y={};de(y,Sn.Audio_Recv_Jitter,b.jitterMs),de(y,Sn.Audio_Recv_Bytes_Retransmit,b.retransmittedBytesReceived),de(y,Sn.Audio_Recv_Packages_Retransmit,b.retransmittedPacketsReceived),de(y,Sn.Audio_Recv_Packages_Discarded,b.packetsDiscarded),de(y,Sn.Audio_Recv_Avg_Processing_Delay,b.avgProcessingDelayMs);const N=C&&C.audioRecv.find(U=>U.ssrc===E);if(N){const U=dc;b.packets!=null&&N.packets!=null&&de(y,Sn.Audio_Recv_Package_Rate,1e3*(b.packets-N.packets)/U),b.packetsLost!=null&&N.packetsLost!=null&&de(y,Sn.Audio_Recv_Package_Lost,b.packetsLost-N.packetsLost)}if(R){const{receivedFrames:U,droppedFrames:X}=b;
113U!=null&&X!=null&&(y[Fi.Audio_Recv_Freeze]=(k=U)===0||100*X/k>20?1:0)}var k;if(v){const U=100*g._source.getAccurateVolumeLevel(),X=b.outputLevel;if(X!=null){const se=Math.ceil(50*Math.log10(100*X+1));de(y,Se.Audio_Render_Level,se)}de(y,Se.Audio_Recv_PCM_Level,U),g&&(y[Se.Audio_Recv_Disabled]=g._originMediaStreamTrack.enabled&&g._mediaStreamTrack.enabled?0:1),de(y,Se.Audio_Recv_Jitter_Buffer,b.jitterBufferMs),de(y,Se.Audio_Recv_Current_Delay,b.jitterBufferMs),y[Se.Audio_Recv_Player_Status]=NS[zn.getPlayerState(g.getTrackId())];const q=v.audioRecv.find(se=>se.ssrc===E);if(q&&(q.bytes!=null&&b.bytes!=null&&de(y,Se.Audio_Recv_Bitrate,8*(b.bytes-q.bytes)/(dc*Gu)),!w)){const se=b.concealedSamples-q.concealedSamples;se>0&&de(y,Se.Audio_Recv_Concealed_Samples,se);const _e=b.totalSamplesReceived-q.totalSamplesReceived;_e>0&&de(y,Se.Audio_Recv_Total_Samples_Received,_e);const me=b.freezeSamples80-q.freezeSamples80;me>0&&de(y,Se.Audio_Render_Freeze_Samples_80ms,me);const ke=b.freezeSamples200-q.freezeSamples200;ke>0&&de(y,Se.Audio_Render_Freeze_Samples_200ms,ke);const We=b.freezeMs80-q.freezeMs80;de(y,Se.Audio_Render_Freeze_Time_80ms,We<0?0:We);const M=b.freezeMs200-q.freezeMs200;de(y,Se.Audio_Render_Freeze_Time_200ms,M<0?0:M)}}return y}(c._audioSSRC,t,c.audioTrack,n,i,r,u):void 0;if(p&&(l.audio=p),c.audioTrack&&h){const E=t.audioRecv.find(m=>m.ssrc===c._audioSSRC);if(E&&E.estimatedPlayoutTimestamp){const m=E.estimatedPlayoutTimestamp-h;l.audio?l.audio[Sn.Audio_Recv_AV_Sync_TIME]=m:l.audio={[Sn.Audio_Recv_AV_Sync_TIME]:m}}}}(l.video||l.audio)&&s.push(l)}),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,s}startUploadTransportStats(){this.uploadTransportStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats()}stopUploadTransportStats(){this.uploadTransportStarted=!1}startUploadOutboundStats(){this.uploadOutboundStarted||(this.uploadOutboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=window.setInterval(()=>{if(!this.requestAllTracks||!this.requestUpload)return;const t=(this.requestAllTracks()||[]).find(n=>n instanceof Zl);if(t&&t._external.getDenoiserStats){const n=t._external.getDenoiserStats();n&&this.requestUpload(Ka.DENOISER_STATS,n)}},2e3),this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=window.setInterval(()=>{!this.requestAllTracks||!this.requestUpload||this.requestAllTracks().forEach(t=>
113{t.getProcessorStats().forEach(n=>{this.requestUpload&&this.requestUpload(n.type,n.stats)})})},2e3))}stopUploadOutboundStats(){this.uploadOutboundStarted&&(this.uploadOutboundStarted=!1,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSend=[],this.lastRefSendStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=void 0,this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=void 0)}startUploadInboundStats(){this.uploadInboundStarted||(this.uploadInboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=window.setInterval(()=>{!this.requestUpload||!this.requestRemoteMedia||(this.requestRemoteMedia()||[]).forEach(t=>{let[n,i]=t;i.has($.VIDEO)&&n.videoTrack&&n.videoTrack.getProcessorStats().forEac
113h(r=>{this.requestUpload&&this.requestUpload(r.type,r.stats)}),i.has($.AUDIO)&&n.audioTrack&&n.audioTrack.getProcessorStats().forEach(r=>{this.requestUpload&&this.requestUpload(r.type,r.stats)})})},2e3))}stopUploadInboundStats(){this.uploadInboundStarted&&(this.uploadInboundStarted=!1,this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0,this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=void 0)}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer);const t=new Map;this.uploadExtUsageStatsTimer=window.setInterval(async()=>{const n=Date.now(),i={connectionInterval:T("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:n};let r=[];const o=this.requestAllTracks&&this.requestAllTracks()||[];for(const d of o)!d.muted&&d.enabled&&(r=r.concat(await d.getProcessorUsage()));const s=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const[d,l]of s)l.has($.VIDEO)&&d.videoTrack&&(r=r.concat(await d.videoTrack.getProcessorUsage())),l.has($.AUDIO)&&d.audioTrack&&(r=r.concat(await d.audioTrack.getProcessorUsage()));if(r.length===0)return;i.details=function(d,l){const h={};for(const{id:m,value:g,level:R,direction:v}of d){var u;const C=(u=l.get(m))!==null&&u!==void 0?u:0,w=g===2?C+T("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:C;var p,E;l.set(m,w),h[m]?(g===2&&(h[m].value=g),R>h[m].level&&(h[m].level=R),v==="remote"&&(h[m].remoteUidCount+=1),h[m].totalTs=(p=l.get(m))!==null&&p!==void 0?p:0):h[m]={value:g,level:R,remoteUidCount:v==="local"?0:1,totalTs:(E=l.get(m))!==null&&E!==void 0?E:0}}return Object.keys(h).map(m=>{const{level:g,value:R,totalTs:v}=h[m];return{id:m,level:g,value:R,totalTs:v}})}(r,t);const a=Date.now(),c=a>n?a:n+1;this.requestUpload&&this.requestUpload(Ka.EXTENSION_USAGE_STATS,{usageStats:i,sendTs:c})},T("EXTENSION_USAGE_UPLOAD_INTERVAL"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}stopUploadBaseStats(){this.uploadBaseStatsStarted=!1,Vi.stopCollectStats()}}const kee=T("ICE_RESTART_INTERVAL");let Am=new Map,Jd=new Map,ia=[gn.UDP_TCP_RELAY,gn.TCP_RELAY,gn.RELAY],Pv=T("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&Oe().supportPCSetConfiguration;function _2(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const n=Am.get(e.id);n&&(window.clearTimeout(n),Am.delete(e.id));const i=Jd.get(e.id);t&&i&&i.index===ia.length-1&&(_.debug("[".concat(e.id,"] reset ICE restart policy")),Jd.delete(e.id))}function m2(e,t,n){if(Am.size===0&&Jd.size===0&&(Array.isArray(T("RESTART_SEQUENCE"))&&T("RESTART_SEQUENCE").length>0&&!function(a,c){if(a.length!==c.length)return!1;for(let d=0;d<a.length;d+=1){const l=a[d];if(a.filter(h=>h===l).length!==c.filter(h=>h===l).length)return!1}return!0}(ia,T("RESTART_SEQUENCE"))&&(ia=T("RESTART_SEQUENCE").filter(a=>{var c;if(x(c=Object.values(gn)).call(c,a))return!0}),_.debug("use reconnection policy from config distribution, queues: ".concat(ia.join(" => ")))),Pv=T("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&Oe().supportPCSetConfiguration),ia.length===0)return void n();let i,{index:r=0,type:o}=Jd.get(e.id)||{};if(Pv&&o===gn.RELAY)return void n();let s=o&&r>=ia.length-1;if(Pv)o=gn.RELAY;else{if(s)return void n();o?(r++,o=ia[r]):(o=ia[0],r=0)}_.debug("[".concat(e.id,"] choose ICE restart policy: ").concat(o,", index: ").concat(r)),t(o),Jd.set(e.id,{index:r,type:o}),i=window.setTimeout(()=>m2(e,t,n),kee),Am.set(e.id,i)}var De;function E2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Jo(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
113t%2?E2(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):E2(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function f2(e){var t,n,i,r=2;for(typeof Symbol<"u"&&(n=lp,i=Symbol.iterator);r--;){if(n&&(t=e[n])!=null)return t.call(e);if(i&&(t=e[i])!=null)return new Cm(t.call(e));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}function Cm(e){function t(n){if(Object(n)!==n)return K.reject(new TypeError(n+" is not an object."));var i=n.done;return K.resolve(n.value).then(function(r){return{value:r,done:i}})}return Cm=function(n){this.s=n,this.n=n.next},Cm.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(n){var i=this.s.return;return i===void 0?K.resolve({value:n,done:!0}):t(i.apply(this.s,arguments))},throw:function(n){var i=this.s.return;return i===void 0?K.reject(n):t(i.apply(this.s,arguments))}},new Cm(e)}let lc=(De=class extends Nt{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(ae.StateChange,t,this._state)}constructor(e,t){super(),S(this,"isPlanB",void 0),S(this,"store",void 0),S(this,"statsUploader",void 0),S(this,"connection",void 0),S(this,"localTrackMap",new Map),S(this,"remoteUserMap",new Map),S(this,"localDataChannels",[]),S(this,"remoteDataChannelMap",new Map),S(this,"pendingLocalTracks",[]),S(this,"pendingRemoteTracks",[]),S(this,"pendingLocalDataChannels",[]),S(this,"pendingRemoteDataChannels",[]),S(this,"statsCollector",void 0),S(this,"shouldForwardP2PCreation",void 0),S(this,"iceFailedCount",0),S(this,"dtlsFailedCount",0),S(this,"mutex",void 0),S(this,"_state",qe.Disconnected),S(this,"_p2pBySDPEndPoint",!1),S(this,"_pcStatsUploadType",T("NEW_ICE_RESTART")?ls.FIRST_CONNECTION:ls.OLD_FIRST_CONNECTION),S(this,"_isStartRestartIce",!1),S(this,"_restartTimer",void 0),S(this,"_isTryConnecting",!1),S(this,"_iceError",null),S(this,"_forceTurn",!1),S(this,"_isWaitPcToRePub",!1),S(this,"handleMuteLocalTrack",async(n,i,r)=>{const o=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==qe.Connected)return void r(new L(A.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const s=this.filterTobeMutedTracks(n);if(s.length===0)return void i();const a=s.find(d=>d[0]==="videoLowTrack");if(a){const d=a[1];this.store.enableInstantMuteRestore?(d.track._originMediaStreamTrack.enabled=!1,_.info("[".concat(this.store.clientId,"] P2PChannel muteLocalLowTrack without close sender because enableInstantMuteRestore is true"))):d.track._originMediaStreamTrack.stop()}this.store.enableInstantMuteRestore?_.info("[".concat(this.store.clientId,"] P2PChannel muteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.muteLocal(s.map(d=>{let[,{id:l}]=d;return l}));const c=this.createMuteMessage(s);await mt(this,ae.RequestMuteLocal,c),i()}catch(s){r(s)}finally{o()}}),S(this,"handleUnmuteLocalTrack",async(n,i,r)=>{const o=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==qe.Connected)return void r(new L(A.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const s=this.filterTobeUnmutedTracks(n);if(s.length===0)return void i();const a=s.find(d=>d[0]==="videoLowTrack");if(a){const d=a[1];if(this.store.enableInstantMuteRestore)d.track._originMediaStreamTrack.enabled=!0,_.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalLowTrack without close sender because enableInstantMuteRestore is true"));else{if(d.track._originMediaStreamTrack.stop(),!T("DISABLE_DUAL_STREAM_USE_ENCODING")&&Oe().supportDualStreamEncoding){const l=n._mediaStreamTrack.clone();d.track._mediaStreamTrack=l,d.track._originMediaStreamTrack=l}else{const l=Nv(n,Na(this,ae.RequestLowStreamParameter));d.track._mediaStreamTrack=l,d.track._originMediaStreamTrack=l}await new K((l,h)=>{this.handleReplaceTrack(d.track,l,h,!0)})}}this.store.enableInstantMuteRestore?_.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalTrack without close sender be
113cause enableInstantMuteRestore is true")):await this.connection.unmuteLocal(s.map(d=>{let[,{id:l}]=d;return l}));const c=this.createUnmuteMessage(s);await mt(this,ae.RequestUnmuteLocal,c),i()}catch(s){r(s)}finally{o()}}),S(this,"handleUpdateVideoEncoder",async(n,i,r,o)=>{let s;o||(s=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoEncoder"));try{const c=this.localTrackMap.get(G.LocalVideoTrack);if(!this.connection||!c||c.track!==n||this.state!==qe.Connected)return void i();const{id:d,track:l}=c;await this.connection.updateSendParameters(d,l),await this.connection.updateEncoderConfig(d,l),this.emit(ae.UpdateVideoEncoder,l),i()}catch(c){r(c)}finally{var a;(a=s)===null||a===void 0||a()}}),S(this,"handleUpdateVideoSendParameters",async(n,i,r)=>{const o=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoSendParameters");try{const s=this.localTrackMap.get(G.LocalVideoTrack);if(!this.connection||!s||s.track!==n||this.state!==qe.Connected)return void i();const{id:a,track:c}=s;await this.connection.updateSendParameters(a,c),i()}catch(s){r(s)}finally{o()}}),S(this,"handleReplaceMixingTrack",async(n,i,r,o)=>{if(!this.connection||this.state!==qe.Connected)return void i();const s=bv([n]);let a;_.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(s.getTrackId(),"]")),typeof o=="boolean"&&o||(a=await this.mutex.lock("From P2PChannel.handleReplaceMixingTrack"));try{await this.replaceTrack(n,s),i()}catch(d){r(d)}finally{var c;(c=a)===null||c===void 0||c()}}),S(this,"handleReplaceTrack",async(n,i,r,o)=>{let s;_.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(n.getTrackId(),"]")),typeof o=="boolean"&&o||(s=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var a;const d=Array.from(this.localTrackMap.entries()).find(l=>{let[,{track:h}]=l;return n===h});if(!this.connection||!d||this.state!==qe.Connected)return void i();if(await((a=this.connection)===null||a===void 0?void 0:a.replaceTrack(n,d[1].id)),this.isPlanB){const l=d[1];l.id=n._mediaStreamTrack.id,this.localTrackMap.set(d[0],l)}if(d[0]===G.LocalVideoTrack&&!T("DISABLE_DUAL_STREAM_USE_ENCODING")&&Oe().supportDualStreamEncoding){const l=this.localTrackMap.get(G.LocalVideoLowTrack);if(l){const h=n._mediaStreamTrack.clone();l.track._originMediaStreamTrack.stop(),l.track._mediaStreamTrack=h,l.track._originMediaStreamTrack=h,await new K((u,p)=>{this.handleReplaceTrack(l.track,u,p,!0)})}}i()}catch(d){r(d)}finally{var c;(c=s)===null||c===void 0||c()}}),S(this,"handleGetRTCStats",n=>{n(this.statsCollector.getRTCStats())}),S(this,"handleGetLocalVideoStats",n=>{n(this.statsCollector.getLocalVideoTrackStats())}),S(this,"handleGetLocalAudioStats",n=>{n(this.statsCollector.getLocalAudioTrackStats())}),S(this,"handleGetRemoteVideoStats",n=>this.statsCollector.getRemoteVideoTrackStats(n.uid)[n.uid]),S(this,"handleGetRemoteAudioStats",n=>this.statsCollector.getRemoteAudioTrackStats(n.uid)[n.uid]),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new p2(this.store),this.bindStatsUploaderEvents(),this.mutex=new An("P2PChannel-mutex",this.store.clientId),this.isPlanB=!Oe().supportUnifiedPlan||T("CHROME_FORCE_PLAN_B")&&Po(),this.shouldForwardP2PCreation=T("FORWARD_P2P_CREATION")&&Oe().supportPCSetConfiguration&&_O(),this.shouldForwardP2PCreation&&this.recreateConnection()}async startP2PConnection(e,t){var n;this.state=qe.New,this._forceTurn=Ov(e),_.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] forceTurn: ").concat(this._forceTurn));const i=this.shouldForwardP2PCreation&&((n=this.connection)===null||n===void 0?void 0:n.peerConnectionState)==="closed";if((!this.shouldForwardP2PCreation||i||t)&&((i||t)&&this.connection&&(_.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.resetConnection(this.connection)),this.recreateConnection(e)),!this.connection)throw new L(A.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=T("NEW_ICE_RESTART")?ls.FIRST_CONNECTION:ls.OLD_FIRST_CONNECTION,this._isTryConnecting=!0,this._isStartRestartIce=!1,this._iceError=null,this.connection.setConfiguration(e),this.connection.establishPromise}updateConnectionConfiguration(e){var t;(t=this.connection)===null||t===void 0||t.setConfiguration(e),this._p2pBySDPEndPoint=!0}async connect(e){if(!this.connection)throw new L(A.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");if(!this.isPreallocation()||this.state!==qe.Connected){this.store.peerConnectionStart();const t=await this.connection.connect(e);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=qe.Connected,t}if(this.connection instanceof xi||this.connection&&"name"in this.connection&&this.connection.name==="DataChannelConnection"){const t=this.connection.checkDtlsParameters(e.dtlsParameters.fingerprints),n=uv(e.iceParameters.iceUfrag,e.iceParameters.icePwd);n||_.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] ice parameters mismatch, length: ").concat(e.iceParameters.iceUfrag.length," / ").concat(e.iceParameters.icePwd.length));const i=this.connection.checkIceParameters(e.iceParameters),r=t||!n||i&&!(this.connection instanceof xi);(r||i)&&(_.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] dtls parameters mismatch, ").concat(r?"try next":"restart ICE")),Z.reportApiInvoke(this.store.sessionId,{name:t?vt.MISMATCH_DTLS_PARAMETERS:vt.MISMATCH_ICE_PARAMETERS,options:t?[e.dtlsParameters.fingerprints]:[e.iceParameters],tag:ht.TRACER}).onSuccess(),setTimeout(()=>
113{r?this.emit(ae.RequestReconnect):i&&this.emit(ae.RequestRestartICE,gn.UDP_RELAY)}))}await this.connection.updateRemoteConnect(e)}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter(r=>{var o;let[s]=r;return x(o=[G.LocalVideoLowTrack,G.LocalVideoTrack]).call(o,s)}),n=t.map(r=>{let[,{id:o}]=r;return o}),i=t.map(r=>{let[o]=r;return o});if(this.connection instanceof xi||this.connection&&"name"in this.connection&&this.connection.name==="DataChannelConnection"){if(Z.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(i),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!x(e).call(e,this.store.codec)){const r=["vp9","vp8","h264"].find(o=>x(e).call(e,o));r&&(this.store.codec=r,_.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default codec is not available, hence the fallback to ").concat(r,".")))}this.connection.updateRemoteRTPCapabilities(n,e)}}async getEstablishParams(){var e;return this.connection&&"name"in this.connection&&this.connection.name==="DataChannelConnection"&&this.connection.peerConnectionState!=="closed"||this.connection instanceof xi&&this.connection.peerConnectionState!=="closed"&&x(e=[qe.New,qe.Connected]).call(e,this.state)?this.connection.establishPromise:void 0}async publishDataChannel(e){if(!this.connection||this.state!==qe.Connected){if(this.state===qe.Disconnected)throw new L(A.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return e.forEach(n=>{var i;x(i=this.pendingLocalDataChannels).call(i,n)||this.pendingLocalDataChannels.push(n)}),[]}const t=this.filterTobePublishedDataChannels(e);return t.length===0?[]:(t.forEach(n=>{const i=Date.now();this.store.publish(n.id.toString(),"datachannel",i)}),await this.connection.createDataChannels(this.store.uid,t),t.forEach(n=>{this.localDataChannels.push(n);const i=Date.now();this.store.publish(n.id+"","datachannel",void 0,i)}),e.map(n=>({streamId:n.id,ordered:n.ordered,maxRetransmits:n.maxRetransmits,metadata:n.metadata,channelId:n._originDataChannelId})))}publish(e,t,n){var i=this;return di(function*(){const r=yield ve(i.mutex.lock("From P2PChannel.publish"));try{var o;const s=i.connection&&x(o=["disconnected","failed"]).call(o,i.connection.peerConnectionState);if(!i.connection||i.state!==qe.Connected||s){if(i.state===qe.Disconnected)throw new L(A.UNEXPECTED_ERROR,"PeerConnection already disconnected.");i.throwIfTrackTypeNotMatch(e);const c=e.filter(d=>i.pendingLocalTracks.indexOf(d)===-1);return i.pendingLocalTracks=i.pendingLocalTracks.concat(c),void(s&&(i._isWaitPcToRePub=!0))}i.store.pubId=i.store.pubId+1,jn.markPublishStart(i.store.clientId,i.store.pubId);const a=i.filterTobePublishedTracks(e,t,n);if(a.length===0)return void(yield ve(i.tryToUnmuteAudio(e)));yield*$c(f2(i.doPublish(i.connection,a)))}finally{r()}})()}doPublish(e,t){var n=this;return di(function*(){t.forEach(u=>{let{track:p,type:E}=u;const m=Date.now();n.store.publish(p.getTrackId(),E===G.LocalAudioTrack?"audio":"video",m)}),n.bindLocalTrackEvents(t);const i=t.map(u=>{let{track:p}=u;return p}),r=yield ve(e.send(i,n.store.codec,n.store.audioCodec)),o=(yield ve(r.next())).value,s=n.createGatewayPublishMessage(t,o);let a;try{a=yield s}catch(u){throw r.throw(u),(u==null?void 0:u.code)===A.WS_ABORT&&t.forEach(p=>{let{track:E}=p;n.pendingLocalTracks.indexOf(E)===-1&&n.pendingLocalTracks.push(E)}),n.unbindLocalTrackEvents(t),u}const c=n.mapPubResToRemoteConfig(s,a,i),d=(yield ve(r.next(c))).value;if(n.state===qe.Disconnected)throw new L(A.UNEXPECTED_ERROR,"PeerConnection already disconnected.");T("ENABLE_VIDEO_SEI");const l=T("ENABLE_ENCODED_TRANSFORM"),h=T("ENABLE_AUDIO_METADATA");i.forEach(async u=>{const p=u.getRTCRtpTransceiver();if(!p||!l)return;const{interceptLocalVideoFrame:E,interceptLocalAudioFrame:m}=um();u.trackMediaType===$.VIDEO?await E(p.sender,u):u.trackMediaType===$.AUDIO&&await m(p.sender,{metadata:h?()=>{const g=u.metadata.shift();return g&&g.value}:void 0})}),t.forEach(u=>{let{type:p}=u;n.statsCollector.addLocalStats(p)}),n.assignLocalTracks(t,d),n.statsUploader.startUploadOutboundStats(),t.forEach(u=>{let{track:p,type:E}=u;const m=Date.now();n.store.publish(p.getTrackId(),E===G.LocalAudioTrack?"audio":"video",void 0,m)})})()}async updateVideoStreamParameter(e,t){const n=this.localTrackMap.get(t);if(!n||!this.connection)return;if(!(n.track instanceof pt))return _.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");const{track:i}=n,r=function(o,s){const a={};return o.height&&o.width&&(a.scaleResolutionDownBy=ov(o,s)),a.maxFramerate=o.framerate?mi(o.framerate):void 0,a.maxBitrate=o.bitrate?1e3*o.bitrate:void 0,a}(e,i);if(i._encoderConfig||(i._encoderConfig={}),t!==G.LocalVideoLowTrack||!T("DISABLE_DUAL_STREAM_USE_ENCODING")&&Oe().supportDualStreamEncoding)r.scaleResolutionDownBy!=null&&(i._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else{const o=i._originMediaStreamTrack;if(!o.canvas)return _.warn("[".concat(i.getTrackId(),"] no canvas on track"));(function(s,a){const c=s.canvas;a.width&&(c.width=mi(a.width)),a.height&&(c.height=mi(a.height)),a.framerate&&(c.stopCapture&&c.stopCapture(),c.stopCapture=LS(()=>{!c.startCapture&&c.stopCapture&&c.stopCapture(),c.startCapture&&c.startCapture()},mi(a.framerate)))})(o,e)}r.maxBitrate!=null&&(i._encoderConfig.bitrateMax=r.maxBitrate/1e3),r.maxFramerate!=null&&(i._encoderConfig.frameRate&&typeof i._encoderConfig.frameRate=="object"?i._encoderConfig.frameRate.max=r.maxFramerate:i._encoderConfig.frameRate={max:r.maxFramerate}),_.debug("[".concat(i.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(i._encoderConfig))),await this.connection.updateRtpSenderEncodings(i)}publishLowStream(e){var t=this;return di(function*(){if(!t.connection||t.state!==qe.Connected)return;const n=yield ve(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=t.localTrackMap.get(G.LocalVideoTrack);if(!r)throw new L(A.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(G.LocalVideoLowTrack))throw new L(A.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const o=[{track:t.getLowVideoTrack(r.track,e),type:G.LocalVideoLowTrack}];if(yield*$c(f2(t.doPublish(t.connection,o))),r.track.muted||!r.track.enabled){var i;const s=(i=t.localTrackMap.get(G.LocalVideoLowTrack))===null||i===void 0?void 0:i.id;s!==void 0&&(yield ve(t.connection.muteLocal([s])))}}finally{n()}})()}async republish(){this.pendingLocalTracks.length>0&&(_.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await Jt(this,ae.RequestRePublish,this.pendingLocalTracks),this.emit
113(ae.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(_.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await Jt(this,ae.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[]),this._isWaitPcToRePub=!1}async reSubscribe(e){for(let t=this.pendingRemoteTracks.length-1;t>=0;t--){const{user:n,kind:i}=this.pendingRemoteTracks[t];(i!==$.AUDIO||n._audio_added_&&n._audioSSRC)&&(i!==$.VIDEO||n._video_added_&&n._videoSSRC)||this.pendingRemoteTracks.splice(t,1)}if(e)await Jt(this,ae.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:t,kind:n}of this.pendingRemoteTracks)await this.subscribe(t,n,n===$.VIDEO?t._videoSSRC:t._audioSSRC);this.pendingRemoteTracks.forEach(t=>{let{user:n}=t;this.emit(ae.MediaReconnectEnd,n.uid)}),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==qe.Connected)return void e.forEach(i=>{const r=this.pendingLocalTracks.indexOf(i);r!==-1&&this.pendingLocalTracks.splice(r,1)});const t=this.filterTobeUnpublishedTracks(e);if(t.length===0)return;const n=t.find(i=>i[0]==="videoLowTrack");return n&&n[1].track.close(),this.doUnpublish(this.connection,t)}async unpublishDataChannel(e){if(!this.connection||this.state!==qe.Connected)return void e.forEach(n=>{const i=this.pendingLocalDataChannels.indexOf(n);i!==-1&&this.pendingLocalDataChannels.splice(i,1)});const t=this.filterTobeUnpublishedDataChannels(e);return t.length!==0?(t.forEach(n=>{const i=this.localDataChannels.indexOf(n);i!==-1&&this.localDataChannels.splice(i,1)}),this.localDataChannels.length===0&&await this.connection.stopD
113ataChannels(this.store.uid),t.map(n=>n.id)):void 0}async unpublishLowStream(){if(!this.connection||this.state!==qe.Connected)return;const e=this.localTrackMap.get(G.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[G.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){const n=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map(i=>{let[,{id:r}]=i;return r})),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map(i=>{let[r,{track:o}]=i;return{type:r,track:o}})),t.forEach(i=>{let[r]=i;this.statsCollector.removeLocalStats(r)}),this.localTrackMap.size===0&&this.statsUploader.stopUploadOutboundStats(),n}async subscribeDataChannel(e,t){if(!this.connection||this.state!==qe.Connected)throw new L(A.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const n=t.filter(i=>{var r;return!((r=this.remoteDataChannelMap.get(e))!==null&&r!==void 0&&r.get(i.id))});if(n.length!==0)return await this.connection.createDataChannels(e.uid,n),n.forEach(i=>{var r;this.remoteDataChannelMap.has(e)?(r=this.remoteDataChannelMap.get(e))===null||r===void 0||r.set(i.id,i):this.remoteDataChannelMap.set(e,new Map([[i.id,i]]));const o=this.pendingRemoteDataChannels.findIndex(s=>{let{user:a,id:c}=s;return a.uid===e.uid&&c===i.id});o!==-1&&this.pendingRemoteDataChannels.splice(o,1)}),n.map(i=>i.id)}async subscribe(e,t,n,i,r){var o;if(!this.connection||this.state!==qe.Connected)throw new L(A.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if((o=this.remoteUserMap.get(e))!==null&&o!==void 0&&o.has(t))return;let s,a,c,d;const l=this.connection.getPreMedia(n);if(l)_.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] preSSRCMap has ssrcId: ").concat(n,", no need to send sub to gateway.")),c=l.transceiver,s=l.track,a=l.mid,d=l.player,l.firstVideoRender&&this.store.firstVideoFrameDecoded(e.uid,{firstPreRender:l.firstVideoRender});else if(r){const p=r.find(m=>{let{stream_type:g}=m;return g===t});if(!p)throw new L(A.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(t," for user: ").concat(e.uid," because subscribe answer from gateway does not contain stream_type: ").concat(t,"."));const E=await this.connection.receive(t,p.ssrcs,String(e._uintid),p.attributes);(this.connection instanceof xi||"name"in this.connection&&this.connection.name==="DataChannelConnection")&&(c=E.transceiver),s=E.track,a=E.id}else{const p=await this.connection.receive(t,[{ssrcId:n,rtx:i}],String(e._uintid),void 0);(this.connection instanceof xi||"name"in this.connection&&this.connection.name==="DataChannelConnection")&&(c=p.transceiver),s=p.track,a=p.id}if(t===$.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new Ed(s,e.uid,e._uintid,this.store),_.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new md(s,e.uid,e._uintid,this.store,d),_.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId())),e._videoTrack.once(pr.PLAY_START,()=>{this.store.firstVideoFrameDecoded(e.uid,{playStart:Date.now()})}),e._videoTrack.once(pr.PLAY_END,()=>{this.store.firstVideoFrameDecoded(e.uid,{playEnd:Date.now()}),this.reportVideoFirstFrameRender(e)}),d?e._videoTrack.once(pr.FIRST_FRAME_RENDER,()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)}):e._videoTrack.once(pr.FIRST_FRAME_DECODED,()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)})),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),c&&T("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:p,interceptRemoteAudioFrame:E}=um();t==$.VIDEO?await p(c.receiver,{onSei:T("ENABLE_VIDEO_SEI")&&(m=>{var g;return(g=e._videoTrack)===null||g===void 0?void 0:g._onSei(m)}),onFirstFrame:m=>{var g;const R=Array.from(_n(g=this.remoteUserMap).call(g)).find(v=>v._videoSSRC===m.ssrc);R&&this.store.firstVideoFrameDecoded(R.uid,{firstReceivedEncodedFrame:Date.now(),frameType:m.type,rtpTimestamp:m.rtpTimestamp,framePayloadType:m.payloadType,frameDataLength:m.length,mimeType:m.mimeType})}}):t==$.AUDIO&&await E(c.receiver,{enableTopn:!!T("ENABLE_AUDIO_TOPN"),enableMetadata:!!T("ENABLE_AUDIO_METADATA"),enablePts:!!T("ENABLE_AUDIO_PTS"),onMetadata:m=>{this.safeEmit(ae.AudioMetadata,m)},onPts:m=>{this.safeEmit(ae.AudioPts,m)}})}const h=this.remoteUserMap.get(e);h?h.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const u=this.pendingRemoteTracks.findIndex(p=>{let{user:E,kind:m}=p;return E.uid===e.uid&&t===m});
113u!==-1&&(this.pendingRemoteTracks.splice(u,1),this.emit(ae.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==qe.Connected)throw new L(A.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter(r=>{var o;let{user:s,mediaType:a}=r;return!((o=this.remoteUserMap.get(s))!==null&&o!==void 0&&o.has(a))});const t=[],n=new Map;e.forEach(r=>{if(!this.connection)return;const o=this.connection.getPreMedia(r.ssrcId);if(o){const{track:s,mid:a,transceiver:c,player:d}=o;n.set(r.ssrcId,{track:s,id:a,transceiver:c,player:d})}else t.push(r)});const i=await this.connection.batchReceive(t.map(r=>{let{user:o,mediaType:s,ssrcId:a,rtxSsrcId:c}=r;return{kind:s,ssrcMsg:[{ssrcId:a,rtx:c}],mslabel:String(o._uintid)}}));t.forEach((r,o)=>{n.set(r.ssrcId,i[o])});for(const{user:r,mediaType:o,ssrcId:s}of e){const a=n.get(s);if(!a)return void _.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] cannot find ").concat(r.uid," subscribe data,").concat(o,", ").concat(s));const{track:c,id:d,transceiver:l,player:h}=a;if(l&&T("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:E,interceptRemoteAudioFrame:m}=um();o==$.VIDEO?await E(l.receiver,{onSei:T("ENABLE_VIDEO_SEI")&&(g=>{var R;return(R=r._videoTrack)===null||R===void 0?void 0:R._onSei(g)}),onFirstFrame:g=>{var R;const v=Array.from(_n(R=this.remoteUserMap).call(R)).find(C=>C._videoSSRC===g.ssrc);v&&this.store.firstVideoFrameDecoded(v.uid,{firstReceivedEncodedFrame:Date.now(),frameType:g.type,rtpTimestamp:g.rtpTimestamp,framePayloadType:g.payloadType,frameDataLength:g.length,mimeType:g.mimeType})}}):o==$.AUDIO&&await m(l.receiver,{enableTopn:!!T("ENABLE_AUDIO_TOPN"),enableMetadata:!!T("ENABLE_AUDIO_METADATA"),enablePts:!!T("ENABLE_AUDIO_PTS"),onMetadata:g=>{this.safeEmit(ae.AudioMetadata,g)},onPts:g=>{this.safeEmit(ae.AudioPts,g)}})}if(o===$.AUDIO?(r._audioTrack?r._audioTrack._updateOriginMediaStreamTrack(c):(r._audioTrack=new Ed(c,r.uid,r._uintid,this.store),_.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(r._audioTrack.getTrackId()))),l&&r._audioTrack._updateRtpTransceiver(l),this.bindRemoteTrackEvents(r,r._audioTrack)):(r._videoTrack?r._videoTrack._updateOriginMediaStreamTrack(c):(r._videoTrack=new md(c,r.uid,r._uintid,this.store,h),_.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(r._videoTrack.getTrackId()))),l&&r._videoTrack._updateRtpTransceiver(l),this.bindRemoteTrackEvents(r,r._videoTrack)),T("ENABLE_VIDEO_SEI")&&l){const{interceptRemoteVideoFrame:E,interceptRemoteAudioFrame:m}=um();o==$.VIDEO?await E(l.receiver,{onSei:g=>{var R;(R=r._videoTrack)===null||R===void 0||R._onSei(g)},onFirstFrame:g=>{var R;const v=Array.from(_n(R=this.remoteUserMap).call(R)).find(C=>C._videoSSRC===g.ssrc);v&&this.store.firstVideoFrameDecoded(v.uid,{firstReceivedEncodedFrame:Date.now(),frameType:g.type,rtpTimestamp:g.rtpTimestamp,framePayloadType:g.payloadType,frameDataLength:g.length,mimeType:g.mimeType})}}):o==$.AUDIO&&await m(l.receiver)}const u=this.remoteUserMap.get(r);u?u.set(o,d):this.remoteUserMap.set(r,new Map([[o,d]])),this.statsCollector.addRemoteStats(r.uid),this.statsUploader.startUploadInboundStats();const p=this.pendingRemoteTracks.findIndex(E=>{let{user:m,kind:g}=E;return m.uid===r.uid&&o===g});p!==-1&&(this.pendingRemoteTracks.splice(p,1),this.emit(ae.MediaReconnectEnd,r.uid))}}async unsubscribe(e,t,n){const i=this.pendingRemoteTracks.filter(s=>{let{user:a,kind:c}=s;return t!==void 0?a.uid===e.uid&&t===c:a.uid===e.uid});if(i.forEach(s=>{const a=this.pendingRemoteTracks.indexOf(s);this.pendingRemoteTracks.splice(a,1)}),this.connection&&this.state===qe.Connected||n||i.forEach(s=>{let{kind:a}=s;var c;if(a===$.AUDIO)(c=e._audioTrack)===null||c===void 0||c._destroy(),e._audioTrack=void 0;else if(a===$.VIDEO){var d;(d=e._videoTrack)===null||d===void 0||d._destroy(),e._videoTrack=void 0}}),!this.connection||this.state!==qe.Connected)return;const r=this.filterTobeUnSubscribedTracks(e,t);if(r.length===0)return;await this.connection.stopReceiving(r.map(s=>{let[,{id:a}]=s;return a}));const o=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),this.remoteUserMap.size===0&&this.statsUploader.stopUploadInboundStats(),r.forEach(s=>{let[a,{kind:c}]=s;var d,l;if(c===$.VIDEO&&a._videoSSRC&&((d=this.connection)===null||d===void 0||d.setStatsRemoteVideoIsReady(a._videoSSRC,
113!1)),c===$.VIDEO)this.unbindRemoteTrackEvents(a._videoTrack),n||((l=a._videoTrack)===null||l===void 0||l._destroy(),a._videoTrack=void 0);else if(c===$.AUDIO){var h;this.unbindRemoteTrackEvents(a._audioTrack),!n&&((h=a._audioTrack)===null||h===void 0||h._destroy(),a._audioTrack=void 0)}}),o}async unsubscribeDataChannel(e,t){if(t.forEach(r=>{const o=this.pendingRemoteDataChannels.findIndex(s=>s.id===r.id);o!==-1&&this.pendingRemoteDataChannels.splice(o,1)}),!this.connection)return;const n=this.filterTobeUnSubscribedDataChannels(e,t);if(n.length===0)return;t.forEach(r=>{r._close()});const i=this.remoteDataChannelMap.get(e);return n.forEach(r=>{i&&i.delete(r.id)}),i&&i.size===0&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),n.map(r=>r.id)}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(const{user:r,mediaType:o}of e){const s=this.pendingRemoteTracks.filter(a=>{let{user:c,kind:d}=a;return o!==void 0?c.uid===r.uid&&o===d:c.uid===r.uid});s.forEach(a=>{const c=this.pendingRemoteTracks.indexOf(a);this.pendingRemoteTracks.splice(c,1)}),t=t.concat(s)}if(!this.connection||this.state!==qe.Connected)return void t.forEach(r=>{let{user:o,kind:s}=r;var a;if(s===$.AUDIO)(a=o._audioTrack)===null||a===void 0||a._destroy(),o._audioTrack=void 0;else if(s===$.VIDEO){var c;(c=o._videoTrack)===null||c===void 0||c._destroy(),o._videoTrack=void 0}});const n=ei(e).call(e,(r,o)=>{let{user:s,mediaType:a}=o;const c=this.filterTobeUnSubscribedTracks(s,a);return r.concat(c)},[]);if(n.length===0)return;await this.connection.stopReceiving(n.map(r=>{let[,{id:o}]=r;return o}));const i=this.createUnsubscribeAllMessage(n);return this.withdrawRemoteTracks(n),this.remoteUserMap.size===0&&this.statsUploader.stopUploadInboundStats(),n.forEac
113h(r=>{let[o,{kind:s}]=r;var a,c;if(s===$.VIDEO&&o._videoSSRC&&((a=this.connection)===null||a===void 0||a.setStatsRemoteVideoIsReady(o._videoSSRC,!1)),s===$.VIDEO)this.unbindRemoteTrackEvents(o._videoTrack),(c=o._videoTrack)===null||c===void 0||c._destroy(),o._videoTrack=void 0;else if(s===$.AUDIO){var d;this.unbindRemoteTrackEvents(o._audioTrack),(d=o._audioTrack)===null||d===void 0||d._destroy(),o._audioTrack=void 0}}),i}isPreSubScribe(e){return!this.connection||this.state!==qe.Connected?!1:!!this.connection.getPreMedia(e)}async muteRemote(e,t){if(!this.connection)return;const n=this.remoteUserMap.get(e);if(!n)return void _.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!n.get(t))return void _.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const i=t===$.VIDEO?e._videoSSRC:e._audioSSRC;i!==void 0&&this.connection.setStatsRemoteVideoIsReady(i,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const n=this.remoteUserMap.get(e);if(!n)return void _.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));n.get(t)||_.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}addAudioMetadata(e){const t=this.localTrackMap.get(G.LocalAudioTrack),n=t&&t.track;n&&n.metadata.push(e)}getAllTracks(e){const t=this.localTrackMap.get(G.LocalAudioTrack);if((t==null?void 0:t.track)instanceof En){const n=t.track;return Array.from(this.localTrackMap.entries()).filter(i=>{let[r]=i;return r!==G.LocalAudioTrack}).filter(i=>{let[r]=i;return!(e&&r===G.LocalVideoLowTrack)}).map(i=>{let[,{track:r}]=i;return r}).concat(n.trackList)}return Array.from(this.localTrackMap.entries()).filter(n=>{let[i]=n;return!(e&&i===G.LocalVideoLowTrack)}).map(n=>{let[,{track:i}]=n;return i})}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(e,t,n,i,r){if(e){const s=this.localTrackMap.get(G.LocalAudioTrack),a=i?this.localTrackMap.get(G.LocalVideoLowTrack):this.localTrackMap.get(G.LocalVideoTrack);Z.publish(this.store.sessionId,{eventElapse:jn.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:s==null?void 0:s.track.getTrackLabel(),videoName:a==null?void 0:a.track.getTrackLabel(),screenshare:(a==null?void 0:a.track._hints.indexOf($e.SCREEN_TRACK))!==-1,audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;n||(n=[]);const s=n.find(c=>c instanceof jt),a=i?(o=this.localTrackMap.get(G.LocalVideoTrack))===null||o===void 0?void 0:o.track:n.find(c=>c instanceof pt);Z.publish(this.store.sessionId,{eventElapse:jn.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:s==null?void 0:s.getTrackLabel(),videoName:a==null?void 0:a.getTrackLabel(),screenshare:(a==null?void 0:a._hints.indexOf($e.SCREEN_TRACK))!==-1,audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,n,i){const r=i===$.VIDEO?n._videoSSRC:n._audioSSRC;r&&Z.subscribe(this.store.sessionId,{succ:e,ec:t,video:i===$.VIDEO,audio:i===$.AUDIO,peerid:n.uid,subscribeRequestid:r,p2pid:this.store.p2pId,eventElapse:jn.measureFromSubscribeStart(this.store.clientId,r),preSsrc:this.isPreSubScribe(r)})}reset(){_.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new An("P2PChannel-mutex",this.store.clientId),this.connection&&(this.resetConnection(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&this.recreateConnection(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.statsUploader.stopUploadBaseStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(G.LocalAudioTrack);if((e==null?void 0:e.track)instanceof En){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach(n=>{t.removeAudioTrack(n)})}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.iceFailedCount=0,this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.localDataChannels=[],this.remoteDataChannelMap.clear(),this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.state=qe.Disconnected}getStats(){var e;return(e=this.connection)===null||e===void 0?void 0:e.getStats()}getRemoteVideoIsReady(e){var t;return((t=this.connection)===null||t===void 0?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(G.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(G.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof pt||t&&t.track instanceof jt?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}getRemoteMedia(e){var t;const n=Array.from(_n(t=this.remoteUserMap).call(t)).find(i=>i.uid===e);return n?{audioTrack:n.audioTrack,audioSSRC:n._audioSSRC,videoTrack:n.videoTrack,videoSSRC:n._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map(n=>{let[i]=n;return{uid:i.uid,level:i.audioTrack?100*i.audioTrack._source.getAccurateVolumeLevel():0}});const t=this.localTrackMap.get(G.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=Pi(e).call(e,(n,i)=>n.level-i.level),e}async disconnectForReconnect(){this.connection&&(_.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=qe.Reconnecting,T("KEEP_LAST_FRAME")&&this.remoteUserMap.size!==0&&Array.from(this.remoteUserMap.entries()).forEac
113h(e=>{let[t]=e;var n;t._videoTrack&&t._videoTrack._player&&((n=t._videoTrack._player.getVideoElement())===null||n===void 0||n.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())}),this.resetConnection(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&this.recreateConnection(),this.localTrackMap.size!==0&&(Array.from(this.localTrackMap.entries()).forEach(e=>{var t;let[n,{track:i}]=e;switch(n){case G.LocalVideoTrack:x(t=i._hints).call(t,$e.LOW_STREAM)?i.close():this.pendingLocalTracks.push(i);break;case G.LocalAudioTrack:i instanceof En?this.pendingLocalTracks=this.pendingLocalTracks.concat(i.trackList):this.pendingLocalTracks.push(i);case G.LocalVideoLowTrack:}}),this.emit(ae.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),this.remoteUserMap.size!==0&&Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,n]=e;Array.from(_n(n).call(n)).forEach(i=>{this.setPendingRemoteMedia(t,i)}),this.emit(ae.MediaReconnectStart,t.uid)}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.localDataChannels.length!==0&&(this.localDataChannels.forEach(e=>{this.pendingLocalDataChannels.push(e)}),this.localDataChannels.length=0),this.remoteDataChannelMap.size!==0&&(Array.from(this.remoteDataChannelMap.entries()).forEach(e=>{let[t,n]=e;Array.from(_n(n).call(n)).forEach(i=>{this.setPendingRemoteDataChannel(t,i)})}),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),_.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")))}hasPendingRemoteDataChannel(e,t){for(const n of this.pendingRemoteDataChannels){const{user:i,id:r}=n;if((e instanceof na?e.uid:e)===i.uid&&r===t)return!0}return!1}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t})}hasPendingRemoteMedia(e,t){for(const n of this.pendingRemoteTracks){const{user:i,kind:r}=n;if((e instanceof na?e.uid:e)===i.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}restartICE(e){var t=this;return di(function*(){if(!t.connection||t.state!==qe.Connected)return;const n=yield ve(t.mutex.lock("From P2PChannel.restartICE"));let i;try{i=yield ve(t.connection.restartICE(e));const o=yield ve(i.next());if(o.done)return;const s=o.value,a=yield s;switch(wv(t.connection)&&t.reportPCStats(Date.now(),!1,t._pcStatsUploadType),e){case gn.UDP_TCP_RELAY:t._pcStatsUploadType=ls.UDP_TCP_RESTART;break;case gn.TCP_RELAY:t._pcStatsUploadType=ls.TCP_RESTART;break;case gn.RELAY:t._pcStatsUploadType=ls.RELAY_RESTART;break;default:t._pcStatsUploadType=ls.OLD_RESTART}t._isTryConnecting=!0,i.next(a)}catch(o){var r;(r=i)===null||r===void 0||r.throw(o)}finally{n()}})()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(G.LocalVideoTrack),n=this.localTrackMap.get(G.LocalAudioTrack),i=e.videoSend.find(p=>p.ssrc===(t==null?void 0:t.ssrcs[0].ssrcId)),r=e.audioSend.find(p=>p.ssrc===(n==null?void 0:n.ssrcs[0].ssrcId));if(!i||!r)return 1;const o=Ui(this,ae.NeedSignalRTT),s=i?i.rttMs:void 0,a=r?r.rttMs:void 0,c=s&&a?(s+a)/2:s||a,d=(c&&o?(c+o)/2:c||o)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,h=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,u=t==null?void 0:t.track;if(u&&u._encoderConfig&&u._hints.indexOf($e.SCREEN_TRACK)===-1){const p=u._encoderConfig.bitrateMax,E=e.bitrate.actualEncoded;if(p&&E){const m=(1e3*p-E)/(1e3*p);return bP[m<.15?0:m<.3?1:m<.45?2:m<.6?3:4][h]}}return h}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach(n=>{let[i]=n;const r=i._audioSSRC,o=i._videoSSRC,s=e.audioRecv.find(E=>E.ssrc===r),a=e.videoRecv.find(E=>E.ssrc===o);if(!s&&!a)return void(t+=1);const c=Ui(this,ae.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,h=s?s.jitterMs:void 0,u=e.recvPacketLossRate;let p=.7*u*100/50+.3*l/1500;h&&(p=.6*u*100/50+.2*l/1500+.2*h/400),t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5}),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new K((t,n)=>{this.handleMuteLocalTrack(e,t,n)})}async replaceTrack(e,t){var n;if(_.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==qe.Connected)return;const i=Array.from(this.localTrackMap.entries()).find(o=>{let[,{track:s}]=o;return e===s});if(!i)return;const r=i[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:r}]),this.bindLocalTrackEvents([{track:t,type:r}]),i[1].track=t),await((n=this.connection)===null||n===void 0?void 0:n.replaceTrack(t,i[1].id)),this.isPlanB){const o=i[1];o.id=t._mediaStreamTrack.id,this.localTrackMap.set(r,o)}if(r===G.LocalVideoTrack&&!T("DISABLE_DUAL_STREAM_USE_ENCODING")&&Oe().supportDualStreamEncoding){const o=this.localTrackMap.get(G.LocalVideoLowTrack);if(o){const s=e._mediaStreamTrack.clone();o.track._originMediaStreamTrack.stop(),o.track._mediaStreamTrack=s,o.track._originMediaStreamTrack=s,await new K((a,c)=>{this.handleReplaceTrack(o.track,a,c,!0)})}}}filterTobePublishedTracks(e,t,n){const i=[],r=this.getAllTracks();e=nd(e=e.filter(c=>r.indexOf(c)===-1));let o,s=!1;const a=this.localTrackMap.get(G.LocalAudioTrack);for(const c of e){if(c instanceof pt&&(this.localTrackMap.has(G.LocalVideoTrack)||s?new L(A.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(i.push({track:c,type:G.LocalVideoTrack}),s=!0),t)){const d=this.getLowVideoTrack(c,n);i.push({track:d,type:G.LocalVideoLowTrack})}if(c instanceof jt)if(a){const d=a.track;if(d instanceof En)Iv([c]),d.addAudioTrack(c),this.bindLocalAudioTrackEvents(c,!0);else{const l=bv([d,c]);_.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(l.getTrackId(),"]")),this.replaceTrack(d,l)}}else o instanceof En?(Iv([c]),o.addAudioTrack(c)):o||!c._useAudioElement&&Oe().webAudioMediaStreamDest&&!c._bypassWebAudio?o=bv(o?[c,o]:[c]):o=c}return o&&(_.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(o.getTrackId(),"]")),i.push({track:o,type:G.LocalAudioTrack})),i}filterTobeUnpublishedTracks(e){const t=[],n=this.getAllTracks();e=nd(e=e.filter(i=>n.indexOf(i)!==-1));for(const i of e){if(i instanceof jt){const r=this.localTrackMap.get(G.LocalAudioTrack);if(!r)continue;r.track instanceof En?(r.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),r.track.trackList.length===0&&(t.push([G.LocalAudioTrack,r]),r.track.close())):t.push([G.LocalAudioTrack,r])}if(i instanceof pt){const r=this.localTrackMap.get(G.LocalVideoTrack);if(!r)continue;t.push([G.LocalVideoTrack,r]);const o=this.localTrackMap.get(G.LocalVideoLowTrack);o&&t.push([G.LocalVideoLowTrack,o])}}return t}filterTobePublishedDataChannels(e){return e=(e=nd(e)).filter(t=>this.localDataChannels.findIndex(n=>n.id===t.id)===-1)}filterTobeUnpublishedDataChannels(e){return e=(e=(e=nd(e)).filter(t=>this.localDataChannels.indexOf(t)!==-1)).filter(t=>t._originDataChannel)}bindLocalTrackEvents(e){e.forEach(t=>{let{track:n,type:i}=t;switch(i){case G.LocalVideoTrack:n.addListener(te.GET_STATS,this.handleGetLocalVideoStats),n.addListener(te.GET_RTC_STATS,this.handleGetRTCStats),n.addListener(te.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),n.addListener(te.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),n.addListener(te.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),n.addListener(te.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),n.addListener(te.NEED_REPLACE_TRACK,this.handleReplaceTrack),n.addListener(te.NEED_MUTE_TRACK,this.handleMuteLocalTrack),n.addListener(te.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case G.LocalAudioTrack:this.bindLocalAudioTrackEvents(n);case G.LocalVideoLowTrack:}})}bindLocalAudioTrackEvents(e,t){e instanceof En?e.trackList.forEach(n=>
113{n.addListener(te.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),n.addListener(te.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),n.addListener(te.GET_STATS,this.handleGetLocalAudioStats),n.addListener(te.NEED_MUTE_TRACK,this.handleMuteLocalTrack),n.addListener(te.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.addListener(te.GET_STATS,this.handleGetLocalAudioStats),e.addListener(te.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(te.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(te.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(te.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(te.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(te.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map(t=>{let[n,{track:i}]=t;return{track:i,type:n}})),e.forEach(t=>{let{track:n,type:i}=t;switch(i){case G.LocalVideoTrack:n.off(te.GET_STATS,this.handleGetLocalVideoStats),n.off(te.GET_RTC_STATS,this.handleGetRTCStats),n.off(te.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),n.off(te.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),n.off(te.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),n.off(te.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),n.off(te.NEED_REPLACE_TRACK,this.handleReplaceTrack),n.off(te.NEED_MUTE_TRACK,this.handleMuteLocalTrack),n.off(te.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case G.LocalAudioTrack:this.unbindLocalAudioTrackEvents(n);case G.LocalVideoLowTrack:}})}unbindLocalAudioTrackEvents(e){e instanceof En?e.trackList.forEach(t=>{t.off(te.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(te.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(te.GET_STATS,this.handleGetLocalAudioStats),t.off(te.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(te.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.off(te.GET_STATS,this.handleGetLocalAudioStats),e.off(te.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(te.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(te.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(te.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(te.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(te.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof md&&t.addListener(te.GET_STATS,n=>{n(this.handleGetRemoteVideoStats(e))}),t instanceof Ed&&t.addListener(te.GET_STATS,n=>{n(this.handleGetRemoteAudioStats(e))})}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(te.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,n]=e;n.has($.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),n.has($.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)})}createGatewayPublishMessage(e,t){return e.map((n,i)=>{var r;let o,s,{track:a,type:c}=n;switch(c){case G.LocalAudioTrack:o=nt.Audio,s={dtx:a instanceof Zl&&a._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case G.LocalVideoTrack:o=x(r=a._hints).call(r,$e.SCREEN_TRACK)?nt.Screen:nt.High,s=Jo(Jo({},TU(a)),{},{codec:this.store.codec,svc_mode:Lu()});break;case G.LocalVideoLowTrack:o=nt.Low,s=Jo(Jo({},TU(a)),{},{codec:this.store.codec,svc_mode:Lu()})}return{stream_type:o,attributes:s,ssrcs:t[i]}})}createGatewayUnpublishMessage(e){return e.map(t=>{var n;let i,[r,{track:o,ssrcs:s,id:a}]=t;switch(r){case G.LocalVideoTrack:i=x(n=o._hints).call(n,$e.SCREEN_TRACK)?nt.Screen:nt.High;break;case G.LocalAudioTrack:i=nt.Audio;break;case G.LocalVideoLowTrack:i=nt.Low}return{stream_type:i,ssrcs:s,mid:a}})}assignLocalTracks(e,t){e.forEach((n,i)=>{let{track:r,type:o}=n;this.localTrackMap.set(o,{track:r,id:t[i].id,ssrcs:t[i].localSSRC})})}withdrawLocalTracks(e){e.forEach(t=>{let[n]=t;this.localTrackMap.delete(n)})}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(ae.PeerConnectionStateChange,t),t==="connecting"&&e instanceof xi&&!Rt()&&T("FIRST_TCP_CANDIDATE")&&window.setTimeout(()=>{t==="connecting"&&e.extendCandidate()},T("FIRST_TCP_CANDIDATE_INTERVAL")),t!=="connected"||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),t==="connected"&&(this._restartTimer&&(window.clearTimeout(this._restartTimer),this._restartTimer=void 0),e instanceof xi&&_2(e,!0),this._isTryConnecting&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isTryConnecting=!1,this._isStartRestartIce=!1,this._pcStatsUploadType=ls.DISCONNECTED_OR_FAILED,Ui(this,ae.QueryClientConnectionState)==="CONNECTED"&&this._isWaitPcToRePub)){const n=this.pendingLocalTracks.map(r=>r.getTrackId()),i=this.pendingLocalDataChannels.map(r=>"dc_".concat(r.id));Z.reportApiInvoke(this.store.sessionId,{name:vt.REPUB_AFTER_PC_CONNECTED,options:n.concat(i),tag:ht.TRACER}).onSuccess(),this.republish()}
113if(T("NEW_ICE_RESTART")&&e instanceof xi&&!Rt()&&!this._forceTurn&&!this.store.useDcSignal){if(x(VP).call(VP,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const n=r=>{wv(e)&&(_.debug("[".concat(this.store.clientId,"] [P2PChannel] try to restartICE, type is ").concat(r)),Ui(this,ae.QueryClientConnectionState)==="CONNECTED"&&this.emit(ae.RequestRestartICE,r))},i=()=>{wv(e)&&(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),_.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout(()=>this.emit(ae.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect())};return void(this._restartTimer=window.setTimeout(()=>{m2(e,n,i)},800))}}else{if(t==="disconnected"&&e.iceConnectionState==="disconnected")return setTimeout(()=>{e.iceConnectionState==="disconnected"&&T("ICE_RESTART")&&Ui(this,ae.QueryClientConnectionState)==="CONNECTED"&&this.emit(ae.RequestRestartICE)},800),void setTimeout(()=>{e.peerConnectionState==="disconnected"&&(_.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection disconnected timeout 4000ms, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isTryConnecting=!1,setTimeout(()=>
113this.emit(ae.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect())},4e3);t==="failed"&&(_.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection state failed, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),setTimeout(()=>this.emit(ae.P2PLost),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=t=>{t!=="connected"||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(t,")")),Z.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:t,tag:ht.TRACER}).onSuccess(),this.emit(ae.IceConnectionStateChange,t)},e.onICETransportStateChange=t=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(t,")"))},e.onDTLSTransportStateChange=t=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(t,")"))},e.onDTLSTransportError=t=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(t,")"))},e.onFirstAudioDecoded=t=>{var n;const i=Array.from(_n(n=this.remoteUserMap).call(n)).find(o=>o._audioSSRC===t);var r;i&&(this.store.subscribe(i.uid,"audio",void 0,void 0,void 0,Date.now()),(r=i.audioTrack)===null||r===void 0||r.emit(pr.FIRST_FRAME_DECODED),Z.firstRemoteFrame(this.store.sessionId,an.FIRST_AUDIO_DECODE,yt.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:jn.measureFromSubscribeStart(this.store.clientId,t),subscribeRequestid:t,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=t=>{var n;const i=Array.from(_n(n=this.remoteUserMap).call(n)).find(r=>r._audioSSRC===t);i&&Z.firstRemoteFrame(this.store.sessionId,an.FIRST_AUDIO_RECEIVED,yt.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:jn.measureFromSubscribeStart(this.store.clientId,t),subscribeRequestid:t,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(t,n,i)=>{var r;const o=Array.from(_n(r=this.remoteUserMap).call(r)).find(s=>s._videoSSRC===t);o&&this.store.firstVideoFrameDecoded(o.uid,{firstDecoded:Date.now()}),this.reportVideoFirstFrameDecoded(t,n,i)},e.onFirstVideoRender=t=>{var n;const i=Array.from(_n(n=this.remoteUserMap).call(n)).find(r=>r._videoSSRC===t);i&&(this.store.firstVideoFrameDecoded(i.uid,{firstPreRender:Date.now()}),this.reportVideoFirstFrameRender(i),this.emit(ae.FirstVideoPreRender,i.uid,t))},e.onFirstVideoReceived=t=>{var n;const i=Array.from(_n(n=this.remoteUserMap).call(n)).find(r=>r._videoSSRC===t);i&&(this.store.firstVideoFrameDecoded(i.uid,{firstReceived:Date.now()}),Z.firstRemoteFrame(this.store.sessionId,an.FIRST_VIDEO_RECEIVED,yt.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:jn.measureFromSubscribeStart(this.store.clientId,t),subscribeRequestid:t,p2pid:this.store.p2pId}))},e.onFirstVideoBufferReady=t=>{var n;const i=Array.from(_n(n=this.remoteUserMap).call(n)).find(r=>r._videoSSRC===t);i&&this.emit(ae.FirstVideoBufferReady,i.uid,t)},e.onSelectedLocalCandidateChanged=(t,n)=>{const i=t.candidateType==="relay",r=n.candidateType==="relay";n.candidateType!=="unknown"&&i===r||this.emit(ae.ConnectionTypeChange,i),_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(ea(n))," -> ").concat(JSON.stringify(ea(t)),")"))},e.onSelectedRemoteCandidateChanged=(t,n)=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(ea(n))," -> ").concat(JSON.stringify(ea(t)),")"))},e.onFirstVideoDecodedTimeout=t=>{this.reportVideoFirstFrameDecoded(t,void 0,void 0,!0)},e.getLocalVideoStats=()=>{const t=this.statsCollector.getLocalVideoTrackStats(),n=this.statsCollector.getRTCStats();return Jo(Jo({},t),n)},e.onICECandidateError=t=>{this._iceError=t}}fallbackConnection(){_.debug("[".concat(this.store.clientId,"] [P2PChannel] try to fallback connection")),this.state===qe.Connected?(_.debug("[".concat(this.store.clientId,"] [P2PChannel] fallback to websocket but P2PChannel state still connected, disconnect first")),this.disconnectForReconnect()):(this.connection&&this.resetConnection(this.connection),this.shouldForwardP2PCreation&&this.recreateConnection())}resetConnection(e){e instanceof xi&&function(t){Jd.delete(t.id),_2(t)}
113(e),e.close(),this.emit(ae.PeerConnectionStateChange,"closed"),function(t){t.onConnectionStateChange=void 0,t.onICEConnectionStateChange=void 0,t.onICETransportStateChange=void 0,t.onDTLSTransportStateChange=void 0,t.onDTLSTransportError=void 0,t.onFirstAudioDecoded=void 0,t.onFirstAudioReceived=void 0,t.onFirstVideoDecoded=void 0,t.onFirstVideoReceived=void 0,t.onSelectedLocalCandidateChanged=void 0,t.onSelectedRemoteCandidateChanged=void 0,t.onFirstVideoDecodedTimeout=void 0,t.getLocalVideoStats=void 0}(e),this._isWaitPcToRePub=!1}recreateConnection(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this._p2pBySDPEndPoint=!1,this.connection=Pee(this.store,e),this.emit(ae.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)}filterTobeMutedTracks(e){const t=[];if(this.getAllTracks().indexOf(e)===-1)return t;const n=this.localTrackMap.get(G.LocalAudioTrack);if(e instanceof jt&&(n==null?void 0:n.track)instanceof En)return n.track.isActive||t.push([G.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find(r=>{let[,{track:o}]=r;return e===o});if(i&&(t.push(i),i[0]===G.LocalVideoTrack)){const r=this.localTrackMap.get(G.LocalVideoLowTrack);r&&t.push([G.LocalVideoLowTrack,r])}return t}filterTobeUnmutedTracks(e){const t=[],n=this.localTrackMap.get(G.LocalAudioTrack);if(e instanceof jt&&(n==null?void 0:n.track)instanceof En)return n.track.isActive&&t.push([G.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find(r=>{let[,{track:o}]=r;return e===o});if(i)if(i[0]===G.LocalVideoTrack){t.push(i);const r=this.localTrackMap.get(G.LocalVideoLowTrack);r&&t.push([G.LocalVideoLowTrack,r])}else t.push(i);return t}createMuteMessage(e){return e.map(t=>{var n;let i,[r,{track:o,ssrcs:s,id:a}]=t;switch(r){case G.LocalAudioTrack:i=nt.Audio;break;case G.LocalVideoTrack:i=x(n=o._hints).call(n,$e.SCREEN_TRACK)?nt.Screen:nt.High;break;case G.LocalVideoLowTrack:i=nt.Low}return{stream_type:i,ssrcs:s,mid:a}})}createUnmuteMessage(e){return e.map(t=>{var n;let i,[r,{track:o,ssrcs:s,id:a}]=t;switch(r){case G.LocalAudioTrack:i=nt.Audio;break;case G.LocalVideoTrack:i=x(n=o._hints).call(n,$e.SCREEN_TRACK)?nt.Screen:nt.High;break;case G.LocalVideoLowTrack:i=nt.Low}return{stream_type:i,ssrcs:s,mid:a}})}filterTobeUnSubscribedTracks(e,t){const n=[],i=this.remoteUserMap.get(e);if(!i)return n;if(t){const r=i.get(t);if(!r)return n;n.push([e,{kind:t,id:r}])}else Array.from(i.entries()).forEach(r=>{let[o,s]=r;n.push([e,{kind:o,id:s}])});return n}filterTobeUnSubscribedDataChannels(e,t){const n=[];return t.forEach(i=>{var r;(r=this.remoteDataChannelMap.get(e))!==null&&r!==void 0&&r.has(i.id)&&n.push(i)}),n}createUnsubscribeMessage(e){const t=[];return e.forEach(n=>{let[i,{kind:r,id:o}]=n;switch(r){case $.VIDEO:return void(i._videoSSRC&&t.push({stream_type:$.VIDEO,ssrcId:i._videoSSRC}));case $.AUDIO:return void(i._audioSSRC&&t.push({stream_type:$.AUDIO,ssrcId:i._audioSSRC}))}}),t}createUnsubscribeAllMessage(e){const t=new Map;return e.forEach(n=>{let[i,{kind:r}]=n;if(t.has(i)){let o=t.get(i);r===$.VIDEO?o|=fn.Video:o|=fn.Audio,t.set(i,o)}else r===$.VIDEO?t.set(i,fn.Video):t.set(i,fn.Audio)}),{users:Array.from(t.entries()).map(n=>{let[i,r]=n;return{stream_id:i.uid,stream_type:r}})}}withdrawRemoteTracks(e){e.forEach(t=>{let[n,{kind:i}]=t;const r=this.remoteUserMap.get(n);r&&(r.delete(i),Array.from(r.entries()).length===0&&this.remoteUserMap.delete(n))})}async updateBitrateLimit(e){const t=this.localTrackMap.get(G.LocalVideoTrack),n=this.localTrackMap.get(G.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new K((i,r)=>{this.handleUpdateVideoEncoder(t.track,i,r,!0)})),n&&e.low_stream_uplink&&(await n.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new K((i,r)=>{this.handleUpdateVideoEncoder(n.track,i,r,!0)}))}isP2PDisconnected(){return this.connection?this.connection.peerConnectionState!=="connected":!0}isPreallocation(){return!(!this.connection||!("name"in this.connection)||this.connection.name!=="DataChannelConnection"||this.connection.peerConnectionState==="closed")||this.connection instanceof xi&&this.connection.isPreallocation}isPreSub(){return(this.connection&&"name"in this.connection&&this.connection.name==="DataChannelConnection"&&this.connection.peerConnectionState!=="closed"||this.connection instanceof xi)&&this.connection.isPreSub()}isPreRender(){return this.connection instanceof xi&&this.connection.isPreRen
113der}mapPubResToRemoteConfig(e,t,n){return e.map((i,r)=>{var o;let{stream_type:s}=i;const a=(o=t.find(c=>{let{stream_type:d}=c;return s===d}))===null||o===void 0?void 0:o.attributes;if(a&&T("DISABLE_SCREEN_SHARE_REMB")){const c=n[r]._hints;(x(c).call(c,$e.SCREEN_TRACK)||x(c).call(c,$e.SCREEN_LOW_TRACK))&&(a.remb=!1,_.debug("disable remb for screen share, hints:",c))}return a})}async tryToUnmuteAudio(e){for(let n=0;n<e.length;n++)if(e[n]instanceof jt){var t;const i=this.filterTobeUnmutedTracks(e[n]);if(i.length===0)continue;await((t=this.connection)===null||t===void 0?void 0:t.unmuteLocal(i.map(o=>{let[,{id:s}]=o;return s})));const r=this.createUnmuteMessage(i);return void await mt(this,ae.RequestUnmuteLocal,r)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=()=>this.getStats(),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!((t=this.connection)===null||t===void 0||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(ae.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(ae.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks(),this.statsUploader.requestTransportStats=()=>{var e;return{connectState:((e=this.connection)===null||e===void 0?void 0:e.peerConnectionState)||"closed"}}}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await ln(Ip(this.dtlsFailedCount,Bt)),this.emit(ae.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await Jt(this,ae.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(ae.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(G.LocalVideoTrack)||this.pendingLocalTracks.some(e=>e instanceof pt)}throwIfTrackTypeNotMatch(e){if(e.filter(t=>t instanceof pt).length>1)throw new L(A.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter(t=>t instanceof jt).length>1&&(e.some(t=>t instanceof jt&&t._bypassWebAudio)||!Oe().webAudioMediaStreamDest))throw new L(A.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof pt&&this.pendingLocalTracks.some(n=>n instanceof pt))throw new L(A.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof jt&&this.pendingLocalTracks.some(n=>n instanceof jt)&&(!Oe().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some(n=>n instanceof jt&&n._bypassWebAudio)))throw new L(A.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){var n;const i=!T("DISABLE_DUAL_STREAM_USE_ENCODING")&&Oe().supportDualStreamEncoding,r=Jo(Jo({},{width:160,height:120,framerate:15,bitrate:50}),t);let o;o=i?e._mediaStreamTrack.clone():Nv(e,r);const s=Qe(8,"track-low-"),a=new pt(o,Jo(Jo({},i&&{scaleResolutionDownBy:ov(r,e)}),{},{frameRate:r.framerate,bitrateMax:r.bitrate,bitrateMin:r.bitrate}),void 0,void 0,s);return a.on(xa.TRANSCEIVER_UPDATED,c=>{e._updateRtpTransceiver(c,dd.LOW_STREAM)}),a._hints.push($e.LOW_STREAM),x(n=e._hints).call(n,$e.SCREEN_TRACK)&&a._hints.push($e.SCREEN_LOW_TRACK),e.on("sei-to-send",c=>{a.emit("sei-to-send",c)}),e.addListener(te.NEED_CLOSE,()=>{a.close()}),a}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock")}async reportPCStats(e,t,n){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;if(this.connection&&this.connection instanceof xi){var r,o,s,a;const c=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:d,dtlsTransportState:l,peerConnectionState:h}=this.connection,{local:u,remote:p}=await this.connection.getSelectedCandidatePair();Z.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:d,dtlsstate:l,connectionstate:h,intSucc:t?1:2,error:this._iceError||i||"",selectedLocalCandidateProtocol:(r=u==null?void 0:u.protocol)!==null&&r!==void 0?r:"",selectedLocalCandidateType:(o=u.candidateType)!==null&&o!==void 0?o:"",selectedLocalCandidateAddress:"".concat(u.address,":").concat(u.port),selectedRemoteCandidateProtocol:(s=
113p.protocol)!==null&&s!==void 0?s:"",selectedRemoteCandidateType:(a=p.candidateType)!==null&&a!==void 0?a:"",selectedRemoteCandidateAddress:"".concat(p.address,":").concat(p.port),restartCnt:n,preallocation:this.connection.isPreallocation,sdpEndPoint:this._p2pBySDPEndPoint?1:0}),this._iceError=null}}reportVideoFirstFrameRender(e){const t=this.store.keyMetrics,n=t.firstVideoFrameDecoded.find(l=>l.userId===e.uid);if(!n)return;const{isInternalUpload:i,isExternalUpload:r}=n;if(i&&r)return;const{subscribeEnd:o,firstPreRender:s,peerPublishDuration:a,peerPubStatusMs:c}=n;let{firstRender:d=0}=n;if(o&&(d||s)&&a&&c){n.isInternalUpload=!0;const{playEnd:l}=n;l&&(n.isExternalUpload=!0);const{firstPreRender:h=0}=n;d=h||d;const u=e.videoTrack,p={peer:e._uintid,width:(u==null?void 0:u._videoWidth)||0,height:(u==null?void 0:u._videoHeight)||0,ssrc:e._videoSSRC||0,p2pid:this.store.p2pId,peerPublishDuration:a,peerPubStatusMs:c,joinChannelStart:t.joinStart||0,preloadStart:t.preloadStart||0,preloadEnd:t.preloadEnd||0,apStart:t.requestAPStart||0,apEnd:t.requestAPEnd||0,suaEnd:t.requestSUAEnd||0,beforeConnect:t.beforeConnect||0,peerReceiver:t.peerReceiver||0,ice:t.iceConnectionEnd||0,pc:t.peerConnectionEnd||0,signalConnected:t.signalConnected||0,joinReq:t.joinReq||0,joinRes:t.joinRep||0,userJoinNotify:n.userJoinNotify||0,videoAddNotify:n.videoAddNotify||0,subscribeStart:n.subscribeStart||0,subscribeEnd:n.subscribeEnd||0,firstReceived:n.firstReceived||0,firstDecoded:n.firstDecoded||0,firstPreRender:h||0,firstRender:l?Math.max(d,l):Math.max(d,o),playStart:n.playStart||0,playEnd:n.playEnd||0,isPreSub:!(!e._videoSSRC||!this.isPreSubScribe(e._videoSSRC)),isPrePc:this.isPreallocation(),isPreInstantVideo:yS(this.store),firstReceivedEncodedFrame:n.firstReceivedEncodedFrame||0,frameType:n.frameType||"",rtpTimestamp:n.rtpTimestamp||0,framePayloadType:n.framePayloadType||0,frameDataLength:n.frameDataLength||0,mimeType:n.mimeType||"",sdpEndPoint:this._p2pBySDPEndPoint};Z.firstXLAPeerFirstVideoFrame(this.store.sessionId,p)}}reportVideoFirstFrameDecoded(e,t,n,i){var r;const o=Array.from(_n(r=this.remoteUserMap).call(r)).find(s=>s._videoSSRC===e);if(o){i||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const s=this.store.keyMetrics,a=s.subscribe.find(c=>c.userId===o.uid&&c.type==="video");Z.firstRemoteVideoDecode(this.store.sessionId,an.FIRST_VIDEO_DECODE,yt.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:n,subscribeElapse:jn.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:s.requestAPEnd||0,apStart:s.requestAPStart||0,joinGwEnd:s.joinGatewayEnd||0,joinGwStart:s.joinGatewayStart||0,pcEnd:s.peerConnectionEnd||0,pcStart:s.peerConnectionStart||0,subscriberEnd:(a==null?void 0:a.subscribeEnd)||0,subscriberStart:(a==null?void 0:a.subscribeStart)||0,videoAddNotify:(a==null?void 0:a.streamAdded)||0,state:i?1:0,firstFrame:(a==null?void 0:a.firstFrame)||0})}}async remoteMediaSsrcChanged(e,t,n){if(!this.connection)return!1;const i=this.remoteUserMap.get(e);if(!i)return!1;const r=i.get(t);if(!r)return!1;const o=await this.connection.getRemoteSSRC(r);return o!==void 0&&o!==n}unbindRtpTransceiver(){this.localTrackMap.size!==0&&Array.from(this.localTrackMap.entries()).forEach(e=>{let[t,{track:n}]=e;t===G.LocalVideoLowTrack?n._updateRtpTransceiver(void 0,dd.LOW_STREAM):n._updateRtpTransceiver(void 0)})}},H(De.prototype,"startP2PConnection",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"startP2PConnection"),De.prototype),H(De.prototype,"connect",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"connect"),De.prototype),H(De.prototype,"updateRemoteRTPCapabilities",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"updateRemoteRTPCapabilities"),De.prototype),H(De.prototype,"publishDataChannel",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"publishDataChannel"),De.prototype),H(De.prototype,"unpublish",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"unpublish"),De.prototype),H(De.prototype,"unpublishDataChannel",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"unpublishDataChannel"),De.prototype),H(De.prototype,"unpublishLowStream",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"unpublishLowStream"),De.prototype),H(De.prototype,"subscribeDataChannel",[Qn
113],Object.getOwnPropertyDescriptor(De.prototype,"subscribeDataChannel"),De.prototype),H(De.prototype,"subscribe",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"subscribe"),De.prototype),H(De.prototype,"massSubscribe",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"massSubscribe"),De.prototype),H(De.prototype,"unsubscribe",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"unsubscribe"),De.prototype),H(De.prototype,"unsubscribeDataChannel",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"unsubscribeDataChannel"),De.prototype),H(De.prototype,"massUnsubscribe",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"massUnsubscribe"),De.prototype),H(De.prototype,"muteRemote",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"muteRemote"),De.prototype),H(De.prototype,"unmuteRemote",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"unmuteRemote"),De.prototype),H(De.prototype,"hasRemoteMediaWithLock",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"hasRemoteMediaWithLock"),De.prototype),H(De.prototype,"disconnectForReconnect",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"disconnectForReconnect"),De.prototype),H(De.prototype,"updateBitrateLimit",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"updateBitrateLimit"),De.prototype),H(De.prototype,"remoteMediaSsrcChanged",[Qn],Object.getOwnPropertyDescriptor(De.prototype,"remoteMediaSsrcChanged"),De.prototype),De);function Qn(e,t,n){const i=e[t];if(typeof i!="function")throw new Error("Cannot use mutex on object property.");return n.value=async function(){const r=this.mutex,o=await r.lock("From P2PChannel.".concat(t));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return await i.apply(this,a)}finally{o()}},n}function g2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function S2(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?g2(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):g2(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}const Mee=Date.now(),Uee=20,Lv=new Map,ym=new Map;async function T2(e){const t=Lv.get(e),n=Array.isArray(t)&&t[t.length-1],i=ym.get(e);if(!n)return void(i.isSyncing=!1);const r={uid:n.uid,payload:n.payload};i.firstRecvTs===0&&(i.firstRecvTs=n.recvTs,i.firstSendTs=n.sendTs);const o=n.sendTs-i.firstSendTs,s=o-(Date.now()-i.firstRecvTs);s>0&&(i.firstRecvTs=Date.now()-o);let a=n.mediaDelay+s;a<=0?(t.pop(),R2(n.context,r),a=0):a=Math.min(a,Uee),setTimeout(()=>t.length&&T2(e),a)}function R2(e,t){e.safeEmit(Ce.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function Vee(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return R2(n,{uid:e.uid,payload:e.payload});const i="".concat(n.id,"-").concat(e.uid),r=Lv.get(i)||[],o=r.findIndex(d=>e.sendTs>=d.sendTs),s=S2(S2({},e),{},{context:n,mediaDelay:t,recvTs:Date.now()});o===-1?r.push(s):r.splice(o,0,s),Lv.set(i,r);let a=!1;var c;ym.has(i)?a=!((c=ym.get(i))===null||c===void 0||!c.isSyncing):ym.set(i,{isSyncing:a,firstRecvTs:0,firstSendTs:0}),a||T2(i)}const xee=Fe().name;function v2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function A2(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?v2(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):v2(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}const zd="websdk_ng_cache_parameter",Fee=T("MAX_PRELOAD_ASYNC_LENGTH"),Bee=1e4,uc=new Map,hc=[];let kv=null,Mv=0,Uv=0;const Im=new Map,C2=new Uint8Array([241,141,127,212,103,139,200,225,251,157,127,139,143,2,22,163]),Gee=function(e,t){const n=[];let i=0;const r=async()=>{const o=n.shift();o&&await o(),n.length>0&&i<t?r():i--};return async function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];return new K(async(c,d)=>{n.push(async()=>{try{const l=await e(...s);c(l)}catch(l){d(l)}}),i<t&&(i++,r())})}}(xv,Fee),Vv=li.CancelToken.source();
113class jee{constructor(){S(this,"_audioContext",null)}createMuteAudioTrack(){this._audioContext=new AudioContext;const t=this._audioContext.sampleRate,n=10*t,i=this._audioContext.createBuffer(2,n,t),r=this._audioContext.createBufferSource();r.buffer=i;const o=this._audioContext.createMediaStreamDestination();return r.connect(o),r.start(),o.stream.getAudioTracks()[0]}close(){this._audioContext&&(this._audioContext.close(),this._audioContext=null)}}async function xv(e,t,n,i,r,o,s){try{if(!T("ENABLE_PRELOAD"))return;if(!Oe().supportWebCrypto)return void Ms(()=>{_.warn("Your browser does not support preloading, this feature be run in a secure environment")},"preload_webcrypto_not_supported");if(!n&&n!==null)throw new L(A.INVALID_PARAMS,"Invalid token: ".concat(n,". If you don not use token, set it to null"));n&&On(n,"token",1,2047),On(e,"appid",1,2047),n_(t),i&&$l(i);const a=La();_.debug("preload channel ".concat(t,", uid is ").concat(i));const c={appId:e,cname:t,token:n||e,uid:typeof i!="string"?i:null,sid:a,proxyServer:r,role:s};let d,l;typeof i=="string"?(c.stringUid=i,[l,d]=await K.all([vee(i,{sid:a,appId:e},Vv.token),JU(A2(A2({},c),{},{token:n||e,uid:0}),Vv.token)]),c.uid=l.uid,d.gatewayInfo.uid=c.uid,d.gatewayInfo.res.uid=c.uid):(o&&(c.stringUid=o),d=await JU(c,Vv.token));const h={sid:a,appId:e,cname:t,token:n||e,uid:c.stringUid||i,intUid:c.uid||d.gatewayInfo.uid,stringUid:c.stringUid,ts:Date.now(),sua:l,ap:d};await Bv(h),Mv++}catch(a){throw Uv++,function(c){kv||(kv=window.setTimeout(()=>{let l="";Im.forEach((h,u)=>{l+="".concat(u,": ").concat(h," ;")}),Z.reportApiInvoke(null,{name:vt.PRELOAD,options:{success:Mv,failed:Uv,err:l}}).onError(c),Mv=0,Uv=0,Im.clear(),kv=null},Bee));const d=Im.get(c.code)||0;Im.set(c.code,d+1)}(a),a}}async function Fv(e){try{if(T("AP_REQUEST_DETAIL")||T("ENABLE_ROLE_SELECT_EDGE")||T("ENABLE_JOIN_V4"))return;const t=y2(e);if(!t||e.cloudProxyServer!=="disabled")return;const n=await async function(i,r){try{const o=await window.crypto.subtle.importKey("raw",IO(r),"AES-GCM",!1,["decrypt"]),s=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:C2},o,Pa(i));return JSON.parse(window.atob(Us(new Uint8Array(s))))}catch{return}}(t,e.token||e.appId);if(!n||!function(i,r){return i.cname===r.cname&&i.appId===r.appId&&i.token===r.token?r.stringUid?i.stringUid===r.stringUid:typeof r.uid=="number"?i.uid===r.uid:i.uid==r.uid:!1}(n,e))return;if(n&&Date.now()-n.ts<T("AP_CACHE_LIFETIME"))return n}catch(t){_.warn("Error get preloadInfo",t.message)}}function y2(e){let t;try{if(t=w2(zd),!t)return;const n=JSON.parse(t),i=O2(e),r=function(s,a){for(let c=s.length-1;c>=0;c--)if(a(s[c]))return c;return-1}(n,s=>i in s);if(r===-1)return;const o=n.splice(r,1)[0];return bm(zd,JSON.stringify(n)),o[i]}catch(n){_.warn("Error delete preload info: ".concat(t),n.message),bm(zd,"")}}async function Bv(e){let t;try{e.uid&&y2({appId:e.appId,cname:e.cname,token:e.token,uid:e.uid,stringUid:e.stringUid});const n=O2(e),i=await async function(o,s){try{const a=await window.crypto.subtle.importKey("raw",IO(s),"AES-GCM",!1,["encrypt"]),c=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:C2},a,Pa(window.btoa(JSON.stringify(o))));return Us(new Uint8Array(c))}catch{return}}(e,e.token||e.appId);if(!i)return;t=w2(zd);const r=t?JSON.parse(t):[];r.push({[n]:i}),r.length>T("AP_CACHE_NUM")&&r.shift(),bm(zd,JSON.stringify(r))}catch(n){_.warn("Error caching server parameters:",n.message),bm(zd,"")}}function Gv(e){if(e){let t=uc.get(e);t&&(window.clearTimeout(t),t=null,uc.delete(e)),x(hc).call(hc,e)||e.cloudProxyServer!=="disabled"||hc.push(e)}if(uc.size<T("AP_CACHE_NUM")&&hc.length>0){const t=hc.shift();uc.set(t,window.setTimeout(async()=>{const{appId:n,cname:i,token:r,stringUid:o,uid:s,proxyServer:a,role:c}=t;try{await Gee(n,i,r,s,a,o,c),uc.has(t)&&Gv(t)}catch(d){_.warn("update preload failed",d.message),I2(t)}},T("AP_UPDATE_INTERVAL")))}}function I2(e){const t=hc.indexOf(e);t!==-1&&hc.splice(t,1);let n=uc.get(e);n&&(window.clearTimeout(n),n=null,uc.delete(e),Gv())}function b2(e,t){const n=e.sua,i=e.ap;t&&n&&Z.reqUserAccount(e.sid,{lts:n.requestTime,elapse:n.elapse,success:!0,serverAddr:n.url,stringUid:t,uid:e.intUid,errorCode:null,extend:n.req}),Z.reportResourceTiming(e.ap.url,e.sid),Z.joinWebProxyAP(e.sid,{lts:i.requestTime,elapse:i.elapse,sucess:1,apServerAddr:i.url,turnServerAddrList:i.proxyInfo.addresses.map(r=>r.ip).join(","),eventType:"disabled",unilbsServerIds:[Dt.CHOOSE_SERVER,Dt.CLOUD_PROXY_FALLBACK].toString()}),Z.joinChooseServer(e.sid,{lts:i.requestTime,elapse:i.elapse,succ:!0,csAddr:i.url,opid:i.opid,serverList:i.gatewayInfo.gatewayAddrs.map(r=>r.address),ec:null,cid:i.gatewayInfo.cid.toString(),uid:i.gatewayInfo.uid.toString(),csIp:i.gatewayInfo.csIp,unilbsServerIds:[Dt.CHOOSE_SERVER].toString(),isHttp3:i.isHttp3})}function w2(e){return window.atob(window.localStorage.getItem(e)||"")}function bm(e,t){window.localStorage.setItem(e,window.btoa(t))}function O2(e){let t="".concat(e.appId,"_").concat(e.cname);return typeof e.uid=="string"&&(t+="_s_".concat(e.uid)),typeof e.uid=="number"&&(t+="_".concat(e.uid)),e.token&&(t+="_".concat(e.token)),LO(t)}function Wee(e){let t=function(){const n=Yee.pop();return n?(n.offset=n.limit=0,n):{bytes:new Uint8Array(64),offset:0,limit:0}}();
113return function(n,i){let r=n.appId;r!==void 0&&(rn(i,10),ra(i,r));let o=n.cid;o!==void 0&&(rn(i,16),rn(i,o));let s=n.cname;s!==void 0&&(rn(i,26),ra(i,s));let a=n.deviceId;a!==void 0&&(rn(i,34),ra(i,a));let c=n.elapse;c!==void 0&&(rn(i,40),oa(i,c));let d=n.fileSize;d!==void 0&&(rn(i,48),oa(i,qd(d)));let l=n.height;l!==void 0&&(rn(i,56),oa(i,qd(l)));let h=n.jpg;h!==void 0&&(rn(i,66),rn(i,h.length),D2(i,h));let u=n.networkType;u!==void 0&&(rn(i,72),oa(i,qd(u)));let p=n.osType;p!==void 0&&(rn(i,80),oa(i,qd(p)));let E=n.requestId;E!==void 0&&(rn(i,90),ra(i,E));let m=n.sdkVersion;m!==void 0&&(rn(i,98),ra(i,m));let g=n.sequence;g!==void 0&&(rn(i,104),oa(i,qd(g)));let R=n.sid;R!==void 0&&(rn(i,114),ra(i,R));let v=n.timestamp;v!==void 0&&(rn(i,120),oa(i,v));let C=n.uid;C!==void 0&&(rn(i,128),rn(i,C));let w=n.vid;w!==void 0&&(rn(i,136),rn(i,w));let b=n.width;b!==void 0&&(rn(i,144),oa(i,qd(b)));let y=n.service;y!==void 0&&(rn(i,152),rn(i,y));let N=n.callbackData;N!==void 0&&(rn(i,162),rn(i,N.length),D2(i,N));let k=n.ticket;k!==void 0&&(rn(i,170),ra(i,k));let U=n.vendorConfigs;U!==void 0&&(rn(i,178),ra(i,U))}(e,t),function(n){let i=n.bytes,r=n.limit;return i.length===r?i:i.subarray(0,r)}(t)}function Kee(e){return function(n){let i={};e:for(;!Xee(n);){let r=ju(n);switch(r>>>3){case 0:break e;case 1:i.code=ju(n);break;case 2:i.msg=P2(n,ju(n));break;case 3:i.requestId=P2(n,ju(n));break;case 4:i.timestamp=Jee(n,!1);break;default:Hee(n,7&r)}}return i}({bytes:t=e,offset:0,limit:t.length});var t}function Hee(e,t){switch(t){case 0:for(;128&$r(e););break;case 2:jv(e,ju(e));break;case 5:jv(e,4);break;case 1:jv(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function qd(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let Yee=[];function jv(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function Xee(e){return e.offset>=e.limit}function wm(e,t){let n=e.bytes,i=e.offset,r=e.limit,o=i+t;if(o>n.length){let s=new Uint8Array(2*o);s.set(n),e.bytes=s}return e.offset=o,o>r&&(e.limit=o),i}function N2(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function D2(e,t){let n=wm(e,t.length);e.bytes.set(t,n)}function P2(e,t){let n=N2(e,t),i=String.fromCharCode,r=e.bytes,o="\uFFFD",s="";for(let a=0;a<t;a++){let c,d,l,h,u=r[a+n];128&u?(224&u)==192?a+1>=t?s+=o:(c=r[a+n+1],(192&c)!=128?s+=o:(h=(31&u)<<6|63&c,h<128?s+=o:(s+=i(h),a++))):(240&u)==224?a+2>=t?s+=o:(c=r[a+n+1],d=r[a+n+2],(49344&(c|d<<8))!=32896?s+=o:(h=(15&u)<<12|(63&c)<<6|63&d,h<2048||h>=55296&&h<=57343?s+=o:(s+=i(h),a+=2))):(248&u)==240?a+3>=t?s+=o:(c=r[a+n+1],d=r[a+n+2],l=r[a+n+3],(12632256&(c|d<<8|l<<16))!=8421504?s+=o:(h=(7&u)<<18|(63&c)<<12|(63&d)<<6|63&l,h<65536||h>1114111?s+=o:(h-=65536,s+=i(55296+(h>>10),56320+(1023&h)),a+=3))):s+=o:s+=i(u)}return s}function ra(e,t){let n=t.length,i=0;for(let s=0;s<n;s++){let a=t.charCodeAt(s);a>=55296&&a<=56319&&s+1<n&&(a=(a<<10)+t.charCodeAt(++s)-56613888),i+=a<128?1:a<2048?2:a<65536?3:4}rn(e,i);let r=wm(e,i),o=e.bytes;for(let s=0;s<n;s++){let a=t.charCodeAt(s);a>=55296&&a<=56319&&s+1<n&&(a=(a<<10)+t.charCodeAt(++s)-56613888),a<128?o[r++]=a:(a<2048?o[r++]=a>>6&31|192:(a<65536?o[r++]=a>>12&15|224:(o[r++]=a>>18&7|240,o[r++]=a>>12&63|128),o[r++]=a>>6&63|128),o[r++]=63&a|128)}}function $r(e){return e.bytes[N2(e,1)]}function L2(e,t){let n=wm(e,1);e.bytes[n]=t}function ju(e){let t,n=0,i=0;do t=$r(e),n<32&&(i|=(127&t)<<n),n+=7;while(128&t);return i}function rn(e,t){for(t>>>=0;t>=128;)L2(e,127&t|128),t>>>=7;L2(e,t)}function Jee(e,t){let n,i=0,r=0,o=0;return n=$r(e),i=127&n,128&n&&(n=$r(e),i|=(127&n)<<7,128&n&&(n=$r(e),i|=(127&n)<<14,128&n&&(n=$r(e),i|=(127&n)<<21,128&n&&(n=$r(e),r=127&n,128&n&&(n=$r(e),r|=(127&n)<<7,128&n&&(n=$r(e),r|=(127&n)<<14,128&n&&(n=$r(e),r|=(127&n)<<21,128&n&&(n=$r(e),o=127&n,128&n&&(n=$r(e),o|=(127&n)<<7))))))))),{low:i|r<<28,high:r>>>4|o<<24,unsigned:t}}function oa(e,t){let n=t.low>>>0,i=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=r===0?i===0?n<16384?n<128?1:2:n<1<<21?3:4:i<16384?i<128?5:6:i<1<<21?7:8:r<128?9:10,s=wm(e,o),a=e.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=o!==9?128|r:127&r;case 8:a[s+7]=o!==8?i>>>21|128:i>>>21&127;case 7:a[s+6]=o!==7?i>>>14|128:i>>>14&127;case 6:a[s+5]=o!==6?i>>>7|128:i>>>7&127;case 5:a[s+4]=o!==5?128|i:127&i;case 4:a[s+3]=o!==4?n>>>21|128:n>>>21&127;case 3:a[s+2]=o!==3?n>>>14|128:n>>>14&127;case 2:a[s+1]=o!==2?n>>>7|128:n>>>7&127;case 1:a[s]=o!==1?128|n:127&n}}const k2={},M2={},Om=4294967296,zee=Om*Om,U2=zee/2;x2(0,!0);const V2=x2(0),qee=Wu(0,-2147483648,!1),Zee=Wu(-1,2147483647,!1);function x2(e,t){let n,i,r;return t?(r=0<=(e>>>=0)&&e<256)&&(i=M2[e],i)?i:(n=Wu(e,0,!0),r&&(M2[e]=n),n):(r=-128<=(e|=0)&&e<128)&&(i=k2[e],i)?i:(n=Wu(e,e<0?-1:0,!1),r&&(k2[e]=n),n)}function Wu(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function F2(e,t){if(isNaN(e))return V2;{if(e<=-U2)return qee;if(e+1>=U2)return Zee}return e<0?V2:Wu(e%Om|0,e/Om|0,t)}function B2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}class Wv extends Nt{get connectionState(){return this._connectionState}set connectionState(t){if(this._connectionState===t)return;const n=this._connectionState;
113this._connectionState=t,this.emit(po.CONNECTION_STATE_CHANGE,t,n)}get quality(){return this._quality}set quality(t){this._quality=t>1?1:t<.1?.1:t,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout(()=>{this.quality=this._quality/this._qualityRatio},6e4))}constructor(t){var n;super(),S(this,"name","AgoraRTCImageModeration"),S(this,"_connectionState",Er.CONNECTING),S(this,"_sequence",0),S(this,"_moderationStartTime",void 0),S(this,"_workerConnection",void 0),S(this,"_workerMessageLengthLimit",void 0),S(this,"_qualityRatio",void 0),S(this,"_connectInfo",void 0),S(this,"_cancelTokenSource",li.CancelToken.source()),S(this,"_retryConfig",void 0),S(this,"_moderationInterval",void 0),S(this,"_moderationTimer",null),S(this,"_moderationMode",1),S(this,"_quality",1),S(this,"_qualityTimer",null),S(this,"_ticket",void 0),S(this,"_moderationIntervalMinimum",void 0),S(this,"_uploadFailedNum",0),S(this,"_uploadNum",0),S(this,"_uploadTimer",null),S(this,"_extraInfo",void 0),S(this,"_vendor",""),S(this,"_encoder",new TextEncoder),S(this,"_moderationId",void 0),S(this,"inspectImage",()=>{if(this.connectionState!==Er.CONNECTED)throw new D(A.OPERATION_ABORTED,"image moderation service connection status is ".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval(()=>{this.connectionState===Er.CONNECTED?this.requestToInspectImage():_.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)},this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage()}),this._moderationId=Qe(5,"image-moderation-"),this._workerMessageLengthLimit=T("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=T("IMAGE_MODERATION_INTERVAL_MINIMUM"),this._moderationInterval=(n=t.interval)!==null&&n!==void 0?n:1e3,t.extraInfo&&(this._extraInfo=this._encoder.encode(t.extraInfo)),t.vendor&&(this._vendor=t.vendor),this._qualityRatio=T("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new eu("worker-"+this._moderationId,Bt),this.on(po.STATE_CHANGE,(i,r)=>{_.debug("[".concat(this._moderationId,"] Moderation operation :").concat(Td[i]," ").concat(r||""))}),this.handleWorkerEvents()}async init(t,n){this.emit(po.STATE_CHANGE,Td.CONNECT_AP),this._connectInfo=t;const i=this._cancelTokenSource.token;return this._retryConfig=n,new K((r,o)=>{this.on(po.CONNECTION_STATE_CHANGE,(s,a)=>{s===Er.CONNECTED&&r()}),this.requestAP(t,i,n).then(s=>{this.connectWorker(s)}).catch(s=>{o(s)})})}updateConfig(t){var n;this._moderationInterval=(n=t.interval)!==null&&n!==void 0?n:1e3,t.extraInfo&&(this._extraInfo=this._encoder.encode(t.extraInfo)),t.vendor&&(this._vendor=t.vendor),_.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(t))),this.connectionState===Er.CONNECTED&&this.inspectImage()}async requestAP(t,n,i){const r=T("WEBCS_DOMAIN").map(c=>"https://".concat(c,"/api/v1")),o=await function(c,d,l,h){let{appId:u,areaCode:p,cname:E,sid:m,token:g,uid:R}=d;Kd++;const v="moderation_plugin",C={service_name:v,json_body:JSON.stringify({appId:u,areaCode:p,cname:E,command:"allocateEdge",requestId:Kd,seq:Kd,sid:m,appToken:g,ts:Date.now(),uid:R+""})};let w,b,y=c[0];return Fr(async()=>{w=Date.now();const N=await Qr(y,{data:C,cancelToken:l,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(b=Date.now()-w,N.code!==0){const q=new D(A.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+N.code,{retry:!0,responseTime:b});throw _.error(q.toString()),q}const k=JSON.parse(N.json_body);if(k.code!==200){const q=new D(A.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(k.code,", reason: ").concat(k.reason),{code:k.code,responseTime:b});throw _.error(q.toString()),q}if(!k.servers||!Array.isArray(k.servers)||k.servers.length===0){const q=new D(A.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{c
113ode:k.code,responseTime:b});throw _.error(q.toString()),q}if(!k.servers.some(q=>!!q.wss)){const q=new D(A.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:k.code,responseTime:b});throw _.error(q.toString()),q}const U=T("IMAGE_MODERATION_WORKER_WSS");if(U)return{addressList:[U],workerToken:k.workerToken,vid:k.vid,responseTime:b};const X=T("IMAGE_MODERATION_WORKER_HOST");return{addressList:k.servers.map(q=>{let{address:se,wss:_e}=q;if(se&&_e)return"wss://".concat(se.replace(/\./g,"-"),".").concat(X,":").concat(_e,"/moderation")}).filter(q=>!!q),workerToken:k.workerToken,vid:k.vid,ticket:k.appTicket,responseTime:b}},(N,k)=>(Z.apworkerEvent(m,{success:!0,sc:200,serviceName:v,responseDetail:JSON.stringify(N.addressList),firstSuccess:k===0,responseTime:b,serverIp:c[k%c.length]}),!1),(N,k)=>(Z.apworkerEvent(m,{success:!1,sc:N.data&&N.data.code||200,serviceName:v,responseTime:b,serverIp:c[k%c.length]}),!!(N.code!==A.OPERATION_ABORTED&&N.code!==A.UNEXPECTED_RESPONSE||N.data&&N.data.retry)&&(y=c[(k+1)%c.length],!0)),h)}(r,t,n,i);this.emit(po.STATE_CHANGE,Td.AP_CONNECTED);const{addressList:s,ticket:a}=o;return this._ticket=a,s}async connectWorker(t){this.emit(po.STATE_CHANGE,Td.CONNECT_WORKER),await this._workerConnection.init(t,1e4)}handleWorkerEvents(){this._workerConnection.on(Re.CONNECTED,async()=>{this.emit(po.STATE_CHANGE,Td.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=Er.CONNECTED}),this._workerConnection.on(Re.CLOSED,()=>{this.connectionState=Er.CLOSED}),this._workerConnection.on(Re.FAILED,()=>{this.connectionState=Er.CLOSED}),this._workerConnection.on(Re.RECONNECTING,()=>{this.connectionState=this.connectionState===Er.CONNECTED?Er.RECONNECTING:Er.CONNECTING}),this._workerConnection.on(Re.ON_MESSAGE,async t=>{if(t.data instanceof ArrayBuffer){const n=Kee(new Uint8Array(t.data));T("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&_.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(n)),this._uploadNum++,n.code===void 0||n.code===0||(this._uploadFailedNum++,_.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(n.code,", msg is ").concat(n.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout(()=>{Z.reportApiInvoke(this._connectInfo.sid||null,{name:vt.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,n.code],tag:ht.TRACER}).onError(new D(A.IMAGE_MODERATION_UPLOAD_FAILED,n.msg)),this._uploadTimer=null},T("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else _.error("[".concat(this._moderationId,"] Unexpected message type from worker"))}),this._workerConnection.on(Re.WILL_RECONNECT,(t,n,i)=>{t==="recover"&&i(t),i("tryNext")}),this._workerConnection.on(Re.REQUEST_NEW_URLS,(t,n)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(t).catch(n)})}static intToLong(t){return{low:t|=0,high:t>>31,unsigned:t>=0}}async requestToInspectImage(){const t=Ui(this,po.CLIENT_LOCAL_VIDEO_TRACK),n={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(t){if(!t.isPlaying)return void(T("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&_.debug("Only the track being played can be inspected"));this._sequence++;const i=await this.generateRequestData(t,n);this._workerConnection.sendMessage(i,!0,!0)}else T("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&_.debug("Only the track being published can be inspected")}async generateRequestData(t,n){let{appId:i,cname:r,cid:o,vid:s,sid:a,uid:c}=n;const d=Date.now(),l=await t.getCurrentFrameImage("image/jpeg",this.quality),h=await kN(l,i,r),u=this._sequence+"-"+o+"-"+c+"-"+d+"-"+Qe(12,""),p={appId:i,cid:o,cname:r,deviceId:"",elapse:Wv.intToLong(Number(d-this._moderationStartTime)),fileSize:l.buffer.byteLength,height:l.height,width:l.width,jpg:h,networkType:6,osType:7,requestId:u,sdkVersion:"4.24.3",sequence:this._sequence,sid:a,timestamp:F2(d),uid:c,vid:s,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};this._extraInfo===void 0&&delete p.callbackData;const E=Wee(p);if(E.byteLength<this._workerMessageLengthLimit){if(T("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const m=function(g){for(var R=1;R<arguments.length;R++){var v=arguments[R]!=null?arguments[R]:{};
113R%2?B2(Object(v),!0).forEach(function(C){S(g,C,v[C])}):Object.getOwnPropertyDescriptors?Object.defineProperties(g,Object.getOwnPropertyDescriptors(v)):B2(Object(v)).forEach(function(C){Object.defineProperty(g,C,Object.getOwnPropertyDescriptor(v,C))})}return g}({},p);delete m.jpg,_.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),JSON.stringify(m))}return E}{const m=this.quality*this._qualityRatio;return this.quality=m,await this.generateRequestData(t,{appId:i,cname:r,cid:o,vid:s,sid:a,uid:c})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=li.CancelToken.source(),this._workerConnection&&this._workerConnection.close(),this._moderationTimer&&window.clearInterval(this._moderationTimer),this._moderationTimer=null,this._uploadTimer&&window.clearTimeout(this._uploadTimer),this._uploadTimer=null,this.connectionState=Er.CLOSED,this.emit(po.STATE_CHANGE,Td.CLOSED)}}function G2(e){if(ut(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new D(A.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new D(A.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}const Qee={name:"ImageModeration",create:function(e){let{config:t}=e;return G2(t),new Wv(t)}};var j2,W2,K2,H2,Y2,X2,J2,z2,q2,Z2,Q2,$2,eV,tV,nV,iV,rV,oV,sV,aV,cV,dV,lV,uV,hV,pV,_V,mV,EV,fV,gV,SV,TV,RV,vV,AV,CV,yV,IV,bV,wV,OV,Q;function NV(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Bi(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?NV(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):NV(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}An.setLogger(_);let $ee=(j2=ue(),W2=ue({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof hd))return[t];t=[t]}return t.map(n=>n?Object(n).toString():"null")}}),K2=ue({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||t.trackMediaType!==ud.DATA?(Array.isArray(t)||(t=[t]),t.map(n=>n.getTrackId())):[t.getChannelId()])}),H2=ue({argsMap:(e,t,n,i)=>[typeof t=="object"?t.uid:t,n,i]}),Y2=ue({argsMap:(e,t,n)=>[t,n]}),X2=ue({argsMap:(e,t)=>t.map(n=>{let{user:i,mediaType:r}=n;return[i==null?void 0:i.uid,r]})}),J2=ue({argsMap:(e,t,n,i)=>[typeof t=="object"?t.uid:t,n,i]}),z2=ue({argsMap:(e,t)=>t.map(n=>{let{user:i,mediaType:r}=n;return{uid:i==null?void 0:i.uid,mediaType:r}})}),q2=ue(),Z2=ue(),Q2=ue(),$2=ue(),eV=ue(),tV=ue(),nV=ue(),iV=ue(),rV=ue(),oV=ue(),sV=ue(),aV=ue(),cV=ue(),dV=ue(),lV=ue(),uV=ue(),hV=ue({argsMap:(e,t)=>[t]}),pV=ue(),_V=ue(),mV=ue(),EV=ue(),fV=ue(),gV=ue(),SV=ue(),TV=ue(),RV=ue({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),vV=ue(),AV=ue(),CV=ue(),yV=ue(),IV=ue(),bV=ue(),wV=ue({reportResult:!0}),OV=ue(),Q=class extends Nt{get connectionState(){return this._gateway.state}get remoteUsers(){return this._users}get localTracks(){return this._p2pChannel.getAllTracks(!0)}get uid(){return this._uid}get channelName(){return this._channelName}get localDataChannels(){return this._p2pChannel.getAllDataChannels()}get mode(){return this._config.mode}get role(){var e;return((e=this._config)===null||e===void 0?void 0:e.role)||"audience"}get codec(){return this._config.codec}get audioCodec(){return this._config.audioCodec||"opus"}get isStringUID(){return!!this._joinInfo&&!!this._joinInfo.stringUid}get __className__(){return"Client"}constructor(e,t){let n;if(super(),S(this,"store",void 0),S(this,"_uid",void 0),S(this,"_channelName",void 0),S(this,"_uintUid",void 0),S(this,"_users",[]),S(this,"_config",void 0),S(this,"_clientId",void 0),S(this,"_appId",void 0),S(this,"_sessionId",null),S(this,"_key",void 0),S(this,"_rtmConfig",{}),S(this,"_joinInfo",void 0),S(this,"_gateway",void 0),S(this,"_statsCollector",void 0),S(this,"_configDistribute",void 0),S(this,"_leaveMutex",void 0),S(this,"_publishMutex",void 0),S(this,"_renewTokenMutex",void 0),S(this,"_subscribeMutex",void 0),S(this,"_encryptionMode","none"),S(this,"_encryptionSecret",null),S(this,"_encryptionSalt",null),S(this,"_encryptDataStream",!1),S(this,"_encryptDataStreamKey",null),S(this,"_encryptDataStreamIv",null),S(this,"_proxyServer",void 0),S(this,"_turnServer",{servers:[],mode:"auto"}),S(this,"_cloudProxyServerMode","disabled"),S(this,"_isDualStreamEnabled",!1),S(this,"_defaultStreamFallbackType",void 0),S(this,"_lowStreamParameter",void 0),S(this,"_streamFallbackTypeCacheMap",new Map),S(this,"_remoteStreamTypeCacheMap",new Map),S(this,"_axiosCancelSource",li.CancelToken.source()),S(this,"_audioVolumeIndicationInterval",void 0),S(this,"_networkQualityInterval",void 0),S(this,"_userOfflineTimeout",void 0),S(this,"_streamRemovedTimeout",void 0),S(this,"_rteDetailInterval",void 0),S(this,"_liveTranscodeStreamingClient",void 0),S(this,"_liveRawStreamingClient",void 0),S(this,"_channelMediaRelayClient",void 0),S(this,"_networkQualitySensitivity","normal"),S(this,"_p2pCh
113annel",void 0),S(this,"_useLocalAccessPoint",!1),S(this,"_setLocalAPVersion",void 0),S(this,"_joinAndNotLeaveYet",!1),S(this,"_numberOfJoinCount",0),S(this,"_joinResponse",null),S(this,"_remoteDefaultVideoStreamType",void 0),S(this,"_inspect",void 0),S(this,"_moderation",void 0),S(this,"_license",void 0),S(this,"_pendingPublishedUsers",[]),S(this,"ntpAlignErrorCount",0),S(this,"remoteInboundOffset",0),S(this,"_peerConnectionState",void 0),S(this,"_pendingRtpCapabilityChange",void 0),S(this,"_fallbackServerInfo",void 0),S(this,"_dualStreamMode",void 0),S(this,"_handleLocalTrackEnable",(r,o,s)=>{this.publish(r,!1).then(o).catch(s)}),S(this,"_handleLocalTrackDisable",(r,o,s)=>{this.unpublish(r).then(o).catch(s)}),S(this,"_handleUserOnline",r=>{if(T("BLOCK_LOCAL_CLIENT")&&xs(r.uid,this.channelName))return void _.debug("[".concat(r.uid,"] will be ignored in local"));this.isStringUID&&typeof r.uid!="string"&&_.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));const o=this._users.find(s=>s.uid===r.uid);if(o)o._trust_in_room_=!0,o._is_pre_created&&(o._is_pre_created=!1,this.safeEmit(Ce.USER_JOINED,o));else{const s=new na(r.uid,r.uint_id||r.uid);this._users.push(s),_.debug("[".concat(this._clientId,"] user online"),r.uid),this.store.firstVideoFrameDecoded(s.uid,{userJoinNotify:Date.now()}),this.safeEmit(Ce.USER_JOINED,s)}}),S(this,"_handleUserOffline",r=>{if(T("BLOCK_LOCAL_CLIENT")&&xs(r.uid,this.channelName))return;const o=this._users.find(s=>s.uid===r.uid);o&&(this._handleRemoveStream(r),this._handleRemoveDataChannels(r),o._audio_pre_subscribed||o._video_pre_subscribed?o._is_pre_created=!0:Cp(this._users,o),this._remoteStreamTypeCacheMap.delete(o.uid),this._streamFallbackTypeCacheMap.delete(o.uid),_.debug("[".concat(this._clientId,"] user offline"),r.uid,"reason:",r.reason),this.safeEmit(Ce.USER_LEAVED,o,r.reason))}),S(this,"_handleAddAudioOrVideoStream",(r,o,s,a,c,d,l,h)=>{if(T("BLOCK_LOCAL_CLIENT")&&xs(o,this.channelName))return;const u=this._users.find(m=>m.uid===o);if(!u)return void _.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));_.debug("[".concat(this._clientId,"] stream added with uid ").concat(o,", type ").concat(r)),this.store.subscribe(u.uid,r,void 0,void 0,void 0,Date.now()),r==="video"&&this.store.firstVideoFrameDecoded(u.uid,{videoAddNotify:Date.now()});const p=r==="audio"?u.hasAudio:u.hasVideo;u._uintid||(u._uintid=d||o),r==="audio"?u._trust_audio_stream_added_state_=!0:u._trust_video_stream_added_state_=!0,r==="audio"?(u._audio_added_=!0,s!==void 0&&(u._audioSSRC=s),a!==void 0&&(u._cname=a),l&&(u._audioOrtc=l)):(u._video_added_=!0,s!==void 0&&(u._videoSSRC=s),a!==void 0&&(u._cname=a),h!==void 0&&(u._rtxSsrcId=h),l&&(u._videoOrtc=l)),(r==="audio"?u.hasAudio:u.hasVideo)&&!p&&(_.info("[".concat(this._clientId,"] remote user ").concat(u.uid," published ").concat(r)),this.safeEmit(Ce.USER_PUBLISHED,u,r)),r==="video"?Z.onGatewayStream(this._sessionId,an.ON_ADD_VIDEO_STREAM,yt.ON_ADD_VIDEO_STREAM,{peer:d||o,ssrc:u._videoSSRC}):Z.onGatewayStream(this._sessionId,an.ON_ADD_AUDIO_STREAM,yt.ON_ADD_AUDIO_STREAM,{peer:d||o,ssrc:u._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(u,r,s).then(m=>{if(m&&(_.debug("[".concat(this._clientId,"] resubscribe ").concat(r," for user ").concat(u.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof lc))return this._p2pChannel.unsubscribe(u,r,!0).then(()=>this._subscribe(u,r,!0).catch(g=>{_.error("[".concat(this._clientId,"] resubscribe error"),g.toString())}))}),this._p2pChannel.hasPendingRemoteMedia(u,r)&&(_.debug("[".concat(this._clientId,"] resubscribe ").concat(r," for user ").concat(u.uid," after reconnect.")),this._subscribe(u,r,!0).catch(m=>{_.error("[".concat(this._clientId,"] resubscribe error"),m.toString())}));const E=this._getEncodingName(c);r==="video"&&(E==="unknown"?this.safeEmit(Ce.AV1_DECODABLE_RESULT,!1):vn()||Hn()||(E==null?void 0:E.toLocaleLowerCase())!==Ma.av1||Tee().then(m=>{T("FLS_ENABLE_AV1_DECODE_DETECT")&&this.safeEmit(Ce.AV1_DECODABLE_RESULT,m),m||this._gateway.downgradeCodec(E)}))}),S(this,"_handleRemoveStream",r=>{if(T("BLOCK_LOCAL_CLIENT")&&xs(r.uid,this.channelName))return;const o=this._users.find(a=>a.uid===r.uid);if(!o)return void _.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));_.debug("[".concat(this._clientId,"] stream removed with uid ").concat(r.uid));let s=()=>{};o.hasAudio&&o.hasVideo?s=()=>{_.info("[".concat(this._clientId,"] remote user ").concat(o.uid," unpublished audio track")),this.safeEmit(Ce.USER_UNPUBLISHED,o,"audio"),_.info("[".concat(this._clientId,"] remote user ").concat(o.uid," unpublished video track")),this.safeEmit(Ce.USER_UNPUBLISHED,o,"video")}:o.hasVideo?s=()=>{_.info("[".concat(this._clientId,"] remote user ").concat(o.uid," unpublished video track")),this.safeEmit(Ce.USER_UNPUBLISHED,o,"video")}:o.hasAudio&&(s=()=>{_.info("[".concat(this._clientId,"] remote user ").concat(o.uid," unpublished audio track")),this.safeEmit(Ce.USER_UNPUBLISHED,o,"audio")}),o._video_pre_subscribed||o._audio_pre_subscribed||(o._trust_audio_stream_added_state_=!0,o._trust_video_stream_added_state_=!0,o._audio_added_=!1,o._video_added_=!1,this._p2pChannel instanceof lc&&this._p2pChannel.unsubscribe(o).then(a=>{if(a)return this._gateway.unsubscribe(a,o.uid)}),o._audioSSRC=void 0,o._videoSSRC=void 0,o._audioOrtc=void 0,o._videoOrtc=void 0,o._rtxSsrcId=void 0),Z.onGatewayStream(this._sessionId,an.ON_REMOVE_STREAM,yt.ON_REMOVE_STREAM,{peer:r.uint_id||r.uid}),s()}),S(this,"_handleSetStreamLocalEnable",(r,o,s)=>{if(T("BLOCK_LOCAL_CLIENT")&&xs(o,this.channelName))return;const a=this._users.find(l=>l.uid===o);if(!a)return void _.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));_.debug("[".concat(this._clientId,"] local ").concat(r," ").concat(s?"enabled":"disabled"," with uid ").concat(o));const c=r==="audio"?a.hasAudio:a.hasVideo;if(r==="audio"){a._trust_audio_enabled_state_=!0;const l=a._audio_enabled_;if(a._audio_enabled_=s,a._audio_enabled_===l)return;{const h=a._audio_enabled_?"enable-local-audio":"disable-local-audio";_.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(o,", msg: ").concat(h)),this.safeEmit(Ce.USER_INFO_UPDATED,o,h)}}else{a._trust_video_enabled_state_=!0;const l=a._video_enabled_;if(a._video_enabled_=s,a._video_enabled_===l)return;{const h=a._video_enabled_?"enable-local-video":"disable-local-video";_.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(o,", msg: ").concat(h)),this.safeEmit(Ce.USER_INFO_UPDATED,o,h)}}const d=r==="audio"?a.hasAudio:a.hasVideo;return c!==d?!c&&d?(_.info("[".concat(this._clientId,"] remote user ").concat(o," published ").concat(r)),void this.safeEmit(Ce.USER_PUBLISHED,a,r)):(r==="video"&&a._videoTrack&&a._videoTrack._destroy(),r==="audio"&&a._audioTrack,this._p2pChannel.muteRemote(a,r),_.info("[".concat(this._clientId,"] remote user ").concat(o," unpublished ").concat(r)),void this.safeEmit(Ce.USER_UNPUBLISHED,a,r)):void 0}),S(this,"_handleMuteStream",(r,o,s)=>{if(T("BLOCK_LOCAL_CLIENT")&&xs(r,this.channelName))return;_.debug("[".concat(this._clientId,"] receive mute message"),r,o,s);const a=this._users.find(l=>l.uid===r);if(!a)return void _.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(r));const c=o==="audio"?a.hasAudio:a.hasVideo;if(o==="audio"){a._trust_audio_mute_state_=!0;const l=a._audio_muted_;if(a._audio_muted_=s,a._audio_muted_===l)return;{const h=a._audio_muted_?"mute-audio":"unmute-audio";_.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(r,", msg: ").concat(h)),this.safeEmit(Ce.USER_INFO_UPDATED,r,h)}}else{a._trust_video_mute_state_=!0;const l=a._video_muted_;if(a._video_muted_=s,a._video_muted_===l)return;{const h=a._video_muted_?"mute-video":"unmute-video";_.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(r,", msg: ").concat(h)),this.safeEmit(Ce.USER_INFO_UPDATED,r,h)}}const d=o==="audio"?a.hasAudio:a.hasVideo;if(c!==d){if(!c&&d)return(o==="audio"?a._audioSSRC:a._videoSSRC)?(_.info("[".concat(this._clientId,"] remote user ").concat(r," published ").concat(o)),void this.safeEmit(Ce.USER_PUBLISHED,a,o)):void _.warning("[".concat(this._clientId,"] remote user ").concat(r," receive ").
113concat(o," unmute message before add stream message, ").concat(o," SSRC doesn't exist yet."));o==="video"&&a._videoTrack&&!a._video_pre_subscribed&&a._videoTrack._destroy(),o==="audio"&&a._audioTrack,this._p2pChannel.muteRemote(a,o),_.info("[".concat(this._clientId,"] remote user ").concat(r," unpublished ").concat(o)),this.safeEmit(Ce.USER_UNPUBLISHED,a,o)}}),S(this,"_handleP2PLost",async r=>{_.debug("[".concat(this._clientId,"] receive p2p lost"),r),parseInt(r.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():_.warning("[".concat(this._clientId,"] P2PLost stream not found"),r)}),S(this,"_handleTokenWillExpire",()=>{_.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(Ce.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)}),S(this,"_handleBeforeUnload",r=>{r.type==="beforeunload"&&r.returnValue!==void 0&&r.returnValue!==""||(this.leave(),_.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))}),S(this,"_handleUpdateNetworkQuality",()=>{if(this._networkQualitySensitivity==="normal")return;if(navigator&&navigator.onLine!==void 0&&!navigator.onLine)return void this.safeEmit(Ce.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const r={downlinkNetworkQuality:0,uplinkNetworkQuality:0};r.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),r.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(Ce.NETWORK_QUALITY,r)}),S(this,"_handleP2PAddAudioOrVideoStream",(r,o,s,a)=>{const c=this._users.find(l=>l.uid===o);if(!c)return void _.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));_.debug("[".concat(this._clientId,"] stream added with uid ").concat(o,", type ").concat(r)),this.store.subscribe(c.uid,r,void 0,void 0,void 0,Date.now());const d=r==="audio"?c.hasAudio:c.hasVideo;r==="audio"?c._trust_audio_stream_added_state_=!0:c._trust_video_stream_added_state_=!0,r==="audio"?(c._audio_added_=!0,s!==void 0&&(c._audioSSRC=s),a!==void 0&&(c._audioMid=a)):(c._video_added_=!0,s!==void 0&&(c._videoSSRC=s),a!==void 0&&(c._videoMid=a)),(r==="audio"?c.hasAudio:c.hasVideo)&&!d&&(_.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published ").concat(r)),this.safeEmit(Ce.USER_PUBLISHED,c,r)),this._p2pChannel.hasPendingRemoteMedia(c,r)&&(_.debug("[".concat(this._clientId,"] resubscribe ").concat(r," for user ").concat(c.uid," after reconnect.")),this._subscribe(c,r,!0).catch(l=>{_.error("[".concat(this._clientId,"] resubscribe error"),l.toString())}))}),this._config=e,this._clientId=t||Qe(5,"client-"),this.store=new class{constructor(r,o,s,a,c){ge(this,"state",void 0),this.state={codec:r,audioCodec:o,mode:s,clientId:a,sessionId:null,p2pId:0,dcId:0,pubId:0,subId:0,keyMetrics:{publish:[],subscribe:[],firstVideoFrameDecoded:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useP2P:!1,p2pTransport:ka.Default,hasStartJoinChannel:!1,isABTestSuccess:!1,rteUrl:void 0,rteSid:void 0,autoSubscribe:!1,enableInstantMuteRestore:!1,networkQualityProbe:!1,useDcSignal:!!c,preSubOptions:void 0}}dispatch(r){this.state=function(o,s){switch(s.type){case pe.SET_SESSION_ID:return j(j({},o),{},{sessionId:s.sessionId});case pe.SET_P2P_ID:return j(j({},o),{},{p2pId:s.p2pId});case pe.SET_UID:return j(j({},o),{},{uid:s.uid});case pe.SET_INT_UID:return j(j({},o),{},{intUid:s.intUid});case pe.SET_PUB_ID:return j(j({},o),{},{pubId:s.pubId});case pe.KEY_METRIC_CLIENT_CREATED:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{clientCreated:s.metric})});case pe.KEY_METRIC_JOIN_START:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{joinStart:s.metric})});case pe.KEY_METRIC_PRELOAD_START:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{preloadStart:s.metric})});case pe.KEY_METRIC_PRELOAD_END:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{preloadEnd:s.metric})});case pe.KEY_METRIC_JOIN_END:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{joinEnd:s.metric})});case pe.KEY_METRIC_REQUEST_AP_START:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{requestAPStart:s.metric})});case pe.KEY_METRIC_REQUEST_AP_END:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{requestAPEnd:s.metric})});case pe.KEY_METRIC_REQUEST_SUA_END:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{requestSUAEnd:s.metric})});case pe.KEY_METRIC_BEFORE_CONNECT:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{beforeConnect:s.metric})});case pe.KEY_METRIC_PEER_RECEIVER:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{peerReceiver:s.metric})});case pe.KEY_METRIC_SIGNAL_CONNECTED:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{signalConnected:s.metric})});case pe.KEY_METRIC_JOIN_REQ:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{joinReq:s.metric})});case pe.KEY_METRIC_JOIN_REP:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{joinRep:s.metric})});case pe.KEY_METRIC_JOIN_GATEWAY_START:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{joinGatewayStart:s.metric})});case pe.KEY_METRIC_JOIN_GATEWAY_END:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{joinGatewayEnd:s.metric})});case pe.KEY_METRIC_PEER_CONNECTION_START:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{peerConnectionStart:s.metric})});case pe.KEY_METRIC_PEER_CONNECTION_END:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{peerConnectionEnd:s.metric})});case pe.KEY_METRIC_DESCRIPTION_START:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{descriptionStart:s.metric})});case pe.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{signalChannelOpen:s.metric})});case pe.KEY_METRIC_ICE_CONNECTION_END:return j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{iceConnectionEnd:s.metric})});case pe.KEY_METRIC_PUBLISH:{const a=o.keyMetrics.publish,c=a.findIndex(d=>d.trackId===s.metric.trackId);return c!==-1?(a[c]=j(j({},a[c]),s.metric),j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{publish:[...a]})})):j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{publish:[...o.keyMetrics.publish,s.metric]})})}case pe.KEY_METRIC_SUBSCRIBE:{const a=o.keyMetrics.subscribe,c=a.findIndex(d=>d.userId===s.metric.userId&&d.type===s.metric.type);return c!==-1?(a[c]=j(j({},a[c]),s.metric),j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{subscribe:[...a]})})):j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{subscribe:[...o.keyMetrics.subscribe,s.metric]})})}case pe.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED:{const a=o.keyMetrics.first
113VideoFrameDecoded,c=a.findIndex(d=>d.userId===s.metric.userId);return c!==-1?(a[c]=j(j({},a[c]),s.metric),j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{firstVideoFrameDecoded:[...a]})})):j(j({},o),{},{keyMetrics:j(j({},o.keyMetrics),{},{firstVideoFrameDecoded:[...o.keyMetrics.firstVideoFrameDecoded,s.metric]})})}case pe.RESET_FIRST_VIDEO_FRAME_DECODED:return o.keyMetrics.firstVideoFrameDecoded=[],o;case pe.SET_CLOUD_PROXY_SERVER_MODE:return o.cloudProxyServerMode=s.mode,o;case pe.RECORD_JOIN_CHANNEL_SERVICE:return typeof s.index!="number"?o.joinChannelServiceRecords=[...o.joinChannelServiceRecords,s.record]:(o.joinChannelServiceRecords[s.index]=j(j({},o.joinChannelServiceRecords[s.index]),s.record),o.joinChannelServiceRecords=[...o.joinChannelServiceRecords]),o;case pe.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return o.joinChannelServiceRecords=[],o;case pe.RESET_KEY_METRICS:return o.keyMetrics={publish:[],subscribe:[],firstVideoFrameDecoded:[]},o;case pe.SET_USE_P2P:return j(j({},o),{},{useP2P:s.val});case pe.SET_TRANSPORT_TYPE:return j(j({},o),{},{p2pTransport:s.val});case pe.SET_RTE_URL:return j(j({},o),{},{rteUrl:s.rteUrl});case pe.SET_RTE_SID:return j(j({},o),{},{rteSid:s.rteSid});default:return o}}(this.state,r)}get useDcSignal(){return this.state.useDcSignal}set useDcSignal(r){this.state.useDcSignal=r}set autoSubscribe(r){this.state.autoSubscribe=r}get autoSubscribe(){return this.state.autoSubscribe}set enableInstantMuteRestore(r){this.state.enableInstantMuteRestore=r}get enableInstantMuteRestore(){return this.state.enableInstantMuteRestore}set networkQualityProbe(r){this.state.networkQualityProbe=r}get networkQualityProbe(){return this.state.networkQualityProbe}set preSubOptions(r){this.state.preSubOptions=r}get preSubOptions(){return this.state.preSubOptions}set sessionId(r){this.dispatch({type:pe.SET_SESSION_ID,sessionId:r})}get sessionId(){return this.state.sessionId}
113set rteUrl(r){this.dispatch({type:pe.SET_RTE_URL,rteUrl:r})}get rteUrl(){return this.state.rteUrl}set rteSid(r){this.dispatch({type:pe.SET_RTE_SID,rteSid:r})}get rteSid(){return this.state.rteSid}set cid(r){this.state.cid=r}get cid(){return this.state.cid}set codec(r){this.state.codec=r}get codec(){return this.state.codec}get mode(){return this.state.mode}get audioCodec(){return this.state.audioCodec}get clientId(){return this.state.clientId}set p2pId(r){this.dispatch({type:pe.SET_P2P_ID,p2pId:r})}get p2pId(){return this.state.p2pId}set dcId(r){this.dispatch({type:pe.SET_DC_ID,dcId:r})}get dcId(){return this.state.dcId}set uid(r){this.dispatch({type:pe.SET_UID,uid:r})}get uid(){return this.state.uid}set intUid(r){this.dispatch({type:pe.SET_INT_UID,intUid:r})}get intUid(){return this.state.intUid}set pubId(r){this.dispatch({type:pe.SET_PUB_ID,pubId:r})}get pubId(){return this.state.pubId}set cloudProxyServerMode(r){this.dispatch({type:pe.SET_CLOUD_PROXY_SERVER_MODE,mode:r})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useP2P(r){this.dispatch({type:pe.SET_USE_P2P,val:r})}get useP2P(){return this.state.useP2P}set p2pTransport(r){this.dispatch({type:pe.SET_TRANSPORT_TYPE,val:r})}get p2pTransport(){return this.state.p2pTransport}set hasStartJoinChannel(r){this.state.hasStartJoinChannel=r}get hasStartJoinChannel(){return this.state.hasStartJoinChannel}set isABTestSuccess(r){this.state.isABTestSuccess=r}get isABTestSuccess(){return this.state.isABTestSuccess}clientCreated(){this.dispatch({type:pe.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:pe.KEY_METRIC_JOIN_START,metric:Date.now()})}preloadStart(){this.dispatch({type:pe.KEY_METRIC_PRELOAD_START,metric:Date.now()})}preloadEnd(){this.dispatch({type:pe.KEY_METRIC_PRELOAD_END,metric:Date.now()})}joinEnd(){this.dispatch({type:pe.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:pe.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:pe.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}requestSUAEnd(){this.dispatch({type:pe.KEY_METRIC_REQUEST_SUA_END,metric:Date.now()})}beforeConnect(){this.dispatch({type:pe.KEY_METRIC_BEFORE_CONNECT,metric:Date.now()})}peerReceiver(){this.dispatch({type:pe.KEY_METRIC_PEER_RECEIVER,metric:Date.now()})}signalConnected(){this.dispatch({type:pe.KEY_METRIC_SIGNAL_CONNECTED,metric:Date.now()})}joinReq(){this.dispatch({type:pe.KEY_METRIC_JOIN_REQ,metric:Date.now()})}joinRep(){this.dispatch({type:pe.KEY_METRIC_JOIN_REP,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:pe.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:pe.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:pe.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:pe.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}firstVideoFrameDecoded(r,o){this.dispatch({type:pe.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED,metric:j({userId:r},o)})}descriptionStart(){this.dispatch({type:pe.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:pe.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:pe.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(r,o,s,a){this.dispatch({type:pe.KEY_METRIC_PUBLISH,metric:j(j({trackId:r,type:o},s&&{publishStart:s}),a&&{publishEnd:a})})}subscribe(r,o,s,a,c,d,l){this.dispatch({type:pe.KEY_METRIC_SUBSCRIBE,metric:j(j(j(j(j({userId:r,type:o},s&&{subscribeStart:s}),a&&{subscribeEnd:a}),c&&{firstFrame:c}),d&&{streamAdded:d}),l&&{firstDecoded:l})})}massSubscribe(r,o,s,a){r.forEach(c=>{this.dispatch({type:pe.KEY_METRIC_SUBSCRIBE,metric:j(j(j({userId:c.userId,type:c.type},o&&{subscribeStart:o}),s&&{subscribeEnd:s}),a&&{firstFrame:a})})})}get keyMetrics(){return this.state.keyMetrics}recordJoinChannelService(r,o){r.service==="gateway"&&Array.isArray(r.urls)&&(r.urls=r.urls.map(s=>s.replace(/(\d+)-\d+-\d+-(\d+)/,"$1-*-*-$2")));try{return typeof o!="number"?(this.dispatch({type:pe.RECORD_JOIN_CHANNEL_SERVICE,record:j(j({},r),{},{sessionId:this.sessionId,cloudProxyMode:this.cloudProxyServerMode,uid:this.uid})}),this.state.joinChannelServiceRecords.length-1):(o<0||o>=this.state.joinChannelServiceRecords.length||this.dispatch({type:pe.RECORD_JOIN_CHANNEL_SERVICE,record:r,index:o}),o)}catch{return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:pe.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:pe.RESET_KEY_METRICS})}resetFirstVideoFrameDecoded(){this.dispatch({type:pe.RESET_FIRST_VIDEO_FRAME_DECODED})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch{return[]}}}(e.codec,e.audioCodec,e.mode,this._clientId,T("SIGNAL_CHANNEL")===1),this._leaveMutex=new An("client-leave",this._clientId),this._publishMutex=new An("client-publish",this._clientId),this._renewTokenMutex=new An("client-renewtoken",this._clientId),this._subscribeMutex=new An("client-subscribe",this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),_.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(qi," build: ").concat(mS,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{tS(e.clientRoleOptions),n=Object.assign({},e.clientRoleOptions)}catch(r){_.warning("[".concat(this._clientId,"] ").concat(r.toString()))}var i;this._statsCollector=new Bu(this.store),this._statsCollector.onStatsException=(r,o,s)=>{_.warn("[".concat(this._clientId,"] receive exception msg, code: ").concat(r,", msg: ").concat(o,", uid: ").concat(s)),r===vv.VIDEO_ENCODE_FAILED&&this.localTracks.forEach(a=>{a instanceof Hp&&T("ENABLE_ENCODE_EXCEPTION")&&a.findClosestProfile()}
113),this.safeEmit(Ce.EXCEPTION,{code:r,msg:o,uid:s})},this._statsCollector.onUploadPublishDuration=(r,o,s,a)=>{const c=this._users.find(d=>d.uid===r);c&&(this.store.keyMetrics&&(this.store.firstVideoFrameDecoded(c.uid,{peerPublishDuration:s,peerPubStatusMs:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(c)),Z.peerPublishStatus(this._sessionId,{subscribeElapse:a,audioPublishDuration:o,videoPublishDuration:s,peer:c._uintid}))},this._statsCollector.onVideoCodecChanged=r=>{if(T("VIDEO_STANDARD_BITRATE_VERSION")&&(r==="av1"||r==="h265"||r==="h264")){const o=this.localTracks.find(s=>s instanceof pt);o&&o._saveEncodeBitrateRatio!==1&&o.setSaveEncodeBitrateRatio(r==="h264"?T("BASELINE_MORE_H264_BITRATE_RATIO"):void 0)}},this.store.useP2P=e.mode==="p2p",this._gateway=new hee(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||Bt,httpRetryConfig:e.httpRetryConfig||Bt,forceWaitGatewayResponse:e.forceWaitGatewayResponse===void 0||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:n}),this._configDistribute=new Iee(this._clientId,this.store),this.store.useP2P?(this._p2pChannel=(i={store:this.store,statsCollector:this._statsCollector},To("P2PChannel").create(i)),this._handleP2PEvents()):this._p2pChannel=new lc(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}async joinMeta(e,t,n,i,r){let o=!(arguments.length>5&&arguments[5]!==void 0)||arguments[5],s=arguments.length>6&&arguments[6]!==void 0&&arguments[6];at("JOIN_GATEWAY_USE_443PORT_ONLY",o),at("JOIN_GATEWAY_USE_DUAL_DOMAIN",s);const a=this._gateway.signal.websocket;return a instanceof oT&&(a.use443PortOnly=o,a.tryDoubleDomain=s),async function(c,d,l){fp.get(c)||fp.set(c,[]),gp.get(c)||gp.set(c,d),Do.get(c)||Do.set(c,0);const h=fp.get(c),u=gp.get(c);if(!h||!u)throw new Error("concurrent: deferQueue or maxConcurrency is null");if(Do.get(c)===u){const R=Bl();h.push(R),await R.promise}Do.set(c,Do.get(c)+1);for(var p=arguments.length,E=new Array(p>3?p-3:0),m=3;m<p;m++)E[m-3]=arguments[m];const g=await l(...E);return Do.set(c,Do.get(c)-1),Do.get(c)===u-1&&h.length>0&&(h[0].resolve(),h.shift()),Do.get(c)===0&&(fp.set(c,[]),gp.set(c,0),Do.set(c,0)),g}("client.join",T("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,n,i,r)}async join(e,t,n,i,r){const o=++this._numberOfJoinCount;this.store.joinStart(),i&&(this.store.uid=i);const s=(bp||bp||(bp=(window.location.protocol.split(":")[0]||"").toUpperCase(),bp))==="HTTPS",a=MO()?window.isSecureContext:"Browser Not Support";(!MO()&&!s||!window.isSecureContext)&&_.warning("The website must be running in a secure context (About secure context: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts ), otherwise the media collection will be restricted by the browser");let c;Z.setAppId(e);try{if(!n&&n!==null)throw new D(A.INVALID_PARAMS,"Invalid token: ".concat(n,". If you don not use token, set it to null"));if(n&&On(n,"token",1,2047),On(e,"appid",1,2047),n_(t),i&&$l(i),r)if(typeof r=="string")On(r,"optionalInfo",1,256),c=r;else{if(typeof r!="object")throw new D(A.INVALID_PARAMS,"Invalid options: options is not a string or object");{const{autoSubscribe:g,enableInstantMuteRestore:R,networkQualityProbe:v,preSubOptions:C}=r;g&&(xr(g,"autoSubscribe"),_.info("[".concat(this._clientId,"] join: autoSubscribe: ").concat(g)),this.store.autoSubscribe=g),R&&(xr(R,"enableInstantMuteRestore"),_.info("[".concat(this._clientId,"] join: enableInstantMuteRestore: ").concat(R)),this.store.enableInstantMuteRestore=R),v&&(xr(v,"networkQualityProbe"),_.info("[".concat(this._clientId,"] join: networkQualityProbe: ").concat(v)),this.store.networkQualityProbe=v),Array.isArray(C)&&(Lo(C,"preSubOptions"),C.forEach(w=>{$l(w.uid),function(b,y){if(typeof b!="string"&&!(b instanceof HTMLElement||b instanceof HTMLVideoElement))throw new L(A.INVALID_PARAMS,"".concat(y," should be a string or a HTML element"))}(w.element,"element")}),_.info("[".concat(this._clientId,"] join: preSubOptions: ").concat(C.map(w=>"".concat(w.uid,": ").concat(typeof w.element=="string"?w.element:w.element.i
113d)).join(","))),this.store.preSubOptions=C)}}}catch(g){throw Z.reportApiInvoke(La(),{name:vt.JOIN,options:[e,t,n,i],states:{isHttps:s,isSecureContext:a},tag:ht.TRACER}).onError(g),g}if(this._leaveMutex.isLocked&&(_.debug("[".concat(this._clientId,"] join: waiting leave operation")),(await this._leaveMutex.lock())(),_.debug("[".concat(this._clientId,"] join: continue"))),this._joinAndNotLeaveYet=!0,this.connectionState!=="DISCONNECTED"){const g=new D(A.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw Z.reportApiInvoke(La(),{name:vt.JOIN,options:[e,t,n,i],states:{isHttps:s,isSecureContext:a},tag:ht.TRACER}).onError(g),g}this._gateway.state="CONNECTING",this.store.preloadStart();const d=await Fv({appId:e,cname:t,uid:i,stringUid:typeof i=="string"?i:void 0,token:n||e,cloudProxyServer:this._cloudProxyServerMode});if(this.store.preloadEnd(),!this._joinAndNotLeaveYet)throw new D(A.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));const l=(d==null?void 0:d.sid)||La();_.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(o)),this._sessionId||(this._sessionId=l,this.store.sessionId=this._sessionId);const h=Z.reportApiInvoke(this._sessionId,{id:this._clientId,name:vt.JOIN,options:[e,t,n,i],states:{isHttps:s,isSecureContext:a},tag:ht.TRACER}),u=Bi(Bi(Bi({},this._rtmConfig),{},{role:this.role,clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:typeof i!="string"?i:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:n||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:c,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint,preload:!!d},this._remoteDefaultVideoStreamType!==void 0&&{defaultVideoStream:this._remoteDefaultVideoStreamType}),{},{apRequestDetail:T("AP_REQUEST_DETAIL")||void 0});if(this._useLocalAccessPoint&&(u.setLocalAPVersion=this._setLocalAPVersion),typeof i=="string"&&(u.stringUid=i,this._uintUid?(u.uid=this._uintUid,this._uintUid=void 0):u.uid=0),this._encryptionMode!=="none"&&this._encryptionSecret){if(u.aesmode=this._encryptionMode,u.aespassword=await(async g=>{const R=function(b){const y=window.atob(`MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu 114STM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+ 115HvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy 116xQiYDz3vqa6bP29adwIDAQAB`),N=new Uint8Array(new ArrayBuffer(y.length));for(let k=0;k<y.length;k+=1)N[k]=y.charCodeAt(k);return N}(),v=await window.crypto.subtle.importKey("spki",R,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]),C=$g(g),w=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},v,C);return function(b){let y="";for(let N=0;N<b.length;N+=1)y+=String.fromCharCode(b[N]);return window.btoa(y)}(new Uint8Array(w))})(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new D(A.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(u.aessalt=this._encryptionSalt)}if(this._encryptDataStream&&(this._encryptionMode==="aes-128-gcm2"||this._encryptionMode==="aes-256-gcm2"))if(this._encryptionSalt&&this._encryptionSecret)if(window.crypto.subtle){const g=new TextEncoder,R=T("USE_PURE_ENCRYPTION_MASTER_KEY")?g.encode(u.appId+this._encryptionSecret+this._encryptionSecret):g.encode(u.appId+u.cname+this._encryptionSecret);this._encryptDataStreamIv=await async function(v,C,w){const b=await window.crypto.subtle.importKey("raw",C,"PBKDF2",!1,["deriveBits","deriveKey"]),y=v==="aes-128-gcm2"?128:256,N=await window.crypto.subtle.deriveBits({name:"PBKDF2",iterations:HO,hash:"SHA-256",salt:w},b,y+J9);return new Uint8Array(N).subarray(y/8)}(this._encryptionMode,R,Pa(this._encryptionSalt)),this._encryptDataStreamKey=await async function(v,C,w){const b=await window.crypto.subtle.importKey("raw",C,"PBKDF2",!1,["deriveBits","deriveKey"]),y=v==="aes-128-gcm2"?128:256;return await window.crypto.subtle.deriveKey({name:"PBKDF2",iterations:HO,hash:"SHA-256",salt:w},b,{name:"AES-GCM",length:y},!0,["encrypt","decrypt"])}(this._encryptionMode,R,Pa(this._encryptionSalt))}else a?_.warning("[".concat(this._clientId,"] encrypt datastream must be running in a secure context, fallback to plain data stream")):_.warning("[".concat(this._clientId,"] current browser do not support WebCrypto ,fallback to plain data stream")),this._encryptDataStream=!1;else this._encryptDataStream=!1,_.debug("[".concat(this._clientId,"] no salt / secret, cannot support encrypt data stream, fallback to plain data stream"));
116this._startSession(this._sessionId,{channel:t,appId:e,stringUid:u.stringUid});const p=this._sessionId;setTimeout(()=>{this.connectionState==="CONNECTING"&&p===this._sessionId&&Z.joinChannelTimeout(this._sessionId,5)},5e3);try{var E;let g;const R=u.cloudProxyServer;if(x(E=["proxy3","proxy4","proxy5"]).call(E,R)){const y=T("PROXY_SERVER_TYPE3");Array.isArray(y)?u.proxyServer=y[0]:u.proxyServer=y}if(Z.setProxyServer(u.proxyServer),_.setProxyServer(u.proxyServer),this.store.requestAPStart(),T("ENABLE_JOIN_V4")&&u.cloudProxyServer==="disabled")try{u.stringUid&&!u.uid&&(u.uid=await Tv(u.stringUid,u,this._axiosCancelSource.token,this._config.httpRetryConfig||Bt,this.store).finally(()=>{this.store.requestSUAEnd()}),_.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(u.stringUid," => ").concat(u.uid))),_.debug("[".concat(this._clientId,"] try use best first frame line"));const y=await this._p2pChannel.startP2PConnection({isPreallocation:!0});g=await Ree(u,this._axiosCancelSource.token,this._config.httpRetryConfig||Bt,this.store,y),_.debug("[".concat(this._clientId,"] get serverInfo from sdp endpoint")),T("ENABLE_SDP_ENDPOINT_LOG")&&_.debug("[".concat(this._clientId,"] serverInfo: "),g)}catch(y){g=void 0,_.debug("[".concat(this._clientId,"] join channel with sdp endpoint failed, fallback to normal join ap"),y)}if(!g)if(d){if(_.debug("[".concat(this._clientId,"] get serverInfo Success from Preload Cache ").concat(u.stringUid?", ".concat(u.stringUid," => ").concat(d.intUid):""," ")),u.stringUid&&!u.uid&&(u.uid=d.intUid),g={gatewayInfo:d.ap.gatewayInfo},T("JOIN_WITH_FALLBACK_MEDIA_PROXY")&&u.turnServer.mode==="auto")if(d.ap.proxyInfo.addresses.length===0)_.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers");else{const y=(await RU(d.ap.proxyInfo,d.ap.gatewayInfo.uid)).map(N=>({turnServerURL:N.address,tcpport:N.tcpport||zt.tcpport,udpport:N.udpport||zt.udpport,username:N.username||zt.username,password:N.password||zt.password,forceturn:!1,security:!0}));u.turnServer={mode:"manual",servers:y}}b2(d,u.stringUid)}else{if(u.stringUid&&!u.uid){let y;[y,g]=await K.all([Tv(u.stringUid,u,this._axiosCancelSource.token,this._config.httpRetryConfig||Bt,this.store).finally(()=>{this.store.requestSUAEnd()}),XU(u,this._axiosCancelSource.token,this._config.httpRetryConfig||Bt,!0,this.store).finally(()=>{this.store.requestAPEnd()})]),_.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(u.stringUid," => ").concat(y)),u.uid=y,g.gatewayInfo.uid=y,g.gatewayInfo.res.uid=y}else g=await XU(u,this._axiosCancelSource.token,this._config.httpRetryConfig||Bt,!0,this.store);if(!this._joinAndNotLeaveYet)throw new D(A.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"))}this.store.requestAPEnd(),setTimeout(()=>{this._configDistribute.startGetConfigDistribute(u,this._axiosCancelSource.token),this._configDistribute.on(ho.UPDATE_BITRATE_LIMIT,y=>{this._p2pChannel.updateBitrateLimit(y)}),this._configDistribute.on(ho.UPDATE_CLIENT_ROLE_OPTIONS,y=>{this._setClientRoleOptions(y)}),this._configDistribute.on(ho.UPDATE_REMOTE_VIDEO_STREAM_TYPE,y=>{var N;x(N=[0,1,4,5,6,7,8,9]).call(N,y)&&(this.remoteUsers.forEach(k=>{this._remoteStreamTypeCacheMap.get(k.uid)!==y&&this.setRemoteVideoStreamType(k.uid,y)}),this.setRemoteDefaultVideoStreamType(y))}),this._configDistribute.on(ho.FALLBACK_TO_HLS,y=>{y&&this.safeEmit(Ce.FALLBACK_TO_HLS,nS.CONFIG)}),this._configDistribute.on(ho.UPDATE_VOS_CONFIGURE,y=>{this._gateway.setConfigure(y).catch(N=>{_.debug("[".concat(this._clientId,"] auto set vos config failed"),N)})})},0),this._key=n||e;const v=g.gatewayInfo,C=u.uid?u.uid:v.uid;this._joinInfo=Bi(Bi({},u),{},{cid:v.cid,uid:C,vid:v.vid,apResponse:v.res,apGatewayAddress:v.apGatewayAddress,uni_lbs_ip:v.uni_lbs_ip,gatewayAddrs:v.gatewayAddrs,signalResponse:v.res.signalResponse}),this.store.intUid=C,this.store.cid=v.cid;const w=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new D(A.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));h.onSuccess(w),this._appId=e,this._channelName=u.cname,this._uid=w,this.store.uid=w,setTimeout(()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),!vn()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(vn()?"beforeunload":"pagehide",this._handleBeforeUnload),this._statsCollector.startUpd
116ateStats()},0);const b=u.stringUid?"string uid: ".concat(u.stringUid,",uid: ").concat(u.uid):"uid: ".concat(this._uid);return _.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(b)),setTimeout(()=>{_.startUpload()},5e3),this.store.joinEnd(),m=this,x(Wa).call(Wa,m)||Wa.push(m),this._cloudProxyServerMode==="disabled"&&Oe().supportWebCrypto&&T("ENABLE_PRELOAD")&&Gv(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0),this._sessionId&&Z.reportRteDetail(this._sessionId),this._rteDetailInterval=window.setInterval(()=>{this._sessionId&&Z.reportRteDetail(this._sessionId)},T("RTE_DETAIL_REPORT_INTERVAL")||6e4),w}catch(g){const R=Array.isArray(g)?g[0]:g;throw R&&R.code===A.OPERATION_ABORTED?_.warning("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),R):_.error("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),R),R.code!==A.OPERATION_ABORTED&&this._numberOfJoinCount===o&&(this._gateway.state="DISCONNECTED",this._reset()),h.onError(R),R}var m}async _joinGateway(){if(!this._joinInfo||!this._key)throw new D(A.INVALID_OPERATION);try{return await this._gateway.join(this._joinInfo,this._key,!(this._joinInfo.cloudProxyServer!=="disabled"||this._joinInfo.proxyServer||!T("JOIN_WITH_FALLBACK_SIGNAL_PROXY")))}catch(e){if(e.code===A.INIT_DATACHANNEL_TIMEOUT){if(this._gateway.leave(!0,Pe.FALLBACK),_.debug("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new D(A.INVALID_OPERATION);return Z.reportApiInvoke(this._sessionId,{name:vt.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:ht.TRACER}).onSuccess(),await this._joinGateway()}throw e}}async leave(){_.info("[".concat(this._clientId,"] Leaving channel"));const e=()=>{!vn()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(vn()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(n){const i=Wa.indexOf(n);i!==-1&&Wa.splice(i,1)}(this),this._statsCollector.stopUpdateStats()};this.store.useDcSignal||e();const t=await this._leaveMutex.lock();if(this.connectionState==="DISCONNECTED")return _.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void t();await this._gateway.leave(this.connectionState!=="CONNECTED",Pe.LEAVE),_.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),t(),this.store.useDcSignal&&e()}async publish(e){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!Array.isArray(e)){if(!(e instanceof hd))return this._publishDataChannel(e);e=[e]}if(e.length===0)throw new D(A.INVALID_PARAMS,"param list is empty");const n=e;if(this._gateway.role==="audience")throw new D(A.INVALID_OPERATION,"audience can not publish stream");for(const r of n){if(!(r instanceof hd))throw new D(A.INVALID_PARAMS,"parameter is not local track");if(!r._enabled&&t)throw new D(A.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(r.getTrackId()))}_.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(n.map(r=>"".concat(r.getTrackId()," "))));const i=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&n.forEac
116h(r=>{const o=this._configDistribute.getBitrateLimit();r instanceof pt&&o&&r.setBitrateLimit(o.uplink)});try{await this._publishHighStream(n),_.info("[".concat(this._clientId,"] Publish success, id ").concat(n.map(r=>"".concat(r.getTrackId()," "))))}catch(r){throw _.error("[".concat(this._clientId,"] publish error"),r.toString()),r}finally{i()}}async _publishDataChannel(e){if(e==null)throw new D(A.INVALID_PARAMS,"parameter is not local track or datachannel config, config is ".concat(JSON.stringify(e)));ut(e.id,"id",0,65535,!0),xr(e.ordered,"ordered"),On(e.metadata,"metadata",0,512),_.info("[".concat(this._clientId,"] Publishing datachannels, id ").concat(e.id));const t=await this._publishMutex.lock();try{if(this._p2pChannel.getAllDataChannels().findIndex(r=>r.id===e.id)!==-1)throw new D(A.INVALID_PARAMS,"Invalid id: ".concat(e.id,". If you want to republish the datachannel, unpublish first"));if(!this._joinInfo||this._uid===void 0)throw new D(A.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if(this._turnServer.mode==="auto"&&T("FORCE_TURN")&&!T("TURN_ENABLE_TCP")&&!T("TURN_ENABLE_UDP"))throw new D(A.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const n=function(r){return FU(r,!1)}(e),i=await this._p2pChannel.publishDataChannel([n]);if(i.length>0){if(typeof n._originDataChannelId!="number")throw _.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new D(A.CREATE_DATACHANNEL_ERROR);try{await K.all(i.map(r=>this._uid&&this._gateway.publishDataChannel(this._uid,r,!0))),await n._waitTillOpen()}catch(r){if(r.code!==A.DISCONNECT_P2P)throw r}}return _.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(n.id)),n}catch(n){throw _.error("[".concat(this._clientId,"] publish datachannels error"),n.toString()),n}finally{t()}}async unpublish(e){if(!this._joinInfo||this._uid===void 0)throw new D(A.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof hd))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);_.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(t.map(i=>"".concat(i.getTrackId()," "))," "));const n=await this._publishMutex.lock();try{if(this.store.useP2P){const i=await this._p2pChannel.unpublish(t);i&&await this._gateway.sendExtensionMessage(Zt.UNPUBLISH,{unpubMsg:i},!0)}else{const i=await this._p2pChannel.unpublish(t);i&&await this._gateway.unpublish(i,this._uid),_.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map(r=>"".concat(r.getTrackId()))))}}catch(i){throw _.error("[".concat(this._clientId,"] unpublish error"),i.toString()),i}finally{n&&n()}}async _unpublishDataChannel(e){e!==void 0&&e.length!==0||(e=this._p2pChannel.getAllDataChannels()),_.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(e.map(n=>"".concat(n.id," "))," "));const t=await this._publishMutex.lock();try{const n=await this._p2pChannel.unpublishDataChannel(e);n&&await this._gateway.unpublishDataChannel(n),_.info("[".concat(this._clientId,"] Unpublish dataChannel success, dataChannel ids: ").concat(e.map(i=>"".concat(i.id))))}catch(n){throw _.error("[".concat(this._clientId,"] unpublish dataChannel error"),n.toString()),n}finally{t&&t()}}async subscribe(e,t,n){if(!(e instanceof na)){const i=this.remoteUsers.find(r=>r.uid===e);if(!i)throw new D(A.INVALID_REMOTE_USER,"user is not in the channel");e=i}return t==="datachannel"?this._subscribeDataChannel(e,n):this._subscribe(e,t)}async presubscribe(e,t){if(nn(t,"mediaType",["audio","video"]),this.store.useP2P)throw new D(A.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new D(A.INVALID_OPERATION,"can't presub when not join");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new D(A.INVA
116LID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const n=t===$.AUDIO,i=t===$.VIDEO,r=await this._subscribeMutex.lock();try{const{ssrcId:o,ortc:s,rtxSsrcId:a,cname:c,uint_id:d}=await this._gateway.presubscribe(e,t,!0);if(o==null)throw new D(A.UNEXPECTED_RESPONSE,"no ssrc id");let l=this._users.find(u=>u.uid===e);l||(l=new na(e,d||e),l._is_pre_created=!0,this._users.push(l)),c&&(l._cname=c),l._uintid||(l._uintid=d||e),n&&(l._audioSSRC=o,l._audio_pre_subscribed=!0,s&&(l._audioOrtc=s)),i&&(l._videoSSRC=o,l._video_pre_subscribed=!0,s&&(l._videoOrtc=s),a!=null&&(l._rtxSsrcId=a)),_.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(o)),await this._p2pChannel.subscribe(l,t,o,a,s);const h=n?l._audioTrack:l._videoTrack;if(!h)throw new D(A.UNEXPECTED_ERROR,"can not find remote track in user");return n&&(l._trust_audio_stream_added_state_=!0,l._audio_added_=!0),i&&(l._trust_video_stream_added_state_=!0,l._video_added_=!0),h}catch(o){throw _.error("[".concat(this._clientId,"] presub user ").concat(e," error"),o),o}finally{r()}}async _subscribeDataChannel(e,t){var n;if(ut(t,"channelId",0,65535,!0),!this._joinInfo)throw new D(A.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));if(!this._users.find(s=>s===e))throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new D(A.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&e._dataChannels.length===0)throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new D(A.INVALID_REMOTE_USER,"user is not published");const i=(n=e._dataChannels)===null||n===void 0?void 0:n.find(s=>s.id===t);if(!i)throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new D(A.REMOTE_USER_IS_NOT_PUBLISHED);const r=await this._subscribeMutex.lock();_.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: datachannel"));try{const s=await this._p2pChannel.subscribeDataChannel(e,[i]);if(s&&x(s).call(s,i.id))try{var o;if(typeof i._originDataChannelId!="number")throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new D(A.CREATE_DATACHANNEL_ERROR);const a={id:i.id,datachannelId:i._originDataChannelId,ordered:i.ordered,maxRetransmits:i.maxRetransmits,metadata:(o=i.metadata)!==null&&o!==void 0?o:""};await this._gateway.subscribeDataChannel(e.uid,a,!0),await i._waitTillOpen()}catch(a){if((a==null?void 0:a.code)!==A.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[i]),a;await this._p2pChannel.unsubscribeDataChannel(e,[i]),this._p2pChannel.setPendingRemoteDataChannel(e,i.id)}return _.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),i}finally{r()}}async _p2pSubscribe(e,t,n){if(nn(t,"mediaType",["audio","video"]),!this._joinInfo)throw new D(A.INVALID_OPERATION,"Can't subscribe stream, not joined");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(r=>r===e)){const r=new D(A.INVALID_REMOTE_USER,"user is not in the channel");throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),r}if(!e.hasAudio&&!e.hasVideo){const r=new D(A.INVALID_REMOTE_USER,"user is not published");throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),r}if(!n&&(t==="audio"&&!e.hasAudio||t==="video"&&!e.hasVideo)){const r=new D(A.REMOTE_USER_IS_NOT_PUBLISHED);throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),r}const i=await this._subscribeMutex.lock();_.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const o=t==="audio"?e._audioSSRC:e._videoSSRC,s=t==="audio"?e._audioMid:e._videoMid;this.store.subscribe(e.uid,t,Date.now()),this.store.useP2P&&await this._p2pChannel.subscribe(e,t,o,s)}catch(o){throw o}_.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType!==void 0&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch(o=>{_.warning("[".concat(this._clientId,"] auto set fallback failed"),o)});const r=t==="audio"?e._audioTrack:e._videoTrack;if(!r)throw new D(A.UNEXPECTED_ERROR,"can not find remote track in user object");return r}catch(r){throw _.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),r),r}finally{i()}}async _subscribe(e,t,n){if(this.store.useP2P)return this._p2pSubscribe(e,t);if(nn(t,"mediaType",["audio","video"]),!this._joinInfo)throw new D(A.INVA
116LID_OPERATION,"Can't subscribe stream, not joined");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(c=>c===e)){const c=new D(A.INVALID_REMOTE_USER,"user is not in the channel");throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),c}if(!e.hasAudio&&!e.hasVideo){const c=new D(A.INVALID_REMOTE_USER,"user is not published");throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),c}if(!(n||(t!=="audio"||e.hasAudio&&e._audioSSRC!==void 0)&&(t!=="video"||e.hasVideo&&e._videoSSRC!==void 0))){const c=new D(A.REMOTE_USER_IS_NOT_PUBLISHED);throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),c}let i=t==="audio"?e._audioSSRC:e._videoSSRC,r=t==="audio"?e._audioOrtc:e._videoOrtc,o=t==="video"?e._rtxSsrcId:void 0,s={stream_type:t==="audio"?$.AUDIO:$.VIDEO,ssrcId:i};t==="video"&&this.store.firstVideoFrameDecoded(e.uid,{subscribeStart:Date.now()});const a=await this._subscribeMutex.lock();_.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const d=t==="audio"?e._audioSSRC:e._videoSSRC;d!==void 0&&d!==i&&(i=d,r=t==="audio"?e._audioOrtc:e._videoOrtc,o=t==="video"?e._rtxSsrcId:void 0,s={stream_type:t==="audio"?$.AUDIO:$.VIDEO,ssrcId:i}),jn.markSubscribeStart(this.store.clientId,i),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,i,o,r);try{this._p2pChannel.isPreSubScribe(i)||await this._gateway.subscribe(e.uid,s,!0)}catch(l){if((l==null?void 0:l.code)!==A.WS_ABORT)throw await this._p2pChannel.unsubscribe(e,t),l;await this._p2pChannel.unsubscribe(e,t,!0),this._p2pChannel.setPendingRemoteMedia(e,t)}this.store.subscribe(e.uid,t,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,e,t)}catch(d){throw this._p2pChannel.reportSubscribeEvent(!1,d==null?void 0:d.code,e,t),d}_.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),this._defaultStreamFallbackType!==void 0&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch(d=>{_.warning("[".concat(this._clientId,"] auto set fallback failed"),d)});const c=t==="audio"?e._audioTrack:e._videoTrack;if(!c)throw new D(A.UNEXPECTED_ERROR,"can not find remote track in user object");return t==="video"&&(this.store.firstVideoFrameDecoded(e.uid,{subscribeEnd:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(e)),c}catch(c){throw _.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),c),c}finally{a()}}async massSubscribe(e){if(Lo(e,"subscribeList"),!this._joinInfo)throw new D(A.INVALID_OPERATION,"Can't subscribe stream, not joined");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),n=new Map,i=await this._subscribeMutex.lock();_.info("[".concat(this._clientId,"]start massSubscribe user ").concat(e.map(a=>{let{user:c,mediaType:d}=a;return"user: ".concat(c==null?void 0:c.uid,", mediaType: ").concat(d)}).join("; ")));const r=(e=[...e]).map(a=>{let{user:c,mediaType:d}=a;return{user:c,mediaType:d}}),o=await this._p2pChannel.globalLock();try{var s;for(let c=e.length-1;c>=0;c--){const d=e[c],{user:l,mediaType:h}=d;if(nn(h,"mediaType",["audio","video"]),!l){const E=new D(A.INVALID_PARAMS,"user property does not exist in subscribeList item");throw _.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),E}if(!this._users.find(E=>E===l)){const E=new D(A.INVALID_REMOTE_USER,"user is not in the channel");_.error("[".concat(this._clientId,"] can not massSubscribe ").concat(l.uid,", this user is not in the channel")),r[c].error=E,e.splice(c,1);continue}if(h==="audio"&&(!l.hasAudio||l._audioSSRC===void 0)||h==="video"&&(!l.hasVideo||l._videoSSRC===void 0)){const E=new D(A.REMOTE_USER_IS_NOT_PUBLISHED);_.error("[".concat(this._clientId,"] can not subscribe ").concat(l.uid," with mediaType ").concat(h,", remote user is not published")),r[c].error=E,e.splice(c,1);continue}const u=fn.Video|fn.LowVideo,p=n.get(l);if(p){if(h==="video"?p&u:p&fn.Audio){e.splice(c,1),_.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(l.uid,", mediaType:").concat(h," twice"));continue}
116n.set(l,p|(h==="video"?u:fn.Audio))}else n.set(l,h==="video"?u:fn.Audio)}for(let c=e.length-1;c>=0;c--){const d=e[c],{user:l,mediaType:h}=d,u=fn.Video|fn.LowVideo;if(this._p2pChannel.hasRemoteMedia(l,h)){await this._p2pChannel.unmuteRemoteNoLock(l,h);const p=n.get(l);n.set(l,h==="video"?p^u:p^fn.Audio),e.splice(c,1)}}this.store.massSubscribe(e.map(c=>({userId:c.user.uid,type:c.mediaType})),t);let a=ei(s=Array.from(n.entries())).call(s,(c,d)=>{let[l,h]=d;if(h===0)return c;const u={stream_id:l.uid,stream_type:h};return h&fn.Audio&&(u.audio_ssrc=l._audioSSRC),h&fn.Video&&(u.video_ssrc=l._videoSSRC),c.push(u),c},[]);try{e.length>0&&await this._p2pChannel.massSubscribeNoLock(e.map(d=>{let{user:l,mediaType:h}=d;return{user:l,mediaType:h,ssrcId:h===$.VIDEO?l._videoSSRC:l._audioSSRC,rtxSsrcId:h===$.VIDEO?l._rtxSsrcId:void 0}}));const c=new Map;if(a=a.filter(d=>d.video_ssrc&&!this._p2pChannel.isPreSubScribe(d.video_ssrc)||d.audio_ssrc&&!this._p2pChannel.isPreSubScribe(d.audio_ssrc)||!d.video_ssrc&&!d.audio_ssrc),a.length>0){const d=await this._gateway.subscribeAll(a,!0);((d==null?void 0:d.users)||[]).forEach(l=>{let{stream_id:h,video_error_code:u,audio_error_code:p,error_code:E}=l;(u||p||E)&&c.set(h,{video_error_code:u,audio_error_code:p,error_code:E})})}if(Array.from(c.entries()).length>0){const d=[];Array.from(c.entries()).forEach(l=>{let[h,u]=l;const p=this.remoteUsers.find(E=>E.uid===h);if(p){let E;u.error_code||u.video_error_code&&u.audio_error_code?E=void 0:u.video_error_code?E=$.VIDEO:u.audio_error_code&&(E=$.AUDIO),d.push({user:p,mediaType:E})}}),d.length>0&&await this._p2pChannel.massUnsubscribeNoLock(d)}for(const d of r){const l=c.get(d.user.uid);if(l){const h=l.error_code||d.mediaType==="audio"&&l.audio_error_code||d.mediaType==="video"&&l.video_error_code;if(h){const u=Ha(h);_.error("user:".concat(d.user.uid," mediaType:").concat(d.mediaType," has massSubscribe error ").concat(u.desc)),d.error=new D(A.SUBSCRIBE_FAILED,"code ".concat(h,": ").concat(u.desc))}}d.error||(d.mediaType==="video"?d.track=d.user.videoTrack:d.track=d.user.audioTrack)}return this.store.massSubscribe(r.filter(d=>!d.error).map(d=>({userId:d.user.uid,type:d.mediaType})),void 0,Date.now()),r.forEach(d=>{var l;Z.subscribe(this.store.sessionId,{succ:!!d.error,ec:((l=d.error)===null||l===void 0?void 0:l.code)||null,video:d.mediaType===$.VIDEO,audio:d.mediaType===$.AUDIO,peerid:d.user.uid,subscribeRequestid:d.mediaType===$.VIDEO?d.user._videoSSRC:d.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t),preSsrc:this._p2pChannel.isPreSubScribe(d.user._videoSSRC)},!0)}),_.info("[".concat(this._clientId,"] massSubscribe success ").concat(e.map(d=>{let{user:l,mediaType:h}=d;return"user: ".concat(l==null?void 0:l.uid,", mediaType: ").concat(h)}).join("; "))),r}catch(c){throw await this._p2pChannel.massUnsubscribeNoLock(e),c}}finally{o(),i()}}async unsubscribe(e,t,n){if(!(e instanceof na)){const r=this.remoteUsers.find(o=>o.uid===e);if(!r)throw new D(A.INVALID_REMOTE_USER,"user is not in the channel");e=r}if(t||this.store.useP2P){if(t==="datachannel")return this._unsubscribeDataChannel(e,n)}else await this._unsubscribeDataChannel(e,n);if(t&&nn(t,"mediaType",["audio","video"]),!this._joinInfo)throw new D(A.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");if(!this._users.find(r=>r===e)){const r=new D(A.INVALID_REMOTE_USER,"user is not in the channel");throw _.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),r}_.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));const i=await this._subscribeMutex.lock();try{if(this.store.useP2P)await this._p2pChannel.unsubscribe(e,t);else{const r=await this._p2pChannel.unsubscribe(e,t);r&&await this._gateway.unsubscribe(r,e.uid),t&&t!=="audio"||(e._audio_pre_subscribed=!1),t&&t!=="video"||(e._video_pre_subscribed=!1),e._is_pre_created&&Cp(this._users,e),_.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}}catch(r){if(r.code===A.DISCONNECT_P2P)return void _.warning("disconnecting p2p, abort unsubscribe request.");throw _.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),r.toString()),r}finally{i()}}
116async _unsubscribeDataChannel(e,t){if(t&&ut(t,"id",0,65535,!0),!this._joinInfo)throw new D(A.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");if(!this._users.find(i=>i===e)){const i=new D(A.INVALID_REMOTE_USER,"user is not in the channel");throw _.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),i}let n;if(typeof t=="number"){const i=e._dataChannels.find(r=>r.id===t);i&&(n=[i])}else n=e._dataChannels;if(n===void 0){const i=new D(A.REMOTE_USER_IS_NOT_PUBLISHED);throw _.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),i}_.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(n.map(i=>i.id)));try{const i=await this._p2pChannel.unsubscribeDataChannel(e,n);i&&await this._gateway.unsubscribeDataChannel(i,e.uid),_.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(i))}catch(i){if(i.code===A.DISCONNECT_P2P)return void _.warning("disconnecting p2p, abort unsubscribe request.");throw _.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),i.toString()),i}}async massUnsubscribe(e){if(Lo(e,"unsubscribeList"),!this._joinInfo)throw new D(A.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");_.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(e.map(n=>{let{user:i,mediaType:r}=n;return"user: ".concat(i==null?void 0:i.uid,", mediaType: ").concat(r,";")}).join())),e=[...e];const t=new Map;for(let n=e.length-1;n>=0;n--){const{user:i,mediaType:r}=e[n];if(!i){const s=new D(A.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw _.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),s}if(nn(r,"mediaType",["video","audio",void 0]),!this._users.find(s=>s===i)){_.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(i.uid,", user is not in the channel")),e.splice(n,1);continue}const o=fn.Video|fn.LowVideo;if(t.has(i)){const s=t.get(i);let a;switch(r){case"video":a=s&o;break;case"audio":a=s&fn.Audio;break;default:a=s&(fn.Audio|o)}if(a){_.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(i.uid,",mediaType:").concat(r," twice.")),e.splice(n,1);continue}r?r==="audio"?t.set(i,s|fn.Audio):r==="video"&&t.set(i,s|o):t.set(i,s|fn.Audio|o)}else r?r==="audio"?t.set(i,fn.Audio):r==="video"&&t.set(i,o):t.set(i,fn.Audio|o)}try{const n=await this._p2pChannel.massUnsubscribe(e);n&&await this._gateway.massUnsubscribe(n),_.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(e.map(i=>{let{user:r,mediaType:o}=i;return"user: ".concat(r==null?void 0:r.uid,", mediaType: ").concat(o,";")}).join()))}catch(n){if(n.code===A.DISCONNECT_P2P)return void _.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw _.error("[".concat(this._clientId,"] massUnsubscribe error"),n.toString()),n}}async setLowStreamParameter(e){(function(n){if(!n)throw new L(A.INVALID_PARAMS);xt(n.width)||Zg(n.width,"streamParameter.width"),xt(n.height)||Zg(n.height,"streamParameter.height"),xt(n.framerate)||Zg(n.framerate,"streamParameter.framerate"),xt(n.bitrate)||ut(n.bitrate,"streamParameter.bitrate")})(e),(!e.width&&e.height||e.width&&!e.height)&&_.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),_.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));const t=this._configDistribute.getLowStreamConfigDistribute();if(t&&t.bitrate&&e.bitrate&&t.bitrate<e.bitrate&&(e.bitrate=t.bitrate),this._lowStreamParameter=e,this._isDualStreamEnabled)return this._p2pChannel.updateVideoStreamParameter(e,G.LocalVideoLowTrack)}async setDualStreamMode(e,t){nn(e,"mode",[0,1,-1]);try{switch(t&&await this.setLowStreamParameter(t),this._dualStreamMode=e,this._joinInfo?this._gateway.setDualStreamMode(e).catch(n=>{_.warning("[".concat(this._clientId,"] set dual stream mode failed"),n.toString())}):_.debug("[".concat(this._clientId,"] haven't joined yet, cache dual stream mode ").concat(e)),e){case td.AUTO_SIMULCAST_STREAM:_.info("[".concat(this._clientId,"] set dual stream mode to ").concat(e));break;case td.DISABLE_SIMULCAST_STREM:return this.disableDualStream();case td.ENABLE_SIMULCAST_STREAM:return this.enableDualStream()}}catch(n){throw _.error("[".concat(this._clientId,"] set dual stream mode error"),n.toString()),n}}async enableDualStream(){if(!Oe().supportDualStream)throw Z.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new D(A.NOT_SUPPORTED,"Your browser is not support dual stream");
116if(this._isDualStreamEnabled)throw new D(A.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw Z.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,this._dualStreamMode=td.ENABLE_SIMULCAST_STREAM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch(e=>{_.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())}),Z.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),_.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)return this._isDualStreamEnabled=!1,void _.info("[".concat(this._clientId,"] disable dual stream before join"));if(this._p2pChannel.getLocalMedia(G.LocalVideoLowTrack))try{const e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw Z.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,this._dualStreamMode=td.DISABLE_SIMULCAST_STREM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch(e=>{_.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())}),Z.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),_.info("[".concat(this._clientId,"] disable dual stream"))}}async setClientRole(e,t){if(function(i){nn(i,"role",["audience","host"])}(e),t&&tS(t),this.mode==="rtc"||this.mode==="p2p")throw _.warning("[".concat(this._clientId,"]").concat(this.mode," mode can not use setClientRole")),new D(A.INVALID_OPERATION,"".concat(this.mode," mode can not use setClientRole"));if(t&&t.level&&e==="host")throw new D(A.INVALID_OPERATION,"host mode can not set audience latency level");if(e==="audience"&&this._p2pChannel.hasLocalMedia())throw new D(A.INVALID_OPERATION,"can not set client role to audience when publishing stream");const n=this._config.role;if(this._joinInfo&&(this._joinInfo.role=e),e!==n&&T("ENABLE_ROLE_SELECT_EDGE")?(this._gateway.updateClientRole(e,t),this._config.role=e,this._gateway.reconnect("recover",Vn.REGIONAL_DISTRIBUTION)):(await this._gateway.setClientRole(e,t),this._config.role=e),_.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level)),n==="audience"&&e!=="audience"&&this._pendingRtpCapabilityChange&&this._p2pChannel instanceof lc){const{video_codec:i}=this._pendingRtpCapabilityChange;this._p2pChannel.updateRemoteRTPCapabilities(i.map(r=>r.toLowerCase()).filter(r=>{var o;return x(o=Object.keys(Ma)).call(o,r)}))}}async _setClientRoleOptions(e){if(this.mode==="rtc"||this.mode==="p2p"||this._config.role!=="audience"||this._p2pChannel.hasLocalMedia())return;let t=!1;try{e&&tS(e),await this._gateway.setClientRole(this._config.role,e),t=!0}catch{}finally{_.info("[".concat(this._clientId,"] set client role options ").concat(t?"succeed":"failed",", options is ").concat(e))}}getRemoteInboundOffset(){var e;const t=(e=this._p2pChannel.getStats())===null||e===void 0?void 0:e.audioSend[0];if(!t||!t.timestamp)return 0;const n=t.timestamp-Date.now();return Math.abs(n)>1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?n:0}getNtpWallTimeInMs(){return document.visibilityState==="visible"&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(e,t){if(On(e,"proxyServer"),!t){if(this.connectionState!=="DISCONNECTED")throw new D(A.INVALID_OPERATION,"Set proxy server before join channel");if(this._cloudProxyServerMode!=="disabled"||this._useLocalAccessPoint)throw new D(A.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,Z.setProxyServer(this._proxyServer),_.setProxyServer(this._proxyServer),_.info("[".concat(this._clientId,"] Set proxy server ").concat(t?"by initialize call":""," success."))}setTurnServer(e,t){if(Array.isArray(e)||(e=[e]),!t){if(this.connectionState!=="DISCONNECTED")throw new D(A.INVA
116LID_OPERATION,"Set turn server before join channel");if(this._cloudProxyServerMode!=="disabled"||this._useLocalAccessPoint)throw new D(A.INVALID_OPERATION,"You have already set the proxy")}if(wa(e))return this._turnServer={servers:e,mode:"original-manual"},void _.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map(n=>n.urls).join(","),"."));e.forEach(n=>AO(n)),this._turnServer={servers:e,mode:"manual"},_.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if(this.connectionState!=="DISCONNECTED")throw new D(A.INVALID_OPERATION,"you should set license before join channel");if(On(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new D(A.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,_.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if(this.connectionState!=="DISCONNECTED")throw new D(A.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||this._turnServer.mode==="manual"||this._useLocalAccessPoint)throw new D(A.INVALID_OPERATION,"You have already set the proxy");const t=[3,4,5];let n;switch(e===void 0&&(e=3),e){case 1:case 2:throw new D(A.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:n="proxy3";break;case 4:n="proxy4";break;case 5:n="proxy5";break;default:throw new D(A.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=n,this.store.cloudProxyServerMode=n,_.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if(this.connectionState!=="DISCONNECTED")throw new D(A.INVALID_OPERATION,"Stop proxy server after leave channel");Z.setProxyServer(),_.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",_.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode),this._proxyServer=void 0,this._turnServer={mode:"auto",servers:[]}}setLocalAccessPointsV2(e){if(!e.accessPoints)throw new D(A.INVALID_PARAMS,"accessPoints is required.");Lo(e.accessPoints.serverList,"accessPoints.serverList"),On(e.accessPoints.domain,"accessPoints.domain");const t=(u,p)=>{ut(u,p,0,65535,!0)};let n=443;if(e.accessPoints.port&&(t(e.accessPoints.port,"accessPoints.port"),n=e.accessPoints.port),this._proxyServer||this._cloudProxyServerMode!=="disabled")throw new D(A.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");T("CLOSE_AFB_FOR_LOCAL_AP")&&(at("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),at("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const i=/^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,r=e.accessPoints.domain,o=e.accessPoints.serverList.map(u=>i.test(u)?"".concat(u.replace(/\./g,"-"),".").concat(r):u),s=o.map(u=>"".concat(u,":").concat(n));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,at("WEBCS_DOMAIN",s),at("WEBCS_DOMAIN_BACKUP_LIST",s),at("GATEWAY_DOMAINS",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(Lo(e.report.hostname,"report.hostname"),at("EVENT_REPORT_DOMAIN",e.report.hostname[0]),at("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(at("EVENT_REPORT_DOMAIN",o[0]),at("EVENT_REPORT_BACKUP_DOMAIN",o[1]||o[0]));let a=6443;e.report&&e.report.port&&(t(e.report.port,"report.port"),a=e.report.port),at("STATS_COLLECTOR_PORT",a),e.report?at("ENABLE_EVENT_REPORT",!0):at("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(Lo(e.log.hostname,"log.hostname"),c=e.log.hostname[0]):c=o[0];let d=6444;e.log&&e.log.port&&(t(e.log.port,"log.port"),d=e.log.port),at("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(Lo(e.cds.hostname,"cds.hostname"),l=e.cds.hostname):l=o;let h=443;e.cds&&e.cds.port&&(t(e.cds.port,"cds.port"),h=e.cds.port),at("CDS_AP",l.map(u=>"".concat(u,":").concat(h))),e.cds?at("ENABLE_CONFIG_DISTRIBUTE",!0):at("ENABLE_CONFIG_DISTRIBUTE",!1),_.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(Lo(e,"serverList"),On(t,"domain"),this._proxyServer||this._cloudProxyServerMode!=="disabled")throw new D(A.INVA
116LID_OPERATION,"set local access point failed, You have already set the cloud proxy");const n=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;e=e.map(i=>n.test(i)?"".concat(i.replace(/\./g,"-"),".").concat(t):i),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,at("WEBCS_DOMAIN",e),at("WEBCS_DOMAIN_BACKUP_LIST",e),at("GATEWAY_DOMAINS",[t]),at("EVENT_REPORT_DOMAIN",e[0]),at("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),at("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),_.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(e){if(nn(e,"streamType",[0,1,4,5,6,7,8,9]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(t){throw _.error("[".concat(this._clientId,"] set default remote video stream type error"),t.toString()),t}else _.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e))}async setRemoteVideoStreamType(e,t){nn(t,"streamType",[0,1,4,5,6,7,8,9]);try{await this._gateway.setRemoteVideoStreamType(e,t),setTimeout(()=>{const n=this._users.find(i=>i.uid===e);n&&n.videoTrack&&n.videoTrack.updateMediaStreamTrackResolution()},2e3)}catch(n){throw _.error("[".concat(this._clientId,"] set remote video stream type error"),n.toString()),n}_.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){nn(t,"fallbackType",[0,1,2,3,4,5,6,7,8]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(n){throw _.error("[".concat(this._clientId,"] set stream fallback option"),n.toString()),n}_.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,n,i){(function(o){nn(o,"encryptionMode",["aes-128-xts","aes-256-xts","aes-128-ecb","sm4-128-ecb","aes-128-gcm","aes-256-gcm","aes-128-gcm2","aes-256-gcm2","none"])})(e),On(t,"secret");const r=["aes-128-gcm2","aes-256-gcm2"];if(x(r).call(r,e)){if(!n||!(n instanceof Uint8Array&&n.length===32))throw new D(A.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(n)throw new D(A.INVALID_PARAMS,"current encrypt mode does not need salt");if(i){if(xr(i,"encryptDataStream"),!x(r).call(r,e))throw new D(A.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0}new RegExp(`^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'"|{}\\[\\]])(?=.{8,})`).test(t)||_.warning(`The secret is not strong: 117 The secret must contain at least 1 lowercase alphabetical character, 118 The secret must contain at least 1 uppercase alphabetical character, 119 The secret must contain at least 1 numeric character, 120 The secret must contain at least one special character, 121 The secret must be eight characters or longer. 122 `),this._encryptionMode=e,this._encryptionSecret=t,n&&(this._encryptionSalt=Us(n))}async renewToken(e){if(On(e,"token",1,2047),!this._key||!this._joinInfo)throw new D(A.INVALID_OPERATION,"renewToken should not be called before user join");const t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);const n=await this._renewTokenMutex.lock();try{if(T("USE_NEW_TOKEN")){_.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const i=await yee(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||Bt);_.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:i})}else _.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});_.debug("[".concat(this._clientId,"] renewToken success"))}catch(i){throw this._key=t,this._joinInfo.token=t,_.error("[".concat(this._clientId,"] renewToken failed"),i.toString()),i}finally{n()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?_.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval(()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(Ce.VOLUME_INDICATOR,e)}
122,T("AUDIO_VOLUME_INDICATION_INTERVAL")||2e3)}getRTCStats(){const e=this._statsCollector.getRTCStats(),t=this._gateway.getInChannelInfo();return e.Duration=Math.round(t.duration/1e3),e}async startLiveStreaming(e,t){if(!t){if(this.codec!=="h264")throw new D(A.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new D(A.LIVE_STREAMING_INVALID_RAW_STREAM,"can not find stream to raw streaming")}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(e)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(e))throw new D(A.LIVE_STREAMING_TASK_CONFLICT);const n=t?cs.TRANSCODE:cs.RAW;return this._createLiveStreamingClient(n).startLiveStreamingTask(e,n)}setLiveTranscoding(e){return this._createLiveStreamingClient(cs.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter(n=>n&&n.hasUrl(e));if(!t.length)throw new D(A.INVALID_PARAMS,"can not find live streaming url to stop");await K.all(t.map(n=>n&&n.stopLiveStreamingTask(e)))}async startChannelMediaRelay(e){QU(e),await this._createChannelMediaRelayClient().startChannelMediaRelay(e)}async updateChannelMediaRelay(e){QU(e),await this._createChannelMediaRelayClient().updateChannelMediaRelay(e)}async stopChannelMediaRelay(){await this._createChannelMediaRelayClient().stopChannelMediaRelay(),this._statsCollector.onStatsChanged&&(this._statsCollector.onStatsChanged=void 0)}sendAudioMetadata(e){this._p2pChannel instanceof lc&&this._p2pChannel.addAudioMetadata(e)}async sendStreamMessage(e){var t;let n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!this._joinInfo)throw new D(A.INVALID_OPERATION,"can not send data stream, not joined");if((typeof e=="string"||e instanceof Uint8Array)&&(e={payload:e}),typeof e.payload=="string"){const r=new TextEncoder;e.payload=r.encode(e.payload)}let i=!1;if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&x(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)&&(i=!0,e.payload=await async function(r,o,s){var a;const c=ei(a=Array.from(s)).call(a,(m,g)=>m+g,0),d={serverTs:0,seq:z9++,length:s.length,checkSum:c},l=new Uint8Array(PO(c,2)),h=new ArrayBuffer(ad),u=new DataView(h);u.setUint32(0,d.serverTs),u.setUint16(4,d.seq),u.setUint16(6,d.length),u.setUint16(8,d.checkSum);const p=16-s.length%16;s=bO(s,new Uint8Array(p));const E=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r,tagLength:KO,additionalData:l},o,s);return bO(new Uint8Array(h),new Uint8Array(E))}(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload)),new Blob([e.payload]).size>1024)throw new D(A.INVALID_PARAMS,i?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(ie.DATA_STREAM,{payload:Us(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-Mee},!n)}sendMetadata(e){if(!this._joinInfo)throw new D(A.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new D(A.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(ie.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:Us(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(iX),!this._joinInfo)throw new D(A.INVALID_OPERATION,"can not send custom report, not joined");await Z.sendCustomReportMessage(this._joinInfo.sid,e)}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats()}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats()}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats()}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats()}getRemoteNetworkQuality(){const e=this._statsCollector.getRemoteNetworkQualityStats();if(T("DELETE_NEQ_AFTER_USER_LEAVE")){const t=this._users.map(n=>n.uid+"");Object.keys(e).forEach(n=>{x(t).call(t,n)||delete e[n]})}return e}getNetworkQuality(){return this._statsCollector.getNetworkQuality()}
122async pickSVCLayer(e,t){nn(t.spatialLayer,"spatialLayer",[0,1,2,3]),nn(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(n){throw _.error("[".concat(this._clientId,"] pick SVC layer failed"),n.toString()),n}}async setRTMConfig(e){const{apRTM:t=!1,rtmFlag:n}=e;if(xr(t,"apRTM"),ut(n,"rtmFlag",0),this._rtmConfig.apRTM=t,this._rtmConfig.rtmFlag=n,_.debug("[".concat(this._clientId,"] setRTMconfig ").concat(JSON.stringify(e)," in ").concat(this.connectionState," state")),(this.connectionState==="CONNECTED"||this.connectionState==="RECONNECTING")&&this._joinInfo)return this._joinInfo.apRTM=t,this._joinInfo.rtmFlag=n,this._gateway.setRTM2Flag(n)}_reset(){if(_.debug("[".concat(this._clientId,"] reset client")),function(e){const t=gd.indexOf(e);t!==-1&&gd.splice(t,1)}(this._clientId),this.store.hasStartJoinChannel=!1,this.store.isABTestSuccess=!1,this.store.autoSubscribe=!1,this._pendingRtpCapabilityChange=void 0,this._axiosCancelSource.cancel(),this._axiosCancelSource=li.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo&&I2(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0,this._sessionId&&Z.reportRteDetail(this._sessionId)),this._fallbackServerInfo=void 0,this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId&&Z.removeSid(this._sessionId),this._sessionId=null,this.store.sessionId=null,this.store.resetFirstVideoFrameDecoded(),this._statsCollector.reset(),this._key=void 0,this._appId=void 0,this._uid=void 0,this.store.uid=void 0,this._channelName=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._encryptDataStreamKey=null,this._encryptDataStreamIv=null,this._pendingPublishedUsers=[],this._users.forEach(e=>{e._audioTrack&&e._audioTrack._destroy(),e._videoTrack&&e._videoTrack._destroy(),e._dataChannels&&(e._dataChannels.forEach(t=>t._close()),e._dataChannels.length=0)}),this._users=[],this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0),this._cloudProxyServerMode==="fallback"&&(this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled"),this._p2pChannel.reset(),this._publishMutex=new An("client-publish",this._clientId),this._subscribeMutex=new An("client-subscribe",this._clientId),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._liveRawStreamingClient&&(this._liveRawStreamingClient.terminate(),this._liveRawStreamingClient.removeAllListeners(),this._liveRawStreamingClient=void 0),this._liveTranscodeStreamingClient&&(this._liveTranscodeStreamingClient.terminate(),this._liveTranscodeStreamingClient.removeAllListeners(),this._liveTranscodeStreamingClient=void 0),this._channelMediaRelayClient&&(this._channelMediaRelayClient.dispose(),this._channelMediaRelayClient=void 0),this._inspect)try{this._inspect.close(),this._inspect=void 0}catch{}if(this._moderation)try{this.setImageModeration(!1)}catch{}}_startSession(e,t){var n;const i=e||La();e?_.debug("[".concat(this._clientId,"] new Session ").concat(i)):_.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(i));const r=e?"":this._sessionId||"";this._sessionId=i,this.store.sessionId=i,Z.addSid(i);const o={lts:new Date().getTime(),mode:this.mode,buildFormat:1,stringUid:(t==null?void 0:t.stringUid)||((n=this._joinInfo)===null||n===void 0?void 0:n.stringUid),channelProfile:this.mode==="live"?1:0,channelMode:0,isABTestSuccess:Number(this._configDistribute.isSuccess),lsid:r,clientRole:this.role==="audience"?2:1,rteUrl:this.store.rteUrl,rteSid:this.store.rteSid};Z.sessionInit(this._sessionId,Bi({cname:t.channel,appid:t.appId},o)),this._joinInfo&&(this._joinInfo.sid=i),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=i)}async _publishHighStream(e){if(!this._joinInfo||this._uid===void 0)throw new D(A.INVA
122LID_OPERATION,"Can't publish stream, haven't joined yet!");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if(this._turnServer.mode==="auto"&&T("FORCE_TURN")&&!T("TURN_ENABLE_TCP")&&!T("TURN_ENABLE_UDP"))throw new D(A.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");_.debug("[".concat(this._clientId,"] publish high stream"));try{const n=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this.store.useP2P){const i=(await n.next()).value;if(i){try{await this._gateway.sendExtensionMessage(Zt.PUBLISH,i,!0)}catch(r){throw n.throw(r),r}await n.next()}this._p2pChannel.reportPublishEvent(!0,null)}else{const i=(await n.next()).value;if(i){var t;let r;try{r=await this._gateway.publish(this._uid,i,!0)}catch(o){if(o.code!==A.DISCONNECT_P2P)throw n.throw(o),o}await n.next(((t=r)===null||t===void 0?void 0:t.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const r of e)r instanceof pt&&r._encoderConfig&&this._gateway.setVideoProfile(r._encoderConfig).catch(o=>{_.debug("[".concat(this._clientId,"] stop setVideoProfile, because websocket is closed"))}),!r.muted&&r.enabled||await this._p2pChannel.muteLocalTrack(r)}}catch(n){if(this._p2pChannel.reportPublishEvent(!1,n==null?void 0:n.code,e),(n==null?void 0:n.code)===A.WS_ABORT)return;throw n}}async _publishLowStream(){if(!this._joinInfo||this._uid===void 0)throw new D(A.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new D(A.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));_.debug("[".concat(this._clientId,"] publish low stream"));const e=this._configDistribute.getLowStreamConfigDistribute();e&&e.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&e.bitrate<this._lowStreamParameter.bitrate&&(this._lowStreamParameter.bitrate=e.bitrate));try{const n=await this._p2pChannel.publishLowStream(this._lowStreamParameter),i=(await n.next()).value;if(i){var t;let r;try{r=await this._gateway.publish(this._uid,i,!0)}catch(o){if(o.code!==A.DISCONNECT_P2P)throw n.throw(o),o}n.next(((t=r)===null||t===void 0?void 0:t.ortc)||[]),this._p2pChannel.reportPublishEvent(!0,null,void 0,!0)}}catch(n){if(this._p2pChannel.reportPublishEvent(!1,n==null?void 0:n.code,void 0,!0),(n==null?void 0:n.code)===A.WS_ABORT)return;throw n}}_createLiveStreamingClient(e){const t=()=>{if(!this._joinInfo||!this._appId)return new D(A.INVALID_OPERATION,"can not create live streaming client, please join channel first").throw();const n=(i={joinInfo:this._joinInfo,appId:this._appId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig},To("LiveStreaming").create(i));var i;return n.onLiveStreamError=(r,o)=>{Z.reportApiInvoke(this._sessionId,{name:vt.ON_LIVE_STREAM_ERROR,options:[r,o],tag:ht.TRACER}).onSuccess(),this.safeEmit(Ce.LIVE_STREAMING_ERROR,r,o)},n.onLiveStreamWarning=(r,o)=>{Z.reportApiInvoke(this._sessionId,{name:vt.ON_LIVE_STREAM_WARNING,options:[r,o],tag:ht.TRACER}).onSuccess(),this.safeEmit(Ce.LIVE_STREAMING_WARNING,r,o)},n.on(nT.REQUEST_WORKER_MANAGER_LIST,(r,o,s)=>{if(!this._joinInfo)return s(new D(A.INVALID_OPERATION,"can not find join info to get worker manager"));(async function(a,c,d,l){const h=T("UAP_AP").slice(0,T("AJAX_REQUEST_CONCURRENT")).map(u=>c.proxyServer?"https://".concat(c.proxyServer,"/ap/?url=").concat(u+"/api/v1?action=uap"):"https://".concat(u,"/api/v1?action=uap"));return await Eee(h,a,c,d,l)})(r,this._joinInfo,this._axiosCancelSource.token,Bt).then(o).catch(s)}),n};return e===cs.RAW?(this._liveRawStreamingClient=this._liveRawStreamingClient||t(),this._liveRawStreamingClient):(this._liveTranscodeStreamingClient=this._liveTranscodeStreamingClient||t(),this._liveTranscodeStreamingClient)}_createChannelMediaRelayClient(){if(!this._joinInfo)return new D(A.INVA
122LID_OPERATION,"can not create channel media relay client, please join channel first").throw();if(!this._channelMediaRelayClient){const{sendResolutionWidth:t,sendResolutionHeight:n}=this.getLocalVideoStats(),i=(e={joinInfo:this._joinInfo,clientId:this._clientId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig,resolution:{width:t,height:n}},To("ChannelMediaRelay").create(e));i.on("state",r=>{r===Ri.RELAY_STATE_FAILURE&&i&&i.dispose(),this.safeEmit(Ce.CHANNEL_MEDIA_RELAY_STATE,r)}),i.on("event",r=>{this.safeEmit(Ce.CHANNEL_MEDIA_RELAY_EVENT,r)}),this._channelMediaRelayClient=i,this._statsCollector.onStatsChanged=(r,o)=>{var s;r==="resolution"&&((s=this._channelMediaRelayClient)===null||s===void 0||s.setVideoProfile(o))}}var e;return this._channelMediaRelayClient}_handleFullDatachannel(e){const t=[],n=[];this._users.forEach(i=>{const r=i._dataChannels;r.forEach(o=>{e.some(s=>s.uid===i._uintid&&s.stream_id===o.id&&s.metadata===o.metadata)||t.push({uid:i._uintid,stream_id:o.id,ordered:o.ordered,max_retrans_times:o.maxRetransmits,metadata:o.metadata})}),e.filter(o=>o.uid===i._uintid).forEach(o=>{if(!r.some(s=>i._uintid===o.uid&&s.id===o.stream_id&&s.metadata===o.metadata)){const s=t.findIndex(a=>i._uintid===a.uid&&a.stream_id===o.stream_id);s!==-1&&(n.push(o),t.splice(s,1))}})}),this._handleDataChannelDeleted(t),this._handleDataChannelUpdated(n),this._handleDataChannelAdded(e,!0),_.debug("[".concat(this._clientId,"] emit full infos, data_channel ids: ").concat(e.map(i=>i.stream_id))),this.safeEmit(Ce.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]}_handleDataChannelAdded(e,t){const n=[];Array.isArray(e)&&e.length>0&&(_.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map(i=>i.stream_id)," added")),e.forEach(i=>{const{uid:r,stream_id:o,ordered:s,max_retrans_times:a,metadata:c}=i,d=this._users.find(l=>l._uintid===r);if(!d)return void _.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));if(_.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(r)),x(n).call(n,d)||n.push(d),d._uintid||(d._uintid=r),d._dataChannels.findIndex(l=>l.id===i.stream_id)!==-1){const l=d._dataChannels.find(h=>h.id===i.stream_id);l==null||l._updateDataChannelConfig(Bi(Bi({},l==null?void 0:l.getConfig()),{},{metadata:i.metadata}))}else{const l={id:o,ordered:!!s,maxRetransmits:a,metadata:c},h=function(u){return FU(u,!0)}(l);d._dataChannels.push(h),_.info("[".concat(this._clientId,"] remote user ").concat(d.uid," published datachannel")),t||this.safeEmit(Ce.USER_PUBLISHED,d,"datachannel",l)}this._p2pChannel.hasPendingRemoteDataChannel(d,i.stream_id)&&(_.debug("[".concat(this._clientId,"] resubscribe datachannel id: ").concat(i.stream_id," for user ").concat(d.uid," after reconnect.")),this._subscribeDataChannel(d,i.stream_id).catch(l=>{_.error("[".concat(this._clientId,"] resubscribe datachannel error"),l.toString())}))}))}_handleDataChannelUpdated(e){Array.isArray(e)&&e.length>0&&(_.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map(t=>t.stream_id)," updated")),e.forEach(t=>{var n;const{uid:i,stream_id:r,metadata:o}=t,s=this._users.find(c=>c._uintid===i);if(!s)return void _.error("[".concat(this._clientId,"] can not find target user!(on_update_data_channel)"));const a=s._dataChannels.find(c=>c.id===r);_.debug("[".concat(this._clientId,"] data_channel: ").concat(r," updated with uid ").concat(i,", last metadata: ").concat(a==null||(n=a._config)===null||n===void 0?void 0:n.metadata,", new metadata: ").concat(o)),this.safeEmit(Ce.USER_UNPUBLISHED,s,"datachannel",a==null?void 0:a._config),this.safeEmit(Ce.USER_PUBLISHED,s,"datachannel",{id:r,ordered:!!t.ordered,maxRetransmits:t.max_retrans_times,metadata:o})}))}_handleDataChannelDeleted(e){Array.isArray(e)&&e.length>0&&(_.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map(t=>t.stream_id)," deleted")),e.forEach(t=>{const{uid:n,stream_id:i}=t,r=this._users.find(s=>s._uintid===n);if(!r)return void _.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const o=r._dataChannels.find(s=>s.id===t.stream_id);o&&(_.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(n)),r._dataChannels=r._dataChannels.filter(s=>
122s.id!==o.id),this._p2pChannel.unsubscribeDataChannel(r,[o]).then(s=>{if(s)return this._gateway.unsubscribeDataChannel(s,r.uid)}),_.info("[".concat(this._clientId,"] remote user ").concat(n," unpublished datachannel , id:").concat(o.id)),this.safeEmit(Ce.USER_UNPUBLISHED,r,"datachannel",o._config))}))}_handleUpdateDataChannel(e){const{added:t,deleted:n}=e;this._handleDataChannelDeleted(n??[]),this._handleDataChannelAdded(t??[])}_getEncodingName(e){var t,n;if(!this._joinResponse)return;const i=(t=this._joinResponse.ortc.rtpCapabilities.sendrecv)===null||t===void 0?void 0:t.videoCodecs;if(!i)return;for(const a of i){var r;if(a.payloadType===e)return a==null||(r=a.rtpMap)===null||r===void 0?void 0:r.encodingName}const o=(n=this._joinResponse.ortc.rtpCapabilities.recv)===null||n===void 0?void 0:n.videoCodecs;if(o)for(const a of o){var s;if(a.payloadType===e)return a==null||(s=a.rtpMap)===null||s===void 0?void 0:s.encodingName}return e===0?"unknown":void 0}_handleRemoveDataChannels(e){const t=this._users.find(n=>n.uid===e.uid);if(t){if(t._dataChannels!==void 0&&t._dataChannels.length>0){_.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const n=()=>{_.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach(i=>{this.safeEmit(Ce.USER_UNPUBLISHED,t,"datachannel",i._config)})};this._p2pChannel.unsubscribeDataChannel(t,t._dataChannels).then(i=>{if(i)return this._gateway.unsubscribeDataChannel(i,t.uid)}),n()}}else _.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(qt.UPDATE_GATEWAY_CONFIG,()=>{(function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(t){return void _.error("Error loading sdk config",t.message)}if(e)try{const t=JSON.parse(window.atob(e)),n=Date.now();Object.keys(t).forEach(i=>{const{value:r,type:o,expires:s}=t[i];s&&s<=n||o||zS()||!Object.prototype.hasOwnProperty.call(Dp,i)||(Zi[i]=r,tt[i]=r,_.debug("Update gateway parameters from config distribute",i,r))})}catch(t){_.error("Error update config from local cache",t.message)}})()}),this._gateway.on(qt.DISCONNECT_P2P,async()=>{await this._p2pChannel.disconnectForReconnect()}),this._gateway.on(qt.CONNECTION_STATE_CHANGE,(e,t,n)=>{var i;if(n===Pe.FALLBACK)return;const r=()=>{this.safeEmit(Ce.CONNECTION_STATE_CHANGE,e,t,n)};if(Z.reportApiInvoke(this._sessionId||((i=this._gateway.joinInfo)===null||i===void 0?void 0:i.sid)||null,{name:vt.CONNECTION_STATE_CHANGE,options:[e,t,n],tag:ht.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:n})),_.info("[".concat(this._clientId,"] signal connection state change: ").concat(t," -> ").concat(e)),e==="DISCONNECTED")return this._reset(),void r();if(e==="RECONNECTING")this._users.forEach(s=>{s._trust_in_room_=!1,s._trust_audio_enabled_state_=!1,s._trust_video_enabled_state_=!1,s._trust_audio_mute_state_=!1,s._trust_video_mute_state_=!1,s._trust_audio_stream_added_state_=!1,s._trust_video_stream_added_state_=!1,s._is_pre_created||(s._audio_pre_subscribed||(s._audioSSRC=void 0,s._audioOrtc=void 0),s._video_pre_subscribed||(s._videoSSRC=void 0,s._videoOrtc=void 0,s._rtxSsrcId=void 0),s._cname=void 0)}),this._userOfflineTimeout&&window.clearTimeout(this._userOfflineTimeout),this._streamRemovedTimeout&&window.clearTimeout(this._streamRemovedTimeout),this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0;else if(e==="CONNECTED"){var o;
122this._streamFallbackTypeCacheMap.forEach((s,a)=>{this._gateway.setStreamFallbackOption(a,s).catch(c=>{_.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),c)})}),this._remoteStreamTypeCacheMap.forEach((s,a)=>{this._gateway.setRemoteVideoStreamType(a,s).catch(c=>{_.warning("[".concat(this._clientId,"] auto set remote stream type failed"),c)})}),T("VOS_CONFIGURE")&&Array.isArray(T("VOS_CONFIGURE"))&&T("VOS_CONFIGURE").length>0&&(this._gateway.setConfigure(T("VOS_CONFIGURE")).catch(s=>{_.debug("[".concat(this._clientId,"] auto set vos config failed"),s)}),_.debug("[".concat(this._clientId,"] ws connected auto set vos config"))),this._remoteDefaultVideoStreamType!==void 0&&((o=this._joinInfo)===null||o===void 0?void 0:o.defaultVideoStream)===void 0&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then(()=>{_.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))}).catch(s=>{_.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(s))}),this._dualStreamMode&&this._gateway.setDualStreamMode(this._dualStreamMode).catch(s=>{_.warning("[".concat(this._clientId,"] auto set dual stream mode failed"),s)}),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout(()=>{this.connectionState==="CONNECTED"&&(this._userOfflineTimeout=void 0,this._users.filter(s=>!s._trust_in_room_).forEach(s=>{_.debug("[".concat(this._clientId,"] user offline timeout, emit user offline ").concat(s.uid)),this._handleUserOffline({uid:s.uid})}))},3e3),this._streamRemovedTimeout=window.setTimeout(()=>{this.connectionState==="CONNECTED"&&(this._streamRemovedTimeout=void 0,this._users.forEach(s=>{s._trust_audio_mute_state_||(_.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(s.uid)),this._handleMuteStream(s.uid,$.AUDIO,!1)),s._trust_video_mute_state_||(_.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(s.uid)),this._handleMuteStream(s.uid,$.VIDEO,!1)),s._trust_audio_enabled_state_||(_.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(s.uid)),this._handleSetStreamLocalEnable("audio",s.uid,!0)),s._trust_video_enabled_state_||(_.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(s.uid)),this._handleSetStreamLocalEnable("video",s.uid,!0)),s._trust_video_stream_added_state_||(_.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(s.uid)),this._handleResetAddStream(s,"video")),s._trust_audio_stream_added_state_||(_.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(s.uid)),this._handleResetAddStream(s,"audio")),s._video_added_||s._audio_added_||(_.debug("[".concat(this._clientId,"] auto dispatch stream remove ").concat(s.uid)),this._handleRemoveStream({uid:s.uid,uint_id:s._uintid}))}))},1e3))}r()}),this._gateway.on(qt.REQUEST_NEW_GATEWAY_LIST,async(e,t)=>{if(!this._joinInfo)return t(new D(A.UNEXPECTED_ERROR,"can not recover, no join info"));try{let n;if(this._fallbackServerInfo)n=this._fallbackServerInfo,this._fallbackServerInfo=void 0,this._joinInfo.preload=!1,Z.reportApiInvoke(this._sessionId,{name:vt.VOS_FALLBACK_CN,options:{cur:n.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!0},tag:ht.TRACER}).onSuccess(),_.info("[".concat(this._clientId,"] use fallback cn server info"));else{const r=await Fv(Bi(Bi({},this._joinInfo),{},{uid:this._joinInfo.uid,stringUid:void 0}));r?(n=r.ap,b2(r),this._joinInfo.preload=!0):(n=await Fu(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||Bt,this.store),this._joinInfo.preload=!1)}this._joinInfo&&(this._joinInfo.apResponse=n.gatewayInfo.res,this._joinInfo.gatewayAddrs=n.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=n.gatewayInfo.uni_lbs_ip,delete this._joinInfo.signalResponse);const i=[];
122n.gatewayInfo.gatewayAddrs.forEach(r=>{let{address:o}=r;const[s,a]=o.split(":");this._joinInfo&&this._joinInfo.proxyServer?i.push({proxy:this._joinInfo.proxyServer,host:s,port:a}):i.push({host:s,port:a})}),e(i)}catch(n){t(n)}}),this._gateway.on(qt.NETWORK_QUALITY,e=>{this._networkQualitySensitivity==="normal"&&this.safeEmit(Ce.NETWORK_QUALITY,e)}),this._gateway.on(qt.STREAM_TYPE_CHANGE,(e,t)=>{this.safeEmit(Ce.STREAM_TYPE_CHANGED,e,t),Z.reportApiInvoke(this._sessionId,{name:vt.STREAM_TYPE_CHANGE,options:[e,t],tag:ht.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))}),this._gateway.isPreSub=()=>"isPreSub"in this._p2pChannel&&this._p2pChannel.isPreSub(),this._gateway.isPreallocation=()=>"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation(),this._gateway.on(qt.IS_P2P_DISCONNECTED,e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)}),this._gateway.on(qt.REQUEST_P2P_CONNECTION_PARAMS,async(e,t,n)=>{try{let i=await this._p2pChannel.getEstablishParams();i&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()||(i=await this._p2pChannel.startP2PConnection(e)),t(i)}catch(i){n(i)}}),this._gateway.on(qt.JOIN_RESPONSE,(e,t)=>{if(this.store.useP2P)return;let n;this._joinResponse=e,e.attributes?n=e.attributes.userAttributes.preSubSsrcs:_.debug("no attributes in joinResponse");const i=OU(e.ortc,t,n);this._p2pChannel.connect(i)}),this._gateway.on(qt.PRE_CONNECT_PC,async(e,t,n)=>{const{candidates:i,fingerprint:r,turnServer:o}=e;if(this._joinInfo&&i.length>0&&!this._p2pChannel.isPlanB){var s,a;const{cert:d,cid:l}=this._joinInfo.apResponse,h="".concat(l,"_").concat(d),u=e.iceUfrag||h,p=e.icePwd||h;if(!uv(u,p))return void _.debug("[".concat(this._clientId,"] ufrag/pwd length is not valid, length: ").concat(u.length," / ").concat(p.length));let E;await this._p2pChannel.getEstablishParams()&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()?(this._p2pChannel.updateConnectionConfiguration({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0}),_.debug("pre pc before connect ws/dc, use sdp endpoint")):await this._p2pChannel.startP2PConnection({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0});const m=(s=this._joinInfo.signalResponse)===null||s===void 0||(s=s.attributes)===null||s===void 0||(s=s.userAttributes)===null||s===void 0?void 0:s.preSubSsrcs;Array.isArray(m)&&m.length>0&&(E=NU(m));const g=(a=this._joinInfo.signalResponse)===null||a===void 0?void 0:a.rtpCapabilities;try{var c;t(await this._p2pChannel.connect(Bi({iceParameters:{iceUfrag:u,icePwd:p},dtlsParameters:{fingerprints:[{hashFunction:"sha-256",fingerprint:(c=T("FINGERPRINT"))!==null&&c!==void 0?c:r}]},candidates:i,rtpCapabilities:g||{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},setup:"active",cname:"o/i14u9pJrxRKAsu",preallocation:!0},E?{preSSRCs:E}:{})))}catch(R){R.code&&R.code===A.EXCHANGE_SDP_FAILED&&(_.debug("try to pre connect pc, but exchange sdp failed, reset p2p connection",R),await this._p2pChannel.startP2PConnection({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer},!0)),n(R)}}}),this._gateway.on(qt.VOS_FALLBACK,e=>{e==="fallback_hls"&&this.safeEmit(Ce.FALLBACK_TO_HLS,nS.VOSERROR)}),this._gateway.on(qt.RESET_SIGNAL,()=>{this._p2pChannel instanceof lc&&this._p2pChannel.fallbackConnection(),this._handleGatewaySignalEvents()}),this._gateway.on(qt.DATACHANNEL_FAILBACK,()=>{Z.reportApiInvoke(this._sessionId,{name:vt.DATACHANNEL_FAILBACK,options:{},tag:ht.TRACER}).onSuccess(),this._joinGateway()})}_handleGatewaySignalEvents(){this._gateway.signal.on(he.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(he.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(he.ON_ADD_AUDIO_STREAM,e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc)),this._gateway.signal.on(he.ON_ADD_VIDEO_STREAM,e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc,e.rtxSsrcId)),this._gateway.signal.on(he.ON_REMOTE_DATASTREAM_UPDATE,e=>
122{this._handleUpdateDataChannel(e)}),this._gateway.signal.on(he.ON_REMOTE_FULL_DATASTREAM_INFO,e=>{var t;this._handleFullDatachannel((t=e.datastreams)!==null&&t!==void 0?t:[])}),this._gateway.signal.on(he.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(he.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(he.MUTE_AUDIO,e=>this._handleMuteStream(e.uid,$.AUDIO,!0)),this._gateway.signal.on(he.UNMUTE_AUDIO,e=>this._handleMuteStream(e.uid,$.AUDIO,!1)),this._gateway.signal.on(he.MUTE_VIDEO,e=>this._handleMuteStream(e.uid,$.VIDEO,!0)),this._gateway.signal.on(he.UNMUTE_VIDEO,e=>this._handleMuteStream(e.uid,$.VIDEO,!1)),this._gateway.signal.on(he.RECEIVE_METADATA,e=>{const t=Pa(e.metadata);this.safeEmit(Ce.RECEIVE_METADATA,e.uid,t)}),this._gateway.signal.on(he.ON_DATA_STREAM,async e=>{var t;if(!e)return;let n=Pa(e.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&x(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)){if(e.payload.length<ad)throw new D(A.UNEXPECTED_RESPONSE,"payload length ".concat(e.payload.length," is less than header length ").concat(ad));n=await async function(r,o,s){const a=s.subarray(0,ad),c=a.slice(8,ad),d=(c[0]<<8)+c[1],l=(a[6]<<8)+a[7],h=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:r,tagLength:KO,additionalData:new Uint8Array(PO(d,2))},o,s.subarray(ad));return new Uint8Array(h).subarray(0,l)}(this._encryptDataStreamIv,this._encryptDataStreamKey,n)}let i=0;if(e.ordered||e.syncWithAudio){const r=this._p2pChannel.getStats(),o=this.remoteUsers.find(a=>a.uid===e.uid),s=r==null?void 0:r.audioRecv.find(a=>a.ssrc===(o==null?void 0:o._audioSSRC));i=s==null?void 0:s.jitterBufferMs}(i==null||Number.isNaN(i))&&(i=0),Vee(Bi(Bi({},e),{},{payload:n}),i,{id:this._clientId,onStreamMessage:typeof this.onStreamMessage=="function"?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)})}),this._gateway.signal.on(he.ON_CRYPT_ERROR,()=>{Ms(()=>{_.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(Ce.CRYPT_ERROR)},this._sessionId)}),this._gateway.signal.on(he.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(he.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{_.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,Pe.TOKEN_EXPIRE),this.safeEmit(Ce.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()}),this._gateway.signal.on(he.ON_STREAM_FALLBACK_UPDATE,e=>{_.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(Ce.STREAM_FALLBACK,e.stream_id,e.stream_type===1?"fallback":"recover")}),this._gateway.signal.on(he.ENABLE_MULTI_STREAM,e=>{this._dualStreamMode===td.AUTO_SIMULCAST_STREAM&&this.enableDualStream().catch(t=>{_.debug("[".concat(this._clientId,"] set dual stream mode error"),t.toString())})}),this._gateway.signal.on(he.ON_PUBLISH_STREAM,e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),_.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))}),this._gateway.signal.on(he.ENABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)}),this._gateway.signal.on(he.DISABLE_LOCAL_VIDEO,e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)}),this._gateway.signal.on(ee.REQUEST_TIMEOUT,(e,t)=>{if(this._joinInfo)switch(e){case ie.PUBLISH:{if(!t)return;const r=t.ortc;if(r){var n,i;const o=r.some(c=>{let{stream_type:d}=c;return d===nt.Audio}),s=r.some(c=>{let{stream_type:d}=c;return d!==nt.Audio}),a=r.some(c=>{let{stream_type:d}=c;return d===nt.Screen||d===nt.ScreenLow});t.state==="offer"&&Z.publish(this._joinInfo.sid,{eventElapse:jn.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:A.TIMEOUT,audio:o,video:s,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:a,audioName:o?(n=r.find(c=>{let{stream_type:d}=c;return d===nt.Audio}))===null||n===void 0||(n=n.ssrcs[0])===null||n===void 0?void 0:n.ssrcId.toString():void 0,videoName:s?(i=r.find(c=>{let{stream_type:d}=c;return d!==nt.Audio}))===null||i===void 0||(i=i.ssrcs[0])===null||i===void 0?void 0:i.ssrcId.toString():void 0})}break}case ie.SUBSCRIBE:t&&Z.subscribe(this._joinInfo.sid,{succ:!1,ec:A.TIMEOUT,audio:t.stream_type===$.AUDIO,video:t.stream_type===$.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:jn.measureFromSubscribeStart(this.store.clientId,t.ssrcId),preSsrc:this._p2pChannel.isPreSubScribe(t.ssrcId)})}}),this._gateway.signal.on(he.ON_P2P_OK,e=>{this.uid,this._uid}),this._gateway.signal.on(he.ON_PUBLISHED_USER_LIST,e=>{if(e==null||!e.users)return;let t=e.users;T("BLOCK_LOCAL_CLIENT")&&(t=t.filter(n=>!xs(n.string_id||n.stream_id,this.channelName))),this._handleUserList(t)}),this._gateway.signal.on(he.ON_USER_LIST,e=>{if(!e||!Array.isArray(e.users)||e.users.length===0)return;let t=e.users;t=T("BLOCK_LOCAL_CLIENT")?t.filter(n=>!xs(n.string_id||n.stream_id,this.channelName)):t,this._handleUserList(t)}),this._gateway.signal.on(he.ON_RTP_CAPABILITY_CHANGE,e=>{const{video_codec:t}=e;if(this._p2pChannel instanceof lc){if(this.role==="audience"&&T("UPDATE_RTP_CAP_IN_HOST"))return this._pendingRtpCapabilityChange=e,void _.debug("[".concat(this._clientId,"] no need to change rtp capability because of audience, params: ").concat(JSON.stringify(e)));this._p2pChannel.updateRemoteRTPCapabilities(t.map(n=>n.toLowerCase()).filter(n=>{var i;return x(i=Object.keys(Ma)).call(i,n)}))}}),this._gateway.signal.on(ee.VOS_FALLBACK_PROMISE,async(e,t,n)=>{if(e==="FALLBACKCN"&&T("ENABLE_QUALITY_FALLBACK")){if(!this._joinInfo)return n(new D(A.UNEXPECTED_ERROR,"can not recover, no join info"));_.info("[".concat(this._clientId,"] try fallback to cn, start request new server info"));const r=this._joinInfo.apRequestDetail;try{this._joinInfo.apRequestDetail=e;const o=await Fu(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||Bt,this.store);if(T("QUALITY_FALLBACK_REHEARSAL"))return Z.reportApiInvoke(this._sessionId,{name:vt.VOS_FALLBACK_CN,options:{cur:o.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:ht.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=r,void n();this._fallbackServerInfo=o,t()}catch(o){var i;const s=o==null||(i=o.data)===null||i===void 0?void 0:i.desc;T("QUALITY_FALLBACK_REHEARSAL")?(Z.reportApiInvoke(this._sessionId,{name:vt.VOS_FALLBACK_CN,options:{cur:"failed, errorReason: "+s||"unknown",prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:ht.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=r):Array.isArray(s)&&x(s).call(s,"request downgrade fallback")&&this.safeEmit(Ce.FALLBACK_TO_HLS,nS.AP_ERROR),n(o)}}else n()})}_handleUserList(e){var t=this;if(e.length===0)return;const n=[],i=[],r=[],o=[],s=[],a=[],c=this.getListeners(Ce.USER_LIST).length>0,d=this.getListeners(Ce.PUBLISHED_USER_LIST).length>0;for(const h of e){let u=this._users.find(C=>C._uintid===h.stream_id);const p=!!u;
122u?u._trust_in_room_=!0:(u=new na(h.string_id||h.stream_id,h.stream_id),this._users.push(u),this.store.firstVideoFrameDecoded(u.uid,{userJoinNotify:Date.now()}));const E=fn.Audio&h.stream_type,m=(fn.Video|fn.LowVideo)&h.stream_type,g=(65280&h.stream_type)!=0,R=E&&u.hasAudio,v=m&&u.hasVideo;m&&(u._trust_video_stream_added_state_=!0,u._video_added_=!0,u._videoSSRC=h.video_ssrc,u._rtxSsrcId=h.video_rtx),E&&(u._trust_audio_stream_added_state_=!0,u._audio_added_=!0,u._audioSSRC=h.audio_ssrc),(E&&!R||m&&!v||g)&&(i.push(u),E&&!R&&r.push(u),m&&!v&&o.push(u)),p||s.push(u),m&&this._p2pChannel.hasPendingRemoteMedia(u,"video")&&a.push({user:u,mediaType:"video"}),E&&this._p2pChannel.hasPendingRemoteMedia(u,"audio")&&a.push({user:u,mediaType:"audio"}),n.push(u)}a.length>0&&(_.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(a.map(h=>"user: ".concat(h.user.uid,", mediaType: ").concat(h.mediaType)).join("; ")," ")),this.massSubscribe(a).catch(h=>{_.error("[".concat(this._clientId,"] mass resubscribe error"),h.toString())}));const l=function(){let h=arguments.length>0&&arguments[0]!==void 0&&arguments[0];_.info("[".concat(t._clientId,"] client not emit user-list event case there is no user-list listener...")),h||s.forEach(u=>{_.debug("[".concat(t._clientId,"] user online"),u._uintid),t.safeEmit(Ce.USER_JOINED,u)}),i.length>0&&(r.forEach(u=>{_.info("[".concat(t._clientId,"] remote user ").concat(u.uid," published audio")),t.safeEmit(Ce.USER_PUBLISHED,u,"audio")}),o.forEach(u=>{_.info("[".concat(t._clientId,"] remote user ").concat(u.uid," published video")),t.safeEmit(Ce.USER_PUBLISHED,u,"video")}))};if(T("ENABLE_USER_LIST"))c?(this.safeEmit(Ce.USER_LIST,n),l(!0)):l();else if(d){if(i.length>0){const h=ei(i).call(i,(u,p)=>"".concat(u&&u+", ").concat(p.uid),"");T("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=i:(_.info("[".concat(this._clientId,"] client emit published-user-list, users: ").concat(h)),this.safeEmit(Ce.PUBLISHED_USER_LIST,i))}}else l()}_handleP2PEvents(){this._gateway.signal.on(he.ON_USER_OFFLINE,()=>{this._p2pChannel.disconnectForReconnect()}),this._gateway.signal.on(Zt.PUBLISH,(e,t,n)=>{const{uid:i}=e;e.forEach(r=>{const{kind:o,ssrcs:s,mid:a,isMuted:c}=r;this._handleP2PAddAudioOrVideoStream(o,i,s[0].ssrcId,a);const d=this._users.find(l=>l.uid===i);return d&&this.store.useP2P?this._p2pChannel.mockSubscribe(d,o,s[0].ssrcId,a).then(()=>{t()}).catch(n):t(),this._handleMuteStream(i,o,!!c)})}),this._gateway.signal.on(Zt.CALL,async(e,t,n)=>{if(this.store.useP2P)try{var i;t(await this._p2pChannel.startP2P({turnServer:(i=this._joinInfo)===null||i===void 0?void 0:i.turnServer},e))}catch(r){n(r)}}),this._gateway.signal.on(ee.P2P_CONNECTION,async e=>{this.store.useP2P&&(await this._p2pChannel).p2pConnect(e)}),this._gateway.signal.on(Zt.UNPUBLISH,async(e,t,n)=>{if(this.store.useP2P){const{unpubMsg:i,uid:r}=e,o=this._users.find(s=>s.uid===r);if(!o)return _.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(r)),void t();try{i.forEach(async s=>{let{stream_type:a}=s;const c=a===nt.Audio?$.AUDIO:$.VIDEO;await this._p2pChannel.unsubscribe(o,c),this._handleMuteStream(r,c,!0)}),t()}catch(s){n(s)}}}),this._gateway.signal.on(Zt.CONTROL,async(e,t)=>{const{action:n}=e;switch(n){case Gs.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,$.VIDEO,!0);break;case Gs.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,$.AUDIO,!0);break;case Gs.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,$.VIDEO,!1);break;case Gs.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,$.AUDIO,!1)}}),this._gateway.signal.on(Zt.RESTART_ICE,async(e,t,n)=>{if(this.store.useP2P)try{const{direction:i,iceParameter:r}=e;i!==si.SEND_ONLY||r?t(await this._p2pChannel.restartICE(i,r)):(this._p2pChannel.handleDisconnect(i),t())}catch(i){n(i)}}),this._gateway.signal.on(Zt.CANDIDATE,e=>{if(this.store.useP2P){const{candidate:t,direction:n}=e;this._p2pChannel.addRemoteCandidate(t,n)}}),this._p2pChannel.on(ae.RequestP2PRestartICE,async(e,t,n)=>{try{const{direction:i}=e;t(await this._gateway.sendExtensionMessage(Zt.RESTART_ICE,e,i===si.SEND_ONLY))}catch(i){n(i)}}),this._p2pChannel.on(ae.LocalCandidate,e=>{this._gateway.sendExtensionMessage(Zt.CANDIDATE,JSON.stringify(e),!0)}),this._p2pChannel.on(ae.RequestP2PMuteLocal,async(e,t,n)=>{try{await this._gateway.sendExtensionMessage(Zt.CONTROL,e,!0),t()}catch(i){n(i)}}),this._p2pChannel.on(ae.RequestP2PUnmuteRemote,async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(i){i.code===A.DISCONNECT_P2P?t():n(i)}else t()}),this._p2pChannel.on(ae.RequestP2PMuteRemote,async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.muteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(i){i.code===A.DISCONNECT_P2P?t():n(i)}else t()}),this._p2pChannel.on(ae.StateChange,(e,t)=>{t===qe.Connected&&this._p2pChannel.republish()})}_handleP2PChannelEvents(){this._p2pChannel.on(ae.PeerConnectionStateChange,e=>{const t=this._peerConnectionState;e!==t&&(this.safeEmit(Ce.PEERCONNECTION_STATE_CHANGE,e,t),this._peerConnectionState=e)}),this._p2pChannel.on(ae.RequestMuteLocal,async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.muteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(i){i.code===A.DISCONNECT_P2P?t():n(i)}else t()}),this._p2pChannel.on(ae.RequestUnmuteLocal,async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(i){i.code===A.DISCONNECT_P2P?t():n(i)}else t()}),this._p2pChannel.on(ae.RequestRePublish,(e,t,n)=>
122{this.publish(e,!1).then(t).catch(n)}),this._p2pChannel.on(ae.RequestRePublishDataChannel,(e,t,n)=>{K.all(e.map(async i=>{const r=await this._p2pChannel.publishDataChannel([i]);try{r.forEach(o=>{this._uid&&this._gateway.publishDataChannel(this._uid,o,!0)})}catch(o){if(o.code!==A.DISCONNECT_P2P)throw o}})).then(t).catch(n)}),this._p2pChannel.on(ae.RequestReSubscribe,async(e,t,n)=>{try{for(const{user:i,kind:r}of e)r===$.VIDEO?await this.subscribe(i,"video"):await this.subscribe(i,"audio");t()}catch(i){n(i)}}),this._p2pChannel.on(ae.RequestUpload,(e,t)=>{this._gateway.upload(e,t)}),this._p2pChannel.on(ae.RequestUploadStats,e=>{this._gateway.uploadWRTCStats(e)}),this._p2pChannel.on(ae.MediaReconnectStart,e=>{this.safeEmit(Ce.MEDIA_RECONNECT_START,e)}),this._p2pChannel.on(ae.MediaReconnectEnd,e=>{this.safeEmit(Ce.MEDIA_RECONNECT_END,e)}),this._p2pChannel.on(ae.NeedSignalRTT,e=>{e(this._gateway.getSignalRTT())}),this._p2pChannel.on(ae.RequestRestartICE,async e=>{if(this.store.useP2P)return;const t=await this._p2pChannel.restartICE(e),n=await t.next();if(n.done)return;const i=n.value;let r;try{r=await this._gateway.restartICE({iceParameters:i})}catch(s){return void t.throw(s)}const{iceParameters:o}=function(s){const a=s.iceParameters;return{iceParameters:{iceUfrag:a.iceUfrag,icePwd:a.icePwd}}}(r);await t.next({remoteIceParameters:o})}),this._p2pChannel.on(ae.RequestReconnect,async()=>{this._gateway.reconnect()}),this._p2pChannel.on(ae.RequestReconnectPC,async()=>{var e;const{iceParameters:t,dtlsParameters:n,rtpCapabilities:i}=await this._p2pChannel.startP2PConnection({turnServer:(e=this._joinInfo)===null||e===void 0?void 0:e.turnServer}),{gatewayEstablishParams:r,gatewayAddress:o}=await this._gateway.reconnectPC({iceParameters:t,dtlsParameters:n,rtpCapabilities:i}),s=OU(r,o);await this._p2pChannel.connect(s),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()}),this._p2pChannel.on(ae.RequestUnpublishForReconnectPC,async(e,t,n)=>{this._joinInfo&&this._uid!==void 0?(await this._gateway.unpublish(e,this._uid),t()):n()}),this._p2pChannel.on(ae.P2PLost,()=>{this.safeEmit(Ce.P2P_LOST,this.store.uid)}),this._p2pChannel.on(ae.UpdateVideoEncoder,e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)}),this._p2pChannel.on(ae.ConnectionTypeChange,e=>{this.safeEmit(Ce.IS_USING_CLOUD_PROXY,e),this._gateway.setUsingProxy(e)}),this._p2pChannel.on(ae.FirstVideoBufferReady,(e,t)=>{this.safeEmit(Ce.FIRST_VIDEO_BUFFER_READY,e,t)}),this._p2pChannel.on(ae.FirstVideoPreRender,(e,t)=>{this.safeEmit(Ce.FIRST_VIDEO_PRE_RENDER,e,t)}),this._p2pChannel.on(ae.RequestLowStreamParameter,e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})}),this._p2pChannel.on(ae.QueryClientConnectionState,e=>{e(this.connectionState)}),this._p2pChannel.on(ae.AudioMetadata,e=>{this.safeEmit(Ce.AUDIO_METADATA,e)}),this._p2pChannel.on(ae.AudioPts,e=>{this.safeEmit(Ce.AUDIO_PTS,Number(e))})}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if(!this._joinInfo||this.connectionState!=="CONNECTED")throw new D(A.INVALID_OPERATION,"[".concat(this._clientId,"] can not create content inspect, please join channel first"));if(this._inspect)throw new D(A.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));try{const n=(t={config:e},To("ContentInspect").create(t));this._inspect=n,this.handleVideoInspectEvents(n);const{appId:i,cname:r,sid:o,token:s,uid:a,cid:c,vid:d}=this._joinInfo;await n.init({appId:i,areaCode:"",cname:r,sid:o,token:s,uid:a,cid:c,vid:d?Number(d):0},Bt)}catch(n){throw Array.isArray(n)?n[0]:n}var t}handleVideoInspectEvents(e){e.on(Cn.CONNECTION_STATE_CHANGE,(t,n)=>{if(this.safeEmit(Ce.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,n),n===Hr.CONNECTED){if(this.connectionState!=="CONNECTED")return void this.safeEmit(Ce.CONTENT_INSPECT_ERROR,new D(A.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}}),e.on(Cn.INSPECT_RESULT,(t,n)=>{var i;if((n==null?void 0:n.code)===A.INVALID_OPERATION&&this.connectionState==="DISCONNECTED")return _.debug("Stop inspect content because that has left channel"),this==null||(i=this._inspect)===null||i===void 0||i.close(),void(this._inspect=void 0);this.safeEmit(Ce.CONTENT_INSPECT_RESULT,t,n)}),e.on(Cn.CLIENT_LOCAL_VIDEO_TRACK,t=>{t(this.localTracks.filter(n=>n.trackMediaType==="video")[0])})}async disableContentInspect(){if(!this._inspect)throw new D(A.INVA
122LID_OPERATION,"[".concat(this._clientId,"] inspectVideoContent not started"));try{this._inspect.close(),this._inspect=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}async setImageModeration(e,t){if(xr(e,"enabled"),e){if(!t)throw new D(A.INVALID_PARAMS,"config is required");if(G2(t),!this._joinInfo)throw new D(A.INVALID_OPERATION,"can not create image moderation, please join channel first");try{if(this._moderation)this._moderation.updateConfig(t);else{const i=(n={config:t},To("ImageModeration").create(n));this._moderation=i,this.handleImageModerationEvents(i);const{appId:r,cname:o,sid:s,token:a,uid:c,cid:d,vid:l}=this._joinInfo;await i.init({appId:r,areaCode:"",cname:o,sid:s,token:a,uid:c,cid:d,vid:l?Number(l):0},Bt)}}catch(i){throw Array.isArray(i)?i[0]:i}}else{var n;if(!this._moderation)throw new D(A.INVALID_OPERATION,"[".concat(this._clientId,"] image moderation not started"));try{this._moderation.close(),this._moderation.removeAllListeners(),this._moderation=void 0}catch(i){throw Array.isArray(i)?i[0]:i}}}handleImageModerationEvents(e){e.on(po.CONNECTION_STATE_CHANGE,(t,n)=>{if(this.safeEmit(Ce.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,n),t===Er.CONNECTED){if(this.connectionState!=="CONNECTED")throw this.setImageModeration(!1),new D(A.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage()}}),e.on(po.CLIENT_LOCAL_VIDEO_TRACK,t=>{t(this.localTracks.filter(n=>n.trackMediaType==="video")[0])})}setP2PTransport(e){if(function(t){nn(t,"transport",["default","auto","relay","sd-rtn"])}(e),this.mode!=="p2p")throw new D(A.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,_.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e))}getJoinChannelServiceRecords(){return _.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){xr(e,"enabled"),at("ENABLE_PUBLISH_AUDIO_FILTER",e),this._joinInfo&&await this._gateway.setPublishAudioFilterEnabled(e)}_setRteInfo(e,t){this.store.rteUrl=e,this.store.rteSid=t}_isPreRender(){return"isPreRender"in this._p2pChannel&&this._p2pChannel.isPreRender()}_handleResetAddStream(e,t){switch(t){case"audio":e._audio_added_=!1,e._trust_audio_stream_added_state_=!0;break;case"video":e._video_added_=!1,e._trust_video_stream_added_state_=!0}}},H(Q.prototype,"leave",[j2],Object.getOwnPropertyDescriptor(Q.prototype,"leave"),Q.prototype),H(Q.prototype,"publish",[W2],Object.getOwnPropertyDescriptor(Q.prototype,"publish"),Q.prototype),H(Q.prototype,"unpublish",[K2],Object.getOwnPropertyDescriptor(Q.prototype,"unpublish"),Q.prototype),H(Q.prototype,"subscribe",[H2],Object.getOwnPropertyDescriptor(Q.prototype,"subscribe"),Q.prototype),H(Q.prototype,"presubscribe",[Y2],Object.getOwnPropertyDescriptor(Q.prototype,"presubscribe"),Q.prototype),H(Q.prototype,"massSubscribe",[X2],Object.getOwnPropertyDescriptor(Q.prototype,"massSubscribe"),Q.prototype),H(Q.prototype,"unsubscribe",[J2],Object.getOwnPropertyDescriptor(Q.prototype,"unsubscribe"),Q.prototype),H(Q.prototype,"massUnsubscribe",[z2],Object.getOwnPropertyDescriptor(Q.prototype,"massUnsubscribe"),Q.prototype),H(Q.prototype,"setLowStreamParameter",[q2],Object.getOwnPropertyDescriptor(Q.prototype,"setLowStreamParameter"),Q.prototype),H(Q.prototype,"setDualStreamMode",[Z2],Object.getOwnPropertyDescriptor(Q.prototype,"setDualStreamMode"),Q.prototype),H(Q.prototype,"enableDualStream",[Q2],Object.getOwnPropertyDescriptor(Q.prototype,"enableDualStream"),Q.prototype),H(Q.prototype,"disableDualStream",[$2],Object.getOwnPropertyDescriptor(Q.prototype,"disableDualStream"),Q.prototype),H(Q.prototype,"setClientRole",[eV],Object.getOwnPropertyDescriptor(Q.prototype,"setClientRole"),Q.prototype),H(Q.prototype,"_setClientRoleOptions",[tV],Object.getOwnPropertyDescriptor(Q.prototype,"_setClientRoleOptions"),Q.prototype),H(Q.prototype,"setProxyServer",[nV],Object.getOwnPropertyDescriptor(Q.prototype,"setProxyServer"),Q.prototype),H(Q.prototype,"setTurnServer",[iV],Object.getOwnPropertyDescriptor(Q.prototype,"setTurnServer"),Q.prototype),H(Q.prototype,"setLicense",[rV],Object.getOwnPropertyDescriptor(Q.prototype,"setLicense"),Q.prototype),H(Q.prototype,"startProxyServer",[oV],Object.getOwnPropertyDescriptor(Q.prototype,"startProxyServer"),Q.prototype),H(Q.prototype,"stopProxyServer",[sV],Object.getOwnPropertyDescriptor(Q.prototype,"stopProxyServer"),Q.prototype),H(Q.prototype,"setLocalAccessPointsV2",[aV],Object.getOwnPropertyDescriptor(Q.prototype,"setLocalAccessPointsV2"),Q.prototype),H(Q.prototype,"setLocalAccessPoints",[cV],Object.getOwnPropertyDescriptor(Q.prototype,"setLocalAccessPoints"),Q.prototype),H(Q.prototype,"setRemoteDefaultVideoStreamType",[dV],Object.getOwnPropertyDescriptor(Q.prototype,"setRemoteDefaultVideoStreamType"),Q.prototype),H(Q.prototype,"setRemoteVideoStreamType",[lV],Object.getOwnPropertyDescriptor(Q.prototype,"setRemoteVideoStreamType"),Q.prototype),H(Q.prototype,"setStreamFallbackOption",[uV],Object.getOwnPropertyDescriptor(Q.prototype,"setStreamFallbackOption"),Q.prototype),H(Q.prototype,"setEncryptionConfig",[hV],Object.getOwnPropertyDescriptor(Q.prototype,"setEncryptionConfig"),Q.prototype),H(Q.prototype,"renewToken",[pV],Object.getOwnPropertyDescriptor(Q.prototype,"renewToken"),Q.prototype),H(Q.prototype,"enableAudioVolumeIndicator",[_V],Object.getOwnPropertyDescriptor(Q.prototype,"enableAudioVolumeIndicator"),Q.prototype),H(Q.prototype,"startLiveStreaming",[mV],Object.getOwnPropertyDescriptor(Q.prototype,"startLiveStreaming"),Q.prototype),H(Q.prototype,"setLiveTranscoding",[EV],Object.getOwnPropertyDescriptor(Q.prototype,"setLiveTranscoding"),Q.prototype),H(Q.prototype,"stopLiveStreaming",[fV],Object.getOwnPropertyDescriptor(Q.prototype,"stopLiveStreaming"),Q.prototype),H(Q.prototype,"startChannelMediaRelay",[gV],Object.getOwnPropertyDescriptor(Q.prototype,"startChannelMediaRelay"),Q.prototype),H(Q.prototype,"updateChannelMediaRelay",[SV],Object.getOwnPropertyDescriptor(Q.prototype,"updateChannelMediaRelay"),Q.prototype),H(Q.prototype,"stopChannelMediaRelay",[TV],Object.getOwnPropertyDescriptor(Q.prototype,"stopChannelMediaRelay"),Q.prototype),H(Q.prototype,"sendCustomReportMessage",[RV],Object.getOwnPropertyDescriptor(Q.prototype,"sendCustomReportMessage"),Q.prototype),H(Q.prototype,"pickSVCLayer",[vV],Object.getOwnPropertyDescriptor(Q.prototype,"pickSVCLayer"),Q.prototype),H(Q.prototype,"setRTMConfig",[AV],Object.getOwnPropertyDescriptor(Q.prototype,"setRTMConfig"),Q.prototype),H(Q.prototype,"enableContentInspect",[CV],Object.getOwnPropertyDescriptor(Q.prototype,"enableContentInspect"),Q.prototype),H(Q.prototype,"disableContentInspect",[yV],Object.getOwnPropertyDescriptor(Q.prototype,"disableContentInspect"),Q.prototype),H(Q.prototype,"setImageModeration",[IV],Object.getOwnPropertyDescriptor(Q.prototype,"setImageModeration"),Q.prototype),H(Q.prototype,"setP2PTransport",[bV],Object.getOwnPropertyDescriptor(Q.prototype,"setP2PTransport"),Q.prototype),H(Q.prototype,"getJoinChannelServiceRecords",[wV],Object.getOwnPropertyDescriptor(Q.prototype,"getJoinChannelServiceRecords"),Q.prototype),H(Q.prototype,"setPublishAudioFilterEnabled",[OV],Object.getOwnPropertyDescriptor(Q.prototype,"setPublishAudioFilterEnabled"),Q.prototype),Q);function DV(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const t=Qe(5,"client-"),n=Z.reportApiInvoke(null,{id:t,name:vt.CREATE_CLIENT,options:[e],tag:ht.TRACER});try{var i;(function(o){nn(o.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),nn(o.mode,"config.mode",["rtc","live","p2p"]),o.audioCodec!==void 0&&nn(o.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),o.proxyServer!==void 0&&On(o.proxyServer,"config.proxyServer",1,1e4),o.turnServer!==void 0&&AO(o.turnServer),o.httpRetryConfig!==void 0&&vO(o.httpRetryConfig),o.websocketRetryConfig!==void 0&&vO(o.websocketRetryConfig)}
122)(e),(dO(16,0,!0)||Ap(16,0,!0))&&(e.codec==="vp9"&&(e.codec="vp8",_.debug("browser not support vp9, force use vp8")),at("UNSUPPORTED_VIDEO_CODEC",["vp9"])),e.audioCodec===void 0&&(e.audioCodec="opus");const r=new $ee(Bi(Bi({forceWaitGatewayResponse:!0},e),{},{role:x(i=["rtc","p2p"]).call(i,e.mode)?"host":e.role||"audience"}),t);return n.onSuccess(),r}catch(r){throw n.onError(r),r}}function ete(){let e=!1;const t=Fe();return(t.name===je.CHROME&&Number(t.version)>=58&&(co.engine.name!=="WebKit"||function(){const n=Fe();if(Tp()){if(n.os===pn.MAC_OS)return!0;if(n.os===pn.IOS){const i=co.os.version&&co.os.version.split(".");if(i&&Number(i[0])===14&&i[1]&&Number(i[1])>=3||i&&Number(i[0])>14)return!0}}return!1}())||t.name===je.FIREFOX&&Number(t.version)>=56||t.name===je.OPERA&&Number(t.version)>=45||t.name===je.SAFARI&&Number(t.version)>=11||t.name==="WebKit"&&(Hn()||Vr())&&t.osVersion&&Number(t.osVersion.split(".")[0])>=11||hO()||Fe().name===je.QQ)&&(e=!0),e}class Ku{constructor(t,n){S(this,"id",0),S(this,"element",void 0),S(this,"peerPair",void 0),S(this,"context",void 0),S(this,"audioPlayerElement",void 0),S(this,"audioTrack",void 0),Ku.count+=1,this.id=Ku.count,this.element=t,this.context=n}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=t=>{const n=document.createElement("audio");n.srcObject=new MediaStream([t.track]),n.play(),this.audioPlayerElement=n}}async switchSdp(){if(!this.peerPair)return;const t=async(i,r)=>{const o=r==="offer"?await i.createOffer():await i.createAnswer();return await i.setLocalDescription(o),i.iceGatheringState==="complete"?i.localDescription:new K(s=>{i.onicegatheringstatechange=()=>{i.iceGatheringState==="complete"&&s(i.localDescription)}})},n=async(i,r)=>await i.setRemoteDescription(r);try{const i=await t(this.peerPair[0],"offer");await n(this.peerPair[1],i);const r=await t(this.peerPair[1],"answer");await n(this.peerPair[0],r)}catch(i){throw new D(A.LOCAL_AEC_ERROR,i.toString()).print()}}async getTracksFromMediaElement(t){if(this.audioTrack)return this.audioTrack;let n;try{t instanceof HTMLVideoElement&&(t.captureStream?t.captureStream():t.mozCaptureStream()),n=this.context.createMediaStreamDestination(),this.context.createMediaElementSource(t).connect(n)}catch(r){throw new D(A.LOCAL_AEC_ERROR,r.toString()).print()}if(!n)throw new D(A.LOCAL_AEC_ERROR,"no dest node when local aec").print();const i=n.stream.getAudioTracks()[0];return this.audioTrack=i,i}getElement(){return this.element}async startEchoCancellation(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();const t=this.element,n=await this.getTracksFromMediaElement(t);this.peerPair&&this.peerPair[0].addTrack(n),await this.switchSdp()}close(){_.debug("close echo cancellation unit, id is",this.id),this.audioPlayerElement&&this.audioPlayerElement.pause(),this.peerPair&&this.peerPair.forEach(t=>{t.close()}),this.peerPair=void 0,this.audioPlayerElement=void 0}}var PV,Nm;S(Ku,"count",0);const tte=window.AudioContext||window.webkitAudioContext,nte=new(PV=ue({report:Z}),H((Nm=class{constructor(){S(this,"units",[]),S(this,"context",void 0)}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return _.debug("the system does not need to process local aec"),-1;this.context||(this.context=new tte);let t=this.units.find(n=>n&&n.getElement()===e);return t||(t=new Ku(e,this.context),this.units.push(t)),t.startEchoCancellation(),_.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return Fe().name!==je.SAFARI}}).prototype,"processExternalMediaAEC",[PV],Object.getOwnPropertyDescriptor(Nm.prototype,"processExternalMediaAEC"),Nm.prototype),Nm);function LV(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function kV(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?LV(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):LV(Object(n)).forEac
122h(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}const Kv=window||document;function MV(e){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];if(!Kv)return;const n=cn._cspEventHandlerPointer;if(n&&t)return void console.error(n,t);const i=r=>{if(!(r&&r.blockedURI&&(cn.onSecurityPolicyViolation||cn.getListeners(Vo.SECURITY_POLICY_VIOLATION).length>0)))return;const o=r.blockedURI;T("CSP_DETECTED_HOSTNAME_LIST").some(s=>x(o).call(o,s))&&(cn.onSecurityPolicyViolation&&typeof cn.onSecurityPolicyViolation=="function"&&cn.onSecurityPolicyViolation(r),cn.getListeners(Vo.SECURITY_POLICY_VIOLATION).length>0&&cn.safeEmit(Vo.SECURITY_POLICY_VIOLATION,r))};n&&Kv.removeEventListener("securitypolicyviolation",n),(t||e&&typeof e=="function"||cn.getListeners(Vo.SECURITY_POLICY_VIOLATION).length>0)&&Kv.addEventListener("securitypolicyviolation",i),cn._cspEventHandlerPointer=i}var UV=function(e){return e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE",e}(UV||{});class ite{constructor(){S(this,"_sequence",0),S(this,"_startTime",Date.now()),S(this,"isUseOneByte",!0)}get startTime(){const t=Date.now()-this._startTime;return t<Math.pow(2,16)?t:(this._startTime+=Math.pow(2,16),this.startTime)}get sequence(){return this._sequence<Math.pow(2,32)?this._sequence++:(this._sequence-=Math.pow(2,32),this.sequence)}serialize(t){const n={commonPacketHeader:{length:0,reserved:0,extension:0,sequence:this.sequence},commonStreamHeader:this.startTime,extension:void 0,payload:t};if(t.byteLength>128){const a=new Uint8Array(4);a.set([1,0,0,0]);const c={id:0,length:4,data:a.buffer},d={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[c]};n.commonPacketHeader.extension=1,n.extension=d,n.payload=this.compress(t),n.commonPacketHeader.length=8+(n.extension.length+2)+n.payload.byteLength}else n.commonPacketHeader.length=8+n.payload.byteLength;T("SHOW_DATASTREAM2_LOG")&&_.debug("send data header: ".concat(JSON.stringify(n.commonPacketHeader)));
122const i=new ArrayBuffer(n.commonPacketHeader.length),r=new Uint8Array(i),o=new DataView(i);let s=0;if(o.setUint16(s,n.commonPacketHeader.extension<<15|n.commonPacketHeader.reserved<<14|n.commonPacketHeader.length,!0),s+=2,o.setUint32(s,n.commonPacketHeader.sequence,!0),s+=4,o.setUint16(s,n.commonStreamHeader,!0),s+=2,n.extension){const a=this.serializeExtension(n.extension);r.set(new Uint8Array(a),s),s+=a.byteLength}if(r.set(new Uint8Array(n.payload),s),s+=n.payload.byteLength,s!==n.commonPacketHeader.length)throw Error("serialize error!");return i}deserialize(t){if(t.byteLength<4)return new ArrayBuffer(0);const n=new DataView(t);let i=0;const r=n.getUint16(i,!0);i+=2;const o={length:16383&r,reserved:(16384&r)>>14,extension:(32768&r)>>15,sequence:n.getUint16(i+2,!0)<<16|n.getUint16(i,!0)};let s,a;if(i+=4,T("SHOW_DATASTREAM2_LOG")&&_.debug("receive data header: ".concat(JSON.stringify(o))),n.getUint16(i,!0),i+=2,o.extension){a=this.deserializeExtension(t.slice(i)),i+=2+a.length,s=t.slice(i);let c=!1;if(a.datas.length>0){const d=a.datas.find(l=>l.id===0);d&&(c=(1&new DataView(d.data).getUint32(0,!0))==1)}s=c?this.decompress(s):s}else s=t.slice(8);return s}serializeExtension(t){const{profile:n,length:i,datas:r}=t,o=new ArrayBuffer(i+2),s=new Uint8Array(o),a=new DataView(o);let c=0;if(a.setUint8(c++,n),a.setUint8(c++,i),r.forEach(d=>{n?(a.setUint8(c++,d.id),a.setUint8(c++,d.length),s.set(new Uint8Array(d.data),c),c+=d.data.byteLength):(a.setUint8(c++,d.id|d.length<<4),s.set(new Uint8Array(d.data),c),c+=d.data.byteLength)}),c!==i+2)throw Error("serialize extension error, is ".concat(c,"!==").concat(i+2));return o}deserializeExtension(t){const n=new DataView(t);let i=0;const r=n.getUint8(i);i++;const o=n.getUint8(i);i++;const s=r===UV.TWO_BYTE,a=[],c=new DataView(t,2);let d=0;for(;d<o;){let l=0,h=0,u=new ArrayBuffer(0);s?(l=c.getUint8(d),d++,h=c.getUint8(d),d++):(l=15&c.getUint8(d),h=c.getUint8(d)>>4,d++),h>0&&(u=c.buffer.slice(d+2,d+2+h),d+=u.byteLength),a.push({id:l,length:h,data:u})}if(d!==o)throw Error("parse error");return{profile:r,length:o,datas:a}}decompress(t){return Rz(new Uint8Array(t))}compress(t){return Tz(new Uint8Array(t))}}const rte={name:"DataStream",create:(e,t)=>{const n=t?new TX(e):new RX(e);return n.useDataStream(new ite),n}};class ote extends Nt{constructor(t,n,i){super(),S(this,"ws",void 0),S(this,"requestId",1),S(this,"heartBeatTimer",void 0),S(this,"joinInfo",void 0),S(this,"clientId",void 0),S(this,"onOpen",()=>{this.emit("open"),this.startHeartBeatCheck()}),S(this,"onClose",r=>{this.emit("close"),this.dispose()}),S(this,"onMessage",r=>{const o=JSON.parse(r.data);if(!o||o.command!=="serverResponse"||!o.requestId)return o&&o.command==="serverStatus"&&o.serverStatus&&o.serverStatus.command?(this.emit("status",o.serverStatus),void this.emit(o.serverStatus.command,o.serverStatus)):void 0;this.emit("req_".concat(o.requestId),o)}),this.joinInfo=t,this.clientId=n,this.ws=new eu("cross-channel-".concat(this.clientId),i),this.ws.on(Re.RECONNECTING,()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")}),this.ws.on(Re.CONNECTED,this.onOpen),this.ws.on(Re.ON_MESSAGE,this.onMessage),this.ws.on(Re.CLOSED,this.onClose)}isConnect(){return this.ws.state==="connected"}sendMessage(t){const n=this.requestId++;return t.requestId=n,t.seq=n,this.ws.sendMessage(t),n}waitStatus(t){return new K((n,i)=>{const r=window.setTimeout(()=>{i(new D(A.TIMEOUT,"wait status timeout, status: ".concat(t)))},5e3);this.once(t,o=>{window.clearTimeout(r),o.state&&o.state!==0?i(new D(A.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(t))):n(void 0)}),this.once("dispose",()=>{window.clearTimeout(r),i(new D(A.WS_ABORT))})})}async request(t){if(this.ws.state==="closed")throw new D(A.WS_DISCONNECT);const n=()=>new K((s,a)=>{this.ws.once(Re.CLOSED,()=>a(new D(A.WS_ABORT))),this.ws.once(Re.CONNECTED,s)});this.ws.state!=="connected"&&await n();const i=this.sendMessage(t),r=new K((s,a)=>{const c=()=>{a(new D(A.WS_ABORT))};this.ws.once(Re.RECONNECTING,c),this.ws.once(Re.CLOSED,c),this.once("req_".concat(i),s),ln(3e3).then(()=>{this.removeAllListeners("req_".concat(i)),this.ws.off(Re.RECONNECTING,c),this.ws.off(Re.CLOSED,c),a(new D(A.TIMEOUT,"cross channel ws request timeout"))})}),o=await r;if(!o||o.code!==200)throw new D(A.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(o)));return o}async connect(t){this.ws.removeAllListeners(Re.REQUEST_NEW_URLS),this.ws.on(Re.REQUEST_NEW_URLS,n=>{n(t)}),await this.ws.init(t)}
122dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(t){const n=this.requestId++;return t.requestId=n,this.ws.sendMessage(t),n}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval(()=>{this.sendPing({command:"ping",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date,requestId:0})},3e3)}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0}}class ste extends Nt{set state(t){t!==this._state&&(t!==Ri.RELAY_STATE_FAILURE&&(this.errorCode=Sd.RELAY_OK),this.emit("state",t,this.errorCode),this._state=t)}get state(){return this._state}constructor(t,n,i,r,o){super(),S(this,"joinInfo",void 0),S(this,"sid",void 0),S(this,"clientId",void 0),S(this,"cancelToken",li.CancelToken.source()),S(this,"workerToken",void 0),S(this,"requestId",0),S(this,"signal",void 0),S(this,"prevChannelMediaConfig",void 0),S(this,"httpRetryConfig",void 0),S(this,"_resolution",void 0),S(this,"_state",Ri.RELAY_STATE_IDLE),S(this,"errorCode",Sd.RELAY_OK),S(this,"onStatus",s=>{_.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(s))),s&&s.command&&(s.command==="onAudioPacketReceived"&&this.emit("event",ds.PACKET_RECEIVED_AUDIO_FROM_SRC),s.command==="onVideoPacketReceived"&&this.emit("event",ds.PACKET_RECEIVED_VIDEO_FROM_SRC),s.command==="onSrcTokenPrivilegeDidExpire"&&(this.errorCode=Sd.SRC_TOKEN_EXPIRED,this.state=Ri.RELAY_STATE_FAILURE),s.command==="onDestTokenPrivilegeDidExpire"&&(this.errorCode=Sd.DEST_TOKEN_EXPIRED,this.state=Ri.RELAY_STATE_FAILURE))}),S(this,"onReconnect",async()=>{_.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",ds.NETWORK_DISCONNECTED),this.state=Ri.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch(s=>{this.state!==Ri.RELAY_STATE_IDLE&&(_.error("auto restart channel media relay failed",s.toString()),this.errorCode=Sd.SERVER_CONNECTION_LOST,this.state=Ri.RELAY_STATE_FAILURE)})}),this.joinInfo=t,this.clientId=n,this.sid=La(),this.signal=new ote(this.joinInfo,this.clientId,i),this.httpRetryConfig=r,this._resolution=o}async startChannelMediaRelay(t){if(this.state!==Ri.RELAY_STATE_IDLE)throw new D(A.INVALID_OPERATION);this.state=Ri.RELAY_STATE_CONNECTING,await this.connect(),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(t)}catch(n){throw n.data&&n.data.serverResponse&&n.data.serverResponse.command==="SetSourceChannel"?new D(A.CROSS_CHANNEL_FAILED_JOIN_SRC):n.data&&n.data.serverResponse&&n.serverResponse.command==="SetDestChannelStatus"?new D(A.CROSS_CHANNEL_FAILED_JOIN_DEST):n.data&&n.data.serverResponse&&n.serverResponse.command==="StartPacketTransfer"?new D(A.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST):n}this.prevChannelMediaConfig=t}async updateChannelMediaRelay(t){if(this.state!==Ri.RELAY_STATE_RUNNING)throw new D(A.INVALID_OPERATION);await this.sendUpdateMessage(t),this.prevChannelMediaConfig=t}async setVideoProfile(t){if(this._resolution=t,this.state!==Ri.RELAY_STATE_RUNNING)throw new D(A.INVALID_OPERATION);const n=this.genMessage(pi.SetVideoProfile);await this.signal.request(n),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),_.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=Ri.RELAY_STATE_IDLE,this.dispose()}dispose(){_.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=li.CancelToken.source(),this.state=Ri.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const t=await Cee(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=t.workerToken,await this.signal.connect(t.addressList),this.emit("event",ds.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(t){const n=this.genMessage(pi.SetSdkProfile,t);await this.signal.request(n),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const i=this.genMessage(pi.SetSourceChannel,t);await this.signal.request(i),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit
122("event",ds.PACKET_JOINED_SRC_CHANNEL),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const r=this.genMessage(pi.SetSourceUserId,t);await this.signal.request(r),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const o=this.genMessage(pi.SetDestChannel,t);await this.signal.request(o),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",ds.PACKET_JOINED_DEST_CHANNEL),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const s=this.genMessage(pi.StartPacketTransfer,t);await this.signal.request(s),this.emit("event",ds.PACKET_SENT_TO_DEST_CHANNEL),this.state=Ri.RELAY_STATE_RUNNING,_.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(t){const n=this.genMessage(pi.UpdateDestChannel,t);await this.signal.request(n),this.emit("event",ds.PACKET_UPDATE_DEST_CHANNEL),_.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const t=this.genMessage(pi.StopPacketTransfer);await this.signal.request(t),_.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(t,n){const i=[],r=[],o=[];this.requestId+=1;const s={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:qi,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};s.sdkVersion==="4.24.3"&&(s.sdkVersion="0.0.1");let a=null,c=null;switch(t){case pi.SetSdkProfile:return s.clientRequest={command:"SetSdkProfile",type:"multi_channel"},s;case pi.SetSourceChannel:if(c=n&&n.getSrcChannelMediaInfo(),!c)throw new D(A.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceChannel",uid:"0",channelName:c.channelName,token:c.token||this.joinInfo.appId},s;case pi.SetSourceUserId:if(c=n&&n.getSrcChannelMediaInfo(),!c)throw new D(A.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceUserId",uid:c.uid+""},s;case pi.SetDestChannel:if(a=n&&n.getDestChannelMediaInfo(),!a)throw new D(A.UNEXPECTED_ERROR,"can not find dest config");return a.forEach(d=>{i.push(d.channelName),r.push(d.uid+""),o.push(d.token||this.joinInfo.appId)}),s.clientRequest={command:"SetDestChannel",channelName:i,uid:r,token:o},s;case pi.StartPacketTransfer:return s.clientRequest={command:"StartPacketTransfer"},s;case pi.Reconnect:return s.clientRequest={command:"Reconnect"},s;case pi.StopPacketTransfer:return s.clientRequest={command:"StopPacketTransfer"},s;case pi.UpdateDestChannel:if(a=n&&n.getDestChannelMediaInfo(),!a)throw new D(A.UNEXPECTED_ERROR,"can not find dest config");return a.forEach(d=>{i.push(d.channelName),r.push(d.uid+""),o.push(d.token||this.joinInfo.appId)}),s.clientRequest={command:"UpdateDestChannel",channelName:i,uid:r,token:o},s;case pi.SetVideoProfile:s.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return s}}const ate={name:"ChannelMediaRelay",create:function(e){return new ste(e.joinInfo,e.clientId,e.websocketRetryConfig||Bt,e.httpRetryConfig||Bt,e.resolution)}};function VV(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Hu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?VV(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):VV(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}class cte extends Nt{constructor(t,n,i,r){super(),S(this,"spec",void 0),S(this,"token",void 0),S(this,"websocket",void 0),S(this,"pingpongTimer",void 0),S(this,"reconnectMode","retry"),S(this,"serviceMode",void 0),S(this,"reqId",0),S(this,"commandReqId",0),S(this,"handleWebSocketOpen",()=>{this.reconnectMode="retry",this.startPingPong()}),S(this,"handleWebSocketMessage",o=>{if(!o.data)return;const s=JSON.parse(o.data);
122s.requestId?this.emit("@".concat(s.requestId,"-").concat(s.sid),s):(Z.workerEvent(this.spec.sid,{actionType:"status",serverCode:s.code,workerType:this.serviceMode===cs.TRANSCODE?1:2}),this.emit(Fs.PUBLISH_STREAM_STATUS,s))}),this.spec=n,this.token=t,this.serviceMode=r,this.websocket=new eu("live-streaming",i),this.websocket.on(Re.CONNECTED,this.handleWebSocketOpen),this.websocket.on(Re.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(Re.REQUEST_NEW_URLS,(o,s)=>{Jt(this,Fs.REQUEST_NEW_ADDRESS).then(o).catch(s)}),this.websocket.on(Re.RECONNECTING,()=>{this.websocket.reconnectMode=this.reconnectMode})}init(t){return this.websocket.init(t)}async request(t,n,i,r){this.reqId+=1,t==="request"&&(this.commandReqId+=1);const o=this.commandReqId,s=this.reqId;if(!s||!this.websocket)throw new D(A.UNEXPECTED_ERROR);const a=Hu({command:t,sdkVersion:qi==="4.24.3"?"0.0.1":qi,seq:s,requestId:s,allocate:i,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},n);if(this.websocket.state==="closed")throw new D(A.WS_DISCONNECT);const c=()=>new K((u,p)=>{this.websocket.once(Re.CLOSED,()=>p(new D(A.WS_ABORT))),this.websocket.once(Re.CONNECTED,u)});this.websocket.state!=="connected"&&await c(),a.clientRequest&&(a.clientRequest.workerToken=this.token);const d=new K((u,p)=>{const E=()=>{p(new D(A.WS_ABORT))};this.websocket.once(Re.RECONNECTING,E),this.websocket.once(Re.CLOSED,E),this.once("@".concat(s,"-").concat(this.spec.sid),m=>{u(m)})});r&&Z.workerEvent(this.spec.sid,Hu(Hu({},r),{},{requestId:o,actionType:"request",payload:JSON.stringify(n.clientRequest),serverCode:0,code:0}));const l=Date.now();this.websocket.sendMessage(a);let h=null;try{h=await d}catch(u){if(this.websocket.state==="closed")throw u;return await c(),await this.request(t,n,i)}return r&&Z.workerEvent(this.spec.sid,Hu(Hu({},r),{},{requestId:o,actionType:"response",payload:JSON.stringify(h.serverResponse),serverCode:h.code,success:h.code===200,responseTime:Date.now()-l})),h.code!==200&&this.handleResponseError(h),h}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){const t=qi==="4.24.3"?"0.0.1":qi;this.reqId+=1,this.websocket.state==="connected"?(this.websocket.sendMessage({command:"request",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:t,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:"DestroyWorker"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0)}handleResponseError(t){switch(t.code){case un.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void _.warning("live stream response already exists stream");case un.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case un.LIVE_STREAM_RESPONSE_BAD_STREAM:case un.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new D(A.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:t.code}).throw();case un.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if(t.serverResponse.command==="UnpublishStream")return;throw new D(A.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case un.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new D(A.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:t.code}).throw();case un.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const n=new D(A.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(Fs.WARNING,n,t.serverResponse.url)}case un.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const n=new D(A.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(Fs.WARNING,n,t.serverResponse.url)}case un.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new D(A.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case un.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new D(A.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:t.code}).throw();case un.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const n=new D(A.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(Fs.WARNING,n,t.serverResponse.url)}case un.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new D(A.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:t.code}).throw();case un.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new D(A.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case un.LIVE_STREAM_RESPONSE_WORKER_LOST:case un.LIVE_STREAM_RESPONSE_WORKER_QUIT:if(t.serverResponse.command==="UnpublishStream")return;throw new D(A.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case un.ERROR_FAIL_SEND_MESSAGE:if(t.serverResponse.command==="UnpublishStream")return;if(t.serverResponse.command==="UpdateTranscoding"||t.serverResponse.command==="ControlStream")return new D(A.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:t.code}).throw();throw new D(A.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case un.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case un.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case un.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case un.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new D(A.LIVE_STREAMING_CDN_ERROR,"",{code:t.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(()=>{this.websocket.state==="connected"&&this.request("ping",{}).catch(Hl)},6e3)}}function xV(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Ai(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
122t%2?xV(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):xV(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}class dte extends Nt{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Bt,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Bt;super(),S(this,"onLiveStreamWarning",void 0),S(this,"onLiveStreamError",void 0),S(this,"spec",void 0),S(this,"retryTimeout",1e4),S(this,"connection",void 0),S(this,"httpRetryConfig",void 0),S(this,"wsRetryConfig",void 0),S(this,"streamingTasks",new Map),S(this,"isStartingStreamingTask",!1),S(this,"taskMutex",new An("live-streaming")),S(this,"cancelToken",li.CancelToken.source()),S(this,"transcodingConfig",void 0),S(this,"uapResponse",void 0),S(this,"lastTaskId",1),S(this,"statusError",new Map),this.spec=t,this.httpRetryConfig=i,this.wsRetryConfig=n}async setTranscodingConfig(t){const n=Ai(Ai({},nJ),t);n.videoCodecProfile!==66&&n.videoCodecProfile!==77&&n.videoCodecProfile!==100&&(_.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(n.videoCodecProfile," -> 100")),n.videoCodecProfile=100),n.transcodingUsers||(n.transcodingUsers=n.userConfigs),n.transcodingUsers&&(n.transcodingUsers=n.transcodingUsers.map(s=>Ai(Ai(Ai({},tJ),s),{},{zOrder:s.zOrder?s.zOrder+1:1}))),function(s){xt(s.width)||ut(s.width,"config.width",0,1e4),xt(s.height)||ut(s.height,"config.height",0,1e4),xt(s.videoBitrate)||ut(s.videoBitrate,"config.videoBitrate",1,1e6),xt(s.videoFrameRate)||ut(s.videoFrameRate,"config.videoFrameRate"),xt(s.lowLatency)||xr(s.lowLatency,"config.lowLatency"),xt(s.audioSampleRate)||nn(s.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),xt(s.audioBitrate)||ut(s.audioBitrate,"config.audioBitrate",1,128),xt(s.audioChannels)||nn(s.audioChannels,"config.audioChannels",[1,2,3,4,5]),xt(s.videoGop)||ut(s.videoGop,"config.videoGop"),xt(s.videoCodecProfile)||nn(s.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),xt(s.userCount)||ut(s.userCount,"config.userCount",0,17),xt(s.backgroundColor)||ut(s.backgroundColor,"config.backgroundColor",0,16777215),xt(s.userConfigExtraInfo)||On(s.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),s.transcodingUsers&&!xt(s.transcodingUsers)&&(Lo(s.transcodingUsers,"config.transcodingUsers"),s.transcodingUsers.forEach((a,c)=>{$l(a.uid),xt(a.x)||ut(a.x,"transcodingUser[".concat(c,"].x"),0,1e4),xt(a.y)||ut(a.y,"transcodingUser[".concat(c,"].y"),0,1e4),xt(a.width)||ut(a.width,"transcodingUser[".concat(c,"].width"),0,1e4),xt(a.height)||ut(a.height,"transcodingUser[".concat(c,"].height"),0,1e4),xt(a.zOrder)||ut(a.zOrder-1,"transcodingUser[".concat(c,"].zOrder"),0,100),xt(a.alpha)||ut(a.alpha,"transcodingUser[".concat(c,"].alpha"),0,1,!1)})),xt(s.watermark)||tT(s.watermark,"watermark"),xt(s.backgroundImage)||tT(s.backgroundImage,"backgroundImage"),s.images&&!xt(s.images)&&(Lo(s.images,"config.images"),s.images.forEach((a,c)=>{tT(a,"images[".concat(c,"]"))}))}(n);const i=[];n.images&&i.push(...n.images.map(s=>Ai(Ai(Ai({},eT),s),{},{zOrder:255}))),n.backgroundImage&&(i.push(Ai(Ai(Ai({},eT),n.backgroundImage),{},{zOrder:0})),delete n.backgroundImage),n.watermark&&(i.push(Ai(Ai(Ai({},eT),n.watermark),{},{zOrder:255})),delete n.watermark),n.images=i,n.transcodingUsers&&(n.userConfigs=n.transcodingUsers.map(s=>Ai({},s)),n.userCount=n.transcodingUsers.length,delete n.transcodingUsers);const r=(n.userConfigs||[]).map(s=>typeof s.uid=="number"?K.resolve(s.uid):Tv(s.uid,this.spec,this.cancelToken.token,this.httpRetryConfig));if((await K.all(r)).forEach((s,a)=>{n.userConfigs&&n.userConfigs[a]&&(n.userConfigs[a].uid=s)}),this.transcodingConfig=n,this.connection)try{var o;const s=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(ti(o=this.streamingTasks).call(o)).map(a=>a.taskId).join("#")});_.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(s.code,", config:"),JSON.stringify(this.transcodingConfig))}catch(s){if(!s.data||!s.data.retry)throw s;s.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach(a=>{_.warning("[".concat(this.spec.clientId,"] live streaming receive error"),s.toString(),"try to republish",a.url),this.startLiveStreamingTask(a.url,a.mode,s).then(()=>{_.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(a.url," success"))}).catch(c=>{_.error("[".concat(this.spec.clientId,"] live streaming republish failed"),a.url,c.toString()),this.onLiveStreamError&&this.onLiveStreamError(a.url,c)})})}}async startLiveStreamingTask(t,n,i){if(!this.transcodingConfig&&n===cs.TRANSCODE)throw new D(A.INVA
122LID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");const r={command:"PublishStream",ts:Date.now(),url:t,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};_.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(t,", mode: ").concat(n));const o=await this.taskMutex.lock();if(!this.connection&&i)return void o();if(this.streamingTasks.get(t)&&!i)return o(),new D(A.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(n))}catch(a){throw o(),a}switch(n){case cs.TRANSCODE:r.transcodingConfig=Ai({},this.transcodingConfig)}this.uapResponse&&this.uapResponse.vid&&(r.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const s=this.lastTaskId++;try{const a=new K((d,l)=>{ln(this.retryTimeout).then(()=>{if(i)return l(i);const h=this.statusError.get(t);return h?(this.statusError.delete(t),l(h)):void 0})}),c=await K.race([this.connection.request("request",{clientRequest:r},!0,{url:t,command:"PublishStream",workerType:n===cs.TRANSCODE?1:2,requestByUser:!i,tid:s.toString()}),a]);this.isStartingStreamingTask=!1,_.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(c.co
vendor: 8,919 bytes, line 122
122de)),this.streamingTasks.set(t,{clientRequest:r,mode:n,url:t,taskId:s}),o()}catch(a){if(o(),this.isStartingStreamingTask=!1,!a.data||!a.data.retry||i)throw a;return a.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(t,n,a)):await this.startLiveStreamingTask(t,n,a)}}stopLiveStreamingTask(t){return new K((n,i)=>{const r=this.streamingTasks.get(t);if(!r||!this.connection)return new D(A.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const o=r.mode;r.abortTask=()=>{_.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(t),n()},this.connection.request("request",{clientRequest:{command:"UnpublishStream",url:r.url}},!1,{url:t,command:"UnPublishStream",workerType:o===cs.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then(s=>{_.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(s.code)),this.streamingTasks.delete(t),this.streamingTasks.size===0&&(this.connection&&this.connection.close(),this.connection=void 0),n()}).catch(i)})}resetAllTask(){var t;const n=Array.from(ti(t=this.streamingTasks).call(t));this.terminate();for(const i of n)this.startLiveStreamingTask(i.url,i.mode).catch(r=>{this.onLiveStreamError&&this.onLiveStreamError(i.url,r)})}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=li.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(t){if(this.connection)throw new D(A.UNEXPECTED_ERROR,"live streaming connection has already connected");const n=await Jt(this,nT.REQUEST_WORKER_MANAGER_LIST,t);return this.uapResponse=n,this.connection=new cte(n.workerToken,this.spec,this.wsRetryConfig,t),this.connection.on(Fs.WARNING,(i,r)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(r,i)),this.connection.on(Fs.PUBLISH_STREAM_STATUS,i=>this.handlePublishStreamServer(i)),this.connection.on(Fs.REQUEST_NEW_ADDRESS,(i,r)=>{if(!this.connection)return r(new D(A.UNEXPECTED_ERROR,"can not get new live streaming address list"));Jt(this,nT.REQUEST_WORKER_MANAGER_LIST,t).then(o=>{this.uapResponse=o,i(o.addressList)}).catch(r)}),await this.connection.init(n.addressList),this.connection}handlePublishStreamServer(t){const n=t.serverStatus&&t.serverStatus.url||"empty_url",i=this.streamingTasks.get(n),r=t.reason;switch(t.code){case un.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case un.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case un.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case un.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const s=new D(A.LIVE_STREAMING_CDN_ERROR,"",{code:t.code});if(i)return _.error(s.toString()),this.onLiveStreamError&&this.onLiveStreamError(n,s);if(!this.isStartingStreamingTask)return;this.statusError.set(n,s)}case un.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const s=new D(A.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,r);return this.onLiveStreamWarning&&this.onLiveStreamWarning(n,s)}case un.LIVE_STREAM_RESPONSE_WORKER_LOST:case un.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var o;if(!this.connection)return;this.connection.tryNextAddress();const s=Array.from(ti(o=this.streamingTasks).call(o));for(const a of s)a.abortTask?a.abortTask():(_.warning("[".concat(this.spec.clientId,"] publish stream status code"),t.code,"try to republish",a.url),this.startLiveStreamingTask(a.url,a.mode,new D(A.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:t.code})).then(()=>{_.debug("[".concat(this.spec.clientId,"] republish live stream success"),a.url)}).catch(c=>{_.error(c.toString()),this.onLiveStreamError&&this.onLiveStreamError(a.url,c)}));return}}}hasUrl(t){return this.streamingTasks.has(t)}}const lte={name:"LiveStreaming",create:function(e){return new dte(e.joinInfo,e.websocketRetryConfig||Bt,e.httpRetryConfig||Bt)}};function ute(e){let t=GV();return function(n,i){let r=n.appId;r!==void 0&&(rt(i,10),zo(i,r));let o=n.cid;o!==void 0&&(rt(i,16),rt(i,o));let s=n.cname;s!==void 0&&(rt(i,26),zo(i,s));let a=n.deviceId;a!==void 0&&(rt(i,34),zo(i,a));let c=n.elapse;c!==void 0&&(rt(i,40),sa(i,c));let d=n.fileSize;d!==void 0&&(rt(i,48),sa(i,Zd(d)));let l=n.height;l!==void 0&&(rt(i,56),sa(i,Zd(l)));let h=n.jpg;h!==void 0&&(rt(i,66),rt(i,h.length),function(We,M){let F=Qd(We,M.length);We.bytes.set(M,F)}(i,h));let u=n.networkType;u!==void 0&&(rt(i,72),sa(i,Zd(u)));let p=n.osType;p!==void 0&&(rt(i,80),sa(i,Zd(p)));let E=n.requestId;E!==void 0&&(rt(i,90),zo(i,E));let m=n.sdkVersion;m!==void 0&&(rt(i,98),zo(i,m));let g=n.sequence;g!==void 0&&(rt(i,104),sa(i,Zd(g)));let R=n.sid;R!==void 0&&(rt(i,114),zo(i,R));let v=n.timestamp;v!==void 0&&(rt(i,120),sa(i,v));let C=n.uid;C!==void 0&&(rt(i,128),rt(i,C));let w=n.vid;w!==void 0&&(rt(i,136),rt(i,w));let b=n.width;b!==void 0&&(rt(i,144),sa(i,Zd(b)));let y=n.service;y!==void 0&&(rt(i,152),rt(i,y));let N=n.callbackData;N!==void 0&&(rt(i,162),zo(i,N));let k=n.jpgEncryption;k!==void 0&&(rt(i,168),rt(i,k));let U=n.requestType;U!==void 0&&(rt(i,176),rt(i,U));let X=n.scorePorn;X!==void 0&&(rt(i,185),zv(i,X));let q=n.scoreSexy;q!==void 0&&(rt(i,193),zv(i,q));let se=n.scoreNeutral;se!==void 0&&(rt(i,201),zv(i,se));let _e=n.scene;_e!==void 0&&(rt(i,208),rt(i,_e));let me=n.ossFilePrefix;me!==void 0&&(rt(i,218),zo(i,me));let ke=n.serviceVendor;if(ke!==void 0)for(let We of ke){rt(i,226);let M=GV();_te(We,M),rt(i,M.limit),gte(i,M),fte(M)}}(e,t),function(n){let i=n.bytes,r=n.limit;return i.length===r?i:i.subarray(0,r)}(t)}function hte(e){return function(n){let i={};e:for(;!jV(n);){let r=qo(n);switch(r>>>3){case 0:break e;case 1:i.code=qo(n);break;case 2:i.msg=WV(n,qo(n));break;case 3:{let o=mte(n);i.data=pte(n),n.limit=o;break}default:FV(n,7&r)}}return i}({bytes:t=e,offset:0,limit:t.length});var t}function pte(e){let t={};e:for(;!jV(e);){let n=qo(e);switch(n>>>3){case 0:break e;case 1:t.requestId=WV(e,qo(e));break;case 2:t.requestType=qo(e)>>>0;break;case 3:t.scorePorn=Jv(e);break;case 4:t.scoreSexy=Jv(e);break;case 5:t.scoreNeutral=Jv(e);break;case 6:t.requestScene=qo(e)>>>0;break;case 7:t.scene=qo(e)>>>0;break;default:FV(e,7&n)}}return t}function _te(e,t){let n=e.service;n!==void 0&&(rt(t,8),rt(t,n));let i=e.vendor;i!==void 0&&(rt(t,16),rt(t,i));let r=e.token;r!==void 0&&(rt(t,26),zo(t,r));let o=e.callbackUrl;o!==void 0&&(rt(t,34),zo(t,o))}function mte(e){let t=qo(e),n=e.limit;return e.limit=e.offset+t,n}function FV(e,t){switch(t){case 0:for(;128&KV(e););break;case 2:Yv(e,qo(e));break;case 5:Yv(e,4);break;case 1:Yv(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let Ete=new Float32Array(1);new Uint8Array(Ete.buffer);let Hv=new Float64Array(1),Ci=new Uint8Array(Hv.buffer);function Zd(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let BV=[];function GV(){const e=BV.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function fte(e){BV.push(e)}function Yv(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function jV(e){return e.offset>=e.limit}function Qd(e,t){let n=e.bytes,i=e.offset,r=e.limit,o=i+t;if(o>n.length){let s=new Uint8Array(2*o);s.set(n),e.bytes=s}return e.offset=o,o>r&&(e.limit=o),i}function Xv(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function WV(e,t){let n=Xv(e,t),i=String.fromCharCode,r=e.bytes,o="\uFFFD",s="";for(let a=0;a<t;a++){let c,d,l,h,u=r[a+n];128&u?(224&u)==192?a+1>=t?s+=o:(c=r[a+n+1],(192&c)!=128?s+=o:(h=(31&u)<<6|63&c,h<128?s+=o:(s+=i(h),a++))):(240&u)==224?a+2>=t?s+=o:(c=r[a+n+1],d=r[a+n+2],(49344&(c|d<<8))!=32896?s+=o:(h=(15&u)<<12|(63&c)<<6|63&d,h<2048||h>=55296&&h<=57343?s+=o:(s+=i(h),a+=2))):(248&u)==240?a+3>=t?s+=o:(c=r[a+n+1],d=r[a+n+2],l=r[a+n+3],(12632256&(c|d<<8|l<<16))!=8421504?s+=o:(h=(7&u)<<18|(63&c)<<12|(63&d)<<6|63&l,h<65536||h>1114111?s+=o:(h-=65536,s+=i(55296+(h>>10),56320+(1023&h)),a+=3))):s+=o:s+=i(u)}return s}function zo(e,t){let n=t.length,i=0;for(let s=0;s<n;s++){let a=t.charCodeAt(s);a>=55296&&a<=56319&&s+1<n&&(a=(a<<10)+t.charCodeAt(++s)-56613888),i+=a<128?1:a<2048?2:a<65536?3:4}rt(e,i);let r=Qd(e,i),o=e.bytes;for(let s=0;s<n;s++){let a=t.charCodeAt(s);a>=55296&&a<=56319&&s+1<n&&(a=(a<<10)+t.charCodeAt(++s)-56613888),a<128?o[r++]=a:(a<2048?o[r++]=a>>6&31|192:(a<65536?o[r++]=a>>12&15|224:(o[r++]=a>>18&7|240,o[r++]=a>>12&63|128),o[r++]=a>>6&63|128),o[r++]=63&a|128)}}function gte(e,t){let n=Qd(e,t.limit),i=e.bytes,r=t.bytes;for(let o=0,s=t.limit;o<s;o++)i[o+n]=r[o]}function KV(e){return e.bytes[Xv(e,1)]}function HV(e,t){let n=Qd(e,1);e.bytes[n]=t}function Jv(e){let t=Xv(e,8),n=e.bytes;return Ci[0]=n[t++],Ci[1]=n[t++],Ci[2]=n[t++],Ci[3]=n[t++],Ci[4]=n[t++],Ci[5]=n[t++],Ci[6]=n[t++],Ci[7]=n[t++],Hv[0]}function zv(e,t){let n=Qd(e,8),i=e.bytes;Hv[0]=t,i[n++]=Ci[0],i[n++]=Ci[1],i[n++]=Ci[2],i[n++]=Ci[3],i[n++]=Ci[4],i[n++]=Ci[5],i[n++]=Ci[6],i[n++]=Ci[7]}function qo(e){let t,n=0,i=0;
122do t=KV(e),n<32&&(i|=(127&t)<<n),n+=7;while(128&t);return i}function rt(e,t){for(t>>>=0;t>=128;)HV(e,127&t|128),t>>>=7;HV(e,t)}function sa(e,t){let n=t.low>>>0,i=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=r===0?i===0?n<16384?n<128?1:2:n<1<<21?3:4:i<16384?i<128?5:6:i<1<<21?7:8:r<128?9:10,s=Qd(e,o),a=e.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=o!==9?128|r:127&r;case 8:a[s+7]=o!==8?i>>>21|128:i>>>21&127;case 7:a[s+6]=o!==7?i>>>14|128:i>>>14&127;case 6:a[s+5]=o!==6?i>>>7|128:i>>>7&127;case 5:a[s+4]=o!==5?128|i:127&i;case 4:a[s+3]=o!==4?n>>>21|128:n>>>21&127;case 3:a[s+2]=o!==3?n>>>14|128:n>>>14&127;case 2:a[s+1]=o!==2?n>>>7|128:n>>>7&127;case 1:a[s]=o!==1?128|n:127&n}}function YV(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}const Ste=new Map([["moderation",1],["supervise",2]]);class Tte extends Nt{get connectionState(){return this._connectionState}set connectionState(t){if(this._connectionState===t)return;const n=this._connectionState;this._connectionState=t,this.emit(Cn.CONNECTION_STATE_CHANGE,n,t)}get inspectType(){return this._inspectType}set inspectType(t){var n;this._inspectMode=ei(n=t.map(i=>Ste.get(i)||0)).call(n,(i,r)=>i+r),this._inspectType=t}get quality(){return this._quality}set quality(t){this._quality=t>1?1:t<.1?.1:t,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout(()=>
122{this.quality=this._quality/this.qualityRatio},6e4))}constructor(t){super(),S(this,"name","AgoraRTCVideoContentInspect"),S(this,"_connectionState",Hr.CONNECTING),S(this,"_innerConnectionState",void 0),S(this,"sequence",0),S(this,"inspectStartTime",void 0),S(this,"workerManagerConnection",void 0),S(this,"workerConnection",void 0),S(this,"workerMessageLengthLimit",void 0),S(this,"inspectIntervalMinimum",void 0),S(this,"qualityRatio",void 0),S(this,"_connectInfo",void 0),S(this,"_cancelTokenSource",li.CancelToken.source()),S(this,"_retryConfig",void 0),S(this,"wmSequence",0),S(this,"inspectInterval",void 0),S(this,"inspectTimer",null),S(this,"ossFilePrefix",void 0),S(this,"extraInfo",void 0),S(this,"_inspectType",void 0),S(this,"_inspectMode",void 0),S(this,"_quality",1),S(this,"qualityTimer",null),S(this,"_inspectId",void 0),S(this,"_needWorkUrlOnly",!1),S(this,"inspectImage",()=>{if(this.connectionState!==Hr.CONNECTED)throw new D(A.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval(()=>{this.connectionState===Hr.CONNECTED?this.requestToInspectImage():_.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)},this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()}),this._inspectId=Qe(5,"inspect-"),this.workerMessageLengthLimit=T("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=T("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=T("VIDEO_INSPECT_QUALITY_RATIO"),this.inspectInterval=t.interval,this.ossFilePrefix=t.ossFilePrefix,this.extraInfo=t.extraInfo,this.inspectType=t.inspectType,this.inspectStartTime=Number(Date.now()),this.workerManagerConnection=new eu("worker-manager-"+this._inspectId,Bt),this.on(Cn.STATE_CHANGE,(n,i)=>{this._innerConnectionState=n,_.debug("[".concat(this._inspectId,"] Inspect operation :").concat(Yr[n]," ").concat(i||""))}),this.handleWorkerManagerEvents(),this.workerConnection=new eu("worker-"+this._inspectId,Bt),this.handleWorkerEvents()}async init(t,n){this.emit(Cn.STATE_CHANGE,Yr.CONNECT_AP),this._connectInfo=t;const i=this._cancelTokenSource.token;return this._retryConfig=n,new K((r,o)=>{this.on(Cn.CONNECTION_STATE_CHANGE,(s,a)=>{a===Hr.CONNECTED&&r()}),this.requestAP(t,i,n).then(s=>{this.connectWorkerManager(s)}).catch(s=>{o(s)})})}async requestAP(t,n,i){const r=T("WEBCS_DOMAIN").map(a=>"https://".concat(a,"/api/v1")),o=await function(a,c,d,l){let{appId:h,areaCode:u,cname:p,sid:E,token:m,uid:g}=c;Kd++;const R="image_moderation_api",v={service_name:R,json_body:JSON.stringify({appId:h,areaCode:u,cname:p,command:"allocateEdge",requestId:Kd,seq:Kd,sid:E,token:m,ts:Date.now(),uid:g+""})};let C,w,b=a[0];return Fr(async()=>{C=Date.now();const y=await Qr(b,{data:v,cancelToken:d,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(w=Date.now()-C,y.code!==0){const q=new D(A.UNEXPECTED_RESPONSE,"image inspect ap error, code"+y.code,{retry:!0,responseTime:w});throw _.error(q.toString()),q}const N=JSON.parse(y.json_body);if(N.code!==200){const q=new D(A.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(N.code,", reason: ").concat(N.reason),{code:N.code,responseTime:w});throw _.error(q.toString()),q}if(!N.servers||!Array.isArray(N.servers)||N.servers.length===0){const q=new D(A.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:N.code,responseTime:w});throw _.error(q.toString()),q}const k=T("VIDEO_INSPECT_WORKER_MANAGER_WSS");if(k)return{addressList:[k],workerToken:N.workerToken,vid:N.vid,responseTime:w};const U=T("VIDEO_INSPECT_WORKER_MANAGER_HOST"),X=T("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:N.servers.map(q=>{let{address:se,wss:_e}=q;if(se&&_e)return"wss://".concat(se.replace(/\./g,"-"),".").concat(U,":").concat(X||_e)}).filter(q=>!!q),workerToken:N.workerToken,vid:N.vid,responseTime:w}},(y,N)=>(Z.apworkerEvent(E,{success:!0,sc:200,serviceName:R,responseDetail:JSON.stringify(y.addressList),firstSuccess:N===0,responseTime:w,serverIp:a[N%a.length]}),!1),(y,N)=>(Z.apworkerEvent(E,{success:!1,sc:y.data&&y.data.code||200,serviceName:R,responseTime:w,serverIp:a[N%a.length]}),!!(y.code!==A.OPERATION_ABORTED&&y.code!==A.UNEXPECTED_RESPONSE||y.data&&y.data.retry)&&(b=a[(N+1)%a.length],!0)),l)}(r,t,n,i);
122this.emit(Cn.STATE_CHANGE,Yr.AP_CONNECTED);const{addressList:s}=o;return this.wmSequence++,s}async connectWorkerManager(t){let n=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this._needWorkUrlOnly=n,this.emit(Cn.STATE_CHANGE,Yr.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(t,1e4)}async connectWorker(t){await this.workerConnection.init([t])}handleWorkerManagerEvents(){this.workerManagerConnection.on(Re.CONNECTED,async()=>{this.emit(Cn.STATE_CHANGE,Yr.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.24.3",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0)}),this.workerManagerConnection.on(Re.CLOSED,()=>{this._innerConnectionState<Yr.GET_WORKER_MANAGER_RESPONSE&&_.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))}),this.workerManagerConnection.on(Re.FAILED,()=>{this._innerConnectionState<Yr.GET_WORKER_MANAGER_RESPONSE&&_.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))}),this.workerManagerConnection.on(Re.RECONNECTING,()=>{this._innerConnectionState<Yr.GET_WORKER_MANAGER_RESPONSE&&_.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))}),this.workerManagerConnection.on(Re.ON_MESSAGE,async t=>{this.emit(Cn.STATE_CHANGE,Yr.GET_WORKER_MANAGER_RESPONSE);const n=this.workerManagerConnection.url;this.workerManagerConnection.close();const i=JSON.parse(t.data);if(i.code!==200)throw _.error("[".concat(this._inspectId,"] Unexpected code ").concat(i.code," from worker manager")),new D(A.UNEXPECTED_RESPONSE,"response code of worker is unexpected",i);if(!(i.serverResponse&&i.serverResponse.portWss&&n))throw _.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(i))),new D(A.UNEXPECTED_RESPONSE,"response content of worker is unexpected",i);{const r=T("VIDEO_INSPECT_WORKER_PORT")||i.serverResponse.portWss,o=n.replace(/:\d+\/?$/,":".concat(r));this.emit(Cn.STATE_CHANGE,Yr.CONNECT_WORKER,o),this._needWorkUrlOnly?this.emit(Cn.REQUEST_NEW_WORKER_URL,o):await this.connectWorker(o)}}),this.workerManagerConnection.on(Re.WILL_RECONNECT,(t,n,i)=>{i(t)}),this.workerManagerConnection.on(Re.REQUEST_NEW_URLS,(t,n)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(t).catch(n)})}handleWorkerEvents(){this.workerConnection.on(Re.CONNECTED,async()=>{this.emit(Cn.STATE_CHANGE,Yr.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=Hr.CONNECTED}),this.workerConnection.on(Re.ON_MESSAGE,async t=>{if(t.data instanceof ArrayBuffer){const i=hte(new Uint8Array(t.data));if(T("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&_.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(i)),i.code===200){if(Array.isArray(this.inspectType)&&this.inspectType.length===1&&this.inspectType[0]==="supervise")return void this.emit(Cn.INSPECT_RESULT,void 0,void 0);if(i.data&&i.data.scorePorn&&i.data.scoreSexy&&i.data.scoreNeutral){var n;const r={porn:i.data.scorePorn,sexy:i.data.scoreSexy,neutral:i.data.scoreNeutral},o=ei(n=Object.keys(r)).call(n,(a,c)=>r[a]>r[c]?a:c,"porn"),s=Object.keys(r).find(a=>a===o);this.emit(Cn.INSPECT_RESULT,s)}else this.emit(Cn.INSPECT_RESULT,void 0,new D(A.UNEXPECTED_RESPONSE,i.code+"","There is an unexpected data on message"))}else this.emit(Cn.INSPECT_RESULT,void 0,new D(A.UNEXPECTED_RESPONSE,i.code+"",i.msg))}else _.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(Cn.INSPECT_RESULT,void 0,new D(A.UNEXPECTED_RESPONSE,"invalid worker message type"))}),this.workerConnection.on(Re.CLOSED,()=>{this.connectionState=Hr.CLOSED}),this.workerConnection.on(Re.FAILED,()=>{this.connectionState=Hr.CLOSED}),this.workerConnection.on(Re.RECONNECTING,()=>{this.connectionState=this.connectionState===Hr.CONNECTED?Hr.RECONNECTING:Hr.CONNECTING}),this.workerConnection.on(Re.WILL_RECONNECT,(t,n,i)=>{t==="recover"&&i(t),i("tryNext")}),this.workerConnection.on(Re.REQUEST_NEW_URLS,(t,n)=>{this.workerManagerConnection.close(),this.once(Cn.REQUEST_NEW_WORKER_URL,i=>{t([i])}),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(i=>{this.connectWorkerManager(i,!0)}).catch(i=>{n(i)})})}async requestToInspectImage(){this.sequence++;const t=Ui(this,Cn.CLIENT_LOCAL_VIDEO_TRACK),n={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};
122if(t){if(!t.isPlaying)return void this.emit(Cn.INSPECT_RESULT,void 0,new D(A.INVALID_OPERATION,"Only the track being played can be inspected"));const i=await this.generateRequestData(t,n);this.workerConnection.sendMessage(i,!0,!0)}else this.emit(Cn.INSPECT_RESULT,void 0,new D(A.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(t,n){let{appId:i,cname:r,cid:o,vid:s,sid:a,uid:c}=n;const d=Date.now(),l=await t.getCurrentFrameImage("image/jpeg",this.quality),h=await kN(l,i,r),u=this.sequence+"-"+o+"-"+c+"-"+d+"-"+Qe(12,""),p={appId:i,cid:o,cname:r,deviceId:"",elapse:(E=Number(d-this.inspectStartTime),{low:E|=0,high:E>>31,unsigned:E>=0}),fileSize:h.byteLength,jpgEncryption:2,height:l.height,width:l.width,jpg:h,networkType:6,osType:7,requestId:u,sdkVersion:"4.24.3",sequence:this.sequence,sid:a,timestamp:F2(d),uid:c,vid:s,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};var E;this.extraInfo===void 0&&delete p.callbackData,this.ossFilePrefix===void 0&&delete p.ossFilePrefix;const m=ute(p);if(m.byteLength<this.workerMessageLengthLimit){if(T("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const g=function(R){for(var v=1;v<arguments.length;v++){var C=arguments[v]!=null?arguments[v]:{};v%2?YV(Object(C),!0).forEach(function(w){S(R,w,C[w])}):Object.getOwnPropertyDescriptors?Object.defineProperties(R,Object.getOwnPropertyDescriptors(C)):YV(Object(C)).forEach(function(w){Object.defineProperty(R,w,Object.getOwnPropertyDescriptor(C,w))})}return R}({},p);delete g.jpg,_.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(g))}return m}
122{const g=this.quality*this.qualityRatio;return this.quality=g,await this.generateRequestData(t,{appId:i,cname:r,cid:o,vid:s,sid:a,uid:c})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=li.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=Hr.CLOSED,this.emit(Cn.STATE_CHANGE,Yr.CLOSED)}}const Rte={name:"ContentInspect",create:function(e){let{config:t}=e;return function(n){if(!n)throw new D(A.INVALID_PARAMS,"inspectConfig is necessary.");if(!n.inspectType||!Array.isArray(n.inspectType))throw new D(A.INVALID_PARAMS,"inspectConfig.inspectType is necessary and is an instance of Array.");{const i=[...new Set(n.inspectType)];i.forEach(r=>{var o;if(!x(o=["supervise","moderation"]).call(o,r))throw new D(A.INVALID_PARAMS,"".concat(r," is not a valid inspect type."))}),n.inspectType=i}if(n&&n.extraInfo&&n.extraInfo.length>1024)throw new D(A.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}(t),new Tte(t)}};var XV=re(cr.Object.getOwnPropertySymbols),vte=st,Ate=nE.indexOf,Cte=th,qv=$n([].indexOf),JV=!!qv&&1/qv([1],1,-0)<0;vte({target:"Array",proto:!0,forced:JV||!Cte("indexOf")},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return JV?qv(this,e,t)||0:Ate(this,e,t)}});var yte=lr("Array").indexOf,Ite=Ee,bte=yte,Zv=Array.prototype,wte=function(e){var t=e.indexOf;return e===Zv||Ite(Zv,e)&&t===Zv.indexOf?bte:t},zV=re(wte);function Ote(e,t){if(e==null)return{};var n,i,r=function(s,a){if(s==null)return{};var c,d,l={},h=NP(s);for(d=0;d<h.length;d++)c=h[d],zV(a).call(a,c)>=0||(l[c]=s[c]);return l}(e,t);if(XV){var o=XV(e);for(i=0;i<o.length;i++)n=o[i],zV(t).call(t,n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}let qV=class{get localCapabilities(){return Ct(this._localCapabilities)}get rtpCapabilities(){return Ct(this._rtpCapabilities)}get candidates(){return Ct(this._candidates)}get iceParameters(){return Ct(this._iceParameters)}get dtlsParameters(){return Ct(this._dtlsParameters)}constructor(e){S(this,"sessionDesc",void 0),S(this,"_localCapabilities",void 0),S(this,"_rtpCapabilities",void 0),S(this,"_candidates",void 0),S(this,"_iceParameters",void 0),S(this,"_dtlsParameters",void 0),S(this,"setup",void 0),S(this,"currentMidIndex",void 0),S(this,"cname","o/i14u9pJrxRKAsu"),S(this,"firefoxSsrcMidMap",new Map),e=Ct(e);const{remoteIceParameters:t,remoteDtlsParameters:n,candidates:i,remoteRTPCapabilities:r,localCapabilities:o,direction:s,setup:a,videoCodec:c,audioCodec:d}=e;let l;this.setup=a,l=s===si.RECEIVE_ONLY?ii(`v=0 123o=- 0 0 IN IP4 127.0.0.1 124s=AgoraGateway 125t=0 0 126a=group:BUNDLE 0 1 127a=msid-semantic: WMS 128a=extmap-allow-mixed 129m=video 9 UDP/TLS/RTP/SAVPF 0 130c=IN IP4 127.0.0.1 131a=rtcp:9 IN IP4 0.0.0.0 132a=sendonly 133a=rtcp-mux 134a=rtcp-rsize 135a=mid:0 136m=audio 9 UDP/TLS/RTP/SAVPF 0 137c=IN IP4 127.0.0.1 138a=rtcp:9 IN IP4 0.0.0.0 139a=sendonly 140a=rtcp-mux 141a=rtcp-rsize 142a=mid:1 143`):ii(`v=0 144o=- 0 0 IN IP4 127.0.0.1 145s=AgoraGateway 146t=0 0 147a=group:BUNDLE 0 1 148a=msid-semantic: WMS 149a=extmap-allow-mixed 150m=video 9 UDP/TLS/RTP/SAVPF 0 151c=IN IP4 127.0.0.1 152a=rtcp:9 IN IP4 0.0.0.0 153a=recvonly 154a=rtcp-mux 155a=rtcp-rsize 156a=mid:0 157m=audio 9 UDP/TLS/RTP/SAVPF 0 158c=IN IP4 127.0.0.1 159a=rtcp:9 IN IP4 0.0.0.0 160a=recvonly 161a=rtcp-mux 162a=rtcp-rsize 163a=mid:1 164`),this._rtpCapabilities=r,this._candidates=i,this._iceParameters=t,this._dtlsParameters=n,this._localCapabilities=o;const h=s===si.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,u=s===si.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,p=s===si.RECEIVE_ONLY?r.send.videoCodecs:Vu($.VIDEO,h,u,c),E=s===si.RECEIVE_ONLY?r.send.audioCodecs:Vu($.AUDIO,h,u,d);for(const m of l.mediaDescriptions)m.attributes.iceUfrag=t.iceUfrag,m.attributes.icePwd=t.icePwd,m.attributes.fingerprints=n.fingerprints,m.attributes.candidates=i,m.attributes.setup=this.setup,m.media.mediaType==="application"&&(m.attributes.sctpPort="5000"),m.media.mediaType==="video"&&(m.media.fmts=p.map(g=>g.payloadType.toString(10)),m.attributes.payloads=p,m.attributes.extmaps=h.videoExtensions),m.media.mediaType==="audio"&&(m.media.fmts=E.map(g=>g.payloadType.toString(10)),m.attributes.payloads=E,m.attributes.extmaps=h.audioExtensions,Wd(m));this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return as(this.sessionDesc)}hasMid(e){return Array.isArray(e)?e.every(t=>this.hasMid(t)):this.sessionDesc.mediaDescriptions.some(t=>t.attributes.mid===e)}send(e,t,n,i,r){n=n.replace(/ /g,"-");const{ssrcs:o,ssrcGroups:s}=Mu(t,this.cname,T("SYNC_GROUP")?n:void 0),a=this.findPreloadMediaDesc(o);if(a){if(Rt()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,a.attributes.mid),r&&(r.twcc||r.remb)){const c=this.sessionDesc.mediaDescriptions.indexOf(a);return this.sessionDesc.mediaDescriptions[c]=this.mungSendMediaDesc(a,r),{mid:a.attributes.mid,needExchangeSDP:!0}}return{mid:a.attributes.mid,needExchangeSDP:!1}}{const c=this.findAvailableMediaIndex(e,o,i);let d;return c===-1?(d=this.createOrRecycleSendMedia(e,o,s,"sendonly",i,r),this.updateBundleMids()):(d=Ct(this.sessionDesc.mediaDescriptions[c]),d.attributes.direction="sendonly",d.attributes.ssrcs=o,d.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[c]=this.mungSendMediaDesc(d,r)),Rt()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,d.attributes.mid),{needExchangeSDP:!0,mid:d.attributes.mid}}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter(n=>n.attributes.mid&&e.indexOf(n.attributes.mid)!==-1);if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach(n=>
164{n.attributes.ssrcs=[]}),this.updateBundleMids()}receive(e,t,n){const i=[];return e.forEach(r=>{const o=r._mediaStreamTrack.kind,s=this.findAvailableRecvMediaIndex(o);let a,c=!1;s===-1?(c=!0,a=this.createOrRecycleRecvMedia(r,[],"recvonly",t,n),this.updateBundleMids()):(a=Ct(this.sessionDesc.mediaDescriptions[s]),a.attributes.direction="recvonly"),i.push({mid:a.attributes.mid,needCreateTransceiver:c})}),i}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter(n=>e.indexOf(n.attributes.mid)!==-1);if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach(n=>{n.media.port="0",n.attributes.direction="inactive"}),this.updateBundleMids()}addRemoteCandidate(e){const{foundation:t,protocol:n,address:i,port:r,type:o,relatedAddress:s,relatedPort:a,priority:c}=new RTCIceCandidate(e),d={foundation:t??"",componentId:"1",transport:n??"",priority:c?c+"":"",connectionAddress:i??"",port:r?r+"":"",type:o?o+"":"",relAddr:s??"",relPort:a?a+"":"",extension:{}};this.candidates.some(l=>l.priority===d.priority&&l.connectionAddress===d.connectionAddress&&l.port===d.port)||(this._candidates.push(d),this.sessionDesc.mediaDescriptions.forEach(l=>{l.attributes.candidates=this.candidates}))}clearRemoteCandidate(){this._candidates=[],this.sessionDesc.mediaDescriptions[0].attributes.candidates=this._candidates}createOrRecycleRecvMedia(e,t,n,i,r){const o=e._mediaStreamTrack.kind,s=this.rtpCapabilities.recv,a=Vu(o,s,this.localCapabilities.send,o===$.AUDIO?r:i),c=o===$.VIDEO?s.videoExtensions:s.audioExtensions,d="".concat(++this.currentMidIndex);let l={media:{mediaType:o,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map(u=>u.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungRecvMediaDsec(l,e);const h=this.findFirstClosedMedia(o);if(h){const u=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[u]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(n=>x(e).call(e,n.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(n=>{n.attributes.direction="inactive"})}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter(n=>x(e).call(e,n.attributes.mid||""));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach(n=>{n.attributes.direction="recvonly"})}findAvailableMediaIndex(e,t,n){return this.sessionDesc.mediaDescriptions.findIndex(i=>{const r=i.media.mediaType===e&&i.media.port!=="0"&&(i.attributes.direction==="sendonly"||i.attributes.direction==="sendrecv")&&i.attributes.ssrcs.length===0;if(Rt()){if(r){const o=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(o||i.attributes.mid!=="0"&&i.attributes.mid!=="1")||!(!o||o!==i.attributes.mid)}return!1}return r&&i.attributes.mid===n})}findAvailableRecvMediaIndex(e){return this.sessionDesc.mediaDescriptions.findIndex(t=>{const n=t.media.mediaType===e&&t.media.port!=="0"&&(t.attributes.direction==="recvonly"||t.attributes.direction==="sendrecv");return t.attributes.mid!=="0"&&t.attributes.mid!=="1"&&n})}predictReceivingMids(e){const t=[];for(let n=0;n<e;n++)t.push((this.currentMidIndex+n+1).toString(10));return t}restartICE(e){e=Ct(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd})}createOrRecycleSendMedia(e,t,n,i,r,o){const s=this.rtpCapabilities.send,a=e===$.VIDEO?s.videoCodecs:s.audioCodecs,c=e===$.VIDEO?s.videoExtensions:s.audioExtensions;Rt()&&(r="".concat(++this.currentMidIndex));let d={media:{mediaType:e,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map(h=>h.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:n,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:r}};d=this.mungSendMediaDesc(d,o);const l=this.findFirstClosedMedia(e);if(l){const h=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[h]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}
164mungRecvMediaDsec(e,t,n){const i=Ct(e);return av(i),rc(i,t),cv(i,t),PU(i),dm(i,n,this.localCapabilities.send),i}mungSendMediaDesc(e,t){const n=Ct(e);return dm(n,t,this.localCapabilities.recv),Wd(n),n}updateRecvMedia(e,t){const n=this.sessionDesc.mediaDescriptions.findIndex(i=>i.attributes.mid===e);if(n!==-1){const i=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],t);this.sessionDesc.mediaDescriptions[n]=i}}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(e=>e.media.port!=="0").map(e=>e.attributes.mid)}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find(t=>{var n;return((n=t.attributes)===null||n===void 0||(n=n.ssrcs[0])===null||n===void 0?void 0:n.ssrcId)===e[0].ssrcId})}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find(t=>Rt()?t.media.port==="0"&&t.media.mediaType===e:t.media.port==="0")}};const Nte=["sdp"];var It;function ZV(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function aa(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?ZV(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ZV(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}let QV=(It=class il extends UP{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var t,n;return(t=(n=this.peerConnection.getReceivers()[0])===null||n===void 0||(n=n.transport)===null||n===void 0?void 0:n.state)!==null&&t!==void 0?t:null}get localCodecs(){return[]}set isInRestartIce(t){this._isInRestartIce=t}get isInRestartIce(){return this._isInRestartIce}constructor(t,n,i){super(t,n),S(this,"direction",void 0),S(this,"name",void 0),S(this,"store",void 0),S(this,"spec",void 0),S(this,"peerConnection",void 0),S(this,"initialOffer",void 0),S(this,"transport",void 0),S(this,"statsFilter",void 0),S(this,"localCandidateCount",0),S(this,"_isInRestartIce",!1),S(this,"mutex",void 0),S(this,"onLocalCandidate",void 0),S(this,"remoteSDP",void 0),S(this,"pendingCandidates",[]),S(this,"localCapabilities",void 0),S(this,"isReady",!1),S(this,"restartCnt",0),S(this,"curTurnServerIndex",0),this.store=n,this.spec=t,this.mutex=new An("P2PConnection-mutex",n.clientId),this.peerConnection=new RTCPeerConnection(il.resolvePCConfiguration(t,n.p2pTransport),{optional:[{googDscp:!0}]}),this.direction=i??si.SEND_ONLY,this.name=this.direction===si.SEND_ONLY?"sendP2PConnection":"recvP2PConnection",this.statsFilter=Np(this.peerConnection,T("STATS_UPDATE_INTERVAL"),void 0,Rt()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1}async establish(t){try{const n=await lv();if(this.localCapabilities=Uu(n),t){const{sdp:i}=t,r=Ote(t,Nte),o=function(){const l={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},h=ku(arguments.length>2?arguments[2]:void 0,arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},"sendonly"),u={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},p={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},E={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(Zr(h,l,"videoExtensions",u,p,E),Zr(h,l,"videoCodecs",u,p,E),Zr(h,l,"audioExtensions",u,p,E),Zr(h,l,"audioCodecs",u,p,E),T("RAISE_H264_BASELINE_PRIORITY")){const m=E.videoCodecs.findIndex(g=>g.rtpMap&&g.rtpMap.encodingName.toLocaleLowerCase()==="h264"&&g.fmtp&&g.fmtp.parameters["profile-level-id"]==="42001f");if(m!==-1){const g=E.videoCodecs.findIndex(R=>R.rtpMap&&R.rtpMap.encodingName.toLocaleLowerCase()==="h264");if(g<m){_.debug("raising H264 baseline profile priority");const R=E.videoCodecs[m];E.videoCodecs.splice(m,1),E.videoCodecs.splice(g,0,R)}g!==-1&&T("FILTER_SEND_H264_BASELINE")&&(u.videoCodecs=u.videoCodecs.filter(R=>!(R.rtpMap&&R.rtpMap.encodingName.toLocaleLowerCase()==="h264"&&R.fmtp&&R.fmtp.parameters["profile-level-id"]!=="42001f")))}}return{send:u,recv:p,sendrecv:E}}({},{},i);this.remoteSDP=new qV({remoteIceParameters:r.iceParameters,remoteDtlsParameters:r.dtlsParameters,candidates:[],remoteRTPCapabilities:o,localCapabilities:this.localCapabilities,direction:this.direction,setup:"actpass",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()}),this.isReady=!0;const s=await this.peerConnection.createAnswer();if(!s.sdp)throw new Error("Cannot get answer sdp when trying to establish PeerConnection.");const a=Ho(s.sdp);await this.peerConnection.setLocalDescription(s);const c=await kU({},{},s.sdp);this.localCapabilities=Uu(c);const d=this.peerConnection.getTransceivers()[0];return d!=null&&d.receiver&&d.receiver.transport&&this.tryBindTransportEvents(d.receiver.transport),aa(aa({},a),{},{sdp:s.sdp})}{this.peerConnection.addTransceiver("video",{direction:"sendonly"}),this.peerConnection.addTransceiver("audio",{direction:"sendonly"});const i=await this.peerConnection.createOffer();if(!i.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const r=Ho(i.sdp);return this.initialOffer=i,aa(aa({},r),{},{sdp:i.sdp})}}catch(n){throw new L(A.GET_LOCAL_CONNECTION_PARAMS_FAILED,n.toString())}}async connect(t){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");await this.peerConnection.setLocalDescription(this.initialOffer);const{sdp:n,iceParameters:i,dtlsParameters:r}=t,o=await kU({},{},n);this.remoteSDP=new qV({remoteIceParameters:i,remoteDtlsParameters:r,candidates:[],remoteRTPCapabilities:o,localCapabilities:this.localCapabilities,direction:this.direction,setup:"active",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()});const s=this.peerConnection.getTransceivers()[0];s!=null&&s.sender&&s.sender.transport&&this.tryBindTransportEvents(s.sender.transport)}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(n.toString()))}}async addRemoteCandidate(t){try{t&&this.pendingCandidates.push(t),this.peerConnection.remoteDescription&&this.isReady&&(this.pendingCandidates.forEac
164h(n=>{this.peerConnection.addIceCandidate(n)}),this.pendingCandidates=[])}catch(n){throw new L(A.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(n.toString()))}}send(t,n,i){var r=this;return di(function*(){const o=yield ve(r.mutex.lock("From P2PConnection.send"));try{if(!r.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[],a=r.remoteSDP.receive(t,n,i);t.forEach((g,R)=>{if(a[R].needCreateTransceiver){const v=r.peerConnection.addTransceiver(g._mediaStreamTrack,{direction:"sendonly"});s.push(v),g._updateRtpTransceiver(v)}else{const v=r.peerConnection.getTransceivers().find(C=>C.mid===a[R].mid);if(!v)throw new Error("cannot find transceiver when sendPeerconnection send, mid is ".concat(a[R].mid));s.push(v),g._updateRtpTransceiver(v)}}),Rt()&&T("SIMULCAST")===!0&&(yield ve(r.applySimulcastForFirefox(s,t)));const c=a.map(g=>g.mid),d=yield ve(r.peerConnection.createOffer()),l=r.mungSendOfferSDP(d.sdp,t,c),h=ii(l),u=c.map(g=>{const R=h.mediaDescriptions.find(v=>v.attributes.mid===g);if(!R)throw new Error("Cannot extract ssrc from mediaDescription.");return sv(R,T("USE_PUB_RTX"))}),p=s.map((g,R)=>{const v=c[R];return{localSSRC:u[R],id:v}});yield ve(r.peerConnection.setLocalDescription({type:"offer",sdp:l}));try{yield p}catch(g){const R=r.remoteSDP.toString();throw yield ve(r.peerConnection.setLocalDescription({type:"offer",sdp:l})),yield ve(r.peerConnection.setRemoteDescription({type:"answer",sdp:R})),yield ve(r.stopSending(c,!0)),g}yield ve(r.applySimulcastEncodings(s,t)),yield ve(r.applySendEncodings(s,t));const E=r.remoteSDP.toString(),m=r.logSDPExchange(l,"offer","local","send");return m==null||m(E),yield ve(r.setRemoteDescription({type:"answer",sdp:E})),s.map((g,R)=>{const v=c[R];return{localSSRC:u[R],id:v}})}catch(s){throw s instanceof L?s:new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(s.toString()))}finally{o()}})()}async stopSending(t,n){const i=n?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const r=this.peerConnection.getTransceivers().filter(c=>t.indexOf(c.mid)!==-1);if(r.length!==t.length)throw new Error("Transceivers' length (".concat(r.length,") doesn't match mids' length (").concat(t.length,") when trying to call P2PConnection.stopSending."));r.map(c=>{var d;c.direction="inactive",(d=c.stop)===null||d===void 0||d.call(c)});const o=await this.peerConnection.createOffer(),s=this.logSDPExchange(o.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(o),this.remoteSDP.stopReceiving(t);const a=this.remoteSDP.toString();s==null||s(a),await this.setRemoteDescription({type:"answer",sdp:a})}catch(r){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(r.toString()))}finally{i&&i()}}async receive(t,n,i,r){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(t," before remoteSDP created."));const{mid:o,needExchangeSDP:s}=this.remoteSDP.send(t,n,i,r);if(s){const c=this.remoteSDP.toString(),d=this.logSDPExchange(c,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:c});const l=await this.peerConnection.createAnswer(),h=this.mungReceiveAnswerSDP(l.sdp,o,t);d==null||d(h||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:h}),_.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(t," by exchanging SDP."))}else _.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(t," no need to exchange SDP."));const a=this.peerConnection.getTransceivers().find(c=>c.mid===o);if(!a||a.mid===null)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:a.receiver.track,mid:a.mid,transceiver:a}}catch(o){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(o.toString()))}}async mockReceive(t,n,i,r){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(t," before remoteSDP created."));const{mid:o,needExchangeSDP:s}=this.remoteSDP.send(t,n,i,r);if(s){const a=this.remoteSDP.toString(),c=this.logSDPExchange(a,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:a});const d=await this.peerConnection.createAnswer(),l=this.mungReceiveAnswerSDP(d.sdp,o,t);c==null||c(l||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:l}),_.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").
164concat(t," by exchanging SDP."))}else _.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(t," no need to exchange SDP."))}catch(o){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(o.toString()))}}async stopReceiving(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(t);const n=this.remoteSDP.toString(),i=this.logSDPExchange(n,"offer","remote","stopReceiving");await this.setRemoteDescription({type:"offer",sdp:n});const r=await this.peerConnection.createAnswer();i==null||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(n.toString()))}}async restartICE(t){try{if(this.store.p2pTransport===ka.Auto&&(this.store.p2pTransport=ka.SdRtn,Oe().supportPCSetConfiguration&&this.peerConnection.setConfiguration(il.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,Oe().supportPCSetConfiguration&&this.peerConnection.setConfiguration(il.resolvePCConfiguration(this.spec,this.store.p2pTransport,++this.curTurnServerIndex))),!t){this.restartCnt++,this.isReady=!1;const n=await this.peerConnection.createOffer({iceRestart:!0});if(!n.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const{iceParameters:i}=Ho(n.sdp);return this.store.descriptionStart(),this.direction===si.SEND_ONLY&&await this.peerConnection.setLocalDescription(n),i}if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");if(this.remoteSDP.restartICE(t),this.store.descriptionStart(),this.direction===si.RECEIVE_ONLY){this.restartCnt++,await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()});const n=await this.peerConnection.createAnswer();if(!n.sdp)throw new Error("Cannot get answer sdp when trying to iceRestart.");const{iceParameters:i}=Ho(n.sdp);return await this.peerConnection.setLocalDescription(n),i}await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()}),this.isReady=!0}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(n.toString()))}}close(){var t;this.peerConnection.close(),this.peerConnection.onicecandidate=null,(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.transport=void 0,this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(t){return this.statsFilter.getVideoIsReady(t)}async updateEncoderConfig(t,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),r=this.mungSendOfferSDP(i.sdp,[n],[t]);this.remoteSDP.updateRecvMedia(t,n);const o=this.remoteSDP.toString(),s=this.logSDPExchange(r,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:r}),s==null||s(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(i){throw new L(A.EXCHANGE_SDP_FAILED,i.toString())}}async updateSendParameters(t,n){const i=this.peerConnection.getTransceivers().filter(r=>r.mid===t);i.length===1&&(this.isVP8Simulcast(n)?Rt()||await this.applySimulcastEncodings(i,[n]):await this.applySendEncodings(i,[n]))}setStatsRemoteVideoIsReady(t,n){this.statsFilter.setVideoIsReady2(t,n)}async replaceTrack(t,n){const i=this.peerConnection.getTransceivers().find(r=>r.mid===n);i&&await i.sender.replaceTrack(t._mediaStreamTrack)}async getSelectedCandidatePair(){const t=this.peerConnection.getReceivers();if(t.length>0&&t[0].transport&&t[0].transport.iceTransport&&t[0].transport.iceTransport.getSelectedCandidatePair&&t[0].transport.iceTransport.getSelectedCandidatePair()){const n=t[0].transport.iceTransport,{local:i,remote:r}=n.getSelectedCandidatePair();return{local:aa(aa({},Gr),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:aa(aa({},Gr),{},{candidateType:r.type,protocol:r.protocol,address:r.address,port:r.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var t,n;x(t=["connected","completed"]).call(t,this.peerConnection.iceConnectionState)&&(this.isReady=!1),(n=this.onICEConnectionStateChange)===null||n===void 0||n.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var t;this.peerConnection.connectionState==="connected"&&(this.restartCnt=0),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,this.peerConnection.connectionState)},this.startICECandidate()}startICECandidate(){this.peerConnection.onicecandidate||(this.localCandidateCount=0,this.peerConnection.onicecandidate=t=>{if(t.candidate){var n;t.candidate.candidate&&((n=this.onLocalCandidate)===null||n===void 0||n.call(this,t.candidate.toJSON())),this.localCandidateCount+=1}else _.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount)})}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0;const r={iceServers:[]};var o;return t.iceServers?r.iceServers=t.iceServers:t.turnServer&&t.turnServer.mode!=="off"&&(wa(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...il.turnServerConfigToIceServers(t.turnServer.servers,n,i)),T("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...il.turnServerConfigToIceServers(t.turnServer.serversFromGateway,n,i)),x(o=[ka.Relay,ka.SdRtn]).call(o,n)&&(r.iceTransportPolicy="relay"),T("FORCE_TURN_TCP")?r.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEac
164h(s=>{s.forceturn&&(r.iceTransportPolicy="relay")}))),T("ENABLE_ENCODED_TRANSFORM")&&Oe().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),_.debug("P2PConnection p2pTransport is ".concat(n)),r}static turnServerConfigToIceServers(t,n){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0;const r=[],o=t.filter(a=>a.tcpport);_.debug("P2PConnection turnServers is ".concat(o,", current index is ").concat(i));const s=o.length>i?o[i]:o[0];switch(n){case ka.SdRtn:const a=t.filter(d=>{var l;return x(l=d.username).call(l,"glb:")&&d.turnServerURL==d.turnServerURL}),c=a.length>i?a[i]:a[0];c&&(r.push({username:c.username,credential:c.password,credentialType:"password",urls:"turn:".concat(qr(c.turnServerURL),":").concat(c.tcpport,"?transport=udp")}),r.push({username:c.username,credential:c.password,credentialType:"password",urls:"turns:".concat(qr(c.turnServerURL),":").concat(c.tcpport,"?transport=tcp")}));break;case ka.Relay:s&&(r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(s.turnServerURL,":").concat(s.tcpport,"?transport=udp")}),r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(qr(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}));break;default:s&&(r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(s.turnServerURL,":").concat(s.tcpport,"?transport=udp")}),r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(qr(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}),r.push({username:s.username,credential:s.password,credentialType:"password",urls:"stun:".concat(s.turnServerURL,":").concat(s.tcpport)}))}return r}tryBindTransportEvents(t){if(t){this.transport=t,t.onstatechange=()=>{var i;t!=null&&t.state&&((i=this.onDTLSTransportStateChange)===null||i===void 0||i.call(this,t.state))},t.onerror=i=>{var r;(r=this.onDTLSTransportError)===null||r===void 0||r.call(this,"error"in i?i.error:i)};const n=t.iceTransport;n&&(n.onstatechange=()=>{const i=t==null?void 0:t.iceTransport.state;var r;i&&((r=this.onICETransportStateChange)===null||r===void 0||r.call(this,i))},n.getSelectedCandidatePair&&(n.onselectedcandidatepairchange=()=>{if(n.getSelectedCandidatePair()){const{local:i,remote:r}=n.getSelectedCandidatePair()||{};if(i&&r){const o=i.address+":"+i.port,s=r.address+":"+r.port;_.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(Ko(o)),", remote ").concat(JSON.stringify(Ko(s))))}}}))}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(t,n){var i;if(n||(n=this.peerConnection.getSenders().find(l=>l.track===t._mediaStreamTrack)),!n)return _.warn("[".concat(t.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(t))return _.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!Oe().supportSetRtpSenderParameters)return _.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const r={},o={};switch(t._optimizationMode){case"motion":r.degradationPreference="maintain-framerate";break;case"detail":r.degradationPreference="maintain-resolution";break;default:r.degradationPreference="balanced"}if(t._encoderConfig){var s;const{bitrateMax:l,frameRate:h,scaleResolutionDownBy:u}=t._encoderConfig;l&&(o.maxBitrate=1e3*l),x(s=t._hints).call(s,$e.LOW_STREAM)&&(h&&(o.maxFramerate=mi(h)),u&&u>=1&&(o.scaleResolutionDownBy=u))}if(T("DSCP_TYPE")&&Po()){var a;const l=T("DSCP_TYPE");x(a=["very-low","low","medium","high"]).call(a,l)&&(o.networkPriority=l)}const c=n.getParameters(),d=(i=c.encodings)===null||i===void 0?void 0:i[0];Rt()&&!d&&(r.encodings=[o]),d&&Object.assign(d,o),Object.assign(c,r),_.debug("[".concat(t.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(c.encodings))),await n.setParameters(c)}async applySendEncodings(t,n){try{if(!Oe().supportSetRtpSenderParameters||t.length!==n.length)return;for(let i=0;i<t.length;i++){const r=t[i],o=n[i];o instanceof pt&&!this.isVP8Simulcast(o)&&await this.updateRtpSenderEncodings(o,r.sender)}}catch{_.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(t,n,i){const r=ii(t);
164return n.forEach((o,s)=>{const a=i[s],c=r.mediaDescriptions.find(d=>d.attributes.mid===a);c&&(rc(c,o),dv(c,o,this.store.codec))}),as(r)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=t=>{var n;(n=this.onFirstAudioReceived)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstVideoReceived=t=>{var n;(n=this.onFirstVideoReceived)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstAudioDecoded=t=>{var n;(n=this.onFirstAudioDecoded)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstVideoDecoded=(t,n,i)=>{var r;(r=this.onFirstVideoDecoded)===null||r===void 0||r.call(this,t,n,i)},this.statsFilter.onSelectedLocalCandidateChanged=(t,n)=>{var i;(i=this.onSelectedLocalCandidateChanged)===null||i===void 0||i.call(this,t,n)},this.statsFilter.onSelectedRemoteCandidateChanged=(t,n)=>{var i;(i=this.onSelectedRemoteCandidateChanged)===null||i===void 0||i.call(this,t,n)},this.statsFilter.onFirstVideoDecodedTimeout=t=>{var n;(n=this.onFirstVideoDecodedTimeout)===null||n===void 0||n.call(this,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(t,n){if(t.length===n.length)for(let c=0;c<t.length;c++){var i,r,o,s,a;const d=t[c],l=n[c];if(l instanceof pt&&!x(i=l._hints).call(i,$e.LOW_STREAM)&&(r=l._encoderConfig)!==null&&r!==void 0&&r.bitrateMax&&((o=l._encoderConfig)===null||o===void 0?void 0:o.bitrateMax)>200&&(s=l._scalabilityMode)!==null&&s!==void 0&&s.numSpatialLayers&&((a=l._scalabilityMode)===null||a===void 0?void 0:a.numSpatialLayers)>1&&this.store.codec==="vp8"){const h={},u={high:1e3*(l._encoderConfig.bitrateMax-50),medium:5e4};h.encodings=[{rid:"m",active:!0,maxBitrate:u.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:u.high}];const p=d.sender.getParameters();await d.sender.setParameters(Object.assign(p,h))}}}
164async applySimulcastEncodings(t,n){if(!Rt()&&t.length===n.length)for(let i=0;i<t.length;i++){const r=n[i];if(r instanceof pt&&this.isVP8Simulcast(r)){const o=t[i],s={},a={high:1e3*(r._encoderConfig.bitrateMax-50),medium:5e4};s.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:a.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:a.medium,scaleResolutionDownBy:4}];const c=o.sender.getParameters();await o.sender.setParameters(Object.assign(c,s))}}}isVP8Simulcast(t){var n,i,r,o,s;return!!(t instanceof pt&&T("SIMULCAST")&&this.store.codec==="vp8"&&!x(n=t._hints).call(n,$e.LOW_STREAM)&&(i=t._encoderConfig)!==null&&i!==void 0&&i.bitrateMax&&((r=t._encoderConfig)===null||r===void 0?void 0:r.bitrateMax)>200&&(o=t._scalabilityMode)!==null&&o!==void 0&&o.numSpatialLayers&&((s=t._scalabilityMode)===null||s===void 0?void 0:s.numSpatialLayers)>1)}logSDPExchange(t,n,i,r){if(T("SDP_LOGGING"))return _.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(n," SDP during P2PConnection.").concat(r,` 165`),t),n==="offer"?o=>{this.logSDPExchange(o,"answer",i==="local"?"remote":"local",r)}:void 0}async muteLocal(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const n=this.peerConnection.getTransceivers().filter(s=>s.mid&&t.indexOf(s.mid)!==-1);if(n.length!==t.length)throw new Error("Transceivers' length doesn't match mids' length.");n.map(s=>{s.direction="inactive"});const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(t);const o=this.remoteSDP.toString();r==null||r(o),await this.setRemoteDescription({type:"answer",sdp:o})}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(n.toString()))}}async unmuteLocal(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const n=this.peerConnection.getTransceivers().filter(s=>s.mid&&t.indexOf(s.mid)!==-1);if(n.length!==t.length)throw new Error("Transceivers' length doesn't match mids' length.");n.map(async s=>{s.direction="sendonly"});const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(t);const o=this.remoteSDP.toString();r==null||r(o),await this.setRemoteDescription({type:"answer",sdp:o})}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(n.toString()))}}async getRemoteSSRC(t,n){var i,r;if(n=(i=n)!==null&&i!==void 0?i:(r=this.currentRemoteDescription)===null||r===void 0?void 0:r.sdp){var o;const s=(o=ii(n).mediaDescriptions.find(a=>a.attributes.mid===t))===null||o===void 0?void 0:o.attributes.ssrcs;return s==null?void 0:s[0].ssrcId}}async setRemoteDescription(t){var n;await this.peerConnection.setRemoteDescription(t),x(n=["connected","completed"]).call(n,this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate())}mungReceiveAnswerSDP(t,n,i){const r=ii(t),o=r.mediaDescriptions.find(s=>s.attributes.mid===n);return o&&i===$.AUDIO&&o.media.mediaType==="audio"&&Wd(o),as(r)}},H(It.prototype,"establish",[eo],Object.getOwnPropertyDescriptor(It.prototype,"establish"),It.prototype),H(It.prototype,"connect",[eo],Object.getOwnPropertyDescriptor(It.prototype,"connect"),It.prototype),H(It.prototype,"receive",[eo],Object.getOwnPropertyDescriptor(It.prototype,"receive"),It.prototype),H(It.prototype,"mockReceive",[eo],Object.getOwnPropertyDescriptor(It.prototype,"mockReceive"),It.prototype),H(It.prototype,"stopReceiving",[eo],Object.getOwnPropertyDescriptor(It.prototype,"stopReceiving"),It.prototype),H(It.prototype,"restartICE",[eo],Object.getOwnPropertyDescriptor(It.prototype,"restartICE"),It.prototype),H(It.prototype,"close",[eo],Object.getOwnPropertyDescriptor(It.prototype,"close"),It.prototype),H(It.prototype,"updateEncoderConfig",[eo],Object.getOwnPropertyDescriptor(It.prototype,"updateEncoderConfig"),It.prototype),H(It.prototype,"updateSendParameters",[eo],Object.getOwnPropertyDescriptor(It.prototype,"updateSendParameters"),It.prototype),H(It.prototype,"replaceTrack",[eo],Object.getOwnPropertyDescriptor(It.prototype,"replaceTrack"),It.prototype),H(It.prototype,"muteLocal",[eo],Object.getOwnPropertyDescriptor(It.prototype,"muteLocal"),It.prototype),H(It.prototype,"unmuteLocal",[eo],Object.getOwnPropertyDescriptor(It.prototype,"unmuteLocal"),It.prototype),It);function eo(e,t,n){const i=e[t];if(typeof i!="function")throw new Error("Cannot use mutex on object property.");return n.value=async function(){const r=this.mutex,o=await r.lock("From P2PConnection.".concat(t));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return await i.apply(this,a)}finally{o()}},n}let Ro=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({});var $V,ex,tx,nx,ix,rx,ox,sx,ax,cx,dx,Lt;function lx(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Dm(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
165t%2?lx(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lx(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}let Dte=($V=vo(Ro.SEND_ONLY),ex=vo(Ro.SEND_ONLY),tx=vo(),nx=vo(Ro.RECEIVE_ONLY),ix=vo(Ro.RECEIVE_ONLY),rx=vo(Ro.RECEIVE_ONLY),ox=vo(Ro.RECEIVE_ONLY),sx=vo(Ro.RECEIVE_ONLY),ax=vo(Ro.RECEIVE_ONLY),cx=vo(),dx=vo(Ro.RECEIVE_ONLY),Lt=class extends Nt{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(ae.StateChange,t,this._state)}constructor(e,t){super(),S(this,"isPlanB",!1),S(this,"store",void 0),S(this,"statsUploader",void 0),S(this,"sendConnection",void 0),S(this,"recvConnection",void 0),S(this,"localTrackMap",new Map),S(this,"remoteUserMap",new Map),S(this,"localDataChannels",[]),S(this,"pendingLocalTracks",[]),S(this,"pendingRemoteTracks",[]),S(this,"statsCollector",void 0),S(this,"dtlsFailedCount",0),S(this,"sendMutex",void 0),S(this,"recvMutex",void 0),S(this,"_state",qe.Disconnected),S(this,"_restartStates",["disconnected","failed"]),S(this,"reconnectInterval",void 0),S(this,"uploadUnplinkStarted",!1),S(this,"uploadDownlinkStarted",!1),S(this,"uplinkStateUploadInterval",void 0),S(this,"downlinkStatsUploadInterval",void 0),S(this,"handleMuteLocalTrack",async(n,i,r)=>{const o=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==qe.Connected)return void r(new L(A.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established."));const c=this.filterTobeMutedTracks(n);if(c.length===0)return void i();const d=c.find(p=>p[0]==="videoLowTrack");d&&d[1].track._originMediaStreamTrack.stop(),await this.sendConnection.muteLocal(c.map(p=>{let[,{id:E}]=p;return E}));let l=!1;var s,a;n.trackMediaType==="video"?l=!((s=this.localTrackMap.get(G.LocalAudioTrack))===null||s===void 0||!s.track._muted):l=((a=this.localTrackMap.get(G.LocalVideoTrack))===null||a===void 0?void 0:a.id)===void 0;const h=this.createMuteMessage(c);await mt(this,ae.RequestMuteLocal,h);const u=n.trackMediaType==="video"?Gs.MUTE_LOCAL_VIDEO:Gs.MUTE_LOCAL_AUDIO;await mt(this,ae.RequestP2PMuteLocal,{action:u,message:h,isMuteAll:l}),i()}catch(c){r(c)}finally{o()}}),S(this,"handleUnmuteLocalTrack",async(n,i,r)=>{const o=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==qe.Connected)return void r(new L(A.INVALID_OPERATION,"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established."));const s=this.filterTobeUnmutedTracks(n);if(s.length===0)return void i();await this.sendConnection.unmuteLocal(s.map(d=>{let[,{id:l}]=d;return l}));const a=this.createUnmuteMessage(s),c=n.trackMediaType==="video"?Gs.UNMUTE_LOCAL_VIDEO:Gs.UNMUTE_LOCAL_AUDIO;await mt(this,ae.RequestP2PMuteLocal,{action:c,message:a}),i()}catch(s){r(s)}finally{o()}}),S(this,"handleUpdateVideoEncoder",async(n,i,r,o)=>{let s;typeof o=="boolean"&&o||(s=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoEncoder"));try{const c=this.localTrackMap.get(G.LocalVideoTrack);if(!this.sendConnection||!c||c.track!==n||this.state!==qe.Connected)return void i();const{id:d,track:l}=c;d&&(await this.sendConnection.updateSendParameters(d,l),await this.sendConnection.updateEncoderConfig(d,l),this.emit(ae.UpdateVideoEncoder,l)),i()}catch(c){r(c)}finally{var a;(a=s)===null||a===void 0||a()}}),S(this,"handleUpdateVideoSendParameters",async(n,i,r)=>{const o=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoSendParameters");try{const s=this.localTrackMap.get(G.LocalVideoTrack);if(!this.sendConnection||!s||s.track!==n||this.state!==qe.Connected)return void i();const{id:a,track:c}=s;a&&await this.sendConnection.updateSendParameters(a,c),i()}catch(s){r(s)}finally{o()}}),S(this,"handleReplaceTrack",async(n,i,r,o)=>{let s;_.debug("[".concat(this.store.clientId,"] P2PChannel2 handleReplaceTrack for [track-id-").concat(n.getTrackId(),"]")),typeof o=="boolean"&&o||(s=await this.sendMutex.lock("From P2PChannel2.handleReplaceTrack"));try{var a;const d=Array.from(this.localTrackMap.entries()).find(l=>{let[,{track:h}]=l;return n===h});if(!this.sendConnection||!d||d[1].id===void 0||this.state!==qe.Connected)return void i();if(await((a=this.sendConnection)===null||a===void 0?void 0:a.replaceTrack(n,d[1].id)),d[0]===G.LocalVideoTrack&&Oe().supportDualStreamEncoding){const l=this.localTrackMap.get(G.LocalVideoLowTrack);if(l){const h=n._mediaStreamTrack.clone();l.track._originMediaStreamTrack.stop(),l.track._mediaStreamTrack=h,l.track._originMediaStreamTrack=h,await new K((u,p)=>{this.handleReplaceTrack(l.track,u,p,!0)})}}i()}catch(d){r(d)}finally{var c;(c=s)===null||c===void 0||c()}}),S(this,"handleGetLocalVideoStats",n=>{n(this.statsCollector.getLocalVideoTrackStats())}),S(this,"handleGetLocalAudioStats",n=>{n(this.statsCollector.getLocalAudioTrackStats())}),S(this,"handleGetRemoteVideoStats",n=>this.statsCollector.getRemoteVideoTrackStats(n.uid)[n.uid]),S(this,"handleGetRemoteAudioStats",n=>this.statsCollector.getRemoteAudioTrackStats(n.uid)[n.uid]),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new p2(e),this.bindStatsUploaderEvents(),this.sendMutex=new An("P2PChannel2-sen
165d-mutex",e.clientId),this.recvMutex=new An("P2PChannel2-recv-mutex",e.clientId),this.reconnectInterval=window.setInterval(()=>{[this.sendConnection,this.recvConnection].forEach(n=>{n&&(n.iceConnectionState!=="disconnected"&&n.iceConnectionState!=="failed"||this.handleDisconnect(n.direction))})},T("ICE_RESTART_INTERVAL"))}async startP2PConnection(e,t){throw new L(A.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.")}async connect(e){throw new L(A.NOT_SUPPORTED,"p2p mode does not support connect.")}async startP2P(e,t){let n;try{if(t){this.recvConnection&&(_.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset recvConnection.")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),n=await this.recvMutex.lock("From P2PChannel.startP2P"),this.recvConnection=new QV(e,this.store,si.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection);const i=await this.recvConnection.establish(t);return{iceParameters:i.iceParameters,dtlsParameters:i.dtlsParameters,sdp:i.sdp}}{this.state=qe.New,this.sendConnection&&(_.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset sendConnection.")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),n=await this.sendMutex.lock("From P2PChannel.startP2P"),this.sendConnection=new QV(e,this.store),this.store.peerConnectionStart(),this.bindConnectionEvents(this.sendConnection);const i=await this.sendConnection.establish();return{iceParameters:i.iceParameters,dtlsParameters:i.dtlsParameters,sdp:i.sdp}}}finally{n&&n()}}async p2pConnect(e){if(!this.sendConnection)throw new L(A.UNEXPECTED_ERROR,"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=qe.Connected}async addRemoteCandidate(e,t){if(t===si.RECEIVE_ONLY){if(!this.sendConnection)throw new L(A.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.sendConnection.addRemoteCandidate(e)}else{if(!this.recvConnection)throw new L(A.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(e)}}publish(e,t,n){var i=this;return di(function*(){const r=yield ve(i.sendMutex.lock("From P2PChannel.publish"));try{if(!i.sendConnection||i.state!==qe.Connected){i.throwIfTrackTypeNotMatch(e);const d=e.filter(l=>i.pendingLocalTracks.indexOf(l)===-1);return void(i.pendingLocalTracks=i.pendingLocalTracks.concat(d))}i.store.pubId=i.store.pubId+1,jn.markPublishStart(i.store.clientId,i.store.pubId);const o=i.filterTobePublishedTracks(e,t,n);if(o.length===0)return void(yield ve(i.tryToUnmuteAudio(e)));o.forEach(d=>{let{track:l,type:h}=d;const u=Date.now();i.store.publish(l.getTrackId(),h===G.LocalAudioTrack?"audio":"video",u)}),i.bindLocalTrackEvents(o);const s=yield ve(i.sendConnection.send(o.map(d=>{let{track:l}=d;return l}),i.store.codec,i.store.audioCodec)),a=(yield ve(s.next())).value,c=i.createGatewayPublishMessage(o,a);try{yield c}catch(d){throw s.throw(d),(d==null?void 0:d.code)===A.WS_ABORT&&o.forEach(l=>{let{track:h}=l;i.pendingLocalTracks.indexOf(h)===-1&&i.pendingLocalTracks.push(h)}),i.unbindLocalTrackEvents(o),d}yield ve(s.next()),o.forEach(d=>{let{type:l}=d;i.statsCollector.addLocalStats(l)}),i.statsUploader.startUploadOutboundStats(),i.assignLocalTracks(o,a),o.forEach(d=>{let{track:l,type:h}=d;const u=Date.now();i.store.publish(l.getTrackId(),h===G.LocalAudioTrack?"audio":"video",void 0,u)}),i.startUploadUplinkState()}finally{r()}})()}async unpublish(e){if(!this.sendConnection||this.state!==qe.Connected)return void(e.length===0?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter(r=>!x(e).call(e,r)));const t=this.filterTobeUnpublishedTracks(e);if(t.length===0)return;const n=t.find(r=>r[0]==="videoLowTrack");n&&n[1].track.close();const i=this.createGatewayUnpublishMessage(t);if(await this.sendConnection.stopSending(t.map(r=>{let[,{id:o}]=r;return o}
165)),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map(r=>{let[o,{track:s}]=r;return{type:o,track:s}})),t.forEach(r=>{let[o]=r;this.statsCollector.removeLocalStats(o)}),this.localTrackMap.size===0&&(this.statsUploader.stopUploadOutboundStats(),this.stopUploadUplinkState()),this.sendConnection&&this.state===qe.Connected)return n&&n[1].track.close(),i;e.forEach(r=>{const o=this.pendingLocalTracks.indexOf(r);o!==-1&&this.pendingLocalTracks.splice(o,1)})}startUploadUplinkState(){if(this.uploadUnplinkStarted)return;this.uploadUnplinkStarted=!0,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval);const e=()=>{const t=[],n=[];Array.from(this.localTrackMap.entries()).forEach(i=>{let[r,{track:o,ssrcs:s}]=i;const a={stream_type:Nee(o,r),ssrcs:s};o._muted||!o._enabled?t.push(a):n.push(a)}),t.length>0&&t.forEach(i=>{mt(this,ae.RequestMuteLocal,[i])}),n.length>0&&n.forEach(i=>{mt(this,ae.RequestUnmuteLocal,[i])})};e(),this.uplinkStateUploadInterval=window.setInterval(()=>{e()},3e3)}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval))}publishLowStream(e){return di(function*(){throw new L(A.NOT_SUPPORTED,"p2p mode does not support publishLowStream.")})()}async republish(){this.pendingLocalTracks.length>0&&(_.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await Jt(this,ae.RequestRePublish,this.pendingLocalTracks),this.emit(ae.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async unpublishLowStream(){throw new L(A.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.")}async subscribe(e,t,n,i){var r;if(!this.recvConnection)throw new L(A.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");if((r=this.remoteUserMap.get(e))!==null&&r!==void 0&&r.has(t))return;const{track:o,mid:s,transceiver:a}=await this.recvConnection.receive(t,[{ssrcId:n}],String(e.uid),i);t===$.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(o):(e._audioTrack=new Ed(o,e.uid,e._uintid,this.store),_.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),a&&e._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoSSRC=n,e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(o):(e._videoTrack=new md(o,e.uid,e._uintid,this.store),_.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),a&&e._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(e,e._videoTrack));const c=this.remoteUserMap.get(e);c?c.set(t,s):this.remoteUserMap.set(e,new Map([[t,s]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats(),this.startUploadDownlinkState();const d=this.pendingRemoteTracks.findIndex(l=>{let{user:h,kind:u}=l;return h.uid===e.uid&&t===u});d!==-1&&(this.pendingRemoteTracks.splice(d,1),this.emit(ae.MediaReconnectEnd,e.uid))}async mockSubscribe(e,t,n,i){if(!this.recvConnection)throw new L(A.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");await this.recvConnection.mockReceive(t,[{ssrcId:n}],String(e.uid),i)}async unsubscribe(e,t,n){const i=this.pendingRemoteTracks.filter(o=>{let{user:s,kind:a}=o;return t!==void 0?s.uid===e.uid&&t===a:s.uid===e.uid});if(i.forEach(o=>{const s=this.pendingRemoteTracks.indexOf(o);this.pendingRemoteTracks.splice(s,1)}),this.recvConnection||n||i.forEach(o=>{let{kind:s}=o;var a;if(s===$.AUDIO)(a=e._audioTrack)===null||a===void 0||a._destroy(),e._audioTrack=void 0;else if(s===$.VIDEO){var c;(c=e._videoTrack)===null||c===void 0||c._destroy(),e._videoTrack=void 0}}),!this.recvConnection)return;const r=this.filterTobeUnSubscribedTracks(e,t);r.length!==0&&(await this.recvConnection.stopReceiving(r.map(o=>{let[,{id:s}]=o;return s})),this.withdrawRemoteTracks(r),this.remoteUserMap.size===0&&(this.statsUploader.stopUploadInboundStats(),this.stopUploadDownlinkState()),r.forEach(o=>{let[s,{kind:a}]=o;var c,d;if(a===$.VIDEO&&s._videoSSRC&&((c=this.recvConnection)===null||c===void 0||c.setStatsRemoteVideoIsReady(s._videoSSRC,
165!1)),a===$.VIDEO)this.unbindRemoteTrackEvents(s._videoTrack),n||((d=s._videoTrack)===null||d===void 0||d._destroy(),s._videoTrack=void 0);else if(a===$.AUDIO){var l;this.unbindRemoteTrackEvents(s._audioTrack),!n&&((l=s._audioTrack)===null||l===void 0||l._destroy(),s._audioTrack=void 0)}}),r.forEach(o=>{let[,{kind:s}]=o;mt(this,ae.RequestP2PMuteRemote,s)}))}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);const e=()=>Array.from(this.remoteUserMap.entries()).forEach(t=>{let[,n]=t;[$.VIDEO,$.AUDIO].forEach(i=>{n.has(i)?mt(this,ae.RequestP2PUnmuteRemote,i):mt(this,ae.RequestP2PMuteRemote,i)})});e(),this.downlinkStatsUploadInterval=window.setInterval(()=>{e()},3e3)}stopUploadDownlinkState(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval))}getAllDataChannels(){return this.localDataChannels}async massSubscribe(e){throw new L(A.NOT_SUPPORTED,"p2p mode does not support massSubscribe.")}async massSubscribeNoLock(e){throw new L(A.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.")}async massUnsubscribe(e){throw new L(A.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.")}async massUnsubscribeNoLock(e){throw new L(A.NOT_SUPPORTED,"p2p mode does not support massUnsubscribeNoLock.")}async muteRemote(e,t){if(!this.recvConnection)return;const n=this.remoteUserMap.get(e);if(!n)return void _.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid,"."));if(!n.get(t))return void _.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const i=t===$.VIDEO?e._videoSSRC:e._audioSSRC;i!==void 0&&this.recvConnection.setStatsRemoteVideoIsReady(i,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.recvConnection)return;const n=this.remoteUserMap.get(e);if(!n)return void _.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid,"."));n.get(t)||_.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}getAllTracks(e){const t=this.localTrackMap.get(G.LocalAudioTrack);if((t==null?void 0:t.track)instanceof En){const n=t.track;return Array.from(this.localTrackMap.entries()).filter(i=>{let[r]=i;return r!==G.LocalAudioTrack}).filter(i=>{let[r]=i;return!(e&&r===G.LocalVideoLowTrack)}).map(i=>{let[,{track:r}]=i;return r}).concat(n.trackList)}return Array.from(this.localTrackMap.entries()).filter(n=>{let[i]=n;return!(e&&i===G.LocalVideoLowTrack)}).map(n=>{let[,{track:i}]=n;return i})}reportPublishEvent(e,t,n,i,r){if(e){const s=this.localTrackMap.get(G.LocalAudioTrack),a=i?this.localTrackMap.get(G.LocalVideoLowTrack):this.localTrackMap.get(G.LocalVideoTrack);Z.publish(this.store.sessionId,{eventElapse:jn.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:s==null?void 0:s.track.getTrackLabel(),videoName:a==null?void 0:a.track.getTrackLabel(),screenshare:(a==null?void 0:a.track._hints.indexOf($e.SCREEN_TRACK))!==-1,audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;n||(n=[]);const s=n.find(c=>c instanceof jt),a=i?(o=this.localTrackMap.get(G.LocalVideoTrack))===null||o===void 0?void 0:o.track:n.find(c=>c instanceof pt);Z.publish(this.store.sessionId,{eventElapse:jn.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:s==null?void 0:s.getTrackLabel(),videoName:a==null?void 0:a.getTrackLabel(),screenshare:(a==null?void 0:a._hints.indexOf($e.SCREEN_TRACK))!==-1,audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,n,i){const r=i===$.VIDEO?n._videoSSRC:n._audioSSRC;r&&Z.subscribe(this.store.sessionId,{succ:e,ec:t,video:i===$.VIDEO,audio:i===$.AUDIO,peerid:n.uid,subscribeRequestid:i===$.VIDEO?n._videoSSRC:n._audioSSRC,p2pid:this.store.p2pId,eventElapse:jn.measureFromSubscribeStart(this.store.clientId,r)})}reset(){_.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new An("P2PChannel2-sen
165d-mutex",this.store.clientId),this.sendMutex=new An("P2PChannel2-recv-mutex",this.store.clientId),this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(G.LocalAudioTrack);if((e==null?void 0:e.track)instanceof En){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach(n=>{t.removeAudioTrack(n)})}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.reconnectInterval&&(window.clearInterval(this.reconnectInterval),this.reconnectInterval=void 0),this.state=qe.Disconnected}getStats(e){var t,n;return e?(n=this.recvConnection)===null||n===void 0?void 0:n.getStats():(t=this.sendConnection)===null||t===void 0?void 0:t.getStats()}getRemoteVideoIsReady(e){var t;return((t=this.recvConnection)===null||t===void 0?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(G.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(G.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof pt||t&&t.track instanceof jt?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}getRemoteMedia(e){var t;const n=Array.from(_n(t=this.remoteUserMap).call(t)).find(i=>i.uid===e);return n?{audioTrack:n.audioTrack,audioSSRC:n._audioSSRC,videoTrack:n.videoTrack,videoSSRC:n._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map(n=>{let[i]=n;return{uid:i.uid,level:i.audioTrack?100*i.audioTrack._source.getAccurateVolumeLevel():0}});const t=this.localTrackMap.get(G.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=Pi(e).call(e,(n,i)=>n.level-i.level),e}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(_.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=qe.Reconnecting,T("KEEP_LAST_FRAME")&&this.remoteUserMap.size!==0&&Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t]=e;var n;t._videoTrack&&t._videoTrack._player&&((n=t._videoTrack._player.getVideoElement())===null||n===void 0||n.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())}),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0,this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0,this.localTrackMap.size!==0&&(Array.from(this.localTrackMap.entries()).forEach(e=>{var t;let[n,{track:i}]=e;switch(n){case G.LocalVideoTrack:x(t=i._hints).call(t,$e.LOW_STREAM)?i.close():this.pendingLocalTracks.push(i);break;case G.LocalAudioTrack:i instanceof En?this.pendingLocalTracks=this.pendingLocalTracks.concat(i.trackList):this.pendingLocalTracks.push(i);case G.LocalVideoLowTrack:}}),this.emit(ae.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),this.remoteUserMap.size!==0&&Array.from(this.remoteUserMap.entries()).forEac
165h(e=>{let[t,n]=e;Array.from(_n(n).call(n)).forEach(i=>{this.setPendingRemoteMedia(t,i)}),this.emit(ae.MediaReconnectStart,t.uid)}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),_.debug("[".concat(this.store.clientId,"] P2PChannel2 disconnected, waiting to reconnect.")))}hasPendingRemoteMedia(e,t){for(const n of this.pendingRemoteTracks){const{user:i,kind:r}=n;if((e instanceof na?e.uid:e)===i.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}async restartICE(e,t){let n,i;if(e===si.SEND_ONLY){if(!this.sendConnection)throw new L(A.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.");n=await this.sendMutex.lock("From P2PChannel.restartICE"),i=this.sendConnection}else{if(!this.recvConnection)throw new L(A.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before recvConnection established.");n=await this.recvMutex.lock("From P2PChannel.restartICE"),i=this.recvConnection}try{if(t){const r=await i.restartICE(t);return i.isInRestartIce=!1,r}{const r=await i.restartICE();if(r){const o=await Jt(this,ae.RequestP2PRestartICE,{direction:si.RECEIVE_ONLY,iceParameter:r});await i.restartICE(o),i.isInRestartIce=!1}}}finally{n()}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const e=this.sendConnection.getStats(),t=this.localTrackMap.get(G.LocalVideoTrack),n=this.localTrackMap.get(G.LocalAudioTrack),i=e.videoSend.find(p=>{var E;return p.ssrc===(t==null||(E=t.ssrcs)===null||E===void 0?void 0:E[0].ssrcId)}),r=e.audioSend.find(p=>{var E;return p.ssrc===(n==null||(E=n.ssrcs)===null||E===void 0?void 0:E[0].ssrcId)});if(!i||!r)return 1;const o=Ui(this,ae.NeedSignalRTT),s=i?i.rttMs:void 0,a=r?r.rttMs:void 0,c=s&&a?(s+a)/2:s||a,d=(c&&o?(c+o)/2:c||o)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,h=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,u=t==null?void 0:t.track;if(u&&u._encoderConfig&&u._hints.indexOf($e.SCREEN_TRACK)===-1){const p=u._encoderConfig.bitrateMax,E=e.bitrate.actualEncoded;if(p&&E){const m=(1e3*p-E)/(1e3*p);return bP[m<.15?0:m<.3?1:m<.45?2:m<.6?3:4][h]}}return h}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;const e=this.recvConnection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach(n=>{let[i]=n;const r=i._audioSSRC,o=i._videoSSRC,s=e.audioRecv.find(E=>E.ssrc===r),a=e.videoRecv.find(E=>E.ssrc===o);if(!s&&!a)return void(t+=1);const c=Ui(this,ae.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,h=s?s.jitterMs:void 0,u=e.recvPacketLossRate;let p=.7*u*100/50+.3*l/1500;h&&(p=.6*u*100/50+.2*l/1500+.2*h/400),t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5}),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new K((t,n)=>{this.handleMuteLocalTrack(e,t,n)})}filterTobePublishedTracks(e,t,n){const i=[],r=Oe(),o=this.getAllTracks();e=nd(e=e.filter(c=>o.indexOf(c)===-1));let s=!1,a=!1;for(const c of e){if(c instanceof pt&&(this.localTrackMap.has(G.LocalVideoTrack)||s?new L(A.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(i.push({track:c,type:G.LocalVideoTrack}),s=!0),t)){const d=this.getLowVideoTrack(c,n);i.push({track:d,type:G.LocalVideoLowTrack})}if(c instanceof jt){const d=this.localTrackMap.get(G.LocalAudioTrack);if(d){if(!(d.track instanceof En))throw new L(A.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(c._bypassWebAudio)throw new L(A.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");d.track.addAudioTrack(c),this.bindLocalAudioTrackEvents(c,!0)}else if(a){const l=i.find(h=>{let{type:u}=h;return u===G.LocalAudioTrack});if(!(l.track instanceof En))throw new L(A.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(c._bypassWebAudio)throw new L(A.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");l.track.addAudioTrack(c)}else{if(!r.webAudioMediaStreamDest||c instanceof En||c._bypassWebAudio)i.push({track:c,type:G.LocalAudioTrack});else{const l=new En;l.addAudioTrack(c),i.push({track:l,type:G.LocalAudioTrack})}a=!0}}}return i}filterTobeUnpublishedTracks(e){const t=[],n=this.getAllTracks();e=nd(e=e.filter(i=>n.indexOf(i)!==-1));for(const i of e){if(i instanceof jt){const r=this.localTrackMap.get(G.LocalAudioTrack);if(!r)continue;r.track instanceof En?(r.track.removeAudioTrack(i),this.unbindLocalAudioTrackEvents(i),r.track.trackList.length===0&&(t.push([G.LocalAudioTrack,r]),r.track.close())):t.push([G.LocalAudioTrack,r])}if(i instanceof pt){const r=this.localTrackMap.get(G.LocalVideoTrack);if(!r)continue;t.push([G.LocalVideoTrack,r]);const o=this.localTrackMap.get(G.LocalVideoLowTrack);o&&t.push([G.LocalVideoLowTrack,o])}}return t}bindLocalTrackEvents(e){e.forEach(t=>{let{track:n,type:i}=t;switch(i){case G.LocalVideoTrack:n.addListener(te.GET_STATS,this.handleGetLocalVideoStats),n.addListener(te.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),n.addListener(te.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),n.addListener(te.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),n.addListener(te.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),n.addListener(te.NEED_REPLACE_TRACK,this.handleReplaceTrack),n.addListener(te.NEED_MUTE_TRACK,this.handleMuteLocalTrack),n.addListener(te.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case G.LocalAudioTrack:this.bindLocalAudioTrackEvents(n);case G.LocalVideoLowTrack:}})}bindLocalAudioTrackEvents(e,t){e instanceof En?e.trackList.forEach(n=>
165{n.addListener(te.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),n.addListener(te.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),n.addListener(te.GET_STATS,this.handleGetLocalAudioStats),n.addListener(te.NEED_MUTE_TRACK,this.handleMuteLocalTrack),n.addListener(te.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.addListener(te.GET_STATS,this.handleGetLocalAudioStats),e.addListener(te.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(te.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(te.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(te.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(te.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map(t=>{let[n,{track:i}]=t;return{track:i,type:n}})),e.forEach(t=>{let{track:n,type:i}=t;switch(i){case G.LocalVideoTrack:n.off(te.GET_STATS,this.handleGetLocalVideoStats),n.off(te.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),n.off(te.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),n.off(te.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),n.off(te.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),n.off(te.NEED_REPLACE_TRACK,this.handleReplaceTrack),n.off(te.NEED_MUTE_TRACK,this.handleMuteLocalTrack),n.off(te.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case G.LocalAudioTrack:this.unbindLocalAudioTrackEvents(n);case G.LocalVideoLowTrack:}})}unbindLocalAudioTrackEvents(e){e instanceof En?e.trackList.forEach(t=>{t.off(te.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(te.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(te.GET_STATS,this.handleGetLocalAudioStats),t.off(te.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(te.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(e.off(te.GET_STATS,this.handleGetLocalAudioStats),e.off(te.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(te.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(te.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(te.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(te.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof md&&t.addListener(te.GET_STATS,n=>{n(this.handleGetRemoteVideoStats(e))}),t instanceof Ed&&t.addListener(te.GET_STATS,n=>{n(this.handleGetRemoteAudioStats(e))})}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(te.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(e=>{let[t,n]=e;n.has($.AUDIO)&&this.unbindRemoteTrackEvents(t._audioTrack),n.has($.VIDEO)&&this.unbindRemoteTrackEvents(t._videoTrack)})}createGatewayPublishMessage(e,t){return e.map((n,i)=>{var r;let o,{track:s,type:a}=n;switch(a){case G.LocalAudioTrack:o=nt.Audio;break;case G.LocalVideoTrack:o=x(r=s._hints).call(r,$e.SCREEN_TRACK)?nt.Screen:nt.High;break;case G.LocalVideoLowTrack:o=nt.Low}return{kind:a===G.LocalAudioTrack?$.AUDIO:$.VIDEO,stream_type:o,mid:t[i].id,ssrcs:t[i].localSSRC,isMuted:s.muted||!s.enabled}})}createGatewayUnpublishMessage(e){return e.map(t=>{var n;let i,[r,{track:o,ssrcs:s,id:a}]=t;switch(r){case G.LocalVideoTrack:i=x(n=o._hints).call(n,$e.SCREEN_TRACK)?nt.Screen:nt.High;break;case G.LocalAudioTrack:i=nt.Audio;break;case G.LocalVideoLowTrack:i=nt.Low}return{stream_type:i,ssrcs:s,mid:a}})}assignLocalTracks(e,t){e.forEach((n,i)=>{let{track:r,type:o}=n;this.localTrackMap.set(o,{track:r,id:t[i].id,ssrcs:t[i].localSSRC})})}withdrawLocalTracks(e){e.forEach(t=>{let[n]=t;this.localTrackMap.delete(n)})}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{var n;_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: ").concat(e.name,".onConnectionStateChange(").concat(t,")")),this.emit(ae.PeerConnectionStateChange,t),t!=="connected"||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),t==="connected"&&(e.isInRestartIce=!1),x(n=this._restartStates).call(n,t)&&!e.isInRestartIce&&(t==="disconnected"&&await ln(800),e.iceConnectionState!=="disconnected"&&e.iceConnectionState!=="failed"||this.handleDisconnect(e.direction))},e.onICEConnectionStateChange=t=>{t!=="connected"||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(t,")")),Z.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:t,tag:ht.TRACER}
165).onSuccess(),this.emit(ae.IceConnectionStateChange,t)},e.onICETransportStateChange=t=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(t,")"))},e.onDTLSTransportStateChange=t=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(t,")"))},e.onDTLSTransportError=t=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(t,")"))},e.onFirstAudioDecoded=t=>{var n;const i=Array.from(_n(n=this.remoteUserMap).call(n)).find(o=>o._audioSSRC===t);var r;i&&(this.store.subscribe(i.uid,"audio",void 0,void 0,void 0,Date.now()),(r=i.audioTrack)===null||r===void 0||r.emit(pr.FIRST_FRAME_DECODED),Z.firstRemoteFrame(this.store.sessionId,an.FIRST_AUDIO_DECODE,yt.FIRST_AUDIO_DECODE,{peer:i._uintid,subscribeElapse:jn.measureFromSubscribeStart(this.store.clientId,t),subscribeRequestid:t,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=t=>{var n;const i=Array.from(_n(n=this.remoteUserMap).call(n)).find(r=>r._audioSSRC===t);i&&Z.firstRemoteFrame(this.store.sessionId,an.FIRST_AUDIO_RECEIVED,yt.FIRST_AUDIO_RECEIVED,{peer:i._uintid,subscribeElapse:jn.measureFromSubscribeStart(this.store.clientId,t),subscribeRequestid:t,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(t,n,i)=>{this.reportVideoFirstFrameDecoded(t,n,i)},e.onFirstVideoReceived=t=>{var n;const i=Array.from(_n(n=this.remoteUserMap).call(n)).find(r=>r._videoSSRC===t);i&&Z.firstRemoteFrame(this.store.sessionId,an.FIRST_VIDEO_RECEIVED,yt.FIRST_VIDEO_RECEIVED,{peer:i._uintid,subscribeElapse:jn.measureFromSubscribeStart(this.store.clientId,t),subscribeRequestid:t,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(t,n)=>{const i=t.candidateType==="relay",r=n.candidateType==="relay";n.candidateType!=="unknown"&&i===r||this.emit(ae.ConnectionTypeChange,i),_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(ea(n))," -> ").concat(JSON.stringify(ea(t)),")"))},e.onSelectedRemoteCandidateChanged=(t,n)=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(ea(n))," -> ").concat(JSON.stringify(ea(t)),")"))},e.onFirstVideoDecodedTimeout=t=>{this.reportVideoFirstFrameDecoded(t,void 0,void 0,!0)},e.onLocalCandidate=t=>{this.emit(ae.LocalCandidate,{candidate:t,direction:e.direction})}}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.onLocalCandidate=void 0}async handleDisconnect(e){const t=e===si.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,_.debug("[".concat(this.store.clientId,"] [P2PChannel-").concat(t.name,"] start use restartICE")),e===si.SEND_ONLY?this.restartICE(e):Jt(this,ae.RequestP2PRestartICE,{direction:si.SEND_ONLY}))}filterTobeMutedTracks(e){const t=[];if(this.getAllTracks().indexOf(e)===-1)return t;const n=this.localTrackMap.get(G.LocalAudioTrack);if(e instanceof jt&&(n==null?void 0:n.track)instanceof En)return n.track.isActive||t.push([G.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find(r=>{let[,{track:o}]=r;return e===o});if(i&&(t.push(i),i[0]===G.LocalVideoTrack)){const r=this.localTrackMap.get(G.LocalVideoLowTrack);r&&t.push([G.LocalVideoLowTrack,r])}return t}filterTobeUnmutedTracks(e){const t=[],n=this.localTrackMap.get(G.LocalAudioTrack);if(e instanceof jt&&(n==null?void 0:n.track)instanceof En)return n.track.isActive&&t.push([G.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find(r=>{let[,{track:o}]=r;return e===o});if(i)if(i[0]===G.LocalVideoTrack){t.push(i);const r=this.localTrackMap.get(G.LocalVideoLowTrack);r&&t.push([G.LocalVideoLowTrack,r])}else t.push(i);return t}createMuteMessage(e){return e.map(t=>{var n;let i,[r,{track:o,ssrcs:s,id:a}]=t;switch(r){case G.LocalAudioTrack:i=nt.Audio;break;case G.LocalVideoTrack:i=x(n=o._hints).call(n,$e.SCREEN_TRACK)?nt.Screen:nt.High;break;case G.LocalVideoLowTrack:i=nt.Low}return{stream_type:i,ssrcs:s,mid:a}})}createUnmuteMessage(e){return e.map(t=>{var n;let i,[r,{track:o,ssrcs:s,id:a}]=t;switch(r){case G.LocalAudioTrack:i=nt.Audio;break;case G.LocalVideoTrack:i=x(n=o._hints).call(n,$e.SCREEN_TRACK)?nt.Screen:nt.High;break;case G.LocalVideoLowTrack:i=nt.Low}return{stream_type:i,ssrcs:s,mid:a}})}filterTobeUnSubscribedTracks(e,t){const n=[],i=this.remoteUserMap.get(e);if(!i)return n;if(t){const r=i.get(t);if(!r)return n;n.push([e,{kind:t,id:r}])}
165else Array.from(i.entries()).forEach(r=>{let[o,s]=r;n.push([e,{kind:o,id:s}])});return n}createUnsubscribeMessage(e){const t=[];return e.forEach(n=>{let[i,{kind:r,id:o}]=n;switch(r){case $.VIDEO:return void(i._videoSSRC&&t.push({stream_type:$.VIDEO,ssrcId:i._videoSSRC}));case $.AUDIO:return void(i._audioSSRC&&t.push({stream_type:$.AUDIO,ssrcId:i._audioSSRC}))}}),t}withdrawRemoteTracks(e){e.forEach(t=>{let[n,{kind:i}]=t;const r=this.remoteUserMap.get(n);r&&(r.delete(i),Array.from(r.entries()).length===0&&this.remoteUserMap.delete(n))})}async updateBitrateLimit(e){const t=this.localTrackMap.get(G.LocalVideoTrack),n=this.localTrackMap.get(G.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new K((i,r)=>{this.handleUpdateVideoEncoder(t.track,i,r,!0)})),n&&e.low_stream_uplink&&(await n.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new K((i,r)=>{this.handleUpdateVideoEncoder(n.track,i,r,!0)}))}isP2PDisconnected(){if(this.sendConnection&&this.recvConnection){const e=this.sendConnection.peerConnectionState,t=this.recvConnection.peerConnectionState;return e!=="connected"&&t!=="connected"}return!0}async tryToUnmuteAudio(e){for(let t=0;t<e.length;t++)if(e[t]instanceof jt){const n=this.filterTobeUnmutedTracks(e[t]);if(n.length===0)continue;const i=this.createUnmuteMessage(n);return void await mt(this,ae.RequestUnmuteLocal,i)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=e=>this.getStats(e),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter(e=>{let[,{ssrcs:t}]=e;return!!t}),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!((t=this.recvConnection)===null||t===void 0||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(ae.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(ae.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await ln(Ip(this.dtlsFailedCount,Bt)),this.emit(ae.RequestReconnect)}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(G.LocalVideoTrack)||this.pendingLocalTracks.some(e=>e instanceof pt)}throwIfTrackTypeNotMatch(e){if(e.filter(t=>t instanceof pt).length>1)throw new L(A.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter(t=>t instanceof jt).length>1&&(e.some(t=>t instanceof jt&&t._bypassWebAudio)||!Oe().webAudioMediaStreamDest))throw new L(A.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof pt&&this.pendingLocalTracks.some(n=>n instanceof pt))throw new L(A.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof jt&&this.pendingLocalTracks.some(n=>n instanceof jt)&&(!Oe().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some(n=>n instanceof jt&&n._bypassWebAudio)))throw new L(A.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const n=!T("DISABLE_DUAL_STREAM_USE_ENCODING")&&Oe().supportDualStreamEncoding,i=Dm(Dm({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=n?e._mediaStreamTrack.clone():Nv(e,i);const o=Qe(8,"track-low-"),s=new pt(r,Dm(Dm({},n&&{scaleResolutionDownBy:ov(i,e)}),{},{frameRate:i.framerate,bitrateMax:i.bitrate,bitrateMin:i.bitrate}),void 0,void 0,o);return s.on(xa.TRANSCEIVER_UPDATED,a=>{e._updateRtpTransceiver(a,dd.LOW_STREAM)}),s._hints.push($e.LOW_STREAM),e.addListener(te.NEED_CLOSE,()=>{s.close()}),s}async globalLock(){return this.recvMutex.lock("From P2PChannel2.globalLock")}reportVideoFirstFrameDecoded(e,t,n,i){var r;const o=Array.from(_n(r=this.remoteUserMap).call(r)).find(s=>s._videoSSRC===e);if(o){i||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const s=this.store.keyMetrics,a=s.subscribe.find(c=>c.userId===o.uid&&c.type==="video");Z.firstRemoteVideoDecode(this.store.sessionId,an.FIRST_VIDEO_DECODE,yt.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:n,subscribeElapse:jn.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:s.requestAPEnd||0,apStart:s.requestAPStart||0,joinGwEnd:s.joinGatewayEnd||0,joinGwStart:s.joinGatewayStart||0,pcEnd:s.peerConnectionEnd||0,pcStart:s.peerConnectionStart||0,subscriberEnd:(a==null?void 0:a.subscribeEnd)||0,subscriberStart:(a==null?void 0:a.subscribeStart)||0,videoAddNotify:(a==null?void 0:a.streamAdded)||0,state:i?1:0})}}async remoteMediaSsrcChanged(e,t,n){if(!this.recvConnection)return!1;const i=this.remoteUserMap.get(e);if(!i)return!1;const r=i.get(t);if(!r)return!1;const o=await this.recvConnection.getRemoteSSRC(r);return o!==void 0&&o!==n}isPreSubScribe(e){return!1}
165async publishDataChannel(e){throw new L(A.NOT_SUPPORTED)}async unpublishDataChannel(e){throw new L(A.NOT_SUPPORTED)}async subscribeDataChannel(e,t){throw new L(A.NOT_SUPPORTED)}async unsubscribeDataChannel(e,t){throw new L(A.NOT_SUPPORTED)}hasPendingRemoteDataChannel(e,t){throw new L(A.NOT_SUPPORTED)}setPendingRemoteDataChannel(e,t){throw new L(A.NOT_SUPPORTED)}async preConnect(e){throw new L(A.NOT_SUPPORTED)}getEstablishParams(){throw new L(A.NOT_SUPPORTED)}async reSubscribe(e){throw new L(A.NOT_SUPPORTED)}reportVideoFirstFrameRender(e){}async updateVideoStreamParameter(e,t){throw new L(A.NOT_SUPPORTED)}unbindRtpTransceiver(){this.localTrackMap.size!==0&&Array.from(this.localTrackMap.entries()).forEach(e=>{let[t,{track:n}]=e;t===G.LocalVideoLowTrack?n._updateRtpTransceiver(void 0,dd.LOW_STREAM):n._updateRtpTransceiver(void 0)})}},H(Lt.prototype,"p2pConnect",[$V],Object.getOwnPropertyDescriptor(Lt.prototype,"p2pConnect"),Lt.prototype),H(Lt.prototype,"unpublish",[ex],Object.getOwnPropertyDescriptor(Lt.prototype,"unpublish"),Lt.prototype),H(Lt.prototype,"unpublishLowStream",[tx],Object.getOwnPropertyDescriptor(Lt.prototype,"unpublishLowStream"),Lt.prototype),H(Lt.prototype,"subscribe",[nx],Object.getOwnPropertyDescriptor(Lt.prototype,"subscribe"),Lt.prototype),H(Lt.prototype,"mockSubscribe",[ix],Object.getOwnPropertyDescriptor(Lt.prototype,"mockSubscribe"),Lt.prototype),H(Lt.prototype,"unsubscribe",[rx],Object.getOwnPropertyDescriptor(Lt.prototype,"unsubscribe"),Lt.prototype),H(Lt.prototype,"muteRemote",[ox],Object.getOwnPropertyDescriptor(Lt.prototype,"muteRemote"),Lt.prototype),H(Lt.prototype,"unmuteRemote",[sx],Object.getOwnPropertyDescriptor(Lt.prototype,"unmuteRemote"),Lt.prototype),H(Lt.prototype,"hasRemoteMediaWithLock",[ax],Object.getOwnPropertyDescriptor(Lt.prototype,"hasRemoteMediaWithLock"),Lt.prototype),H(Lt.prototype,"disconnectForReconnect",[cx],Object.getOwnPropertyDescriptor(Lt.prototype,"disconnectForReconnect"),Lt.prototype),H(Lt.prototype,"remoteMediaSsrcChanged",[dx],Object.getOwnPropertyDescriptor(Lt.prototype,"remoteMediaSsrcChanged"),Lt.prototype),Lt);function vo(e){return function(t,n,i){const r=t[n];if(typeof r!="function")throw new Error("Cannot use mutex on object property.");return i.value=async function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];switch(e){case Ro.SEND_ONLY:{const c=await this.sendMutex.lock("From P2PChannel2.".concat(n));try{return await r.apply(this,s)}finally{c()}}case Ro.RECEIVE_ONLY:{const c=await this.recvMutex.lock("From P2PChannel2.".concat(n));try{return await r.apply(this,s)}finally{c()}}default:{const c=await this.sendMutex.lock("From P2PChannel2.".concat(n)),d=await this.recvMutex.lock("From P2PChannel2.".concat(n));try{return await r.apply(this,s)}finally{c(),d()}}}},i}}class pc extends Nt{constructor(t,n){super(),S(this,"signal",void 0),S(this,"token",void 0),S(this,"tokenTimeout",void 0),S(this,"tokenInterval",void 0),S(this,"_sequence",0),S(this,"userMap",new Map),S(this,"encoder",new TextEncoder),this.signal=t,this.token=n;const i=()=>{this.signal.connectionState===Le.CONNECTED&&this.check(),this.userMap.size===0?this.tokenInterval=window.setTimeout(i,1e3):this.tokenInterval=window.setTimeout(i,3*T("P2P_TOKEN_INTERVAL"))};i()}async send(t,n,i,r,o){var s,a,c;if(this.userMap.size===0)return;const d=Array.from(ti(s=this.userMap).call(s))[0].token;typeof n!="string"&&(n=JSON.stringify(n)),r=(a=r)!==null&&a!==void 0?a:Qe(6,""),o=(c=o)!==null&&c!==void 0?c:this._sequence++;const l={_id:r,_type:t,_seq:o,_message:n,token:"".concat(this.token,"_").concat(d)};T("SHOW_P2P_LOG")&&_.debug("send message",l,"noNeedResponse : ".concat(i)),this.splitMessage(JSON.stringify(l)).forEach(u=>{this.signal.request(ie.DATA_STREAM,{payload:Us(this.encoder.encode(u))})});const h=new K((u,p)=>{const E=window.setTimeout(()=>{this.off("res-@".concat(r,"_ack"),m),this.off("res-@".concat(r),R),this.off(Rd.ABORT,g),_.debug("[external-signal] request timeout, type: ".concat(t,", requestId: ").concat(r)),this.userMap.size===0?p(new L(A.INVALID_REMOTE_USER)):p(new L(A.TIMEOUT))},T("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),m=()=>{E&&window.clearTimeout(E),this.off(Rd.ABORT,g),i&&u()},g=()=>{E&&window.clearTimeout(E),this.off("res-@".concat(r,"_ack"),m),this.off("res-@".concat(r),R),p(new L(A.EXTERNAL_SIGNAL_ABORT,"type: ".concat(t,", requestId: ").concat(r)))};this.once(Rd.ABORT,g),this.once("res-@".concat(r,"_ack"),m);const R=(C,w)=>{v=!0,E&&window.clearTimeout(E),this.off("res-@".concat(r,"_ack"),m),this.off(Rd.ABORT,g),C==="success"?u(w):p(new L(A.P2P_MESSAGE_FAILED,"request ".concat(t," failed, requestId: ").concat(r)))};let v=!1;i||(this.once("res-@".concat(r),R),ln(T("SIGNAL_REQUEST_TIMEOUT")).then(()=>{v||_.warning("external_signal request timeout, type: ".concat(t,", requestId: ").concat(r,", ").concat(l))}))});try{return await h}catch(u){if(u.code===A.TIMEOUT)return await this.send(t,n,i,r,o);throw u}}onMessage(t){var n;const{_uid:i}=t;let r,o=this.userMap.get(i);if(o)r=o.splitMessageMap;else{if(this.userMap.size>0||!("_type"in t)||t._type!==Zt.CHECK)return;const{token:d}=t;r=new Map,o={uid:i,isStart:!0,token:d,splitMessageMap:r,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map},this.userMap.set(i,o),this.signal.emit(he.ON_USER_ONLINE,{uid:i}),this.handleUserOnline()}if("id"in t&&"total"in t){var s;const{id:d,total:l}=t,h=(s=r.get(d))!==null&&s!==void 0?s:[];if(h.push(t),r.has(d)||r.set(d,h),h.length!==l)return;{const u=Pi(h).call(h,(p,E)=>p.index-E.index).map(p=>p.payload).join("");r.delete(d),(t=JSON.parse(u))._uid=i}}const{_type:a,token:c}=t;
165if(x(n=[Zt.ACK,Zt.CHECK]).call(n,a))return a===Zt.CHECK&&this.handleCheckToken(o,c),void this.receiveMessage(t);c==="".concat(o.token,"_").concat(this.token)?this.handleReceivedMessage(t):_.debug('Receive unexpected message", '.concat(c,", cur_token: ").concat(o.token,"_").concat(this.token),t)}check(){const t={_id:Qe(6,""),token:this.token,_type:Zt.CHECK};T("SHOW_P2P_LOG")&&_.debug("send message",t),this.signal.request(ie.DATA_STREAM,{payload:Us(this.encoder.encode(JSON.stringify(t)))})}ack(t){const n={_id:t,_type:Zt.ACK,token:this.token};T("SHOW_P2P_LOG")&&_.debug("send message",n),this.signal.request(ie.DATA_STREAM,{payload:Us(this.encoder.encode(JSON.stringify(n)))})}response(t,n,i){this.send(Zt.RESPONSE,JSON.stringify({success:!i,message:n}),!0,t)}handleReceivedMessage(t){const n=()=>{this.userMap.forEach(d=>{const{receivedMessagesMap:l,nextExpectedSequenceNumber:h}=d;for(;l.has(h);){const u=l.get(h);l.delete(h),this.receiveMessage(u),d.nextExpectedSequenceNumber++}})};if(!t)return void n();const{_uid:i,_seq:r}=t,o=this.userMap.get(i),{receivedMessagesMap:s,isStart:a,nextExpectedSequenceNumber:c}=o;if(r<c)return this.ack(t._id),void _.debug("[external-signal] receive old message, seq: ".concat(r,", ").concat(t._message));s.set(r,t),a&&r===c&&(this.receiveMessage(t),s.delete(c),o.nextExpectedSequenceNumber++,n())}receiveMessage(t){const{_id:n,_type:i,_message:r,_uid:o}=t;if(T("SHOW_P2P_LOG")&&_.debug("receive message",t),n){let s;switch(t._type!==Zt.ACK&&(r&&(s=JSON.parse(r)),this.ack(t._id)),t._type){case Zt.CANDIDATE:case Zt.CONTROL:this.signal.emit(i,s,o);break;case Zt.PUBLISH:case Zt.UNPUBLISH:case Zt.RESTART_ICE:case Zt.CALL:s.uid=o,Jt(this.signal,i,s).then(a=>{this.response(t._id,a)}).catch(()=>{this.response(t._id,void 0,!0)});break;case Zt.ACK:this.getListeners("res-@".concat(n,"_ack")).length>0&&this.emit("res-@".concat(n,"_ack"));break;case Zt.RESPONSE:{const{success:a,message:c}=s;this.emit("res-@".concat(n),a?"success":"failed",c);break}}}}splitMessage(t){if(t.length<pc.MAX_MESSAGE_SIZE)return[t];const n=[],{remoteToken:i}=JSON.parse(t),r=Qe(6,"");let o=0,s=800;const a=Math.ceil(t.length/s);for(;t.length>0;){o++;const c={id:r,index:o,total:a,payload:t.slice(0,s),token:"".concat(this.token,"_").concat(i)};JSON.stringify(c).length>pc.MAX_MESSAGE_SIZE?s-=50:(n.push(c),t=t.slice(s))}return n.map(c=>JSON.stringify(c))}handleCheckToken(t,n){return t.token!==n?(_.debug("token changed, from ".concat(t.token," to ").concat(n)),this.reset(t.uid,n),!1):(this.tokenTimeout&&(window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0),this.tokenTimeout=window.setTimeout(()=>{_.debug("token timeout, ".concat(n)),this.reset(t.uid)},T("MAX_P2P_TIMEOUT")),!0)}async handleUserOnline(){const t=await Jt(this.signal,Zt.CALL,void 0),n=await this.send(Zt.CALL,t);this.signal.emit(ee.P2P_CONNECTION,n,!0)}async reset(t,n){const i=this.userMap.get(t);i&&(this.emit(Rd.ABORT),this.signal.emit(he.ON_USER_OFFLINE,{uid:i.uid,reason:iJ.P2P_TOKEN_CHANGED}),this._sequence=0,this.userMap.clear(),n||(_.debug("change local token from ".concat(n," to ").concat(n)),this.token=Qe(6,"")))}clear(){this._sequence=0,this.userMap.clear(),this.tokenInterval&&window.clearTimeout(this.tokenInterval),this.tokenInterval=void 0,this.tokenTimeout&&window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0,this.emit(Rd.ABORT)}}S(pc,"MAX_SIZE",1),S(pc,"MAX_MESSAGE_SIZE",1024);class Pte extends Nt{get connectionState(){return this._connectionState}set connectionState(t){t!==this._connectionState&&(this._connectionState=t,t===Le.CONNECTED?this.emit(ee.WS_CONNECTED):t===Le.RECONNECTING?this.emit(ee.WS_RECONNECTING,this._websocketReconnectReason):t===Le.CLOSED&&this.emit(ee.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(t,n){super(),S(this,"__name__","P2PSignal"),S(this,"_disconnectedReason",void 0),S(this,"_websocketReconnectReason",void 0),S(this,"_connectionState",Le.CLOSED),S(this,"reconnectToken",void 0),S(this,"p2pToken",void 0),S(this,"websocket",void 0),S(this,"openConnectionTime",void 0),S(this,"clientId",void 0),S(this,"lastMsgTime",Date.now()),S(this,"uploadCache",[]),S(this,"uploadCacheInterval",void 0),S(this,"rttRolling",new aS(5)),S(this,"pingpongTimer",void 0),S(this,"pingpongTimeoutCount",0),S(this,"joinResponse",void 0),S(this,"multiIpOption",void 0),S(this,"initError",void 0),S(this,"spec",void 0),S(this,"store",void 0),S(this,"_external_signal",void 0),S(this,"onWebsocketMessage",i=>
165{if(i.data instanceof ArrayBuffer)return void this.emit(ee.ON_BINARY_DATA,i.data);const r=JSON.parse(i.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(r,"_id")){const o="res-@".concat(r._id);this.emit(o,r._result,r._message)}else if(Object.prototype.hasOwnProperty.call(r,"_type")){switch(r._type){case he.ON_DATA_STREAM:return void this.handleDataStream(r._message);case he.MUTE_AUDIO:case he.MUTE_VIDEO:case he.ON_P2P_LOST:case he.ON_USER_ONLINE:return;case he.ON_USER_OFFLINE:const{uid:o}=r._message;return _.debug("[".concat(this.clientId,"] user-offline uid: ").concat(o)),void this._external_signal.reset(o)}if(this.emit(r._type,r._message),r._type===he.ON_NOTIFICATION&&this.handleNotification(r._message),r._type===he.ON_USER_BANNED)switch(r._message.error_code){case 14:this.close(Pe.UID_BANNED);break;case 15:this.close(Pe.IP_BANNED);break;case 16:this.close(Pe.CHANNEL_BANNED)}if(r._type===he.ON_USER_LICENSE_BANNED)switch(r._message.error_code){case ce.ERR_LICENSE_MISSING:this.close(Pe.LICENSE_MISSING);break;case ce.ERR_LICENSE_EXPIRED:this.close(Pe.LICENSE_EXPIRED);break;case ce.ERR_LICENSE_MINUTES_EXCEEDED:this.close(Pe.LICENSE_MINUTES_EXCEEDED);break;case ce.ERR_LICENSE_PERIOD_INVALID:this.close(Pe.LICENSE_PERIOD_INVALID);break;case ce.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(Pe.LICENSE_MULTIPLE_SDK_SERVICE);break;case ce.ERR_LICENSE_ILLEGAL:this.close(Pe.LICENSE_ILLEGAL);break;default:this.close()}}}),this.clientId=t.clientId,this.spec=t,this.store=n,this.websocket=new oT("gateway-".concat(this.clientId),this.spec.retryConfig,!0,T("JOIN_GATEWAY_USE_DUAL_DOMAIN"),T("JOIN_GATEWAY_USE_443PORT_ONLY"),n),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===Le.CONNECTED&&this.reconnect("retry",Vn.OFFLINE)}),this.p2pToken=Qe(6,""),this._external_signal=new pc(this,this.p2pToken)}async request(t,n,i,r){const o=Qe(6,""),s={_id:o,_type:t,_message:n},a=this.websocket.connectionID,c=()=>new K((E,m)=>{if(this.connectionState===Le.CONNECTED)return E();const g=()=>{this.off(ee.WS_CLOSED,R),E()},R=()=>{this.off(ee.WS_CONNECTED,g),m(new L(A.WS_ABORT))};this.once(ee.WS_CONNECTED,g),this.once(ee.WS_CLOSED,R)});if(this.connectionState!==Le.CONNECTING&&this.connectionState!==Le.RECONNECTING||t===ie.JOIN||t===ie.REJOIN||await c(),this.websocket.sendMessage(s,!0),r)return;const d=new K((E,m)=>{let g=!1;const R=(C,w)=>{g=!0,E({isSuccess:C==="success",message:w||{}}),this.off(ee.WS_CLOSED,v),this.off(ee.WS_RECONNECTING,v),this.emit(ee.REQUEST_SUCCESS,t,n)};this.once("res-@".concat(o),R);const v=()=>{m(new L(A.WS_ABORT,"type: ".concat(t))),this.off(ee.WS_CLOSED,v),this.off(ee.WS_RECONNECTING,v),this.off("res-@".concat(o),R)};this.once(ee.WS_CLOSED,v),this.once(ee.WS_RECONNECTING,v),ln(T("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==a||g||(_.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(t)),this.emit(ee.REQUEST_TIMEOUT,t,n))})});let l=null;try{l=await d}catch(E){if(this.connectionState===Le.CLOSED||t===ie.LEAVE)throw new L(A.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?E.throw():t===ie.JOIN||t===ie.REJOIN?null:(await c(),await this.request(t,n))}if(l.isSuccess)return l.message;const h=Number(l.message.error_code||l.message.code),u=Ha(h),p=new L(A.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(l.message.error_str),{code:h,data:l.message,desc:u.desc});return u.action==="success"?l.message:(_.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(t,", error_code: ").concat(h,", message: ").concat(u.desc,", action: ").concat(u.action)),h===ce.ERR_TOO_MANY_BROADCASTERS?((t===ie.JOIN||t===ie.REJOIN)&&(this.initError=p,this.close()),p.throw()):u.action==="failed"?p.throw():u.action==="quit"?(this.initError=p,this.close(),p.throw()):(h===ce.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=l.message.option,_.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Vn.MULTI_IP)):this.reconnect(u.action,Vn.SERVER_ERROR),t===ie.JOIN||t===ie.REJOIN?null:await this.request(t,n)))}waitMessage(t,n){return new K(i=>
165{const r=o=>{(!n||n(o))&&(this.off(t,r),i(o))};this.on(t,r)})}uploadWRTCStats(t){if(!this.store.sessionId)return void _.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const n={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:t};this.upload(Ka.WRTC_STATS,n)}upload(t,n){const i={_type:t,_message:n};try{this.websocket.sendMessage(i)}catch{const r=T("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>r&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==Le.CONNECTED)return;const o=this.uploadCache.splice(0,1)[0];this.uploadCache.length===0&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(o._type,o._message)},T("UPLOAD_CACHE_INTERVAL")||2e3))}}send(t,n){const i={_type:t,_message:n};this.websocket.sendMessage(i)}async sendExtensionMessage(t,n,i){return await this._external_signal.send(t,n,i)}init(t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new K((n,i)=>{this.once(ee.WS_CONNECTED,()=>n(this.joinResponse)),this.once(ee.WS_CLOSED,()=>i(this.initError||new L(A.WS_ABORT))),this.connectionState=Le.CONNECTING,this.websocket.init(t).catch(i)})}close(t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._external_signal.clear(),this._disconnectedReason=t||Pe.LEAVE,this.connectionState=Le.CLOSED,_.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),this.p2pToken=Qe(6,""),this._external_signal.clear(),this._external_signal=new pc(this,this.p2pToken)}async join(){if(!this.joinResponse){this.emit(ee.ABORT_P2P_EXECUTION);const t=await Jt(this,ee.REQUEST_JOIN_INFO),n=await this.request(ie.JOIN,t);if(!n)return this.emit(ee.REPORT_JOIN_GATEWAY,A.TIMEOUT,this.url||""),!1;this.joinResponse=n,this.emit(ee.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Le.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}reconnect(t,n){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(t,n)}async downgradeCodec(t){return!1}handleDataStream(t){try{var n;const i=Pa(t.payload),r=new TextDecoder().decode(i),o=JSON.parse(r);"total"in o&&"id"in o||x(n=Object.values(Zt)).call(n,o._type)?(o._uid=t.uid,this._external_signal.onMessage(o)):this.emit(he.ON_DATA_STREAM,t)}catch{this.emit(he.ON_DATA_STREAM,t)}}handleNotification(t){_.debug("[".concat(this.clientId,"] receive notification: "),t);const n=Ha(t.code);if(n.action!=="success"){if(n.action!=="failed")return n.action==="quit"?t.code===ce.ERR_REPEAT_JOIN_CHANNEL&&T("IGNORE_UID_CHECK")?void this.close(Pe.UID_CONFLICT):(n.desc==="ERR_REPEAT_JOIN_CHANNEL"&&this.close(Pe.UID_BANNED),void this.close()):void this.reconnect(n.action,Vn.SERVER_ERROR);_.error("[".concat(this.clientId,"] ignore error: "),n.desc)}}handlePingPong(){if(!this.websocket||this.websocket.state!=="connected")return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const t=T("PING_PONG_TIME_OUT"),n=Date.now();this.pingpongTimeoutCount>=t&&(_.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(n-this.lastMsgTime,"ms")),n-this.lastMsgTime>T("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",Vn.TIMEOUT):this.request(ie.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const i=Date.now()-n;this.rttRolling.add(i),T("REPORT_STATS")&&this.send(ie.PING_BACK,{pingpongElapse:i})}).catch(i=>{})}handleWebsocketEvents(){this.websocket.on(Re.RECONNECT_CREATE_CONNECTION,t=>{this.emit(ee.WS_RECONNECT_CREATE_CONNECTION,t)}),this.websocket.on(Re.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(Re.CLOSED,()=>{this.connectionState=Le.CLOSED}),this.websocket.on(Re.FAILED,()=>
165{this._disconnectedReason=Pe.NETWORK_ERROR,this.connectionState=Le.CLOSED}),this.websocket.on(Re.RECONNECTING,t=>{this._websocketReconnectReason=t,this.joinResponse=void 0,this.connectionState===Le.CONNECTED?this.connectionState=Le.RECONNECTING:this.connectionState=Le.CONNECTING}),this.websocket.on(Re.WILL_RECONNECT,(t,n,i)=>{t!=="retry"?(_.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(t)),this.reconnectToken=void 0):_.debug("".concat(this.clientId," reconnect mode is retry, no need to renew session")),i(t)}),this.websocket.on(Re.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.join().catch(t=>{if(this.emit(ee.REPORT_JOIN_GATEWAY,t,this.url||""),t instanceof L&&t.code===A.UNEXPECTED_RESPONSE&&t.data.code===ce.ERR_NO_AUTHORIZED)return _.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",Vn.SERVER_ERROR);_.error("[".concat(this.clientId,"] join gateway request failed"),t.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Vn.SERVER_ERROR):(this.initError=t,this.close())})}),this.websocket.on(Re.REQUEST_NEW_URLS,(t,n)=>{Jt(this,ee.REQUEST_RECOVER,this.multiIpOption).then(t).catch(n)}),this.websocket.on(Re.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(he.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})}}const Lte={name:"P2PChannel",create:function(e){let{store:t,statsCollector:n}=e;return new Dte(t,n)},createSubmodule:function(e){let{store:t,spec:n}=e;return new Pte(n,t)}};function ux(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function hx(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?ux(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ux(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}class kte{constructor(t){S(this,"sessionDesc",void 0),S(this,"localCapabilities",void 0),S(this,"rtpCapabilities",void 0),S(this,"candidates",void 0),S(this,"_originCandidates",void 0),S(this,"iceParameters",void 0),S(this,"dtlsParameters",void 0),S(this,"setup",void 0),S(this,"currentMidIndex",void 0),S(this,"cname",void 0),t=Ct(t);const{iceParameters:n,dtlsParameters:i,candidates:r,rtpCapabilities:o,setup:s,localCapabilities:a,sdkCodec:c,cname:d}=t,l=ii(`v=0 166o=- 0 0 IN IP4 127.0.0.1 167s=AgoraGateway 168t=0 0 169a=group:BUNDLE audio video 170a=msid-semantic: WMS 171a=ice-lite 172m=audio 9 UDP/TLS/RTP/SAVPF 0 173c=IN IP4 127.0.0.1 174a=rtcp:9 IN IP4 0.0.0.0 175a=sendrecv 176a=rtcp-mux 177a=rtcp-rsize 178a=mid:audio 179m=video 9 UDP/TLS/RTP/SAVPF 0 180c=IN IP4 127.0.0.1 181a=rtcp:9 IN IP4 0.0.0.0 182a=sendrecv 183a=rtcp-mux 184a=rtcp-rsize 185a=mid:video 186`);this.rtpCapabilities=o,this.candidates=r,this._originCandidates=Ct(r),this.iceParameters=n,this.dtlsParameters=i,this.setup=s,this.localCapabilities=a,this.cname=d;for(let h=0;h<l.mediaDescriptions.length;h++){const u=l.mediaDescriptions[h];if(u.attributes.iceUfrag=n.iceUfrag,u.attributes.icePwd=n.icePwd,u.attributes.fingerprints=i.fingerprints,u.attributes.candidates=r,u.attributes.setup=s,u.media.mediaType==="video"){u.media.fmts=o.videoCodecs.map(m=>m.payloadType.toString(10));const p=o.videoCodecs.filter(m=>{var g,R;return(g=m.rtpMap)===null||g===void 0?void 0:x(R=g.encodingName.toLowerCase()).call(R,c)}),E=o.videoCodecs.filter(m=>!x(p).call(p,m));u.attributes.payloads=[...p,...E],u.attributes.extmaps=o.videoExtensions}u.media.mediaType==="audio"&&(u.media.fmts=o.audioCodecs.map(p=>p.payloadType.toString(10)),u.attributes.payloads=o.audioCodecs,u.attributes.extmaps=o.audioExtensions),l.mediaDescriptions[h]=this.mungMediaDesc(u)}this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return as(this.sessionDesc)}send(t,n,i){const{ssrcs:r,ssrcGroups:o}=Mu(n,this.cname),s=this.sessionDesc.mediaDescriptions.find(d=>t===$.VIDEO?d.media.mediaType==="video":d.media.mediaType==="audio"),a=r[0].attributes.label,c=r[0].attributes.mslabel;return s.attributes.ssrcs=s.attributes.ssrcs.concat(r),s.attributes.ssrcGroups=s.attributes.ssrcGroups.concat(o),{id:a,mslabel:c}}batchSend(t){return t.map(n=>{let{kind:i,ssrcMsg:r}=n;return this.send(i,r,void 0)})}stopSending(t){this.sessionDesc.mediaDescriptions.forEach(n=>{const i=[],r=[],o=[];n.attributes.ssrcs.forEach(s=>{x(t).call(t,s.attributes.label||"")?o.push(s):i.push(s)}),n.attributes.ssrcGroups.forEach(s=>{var a;x(a=o.map(c=>c.ssrcId)).call(a,s.ssrcIds[0])||r.push(s)}),n.attributes.ssrcs=i,n.attributes.ssrcGroups=r})}mute(t){const n=this.sessionDesc.mediaDescriptions.find(i=>i.attributes.mid===t);if(!n)throw new Error("mediaDescription not found with ".concat(t," in remote SDP when calling RemoteSDP.mute."));n.attributes.direction="inactive"}unmute(t){const n=this.sessionDesc.mediaDescriptions.find(i=>i.attributes.mid===t);if(!n)throw new Error("mediaDescription not found with ".concat(t," in remote SDP when calling RemoteSDP.unmute."));n.attributes.direction="sendonly"}receive(t,n,i){t.forEach((r,o)=>{const s=r._mediaStreamTrack,a=this.sessionDesc.mediaDescriptions.findIndex(d=>d.attributes.mid===s.kind),c=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[a],r);this.sessionDesc.mediaDescriptions[a]=c})}stopReceiving(t){}updateCandidates(t){const n=this._originCandidates.filter(r=>r.transport==="udp"),i=[];if(n.forEach(r=>{i.push(hx(hx({},r),{},{foundation:"tcpcandidate",priority:Number(r.priority)-1+"",transport:"tcp",port:Number(r.port)+90+""}))}),n.length!==0){switch(t){case gn.TCP_RELAY:this.candidates=i;break;
186case gn.UDP_TCP_RELAY:case gn.RELAY:this.candidates=[...n,...i];break;default:this.candidates=n}for(const r of this.sessionDesc.mediaDescriptions)r.attributes.candidates=this.candidates}}restartICE(t){t=Ct(t),this.iceParameters=t,this.sessionDesc.mediaDescriptions.forEach(n=>{n.attributes.iceUfrag=t.iceUfrag,n.attributes.icePwd=t.icePwd})}predictReceivingMids(t){const n=[];for(let i=0;i<t;i++)n.push((this.currentMidIndex+i+1).toString(10));return n}mungRecvMediaDsec(t,n){const i=Ct(t);return rc(i,n),cv(i,n),i}updateRecvMedia(t,n){const i=this.sessionDesc.mediaDescriptions.findIndex(r=>r.attributes.mid===t);if(i!==-1){const r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],n);this.sessionDesc.mediaDescriptions[i]=r}}bumpMid(t){this.currentMidIndex+=t}updateTrackLabel(t,n,i){const r=this.sessionDesc.mediaDescriptions.find(s=>t===$.VIDEO?s.attributes.mid==="video":s.attributes.mid==="audio");if(r){const s=r.attributes.ssrcs.find(a=>a.attributes.label===n);var o;s&&(s.attributes.label=i,(o=s.attributes.msid)===null||o===void 0||o.replace(n,i))}}mungMediaDesc(t){const n=Ct(t);return av(n),function(i){const r=i.attributes.extmaps.find(o=>cm(o.extensionName));r&&i.attributes.extmaps.splice(i.attributes.extmaps.indexOf(r),1),i.attributes.payloads.forEach(o=>{const s=o.rtcpFeedbacks.findIndex(a=>a.type==="transport-cc");s!==-1&&o.rtcpFeedbacks.splice(s,1)})}(n),n}getSSRC(t){for(const n of this.sessionDesc.mediaDescriptions)for(const i of n.attributes.ssrcs)if(i.attributes.label===t)return[i]}}var Et;function px(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Pm(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?px(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):px(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}let Mte=(Et=class zu extends o_{get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.videoCodecs.map(t=>t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").filter(t=>{var n;return x(n=Object.keys(Ma)).call(n,t)}))]}constructor(t,n){super(t,n),S(this,"store",void 0),S(this,"peerConnection",void 0),S(this,"remoteSDP",void 0),S(this,"initialOffer",void 0),S(this,"statsFilter",void 0),S(this,"useRTX",!1),S(this,"localCapabilities",void 0),S(this,"localCandidateCount",0),S(this,"allCandidatesReceived",!1),S(this,"establishPromise",void 0),S(this,"mutex",void 0),this.store=n,this.mutex=new An("P2PConnection-mutex",n.clientId),this.peerConnection=new RTCPeerConnection(zu.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=Np(this.peerConnection,T("STATS_UPDATE_INTERVAL"),void 0,Rt()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(){try{const t=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!t.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const n=Ho(t.sdp),i=ku(t.sdp,{filterRTX:!this.useRTX,filterVideoFec:T("FILTER_VIDEO_FEC"),filterAudioFec:T("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=i,this.initialOffer=t,Pm(Pm({},n),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:i},offerSDP:t.sdp})}catch(t){throw new L(A.GET_LOCAL_CONNECTION_PARAMS_FAILED,t.toString())}}async updateRemoteConnect(){}async connect(t){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new kte(Pm(Pm({},t),{},{rtpCapabilities:t.rtpCapabilities.send,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec}));const n=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(n.toString()))}}async updateRemoteRTPCapabilities(t,n){throw new L(A.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}getPreMedia(t){}send(t,n){var i=this;return di(function*(){const r=yield ve(i.mutex.lock());try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=t.map(u=>i.peerConnection.addTrack(u._mediaStreamTrack)),s=yield ve(i.peerConnection.createOffer()),a=ii(s.sdp),c=t.map(u=>{const p=u._mediaStreamTrack,E=a.mediaDescriptions.find(m=>m.attributes.mid===p.kind);if(!E)throw new Error("Cannot extract ssrc from mediaDescription.");return function(m,g,R){const v=m.attributes.ssrcs.filter(w=>w.attributes.label===g),C=m.attributes.ssrcGroups;if(v.length===0)throw new Error("Cannot extract ssrc from plan-b SDP.");if(C&&v.length>1){const w=C.find(b=>b.ssrcIds.indexOf(v[0].ssrcId)!==-1);return w?[{ssrcId:w.ssrcIds[0],rtx:R?w.ssrcIds[1]:void 0}]:[{ssrcId:v[0].ssrcId}]}return[{ssrcId:v[0].ssrcId}]}(E,p.id,i.useRTX)});let d;try{d=yield c}catch(u){throw o.forEach(p=>{vn()&&p.replaceTrack(null),i.peerConnection.removeTrack(p)}),u}const l=i.mungSendOfferSDP(s.sdp,t);
186i.remoteSDP.receive(t,n,d);const h=i.remoteSDP.toString();return yield ve(i.peerConnection.setLocalDescription({type:"offer",sdp:l})),yield ve(i.applySendEncodings(o,t)),yield ve(i.peerConnection.setRemoteDescription({type:"answer",sdp:h})),t.map((u,p)=>{const E=u._mediaStreamTrack.id;return{localSSRC:c[p],id:E}})}catch(o){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(o.toString()))}finally{r()}})()}async stopSending(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const n=this.peerConnection.getSenders().filter(o=>{var s;return t.indexOf(((s=o.track)===null||s===void 0?void 0:s.id)||"")!==-1});if(n.length!==t.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");n.map(o=>{vn()&&o.replaceTrack(null),this.peerConnection.removeTrack(o)});const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(t);const r=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(n.toString()))}}async receive(t,n,i,r){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(t," before remoteSDP created."));const{id:o,mslabel:s}=this.remoteSDP.send(t,n,r),a=new K((l,h)=>{const u=setTimeout(()=>{h(new Error("Cannot receive track, id: ".concat(o)))},1e4),p=E=>{const m=Fe();if((m.name==="Safari"&&Number(m.version)===11||Hn())&&E.track.id!==o&&E.streams[0].id===s){var g;const R=E.streams[0].getTracks()[0];return(g=this.remoteSDP)===null||g===void 0||g.updateTrackLabel(t,o,E.track.id),this.peerConnection.removeEventListener("track",p),clearTimeout(u),void l(R)}if(E.track.id===o)return this.peerConnection.removeEventListener("track",p),clearTimeout(u),void l(E.track)};this.peerConnection.addEventListener("track",p)}),c=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:c});const d=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(d),{track:await a,id:o}}catch(o){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(o.toString()))}}async stopReceiving(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(t);const n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const i=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(i)}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(n.toString()))}}async muteRemote(t){}async unmuteRemote(t){}async muteLocal(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const n=this.peerConnection.getSenders().filter(i=>{var r;return t.indexOf(((r=i.track)===null||r===void 0?void 0:r.id)||"")!==-1});if(n.length!==t.length)throw new Error("sender' length doesn't match mids' length.");n.map(i=>{if(vn()&&i.track)i.track.enabled=!1;else{const r=i.getParameters();
186r.encodings.forEach(o=>o.active=!1),i.setParameters(r)}})}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(n.toString()))}}async unmuteLocal(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const n=this.peerConnection.getSenders().filter(o=>{var s;return t.indexOf(((s=o.track)===null||s===void 0?void 0:s.id)||"")!==-1});if(n.length!==t.length)throw new Error("Senders' length doesn't match mids' length.");n.map(async o=>{if(vn()&&o.track)o.track.enabled=!0;else{const s=o.getParameters();s.encodings.forEach(a=>a.active=!0),await o.setParameters(s)}});const i=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(i);const r=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(n.toString()))}}restartICE(t){var n=this;return di(function*(){const i=yield ve(n.mutex.lock("From P2PConnection.restartICE"));try{if(!n.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const r=Oe().supportPCSetConfiguration;if(t===gn.RELAY&&!r)return;if(r){const d=n.peerConnection.getConfiguration(),l=t===gn.RELAY?"relay":"all";d.iceTransportPolicy!==l&&(_.debug("[".concat(n.store.clientId,"] restartICE change iceTransportPolicy from [").concat(d.iceTransportPolicy,"] to [").concat(l,"]")),d.iceTransportPolicy=l,n.peerConnection.setConfiguration(d))}t!==gn.RELAY&&n.remoteSDP.updateCandidates(t);const o=yield ve(n.peerConnection.createOffer({iceRestart:!0}));if(!o.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const s=Ho(o.sdp),{remoteIceParameters:a}=yield s.iceParameters;n.remoteSDP.restartICE(a);const c=n.remoteSDP.toString();yield ve(n.peerConnection.setLocalDescription(o)),yield ve(n.peerConnection.setRemoteDescription({type:"answer",sdp:c}))}catch(r){_.warning("[".concat(n.store.clientId,"] restart ICE failed, abort operation"),r)}finally{i()}})()}close(){var t;this.peerConnection.close(),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(t){return this.statsFilter.getVideoIsReady(t)}async updateEncoderConfig(t,n){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),r=this.mungSendOfferSDP(i.sdp,[n]);this.remoteSDP.updateRecvMedia(n._mediaStreamTrack.kind,n);const o=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:r}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(i){throw new L(A.EXCHANGE_SDP_FAILED,i.toString())}}async updateSendParameters(t,n){const i=this.peerConnection.getSenders().filter(r=>{var o;return((o=r.track)===null||o===void 0?void 0:o.id)===t});i.length===1&&await this.applySendEncodings(i,[n])}setStatsRemoteVideoIsReady(t,n){this.statsFilter.setVideoIsReady2(t,n)}async replaceTrack(t,n){const i=this.peerConnection.getSenders().find(r=>{var o;return((o=r.track)===null||o===void 0?void 0:o.id)===n});i&&await i.replaceTrack(t._mediaStreamTrack)}createDataChannels(t,n){throw new L(A.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(t){throw new L(A.NOT_SUPPORTED,"Planb mode does not support stopDataChannels.")}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var t;(t=this.onICEConnectionStateChange)===null||t===void 0||t.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=t=>{t.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,_.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,_.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},T("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const n={iceServers:[],sdpSemantics:"plan-b"};return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&t.turnServer.mode!=="off"&&(wa(t.turnServer.servers)?n.iceServers=t.turnServer.servers:(n.iceServers&&n.iceServers.push(...zu.turnServerConfigToIceServers(t.turnServer.servers)),T("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...zu.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEac
186h(i=>{i.forceturn&&(n.iceTransportPolicy="relay")}))),n}static turnServerConfigToIceServers(t){const n=[];return t.forEach(i=>{i.security?i.tcpport&&n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turns:".concat(i.turnServerURL,":").concat(i.tcpport,"?transport=tcp")}):(i.udpport&&n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":").concat(i.udpport,"?transport=udp")}),i.tcpport&&n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":").concat(i.tcpport,"?transport=tcp")}))}),n}async updateRtpSenderEncodings(t,n){var i;if(n||(n=this.peerConnection.getSenders().find(d=>{var l;return((l=d.track)===null||l===void 0?void 0:l.id)===t._mediaStreamTrack.id})),!n)return _.warn("[".concat(t.getTrackId(),"] no rtpSender found}"));if(!Oe().supportSetRtpSenderParameters)return _.warn("Browser not support set rtp-sender parameters");const r={},o={};if(t instanceof pt)switch(t._optimizationMode){case"motion":r.degradationPreference="maintain-framerate";break;case"detail":r.degradationPreference="maintain-resolution";break;default:r.degradationPreference="balanced"}if(T("DSCP_TYPE")&&Po()){var s;const d=T("DSCP_TYPE");x(s=["very-low","low","medium","high"]).call(s,d)&&(o.networkPriority=d)}const a=n.getParameters(),c=(i=a.encodings)===null||i===void 0?void 0:i[0];c&&Object.assign(c,o),Object.assign(a,r),_.debug("[".concat(t.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await n.setParameters(a)}async applySendEncodings(t,n){try{if(!Oe().supportSetRtpSenderParameters||t.length!==n.length)return;for(let i=0;i<t.length;i++){const r=t[i],o=n[i];r&&o&&await this.updateRtpSenderEncodings(o,r)}}catch{_.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(t,n){const i=ii(t);return n.forEach((r,o)=>{const s=r._mediaStreamTrack,a=i.mediaDescriptions.find(c=>c.attributes.mid===s.kind);a&&rc(a,r)}),as(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=t=>{var n;(n=this.onFirstAudioReceived)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstVideoReceived=t=>{var n;(n=this.onFirstVideoReceived)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstAudioDecoded=t=>{var n;(n=this.onFirstAudioDecoded)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstVideoDecoded=(t,n,i)=>{var r;(r=this.onFirstVideoDecoded)===null||r===void 0||r.call(this,t,n,i)},this.statsFilter.onSelectedLocalCandidateChanged=(t,n)=>{var i;(i=this.onSelectedLocalCandidateChanged)===null||i===void 0||i.call(this,t,n)},this.statsFilter.onSelectedRemoteCandidateChanged=(t,n)=>{var i;(i=this.onSelectedRemoteCandidateChanged)===null||i===void 0||i.call(this,t,n)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0}async batchReceive(t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const n=this.remoteSDP.batchSend(t).map((o,s)=>{let{id:a,mslabel:c}=o;const{kind:d}=t[s];return new K((l,h)=>{const u=setTimeout(()=>{h(new Error("Cannot receive track, id: ".concat(a)))},1e4),p=E=>{const m=Fe();if(m.name==="Safari"&&Number(m.version)===11&&E.track.id!==a&&E.streams[0].id===c){var g;const R=E.streams[0].getTracks()[0];return(g=this.remoteSDP)===null||g===void 0||g.updateTrackLabel(d,a,E.track.id),this.peerConnection.removeEventListener("track",p),clearTimeout(u),void l({track:R,id:a})}if(E.track.id===a)return this.peerConnection.removeEventListener("track",p),clearTimeout(u),void l({track:E.track,id:a})};this.peerConnection.addEventListener("track",p)})}),i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const r=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(r),await K.all(n)}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(n.toString()))}}async getRemoteSSRC(t){if(!this.remoteSDP)return;const n=this.remoteSDP.getSSRC(t);return n==null?void 0:n[0].ssrcId}setConfiguration(t){if(Oe().supportPCSetConfiguration){const n=zu.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}}},H(Et.prototype,"connect",[Ar],Object.getOwnPropertyDescriptor(Et.prototype,"connect"),Et.prototype),H(Et.prototype,"stopSending",[Ar],Object.getOwnPropertyDescriptor(Et.prototype,"stopSending"),Et.prototype),H(Et.prototype,"receive",[Ar],Object.getOwnPropertyDescriptor(Et.prototype,"receive"),Et.prototype),H(Et.prototype,"stopReceiving",[Ar],Object.getOwnPropertyDescriptor(Et.prototype,"stopReceiving"),Et.prototype),H(Et.prototype,"muteRemote",[Ar],Object.getOwnPropertyDescriptor(Et.prototype,"muteRemote"),Et.prototype),H(Et.prototype,"unmuteRemote",[Ar],Object.getOwnPropertyDescriptor(Et.prototype,"unmuteRemote"),Et.prototype),H(Et.prototype,"muteLocal",[Ar],Object.getOwnPropertyDescriptor(Et.prototype,"muteLocal"),Et.prototype),H(Et.prototype,"unmuteLocal",[Ar],Object.getOwnPropertyDescriptor(Et.prototype,"unmuteLocal"),Et.prototype),H(Et.prototype,"close",[Ar],Object.getOwnPropertyDescriptor(Et.prototype,"close"),Et.prototype),H(Et.prototype,"updateEncoderConfig",[Ar],Object.getOwnPropertyDescriptor(Et.prototype,"updateEncoderConfig"),Et.prototype),H(Et.prototype,"updateSendParameters",[Ar],Object.getOwnPropertyDescriptor(Et.prototype,"updateSendParameters"),Et.prototype),H(Et.prototype,"replaceTrack",[Ar],Object.getOwnPropertyDescriptor(Et.prototype,"replaceTrack"),Et.prototype),H(Et.prototype,"getRemoteSSRC",[Ar],Object.getOwnPropertyDescriptor(Et.prototype,"getRemoteSSRC"),Et.prototype),Et);function Ar(e,t,n){const i=e[t];if(typeof i!="function")throw new Error("Cannot use mutex on object property.");return n.value=async function(){const r=this.mutex,o=await r.lock("Locking from P2PConnection.".concat(t));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return await i.apply(this,a)}finally{o()}},n}const Ute={name:"PlanBConnection",create:function(e){let{store:t,spec:n}=e;return new Mte(n,t)}},Vte={interceptLocalAudioFrame:async function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!Oe().supportWebRTCEncodedTransform)return void _.warning("browser not support audio encoded transform");if(Xp.has(e)||!e.track)return;const n={track:e.track};if(ss()){if(!e.createEncodedStreams)return void _.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}
186catch(s){return void _.error("create audio-encoded-streams error",s&&s.message)}const o=new TransformStream({transform(s,a){n.controller||(n.controller=a),e.track&&e.track.id!==n.track.id&&(_.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i));const c=t.metadata&&t.metadata();c?function(d,l){const{chunk:h,controller:u}=l,p=Vs.METADATA;h.data=function(E,m,g){const R=g.byteLength,v=R+jS+SP,C=BS+GS+v,w=new ArrayBuffer(E.byteLength+C),b=new DataView(w);b.setUint8(0,gP),b.setUint16(1,v),b.setUint8(3,m),b.setUint16(4,R);for(let N=0;N<R;N++)b.setUint8(6+N,g[N]);const y=new Uint8Array(b.buffer);return y.set(new Uint8Array(E),C),y.buffer}(h.data,p,d),u.enqueue(h)}(c,{chunk:s,controller:a}):a.enqueue(s)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else if(vn()){if(typeof RTCRtpScriptTransform>"u")return void _.warning("browser not support RTCRtpScriptTransform");const r=Yp(),o=new MessageChannel;await new K(a=>r.onmessage=c=>{c.data==="registered"&&a(void 0)});const s=new RTCRtpScriptTransform(r,{name:"audio-metadata-tx",port:o.port2},[o.port2]);e.transform=s,await new K(a=>r.onmessage=c=>{c.data==="started"&&a(void 0)}),o.port1.onmessage=a=>{var c;if(a.data.transformed&&e.track&&((c=e.track)===null||c===void 0?void 0:c.id)!==n.track.id)_.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i);else if(a.data.getMetadata){const d=t.metadata&&t.metadata();d&&o.port1.postMessage({metadata:d})}},n.worker=r}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}const r=Xp.get(e);if(r){Xp.delete(e);try{var o,s;(o=r.controller)===null||o===void 0||o.terminate(),(s=r.worker)===null||s===void 0||s.terminate()}catch(a){_.warning(a&&a.message)}}}Xp.set(e,n),e.track.addEventListener("ended",i)},interceptRemoteAudioFrame:async function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!Oe().supportWebRTCEncodedTransform)return void _.warning("browser not support audio encoded transform");if($p.has(e))return;const n={track:e.track,onMetadata:t.onMetadata,onPts:t.onPts};if(ss()&&!Hn()){if(!e.createEncodedStreams)return void _.warning("browser not support createEncodedStreams() API");Rp(je.CHROME,87,116)||(t.enableTopn=!1);let r=null;try{r=e.createEncodedStreams()}catch(s){return void _.error("create audio-encoded-streams error",s&&s.message)}const o=new TransformStream({transform(s,a){n.controller||(n.controller=a),e.track&&e.track.id!==n.track.id&&(_.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i)),t.enableTopn?function(c,d,l){var h;const u=WS(new DataView(d.data));if(!u)return l.enqueue(d);const p=c.track.id;yX.set(p,c.track);const E=(h=u.tlv.find(w=>w.tag===Vs.AUDIO_LEVEL))===null||h===void 0?void 0:h.value;let m=0;typeof E=="number"&&(m=127-E);const g=Math.round(Math.pow(10,m/60)-1),{selected:R,speaker:v}=function(w,b){let y=fd.get(w);if(y||(y=function(N){const k=new RP;return fd.set(N,k),lo||(lo=new AX(T("TOPN_SILENCE_THRESHOLD")||500),lo.on("ActiveSpeakerChanged",U=>{U!=null&&(qp=U)})),lo.addSpeakers([k]),k}(w)),fd.size<=vP)return{selected:!0,speaker:y};if(!lo)throw new Error("no active speaker detector");return lo.levelChanged(y.id,b),ja=lo.loudest.map(N=>N.id),qp&&!x(ja).call(ja,qp)&&ja.length>=vP&&ja.pop(),{selected:x(ja).call(ja,y.id)||y.id===qp,speaker:y}}(c,g),C=function(w,b,y){const N=uo.get(w)||new CX(w,b);return N.score=y,uo.set(w,N),function(k){if(Zp.set(k,!0),!Qp)return void(Qp=Date.now());const U=Date.now();U-Qp>1e3&&(Zp.get(k)?Zp.set(k,!1):(AP(k),Zp.delete(k)),Qp=U)}(w),N}(p,c.track,v.energyScore);C.addSample(R),C.active&&(d.data=u.frame.buffer,l.enqueue(d))}(e,s,a):t.enableMetadata||t.enablePts?function(c,d,l,h){const u=new DataView(c.data),p=u.getUint8(0);let E;if(128&p&&p!==71){const R=function(v){if(v.byteLength<=0)return[];const C=[];let w=0;for(;w<v.byteLength;){const y=(128&v.getUint8(w))>>7,N=127&v.getUint8(w);if(!(y&&w+4<=v.byteLength)){w++;break}{const k=v.getUint32(w,!1),U=(16776192&k)>>10,X=1023&k;C.push({pt:N,ts_offset:U,length:X,data:new Uint8Array}),w+=4}}let b=v.byteLength-w;for(const y of C){if(y.length>b)return console.warn("Broken red payload"),[];y.length>0&&(y.data=new Uint8Array(v.buffer,v.byteOffset+w,y.length),w+=y.length,b-=y.length)}if(b>0){const y={pt:C.length>0?C[C.length-1].pt:0,ts_offset:0,length:b,data:new Uint8Array(v.buffer,v.byteOffset+w,b)};C.push(y)}return C}(u);if(R.length>0){const v=function(C){let w=0;for(let N=0;N<C.length;N++)w+=N<C.length-1?4:1,w+=C[N].length;const b=new Uint8Array(w);let y=0;for(let N=0;N<C.length;N++)if(N<C.length-1){const k=(2147483648|(127&C[N].pt)<<24|(262143&C[N].ts_offset)<<10|1023&C[N].length)>>>0;b[y++]=k>>24&255,b[y++]=k>>16&255,b[y++]=k>>8&255,b[y++]=255&k}else b[y++]=127&C[N].pt;for(const N of C)b.set(N.data,y),y+=N.length;return b}(R.map(C=>{const w=new Uint8Array(C.length);w.set(C.data);const b=WS(new DataView(w.buffer));return b!=null&&b.frame&&(C.data=b==null?void 0:b.frame),E=b,C}));c.data=v.buffer}}else E=WS(u),E&&(c.data=E.frame.buffer);if(d.enqueue(c),!E)return;const m=E.tlv.find(R=>R.tag===Vs.METADATA);m&&l&&m.value instanceof Uint8Array&&l(m.value);const g=E.tlv.find(R=>R.tag===Vs.AUDIO_64_BIT_PTS);g&&h&&g.value instanceof Uint8Array&&g.value.length==8&&h(new DataView(g.value.buffer).getBigUint64(0,!0))}
186(s,a,t.onMetadata,t.onPts):a.enqueue(s)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else{if(typeof RTCRtpScriptTransform>"u")return void _.warning("browser not support RTCRtpScriptTransform");const r=Yp(),o=new MessageChannel;await new K(a=>r.onmessage=c=>{c.data==="registered"&&a(void 0)});const s=new RTCRtpScriptTransform(r,{name:"audio-metadata-rx",port:o.port2},[o.port2]);e.transform=s,await new K(a=>r.onmessage=c=>{c.data==="started"&&a(void 0)}),o.port1.onmessage=a=>{var c;a.data.transformed&&e.track&&((c=e.track)===null||c===void 0?void 0:c.id)!==n.track.id?(_.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i)):a.data.metadata&&n.onMetadata?n.onMetadata(a.data.metadata):a.data.pts&&n.onPts&&n.onPts(a.data.pts)},n.worker=r}function i(){e.track.removeEventListener("ended",i),function(r){const o=$p.get(r);if(o){(function(c){const d=fd.get(c);d&&(fd.delete(c),lo&&(lo.removeSpeakers([d]),fd.size===0&&(lo.destroy(),lo=null)))})(r),AP(r.track.id),$p.delete(r);try{var s,a;(s=o.controller)===null||s===void 0||s.terminate(),(a=o.worker)===null||a===void 0||a.terminate()}catch(c){_.warning(c&&c.message)}}}(e)}$p.set(e,n),e.track.addEventListener("ended",i)},interceptLocalVideoFrame:async function(e,t){if(!Oe().supportWebRTCEncodedTransform)return void _.warning("browser not support video encoded transform");if(e_.has(e)||!e.track)return;const n={track:e.track};if(ss()){if(!e.createEncodedStreams)return void _.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(a){return void _.error("create video-encoded-streams error",a&&a.message)}const o=[];t.on("sei-to-send",a=>{o.push(a)});const s=new TransformStream({transform(a,c){n.controller||(n.controller=c),e.track&&e.track.id!==n.track.id&&(_.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i));const d=IP(new Uint8Array(a.data)),l=o.shift();if(l){const h=function(u,p,E){switch(E){case XS:return function(m,g){const R=yP(g),v=R.length,C=Math.floor(v/255),w=v%255,b=new Uint8Array(6+C+1+v+m.byteLength);b[0]=0,b[1]=0,b[2]=0,b[3]=1,b[4]=6,b[5]=101;let y=0;for(;y<C;)b[6+y]=255,y++;return b[6+y]=w,y++,b.set(R,6+y),b.set(new Uint8Array(m),6+y+v),b.buffer}(u,p);case JS:return function(m,g){const R=yP(g),v=R.length,C=Math.floor(v/255),w=v%255,b=new Uint8Array(7+C+1+v+1+m.byteLength);b[0]=0,b[1]=0,b[2]=0,b[3]=1,b[4]=78,b[5]=1,b[6]=101;let y=0;for(;y<C;)b[7+y]=255,y++;return b[7+y]=w,y++,b.set(R,7+y),y+=v,b[7+y]=128,y++,b.set(new Uint8Array(m),7+y),b.buffer}(u,p);default:return null}}(a.data,l,d);h&&(a.data=h)}c.enqueue(a)}});r.readable.pipeThrough(s).pipeTo(r.writable)}else{if(!vn())return;{if(typeof RTCRtpScriptTransform>"u")return void _.warning("browser not support RTCRtpScriptTransform");const r=Yp(),o=new MessageChannel;await new K(a=>r.onmessage=c=>{c.data==="registered"&&a(void 0)});const s=new RTCRtpScriptTransform(r,{name:"sei-tx",port:o.port2},[o.port2]);e.transform=s,await new K(a=>r.onmessage=c=>{c.data==="started"&&a(void 0)}),t.on("sei-to-send",a=>{o.port1.postMessage({sei:a})}),o.port1.onmessage=a=>{var c;a.data.transformed&&e.track&&((c=e.track)===null||c===void 0?void 0:c.id)!==n.track.id&&(_.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i))},n.worker=r}}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}const r=e_.get(e);if(r){e_.delete(e);try{var o,s;(o=r.controller)===null||o===void 0||o.terminate(),(s=r.worker)===null||s===void 0||s.terminate()}catch(a){_.warning(a&&a.message)}}}e_.set(e,n),e.track.addEventListener("ended",i)},interceptRemoteVideoFrame:async function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!Oe().supportWebRTCEncodedTransform)return void _.warning("browser not support video encoded transform");if(!e.track)return;if(Ql.has(e)){const r=Ql.get(e);return void(r&&(r.onSei=t.onSei))}const n={track:e.track,onSei:t.onSei};if(ss()){if(!e.createEncodedStreams)return void _.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}
186catch(s){return void _.error("create video-encoded-streams error",s&&s.message)}const o=new TransformStream({transform(s,a){if(n.controller||(n.controller=a),!n.firstFrameInfo){var c;const l=s.getMetadata()||{};n.firstFrameInfo=ft({type:s.type,rtpTimestamp:s.timestamp,payloadType:l.payloadType||0,ssrc:l.synchronizationSource||0,length:s.data.byteLength},"mimeType"in l?{mimeType:l.mimeType}:{}),(c=t.onFirstFrame)===null||c===void 0||c.call(t,n.firstFrameInfo)}e.track&&e.track.id!==n.track.id&&(_.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i));const d=function(l,h){switch(h){case XS:return function(u){const p=new DataView(u.data);let E=0;for(;E+4<u.data.byteLength;){if(p.getUint8(E+0)===0&&p.getUint8(E+1)===0&&p.getUint8(E+2)===0&&p.getUint8(E+3)===1&&p.getUint8(E+4)===6){let m=E+6,g=0,R=0;for(;(R=p.getUint8(m++))===255;)g+=255;g+=R;const v=CP(u.data,m,g);return new Uint8Array(v)}E++}return null}(l);case JS:return function(u){const p=new DataView(u.data);let E=0;for(;E+5<u.data.byteLength;){if(p.getUint8(E+0)===0&&p.getUint8(E+1)===0&&p.getUint8(E+2)===0&&p.getUint8(E+3)===1&&p.getUint8(E+4)===78&&p.getUint8(E+5)===1&&p.getUint8(E+6)===101){let m=E+7,g=0,R=0;for(;(R=p.getUint8(m++))===255;)g+=255;g+=R;const v=CP(u.data,m,g);return new Uint8Array(v)}E++}return null}(l);default:return null}}(s,IP(new Uint8Array(s.data)));d&&n.onSei&&n.onSei(d),a.enqueue(s)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else if(vn()){if(typeof RTCRtpScriptTransform>"u")return void _.warning("browser not support RTCRtpScriptTransform");const r=Yp(),o=new MessageChannel;await new K(a=>r.onmessage=c=>{c.data==="registered"&&a(void 0)});const s=new RTCRtpScriptTransform(r,{name:"sei-rx",port:o.port2},[o.port2]);e.transform=s,await new K(a=>r.onmessage=c=>{c.data==="started"&&a(void 0)}),o.port1.onmessage=a=>{var c;if(a.data.transformed&&e.track&&((c=e.track)===null||c===void 0?void 0:c.id)!==n.track.id)_.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i);else if(a.data.sei&&n.onSei)n.onSei(a.data.sei);else if(a.data.firstFrameInfo&&t.onFirstFrame){var d;(d=t.onFirstFrame)===null||d===void 0||d.call(t,a.data.firstFrameInfo)}},n.worker=r}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}(function(r){const o=Ql.get(r);if(o){Ql.delete(r);try{var s,a;(s=o.controller)===null||s===void 0||s.terminate(),(a=o.worker)===null||a===void 0||a.terminate()}catch(c){_.warning(c&&c.message)}}})(e)}Ql.set(e,n),e.track.addEventListener("ended",i)}},xte={name:"InterceptFrame",create:()=>Vte};var xe;function _x(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function Ao(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?_x(Object(n),!0).forEach(function(i){S(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_x(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}let Fte=(xe=class rl extends o_{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var t,n;return(t=(n=this.peerConnection.getReceivers()[0])===null||n===void 0||(n=n.transport)===null||n===void 0?void 0:n.state)!==null&&t!==void 0?t:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map(t=>t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"").filter(t=>{var n;return x(n=Object.keys(Ma)).call(n,t)}))]}constructor(t,n,i){super(t,n),S(this,"id",Qe(5,"connection-")),S(this,"store",void 0),S(this,"peerConnection",void 0),S(this,"forceTurn",!1),S(this,"remoteSDP",void 0),S(this,"initialOffer",void 0),S(this,"transportEventReceiver",void 0),S(this,"statsFilter",void 0),S(this,"extension",{useXR:T("USE_XR")}),S(this,"localCapabilities",void 0),S(this,"remoteCodecs",void 0),S(this,"localCandidateCount",0),S(this,"allCandidatesReceived",!1),S(this,"isPreallocation",!1),S(this,"preMediaMap",new Map),S(this,"dataStreamChannelMap",new Map),S(this,"establishPromise",void 0),S(this,"recoveredDataChannelIds",[]),S(this,"currentDataChannelId",1),S(this,"supportAV1RtpSpec",!1),S(this,"mutex",void 0),S(this,"qualityLimitationReason",od.NONE),S(this,"isFirstConnected",!1),this.store=n,this.forceTurn=Ov(t),this.mutex=new An("NVConnectionExtension-mutex",n.clientId),this.peerConnection=i,this.isFirstConnected=!1,this.statsFilter=Np(this.peerConnection,T("STATS_UPDATE_INTERVAL"),void 0,Rt()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,t.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}getPreMedia(t){return this.preMediaMap.get(t)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(t,n){if(this.remoteCodecs=n,!this.remoteSDP)return void _.debug("[NVConnectionExtension] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(n));if(this.remoteSDP.updateRemoteCodec(t,n,this.store.codec)){const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i);const o=this.remoteSDP.toString();r==null||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}else _.debug("[NVConnectionExtension] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const n=await this.peerConnection.createOffer();if(!n.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");
186const i=Ho(n.sdp),r=await lv({filterRTX:!T("USE_PUB_RTX")&&!T("USE_SUB_RTX"),filterVideoFec:T("FILTER_VIDEO_FEC"),filterAudioFec:T("FILTER_AUDIO_FEC"),filterVideoCodec:T("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:T("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:T("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=Uu(r),this.initialOffer=n,T("ENABLE_SVC")&&this.store.codec=="av1"){const s=await LU();var t;s&&(this.supportAV1RtpSpec=!0,(t=r.send)===null||t===void 0||t.videoExtensions.push(s))}let o;return n.sdp&&lm(n.sdp)&&(o=Ct(r),CU(o)),Ao(Ao({},i),{},{rtpCapabilities:o||r,offerSDP:n.sdp})}catch(n){throw new L(A.GET_LOCAL_CONNECTION_PARAMS_FAILED,n.toString())}}async connect(t){try{if(!this.initialOffer)throw new Error("Cannot establish NVConnectionExtension without initial offer.");if(this.initialOffer.sdp&&lm(this.initialOffer.sdp)&&yU(t.rtpCapabilities,this.localCapabilities),this.remoteSDP=new e2(Ao(Ao({},t),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!T("ENABLE_PRE_SUB_WITH_PRE_PC")||!T("PRE_USE_LOCAL_CODECS"))&&Ua(this.store),!0),t.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec),sN()){var n;const r=((n=this.store.preSubOptions)===null||n===void 0?void 0:n.length)||0,o=T("PRE_SUB_NUM")||1,s=r>o?r:o,{mids:a,preSSRCs:c}=this.remoteSDP.preloadRemoteMedia(s),d=xu(this.initialOffer.sdp,this.extension),l=this.logSDPExchange(d||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:d}),l==null||l(d),new Array(s).fill(0).forEach(()=>{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})});const h=await this.peerConnection.createOffer(),u=this.logSDPExchange(h.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(h);const p=this.remoteSDP.toString();u==null||u(p),await this.peerConnection.setRemoteDescription({type:"answer",sdp:p}),_.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media with icc/dtls, add preload ssrcs ").concat(c)),this.presetMedia(a,c);const E=this.peerConnection.getTransceivers()[0];E!=null&&E.receiver&&this.tryBindTransportEvents(E.receiver)}else{const r=this.remoteSDP.toString(),o=xu(this.initialOffer.sdp,this.extension),s=this.logSDPExchange(o||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:o}),s==null||s(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r});const a=this.peerConnection.getTransceivers()[0];if(a!=null&&a.receiver&&this.tryBindTransportEvents(a.receiver),Ua(this.store))if(t.preallocation&&T("ENABLE_PRE_SUB_WITH_PRE_PC")){var i;const c=((i=this.store.preSubOptions)===null||i===void 0?void 0:i.length)||0,d=T("PRE_SUB_NUM")||1,l=c>d?c:d,{mids:h,preSSRCs:u}=this.remoteSDP.preloadRemoteMedia(l);await vi(this.peerConnection,this.remoteSDP,this.extension),_.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(u)),this.presetMedia(h,u)}else{const{preSSRCs:c=[]}=t,d=c.map(h=>h.ssrcMsg[0].ssrcId);if(c.length===0)return;const{mids:l}=this.remoteSDP.batchSend(c.map(h=>Object.assign({},h)));await vi(this.peerConnection,this.remoteSDP,this.extension),_.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(d)),this.presetMedia(l,d)}}}catch(r){throw new L(A.EXCHANGE_SDP_FAILED,"NVConnectionExtension.connect failed; ".concat(r.toString()))}}presetMedia(t,n){t.forEach((i,r)=>{this.peerConnection.getTransceivers().forEach(o=>{if(o.mid!=null&&i===o.mid&&o.receiver.track){const s=o.receiver.track;let a;s.kind==="video"&&T("ENABLE_PRE_RENDER")&&(a=new Kp({trackId:"track-".concat(s.kind,"-unknown-").concat(this.store.clientId,"_").concat(Qe(5,""))},!0),a.updateVideoTrack(s),a.onFirstVideoFrameRender=()=>{var c;const d=this.preMediaMap.get(n[r]);d&&(d.firstVideoRender=Date.now()),(c=this.onFirstVideoRender)===null||c===void 0||c.c
186all(this,n[r])},a.onVideoBufferReady=()=>{var c;(c=this.onFirstVideoBufferReady)===null||c===void 0||c.call(this,n[r])},a.play(this.store.sessionId||void 0)),this.preMediaMap.set(n[r],{mid:i,track:s,player:a,transceiver:o})}}),this.store.peerReceiver()})}checkDtlsParameters(t){return!!this.remoteSDP&&t.length>0&&this.remoteSDP.updateRemoteDtlsParameters(t)}checkIceParameters(t){return this.remoteSDP?this.remoteSDP.restartICE(t):!1}async updateRemoteConnect(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateRemoteConnect before remote SDP created");let n=!1;const{rtpCapabilities:i}=t;if([,n]=this.remoteSDP.updateRemoteRTPCapabilities(i),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const s=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);n=n||s}const{preSSRCs:r=[]}=t,o=r.map(s=>s.ssrcMsg[0].ssrcId);if(!this.remoteSDP.checkPreloadSsrcs(o)){const s=[],a=[];if(Array.from(this.preMediaMap.entries()).every(c=>{let[d,{mid:l,player:h,track:u}]=c;return s.push(l),a.push(d),this.preMediaMap.delete(d),h&&h.destroy(),!0}),s.length>0&&(this.remoteSDP.stopSending(s),await vi(this.peerConnection,this.remoteSDP,this.extension),_.warn("[NVConnectionExtension.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(a)),Z.reportApiInvoke(this.store.sessionId,{name:vt.PRELOAD_MEDIA_FAILED,options:[r,a],tag:ht.TRACER}).onSuccess()),r.length>0){const{mids:c}=this.remoteSDP.batchSend(r.map(d=>Object.assign({},d)));await vi(this.peerConnection,this.remoteSDP,this.extension),_.debug("[NVConnectionExtension.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(o)),this.presetMedia(c,o)}}n?(await vi(this.peerConnection,this.remoteSDP,this.extension),_.debug("[NVConnectionExtension] updateRemoteConnect by exchanging SDP.")):_.debug("[NVConnectionExtension] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"NVConnectionExtension.updateRemoteConnect failed; ".concat(n.toString()))}}send(t,n,i){var r=this;return di(function*(){const o=yield ve(r.mutex.lock("From NVConnectionExtension.send"));try{if(!r.remoteSDP)throw new Error("Cannot call NVConnectionExtension.send before remote SDP created");const s=[],a=Lu();t.forEach(g=>{const R=r.peerConnection.addTransceiver(g._mediaStreamTrack,Ao({direction:"sendonly"},g.trackMediaType==="video"&&r.supportAV1RtpSpec&&a?{sendEncodings:[{scalabilityMode:a}]}:{}));s.push(R),g._updateRtpTransceiver(R)}),Rt()&&T("SIMULCAST")===!0&&(yield ve(r.applySimulcastForFirefox(s,t)));const c=yield ve(r.peerConnection.createOffer()),d=r.remoteSDP.predictReceivingMids(t.length),l=r.mungSendOfferSDP(c.sdp,t,d),h=ii(l),u=d.map(g=>{const R=h.mediaDescriptions.find(v=>v.attributes.mid===g);if(!R)throw new Error("Cannot extract ssrc from mediaDescription.");return sv(R,T("USE_PUB_RTX"))});let p;try{p=yield u}catch(g){p=[],r.remoteSDP.receive(t,n,i,p);const R=r.remoteSDP.toString();throw yield ve(r.peerConnection.setLocalDescription({type:"offer",sdp:l})),yield ve(r.peerConnection.setRemoteDescription({type:"answer",sdp:R})),yield ve(r.stopSending(d,!0)),g}r.remoteSDP.receive(t,n,i,p);const E=r.remoteSDP.toString(),m=r.logSDPExchange(l,"offer","local","send");return yield ve(r.peerConnection.setLocalDescription({type:"offer",sdp:l})),yield ve(r.applySimulcastEncodings(s,t)),yield ve(r.applySendEncodings(s,t)),m==null||m(E),yield ve(r.peerConnection.setRemoteDescription({type:"answer",sdp:E})),s.map((g,R)=>{const v=d[R];return{localSSRC:u[R],id:v,transceiver:g}})}catch(s){throw s instanceof L?s:new L(A.EXCHANGE_SDP_FAILED,"NVConnectionExtension.send failed; ".concat(s.toString()))}finally{o()}})()}async createDataChannels(t,n){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.createDataChannels before remote SDP created");let i=this.dataStreamChannelMap.get(t);if(i&&i.readyState==="open")_.debug("[NVConnectionExtension] Channels are already available and can be reused directly.");else{const o=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if(typeof o!="number")throw new Error("create DataChannel error, because cannot get dc id");
186i=this.peerConnection.createDataChannel("datastream-channel",{id:o,negotiated:!0,ordered:!1,maxRetransmits:T("DATASTREAM_MAX_RETRANSMITS")}),i.binaryType="arraybuffer",this.dataStreamChannelMap.set(t,i)}n.forEach(o=>{o._updateOriginDataChannel(i)});const{needExchangeSDP:r}=this.remoteSDP.sendDataChannel();if(r){const o=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const s=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(s),_.debug("[NVConnectionExtension] createDataChannels by exchanging SDP.")}else _.debug("[NVConnectionExtension] createDataChannels no need to exchange SDP.");return}catch(i){throw i instanceof L?i:new L(A.EXCHANGE_SDP_FAILED,"NVConnectionExtension.createDataChannels failed; ".concat(i.toString()))}}async stopDataChannels(t){try{const n=this.dataStreamChannelMap.get(t);return n&&(n.id&&this.recoveredDataChannelIds.push(n.id),n.close()),void this.dataStreamChannelMap.delete(t)}catch(n){throw n instanceof L?n:new L(A.DATACHANNEL_FAILED,"NVConnectionExtension.stopDataChannels failed; ".concat(n.toString()))}}async stopSending(t,n){const i=n?void 0:await this.mutex.lock("From NVConnectionExtension.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.stopSending before remote SDP created");const r=this.peerConnection.getTransceivers().filter(c=>t.indexOf(c.mid)!==-1);if(r.length!==t.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call NVConnectionExtension.stopSending.");r.map(c=>{var d;Yd(this.id+c.mid,this),c.direction="inactive",(d=c.stop)===null||d===void 0||d.call(c)});const o=await this.peerConnection.createOffer(),s=this.logSDPExchange(o.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(o),this.remoteSDP.stopReceiving(t);const a=this.remoteSDP.toString();s==null||s(a),await this.peerConnection.setRemoteDescription({type:"answer",sdp:a})}catch(r){throw new L(A.EXCHANGE_SDP_FAILED,"NVConnectionExtension.stopSending failed; ".concat(r.toString()))}finally{i&&i()}}async receive(t,n,i,r){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.receive ".concat(t," before remoteSDP created."));const{mid:o,needExchangeSDP:s}=this.remoteSDP.send(t,n,i,r);s&&(await vi(this.peerConnection,this.remoteSDP,this.extension),_.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] receive ").concat(t," by exchanging SDP.")));const a=this.peerConnection.getTransceivers().find(c=>c.mid===o);if(!a)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:a.receiver.track,id:o,transceiver:a}}catch(o){throw new L(A.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(o.toString()))}}async batchReceive(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.batchReceive before remoteSDP created.");const{mids:n,needExchangeSDP:i}=this.remoteSDP.batchSend(t);return i&&(await vi(this.peerConnection,this.remoteSDP,this.extension),_.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] batchReceive by exchanging SDP."))),n.map(r=>{const o=this.peerConnection.getTransceivers().find(s=>s.mid===r);if(!o)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:o.receiver.track,id:r,transceiver:o}})}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(n.toString()))}}async stopReceiving(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.stopReceiving before remote SDP created.");t.forEach(o=>{Array.from(this.preMediaMap.entries()).some(s=>{let[a,{mid:c,player:d}]=s;if(c===o)return this.preMediaMap.delete(a),d&&d.destroy(),!0})}),this.remoteSDP.stopSending(t);const n=this.remoteSDP.toString(),i=this.logSDPExchange(n,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const r=await this.peerConnection.createAnswer();i==null||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"NVConnectionExtension stopReceiving failed; ".concat(n.toString()))}}async muteRemote(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.muteRemote mid=".concat(t," before remote SDP created."));this.remoteSDP.mute(t);const n=this.remoteSDP.toString(),i=this.logSDPExchange(n,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const r=await this.peerConnection.createAnswer();i==null||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteRemote failed; ".concat(n.toString()))}}async unmuteRemote(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.unmuteRemote mid=".concat(t," before remote SDP created."));this.remoteSDP.unmute(t);const n=this.remoteSDP.toString(),i=this.logSDPExchange(n,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const r=await this.peerConnection.createAnswer();i==null||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteRemote failed; ".concat(n.toString()))}}async muteLocal(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.muteLocal before remote SDP created.");const n=this.peerConnection.getTransceivers().filter(s=>s.mid&&t.indexOf(s.mid)!==-1);if(n.length!==t.length)throw new Error("Transceivers' length doesn't match mids' length.");n.map(s=>{s.direction="inactive"});const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.muteRemote(t);const o=this.remoteSDP.toString();r==null||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteLocal failed; ".concat(n.toString()))}}async unmuteLocal(t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.unmuteLocal before remote SDP created.");const n=this.peerConnection.getTransceivers().filter(s=>s.mid&&t.indexOf(s.mid)!==-1);if(n.length!==t.length)throw new Error("Transceivers' length doesn't match mids' length.");n.map(async(s,a)=>{s.direction="sendonly"});const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(i),this.remoteSDP.unmuteRemote(t),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(t,this.remoteCodecs,this.store.codec);const o=this.remoteSDP.toString();r==null||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(n){throw new L(A.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteLocal failed; ".concat(n.toString()))}}restartICE(t){var n=this;return di(function*(){const i=yield ve(n.mutex.lock("From NVConnectionExtension.restartICE"));try{if(!n.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const r=Oe().supportPCSetConfiguration,o=T("FORCE_TURN_TCP")||n.forceTurn;if(t===gn.RELAY&&!r)return;if(r&&!o){const h=t===gn.RELAY?"relay":"all",u=n.peerConnection.getConfiguration();u.iceTransportPolicy!==h&&(_.debug("[".concat(n.store.clientId,"] restartICE change iceTransportPolicy from [").concat(u.iceTransportPolicy,"] to [").concat(h,"]")),u.iceTransportPolicy=h,n.peerConnection.setConfiguration(u))}n.remoteSDP.updateCandidates(t);const s=yield ve(n.peerConnection.createOffer({iceRestart:!0}));if(!s.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const a=Ho(s.sdp),{remoteIceParameters:c}=yield a.iceParameters;n.remoteSDP.restartICE(c);const d=n.remoteSDP.toString(),l=n.logSDPExchange(s.sdp||"","offer","local","restartICE");n.store.descriptionStart(),yield ve(n.peerConnection.setLocalDescription(s)),l==null||l(d),yield ve(n.peerConnection.setRemoteDescription({type:"answer",sdp:d}))}catch(r){_.warning("[".concat(n.store.clientId,"] restart ICE failed, abort operation"),r)}finally{i()}})()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const t=await this.mutex.lock("From NVConnectionExtension.extendCandidate");try{this.remoteSDP.updateCandidates(gn.TCP_RELAY),await vi(this.peerConnection,this.remoteSDP,this.extension)}catch(n){_.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),n)}finally{t()}}close(){var t;
186this.peerConnection.getTransceivers().forEach(n=>{Yd(this.id+n.mid,this)}),this.preMediaMap.forEach(n=>{let{player:i}=n;i&&i.destroy()}),this.preMediaMap.clear(),this.peerConnection.close(),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return Ao(Ao({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(t){return this.statsFilter.getVideoIsReady(t)}async updateEncoderConfig(t,n){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateEncoderConfig before remote SDP created.");const i=await this.peerConnection.createOffer(),r=this.mungSendOfferSDP(i.sdp,[n],[t]);this.remoteSDP.updateRecvMedia(t,n);const o=this.remoteSDP.toString(),s=this.logSDPExchange(r,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:r}),s==null||s(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(i){throw new L(A.EXCHANGE_SDP_FAILED,i.toString())}}async updateSendParameters(t,n){const i=this.peerConnection.getTransceivers().filter(r=>r.mid===t);i.length===1&&(this.isVP8Simulcast(n)?Rt()||await this.applySimulcastEncodings(i,[n]):await this.applySendEncodings(i,[n]))}setStatsRemoteVideoIsReady(t,n){this.statsFilter.setVideoIsReady2(t,n)}async replaceTrack(t,n){const i=this.peerConnection.getTransceivers().find(r=>r.mid===n);i&&await i.sender.replaceTrack(t._mediaStreamTrack)}async getSelectedCandidatePair(){const t=this.peerConnection.getReceivers();if(t.length>0&&t[0].transport&&t[0].transport.iceTransport&&t[0].transport.iceTransport.getSelectedCandidatePair&&t[0].transport.iceTransport.getSelectedCandidatePair()){const n=t[0].transport.iceTransport,{local:i,remote:r}=n.getSelectedCandidatePair();return{local:Ao(Ao({},Gr),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port}),remote:Ao(Ao({},Gr),{},{candidateType:r.type,protocol:r.protocol,address:r.address,port:r.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var t;(t=this.onICEConnectionStateChange)===null||t===void 0||t.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var t;this.peerConnection.connectionState==="connected"&&(this.isFirstConnected=!0),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=t=>{if(t&&(t.errorCode||t.errorText)){var n;const i="code: ".concat(t.errorCode,", message: ").concat(t.errorText),r=t.port?"local: ".concat(t.port):"",o=Ko(t.url||"");_.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: NVConnectionExtension.onICECandidateError(").concat(i,"), url: ").concat(o||"",", host_candidate:").concat(r)),(n=this.onICECandidateError)===null||n===void 0||n.call(this,i)}},this.peerConnection.onicegatheringstatechange=t=>{t&&t.target&&"iceGatheringState"in t.target&&_.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(t.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=t=>{t.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,_.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,_.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},T("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const n={iceServers:[]},i=t.cloudProxyServer||"disabled";return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&(wa(t.turnServer.servers)?n.iceServers=t.turnServer.servers:T("NEW_TURN_MODE")&&n.iceServers&&i==="disabled"?(T("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&n.iceServers.push(...rl.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):n.iceServers.push(...rl.newTurnServerConfigToIceServers(t.turnServer.servers)),T("NEW_FORCE_TURN")&&(n.iceTransportPolicy="relay")):t.turnServer.mode!=="off"&&(n.iceServers&&n.iceServers.push(...rl.turnServerConfigToIceServers(t.turnServer.servers)),T("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...rl.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),T("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEac
186h(r=>{r.forceturn&&(n.iceTransportPolicy="relay")}))),T("ENABLE_ENCODED_TRANSFORM")&&Oe().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}static turnServerConfigToIceServers(t){const n=[];return t.forEach(i=>{i.security?i.tcpport&&n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turns:".concat(qr(i.turnServerURL),":").concat(i.tcpport,"?transport=tcp")}):(i.udpport&&!T("FORCE_TURN_TCP")&&n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":").concat(i.udpport,"?transport=udp")}),i.tcpport&&n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":").concat(i.tcpport,"?transport=tcp")}))}),n}static newTurnServerConfigToIceServers(t){const n=[];return t.forEach(i=>{const r=T("NEW_TURN_MODE");r===1?n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":3478?transport=udp")}):r===2?n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":3478?transport=tcp")}):r===3?n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turns:".concat(qr(i.turnServerURL),":443?transport=tcp")}):r===4&&(n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":3478?transport=udp")}),n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":3478?transport=tcp")}),n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turns:".concat(qr(i.turnServerURL),":443?transport=tcp")}))}),n}tryBindTransportEvents(t){const n=t.transport;if(n){this.transportEventReceiver=t,n.onstatechange=()=>{var r;n!=null&&n.state&&((r=this.onDTLSTransportStateChange)===null||r===void 0||r.call(this,n.state))},n.onerror=r=>{var o;(o=this.onDTLSTransportError)===null||o===void 0||o.call(this,"error"in r?r.error:r)};const i=n.iceTransport;i&&(i.onstatechange=()=>{const r=n==null?void 0:n.iceTransport.state;var o;r&&((o=this.onICETransportStateChange)===null||o===void 0||o.call(this,r))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const{local:r,remote:o}=i.getSelectedCandidatePair()||{};if(r&&o){const s=r.address+":"+r.port,a=o.address+":"+o.port;_.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(Ko(s)),", remote ").concat(JSON.stringify(Ko(a))))}}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(t,n){var i,r;if(n||(n=this.peerConnection.getSenders().find(m=>m.track===t._mediaStreamTrack)),!n)return _.warn("[".concat(t.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(t))return _.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!Oe().supportSetRtpSenderParameters)return _.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const o={},s={};switch(t._optimizationMode){case"motion":o.degradationPreference="maintain-framerate";break;case"detail":o.degradationPreference="maintain-resolution";break;case"balanced":o.degradationPreference="balanced"}const a=vU(this.peerConnection,t._mediaStreamTrack),c=LN(t);if(s2(t)&&a&&n&&c&&this.getLocalVideoStats&&x(i=["vp8","vp9"]).call(i,this.store.codec)){var d;const m=o.degradationPreference||(x(d=t._hints).call(d,$e.CUSTOM_TRACK)?T("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");a2(this.id+a.mid,c,this,m,g=>{n&&this.updateAdaptation(n,g)},this.getLocalVideoStats.bind(this))}if(t._encoderConfig){var l;const{bitrateMax:m,frameRate:g,scaleResolutionDownBy:R}=t._encoderConfig;m&&(s.maxBitrate=1e3*m),(x(l=t._hints).call(l,$e.LOW_STREAM)||t.isUseScaleResolutionDownBy)&&(g&&(s.maxFramerate=mi(g)),R&&R>=1&&(s.scaleResolutionDownBy=R))}const{maxFramerate:h}=T("ENCODER_CONFIG_LIMIT");if(h&&typeof h=="number"&&(s.maxFramerate=s.maxFramerate?Math.min(s.maxFramerate,h):h),T("DSCP_TYPE")&&Po()){var u;const m=T("DSCP_TYPE");x(u=["very-low","low","medium","high"]).call(u,m)&&(s.networkPriority=m)}const p=n.getParameters(),E=(r=p.encodings)===null||r===void 0?void 0:r[0];
186Rt()&&!E&&(o.encodings=[s]),E&&Object.assign(E,s),Object.assign(p,o),_.debug("[".concat(t.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(p.encodings))),await n.setParameters(p),await UU(this.store.codec,n,T("SVC_MODE"))}async updateAdaptation(t,n){var i,r;if(!t)return _.debug("[updateAdaptation] no rtpSender found");if(!Oe().supportSetRtpSenderParameters)return _.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const o={},{bitrateMax:s,frameRate:a,scaleResolutionDownBy:c}=n;s&&(o.maxBitrate=1e3*s),a&&(o.maxFramerate=mi(a)),c&&c>=1&&x(i=["vp8","vp9"]).call(i,this.store.codec)&&(o.scaleResolutionDownBy=c);const d=t.getParameters(),l=(r=d.encodings)===null||r===void 0?void 0:r[0];l&&Object.assign(l,o),Object.assign(d,{});try{await t.setParameters(d),_.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(d.encodings)))}catch(h){!("transport"in t)||t.transport&&t.transport.state==="connected"?this.peerConnectionState!=="connected"?_.debug("[updateAdaptation] peerConnection not connected}"):_.debug("[updateAdaptation] updateRtpSenderEncodings failed",h):_.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(t,n){try{if(!Oe().supportSetRtpSenderParameters||t.length!==n.length)return;for(let i=0;i<t.length;i++){const r=t[i],o=n[i];o instanceof pt&&!this.isVP8Simulcast(o)&&await this.updateRtpSenderEncodings(o,r.sender)}}catch{_.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(t,n,i){const r=ii(t);return n.forEach((o,s)=>{const a=i[s],c=r.mediaDescriptions.find(d=>d.attributes.mid===a);c&&(rc(c,o),dv(c,o,this.store.codec))}),as(r)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=t=>{var n;(n=this.onFirstAudioReceived)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstVideoReceived=t=>{var n;(n=this.onFirstVideoReceived)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstAudioDecoded=t=>{var n;(n=this.onFirstAudioDecoded)===null||n===void 0||n.call(this,t)},this.statsFilter.onFirstVideoDecoded=(t,n,i)=>{var r;(r=this.onFirstVideoDecoded)===null||r===void 0||r.call(this,t,n,i)},this.statsFilter.onSelectedLocalCandidateChanged=(t,n)=>{var i;(i=this.onSelectedLocalCandidateChanged)===null||i===void 0||i.call(this,t,n)},this.statsFilter.onSelectedRemoteCandidateChanged=(t,n)=>{var i;(i=this.onSelectedRemoteCandidateChanged)===null||i===void 0||i.call(this,t,n)},this.statsFilter.onFirstVideoDecodedTimeout=t=>{var n;(n=this.onFirstVideoDecodedTimeout)===null||n===void 0||n.call(this,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(t,n){if(t.length===n.length)for(let c=0;c<t.length;c++){var i,r,o,s,a;const d=t[c],l=n[c];if(l instanceof pt&&!x(i=l._hints).call(i,$e.LOW_STREAM)&&(r=l._encoderConfig)!==null&&r!==void 0&&r.bitrateMax&&((o=l._encoderConfig)===null||o===void 0?void 0:o.bitrateMax)>200&&(s=l._scalabilityMode)!==null&&s!==void 0&&s.numSpatialLayers&&((a=l._scalabilityMode)===null||a===void 0?void 0:a.numSpatialLayers)>1&&this.store.codec==="vp8"){const h={},u={high:1e3*(l._encoderConfig.bitrateMax-50),medium:5e4};h.encodings=[{rid:"m",active:!0,maxBitrate:u.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:u.high}];const p=d.sender.getParameters();await d.sender.setParameters(Object.assign(p,h))}}}
186async applySimulcastEncodings(t,n){if(!Rt()&&t.length===n.length)for(let i=0;i<t.length;i++){const r=n[i];if(r instanceof pt&&this.isVP8Simulcast(r)){const o=t[i],s={},a={high:1e3*(r._encoderConfig.bitrateMax-50),medium:5e4};s.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:a.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:a.medium,scaleResolutionDownBy:4}];const c=o.sender.getParameters();await o.sender.setParameters(Object.assign(c,s))}}}isVP8Simulcast(t){var n,i,r,o,s;return!!(t instanceof pt&&T("SIMULCAST")&&this.store.codec==="vp8"&&!x(n=t._hints).call(n,$e.LOW_STREAM)&&(i=t._encoderConfig)!==null&&i!==void 0&&i.bitrateMax&&((r=t._encoderConfig)===null||r===void 0?void 0:r.bitrateMax)>200&&(o=t._scalabilityMode)!==null&&o!==void 0&&o.numSpatialLayers&&((s=t._scalabilityMode)===null||s===void 0?void 0:s.numSpatialLayers)>1)}logSDPExchange(t,n,i,r){if(T("SDP_LOGGING"))return _.upload("[".concat(this.store.clientId,"] exchanging ").concat(i," ").concat(n," SDP during NVConnectionExtension.").concat(r,` 187`),t),n==="offer"?o=>{this.logSDPExchange(o,"answer",i==="local"?"remote":"local",r)}:void 0}async getRemoteSSRC(t){if(!this.remoteSDP)return;const n=this.remoteSDP.getSSRC(t);return n&&n.length!==0?n[0].ssrcId:void 0}setConfiguration(t){if(Oe().supportPCSetConfiguration){const n=rl.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}t.isPreallocation&&(this.isPreallocation=!0)}},H(xe.prototype,"updateRemoteRTPCapabilities",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"updateRemoteRTPCapabilities"),xe.prototype),H(xe.prototype,"connect",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"connect"),xe.prototype),H(xe.prototype,"updateRemoteConnect",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"updateRemoteConnect"),xe.prototype),H(xe.prototype,"createDataChannels",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"createDataChannels"),xe.prototype),H(xe.prototype,"receive",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"receive"),xe.prototype),H(xe.prototype,"batchReceive",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"batchReceive"),xe.prototype),H(xe.prototype,"stopReceiving",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"stopReceiving"),xe.prototype),H(xe.prototype,"muteRemote",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"muteRemote"),xe.prototype),H(xe.prototype,"unmuteRemote",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"unmuteRemote"),xe.prototype),H(xe.prototype,"muteLocal",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"muteLocal"),xe.prototype),H(xe.prototype,"unmuteLocal",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"unmuteLocal"),xe.prototype),H(xe.prototype,"close",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"close"),xe.prototype),H(xe.prototype,"updateEncoderConfig",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"updateEncoderConfig"),xe.prototype),H(xe.prototype,"updateSendParameters",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"updateSendParameters"),xe.prototype),H(xe.prototype,"replaceTrack",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"replaceTrack"),xe.prototype),H(xe.prototype,"updateAdaptation",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"updateAdaptation"),xe.prototype),H(xe.prototype,"getRemoteSSRC",[fi],Object.getOwnPropertyDescriptor(xe.prototype,"getRemoteSSRC"),xe.prototype),xe);function fi(e,t,n){const i=e[t];if(typeof i!="function")throw new Error("Cannot use mutex on object property.");return n.value=async function(){const r=this.mutex,o=await r.lock("From NVConnectionExtension.".concat(t));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return await i.apply(this,a)}finally{o()}},n}var ot;function mx(e){var t,n,i,r=2;for(typeof Symbol<"u"&&(n=lp,i=Symbol.iterator);r--;){if(n&&(t=e[n])!=null)return t.call(e);if(i&&(t=e[i])!=null)return new Lm(t.call(e));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}function Lm(e){function t(n){if(Object(n)!==n)return K.reject(new TypeError(n+" is not an object."));var i=n.done;return K.resolve(n.value).then(function(r){return{value:r,done:i}})}return Lm=function(n){this.s=n,this.n=n.next},Lm.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(n){var i=this.s.return;return i===void 0?K.resolve({value:n,done:!0}):t(i.apply(this.s,arguments))},throw:function(n){var i=this.s.return;return i===void 0?K.reject(n):t(i.apply(this.s,arguments))}},new Lm(e)}let Bte=(ot=class Bm extends o_{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get localCodecs(){return this._p2pConnection.localCodecs}constructor(t,n){super(t,n),S(this,"name","DataChannelConnection"),S(this,"store",void 0),S(this,"peerConnection",void 0),S(this,"cname",void 0),S(this,"mutex",new An("DataChannelConnection-mutex")),S(this,"dataChannel",void 0),S(this,"_p2pConnection",void 0),S(this,"establishPromise",void 0),S(this,"_nvMedia",void 0),this.store=n,this.store.dcId=this.store.dcId+1,this.peerConnection=new RTCPeerConnection(Bm.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}
187),this.dataChannel=this.peerConnection.createDataChannel("agora-signal",{ordered:!1,maxPacketLifeTime:50}),this.dataChannel.binaryType="arraybuffer",this._p2pConnection=new Fte(t,n,this.peerConnection),this.bindPCEvents(),this.establishPromise=this._p2pConnection.establishPromise}getPreMedia(t){var n;return(n=this._p2pConnection)===null||n===void 0?void 0:n.getPreMedia(t)}isPreSub(){var t,n;return(t=(n=this._p2pConnection)===null||n===void 0?void 0:n.isPreSub())!==null&&t!==void 0&&t}async establish(){return await this._p2pConnection.establish()}getP2PConnectionParams(){return this._p2pConnection.establishPromise}updateRtpSenderEncodings(t){return this._p2pConnection.updateRtpSenderEncodings(t)}async connect(t){return this.cname=t.cname,await this._p2pConnection.connect(t),await new K((n,i)=>{const r=setTimeout(()=>{this.closeSignal(),i(new D(A.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(t.candidates))))},T("DC_CONNECTION_TIMEOUT"));this.dataChannel.onopen=()=>{if(this.dataChannel.readyState==="open")return clearTimeout(r),void n()},this.dataChannel.onerror=o=>{this.closeSignal(),i(o)},this.dataChannel.addEventListener("close",()=>{i(new D(A.DATACHANNEL_CONNECTION_TIMEOUT))})}),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}checkDtlsParameters(t){return this._p2pConnection.checkDtlsParameters(t)}checkIceParameters(t){return this._p2pConnection.checkIceParameters(t)}async updateRemoteRTPCapabilities(t,n){return this._p2pConnection.updateRemoteRTPCapabilities(t,n)}send(t,n,i){var r=this;return di(function*(){const o=yield ve(r.mutex.lock("From DataChannelConnection.send"));try{return yield*$c(mx(r._p2pConnection.send(t,n,i)))}finally{o()}})()}async stopSending(t,n){return this._p2pConnection.stopSending(t,n)}async createDataChannels(t,n){return this._p2pConnection.createDataChannels(t,n)}
187async stopDataChannels(t){return this._p2pConnection.stopDataChannels(t)}async receive(t,n,i,r){return this._nvMedia?(_.debug("[DataChannelConnection] receive ".concat(t," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(t,n,this.cname)):(_.debug("[DataChannelConnection] receive ".concat(t," by WebRTC.")),await this._p2pConnection.receive(t,n,i,r))}async batchReceive(t){return[...await this._p2pConnection.batchReceive(t)]}async stopReceiving(t){return await this._p2pConnection.stopReceiving(t)}async muteRemote(t){return await this._p2pConnection.muteRemote(t)}async unmuteRemote(t){return await this._p2pConnection.unmuteRemote(t)}async muteLocal(t){return await this._p2pConnection.muteLocal(t)}async unmuteLocal(t){return await this._p2pConnection.unmuteLocal(t)}restartICE(t){var n=this;return di(function*(){return yield*$c(mx(n._p2pConnection.restartICE(t)))})()}close(){var t;(t=this._nvMedia)===null||t===void 0||t.close(),this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection)}getStats(){return this._p2pConnection.getStats()}getRemoteVideoIsReady(t){return this._p2pConnection.getRemoteVideoIsReady(t)}updateRemoteConnect(t){var n;return(n=this._nvMedia)===null||n===void 0||n.setRemoteRtpCapabilities(t),this._p2pConnection.updateRemoteConnect(t)}async updateEncoderConfig(t,n){return await this._p2pConnection.updateEncoderConfig(t,n)}async updateSendParameters(t,n){return await this._p2pConnection.updateSendParameters(t,n)}setStatsRemoteVideoIsReady(t,n){this._p2pConnection.setStatsRemoteVideoIsReady(t,n)}async replaceTrack(t,n){return await this._p2pConnection.replaceTrack(t,n)}async getRemoteSSRC(t){return this._p2pConnection.getRemoteSSRC(t)}logSDPExchange(t,n,i,r){if(T("SDP_LOGGING"))return _.upload("exchanging ".concat(i," ").concat(n," SDP during DataChannelConnection.").concat(r,` 188`),t),n==="offer"?o=>{this.logSDPExchange(o,"answer",i==="local"?"remote":"local",r)}:void 0}static resolvePCConfiguration(t){const n={iceServers:[]};return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&t.turnServer.mode!=="off"&&(wa(t.turnServer.servers)?n.iceServers=t.turnServer.servers:(n.iceServers&&n.iceServers.push(...Bm.turnServerConfigToIceServers(t.turnServer.servers)),T("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...Bm.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),T("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach(i=>{i.forceturn&&(n.iceTransportPolicy="relay")}))),T("ENABLE_ENCODED_TRANSFORM")&&Oe().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}static turnServerConfigToIceServers(t){const n=[];return t.forEach(i=>{i.security?i.tcpport&&n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turns:".concat(qr(i.turnServerURL),":").concat(i.tcpport,"?transport=tcp")}):(i.udpport&&!T("FORCE_TURN_TCP")&&n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":").concat(i.udpport,"?transport=udp")}),i.tcpport&&n.push({username:i.username,credential:i.password,credentialType:"password",urls:"turn:".concat(i.turnServerURL,":").concat(i.tcpport,"?transport=tcp")}))}),n}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=t=>{var n;return(n=this.onICEConnectionStateChange)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onConnectionStateChange=t=>{var n;return(n=this.onConnectionStateChange)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onDTLSTransportStateChange=t=>{var n;return(n=this.onDTLSTransportStateChange)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onDTLSTransportError=t=>{var n;return(n=this.onDTLSTransportError)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onICETransportStateChange=t=>{var n;return(n=this.onICETransportStateChange)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstAudioReceived=t=>{var n;return(n=this.onFirstAudioReceived)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstVideoReceived=t=>{var n;return(n=this.onFirstVideoReceived)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstAudioDecoded=t=>{var n;return(n=this.onFirstAudioDecoded)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstVideoRender=t=>{var n;return(n=this.onFirstVideoRender)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstVideoBufferReady=t=>{var n;return(n=this.onFirstVideoBufferReady)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onFirstVideoDecoded=(t,n,i)=>{var r;return(r=this.onFirstVideoDecoded)===null||r===void 0?void 0:r.call(this,t,n,i)},this._p2pConnection.onFirstVideoDecodedTimeout=t=>{var n;return(n=this.onFirstVideoDecodedTimeout)===null||n===void 0?void 0:n.call(this,t)},this._p2pConnection.onSelectedLocalCandidateChanged=(t,n)=>{var i;return(i=this.onSelectedLocalCandidateChanged)===null||i===void 0?void 0:i.call(this,t,n)},this._p2pConnection.onSelectedRemoteCandidateChanged=(t,n)=>{var i;return(i=this.onSelectedRemoteCandidateChanged)===null||i===void 0?void 0:i.call(this,t,n)}}closeSignal(){this.dataChannel.close(),this.peerConnection.close()}unbindConnectionEvents(t){t.onConnectionStateChange=void 0,t.onICEConnectionStateChange=void 0,t.onICETransportStateChange=void 0,t.onDTLSTransportStateChange=void 0,t.onDTLSTransportError=void 0,t.onFirstAudioDecoded=void 0,t.onFirstAudioReceived=void 0,t.onFirstVideoDecoded=void 0,t.onFirstVideoReceived=void 0,t.onSelectedLocalCandidateChanged=void 0,t.onSelectedRemoteCandidateChanged=void 0,t.onFirstVideoDecodedTimeout=void 0}setConfiguration(t){this._p2pConnection.setConfiguration(t)}},H(ot.prototype,"connect",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"connect"),ot.prototype),H(ot.prototype,"updateRemoteRTPCapabilities",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"updateRemoteRTPCapabilities"),ot.prototype),H(ot.prototype,"createDataChannels",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"createDataChannels"),ot.prototype),H(ot.prototype,"receive",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"receive"),ot.prototype),H(ot.prototype,"stopReceiving",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"stopReceiving"),ot.prototype),H(ot.prototype,"muteRemote",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"muteRemote"),ot.prototype),H(ot.prototype,"unmuteRemote",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"unmuteRemote"),ot.prototype),H(ot.prototype,"muteLocal",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"muteLocal"),ot.prototype),H(ot.prototype,"unmuteLocal",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"unmuteLocal"),ot.prototype),H(ot.prototype,"close",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"close"),ot.prototype),H(ot.prototype,"updateEncoderConfig",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"updateEncoderConfig"),ot.prototype),H(ot.prototype,"updateSendParameters",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"updateSendParameters"),ot.prototype),H(ot.prototype,"replaceTrack",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"replaceTrack"),ot.prototype),H(ot.prototype,"getRemoteSSRC",[sr],Object.getOwnPropertyDescriptor(ot.prototype,"getRemoteSSRC"),ot.prototype),ot);function sr(e,t,n){const i=e[t];if(typeof i!="function")throw new Error("Cannot use mutex on object property.");return n.value=async function(){const r=this.mutex,o=await r.lock("From DataChannelConnection.".concat(t));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return await i.apply(this,a)}finally{o()}},n}function Ex(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}class Gte extends Nt{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(t){var n;x(n=["tryNext","recover"]).call(n,t)&&this.resetReconnectCount(t),this._reconnectMode=t}get state(){return this._state}set state(t){t!==this._state&&(this._state=t,this._state==="reconnecting"?this.emit
188(hn.RECONNECTING,this.reconnectReason):this._state==="connected"?this.emit(hn.CONNECTED):this._state==="closed"?this.emit(hn.CLOSED):this._state==="failed"&&this.emit(hn.FAILED))}constructor(t,n,i,r){super(),S(this,"connectionID",0),S(this,"currentURLIndex",0),S(this,"reconnectReason",void 0),S(this,"_reconnectMode","tryNext"),S(this,"_initMutex",void 0),S(this,"_name",void 0),S(this,"_state","closed"),S(this,"_reconnectInterrupter",void 0),S(this,"_url",void 0),S(this,"_retryConfig",void 0),S(this,"_reconnectCount",0),S(this,"_forceCloseTimeout",5e3),S(this,"_onlineReconnectListener",void 0),S(this,"_closeEstablishingTransmitter",()=>{}),S(this,"_store",void 0),S(this,"_joinChannelServiceRecordIndex",void 0),S(this,"_transmitter",void 0),S(this,"_useCompress",void 0),S(this,"_inflateLength",0),S(this,"_deflateLength",0),this._store=r,this._name=t,this._retryConfig=function(o){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?Ex(Object(a),!0).forEach(function(c){S(o,c,a[c])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(a)):Ex(Object(a)).forEach(function(c){Object.defineProperty(o,c,Object.getOwnPropertyDescriptor(a,c))})}return o}({},n),this._useCompress=i}resetReconnectCount(t){_.debug("".concat(this._name," reset reconnect count, reason: ").concat(t)),this._reconnectCount=0}close(t,n){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this._reconnectInterrupter&&this._reconnectInterrupter(),this._transmitter){this._transmitter.onclose=null,this._transmitter.onopen=null,this._transmitter.onmessage=null;const i=this._transmitter;n?setTimeout(()=>i.close(),500):i.close(),this._transmitter=void 0}this.state=t?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter()}reconnect(t,n){if(!this._transmitter)return void _.warning("[".concat(this._name,"] can not reconnect, no websocket"));var i;t!==void 0&&(this.reconnectMode=t),_.debug("[".concat(this._name,"] reconnect is triggered initiative")),typeof this._joinChannelServiceRecordIndex=="number"&&((i=this._store)===null||i===void 0||i.recordJoinChannelService({status:"error",errors:[new Error(n)]},this._joinChannelServiceRecordIndex));const r=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),r&&r.bind(this._transmitter)({code:9999,reason:n})}getInflateData(){const t=this._inflateLength,n=this._deflateLength;return this.clearInflateData(),{inflateLength:t,deflateLength:n}}setInflateData(t){this._deflateLength=this._deflateLength+t.originLength,this._inflateLength=this._inflateLength+t.compressedLength}clearInflateData(){this._inflateLength=0,this._deflateLength=0}}let Co=function(e){return e[e.Default=0]="Default",e[e.Ack=1]="Ack",e}({});class jte{constructor(t,n,i){S(this,"version",1),S(this,"initialRTO",void 0),S(this,"maxBatchAckCount",void 0),S(this,"maxRTO",void 0),S(this,"initialRTT",void 0),S(this,"ID",void 0),S(this,"rtt",void 0),S(this,"packetNumber",1),S(this,"rtoRatioMap",new Map),S(this,"timeoutMap",new Map),S(this,"unorderedPacketQueue",[]),S(this,"batchAckPacketQueue",[]),S(this,"lastOrderedPacketNumber",0),S(this,"batchAckTimer",void 0),S(this,"sendImpl",void 0),S(this,"receiveImpl",void 0),this.sendImpl=t,this.receiveImpl=n,this.ID=Qe(7,"transmitter-"),this.initialRTO=(i==null?void 0:i.initialRTO)!==void 0?i.initialRTO:T("TRANSMITTER_INITIAL_RTO"),this.initialRTT=(i==null?void 0:i.initialRTT)!==void 0?i.initialRTT:T("TRANSMITTER_INITIAL_RTT"),this.rtt=(i==null?void 0:i.initialRTT)!==void 0?i.initialRTT:T("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=(i==null?void 0:i.maxBatchAckCount)!==void 0?i.maxBatchAckCount:T("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=(i==null?void 0:i.maxRTO)!==void 0?i.maxRTO:T("TRANSMITTER_MAX_RTO")}packetize(t,n){return{type:Co.Default,version:this.version,packetNumber:n,payload:t}}serialize(t){switch(t.type){case Co.Default:{let n;typeof t.payload=="string"?n=new TextEncoder().encode(t.payload):n=t.payload;const i=new ArrayBuffer(n.length+15),r=new DataView(i);return r.setUint16(0,t.version),r.setUint8(2,t.type),r.setUint32(3,t.packetNumber),gO(r,7,BigInt(t.sendTs)),new Uint8Array(r.buffer).set(n,15),i}case Co.Ack:{const n=new ArrayBuffer(16),i=new DataView(n);return i.setUint16(0,t.version),i.setUint8(2,t.type),i.setUint32(3,t.maxAckPacketNumber),i.setUint8(7,t.shift),gO(i,8,BigInt(t.ackSendTs)),n}}}deserialize(t){const n=new DataView(t),i=n.getUint16(0),r=n.getUint8(2);switch(r){case Co.Default:{const o=n.getUint32(3),s=fO(n,7),a=t.slice(15),c=new Uint8Array(a);return{version:i,type:r,packetNumber:o,sendTs:Number(s),payload:c}}case Co.Ack:{const o=n.getUint32(3),s=n.getUint8(7),a=fO(n,8);return{version:i,type:r,maxAckPacketNumber:o,shift:s,ackSendTs:Number(a)}}default:throw _.error("[".concat(this.ID,"] Unrecognized packet type ").concat(r)),new Error("Unrecognized packet type ".concat(r))}}sendMessage(t){T("DC_DEBUG_LOG")&&typeof t=="string"&&_.debug("[".concat(this.ID,"] sending message packet"),JSON.parse(t));const n=this.packetize(t,this.packetNumber);this.packetNumber=this.packetNumber===4294967295?1:this.packetNumber+1;const i=this.calculateRTO(n),r=window.setTimeout(()=>{this.resendMessage(n)},i);this.timeoutMap.set(n.packetNumber,r),this.sendPacket(n)}onData(t){const n=this.deserialize(t);n.type===Co.Default?this.ack(n):n.type===Co.Ack&&(this.updateRTT(n,Math.round(performance.now())),this.clearRTO(n))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEac
188h(t=>{let[n,i]=t;window.clearTimeout(i)}),this.timeoutMap=new Map,this.rtoRatioMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,this.batchAckTimer!==void 0&&window.clearTimeout(this.batchAckTimer)}resendMessage(t){const n=this.calculateRTO(t),i=window.setTimeout(()=>{T("DC_DEBUG_LOG")&&typeof t.payload=="string"&&_.debug("[".concat(this.ID,"] resending message packet"),JSON.parse(t.payload),"timeout: ".concat(n)),this.resendMessage(t)},n);this.timeoutMap.set(t.packetNumber,i),this.sendPacket(t)}calculateRTO(t){const n=this.rtoRatioMap.get(t.packetNumber);if(n===void 0)return this.rtoRatioMap.set(t.packetNumber,1),this.initialRTO;{const i=9*this.rtt/8*n;return this.rtoRatioMap.set(t.packetNumber,n+1),i>this.maxRTO?this.maxRTO:i}}updateRTT(t,n){const i=t.ackSendTs;this.rtt=this.rtt*(7/8)+(n-i-this.rtt)/8}ack(t){if(t.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(t):(this.batchAckPacketQueue.push(t),this.batchAckTimer=window.setTimeout(()=>{this.batchAck()},this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(t.payload);;){const n=this.unorderedPacketQueue[0];if(!n){this.unorderedPacketQueue.shift();break}this.batchAckTimer&&this.batchAck(),this.receiveImpl(n.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1}else if(t.packetNumber<=this.lastOrderedPacketNumber){const n={ackSendTs:t.sendTs,maxAckPacketNumber:t.packetNumber,shift:0,type:Co.Ack,version:this.version};T("DC_DEBUG_LOG")&&_.debug("[".concat(this.ID,"] sending ack packet"),n,"packetNumber: ".concat(t.packetNumber)),this.sendPacket(n)}else if(t.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[t.packetNumber-this.lastOrderedPacketNumber-2]=t;const n={ackSendTs:t.sendTs,maxAckPacketNumber:t.packetNumber,shift:0,type:Co.Ack,version:this.version};T("DC_DEBUG_LOG")&&_.debug("[".concat(this.ID,"] sending ack packet"),n,"packetNumber: ".concat(t.packetNumber)),this.sendPacket(n)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const t={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:Co.Ack,version:this.version};T("DC_DEBUG_LOG")&&_.debug("[".concat(this.ID,"] sending batch ack packet"),t,"shift: ".concat(this.batchAckPacketQueue.length-1)),this.sendPacket(t),this.batchAckPacketQueue=[]}sendPacket(t){t.type===Co.Default&&(t.sendTs=Math.round(performance.now()));const n=this.serialize(t);this.sendImpl(n)}clearRTO(t){for(let n=t.maxAckPacketNumber-t.shift;n<=t.maxAckPacketNumber;n++){const i=this.timeoutMap.get(n);i!==void 0&&window.clearTimeout(i),this.timeoutMap.delete(n),this.rtoRatioMap.delete(n)}}}class fx extends Gte{constructor(t,n){super(t,n,arguments.length>2&&arguments[2]!==void 0&&arguments[2],arguments.length>3?arguments[3]:void 0),S(this,"_initMutex",void 0),S(this,"_reconnectInterrupter",void 0),S(this,"_url",void 0),S(this,"_transmitter",void 0),S(this,"_addresses",void 0),S(this,"_reliableTransmission",void 0),S(this,"_textEncoder",void 0),S(this,"_textDecoder",void 0),this._textEncoder=new TextEncoder,this._textDecoder=new TextDecoder,this._initMutex=new An("datachannel");const{timeout:i,timeoutFactor:r}=n,o=Math.max(300,Math.floor(3*i/5)),s=Math.max(1.2,Math.floor(8*r)/10);Jn.ONLINE&&(this._retryConfig.timeout=o,this._retryConfig.timeoutFactor=s),At.on(Oa.NETWORK_STATE_CHANGE,(a,c)=>{a!==c&&(this.resetReconnectCount("network state change: ".concat(c," -> ").concat(a)),a===Jn.ONLINE?(this._retryConfig.timeout=o,this._retryConfig.timeoutFactor=s):(this._retryConfig.timeout=i,this._retryConfig.timeoutFactor=r))})}getConnection(){if(this._reliableTransmission)return this._reliableTransmission}async init(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;this._forceCloseTimeout=n;const i=(r,o)=>{this._addresses=t,this.currentURLIndex=this._addresses.findIndex(a=>a.fingerprint||T("FINGERPRINT"));const s=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(s).then(r).catch(o),this.once(hn.CLOSED,()=>o(new D(A.WS_DISCONNECT))),this.once(hn.CONNECTED,()=>r())};return this._initMutex.lock().then(r=>new K((o,s)=>{i(o,s)}).then(()=>{r()}).catch(()=>{r()}))}async sendMessage(t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new D(A.WS_ABORT,"datachannel is not ready");try{n||(t=JSON.stringify(t));const i=this._textEncoder.encode(t),r=PL(i,{raw:!0});this._reliableTransmission.sendMessage(r)}catch(i){throw new D(A.WS_ERR,"send datachannel signal message error"+i.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(t){const n=JSON.stringify(t);return{compressed:n,compressedLength:n.length,origin:t}}sendMessageWithUint8Array(t){return{compressed:t,compressedLength:t.byteLength,origin:t}}createTransmitterConnection(t){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(t.ip,":").concat(t.port),new K((n,i)=>{var r;const o=()=>{_.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="recover",this.state="connected",this.resetReconnectCount("opened"),n()},s=async l=>{var h;if((h=this._closeEstablishingTransmitter)===null||h===void 0||h.call(this),_.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat(l.code,", reason: ").concat(l.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount<this._retryConfig.maxRetryCount){this.state==="connected"&&(this.reconnectReason=l.reason,this.state="reconnecting");const u=Ui(this,hn.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,p=await this.reconnectWithAction(u);if(this.state==="closed")return void _.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!p)return i(new D(A.WS_DISCONNECT,"datachannel reconnect failed: ".concat(l.code))),void this.close(!0);n()}else i(new D(A.WS_DISCONNECT,"datachannel close: ".concat(l.code))),this.close()},a=async l=>{try{var h;(h=this._reliableTransmission)===null||h===void 0||h.onData(l.data)}catch(u){console.log(u)}};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),_.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(t)));const c=(r=this._store)===null||r===void 0?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),d=Date.now();Jt(this,hn.TO_CONNECT_DATACHANNEL).then(l=>{var h,u;if(!l)throw new Error("transmissonInfo not exist yet");const{transmitter:p,close:E}=l;this._transmitter=p,(h=this._store)===null||h===void 0||h.signalChannelOpen();const m=Date.now()-d;_.debug("[choose dc] dc open cost ".concat(m,"ms")),this._reliableTransmission=new jte(g=>{var R;this._transmitter&&this._transmitter.readyState==="open"&&((R=this._transmitter)===null||R===void 0||R.send(g))},g=>
188{if(typeof g=="string")this.emit(hn.ON_MESSAGE,g);else{const R=yT(g,{raw:!0}).buffer,v=this._textDecoder.decode(R);this.emit(hn.ON_MESSAGE,v)}}),this._closeEstablishingTransmitter=()=>{var g;(g=this._reliableTransmission)===null||g===void 0||g.close(),this._reliableTransmission=void 0,E()},o&&o(),p.onclose=s,p.onmessage=a,(u=this._store)===null||u===void 0||u.recordJoinChannelService({endTs:Date.now(),status:"success"},c),this._joinChannelServiceRecordIndex=c}).catch(l=>{var h;if((h=this._store)===null||h===void 0||h.recordJoinChannelService({endTs:Date.now(),status:l instanceof D&&l.code===A.WS_ABORT?"aborted":"error",errors:[l]},c),this.state!=="closed"){if(l instanceof D&&l.code===A.WS_ERR){const u=new D(A.WS_ERR,"init datachannel failed! Error: ".concat(l.toString()));return _.error("[".concat(this._name,"]").concat(u)),void i(u)}s&&s(l)}else i(new D(A.WS_DISCONNECT,"datachannel is closed: ".concat(l.toString())))})})}async reconnectWithAction(t){let n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount||!this._addresses||this.state==="closed")return!1;this._onlineReconnectListener||At.networkState!==Jn.OFFLINE||(this._onlineReconnectListener=At.onlineWaiter&&At.onlineWaiter.then(()=>{this._onlineReconnectListener=void 0}));let i=!0;if(this._reconnectInterrupter=()=>{i=!1},n){const a=Ip(this._reconnectCount,this._retryConfig);_.debug("[".concat(this._name,"] wait ").concat(a,"ms to reconnect datachannel, mode: ").concat(t)),await K.race([ln(a),this._onlineReconnectListener||new K(()=>{})])}if(this.state==="closed"||!i)return!1;this._reconnectCount+=1;const r=async(a,c)=>{this.emit(hn.RECONNECT_CREATE_CONNECTION,c),await this.createTransmitterConnection(a)};try{if(t==="retry"){const a=this._addresses[this.currentURLIndex];await r(a,t)}else if(t==="tryNext"){this.currentURLIndex+=1;for(let c=this.currentURLIndex;c<this._addresses.length;c++){if(this._addresses[c].fingerprint||T("FINGERPRINT")){this.currentURLIndex=c;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return _.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);_.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const a=this._addresses[this.currentURLIndex];await r(a,t)}else t==="recover"&&(_.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(hn.FAILBACK));return!0}catch(a){var o,s;return _.error("[".concat(this._name,"] reconnect failed"),a.toString()),a!=null&&(o=a.data)!==null&&o!==void 0&&o.desc&&Array.isArray(a.data.desc)&&a.data.desc.length&&x(s=a.data.desc).call(s,"dynamic key expired")?(this.emit(hn.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(t,n)}}}class Wte extends Nt{get connectionState(){return this._connectionState}set connectionState(t){t!==this._connectionState&&(this._connectionState=t,t===Le.CONNECTED?this.emit(ee.WS_CONNECTED):t===Le.RECONNECTING?this.emit(ee.WS_RECONNECTING,this._websocketReconnectReason):t===Le.CLOSED&&this.emit(ee.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket?this.websocket.url:null}get rtt(){return this.rttRolling.mean()}processPendingNotifications(){this.pendingNotifications.length!==0&&(_.debug("[".concat(this.clientId,"] processing ").concat(this.pendingNotifications.length," pending notifications")),this.pendingNotifications.forEach(t=>{let{type:n,message:i}=t;this.emit(n,i),n===he.ON_NOTIFICATION&&this.handleNotification(i),n===he.ON_USER_BANNED&&this.handleUserBanned(i)}),this.pendingNotifications=[])}handleUserBanned(t){switch(t.error_code){case 14:this.close(Pe.UID_BANNED);break;case 15:this.close(Pe.IP_BANNED);break;case 16:this.close(Pe.CHANNEL_BANNED)}}constructor(t,n){super(),S(this,"__name__","DataChannelSignal"),S(this,"_disconnectedReason",void 0),S(this,"_websocketReconnectReason",void 0),S(this,"_connectionState",Le.CLOSED),S(this,"reconnectToken",void 0),S(this,"websocket",void 0),S(this,"openConnectionTime",void 0),S(this,"clientId",void 0),S(this,"lastMsgTime",Date.now()),S(this,"uploadCache",[]),S(this,"uploadCacheInterval",void 0),S(this,"rttRolling",new aS(5)),S(this,"pingpongTimer",void 0),S(this,"inflateDataTimer",void 0),S(this,"pingpongTimeoutCount",0),S(this,"ortc",void 0),S(this,"joinResponse",void 0),S(this,"multiIpOption",void 0),S(this,"initError",void 0),S(this,"spec",void 0),S(this,"store",void 0),S(this,"isJoining",!1),S(this,"pendingNotifications",[]),S(this,"onWebsocketMessage",i=>
188{if(i instanceof ArrayBuffer)return void this.emit(ee.ON_BINARY_DATA,i);const r=JSON.parse(i);if(T("DC_DEBUG_LOG")&&_.debug("[datachannel-signal] received packet",r),this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(r,"_id")){const o="res-@".concat(r._id);this.emit(o,r._result,r._message)}else Object.prototype.hasOwnProperty.call(r,"_type")&&(this.isJoining?r._type===he.ON_NOTIFICATION||r._type===he.ON_USER_BANNED?(this.emit(r._type,r._message),r._type===he.ON_NOTIFICATION&&this.handleNotification(r._message),r._type===he.ON_USER_BANNED&&this.handleUserBanned(r._message)):(this.pendingNotifications.push({type:r._type,message:r._message}),_.debug("[".concat(this.clientId,"] cached notification during join: ").concat(r._type))):(this.emit(r._type,r._message),r._type===he.ON_NOTIFICATION&&this.handleNotification(r._message),r._type===he.ON_USER_BANNED&&this.handleUserBanned(r._message)))}),this.clientId=t.clientId,this.spec=t,this.store=n,this.websocket=new fx("gateway-".concat(this.clientId),this.spec.retryConfig,!0,n),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===Le.CONNECTED&&this.reconnect("retry",Bs.OFFLINE)})}async request(t,n,i,r){const o=Qe(6,""),s={_id:o,_type:t,_message:n},a=this.websocket.connectionID,c=()=>new K((E,m)=>{if(this.connectionState===Le.CONNECTED)return E();const g=()=>{this.off(ee.WS_CLOSED,R),E()},R=()=>{this.off(ee.WS_CONNECTED,g),m(new D(A.WS_ABORT))};this.once(ee.WS_CONNECTED,g),this.once(ee.WS_CLOSED,R),t!==ie.PUBLISH&&t!==ie.SUBSCRIBE&&t!==ie.UNSUBSCRIBE&&t!==ie.UNPUBLISH&&t!==ie.CONTROL&&t!==ie.RESTART_ICE||this.once(ee.DISCONNECT_P2P,()=>{m(new D(A.DISCONNECT_P2P))}),t!==ie.PUBLISH&&t!==ie.RESTART_ICE||this.once(ee.ABORT_P2P_EXECUTION,()=>{m(new D(A.DISCONNECT_P2P))})});if(this.connectionState!==Le.CONNECTING&&this.connectionState!==Le.RECONNECTING||t===ie.JOIN||t===ie.REJOIN||await c(),t===ie.LEAVE&&(this.websocket.unbindDcCloseEventListener(),r=!0),T("DC_DEBUG_LOG")&&_.debug("[datachannel-signal] sendMessage",s),await this.websocket.sendMessage(s,!0,!1),r)return;const d=new K((E,m)=>{let g=!1;const R=(C,w)=>{g=!0,E({isSuccess:C==="success",message:w||{}}),this.off(ee.WS_CLOSED,v),this.off(ee.WS_RECONNECTING,v),this.emit(ee.REQUEST_SUCCESS,t,n)};this.once("res-@".concat(o),R);const v=()=>{m(new D(A.WS_ABORT,"type: ".concat(t))),this.off(ee.WS_CLOSED,v),this.off(ee.WS_RECONNECTING,v),this.off("res-@".concat(o),R)};this.once(ee.WS_CLOSED,v),this.once(ee.WS_RECONNECTING,v),ln(T("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==a||g||(_.warning("dc request timeout, type: ".concat(t)),this.emit(ee.REQUEST_TIMEOUT,t,n))})});let l=null;try{l=await d}catch(E){if(this.connectionState===Le.CLOSED||t===ie.LEAVE)throw new D(A.WS_ABORT);return!this.spec.forceWaitGatewayResponse||i?E.throw():t===ie.JOIN||t===ie.REJOIN?null:(await c(),await this.request(t,n))}if(l.isSuccess)return l.message;const h=Number(l.message.error_code||l.message.code),u=Ha(h),p=new D(A.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(l.message.error_str),{code:h,data:l.message});return u.action==="success"?l.message:(_.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(t,", error_code: ").concat(h,", message: ").concat(u.desc,", action: ").concat(u.action)),h===ce.ERR_TOO_MANY_BROADCASTERS?((t===ie.JOIN||t===ie.REJOIN)&&(this.initError=p,this.close()),p.throw()):u.action==="failed"?p.throw():u.action==="quit"?(this.initError=p,this.close(),p.throw()):(h===ce.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=l.message.option,_.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Bs.MULTI_IP)):this.reconnect(u.action,Bs.SERVER_ERROR),t===ie.JOIN||t===ie.REJOIN?null:await this.request(t,n)))}waitMessage(t,n){return new K(i=>{const r=o=>{(!n||n(o))&&(this.off(t,r),i(o))};this.on(t,r)})}uploadWRTCStats(t){if(!this.store.sessionId)return void _.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const n={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:t};this.upload(Ka.WRTC_STATS,n)}upload(t,n){const i={_type:t,_message:n};try{this.websocket.sendMessage(i)}catch{const r=T("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(i),this.uploadCache.length>r&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==Le.CONNECTED)return;const o=this.uploadCache.splice(0,1)[0];this.uploadCache.length===0&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(o._type,o._message)},T("UPLOAD_CACHE_INTERVAL")||2e3))}}async send(t,n){const i={_type:t,_message:n};await this.websocket.sendMessage(i)}init(t){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new K((n,i)=>{this.once(ee.WS_CONNECTED,()=>n(this.joinResponse)),this.once(ee.WS_CLOSED,()=>i(this.initError||new D(A.WS_ABORT))),this.connectionState=Le.CONNECTING,this.websocket.init(t).catch(i),this.websocket.once(hn.FAILBACK,()=>{i(new D(A.INIT_DATACHANNEL_TIMEOUT))}),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval(()=>{this.handleInflateData()},2e4),setTimeout(()=>{this.openConnectionTime===void 0&&(_.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),i(new D(A.INIT_DATACHANNEL_TIMEOUT)))},T("DC_JOIN_WITH_FAILBACK"))})}close(t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this.isJoining=!1,this.pendingNotifications=[],this._disconnectedReason=t||Pe.LEAVE,this.connectionState=Le.CLOSED,_.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),t===Pe.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new fx("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),T("DC_PINGPONG_INTERVAL")),!this.joinResponse){this.emit
188(ee.ABORT_P2P_EXECUTION),this.store.signalConnected();const t=await Jt(this,ee.REQUEST_JOIN_INFO);this.store.joinReq();let n=await Jt(this,ee.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE);if(this.isJoining=!0,this.pendingNotifications=[],n){_.debug("join response from pre join response");const i=await this.request(ie.JOIN,t);i&&"ortc"in i&&(n=i)}else _.debug("join response from request join_v3"),n=await this.request(ie.JOIN,t);if(this.store.joinRep(),this.ortc=t==null?void 0:t.ortc,!n)return this.emit(ee.REPORT_JOIN_GATEWAY,A.TIMEOUT,this.url||""),!1;this.joinResponse=n,this.emit(ee.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Le.CONNECTED,this.isJoining=!1,this.processPendingNotifications(),!0}async rejoin(){if(!this.reconnectToken)throw new D(A.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const t=Na(this,ee.REQUEST_REJOIN_INFO);t.token=this.reconnectToken;const n=await this.request(ie.REJOIN,t);return!!n&&(this.connectionState=Le.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),T("DC_PINGPONG_INTERVAL")),n.peers&&n.peers.forEach(i=>{this.emit(he.ON_USER_ONLINE,{uid:i.uid}),i.audio&&this.emit(he.ON_ADD_AUDIO_STREAM,{uid:i.uid,uint_id:i.uint_id,audio:!0,ssrcId:i.audio_ssrc}),i.video&&this.emit(he.ON_ADD_VIDEO_STREAM,{uid:i.uid,uint_id:i.uint_id,video:!0,ssrcId:i.video_ssrc}),i.audio_mute?this.emit(he.MUTE_AUDIO,{uid:i.uid}):this.emit(he.UNMUTE_AUDIO,{uid:i.uid}),i.video_mute?this.emit(he.MUTE_VIDEO,{uid:i.uid}):this.emit(he.UNMUTE_VIDEO,{uid:i.uid}),i.audio_enable_local?this.emit(he.ENABLE_LOCAL_AUDIO,{uid:i.uid}):this.emit(he.DISABLE_LOCAL_AUDIO,{uid:i.uid}),i.video_enable_local?this.emit(he.ENABLE_LOCAL_VIDEO,{uid:i.uid}):this.emit(he.DISABLE_LOCAL_VIDEO,{uid:i.uid}),i.audio||i.video||this.emit(he.ON_REMOVE_STREAM,{uid:i.uid,uint_id:i.uint_id})}),!0)}reconnect(t,n){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(t,n)}async downgradeCodec(t){if(!this.ortc)return!1;const n={downgrade_codec:t,ortc:this.ortc};return!!await this.request(ie.DOWNGRADE_CODEC,n)}handleNotification(t){_.debug("[".concat(this.clientId,"] receive notification: "),t);const n=Ha(t.code);if(n.action!=="success"){if(n.action!=="failed")return n.action==="quit"?(n.desc==="ERR_REPEAT_JOIN_CHANNEL"&&this.close(Pe.UID_BANNED),void this.close()):void this.reconnect(n.action,Bs.SERVER_ERROR);_.error("[".concat(this.clientId,"] ignore error: "),n.desc)}}handlePingPong(){if(!this.websocket||this.websocket.state!=="connected")return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1,T("DC_DEBUG_LOG")&&console.debug("[datachannel-signal] pingpongTimeoutCount: ".concat(this.pingpongTimeoutCount));const t=T("PING_PONG_TIME_OUT"),n=Date.now();this.pingpongTimeoutCount>=t&&(_.warning("[datachannel-signal] PINGPONG Timeout. Last Socket Message: ".concat(n-this.lastMsgTime,"ms")),n-this.lastMsgTime>T("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("recover",Bs.FALLBACK):this.request(ie.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const i=Date.now()-n;this.rttRolling.add(i),T("REPORT_STATS")&&this.send(ie.PING_BACK,{pingpongElapse:i})}).catch(i=>{})}handleInflateData(){const{inflateLength:t,deflateLength:n}=this.websocket.getInflateData();t!==0&&n!==0&&this.upload(Ka.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:n,ws_inflate_length:t})}handleWebsocketEvents(){this.websocket.on(hn.RECONNECT_CREATE_CONNECTION,t=>{this.emit(ee.WS_RECONNECT_CREATE_CONNECTION,t)}),this.websocket.on(hn.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(hn.CLOSED,()=>{this.connectionState=Le.CLOSED}),this.websocket.on(hn.FAILED,()=>{this._disconnectedReason=Pe.NETWORK_ERROR,this.connectionState=Le.CLOSED}),this.websocket.on(hn.RECONNECTING,t=>{this._websocketReconnectReason=t,this.joinResponse=void 0,this.connectionState===Le.CONNECTED?this.connectionState=Le.RECONNECTING:this.connectionState=Le.CONNECTING}),this.websocket.on(hn.WILL_RECONNECT,(t,n)=>{if(Na(this,ee.IS_P2P_DISCONNECTED)&&t==="retry")return _.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit
188(ee.NEED_RENEW_SESSION),this.emit(ee.DISCONNECT_P2P),n("tryNext");t!=="retry"&&(_.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(t)),this.reconnectToken=void 0,this.emit(ee.NEED_RENEW_SESSION),this.emit(ee.DISCONNECT_P2P)),n(t)}),this.websocket.on(hn.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(t=>{_.warning("[".concat(this.clientId,"] rejoin failed ").concat(t)),this.reconnect("tryNext",Bs.SERVER_ERROR)}):this.join().catch(t=>{if(this.emit(ee.REPORT_JOIN_GATEWAY,t.message||t.code,this.url||""),t instanceof D&&t.code===A.UNEXPECTED_RESPONSE&&t.data.code===ce.ERR_NO_AUTHORIZED)return _.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",Bs.SERVER_ERROR);_.error("[".concat(this.clientId,"] join gateway request failed"),t.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Bs.SERVER_ERROR):(this.initError=t,this.close())})}),this.websocket.on(hn.REQUEST_NEW_URLS,(t,n)=>{Jt(this,ee.REQUEST_RECOVER,this.multiIpOption).then(t).catch(n)}),this.websocket.on(hn.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(he.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}),this.websocket.on(hn.TO_CONNECT_DATACHANNEL,(t,n)=>{Jt(this,ee.PRE_CONNECT_PC).then(t).catch(n)}),this.websocket.on(hn.FAILBACK,()=>{this.openConnectionTime!==void 0&&this.emit(ee.DATACHANNEL_FAILBACK)})}}const Kte={name:"DataChannelConnection",create:function(e){let{store:t,spec:n}=e;return new Bte(n,t)}},Hte={name:"DataChannelSignal",create:function(e){let{store:t,spec:n}=e;return new Wte(n,t)}};Jl(),at("PROCESS_ID","process-".concat(Qe(8,""),"-").concat(Qe(4,""),"-").concat(Qe(4,""),"-").concat(Qe(4,""),"-").concat(Qe(12,""))),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(t){return void _.error("Error loading sdk config",t.message)}if(e)try{const t=JSON.parse(window.atob(e)),n=Date.now();_.debug("Loading global parameters from cache",t),Object.keys(t).forEach(i=>{if(Object.prototype.hasOwnProperty.call(tt,i)){const{value:r,expires:o}=t[i];if(o&&o<=n)return;Zi[i]=r,tt[i]=r}})}catch(t){_.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(Zi.AREAS)&&Zi.AREAS.length>0&&mv(Zi.AREAS,!0);const gx=(e,t,n)=>{_.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),at(e,t,n)};Yo(ate,!1),Yo(lte,!1),Yo(Qee,!1),Yo(Rte,!1),Yo(rte,!1),Yo(Lte,!1),Yo(Ute,!1),Yo(xte,!1),Yo(Kte,!1),Yo(Hte,!1);const cn=function(e){const t=new Nt,n=e,i={getListeners:t.getListeners.bind(t),on:(r,o)=>(function(s,a){s===Vo.SECURITY_POLICY_VIOLATION&&MV(a,!0)}(r,o),t.on.bind(t)(r,o)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return kV(kV({},n),i)}({__TRACK_LIST__:Va,VERSION:qi,BUILD:mS,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:gx,getParameter:T,getSupp
vendor: 8,932 bytes, line 188
188ortedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;const n=await async function(i){let r;return Oe().supportUnifiedPlan?(i.addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"}),r=(await i.createOffer()).sdp):r=(await i.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0})).sdp,r}(t);if(!n)return e;t.close(),t=null,e=function(i){const r={video:[],audio:[]};return i.match(/ VP8/i)&&r.video.push("VP8"),i.match(/ VP9/i)&&r.video.push("VP9"),i.match(/ AV1/i)&&r.video.push("AV1"),i.match(/ H264/i)&&r.video.push("H264"),i.match(/ H265/i)&&r.video.push("H265"),i.match(/ opus/i)&&r.audio.push("OPUS"),i.match(/ PCMU/i)&&r.audio.push("PCMU"),i.match(/ PCMA/i)&&r.audio.push("PCMA"),i.match(/ G722/i)&&r.audio.push("G722"),r}(n)}catch(t){throw new D(A.CREATE_OFFER_FAILED,t.toString&&t.toString()).print()}return e},checkSystemRequirements:function(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];const t=Z.reportApiInvoke(null,{name:vt.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:ht.TRACER}),n=function(){let o=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0],s=!1;try{const a=window.RTCPeerConnection,c=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,d=window.WebSocket;s=!(!a||!d),o&&!c&&(s=!1),s&&Gl()&&aO(75)&&new a().close()}catch(a){_.error("check system requirement failed: ",a),s=!1}return s}(e),i=ete();_.debug("checkSystemRequirements, api:",n,"browser",i);const r=n&&i;return t.onSuccess(r),T("IGNORE_RTC_DEVICE_CHECK")?n:r},getDevices:function(e){return nr.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return nr.getRecordingDevices(e)},getCameras:function(e){return nr.getCamerasDevices(e)},getElectronScreenSources:RN,getPlaybackDevices:function(e){return nr.getSpeakers(e)},createClient:DV,createCameraVideoTrack:async function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const t=T("CAMERA_CAPTURE_CONFIG"),n=Qe(8,"track-cam-"),i=Z.reportApiInvoke(null,{id:n,tag:ht.TRACER,name:vt.CREATE_CAM_VIDEO_TRACK,options:[ft({},e),t]});t&&(e.encoderConfig=t);const r=jp(e);let o=null;_.info("start create camera video track with config",JSON.stringify(e),"trackId",n);try{o=(await tr({video:r},n)).getVideoTracks()[0]||null}catch(a){throw i.onError(a),a}if(!o){const a=new L(A.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(a),a.throw(_)}if(e.optimizationMode&&FS(n,o,e,Kr(e.encoderConfig)),T("USE_STANDARD_BITRATE_DEFAULT")){const a=Kr(e.encoderConfig);e.encoderConfig=a,delete a.bitrateMax,delete a.bitrateMin}const s=new Hp(o,e,r,e.scalabiltyMode?xp(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return i.onSuccess(s.getTrackId()),_.info("create camera video success, trackId:",n),s},createCustomVideoTrack:function(e){const t=Qe(8,"track-cus-"),n=Z.reportApiInvoke(null,{id:t,tag:ht.TRACER,name:vt.CREATE_CUSTOM_VIDEO_TRACK,options:[e]});T("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin);const i=new pt(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin},e.scalabiltyMode?xp(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[$e.CUSTOM_TRACK]);return n.onSuccess(i.getTrackId()),_.info("create custom video track success with config",e,"trackId",i.getTrackId()),i},createScreenVideoTrack:async function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"disable";const n=typeof t=="object"?function(u){const p=DN(u);return lN()&&u.suppressLocalAudioPlayback&&(p.suppressLocalAudioPlayback=u.suppressLocalAudioPlayback),uN()&&u.restrictOwnAudio&&(p.restrictOwnAudio=!0),p}(t):void 0;n&&(t="auto");const i=Qe(8,"track-scr-v-"),r=Z.reportApiInvoke(null,{id:i,tag:ht.TRACER,name:vt.CREATE_SCREEN_VIDEO_TRACK,options:[ft({},e),t]});e.encoderConfig?typeof e.encoderConfig=="string"||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";const o=function(u){const p={};u.screenSourceType&&(p.mediaSource=u.screenSourceType),u.extensionId&&ss()&&(p.extensionId=u.extensionId);const{displaySurface:E,selfBrowserSurface:m,surfaceSwitching:g,systemAudio:R,preferCurrentTab:v,windowAudio:C,monitorTypeSurfaces:w}=u;(Ur(107)||ks(107)||ba(93))&&(E&&(nn(E,"displaySurface",["browser","window","monitor"]),p.displaySurface=E),m?(nn(m,"selfBrowserSurface",["exclude","include"]),p.selfBrowserSurface=m):p.selfBrowserSurface="include",g&&(nn(g,"surfaceSwitching",["exclude","include"]),p.surfaceSwitching=g)),(Ur(105)||ks(105)||ba(91))&&R&&(nn(R,"systemAudio",["exclude","include"]),p.systemAudio=R),(Ur(94)||ks(94)||ba(80))&&v&&(p.preferCurrentTab=!0),(Ur(141)||ks(141)||ba(125))&&C&&(nn(C,"windowAudio",["exclude","system"]),p.windowAudio=C),(Ur(119)||ks(119)||ba(105))&&w&&(nn(w,"monitorTypeSurfaces",["exclude","include"]),p.monitorTypeSurfaces=w),u.electronScreenSourceId&&(p.sourceId=u.electronScreenSourceId);const b=u.encoderConfig?bS(u.encoderConfig):null;return p.mandatory={chromeMediaSource:"desktop",maxWidth:b?b.width:void 0,maxHeight:b?b.height:void 0},b&&(b.frameRate&&(typeof b.frameRate=="number"?(p.mandatory.maxFrameRate=b.frameRate,p.mandatory.minFrameRate=b.frameRate):(p.mandatory.maxFrameRate=b.frameRate.max||b.frameRate.ideal||b.frameRate.exact||void 0,p.mandatory.minFrameRate=b.frameRate.min||b.frameRate.ideal||b.frameRate.exact||void 0),p.frameRate=b.frameRate),b.width&&(p.width=b.width),b.height&&(p.height=b.height)),p}(e);let s=null,a=null;const c=Oe();if(!c.supportShareAudio&&t==="enable"){const u=new L(A.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return r.onError(u),u.throw(_)}_.info("start create screen video track with config",e,"withAudio",t,"trackId",i);const d=c.supportShareAudio&&t!=="disable";try{const u=await tr({screen:o,screenAudio:d?n||!0:void 0},i);s=u.getVideoTracks()[0]||null,a=u.getAudioTracks()[0]||null}catch(u){throw r.onError(u),u}if(!s){const u=new L(A.UNEXPECTED_ERROR,"can not find track in media stream");return r.onError(u),u.throw(_)}if(!a&&t==="enable"){s&&s.stop();const u=new L(A.SHARE_AUDIO_NOT_ALLOWED);return r.onError(u),u.throw(_)}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(FS(i,s,e,e.encoderConfig&&bS(e.encoderConfig)||void 0),e.encoderConfig&&typeof e.encoderConfig!="string"&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));const l=new pt(s,e.encoderConfig?bS(e.encoderConfig):{},e.scalabiltyMode?xp(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,i,[$e.SCREEN_TRACK]);if(!a)return r.onSuccess(l.getTrackId()),_.info("create screen video track success","video:",l.getTrackId()),l;const h=new jt(a,void 0,Qe(8,"track-scr-a-"),!1);return r.onSuccess([l.getTrackId(),h.getTrackId()]),_.info("create screen video track success","video:",l.getTrackId(),"audio:",h.getTrackId()),[l,h]},createMicrophoneAndCameraTracks:async function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const n=T("CAMERA_CAPTURE_CONFIG"),i=Qe(8,"track-mic-"),r=Qe(8,"track-cam-"),o=Z.reportApiInvoke(null,{id:"".concat(i,"-").concat(r),tag:ht.TRACER,name:vt.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,n]});n&&(t.encoderConfig=n);const s=jp(t),a=PN(e);let c=null,d=null;_.info("start create camera video track(".concat(r,") and microphone audio track(").concat(i,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const u=await tr({audio:a,video:s},"".concat(i,"-").concat(r));c=u.getAudioTracks()[0],d=u.getVideoTracks()[0]}catch(u){throw o.onError(u),u}if(!c||!d){const u=new L(A.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(u),u.throw(_)}if(t.optimizationMode&&FS(r,d,t,Kr(t.encoderConfig)),T("USE_STANDARD_BITRATE_DEFAULT")){const u=Kr(t.encoderConfig);t.encoderConfig=u,delete u.bitrateMax,delete u.bitrateMin}const l=new Zl(c,e,a,i),h=new Hp(d,t,s,t.scalabiltyMode?xp(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,r);return o.onSuccess([l.getTrackId(),h.getTrackId()]),_.info("create camera video track(".concat(r,") and microphone audio track(").concat(i,") success")),[l,h]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const t=Qe(8,"track-mic-"),n=Z.reportApiInvoke(null,{id:t,tag:ht.TRACER,name:vt.CREATE_MIC_AUDIO_TRACK,options:[e]}),i=PN(e);let r=null;_.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{r=(await tr({audio:i},t)).getAudioTracks()[0]||null}catch(s){throw n.onError(s),s}if(!r){const s=new L(A.UNEXPECTED_ERROR,"can not find track in media stream");return n.onError(s),s.throw(_)}
188const o=new Zl(r,e,i,t);return n.onSuccess(o.getTrackId()),_.info("create microphone audio track success, trackId:",t),o},createCustomAudioTrack:rP,createBufferSourceAudioTrack:async function(e){var t;const{cacheOnlineFile:n,encoderConfig:i}=e;let{source:r}=e;const o={source:r instanceof AudioBuffer?"AudioBuffer":r instanceof File?(t=File.name)!==null&&t!==void 0?t:"File":r,cacheOnlineFile:n,encoderConfig:i},s=Qe(8,"track-buf-"),a=Z.reportApiInvoke(null,{id:s,tag:ht.TRACER,name:vt.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(T("DISABLE_WEBAUDIO"))throw new L(A.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");_.info("start create buffer source audio track with config",JSON.stringify(o),"trackId",s);const c=r;if(!(r instanceof AudioBuffer))try{r=await async function(h,u){let p=null;if(typeof h=="string"){const m=SD.get(h);if(m)return _.debug("use cached audio resource: ",h),m;try{p=(await Fr(()=>li.get(h,{responseType:"arraybuffer"}),void 0,void 0,{maxRetryCount:3})).data}catch(g){throw new L(A.FETCH_AUDIO_FILE_FAILED,g.toString())}}else p=await new K((m,g)=>{const R=new FileReader;R.onload=v=>{v.target?m(v.target.result):g(new L(A.READ_LOCAL_AUDIO_FILE_ERROR))},R.onerror=()=>{g(new L(A.READ_LOCAL_AUDIO_FILE_ERROR))},R.readAsArrayBuffer(h)});const E=await function(m){const g=pd();return new K((R,v)=>{g.decodeAudioData(m,C=>{R(C)},C=>{v(new L(A.DECODE_AUDIO_FILE_FAILED,C.toString()))})})}(p);return typeof h=="string"&&u&&SD.set(h,E),E}(r,n)}catch(h){return a.onError(h),h.throw(_)}const d=new SX(r),l=new gX(c,d,i?Fp(i):{},s);return _.info("create buffer source audio track success, trackId:",s),a.onSuccess(l.getTrackId()),l},setAppType:function(e){if(_.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw _.debug("Invalid appType"),new D(A.INVALID_PARAMS,"invalid app type",e);at("APP_TYPE",Math.floor(e))},setLogLevel:function(e){_.setLogLevel(e)},enableLogUpload:function(){T("USE_NEW_LOG")?at("UPLOAD_LOG",!0):_.enableLogUpload()},disableLogUpload:function(){T("USE_NEW_LOG")?at("UPLOAD_LOG",!1):_.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new ZU},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;const n=Z.reportApiInvoke(null,{tag:ht.TRACER,name:vt.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof jt||e instanceof Ed)){const c=new D(A.INVALID_TRACK,"the parameter is not a audio track");return n.onError(c),c.throw()}t&&t<1e3&&(t=1e3);const i=e instanceof jt?e.getTrackLabel():"remote_track",r=e.getVolumeLevel();let o=r,s=r;const a=Date.now();return new K(c=>{const d=setInterval(()=>{const l=e.getVolumeLevel();o=l>o?l:o,s=l<s?l:s;const h=o-s>1e-4,u=Date.now()-a;if(h||u>t){clearInterval(d);const p=h,E={duration:u,deviceLabel:i,maxVolumeLevel:o,result:p};_.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(E))),n.onSuccess(E),c(p)}},200)})},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;const n=Z.reportApiInvoke(null,{tag:ht.TRACER,name:vt.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof pt||e instanceof md)){const h=new D(A.INVALID_TRACK,"the parameter is not a video track");return n.onError(h),h.throw()}t&&t<1e3&&(t=1e3);const i=e instanceof pt?e.getTrackLabel():"remote_track",r=e.getMediaStreamTrack(!0),o=document.createElement("video");o.style.width="1px",o.style.height="1px",o.setAttribute("muted",""),o.muted=!0,o.setAttribute("playsinline",""),o.controls=!1,(vn()||Tp())&&(o.style.opacity="0.01",o.style.position="fixed",o.style.left="0",o.style.top="0",document.body.appendChild(o)),o.srcObject=new MediaStream([r]),o.play();const s=document.createElement("canvas");s.width=160,s.height=120;let a=0,c=0;try{const h=Date.now();a=await function(u,p,E,m){let g,R=0,v=null;return new K((C,w)=>{function b(){R>m&&g&&(g(),C(R));const y=E.getContext("2d");if(!y){const U=new D(A.UNEXPECTED_ERROR,"can not get canvas 2d context.");return _.error(U.toString()),void w(U)}y.drawImage(u,0,0,160,120);const N=y.getImageData(0,0,E.width,E.height),k=Math.floor(N.data.length/3);if(v){for(let U=0;U<k;U+=3)if(N.data[U]!==v[U])return R+=1,void(v=N.data);v=N.data}else v=N.data}setTimeout(()=>
188{g&&(g(),C(R))},p),g=LS(()=>{b()},30)})}(o,t,s,4),c=Date.now()-h}catch(h){throw n.onError(h),h}xee===je.SAFARI&&(o.pause(),o.remove()),o.srcObject=null;const d=a>4,l={duration:c,changedPicNum:a,deviceLabel:i,result:d};return _.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(l))),n.onSuccess(l),d},setArea:mv,audioElementPlayCenter:zn,resumeAudioContext:function(){return zn.autoResumeAfterInterruption(!0)},processExternalMediaAEC:function(e){nte.processExternalMediaAEC(e)},registerExtensions:function(e){const t=T("PLUGIN_INFO")||[];e.forEach(n=>{"name"in n&&!x(t).call(t,n.name)&&t.push(n.name);const i=n;i.__registered__=!0,i.logger.hookLog=_.extLog,i.reporter.hookApiInvoke=Z.extApiInvoke,i.parameters&&Object.keys(i.parameters).forEach(r=>{i.parameters[r]=T(r)})}),gx("PLUGIN_INFO",t)},ChannelMediaRelayError:Sd,ChannelMediaRelayEvent:ds,ChannelMediaRelayState:Ri,RemoteStreamFallbackType:hX,RemoteStreamType:uX,ConnectionDisconnectedReason:Pe,AudienceLatencyLevelType:B9,AREAS:Je,preload:async function(e,t,n,i){return xv(e,t,n,i)},startLastmileProbeTest:async function(e,t,n,i){let r={state:"unavailable"};await xv(e,t,n,i);const o=await Fv({appId:e,cname:t,token:n||e,uid:i,cloudProxyServer:"disabled"});if(!o)return r;await Bv(o);const s=DV({mode:"rtc",codec:"vp8"});let a;try{a=await s.join(e,t,n,i,{networkQualityProbe:!0})}catch{return r}const c=new jee,d=c.createMuteAudioTrack(),l=await rP({mediaStreamTrack:d});await s.publish([l]);const[h,u,p]=await new K((C,w)=>{const b=setTimeout(()=>{clearTimeout(b),C([!0,null,"audio"])},5e3);s.on("user-published",async(y,N)=>{y.uid===a&&(clearTimeout(b),C([!1,y,N]))})});if(h||!u)return await s.unpublish([l]),await s.leave(),l.close(),c.close(),r;await s.subscribe(u,p),await new K((C,w)=>{const b=setTimeout(()=>{clearTimeout(b),C(null)},5e3)});const E=s.getRTCStats(),m=s.getLocalAudioStats(),g=E.RTT,R=m.sendJitterMs,v=m.currentPacketLossRate;return r={state:"complete",rtt:g,packetLossRate:v,jitter:R,networkQuality:((C,w,b)=>{let y=1;if(b>0){let q=Math.log(100*b)/Math.log(2)+1;q=Math.min(5,Math.max(0,q)),y=1-q/5}let N=1;if(C>0){let q=Math.log(C/40)/Math.log(2)+1;q=Math.min(5,Math.max(0,q)),N=1-q/5}let k=1;if(w>0){let q=Math.log(w/10)/Math.log(2.5)+1;q=Math.min(5,Math.max(0,q)),k=1-q/5}const U=.5*y+.3*N+.2*k;let X=0;return X=U>=.8?1:U>=.6?2:U>=.4?3:U>=.2?4:5,X})(g,R,v)},await s.unsubscribe(u),await s.unpublish([l]),await s.leave(),l.close(),c.close(),await Bv(o),r}});return Object.defineProperties(cn,{onAudioAutoplayFailed:{get:()=>hi.onAudioAutoplayFailed,set:e=>{hi.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>hi.onAutoplayFailed,set:e=>{hi.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>cn._onSecurityPolicyViolation,set(e){cn._onSecurityPolicyViolation=e,MV(e)}},__CLIENT_LIST__:{get:()=>T("SHOW_GLOBAL_CLIENT_LIST")?Wa:[]}}),nr.on(Fa.CAMERA_DEVICE_CHANGED,e=>{_.info("camera device changed",JSON.stringify(e)),cn.onCameraChanged&&cn.onCameraChanged(e),cn.safeEmit(Vo.CAMERA_CHANGED,e)}),nr.on(Fa.RECORDING_DEVICE_CHANGED,e=>{_.info("microphone device changed",JSON.stringify(e)),cn.onMicrophoneChanged&&cn.onMicrophoneChanged(e),cn.safeEmit(Vo.MICROPHONE_CHANGED,e)}),nr.on(Fa.PLAYOUT_DEVICE_CHANGED,e=>{_.debug("playout device changed",JSON.stringify(e)),cn.onPlaybackDeviceChanged&&cn.onPlaybackDeviceChanged(e),cn.safeEmit(Vo.PLAYBACK_DEVICE_CHANGED,e)}),zn.onAutoplayFailed=()=>{_.info("detect audio element autoplay failed"),hi.onAudioAutoplayFailed&&hi.onAudioAutoplayFailed()},ct.on("autoplay-failed",()=>{_.info("detect webaudio autoplay failed"),hi.onAudioAutoplayFailed&&hi.onAudioAutoplayFailed(),cn.safeEmit(Vo.AUTOPLAY_FAILED)}),ct.on(Nn.STATE_CHANGE,(e,t)=>{_.info("audio context state changed: ".concat(t," => ").concat(e)),cn.onAudioContextStateChanged&&cn.onAudioContextStateChanged(e,t),cn.safeEmit(Vo.AUDIO_CONTEXT_STATE_CHANGED,e,t)}),At.on(Oa.NETWORK_STATE_CHANGE,(e,t)=>{_.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))}),window&&(window.__ARTC__=cn),cn})})(Mx);var Fne=Mx.exports;const no=Yte(Fne),Ux="15cb0d28b87b425ea613fc46f7c9f974";
188no.setLogLevel(3);const Bne={class:"mini_stream_text",style:{"margin-left":"5px"}},Gne={__name:"miniStreamContainer",props:{showType:{type:Number,default:0,required:!0},callTime:{type:String,default:"00:00",required:!0}},emits:["changeMiniSize"],setup(gt,{emit:He}){const dt=gt,{showType:Ye,callTime:Ae}=Um(dt),re=He,{width:le,height:Xe}=$v(),we=bn(null),{style:St}=eA(we,{initialValue:{x:le.value-136,y:0},onMove:bt=>{bt.x>le.value-136&&(bt.x=le.value-136),bt.x<0&&(bt.x=0),bt.y>Xe.value-116&&(bt.y=Xe.value-116),bt.y<0&&(bt.y=0)},preventDefault:!0,stopPropagation:!0}),Tt=()=>{re("changeMiniSize",!1)};return(bt,et)=>(ar(),to("div",{class:"mini_stream_container",ref_key:"miniStreamContainer",ref:we,style:tA([Me(St),{position:"fixed"}])},[ye("div",{class:"minimodal",onClick:Xte(Tt,["prevent","stop"])}),ye("div",null,[bi(ye("span",Bne,[Rx(Ts(Me(ji)("im.call.status.waiting")),1),et[0]||(et[0]=ye("span",{class:"dot"},"...",-1))],512),[[wi,Me(Ye)===0]]),bi(ye("span",{class:"mini_stream_text"},Ts(Me(Ae)),513),[[wi,Me(Ye)===1]])])],4))}},Vx=$d(Gne,[["__scopeId","data-v-b6accda2"]]),xx="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAMAAAC5zwKfAAABZVBMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICAgQEBAcHBweHh4pKSksLCwuLi4vLy8zMzM6Ojo8PDxKSkpUVFRXV1daWlpgYGBhYWFsbGxubm5vb290dHR1dXV4eHh5eXl6enp7e3t8fHx/f3+IiIiKioqKioqNjY2Ojo6QkJCRkZGSkpKTk5OUlJSZmZmampqbm5ucnJydnZ2lpaWmpqapqamqqqqtra2urq6ysrK0tLS1tbW6urq9vb2/v7/CwsLExMTLy8vLy8vS0tLW1tbW1tbY2NjY2Nja2trc3Nzi4uLm5ubm5ubn5+fu7u7w8PD09PT5+fn5+fn6+vr8/Pz8/Pz9/f3+/v7+/v7///////9LPp8TAAAAdnRSTlMAAQQFCgsPEBQgIycqNTc5OkhKS09ZXmNpamtvcHJzd3h5fYCBg4eHiouMjI2QkJWYmZudnaGio6WlpqenqKiqra6vsLCxsrKzs7a2t7e4vL2+v8HBxMTFycrMzs7T1Njb3Nzd39/l5+jo7/D0+Pn5+/z9/f7+AYwGawAAAwFJREFUWMPFmetbElEQxkdXREBA7hdRLoNmZN5KM/PS1UwtJRTFUjNLTQVFYf7+PnhhN2XOWTg+vV939vdwOLPvzJkDwMtid3mDkVg8lYrHIkGvy26BxqU5PGG8o7DHoTVCa7H5k1hHSb+txSSu1dmNrLqdrWbW6u5FoXrd0it3xFBKMYcUzhpAaQWsYl5nAk0o0SnaDC+alJfdnLYQmlaorT6vPYoNKNpej9fRgw2pp6PO72uQh9hz729si2LDit7zP7aGsAmF7u61F5uS904+Y5P6J8OtiWaBCeNXGMCmFTD4CyqQzns0gV9l1g6LxcO1jMDNav7YxUe+LxEREZXe8XHu2xTk/XmJbrXEe/hNMjrZsNHLGvBilA11Xtc3vh7tkU57fOW6qoU2NmigogdWBthgGwAA+NmYKTJoig32AwBoSTZmwQj8yAYnNXFSLxqBi+Lk9qgEegAgrBIYBrCgSiBawK4WaAeXWqALfGqBPgiqBQYhohYYAdZbH+8fnBiBJwf7T1mXhTj3+DXdoyz3RhxS3OMPlP9upH3L0zr3RkoEnPlkBC7MiICCJb+ZNgKn39JXfsnspryilSdVPa+aWeE3OsanzRjt4W898Bf+pJd82rCJ/YjKmee6GlB5linTAJ/YPkGFKuBqDbiKBfoh6MJ4cxirVifxS/kKV/6Mk9XqmMAcBPa1TsUJHNo8rlSON4fwRZFPGkS7yGDTu3SR70dMpxH78xe0mxYZrKgEpLeISjvLc3PLOyWirbSwBIiKFOL40c2eHI6LYj1yveFIdvvsbDs7ItcjCgr9tf4cyUQlNXErYgrol2iWTAFtMu2cCeB1OydoOBGH53O509Ncbn5YEOiUaon7CrVvudAn1RKDmwvb0NvXhlTTzh4rBi/1wMtBqWMFl9yzxhIwK3Xw4Y5mE+d63vmE3NFM/eFR+fFW/QFc/YhA+RBD/ZhF/SBI/ahK/TBN/bhP/UDyAUam6oe6AKB1yYydu7T/Nxh/gNH9A1wu1K4/fLXrD5/4+uMvDEtYzCWIYWAAAAAASUVORK5CYII=",Fx="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAMAAAC5zwKfAAABp1BMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAgIEBAQGBgYICAgKCgoMDAwODg4QEBARERETExMVFRUXFxcZGRkbGxscHBweHh4iIiIjIyMnJycpKSkqKiosLCwuLi4vLy8xMTEzMzM2NjY6Ojo8PDw/Pz9BQUFERERHR0dKSkpLS0tNTU1PT09RUVFUVFRVVVVXV1dZWVlaWlpdXV1fX19gYGBhYWFiYmJkZGRlZWVoaGhpaWlsbGxubm5vb29zc3N1dXV2dnZ5eXl6enp7e3t8fHx9fX1/f39/f3+BgYGCgoKDg4OEhISFhYWGhoaIiIiKioqKioqMjIyNjY2Ojo6Pj4+QkJCRkZGSkpKTk5OUlJSVlZWWlpaXl5eYmJiZmZmampqcnJydnZ2enp6fn5+goKCgoKCioqKioqKkpKSkpKSmpqanp6eoqKipqamqqqqrq6sKB1vfAAAAjXRSTlMAAQQFCgsPEBQgIycqNTc5OkhKS09ZXmNpamtvcHJzd3h5fYCAgIGBgoKDg4SEhYWGhoeHiImKiouLjIyNjY6QkJGSk5SVlZaXl5iZmZqbnJydnZ6en6CgoaKjpKWmp6eoqKmpqqqrq6ysra2ur6+wsLGxsrKzs7S0tbW2tre4uLm5urq7u7y9vb6+v78Th7meAAADlElEQVRYw8WZ+VcSURTHR3EDBASUTQzkBigK5J6apomm4RKmqZhlplZmZoaiuWS5pdw/OiSWIZj3HjCevr/MzHlzPmfevDvfe98djiOrVKbU6Ixmi81mMRt1GqWslMtfErnaABkyqOWSfGhF0up6EFB9tbQoR1yxohaIqlUU5zJX1T2g6p6KeeZyMzDJLGfCldcAs2rK6bxKK+QgayVtMTSQozTExSnRQ87SlwjzykyQh0xlQryKOshLdRUCz5cnL0rM+owlJshbpizvsVgPBUifudYaKEiajHiGAvVPhJdbCwVa07/CGihYNWn+AiKI5z0SsxhAc8ofqzJHhz8/SJ67Auvf99dG7DSiKhmCWfx5CA888dOxM4xpv4vm4YlgVGQbHcewO3bix4QuOyhERTy/Zc9Hk7jXHD30RZJA/EqZde3fXCgVGJ7CUBPABvI0SXlEaQxYLTQ8jTsu+y4fuEsBVsdiRjCfwyxuN7rDPGDEQQbWSyhB/RK3GjwHPGILQ3CrSTfM42aD9zAFbKMA1VGggXjHW/zkbDliBhqi9Rr5jhnEj47WY1YglHIyKhDfO9pOWIEyTkkH4pq9/QcjUMlpGYC4Yu/4yQbUcjoWIC7bO38xAXWckQmIr+93nbEAjRzJW70+30pifV9B9zmi3zdINggzZyGMrvO/40Xovbg9+ohAC2cjjG5ejKymiEHou5yYw1Ei0EYEbpxDgPeM89Df/ASHKUDSlJfQOcKf9dytkT+mTJm0KAHs90b4xFnov/JQFoUUNl24ACt8IE5DLy1siIG9d+luPk3hPoTwOTWwiZ/eEL6BgasE75urk5pWNBRzWMMp6N6J4X4Hna5dPMFxijmQ7csVxqAT+maWFvxueBjGQDQhPCPbF8Vgm7bw2B/L+D2L1zfRN+g9jIwRDZaSAsA+eYGRw61Q9EPeia1wy1HkKSkFkJPUrRpG3+3j1VbwUfy69TgyTEpSTLUhLvMu2k5uBglplJDoBYDQfvSCkOiFSxFBILkUESyW8gBKSeUcL3Q8Hlz1eBxUXrycy15wJjWRqBuuv/SwFZxZS2JedZPSdQ9bScyphG/qSPPDbbainbStGEuzw5tGtm0FIbgHjk95CjnYNj7ib83E3zyKvr0VfwMufotA9CaG+G0W8RtB4reqxG+mid/uE78heQctU/Gburf+WMXSdq6S/L/G+B207u/g50Lq94c29ftDS//98QdzNG/F/URQnQAAAABJRU5ErkJggg==",jne={key:0,class:"stream_invite_box",title:"\u53D6\u6D88\u547C\u53EB"},Wne={class:"invite_name"},Kne={class:"time"},Hne={class:"stream_audio_container"},Yne={class:"audio_name"},Xne={class:"stream_video_container"},Jne={class:"stream_control"},zne=["src"],qne={__name:"singleCall",props:{callKitStatus:{type:Object,default:()=>({}),required:!0}},emits:["getAgoraRtcToken","updateLocalStatus","handleCancelCall","handleVideoToVioce"],setup(gt,{emit:He}){const{width:dt,height:Ye}=$v(),Ae=bn(null),{style:re}=eA(Ae,{initialValue:{x:dt.value/2-292/2,y:Ye.value-750},onMove:oe=>{oe.x>dt.value-292&&(oe.x=dt.value-292),oe.x<0&&(oe.x=0),oe.y>Ye.value-500&&(oe.y=Ye.value-500),oe.y<0&&(oe.y=0)},stopPropagation:!0}),le=bn(null),{isOutside:Xe}=vx(le),we=gt,{callKitStatus:St}=Um(we),{EVENT_NAME:Tt,CALLKIT_EVENT_TYPE:bt,CALLKIT_EVENT_CODE:et,PUB_CHANNEL_EVENT:Ee}=xm(),on=bn(!1),be=oe=>{on.value=oe},kn=bn(!1),Yn=bn(null),en=bn(null),Xn=He;let sn=null,Ze=null,lt=null;const Wt=oA({voice:!1,video:!1});sn=no.createClient({mode:"live",codec:"h264"}),sn.setClientRole("host");
188const wn=async oe=>{console.log("%c\u5F00\u542F\u5A92\u4F53\u68C0\u67E5","color:green");const z={type:{},ext:{},callType:oe};if(oe===Rs.SINGLE_VOICE){const Ie=await no.getMicrophones();Ie.length||(z.type=bt[et.NOT_HAVE_MICROPHONE],z.ext.message="\u672A\u53D1\u73B0\u97F3\u9891\u8F93\u5165\u8BBE\u5907\uFF0C\u8BF7\u68C0\u67E5\u9EA6\u514B\u98CE",Ee(Tt,{...z})),console.log("getMicrophones devices",Ie)}if(oe===Rs.SINGLE_VIDEO){const Ie=await no.getCameras(),_t=await no.getMicrophones();Ie.length||(z.type=bt[et.NOT_HAVE_CAMERA],z.ext.message="\u672A\u53D1\u73B0\u89C6\u9891\u8F93\u5165\u8BBE\u5907\uFF0C\u8BF7\u68C0\u67E5\u6444\u50CF\u5934",Ee(Tt,{...z})),_t||(z.type=bt[et.NOT_HAVE_MICROPHONE],z.ext.message="\u672A\u53D1\u73B0\u97F3\u9891\u8F93\u5165\u8BBE\u5907\uFF0C\u8BF7\u68C0\u67E5\u9EA6\u514B\u98CE",Ee(Tt,{...z})),console.log("getCameras devices",Ie,_t)}},Wi=()=>{console.log(">>>>>AgoraRtc\u76D1\u542C\u6302\u8F7D\u5B8C\u6BD5"),sn.on("user-published",async(oe,z)=>{if(await sn.subscribe(oe,z),z==="video"){console.log(">>>>>>\u89C6\u9891\u7C7B\u578B");const Ie=oe.videoTrack;console.log("remoteVideoTrack",Ie),setTimeout(()=>
188{Ie.play(en.value),console.log("%c \u8FDC\u7AEF\u6D41\u5DF2\u64AD\u653E","color:green")},300)}z==="audio"&&(console.log(">>>>>>\u97F3\u89C6\u7C7B\u578B"),oe.audioTrack.play())}),sn.on("user-unpublished",(oe,z)=>{console.log(">>>>>>\u76D1\u542C\u5230\u6D41\u79FB\u9664",oe,z),z==="video"&&console.log(">>>>>\u53D6\u6D88\u53D1\u5E03\u4E86\u89C6\u9891\u6D41"),z==="audio"&&console.log(">>>>>>\u53D6\u6D88\u53D1\u5E03\u4E86\u97F3\u9891\u6D41")}),sn.on("user-left",(oe,z)=>{console.log(">>>>>>\u7528\u6237\u79BB\u5F00\u56DE\u8C03\u89E6\u53D1,\u79BB\u5F00\u539F\u56E0",z),fe(!1)})};nA(()=>{Wi()}),Ax(()=>St.value.localClientStatus,(oe,z)=>{console.log(">>>>>>> single\u7EC4\u4EF6\u76D1\u542C\u662F\u5426\u53EF\u52A0\u5165\u623F\u95F4",oe,z),oe===Vt.confirmCallee&&Ni()},{immediate:!0});const Ni=()=>{Xn("getAgoraRtcToken",async()=>{console.log(">>>>\u89E6\u53D1\u4E86\u5B50\u7EC4\u4EF6\u7684callback"),await Kt()})},$n=bn(null),Ir=bn(0),br=()=>{$n.value&&clearInterval($n.value),$n.value=setInterval(()=>{Ir.value++},1e3)},es=Qv(()=>{const oe=Math.floor(Ir.value/60),z=Ir.value%60,Ie=Math.floor(oe/60),_t=oe%60;return`${Ie>0?Ie+":":""}${_t<10?"0"+_t:_t}:${z<10?"0"+z:z}`}),Kt=async()=>{const oe=St.value.channelInfos,z=oe.channelName,Ie=oe.agoraChannelToken,_t=oe.agoraUserId,it=oe.callType;try{wn(it),await sn.join(Ux,z,Ie,_t),console.log(">>>>\u52A0\u5165\u9891\u9053\u6210\u529F"),br(),Ze=await no.createMicrophoneAudioTrack(),lt=await no.createCameraVideoTrack(),it===Rs.SINGLE_VOICE&&(Ze&&await sn.publish(Ze),Xt("voice"),console.log("%c---\u672C\u5730\u8F68\u9053\u97F3\u9891\u63A8\u6D41\u6210\u529F","color:green")),it===Rs.SINGLE_VIDEO&&(Ze&<&&await sn.publish([Ze,lt]),setTimeout(()=>{lt.play(Yn.value)},300),Xt("allPlay"),console.log("%c---\u672C\u5730\u8F68\u9053\u97F3\u9891\u4EE5\u53CA\u89C6\u9891\u63A8\u6D41\u6210\u529F","color:green")),kn.value=!0}catch(Ki){Ze&&Ze.close(),lt&<.close(),console.log("%c>>>>\u52A0\u5165\u9891\u9053\u5931\u8D25","color:red",Ki)}},Ke=()=>{Xn("handleCancelCall")},fe=async oe=>{console.log("\u300B\u300B\u300B\u300B\u300B\u6302\u65AD"),await sn.leave(),oe&&Ke();const z={type:bt[et.HANGUP],ext:{message:`\u901A\u8BDD\u7ED3\u675F\u3010${es.value}\u3011`,calltime_length:Ir.value},callType:St.value.channelInfos.callType,eventHxId:St.value.channelInfos.callerIMName};Ee(Tt,{...z}),Xn("updateLocalStatus",Vt.idle)},Xt=oe=>{if(oe==="allPlay"&&(Wt.voice=!0,Wt.video=!0),oe==="voice"){const z=Wt.voice;Ze&&typeof Ze.setEnabled=="function"?(Ze.setEnabled(!z),Wt.voice=!z):console.warn("localVoiceTrack is not available or setEnabled method is missing")}if(oe==="video"){const z=Wt.video;lt&&typeof lt.setEnabled=="function"?(lt.setEnabled(!z),Wt.video=!z):console.warn("localVideoTrack is not available or setEnabled method is missing")}},kt=bn(!0),wt=()=>kt.value=!kt.value;return iA(()=>{console.log(">>>>>>\u76D1\u542C\u5230\u7EC4\u4EF6\u5378\u8F7D"),Ze&&Ze.close(),lt&<.close(),$n.value&&clearInterval($n.value)}),(oe,z)=>(ar(),to("div",null,[bi(ye("div",{ref_key:"singleContainer",ref:Ae,class:"app_container",style:tA([Me(re),{position:"fixed"}])},[ye("div",{class:"mini_stream_icon",onClick:z[0]||(z[0]=Ie=>be(!0))}),ye("div",{class:"stream_container",ref_key:"streamContainer",ref:le},[Me(St).localClientStatus===Me(Vt).inviting?(ar(),to("div",jne,[z[6]||(z[6]=ye("img",{class:"invite_avatar",src:cA,alt:"\u5934\u50CF",draggable:"false"},null,-1)),ye("p",Wne,Ts(Me(St).inviteTarget||""),1),z[7]||(z[7]=ye("p",{class:"invite_text"},[Rx(" \u6B63\u5728\u7B49\u5F85\u5BF9\u65B9\u63A5\u6536\u9080\u8BF7"),ye("span",{class:"dot"}," ...")],-1))])):Xu("",!0),Me(St).localClientStatus===Me(Vt).confirmCallee?(ar(),to(Vm,{key:1},[ye("div",Kne,Ts(es.value),1),bi(ye("div",Hne,[z[8]||(z[8]=ye("img",{class:"audio_avatar",src:cA,alt:"\u5934\u50CF"},null,-1)),ye("p",Yne,Ts(Me(St).inviteTarget||Me(St).channelInfos.callerIMName),1)],512),[[wi,Me(St).channelInfos.callType===0]]),bi(ye("div",Xne,[ye("div",{class:rA([kt.value?"smallContainer":"mainContainer"]),ref_key:"smallContainer",ref:Yn,onClick:z[1]||(z[1]=()=>kt.value&&wt())},null,2),ye("div",{class:rA([kt.value?"mainContainer":"smallContainer"]),ref_key:"mainContainer",ref:en,onClick:z[2]||(z[2]=()=>!kt.value&&wt())},null,2)],512),[[wi,Me(St).channelInfos.callType===1]])],64)):Xu("",!0),bi(ye("div",Jne,[Me(St).localClientStatus===Me(Vt).inviting?(ar(),to("div",{key:0,class:"stream_invite_btn",onClick:Ke},[...z[9]||(z[9]=[ye("img",{src:Fm,alt:"\u53D6\u6D88",draggable:"false"},null,-1),ye("p",{class:"btn_text"},"\u53D6\u6D88",-1)])])):Xu("",!0),Me(St).localClientStatus===Me(Vt).confirmCallee?(ar(),to(Vm,{key:1},[ye("div",{class:"stream_calling_btn",onClick:z[3]||(z[3]=Ie=>Xt("voice"))},[ye("img",{src:Wt.voice?Me(xx):Me(Fx),alt:"",draggable:"false"},null,8,zne),z[10]||(z[10]=ye("p",{class:"btn_text"},"\u8BED\u97F3",-1))]),ye("div",{class:"stream_calling_btn",onClick:z[4]||(z[4]=Ie=>fe(!0))},[...z[11]||(z[11]=[ye("img",{src:Fm,alt:"\u6302\u65AD",draggable:"false"},null,-1),ye("p",{class:"btn_text"},"\u6302\u65AD",-1)])]),bi(ye("div",{class:"stream_calling_btn",onClick:z[5]||(z[5]=()=>{Xn("handleVideoToVioce")})},[...z[12]||(z[12]=[ye("img",{src:xne,alt:"\u8F6C\u8BED\u97F3",draggable:"false"},null,-1),ye("p",{class:"btn_text"},"\u8F6C\u8BED\u97F3",-1)])],512),[[wi,Me(St).channelInfos.callType===1]])],64)):Xu("",!0)],512),[[wi,!Me(Xe)]])],512)],4),[[wi,!on.value]]),bi(Qo(Me(Vx),{"show-type":kn.value?1:0,"call-time":es.value,onChangeMiniSize:be},null,8,["show-type","call-time"]),[[wi,on.value]])]))}},Zne=$d(qne,[["__scopeId","data-v-90a5a8ef"]]),Qne="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAWCAMAAADto6y6AAABPlBMVEUAAAAA/wAAf38A/39A/38zzGYq1H9J221G0XRA1GpAz3A51HFAzHM3029D02891nA72HZA0W0+03I7zG5Az3A+z25B0W9A0mxA0nM+zXBB1XFA0W4+1XI90XA80W9A1G491G8/1HE/0G490W890W4/0HA+0W4/0m4+03A9
1880G890m8/0m8/0G4/0HA/0nA+0W4+0m8+0XA/0nA/0W490HA+03A90nA+0XE+0m8+0W8+0m890W8/0m8/0W4/0XA+0W8+0nA90G8/0m8+0W8+0W8+0XA+0W890m8+0nA+0m8+0W8+0nA+0XA90HA+0m8+0W4+0XA+0G8+0W8+0m8+0W8+0W8+0W8+0G8+0m8+0W8+0XA+0W8+0W8+0W8+0nA+0W8+0W4+0m490W8+0W8+0W890m8+0W4+0W8+0m8+0W/xmVXQAAAAaXRSTlMAAQICBAUGBwsMEBIUFxcZGhwdHiAlJygoKSssMTI3PEdNUVNYXV9hYmxscXJycnR3gIKGiYuNkZOXmJqam5ucnZ6eoayyvb/AxcjIydDR0tnb3eHi5OXm5ujp6u709Pb39/n6/P3+/v6BRgf3AAAA5UlEQVQYGW3BBz8CAQDG4b9RdJnZsrfM7HV3GdmyCRkN8n7/L+DSD3flefjTd/a8VkWZitmMpHFKBeMq2KRE/7W+7eBoWe/AMZZIJh8/VbSNY0pXQRiVW4xKMC61Cxdys5tSG9D7nusiJzc7lNYg7GkBedjM6QBGdIw8bALZrJ92PSAPC27USIMyyMOi+iVfS7fukIfFsBIwoUPkYRn3isC+5nmVm9n5ceRjQG/NxOVmEg4QetIytN3KxcQxrdMaoC4SjS6eq8jEYczU88O/mlfBFmWGUnIsUa71REqH+YdvcqWHX1+ya3R3OAkocgAAAABJRU5ErkJggg==",$ne="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAMAAAC5zwKfAAAAflBMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACNjY2UlJS3t7fPz8/Z2dn///+EpG8NAAAAKXRSTlMAAQQFCgsPEBQgIycqNTc5OkhKS09ZXmNpamtvcHJzd3h5fYCws8bW3QwagtgAAAG0SURBVFjDxZnZdoJAEERLERVQEJQdZWmN8v8/mIckGqMjA5Qn980D1GGcppca4DWm7QZRWpRNUxZpFLi2ieEYjp/IA4nvGEPUJtauFgX1zpr0lJuuc3lJvp72Wat3kE4OnvbKnUK0KBwtuUUo2oSLbr1VJT2oVl2bEUhPgpebM4ulN/FMrTfPZADZXKW33Msg9kvF+w3UE9k/fcdZJoPJnvyP01hGED/udSCjCB7iWUbyJ8IX1VjB6v4rDGU04V1+EQK/co9RMASLW37cCAXvGoIHjuDhJxjXQmL9Xd9ylmD+VQstoWEBAHYad57a9qRx2w4AjJonWBu6Qa0pKA4AnynoA0iYgglgClNQTNhcQRsuV9DFliu4RcQVjJByBVMUXMECpfri8ePKpW0vt19H9TMlGvXFc6vgrH6m4QvSl0zfFHrY0AOb/OkF/ORAT1/0BEsvAfwiRS+j9EJPb0X4zRK9naM3nPyWGB65aeePFfTBhz+a8YdH+njLH8D5FgHdxODbLHwjiG9V8c00vt3HNyTfYJnyTV0AxkbHdt4Y/2eMv8G6f8Phwu34Y3s7/th2H398AlPesOc3SbJkAAAAAElFTkSuQmCC",eie="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAMAAAC5zwKfAAAA/FBMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAgIKCgoMDAwODg4VFRUXFxciIiIjIyMnJycpKSkqKio2NjY5OTk6OjpISEhLS0tUVFRVVVVXV1dgYGBiYmJnZ2doaGiGhoaPj4+UlJSmpqatra2/v7/MzMzNzc3d3d3f39/h4eHj4+Pm5ubq6urt7e319fX19fX39/f39/f5+fn9/f39/f3+/v7///////8BpbKTAAAAU3RSTlMAAQQFCgsPEBQgIycqNTc5OkhKS09ZXmNpamtvcHJzd3h5fYCAgoKDhYWIiYqKi46PkJSVmJmZnZ6foK2xs73Ay9TV4OLk5ufs7fT19vf5/P39/o1GTT4AAAIoSURBVFjDxZnncsIwEIQVDCGYYMCAaQ7t0nvvhfRe/f7vEghJSIIkW/Iy2V+a8ejDQue704oxuWKmZTtlt95q1d2yY1tmjOnLSGZLNKBSNmno0EYS+SYJ1MwnRhRxkVSVpKqmIiprTdfIV7V04JUnXQokNxkIFy9QYBXi/rzxBimoMe63GTYpypZuTrRIyipGxbzRCmmoMirijU2QlibGBO+nyesQue8YrZC2Kpz/MVKkECoO7rVNoWQPxDOF1J8IjzfCAhu/v8IChVbhV34hgH7kHsNFAN1+fswQROnvEKxhgLWvYEwRSKnP+lZFAau9WpggmBIfwDwOmP+ImSYO2DSEQT3ZfvI4er1Y8w3uLPfJmifQmRSY7QBL3CebIuBNbwHzM9xppU6/xv+pLRHwtvt05cp7WODOizFTA7h71xnscOeZzFIHHj13B/vceRbLqQKn2r0BH5hjjirw3JMBHVZWBXpSYJm5WKDL6lhgnbWwwBYeCF8yfFPgYeNggY76p/ciBdrqyWHvXga0NNLX6rUEaOok2NlTMTAmKgHyjH385nnrghIgKFJyIG2fHEyKihS/jG6IgJe+ZZRf6OceBcBD30IvaEWmF5c5Wprzb0XwzRK8nYM3nPiWmKXBTTv+WAE/+OCPZvjDI/x4iz+A4y0CuImBt1nwRhDeqsKbaXi7D29IDsEyxZu63fyYCWI7Z4z/M8aHYN0P4XKhf/2R619/5PyvP94B+9M+C2wRcGUAAAAASUVORK5CYII=",tie="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAMAAAC5zwKfAAABiVBMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAgIEBAQGBgYICAgKCgoMDAwODg4RERETExMVFRUXFxcZGRkbGxscHBweHh4gICAiIiIlJSUnJycpKSkqKiouLi4vLy8zMzM0NDQ3Nzc5OTk8PDw+Pj5ERERHR0dISEhKSkpOTk5PT09RUVFSUlJVVVVXV1dYWFhcXFxfX19gYGBhYWFlZWVnZ2doaGhsbGxtbW1ubm5vb29zc3N0dHR2dnZ4eHh5eXl8fHx/f39/f3+BgYGCgoKDg4OEhISFhYWGhoaIiIiIiIiKioqKioqMjIyNjY2Ojo6QkJCRkZGSkpKUlJSWlpaXl5eZmZmampqcnJydnZ2enp6goKCgoKCioqKioqKkpKSlpaWmpqanp6eoqKipqamqqqqrq6v2DIqHAAAAg3RSTlMAAQQFCgsPEBQgIycqNTc5OkhKS09ZXmNpamtvcHJzd3h5fYCAgIGBgoKDhISFhYaGh4eIiImKiouMjI2Oj4+QkZOUlJWWl5eYmZmam5ydnZ+foKGioqOkpaamp6ipqqqrq6ysra2urq+vsLCxsrKztLW2tre4uLm6uru7vL29vr6/v2qNU+MAAAL9SURBVFjDxZlrWxJBFICPrqiAgCx3WAE5AqmZpZVldr9oWWllapZWWJlmmWkX0zLPL+9DlsLObZfx6f06z7zs7hzmnDkDIMbjC5rxlJUrFHJWKm4GfR5wj+EPJ9FGMuw33NgavNFO5NAZ9TY41DUGMigkE2h08q6hLErJhpTf3G+hEpZfSdcSQ2ViLXJfWx4dkG+TLYaJDjGFi9OUQMckmvi+5jS6IN3M87V2oCs6WjnP59KH2MF8xqY0uibN+I6NCayDhH2tTawL0xbPWCc1Ed6Sr1eYr/4XxrBuYlX7C2rg0N5jWDqE1sH+2I5aCP0LwaweYfZvMAZQE4H9/MbIRx9mu1wIM39yoZcxNEezbh7RCwAAUcZIcYEeuxBGAQAMZj4vVeihc2GnwQ/q8gZN4NDyu1peXJQFd5g9NEpEd3GUbPwcFAjDAJBkD1WIiG7jHbtxbP8zs2YlATyc33pLRLR3C+/ZhOOIiGdXd6dZ0zzgEwlp7wZOsoTXd4joJGOaD4JCIf26ilM2YfERERENM6YFISIW0u4VnKkRHn9DXGEE4hIh/bjU9bRK+GST+MI4pGRC2hkpzhMLljAFllRI28Oll6pCC3JyIX0/V36tKMxBQUFI384cW1YTFtSE9GWwZ1VRmFMS0uap3jW1V7bUhPSpv29daVFSikJa7+vfUAmbuKqQ1noHPkuFcelf7xDve05/lQlN2eZQxUr30BbR9EeBMCjZvmpYKp/fpvHuBb7QJ95gbSyWLuyMI97f4wk93BTAFtLz4qVRRLy8RUQnmCmAl6Q4QnpWLCIiDrzamuQkKU4aXeQIaa5LkkbZiR7HeEKakSR6ZimCiDfnKyxmKjQlLkWYxZKA0iI9EBdLDRlnxvISTQjLOccFZ/cKXRMVnM5L4p65EWFJDCHNRbv+Y4X2g4/+o5n+w6P2463+A7j+FoH2Job+Nov+RpD+VpX+Zpr+dp/+huQRtEz1N3UBwGhXaTu3G/+vMX4ErfsjuFw4uP6IHFx/ROTXH78BafjMUKO/LtMAAAAASUVORK5CYII=",nie={class:"time"},iie=["id"],rie={class:"userInfo"},oie={class:"userIMId"},sie={class:"muteStatus"},aie={class:"volumeStatus",src:Qne},cie={class:"stream_control"},die={class:"stream_multiCall_btn"},lie=["src"],uie={class:"stream_multiCall_btn"},hie=["src"],pie={class:"stream_multiCall_btn"},_ie=["src"],mie={__name:"multiCall",props:{callKitStatus:{type:Object,default:()=>({}),required:!0},loginUserHxId:{type:String,default:"",required:!0}},emits:["getAgoraRtcToken","getAgoraChannelDetails","updateLocalStatus","onInviteMembers","handleCancelCall"],setup(gt,{emit:He}){const dt=bn(null),{width:Ye,height:Ae}=$v(),{style:re}=eA(dt,{initialValue:{x:600,y:40},onMove:oe=>{oe.x>Ye.value-500&&(oe.x=Ye.value-500),oe.x<0&&(oe.x=0),oe.y>Ae.value-350&&(oe.y=Ae.value-350),oe.y<0&&(oe.y=0)},stopPropagation:!0}),le=bn(!1),Xe=oe=>{le.value=oe},we=bn(null),{isOutside:St}=vx(we),Tt=gt,{callKitStatus:bt,loginUserHxId:et}=Um(Tt),Ee=He;let on=null;on=no.createClient({mode:"live",codec:"h264"}),on.setClientRole("host");let be=null,kn=null;const Yn=oA({voice:!1,video:!1}),en=oA([]),Xn=()=>{console.log(">>>>>AgoraRtc\u76D1\u542C\u6302\u8F7D\u5B8C\u6BD5"),on.on("user-joined",oe=>{const z=oe.uid.toString();Ke("create",z),console.log(">>>>>\u52A0\u5165\u9891\u9053\u7684\u7528\u6237id",z)}),on.on("user-published",async(oe,z)=>{console.log("%c\u76D1\u542C\u7528\u6237\u53D1\u5E03\u6D41","color:green"),await on.subscribe(oe,z);const Ie=oe.uid.toString();if(z==="video"){console.log(">>>>>>\u89C6\u9891\u7C7B\u578B");const _t=oe.videoTrack;zte(()=>{const it=document.getElementById(Ie);it?setTimeout(()=>{_t.play(it)},300):(console.log("+++++\u6CA1\u6709\u53D6\u5230\u6D41\u5BB9\u5668remotePlayerContainer",it),setTimeout(()=>{_t.play(document.getElementById(Ie))},500)),fe("videoPlay",Ie,!0)})}z==="audio"&&(console.log(">>>>>>\u97F3\u89C6\u7C7B\u578B"),oe.audioTrack.play(),fe("muteStatus",Ie,!1))}),on.enableAudioVolumeIndicator(),on.on("volume-indicator",oe=>
188{Xt(oe)}),on.on("user-unpublished",(oe,z)=>{console.log(">>>>>>\u76D1\u542C\u5230\u6D41\u79FB\u9664",oe,z);const Ie=oe.uid.toString();z==="video"&&(console.log(">>>>>\u53D6\u6D88\u53D1\u5E03\u4E86\u89C6\u9891\u6D41"),fe("videoPlay",Ie,!1)),z==="audio"&&(console.log(">>>>>>\u53D6\u6D88\u53D1\u5E03\u4E86\u97F3\u9891\u6D41"),fe("muteStatus",Ie,!0))}),on.on("user-left",(oe,z)=>{console.log(">>>>>>\u7528\u6237\u79BB\u5F00\u56DE\u8C03\u89E6\u53D1,\u79BB\u5F00\u539F\u56E0",z);const Ie=oe.uid.toString();Ke("remove",Ie),en.length===0&&Kt()})},sn=async oe=>{console.log("%c\u5F00\u542F\u5A92\u4F53\u68C0\u67E5","color:green");const z={type:{},ext:{},callType:Rs.MULTI_VIDEO};{const Ie=await no.getCameras(),_t=await no.getMicrophones();Ie.length||(z.type=lt[Wt.NOT_HAVE_CAMERA],z.ext.message="\u672A\u53D1\u73B0\u89C6\u9891\u8F93\u5165\u8BBE\u5907\uFF0C\u8BF7\u68C0\u67E5\u6444\u50CF\u5934",wn(Ze,{...z})),_t||(z.type=lt[Wt.NOT_HAVE_MICROPHONE],z.ext.message="\u672A\u53D1\u73B0\u97F3\u9891\u8F93\u5165\u8BBE\u5907\uFF0C\u8BF7\u68C0\u67E5\u9EA6\u514B\u98CE",wn(Ze,{...z})),console.log("getCameras devices",Ie,_t)}};nA(()=>{Xn()});const{EVENT_NAME:Ze,CALLKIT_EVENT_TYPE:lt,CALLKIT_EVENT_CODE:Wt,PUB_CHANNEL_EVENT:wn}=xm();Ax(()=>bt.value.localClientStatus,(oe,z)=>{console.log(">>>>>>> multiCall\u7EC4\u4EF6\u76D1\u542C\u662F\u5426\u53EF\u52A0\u5165\u623F\u95F4",oe,z),oe===Vt.confirmCallee&&z!==Vt.inviting&&(console.log("\u5DF2\u5E94\u7B54\u52A0\u5165"),Wi()),oe===Vt.inviting&&(console.log("\u9080\u8BF7\u72B6\u6001\u52A0\u5165"),setTimeout(()=>{Wi()},500))},{immediate:!0});const Wi=()=>{Ee("getAgoraRtcToken",async()=>{console.log(">>>>\u89E6\u53D1\u4E86\u5B50\u7EC4\u4EF6\u7684callback"),es()})},Ni=bn(null),$n=bn(0),Ir=()=>{Ni.value&&clearInterval(Ni.value),Ni.value=setInterval(()=>{$n.value++},1e3)},br=Qv(()=>{const oe=Math.floor($n.value/60),z=$n.value%60,Ie=Math.floor(oe/60),_t=oe%60;return`${Ie>0?Ie+":":""}${_t<10?"0"+_t:_t}:${z<10?"0"+z:z}`}),es=async()=>{const oe=bt.value.channelInfos,z=oe.channelName,Ie=oe.agoraChannelToken,_t=oe.agoraUserId;sn();try{await on.join(Ux,z,Ie,_t),Ir(),console.log("%c\u52A0\u5165channel\u5F53\u4E2D","color:green"),en.push({easeimUserId:et.value,agoraUserId:_t.toString(),volume:0,muteStatus:!1,videoPlay:!0}),be=await no.createMicrophoneAudioTrack(),kn=await no.createCameraVideoTrack(),be&&kn&&await on.publish([be,kn]),kt("allPlay"),setTimeout(()=>{const it=document.getElementById(`${_t}`);kn.play(it)},300)}catch(it){console.log(">>>>\u52A0\u5165\u9891\u9053\u5931\u8D25",it)}},Kt=async()=>{if(console.log("\u300B\u300B\u300B\u300B\u300B\u6302\u65AD",bt.value.localClientStatus),[Vt.inviting,Vt.confirmRing].includes(bt.value.localClientStatus))console.log(">>>>>>\u8C03\u7528\u53D1\u9001\u53D6\u6D88\u4FE1\u4EE4"),await on.leave(),Ee("handleCancelCall");else{await on.leave();const oe={type:lt[Wt.HANGUP],ext:{message:`\u901A\u8BDD\u7ED3\u675F\u3010${br.value}\u3011`,calltime_length:$n.value},callType:bt.value.channelInfos.callType,eventHxId:bt.value.channelInfos.groupId};wn(Ze,{...oe})}Ee("updateLocalStatus",Vt.idle)},Ke=(oe,z)=>{if(oe==="create"){console.log("\u8C03\u7528\u4E86\u521B\u5EFA\u89C6\u9891\u5BB9\u5668",oe,z);const Ie=en.some(_t=>_t.agoraUserId===z);if(Ie)return;if(!Ie){const _t=bt.value.channelInfos.channelUsers;if(_t[z]){console.log(">>>>\u5305\u542B\u8BE5\u7528\u6237\u7684\u5BF9\u5E94\u4FE1\u606F"),en.push({easeimUserId:_t[z],agoraUserId:z.toString(),volume:0,muteStatus:!1,videoPlay:!1}
188);return}else{console.log(">>>>\u4E0D\u5305\u542B\u8BE5\u7528\u6237\u7684\u5BF9\u5E94\u4FE1\u606F"),Ee("getAgoraChannelDetails",()=>{const it=bt.value.channelInfos.channelUsers;en.push({easeimUserId:it[z],agoraUserId:z.toString(),volume:0,muteStatus:!1,videoPlay:!1}),console.log(">>>>>\u6267\u884C\u6DFB\u52A0\u4E00\u4E2A\u65B0\u7684\u5BB9\u5668",it)});return}}}if(oe==="remove"&&document.getElementById(z)){const Ie=en.findIndex(it=>it.agoraUserId===z);Ie>-1&&en.splice(Ie,1);const _t=document.getElementById(z);we.value.removeChild(_t)}},fe=(oe,z,Ie)=>{const _t=bt.value.channelInfos.channelUsers[z];if(_t){const it=en.length>0&&en.findIndex(Ki=>Ki.easeimUserId===_t);oe==="volume"&&(console.log(">>>>>\u66F4\u6539\u97F3\u91CF\u72B6\u6001",z,Ie),it!==-1&&(en[it].volume=Ie)),oe==="muteStatus"&&it!==-1&&(en[it].muteStatus=Ie),oe==="videoPlay"&&it!==-1&&(en[it].videoPlay=Ie)}},Xt=oe=>{const z=bt.value.channelInfos.channelUsers;oe.forEach(Ie=>{const{level:_t}=Ie,it=Ie.uid.toString(),Ki=z[it];if(Ki){const Ht=en.filter(fc=>fc.easeimUserId===Ki);if(sA(Ht[0]).volume===1&&_t*1>=5)return;Ht[0].muteStatus===!0&&fe("volume",it,0),sA(Ht[0]).volume===0&&_t*1>=5&&fe("volume",it,1),sA(Ht[0]).volume===1&&_t*1===0&&fe("volume",it,0)}})},kt=oe=>{if(oe==="allPlay"&&(Yn.voice=!0,Yn.video=!0),oe==="voice"){const z=Yn.voice;be&&typeof be.setEnabled=="function"?(be.setEnabled(!z),Yn.voice=!z):console.warn("localVoiceTrack is not available or setEnabled method is missing")}if(oe==="video"){const z=Yn.video;kn&&typeof kn.setEnabled=="function"?(kn.setEnabled(!z),Yn.video=!z):console.warn("localVideoTrack is not available or setEnabled method is missing")}},wt=()=>{const oe=bt.value.channelInfos.groupId;Ee("onInviteMembers",{groupId:oe})};return iA(()=>{be&&be.close(),kn&&kn.close(),console.log(">>>>>>\u76D1\u542C\u5230\u7EC4\u4EF6\u5378\u8F7D"),Ni.value&&clearInterval(Ni.value)}),(oe,z)=>(ar(),to("div",null,[bi(ye("div",{ref_key:"multiContainer",ref:dt,class:"app_container",style:tA([Me(re),{position:"fixed"}])},[ye("div",{class:"mini_stream_icon",onClick:z[0]||(z[0]=Ie=>Xe(!0))}),ye("div",nie,Ts(br.value),1),ye("div",{class:"stream_container",ref_key:"streamContainer",ref:we},[(ar(!0),to(Vm,null,Jte(en,Ie=>(ar(),to("div",{class:rA([en.length<=2?"stream_two_user_container":"stream_users_container"]),key:Ie.agoraUserId,id:Ie.agoraUserId},[ye("div",rie,[ye("span",oie,Ts(Ie.easeimUserId),1),bi(ye("span",sie,"\u5DF2\u95ED\u9EA6",512),[[wi,Ie.muteStatus]]),bi(ye("img",aie,null,512),[[wi,Ie.volume>0]])])],10,iie))),128)),bi(ye("div",cie,[ye("div",die,[ye("img",{src:Me($ne),alt:"",draggable:"false",onClick:wt},null,8,lie),z[3]||(z[3]=ye("p",{class:"btn_text"},"\u6DFB\u52A0\u6210\u5458",-1))]),ye("div",uie,[ye("img",{src:Yn.voice?Me(xx):Me(Fx),onClick:z[1]||(z[1]=Ie=>kt("voice")),alt:"",draggable:"false"},null,8,hie),z[4]||(z[4]=ye("p",{class:"btn_text"},"\u8BED\u97F3",-1))]),ye("div",{class:"stream_multiCall_btn"},[ye("img",{src:Fm,onClick:Kt,alt:"",draggable:"false"}),z[5]||(z[5]=ye("p",{class:"btn_text"},"\u79BB\u5F00",-1))]),ye("div",pie,[ye("img",{src:Yn.video?Me(eie):Me(tie),onClick:z[2]||(z[2]=Ie=>kt("video")),alt:"",draggable:"false"},null,8,_ie),z[6]||(z[6]=ye("p",{class:"btn_text"},"\u6444\u50CF\u5934",-1))])],512),[[wi,!Me(St)]])],512)],4),[[wi,!le.value]]),bi(ye("div",null,[bi(Qo(Me(Vx),{"show-type":1,"call-time":br.value,onChangeMiniSize:Xe},null,8,["call-time"]),[[wi,le.value]])],512),[[wi,le.value]])]))}},Eie=$d(mie,[["__scopeId","data-v-975271f4"]]),fie={class:"container"},Bx="IM_MESSAGE",gie={__name:"index",props:{EaseIMClient:{type:Object,default:()=>({}),required:!0},msgCreateFunc:{type:Function,default:()=>({}),required:!0}},emits:["onInviteMembers"],setup(gt,{expose:He,emit:dt}){const Ye=gt,Ae=dt,{EaseIMClient:re,msgCreateFunc:le}=Ye;une(re,le),re.addEventHandler("IM_CONNECT",{onConnected:()=>{console.log("%c>>>>EaseCallKitIM\u5DF2\u8FDE\u63A5","color:green;"),Xe()},onDisconnected:()=>{console.log("%c>>>>EaseCallKitIM\u5DF2\u65AD\u5F00\u8FDE\u63A5","color:red;"),we()}});const Xe=()=>{console.log(">>>>>IM\u4FE1\u4EE4\u76D1\u542C\u6302\u8F7D");const Ke={onTextMessage:fe=>{const{ext:Xt}=fe;console.log(">>>>>\u6536\u5230\u6587\u672C\u4FE1\u4EE4\u6D88\u606F",fe),Xt&&(Xt==null?void 0:Xt.action)===ua.INVITE&&wn(fe)},onCmdMessage:fe=>{console.log(">>>>>\u6536\u5230\u547D\u4EE4\u4FE1\u4EE4\u6D88\u606F",fe),fe&&(fe==null?void 0:fe.action)===ua.RTC_CALL&&Wi(fe)}};we(),re.addEventHandler(Bx,Ke),Tt()},we=()=>re.removeEventHandler(Bx),St=bn(""),Tt=()=>St.value=re.user||"",bt={singleCall:Zne,multiCall:Eie},{callComponents:et,callKitStatus:Ee,callKitTimer:on,updateLocalStatus:be,updateChannelInfos:kn,sendInviteMessage:Yn,inMultiChanelSendInviteMsg:en}=hne(),{EVENT_NAME:Xn,CALLKIT_EVENT_TYPE:sn,CALLKIT_EVENT_CODE:Ze,PUB_CHANNEL_EVENT:lt}=xm(),Wt=new pne,wn=Ke=>{console.log(">>>>>\u5F00\u59CB\u5904\u7406\u88AB\u9080\u8BF7\u6D88\u606F");const{from:fe,ext:Xt}=Ke||{};if(fe!==re.user)if(Ee.localClientStatus>Vt.idle){console.log(">>>>>\u56DE\u590D\u5FD9\u788C");const kt={targetId:fe,sendBody:Xt};Wt.sendAnswerMsg(kt,yr.BUSY)}else kn(Ke),be(Vt.alerting),Wt.sendAlertMsg(Ke)},Wi=Ke=>{if(Ke.from===re.user)return;console.log(">>>>\u5F00\u59CB\u5904\u7406command\u547D\u4EE4\u6D88\u606F",Ke);const fe=Object.assign({},Ke.ext)||{},{calleeDevId:Xt,callerDevId:kt}=fe,wt=re.context.jid.clientResource,{action:oe}=fe,{localClientStatus:z,channelInfos:Ie}=Ee,_t=Ee.channelInfos.callId;let it=!0;const Ki={targetId:Ke.from,sendBody:fe,status:it},Ht={type:{},ext:{},callType:0,eventHxId:""};switch(oe){case ua.ALERT:if(be(Vt.alerting),console.log("%c>>>>>\u6536\u5230alert\u4FE1\u4EE4","color:blue",_t,it),fe.callId!==_t){it=!1,console.warn("callId \u4E8E\u5F53\u524D\u547C\u53EB\u7AEFcallId \u4E0D\u4E00\u81F4");return}z>Vt.receivedConfirmRing&&Ie.callType!==2&&(it=!1),kt!==wt&&(console.warn("callerDevId \u8BBE\u5907\u4E0D\u76F8\u540C"),it=!1),it?(Wt.sendConfirmRing(Ki),be(Vt.inviting)):(Wt.sendConfirmRing(Ki),be(Vt.idle));break;case ua.CONFIRM_RING:{if(Xt!==wt)return;!fe.status&&Ee.localClientStatus<Vt.receivedConfirmRing&&be(Vt.idle),console.log("%chandle confimring","color:blue;"),be(Vt.receivedConfirmRing)}break;case ua.ANSWER:{if(console.log(">>>>>cmdMsgBody",fe),kt!==wt)return;be(Vt.receivedAnswerCall),on.value&&clearTimeout(on.value);const fc={targetId:Ke.from,sendBody:fe};
188if(!Ee.channelInfos.calleeDevId&&Ee.channelInfos.callType!==2?(fe.videoToVoice&&(Ee.channelInfos.callType=0),kn(Ke)):Ee.channelInfos.calleeDevId!==fe.calleeDevId&&Ee.channelInfos.callType!==2&&(console.log("callKitStatus.channelInfos.calleeDevId",Ee.channelInfos.calleeDevId),fc.sendBody.result=yr.REFUSE),Wt.sendConfirmCallee(fc),be(Vt.confirmCallee),fe.result!==yr.ACCPET&&(console.log("callKitStatus.channelInfos.callType ",Ee.channelInfos.callType),Ee.channelInfos.callType!==2))return fe.result===yr.BUSY&&(Ht.type=sn[Ze.CALLEE_BUSY],Ht.ext={message:ji("im.call.events.calleeBusy")}),fe.result===yr.REFUSE&&(Ht.type=sn[Ze.CALLEE_REFUSE],Ht.ext={message:ji("im.call.events.calleeRefuse")}),Ht.callType=Ee.channelInfos.callType,Ht.eventHxId=Ke.from||"",lt(Xn,{...Ht}),console.log(">>>>>\u4FEE\u6539\u5F53\u524D\u72B6\u6001\u4E3A\u7A7A\u95F2"),be(Vt.idle)}break;case ua.CONFIRM_CALLEE:{if(Ke.to===re.user){if(fe.result&&fe.result===yr.BUSY)return;if(fe.calleeDevId!==wt){be(Vt.idle),console.log("%c \u5DF2\u5728\u5176\u4ED6\u8BBE\u5907\u5904\u7406","color:red;"),Ht.type=sn[Ze.OTHER_HANDLE],Ht.ext={message:ji("im.call.events.otherDeviceHandled")},Ht.callType=Ee.channelInfos.callType,Ht.eventHxId=Ke.from||"",lt(Xn,{...Ht});return}}if(fe.result!==yr.ACCPET&&Ee.localClientStatus!==Vt.confirmCallee)return be(Vt.idle);be(Vt.confirmCallee)}break;case ua.CANCEL:{if(Ke.from===re.user)return;if(Ke.from===Ee.channelInfos.callerIMName)return be(Vt.idle);Ht.type=sn[Ze.CALLER_CANCEL],Ht.ext={message:ji("im.call.events.callerCancel")},Ht.callType=Ee.channelInfos.callType,Ht.eventHxId=Ke.from||"",lt(Xn,{...Ht});break}case ua.VIDEO_TO_VOICE:{if(console.log("\u89C6\u9891\u8F6C\u8BED\u97F3\u901A\u77E5"),fe.callId!==Ee.channelInfos.callType)return;Ee.channelInfos.callType=Rs.SINGLE_VOICE;break}default:console.log(">>>\u5176\u4ED6\u672A\u77E5\u72B6\u6001");break}},Ni=Ke=>{const fe=Ee.channelInfos,Xt={targetId:fe.callerIMName,sendBody:{callerDevId:fe.callerDevId,callId:fe.callId}};if(Ke===yr.ACCPET){Wt.sendAnswerMsg(Xt,yr.ACCPET),be(Vt.answerCall),console.log(">>>>\u5F00\u59CB\u53D1\u9001\u63A5\u542C\u4FE1\u4EE4");const kt={type:sn[Ze.CALLEE_ACCPET],ext:{message:ji("im.call.events.calleeAccepted")},callType:Ee.channelInfos.callType,eventHxId:fe.callerIMName};Ee.channelInfos.callType===2&&(kt.eventHxId=Ee.channelInfos.groupId),lt(Xn,{...kt})}if(Ke===yr.REFUSE){Wt.sendAnswerMsg(Xt,yr.REFUSE),be(Vt.idle),console.log(">>>>\u5F00\u59CB\u53D1\u9001\u6302\u65AD\u4FE1\u4EE4");const kt={type:sn[Ze.CALLEE_REFUSE],ext:{message:ji("im.call.events.calleeRefusedInvite")},callType:Ee.channelInfos.callType,eventHxId:fe.callerIMName};Ee.channelInfos.callType===2&&(kt.eventHxId=Ee.channelInfos.groupId),lt(Xn,{...kt})}},$n=()=>{const Ke=Ee.inviteTarget;if(!Ke)return console.log(">>>\u6302\u65AD\u76EE\u6807ID\u4E3A\u7A7A",Ke);if(Ee.channelInfos.callType===Rs.MULTI_VIDEO){Ke.length&&Ke.forEach(Xt=>{Wt.sendCannelMsg({targetId:Xt,callId:Ee.channelInfos.callId})});const fe={type:sn[Ze.CANCEL],ext:{message:ji("im.call.events.multiCanceled")},callType:Rs.MULTI_VIDEO,eventHxId:Ee.channelInfos.groupId};lt(Xn,{...fe}),be(Vt.idle)}else{Wt.sendCannelMsg({targetId:Ke,callId:Ee.channelInfos.callId});const fe={type:sn[Ze.CANCEL],ext:{message:ji("im.call.events.canceled")},callType:Ee.channelInfos.callType,eventHxId:Ke};lt(Xn,{...fe}),be(Vt.idle)}},Ir=()=>{const{calleeIMName:Ke,callerIMName:fe,callId:Xt}=Ee.channelInfos,kt=Ke===re.user?fe:Ke;Wt.sendVideoToVioce(kt,Xt),Ee.channelInfos.callType=Rs.SINGLE_VOICE},br=async Ke=>{const fe=re.user,Xt=Ee.channelInfos.channelName;if(console.log("channelNamechannelNamechannelName",Xt),!fe&&!Xt)return;const{accessToken:kt,agoraUserId:wt}=await Cne(re,{username:fe,channelName:Xt});console.log("+_+_+_+_+_+\u83B7\u53D6\u623F\u95F4token\u6210\u529F",kt,wt),Ee.channelInfos.agoraChannelToken=kt,Ee.channelInfos.agoraUserId=wt,Ke()},es=async Ke=>{console.log(">>>>>\u8C03\u7528\u83B7\u53D6channel\u4FE1\u606F");const fe=re.user,Xt=Ee.channelInfos.channelName;if(!fe&&!Xt)return;const{result:kt}=await yne(re,{username:fe,channelName:Xt});console.log("+_+_+_+_+_+\u83B7\u53D6\u623F\u95F4\u5185\u7528\u6237\u4FE1\u606F",kt),Ee.channelInfos.channelUsers={...kt},Ke()},Kt=({groupId:Ke})=>{Ae("onInviteMembers",{groupId:Ke}),console.log("\u53EF\u4EE5\u5BF9\u901A\u77E5\u89E6\u53D1\u4E86\u9080\u8BF7\u4E8B\u4EF6")};return He({sendInviteMessage:Yn,inMultiChanelSendInviteMsg:en}),qte(()=>{we()}),(Ke,fe)=>(ar(),to("div",fie,[Me(Ee).localClientStatus===Me(Vt).receivedConfirmRing?(ar(),Cx(Vne,{key:0,callKitStatus:Me(Ee),onUpdateLocalStatus:Me(be),onHandleSendAnswerMsg:Ni},null,8,["callKitStatus","onUpdateLocalStatus"])):Xu("",!0),(ar(),Cx(Zte(bt[Me(et)]),{callKitStatus:Me(Ee),loginUserHxId:St.value,onGetAgoraRtcToken:br,onGetAgoraChannelDetails:es,onUpdateLocalStatus:Me(be),onOnInviteMembers:Kt,onHandleCancelCall:$n,onHandleVideoToVioce:Ir},null,40,["callKitStatus","loginUserHxId","onUpdateLocalStatus"]))]))}},Sie=$d(gie,[["__scopeId","data-v-62d6e96d"]]),Tie={class:"app-container"},Rie=["src"],vie={__name:"index",setup(gt){const He=bn(null),dt=bn(null),Ye=bn(null),Ae=({groupId:Ze})=>{dt.value.alertDialog(Ze)},re=Ze=>{He.value.inMultiChanelSendInviteMsg(Ze,2)};vne(),Qte();const le=Tx(),Xe=Ju(),we=bn("conversation"),St=bn("conversation"),Tt=bn({}),bt=(Ze,lt={})=>{we.value=Ze,Tt.value=lt,Ze==="contactInfos"&&(we.value="contacts")}
188,et=(Ze,lt={})=>{console.log(Ze,lt),St.value=Ze,Tt.value=lt,Ze==="contactInfos"&&(St.value="contacts"),Ze==="message"&&(we.value="conversation",Ye.value.toChatMessage(lt.id,lt.chatType))};$te("IM_IS_OPEN_CUSTOM_SERVER_CONFIG",!1),JSON.parse(localStorage.getItem("webimConfig"));const Ee=window.localStorage.getItem("EASEIM_loginUser");JSON.parse(Ee);const on=bn(!1),be=async()=>{const{clickRing:Ze}=Nx();Ze(),on.value=!0;try{let{accessToken:lt}=await Oi.open({username:le.user.easemobUserName,accessToken:le.user.easemobUserToken});window.localStorage.setItem("EASEIM_loginUser",JSON.stringify({username:le.user.easemobUserName,accessToken:le.user.easemobUserToken}))}catch(lt){console.log(lt)}finally{on.value=!1}},{CHAT_TYPE:kn}=one,{EVENT_NAME:Yn,CALLKIT_EVENT_CODE:en,SUB_CHANNEL_EVENT:Xn,UN_SUB_CHANNEL_ENENT:sn}=xm();return Xn(Yn,Ze=>{console.log("%c>>>>>>\u8BA2\u9605\u4E8B\u4EF6\u89E6\u53D1","color:blue",Ze);const{type:lt,ext:Wt,callType:wn,eventHxId:Wi}=Ze;if(lt.code===en.CALLEE_REFUSE||lt.code===en.CALLEE_BUSY||lt.code===en.OTHER_HANDLE){yx({type:"error",message:Wt.message,center:!0});const Ni={from:bx.user,to:Wi,chatType:wn===2?kn.GROUP:kn.SINGLE,msg:Wt.message};Xe.createInformMessage({...Ni})}else if(lt.code===en.NOT_HAVE_MICROPHONE||lt.code===en.NOT_HAVE_CAMERA)yx({type:"warning",message:Wt.message,center:!0});else if(Wi){const Ni={from:bx.user,to:Wi,chatType:wn===2?kn.GROUP:kn.SINGLE,msg:Wt.message};Xe.createInformMessage({...Ni})}}),nA(()=>{be()}),iA(()=>{sn(Yn)}),(Ze,lt)=>{const Wt=ene,wn=tne,Wi=nne;return ar(),to(Vm,null,[ye("div",Tie,[Qo(Wi,{class:"chat_container"},{default:aA(()=>[Qo(Wt,{class:"chat_nav_bar",width:"72px"},{default:aA(()=>[Qo(Me(ane),{"current-view":we.value,onSwitchView:bt},null,8,["current-view"])]),_:1}),Qo(wn,{class:"chat_main_box"},{default:aA(()=>[bi(Qo(Me(cne),{ref_key:"conversationRef",ref:Ye,onSwitchView:et},null,512),[[wi,we.value=="conversation"]]),bi(Qo(Me(dne),{onSwitchView:et},null,512),[[wi,we.value==="contacts"]])]),_:1})]),_:1}),ye("audio",{id:"ring",src:Me(Ane),controls:"",hidden:""},null,8,Rie)]),Qo(Me(Sie),{ref_key:"easeCallKit",ref:He,EaseIMClient:Me(Oi),msgCreateFunc:Me(Oi).Message,onOnInviteMembers:Ae},null,8,["EaseIMClient","msgCreateFunc"]),Qo(Me(_ne),{ref_key:"inviteCallComp",ref:dt,onSendMulitInviteMsg:re},null,512)],64)}}},Aie=$d(vie,[["__scopeId","data-v-8079edba"]]);export{Aie as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.