From 8d8ea0580d184e165ef676977004ed65ea11db18 Mon Sep 17 00:00:00 2001 From: AdwaithAthman Date: Thu, 21 Dec 2023 11:02:49 +0530 Subject: [PATCH] Updated dist --- client/dist/assets/ChatPage-7360094c.js | 250 ++ client/dist/assets/ChatPage-a822549c.css | 1 + client/dist/assets/HomePage-6aa90e32.js | 3 + client/dist/assets/ImageCropper-d68e4cbb.js | 107 + client/dist/assets/PeoplePage-6dd427a0.js | 1 + client/dist/assets/ProfilePage-bf24045d.js | 7 + client/dist/assets/SharedPostPage-5016eed8.js | 2 + client/dist/assets/index-22c2fa6b.js | 1 + client/dist/assets/index-25380988.css | 6 + client/dist/assets/index-50c9551a.js | 3066 ----------------- client/dist/assets/index-7c9a26da.js | 2701 +++++++++++++++ client/dist/assets/index-f8f955eb.css | 6 - client/dist/assets/index.esm-d84a1b1e.js | 1 + client/dist/index.html | 4 +- .../Components/Skeletons/HomePageLoading.tsx | 1 - 15 files changed, 3082 insertions(+), 3075 deletions(-) create mode 100644 client/dist/assets/ChatPage-7360094c.js create mode 100644 client/dist/assets/ChatPage-a822549c.css create mode 100644 client/dist/assets/HomePage-6aa90e32.js create mode 100644 client/dist/assets/ImageCropper-d68e4cbb.js create mode 100644 client/dist/assets/PeoplePage-6dd427a0.js create mode 100644 client/dist/assets/ProfilePage-bf24045d.js create mode 100644 client/dist/assets/SharedPostPage-5016eed8.js create mode 100644 client/dist/assets/index-22c2fa6b.js create mode 100644 client/dist/assets/index-25380988.css delete mode 100644 client/dist/assets/index-50c9551a.js create mode 100644 client/dist/assets/index-7c9a26da.js delete mode 100644 client/dist/assets/index-f8f955eb.css create mode 100644 client/dist/assets/index.esm-d84a1b1e.js diff --git a/client/dist/assets/ChatPage-7360094c.js b/client/dist/assets/ChatPage-7360094c.js new file mode 100644 index 0000000..2a4a064 --- /dev/null +++ b/client/dist/assets/ChatPage-7360094c.js @@ -0,0 +1,250 @@ +import{X as hooks,j as jsxRuntimeExports,C as CONSTANTS_COMMON,u as useSelector,r as reactExports,a as useDispatch,Q,T as TOAST_ACTION,t as setSelectedChat,Y as setFetchUserChatsAgain,b as react,Z as searchUsers,k,A as AiOutlineCloseCircle,L as Link,_ as ConfirmDeleteToast,$ as setChats,a0 as commonjsGlobal,a1 as getDefaultExportFromCjs,a2 as React,a3 as getAllMessagesFromChat,D as classnames,a4 as InputEmojiWithRef,a5 as ImAttachment,a6 as sendMessageWithImg,a7 as sendMessage,a8 as setJoinVideoRoom,a9 as FaArrowLeft,v as setOpenVideoCall,q as MdVideoCall,aa as SlOptionsVertical,ab as BiSearchAlt,ac as AiOutlinePlusCircle,m as useNavigate,c as getUserInfo,s as store,d as setCredentials,P as isAxiosError}from"./index-7c9a26da.js";import{u as updateGroupChat,a as addGroupDp,r as removeFromGroup,g as groupRemove,f as fetchOtherUserChat,c as createGroupChat,b as fetchChats}from"./index-22c2fa6b.js";const getSender=(e,r)=>r[0]._id===e?r[1]:r[0],groupByDate=e=>e.reduce((r,s)=>{const d=hooks(s.createdAt).format("LL");return r[d]||(r[d]=[]),r[d].push(s),r},{}),truncate=(e,r)=>{if(!(!e||typeof e!="string"))return e.length<=r?e:e.slice(0,r)+"..."},UserCard=({user:e})=>jsxRuntimeExports.jsx("div",{className:`flex w-full px-4 py-2 mb-5 items-center justify-between transition duration-100 + ease-in-out rounded-lg shadow-md hover:scale-95 hover:rounded-lg cursor-pointer + bg-[#E8E8E8] hover:bg-blue-gray-600 group`,children:jsxRuntimeExports.jsxs("div",{className:"s) => setLimt-3 flex items-center space-x-2",children:[jsxRuntimeExports.jsx("img",{className:"inline-block h-12 w-12 rounded-full",src:e.dp?e.dp:CONSTANTS_COMMON.DEFAULT_IMG,alt:"user dp"}),jsxRuntimeExports.jsxs("span",{className:"flex flex-col",children:[jsxRuntimeExports.jsx("span",{className:"text-[14px] font-medium text-gray-900 group-hover:text-white group-hover:font-bold",children:e.name}),jsxRuntimeExports.jsxs("span",{className:"text-[11px] font-medium text-gray-500 group-hover:text-white group-hover:font-bold",children:["@",e.username]})]})]})}),ChatLoading=()=>jsxRuntimeExports.jsx("div",{className:"border border-blue-300 shadow rounded-lg p-3 w-full mx-auto",children:jsxRuntimeExports.jsxs("div",{className:"animate-pulse flex space-x-4",children:[jsxRuntimeExports.jsx("div",{className:"rounded-full bg-blue-gray-700 h-10 w-10"}),jsxRuntimeExports.jsx("div",{className:"flex-1 space-y-6 py-1",children:jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx("div",{className:"h-2 bg-blue-gray-700 rounded"}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[jsxRuntimeExports.jsx("div",{className:"h-2 bg-blue-gray-700 rounded col-span-2"}),jsxRuntimeExports.jsx("div",{className:"h-2 bg-blue-gray-700 rounded col-span-1"})]})]})})]})}),AdminGroupEdit=({updateGroup:e,setUpdateGroup:r,handleOpenOptions:s,setDisableUpdate:d,socket:f})=>{const _=useSelector(cE=>cE.chat.selectedChat),C=useSelector(cE=>{var _E;return(_E=cE.auth.user)==null?void 0:_E._id}),[P,x]=reactExports.useState((_==null?void 0:_.chatName)??""),[B,_t]=reactExports.useState(""),[ue,Wt]=reactExports.useState((_==null?void 0:_.users)??[]),[_n,_i]=reactExports.useState(),[Ei,_a]=reactExports.useState([]),[Di,_o]=reactExports.useState(!1),[_s,_c]=reactExports.useState(new FormData),[_m,Qm]=reactExports.useState(new FormData),tE=useDispatch();reactExports.useEffect(()=>{(_==null?void 0:_.chatName)===P&&(_==null?void 0:_.users)===ue?d(!0):d(!1),_n&&d(!1)},[P,ue,_n]),reactExports.useEffect(()=>{let cE;const _E=async()=>{try{_o(!0);const iE=await searchUsers(B);_o(!1),_a(iE.users)}catch{Q.dismiss(),Q.error("Failed to load search results",TOAST_ACTION)}};return B.length>0&&(cE=setTimeout(_E,500)),()=>{clearTimeout(cE)}},[B]),reactExports.useEffect(()=>{e&&aE()},[r,e]);const aE=async()=>{if(P.trim().length===0&&ue.length===0){Q.dismiss(),Q.error("Group name and members cannot be empty",TOAST_ACTION);return}if(P!==(_==null?void 0:_.chatName)&&_s.append("chatName",P),ue!==(_==null?void 0:_.users)){const cE=ue.map(_E=>_E._id);_s.append("users",JSON.stringify(cE))}_n&&_m.append("groupDp",_n);try{let cE;Q.info("Updating group...",{...TOAST_ACTION,autoClose:!1}),(P!==(_==null?void 0:_.chatName)||ue!==(_==null?void 0:_.users))&&(cE=_&&await updateGroupChat(_==null?void 0:_._id,_s)),_n&&(cE=_&&await addGroupDp(_._id,_m)),cE&&tE(setSelectedChat(cE.groupChat)),tE(setFetchUserChatsAgain(!0)),cE&&f.emit("group updation",cE.groupChat),Q.dismiss(),r(!1),Q.success("Group updated successfully",TOAST_ACTION),Qm(new FormData),_c(new FormData),s()}catch{Q.dismiss(),Q.error("Failed to update group",TOAST_ACTION)}},RE=cE=>{Wt(ue.filter(_E=>_E!==cE))},lE=cE=>{if(ue.some(_E=>_E._id===cE._id)){Q.dismiss(),Q.warn("User already added",TOAST_ACTION);return}else Wt([...ue,cE])},gE=cE=>{cE.target.files&&cE.target.files.length>0&&_i(cE.target.files[0])};return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(react.Typography,{className:"-mb-2",variant:"h6",children:"Add Image"}),jsxRuntimeExports.jsxs("div",{className:"mx-auto",children:[jsxRuntimeExports.jsx("input",{type:"file",accept:"image/*",id:"newGroup-image",className:"hidden",onChange:gE}),jsxRuntimeExports.jsx("label",{htmlFor:"newGroup-image",children:jsxRuntimeExports.jsx("img",{src:_n instanceof File?URL.createObjectURL(_n):_==null?void 0:_.groupDp,className:"h-36 w-36 rounded-full border-4 border-gray-500 border-dashed bg-white m-2 flex items-center justify-center cursor-pointer p-2"})})]}),jsxRuntimeExports.jsx(react.Typography,{className:"-mb-2",variant:"h6",children:"Group Name"}),jsxRuntimeExports.jsx(react.Input,{label:"Enter the name",size:"lg",value:P,onChange:cE=>x(cE.target.value)}),jsxRuntimeExports.jsx(react.Typography,{className:"-mb-2",variant:"h6",children:"Add Members"}),jsxRuntimeExports.jsx(react.Input,{label:"Enter the members",size:"lg",onChange:cE=>_t(cE.target.value)}),jsxRuntimeExports.jsx("div",{className:"max-h-36 overflow-y-scroll flex items-center justify-center flex-wrap gap-2 no-scrollbar",children:ue.map(cE=>cE._id!==C&&jsxRuntimeExports.jsx("div",{children:jsxRuntimeExports.jsx(react.Chip,{variant:"ghost",animate:{mount:{y:0},unmount:{y:50}},value:cE.name,onClose:()=>RE(cE),className:"rounded-full",color:"green"})},`selected-${cE._id}`))}),Di?jsxRuntimeExports.jsx("div",{className:"overflow-y-hidden flex flex-col gap-4",children:Array(3).fill(0).map((cE,_E)=>jsxRuntimeExports.jsx(ChatLoading,{},_E))}):jsxRuntimeExports.jsx("div",{className:"max-h-64 overflow-y-scroll overflow-x-hidden no-scrollbar mx-4",children:Ei==null?void 0:Ei.slice(0,4).map(cE=>cE._id!==C&&jsxRuntimeExports.jsx("div",{className:"w-full",onClick:()=>lE(cE),children:jsxRuntimeExports.jsx(UserCard,{user:cE})},`search-${cE._id}`))})]})},OptionsDialog=({openOptions:e,handleOpenOptions:r,socket:s})=>{const d=useSelector(Ei=>Ei.chat.selectedChat),f=useSelector(Ei=>{var _a;return(_a=Ei.auth.user)==null?void 0:_a._id}),_=useSelector(Ei=>Ei.chat.chats),[C,P]=reactExports.useState(!1),[x,B]=reactExports.useState(!1),_t=useDispatch(),ue=async()=>{Q.dismiss(),Q(jsxRuntimeExports.jsx(ConfirmDeleteToast,{onDelete:Wt,message:"Are you sure you want to leave this Group?"}),{...TOAST_ACTION,closeButton:!1})},Wt=async()=>{const Ei=d&&f&&await removeFromGroup(d==null?void 0:d._id,f);Ei&&(Ei==null?void 0:Ei.status)==="success"&&(Q.dismiss(),_t(setSelectedChat("")),_t(setChats(_.filter(_a=>_a._id!==(d==null?void 0:d._id)))),Q.success("Successfully left the group"),r())},_n=async()=>{Q.dismiss(),Q(jsxRuntimeExports.jsx(ConfirmDeleteToast,{onDelete:_i,message:"Are you sure you want to delete this group?"}),{...TOAST_ACTION,closeButton:!1})},_i=async()=>{const Ei=d&&await groupRemove(d==null?void 0:d._id);Ei&&(Ei==null?void 0:Ei.status)==="success"&&(Q.dismiss(),_t(setSelectedChat("")),_t(setChats(_.filter(_a=>_a._id!==(d==null?void 0:d._id)))),Q.success("Successfully deleted the group"),r())};return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:jsxRuntimeExports.jsxs(react.Dialog,{size:"xs",dismiss:{enabled:!1},open:e,handler:r,className:"bg-transparent shadow-none",children:[jsxRuntimeExports.jsx(k,{}),jsxRuntimeExports.jsxs(react.Card,{className:"mx-auto w-full ",children:[jsxRuntimeExports.jsxs(react.CardBody,{className:"flex flex-col gap-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-medium text-black",children:d!=null&&d.isGroupChat?d.chatName:"User Info"}),jsxRuntimeExports.jsx(AiOutlineCloseCircle,{className:"text-3xl cursor-pointer text-black",onClick:Ei=>{Ei.stopPropagation(),r()}})]}),d&&!d.isGroupChat?jsxRuntimeExports.jsxs("div",{className:"relative h-60 md:h-80 w-60 md:w-80 rounded-md mx-auto overflow-hidden",children:[jsxRuntimeExports.jsx("img",{src:f&&getSender(f,d.users).dp?getSender(f,d.users).dp:CONSTANTS_COMMON.DEFAULT_IMG,alt:"user dp",className:"z-0 h-full w-full rounded-md object-cover"}),jsxRuntimeExports.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-gray-900 to-transparent"}),jsxRuntimeExports.jsxs("div",{className:"absolute bottom-4 left-4 text-left",children:[jsxRuntimeExports.jsx("h1",{className:"text-lg font-semibold text-white",children:f&&getSender(f,d.users).name}),jsxRuntimeExports.jsxs("h1",{className:"text-xs font-light text-white",children:["@",f&&getSender(f,d.users).username]}),jsxRuntimeExports.jsx(Link,{to:`/profile/${f&&getSender(f,d.users)._id}`,children:jsxRuntimeExports.jsx("button",{className:"mt-2 inline-flex cursor-pointer items-center text-sm font-semibold text-white",children:"View Profile →"})})]})]}):(d==null?void 0:d.groupAdmin._id)===f?jsxRuntimeExports.jsx(AdminGroupEdit,{updateGroup:C,setUpdateGroup:P,handleOpenOptions:r,setDisableUpdate:B,socket:s}):jsxRuntimeExports.jsxs("div",{className:"max-h-96 overflow-y-scroll overflow-x-hidden no-scrollbar mx-4",children:[jsxRuntimeExports.jsx("img",{src:d==null?void 0:d.groupDp,className:"h-48 w-48 rounded-full border-4 border-gray-500 border-dashed bg-white mx-auto flex items-center justify-center p-2"}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 items-center mb-2",children:[jsxRuntimeExports.jsx("h1",{className:"text-lg font-medium",children:"Admin"}),jsxRuntimeExports.jsx("span",{className:`inline-flex items-center justify-center px-2 py-1 mr-2 text-xs + font-bold leading-none text-white bg-socioverse-400 rounded-full`,children:d&&(d==null?void 0:d.users.filter(Ei=>Ei._id===d.groupAdmin._id).length)})]}),d==null?void 0:d.users.map(Ei=>Ei._id===d.groupAdmin._id&&jsxRuntimeExports.jsx(UserCard,{user:Ei},Ei._id)),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 items-center mb-2",children:[jsxRuntimeExports.jsx("h1",{className:"text-lg font-medium",children:"Members"}),jsxRuntimeExports.jsx("span",{className:`inline-flex items-center justify-center px-2 py-1 mr-2 text-xs + font-bold leading-none text-white bg-socioverse-400 rounded-full`,children:d&&(d==null?void 0:d.users.filter(Ei=>Ei._id!==d.groupAdmin._id).length)})]}),d==null?void 0:d.users.map(Ei=>Ei._id!==d.groupAdmin._id&&jsxRuntimeExports.jsx(UserCard,{user:Ei},Ei._id))]})]}),(d==null?void 0:d.isGroupChat)&&jsxRuntimeExports.jsx(react.CardFooter,{className:"pt-0",children:d.groupAdmin._id===f?jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 float-right",children:[jsxRuntimeExports.jsx(react.Button,{className:" rounded-full text-black border-black hover:border-2 ",variant:"outlined",onClick:()=>P(!0),disabled:x,children:"Update"}),jsxRuntimeExports.jsx(react.Button,{className:" bg-socioverse-400 rounded-full",onClick:_n,children:"Leave"})]}):jsxRuntimeExports.jsx(react.Button,{className:"float-right bg-socioverse-400 rounded-full",onClick:ue,children:"Leave Group"})})]})]})})};var lottie$1={exports:{}};(function(module,exports){typeof navigator<"u"&&function(e,r){module.exports=r()}(commonjsGlobal,function(){var svgNS="http://www.w3.org/2000/svg",locationHref="",_useWebWorker=!1,initialDefaultFrame=-999999,setWebWorker=function(r){_useWebWorker=!!r},getWebWorker=function(){return _useWebWorker},setLocationHref=function(r){locationHref=r},getLocationHref=function(){return locationHref};function createTag(e){return document.createElement(e)}function extendPrototype(e,r){var s,d=e.length,f;for(s=0;s1?s[1]=1:s[1]<=0&&(s[1]=0),HSVtoRGB(s[0],s[1],s[2])}function addBrightnessToRGB(e,r){var s=RGBtoHSV(e[0]*255,e[1]*255,e[2]*255);return s[2]+=r,s[2]>1?s[2]=1:s[2]<0&&(s[2]=0),HSVtoRGB(s[0],s[1],s[2])}function addHueToRGB(e,r){var s=RGBtoHSV(e[0]*255,e[1]*255,e[2]*255);return s[0]+=r/360,s[0]>1?s[0]-=1:s[0]<0&&(s[0]+=1),HSVtoRGB(s[0],s[1],s[2])}var rgbToHex=function(){var e=[],r,s;for(r=0;r<256;r+=1)s=r.toString(16),e[r]=s.length===1?"0"+s:s;return function(d,f,_){return d<0&&(d=0),f<0&&(f=0),_<0&&(_=0),"#"+e[d]+e[f]+e[_]}}(),setSubframeEnabled=function(r){subframeEnabled=!!r},getSubframeEnabled=function(){return subframeEnabled},setExpressionsPlugin=function(r){expressionsPlugin=r},getExpressionsPlugin=function(){return expressionsPlugin},setExpressionInterfaces=function(r){expressionsInterfaces=r},getExpressionInterfaces=function(){return expressionsInterfaces},setDefaultCurveSegments=function(r){defaultCurveSegments=r},getDefaultCurveSegments=function(){return defaultCurveSegments},setIdPrefix=function(r){idPrefix$1=r};function createNS(e){return document.createElementNS(svgNS,e)}function _typeof$5(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?_typeof$5=function(s){return typeof s}:_typeof$5=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},_typeof$5(e)}var dataManager=function(){var e=1,r=[],s,d,f={onmessage:function(){},postMessage:function(_n){s({data:_n})}},_={postMessage:function(_n){f.onmessage({data:_n})}};function C(Wt){if(window.Worker&&window.Blob&&getWebWorker()){var _n=new Blob(["var _workerSelf = self; self.onmessage = ",Wt.toString()],{type:"text/javascript"}),_i=URL.createObjectURL(_n);return new Worker(_i)}return s=Wt,f}function P(){d||(d=C(function(_n){function _i(){function _a(rE,vf){var Fg,_d,_f=rE.length,uE,dE,IE,DE;for(_d=0;_d<_f;_d+=1)if(Fg=rE[_d],"ks"in Fg&&!Fg.completed){if(Fg.completed=!0,Fg.hasMask){var GE=Fg.masksProperties;for(dE=GE.length,uE=0;uE=0;vf-=1)if(rE[vf].ty==="sh")if(rE[vf].ks.k.i)_m(rE[vf].ks.k);else for(_f=rE[vf].ks.k.length,_d=0;_d<_f;_d+=1)rE[vf].ks.k[_d].s&&_m(rE[vf].ks.k[_d].s[0]),rE[vf].ks.k[_d].e&&_m(rE[vf].ks.k[_d].e[0]);else rE[vf].ty==="gr"&&_c(rE[vf].it)}function _m(rE){var vf,Fg=rE.i.length;for(vf=0;vfFg[0]?!0:Fg[0]>rE[0]?!1:rE[1]>Fg[1]?!0:Fg[1]>rE[1]?!1:rE[2]>Fg[2]?!0:Fg[2]>rE[2]?!1:null}var tE=function(){var rE=[4,4,14];function vf(_d){var _f=_d.t.d;_d.t.d={k:[{s:_f,t:0}]}}function Fg(_d){var _f,uE=_d.length;for(_f=0;_f=0;_f-=1)if(_d[_f].ty==="sh")if(_d[_f].ks.k.i)_d[_f].ks.k.c=_d[_f].closed;else for(IE=_d[_f].ks.k.length,dE=0;dE500)&&(this._imageLoaded(),clearInterval(_s)),_o+=1}).bind(this),50)}function _(Di){var _o=d(Di,this.assetsPath,this.path),_s=createNS("image");isSafari?this.testImageLoaded(_s):_s.addEventListener("load",this._imageLoaded,!1),_s.addEventListener("error",(function(){_c.img=e,this._imageLoaded()}).bind(this),!1),_s.setAttributeNS("http://www.w3.org/1999/xlink","href",_o),this._elementHelper.append?this._elementHelper.append(_s):this._elementHelper.appendChild(_s);var _c={img:_s,assetData:Di};return _c}function C(Di){var _o=d(Di,this.assetsPath,this.path),_s=createTag("img");_s.crossOrigin="anonymous",_s.addEventListener("load",this._imageLoaded,!1),_s.addEventListener("error",(function(){_c.img=e,this._imageLoaded()}).bind(this),!1),_s.src=_o;var _c={img:_s,assetData:Di};return _c}function P(Di){var _o={assetData:Di},_s=d(Di,this.assetsPath,this.path);return dataManager.loadData(_s,(function(_c){_o.img=_c,this._footageLoaded()}).bind(this),(function(){_o.img={},this._footageLoaded()}).bind(this)),_o}function x(Di,_o){this.imagesLoadedCb=_o;var _s,_c=Di.length;for(_s=0;_s<_c;_s+=1)Di[_s].layers||(!Di[_s].t||Di[_s].t==="seq"?(this.totalImages+=1,this.images.push(this._createImageData(Di[_s]))):Di[_s].t===3&&(this.totalFootages+=1,this.images.push(this.createFootageData(Di[_s]))))}function B(Di){this.path=Di||""}function _t(Di){this.assetsPath=Di||""}function ue(Di){for(var _o=0,_s=this.images.length;_o<_s;){if(this.images[_o].assetData===Di)return this.images[_o].img;_o+=1}return null}function Wt(){this.imagesLoadedCb=null,this.images.length=0}function _n(){return this.totalImages===this.loadedAssets}function _i(){return this.totalFootages===this.loadedFootagesCount}function Ei(Di,_o){Di==="svg"?(this._elementHelper=_o,this._createImageData=this.createImageData.bind(this)):this._createImageData=this.createImgData.bind(this)}function _a(){this._imageLoaded=r.bind(this),this._footageLoaded=s.bind(this),this.testImageLoaded=f.bind(this),this.createFootageData=P.bind(this),this.assetsPath="",this.path="",this.totalImages=0,this.totalFootages=0,this.loadedAssets=0,this.loadedFootagesCount=0,this.imagesLoadedCb=null,this.images=[]}return _a.prototype={loadAssets:x,setAssetsPath:_t,setPath:B,loadedImages:_n,loadedFootages:_i,destroy:Wt,getAsset:ue,createImgData:C,createImageData:_,imageLoaded:r,footageLoaded:s,setCacheType:Ei},_a}();function BaseEvent(){}BaseEvent.prototype={triggerEvent:function(r,s){if(this._cbs[r])for(var d=this._cbs[r],f=0;fthis.animationData.op&&(this.animationData.op=e.op,this.totalFrames=Math.floor(e.op-this.animationData.ip));var r=this.animationData.layers,s,d=r.length,f=e.layers,_,C=f.length;for(_=0;_this.timeCompleted&&(this.currentFrame=this.timeCompleted),this.trigger("enterFrame"),this.renderFrame(),this.trigger("drawnFrame")},AnimationItem.prototype.renderFrame=function(){if(!(this.isLoaded===!1||!this.renderer))try{this.expressionsPlugin&&this.expressionsPlugin.resetFrame(),this.renderer.renderFrame(this.currentFrame+this.firstFrame)}catch(e){this.triggerRenderFrameError(e)}},AnimationItem.prototype.play=function(e){e&&this.name!==e||this.isPaused===!0&&(this.isPaused=!1,this.trigger("_play"),this.audioController.resume(),this._idle&&(this._idle=!1,this.trigger("_active")))},AnimationItem.prototype.pause=function(e){e&&this.name!==e||this.isPaused===!1&&(this.isPaused=!0,this.trigger("_pause"),this._idle=!0,this.trigger("_idle"),this.audioController.pause())},AnimationItem.prototype.togglePause=function(e){e&&this.name!==e||(this.isPaused===!0?this.play():this.pause())},AnimationItem.prototype.stop=function(e){e&&this.name!==e||(this.pause(),this.playCount=0,this._completedLoop=!1,this.setCurrentRawFrameValue(0))},AnimationItem.prototype.getMarkerData=function(e){for(var r,s=0;s=this.totalFrames-1&&this.frameModifier>0?!this.loop||this.playCount===this.loop?this.checkSegments(r>this.totalFrames?r%this.totalFrames:0)||(s=!0,r=this.totalFrames-1):r>=this.totalFrames?(this.playCount+=1,this.checkSegments(r%this.totalFrames)||(this.setCurrentRawFrameValue(r%this.totalFrames),this._completedLoop=!0,this.trigger("loopComplete"))):this.setCurrentRawFrameValue(r):r<0?this.checkSegments(r%this.totalFrames)||(this.loop&&!(this.playCount--<=0&&this.loop!==!0)?(this.setCurrentRawFrameValue(this.totalFrames+r%this.totalFrames),this._completedLoop?this.trigger("loopComplete"):this._completedLoop=!0):(s=!0,r=0)):this.setCurrentRawFrameValue(r),s&&(this.setCurrentRawFrameValue(r),this.pause(),this.trigger("complete"))}},AnimationItem.prototype.adjustSegment=function(e,r){this.playCount=0,e[1]0&&(this.playSpeed<0?this.setSpeed(-this.playSpeed):this.setDirection(-1)),this.totalFrames=e[0]-e[1],this.timeCompleted=this.totalFrames,this.firstFrame=e[1],this.setCurrentRawFrameValue(this.totalFrames-.001-r)):e[1]>e[0]&&(this.frameModifier<0&&(this.playSpeed<0?this.setSpeed(-this.playSpeed):this.setDirection(1)),this.totalFrames=e[1]-e[0],this.timeCompleted=this.totalFrames,this.firstFrame=e[0],this.setCurrentRawFrameValue(.001+r)),this.trigger("segmentStart")},AnimationItem.prototype.setSegment=function(e,r){var s=-1;this.isPaused&&(this.currentRawFrame+this.firstFramer&&(s=r-e)),this.firstFrame=e,this.totalFrames=r-e,this.timeCompleted=this.totalFrames,s!==-1&&this.goToAndStop(s,!0)},AnimationItem.prototype.playSegments=function(e,r){if(r&&(this.segments.length=0),_typeof$4(e[0])==="object"){var s,d=e.length;for(s=0;s=0;Fg-=1)r[Fg].animation.destroy(vf)}function aE(vf,Fg,_d){var _f=[].concat([].slice.call(document.getElementsByClassName("lottie")),[].slice.call(document.getElementsByClassName("bodymovin"))),uE,dE=_f.length;for(uE=0;uE0?_c=aE:_s=aE;while(Math.abs(tE)>_&&++RE=f?_a(_s,gE,_c,_m):cE===0?gE:Ei(_s,tE,tE+x,_c,_m)}},e}(),pooling=function(){function e(r){return r.concat(createSizedArray(r.length))}return{double:e}}(),poolFactory=function(){return function(e,r,s){var d=0,f=e,_=createSizedArray(f),C={newElement:P,release:x};function P(){var B;return d?(d-=1,B=_[d]):B=r(),B}function x(B){d===f&&(_=pooling.double(_),f*=2),s&&s(B),_[d]=B,d+=1}return C}}(),bezierLengthPool=function(){function e(){return{addedLength:0,percents:createTypedArray("float32",getDefaultCurveSegments()),lengths:createTypedArray("float32",getDefaultCurveSegments())}}return poolFactory(8,e)}(),segmentsLengthPool=function(){function e(){return{lengths:[],totalLength:0}}function r(s){var d,f=s.lengths.length;for(d=0;d-.001&&_o<.001}function s(Wt,_n,_i,Ei,_a,Di,_o,_s,_c){if(_i===0&&Di===0&&_c===0)return r(Wt,_n,Ei,_a,_o,_s);var _m=e.sqrt(e.pow(Ei-Wt,2)+e.pow(_a-_n,2)+e.pow(Di-_i,2)),Qm=e.sqrt(e.pow(_o-Wt,2)+e.pow(_s-_n,2)+e.pow(_c-_i,2)),tE=e.sqrt(e.pow(_o-Ei,2)+e.pow(_s-_a,2)+e.pow(_c-Di,2)),aE;return _m>Qm?_m>tE?aE=_m-Qm-tE:aE=tE-Qm-_m:tE>Qm?aE=tE-Qm-_m:aE=Qm-_m-tE,aE>-1e-4&&aE<1e-4}var d=function(){return function(Wt,_n,_i,Ei){var _a=getDefaultCurveSegments(),Di,_o,_s,_c,_m,Qm=0,tE,aE=[],RE=[],lE=bezierLengthPool.newElement();for(_s=_i.length,Di=0;Di<_a;Di+=1){for(_m=Di/(_a-1),tE=0,_o=0;_o<_s;_o+=1)_c=bmPow(1-_m,3)*Wt[_o]+3*bmPow(1-_m,2)*_m*_i[_o]+3*(1-_m)*bmPow(_m,2)*Ei[_o]+bmPow(_m,3)*_n[_o],aE[_o]=_c,RE[_o]!==null&&(tE+=bmPow(aE[_o]-RE[_o],2)),RE[_o]=aE[_o];tE&&(tE=bmSqrt(tE),Qm+=tE),lE.percents[Di]=_m,lE.lengths[Di]=Qm}return lE.addedLength=Qm,lE}}();function f(Wt){var _n=segmentsLengthPool.newElement(),_i=Wt.c,Ei=Wt.v,_a=Wt.o,Di=Wt.i,_o,_s=Wt._length,_c=_n.lengths,_m=0;for(_o=0;_o<_s-1;_o+=1)_c[_o]=d(Ei[_o],Ei[_o+1],_a[_o],Di[_o+1]),_m+=_c[_o].addedLength;return _i&&_s&&(_c[_o]=d(Ei[_o],Ei[0],_a[_o],Di[0]),_m+=_c[_o].addedLength),_n.totalLength=_m,_n}function _(Wt){this.segmentLength=0,this.points=new Array(Wt)}function C(Wt,_n){this.partialLength=Wt,this.point=_n}var P=function(){var Wt={};return function(_n,_i,Ei,_a){var Di=(_n[0]+"_"+_n[1]+"_"+_i[0]+"_"+_i[1]+"_"+Ei[0]+"_"+Ei[1]+"_"+_a[0]+"_"+_a[1]).replace(/\./g,"p");if(!Wt[Di]){var _o=getDefaultCurveSegments(),_s,_c,_m,Qm,tE,aE=0,RE,lE,gE=null;_n.length===2&&(_n[0]!==_i[0]||_n[1]!==_i[1])&&r(_n[0],_n[1],_i[0],_i[1],_n[0]+Ei[0],_n[1]+Ei[1])&&r(_n[0],_n[1],_i[0],_i[1],_i[0]+_a[0],_i[1]+_a[1])&&(_o=2);var cE=new _(_o);for(_m=Ei.length,_s=0;_s<_o;_s+=1){for(lE=createSizedArray(_m),tE=_s/(_o-1),RE=0,_c=0;_c<_m;_c+=1)Qm=bmPow(1-tE,3)*_n[_c]+3*bmPow(1-tE,2)*tE*(_n[_c]+Ei[_c])+3*(1-tE)*bmPow(tE,2)*(_i[_c]+_a[_c])+bmPow(tE,3)*_i[_c],lE[_c]=Qm,gE!==null&&(RE+=bmPow(lE[_c]-gE[_c],2));RE=bmSqrt(RE),aE+=RE,cE.points[_s]=new C(RE,lE),gE=lE}cE.segmentLength=aE,Wt[Di]=cE}return Wt[Di]}}();function x(Wt,_n){var _i=_n.percents,Ei=_n.lengths,_a=_i.length,Di=bmFloor((_a-1)*Wt),_o=Wt*_n.addedLength,_s=0;if(Di===_a-1||Di===0||_o===Ei[Di])return _i[Di];for(var _c=Ei[Di]>_o?-1:1,_m=!0;_m;)if(Ei[Di]<=_o&&Ei[Di+1]>_o?(_s=(_o-Ei[Di])/(Ei[Di+1]-Ei[Di]),_m=!1):Di+=_c,Di<0||Di>=_a-1){if(Di===_a-1)return _i[Di];_m=!1}return _i[Di]+(_i[Di+1]-_i[Di])*_s}function B(Wt,_n,_i,Ei,_a,Di){var _o=x(_a,Di),_s=1-_o,_c=e.round((_s*_s*_s*Wt[0]+(_o*_s*_s+_s*_o*_s+_s*_s*_o)*_i[0]+(_o*_o*_s+_s*_o*_o+_o*_s*_o)*Ei[0]+_o*_o*_o*_n[0])*1e3)/1e3,_m=e.round((_s*_s*_s*Wt[1]+(_o*_s*_s+_s*_o*_s+_s*_s*_o)*_i[1]+(_o*_o*_s+_s*_o*_o+_o*_s*_o)*Ei[1]+_o*_o*_o*_n[1])*1e3)/1e3;return[_c,_m]}var _t=createTypedArray("float32",8);function ue(Wt,_n,_i,Ei,_a,Di,_o){_a<0?_a=0:_a>1&&(_a=1);var _s=x(_a,_o);Di=Di>1?1:Di;var _c=x(Di,_o),_m,Qm=Wt.length,tE=1-_s,aE=1-_c,RE=tE*tE*tE,lE=_s*tE*tE*3,gE=_s*_s*tE*3,cE=_s*_s*_s,_E=tE*tE*aE,iE=_s*tE*aE+tE*_s*aE+tE*tE*_c,rE=_s*_s*aE+tE*_s*_c+_s*tE*_c,vf=_s*_s*_c,Fg=tE*aE*aE,_d=_s*aE*aE+tE*_c*aE+tE*aE*_c,_f=_s*_c*aE+tE*_c*_c+_s*aE*_c,uE=_s*_c*_c,dE=aE*aE*aE,IE=_c*aE*aE+aE*_c*aE+aE*aE*_c,DE=_c*_c*aE+aE*_c*_c+_c*aE*_c,GE=_c*_c*_c;for(_m=0;_m=B.t-s){x.h&&(x=B),f=0;break}if(B.t-s>e){f=_;break}_=Di||e<_o){var _m=e>=Di?_c.points.length-1:0;for(Wt=_c.points[_m].point.length,ue=0;ue=aE&&Qm=Di)d[0]=_s[0],d[1]=_s[1],d[2]=_s[2];else if(e<=_o)d[0]=x.s[0],d[1]=x.s[1],d[2]=x.s[2];else{var iE=createQuaternion(x.s),rE=createQuaternion(_s),vf=(e-_o)/(Di-_o);quaternionToEuler(d,slerp(iE,rE,vf))}else for(_=0;_=Di?_n=1:e<_o?_n=0:(x.o.x.constructor===Array?(_t.__fnct||(_t.__fnct=[]),_t.__fnct[_]?_a=_t.__fnct[_]:(RE=x.o.x[_]===void 0?x.o.x[0]:x.o.x[_],lE=x.o.y[_]===void 0?x.o.y[0]:x.o.y[_],gE=x.i.x[_]===void 0?x.i.x[0]:x.i.x[_],cE=x.i.y[_]===void 0?x.i.y[0]:x.i.y[_],_a=BezierFactory.getBezierEasing(RE,lE,gE,cE).get,_t.__fnct[_]=_a)):_t.__fnct?_a=_t.__fnct:(RE=x.o.x,lE=x.o.y,gE=x.i.x,cE=x.i.y,_a=BezierFactory.getBezierEasing(RE,lE,gE,cE).get,x.keyframeMetadata=_a),_n=_a((e-_o)/(Di-_o)))),_s=B.s||x.e,_E=x.h===1?x.s[_]:x.s[_]+(_s[_]-x.s[_])*_n,this.propType==="multidimensional"?d[_]=_E:d=_E}return r.lastIndex=f,d}function slerp(e,r,s){var d=[],f=e[0],_=e[1],C=e[2],P=e[3],x=r[0],B=r[1],_t=r[2],ue=r[3],Wt,_n,_i,Ei,_a;return _n=f*x+_*B+C*_t+P*ue,_n<0&&(_n=-_n,x=-x,B=-B,_t=-_t,ue=-ue),1-_n>1e-6?(Wt=Math.acos(_n),_i=Math.sin(Wt),Ei=Math.sin((1-s)*Wt)/_i,_a=Math.sin(s*Wt)/_i):(Ei=1-s,_a=s),d[0]=Ei*f+_a*x,d[1]=Ei*_+_a*B,d[2]=Ei*C+_a*_t,d[3]=Ei*P+_a*ue,d}function quaternionToEuler(e,r){var s=r[0],d=r[1],f=r[2],_=r[3],C=Math.atan2(2*d*_-2*s*f,1-2*d*d-2*f*f),P=Math.asin(2*s*d+2*f*_),x=Math.atan2(2*s*_-2*d*f,1-2*s*s-2*f*f);e[0]=C/degToRads,e[1]=P/degToRads,e[2]=x/degToRads}function createQuaternion(e){var r=e[0]*degToRads,s=e[1]*degToRads,d=e[2]*degToRads,f=Math.cos(r/2),_=Math.cos(s/2),C=Math.cos(d/2),P=Math.sin(r/2),x=Math.sin(s/2),B=Math.sin(d/2),_t=f*_*C-P*x*B,ue=P*x*C+f*_*B,Wt=P*_*C+f*x*B,_n=f*x*C-P*_*B;return[ue,Wt,_n,_t]}function getValueAtCurrentTime(){var e=this.comp.renderedFrame-this.offsetTime,r=this.keyframes[0].t-this.offsetTime,s=this.keyframes[this.keyframes.length-1].t-this.offsetTime;if(!(e===this._caching.lastFrame||this._caching.lastFrame!==initFrame&&(this._caching.lastFrame>=s&&e>=s||this._caching.lastFrame=e&&(this._caching._lastKeyframeIndex=-1,this._caching.lastIndex=0);var d=this.interpolateValue(e,this._caching);this.pv=d}return this._caching.lastFrame=e,this.pv}function setVValue(e){var r;if(this.propType==="unidimensional")r=e*this.mult,mathAbs(this.v-r)>1e-5&&(this.v=r,this._mdf=!0);else for(var s=0,d=this.v.length;s1e-5&&(this.v[s]=r,this._mdf=!0),s+=1}function processEffectsSequence(){if(!(this.elem.globalData.frameId===this.frameId||!this.effectsSequence.length)){if(this.lock){this.setVValue(this.pv);return}this.lock=!0,this._mdf=this._isFirstFrame;var e,r=this.effectsSequence.length,s=this.kf?this.pv:this.data.k;for(e=0;e=this._maxLength&&this.doubleArrayLength(),s){case"v":_=this.v;break;case"i":_=this.i;break;case"o":_=this.o;break;default:_=[];break}(!_[d]||_[d]&&!f)&&(_[d]=pointPool.newElement()),_[d][0]=e,_[d][1]=r},ShapePath.prototype.setTripleAt=function(e,r,s,d,f,_,C,P){this.setXYAt(e,r,"v",C,P),this.setXYAt(s,d,"o",C,P),this.setXYAt(f,_,"i",C,P)},ShapePath.prototype.reverse=function(){var e=new ShapePath;e.setPathData(this.c,this._length);var r=this.v,s=this.o,d=this.i,f=0;this.c&&(e.setTripleAt(r[0][0],r[0][1],d[0][0],d[0][1],s[0][0],s[0][1],0,!1),f=1);var _=this._length-1,C=this._length,P;for(P=f;P=iE[iE.length-1].t-this.offsetTime)_m=iE[iE.length-1].s?iE[iE.length-1].s[0]:iE[iE.length-2].e[0],tE=!0;else{for(var rE=_c,vf=iE.length-1,Fg=!0,_d,_f,uE;Fg&&(_d=iE[rE],_f=iE[rE+1],!(_f.t-this.offsetTime>Di));)rE=_f.t-this.offsetTime)cE=1;else if(Di<_d.t-this.offsetTime)cE=0;else{var dE;uE.__fnct?dE=uE.__fnct:(dE=BezierFactory.getBezierEasing(_d.o.x,_d.o.y,_d.i.x,_d.i.y).get,uE.__fnct=dE),cE=dE((Di-(_d.t-this.offsetTime))/(_f.t-this.offsetTime-(_d.t-this.offsetTime)))}Qm=_f.s?_f.s[0]:_d.e[0]}_m=_d.s[0]}for(lE=_o._length,gE=_m.i[0].length,_s.lastIndex=_c,aE=0;aE_s&&Di>_s)||(this._caching.lastIndex=_c0||_d>-1e-6&&_d<0?d(_d*_f)/_f:_d}function Fg(){var _d=this.props,_f=vf(_d[0]),uE=vf(_d[1]),dE=vf(_d[4]),IE=vf(_d[5]),DE=vf(_d[12]),GE=vf(_d[13]);return"matrix("+_f+","+uE+","+dE+","+IE+","+DE+","+GE+")"}return function(){this.reset=f,this.rotate=_,this.rotateX=C,this.rotateY=P,this.rotateZ=x,this.skew=_t,this.skewFromAxis=ue,this.shear=B,this.scale=Wt,this.setTransform=_n,this.translate=_i,this.transform=Ei,this.multiply=_a,this.applyToPoint=_m,this.applyToX=Qm,this.applyToY=tE,this.applyToZ=aE,this.applyToPointArray=_E,this.applyToTriplePoints=cE,this.applyToPointStringified=iE,this.toCSS=rE,this.to2dCSS=Fg,this.clone=_s,this.cloneFromProps=_c,this.equals=_o,this.inversePoints=gE,this.inversePoint=lE,this.getInverseMatrix=RE,this._t=this.transform,this.isIdentity=Di,this._identity=!0,this._identityCalculated=!1,this.props=createTypedArray("float32",16),this.reset()}}();function _typeof$3(e){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?_typeof$3=function(s){return typeof s}:_typeof$3=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},_typeof$3(e)}var lottie={};function setLocation(e){setLocationHref(e)}function searchAnimations(){animationManager.searchAnimations()}function setSubframeRendering(e){setSubframeEnabled(e)}function setPrefix(e){setIdPrefix(e)}function loadAnimation(e){return animationManager.loadAnimation(e)}function setQuality(e){if(typeof e=="string")switch(e){case"high":setDefaultCurveSegments(200);break;default:case"medium":setDefaultCurveSegments(50);break;case"low":setDefaultCurveSegments(10);break}else!isNaN(e)&&e>1&&setDefaultCurveSegments(e)}function inBrowser(){return typeof navigator<"u"}function installPlugin(e,r){e==="expressions"&&setExpressionsPlugin(r)}function getFactory(e){switch(e){case"propertyFactory":return PropertyFactory;case"shapePropertyFactory":return ShapePropertyFactory;case"matrix":return Matrix;default:return null}}lottie.play=animationManager.play,lottie.pause=animationManager.pause,lottie.setLocationHref=setLocation,lottie.togglePause=animationManager.togglePause,lottie.setSpeed=animationManager.setSpeed,lottie.setDirection=animationManager.setDirection,lottie.stop=animationManager.stop,lottie.searchAnimations=searchAnimations,lottie.registerAnimation=animationManager.registerAnimation,lottie.loadAnimation=loadAnimation,lottie.setSubframeRendering=setSubframeRendering,lottie.resize=animationManager.resize,lottie.goToAndStop=animationManager.goToAndStop,lottie.destroy=animationManager.destroy,lottie.setQuality=setQuality,lottie.inBrowser=inBrowser,lottie.installPlugin=installPlugin,lottie.freeze=animationManager.freeze,lottie.unfreeze=animationManager.unfreeze,lottie.setVolume=animationManager.setVolume,lottie.mute=animationManager.mute,lottie.unmute=animationManager.unmute,lottie.getRegisteredAnimations=animationManager.getRegisteredAnimations,lottie.useWebWorker=setWebWorker,lottie.setIDPrefix=setPrefix,lottie.__getFactory=getFactory,lottie.version="5.12.2";function checkReady(){document.readyState==="complete"&&(clearInterval(readyStateCheckInterval),searchAnimations())}function getQueryVariable(e){for(var r=queryString.split("&"),s=0;s=1?_.push({s:e-1,e:r-1}):(_.push({s:e,e:1}),_.push({s:0,e:r-1}));var C=[],P,x=_.length,B;for(P=0;Pd+s)){var _t,ue;B.s*f<=d?_t=0:_t=(B.s*f-d)/s,B.e*f>=d+s?ue=1:ue=(B.e*f-d)/s,C.push([_t,ue])}return C.length||C.push([0,0]),C},TrimModifier.prototype.releasePathsData=function(e){var r,s=e.length;for(r=0;r1?r=1+d:this.s.v<0?r=0+d:r=this.s.v+d,this.e.v>1?s=1+d:this.e.v<0?s=0+d:s=this.e.v+d,r>s){var f=r;r=s,s=f}r=Math.round(r*1e4)*1e-4,s=Math.round(s*1e4)*1e-4,this.sValue=r,this.eValue=s}else r=this.sValue,s=this.eValue;var _,C,P=this.shapes.length,x,B,_t,ue,Wt,_n=0;if(s===r)for(C=0;C=0;C-=1)if(Ei=this.shapes[C],Ei.shape._mdf){for(_a=Ei.localShapeCollection,_a.releaseShapes(),this.m===2&&P>1?(_c=this.calculateShapeEdges(r,s,Ei.totalShapeLength,_s,_n),_s+=Ei.totalShapeLength):_c=[[Di,_o]],B=_c.length,x=0;x=1?_i.push({s:Ei.totalShapeLength*(Di-1),e:Ei.totalShapeLength*(_o-1)}):(_i.push({s:Ei.totalShapeLength*Di,e:Ei.totalShapeLength}),_i.push({s:0,e:Ei.totalShapeLength*(_o-1)}));var _m=this.addShapes(Ei,_i[0]);if(_i[0].s!==_i[0].e){if(_i.length>1){var Qm=Ei.shape.paths.shapes[Ei.shape.paths._length-1];if(Qm.c){var tE=_m.pop();this.addPaths(_m,_a),_m=this.addShapes(Ei,_i[1],tE)}else this.addPaths(_m,_a),_m=this.addShapes(Ei,_i[1])}this.addPaths(_m,_a)}}Ei.shape.paths=_a}}},TrimModifier.prototype.addPaths=function(e,r){var s,d=e.length;for(s=0;sr.e){s.c=!1;break}else r.s<=B&&r.e>=B+_t.addedLength?(this.addSegment(f[_].v[P-1],f[_].o[P-1],f[_].i[P],f[_].v[P],s,ue,_a),_a=!1):(_n=bez.getNewSegment(f[_].v[P-1],f[_].v[P],f[_].o[P-1],f[_].i[P],(r.s-B)/_t.addedLength,(r.e-B)/_t.addedLength,Wt[P-1]),this.addSegmentFromArray(_n,s,ue,_a),_a=!1,s.c=!1),B+=_t.addedLength,ue+=1;if(f[_].c&&Wt.length){if(_t=Wt[P-1],B<=r.e){var Di=Wt[P-1].addedLength;r.s<=B&&r.e>=B+Di?(this.addSegment(f[_].v[P-1],f[_].o[P-1],f[_].i[0],f[_].v[0],s,ue,_a),_a=!1):(_n=bez.getNewSegment(f[_].v[P-1],f[_].v[0],f[_].o[P-1],f[_].i[0],(r.s-B)/Di,(r.e-B)/Di,Wt[P-1]),this.addSegmentFromArray(_n,s,ue,_a),_a=!1,s.c=!1)}else s.c=!1;B+=_t.addedLength,ue+=1}if(s._length&&(s.setXYAt(s.v[Ei][0],s.v[Ei][1],"i",Ei),s.setXYAt(s.v[s._length-1][0],s.v[s._length-1][1],"o",s._length-1)),B>r.e)break;_=this.p.keyframes[this.p.keyframes.length-1].t?(_t=this.p.getValueAtTime(this.p.keyframes[this.p.keyframes.length-1].t/B,0),ue=this.p.getValueAtTime((this.p.keyframes[this.p.keyframes.length-1].t-.05)/B,0)):(_t=this.p.pv,ue=this.p.getValueAtTime((this.p._caching.lastFrame+this.p.offsetTime-.01)/B,this.p.offsetTime));else if(this.px&&this.px.keyframes&&this.py.keyframes&&this.px.getValueAtTime&&this.py.getValueAtTime){_t=[],ue=[];var Wt=this.px,_n=this.py;Wt._caching.lastFrame+Wt.offsetTime<=Wt.keyframes[0].t?(_t[0]=Wt.getValueAtTime((Wt.keyframes[0].t+.01)/B,0),_t[1]=_n.getValueAtTime((_n.keyframes[0].t+.01)/B,0),ue[0]=Wt.getValueAtTime(Wt.keyframes[0].t/B,0),ue[1]=_n.getValueAtTime(_n.keyframes[0].t/B,0)):Wt._caching.lastFrame+Wt.offsetTime>=Wt.keyframes[Wt.keyframes.length-1].t?(_t[0]=Wt.getValueAtTime(Wt.keyframes[Wt.keyframes.length-1].t/B,0),_t[1]=_n.getValueAtTime(_n.keyframes[_n.keyframes.length-1].t/B,0),ue[0]=Wt.getValueAtTime((Wt.keyframes[Wt.keyframes.length-1].t-.01)/B,0),ue[1]=_n.getValueAtTime((_n.keyframes[_n.keyframes.length-1].t-.01)/B,0)):(_t=[Wt.pv,_n.pv],ue[0]=Wt.getValueAtTime((Wt._caching.lastFrame+Wt.offsetTime-.01)/B,Wt.offsetTime),ue[1]=_n.getValueAtTime((_n._caching.lastFrame+_n.offsetTime-.01)/B,_n.offsetTime))}else ue=e,_t=ue;this.v.rotate(-Math.atan2(_t[1]-ue[1],_t[0]-ue[0]))}this.data.p&&this.data.p.s?this.data.p.z?this.v.translate(this.px.v,this.py.v,-this.pz.v):this.v.translate(this.px.v,this.py.v,0):this.v.translate(this.p.v[0],this.p.v[1],-this.p.v[2])}this.frameId=this.elem.globalData.frameId}}function d(){if(this.appliedTransformations=0,this.pre.reset(),!this.a.effectsSequence.length)this.pre.translate(-this.a.v[0],-this.a.v[1],this.a.v[2]),this.appliedTransformations=1;else return;if(!this.s.effectsSequence.length)this.pre.scale(this.s.v[0],this.s.v[1],this.s.v[2]),this.appliedTransformations=2;else return;if(this.sk)if(!this.sk.effectsSequence.length&&!this.sa.effectsSequence.length)this.pre.skewFromAxis(-this.sk.v,this.sa.v),this.appliedTransformations=3;else return;this.r?this.r.effectsSequence.length||(this.pre.rotate(-this.r.v),this.appliedTransformations=4):!this.rz.effectsSequence.length&&!this.ry.effectsSequence.length&&!this.rx.effectsSequence.length&&!this.or.effectsSequence.length&&(this.pre.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]),this.appliedTransformations=4)}function f(){}function _(x){this._addDynamicProperty(x),this.elem.addDynamicProperty(x),this._isDirty=!0}function C(x,B,_t){if(this.elem=x,this.frameId=-1,this.propType="transform",this.data=B,this.v=new Matrix,this.pre=new Matrix,this.appliedTransformations=0,this.initDynamicPropertyContainer(_t||x),B.p&&B.p.s?(this.px=PropertyFactory.getProp(x,B.p.x,0,0,this),this.py=PropertyFactory.getProp(x,B.p.y,0,0,this),B.p.z&&(this.pz=PropertyFactory.getProp(x,B.p.z,0,0,this))):this.p=PropertyFactory.getProp(x,B.p||{k:[0,0,0]},1,0,this),B.rx){if(this.rx=PropertyFactory.getProp(x,B.rx,0,degToRads,this),this.ry=PropertyFactory.getProp(x,B.ry,0,degToRads,this),this.rz=PropertyFactory.getProp(x,B.rz,0,degToRads,this),B.or.k[0].ti){var ue,Wt=B.or.k.length;for(ue=0;ue0;)s-=1,this._elements.unshift(r[s]);this.dynamicProperties.length?this.k=!0:this.getValue(!0)},RepeaterModifier.prototype.resetElements=function(e){var r,s=e.length;for(r=0;r0?Math.floor(Wt):Math.ceil(Wt),Ei=this.pMatrix.props,_a=this.rMatrix.props,Di=this.sMatrix.props;this.pMatrix.reset(),this.rMatrix.reset(),this.sMatrix.reset(),this.tMatrix.reset(),this.matrix.reset();var _o=0;if(Wt>0){for(;_o<_i;)this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,1,!1),_o+=1;_n&&(this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,_n,!1),_o+=_n)}else if(Wt<0){for(;_o>_i;)this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,1,!0),_o-=1;_n&&(this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,-_n,!0),_o-=_n)}d=this.data.m===1?0:this._currentCopies-1,f=this.data.m===1?1:-1,_=this._currentCopies;for(var _s,_c;_;){if(r=this.elemsData[d].it,s=r[r.length-1].transform.mProps.v.props,_c=s.length,r[r.length-1].transform.mProps._mdf=!0,r[r.length-1].transform.op._mdf=!0,r[r.length-1].transform.op.v=this._currentCopies===1?this.so.v:this.so.v+(this.eo.v-this.so.v)*(d/(this._currentCopies-1)),_o!==0){for((d!==0&&f===1||d!==this._currentCopies-1&&f===-1)&&this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,1,!1),this.matrix.transform(_a[0],_a[1],_a[2],_a[3],_a[4],_a[5],_a[6],_a[7],_a[8],_a[9],_a[10],_a[11],_a[12],_a[13],_a[14],_a[15]),this.matrix.transform(Di[0],Di[1],Di[2],Di[3],Di[4],Di[5],Di[6],Di[7],Di[8],Di[9],Di[10],Di[11],Di[12],Di[13],Di[14],Di[15]),this.matrix.transform(Ei[0],Ei[1],Ei[2],Ei[3],Ei[4],Ei[5],Ei[6],Ei[7],Ei[8],Ei[9],Ei[10],Ei[11],Ei[12],Ei[13],Ei[14],Ei[15]),_s=0;_s<_c;_s+=1)s[_s]=this.matrix.props[_s];this.matrix.reset()}else for(this.matrix.reset(),_s=0;_s<_c;_s+=1)s[_s]=this.matrix.props[_s];_o+=1,_-=1,d+=f}}else for(_=this._currentCopies,d=0,f=1;_;)r=this.elemsData[d].it,s=r[r.length-1].transform.mProps.v.props,r[r.length-1].transform.mProps._mdf=!1,r[r.length-1].transform.op._mdf=!1,_-=1,d+=f;return C},RepeaterModifier.prototype.addShape=function(){};function RoundCornersModifier(){}extendPrototype([ShapeModifier],RoundCornersModifier),RoundCornersModifier.prototype.initModifierProperties=function(e,r){this.getValue=this.processKeys,this.rd=PropertyFactory.getProp(e,r.r,0,null,this),this._isAnimated=!!this.rd.effectsSequence.length},RoundCornersModifier.prototype.processPath=function(e,r){var s=shapePool.newElement();s.c=e.c;var d,f=e._length,_,C,P,x,B,_t,ue=0,Wt,_n,_i,Ei,_a,Di;for(d=0;d0&&d<1?[r]:[]:[r-d,r+d].filter(function(f){return f>0&&f<1})},PolynomialBezier.prototype.split=function(e){if(e<=0)return[singlePoint(this.points[0]),this];if(e>=1)return[this,singlePoint(this.points[this.points.length-1])];var r=lerpPoint(this.points[0],this.points[1],e),s=lerpPoint(this.points[1],this.points[2],e),d=lerpPoint(this.points[2],this.points[3],e),f=lerpPoint(r,s,e),_=lerpPoint(s,d,e),C=lerpPoint(f,_,e);return[new PolynomialBezier(this.points[0],r,f,C,!0),new PolynomialBezier(C,_,d,this.points[3],!0)]};function extrema(e,r){var s=e.points[0][r],d=e.points[e.points.length-1][r];if(s>d){var f=d;d=s,s=f}for(var _=quadRoots(3*e.a[r],2*e.b[r],e.c[r]),C=0;C<_.length;C+=1)if(_[C]>0&&_[C]<1){var P=e.point(_[C])[r];Pd&&(d=P)}return{min:s,max:d}}PolynomialBezier.prototype.bounds=function(){return{x:extrema(this,0),y:extrema(this,1)}},PolynomialBezier.prototype.boundingBox=function(){var e=this.bounds();return{left:e.x.min,right:e.x.max,top:e.y.min,bottom:e.y.max,width:e.x.max-e.x.min,height:e.y.max-e.y.min,cx:(e.x.max+e.x.min)/2,cy:(e.y.max+e.y.min)/2}};function intersectData(e,r,s){var d=e.boundingBox();return{cx:d.cx,cy:d.cy,width:d.width,height:d.height,bez:e,t:(r+s)/2,t1:r,t2:s}}function splitData(e){var r=e.bez.split(.5);return[intersectData(r[0],e.t1,e.t),intersectData(r[1],e.t,e.t2)]}function boxIntersect(e,r){return Math.abs(e.cx-r.cx)*2=_||e.width<=d&&e.height<=d&&r.width<=d&&r.height<=d){f.push([e.t,r.t]);return}var C=splitData(e),P=splitData(r);intersectsImpl(C[0],P[0],s+1,d,f,_),intersectsImpl(C[0],P[1],s+1,d,f,_),intersectsImpl(C[1],P[0],s+1,d,f,_),intersectsImpl(C[1],P[1],s+1,d,f,_)}}PolynomialBezier.prototype.intersections=function(e,r,s){r===void 0&&(r=2),s===void 0&&(s=7);var d=[];return intersectsImpl(intersectData(this,0,1),intersectData(e,0,1),0,r,d,s),d},PolynomialBezier.shapeSegment=function(e,r){var s=(r+1)%e.length();return new PolynomialBezier(e.v[r],e.o[r],e.i[s],e.v[s],!0)},PolynomialBezier.shapeSegmentInverted=function(e,r){var s=(r+1)%e.length();return new PolynomialBezier(e.v[s],e.i[s],e.o[r],e.v[r],!0)};function crossProduct(e,r){return[e[1]*r[2]-e[2]*r[1],e[2]*r[0]-e[0]*r[2],e[0]*r[1]-e[1]*r[0]]}function lineIntersection(e,r,s,d){var f=[e[0],e[1],1],_=[r[0],r[1],1],C=[s[0],s[1],1],P=[d[0],d[1],1],x=crossProduct(crossProduct(f,_),crossProduct(C,P));return floatZero(x[2])?null:[x[0]/x[2],x[1]/x[2]]}function polarOffset(e,r,s){return[e[0]+Math.cos(r)*s,e[1]-Math.sin(r)*s]}function pointDistance(e,r){return Math.hypot(e[0]-r[0],e[1]-r[1])}function pointEqual(e,r){return floatEqual(e[0],r[0])&&floatEqual(e[1],r[1])}function ZigZagModifier(){}extendPrototype([ShapeModifier],ZigZagModifier),ZigZagModifier.prototype.initModifierProperties=function(e,r){this.getValue=this.processKeys,this.amplitude=PropertyFactory.getProp(e,r.s,0,null,this),this.frequency=PropertyFactory.getProp(e,r.r,0,null,this),this.pointsType=PropertyFactory.getProp(e,r.pt,0,null,this),this._isAnimated=this.amplitude.effectsSequence.length!==0||this.frequency.effectsSequence.length!==0||this.pointsType.effectsSequence.length!==0};function setPoint(e,r,s,d,f,_,C){var P=s-Math.PI/2,x=s+Math.PI/2,B=r[0]+Math.cos(s)*d*f,_t=r[1]-Math.sin(s)*d*f;e.setTripleAt(B,_t,B+Math.cos(P)*_,_t-Math.sin(P)*_,B+Math.cos(x)*C,_t-Math.sin(x)*C,e.length())}function getPerpendicularVector(e,r){var s=[r[0]-e[0],r[1]-e[1]],d=-Math.PI*.5,f=[Math.cos(d)*s[0]-Math.sin(d)*s[1],Math.sin(d)*s[0]+Math.cos(d)*s[1]];return f}function getProjectingAngle(e,r){var s=r===0?e.length()-1:r-1,d=(r+1)%e.length(),f=e.v[s],_=e.v[d],C=getPerpendicularVector(f,_);return Math.atan2(0,1)-Math.atan2(C[1],C[0])}function zigZagCorner(e,r,s,d,f,_,C){var P=getProjectingAngle(r,s),x=r.v[s%r._length],B=r.v[s===0?r._length-1:s-1],_t=r.v[(s+1)%r._length],ue=_===2?Math.sqrt(Math.pow(x[0]-B[0],2)+Math.pow(x[1]-B[1],2)):0,Wt=_===2?Math.sqrt(Math.pow(x[0]-_t[0],2)+Math.pow(x[1]-_t[1],2)):0;setPoint(e,r.v[s%r._length],P,C,d,Wt/((f+1)*2),ue/((f+1)*2))}function zigZagSegment(e,r,s,d,f,_){for(var C=0;C1&&r.length>1&&(f=getIntersection(e[0],r[r.length-1]),f)?[[e[0].split(f[0])[0]],[r[r.length-1].split(f[1])[1]]]:[s,d]}function pruneIntersections(e){for(var r,s=1;s1&&(r=pruneSegmentIntersection(e[e.length-1],e[0]),e[e.length-1]=r[0],e[0]=r[1]),e}function offsetSegmentSplit(e,r){var s=e.inflectionPoints(),d,f,_,C;if(s.length===0)return[offsetSegment(e,r)];if(s.length===1||floatEqual(s[1],1))return _=e.split(s[0]),d=_[0],f=_[1],[offsetSegment(d,r),offsetSegment(f,r)];_=e.split(s[0]),d=_[0];var P=(s[1]-s[0])/(1-s[0]);return _=_[1].split(P),C=_[0],f=_[1],[offsetSegment(d,r),offsetSegment(C,r),offsetSegment(f,r)]}function OffsetPathModifier(){}extendPrototype([ShapeModifier],OffsetPathModifier),OffsetPathModifier.prototype.initModifierProperties=function(e,r){this.getValue=this.processKeys,this.amount=PropertyFactory.getProp(e,r.a,0,null,this),this.miterLimit=PropertyFactory.getProp(e,r.ml,0,null,this),this.lineJoin=r.lj,this._isAnimated=this.amount.effectsSequence.length!==0},OffsetPathModifier.prototype.processPath=function(e,r,s,d){var f=shapePool.newElement();f.c=e.c;var _=e.length();e.c||(_-=1);var C,P,x,B=[];for(C=0;C<_;C+=1)x=PolynomialBezier.shapeSegment(e,C),B.push(offsetSegmentSplit(x,r));if(!e.c)for(C=_-1;C>=0;C-=1)x=PolynomialBezier.shapeSegmentInverted(e,C),B.push(offsetSegmentSplit(x,r));B=pruneIntersections(B);var _t=null,ue=null;for(C=0;C0&&(IE=!1),IE){var QE=createTag("style");QE.setAttribute("f-forigin",_d[_f].fOrigin),QE.setAttribute("f-origin",_d[_f].origin),QE.setAttribute("f-family",_d[_f].fFamily),QE.type="text/css",QE.innerText="@font-face {font-family: "+_d[_f].fFamily+"; font-style: normal; src: url('"+_d[_f].fPath+"');}",Fg.appendChild(QE)}}else if(_d[_f].fOrigin==="g"||_d[_f].origin===1){for(DE=document.querySelectorAll('link[f-forigin="g"], link[f-origin="1"]'),GE=0;GE=55296&&_d<=56319){var _f=vf.charCodeAt(1);_f>=56320&&_f<=57343&&(Fg=(_d-55296)*1024+_f-56320+65536)}return Fg}function Qm(vf,Fg){var _d=vf.toString(16)+Fg.toString(16);return ue.indexOf(_d)!==-1}function tE(vf){return vf===x}function aE(vf){return vf===P}function RE(vf){var Fg=_m(vf);return Fg>=B&&Fg<=_t}function lE(vf){return RE(vf.substr(0,2))&&RE(vf.substr(2,2))}function gE(vf){return s.indexOf(vf)!==-1}function cE(vf,Fg){var _d=_m(vf.substr(Fg,2));if(_d!==d)return!1;var _f=0;for(Fg+=2;_f<5;){if(_d=_m(vf.substr(Fg,2)),_d<_||_d>C)return!1;_f+=1,Fg+=2}return _m(vf.substr(Fg,2))===f}function _E(){this.isLoaded=!0}var iE=function(){this.fonts=[],this.chars=null,this.typekitLoaded=0,this.isLoaded=!1,this._warned=!1,this.initTime=Date.now(),this.setIsLoadedBinded=this.setIsLoaded.bind(this),this.checkLoadedFontsBinded=this.checkLoadedFonts.bind(this)};iE.isModifier=Qm,iE.isZeroWidthJoiner=tE,iE.isFlagEmoji=lE,iE.isRegionalCode=RE,iE.isCombinedCharacter=gE,iE.isRegionalFlag=cE,iE.isVariationSelector=aE,iE.BLACK_FLAG_CODE_POINT=d;var rE={addChars:Di,addFonts:_a,getCharData:_o,getFontByName:_c,measureText:_s,checkLoadedFonts:_i,setIsLoaded:_E};return iE.prototype=rE,iE}();function SlotManager(e){this.animationData=e}SlotManager.prototype.getProp=function(e){return this.animationData.slots&&this.animationData.slots[e.sid]?Object.assign(e,this.animationData.slots[e.sid].p):e};function slotFactory(e){return new SlotManager(e)}function RenderableElement(){}RenderableElement.prototype={initRenderable:function(){this.isInRange=!1,this.hidden=!1,this.isTransparent=!1,this.renderableComponents=[]},addRenderableComponent:function(r){this.renderableComponents.indexOf(r)===-1&&this.renderableComponents.push(r)},removeRenderableComponent:function(r){this.renderableComponents.indexOf(r)!==-1&&this.renderableComponents.splice(this.renderableComponents.indexOf(r),1)},prepareRenderableFrame:function(r){this.checkLayerLimits(r)},checkTransparency:function(){this.finalTransform.mProp.o.v<=0?!this.isTransparent&&this.globalData.renderConfig.hideOnTransparent&&(this.isTransparent=!0,this.hide()):this.isTransparent&&(this.isTransparent=!1,this.show())},checkLayerLimits:function(r){this.data.ip-this.data.st<=r&&this.data.op-this.data.st>r?this.isInRange!==!0&&(this.globalData._mdf=!0,this._mdf=!0,this.isInRange=!0,this.show()):this.isInRange!==!1&&(this.globalData._mdf=!0,this.isInRange=!1,this.hide())},renderRenderable:function(){var r,s=this.renderableComponents.length;for(r=0;r.1)&&this.audio.seek(this._currentTime/this.globalData.frameRate):(this.audio.play(),this.audio.seek(this._currentTime/this.globalData.frameRate),this._isPlaying=!0))},AudioElement.prototype.show=function(){},AudioElement.prototype.hide=function(){this.audio.pause(),this._isPlaying=!1},AudioElement.prototype.pause=function(){this.audio.pause(),this._isPlaying=!1,this._canPlay=!1},AudioElement.prototype.resume=function(){this._canPlay=!0},AudioElement.prototype.setRate=function(e){this.audio.rate(e)},AudioElement.prototype.volume=function(e){this._volumeMultiplier=e,this._previousVolume=e*this._volume,this.audio.volume(this._previousVolume)},AudioElement.prototype.getBaseElement=function(){return null},AudioElement.prototype.destroy=function(){},AudioElement.prototype.sourceRectAtTime=function(){},AudioElement.prototype.initExpressions=function(){};function BaseRenderer(){}BaseRenderer.prototype.checkLayers=function(e){var r,s=this.layers.length,d;for(this.completeLayers=!0,r=s-1;r>=0;r-=1)this.elements[r]||(d=this.layers[r],d.ip-d.st<=e-this.layers[r].st&&d.op-d.st>e-this.layers[r].st&&this.buildItem(r)),this.completeLayers=this.elements[r]?this.completeLayers:!1;this.checkPendingElements()},BaseRenderer.prototype.createItem=function(e){switch(e.ty){case 2:return this.createImage(e);case 0:return this.createComp(e);case 1:return this.createSolid(e);case 3:return this.createNull(e);case 4:return this.createShape(e);case 5:return this.createText(e);case 6:return this.createAudio(e);case 13:return this.createCamera(e);case 15:return this.createFootage(e);default:return this.createNull(e)}},BaseRenderer.prototype.createCamera=function(){throw new Error("You're using a 3d camera. Try the html renderer.")},BaseRenderer.prototype.createAudio=function(e){return new AudioElement(e,this.globalData,this)},BaseRenderer.prototype.createFootage=function(e){return new FootageElement(e,this.globalData,this)},BaseRenderer.prototype.buildAllItems=function(){var e,r=this.layers.length;for(e=0;e0&&(this.maskElement.setAttribute("id",Wt),this.element.maskedElement.setAttribute(_o,"url("+getLocationHref()+"#"+Wt+")"),d.appendChild(this.maskElement)),this.viewData.length&&this.element.addRenderableComponent(this)}MaskElement.prototype.getMaskProperty=function(e){return this.viewData[e].prop},MaskElement.prototype.renderFrame=function(e){var r=this.element.finalTransform.mat,s,d=this.masksProperties.length;for(s=0;s1&&(d+=" C"+r.o[f-1][0]+","+r.o[f-1][1]+" "+r.i[0][0]+","+r.i[0][1]+" "+r.v[0][0]+","+r.v[0][1]),s.lastPath!==d){var C="";s.elem&&(r.c&&(C=e.inv?this.solidPath+d:d),s.elem.setAttribute("d",C)),s.lastPath=d}},MaskElement.prototype.destroy=function(){this.element=null,this.globalData=null,this.maskElement=null,this.data=null,this.masksProperties=null};var filtersFactory=function(){var e={};e.createFilter=r,e.createAlphaToLuminanceFilter=s;function r(d,f){var _=createNS("filter");return _.setAttribute("id",d),f!==!0&&(_.setAttribute("filterUnits","objectBoundingBox"),_.setAttribute("x","0%"),_.setAttribute("y","0%"),_.setAttribute("width","100%"),_.setAttribute("height","100%")),_}function s(){var d=createNS("feColorMatrix");return d.setAttribute("type","matrix"),d.setAttribute("color-interpolation-filters","sRGB"),d.setAttribute("values","0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1"),d}return e}(),featureSupport=function(){var e={maskType:!0,svgLumaHidden:!0,offscreenCanvas:typeof OffscreenCanvas<"u"};return(/MSIE 10/i.test(navigator.userAgent)||/MSIE 9/i.test(navigator.userAgent)||/rv:11.0/i.test(navigator.userAgent)||/Edge\/\d./i.test(navigator.userAgent))&&(e.maskType=!1),/firefox/i.test(navigator.userAgent)&&(e.svgLumaHidden=!1),e}(),registeredEffects$1={},idPrefix="filter_result_";function SVGEffects(e){var r,s="SourceGraphic",d=e.data.ef?e.data.ef.length:0,f=createElementID(),_=filtersFactory.createFilter(f,!0),C=0;this.filters=[];var P;for(r=0;r=0&&(d=this.shapeModifiers[r].processShapes(this._isFirstFrame),!d);r-=1);}},searchProcessedElement:function(r){for(var s=this.processedElements,d=0,f=s.length;d.01)return!1;s+=1}return!0},GradientProperty.prototype.checkCollapsable=function(){if(this.o.length/2!==this.c.length/4)return!1;if(this.data.k.k[0].s)for(var e=0,r=this.data.k.k.length;e0;)Di=Wt.transformers[RE].mProps._mdf||Di,aE-=1,RE-=1;if(Di)for(aE=_m-Wt.styles[_s].lvl,RE=Wt.transformers.length-1;aE>0;)tE.multiply(Wt.transformers[RE].mProps.v),aE-=1,RE-=1}else tE=e;if(Qm=Wt.sh.paths,Ei=Qm._length,Di){for(_a="",_i=0;_i=1?_E=.99:_E<=-1&&(_E=-.99);var iE=gE*_E,rE=Math.cos(cE+Wt.a.v)*iE+_a[0],vf=Math.sin(cE+Wt.a.v)*iE+_a[1];_i.setAttribute("fx",rE),_i.setAttribute("fy",vf),Ei&&!Wt.g._collapsable&&(Wt.of.setAttribute("fx",rE),Wt.of.setAttribute("fy",vf))}}}function _t(ue,Wt,_n){var _i=Wt.style,Ei=Wt.d;Ei&&(Ei._mdf||_n)&&Ei.dashStr&&(_i.pElem.setAttribute("stroke-dasharray",Ei.dashStr),_i.pElem.setAttribute("stroke-dashoffset",Ei.dashoffset[0])),Wt.c&&(Wt.c._mdf||_n)&&_i.pElem.setAttribute("stroke","rgb("+bmFloor(Wt.c.v[0])+","+bmFloor(Wt.c.v[1])+","+bmFloor(Wt.c.v[2])+")"),(Wt.o._mdf||_n)&&_i.pElem.setAttribute("stroke-opacity",Wt.o.v),(Wt.w._mdf||_n)&&(_i.pElem.setAttribute("stroke-width",Wt.w.v),_i.msElem&&_i.msElem.setAttribute("stroke-width",Wt.w.v))}return s}();function SVGShapeElement(e,r,s){this.shapes=[],this.shapesData=e.shapes,this.stylesList=[],this.shapeModifiers=[],this.itemsData=[],this.processedElements=[],this.animatedContents=[],this.initElement(e,r,s),this.prevViewData=[]}extendPrototype([BaseElement,TransformElement,SVGBaseElement,IShapeElement,HierarchyElement,FrameElement,RenderableDOMElement],SVGShapeElement),SVGShapeElement.prototype.initSecondaryElement=function(){},SVGShapeElement.prototype.identityMatrix=new Matrix,SVGShapeElement.prototype.buildExpressionInterface=function(){},SVGShapeElement.prototype.createContent=function(){this.searchShapes(this.shapesData,this.itemsData,this.prevViewData,this.layerElement,0,[],!0),this.filterUniqueShapes()},SVGShapeElement.prototype.filterUniqueShapes=function(){var e,r=this.shapes.length,s,d,f=this.stylesList.length,_,C=[],P=!1;for(d=0;d1&&P&&this.setShapesAsAnimated(C)}},SVGShapeElement.prototype.setShapesAsAnimated=function(e){var r,s=e.length;for(r=0;r=0;x-=1){if(_a=this.searchProcessedElement(e[x]),_a?r[x]=s[_a-1]:e[x]._render=C,e[x].ty==="fl"||e[x].ty==="st"||e[x].ty==="gf"||e[x].ty==="gs"||e[x].ty==="no")_a?r[x].style.closed=!1:r[x]=this.createStyleElement(e[x],f),e[x]._render&&r[x].style.pElem.parentNode!==d&&d.appendChild(r[x].style.pElem),Wt.push(r[x].style);else if(e[x].ty==="gr"){if(!_a)r[x]=this.createGroupElement(e[x]);else for(ue=r[x].it.length,_t=0;_t1,this.kf&&this.addEffect(this.getKeyframeValue.bind(this)),this.kf},TextProperty.prototype.addEffect=function(e){this.effectsSequence.push(e),this.elem.addDynamicProperty(this)},TextProperty.prototype.getValue=function(e){if(!((this.elem.globalData.frameId===this.frameId||!this.effectsSequence.length)&&!e)){this.currentData.t=this.data.d.k[this.keysIndex].s.t;var r=this.currentData,s=this.keysIndex;if(this.lock){this.setCurrentData(this.currentData);return}this.lock=!0,this._mdf=!1;var d,f=this.effectsSequence.length,_=e||this.data.d.k[this.keysIndex].s;for(d=0;dr);)s+=1;return this.keysIndex!==s&&(this.keysIndex=s),this.data.d.k[this.keysIndex].s},TextProperty.prototype.buildFinalText=function(e){for(var r=[],s=0,d=e.length,f,_,C=!1,P=!1,x="";s=55296&&f<=56319?FontManager.isRegionalFlag(e,s)?x=e.substr(s,14):(_=e.charCodeAt(s+1),_>=56320&&_<=57343&&(FontManager.isModifier(f,_)?(x=e.substr(s,2),C=!0):FontManager.isFlagEmoji(e.substr(s,4))?x=e.substr(s,4):x=e.substr(s,2))):f>56319?(_=e.charCodeAt(s+1),FontManager.isVariationSelector(f)&&(C=!0)):FontManager.isZeroWidthJoiner(f)&&(C=!0,P=!0),C?(r[r.length-1]+=x,C=!1):r.push(x),s+=x.length;return r},TextProperty.prototype.completeTextData=function(e){e.__complete=!0;var r=this.elem.globalData.fontManager,s=this.data,d=[],f,_,C,P=0,x,B=s.m.g,_t=0,ue=0,Wt=0,_n=[],_i=0,Ei=0,_a,Di,_o=r.getFontByName(e.f),_s,_c=0,_m=getFontProperties(_o);e.fWeight=_m.weight,e.fStyle=_m.style,e.finalSize=e.s,e.finalText=this.buildFinalText(e.t),_=e.finalText.length,e.finalLineHeight=e.lh;var Qm=e.tr/1e3*e.finalSize,tE;if(e.sz)for(var aE=!0,RE=e.sz[0],lE=e.sz[1],gE,cE;aE;){cE=this.buildFinalText(e.t),gE=0,_i=0,_=cE.length,Qm=e.tr/1e3*e.finalSize;var _E=-1;for(f=0;f<_;f+=1)tE=cE[f].charCodeAt(0),C=!1,cE[f]===" "?_E=f:(tE===13||tE===3)&&(_i=0,C=!0,gE+=e.finalLineHeight||e.finalSize*1.2),r.chars?(_s=r.getCharData(cE[f],_o.fStyle,_o.fFamily),_c=C?0:_s.w*e.finalSize/100):_c=r.measureText(cE[f],e.f,e.finalSize),_i+_c>RE&&cE[f]!==" "?(_E===-1?_+=1:f=_E,gE+=e.finalLineHeight||e.finalSize*1.2,cE.splice(f,_E===f?1:0,"\r"),_E=-1,_i=0):(_i+=_c,_i+=Qm);gE+=_o.ascent*e.finalSize/100,this.canResize&&e.finalSize>this.minimumFontSize&&lEEi?_i:Ei,_i=-2*Qm,x="",C=!0,Wt+=1):x=rE,r.chars?(_s=r.getCharData(rE,_o.fStyle,r.getFontByName(e.f).fFamily),_c=C?0:_s.w*e.finalSize/100):_c=r.measureText(x,e.f,e.finalSize),rE===" "?iE+=_c+Qm:(_i+=_c+Qm+iE,iE=0),d.push({l:_c,an:_c,add:_t,n:C,anIndexes:[],val:x,line:Wt,animatorJustifyOffset:0}),B==2){if(_t+=_c,x===""||x===" "||f===_-1){for((x===""||x===" ")&&(_t-=_c);ue<=f;)d[ue].an=_t,d[ue].ind=P,d[ue].extra=_c,ue+=1;P+=1,_t=0}}else if(B==3){if(_t+=_c,x===""||f===_-1){for(x===""&&(_t-=_c);ue<=f;)d[ue].an=_t,d[ue].ind=P,d[ue].extra=_c,ue+=1;_t=0,P+=1}}else d[P].ind=P,d[P].extra=0,P+=1;if(e.l=d,Ei=_i>Ei?_i:Ei,_n.push(_i),e.sz)e.boxWidth=e.sz[0],e.justifyOffset=0;else switch(e.boxWidth=Ei,e.j){case 1:e.justifyOffset=-e.boxWidth;break;case 2:e.justifyOffset=-e.boxWidth/2;break;default:e.justifyOffset=0}e.lineWidths=_n;var vf=s.a,Fg,_d;Di=vf.length;var _f,uE,dE=[];for(_a=0;_a0?P=this.ne.v/100:x=-this.ne.v/100,this.xe.v>0?B=1-this.xe.v/100:_t=1+this.xe.v/100;var ue=BezierFactory.getBezierEasing(P,x,B,_t).get,Wt=0,_n=this.finalS,_i=this.finalE,Ei=this.data.sh;if(Ei===2)_i===_n?Wt=C>=_i?1:0:Wt=e(0,r(.5/(_i-_n)+(C-_n)/(_i-_n),1)),Wt=ue(Wt);else if(Ei===3)_i===_n?Wt=C>=_i?0:1:Wt=1-e(0,r(.5/(_i-_n)+(C-_n)/(_i-_n),1)),Wt=ue(Wt);else if(Ei===4)_i===_n?Wt=0:(Wt=e(0,r(.5/(_i-_n)+(C-_n)/(_i-_n),1)),Wt<.5?Wt*=2:Wt=1-2*(Wt-.5)),Wt=ue(Wt);else if(Ei===5){if(_i===_n)Wt=0;else{var _a=_i-_n;C=r(e(0,C+.5-_n),_i-_n);var Di=-_a/2+C,_o=_a/2;Wt=Math.sqrt(1-Di*Di/(_o*_o))}Wt=ue(Wt)}else Ei===6?(_i===_n?Wt=0:(C=r(e(0,C+.5-_n),_i-_n),Wt=(1+Math.cos(Math.PI+Math.PI*2*C/(_i-_n)))/2),Wt=ue(Wt)):(C>=s(_n)&&(C-_n<0?Wt=e(0,r(r(_i,1)-(_n-C),1)):Wt=e(0,r(_i-C,1))),Wt=ue(Wt));if(this.sm.v!==100){var _s=this.sm.v*.01;_s===0&&(_s=1e-8);var _c=.5-_s*.5;Wt<_c?Wt=0:(Wt=(Wt-_c)/_s,Wt>1&&(Wt=1))}return Wt*this.a.v},getValue:function(C){this.iterateDynamicProperties(),this._mdf=C||this._mdf,this._currentTextLength=this.elem.textProperty.currentData.l.length||0,C&&this.data.r===2&&(this.e.v=this._currentTextLength);var P=this.data.r===2?1:100/this.data.totalChars,x=this.o.v/P,B=this.s.v/P+x,_t=this.e.v/P+x;if(B>_t){var ue=B;B=_t,_t=ue}this.finalS=B,this.finalE=_t}},extendPrototype([DynamicPropertyContainer],d);function f(_,C,P){return new d(_,C)}return{getTextSelectorProp:f}}();function TextAnimatorDataProperty(e,r,s){var d={propType:!1},f=PropertyFactory.getProp,_=r.a;this.a={r:_.r?f(e,_.r,0,degToRads,s):d,rx:_.rx?f(e,_.rx,0,degToRads,s):d,ry:_.ry?f(e,_.ry,0,degToRads,s):d,sk:_.sk?f(e,_.sk,0,degToRads,s):d,sa:_.sa?f(e,_.sa,0,degToRads,s):d,s:_.s?f(e,_.s,1,.01,s):d,a:_.a?f(e,_.a,1,0,s):d,o:_.o?f(e,_.o,0,.01,s):d,p:_.p?f(e,_.p,1,0,s):d,sw:_.sw?f(e,_.sw,0,0,s):d,sc:_.sc?f(e,_.sc,1,0,s):d,fc:_.fc?f(e,_.fc,1,0,s):d,fh:_.fh?f(e,_.fh,0,0,s):d,fs:_.fs?f(e,_.fs,0,.01,s):d,fb:_.fb?f(e,_.fb,0,.01,s):d,t:_.t?f(e,_.t,0,0,s):d},this.s=TextSelectorProp.getTextSelectorProp(e,r.s,s),this.s.t=r.s.t}function TextAnimatorProperty(e,r,s){this._isFirstFrame=!0,this._hasMaskedPath=!1,this._frameId=-1,this._textData=e,this._renderType=r,this._elem=s,this._animatorsData=createSizedArray(this._textData.a.length),this._pathData={},this._moreOptions={alignment:{}},this.renderedLetters=[],this.lettersChangedFlag=!1,this.initDynamicPropertyContainer(s)}TextAnimatorProperty.prototype.searchProperties=function(){var e,r=this._textData.a.length,s,d=PropertyFactory.getProp;for(e=0;e=_i+rS||!_m?(RE=(_i+rS-_a)/Ei.partialLength,GE=_c.point[0]+(Ei.point[0]-_c.point[0])*RE,QE=_c.point[1]+(Ei.point[1]-_c.point[1])*RE,_.translate(-s[0]*Wt[_t].an*.005,-(s[1]*iE)*.01),Di=!1):_m&&(_a+=Ei.partialLength,_o+=1,_o>=_m.length&&(_o=0,_s+=1,Qm[_s]?_m=Qm[_s].points:gE.v.c?(_o=0,_s=0,_m=Qm[_s].points):(_a-=Ei.partialLength,_m=null)),_m&&(_c=Ei,Ei=_m[_o],tE=Ei.partialLength));DE=Wt[_t].an/2-Wt[_t].add,_.translate(-DE,0,0)}else DE=Wt[_t].an/2-Wt[_t].add,_.translate(-DE,0,0),_.translate(-s[0]*Wt[_t].an*.005,-s[1]*iE*.01,0);for(_d=0;_d<_f;_d+=1)vf=d[_d].a,vf.t.propType&&(Fg=d[_d].s,dE=Fg.getMult(Wt[_t].anIndexes[_d],f.a[_d].s.totalChars),(x!==0||e.j!==0)&&(this._hasMaskedPath?dE.length?_i+=vf.t.v*dE[0]:_i+=vf.t.v*dE:dE.length?x+=vf.t.v*dE[0]:x+=vf.t.v*dE));for(e.strokeWidthAnim&&(Y0=e.sw||0),e.strokeColorAnim&&(e.sc?s0=[e.sc[0],e.sc[1],e.sc[2]]:s0=[0,0,0]),e.fillColorAnim&&e.fc&&(o_=[e.fc[0],e.fc[1],e.fc[2]]),_d=0;_d<_f;_d+=1)vf=d[_d].a,vf.a.propType&&(Fg=d[_d].s,dE=Fg.getMult(Wt[_t].anIndexes[_d],f.a[_d].s.totalChars),dE.length?_.translate(-vf.a.v[0]*dE[0],-vf.a.v[1]*dE[1],vf.a.v[2]*dE[2]):_.translate(-vf.a.v[0]*dE,-vf.a.v[1]*dE,vf.a.v[2]*dE));for(_d=0;_d<_f;_d+=1)vf=d[_d].a,vf.s.propType&&(Fg=d[_d].s,dE=Fg.getMult(Wt[_t].anIndexes[_d],f.a[_d].s.totalChars),dE.length?_.scale(1+(vf.s.v[0]-1)*dE[0],1+(vf.s.v[1]-1)*dE[1],1):_.scale(1+(vf.s.v[0]-1)*dE,1+(vf.s.v[1]-1)*dE,1));for(_d=0;_d<_f;_d+=1){if(vf=d[_d].a,Fg=d[_d].s,dE=Fg.getMult(Wt[_t].anIndexes[_d],f.a[_d].s.totalChars),vf.sk.propType&&(dE.length?_.skewFromAxis(-vf.sk.v*dE[0],vf.sa.v*dE[1]):_.skewFromAxis(-vf.sk.v*dE,vf.sa.v*dE)),vf.r.propType&&(dE.length?_.rotateZ(-vf.r.v*dE[2]):_.rotateZ(-vf.r.v*dE)),vf.ry.propType&&(dE.length?_.rotateY(vf.ry.v*dE[1]):_.rotateY(vf.ry.v*dE)),vf.rx.propType&&(dE.length?_.rotateX(vf.rx.v*dE[0]):_.rotateX(vf.rx.v*dE)),vf.o.propType&&(dE.length?M0+=(vf.o.v*dE[0]-M0)*dE[0]:M0+=(vf.o.v*dE-M0)*dE),e.strokeWidthAnim&&vf.sw.propType&&(dE.length?Y0+=vf.sw.v*dE[0]:Y0+=vf.sw.v*dE),e.strokeColorAnim&&vf.sc.propType)for(LE=0;LE<3;LE+=1)dE.length?s0[LE]+=(vf.sc.v[LE]-s0[LE])*dE[0]:s0[LE]+=(vf.sc.v[LE]-s0[LE])*dE;if(e.fillColorAnim&&e.fc){if(vf.fc.propType)for(LE=0;LE<3;LE+=1)dE.length?o_[LE]+=(vf.fc.v[LE]-o_[LE])*dE[0]:o_[LE]+=(vf.fc.v[LE]-o_[LE])*dE;vf.fh.propType&&(dE.length?o_=addHueToRGB(o_,vf.fh.v*dE[0]):o_=addHueToRGB(o_,vf.fh.v*dE)),vf.fs.propType&&(dE.length?o_=addSaturationToRGB(o_,vf.fs.v*dE[0]):o_=addSaturationToRGB(o_,vf.fs.v*dE)),vf.fb.propType&&(dE.length?o_=addBrightnessToRGB(o_,vf.fb.v*dE[0]):o_=addBrightnessToRGB(o_,vf.fb.v*dE))}}for(_d=0;_d<_f;_d+=1)vf=d[_d].a,vf.p.propType&&(Fg=d[_d].s,dE=Fg.getMult(Wt[_t].anIndexes[_d],f.a[_d].s.totalChars),this._hasMaskedPath?dE.length?_.translate(0,vf.p.v[1]*dE[0],-vf.p.v[2]*dE[1]):_.translate(0,vf.p.v[1]*dE,-vf.p.v[2]*dE):dE.length?_.translate(vf.p.v[0]*dE[0],vf.p.v[1]*dE[1],-vf.p.v[2]*dE[2]):_.translate(vf.p.v[0]*dE,vf.p.v[1]*dE,-vf.p.v[2]*dE));if(e.strokeWidthAnim&&(C_=Y0<0?0:Y0),e.strokeColorAnim&&(KE="rgb("+Math.round(s0[0]*255)+","+Math.round(s0[1]*255)+","+Math.round(s0[2]*255)+")"),e.fillColorAnim&&e.fc&&(f_="rgb("+Math.round(o_[0]*255)+","+Math.round(o_[1]*255)+","+Math.round(o_[2]*255)+")"),this._hasMaskedPath){if(_.translate(0,-e.ls),_.translate(0,s[1]*iE*.01+B,0),this._pathData.p.v){lE=(Ei.point[1]-_c.point[1])/(Ei.point[0]-_c.point[0]);var GT=Math.atan(lE)*180/Math.PI;Ei.point[0]<_c.point[0]&&(GT+=180),_.rotate(-GT*Math.PI/180)}_.translate(GE,QE,0),_i-=s[0]*Wt[_t].an*.005,Wt[_t+1]&&IE!==Wt[_t+1].ind&&(_i+=Wt[_t].an/2,_i+=e.tr*.001*e.finalSize)}else{switch(_.translate(x,B,0),e.ps&&_.translate(e.ps[0],e.ps[1]+e.ascent,0),e.j){case 1:_.translate(Wt[_t].animatorJustifyOffset+e.justifyOffset+(e.boxWidth-e.lineWidths[Wt[_t].line]),0,0);break;case 2:_.translate(Wt[_t].animatorJustifyOffset+e.justifyOffset+(e.boxWidth-e.lineWidths[Wt[_t].line])/2,0,0);break}_.translate(0,-e.ls),_.translate(DE,0,0),_.translate(s[0]*Wt[_t].an*.005,s[1]*iE*.01,0),x+=Wt[_t].l+e.tr*.001*e.finalSize}C==="html"?F_=_.toCSS():C==="svg"?F_=_.to2dCSS():T0=[_.props[0],_.props[1],_.props[2],_.props[3],_.props[4],_.props[5],_.props[6],_.props[7],_.props[8],_.props[9],_.props[10],_.props[11],_.props[12],_.props[13],_.props[14],_.props[15]],Mb=M0}P<=_t?(uE=new LetterProps(Mb,C_,KE,f_,F_,T0),this.renderedLetters.push(uE),P+=1,this.lettersChangedFlag=!0):(uE=this.renderedLetters[_t],this.lettersChangedFlag=uE.update(Mb,C_,KE,f_,F_,T0)||this.lettersChangedFlag)}}},TextAnimatorProperty.prototype.getValue=function(){this._elem.globalData.frameId!==this._frameId&&(this._frameId=this._elem.globalData.frameId,this.iterateDynamicProperties())},TextAnimatorProperty.prototype.mHelper=new Matrix,TextAnimatorProperty.prototype.defaultPropsArray=[],extendPrototype([DynamicPropertyContainer],TextAnimatorProperty);function ITextElement(){}ITextElement.prototype.initElement=function(e,r,s){this.lettersChangedFlag=!0,this.initFrame(),this.initBaseData(e,r,s),this.textProperty=new TextProperty(this,e.t,this.dynamicProperties),this.textAnimator=new TextAnimatorProperty(e.t,this.renderType,this),this.initTransform(e,r,s),this.initHierarchy(),this.initRenderable(),this.initRendererElement(),this.createContainerElements(),this.createRenderableComponents(),this.createContent(),this.hide(),this.textAnimator.searchProperties(this.dynamicProperties)},ITextElement.prototype.prepareFrame=function(e){this._mdf=!1,this.prepareRenderableFrame(e),this.prepareProperties(e,this.isInRange)},ITextElement.prototype.createPathShape=function(e,r){var s,d=r.length,f,_="";for(s=0;se?this.textSpans[e].span:createNS(P?"g":"text"),_s<=e){if(x.setAttribute("stroke-linecap","butt"),x.setAttribute("stroke-linejoin","round"),x.setAttribute("stroke-miterlimit","4"),this.textSpans[e].span=x,P){var _m=createNS("g");x.appendChild(_m),this.textSpans[e].childSpan=_m}this.textSpans[e].span=x,this.layerElement.appendChild(x)}x.style.display="inherit"}if(B.reset(),ue&&(C[e].n&&(Wt=-Ei,_n+=s.yOffset,_n+=_i?1:0,_i=!1),this.applyTextPropertiesToMatrix(s,B,C[e].line,Wt,_n),Wt+=C[e].l||0,Wt+=Ei),P){_c=this.globalData.fontManager.getCharData(s.finalText[e],d.fStyle,this.globalData.fontManager.getFontByName(s.f).fFamily);var Qm;if(_c.t===1)Qm=new SVGCompElement(_c.data,this.globalData,this);else{var tE=emptyShapeData;_c.data&&_c.data.shapes&&(tE=this.buildShapeData(_c.data,s.finalSize)),Qm=new SVGShapeElement(tE,this.globalData,this)}if(this.textSpans[e].glyph){var aE=this.textSpans[e].glyph;this.textSpans[e].childSpan.removeChild(aE.layerElement),aE.destroy()}this.textSpans[e].glyph=Qm,Qm._debug=!0,Qm.prepareFrame(0),Qm.renderFrame(),this.textSpans[e].childSpan.appendChild(Qm.layerElement),_c.t===1&&this.textSpans[e].childSpan.setAttribute("transform","scale("+s.finalSize/100+","+s.finalSize/100+")")}else ue&&x.setAttribute("transform","translate("+B.props[12]+","+B.props[13]+")"),x.textContent=C[e].val,x.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve")}ue&&x&&x.setAttribute("d",_t)}for(;e=0;r-=1)(this.completeLayers||this.elements[r])&&this.elements[r].prepareFrame(e-this.layers[r].st);if(this.globalData._mdf)for(r=0;r=0;s-=1)(this.completeLayers||this.elements[s])&&(this.elements[s].prepareFrame(this.renderedFrame-this.layers[s].st),this.elements[s]._mdf&&(this._mdf=!0))}},ICompElement.prototype.renderInnerContent=function(){var e,r=this.layers.length;for(e=0;e=0;d-=1)r.finalTransform.multiply(r.transforms[d].transform.mProps.v);r._mdf=_},processSequences:function(r){var s,d=this.sequenceList.length;for(s=0;s=1){this.buffers=[];var r=this.globalData.canvasContext,s=assetLoader.createCanvas(r.canvas.width,r.canvas.height);this.buffers.push(s);var d=assetLoader.createCanvas(r.canvas.width,r.canvas.height);this.buffers.push(d),this.data.tt>=3&&!document._isProxy&&assetLoader.loadLumaCanvas()}this.canvasContext=this.globalData.canvasContext,this.transformCanvas=this.globalData.transformCanvas,this.renderableEffectsManager=new CVEffects(this),this.searchEffectTransforms()},createContent:function(){},setBlendMode:function(){var r=this.globalData;if(r.blendMode!==this.data.bm){r.blendMode=this.data.bm;var s=getBlendMode(this.data.bm);r.canvasContext.globalCompositeOperation=s}},createRenderableComponents:function(){this.maskManager=new CVMaskElement(this.data,this),this.transformEffects=this.renderableEffectsManager.getEffects(effectTypes.TRANSFORM_EFFECT)},hideElement:function(){!this.hidden&&(!this.isInRange||this.isTransparent)&&(this.hidden=!0)},showElement:function(){this.isInRange&&!this.isTransparent&&(this.hidden=!1,this._isFirstFrame=!0,this.maskManager._isFirstFrame=!0)},clearCanvas:function(r){r.clearRect(this.transformCanvas.tx,this.transformCanvas.ty,this.transformCanvas.w*this.transformCanvas.sx,this.transformCanvas.h*this.transformCanvas.sy)},prepareLayer:function(){if(this.data.tt>=1){var r=this.buffers[0],s=r.getContext("2d");this.clearCanvas(s),s.drawImage(this.canvasContext.canvas,0,0),this.currentTransform=this.canvasContext.getTransform(),this.canvasContext.setTransform(1,0,0,1,0,0),this.clearCanvas(this.canvasContext),this.canvasContext.setTransform(this.currentTransform)}},exitLayer:function(){if(this.data.tt>=1){var r=this.buffers[1],s=r.getContext("2d");this.clearCanvas(s),s.drawImage(this.canvasContext.canvas,0,0),this.canvasContext.setTransform(1,0,0,1,0,0),this.clearCanvas(this.canvasContext),this.canvasContext.setTransform(this.currentTransform);var d=this.comp.getElementById("tp"in this.data?this.data.tp:this.data.ind-1);if(d.renderFrame(!0),this.canvasContext.setTransform(1,0,0,1,0,0),this.data.tt>=3&&!document._isProxy){var f=assetLoader.getLumaCanvas(this.canvasContext.canvas),_=f.getContext("2d");_.drawImage(this.canvasContext.canvas,0,0),this.clearCanvas(this.canvasContext),this.canvasContext.drawImage(f,0,0)}this.canvasContext.globalCompositeOperation=operationsMap[this.data.tt],this.canvasContext.drawImage(r,0,0),this.canvasContext.globalCompositeOperation="destination-over",this.canvasContext.drawImage(this.buffers[0],0,0),this.canvasContext.setTransform(this.currentTransform),this.canvasContext.globalCompositeOperation="source-over"}},renderFrame:function(r){if(!(this.hidden||this.data.hd)&&!(this.data.td===1&&!r)){this.renderTransform(),this.renderRenderable(),this.renderLocalTransform(),this.setBlendMode();var s=this.data.ty===0;this.prepareLayer(),this.globalData.renderer.save(s),this.globalData.renderer.ctxTransform(this.finalTransform.localMat.props),this.globalData.renderer.ctxOpacity(this.finalTransform.localOpacity),this.renderInnerContent(),this.globalData.renderer.restore(s),this.exitLayer(),this.maskManager.hasMasks&&this.globalData.renderer.restore(!0),this._isFirstFrame&&(this._isFirstFrame=!1)}},destroy:function(){this.canvasContext=null,this.data=null,this.globalData=null,this.maskManager.destroy()},mHelper:new Matrix},CVBaseElement.prototype.hide=CVBaseElement.prototype.hideElement,CVBaseElement.prototype.show=CVBaseElement.prototype.showElement;function CVShapeData(e,r,s,d){this.styledShapes=[],this.tr=[0,0,0,0,0,0];var f=4;r.ty==="rc"?f=5:r.ty==="el"?f=6:r.ty==="sr"&&(f=7),this.sh=ShapePropertyFactory.getShapeProp(e,r,f,e);var _,C=s.length,P;for(_=0;_=0;_-=1){if(ue=this.searchProcessedElement(e[_]),ue?r[_]=s[ue-1]:e[_]._shouldRender=d,e[_].ty==="fl"||e[_].ty==="st"||e[_].ty==="gf"||e[_].ty==="gs")ue?r[_].style.closed=!1:r[_]=this.createStyleElement(e[_],_i),B.push(r[_].style);else if(e[_].ty==="gr"){if(!ue)r[_]=this.createGroupElement(e[_]);else for(x=r[_].it.length,P=0;P=0;f-=1)r[f].ty==="tr"?(C=s[f].transform,this.renderShapeTransform(e,C)):r[f].ty==="sh"||r[f].ty==="el"||r[f].ty==="rc"||r[f].ty==="sr"?this.renderPath(r[f],s[f]):r[f].ty==="fl"?this.renderFill(r[f],s[f],C):r[f].ty==="st"?this.renderStroke(r[f],s[f],C):r[f].ty==="gf"||r[f].ty==="gs"?this.renderGradientFill(r[f],s[f],C):r[f].ty==="gr"?this.renderShape(C,r[f].it,s[f].it):r[f].ty;d&&this.drawLayer()},CVShapeElement.prototype.renderStyledShape=function(e,r){if(this._isFirstFrame||r._mdf||e.transforms._mdf){var s=e.trNodes,d=r.paths,f,_,C,P=d._length;s.length=0;var x=e.transforms.finalTransform;for(C=0;C=1?_t=.99:_t<=-1&&(_t=-.99);var ue=x*_t,Wt=Math.cos(B+r.a.v)*ue+C[0],_n=Math.sin(B+r.a.v)*ue+C[1];f=_.createRadialGradient(Wt,_n,0,C[0],C[1],x)}var _i,Ei=e.g.p,_a=r.g.c,Di=1;for(_i=0;_i_&&x==="xMidYMid slice"||f<_&&x!=="xMidYMid slice"?(P=d,C=P*_):(C=s,P=C/_),r.drawImage(this.img,(s-C)/2,(d-P)/2,C,P,0,0,this.assetData.w,this.assetData.h),this.img=e}},CVImageElement.prototype.renderInnerContent=function(){this.canvasContext.drawImage(this.img,0,0)},CVImageElement.prototype.destroy=function(){this.img=null};function CVSolidElement(e,r,s){this.initElement(e,r,s)}extendPrototype([BaseElement,TransformElement,CVBaseElement,HierarchyElement,FrameElement,RenderableElement],CVSolidElement),CVSolidElement.prototype.initElement=SVGShapeElement.prototype.initElement,CVSolidElement.prototype.prepareFrame=IImageElement.prototype.prepareFrame,CVSolidElement.prototype.renderInnerContent=function(){this.globalData.renderer.ctxFillStyle(this.data.sc),this.globalData.renderer.ctxFillRect(0,0,this.data.sw,this.data.sh)};function CanvasRendererBase(){}extendPrototype([BaseRenderer],CanvasRendererBase),CanvasRendererBase.prototype.createShape=function(e){return new CVShapeElement(e,this.globalData,this)},CanvasRendererBase.prototype.createText=function(e){return new CVTextElement(e,this.globalData,this)},CanvasRendererBase.prototype.createImage=function(e){return new CVImageElement(e,this.globalData,this)},CanvasRendererBase.prototype.createSolid=function(e){return new CVSolidElement(e,this.globalData,this)},CanvasRendererBase.prototype.createNull=SVGRenderer.prototype.createNull,CanvasRendererBase.prototype.ctxTransform=function(e){e[0]===1&&e[1]===0&&e[4]===0&&e[5]===1&&e[12]===0&&e[13]===0||this.canvasContext.transform(e[0],e[1],e[4],e[5],e[12],e[13])},CanvasRendererBase.prototype.ctxOpacity=function(e){this.canvasContext.globalAlpha*=e<0?0:e},CanvasRendererBase.prototype.ctxFillStyle=function(e){this.canvasContext.fillStyle=e},CanvasRendererBase.prototype.ctxStrokeStyle=function(e){this.canvasContext.strokeStyle=e},CanvasRendererBase.prototype.ctxLineWidth=function(e){this.canvasContext.lineWidth=e},CanvasRendererBase.prototype.ctxLineCap=function(e){this.canvasContext.lineCap=e},CanvasRendererBase.prototype.ctxLineJoin=function(e){this.canvasContext.lineJoin=e},CanvasRendererBase.prototype.ctxMiterLimit=function(e){this.canvasContext.miterLimit=e},CanvasRendererBase.prototype.ctxFill=function(e){this.canvasContext.fill(e)},CanvasRendererBase.prototype.ctxFillRect=function(e,r,s,d){this.canvasContext.fillRect(e,r,s,d)},CanvasRendererBase.prototype.ctxStroke=function(){this.canvasContext.stroke()},CanvasRendererBase.prototype.reset=function(){if(!this.renderConfig.clearCanvas){this.canvasContext.restore();return}this.contextData.reset()},CanvasRendererBase.prototype.save=function(){this.canvasContext.save()},CanvasRendererBase.prototype.restore=function(e){if(!this.renderConfig.clearCanvas){this.canvasContext.restore();return}e&&(this.globalData.blendMode="source-over"),this.contextData.restore(e)},CanvasRendererBase.prototype.configAnimation=function(e){if(this.animationItem.wrapper){this.animationItem.container=createTag("canvas");var r=this.animationItem.container.style;r.width="100%",r.height="100%";var s="0px 0px 0px";r.transformOrigin=s,r.mozTransformOrigin=s,r.webkitTransformOrigin=s,r["-webkit-transform"]=s,r.contentVisibility=this.renderConfig.contentVisibility,this.animationItem.wrapper.appendChild(this.animationItem.container),this.canvasContext=this.animationItem.container.getContext("2d"),this.renderConfig.className&&this.animationItem.container.setAttribute("class",this.renderConfig.className),this.renderConfig.id&&this.animationItem.container.setAttribute("id",this.renderConfig.id)}else this.canvasContext=this.renderConfig.context;this.contextData.setContext(this.canvasContext),this.data=e,this.layers=e.layers,this.transformCanvas={w:e.w,h:e.h,sx:0,sy:0,tx:0,ty:0},this.setupGlobalData(e,document.body),this.globalData.canvasContext=this.canvasContext,this.globalData.renderer=this,this.globalData.isDashed=!1,this.globalData.progressiveLoad=this.renderConfig.progressiveLoad,this.globalData.transformCanvas=this.transformCanvas,this.elements=createSizedArray(e.layers.length),this.updateContainerSize()},CanvasRendererBase.prototype.updateContainerSize=function(e,r){this.reset();var s,d;e?(s=e,d=r,this.canvasContext.canvas.width=s,this.canvasContext.canvas.height=d):(this.animationItem.wrapper&&this.animationItem.container?(s=this.animationItem.wrapper.offsetWidth,d=this.animationItem.wrapper.offsetHeight):(s=this.canvasContext.canvas.width,d=this.canvasContext.canvas.height),this.canvasContext.canvas.width=s*this.renderConfig.dpr,this.canvasContext.canvas.height=d*this.renderConfig.dpr);var f,_;if(this.renderConfig.preserveAspectRatio.indexOf("meet")!==-1||this.renderConfig.preserveAspectRatio.indexOf("slice")!==-1){var C=this.renderConfig.preserveAspectRatio.split(" "),P=C[1]||"meet",x=C[0]||"xMidYMid",B=x.substr(0,4),_t=x.substr(4);f=s/d,_=this.transformCanvas.w/this.transformCanvas.h,_>f&&P==="meet"||_f&&P==="slice")?this.transformCanvas.tx=(s-this.transformCanvas.w*(d/this.transformCanvas.h))/2*this.renderConfig.dpr:B==="xMax"&&(_f&&P==="slice")?this.transformCanvas.tx=(s-this.transformCanvas.w*(d/this.transformCanvas.h))*this.renderConfig.dpr:this.transformCanvas.tx=0,_t==="YMid"&&(_>f&&P==="meet"||_f&&P==="meet"||_=0;e-=1)this.elements[e]&&this.elements[e].destroy&&this.elements[e].destroy();this.elements.length=0,this.globalData.canvasContext=null,this.animationItem.container=null,this.destroyed=!0},CanvasRendererBase.prototype.renderFrame=function(e,r){if(!(this.renderedFrame===e&&this.renderConfig.clearCanvas===!0&&!r||this.destroyed||e===-1)){this.renderedFrame=e,this.globalData.frameNum=e-this.animationItem._isFirstFrame,this.globalData.frameId+=1,this.globalData._mdf=!this.renderConfig.clearCanvas||r,this.globalData.projectInterface.currentFrame=e;var s,d=this.layers.length;for(this.completeLayers||this.checkLayers(e),s=d-1;s>=0;s-=1)(this.completeLayers||this.elements[s])&&this.elements[s].prepareFrame(e-this.layers[s].st);if(this.globalData._mdf){for(this.renderConfig.clearCanvas===!0?this.canvasContext.clearRect(0,0,this.transformCanvas.w,this.transformCanvas.h):this.save(),s=d-1;s>=0;s-=1)(this.completeLayers||this.elements[s])&&this.elements[s].renderFrame();this.renderConfig.clearCanvas!==!0&&this.restore()}}},CanvasRendererBase.prototype.buildItem=function(e){var r=this.elements;if(!(r[e]||this.layers[e].ty===99)){var s=this.createItem(this.layers[e],this,this.globalData);r[e]=s,s.initExpressions()}},CanvasRendererBase.prototype.checkPendingElements=function(){for(;this.pendingElements.length;){var e=this.pendingElements.pop();e.checkParenting()}},CanvasRendererBase.prototype.hide=function(){this.animationItem.container.style.display="none"},CanvasRendererBase.prototype.show=function(){this.animationItem.container.style.display="block"};function CanvasContext(){this.opacity=-1,this.transform=createTypedArray("float32",16),this.fillStyle="",this.strokeStyle="",this.lineWidth="",this.lineCap="",this.lineJoin="",this.miterLimit="",this.id=Math.random()}function CVContextData(){this.stack=[],this.cArrPos=0,this.cTr=new Matrix;var e,r=15;for(e=0;e=0;r-=1)(this.completeLayers||this.elements[r])&&this.elements[r].renderFrame()},CVCompElement.prototype.destroy=function(){var e,r=this.layers.length;for(e=r-1;e>=0;e-=1)this.elements[e]&&this.elements[e].destroy();this.layers=null,this.elements=null},CVCompElement.prototype.createComp=function(e){return new CVCompElement(e,this.globalData,this)};function CanvasRenderer(e,r){this.animationItem=e,this.renderConfig={clearCanvas:r&&r.clearCanvas!==void 0?r.clearCanvas:!0,context:r&&r.context||null,progressiveLoad:r&&r.progressiveLoad||!1,preserveAspectRatio:r&&r.preserveAspectRatio||"xMidYMid meet",imagePreserveAspectRatio:r&&r.imagePreserveAspectRatio||"xMidYMid slice",contentVisibility:r&&r.contentVisibility||"visible",className:r&&r.className||"",id:r&&r.id||"",runExpressions:!r||r.runExpressions===void 0||r.runExpressions},this.renderConfig.dpr=r&&r.dpr||1,this.animationItem.wrapper&&(this.renderConfig.dpr=r&&r.dpr||window.devicePixelRatio||1),this.renderedFrame=-1,this.globalData={frameNum:-1,_mdf:!1,renderConfig:this.renderConfig,currentGlobalAlpha:-1},this.contextData=new CVContextData,this.elements=[],this.pendingElements=[],this.transformMat=new Matrix,this.completeLayers=!1,this.rendererType="canvas",this.renderConfig.clearCanvas&&(this.ctxTransform=this.contextData.transform.bind(this.contextData),this.ctxOpacity=this.contextData.opacity.bind(this.contextData),this.ctxFillStyle=this.contextData.fillStyle.bind(this.contextData),this.ctxStrokeStyle=this.contextData.strokeStyle.bind(this.contextData),this.ctxLineWidth=this.contextData.lineWidth.bind(this.contextData),this.ctxLineCap=this.contextData.lineCap.bind(this.contextData),this.ctxLineJoin=this.contextData.lineJoin.bind(this.contextData),this.ctxMiterLimit=this.contextData.miterLimit.bind(this.contextData),this.ctxFill=this.contextData.fill.bind(this.contextData),this.ctxFillRect=this.contextData.fillRect.bind(this.contextData),this.ctxStroke=this.contextData.stroke.bind(this.contextData),this.save=this.contextData.save.bind(this.contextData))}extendPrototype([CanvasRendererBase],CanvasRenderer),CanvasRenderer.prototype.createComp=function(e){return new CVCompElement(e,this.globalData,this)};function HBaseElement(){}HBaseElement.prototype={checkBlendMode:function(){},initRendererElement:function(){this.baseElement=createTag(this.data.tg||"div"),this.data.hasMask?(this.svgElement=createNS("svg"),this.layerElement=createNS("g"),this.maskedElement=this.layerElement,this.svgElement.appendChild(this.layerElement),this.baseElement.appendChild(this.svgElement)):this.layerElement=this.baseElement,styleDiv(this.baseElement)},createContainerElements:function(){this.renderableEffectsManager=new CVEffects(this),this.transformedElement=this.baseElement,this.maskedElement=this.layerElement,this.data.ln&&this.layerElement.setAttribute("id",this.data.ln),this.data.cl&&this.layerElement.setAttribute("class",this.data.cl),this.data.bm!==0&&this.setBlendMode()},renderElement:function(){var r=this.transformedElement?this.transformedElement.style:{};if(this.finalTransform._matMdf){var s=this.finalTransform.mat.toCSS();r.transform=s,r.webkitTransform=s}this.finalTransform._opMdf&&(r.opacity=this.finalTransform.mProp.o.v)},renderFrame:function(){this.data.hd||this.hidden||(this.renderTransform(),this.renderRenderable(),this.renderElement(),this.renderInnerContent(),this._isFirstFrame&&(this._isFirstFrame=!1))},destroy:function(){this.layerElement=null,this.transformedElement=null,this.matteElement&&(this.matteElement=null),this.maskManager&&(this.maskManager.destroy(),this.maskManager=null)},createRenderableComponents:function(){this.maskManager=new MaskElement(this.data,this,this.globalData)},addEffects:function(){},setMatte:function(){}},HBaseElement.prototype.getBaseElement=SVGBaseElement.prototype.getBaseElement,HBaseElement.prototype.destroyBaseElement=HBaseElement.prototype.destroy,HBaseElement.prototype.buildElementParenting=BaseRenderer.prototype.buildElementParenting;function HSolidElement(e,r,s){this.initElement(e,r,s)}extendPrototype([BaseElement,TransformElement,HBaseElement,HierarchyElement,FrameElement,RenderableDOMElement],HSolidElement),HSolidElement.prototype.createContent=function(){var e;this.data.hasMask?(e=createNS("rect"),e.setAttribute("width",this.data.sw),e.setAttribute("height",this.data.sh),e.setAttribute("fill",this.data.sc),this.svgElement.setAttribute("width",this.data.sw),this.svgElement.setAttribute("height",this.data.sh)):(e=createTag("div"),e.style.width=this.data.sw+"px",e.style.height=this.data.sh+"px",e.style.backgroundColor=this.data.sc),this.layerElement.appendChild(e)};function HShapeElement(e,r,s){this.shapes=[],this.shapesData=e.shapes,this.stylesList=[],this.shapeModifiers=[],this.itemsData=[],this.processedElements=[],this.animatedContents=[],this.shapesContainer=createNS("g"),this.initElement(e,r,s),this.prevViewData=[],this.currentBBox={x:999999,y:-999999,h:0,w:0}}extendPrototype([BaseElement,TransformElement,HSolidElement,SVGShapeElement,HBaseElement,HierarchyElement,FrameElement,RenderableElement],HShapeElement),HShapeElement.prototype._renderShapeFrame=HShapeElement.prototype.renderInnerContent,HShapeElement.prototype.createContent=function(){var e;if(this.baseElement.style.fontSize=0,this.data.hasMask)this.layerElement.appendChild(this.shapesContainer),e=this.svgElement;else{e=createNS("svg");var r=this.comp.data?this.comp.data:this.globalData.compSize;e.setAttribute("width",r.w),e.setAttribute("height",r.h),e.appendChild(this.shapesContainer),this.layerElement.appendChild(e)}this.searchShapes(this.shapesData,this.itemsData,this.prevViewData,this.shapesContainer,0,[],!0),this.filterUniqueShapes(),this.shapeCont=e},HShapeElement.prototype.getTransformedPoint=function(e,r){var s,d=e.length;for(s=0;s0&&x<1&&f[Wt].push(this.calculateF(x,e,r,s,d,Wt))):(B=C*C-4*P*_,B>=0&&(_t=(-C+bmSqrt(B))/(2*_),_t>0&&_t<1&&f[Wt].push(this.calculateF(_t,e,r,s,d,Wt)),ue=(-C-bmSqrt(B))/(2*_),ue>0&&ue<1&&f[Wt].push(this.calculateF(ue,e,r,s,d,Wt)))));this.shapeBoundingBox.left=bmMin.apply(null,f[0]),this.shapeBoundingBox.top=bmMin.apply(null,f[1]),this.shapeBoundingBox.right=bmMax.apply(null,f[0]),this.shapeBoundingBox.bottom=bmMax.apply(null,f[1])},HShapeElement.prototype.calculateF=function(e,r,s,d,f,_){return bmPow(1-e,3)*r[_]+3*bmPow(1-e,2)*e*s[_]+3*(1-e)*bmPow(e,2)*d[_]+bmPow(e,3)*f[_]},HShapeElement.prototype.calculateBoundingBox=function(e,r){var s,d=e.length;for(s=0;ss&&(s=f)}s*=e.mult}else s=e.v*e.mult;r.x-=s,r.xMax+=s,r.y-=s,r.yMax+=s},HShapeElement.prototype.currentBoxContains=function(e){return this.currentBBox.x<=e.x&&this.currentBBox.y<=e.y&&this.currentBBox.width+this.currentBBox.x>=e.x+e.width&&this.currentBBox.height+this.currentBBox.y>=e.y+e.height},HShapeElement.prototype.renderInnerContent=function(){if(this._renderShapeFrame(),!this.hidden&&(this._isFirstFrame||this._mdf)){var e=this.tempBoundingBox,r=999999;if(e.x=r,e.xMax=-r,e.y=r,e.yMax=-r,this.calculateBoundingBox(this.itemsData,e),e.width=e.xMax=0;r-=1){var d=this.hierarchy[r].finalTransform.mProp;this.mat.translate(-d.p.v[0],-d.p.v[1],d.p.v[2]),this.mat.rotateX(-d.or.v[0]).rotateY(-d.or.v[1]).rotateZ(d.or.v[2]),this.mat.rotateX(-d.rx.v).rotateY(-d.ry.v).rotateZ(d.rz.v),this.mat.scale(1/d.s.v[0],1/d.s.v[1],1/d.s.v[2]),this.mat.translate(d.a.v[0],d.a.v[1],d.a.v[2])}if(this.p?this.mat.translate(-this.p.v[0],-this.p.v[1],this.p.v[2]):this.mat.translate(-this.px.v,-this.py.v,this.pz.v),this.a){var f;this.p?f=[this.p.v[0]-this.a.v[0],this.p.v[1]-this.a.v[1],this.p.v[2]-this.a.v[2]]:f=[this.px.v-this.a.v[0],this.py.v-this.a.v[1],this.pz.v-this.a.v[2]];var _=Math.sqrt(Math.pow(f[0],2)+Math.pow(f[1],2)+Math.pow(f[2],2)),C=[f[0]/_,f[1]/_,f[2]/_],P=Math.sqrt(C[2]*C[2]+C[0]*C[0]),x=Math.atan2(C[1],P),B=Math.atan2(C[0],-C[2]);this.mat.rotateY(B).rotateX(-x)}this.mat.rotateX(-this.rx.v).rotateY(-this.ry.v).rotateZ(this.rz.v),this.mat.rotateX(-this.or.v[0]).rotateY(-this.or.v[1]).rotateZ(this.or.v[2]),this.mat.translate(this.globalData.compSize.w/2,this.globalData.compSize.h/2,0),this.mat.translate(0,0,this.pe.v);var _t=!this._prevMat.equals(this.mat);if((_t||this.pe._mdf)&&this.comp.threeDElements){s=this.comp.threeDElements.length;var ue,Wt,_n;for(r=0;r=e)return this.threeDElements[r].perspectiveElem;r+=1}return null},HybridRendererBase.prototype.createThreeDContainer=function(e,r){var s=createTag("div"),d,f;styleDiv(s);var _=createTag("div");if(styleDiv(_),r==="3d"){d=s.style,d.width=this.globalData.compSize.w+"px",d.height=this.globalData.compSize.h+"px";var C="50% 50%";d.webkitTransformOrigin=C,d.mozTransformOrigin=C,d.transformOrigin=C,f=_.style;var P="matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)";f.transform=P,f.webkitTransform=P}s.appendChild(_);var x={container:_,perspectiveElem:s,startPos:e,endPos:e,type:r};return this.threeDElements.push(x),x},HybridRendererBase.prototype.build3dContainers=function(){var e,r=this.layers.length,s,d="";for(e=0;e=0;e-=1)this.resizerElem.appendChild(this.threeDElements[e].perspectiveElem)},HybridRendererBase.prototype.addTo3dContainer=function(e,r){for(var s=0,d=this.threeDElements.length;ss?(f=e/this.globalData.compSize.w,_=e/this.globalData.compSize.w,C=0,P=(r-this.globalData.compSize.h*(e/this.globalData.compSize.w))/2):(f=r/this.globalData.compSize.h,_=r/this.globalData.compSize.h,C=(e-this.globalData.compSize.w*(r/this.globalData.compSize.h))/2,P=0);var x=this.resizerElem.style;x.webkitTransform="matrix3d("+f+",0,0,0,0,"+_+",0,0,0,0,1,0,"+C+","+P+",0,1)",x.transform=x.webkitTransform},HybridRendererBase.prototype.renderFrame=SVGRenderer.prototype.renderFrame,HybridRendererBase.prototype.hide=function(){this.resizerElem.style.display="none"},HybridRendererBase.prototype.show=function(){this.resizerElem.style.display="block"},HybridRendererBase.prototype.initItems=function(){if(this.buildAllItems(),this.camera)this.camera.setup();else{var e=this.globalData.compSize.w,r=this.globalData.compSize.h,s,d=this.threeDElements.length;for(s=0;s=B;)gE/=2,cE/=2,_E>>>=1;return(gE+_E)/cE};return RE.int32=function(){return aE.g(4)|0},RE.quick=function(){return aE.g(4)/4294967296},RE.double=RE,_a(_o(aE.S),e),(_c.pass||_m||function(lE,gE,cE,_E){return _E&&(_E.S&&_i(_E,aE),lE.state=function(){return _i(aE,{})}),cE?(r[C]=lE,gE):lE})(RE,tE,"global"in _c?_c.global:this==r,_c.state)}r["seed"+C]=Wt;function _n(_s){var _c,_m=_s.length,Qm=this,tE=0,aE=Qm.i=Qm.j=0,RE=Qm.S=[];for(_m||(_s=[_m++]);tEs){var d=s;s=r,r=d}return Math.min(Math.max(e,r),s)}function radiansToDegrees(e){return e/degToRads}var radians_to_degrees=radiansToDegrees;function degreesToRadians(e){return e*degToRads}var degrees_to_radians=radiansToDegrees,helperLengthArray=[0,0,0,0,0,0];function length(e,r){if(typeof e=="number"||e instanceof Number)return r=r||0,Math.abs(e-r);r||(r=helperLengthArray);var s,d=Math.min(e.length,r.length),f=0;for(s=0;s.5?B/(2-f-_):B/(f+_),f){case r:C=(s-d)/B+(s1&&(s-=1),s<1/6?e+(r-e)*6*s:s<1/2?r:s<2/3?e+(r-e)*(2/3-s)*6:e}function hslToRgb(e){var r=e[0],s=e[1],d=e[2],f,_,C;if(s===0)f=d,C=d,_=d;else{var P=d<.5?d*(1+s):d+s-d*s,x=2*d-P;f=hue2rgb(x,P,r+1/3),_=hue2rgb(x,P,r),C=hue2rgb(x,P,r-1/3)}return[f,_,C,e[3]]}function linear(e,r,s,d,f){if((d===void 0||f===void 0)&&(d=r,f=s,r=0,s=1),s=s)return f;var C=s===r?0:(e-r)/(s-r);if(!d.length)return d+(f-d)*C;var P,x=d.length,B=createTypedArray("float32",x);for(P=0;P1){for(f=0;f<_;f+=1)_t[f]=this.pv[f]+C[f]+(-s+s*2*BMMath.random())*B;return _t}return this.pv+C[0]+(-s+s*2*BMMath.random())*B}).bind(this);thisProperty.loopIn&&(loopIn=thisProperty.loopIn.bind(thisProperty),loop_in=loopIn),thisProperty.loopOut&&(loopOut=thisProperty.loopOut.bind(thisProperty),loop_out=loopOut),thisProperty.smooth&&(smooth=thisProperty.smooth.bind(thisProperty));function loopInDuration(e,r){return loopIn(e,r,!0)}function loopOutDuration(e,r){return loopOut(e,r,!0)}this.getValueAtTime&&(valueAtTime=this.getValueAtTime.bind(this)),this.getVelocityAtTime&&(velocityAtTime=this.getVelocityAtTime.bind(this));var comp=elem.comp.globalData.projectInterface.bind(elem.comp.globalData.projectInterface);function lookAt(e,r){var s=[r[0]-e[0],r[1]-e[1],r[2]-e[2]],d=Math.atan2(s[0],Math.sqrt(s[1]*s[1]+s[2]*s[2]))/degToRads,f=-Math.atan2(s[1],s[2])/degToRads;return[f,d,0]}function easeOut(e,r,s,d,f){return applyEase(easeOutBez,e,r,s,d,f)}function easeIn(e,r,s,d,f){return applyEase(easeInBez,e,r,s,d,f)}function ease(e,r,s,d,f){return applyEase(easeInOutBez,e,r,s,d,f)}function applyEase(e,r,s,d,f,_){f===void 0?(f=s,_=d):r=(r-s)/(d-s),r>1?r=1:r<0&&(r=0);var C=e(r);if($bm_isInstanceOfArray(f)){var P,x=f.length,B=createTypedArray("float32",x);for(P=0;Pdata.k[r].t&&edata.k[r+1].t-e?(d=r+2,f=data.k[r+1].t):(d=r+1,f=data.k[r].t);break}d===-1&&(d=r+1,f=data.k[r].t)}var _={};return _.index=d,_.time=f/elem.comp.globalData.frameRate,_}function key(e){var r,s,d;if(!data.k.length||typeof data.k[0]=="number")throw new Error("The property has no keyframe at index "+e);e-=1,r={time:data.k[e].t/elem.comp.globalData.frameRate,value:[]};var f=Object.prototype.hasOwnProperty.call(data.k[e],"s")?data.k[e].s:data.k[e-1].e;for(d=f.length,s=0;s_a.length-1)&&(_n=_a.length-1),_s=_a[_a.length-1-_n].t,_o=Di-_s);var _c,_m,Qm;if(Wt==="pingpong"){var tE=Math.floor((Ei-_s)/_o);if(tE%2!==0)return this.getValueAtTime((_o-(Ei-_s)%_o+_s)/this.comp.globalData.frameRate,0)}else if(Wt==="offset"){var aE=this.getValueAtTime(_s/this.comp.globalData.frameRate,0),RE=this.getValueAtTime(Di/this.comp.globalData.frameRate,0),lE=this.getValueAtTime(((Ei-_s)%_o+_s)/this.comp.globalData.frameRate,0),gE=Math.floor((Ei-_s)/_o);if(this.pv.length){for(Qm=new Array(aE.length),_m=Qm.length,_c=0;_c<_m;_c+=1)Qm[_c]=(RE[_c]-aE[_c])*gE+lE[_c];return Qm}return(RE-aE)*gE+lE}else if(Wt==="continue"){var cE=this.getValueAtTime(Di/this.comp.globalData.frameRate,0),_E=this.getValueAtTime((Di-.001)/this.comp.globalData.frameRate,0);if(this.pv.length){for(Qm=new Array(cE.length),_m=Qm.length,_c=0;_c<_m;_c+=1)Qm[_c]=cE[_c]+(cE[_c]-_E[_c])*((Ei-Di)/this.comp.globalData.frameRate)/5e-4;return Qm}return cE+(cE-_E)*((Ei-Di)/.001)}return this.getValueAtTime(((Ei-_s)%_o+_s)/this.comp.globalData.frameRate,0)}function r(Wt,_n,_i){if(!this.k)return this.pv;Wt=Wt?Wt.toLowerCase():"";var Ei=this.comp.renderedFrame,_a=this.keyframes,Di=_a[0].t;if(Ei>=Di)return this.pv;var _o,_s;_i?(_n?_o=Math.abs(this.elem.comp.globalData.frameRate*_n):_o=Math.max(0,this.elem.data.op-Di),_s=Di+_o):((!_n||_n>_a.length-1)&&(_n=_a.length-1),_s=_a[_n].t,_o=_s-Di);var _c,_m,Qm;if(Wt==="pingpong"){var tE=Math.floor((Di-Ei)/_o);if(tE%2===0)return this.getValueAtTime(((Di-Ei)%_o+Di)/this.comp.globalData.frameRate,0)}else if(Wt==="offset"){var aE=this.getValueAtTime(Di/this.comp.globalData.frameRate,0),RE=this.getValueAtTime(_s/this.comp.globalData.frameRate,0),lE=this.getValueAtTime((_o-(Di-Ei)%_o+Di)/this.comp.globalData.frameRate,0),gE=Math.floor((Di-Ei)/_o)+1;if(this.pv.length){for(Qm=new Array(aE.length),_m=Qm.length,_c=0;_c<_m;_c+=1)Qm[_c]=lE[_c]-(RE[_c]-aE[_c])*gE;return Qm}return lE-(RE-aE)*gE}else if(Wt==="continue"){var cE=this.getValueAtTime(Di/this.comp.globalData.frameRate,0),_E=this.getValueAtTime((Di+.001)/this.comp.globalData.frameRate,0);if(this.pv.length){for(Qm=new Array(cE.length),_m=Qm.length,_c=0;_c<_m;_c+=1)Qm[_c]=cE[_c]+(cE[_c]-_E[_c])*(Di-Ei)/.001;return Qm}return cE+(cE-_E)*(Di-Ei)/.001}return this.getValueAtTime((_o-((Di-Ei)%_o+Di))/this.comp.globalData.frameRate,0)}function s(Wt,_n){if(!this.k)return this.pv;if(Wt=(Wt||.4)*.5,_n=Math.floor(_n||5),_n<=1)return this.pv;var _i=this.comp.renderedFrame/this.comp.globalData.frameRate,Ei=_i-Wt,_a=_i+Wt,Di=_n>1?(_a-Ei)/(_n-1):1,_o=0,_s=0,_c;this.pv.length?_c=createTypedArray("float32",this.pv.length):_c=0;for(var _m;_o<_n;){if(_m=this.getValueAtTime(Ei+_o*Di),this.pv.length)for(_s=0;_s_o){var tE=_s,aE=Ei.c&&_s===_c-1?0:_s+1,RE=(_o-_m)/Di[_s].addedLength;Qm=bez.getPointInSegment(Ei.v[tE],Ei.v[aE],Ei.o[tE],Ei.i[aE],RE,Di[_s]);break}else _m+=Di[_s].addedLength;_s+=1}return Qm||(Qm=Ei.c?[Ei.v[0][0],Ei.v[0][1]]:[Ei.v[Ei._length-1][0],Ei.v[Ei._length-1][1]]),Qm},vectorOnPath:function(_n,_i,Ei){_n==1?_n=this.v.c:_n==0&&(_n=.999);var _a=this.pointOnPath(_n,_i),Di=this.pointOnPath(_n+.001,_i),_o=Di[0]-_a[0],_s=Di[1]-_a[1],_c=Math.sqrt(Math.pow(_o,2)+Math.pow(_s,2));if(_c===0)return[0,0];var _m=Ei==="tangent"?[_o/_c,_s/_c]:[-_s/_c,_o/_c];return _m},tangentOnPath:function(_n,_i){return this.vectorOnPath(_n,_i,"tangent")},normalOnPath:function(_n,_i){return this.vectorOnPath(_n,_i,"normal")},setGroupProperty:expressionHelpers.setGroupProperty,getValueAtTime:expressionHelpers.getStaticValueAtTime},extendPrototype([_t],x),extendPrototype([_t],B),B.prototype.getValueAtTime=P,B.prototype.initiateExpression=ExpressionManager.initiateExpression;var ue=ShapePropertyFactory.getShapeProp;ShapePropertyFactory.getShapeProp=function(Wt,_n,_i,Ei,_a){var Di=ue(Wt,_n,_i,Ei,_a);return Di.propertyIndex=_n.ix,Di.lock=!1,_i===3?expressionHelpers.searchExpressions(Wt,_n.pt,Di):_i===4&&expressionHelpers.searchExpressions(Wt,_n.ks,Di),Di.k&&Wt.addDynamicProperty(Di),Di}}function initialize$1(){addPropertyDecorator()}function addDecorator(){function e(){return this.data.d.x?(this.calculateExpression=ExpressionManager.initiateExpression.bind(this)(this.elem,this.data.d,this),this.addEffect(this.getExpressionValue.bind(this)),!0):null}TextProperty.prototype.getExpressionValue=function(r,s){var d=this.calculateExpression(s);if(r.t!==d){var f={};return this.copyData(f,r),f.t=d.toString(),f.__complete=!1,f}return r},TextProperty.prototype.searchProperty=function(){var r=this.searchKeyframes(),s=this.searchExpressions();return this.kf=r||s,this.kf},TextProperty.prototype.searchExpressions=e}function initialize(){addDecorator()}function SVGComposableEffect(){}SVGComposableEffect.prototype={createMergeNode:function e(r,s){var d=createNS("feMerge");d.setAttribute("result",r);var f,_;for(_=0;_=B?ue=_i<0?d:f:ue=d+_n*Math.pow((P-e)/_i,1/s),_t[Wt]=ue,Wt+=1,_+=256/(C-1);return _t.join(" ")},SVGProLevelsFilter.prototype.renderFrame=function(e){if(e||this.filterManager._mdf){var r,s=this.filterManager.effectElements;this.feFuncRComposed&&(e||s[3].p._mdf||s[4].p._mdf||s[5].p._mdf||s[6].p._mdf||s[7].p._mdf)&&(r=this.getTableValue(s[3].p.v,s[4].p.v,s[5].p.v,s[6].p.v,s[7].p.v),this.feFuncRComposed.setAttribute("tableValues",r),this.feFuncGComposed.setAttribute("tableValues",r),this.feFuncBComposed.setAttribute("tableValues",r)),this.feFuncR&&(e||s[10].p._mdf||s[11].p._mdf||s[12].p._mdf||s[13].p._mdf||s[14].p._mdf)&&(r=this.getTableValue(s[10].p.v,s[11].p.v,s[12].p.v,s[13].p.v,s[14].p.v),this.feFuncR.setAttribute("tableValues",r)),this.feFuncG&&(e||s[17].p._mdf||s[18].p._mdf||s[19].p._mdf||s[20].p._mdf||s[21].p._mdf)&&(r=this.getTableValue(s[17].p.v,s[18].p.v,s[19].p.v,s[20].p.v,s[21].p.v),this.feFuncG.setAttribute("tableValues",r)),this.feFuncB&&(e||s[24].p._mdf||s[25].p._mdf||s[26].p._mdf||s[27].p._mdf||s[28].p._mdf)&&(r=this.getTableValue(s[24].p.v,s[25].p.v,s[26].p.v,s[27].p.v,s[28].p.v),this.feFuncB.setAttribute("tableValues",r)),this.feFuncA&&(e||s[31].p._mdf||s[32].p._mdf||s[33].p._mdf||s[34].p._mdf||s[35].p._mdf)&&(r=this.getTableValue(s[31].p.v,s[32].p.v,s[33].p.v,s[34].p.v,s[35].p.v),this.feFuncA.setAttribute("tableValues",r))}};function SVGDropShadowEffect(e,r,s,d,f){var _=r.container.globalData.renderConfig.filterSize,C=r.data.fs||_;e.setAttribute("x",C.x||_.x),e.setAttribute("y",C.y||_.y),e.setAttribute("width",C.width||_.width),e.setAttribute("height",C.height||_.height),this.filterManager=r;var P=createNS("feGaussianBlur");P.setAttribute("in","SourceAlpha"),P.setAttribute("result",d+"_drop_shadow_1"),P.setAttribute("stdDeviation","0"),this.feGaussianBlur=P,e.appendChild(P);var x=createNS("feOffset");x.setAttribute("dx","25"),x.setAttribute("dy","0"),x.setAttribute("in",d+"_drop_shadow_1"),x.setAttribute("result",d+"_drop_shadow_2"),this.feOffset=x,e.appendChild(x);var B=createNS("feFlood");B.setAttribute("flood-color","#00ff00"),B.setAttribute("flood-opacity","1"),B.setAttribute("result",d+"_drop_shadow_3"),this.feFlood=B,e.appendChild(B);var _t=createNS("feComposite");_t.setAttribute("in",d+"_drop_shadow_3"),_t.setAttribute("in2",d+"_drop_shadow_2"),_t.setAttribute("operator","in"),_t.setAttribute("result",d+"_drop_shadow_4"),e.appendChild(_t);var ue=this.createMergeNode(d,[d+"_drop_shadow_4",f]);e.appendChild(ue)}extendPrototype([SVGComposableEffect],SVGDropShadowEffect),SVGDropShadowEffect.prototype.renderFrame=function(e){if(e||this.filterManager._mdf){if((e||this.filterManager.effectElements[4].p._mdf)&&this.feGaussianBlur.setAttribute("stdDeviation",this.filterManager.effectElements[4].p.v/4),e||this.filterManager.effectElements[0].p._mdf){var r=this.filterManager.effectElements[0].p.v;this.feFlood.setAttribute("flood-color",rgbToHex(Math.round(r[0]*255),Math.round(r[1]*255),Math.round(r[2]*255)))}if((e||this.filterManager.effectElements[1].p._mdf)&&this.feFlood.setAttribute("flood-opacity",this.filterManager.effectElements[1].p.v/255),e||this.filterManager.effectElements[2].p._mdf||this.filterManager.effectElements[3].p._mdf){var s=this.filterManager.effectElements[3].p.v,d=(this.filterManager.effectElements[2].p.v-90)*degToRads,f=s*Math.cos(d),_=s*Math.sin(d);this.feOffset.setAttribute("dx",f),this.feOffset.setAttribute("dy",_)}}};var _svgMatteSymbols=[];function SVGMatte3Effect(e,r,s){this.initialized=!1,this.filterManager=r,this.filterElem=e,this.elem=s,s.matteElement=createNS("g"),s.matteElement.appendChild(s.layerElement),s.matteElement.appendChild(s.transformedElement),s.baseElement=s.matteElement}SVGMatte3Effect.prototype.findSymbol=function(e){for(var r=0,s=_svgMatteSymbols.length;r=0)&&(s[f]=e[f]);return s}function _objectWithoutProperties(e,r){if(e==null)return{};var s=_objectWithoutPropertiesLoose$1(e,r),d,f;if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(e);for(f=0;f<_.length;f++)d=_[f],!(r.indexOf(d)>=0)&&Object.prototype.propertyIsEnumerable.call(e,d)&&(s[d]=e[d])}return s}function _slicedToArray(e,r){return _arrayWithHoles(e)||_iterableToArrayLimit(e,r)||_unsupportedIterableToArray(e,r)||_nonIterableRest()}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _unsupportedIterableToArray(e,r){if(e){if(typeof e=="string")return _arrayLikeToArray(e,r);var s=Object.prototype.toString.call(e).slice(8,-1);if(s==="Object"&&e.constructor&&(s=e.constructor.name),s==="Map"||s==="Set")return Array.from(e);if(s==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s))return _arrayLikeToArray(e,r)}}function _arrayLikeToArray(e,r){(r==null||r>e.length)&&(r=e.length);for(var s=0,d=new Array(r);s0&&arguments[0]!==void 0?arguments[0]:{},DE;if(tE.current){(DE=Qm.current)===null||DE===void 0||DE.destroy();var GE=_objectSpread2(_objectSpread2(_objectSpread2({},r),IE),{},{container:tE.current});return Qm.current=lottie.loadAnimation(GE),_m(!!Qm.current),function(){var QE;(QE=Qm.current)===null||QE===void 0||QE.destroy(),Qm.current=void 0}}};reactExports.useEffect(function(){var dE=_f();return function(){return dE==null?void 0:dE()}},[d,f]),reactExports.useEffect(function(){Qm.current&&(Qm.current.autoplay=!!_)},[_]),reactExports.useEffect(function(){if(Qm.current){if(!C){Qm.current.resetSegments(!0);return}!Array.isArray(C)||!C.length||((Qm.current.currentRawFrameC[1])&&(Qm.current.currentRawFrame=C[0]),Qm.current.setSegment(C[0],C[1]))}},[C]),reactExports.useEffect(function(){var dE=[{name:"complete",handler:P},{name:"loopComplete",handler:x},{name:"enterFrame",handler:B},{name:"segmentStart",handler:_t},{name:"config_ready",handler:ue},{name:"data_ready",handler:Wt},{name:"data_failed",handler:_n},{name:"loaded_images",handler:_i},{name:"DOMLoaded",handler:Ei},{name:"destroy",handler:_a}],IE=dE.filter(function(GE){return GE.handler!=null});if(IE.length){var DE=IE.map(function(GE){var QE;return(QE=Qm.current)===null||QE===void 0||QE.addEventListener(GE.name,GE.handler),function(){var a_;(a_=Qm.current)===null||a_===void 0||a_.removeEventListener(GE.name,GE.handler)}});return function(){DE.forEach(function(GE){return GE()})}}},[P,x,B,_t,ue,Wt,_n,_i,Ei,_a]);var uE=React.createElement("div",_objectSpread2({style:s,ref:tE},Di));return{View:uE,play:aE,stop:RE,pause:lE,setSpeed:gE,goToAndStop:_E,goToAndPlay:cE,setDirection:iE,playSegments:rE,setSubframe:vf,getDuration:Fg,destroy:_d,animationContainerRef:tE,animationLoaded:_c,animationItem:Qm.current}};function getContainerVisibility(e){var r=e.getBoundingClientRect(),s=r.top,d=r.height,f=window.innerHeight-s,_=window.innerHeight+d;return f/_}function getContainerCursorPosition(e,r,s){var d=e.getBoundingClientRect(),f=d.top,_=d.left,C=d.width,P=d.height,x=(r-_)/C,B=(s-f)/P;return{x,y:B}}var useInitInteractivity=function e(r){var s=r.wrapperRef,d=r.animationItem,f=r.mode,_=r.actions;reactExports.useEffect(function(){var C=s.current;if(!(!C||!d||!_.length)){d.stop();var P=function(){var _t=null,ue=function(){var _n=getContainerVisibility(C),_i=_.find(function(_a){var Di=_a.visibility;return Di&&_n>=Di[0]&&_n<=Di[1]});if(_i){if(_i.type==="seek"&&_i.visibility&&_i.frames.length===2){var Ei=_i.frames[0]+Math.ceil((_n-_i.visibility[0])/(_i.visibility[1]-_i.visibility[0])*_i.frames[1]);//! goToAndStop must be relative to the start of the current segment +d.goToAndStop(Ei-d.firstFrame-1,!0)}_i.type==="loop"&&(_t===null||_t!==_i.frames||d.isPaused)&&(d.playSegments(_i.frames,!0),_t=_i.frames),_i.type==="play"&&d.isPaused&&(d.resetSegments(!0),d.play()),_i.type==="stop"&&d.goToAndStop(_i.frames[0]-d.firstFrame-1,!0)}};return document.addEventListener("scroll",ue),function(){document.removeEventListener("scroll",ue)}},x=function(){var _t=function(_i,Ei){var _a=_i,Di=Ei;if(_a!==-1&&Di!==-1){var _o=getContainerCursorPosition(C,_a,Di);_a=_o.x,Di=_o.y}var _s=_.find(function(Qm){var tE=Qm.position;return tE&&Array.isArray(tE.x)&&Array.isArray(tE.y)?_a>=tE.x[0]&&_a<=tE.x[1]&&Di>=tE.y[0]&&Di<=tE.y[1]:tE&&!Number.isNaN(tE.x)&&!Number.isNaN(tE.y)?_a===tE.x&&Di===tE.y:!1});if(_s){if(_s.type==="seek"&&_s.position&&Array.isArray(_s.position.x)&&Array.isArray(_s.position.y)&&_s.frames.length===2){var _c=(_a-_s.position.x[0])/(_s.position.x[1]-_s.position.x[0]),_m=(Di-_s.position.y[0])/(_s.position.y[1]-_s.position.y[0]);d.playSegments(_s.frames,!0),d.goToAndStop(Math.ceil((_c+_m)/2*(_s.frames[1]-_s.frames[0])),!0)}_s.type==="loop"&&d.playSegments(_s.frames,!0),_s.type==="play"&&(d.isPaused&&d.resetSegments(!1),d.playSegments(_s.frames)),_s.type==="stop"&&d.goToAndStop(_s.frames[0],!0)}},ue=function(_i){_t(_i.clientX,_i.clientY)},Wt=function(){_t(-1,-1)};return C.addEventListener("mousemove",ue),C.addEventListener("mouseout",Wt),function(){C.removeEventListener("mousemove",ue),C.removeEventListener("mouseout",Wt)}};switch(f){case"scroll":return P();case"cursor":return x()}}},[f,d])},useLottieInteractivity=function e(r){var s=r.actions,d=r.mode,f=r.lottieObj,_=f.animationItem,C=f.View,P=f.animationContainerRef;return useInitInteractivity({actions:s,animationItem:_,mode:d,wrapperRef:P}),C},_excluded=["style","interactivity"],Lottie=function e(r){var s,d,f,_=r.style,C=r.interactivity,P=_objectWithoutProperties(r,_excluded),x=useLottie(P,_),B=x.View,_t=x.play,ue=x.stop,Wt=x.pause,_n=x.setSpeed,_i=x.goToAndStop,Ei=x.goToAndPlay,_a=x.setDirection,Di=x.playSegments,_o=x.setSubframe,_s=x.getDuration,_c=x.destroy,_m=x.animationContainerRef,Qm=x.animationLoaded,tE=x.animationItem;return reactExports.useEffect(function(){r.lottieRef&&(r.lottieRef.current={play:_t,stop:ue,pause:Wt,setSpeed:_n,goToAndPlay:Ei,goToAndStop:_i,setDirection:_a,playSegments:Di,setSubframe:_o,getDuration:_s,destroy:_c,animationContainerRef:_m,animationLoaded:Qm,animationItem:tE})},[(s=r.lottieRef)===null||s===void 0?void 0:s.current]),useLottieInteractivity({lottieObj:{View:B,play:_t,stop:ue,pause:Wt,setSpeed:_n,goToAndStop:_i,goToAndPlay:Ei,setDirection:_a,playSegments:Di,setSubframe:_o,getDuration:_s,destroy:_c,animationContainerRef:_m,animationLoaded:Qm,animationItem:tE},actions:(d=C==null?void 0:C.actions)!==null&&d!==void 0?d:[],mode:(f=C==null?void 0:C.mode)!==null&&f!==void 0?f:"scroll"})};const v="5.7.6",fr=29.9700012207031,ip=0,op=140.000005702317,w=320,h=192,nm="lottiefiles.com",ddd=0,assets=[{id:"image_0",w:1,h:1,u:"",p:"data:image/png;base64,dataimage/pngbase640",e:1}],layers=[{ddd:0,ind:1,ty:4,nm:"Dot 3 Outlines",parent:11,sr:1,ks:{o:{a:0,k:100,ix:11},r:{a:0,k:0,ix:10},p:{a:1,k:[{i:{x:.667,y:1},o:{x:.625,y:.017},t:49,s:[160.25,52.25,0],to:[0,-4.167,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.625,y:0},t:54,s:[160.25,27.25,0],to:[0,0,0],ti:[0,-4.167,0]},{i:{x:.833,y:.833},o:{x:.167,y:.167},t:59,s:[160.25,52.25,0],to:[0,0,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.625,y:.017},t:93,s:[160.25,52.25,0],to:[0,-4.167,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.625,y:0},t:98,s:[160.25,27.25,0],to:[0,0,0],ti:[0,-4.167,0]},{t:103.000004195276,s:[160.25,52.25,0]}],ix:2,l:2},a:{a:0,k:[12.25,12.25,0],ix:1,l:2},s:{a:0,k:[100,100,100],ix:6,l:2}},ao:0,shapes:[{ty:"gr",it:[{ind:0,ty:"sh",ix:1,ks:{a:0,k:{i:[[0,-6.627],[6.627,0],[0,6.627],[-6.628,0]],o:[[0,6.627],[-6.628,0],[0,-6.627],[6.627,0]],v:[[12,0],[0,12],[-12,0],[0,-12]],c:!0},ix:2},nm:"Path 1",mn:"ADBE Vector Shape - Group",hd:!1},{ty:"fl",c:{a:0,k:[.081047865924,.137433205399,.185762727027,1],ix:4},o:{a:0,k:100,ix:5},r:1,bm:0,nm:"Fill 1",mn:"ADBE Vector Graphic - Fill",hd:!1},{ty:"tr",p:{a:0,k:[12.25,12.25],ix:2},a:{a:0,k:[0,0],ix:1},s:{a:0,k:[100,100],ix:3},r:{a:0,k:0,ix:6},o:{a:0,k:100,ix:7},sk:{a:0,k:0,ix:4},sa:{a:0,k:0,ix:5},nm:"Transform"}],nm:"Group 1",np:2,cix:2,bm:0,ix:1,mn:"ADBE Vector Group",hd:!1}],ip:0,op:140.000005702317,st:0,bm:0},{ddd:0,ind:2,ty:4,nm:"Dot 2 Outlines",parent:11,sr:1,ks:{o:{a:0,k:100,ix:11},r:{a:0,k:0,ix:10},p:{a:1,k:[{i:{x:.667,y:1},o:{x:.644,y:0},t:44,s:[116.25,52.25,0],to:[0,-4.167,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.633,y:0},t:49,s:[116.25,27.25,0],to:[0,0,0],ti:[0,-4.167,0]},{i:{x:.667,y:.667},o:{x:.333,y:.333},t:54,s:[116.25,52.25,0],to:[0,0,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.644,y:0},t:88,s:[116.25,52.25,0],to:[0,-4.167,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.633,y:0},t:93,s:[116.25,27.25,0],to:[0,0,0],ti:[0,-4.167,0]},{t:98.0000039916218,s:[116.25,52.25,0]}],ix:2,l:2},a:{a:0,k:[12.25,12.25,0],ix:1,l:2},s:{a:0,k:[100,100,100],ix:6,l:2}},ao:0,shapes:[{ty:"gr",it:[{ind:0,ty:"sh",ix:1,ks:{a:0,k:{i:[[0,-6.627],[6.627,0],[0,6.627],[-6.628,0]],o:[[0,6.627],[-6.628,0],[0,-6.627],[6.627,0]],v:[[12,0],[0,12],[-12,0],[0,-12]],c:!0},ix:2},nm:"Path 1",mn:"ADBE Vector Shape - Group",hd:!1},{ty:"fl",c:{a:0,k:[.081047865924,.137433205399,.185762727027,1],ix:4},o:{a:0,k:100,ix:5},r:1,bm:0,nm:"Fill 1",mn:"ADBE Vector Graphic - Fill",hd:!1},{ty:"tr",p:{a:0,k:[12.25,12.25],ix:2},a:{a:0,k:[0,0],ix:1},s:{a:0,k:[100,100],ix:3},r:{a:0,k:0,ix:6},o:{a:0,k:100,ix:7},sk:{a:0,k:0,ix:4},sa:{a:0,k:0,ix:5},nm:"Transform"}],nm:"Group 1",np:2,cix:2,bm:0,ix:1,mn:"ADBE Vector Group",hd:!1}],ip:0,op:140.000005702317,st:0,bm:0},{ddd:0,ind:3,ty:4,nm:"Dot 1 Outlines",parent:11,sr:1,ks:{o:{a:0,k:100,ix:11},r:{a:0,k:0,ix:10},p:{a:1,k:[{i:{x:.811,y:1},o:{x:.614,y:.001},t:31,s:[72.499,63.5,0],to:[0,-5,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.766,y:.002},t:36,s:[72.499,33.5,0],to:[0,0,0],ti:[0,-4.167,0]},{i:{x:.678,y:1},o:{x:.681,y:0},t:46,s:[72.499,63.5,0],to:[0,4.167,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.532,y:0},t:50,s:[72.499,58.5,0],to:[0,0,0],ti:[0,-.833,0]},{i:{x:.667,y:.667},o:{x:.167,y:.167},t:54,s:[72.499,63.5,0],to:[0,0,0],ti:[0,0,0]},{i:{x:.811,y:1},o:{x:.614,y:.001},t:75,s:[72.499,63.5,0],to:[0,-5,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.766,y:.002},t:80,s:[72.499,33.5,0],to:[0,0,0],ti:[0,-4.167,0]},{i:{x:.678,y:1},o:{x:.681,y:0},t:90,s:[72.499,63.5,0],to:[0,4.167,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.532,y:0},t:94,s:[72.499,58.5,0],to:[0,0,0],ti:[0,-.833,0]},{t:98.0000039916218,s:[72.499,63.5,0]}],ix:2,l:2},a:{a:0,k:[12.5,23.5,0],ix:1,l:2},s:{a:1,k:[{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:25,s:[100,100,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:29,s:[100,40,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:34,s:[100,100,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:44,s:[100,100,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:46,s:[100,75,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.167,.167,.167],y:[0,0,0]},t:50,s:[100,100,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:69,s:[100,100,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:73,s:[100,40,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:78,s:[100,100,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:88,s:[100,100,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:90,s:[100,75,100]},{t:94.0000038286985,s:[100,100,100]}],ix:6,l:2}},ao:0,shapes:[{ty:"gr",it:[{ind:0,ty:"sh",ix:1,ks:{a:0,k:{i:[[0,-6.627],[6.627,0],[0,6.627],[-6.627,0]],o:[[0,6.627],[-6.627,0],[0,-6.627],[6.627,0]],v:[[12,0],[0,12],[-12,0],[0,-12]],c:!0},ix:2},nm:"Path 1",mn:"ADBE Vector Shape - Group",hd:!1},{ty:"fl",c:{a:0,k:[.081047865924,.137433205399,.185762727027,1],ix:4},o:{a:0,k:100,ix:5},r:1,bm:0,nm:"Fill 1",mn:"ADBE Vector Graphic - Fill",hd:!1},{ty:"tr",p:{a:0,k:[12.25,12.25],ix:2},a:{a:0,k:[0,0],ix:1},s:{a:0,k:[100,100],ix:3},r:{a:0,k:0,ix:6},o:{a:0,k:100,ix:7},sk:{a:0,k:0,ix:4},sa:{a:0,k:0,ix:5},nm:"Transform"}],nm:"Group 1",np:2,cix:2,bm:0,ix:1,mn:"ADBE Vector Group",hd:!1}],ip:0,op:140.000005702317,st:0,bm:0},{ddd:0,ind:4,ty:4,nm:"Dialog Box Outlines",sr:1,ks:{o:{a:0,k:100,ix:11},r:{a:0,k:0,ix:10},p:{a:1,k:[{i:{x:.667,y:1},o:{x:.333,y:0},t:4,s:[144.105,113.25,0],to:[6.667,-6.667,0],ti:[-6.667,6.667,0]},{i:{x:.667,y:.667},o:{x:.333,y:.333},t:8,s:[184.105,73.25,0],to:[0,0,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.167,y:0},t:116,s:[184.105,73.25,0],to:[-6.667,6.667,0],ti:[6.667,-6.667,0]},{t:118.000004806239,s:[144.105,113.25,0]}],ix:2,l:2},a:{a:0,k:[116.5,52.5,0],ix:1,l:2},s:{a:1,k:[{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:5.455,s:[0,0,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:10.909,s:[108,108,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.167,.167,.167],y:[0,0,0]},t:15,s:[100,100,100]},{i:{x:[.833,.833,.833],y:[1,1,1]},o:{x:[.167,.167,.167],y:[0,0,0]},t:116,s:[100,100,100]},{t:118.000004806239,s:[0,0,100]}],ix:6,l:2}},ao:0,shapes:[{ty:"gr",it:[{ind:0,ty:"sh",ix:1,ks:{a:0,k:{i:[[28.719,0],[0,0],[0,28.719],[-28.719,0],[0,0],[0,-28.719]],o:[[0,0],[-28.719,0],[0,-28.719],[0,0],[28.719,0],[0,28.719]],v:[[64,52],[-64,52],[-116,0],[-64,-52],[64,-52],[116,0]],c:!0},ix:2},nm:"Path 1",mn:"ADBE Vector Shape - Group",hd:!1},{ty:"fl",c:{a:0,k:[.858770333084,.866351617551,.873935415231,1],ix:4},o:{a:0,k:100,ix:5},r:1,bm:0,nm:"Fill 1",mn:"ADBE Vector Graphic - Fill",hd:!1},{ty:"tr",p:{a:0,k:[116.25,52.25],ix:2},a:{a:0,k:[0,0],ix:1},s:{a:0,k:[100,100],ix:3},r:{a:0,k:0,ix:6},o:{a:0,k:100,ix:7},sk:{a:0,k:0,ix:4},sa:{a:0,k:0,ix:5},nm:"Transform"}],nm:"Group 1",np:2,cix:2,bm:0,ix:1,mn:"ADBE Vector Group",hd:!1}],ip:0,op:140.000005702317,st:0,bm:0},{ddd:0,ind:5,ty:4,nm:"Dialog Box Tail 2 Outlines",sr:1,ks:{o:{a:0,k:100,ix:11},r:{a:0,k:0,ix:10},p:{a:1,k:[{i:{x:.667,y:1},o:{x:.333,y:0},t:2,s:[40.396,151.25,0],to:[3.333,-3.333,0],ti:[-3.333,3.333,0]},{i:{x:.667,y:.667},o:{x:.333,y:.333},t:6,s:[60.396,131.25,0],to:[0,0,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.167,y:0},t:117,s:[60.396,131.25,0],to:[-3.333,3.333,0],ti:[3.333,-3.333,0]},{t:119.000004846969,s:[40.396,151.25,0]}],ix:2,l:2},a:{a:0,k:[16.5,16.5,0],ix:1,l:2},s:{a:1,k:[{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:2.728,s:[0,0,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:8.181,s:[125,125,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.167,.167,.167],y:[0,0,0]},t:10.909,s:[100,100,100]},{i:{x:[.833,.833,.833],y:[1,1,1]},o:{x:[.167,.167,.167],y:[0,0,0]},t:117,s:[100,100,100]},{t:119.000004846969,s:[0,0,100]}],ix:6,l:2}},ao:0,shapes:[{ty:"gr",it:[{ind:0,ty:"sh",ix:1,ks:{a:0,k:{i:[[0,-8.837],[8.836,0],[0,8.837],[-8.836,0]],o:[[0,8.837],[-8.836,0],[0,-8.837],[8.836,0]],v:[[16,0],[0,16],[-16,0],[0,-16]],c:!0},ix:2},nm:"Path 1",mn:"ADBE Vector Shape - Group",hd:!1},{ty:"fl",c:{a:0,k:[.858770333084,.866351617551,.873935415231,1],ix:4},o:{a:0,k:100,ix:5},r:1,bm:0,nm:"Fill 1",mn:"ADBE Vector Graphic - Fill",hd:!1},{ty:"tr",p:{a:0,k:[16.25,16.25],ix:2},a:{a:0,k:[0,0],ix:1},s:{a:0,k:[100,100],ix:3},r:{a:0,k:0,ix:6},o:{a:0,k:100,ix:7},sk:{a:0,k:0,ix:4},sa:{a:0,k:0,ix:5},nm:"Transform"}],nm:"Group 1",np:2,cix:2,bm:0,ix:1,mn:"ADBE Vector Group",hd:!1}],ip:0,op:140.000005702317,st:0,bm:0},{ddd:0,ind:6,ty:4,nm:"Dialog Box Tail 1 Outlines",sr:1,ks:{o:{a:0,k:100,ix:11},r:{a:0,k:0,ix:10},p:{a:1,k:[{i:{x:.667,y:1},o:{x:.333,y:0},t:0,s:[12.396,179.25,0],to:[3.333,-3.333,0],ti:[-3.333,3.333,0]},{i:{x:.667,y:.667},o:{x:.333,y:.333},t:4,s:[32.396,159.25,0],to:[0,0,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.167,y:0},t:118,s:[32.396,159.25,0],to:[-3.333,3.333,0],ti:[3.333,-3.333,0]},{t:120.0000048877,s:[12.396,179.25,0]}],ix:2,l:2},a:{a:0,k:[12.5,12.5,0],ix:1,l:2},s:{a:1,k:[{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:0,s:[0,0,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:5.455,s:[125,125,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.167,.167,.167],y:[0,0,0]},t:8.181,s:[100,100,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.167,.167,.167],y:[0,0,0]},t:118,s:[100,100,100]},{t:120.0000048877,s:[0,0,100]}],ix:6,l:2}},ao:0,shapes:[{ty:"gr",it:[{ind:0,ty:"sh",ix:1,ks:{a:0,k:{i:[[0,-6.627],[6.627,0],[0,6.627],[-6.627,0]],o:[[0,6.627],[-6.627,0],[0,-6.627],[6.627,0]],v:[[12,0],[0,12],[-12,0],[0,-12]],c:!0},ix:2},nm:"Path 1",mn:"ADBE Vector Shape - Group",hd:!1},{ty:"fl",c:{a:0,k:[.858770333084,.866351617551,.873935415231,1],ix:4},o:{a:0,k:100,ix:5},r:1,bm:0,nm:"Fill 1",mn:"ADBE Vector Graphic - Fill",hd:!1},{ty:"tr",p:{a:0,k:[12.25,12.25],ix:2},a:{a:0,k:[0,0],ix:1},s:{a:0,k:[100,100],ix:3},r:{a:0,k:0,ix:6},o:{a:0,k:100,ix:7},sk:{a:0,k:0,ix:4},sa:{a:0,k:0,ix:5},nm:"Transform"}],nm:"Group 1",np:2,cix:2,bm:0,ix:1,mn:"ADBE Vector Group",hd:!1}],ip:0,op:140.000005702317,st:0,bm:0},{ddd:0,ind:7,ty:2,nm:"Backup",refId:"image_0",sr:1,ks:{o:{a:0,k:100,ix:11},r:{a:0,k:0,ix:10},p:{a:0,k:[0,192,0],ix:2,l:2},a:{a:0,k:[0,0,0],ix:1,l:2},s:{a:0,k:[100,100,100],ix:6,l:2}},ao:0,ip:0,op:140.000005702317,st:0,bm:0},{ddd:0,ind:11,ty:3,nm:"Dialog Box",sr:1,ks:{o:{a:0,k:100,ix:11},r:{a:0,k:0,ix:10},p:{a:1,k:[{i:{x:.667,y:1},o:{x:.333,y:0},t:4,s:[144.105,113.25,0],to:[6.667,-6.667,0],ti:[-6.667,6.667,0]},{i:{x:.667,y:.667},o:{x:.333,y:.333},t:8,s:[184.105,73.25,0],to:[0,0,0],ti:[0,0,0]},{i:{x:.667,y:1},o:{x:.167,y:0},t:116,s:[184.105,73.25,0],to:[-6.667,6.667,0],ti:[6.667,-6.667,0]},{t:118.000004806239,s:[144.105,113.25,0]}],ix:2,l:2},a:{a:0,k:[116.5,52.5,0],ix:1,l:2},s:{a:1,k:[{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:5.455,s:[0,0,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.333,.333,.333],y:[0,0,0]},t:10.909,s:[108,108,100]},{i:{x:[.667,.667,.667],y:[1,1,1]},o:{x:[.167,.167,.167],y:[0,0,0]},t:15,s:[100,100,100]},{i:{x:[.833,.833,.833],y:[1,1,1]},o:{x:[.167,.167,.167],y:[0,0,0]},t:116,s:[100,100,100]},{t:118.000004806239,s:[0,0,100]}],ix:6,l:2}},ao:0,ip:0,op:140.000005702317,st:0,bm:0}],markers=[],typingAnimation={v,fr,ip,op,w,h,nm,ddd,assets,layers,markers},index="";function styleInject(e,r){r===void 0&&(r={});var s=r.insertAt;if(!(!e||typeof document>"u")){var d=document.head||document.getElementsByTagName("head")[0],f=document.createElement("style");f.type="text/css",s==="top"&&d.firstChild?d.insertBefore(f,d.firstChild):d.appendChild(f),f.styleSheet?f.styleSheet.cssText=e:f.appendChild(document.createTextNode(e))}}var css_248z=`.styles-module_wrapper__1I_qj { + z-index: 1; + display: flex; + align-items: center; + position: fixed; + padding: 0px 60px 0px 60px; + left: 0; + top: 0; + width: 100%; + height: 100%; + background-color: black; + box-sizing: border-box; +} + +.styles-module_content__2jwZj { + margin: auto; + padding: 0; + width: 90%; + height: 100%; + max-height: 100%; + text-align: center; +} + +.styles-module_slide__1zrfk { + height: 100%; + display: flex; + align-items: center; + justify-content: center; +} + +.styles-module_image__2hdkJ { + max-height: 100%; + max-width: 100%; + user-select: none; + -moz-user-select: none; + -webkit-user-select: none; +} + +.styles-module_close__2I1sI { + color: white; + position: absolute; + top: 15px; + right: 15px; + font-size: 40px; + font-weight: bold; + opacity: 0.2; + cursor: pointer; +} + +.styles-module_close__2I1sI:hover { + opacity: 1; +} + +.styles-module_navigation__1pqAE { + height: 80%; + color: white; + cursor: pointer; + position: absolute; + font-size: 60px; + line-height: 60px; + font-weight: bold; + display: flex; + align-items: center; + opacity: 0.2; + padding: 0 15px; + user-select: none; + -moz-user-select: none; + -webkit-user-select: none; +} + +.styles-module_navigation__1pqAE:hover { + opacity: 1; +} + +@media (hover: none) { + .styles-module_navigation__1pqAE:hover { + opacity: 0.2; + } +} + +.styles-module_prev__KqFRp { + left: 0; +} + +.styles-module_next__1uQwZ { + right: 0; +} + +@media (max-width: 900px) { + .styles-module_wrapper__1I_qj { + padding: 0; + } +} +`,styles$4={wrapper:"styles-module_wrapper__1I_qj",content:"styles-module_content__2jwZj",slide:"styles-module_slide__1zrfk",image:"styles-module_image__2hdkJ",close:"styles-module_close__2I1sI",navigation:"styles-module_navigation__1pqAE",prev:"styles-module_prev__KqFRp",next:"styles-module_next__1uQwZ"};styleInject(css_248z);const ReactSimpleImageViewer=e=>{var r;const[s,d]=reactExports.useState((r=e.currentIndex)!==null&&r!==void 0?r:0),f=reactExports.useCallback(x=>{let B=(s+x)%e.src.length;B<0&&(B=e.src.length-1),d(B)},[s]),_=reactExports.useCallback(x=>{var B;if(!x.target||!e.closeOnClickOutside)return;const _t=x.target.id==="ReactSimpleImageViewer",ue=x.target.classList.contains("react-simple-image-viewer__slide");(_t||ue)&&(x.stopPropagation(),(B=e.onClose)===null||B===void 0||B.call(e))},[e.onClose]),C=reactExports.useCallback(x=>{var B;x.key==="Escape"&&((B=e.onClose)===null||B===void 0||B.call(e)),["ArrowLeft","h"].includes(x.key)&&f(-1),["ArrowRight","l"].includes(x.key)&&f(1)},[e.onClose,f]),P=reactExports.useCallback(x=>{x.wheelDeltaY>0?f(-1):f(1)},[f]);return reactExports.useEffect(()=>(document.addEventListener("keydown",C),e.disableScroll||document.addEventListener("wheel",P),()=>{document.removeEventListener("keydown",C),e.disableScroll||document.removeEventListener("wheel",P)}),[C,P]),React.createElement("div",{id:"ReactSimpleImageViewer",className:`${styles$4.wrapper} react-simple-image-viewer__modal`,onKeyDown:C,onClick:_,style:e.backgroundStyle},React.createElement("span",{className:`${styles$4.close} react-simple-image-viewer__close`,onClick:()=>{var x;return(x=e.onClose)===null||x===void 0?void 0:x.call(e)}},e.closeComponent||"×"),e.src.length>1&&React.createElement("span",{className:`${styles$4.navigation} ${styles$4.prev} react-simple-image-viewer__previous`,onClick:()=>f(-1)},e.leftArrowComponent||"❮"),e.src.length>1&&React.createElement("span",{className:`${styles$4.navigation} ${styles$4.next} react-simple-image-viewer__next`,onClick:()=>f(1)},e.rightArrowComponent||"❯"),React.createElement("div",{className:`${styles$4.content} react-simple-image-viewer__modal-content`,onClick:_},React.createElement("div",{className:`${styles$4.slide} react-simple-image-viewer__slide`},React.createElement("img",{className:styles$4.image,src:e.src[s],alt:""}))))},loader="/assets/Loader-cbc659e7.png";let selectedChatCompare;const ChatBoxContent=({socket:e,socketConnected:r})=>{const s=useSelector(rE=>rE.chat.selectedChat),d=useSelector(rE=>rE.auth.user),[f,_]=reactExports.useState(""),C=reactExports.useRef(null),[P,x]=reactExports.useState(!1),[B,_t]=reactExports.useState(!1),[ue,Wt]=reactExports.useState([]),[_n,_i]=reactExports.useState(!1),[Ei,_a]=reactExports.useState(""),[Di,_o]=reactExports.useState(null),[_s,_c]=reactExports.useState(!1),[_m,Qm]=reactExports.useState([]),tE=useDispatch();reactExports.useEffect(()=>{_a(""),aE(),selectedChatCompare=s},[s]),reactExports.useEffect(()=>{e&&(e.on("message recieved",rE=>{selectedChatCompare&&selectedChatCompare._id===rE.chat._id&&(Wt([...ue,rE]),tE(setFetchUserChatsAgain(!0)))}),e.on("typing",rE=>{_(rE),_t(!0)}),e.on("stop typing",()=>_t(!1)))}),reactExports.useEffect(()=>{var rE;(rE=C.current)==null||rE.scrollIntoView({behavior:"smooth"})},[ue,B]);const aE=async()=>{if(s)try{_i(!0);const rE=await getAllMessagesFromChat(s._id);Wt(rE.messages),_i(!1),e&&e.emit("join room",s._id)}catch{Q.dismiss(),Q.error("Error fetching messages",TOAST_ACTION)}},RE=async()=>{try{e.emit("stop typing",s==null?void 0:s._id),_a("");let rE;if(Di){_o(null);const vf=new FormData;vf.append("image",Di),vf.append("chat",s==null?void 0:s._id),Ei&&vf.append("content",Ei),rE=s&&await sendMessageWithImg(vf)}else rE=s&&await sendMessage(Ei,s._id);if(tE(setFetchUserChatsAgain(!0)),rE&&rE.message){const vf=rE.message;rE&&e.emit("new message",{...vf,chat:s}),rE&&rE.message&&Wt(Fg=>[...Fg,vf])}}catch{Q.dismiss(),Q.error("Error sending message",TOAST_ACTION)}};let lE;const gE=rE=>{if(_a(rE),!r)return;P||(x(!0),e.emit("typing",s==null?void 0:s._id));const vf=3e3;clearTimeout(lE),lE=setTimeout(()=>{e.emit("stop typing",s==null?void 0:s._id),x(!1)},vf)},cE=async rE=>{var Fg;const vf=(Fg=rE.target.files)==null?void 0:Fg[0];if(vf){if(!vf.type.startsWith("image/")){Q.dismiss(),Q.error("Only image files are allowed",TOAST_ACTION);return}_o(vf)}},_E=()=>{_c(!1)},iE=reactExports.useCallback(rE=>{Qm([rE]),_c(!0)},[]);return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:_n?jsxRuntimeExports.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntimeExports.jsx("img",{src:loader,alt:"loader",className:"animate-spin w-20 h-20"})}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:"overflow-y-scroll flex flex-col h-full mt-4 no-scrollbar gap-2 w-full",children:[Object.entries(groupByDate(ue)).map(([rE,vf])=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"flex justify-center mt-8 mb-4",children:jsxRuntimeExports.jsx("h1",{className:"bg-socioverse-100 rounded-xl px-2 py-1 text-xs font-thin text-blue-gray-900",children:rE})}),jsxRuntimeExports.jsx("div",{className:"flex flex-col gap-2",children:vf.map(Fg=>jsxRuntimeExports.jsx("div",{className:classnames("flex md:mx-4 mx-1 text-sm p-2",{"justify-end":Fg.sender._id===(d==null?void 0:d._id)},{"justify-start":Fg.sender._id!==(d==null?void 0:d._id)}),children:jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-2",children:[(s==null?void 0:s.isGroupChat)&&d&&Fg.sender._id!==d._id&&jsxRuntimeExports.jsx("img",{className:"inline-block h-8 w-8 md:h-12 md:w-12 rounded-full",src:Fg.sender.dp?Fg.sender.dp:CONSTANTS_COMMON.DEFAULT_IMG,alt:"user dp"}),jsxRuntimeExports.jsxs("div",{className:classnames("inline rounded-xl shadow-lg max-w-[25rem] break-words",{"bg-gray-100 text-black":Fg.sender._id!==(d==null?void 0:d._id)},{"bg-blue-gray-500/80 text-white":Fg.sender._id===(d==null?void 0:d._id)}),children:[(s==null?void 0:s.isGroupChat)&&d&&Fg.sender._id!==d._id&&jsxRuntimeExports.jsxs("h6",{className:"text-[0.65rem] font-thin text-left px-1 pt-1",children:["~ ",Fg.sender.name]}),jsxRuntimeExports.jsxs("div",{className:classnames("flex flex-col",{"p-4":!(s!=null&&s.isGroupChat)||Fg.sender._id===(d==null?void 0:d._id)},{"px-4 pb-2":(s==null?void 0:s.isGroupChat)&&d&&Fg.sender._id!==(d==null?void 0:d._id)}),children:[Fg.image&&jsxRuntimeExports.jsx("img",{src:Fg.image,alt:"image",className:"mb-2 rounded-lg cursor-pointer",onClick:()=>iE(Fg.image)}),jsxRuntimeExports.jsx("h1",{className:"text-sm my-1 font-normal text-left",children:Fg.content&&Fg.content}),jsxRuntimeExports.jsx("h6",{className:"text-[0.65rem] font-thin opacity-80 text-right",children:hooks(Fg.createdAt).format("LT")})]})]})]})},`message+${rE}+${Fg._id}`))})]},`date+${rE}`)),jsxRuntimeExports.jsx("div",{ref:C,className:"h-10 md:mx-4 mx-1",children:B&&(s==null?void 0:s._id)===f&&jsxRuntimeExports.jsx("div",{className:"w-24",children:jsxRuntimeExports.jsx(Lottie,{animationData:typingAnimation,loop:!0})})})]}),Di&&jsxRuntimeExports.jsxs("div",{className:"md:mx-4 mx-1 relative h-36 w-36 overflow-hidden",children:[jsxRuntimeExports.jsx("img",{src:URL.createObjectURL(Di),alt:"img",className:"h-full w-full rounded-lg object-cover"}),jsxRuntimeExports.jsx(AiOutlineCloseCircle,{className:"text-xl cursor-pointer text-white hover:scale-105 absolute top-0 right-0 ",onClick:()=>_o(null)})]}),jsxRuntimeExports.jsxs("div",{className:" md:mx-4 mx-1 md:mb-4 mb-2 flex items-center justify-between z-0",children:[jsxRuntimeExports.jsx(InputEmojiWithRef,{value:Ei,onChange:gE,cleanOnEnter:!0,onEnter:RE,placeholder:"Enter a message...",theme:"auto",fontSize:14,fontFamily:"sans-serif",keepOpened:!0,searchMention:async rE=>["no user"].filter(vf=>vf.includes(rE))}),jsxRuntimeExports.jsxs("div",{className:"mx-auto",children:[jsxRuntimeExports.jsx("input",{type:"file",accept:"image/*",id:"image-input",className:"hidden",onChange:cE}),jsxRuntimeExports.jsx("label",{htmlFor:"image-input",children:jsxRuntimeExports.jsx(ImAttachment,{className:"text-2xl text-[#858585] cursor-pointer hover:text-[#128b7e]"})})]})]}),_s&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"hidden lg:block",children:jsxRuntimeExports.jsx(ReactSimpleImageViewer,{src:_m,currentIndex:0,disableScroll:!1,closeOnClickOutside:!0,onClose:_E,backgroundStyle:{backgroundColor:"rgba(0,0,0,0.8)",padding:"8rem 4rem 4rem 4rem"}})}),jsxRuntimeExports.jsx("div",{className:"block lg:hidden",children:jsxRuntimeExports.jsx(ReactSimpleImageViewer,{src:_m,currentIndex:0,disableScroll:!1,closeOnClickOutside:!0,onClose:_E,backgroundStyle:{backgroundColor:"rgba(0,0,0,0.8)"}})})]})]})})};var AgoraRTC_NProduction={exports:{}};(function(e,r){(function(s,d){e.exports=d()})(commonjsGlobal,function(){function s(l,i){return i.forEach(function(o){o&&typeof o!="string"&&!Array.isArray(o)&&Object.keys(o).forEach(function(p){if(p!=="default"&&!(p in l)){var g=Object.getOwnPropertyDescriptor(o,p);Object.defineProperty(l,p,g.get?g:{enumerable:!0,get:function(){return o[p]}})}})}),Object.freeze(l)}let d=!0,f=!0;function _(l,i,o){const p=l.match(i);return p&&p.length>=o&&parseInt(p[o],10)}function C(l,i,o){if(!l.RTCPeerConnection)return;const p=l.RTCPeerConnection.prototype,g=p.addEventListener;p.addEventListener=function(A,j){if(A!==i)return g.apply(this,arguments);const H=z=>{const $=o(z);$&&(j.handleEvent?j.handleEvent($):j($))};return this._eventMap=this._eventMap||{},this._eventMap[i]||(this._eventMap[i]=new Map),this._eventMap[i].set(j,H),g.apply(this,[A,H])};const b=p.removeEventListener;p.removeEventListener=function(A,j){if(A!==i||!this._eventMap||!this._eventMap[i])return b.apply(this,arguments);if(!this._eventMap[i].has(j))return b.apply(this,arguments);const H=this._eventMap[i].get(j);return this._eventMap[i].delete(j),this._eventMap[i].size===0&&delete this._eventMap[i],Object.keys(this._eventMap).length===0&&delete this._eventMap,b.apply(this,[A,H])},Object.defineProperty(p,"on"+i,{get(){return this["_on"+i]},set(A){this["_on"+i]&&(this.removeEventListener(i,this["_on"+i]),delete this["_on"+i]),A&&this.addEventListener(i,this["_on"+i]=A)},enumerable:!0,configurable:!0})}function P(l){return typeof l!="boolean"?new Error("Argument type: "+typeof l+". Please use a boolean."):(d=l,l?"adapter.js logging disabled":"adapter.js logging enabled")}function x(l){return typeof l!="boolean"?new Error("Argument type: "+typeof l+". Please use a boolean."):(f=!l,"adapter.js deprecation warnings "+(l?"disabled":"enabled"))}function B(){if(typeof window=="object"){if(d)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function _t(l,i){f&&console.warn(l+" is deprecated, please use "+i+" instead.")}function ue(l){return Object.prototype.toString.call(l)==="[object Object]"}function Wt(l){return ue(l)?Object.keys(l).reduce(function(i,o){const p=ue(l[o]),g=p?Wt(l[o]):l[o],b=p&&!Object.keys(g).length;return g===void 0||b?i:Object.assign(i,{[o]:g})},{}):l}function _n(l,i,o){i&&!o.has(i.id)&&(o.set(i.id,i),Object.keys(i).forEach(p=>{p.endsWith("Id")?_n(l,l.get(i[p]),o):p.endsWith("Ids")&&i[p].forEach(g=>{_n(l,l.get(g),o)})}))}function _i(l,i,o){const p=o?"outbound-rtp":"inbound-rtp",g=new Map;if(i===null)return g;const b=[];return l.forEach(A=>{A.type==="track"&&A.trackIdentifier===i.id&&b.push(A)}),b.forEach(A=>{l.forEach(j=>{j.type===p&&j.trackId===A.id&&_n(l,j,g)})}),g}const Ei=B;function _a(l,i){const o=l&&l.navigator;if(!o.mediaDevices)return;const p=function(A){if(typeof A!="object"||A.mandatory||A.optional)return A;const j={};return Object.keys(A).forEach(H=>{if(H==="require"||H==="advanced"||H==="mediaSource")return;const z=typeof A[H]=="object"?A[H]:{ideal:A[H]};z.exact!==void 0&&typeof z.exact=="number"&&(z.min=z.max=z.exact);const $=function(Vt,_r){return Vt?Vt+_r.charAt(0).toUpperCase()+_r.slice(1):_r==="deviceId"?"sourceId":_r};if(z.ideal!==void 0){j.optional=j.optional||[];let Vt={};typeof z.ideal=="number"?(Vt[$("min",H)]=z.ideal,j.optional.push(Vt),Vt={},Vt[$("max",H)]=z.ideal,j.optional.push(Vt)):(Vt[$("",H)]=z.ideal,j.optional.push(Vt))}z.exact!==void 0&&typeof z.exact!="number"?(j.mandatory=j.mandatory||{},j.mandatory[$("",H)]=z.exact):["min","max"].forEach(Vt=>{z[Vt]!==void 0&&(j.mandatory=j.mandatory||{},j.mandatory[$(Vt,H)]=z[Vt])})}),A.advanced&&(j.optional=(j.optional||[]).concat(A.advanced)),j},g=function(A,j){if(i.version>=61)return j(A);if((A=JSON.parse(JSON.stringify(A)))&&typeof A.audio=="object"){const H=function(z,$,Vt){$ in z&&!(Vt in z)&&(z[Vt]=z[$],delete z[$])};H((A=JSON.parse(JSON.stringify(A))).audio,"autoGainControl","googAutoGainControl"),H(A.audio,"noiseSuppression","googNoiseSuppression"),A.audio=p(A.audio)}if(A&&typeof A.video=="object"){let H=A.video.facingMode;H=H&&(typeof H=="object"?H:{ideal:H});const z=i.version<66;if(H&&(H.exact==="user"||H.exact==="environment"||H.ideal==="user"||H.ideal==="environment")&&(!o.mediaDevices.getSupportedConstraints||!o.mediaDevices.getSupportedConstraints().facingMode||z)){let $;if(delete A.video.facingMode,H.exact==="environment"||H.ideal==="environment"?$=["back","rear"]:H.exact!=="user"&&H.ideal!=="user"||($=["front"]),$)return o.mediaDevices.enumerateDevices().then(Vt=>{let _r=(Vt=Vt.filter(Fi=>Fi.kind==="videoinput")).find(Fi=>$.some(_l=>Fi.label.toLowerCase().includes(_l)));return!_r&&Vt.length&&$.includes("back")&&(_r=Vt[Vt.length-1]),_r&&(A.video.deviceId=H.exact?{exact:_r.deviceId}:{ideal:_r.deviceId}),A.video=p(A.video),Ei("chrome: "+JSON.stringify(A)),j(A)})}A.video=p(A.video)}return Ei("chrome: "+JSON.stringify(A)),j(A)},b=function(A){return i.version>=64?A:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[A.name]||A.name,message:A.message,constraint:A.constraint||A.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(o.getUserMedia=(function(A,j,H){g(A,z=>{o.webkitGetUserMedia(z,j,$=>{H&&H(b($))})})}).bind(o),o.mediaDevices.getUserMedia){const A=o.mediaDevices.getUserMedia.bind(o.mediaDevices);o.mediaDevices.getUserMedia=function(j){return g(j,H=>A(H).then(z=>{if(H.audio&&!z.getAudioTracks().length||H.video&&!z.getVideoTracks().length)throw z.getTracks().forEach($=>{$.stop()}),new DOMException("","NotFoundError");return z},z=>Promise.reject(b(z))))}}}function Di(l){l.MediaStream=l.MediaStream||l.webkitMediaStream}function _o(l){if(typeof l=="object"&&l.RTCPeerConnection&&!("ontrack"in l.RTCPeerConnection.prototype)){Object.defineProperty(l.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(o){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=o)},enumerable:!0,configurable:!0});const i=l.RTCPeerConnection.prototype.setRemoteDescription;l.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=o=>{o.stream.addEventListener("addtrack",p=>{let g;g=l.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(A=>A.track&&A.track.id===p.track.id):{track:p.track};const b=new Event("track");b.track=p.track,b.receiver=g,b.transceiver={receiver:g},b.streams=[o.stream],this.dispatchEvent(b)}),o.stream.getTracks().forEach(p=>{let g;g=l.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(A=>A.track&&A.track.id===p.id):{track:p};const b=new Event("track");b.track=p,b.receiver=g,b.transceiver={receiver:g},b.streams=[o.stream],this.dispatchEvent(b)})},this.addEventListener("addstream",this._ontrackpoly)),i.apply(this,arguments)}}else C(l,"track",i=>(i.transceiver||Object.defineProperty(i,"transceiver",{value:{receiver:i.receiver}}),i))}function _s(l){if(typeof l=="object"&&l.RTCPeerConnection&&!("getSenders"in l.RTCPeerConnection.prototype)&&"createDTMFSender"in l.RTCPeerConnection.prototype){const i=function(g,b){return{track:b,get dtmf(){return this._dtmf===void 0&&(b.kind==="audio"?this._dtmf=g.createDTMFSender(b):this._dtmf=null),this._dtmf},_pc:g}};if(!l.RTCPeerConnection.prototype.getSenders){l.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const g=l.RTCPeerConnection.prototype.addTrack;l.RTCPeerConnection.prototype.addTrack=function(A,j){let H=g.apply(this,arguments);return H||(H=i(this,A),this._senders.push(H)),H};const b=l.RTCPeerConnection.prototype.removeTrack;l.RTCPeerConnection.prototype.removeTrack=function(A){b.apply(this,arguments);const j=this._senders.indexOf(A);j!==-1&&this._senders.splice(j,1)}}const o=l.RTCPeerConnection.prototype.addStream;l.RTCPeerConnection.prototype.addStream=function(g){this._senders=this._senders||[],o.apply(this,[g]),g.getTracks().forEach(b=>{this._senders.push(i(this,b))})};const p=l.RTCPeerConnection.prototype.removeStream;l.RTCPeerConnection.prototype.removeStream=function(g){this._senders=this._senders||[],p.apply(this,[g]),g.getTracks().forEach(b=>{const A=this._senders.find(j=>j.track===b);A&&this._senders.splice(this._senders.indexOf(A),1)})}}else if(typeof l=="object"&&l.RTCPeerConnection&&"getSenders"in l.RTCPeerConnection.prototype&&"createDTMFSender"in l.RTCPeerConnection.prototype&&l.RTCRtpSender&&!("dtmf"in l.RTCRtpSender.prototype)){const i=l.RTCPeerConnection.prototype.getSenders;l.RTCPeerConnection.prototype.getSenders=function(){const o=i.apply(this,[]);return o.forEach(p=>p._pc=this),o},Object.defineProperty(l.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 _c(l){if(!l.RTCPeerConnection)return;const i=l.RTCPeerConnection.prototype.getStats;l.RTCPeerConnection.prototype.getStats=function(){const[o,p,g]=arguments;if(arguments.length>0&&typeof o=="function")return i.apply(this,arguments);if(i.length===0&&(arguments.length===0||typeof o!="function"))return i.apply(this,[]);const b=function(j){const H={};return j.result().forEach(z=>{const $={id:z.id,timestamp:z.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[z.type]||z.type};z.names().forEach(Vt=>{$[Vt]=z.stat(Vt)}),H[$.id]=$}),H},A=function(j){return new Map(Object.keys(j).map(H=>[H,j[H]]))};if(arguments.length>=2){const j=function(H){p(A(b(H)))};return i.apply(this,[j,o])}return new Promise((j,H)=>{i.apply(this,[function(z){j(A(b(z)))},H])}).then(p,g)}}function _m(l){if(!(typeof l=="object"&&l.RTCPeerConnection&&l.RTCRtpSender&&l.RTCRtpReceiver))return;if(!("getStats"in l.RTCRtpSender.prototype)){const o=l.RTCPeerConnection.prototype.getSenders;o&&(l.RTCPeerConnection.prototype.getSenders=function(){const g=o.apply(this,[]);return g.forEach(b=>b._pc=this),g});const p=l.RTCPeerConnection.prototype.addTrack;p&&(l.RTCPeerConnection.prototype.addTrack=function(){const g=p.apply(this,arguments);return g._pc=this,g}),l.RTCRtpSender.prototype.getStats=function(){const g=this;return this._pc.getStats().then(b=>_i(b,g.track,!0))}}if(!("getStats"in l.RTCRtpReceiver.prototype)){const o=l.RTCPeerConnection.prototype.getReceivers;o&&(l.RTCPeerConnection.prototype.getReceivers=function(){const p=o.apply(this,[]);return p.forEach(g=>g._pc=this),p}),C(l,"track",p=>(p.receiver._pc=p.srcElement,p)),l.RTCRtpReceiver.prototype.getStats=function(){const p=this;return this._pc.getStats().then(g=>_i(g,p.track,!1))}}if(!("getStats"in l.RTCRtpSender.prototype)||!("getStats"in l.RTCRtpReceiver.prototype))return;const i=l.RTCPeerConnection.prototype.getStats;l.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof l.MediaStreamTrack){const o=arguments[0];let p,g,b;return this.getSenders().forEach(A=>{A.track===o&&(p?b=!0:p=A)}),this.getReceivers().forEach(A=>(A.track===o&&(g?b=!0:g=A),A.track===o)),b||p&&g?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):p?p.getStats():g?g.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return i.apply(this,arguments)}}function Qm(l){l.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(b=>this._shimmedLocalStreams[b][0])};const i=l.RTCPeerConnection.prototype.addTrack;l.RTCPeerConnection.prototype.addTrack=function(b,A){if(!A)return i.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const j=i.apply(this,arguments);return this._shimmedLocalStreams[A.id]?this._shimmedLocalStreams[A.id].indexOf(j)===-1&&this._shimmedLocalStreams[A.id].push(j):this._shimmedLocalStreams[A.id]=[A,j],j};const o=l.RTCPeerConnection.prototype.addStream;l.RTCPeerConnection.prototype.addStream=function(b){this._shimmedLocalStreams=this._shimmedLocalStreams||{},b.getTracks().forEach(H=>{if(this.getSenders().find(z=>z.track===H))throw new DOMException("Track already exists.","InvalidAccessError")});const A=this.getSenders();o.apply(this,arguments);const j=this.getSenders().filter(H=>A.indexOf(H)===-1);this._shimmedLocalStreams[b.id]=[b].concat(j)};const p=l.RTCPeerConnection.prototype.removeStream;l.RTCPeerConnection.prototype.removeStream=function(b){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[b.id],p.apply(this,arguments)};const g=l.RTCPeerConnection.prototype.removeTrack;l.RTCPeerConnection.prototype.removeTrack=function(b){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},b&&Object.keys(this._shimmedLocalStreams).forEach(A=>{const j=this._shimmedLocalStreams[A].indexOf(b);j!==-1&&this._shimmedLocalStreams[A].splice(j,1),this._shimmedLocalStreams[A].length===1&&delete this._shimmedLocalStreams[A]}),g.apply(this,arguments)}}function tE(l,i){if(!l.RTCPeerConnection)return;if(l.RTCPeerConnection.prototype.addTrack&&i.version>=65)return Qm(l);const o=l.RTCPeerConnection.prototype.getLocalStreams;l.RTCPeerConnection.prototype.getLocalStreams=function(){const H=o.apply(this);return this._reverseStreams=this._reverseStreams||{},H.map(z=>this._reverseStreams[z.id])};const p=l.RTCPeerConnection.prototype.addStream;l.RTCPeerConnection.prototype.addStream=function(H){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},H.getTracks().forEach(z=>{if(this.getSenders().find($=>$.track===z))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[H.id]){const z=new l.MediaStream(H.getTracks());this._streams[H.id]=z,this._reverseStreams[z.id]=H,H=z}p.apply(this,[H])};const g=l.RTCPeerConnection.prototype.removeStream;function b(H,z){let $=z.sdp;return Object.keys(H._reverseStreams||[]).forEach(Vt=>{const _r=H._reverseStreams[Vt],Fi=H._streams[_r.id];$=$.replace(new RegExp(Fi.id,"g"),_r.id)}),new RTCSessionDescription({type:z.type,sdp:$})}l.RTCPeerConnection.prototype.removeStream=function(H){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},g.apply(this,[this._streams[H.id]||H]),delete this._reverseStreams[this._streams[H.id]?this._streams[H.id].id:H.id],delete this._streams[H.id]},l.RTCPeerConnection.prototype.addTrack=function(H,z){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const $=[].slice.call(arguments,1);if($.length!==1||!$[0].getTracks().find(_r=>_r===H))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(_r=>_r.track===H))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const Vt=this._streams[z.id];if(Vt)Vt.addTrack(H),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const _r=new l.MediaStream([H]);this._streams[z.id]=_r,this._reverseStreams[_r.id]=z,this.addStream(_r)}return this.getSenders().find(_r=>_r.track===H)},["createOffer","createAnswer"].forEach(function(H){const z=l.RTCPeerConnection.prototype[H],$={[H](){const Vt=arguments;return arguments.length&&typeof arguments[0]=="function"?z.apply(this,[_r=>{const Fi=b(this,_r);Vt[0].apply(null,[Fi])},_r=>{Vt[1]&&Vt[1].apply(null,_r)},arguments[2]]):z.apply(this,arguments).then(_r=>b(this,_r))}};l.RTCPeerConnection.prototype[H]=$[H]});const A=l.RTCPeerConnection.prototype.setLocalDescription;l.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(H,z){let $=z.sdp;return Object.keys(H._reverseStreams||[]).forEach(Vt=>{const _r=H._reverseStreams[Vt],Fi=H._streams[_r.id];$=$.replace(new RegExp(_r.id,"g"),Fi.id)}),new RTCSessionDescription({type:z.type,sdp:$})}(this,arguments[0]),A.apply(this,arguments)):A.apply(this,arguments)};const j=Object.getOwnPropertyDescriptor(l.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(l.RTCPeerConnection.prototype,"localDescription",{get(){const H=j.get.apply(this);return H.type===""?H:b(this,H)}}),l.RTCPeerConnection.prototype.removeTrack=function(H){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!H._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(H._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let z;this._streams=this._streams||{},Object.keys(this._streams).forEach($=>{this._streams[$].getTracks().find(Vt=>H.track===Vt)&&(z=this._streams[$])}),z&&(z.getTracks().length===1?this.removeStream(this._reverseStreams[z.id]):z.removeTrack(H.track),this.dispatchEvent(new Event("negotiationneeded")))}}function aE(l,i){!l.RTCPeerConnection&&l.webkitRTCPeerConnection&&(l.RTCPeerConnection=l.webkitRTCPeerConnection),l.RTCPeerConnection&&i.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(o){const p=l.RTCPeerConnection.prototype[o],g={[o](){return arguments[0]=new(o==="addIceCandidate"?l.RTCIceCandidate:l.RTCSessionDescription)(arguments[0]),p.apply(this,arguments)}};l.RTCPeerConnection.prototype[o]=g[o]})}function RE(l,i){C(l,"negotiationneeded",o=>{const p=o.target;if(!(i.version<72||p.getConfiguration&&p.getConfiguration().sdpSemantics==="plan-b")||p.signalingState==="stable")return o})}var lE=Object.freeze({__proto__:null,fixNegotiationNeeded:RE,shimAddTrackRemoveTrack:tE,shimAddTrackRemoveTrackWithNative:Qm,shimGetDisplayMedia:function(l,i){l.navigator.mediaDevices&&"getDisplayMedia"in l.navigator.mediaDevices||l.navigator.mediaDevices&&(typeof i=="function"?l.navigator.mediaDevices.getDisplayMedia=function(o){return i(o).then(p=>{const g=o.video&&o.video.width,b=o.video&&o.video.height,A=o.video&&o.video.frameRate;return o.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:p,maxFrameRate:A||3}},g&&(o.video.mandatory.maxWidth=g),b&&(o.video.mandatory.maxHeight=b),l.navigator.mediaDevices.getUserMedia(o)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:_s,shimGetStats:_c,shimGetUserMedia:_a,shimMediaStream:Di,shimOnTrack:_o,shimPeerConnection:aE,shimSenderReceiverGetStats:_m});function gE(l,i){const o=l&&l.navigator,p=l&&l.MediaStreamTrack;if(o.getUserMedia=function(g,b,A){_t("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),o.mediaDevices.getUserMedia(g).then(b,A)},!(i.version>55&&"autoGainControl"in o.mediaDevices.getSupportedConstraints())){const g=function(A,j,H){j in A&&!(H in A)&&(A[H]=A[j],delete A[j])},b=o.mediaDevices.getUserMedia.bind(o.mediaDevices);if(o.mediaDevices.getUserMedia=function(A){return typeof A=="object"&&typeof A.audio=="object"&&(A=JSON.parse(JSON.stringify(A)),g(A.audio,"autoGainControl","mozAutoGainControl"),g(A.audio,"noiseSuppression","mozNoiseSuppression")),b(A)},p&&p.prototype.getSettings){const A=p.prototype.getSettings;p.prototype.getSettings=function(){const j=A.apply(this,arguments);return g(j,"mozAutoGainControl","autoGainControl"),g(j,"mozNoiseSuppression","noiseSuppression"),j}}if(p&&p.prototype.applyConstraints){const A=p.prototype.applyConstraints;p.prototype.applyConstraints=function(j){return this.kind==="audio"&&typeof j=="object"&&(j=JSON.parse(JSON.stringify(j)),g(j,"autoGainControl","mozAutoGainControl"),g(j,"noiseSuppression","mozNoiseSuppression")),A.apply(this,[j])}}}}function cE(l){typeof l=="object"&&l.RTCTrackEvent&&"receiver"in l.RTCTrackEvent.prototype&&!("transceiver"in l.RTCTrackEvent.prototype)&&Object.defineProperty(l.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function _E(l,i){if(typeof l!="object"||!l.RTCPeerConnection&&!l.mozRTCPeerConnection)return;!l.RTCPeerConnection&&l.mozRTCPeerConnection&&(l.RTCPeerConnection=l.mozRTCPeerConnection),i.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(g){const b=l.RTCPeerConnection.prototype[g],A={[g](){return arguments[0]=new(g==="addIceCandidate"?l.RTCIceCandidate:l.RTCSessionDescription)(arguments[0]),b.apply(this,arguments)}};l.RTCPeerConnection.prototype[g]=A[g]});const o={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},p=l.RTCPeerConnection.prototype.getStats;l.RTCPeerConnection.prototype.getStats=function(){const[g,b,A]=arguments;return p.apply(this,[g||null]).then(j=>{if(i.version<53&&!b)try{j.forEach(H=>{H.type=o[H.type]||H.type})}catch(H){if(H.name!=="TypeError")throw H;j.forEach((z,$)=>{j.set($,Object.assign({},z,{type:o[z.type]||z.type}))})}return j}).then(b,A)}}function iE(l){if(typeof l!="object"||!l.RTCPeerConnection||!l.RTCRtpSender||l.RTCRtpSender&&"getStats"in l.RTCRtpSender.prototype)return;const i=l.RTCPeerConnection.prototype.getSenders;i&&(l.RTCPeerConnection.prototype.getSenders=function(){const p=i.apply(this,[]);return p.forEach(g=>g._pc=this),p});const o=l.RTCPeerConnection.prototype.addTrack;o&&(l.RTCPeerConnection.prototype.addTrack=function(){const p=o.apply(this,arguments);return p._pc=this,p}),l.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function rE(l){if(typeof l!="object"||!l.RTCPeerConnection||!l.RTCRtpSender||l.RTCRtpSender&&"getStats"in l.RTCRtpReceiver.prototype)return;const i=l.RTCPeerConnection.prototype.getReceivers;i&&(l.RTCPeerConnection.prototype.getReceivers=function(){const o=i.apply(this,[]);return o.forEach(p=>p._pc=this),o}),C(l,"track",o=>(o.receiver._pc=o.srcElement,o)),l.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function vf(l){l.RTCPeerConnection&&!("removeStream"in l.RTCPeerConnection.prototype)&&(l.RTCPeerConnection.prototype.removeStream=function(i){_t("removeStream","removeTrack"),this.getSenders().forEach(o=>{o.track&&i.getTracks().includes(o.track)&&this.removeTrack(o)})})}function Fg(l){l.DataChannel&&!l.RTCDataChannel&&(l.RTCDataChannel=l.DataChannel)}function _d(l){if(typeof l!="object"||!l.RTCPeerConnection)return;const i=l.RTCPeerConnection.prototype.addTransceiver;i&&(l.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let o=arguments[1]&&arguments[1].sendEncodings;o===void 0&&(o=[]),o=[...o];const p=o.length>0;p&&o.forEach(b=>{if("rid"in b&&!/^[a-z0-9]{0,16}$/i.test(b.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in b&&!(parseFloat(b.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in b&&!(parseFloat(b.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const g=i.apply(this,arguments);if(p){const{sender:b}=g,A=b.getParameters();(!("encodings"in A)||A.encodings.length===1&&Object.keys(A.encodings[0]).length===0)&&(A.encodings=o,b.sendEncodings=o,this.setParametersPromises.push(b.setParameters(A).then(()=>{delete b.sendEncodings}).catch(()=>{delete b.sendEncodings})))}return g})}function _f(l){if(typeof l!="object"||!l.RTCRtpSender)return;const i=l.RTCRtpSender.prototype.getParameters;i&&(l.RTCRtpSender.prototype.getParameters=function(){const o=i.apply(this,arguments);return"encodings"in o||(o.encodings=[].concat(this.sendEncodings||[{}])),o})}function uE(l){if(typeof l!="object"||!l.RTCPeerConnection)return;const i=l.RTCPeerConnection.prototype.createOffer;l.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>i.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):i.apply(this,arguments)}}function dE(l){if(typeof l!="object"||!l.RTCPeerConnection)return;const i=l.RTCPeerConnection.prototype.createAnswer;l.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>i.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):i.apply(this,arguments)}}var IE=Object.freeze({__proto__:null,shimAddTransceiver:_d,shimCreateAnswer:dE,shimCreateOffer:uE,shimGetDisplayMedia:function(l,i){l.navigator.mediaDevices&&"getDisplayMedia"in l.navigator.mediaDevices||l.navigator.mediaDevices&&(l.navigator.mediaDevices.getDisplayMedia=function(o){if(!o||!o.video){const p=new DOMException("getDisplayMedia without video constraints is undefined");return p.name="NotFoundError",p.code=8,Promise.reject(p)}return o.video===!0?o.video={mediaSource:i}:o.video.mediaSource=i,l.navigator.mediaDevices.getUserMedia(o)})},shimGetParameters:_f,shimGetUserMedia:gE,shimOnTrack:cE,shimPeerConnection:_E,shimRTCDataChannel:Fg,shimReceiverGetStats:rE,shimRemoveStream:vf,shimSenderGetStats:iE});function DE(l){if(typeof l=="object"&&l.RTCPeerConnection){if("getLocalStreams"in l.RTCPeerConnection.prototype||(l.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in l.RTCPeerConnection.prototype)){const i=l.RTCPeerConnection.prototype.addTrack;l.RTCPeerConnection.prototype.addStream=function(o){this._localStreams||(this._localStreams=[]),this._localStreams.includes(o)||this._localStreams.push(o),o.getAudioTracks().forEach(p=>i.call(this,p,o)),o.getVideoTracks().forEach(p=>i.call(this,p,o))},l.RTCPeerConnection.prototype.addTrack=function(o,...p){return p&&p.forEach(g=>{this._localStreams?this._localStreams.includes(g)||this._localStreams.push(g):this._localStreams=[g]}),i.apply(this,arguments)}}"removeStream"in l.RTCPeerConnection.prototype||(l.RTCPeerConnection.prototype.removeStream=function(i){this._localStreams||(this._localStreams=[]);const o=this._localStreams.indexOf(i);if(o===-1)return;this._localStreams.splice(o,1);const p=i.getTracks();this.getSenders().forEach(g=>{p.includes(g.track)&&this.removeTrack(g)})})}}function GE(l){if(typeof l=="object"&&l.RTCPeerConnection&&("getRemoteStreams"in l.RTCPeerConnection.prototype||(l.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in l.RTCPeerConnection.prototype))){Object.defineProperty(l.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(o){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=o),this.addEventListener("track",this._onaddstreampoly=p=>{p.streams.forEach(g=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(g))return;this._remoteStreams.push(g);const b=new Event("addstream");b.stream=g,this.dispatchEvent(b)})})}});const i=l.RTCPeerConnection.prototype.setRemoteDescription;l.RTCPeerConnection.prototype.setRemoteDescription=function(){const o=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(p){p.streams.forEach(g=>{if(o._remoteStreams||(o._remoteStreams=[]),o._remoteStreams.indexOf(g)>=0)return;o._remoteStreams.push(g);const b=new Event("addstream");b.stream=g,o.dispatchEvent(b)})}),i.apply(o,arguments)}}}function QE(l){if(typeof l!="object"||!l.RTCPeerConnection)return;const i=l.RTCPeerConnection.prototype,o=i.createOffer,p=i.createAnswer,g=i.setLocalDescription,b=i.setRemoteDescription,A=i.addIceCandidate;i.createOffer=function(H,z){const $=arguments.length>=2?arguments[2]:arguments[0],Vt=o.apply(this,[$]);return z?(Vt.then(H,z),Promise.resolve()):Vt},i.createAnswer=function(H,z){const $=arguments.length>=2?arguments[2]:arguments[0],Vt=p.apply(this,[$]);return z?(Vt.then(H,z),Promise.resolve()):Vt};let j=function(H,z,$){const Vt=g.apply(this,[H]);return $?(Vt.then(z,$),Promise.resolve()):Vt};i.setLocalDescription=j,j=function(H,z,$){const Vt=b.apply(this,[H]);return $?(Vt.then(z,$),Promise.resolve()):Vt},i.setRemoteDescription=j,j=function(H,z,$){const Vt=A.apply(this,[H]);return $?(Vt.then(z,$),Promise.resolve()):Vt},i.addIceCandidate=j}function a_(l){const i=l&&l.navigator;if(i.mediaDevices&&i.mediaDevices.getUserMedia){const o=i.mediaDevices,p=o.getUserMedia.bind(o);i.mediaDevices.getUserMedia=g=>p(m0(g))}!i.getUserMedia&&i.mediaDevices&&i.mediaDevices.getUserMedia&&(i.getUserMedia=(function(o,p,g){i.mediaDevices.getUserMedia(o).then(p,g)}).bind(i))}function m0(l){return l&&l.video!==void 0?Object.assign({},l,{video:Wt(l.video)}):l}function W0(l){if(!l.RTCPeerConnection)return;const i=l.RTCPeerConnection;l.RTCPeerConnection=function(o,p){if(o&&o.iceServers){const g=[];for(let b=0;bi.generateCertificate})}function mS(l){typeof l=="object"&&l.RTCTrackEvent&&"receiver"in l.RTCTrackEvent.prototype&&!("transceiver"in l.RTCTrackEvent.prototype)&&Object.defineProperty(l.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function M0(l){const i=l.RTCPeerConnection.prototype.createOffer;l.RTCPeerConnection.prototype.createOffer=function(o){if(o){o.offerToReceiveAudio!==void 0&&(o.offerToReceiveAudio=!!o.offerToReceiveAudio);const p=this.getTransceivers().find(b=>b.receiver.track.kind==="audio");o.offerToReceiveAudio===!1&&p?p.direction==="sendrecv"?p.setDirection?p.setDirection("sendonly"):p.direction="sendonly":p.direction==="recvonly"&&(p.setDirection?p.setDirection("inactive"):p.direction="inactive"):o.offerToReceiveAudio!==!0||p||this.addTransceiver("audio",{direction:"recvonly"}),o.offerToReceiveVideo!==void 0&&(o.offerToReceiveVideo=!!o.offerToReceiveVideo);const g=this.getTransceivers().find(b=>b.receiver.track.kind==="video");o.offerToReceiveVideo===!1&&g?g.direction==="sendrecv"?g.setDirection?g.setDirection("sendonly"):g.direction="sendonly":g.direction==="recvonly"&&(g.setDirection?g.setDirection("inactive"):g.direction="inactive"):o.offerToReceiveVideo!==!0||g||this.addTransceiver("video",{direction:"recvonly"})}return i.apply(this,arguments)}}function s0(l){typeof l!="object"||l.AudioContext||(l.AudioContext=l.webkitAudioContext)}var Y0=Object.freeze({__proto__:null,shimAudioContext:s0,shimCallbacksAPI:QE,shimConstraints:m0,shimCreateOfferLegacy:M0,shimGetUserMedia:a_,shimLocalStreamsAPI:DE,shimRTCIceServerUrls:W0,shimRemoteStreamsAPI:GE,shimTrackEventTransceiver:mS}),o_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof commonjsGlobal<"u"?commonjsGlobal:typeof self<"u"?self:{};function LE(l){return l&&l.__esModule&&Object.prototype.hasOwnProperty.call(l,"default")?l.default:l}var C_={exports:{}};(function(l){const i={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};i.localCName=i.generateIdentifier(),i.splitLines=function(o){return o.trim().split(` +`).map(p=>p.trim())},i.splitSections=function(o){return o.split(` +m=`).map((p,g)=>(g>0?"m="+p:p).trim()+`\r +`)},i.getDescription=function(o){const p=i.splitSections(o);return p&&p[0]},i.getMediaSections=function(o){const p=i.splitSections(o);return p.shift(),p},i.matchPrefix=function(o,p){return i.splitLines(o).filter(g=>g.indexOf(p)===0)},i.parseCandidate=function(o){let p;p=o.indexOf("a=candidate:")===0?o.substring(12).split(" "):o.substring(10).split(" ");const g={foundation:p[0],component:{1:"rtp",2:"rtcp"}[p[1]]||p[1],protocol:p[2].toLowerCase(),priority:parseInt(p[3],10),ip:p[4],address:p[4],port:parseInt(p[5],10),type:p[7]};for(let b=8;b0?p[0].split("/")[1]:"sendrecv",uri:p[1],attributes:p.slice(2).join(" ")}},i.writeExtmap=function(o){return"a=extmap:"+(o.id||o.preferredId)+(o.direction&&o.direction!=="sendrecv"?"/"+o.direction:"")+" "+o.uri+(o.attributes?" "+o.attributes:"")+`\r +`},i.parseFmtp=function(o){const p={};let g;const b=o.substring(o.indexOf(" ")+1).split(";");for(let A=0;A{o.parameters[A]!==void 0?b.push(A+"="+o.parameters[A]):b.push(A)}),p+="a=fmtp:"+g+" "+b.join(";")+`\r +`}return p},i.parseRtcpFb=function(o){const p=o.substring(o.indexOf(" ")+1).split(" ");return{type:p.shift(),parameter:p.join(" ")}},i.writeRtcpFb=function(o){let p="",g=o.payloadType;return o.preferredPayloadType!==void 0&&(g=o.preferredPayloadType),o.rtcpFeedback&&o.rtcpFeedback.length&&o.rtcpFeedback.forEach(b=>{p+="a=rtcp-fb:"+g+" "+b.type+(b.parameter&&b.parameter.length?" "+b.parameter:"")+`\r +`}),p},i.parseSsrcMedia=function(o){const p=o.indexOf(" "),g={ssrc:parseInt(o.substring(7,p),10)},b=o.indexOf(":",p);return b>-1?(g.attribute=o.substring(p+1,b),g.value=o.substring(b+1)):g.attribute=o.substring(p+1),g},i.parseSsrcGroup=function(o){const p=o.substring(13).split(" ");return{semantics:p.shift(),ssrcs:p.map(g=>parseInt(g,10))}},i.getMid=function(o){const p=i.matchPrefix(o,"a=mid:")[0];if(p)return p.substring(6)},i.parseFingerprint=function(o){const p=o.substring(14).split(" ");return{algorithm:p[0].toLowerCase(),value:p[1].toUpperCase()}},i.getDtlsParameters=function(o,p){return{role:"auto",fingerprints:i.matchPrefix(o+p,"a=fingerprint:").map(i.parseFingerprint)}},i.writeDtlsParameters=function(o,p){let g="a=setup:"+p+`\r +`;return o.fingerprints.forEach(b=>{g+="a=fingerprint:"+b.algorithm+" "+b.value+`\r +`}),g},i.parseCryptoLine=function(o){const p=o.substring(9).split(" ");return{tag:parseInt(p[0],10),cryptoSuite:p[1],keyParams:p[2],sessionParams:p.slice(3)}},i.writeCryptoLine=function(o){return"a=crypto:"+o.tag+" "+o.cryptoSuite+" "+(typeof o.keyParams=="object"?i.writeCryptoKeyParams(o.keyParams):o.keyParams)+(o.sessionParams?" "+o.sessionParams.join(" "):"")+`\r +`},i.parseCryptoKeyParams=function(o){if(o.indexOf("inline:")!==0)return null;const p=o.substring(7).split("|");return{keyMethod:"inline",keySalt:p[0],lifeTime:p[1],mkiValue:p[2]?p[2].split(":")[0]:void 0,mkiLength:p[2]?p[2].split(":")[1]:void 0}},i.writeCryptoKeyParams=function(o){return o.keyMethod+":"+o.keySalt+(o.lifeTime?"|"+o.lifeTime:"")+(o.mkiValue&&o.mkiLength?"|"+o.mkiValue+":"+o.mkiLength:"")},i.getCryptoParameters=function(o,p){return i.matchPrefix(o+p,"a=crypto:").map(i.parseCryptoLine)},i.getIceParameters=function(o,p){const g=i.matchPrefix(o+p,"a=ice-ufrag:")[0],b=i.matchPrefix(o+p,"a=ice-pwd:")[0];return g&&b?{usernameFragment:g.substring(12),password:b.substring(10)}:null},i.writeIceParameters=function(o){let p="a=ice-ufrag:"+o.usernameFragment+`\r +a=ice-pwd:`+o.password+`\r +`;return o.iceLite&&(p+=`a=ice-lite\r +`),p},i.parseRtpParameters=function(o){const p={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},g=i.splitLines(o)[0].split(" ");p.profile=g[2];for(let A=3;A{p.headerExtensions.push(i.parseExtmap(A))});const b=i.matchPrefix(o,"a=rtcp-fb:* ").map(i.parseRtcpFb);return p.codecs.forEach(A=>{b.forEach(j=>{A.rtcpFeedback.find(H=>H.type===j.type&&H.parameter===j.parameter)||A.rtcpFeedback.push(j)})}),p},i.writeRtpDescription=function(o,p){let g="";g+="m="+o+" ",g+=p.codecs.length>0?"9":"0",g+=" "+(p.profile||"UDP/TLS/RTP/SAVPF")+" ",g+=p.codecs.map(A=>A.preferredPayloadType!==void 0?A.preferredPayloadType:A.payloadType).join(" ")+`\r +`,g+=`c=IN IP4 0.0.0.0\r +`,g+=`a=rtcp:9 IN IP4 0.0.0.0\r +`,p.codecs.forEach(A=>{g+=i.writeRtpMap(A),g+=i.writeFmtp(A),g+=i.writeRtcpFb(A)});let b=0;return p.codecs.forEach(A=>{A.maxptime>b&&(b=A.maxptime)}),b>0&&(g+="a=maxptime:"+b+`\r +`),p.headerExtensions&&p.headerExtensions.forEach(A=>{g+=i.writeExtmap(A)}),g},i.parseRtpEncodingParameters=function(o){const p=[],g=i.parseRtpParameters(o),b=g.fecMechanisms.indexOf("RED")!==-1,A=g.fecMechanisms.indexOf("ULPFEC")!==-1,j=i.matchPrefix(o,"a=ssrc:").map(_r=>i.parseSsrcMedia(_r)).filter(_r=>_r.attribute==="cname"),H=j.length>0&&j[0].ssrc;let z;const $=i.matchPrefix(o,"a=ssrc-group:FID").map(_r=>_r.substring(17).split(" ").map(Fi=>parseInt(Fi,10)));$.length>0&&$[0].length>1&&$[0][0]===H&&(z=$[0][1]),g.codecs.forEach(_r=>{if(_r.name.toUpperCase()==="RTX"&&_r.parameters.apt){let Fi={ssrc:H,codecPayloadType:parseInt(_r.parameters.apt,10)};H&&z&&(Fi.rtx={ssrc:z}),p.push(Fi),b&&(Fi=JSON.parse(JSON.stringify(Fi)),Fi.fec={ssrc:H,mechanism:A?"red+ulpfec":"red"},p.push(Fi))}}),p.length===0&&H&&p.push({ssrc:H});let Vt=i.matchPrefix(o,"b=");return Vt.length&&(Vt=Vt[0].indexOf("b=TIAS:")===0?parseInt(Vt[0].substring(7),10):Vt[0].indexOf("b=AS:")===0?1e3*parseInt(Vt[0].substring(5),10)*.95-16e3:void 0,p.forEach(_r=>{_r.maxBitrate=Vt})),p},i.parseRtcpParameters=function(o){const p={},g=i.matchPrefix(o,"a=ssrc:").map(j=>i.parseSsrcMedia(j)).filter(j=>j.attribute==="cname")[0];g&&(p.cname=g.value,p.ssrc=g.ssrc);const b=i.matchPrefix(o,"a=rtcp-rsize");p.reducedSize=b.length>0,p.compound=b.length===0;const A=i.matchPrefix(o,"a=rtcp-mux");return p.mux=A.length>0,p},i.writeRtcpParameters=function(o){let p="";return o.reducedSize&&(p+=`a=rtcp-rsize\r +`),o.mux&&(p+=`a=rtcp-mux\r +`),o.ssrc!==void 0&&o.cname&&(p+="a=ssrc:"+o.ssrc+" cname:"+o.cname+`\r +`),p},i.parseMsid=function(o){let p;const g=i.matchPrefix(o,"a=msid:");if(g.length===1)return p=g[0].substring(7).split(" "),{stream:p[0],track:p[1]};const b=i.matchPrefix(o,"a=ssrc:").map(A=>i.parseSsrcMedia(A)).filter(A=>A.attribute==="msid");return b.length>0?(p=b[0].value.split(" "),{stream:p[0],track:p[1]}):void 0},i.parseSctpDescription=function(o){const p=i.parseMLine(o),g=i.matchPrefix(o,"a=max-message-size:");let b;g.length>0&&(b=parseInt(g[0].substring(19),10)),isNaN(b)&&(b=65536);const A=i.matchPrefix(o,"a=sctp-port:");if(A.length>0)return{port:parseInt(A[0].substring(12),10),protocol:p.fmt,maxMessageSize:b};const j=i.matchPrefix(o,"a=sctpmap:");if(j.length>0){const H=j[0].substring(10).split(" ");return{port:parseInt(H[0],10),protocol:H[1],maxMessageSize:b}}},i.writeSctpDescription=function(o,p){let g=[];return g=o.protocol!=="DTLS/SCTP"?["m="+o.kind+" 9 "+o.protocol+" "+p.protocol+`\r +`,`c=IN IP4 0.0.0.0\r +`,"a=sctp-port:"+p.port+`\r +`]:["m="+o.kind+" 9 "+o.protocol+" "+p.port+`\r +`,`c=IN IP4 0.0.0.0\r +`,"a=sctpmap:"+p.port+" "+p.protocol+` 65535\r +`],p.maxMessageSize!==void 0&&g.push("a=max-message-size:"+p.maxMessageSize+`\r +`),g.join("")},i.generateSessionId=function(){return Math.random().toString().substr(2,22)},i.writeSessionBoilerplate=function(o,p,g){let b;const A=p!==void 0?p:2;return b=o||i.generateSessionId(),`v=0\r +o=`+(g||"thisisadapterortc")+" "+b+" "+A+` IN IP4 127.0.0.1\r +s=-\r +t=0 0\r +`},i.getDirection=function(o,p){const g=i.splitLines(o);for(let b=0;b(o.candidate&&Object.defineProperty(o,"candidate",{value:new l.RTCIceCandidate(o.candidate),writable:"false"}),o))}function Mb(l){!l.RTCIceCandidate||l.RTCIceCandidate&&"relayProtocol"in l.RTCIceCandidate.prototype||C(l,"icecandidate",i=>{if(i.candidate){const o=f_.parseCandidate(i.candidate.candidate);o.type==="relay"&&(i.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[o.priority>>24])}return i})}function A0(l,i){if(!l.RTCPeerConnection)return;"sctp"in l.RTCPeerConnection.prototype||Object.defineProperty(l.RTCPeerConnection.prototype,"sctp",{get(){return this._sctp===void 0?null:this._sctp}});const o=function(j){if(!j||!j.sdp)return!1;const H=f_.splitSections(j.sdp);return H.shift(),H.some(z=>{const $=f_.parseMLine(z);return $&&$.kind==="application"&&$.protocol.indexOf("SCTP")!==-1})},p=function(j){const H=j.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(H===null||H.length<2)return-1;const z=parseInt(H[1],10);return z!=z?-1:z},g=function(j){let H=65536;return i.browser==="firefox"&&(H=i.version<57?j===-1?16384:2147483637:i.version<60?i.version===57?65535:65536:2147483637),H},b=function(j,H){let z=65536;i.browser==="firefox"&&i.version===57&&(z=65535);const $=f_.matchPrefix(j.sdp,"a=max-message-size:");return $.length>0?z=parseInt($[0].substr(19),10):i.browser==="firefox"&&H!==-1&&(z=2147483637),z},A=l.RTCPeerConnection.prototype.setRemoteDescription;l.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,i.browser==="chrome"&&i.version>=76){const{sdpSemantics:j}=this.getConfiguration();j==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(o(arguments[0])){const j=p(arguments[0]),H=g(j),z=b(arguments[0],j);let $;$=H===0&&z===0?Number.POSITIVE_INFINITY:H===0||z===0?Math.max(H,z):Math.min(H,z);const Vt={};Object.defineProperty(Vt,"maxMessageSize",{get:()=>$}),this._sctp=Vt}return A.apply(this,arguments)}}function jS(l){if(!l.RTCPeerConnection||!("createDataChannel"in l.RTCPeerConnection.prototype))return;function i(p,g){const b=p.send;p.send=function(){const A=arguments[0],j=A.length||A.size||A.byteLength;if(p.readyState==="open"&&g.sctp&&j>g.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+g.sctp.maxMessageSize+" bytes)");return b.apply(p,arguments)}}const o=l.RTCPeerConnection.prototype.createDataChannel;l.RTCPeerConnection.prototype.createDataChannel=function(){const p=o.apply(this,arguments);return i(p,this),p},C(l,"datachannel",p=>(i(p.channel,p.target),p))}function eT(l){if(!l.RTCPeerConnection||"connectionState"in l.RTCPeerConnection.prototype)return;const i=l.RTCPeerConnection.prototype;Object.defineProperty(i,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(i,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(o){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),o&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=o)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(o=>{const p=i[o];i[o]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=g=>{const b=g.target;if(b._lastConnectionState!==b.connectionState){b._lastConnectionState=b.connectionState;const A=new Event("connectionstatechange",g);b.dispatchEvent(A)}return g},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),p.apply(this,arguments)}})}function gS(l,i){if(!l.RTCPeerConnection||i.browser==="chrome"&&i.version>=71||i.browser==="safari"&&i.version>=605)return;const o=l.RTCPeerConnection.prototype.setRemoteDescription;l.RTCPeerConnection.prototype.setRemoteDescription=function(p){if(p&&p.sdp&&p.sdp.indexOf(` +a=extmap-allow-mixed`)!==-1){const g=p.sdp.split(` +`).filter(b=>b.trim()!=="a=extmap-allow-mixed").join(` +`);l.RTCSessionDescription&&p instanceof l.RTCSessionDescription?arguments[0]=new l.RTCSessionDescription({type:p.type,sdp:g}):p.sdp=g}return o.apply(this,arguments)}}function VS(l,i){if(!l.RTCPeerConnection||!l.RTCPeerConnection.prototype)return;const o=l.RTCPeerConnection.prototype.addIceCandidate;o&&o.length!==0&&(l.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(i.browser==="chrome"&&i.version<78||i.browser==="firefox"&&i.version<68||i.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():o.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function rS(l,i){if(!l.RTCPeerConnection||!l.RTCPeerConnection.prototype)return;const o=l.RTCPeerConnection.prototype.setLocalDescription;o&&o.length!==0&&(l.RTCPeerConnection.prototype.setLocalDescription=function(){let p=arguments[0]||{};if(typeof p!="object"||p.type&&p.sdp)return o.apply(this,arguments);if(p={type:p.type,sdp:p.sdp},!p.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":p.type="offer";break;default:p.type="answer"}return p.sdp||p.type!=="offer"&&p.type!=="answer"?o.apply(this,[p]):(p.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(g=>o.apply(this,[g]))})}var GT=Object.freeze({__proto__:null,removeExtmapAllowMixed:gS,shimAddIceCandidateNullOrEmpty:VS,shimConnectionState:eT,shimMaxMessageSize:A0,shimParameterlessSetLocalDescription:rS,shimRTCIceCandidate:T0,shimRTCIceCandidateRelayProtocol:Mb,shimSendThrowTypeError:jS});(function({window:l}={},i={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const o=B,p=function(b){const A={browser:null,version:null};if(b===void 0||!b.navigator)return A.browser="Not a browser.",A;const{navigator:j}=b;if(j.mozGetUserMedia)A.browser="firefox",A.version=_(j.userAgent,/Firefox\/(\d+)\./,1);else if(j.webkitGetUserMedia||b.isSecureContext===!1&&b.webkitRTCPeerConnection)A.browser="chrome",A.version=_(j.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!b.RTCPeerConnection||!j.userAgent.match(/AppleWebKit\/(\d+)\./))return A.browser="Not a supported browser.",A;A.browser="safari",A.version=_(j.userAgent,/AppleWebKit\/(\d+)\./,1),A.supportsUnifiedPlan=b.RTCRtpTransceiver&&"currentDirection"in b.RTCRtpTransceiver.prototype}return A}(l),g={browserDetails:p,commonShim:GT,extractVersion:_,disableLog:P,disableWarnings:x,sdp:F_};switch(p.browser){case"chrome":if(!lE||!aE||!i.shimChrome)return o("Chrome shim is not included in this adapter release."),g;if(p.version===null)return o("Chrome shim can not determine version, not shimming."),g;o("adapter.js shimming chrome."),g.browserShim=lE,VS(l,p),rS(l),_a(l,p),Di(l),aE(l,p),_o(l),tE(l,p),_s(l),_c(l),_m(l),RE(l,p),T0(l),Mb(l),eT(l),A0(l,p),jS(l),gS(l,p);break;case"firefox":if(!IE||!_E||!i.shimFirefox)return o("Firefox shim is not included in this adapter release."),g;o("adapter.js shimming firefox."),g.browserShim=IE,VS(l,p),rS(l),gE(l,p),_E(l,p),cE(l),vf(l),iE(l),rE(l),Fg(l),_d(l),_f(l),uE(l),dE(l),T0(l),eT(l),A0(l,p),jS(l);break;case"safari":if(!Y0||!i.shimSafari)return o("Safari shim is not included in this adapter release."),g;o("adapter.js shimming safari."),g.browserShim=Y0,VS(l,p),rS(l),W0(l),M0(l),QE(l),DE(l),GE(l),mS(l),a_(l),s0(l),T0(l),Mb(l),A0(l,p),jS(l),gS(l,p);break;default:o("Unsupported browser!")}})({window:typeof window>"u"?void 0:window});var t0=function(l){try{return!!l()}catch{return!0}},qT=!t0(function(){var l=(function(){}).bind();return typeof l!="function"||l.hasOwnProperty("prototype")}),MR=qT,F2=Function.prototype,AP=F2.call,j8=MR&&F2.bind.bind(AP,AP),R0=MR?j8:function(l){return function(){return AP.apply(l,arguments)}},mT=R0({}.isPrototypeOf),b1=function(l){return l&&l.Math==Math&&l},J0=b1(typeof globalThis=="object"&&globalThis)||b1(typeof window=="object"&&window)||b1(typeof self=="object"&&self)||b1(typeof o_=="object"&&o_)||function(){return this}()||o_||Function("return this")(),V8=qT,j2=Function.prototype,V2=j2.apply,B2=j2.call,OP=typeof Reflect=="object"&&Reflect.apply||(V8?B2.bind(V2):function(){return B2.apply(V2,arguments)}),G2=R0,B8=G2({}.toString),G8=G2("".slice),iR=function(l){return G8(B8(l),8,-1)},q8=iR,W8=R0,NP=function(l){if(q8(l)==="Function")return W8(l)},PP=typeof document=="object"&&document.all,S1={all:PP,IS_HTMLDDA:PP===void 0&&PP!==void 0},H8=S1.all,U0=S1.IS_HTMLDDA?function(l){return typeof l=="function"||l===H8}:function(l){return typeof l=="function"},mO={},TT=!t0(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),z8=qT,T1=Function.prototype.call,iS=z8?T1.bind(T1):function(){return T1.apply(T1,arguments)},kP={},q2={}.propertyIsEnumerable,W2=Object.getOwnPropertyDescriptor,K8=W2&&!q2.call({1:2},1);kP.f=K8?function(l){var i=W2(this,l);return!!i&&i.enumerable}:q2;var sR,R1,UR=function(l,i){return{enumerable:!(1&l),configurable:!(2&l),writable:!(4&l),value:i}},Y8=t0,J8=iR,DP=Object,X8=R0("".split),LP=Y8(function(){return!DP("z").propertyIsEnumerable(0)})?function(l){return J8(l)=="String"?X8(l,""):DP(l)}:DP,C1=function(l){return l==null},Q8=C1,$8=TypeError,gO=function(l){if(Q8(l))throw $8("Can't call method on "+l);return l},Z8=LP,tW=gO,FR=function(l){return Z8(tW(l))},H2=U0,eW=S1.all,nT=S1.IS_HTMLDDA?function(l){return typeof l=="object"?l!==null:H2(l)||l===eW}:function(l){return typeof l=="object"?l!==null:H2(l)},jR={},xP=jR,MP=J0,nW=U0,z2=function(l){return nW(l)?l:void 0},TS=function(l,i){return arguments.length<2?z2(xP[l])||z2(MP[l]):xP[l]&&xP[l][i]||MP[l]&&MP[l][i]},VR=typeof navigator<"u"&&String(navigator.userAgent)||"",K2=J0,UP=VR,Y2=K2.process,J2=K2.Deno,X2=Y2&&Y2.versions||J2&&J2.version,Q2=X2&&X2.v8;Q2&&(R1=(sR=Q2.split("."))[0]>0&&sR[0]<4?1:+(sR[0]+sR[1])),!R1&&UP&&(!(sR=UP.match(/Edge\/(\d+)/))||sR[1]>=74)&&(sR=UP.match(/Chrome\/(\d+)/))&&(R1=+sR[1]);var BR=R1,$2=BR,rW=t0,iW=J0.String,_I=!!Object.getOwnPropertySymbols&&!rW(function(){var l=Symbol();return!iW(l)||!(Object(l)instanceof Symbol)||!Symbol.sham&&$2&&$2<41}),Z2=_I&&!Symbol.sham&&typeof Symbol.iterator=="symbol",sW=TS,oW=U0,aW=mT,cW=Object,EO=Z2?function(l){return typeof l=="symbol"}:function(l){var i=sW("Symbol");return oW(i)&&aW(i.prototype,cW(l))},uW=String,yI=function(l){try{return uW(l)}catch{return"Object"}},lW=U0,dW=yI,hW=TypeError,rT=function(l){if(lW(l))return l;throw hW(dW(l)+" is not a function")},pW=rT,fW=C1,FP=function(l,i){var o=l[i];return fW(o)?void 0:pW(o)},jP=iS,VP=U0,BP=nT,mW=TypeError,tU={exports:{}},eU=J0,gW=Object.defineProperty,EW=function(l,i){try{gW(eU,l,{value:i,configurable:!0,writable:!0})}catch{eU[l]=i}return i},nU="__core-js_shared__",GP=J0[nU]||EW(nU,{}),rU=GP;(tU.exports=function(l,i){return rU[l]||(rU[l]=i!==void 0?i:{})})("versions",[]).push({version:"3.31.1",mode:"pure",copyright:"© 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 bI=tU.exports,vW=gO,_W=Object,GR=function(l){return _W(vW(l))},yW=GR,bW=R0({}.hasOwnProperty),sS=Object.hasOwn||function(l,i){return bW(yW(l),i)},SW=R0,TW=0,RW=Math.random(),CW=SW(1 .toString),qP=function(l){return"Symbol("+(l===void 0?"":l)+")_"+CW(++TW+RW,36)},IW=bI,iU=sS,wW=qP,AW=_I,OW=Z2,SI=J0.Symbol,WP=IW("wks"),NW=OW?SI.for||SI:SI&&SI.withoutSetter||wW,g0=function(l){return iU(WP,l)||(WP[l]=AW&&iU(SI,l)?SI[l]:NW("Symbol."+l)),WP[l]},PW=iS,sU=nT,oU=EO,kW=FP,DW=function(l,i){var o,p;if(i==="string"&&VP(o=l.toString)&&!BP(p=jP(o,l))||VP(o=l.valueOf)&&!BP(p=jP(o,l))||i!=="string"&&VP(o=l.toString)&&!BP(p=jP(o,l)))return p;throw mW("Can't convert object to primitive value")},LW=TypeError,xW=g0("toPrimitive"),MW=function(l,i){if(!sU(l)||oU(l))return l;var o,p=kW(l,xW);if(p){if(i===void 0&&(i="default"),o=PW(p,l,i),!sU(o)||oU(o))return o;throw LW("Can't convert object to primitive value")}return i===void 0&&(i="number"),DW(l,i)},UW=EO,I1=function(l){var i=MW(l,"string");return UW(i)?i:i+""},aU=nT,HP=J0.document,FW=aU(HP)&&aU(HP.createElement),zP=function(l){return FW?HP.createElement(l):{}},jW=zP,cU=!TT&&!t0(function(){return Object.defineProperty(jW("div"),"a",{get:function(){return 7}}).a!=7}),VW=TT,BW=iS,GW=kP,qW=UR,WW=FR,HW=I1,zW=sS,KW=cU,uU=Object.getOwnPropertyDescriptor;mO.f=VW?uU:function(l,i){if(l=WW(l),i=HW(i),KW)try{return uU(l,i)}catch{}if(zW(l,i))return qW(!BW(GW.f,l,i),l[i])};var YW=t0,JW=U0,XW=/#|\.prototype\./,vO=function(l,i){var o=$W[QW(l)];return o==tH||o!=ZW&&(JW(i)?YW(i):!!i)},QW=vO.normalize=function(l){return String(l).replace(XW,".").toLowerCase()},$W=vO.data={},ZW=vO.NATIVE="N",tH=vO.POLYFILL="P",lU=vO,eH=rT,nH=qT,rH=NP(NP.bind),_O=function(l,i){return eH(l),i===void 0?l:nH?rH(l,i):function(){return l.apply(i,arguments)}},iT={},dU=TT&&t0(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),iH=nT,sH=String,oH=TypeError,gT=function(l){if(iH(l))return l;throw oH(sH(l)+" is not an object")},aH=TT,cH=cU,uH=dU,w1=gT,hU=I1,lH=TypeError,KP=Object.defineProperty,dH=Object.getOwnPropertyDescriptor,YP="enumerable",JP="configurable",XP="writable";iT.f=aH?uH?function(l,i,o){if(w1(l),i=hU(i),w1(o),typeof l=="function"&&i==="prototype"&&"value"in o&&XP in o&&!o[XP]){var p=dH(l,i);p&&p[XP]&&(l[i]=o.value,o={configurable:JP in o?o[JP]:p[JP],enumerable:YP in o?o[YP]:p[YP],writable:!1})}return KP(l,i,o)}:KP:function(l,i,o){if(w1(l),i=hU(i),w1(o),cH)try{return KP(l,i,o)}catch{}if("get"in o||"set"in o)throw lH("Accessors not supported");return"value"in o&&(l[i]=o.value),l};var hH=iT,pH=UR,oR=TT?function(l,i,o){return hH.f(l,i,pH(1,o))}:function(l,i,o){return l[i]=o,l},A1=J0,fH=OP,mH=NP,gH=U0,EH=mO.f,vH=lU,TI=jR,_H=_O,RI=oR,pU=sS,yH=function(l){var i=function(o,p,g){if(this instanceof i){switch(arguments.length){case 0:return new l;case 1:return new l(o);case 2:return new l(o,p)}return new l(o,p,g)}return fH(l,this,arguments)};return i.prototype=l.prototype,i},Y_=function(l,i){var o,p,g,b,A,j,H,z,$,Vt=l.target,_r=l.global,Fi=l.stat,_l=l.proto,_u=_r?A1:Fi?A1[Vt]:(A1[Vt]||{}).prototype,_h=_r?TI:TI[Vt]||RI(TI,Vt,{})[Vt],_g=_h.prototype;for(b in i)p=!(o=vH(_r?b:Vt+(Fi?".":"#")+b,l.forced))&&_u&&pU(_u,b),j=_h[b],p&&(H=l.dontCallGetSet?($=EH(_u,b))&&$.value:_u[b]),A=p&&H?H:i[b],p&&typeof j==typeof A||(z=l.bind&&p?_H(A,A1):l.wrap&&p?yH(A):_l&&gH(A)?mH(A):A,(l.sham||A&&A.sham||j&&j.sham)&&RI(z,"sham",!0),RI(_h,b,z),_l&&(pU(TI,g=Vt+"Prototype")||RI(TI,g,{}),RI(TI[g],b,A),l.real&&_g&&(o||!_g[b])&&RI(_g,b,A)))},bH=Math.ceil,SH=Math.floor,TH=Math.trunc||function(l){var i=+l;return(i>0?SH:bH)(i)},QP=function(l){var i=+l;return i!=i||i===0?0:TH(i)},RH=QP,CH=Math.max,IH=Math.min,fU=function(l,i){var o=RH(l);return o<0?CH(o+i,0):IH(o,i)},wH=QP,AH=Math.min,OH=function(l){return l>0?AH(wH(l),9007199254740991):0},qR=function(l){return OH(l.length)},NH=FR,PH=fU,kH=qR,mU=function(l){return function(i,o,p){var g,b=NH(i),A=kH(b),j=PH(p,A);if(l&&o!=o){for(;A>j;)if((g=b[j++])!=g)return!0}else for(;A>j;j++)if((l||j in b)&&b[j]===o)return l||j||0;return!l&&-1}},gU={includes:mU(!0),indexOf:mU(!1)},DH=gU.includes;Y_({target:"Array",proto:!0,forced:t0(function(){return!Array(1).includes()})},{includes:function(l){return DH(this,l,arguments.length>1?arguments[1]:void 0)}});var LH=jR,WR=function(l){return LH[l+"Prototype"]},xH=WR("Array").includes,MH=nT,UH=iR,FH=g0("match"),jH=function(l){var i;return MH(l)&&((i=l[FH])!==void 0?!!i:UH(l)=="RegExp")},VH=TypeError,EU={};EU[g0("toStringTag")]="z";var $P=String(EU)==="[object z]",BH=$P,GH=U0,O1=iR,qH=g0("toStringTag"),WH=Object,HH=O1(function(){return arguments}())=="Arguments",HR=BH?O1:function(l){var i,o,p;return l===void 0?"Undefined":l===null?"Null":typeof(o=function(g,b){try{return g[b]}catch{}}(i=WH(l),qH))=="string"?o:HH?O1(i):(p=O1(i))=="Object"&&GH(i.callee)?"Arguments":p},zH=HR,KH=String,WT=function(l){if(zH(l)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return KH(l)},YH=g0("match"),JH=Y_,XH=function(l){if(jH(l))throw VH("The method doesn't accept regular expressions");return l},QH=gO,vU=WT,$H=function(l){var i=/./;try{"/./"[l](i)}catch{try{return i[YH]=!1,"/./"[l](i)}catch{}}return!1},ZH=R0("".indexOf);JH({target:"String",proto:!0,forced:!$H("includes")},{includes:function(l){return!!~ZH(vU(QH(this)),vU(XH(l)),arguments.length>1?arguments[1]:void 0)}});var _z=WR("String").includes,_U=mT,tK=xH,eK=_z,ZP=Array.prototype,_k=String.prototype,VE=LE(function(l){var i=l.includes;return l===ZP||_U(ZP,l)&&i===ZP.includes?tK:typeof l=="string"||l===_k||_U(_k,l)&&i===_k.includes?eK:i}),yU={exports:{}},nK=Y_,rK=TT,bU=iT.f;nK({target:"Object",stat:!0,forced:Object.defineProperty!==bU,sham:!rK},{defineProperty:bU});var SU=jR.Object,iK=yU.exports=function(l,i,o){return SU.defineProperty(l,i,o)};SU.defineProperty.sham&&(iK.sham=!0);var sK=LE(yU.exports),oK=iR,tD=Array.isArray||function(l){return oK(l)=="Array"},aK=TypeError,cK=I1,uK=iT,lK=UR,TU=function(l,i,o){var p=cK(i);p in l?uK.f(l,p,lK(0,o)):l[p]=o},dK=U0,sD=GP,hK=R0(Function.toString);dK(sD.inspectSource)||(sD.inspectSource=function(l){return hK(l)});var RU=sD.inspectSource,pK=R0,fK=t0,CU=U0,mK=HR,gK=RU,IU=function(){},EK=[],wU=TS("Reflect","construct"),uD=/^\s*(?:class|function)\b/,vK=pK(uD.exec),_K=!uD.exec(IU),yO=function(l){if(!CU(l))return!1;try{return wU(IU,EK,l),!0}catch{return!1}},AU=function(l){if(!CU(l))return!1;switch(mK(l)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return _K||!!vK(uD,gK(l))}catch{return!0}};AU.sham=!0;var OU=!wU||fK(function(){var l;return yO(yO.call)||!yO(Object)||!yO(function(){l=!0})||l})?AU:yO,NU=tD,yK=OU,bK=nT,SK=g0("species"),PU=Array,TK=function(l){var i;return NU(l)&&(i=l.constructor,(yK(i)&&(i===PU||NU(i.prototype))||bK(i)&&(i=i[SK])===null)&&(i=void 0)),i===void 0?PU:i},kU=function(l,i){return new(TK(l))(i===0?0:i)},RK=t0,CK=BR,IK=g0("species"),wK=Y_,AK=t0,OK=tD,NK=nT,PK=GR,kK=qR,DU=function(l){if(l>9007199254740991)throw aK("Maximum allowed index exceeded");return l},LU=TU,DK=kU,LK=function(l){return CK>=51||!RK(function(){var i=[];return(i.constructor={})[IK]=function(){return{foo:1}},i[l](Boolean).foo!==1})},xK=BR,xU=g0("isConcatSpreadable"),MK=xK>=51||!AK(function(){var l=[];return l[xU]=!1,l.concat()[0]!==l}),UK=function(l){if(!NK(l))return!1;var i=l[xU];return i!==void 0?!!i:OK(l)};wK({target:"Array",proto:!0,arity:1,forced:!MK||!LK("concat")},{concat:function(l){var i,o,p,g,b,A=PK(this),j=DK(A,0),H=0;for(i=-1,p=arguments.length;ig;)vD(p,o=i[g++])&&(~jK(b,o)||MU(b,o));return b},_D=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],BK=UU,GK=_D,FU=Object.keys||function(l){return BK(l,GK)},qK=TT,WK=dU,HK=iT,zK=gT,KK=FR,YK=FU;ED.f=qK&&!WK?Object.defineProperties:function(l,i){zK(l);for(var o,p=KK(i),g=YK(i),b=g.length,A=0;b>A;)HK.f(l,o=g[A++],p[o]);return l};var P1,jU=TS("document","documentElement"),JK=qP,VU=bI("keys"),k1=function(l){return VU[l]||(VU[l]=JK(l))},XK=gT,QK=ED,BU=_D,$K=N1,ZK=jU,t7=zP,yD="prototype",SD="script",GU=k1("IE_PROTO"),TD=function(){},qU=function(l){return"<"+SD+">"+l+""},WU=function(l){l.write(qU("")),l.close();var i=l.parentWindow.Object;return l=null,i},D1=function(){try{P1=new ActiveXObject("htmlfile")}catch{}var l,i,o;D1=typeof document<"u"?document.domain&&P1?WU(P1):(i=t7("iframe"),o="java"+SD+":",i.style.display="none",ZK.appendChild(i),i.src=String(o),(l=i.contentWindow.document).open(),l.write(qU("document.F=Object")),l.close(),l.F):WU(P1);for(var p=BU.length;p--;)delete D1[yD][BU[p]];return D1()};$K[GU]=!0;var L1=Object.create||function(l,i){var o;return l!==null?(TD[yD]=XK(l),o=new TD,TD[yD]=null,o[GU]=l):o=D1(),i===void 0?o:QK.f(o,i)},x1={},e7=UU,n7=_D.concat("length","prototype");x1.f=Object.getOwnPropertyNames||function(l){return e7(l,n7)};var HU={},zU=fU,r7=qR,i7=TU,s7=Array,o7=Math.max,KU=function(l,i,o){for(var p=r7(l),g=zU(i,p),b=zU(o===void 0?p:o,p),A=s7(o7(b-g,0)),j=0;geE;eE++)if((j||eE in _u)&&(Fi=_h(_r=_u[eE],eE,_l),l))if(i)SE[eE]=Fi;else if(Fi)switch(l){case 3:return!0;case 5:return _r;case 6:return eE;case 2:rF(SE,_r)}else switch(l){case 4:return!1;case 7:rF(SE,_r)}return b?-1:p||g?g:SE}},j7={forEach:aR(0),map:aR(1),filter:aR(2),some:aR(3),every:aR(4),find:aR(5),findIndex:aR(6),filterReject:aR(7)},V1=Y_,wD=J0,AD=iS,V7=R0,AI=TT,OI=_I,B7=t0,X0=sS,G7=mT,OD=gT,B1=FR,ND=I1,q7=WT,PD=UR,TO=L1,iF=FU,W7=x1,sF=HU,H7=M1,oF=mO,aF=iT,z7=ED,cF=kP,uF=bO,K7=XU,DD=bI,lF=N1,dF=qP,Y7=g0,J7=CI,X7=I0,Q7=$U,$7=II,hF=j1,G1=j7.forEach,RS=k1("hidden"),q1="Symbol",RO="prototype",Z7=hF.set,pF=hF.getterFor(q1),ET=Object[RO],zR=wD.Symbol,W1=zR&&zR[RO],t9=wD.TypeError,LD=wD.QObject,fF=oF.f,KR=aF.f,mF=sF.f,e9=cF.f,gF=V7([].push),HT=DD("symbols"),CO=DD("op-symbols"),n9=DD("wks"),xD=!LD||!LD[RO]||!LD[RO].findChild,MD=AI&&B7(function(){return TO(KR({},"a",{get:function(){return KR(this,"a",{value:7}).a}})).a!=7})?function(l,i,o){var p=fF(ET,i);p&&delete ET[i],KR(l,i,o),p&&l!==ET&&KR(ET,i,p)}:KR,UD=function(l,i){var o=HT[l]=TO(W1);return Z7(o,{type:q1,tag:l,description:i}),AI||(o.description=i),o},H1=function(l,i,o){l===ET&&H1(CO,i,o),OD(l);var p=ND(i);return OD(o),X0(HT,p)?(o.enumerable?(X0(l,RS)&&l[RS][p]&&(l[RS][p]=!1),o=TO(o,{enumerable:PD(0,!1)})):(X0(l,RS)||KR(l,RS,PD(1,{})),l[RS][p]=!0),MD(l,p,o)):KR(l,p,o)},FD=function(l,i){OD(l);var o=B1(i),p=iF(o).concat(yF(o));return G1(p,function(g){AI&&!AD(EF,o,g)||H1(l,g,o[g])}),l},EF=function(l){var i=ND(l),o=AD(e9,this,i);return!(this===ET&&X0(HT,i)&&!X0(CO,i))&&(!(o||!X0(this,i)||!X0(HT,i)||X0(this,RS)&&this[RS][i])||o)},vF=function(l,i){var o=B1(l),p=ND(i);if(o!==ET||!X0(HT,p)||X0(CO,p)){var g=fF(o,p);return!g||!X0(HT,p)||X0(o,RS)&&o[RS][p]||(g.enumerable=!0),g}},_F=function(l){var i=mF(B1(l)),o=[];return G1(i,function(p){X0(HT,p)||X0(lF,p)||gF(o,p)}),o},yF=function(l){var i=l===ET,o=mF(i?CO:B1(l)),p=[];return G1(o,function(g){!X0(HT,g)||i&&!X0(ET,g)||gF(p,HT[g])}),p};OI||(zR=function(){if(G7(W1,this))throw t9("Symbol is not a constructor");var l=arguments.length&&arguments[0]!==void 0?q7(arguments[0]):void 0,i=dF(l),o=function(p){this===ET&&AD(o,CO,p),X0(this,RS)&&X0(this[RS],i)&&(this[RS][i]=!1),MD(this,i,PD(1,p))};return AI&&xD&&MD(ET,i,{configurable:!0,set:o}),UD(i,l)},uF(W1=zR[RO],"toString",function(){return pF(this).tag}),uF(zR,"withoutSetter",function(l){return UD(dF(l),l)}),cF.f=EF,aF.f=H1,z7.f=FD,oF.f=vF,W7.f=sF.f=_F,H7.f=yF,J7.f=function(l){return UD(Y7(l),l)},AI&&K7(W1,"description",{configurable:!0,get:function(){return pF(this).description}})),V1({global:!0,constructor:!0,wrap:!0,forced:!OI,sham:!OI},{Symbol:zR}),G1(iF(n9),function(l){X7(l)}),V1({target:q1,stat:!0,forced:!OI},{useSetter:function(){xD=!0},useSimple:function(){xD=!1}}),V1({target:"Object",stat:!0,forced:!OI,sham:!AI},{create:function(l,i){return i===void 0?TO(l):FD(TO(l),i)},defineProperty:H1,defineProperties:FD,getOwnPropertyDescriptor:vF}),V1({target:"Object",stat:!0,forced:!OI},{getOwnPropertyNames:_F}),Q7(),$7(zR,q1),lF[RS]=!0;var bF=_I&&!!Symbol.for&&!!Symbol.keyFor,r9=Y_,i9=TS,s9=sS,o9=WT,SF=bI,a9=bF,VD=SF("string-to-symbol-registry"),c9=SF("symbol-to-string-registry");r9({target:"Symbol",stat:!0,forced:!a9},{for:function(l){var i=o9(l);if(s9(VD,i))return VD[i];var o=i9("Symbol")(i);return VD[i]=o,c9[o]=i,o}});var u9=Y_,l9=sS,d9=EO,h9=yI,p9=bF,TF=bI("symbol-to-string-registry");u9({target:"Symbol",stat:!0,forced:!p9},{keyFor:function(l){if(!d9(l))throw TypeError(h9(l)+" is not a symbol");if(l9(TF,l))return TF[l]}});var RF=R0([].slice),CF=tD,f9=U0,IF=iR,m9=WT,wF=R0([].push),g9=Y_,AF=TS,OF=OP,E9=iS,IO=R0,NF=t0,PF=U0,kF=EO,DF=RF,v9=function(l){if(f9(l))return l;if(CF(l)){for(var i=l.length,o=[],p=0;p=i.length?(l.target=void 0,t3(void 0,!0)):t3(o=="keys"?p:o=="values"?i[p]:[p,i[p]],!1)},"values"),_j.Arguments=_j.Array;var yY={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},bY=J0,SY=HR,TY=oR,n3=NI,r3=g0("toStringTag");for(var YD in yY){var i3=bY[YD],JD=i3&&i3.prototype;JD&&SY(JD)!==r3&&TY(JD,r3,YD),n3[YD]=n3.Array}var RY=P9,CY=g0,IY=iT.f,s3=CY("metadata"),o3=Function.prototype;o3[s3]===void 0&&IY(o3,s3,{value:null}),I0("dispose"),I0("metadata");var wY=RY;I0("asyncDispose");var AY=R0,XD=TS("Symbol"),OY=XD.keyFor,NY=AY(XD.prototype.valueOf),a3=XD.isRegisteredSymbol||function(l){try{return OY(NY(l))!==void 0}catch{return!1}};Y_({target:"Symbol",stat:!0},{isRegisteredSymbol:a3});for(var PY=bI,c3=TS,kY=R0,DY=EO,LY=g0,J1=c3("Symbol"),u3=J1.isWellKnownSymbol,l3=c3("Object","getOwnPropertyNames"),xY=kY(J1.prototype.valueOf),d3=PY("wks"),QD=0,h3=l3(J1),MY=h3.length;QD=j?l?"":void 0:(p=m3(b,A))<55296||p>56319||A+1===j||(g=m3(b,A+1))<56320||g>57343?l?VY(b,A):p:l?BY(b,A,A+2):g-56320+(p-55296<<10)+65536}},GY={codeAt:g3(!1),charAt:g3(!0)}.charAt,qY=WT,E3=j1,WY=$F,v3=ZF,_3="String Iterator",HY=E3.set,zY=E3.getterFor(_3);WY(String,"String",function(l){HY(this,{type:_3,string:qY(l),index:0})},function(){var l,i=zY(this),o=i.string,p=i.index;return p>=o.length?v3(void 0,!0):(l=GY(o,p),i.index+=l.length,v3(l,!1))});var y3=LE(CI.f("iterator"));function wO(l){return wO=typeof PI=="function"&&typeof y3=="symbol"?function(i){return typeof i}:function(i){return i&&typeof PI=="function"&&i.constructor===PI&&i!==PI.prototype?"symbol":typeof i},wO(l)}var KY=LE(CI.f("toPrimitive"));function YY(l){var i=function(o,p){if(wO(o)!=="object"||o===null)return o;var g=o[KY];if(g!==void 0){var b=g.call(o,p||"default");if(wO(b)!=="object")return b;throw new TypeError("@@toPrimitive must return a primitive value.")}return(p==="string"?String:Number)(o)}(l,"string");return wO(i)==="symbol"?i:String(i)}function _e(l,i,o){return(i=YY(i))in l?sK(l,i,{value:o,enumerable:!0,configurable:!0,writable:!0}):l[i]=o,l}var JY=WR("Array").keys,XY=HR,QY=sS,$Y=mT,ZY=JY,ZD=Array.prototype,tJ={DOMTokenList:!0,NodeList:!0},CS=LE(function(l){var i=l.keys;return l===ZD||$Y(ZD,l)&&i===ZD.keys||QY(tJ,XY(l))?ZY:i}),b3=yI,eJ=TypeError,S3=KU,nJ=Math.floor,tL=function(l,i){var o=l.length,p=nJ(o/2);return o<8?rJ(l,i):iJ(l,tL(S3(l,0,p),i),tL(S3(l,p),i),i)},rJ=function(l,i){for(var o,p,g=l.length,b=1;b0;)l[p]=l[--p];p!==b++&&(l[p]=o)}return l},iJ=function(l,i,o,p){for(var g=i.length,b=o.length,A=0,j=0;A3)){if(gJ)return!0;if(P3)return P3<603;var l,i,o,p,g="";for(l=65;l<76;l++){switch(i=String.fromCharCode(l),l){case 66:case 69:case 70:case 72:o=3;break;case 68:case 71:o=4;break;default:o=2}for(p=0;p<47;p++)uR.push({k:i+p,v:o})}for(uR.sort(function(b,A){return A.v-b.v}),p=0;pA3(H)?1:-1}}(l)),o=w3(g),p=0;pb;b++)if((j=_g(l[b]))&&B3(q3,j))return j;return new X1(!1)}p=lX(l,g)}for(H=_r?l.next:p.next;!(z=sX(H,p)).done;){try{j=_g(z.value)}catch(eE){G3(p,"throw",eE)}if(typeof j=="object"&&j&&B3(q3,j))return j}return new X1(!1)},pX=WT,fX=Y_,mX=mT,gX=HD,Q1=oY,EX=function(l,i,o){for(var p=NJ(i),g=kJ.f,b=PJ.f,A=0;A2&&vX(o,arguments[2]);var g=[];return yX(l,TX,{that:g}),rL(o,"errors",g),o};Q1?Q1(kI,$1):EX(kI,$1,{name:!0});var sL=kI.prototype=W3($1.prototype,{constructor:iL(1,kI),message:iL(1,""),name:iL(1,"AggregateError")});fX({global:!0,constructor:!0,arity:2},{AggregateError:kI});var NO,DI,H3,oL,PO=typeof process<"u"&&iR(process)=="process",RX=TS,CX=XU,IX=TT,z3=g0("species"),wX=mT,AX=TypeError,OX=OU,NX=yI,PX=TypeError,K3=gT,kX=function(l){if(OX(l))return l;throw PX(NX(l)+" is not a constructor")},DX=C1,LX=g0("species"),Y3=function(l,i){var o,p=K3(l).constructor;return p===void 0||DX(o=K3(p)[LX])?i:kX(o)},xX=TypeError,J3=/(?:ipad|iphone|ipod).*applewebkit/i.test(VR),BS=J0,MX=OP,UX=_O,X3=U0,FX=sS,Q3=t0,$3=jU,jX=RF,Z3=zP,VX=function(l,i){if(l{};function UO(){const l={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:_$};return l.promise=new pE((i,o)=>{l.resolve=p=>{l.isFinished||(l.isResolved=!0,l.isFinished=!0,i(p),l.value=p)},l.reject=p=>{l.isFinished||(l.isRejected=!0,l.isFinished=!0,o(p))}}),l}const sN=new Map,oN=new Map,IT=new Map;var l0,m_;(function(l){l.WIN_10="Windows 10",l.WIN_81="Windows 8.1",l.WIN_8="Windows 8",l.WIN_7="Windows 7",l.WIN_VISTA="Windows Vista",l.WIN_SERVER_2003="Windows Server 2003",l.WIN_XP="Windows XP",l.WIN_2000="Windows 2000",l.ANDROID="Android",l.HARMONY_OS="HarmonyOS",l.OPEN_BSD="Open BSD",l.SUN_OS="Sun OS",l.LINUX="Linux",l.IOS="iOS",l.MAC_OS="Mac OS",l.QNX="QNX",l.UNIX="UNIX",l.BEOS="BeOS",l.OS_2="OS/2",l.SEARCH_BOT="Search Bot"})(l0||(l0={})),function(l){l.CHROME="Chrome",l.SAFARI="Safari",l.EDGE="Edge",l.FIREFOX="Firefox",l.OPERA="OPR",l.QQ="QQBrowser",l.WECHAT="MicroMessenger"}(m_||(m_={}));var PL={exports:{}};(function(l,i){(function(o,p){var g="function",b="undefined",A="object",j="string",H="major",z="model",$="name",Vt="type",_r="vendor",Fi="version",_l="architecture",_u="console",_h="mobile",_g="tablet",eE="smarttv",oE="wearable",SE="embedded",vE="Amazon",fE="Apple",mE="ASUS",EE="BlackBerry",PE="Browser",OE="Chrome",$E="Firefox",s_="Google",B_="Huawei",r0="LG",P_="Microsoft",yS="Motorola",CE="Opera",AE="Samsung",UE="Sharp",YE="Sony",h_="Xiaomi",NE="Zebra",ga="Facebook",Eg="Chromium OS",sE="Mac OS",wE=function(z_){for(var i0={},k_=0;k_0?K_.length===2?typeof K_[1]==g?this[K_[0]]=K_[1].call(this,fS):this[K_[0]]=K_[1]:K_.length===3?typeof K_[1]!==g||K_[1].exec&&K_[1].test?this[K_[0]]=fS?fS.replace(K_[1],K_[2]):p:this[K_[0]]=fS?K_[1].call(this,fS,K_[2]):p:K_.length===4&&(this[K_[0]]=fS?K_[3].call(this,fS.replace(K_[1],K_[2])):p):this[K_]=fS||p;xR+=2}},rR=function(z_,i0){for(var k_ in i0)if(typeof i0[k_]===A&&i0[k_].length>0){for(var SS=0;SS2&&(p_[z]="iPad",p_[Vt]=_g),p_},this.getEngine=function(){var p_={};return p_[$]=p,p_[Fi]=p,bS.call(p_,SS,K_.engine),p_},this.getOS=function(){var p_={};return p_[$]=p,p_[Fi]=p,bS.call(p_,SS,K_.os),!p_[$]&&BT&&BT.platform!="Unknown"&&(p_[$]=BT.platform.replace(/chrome os/i,Eg).replace(/macos/i,sE)),p_},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 SS},this.setUA=function(p_){return SS=typeof p_===j&&p_.length>350?x0(p_,350):p_,this},this.setUA(SS),this};tT.VERSION="0.7.34",tT.BROWSER=wE([$,Fi,H]),tT.CPU=wE([_l]),tT.DEVICE=wE([z,_r,Vt,_u,_h,eE,_g,oE,SE]),tT.ENGINE=tT.OS=wE([$,Fi]),l.exports&&(i=l.exports=tT),i.UAParser=tT;var LR=typeof o!==b&&(o.jQuery||o.Zepto);if(LR&&!LR.ua){var fO=new tT;LR.ua=fO.getResult(),LR.ua.get=function(){return fO.getUA()},LR.ua.set=function(z_){fO.setUA(z_);var i0=fO.getResult();for(var k_ in i0)LR.ua[k_]=i0[k_]}}})(typeof window=="object"?window:o_)})(PL,PL.exports);const kL=new(LE(PL.exports));let zT=kL.getResult(),DL=null;function l_(l){if(!DL){l&&kL.setUA(l),zT=kL.getResult();const i=function(b){if(b.engine.name==="Blink"&&b.browser.name!=="WeChat")return m_.CHROME;switch(b.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return m_.CHROME;case"Safari":case"Mobile Safari":return m_.SAFARI;case"Edge":return m_.EDGE;case"Firefox":return m_.FIREFOX;case"QQBrowser":return m_.QQ;case"Opera":return m_.OPERA;case"WeChat":return m_.WECHAT;default:return b.browser.name||""}}(zT),o=function(b){let A;return A=b.engine.name==="Blink"?b.engine.version||"":b.browser.version||"",A.split(".")[0]}(zT),p=function(b){return b.os.name==="Windows"?b.os.version?b.os.name+" "+b.os.version:b.os.name:b.os.name||""}(zT),g=zT.os.version;if(!(i&&o&&p&&g))return{name:i,version:o,os:p,osVersion:g};DL={name:i,version:o,os:p,osVersion:g}}return DL}function aN(){return l_().os}function FV(){const l=l_();return"".concat(l.os," ").concat(l.osVersion)}function cN(){const l=l_();return!!(zT.engine.name==="WebKit"&&l.os===l0.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&l.name!==m_.SAFARI||z0()&&l.name!==m_.SAFARI)}function y$(){const l=l_();if(cN()){if(l.os===l0.MAC_OS)return!0;if(l.os===l0.IOS){const i=zT.os.version&&zT.os.version.split(".");if(i&&Number(i[0])===14&&i[1]&&Number(i[1])>=3||i&&Number(i[0])>14)return!0}}return!1}function b$(){return zT.engine.name==="WebKit"}function LL(){return l_().name===m_.CHROME}function H0(){return l_().name===m_.SAFARI}function N_(){return l_().name===m_.FIREFOX}function z0(){return l_().os===l0.IOS}function xL(l){const i=l_();return!(i.name!==m_.CHROME||!i.osVersion)&&Number(i.version)>=l}function jV(l){const i=l_();return!(i.name!==m_.EDGE||!i.osVersion)&&Number(i.version)>=l}function VV(l){const i=l_();return!(i.name!==m_.OPERA||!i.osVersion)&&Number(i.version)>=l}function BV(){const l=l_();return!(l.name!==m_.CHROME||!l.osVersion)&&Number(l.version)<=90}function GV(){const l=l_();if(l.os!==l0.IOS||!l.osVersion)return!1;const i=l.osVersion.split(".");return Number(i[0])<14||Number(i[0])===14&&Number(i[1])<=6}function FI(){const l=l_();if(l.os!==l0.IOS||!l.osVersion)return!1;const i=l.osVersion.split(".");return Number(i[0])===15}function ML(){const l=l_();if(l.os!==l0.IOS||!l.osVersion)return!1;const i=l.osVersion.split(".");return Number(i[0])===16}function qV(){const l=l_();if(l.os!==l0.IOS||!l.osVersion)return!1;const i=l.osVersion.split(".");return Number(i[0])===15&&Number(i[1])>=1}function wT(){return H0()&&navigator.maxTouchPoints>0}function WV(){return l_().name===m_.WECHAT}function HV(){return window.navigator.appVersion&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)!==null&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function dR(){const l=l_();return l.name===m_.EDGE||l.name===m_.SAFARI?!1:!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function uN(){return aN()===l0.ANDROID}function FO(){const l=l_();return uN()&&(l.name===m_.CHROME||l.name===m_.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}var _p;(function(l){l.UNEXPECTED_ERROR="UNEXPECTED_ERROR",l.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",l.TIMEOUT="TIMEOUT",l.INVALID_PARAMS="INVALID_PARAMS",l.NOT_READABLE="NOT_READABLE",l.NOT_SUPPORTED="NOT_SUPPORTED",l.INVALID_OPERATION="INVALID_OPERATION",l.OPERATION_ABORTED="OPERATION_ABORTED",l.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",l.EXCHANGE_SDP_FAILED="EXCHANGE_SDP_FAILED",l.ADD_CANDIDATE_FAILED="ADD_CANDIDATE_FAILED",l.DATACHANNEL_FAILED="DATACHANNEL_FAILED",l.NETWORK_ERROR="NETWORK_ERROR",l.NETWORK_TIMEOUT="NETWORK_TIMEOUT",l.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR",l.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT",l.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED",l.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",l.ELECTRON_IS_NULL="ELECTRON_IS_NULL",l.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",l.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE",l.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL",l.MEDIA_OPTION_INVALID="MEDIA_OPTION_INVALID",l.PERMISSION_DENIED="PERMISSION_DENIED",l.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED",l.TRACK_IS_DISABLED="TRACK_IS_DISABLED",l.GET_VIDEO_ELEMENT_VISIBLE_ERROR="GET_VIDEO_ELEMENT_VISIBLE_ERROR",l.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",l.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",l.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR",l.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE",l.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID",l.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER",l.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER",l.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS",l.UID_CONFLICT="UID_CONFLICT",l.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR",l.UPDATE_TICKET_FAILED="UPDATE_TICKET_FAILED",l.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK",l.INVALID_TRACK="INVALID_TRACK",l.SENDER_NOT_FOUND="SENDER_NOT_FOUND",l.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED",l.SET_ANSWER_FAILED="SET_ANSWER_FAILED",l.ICE_FAILED="ICE_FAILED",l.PC_CLOSED="PC_CLOSED",l.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED",l.GET_LOCAL_CAPABILITIES_FAILED="GET_LOCAL_CAPABILITIES_FAILED",l.GET_LOCAL_CONNECTION_PARAMS_FAILED="GET_LOCAL_CONNECTION_PARAMS_FAILED",l.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",l.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",l.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",l.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE",l.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS",l.EXIST_DISABLED_VIDEO_TRACK="EXIST_DISABLED_VIDEO_TRACK",l.INVALID_REMOTE_USER="INVALID_REMOTE_USER",l.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED",l.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED",l.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH",l.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED",l.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR",l.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED",l.WS_ABORT="WS_ABORT",l.WS_DISCONNECT="WS_DISCONNECT",l.WS_ERR="WS_ERR",l.LIVE_STREAMING_TASK_CONFLICT="LIVE_STREAMING_TASK_CONFLICT",l.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT",l.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR",l.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED",l.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED",l.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR",l.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM",l.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT="LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT",l.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE",l.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST",l.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR",l.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR",l.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR",l.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC",l.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST",l.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST",l.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE",l.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE",l.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR",l.INVALID_PLUGIN="INVALID_PLUGIN",l.DISCONNECT_P2P="DISCONNECT_P2P",l.INIT_WEBSOCKET_TIMEOUT="INIT_WEBSOCKET_TIMEOUT",l.CONVERTING_IMAGEDATA_TO_BLOB_FAILED="CONVERTING_IMAGEDATA_TO_BLOB_FAILED",l.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED="CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED",l.INIT_DATACHANNEL_TIMEOUT="INIT_DATACHANNEL_TIMEOUT",l.DATACHANNEL_CONNECTION_TIMEOUT="DATACHANNEL_CONNECTION_TIMEOUT",l.PROHIBITED_OPERATION="PROHIBITED_OPERATION",l.IMAGE_MODERATION_UPLOAD_FAILED="IMAGE_MODERATION_UPLOAD_FAILED"})(_p||(_p={}));let yE=class extends Error{constructor(l){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",o=arguments.length>2?arguments[2]:void 0;super(i),_e(this,"code",void 0),_e(this,"message",void 0),_e(this,"data",void 0),_e(this,"name","AgoraRTCException"),this.code=l,this.message="AgoraRTCError ".concat(this.code,": ").concat(i),this.data=o}toString(){return this.data?"data: ".concat(JSON.stringify(this.data),` +`).concat(this.stack):"".concat(this.stack)}print(){let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"error",i=arguments.length>1?arguments[1]:void 0;return l==="error"&&(i||console).error(this.toString()),l==="warning"&&(i||console).warn(this.toString()),this}throw(l){throw this.print("error",l),this}};function QR(l,i){if(typeof l!="boolean")throw new yE(_p.INVALID_PARAMS,"Invalid ".concat(i,": The value is of the boolean type."))}function d0(l,i,o){if(!VE(o).call(o,l))throw new yE(_p.INVALID_PARAMS,"".concat(i," can only be set as ").concat(JSON.stringify(o)))}function b_(l,i){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,p=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1e4;if(lp||(!(arguments.length>4&&arguments[4]!==void 0)||arguments[4])&&!function(g){return typeof g=="number"&&g%1==0}(l))throw new yE(_p.INVALID_PARAMS,"invalid ".concat(i,": the value range is [").concat(o,", ").concat(p,"]. integer only"))}function UL(l,i){if(typeof l!="number"){if(!(l.min||l.max||l.ideal||l.exact))throw new yE(_p.INVALID_PARAMS,"".concat(i," is not a valid ConstrainLong"));l.min!==void 0&&b_(l.min,"".concat(i,".min"),0,1/0),l.max!==void 0&&b_(l.max,"".concat(i,".max"),1,1/0),l.exact!==void 0&&b_(l.exact,"".concat(i,".exact"),1,1/0),l.ideal!==void 0&&b_(l.ideal,"".concat(i,".ideal"),1,1/0)}else b_(l,i,1,1/0)}function O0(l,i){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,p=arguments.length>3&&arguments[3]!==void 0?arguments[3]:255,g=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4];if(l==null)throw new yE(_p.INVALID_PARAMS,"".concat(i||"param"," cannot be empty"));if(!zV(l,o,p,g))throw new yE(_p.INVALID_PARAMS,"Invalid ".concat(i||"string param",": Length of the string: [").concat(o,",").concat(p,"].").concat(g?" ASCII characters only.":""))}function KT(l,i){if(!Array.isArray(l))throw new yE(_p.INVALID_PARAMS,"".concat(i," should be an array"))}function M_(l){return l==null}function zV(l){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:255,p=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3];return typeof l=="string"&&l.length<=o&&l.length>=i&&(!p||function(g){if(typeof g!="string")return!1;for(let b=0;b255)return!1}return!0}(l))}function KV(l,i,o){if("getBigUint64"in DataView.prototype)return l.getBigUint64(i,o);const p=l.getUint32(i,o),g=l.getUint32(i+4,o),b=+!!o,A=+!o;return BigInt(p*A+g*b)<>BigInt(32)),b=Number(o&BigInt(4294967295));p?(l.setUint32(i+4,g,p),l.setUint32(i,b,p)):(l.setUint32(i,g,p),l.setUint32(i+4,b,p))}var jI,lN;(function(l){l.COVERED="COVERED",l.POSITION="POSITION",l.SIZE="SIZE",l.STYLE="STYLE"})(jI||(jI={})),function(l){l.UNMOUNTED="UNMOUNTED",l.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT"}(lN||(lN={}));const JV=new class{constructor(){_e(this,"_clientSize",null),_e(this,"getClientWidth",()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth),_e(this,"getClientHeight",()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight),_e(this,"getStyle",l=>window.getComputedStyle(l,null)),_e(this,"checkCssVisibleProperty",l=>{var i;let o=!0;const p=this.getStyle(l),{display:g,visibility:b,opacity:A,filter:j}=p;return(g==="none"||VE(i=["hidden","collapse"]).call(i,b)||Number(A)<.1)&&(o=!1),o?(j&&j.split(" ").filter(H=>{var z;const $=H.split("(")[0];return VE(z=["brightness","blur","opacity"]).call(z,$)}).map(H=>{const[z,$]=H.split(/\(|\)/);return[z,Number($.match(/^[0-9\.]+/))]}).forEach(H=>{const[z,$]=H;switch(z){case"brightness":($<.1||$>3)&&(o=!1);break;case"blur":$>3&&(o=!1);break;case"opacity":$<.1&&(o=!1)}}),o):!1}),_e(this,"checkPropertyUpToAllParentNodes",(l,i)=>{let o=!0,p=!0;const g=A=>i(A);let b=l;for(;b&&p;)g(b)||(o=!1,p=!1),b=b.parentElement,b||(p=!1);return o}),_e(this,"checkActualCssVisibleIncludeInherit",l=>this.checkPropertyUpToAllParentNodes(l,this.checkCssVisibleProperty)),_e(this,"getSizeAboutClient",l=>{const{width:i,height:o,left:p,right:g,top:b,bottom:A}=l.getBoundingClientRect(),j=this.getClientWidth(),H=this.getClientHeight();return{width:i,height:o,left:p,right:g,top:b,bottom:A,clientWidth:j,clientHeight:H,clientMin:Math.min(j,H)}}),_e(this,"checkActualSize",()=>{const{width:l,height:i,clientMin:o}=this._clientSize;return this.checkSizeIsVisible(l,i,o)}),_e(this,"elementFromPoint",(l,i)=>document.elementFromPoint?document.elementFromPoint(l,i):null),_e(this,"checkCoverForAPoint",(l,i,o)=>{const p=this.elementFromPoint(l,i);return p!==null&&p!==o}),_e(this,"getPointPositionList",()=>{const{width:l,height:i,left:o,top:p}=this._clientSize,g=l/6,b=i/6,A=[],j=10**6;for(let H=0;H<5;H++)for(let z=0;z<5;z++){const $=(o*j+(H===0?.1:H===4?(g*H*j-1e5)/j:g*H)*j)/j,Vt=(p*j+(z===0?.1:z===4?(b*z*j-1e5)/j:b*z)*j)/j;A.push({x:$,y:Vt})}return[...A]}),_e(this,"checkElementCover",l=>this.getPointPositionList().map(i=>this.checkCoverForAPoint(i.x,i.y,l)).filter(i=>!!i).length>6),_e(this,"checkSizeIsVisible",(l,i,o)=>(l>50||o/l<=10)&&(i>50||o/i<=10)),_e(this,"checkSizeOfPartInClient",()=>{const{left:l,right:i,top:o,bottom:p,clientHeight:g,clientWidth:b,clientMin:A}=this._clientSize;let j,H,z,$;if(l<0)j=0;else{if(!(l(this._clientSize=null,{visible:!1,reason:l})),_e(this,"checkOneElementVisible",l=>{if(l instanceof HTMLElement){if(this.checkElementIsMountedOnDom(l)){if(this.checkActualCssVisibleIncludeInherit(l)){if(this._clientSize=this.getSizeAboutClient(l),this.checkElementCover(l))return this.returnHiddenResult(jI.COVERED);{const i=this.checkActualSize(),o=this.checkSizeOfPartInClient();return i&&!o?this.returnHiddenResult(jI.POSITION):i?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(jI.SIZE)}}return this.returnHiddenResult(jI.STYLE)}return this.returnHiddenResult(lN.UNMOUNTED)}return this.returnHiddenResult(lN.INVALID_HTML_ELEMENT)}),_e(this,"checkElementIsMountedOnDom",l=>this.checkPropertyUpToAllParentNodes(l,i=>i.nodeName.toUpperCase()!=="HTML"?i.parentElement!==null:!!document.documentElement))}};function FL(l){return new TextEncoder().encode(l)}const XV=function(l,i){const o=new Uint8Array(l.byteLength+i.byteLength);return o.set(new Uint8Array(l),0),o.set(new Uint8Array(i),l.byteLength),o},S$=async l=>{const i=function(b){const A=window.atob(b),j=new Uint8Array(new ArrayBuffer(A.length));for(let H=0;Hfunction(i,o){let p="";return new Uint8Array(i).forEach(g=>{p+=g.toString(o).padStart(2,"0")}),p}(await crypto.subtle.digest("SHA-256",FL(l)),16);class D_{constructor(){_e(this,"_events",{}),_e(this,"addListener",this.on)}getListeners(i){return this._events[i]?this._events[i].map(o=>o.listener):[]}on(i,o){this._events[i]||(this._events[i]=[]);const p=this._events[i];this._indexOfListener(p,o)===-1&&p.push({listener:o,once:!1})}once(i,o){this._events[i]||(this._events[i]=[]);const p=this._events[i];this._indexOfListener(p,o)===-1&&p.push({listener:o,once:!0})}off(i,o){if(!this._events[i])return;const p=this._events[i],g=this._indexOfListener(p,o);g!==-1&&p.splice(g,1),this._events[i].length===0&&delete this._events[i]}removeAllListeners(i){i?delete this._events[i]:this._events={}}emit(i){this._events[i]||(this._events[i]=[]);const o=this._events[i].map(A=>A);for(var p=arguments.length,g=new Array(p>1?p-1:0),b=1;b1?o-1:0),g=1;g{b.once&&this.off(i,b.listener);try{b.listener.apply(this,p)}catch(A){console.error("safeEmit event:".concat(i," error ").concat(A==null?void 0:A.toString()))}})}_indexOfListener(i,o){let p=i.length;for(;p--;)if(i[p].listener===o)return p;return-1}}let jO=null;function QV(){if(jO)return jO;if(window.electron)return jO=window.electron;if(!window.require)return null;try{return jO=window.require("electron"),jO}catch{return null}}var e0,x_,jL,e_,n_,h0,K0,YT;function $V(l){return b_(l.timeout,"config.timeout",0,1e5),b_(l.timeoutFactor,"config.timeoutFactor",0,100,!1),b_(l.maxRetryCount,"config.maxRetryConfig",0,1/0),b_(l.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}function VI(l){if(!Array.isArray(l)||l.length<1)return!1;try{l.forEach(i=>{if(!i.urls)throw Error()})}catch{return!1}return!0}function ZV(l){return O0(l.turnServerURL,"turnServerURL"),O0(l.username,"username"),O0(l.password,"password"),l.udpport&&b_(l.udpport,"udpport",1,99999,!0),l.forceturn&&QR(l.forceturn,"forceturn"),l.security&&QR(l.security,"security"),l.tcpport&&b_(l.tcpport,"tcpport",1,99999,!0),!0}function _B(l){return l.level!==void 0&&d0(l.level,"level",[1,2,3]),l.delay!==void 0&&b_(l.delay,"delay",0,3e3,!0),!0}function U_(l,i){for(var o=arguments.length,p=new Array(o>2?o-2:0),g=2;g{l.emit(i,...p,b,A)})}function S_(l,i){if(l.getListeners(i).length===0)return pE.resolve();for(var o=arguments.length,p=new Array(o>2?o-2:0),g=2;g2?o-2:0),g=2;g2?g-2:0),A=2;A{o=j},j=>{p=j}),p!==null)throw p;if(o===null)throw new yE(_p.UNEXPECTED_ERROR,"handler is not sync");return o}(function(l){l.CREATE_CLIENT="createClient",l.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",l.SET_AREA="setArea",l.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",l.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",l.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",l.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",l.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",l.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",l.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",l.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",l.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",l.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",l.START_PROXY_SERVER="Client.startProxyServer",l.STOP_PROXY_SERVER="Client.stopProxyServer",l.SET_PROXY_SERVER="Client.setProxyServer",l.SET_TURN_SERVER="Client.setTurnServer",l.SET_CLIENT_ROLE="Client.setClientRole",l.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",l.ENABLE_DUAL_STREAM="Client.enableDualStream",l.DISABLE_DUAL_STREAM="Client.disableDualStream",l.JOIN="Client.join",l.LEAVE="Client.leave",l.PUBLISH="Client.publish",l.UNPUBLISH="Client.unpublish",l.SUBSCRIBE="Client.subscribe",l.MASS_SUBSCRIBE="Client.massSubscribe",l.MASS_UNSUBSCRIBE="Client.massUnsubscribe",l.UNSUBSCRIBE="Client.unsubscribe",l.RENEW_TOKEN="Client.renewToken",l.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",l.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",l.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",l.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",l.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",l.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",l.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",l.DATACHANNEL_FAILBACK="Client._datachannelFailback",l.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",l.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",l.START_LIVE_STREAMING="Client.startLiveStreaming",l.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",l.STOP_LIVE_STREAMING="Client.stopLiveStreaming",l.ADD_INJECT_STREAM_URL="Client.addInjectStreamUrl",l.REMOVE_INJECT_STREAM_URL="Client.removeInjectStreamUrl",l.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",l.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",l.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",l.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",l.SET_CONFIG_DISTRIBUTE="_configDistribute",l.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",l.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",l.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",l.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",l.LOCAL_AUDIO_TRACK_SET_VOLUME="LocalAudioTrack.setVolume",l.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",l.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",l.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",l.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",l.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",l.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",l.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",l.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",l.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",l.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",l.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",l.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration",l.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",l.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",l.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",l.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",l.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",l.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",l.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",l.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",l.STREAM_TYPE_CHANGE="streamTypeChange",l.CONNECTION_STATE_CHANGE="connectionStateChange",l.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage",l.IMAGE_MODERATION_UPLOAD="imageModerationUpload"})(e0||(e0={})),function(l){l.TRACER="tracer"}(x_||(x_={})),function(l){l[l.AUDIENCE_LEVEL_LOW_LATENCY=1]="AUDIENCE_LEVEL_LOW_LATENCY",l[l.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]="AUDIENCE_LEVEL_ULTRA_LOW_LATENCY",l[l.AUDIENCE_LEVEL_SYNC_LATENCY=3]="AUDIENCE_LEVEL_SYNC_LATENCY"}(jL||(jL={})),function(l){l.LEAVE="LEAVE",l.NETWORK_ERROR="NETWORK_ERROR",l.SERVER_ERROR="SERVER_ERROR",l.UID_BANNED="UID_BANNED",l.IP_BANNED="IP_BANNED",l.CHANNEL_BANNED="CHANNEL_BANNED",l.FALLBACK="FALLBACK",l.LICENSE_MISSING="LICENSE_MISSING",l.LICENSE_EXPIRED="LICENSE_EXPIRED",l.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",l.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",l.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",l.LICENSE_ILLEGAL="LICENSE_ILLEGAL",l.TOKEN_EXPIRE="TOKEN_EXPIRE"}(e_||(e_={})),function(l){l.CONNECTION_STATE_CHANGE="connection-state-change",l.MEDIA_RECONNECT_START="media-reconnect-start",l.MEDIA_RECONNECT_END="media-reconnect-end",l.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",l.USER_JOINED="user-joined",l.USER_LEAVED="user-left",l.USER_PUBLISHED="user-published",l.USER_UNPUBLISHED="user-unpublished",l.USER_INFO_UPDATED="user-info-updated",l.CLIENT_BANNED="client-banned",l.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",l.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",l.VOLUME_INDICATOR="volume-indicator",l.CRYPT_ERROR="crypt-error",l.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",l.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",l.NETWORK_QUALITY="network-quality",l.STREAM_TYPE_CHANGED="stream-type-changed",l.STREAM_FALLBACK="stream-fallback",l.RECEIVE_METADATA="receive-metadata",l.STREAM_MESSAGE="stream-message",l.LIVE_STREAMING_ERROR="live-streaming-error",l.LIVE_STREAMING_WARNING="live-streaming-warning",l.INJECT_STREAM_STATUS="stream-inject-status",l.EXCEPTION="exception",l.ERROR="error",l.P2P_LOST="p2p_lost",l.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",l.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",l.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",l.PUBLISHED_USER_LIST="published-user-list",l.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",l.CONTENT_INSPECT_ERROR="content-inspect-error",l.CONTENT_INSPECT_RESULT="content-inspect-result",l.IMAGE_MODERATION_CONNECTION_STATE_CHANGE="image-moderation-connection-state-change"}(n_||(n_={})),function(l){l.NETWORK_ERROR="NETWORK_ERROR",l.SERVER_ERROR="SERVER_ERROR",l.MULTI_IP="MULTI_IP",l.TIMEOUT="TIMEOUT",l.OFFLINE="OFFLINE",l.LEAVE="LEAVE",l.P2P_FAILED="P2P_FAILED",l.FALLBACK="FALLBACK"}(h0||(h0={})),function(l){l.ONLINE="ONLINE",l.OFFLINE="OFFLINE"}(K0||(K0={})),function(l){l.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",l.ONLINE="ONLINE",l.OFFLINE="OFFLINE"}(YT||(YT={}));const X_=new class extends D_{set networkState(l){this.emit(YT.NETWORK_STATE_CHANGE,l,this._networkState),l===K0.ONLINE?this.emit(YT.ONLINE):l===K0.OFFLINE&&(this.onlineWaiter=new pE(i=>{this.once(YT.ONLINE,()=>{this.onlineWaiter=void 0,i(K0.ONLINE)})}),this.emit(YT.OFFLINE)),this._networkState=l}get networkState(){return this._networkState}get isOnline(){return this._networkState===K0.ONLINE}constructor(){super(),_e(this,"_moduleName","network-indicator"),_e(this,"_networkState",K0.ONLINE),_e(this,"onlineWaiter",void 0),window.addEventListener("online",()=>{this.networkState=K0.ONLINE}),window.addEventListener("offline",()=>{this.networkState=K0.OFFLINE})}};function tG(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function $R(l){for(var i=1;i{i.indexOf(o)===-1&&i.push(o)}),i}function sT(l){pE!==void 0?pE.resolve().then(l):setTimeout(l,0)}function Q_(l){return JSON.parse(JSON.stringify(l))}function ZR(l){try{return Q_(l)}catch{return l}}const eG={};function VO(l,i){eG[i]||(eG[i]=!0,l())}function dN(l){const i=window.atob(l),o=new Uint8Array(new ArrayBuffer(i.length));for(let p=0;p{i+=typeof o=="string"?AT(o):o.size}),i+138}function R$(l){const i=new yE(_p.TIMEOUT,"timeout");return new pE((o,p)=>{window.setTimeout(()=>p(i),l)})}function w0(l){return new pE(i=>{window.setTimeout(i,l)})}function T_(){let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:7,i=arguments.length>1?arguments[1]:void 0;const o=Math.random().toString(16).substr(2,l).toLowerCase();return o.length===l?"".concat(i).concat(o):"".concat(i).concat(o)+T_(l-o.length,"")}function BL(){return T_(32,"").toUpperCase()}const pN=()=>{},rG=new class{constructor(){_e(this,"fnMap",new Map)}throttleByKey(l,i,o,p){for(var g=arguments.length,b=new Array(g>4?g-4:0),A=4;A{const z=this.fnMap.get(i);z&&z.fn(...z.args),this.fnMap.delete(i)},o);this.fnMap.set(i,{fn:l,threshold:o,timer:H,args:b,skipFn:p})}else j.skipFn&&j.skipFn(...j.args),this.fnMap.set(i,$R($R({},j),{},{fn:l,args:b,skipFn:p}))}else{const j=window.setTimeout(()=>{const H=this.fnMap.get(i);H&&H.fn(...H.args),this.fnMap.delete(i)},o);this.fnMap.set(i,{fn:l,threshold:o,timer:j,args:b,skipFn:p})}}},iG=rG.throttleByKey.bind(rG);function sG(l){return typeof l=="object"&&l!==null&&!(l instanceof RegExp)}function GL(l,i){if(!sG(l)||!sG(i)||Array.isArray(l)&&!Array.isArray(i)||!Array.isArray(l)&&Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(l)){const o=[...l];for(let p=0;p0}lock(i){let o;this.locks+=1,fN.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is locked, current queue ").concat(this.locks,". ").concat(typeof i=="string"?i:""));const p=new pE(b=>{o=()=>{this.locks-=1,fN.debug("[lock-".concat(this.name,"-").concat(this.lockId,"] is not locked, current queue ").concat(this.locks,". ").concat(typeof i=="string"?i:"")),b()}}),g=this.lockingPromise.then(()=>o);return this.lockingPromise=this.lockingPromise.then(()=>p),g}}function GI(l,i){return function(o,p,g){const b=g.value;if(typeof b!="function")throw new Error("Cannot use mutex on object property.");return g.value=async function(){const A=this[i];if(!A)throw new Error("mutex property key ".concat(i," doesn't exist on ").concat(l));const j=await A.lock("From ".concat(l,".").concat(p));try{for(var H=arguments.length,z=new Array(H),$=0;${await function(z){return new pE($=>{window.setTimeout($,z)})}(b),b*=g.timeoutFactor,b=Math.min(g.maxRetryTimeout,b)};let j=!1;const H=new pE(async(z,$)=>{i=i||(()=>!1),o=o||(()=>!0);for(let Vt=0;Vtj=!0,H}var I$=rT,w$=GR,A$=LP,O$=qR,N$=TypeError,oG=function(l){return function(i,o,p,g){I$(o);var b=w$(i),A=A$(b),j=O$(b),H=l?j-1:0,z=l?-1:1;if(p<2)for(;;){if(H in A){g=A[H],H+=z;break}if(H+=z,l?H<0:j<=H)throw N$("Reduce of empty array with no initial value")}for(;l?H>=0:j>H;H+=z)H in A&&(g=o(g,A[H],H,b));return g}},P$={left:oG(!1),right:oG(!0)}.left;Y_({target:"Array",proto:!0,forced:!PO&&BR>79&&BR<83||!T3("reduce")},{reduce:function(l){var i=arguments.length;return P$(this,l,i,i>1?arguments[1]:void 0)}});var k$=WR("Array").reduce,D$=mT,L$=k$,qL=Array.prototype,_C=LE(function(l){var i=l.reduce;return l===qL||D$(qL,l)&&i===qL.reduce?L$:i});let WL=class{constructor(l){_e(this,"input",[]),_e(this,"size",void 0),this.size=l}add(l){this.input.push(l),this.input.length>this.size&&this.input.splice(0,1)}mean(){var l;return this.input.length===0?0:_C(l=this.input).call(l,(i,o)=>i+o)/this.input.length}};var HL,zL={exports:{}},aG=function(l,i){return function(){for(var o=new Array(arguments.length),p=0;p"u"||navigator.product!=="ReactNative"&&navigator.product!=="NativeScript"&&navigator.product!=="NS")&&typeof window<"u"&&typeof document<"u"},forEach:QL,merge:function l(){var i={};function o(b,A){EN(i[A])&&EN(b)?i[A]=l(i[A],b):EN(b)?i[A]=l({},b):JL(b)?i[A]=b.slice():i[A]=b}for(var p=0,g=arguments.length;p0;)A[b=p[g]]||(i[b]=l[b],A[b]=!0);l=Object.getPrototypeOf(l)}while(l&&(!o||o(l,i))&&l!==Object.prototype);return i},kindOf:YL,kindOfTest:tI,endsWith:function(l,i,o){l=String(l),(o===void 0||o>l.length)&&(o=l.length),o-=i.length;var p=l.indexOf(i,o);return p!==-1&&p===o},toArray:function(l){if(!l)return null;var i=l.length;if(gN(i))return null;for(var o=new Array(i);i-- >0;)o[i]=l[i];return o},isTypedArray:B$,isFileList:j$},qI=tS;function lG(l){return encodeURIComponent(l).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var dG=function(l,i,o){if(!i)return l;var p;if(o)p=o(i);else if(qI.isURLSearchParams(i))p=i.toString();else{var g=[];qI.forEach(i,function(A,j){A!=null&&(qI.isArray(A)?j+="[]":A=[A],qI.forEach(A,function(H){qI.isDate(H)?H=H.toISOString():qI.isObject(H)&&(H=JSON.stringify(H)),g.push(lG(j)+"="+lG(H))}))}),p=g.join("&")}if(p){var b=l.indexOf("#");b!==-1&&(l=l.slice(0,b)),l+=(l.indexOf("?")===-1?"?":"&")+p}return l},G$=tS;function vN(){this.handlers=[]}vN.prototype.use=function(l,i,o){return this.handlers.push({fulfilled:l,rejected:i,synchronous:!!o&&o.synchronous,runWhen:o?o.runWhen:null}),this.handlers.length-1},vN.prototype.eject=function(l){this.handlers[l]&&(this.handlers[l]=null)},vN.prototype.forEach=function(l){G$.forEach(this.handlers,function(i){i!==null&&l(i)})};var hG,pG,q$=vN,W$=tS;function WI(){if(pG)return hG;pG=1;var l=tS;function i(g,b,A,j,H){Error.call(this),this.message=g,this.name="AxiosError",b&&(this.code=b),A&&(this.config=A),j&&(this.request=j),H&&(this.response=H)}l.inherits(i,Error,{toJSON:function(){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:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var o=i.prototype,p={};return["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED"].forEach(function(g){p[g]={value:g}}),Object.defineProperties(i,p),Object.defineProperty(o,"isAxiosError",{value:!0}),i.from=function(g,b,A,j,H,z){var $=Object.create(o);return l.toFlatObject(g,$,function(Vt){return Vt!==Error.prototype}),i.call($,g.message,b,A,j,H),$.name=g.name,z&&Object.assign($,z),$},hG=i}var ZL,fG,mG,gG,_x,EG,vG={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};function _G(){if(fG)return ZL;fG=1;var l=tS;return ZL=function(i,o){o=o||new FormData;var p=[];function g(b){return b===null?"":l.isDate(b)?b.toISOString():l.isArrayBuffer(b)||l.isTypedArray(b)?typeof Blob=="function"?new Blob([b]):Buffer.from(b):b}return function b(A,j){if(l.isPlainObject(A)||l.isArray(A)){if(p.indexOf(A)!==-1)throw Error("Circular reference detected in "+j);p.push(A),l.forEach(A,function(H,z){if(!l.isUndefined(H)){var $,Vt=j?j+"."+z:z;if(H&&!j&&typeof H=="object"){if(l.endsWith(z,"{}"))H=JSON.stringify(H);else if(l.endsWith(z,"[]")&&($=l.toArray(H)))return void $.forEach(function(_r){!l.isUndefined(_r)&&o.append(Vt,g(_r))})}b(H,Vt)}}),p.pop()}else o.append(j,g(A))}(i),o},ZL}function H$(){if(gG)return mG;gG=1;var l=WI();return mG=function(i,o,p){var g=p.config.validateStatus;p.status&&g&&!g(p.status)?o(new l("Request failed with status code "+p.status,[l.ERR_BAD_REQUEST,l.ERR_BAD_RESPONSE][Math.floor(p.status/100)-4],p.config,p.request,p)):i(p)}}function z$(){if(EG)return _x;EG=1;var l=tS;return _x=l.isStandardBrowserEnv()?{write:function(i,o,p,g,b,A){var j=[];j.push(i+"="+encodeURIComponent(o)),l.isNumber(p)&&j.push("expires="+new Date(p).toGMTString()),l.isString(g)&&j.push("path="+g),l.isString(b)&&j.push("domain="+b),A===!0&&j.push("secure"),document.cookie=j.join("; ")},read:function(i){var o=document.cookie.match(new RegExp("(^|;\\s*)("+i+")=([^;]*)"));return o?decodeURIComponent(o[3]):null},remove:function(i){this.write(i,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},_x}var tM,yG,bG,SG,TG,RG,CG,IG,eM,wG,AG,OG,K$=function(l){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(l)},Y$=function(l,i){return i?l.replace(/\/+$/,"")+"/"+i.replace(/^\/+/,""):l},NG=function(l,i){return l&&!K$(i)?Y$(l,i):i};function J$(){if(yG)return tM;yG=1;var l=tS,i=["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"];return tM=function(o){var p,g,b,A={};return o&&l.forEach(o.split(` +`),function(j){if(b=j.indexOf(":"),p=l.trim(j.substr(0,b)).toLowerCase(),g=l.trim(j.substr(b+1)),p){if(A[p]&&i.indexOf(p)>=0)return;A[p]=p==="set-cookie"?(A[p]?A[p]:[]).concat([g]):A[p]?A[p]+", "+g:g}}),A},tM}function X$(){if(SG)return bG;SG=1;var l=tS;return bG=l.isStandardBrowserEnv()?function(){var i,o=/(msie|trident)/i.test(navigator.userAgent),p=document.createElement("a");function g(b){var A=b;return o&&(p.setAttribute("href",A),A=p.href),p.setAttribute("href",A),{href:p.href,protocol:p.protocol?p.protocol.replace(/:$/,""):"",host:p.host,search:p.search?p.search.replace(/^\?/,""):"",hash:p.hash?p.hash.replace(/^#/,""):"",hostname:p.hostname,port:p.port,pathname:p.pathname.charAt(0)==="/"?p.pathname:"/"+p.pathname}}return i=g(window.location.href),function(b){var A=l.isString(b)?g(b):b;return A.protocol===i.protocol&&A.host===i.host}}():function(){return!0}}function _N(){if(RG)return TG;RG=1;var l=WI();function i(o){l.call(this,o??"canceled",l.ERR_CANCELED),this.name="CanceledError"}return tS.inherits(i,l,{__CANCEL__:!0}),TG=i}function Q$(){return IG||(IG=1,CG=function(l){var i=/^([-+\w]{1,25})(:?\/\/|:)/.exec(l);return i&&i[1]||""}),CG}function $$(){if(wG)return eM;wG=1;var l=tS,i=H$(),o=z$(),p=dG,g=NG,b=J$(),A=X$(),j=vG,H=WI(),z=_N(),$=Q$();return eM=function(Vt){return new Promise(function(_r,Fi){var _l,_u=Vt.data,_h=Vt.headers,_g=Vt.responseType;function eE(){Vt.cancelToken&&Vt.cancelToken.unsubscribe(_l),Vt.signal&&Vt.signal.removeEventListener("abort",_l)}l.isFormData(_u)&&l.isStandardBrowserEnv()&&delete _h["Content-Type"];var oE=new XMLHttpRequest;if(Vt.auth){var SE=Vt.auth.username||"",vE=Vt.auth.password?unescape(encodeURIComponent(Vt.auth.password)):"";_h.Authorization="Basic "+btoa(SE+":"+vE)}var fE=g(Vt.baseURL,Vt.url);function mE(){if(oE){var OE="getAllResponseHeaders"in oE?b(oE.getAllResponseHeaders()):null,$E={data:_g&&_g!=="text"&&_g!=="json"?oE.response:oE.responseText,status:oE.status,statusText:oE.statusText,headers:OE,config:Vt,request:oE};i(function(s_){_r(s_),eE()},function(s_){Fi(s_),eE()},$E),oE=null}}if(oE.open(Vt.method.toUpperCase(),p(fE,Vt.params,Vt.paramsSerializer),!0),oE.timeout=Vt.timeout,"onloadend"in oE?oE.onloadend=mE:oE.onreadystatechange=function(){oE&&oE.readyState===4&&(oE.status!==0||oE.responseURL&&oE.responseURL.indexOf("file:")===0)&&setTimeout(mE)},oE.onabort=function(){oE&&(Fi(new H("Request aborted",H.ECONNABORTED,Vt,oE)),oE=null)},oE.onerror=function(){Fi(new H("Network Error",H.ERR_NETWORK,Vt,oE,oE)),oE=null},oE.ontimeout=function(){var OE=Vt.timeout?"timeout of "+Vt.timeout+"ms exceeded":"timeout exceeded",$E=Vt.transitional||j;Vt.timeoutErrorMessage&&(OE=Vt.timeoutErrorMessage),Fi(new H(OE,$E.clarifyTimeoutError?H.ETIMEDOUT:H.ECONNABORTED,Vt,oE)),oE=null},l.isStandardBrowserEnv()){var EE=(Vt.withCredentials||A(fE))&&Vt.xsrfCookieName?o.read(Vt.xsrfCookieName):void 0;EE&&(_h[Vt.xsrfHeaderName]=EE)}"setRequestHeader"in oE&&l.forEach(_h,function(OE,$E){_u===void 0&&$E.toLowerCase()==="content-type"?delete _h[$E]:oE.setRequestHeader($E,OE)}),l.isUndefined(Vt.withCredentials)||(oE.withCredentials=!!Vt.withCredentials),_g&&_g!=="json"&&(oE.responseType=Vt.responseType),typeof Vt.onDownloadProgress=="function"&&oE.addEventListener("progress",Vt.onDownloadProgress),typeof Vt.onUploadProgress=="function"&&oE.upload&&oE.upload.addEventListener("progress",Vt.onUploadProgress),(Vt.cancelToken||Vt.signal)&&(_l=function(OE){oE&&(Fi(!OE||OE&&OE.type?new z:OE),oE.abort(),oE=null)},Vt.cancelToken&&Vt.cancelToken.subscribe(_l),Vt.signal&&(Vt.signal.aborted?_l():Vt.signal.addEventListener("abort",_l))),_u||(_u=null);var PE=$(fE);PE&&["http","https","file"].indexOf(PE)===-1?Fi(new H("Unsupported protocol "+PE+":",H.ERR_BAD_REQUEST,Vt)):oE.send(_u)})},eM}var Q0=tS,PG=function(l,i){W$.forEach(l,function(o,p){p!==i&&p.toUpperCase()===i.toUpperCase()&&(l[i]=o,delete l[p])})},kG=WI(),Z$=vG,tZ=_G(),eZ={"Content-Type":"application/x-www-form-urlencoded"};function DG(l,i){!Q0.isUndefined(l)&&Q0.isUndefined(l["Content-Type"])&&(l["Content-Type"]=i)}var LG,yN={transitional:Z$,adapter:((typeof XMLHttpRequest<"u"||typeof process<"u"&&Object.prototype.toString.call(process)==="[object process]")&&(LG=$$()),LG),transformRequest:[function(l,i){if(PG(i,"Accept"),PG(i,"Content-Type"),Q0.isFormData(l)||Q0.isArrayBuffer(l)||Q0.isBuffer(l)||Q0.isStream(l)||Q0.isFile(l)||Q0.isBlob(l))return l;if(Q0.isArrayBufferView(l))return l.buffer;if(Q0.isURLSearchParams(l))return DG(i,"application/x-www-form-urlencoded;charset=utf-8"),l.toString();var o,p=Q0.isObject(l),g=i&&i["Content-Type"];if((o=Q0.isFileList(l))||p&&g==="multipart/form-data"){var b=this.env&&this.env.FormData;return tZ(o?{"files[]":l}:l,b&&new b)}return p||g==="application/json"?(DG(i,"application/json"),function(A,j,H){if(Q0.isString(A))try{return(j||JSON.parse)(A),Q0.trim(A)}catch(z){if(z.name!=="SyntaxError")throw z}return(H||JSON.stringify)(A)}(l)):l}],transformResponse:[function(l){var i=this.transitional||yN.transitional,o=i&&i.silentJSONParsing,p=i&&i.forcedJSONParsing,g=!o&&this.responseType==="json";if(g||p&&Q0.isString(l)&&l.length)try{return JSON.parse(l)}catch(b){if(g)throw b.name==="SyntaxError"?kG.from(b,kG.ERR_BAD_RESPONSE,this,null,this.response):b}return l}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:OG?AG:(OG=1,AG=null)},validateStatus:function(l){return l>=200&&l<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};Q0.forEach(["delete","get","head"],function(l){yN.headers[l]={}}),Q0.forEach(["post","put","patch"],function(l){yN.headers[l]=Q0.merge(eZ)});var xG,MG,nM=yN,nZ=tS,rZ=nM;function UG(){return MG?xG:(MG=1,xG=function(l){return!(!l||!l.__CANCEL__)})}var FG=tS,rM=function(l,i,o){var p=this||rZ;return nZ.forEach(o,function(g){l=g.call(p,l,i)}),l},iZ=UG(),sZ=nM,oZ=_N();function iM(l){if(l.cancelToken&&l.cancelToken.throwIfRequested(),l.signal&&l.signal.aborted)throw new oZ}var jG,VG,GS=tS,BG=function(l,i){i=i||{};var o={};function p(z,$){return GS.isPlainObject(z)&&GS.isPlainObject($)?GS.merge(z,$):GS.isPlainObject($)?GS.merge({},$):GS.isArray($)?$.slice():$}function g(z){return GS.isUndefined(i[z])?GS.isUndefined(l[z])?void 0:p(void 0,l[z]):p(l[z],i[z])}function b(z){if(!GS.isUndefined(i[z]))return p(void 0,i[z])}function A(z){return GS.isUndefined(i[z])?GS.isUndefined(l[z])?void 0:p(void 0,l[z]):p(void 0,i[z])}function j(z){return z in i?p(l[z],i[z]):z in l?p(void 0,l[z]):void 0}var H={url:b,method:b,data:b,baseURL:A,transformRequest:A,transformResponse:A,paramsSerializer:A,timeout:A,timeoutMessage:A,withCredentials:A,adapter:A,responseType:A,xsrfCookieName:A,xsrfHeaderName:A,onUploadProgress:A,onDownloadProgress:A,decompress:A,maxContentLength:A,maxBodyLength:A,beforeRedirect:A,transport:A,httpAgent:A,httpsAgent:A,cancelToken:A,socketPath:A,responseEncoding:A,validateStatus:j};return GS.forEach(Object.keys(l).concat(Object.keys(i)),function(z){var $=H[z]||g,Vt=$(z);GS.isUndefined(Vt)&&$!==j||(o[z]=Vt)}),o};function GG(){return VG?jG:(VG=1,jG={version:"0.27.2"})}var aZ=GG().version,hR=WI(),sM={};["object","boolean","number","function","string","symbol"].forEach(function(l,i){sM[l]=function(o){return typeof o===l||"a"+(i<1?"n ":" ")+l}});var qG={};sM.transitional=function(l,i,o){function p(g,b){return"[Axios v"+aZ+"] Transitional option '"+g+"'"+b+(o?". "+o:"")}return function(g,b,A){if(l===!1)throw new hR(p(b," has been removed"+(i?" in "+i:"")),hR.ERR_DEPRECATED);return i&&!qG[b]&&(qG[b]=!0,console.warn(p(b," has been deprecated since v"+i+" and will be removed in the near future"))),!l||l(g,b,A)}};var WG,HG,zG,KG,YG,JG,cZ={assertOptions:function(l,i,o){if(typeof l!="object")throw new hR("options must be an object",hR.ERR_BAD_OPTION_VALUE);for(var p=Object.keys(l),g=p.length;g-- >0;){var b=p[g],A=i[b];if(A){var j=l[b],H=j===void 0||A(j,b,l);if(H!==!0)throw new hR("option "+b+" must be "+H,hR.ERR_BAD_OPTION_VALUE)}else if(o!==!0)throw new hR("Unknown option "+b,hR.ERR_BAD_OPTION)}},validators:sM},XG=tS,uZ=dG,QG=q$,$G=function(l){return iM(l),l.headers=l.headers||{},l.data=rM.call(l,l.data,l.headers,l.transformRequest),l.headers=FG.merge(l.headers.common||{},l.headers[l.method]||{},l.headers),FG.forEach(["delete","get","head","post","put","patch","common"],function(i){delete l.headers[i]}),(l.adapter||sZ.adapter)(l).then(function(i){return iM(l),i.data=rM.call(l,i.data,i.headers,l.transformResponse),i},function(i){return iZ(i)||(iM(l),i&&i.response&&(i.response.data=rM.call(l,i.response.data,i.response.headers,l.transformResponse))),Promise.reject(i)})},bN=BG,lZ=NG,ZG=cZ,HI=ZG.validators;function zI(l){this.defaults=l,this.interceptors={request:new QG,response:new QG}}zI.prototype.request=function(l,i){typeof l=="string"?(i=i||{}).url=l:i=l||{},(i=bN(this.defaults,i)).method?i.method=i.method.toLowerCase():this.defaults.method?i.method=this.defaults.method.toLowerCase():i.method="get";var o=i.transitional;o!==void 0&&ZG.assertOptions(o,{silentJSONParsing:HI.transitional(HI.boolean),forcedJSONParsing:HI.transitional(HI.boolean),clarifyTimeoutError:HI.transitional(HI.boolean)},!1);var p=[],g=!0;this.interceptors.request.forEach(function(Vt){typeof Vt.runWhen=="function"&&Vt.runWhen(i)===!1||(g=g&&Vt.synchronous,p.unshift(Vt.fulfilled,Vt.rejected))});var b,A=[];if(this.interceptors.response.forEach(function(Vt){A.push(Vt.fulfilled,Vt.rejected)}),!g){var j=[$G,void 0];for(Array.prototype.unshift.apply(j,p),j=j.concat(A),b=Promise.resolve(i);j.length;)b=b.then(j.shift(),j.shift());return b}for(var H=i;p.length;){var z=p.shift(),$=p.shift();try{H=z(H)}catch(Vt){$(Vt);break}}try{b=$G(H)}catch(Vt){return Promise.reject(Vt)}for(;A.length;)b=b.then(A.shift(),A.shift());return b},zI.prototype.getUri=function(l){l=bN(this.defaults,l);var i=lZ(l.baseURL,l.url);return uZ(i,l.params,l.paramsSerializer)},XG.forEach(["delete","get","head","options"],function(l){zI.prototype[l]=function(i,o){return this.request(bN(o||{},{method:l,url:i,data:(o||{}).data}))}}),XG.forEach(["post","put","patch"],function(l){function i(o){return function(p,g,b){return this.request(bN(b||{},{method:l,headers:o?{"Content-Type":"multipart/form-data"}:{},url:p,data:g}))}}zI.prototype[l]=i(),zI.prototype[l+"Form"]=i(!0)});var t6=tS,dZ=aG,SN=zI,hZ=BG,IS=function l(i){var o=new SN(i),p=dZ(SN.prototype.request,o);return t6.extend(p,SN.prototype,o),t6.extend(p,o),p.create=function(g){return l(hZ(i,g))},p}(nM);IS.Axios=SN,IS.CanceledError=_N(),IS.CancelToken=function(){if(HG)return WG;HG=1;var l=_N();function i(o){if(typeof o!="function")throw new TypeError("executor must be a function.");var p;this.promise=new Promise(function(b){p=b});var g=this;this.promise.then(function(b){if(g._listeners){var A,j=g._listeners.length;for(A=0;A{i.responseType=i.responseType||"json",i.data&&!o?(i.data=JSON.stringify(i.data),RN+=AT(i.data)):o&&(i.data.size?RN+=i.data.size:i.data instanceof FormData?RN+=nG(i.data):RN+=AT(JSON.stringify(i.data))),i.headers=i.headers||{},i.headers["Content-Type"]=i.headers["Content-Type"]||"application/json",i.method="POST",i.url=l,aS.request(i).then(A=>{typeof A.data=="string"?oM+=AT(A.data):A.data instanceof ArrayBuffer||A.data instanceof Uint8Array?oM+=A.data.byteLength:oM+=AT(JSON.stringify(A.data)),p&&g({data:A.data,headers:A.headers}),g(A.data)}).catch(A=>{aS.isCancel(A)?b(new yE(_p.OPERATION_ABORTED,"cancel token canceled")):A.code==="ECONNABORTED"?b(new yE(_p.NETWORK_TIMEOUT,A.message)):A.response?b(new yE(_p.NETWORK_RESPONSE_ERROR,A.response.status)):b(new yE(_p.NETWORK_ERROR,A.message))})})}async function pZ(l,i){const o=new Blob([i.data],{type:"buffer"});return await aM(l,n6(n6({},i),{},{data:o,headers:{"Content-Type":"application/octet-stream"}}),!0)}const fZ=()=>(TN||TN||(TN=(window.location.protocol.split(":")[0]||"").toUpperCase(),TN))==="HTTPS",r6=()=>window.isSecureContext!==void 0;function i6(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function BE(l){for(var i=1;iA.trackId===p.metric.trackId);return b!==-1?(g[b]=BE(BE({},g[b]),p.metric),BE(BE({},o),{},{keyMetrics:BE(BE({},o.keyMetrics),{},{publish:[...g]})})):BE(BE({},o),{},{keyMetrics:BE(BE({},o.keyMetrics),{},{publish:[...o.keyMetrics.publish,p.metric]})})}case r_.KEY_METRIC_SUBSCRIBE:{const g=o.keyMetrics.subscribe,b=g.findIndex(A=>A.userId===p.metric.userId&&A.type===p.metric.type);return b!==-1?(g[b]=BE(BE({},g[b]),p.metric),BE(BE({},o),{},{keyMetrics:BE(BE({},o.keyMetrics),{},{subscribe:[...g]})})):BE(BE({},o),{},{keyMetrics:BE(BE({},o.keyMetrics),{},{subscribe:[...o.keyMetrics.subscribe,p.metric]})})}case r_.SET_CLOUD_PROXY_SERVER_MODE:return o.cloudProxyServerMode=p.mode,o;case r_.RECORD_JOIN_CHANNEL_SERVICE:return typeof p.index!="number"?o.joinChannelServiceRecords=[...o.joinChannelServiceRecords,p.record]:(o.joinChannelServiceRecords[p.index]=BE(BE({},o.joinChannelServiceRecords[p.index]),p.record),o.joinChannelServiceRecords=[...o.joinChannelServiceRecords]),o;case r_.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return o.joinChannelServiceRecords=[],o;case r_.RESET_KEY_METRICS:return o.keyMetrics={publish:[],subscribe:[]},o;case r_.SET_USE_DATACHANNEL:return BE(BE({},o),{},{useDataChannel:p.val});case r_.SET_USE_P2P:return BE(BE({},o),{},{useP2P:p.val});default:return o}}(this.state,i)}set sessionId(i){this.dispatch({type:r_.SET_SESSION_ID,sessionId:i})}get sessionId(){return this.state.sessionId}set codec(i){this.state.codec=i}get codec(){return this.state.codec}get audioCodec(){return this.state.audioCodec}get clientId(){return this.state.clientId}set p2pId(i){this.dispatch({type:r_.SET_P2P_ID,p2pId:i})}get p2pId(){return this.state.p2pId}set dcId(i){this.dispatch({type:r_.SET_DC_ID,dcId:i})}get dcId(){return this.state.dcId}set uid(i){this.dispatch({type:r_.SET_UID,uid:i})}get uid(){return this.state.uid}set pubId(i){this.dispatch({type:r_.SET_PUB_ID,pubId:i})}get pubId(){return this.state.pubId}set cloudProxyServerMode(i){this.dispatch({type:r_.SET_CLOUD_PROXY_SERVER_MODE,mode:i})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useDataChannel(i){this.dispatch({type:r_.SET_USE_DATACHANNEL,val:i})}get useDataChannel(){return this.state.useDataChannel}set useP2P(i){this.dispatch({type:r_.SET_USE_P2P,val:i})}get useP2P(){return this.state.useP2P}clientCreated(){this.dispatch({type:r_.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:r_.KEY_METRIC_JOIN_START,metric:Date.now()})}joinEnd(){this.dispatch({type:r_.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:r_.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:r_.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:r_.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:r_.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:r_.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:r_.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}descriptionStart(){this.dispatch({type:r_.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:r_.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:r_.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(i,o,p,g){this.dispatch({type:r_.KEY_METRIC_PUBLISH,metric:BE(BE({trackId:i,type:o},p&&{publishStart:p}),g&&{publishEnd:g})})}subscribe(i,o,p,g,b,A,j){this.dispatch({type:r_.KEY_METRIC_SUBSCRIBE,metric:BE(BE(BE(BE(BE({userId:i,type:o},p&&{subscribeStart:p}),g&&{subscribeEnd:g}),b&&{firstFrame:b}),A&&{streamAdded:A}),j&&{firstDecoded:j})})}massSubscribe(i,o,p,g){i.forEach(b=>{this.dispatch({type:r_.KEY_METRIC_SUBSCRIBE,metric:BE(BE(BE({userId:b.userId,type:b.type},o&&{subscribeStart:o}),p&&{subscribeEnd:p}),g&&{firstFrame:g})})})}get keyMetrics(){return this.state.keyMetrics}recordJoinChannelService(i,o){i.service==="gateway"&&Array.isArray(i.urls)&&(i.urls=i.urls.map(p=>p.replace(/(\d+)-\d+-\d+-(\d+)/,"$1-*-*-$2")));try{return typeof o!="number"?(this.dispatch({type:r_.RECORD_JOIN_CHANNEL_SERVICE,record:BE(BE({},i),{},{sessionId:this.sessionId,cloudProxyMode:this.cloudProxyServerMode,uid:this.uid})}),this.state.joinChannelServiceRecords.length-1):(o<0||o>=this.state.joinChannelServiceRecords.length||this.dispatch({type:r_.RECORD_JOIN_CHANNEL_SERVICE,record:i,index:o}),o)}catch{return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:r_.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:r_.RESET_KEY_METRICS})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch{return[]}}get avoidJoinStart(){return this.state.avoidJoinStart}set avoidJoinStart(i){this.dispatch({type:r_.AVOID_JOIN_START,avoidJoinStart:i})}}const qS=function(l){if(l.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return l;const i=l.match(/([0-9]+\.[0-9]+\.[0-9]+)\-alpha\.([0-9]+)/);if(i&&i[1]&&i[2]){const p=i[1],g=i[2];return"".concat(p,".").concat(g)}const o=l.match(/([0-9]+\.[0-9]+\.[0-9]+)\-special\.([0-9]+)/);if(o&&o[1]&&o[2]){const p=o[1],g=o[2];return"".concat(p,".").concat(100*(Number(g)+1))}return"4.0.0.999"}("4.19.3"),cM=function(){try{return JSON.parse("true")===!0}catch{return!0}}(),uM="v4.19.3-0-gb2ca8ca7(11/2/2023, 2:57:33 PM)",$0={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"],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",ENABLE_EVENT_REPORT:!0,GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,UPLOAD_LOG:!1,NOT_REPORT_EVENT:[],SUBSCRIBE_TWCC:!1,PUBLISH_TWCC:!1,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,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"],WORKER_DOMAIN:"edge.agora.io",TURN_DOMAIN:"edge.agora.io",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AUDIO_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,PRELOAD_MEDIA_COUNT:0,USE_PUB_RTX:!1,USE_SUB_RTX:!1,CHECK_VIDEO_VISIBLE_INTERVAL:3e4,CHECK_LOCAL_STATS_INTERVAL:100,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:!0,BITRATE_ADAPTER_TYPE:"STANDARD_BITRATE",AI_DENOISER_PARAMETERS:{},ADJUST_3A_FROM_PLUGINS:!0,RAISE_H264_BASELINE_PRIORITY:!0,FILTER_SEND_H264_BASELINE:!1,ENABLE_PUBLISHED_USER_LIST:!0,MAX_SUBSCRIPTION:50,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_PORT:"",SHOW_VIDEO_INSPECT_WORKER_MESSAGE:!1,STATS_COLLECTOR_PORT:443,FORCE_TURN_TCP:!1,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,DISABLE_FEC:void 0,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,ICE_RESTART_INTERVAL:1e4,NEW_ICE_RESTART:!1,ENABLE_USER_LICENSE_CHECK:!0,SIGNAL_CHANNEL:0,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,FINGERPRINT:null,DC_JOIN_WITH_FAILBACK:5e3,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,AP_AREA:!0,SVC:[],ENABLE_ENCODED_TRANSFORM:!1,IMAGE_MODERATION_WORKER_HOST:"edge.agora.io",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,RTM2_FLAG:void 0,AP_RTM:!1,ENABLE_DATASTREAM_2:!1,DATASTREAM_MAX_RETRANSMITS:10,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,ENABLE_INSTANT_VIDEO:!1,ENABLE_NTP_REPORT:!1,USE_XR:!1,TCP_CANDIDATE_ONLY:!1,EXTERNAL_SIGNAL_REQUEST_TIMEOUT:1e4,P2P:!1,SHOW_P2P_LOG:!1,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:[]};function y_(l,i,o){var p,g;VE(p=Object.keys($0)).call(p,l)&&(!o&&VE(g=Object.keys(pR)).call(g,l)||($0[l]=i))}function nE(l){return $0[l]}const pR={};var eI,s6;(function(l){l.h264="h264",l.h265="h265",l.vp8="vp8",l.vp9="vp9",l.av1="av1"})(eI||(eI={})),function(l){l.opus="opus",l.pcma="pcma",l.pcmu="pcmu",l.g722="g722"}(s6||(s6={}));const CN=new class extends D_{reportLogUploadError(l){this.emit("REPORT_LOG_UPLOAD",l)}};class gZ{constructor(i){_e(this,"logger",void 0),_e(this,"prefixLists",[]),this.logger=i}debug(){for(var i=arguments.length,o=new Array(i),p=0;p{for(const i in WS)if(Object.prototype.hasOwnProperty.call(WS,i)&&WS[i]===l)return i;return"DEFAULT"},Gi=new class{constructor(){_e(this,"proxyServerURL",void 0),_e(this,"logLevel",WS.DEBUG),_e(this,"uploadState","collecting"),_e(this,"uploadLogWaitingList",[]),_e(this,"uploadLogUploadingList",[]),_e(this,"uploadErrorCount",0),_e(this,"currentLogID",0),_e(this,"url",void 0),_e(this,"extLog",(l,i)=>{this.appendLogToWaitingList(l,...i)})}debug(){for(var l=arguments.length,i=new Array(l),o=0;o{this.log(...i)},Date.now()-IN);const p=Math.max(0,Math.min(4,i[0]));if(i[0]=lM()+" Agora-SDK [".concat(BO(p),"]:"),this.appendLogToWaitingList(p,...i),p{this.uploadLog(...i)},Date.now()-IN);const p=Math.max(0,Math.min(4,i[0]));i[0]=lM()+" Agora-SDK [".concat(BO(p),"]:"),this.appendLogToWaitingList(p,...i)}appendLogToWaitingList(l){if(!nE("UPLOAD_LOG"))return;for(var i=arguments.length,o=new Array(i>1?i-1:0),p=1;p{typeof b=="object"&&(b=JSON.stringify(b)),g+="".concat(b," ")}),this.uploadLogWaitingList.push({payload_str:g,log_level:l,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 l=this.uploadLogUploadingList,i={sdk_version:qS,process_id:nE("PROCESS_ID"),payload:JSON.stringify(l)};return vT(async()=>{const o=await aS.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(nE("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(nE("LOG_UPLOAD_SERVER"),"/upload/v1")),i,{responseType:"text"});if(o.data!=="OK"){const p=new Error("unexpected upload log response");throw p.response=o,p}},()=>(this.uploadLogUploadingList=[],!1),o=>(o.response?CN.reportLogUploadError({status:o.response.status,data:o.response.data,headers:o.response.headers,message:o.message}):o.request?CN.reportLogUploadError({status:o.request.status,message:o.message}):CN.reportLogUploadError({status:-1,message:o.message}),!0),{timeout:nE("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:nE("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,nE("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then(()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout(()=>this.uploadLogInterval(),nE("UPLOAD_LOG_INTERVAL"))}).catch(l=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout(()=>this.uploadLogInterval(),nE("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout(()=>this.uploadLogInterval(),nE("UPLOAD_LOG_RETRY_INTERVAL_V1"))}))}};var a6,c6;function EZ(l){return O0(l.reportId,"params.reportId",0,100,!1),O0(l.category,"params.category",0,100,!1),O0(l.event,"params.event",0,100,!1),O0(l.label,"params.label",0,100,!1),b_(l.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}(function(l){l.FREE="free",l.UPLOADING="uploading"})(a6||(a6={})),function(l){l[l.MISC=0]="MISC",l[l.INTERNAL_EVENT=1]="INTERNAL_EVENT",l[l.PUBLIC_EVENT=2]="PUBLIC_EVENT",l[l.WEB_EVENT=3]="WEB_EVENT",l[l.INTERNAL_API=4]="INTERNAL_API",l[l.WEB_API=5]="WEB_API",l[l.PUBLIC_API=6]="PUBLIC_API"}(c6||(c6={}));const vZ={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};var p0,L_,u6,l6;function d6(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function _v(l){for(var i=1;i{for(const o of i){const p=_v(_v({},o),{},{sid:null,invokeId:++this.apiInvokeCount,tag:x_.TRACER});this.sendApiInvoke(p)}}),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),nE("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),nE("EVENT_REPORT_SEND_INTERVAL"))}getBaseInfoBySessionId(i){return this.baseInfoMap.get(i)}adjustSessionStartTime(i){if(!this.baseInfoMap.has(i)&&!this.baseInfoMap.get(i))return void Gi.error("adjust session ".concat(i," start time, sid is not exist or info is undefined"));const o=this.baseInfoMap.get(i),p=Date.now(),g=o.startTime;o.startTime=p,Gi.debug("rewrite session ".concat(i," startTime: ").concat(p," , ").concat(p-g,"ms")),this.baseInfoMap.set(i,o)}setAppId(i){this._appId=i}reportApiInvoke(i,o,p){o.timeout=o.timeout||6e4,o.reportResult=o.reportResult===void 0||o.reportResult;const g=Date.now();this.apiInvokeCount+=1;const b=this.apiInvokeCount,A=()=>({tag:o.tag,invokeId:b,sid:i,name:o.name,apiInvokeTime:g,options:o.options,states:o.states||null}),j=!!nE("SHOW_REPORT_INVOKER_LOG");j&&Gi.info("".concat(o.name," start"),o.options);let H=!1;w0(o.timeout).then(()=>{H||(this.sendApiInvoke(_v(_v({},A()),{},{error:_p.API_INVOKE_TIMEOUT,success:!1})),Gi.debug("".concat(o.name," timeout")))});const z=new yE(_p.UNEXPECTED_ERROR,"".concat(o.name,": this api invoke is end"));return{onSuccess:$=>{const Vt=()=>{if(H)throw z;return H=!0,this.sendApiInvoke(_v(_v({},A()),{},{success:!0},o.reportResult&&{result:$})),j&&Gi.info("".concat(o.name," onSuccess")),$};return p?iG(Vt,o.name+"Success",p,()=>H=!0):Vt()},onError:$=>{const Vt=()=>{if(H)throw $;H=!0,this.sendApiInvoke(_v(_v({},A()),{},{success:!1,error:$})),j&&Gi.info("".concat(o.name," onFailure"),$.toString())};return p?iG(Vt,o.name+"Error",p,()=>H=!0):Vt()}}}sessionInit(i,o){if(this.baseInfoMap.has(i))return;const p=Date.now(),g=this.createBaseInfo(i,p);g.cname=o.cname;const b=Object.assign({},{willUploadConsoleLog:nE("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:cM?"global":"oversea",areas:nE("AREAS")&&nE("AREAS").join(",")},o.extend),A=Date.now(),j=_v(_v({},g),{},{eventType:p0.SESSION_INIT,appid:o.appid,browser:navigator.userAgent,build:uM,lts:A,elapse:A-p,extend:JSON.stringify(b),mode:o.mode,process:nE("PROCESS_ID"),appType:nE("APP_TYPE"),success:!0,version:qS});this.send({type:L_.SESSION,data:j},!0)}joinChooseServer(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=p.info,b=Date.now(),A=_v(_v({},g),{},{eventType:p0.JOIN_CHOOSE_SERVER,lts:b,eventElapse:b-o.lts,chooseServerAddr:o.csAddr,errorCode:o.ec,elapse:b-p.startTime,success:o.succ,chooseServerAddrList:JSON.stringify(o.serverList),uid:o.uid?parseInt(o.uid):null,cid:o.cid?parseInt(o.cid):null,chooseServerIp:o.csIp||"",opid:o.opid,unilbsServerIds:o.unilbsServerIds,extend:o.extend||void 0,isHttp3:o.isHttp3});this.send({type:L_.JOIN_CHOOSE_SERVER,data:A},!0)}reqUserAccount(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=p.info,b=Date.now(),A=_v(_v({},g),{},{eventType:p0.REQ_USER_ACCOUNT,lts:b,success:o.success,serverAddress:o.serverAddr,stringUid:o.stringUid,uid:o.uid,errorCode:o.errorCode,elapse:b-p.startTime,eventElapse:b-o.lts,extend:JSON.stringify(o.extend)});this.send({type:L_.REQ_USER_ACCOUNT,data:A},!0)}joinGateway(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=p.info;o.vid&&(g.vid=o.vid),g.uid=o.uid,g.cid=o.cid;const b=Date.now(),{firstSuccess:A,avoidJoinStartTime:j,isProxy:H,addr:z}=o,$=b-(A&&j?j:p.startTime),Vt=_v(_v({},g),{},{eventType:p0.JOIN_GATEWAY,lts:b,gatewayAddr:o.addr,success:o.succ,errorCode:o.ec,elapse:$,eventElapse:b-o.lts,firstSuccess:A,signalChannel:o.signalChannel}),_r=Vt.success?1:0;if(o.succ&&(p.lastJoinSuccessTime=b),A)this.send({type:L_.JOIN_GATEWAY,data:Vt},!0);else{let Fi;if(z)if(H){const _u=z.match(/h=(\d{1,3}-){3}\d{1,3}/g),_h=z.match(/p=[0-9]{1,6}/g);Fi={isSuccess:_r,gatewayIp:_u&&_u.length?_u[0].split("=")[1].replace(/-/g,"."):"",port:_h&&_h.length?_h[0].split("=")[1]:"",isProxy:H?1:0}}else{const _u=z.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),_h=z.match(/(:|p=)[0-9]{1,6}/g);Fi={isSuccess:_r,gatewayIp:_u&&_u.length?_u[0].split("//")[1].replace(/-/g,"."):"",port:_h&&_h.length?_h[0].split(/:|p=/g)[1]:"",isProxy:H?1:0}}else Fi={isSuccess:_r,gatewayIp:"",port:"",isProxy:H?1:0};delete Vt.success,delete Vt.eventType,delete Vt.firstSuccess,Vt.vid=Number(Vt.vid);const _l=Object.assign({},Vt,Fi,{eventType:p0.REJOIN_GATEWAY});this.send({type:L_.RE_JOIN_GATEWAY,data:_l},!0)}}joinChannelTimeout(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=Date.now(),b=_v(_v({},p.info),{},{lts:g,timeout:o,elapse:g-p.startTime});this.send({type:L_.JOIN_CHANNEL_TIMEOUT,data:b},!0)}publish(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=p.info,b=Date.now(),A=_v(_v({},g),{},{eventType:p0.PUBLISH,lts:b,eventElapse:o.eventElapse,elapse:b-p.startTime,success:o.succ,errorCode:o.ec,videoName:o.videoName,audioName:o.audioName,screenName:o.screenName,screenshare:o.screenshare,audio:o.audio,video:o.video,p2pid:o.p2pid,publishRequestid:o.publishRequestid});this.send({type:L_.PUBLISH,data:A},!0)}subscribe(i,o,p){const g=this.baseInfoMap.get(i);if(!g)return;const b=g.info,A=Date.now(),j=_v(_v({},b),{},{eventType:p0.SUBSCRIBE,lts:A,eventElapse:o.eventElapse,elapse:A-g.startTime,success:o.succ,errorCode:o.ec,video:o.video,audio:o.audio,subscribeRequestid:o.subscribeRequestid,p2pid:o.p2pid},p&&{extend:JSON.stringify({isMassSubscribe:!0})});typeof o.peerid=="string"?j.peerSuid=o.peerid:j.peer=o.peerid,this.send({type:L_.SUBSCRIBE,data:j},!0)}wsCompressorInit(i){var o;const p=[...CS(o=this.baseInfoMap).call(o)],g=p.length?p[0]:"UnableToGetSid",b=this.baseInfoMap.get(g);if(!b)return;const A=b.info,j=Date.now(),H=_v(_v({},A),{},{eventType:p0.WS_COMPRESSOR_INIT,lts:j,eventElapse:i.eventElapse,elapse:j-b.startTime,status:i.status?1:2});this.send({type:L_.WS_COMPRESSOR_INIT,data:H},!0)}firstRemoteVideoDecode(i,o,p,g){const b=this.baseInfoMap.get(i);if(!b)return;const A=b.info,j=Date.now(),H=_v(_v(_v({},A),g),{},{elapse:j-b.startTime,eventType:o,lts:j,firstDecodeFrame:Math.max(j-b.startTime,0),apEnd:Math.max(g.apEnd-b.startTime,0),apStart:Math.max(g.apStart-b.startTime,0),joinGwEnd:Math.max(g.joinGwEnd-b.startTime,0),joinGwStart:Math.max(g.joinGwStart-b.startTime,0),pcEnd:Math.max(g.pcEnd-b.startTime,0),pcStart:Math.max(g.pcStart-b.startTime,0),subscriberEnd:Math.max(g.subscriberEnd-b.startTime,0),subscriberStart:Math.max(g.subscriberStart-b.startTime,0),videoAddNotify:Math.max(g.videoAddNotify-b.startTime,0)});this.send({type:p,data:H},!0)}firstRemoteFrame(i,o,p,g){const b=this.baseInfoMap.get(i);if(!b)return;const A=b.info,j=Date.now(),H=_v(_v(_v({},A),g),{},{elapse:j-b.startTime,eventType:o,lts:j});this.send({type:p,data:H},!0)}pcStats(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=p.info,b=Date.now(),A=_v(_v(_v({},g),o),{},{vid:g.vid===void 0?0:Number(g.vid),elapse:b-p.startTime,eventType:p0.PC_STATS,lts:b});this.send({type:L_.PC_STATS,data:A},!0)}updateRemoteRTPCapabilities(i,o){this.reportApiInvoke(i,{name:"Client.updateRemoteRTPCapabilities",options:o,tag:x_.TRACER}).onSuccess()}onGatewayStream(i,o,p,g){const b=this.baseInfoMap.get(i);if(!b)return;const A=b.info,j=Date.now(),H=_v(_v(_v({},A),g),{},{eventType:o,lts:j});this.send({type:p,data:H},!0)}streamSwitch(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=p.info,b=Date.now(),A=_v(_v({},g),{},{eventType:p0.STREAM_SWITCH,lts:b,isDual:o.isdual,elapse:b-p.startTime,success:o.succ});this.send({type:L_.STREAM_SWITCH,data:A},!0)}requestProxyAppCenter(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=p.info,b=Date.now(),A=_v(_v({},g),{},{eventType:p0.REQUEST_PROXY_APPCENTER,lts:b,eventElapse:b-o.lts,elapse:b-p.startTime,APAddr:o.APAddr,workerManagerList:o.workerManagerList,response:o.response,errorCode:o.ec,success:o.succ});this.send({type:L_.REQUEST_PROXY_APPCENTER,data:A},!0)}requestProxyWorkerManager(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=p.info,b=Date.now(),A=_v(_v({},g),{},{eventType:p0.REQUEST_PROXY_WORKER_MANAGER,lts:b,eventElapse:b-o.lts,elapse:b-p.startTime,workerManagerAddr:o.workerManagerAddr,response:o.response,errorCode:o.ec,success:o.succ});this.send({type:L_.REQUEST_PROXY_WORKER_MANAGER,data:A},!0)}setProxyServer(i){this.proxyServer=i,i?Gi.debug("reportProxyServerurl: ".concat(i)):Gi.debug("disable reportProxyServerurl: ".concat(i))}peerPublishStatus(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=p.info,b=Date.now(),A=_v(_v({},g),{},{subscribeElapse:o.subscribeElapse,peer:o.peer,peerPublishDuration:Math.max(o.audioPublishDuration,o.videoPublishDuration),audiotag:o.audioPublishDuration>0?1:-1,videotag:o.videoPublishDuration>0?1:-1,lts:b,elapse:b-p.startTime,joinChannelSuccessElapse:b-(p.lastJoinSuccessTime||b),peerPublishDurationVideo:o.videoPublishDuration,peerPublishDurationAudio:o.audioPublishDuration});this.send({type:L_.PEER_PUBLISH_STATUS,data:A},!0)}workerEvent(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=p.info,b=Date.now();(function(j,H,z){const $=j[H];if(!$||typeof $!="string")return[j];j[H]="";const Vt=AT(JSON.stringify(j));let _r=0;const Fi=[];let _l=0;for(let _u=0;_u<$.length;_u++)_l+=$.charCodeAt(_u)<=127?1:3,_l<=z-Vt||(Fi[Fi.length]=$R($R({},j),{},{[H]:$.substring(_r,_u)}),_r=_u,_l=$.charCodeAt(_u)<=127?1:3);return _r!==$.length-1&&(Fi[Fi.length]=$R($R({},j),{},{[H]:$.substring(_r)})),Fi})(_v(_v(_v({},g),o),{},{elapse:b-p.startTime,lts:b,productType:"WebRTC"}),"payload",1300).forEach(j=>this.send({type:L_.WORKER_EVENT,data:j},!0))}apworkerEvent(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=p.info,b=Date.now(),A=_v(_v(_v({},g),o),{},{elapse:b-p.startTime,lts:b});this.send({type:L_.AP_WORKER_EVENT,data:A},!0)}joinWebProxyAP(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=p.info,b=Date.now(),A=_v(_v(_v({},g),o),{},{elapse:b-p.startTime,lts:b,extend:o.extend||void 0});this.send({type:L_.JOIN_WEB_PROXY_AP,data:A},!0)}WebSocketQuit(i,o){const p=this.baseInfoMap.get(i);if(!p)return;const g=p.info,b=Date.now(),A=_v(_v(_v({},g),o),{},{elapse:b-p.startTime,lts:b});this.send({type:L_.WEBSOCKET_QUIT,data:A},!0)}async sendCustomReportMessage(i,o){if(this.customReportCount+=o.length,this.customReportCount>nE("CUSTOM_REPORT_LIMIT"))throw new yE(_p.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval(()=>{this.customReportCount=0},5e3));const p=Date.now(),g=o.map(b=>({type:L_.USER_ANALYTICS,data:_v(_v({sid:i},b),{},{lts:p})}));try{nE("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(g):await this.postDataToStatsCollector(g)}catch(b){throw Gi.error("send custom report message failed",b.toString()),new yE(_p.CUSTOM_REPORT_SEND_FAILED,b.message)}}sendApiInvoke(i){const o=nE("NOT_REPORT_EVENT");if(i.tag&&VE(o)&&VE(o).call(o,i.tag))return!1;if(i.sid===null)return this.apiInvokeUploadPendingItems.push(i),!1;const p=this.baseInfoMap.get(i.sid);if(!p)return this.apiInvokeUploadPendingItems.push(i),!1;const{cname:g,uid:b,cid:A}=p.info;let j;if(i.lts=i.lts||Date.now(),i.error)if(i.error instanceof yE){const{code:z,message:$}=i.error;j=z||$||i.error.toString()}else j=i.error.toString();const H={invokeId:i.invokeId,sid:i.sid,cname:g,cid:A,uid:b,lts:i.lts,success:i.success,elapse:i.lts-p.startTime,execElapse:i.lts-i.apiInvokeTime,apiName:i.name,options:i.options?JSON.stringify(i.options):void 0,execStates:i.states?JSON.stringify(i.states):void 0,execResult:i.result?JSON.stringify(i.result):void 0,errorCode:i.error?j:void 0,errorMsg:i.error?JSON.stringify(i.error):void 0};return this.send({type:L_.API_INVOKE,data:H},!1),!0}appendSessionId(){GO.__CLIENT_LIST__.forEach(i=>{if(i._sessionId){const o=this.apiInvokeUploadPendingItems.length;for(let p=0;pnE("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(i,o){const p=[],g=[];for(;i.length;){const A=i.shift();p.length<20?p.push(A):g.push(A)}i.push(...g);for(const A of[...p]){var b;this.ltsList.indexOf(A.data.lts)!==-1?(A.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(A.data.lts)):(this.ltsList.push(A.data.lts),AO(b=this.ltsList).call(b,(j,H)=>j-H))}return o||(this.lastSendNormalEventTime=Date.now()),nE("ENABLE_EVENT_REPORT")&&p.length&&(nE("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(p):this.postDataToStatsCollector(p)).catch((A=>j=>{nE("EVENT_REPORT_RETRY")&&(o?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(A):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(A),this.normalEventUploadPendingItems.length>nE("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-nE("NORMAL_EVENT_QUEUE_CAPACITY")),Gi.warning("report: drop normal events"))))})(p)),i}async postDataToStatsCollector2(i){X_.networkState===K0.OFFLINE&&await pE.race([X_.onlineWaiter,w0(2*$_.maxRetryTimeout)]);const o=b=>{let A=new Uint8Array;return b.forEach(j=>{const H=FL(JSON.stringify(j.data)),z=new ArrayBuffer(5),$=(_r=>{let Fi=0;return Object.entries(L_).forEach(_l=>{let[_u,_h]=_l;_h===_r.type&&(Fi=EventNameToID[_u])}),Fi})(j),Vt=new DataView(z);Vt.setUint16(0,H.byteLength,!0),Vt.setUint8(2,255&$),Vt.setUint8(3,$>>>8&255),Vt.setUint8(4,$>>>16&255),A=XV(A,new Uint8Array(z)),A=XV(A,H)}),A},p="event";let g=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(nE("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(p):"https://".concat(nE("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(p);for(let b=0;b<2;b+=1){b===1&&(g=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(nE("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(p):"https://".concat(nE("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(p));try{await aM(g,{timeout:1e4,data:o(i),headers:_v(_v({biz:"webrtc",sendts:Math.round(Date.now()/1e3),debug:"false"},this._appId&&{appid:this._appId}),{},{"Content-Type":"application/octet-stream"})},!0)}catch(A){if(b===1)throw A;continue}return}}async postDataToStatsCollector(i){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const p={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:i.map(A=>JSON.stringify(A)),vid:(A=>{const j=A&&A.data.sid&&this.baseInfoMap.get(A.data.sid);return j&&j.info.vid&&+j.info.vid||0})(i[0])};X_.networkState===K0.OFFLINE&&await pE.race([X_.onlineWaiter,w0(2*$_.maxRetryTimeout)]);const g=o?"/events/proto-raws":"/events/messages";let b=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(nE("EVENT_REPORT_DOMAIN"),"&p=").concat(nE("STATS_COLLECTOR_PORT"),"&d=").concat(g):"https://".concat(nE("EVENT_REPORT_DOMAIN"),":").concat(nE("STATS_COLLECTOR_PORT")).concat(g));for(let A=0;A<2;A+=1){A===1&&(b=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(nE("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(nE("STATS_COLLECTOR_PORT"),"&d=").concat(g):"https://".concat(nE("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(nE("STATS_COLLECTOR_PORT")).concat(g)));try{o?await pZ(b,{timeout:1e4,data:p}):await aM(b,{timeout:1e4,data:p})}catch(j){if(A===1)throw j;continue}return}}createBaseInfo(i,o){const p=Object.assign({},vZ);return p.sid=i,this.baseInfoMap.set(i,{info:p,startTime:o}),p}reportResourceTiming(i,o){const p=performance.getEntriesByName(i),g=p[p.length-1];g&&this.reportApiInvoke(o,{name:"Client.resourceTiming",options:g,tag:x_.TRACER}).onSuccess()}}function HE(){let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function(i,o,p){const g=p.value;if(typeof g=="function"){const b=l.className||i.__className__||(i.constructor.name==="AgoraRTCClient"?"Client":i.constructor.name);p.value=function(){for(var A=arguments.length,j=new Array(A),H=0;H($.onSuccess(l.reportResult&&_r),_r)).catch(_r=>{throw $.onError(_r),_r}):($.onSuccess(l.reportResult&&Vt),Vt)}catch(Vt){throw $.onError(Vt),Vt}}}return p}}_e(GO,"__CLIENT_LIST__",[]);const jE=new GO;CN.on("REPORT_LOG_UPLOAD",l=>{l.networkState=X_.networkState,jE.reportApiInvoke(null,{name:"logUploadError",options:l,tag:x_.TRACER})});const _Z=["CHINA","GLOBAL"],wS=function(){const l="us".concat("erna","me"),i="pa".concat("sswo","rd"),o=["t","s","t"];o.splice(1,0,"e");const p=o.join(""),g=[];for(let j=0;j<6;j++)g.push("1");const b=g.join(""),A={};return A[l]=p,A[i]=b,Object.assign(A,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=wS,cM||($0.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],$0.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],$0.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],$0.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],$0.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],$0.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],$0.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",$0.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",$0.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",$0.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",$0.AREAS=["NORTH_AMERICA","OVERSEA"]);const h6=[[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]],fR=[];function nI(l,i){return!!i&&fR.some(o=>o.uid===l&&o.channelName===i)}GO.__CLIENT_LIST__=fR;var dM,cS,KI,qO,AS,F0,qE,t_,kE,FE,uS,JE,p6,YI,zE,o0,mR,yZ=WR("Array").values,bZ=HR,SZ=sS,TZ=mT,RZ=yZ,hM=Array.prototype,CZ={DOMTokenList:!0,NodeList:!0},OT=LE(function(l){var i=l.values;return l===hM||TZ(hM,l)&&i===hM.values||SZ(CZ,bZ(l))?RZ:i});function bE(l,i,o,p){var g,b=arguments.length,A=b<3?i:p===null?p=Object.getOwnPropertyDescriptor(i,o):p;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(l,i,o,p);else for(var j=l.length-1;j>=0;j--)(g=l[j])&&(A=(b<3?g(A):b>3?g(i,o,A):g(i,o))||A);return b>3&&A&&Object.defineProperty(i,o,A),A}function kc(l,i){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(l,i)}(function(l){l.L1T1="L1T1",l.L1T2="L1T2",l.L1T3="L1T3",l.L2T1_KEY="L2T1_KEY",l.L2T2_KEY="L2T2_KEY",l.L2T3_KEY="L2T3_KEY",l.L3T1_KEY="L3T1_KEY",l.L3T2_KEY="L3T2_KEY",l.L3T3_KEY="L3T3_KEY"})(dM||(dM={})),function(l){l.CERTIFICATE="certificate",l.CODEC="codec",l.CANDIDATE_PAIR="candidate-pair",l.LOCAL_CANDIDATE="local-candidate",l.REMOTE_CANDIDATE="remote-candidate",l.INBOUND="inbound-rtp",l.TRACK="track",l.OUTBOUND="outbound-rtp",l.PC="peer-connection",l.REMOTE_INBOUND="remote-inbound-rtp",l.REMOTE_OUTBOUND="remote-outbound-rtp",l.TRANSPORT="transport",l.CSRC="csrc",l.DATA_CHANNEL="data-channel",l.STREAM="stream",l.SENDER="sender",l.RECEIVER="receiver"}(cS||(cS={})),function(l){l[l.ACCESS_POINT=101]="ACCESS_POINT",l[l.UNILBS=201]="UNILBS",l[l.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR"}(KI||(KI={})),function(l){l[l.IIIEGAL_APPID=1]="IIIEGAL_APPID",l[l.IIIEGAL_UID=2]="IIIEGAL_UID",l[l.INTERNAL_ERROR=3]="INTERNAL_ERROR"}(qO||(qO={})),function(l){l[l.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",l[l.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",l[l.INTERNAL_ERROR=8]="INTERNAL_ERROR",l[l.NO_AUTHORIZED=9]="NO_AUTHORIZED",l[l.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",l[l.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",l[l.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",l[l.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",l[l.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",l[l.USER_OVERLOAD=16]="USER_OVERLOAD",l[l.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",l[l.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND"}(AS||(AS={})),function(l){l[l.NO_FLAG_SET=100]="NO_FLAG_SET",l[l.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",l[l.INVALID_FALG_SET=102]="INVALID_FALG_SET",l[l.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",l[l.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",l[l.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",l[l.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",l[l.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",l[l.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",l[l.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",l[l.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",l[l.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",l[l.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",l[l.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",l[l.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",l[l.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",l[l.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",l[l.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",l[l.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV"}(F0||(F0={})),function(l){l[l.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",l[l.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",l[l.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",l[l.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",l[l.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",l[l.K_TICKET_INVALID=7]="K_TICKET_INVALID",l[l.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",l[l.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",l[l.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",l[l.K_UID_BANNED=14]="K_UID_BANNED",l[l.K_IP_BANNED=15]="K_IP_BANNED",l[l.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",l[l.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",l[l.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",l[l.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",l[l.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",l[l.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",l[l.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",l[l.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",l[l.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",l[l.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",l[l.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",l[l.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",l[l.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",l[l.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",l[l.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",l[l.ERR_INVALID_UID=117]="ERR_INVALID_UID",l[l.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",l[l.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",l[l.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",l[l.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",l[l.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",l[l.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",l[l.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",l[l.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",l[l.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",l[l.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",l[l.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",l[l.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",l[l.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",l[l.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",l[l.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",l[l.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",l[l.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",l[l.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",l[l.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",l[l.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",l[l.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",l[l.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",l[l.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",l[l.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",l[l.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",l[l.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",l[l.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",l[l.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",l[l.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",l[l.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",l[l.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",l[l.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",l[l.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",l[l.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",l[l.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",l[l.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",l[l.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY"}(qE||(qE={})),function(l){l.CONNECTING="connecting",l.CONNECTED="connected",l.RECONNECTING="reconnecting",l.CLOSED="closed"}(t_||(t_={})),function(l){l.WS_CONNECTED="ws_connected",l.WS_RECONNECTING="ws_reconnecting",l.WS_CLOSED="ws_closed",l.WS_RECONNECT_WAITTING_FINISH="ws_reconnect_waitting_finish",l.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",l.ON_BINARY_DATA="on_binary_data",l.REQUEST_RECOVER="request_recover",l.REQUEST_JOIN_INFO="request_join_info",l.REQUEST_REJOIN_INFO="req_rejoin_info",l.IS_P2P_DISCONNECTED="is_p2p_dis",l.DISCONNECT_P2P="dis_p2p",l.ABORT_P2P_EXECUTION="abort_p2p_execution",l.NEED_RENEW_SESSION="need-sid",l.REPORT_JOIN_GATEWAY="report_join_gateway",l.REQUEST_TIMEOUT="request_timeout",l.REQUEST_SUCCESS="request_success",l.JOIN_RESPONSE="join_response",l.DATACHANNEL_PRECONNECT="datachannel_preconnect",l.DATACHANNEL_CONNECTING="datachannel_connecting",l.DATACHANNEL_FAILBACK="datachannel_failback",l.P2P_START="p2p_start",l.P2P_CONNECTION="p2p_connection",l.P2P_REMOTE_CANDIDATE_UPDATE="p2p_remote_candidate_update",l.P2P_SUBSCRIBE="p2p_subscribe",l.P2P_UNSUBSCRIBE="p2p_unsubscribe",l.P2P_EXCHANGE_SDP="p2p_exchange_sdp",l.P2P_ON_ADD_VIDEO_STREAM="p2p_on_add_video_stream",l.P2P_ON_ADD_AUDIO_STREAM="p2p_on_add_audio_stream"}(kE||(kE={})),function(l){l.PING="ping",l.PING_BACK="ping_back",l.JOIN="join_v3",l.REJOIN="rejoin_v3",l.LEAVE="leave",l.SET_CLIENT_ROLE="set_client_role",l.PUBLISH="publish",l.PUBLISH_DATASTREAM="publish_datastream",l.UNPUBLISH="unpublish",l.UNPUBLISH_DATASTREAM="unpublish_datastream",l.SUBSCRIBE="subscribe",l.SUBSCRIBE_DATASTREAM="subscribe_datastream",l.SUBSCRIBE_STREAMS="subscribe_streams",l.UNSUBSCRIBE="unsubscribe",l.UNSUBSCRIBE_DATASTREAM="unsubscribe_datastream",l.UNSUBSCRIBE_STREAMS="unsubscribe_streams",l.SUBSCRIBE_CHANGE="subscribe_change",l.TRAFFIC_STATS="traffic_stats",l.RENEW_TOKEN="renew_token",l.SWITCH_VIDEO_STREAM="switch_video_stream",l.DEFAULT_VIDEO_STREAM="default_video_stream",l.SET_FALLBACK_OPTION="set_fallback_option",l.GATEWAY_INFO="gateway_info",l.CONTROL="control",l.SEND_METADATA="send_metadata",l.DATA_STREAM="data_stream",l.PICK_SVC_LAYER="pick_svc_layer",l.RESTART_ICE="restart_ice",l.CONNECT_PC="connect_pc",l.SET_VIDEO_PROFILE="set_video_profile",l.SET_PARAMETER="set_parameter",l.SET_RTM2_FLAG="set_rtm2_flag"}(FE||(FE={})),function(l){l.PUBLISH_STATS="publish_stats",l.PUBLISH_RELATED_STATS="publish_related_stats",l.SUBSCRIBE_STATS="subscribe_stats",l.SUBSCRIBE_RELATED_STATS="subscribe_related_stats",l.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",l.DENOISER_STATS="denoiser_stats",l.TRANSPORT_STATS="transport_stats",l.EXTENSION_USAGE_STATS="extension_usage_stats"}(uS||(uS={})),function(l){l.ON_USER_ONLINE="on_user_online",l.ON_USER_OFFLINE="on_user_offline",l.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",l.ON_PUBLISH_STREAM="on_publish_stream",l.ON_UPLINK_STATS="on_uplink_stats",l.ON_P2P_LOST="on_p2p_lost",l.ON_REMOVE_STREAM="on_remove_stream",l.ON_ADD_AUDIO_STREAM="on_add_audio_stream",l.ON_ADD_VIDEO_STREAM="on_add_video_stream",l.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",l.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",l.ON_USER_BANNED="on_user_banned",l.ON_USER_LICENSE_BANNED="on_user_license_banned",l.ON_NOTIFICATION="on_notification",l.ON_CRYPT_ERROR="on_crypt_error",l.MUTE_AUDIO="mute_audio",l.MUTE_VIDEO="mute_video",l.UNMUTE_AUDIO="unmute_audio",l.UNMUTE_VIDEO="unmute_video",l.ON_P2P_OK="on_p2p_ok",l.RECEIVE_METADATA="receive_metadata",l.ON_DATA_STREAM="on_data_stream",l.ON_RTP_CAPABILITY_CHANGE="on_rtp_capability_change",l.ON_REMOTE_DATASTREAM_UPDATE="on_remote_datastream_update",l.ON_REMOTE_FULL_DATASTREAM_INFO="on_remote_full_datastream_info",l.ENABLE_LOCAL_VIDEO="enable_local_video",l.DISABLE_LOCAL_VIDEO="disable_local_video",l.ENABLE_LOCAL_AUDIO="enable_local_audio",l.DISABLE_LOCAL_AUDIO="disable_local_audio",l.ON_PUBLISHED_USER_LIST="on_published_user_list"}(JE||(JE={})),function(l){l.CONNECTION_STATE_CHANGE="CONNECTION_STATE_CHANGE",l.NEED_ANSWER="NEED_ANSWER",l.NEED_RENEGOTIATE="NEED_RENEGOTIATE",l.P2P_LOST="P2P_LOST",l.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",l.NEED_UNPUB="NEED_UNPUB",l.NEED_UNSUB="NEED_UNSUB",l.NEED_UPLOAD="NEED_UPLOAD",l.NEED_CONTROL="NEED_CONTROL",l.START_RECONNECT="START_RECONNECT",l.END_RECONNECT="END_RECONNECT",l.NEED_SIGNAL_RTT="NEED_SIGNAL_RTT"}(p6||(p6={})),function(l){l.SEND_ONLY="SEND_ONLY",l.RECEIVE_ONLY="RECEIVE_ONLY"}(YI||(YI={})),function(l){l.CONNECTED="websocket:connected",l.RECONNECTING="websocket:reconnecting",l.WILL_RECONNECT="websocket:will_reconnect",l.CLOSED="websocket:closed",l.FAILED="websocket:failed",l.ON_MESSAGE="websocket:on_message",l.REQUEST_NEW_URLS="websocket:request_new_urls",l.RECONNECT_WAITTING_FINISH="websocket:reconnect_waitting_finish",l.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",l.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire"}(zE||(zE={}));class hE extends yE{constructor(i){super(i,arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",arguments.length>2?arguments[2]:void 0),_e(this,"name","AgoraRTCException")}print(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"error";return super.print(i,Gi)}throw(){super.throw(Gi)}}function pM(l){if(typeof l!="string"||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(l))throw Gi.error("Invalid Channel Name ".concat(l)),new hE(_p.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function fM(l){if(i=l,!(typeof i=="number"&&Math.floor(i)===i&&0<=i&&i<=4294967295||zV(l,1,255)))throw new hE(_p.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var i;typeof l=="string"&&Gi.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.")}(function(l){l.TRANSCODE="mix_streaming",l.RAW="raw_streaming",l.INJECT="inject_streaming"})(o0||(o0={})),function(l){l[l.INJECT_STREAM_STATUS_START_SUCCESS=0]="INJECT_STREAM_STATUS_START_SUCCESS",l[l.INJECT_STREAM_STATUS_START_ALREADY_EXISTS=1]="INJECT_STREAM_STATUS_START_ALREADY_EXISTS",l[l.INJECT_STREAM_STATUS_START_UNAUTHORIZED=2]="INJECT_STREAM_STATUS_START_UNAUTHORIZED",l[l.INJECT_STREAM_STATUS_START_TIMEOUT=3]="INJECT_STREAM_STATUS_START_TIMEOUT",l[l.INJECT_STREAM_STATUS_START_FAILED=4]="INJECT_STREAM_STATUS_START_FAILED",l[l.INJECT_STREAM_STATUS_STOP_SUCCESS=5]="INJECT_STREAM_STATUS_STOP_SUCCESS",l[l.INJECT_STREAM_STATUS_STOP_NOT_FOUND=6]="INJECT_STREAM_STATUS_STOP_NOT_FOUND",l[l.INJECT_STREAM_STATUS_STOP_UNAUTHORIZED=7]="INJECT_STREAM_STATUS_STOP_UNAUTHORIZED",l[l.INJECT_STREAM_STATUS_STOP_TIMEOUT=8]="INJECT_STREAM_STATUS_STOP_TIMEOUT",l[l.INJECT_STREAM_STATUS_STOP_FAILED=9]="INJECT_STREAM_STATUS_STOP_FAILED",l[l.INJECT_STREAM_STATUS_BROKEN=10]="INJECT_STREAM_STATUS_BROKEN"}(mR||(mR={}));const IZ={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},mM={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function gM(l,i){O0(l.url,"".concat(i,".url"),1,1e3,!1),M_(l.x)||b_(l.x,"".concat(i,".x"),0,1e4),M_(l.y)||b_(l.y,"".concat(i,".y"),0,1e4),M_(l.width)||b_(l.width,"".concat(i,".width"),0,1e4),M_(l.height)||b_(l.height,"".concat(i,".height"),0,1e4),M_(l.zOrder)||b_(l.zOrder,"".concat(i,".zOrder"),0,255),M_(l.alpha)||b_(l.alpha,"".concat(i,".alpha"),0,1,!1)}const wZ={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:""},AZ={audioBitrate:48,audioChannels:2,audioVolume:100,audioSampleRate:48e3,height:0,width:0,videoBitrate:400,videoFramerate:15,videoGop:30};var oT,JI,J_,f6,j0,_T,Z0,gR,v_,j_,rI,n0,wN,c_;function m6(l){if(!l.channelName)throw new hE(_p.INVALID_PARAMS,"invalid channelName in info");if(typeof l.uid!="number")throw new hE(_p.INVALID_PARAMS,"invalid uid in info, uid must be a number");return l.token&&O0(l.token,"info.token",1,2047),fM(l.uid),pM(l.channelName),!0}(function(l){l.WARNING="@live_uap-warning",l.ERROR="@line_uap-error",l.PUBLISH_STREAM_STATUS="@live_uap-publish-status",l.INJECT_STREAM_STATUS="@live_uap-inject-status",l.WORKER_STATUS="@live_uap-worker-status",l.REQUEST_NEW_ADDRESS="@live_uap-request-address"})(oT||(oT={})),function(l){l.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager"}(JI||(JI={})),function(l){l[l.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",l[l.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",l[l.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",l[l.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",l[l.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",l[l.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",l[l.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",l[l.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",l[l.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",l[l.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",l[l.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",l[l.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",l[l.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",l[l.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",l[l.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",l[l.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",l[l.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",l[l.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",l[l.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",l[l.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",l[l.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN"}(J_||(J_={})),function(l){l.CONNECT_FAILED="connect failed",l.CONNECT_TIMEOUT="connect timeout",l.WS_DISCONNECTED="websocket disconnected",l.REQUEST_TIMEOUT="request timeout",l.REQUEST_FAILED="request failed",l.WAIT_STATUS_TIMEOUT="wait status timeout",l.WAIT_STATUS_ERROR="wait status error",l.BAD_STATE="bad state",l.WS_ABORT="ws abort",l.AP_REQUEST_TIMEOUT="AP request timeout",l.AP_JSON_PARSE_ERROR="AP json parse error",l.AP_REQUEST_ERROR="AP request error",l.AP_REQUEST_ABORT="AP request abort"}(f6||(f6={})),function(l){l[l.SetSdkProfile=0]="SetSdkProfile",l[l.SetSourceChannel=1]="SetSourceChannel",l[l.SetSourceUserId=2]="SetSourceUserId",l[l.SetDestChannel=3]="SetDestChannel",l[l.StartPacketTransfer=4]="StartPacketTransfer",l[l.StopPacketTransfer=5]="StopPacketTransfer",l[l.UpdateDestChannel=6]="UpdateDestChannel",l[l.Reconnect=7]="Reconnect",l[l.SetVideoProfile=8]="SetVideoProfile"}(j0||(j0={})),function(l){l.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",l.NETWORK_CONNECTED="NETWORK_CONNECTED",l.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",l.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",l.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",l.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",l.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",l.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",l.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",l.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE"}(_T||(_T={})),function(l){l.RELAY_STATE_IDLE="RELAY_STATE_IDLE",l.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",l.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",l.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE"}(Z0||(Z0={})),function(l){l.RELAY_OK="RELAY_OK",l.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",l.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",l.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED"}(gR||(gR={})),function(l){l.High="high",l.Low="low",l.Audio="audio",l.Screen="screen",l.ScreenLow="screen_low"}(v_||(v_={})),function(l){l.DISCONNECT="disconnect",l.CONNECTION_STATE_CHANGE="connection-state-change",l.NETWORK_QUALITY="network-quality",l.STREAM_TYPE_CHANGE="stream-type-change",l.IS_P2P_DISCONNECTED="is-p2p-dis",l.DISCONNECT_P2P="dis-p2p",l.REQUEST_NEW_GATEWAY_LIST="req-gate-url",l.NEED_RENEW_SESSION="need-sid",l.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",l.JOIN_RESPONSE="join-response",l.REQUEST_DC_CONNECTION_PARAMS="request-dc-connection-params",l.RESET_CONNECTION_EVENTS="reset-connection-events",l.DATACHANNEL_PRECONNECT="datachannel_preconnect",l.DATACHANNEL_FAILBACK="datachannel_failback",l.RESET_SIGNAL="reset-signal"}(j_||(j_={})),function(l){l.P2P_DISCONNECTED="P2P_DISCONNECTED",l.A_ROUND_WS_FAILED="A_ROUND_WS_FAILED",l.TIMEOUT="TIMEOUT",l.UNKNOWN_REASON="UNKNOWN_REASON"}(rI||(rI={})),function(l){l[l.Nothing=0]="Nothing",l[l.Audio=1]="Audio",l[l.LwoVideo=2]="LwoVideo",l[l.Video=4]="Video",l[l.Data=8]="Data",l[l.DataStream0=256]="DataStream0",l[l.DataStream1=512]="DataStream1",l[l.DataStream2=1024]="DataStream2",l[l.DataStream3=2048]="DataStream3",l[l.DataStream4=4096]="DataStream4",l[l.DataStream5=8192]="DataStream5",l[l.DataStream6=16384]="DataStream6",l[l.DataStream7=32768]="DataStream7"}(n0||(n0={})),function(l){l[l.websocket=0]="websocket",l[l.datachannel=1]="datachannel"}(wN||(wN={})),function(l){l.CHINA="CHINA",l.ASIA="ASIA",l.NORTH_AMERICA="NORTH_AMERICA",l.EUROPE="EUROPE",l.JAPAN="JAPAN",l.INDIA="INDIA",l.KOREA="KOREA",l.HKMC="HKMC",l.US="US",l.OCEANIA="OCEANIA",l.SOUTH_AMERICA="SOUTH_AMERICA",l.AFRICA="AFRICA",l.OVERSEA="OVERSEA",l.GLOBAL="GLOBAL",l.EXTENSIONS="EXTENSIONS"}(c_||(c_={}));const g6=[c_.AFRICA,c_.ASIA,c_.CHINA,c_.EUROPE,c_.GLOBAL,c_.INDIA,c_.JAPAN,c_.NORTH_AMERICA,c_.OCEANIA,c_.OVERSEA,c_.SOUTH_AMERICA];var C0;(function(l){l.CHINA="CN",l.ASIA="AS",l.NORTH_AMERICA="NA",l.EUROPE="EU",l.JAPAN="JP",l.INDIA="IN",l.KOREA="KR",l.HKMC="HK",l.US="US",l.OCEANIA="OC",l.SOUTH_AMERICA="SA",l.AFRICA="AF",l.OVERSEA="OVERSEA",l.GLOBAL="GLOBAL",l.EXTENSIONS="GLOBAL"})(C0||(C0={}));const AN={CHINA:{},ASIA:{CODE:C0.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:C0.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:C0.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:C0.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:C0.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:C0.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:C0.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:C0.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:C0.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:C0.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:C0.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:C0.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:C0.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:{}};var WO,E6,ME,N0,yT,TE,u_,WE,v6,OS,NS,a0,NT,W_,bT,_6,ES,HS,ER,w_,PT,y6;cM&&(AN.CHINA={CODE:C0.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"]}),function(l){l.UPDATE_BITRATE_LIMIT="update_bitrate_limit"}(WO||(WO={}));class b6 extends D_{constructor(i,o){super(),_e(this,"onICEConnectionStateChange",void 0),_e(this,"onConnectionStateChange",void 0),_e(this,"onDTLSTransportStateChange",void 0),_e(this,"onDTLSTransportError",void 0),_e(this,"onICETransportStateChange",void 0),_e(this,"onFirstAudioReceived",void 0),_e(this,"onFirstVideoReceived",void 0),_e(this,"onFirstAudioDecoded",void 0),_e(this,"onFirstVideoDecoded",void 0),_e(this,"onFirstVideoDecodedTimeout",void 0),_e(this,"onSelectedLocalCandidateChanged",void 0),_e(this,"onSelectedRemoteCandidateChanged",void 0)}}class ON extends b6{constructor(i,o){super(i,o)}}(function(l){l.SEND="sendonly",l.RECV="recvonly",l.SENDRECV="sendrecv",l.INACTIVE="inactive"})(E6||(E6={})),function(l){l.VIDEO="video",l.AUDIO="audio"}(ME||(ME={})),function(l){l[l.UDP=0]="UDP",l[l.TCP=1]="TCP",l[l.RELAY=2]="RELAY"}(N0||(N0={})),function(l){l[l.FIRST_CONNECTION=0]="FIRST_CONNECTION",l[l.TCP_RESTART=1]="TCP_RESTART",l[l.RELAY_RESTART=2]="RELAY_RESTART",l[l.OLD_FIRST_CONNECTION=10]="OLD_FIRST_CONNECTION",l[l.OLD_RESTART=11]="OLD_RESTART",l[l.DISCONNECTED_OR_FAILED=20]="DISCONNECTED_OR_FAILED"}(yT||(yT={})),function(l){l.LocalVideoTrack="videoTrack",l.LocalAudioTrack="audioTrack",l.LocalVideoLowTrack="videoLowTrack"}(TE||(TE={})),function(l){l.New="new",l.Connected="connected",l.Reconnecting="reconnecting",l.Disconnected="disconnected"}(u_||(u_={})),function(l){l.StateChange="stateChange",l.IceConnectionStateChange="iceConnectionStateChange",l.RequestMuteLocal="requestMuteLocal",l.RequestUnmuteLocal="requestUnmuteLocal",l.RequestRePublish="requestRePublish",l.RequestRePublishDataChannel="requestRePublishDataChannel",l.RequestReSubscribe="requestReSubscribe",l.RequestUploadStats="requestUploadStats",l.MediaReconnectStart="MediaReconnectStart",l.MediaReconnectEnd="MediaReconnectEnd",l.NeedSignalRTT="NeedSignalRTT",l.RequestRestartICE="RequestRestartIce",l.PeerConnectionStateChange="PeerConnectionStateChange",l.RequestReconnect="RequestReconnect",l.RequestReconnectPC="RequestReconnectPC",l.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",l.P2PLost="P2PLost",l.UpdateVideoEncoder="UpdateVideoEncoder",l.ConnectionTypeChange="ConnectionTypeChange",l.RequestLowStreamParameter="RequestLowStreamParameter",l.QueryClientConnectionState="QueryClientConnectionState",l.LocalCandidate="LocalCandidate",l.RequestP2PMuteLocal="requestP2PMuteLocal",l.RequestP2PPublish="RequestP2PPublish",l.RequestP2PUnPublish="RequestP2PUnPublish",l.RequestP2PUnmuteRemote="RequestP2PUnmuteRemote",l.RequestP2PMuteRemote="RequestP2PMuteRemote",l.RequestP2PRestartICE="RequestP2PRestartICE"}(WE||(WE={})),function(l){l.MUTE_LOCAL_VIDEO="mute_local_video",l.MUTE_LOCAL_AUDIO="mute_local_audio",l.UNMUTE_LOCAL_VIDEO="unmute_local_video",l.UNMUTE_LOCAL_AUDIO="unmute_local_audio",l.MUTE_REMOTE_VIDEO="mute_remote_video",l.MUTE_REMOTE_AUDIO="mute_remote_audio",l.UNMUTE_REMOTE_VIDEO="unmute_remote_video",l.UNMUTE_REMOTE_AUDIO="unmute_remote_audio"}(v6||(v6={})),function(l){l.CONNECTING="CONNECTING",l.RECONNECTING="RECONNECTING",l.CONNECTED="CONNECTED",l.CLOSED="CLOSED"}(OS||(OS={})),function(l){l[l.CONNECT_AP=0]="CONNECT_AP",l[l.AP_CONNECTED=1]="AP_CONNECTED",l[l.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",l[l.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",l[l.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",l[l.CONNECT_WORKER=5]="CONNECT_WORKER",l[l.WORKER_CONNECTED=6]="WORKER_CONNECTED",l[l.CLOSED=7]="CLOSED"}(NS||(NS={})),function(l){l.CONNECTION_STATE_CHANGE="connection-state-change",l.STATE_CHANGE="state-change",l.INSPECT_RESULT="inspect-result",l.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",l.REQUEST_NEW_WORKER_URL="request-new-worker-url"}(a0||(a0={})),function(l){l.NETWORK_ERROR="NETWORK_ERROR",l.SERVER_ERROR="SERVER_ERROR",l.MULTI_IP="MULTI_IP",l.TIMEOUT="TIMEOUT",l.OFFLINE="OFFLINE",l.LEAVE="LEAVE",l.P2P_FAILED="P2P_FAILED",l.FALLBACK="FALLBACK"}(NT||(NT={})),function(l){l.CONNECTED="transmitter:connected",l.RECONNECTING="transmitter:reconnecting",l.WILL_RECONNECT="transmitter:will_reconnect",l.CLOSED="transmitter:closed",l.FAILED="transmitter:failed",l.ON_MESSAGE="transmitter:on_message",l.REQUEST_NEW_URLS="transmitter:request_new_urls",l.RECONNECT_WAITTING_FINISH="transmitter:reconnect_waitting_finish",l.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",l.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",l.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",l.FAILBACK="transmitter:failback"}(W_||(W_={})),function(l){l.CAMERA_CHANGED="camera-changed",l.MICROPHONE_CHANGED="microphone-changed",l.PLAYBACK_DEVICE_CHANGED="playback-device-changed",l.AUDIO_AUTOPLAY_FAILED="audio-autoplay-failed",l.AUTOPLAY_FAILED="autoplay-failed",l.SECURITY_POLICY_VIOLATION="security-policy-violation"}(bT||(bT={})),function(l){l[l.APP_TYPE_INVALID_VALUE=-1]="APP_TYPE_INVALID_VALUE",l[l.APP_TYPE_NATIVE=0]="APP_TYPE_NATIVE",l[l.APP_TYPE_NATIVE_COCOS=1]="APP_TYPE_NATIVE_COCOS",l[l.APP_TYPE_NATIVE_UNITY=2]="APP_TYPE_NATIVE_UNITY",l[l.APP_TYPE_NATIVE_ELECTRON=3]="APP_TYPE_NATIVE_ELECTRON",l[l.APP_TYPE_NATIVE_FLUTTER=4]="APP_TYPE_NATIVE_FLUTTER",l[l.APP_TYPE_NATIVE_UNREAL=5]="APP_TYPE_NATIVE_UNREAL",l[l.APP_TYPE_NATIVE_XAMARIN=6]="APP_TYPE_NATIVE_XAMARIN",l[l.APP_TYPE_NATIVE_API_CLOUD=7]="APP_TYPE_NATIVE_API_CLOUD",l[l.APP_TYPE_NATIVE_REACT_NATIVE=8]="APP_TYPE_NATIVE_REACT_NATIVE",l[l.APP_TYPE_NATIVE_PYTHON=9]="APP_TYPE_NATIVE_PYTHON",l[l.APP_TYPE_NATIVE_COCOS_CREATOR=10]="APP_TYPE_NATIVE_COCOS_CREATOR",l[l.APP_TYPE_NATIVE_RUST=11]="APP_TYPE_NATIVE_RUST",l[l.APP_TYPE_NATIVE_C_SHARP=12]="APP_TYPE_NATIVE_C_SHARP",l[l.APP_TYPE_NATIVE_CEF=13]="APP_TYPE_NATIVE_CEF",l[l.APP_TYPE_NATIVE_UNI_APP=14]="APP_TYPE_NATIVE_UNI_APP",l[l.APP_TYPE_WEBRTC=1e3]="APP_TYPE_WEBRTC",l[l.APP_TYPE_WEBRTC_REACT=1001]="APP_TYPE_WEBRTC_REACT",l[l.APP_TYPE_WEBRTC_VUE=1002]="APP_TYPE_WEBRTC_VUE",l[l.APP_TYPE_WEBRTC_ANGULAR=1003]="APP_TYPE_WEBRTC_ANGULAR"}(_6||(_6={})),function(l){l.CONNECTING="CONNECTING",l.RECONNECTING="RECONNECTING",l.CONNECTED="CONNECTED",l.CLOSED="CLOSED"}(ES||(ES={})),function(l){l.CONNECTION_STATE_CHANGE="connection-state-change",l.STATE_CHANGE="state-change",l.INSPECT_RESULT="inspect-result",l.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",l.REQUEST_NEW_WORKER_URL="request-new-worker-url"}(HS||(HS={})),function(l){l[l.CONNECT_AP=0]="CONNECT_AP",l[l.AP_CONNECTED=1]="AP_CONNECTED",l[l.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",l[l.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",l[l.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",l[l.CONNECT_WORKER=5]="CONNECT_WORKER",l[l.WORKER_CONNECTED=6]="WORKER_CONNECTED",l[l.CLOSED=7]="CLOSED"}(ER||(ER={})),function(l){l.CALL="call",l.CANDIDATE="candidate",l.PUBLISH="publish",l.UNPUBLISH="unpublish",l.SUBSCRIBE="subscribe",l.UNSUBSCRIBE="unsubscribe",l.CONTROL="control",l.RESTART_ICE="restart_ice",l.ACK="ack",l.JOIN="join",l.EXCHANGE_SDP="exchange_sdp",l.DO_SUBSCRIBE="do_subscribe",l.DO_UNSUBSCRIBE="do_unsubscribe"}(w_||(w_={})),function(l){l.MUTE_LOCAL_AUDIO="mute_local_audio",l.MUTE_LOCAL_VIDEO="mute_local_video",l.UNMUTE_LOCAL_AUDIO="unmute_local_audio",l.UNMUTE_LOCAL_VIDEO="unmute_local_video"}(PT||(PT={})),function(l){l[l.SUCCESS=1]="SUCCESS",l[l.FAILED=0]="FAILED"}(y6||(y6={}));const OZ={[KI.ACCESS_POINT]:{[F0.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[F0.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[F0.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[F0.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[F0.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[F0.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[F0.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[F0.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[F0.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[F0.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[F0.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[F0.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[F0.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[F0.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[F0.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[F0.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[F0.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[F0.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[KI.UNILBS]:{[AS.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[AS.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[AS.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[AS.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[AS.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[AS.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[AS.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[AS.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[AS.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[AS.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[AS.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[AS.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[KI.STRING_UID_ALLOCATOR]:{[qO.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[qO.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[qO.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function NN(l){const i=OZ[Math.floor(l/1e4)];if(!i)return{desc:"unkonw error",retry:!1};const o=i[l%1e4];if(!o){if(Math.floor(l/1e4)===KI.ACCESS_POINT){const p=l%1e4;if(p.toString()[0]==="1")return{desc:l.toString(),retry:!1};if(p.toString()[0]==="2")return{desc:l.toString(),retry:!0}}return{desc:"unkonw error",retry:!1}}return o}const NZ={[qE.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[qE.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[qE.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[qE.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[qE.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[qE.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[qE.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[qE.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[qE.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[qE.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[qE.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[qE.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[qE.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[qE.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[qE.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[qE.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[qE.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[qE.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[qE.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[qE.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[qE.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[qE.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[qE.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[qE.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[qE.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[qE.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[qE.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[qE.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[qE.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[qE.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[qE.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[qE.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[qE.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[qE.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[qE.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[qE.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[qE.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[qE.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[qE.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[qE.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[qE.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[qE.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[qE.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[qE.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[qE.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[qE.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[qE.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[qE.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[qE.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[qE.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[qE.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[qE.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[qE.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[qE.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[qE.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[qE.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[qE.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[qE.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[qE.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[qE.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[qE.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[qE.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[qE.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function iI(l){return NZ[l]||{desc:"UNKNOW_ERROR_".concat(l),action:"failed"}}function S6(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function EM(l){for(var i=1;ii.readyState===WebSocket.CLOSED||i.readyState===WebSocket.CLOSING)}function R6(l,i){if(typeof l=="string")return l;const{proxy:o,host:p,port:g}=l;if(i){const b=nE("JOIN_GATEWAY_FALLBACK_PORT")||443;return b===443?"wss://".concat(p,"/ws/?p=").concat(Number(g)+150):"wss://".concat(p,":").concat(b,"/ws/?p=").concat(Number(g)+150)}return o?"wss://".concat(o,"/ws/?h=").concat(p,"&p=").concat(g):"wss://".concat(p,":").concat(g)}const PZ=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,kZ=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,DZ=/wss:\/\/(.+):([0-9]+)\/?/,LZ=/wss:\/\/(.[^\/]+)\/?/;let xZ=0;class MZ{constructor(i,o){_e(this,"id",0),_e(this,"store",void 0),_e(this,"recordIndex",void 0),_e(this,"websockets",[]),_e(this,"try443PortDuration",2e3),_e(this,"forceCloseWSDuration",5e3),_e(this,"try443PortTimeout",null),_e(this,"forceCloseTimeout",null),_e(this,"isTry443PortFailed",!1),_e(this,"isNormalPortFailed",!1),_e(this,"useDoubleDomain",!1),_e(this,"useProxy",!1),_e(this,"startTime",Date.now()),this.id=++xZ,this.try443PortDuration=nE("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=i||5e3,this.store=o}closeAllWebsockets(){this.websockets.forEach(i=>{i.onopen=null,i.onclose=null,i.onmessage=null,i.close()}),this.websockets.length=0}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout)}logger(){var i;const o=Date.now()-this.startTime;for(var p=arguments.length,g=new Array(p),b=0;b{var Vt;return VE(Vt=i.host).call(Vt,$)});j||(this.useDoubleDomain=!1);const H=[];if(this.useDoubleDomain)g.forEach($=>{H.push(R6(EM(EM({},i),{},{host:i.host.replace(j,$)}),o))});else{const $=EM({},i);if(o&&j){const Vt=g.find(_r=>_r!==j);Vt&&($.host=$.host.replace(j,Vt))}H.push(R6($,o))}try{H.forEach($=>{const Vt=new WebSocket($);Vt.binaryType="arraybuffer",A.push(Vt),this.logger("ws is connecting:",Vt.url)})}catch($){if(this.logger("ws create failed"),A.forEach(Vt=>Vt.close()),A.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(i,o,p);if(!o&&Number(i.port)!==443)return this.createWebSocket(i,!0,p);throw new hE(_p.WS_ERR,"init websocket failed! Error: ".concat($.toString()))}const z=UO();return this.store&&this.store.recordJoinChannelService({urls:A.map($=>$.url),service:"gateway"},this.recordIndex),A.forEach($=>{$.onopen=()=>{this.logger("onopen: ws ".concat($.url," open cost ").concat(Date.now()-b,"ms")),this.websockets.forEach(Vt=>{Vt!==$&&(Vt.onopen=null,Vt.onclose=null,Vt.onmessage=null,Vt.close(),this.logger("close backup websocket: ".concat(Vt.url)))}),this.websockets.length=0,z.resolve($)},$.onclose=Vt=>{this.logger("onclose: ws ".concat($.url," closed cost ").concat(Date.now()-b,"ms state: ").concat($.readyState)),o?this.isTry443PortFailed=T6(A):this.isNormalPortFailed=T6(A),this.logger("443: ".concat(this.useProxy?"not try":this.isTry443PortFailed?"failed":"trying"," 47xx: ").concat(this.isNormalPortFailed?"failed":"trying")),(o&&this.isTry443PortFailed||!o&&(this.isTry443PortFailed||this.useProxy)&&this.isNormalPortFailed)&&(this.logger("onclose: all websocket is closed, ".concat(Vt.reason)),z.reject({code:Vt.code,reason:rI.A_ROUND_WS_FAILED}))},$.onmessage=Vt=>this.logger("".concat($.url," onmessage: ").concat(Vt.data))}),this.websockets.push(...A),p||(()=>{const $=()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",z.isResolved),this.websockets.forEach(Vt=>Vt.readyState!==WebSocket.OPEN&&Vt.close())};if(o||this.useProxy)return this.logger("add 5s timeout at ".concat(o?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout($,this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout(()=>{if(this.logger("2s timeout, isWebsocket created: ",z.isResolved),z.isResolved)return $();l_().os===l0.MAC_OS&&N_()&&$(),this.createWebSocket(i,!0,!0).then(Vt=>z.resolve(Vt)).catch(Vt=>{this.isNormalPortFailed&&z.reject(Vt),this.logger("try 443 port to create ws failed")}),this.forceCloseTimeout=window.setTimeout($,this.forceCloseWSDuration)},this.try443PortDuration)})(),z.promise}chooseBestWebsocket(i,o,p,g){return this.useDoubleDomain=!!o,typeof i=="string"&&(i=function(b){let A,j,H;return[,A,j,H]=b.match(PZ)||[],A||([,j,H]=b.match(kZ)||[]),j&&H||([,j,H]=b.match(DZ)||[]),j&&H||([,j]=b.match(LZ)||[]),j||Gi.warning("un-destructible url: ",b),{proxy:A,host:j,port:H||"443"}}(i)),this.recordIndex=g,this.useProxy=!!i.proxy,p&&this.useProxy&&(Gi.warn("cannot use 443 only when use proxy"),p=!1),this.createWebSocket(i,!!p,!1).finally(()=>this.clearTimeout())}}function C6(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}class I6 extends D_{get url(){return this.websocket&&this.websocket.url||null}get reconnectMode(){return this._reconnectMode}set reconnectMode(i){var o;VE(o=["tryNext","recover"]).call(o,i)&&this.resetReconnectCount(i),this._reconnectMode=i}get state(){return this._state}set state(i){i!==this._state&&(this._state=i,this._state==="reconnecting"?this.emit(zE.RECONNECTING,this.reconnectReason):this._state==="connected"?this.emit(zE.CONNECTED):this._state==="closed"?this.emit(zE.CLOSED):this._state==="failed"&&this.emit(zE.FAILED))}resetReconnectCount(i){Gi.debug("websocket reset reconnect count, reason: "+i),this.reconnectCount=0}constructor(i,o){let p=arguments.length>2&&arguments[2]!==void 0&&arguments[2],g=arguments.length>3&&arguments[3]!==void 0&&arguments[3],b=arguments.length>4&&arguments[4]!==void 0&&arguments[4],A=arguments.length>5?arguments[5]:void 0;super(),_e(this,"connectionID",0),_e(this,"currentURLIndex",0),_e(this,"urls",[]),_e(this,"_reconnectMode","tryNext"),_e(this,"reconnectReason",void 0),_e(this,"_initMutex",new E0("websocket")),_e(this,"name",void 0),_e(this,"_state","closed"),_e(this,"reconnectInterrupter",void 0),_e(this,"websocket",void 0),_e(this,"retryConfig",void 0),_e(this,"reconnectCount",0),_e(this,"forceCloseTimeout",5e3),_e(this,"onlineReconnectListener",void 0),_e(this,"useCompress",void 0),_e(this,"tryDoubleDomain",!1),_e(this,"use443PortOnly",!1),_e(this,"wsInflateLength",0),_e(this,"wsDeflateLength",0),_e(this,"closeEstablishingWs",()=>{}),_e(this,"store",void 0),_e(this,"joinGatewayRecordIndex",void 0),this.store=A,this.name=i,this.retryConfig=function(Vt){for(var _r=1;_r{Vt!==_r&&(this.resetReconnectCount("network state change: ".concat(_r," -> ").concat(Vt)),Vt===K0.ONLINE?(this.retryConfig.timeout=z,this.retryConfig.timeoutFactor=$):(this.retryConfig.timeout=j,this.retryConfig.timeoutFactor=H))})}getConnection(){return this.websocket||void 0}async init(i){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;const p=await this._initMutex.lock();this.forceCloseTimeout=o,this.urls=i,this.state="connecting";try{const g=UO(),b=this.urls[this.currentURLIndex];this.createWebSocketConnection(b).then(g.resolve).catch(g.reject),this.once(zE.CLOSED,()=>{g.reject(new yE(_p.WS_DISCONNECT))}),this.once(zE.CONNECTED,g.resolve),await g.promise}catch{}finally{p()}}close(i,o){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 p=this.websocket;o?setTimeout(()=>p.close(),500):p.close(),this.websocket=void 0}this.state=i?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(i,o){if(!this.websocket)return void Gi.warning("[".concat(this.name,"] can not reconnect, no websocket"));i!==void 0&&(this.reconnectMode=i),Gi.debug("[".concat(this.name,"] reconnect is triggered initiative")),typeof this.joinGatewayRecordIndex=="number"&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(o)]},this.joinGatewayRecordIndex);const p=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),p&&p.bind(this.websocket)({code:9999,reason:o})}sendMessage(i){let o=arguments.length>2&&arguments[2]!==void 0&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new yE(_p.WS_ABORT,"websocket is not ready");try{o||(i=JSON.stringify(i)),this.websocket.send(i)}catch(p){throw new yE(_p.WS_ERR,"send websocket message error"+p.toString())}}setWsInflateData(i){this.wsDeflateLength=this.wsDeflateLength+i.originLength,this.wsInflateLength=this.wsInflateLength+i.compressedLength}getWsInflateData(){const i=this.wsInflateLength,o=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:i,wsDeflateLength:o}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(i){var o;const p=UO();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const g=$=>{var Vt;(Vt=this.store)===null||Vt===void 0||Vt.signalChannelOpen(),Gi.debug("[".concat(this.name,"] websocket opened:"),$),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),p.resolve()},b=async $=>{var Vt;if(Gi.debug("[".concat(this.name,"] websocket close ").concat((Vt=this.websocket)===null||Vt===void 0?void 0:Vt.url,", code: ").concat($.code,", reason: ").concat($.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)p.reject(new yE(_p.WS_DISCONNECT,"websocket close: ".concat($.code))),this.close();else{this.state==="connected"&&(this.reconnectReason=$.reason,this.state="reconnecting");const _r=oS(this,zE.WILL_RECONNECT,this.reconnectMode,$.reason)||this.reconnectMode,Fi=await this.reconnectWithAction(_r);if(this.state==="closed")return void Gi.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!Fi)return p.reject(new yE(_p.WS_DISCONNECT,"websocket reconnect failed: ".concat($.code))),this.close(!0);p.resolve()}},A=$=>{this.emit(zE.ON_MESSAGE,$)},j=$=>{Gi.warn("[".concat(this.connectionID,"] ws open error ").concat($))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),nE("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(i=nE("GATEWAY_WSS_ADDRESS")),Gi.debug("[".concat(this.name,"] start connect, url:"),i);const H=(o=this.store)===null||o===void 0?void 0:o.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var z;const $=await this.chooseBestWebsocketConnection(i);this.websocket=$,g&&g(this.websocket.url),this.websocket.onclose=b,this.websocket.onmessage=A,this.websocket.onerror=j,(z=this.store)===null||z===void 0||z.recordJoinChannelService({endTs:Date.now(),status:"success"},H),this.joinGatewayRecordIndex=H}catch($){const Vt=this.state==="closed",_r=$ instanceof yE,Fi=_r&&$.code===_p.WS_ABORT,_l=_r&&$.code===_p.WS_ERR,_u=_r?$.message:$&&($.reason||$.toString());Gi.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(_u)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:Fi?"aborted":"error",errors:[$]},H),Vt||_l?(p.reject(Vt?new yE(_p.WS_DISCONNECT,"websocket is closed: ".concat(_u)):new yE(_p.WS_ERR,"init websocket failed: ".concat(_u))),_l&&Gi.error("[".concat(this.name,"] init websocket failed: ").concat(_u))):b&&b($)}return p.promise}async reconnectWithAction(i){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount||this.urls.length===0||this.state==="closed")return!1;Gi.warning("[choose-best-ws] action: =>",i),this.onlineReconnectListener||X_.isOnline||!X_.onlineWaiter||(this.onlineReconnectListener=X_.onlineWaiter.then(()=>{this.onlineReconnectListener=void 0}));let p=!0;if(this.reconnectInterrupter=()=>p=!1,o){const A=mN(this.reconnectCount,this.retryConfig);Gi.debug("[".concat(this.name,"] wait ").concat(A,"ms to reconnect websocket, mode: ").concat(i)),await pE.race([w0(A),this.onlineReconnectListener||new pE(()=>{})])}if(this._state==="closed"||!p)return!1;this.reconnectCount+=1;const g=async(A,j)=>{this.emit(zE.RECONNECT_CREATE_CONNECTION,j),await this.createWebSocketConnection(A)};try{if(i==="retry")this.emit(zE.RECONNECT_WAITTING_FINISH,i),await g(this.urls[this.currentURLIndex],i);else if(i==="tryNext"){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);Gi.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),this.emit(zE.RECONNECT_WAITTING_FINISH,i),await g(this.urls[this.currentURLIndex],i)}else i==="recover"&&(Gi.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.emit(zE.RECONNECT_WAITTING_FINISH,i),this.urls=await U_(this,zE.REQUEST_NEW_URLS),this.currentURLIndex=0,await g(this.urls[this.currentURLIndex],i))}catch(A){var b;Gi.error("[".concat(this.name,"] reconnect failed ").concat(A&&A.toString()));const j=A==null||(b=A.data)===null||b===void 0?void 0:b.desc;return Array.isArray(j)&&VE(j).call(j,"dynamic key expired")?(this.emit(zE.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(i,o)}return!0}}class HO extends I6{constructor(i,o){super(i,o,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(i,o){const p=UO(),g=function(A,j){return new MZ(A,j)}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{Gi.debug("[choose-best-ws] close establishing websockets"),g.closeAllWebsockets(),p.reject(new yE(_p.WS_ABORT,"choose best websocket aborted"))};const b=nE("GATEWAY_DOMAINS");return Gi.debug("[choose-best-ws] currentDomain: ",i,", domains: ",b,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),g.chooseBestWebsocket(i,this.tryDoubleDomain,this.use443PortOnly,o).then(p.resolve).catch(p.reject),p.promise.finally(()=>{this.closeEstablishingWs=void 0})}}class zO extends I6{constructor(i,o){super(i,o,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(i,o){return new pE((p,g)=>{let b=!1;const A=[];this.closeEstablishingWs=()=>{Gi.debug("[choose-best-ws] close establishing websockets"),A.forEach(_l=>{_l.onclose=null,_l.onopen=null,_l.onmessage=null,_l.close()}),g(new yE(_p.WS_ABORT,"choose best websocket aborted"))};const j=nE("GATEWAY_DOMAINS");let H;const z=i.indexOf("?h="),$=j.find(_l=>z!==-1?VE(i).call(i,_l,z):VE(i).call(i,_l));Gi.debug("[choose-best-ws] currentDomain: ",$,", domains: ",j);let Vt=!this.tryDoubleDomain||!$;if(!Vt&&$){var _r;const _l=Date.now();try{j.forEach(_u=>{const _h=z===-1?i.replace($,_u):i.substr(0,z)+i.substr(z).replace($,_u),_g=new WebSocket(_h);_g.binaryType="arraybuffer",A.push(_g),Gi.debug("[choose-best-ws] ws is connecting:",_g.url)})}catch{for(Gi.debug("[choose-best-ws] ws create failed, fallback to single url"),A.forEach(_h=>_h.close());A.length;)A.pop();Vt=!0}(_r=this.store)===null||_r===void 0||_r.recordJoinChannelService({urls:A.map(_u=>_u.url),service:"gateway"},o),A.forEach(_u=>{_u.onopen=()=>{if(b)return;const _h=Date.now()-_l;Gi.debug("[choose-best-ws] ws open cost ".concat(_h,"ms")),A.filter(_g=>_g!==_u).forEach(_g=>{Gi.debug("[choose-best-ws]close backup websocket: ".concat(_g.url)),_g.close()}),b=!0,p(_u)},_u.onclose=_h=>{H=_h,!b&&(A.find(_g=>!(_g.readyState===WebSocket.CLOSED||_g.readyState===WebSocket.CLOSING))||(Gi.debug("[choose-best-ws] all websocket is closed"),b=!0,g(H)))},_u.onmessage=_h=>{Gi.debug("[choose-best-ws]".concat(_u.url," onmessage: ").concat(_h.data))}}),w0(this.forceCloseTimeout).then(()=>{A.forEach(_u=>{_u.readyState!==WebSocket.OPEN&&_u.close()})})}if(Vt){var Fi;let _l;Gi.debug("[choose-best-ws] use single url: ",i),(Fi=this.store)===null||Fi===void 0||Fi.recordJoinChannelService({urls:[i],service:"gateway"},o);try{_l=new WebSocket(i),A.push(_l),_l.binaryType="arraybuffer"}catch(_u){const _h=new yE(_p.WS_ERR,"init websocket failed! Error: ".concat(_u.toString()));return Gi.error("[".concat(this.name,"]").concat(_h)),void g(_h)}_l.onopen=()=>{p(_l)},_l.onclose=_u=>{g(_u)},_l.onmessage=_u=>{Gi.debug("[choose-best-ws]".concat(_l.url," onmessage: ").concat(_u.data))},w0(this.forceCloseTimeout).then(()=>{_l&&_l.readyState!==WebSocket.OPEN&&_l.close()})}}).then(p=>(this.closeEstablishingWs=void 0,p)).catch(p=>{throw this.closeEstablishingWs=void 0,p})}}class w6 extends D_{get connectionState(){return this._connectionState}set connectionState(i){i!==this._connectionState&&(this._connectionState=i,i===t_.CONNECTED?this.emit(kE.WS_CONNECTED):i===t_.RECONNECTING?this.emit(kE.WS_RECONNECTING,this._websocketReconnectReason):i===t_.CLOSED&&this.emit(kE.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(i,o){super(),_e(this,"_disconnectedReason",void 0),_e(this,"_websocketReconnectReason",void 0),_e(this,"_connectionState",t_.CLOSED),_e(this,"reconnectToken",void 0),_e(this,"websocket",void 0),_e(this,"openConnectionTime",void 0),_e(this,"clientId",void 0),_e(this,"lastMsgTime",Date.now()),_e(this,"uploadCache",[]),_e(this,"uploadCacheInterval",void 0),_e(this,"rttRolling",new WL(5)),_e(this,"pingpongTimer",void 0),_e(this,"wsInflateDataTimer",void 0),_e(this,"pingpongTimeoutCount",0),_e(this,"joinResponse",void 0),_e(this,"multiIpOption",void 0),_e(this,"initError",void 0),_e(this,"spec",void 0),_e(this,"store",void 0),_e(this,"onWebsocketMessage",p=>{if(p.data instanceof ArrayBuffer)return void this.emit(kE.ON_BINARY_DATA,p.data);const g=JSON.parse(p.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(g,"_id")){const b="res-@".concat(g._id);this.emit(b,g._result,g._message)}else if(Object.prototype.hasOwnProperty.call(g,"_type")){if(this.emit(g._type,g._message),g._type===JE.ON_NOTIFICATION&&this.handleNotification(g._message),g._type===JE.ON_USER_BANNED)switch(g._message.error_code){case 14:this.close(e_.UID_BANNED);break;case 15:this.close(e_.IP_BANNED);break;case 16:this.close(e_.CHANNEL_BANNED)}if(g._type===JE.ON_USER_LICENSE_BANNED)switch(g._message.error_code){case qE.ERR_LICENSE_MISSING:this.close(e_.LICENSE_MISSING);break;case qE.ERR_LICENSE_EXPIRED:this.close(e_.LICENSE_EXPIRED);break;case qE.ERR_LICENSE_MINUTES_EXCEEDED:this.close(e_.LICENSE_MINUTES_EXCEEDED);break;case qE.ERR_LICENSE_PERIOD_INVALID:this.close(e_.LICENSE_PERIOD_INVALID);break;case qE.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(e_.LICENSE_MULTIPLE_SDK_SERVICE);break;case qE.ERR_LICENSE_ILLEGAL:this.close(e_.LICENSE_ILLEGAL);break;default:this.close()}}}),this.clientId=i.clientId,this.spec=i,this.store=o,this.websocket=new HO("gateway-".concat(this.clientId),this.spec.retryConfig,!0,nE("JOIN_GATEWAY_USE_DUAL_DOMAIN"),nE("JOIN_GATEWAY_USE_443PORT_ONLY"),o),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===t_.CONNECTED&&this.reconnect("retry",h0.OFFLINE)})}async request(i,o,p,g){const b=T_(6,""),A={_id:b,_type:i,_message:o},j=this.websocket.connectionID,H=()=>new pE((_l,_u)=>{if(this.connectionState===t_.CONNECTED)return _l();const _h=()=>{this.off(kE.WS_CLOSED,_g),_l()},_g=()=>{this.off(kE.WS_CONNECTED,_h),_u(new hE(_p.WS_ABORT))};this.once(kE.WS_CONNECTED,_h),this.once(kE.WS_CLOSED,_g),i!==FE.PUBLISH&&i!==FE.SUBSCRIBE&&i!==FE.UNSUBSCRIBE&&i!==FE.UNPUBLISH&&i!==FE.CONTROL&&i!==FE.RESTART_ICE||this.once(kE.DISCONNECT_P2P,()=>{_u(new hE(_p.DISCONNECT_P2P))}),i!==FE.PUBLISH&&i!==FE.RESTART_ICE||this.once(kE.ABORT_P2P_EXECUTION,()=>{_u(new hE(_p.DISCONNECT_P2P))})});if(this.connectionState!==t_.CONNECTING&&this.connectionState!==t_.RECONNECTING||i===FE.JOIN||i===FE.REJOIN||await H(),this.websocket.sendMessage(A,!0),g)return;const z=new pE((_l,_u)=>{let _h=!1;const _g=(oE,SE)=>{_h=!0,_l({isSuccess:oE==="success",message:SE||{}}),this.off(kE.WS_CLOSED,eE),this.off(kE.WS_RECONNECTING,eE),this.emit(kE.REQUEST_SUCCESS,i,o)};this.once("res-@".concat(b),_g);const eE=()=>{_u(new hE(_p.WS_ABORT,"type: ".concat(i))),this.off(kE.WS_CLOSED,eE),this.off(kE.WS_RECONNECTING,eE),this.off("res-@".concat(b),_g)};this.once(kE.WS_CLOSED,eE),this.once(kE.WS_RECONNECTING,eE),w0(nE("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==j||_h||(Gi.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(i)),this.emit(kE.REQUEST_TIMEOUT,i,o))})});let $=null;try{$=await z}catch(_l){if(this.connectionState===t_.CLOSED||i===FE.LEAVE)throw new hE(_p.WS_ABORT);return!this.spec.forceWaitGatewayResponse||p?_l.throw():i===FE.JOIN||i===FE.REJOIN?null:(await H(),await this.request(i,o))}if($.isSuccess)return $.message;const Vt=Number($.message.error_code||$.message.code),_r=iI(Vt),Fi=new hE(_p.UNEXPECTED_RESPONSE,"".concat(_r.desc,": ").concat($.message.error_str),{code:Vt,data:$.message});return _r.action==="success"?$.message:(Gi.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(i,", error_code: ").concat(Vt,", message: ").concat(_r.desc,", action: ").concat(_r.action)),Vt===qE.ERR_TOO_MANY_BROADCASTERS?((i===FE.JOIN||i===FE.REJOIN)&&(this.initError=Fi,this.close()),Fi.throw()):_r.action==="failed"?Fi.throw():_r.action==="quit"?(this.initError=Fi,this.close(),Fi.throw()):(Vt===qE.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=$.message.option,Gi.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",h0.MULTI_IP)):this.reconnect(_r.action,h0.SERVER_ERROR),i===FE.JOIN||i===FE.REJOIN?null:await this.request(i,o)))}waitMessage(i,o){return new pE(p=>{const g=b=>{(!o||o(b))&&(this.off(i,g),p(b))};this.on(i,g)})}upload(i,o){const p={_type:i,_message:o};try{this.websocket.sendMessage(p)}catch{const b=nE("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(p),this.uploadCache.length>b&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==t_.CONNECTED)return;const A=this.uploadCache.splice(0,1)[0];this.uploadCache.length===0&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(A._type,A._message)},nE("UPLOAD_CACHE_INTERVAL")||2e3))}}send(i,o){const p={_type:i,_message:o};this.websocket.sendMessage(p)}init(i,o){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new pE((p,g)=>{this.once(kE.WS_CONNECTED,()=>p(this.joinResponse)),this.once(kE.WS_CLOSED,()=>g(this.initError||new hE(_p.WS_ABORT))),this.connectionState=t_.CONNECTING,this.websocket.init(i).catch(g),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval(()=>{this.handleWsInflateData()},2e4)})}close(i){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=i||e_.LEAVE,this.connectionState=t_.CLOSED,Gi.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),i===e_.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new HO("gateway-".concat(this.clientId),this.spec.retryConfig,!0,nE("JOIN_GATEWAY_USE_DUAL_DOMAIN"),nE("JOIN_GATEWAY_USE_443PORT_ONLY"),this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(kE.ABORT_P2P_EXECUTION);const i=await U_(this,kE.REQUEST_JOIN_INFO),o=await this.request(FE.JOIN,i);if(!o)return this.emit(kE.REPORT_JOIN_GATEWAY,rI.TIMEOUT,this.url||""),!1;this.joinResponse=o,this.emit(kE.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=t_.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new hE(_p.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const i=JT(this,kE.REQUEST_REJOIN_INFO);i.token=this.reconnectToken;const o=await this.request(FE.REJOIN,i);return!!o&&(this.connectionState=t_.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),o.peers&&o.peers.forEach(p=>{this.emit(JE.ON_USER_ONLINE,{uid:p.uid}),p.audio&&this.emit(JE.ON_ADD_AUDIO_STREAM,{uid:p.uid,uint_id:p.uint_id,audio:!0,ssrcId:p.audio_ssrc}),p.video&&this.emit(JE.ON_ADD_VIDEO_STREAM,{uid:p.uid,uint_id:p.uint_id,video:!0,ssrcId:p.video_ssrc}),p.audio_mute?this.emit(JE.MUTE_AUDIO,{uid:p.uid}):this.emit(JE.UNMUTE_AUDIO,{uid:p.uid}),p.video_mute?this.emit(JE.MUTE_VIDEO,{uid:p.uid}):this.emit(JE.UNMUTE_VIDEO,{uid:p.uid}),p.audio_enable_local?this.emit(JE.ENABLE_LOCAL_AUDIO,{uid:p.uid}):this.emit(JE.DISABLE_LOCAL_AUDIO,{uid:p.uid}),p.video_enable_local?this.emit(JE.ENABLE_LOCAL_VIDEO,{uid:p.uid}):this.emit(JE.DISABLE_LOCAL_VIDEO,{uid:p.uid}),p.audio||p.video||this.emit(JE.ON_REMOVE_STREAM,{uid:p.uid,uint_id:p.uint_id})}),!0)}reconnect(i,o){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(i,o)}handleNotification(i){Gi.debug("[".concat(this.clientId,"] receive notification: "),i);const o=iI(i.code);if(o.action!=="success"){if(o.action!=="failed")return o.action==="quit"?(o.desc==="ERR_REPEAT_JOIN_CHANNEL"&&this.close(e_.UID_BANNED),void this.close()):void this.reconnect(o.action,h0.SERVER_ERROR);Gi.error("[".concat(this.clientId,"] ignore error: "),o.desc)}}handlePingPong(){if(!this.websocket||this.websocket.state!=="connected")return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const i=nE("PING_PONG_TIME_OUT"),o=Date.now();this.pingpongTimeoutCount>=i&&(Gi.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(o-this.lastMsgTime,"ms")),o-this.lastMsgTime>nE("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",h0.TIMEOUT):this.request(FE.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const p=Date.now()-o;this.rttRolling.add(p),nE("REPORT_STATS")&&this.send(FE.PING_BACK,{pingpongElapse:p})}).catch(p=>{})}handleWsInflateData(){const{wsInflateLength:i,wsDeflateLength:o}=this.websocket.getWsInflateData();i!==0&&o!==0&&this.upload(uS.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:o,ws_inflate_length:i})}handleWebsocketEvents(){this.websocket.on(zE.RECONNECT_WAITTING_FINISH,i=>{this.emit(kE.WS_RECONNECT_WAITTING_FINISH,i)}),this.websocket.on(zE.RECONNECT_CREATE_CONNECTION,i=>{this.emit(kE.WS_RECONNECT_CREATE_CONNECTION,i)}),this.websocket.on(zE.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(zE.CLOSED,()=>{this.connectionState=t_.CLOSED}),this.websocket.on(zE.FAILED,()=>{this._disconnectedReason=e_.NETWORK_ERROR,this.connectionState=t_.CLOSED}),this.websocket.on(zE.RECONNECTING,i=>{this._websocketReconnectReason=i,this.joinResponse=void 0,this.connectionState===t_.CONNECTED?this.connectionState=t_.RECONNECTING:this.connectionState=t_.CONNECTING}),this.websocket.on(zE.WILL_RECONNECT,(i,o,p)=>{const g=JT(this,kE.IS_P2P_DISCONNECTED),b=g||i!=="retry";g&&i==="retry"&&(Gi.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),i="tryNext",o=rI.P2P_DISCONNECTED),b&&(Gi.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(i)),this.emit(kE.REPORT_JOIN_GATEWAY,o||rI.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(kE.NEED_RENEW_SESSION),this.emit(kE.DISCONNECT_P2P)),p(i)}),this.websocket.on(zE.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(i=>{Gi.warning("[".concat(this.clientId,"] rejoin failed ").concat(i)),this.reconnect("tryNext",h0.SERVER_ERROR)}):this.join().catch(i=>{if(this.emit(kE.REPORT_JOIN_GATEWAY,i.message||i.code||rI.UNKNOWN_REASON,this.url||""),i instanceof hE&&i.code===_p.UNEXPECTED_RESPONSE&&i.data.code===qE.ERR_NO_AUTHORIZED)return Gi.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",h0.SERVER_ERROR);Gi.error("[".concat(this.clientId,"] join gateway request failed"),i.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",h0.SERVER_ERROR):(this.initError=i,this.close())})}),this.websocket.on(zE.REQUEST_NEW_URLS,(i,o)=>{U_(this,kE.REQUEST_RECOVER,this.multiIpOption).then(i).catch(o)}),this.websocket.on(zE.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(JE.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})}}var A6=` +\v\f\r                 \u2028\u2029\uFEFF`,UZ=gO,FZ=WT,vM=A6,O6=R0("".replace),jZ=RegExp("^["+vM+"]+"),VZ=RegExp("(^|[^"+vM+"])["+vM+"]+$"),_M=function(l){return function(i){var o=FZ(UZ(i));return 1&l&&(o=O6(o,jZ,"")),2&l&&(o=O6(o,VZ,"$1")),o}},BZ={start:_M(1),end:_M(2),trim:_M(3)},GZ=qF.PROPER,qZ=t0,N6=A6,WZ=BZ.trim;Y_({target:"String",proto:!0,forced:function(l){return qZ(function(){return!!N6[l]()||"​…᠎"[l]()!=="​…᠎"||GZ&&N6[l].name!==l})}("trim")},{trim:function(){return WZ(this)}});var v0,_0,HZ=WR("String").trim,zZ=mT,KZ=HZ,yM=String.prototype,bM=LE(function(l){var i=l.trim;return typeof l=="string"||l===yM||zZ(yM,l)&&i===yM.trim?KZ:i});function XI(l,i,o){return{sampleRate:l,stereo:i,bitrate:o}}function i_(l,i,o,p,g){return{width:l,height:i,frameRate:o,bitrateMin:p,bitrateMax:g}}function aT(l,i,o,p,g){return{width:{max:l},height:{max:i},frameRate:o,bitrateMin:p,bitrateMax:g}}function SM(l,i){return{numSpatialLayers:l,numTemporalLayers:i}}(function(l){l[l.CHOOSE_SERVER=11]="CHOOSE_SERVER",l[l.CLOUD_PROXY=18]="CLOUD_PROXY",l[l.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",l[l.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK"})(v0||(v0={})),function(l){l.IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",l.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",l.IOS_INTERRUPTION_START="ios-interruption-start",l.IOS_INTERRUPTION_END="ios-interruption-end",l.STATE_CHANGE="state-change"}(_0||(_0={}));const YZ={"90p":i_(160,90),"90p_1":i_(160,90),"120p":i_(160,120,15,30,65),"120p_1":i_(160,120,15,30,65),"120p_3":i_(120,120,15,30,50),"120p_4":i_(212,120),"180p":i_(320,180,15,30,140),"180p_1":i_(320,180,15,30,140),"180p_3":i_(180,180,15,30,100),"180p_4":i_(240,180,15,30,120),"240p":i_(320,240,15,40,200),"240p_1":i_(320,240,15,40,200),"240p_3":i_(240,240,15,40,140),"240p_4":i_(424,240,15,40,220),"360p":i_(640,360,15,80,400),"360p_1":i_(640,360,15,80,400),"360p_3":i_(360,360,15,80,260),"360p_4":i_(640,360,30,80,600),"360p_6":i_(360,360,30,80,400),"360p_7":i_(480,360,15,80,320),"360p_8":i_(480,360,30,80,490),"360p_9":i_(640,360,15,80,800),"360p_10":i_(640,360,24,80,800),"360p_11":i_(640,360,24,80,1e3),"480p":i_(640,480,15,100,500),"480p_1":i_(640,480,15,100,500),"480p_2":i_(640,480,30,100,1e3),"480p_3":i_(480,480,15,100,400),"480p_4":i_(640,480,30,100,750),"480p_6":i_(480,480,30,100,600),"480p_8":i_(848,480,15,100,610),"480p_9":i_(848,480,30,100,930),"480p_10":i_(640,480,10,100,400),"720p":i_(1280,720,15,120,1130),"720p_auto":i_(1280,720,30,900,3e3),"720p_1":i_(1280,720,15,120,1130),"720p_2":i_(1280,720,30,120,2e3),"720p_3":i_(1280,720,30,120,1710),"720p_5":i_(960,720,15,120,910),"720p_6":i_(960,720,30,120,1380),"1080p":i_(1920,1080,15,120,2080),"1080p_1":i_(1920,1080,15,120,2080),"1080p_2":i_(1920,1080,30,120,3e3),"1080p_3":i_(1920,1080,30,120,3150),"1080p_5":i_(1920,1080,60,120,4780),"1440p":i_(2560,1440,30,120,4850),"1440p_1":i_(2560,1440,30,120,4850),"1440p_2":i_(2560,1440,60,120,7350),"4k":i_(3840,2160,30,120,8910),"4k_1":i_(3840,2160,30,120,8910),"4k_3":i_(3840,2160,60,120,13500)},PN=[{scaleResolutionDownBy:2,width:1280,height:720,frameRate:30,bitrateMin:300,bitrateMax:900},{scaleResolutionDownBy:1.333333,width:1280,height:720,frameRate:30,bitrateMin:600,bitrateMax:2e3},{scaleResolutionDownBy:1,width:1280,height:720,frameRate:30,bitrateMin:900,bitrateMax:3e3}],JZ={"480p":aT(640,480,5),"480p_1":aT(640,480,5),"480p_2":aT(640,480,30),"480p_3":aT(640,480,15),"720p":aT(1280,720,5),"720p_auto":i_(1280,720,30,900,3e3),"720p_1":aT(1280,720,5),"720p_2":aT(1280,720,30),"720p_3":aT(1280,720,15),"1080p":aT(1920,1080,5),"1080p_1":aT(1920,1080,5),"1080p_2":aT(1920,1080,30),"1080p_3":aT(1920,1080,15)},XZ={"1SL1TL":SM(1,1),"3SL3TL":SM(3,3),"2SL3TL":SM(2,3)};function kT(l){return l||(l="480p_1"),typeof l=="string"?Object.assign({},YZ[l]):l}function TM(l){return typeof l=="string"?Object.assign({},JZ[l]):l}function kN(l){return typeof l=="string"?Object.assign({},XZ[l]):l}const QZ={speech_low_quality:XI(16e3,!1),speech_standard:XI(32e3,!1,18),music_standard:XI(48e3,!1),standard_stereo:XI(48e3,!0,56),high_quality:XI(48e3,!1,128),high_quality_stereo:XI(48e3,!0,192)};function DN(l){return typeof l=="string"?Object.assign({},QZ[l]):l}const QI=[];function P6(l){return d0(l,"mediaSource",["screen","window","application"]),!0}var xE,A_,vR,LN,RM,$I,_R,sI,lS,xN;(function(l){l.NEED_RENEGOTIATE="@need_renegotiate",l.NEED_REPLACE_TRACK="@need_replace_track",l.NEED_CLOSE="@need_close",l.NEED_ENABLE_TRACK="@need_enable_track",l.NEED_DISABLE_TRACK="@need_disable_track",l.NEED_SESSION_ID="@need_sid",l.SET_OPTIMIZATION_MODE="@set_optimization_mode",l.GET_STATS="@get_stats",l.GET_RTC_STATS="@get_rtc_stats",l.GET_LOW_VIDEO_TRACK="@get_low_video_track",l.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",l.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",l.NEED_MUTE_TRACK="@need_mute_track",l.NEED_UNMUTE_TRACK="@need_unmute_track"})(xE||(xE={})),function(l){l.SCREEN_TRACK="screen_track",l.CUSTOM_TRACK="custome_track",l.LOW_STREAM="low_stream"}(A_||(A_={})),function(l){l[l.HIGH_STREAM=0]="HIGH_STREAM",l[l.LOW_STREAM=1]="LOW_STREAM"}(vR||(vR={})),function(l){l[l.HIGH_STREAM=0]="HIGH_STREAM",l[l.LOW_STREAM=1]="LOW_STREAM"}(LN||(LN={})),function(l){l[l.DISABLE=0]="DISABLE",l[l.LOW_STREAM=1]="LOW_STREAM",l[l.AUDIO_ONLY=2]="AUDIO_ONLY"}(RM||(RM={})),function(l){l.TRANSCEIVER_UPDATED="transceiver-updated"}($I||($I={})),function(l){l.SOURCE_STATE_CHANGE="source-state-change",l.TRACK_ENDED="track-ended",l.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",l.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",l.CLOSED="closed"}(_R||(_R={})),function(l){l.FIRST_FRAME_DECODED="first-frame-decoded",l.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status"}(sI||(sI={})),function(l){l.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",l.RECEIVE_TRACK_BUFFER="receive_track_buffer",l.ON_AUDIO_BUFFER="on_audio_buffer",l.UPDATE_SOURCE="update_source"}(lS||(lS={})),function(l){l.UPDATE_TRACK_SOURCE="update-track-source"}(xN||(xN={}));const CM={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},IM={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},k6={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},$Z={uplinkNetworkQuality:0,downlinkNetworkQuality:0},D6={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};var V0,dS,oI,XT,B0;(function(l){l.ON_TRACK="on_track",l.ON_NODE="on_node"})(V0||(V0={})),function(l){l.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",l.REQUEST_CONSTRAINTS="request_constraints"}(dS||(dS={})),function(l){l.IDLE="IDLE",l.INITING="INITING",l.INITEND="INITEND"}(oI||(oI={})),function(l){l.STATE_CHANGE="state_change",l.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",l.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",l.CAMERA_DEVICE_CHANGED="cameraDeviceChanged"}(XT||(XT={})),function(l){l.NONE="none",l.INIT="init",l.CANPLAY="canplay",l.PLAYING="playing",l.PAUSED="paused",l.SUSPEND="suspend",l.STALLED="stalled",l.WAITING="waiting",l.ERROR="error",l.DESTROYED="destroyed",l.ABORT="abort",l.ENDED="ended",l.EMPTIED="emptied",l.LOADEDDATA="loadeddata"}(B0||(B0={}));const wM={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};var ZI;(function(l){l.OPEN="open",l.MESSAGE="message",l.CLOSE="close",l.CLOSING="closing",l.ERROR="error"})(ZI||(ZI={}));class L6 extends D_{constructor(i,o){super(),_e(this,"_ID",void 0),_e(this,"_rtpTransceiver",void 0),_e(this,"_lowRtpTransceiver",void 0),_e(this,"_hints",[]),_e(this,"_isClosed",!1),_e(this,"_originMediaStreamTrack",void 0),_e(this,"_mediaStreamTrack",void 0),_e(this,"_external",{}),this._ID=o||T_(8,"track-"),this._originMediaStreamTrack=i,this._mediaStreamTrack=i,function(p){VE(QI).call(QI,p)||QI.push(p)}(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(i){if(!i){const o=jE.reportApiInvoke(null,{name:e0.GET_MEDIA_STREAM_TRACK,options:[],tag:x_.TRACER});this._mediaStreamTrack&&typeof this._mediaStreamTrack.label=="string"?o.onSuccess(this._mediaStreamTrack.label):o.onSuccess("")}return this._mediaStreamTrack}getRTCRtpTransceiver(i){return i===vR.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(i){const o=QI.indexOf(i);o!==-1&&QI.splice(o,1)}(this),this.emit(_R.CLOSED)}_updateRtpTransceiver(i,o){if(o===vR.LOW_STREAM){if(this._lowRtpTransceiver===i)return;this._lowRtpTransceiver=i}else{if(this._rtpTransceiver===i)return;this._rtpTransceiver=i}this.emit($I.TRANSCEIVER_UPDATED,i,o)}}class P0 extends L6{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}set processorContext(i){this._processorContext=i}constructor(i,o){super(i,o),_e(this,"_enabled",!0),_e(this,"_muted",!1),_e(this,"_isExternalTrack",!1),_e(this,"_isClosed",!1),_e(this,"_enabledMutex",void 0),_e(this,"processor",void 0),_e(this,"_handleTrackEnded",()=>{this.onTrackEnded()}),this._enabledMutex=new E0("".concat(this.getTrackId())),i.addEventListener("ended",this._handleTrackEnded)}getTrackLabel(){var i,o;return(i=(o=this._originMediaStreamTrack)===null||o===void 0?void 0:o.label)!==null&&i!==void 0?i:""}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,Gi.debug("[".concat(this.getTrackId(),"] close")),this.emit(xE.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(i,o){let p=arguments.length>2&&arguments[2]!==void 0&&arguments[2];this._isExternalTrack=p,i!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),o&&this._originMediaStreamTrack.stop()),i.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=i,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await S_(this,xE.NEED_REPLACE_TRACK,this),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){Gi.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(_R.TRACK_ENDED)}stateCheck(i,o){if(Gi.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(i,": ").concat(o,"]")),QR(o,i),this._enabled&&this._muted&&i==="enabled"&&o===!1)throw new yE(_p.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",Gi);if(!this._enabled&&!this._muted&&i==="muted"&&o===!0)throw new yE(_p.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",Gi)}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}function x6(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}const M6=window.AudioContext||window.webkitAudioContext;let PS=null;const __=new class extends D_{constructor(){super(...arguments),_e(this,"prevState",void 0),_e(this,"curState",void 0),_e(this,"currentTime",void 0),_e(this,"currentTimeStuckAt",void 0),_e(this,"interruptDetectorTrack",void 0),_e(this,"onLocalAudioTrackMute",()=>{Gi.info("ios15-interruption-start"),this.emit(_0.IOS_15_16_INTERRUPTION_START)}),_e(this,"onLocalAudioTrackUnmute",async()=>{Gi.info("ios15-interruption-end"),this.curState!=="running"||this.duringInterruption?Gi.info("ios15-interruption-end-canceled"):(PS&&await PS.suspend(),this.emit(_0.IOS_15_16_INTERRUPTION_END))})}get duringInterruption(){return this.prevState==="running"&&this.curState==="interrupted"}bindInterruptDetectorTrack(l){Gi.debug("webaudio bindInterruptDetectorTrack ".concat(l.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=l,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(l){Gi.debug("webaudio unbindInterruptDetectorTrack ".concat(l.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===l&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}};function ZZ(){if(!M6)return void Gi.error("your browser is not support web audio");Gi.info("create audio context");const l=function(i){for(var o=1;o{__.prevState=__.curState,__.curState=PS?PS.state:void 0;const{prevState:i,curState:o}=__,p=o==="running",g=o==="interrupted",b=i==="running",A=i==="suspended",j=i==="interrupted",H=l_().osVersion;(z0()||wT())&&b&&g&&(Gi.info("ios".concat(H,"-interruption-start")),__.emit(_0.IOS_INTERRUPTION_START)),(z0()||wT())&&(A||j)&&p&&(Gi.info("ios".concat(H,"-interruption-end")),__.emit(_0.IOS_INTERRUPTION_END)),i!==o&&(Gi.debug("AudioContext State Change","".concat(i,"=>").concat(o)),__.emit(_0.STATE_CHANGE))},setInterval(()=>{var i;const o=(i=PS)===null||i===void 0?void 0:i.currentTime;__.currentTime!==o?(__.currentTimeStuckAt&&(Gi.debug("AudioContext current time resume at ".concat(o)),__.currentTimeStuckAt=void 0),__.currentTime=o):(o!==__.currentTimeStuckAt&&(jE.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:o},tag:x_.TRACER}).onSuccess(),Gi.warning("AudioContext current time stuck at ".concat(o))),__.currentTimeStuckAt=o)},5e3),async function(i){const o=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let p,g=!1,b=!1,A=!1;function j(_h){i.state==="running"?H(!1):z0()||wT()?i.state==="suspended"&&(H(!0),_h&&i.resume().then($,$)):i.state!=="closed"&&(H(!0),_h&&i.resume().then($,$))}function H(_h){if(g!==_h){g=_h;for(let _g=0,eE=o;_g",p=_g.children.item(0),p.controls=!1,p.disableRemotePlayback=!0,p.preload="auto",p.srcObject=_h.stream,_r(!0)}__.on(_0.STATE_CHANGE,z),j(!1)}(PS)}function _w(){if(!PS){if(ZZ(),!PS)throw new yE(_p.NOT_SUPPORTED,"can not create audio context");return PS}return PS}function U6(){return!!PS}function aI(l){if(function(){if(AM!==null)return AM;const p=_w(),g=p.createBufferSource(),b=p.createGain(),A=p.createGain();g.connect(b),g.connect(A),g.disconnect(b);let j=!1;try{g.disconnect(b)}catch{j=!0}return g.disconnect(),AM=j,j}())return;const i=l.connect,o=l.disconnect;l.connect=(p,g,b)=>{var A;return l._inputNodes||(l._inputNodes=[]),VE(A=l._inputNodes).call(A,p)||(p instanceof AudioNode?(l._inputNodes.push(p),i.call(l,p,g,b)):i.call(l,p,g)),l},l.disconnect=(p,g,b)=>{o.call(l),p?VL(l._inputNodes,p):l._inputNodes=[];for(const A of l._inputNodes)i.call(l,A)}}let AM=null;function OM(l,i){let o=!1;const p=1/i;if(nE("DISABLE_WEBAUDIO")){const g=window.setInterval(()=>{o?window.clearInterval(g):l(performance.now()/1e3)},1e3*p)}else{const g=_w();let b=g.createGain();b.gain.value=0,b.connect(g.destination);const A=()=>{if(o)return void(b=null);const j=g.createOscillator();j.onended=A,j.connect(b),j.start(0),j.stop(g.currentTime+p),l(g.currentTime)};A()}return()=>{o=!0}}const G0={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};function I_(){return G0}class F6{constructor(){_e(this,"context",void 0),_e(this,"analyserNode",void 0),_e(this,"sourceNode",void 0),this.context=_w(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4}updateSource(i){if(i!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode)}catch{}this.sourceNode=i,i==null||i.connect(this.analyserNode)}}getVolumeLevel(){if(!this.sourceNode||(!this.context||z0()||wT()||this.context.state!=="running"&&this.context.resume(),!this.analyserNode))return 0;const i=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(i);else{const p=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(p);for(let g=0;gp+g*g,0)/i.length;return Math.max(10*Math.log10(o)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var i,o;(i=this.sourceNode)===null||i===void 0||i.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,(o=this.sourceNode)===null||o===void 0||o.connect(this.analyserNode)}catch{Gi.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class j6 extends D_{get processSourceNode(){return this.sourceNode}set processedNode(i){var o;if(!this.isDestroyed&&this._processedNode!==i){try{var p;(p=this.sourceNode)===null||p===void 0||p.disconnect(this.outputNode)}catch{}(o=this._processedNode)===null||o===void 0||o.disconnect(),this._processedNode=i,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),_e(this,"outputNode",void 0),_e(this,"outputTrack",void 0),_e(this,"isPlayed",!1),_e(this,"context",void 0),_e(this,"audioBufferNode",void 0),_e(this,"destNode",void 0),_e(this,"audioOutputLevel",0),_e(this,"volumeLevelAnalyser",void 0),_e(this,"_processedNode",void 0),_e(this,"playNode",void 0),_e(this,"isDestroyed",!1),_e(this,"onNoAudioInput",void 0),_e(this,"isNoAudioInput",!1),_e(this,"_noAudioInputCount",0),this.context=_w(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),aI(this.outputNode),this.volumeLevelAnalyser=new F6}startGetAudioBuffer(i){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(i),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=o=>{this.emit(lS.ON_AUDIO_BUFFER,function(p){for(let g=0;g{__.emit("autoplay-failed")}),this.isPlayed=!0,this.playNode=i||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 i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;if(i>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;z0()||wT()?this.context.state==="suspended"&&this.context.resume():this.context.state!=="running"&&this.context.resume();const o=this.volumeLevelAnalyser.getAnalyserNode();let p;o.getFloatTimeDomainData?(p=new Float32Array(o.fftSize),o.getFloatTimeDomainData(p)):(p=new Uint8Array(o.fftSize),o.getByteTimeDomainData(p));let g=!1;for(let b=0;b{if(Gi.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 Gi.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then(()=>Gi.info("resume success")),Gi.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const j=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?j.stop():this.isCurrentTrackCloned=!0;const H=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(H),aI(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const z=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(z,this.context.currentTime),aI(this.outputNode),this.emit(lS.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=H,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()}),i.kind!=="audio")throw new yE(_p.UNEXPECTED_ERROR);this.track=i;const b=new MediaStream([this.track]);if(this.isRemoteTrack=!!o,this.sourceNode=this.context.createMediaStreamSource(b),aI(this.sourceNode),p){const j=p.clone();j.enabled=!0,this.clonedTrack=j,Gi.debug("create an unmuted track ".concat(j.id," from the original track ").concat(p.id," to get the volume"));const H=this.context.createMediaStreamSource(new MediaStream([j]));aI(H),this.originVolumeLevelAnalyser=new F6,this.originVolumeLevelAnalyser.updateSource(H)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=b;const A=l_();o&&A.os===l0.IOS&&Number((g=A.osVersion)===null||g===void 0?void 0:g.split(".")[0])<15&&(__.on(_0.STATE_CHANGE,()=>{this.context.state==="suspended"?document.body.addEventListener("click",this.rebuildWebAudio,!0):this.context.state==="running"&&this.rebuildWebAudio()}),this.checkHasAudioInput().then(j=>{j||document.body.addEventListener("click",this.rebuildWebAudio,!0)}))}updateTrack(i){this.sourceNode.disconnect(),this.track=i,this.isCurrentTrackCloned=!1;const o=new MediaStream([i]);this.sourceNode=this.context.createMediaStreamSource(o),aI(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(lS.UPDATE_SOURCE),this.audioElement.srcObject=o}destroy(){var i;this.audioElement.srcObject=null,this.audioElement.remove(),__.off("state-change",this.rebuildWebAudio),(i=this.originVolumeLevelAnalyser)===null||i===void 0||i.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(i){return this.context.createMediaStreamSource(new MediaStream([i]))}updateOriginTrack(i){const o=i.clone();o.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=o),Gi.debug("create an unmuted track ".concat(o.id," from the original track ").concat(i.id," to get the volume"));const p=this.context.createMediaStreamSource(new MediaStream([o]));aI(p),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(p)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}async function V6(l,i,o){const p=(b,A)=>b?typeof b!="number"?b.max||b.exact||b.ideal||b.min||A:b:A,g={audio:!!o&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:l,maxHeight:p(i.height,1080),maxWidth:p(i.width,1920)}}};return i.frameRate&&typeof i.frameRate!="number"?(g.video.mandatory.maxFrameRate=i.frameRate.max,g.video.mandatory.minFrameRate=i.frameRate.min):typeof i.frameRate=="number"&&(g.video.mandatory.maxFrameRate=i.frameRate),await navigator.mediaDevices.getUserMedia(g)}async function ttt(l,i){const o=await B6(l.mediaSource),{sourceId:p,audio:g}=await function(b){let A=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new pE((j,H)=>{const z=document.createElement("div");z.innerText="share screen",z.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");const $=document.createElement("div");$.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const Vt=document.createElement("div");Vt.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",Vt.setAttribute("style","height: 12%;");const _r=document.createElement("div");_r.setAttribute("style","width: 100%; height: 80%; background: #FFF; border: solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const Fi=document.createElement("div");Fi.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");const _l=document.createElement("button");_l.innerHTML="cancel",_l.setAttribute("style","width: 85px;"),_l.onclick=()=>{document.body.removeChild(_g);const eE=new Error("NotAllowedError");eE.name="NotAllowedError",H(eE)};let _u=A;const _h=document.createElement("div");if(A){const eE=document.createElement("input");eE.setAttribute("type","checkbox");const oE=document.createElement("span");eE.setAttribute("style","margin-right: 6px;"),oE.innerText="Share audio",eE.checked=_u,eE.onchange=()=>{_u=eE.checked},_h.appendChild(eE),_h.appendChild(oE)}Fi.appendChild(_h),Fi.appendChild(_l),$.appendChild(Vt),$.appendChild(_r),$.appendChild(Fi);const _g=document.createElement("div");_g.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%);"),_g.appendChild(z),_g.appendChild($),document.body.appendChild(_g),b.map(eE=>{if(eE.id){const oE=document.createElement("div");oE.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let SE=eE.thumbnail;try{const{width:vE}=SE.getSize();vE>1920&&(SE=SE.resize({width:1920}))}catch(vE){throw vE&&vE.message.startsWith("Illegal invocation")&&console.error("Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)"),vE}oE.innerHTML='
'+eE.name.replace(/[\u00A0-\u9999<>\&]/g,function(vE){return"&#"+vE.charCodeAt(0)+";"})+"",oE.onclick=()=>{document.body.removeChild(_g),j({sourceId:eE.id,audio:_u})},_r.appendChild(oE)}})})}(o,i);return await V6(p,l,g)}async function B6(l){let i=["window","screen"];l!=="application"&&l!=="window"||(i=["window"]),l==="screen"&&(i=["screen"]);const o=QV();if(!o)throw console.error("failed to fetch electron, please mount it to window"),new yE(_p.ELECTRON_IS_NULL);let p=null;try{var g;p=((g=o.desktopCapturer)===null||g===void 0?void 0:g.getSources({types:i}))||o.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:i})}catch{p=null}p&&p.then||(p=new pE((b,A)=>{o.desktopCapturer.getSources({types:i},(j,H)=>{j?A(j):b(H)})}));try{return await p}catch(b){throw new yE(_p.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,b.toString())}}function G6(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}const PM=new E0("safari");let q6=!1,W6=!1;async function kS(l,i){let o=0,p=null;for(;o<2;)try{p=await ett(l,i,o>0);break}catch(g){if(g instanceof yE)throw Gi.error("[".concat(i,"] ").concat(g.toString())),g;const b=MN(g.name||g.code||g,g.message);if(b.code===_p.MEDIA_OPTION_INVALID){Gi.debug("[".concat(i,"] detect media option invalid, retry")),o+=1,await w0(500);continue}throw Gi.error("[".concat(i,"] ").concat(b.toString())),b}if(!p)throw new yE(_p.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return p}async function ett(l,i,o){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new yE(_p.NOT_SUPPORTED,"can not find getUserMedia");o&&(l.video&&(delete l.video.width,delete l.video.height),l.screen&&(delete l.screen.width,delete l.screen.height));const p=I_(),g=new MediaStream;if(l.audioSource&&g.addTrack(l.audioSource),l.videoSource&&g.addTrack(l.videoSource),!l.audio&&!l.video&&!l.screen)return Gi.debug("Using Video Source/ Audio Source"),g;if(l.screen)if(QV())l.screen.sourceId?_A(g,await V6(l.screen.sourceId,l.screen,l.screenAudio)):_A(g,await ttt(l.screen,l.screenAudio));else if(LL()&&l.screen.extensionId&&l.screen.mandatory){if(!p.getStreamFromExtension)throw new yE(_p.NOT_SUPPORTED,"This browser does not support screen sharing");Gi.debug("[".concat(i,'] Screen access on chrome stable, looking for extension"'));const _r=await(A=l.screen.extensionId,j=i,new pE((Fi,_l)=>{try{chrome.runtime.sendMessage(A,{getStream:!0},_u=>{if(!_u||!_u.streamId)return Gi.error("[".concat(j,"] No response from Chrome Plugin. Plugin not installed properly"),_u),void _l(new yE(_p.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));Fi(_u.streamId)})}catch(_u){Gi.error("[".concat(j,"] AgoraRTC screensharing plugin is not accessible(").concat(A,")"),_u.toString()),_l(new yE(_p.CHROME_PLUGIN_NOT_INSTALL))}}));l.screen.mandatory.chromeMediaSourceId=_r,_A(g,await navigator.mediaDevices.getUserMedia({video:{mandatory:l.screen.mandatory}}))}else if(p.getDisplayMedia){var b;l.screen.mediaSource&&P6(l.screen.mediaSource);const _r={width:l.screen.width,height:l.screen.height,frameRate:l.screen.frameRate,displaySurface:(b=l.screen.displaySurface)!==null&&b!==void 0?b:l.screen.mediaSource==="screen"?"monitor":l.screen.mediaSource},{selfBrowserSurface:Fi,surfaceSwitching:_l,systemAudio:_u}=l.screen,_h={selfBrowserSurface:Fi,surfaceSwitching:_l,systemAudio:_u};!Fi&&delete _h.selfBrowserSurface,!_l&&delete _h.surfaceSwitching,!_u&&delete _h.systemAudio,Gi.debug("[".concat(i,"] getDisplayMedia:"),JSON.stringify({video:_r,audio:!!l.screenAudio,controls:_h}));const _g=await navigator.mediaDevices.getDisplayMedia(function(eE){for(var oE=1;oE{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval(()=>{(nE("ENUMERATE_DEVICES_INTERVAL")||(uN()||aN()===l0.HARMONY_OS)&&dR())&&this.updateDevicesInfo()},nE("ENUMERATE_DEVICES_INTERVAL_TIME"))}).catch(l=>Gi.error(l.toString()))}async enumerateDevices(l,i){let o=arguments.length>2&&arguments[2]!==void 0&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)return new yE(_p.NOT_SUPPORTED,"enumerateDevices() not supported.").throw();const p=await navigator.mediaDevices.enumerateDevices(),g=this.checkMediaDeviceInfoIsOk(p);let b=!this.isAccessMicrophonePermission&&l,A=!this.isAccessCameraPermission&&i;g.audio&&(b=!1),g.video&&(A=!1);let j=null,H=null,z=null;if(!o&&(b||A)){if(PM.isLocked&&(Gi.debug("[device manager] wait GUM lock"),(await PM.lock())(),Gi.debug("[device manager] GUM unlock")),q6&&(b=!1,this.isAccessMicrophonePermission=!0),W6&&(A=!1,this.isAccessCameraPermission=!0),Gi.debug("[device manager] check media device permissions",l,i,b,A),b&&A){try{z=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch($){const Vt=MN($.name||$.code||$,$.message);if(Vt.code===_p.PERMISSION_DENIED)throw Vt;Gi.warning("getUserMedia failed in getDevices",Vt)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(b){try{j=await navigator.mediaDevices.getUserMedia({audio:l})}catch($){const Vt=MN($.name||$.code||$,$.message);if(Vt.code===_p.PERMISSION_DENIED)throw Vt;Gi.warning("getUserMedia failed in getDevices",Vt)}this.isAccessMicrophonePermission=!0}else if(A){try{H=await navigator.mediaDevices.getUserMedia({video:i})}catch($){const Vt=MN($.name||$.code||$,$.message);if(Vt.code===_p.PERMISSION_DENIED)throw Vt;Gi.warning("getUserMedia failed in getDevices",Vt)}this.isAccessCameraPermission=!0}Gi.debug("[device manager] mic permission",l,"cam permission",i)}try{const $=await navigator.mediaDevices.enumerateDevices();return j&&j.getTracks().forEach(Vt=>Vt.stop()),H&&H.getTracks().forEach(Vt=>Vt.stop()),z&&z.getTracks().forEach(Vt=>Vt.stop()),j=null,H=null,z=null,$}catch($){return j&&j.getTracks().forEach(Vt=>Vt.stop()),H&&H.getTracks().forEach(Vt=>Vt.stop()),z&&z.getTracks().forEach(Vt=>Vt.stop()),j=null,H=null,z=null,new yE(_p.ENUMERATE_DEVICES_FAILED,$.toString()).throw()}}async getRecordingDevices(){let l=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return(await this.enumerateDevices(!0,!1,l)).filter(i=>i.kind==="audioinput")}async getCamerasDevices(){let l=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return(await this.enumerateDevices(!1,!0,l)).filter(i=>i.kind==="videoinput")}async getSpeakers(){let l=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return(await this.enumerateDevices(!0,!1,l)).filter(i=>i.kind==="audiooutput")}searchDeviceIdByName(l){let i=null;return this.deviceInfoMap.forEach(o=>{o.device.label===l&&(i=o.device.deviceId)}),i}async getDeviceById(l){const i=(await this.enumerateDevices(!0,!0,!0)).find(o=>o.deviceId===l);if(!i)throw new yE(_p.DEVICE_NOT_FOUND,"deviceId: ".concat(l));return i}async init(){this.state=oI.INITING;try{await this.updateDevicesInfo(),this.state=oI.INITEND}catch(l){throw Gi.warning("Device Detection functionality cannot start properly.",l.toString()),this.state=oI.IDLE,!(typeof isSecureContext=="boolean"?isSecureContext:location.protocol==="https:"||location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"||location.hostname==="::1")&&new yE(_p.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw(),l}}async updateDevicesInfo(){const l=await this.enumerateDevices(!0,!0,!0),i=Date.now(),o=[];if(l[0]&&l[0].label&&this.checkdeviceMatched===!1){this.checkdeviceMatched=!0;const g=l.find(A=>A.kind==="audioinput"&&A.deviceId==="default"),b=l.find(A=>A.kind==="audiooutput"&&A.deviceId==="default");g&&b?b.groupId===g.groupId?Gi.debug("[device-check] default input ".concat(g.label," and output ").concat(b.label," is the same group")):Gi.warning("[device-check] default input ".concat(g.label," and output ").concat(b.label," is not the same group")):Gi.debug("[device-check] default input or output not found")}const p=this.checkMediaDeviceInfoIsOk(l);if(l.forEach(g=>{if(!g.deviceId)return;const b=this.deviceInfoMap.get("".concat(g.kind,"_").concat(g.deviceId));if((b?b.state:"INACTIVE")!=="ACTIVE"){const A={initAt:i,updateAt:i,device:g,state:"ACTIVE"};this.deviceInfoMap.set("".concat(g.kind,"_").concat(g.deviceId),A),o.push(A)}b&&(b.updateAt=i)}),this.deviceInfoMap.forEach((g,b)=>{g.state==="ACTIVE"&&g.updateAt!==i&&(g.state="INACTIVE",o.push(g))}),this.state!==oI.INITEND)return p.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(p.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));o.forEach(g=>{switch(g.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(XT.RECORDING_DEVICE_CHANGED,g);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(XT.CAMERA_DEVICE_CHANGED,g);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(XT.PLAYOUT_DEVICE_CHANGED,g)}}),p.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),p.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(l){const i=l.filter(g=>g.kind==="audioinput"),o=l.filter(g=>g.kind==="videoinput"),p={audio:!1,video:!1};for(const g of i)if(g.label&&g.deviceId){p.audio=!0;break}for(const g of o)if(g.label&&g.deviceId){p.video=!0;break}return p}};let kM=!1;const LS=new class extends D_{constructor(){super(...arguments),_e(this,"onAutoplayFailed",void 0),_e(this,"onAudioAutoplayFailed",void 0)}};function H6(){if(l_(),!kM){const l=i=>{i.preventDefault(),kM=!1,FO()?document.body.removeEventListener("click",l,!0):(document.body.removeEventListener("touchstart",l,!0),document.body.removeEventListener("mousedown",l,!0))};kM=!0,FO()?document.body.addEventListener("click",l,!0):(document.body.addEventListener("touchstart",l,!0),document.body.addEventListener("mousedown",l,!0)),Gi.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),LS.onAutoplayFailed?LS.onAutoplayFailed():LS.onAudioAutoplayFailed?Gi.warning(`AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed. + + Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web .`):Gi.warning(`We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet. + + It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences. + + Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web .`),LS.emit("autoplay-failed")}}function z6(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function K6(l){for(var i=1;i{Array.from(this.elementMap.entries()).forEach(l=>{let[i,o]=l;const p=this.elementStateMap.get(i),g=o.srcObject.getAudioTracks()[0];FI()?g&&g.readyState==="live"&&__.curState==="running"&&(Gi.debug("auto resume after interruption for iOS 15"),o.pause(),o.play()):p&&p==="paused"&&g&&g.readyState==="live"&&__.curState==="running"&&(Gi.debug("auto resume after interruption for iOS"),o.play())})}),_e(this,"autoResumeAfterInterruptionOnIOS15_16",()=>{Array.from(this.elementMap.entries()).forEach(l=>{let[i,o]=l;const p=o.srcObject.getAudioTracks()[0];p&&p.readyState==="live"&&(Gi.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),o.pause(),o.play())})}),this.autoResumeAudioElement(),__.on(_0.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),__.on(_0.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),__.on(_0.STATE_CHANGE,()=>{z0()&&__.prevState==="suspended"&&__.curState==="running"&&this.autoResumeAfterInterruption()})}async setSinkID(l,i){const o=this.elementMap.get(l);if(this.sinkIdMap.set(l,i),o)try{await o.setSinkId(i)}catch(p){throw new yE(_p.PERMISSION_DENIED,"can not set sink id: "+p.toString())}}play(l,i,o,p){if(this.elementMap.has(i))return;const g=document.createElement("audio");g.autoplay=!0,g.srcObject=new MediaStream([l]),this.bindAudioElementEvents(i,g),this.elementMap.set(i,g),this.elementStateMap.set(i,B0.INIT),this.setVolume(i,o);const b=this.sinkIdMap.get(i);if(b)try{g.setSinkId(b).catch(j=>{Gi.warning("[".concat(i,"] set sink id failed"),j.toString())})}catch(j){Gi.warning("[".concat(i,"] set sink id failed"),j.toString())}const A=g.play();A&&A.then&&A.catch(j=>{p&&Y6(p,"audio",j.message,i),Gi.warning("audio element play warning",j.toString()),this.elementMap.has(i)&&j.name==="NotAllowedError"&&(Gi.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(g),sT(()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),H6()}))})}updateTrack(l,i){const o=this.elementMap.get(l);o&&(o.srcObject=new MediaStream([i]))}isPlaying(l){return this.elementMap.has(l)&&this.elementStateMap.get(l)==="playing"}setVolume(l,i){const o=this.elementMap.get(l);o&&(i=Math.max(0,Math.min(100,i)),o.volume=i/100)}stop(l){const i=this.elementMap.get(l);if(this.sinkIdMap.delete(l),!i)return;const o=this.elementsNeedToResume.indexOf(i);this.elementsNeedToResume.splice(o,1),i.srcObject=null,i.remove(),this.elementMap.delete(l),this.elementStateMap.delete(l)}bindAudioElementEvents(l,i){ntt.forEach(o=>{i.addEventListener(o,p=>{const g=this.elementStateMap.get(l),b=p.type==="pause"?"paused":p.type;if(Gi.debug("[".concat(l,"] audio-element-status change ").concat(g," => ").concat(b)),p.type==="error"){const A=i==null?void 0:i.error;A&&Gi.error("[".concat(l,"] media error, code: ").concat(A.code,", message: ").concat(A.message))}this.elementStateMap.set(l,b)})})}getPlayerState(l){return this.elementStateMap.get(l)||"uninit"}autoResumeAudioElement(){const l=()=>{this.elementsNeedToResume.forEach(i=>{i.play().then(o=>{Gi.debug("Auto resume audio element success")}).catch(o=>{Gi.warning("Auto resume audio element failed!",o)})}),this.elementsNeedToResume=[]};new pE(i=>{document.body?i():window.addEventListener("load",()=>i())}).then(()=>{FO()?document.body.addEventListener("click",l,!0):(document.body.addEventListener("touchstart",l,!0),document.body.addEventListener("mousedown",l,!0))})}};function H_(){return function(l,i,o){const p=o.value;return typeof p=="function"&&(o.value=function(){this._isClosed&&new yE(_p.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",Gi);for(var g=arguments.length,b=new Array(g),A=0;A{j.then(H).catch(z)}):j}),o}}function J6(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function UN(l){for(var i=1;ig.processorID===i.ID&&g.processorName===i.name&&g.type===o)||this.statsRegistry.push({processorName:i.name,processorID:i.ID,type:o,cb:p})}unregisterStats(i,o){const p=this.statsRegistry.findIndex(g=>g.processorID===i.ID&&g.processorName===i.name&&g.type===o);p!==-1&&this.statsRegistry.splice(p,1)}gatherStats(){const i=[];for(const{processorID:o,processorName:p,type:g,cb:b}of this.statsRegistry)try{const A=b();i.push({processorID:o,processorName:p,type:g,stats:A})}catch(A){Gi.error(new yE(_p.UNEXPECTED_ERROR,A.message))}return i}registerUsage(i,o){this.usageRegistry.find(p=>p.processorID===i.ID&&p.processorName===i.name)||this.usageRegistry.push({processorID:i.ID,processorName:i.name,cb:o})}unregisterUsage(i){const o=this.usageRegistry.findIndex(p=>p.processorID===i.ID&&p.processorName===i.name);o!==-1&&this.usageRegistry.splice(o,1)}async gatherUsage(){const i=[];if(!this.chained)return[];for(const{cb:o}of this.usageRegistry)try{let p=o();p instanceof pE&&(p=await p),i.push(UN(UN({},p),{},{direction:this.direction}))}catch(p){Gi.error("gather extension usage error",p)}return i}getDirection(){return this.direction}}class FN extends D_{constructor(i){super(),_e(this,"name","AudioProcessorDestination"),_e(this,"ID","0"),_e(this,"inputTrack",void 0),_e(this,"inputNode",void 0),_e(this,"audioProcessorContext",void 0),_e(this,"_source",void 0),this.audioProcessorContext=i}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new yE(_p.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new yE(_p.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(V0.ON_TRACK,void 0),this.emit(V0.ON_NODE,void 0)}updateInput(i){if(i.context!==this.audioProcessorContext)throw new Error(`ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context. + Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).`);i.track&&this.inputTrack!==i.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=i.track,this.emit(V0.ON_TRACK,this.inputTrack)),i.node&&this.inputNode!==i.node&&(this.audioProcessorContext.chained=!0,this.inputNode=i.node,this.emit(V0.ON_NODE,this.inputNode))}}class jN extends D_{set chained(i){this._chained=i}get chained(){return this._chained}constructor(i,o,p){super(),_e(this,"constraintsMap",new Map),_e(this,"statsRegistry",[]),_e(this,"audioContext",void 0),_e(this,"trackId",void 0),_e(this,"direction",void 0),_e(this,"usageRegistry",[]),_e(this,"_chained",!1),this.audioContext=i,this.trackId=o,this.direction=p}async getConstraints(){return U_(this,dS.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(i,o){var p;return Gi.info("processor ".concat(o.name," requestApplyConstraints for ").concat(this.trackId)),i&&this.constraintsMap.set(o,i),S_(this,dS.REQUEST_UPDATE_CONSTRAINTS,Array.from(OT(p=this.constraintsMap).call(p)))}async requestRevertConstraints(i){var o;if(this.constraintsMap.has(i))return this.constraintsMap.delete(i),S_(this,dS.REQUEST_UPDATE_CONSTRAINTS,Array.from(OT(o=this.constraintsMap).call(o)))}registerStats(i,o,p){this.statsRegistry.find(g=>g.processorID===i.ID&&g.processorName===i.name&&g.type===o)||this.statsRegistry.push({processorName:i.name,processorID:i.ID,type:o,cb:p})}unregisterStats(i,o){const p=this.statsRegistry.findIndex(g=>g.processorID===i.ID&&g.processorName===i.name&&g.type===o);p!==-1&&this.statsRegistry.splice(p,1)}gatherStats(){const i=[];for(const{processorID:o,processorName:p,type:g,cb:b}of this.statsRegistry)try{const A=b();i.push({processorID:o,processorName:p,type:g,stats:A})}catch(A){Gi.error(new yE(_p.UNEXPECTED_ERROR,A.message))}return i}registerUsage(i,o){this.usageRegistry.find(p=>p.processorID===i.ID&&p.processorName===i.name)||this.usageRegistry.push({processorID:i.ID,processorName:i.name,cb:o})}unregisterUsage(i){const o=this.usageRegistry.findIndex(p=>p.processorID===i.ID&&p.processorName===i.name);o!==-1&&this.usageRegistry.splice(o,1)}async gatherUsage(){const i=[];if(!this.chained)return[];for(const{cb:o}of this.usageRegistry)try{let p=o();p instanceof pE&&(p=await p),i.push(UN(UN({},p),{},{direction:this.direction}))}catch(p){Gi.error("gather extension usage error",p)}return i}getDirection(){return this.direction}}class DM extends D_{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),_e(this,"context",void 0),_e(this,"processSourceNode",void 0),_e(this,"outputTrack",void 0),_e(this,"processedNode",void 0),_e(this,"clonedTrack",void 0),_e(this,"outputNode",void 0),this.outputNode=new rtt}setVolume(){}createOutputTrack(){throw new yE(_p.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class rtt{disconnect(){}connect(){}}let tO=null;class itt{constructor(){_e(this,"state","open"),_e(this,"trigger",void 0),_e(this,"tasks",[]),Gi.debug("[macro-task-queue] is created."),this.trigger=window.setTimeout(()=>{this.state="closed",Gi.debug("[macro-task-queue] will be closed, all remaining tasks will execute. [".concat(this.tasks.map(i=>i.key),"]")),this.trigger=void 0,this.tasks.forEach(i=>{let{func:o}=i;return o()}),this.tasks.length=0,Gi.debug("[macro-task-queue] is closed.")})}enqueue(i,o){this.state!=="closed"&&(this.tasks.push({key:i,func:o}),Gi.debug("[macro-task-queue] is queued, current queue ".concat(this.tasks.length,". ").concat(typeof i=="string"?i:"")))}runTask(i){if(this.state==="closed")return;const o=this.tasks.findIndex(p=>p.key===i);if(o!==-1){const p=this.tasks.splice(o,1);Gi.debug("[macro-task-queue] is unqueued, current queue ".concat(this.tasks.length,". ").concat(typeof i=="string"?i:"")),p[0].func()}}release(){this.trigger&&(this.state="closed",clearTimeout(this.trigger),this.trigger=void 0,this.tasks.length=0,Gi.debug("[macro-task-queue] is closed."))}}function LM(l){return function(i,o,p){var g;const b=(g=p.value)!==null&&g!==void 0?g:p.get,A=function(){tO&&tO.state==="open"&&tO.runTask(l);for(var j=arguments.length,H=new Array(j),z=0;z{this.processorContext=new jN(this._source.context,this.getTrackId(),"local"),this.processorDestination=new FN(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(lS.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})})},j=b&&H0()&&!U6();nE("DISABLE_WEBAUDIO")?(this._source=new DM,this._useAudioElement=!0,this._bypassWebAudio=!0):j?this._source=new DM:(this._source=new NM(i,!1,this._getOriginVolumeLevel?i:void 0),nE("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")||(this._useAudioElement=!0)),A(),!nE("DISABLE_WEBAUDIO")&&j&&(tO||(tO=new itt),tO).enqueue("INIT_WEBAUDIO",()=>{this._source=new NM(i,!1,this._getOriginVolumeLevel?i:void 0),nE("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")||(this._useAudioElement=!0),A(),this.emit(xN.UPDATE_TRACK_SOURCE)})}setVolume(i){b_(i,"volume",0,1e3),this._volume=i,this._source.setVolume(i/100),this._useAudioElement&&vS.setVolume(this.getTrackId(),i);try{if(this._bypassWebAudio)return void Gi.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const o=this._source.createOutputTrack();this._mediaStreamTrack!==o&&(this._mediaStreamTrack=o,S_(this,xE.NEED_REPLACE_TRACK,this).then(()=>{Gi.debug("[".concat(this.getTrackId(),"] replace web audio track success"))}).catch(p=>{Gi.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),p)}))}catch{}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel()}async setPlaybackDevice(i){if(!this._useAudioElement)throw new yE(_p.NOT_SUPPORTED,"your browser does not support setting the audio output device");await vS.setSinkID(this.getTrackId(),i)}async setEnabled(i,o,p){return this._setEnabled(i,o,p)}async _setEnabled(i,o,p){if(!p){if(i===this._enabled)return;this.stateCheck("enabled",i)}if(Gi.info("[".concat(this.getTrackId(),"] start setEnabled"),i),i){this._originMediaStreamTrack.enabled=!0;try{p||(this._enabled=!0),await S_(this,xE.NEED_ENABLE_TRACK,this),Gi.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(i," success"))}catch(g){throw p||(this._enabled=!1),Gi.error("[".concat(this.getTrackId(),"] setEnabled to true error"),g.toString()),g}}else{this._originMediaStreamTrack.enabled=!1,p||(this._enabled=!1);try{await S_(this,xE.NEED_DISABLE_TRACK,this)}catch(g){throw p||(this._enabled=!0),Gi.error("[".concat(this.getTrackId(),"] setEnabled to false error"),g.toString()),g}}}async setMuted(i){i!==this._muted&&(this.stateCheck("muted",i),this._muted=i,this._originMediaStreamTrack.enabled=!i,Gi.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(i)),i?await S_(this,xE.NEED_MUTE_TRACK,this):await S_(this,xE.NEED_UNMUTE_TRACK,this))}getStats(){return VO(()=>{Gi.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")},"localAudioTrackGetStatsWarning"),oS(this,xE.GET_STATS)||xM({},CM)}setAudioFrameCallback(i){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:4096;if(!i)return this._source.removeAllListeners(lS.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(o),this._source.removeAllListeners(lS.ON_AUDIO_BUFFER),this._source.on(lS.ON_AUDIO_BUFFER,p=>i(p))}play(){Gi.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(Gi.debug("[".concat(this.getTrackId(),"] start audio playback in element")),vS.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){Gi.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?vS.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe(),this._source.destroy()}_updatePlayerSource(){let i=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];Gi.debug("[".concat(this.getTrackId(),"] update player source track")),i&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&vS.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(i,o){this._originMediaStreamTrack!==i&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),o&&this._originMediaStreamTrack.stop()),i.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=i,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this.processor.updateInput({track:i,context:this.processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await S_(this,xE.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(i))}renewMediaStreamTrack(i){return pE.resolve(void 0)}pipe(i){if(this._bypassWebAudio)throw new yE(_p.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===i)return i;if(i._source)throw new yE(_p.INVALID_OPERATION,"Processor ".concat(i.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=i,this.processor._source=this,i.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),i}unpipe(){var i;if(!this.processor)return;const o=this.processor;(i=this._source.processSourceNode)===null||i===void 0||i.disconnect(),this.processor._source=!1,this.processor=void 0,o.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(V0.ON_TRACK,async i=>{i?i!==this._mediaStreamTrack&&(this._mediaStreamTrack=i,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(i),await S_(this,xE.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await S_(this,xE.NEED_REPLACE_TRACK,this))}),this.processorDestination.on(V0.ON_NODE,i=>{this._source.processedNode=i})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(V0.ON_TRACK),this.processorDestination.removeAllListeners(V0.ON_NODE)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(dS.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(dS.REQUEST_CONSTRAINTS)}}bE([LM("INIT_WEBAUDIO"),kc("design:type",Object),kc("design:paramtypes",[Object])],g_.prototype,"_source",null),bE([LM("INIT_WEBAUDIO"),kc("design:type",jN),kc("design:paramtypes",[jN])],g_.prototype,"processorContext",null),bE([LM("INIT_WEBAUDIO"),kc("design:type",FN),kc("design:paramtypes",[FN])],g_.prototype,"processorDestination",null),bE([HE({argsMap:(l,i)=>[l.getTrackId(),i],throttleTime:300}),kc("design:type",Function),kc("design:paramtypes",[Number]),kc("design:returntype",void 0)],g_.prototype,"setVolume",null),bE([HE({argsMap:(l,i)=>[l.getTrackId(),i]}),H_(),kc("design:type",Function),kc("design:paramtypes",[String]),kc("design:returntype",pE)],g_.prototype,"setPlaybackDevice",null),bE([GI("LocalAudioTrack","_enabledMutex"),HE({argsMap:(l,i)=>[l.getTrackId(),i]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Boolean,Object,Boolean]),kc("design:returntype",pE)],g_.prototype,"setEnabled",null),bE([GI("LocalAudioTrack","_enabledMutex"),HE({argsMap:(l,i)=>[l.getTrackId(),i]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Boolean]),kc("design:returntype",pE)],g_.prototype,"setMuted",null),bE([H_(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",Object)],g_.prototype,"getStats",null),bE([H_(),kc("design:type",Function),kc("design:paramtypes",[Object,Number]),kc("design:returntype",void 0)],g_.prototype,"setAudioFrameCallback",null),bE([HE({argsMap:l=>[l.getTrackId()]}),H_(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],g_.prototype,"play",null),bE([HE({argsMap:l=>[l.getTrackId()]}),H_(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],g_.prototype,"stop",null),bE([HE({argsMap:l=>[l.getTrackId()]}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],g_.prototype,"close",null),bE([HE({argsMap:(l,i)=>[l.getTrackId(),i.name]}),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",Object)],g_.prototype,"pipe",null),bE([HE({argsMap:l=>[l.getTrackId()]}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],g_.prototype,"unpipe",null);class yR extends g_{get __className__(){return"MicrophoneAudioTrack"}constructor(i,o,p,g){super(i,o.encoderConfig?DN(o.encoderConfig):{},g,nE("GET_VOLUME_OF_MUTED_AUDIO_TRACK"),!0),_e(this,"_config",void 0),_e(this,"_deviceName","default"),_e(this,"_constraints",void 0),_e(this,"_originalConstraints",void 0),_e(this,"_enabled",!0),this._config=o,this._constraints=p,this._originalConstraints=p,this._deviceName=i.label,typeof o.bypassWebAudio=="boolean"&&(this._bypassWebAudio=o.bypassWebAudio),(FI()||ML())&&__.bindInterruptDetectorTrack(this),this.on(xN.UPDATE_TRACK_SOURCE,()=>{this.bindProcessorContextEvents()}),U6()&&this.bindProcessorContextEvents()}async setDevice(i){if(Gi.info("[".concat(this.getTrackId(),"] start set device to ").concat(i)),this._enabled)try{const o=await DS.getDeviceById(i),p={};p.audio=xM({},this._constraints),p.audio.deviceId={exact:i},this._originMediaStreamTrack.stop();let g=null;try{g=await kS(p,this.getTrackId())}catch(b){throw Gi.error("[".concat(this.getTrackId(),"] setDevice failed"),b.toString()),g=await kS({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(g.getAudioTracks()[0],!1),b}await this._updateOriginMediaStreamTrack(g.getAudioTracks()[0],!1),this._deviceName=o.label,this._config.microphoneId=i,this._constraints.deviceId={exact:i}}catch(o){throw Gi.error("[".concat(this.getTrackId(),"] setDevice error"),o.toString()),o}else try{const o=await DS.getDeviceById(i);this._deviceName=o.label,this._config.microphoneId=i,this._constraints.deviceId={exact:i}}catch(o){throw Gi.error("[".concat(this.getTrackId(),"] setDevice error"),o.toString()),o}Gi.info("[".concat(this.getTrackId(),"] set device to ").concat(i," success"))}async setEnabled(i,o,p){if(o)return Gi.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(i);if(!p){if(i===this._enabled)return;this.stateCheck("enabled",i)}if(Gi.info("[".concat(this.getTrackId(),"] start setEnabled"),i),!i){var g;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),(g=this._source.clonedTrack)===null||g===void 0||g.stop(),p||(this._enabled=!1);try{await S_(this,xE.NEED_DISABLE_TRACK,this)}catch(j){throw Gi.error("[".concat(this.getTrackId(),"] setEnabled false failed"),j.toString()),j}return}const b=xM({},this._constraints),A=DS.searchDeviceIdByName(this._deviceName);A&&!b.deviceId&&(b.deviceId=A);try{p||(this._enabled=!0);const j=await kS({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(j.getAudioTracks()[0],!1),await S_(this,xE.NEED_ENABLE_TRACK,this)}catch(j){throw p||(this._enabled=!1),Gi.error("[".concat(this.getTrackId(),"] setEnabled true failed"),j.toString()),j}Gi.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(FI()||ML())&&__.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((z0()||wT())&&this._enabled&&!this._isClosed&&__.duringInterruption){const i=async()=>{__.off(_0.IOS_INTERRUPTION_END,i),this._enabled&&!this._isClosed&&(Gi.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};__.on(_0.IOS_INTERRUPTION_END,i)}else Gi.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(_R.TRACK_ENDED)}async renewMediaStreamTrack(i){const o=i||this._constraints,p=DS.searchDeviceIdByName(this._deviceName);if(p&&!o.deviceId&&(o.deviceId=p),this._constraints=o,this._enabled){this._originMediaStreamTrack.stop();const g=await kS({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(g.getAudioTracks()[0],!0)}}bindProcessorContextEvents(){this.processorContext.on(dS.REQUEST_UPDATE_CONSTRAINTS,async(i,o,p)=>{try{const g=Object.assign({},this._originalConstraints,...i);await this.renewMediaStreamTrack(g),o()}catch(g){p(g)}}),this.processorContext.on(dS.REQUEST_CONSTRAINTS,async i=>{i(this._originMediaStreamTrack.getSettings())})}}bE([HE({argsMap:(l,i)=>[l.getTrackId(),i]}),H_(),kc("design:type",Function),kc("design:paramtypes",[String]),kc("design:returntype",pE)],yR.prototype,"setDevice",null),bE([GI("MicrophoneAudioTrack","_enabledMutex"),HE({argsMap:(l,i,o)=>[l.getTrackId(),i,o]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Boolean,Boolean,Boolean]),kc("design:returntype",pE)],yR.prototype,"setEnabled",null),bE([HE({argsMap:l=>[l.getTrackId()]}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],yR.prototype,"close",null);class bR extends g_{get __className__(){return"BufferSourceAudioTrack"}constructor(i,o,p,g){super(o.createOutputTrack(),p,g),_e(this,"source",void 0),_e(this,"_bufferSource",void 0),this.source=i,this._bufferSource=o,this._bufferSource.on(lS.AUDIO_SOURCE_STATE_CHANGE,b=>{this.safeEmit(_R.SOURCE_STATE_CHANGE,b)});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(i){i&&this._bufferSource.updateOptions(i),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(i){this._bufferSource.seekAudioBuffer(i)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(i){b_(i,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(i)}}bE([HE({argsMap:(l,i)=>[l.getTrackId(),i,l.duration]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",void 0)],bR.prototype,"startProcessAudioBuffer",null),bE([HE({argsMap:l=>[l.getTrackId()]}),H_(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],bR.prototype,"pauseProcessAudioBuffer",null),bE([HE({argsMap:l=>[l.getTrackId()]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Number]),kc("design:returntype",void 0)],bR.prototype,"seekAudioBuffer",null),bE([HE({argsMap:l=>[l.getTrackId()]}),H_(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],bR.prototype,"resumeProcessAudioBuffer",null),bE([HE({argsMap:l=>[l.getTrackId()]}),H_(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],bR.prototype,"stopProcessAudioBuffer",null),bE([HE({argsMap:l=>[l.getTrackId()]}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],bR.prototype,"close",null),bE([HE({argsMap:l=>[l.getTrackId()]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Number]),kc("design:returntype",void 0)],bR.prototype,"setAudioBufferPlaybackSpeed",null);class Z_ extends g_{get __className__(){return"MixingAudioTrack"}get isActive(){for(const i of this.trackList)if(i._enabled&&!i._isClosed&&!i.muted)return!0;return!1}constructor(){const i=_w().createMediaStreamDestination();super(i.stream.getAudioTracks()[0],void 0,T_(8,"track-mix-")),_e(this,"trackList",void 0),_e(this,"destNode",void 0);try{this._mediaStreamTrack=this._source.createOutputTrack()}catch{}this.destNode=i,this.trackList=[]}hasAudioTrack(i){return this.trackList.indexOf(i)!==-1}addAudioTrack(i){this.trackList.indexOf(i)===-1?(Gi.debug("add ".concat(i.getTrackId()," to mixing track")),i._source.outputNode.connect(this.destNode),this.trackList.push(i),this.updateEncoderConfig()):Gi.debug("track ".concat(i.getTrackId()," is already added"))}removeAudioTrack(i){if(this.trackList.indexOf(i)!==-1){Gi.debug("remove ".concat(i.getTrackId()," from mixing track"));try{i._source.outputNode.disconnect(this.destNode)}catch{}VL(this.trackList,i),this.updateEncoderConfig()}}updateEncoderConfig(){const i={};this.trackList.forEach(o=>{o._encoderConfig&&((o._encoderConfig.bitrate||0)>(i.bitrate||0)&&(i.bitrate=o._encoderConfig.bitrate),(o._encoderConfig.sampleRate||0)>(i.sampleRate||0)&&(i.sampleRate=o._encoderConfig.sampleRate),(o._encoderConfig.sampleSize||0)>(i.sampleSize||0)&&(i.sampleSize=o._encoderConfig.sampleSize),o._encoderConfig.stereo&&(i.stereo=!0))}),this._encoderConfig=i}_updateRtpTransceiver(i){this._rtpTransceiver!==i&&(this._rtpTransceiver=i,this.trackList.forEach(o=>{o instanceof Z_?o.emit($I.TRANSCEIVER_UPDATED,i):o._updateRtpTransceiver(i)}))}}function VN(l){const i={};l.facingMode&&(i.facingMode=l.facingMode),l.cameraId&&(i.deviceId={exact:l.cameraId});const o=kT(l.encoderConfig);return o.width!=null&&(i.width=o.width),o.height!=null&&(i.height=o.height),!HV()&&o.frameRate&&(i.frameRate=o.frameRate),l_().name===m_.EDGE&&typeof i.frameRate=="object"&&(i.frameRate.max=60),N_()&&(i.frameRate={ideal:30,max:30}),i}function Z6(l){const i={};if(HV()||(l.AGC!==void 0&&(i.autoGainControl=l.AGC),l.AEC!==void 0&&(i.echoCancellation=l.AEC),l.ANS!==void 0&&(i.noiseSuppression=l.ANS,LL()&&l.ANS&&(i.googHighpassFilter=l.ANS))),l.encoderConfig){const o=DN(l.encoderConfig);i.channelCount=o.stereo?2:1,i.sampleRate=o.sampleRate,i.sampleSize=o.sampleSize}return l.microphoneId&&(i.deviceId={exact:l.microphoneId}),uN()&&(i.sampleRate=void 0),i}class stt extends j6{set currentState(i){i!==this._currentState&&(this._currentState=i,this.safeEmit(lS.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}constructor(i){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),_e(this,"audioBuffer",void 0),_e(this,"sourceNode",void 0),_e(this,"startPlayTime",0),_e(this,"startPlayOffset",0),_e(this,"pausePlayTime",0),_e(this,"options",void 0),_e(this,"currentLoopCount",0),_e(this,"currentPlaybackSpeed",100),_e(this,"_currentState","stopped"),this.audioBuffer=i,this.options=o,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(i){this.currentState==="stopped"?(this.options=i,this.startPlayOffset=this.options.startPlayTime||0):Gi.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(i){this.sourceNode&&(this.sourceNode.onended=null,this.currentState==="playing"&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),this.currentState==="playing"?(this.startPlayOffset=i,this.startSourceNode()):this.currentState==="paused"&&(this.pausePlayTime=i))}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(i){this.sourceNode&&(this.currentState==="playing"&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=i/100),this.currentPlaybackSpeed=i}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 i=this.context.createBufferSource();return i.buffer=this.audioBuffer,i.loop=!!this.options.loop,i.connect(this.outputNode),i.playbackRate.value=this.currentPlaybackSpeed/100,i}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 t4=new Map;async function ott(l,i){let o=null;if(typeof l=="string"){const g=t4.get(l);if(g)return Gi.debug("use cached audio resource: ",l),g;try{o=(await vT(()=>aS.get(l,{responseType:"arraybuffer"}),void 0,void 0,{maxRetryCount:3})).data}catch(b){throw new yE(_p.FETCH_AUDIO_FILE_FAILED,b.toString())}}else o=await new pE((b,A)=>{const j=new FileReader;j.onload=H=>{H.target?b(H.target.result):A(new yE(_p.READ_LOCAL_AUDIO_FILE_ERROR))},j.onerror=()=>{A(new yE(_p.READ_LOCAL_AUDIO_FILE_ERROR))},j.readAsArrayBuffer(l)});const p=await function(g){const b=_w();return new pE((A,j)=>{b.decodeAudioData(g,H=>{A(H)},H=>{j(new yE(_p.DECODE_AUDIO_FILE_FAILED,H.toString()))})})}(o);return typeof l=="string"&&i&&t4.set(l,p),p}const MM=l=>{const i=document.createElement("canvas");return i.width=2,i.height=2,new pE((o,p)=>{i.toBlob(async g=>{if(i.remove(),g){const b=await e4(g);o({buffer:b,width:i.width,height:i.height})}else p(new yE(_p.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))},l,1)})},e4=async l=>{const i=await l.arrayBuffer();return new Uint8Array(i)},QT=new class extends D_{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),_e(this,"_lastHiddenTime",0),_e(this,"_lastVisibleTime",0),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),Gi.debug("document visibility went ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)})}};function n4(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function r4(l){for(var i=1;i ").concat(i)),this._videoElementStatus=i)}constructor(i){_e(this,"trackId",void 0),_e(this,"config",void 0),_e(this,"onFirstVideoFrameDecoded",void 0),_e(this,"freezeTimeCounterList",[]),_e(this,"renderFreezeAccTime",0),_e(this,"isKeepLastFrame",!1),_e(this,"timeUpdatedCount",0),_e(this,"freezeTime",0),_e(this,"playbackTime",0),_e(this,"lastTimeUpdatedTime",0),_e(this,"autoplayFailed",!1),_e(this,"videoTrack",void 0),_e(this,"videoElement",void 0),_e(this,"cacheVideoElement",void 0),_e(this,"videoElementCheckInterval",void 0),_e(this,"_videoElementStatus",B0.NONE),_e(this,"isGettingVideoDimensions",!1),_e(this,"startGetVideoDimensions",()=>{const o=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return Gi.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(o,500)};!this.isGettingVideoDimensions&&o()}),_e(this,"autoResumeAfterInterruption",()=>{this.videoTrack&&this.videoTrack.readyState==="live"&&__.curState==="running"&&(Gi.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(FV())),qV()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))}),_e(this,"handleVideoEvents",o=>{switch(o.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=B0.PLAYING;break;case"loadeddata":if(this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch{}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=B0.CANPLAY;break;case"stalled":this.videoElementStatus=B0.STALLED;break;case"suspend":this.videoElementStatus=B0.SUSPEND;break;case"pause":this.videoElementStatus=B0.PAUSED,z0()||wT()||H0()&&this.autoplayFailed||!this.videoTrack||this.videoTrack.readyState!=="live"||(Gi.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=B0.WAITING;break;case"abort":this.videoElementStatus=B0.ABORT;break;case"ended":this.videoElementStatus=B0.ENDED;break;case"emptied":this.videoElementStatus=B0.EMPTIED;break;case"error":{this.videoElementStatus=B0.ERROR;const p=this.videoElement.error;p&&Gi.error("[".concat(this.trackId,"] media error, code: ").concat(p.code,", message: ").concat(p.message));break}case"timeupdate":{const p=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=p);const g=p-this.lastTimeUpdatedTime,b=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=p,QT.lastVisibleTimenE("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=g),this.playbackTime+=g;this.playbackTime>=6e3;){this.playbackTime-=6e3;const A=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(A),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}}),_e(this,"autoResumeAfterInterruptionOnIOS15_16",()=>{this.videoTrack&&this.videoTrack.readyState==="live"&&(Gi.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(FV())),qV()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))}),this.trackId=i.trackId,this.config=i,i.element instanceof HTMLVideoElement?this.videoElement=i.element:this.videoElement=document.createElement("video"),__.on(_0.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),__.on(_0.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var i;return(i=this.videoElement.parentElement)!==null&&i!==void 0?i:void 0}updateConfig(i){this.config=i,this.trackId=i.trackId,i.element!==this.videoElement&&(this.destroy(),this.videoElement=i.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(i){this.videoTrack!==i&&(this.videoTrack=i,this.initVideoElement())}play(i){const o=this.videoElement.play();o&&o.catch&&o.catch(g=>{i&&Y6(i,"video",g.message,this.trackId),g.name==="NotAllowedError"?(Gi.warning("detected video element autoplay failed",g),this.autoplayFailed=!0,this.handleAutoPlayFailed()):Gi.warning("[".concat(this.trackId,"] play warning: "),g)});const p=l_();if((p.name==="Safari"&&Number(p.version)===15||FI())&&o&&o.then){const g=()=>{this.config.mirror&&(this.videoElement.style.transform="rotateY(180deg)")};o.then(g).catch(g)}}getCurrentFrame(){const i=document.createElement("canvas");i.width=this.videoElement.videoWidth,i.height=this.videoElement.videoHeight;const o=i.getContext("2d");if(!o)return Gi.error("create canvas context failed!"),new ImageData(2,2);o.drawImage(this.videoElement,0,0,i.width,i.height);const p=o.getImageData(0,0,i.width,i.height);return i.remove(),p}async getCurrentFrameToUint8Array(i){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;const p=document.createElement("canvas");p.width=this.videoElement.videoWidth,p.height=this.videoElement.videoHeight;const g=p.getContext("2d");return g?(g.drawImage(this.videoElement,0,0,p.width,p.height),new pE((b,A)=>{p.toBlob(async j=>{if(p.remove(),j){const H=await e4(j);b({buffer:H,width:p.width,height:p.height})}else A(new yE(_p.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))},i,o<0?.1:o>1?1:o)})):await MM(i)}destroy(){__.off(_0.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),__.off(_0.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[]}initVideoElement(){if(this.videoElementStatus=B0.INIT,!this.videoElementCheckInterval&&(i4.forEach(b=>{this.videoElement.addEventListener(b,this.handleVideoEvents)}),this.videoElementCheckInterval=window.setInterval(()=>{(function(b){return b!==document.body&&document.body.contains(b)})(this.videoElement)||(this.videoElementStatus=B0.DESTROYED)},1e3),nE("ENABLE_VIDEO_FRAME_CALLBACK"))){var i,o;let b;const A=(j,H)=>{if(this.videoElementStatus===B0.PLAYING){if(b){const Vt=H.presentationTime-b.presentationTime;Vt>nE("VIDEO_FREEZE_DURATION")&&QT.lastVisibleTime>=QT.lastHiddenTime&&b.timestamp>QT.lastVisibleTime&&b.timestamp>QT.lastHiddenTime&&(this.renderFreezeAccTime+=Vt)}b=r4(r4({},H),{},{timestamp:j})}var z,$;nE("ENABLE_VIDEO_FRAME_CALLBACK")&&((z=($=this.videoElement).requestVideoFrameCallback)===null||z===void 0||z.call($,A))};(i=(o=this.videoElement).requestVideoFrameCallback)===null||i===void 0||i.call(o,A)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),uN()&&(this.videoElement.poster="noposter");const p=l_();p.name==="Safari"&&Number(p.version)===15||FI()||!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,N_()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,N_()&&this.videoElement.load());const g=this.videoElement.play();g!==void 0&&g.catch(b=>{Gi.debug("[".concat(this.trackId,"] playback interrupted"),b.toString())})}resetVideoElement(){i4.forEach(i=>{this.videoElement&&this.videoElement.removeEventListener(i,this.handleVideoEvents)}),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=B0.NONE}handleAutoPlayFailed(){const i=o=>{o.preventDefault(),this.videoElement.play().then(()=>{Gi.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))}).catch(p=>{Gi.error(p)}),this.autoplayFailed=!1,FO()?document.body.removeEventListener("click",i,!0):(document.body.removeEventListener("touchstart",i,!0),document.body.removeEventListener("mousedown",i,!0))};FO()?document.body.addEventListener("click",i,!0):(document.body.addEventListener("touchstart",i,!0),document.body.addEventListener("mousedown",i,!0)),H6()}}const i4=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class s4 extends UM{constructor(i){super(i),_e(this,"container",void 0),_e(this,"slot",void 0),this.slot=i.element,this.updateConfig(i)}updateConfig(i){this.config=i,this.trackId=i.trackId;const o=i.element;o!==this.slot&&(this.destroy(),this.slot=o),this.createElements()}updateVideoTrack(i){this.videoTrack!==i&&(this.videoTrack=i,this.createElements())}play(i){var o;(o=this.container)!==null&&o!==void 0&&o.contains(this.videoElement)&&super.play(i)}getCurrentFrame(){var i;return(i=this.container)!==null&&i!==void 0&&i.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(i){var o;let p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;return(o=this.container)!==null&&o!==void 0&&o.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(i,p):await MM(i)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch{}this.container=void 0}}createElements(){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",nE("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container)}mountedVideoElement(){var i;!this.container||(i=this.container)!==null&&i!==void 0&&i.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 i;if((i=this.container)!==null&&i!==void 0&&i.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch{}this.videoElement=document.createElement("video")}}resetVideoElement(){var i;(i=this.container)!==null&&i!==void 0&&i.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}}function o4(l){return new pE((i,o)=>{let p=!1;const g=document.createElement("video");g.setAttribute("autoplay",""),g.setAttribute("muted",""),g.muted=!0,g.autoplay=!0,g.setAttribute("playsinline",""),g.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(g);const b=z0()?"canplay":"playing";g.addEventListener(b,()=>{const A=g.videoWidth,j=g.videoHeight;!A&&N_()||(p=!0,g.srcObject=null,g.remove(),i([A,j]))}),g.srcObject=new MediaStream([l]),g.play().catch(pN),setTimeout(()=>{p||(g.srcObject=null,g.remove(),i([g.videoWidth,g.videoHeight]))},4e3)})}const att=async(l,i,o)=>{const p=function(A){const j=[];for(let H=0;H>8*OE+4&15)+j.charAt(PE>>8*OE&15);return $E}function z(PE,OE){const $E=(65535&PE)+(65535&OE);return(PE>>16)+(OE>>16)+($E>>16)<<16|65535&$E}function $(PE,OE,$E,s_,B_,r0){return z(function(P_,yS){return P_<>>32-yS}(z(z(OE,PE),z(s_,r0)),B_),$E)}function Vt(PE,OE,$E,s_,B_,r0,P_){return $(OE&$E|~OE&s_,PE,OE,B_,r0,P_)}function _r(PE,OE,$E,s_,B_,r0,P_){return $(OE&s_|$E&~s_,PE,OE,B_,r0,P_)}function Fi(PE,OE,$E,s_,B_,r0,P_){return $(OE^$E^s_,PE,OE,B_,r0,P_)}function _l(PE,OE,$E,s_,B_,r0,P_){return $($E^(OE|~s_),PE,OE,B_,r0,P_)}const _u=function(PE){let OE;const $E=1+(PE.length+8>>6),s_=new Array(16*$E);for(OE=0;OE<16*$E;OE++)s_[OE]=0;for(OE=0;OE>2]|=PE.charCodeAt(OE)<>2]|=128<await att(l.buffer,i,o);function c4(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function xS(l){for(var i=1;ithis._previousVideoVisibleStatus=void 0),_e(this,"_encoderConfig",void 0),_e(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),_e(this,"_optimizationMode",void 0),_e(this,"_videoHeight",void 0),_e(this,"_videoWidth",void 0),_e(this,"_forceBitrateLimit",void 0),_e(this,"_enabled",!0),_e(this,"processorDestination",void 0),_e(this,"_processorContext",void 0),H0()){const{width:j,height:H}=i.getSettings();this._videoWidth=j,this._videoHeight=H}else this.updateMediaStreamTrackResolution();if(this._encoderConfig=o,this._scalabilityMode=p,this._optimizationMode=g,this._hints=A||[],this._hints.indexOf(A_.SCREEN_TRACK)===-1)this.updateBitrateFromProfile();else if(function(j,H,z){const $=l_();return!($.name!==j||!$.osVersion)&&(z?Number($.version)>=H&&Number($.version)<=z:Number($.version)===H)}(m_.CHROME,115)&&aN().indexOf("Windows")!==-1){const j=function(H,z){if("VideoFrame"in window&&"TransformStream"in window&&I_().supportWebRTCInsertableStream){const $=new MediaStreamTrackProcessor(H),Vt=new MediaStreamTrackGenerator({kind:"video"});let _r,Fi,_l=Date.now();const _u=()=>{_h&&(clearInterval(_h),_h=void 0),_r&&(_r.close(),_r=void 0),H.stop(),Fi=void 0,Vt.removeEventListener("ended",_u)};let _h=window.setInterval(()=>{if(Fi&&_r&&Date.now()-_l>(z??1e3))try{Vt.readyState==="live"?Fi.enqueue(_r.clone()):_u()}catch{_u()}},z??1e3);const _g=new TransformStream({transform:(eE,oE)=>{Vt.readyState==="live"?(Fi=oE,_l=Date.now(),_r===void 0?(_r=eE,oE.enqueue(eE.clone())):(oE.enqueue(_r),_r=eE)):eE.close()}});return Vt.addEventListener("ended",_u),$.readable.pipeThrough(_g).pipeTo(Vt.writable),Vt}}(i);j&&(Gi.info("local screen video track begin to inject frame"),this._mediaStreamTrack=j)}o&&this._hints.indexOf(A_.CUSTOM_TRACK)!==-1&&this.setEncoderConfiguration(o),this.processorContext=new Q6(this.getTrackId(),"local"),this.processorDestination=new X6(this.processorContext),this.bindProcessorDestinationEvents()}play(i){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(typeof i=="string"){const g=document.getElementById(i);g?i=g:(Gi.warning("[".concat(this.getTrackId(),'] can not find "#').concat(i,'" element, use document.body')),i=document.body)}Gi.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(i instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(o));const p=xS(xS(xS({},this._getDefaultPlayerConfig()),o),{},{trackId:this.getTrackId(),element:i});this._player?this._player.updateConfig(p):(i instanceof HTMLVideoElement?this._player=new UM(p):this._player=new s4(p),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{const g=this.getVideoElementVisibleStatus();this.safeEmit(_R.VIDEO_ELEMENT_VISIBLE_STATUS,g)}catch{}},nE("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._statsTimer&&(this.isUseScaleResolutionDownBy=!1,window.clearInterval(this._statsTimer),this._statsTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,Gi.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(i,o){if(!o){if(i===this._enabled)return;this.stateCheck("enabled",i)}if(Gi.info("[".concat(this.getTrackId(),"] start setEnabled"),i),!i){this._originMediaStreamTrack.enabled=!1;try{await S_(this,xE.NEED_DISABLE_TRACK,this)}catch(p){throw Gi.error("[".concat(this.getTrackId(),"] setEnabled to false error"),p.toString()),p}return o||(this._enabled=!1),void Gi.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await S_(this,xE.NEED_ENABLE_TRACK,this)}catch(p){throw Gi.error("[".concat(this.getTrackId(),"] setEnabled to true error"),p.toString()),p}Gi.info("[".concat(this.getTrackId(),"] setEnabled to true success")),o||(this._enabled=!0)}async setMuted(i){i!==this._muted&&(this.stateCheck("muted",i),this._muted=i,this._originMediaStreamTrack.enabled=!i,Gi.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(i)),i?await S_(this,xE.NEED_MUTE_TRACK,this):await S_(this,xE.NEED_UNMUTE_TRACK,this))}async setEncoderConfiguration(i,o){if(!this._enabled)throw new yE(_p.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(i==="720p_auto"?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),i=kT(i),this._forceBitrateLimit&&(i.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:i.bitrateMax,i.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:i.bitrateMin),i.width||i.height||i.frameRate){const p=VN({encoderConfig:i});(H0()||z0()||wT())&&(p.deviceId=void 0),Gi.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(i),JSON.stringify(p));try{await this._originMediaStreamTrack.applyConstraints(p),this.updateMediaStreamTrackResolution()}catch(g){const b=new yE(_p.UNEXPECTED_ERROR,g.toString());throw Gi.error("[".concat(this.getTrackId(),"] applyConstraints error"),b.toString()),b}}this._encoderConfig=i,this._hints.indexOf(A_.SCREEN_TRACK)===-1&&this.updateBitrateFromProfile();try{await S_(this,xE.NEED_UPDATE_VIDEO_ENCODER,this)}catch(p){return p.throw(Gi)}}getStats(){return VO(()=>{Gi.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")},"localVideoTrackGetStatsWarning"),oS(this,xE.GET_STATS)||xS({},IM)}async setBeautyEffect(i){Gi.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(i){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(i,o):await MM(i)}async setBitrateLimit(i){if(Gi.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(i))),i){this._forceBitrateLimit=i,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax{let[o,p]=i;this._videoHeight=p,this._videoWidth=o}).catch(pN)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(i){if(!this._enabled)throw new yE(_p.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");Gi.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(i)),i=kT(i),this._forceBitrateLimit&&(i.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:i.bitrateMax,i.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:i.bitrateMin),this._encoderConfig=i,this._hints.indexOf(A_.SCREEN_TRACK)===-1&&this.updateBitrateFromProfile();try{await S_(this,xE.NEED_UPDATE_VIDEO_ENCODER,this)}catch(o){return o.throw(Gi)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:i,height:o,frameRate:p}=this.getMediaStreamTrackSettings();if(!i||!o||!p)return;const[g,b]=function(A,j,H,z){let $;const Vt=200*Math.pow(H/15,.6)*Math.pow(A*j/640/360,.75),_r=Vt;if(z==="STANDARD_BITRATE")$=4*Vt;else{if(z!=="COMPATIABLE_BITRATE")return;$=2*Vt}return[Math.floor($),Math.floor(_r)]}(i,o,p,nE("BITRATE_ADAPTER_TYPE"))||[void 0,void 0];this._encoderConfig.bitrateMin||this._encoderConfig.bitrateMax||(this._encoderConfig.bitrateMin=b,this._encoderConfig.bitrateMax=g,Gi.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(i,", h: ").concat(o,", fps: ").concat(p,"] => [brMax: ").concat(g,", brMin: ").concat(b,"]")))}getVideoElementVisibleStatus(){try{var i,o;const p=this==null||(i=this._player)===null||i===void 0?void 0:i.getContainerElement(),g={track:this,element:this==null||(o=this._player)===null||o===void 0?void 0:o.getVideoElement(),slot:p==null?void 0:p.parentElement},{element:b,slot:A}=g;if(this.isPlaying&&b instanceof HTMLVideoElement&&A instanceof HTMLElement){const j=JV.checkOneElementVisible(b),H=Object.assign({},j);if(H.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=H.visible;const z=jE.reportApiInvoke(null,{tag:x_.TRACER,name:e0.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});H.visible?z.onSuccess("Video is visible"):z.onSuccess("Invisible because of ".concat(H.reason))}return H}return}catch(p){throw new yE(_p.GET_VIDEO_ELEMENT_VISIBLE_ERROR,p.message)}}async renewMediaStreamTrack(i){}pipe(i){if(this.processor===i)return i;if(i._source)throw new yE(_p.INVALID_OPERATION,"Processor ".concat(i.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=i,this.processor._source=this,i.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),i}unpipe(){if(!this.processor)return;const i=this.processor;this.processor._source=void 0,this.processor=void 0,i.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe()}clone(i){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],p=this._encoderConfig;i&&(p=xS(xS({},p),kT(i))),p=ZR(p);const g=T_(8,"track-video-cloned-"),b=new ZE(o?this._mediaStreamTrack.clone():this._mediaStreamTrack,p,ZR(this._scalabilityMode),this._optimizationMode,g,ZR(this._hints));return i&&p&&b.setEncoderConfiguration(p),Gi.debug("clone video track from ".concat(this.getTrackId()," to ").concat(g,", clone ").concat(o)),b}async replaceTrack(i,o){if(!(i instanceof MediaStreamTrack))throw new yE(_p.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if(i.kind!=="video")throw new yE(_p.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(i,o,!0),this.updateMediaStreamTrackResolution()}startMonitorStats(){if(!H0()&&!z0())return;this._statsTimer&&window.clearInterval(this._statsTimer);let i=2,o=PN[i],p=-1,g=Date.now();const b=A=>{A>2||A<0||(g=Date.now(),o=PN[A],this.setSenderConfiguration(o))};this.isUseScaleResolutionDownBy=!0,this._statsTimer=window.setInterval(()=>{const A=this.getStats(),j=oS(this,xE.GET_RTC_STATS);if(A.sendPackets>0&&j){p===-1&&(p=Date.now());const H=Date.now();if(H-p<1e3||H-g0&&z<$?i>0&&(i--,b(i),Gi.debug("[".concat(this.getTrackId(),"] step down for fps ").concat(z,", switchProfile to ").concat(i))):j.OutgoingAvailableBandwidth0&&(i--,b(i),Gi.debug("[".concat(this.getTrackId(),"] step down for OutgoingAvailableBandwidth ").concat(j.OutgoingAvailableBandwidth,", bitrateMin ").concat(o.bitrateMin,", switchProfile to ").concat(i))):typeof z=="number"&&z>Vt&&i1.2*PN[i+1].bitrateMin&&(i++,b(i),Gi.debug("[".concat(this.getTrackId(),"] step up for fps ").concat(z,", OutgoingAvailableBandwidth ").concat(j.OutgoingAvailableBandwidth,", switchProfile to ").concat(i)))}},nE("CHECK_LOCAL_STATS_INTERVAL"))}bindProcessorDestinationEvents(){this.processorDestination.on(V0.ON_TRACK,async i=>{i?i!==this._mediaStreamTrack&&(this._mediaStreamTrack=i,this._updatePlayerSource(),await S_(this,xE.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await S_(this,xE.NEED_REPLACE_TRACK,this))})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(V0.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(dS.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(dS.REQUEST_CONSTRAINTS)}}bE([HE({argsMap:(l,i,o)=>[l.getTrackId(),typeof i=="string"?i:i instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",o]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Object,Object]),kc("design:returntype",void 0)],ZE.prototype,"play",null),bE([HE({argsMap:l=>[l.getTrackId()]}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],ZE.prototype,"stop",null),bE([GI("LocalVideoTrack","_enabledMutex"),HE({argsMap:(l,i)=>[l.getTrackId(),i]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Boolean,Boolean]),kc("design:returntype",pE)],ZE.prototype,"setEnabled",null),bE([GI("LocalVideoTrack","_enabledMutex"),HE({argsMap:(l,i)=>[l.getTrackId(),i]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Boolean]),kc("design:returntype",pE)],ZE.prototype,"setMuted",null),bE([HE({argsMap:(l,i)=>[l.getTrackId(),i]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Object,Boolean]),kc("design:returntype",pE)],ZE.prototype,"setEncoderConfiguration",null),bE([H_(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",Object)],ZE.prototype,"getStats",null),bE([HE({argsMap:(l,i,o)=>[l.getTrackId(),i,o]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Boolean,Object]),kc("design:returntype",pE)],ZE.prototype,"setBeautyEffect",null),bE([H_(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",ImageData)],ZE.prototype,"getCurrentFrameData",null),bE([H_(),kc("design:type",Function),kc("design:paramtypes",[String,Number]),kc("design:returntype",pE)],ZE.prototype,"getCurrentFrameImage",null),bE([H_(),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",pE)],ZE.prototype,"setBitrateLimit",null),bE([H_(),kc("design:type",Function),kc("design:paramtypes",[String]),kc("design:returntype",pE)],ZE.prototype,"setOptimizationMode",null),bE([H_(),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",void 0)],ZE.prototype,"setScalabiltyMode",null),bE([H_(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],ZE.prototype,"updateMediaStreamTrackResolution",null),bE([HE({argsMap:(l,i)=>[l.getTrackId(),i.name]}),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",Object)],ZE.prototype,"pipe",null),bE([HE({argsMap:l=>[l.getTrackId()]}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],ZE.prototype,"unpipe",null),bE([HE({argsMap:l=>[l.getTrackId()]}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],ZE.prototype,"close",null),bE([HE({argsMap:(l,i,o)=>[l.getTrackId(),i.label,o]}),kc("design:type",Function),kc("design:paramtypes",[MediaStreamTrack,Boolean]),kc("design:returntype",pE)],ZE.prototype,"replaceTrack",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],ZE.prototype,"startMonitorStats",null);class SR extends ZE{get __className__(){return"CameraVideoTrack"}constructor(i,o,p,g,b,A){super(i,kT(o.encoderConfig),g,b,A),_e(this,"_config",void 0),_e(this,"_originalConstraints",void 0),_e(this,"_constraints",void 0),_e(this,"_enabled",!0),_e(this,"_deviceName","default"),_e(this,"tryResumeVideoForIOS15_16WeChat",async()=>{(FI()||ML())&&!function(){const j=l_();if(j.os!==l0.IOS||!j.osVersion)return!1;const H=j.osVersion.split(".");return Number(H[0])===15&&Number(H[1])>=2}()&&WV()&&this._enabled&&!this._isClosed&&(Gi.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())}),this._config=o,this._originalConstraints=p,this._constraints=p,this._deviceName=i.label,this._encoderConfig=kT(this._config.encoderConfig),__.on(_0.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),__.on(_0.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents()}async setDevice(i){return typeof i=="string"?this._setDeviceById(i):i.deviceId?this._setDeviceById(i.deviceId):i.facingMode?this._setDeviceByFacingModel(i.facingMode):void 0}async _setDeviceById(i){if(Gi.info("[".concat(this.getTrackId(),"] set device to ").concat(i)),this._enabled)try{const o=await DS.getDeviceById(i),p={};p.video=xS({},this._constraints),p.video.deviceId={exact:i},p.video.facingMode=void 0,this._originMediaStreamTrack.stop();let g=null;try{g=await kS(p,this.getTrackId())}catch(b){throw Gi.error("[".concat(this.getTrackId(),"] setDevice failed"),b.toString()),g=await kS({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(g.getVideoTracks()[0],!1),b}await this._updateOriginMediaStreamTrack(g.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=o.label,this._config.cameraId=i,this._constraints.deviceId={exact:i}}catch(o){throw Gi.error("[".concat(this.getTrackId(),"] setDevice error"),o.toString()),o}else try{const o=await DS.getDeviceById(i);this._deviceName=o.label,this._config.cameraId=i,this._constraints.deviceId={exact:i}}catch(o){throw Gi.error("[".concat(this.getTrackId(),"] setDevice error"),o.toString()),o}Gi.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(i){Gi.info("[".concat(this.getTrackId(),"] set facingMode ").concat(i));const o={video:xS(xS({},this._constraints),{},{deviceId:void 0,facingMode:{exact:i}})};if(this._enabled){this._originMediaStreamTrack.stop();let p=null;try{p=await kS(o,this.getTrackId())}catch(g){throw Gi.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),g.toString()),p=await kS({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(p.getVideoTracks()[0],!1),g}await this._updateOriginMediaStreamTrack(p.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution()}this._deviceName="",this._config.facingMode=i,this._config.cameraId=void 0,this._constraints=xS({},o.video),Gi.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(i,o){if(!o){if(i===this._enabled)return;this.stateCheck("enabled",i)}if(Gi.info("[".concat(this.getTrackId(),"] start setEnabled"),i),i){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const p=await kS({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(p.getVideoTracks()[0],!1)}await S_(this,xE.NEED_ENABLE_TRACK,this)}catch(p){throw Gi.error("[".concat(this.getTrackId(),"] setEnabled true error"),p.toString()),p}this.updateMediaStreamTrackResolution(),Gi.info("[".concat(this.getTrackId(),"] setEnabled to true success")),o||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),o||(this._enabled=!1);try{await S_(this,xE.NEED_DISABLE_TRACK,this)}catch(p){throw Gi.error("[".concat(this.getTrackId(),"] setEnabled to false error"),p.toString()),p}Gi.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(i,o){if(!this._enabled)throw new yE(_p.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");i==="720p_auto"?this.startMonitorStats():this._statsTimer&&(window.clearInterval(this._statsTimer),this._statsTimer=null),i=kT(i),this._forceBitrateLimit&&(i.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:i.bitrateMax,i.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:i.bitrateMin);const p=Q_(this._config);p.encoderConfig=i;const g=VN(p);(H0()||z0()||wT())&&(g.deviceId=void 0),Gi.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(i),JSON.stringify(g));try{await this._originMediaStreamTrack.applyConstraints(g),this.updateMediaStreamTrackResolution()}catch(b){const A=new yE(_p.UNEXPECTED_ERROR,b.toString());throw Gi.error("[".concat(this.getTrackId(),"] applyConstraints error"),A.toString()),A}this._config=p,this._constraints=g,this._originalConstraints=g,this._encoderConfig=i,this._hints.indexOf(A_.SCREEN_TRACK)===-1&&this.updateBitrateFromProfile();try{await S_(this,xE.NEED_UPDATE_VIDEO_ENCODER,this)}catch(b){return b.throw(Gi)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((z0()||wT())&&this._enabled&&!this._isClosed&&__.duringInterruption){const i=async()=>{__.off(_0.IOS_INTERRUPTION_END,i),this._enabled&&!this._isClosed&&(Gi.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};__.on(_0.IOS_INTERRUPTION_END,i)}else Gi.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(_R.TRACK_ENDED)}async renewMediaStreamTrack(i){const o=i||this._constraints,p=DS.searchDeviceIdByName(this._deviceName);if(p&&!o.deviceId&&(o.deviceId={exact:p}),this._enabled){const g=await kS({video:o},this.getTrackId());this._constraints=o,await this._updateOriginMediaStreamTrack(g.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),__.off(_0.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),__.off(_0.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(i){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],p=this._encoderConfig;i&&(p=xS(xS({},p),kT(i))),p=ZR(p);const g=T_(8,"track-cam-cloned-"),b=new SR(o?this._mediaStreamTrack.clone():this._mediaStreamTrack,ZR(xS(xS({},this._config),{},{encoderConfig:p})),ZR(this._constraints),ZR(this._scalabilityMode),this._optimizationMode,g);return i&&p&&b.setEncoderConfiguration(p),Gi.debug("clone track from ".concat(this.getTrackId()," to ").concat(g,", clone ").concat(o)),b}bindProcessorContextEvents(){this.processorContext.on(dS.REQUEST_UPDATE_CONSTRAINTS,async(i,o,p)=>{try{const g=Object.assign({},this._originalConstraints,...i);await this.renewMediaStreamTrack(g),o()}catch(g){p(g)}}),this.processorContext.on(dS.REQUEST_CONSTRAINTS,async i=>{i(this._originMediaStreamTrack.getSettings())})}}function u4(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function BN(l){for(var i=1;i[l.getTrackId(),i]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",pE)],SR.prototype,"setDevice",null),bE([GI("CameraVideoTrack","_enabledMutex"),HE({argsMap:(l,i)=>[l.getTrackId(),i]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Boolean,Boolean]),kc("design:returntype",pE)],SR.prototype,"setEnabled",null),bE([HE({argsMap:(l,i)=>[l.getTrackId(),i]}),H_(),kc("design:type",Function),kc("design:paramtypes",[Object,Boolean]),kc("design:returntype",pE)],SR.prototype,"setEncoderConfiguration",null),bE([HE({argsMap:l=>[l.getTrackId()]}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],SR.prototype,"close",null);class d4 extends L6{getUserId(){return this._userId}constructor(i,o,p,g){super(i,"track-".concat(i.kind,"-").concat(o,"-").concat(g.clientId,"_").concat(T_(5,""))),_e(this,"_userId",void 0),_e(this,"_uintId",void 0),_e(this,"_isDestroyed",!1),_e(this,"store",void 0),_e(this,"processor",void 0),this._userId=o,this._uintId=p,this.store=g}_updateOriginMediaStreamTrack(i){this._originMediaStreamTrack=i,this._mediaStreamTrack=i,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,Gi.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}class DT extends d4{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==B0.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(i,o,p,g){super(i,o,p,g),_e(this,"_videoVisibleTimer",null),_e(this,"_previousVideoVisibleStatus",void 0),_e(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),_e(this,"trackMediaType","video"),_e(this,"_videoWidth",void 0),_e(this,"_videoHeight",void 0),_e(this,"_player",void 0),_e(this,"processorDestination",void 0),_e(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new Q6(this.getTrackId(),"remote"),this.processorDestination=new X6(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return VO(()=>{Gi.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")},"remoteVideoTrackGetStatsWarning"),oS(this,xE.GET_STATS)||GN({},D6)}play(i){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(typeof i=="string"){const g=document.getElementById(i);g?i=g:(Gi.warning("[".concat(this.getTrackId(),'] can not find "#').concat(i,'" element, use document.body')),i=document.body)}Gi.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(i instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(o));const p=GN(GN({fit:"cover"},o),{},{trackId:this.getTrackId(),element:i});this._player?this._player.updateConfig(p):(i instanceof HTMLVideoElement?this._player=new UM(p):this._player=new s4(p),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(sI.FIRST_FRAME_DECODED)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{const g=this.getVideoElementVisibleStatus();this.safeEmit(sI.VIDEO_ELEMENT_VISIBLE_STATUS,g)}catch{}},nE("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,Gi.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){o4(this._originMediaStreamTrack).then(i=>{let[o,p]=i;this._videoHeight=p,this._videoWidth=o}).catch(pN)}_updatePlayerSource(){Gi.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var i,o;const p=this==null||(i=this._player)===null||i===void 0?void 0:i.getContainerElement(),g={track:this,element:this==null||(o=this._player)===null||o===void 0?void 0:o.getVideoElement(),slot:p==null?void 0:p.parentElement},{element:b,slot:A}=g;if(this.isPlaying&&b instanceof HTMLVideoElement&&A instanceof HTMLElement){const j=JV.checkOneElementVisible(b),H=Object.assign({},j);if(H.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=H.visible;const z=jE.reportApiInvoke(null,{tag:x_.TRACER,name:e0.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});H.visible?z.onSuccess("Video is visible"):z.onSuccess("Invisible because of ".concat(H.reason))}return H}return}catch(p){throw new yE(_p.GET_VIDEO_ELEMENT_VISIBLE_ERROR,p.message)}}pipe(i){if(this.processor===i)return i;if(i._source)throw new yE(_p.INVALID_OPERATION,"Processor ".concat(i.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=i,this.processor._source=this,i.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),i}unpipe(){if(!this.processor)return;const i=this.processor;this.processor._source=void 0,this.processor=void 0,i.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(V0.ON_TRACK,async i=>{i?i!==this._mediaStreamTrack&&(this._mediaStreamTrack=i,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(V0.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}}bE([HE({argsMap:(l,i,o)=>[l.getTrackId(),typeof i=="string"?i:i instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",o]}),kc("design:type",Function),kc("design:paramtypes",[Object,Object]),kc("design:returntype",void 0)],DT.prototype,"play",null),bE([HE({argsMap:l=>[l.getTrackId()]}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],DT.prototype,"stop",null),bE([HE({argsMap:(l,i)=>[l.getTrackId(),i.name]}),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",Object)],DT.prototype,"pipe",null),bE([HE({argsMap:l=>[l.getTrackId()]}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],DT.prototype,"unpipe",null);class cT extends d4{get isPlaying(){return this._useAudioElement?vS.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(i,o,p,g){super(i,o,p,g),_e(this,"trackMediaType","audio"),_e(this,"_source",void 0),_e(this,"_useAudioElement",!0),_e(this,"_volume",100),_e(this,"processorContext",void 0),_e(this,"processorDestination",void 0),_e(this,"_played",!1),_e(this,"_bypassWebAudio",!1),nE("DISABLE_WEBAUDIO")?(this._source=new DM,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new NM(i,!0),nE("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(lS.RECEIVE_TRACK_BUFFER,()=>{this.safeEmit(sI.FIRST_FRAME_DECODED)}),this.processorContext=new jN(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new FN(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(lS.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})})}setAudioFrameCallback(i){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:4096;if(!i)return this._source.removeAllListeners(lS.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(o),this._source.removeAllListeners(lS.ON_AUDIO_BUFFER),this._source.on(lS.ON_AUDIO_BUFFER,p=>i(p))}setVolume(i){this._volume=i,this._useAudioElement?vS.setVolume(this.getTrackId(),i):this._source.setVolume(i/100)}async setPlaybackDevice(i){if(!this._useAudioElement)throw new yE(_p.NOT_SUPPORTED,"your browser does not support setting the audio output device");await vS.setSinkID(this.getTrackId(),i)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){return VO(()=>{Gi.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")},"remoteAudioTrackGetStatsWarning"),oS(this,xE.GET_STATS)||GN({},k6)}play(){Gi.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(Gi.debug("[".concat(this.getTrackId(),"] use audio element to play")),vS.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){Gi.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?vS.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let i=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];Gi.debug("[".concat(this.getTrackId(),"] update player source track")),i&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&vS.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(i){if(this._bypassWebAudio)throw new yE(_p.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===i)return i;if(i._source)throw new yE(_p.INVALID_OPERATION,"Processor ".concat(i.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=i,this.processor._source=this,i.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),i}unpipe(){var i;if(this._bypassWebAudio)throw new yE(_p.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const o=this.processor;(i=this._source.processSourceNode)===null||i===void 0||i.disconnect(),this.processor._source=!1,this.processor=void 0,o.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(V0.ON_TRACK,async i=>{i?i!==this._mediaStreamTrack&&(this._mediaStreamTrack=i,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(i)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}),this.processorDestination.on(V0.ON_NODE,i=>{this._source.processedNode=i;const o=!i;this._useAudioElement!==o&&(this._played?(this.stop(),this._useAudioElement=o,this.play()):this._useAudioElement=o)})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(V0.ON_TRACK),this.processorDestination.removeAllListeners(V0.ON_NODE)}}bE([HE({argsMap:(l,i)=>[l.getTrackId(),i],throttleTime:300}),kc("design:type",Function),kc("design:paramtypes",[Number]),kc("design:returntype",void 0)],cT.prototype,"setVolume",null),bE([HE({argsMap:(l,i)=>[l.getTrackId(),i]}),kc("design:type",Function),kc("design:paramtypes",[String]),kc("design:returntype",pE)],cT.prototype,"setPlaybackDevice",null),bE([HE({argsMap:l=>[l.getTrackId()]}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],cT.prototype,"play",null),bE([HE({argsMap:l=>[l.getTrackId()]}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],cT.prototype,"stop",null),bE([HE({argsMap:(l,i)=>[l.getTrackId(),i.name]}),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",Object)],cT.prototype,"pipe",null),bE([HE({argsMap:l=>[l.getTrackId()]}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],cT.prototype,"unpipe",null);function eO(l){let i=l.length;for(;--i>=0;)l[i]=0}const jM=256,h4=286,KO=30,YO=15,VM=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]),qN=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]),ctt=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),p4=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),$T=new Array(576);eO($T);const JO=new Array(60);eO(JO);const XO=new Array(512);eO(XO);const QO=new Array(256);eO(QO);const BM=new Array(29);eO(BM);const WN=new Array(KO);function GM(l,i,o,p,g){this.static_tree=l,this.extra_bits=i,this.extra_base=o,this.elems=p,this.max_length=g,this.has_stree=l&&l.length}let f4,m4,g4;function qM(l,i){this.dyn_tree=l,this.max_code=0,this.stat_desc=i}eO(WN);const E4=l=>l<256?XO[l]:XO[256+(l>>>7)],$O=(l,i)=>{l.pending_buf[l.pending++]=255&i,l.pending_buf[l.pending++]=i>>>8&255},MS=(l,i,o)=>{l.bi_valid>16-o?(l.bi_buf|=i<>16-l.bi_valid,l.bi_valid+=o-16):(l.bi_buf|=i<{MS(l,o[2*i],o[2*i+1])},v4=(l,i)=>{let o=0;do o|=1&l,l>>>=1,o<<=1;while(--i>0);return o>>>1},_4=(l,i,o)=>{const p=new Array(16);let g,b,A=0;for(g=1;g<=YO;g++)A=A+o[g-1]<<1,p[g]=A;for(b=0;b<=i;b++){let j=l[2*b+1];j!==0&&(l[2*b]=v4(p[j]++,j))}},y4=l=>{let i;for(i=0;i{l.bi_valid>8?$O(l,l.bi_buf):l.bi_valid>0&&(l.pending_buf[l.pending++]=l.bi_buf),l.bi_buf=0,l.bi_valid=0},S4=(l,i,o,p)=>{const g=2*i,b=2*o;return l[g]{const p=l.heap[o];let g=o<<1;for(;g<=l.heap_len&&(g{let p,g,b,A,j=0;if(l.sym_next!==0)do p=255&l.pending_buf[l.sym_buf+j++],p+=(255&l.pending_buf[l.sym_buf+j++])<<8,g=l.pending_buf[l.sym_buf+j++],p===0?LT(l,g,i):(b=QO[g],LT(l,b+jM+1,i),A=VM[b],A!==0&&(g-=BM[b],MS(l,g,A)),p--,b=E4(p),LT(l,b,o),A=qN[b],A!==0&&(p-=WN[b],MS(l,p,A)));while(j{const o=i.dyn_tree,p=i.stat_desc.static_tree,g=i.stat_desc.has_stree,b=i.stat_desc.elems;let A,j,H,z=-1;for(l.heap_len=0,l.heap_max=573,A=0;A>1;A>=1;A--)WM(l,o,A);H=b;do A=l.heap[1],l.heap[1]=l.heap[l.heap_len--],WM(l,o,1),j=l.heap[1],l.heap[--l.heap_max]=A,l.heap[--l.heap_max]=j,o[2*H]=o[2*A]+o[2*j],l.depth[H]=(l.depth[A]>=l.depth[j]?l.depth[A]:l.depth[j])+1,o[2*A+1]=o[2*j+1]=H,l.heap[1]=H++,WM(l,o,1);while(l.heap_len>=2);l.heap[--l.heap_max]=l.heap[1],(($,Vt)=>{const _r=Vt.dyn_tree,Fi=Vt.max_code,_l=Vt.stat_desc.static_tree,_u=Vt.stat_desc.has_stree,_h=Vt.stat_desc.extra_bits,_g=Vt.stat_desc.extra_base,eE=Vt.stat_desc.max_length;let oE,SE,vE,fE,mE,EE,PE=0;for(fE=0;fE<=YO;fE++)$.bl_count[fE]=0;for(_r[2*$.heap[$.heap_max]+1]=0,oE=$.heap_max+1;oE<573;oE++)SE=$.heap[oE],fE=_r[2*_r[2*SE+1]+1]+1,fE>eE&&(fE=eE,PE++),_r[2*SE+1]=fE,SE>Fi||($.bl_count[fE]++,mE=0,SE>=_g&&(mE=_h[SE-_g]),EE=_r[2*SE],$.opt_len+=EE*(fE+mE),_u&&($.static_len+=EE*(_l[2*SE+1]+mE)));if(PE!==0){do{for(fE=eE-1;$.bl_count[fE]===0;)fE--;$.bl_count[fE]--,$.bl_count[fE+1]+=2,$.bl_count[eE]--,PE-=2}while(PE>0);for(fE=eE;fE!==0;fE--)for(SE=$.bl_count[fE];SE!==0;)vE=$.heap[--oE],vE>Fi||(_r[2*vE+1]!==fE&&($.opt_len+=(fE-_r[2*vE+1])*_r[2*vE],_r[2*vE+1]=fE),SE--)}})(l,i),_4(o,z,l.bl_count)},R4=(l,i,o)=>{let p,g,b=-1,A=i[1],j=0,H=7,z=4;for(A===0&&(H=138,z=3),i[2*(o+1)+1]=65535,p=0;p<=o;p++)g=A,A=i[2*(p+1)+1],++j{let p,g,b=-1,A=i[1],j=0,H=7,z=4;for(A===0&&(H=138,z=3),p=0;p<=o;p++)if(g=A,A=i[2*(p+1)+1],!(++j{MS(l,0+(p?1:0),3),b4(l),$O(l,o),$O(l,~o),o&&l.pending_buf.set(l.window.subarray(i,i+o),l.pending),l.pending+=o};var utt=l=>{I4||((()=>{let i,o,p,g,b;const A=new Array(16);for(p=0,g=0;g<28;g++)for(BM[g]=p,i=0;i<1<>=7;g{let g,b,A=0;l.level>0?(l.strm.data_type===2&&(l.strm.data_type=(j=>{let H,z=4093624447;for(H=0;H<=31;H++,z>>>=1)if(1&z&&j.dyn_ltree[2*H]!==0)return 0;if(j.dyn_ltree[18]!==0||j.dyn_ltree[20]!==0||j.dyn_ltree[26]!==0)return 1;for(H=32;H{let H;for(R4(j,j.dyn_ltree,j.l_desc.max_code),R4(j,j.dyn_dtree,j.d_desc.max_code),HM(j,j.bl_desc),H=18;H>=3&&j.bl_tree[2*p4[H]+1]===0;H--);return j.opt_len+=3*(H+1)+5+5+4,H})(l),g=l.opt_len+3+7>>>3,b=l.static_len+3+7>>>3,b<=g&&(g=b)):g=b=o+5,o+4<=g&&i!==-1?w4(l,i,o,p):l.strategy===4||b===g?(MS(l,2+(p?1:0),3),T4(l,$T,JO)):(MS(l,4+(p?1:0),3),((j,H,z,$)=>{let Vt;for(MS(j,H-257,5),MS(j,z-1,5),MS(j,$-4,4),Vt=0;Vt<$;Vt++)MS(j,j.bl_tree[2*p4[Vt]+1],3);C4(j,j.dyn_ltree,H-1),C4(j,j.dyn_dtree,z-1)})(l,l.l_desc.max_code+1,l.d_desc.max_code+1,A+1),T4(l,l.dyn_ltree,l.dyn_dtree)),y4(l),p&&b4(l)},dtt=(l,i,o)=>(l.pending_buf[l.sym_buf+l.sym_next++]=i,l.pending_buf[l.sym_buf+l.sym_next++]=i>>8,l.pending_buf[l.sym_buf+l.sym_next++]=o,i===0?l.dyn_ltree[2*o]++:(l.matches++,i--,l.dyn_ltree[2*(QO[o]+jM+1)]++,l.dyn_dtree[2*E4(i)]++),l.sym_next===l.sym_end),htt={_tr_init:utt,_tr_stored_block:w4,_tr_flush_block:ltt,_tr_tally:dtt,_tr_align:l=>{MS(l,2,3),LT(l,256,$T),(i=>{i.bi_valid===16?($O(i,i.bi_buf),i.bi_buf=0,i.bi_valid=0):i.bi_valid>=8&&(i.pending_buf[i.pending++]=255&i.bi_buf,i.bi_buf>>=8,i.bi_valid-=8)})(l)}},ZO=(l,i,o,p)=>{let g=65535&l|0,b=l>>>16&65535|0,A=0;for(;o!==0;){A=o>2e3?2e3:o,o-=A;do g=g+i[p++]|0,b=b+g|0;while(--A);g%=65521,b%=65521}return g|b<<16|0};const ptt=new Uint32Array((()=>{let l,i=[];for(var o=0;o<256;o++){l=o;for(var p=0;p<8;p++)l=1&l?3988292384^l>>>1:l>>>1;i[o]=l}return i})());var _b=(l,i,o,p)=>{const g=ptt,b=p+o;l^=-1;for(let A=p;A>>8^g[255&(l^i[A])];return-1^l},cI={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"},nO={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_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:ftt,_tr_stored_block:zM,_tr_flush_block:mtt,_tr_tally:TR,_tr_align:gtt}=htt,{Z_NO_FLUSH:RR,Z_PARTIAL_FLUSH:Ett,Z_FULL_FLUSH:vtt,Z_FINISH:uT,Z_BLOCK:A4,Z_OK:eS,Z_STREAM_END:O4,Z_STREAM_ERROR:xT,Z_DATA_ERROR:_tt,Z_BUF_ERROR:KM,Z_DEFAULT_COMPRESSION:ytt,Z_FILTERED:btt,Z_HUFFMAN_ONLY:HN,Z_RLE:Stt,Z_FIXED:Ttt,Z_DEFAULT_STRATEGY:Rtt,Z_UNKNOWN:Ctt,Z_DEFLATED:zN}=nO,YM=286,Itt=30,wtt=19,Att=2*YM+1,Ott=15,uI=258,MT=262,rO=42,lI=113,t1=666,dI=(l,i)=>(l.msg=cI[i],i),N4=l=>2*l-(l>4?9:0),CR=l=>{let i=l.length;for(;--i>=0;)l[i]=0},Ntt=l=>{let i,o,p,g=l.w_size;i=l.hash_size,p=i;do o=l.head[--p],l.head[p]=o>=g?o-g:0;while(--i);i=g,p=i;do o=l.prev[--p],l.prev[p]=o>=g?o-g:0;while(--i)};let IR=(l,i,o)=>(i<{const i=l.state;let o=i.pending;o>l.avail_out&&(o=l.avail_out),o!==0&&(l.output.set(i.pending_buf.subarray(i.pending_out,i.pending_out+o),l.next_out),l.next_out+=o,i.pending_out+=o,l.total_out+=o,l.avail_out-=o,i.pending-=o,i.pending===0&&(i.pending_out=0))},KS=(l,i)=>{mtt(l,l.block_start>=0?l.block_start:-1,l.strstart-l.block_start,i),l.block_start=l.strstart,zS(l.strm)},G_=(l,i)=>{l.pending_buf[l.pending++]=i},e1=(l,i)=>{l.pending_buf[l.pending++]=i>>>8&255,l.pending_buf[l.pending++]=255&i},JM=(l,i,o,p)=>{let g=l.avail_in;return g>p&&(g=p),g===0?0:(l.avail_in-=g,i.set(l.input.subarray(l.next_in,l.next_in+g),o),l.state.wrap===1?l.adler=ZO(l.adler,i,g,o):l.state.wrap===2&&(l.adler=_b(l.adler,i,g,o)),l.next_in+=g,l.total_in+=g,g)},P4=(l,i)=>{let o,p,g=l.max_chain_length,b=l.strstart,A=l.prev_length,j=l.nice_match;const H=l.strstart>l.w_size-MT?l.strstart-(l.w_size-MT):0,z=l.window,$=l.w_mask,Vt=l.prev,_r=l.strstart+uI;let Fi=z[b+A-1],_l=z[b+A];l.prev_length>=l.good_match&&(g>>=2),j>l.lookahead&&(j=l.lookahead);do if(o=i,z[o+A]===_l&&z[o+A-1]===Fi&&z[o]===z[b]&&z[++o]===z[b+1]){b+=2,o++;do;while(z[++b]===z[++o]&&z[++b]===z[++o]&&z[++b]===z[++o]&&z[++b]===z[++o]&&z[++b]===z[++o]&&z[++b]===z[++o]&&z[++b]===z[++o]&&z[++b]===z[++o]&&b<_r);if(p=uI-(_r-b),b=_r-uI,p>A){if(l.match_start=i,A=p,p>=j)break;Fi=z[b+A-1],_l=z[b+A]}}while((i=Vt[i&$])>H&&--g!=0);return A<=l.lookahead?A:l.lookahead},iO=l=>{const i=l.w_size;let o,p,g;do{if(p=l.window_size-l.lookahead-l.strstart,l.strstart>=i+(i-MT)&&(l.window.set(l.window.subarray(i,i+i-p),0),l.match_start-=i,l.strstart-=i,l.block_start-=i,l.insert>l.strstart&&(l.insert=l.strstart),Ntt(l),p+=i),l.strm.avail_in===0)break;if(o=JM(l.strm,l.window,l.strstart+l.lookahead,p),l.lookahead+=o,l.lookahead+l.insert>=3)for(g=l.strstart-l.insert,l.ins_h=l.window[g],l.ins_h=IR(l,l.ins_h,l.window[g+1]);l.insert&&(l.ins_h=IR(l,l.ins_h,l.window[g+3-1]),l.prev[g&l.w_mask]=l.head[l.ins_h],l.head[l.ins_h]=g,g++,l.insert--,!(l.lookahead+l.insert<3)););}while(l.lookahead{let o,p,g,b=l.pending_buf_size-5>l.w_size?l.w_size:l.pending_buf_size-5,A=0,j=l.strm.avail_in;do{if(o=65535,g=l.bi_valid+42>>3,l.strm.avail_outp+l.strm.avail_in&&(o=p+l.strm.avail_in),o>g&&(o=g),o>8,l.pending_buf[l.pending-2]=~o,l.pending_buf[l.pending-1]=~o>>8,zS(l.strm),p&&(p>o&&(p=o),l.strm.output.set(l.window.subarray(l.block_start,l.block_start+p),l.strm.next_out),l.strm.next_out+=p,l.strm.avail_out-=p,l.strm.total_out+=p,l.block_start+=p,o-=p),o&&(JM(l.strm,l.strm.output,l.strm.next_out,o),l.strm.next_out+=o,l.strm.avail_out-=o,l.strm.total_out+=o)}while(A===0);return j-=l.strm.avail_in,j&&(j>=l.w_size?(l.matches=2,l.window.set(l.strm.input.subarray(l.strm.next_in-l.w_size,l.strm.next_in),0),l.strstart=l.w_size,l.insert=l.strstart):(l.window_size-l.strstart<=j&&(l.strstart-=l.w_size,l.window.set(l.window.subarray(l.w_size,l.w_size+l.strstart),0),l.matches<2&&l.matches++,l.insert>l.strstart&&(l.insert=l.strstart)),l.window.set(l.strm.input.subarray(l.strm.next_in-j,l.strm.next_in),l.strstart),l.strstart+=j,l.insert+=j>l.w_size-l.insert?l.w_size-l.insert:j),l.block_start=l.strstart),l.high_waterg&&l.block_start>=l.w_size&&(l.block_start-=l.w_size,l.strstart-=l.w_size,l.window.set(l.window.subarray(l.w_size,l.w_size+l.strstart),0),l.matches<2&&l.matches++,g+=l.w_size,l.insert>l.strstart&&(l.insert=l.strstart)),g>l.strm.avail_in&&(g=l.strm.avail_in),g&&(JM(l.strm,l.window,l.strstart,g),l.strstart+=g,l.insert+=g>l.w_size-l.insert?l.w_size-l.insert:g),l.high_water>3,g=l.pending_buf_size-g>65535?65535:l.pending_buf_size-g,b=g>l.w_size?l.w_size:g,p=l.strstart-l.block_start,(p>=b||(p||i===uT)&&i!==RR&&l.strm.avail_in===0&&p<=g)&&(o=p>g?g:p,A=i===uT&&l.strm.avail_in===0&&o===p?1:0,zM(l,l.block_start,o,A),l.block_start+=o,zS(l.strm)),A?3:1)},XM=(l,i)=>{let o,p;for(;;){if(l.lookahead=3&&(l.ins_h=IR(l,l.ins_h,l.window[l.strstart+3-1]),o=l.prev[l.strstart&l.w_mask]=l.head[l.ins_h],l.head[l.ins_h]=l.strstart),o!==0&&l.strstart-o<=l.w_size-MT&&(l.match_length=P4(l,o)),l.match_length>=3)if(p=TR(l,l.strstart-l.match_start,l.match_length-3),l.lookahead-=l.match_length,l.match_length<=l.max_lazy_match&&l.lookahead>=3){l.match_length--;do l.strstart++,l.ins_h=IR(l,l.ins_h,l.window[l.strstart+3-1]),o=l.prev[l.strstart&l.w_mask]=l.head[l.ins_h],l.head[l.ins_h]=l.strstart;while(--l.match_length!=0);l.strstart++}else l.strstart+=l.match_length,l.match_length=0,l.ins_h=l.window[l.strstart],l.ins_h=IR(l,l.ins_h,l.window[l.strstart+1]);else p=TR(l,0,l.window[l.strstart]),l.lookahead--,l.strstart++;if(p&&(KS(l,!1),l.strm.avail_out===0))return 1}return l.insert=l.strstart<2?l.strstart:2,i===uT?(KS(l,!0),l.strm.avail_out===0?3:4):l.sym_next&&(KS(l,!1),l.strm.avail_out===0)?1:2},sO=(l,i)=>{let o,p,g;for(;;){if(l.lookahead=3&&(l.ins_h=IR(l,l.ins_h,l.window[l.strstart+3-1]),o=l.prev[l.strstart&l.w_mask]=l.head[l.ins_h],l.head[l.ins_h]=l.strstart),l.prev_length=l.match_length,l.prev_match=l.match_start,l.match_length=2,o!==0&&l.prev_length4096)&&(l.match_length=2)),l.prev_length>=3&&l.match_length<=l.prev_length){g=l.strstart+l.lookahead-3,p=TR(l,l.strstart-1-l.prev_match,l.prev_length-3),l.lookahead-=l.prev_length-1,l.prev_length-=2;do++l.strstart<=g&&(l.ins_h=IR(l,l.ins_h,l.window[l.strstart+3-1]),o=l.prev[l.strstart&l.w_mask]=l.head[l.ins_h],l.head[l.ins_h]=l.strstart);while(--l.prev_length!=0);if(l.match_available=0,l.match_length=2,l.strstart++,p&&(KS(l,!1),l.strm.avail_out===0))return 1}else if(l.match_available){if(p=TR(l,0,l.window[l.strstart-1]),p&&KS(l,!1),l.strstart++,l.lookahead--,l.strm.avail_out===0)return 1}else l.match_available=1,l.strstart++,l.lookahead--}return l.match_available&&(p=TR(l,0,l.window[l.strstart-1]),l.match_available=0),l.insert=l.strstart<2?l.strstart:2,i===uT?(KS(l,!0),l.strm.avail_out===0?3:4):l.sym_next&&(KS(l,!1),l.strm.avail_out===0)?1:2};function UT(l,i,o,p,g){this.good_length=l,this.max_lazy=i,this.nice_length=o,this.max_chain=p,this.func=g}const n1=[new UT(0,0,0,0,k4),new UT(4,4,8,4,XM),new UT(4,5,16,8,XM),new UT(4,6,32,32,XM),new UT(4,4,16,16,sO),new UT(8,16,32,32,sO),new UT(8,16,128,128,sO),new UT(8,32,128,256,sO),new UT(32,128,258,1024,sO),new UT(32,258,258,4096,sO)];function Ptt(){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=zN,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*Att),this.dyn_dtree=new Uint16Array(2*(2*Itt+1)),this.bl_tree=new Uint16Array(2*(2*wtt+1)),CR(this.dyn_ltree),CR(this.dyn_dtree),CR(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(Ott+1),this.heap=new Uint16Array(2*YM+1),CR(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*YM+1),CR(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 r1=l=>{if(!l)return 1;const i=l.state;return!i||i.strm!==l||i.status!==rO&&i.status!==57&&i.status!==69&&i.status!==73&&i.status!==91&&i.status!==103&&i.status!==lI&&i.status!==t1?1:0},D4=l=>{if(r1(l))return dI(l,xT);l.total_in=l.total_out=0,l.data_type=Ctt;const i=l.state;return i.pending=0,i.pending_out=0,i.wrap<0&&(i.wrap=-i.wrap),i.status=i.wrap===2?57:i.wrap?rO:lI,l.adler=i.wrap===2?0:1,i.last_flush=-2,ftt(i),eS},L4=l=>{const i=D4(l);var o;return i===eS&&((o=l.state).window_size=2*o.w_size,CR(o.head),o.max_lazy_match=n1[o.level].max_lazy,o.good_match=n1[o.level].good_length,o.nice_match=n1[o.level].nice_length,o.max_chain_length=n1[o.level].max_chain,o.strstart=0,o.block_start=0,o.lookahead=0,o.insert=0,o.match_length=o.prev_length=2,o.match_available=0,o.ins_h=0),i},x4=(l,i,o,p,g,b)=>{if(!l)return xT;let A=1;if(i===ytt&&(i=6),p<0?(A=0,p=-p):p>15&&(A=2,p-=16),g<1||g>9||o!==zN||p<8||p>15||i<0||i>9||b<0||b>Ttt||p===8&&A!==1)return dI(l,xT);p===8&&(p=9);const j=new Ptt;return l.state=j,j.strm=l,j.status=rO,j.wrap=A,j.gzhead=null,j.w_bits=p,j.w_size=1<{if(r1(l)||i>A4||i<0)return l?dI(l,xT):xT;const o=l.state;if(!l.output||l.avail_in!==0&&!l.input||o.status===t1&&i!==uT)return dI(l,l.avail_out===0?KM:xT);const p=o.last_flush;if(o.last_flush=i,o.pending!==0){if(zS(l),l.avail_out===0)return o.last_flush=-1,eS}else if(l.avail_in===0&&N4(i)<=N4(p)&&i!==uT)return dI(l,KM);if(o.status===t1&&l.avail_in!==0)return dI(l,KM);if(o.status===rO&&o.wrap===0&&(o.status=lI),o.status===rO){let g=zN+(o.w_bits-8<<4)<<8,b=-1;if(b=o.strategy>=HN||o.level<2?0:o.level<6?1:o.level===6?2:3,g|=b<<6,o.strstart!==0&&(g|=32),g+=31-g%31,e1(o,g),o.strstart!==0&&(e1(o,l.adler>>>16),e1(o,65535&l.adler)),l.adler=1,o.status=lI,zS(l),o.pending!==0)return o.last_flush=-1,eS}if(o.status===57){if(l.adler=0,G_(o,31),G_(o,139),G_(o,8),o.gzhead)G_(o,(o.gzhead.text?1:0)+(o.gzhead.hcrc?2:0)+(o.gzhead.extra?4:0)+(o.gzhead.name?8:0)+(o.gzhead.comment?16:0)),G_(o,255&o.gzhead.time),G_(o,o.gzhead.time>>8&255),G_(o,o.gzhead.time>>16&255),G_(o,o.gzhead.time>>24&255),G_(o,o.level===9?2:o.strategy>=HN||o.level<2?4:0),G_(o,255&o.gzhead.os),o.gzhead.extra&&o.gzhead.extra.length&&(G_(o,255&o.gzhead.extra.length),G_(o,o.gzhead.extra.length>>8&255)),o.gzhead.hcrc&&(l.adler=_b(l.adler,o.pending_buf,o.pending,0)),o.gzindex=0,o.status=69;else if(G_(o,0),G_(o,0),G_(o,0),G_(o,0),G_(o,0),G_(o,o.level===9?2:o.strategy>=HN||o.level<2?4:0),G_(o,3),o.status=lI,zS(l),o.pending!==0)return o.last_flush=-1,eS}if(o.status===69){if(o.gzhead.extra){let g=o.pending,b=(65535&o.gzhead.extra.length)-o.gzindex;for(;o.pending+b>o.pending_buf_size;){let j=o.pending_buf_size-o.pending;if(o.pending_buf.set(o.gzhead.extra.subarray(o.gzindex,o.gzindex+j),o.pending),o.pending=o.pending_buf_size,o.gzhead.hcrc&&o.pending>g&&(l.adler=_b(l.adler,o.pending_buf,o.pending-g,g)),o.gzindex+=j,zS(l),o.pending!==0)return o.last_flush=-1,eS;g=0,b-=j}let A=new Uint8Array(o.gzhead.extra);o.pending_buf.set(A.subarray(o.gzindex,o.gzindex+b),o.pending),o.pending+=b,o.gzhead.hcrc&&o.pending>g&&(l.adler=_b(l.adler,o.pending_buf,o.pending-g,g)),o.gzindex=0}o.status=73}if(o.status===73){if(o.gzhead.name){let g,b=o.pending;do{if(o.pending===o.pending_buf_size){if(o.gzhead.hcrc&&o.pending>b&&(l.adler=_b(l.adler,o.pending_buf,o.pending-b,b)),zS(l),o.pending!==0)return o.last_flush=-1,eS;b=0}g=o.gzindexb&&(l.adler=_b(l.adler,o.pending_buf,o.pending-b,b)),o.gzindex=0}o.status=91}if(o.status===91){if(o.gzhead.comment){let g,b=o.pending;do{if(o.pending===o.pending_buf_size){if(o.gzhead.hcrc&&o.pending>b&&(l.adler=_b(l.adler,o.pending_buf,o.pending-b,b)),zS(l),o.pending!==0)return o.last_flush=-1,eS;b=0}g=o.gzindexb&&(l.adler=_b(l.adler,o.pending_buf,o.pending-b,b))}o.status=103}if(o.status===103){if(o.gzhead.hcrc){if(o.pending+2>o.pending_buf_size&&(zS(l),o.pending!==0))return o.last_flush=-1,eS;G_(o,255&l.adler),G_(o,l.adler>>8&255),l.adler=0}if(o.status=lI,zS(l),o.pending!==0)return o.last_flush=-1,eS}if(l.avail_in!==0||o.lookahead!==0||i!==RR&&o.status!==t1){let g=o.level===0?k4(o,i):o.strategy===HN?((b,A)=>{let j;for(;;){if(b.lookahead===0&&(iO(b),b.lookahead===0)){if(A===RR)return 1;break}if(b.match_length=0,j=TR(b,0,b.window[b.strstart]),b.lookahead--,b.strstart++,j&&(KS(b,!1),b.strm.avail_out===0))return 1}return b.insert=0,A===uT?(KS(b,!0),b.strm.avail_out===0?3:4):b.sym_next&&(KS(b,!1),b.strm.avail_out===0)?1:2})(o,i):o.strategy===Stt?((b,A)=>{let j,H,z,$;const Vt=b.window;for(;;){if(b.lookahead<=uI){if(iO(b),b.lookahead<=uI&&A===RR)return 1;if(b.lookahead===0)break}if(b.match_length=0,b.lookahead>=3&&b.strstart>0&&(z=b.strstart-1,H=Vt[z],H===Vt[++z]&&H===Vt[++z]&&H===Vt[++z])){$=b.strstart+uI;do;while(H===Vt[++z]&&H===Vt[++z]&&H===Vt[++z]&&H===Vt[++z]&&H===Vt[++z]&&H===Vt[++z]&&H===Vt[++z]&&H===Vt[++z]&&z<$);b.match_length=uI-($-z),b.match_length>b.lookahead&&(b.match_length=b.lookahead)}if(b.match_length>=3?(j=TR(b,1,b.match_length-3),b.lookahead-=b.match_length,b.strstart+=b.match_length,b.match_length=0):(j=TR(b,0,b.window[b.strstart]),b.lookahead--,b.strstart++),j&&(KS(b,!1),b.strm.avail_out===0))return 1}return b.insert=0,A===uT?(KS(b,!0),b.strm.avail_out===0?3:4):b.sym_next&&(KS(b,!1),b.strm.avail_out===0)?1:2})(o,i):n1[o.level].func(o,i);if(g!==3&&g!==4||(o.status=t1),g===1||g===3)return l.avail_out===0&&(o.last_flush=-1),eS;if(g===2&&(i===Ett?gtt(o):i!==A4&&(zM(o,0,0,!1),i===vtt&&(CR(o.head),o.lookahead===0&&(o.strstart=0,o.block_start=0,o.insert=0))),zS(l),l.avail_out===0))return o.last_flush=-1,eS}return i!==uT?eS:o.wrap<=0?O4:(o.wrap===2?(G_(o,255&l.adler),G_(o,l.adler>>8&255),G_(o,l.adler>>16&255),G_(o,l.adler>>24&255),G_(o,255&l.total_in),G_(o,l.total_in>>8&255),G_(o,l.total_in>>16&255),G_(o,l.total_in>>24&255)):(e1(o,l.adler>>>16),e1(o,65535&l.adler)),zS(l),o.wrap>0&&(o.wrap=-o.wrap),o.pending!==0?eS:O4)},Dtt=(l,i)=>{let o=i.length;if(r1(l))return xT;const p=l.state,g=p.wrap;if(g===2||g===1&&p.status!==rO||p.lookahead)return xT;if(g===1&&(l.adler=ZO(l.adler,i,o,0)),p.wrap=0,o>=p.w_size){g===0&&(CR(p.head),p.strstart=0,p.block_start=0,p.insert=0);let H=new Uint8Array(p.w_size);H.set(i.subarray(o-p.w_size,o),0),i=H,o=p.w_size}const b=l.avail_in,A=l.next_in,j=l.input;for(l.avail_in=o,l.next_in=0,l.input=i,iO(p);p.lookahead>=3;){let H=p.strstart,z=p.lookahead-2;do p.ins_h=IR(p,p.ins_h,p.window[H+3-1]),p.prev[H&p.w_mask]=p.head[p.ins_h],p.head[p.ins_h]=H,H++;while(--z);p.strstart=H,p.lookahead=2,iO(p)}return p.strstart+=p.lookahead,p.block_start=p.strstart,p.insert=p.lookahead,p.lookahead=0,p.match_length=p.prev_length=2,p.match_available=0,l.next_in=A,l.input=j,l.avail_in=b,p.wrap=g,eS},i1={deflateInit:(l,i)=>x4(l,i,zN,15,8,Rtt),deflateInit2:x4,deflateReset:L4,deflateResetKeep:D4,deflateSetHeader:(l,i)=>r1(l)||l.state.wrap!==2?xT:(l.state.gzhead=i,eS),deflate:ktt,deflateEnd:l=>{if(r1(l))return xT;const i=l.state.status;return l.state=null,i===lI?dI(l,_tt):eS},deflateSetDictionary:Dtt,deflateInfo:"pako deflate (from Nodeca project)"};const Ltt=(l,i)=>Object.prototype.hasOwnProperty.call(l,i);var KN={assign:function(l){const i=Array.prototype.slice.call(arguments,1);for(;i.length;){const o=i.shift();if(o){if(typeof o!="object")throw new TypeError(o+"must be non-object");for(const p in o)Ltt(o,p)&&(l[p]=o[p])}}return l},flattenChunks:l=>{let i=0;for(let p=0,g=l.length;p=252?6:l>=248?5:l>=240?4:l>=224?3:l>=192?2:1;s1[254]=s1[254]=1;var o1={string2buf:l=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(l);let i,o,p,g,b,A=l.length,j=0;for(g=0;g>>6,i[b++]=128|63&o):o<65536?(i[b++]=224|o>>>12,i[b++]=128|o>>>6&63,i[b++]=128|63&o):(i[b++]=240|o>>>18,i[b++]=128|o>>>12&63,i[b++]=128|o>>>6&63,i[b++]=128|63&o);return i},buf2string:(l,i)=>{const o=i||l.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(l.subarray(0,i));let p,g;const b=new Array(2*o);for(g=0,p=0;p4)b[g++]=65533,p+=j-1;else{for(A&=j===2?31:j===3?15:7;j>1&&p1?b[g++]=65533:A<65536?b[g++]=A:(A-=65536,b[g++]=55296|A>>10&1023,b[g++]=56320|1023&A)}}return((A,j)=>{if(j<65534&&A.subarray&&M4)return String.fromCharCode.apply(null,A.length===j?A:A.subarray(0,j));let H="";for(let z=0;z{(i=i||l.length)>l.length&&(i=l.length);let o=i-1;for(;o>=0&&(192&l[o])==128;)o--;return o<0||o===0?i:o+s1[l[o]]>i?o:i}},U4=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 F4=Object.prototype.toString,{Z_NO_FLUSH:xtt,Z_SYNC_FLUSH:Mtt,Z_FULL_FLUSH:Utt,Z_FINISH:Ftt,Z_OK:YN,Z_STREAM_END:jtt,Z_DEFAULT_COMPRESSION:Vtt,Z_DEFAULT_STRATEGY:Btt,Z_DEFLATED:Gtt}=nO;function a1(l){this.options=KN.assign({level:Vtt,method:Gtt,chunkSize:16384,windowBits:15,memLevel:8,strategy:Btt},l||{});let i=this.options;i.raw&&i.windowBits>0?i.windowBits=-i.windowBits:i.gzip&&i.windowBits>0&&i.windowBits<16&&(i.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new U4,this.strm.avail_out=0;let o=i1.deflateInit2(this.strm,i.level,i.method,i.windowBits,i.memLevel,i.strategy);if(o!==YN)throw new Error(cI[o]);if(i.header&&i1.deflateSetHeader(this.strm,i.header),i.dictionary){let p;if(p=typeof i.dictionary=="string"?o1.string2buf(i.dictionary):F4.call(i.dictionary)==="[object ArrayBuffer]"?new Uint8Array(i.dictionary):i.dictionary,o=i1.deflateSetDictionary(this.strm,p),o!==YN)throw new Error(cI[o]);this._dict_set=!0}}function QM(l,i){const o=new a1(i);if(o.push(l,!0),o.err)throw o.msg||cI[o.err];return o.result}a1.prototype.push=function(l,i){const o=this.strm,p=this.options.chunkSize;let g,b;if(this.ended)return!1;for(b=i===~~i?i:i===!0?Ftt:xtt,typeof l=="string"?o.input=o1.string2buf(l):F4.call(l)==="[object ArrayBuffer]"?o.input=new Uint8Array(l):o.input=l,o.next_in=0,o.avail_in=o.input.length;;)if(o.avail_out===0&&(o.output=new Uint8Array(p),o.next_out=0,o.avail_out=p),(b===Mtt||b===Utt)&&o.avail_out<=6)this.onData(o.output.subarray(0,o.next_out)),o.avail_out=0;else{if(g=i1.deflate(o,b),g===jtt)return o.next_out>0&&this.onData(o.output.subarray(0,o.next_out)),g=i1.deflateEnd(this.strm),this.onEnd(g),this.ended=!0,g===YN;if(o.avail_out!==0){if(b>0&&o.next_out>0)this.onData(o.output.subarray(0,o.next_out)),o.avail_out=0;else if(o.avail_in===0)break}else this.onData(o.output)}return!0},a1.prototype.onData=function(l){this.chunks.push(l)},a1.prototype.onEnd=function(l){l===YN&&(this.result=KN.flattenChunks(this.chunks)),this.chunks=[],this.err=l,this.msg=this.strm.msg};var qtt={Deflate:a1,deflate:QM,deflateRaw:function(l,i){return(i=i||{}).raw=!0,QM(l,i)},gzip:function(l,i){return(i=i||{}).gzip=!0,QM(l,i)},constants:nO};const JN=16209;var Wtt=function(l,i){let o,p,g,b,A,j,H,z,$,Vt,_r,Fi,_l,_u,_h,_g,eE,oE,SE,vE,fE,mE,EE,PE;const OE=l.state;o=l.next_in,EE=l.input,p=o+(l.avail_in-5),g=l.next_out,PE=l.output,b=g-(i-l.avail_out),A=g+(l.avail_out-257),j=OE.dmax,H=OE.wsize,z=OE.whave,$=OE.wnext,Vt=OE.window,_r=OE.hold,Fi=OE.bits,_l=OE.lencode,_u=OE.distcode,_h=(1<>>24,_r>>>=oE,Fi-=oE,oE=eE>>>16&255,oE===0)PE[g++]=65535&eE;else{if(!(16&oE)){if(!(64&oE)){eE=_l[(65535&eE)+(_r&(1<>>=oE,Fi-=oE),Fi<15&&(_r+=EE[o++]<>>24,_r>>>=oE,Fi-=oE,oE=eE>>>16&255,!(16&oE)){if(!(64&oE)){eE=_u[(65535&eE)+(_r&(1<j){l.msg="invalid distance too far back",OE.mode=JN;break t}if(_r>>>=oE,Fi-=oE,oE=g-b,vE>oE){if(oE=vE-oE,oE>z&&OE.sane){l.msg="invalid distance too far back",OE.mode=JN;break t}if(fE=0,mE=Vt,$===0){if(fE+=H-oE,oE2;)PE[g++]=mE[fE++],PE[g++]=mE[fE++],PE[g++]=mE[fE++],SE-=3;SE&&(PE[g++]=mE[fE++],SE>1&&(PE[g++]=mE[fE++]))}else{fE=g-vE;do PE[g++]=PE[fE++],PE[g++]=PE[fE++],PE[g++]=PE[fE++],SE-=3;while(SE>2);SE&&(PE[g++]=PE[fE++],SE>1&&(PE[g++]=PE[fE++]))}break}}break}}while(o>3,o-=SE,Fi-=SE<<3,_r&=(1<{const H=j.bits;let z,$,Vt,_r,Fi,_l,_u=0,_h=0,_g=0,eE=0,oE=0,SE=0,vE=0,fE=0,mE=0,EE=0,PE=null;const OE=new Uint16Array(16),$E=new Uint16Array(16);let s_,B_,r0,P_=null;for(_u=0;_u<=XN;_u++)OE[_u]=0;for(_h=0;_h=1&&OE[eE]===0;eE--);if(oE>eE&&(oE=eE),eE===0)return g[b++]=20971520,g[b++]=20971520,j.bits=1,0;for(_g=1;_g0&&(l===0||eE!==1))return-1;for($E[1]=0,_u=1;_u852||l===2&&mE>592)return 1;for(;;){s_=_u-vE,A[_h]+1<_l?(B_=0,r0=A[_h]):A[_h]>=_l?(B_=P_[A[_h]-_l],r0=PE[A[_h]-_l]):(B_=96,r0=0),z=1<<_u-vE,$=1<>vE)+$]=s_<<24|B_<<16|r0|0;while($!==0);for(z=1<<_u-1;EE&z;)z>>=1;if(z!==0?(EE&=z-1,EE+=z):EE=0,_h++,--OE[_u]==0){if(_u===eE)break;_u=i[o+A[_h]]}if(_u>oE&&(EE&_r)!==Vt){for(vE===0&&(vE=oE),Fi+=_g,SE=_u-vE,fE=1<852||l===2&&mE>592)return 1;Vt=EE&_r,g[Vt]=oE<<24|SE<<16|Fi-b|0}}return EE!==0&&(g[Fi+EE]=_u-vE<<24|64<<16|0),j.bits=oE,0};const{Z_FINISH:j4,Z_BLOCK:Jtt,Z_TREES:QN,Z_OK:hI,Z_STREAM_END:Xtt,Z_NEED_DICT:Qtt,Z_STREAM_ERROR:lT,Z_DATA_ERROR:V4,Z_MEM_ERROR:B4,Z_BUF_ERROR:$tt,Z_DEFLATED:G4}=nO,$N=16180,ZN=16190,ZT=16191,$M=16192,ZM=16194,tP=16199,eP=16200,t2=16206,y0=16209,q4=l=>(l>>>24&255)+(l>>>8&65280)+((65280&l)<<8)+((255&l)<<24);function Ztt(){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 pI=l=>{if(!l)return 1;const i=l.state;return!i||i.strm!==l||i.mode<$N||i.mode>16211?1:0},W4=l=>{if(pI(l))return lT;const i=l.state;return l.total_in=l.total_out=i.total=0,l.msg="",i.wrap&&(l.adler=1&i.wrap),i.mode=$N,i.last=0,i.havedict=0,i.flags=-1,i.dmax=32768,i.head=null,i.hold=0,i.bits=0,i.lencode=i.lendyn=new Int32Array(852),i.distcode=i.distdyn=new Int32Array(592),i.sane=1,i.back=-1,hI},H4=l=>{if(pI(l))return lT;const i=l.state;return i.wsize=0,i.whave=0,i.wnext=0,W4(l)},z4=(l,i)=>{let o;if(pI(l))return lT;const p=l.state;return i<0?(o=0,i=-i):(o=5+(i>>4),i<48&&(i&=15)),i&&(i<8||i>15)?lT:(p.window!==null&&p.wbits!==i&&(p.window=null),p.wrap=o,p.wbits=i,H4(l))},K4=(l,i)=>{if(!l)return lT;const o=new Ztt;l.state=o,o.strm=l,o.window=null,o.mode=$N;const p=z4(l,i);return p!==hI&&(l.state=null),p};let e2,n2,Y4=!0;const tet=l=>{if(Y4){e2=new Int32Array(512),n2=new Int32Array(32);let i=0;for(;i<144;)l.lens[i++]=8;for(;i<256;)l.lens[i++]=9;for(;i<280;)l.lens[i++]=7;for(;i<288;)l.lens[i++]=8;for(c1(1,l.lens,0,288,e2,0,l.work,{bits:9}),i=0;i<32;)l.lens[i++]=5;c1(2,l.lens,0,32,n2,0,l.work,{bits:5}),Y4=!1}l.lencode=e2,l.lenbits=9,l.distcode=n2,l.distbits=5},J4=(l,i,o,p)=>{let g;const b=l.state;return b.window===null&&(b.wsize=1<=b.wsize?(b.window.set(i.subarray(o-b.wsize,o),0),b.wnext=0,b.whave=b.wsize):(g=b.wsize-b.wnext,g>p&&(g=p),b.window.set(i.subarray(o-p,o-p+g),b.wnext),(p-=g)?(b.window.set(i.subarray(o-p,o),0),b.wnext=p,b.whave=b.wsize):(b.wnext+=g,b.wnext===b.wsize&&(b.wnext=0),b.whave{let o,p,g,b,A,j,H,z,$,Vt,_r,Fi,_l,_u,_h,_g,eE,oE,SE,vE,fE,mE,EE=0;const PE=new Uint8Array(4);let OE,$E;const s_=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(pI(l)||!l.output||!l.input&&l.avail_in!==0)return lT;o=l.state,o.mode===ZT&&(o.mode=$M),A=l.next_out,g=l.output,H=l.avail_out,b=l.next_in,p=l.input,j=l.avail_in,z=o.hold,$=o.bits,Vt=j,_r=H,mE=hI;t:for(;;)switch(o.mode){case $N:if(o.wrap===0){o.mode=$M;break}for(;$<16;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}if(2&o.wrap&&z===35615){o.wbits===0&&(o.wbits=15),o.check=0,PE[0]=255&z,PE[1]=z>>>8&255,o.check=_b(o.check,PE,2,0),z=0,$=0,o.mode=16181;break}if(o.head&&(o.head.done=!1),!(1&o.wrap)||(((255&z)<<8)+(z>>8))%31){l.msg="incorrect header check",o.mode=y0;break}if((15&z)!==G4){l.msg="unknown compression method",o.mode=y0;break}if(z>>>=4,$-=4,fE=8+(15&z),o.wbits===0&&(o.wbits=fE),fE>15||fE>o.wbits){l.msg="invalid window size",o.mode=y0;break}o.dmax=1<>8&1),512&o.flags&&4&o.wrap&&(PE[0]=255&z,PE[1]=z>>>8&255,o.check=_b(o.check,PE,2,0)),z=0,$=0,o.mode=16182;case 16182:for(;$<32;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}o.head&&(o.head.time=z),512&o.flags&&4&o.wrap&&(PE[0]=255&z,PE[1]=z>>>8&255,PE[2]=z>>>16&255,PE[3]=z>>>24&255,o.check=_b(o.check,PE,4,0)),z=0,$=0,o.mode=16183;case 16183:for(;$<16;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}o.head&&(o.head.xflags=255&z,o.head.os=z>>8),512&o.flags&&4&o.wrap&&(PE[0]=255&z,PE[1]=z>>>8&255,o.check=_b(o.check,PE,2,0)),z=0,$=0,o.mode=16184;case 16184:if(1024&o.flags){for(;$<16;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}o.length=z,o.head&&(o.head.extra_len=z),512&o.flags&&4&o.wrap&&(PE[0]=255&z,PE[1]=z>>>8&255,o.check=_b(o.check,PE,2,0)),z=0,$=0}else o.head&&(o.head.extra=null);o.mode=16185;case 16185:if(1024&o.flags&&(Fi=o.length,Fi>j&&(Fi=j),Fi&&(o.head&&(fE=o.head.extra_len-o.length,o.head.extra||(o.head.extra=new Uint8Array(o.head.extra_len)),o.head.extra.set(p.subarray(b,b+Fi),fE)),512&o.flags&&4&o.wrap&&(o.check=_b(o.check,p,Fi,b)),j-=Fi,b+=Fi,o.length-=Fi),o.length))break t;o.length=0,o.mode=16186;case 16186:if(2048&o.flags){if(j===0)break t;Fi=0;do fE=p[b+Fi++],o.head&&fE&&o.length<65536&&(o.head.name+=String.fromCharCode(fE));while(fE&&Fi>9&1,o.head.done=!0),l.adler=o.check=0,o.mode=ZT;break;case 16189:for(;$<32;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}l.adler=o.check=q4(z),z=0,$=0,o.mode=ZN;case ZN:if(o.havedict===0)return l.next_out=A,l.avail_out=H,l.next_in=b,l.avail_in=j,o.hold=z,o.bits=$,Qtt;l.adler=o.check=1,o.mode=ZT;case ZT:if(i===Jtt||i===QN)break t;case $M:if(o.last){z>>>=7&$,$-=7&$,o.mode=t2;break}for(;$<3;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}switch(o.last=1&z,z>>>=1,$-=1,3&z){case 0:o.mode=16193;break;case 1:if(tet(o),o.mode=tP,i===QN){z>>>=2,$-=2;break t}break;case 2:o.mode=16196;break;case 3:l.msg="invalid block type",o.mode=y0}z>>>=2,$-=2;break;case 16193:for(z>>>=7&$,$-=7&$;$<32;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}if((65535&z)!=(z>>>16^65535)){l.msg="invalid stored block lengths",o.mode=y0;break}if(o.length=65535&z,z=0,$=0,o.mode=ZM,i===QN)break t;case ZM:o.mode=16195;case 16195:if(Fi=o.length,Fi){if(Fi>j&&(Fi=j),Fi>H&&(Fi=H),Fi===0)break t;g.set(p.subarray(b,b+Fi),A),j-=Fi,b+=Fi,H-=Fi,A+=Fi,o.length-=Fi;break}o.mode=ZT;break;case 16196:for(;$<14;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}if(o.nlen=257+(31&z),z>>>=5,$-=5,o.ndist=1+(31&z),z>>>=5,$-=5,o.ncode=4+(15&z),z>>>=4,$-=4,o.nlen>286||o.ndist>30){l.msg="too many length or distance symbols",o.mode=y0;break}o.have=0,o.mode=16197;case 16197:for(;o.have>>=3,$-=3}for(;o.have<19;)o.lens[s_[o.have++]]=0;if(o.lencode=o.lendyn,o.lenbits=7,OE={bits:o.lenbits},mE=c1(0,o.lens,0,19,o.lencode,0,o.work,OE),o.lenbits=OE.bits,mE){l.msg="invalid code lengths set",o.mode=y0;break}o.have=0,o.mode=16198;case 16198:for(;o.have>>24,_g=EE>>>16&255,eE=65535&EE,!(_h<=$);){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}if(eE<16)z>>>=_h,$-=_h,o.lens[o.have++]=eE;else{if(eE===16){for($E=_h+2;$<$E;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}if(z>>>=_h,$-=_h,o.have===0){l.msg="invalid bit length repeat",o.mode=y0;break}fE=o.lens[o.have-1],Fi=3+(3&z),z>>>=2,$-=2}else if(eE===17){for($E=_h+3;$<$E;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}z>>>=_h,$-=_h,fE=0,Fi=3+(7&z),z>>>=3,$-=3}else{for($E=_h+7;$<$E;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}z>>>=_h,$-=_h,fE=0,Fi=11+(127&z),z>>>=7,$-=7}if(o.have+Fi>o.nlen+o.ndist){l.msg="invalid bit length repeat",o.mode=y0;break}for(;Fi--;)o.lens[o.have++]=fE}}if(o.mode===y0)break;if(o.lens[256]===0){l.msg="invalid code -- missing end-of-block",o.mode=y0;break}if(o.lenbits=9,OE={bits:o.lenbits},mE=c1(1,o.lens,0,o.nlen,o.lencode,0,o.work,OE),o.lenbits=OE.bits,mE){l.msg="invalid literal/lengths set",o.mode=y0;break}if(o.distbits=6,o.distcode=o.distdyn,OE={bits:o.distbits},mE=c1(2,o.lens,o.nlen,o.ndist,o.distcode,0,o.work,OE),o.distbits=OE.bits,mE){l.msg="invalid distances set",o.mode=y0;break}if(o.mode=tP,i===QN)break t;case tP:o.mode=eP;case eP:if(j>=6&&H>=258){l.next_out=A,l.avail_out=H,l.next_in=b,l.avail_in=j,o.hold=z,o.bits=$,Wtt(l,_r),A=l.next_out,g=l.output,H=l.avail_out,b=l.next_in,p=l.input,j=l.avail_in,z=o.hold,$=o.bits,o.mode===ZT&&(o.back=-1);break}for(o.back=0;EE=o.lencode[z&(1<>>24,_g=EE>>>16&255,eE=65535&EE,!(_h<=$);){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}if(_g&&!(240&_g)){for(oE=_h,SE=_g,vE=eE;EE=o.lencode[vE+((z&(1<>oE)],_h=EE>>>24,_g=EE>>>16&255,eE=65535&EE,!(oE+_h<=$);){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}z>>>=oE,$-=oE,o.back+=oE}if(z>>>=_h,$-=_h,o.back+=_h,o.length=eE,_g===0){o.mode=16205;break}if(32&_g){o.back=-1,o.mode=ZT;break}if(64&_g){l.msg="invalid literal/length code",o.mode=y0;break}o.extra=15&_g,o.mode=16201;case 16201:if(o.extra){for($E=o.extra;$<$E;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}o.length+=z&(1<>>=o.extra,$-=o.extra,o.back+=o.extra}o.was=o.length,o.mode=16202;case 16202:for(;EE=o.distcode[z&(1<>>24,_g=EE>>>16&255,eE=65535&EE,!(_h<=$);){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}if(!(240&_g)){for(oE=_h,SE=_g,vE=eE;EE=o.distcode[vE+((z&(1<>oE)],_h=EE>>>24,_g=EE>>>16&255,eE=65535&EE,!(oE+_h<=$);){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}z>>>=oE,$-=oE,o.back+=oE}if(z>>>=_h,$-=_h,o.back+=_h,64&_g){l.msg="invalid distance code",o.mode=y0;break}o.offset=eE,o.extra=15&_g,o.mode=16203;case 16203:if(o.extra){for($E=o.extra;$<$E;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}o.offset+=z&(1<>>=o.extra,$-=o.extra,o.back+=o.extra}if(o.offset>o.dmax){l.msg="invalid distance too far back",o.mode=y0;break}o.mode=16204;case 16204:if(H===0)break t;if(Fi=_r-H,o.offset>Fi){if(Fi=o.offset-Fi,Fi>o.whave&&o.sane){l.msg="invalid distance too far back",o.mode=y0;break}Fi>o.wnext?(Fi-=o.wnext,_l=o.wsize-Fi):_l=o.wnext-Fi,Fi>o.length&&(Fi=o.length),_u=o.window}else _u=g,_l=A-o.offset,Fi=o.length;Fi>H&&(Fi=H),H-=Fi,o.length-=Fi;do g[A++]=_u[_l++];while(--Fi);o.length===0&&(o.mode=eP);break;case 16205:if(H===0)break t;g[A++]=o.length,H--,o.mode=eP;break;case t2:if(o.wrap){for(;$<32;){if(j===0)break t;j--,z|=p[b++]<<$,$+=8}if(_r-=H,l.total_out+=_r,o.total+=_r,4&o.wrap&&_r&&(l.adler=o.check=o.flags?_b(o.check,g,_r,A-_r):ZO(o.check,g,_r,A-_r)),_r=H,4&o.wrap&&(o.flags?z:q4(z))!==o.check){l.msg="incorrect data check",o.mode=y0;break}z=0,$=0}o.mode=16207;case 16207:if(o.wrap&&o.flags){for(;$<32;){if(j===0)break t;j--,z+=p[b++]<<$,$+=8}if(4&o.wrap&&z!==(4294967295&o.total)){l.msg="incorrect length check",o.mode=y0;break}z=0,$=0}o.mode=16208;case 16208:mE=Xtt;break t;case y0:mE=V4;break t;case 16210:return B4;default:return lT}return l.next_out=A,l.avail_out=H,l.next_in=b,l.avail_in=j,o.hold=z,o.bits=$,(o.wsize||_r!==l.avail_out&&o.modeK4(l,15),inflateInit2:K4,inflate:eet,inflateEnd:l=>{if(pI(l))return lT;let i=l.state;return i.window&&(i.window=null),l.state=null,hI},inflateGetHeader:(l,i)=>{if(pI(l))return lT;const o=l.state;return 2&o.wrap?(o.head=i,i.done=!1,hI):lT},inflateSetDictionary:(l,i)=>{const o=i.length;let p,g,b;return pI(l)?lT:(p=l.state,p.wrap!==0&&p.mode!==ZN?lT:p.mode===ZN&&(g=1,g=ZO(g,i,o,0),g!==p.check)?V4:(b=J4(l,i,o,o),b?(p.mode=16210,B4):(p.havedict=1,hI)))},inflateInfo:"pako inflate (from Nodeca project)"},net=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 X4=Object.prototype.toString,{Z_NO_FLUSH:ret,Z_FINISH:iet,Z_OK:u1,Z_STREAM_END:r2,Z_NEED_DICT:i2,Z_STREAM_ERROR:set,Z_DATA_ERROR:Q4,Z_MEM_ERROR:oet}=nO;function l1(l){this.options=KN.assign({chunkSize:65536,windowBits:15,to:""},l||{});const i=this.options;i.raw&&i.windowBits>=0&&i.windowBits<16&&(i.windowBits=-i.windowBits,i.windowBits===0&&(i.windowBits=-15)),!(i.windowBits>=0&&i.windowBits<16)||l&&l.windowBits||(i.windowBits+=32),i.windowBits>15&&i.windowBits<48&&!(15&i.windowBits)&&(i.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new U4,this.strm.avail_out=0;let o=tR.inflateInit2(this.strm,i.windowBits);if(o!==u1)throw new Error(cI[o]);if(this.header=new net,tR.inflateGetHeader(this.strm,this.header),i.dictionary&&(typeof i.dictionary=="string"?i.dictionary=o1.string2buf(i.dictionary):X4.call(i.dictionary)==="[object ArrayBuffer]"&&(i.dictionary=new Uint8Array(i.dictionary)),i.raw&&(o=tR.inflateSetDictionary(this.strm,i.dictionary),o!==u1)))throw new Error(cI[o])}function s2(l,i){const o=new l1(i);if(o.push(l),o.err)throw o.msg||cI[o.err];return o.result}l1.prototype.push=function(l,i){const o=this.strm,p=this.options.chunkSize,g=this.options.dictionary;let b,A,j;if(this.ended)return!1;for(A=i===~~i?i:i===!0?iet:ret,X4.call(l)==="[object ArrayBuffer]"?o.input=new Uint8Array(l):o.input=l,o.next_in=0,o.avail_in=o.input.length;;){for(o.avail_out===0&&(o.output=new Uint8Array(p),o.next_out=0,o.avail_out=p),b=tR.inflate(o,A),b===i2&&g&&(b=tR.inflateSetDictionary(o,g),b===u1?b=tR.inflate(o,A):b===Q4&&(b=i2));o.avail_in>0&&b===r2&&o.state.wrap>0&&l[o.next_in]!==0;)tR.inflateReset(o),b=tR.inflate(o,A);switch(b){case set:case Q4:case i2:case oet:return this.onEnd(b),this.ended=!0,!1}if(j=o.avail_out,o.next_out&&(o.avail_out===0||b===r2))if(this.options.to==="string"){let H=o1.utf8border(o.output,o.next_out),z=o.next_out-H,$=o1.buf2string(o.output,H);o.next_out=z,o.avail_out=p-z,z&&o.output.set(o.output.subarray(H,H+z),0),this.onData($)}else this.onData(o.output.length===o.next_out?o.output:o.output.subarray(0,o.next_out));if(b!==u1||j!==0){if(b===r2)return b=tR.inflateEnd(this.strm),this.onEnd(b),this.ended=!0,!0;if(o.avail_in===0)break}}return!0},l1.prototype.onData=function(l){this.chunks.push(l)},l1.prototype.onEnd=function(l){l===u1&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=KN.flattenChunks(this.chunks)),this.chunks=[],this.err=l,this.msg=this.strm.msg};var aet={Inflate:l1,inflate:s2,inflateRaw:function(l,i){return(i=i||{}).raw=!0,s2(l,i)},ungzip:s2,constants:nO};const{Deflate:mnt,deflate:cet,deflateRaw:gnt,gzip:Ent}=qtt,{Inflate:vnt,inflate:uet,inflateRaw:_nt,ungzip:ynt}=aet;var o2,det=cet,het=uet;(function(l){l[l.ONE_BYTE=0]="ONE_BYTE",l[l.TWO_BYTE=1]="TWO_BYTE"})(o2||(o2={}));class pet{constructor(){_e(this,"_sequence",0),_e(this,"_startTime",Date.now()),_e(this,"isUseOneByte",!0)}get startTime(){const i=Date.now()-this._startTime;return i128){const j=new Uint8Array(4);j.set([1,0,0,0]);const H={id:0,length:4,data:j.buffer},z={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[H]};o.commonPacketHeader.extension=1,o.extension=z,o.payload=this.compress(i),o.commonPacketHeader.length=8+(o.extension.length+2)+o.payload.byteLength}else o.commonPacketHeader.length=8+o.payload.byteLength;const p=new ArrayBuffer(o.commonPacketHeader.length),g=new Uint8Array(p),b=new DataView(p);let A=0;if(b.setUint16(A,o.commonPacketHeader.extension<<15|o.commonPacketHeader.reserved<<14|o.commonPacketHeader.length,!0),A+=2,b.setUint32(A,o.commonPacketHeader.sequence,!0),A+=4,b.setUint16(A,o.commonStreamHeader,!0),A+=2,o.extension){const j=this.serializeExtension(o.extension);g.set(new Uint8Array(j),A),A+=j.byteLength}if(g.set(new Uint8Array(o.payload),A),A+=o.payload.byteLength,A!==o.commonPacketHeader.length)throw Error("serialize error!");return p}deserialize(i){if(i.byteLength<4)return new ArrayBuffer(0);const o=new DataView(i);let p=0;const g=o.getUint16(p,!0);p+=2;const b=(32768&g)>>15;o.getUint16(p+2,!0),o.getUint16(p,!0);let A,j;if(p+=4,o.getUint16(p,!0),p+=2,b){j=this.deserializeExtension(i.slice(p)),p+=2+j.length,A=i.slice(p);let H=!1;if(j.datas.length>0){const z=j.datas.find($=>$.id===0);z&&(H=(1&new DataView(z.data).getUint32(0,!0))==1)}A=H?this.decompress(A):A}else A=i.slice(8);return A}serializeExtension(i){const{profile:o,length:p,datas:g}=i,b=new ArrayBuffer(p+2),A=new Uint8Array(b),j=new DataView(b);let H=0;if(j.setUint8(H++,o),j.setUint8(H++,p),g.forEach(z=>{o?(j.setUint8(H++,z.id),j.setUint8(H++,z.length),A.set(new Uint8Array(z.data),H),H+=z.data.byteLength):(j.setUint8(H++,z.id|z.length<<4),A.set(new Uint8Array(z.data),H),H+=z.data.byteLength)}),H!==p+2)throw Error("serialize extension error, is ".concat(H,"!==").concat(p+2));return b}deserializeExtension(i){const o=new DataView(i);let p=0;const g=o.getUint8(p);p++;const b=o.getUint8(p);p++;const A=g===o2.TWO_BYTE,j=[],H=new DataView(i,2);let z=0;for(;z>4,z++),Vt>0&&(_r=H.buffer.slice(z+2,z+2+Vt),z+=_r.byteLength),j.push({id:$,length:Vt,data:_r})}if(z!==b)throw Error("parse error");return{profile:g,length:b,datas:j}}decompress(i){return het(new Uint8Array(i))}compress(i){return det(new Uint8Array(i))}}class $4 extends D_{constructor(i,o){super(),_e(this,"_version",1),_e(this,"_type",3),_e(this,"_config",void 0),_e(this,"_originDataChannel",void 0),_e(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),_e(this,"_dataStreamPacketHandler",void 0),_e(this,"_datachannelEventMap",new Map),this._config=i,o&&(this._originDataChannel=o,this._bandDataChannelEvents(o)),this._initPacketHeader(),this._dataStreamPacketHandler=new pet}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return nE("DATASTREAM_MAX_RETRANSMITS")}get metadata(){return this._config.metadata}get readyState(){var i,o;return(i=(o=this._originDataChannel)===null||o===void 0?void 0:o.readyState)!==null&&i!==void 0?i:"connecting"}get _originDataChannelId(){var i,o;return(i=(o=this._originDataChannel)===null||o===void 0?void 0:o.id)!==null&&i!==void 0?i:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}async _waitTillOpen(){return new pE((i,o)=>{if(this._originDataChannel){this._originDataChannel.readyState==="open"&&i();const p=setTimeout(()=>{var g;o(new yE(_p.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat((g=this._originDataChannel)===null||g===void 0?void 0:g.id)))},1e4);this._originDataChannel.onopen=()=>{clearTimeout(p),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),i()},this._originDataChannel.onerror=()=>{throw clearTimeout(p),new yE(_p.DATACHANNEL_CONNECTION_TIMEOUT)}}else o(new yE(_p.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"))})}_updateOriginDataChannel(i){this._originDataChannel=i,this._bandDataChannelEvents(i)}_initPacketHeader(){const i=new DataView(this._dataStreamPacketHeader);i.setUint16(0,this._version),i.setUint8(2,this._type),i.setUint8(3,this._config.id)}_bandDataChannelEvents(i){this._unbindDataChannelEvents(i),[ZI.OPEN,ZI.CLOSE,ZI.ERROR].forEach(o=>{const p=()=>{this.emit(o)};this._datachannelEventMap.set(o,p),i.addEventListener(o,p)})}_unbindDataChannelEvents(i){Array.from(this._datachannelEventMap.entries()).forEach(o=>{let[p,g]=o;i.removeEventListener(p,g)}),this._datachannelEventMap.clear()}}class fet extends $4{constructor(i){super(i),_e(this,"_messageListener",void 0),this._messageListener=o=>{if(o.data.byteLength500)return;this.resultStorage.has(i)||this.resultStorage.set(i,{result:[],isPrevNormal:!0});const g=this.resultStorage.get(i);if(g&&(g.result.push(p),g.result.length>=5)){var b;const A=VE(b=g.result).call(b,!0);g.isPrevNormal&&!A&&this.emit("exception",t5[i],i,o),!g.isPrevNormal&&A&&this.emit("exception",t5[i]+2e3,i+"_RECOVER",o),g.isPrevNormal=A,g.result=[]}}checkAudioOutputLevel(i){return!(i.receiveBitrate>0&&i.receiveLevel===0)}checkAudioInputLevel(i,o){return o instanceof Z_&&!o.isActive||!!o.muted||i.sendVolumeLevel!==0}checkFramerateInput(i,o){let p=null;o._encoderConfig&&o._encoderConfig.frameRate&&(p=US(o._encoderConfig.frameRate));const g=i.captureFrameRate;return!p||!g||!(p>10&&g<5||p<10&&p>=5&&g<=1)}checkFramerateSent(i){return!(i.captureFrameRate&&i.sendFrameRate&&i.captureFrameRate>5&&i.sendFrameRate<=1)}checkSendVideoBitrate(i,o){return!!o.muted||i.sendBitrate!==0}checkSendAudioBitrate(i,o){return o instanceof Z_&&!o.isActive||!!o.muted||i.sendBitrate!==0}checkVideoDecode(i){return i.receiveBitrate===0||i.decodeFrameRate!==0}}const t5={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},k0=new class{markSubscribeStart(l,i){performance.mark("agora-web-sdk/".concat(l,"/subscribe-").concat(i))}markPublishStart(l,i){performance.mark("agora-web-sdk/".concat(l,"/publish-").concat(i))}measureFromSubscribeStart(l,i){const o=performance.getEntriesByName("agora-web-sdk/".concat(l,"/subscribe-").concat(i));if(o.length>0){const p=o[o.length-1];return Math.round(performance.now()-p.startTime)}return 0}measureFromPublishStart(l,i){const o=performance.getEntriesByName("agora-web-sdk/".concat(l,"/publish-").concat(i));if(o.length>0){const p=o[o.length-1];return Math.round(performance.now()-p.startTime)}return 0}};function e5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function fI(l){for(var i=1;i{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))}),this.store=i,this.updateStatsInterval=window.setInterval(this.updateStats,1e3),this.exceptionMonitor=new met,this.exceptionMonitor.on("exception",(o,p,g)=>{this.onStatsException&&this.onStatsException(o,p,g)})}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(TE.LocalAudioTrack)||fI({},CM)}getLocalVideoTrackStats(){return this.localStats.get(TE.LocalVideoTrack)||fI({},IM)}getRemoteAudioTrackStats(i){const o=(b,A)=>{if(!this.trafficStats)return A;const j=this.trafficStats.peer_delay.find(H=>H.peer_uid===b);return j&&(A.publishDuration=j.B_ppad+(Date.now()-this.trafficStats.timestamp)),A},p={};if(i){var g;const b=(g=this.remoteStats.get(i))===null||g===void 0?void 0:g.audioStats;b&&(p[i]=o(i,b))}else Array.from(this.remoteStats.entries()).forEach(b=>{let[A,{audioStats:j}]=b;j&&(p[A]=o(A,j))});return p}getRemoteNetworkQualityStats(i){const o={};if(i){var p;const g=(p=this.remoteStats.get(i))===null||p===void 0?void 0:p.networkStats;g&&(o[i]=g)}else Array.from(this.remoteStats.entries()).forEach(g=>{let[b,{networkStats:A}]=g;A&&(o[b]=A)});return o}getRemoteVideoTrackStats(i){const o=(b,A)=>{if(!this.trafficStats)return A;const j=this.trafficStats.peer_delay.find(H=>H.peer_uid===b);return j&&(A.publishDuration=j.B_ppvd+(Date.now()-this.trafficStats.timestamp)),A},p={};if(i){var g;const b=(g=this.remoteStats.get(i))===null||g===void 0?void 0:g.videoStats;b&&(p[i]=o(i,b))}else Array.from(this.remoteStats.entries()).forEach(b=>{let[A,{videoStats:j}]=b;j&&(p[A]=o(A,j))});return p}getRTCStats(){let i=0,o=0,p=0,g=0;const b=this.localStats.get(TE.LocalAudioTrack);b&&(i+=b.sendBytes,o+=b.sendBitrate);const A=this.localStats.get(TE.LocalVideoTrack);A&&(i+=A.sendBytes,o+=A.sendBitrate);const j=this.localStats.get(TE.LocalVideoLowTrack);j&&(i+=j.sendBytes,o+=j.sendBitrate),this.remoteStats.forEach(z=>{let{audioStats:$,videoStats:Vt}=z;$&&(p+=$.receiveBytes,g+=$.receiveBitrate),Vt&&(p+=Vt.receiveBytes,g+=Vt.receiveBitrate)});let H=1;return this.trafficStats&&(H+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:H,SendBitrate:o,SendBytes:i,RecvBytes:p,RecvBitrate:g,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(i){this.localStats.set(i,void 0)}removeLocalStats(i){i?this.localStats.delete(i):this.localStats.clear()}addRemoteStats(i){this.remoteStats.set(i,{})}removeRemoteStats(i){i?this.remoteStats.delete(i):this.remoteStats.clear()}addP2PChannel(i){this.p2pChannel=i}updateTrafficStats(i){i.peer_delay=i.peer_delay.filter(o=>o.B_ppad!==void 0||o.B_ppvd!==void 0),i.peer_delay.filter(o=>this.trafficStatsPeerList.indexOf(o.peer_uid)===-1).forEach(o=>{var p;const g=(p=this.p2pChannel)===null||p===void 0?void 0:p.getRemoteMedia(o.peer_uid),b=g!=null&&g.videoSSRC?k0.measureFromSubscribeStart(this.store.clientId,g.videoSSRC):0,A=g!=null&&g.audioSSRC?k0.measureFromSubscribeStart(this.store.clientId,g.audioSSRC):0;o.B_ppad!==void 0&&o.B_ppvd!==void 0&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(o.peer_uid,o.B_ppad,o.B_ppvd,b>A?b:A),this.trafficStatsPeerList.push(o.peer_uid))}),this.trafficStats=i}updateUplinkStats(i){this.uplinkStats&&this.uplinkStats.B_fir!==i.B_fir&&Gi.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(i.B_fir)),this.uplinkStats=i}static isRemoteVideoFreeze(i,o,p){if(!i)return!1;const g=!!p&&o.framesDecodeFreezeTime>p.framesDecodeFreezeTime,b=!p||o.framesDecodeCount>p.framesDecodeCount;return g||!b}static isRemoteAudioFreeze(i){return!!i&&i._isFreeze()}isLocalVideoFreeze(i){return!(!i.inputFrame||!i.sentFrame)&&i.inputFrame.frameRate>5&&i.sentFrame.frameRate<3}updateLocalStats(i){Array.from(this.localStats.entries()).forEach(o=>{let[p,g]=o;switch(p){case TE.LocalVideoTrack:case TE.LocalVideoLowTrack:{const A=g,j=fI({},IM),H=i.getStats(),z=i.getLocalMedia(p);if(H){const $=H.videoSend.find(Vt=>Vt.ssrc===(z==null?void 0:z.ssrcs[0].ssrcId));if($){const Vt=i.getLocalVideoSize(),_r=i.getEncoderConfig(TE.LocalVideoTrack);$.codec!=="H264"&&$.codec!=="H265"&&$.codec!=="VP8"&&$.codec!=="VP9"&&$.codec!=="AV1X"&&$.codec!=="AV1"||(j.codecType=$.codec),j.sendBytes=$.bytes,j.sendBitrate=A?8*Math.max(0,j.sendBytes-A.sendBytes):0,$.inputFrame?(j.captureFrameRate=$.inputFrame.frameRate,j.captureResolutionHeight=$.inputFrame.height,j.captureResolutionWidth=$.inputFrame.width):Vt&&(j.captureResolutionWidth=Vt.width,j.captureResolutionHeight=Vt.height),$.sentFrame?(j.sendFrameRate=$.sentFrame.frameRate,j.sendResolutionHeight=$.sentFrame.height,j.sendResolutionWidth=$.sentFrame.width):Vt&&(j.sendResolutionWidth=Vt.width,j.sendResolutionHeight=Vt.height),$.avgEncodeMs&&(j.encodeDelay=$.avgEncodeMs),_r&&_r.bitrateMax&&(j.targetSendBitrate=1e3*_r.bitrateMax),j.sendPackets=$.packets,j.sendPacketsLost=$.packetsLost,j.sendJitterMs=$.jitterMs,j.sendRttMs=$.rttMs,j.totalDuration=A?A.totalDuration+1:1,j.totalFreezeTime=A?A.totalFreezeTime:0,this.isLocalVideoFreeze($)&&(j.totalFreezeTime+=1),$.scalabilityMode&&this.scalabilityMode!==$.scalabilityMode&&(Gi.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat($.scalabilityMode)),this.scalabilityMode=$.scalabilityMode)}this.trafficStats&&(j.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var b;this.localStats.set(p,j),((A==null?void 0:A.sendResolutionWidth)!==j.sendResolutionWidth||(A==null?void 0:A.sendResolutionHeight)!==j.sendResolutionHeight)&&((b=this.onStatsChanged)===null||b===void 0||b.call(this,"resolution",{width:j.sendResolutionWidth,height:j.sendResolutionHeight})),j&&z&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,z.track,j);break}case TE.LocalAudioTrack:{const A=g,j=fI({},CM),H=i.getStats(),z=i.getLocalMedia(p);if(H){const $=H.audioSend.find(Vt=>Vt.ssrc===(z==null?void 0:z.ssrcs[0].ssrcId));if($){if($.codec!=="opus"&&$.codec!=="aac"&&$.codec!=="PCMU"&&$.codec!=="PCMA"&&$.codec!=="G722"||(j.codecType=$.codec),$.inputLevel)j.sendVolumeLevel=Math.round(32767*$.inputLevel);else{const Vt=i.getLocalAudioVolume();Vt&&(j.sendVolumeLevel=Math.round(32767*Vt))}j.sendBytes=$.bytes,j.sendPackets=$.packets,j.sendPacketsLost=$.packetsLost,j.sendJitterMs=$.jitterMs,j.sendRttMs=$.rttMs,j.sendBitrate=A?8*Math.max(0,j.sendBytes-A.sendBytes):0}}this.trafficStats&&(j.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(TE.LocalAudioTrack,j),j&&z&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,z.track,j);break}}})}updateRemoteStats(i){Array.from(this.remoteStats.entries()).forEach(o=>{let[p,{videoStats:g,audioStats:b,videoPcStats:A}]=o;const j=b,H=g,z=A,$=fI({},k6),Vt=fI({},D6),_r=fI({},$Z),{audioTrack:Fi,videoTrack:_l,audioSSRC:_u,videoSSRC:_h}=i.getRemoteMedia(p),_g=i.getStats(),eE=_g==null?void 0:_g.audioRecv.find(vE=>vE.ssrc===_u),oE=_g==null?void 0:_g.videoRecv.find(vE=>vE.ssrc===_h),SE=this.trafficStats&&this.trafficStats.peer_delay.find(vE=>vE.peer_uid===p);if(eE&&(eE.codec!=="opus"&&eE.codec!=="aac"&&eE.codec!=="PCMU"&&eE.codec!=="PCMA"&&eE.codec!=="G722"||($.codecType=eE.codec),eE.outputLevel?$.receiveLevel=Math.round(32767*eE.outputLevel):Fi&&($.receiveLevel=Math.round(32767*Fi.getVolumeLevel())),$.receiveBytes=eE.bytes,$.receivePackets=eE.packets,$.receivePacketsLost=eE.packetsLost,$.packetLossRate=$.receivePacketsLost/($.receivePackets+$.receivePacketsLost),$.receiveBitrate=j?8*Math.max(0,$.receiveBytes-j.receiveBytes):0,$.totalDuration=j?j.totalDuration+1:1,$.totalFreezeTime=j?j.totalFreezeTime:0,$.freezeRate=$.totalFreezeTime/$.totalDuration,$.receiveDelay=eE.jitterBufferMs,$.totalDuration>10&&oO.isRemoteAudioFreeze(Fi)&&($.totalFreezeTime+=1)),oE){oE.codec!=="H264"&&oE.codec!=="H265"&&oE.codec!=="VP8"&&oE.codec!=="VP9"&&oE.codec!=="AV1X"&&oE.codec!=="AV1"||(Vt.codecType=oE.codec),Vt.receiveBytes=oE.bytes,Vt.receiveBitrate=H?8*Math.max(0,Vt.receiveBytes-H.receiveBytes):0,Vt.decodeFrameRate=oE.decodeFrameRate<0?0:oE.decodeFrameRate,Vt.renderFrameRate=oE.decodeFrameRate<0?0:oE.decodeFrameRate,oE.outputFrame&&(Vt.renderFrameRate=oE.outputFrame.frameRate),oE.receivedFrame?(Vt.receiveFrameRate=oE.receivedFrame.frameRate,Vt.receiveResolutionHeight=oE.receivedFrame.height,Vt.receiveResolutionWidth=oE.receivedFrame.width):_l&&(Vt.receiveResolutionHeight=_l._videoHeight||0,Vt.receiveResolutionWidth=_l._videoWidth||0),oE.framesRateFirefox!==void 0&&(Vt.receiveFrameRate=Math.round(oE.framesRateFirefox)),Vt.receivePackets=oE.packets,Vt.receivePacketsLost=oE.packetsLost,Vt.packetLossRate=Vt.receivePacketsLost/(Vt.receivePackets+Vt.receivePacketsLost),Vt.totalDuration=H?H.totalDuration+1:1,Vt.totalFreezeTime=H?H.totalFreezeTime:0,Vt.receiveDelay=oE.jitterBufferMs||0;const vE=!!_h&&i.getRemoteVideoIsReady(_h);_l&&vE&&oO.isRemoteVideoFreeze(_l,oE,z)&&(Vt.totalFreezeTime+=1),Vt.freezeRate=Vt.totalFreezeTime/Vt.totalDuration}SE&&($.end2EndDelay=SE.B_ad,Vt.end2EndDelay=SE.B_vd,$.transportDelay=SE.B_ed,Vt.transportDelay=SE.B_ed,$.currentPacketLossRate=SE.B_ealr4/100,Vt.currentPacketLossRate=SE.B_evlr4/100,_r.uplinkNetworkQuality=SE.B_punq?SE.B_punq:0,_r.downlinkNetworkQuality=SE.B_pdnq?SE.B_pdnq:0),this.remoteStats.set(p,{audioStats:$,videoStats:Vt,videoPcStats:oE,networkStats:_r}),Fi&&this.exceptionMonitor.setRemoteAudioStats(Fi,$),_l&&this.exceptionMonitor.setRemoteVideoStats(_l,Vt)})}}function n5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function nP(l){for(var i=1;iH.domain_prefix?{address:"".concat(H.domain_prefix,".").concat(g[b++%g.length],":").concat(H.port)}:H.ip.match(/^[\.\:\d]+$/)?{ip:H.ip,port:H.port,address:"".concat(H.ip.replace(/[^\d]/g,"-"),".").concat(g[b++%g.length],":").concat(H.port)}:(Gi.info("Cannot recognized as IP address ".concat(H.ip,". Used As Host instead")),{ip:H.ip,port:H.port,address:"".concat(H.ip,":").concat(H.port)}));if((o=l.detail)!==null&&o!==void 0&&o[18]&&typeof((p=l.detail)===null||p===void 0?void 0:p[18])=="string"){const H=l.detail[18],z=H==null?void 0:H.split(";");for(let $=0;$=0&&l<.17?1:l>=.17&&l<.36?2:l>=.36&&l<.59?3:l>=.59&&l<=1?4:l>1?5:0}function a2(l,i){let o,p,g;switch(i){case v0.CHOOSE_SERVER:p=4096,g="choose server";break;case v0.CLOUD_PROXY:p=1048576,g="proxy";break;case v0.CLOUD_PROXY_5:p=4194304,g="proxy5";break;case v0.CLOUD_PROXY_FALLBACK:p=4194310,g="proxy fallback";break;default:throw new hE(_p.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:l.detail&&l.detail[502],retry:!1})}if(l.response_body.forEach(b=>{b.buffer&&b.buffer.flag===p&&(o={code:b.buffer.code,addresses:(b.buffer.edges_services||[]).map(A=>nP(nP({},A),{},{ticket:b.buffer.cert})),server_ts:l.enter_ts,uid:b.buffer.uid,cid:b.buffer.cid,cname:b.buffer.cname,detail:nP(nP({},b.buffer.detail),l.detail),flag:b.buffer.flag,opid:l.opid,cert:b.buffer.cert})}),!o)throw new hE(_p.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(g," from multi unilbs response"),{csIp:l.detail&&l.detail[502]});return o}async function get(l,i){return await pE.all(l.addresses.map(async o=>({address:d1(o.ip),tcpport:o.port,udpport:o.port,username:i&&nE("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?i.toString():wS.username,password:i&&nE("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await T$(i.toString()):wS.password})))}function c2(l,i){const o=i._videoHeight||i.getMediaStreamTrack(!0).getSettings().height;return o?Math.max(o/US(l.height),1):(Gi.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function wR(l){let{candidateType:i,relayProtocol:o,type:p,address:g,port:b,protocol:A}=l;return p==="local-candidate"?{candidateType:i,relayProtocol:o,protocol:A}:{candidateType:i,relayProtocol:o,address:g,port:b,protocol:A}}function o5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}class Eet extends D_{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(i){var o;VE(o=["tryNext","recover"]).call(o,i)&&this.resetReconnectCount(i),this._reconnectMode=i}get state(){return this._state}set state(i){i!==this._state&&(this._state=i,this._state==="reconnecting"?this.emit(W_.RECONNECTING,this.reconnectReason):this._state==="connected"?this.emit(W_.CONNECTED):this._state==="closed"?this.emit(W_.CLOSED):this._state==="failed"&&this.emit(W_.FAILED))}constructor(i,o,p,g){super(),_e(this,"connectionID",0),_e(this,"currentURLIndex",0),_e(this,"reconnectReason",void 0),_e(this,"_reconnectMode","tryNext"),_e(this,"_name",void 0),_e(this,"_state","closed"),_e(this,"_retryConfig",void 0),_e(this,"_reconnectCount",0),_e(this,"_forceCloseTimeout",5e3),_e(this,"_onlineReconnectListener",void 0),_e(this,"_closeEstablishingTransmitter",()=>{}),_e(this,"_store",void 0),_e(this,"_joinChannelServiceRecordIndex",void 0),_e(this,"_useCompress",void 0),_e(this,"_inflateLength",0),_e(this,"_deflateLength",0),this._store=g,this._name=i,this._retryConfig=function(b){for(var A=1;Ap.close(),500):p.close(),this._transmitter=void 0}this.state=i?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter()}reconnect(i,o){if(!this._transmitter)return void Gi.warning("[".concat(this._name,"] can not reconnect, no websocket"));var p;i!==void 0&&(this.reconnectMode=i),Gi.debug("[".concat(this._name,"] reconnect is triggered initiative")),typeof this._joinChannelServiceRecordIndex=="number"&&((p=this._store)===null||p===void 0||p.recordJoinChannelService({status:"error",errors:[new Error(o)]},this._joinChannelServiceRecordIndex));const g=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),g&&g.bind(this._transmitter)({code:9999,reason:o})}getInflateData(){const i=this._inflateLength,o=this._deflateLength;return this.clearInflateData(),{inflateLength:i,deflateLength:o}}setInflateData(i){this._deflateLength=this._deflateLength+i.originLength,this._inflateLength=this._inflateLength+i.compressedLength}clearInflateData(){this._inflateLength=0,this._deflateLength=0}}var YS;(function(l){l[l.Default=0]="Default",l[l.Ack=1]="Ack"})(YS||(YS={}));class vet{constructor(i,o,p){_e(this,"version",1),_e(this,"initialRTO",void 0),_e(this,"maxBatchAckCount",void 0),_e(this,"maxRTO",void 0),_e(this,"initialRTT",void 0),_e(this,"ID",void 0),_e(this,"rtt",void 0),_e(this,"packetNumber",1),_e(this,"rtoRatioMap",new Map),_e(this,"timeoutMap",new Map),_e(this,"unorderedPacketQueue",[]),_e(this,"batchAckPacketQueue",[]),_e(this,"lastOrderedPacketNumber",0),_e(this,"batchAckTimer",void 0),_e(this,"sendImpl",void 0),_e(this,"receiveImpl",void 0),this.sendImpl=i,this.receiveImpl=o,this.ID=T_(7,"transmitter-"),this.initialRTO=(p==null?void 0:p.initialRTO)!==void 0?p.initialRTO:nE("TRANSMITTER_INITIAL_RTO"),this.initialRTT=(p==null?void 0:p.initialRTT)!==void 0?p.initialRTT:nE("TRANSMITTER_INITIAL_RTT"),this.rtt=(p==null?void 0:p.initialRTT)!==void 0?p.initialRTT:nE("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=(p==null?void 0:p.maxBatchAckCount)!==void 0?p.maxBatchAckCount:nE("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=(p==null?void 0:p.maxRTO)!==void 0?p.maxRTO:nE("TRANSMITTER_MAX_RTO")}packetize(i,o){return{type:YS.Default,version:this.version,packetNumber:o,payload:i}}serialize(i){switch(i.type){case YS.Default:{let o;typeof i.payload=="string"?o=new TextEncoder().encode(i.payload):o=i.payload;const p=new ArrayBuffer(o.length+15),g=new DataView(p);return g.setUint16(0,i.version),g.setUint8(2,i.type),g.setUint32(3,i.packetNumber),YV(g,7,BigInt(i.sendTs)),new Uint8Array(g.buffer).set(o,15),p}case YS.Ack:{const o=new ArrayBuffer(16),p=new DataView(o);return p.setUint16(0,i.version),p.setUint8(2,i.type),p.setUint32(3,i.maxAckPacketNumber),p.setUint8(7,i.shift),YV(p,8,BigInt(i.ackSendTs)),o}}}deserialize(i){const o=new DataView(i),p=o.getUint16(0),g=o.getUint8(2);switch(g){case YS.Default:{const b=o.getUint32(3),A=KV(o,7),j=i.slice(15),H=new TextDecoder().decode(j);return{version:p,type:g,packetNumber:b,sendTs:Number(A),payload:H}}case YS.Ack:{const b=o.getUint32(3),A=o.getUint8(7),j=KV(o,8);return{version:p,type:g,maxAckPacketNumber:b,shift:A,ackSendTs:Number(j)}}default:throw Gi.error("[".concat(this.ID,"] Unrecognized packet type ").concat(g)),new Error("Unrecognized packet type ".concat(g))}}sendMessage(i){const o=this.packetize(i,this.packetNumber);this.packetNumber=this.packetNumber===4294967295?1:this.packetNumber+1;const p=this.calculateRTO(o),g=window.setTimeout(()=>{this.resendMessage(o)},p);this.timeoutMap.set(o.packetNumber,g),this.sendPacket(o)}onData(i){const o=this.deserialize(i);o.type===YS.Default?this.ack(o):o.type===YS.Ack&&(this.updateRTT(o,Math.round(performance.now())),this.clearRTO(o))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach(i=>{let[o,p]=i;window.clearTimeout(p)}),this.timeoutMap=new Map,this.rtoRatioMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,this.batchAckTimer!==void 0&&window.clearTimeout(this.batchAckTimer)}resendMessage(i){const o=this.calculateRTO(i),p=window.setTimeout(()=>{this.resendMessage(i)},o);this.timeoutMap.set(i.packetNumber,p),this.sendPacket(i)}calculateRTO(i){const o=this.rtoRatioMap.get(i.packetNumber);if(o===void 0)return this.rtoRatioMap.set(i.packetNumber,1),this.initialRTO;{const p=9*this.rtt/8*o;return this.rtoRatioMap.set(i.packetNumber,o+1),p>this.maxRTO?this.maxRTO:p}}updateRTT(i,o){const p=i.ackSendTs;this.rtt=this.rtt*(7/8)+(o-p-this.rtt)/8}ack(i){if(i.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(i):(this.batchAckPacketQueue.push(i),this.batchAckTimer=window.setTimeout(()=>{this.batchAck()},this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(i.payload);;){const o=this.unorderedPacketQueue[0];if(!o){this.unorderedPacketQueue.shift();break}this.batchAckTimer&&this.batchAck(),this.receiveImpl(o.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1}else if(i.packetNumber<=this.lastOrderedPacketNumber){const o={ackSendTs:i.sendTs,maxAckPacketNumber:i.packetNumber,shift:0,type:YS.Ack,version:this.version};this.sendPacket(o)}else if(i.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[i.packetNumber-this.lastOrderedPacketNumber-2]=i;const o={ackSendTs:i.sendTs,maxAckPacketNumber:i.packetNumber,shift:0,type:YS.Ack,version:this.version};this.sendPacket(o)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const i={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:YS.Ack,version:this.version};this.sendPacket(i),this.batchAckPacketQueue=[]}sendPacket(i){i.type===YS.Default&&(i.sendTs=Math.round(performance.now()));const o=this.serialize(i);this.sendImpl(o)}clearRTO(i){for(let o=i.maxAckPacketNumber-i.shift;o<=i.maxAckPacketNumber;o++){const p=this.timeoutMap.get(o);p!==void 0&&window.clearTimeout(p),this.timeoutMap.delete(o),this.rtoRatioMap.delete(o)}}}class a5 extends Eet{constructor(i,o){super(i,o,arguments.length>2&&arguments[2]!==void 0&&arguments[2],arguments.length>3?arguments[3]:void 0),_e(this,"_initMutex",void 0),_e(this,"_reconnectInterrupter",void 0),_e(this,"_url",void 0),_e(this,"_transmitter",void 0),_e(this,"_addresses",void 0),_e(this,"_reliableTransmission",void 0),this._initMutex=new E0("datachannel");const{timeout:p,timeoutFactor:g}=o,b=Math.max(300,Math.floor(3*p/5)),A=Math.max(1.2,Math.floor(8*g)/10);K0.ONLINE&&(this._retryConfig.timeout=b,this._retryConfig.timeoutFactor=A),X_.on(YT.NETWORK_STATE_CHANGE,(j,H)=>{j!==H&&(this.resetReconnectCount("network state change: ".concat(H," -> ").concat(j)),j===K0.ONLINE?(this._retryConfig.timeout=b,this._retryConfig.timeoutFactor=A):(this._retryConfig.timeout=p,this._retryConfig.timeoutFactor=g))})}getConnection(){if(this._reliableTransmission)return this._reliableTransmission}async init(i){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;this._forceCloseTimeout=o;const p=(g,b)=>{this._addresses=i,this.currentURLIndex=this._addresses.findIndex(j=>j.fingerprint||nE("FINGERPRINT"));const A=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(A).then(g).catch(b),this.once(W_.CLOSED,()=>b(new hE(_p.WS_DISCONNECT))),this.once(W_.CONNECTED,()=>g())};return this._initMutex.lock().then(g=>new pE((b,A)=>{p(b,A)}).then(()=>{g()}).catch(()=>{g()}))}sendMessage(i){let o=arguments.length>2&&arguments[2]!==void 0&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new hE(_p.WS_ABORT,"datachannel is not ready");try{o||(i=JSON.stringify(i)),this._reliableTransmission.sendMessage(i)}catch(p){throw new hE(_p.WS_ERR,"send datachannel signal message error"+p.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(i){const o=JSON.stringify(i);return{compressed:o,compressedLength:o.length,origin:i}}sendMessageWithUint8Array(i){return{compressed:i,compressedLength:i.byteLength,origin:i}}createTransmitterConnection(i){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(i.ip,":").concat(i.port),new pE((o,p)=>{var g;const b=()=>{Gi.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),o()},A=async $=>{var Vt;if((Vt=this._closeEstablishingTransmitter)===null||Vt===void 0||Vt.call(this),Gi.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat($.code,", reason: ").concat($.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount{var Vt;(Vt=this._reliableTransmission)===null||Vt===void 0||Vt.onData($.data)};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),Gi.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(i)));const H=(g=this._store)===null||g===void 0?void 0:g.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),z=Date.now();U_(this,W_.TO_CONNECT_DATACHANNEL,i).then($=>{var Vt,_r;if(!$)throw new Error("transmissonInfo not exist yet");const{transmitter:Fi,close:_l}=$;this._transmitter=Fi,(Vt=this._store)===null||Vt===void 0||Vt.signalChannelOpen();const _u=Date.now()-z;Gi.debug("[choose dc] dc open cost ".concat(_u,"ms")),this._reliableTransmission=new vet(_h=>{var _g;this._transmitter&&this._transmitter.readyState==="open"&&((_g=this._transmitter)===null||_g===void 0||_g.send(_h))},_h=>{typeof _h=="string"&&this.emit(W_.ON_MESSAGE,_h)}),this._closeEstablishingTransmitter=()=>{var _h;(_h=this._reliableTransmission)===null||_h===void 0||_h.close(),this._reliableTransmission=void 0,_l()},b&&b(),Fi.onclose=A,Fi.onmessage=j,(_r=this._store)===null||_r===void 0||_r.recordJoinChannelService({endTs:Date.now(),status:"success"},H),this._joinChannelServiceRecordIndex=H}).catch($=>{var Vt;if((Vt=this._store)===null||Vt===void 0||Vt.recordJoinChannelService({endTs:Date.now(),status:$ instanceof hE&&$.code===_p.WS_ABORT?"aborted":"error",errors:[$]},H),this.state!=="closed"){if($ instanceof hE&&$.code===_p.WS_ERR){const _r=new hE(_p.WS_ERR,"init datachannel failed! Error: ".concat($.toString()));return Gi.error("[".concat(this._name,"]").concat(_r)),void p(_r)}A&&A($)}else p(new hE(_p.WS_DISCONNECT,"datachannel is closed: ".concat($.toString())))})})}async reconnectWithAction(i){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount||!this._addresses||this.state==="closed")return!1;this._onlineReconnectListener||X_.networkState!==K0.OFFLINE||(this._onlineReconnectListener=X_.onlineWaiter&&X_.onlineWaiter.then(()=>{this._onlineReconnectListener=void 0}));let p=!0;if(this._reconnectInterrupter=()=>{p=!1},o){const j=mN(this._reconnectCount,this._retryConfig);Gi.debug("[".concat(this._name,"] wait ").concat(j,"ms to reconnect datachannel, mode: ").concat(i)),await pE.race([w0(j),this._onlineReconnectListener||new pE(()=>{})])}if(this.state==="closed"||!p)return!1;this._reconnectCount+=1;const g=async(j,H)=>{this.emit(W_.RECONNECT_CREATE_CONNECTION,H),await this.createTransmitterConnection(j)};try{if(i==="retry"){const j=this._addresses[this.currentURLIndex];this.emit(W_.RECONNECT_WAITTING_FINISH,i),await g(j,i)}else if(i==="tryNext"){this.currentURLIndex+=1;for(let H=this.currentURLIndex;H=this._addresses.length)return Gi.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);Gi.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const j=this._addresses[this.currentURLIndex];this.emit(W_.RECONNECT_WAITTING_FINISH,i),await g(j,i)}else i==="recover"&&(Gi.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(W_.RECONNECT_WAITTING_FINISH,i),this.emit(W_.FAILBACK));return!0}catch(j){var b,A;return Gi.error("[".concat(this._name,"] reconnect failed"),j.toString()),j!=null&&(b=j.data)!==null&&b!==void 0&&b.desc&&Array.isArray(j.data.desc)&&j.data.desc.length&&VE(A=j.data.desc).call(A,"dynamic key expired")?(this.emit(W_.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(i,o)}}}class eR extends D_{get connectionState(){return this._connectionState}set connectionState(i){i!==this._connectionState&&(this._connectionState=i,i===t_.CONNECTED?this.emit(kE.WS_CONNECTED):i===t_.RECONNECTING?this.emit(kE.WS_RECONNECTING,this._websocketReconnectReason):i===t_.CLOSED&&this.emit(kE.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(i,o){super(),_e(this,"_disconnectedReason",void 0),_e(this,"_websocketReconnectReason",void 0),_e(this,"_connectionState",t_.CLOSED),_e(this,"reconnectToken",void 0),_e(this,"websocket",void 0),_e(this,"openConnectionTime",void 0),_e(this,"clientId",void 0),_e(this,"lastMsgTime",Date.now()),_e(this,"uploadCache",[]),_e(this,"uploadCacheInterval",void 0),_e(this,"rttRolling",new WL(5)),_e(this,"pingpongTimer",void 0),_e(this,"inflateDataTimer",void 0),_e(this,"pingpongTimeoutCount",0),_e(this,"joinResponse",void 0),_e(this,"multiIpOption",void 0),_e(this,"initError",void 0),_e(this,"spec",void 0),_e(this,"store",void 0),_e(this,"onWebsocketMessage",p=>{if(p instanceof ArrayBuffer)return void this.emit(kE.ON_BINARY_DATA,p);const g=JSON.parse(p);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(g,"_id")){const b="res-@".concat(g._id);this.emit(b,g._result,g._message)}else if(Object.prototype.hasOwnProperty.call(g,"_type")&&(this.emit(g._type,g._message),g._type===JE.ON_NOTIFICATION&&this.handleNotification(g._message),g._type===JE.ON_USER_BANNED))switch(g._message.error_code){case 14:this.close(e_.UID_BANNED);break;case 15:this.close(e_.IP_BANNED);break;case 16:this.close(e_.CHANNEL_BANNED)}}),this.clientId=i.clientId,this.spec=i,this.store=o,this.websocket=new a5("gateway-".concat(this.clientId),this.spec.retryConfig,!0,o),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===t_.CONNECTED&&this.reconnect("retry",NT.OFFLINE)})}async request(i,o,p,g){const b=T_(6,""),A={_id:b,_type:i,_message:o},j=this.websocket.connectionID,H=()=>new pE((_l,_u)=>{if(this.connectionState===t_.CONNECTED)return _l();const _h=()=>{this.off(kE.WS_CLOSED,_g),_l()},_g=()=>{this.off(kE.WS_CONNECTED,_h),_u(new hE(_p.WS_ABORT))};this.once(kE.WS_CONNECTED,_h),this.once(kE.WS_CLOSED,_g),i!==FE.PUBLISH&&i!==FE.SUBSCRIBE&&i!==FE.UNSUBSCRIBE&&i!==FE.UNPUBLISH&&i!==FE.CONTROL&&i!==FE.RESTART_ICE||this.once(kE.DISCONNECT_P2P,()=>{_u(new hE(_p.DISCONNECT_P2P))}),i!==FE.PUBLISH&&i!==FE.RESTART_ICE||this.once(kE.ABORT_P2P_EXECUTION,()=>{_u(new hE(_p.DISCONNECT_P2P))})});if(this.connectionState!==t_.CONNECTING&&this.connectionState!==t_.RECONNECTING||i===FE.JOIN||i===FE.REJOIN||await H(),i===FE.LEAVE&&(this.websocket.unbindDcCloseEventListener(),g=!0),this.websocket.sendMessage(A,!0,!1),g)return;const z=new pE((_l,_u)=>{let _h=!1;const _g=(oE,SE)=>{_h=!0,_l({isSuccess:oE==="success",message:SE||{}}),this.off(kE.WS_CLOSED,eE),this.off(kE.WS_RECONNECTING,eE),this.emit(kE.REQUEST_SUCCESS,i,o)};this.once("res-@".concat(b),_g);const eE=()=>{_u(new hE(_p.WS_ABORT,"type: ".concat(i))),this.off(kE.WS_CLOSED,eE),this.off(kE.WS_RECONNECTING,eE),this.off("res-@".concat(b),_g)};this.once(kE.WS_CLOSED,eE),this.once(kE.WS_RECONNECTING,eE),w0(nE("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==j||_h||(Gi.warning("dc request timeout, type: ".concat(i)),this.emit(kE.REQUEST_TIMEOUT,i,o))})});let $=null;try{$=await z}catch(_l){if(this.connectionState===t_.CLOSED||i===FE.LEAVE)throw new hE(_p.WS_ABORT);return!this.spec.forceWaitGatewayResponse||p?_l.throw():i===FE.JOIN||i===FE.REJOIN?null:(await H(),await this.request(i,o))}if($.isSuccess)return $.message;const Vt=Number($.message.error_code||$.message.code),_r=iI(Vt),Fi=new hE(_p.UNEXPECTED_RESPONSE,"".concat(_r.desc,": ").concat($.message.error_str),{code:Vt,data:$.message});return _r.action==="success"?$.message:(Gi.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(i,", error_code: ").concat(Vt,", message: ").concat(_r.desc,", action: ").concat(_r.action)),Vt===qE.ERR_TOO_MANY_BROADCASTERS?((i===FE.JOIN||i===FE.REJOIN)&&(this.initError=Fi,this.close()),Fi.throw()):_r.action==="failed"?Fi.throw():_r.action==="quit"?(this.initError=Fi,this.close(),Fi.throw()):(Vt===qE.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=$.message.option,Gi.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",NT.MULTI_IP)):this.reconnect(_r.action,NT.SERVER_ERROR),i===FE.JOIN||i===FE.REJOIN?null:await this.request(i,o)))}waitMessage(i,o){return new pE(p=>{const g=b=>{(!o||o(b))&&(this.off(i,g),p(b))};this.on(i,g)})}upload(i,o){const p={_type:i,_message:o};try{this.websocket.sendMessage(p)}catch{const b=nE("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(p),this.uploadCache.length>b&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==t_.CONNECTED)return;const A=this.uploadCache.splice(0,1)[0];this.uploadCache.length===0&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(A._type,A._message)},nE("UPLOAD_CACHE_INTERVAL")||2e3))}}send(i,o){const p={_type:i,_message:o};this.websocket.sendMessage(p)}init(i,o){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new pE((p,g)=>{this.once(kE.WS_CONNECTED,()=>p(this.joinResponse)),this.once(kE.WS_CLOSED,()=>g(this.initError||new hE(_p.WS_ABORT))),this.connectionState=t_.CONNECTING,this.websocket.init(i).catch(g),this.websocket.once(W_.FAILBACK,()=>{this.openConnectionTime===void 0&&g(new hE(_p.INIT_DATACHANNEL_TIMEOUT))}),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval(()=>{this.handleInflateData()},2e4),setTimeout(()=>{o&&this.openConnectionTime===void 0&&(Gi.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),g(new hE(_p.INIT_DATACHANNEL_TIMEOUT)))},nE("DC_JOIN_WITH_FAILBACK"))})}close(i){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._disconnectedReason=i||e_.LEAVE,this.connectionState=t_.CLOSED,Gi.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),i===e_.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new a5("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(kE.ABORT_P2P_EXECUTION);const i=await U_(this,kE.DATACHANNEL_CONNECTING),o=await this.request(FE.JOIN,i);if(!o)return this.emit(kE.REPORT_JOIN_GATEWAY,_p.TIMEOUT,this.url||""),!1;this.joinResponse=o,this.emit(kE.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=t_.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new hE(_p.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const i=JT(this,kE.REQUEST_REJOIN_INFO);i.token=this.reconnectToken;const o=await this.request(FE.REJOIN,i);return!!o&&(this.connectionState=t_.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),o.peers&&o.peers.forEach(p=>{this.emit(JE.ON_USER_ONLINE,{uid:p.uid}),p.audio&&this.emit(JE.ON_ADD_AUDIO_STREAM,{uid:p.uid,uint_id:p.uint_id,audio:!0,ssrcId:p.audio_ssrc}),p.video&&this.emit(JE.ON_ADD_VIDEO_STREAM,{uid:p.uid,uint_id:p.uint_id,video:!0,ssrcId:p.video_ssrc}),p.audio_mute?this.emit(JE.MUTE_AUDIO,{uid:p.uid}):this.emit(JE.UNMUTE_AUDIO,{uid:p.uid}),p.video_mute?this.emit(JE.MUTE_VIDEO,{uid:p.uid}):this.emit(JE.UNMUTE_VIDEO,{uid:p.uid}),p.audio_enable_local?this.emit(JE.ENABLE_LOCAL_AUDIO,{uid:p.uid}):this.emit(JE.DISABLE_LOCAL_AUDIO,{uid:p.uid}),p.video_enable_local?this.emit(JE.ENABLE_LOCAL_VIDEO,{uid:p.uid}):this.emit(JE.DISABLE_LOCAL_VIDEO,{uid:p.uid}),p.audio||p.video||this.emit(JE.ON_REMOVE_STREAM,{uid:p.uid,uint_id:p.uint_id})}),!0)}reconnect(i,o){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(i,o)}handleNotification(i){Gi.debug("[".concat(this.clientId,"] receive notification: "),i);const o=iI(i.code);if(o.action!=="success"){if(o.action!=="failed")return o.action==="quit"?(o.desc==="ERR_REPEAT_JOIN_CHANNEL"&&this.close(e_.UID_BANNED),void this.close()):void this.reconnect(o.action,NT.SERVER_ERROR);Gi.error("[".concat(this.clientId,"] ignore error: "),o.desc)}}handlePingPong(){if(!this.websocket||this.websocket.state!=="connected")return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const i=nE("PING_PONG_TIME_OUT"),o=Date.now();this.pingpongTimeoutCount>=i&&(Gi.warning("PINGPONG Timeout. Last Socket Message: ".concat(o-this.lastMsgTime,"ms")),o-this.lastMsgTime>nE("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",NT.TIMEOUT):this.request(FE.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const p=Date.now()-o;this.rttRolling.add(p),nE("REPORT_STATS")&&this.send(FE.PING_BACK,{pingpongElapse:p})}).catch(p=>{})}handleInflateData(){const{inflateLength:i,deflateLength:o}=this.websocket.getInflateData();i!==0&&o!==0&&this.upload(uS.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:o,ws_inflate_length:i})}handleWebsocketEvents(){this.websocket.on(W_.RECONNECT_WAITTING_FINISH,i=>{this.emit(kE.WS_RECONNECT_WAITTING_FINISH,i)}),this.websocket.on(W_.RECONNECT_CREATE_CONNECTION,i=>{this.emit(kE.WS_RECONNECT_CREATE_CONNECTION,i)}),this.websocket.on(W_.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(W_.CLOSED,()=>{this.connectionState=t_.CLOSED}),this.websocket.on(W_.FAILED,()=>{this._disconnectedReason=e_.NETWORK_ERROR,this.connectionState=t_.CLOSED}),this.websocket.on(W_.RECONNECTING,i=>{this._websocketReconnectReason=i,this.joinResponse=void 0,this.connectionState===t_.CONNECTED?this.connectionState=t_.RECONNECTING:this.connectionState=t_.CONNECTING}),this.websocket.on(W_.WILL_RECONNECT,(i,o)=>{if(JT(this,kE.IS_P2P_DISCONNECTED)&&i==="retry")return Gi.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(kE.NEED_RENEW_SESSION),this.emit(kE.DISCONNECT_P2P),o("tryNext");i!=="retry"&&(Gi.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(i)),this.reconnectToken=void 0,this.emit(kE.NEED_RENEW_SESSION),this.emit(kE.DISCONNECT_P2P)),o(i)}),this.websocket.on(W_.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(i=>{Gi.warning("[".concat(this.clientId,"] rejoin failed ").concat(i)),this.reconnect("tryNext",NT.SERVER_ERROR)}):this.join().catch(i=>{if(this.emit(kE.REPORT_JOIN_GATEWAY,i.message||i.code,this.url||""),i instanceof hE&&i.code===_p.UNEXPECTED_RESPONSE&&i.data.code===qE.ERR_NO_AUTHORIZED)return Gi.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",NT.SERVER_ERROR);Gi.error("[".concat(this.clientId,"] join gateway request failed"),i.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",NT.SERVER_ERROR):(this.initError=i,this.close())})}),this.websocket.on(W_.REQUEST_NEW_URLS,(i,o)=>{U_(this,kE.REQUEST_RECOVER,this.multiIpOption).then(i).catch(o)}),this.websocket.on(W_.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(JE.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}),this.websocket.on(W_.TO_CONNECT_DATACHANNEL,async(i,o,p)=>U_(this,kE.DATACHANNEL_PRECONNECT,i).then(o).catch(p)),this.websocket.on(W_.FAILBACK,()=>{this.openConnectionTime!==void 0&&this.emit(kE.DATACHANNEL_FAILBACK)})}}class iP extends D_{constructor(i){super(),_e(this,"_signal",void 0),_e(this,"_sequence",0),_e(this,"_userMap",new Map),_e(this,"_encoder",new TextEncoder),this._signal=i}async send(i,o,p,g,b){var A,j,H;typeof o!="string"&&(o=JSON.stringify(o)),g=(A=g)!==null&&A!==void 0?A:T_(6,""),b=(j=b)!==null&&j!==void 0?j:this._sequence++;const z={_id:g,_type:i,_seq:(H=b)!==null&&H!==void 0?H:this._sequence++,_message:o};if(nE("SHOW_P2P_LOG")&&Gi.debug("send message",z),this.sendStreamMessage(JSON.stringify(z)),p)return;const $=new pE((_r,Fi)=>{const _l=window.setTimeout(()=>{this.off("res-@".concat(g),_u),Gi.warning("[external-signal] request timeout, type: ".concat(i)),this._userMap.size===0?Fi(new yE(_p.INVALID_REMOTE_USER)):Fi(new yE(_p.TIMEOUT))},nE("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),_u=(_h,_g)=>{_l&&window.clearTimeout(_l),_h==="success"?_r({isSuccess:!0,message:_g}):Fi(new yE(_p.UNEXPECTED_ERROR,_g))};this.once("res-@".concat(g),_u)});let Vt;try{Vt=await $}catch(_r){if(_r.code===_p.TIMEOUT)return await this.send(i,o,!1,g,b);throw _r}return Vt.isSuccess?Vt.message:void 0}sendStreamMessage(i){this._splitMessage(i).forEach(o=>{this._signal.request(FE.DATA_STREAM,{payload:hN(this._encoder.encode(o))})})}onMessage(i){const{_uid:o}=i;let p;const g=this._userMap.get(o);if(g?p=g.splitMessageMap:(p=new Map,this._userMap.set(o,{isStart:!1,splitMessageMap:p,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map})),"id"in i&&"total"in i){var b;const{id:A,total:j}=i,H=(b=p.get(A))!==null&&b!==void 0?b:[];if(H.push(i),p.has(A)||p.set(A,H),H.length!==j)return;{const z=AO(H).call(H,($,Vt)=>$.index-Vt.index).map($=>$.payload).join("");p.delete(A),(i=JSON.parse(z))._uid=o}}this.handleReceivedMessage(i)}setStart(i){this._userMap.has(i)?this._userMap.get(i).isStart=!0:this._userMap.set(i,{isStart:!0,splitMessageMap:new Map,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map}),this.handleReceivedMessage()}setEnd(i){return this._userMap.delete(i),this._userMap.size===0}ack(i,o,p){this.send(w_.ACK,JSON.stringify({success:!p,message:o}),!0,i)}handleReceivedMessage(i){const o=()=>{this._userMap.forEach(z=>{const{receivedMessagesMap:$,nextExpectedSequenceNumber:Vt}=z;for(;$.has(Vt);){const _r=$.get(Vt);$.delete(Vt),this.receiveMessage(_r),z.nextExpectedSequenceNumber++}})};if(!i)return void o();const{_uid:p,_seq:g}=i,b=this._userMap.get(p),{receivedMessagesMap:A,isStart:j,nextExpectedSequenceNumber:H}=b;g{this.ack(i._id,H)}).catch(H=>{this.ack(i._id,void 0,!0)});break}case w_.ACK:{const{success:j,message:H}=JSON.parse(g);this.emit("res-@".concat(o),j?"success":"failed",H);break}case w_.CALL:U_(this,p,g).then(j=>{this.ack(o,j)});break;case w_.RESTART_ICE:case w_.EXCHANGE_SDP:case w_.SUBSCRIBE:case w_.UNSUBSCRIBE:U_(this._signal,p,g).then(j=>{this.ack(o,j)}).catch(j=>{this.ack(i._id,void 0,!0)});break;case w_.CANDIDATE:this._signal.emit(p,g),this.ack(o);break;case w_.JOIN:this.emit(p,JSON.parse(g));break;default:this.emit(p,g),this.ack(o)}}_splitMessage(i){if(i.length0;){g++;const A=i.slice(0,800);o.push({id:p,index:g,total:b,payload:A}),i=i.slice(800)}return o.map(A=>JSON.stringify(A))}clear(){this._sequence=0,this._userMap.clear()}}_e(iP,"MAX_MESSAGE_SIZE",1024);class c5 extends D_{get connectionState(){return this._connectionState}set connectionState(i){i!==this._connectionState&&(this._connectionState=i,i===t_.CONNECTED?this.emit(kE.WS_CONNECTED):i===t_.RECONNECTING?this.emit(kE.WS_RECONNECTING,this._websocketReconnectReason):i===t_.CLOSED&&this.emit(kE.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(i,o){super(),_e(this,"_disconnectedReason",void 0),_e(this,"_websocketReconnectReason",void 0),_e(this,"_connectionState",t_.CLOSED),_e(this,"reconnectToken",void 0),_e(this,"_userInRoom",!1),_e(this,"_userOnlineTime",void 0),_e(this,"websocket",void 0),_e(this,"openConnectionTime",void 0),_e(this,"clientId",void 0),_e(this,"lastMsgTime",Date.now()),_e(this,"uploadCache",[]),_e(this,"uploadCacheInterval",void 0),_e(this,"rttRolling",new WL(5)),_e(this,"pingpongTimer",void 0),_e(this,"wsInflateDataTimer",void 0),_e(this,"pingpongTimeoutCount",0),_e(this,"joinResponse",void 0),_e(this,"multiIpOption",void 0),_e(this,"initError",void 0),_e(this,"spec",void 0),_e(this,"store",void 0),_e(this,"_external_signal",void 0),_e(this,"onWebsocketMessage",p=>{if(p.data instanceof ArrayBuffer)return void this.emit(kE.ON_BINARY_DATA,p.data);const g=JSON.parse(p.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(g,"_id")){const b="res-@".concat(g._id);this.emit(b,g._result,g._message)}else if(Object.prototype.hasOwnProperty.call(g,"_type")){switch(g._type){case JE.ON_DATA_STREAM:return void this.handleDataStream(g._message);case JE.MUTE_AUDIO:case JE.MUTE_VIDEO:case JE.ON_P2P_LOST:return;case JE.ON_USER_ONLINE:this.emit(g._type,g._message);const{uid:b}=g._message;return this._external_signal.setStart(b),void this._external_signal.send(w_.JOIN,{onlineTime:this._userOnlineTime},!0)}if(this.emit(g._type,g._message),g._type===JE.ON_NOTIFICATION&&this.handleNotification(g._message),g._type===JE.ON_USER_BANNED)switch(g._message.error_code){case 14:this.close(e_.UID_BANNED);break;case 15:this.close(e_.IP_BANNED);break;case 16:this.close(e_.CHANNEL_BANNED)}if(g._type===JE.ON_USER_LICENSE_BANNED)switch(g._message.error_code){case qE.ERR_LICENSE_MISSING:this.close(e_.LICENSE_MISSING);break;case qE.ERR_LICENSE_EXPIRED:this.close(e_.LICENSE_EXPIRED);break;case qE.ERR_LICENSE_MINUTES_EXCEEDED:this.close(e_.LICENSE_MINUTES_EXCEEDED);break;case qE.ERR_LICENSE_PERIOD_INVALID:this.close(e_.LICENSE_PERIOD_INVALID);break;case qE.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(e_.LICENSE_MULTIPLE_SDK_SERVICE);break;case qE.ERR_LICENSE_ILLEGAL:this.close(e_.LICENSE_ILLEGAL);break;default:this.close()}}}),this.clientId=i.clientId,this.spec=i,this.store=o,this.websocket=new HO("gateway-".concat(this.clientId),this.spec.retryConfig,!0,nE("JOIN_GATEWAY_USE_DUAL_DOMAIN"),nE("JOIN_GATEWAY_USE_443PORT_ONLY"),o),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===t_.CONNECTED&&this.reconnect("retry",h0.OFFLINE)}),this._external_signal=new iP(this),this._handleSignalP2PEvents()}async request(i,o,p,g){const b=T_(6,""),A={_id:b,_type:i,_message:o},j=this.websocket.connectionID,H=()=>new pE((_l,_u)=>{if(this.connectionState===t_.CONNECTED)return _l();const _h=()=>{this.off(kE.WS_CLOSED,_g),_l()},_g=()=>{this.off(kE.WS_CONNECTED,_h),_u(new yE(_p.WS_ABORT))};this.once(kE.WS_CONNECTED,_h),this.once(kE.WS_CLOSED,_g),i!==FE.PUBLISH&&i!==FE.SUBSCRIBE&&i!==FE.UNSUBSCRIBE&&i!==FE.UNPUBLISH&&i!==FE.CONTROL&&i!==FE.RESTART_ICE||this.once(kE.DISCONNECT_P2P,()=>{_u(new yE(_p.DISCONNECT_P2P))}),i!==FE.PUBLISH&&i!==FE.RESTART_ICE||this.once(kE.ABORT_P2P_EXECUTION,()=>{_u(new yE(_p.DISCONNECT_P2P))})});if(this.connectionState!==t_.CONNECTING&&this.connectionState!==t_.RECONNECTING||i===FE.JOIN||i===FE.REJOIN||await H(),this.websocket.sendMessage(A,!0),g)return;const z=new pE((_l,_u)=>{let _h=!1;const _g=(oE,SE)=>{_h=!0,_l({isSuccess:oE==="success",message:SE||{}}),this.off(kE.WS_CLOSED,eE),this.off(kE.WS_RECONNECTING,eE),this.emit(kE.REQUEST_SUCCESS,i,o)};this.once("res-@".concat(b),_g);const eE=()=>{_u(new yE(_p.WS_ABORT,"type: ".concat(i))),this.off(kE.WS_CLOSED,eE),this.off(kE.WS_RECONNECTING,eE),this.off("res-@".concat(b),_g)};this.once(kE.WS_CLOSED,eE),this.once(kE.WS_RECONNECTING,eE),w0(nE("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==j||_h||(Gi.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(i)),this.emit(kE.REQUEST_TIMEOUT,i,o))})});let $=null;try{$=await z}catch(_l){if(this.connectionState===t_.CLOSED||i===FE.LEAVE)throw new yE(_p.WS_ABORT);return!this.spec.forceWaitGatewayResponse||p?_l.throw():i===FE.JOIN||i===FE.REJOIN?null:(await H(),await this.request(i,o))}if($.isSuccess)return $.message;const Vt=Number($.message.error_code||$.message.code),_r=iI(Vt),Fi=new yE(_p.UNEXPECTED_RESPONSE,"".concat(_r.desc,": ").concat($.message.error_str),{code:Vt,data:$.message});return _r.action==="success"?$.message:(Gi.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(i,", error_code: ").concat(Vt,", message: ").concat(_r.desc,", action: ").concat(_r.action)),Vt===qE.ERR_TOO_MANY_BROADCASTERS?((i===FE.JOIN||i===FE.REJOIN)&&(this.initError=Fi,this.close()),Fi.throw()):_r.action==="failed"?Fi.throw():_r.action==="quit"?(this.initError=Fi,this.close(),Fi.throw()):(Vt===qE.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=$.message.option,Gi.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",h0.MULTI_IP)):this.reconnect(_r.action,h0.SERVER_ERROR),i===FE.JOIN||i===FE.REJOIN?null:await this.request(i,o)))}waitMessage(i,o){return new pE(p=>{const g=b=>{(!o||o(b))&&(this.off(i,g),p(b))};this.on(i,g)})}upload(i,o){const p={_type:i,_message:o};try{this.websocket.sendMessage(p)}catch{const b=nE("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(p),this.uploadCache.length>b&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==t_.CONNECTED)return;const A=this.uploadCache.splice(0,1)[0];this.uploadCache.length===0&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(A._type,A._message)},nE("UPLOAD_CACHE_INTERVAL")||2e3))}}send(i,o){const p={_type:i,_message:o};this.websocket.sendMessage(p)}async sendExtensionMessage(i,o,p){return await this.waitTillUserOnline(),await this._external_signal.send(i,o,p)}init(i,o){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new pE((p,g)=>{this.once(kE.WS_CONNECTED,()=>p(this.joinResponse)),this.once(kE.WS_CLOSED,()=>g(this.initError||new yE(_p.WS_ABORT))),this.connectionState=t_.CONNECTING,this.websocket.init(i).catch(g),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval(()=>{this.handleWsInflateData()},2e4)})}close(i){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=i||e_.LEAVE,this.connectionState=t_.CLOSED,Gi.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),i===e_.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new HO("gateway-".concat(this.clientId),this.spec.retryConfig,!0,nE("JOIN_GATEWAY_USE_DUAL_DOMAIN"),nE("JOIN_GATEWAY_USE_443PORT_ONLY"),this.store),this.handleWebsocketEvents())}async join(){if(!this.joinResponse){this.emit(kE.ABORT_P2P_EXECUTION);const i=await U_(this,kE.REQUEST_JOIN_INFO),o=await this.request(FE.JOIN,i);if(!o)return this.emit(kE.REPORT_JOIN_GATEWAY,_p.TIMEOUT,this.url||""),!1;this.joinResponse=o,this.emit(kE.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=t_.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),this._userOnlineTime=new Date().getTime(),this._external_signal.clear(),!0}async rejoin(){if(!this.reconnectToken)throw new yE(_p.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const i=JT(this,kE.REQUEST_REJOIN_INFO);return i.token=this.reconnectToken,!!await this.request(FE.REJOIN,i)&&(this.connectionState=t_.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0)}reconnect(i,o){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(i,o)}handleDataStream(i){try{var o;const p=dN(i.payload),g=new TextDecoder().decode(p),b=JSON.parse(g);"total"in b&&"id"in b||VE(o=Object.values(w_)).call(o,b._type)?(i.seq&&delete i.seq,b._uid=i.uid,this._external_signal.onMessage(b)):this.emit(JE.ON_DATA_STREAM,i)}catch{}}handleNotification(i){Gi.debug("[".concat(this.clientId,"] receive notification: "),i);const o=iI(i.code);if(o.action!=="success"){if(o.action!=="failed")return o.action==="quit"?(o.desc==="ERR_REPEAT_JOIN_CHANNEL"&&this.close(e_.UID_BANNED),void this.close()):void this.reconnect(o.action,h0.SERVER_ERROR);Gi.error("[".concat(this.clientId,"] ignore error: "),o.desc)}}handlePingPong(){if(!this.websocket||this.websocket.state!=="connected")return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const i=nE("PING_PONG_TIME_OUT"),o=Date.now();this.pingpongTimeoutCount>=i&&(Gi.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(o-this.lastMsgTime,"ms")),o-this.lastMsgTime>nE("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",h0.TIMEOUT):this.request(FE.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const p=Date.now()-o;this.rttRolling.add(p),nE("REPORT_STATS")&&this.send(FE.PING_BACK,{pingpongElapse:p})}).catch(p=>{})}handleWsInflateData(){const{wsInflateLength:i,wsDeflateLength:o}=this.websocket.getWsInflateData();i!==0&&o!==0&&this.upload(uS.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:o,ws_inflate_length:i})}handleWebsocketEvents(){this.websocket.on(zE.RECONNECT_WAITTING_FINISH,i=>{this.emit(kE.WS_RECONNECT_WAITTING_FINISH,i)}),this.websocket.on(zE.RECONNECT_CREATE_CONNECTION,i=>{this.emit(kE.WS_RECONNECT_CREATE_CONNECTION,i)}),this.websocket.on(zE.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(zE.CLOSED,()=>{this.connectionState=t_.CLOSED}),this.websocket.on(zE.FAILED,()=>{this._disconnectedReason=e_.NETWORK_ERROR,this.connectionState=t_.CLOSED}),this.websocket.on(zE.RECONNECTING,i=>{this._websocketReconnectReason=i,this.joinResponse=void 0,this.connectionState===t_.CONNECTED?this.connectionState=t_.RECONNECTING:this.connectionState=t_.CONNECTING}),this.websocket.on(zE.WILL_RECONNECT,(i,o,p)=>{if(JT(this,kE.IS_P2P_DISCONNECTED)&&i==="retry")return Gi.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(kE.NEED_RENEW_SESSION),this.emit(kE.DISCONNECT_P2P),p("tryNext");i!=="retry"&&(Gi.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(i)),this.reconnectToken=void 0,this.emit(kE.NEED_RENEW_SESSION),this.emit(kE.DISCONNECT_P2P)),p(i)}),this.websocket.on(zE.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(i=>{Gi.warning("[".concat(this.clientId,"] rejoin failed ").concat(i)),this.reconnect("tryNext",h0.SERVER_ERROR)}):this.join().catch(i=>{if(this.emit(kE.REPORT_JOIN_GATEWAY,i.message||i.code,this.url||""),i instanceof yE&&i.code===_p.UNEXPECTED_RESPONSE&&i.data.code===qE.ERR_NO_AUTHORIZED)return Gi.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",h0.SERVER_ERROR);Gi.error("[".concat(this.clientId,"] join gateway request failed"),i.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",h0.SERVER_ERROR):(this.initError=i,this.close())})}),this.websocket.on(zE.REQUEST_NEW_URLS,(i,o)=>{U_(this,kE.REQUEST_RECOVER,this.multiIpOption).then(i).catch(o)}),this.websocket.on(zE.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(JE.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})}_handleSignalP2PEvents(){this._external_signal.on(w_.JOIN,async i=>{if(this._userOnlineTime&&this._userOnlineTime{this._external_signal.clear(),this._userInRoom=!1}),this._external_signal.on(w_.CALL,async(i,o,p)=>{this._userInRoom=!0,this.emit("user-online");try{o(await U_(this,kE.P2P_START,i))}catch(g){p(g)}})}async waitTillUserOnline(){return new pE(i=>{if(this._userInRoom)i();else{const o=()=>{this.off("user-online",o),i()};this.on("user-online",o)}})}}function u5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function dT(l){for(var i=1;i255||"".concat(i.apResponse.cid,"_").concat(i.apResponse.cert).length<22?(Gi.debug("[".concat(this.store.clientId,"] Dc is not supported, because ticket length is incorrect, it has to be between 22 and 255")),H=!0):i.apResponse.addresses.some(z=>z.fingerprint)||nE("FINGERPRINT")||(Gi.debug("[".concat(this.store.clientId,"] Dc is not supported, because fingerprint does not exist")),H=!0),H&&this.resetSignal()}this.store.joinGatewayStart(),i.cloudProxyServer!=="disabled"&&(this.hasChangeBGPAddress=!0);const g=Date.now();let b=u2.get(i.cname);if(b||(b=new Map,u2.set(i.cname,b)),this._isProactiveJoin=!0,b.has(i.uid)){const H=new hE(_p.UID_CONFLICT);throw jE.joinGateway(i.sid,{lts:g,succ:!1,ec:H.message,addr:null,uid:i.uid,cid:i.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!i.proxyServer,signalChannel:this.signal instanceof eR?"1":"0"}),this._isProactiveJoin=!1,H}b.set(i.uid,!0),this.joinInfo=i,this.key=o;let A=0;this.joinGatewayStartTime=g;const j=i.proxyServer;try{let H;if(Gi.debug("[".concat(this.store.clientId,"] use ").concat(this.signal instanceof eR?"datachannel":"websocket"," join uid ").concat(A)),this.signal instanceof eR)H=await this.signal.init(i.apResponse.addresses,p);else{const z=i.gatewayAddrs.map($=>{let{address:Vt}=$;const[_r,Fi]=Vt.split(":"),_l={host:_r,port:Fi};return i.proxyServer&&(_l.proxy=i.proxyServer),_l});H=await this.signal.init(z,p)}A=H.uid,Gi.debug("[".concat(this.store.clientId,"] ").concat(this.signal instanceof eR?"datachannel":"websocket"," join uid ").concat(A," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(H){throw H&&H.code===_p.INIT_WEBSOCKET_TIMEOUT?(Gi.warning("[".concat(this.store.clientId,"] User join failed"),H.toString()),H):H&&H.code===_p.INIT_DATACHANNEL_TIMEOUT?(Gi.warning("[".concat(this.store.clientId,"] User join datachannel failed"),H.toString()),this.resetSignal(),H):(Gi.error("[".concat(this.store.clientId,"] User join failed"),H.toString()),jE.joinGateway(i.sid,{lts:g,succ:!1,ec:H.message,addr:this.signal.url,uid:i.uid,cid:i.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!j,signalChannel:this.signal instanceof eR?"1":"0"}),this._isProactiveJoin=!1,b.delete(i.uid),this.signal.close(),H)}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),Gi.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval(()=>{this.updateTrafficStats().catch(H=>{Gi.warning("[".concat(this.store.clientId,"] get traffic stats error"),H.toString())})},3e3),this.networkQualityInterval=window.setInterval(()=>{navigator&&navigator.onLine!==void 0&&!navigator.onLine?this.emit(j_.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(j_.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):this.state==="CONNECTED"&&this._statsCollector.trafficStats?this.emit(j_.NETWORK_QUALITY,{uplinkNetworkQuality:s5(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:s5(this._statsCollector.trafficStats.B_dnq)}):this.emit(j_.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})},2e3),this.store.joinGatewayEnd(),A}async leave(){let i=arguments.length>0&&arguments[0]!==void 0&&arguments[0],o=arguments.length>1?arguments[1]:void 0;if(this.state!=="DISCONNECTED"){o!==e_.FALLBACK&&(this.state="DISCONNECTING");try{i||this.signal.connectionState!==t_.CONNECTED||await function(p,g){return g===1/0?p:pE.race([p,R$(g)])}(this.signal.request(FE.LEAVE,void 0,!0),3e3)}catch(p){Gi.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),p)}this.signal.close(o),o!==e_.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(i,o,p){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const g={state:"offer",p2p_id:this.store.p2pId,ortc:o,mode:this.spec.mode,extend:nE("PUB_EXTEND"),twcc:!!nE("PUBLISH_TWCC"),rtx:!!nE("USE_PUB_RTX")};try{return(await this.signal.request(FE.PUBLISH,g,!0))._message}catch(b){if(p&&b.data&&b.data.code===qE.ERR_PUBLISH_REQUEST_INVALID)return Gi.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),b.toString()),await this.tryUnpubBeforeRepub(i,o),this.publish(i,o,!1);throw b}}async publishDataChannel(i,o,p){var g;if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const b={stream_id:o.streamId,ordered:o.ordered?1:0,max_retrans_times:(g=o.maxRetransmits)!==null&&g!==void 0?g:10,channel_id:o.channelId,metadata:o.metadata};try{await this.signal.request(FE.PUBLISH_DATASTREAM,b,!0)}catch(A){if(p&&A.data&&A.data.code===qE.ERR_PUBLISH_REQUEST_INVALID)return Gi.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),A.toString()),await this.tryUnpubDataChannelBeforeRepub(i,o),this.publishDataChannel(i,o,!1);throw A}}async unpublish(i,o){try{if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(FE.UNPUBLISH,{stream_id:o,ortc:i},!0)}catch(p){Gi.warning("[".concat(this.store.clientId,"] unpublish warning: "),p)}}async unpublishDataChannel(i){try{if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await pE.all(i.map(o=>this.signal.request(FE.UNPUBLISH_DATASTREAM,{channel_id:o},!0)))}catch(o){Gi.warning("unpublish datachannels warning: ",o)}}async subscribe(i,o,p){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const g={stream_id:i,stream_type:o.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!nE("SUBSCRIBE_TWCC"),rtx:!!nE("USE_SUB_RTX"),extend:nE("SUB_EXTEND"),ssrcId:o.ssrcId,svc:Array.isArray(nE("SVC"))&&nE("SVC").length!==0?nE("SVC"):void 0};try{return(await this.signal.request(FE.SUBSCRIBE,g,!0))._message}catch(b){if(p&&b.data&&b.data.code===qE.ERR_SUBSCRIBE_REQUEST_INVALID)return Gi.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),b.toString()),await this.tryUnsubBeforeResub(i,o),await this.subscribe(i,o,!1);throw b}}async subscribeDataChannel(i,o,p){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const g={uid:i,stream_id:o.id,channel_id:o.datachannelId};try{return void await this.signal.request(FE.SUBSCRIBE_DATASTREAM,g,!0)}catch(b){if(p&&b.data&&b.data.code===qE.ERR_SUBSCRIBE_REQUEST_INVALID)return Gi.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),b.toString()),await this.tryUnsubDataChannelBeforeResub(i,o),await this.subscribeDataChannel(i,o,!1);throw b}}async subscribeAll(i,o){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const p={p2p_id:this.store.p2pId,users:i,dtx:!1,rtx:!!nE("USE_SUB_RTX")};try{return await this.signal.request(FE.SUBSCRIBE_STREAMS,p,!0)}catch(g){if(o&&g.data&&g.data.code===qE.ERR_SUBSCRIBE_REQUEST_INVALID)return Gi.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),g.toString()),await this.tryMassUnsubBeforeResub(i),await this.subscribeAll(i,!1);throw g}}async setVideoProfile(i){const o=function(p){if(!(p.bitrateMax&&p.bitrateMin&&p.frameRate&&p.height&&p.width))return;let g=p.frameRate,b=p.width,A=p.height,j=!0;return typeof g!="number"&&(g=g.exact||g.ideal||g.max||g.min||0,g||(j=!1)),typeof b!="number"&&(b=b.exact||b.ideal||b.max||b.min||0,b||(j=!1)),typeof A!="number"&&(A=A.exact||A.ideal||A.max||A.min||0,g||(j=!1)),j?{stream_type:0,width:b,height:A,fps:g,start_bps:1e3*p.bitrateMax,min_bps:1e3*p.bitrateMin,target_bps:1e3*p.bitrateMax}:void 0}(i);if(o)return this.signal.request(FE.SET_VIDEO_PROFILE,o);Gi.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(i,o){try{await this.signal.request(FE.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:i,stream_id:o},!0)}catch(p){Gi.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),p)}}async unsubscribeDataChannel(i,o){try{if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await pE.all(i.map(p=>this.signal.request(FE.UNSUBSCRIBE_DATASTREAM,{stream_id:p,uid:o},!0)))}catch(p){Gi.warning("unsubscribeDataChannel warning: ",p)}}async massUnsubscribe(i){try{await this.signal.request(FE.UNSUBSCRIBE_STREAMS,i,!0)}catch(o){Gi.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),o)}}async reconnectPC(i){const{iceParameters:o,dtlsParameters:p,rtpCapabilities:g}=i;return{gatewayEstablishParams:await this.signal.request(FE.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:o,dtlsParameters:p,rtpCapabilities:g}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(FE.GATEWAY_INFO)}async renewToken(i){await this.signal.request(FE.RENEW_TOKEN,i),this.key=i.token}async setClientRole(i,o){if(o&&(this._clientRoleOptions=Object.assign({},o)),this.state!=="CONNECTED")return void(this.role=i);let p,g=0;i==="audience"?this._clientRoleOptions&&this._clientRoleOptions.delay?(p=this._clientRoleOptions.delay,g=1):g=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:g=0,await this.signal.request(FE.SET_CLIENT_ROLE,{role:i,level:g,delay:p,client_ts:Date.now()}),this.role=i}async setRemoteVideoStreamType(i,o){await this.signal.request(FE.SWITCH_VIDEO_STREAM,{stream_id:i,stream_type:o})}async setDefaultRemoteVideoStreamType(i){await this.signal.request(FE.DEFAULT_VIDEO_STREAM,{stream_type:i})}async setStreamFallbackOption(i,o){await this.signal.request(FE.SET_FALLBACK_OPTION,{stream_id:i,fallback_type:o})}async pickSVCLayer(i,o){await this.signal.request(FE.PICK_SVC_LAYER,{stream_id:i,spatial_layer:o.spatialLayer,temporal_layer:o.temporalLayer})}async setRTM2Flag(i){await this.signal.request(FE.SET_RTM2_FLAG,{rtm2_flag:i})}async sendExtensionMessage(i,o,p){if(this.signal instanceof c5)return this.signal.sendExtensionMessage(i,o,p)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),dT({},this.inChannelInfo)}async getGatewayVersion(){return(await this.signal.request(FE.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 i=u2.get(this.joinInfo.cname);i&&i.delete(this.joinInfo.uid)}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0)}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const i=function(o){let p;return p=o.startsWith("dc")?o.match(/(dc\:\/\/)?([^:]+):(\d+)/):o.match(/(wss\:\/\/)?([^:]+):(\d+)/),p?{username:wS.username,password:wS.password,turnServerURL:p[2],tcpport:parseInt(p[3])+30,udpport:parseInt(p[3])+30,forceturn:!1}:null}((this.joinInfo.cloudProxyServer==="disabled"?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"");this.joinInfo.turnServer.serversFromGateway=[],i&&this.joinInfo.turnServer.mode!=="off"&&this.joinInfo.cloudProxyServer==="disabled"&&this.joinInfo.turnServer.serversFromGateway.push(dT(dT({},wS),{},{turnServerURL:i.turnServerURL,tcpport:i.tcpport,udpport:i.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}async updateTrafficStats(){if(this.state!=="CONNECTED")return;const i=await this.signal.request(FE.TRAFFIC_STATS,void 0,!0);i.timestamp=Date.now(),i.ntp_offset!=null&&(this.ntpOffset=i.ntp_offset),i.peer_delay.forEach(o=>{const p=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find(g=>g.peer_uid===o.peer_uid);p&&p.B_st!==o.B_st&&sT(()=>{this.emit(j_.STREAM_TYPE_CHANGE,o.peer_uid,o.B_st)})}),this._statsCollector.updateTrafficStats(i)}getJoinMessage(i){if(!this.joinInfo||!this.key)throw new hE(_p.UNEXPECTED_ERROR,"can not generate join message, no join info");const o=Object.assign({},this.joinInfo.apResponse);let p=nE("REPORT_APP_SCENARIO");if(typeof p!="string")try{p=JSON.stringify(p)}catch{p=void 0}p&&p.length>128&&(p=void 0);const g=dT({license:this.joinInfo.license,p2p_id:this.store.p2pId,session_id:this.joinInfo.sid,app_id:this.joinInfo.appId,channel_key:this.key,channel_name:this.joinInfo.cname,sdk_version:qS,browser:navigator.userAgent,process_id:nE("PROCESS_ID"),mode:this.store.useP2P?"p2p":this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:o,extend:nE("JOIN_EXTEND"),details:{6:this.joinInfo.stringUid,cservice_map:this.joinInfo.cloudProxyServer==="proxy3"?"1":this.joinInfo.cloudProxyServer==="proxy5"?"2":void 0},features:{rejoin:!0},optionalInfo:this.joinInfo.optionalInfo,appScenario:p,attributes:{userAttributes:{enablePublishedUserList:nE("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:nE("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:typeof nE("SUBSCRIBE_AUDIO_FILTER_TOPN")=="number"?nE("SUBSCRIBE_AUDIO_FILTER_TOPN"):void 0,enablePublishAudioFilter:typeof nE("ENABLE_PUBLISH_AUDIO_FILTER")=="boolean"?nE("ENABLE_PUBLISH_AUDIO_FILTER"):void 0,enableUserLicenseCheck:typeof nE("ENABLE_USER_LICENSE_CHECK")=="boolean"?nE("ENABLE_USER_LICENSE_CHECK"):void 0,enableRTX:nE("USE_PUB_RTX")===!0||nE("USE_SUB_RTX")===!0||void 0,disableFEC:nE("DISABLE_FEC"),enableNTPReport:!!nE("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:!!nE("ENABLE_INSTANT_VIDEO")||void 0,enableDataStream2:typeof nE("ENABLE_DATASTREAM_2")=="boolean"?nE("ENABLE_DATASTREAM_2"):void 0,rtm2Flag:typeof nE("RTM2_FLAG")=="number"?nE("RTM2_FLAG"):void 0,enableUserAutoRebalanceCheck:!!nE("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:typeof nE("USE_XR")=="boolean"?nE("USE_XR"):void 0}},join_ts:this.joinGatewayStartTime},i);return this.joinInfo.stringUid&&(g.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(g.aes_mode=this.joinInfo.aesmode,nE("ENCRYPT_AES")?(g.aes_secret=this.joinInfo.aespassword,g.aes_encrypt=!0):g.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(g.aes_salt=this.joinInfo.aessalt)),o.addresses[this.signal.websocket.currentURLIndex]&&(g.ap_response.ticket=o.addresses[this.signal.websocket.currentURLIndex].ticket,delete o.addresses),this.joinInfo.defaultVideoStream!==void 0&&(g.default_video_stream=this.joinInfo.defaultVideoStream),g}getRejoinMessage(){if(!this.joinInfo)throw new hE(_p.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(kE.WS_RECONNECT_WAITTING_FINISH,i=>{var o;VE(o=["tryNext","recover"]).call(o,i)&&this.joinInfo&&jE.adjustSessionStartTime(this.joinInfo.sid)}),this.signal.on(kE.WS_RECONNECT_CREATE_CONNECTION,i=>{this.joinGatewayStartTime=Date.now()}),this.signal.on(kE.WS_RECONNECTING,i=>{this.joinInfo&&jE.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:i||h0.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",jE.sessionInit(this.joinInfo.sid,{lts:new Date().getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())}),this.signal.on(kE.WS_CLOSED,i=>{let o;switch(i){case e_.LEAVE:o=h0.LEAVE;break;case e_.UID_BANNED:case e_.IP_BANNED:case e_.CHANNEL_BANNED:case e_.SERVER_ERROR:o=h0.SERVER_ERROR;break;case e_.FALLBACK:o=h0.FALLBACK;break;case e_.LICENSE_MISSING:case e_.LICENSE_EXPIRED:case e_.LICENSE_MINUTES_EXCEEDED:case e_.LICENSE_PERIOD_INVALID:case e_.LICENSE_MULTIPLE_SDK_SERVICE:case e_.LICENSE_ILLEGAL:case e_.TOKEN_EXPIRE:o=i;break;default:o=h0.NETWORK_ERROR}Gi.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(o||"undefined -> "+h0.NETWORK_ERROR)),this.joinInfo&&jE.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:i===e_.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:o}),this._disconnectedReason=i,i!==e_.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}),this.signal.on(kE.WS_CONNECTED,()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo&&(this.role==="audience"&&this._clientRoleOptions&&(this._clientRoleOptions.level||this._clientRoleOptions.delay)&&(Gi.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(this._clientRoleOptions.level,", delay: ").concat(this._clientRoleOptions.delay)),this.setClientRole(this.role,this._clientRoleOptions)),jE.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,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof eR?"1":"0"}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&this.joinInfo.setLocalAPVersion===1)){const i=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!i)return void Gi.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(i));y_("EVENT_REPORT_DOMAIN",i[1]),y_("EVENT_REPORT_BACKUP_DOMAIN",i[1]),y_("LOG_UPLOAD_SERVER","".concat(i[1],":6444"))}}),this.signal.on(JE.ON_UPLINK_STATS,i=>{this._statsCollector.updateUplinkStats(i)}),this.signal.on(kE.REQUEST_RECOVER,(i,o,p)=>{if(!this.joinInfo)return p(new hE(_p.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));i&&(this.joinInfo.multiIP=i,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,U_(this,j_.REQUEST_NEW_GATEWAY_LIST).then(o).catch(p)}),this.signal.on(kE.REQUEST_JOIN_INFO,async i=>{var o;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void i(this.getJoinMessage({ortc:{}}));const{iceParameters:p,dtlsParameters:g,rtpCapabilities:b}=await U_(this,j_.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:(o=this.joinInfo)===null||o===void 0?void 0:o.turnServer});i(this.getJoinMessage({ortc:{iceParameters:p,dtlsParameters:g,rtpCapabilities:b,version:"2"}}))}),this.signal.on(kE.REQUEST_REJOIN_INFO,i=>{i(this.getRejoinMessage())}),this.signal.on(kE.REPORT_JOIN_GATEWAY,(i,o)=>{this.joinInfo&&(jE.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:i,addr:o,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,avoidJoinStartTime:this.store.avoidJoinStart,isProxy:!!this.joinInfo.proxyServer,signalChannel:this.signal instanceof eR?"1":"0"}),this._isProactiveJoin=!1)}),this.signal.on(kE.IS_P2P_DISCONNECTED,i=>{i(JT(this,j_.IS_P2P_DISCONNECTED))}),this.signal.on(kE.DISCONNECT_P2P,()=>{this.emit(j_.DISCONNECT_P2P)}),this.signal.on(kE.NEED_RENEW_SESSION,()=>{this.emit(j_.NEED_RENEW_SESSION)}),this.signal.on(kE.REQUEST_SUCCESS,()=>{this._signalTimeout=!1}),this.signal.on(kE.REQUEST_TIMEOUT,()=>{this._signalTimeout=!0}),this.signal.on(kE.JOIN_RESPONSE,i=>{const o=this.getCurrentGatewayAddress();this.emit(j_.JOIN_RESPONSE,i,o)}),this.signal.on(kE.DATACHANNEL_PRECONNECT,async(i,o,p)=>{this.updateTurnConfigFromSignal();const g=this.getCurrentGatewayAddress();return U_(this,j_.DATACHANNEL_PRECONNECT,i,g).then(o).catch(p)}),this.signal.on(kE.DATACHANNEL_CONNECTING,async i=>{const{iceParameters:o,dtlsParameters:p,rtpCapabilities:g}=await U_(this,j_.REQUEST_DC_CONNECTION_PARAMS);i(this.getJoinMessage({ortc:{iceParameters:o,dtlsParameters:p,rtpCapabilities:g,version:"2"}}))}),this.signal.on(kE.DATACHANNEL_FAILBACK,()=>{Gi.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(j_.DATACHANNEL_FAILBACK)})}async tryUnsubBeforeResub(i,o){try{await this.signal.request(FE.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:i,ortc:[o]},!0)}catch(p){throw Gi.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),p),p}}async tryUnsubDataChannelBeforeResub(i,o){try{await this.signal.request(FE.UNSUBSCRIBE,{stream_id:o.id},!0)}catch(p){throw Gi.warning("unsubscribe datachannel warning",p),p}}async tryUnpubBeforeRepub(i,o){try{await this.signal.request(FE.UNPUBLISH,{stream_id:i,ortc:o},!0)}catch(p){throw Gi.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),p),p}}async tryUnpubDataChannelBeforeRepub(i,o){try{await this.signal.request(FE.UNPUBLISH_DATASTREAM,{channnel_id:o.channelId},!0)}catch(p){throw Gi.warning("unpublish datastream warning: ",p),p}}async tryMassUnsubBeforeResub(i){const o={users:i.map(p=>({stream_id:p.stream_id,stream_type:p.stream_type}))};try{await this.signal.request(FE.UNSUBSCRIBE_STREAMS,o,!0)}catch(p){throw Gi.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),p),p}}async muteLocal(i,o){const p={action:i.find(g=>g.stream_type===v_.Audio)?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:i,stream_id:o};try{await this.signal.request(FE.CONTROL,p,!0,!0)}catch(g){throw Gi.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),g),g}}async unmuteLocal(i,o){const p={action:i.find(g=>g.stream_type===v_.Audio)?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:i,stream_id:o};try{await this.signal.request(FE.CONTROL,p,!0,!0)}catch(g){throw Gi.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),g),g}}async muteRemote(i,o){const p={action:i===ME.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:o};try{await this.signal.request(FE.CONTROL,p,!0,!0)}catch(g){throw Gi.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),g),g}}async unmuteRemote(i,o){const p={action:i===ME.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:o};try{await this.signal.request(FE.CONTROL,p,!0,!0)}catch(g){throw Gi.warning("[".concat(this.store.clientId,"] gateway unmuteRemote warning: "),g),g}}uploadStats(i,o){this.signal.upload(i,o)}getSignalRTT(){return this.signal.rtt}async restartICE(i){const o={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:i};try{return await this.signal.request(FE.RESTART_ICE,o,!0)}catch(p){throw Gi.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),p),p}}reconnect(){this.state==="CONNECTED"&&this.signal.reconnect(void 0,h0.P2P_FAILED)}getCurrentGatewayAddress(){var i;if(!nE("GATEWAY_WSS_ADDRESS"))return(i=this.joinInfo)!==null&&i!==void 0&&i.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}async setPublishAudioFilterEnabled(i){await this.signal.request(FE.SET_PARAMETER,{enablePublishAudioFilter:i})}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close(e_.FALLBACK)),this.store.useDataChannel=!1,this.signal=new w6(dT(dT({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(j_.RESET_SIGNAL,wN.websocket)}}let sP=0,l2=0;function nR(l,i,o,p){return new pE((g,b)=>{i.timeout=i.timeout||nE("HTTP_CONNECT_TIMEOUT"),i.responseType=i.responseType||"json",i.data&&!o?(i.data=JSON.stringify(i.data),sP+=AT(i.data)):o&&(i.data.size?sP+=i.data.size:i.data instanceof FormData?sP+=nG(i.data):sP+=AT(JSON.stringify(i.data))),i.headers=i.headers||{},i.headers["Content-Type"]=i.headers["Content-Type"]||"application/json",i.method="POST",i.url=l,aS.request(i).then(A=>{typeof A.data=="string"?l2+=AT(A.data):A.data instanceof ArrayBuffer||A.data instanceof Uint8Array?l2+=A.data.byteLength:l2+=AT(JSON.stringify(A.data)),p&&g({data:A.data,headers:A.headers}),g(A.data)}).catch(A=>{aS.isCancel(A)?b(new hE(_p.OPERATION_ABORTED,"cancel token canceled")):A.code==="ECONNABORTED"?b(new hE(_p.NETWORK_TIMEOUT,A.message)):A.response?b(new hE(_p.NETWORK_RESPONSE_ERROR,A.response.status)):b(new hE(_p.NETWORK_ERROR,A.message))})})}/*! formdata-polyfill. MIT License. Jimmy W?rting */(function(){var l;function i(CE){var AE=0;return function(){return AE>>0)+"_",YE=0;return function h_(NE){if(this instanceof h_)throw new TypeError("Symbol is not a constructor");return new AE(UE+(NE||"")+"_"+YE++,NE)}}),b("Symbol.iterator",function(CE){if(CE)return CE;CE=Symbol("Symbol.iterator");for(var AE="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),UE=0;UE"u"||!FormData.prototype.keys)){var oE=function(CE,AE){for(var UE=0;UE{const l=nE("AREAS");return l.length===0&&l.push(c_.GLOBAL),_C(l).call(l,(i,o,p)=>{const g=l5(o);return g?p===0?g:"".concat(i,",").concat(g):i},"")},l5=l=>l===c_.OVERSEA?"".concat(C0.ASIA,",").concat(C0.EUROPE,",").concat(C0.AFRICA,",").concat(C0.NORTH_AMERICA,",").concat(C0.SOUTH_AMERICA,",").concat(C0.OCEANIA):C0[l],yet=l=>{const i={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 l.map(o=>{const p=AN[o],g=Object.keys(p);g&&g.map(b=>{b!=="CODE"&&(i[b]=i[b].concat(p[b]))})}),i},aP={GLOBAL:{ASIA:[c_.CHINA,c_.JAPAN,c_.INDIA,c_.KOREA,c_.HKMC],EUROPE:[],NORTH_AMERICA:[c_.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},cP=Object.keys(aP[c_.GLOBAL]),d2=[c_.CHINA,c_.NORTH_AMERICA,c_.EUROPE,c_.ASIA,c_.JAPAN,c_.INDIA,c_.OCEANIA,c_.SOUTH_AMERICA,c_.AFRICA,c_.KOREA,c_.HKMC,c_.US],bet=function(l,i){let o=[];if(VE(l).call(l,c_.GLOBAL)){const b=[c_.GLOBAL,c_.OVERSEA],A=Object.keys(AN);if(i===c_.GLOBAL)throw new hE(_p.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(i===c_.CHINA)o=[c_.OVERSEA];else if(g=i,VE(cP).call(cP,g)){const j=(p=i,aP[c_.GLOBAL][p]||[]),H=[...b,i,...j];o=A.filter(z=>!VE(H).call(H,z))}else if(function(j){let H=!1;return cP.forEach(z=>{var $;VE($=aP[c_.GLOBAL][z]).call($,j)&&(H=!0)}),H}(i)){const j=function(z){let $;return cP.forEach(Vt=>{var _r;VE(_r=aP[c_.GLOBAL][Vt]).call(_r,z)&&($=Vt)}),$}(i),H=[...b,j,i];o=A.filter(z=>!VE(H).call(H,z))}else o=l;o=function(j){const H=[];return d2.forEach(z=>{VE(j).call(j,z)&&H.push(z)}),H.concat(j.filter(z=>!VE(d2).call(d2,z)))}(o)}else o=l;var p,g;return o};function d5(l){var i,o;if(!l&&VE(i=nE("AREAS")).call(i,c_.EXTENSIONS))return Gi.debug("update area from ap : reset"),void h2(_Z,!0);if(!VE(o=nE("AREAS")).call(o,c_.GLOBAL)||!l)return;let p=AN.EXTENSIONS;p&&(p={CODE:l5(c_.EXTENSIONS),WEBCS_DOMAIN:["ap-web-1-".concat(l,".agora.io")],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-".concat(l,".ap.sd-rtn.com")],PROXY_CS:["proxy-ap-web-".concat(l,".agora.io")],CDS_AP:["cds-ap-web-1-".concat(l,".agora.io"),"cds-ap-web-2-".concat(l,".ap.sd-rtn.com")],ACCOUNT_REGISTER:["sua-ap-web-1-".concat(l,".agora.io"),"sua-ap-web-2-".concat(l,".ap.sd-rtn.com")],UAP_AP:["uap-ap-web-1-".concat(l,".agora.io"),"uap-ap-web-2-".concat(l,".ap.sd-rtn.com")],EVENT_REPORT_DOMAIN:["statscollector-1-".concat(l,".agora.io")],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-".concat(l,".agora.io")],LOG_UPLOAD_SERVER:["logservice-".concat(l,".agora.io")],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy-".concat(l,".agora.io")]},Gi.debug("update area from ap success: ".concat(l,",config is "),p),y_("AREAS",[c_.EXTENSIONS],!0),Object.keys(p).map(g=>{g==="LOG_UPLOAD_SERVER"||g==="EVENT_REPORT_DOMAIN"||g==="EVENT_REPORT_BACKUP_DOMAIN"||g==="PROXY_SERVER_TYPE3"?y_(g,p[g][0]):y_(g,p[g])}))}function h2(l){let i=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const o=jE.reportApiInvoke(null,{name:e0.SET_AREA,options:l,tag:x_.TRACER});try{let p=[];if(typeof l=="string"&&(p=[l]),Array.isArray(l)&&(l.forEach(b=>{if(!VE(g6).call(g6,b))throw new hE(_p.INVALID_PARAMS,"invalid area code")}),p=l),Object.prototype.toString.call(l)==="[object Object]"){const{areaCode:b,excludedArea:A}=l;if(!b)throw new hE(_p.INVALID_PARAMS,"area code is needed");let j=b;typeof b=="string"&&(j=[b]),p=A?bet(j,A):j}if(!i){if(pR.AREAS){const b=new hE(_p.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return o.onError(b),void Gi.warning("setArea is prohibited because of config-distribute")}if(VE(p).call(p,c_.GLOBAL)&&nE("AREAS")===c_.EXTENSIONS){const b=new hE(_p.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return o.onError(b),void Gi.warning("setArea is prohibited because of ap extensions")}}y_("AREAS",p,i);const g=yet(p);Object.keys(g).map(b=>{b==="LOG_UPLOAD_SERVER"||b==="EVENT_REPORT_DOMAIN"||b==="EVENT_REPORT_BACKUP_DOMAIN"||b==="PROXY_SERVER_TYPE3"?y_(b,g[b][0]):y_(b,g[b])}),Gi.debug("set area success:",p.join(","))}catch(p){throw o.onError(p),p}o.onSuccess()}function h5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function p2(l){for(var i=1;i{j=Date.now();const $=await nR(z,{data:A,cancelToken:p,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(H=Date.now()-j,$.code!==0){const Fi=new hE(_p.UNEXPECTED_RESPONSE,"live streaming ap error, code"+$.code,{retry:!0,responseTime:H});throw Gi.error(Fi.toString()),Fi}const Vt=JSON.parse($.json_body);if(Vt.code!==200){const Fi=new hE(_p.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(Vt.code,", reason: ").concat(Vt.reason),{code:Vt.code,responseTime:H});throw Gi.error(Fi.toString()),Fi}if(!Vt.servers||Vt.servers.length===0){const Fi=new hE(_p.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:Vt.code,responseTime:H});throw Gi.error(Fi.toString()),Fi}const _r=function(Fi,_l){return{addressList:Fi.servers.map(_u=>"wss://".concat(_u.address.replace(/\./g,"-"),".").concat(nE("WORKER_DOMAIN"),":").concat(_u.wss,"?serviceName=").concat(encodeURIComponent(_l))),workerToken:Fi.workerToken,vid:Fi.vid}}(Vt,i);return nE("LIVE_STREAMING_ADDRESS")&&(_r.addressList=nE("LIVE_STREAMING_ADDRESS")instanceof Array?nE("LIVE_STREAMING_ADDRESS"):[nE("LIVE_STREAMING_ADDRESS")]),p2(p2({},_r),{},{responseTime:H})},($,Vt)=>(jE.apworkerEvent(o.sid,{success:!0,sc:200,serviceName:i,responseDetail:JSON.stringify($.addressList),firstSuccess:Vt===0,responseTime:H,serverIp:l[Vt%l.length]}),!1),($,Vt)=>(jE.apworkerEvent(o.sid,{success:!1,sc:$.data&&$.data.code||200,serviceName:i,responseTime:H,serverIp:l[Vt%l.length]}),!!($.code!==_p.OPERATION_ABORTED&&$.code!==_p.UNEXPECTED_RESPONSE||$.data&&$.data.retry)&&(z=l[(Vt+1)%l.length],!0)),g)}let m2=1;function p5(l,i,o,p){let{url:g,areaCode:b}=l;const A=Date.now();let j;const[H,z]=E5(i,b,[v0.CHOOSE_SERVER]);let $=X_.networkState;return vT(async()=>{$&&X_.networkState===K0.OFFLINE&&X_.onlineWaiter&&await pE.race([X_.onlineWaiter,w0(p&&p.maxRetryTimeout||$_.maxRetryTimeout)]),$=X_.networkState;const{data:Vt,headers:_r}=await nR(g,{data:H,cancelToken:o,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);j=_r.http3==="1"?1:-1,jE.reportResourceTiming(g,i.sid),m5(Vt,g,i,A,[v0.CHOOSE_SERVER],j);const Fi=a2(Vt,v0.CHOOSE_SERVER);return g5(Fi),r5(Fi,g)},Vt=>(Vt&&jE.joinChooseServer(i.sid,{lts:A,succ:!0,csAddr:g,opid:z,serverList:Vt.gatewayAddrs.map(_r=>_r.address),ec:null,cid:Vt.cid.toString(),uid:Vt.uid.toString(),csIp:Vt.csIp,unilbsServerIds:[v0.CHOOSE_SERVER].toString(),isHttp3:j}),!1),Vt=>Vt.code!==_p.OPERATION_ABORTED&&(Vt.code===_p.CAN_NOT_GET_GATEWAY_SERVER?Vt.data.retry:(jE.joinChooseServer(i.sid,{lts:A,succ:!1,csAddr:g,serverList:null,opid:z,ec:Vt.code,csIp:Vt.data&&Vt.data.csIp,unilbsServerIds:[v0.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:$}),isHttp3:j}),Gi.warning("[".concat(i.clientId,"] Choose server network error, retry"),Vt),!0)),p)}function f5(l,i,o,p){let g,{url:b,areaCode:A,serviceIds:j}=l;const H=Date.now(),[z,$]=E5(i,A,j);let Vt;return vT(async()=>{Vt&&X_.networkState===K0.OFFLINE&&X_.onlineWaiter&&await pE.race([X_.onlineWaiter,w0(p&&p.maxRetryTimeout||$_.maxRetryTimeout)]),Vt=X_.networkState;const{data:_r,headers:Fi}=await nR(b,{data:z,cancelToken:o,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);g=Fi.http3==="1"?1:-1,jE.reportResourceTiming(b,i.sid),m5(_r,b,i,H,j,g);const _l=a2(_r,v0.CHOOSE_SERVER),_u=a2(_r,i.cloudProxyServer==="proxy5"?v0.CLOUD_PROXY_5:i.cloudProxyServer==="proxy3"||i.cloudProxyServer==="proxy4"?v0.CLOUD_PROXY:v0.CLOUD_PROXY_FALLBACK);return g5(_l),{gatewayInfo:r5(_l,b),proxyInfo:_u,url:b}},_r=>(_r.gatewayInfo&&jE.joinChooseServer(i.sid,{lts:H,succ:!0,csAddr:b,serverList:_r.gatewayInfo.gatewayAddrs.map(Fi=>Fi.address),ec:null,opid:$,cid:_r.gatewayInfo.cid.toString(),uid:_r.gatewayInfo.uid.toString(),csIp:_r.gatewayInfo.csIp,unilbsServerIds:j.toString(),isHttp3:g}),_r.proxyInfo&&jE.joinWebProxyAP(i.sid,{lts:H,sucess:1,apServerAddr:b,turnServerAddrList:_r.proxyInfo.addresses.map(Fi=>Fi.ip).join(","),errorCode:null,eventType:i.cloudProxyServer,unilbsServerIds:j.toString()}),!1),_r=>_r.code!==_p.OPERATION_ABORTED&&(_r.code===_p.CAN_NOT_GET_GATEWAY_SERVER?_r.data.retry:(jE.joinWebProxyAP(i.sid,{lts:H,sucess:0,apServerAddr:b,turnServerAddrList:null,errorCode:_r.code,eventType:i.cloudProxyServer,unilbsServerIds:j.toString(),extend:JSON.stringify({networkState:Vt})}),Gi.warning("[".concat(i.clientId,"] multi unilbs network error, retry"),_r),!0)),p)}const m5=(l,i,o,p,g,b)=>{const A=[],j=H=>{H.flag===4096?jE.joinChooseServer(o.sid,{lts:p,succ:!1,csAddr:i,opid:l.opid,serverList:null,ec:H.error.message,csIp:H.error.data&&H.error.data.csIp,unilbsServerIds:g.toString(),isHttp3:b}):H.flag!==1048576&&H.flag!==4194304&&H.flag!==4194310||jE.joinWebProxyAP(o.sid,{lts:p,sucess:0,apServerAddr:i,turnServerAddrList:null,errorCode:H.error.code,eventType:o.cloudProxyServer,unilbsServerIds:g.toString()})};if(l.response_body.forEach(H=>{const z=H.buffer.code;if(H.uri===23&&z===0&&!H.buffer.edges_services)if(H.buffer.flag===4194310)Gi.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),H.buffer.edges_services=[];else{const $={error:new hE(_p.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:l.detail[502]}),flag:H.buffer.flag};A.push($),j($)}if(z!==0){const $=NN(z),Vt={error:new hE(_p.CAN_NOT_GET_GATEWAY_SERVER,$.desc,{desc:$.desc,retry:$.retry,csIp:l.detail[502]}),flag:H.buffer.flag};H.buffer.flag===4194310?Gi.warning(Vt.error.toString()):A.push(Vt),j(Vt)}}),A.length)throw Gi.warning("[".concat(o.clientId,"] multi unilbs ").concat(i," failed, ").concat(A.map(H=>"flag: ".concat(H.flag,", message: ").concat(H.error.message,", retry: ").concat(H.error.data.retry)).join(" | "))),new hE(_p.CAN_NOT_GET_GATEWAY_SERVER,A.map(H=>"flag: ".concat(H.flag,", message: ").concat(H.error.message)).join(" | "),{retry:!!A.find(H=>H.error.data.retry),csIp:l.detail[502],desc:[...new Set(A.map(H=>{var z;return H==null||(z=H.error)===null||z===void 0||(z=z.data)===null||z===void 0?void 0:z.desc}).filter(H=>!!H))]})},g5=l=>{var i,o,p,g;if(l.addresses&&l.addresses.length===0&&l.code===0)throw new hE(_p.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:l.detail&&l.detail[502]});if(nE("AP_AREA")&&((p=l.detail)!==null&&p!==void 0&&p[23]&&typeof((g=l.detail)===null||g===void 0?void 0:g[23])=="string"?d5(l.detail[23].toLowerCase()):d5()),(i=l.detail)!==null&&i!==void 0&&i[19]&&typeof((o=l.detail)===null||o===void 0?void 0:o[19])=="string"){const A=l.detail[19],j=A==null?void 0:A.split(";");for(let H=0;H0){Gi.debug("assign gateway address to",nE("GATEWAY_ADDRESS"));const A=nE("GATEWAY_ADDRESS").map(j=>{var H,z;const $=(H=(z=l.addresses.find(Vt=>Vt.ip===j.ip&&Vt.port===j.port))===null||z===void 0?void 0:z.fingerprint)!==null&&H!==void 0?H:"";return{ip:j.ip,port:j.port,ticket:l.addresses[0]&&l.addresses[0].ticket,fingerprint:$}});l.addresses=A}},Ret=(l,i)=>{if(l.response_body&&l.response_body.length){const o=l.response_body[0];if(o.buffer.code!==0){const p=NN(o.buffer.code);throw new hE(_p.UPDATE_TICKET_FAILED,"[".concat(o.buffer.code,"]: ").concat(p.desc),{retry:p.retry})}return o.buffer.ticket}throw Gi.debug("update ticket request received ap response without response body:",i),new hE(_p.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},E5=(l,i,o)=>{const p=Math.floor(Math.random()*1e12),g={appid:l.appId,client_ts:Date.now(),opid:p,sid:l.sid,request_bodies:[{uri:22,buffer:{cname:l.cname,detail:p2({6:l.stringUid,11:i,12:nE("USE_NEW_TOKEN")?"1":void 0,22:i},nE("AP_RTM")?{26:"RTM2"}:{}),key:l.token,service_ids:o,uid:l.uid||0}}]};g.request_bodies.forEach(A=>{l.multiIP&&l.multiIP.gateway_ip&&(A.buffer.detail[5]=JSON.stringify({vocs_ip:[l.multiIP.uni_lbs_ip],vos_ip:[l.multiIP.gateway_ip]}))});const b=new FormData;return b.append("request",JSON.stringify(g)),[b,p]},Cet=(l,i)=>{const o=Math.floor(Math.random()*1e12),p={appid:l.appId,client_ts:Date.now(),opid:o,sid:l.sid,request_bodies:[{uri:28,buffer:{cname:l.cname,detail:{1:"",6:l.stringUid,12:"1"},token:l.token,service_ids:i,uid:l.uid||0,edges_services:l.apResponse.addresses.map(b=>({ip:b.ip,port:b.port}))}}]},g=new FormData;return g.append("request",JSON.stringify(p)),[g,o]};let aO=0;function cO(l){return pE.all(l.map(i=>i.then(o=>{throw o},o=>o))).then(i=>{throw i},i=>i)}const h1=async l=>{let{fragementLength:i,referenceList:o,asyncMapHandler:p,allFailedhandler:g,promisesCollector:b}=l,A=0;const j=i;let H,z=0;const $=async()=>{const Vt=(()=>{const _r=A*j,Fi=_r+j;return o.slice(_r,Fi).map(p)})();b&&b.push(...Vt);try{H=await cO(Vt)}catch(_r){if(z+=j,A++,!(z>=o.length))return void await $();g(_r)}Vt.forEach(_r=>_r.cancel())};return await $(),H};async function g2(l,i,o,p){return{gatewayInfo:await async function(b,A,j,H){let z=null;const $=[],Vt=async()=>{const Fi=nE("WEBCS_DOMAIN").slice(0,nE("AJAX_REQUEST_CONCURRENT")).map(_h=>({url:b.proxyServer?"https://".concat(b.proxyServer,"/ap/?url=").concat(_h+"/api/v2/transpond/webrtc?v=2"):"https://".concat(_h,"/api/v2/transpond/webrtc?v=2"),areaCode:oP()})),_l=H.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:Fi.map(_h=>_h.url)}),_u=await h1({fragementLength:nE("FRAGEMENT_LENGTH"),referenceList:Fi,asyncMapHandler:_h=>(Gi.debug("[".concat(b.clientId,"] Connect to choose_server:"),_h.url),p5(_h,b,A,j)),allFailedhandler:_h=>{throw H.recordJoinChannelService({endTs:Date.now(),status:"error",errors:_h},_l),_h[0]},promisesCollector:$});return H.recordJoinChannelService({endTs:Date.now(),status:"success"},_l),_u},_r=async()=>{if(await w0(1e3),z!==null)return z;const Fi=nE("WEBCS_DOMAIN_BACKUP_LIST").map(_h=>({url:b.proxyServer?"https://".concat(b.proxyServer,"/ap/?url=").concat(_h+"/api/v2/transpond/webrtc?v=2"):"https://".concat(_h,"/api/v2/transpond/webrtc?v=2"),areaCode:oP()})),_l=H.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:Fi.map(_h=>_h.url)}),_u=await h1({fragementLength:nE("FRAGEMENT_LENGTH"),referenceList:Fi,asyncMapHandler:_h=>(Gi.debug("[".concat(b.clientId,"] Connect to backup choose_server:"),_h.url),p5(_h,b,A,j)),allFailedhandler:_h=>{throw H.recordJoinChannelService({endTs:Date.now(),status:"error",errors:_h},_l),_h[0]},promisesCollector:$});return H.recordJoinChannelService({endTs:Date.now(),status:"success"},_l),_u};try{return z=await cO([Vt(),_r()]),$.length&&$.forEach(Fi=>Fi.cancel&&typeof Fi.cancel=="function"&&Fi.cancel()),z}catch(Fi){throw Fi[0]}}(l,i,o,p)}}async function v5(l,i,o,p,g){const b=l.cloudProxyServer;if(b==="disabled"){if(!p)return;if(l.useLocalAccessPoint)return await g2(l,i,o,g);if(nE("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:z,proxyInfo:$}=await y5(l,i,o,g);return l.turnServer&&l.turnServer.mode!=="auto"||(l.turnServer={mode:"manual",servers:$.map(Vt=>({turnServerURL:Vt.address,tcpport:Vt.tcpport||wS.tcpport,udpport:Vt.udpport||wS.udpport,username:Vt.username||wS.username,password:Vt.password||wS.password,forceturn:!1,security:!0}))}),{gatewayInfo:z}}return await g2(l,i,o,g)}const{proxyInfo:A,gatewayInfo:j}=await y5(l,i,o,g),H={gatewayInfo:j};return l.turnServer={mode:"manual",servers:A.map(z=>({turnServerURL:z.address,tcpport:b==="proxy3"?void 0:z.tcpport?z.tcpport:wS.tcpport,udpport:b==="proxy4"?void 0:z.udpport?z.udpport:wS.udpport,username:z.username||wS.username,password:z.password||wS.password,forceturn:b!=="proxy4",security:b==="proxy5"}))},Gi.debug("[".concat(l.clientId,"] set proxy server: ").concat(l.proxyServer,", mode: ").concat(b)),H}async function _5(l,i,o,p,g){const b=nE("ACCOUNT_REGISTER").slice(0,nE("AJAX_REQUEST_CONCURRENT"));let A=[];A=i.proxyServer?b.map(H=>"https://".concat(i.proxyServer,"/ap/?url=").concat(H+"/api/v1")):b.map(H=>"https://".concat(H,"/api/v1"));const j=g==null?void 0:g.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:A});try{const H=await async function(z,$,Vt,_r,Fi){const _l=Date.now(),_u={sid:Vt.sid,opid:10,appid:Vt.appId,string_uid:$};let _h=z[0];const _g=await vT(()=>nR(_h+"".concat(_h.indexOf("?")===-1?"?":"&","action=stringuid"),{data:_u,cancelToken:_r,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}}),(eE,oE)=>{if(eE.code===0){if(eE.uid<=0||eE.uid>=Math.pow(2,32))throw Gi.error("Invalid Uint Uid ".concat($," => ").concat(eE.uid),eE),jE.reqUserAccount(_u.sid,{lts:_l,success:!1,serverAddr:_h,stringUid:_u.string_uid,uid:eE.uid,errorCode:_p.INVALID_UINT_UID_FROM_STRING_UID,extend:_u}),new hE(_p.INVALID_UINT_UID_FROM_STRING_UID);return jE.reqUserAccount(_u.sid,{lts:_l,success:!0,serverAddr:_h,stringUid:_u.string_uid,uid:eE.uid,errorCode:null,extend:_u}),!1}const SE=NN(eE.code);return SE.retry&&(_h=z[(oE+1)%z.length]),jE.reqUserAccount(_u.sid,{lts:_l,success:!1,serverAddr:_h,stringUid:_u.string_uid,uid:eE.uid,errorCode:SE.desc,extend:_u}),SE.retry},(eE,oE)=>eE.code!==_p.OPERATION_ABORTED&&(jE.reqUserAccount(_u.sid,{lts:_l,success:!1,serverAddr:_h,stringUid:_u.string_uid,uid:null,errorCode:eE.code,extend:_u}),_h=z[(oE+1)%z.length],!0),Fi);if(_g.code!==0){const eE=NN(_g.code);throw new hE(_p.UNEXPECTED_RESPONSE,eE.desc)}return _g}(A,l,i,o,p);return g==null||g.recordJoinChannelService({status:"success",endTs:Date.now()},j),H.uid}catch(H){throw g==null||g.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[H]},j),H}}async function Iet(l,i,o){const p=nE("CDS_AP").slice(0,nE("AJAX_REQUEST_CONCURRENT")).map(j=>l.proxyServer?"https://".concat(l.proxyServer,"/ap/?url=").concat(j+"/api/v1"):"https://".concat(j,"/api/v1?action=config")).map(j=>function(H,z,$,Vt){const _r=l_(),Fi={flag:64,cipher_method:0,features:{device:_r.name,system:_r.os,system_general:navigator.userAgent,vendor:z.appId,version:qS,cname:z.cname,sid:z.sid,session_id:z.sid,detail:"",proxyServer:z.proxyServer}};return vT(()=>nR(H,{data:Fi,timeout:1e3,cancelToken:$,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}}),void 0,_l=>_l.code!==_p.OPERATION_ABORTED,Vt)}(j,l,i,o));let g=null,b=null,A={};try{g=await cO(p)}catch(j){if(j.code===_p.OPERATION_ABORTED)throw j;b=j}if(p.forEach(j=>j.cancel()),jE.reportApiInvoke(l.sid,{name:e0.REQUEST_CONFIG_DISTRIBUTE,options:{error:b,res:g}}).onSuccess(),g&&g.test_tags)try{A=function(j){if(!j.test_tags)return{};const H=j.test_tags,z=Object.keys(H),$={};return z.forEach(Vt=>{var _r;const Fi=bM(_r=Vt.slice(4)).call(_r),_l=JSON.parse(H[Vt])[1];$[Fi]=_l}),$}(g)}catch{}return A}async function y5(l,i,o,p){const g=nE("PROXY_SERVER_TYPE3"),b=(Fi,_l,_u)=>{let _h=_u||g;return Array.isArray(_h)&&(_h=_l%2==0?g[1]:g[0]),"https://".concat(_h,"/ap/?url=").concat(Fi)};let A=null;const j=[],H=async()=>{const Fi=nE("WEBCS_DOMAIN").slice(0,nE("AJAX_REQUEST_CONCURRENT")).map((_h,_g)=>{let eE;return eE=l.cloudProxyServer==="disabled"&&l.proxyServer?b("".concat(_h,"/api/v2/transpond/webrtc?v=2"),_g,l.proxyServer):l.cloudProxyServer==="disabled"||l.cloudProxyServer==="fallback"?"https://".concat(_h,"/api/v2/transpond/webrtc?v=2"):b("".concat(_h,"/api/v2/transpond/webrtc?v=2"),_g),{url:eE,areaCode:oP(),serviceIds:[v0.CHOOSE_SERVER,l.cloudProxyServer==="proxy5"?v0.CLOUD_PROXY_5:l.cloudProxyServer==="proxy3"||l.cloudProxyServer==="proxy4"?v0.CLOUD_PROXY:v0.CLOUD_PROXY_FALLBACK]}}),_l=p.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:Fi.map(_h=>_h.url)}),_u=await h1({fragementLength:nE("FRAGEMENT_LENGTH"),referenceList:Fi,asyncMapHandler:_h=>(Gi.debug("[".concat(l.clientId,"] Connect to choose_server:"),_h.url),f5(_h,l,i,o)),allFailedhandler:_h=>{throw p.recordJoinChannelService({endTs:Date.now(),status:"error",errors:_h},_l),_h[0]},promisesCollector:j});return p.recordJoinChannelService({endTs:Date.now(),status:"success"},_l),_u},z=async()=>{if(await w0(1e3),A!==null)return A;const Fi=nE("WEBCS_DOMAIN_BACKUP_LIST").map((_h,_g)=>{let eE;return eE=l.cloudProxyServer==="disabled"&&l.proxyServer?b("".concat(_h,"/api/v2/transpond/webrtc?v=2"),_g,l.proxyServer):l.cloudProxyServer==="disabled"||l.cloudProxyServer==="fallback"?"https://".concat(_h,"/api/v2/transpond/webrtc?v=2"):b("".concat(_h,"/api/v2/transpond/webrtc?v=2"),_g),{url:eE,areaCode:oP(),serviceIds:[v0.CHOOSE_SERVER,l.cloudProxyServer==="proxy5"?v0.CLOUD_PROXY_5:l.cloudProxyServer==="proxy3"||l.cloudProxyServer==="proxy4"?v0.CLOUD_PROXY:v0.CLOUD_PROXY_FALLBACK]}}),_l=p.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:Fi.map(_h=>_h.url)}),_u=await h1({fragementLength:nE("FRAGEMENT_LENGTH"),referenceList:Fi,asyncMapHandler:_h=>(Gi.debug("[".concat(l.clientId,"] Connect to backup choose_server:"),_h.url),f5(_h,l,i,o)),allFailedhandler:_h=>{throw p.recordJoinChannelService({endTs:Date.now(),status:"error",errors:_h},_l),_h[0]},promisesCollector:j});return p.recordJoinChannelService({endTs:Date.now(),status:"success"},_l),_u};let $,Vt,_r;try{({gatewayInfo:$,proxyInfo:Vt,url:_r}=await cO([H(),z()]))}catch(Fi){throw Fi[0]}if(j.length&&j.forEach(Fi=>Fi.cancel&&typeof Fi.cancel=="function"&&Fi.cancel()),!$||!Vt)throw new hE(_p.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(l.apUrl=_r,l.cloudProxyServer!=="disabled"&&Array.isArray(g)&&_r){const Fi=/^https?:\/\/(.+?)(\/.*)?$/.exec(_r)[1];VE(g).call(g,Fi)&&(l.proxyServer=Fi,Gi.setProxyServer(Fi),jE.setProxyServer(Fi))}return A={gatewayInfo:$,proxyInfo:await get(Vt,$.uid)},A}async function b5(l,i,o,p){const g=nE("UAP_AP").slice(0,nE("AJAX_REQUEST_CONCURRENT")).map(b=>i.proxyServer?"https://".concat(i.proxyServer,"/ap/?url=").concat(b+"/api/v1?action=uap"):"https://".concat(b,"/api/v1?action=uap"));return await Tet(g,l,i,o,p)}async function wet(l,i,o){const p=nE("UAP_AP").slice(0,nE("AJAX_REQUEST_CONCURRENT")).map(g=>l.proxyServer?"https://".concat(l.proxyServer,"/ap/?url=").concat(g+"/api/v1?action=uap"):"https://".concat(g,"/api/v1?action=uap")).map(g=>function(b,A,j,H){const z={command:"convergeAllocateEdge",sid:A.sid,appId:A.appId,token:A.token,ts:Date.now(),version:qS,cname:A.cname,uid:A.uid.toString(),requestId:m2,seq:m2};m2+=1;const $={service_name:"tele_channel",json_body:JSON.stringify(z)};return vT(async()=>{const Vt=await nR(b,{data:$,cancelToken:j,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(Vt.code!==0){const Fi=new hE(_p.UNEXPECTED_RESPONSE,"cross channel ap error, code"+Vt.code,{retry:!0});throw Gi.error(Fi.toString()),Fi}const _r=JSON.parse(Vt.json_body);if(_r.code!==200){const Fi=new hE(_p.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(_r.code,", reason: ").concat(_r.reason));throw Gi.error(Fi.toString()),Fi}if(!_r.servers||_r.servers.length===0){const Fi=new hE(_p.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw Gi.error(Fi.toString()),Fi}return{vid:_r.vid,workerToken:_r.workerToken,addressList:(nE("CHANNEL_MEDIA_RELAY_SERVERS")||_r.servers).map(Fi=>"wss://".concat(Fi.address.replace(/\./g,"-"),".").concat(nE("WORKER_DOMAIN"),":").concat(Fi.wss))}},void 0,Vt=>!!(Vt.code!==_p.OPERATION_ABORTED&&Vt.code!==_p.UNEXPECTED_RESPONSE||Vt.data&&Vt.data.retry),H)}(g,l,i,o));try{const g=await cO(p);return p.forEach(b=>b.cancel()),g}catch(g){throw g[0]}}async function Aet(l,i,o){let p=null;const g=[],b=async A=>{const j=nE(A?"WEBCS_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN").map(H=>l.proxyServer?"https://".concat(l.proxyServer,"/ap/?url=").concat(H+"/api/v2/transpond/webrtc?v=2"):"https://".concat(H,"/api/v2/transpond/webrtc?v=2"));return A&&(await w0(1e3),p!==null)?p:await h1({fragementLength:nE("FRAGEMENT_LENGTH"),referenceList:j,asyncMapHandler:H=>(Gi.debug("[".concat(l.clientId,"] update ticket, Connect to ").concat(A?"backup":""," choose_server:"),H),function(z,$,Vt,_r){const[Fi]=Cet($,[v0.CHOOSE_SERVER]);let _l=X_.networkState;return vT(async()=>{_l&&X_.networkState===K0.OFFLINE&&X_.onlineWaiter&&await pE.race([X_.onlineWaiter,w0(_r&&_r.maxRetryTimeout||$_.maxRetryTimeout)]),_l=X_.networkState;const _u=await nR(z,{data:Fi,cancelToken:Vt,headers:{"Content-Type":"multipart/form-data;"}},!0);return Ret(_u,z)},()=>!1,_u=>_u.code!==_p.OPERATION_ABORTED&&(_u.code===_p.UPDATE_TICKET_FAILED?_u.data.retry:(Gi.warning("[".concat($.clientId,"] update ticket network error, retry"),_u),!0)),_r)}(H,l,i,o)),allFailedhandler:H=>{throw H[0]},promisesCollector:g})};try{return p=await cO([b(!1),b(!0)]),g.length&&g.forEach(A=>A.cancel&&typeof A.cancel=="function"&&A.cancel()),p}catch(A){throw A[0]}}function S5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function T5(l){for(var i=1;i{this.updateConfigDistribute()},nE("CONFIG_DISTRIBUTE_INTERVAL")))}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0}async awaitConfigDistributeComplete(){this.mutex.isLocked&&(await this.mutex.lock())()}async updateConfigDistribute(){if(this.mutableParamsRead||(this.mutableParamsRead=!0,jE.reportApiInvoke(null,{options:void 0,name:e0.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:x_.TRACER}).onSuccess(JSON.stringify(pR))),!this.joinInfo||!this.cancelToken||!this.retryConfig)return void Gi.debug("[config-distribute] get config distribute interrupted have no joininfo");let i;const o=await this.mutex.lock();try{i=await Iet(this.joinInfo,this.cancelToken,this.retryConfig),Gi.debug("[config-distribute] get config distribute",JSON.stringify(i)),i.limit_bitrate&&this.handleBitrateLimit(i.limit_bitrate),this.cacheGlobalParameterConfig(i),this.configs=i}catch(p){const g=new hE(_p.NETWORK_RESPONSE_ERROR,p);Gi.warning("[config-distribute] ".concat(g.toString()))}finally{o()}}getBitrateLimit(){return this.configs?this.configs.limit_bitrate:void 0}handleBitrateLimit(i){var o;(o=i)&&o.uplink&&o.id&&o.uplink.max_bitrate!==void 0&&o.uplink.min_bitrate!==void 0&&(this.configs&&this.configs.limit_bitrate?this.configs&&this.configs.limit_bitrate&&this.configs.limit_bitrate.id!==i.id&&this.emit(WO.UPDATE_BITRATE_LIMIT,i):this.emit(WO.UPDATE_BITRATE_LIMIT,i))}getLowStreamConfigDistribute(){return this.configs&&this.configs.limit_bitrate&&T5({},this.configs.limit_bitrate.low_stream_uplink)}cacheGlobalParameterConfig(i){var o;const p=AO(o=Object.keys(i).filter(b=>/^webrtc_ng_global_parameter/.test(b))).call(o);for(let b=0;bb;A--){const j=p[A];if(typeof i[j].__priority=="number"){const H=i[j].__priority,z=p[A-1];if(typeof i[z].__priority=="number"){if(!(H>i[z].__priority))continue;{const $=j;p[A]=p[A-1],p[A-1]=$}}else{const $=j;p[A]=p[A-1],p[A-1]=$}}}const g={};p.forEach(b=>{const A=i[b],j=A.__expires;Object.keys(A).forEach(H=>{H==="__priority"||H==="__expires"||Object.prototype.hasOwnProperty.call(g,H)||(g[H]=T5({value:A[H]},j&&{expires:j}))})});try{(function(j){try{const H=Date.now();Object.keys(j).forEach(z=>{switch(z){case"ENABLE_EVENT_REPORT":case"UPLOAD_LOG":if(Object.prototype.hasOwnProperty.call($0,z)){const{value:$,expires:Vt}=j[z];if(Vt&&Vt<=H)return;pR[z]=$,$0[z]=$,Gi.debug("Update global parameters from config distribute",z,$)}}})}catch(H){Gi.error("Error update config immediately: ".concat(j),H.message)}})(g);const b=JSON.stringify(g),A=window.btoa(b);window.localStorage.setItem("websdk_ng_global_parameter",A),Gi.debug("Caching global parameters ".concat(b))}catch(b){Gi.error("Error caching global parameters:",b.message)}}}function R5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function p1(l){for(var i=1;i{this.reconnectMode="retry",this.startPingPong()}),_e(this,"handleWebSocketMessage",b=>{if(!b.data)return;const A=JSON.parse(b.data);A.requestId?this.emit("@".concat(A.requestId,"-").concat(A.sid),A):this.serviceMode===o0.INJECT?this.emit(oT.INJECT_STREAM_STATUS,A):(jE.workerEvent(this.spec.sid,{actionType:"status",serverCode:A.code,workerType:this.serviceMode===o0.TRANSCODE?1:2}),this.emit(oT.PUBLISH_STREAM_STATUS,A))}),this.spec=o,this.token=i,this.serviceMode=g,this.websocket=new zO("live-streaming",p),this.websocket.on(zE.CONNECTED,this.handleWebSocketOpen),this.websocket.on(zE.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(zE.REQUEST_NEW_URLS,(b,A)=>{U_(this,oT.REQUEST_NEW_ADDRESS).then(b).catch(A)}),this.websocket.on(zE.RECONNECTING,()=>{this.websocket.reconnectMode=this.reconnectMode})}init(i){return this.websocket.init(i)}async request(i,o,p,g){this.reqId+=1,i==="request"&&(this.commandReqId+=1);const b=this.commandReqId,A=this.reqId;if(!A||!this.websocket)throw new hE(_p.UNEXPECTED_ERROR);const j=p1({command:i,sdkVersion:qS==="4.19.3"?"0.0.1":qS,seq:A,requestId:A,allocate:p,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},o);if(this.websocket.state==="closed")throw new hE(_p.WS_DISCONNECT);const H=()=>new pE((_r,Fi)=>{this.websocket.once(zE.CLOSED,()=>Fi(new hE(_p.WS_ABORT))),this.websocket.once(zE.CONNECTED,_r)});this.websocket.state!=="connected"&&await H(),j.clientRequest&&(j.clientRequest.workerToken=this.token);const z=new pE((_r,Fi)=>{const _l=()=>{Fi(new hE(_p.WS_ABORT))};this.websocket.once(zE.RECONNECTING,_l),this.websocket.once(zE.CLOSED,_l),this.once("@".concat(A,"-").concat(this.spec.sid),_u=>{_r(_u)})});g&&jE.workerEvent(this.spec.sid,p1(p1({},g),{},{requestId:b,actionType:"request",payload:JSON.stringify(o.clientRequest),serverCode:0,code:0}));const $=Date.now();this.websocket.sendMessage(j);let Vt=null;try{Vt=await z}catch(_r){if(this.websocket.state==="closed")throw _r;return await H(),await this.request(i,o,p)}return g&&jE.workerEvent(this.spec.sid,p1(p1({},g),{},{requestId:b,actionType:"response",payload:JSON.stringify(Vt.serverResponse),serverCode:Vt.code,success:Vt.code===200,responseTime:Date.now()-$})),Vt.code!==200&&this.handleResponseError(Vt),Vt}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){const i=qS==="4.19.3"?"0.0.1":qS;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:i,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(i){switch(i.code){case J_.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void Gi.warning("live stream response already exists stream");case J_.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case J_.LIVE_STREAM_RESPONSE_BAD_STREAM:case J_.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new hE(_p.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:i.code}).throw();case J_.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if(i.serverResponse.command==="UnpublishStream"||i.serverResponse.command==="UninjectStream")return;throw new hE(_p.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case J_.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new hE(_p.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:i.code}).throw();case J_.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const o=new hE(_p.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(oT.WARNING,o,i.serverResponse.url)}case J_.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const o=new hE(_p.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(oT.WARNING,o,i.serverResponse.url)}case J_.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new hE(_p.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case J_.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new hE(_p.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:i.code}).throw();case J_.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const o=new hE(_p.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(oT.WARNING,o,i.serverResponse.url)}case J_.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new hE(_p.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:i.code}).throw();case J_.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new hE(_p.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case J_.LIVE_STREAM_RESPONSE_WORKER_LOST:case J_.LIVE_STREAM_RESPONSE_WORKER_QUIT:if(i.serverResponse.command==="UnpublishStream"||i.serverResponse.command==="UninjectStream")return;throw new hE(_p.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case J_.ERROR_FAIL_SEND_MESSAGE:if(i.serverResponse.command==="UnpublishStream"||i.serverResponse.command==="UninjectStream")return;if(i.serverResponse.command==="UpdateTranscoding"||i.serverResponse.command==="ControlStream")return new hE(_p.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:i.code}).throw();throw new hE(_p.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case J_.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case J_.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case J_.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case J_.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new hE(_p.LIVE_STREAMING_CDN_ERROR,"",{code:i.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(()=>{this.websocket.state==="connected"&&this.request("ping",{}).catch(pN)},6e3)}}function C5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function nS(l){for(var i=1;i1&&arguments[1]!==void 0?arguments[1]:$_,p=arguments.length>2&&arguments[2]!==void 0?arguments[2]:$_;super(),_e(this,"onLiveStreamWarning",void 0),_e(this,"onLiveStreamError",void 0),_e(this,"onInjectStatusChange",void 0),_e(this,"spec",void 0),_e(this,"retryTimeout",1e4),_e(this,"connection",void 0),_e(this,"httpRetryConfig",void 0),_e(this,"wsRetryConfig",void 0),_e(this,"streamingTasks",new Map),_e(this,"isStartingStreamingTask",!1),_e(this,"taskMutex",new E0("live-streaming")),_e(this,"cancelToken",aS.CancelToken.source()),_e(this,"transcodingConfig",void 0),_e(this,"injectConfig",nS({},AZ)),_e(this,"injectLoopTimes",0),_e(this,"uapResponse",void 0),_e(this,"lastTaskId",1),_e(this,"statusError",new Map),this.spec=i,this.httpRetryConfig=p,this.wsRetryConfig=o}async setTranscodingConfig(i){const o=nS(nS({},wZ),i);o.videoCodecProfile!==66&&o.videoCodecProfile!==77&&o.videoCodecProfile!==100&&(Gi.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(o.videoCodecProfile," -> 100")),o.videoCodecProfile=100),o.transcodingUsers||(o.transcodingUsers=o.userConfigs),o.transcodingUsers&&(o.transcodingUsers=o.transcodingUsers.map(A=>nS(nS(nS({},IZ),A),{},{zOrder:A.zOrder?A.zOrder+1:1}))),function(A){M_(A.width)||b_(A.width,"config.width",0,1e4),M_(A.height)||b_(A.height,"config.height",0,1e4),M_(A.videoBitrate)||b_(A.videoBitrate,"config.videoBitrate",1,1e6),M_(A.videoFrameRate)||b_(A.videoFrameRate,"config.videoFrameRate"),M_(A.lowLatency)||QR(A.lowLatency,"config.lowLatency"),M_(A.audioSampleRate)||d0(A.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),M_(A.audioBitrate)||b_(A.audioBitrate,"config.audioBitrate",1,128),M_(A.audioChannels)||d0(A.audioChannels,"config.audioChannels",[1,2,3,4,5]),M_(A.videoGop)||b_(A.videoGop,"config.videoGop"),M_(A.videoCodecProfile)||d0(A.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),M_(A.userCount)||b_(A.userCount,"config.userCount",0,17),M_(A.backgroundColor)||b_(A.backgroundColor,"config.backgroundColor",0,16777215),M_(A.userConfigExtraInfo)||O0(A.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),A.transcodingUsers&&!M_(A.transcodingUsers)&&(KT(A.transcodingUsers,"config.transcodingUsers"),A.transcodingUsers.forEach((j,H)=>{fM(j.uid),M_(j.x)||b_(j.x,"transcodingUser[".concat(H,"].x"),0,1e4),M_(j.y)||b_(j.y,"transcodingUser[".concat(H,"].y"),0,1e4),M_(j.width)||b_(j.width,"transcodingUser[".concat(H,"].width"),0,1e4),M_(j.height)||b_(j.height,"transcodingUser[".concat(H,"].height"),0,1e4),M_(j.zOrder)||b_(j.zOrder-1,"transcodingUser[".concat(H,"].zOrder"),0,100),M_(j.alpha)||b_(j.alpha,"transcodingUser[".concat(H,"].alpha"),0,1,!1)})),M_(A.watermark)||gM(A.watermark,"watermark"),M_(A.backgroundImage)||gM(A.backgroundImage,"backgroundImage"),A.images&&!M_(A.images)&&(KT(A.images,"config.images"),A.images.forEach((j,H)=>{gM(j,"images[".concat(H,"]"))}))}(o);const p=[];o.images&&p.push(...o.images.map(A=>nS(nS(nS({},mM),A),{},{zOrder:255}))),o.backgroundImage&&(p.push(nS(nS(nS({},mM),o.backgroundImage),{},{zOrder:0})),delete o.backgroundImage),o.watermark&&(p.push(nS(nS(nS({},mM),o.watermark),{},{zOrder:255})),delete o.watermark),o.images=p,o.transcodingUsers&&(o.userConfigs=o.transcodingUsers.map(A=>nS({},A)),o.userCount=o.transcodingUsers.length,delete o.transcodingUsers);const g=(o.userConfigs||[]).map(A=>typeof A.uid=="number"?pE.resolve(A.uid):_5(A.uid,this.spec,this.cancelToken.token,this.httpRetryConfig));if((await pE.all(g)).forEach((A,j)=>{o.userConfigs&&o.userConfigs[j]&&(o.userConfigs[j].uid=A)}),this.transcodingConfig=o,this.connection)try{var b;const A=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(OT(b=this.streamingTasks).call(b)).map(j=>j.taskId).join("#")});Gi.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(A.code,", config:"),JSON.stringify(this.transcodingConfig))}catch(A){if(!A.data||!A.data.retry)throw A;A.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach(j=>{Gi.warning("[".concat(this.spec.clientId,"] live streaming receive error"),A.toString(),"try to republish",j.url),this.startLiveStreamingTask(j.url,j.mode,A).then(()=>{Gi.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(j.url," success"))}).catch(H=>{Gi.error("[".concat(this.spec.clientId,"] live streaming republish failed"),j.url,H.toString()),this.onLiveStreamError&&this.onLiveStreamError(j.url,H)})})}}setInjectStreamConfig(i,o){this.injectConfig=Object.assign({},this.injectConfig,i),this.injectLoopTimes=o}async startLiveStreamingTask(i,o,p){var g;if(Array.from(OT(g=this.streamingTasks).call(g)).find(H=>H.mode===o0.INJECT)&&o===o0.INJECT)return new hE(_p.LIVE_STREAMING_TASK_CONFLICT,"inject stream over limit").throw();if(!this.transcodingConfig&&o===o0.TRANSCODE)throw new hE(_p.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");let b={command:"PublishStream",ts:Date.now(),url:i,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};Gi.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(i,", mode: ").concat(o));const A=await this.taskMutex.lock();if(!this.connection&&p)return void A();if(this.streamingTasks.get(i)&&!p)return A(),new hE(_p.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(o))}catch(H){throw A(),H}switch(o){case o0.TRANSCODE:b.transcodingConfig=nS({},this.transcodingConfig);break;case o0.RAW:break;case o0.INJECT:b={cname:this.spec.cname,command:"InjectStream",sid:this.spec.sid,transcodingConfig:this.injectConfig,ts:Date.now(),url:i,loopTimes:this.injectLoopTimes}}this.uapResponse&&this.uapResponse.vid&&(b.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const j=this.lastTaskId++;try{const H=new pE(($,Vt)=>{w0(this.retryTimeout).then(()=>{if(p)return Vt(p);const _r=this.statusError.get(i);return _r?(this.statusError.delete(i),Vt(_r)):void 0})}),z=await pE.race([this.connection.request("request",{clientRequest:b},!0,{url:i,command:"PublishStream",workerType:o===o0.TRANSCODE?1:2,requestByUser:!p,tid:j.toString()}),H]);this.isStartingStreamingTask=!1,Gi.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(z.code)),this.streamingTasks.set(i,{clientRequest:b,mode:o,url:i,taskId:j}),A()}catch(H){if(A(),this.isStartingStreamingTask=!1,!H.data||!H.data.retry||p)throw H;return H.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(i,o,H)):await this.startLiveStreamingTask(i,o,H)}}stopLiveStreamingTask(i){return new pE((o,p)=>{const g=this.streamingTasks.get(i);if(!g||!this.connection)return new hE(_p.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const b=g.mode;g.abortTask=()=>{Gi.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(i),o()},this.connection.request("request",{clientRequest:{command:b===o0.INJECT?"UninjectStream":"UnpublishStream",url:g.url}},!1,{url:i,command:"UnPublishStream",workerType:b===o0.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then(A=>{Gi.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(A.code)),this.streamingTasks.delete(i),this.streamingTasks.size===0&&b!==o0.INJECT&&(this.connection&&this.connection.close(),this.connection=void 0),o(),b===o0.INJECT&&this.onInjectStatusChange&&this.onInjectStatusChange(mR.INJECT_STREAM_STATUS_STOP_SUCCESS,this.spec.uid,i)}).catch(p)})}async controlInjectStream(i,o,p,g){const b=this.streamingTasks.get(i);if(!b||!this.connection||b.mode!==o0.INJECT)throw new hE(_p.INVALID_OPERATION,"can not find inject stream task to control");return(await this.connection.request("request",{clientRequest:{command:"ControlStream",url:i,control:o,audioVolume:p,position:g}})).serverResponse}resetAllTask(){var i;const o=Array.from(OT(i=this.streamingTasks).call(i));this.terminate();for(const p of o)this.startLiveStreamingTask(p.url,p.mode).catch(g=>{this.onLiveStreamError&&this.onLiveStreamError(p.url,g)})}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=aS.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(i){if(this.connection)throw new hE(_p.UNEXPECTED_ERROR,"live streaming connection has already connected");const o=await U_(this,JI.REQUEST_WORKER_MANAGER_LIST,i);return this.uapResponse=o,this.connection=new Net(o.workerToken,this.spec,this.wsRetryConfig,i),this.connection.on(oT.WARNING,(p,g)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(g,p)),this.connection.on(oT.PUBLISH_STREAM_STATUS,p=>this.handlePublishStreamServer(p)),this.connection.on(oT.INJECT_STREAM_STATUS,p=>this.handleInjectStreamServerStatus(p)),this.connection.on(oT.REQUEST_NEW_ADDRESS,(p,g)=>{if(!this.connection)return g(new hE(_p.UNEXPECTED_ERROR,"can not get new live streaming address list"));U_(this,JI.REQUEST_WORKER_MANAGER_LIST,i).then(b=>{this.uapResponse=b,p(b.addressList)}).catch(g)}),await this.connection.init(o.addressList),this.connection}handlePublishStreamServer(i){const o=i.serverStatus&&i.serverStatus.url||"empty_url",p=this.streamingTasks.get(o),g=i.reason;switch(i.code){case J_.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case J_.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case J_.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case J_.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const A=new hE(_p.LIVE_STREAMING_CDN_ERROR,"",{code:i.code});if(p)return Gi.error(A.toString()),this.onLiveStreamError&&this.onLiveStreamError(o,A);if(!this.isStartingStreamingTask)return;this.statusError.set(o,A)}case J_.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const A=new hE(_p.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,g);return this.onLiveStreamWarning&&this.onLiveStreamWarning(o,A)}case J_.LIVE_STREAM_RESPONSE_WORKER_LOST:case J_.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var b;if(!this.connection)return;this.connection.tryNextAddress();const A=Array.from(OT(b=this.streamingTasks).call(b));for(const j of A)j.abortTask?j.abortTask():(Gi.warning("[".concat(this.spec.clientId,"] publish stream status code"),i.code,"try to republish",j.url),this.startLiveStreamingTask(j.url,j.mode,new hE(_p.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:i.code})).then(()=>{Gi.debug("[".concat(this.spec.clientId,"] republish live stream success"),j.url)}).catch(H=>{Gi.error(H.toString()),this.onLiveStreamError&&this.onLiveStreamError(j.url,H)}));return}}}handleInjectStreamServerStatus(i){const o=Number(i.uid),p=i.serverStatus&&i.serverStatus.url;switch(i.code){case 200:return void(this.onInjectStatusChange&&this.onInjectStatusChange(mR.INJECT_STREAM_STATUS_START_SUCCESS,o,p));case 451:return this.onInjectStatusChange&&this.onInjectStatusChange(mR.INJECT_STREAM_STATUS_START_ALREADY_EXISTS,o,p),void this.streamingTasks.delete(p);case 453:return this.onInjectStatusChange&&this.onInjectStatusChange(mR.INJECT_STREAM_STATUS_START_UNAUTHORIZED,o,p),void this.streamingTasks.delete(p);case 470:return this.onInjectStatusChange&&this.onInjectStatusChange(mR.INJECT_STREAM_STATUS_BROKEN,o,p),void this.streamingTasks.delete(p);case 499:return this.onInjectStatusChange&&this.onInjectStatusChange(mR.INJECT_STREAM_STATUS_START_TIMEOUT,o,p),void this.streamingTasks.delete(p);default:return void Gi.debug("inject stream server status",i)}}hasUrl(i){return this.streamingTasks.has(i)}}class uP{constructor(){_e(this,"destChannelMediaInfos",new Map),_e(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(i){m6(i),this.srcChannelMediaInfo=i}addDestChannelInfo(i){m6(i),this.destChannelMediaInfos.set(i.channelName,i)}removeDestChannelInfo(i){pM(i),this.destChannelMediaInfos.delete(i)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function I5(l){if(!(l instanceof uP))return new hE(_p.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw();const i=l.getSrcChannelMediaInfo(),o=l.getDestChannelMediaInfo();if(!i)return new hE(_p.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw();if(o.size===0)return new hE(_p.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}class ket extends D_{constructor(i,o,p){super(),_e(this,"ws",void 0),_e(this,"requestId",1),_e(this,"heartBeatTimer",void 0),_e(this,"joinInfo",void 0),_e(this,"clientId",void 0),_e(this,"onOpen",()=>{this.emit("open"),this.startHeartBeatCheck()}),_e(this,"onClose",g=>{this.emit("close"),this.dispose()}),_e(this,"onMessage",g=>{const b=JSON.parse(g.data);if(!b||b.command!=="serverResponse"||!b.requestId)return b&&b.command==="serverStatus"&&b.serverStatus&&b.serverStatus.command?(this.emit("status",b.serverStatus),void this.emit(b.serverStatus.command,b.serverStatus)):void 0;this.emit("req_".concat(b.requestId),b)}),this.joinInfo=i,this.clientId=o,this.ws=new zO("cross-channel-".concat(this.clientId),p),this.ws.on(zE.RECONNECTING,()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")}),this.ws.on(zE.CONNECTED,this.onOpen),this.ws.on(zE.ON_MESSAGE,this.onMessage),this.ws.on(zE.CLOSED,this.onClose)}isConnect(){return this.ws.state==="connected"}sendMessage(i){const o=this.requestId++;return i.requestId=o,i.seq=o,this.ws.sendMessage(i),o}waitStatus(i){return new pE((o,p)=>{const g=window.setTimeout(()=>{p(new hE(_p.TIMEOUT,"wait status timeout, status: ".concat(i)))},5e3);this.once(i,b=>{window.clearTimeout(g),b.state&&b.state!==0?p(new hE(_p.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(i))):o(void 0)}),this.once("dispose",()=>{window.clearTimeout(g),p(new hE(_p.WS_ABORT))})})}async request(i){if(this.ws.state==="closed")throw new hE(_p.WS_DISCONNECT);const o=()=>new pE((A,j)=>{this.ws.once(zE.CLOSED,()=>j(new hE(_p.WS_ABORT))),this.ws.once(zE.CONNECTED,A)});this.ws.state!=="connected"&&await o();const p=this.sendMessage(i),g=new pE((A,j)=>{const H=()=>{j(new hE(_p.WS_ABORT))};this.ws.once(zE.RECONNECTING,H),this.ws.once(zE.CLOSED,H),this.once("req_".concat(p),A),w0(3e3).then(()=>{this.removeAllListeners("req_".concat(p)),this.ws.off(zE.RECONNECTING,H),this.ws.off(zE.CLOSED,H),j(new hE(_p.TIMEOUT,"cross channel ws request timeout"))})}),b=await g;if(!b||b.code!==200)throw new hE(_p.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(b)));return b}async connect(i){this.ws.removeAllListeners(zE.REQUEST_NEW_URLS),this.ws.on(zE.REQUEST_NEW_URLS,o=>{o(i)}),await this.ws.init(i)}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(i){const o=this.requestId++;return i.requestId=o,this.ws.sendMessage(i),o}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 Det extends D_{set state(i){i!==this._state&&(i!==Z0.RELAY_STATE_FAILURE&&(this.errorCode=gR.RELAY_OK),this.emit("state",i,this.errorCode),this._state=i)}get state(){return this._state}constructor(i,o,p,g,b){super(),_e(this,"joinInfo",void 0),_e(this,"sid",void 0),_e(this,"clientId",void 0),_e(this,"cancelToken",aS.CancelToken.source()),_e(this,"workerToken",void 0),_e(this,"requestId",0),_e(this,"signal",void 0),_e(this,"prevChannelMediaConfig",void 0),_e(this,"httpRetryConfig",void 0),_e(this,"_resolution",void 0),_e(this,"_state",Z0.RELAY_STATE_IDLE),_e(this,"errorCode",gR.RELAY_OK),_e(this,"onStatus",A=>{Gi.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(A))),A&&A.command&&(A.command==="onAudioPacketReceived"&&this.emit("event",_T.PACKET_RECEIVED_AUDIO_FROM_SRC),A.command==="onVideoPacketReceived"&&this.emit("event",_T.PACKET_RECEIVED_VIDEO_FROM_SRC),A.command==="onSrcTokenPrivilegeDidExpire"&&(this.errorCode=gR.SRC_TOKEN_EXPIRED,this.state=Z0.RELAY_STATE_FAILURE),A.command==="onDestTokenPrivilegeDidExpire"&&(this.errorCode=gR.DEST_TOKEN_EXPIRED,this.state=Z0.RELAY_STATE_FAILURE))}),_e(this,"onReconnect",async()=>{Gi.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",_T.NETWORK_DISCONNECTED),this.state=Z0.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch(A=>{this.state!==Z0.RELAY_STATE_IDLE&&(Gi.error("auto restart channel media relay failed",A.toString()),this.errorCode=gR.SERVER_CONNECTION_LOST,this.state=Z0.RELAY_STATE_FAILURE)})}),this.joinInfo=i,this.clientId=o,this.sid=BL(),this.signal=new ket(this.joinInfo,this.clientId,p),this.httpRetryConfig=g,this._resolution=b}async startChannelMediaRelay(i){if(this.state!==Z0.RELAY_STATE_IDLE)throw new hE(_p.INVALID_OPERATION);this.state=Z0.RELAY_STATE_CONNECTING,await this.connect(),Gi.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(i)}catch(o){throw o.data&&o.data.serverResponse&&o.data.serverResponse.command==="SetSourceChannel"?new hE(_p.CROSS_CHANNEL_FAILED_JOIN_SRC):o.data&&o.data.serverResponse&&o.serverResponse.command==="SetDestChannelStatus"?new hE(_p.CROSS_CHANNEL_FAILED_JOIN_DEST):o.data&&o.data.serverResponse&&o.serverResponse.command==="StartPacketTransfer"?new hE(_p.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST):o}this.prevChannelMediaConfig=i}async updateChannelMediaRelay(i){if(this.state!==Z0.RELAY_STATE_RUNNING)throw new hE(_p.INVALID_OPERATION);await this.sendUpdateMessage(i),this.prevChannelMediaConfig=i}async setVideoProfile(i){if(this._resolution=i,this.state!==Z0.RELAY_STATE_RUNNING)throw new hE(_p.INVALID_OPERATION);const o=this.genMessage(j0.SetVideoProfile);await this.signal.request(o),Gi.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),Gi.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=Z0.RELAY_STATE_IDLE,this.dispose()}dispose(){Gi.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=aS.CancelToken.source(),this.state=Z0.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const i=await wet(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=i.workerToken,await this.signal.connect(i.addressList),this.emit("event",_T.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(i){const o=this.genMessage(j0.StopPacketTransfer);await this.signal.request(o),await this.signal.waitStatus("Normal Quit"),Gi.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const p=this.genMessage(j0.SetSdkProfile,i);await this.signal.request(p),Gi.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const g=this.genMessage(j0.SetSourceChannel,i);await this.signal.request(g),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",_T.PACKET_JOINED_SRC_CHANNEL),Gi.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const b=this.genMessage(j0.SetSourceUserId,i);await this.signal.request(b),Gi.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const A=this.genMessage(j0.SetDestChannel,i);await this.signal.request(A),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",_T.PACKET_JOINED_DEST_CHANNEL),Gi.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const j=this.genMessage(j0.StartPacketTransfer,i);await this.signal.request(j),this.emit("event",_T.PACKET_SENT_TO_DEST_CHANNEL),this.state=Z0.RELAY_STATE_RUNNING,Gi.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(i){const o=this.genMessage(j0.UpdateDestChannel,i);await this.signal.request(o),this.emit("event",_T.PACKET_UPDATE_DEST_CHANNEL),Gi.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const i=this.genMessage(j0.StopPacketTransfer);await this.signal.request(i),Gi.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(i,o){const p=[],g=[],b=[];this.requestId+=1;const A={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:qS,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};A.sdkVersion==="4.19.3"&&(A.sdkVersion="0.0.1");let j=null,H=null;switch(i){case j0.SetSdkProfile:return A.clientRequest={command:"SetSdkProfile",type:"multi_channel"},A;case j0.SetSourceChannel:if(H=o&&o.getSrcChannelMediaInfo(),!H)throw new hE(_p.UNEXPECTED_ERROR,"can not find source config");return A.clientRequest={command:"SetSourceChannel",uid:"0",channelName:H.channelName,token:H.token||this.joinInfo.appId},A;case j0.SetSourceUserId:if(H=o&&o.getSrcChannelMediaInfo(),!H)throw new hE(_p.UNEXPECTED_ERROR,"can not find source config");return A.clientRequest={command:"SetSourceUserId",uid:H.uid+""},A;case j0.SetDestChannel:if(j=o&&o.getDestChannelMediaInfo(),!j)throw new hE(_p.UNEXPECTED_ERROR,"can not find dest config");return j.forEach(z=>{p.push(z.channelName),g.push(z.uid+""),b.push(z.token||this.joinInfo.appId)}),A.clientRequest={command:"SetDestChannel",channelName:p,uid:g,token:b},A;case j0.StartPacketTransfer:return A.clientRequest={command:"StartPacketTransfer"},A;case j0.Reconnect:return A.clientRequest={command:"Reconnect"},A;case j0.StopPacketTransfer:return A.clientRequest={command:"StopPacketTransfer"},A;case j0.UpdateDestChannel:if(j=o&&o.getDestChannelMediaInfo(),!j)throw new hE(_p.UNEXPECTED_ERROR,"can not find dest config");return j.forEach(z=>{p.push(z.channelName),g.push(z.uid+""),b.push(z.token||this.joinInfo.appId)}),A.clientRequest={command:"UpdateDestChannel",channelName:p,uid:g,token:b},A;case j0.SetVideoProfile:A.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return A}}class D0{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)return this._audioTrack}get videoTrack(){if(this.hasVideo)return this._videoTrack}get dataChannels(){return this._dataChannels}constructor(i,o){_e(this,"uid",void 0),_e(this,"_uintid",void 0),_e(this,"_trust_in_room_",!0),_e(this,"_trust_audio_enabled_state_",!0),_e(this,"_trust_video_enabled_state_",!0),_e(this,"_trust_audio_mute_state_",!0),_e(this,"_trust_video_mute_state_",!0),_e(this,"_audio_muted_",!1),_e(this,"_video_muted_",!1),_e(this,"_audio_enabled_",!0),_e(this,"_video_enabled_",!0),_e(this,"_audio_added_",!1),_e(this,"_video_added_",!1),_e(this,"_trust_video_stream_added_state_",!0),_e(this,"_trust_audio_stream_added_state_",!0),_e(this,"_audioTrack",void 0),_e(this,"_videoTrack",void 0),_e(this,"_dataChannels",[]),_e(this,"_audioSSRC",void 0),_e(this,"_videoSSRC",void 0),_e(this,"_audioOrtc",void 0),_e(this,"_videoOrtc",void 0),_e(this,"_cname",void 0),_e(this,"_rtxSsrcId",void 0),this.uid=i,this._uintid=o}}var Let=UV,xet=CT;Y_({target:"Promise",stat:!0,forced:!0},{withResolvers:function(){var l=xet.f(this);return{promise:l.promise,resolve:l.resolve,reject:l.reject}}});var Met=CT,Uet=xI;Y_({target:"Promise",stat:!0,forced:!0},{try:function(l){var i=Met.f(this),o=Uet(l);return(o.error?i.reject:i.resolve)(o.value),i.promise}});var E2=LE(Let),w5=CI.f("asyncIterator"),Fet=LE(w5);function v2(l,i){this.v=l,this.k=i}function f1(l){var i,o;function p(b,A){try{var j=l[b](A),H=j.value,z=H instanceof v2;E2.resolve(z?H.v:H).then(function($){if(z){var Vt=b==="return"?"return":"next";if(!H.k||$.done)return p(Vt,$);$=l[Vt]($).value}g(j.done?"return":"normal",$)},function($){p("throw",$)})}catch($){g("throw",$)}}function g(b,A){switch(b){case"return":i.resolve({value:A,done:!0});break;case"throw":i.reject(A);break;default:i.resolve({value:A,done:!1})}(i=i.next)?p(i.key,i.arg):o=null}this._invoke=function(b,A){return new E2(function(j,H){var z={key:b,arg:A,resolve:j,reject:H,next:null};o?o=o.next=z:(i=o=z,p(b,A))})},typeof l.return!="function"&&(this.return=void 0)}function JS(l){return function(){return new f1(l.apply(this,arguments))}}function d_(l){return new v2(l,0)}function lP(l){var i={},o=!1;function p(g,b){return o=!0,{done:!1,value:new v2(b=new E2(function(A){A(l[g](b))}),1)}}return i[PI!==void 0&&y3||"@@iterator"]=function(){return this},i.next=function(g){return o?(o=!1,g):p("next",g)},typeof l.throw=="function"&&(i.throw=function(g){if(o)throw o=!1,g;return p("throw",g)}),typeof l.return=="function"&&(i.return=function(g){return o?(o=!1,g):p("return",g)}),i}f1.prototype[typeof PI=="function"&&Fet||"@@asyncIterator"]=function(){return this},f1.prototype.next=function(l){return this._invoke("next",l)},f1.prototype.throw=function(l){return this._invoke("throw",l)},f1.prototype.return=function(l){return this._invoke("return",l)};var A5=LE(w5),O5={exports:{}};(function(l,i){l.exports=(()=>{var o={8:(b,A,j)=>{j.r(A),j.d(A,{Parser:()=>$E,Printer:()=>yS,parse:()=>YE,print:()=>h_});const H=` +`,z="".concat("\r").concat(H),$=" ";let Vt;function _r(NE){return NE>="0"&&NE<="9"}function Fi(NE){return NE>="!"&&NE<="~"}function _l(NE){return Fi(NE)||NE>="€"&&NE<="ÿ"}function _u(NE){return NE==="!"||NE>="#"&&NE<="'"||NE>="*"&&NE<="+"||NE>="-"&&NE<="."||NE>="0"&&NE<="9"||NE>="A"&&NE<="Z"||NE>="^"&&NE<="~"}function _h(NE){return NE>="1"&&NE<="9"}function _g(NE){return NE>="A"&&NE<="Z"||NE>="a"&&NE<="z"}function eE(NE){return NE==="d"||NE==="h"||NE==="m"||NE==="s"}function oE(NE){return NE>""&&NE<" "||NE>"\v"&&NE<"\f"||NE>""&&NE<"ÿ"}function SE(NE){return _g(NE)||_r(NE)||NE==="+"||NE==="/"}function vE(NE){return _r(NE)||_g(NE)||NE==="+"||NE==="/"||NE==="-"||NE==="_"}function fE(NE){return _g(NE)||_r(NE)||NE==="+"||NE==="/"}function mE(NE,ga){var Eg=Object.keys(NE);if(Object.getOwnPropertySymbols){var sE=Object.getOwnPropertySymbols(NE);ga&&(sE=sE.filter(function(wE){return Object.getOwnPropertyDescriptor(NE,wE).enumerable})),Eg.push.apply(Eg,sE)}return Eg}function EE(NE){for(var ga=1;ga=0&&wE<=255)return sE;throw new Error("Invalid decimal uchar")}consumeIP6Address(ga,Eg){let sE=this.consumeHexpart(ga,Eg);return ga[sE]===":"&&(sE+=1,sE=this.consumeIP4Address(ga,sE)),sE}consumeHexpart(ga,Eg){let sE=Eg;if(ga[sE]===":"&&ga[sE+1]===":"){sE+=2;try{sE=this.consumeHexseq(ga,sE)}catch{}return sE}if(sE=this.consumeHexseq(ga,sE),ga[sE]===":"&&ga[sE+1]===":"){sE+=2;try{sE=this.consumeHexseq(ga,sE)}catch{}return sE}return sE}consumeHexseq(ga,Eg){let sE=Eg;for(;sE=this.consumeHex4(ga,sE),ga[sE]===":"&&ga[sE+1]!==":";)sE+=1;return sE}consumeHex4(ga,Eg){let sE=0;for(;sE<4;sE++)if(!((wE=ga[Eg+sE])>="0"&&wE<="9"||wE>="a"&&wE<="f"||wE>="A"&&wE<="F")){if(sE===0)throw new Error("Invalid hex 4");break}var wE;return Eg+sE}consumeFQDN(ga,Eg){let sE=Eg;for(;_r(ga[sE])||_g(ga[sE])||ga[sE]==="-"||ga[sE]===".";)sE+=1;if(sE-Eg<4)throw new Error("Invalid FQDN");return sE}consumeExtnAddr(ga,Eg){return this.consumeOneOrMore(ga,Eg,_l)}consumeMulticastAddress(ga,Eg,sE){switch(sE){case"IP4":case"ip4":return this.consumeIP4MulticastAddress(ga,Eg);case"IP6":case"ip6":return this.consumeIP6MulticastAddress(ga,Eg);default:try{return this.consumeFQDN(ga,Eg)}catch{return this.consumeExtnAddr(ga,Eg)}}}consumeIP6MulticastAddress(ga,Eg){const sE=this.consumeHexpart(ga,Eg);return ga[sE]==="/"?this.consumeInteger(ga,sE+1):sE}consumeIP4MulticastAddress(ga,Eg){let sE=Eg+3;const wE=ga.slice(Eg,sE),XE=parseInt(wE);if(XE<224||XE>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 O_=0;O_<3;O_++){if(ga[sE]!==".")throw new Error("Invalid IP4 multicast address.");sE+=1,sE=this.consumeDecimalUChar(ga,sE)}return ga[sE]==="/"&&(sE+=1),sE=this.consumeTTL(ga,sE),ga[sE]==="/"&&(sE=this.consumeInteger(ga,sE)),sE}consumeInteger(ga,Eg){if(!_h(ga[Eg]))throw new Error("Invalid integer.");for(Eg+=1;_r(ga[Eg]);)Eg+=1;return Eg}consumeTTL(ga,Eg){if(ga[Eg]==="0")return Eg+1;if(!_h(ga[Eg]))throw new Error("Invalid TTL.");Eg+=1;for(let sE=0;sE<2&&_r(ga[Eg]);sE++)Eg+=1;return Eg}consumeToken(ga,Eg){return this.consumeOneOrMore(ga,Eg,_u)}consumeTime(ga,Eg){let sE=Eg;if(ga[sE]==="0")return sE+1;for(_h(ga[sE])&&(sE+=1);_r(ga[sE]);)sE++;if(sE-Eg<10)throw new Error("Invalid time");return sE}consumeAddress(ga,Eg){return this.consumeTill(ga,Eg,$)}consumeTypedTime(ga,Eg){let sE=Eg;return sE=this.consumeOneOrMore(ga,sE,_r),eE(ga[sE])?sE+1:sE}consumeRepeatInterval(ga,Eg){if(!_h(ga[Eg]))throw new Error("Invalid repeat interval");for(Eg+=1;_r(ga[Eg]);)Eg+=1;return eE(ga[Eg])&&(Eg+=1),Eg}consumePort(ga,Eg){return this.consumeOneOrMore(ga,Eg,_r)}consume(ga,Eg,sE){for(let wE=0;wE=ga.length)throw new Error("consume exceeding value length");if(ga[Eg+wE]!==sE[wE])throw new Error("consume ".concat(sE," failed at ").concat(wE))}return Eg+sE.length}consumeTill(ga,Eg,sE){let wE=Eg;for(;wE!!i0.trim()).map(this.parseLine),this.currentLine=0;const sE=this.parseVersion(),wE=this.parseOrigin(),XE=this.parseSessionName(),O_=this.parseInformation(),x0=this.parseUri(),bS=this.parseEmail(),rR=this.parsePhone(),IP=this.parseConnection(),wP=this.parseBandWidth(),tT=this.parseTimeFields(),LR=this.parseKey(),fO=this.parseSessionAttribute(),z_=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error("parsing failed, non exhaustive sdp lines.");return{version:sE,origin:wE,sessionName:XE,information:O_,uri:x0,emails:bS,phones:rR,connection:IP,bandwidths:wP,timeFields:tT,key:LR,attributes:fO,mediaDescriptions:z_}}getCurrentRecord(){const ga=this.records[this.currentLine];if(!ga)throw new Error("Record doesn't exit.");return ga}probeEOL(ga){for(let Eg=0;Eg=.");const sE=ga[0];if(ga[1]!=="=")throw new Error('Invalid sdp line, should be a single character followed by an "=" sign.');return{type:sE,value:ga.slice(2),line:Eg,cur:0}}parseSessionAttribute(){const ga=new B_;for(;this.currentLine_u(wE)&&wE!==":"),_cur:0};Eg.value[Eg.cur]===":"&&(Eg.cur+=1,sE.attValue=this.extractOneOrMore(Eg,oE)),ga.parse(sE),this.currentLine++}return ga.digest()}parseMediaAttributes(ga){const Eg=new r0(ga);for(;this.currentLine_u(XE)&&XE!==":"),_cur:0};sE.value[sE.cur]===":"&&(sE.cur+=1,wE.attValue=this.extractOneOrMore(sE,oE)),Eg.parse(wE),this.currentLine++}return Eg.digest()}parseKey(){const ga=this.getCurrentRecord();if(ga.type===Vt.KEY){if(ga.value==="prompt"||ga.value==="clear:"||ga.value==="base64:"||ga.value==="uri:")return ga.value;throw this.currentLine++,new Error("Invalid key.")}}parseZone(){const ga=this.getCurrentRecord();if(ga.type===Vt.ZONE_ADJUSTMENTS){const Eg=[];for(;;)try{const sE=this.extract(ga,this.consumeTime);this.consumeSpaceForRecord(ga);let wE=!1;ga.value[ga.cur]==="-"&&(wE=!0,ga.cur+=1);const XE=this.extract(ga,this.consumeTypedTime);Eg.push({time:sE,typedTime:XE,back:wE})}catch{break}if(Eg.length===0)throw new Error("Invalid zone adjustments");return this.currentLine++,Eg}return[]}parseRepeat(){const ga=[];for(;;){const Eg=this.getCurrentRecord();if(Eg.type!==Vt.REPEAT)break;{const sE=this.extract(Eg,this.consumeRepeatInterval),wE=this.parseTypedTime(Eg);ga.push({repeatInterval:sE,typedTimes:wE}),this.currentLine++}}return ga}parseTypedTime(ga){const Eg=[];for(;;)try{this.consumeSpaceForRecord(ga),Eg.push(this.extract(ga,this.consumeTypedTime))}catch{break}if(Eg.length===0)throw new Error("Invalid typed time.");return Eg}parseTime(){const ga=this.getCurrentRecord(),Eg=this.extract(ga,this.consumeTime);this.consumeSpaceForRecord(ga);const sE=this.extract(ga,this.consumeTime);return this.currentLine++,{startTime:Eg,stopTime:sE}}parseBandWidth(){const ga=[];for(;this.currentLinex0)throw new Error("error in length, should be less or equal than ".concat(x0," characters."));return ga._cur=wE,XE}consumeAttributeSpace(ga){if(ga.attValue[ga._cur]!==$)throw new Error("Invalid space at ".concat(ga._cur,"."));ga._cur+=1}extract(ga,Eg,...sE){if(!ga.attValue)throw new Error("Nothing to extract from attValue.");const wE=Eg.call(this,ga.attValue,ga._cur,...sE),XE=ga.attValue.slice(ga._cur,wE);return ga._cur=wE,XE}atEnd(ga){if(!ga.attValue)throw new Error;return ga._cur>=ga.attValue.length}peekChar(ga){if(!ga.attValue)throw new Error;return ga.attValue[ga._cur]}peek(ga,Eg){if(!ga.attValue)throw new Error;for(let sE=0;sEO_!==$&&oE(O_));sE.push({name:wE,value:XE})}this.attributes.identities.push({assertionValue:Eg,extensions:sE})}parseMsidSemantic(ga){this.peekChar(ga)===$&&this.consumeAttributeSpace(ga);const Eg={semantic:this.extract(ga,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(ga)}catch{break}if(this.peekChar(ga)==="*"){this.extract(ga,this.consume,"*"),Eg.applyForAll=!0;break}{const sE=this.extract(ga,this.consumeTill,$);Eg.identifierList.push(sE)}}this.attributes.msidSemantic=Eg}}class r0 extends s_{constructor(ga){super(),PE(this,"attributes",void 0),ga.protos.indexOf("RTP")!==-1||ga.protos.indexOf("rtp"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]}}parse(ga){if(this.digested)throw new Error("already digested");try{switch(ga.attField){case"extmap":this.parseExtmap(ga);break;case"setup":this.parseSetup(ga);break;case"ice-ufrag":this.parseIceUfrag(ga);break;case"ice-pwd":this.parseIcePwd(ga);break;case"ice-options":this.parseIceOptions(ga);break;case"candidate":this.parseCandidate(ga);break;case"remote-candidate":this.parseRemoteCandidate(ga);break;case"end-of-candidates":this.parseEndOfCandidates();break;case"fingerprint":this.parseFingerprint(ga);break;case"rtpmap":this.parseRtpmap(ga);break;case"ptime":this.parsePtime(ga);break;case"maxptime":this.parseMaxPtime(ga);break;case"sendrecv":case"recvonly":case"sendonly":case"inactive":this.parseDirection(ga);break;case"ssrc":this.parseSSRC(ga);break;case"fmtp":this.parseFmtp(ga);break;case"rtcp-fb":this.parseRtcpFb(ga);break;case"rtcp-mux":this.parseRTCPMux();break;case"rtcp-mux-only":this.parseRTCPMuxOnly();break;case"rtcp-rsize":this.parseRTCPRsize();break;case"rtcp":this.parseRTCP(ga);break;case"mid":this.parseMid(ga);break;case"msid":this.parseMsid(ga);break;case"imageattr":this.parseImageAttr(ga);break;case"rid":this.parseRid(ga);break;case"simulcast":this.parseSimulcast(ga);break;case"sctp-port":this.parseSctpPort(ga);break;case"max-message-size":this.parseMaxMessageSize(ga);break;case"ssrc-group":this.parseSSRCGroup(ga);break;default:ga.ignored=!0,this.attributes.unrecognized.push(ga)}}catch(Eg){throw console.error("parsing media attribute ".concat(ga.attField,' error, "a=').concat(ga.attField,":").concat(ga.attValue,'"')),Eg}if(!ga.ignored&&ga.attValue&&!this.atEnd(ga))throw new Error("attribute parsing error")}parseCandidate(ga){const Eg=this.extractOneOrMore(ga,SE,[1,32]);this.consumeAttributeSpace(ga);const sE=this.extractOneOrMore(ga,_r,[1,5]);this.consumeAttributeSpace(ga);const wE=this.extract(ga,this.consumeToken);this.consumeAttributeSpace(ga);const XE=this.extractOneOrMore(ga,_r,[1,10]);this.consumeAttributeSpace(ga);const O_=this.extract(ga,this.consumeAddress);this.consumeAttributeSpace(ga);const x0=this.extract(ga,this.consumePort);this.consumeAttributeSpace(ga),this.extract(ga,this.consume,"typ"),this.consumeAttributeSpace(ga);const bS={foundation:Eg,componentId:sE,transport:wE,priority:XE,connectionAddress:O_,port:x0,type:this.extract(ga,this.consumeToken),extension:{}};for(this.peek(ga," raddr")&&(this.extract(ga,this.consume," raddr"),this.consumeAttributeSpace(ga),bS.relAddr=this.extract(ga,this.consumeAddress)),this.peek(ga," rport")&&(this.extract(ga,this.consume," rport"),this.consumeAttributeSpace(ga),bS.relPort=this.extract(ga,this.consumePort));this.peekChar(ga)===$;){this.consumeAttributeSpace(ga);const rR=this.extract(ga,this.consumeToken);this.consumeAttributeSpace(ga),bS.extension[rR]=this.extractOneOrMore(ga,Fi)}this.attributes.candidates.push(bS)}parseRemoteCandidate(ga){const Eg=[];for(;;){const sE=this.extractOneOrMore(ga,_r,[1,5]);this.consumeAttributeSpace(ga);const wE=this.extract(ga,this.consumeAddress);this.consumeAttributeSpace(ga);const XE=this.extract(ga,this.consumePort);Eg.push({componentId:sE,connectionAddress:wE,port:XE});try{this.consumeAttributeSpace(ga)}catch{break}}this.attributes.remoteCandidatesList.push(Eg)}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error("must be only one line of end-of-candidates");this.attributes.endOfCandidates=!0}parseRtpmap(ga){const Eg=this.extract(ga,this.consumeToken);this.consumeAttributeSpace(ga);const sE=this.extract(ga,this.consumeTill,"/");this.extract(ga,this.consume,"/");const wE={encodingName:sE,clockRate:this.extractOneOrMore(ga,_r)};this.atEnd(ga)||this.peekChar(ga)!=="/"||(this.extract(ga,this.consume,"/"),wE.encodingParameters=parseInt(this.extract(ga,this.consumeTill),10));const XE=this.attributes.payloads.find(O_=>O_.payloadType===parseInt(Eg,10));XE?XE.rtpMap=wE:this.attributes.payloads.push({payloadType:parseInt(Eg,10),rtpMap:wE,rtcpFeedbacks:[]})}parsePtime(ga){if(this.attributes.ptime)throw new Error("must be only one line of ptime");this.attributes.ptime=this.extract(ga,this.consumeTill)}parseMaxPtime(ga){if(this.attributes.maxPtime)throw new Error("must be only one line of ptime");this.attributes.maxPtime=this.extract(ga,this.consumeTill)}parseDirection(ga){if(this.attributes.direction)throw new Error("must be only one line of direction info");this.attributes.direction=ga.attField}parseSSRC(ga){const Eg=this.extractOneOrMore(ga,_r);this.consumeAttributeSpace(ga);const sE=this.extract(ga,this.consumeTill,":");let wE;this.peekChar(ga)===":"&&(this.extract(ga,this.consume,":"),wE=this.extract(ga,this.consumeTill));const XE=this.attributes.ssrcs.find(O_=>O_.ssrcId===parseInt(Eg,10));XE?XE.attributes[sE]=wE:this.attributes.ssrcs.push({ssrcId:parseInt(Eg,10),attributes:{[sE]:wE}})}parseFmtp(ga){const Eg=this.extract(ga,this.consumeTill,$);this.consumeAttributeSpace(ga);const sE=this.extract(ga,this.consumeTill),wE={};sE.split(";").forEach(O_=>{let[x0,bS]=O_.split("=");x0=x0.trim();const rR=typeof bS=="string"?bS.trim():null;typeof x0=="string"&&x0.length>0&&(wE[x0]=rR)});const XE=this.attributes.payloads.find(O_=>O_.payloadType===parseInt(Eg,10));XE?XE.fmtp={parameters:wE}:this.attributes.payloads.push({payloadType:parseInt(Eg,10),rtcpFeedbacks:[],fmtp:{parameters:wE}})}parseFmtParameters(ga){const Eg={},sE=this.extract(ga,this.consumeTill,"=");ga._cur++;const wE=this.extract(ga,this.consumeTill,";");for(Eg[sE]=wE;ga.attValue[ga._cur]===";";){const XE=this.extract(ga,this.consumeTill,"=");ga._cur++;const O_=this.extract(ga,this.consumeTill,";");Eg[XE]=O_}return Eg}parseRtcpFb(ga){let Eg="";Eg=this.peekChar(ga)==="*"?this.extract(ga,this.consume,"*"):this.extract(ga,this.consumeTill,$),this.consumeAttributeSpace(ga);const sE=this.extract(ga,this.consumeTill,$);let wE;if(sE==="trr-int")wE={type:sE,interval:this.extract(ga,this.consumeTill)};else{const XE={type:sE};this.peekChar(ga)===$&&(this.consumeAttributeSpace(ga),XE.parameter=this.extract(ga,this.consumeToken),this.peekChar(ga)===$&&(XE.additional=this.extract(ga,this.consumeTill))),wE=XE}if(Eg==="*")this.attributes.rtcpFeedbackWildcards.push(wE);else{const XE=this.attributes.payloads.find(O_=>O_.payloadType===parseInt(Eg,10));XE?XE.rtcpFeedbacks.push(wE):this.attributes.payloads.push({payloadType:parseInt(Eg,10),rtcpFeedbacks:[wE]})}}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(ga){if(this.attributes.rtcp)throw new Error("must be single line of rtcp");const Eg={port:this.extract(ga,this.consumePort)};this.peekChar(ga)===$&&(this.consumeAttributeSpace(ga),Eg.netType=this.extractOneOrMore(ga,_u),this.consumeAttributeSpace(ga),Eg.addressType=this.extractOneOrMore(ga,_u),this.consumeAttributeSpace(ga),Eg.address=this.extract(ga,this.consumeAddress)),this.attributes.rtcp=Eg}parseMsid(ga){const Eg={id:this.extractOneOrMore(ga,_u,[1,64])};this.peekChar(ga)===$&&(this.consumeAttributeSpace(ga),Eg.appdata=this.extractOneOrMore(ga,_u,[1,64])),this.attributes.msids.push(Eg)}parseImageAttr(ga){this.attributes.imageattr.push(ga.attValue)}parseRid(ga){const Eg=this.extractOneOrMore(ga,wE=>_g(wE)||_r(wE)||wE==="_"||wE==="-");this.consumeAttributeSpace(ga);const sE={id:Eg,direction:this.extract(ga,this.consumeToken),params:[]};if(this.peekChar(ga)===$){if(this.consumeAttributeSpace(ga),this.peek(ga,"pt=")){this.extract(ga,this.consume,"pt=");const wE=[];for(;;){const XE=this.extract(ga,this.consumeToken);wE.push(XE);try{this.extract(ga,this.consume,",")}catch{break}}sE.payloads=wE,this.peekChar(ga)===$&&this.extract(ga,this.consume,$)}for(;;){const wE=this.extract(ga,this.consumeToken);switch(wE){case"depend":{const XE={type:wE,rids:this.extract(ga,this.consume,"=").split(",")};sE.params.push(XE);break}default:{const XE={type:wE};this.peekChar(ga)==="="&&(this.extract(ga,this.consume,"="),XE.val=this.extract(ga,this.consumeTill,";")),sE.params.push(XE)}}try{this.extract(ga,this.consume,";")}catch{break}}}this.attributes.rids.push(sE)}parseSimulcast(ga){if(this.attributes.simulcast)throw new Error("must be single line of simulcast");this.attributes.simulcast=ga.attValue,this.extract(ga,this.consumeTill)}parseSctpPort(ga){this.attributes.sctpPort=this.extractOneOrMore(ga,_r,[1,5])}parseMaxMessageSize(ga){this.attributes.maxMessageSize=this.extractOneOrMore(ga,_r,[1,void 0])}digest(){return this.digested=!0,this.attributes}parseMid(ga){this.attributes.mid=this.extract(ga,this.consumeToken)}parseSSRCGroup(ga){const Eg=this.extract(ga,this.consumeToken),sE=[];for(;;)try{this.consumeAttributeSpace(ga);const wE=this.extract(ga,this.consumeInteger);sE.push(parseInt(wE,10))}catch{break}this.attributes.ssrcGroups.push({semantic:Eg,ssrcIds:sE})}}function P_(NE,ga,Eg){return ga in NE?Object.defineProperty(NE,ga,{value:Eg,enumerable:!0,configurable:!0,writable:!0}):NE[ga]=Eg,NE}class yS{constructor(){P_(this,"eol",z)}print(ga,Eg){let sE="";return Eg&&(this.eol=Eg),sE+=this.printVersion(ga.version),sE+=this.printOrigin(ga.origin),sE+=this.printSessionName(ga.sessionName),sE+=this.printInformation(ga.information),sE+=this.printUri(ga.uri),sE+=this.printEmail(ga.emails),sE+=this.printPhone(ga.phones),sE+=this.printConnection(ga.connection),sE+=this.printBandwidth(ga.bandwidths),sE+=this.printTimeFields(ga.timeFields),sE+=this.printKey(ga.key),sE+=this.printSessionAttributes(ga.attributes),sE+=this.printMediaDescription(ga.mediaDescriptions),sE}printVersion(ga){return"v=".concat(ga).concat(this.eol)}printOrigin(ga){return"o=".concat(ga.username," ").concat(ga.sessId," ").concat(ga.sessVersion," ").concat(ga.nettype," ").concat(ga.addrtype," ").concat(ga.unicastAddress).concat(this.eol)}printSessionName(ga){return ga?"s=".concat(ga).concat(this.eol):""}printInformation(ga){return ga?"i=".concat(ga).concat(this.eol):""}printUri(ga){return ga?"u=".concat(ga).concat(this.eol):""}printEmail(ga){let Eg="";for(const sE of ga)Eg+="e=".concat(sE).concat(this.eol);return Eg}printPhone(ga){let Eg="";for(const sE of ga)Eg+="e=".concat(sE).concat(this.eol);return Eg}printConnection(ga){return ga?"c=".concat(ga.nettype," ").concat(ga.addrtype," ").concat(ga.address).concat(this.eol):""}printBandwidth(ga){let Eg="";for(const sE of ga)Eg+="b=".concat(sE.bwtype,":").concat(sE.bandwidth).concat(this.eol);return Eg}printTimeFields(ga){let Eg="";for(const sE of ga){Eg+="t=".concat(sE.time.startTime," ").concat(sE.time.startTime).concat(this.eol);for(const wE of sE.repeats)Eg+="r=".concat(wE.repeatInterval," ").concat(wE.typedTimes.join(" ")).concat(this.eol);sE.zoneAdjustments&&(Eg+="z=",Eg+="z=".concat(sE.zoneAdjustments.map(wE=>"".concat(wE.time," ").concat(wE.back?"-":""," ").concat(wE.typedTime)).join(" ")).concat(this.eol),Eg+=this.eol)}return Eg}printKey(ga){return ga?"k=".concat(ga).concat(this.eol):""}printAttributes(ga){let Eg="";for(const sE of ga)Eg+="a=".concat(sE.attField).concat(sE.attValue?":".concat(sE.attValue):"").concat(this.eol);return Eg}printMediaDescription(ga){let Eg="";for(const sE of ga)Eg+=this.printMedia(sE.media),Eg+=this.printInformation(sE.information),Eg+=this.printConnections(sE.connections),Eg+=this.printBandwidth(sE.bandwidths),Eg+=this.printKey(sE.key),Eg+=this.printMediaAttributes(sE);return Eg}printConnections(ga){let Eg="";for(const sE of ga)Eg+=this.printConnection(sE);return Eg}printMedia(ga){return"m=".concat(ga.mediaType," ").concat(ga.port," ").concat(ga.protos.join("/")," ").concat(ga.fmts.join(" ")).concat(this.eol)}printSessionAttributes(ga){return new AE(this.eol).print(ga)}printMediaAttributes(ga){return new UE(this.eol).print(ga)}}class CE{constructor(ga){P_(this,"eol",void 0),this.eol=ga}printIceUfrag(ga){return ga===void 0?"":"a=ice-ufrag:".concat(ga).concat(this.eol)}printIcePwd(ga){return ga===void 0?"":"a=ice-pwd:".concat(ga).concat(this.eol)}printIceOptions(ga){return ga===void 0?"":"a=ice-options:".concat(ga.join($)).concat(this.eol)}printFingerprints(ga){return ga.length>0?ga.map(Eg=>"a=fingerprint:".concat(Eg.hashFunction).concat($).concat(Eg.fingerprint)).join(this.eol)+this.eol:""}printExtmap(ga){return ga.map(Eg=>"a=extmap:".concat(Eg.entry).concat(Eg.direction?"/".concat(Eg.direction):"").concat($).concat(Eg.extensionName).concat(Eg.extensionAttributes?"".concat($).concat(Eg.extensionAttributes):"").concat(this.eol)).join("")}printSetup(ga){return ga===void 0?"":"a=setup:".concat(ga).concat(this.eol)}printUnrecognized(ga){return ga.map(Eg=>"a=".concat(Eg.attField).concat(Eg.attValue?":".concat(Eg.attValue):"").concat(this.eol)).join("")}}class AE extends CE{print(ga){let Eg="";return Eg+=this.printGroups(ga.groups),Eg+=this.printMsidSemantic(ga.msidSemantic),Eg+=this.printIceLite(ga.iceLite),Eg+=this.printIceUfrag(ga.iceUfrag),Eg+=this.printIcePwd(ga.icePwd),Eg+=this.printIceOptions(ga.iceOptions),Eg+=this.printFingerprints(ga.fingerprints),Eg+=this.printSetup(ga.setup),Eg+=this.printTlsId(ga.tlsId),Eg+=this.printIdentity(ga.identities),Eg+=this.printExtmap(ga.extmaps),Eg+=this.printUnrecognized(ga.unrecognized),Eg}printGroups(ga){let Eg="";return ga.length>0&&(Eg+=ga.map(sE=>"a=group:".concat(sE.semantic).concat(sE.identificationTag.map(wE=>"".concat($).concat(wE)).join("")).concat(this.eol)).join("")),Eg}printIceLite(ga){return ga===void 0?"":"a=ice-lite"+this.eol}printTlsId(ga){return ga?"a=tls-id:".concat(ga).concat(this.eol):""}printIdentity(ga){return ga.length===0?"":ga.map(Eg=>"a=identity:".concat(Eg.assertionValue).concat(Eg.extensions.map(sE=>"".concat($).concat(sE.name).concat(sE.value?"=".concat(sE.value):"")))).join(this.eol)+this.eol}printMsidSemantic(ga){if(!ga)return"";let Eg="a=msid-semantic:".concat(ga.semantic);return ga.applyForAll?Eg+="".concat($,"*"):ga.identifierList.length>0&&(Eg+=ga.identifierList.map(sE=>"".concat($).concat(sE))),Eg+this.eol}}class UE extends CE{print(ga){const Eg=ga.attributes;let sE="";return sE+=this.printRTCP(Eg.rtcp),sE+=this.printIceUfrag(Eg.iceUfrag),sE+=this.printIcePwd(Eg.icePwd),sE+=this.printIceOptions(Eg.iceOptions),sE+=this.printCandidates(Eg.candidates),sE+=this.printRemoteCandidatesList(Eg.remoteCandidatesList),sE+=this.printEndOfCandidates(Eg.endOfCandidates),sE+=this.printFingerprints(Eg.fingerprints),sE+=this.printSetup(Eg.setup),sE+=this.printMid(Eg.mid),sE+=this.printExtmap(Eg.extmaps),sE+=this.printRTPRelated(Eg),sE+=this.printPtime(Eg.ptime),sE+=this.printMaxPtime(Eg.maxPtime),sE+=this.printDirection(Eg.direction),sE+=this.printSSRCGroups(Eg.ssrcGroups),sE+=this.printSSRC(Eg.ssrcs),sE+=this.printRTCPMux(Eg.rtcpMux),sE+=this.printRTCPMuxOnly(Eg.rtcpMuxOnly),sE+=this.printRTCPRsize(Eg.rtcpRsize),sE+=this.printMSId(Eg.msids),sE+=this.printImageattr(Eg.imageattr),sE+=this.printRid(Eg.rids),sE+=this.printSimulcast(Eg.simulcast),sE+=this.printSCTPPort(Eg.sctpPort),sE+=this.printMaxMessageSize(Eg.maxMessageSize),sE+=this.printUnrecognized(Eg.unrecognized),sE}printCandidates(ga){return ga.map(Eg=>"a=candidate:".concat(Eg.foundation).concat($).concat(Eg.componentId).concat($).concat(Eg.transport).concat($).concat(Eg.priority).concat($).concat(Eg.connectionAddress).concat($).concat(Eg.port).concat($,"typ").concat($).concat(Eg.type).concat(Eg.relAddr?"".concat($,"raddr").concat($).concat(Eg.relAddr):"").concat(Eg.relPort?"".concat($,"rport").concat($).concat(Eg.relPort):"").concat(Object.keys(Eg.extension).map(sE=>"".concat($).concat(sE).concat($).concat(Eg.extension[sE])).join("")).concat(this.eol)).join("")}printRemoteCandidatesList(ga){return ga.map(Eg=>"a=remote-candidates:".concat(Eg.join($)).concat(this.eol)).join("")}printEndOfCandidates(ga){return ga===void 0?"":"a=end-of-candidates"+this.eol}printRTPRelated(ga){if(!ga.payloads)return"";const Eg=ga.payloads;let sE="";sE+=ga.rtcpFeedbackWildcards.map(wE=>this.printRTCPFeedback("*",wE)).join("");for(const wE of Eg)sE+=this.printRtpMap(wE.payloadType,wE.rtpMap),sE+=this.printFmtp(wE.payloadType,wE.fmtp),sE+=wE.rtcpFeedbacks.map(XE=>this.printRTCPFeedback(wE.payloadType,XE)).join("");return sE}printFmtp(ga,Eg){if(!Eg)return"";const sE=Object.keys(Eg.parameters);return sE.length===1&&Eg.parameters[sE[0]]===null?"a=fmtp:".concat(ga).concat($).concat(sE[0]).concat(this.eol):"a=fmtp:".concat(ga).concat($).concat(Object.keys(Eg.parameters).map(wE=>"".concat(wE,"=").concat(Eg.parameters[wE])).join(";")).concat(this.eol)}printRtpMap(ga,Eg){return Eg?"a=rtpmap:".concat(ga).concat($).concat(Eg.encodingName,"/").concat(Eg.clockRate).concat(Eg.encodingParameters?"/".concat(Eg.encodingParameters):"").concat(this.eol):""}printRTCPFeedback(ga,Eg){let sE="a=rtcp-fb:".concat(ga).concat($),wE=Eg;return wE.type==="trr-int"?sE+="ttr-int".concat($).concat(wE.interval):(sE+="".concat(wE.type),wE.parameter&&(sE+="".concat($).concat(wE.parameter),wE.additional&&(sE+="".concat($).concat(wE.additional)))),sE+this.eol}printPtime(ga){return ga===void 0?"":"a=ptime:".concat(ga).concat(this.eol)}printMaxPtime(ga){return ga===void 0?"":"a=maxptime:".concat(ga).concat(this.eol)}printDirection(ga){return ga===void 0?"":"a=".concat(ga).concat(this.eol)}printSSRC(ga){return ga.map(Eg=>Object.keys(Eg.attributes).map(sE=>"a=ssrc:".concat(Eg.ssrcId.toString(10)).concat($).concat(sE).concat(Eg.attributes[sE]?":".concat(Eg.attributes[sE]):"").concat(this.eol)).join("")).join("")}printRTCPMux(ga){return ga===void 0?"":"a=rtcp-mux".concat(this.eol)}printRTCPMuxOnly(ga){return ga===void 0?"":"a=rtcp-mux-only".concat(this.eol)}printRTCPRsize(ga){return ga===void 0?"":"a=rtcp-rsize".concat(this.eol)}printRTCP(ga){if(ga===void 0)return"";let Eg="a=rtcp:".concat(ga.port);return ga.netType&&(Eg+="".concat($).concat(ga.netType)),ga.addressType&&(Eg+="".concat($).concat(ga.addressType)),ga.address&&(Eg+="".concat($).concat(ga.address)),Eg+this.eol}printMSId(ga){return ga.map(Eg=>"a=msid:".concat(Eg.id).concat(Eg.appdata?"".concat($).concat(Eg.appdata):"").concat(this.eol)).join("")}printImageattr(ga){return ga.map(Eg=>"a=imageattr:".concat(Eg).concat(this.eol)).join("")}printRid(ga){return ga.map(Eg=>{let sE="a=rid:".concat(Eg.id).concat($).concat(Eg.direction);return Eg.payloads&&(sE+="".concat($,"pt=").concat(Eg.payloads.join(","))),Eg.params.length>0&&(sE+="".concat($).concat(Eg.params.map(wE=>wE.type==="depend"?"depend=".concat(wE.rids.join(",")):"".concat(wE.type,"=").concat(wE.val)).join(";"))),sE+this.eol}).join("")}printSimulcast(ga){return ga===void 0?"":"a=simulcast:".concat(ga).concat(this.eol)}printSCTPPort(ga){return ga===void 0?"":"a=sctp-port:".concat(ga).concat(this.eol)}printMaxMessageSize(ga){return ga===void 0?"":"a=max-message-size:".concat(ga).concat(this.eol)}printMid(ga){return ga===void 0?"":"a=mid:".concat(ga).concat(this.eol)}printSSRCGroups(ga){return ga.map(Eg=>"a=ssrc-group:".concat(Eg.semantic).concat(Eg.ssrcIds.map(sE=>"".concat($).concat(sE.toString(10))).join("")).concat(this.eol)).join("")}}function YE(NE){return new $E().parse(NE)}function h_(NE,ga){return new yS().print(NE,ga)}}},p={};function g(b){if(p[b])return p[b].exports;var A=p[b]={exports:{}};return o[b](A,A.exports,g),A.exports}return g.d=(b,A)=>{for(var j in A)g.o(A,j)&&!g.o(b,j)&&Object.defineProperty(b,j,{enumerable:!0,get:A[j]})},g.o=(b,A)=>Object.prototype.hasOwnProperty.call(b,A),g.r=b=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(b,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(b,"__esModule",{value:!0})},g(8)})()})(O5);var q_=O5.exports;function N5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function P5(l){for(var i=1;i1&&arguments[1]!==void 0?arguments[1]:{},o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},p=arguments.length>3?arguments[3]:void 0;const{filterRTX:g,filterVideoFec:b,filterAudioFec:A,filterAudioCodec:j,filterVideoCodec:H}=i,{useXR:z}=o;let $=[],Vt=[],_r=[],Fi=[],_l=!1,_u=!1;if(q_.parse(l).mediaDescriptions.forEach(_g=>{p&&p!==_g.attributes.direction||(_g.media.mediaType!=="video"||_l||(Vt=_g.attributes.payloads,Fi=_g.attributes.extmaps,_l=!0),_g.media.mediaType!=="audio"||_u||($=_g.attributes.payloads,_r=_g.attributes.extmaps,_u=!0))}),!Fi||Vt.length===0)throw new Error("Cannot get video capabilities from SDP.");if(!_r||$.length===0)throw new Error("Cannot get audio capabilities from SDP.");Vt.forEach(_g=>{var eE;(eE=_g.rtpMap)!==null&&eE!==void 0&&eE.clockRate&&(_g.rtpMap.clockRate=parseInt(_g.rtpMap.clockRate)),z&&_g.rtcpFeedbacks.push({type:"rrtr"})}),$.forEach(_g=>{var eE;(eE=_g.rtpMap)!==null&&eE!==void 0&&eE.clockRate&&(_g.rtpMap.clockRate=parseInt(_g.rtpMap.clockRate)),z&&_g.rtcpFeedbacks.push({type:"rrtr"})}),g&&($=$.filter(_g=>{var eE;return((eE=_g.rtpMap)===null||eE===void 0?void 0:eE.encodingName.toLowerCase())!=="rtx"}),Vt=Vt.filter(_g=>{var eE;return((eE=_g.rtpMap)===null||eE===void 0?void 0:eE.encodingName.toLowerCase())!=="rtx"})),b&&(Vt=Vt.filter(_g=>{var eE;return!/(red)|(ulpfec)|(flexfec)/i.test(((eE=_g.rtpMap)===null||eE===void 0?void 0:eE.encodingName)||"")})),A&&($=$.filter(_g=>{var eE;return!/(red)|(ulpfec)|(flexfec)/i.test(((eE=_g.rtpMap)===null||eE===void 0?void 0:eE.encodingName)||"")})),j&&(j==null?void 0:j.length)>0&&($=$.filter(_g=>{var eE;return VE(j).call(j,((eE=_g.rtpMap)===null||eE===void 0?void 0:eE.encodingName.toLowerCase())||"")})),H&&(H==null?void 0:H.length)>0&&(Vt=Vt.filter(_g=>{var eE;return VE(H).call(H,((eE=_g.rtpMap)===null||eE===void 0?void 0:eE.encodingName.toLowerCase())||"")}));const _h=nE("UNSUPPORTED_VIDEO_CODEC");return _h&&_h.length>0&&(Vt=Vt.filter(_g=>!(_g.rtpMap&&VE(_h).call(_h,_g.rtpMap.encodingName.toLowerCase())))),{audioCodecs:$,videoCodecs:Vt,audioExtensions:_r,videoExtensions:Fi}}function mI(l){const i=q_.parse(l);let o,p;for(const g of i.mediaDescriptions){if(!o){const b=g.attributes.iceUfrag,A=g.attributes.icePwd;if(!b||!A)throw new Error("Cannot get iceUfrag or icePwd from SDP.");o={iceUfrag:b,icePwd:A}}if(!p){const b=g.attributes.fingerprints;b.length>0&&(p={fingerprints:b})}}if(!p&&i.attributes.fingerprints.length>0&&(p={fingerprints:i.attributes.fingerprints}),!p||!o)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:o,dtlsParameters:p}}function k5(l,i){const o=[],p=l.attributes.ssrcGroups.filter(A=>A.semantic==="FID"),g=l.attributes.ssrcGroups.find(A=>A.semantic==="SIM"),b=l.attributes.ssrcs;if(g)g.ssrcIds.forEach(A=>{var j;const H=(j=p.find(z=>z.ssrcIds[0]===A))===null||j===void 0?void 0:j.ssrcIds[1];o.push({ssrcId:A,rtx:i?H:void 0})});else if(p.length>0){const A=p[0].ssrcIds[0],j=p[0].ssrcIds[1];o.push({ssrcId:A,rtx:i?j:void 0})}else{if(b.length===0)throw new Error("No ssrcs found on local media description.");o.push({ssrcId:b[0].ssrcId})}return o}function D5(l,i){const{cname:o}=l;let p;i&&i.ip&&typeof i.port=="number"?(p=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:i.ip,port:i.port.toString(),type:"host",extension:{}}],Gi.debug("Using remote candidate from AP ".concat(i.ip,":").concat(i.port)),i.ip6&&(p.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:i.ip6,port:i.port.toString(),type:"host",extension:{}}),Gi.debug("Using IPV6 remote candidate from AP ".concat(i.ip6,":").concat(i.port)))):p=l.iceParameters.candidates.map(j=>({foundation:j.foundation,componentId:"1",transport:j.protocol,priority:j.priority.toString(),connectionAddress:j.ip,port:j.port.toString(),type:j.type,extension:{}}));const g={fingerprints:l.dtlsParameters.fingerprints.map(j=>({hashFunction:j.algorithm,fingerprint:j.fingerprint}))},b={iceUfrag:l.iceParameters.iceUfrag,icePwd:l.iceParameters.icePwd};let A;switch(l.dtlsParameters.role){case"server":A="passive";break;case"client":A="active";break;case"auto":A="actpass"}return{dtlsParameters:g,iceParameters:b,candidates:p,rtpCapabilities:pP(l.rtpCapabilities),setup:A,cname:o}}function XS(l,i,o){const p=[],g=[];return l.forEach(b=>{let{ssrcId:A,rtx:j}=b;const H=T_(8,"track-"),z={ssrcId:A,attributes:P5({label:H,mslabel:o=o||T_(10,""),msid:"".concat(o," ").concat(H)},i&&{cname:i})};if(p.push(z),j!==void 0){const $={ssrcId:j,attributes:P5({label:H,mslabel:o,msid:"".concat(o," ").concat(H)},i&&{cname:i})};p.push($),g.push({semantic:"FID",ssrcIds:[A,j]})}}),l.length>1&&g.push({semantic:"SIM",ssrcIds:l.map(b=>{let{ssrcId:A}=b;return A})}),{ssrcs:p,ssrcGroups:g}}function gI(l,i){i instanceof g_&&l.attributes.payloads.forEach(o=>{var p;const g=(p=o.rtpMap)===null||p===void 0?void 0:p.encodingName.toLowerCase();if(!g||["opus","pcmu","pcma","g722"].indexOf(g)===-1)return;o.fmtp||(o.fmtp={parameters:{}}),o.fmtp.parameters.minptime="10",o.fmtp.parameters.useinbandfec="1";const b=i._encoderConfig;b&&g!=="pcmu"&&g!=="pcma"&&g!=="g722"&&(b.bitrate&&!N_()&&(o.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*b.bitrate))),b.sampleRate&&(o.fmtp.parameters.maxplaybackrate="".concat(b.sampleRate),o.fmtp.parameters["sprop-maxcapturerate"]="".concat(b.sampleRate)),b.stereo&&(o.fmtp.parameters.stereo="1",o.fmtp.parameters["sprop-stereo"]="1"))})}function y2(l){const i=l.attributes.unrecognized.findIndex(o=>o.attField==="x-google-flag"&&o.attValue==="conference");i!==-1&&l.attributes.unrecognized.splice(i,1)}function b2(l,i){var o;if(!(i instanceof ZE&&i._encoderConfig&&i._hints.indexOf(A_.SCREEN_TRACK)===-1))return;const p=i._encoderConfig;I_().supportMinBitrate&&p.bitrateMin&&l.attributes.payloads.forEach(g=>{var b,A;VE(b=["h264","h265","vp8","vp9","av1"]).call(b,((A=g.rtpMap)===null||A===void 0?void 0:A.encodingName.toLowerCase())||"")&&(g.fmtp||(g.fmtp={parameters:{}}),g.fmtp.parameters["x-google-min-bitrate"]="".concat(p.bitrateMin))}),I_().supportMinBitrate&&!VE(o=i._hints).call(o,A_.LOW_STREAM)&&p.bitrateMax&&l.attributes.payloads.forEach(g=>{var b,A;VE(b=["h264","h265","vp8","vp9","av1"]).call(b,((A=g.rtpMap)===null||A===void 0?void 0:A.encodingName.toLowerCase())||"")&&(g.fmtp||(g.fmtp={parameters:{}}),g.fmtp.parameters["x-google-start-bitrate"]="".concat(nE("X_GOOGLE_START_BITRATE")||Math.floor(p.bitrateMax)))})}function L5(l){if(l.media.mediaType!=="video")return;const i=l_();if(i.name!==m_.SAFARI&&i.os!==l0.IOS)return;const o=l.attributes.extmaps.findIndex(p=>/video-orientation/g.test(p.extensionName));o!==-1&&l.attributes.extmaps.splice(o,1)}function dP(l,i,o){if(!i)return;let p,g;if(l.media.mediaType==="video"?(p=o.videoExtensions,g=o.videoCodecs):(p=o.audioExtensions,g=o.audioCodecs),i.twcc===!0){const b=p.find(A=>A.extensionName==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01");b&&(l.attributes.extmaps.find(j=>j.extensionName==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01")||l.attributes.extmaps.push({entry:b.entry,extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"}),function(j,H){return H.filter(z=>!!j.find($=>$.payloadType===z.payloadType&&!!$.rtcpFeedbacks.find(Vt=>Vt.type==="transport-cc")))}(g,l.attributes.payloads).forEach(j=>{j.rtcpFeedbacks.find(H=>H.type==="transport-cc")||j.rtcpFeedbacks.push({type:"transport-cc"})}))}else if(i.twcc===!1){const b=l.attributes.extmaps.findIndex(A=>A.extensionName==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01");b!==-1&&l.attributes.extmaps.splice(b,1),l.attributes.payloads.forEach(A=>{const j=A.rtcpFeedbacks.findIndex(H=>H.type==="transport-cc");j!==-1&&A.rtcpFeedbacks.splice(j,1)})}if(i.remb===!0){const b=p.find(A=>A.extensionName==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time");b&&(l.attributes.extmaps.find(j=>j.extensionName==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time")||l.attributes.extmaps.push({entry:b.entry,extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"}),function(j,H){return H.filter(z=>!!j.find($=>$.payloadType===z.payloadType&&!!$.rtcpFeedbacks.find(Vt=>Vt.type==="goog-remb")))}(g,l.attributes.payloads).forEach(j=>{j.rtcpFeedbacks.find(H=>H.type==="goog-remb")||j.rtcpFeedbacks.push({type:"goog-remb"})}))}else if(i.remb===!1){const b=l.attributes.extmaps.findIndex(A=>A.extensionName==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time");b!==-1&&l.attributes.extmaps.splice(b,1),l.attributes.payloads.forEach(A=>{const j=A.rtcpFeedbacks.findIndex(H=>H.type==="goog-remb");j!==-1&&A.rtcpFeedbacks.splice(j,1)})}}function S2(l,i,o){if(N_()||l.media.mediaType!=="video"||!(i instanceof ZE)||o!=="vp9"&&o!=="vp8"||o==="vp8"&&!nE("SIMULCAST")||i._scalabilityMode===void 0||i._scalabilityMode.numSpatialLayers<=1)return;const p=o==="vp8"?2:i._scalabilityMode.numSpatialLayers,g=l.attributes.ssrcs[0],b=l.attributes.ssrcGroups.find(j=>j.semantic==="FID"&&j.ssrcIds[0]===g.ssrcId),A={semantic:"SIM",ssrcIds:[g.ssrcId]};for(let j=1;j0&&arguments[0]!==void 0?arguments[0]:{},i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const{filterRTX:o,filterVideoFec:p,filterAudioFec:g,filterAudioCodec:b,filterVideoCodec:A}=l,{useXR:j}=i,H=new RTCPeerConnection;H.addTransceiver("video",{direction:"sendonly"}),H.addTransceiver("audio",{direction:"sendonly"}),H.addTransceiver("video",{direction:"recvonly"}),H.addTransceiver("audio",{direction:"recvonly"});const z=(await H.createOffer()).sdp,$=_2(z,{filterRTX:o,filterVideoFec:p,filterAudioFec:g,filterAudioCodec:b,filterVideoCodec:A},{useXR:j},"sendonly"),Vt=_2(z,{filterRTX:o,filterVideoFec:p,filterAudioFec:g,filterAudioCodec:b,filterVideoCodec:A},{useXR:j},"recvonly"),_r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},Fi={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},_l={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(hP($,Vt,"videoExtensions",_r,Fi,_l),hP($,Vt,"videoCodecs",_r,Fi,_l),hP($,Vt,"audioExtensions",_r,Fi,_l),hP($,Vt,"audioCodecs",_r,Fi,_l),nE("RAISE_H264_BASELINE_PRIORITY")){const _u=_l.videoCodecs.findIndex(_h=>{var _g,eE;return((_g=_h.rtpMap)===null||_g===void 0?void 0:_g.encodingName.toLocaleLowerCase())==="h264"&&((eE=_h.fmtp)===null||eE===void 0?void 0:eE.parameters["profile-level-id"])==="42001f"});if(_u!==-1){const _h=_l.videoCodecs.findIndex(_g=>{var eE;return((eE=_g.rtpMap)===null||eE===void 0?void 0:eE.encodingName.toLocaleLowerCase())==="h264"});if(_h<_u){Gi.debug("raising H264 baseline profile priority");const _g=_l.videoCodecs[_u];_l.videoCodecs.splice(_u,1),_l.videoCodecs.splice(_h,0,_g)}_h!==-1&&(Fi.videoCodecs=Fi.videoCodecs.filter(_g=>{var eE,oE;return!(((eE=_g.rtpMap)===null||eE===void 0?void 0:eE.encodingName.toLocaleLowerCase())==="h264"&&((oE=_g.fmtp)===null||oE===void 0?void 0:oE.parameters["profile-level-id"])!=="42001f")})),_h!==-1&&nE("FILTER_SEND_H264_BASELINE")&&(_r.videoCodecs=_r.videoCodecs.filter(_g=>{var eE,oE;return!(((eE=_g.rtpMap)===null||eE===void 0?void 0:eE.encodingName.toLocaleLowerCase())==="h264"&&((oE=_g.fmtp)===null||oE===void 0?void 0:oE.parameters["profile-level-id"])!=="42001f")}))}}try{H.close()}catch{}return{send:_r,recv:Fi,sendrecv:_l}}function hP(l,i,o,p,g,b){if(o==="videoExtensions"||o==="audioExtensions"){const A=[];return l[o].forEach(j=>{i[o].some((H,z)=>{if(j.entry===H.entry&&j.extensionName===H.extensionName)return A.push(z),!0})?b[o].push(j):p[o].push(j)}),void i[o].forEach((j,H)=>{A.indexOf(H)===-1&&g[o].push(j)})}if(o==="videoCodecs"||o==="audioCodecs"){const A=[];return l[o].forEach(j=>{i[o].some((H,z)=>{if(j.payloadType===H.payloadType&&JSON.stringify(j)===JSON.stringify(H))return A.push(z),!0})?b[o].push(j):p[o].push(j)}),void i[o].forEach((j,H)=>{A.indexOf(H)===-1&&g[o].push(j)})}}function pP(l){const{send:i,recv:o,sendrecv:p}=l;if(!p){if(!i||!o)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:i,recv:o}}let g,b;return i?(g={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},g.audioCodecs=[...i.audioCodecs,...p.audioCodecs],g.videoCodecs=[...i.videoCodecs,...p.videoCodecs],g.audioExtensions=[...i.audioExtensions,...p.audioExtensions],g.videoExtensions=[...i.videoExtensions,...p.videoExtensions]):g=p,o?(b={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},b.audioCodecs=[...o.audioCodecs,...p.audioCodecs],b.videoCodecs=[...o.videoCodecs,...p.videoCodecs],b.audioExtensions=[...o.audioExtensions,...p.audioExtensions],b.videoExtensions=[...o.videoExtensions,...p.videoExtensions]):b=p,{send:g,recv:b}}function AR(l){l.media.mediaType==="audio"&&l.attributes.payloads.filter(i=>{var o;return((o=i.rtpMap)===null||o===void 0?void 0:o.encodingName.toLowerCase())==="opus"}).forEach(i=>{i.fmtp||(i.fmtp={parameters:{}}),i.fmtp.parameters.stereo="1",i.fmtp.parameters["sprop-stereo"]="1"})}function fP(l){l.mediaDescriptions.forEach(i=>{i.media.mediaType!=="video"&&i.media.mediaType!=="audio"||i.attributes.payloads.forEach(o=>{o.rtcpFeedbacks.findIndex(p=>p.type==="rrtr")===-1&&o.rtcpFeedbacks.push({type:"rrtr"})})})}function mP(l,i,o,p){let g=[];if(l===ME.VIDEO){if(nE("H264_PROFILE_LEVEL_ID")&&p==="h264"&&(g=i.videoCodecs.filter(b=>{var A;return VE(A=b.rtpMap&&b.rtpMap.encodingName.toLowerCase()||"").call(A,p)&&b&&b.fmtp&&b.fmtp.parameters["profile-level-id"]===nE("H264_PROFILE_LEVEL_ID")})),!Array.isArray(g)||g.length===0){const b=o.videoCodecs.filter(A=>{var j;return VE(j=A.rtpMap&&A.rtpMap.encodingName.toLowerCase()||"").call(j,p)});b.length!==0&&(g=i.videoCodecs.filter(A=>b.some(j=>j.payloadType===A.payloadType)))}if(nE("USE_PUB_RTX")){const b=g.map(j=>j.payloadType.toString()),A=i.videoCodecs.filter(j=>j.rtpMap&&j.rtpMap.encodingName==="rtx"&&VE(b).call(b,j.fmtp&&j.fmtp.parameters.apt||""));g=[...g,...A]}g.length===0&&(Gi.warning("codec ".concat(p," not included in rtpCapabilities, fallback to default payloads: ").concat(i.videoCodecs[0].rtpMap&&i.videoCodecs[0].rtpMap.encodingName)),g=i.videoCodecs)}else g=i.audioCodecs.filter(b=>{var A;return VE(A=b.rtpMap&&b.rtpMap.encodingName.toLowerCase()||"").call(A,p)}),g.length===0&&(Gi.warning("codec ".concat(p," not included in rtpCapabilities, fallback to opus")),g=i.audioCodecs.filter(b=>{var A;return VE(A=b.rtpMap&&b.rtpMap.encodingName.toLowerCase()||"").call(A,"opus")}));return g}function M5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function U5(l){for(var i=1;io);if(!F5(l))return l;const i={};for(const o in l){const p=l[o];F5(p)||Array.isArray(p)?i[o]=hT(p):i[o]=p}return i}function F5(l){return!(typeof l!="object"||Array.isArray(l)||!l)}class T2{constructor(i){_e(this,"input",[]),_e(this,"size",void 0),this.size=i}add(i){this.input.push(i),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 FT={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},m1={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],selectedCandidatePair:{id:"unknown",localCandidate:FT,remoteCandidate:FT}},j5={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},V5={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},B5={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},G5={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0};function q5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function W5(l){for(var i=1;i{this.updateStats()},this.options.updateInterval)}getStats(){return this.stats}getSelectedCandidatePair(){return new pE(i=>{i({local:W5({},FT),remote:W5({},FT)})})}setVideoIsReady(i){this.videoIsReady=i}setVideoIsReady2(i,o){this.videoIsReady2[i]=o}getVideoIsReady(i){return this.videoIsReady2[i]||!1}setIsFirstAudioDecoded(i){}destroy(){window.clearInterval(this.intervalTimer),this.pc=void 0}calcLossRate(i){this.lossRateWindowStats.push(i),this.lossRateWindowStats.length>this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);const o=this.lossRateWindowStats.length,p=["videoSend","audioSend","videoRecv","audioRecv"];let g=0,b=0,A=0,j=0;for(const H of p)i[H].forEach((z,$)=>{if(!this.lossRateWindowStats[o-1][H][$]||!this.lossRateWindowStats[0][H][$])return;const Vt=this.lossRateWindowStats[o-1][H][$].packets-this.lossRateWindowStats[0][H][$].packets,_r=this.lossRateWindowStats[o-1][H][$].packetsLost-this.lossRateWindowStats[0][H][$].packetsLost;H==="videoSend"||H==="audioSend"?(g+=Vt,A+=_r):(b+=Vt,j+=_r),Number.isNaN(Vt)||Number.isNaN(Vt)?z.packetLostRate=0:z.packetLostRate=Vt<=0||_r<=0?0:_r/(Vt+_r)});i.sendPacketLossRate=g<=0||A<=0?0:A/(g+A),i.recvPacketLossRate=b<=0||j<=0?0:j/(b+j)}}function H5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function jet(l){for(var i=1;ib.type==="ssrc");this.processSSRCStats(p);const g=o.find(b=>b.type==="VideoBwe");g&&this.processBandwidthStats(g),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}processBandwidthStats(i){this._stats.bitrate={actualEncoded:Number(i.googActualEncBitrate),targetEncoded:Number(i.googTargetEncBitrate),retransmit:Number(i.googRetransmitBitrate),transmit:Number(i.googTransmitBitrate)},this._stats.sendBandwidth=Number(i.googAvailableSendBandwidth)}processSSRCStats(i){i.forEach(o=>{var p;const g=VE(p=o.id).call(p,"send");switch("".concat(o.mediaType,"_").concat(g?"send":"recv")){case"video_send":{const b=hT(V5);b.codec=o.googCodecName,b.adaptionChangeReason="none",o.googCpuLimitedResolution&&(b.adaptionChangeReason="cpu"),o.googBandwidthLimitedResolution&&(b.adaptionChangeReason="bandwidth"),b.avgEncodeMs=Number(o.googAvgEncodeMs),b.inputFrame={width:Number(o.googFrameWidthInput)||Number(o.googFrameWidthSent),height:Number(o.googFrameHeightInput)||Number(o.googFrameHeightSent),frameRate:Number(o.googFrameRateInput)},b.sentFrame={width:Number(o.googFrameWidthSent),height:Number(o.googFrameHeightSent),frameRate:Number(o.googFrameRateInput)},b.firsCount=Number(o.googFirReceived),b.nacksCount=Number(o.googNacksReceived),b.plisCount=Number(o.googPlisReceived),b.frameCount=Number(o.framesEncoded),b.bytes=Number(o.bytesSent),b.packets=Number(o.packetsSent),b.packetsLost=Number(o.packetsLost),b.ssrc=Number(o.ssrc),b.rttMs=Number(o.googRtt||0),this._stats.videoSend.push(b),this._stats.rtt=b.rttMs;break}case"video_recv":{const b=hT(j5),A=this.lastDecodeVideoReceiverStats.get(Number(o.ssrc));if(b.codec=o.googCodecName,b.targetDelayMs=Number(o.googTargetDelayMs),b.renderDelayMs=Number(o.googRenderDelayMs),b.currentDelayMs=Number(o.googCurrentDelayMs),b.minPlayoutDelayMs=Number(o.googMinPlayoutDelayMs),b.decodeMs=Number(o.googDecodeMs),b.maxDecodeMs=Number(o.googMaxDecodeMs),b.receivedFrame={width:Number(o.googFrameWidthReceived),height:Number(o.googFrameHeightReceived),frameRate:Number(o.googFrameRateReceived)},b.decodedFrame={width:Number(o.googFrameWidthReceived),height:Number(o.googFrameHeightReceived),frameRate:Number(o.googFrameRateDecoded)},b.decodeFrameRate=Number(o.googFrameRateDecoded),b.outputFrame={width:Number(o.googFrameWidthReceived),height:Number(o.googFrameHeightReceived),frameRate:Number(o.googFrameRateOutput)},b.jitterBufferMs=Number(o.googJitterBufferMs),b.firsCount=Number(o.googFirsSent),b.nacksCount=Number(o.googNacksSent),b.plisCount=Number(o.googPlisSent),b.framesDecodeCount=Number(o.framesDecoded),b.bytes=Number(o.bytesReceived),b.packets=Number(o.packetsReceived),b.packetsLost=Number(o.packetsLost),b.ssrc=Number(o.ssrc),b.packets>0&&!this.isFirstVideoReceived[b.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(b.ssrc),this.isFirstVideoReceived[b.ssrc]=!0),b.framesDecodeCount>0&&!this.isFirstVideoDecoded[b.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(b.ssrc,b.decodedFrame.width,b.decodedFrame.height),this.isFirstVideoDecoded[b.ssrc]=!0),A){const j=A.stats,H=Date.now()-A.lts;b.framesDecodeFreezeTime=j.framesDecodeFreezeTime,b.framesDecodeInterval=j.framesDecodeInterval,b.framesDecodeCount>j.framesDecodeCount&&this.isFirstVideoDecoded[b.ssrc]?(A.lts=Date.now(),b.framesDecodeInterval=H,b.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(o.ssrc,10))?b.framesDecodeFreezeTime+=b.framesDecodeInterval:this.setVideoIsReady2(parseInt(o.ssrc,10),!0))):b.framesDecodeCount0&&!this.isFirstAudioReceived[b.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(b.ssrc),this.isFirstAudioReceived[b.ssrc]=!0),b.decodingNormal>0&&!this.isFirstAudioDecoded[b.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(b.ssrc),this.isFirstAudioDecoded[b.ssrc]=!0),this._stats.audioRecv.push(b);break}case"audio_send":{const b=hT(B5);b.codec=o.googCodecName,b.inputLevel=Math.abs(Number(o.audioInputLevel))/32767,b.aecReturnLoss=Number(o.googEchoCancellationReturnLoss||0),b.aecReturnLossEnhancement=Number(o.googEchoCancellationReturnLossEnhancement||0),b.residualEchoLikelihood=Number(o.googResidualEchoLikelihood||0),b.residualEchoLikelihoodRecentMax=Number(o.googResidualEchoLikelihoodRecentMax||0),b.bytes=Number(o.bytesSent),b.packets=Number(o.packetsSent),b.packetsLost=Number(o.packetsLost),b.ssrc=Number(o.ssrc),b.rttMs=Number(o.googRtt||0),this._stats.rtt=b.rttMs,this._stats.audioSend.push(b);break}}})}_getStats(){return new pE((i,o)=>{this.pc.getStats(i,o)})}statsResponsesToObjects(i){const o=[];return i.result().forEach(p=>{const g={id:p.id,timestamp:p.timestamp.valueOf().toString(),type:p.type};p.names().forEach(b=>{g[b]=p.stat(b)}),o.push(g)}),o}}function z5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function EI(l){for(var i=1;i{switch(i.type){case cS.OUTBOUND:case cS.INBOUND:{const o=i.mediaType||i.kind,p=!o&&"frameWidth"in i,g=!o&&!("frameWidth"in i);i.type===cS.OUTBOUND?o==="audio"||g?this.processAudioOutboundStats(i):(o==="video"||p)&&this.processVideoOutboundStats(i):i.type===cS.INBOUND&&(o==="audio"||g?this.processAudioInboundStats(i):(o==="video"||p)&&this.processVideoInboundStats(i));break}case cS.TRANSPORT:{const o=this.report.get(i.selectedCandidatePairId);o&&this.processCandidatePairStats(o);break}case cS.CANDIDATE_PAIR:i.selected&&this.processCandidatePairStats(i)}}),this.updateSendBitrate(),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}async getSelectedCandidatePair(){const i=await this.pc.getStats(),o={local:EI({},FT),remote:EI({},FT)};return i.forEach(p=>{let g;if(p.type===cS.TRANSPORT&&(g=i.get(p.selectedCandidatePairId)),p.type===cS.CANDIDATE_PAIR&&p.selected&&(g=p),g){const b=(A,j)=>{A.type=j.type,A.id=j.id,j.address&&(A.address=j.address),j.candidateType&&(A.candidateType=j.candidateType),j.port&&(A.port=j.port),j.priority&&(A.priority=j.priority),j.protocol&&(A.protocol=j.protocol),j.relayProtocol&&(A.relayProtocol=j.relayProtocol)};if(g.localCandidateId){const A=i.get(g.localCandidateId);A&&b(o.local,A)}if(g.remoteCandidateId){const A=i.get(g.remoteCandidateId);A&&b(o.remote,A)}}}),o}processCandidatePairStats(i){if(this._stats.sendBandwidth=i.availableOutgoingBitrate||0,i.currentRoundTripTime&&(this._stats.rtt=1e3*i.currentRoundTripTime),this._stats.videoSend.forEach(o=>{i.currentRoundTripTime&&(o.rttMs=1e3*i.currentRoundTripTime)}),this._stats.audioSend.forEach(o=>{i.currentRoundTripTime&&(o.rttMs=1e3*i.currentRoundTripTime)}),this._stats.selectedCandidatePair.id=i.id,i.localCandidateId){const o=this.report.get(i.localCandidateId);o&&this.processCandidateStats(o)}if(i.remoteCandidateId){const o=this.report.get(i.remoteCandidateId);o&&this.processCandidateStats(o)}}processCandidateStats(i){let o;i.type===cS.LOCAL_CANDIDATE&&(o=this._stats.selectedCandidatePair.localCandidate),i.type===cS.REMOTE_CANDIDATE&&(o=this._stats.selectedCandidatePair.remoteCandidate),o&&(o.type=i.type,o.id=i.id,i.address&&(o.address=i.address),i.candidateType&&(o.candidateType=i.candidateType),i.port&&(o.port=i.port),i.priority&&(o.priority=i.priority),i.protocol&&(o.protocol=i.protocol),i.relayProtocol&&(o.relayProtocol=i.relayProtocol),i.type===cS.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==o.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(EI({},o),EI({},this.stats.selectedCandidatePair.localCandidate)),i.type===cS.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==o.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(EI({},o),EI({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(i){let o=this._stats.audioRecv.find(p=>p.ssrc===i.ssrc);o||(o=hT(G5),this._stats.audioRecv.push(o)),o.ssrc=i.ssrc,o.packets=i.packetsReceived,o.packetsLost=i.packetsLost,o.bytes=i.bytesReceived,o.jitterMs=1e3*i.jitter,this.processAudioTrackReceiverStats(i,i.trackId,o),i.codecId&&(o.codec=this.getCodecFromCodecStats(i.codecId)),o.receivedFrames||(o.receivedFrames=i.packetsReceived),o.droppedFrames||(o.droppedFrames=i.packetsLost),o.receivedFrames>0&&!this.isFirstAudioReceived[o.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(o.ssrc),this.isFirstAudioReceived[o.ssrc]=!0),o.outputLevel&&o.outputLevel>0&&!this.isFirstAudioDecoded[o.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(o.ssrc),this.isFirstAudioDecoded[o.ssrc]=!0),typeof i.concealedSamples=="number"&&(o.concealedSamples=i.concealedSamples)}processVideoInboundStats(i){let o=this._stats.videoRecv.find(A=>A.ssrc===i.ssrc);o||(o=hT(j5),this._stats.videoRecv.push(o)),o.ssrc=i.ssrc,o.packets=i.packetsReceived,o.packetsLost=i.packetsLost,o.bytes=i.bytesReceived,o.firsCount=i.firCount,o.nacksCount=i.nackCount,o.plisCount=i.pliCount,o.framesDecodeCount=i.framesDecoded,o.totalInterFrameDelay=i.totalInterFrameDelay,o.totalSquaredInterFrameDelay=i.totalSquaredInterFrameDelay;const p=this.lastDecodeVideoReceiverStats.get(o.ssrc),g=this.lastVideoFramesDecode.get(o.ssrc),b=Date.now();if(o.framesDecodeCount>0&&!this.isFirstVideoDecoded[o.ssrc]){const A=o.decodedFrame?o.decodedFrame.width:0,j=o.decodedFrame?o.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(o.ssrc,A,j),this.isFirstVideoDecoded[o.ssrc]=!0}if(p){const A=p.stats,j=b-p.lts;o.framesDecodeFreezeTime=A.framesDecodeFreezeTime,o.framesDecodeInterval=A.framesDecodeInterval,!this.isFirstVideoDecoded[o.ssrc]&&j>this.options.firstVideoDecodedTimeout&&!this.isFirstVideoDecodedTimeout[o.ssrc]&&(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(o.ssrc),this.isFirstVideoDecodedTimeout[o.ssrc]=!0),o.framesDecodeCount>A.framesDecodeCount&&this.isFirstVideoDecoded[o.ssrc]?(p.lts=Date.now(),o.framesDecodeInterval=j,o.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(i.ssrc))?o.framesDecodeFreezeTime+=o.framesDecodeInterval:this.setVideoIsReady2(parseInt(i.ssrc,10),!0))):o.framesDecodeCounti.framesDecoded?o.qpSumPerFrame=i.qpSum/i.framesDecoded:o.qpSumPerFrame=(i.qpSum-p.qpSum)/(i.framesDecoded-p.stats.framesDecodeCount))}g&&b-g.lts>=800?(o.decodeFrameRate=Math.round((o.framesDecodeCount-g.count)/((b-g.lts)/1e3)),this.lastVideoFramesDecode.set(o.ssrc,{count:o.framesDecodeCount,lts:b,rate:o.decodeFrameRate})):g?o.decodeFrameRate=g.rate:this.lastVideoFramesDecode.set(o.ssrc,{count:o.framesDecodeCount,lts:b,rate:0}),i.totalDecodeTime&&(o.decodeMs=1e3*i.totalDecodeTime),this.processVideoTrackReceiverStats(i,i.trackId,o),i.codecId&&(o.codec=this.getCodecFromCodecStats(i.codecId)),i.framerateMean&&(o.framesRateFirefox=i.framerateMean),o.packets>0&&!this.isFirstVideoReceived[o.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(o.ssrc),this.isFirstVideoReceived[o.ssrc]=!0),this.lastDecodeVideoReceiverStats.set(o.ssrc,{stats:EI({},o),lts:p?p.lts:Date.now(),qpSum:i.qpSum})}processVideoOutboundStats(i){let o=this._stats.videoSend.find(g=>g.ssrc===i.ssrc);o||(o=hT(V5),this._stats.videoSend.push(o));const p=this.mediaBytesSent.get(i.ssrc);if(p)p.add(i.bytesSent);else{const g=new T2(10);g.add(i.bytesSent),this.mediaBytesSent.set(i.ssrc,g)}if(i.retransmittedBytesSent!==void 0){const g=this.mediaBytesRetransmit.get(i.ssrc);if(g)g.add(i.retransmittedBytesSent);else{const b=new T2(10);b.add(i.retransmittedBytesSent),this.mediaBytesRetransmit.set(i.ssrc,b)}}if(i.totalEncodedBytesTarget){const g=this.mediaBytesTargetEncode.get(i.ssrc);if(g)g.add(i.totalEncodedBytesTarget);else{const b=new T2(10);b.add(i.totalEncodedBytesTarget),this.mediaBytesTargetEncode.set(i.ssrc,b)}}if(o.ssrc=i.ssrc,o.bytes=i.bytesSent,o.packets=i.packetsSent,o.firsCount=i.firCount,o.nacksCount=i.nackCount,o.plisCount=i.pliCount,o.frameCount=i.framesEncoded,o.adaptionChangeReason=i.qualityLimitationReason,o.scalabilityMode=i.scalabilityMode,i.totalEncodeTime&&i.framesEncoded){const g=this.lastEncoderMs.get(i.ssrc);if(!g||g.lastFrameCount>i.framesEncoded)o.avgEncodeMs=1e3*i.totalEncodeTime/i.framesEncoded;else{const b=i.framesEncoded-g.lastFrameCount,A=i.totalEncodeTime-g.lastEncoderTime;o.avgEncodeMs=1e3*A/b}}if(i.framesEncoded&&i.qpSum){const g=this.lastEncoderMs.get(i.ssrc);!g||g.lastFrameCount>i.framesEncoded?o.qpSumPerFrame=i.qpSum/i.framesEncoded:o.qpSumPerFrame=(i.qpSum-g.lastQpSum)/(i.framesEncoded-g.lastFrameCount)}if(this.lastEncoderMs.set(i.ssrc,{lastFrameCount:i.framesEncoded,lastEncoderTime:i.totalEncodeTime,lastQpSum:i.qpSum,lts:Date.now()}),i.codecId&&(o.codec=this.getCodecFromCodecStats(i.codecId)),i.mediaSourceId&&this.processVideoMediaSource(i.mediaSourceId,o),this.processVideoTrackSenderStats(i,i.trackId,o),i.remoteId)this.processRemoteInboundStats(i.remoteId,o);else{const g=this.findRemoteStatsId(i.ssrc,cS.REMOTE_INBOUND);g&&this.processRemoteInboundStats(g,o)}}processAudioOutboundStats(i){let o=this._stats.audioSend.find(p=>p.ssrc===i.ssrc);if(o||(o=hT(B5),this._stats.audioSend.push(o)),o.ssrc=i.ssrc,o.packets=i.packetsSent,o.bytes=i.bytesSent,i.mediaSourceId&&this.processAudioMediaSource(i.mediaSourceId,o),i.codecId&&(o.codec=this.getCodecFromCodecStats(i.codecId)),this.processAudioTrackSenderStats(i,i.trackId,o),i.remoteId)this.processRemoteInboundStats(i.remoteId,o);else{const p=this.findRemoteStatsId(i.ssrc,cS.REMOTE_INBOUND);p&&this.processRemoteInboundStats(p,o)}}findRemoteStatsId(i,o){var p;const g=Array.from(OT(p=this.report).call(p)).find(b=>b.type===o&&b.ssrc===i);return g?g.id:null}processVideoMediaSource(i,o){const p=this.report.get(i);p&&p.width&&p.height&&p.framesPerSecond&&(o.inputFrame={width:p.width,height:p.height,frameRate:p.framesPerSecond})}processAudioMediaSource(i,o){const p=this.report.get(i);p&&(o.inputLevel=p.audioLevel)}processVideoTrackSenderStats(i,o,p){var g,b,A,j;const H=o?this.report.get(o):void 0,z=(g=H==null?void 0:H.framesSent)!==null&&g!==void 0?g:i.framesSent;if(typeof z!="number")return;let $=(b=H==null?void 0:H.frameWidth)!==null&&b!==void 0?b:i.frameWidth,Vt=(A=H==null?void 0:H.frameHeight)!==null&&A!==void 0?A:i.frameHeight,_r=(j=H==null?void 0:H.framesPerSecond)!==null&&j!==void 0?j:i.framesPerSecond;if(typeof $=="number"&&typeof Vt=="number"||($=0,Vt=0),_r==null){const Fi=Date.now(),_l=this.lastVideoFramesSent.get(p.ssrc);_l&&Fi-_l.lts>=800?(_r=Math.round((z-_l.count)/((Fi-_l.lts)/1e3)),this.lastVideoFramesSent.set(p.ssrc,{count:z,lts:Fi,rate:_r})):_l?_r=_l.rate:this.lastVideoFramesSent.set(p.ssrc,{count:z,lts:Fi,rate:0})}p.sentFrame={width:$,height:Vt,frameRate:Math.max(0,_r)}}processVideoTrackReceiverStats(i,o,p){var g,b,A,j,H;const z=o?this.report.get(o):void 0,$=(g=z==null?void 0:z.framesReceived)!==null&&g!==void 0?g:i.framesReceived,Vt=(b=z==null?void 0:z.frameWidth)!==null&&b!==void 0?b:i.frameWidth,_r=(A=z==null?void 0:z.frameHeight)!==null&&A!==void 0?A:i.frameHeight,Fi=(j=z==null?void 0:z.jitterBufferDelay)!==null&&j!==void 0?j:i.jitterBufferDelay,_l=(H=z==null?void 0:z.jitterBufferEmittedCount)!==null&&H!==void 0?H:i.jitterBufferEmittedCount;if(typeof $=="number"){const _u=this.lastVideoFramesRecv.get(p.ssrc),_h=Date.now();p.framesReceivedCount=$;let _g=0;_u&&_h-_u.lts>=800?(_g=Math.round(($-_u.count)/((_h-_u.lts)/1e3)),this.lastVideoFramesRecv.set(p.ssrc,{count:$,lts:_h,rate:_g})):_u?_g=_u.rate:this.lastVideoFramesRecv.set(p.ssrc,{count:$,lts:_h,rate:0}),p.receivedFrame={width:Vt||0,height:_r||0,frameRate:_g||0},p.decodedFrame={width:Vt||0,height:_r||0,frameRate:p.decodeFrameRate||0},p.outputFrame={width:Vt||0,height:_r||0,frameRate:p.decodeFrameRate||0}}if(Fi&&_l){const _u=this.lastVideoJBDelay.get(p.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let _h=_u.jitterBufferMs;const _g=_l-_u.jitterBufferEmittedCount;_g>0&&(_h=1e3*(Fi-_u.jitterBufferDelay)/_g),p.jitterBufferMs=_h,p.currentDelayMs=Math.round(_h),this.lastVideoJBDelay.set(p.ssrc,{jitterBufferDelay:Fi,jitterBufferEmittedCount:_l,jitterBufferMs:p.currentDelayMs})}}processAudioTrackSenderStats(i,o,p){var g,b,A,j;const H=o?this.report.get(o):void 0,z=(g=(b=H==null?void 0:H.echoReturnLoss)!==null&&b!==void 0?b:i.echoReturnLoss)!==null&&g!==void 0?g:0,$=(A=(j=H==null?void 0:H.echoReturnLossEnhancement)!==null&&j!==void 0?j:i.echoReturnLossEnhancement)!==null&&A!==void 0?A:0;p.aecReturnLoss=z,p.aecReturnLossEnhancement=$}processAudioTrackReceiverStats(i,o,p){var g,b,A,j,H,z,$;const Vt=o?this.report.get(o):void 0,_r=(g=Vt==null?void 0:Vt.removedSamplesForAcceleration)!==null&&g!==void 0?g:i.removedSamplesForAcceleration,Fi=(b=Vt==null?void 0:Vt.totalSamplesReceived)!==null&&b!==void 0?b:i.totalSamplesReceived,_l=(A=Vt==null?void 0:Vt.jitterBufferDelay)!==null&&A!==void 0?A:i.jitterBufferDelay,_u=(j=Vt==null?void 0:Vt.jitterBufferEmittedCount)!==null&&j!==void 0?j:i.jitterBufferEmittedCount,_h=(H=Vt==null?void 0:Vt.audioLevel)!==null&&H!==void 0?H:i==null?void 0:i.audioLevel,_g=(z=Vt==null?void 0:Vt.totalSamplesDuration)!==null&&z!==void 0?z:i==null?void 0:i.totalSamplesDuration,eE=($=Vt==null?void 0:Vt.concealedSamples)!==null&&$!==void 0?$:i.concealedSamples;if(_r&&Fi&&(p.accelerateRate=_r/Fi),_l&&_u){const SE=this.lastAudioJBDelay.get(p.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let vE=SE.jitterBufferMs;const fE=_u-SE.jitterBufferEmittedCount;fE>0&&(vE=1e3*(_l-SE.jitterBufferDelay)/fE),p.jitterBufferMs=Math.round(vE),this.lastAudioJBDelay.set(p.ssrc,{jitterBufferDelay:_l,jitterBufferEmittedCount:_u,jitterBufferMs:p.jitterBufferMs})}p.outputLevel=_h;let oE=1920;_g&&Fi&&(oE=Fi/_g/50,p.receivedFrames=Math.round(Fi/oE)),eE&&(p.droppedFrames=Math.round(eE/oE))}processRemoteInboundStats(i,o){const p=this.report.get(i);p&&(o.packetsLost=p.packetsLost,p.roundTripTime&&(o.rttMs=1e3*p.roundTripTime),p.jitter&&(o.jitterMs=1e3*p.jitter),p.timestamp&&(o.timestamp=p.timestamp))}getCodecFromCodecStats(i){const o=this.report.get(i);if(!o)return"";const p=o.mimeType.match(/\/(.*)$/);return p&&p[1]?p[1]:""}updateSendBitrate(){let i=0,o=null,p=null;this.mediaBytesSent.forEach(b=>{i+=b.diffMean()}),this.mediaBytesRetransmit.forEach(b=>{o=o===null?b.diffMean():o+b.diffMean()}),this.mediaBytesTargetEncode.forEach(b=>{p=p===null?b.diffMean():p+b.diffMean()});const g=o!==null?i-o:i;this._stats.bitrate={actualEncoded:8*g/(this.options.updateInterval/1e3),transmit:8*i/(this.options.updateInterval/1e3)},o!==null&&(this._stats.bitrate.retransmit=8*o/(this.options.updateInterval/1e3)),p!==null&&(this._stats.bitrate.targetEncoded=8*p/(this.options.updateInterval/1e3))}}class Bet extends R2{updateStats(){return pE.resolve()}}function gP(l){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:250,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:8,p=arguments.length>3&&arguments[3]!==void 0?arguments[3]:500,g=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1e4;const b=function(){const A=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return A&&A[0]?Number(A[0].split("/")[1]):null}();return b?b<76?new Vet(l,{updateInterval:i,lossRateInterval:o,freezeRateLimit:p,firstVideoDecodedTimeout:g}):new K5(l,{updateInterval:i,lossRateInterval:o,freezeRateLimit:p,firstVideoDecodedTimeout:g}):function(A){return!!window.RTCStatsReport&&A.getStats()instanceof pE}(l)?new K5(l,{updateInterval:i,lossRateInterval:o,freezeRateLimit:p,firstVideoDecodedTimeout:g}):new Bet(l,{updateInterval:i,lossRateInterval:o,freezeRateLimit:p,firstVideoDecodedTimeout:g})}function Y5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function J5(l){for(var i=1;ivE.payloadType.toString(10));let SE=_r.videoCodecs.filter(vE=>{var fE,mE;return(fE=vE.rtpMap)===null||fE===void 0?void 0:VE(mE=fE.encodingName.toLowerCase()).call(mE,_u)});SE.length===0&&(SE=_r.videoCodecs),oE.attributes.payloads=SE,oE.attributes.extmaps=_r.videoExtensions}oE.media.mediaType==="audio"&&(oE.media.fmts=_r.audioCodecs.map(SE=>SE.payloadType.toString(10)),oE.attributes.payloads=_r.audioCodecs,oE.attributes.extmaps=_r.audioExtensions),_g.mediaDescriptions[eE]=this.mungMediaDesc(oE)}this.sessionDesc=_g,this.currentMidIndex=_g.mediaDescriptions.length-1}toString(){return q_.print(this.sessionDesc)}send(H,z,$){const{ssrcs:Vt,ssrcGroups:_r}=XS(z,this.cname),Fi=this.sessionDesc.mediaDescriptions.find(_h=>H===ME.VIDEO?_h.media.mediaType==="video":_h.media.mediaType==="audio"),_l=Vt[0].attributes.label,_u=Vt[0].attributes.mslabel;return Fi.attributes.ssrcs=Fi.attributes.ssrcs.concat(Vt),Fi.attributes.ssrcGroups=Fi.attributes.ssrcGroups.concat(_r),{id:_l,mslabel:_u}}batchSend(H){return H.map(z=>{let{kind:$,ssrcMsg:Vt}=z;return this.send($,Vt,void 0)})}stopSending(H){this.sessionDesc.mediaDescriptions.forEach(z=>{const $=[],Vt=[],_r=[];z.attributes.ssrcs.forEach(Fi=>{VE(H).call(H,Fi.attributes.label||"")?_r.push(Fi):$.push(Fi)}),z.attributes.ssrcGroups.forEach(Fi=>{var _l;VE(_l=_r.map(_u=>_u.ssrcId)).call(_l,Fi.ssrcIds[0])||Vt.push(Fi)}),z.attributes.ssrcs=$,z.attributes.ssrcGroups=Vt})}mute(H){const z=this.sessionDesc.mediaDescriptions.find($=>$.attributes.mid===H);if(!z)throw new Error("mediaDescription not found with ".concat(H," in remote SDP when calling RemoteSDP.mute."));z.attributes.direction="inactive"}unmute(H){const z=this.sessionDesc.mediaDescriptions.find($=>$.attributes.mid===H);if(!z)throw new Error("mediaDescription not found with ".concat(H," in remote SDP when calling RemoteSDP.unmute."));z.attributes.direction="sendonly"}receive(H,z,$){H.forEach((Vt,_r)=>{const Fi=Vt._mediaStreamTrack,_l=this.sessionDesc.mediaDescriptions.findIndex(_h=>_h.attributes.mid===Fi.kind),_u=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[_l],Vt);this.sessionDesc.mediaDescriptions[_l]=_u})}stopReceiving(H){}updateCandidates(H){H===N0.TCP?this.candidates.forEach(z=>{this.candidates.findIndex($=>$.transport==="tcp"&&$.connectionAddress===z.connectionAddress&&$.port===z.port)===-1&&this.candidates.push(U5(U5({},z),{},{foundation:"tcpcandidate",priority:Number(z.priority)-1+"",transport:"tcp",port:Number(z.port)+90+""}))}):this.candidates=this.candidates.filter(z=>z.transport!=="tcp");for(const z of this.sessionDesc.mediaDescriptions)z.attributes.candidates=this.candidates}restartICE(H){H=Q_(H),this.iceParameters=H,this.sessionDesc.mediaDescriptions.forEach(z=>{z.attributes.iceUfrag=H.iceUfrag,z.attributes.icePwd=H.icePwd})}predictReceivingMids(H){const z=[];for(let $=0;$Vt.attributes.mid===H);if($!==-1){const Vt=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[$],z);this.sessionDesc.mediaDescriptions[$]=Vt}}bumpMid(H){this.currentMidIndex+=H}updateTrackLabel(H,z,$){const Vt=this.sessionDesc.mediaDescriptions.find(Fi=>H===ME.VIDEO?Fi.attributes.mid==="video":Fi.attributes.mid==="audio");if(Vt){const Fi=Vt.attributes.ssrcs.find(_l=>_l.attributes.label===z);var _r;Fi&&(Fi.attributes.label=$,(_r=Fi.attributes.msid)===null||_r===void 0||_r.replace(z,$))}}mungMediaDesc(H){const z=Q_(H);return y2(z),function($){const Vt=$.attributes.extmaps.find(_r=>_r.extensionName==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01");Vt&&$.attributes.extmaps.splice($.attributes.extmaps.indexOf(Vt),1),$.attributes.payloads.forEach(_r=>{const Fi=_r.rtcpFeedbacks.findIndex(_l=>_l.type==="transport-cc");Fi!==-1&&_r.rtcpFeedbacks.splice(Fi,1)})}(z),z}getSSRC(H){for(const z of this.sessionDesc.mediaDescriptions)for(const $ of z.attributes.ssrcs)if($.attributes.label===H)return[$]}}({remoteIceParameters:i,remoteDtlsParameters:o,candidates:p,remoteRTPCapabilities:g.send,remoteSetup:b,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec,cname:A});const j=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:j})}catch(j){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(j.toString()))}}async updateRemoteRTPCapabilities(i,o){throw new yE(_p.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}send(i,o){var p=this;return JS(function*(){const g=yield d_(p.mutex.lock());try{if(!p.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const b=i.map(_r=>p.peerConnection.addTrack(_r._mediaStreamTrack)),A=yield d_(p.peerConnection.createOffer()),j=q_.parse(A.sdp),H=i.map(_r=>{const Fi=_r._mediaStreamTrack,_l=j.mediaDescriptions.find(_u=>_u.attributes.mid===Fi.kind);if(!_l)throw new Error("Cannot extract ssrc from mediaDescription.");return function(_u,_h,_g){const eE=_u.attributes.ssrcs.filter(SE=>SE.attributes.label===_h),oE=_u.attributes.ssrcGroups;if(eE.length===0)throw new Error("Cannot extract ssrc from plan-b SDP.");if(oE&&eE.length>1){const SE=oE.find(vE=>vE.ssrcIds.indexOf(eE[0].ssrcId)!==-1);return SE?[{ssrcId:SE.ssrcIds[0],rtx:_g?SE.ssrcIds[1]:void 0}]:[{ssrcId:eE[0].ssrcId}]}return[{ssrcId:eE[0].ssrcId}]}(_l,Fi.id,p.useRTX)});let z;try{z=yield H}catch(_r){throw b.forEach(Fi=>{H0()&&Fi.replaceTrack(null),p.peerConnection.removeTrack(Fi)}),_r}const $=p.mungSendOfferSDP(A.sdp,i);p.remoteSDP.receive(i,o,z);const Vt=p.remoteSDP.toString();return yield d_(p.peerConnection.setLocalDescription({type:"offer",sdp:$})),yield d_(p.applySendEncodings(b,i)),yield d_(p.peerConnection.setRemoteDescription({type:"answer",sdp:Vt})),i.map((_r,Fi)=>{const _l=_r._mediaStreamTrack.id;return{localSSRC:H[Fi],id:_l}})}catch(b){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(b.toString()))}finally{g()}})()}async stopSending(i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const o=this.peerConnection.getSenders().filter(b=>{var A;return i.indexOf(((A=b.track)===null||A===void 0?void 0:A.id)||"")!==-1});if(o.length!==i.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");o.map(b=>{H0()&&b.replaceTrack(null),this.peerConnection.removeTrack(b)});const p=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(p),this.remoteSDP.stopReceiving(i);const g=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:g})}catch(o){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(o.toString()))}}async receive(i,o,p,g){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(i," before remoteSDP created."));const{id:b,mslabel:A}=this.remoteSDP.send(i,o,g),j=new pE(($,Vt)=>{const _r=setTimeout(()=>{Vt(new Error("Cannot receive track, id: ".concat(b)))},1e4),Fi=_l=>{const _u=l_();if((_u.name==="Safari"&&Number(_u.version)===11||z0())&&_l.track.id!==b&&_l.streams[0].id===A){var _h;const _g=_l.streams[0].getTracks()[0];return(_h=this.remoteSDP)===null||_h===void 0||_h.updateTrackLabel(i,b,_l.track.id),this.peerConnection.removeEventListener("track",Fi),clearTimeout(_r),void $(_g)}if(_l.track.id===b)return this.peerConnection.removeEventListener("track",Fi),clearTimeout(_r),void $(_l.track)};this.peerConnection.addEventListener("track",Fi)}),H=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:H});const z=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(z),{track:await j,id:b}}catch(b){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(b.toString()))}}async stopReceiving(i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(i);const o=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const p=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(p)}catch(o){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(o.toString()))}}async muteRemote(i){}async unmuteRemote(i){}async muteLocal(i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const o=this.peerConnection.getSenders().filter(p=>{var g;return i.indexOf(((g=p.track)===null||g===void 0?void 0:g.id)||"")!==-1});if(o.length!==i.length)throw new Error("sender' length doesn't match mids' length.");o.map(p=>{if(H0()&&p.track)p.track.enabled=!1;else{const g=p.getParameters();g.encodings.forEach(b=>b.active=!1),p.setParameters(g)}})}catch(o){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(o.toString()))}}async unmuteLocal(i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const o=this.peerConnection.getSenders().filter(b=>{var A;return i.indexOf(((A=b.track)===null||A===void 0?void 0:A.id)||"")!==-1});if(o.length!==i.length)throw new Error("Senders' length doesn't match mids' length.");o.map(async b=>{if(H0()&&b.track)b.track.enabled=!0;else{const A=b.getParameters();A.encodings.forEach(j=>j.active=!0),await b.setParameters(A)}});const p=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(p);const g=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:g})}catch(o){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(o.toString()))}}restartICE(i){var o=this;return JS(function*(){const p=yield d_(o.mutex.lock("From P2PConnection.restartICE"));try{if(!o.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(I_().supportPCSetConfiguration){const H=o.peerConnection.getConfiguration(),z=i===N0.RELAY?"relay":"all";H.iceTransportPolicy!==z&&(Gi.debug("[".concat(o.store.clientId,"] restartICE change iceTransportPolicy from [").concat(H.iceTransportPolicy,"] to [").concat(z,"]")),H.iceTransportPolicy=z,o.peerConnection.setConfiguration(H))}else if(i===N0.RELAY)return;i!==N0.RELAY&&o.remoteSDP.updateCandidates(i);const g=yield d_(o.peerConnection.createOffer({iceRestart:!0}));if(!g.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const b=mI(g.sdp),{remoteIceParameters:A}=yield b.iceParameters;o.remoteSDP.restartICE(A);const j=o.remoteSDP.toString();yield d_(o.peerConnection.setLocalDescription(g)),yield d_(o.peerConnection.setRemoteDescription({type:"answer",sdp:j}))}catch(g){Gi.warning("[".concat(o.store.clientId,"] restart ICE failed, abort operation"),g)}finally{p()}})()}close(){var i;this.peerConnection.close(),(i=this.onConnectionStateChange)===null||i===void 0||i.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(i){return this.statsFilter.getVideoIsReady(i)}async updateEncoderConfig(i,o){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const p=await this.peerConnection.createOffer(),g=this.mungSendOfferSDP(p.sdp,[o]);this.remoteSDP.updateRecvMedia(o._mediaStreamTrack.kind,o);const b=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:g}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:b})}catch(p){throw new yE(_p.EXCHANGE_SDP_FAILED,p.toString())}}async updateSendParameters(i,o){const p=this.peerConnection.getSenders().filter(g=>{var b;return((b=g.track)===null||b===void 0?void 0:b.id)===i});p.length===1&&await this.applySendEncodings(p,[o])}setStatsRemoteVideoIsReady(i,o){this.statsFilter.setVideoIsReady2(i,o)}async replaceTrack(i,o){const p=this.peerConnection.getSenders().find(g=>{var b;return((b=g.track)===null||b===void 0?void 0:b.id)===o});p&&await p.replaceTrack(i._mediaStreamTrack)}createDataChannels(i,o){throw new yE(_p.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(i){throw new yE(_p.NOT_SUPPORTED,"Planb mode does not support stopDataChannels.")}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var i;(i=this.onICEConnectionStateChange)===null||i===void 0||i.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var i;(i=this.onConnectionStateChange)===null||i===void 0||i.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=i=>{i.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,Gi.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,Gi.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},nE("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(i){const o={iceServers:[],sdpSemantics:"plan-b"};return i.iceServers?o.iceServers=i.iceServers:i.turnServer&&i.turnServer.mode!=="off"&&(VI(i.turnServer.servers)?o.iceServers=i.turnServer.servers:(o.iceServers&&o.iceServers.push(...b0.turnServerConfigToIceServers(i.turnServer.servers)),nE("USE_TURN_SERVER_OF_GATEWAY")&&o.iceServers&&i.turnServer.serversFromGateway&&o.iceServers.push(...b0.turnServerConfigToIceServers(i.turnServer.serversFromGateway)),i.turnServer.servers.concat(i.turnServer.serversFromGateway||[]).forEach(p=>{p.forceturn&&(o.iceTransportPolicy="relay")}))),o}static turnServerConfigToIceServers(i){const o=[];return i.forEach(p=>{p.security?p.tcpport&&o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turns:".concat(p.turnServerURL,":").concat(p.tcpport,"?transport=tcp")}):(p.udpport&&o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turn:".concat(p.turnServerURL,":").concat(p.udpport,"?transport=udp")}),p.tcpport&&o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turn:".concat(p.turnServerURL,":").concat(p.tcpport,"?transport=tcp")}))}),o}async updateRtpSenderEncodings(i,o){var p;if(o||(o=this.peerConnection.getSenders().find(z=>{var $;return(($=z.track)===null||$===void 0?void 0:$.id)===i._mediaStreamTrack.id})),!o)return Gi.warn("[".concat(i.getTrackId(),"] no rtpSender found}"));if(!I_().supportSetRtpSenderParameters)return Gi.warn("Browser not support set rtp-sender parameters");const g={},b={};if(i instanceof ZE)switch(i._optimizationMode){case"motion":g.degradationPreference="maintain-framerate";break;case"detail":g.degradationPreference="maintain-resolution";break;default:g.degradationPreference="balanced"}if(nE("DSCP_TYPE")&&dR()){var A;const z=nE("DSCP_TYPE");VE(A=["very-low","low","medium","high"]).call(A,z)&&(b.networkPriority=z)}const j=o.getParameters(),H=(p=j.encodings)===null||p===void 0?void 0:p[0];H&&Object.assign(H,b),Object.assign(j,g),Gi.debug("[".concat(i.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(j.encodings))),await o.setParameters(j)}async applySendEncodings(i,o){try{if(!I_().supportSetRtpSenderParameters||i.length!==o.length)return;for(let p=0;p{const A=g._mediaStreamTrack,j=p.mediaDescriptions.find(H=>H.attributes.mid===A.kind);j&&gI(j,g)}),q_.print(p)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=i=>{var o;(o=this.onFirstAudioReceived)===null||o===void 0||o.call(this,i)},this.statsFilter.onFirstVideoReceived=i=>{var o;(o=this.onFirstVideoReceived)===null||o===void 0||o.call(this,i)},this.statsFilter.onFirstAudioDecoded=i=>{var o;(o=this.onFirstAudioDecoded)===null||o===void 0||o.call(this,i)},this.statsFilter.onFirstVideoDecoded=(i,o,p)=>{var g;(g=this.onFirstVideoDecoded)===null||g===void 0||g.call(this,i,o,p)},this.statsFilter.onSelectedLocalCandidateChanged=(i,o)=>{var p;(p=this.onSelectedLocalCandidateChanged)===null||p===void 0||p.call(this,i,o)},this.statsFilter.onSelectedRemoteCandidateChanged=(i,o)=>{var p;(p=this.onSelectedRemoteCandidateChanged)===null||p===void 0||p.call(this,i,o)}}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(i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const o=this.remoteSDP.batchSend(i).map((b,A)=>{let{id:j,mslabel:H}=b;const{kind:z}=i[A];return new pE(($,Vt)=>{const _r=setTimeout(()=>{Vt(new Error("Cannot receive track, id: ".concat(j)))},1e4),Fi=_l=>{const _u=l_();if(_u.name==="Safari"&&Number(_u.version)===11&&_l.track.id!==j&&_l.streams[0].id===H){var _h;const _g=_l.streams[0].getTracks()[0];return(_h=this.remoteSDP)===null||_h===void 0||_h.updateTrackLabel(z,j,_l.track.id),this.peerConnection.removeEventListener("track",Fi),clearTimeout(_r),void $({track:_g,id:j})}if(_l.track.id===j)return this.peerConnection.removeEventListener("track",Fi),clearTimeout(_r),void $({track:_l.track,id:j})};this.peerConnection.addEventListener("track",Fi)})}),p=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:p});const g=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(g),await pE.all(o)}catch(o){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(o.toString()))}}async getRemoteSSRC(i){if(!this.remoteSDP)return;const o=this.remoteSDP.getSSRC(i);return o==null?void 0:o[0].ssrcId}setConfiguration(i){if(I_().supportPCSetConfiguration){const o=b0.resolvePCConfiguration(i);this.peerConnection.setConfiguration(o)}}}function QS(l,i,o){const p=l[i];if(typeof p!="function")throw new Error("Cannot use mutex on object property.");return o.value=async function(){const g=this.mutex,b=await g.lock("Locking from P2PConnection.".concat(i));try{for(var A=arguments.length,j=new Array(A),H=0;Hg.rtpMap&&g.rtpMap.encodingName.toLowerCase()||"").filter(g=>{var b;return VE(b=Object.keys(eI)).call(b,g)}))];if(jE.updateRemoteRTPCapabilities(this.store.sessionId,{mids:i,localCodecs:p,remoteCodecs:this.remoteCodecs}),!this.remoteSDP)return void Gi.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(p,", codecs: ").concat(o));if(this.remoteSDP.updateRemoteCodec(i,o,this.store.codec)){const g=await this.peerConnection.createOffer(),b=this.logSDPExchange(g.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(g);const A=this.remoteSDP.toString();b==null||b(A),await this.peerConnection.setRemoteDescription({type:"answer",sdp:A})}else Gi.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const i=await this.peerConnection.createOffer();if(!i.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const o=mI(i.sdp),p=await x5({filterRTX:!nE("USE_PUB_RTX")&&!nE("USE_SUB_RTX"),filterVideoFec:nE("FILTER_VIDEO_FEC"),filterAudioFec:nE("FILTER_AUDIO_FEC"),filterVideoCodec:nE("FILTER_VIDEO_CODEC")},{useXR:this.useXR});return this.localCapabilities=pP(p),this.initialOffer=i,uO(uO({},o),{},{rtpCapabilities:p,offerSDP:i.sdp})}catch(i){throw new yE(_p.GET_LOCAL_CONNECTION_PARAMS_FAILED,i.toString())}}async connect(i,o,p,g,b,A){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new class{get localCapabilities(){return Q_(this._localCapabilities)}get rtpCapabilities(){return Q_(this._rtpCapabilities)}get candidates(){return Q_(this._candidates)}get iceParameters(){return Q_(this._iceParameters)}get dtlsParameters(){return Q_(this._dtlsParameters)}constructor(Fi){_e(this,"sessionDesc",void 0),_e(this,"_localCapabilities",void 0),_e(this,"_rtpCapabilities",void 0),_e(this,"_candidates",void 0),_e(this,"_iceParameters",void 0),_e(this,"_dtlsParameters",void 0),_e(this,"setup",void 0),_e(this,"currentMidIndex",void 0),_e(this,"cname",void 0),_e(this,"firefoxSsrcMidMap",new Map),Fi=Q_(Fi);const{remoteIceParameters:_l,remoteDtlsParameters:_u,candidates:_h,remoteRTPCapabilities:_g,remoteSetup:eE,localCapabilities:oE,cname:SE}=Fi,vE=q_.parse(`v=0 +o=- 0 0 IN IP4 127.0.0.1 +s=AgoraGateway +t=0 0 +a=group:BUNDLE 0 1 +a=msid-semantic: WMS +a=ice-lite +m=video 9 UDP/TLS/RTP/SAVPF 0 +c=IN IP4 127.0.0.1 +a=rtcp:9 IN IP4 0.0.0.0 +a=sendonly +a=rtcp-mux +a=rtcp-rsize +a=mid:0 +m=audio 9 UDP/TLS/RTP/SAVPF 0 +c=IN IP4 127.0.0.1 +a=rtcp:9 IN IP4 0.0.0.0 +a=sendonly +a=rtcp-mux +a=rtcp-rsize +a=mid:1 +`);this._rtpCapabilities=_g,this._candidates=_h,this._iceParameters=_l,this._dtlsParameters=_u,this._localCapabilities=oE,this.setup=eE,this.cname=SE;const fE=this.rtpCapabilities.send;for(const mE of vE.mediaDescriptions){if(mE.attributes.iceUfrag=_l.iceUfrag,mE.attributes.icePwd=_l.icePwd,mE.attributes.fingerprints=_u.fingerprints,mE.attributes.candidates=_h,mE.attributes.setup=eE,mE.media.mediaType==="video"&&(mE.media.fmts=fE.videoCodecs.map(EE=>EE.payloadType.toString(10)),mE.attributes.payloads=fE.videoCodecs,mE.attributes.extmaps=fE.videoExtensions,nE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:EE,ssrcGroups:PE}=XS([{ssrcId:Q5,rtx:nE("USE_SUB_RTX")?40001:void 0}],this.cname);mE.attributes.ssrcs=EE,mE.attributes.ssrcGroups=PE}if(mE.media.mediaType==="audio"&&(mE.media.fmts=fE.audioCodecs.map(EE=>EE.payloadType.toString(10)),mE.attributes.payloads=fE.audioCodecs,mE.attributes.extmaps=fE.audioExtensions,AR(mE),nE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:EE,ssrcGroups:PE}=XS([{ssrcId:2e4}],this.cname);mE.attributes.ssrcs=EE,mE.attributes.ssrcGroups=PE}}this.sessionDesc=vE,this.currentMidIndex=vE.mediaDescriptions.length-1}preloadRemoteMedia(){const Fi=nE("PRELOAD_MEDIA_COUNT");this.rtpCapabilities;const _l=this.candidates,_u=this.dtlsParameters,_h=this.iceParameters,_g=this.rtpCapabilities.send;for(let eE=1;eEPE.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:_h.iceUfrag,icePwd:_h.icePwd,unrecognized:[],candidates:_l,extmaps:_g.videoExtensions,fingerprints:_u.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:mE,ssrcGroups:EE,rtcpFeedbackWildcards:[],payloads:_g.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*eE)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:g1,protos:["UDP","TLS","RTP","SAVPF"],fmts:_g.audioCodecs.map(PE=>PE.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:_h.iceUfrag,icePwd:_h.icePwd,unrecognized:[],candidates:_l,extmaps:_g.audioExtensions,fingerprints:_u.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:vE,ssrcGroups:fE,rtcpFeedbackWildcards:[],payloads:_g.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*eE+1)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return q_.print(this.sessionDesc)}send(Fi,_l,_u,_h){const{ssrcs:_g,ssrcGroups:eE}=XS(_l,this.cname,nE("SYNC_GROUP")?_u:void 0),oE=this.findPreloadMediaDesc(_g);if(oE){if(N_()&&this.firefoxSsrcMidMap.set(_g[0].ssrcId,oE.attributes.mid),_h&&(_h.twcc||_h.remb)){const SE=this.sessionDesc.mediaDescriptions.indexOf(oE);return this.sessionDesc.mediaDescriptions[SE]=this.mungSendMediaDesc(oE,_h),{mid:oE.attributes.mid,needExchangeSDP:!0}}return{mid:oE.attributes.mid,needExchangeSDP:!1}}{const SE=this.findAvailableMediaIndex(Fi,_g);let vE;return SE===-1||SE===1&&(H0()||BV())||SE===0&&nE("USE_SUB_RTX")||GV()?(vE=this.createOrRecycleSendMedia(Fi,_g,eE,"sendonly",_h),this.updateBundleMids()):(vE=Q_(this.sessionDesc.mediaDescriptions[SE]),vE.attributes.direction="sendonly",vE.attributes.ssrcs=_g,vE.attributes.ssrcGroups=eE,this.sessionDesc.mediaDescriptions[SE]=this.mungSendMediaDesc(vE,_h)),N_()&&this.firefoxSsrcMidMap.set(_g[0].ssrcId,vE.attributes.mid),{mid:vE.attributes.mid,needExchangeSDP:!0}}}sendDataChannel(){const{mediaDesc:Fi,needExchangeSDP:_l}=this.createOrRecycleDataChannel();return this.updateBundleMids(),{mid:Fi.attributes.mid,needExchangeSDP:_l}}batchSend(Fi){const _l=Fi.map(_g=>{let{kind:eE,ssrcMsg:oE,mslabel:SE}=_g;return this.send(eE,oE,SE)}),_u=[];let _h=!1;return _l.forEach(_g=>{let{mid:eE,needExchangeSDP:oE}=_g;oE&&(_h=!0),_u.push(eE)}),{mids:_u,needExchangeSDP:_h}}stopSending(Fi){const _l=this.sessionDesc.mediaDescriptions.filter(_u=>_u.attributes.mid&&Fi.indexOf(_u.attributes.mid)!==-1);if(_l.length!==Fi.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");_l.forEach(_u=>{_u.attributes.mid==="0"||N_()||GV()?_u.attributes.ssrcs=[]:(_u.attributes.ssrcs=[],_u.attributes.direction="inactive",_u.media.port="0")}),this.updateBundleMids()}mute(Fi){const _l=this.sessionDesc.mediaDescriptions.find(_u=>_u.attributes.mid===Fi);if(!_l)throw new Error("mediaDescription not found with ".concat(Fi," in remote SDP when calling RemoteSDP.mute."));_l.attributes.direction="inactive"}unmute(Fi){const _l=this.sessionDesc.mediaDescriptions.find(_u=>_u.attributes.mid===Fi);if(!_l)throw new Error("mediaDescription not found with ".concat(Fi," in remote SDP when calling RemoteSDP.unmute."));_l.attributes.direction="sendonly"}muteRemote(Fi){const _l=this.sessionDesc.mediaDescriptions.filter(_u=>VE(Fi).call(Fi,_u.attributes.mid||""));if(_l.length!==Fi.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");_l.forEach(_u=>{_u.attributes.direction="inactive"})}unmuteRemote(Fi){const _l=this.sessionDesc.mediaDescriptions.filter(_u=>VE(Fi).call(Fi,_u.attributes.mid||""));if(_l.length!==Fi.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");_l.forEach(_u=>{_u.attributes.direction="recvonly"})}receive(Fi,_l,_u,_h){Fi.forEach((_g,eE)=>{this.createOrRecycleRecvMedia(_g,[],"recvonly",_l,_u,_h[eE])}),this.updateBundleMids()}stopReceiving(Fi){const _l=this.sessionDesc.mediaDescriptions.filter(_u=>Fi.indexOf(_u.attributes.mid)!==-1);if(_l.length!==Fi.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");_l.forEach(_u=>{_u.media.port="0",_u.attributes.direction="inactive"}),this.updateBundleMids()}updateCandidates(Fi){const _l=this._candidates.filter(_u=>_u.transport==="udp");if(Fi===N0.TCP){if(_l.length===0)return;if(nE("TCP_CANDIDATE_ONLY")){const _u=this._candidates.filter(_h=>_h.transport==="tcp");_l.forEach(_h=>{_u.findIndex(_g=>_g.connectionAddress===_h.connectionAddress)===-1&&_u.push(OR(OR({},_h),{},{foundation:"tcpcandidate",priority:Number(_h.priority)-1+"",transport:"tcp",port:Number(_h.port)+90+""}))}),this._candidates=_u}else{const _u=[];_l.forEach(_h=>{_u.push(OR(OR({},_h),{},{foundation:"tcpcandidate",priority:Number(_h.priority)-1+"",transport:"tcp",port:Number(_h.port)+90+""}))}),this._candidates=[..._l,..._u]}}else if(Fi===N0.RELAY){if(_l.length!==0)return;{const _u=this._candidates.filter(_h=>_h.transport==="tcp");_u.forEach(_h=>{_l.push(OR(OR({},_h),{},{foundation:"udpcandidate",priority:Number(_h.priority)+1+"",transport:"udp",port:Number(_h.port)-90+""}))}),this._candidates=[..._l,..._u]}}else _l.length===0?(this._candidates.filter(_u=>_u.transport==="tcp").forEach(_u=>{_l.push(OR(OR({},_u),{},{foundation:"udpcandidate",priority:Number(_u.priority)+1+"",transport:"udp",port:Number(_u.port)-90+""}))}),this._candidates=_l):this._candidates=this._candidates.filter(_u=>_u.transport!=="tcp");for(const _u of this.sessionDesc.mediaDescriptions)_u.attributes.candidates=this.candidates}restartICE(Fi){Fi=Q_(Fi),this._iceParameters=Fi,this.sessionDesc.mediaDescriptions.forEach(_l=>{_l.attributes.iceUfrag=Fi.iceUfrag,_l.attributes.icePwd=Fi.icePwd})}predictReceivingMids(Fi){const _l=[];for(let _u=0;_u{const _h=_u.media.mediaType===Fi&&_u.media.port!=="0"&&(_u.attributes.direction==="sendonly"||_u.attributes.direction==="sendrecv")&&_u.attributes.ssrcs.length===0;if(N_()){if(_h){const _g=this.firefoxSsrcMidMap.get(_l[0].ssrcId);return!(_g||_u.attributes.mid!=="0"&&_u.attributes.mid!=="1")||!(!_g||_g!==_u.attributes.mid)}return!1}return _h})}createOrRecycleDataChannel(){for(const _u of this.sessionDesc.mediaDescriptions)if(_u.media.mediaType==="application")return{mediaDesc:_u,needExchangeSDP:!1};this.currentMidIndex+=1;const Fi="".concat(this.currentMidIndex),_l={media:{mediaType:"application",port:g1,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(Fi),sctpPort:"5000"}};return this.sessionDesc.mediaDescriptions.push(_l),{mediaDesc:_l,needExchangeSDP:!0}}createOrRecycleRecvMedia(Fi,_l,_u,_h,_g,eE){const oE=Fi._mediaStreamTrack.kind,SE=this.rtpCapabilities.recv,vE=mP(oE,SE,this.localCapabilities.send,oE===ME.VIDEO?_h:_g),fE=oE===ME.VIDEO?SE.videoExtensions:SE.audioExtensions;this.currentMidIndex+=1;const mE="".concat(this.currentMidIndex);let EE={media:{mediaType:oE,port:g1,protos:["UDP","TLS","RTP","SAVPF"],fmts:vE.map(OE=>OE.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:fE,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:_l,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:vE,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:_u,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(mE)}};EE=this.mungRecvMediaDsec(EE,Fi,eE);const PE=this.findFirstClosedMedia(oE);if(PE){const OE=this.sessionDesc.mediaDescriptions.indexOf(PE);this.sessionDesc.mediaDescriptions[OE]=EE}else this.sessionDesc.mediaDescriptions.push(EE);return EE}updateRemoteCodec(Fi,_l,_u){const _h=[...new Set(this._rtpCapabilities.recv.videoCodecs.map(EE=>EE.rtpMap&&EE.rtpMap.encodingName.toLowerCase()||"").filter(EE=>{var PE;return VE(PE=Object.keys(eI)).call(PE,EE)}))],_g=new Set(_l);if(_h.every(EE=>_g.has(EE)))return Gi.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(_l)),!1;const eE=this._rtpCapabilities.recv.videoCodecs.filter(EE=>_l.some(PE=>{var OE;return VE(OE=EE.rtpMap&&EE.rtpMap.encodingName.toLowerCase()||"").call(OE,PE)}));if(eE.length===0)return Gi.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(_h," codecs: ").concat(_l)),!1;const oE=[...new Set(eE.map(EE=>EE.rtpMap&&EE.rtpMap.encodingName.toLowerCase()||""))];let SE;if(Gi.debug("updateRemoteCodec, from ".concat(_h," to ").concat(oE)),Fi.length===0)SE=this.sessionDesc.mediaDescriptions.filter(EE=>EE.media.mediaType==="video"&&EE.attributes.direction==="recvonly");else if(SE=this.sessionDesc.mediaDescriptions.filter(EE=>EE.attributes.mid&&VE(Fi).call(Fi,EE.attributes.mid)&&EE.attributes.direction==="recvonly"),SE.length!==Fi.length)return Gi.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(Fi,", codecs: ").concat(_l)),!1;this._rtpCapabilities.recv.videoCodecs=eE;const vE=this.localCapabilities.send,fE=this.rtpCapabilities.recv,mE=mP(ME.VIDEO,fE,vE,_u);return SE.forEach(EE=>{const PE=mE.map(OE=>OE.payloadType.toString(10));Gi.debug("updateRemoteCodec mid: ".concat(EE.attributes.mid,", from ").concat(EE.attributes.payloads," to ").concat(mE)),EE.attributes.payloads=mE,EE.media.fmts=PE}),!0}createOrRecycleSendMedia(Fi,_l,_u,_h,_g){const eE=this.rtpCapabilities.send,oE=Fi===ME.VIDEO?eE.videoCodecs:eE.audioCodecs,SE=Fi===ME.VIDEO?eE.videoExtensions:eE.audioExtensions;this.currentMidIndex+=1;const vE="".concat(this.currentMidIndex);let fE={media:{mediaType:Fi,port:g1,protos:["UDP","TLS","RTP","SAVPF"],fmts:oE.map(EE=>EE.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:SE,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:_l,ssrcGroups:_u,rtcpFeedbackWildcards:[],payloads:oE,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:_h,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(vE)}};fE=this.mungSendMediaDesc(fE,_g);const mE=this.findFirstClosedMedia(Fi);if(mE){const EE=this.sessionDesc.mediaDescriptions.indexOf(mE);this.sessionDesc.mediaDescriptions[EE]=fE}else this.sessionDesc.mediaDescriptions.push(fE);return fE}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(Fi=>Fi.media.port!=="0").map(Fi=>Fi.attributes.mid)}mungRecvMediaDsec(Fi,_l,_u){const _h=Q_(Fi);return y2(_h),gI(_h,_l),b2(_h,_l),L5(_h),dP(_h,_u,this.localCapabilities.send),_h}mungSendMediaDesc(Fi,_l){const _u=Q_(Fi);return dP(_u,_l,this.localCapabilities.recv),AR(_u),_u}updateRecvMedia(Fi,_l){const _u=this.sessionDesc.mediaDescriptions.findIndex(_h=>_h.attributes.mid===Fi);if(_u!==-1){const _h=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[_u],_l);this.sessionDesc.mediaDescriptions[_u]=_h}}bumpMid(Fi){this.currentMidIndex+=Fi}findFirstClosedMedia(Fi){return this.sessionDesc.mediaDescriptions.find(_l=>N_()?_l.media.port==="0"&&_l.media.mediaType===Fi:_l.media.port==="0")}findPreloadMediaDesc(Fi){return this.sessionDesc.mediaDescriptions.find(_l=>{var _u;return((_u=_l.attributes)===null||_u===void 0||(_u=_u.ssrcs[0])===null||_u===void 0?void 0:_u.ssrcId)===Fi[0].ssrcId})}getSSRC(Fi){var _l;return(_l=this.sessionDesc.mediaDescriptions.find(_u=>_u.attributes.mid===Fi))===null||_l===void 0?void 0:_l.attributes.ssrcs}}({remoteIceParameters:i,remoteDtlsParameters:o,candidates:p,remoteRTPCapabilities:g,remoteSetup:b,localCapabilities:this.localCapabilities,cname:A}),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const j=this.remoteSDP.toString(),H=q_.parse(this.initialOffer.sdp),z=H.mediaDescriptions.find(Fi=>Fi.media.mediaType==="audio");z&&AR(z),this.useXR&&fP(H);const $=q_.print(H),Vt=this.logSDPExchange($||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:$}),Vt==null||Vt(j),await this.peerConnection.setRemoteDescription({type:"answer",sdp:j});const _r=this.peerConnection.getTransceivers()[0];if(_r!=null&&_r.receiver&&this.tryBindTransportEvents(_r.receiver),nE("PRELOAD_MEDIA_COUNT")>0){this.remoteSDP.preloadRemoteMedia();const Fi=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:Fi});const _l=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(_l)}}catch(j){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(j.toString()))}}send(i,o,p){var g=this;return JS(function*(){const b=yield d_(g.mutex.lock("From P2PConnection.send"));try{if(!g.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const A=[];i.forEach(_u=>{const _h=g.peerConnection.addTransceiver(_u._mediaStreamTrack,{direction:"sendonly"});A.push(_h),_u._updateRtpTransceiver(_h)}),N_()&&nE("SIMULCAST")===!0&&(yield d_(g.applySimulcastForFirefox(A,i)));const j=yield d_(g.peerConnection.createOffer()),H=g.remoteSDP.predictReceivingMids(i.length),z=g.mungSendOfferSDP(j.sdp,i,H),$=q_.parse(z),Vt=H.map(_u=>{const _h=$.mediaDescriptions.find(_g=>_g.attributes.mid===_u);if(!_h)throw new Error("Cannot extract ssrc from mediaDescription.");return k5(_h,nE("USE_PUB_RTX"))});let _r;try{_r=yield Vt}catch(_u){_r=[],g.remoteSDP.receive(i,o,p,_r);const _h=g.remoteSDP.toString();throw yield d_(g.peerConnection.setLocalDescription({type:"offer",sdp:z})),yield d_(g.peerConnection.setRemoteDescription({type:"answer",sdp:_h})),yield d_(g.stopSending(H,!0)),_u}g.remoteSDP.receive(i,o,p,_r);const Fi=g.remoteSDP.toString(),_l=g.logSDPExchange(z,"offer","local","send");return yield d_(g.peerConnection.setLocalDescription({type:"offer",sdp:z})),yield d_(g.applySimulcastEncodings(A,i)),yield d_(g.applySendEncodings(A,i)),_l==null||_l(Fi),yield d_(g.peerConnection.setRemoteDescription({type:"answer",sdp:Fi})),A.map((_u,_h)=>{const _g=H[_h];return{localSSRC:Vt[_h],id:_g,transceiver:_u}})}catch(A){throw A instanceof yE?A:new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(A.toString()))}finally{b()}})()}async createDataChannels(i,o){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let p=this.dataStreamChannelMap.get(i);p&&p.readyState==="open"?Gi.debug("[P2PConnection] Channels are already available and can be reused directly."):(p=this.peerConnection.createDataChannel("datastream-channel",{ordered:!1,maxRetransmits:nE("DATASTREAM_MAX_RETRANSMITS")}),p.binaryType="arraybuffer",this.dataStreamChannelMap.set(i,p)),o.forEach(b=>{b._updateOriginDataChannel(p)});const{needExchangeSDP:g}=this.remoteSDP.sendDataChannel();if(g){const b=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:b});const A=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(A),Gi.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else Gi.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(p){throw p instanceof yE?p:new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.createDataChannels failed; ".concat(p.toString()))}}async stopDataChannels(i){try{const o=this.dataStreamChannelMap.get(i);return o==null||o.close(),void this.dataStreamChannelMap.delete(i)}catch(o){throw o instanceof yE?o:new yE(_p.DATACHANNEL_FAILED,"P2PConnection.stopDataChannels failed; ".concat(o.toString()))}}async stopSending(i,o){const p=o?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 g=this.peerConnection.getTransceivers().filter(H=>i.indexOf(H.mid)!==-1);if(g.length!==i.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");g.map(H=>{var z;H.direction="inactive",(z=H.stop)===null||z===void 0||z.call(H)});const b=await this.peerConnection.createOffer(),A=this.logSDPExchange(b.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(b),this.remoteSDP.stopReceiving(i);const j=this.remoteSDP.toString();A==null||A(j),await this.peerConnection.setRemoteDescription({type:"answer",sdp:j})}catch(g){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(g.toString()))}finally{p&&p()}}async receive(i,o,p,g){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(i," before remoteSDP created."));const{mid:b,needExchangeSDP:A}=this.remoteSDP.send(i,o,p,g);if(A){const H=this.remoteSDP.toString(),z=this.logSDPExchange(H,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:H});const $=await this.peerConnection.createAnswer(),Vt=this.mungReceiveAnswerSDP($.sdp,b,i);z==null||z(Vt||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:Vt}),Gi.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(i," by exchanging SDP."))}else Gi.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(i," no need to exchange SDP."));const j=this.peerConnection.getTransceivers().find(H=>H.mid===b);if(!j)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:j.receiver.track,id:b,transceiver:j}}catch(b){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(b.toString()))}}async batchReceive(i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const{mids:o,needExchangeSDP:p}=this.remoteSDP.batchSend(i);if(p){const g=this.remoteSDP.toString(),b=this.logSDPExchange(g,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:g});const A=await this.peerConnection.createAnswer();b==null||b(A.sdp||""),await this.peerConnection.setLocalDescription(A),Gi.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."))}else Gi.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive no need to exchange SDP."));return o.map(g=>{const b=this.peerConnection.getTransceivers().find(A=>A.mid===g);if(!b)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:b.receiver.track,id:g,transceiver:b}})}catch(o){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(o.toString()))}}async stopReceiving(i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(i);const o=this.remoteSDP.toString(),p=this.logSDPExchange(o,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const g=await this.peerConnection.createAnswer();p==null||p(g.sdp||""),await this.peerConnection.setLocalDescription(g)}catch(o){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(o.toString()))}}async muteRemote(i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteRemote mid=".concat(i," before remote SDP created."));this.remoteSDP.mute(i);const o=this.remoteSDP.toString(),p=this.logSDPExchange(o,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const g=await this.peerConnection.createAnswer();p==null||p(g.sdp||""),await this.peerConnection.setLocalDescription(g)}catch(o){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(o.toString()))}}async unmuteRemote(i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteRemote mid=".concat(i," before remote SDP created."));this.remoteSDP.unmute(i);const o=this.remoteSDP.toString(),p=this.logSDPExchange(o,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const g=await this.peerConnection.createAnswer();p==null||p(g.sdp||""),await this.peerConnection.setLocalDescription(g)}catch(o){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(o.toString()))}}async muteLocal(i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const o=this.peerConnection.getTransceivers().filter(A=>A.mid&&i.indexOf(A.mid)!==-1);if(o.length!==i.length)throw new Error("Transceivers' length doesn't match mids' length.");o.map(A=>{A.direction="inactive"});const p=await this.peerConnection.createOffer(),g=this.logSDPExchange(p.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(p),this.remoteSDP.muteRemote(i);const b=this.remoteSDP.toString();g==null||g(b),await this.peerConnection.setRemoteDescription({type:"answer",sdp:b})}catch(o){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(o.toString()))}}async unmuteLocal(i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const o=this.peerConnection.getTransceivers().filter(A=>A.mid&&i.indexOf(A.mid)!==-1);if(o.length!==i.length)throw new Error("Transceivers' length doesn't match mids' length.");o.map(async(A,j)=>{A.direction="sendonly"});const p=await this.peerConnection.createOffer(),g=this.logSDPExchange(p.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(p),this.remoteSDP.unmuteRemote(i);const b=this.remoteSDP.toString();g==null||g(b),await this.peerConnection.setRemoteDescription({type:"answer",sdp:b})}catch(o){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(o.toString()))}}restartICE(i){var o=this;return JS(function*(){const p=yield d_(o.mutex.lock("From P2PConnection.restartICE"));try{if(!o.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(I_().supportPCSetConfiguration){const z=o.peerConnection.getConfiguration(),$=i===N0.RELAY?"relay":"all";z.iceTransportPolicy!==$&&(Gi.debug("[".concat(o.store.clientId,"] restartICE change iceTransportPolicy from [").concat(z.iceTransportPolicy,"] to [").concat($,"]")),z.iceTransportPolicy=$,o.peerConnection.setConfiguration(z))}else if(i===N0.RELAY)return;o.remoteSDP.updateCandidates(i);const g=yield d_(o.peerConnection.createOffer({iceRestart:!0}));if(!g.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const b=mI(g.sdp),{remoteIceParameters:A}=yield b.iceParameters;o.remoteSDP.restartICE(A);const j=o.remoteSDP.toString(),H=o.logSDPExchange(g.sdp||"","offer","local","restartICE");o.store.descriptionStart(),yield d_(o.peerConnection.setLocalDescription(g)),H==null||H(j),yield d_(o.peerConnection.setRemoteDescription({type:"answer",sdp:j}))}catch(g){Gi.warning("[".concat(o.store.clientId,"] restart ICE failed, abort operation"),g)}finally{p()}})()}close(){var i;this.peerConnection.close(),(i=this.onConnectionStateChange)===null||i===void 0||i.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(i){return this.statsFilter.getVideoIsReady(i)}async updateEncoderConfig(i,o){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const p=await this.peerConnection.createOffer(),g=this.mungSendOfferSDP(p.sdp,[o],[i]);this.remoteSDP.updateRecvMedia(i,o);const b=this.remoteSDP.toString(),A=this.logSDPExchange(g,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:g}),A==null||A(b),await this.peerConnection.setRemoteDescription({type:"answer",sdp:b})}catch(p){throw new yE(_p.EXCHANGE_SDP_FAILED,p.toString())}}async updateSendParameters(i,o){const p=this.peerConnection.getTransceivers().filter(g=>g.mid===i);p.length===1&&(this.isVP8Simulcast(o)?N_()||await this.applySimulcastEncodings(p,[o]):await this.applySendEncodings(p,[o]))}setStatsRemoteVideoIsReady(i,o){this.statsFilter.setVideoIsReady2(i,o)}async replaceTrack(i,o){const p=this.peerConnection.getTransceivers().find(g=>g.mid===o);p&&await p.sender.replaceTrack(i._mediaStreamTrack)}async getSelectedCandidatePair(){const i=this.peerConnection.getReceivers();if(i.length>0&&i[0].transport&&i[0].transport.iceTransport&&i[0].transport.iceTransport.getSelectedCandidatePair&&i[0].transport.iceTransport.getSelectedCandidatePair()){const o=i[0].transport.iceTransport,{local:p,remote:g}=o.getSelectedCandidatePair();return{local:uO(uO({},FT),{},{candidateType:p.type,protocol:p.protocol,address:p.address,port:p.port}),remote:uO(uO({},FT),{},{candidateType:g.type,protocol:g.protocol,address:g.address,port:g.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var i;(i=this.onICEConnectionStateChange)===null||i===void 0||i.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var i;(i=this.onConnectionStateChange)===null||i===void 0||i.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=i=>{i.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,Gi.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,Gi.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},nE("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(i){const o={iceServers:[]};return i.iceServers?o.iceServers=i.iceServers:i.turnServer&&i.turnServer.mode!=="off"&&(VI(i.turnServer.servers)?o.iceServers=i.turnServer.servers:(o.iceServers&&o.iceServers.push(...y1.turnServerConfigToIceServers(i.turnServer.servers)),nE("USE_TURN_SERVER_OF_GATEWAY")&&o.iceServers&&i.turnServer.serversFromGateway&&o.iceServers.push(...y1.turnServerConfigToIceServers(i.turnServer.serversFromGateway)),nE("FORCE_TURN_TCP")?o.iceTransportPolicy="relay":i.turnServer.servers.concat(i.turnServer.serversFromGateway||[]).forEach(p=>{p.forceturn&&(o.iceTransportPolicy="relay")}))),nE("ENABLE_ENCODED_TRANSFORM")&&I_().supportWebRTCEncodedTransform&&(o.encodedInsertableStreams=!0),o}static turnServerConfigToIceServers(i){const o=[];return i.forEach(p=>{p.security?p.tcpport&&o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turns:".concat(d1(p.turnServerURL),":").concat(p.tcpport,"?transport=tcp")}):(p.udpport&&!nE("FORCE_TURN_TCP")&&o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turn:".concat(p.turnServerURL,":").concat(p.udpport,"?transport=udp")}),p.tcpport&&o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turn:".concat(p.turnServerURL,":").concat(p.tcpport,"?transport=tcp")}))}),o}tryBindTransportEvents(i){const o=i.transport;if(o){this.transportEventReceiver=i,o.onstatechange=()=>{var g;o!=null&&o.state&&((g=this.onDTLSTransportStateChange)===null||g===void 0||g.call(this,o.state))},o.onerror=g=>{var b;(b=this.onDTLSTransportError)===null||b===void 0||b.call(this,"error"in g?g.error:g)};const p=o.iceTransport;p&&(p.onstatechange=()=>{const g=o==null?void 0:o.iceTransport.state;var b;g&&((b=this.onICETransportStateChange)===null||b===void 0||b.call(this,g))},p.getSelectedCandidatePair&&(p.onselectedcandidatepairchange=()=>{if(p.getSelectedCandidatePair()){const{local:g,remote:b}=p.getSelectedCandidatePair();Gi.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:g.type,protocol:g.protocol}),", remote ").concat(JSON.stringify({candidateType:b.type,protocol:b.protocol,address:b.address,port:b.port})," )"))}}))}}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(i,o){var p;if(o||(o=this.peerConnection.getSenders().find($=>$.track===i._mediaStreamTrack)),!o)return Gi.warn("[".concat(i.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(i))return Gi.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!I_().supportSetRtpSenderParameters)return Gi.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const g={},b={};switch(i._optimizationMode){case"motion":g.degradationPreference="maintain-framerate";break;case"detail":g.degradationPreference="maintain-resolution";break;default:g.degradationPreference="balanced"}if(i._encoderConfig){var A;const{bitrateMax:$,frameRate:Vt,scaleResolutionDownBy:_r}=i._encoderConfig;$&&(b.maxBitrate=1e3*$),(VE(A=i._hints).call(A,A_.LOW_STREAM)||i.isUseScaleResolutionDownBy)&&(Vt&&(b.maxFramerate=US(Vt)),_r&&_r>=1&&(b.scaleResolutionDownBy=_r))}if(nE("DSCP_TYPE")&&dR()){var j;const $=nE("DSCP_TYPE");VE(j=["very-low","low","medium","high"]).call(j,$)&&(b.networkPriority=$)}const H=o.getParameters(),z=(p=H.encodings)===null||p===void 0?void 0:p[0];N_()&&!z&&(g.encodings=[b]),z&&Object.assign(z,b),Object.assign(H,g),Gi.debug("[".concat(i.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(H.encodings))),await o.setParameters(H)}async applySendEncodings(i,o){try{if(!I_().supportSetRtpSenderParameters||i.length!==o.length)return;for(let p=0;p{const j=p[A],H=g.mediaDescriptions.find(z=>z.attributes.mid===j);H&&(gI(H,b),S2(H,b,this.store.codec))}),q_.print(g)}mungReceiveAnswerSDP(i,o,p){const g=q_.parse(i),b=g.mediaDescriptions.find(A=>A.attributes.mid===o);return b&&(p===ME.AUDIO&&b.media.mediaType==="audio"&&AR(b),this.useXR&&fP(g)),q_.print(g)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=i=>{var o;(o=this.onFirstAudioReceived)===null||o===void 0||o.call(this,i)},this.statsFilter.onFirstVideoReceived=i=>{var o;(o=this.onFirstVideoReceived)===null||o===void 0||o.call(this,i)},this.statsFilter.onFirstAudioDecoded=i=>{var o;(o=this.onFirstAudioDecoded)===null||o===void 0||o.call(this,i)},this.statsFilter.onFirstVideoDecoded=(i,o,p)=>{var g;(g=this.onFirstVideoDecoded)===null||g===void 0||g.call(this,i,o,p)},this.statsFilter.onSelectedLocalCandidateChanged=(i,o)=>{var p;(p=this.onSelectedLocalCandidateChanged)===null||p===void 0||p.call(this,i,o)},this.statsFilter.onSelectedRemoteCandidateChanged=(i,o)=>{var p;(p=this.onSelectedRemoteCandidateChanged)===null||p===void 0||p.call(this,i,o)},this.statsFilter.onFirstVideoDecodedTimeout=i=>{var o;(o=this.onFirstVideoDecodedTimeout)===null||o===void 0||o.call(this,i)}}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(i,o){if(i.length===o.length)for(let H=0;H200&&(A=$._scalabilityMode)!==null&&A!==void 0&&A.numSpatialLayers&&((j=$._scalabilityMode)===null||j===void 0?void 0:j.numSpatialLayers)>1&&this.store.codec==="vp8"){const Vt={},_r={high:1e3*($._encoderConfig.bitrateMax-50),medium:5e4};Vt.encodings=[{rid:"m",active:!0,maxBitrate:_r.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:_r.high}];const Fi=z.sender.getParameters();await z.sender.setParameters(Object.assign(Fi,Vt))}}}async applySimulcastEncodings(i,o){if(!N_()&&i.length===o.length)for(let p=0;p200&&(b=i._scalabilityMode)!==null&&b!==void 0&&b.numSpatialLayers&&((A=i._scalabilityMode)===null||A===void 0?void 0:A.numSpatialLayers)>1)}logSDPExchange(i,o,p,g){if(nE("SDP_LOGGING"))return Gi.upload("[".concat(this.store.clientId,"] exchanging ").concat(p," ").concat(o," SDP during P2PConnection.").concat(g,` +`),i),o==="offer"?b=>{this.logSDPExchange(b,"answer",p==="local"?"remote":"local",g)}:void 0}async getRemoteSSRC(i){if(!this.remoteSDP)return;const o=this.remoteSDP.getSSRC(i);return o==null?void 0:o[0].ssrcId}setConfiguration(i){if(I_().supportPCSetConfiguration){const o=y1.resolvePCConfiguration(i);this.peerConnection.setConfiguration(o)}}};function _S(l,i,o){const p=l[i];if(typeof p!="function")throw new Error("Cannot use mutex on object property.");return o.value=async function(){const g=this.mutex,b=await g.lock("From P2PConnection.".concat(i));try{for(var A=arguments.length,j=new Array(A),H=0;H{if(!o)return p.stopCapture&&p.stopCapture();if(o.paused&&o.play(),o.videoHeight>2&&o.videoWidth>2){const $=o.videoWidth,Vt=o.videoHeight/$,_r=p.width*Vt;Math.abs(_r-p.height)>=2&&(Gi.debug("adjust low stream resolution","".concat(p.width,"x").concat(p.height," -> ").concat(p.width,"x").concat(_r)),p.height=_r)}A.drawImage(o,0,0,p.width,p.height),H.requestFrame&&H.requestFrame(),b!==l._mediaStreamTrack&&(b=l._mediaStreamTrack,o.srcObject=new MediaStream([b]))},p.stopCapture=OM(()=>p.startCapture&&p.startCapture(),g);const z=H.stop;return H.stop=()=>{z.call(H),o&&(o.remove(),o.srcObject=null,o=null),p&&(p.width=0,p.remove(),p.stopCapture&&p.stopCapture(),p.startCapture=void 0,p.stopCapture=void 0,p=null),Gi.debug("clean low stream renderer")},H}function Z5(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function _q(l){for(var i=1;i_r.payloadType.toString(10)),Vt.attributes.payloads=$.videoCodecs,Vt.attributes.extmaps=$.videoExtensions,nE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:_r,ssrcGroups:Fi}=XS([{ssrcId:w2,rtx:nE("USE_SUB_RTX")?40001:void 0}],this.cname);Vt.attributes.ssrcs=_r,Vt.attributes.ssrcGroups=Fi}if(Vt.media.mediaType==="audio"&&(Vt.media.fmts=$.audioCodecs.map(_r=>_r.payloadType.toString(10)),Vt.attributes.payloads=$.audioCodecs,Vt.attributes.extmaps=$.audioExtensions,AR(Vt),nE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:_r,ssrcGroups:Fi}=XS([{ssrcId:I2}],this.cname);Vt.attributes.ssrcs=_r,Vt.attributes.ssrcGroups=Fi}}this.sessionDesc=z,this.currentMidIndex=z.mediaDescriptions.length-1}updateRemoteRTPCapabilities(i){const o=q_.parse(t8);this._rtpCapabilities=i;const p=this.rtpCapabilities.send;for(const g of o.mediaDescriptions){if(g.attributes.iceUfrag=this._iceParameters.iceUfrag,g.attributes.icePwd=this._iceParameters.icePwd,g.attributes.fingerprints=this._dtlsParameters.fingerprints,g.attributes.candidates=this._candidates,g.attributes.setup=this.setup,g.media.mediaType==="application"&&(g.attributes.sctpPort="5000"),g.media.mediaType==="video"&&(g.media.fmts=p.videoCodecs.map(b=>b.payloadType.toString(10)),g.attributes.payloads=p.videoCodecs,g.attributes.extmaps=p.videoExtensions,nE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:b,ssrcGroups:A}=XS([{ssrcId:w2,rtx:nE("USE_SUB_RTX")?40001:void 0}],this.cname);g.attributes.ssrcs=b,g.attributes.ssrcGroups=A}if(g.media.mediaType==="audio"&&(g.media.fmts=p.audioCodecs.map(b=>b.payloadType.toString(10)),g.attributes.payloads=p.audioCodecs,g.attributes.extmaps=p.audioExtensions,nE("PRELOAD_MEDIA_COUNT")>0)){const{ssrcs:b,ssrcGroups:A}=XS([{ssrcId:I2}],this.cname);g.attributes.ssrcs=b,g.attributes.ssrcGroups=A}}this.sessionDesc=o,this.currentMidIndex=o.mediaDescriptions.length-1}preloadRemoteMedia(i){this.rtpCapabilities;const o=this.candidates,p=this.dtlsParameters,g=this.iceParameters,b=this.rtpCapabilities.send;for(let A=1;AFi.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:g.iceUfrag,icePwd:g.icePwd,unrecognized:[],candidates:o,extmaps:b.videoExtensions,fingerprints:p.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:Vt,ssrcGroups:_r,rtcpFeedbackWildcards:[],payloads:b.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*A-1)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:EP,protos:["UDP","TLS","RTP","SAVPF"],fmts:b.audioCodecs.map(Fi=>Fi.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:g.iceUfrag,icePwd:g.icePwd,unrecognized:[],candidates:o,extmaps:b.audioExtensions,fingerprints:p.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:z,ssrcGroups:$,rtcpFeedbackWildcards:[],payloads:b.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(2*A)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return q_.print(this.sessionDesc)}send(i,o,p,g){const{ssrcs:b,ssrcGroups:A}=XS(o,this.cname,nE("SYNC_GROUP")?p:void 0),j=this.findPreloadMediaDesc(b);if(j){if(N_()&&this.firefoxSsrcMidMap.set(b[0].ssrcId,j.attributes.mid),g&&(g.twcc||g.remb)){const H=this.sessionDesc.mediaDescriptions.indexOf(j);return this.sessionDesc.mediaDescriptions[H]=this.mungSendMediaDesc(j,g),{mid:j.attributes.mid,needExchangeSDP:!0}}return{mid:j.attributes.mid,needExchangeSDP:!1}}{const H=this.findAvailableMediaIndex(i,b);let z;return H===-1||H0()||z0()||BV()||H===0&&nE("USE_SUB_RTX")?(z=this.createOrRecycleSendMedia(i,b,A,"sendonly",g),this.updateBundleMids()):(z=Q_(this.sessionDesc.mediaDescriptions[H]),z.attributes.direction="sendonly",z.attributes.ssrcs=b,z.attributes.ssrcGroups=A,this.sessionDesc.mediaDescriptions[H]=this.mungSendMediaDesc(z,g)),N_()&&this.firefoxSsrcMidMap.set(b[0].ssrcId,z.attributes.mid),{mid:z.attributes.mid,needExchangeSDP:!0}}}batchSend(i){const o=i.map(b=>{let{kind:A,ssrcMsg:j,mslabel:H}=b;return this.send(A,j,H)}),p=[];let g=!1;return o.forEach(b=>{let{mid:A,needExchangeSDP:j}=b;j&&(g=!0),p.push(A)}),{mids:p,needExchangeSDP:g}}stopSending(i){const o=this.sessionDesc.mediaDescriptions.filter(p=>p.attributes.mid&&i.indexOf(p.attributes.mid)!==-1);if(o.length!==i.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");o.forEach(p=>{p.attributes.mid==="0"||N_()||H0()||z0()?p.attributes.ssrcs=[]:(p.attributes.ssrcs=[],p.attributes.direction="inactive",p.media.port="0")}),this.updateBundleMids()}mute(i){const o=this.sessionDesc.mediaDescriptions.find(p=>p.attributes.mid===i);if(!o)throw new Error("mediaDescription not found with ".concat(i," in remote SDP when calling RemoteSDP.mute."));o.attributes.direction="inactive"}unmute(i){const o=this.sessionDesc.mediaDescriptions.find(p=>p.attributes.mid===i);if(!o)throw new Error("mediaDescription not found with ".concat(i," in remote SDP when calling RemoteSDP.unmute."));o.attributes.direction="sendonly"}muteRemote(i){const o=this.sessionDesc.mediaDescriptions.filter(p=>VE(i).call(i,p.attributes.mid||""));if(o.length!==i.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");o.forEach(p=>{p.attributes.direction="inactive"})}unmuteRemote(i){const o=this.sessionDesc.mediaDescriptions.filter(p=>VE(i).call(i,p.attributes.mid||""));if(o.length!==i.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");o.forEach(p=>{p.attributes.direction="recvonly"})}receive(i,o,p,g){i.forEach((b,A)=>{this.createOrRecycleRecvMedia(b,[],"recvonly",o,p,g[A])}),this.updateBundleMids()}stopReceiving(i){const o=this.sessionDesc.mediaDescriptions.filter(p=>i.indexOf(p.attributes.mid)!==-1);if(o.length!==i.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");o.forEach(p=>{p.media.port="0",p.attributes.direction="inactive"}),this.updateBundleMids()}updateCandidates(i){i===N0.TCP?this._candidates.forEach(o=>{this._candidates.findIndex(p=>p.transport==="tcp"&&p.connectionAddress===o.connectionAddress&&p.port===o.port)===-1&&this._candidates.push(_q(_q({},o),{},{foundation:"tcpcandidate",priority:Number(o.priority)-1+"",transport:"tcp",port:Number(o.port)+90+""}))}):this._candidates=this._candidates.filter(o=>o.transport!=="tcp");for(const o of this.sessionDesc.mediaDescriptions)o.attributes.candidates=this.candidates}restartICE(i){i=Q_(i),this._iceParameters=i,this.sessionDesc.mediaDescriptions.forEach(o=>{o.attributes.iceUfrag=i.iceUfrag,o.attributes.icePwd=i.icePwd})}predictReceivingMids(i){const o=[];for(let p=0;p{const g=p.media.mediaType===i&&p.media.port!=="0"&&(p.attributes.direction==="sendonly"||p.attributes.direction==="sendrecv")&&p.attributes.ssrcs.length===0;if(N_()){if(g){const b=this.firefoxSsrcMidMap.get(o[0].ssrcId);return!(b||p.attributes.mid!=="0"&&p.attributes.mid!=="1")||!(!b||b!==p.attributes.mid)}return!1}return g})}createOrRecycleRecvMedia(i,o,p,g,b,A){const j=i._mediaStreamTrack.kind,H=this.rtpCapabilities.recv,z=mP(j,H,this.localCapabilities.send,j===ME.VIDEO?g:b),$=j===ME.VIDEO?H.videoExtensions:H.audioExtensions;this.currentMidIndex+=1;const Vt="".concat(this.currentMidIndex);let _r={media:{mediaType:j,port:EP,protos:["UDP","TLS","RTP","SAVPF"],fmts:z.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:$,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:o,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:z,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:p,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(Vt)}};_r=this.mungRecvMediaDsec(_r,i,A);const Fi=this.findFirstClosedMedia(j);if(Fi){const _l=this.sessionDesc.mediaDescriptions.indexOf(Fi);this.sessionDesc.mediaDescriptions[_l]=_r}else this.sessionDesc.mediaDescriptions.push(_r);return _r}updateRemoteCodec(i,o,p){const g=[...new Set(this._rtpCapabilities.recv.videoCodecs.map(_r=>_r.rtpMap&&_r.rtpMap.encodingName.toLowerCase()||"").filter(_r=>{var Fi;return VE(Fi=Object.keys(eI)).call(Fi,_r)}))],b=new Set(o);if(g.every(_r=>b.has(_r)))return Gi.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(o)),!1;const A=this._rtpCapabilities.recv.videoCodecs.filter(_r=>o.some(Fi=>{var _l;return VE(_l=_r.rtpMap&&_r.rtpMap.encodingName.toLowerCase()||"").call(_l,Fi)}));if(A.length===0)return Gi.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(g," codecs: ").concat(o)),!1;const j=[...new Set(A.map(_r=>_r.rtpMap&&_r.rtpMap.encodingName.toLowerCase()||""))];let H;if(Gi.debug("updateRemoteCodec, from ".concat(g," to ").concat(j)),i.length===0)H=this.sessionDesc.mediaDescriptions.filter(_r=>_r.media.mediaType==="video"&&_r.attributes.direction==="recvonly");else if(H=this.sessionDesc.mediaDescriptions.filter(_r=>_r.attributes.mid&&VE(i).call(i,_r.attributes.mid)&&_r.attributes.direction==="recvonly"),H.length!==i.length)return Gi.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(i,", codecs: ").concat(o)),!1;this._rtpCapabilities.recv.videoCodecs=A;const z=this.localCapabilities.send,$=this.rtpCapabilities.recv,Vt=mP(ME.VIDEO,$,z,p);return H.forEach(_r=>{const Fi=Vt.map(_l=>_l.payloadType.toString(10));Gi.debug("updateRemoteCodec mid: ".concat(_r.attributes.mid,", from ").concat(_r.attributes.payloads," to ").concat(Vt)),_r.attributes.payloads=Vt,_r.media.fmts=Fi}),!0}createOrRecycleSendMedia(i,o,p,g,b){const A=this.rtpCapabilities.send,j=i===ME.VIDEO?A.videoCodecs:A.audioCodecs,H=i===ME.VIDEO?A.videoExtensions:A.audioExtensions;this.currentMidIndex+=1;const z="".concat(this.currentMidIndex);let $={media:{mediaType:i,port:EP,protos:["UDP","TLS","RTP","SAVPF"],fmts:j.map(_r=>_r.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:H,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:o,ssrcGroups:p,rtcpFeedbackWildcards:[],payloads:j,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:g,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(z)}};$=this.mungSendMediaDesc($,b);const Vt=this.findFirstClosedMedia(i);if(Vt){const _r=this.sessionDesc.mediaDescriptions.indexOf(Vt);this.sessionDesc.mediaDescriptions[_r]=$}else this.sessionDesc.mediaDescriptions.push($);return $}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(i=>i.media.port!=="0").map(i=>i.attributes.mid)}mungRecvMediaDsec(i,o,p){const g=Q_(i);return y2(g),gI(g,o),b2(g,o),L5(g),dP(g,p,this.localCapabilities.send),g}mungSendMediaDesc(i,o){const p=Q_(i);return dP(p,o,this.localCapabilities.recv),AR(p),p}updateRecvMedia(i,o){const p=this.sessionDesc.mediaDescriptions.findIndex(g=>g.attributes.mid===i);if(p!==-1){const g=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[p],o);this.sessionDesc.mediaDescriptions[p]=g}}bumpMid(i){this.currentMidIndex+=i}findFirstClosedMedia(i){return this.sessionDesc.mediaDescriptions.find(o=>N_()?o.media.port==="0"&&o.media.mediaType===i:o.media.port==="0")}findPreloadMediaDesc(i){return this.sessionDesc.mediaDescriptions.find(o=>{var p;return((p=o.attributes)===null||p===void 0||(p=p.ssrcs[0])===null||p===void 0?void 0:p.ssrcId)===i[0].ssrcId})}getSSRC(i){var o;return(o=this.sessionDesc.mediaDescriptions.find(p=>p.attributes.mid===i))===null||o===void 0?void 0:o.attributes.ssrcs}}function e8(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function vP(l){for(var i=1;i_r.media.mediaType==="audio");z&&AR(z),this.useXR&&fP(H);const $=q_.print(H),Vt=this.logSDPExchange($||"","offer","local","connect");await this.peerConnection.setLocalDescription({type:"offer",sdp:$}),Vt==null||Vt(j),await this.peerConnection.setRemoteDescription({type:"answer",sdp:j})}catch(j){throw new hE(_p.EXCHANGE_SDP_FAILED,"NV.connect failed; ".concat(j.toString()))}}async updateRemoteRTPCapabilities(i,o){let p;this.remoteCodecs=o,this.localCapabilities&&(p=pP(this.localCapabilities));const g=[...new Set(p&&p.send.videoCodecs.map(b=>b.rtpMap&&b.rtpMap.encodingName.toLowerCase()||"").filter(b=>{var A;return VE(A=Object.keys(eI)).call(A,b)}))];if(jE.updateRemoteRTPCapabilities(this.store.sessionId,{mids:i,localCodecs:g,remoteCodecs:this.remoteCodecs}),!this.remoteSDP)return void Gi.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(g,", codecs: ").concat(o));if(this.remoteSDP.updateRemoteCodec(i,o,this.store.codec)){const b=await this.peerConnection.createOffer(),A=this.logSDPExchange(b.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(b);const j=this.remoteSDP.toString();A==null||A(j),await this.peerConnection.setRemoteDescription({type:"answer",sdp:j})}else Gi.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")}async updateRemoteConnect(i){var o,p,g,b;(o=this.remoteSDP)===null||o===void 0||o.updateRemoteRTPCapabilities(i),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&((b=this.remoteSDP)===null||b===void 0||b.updateRemoteCodec([],this.remoteCodecs,this.store.codec)),(p=this.remoteSDP)===null||p===void 0||p.preloadRemoteMedia(2);const A=(g=this.remoteSDP)===null||g===void 0?void 0:g.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:A});const j=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(j),Gi.debug("[NVExtentionsConnection] updateRemoteRTPCapabilities by exchanging SDP.")}send(i,o,p){var g=this;return JS(function*(){const b=yield d_(g.mutex.lock("From NVExtentionsConnection.send"));try{if(!g.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.send before remote SDP created");const A=[];i.forEach(_u=>{const _h=g.peerConnection.addTransceiver(_u._mediaStreamTrack,{direction:"sendonly"});A.push(_h)}),N_()&&nE("SIMULCAST")===!0&&(yield d_(g.applySimulcastForFirefox(A,i)));const j=yield d_(g.peerConnection.createOffer()),H=g.remoteSDP.predictReceivingMids(i.length),z=g.mungSendOfferSDP(j.sdp,i,H),$=q_.parse(z),Vt=H.map(_u=>{const _h=$.mediaDescriptions.find(_g=>_g.attributes.mid===_u);if(!_h)throw new Error("Cannot extract ssrc from mediaDescription.");return k5(_h,nE("USE_PUB_RTX"))});let _r;try{_r=yield Vt}catch(_u){_r=[],g.remoteSDP.receive(i,o,p,_r);const _h=g.remoteSDP.toString();throw yield d_(g.peerConnection.setLocalDescription({type:"offer",sdp:z})),yield d_(g.peerConnection.setRemoteDescription({type:"answer",sdp:_h})),yield d_(g.stopSending(H,!0)),_u}g.remoteSDP.receive(i,o,p,_r);const Fi=g.remoteSDP.toString(),_l=g.logSDPExchange(z,"offer","local","send");return yield d_(g.peerConnection.setLocalDescription({type:"offer",sdp:z})),yield d_(g.applySimulcastEncodings(A,i)),yield d_(g.applySendEncodings(A,i)),_l==null||_l(Fi),yield d_(g.peerConnection.setRemoteDescription({type:"answer",sdp:Fi})),A.map((_u,_h)=>{const _g=H[_h];return{localSSRC:Vt[_h],id:_g,transceiver:_u}})}catch(A){throw A instanceof hE?A:new hE(_p.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.send failed; ".concat(A.toString()))}finally{b()}})()}async stopSending(i,o){const p=o?void 0:await this.mutex.lock("From NVExtentionsConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.stopSending before remote SDP created");const g=this.peerConnection.getTransceivers().filter(H=>i.indexOf(H.mid)!==-1);if(g.length!==i.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call NVExtentionsConnection.stopSending.");g.map(H=>{var z;H.direction="inactive",(z=H.stop)===null||z===void 0||z.call(H)});const b=await this.peerConnection.createOffer(),A=this.logSDPExchange(b.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(b),this.remoteSDP.stopReceiving(i);const j=this.remoteSDP.toString();A==null||A(j),await this.peerConnection.setRemoteDescription({type:"answer",sdp:j})}catch(g){throw new hE(_p.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.stopSending failed; ".concat(g.toString()))}finally{p&&p()}}async createDataChannels(i,o){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.createDataChannels before remote SDP created");let p=this.dataStreamChannelMap.get(i);return p&&p.readyState==="open"?Gi.debug("[P2PConnection] Channels are already available and can be reused directly."):(p=this.peerConnection.createDataChannel("datastream-channel",{ordered:!1,maxRetransmits:nE("DATASTREAM_MAX_RETRANSMITS")}),p.binaryType="arraybuffer",this.dataStreamChannelMap.set(i,p)),void o.forEach(g=>{g._updateOriginDataChannel(p)})}catch(p){throw p instanceof hE?p:new hE(_p.DATACHANNEL_FAILED,"NVExtentionsConnection.createDataChannels failed; ".concat(p.toString()))}}async stopDataChannels(i){try{const o=this.dataStreamChannelMap.get(i);return o==null||o.close(),void this.dataStreamChannelMap.delete(i)}catch(o){throw o instanceof hE?o:new hE(_p.DATACHANNEL_FAILED,"NVExtentionsConnection.stopDataChannels failed; ".concat(o.toString()))}}async receive(i,o,p,g){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.receive ".concat(i," before remoteSDP created."));const{mid:b,needExchangeSDP:A}=this.remoteSDP.send(i,o,p,g);if(A){const H=this.remoteSDP.toString(),z=this.logSDPExchange(H,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:H});const $=await this.peerConnection.createAnswer(),Vt=this.mungReceiveAnswerSDP($.sdp,b,i);z==null||z(Vt||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:Vt}),Gi.debug("[NVExtentionsConnection] receive ".concat(i," by exchanging SDP."))}else Gi.debug("[NVExtentionsConnection] receive ".concat(i," no need to exchange SDP."));const j=this.peerConnection.getTransceivers().find(H=>H.mid===b);if(!j)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:j.receiver.track,id:b}}catch(b){throw new hE(_p.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.receive failed; ".concat(b.toString()))}}async batchReceive(i){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.batchReceive before remoteSDP created.");const{mids:o,needExchangeSDP:p}=this.remoteSDP.batchSend(i);if(p){const g=this.remoteSDP.toString(),b=this.logSDPExchange(g,"offer","remote","receive");await this.peerConnection.setRemoteDescription({type:"offer",sdp:g});const A=await this.peerConnection.createAnswer();b==null||b(A.sdp||""),await this.peerConnection.setLocalDescription(A),Gi.debug("[NVExtentionsConnection] batchReceive by exchanging SDP.")}else Gi.debug("[NVExtentionsConnection] batchReceive no need to exchange SDP.");return o.map(g=>{const b=this.peerConnection.getTransceivers().find(A=>A.mid===g);if(!b)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:b.receiver.track,id:g}})}catch(o){throw new hE(_p.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.receive failed; ".concat(o.toString()))}}async stopReceiving(i){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(i);const o=this.remoteSDP.toString(),p=this.logSDPExchange(o,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const g=await this.peerConnection.createAnswer();p==null||p(g.sdp||""),await this.peerConnection.setLocalDescription(g)}catch(o){throw new hE(_p.EXCHANGE_SDP_FAILED,"NVExtentionsConnection stopReceiving failed; ".concat(o.toString()))}}async muteRemote(i){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.muteRemote mid=".concat(i," before remote SDP created."));this.remoteSDP.mute(i);const o=this.remoteSDP.toString(),p=this.logSDPExchange(o,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const g=await this.peerConnection.createAnswer();p==null||p(g.sdp||""),await this.peerConnection.setLocalDescription(g)}catch(o){throw new hE(_p.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.muteRemote failed; ".concat(o.toString()))}}async unmuteRemote(i){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.unmuteRemote mid=".concat(i," before remote SDP created."));this.remoteSDP.unmute(i);const o=this.remoteSDP.toString(),p=this.logSDPExchange(o,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const g=await this.peerConnection.createAnswer();p==null||p(g.sdp||""),await this.peerConnection.setLocalDescription(g)}catch(o){throw new hE(_p.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteRemote failed; ".concat(o.toString()))}}async muteLocal(i){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.muteLocal before remote SDP created.");const o=this.peerConnection.getTransceivers().filter(A=>A.mid&&i.indexOf(A.mid)!==-1);if(o.length!==i.length)throw new Error("Transceivers' length doesn't match mids' length.");o.map(A=>{A.direction="inactive"});const p=await this.peerConnection.createOffer(),g=this.logSDPExchange(p.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(p),this.remoteSDP.muteRemote(i);const b=this.remoteSDP.toString();g==null||g(b),await this.peerConnection.setRemoteDescription({type:"answer",sdp:b})}catch(o){throw new hE(_p.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.muteLocal failed; ".concat(o.toString()))}}async unmuteLocal(i){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.unmuteLocal before remote SDP created.");const o=this.peerConnection.getTransceivers().filter(A=>A.mid&&i.indexOf(A.mid)!==-1);if(o.length!==i.length)throw new Error("Transceivers' length doesn't match mids' length.");o.map(async(A,j)=>{A.direction="sendonly"});const p=await this.peerConnection.createOffer(),g=this.logSDPExchange(p.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(p),this.remoteSDP.unmuteRemote(i);const b=this.remoteSDP.toString();g==null||g(b),await this.peerConnection.setRemoteDescription({type:"answer",sdp:b})}catch(o){throw new hE(_p.EXCHANGE_SDP_FAILED,"NVExtentionsConnection.unmuteLocal failed; ".concat(o.toString()))}}restartICE(i){var o=this;return JS(function*(){const p=yield d_(o.mutex.lock("From NVExtentionsConnection.restartICE"));try{if(!o.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");if(I_().supportPCSetConfiguration){const z=o.peerConnection.getConfiguration(),$=i===N0.RELAY?"relay":"all";z.iceTransportPolicy!==$&&(Gi.debug("restartICE change iceTransportPolicy from [".concat(z.iceTransportPolicy,"] to [").concat($,"]")),z.iceTransportPolicy=$,o.peerConnection.setConfiguration(z))}else if(i===N0.RELAY)return;i!==N0.RELAY&&o.remoteSDP.updateCandidates(i);const g=yield d_(o.peerConnection.createOffer({iceRestart:!0}));if(!g.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const b=mI(g.sdp),{remoteIceParameters:A}=yield b.iceParameters;o.remoteSDP.restartICE(A);const j=o.remoteSDP.toString(),H=o.logSDPExchange(g.sdp||"","offer","local","restartICE");yield d_(o.peerConnection.setLocalDescription(g)),H==null||H(j),yield d_(o.peerConnection.setRemoteDescription({type:"answer",sdp:j}))}catch(g){Gi.warning("restart ICE failed, abort operation",g)}finally{p()}})()}close(){var i;(i=this.onConnectionStateChange)===null||i===void 0||i.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(i){return this.statsFilter.getVideoIsReady(i)}async updateEncoderConfig(i,o){try{if(!this.remoteSDP)throw new Error("Cannot call NVExtentionsConnection.updateEncoderConfig before remote SDP created.");const p=await this.peerConnection.createOffer(),g=this.mungSendOfferSDP(p.sdp,[o],[i]);this.remoteSDP.updateRecvMedia(i,o);const b=this.remoteSDP.toString(),A=this.logSDPExchange(g,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:g}),A==null||A(b),await this.peerConnection.setRemoteDescription({type:"answer",sdp:b})}catch(p){throw new hE(_p.EXCHANGE_SDP_FAILED,p.toString())}}async updateSendParameters(i,o){const p=this.peerConnection.getTransceivers().filter(g=>g.mid===i);p.length===1&&(this.isVP8Simulcast(o)?N_()||await this.applySimulcastEncodings(p,[o]):await this.applySendEncodings(p,[o]))}setStatsRemoteVideoIsReady(i,o){this.statsFilter.setVideoIsReady2(i,o)}async replaceTrack(i,o){const p=this.peerConnection.getTransceivers().find(g=>g.mid===o);p&&await p.sender.replaceTrack(i._mediaStreamTrack)}getP2PConnectionParams(){var i;if((i=this.peerConnection.currentLocalDescription)===null||i===void 0||!i.sdp||!this.localCapabilities)throw new Error;return vP(vP({},mI(this.peerConnection.currentLocalDescription.sdp)),{},{rtpCapabilities:this.localCapabilities})}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var i;(i=this.onICEConnectionStateChange)===null||i===void 0||i.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var i;(i=this.onConnectionStateChange)===null||i===void 0||i.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=i=>{i.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,Gi.debug("[pc-".concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,Gi.debug("[pc-".concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},nE("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(i){const o={iceServers:[]};return i.iceServers?o.iceServers=i.iceServers:i.turnServer&&i.turnServer.mode!=="off"&&(VI(i.turnServer.servers)?o.iceServers=i.turnServer.servers:(o.iceServers&&o.iceServers.push(...L0.turnServerConfigToIceServers(i.turnServer.servers)),nE("USE_TURN_SERVER_OF_GATEWAY")&&o.iceServers&&i.turnServer.serversFromGateway&&o.iceServers.push(...L0.turnServerConfigToIceServers(i.turnServer.serversFromGateway)),nE("FORCE_TURN_TCP")?o.iceTransportPolicy="relay":i.turnServer.servers.concat(i.turnServer.serversFromGateway||[]).forEach(p=>{p.forceturn&&(o.iceTransportPolicy="relay")}))),o}static turnServerConfigToIceServers(i){const o=[];return i.forEach(p=>{p.security?p.tcpport&&o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turns:".concat(d1(p.turnServerURL),":").concat(p.tcpport,"?transport=tcp")}):(p.udpport&&!nE("FORCE_TURN_TCP")&&o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turn:".concat(p.turnServerURL,":").concat(p.udpport,"?transport=udp")}),p.tcpport&&o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turn:".concat(p.turnServerURL,":").concat(p.tcpport,"?transport=tcp")}))}),o}async applySendEncodings(i,o){try{if(!I_().supportSetRtpSenderParameters||i.length!==o.length)return;for(let Vt=0;Vt1&&(_u.scaleResolutionDownBy=Fi._encoderConfig.scaleResolutionDownBy)),nE("DSCP_TYPE")&&dR()){var $;const eE=nE("DSCP_TYPE");VE($=["very-low","low","medium","high"]).call($,eE)&&(_u.networkPriority=eE)}const _h=_r.sender.getParameters(),_g=(b=_h.encodings)===null||b===void 0?void 0:b[0];N_()&&!_g&&(_l.encodings=[_u]),_g&&Object.assign(_g,_u),Object.assign(_h,_l),await _r.sender.setParameters(_h)}}}catch{Gi.debug("Apply RTPSendEncodings failed.")}}mungSendOfferSDP(i,o,p){const g=q_.parse(i);return o.forEach((b,A)=>{const j=p[A],H=g.mediaDescriptions.find(z=>z.attributes.mid===j);H&&(gI(H,b),S2(H,b,this.store.codec))}),q_.print(g)}mungReceiveAnswerSDP(i,o,p){const g=q_.parse(i),b=g.mediaDescriptions.find(A=>A.attributes.mid===o);return b&&p===ME.AUDIO&&b.media.mediaType==="audio"&&AR(b),this.useXR&&fP(g),q_.print(g)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=i=>{var o;(o=this.onFirstAudioReceived)===null||o===void 0||o.call(this,i)},this.statsFilter.onFirstVideoReceived=i=>{var o;(o=this.onFirstVideoReceived)===null||o===void 0||o.call(this,i)},this.statsFilter.onFirstAudioDecoded=i=>{var o;(o=this.onFirstAudioDecoded)===null||o===void 0||o.call(this,i)},this.statsFilter.onFirstVideoDecoded=(i,o,p)=>{var g;(g=this.onFirstVideoDecoded)===null||g===void 0||g.call(this,i,o,p)},this.statsFilter.onSelectedLocalCandidateChanged=(i,o)=>{var p;(p=this.onSelectedLocalCandidateChanged)===null||p===void 0||p.call(this,i,o)},this.statsFilter.onSelectedRemoteCandidateChanged=(i,o)=>{var p;(p=this.onSelectedRemoteCandidateChanged)===null||p===void 0||p.call(this,i,o)},this.statsFilter.onFirstVideoDecodedTimeout=i=>{var o;(o=this.onFirstVideoDecodedTimeout)===null||o===void 0||o.call(this,i)}}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(i,o){if(i.length===o.length)for(let H=0;H200&&(A=$._scalabilityMode)!==null&&A!==void 0&&A.numSpatialLayers&&((j=$._scalabilityMode)===null||j===void 0?void 0:j.numSpatialLayers)>1&&this.store.codec==="vp8"){const Vt={},_r={high:1e3*($._encoderConfig.bitrateMax-50),medium:5e4};Vt.encodings=[{rid:"m",active:!0,maxBitrate:_r.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:_r.high}];const Fi=z.sender.getParameters();await z.sender.setParameters(Object.assign(Fi,Vt))}}}async applySimulcastEncodings(i,o){if(!N_()&&i.length===o.length)for(let p=0;p200&&(b=i._scalabilityMode)!==null&&b!==void 0&&b.numSpatialLayers&&((A=i._scalabilityMode)===null||A===void 0?void 0:A.numSpatialLayers)>1)}logSDPExchange(i,o,p,g){if(nE("SDP_LOGGING"))return Gi.upload("exchanging ".concat(p," ").concat(o," SDP during NVExtentionsConnection.").concat(g,` +`),i),o==="offer"?b=>{this.logSDPExchange(b,"answer",p==="local"?"remote":"local",g)}:void 0}async getRemoteSSRC(i){if(!this.remoteSDP)return;const o=this.remoteSDP.getSSRC(i);return o==null?void 0:o[0].ssrcId}setConfiguration(i){if(I_().supportPCSetConfiguration){const o=L0.resolvePCConfiguration(i);this.peerConnection.setConfiguration(o)}}}function hS(l,i,o){const p=l[i];if(typeof p!="function")throw new Error("Cannot use mutex on object property.");return o.value=async function(){const g=this.mutex,b=await g.lock("From NVExtentionsConnection.".concat(i));try{for(var A=arguments.length,j=new Array(A),H=0;H{const z=setTimeout(()=>{this.closeSignal(),H(new hE(_p.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(p))))},2e3);this.dataChannel.onopen=()=>{if(this.dataChannel.readyState==="open")return clearTimeout(z),void j()},this.dataChannel.onerror=$=>{this.closeSignal(),H($)}}),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}async updateRemoteRTPCapabilities(i,o){return this._p2pConnection.updateRemoteRTPCapabilities(i,o)}send(i,o,p){var g=this;return JS(function*(){const b=yield d_(g.mutex.lock("From DataChannelConnection.send"));try{return yield*lP(n8(g._p2pConnection.send(i,o,p)))}finally{b()}})()}async stopSending(i,o){return this._p2pConnection.stopSending(i,o)}async createDataChannels(i,o){return this._p2pConnection.createDataChannels(i,o)}async stopDataChannels(i){return this._p2pConnection.stopDataChannels(i)}async receive(i,o,p,g){return this._nvMedia?(Gi.debug("[DataChannelConnection] receive ".concat(i," by DataChannel.")),await this._nvMedia.reveiveByRTCMedia(i,o,this.cname)):(Gi.debug("[DataChannelConnection] receive ".concat(i," by WebRTC.")),await this._p2pConnection.receive(i,o,p,g))}async batchReceive(i){return[...await this._p2pConnection.batchReceive(i)]}async stopReceiving(i){return await this._p2pConnection.stopReceiving(i)}async muteRemote(i){return await this._p2pConnection.muteRemote(i)}async unmuteRemote(i){return await this._p2pConnection.unmuteRemote(i)}async muteLocal(i){return await this._p2pConnection.muteLocal(i)}async unmuteLocal(i){return await this._p2pConnection.unmuteLocal(i)}restartICE(i){var o=this;return JS(function*(){return yield*lP(n8(o._p2pConnection.restartICE(i)))})()}close(){var i;(i=this._nvMedia)===null||i===void 0||i.close(),this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection)}getStats(){return this._p2pConnection.getStats()}getRemoteVideoIsReady(i){return this._p2pConnection.getRemoteVideoIsReady(i)}updateRemoteConnect(i){var o;(o=this._nvMedia)===null||o===void 0||o.setRemoteRtpCapabilities(i),this._p2pConnection.updateRemoteConnect(i)}async updateEncoderConfig(i,o){return await this._p2pConnection.updateEncoderConfig(i,o)}async updateSendParameters(i,o){return await this._p2pConnection.updateSendParameters(i,o)}setStatsRemoteVideoIsReady(i,o){this._p2pConnection.setStatsRemoteVideoIsReady(i,o)}async replaceTrack(i,o){return await this._p2pConnection.replaceTrack(i,o)}async getRemoteSSRC(i){return this._p2pConnection.getRemoteSSRC(i)}logSDPExchange(i,o,p,g){if(nE("SDP_LOGGING"))return Gi.upload("exchanging ".concat(p," ").concat(o," SDP during DataChannelConnection.").concat(g,` +`),i),o==="offer"?b=>{this.logSDPExchange(b,"answer",p==="local"?"remote":"local",g)}:void 0}static resolvePCConfiguration(i){const o={iceServers:[]};return i.iceServers?o.iceServers=i.iceServers:i.turnServer&&i.turnServer.mode!=="off"&&(VI(i.turnServer.servers)?o.iceServers=i.turnServer.servers:(o.iceServers&&o.iceServers.push(...u0.turnServerConfigToIceServers(i.turnServer.servers)),nE("USE_TURN_SERVER_OF_GATEWAY")&&o.iceServers&&i.turnServer.serversFromGateway&&o.iceServers.push(...u0.turnServerConfigToIceServers(i.turnServer.serversFromGateway)),nE("FORCE_TURN_TCP")?o.iceTransportPolicy="relay":i.turnServer.servers.concat(i.turnServer.serversFromGateway||[]).forEach(p=>{p.forceturn&&(o.iceTransportPolicy="relay")}))),o}static turnServerConfigToIceServers(i){const o=[];return i.forEach(p=>{p.security?p.tcpport&&o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turns:".concat(d1(p.turnServerURL),":").concat(p.tcpport,"?transport=tcp")}):(p.udpport&&!nE("FORCE_TURN_TCP")&&o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turn:".concat(p.turnServerURL,":").concat(p.udpport,"?transport=udp")}),p.tcpport&&o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turn:".concat(p.turnServerURL,":").concat(p.tcpport,"?transport=tcp")}))}),o}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=i=>{var o;return(o=this.onICEConnectionStateChange)===null||o===void 0?void 0:o.call(this,i)},this._p2pConnection.onConnectionStateChange=i=>{var o;return(o=this.onConnectionStateChange)===null||o===void 0?void 0:o.call(this,i)},this._p2pConnection.onDTLSTransportStateChange=i=>{var o;return(o=this.onDTLSTransportStateChange)===null||o===void 0?void 0:o.call(this,i)},this._p2pConnection.onDTLSTransportError=i=>{var o;return(o=this.onDTLSTransportError)===null||o===void 0?void 0:o.call(this,i)},this._p2pConnection.onICETransportStateChange=i=>{var o;return(o=this.onICETransportStateChange)===null||o===void 0?void 0:o.call(this,i)},this._p2pConnection.onFirstAudioReceived=i=>{var o;return(o=this.onFirstAudioReceived)===null||o===void 0?void 0:o.call(this,i)},this._p2pConnection.onFirstVideoReceived=i=>{var o;return(o=this.onFirstVideoReceived)===null||o===void 0?void 0:o.call(this,i)},this._p2pConnection.onFirstAudioDecoded=i=>{var o;return(o=this.onFirstAudioDecoded)===null||o===void 0?void 0:o.call(this,i)},this._p2pConnection.onFirstVideoDecoded=(i,o,p)=>{var g;return(g=this.onFirstVideoDecoded)===null||g===void 0?void 0:g.call(this,i,o,p)},this._p2pConnection.onFirstVideoDecodedTimeout=i=>{var o;return(o=this.onFirstVideoDecodedTimeout)===null||o===void 0?void 0:o.call(this,i)},this._p2pConnection.onSelectedLocalCandidateChanged=(i,o)=>{var p;return(p=this.onSelectedLocalCandidateChanged)===null||p===void 0?void 0:p.call(this,i,o)},this._p2pConnection.onSelectedRemoteCandidateChanged=(i,o)=>{var p;return(p=this.onSelectedRemoteCandidateChanged)===null||p===void 0?void 0:p.call(this,i,o)}}closeSignal(){this.dataChannel.close(),this.peerConnection.close()}unbindConnectionEvents(i){i.onConnectionStateChange=void 0,i.onICEConnectionStateChange=void 0,i.onICETransportStateChange=void 0,i.onDTLSTransportStateChange=void 0,i.onDTLSTransportError=void 0,i.onFirstAudioDecoded=void 0,i.onFirstAudioReceived=void 0,i.onFirstVideoDecoded=void 0,i.onFirstVideoReceived=void 0,i.onSelectedLocalCandidateChanged=void 0,i.onSelectedRemoteCandidateChanged=void 0,i.onFirstVideoDecodedTimeout=void 0}setConfiguration(i){this._p2pConnection.setConfiguration(i)}}function FS(l,i,o){const p=l[i];if(typeof p!="function")throw new Error("Cannot use mutex on object property.");return o.value=async function(){const g=this.mutex,b=await g.lock("From DataChannelConnection.".concat(i));try{for(var A=arguments.length,j=new Array(A),H=0;H{var o;const p=(o=this.requestStats)===null||o===void 0?void 0:o.call(this);if(p){const b=i5(p);if(i){var g;const A=(g=this.requestStats)===null||g===void 0?void 0:g.call(this,!0);if(A){const j=i5(A);b.connectionType+=j.connectionType<<3}b.connectionType+=110}else b.connectionType+=100;sT(()=>{var A;(A=this.requestUpload)===null||A===void 0||A.call(this,uS.TRANSPORT_STATS,b)})}},1e3))}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.extensionUsageStatsUploadInterval&&window.clearInterval(this.extensionUsageStatsUploadInterval);const i=new Map;this.extensionUsageStatsUploadInterval=window.setInterval(async()=>{var o,p,g;const b=Date.now(),A={connectionInterval:nE("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:b};let j=[];const H=((o=this.requestAllTracks)===null||o===void 0?void 0:o.call(this))||[];for(const _r of H)!_r.muted&&_r.enabled&&(j=j.concat(await _r.getProcessorUsage()));const z=((p=this.requestRemoteMedia)===null||p===void 0?void 0:p.call(this))||[];for(const[_r,Fi]of z)Fi.has(ME.VIDEO)&&_r.videoTrack&&(j=j.concat(await _r.videoTrack.getProcessorUsage())),Fi.has(ME.AUDIO)&&_r.audioTrack&&(j=j.concat(await _r.audioTrack.getProcessorUsage()));if(j.length===0)return;A.details=function(_r,Fi){const _l={};for(const{id:eE,value:oE,level:SE,direction:vE}of _r){var _u;const fE=(_u=Fi.get(eE))!==null&&_u!==void 0?_u:0,mE=oE===2?fE+nE("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:fE;var _h,_g;Fi.set(eE,mE),_l[eE]?(oE===2&&(_l[eE].value=oE),SE>_l[eE].level&&(_l[eE].level=SE),vE==="remote"&&(_l[eE].remoteUidCount+=1),_l[eE].totalTs=(_h=Fi.get(eE))!==null&&_h!==void 0?_h:0):_l[eE]={value:oE,level:SE,remoteUidCount:vE==="local"?0:1,totalTs:(_g=Fi.get(eE))!==null&&_g!==void 0?_g:0}}return Object.keys(_l).map(eE=>{const{level:oE,value:SE,totalTs:vE}=_l[eE];return{id:eE,level:oE,value:SE,totalTs:vE}})}(j,i);const $=Date.now(),Vt=$>b?$:b+1;(g=this.requestUpload)===null||g===void 0||g.call(this,uS.EXTENSION_USAGE_STATS,{usageStats:A,sendTs:Vt})},nE("EXTENSION_USAGE_UPLOAD_INTERVAL"))}startUploadUplinkStats(){this.uploadUnplinkStarted||(this.uploadUnplinkStarted=!0,this.uplinkStatsUploadInterval&&window.clearInterval(this.uplinkStatsUploadInterval),this.uplinkStatsUploadInterval=window.setInterval(()=>{var i;const o=(i=this.requestStats)===null||i===void 0?void 0:i.call(this);o&&(this.uploadUplinkStats(o),this.lastStats=o)},3e3),this.uplinkRelatedStatsUploadInterval&&window.clearInterval(this.uplinkRelatedStatsUploadInterval),this.uplinkRelatedStatsUploadInterval=window.setInterval(()=>{var i;const o=(i=this.requestStats)===null||i===void 0?void 0:i.call(this);o&&this.uploadRelatedUplinkStats(o,this.lastStats),this.lastStats=o},1e3),this.uplinkDenoiserStatsUploadInterval&&window.clearInterval(this.uplinkDenoiserStatsUploadInterval),this.uplinkDenoiserStatsUploadInterval=window.setInterval(()=>{var i;const o=(i=this.requestAllTracks)===null||i===void 0?void 0:i.call(this);o&&this.uploadDenoiserStats(o)},2e3),this.uplinkExtensionStatsUploadInterval&&window.clearInterval(this.uplinkExtensionStatsUploadInterval),this.uplinkExtensionStatsUploadInterval=window.setInterval(()=>{var i;const o=(i=this.requestAllTracks)===null||i===void 0?void 0:i.call(this);o&&this.uploadExtensionStats(o)},2e3))}uploadUplinkStats(i){var o;(((o=this.requestLocalMedia)===null||o===void 0?void 0:o.call(this))||[]).forEach(p=>{let[g,{track:b,ssrcs:A}]=p;switch(g){case TE.LocalVideoLowTrack:case TE.LocalVideoTrack:{const j=function($,Vt,_r){var Fi;const _l=Vt.videoSend.find(_h=>_h.ssrc===$);if(!_l)return null;const _u={id:T_(10,""),timestamp:new Date(Vt.timestamp).toISOString(),mediaType:"video",type:"ssrc",ssrc:_l.ssrc.toString()};switch(_u.A_vstd=_r._originMediaStreamTrack&&!_r._originMediaStreamTrack.enabled||_r._mediaStreamTrack&&!_r._mediaStreamTrack.enabled?"1":"0",_l.sentFrame&&(_u.A_fhs=_l.sentFrame.height.toString(),_u.A_frs=_l.sentFrame.frameRate.toString(),_u.A_fws=_l.sentFrame.width.toString()),_l.adaptionChangeReason){case"none":_u.A_ac="0";break;case"cpu":_u.A_ac="1";break;case"bandwidth":_u.A_ac="2";break;case"other":_u.A_ac="3"}return _u.A_lvps=wM[_r._player?_r._player.videoElementStatus:"uninit"].toString(),_u.A_nr=(Fi=_l.nacksCount)===null||Fi===void 0?void 0:Fi.toString(),_l.avgEncodeMs&&(_u.A_aem=_l.avgEncodeMs.toFixed(0).toString()),nE("P2P")&&(_l.bytes&&(_u.bytesSent=_l.bytes.toString()),typeof _l.packetsLost=="number"&&(_u.packetsLost=_l.packetsLost.toString()),_l.packets&&(_u.packetsSent=_l.packets.toString())),_u}(A[0].ssrcId,i,b),H=g===TE.LocalVideoTrack?function($,Vt,_r){var Fi,_l,_u,_h,_g,eE,oE,SE;const vE=Vt.videoSend.find(OE=>OE.ssrc===$);if(!vE)return null;const fE={id:T_(10,""),timestamp:new Date(Vt.timestamp).toISOString(),mediaType:"video",type:"ssrc",ssrc:vE.ssrc.toString()},mE=(Fi=(_l=(_u=vE.inputFrame)===null||_u===void 0?void 0:_u.height)!==null&&_l!==void 0?_l:_r==null?void 0:_r._videoHeight)!==null&&Fi!==void 0?Fi:0,EE=(_h=(_g=(eE=vE.inputFrame)===null||eE===void 0?void 0:eE.width)!==null&&_g!==void 0?_g:_r==null?void 0:_r._videoWidth)!==null&&_h!==void 0?_h:0,PE=(oE=(SE=vE.inputFrame)===null||SE===void 0?void 0:SE.frameRate)!==null&&oE!==void 0?oE:0;return mE&&(fE.A_fhi=mE+""),EE&&(fE.A_fwi=EE+""),PE&&(fE.A_fri=PE+""),fE}(A[0].ssrcId,i,b):null;j&&sT(()=>{var $;return($=this.requestUpload)===null||$===void 0?void 0:$.call(this,uS.PUBLISH_STATS,{stream_type:g===TE.LocalVideoLowTrack?"low":"high",stats:i8(i8({},j),H)})});const z=function($){const Vt={id:"bweforvideo",timestamp:new Date($.timestamp).toISOString(),type:"VideoBwe"};return $.bitrate.retransmit&&(Vt.A_rb=$.bitrate.retransmit.toString()),$.bitrate.targetEncoded&&(Vt.A_teb=$.bitrate.targetEncoded.toString()),Vt.A_aeb=$.bitrate.actualEncoded.toString(),Vt.A_tb=$.bitrate.transmit.toString(),$.sendBandwidth!==void 0&&(Vt.A_asb=$.sendBandwidth.toString()),Vt}(i);z&&setTimeout(()=>{var $;return($=this.requestUpload)===null||$===void 0?void 0:$.call(this,uS.PUBLISH_STATS,{stream_type:g===TE.LocalVideoLowTrack?"low":"high",stats:z})},1e3);break}case TE.LocalAudioTrack:{const j=function(H,z,$){const Vt=z.audioSend.find(Fi=>Fi.ssrc===H);if(!Vt)return null;const _r={id:T_(10,""),timestamp:new Date(z.timestamp).toISOString(),mediaType:"audio",type:"ssrc",ssrc:Vt.ssrc.toString()};return _r.A_astd=$._originMediaStreamTrack&&!$._originMediaStreamTrack.enabled||$._mediaStreamTrack&&!$._mediaStreamTrack.enabled?"1":"0",Vt.inputLevel?_r.A_ail=Math.round(100*Vt.inputLevel).toString():_r.A_ail=Math.round(100*$._source.getAccurateVolumeLevel()).toString(),_r.A_apil=Math.round(100*$._source.getAccurateVolumeLevel()).toString(),Vt.aecReturnLoss&&(_r.A_ecrl=Math.round(Vt.aecReturnLoss).toString()),Vt.aecReturnLossEnhancement&&(_r.A_ecrle=Math.round(Vt.aecReturnLossEnhancement).toString()),nE("P2P")&&(Vt.bytes&&(_r.bytesSent=Vt.bytes.toString()),typeof Vt.packetsLost=="number"&&(_r.packetsLost=Vt.packetsLost.toString()),Vt.packets&&(_r.packetsSent=Vt.packets.toString())),_r}(A[0].ssrcId,i,b);j&&sT(()=>{var H;return(H=this.requestUpload)===null||H===void 0?void 0:H.call(this,uS.PUBLISH_STATS,{stream_type:"high",stats:j})});break}}})}uploadRelatedUplinkStats(i,o){var p;(((p=this.requestLocalMedia)===null||p===void 0?void 0:p.call(this))||[]).filter(g=>{let[b]=g;return b===TE.LocalVideoLowTrack||b===TE.LocalVideoTrack}).forEach(g=>{let[b,{ssrcs:A}]=g;const j=function(H,z){const $=z.videoSend.find(Vt=>Vt.ssrc===H);return $?{mediaType:"video",isVideoMute:!1,frameRateInput:$.inputFrame&&$.inputFrame.frameRate.toString(),frameRateSent:$.sentFrame&&$.sentFrame.frameRate.toString(),googRtt:$.rttMs.toString(),qpSumPerFrame:Math.floor($.qpSumPerFrame).toString()}:null}(A[0].ssrcId,i);j&&sT(()=>{var H;(H=this.requestUpload)===null||H===void 0||H.call(this,uS.PUBLISH_RELATED_STATS,{stream_type:b===TE.LocalVideoLowTrack?"low":"high",stats:j})})})}uploadDenoiserStats(i){for(let b=0;b{var g;(g=this.requestUpload)===null||g===void 0||g.call(this,p.type,p.stats)})}stopUploadUplinkStats(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStatsUploadInterval&&window.clearInterval(this.uplinkStatsUploadInterval),this.uplinkRelatedStatsUploadInterval&&window.clearInterval(this.uplinkRelatedStatsUploadInterval),this.uplinkDenoiserStatsUploadInterval&&window.clearInterval(this.uplinkDenoiserStatsUploadInterval),this.uplinkStatsUploadInterval=void 0,this.uplinkRelatedStatsUploadInterval=void 0,this.uplinkDenoiserStatsUploadInterval=void 0)}startUploadDownlinkStats(){if(this.uploadDownlinkStarted)return;let i;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);let o=!1;this.downlinkStatsUploadInterval=window.setInterval(()=>{var p;const g=(p=this.requestStats)===null||p===void 0?void 0:p.call(this,!0);g&&(this.uploadDownlinkStats(g,o,i),i=g),o=!o},3e3),this.downlinkRelatedStatsUploadInterval&&window.clearInterval(this.downlinkRelatedStatsUploadInterval),this.downlinkRelatedStatsUploadInterval=window.setInterval(()=>{var p;const g=(p=this.requestStats)===null||p===void 0?void 0:p.call(this,!0);g&&(this.uploadRelatedDownlinkStats(g,this.lastStats),this.lastStats=g)},1e3),this.downlinkExtensionStatsUploadInterval&&window.clearInterval(this.downlinkExtensionStatsUploadInterval),this.downlinkExtensionStatsUploadInterval=window.setInterval(()=>{var p;const g=(p=this.requestRemoteMedia)===null||p===void 0?void 0:p.call(this);g&&this.uploadDownlinkExtensionStats(g)},2e3)}uploadDownlinkStats(i,o,p){var g;(((g=this.requestRemoteMedia)===null||g===void 0?void 0:g.call(this))||[]).forEach(b=>{let[A,j]=b;if(j.has(ME.VIDEO)&&A.videoTrack){const H=A.videoTrack?function(z,$,Vt,_r,Fi){const _l=$.videoRecv.find(eE=>eE.ssrc===z);if(!_l)return null;const _u={id:T_(10,""),timestamp:new Date($.timestamp).toISOString(),mediaType:"video",type:"ssrc",ssrc:_l.ssrc.toString()};var _h,_g;if(_u.bytesReceived=_l.bytes.toString(),_u.packetsLost=_l.packetsLost.toString(),_u.packetsReceived=_l.packets.toString(),_l.framesRateFirefox&&(_u.A_frr=_l.framesRateFirefox.toString()),_l.receivedFrame?(_u.A_frr=_l.receivedFrame.frameRate.toString(),_u.A_fhr=_l.receivedFrame.height.toString(),_u.A_fwr=_l.receivedFrame.width.toString()):(_u.A_fhr=(_h=_r._videoHeight)===null||_h===void 0?void 0:_h.toString(),_u.A_fwr=(_g=_r._videoWidth)===null||_g===void 0?void 0:_g.toString()),_u.A_frd=_l.decodeFrameRate.toString(),_l.outputFrame&&(_u.A_fro=_l.outputFrame.frameRate.toString()),_l.jitterBufferMs!==void 0&&(_u.A_jbm=Math.floor(_l.jitterBufferMs).toString()),_l.currentDelayMs!==void 0&&(_u.A_cdm=Math.floor(_l.currentDelayMs).toString()),_u.A_fs=_l.firsCount.toString(),_u.A_ns=_l.nacksCount.toString(),_u.A_ps=_l.plisCount.toString(),_r&&(_u.A_vrtd=_r._originMediaStreamTrack.enabled&&_r._mediaStreamTrack.enabled?"0":"1"),_r._player&&_r._player.freezeTimeCounterList.length>0&&(_u.A_vrft=Math.round(_r._player.freezeTimeCounterList.splice(0,1)[0]).toString()),Fi&&_r._player&&QT.visibility==="visible"){const eE=Math.min(6e3,_r._player.renderFreezeAccTime);_u.A_vrrft=Math.round(eE).toString(),_r._player.renderFreezeAccTime=Math.max(0,_r._player.renderFreezeAccTime-eE)}if(_u.A_rvps=wM[_r._player?_r._player.videoElementStatus:"uninit"].toString(),Vt){const eE=Vt.videoRecv.find(oE=>oE.ssrc===z);if(eE&&_l.totalInterFrameDelay!==void 0&&_l.totalSquaredInterFrameDelay!==void 0&&eE.totalInterFrameDelay!==void 0&&eE.totalSquaredInterFrameDelay!==void 0){const oE=_l.totalInterFrameDelay-eE.totalInterFrameDelay,SE=_l.totalSquaredInterFrameDelay-eE.totalSquaredInterFrameDelay,vE=_l.framesDecodeCount-eE.framesDecodeCount,fE=oE/vE*1e3,mE=Math.round(1e3*Math.sqrt((SE-Math.pow(oE,2)/vE)/vE));!isNaN(mE)&&fE+mE>Math.max(3*fE,fE+150)&&(_u.A_ifdsd=mE.toString())}}return _u}(A._videoSSRC,i,p,A.videoTrack,o):void 0;H&&sT(()=>{var z;return(z=this.requestUpload)===null||z===void 0?void 0:z.call(this,uS.SUBSCRIBE_STATS,{stream_id:A.uid,stats:H})})}if(j.has(ME.AUDIO)&&A.audioTrack){const H=A.audioTrack?function(z,$,Vt,_r){const Fi=$.audioRecv.find(_u=>_u.ssrc===z);if(!Fi)return null;const _l={id:T_(10,""),timestamp:new Date($.timestamp).toISOString(),mediaType:"audio",type:"ssrc",ssrc:Fi.ssrc.toString()};if(_l.bytesReceived=Fi.bytes.toString(),_l.packetsLost=Fi.packetsLost.toString(),_l.packetsReceived=Fi.packets.toString(),Fi.outputLevel?_l.A_aol=Math.round(100*Fi.outputLevel).toString():_l.A_aol=Math.round(100*_r._source.getAccurateVolumeLevel()).toString(),_l.A_apol=Math.round(100*_r._source.getAccurateVolumeLevel()).toString(),_r&&(_l.A_artd=_r._originMediaStreamTrack.enabled&&_r._mediaStreamTrack.enabled?"0":"1"),_l.A_jr=Fi.jitterMs.toString(),_l.A_jbm=Math.floor(Fi.jitterBufferMs).toString(),_l.A_cdm=Math.floor(Fi.jitterBufferMs).toString(),_l.A_raps=wM[vS.getPlayerState(_r.getTrackId())].toString(),Vt){const _u=Vt.audioRecv.find(_h=>_h.ssrc===z);if(_u){const _h=Fi.concealedSamples-_u.concealedSamples;_h>0&&(_l.A_cs=Math.round(_h).toString())}}return _l}(A._audioSSRC,i,p,A.audioTrack):void 0;H&&sT(()=>{var z;return(z=this.requestUpload)===null||z===void 0?void 0:z.call(this,uS.SUBSCRIBE_STATS,{stream_id:A.uid,stats:H})})}})}uploadRelatedDownlinkStats(i,o){var p;(((p=this.requestRemoteMedia)===null||p===void 0?void 0:p.call(this))||[]).forEach(g=>{let[b,A]=g;if(A.has(ME.VIDEO)&&b.videoTrack){var j;const H=(b._videoSSRC&&((j=this.requestVideoIsReady)===null||j===void 0?void 0:j.call(this,b._videoSSRC))||!1)===!0,z=function($,Vt,_r,Fi,_l,_u){const _h=_r.videoRecv.find(SE=>SE.ssrc===$),_g=_l?_l.videoRecv.find(SE=>SE.ssrc===$):void 0;if(!_h)return null;const eE=oO.isRemoteVideoFreeze(_u,_h,_g)&&Vt,oE={mediaType:"video",isVideoMute:!1,peerId:Fi,frameRateReceived:_h.receivedFrame&&_h.receivedFrame.frameRate.toString(),frameRateDecoded:_h.decodedFrame&&_h.decodedFrame.frameRate.toString(),isFreeze:eE,bytesReceived:_h.bytes.toString(),packetsReceived:_h.packets.toString(),packetsLost:_h.packetsLost.toString(),qpSumPerFrame:Math.floor(_h.qpSumPerFrame).toString()};return _h.framesRateFirefox&&(oE.frameRateDecoded=_h.framesRateFirefox.toString(),oE.frameRateReceived=_h.framesRateFirefox.toString()),oE}(b._videoSSRC,H,i,b.uid,o,b.videoTrack);z&&sT(()=>{var $;($=this.requestUpload)===null||$===void 0||$.call(this,uS.SUBSCRIBE_RELATED_STATS,{stream_id:b.uid,stats:z})})}if(A.has(ME.AUDIO)&&b.audioTrack){const H=function(z,$,Vt,_r){const Fi=$.audioRecv.find(_u=>_u.ssrc===z);if(!Fi)return null;const _l=oO.isRemoteAudioFreeze(_r);return{mediaType:"audio",isAudioMute:!1,peerId:Vt,googJitterReceived:Fi.jitterMs.toString(),isFreeze:_l,bytesReceived:Fi.bytes.toString(),packetsReceived:Fi.packets.toString(),packetsLost:Fi.packetsLost.toString(),frameReceived:Fi.receivedFrames.toString(),frameDropped:Fi.droppedFrames.toString()}}(b._audioSSRC,i,b.uid,b.audioTrack);H&&sT(()=>{var z;(z=this.requestUpload)===null||z===void 0||z.call(this,uS.SUBSCRIBE_RELATED_STATS,{stream_id:b.uid,stats:H})})}})}stopUploadDownlinkStats(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval),this.downlinkRelatedStatsUploadInterval&&window.clearInterval(this.downlinkRelatedStatsUploadInterval),this.downlinkStatsUploadInterval=void 0,this.downlinkRelatedStatsUploadInterval=void 0)}stopUploadTransportStats(){this.uploadTransportStarted&&(this.uploadTransportStarted=!1,this.transportStatsUploadInterval&&window.clearInterval(this.transportStatsUploadInterval),this.transportStatsUploadInterval=void 0)}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.extensionUsageStatsUploadInterval&&window.clearInterval(this.extensionUsageStatsUploadInterval),this.extensionUsageStatsUploadInterval=void 0)}uploadDownlinkExtensionStats(i){i.forEach(o=>{let[p,g]=o;g.has(ME.VIDEO)&&p.videoTrack&&p.videoTrack.getProcessorStats().forEach(b=>{var A;(A=this.requestUpload)===null||A===void 0||A.call(this,b.type,b.stats)}),g.has(ME.AUDIO)&&p.audioTrack&&p.audioTrack.getProcessorStats().forEach(b=>{var A;(A=this.requestUpload)===null||A===void 0||A.call(this,b.type,b.stats)})})}}function o8(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function NR(l){for(var i=1;i{const A=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==u_.Connected)return void b(new yE(_p.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const j=this.filterTobeMutedTracks(p);if(j.length===0)return void g();const H=j.find($=>$[0]==="videoLowTrack");H&&H[1].track._originMediaStreamTrack.stop(),await this.connection.muteLocal(j.map($=>{let[,{id:Vt}]=$;return Vt}));const z=this.createMuteMessage(j);await S_(this,WE.RequestMuteLocal,z),g()}catch(j){b(j)}finally{A()}}),_e(this,"handleUnmuteLocalTrack",async(p,g,b)=>{const A=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==u_.Connected)return void b(new yE(_p.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const j=this.filterTobeUnmutedTracks(p);if(j.length===0)return void g();const H=j.find($=>$[0]==="videoLowTrack");if(H){const $=H[1];if($.track._originMediaStreamTrack.stop(),!nE("DISABLE_DUAL_STREAM_USE_ENCODING")&&I_().supportDualStreamEncoding){const Vt=p._mediaStreamTrack.clone();$.track._mediaStreamTrack=Vt,$.track._originMediaStreamTrack=Vt}else{const Vt=C2(p,JT(this,WE.RequestLowStreamParameter));$.track._mediaStreamTrack=Vt,$.track._originMediaStreamTrack=Vt}await new pE((Vt,_r)=>{this.handleReplaceTrack($.track,Vt,_r,!0)})}await this.connection.unmuteLocal(j.map($=>{let[,{id:Vt}]=$;return Vt}));const z=this.createUnmuteMessage(j);await S_(this,WE.RequestUnmuteLocal,z),g()}catch(j){b(j)}finally{A()}}),_e(this,"handleUpdateVideoEncoder",async(p,g,b)=>{const A=await this.mutex.lock("Locking from P2PChannel.handleSetVideoEncoder");try{const j=this.localTrackMap.get(TE.LocalVideoTrack);if(!this.connection||!j||j.track!==p||this.state!==u_.Connected)return void g();const{id:H,track:z}=j;await this.connection.updateSendParameters(H,z),await this.connection.updateEncoderConfig(H,z),this.emit(WE.UpdateVideoEncoder,z),g()}catch(j){b(j)}finally{A()}}),_e(this,"handleSetOptimizationMode",async(p,g,b)=>{const A=await this.mutex.lock("Locking from P2PChannel.handleSetOptimizationMode");try{const j=this.localTrackMap.get(TE.LocalVideoTrack);if(!this.connection||!j||j.track!==p||this.state!==u_.Connected)return;const{id:H,track:z}=j;await this.connection.updateSendParameters(H,z),g()}catch(j){b(j)}finally{A()}}),_e(this,"handleReplaceTrack",async(p,g,b,A)=>{let j;Gi.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(p.getTrackId(),"]")),typeof A=="boolean"&&A||(j=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var H;const $=Array.from(this.localTrackMap.entries()).find(Vt=>{let[,{track:_r}]=Vt;return p===_r});if(!this.connection||!$||this.state!==u_.Connected)return void g();if(await((H=this.connection)===null||H===void 0?void 0:H.replaceTrack(p,$[1].id)),this.isPlanB){const Vt=$[1];Vt.id=p._mediaStreamTrack.id,this.localTrackMap.set($[0],Vt)}if($[0]===TE.LocalVideoTrack&&!nE("DISABLE_DUAL_STREAM_USE_ENCODING")&&I_().supportDualStreamEncoding){const Vt=this.localTrackMap.get(TE.LocalVideoLowTrack);if(Vt){const _r=p._mediaStreamTrack.clone();Vt.track._originMediaStreamTrack.stop(),Vt.track._mediaStreamTrack=_r,Vt.track._originMediaStreamTrack=_r,await new pE((Fi,_l)=>{this.handleReplaceTrack(Vt.track,Fi,_l,!0)})}}g()}catch($){b($)}finally{var z;(z=j)===null||z===void 0||z()}}),_e(this,"handleGetRTCStats",p=>{p(this.statsCollector.getRTCStats())}),_e(this,"handleGetLocalVideoStats",p=>{p(this.statsCollector.getLocalVideoTrackStats())}),_e(this,"handleGetLocalAudioStats",p=>{p(this.statsCollector.getLocalAudioTrackStats())}),_e(this,"handleGetRemoteVideoStats",p=>this.statsCollector.getRemoteVideoTrackStats(p.uid)[p.uid]),_e(this,"handleGetRemoteAudioStats",p=>this.statsCollector.getRemoteAudioTrackStats(p.uid)[p.uid]),this.store=i,this.statsCollector=o,this.statsCollector.addP2PChannel(this),this.statsUploader=new s8,this.bindStatsUploaderEvents(),this.isPlanB=!I_().supportUnifiedPlan||nE("CHROME_FORCE_PLAN_B")&&dR(),this.shouldForwardP2PCreation=nE("FORWARD_P2P_CREATION")&&I_().supportPCSetConfiguration&&function(){const p=aN();return p===l0.ANDROID||p===l0.IOS||p===l0.HARMONY_OS}(),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new u0({},this.store):this.isPlanB?new b0({},this.store):new c0({},this.store),this.bindConnectionEvents(this.connection))}async startP2PConnection(i,o){var p;this.state=u_.New;const g=this.shouldForwardP2PCreation&&((p=this.connection)===null||p===void 0?void 0:p.peerConnectionState)==="closed";if(this.shouldForwardP2PCreation&&!g||(g&&this.connection&&(Gi.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.connection.close(),this.unbindConnectionEvents(this.connection)),this.connection=this.store.useDataChannel?new u0(i,this.store):this.isPlanB?new b0(i,this.store):new c0(i,this.store),this.bindConnectionEvents(this.connection)),!this.connection)throw new yE(_p.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=nE("NEW_ICE_RESTART")?yT.FIRST_CONNECTION:yT.OLD_FIRST_CONNECTION,this._isFirstConnected=!0,this._isInRestartIce=!1,this._isStartRestartIce=!1,this.connection.setConfiguration(i),this.connection.establishPromise}async connect(i,o,p,g,b,A){if(!this.connection)throw new yE(_p.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.connection instanceof u0?this.connection.updateRemoteConnect(g):(this.store.peerConnectionStart(),await this.connection.connect(i,o,p,g,b,A),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=u_.Connected)}updateRemoteRTPCapabilities(i){const o=Array.from(this.localTrackMap.entries()).filter(p=>{var g;let[b]=p;return VE(g=[TE.LocalVideoLowTrack,TE.LocalVideoTrack]).call(g,b)}).map(p=>{let[,{id:g}]=p;return g});if(this.connection instanceof c0){if(!VE(i).call(i,this.store.codec)){const p=["vp8","h264"].find(g=>VE(i).call(i,g));p&&(this.store.codec=p,Gi.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default codec is not available, hence the fallback to ").concat(p,".")))}this.connection.updateRemoteRTPCapabilities(o,i)}}async preConnect(i,o,p,g,b,A){if(!this.connection)throw new yE(_p.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");this.store.peerConnectionStart();const j=await this.connection.connect(i,o,p,g,b,A);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=u_.Connected,j}getEstablishParams(){if(this.connection instanceof u0)return this.connection.getP2PConnectionParams();throw new Error("Only DataChannelConnection needs to obtain establishParams")}async publishDataChannel(i){if(!this.connection){if(this.state===u_.Disconnected)throw new yE(_p.UNEXPECTED_ERROR,"PeerConnection already disconnected.");const p=i.filter(g=>this.pendingLocalDataChannels.findIndex(b=>b.id===g.id)!==-1);return void(this.pendingLocalDataChannels=this.pendingLocalDataChannels.concat(p))}const o=this.filterTobePublishedDataChannels(i);o.length!==0&&(o.forEach(p=>{const g=Date.now();this.store.publish(p.id.toString(),"datachannel",g)}),await this.connection.createDataChannels(this.store.uid,o),o.forEach(p=>{this.localDataChannels.push(p);const g=Date.now();this.store.publish(p.id+"","datachannel",void 0,g)}))}publish(i,o,p){var g=this;return JS(function*(){const b=yield d_(g.mutex.lock("From P2PChannel.publish"));try{if(!g.connection||g.state!==u_.Connected){if(g.state===u_.Disconnected)throw new yE(_p.UNEXPECTED_ERROR,"PeerConnection already disconnected.");g.throwIfTrackTypeNotMatch(i);const j=i.filter(H=>g.pendingLocalTracks.indexOf(H)===-1);return void(g.pendingLocalTracks=g.pendingLocalTracks.concat(j))}g.store.pubId=g.store.pubId+1,k0.markPublishStart(g.store.clientId,g.store.pubId);const A=g.filterTobePublishedTracks(i,o,p);if(A.length===0)return void(yield d_(g.tryToUnmuteAudio(i)));yield*lP(a8(g.doPublish(g.connection,A)))}finally{b()}})()}doPublish(i,o){var p=this;return JS(function*(){o.forEach($=>{let{track:Vt,type:_r}=$;const Fi=Date.now();p.store.publish(Vt.getTrackId(),_r===TE.LocalAudioTrack?"audio":"video",Fi)}),p.bindLocalTrackEvents(o);const g=yield d_(i.send(o.map($=>{let{track:Vt}=$;return Vt}),p.store.codec,p.store.audioCodec)),b=(yield d_(g.next())).value,A=p.createGatewayPublishMessage(o,b);let j;try{j=yield A}catch($){throw g.throw($),($==null?void 0:$.code)===_p.WS_ABORT&&o.forEach(Vt=>{let{track:_r}=Vt;p.pendingLocalTracks.indexOf(_r)===-1&&p.pendingLocalTracks.push(_r)}),p.unbindLocalTrackEvents(o),$}const H=p.mapPubResToRemoteConfig(A,j),z=(yield d_(g.next(H))).value;o.forEach($=>{let{type:Vt}=$;p.statsCollector.addLocalStats(Vt)}),p.assignLocalTracks(o,z),p.statsUploader.startUploadUplinkStats(),o.forEach($=>{let{track:Vt,type:_r}=$;const Fi=Date.now();p.store.publish(Vt.getTrackId(),_r===TE.LocalAudioTrack?"audio":"video",void 0,Fi)})})()}async updateVideoStreamParameter(i,o){const p=this.localTrackMap.get(o);if(!p)return;if(!(p.track instanceof ZE))return Gi.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");if(!(this.connection instanceof c0||this.connection instanceof b0))return Gi.warn("[updateVideoStreamParameter]: connection is not P2PConnection or P2PConnectionPlanB");const{track:g}=p,b=function(A,j){const H={};return A.height&&A.width&&(H.scaleResolutionDownBy=c2(A,j)),H.maxFramerate=A.framerate?US(A.framerate):void 0,H.maxBitrate=A.bitrate?1e3*A.bitrate:void 0,H}(i,g);if(g._encoderConfig||(g._encoderConfig={}),o!==TE.LocalVideoLowTrack||!nE("DISABLE_DUAL_STREAM_USE_ENCODING")&&I_().supportDualStreamEncoding)b.scaleResolutionDownBy!=null&&(g._encoderConfig.scaleResolutionDownBy=b.scaleResolutionDownBy);else{const A=g._originMediaStreamTrack;if(!A.canvas)return Gi.warn("[".concat(g.getTrackId(),"] no canvas on track"));(function(j,H){const z=j.canvas;H.width&&(z.width=US(H.width)),H.height&&(z.height=US(H.height)),H.framerate&&(z.stopCapture&&z.stopCapture(),z.stopCapture=OM(()=>{!z.startCapture&&z.stopCapture&&z.stopCapture(),z.startCapture&&z.startCapture()},US(H.framerate)))})(A,i)}b.maxBitrate!=null&&(g._encoderConfig.bitrateMax=b.maxBitrate/1e3),b.maxFramerate!=null&&(g._encoderConfig.frameRate&&typeof g._encoderConfig.frameRate=="object"?g._encoderConfig.frameRate.max=b.maxFramerate:g._encoderConfig.frameRate={max:b.maxFramerate}),Gi.debug("[".concat(g.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(g._encoderConfig))),await this.connection.updateRtpSenderEncodings(g)}publishLowStream(i){var o=this;return JS(function*(){if(!o.connection||o.state!==u_.Connected)return;const p=yield d_(o.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const b=o.localTrackMap.get(TE.LocalVideoTrack);if(!b)throw new yE(_p.UNEXPECTED_ERROR,"Could not find high stream");if(o.localTrackMap.has(TE.LocalVideoLowTrack))throw new yE(_p.UNEXPECTED_ERROR,"[".concat(o.store.clientId,"] Can't publish low stream when stream already publish"));const A=[{track:o.getLowVideoTrack(b.track,i),type:TE.LocalVideoLowTrack}];if(yield*lP(a8(o.doPublish(o.connection,A))),b.track.muted||!b.track.enabled){var g;const j=(g=o.localTrackMap.get(TE.LocalVideoLowTrack))===null||g===void 0?void 0:g.id;j!==void 0&&(yield d_(o.connection.muteLocal([j])))}}finally{p()}})()}async republish(){this.pendingLocalTracks.length>0&&(Gi.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await U_(this,WE.RequestRePublish,this.pendingLocalTracks),this.emit(WE.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(Gi.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await U_(this,WE.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[])}async reSubscribe(i){for(let o=this.pendingRemoteTracks.length-1;o>=0;o--){const{user:p,kind:g}=this.pendingRemoteTracks[o];(g!==ME.AUDIO||p._audio_added_&&p._audioSSRC)&&(g!==ME.VIDEO||p._video_added_&&p._videoSSRC)||this.pendingRemoteTracks.splice(o,1)}if(i)await U_(this,WE.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:o,kind:p}of this.pendingRemoteTracks)await this.subscribe(o,p,p===ME.VIDEO?o._videoSSRC:o._audioSSRC);this.pendingRemoteTracks.forEach(o=>{let{user:p}=o;this.emit(WE.MediaReconnectEnd,p.uid)}),this.pendingRemoteTracks=[]}async unpublish(i){if(!this.connection||this.state!==u_.Connected)return void i.forEach(g=>{const b=this.pendingLocalTracks.indexOf(g);b!==-1&&this.pendingLocalTracks.splice(b,1)});const o=this.filterTobeUnpublishedTracks(i);if(o.length===0)return;const p=o.find(g=>g[0]==="videoLowTrack");return p&&p[1].track.close(),this.doUnpublish(this.connection,o)}async unpublishDataChannel(i){if(!this.connection||this.state!==u_.Connected)return void i.forEach(p=>{const g=this.pendingLocalDataChannels.indexOf(p);g!==-1&&this.pendingLocalDataChannels.splice(g,1)});const o=this.filterTobeUnpublishedDataChannels(i);return o.length!==0?(o.forEach(p=>{const g=this.localDataChannels.indexOf(p);g!==-1&&this.localDataChannels.splice(g,1)}),this.localDataChannels.length===0&&await this.connection.stopDataChannels(this.store.uid),o.map(p=>p.id)):void 0}async unpublishLowStream(){if(!this.connection||this.state!==u_.Connected)return;const i=this.localTrackMap.get(TE.LocalVideoLowTrack);if(!i)return;i.track.close();const o=[[TE.LocalVideoLowTrack,i]];return this.doUnpublish(this.connection,o)}async doUnpublish(i,o){const p=this.createGatewayUnpublishMessage(o);return await i.stopSending(o.map(g=>{let[,{id:b}]=g;return b})),this.withdrawLocalTracks(o),this.unbindLocalTrackEvents(o.map(g=>{let[b,{track:A}]=g;return{type:b,track:A}})),o.forEach(g=>{let[b]=g;this.statsCollector.removeLocalStats(b)}),this.localTrackMap.size===0&&this.statsUploader.stopUploadUplinkStats(),p}async subscribeDataChannel(i,o){if(!this.connection||this.state!==u_.Connected)throw new yE(_p.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const p=o.filter(g=>{var b;return!((b=this.remoteDataChannelMap.get(i))!==null&&b!==void 0&&b.get(g.id))});if(p.length!==0)return await this.connection.createDataChannels(i.uid,p),p.forEach(g=>{var b;this.remoteDataChannelMap.has(i)?(b=this.remoteDataChannelMap.get(i))===null||b===void 0||b.set(g.id,g):this.remoteDataChannelMap.set(i,new Map([[g.id,g]]));const A=this.pendingRemoteDataChannels.findIndex(j=>{let{user:H,id:z}=j;return H.uid===i.uid&&z===g.id});A!==-1&&this.pendingRemoteDataChannels.splice(A,1)}),p.map(g=>g.id)}async subscribe(i,o,p,g,b){var A;if(!this.connection||this.state!==u_.Connected)throw new yE(_p.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if((A=this.remoteUserMap.get(i))!==null&&A!==void 0&&A.has(o))return;let j,H,z;if(b){const _r=b.find(_l=>{let{stream_type:_u}=_l;return _u===o});if(!_r)throw new yE(_p.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(o," for user: ").concat(i.uid," because subscribe answer from gateway does not contain stream_type: ").concat(o,"."));const Fi=await this.connection.receive(o,_r.ssrcs,String(i._uintid),_r.attributes);this.connection instanceof c0&&(z=Fi.transceiver),j=Fi.track,H=Fi.id}else{const _r=await this.connection.receive(o,[{ssrcId:p,rtx:g}],String(i._uintid),void 0);this.connection instanceof c0&&(z=_r.transceiver),j=_r.track,H=_r.id}o===ME.AUDIO?(i._audioTrack?i._audioTrack._updateOriginMediaStreamTrack(j):(i._audioTrack=new cT(j,i.uid,i._uintid,this.store),Gi.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(i._audioTrack.getTrackId()))),z&&i._audioTrack._updateRtpTransceiver(z),this.bindRemoteTrackEvents(i,i._audioTrack)):(i._videoTrack?i._videoTrack._updateOriginMediaStreamTrack(j):(i._videoTrack=new DT(j,i.uid,i._uintid,this.store),Gi.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(i._videoTrack.getTrackId()))),z&&i._videoTrack._updateRtpTransceiver(z),this.bindRemoteTrackEvents(i,i._videoTrack));const $=this.remoteUserMap.get(i);$?$.set(o,H):this.remoteUserMap.set(i,new Map([[o,H]])),this.statsCollector.addRemoteStats(i.uid),this.statsUploader.startUploadDownlinkStats();const Vt=this.pendingRemoteTracks.findIndex(_r=>{let{user:Fi,kind:_l}=_r;return Fi.uid===i.uid&&o===_l});Vt!==-1&&(this.pendingRemoteTracks.splice(Vt,1),this.emit(WE.MediaReconnectEnd,i.uid))}async massSubscribe(i){return this.massSubscribeNoLock(i)}async massSubscribeNoLock(i){if(!this.connection||this.state!==u_.Connected)throw new yE(_p.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");i=i.filter(p=>{var g;let{user:b,mediaType:A}=p;return!((g=this.remoteUserMap.get(b))!==null&&g!==void 0&&g.has(A))});const o=await this.connection.batchReceive(i.map(p=>{let{user:g,mediaType:b,ssrcId:A,rtxSsrcId:j}=p;return{kind:b,ssrcMsg:[{ssrcId:A,rtx:j}],mslabel:String(g._uintid)}}));i.forEach((p,g)=>{let{user:b,mediaType:A}=p;const{track:j,id:H,transceiver:z}=o[g];A===ME.AUDIO?(b._audioTrack?b._audioTrack._updateOriginMediaStreamTrack(j):(b._audioTrack=new cT(j,b.uid,b._uintid,this.store),Gi.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(b._audioTrack.getTrackId()))),z&&b._audioTrack._updateRtpTransceiver(z),this.bindRemoteTrackEvents(b,b._audioTrack)):(b._videoTrack?b._videoTrack._updateOriginMediaStreamTrack(j):(b._videoTrack=new DT(j,b.uid,b._uintid,this.store),Gi.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(b._videoTrack.getTrackId()))),z&&b._videoTrack._updateRtpTransceiver(z),this.bindRemoteTrackEvents(b,b._videoTrack));const $=this.remoteUserMap.get(b);$?$.set(A,H):this.remoteUserMap.set(b,new Map([[A,H]])),this.statsCollector.addRemoteStats(b.uid),this.statsUploader.startUploadDownlinkStats();const Vt=this.pendingRemoteTracks.findIndex(_r=>{let{user:Fi,kind:_l}=_r;return Fi.uid===b.uid&&A===_l});Vt!==-1&&(this.pendingRemoteTracks.splice(Vt,1),this.emit(WE.MediaReconnectEnd,b.uid))})}async unsubscribe(i,o,p){const g=this.pendingRemoteTracks.filter(j=>{let{user:H,kind:z}=j;return o!==void 0?H.uid===i.uid&&o===z:H.uid===i.uid});if(g.forEach(j=>{const H=this.pendingRemoteTracks.indexOf(j);this.pendingRemoteTracks.splice(H,1)}),this.connection&&this.state===u_.Connected||p||g.forEach(j=>{let{kind:H}=j;var z;if(H===ME.AUDIO)(z=i._audioTrack)===null||z===void 0||z._destroy(),i._audioTrack=void 0;else if(H===ME.VIDEO){var $;($=i._videoTrack)===null||$===void 0||$._destroy(),i._videoTrack=void 0}}),!this.connection||this.state!==u_.Connected)return;const b=this.filterTobeUnSubscribedTracks(i,o);if(b.length===0)return;await this.connection.stopReceiving(b.map(j=>{let[,{id:H}]=j;return H}));const A=this.createUnsubscribeMessage(b);return this.withdrawRemoteTracks(b),this.remoteUserMap.size===0&&this.statsUploader.stopUploadDownlinkStats(),b.forEach(j=>{let[H,{kind:z}]=j;var $,Vt;if(z===ME.VIDEO&&H._videoSSRC&&(($=this.connection)===null||$===void 0||$.setStatsRemoteVideoIsReady(H._videoSSRC,!1)),z===ME.VIDEO)this.unbindRemoteTrackEvents(H._videoTrack),p||((Vt=H._videoTrack)===null||Vt===void 0||Vt._destroy(),H._videoTrack=void 0);else if(z===ME.AUDIO){var _r;this.unbindRemoteTrackEvents(H._audioTrack),!p&&((_r=H._audioTrack)===null||_r===void 0||_r._destroy(),H._audioTrack=void 0)}}),A}async unsubscribeDataChannel(i,o){if(o.forEach(b=>{const A=this.pendingRemoteDataChannels.findIndex(j=>j.id===b.id);A!==-1&&this.pendingRemoteDataChannels.splice(A,1)}),!this.connection)return;const p=this.filterTobeUnSubscribedDataChannels(i,o);if(p.length===0)return;o.forEach(b=>{b._close()});const g=this.remoteDataChannelMap.get(i);return p.forEach(b=>{g&&g.delete(b.id)}),g&&g.size===0&&(this.remoteDataChannelMap.delete(i),await this.connection.stopDataChannels(i.uid)),p.map(b=>b.id)}async massUnsubscribe(i){return this.massUnsubscribeNoLock(i)}async massUnsubscribeNoLock(i){let o=[];for(const{user:b,mediaType:A}of i){const j=this.pendingRemoteTracks.filter(H=>{let{user:z,kind:$}=H;return A!==void 0?z.uid===b.uid&&A===$:z.uid===b.uid});j.forEach(H=>{const z=this.pendingRemoteTracks.indexOf(H);this.pendingRemoteTracks.splice(z,1)}),o=o.concat(j)}if(!this.connection||this.state!==u_.Connected)return void o.forEach(b=>{let{user:A,kind:j}=b;var H;if(j===ME.AUDIO)(H=A._audioTrack)===null||H===void 0||H._destroy(),A._audioTrack=void 0;else if(j===ME.VIDEO){var z;(z=A._videoTrack)===null||z===void 0||z._destroy(),A._videoTrack=void 0}});const p=_C(i).call(i,(b,A)=>{let{user:j,mediaType:H}=A;const z=this.filterTobeUnSubscribedTracks(j,H);return b.concat(z)},[]);if(p.length===0)return;await this.connection.stopReceiving(p.map(b=>{let[,{id:A}]=b;return A}));const g=this.createUnsubscribeAllMessage(p);return this.withdrawRemoteTracks(p),this.remoteUserMap.size===0&&this.statsUploader.stopUploadDownlinkStats(),p.forEach(b=>{let[A,{kind:j}]=b;var H,z;if(j===ME.VIDEO&&A._videoSSRC&&((H=this.connection)===null||H===void 0||H.setStatsRemoteVideoIsReady(A._videoSSRC,!1)),j===ME.VIDEO)this.unbindRemoteTrackEvents(A._videoTrack),(z=A._videoTrack)===null||z===void 0||z._destroy(),A._videoTrack=void 0;else if(j===ME.AUDIO){var $;this.unbindRemoteTrackEvents(A._audioTrack),($=A._audioTrack)===null||$===void 0||$._destroy(),A._audioTrack=void 0}}),g}async muteRemote(i,o){if(!this.connection)return;const p=this.remoteUserMap.get(i);if(!p)return void Gi.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(i.uid,"."));if(!p.get(o))return void Gi.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(i.uid," media type ").concat(o,"."));const g=o===ME.VIDEO?i._videoSSRC:i._audioSSRC;g!==void 0&&this.connection.setStatsRemoteVideoIsReady(g,!1)}async unmuteRemote(i,o){return this.unmuteRemoteNoLock(i,o)}async unmuteRemoteNoLock(i,o){if(!this.connection)return;const p=this.remoteUserMap.get(i);if(!p)return void Gi.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(i.uid,"."));p.get(o)||Gi.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(i.uid," media type ").concat(o,"."))}getAllTracks(i){const o=this.localTrackMap.get(TE.LocalAudioTrack);if((o==null?void 0:o.track)instanceof Z_){const p=o.track;return Array.from(this.localTrackMap.entries()).filter(g=>{let[b]=g;return b!==TE.LocalAudioTrack}).filter(g=>{let[b]=g;return!(i&&b===TE.LocalVideoLowTrack)}).map(g=>{let[,{track:b}]=g;return b}).concat(p.trackList)}return Array.from(this.localTrackMap.entries()).filter(p=>{let[g]=p;return!(i&&g===TE.LocalVideoLowTrack)}).map(p=>{let[,{track:g}]=p;return g})}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(i,o,p,g,b){if(i){const j=this.localTrackMap.get(TE.LocalAudioTrack),H=g?this.localTrackMap.get(TE.LocalVideoLowTrack):this.localTrackMap.get(TE.LocalVideoTrack);jE.publish(this.store.sessionId,{eventElapse:k0.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:i,ec:o,audioName:j==null?void 0:j.track.getTrackLabel(),videoName:H==null?void 0:H.track.getTrackLabel(),screenshare:(H==null?void 0:H.track._hints.indexOf(A_.SCREEN_TRACK))!==-1,audio:!!j,video:!!H,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:b})}else{var A;p||(p=[]);const j=p.find(z=>z instanceof g_),H=g?(A=this.localTrackMap.get(TE.LocalVideoTrack))===null||A===void 0?void 0:A.track:p.find(z=>z instanceof ZE);jE.publish(this.store.sessionId,{eventElapse:k0.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:i,ec:o,audioName:j==null?void 0:j.getTrackLabel(),videoName:H==null?void 0:H.getTrackLabel(),screenshare:(H==null?void 0:H._hints.indexOf(A_.SCREEN_TRACK))!==-1,audio:!!j,video:!!H,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:b})}}reportSubscribeEvent(i,o,p,g){const b=g===ME.VIDEO?p._videoSSRC:p._audioSSRC;b&&jE.subscribe(this.store.sessionId,{succ:i,ec:o,video:g===ME.VIDEO,audio:g===ME.AUDIO,peerid:p.uid,subscribeRequestid:g===ME.VIDEO?p._videoSSRC:p._audioSSRC,p2pid:this.store.p2pId,eventElapse:k0.measureFromSubscribeStart(this.store.clientId,b)})}reset(){Gi.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new E0("P2PChannel-mutex"),this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new u0({},this.store):this.isPlanB?new b0({},this.store):new c0({},this.store),this.bindConnectionEvents(this.connection)),this.statsUploader.stopUploadUplinkStats(),this.statsUploader.stopUploadDownlinkStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const i=this.localTrackMap.get(TE.LocalAudioTrack);if((i==null?void 0:i.track)instanceof Z_){if(i.track.trackList.length>0){const o=i.track;i.track.trackList.forEach(p=>{o.removeAudioTrack(p)})}i.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=u_.Disconnected}getStats(){var i;return(i=this.connection)===null||i===void 0?void 0:i.getStats()}getRemoteVideoIsReady(i){var o;return((o=this.connection)===null||o===void 0?void 0:o.getRemoteVideoIsReady(i))||!1}getLocalAudioVolume(){const i=this.localTrackMap.get(TE.LocalAudioTrack);if(i)return i.track.getVolumeLevel()}getLocalVideoSize(){const i=this.localTrackMap.get(TE.LocalVideoTrack);if(i)return{width:i.track._videoWidth||0,height:i.track._videoHeight||0}}getEncoderConfig(i){const o=this.localTrackMap.get(i);return o&&o.track instanceof ZE||o&&o.track instanceof g_?o.track._encoderConfig:void 0}getLocalMedia(i){return this.localTrackMap.get(i)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(i,o){if(!i)return this.remoteUserMap.size>0;const p=this.remoteUserMap.get(i);return!!p&&(!o||p.has(o))}async hasRemoteMediaWithLock(i,o){if(!i)return this.remoteUserMap.size>0;const p=this.remoteUserMap.get(i);return!!p&&(!o||p.has(o))}getRemoteMedia(i){var o;const p=Array.from(CS(o=this.remoteUserMap).call(o)).find(g=>g.uid===i);return p?{audioTrack:p.audioTrack,audioSSRC:p._audioSSRC,videoTrack:p.videoTrack,videoSSRC:p._videoSSRC}:{}}getAudioLevels(){let i=Array.from(this.remoteUserMap.entries()).map(p=>{let[g]=p;return{uid:g.uid,level:g.audioTrack?100*g.audioTrack._source.getAccurateVolumeLevel():0}});const o=this.localTrackMap.get(TE.LocalAudioTrack);return o&&i.push({level:100*o.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),i=AO(i).call(i,(p,g)=>p.level-g.level),i}async disconnectForReconnect(){this.connection&&(Gi.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=u_.Reconnecting,nE("KEEP_LAST_FRAME")&&this.remoteUserMap.size!==0&&Array.from(this.remoteUserMap.entries()).forEach(i=>{let[o]=i;var p;o._videoTrack&&o._videoTrack._player&&((p=o._videoTrack._player.getVideoElement())===null||p===void 0||p.pause(),o._videoTrack._player.isKeepLastFrame=!0,o._videoTrack._originMediaStreamTrack.stop())}),this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=this.store.useDataChannel?new u0({},this.store):this.isPlanB?new b0({},this.store):new c0({},this.store),this.bindConnectionEvents(this.connection)),this.localTrackMap.size!==0&&(Array.from(this.localTrackMap.entries()).forEach(i=>{var o;let[p,{track:g}]=i;switch(p){case TE.LocalVideoTrack:VE(o=g._hints).call(o,A_.LOW_STREAM)?g.close():this.pendingLocalTracks.push(g);break;case TE.LocalAudioTrack:g instanceof Z_?this.pendingLocalTracks=this.pendingLocalTracks.concat(g.trackList):this.pendingLocalTracks.push(g);case TE.LocalVideoLowTrack:}}),this.emit(WE.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),this.remoteUserMap.size!==0&&Array.from(this.remoteUserMap.entries()).forEach(i=>{let[o,p]=i;Array.from(CS(p).call(p)).forEach(g=>{this.setPendingRemoteMedia(o,g)}),this.emit(WE.MediaReconnectStart,o.uid)}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.localDataChannels.length!==0&&(this.localDataChannels.forEach(i=>{this.pendingLocalDataChannels.push(i)}),this.localDataChannels.length=0),this.remoteDataChannelMap.size!==0&&(Array.from(this.remoteDataChannelMap.entries()).forEach(i=>{let[o,p]=i;Array.from(CS(p).call(p)).forEach(g=>{this.setPendingRemoteDataChannel(o,g)})}),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadUplinkStats(),this.statsUploader.stopUploadDownlinkStats(),this.statsUploader.stopUploadTransportStats(),Gi.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")))}hasPendingRemoteDataChannel(i,o){for(const p of this.pendingRemoteDataChannels){const{user:g,id:b}=p;if((i instanceof D0?i.uid:i)===g.uid&&b===o)return!0}return!1}setPendingRemoteDataChannel(i,o){this.hasPendingRemoteDataChannel(i,o)||this.pendingRemoteDataChannels.push({user:i,id:o})}hasPendingRemoteMedia(i,o){for(const p of this.pendingRemoteTracks){const{user:g,kind:b}=p;if((i instanceof D0?i.uid:i)===g.uid&&o===b)return!0}return!1}setPendingRemoteMedia(i,o){this.hasPendingRemoteMedia(i,o)||this.pendingRemoteTracks.push({user:i,kind:o})}restartICE(i){var o=this;return JS(function*(){if(!o.connection||o.state!==u_.Connected||o.connection instanceof u0)return;const p=yield d_(o.mutex.lock("From P2PChannel.restartICE"));let g;try{g=yield d_(o.connection.restartICE(i));const A=yield d_(g.next());if(A.done)return;const j=A.value,H=yield j;switch(o.reportPCDisconnectedOrFailed(i),i){case N0.TCP:o._pcStatsUploadType=yT.TCP_RESTART;break;case N0.RELAY:o._pcStatsUploadType=yT.RELAY_RESTART;break;default:o._pcStatsUploadType=yT.OLD_RESTART}o._isInRestartIce=!0,g.next(H)}catch(A){var b;(b=g)===null||b===void 0||b.throw(A)}finally{p()}})()}getUplinkNetworkQuality(){if(!this.connection)return 0;const i=this.connection.getStats(),o=this.localTrackMap.get(TE.LocalVideoTrack),p=this.localTrackMap.get(TE.LocalAudioTrack),g=i.videoSend.find(_l=>_l.ssrc===(o==null?void 0:o.ssrcs[0].ssrcId)),b=i.audioSend.find(_l=>_l.ssrc===(p==null?void 0:p.ssrcs[0].ssrcId));if(!g||!b)return 1;const A=oS(this,WE.NeedSignalRTT),j=g?g.rttMs:void 0,H=b?b.rttMs:void 0,z=j&&H?(j+H)/2:j||H,$=(z&&A?(z+A)/2:z||A)||0,Vt=100*i.sendPacketLossRate*.7/50+.3*$/1500,_r=Vt<.17?1:Vt<.36?2:Vt<.59?3:Vt<.1?4:5,Fi=o==null?void 0:o.track;if(Fi&&Fi._encoderConfig&&Fi._hints.indexOf(A_.SCREEN_TRACK)===-1){const _l=Fi._encoderConfig.bitrateMax,_u=i.bitrate.actualEncoded;if(_l&&_u){const _h=(1e3*_l-_u)/(1e3*_l);return h6[_h<.15?0:_h<.3?1:_h<.45?2:_h<.6?3:4][_r]}}return _r}getDownlinkNetworkQuality(){if(!this.connection)return 0;const i=this.connection.getStats();let o=0;return Array.from(this.remoteUserMap.entries()).forEach(p=>{let[g]=p;const b=g._audioSSRC,A=g._videoSSRC,j=i.audioRecv.find(_u=>_u.ssrc===b),H=i.videoRecv.find(_u=>_u.ssrc===A);if(!j&&!H)return void(o+=1);const z=oS(this,WE.NeedSignalRTT),$=i.rtt,Vt=($&&z?($+z)/2:$||z)||0,_r=j?j.jitterMs:void 0,Fi=i.recvPacketLossRate;let _l=.7*Fi*100/50+.3*Vt/1500;_r&&(_l=.6*Fi*100/50+.2*Vt/1500+.2*_r/400),o+=_l<.1?1:_l<.17?2:_l<.36?3:_l<.59?4:5}),this.remoteUserMap.size>0?Math.round(o/this.remoteUserMap.size):o}async muteLocalTrack(i){return new pE((o,p)=>{this.handleMuteLocalTrack(i,o,p)})}filterTobePublishedTracks(i,o,p){const g=[],b=I_(),A=this.getAllTracks();i=BI(i=i.filter(z=>A.indexOf(z)===-1));let j=!1,H=!1;for(const z of i){if(z instanceof ZE&&(this.localTrackMap.has(TE.LocalVideoTrack)||j?new yE(_p.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(g.push({track:z,type:TE.LocalVideoTrack}),j=!0),o)){const $=this.getLowVideoTrack(z,p);g.push({track:$,type:TE.LocalVideoLowTrack})}if(z instanceof g_){const $=this.localTrackMap.get(TE.LocalAudioTrack);if($){if(!($.track instanceof Z_))throw new yE(_p.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(z._bypassWebAudio)throw new yE(_p.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");$.track.addAudioTrack(z),this.bindLocalAudioTrackEvents(z,!0)}else if(H){const Vt=g.find(_r=>{let{type:Fi}=_r;return Fi===TE.LocalAudioTrack});if(!(Vt.track instanceof Z_))throw new yE(_p.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(z._bypassWebAudio)throw new yE(_p.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");Vt.track.addAudioTrack(z)}else{if(!b.webAudioMediaStreamDest||z instanceof Z_||z._bypassWebAudio)g.push({track:z,type:TE.LocalAudioTrack});else{const Vt=new Z_;Vt.addAudioTrack(z),g.push({track:Vt,type:TE.LocalAudioTrack})}H=!0}}}return g}filterTobeUnpublishedTracks(i){const o=[],p=this.getAllTracks();i=BI(i=i.filter(g=>p.indexOf(g)!==-1));for(const g of i){if(g instanceof g_){const b=this.localTrackMap.get(TE.LocalAudioTrack);if(!b)continue;b.track instanceof Z_?(b.track.removeAudioTrack(g),this.unbindLocalAudioTrackEvents(g),b.track.trackList.length===0&&(o.push([TE.LocalAudioTrack,b]),b.track.close())):o.push([TE.LocalAudioTrack,b])}if(g instanceof ZE){const b=this.localTrackMap.get(TE.LocalVideoTrack);if(!b)continue;o.push([TE.LocalVideoTrack,b]);const A=this.localTrackMap.get(TE.LocalVideoLowTrack);A&&o.push([TE.LocalVideoLowTrack,A])}}return o}filterTobePublishedDataChannels(i){return i=(i=BI(i)).filter(o=>this.localDataChannels.findIndex(p=>p.id===o.id)===-1)}filterTobeUnpublishedDataChannels(i){return i=(i=(i=BI(i)).filter(o=>this.localDataChannels.indexOf(o)!==-1)).filter(o=>o._originDataChannel)}bindLocalTrackEvents(i){i.forEach(o=>{let{track:p,type:g}=o;switch(g){case TE.LocalVideoTrack:p.addListener(xE.GET_STATS,this.handleGetLocalVideoStats),p.addListener(xE.GET_RTC_STATS,this.handleGetRTCStats),p.addListener(xE.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),p.addListener(xE.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),p.addListener(xE.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),p.addListener(xE.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),p.addListener(xE.NEED_REPLACE_TRACK,this.handleReplaceTrack),p.addListener(xE.NEED_MUTE_TRACK,this.handleMuteLocalTrack),p.addListener(xE.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case TE.LocalAudioTrack:this.bindLocalAudioTrackEvents(p);case TE.LocalVideoLowTrack:}})}bindLocalAudioTrackEvents(i,o){i instanceof Z_?i.trackList.forEach(p=>{p.addListener(xE.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),p.addListener(xE.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),p.addListener(xE.GET_STATS,this.handleGetLocalAudioStats),p.addListener(xE.NEED_MUTE_TRACK,this.handleMuteLocalTrack),p.addListener(xE.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(i.addListener(xE.GET_STATS,this.handleGetLocalAudioStats),i.addListener(xE.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),i.addListener(xE.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),i.addListener(xE.NEED_MUTE_TRACK,this.handleMuteLocalTrack),i.addListener(xE.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),o||i.addListener(xE.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(i){i||(i=Array.from(this.localTrackMap.entries()).map(o=>{let[p,{track:g}]=o;return{track:g,type:p}})),i.forEach(o=>{let{track:p,type:g}=o;switch(g){case TE.LocalVideoTrack:p.off(xE.GET_STATS,this.handleGetLocalVideoStats),p.off(xE.GET_RTC_STATS,this.handleGetRTCStats),p.off(xE.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),p.off(xE.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),p.off(xE.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),p.off(xE.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),p.off(xE.NEED_REPLACE_TRACK,this.handleReplaceTrack),p.off(xE.NEED_MUTE_TRACK,this.handleMuteLocalTrack),p.off(xE.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case TE.LocalAudioTrack:this.unbindLocalAudioTrackEvents(p);case TE.LocalVideoLowTrack:}})}unbindLocalAudioTrackEvents(i){i instanceof Z_?i.trackList.forEach(o=>{o.off(xE.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),o.off(xE.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),o.off(xE.GET_STATS,this.handleGetLocalAudioStats),o.off(xE.NEED_MUTE_TRACK,this.handleMuteLocalTrack),o.off(xE.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(i.off(xE.GET_STATS,this.handleGetLocalAudioStats),i.off(xE.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),i.off(xE.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),i.off(xE.NEED_REPLACE_TRACK,this.handleReplaceTrack),i.off(xE.NEED_MUTE_TRACK,this.handleMuteLocalTrack),i.off(xE.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(i,o){o instanceof DT&&o.addListener(xE.GET_STATS,p=>{p(this.handleGetRemoteVideoStats(i))}),o instanceof cT&&o.addListener(xE.GET_STATS,p=>{p(this.handleGetRemoteAudioStats(i))})}unbindRemoteTrackEvents(i){i&&i.removeAllListeners(xE.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(i=>{let[o,p]=i;p.has(ME.AUDIO)&&this.unbindRemoteTrackEvents(o._audioTrack),p.has(ME.VIDEO)&&this.unbindRemoteTrackEvents(o._videoTrack)})}createGatewayPublishMessage(i,o){return i.map((p,g)=>{var b;let A,j,{track:H,type:z}=p;switch(z){case TE.LocalAudioTrack:A=v_.Audio,j={dtx:H instanceof yR&&H._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case TE.LocalVideoTrack:A=VE(b=H._hints).call(b,A_.SCREEN_TRACK)?v_.Screen:v_.High,j=NR(NR({},rP(H)),{},{codec:this.store.codec});break;case TE.LocalVideoLowTrack:A=v_.Low,j=NR(NR({},rP(H)),{},{codec:this.store.codec})}return{stream_type:A,attributes:j,ssrcs:o[g]}})}createGatewayUnpublishMessage(i){return i.map(o=>{var p;let g,[b,{track:A,ssrcs:j,id:H}]=o;switch(b){case TE.LocalVideoTrack:g=VE(p=A._hints).call(p,A_.SCREEN_TRACK)?v_.Screen:v_.High;break;case TE.LocalAudioTrack:g=v_.Audio;break;case TE.LocalVideoLowTrack:g=v_.Low}return{stream_type:g,ssrcs:j,mid:H}})}assignLocalTracks(i,o){i.forEach((p,g)=>{let{track:b,type:A}=p;this.localTrackMap.set(A,{track:b,id:o[g].id,ssrcs:o[g].localSSRC})})}withdrawLocalTracks(i){i.forEach(o=>{let[p]=o;this.localTrackMap.delete(p)})}bindConnectionEvents(i){i.onConnectionStateChange=async o=>{if(Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(o,")")),this.emit(WE.PeerConnectionStateChange,o),o!=="connected"||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),o==="connected"&&(this._restartTimer&&(clearTimeout(this._restartTimer),this._restartTimer=void 0),(this._isFirstConnected||this._isInRestartIce)&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isInRestartIce=!1,this._isFirstConnected=!1,this._isStartRestartIce=!1),nE("NEW_ICE_RESTART")){var p;if(VE(p=this._restartStates).call(p,o)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const g=j=>{(i.iceConnectionState==="disconnected"||i.iceConnectionState==="checking"||i.iceConnectionState==="failed")&&(Gi.debug("[".concat(this.store.clientId,"] [P2PChannel] start use restartICE, type is ").concat(j)),oS(this,WE.QueryClientConnectionState)==="CONNECTED"&&this.emit(WE.RequestRestartICE,j))},b=()=>{i.iceConnectionState!=="disconnected"&&i.iceConnectionState!=="checking"&&i.iceConnectionState!=="failed"||(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),Gi.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout(()=>this.emit(WE.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect())},A=nE("ICE_RESTART_INTERVAL");return void(this._restartTimer=window.setTimeout(()=>{if(nE("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&I_().supportPCSetConfiguration)g(N0.RELAY),this._restartTimer=window.setTimeout(b,A);else if(N_())g(N0.UDP),this._restartTimer=window.setTimeout(b,4e3);else{if(g(N0.TCP),I_().supportPCSetConfiguration)return void(this._restartTimer=window.setTimeout(()=>{g(N0.RELAY),this._restartTimer=window.setTimeout(b,A)},A));this._restartTimer=window.setTimeout(b,A)}},800))}}else{if(o==="disconnected"&&i.iceConnectionState==="disconnected")return setTimeout(()=>{i.iceConnectionState==="disconnected"&&nE("ICE_RESTART")&&oS(this,WE.QueryClientConnectionState)==="CONNECTED"&&this.emit(WE.RequestRestartICE)},800),void setTimeout(()=>{i.peerConnectionState==="disconnected"&&(Gi.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection disconnected timeout 4000ms, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isInRestartIce=!1,setTimeout(()=>this.emit(WE.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect())},4e3);o==="failed"&&(Gi.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection state failed, force reconnect")),this.reportPCDisconnectedOrFailed(),setTimeout(()=>this.emit(WE.P2PLost),0),this.iceFailedCount+=1,await this.requestReconnect())}},i.onICEConnectionStateChange=o=>{o!=="connected"||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(o,")")),jE.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:o,tag:x_.TRACER}).onSuccess(),this.emit(WE.IceConnectionStateChange,o)},i.onICETransportStateChange=o=>{Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(o,")"))},i.onDTLSTransportStateChange=o=>{Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(o,")"))},i.onDTLSTransportError=o=>{Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(o,")"))},i.onFirstAudioDecoded=o=>{var p;const g=Array.from(CS(p=this.remoteUserMap).call(p)).find(A=>A._audioSSRC===o);var b;g&&(this.store.subscribe(g.uid,"audio",void 0,void 0,void 0,Date.now()),(b=g.audioTrack)===null||b===void 0||b.emit(sI.FIRST_FRAME_DECODED),jE.firstRemoteFrame(this.store.sessionId,p0.FIRST_AUDIO_DECODE,L_.FIRST_AUDIO_DECODE,{peer:g._uintid,subscribeElapse:k0.measureFromSubscribeStart(this.store.clientId,o),subscribeRequestid:o,p2pid:this.store.p2pId}))},i.onFirstAudioReceived=o=>{var p;const g=Array.from(CS(p=this.remoteUserMap).call(p)).find(b=>b._audioSSRC===o);g&&jE.firstRemoteFrame(this.store.sessionId,p0.FIRST_AUDIO_RECEIVED,L_.FIRST_AUDIO_RECEIVED,{peer:g._uintid,subscribeElapse:k0.measureFromSubscribeStart(this.store.clientId,o),subscribeRequestid:o,p2pid:this.store.p2pId})},i.onFirstVideoDecoded=(o,p,g)=>{this.reportVideoFirstFrameDecoded(o,p,g)},i.onFirstVideoReceived=o=>{var p;const g=Array.from(CS(p=this.remoteUserMap).call(p)).find(b=>b._videoSSRC===o);g&&jE.firstRemoteFrame(this.store.sessionId,p0.FIRST_VIDEO_RECEIVED,L_.FIRST_VIDEO_RECEIVED,{peer:g._uintid,subscribeElapse:k0.measureFromSubscribeStart(this.store.clientId,o),subscribeRequestid:o,p2pid:this.store.p2pId})},i.onSelectedLocalCandidateChanged=(o,p)=>{const g=o.candidateType==="relay",b=p.candidateType==="relay";p.candidateType!=="unknown"&&g===b||this.emit(WE.ConnectionTypeChange,g),Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(wR(p))," -> ").concat(JSON.stringify(wR(o)),")"))},i.onSelectedRemoteCandidateChanged=(o,p)=>{Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(wR(p))," -> ").concat(JSON.stringify(wR(o)),")"))},i.onFirstVideoDecodedTimeout=o=>{this.reportVideoFirstFrameDecoded(o,void 0,void 0,!0)}}unbindConnectionEvents(i){i.onConnectionStateChange=void 0,i.onICEConnectionStateChange=void 0,i.onICETransportStateChange=void 0,i.onDTLSTransportStateChange=void 0,i.onDTLSTransportError=void 0,i.onFirstAudioDecoded=void 0,i.onFirstAudioReceived=void 0,i.onFirstVideoDecoded=void 0,i.onFirstVideoReceived=void 0,i.onSelectedLocalCandidateChanged=void 0,i.onSelectedRemoteCandidateChanged=void 0,i.onFirstVideoDecodedTimeout=void 0}filterTobeMutedTracks(i){const o=[];if(this.getAllTracks().indexOf(i)===-1)return o;const p=this.localTrackMap.get(TE.LocalAudioTrack);if(i instanceof g_&&(p==null?void 0:p.track)instanceof Z_)return p.track.isActive||o.push([TE.LocalAudioTrack,p]),o;const g=Array.from(this.localTrackMap.entries()).find(b=>{let[,{track:A}]=b;return i===A});if(g&&(o.push(g),g[0]===TE.LocalVideoTrack)){const b=this.localTrackMap.get(TE.LocalVideoLowTrack);b&&o.push([TE.LocalVideoLowTrack,b])}return o}filterTobeUnmutedTracks(i){const o=[],p=this.localTrackMap.get(TE.LocalAudioTrack);if(i instanceof g_&&(p==null?void 0:p.track)instanceof Z_)return p.track.isActive&&o.push([TE.LocalAudioTrack,p]),o;const g=Array.from(this.localTrackMap.entries()).find(b=>{let[,{track:A}]=b;return i===A});if(g)if(g[0]===TE.LocalVideoTrack){o.push(g);const b=this.localTrackMap.get(TE.LocalVideoLowTrack);b&&o.push([TE.LocalVideoLowTrack,b])}else o.push(g);return o}createMuteMessage(i){return i.map(o=>{var p;let g,[b,{track:A,ssrcs:j,id:H}]=o;switch(b){case TE.LocalAudioTrack:g=v_.Audio;break;case TE.LocalVideoTrack:g=VE(p=A._hints).call(p,A_.SCREEN_TRACK)?v_.Screen:v_.High;break;case TE.LocalVideoLowTrack:g=v_.Low}return{stream_type:g,ssrcs:j,mid:H}})}createUnmuteMessage(i){return i.map(o=>{var p;let g,[b,{track:A,ssrcs:j,id:H}]=o;switch(b){case TE.LocalAudioTrack:g=v_.Audio;break;case TE.LocalVideoTrack:g=VE(p=A._hints).call(p,A_.SCREEN_TRACK)?v_.Screen:v_.High;break;case TE.LocalVideoLowTrack:g=v_.Low}return{stream_type:g,ssrcs:j,mid:H}})}filterTobeUnSubscribedTracks(i,o){const p=[],g=this.remoteUserMap.get(i);if(!g)return p;if(o){const b=g.get(o);if(!b)return p;p.push([i,{kind:o,id:b}])}else Array.from(g.entries()).forEach(b=>{let[A,j]=b;p.push([i,{kind:A,id:j}])});return p}filterTobeUnSubscribedDataChannels(i,o){const p=[];return o.forEach(g=>{var b;(b=this.remoteDataChannelMap.get(i))!==null&&b!==void 0&&b.has(g.id)&&p.push(g)}),p}createUnsubscribeMessage(i){const o=[];return i.forEach(p=>{let[g,{kind:b,id:A}]=p;switch(b){case ME.VIDEO:return void(g._videoSSRC&&o.push({stream_type:ME.VIDEO,ssrcId:g._videoSSRC}));case ME.AUDIO:return void(g._audioSSRC&&o.push({stream_type:ME.AUDIO,ssrcId:g._audioSSRC}))}}),o}createUnsubscribeAllMessage(i){const o=new Map;return i.forEach(p=>{let[g,{kind:b}]=p;if(o.has(g)){let A=o.get(g);b===ME.VIDEO?A|=n0.Video:A|=n0.Audio,o.set(g,A)}else b===ME.VIDEO?o.set(g,n0.Video):o.set(g,n0.Audio)}),{users:Array.from(o.entries()).map(p=>{let[g,b]=p;return{stream_id:g.uid,stream_type:b}})}}withdrawRemoteTracks(i){i.forEach(o=>{let[p,{kind:g}]=o;const b=this.remoteUserMap.get(p);b&&(b.delete(g),Array.from(b.entries()).length===0&&this.remoteUserMap.delete(p))})}async updateBitrateLimit(i){const o=this.localTrackMap.get(TE.LocalVideoTrack),p=this.localTrackMap.get(TE.LocalVideoLowTrack);o&&await o.track.setBitrateLimit(i.uplink),p&&i.low_stream_uplink&&await p.track.setBitrateLimit({max_bitrate:i.low_stream_uplink.bitrate,min_bitrate:i.low_stream_uplink.bitrate||0})}isP2PDisconnected(){return this.connection?this.connection.peerConnectionState!=="connected":!0}mapPubResToRemoteConfig(i,o){return i.map((p,g)=>{var b;let{stream_type:A}=p;return(b=o.find(j=>{let{stream_type:H}=j;return A===H}))===null||b===void 0?void 0:b.attributes})}async tryToUnmuteAudio(i){for(let p=0;p{let[,{id:j}]=A;return j})));const b=this.createUnmuteMessage(g);return void await S_(this,WE.RequestUnmuteLocal,b)}}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=i=>{var o;return!((o=this.connection)===null||o===void 0||!o.getRemoteVideoIsReady(i))},this.statsUploader.requestUpload=(i,o)=>this.emit(WE.RequestUploadStats,i,o),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 w0(mN(this.dtlsFailedCount,$_)),this.emit(WE.RequestReconnect)}async reconnectP2P(){const i=Array.from(this.localTrackMap.entries()),o=this.createGatewayUnpublishMessage(i);Array.from(this.remoteUserMap.entries()),o.length>0&&await U_(this,WE.RequestUnpublishForReconnectPC,o),this.disconnectForReconnect(),this.emit(WE.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(TE.LocalVideoTrack)||this.pendingLocalTracks.some(i=>i instanceof ZE)}throwIfTrackTypeNotMatch(i){if(i.filter(o=>o instanceof ZE).length>1)throw new yE(_p.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(i.filter(o=>o instanceof g_).length>1&&(i.some(o=>o instanceof g_&&o._bypassWebAudio)||!I_().webAudioMediaStreamDest))throw new yE(_p.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const o of i){if(o instanceof ZE&&this.pendingLocalTracks.some(p=>p instanceof ZE))throw new yE(_p.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(o instanceof g_&&this.pendingLocalTracks.some(p=>p instanceof g_)&&(!I_().webAudioMediaStreamDest||o._bypassWebAudio||this.pendingLocalTracks.some(p=>p instanceof g_&&p._bypassWebAudio)))throw new yE(_p.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(i,o){const p=!nE("DISABLE_DUAL_STREAM_USE_ENCODING")&&I_().supportDualStreamEncoding,g=NR(NR({},{width:160,height:120,framerate:15,bitrate:50}),o);let b;b=p?i._mediaStreamTrack.clone():C2(i,g);const A=T_(8,"track-low-"),j=new ZE(b,NR(NR({},p&&{scaleResolutionDownBy:c2(g,i)}),{},{frameRate:g.framerate,bitrateMax:g.bitrate,bitrateMin:g.bitrate}),void 0,void 0,A);return j.on($I.TRANSCEIVER_UPDATED,H=>{i._updateRtpTransceiver(H,vR.LOW_STREAM)}),j._hints.push(A_.LOW_STREAM),i.addListener(xE.NEED_CLOSE,()=>{j.close()}),j}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock")}async reportPCStats(i,o,p){let g=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;if(this.connection&&this.connection instanceof c0){var b,A,j,H;const z=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:$,dtlsTransportState:Vt,peerConnectionState:_r}=this.connection,{local:Fi,remote:_l}=await this.connection.getSelectedCandidatePair();jE.pcStats(this.store.sessionId,{startTime:z,eventElapse:i-z||0,iceconnectionsate:$,dtlsstate:Vt,connectionstate:_r,intSucc:o?1:2,error:g,selectedLocalCandidateProtocol:(b=Fi==null?void 0:Fi.protocol)!==null&&b!==void 0?b:"",selectedLocalCandidateType:(A=Fi.candidateType)!==null&&A!==void 0?A:"",selectedLocalCandidateAddress:"".concat(Fi.address,":").concat(Fi.port),selectedRemoteCandidateProtocol:(j=_l.protocol)!==null&&j!==void 0?j:"",selectedRemoteCandidateType:(H=_l.candidateType)!==null&&H!==void 0?H:"",selectedRemoteCandidateAddress:"".concat(_l.address,":").concat(_l.port),restartCnt:p})}}reportVideoFirstFrameDecoded(i,o,p,g){var b;const A=Array.from(CS(b=this.remoteUserMap).call(b)).find(j=>j._videoSSRC===i);if(A){g||this.store.subscribe(A.uid,"video",void 0,void 0,void 0,void 0,Date.now());const j=this.store.keyMetrics,H=j.subscribe.find(z=>z.userId===A.uid&&z.type==="video");jE.firstRemoteVideoDecode(this.store.sessionId,p0.FIRST_VIDEO_DECODE,L_.FIRST_VIDEO_DECODE,{peer:A._uintid,videowidth:o,videoheight:p,subscribeElapse:k0.measureFromSubscribeStart(this.store.clientId,i),subscribeRequestid:i,p2pid:this.store.p2pId,apEnd:j.requestAPEnd||0,apStart:j.requestAPStart||0,joinGwEnd:j.joinGatewayEnd||0,joinGwStart:j.joinGatewayStart||0,pcEnd:j.peerConnectionEnd||0,pcStart:j.peerConnectionStart||0,subscriberEnd:(H==null?void 0:H.subscribeEnd)||0,subscriberStart:(H==null?void 0:H.subscribeStart)||0,videoAddNotify:(H==null?void 0:H.streamAdded)||0,state:g?1:0})}}async remoteMediaSsrcChanged(i,o,p){if(!this.connection)return!1;const g=this.remoteUserMap.get(i);if(!g)return!1;const b=g.get(o);if(!b)return!1;const A=await this.connection.getRemoteSSRC(b);return A!==void 0&&A!==p}resetConnection(i){Gi.debug("[".concat(this.store.clientId,"] [P2PChannel] reset connection to ").concat(i)),this.state===u_.Connected?(Gi.debug("[".concat(this.store.clientId,"] [P2PChannel] fallback to websocket but P2PChannel state still connected, disconnect first")),this.disconnectForReconnect()):(this.connection&&(this.connection.close(),this.unbindConnectionEvents(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=i===wN.datachannel?new u0({},this.store):this.isPlanB?new b0({},this.store):new c0({},this.store),this.bindConnectionEvents(this.connection)))}unbindRtpTransceiver(){this.localTrackMap.size!==0&&Array.from(this.localTrackMap.entries()).forEach(i=>{let[o,{track:p}]=i;o===TE.LocalVideoLowTrack?p._updateRtpTransceiver(void 0,vR.LOW_STREAM):p._updateRtpTransceiver(void 0)})}reportPCDisconnectedOrFailed(i){this.connection&&this.connection instanceof c0&&(this.connection.iceConnectionState!=="disconnected"&&this.connection.iceConnectionState!=="checking"&&this.connection.iceConnectionState!=="failed"||(this._isFirstConnected?(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isFirstConnected=!1):this._pcStatsUploadType===yT.TCP_RESTART&&i===N0.RELAY?this.reportPCStats(Date.now(),!1,this._pcStatsUploadType):this.reportPCStats(Date.now(),!1,yT.DISCONNECTED_OR_FAILED)))}}function q0(l,i,o){const p=l[i];if(typeof p!="function")throw new Error("Cannot use mutex on object property.");return o.value=async function(){const g=this.mutex,b=await g.lock("From P2PChannel.".concat(i));try{for(var A=arguments.length,j=new Array(A),H=0;H>>3){case 0:break t;case 1:p.code=VT(o);break;case 2:p.msg=h8(o,VT(o));break;case 3:{let b=Ket(o);p.data=Het(o),o.limit=b;break}default:c8(o,7&g)}}return p}({bytes:i=l,offset:0,limit:i.length});var i}function Het(l){let i={};t:for(;!d8(l);){let o=VT(l);switch(o>>>3){case 0:break t;case 1:i.requestId=h8(l,VT(l));break;case 2:i.requestType=VT(l)>>>0;break;case 3:i.scorePorn=P2(l);break;case 4:i.scoreSexy=P2(l);break;case 5:i.scoreNeutral=P2(l);break;case 6:i.requestScene=VT(l)>>>0;break;case 7:i.scene=VT(l)>>>0;break;default:c8(l,7&o)}}return i}function zet(l,i){let o=l.service;o!==void 0&&(E_(i,8),E_(i,o));let p=l.vendor;p!==void 0&&(E_(i,16),E_(i,p));let g=l.token;g!==void 0&&(E_(i,26),jT(i,g));let b=l.callbackUrl;b!==void 0&&(E_(i,34),jT(i,b))}function Ket(l){let i=VT(l),o=l.limit;return l.limit=l.offset+i,o}function c8(l,i){switch(i){case 0:for(;128&p8(l););break;case 2:O2(l,VT(l));break;case 5:O2(l,4);break;case 1:O2(l,8);break;default:throw new Error("Unimplemented type: "+i)}}bE([q0,kc("design:type",Function),kc("design:paramtypes",[Object,Boolean]),kc("design:returntype",pE)],S0.prototype,"startP2PConnection",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[Object,Object,Array,Object,String,String]),kc("design:returntype",pE)],S0.prototype,"connect",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[Array]),kc("design:returntype",void 0)],S0.prototype,"updateRemoteRTPCapabilities",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[Object,Object,Array,Object,String,String]),kc("design:returntype",pE)],S0.prototype,"preConnect",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[Array]),kc("design:returntype",pE)],S0.prototype,"publishDataChannel",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[Array]),kc("design:returntype",pE)],S0.prototype,"unpublish",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[Array]),kc("design:returntype",pE)],S0.prototype,"unpublishDataChannel",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",pE)],S0.prototype,"unpublishLowStream",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[D0,Array]),kc("design:returntype",pE)],S0.prototype,"subscribeDataChannel",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[D0,String,Number,Number,Array]),kc("design:returntype",pE)],S0.prototype,"subscribe",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[Array]),kc("design:returntype",pE)],S0.prototype,"massSubscribe",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[D0,String,Boolean]),kc("design:returntype",pE)],S0.prototype,"unsubscribe",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[D0,Array]),kc("design:returntype",pE)],S0.prototype,"unsubscribeDataChannel",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[Array]),kc("design:returntype",pE)],S0.prototype,"massUnsubscribe",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[D0,String]),kc("design:returntype",pE)],S0.prototype,"muteRemote",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[D0,String]),kc("design:returntype",pE)],S0.prototype,"unmuteRemote",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[D0,String]),kc("design:returntype",pE)],S0.prototype,"hasRemoteMediaWithLock",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",pE)],S0.prototype,"disconnectForReconnect",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",pE)],S0.prototype,"updateBitrateLimit",null),bE([q0,kc("design:type",Function),kc("design:paramtypes",[D0,String,Number]),kc("design:returntype",pE)],S0.prototype,"remoteMediaSsrcChanged",null);let Yet=new Float32Array(1);new Uint8Array(Yet.buffer);let A2=new Float64Array(1),pS=new Uint8Array(A2.buffer);function lO(l){return{low:l|=0,high:l>>31,unsigned:l>=0}}let u8=[];function l8(){const l=u8.pop();return l?(l.offset=l.limit=0,l):{bytes:new Uint8Array(64),offset:0,limit:0}}function Jet(l){u8.push(l)}function O2(l,i){if(l.offset+i>l.limit)throw new Error("Skip past limit");l.offset+=i}function d8(l){return l.offset>=l.limit}function dO(l,i){let o=l.bytes,p=l.offset,g=l.limit,b=p+i;if(b>o.length){let A=new Uint8Array(2*b);A.set(o),l.bytes=A}return l.offset=b,b>g&&(l.limit=b),p}function N2(l,i){let o=l.offset;if(o+i>l.limit)throw new Error("Read past limit");return l.offset+=i,o}function h8(l,i){let o=N2(l,i),p=String.fromCharCode,g=l.bytes,b="�",A="";for(let j=0;j=i?A+=b:(H=g[j+o+1],(192&H)!=128?A+=b:(Vt=(31&_r)<<6|63&H,Vt<128?A+=b:(A+=p(Vt),j++))):(240&_r)==224?j+2>=i?A+=b:(H=g[j+o+1],z=g[j+o+2],(49344&(H|z<<8))!=32896?A+=b:(Vt=(15&_r)<<12|(63&H)<<6|63&z,Vt<2048||Vt>=55296&&Vt<=57343?A+=b:(A+=p(Vt),j+=2))):(248&_r)==240?j+3>=i?A+=b:(H=g[j+o+1],z=g[j+o+2],$=g[j+o+3],(12632256&(H|z<<8|$<<16))!=8421504?A+=b:(Vt=(7&_r)<<18|(63&H)<<12|(63&z)<<6|63&$,Vt<65536||Vt>1114111?A+=b:(Vt-=65536,A+=p(55296+(Vt>>10),56320+(1023&Vt)),j+=3))):A+=b:A+=p(_r)}return A}function jT(l,i){let o=i.length,p=0;for(let A=0;A=55296&&j<=56319&&A+1=55296&&j<=56319&&A+1>6&31|192:(j<65536?b[g++]=j>>12&15|224:(b[g++]=j>>18&7|240,b[g++]=j>>12&63|128),b[g++]=j>>6&63|128),b[g++]=63&j|128)}}function Xet(l,i){let o=dO(l,i.limit),p=l.bytes,g=i.bytes;for(let b=0,A=i.limit;b>>=0;i>=128;)f8(l,127&i|128),i>>>=7;f8(l,i)}function PR(l,i){let o=i.low>>>0,p=(i.low>>>28|i.high<<4)>>>0,g=i.high>>>24,b=g===0?p===0?o<16384?o<128?1:2:o<1<<21?3:4:p<16384?p<128?5:6:p<1<<21?7:8:g<128?9:10,A=dO(l,b),j=l.bytes;switch(b){case 10:j[A+9]=g>>>7&1;case 9:j[A+8]=b!==9?128|g:127&g;case 8:j[A+7]=b!==8?p>>>21|128:p>>>21&127;case 7:j[A+6]=b!==7?p>>>14|128:p>>>14&127;case 6:j[A+5]=b!==6?p>>>7|128:p>>>7&127;case 5:j[A+4]=b!==5?128|p:127&p;case 4:j[A+3]=b!==4?o>>>21|128:o>>>21&127;case 3:j[A+2]=b!==3?o>>>14|128:o>>>14&127;case 2:j[A+1]=b!==2?o>>>7|128:o>>>7&127;case 1:j[A]=b!==1?128|o:127&o}}function m8(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}const Qet=new Map([["moderation",1],["supervise",2]]);class bP extends D_{get connectionState(){return this._connectionState}set connectionState(i){if(this._connectionState===i)return;const o=this._connectionState;this._connectionState=i,this.emit(a0.CONNECTION_STATE_CHANGE,o,i)}get inspectType(){return this._inspectType}set inspectType(i){var o;this._inspectMode=_C(o=i.map(p=>Qet.get(p)||0)).call(o,(p,g)=>p+g),this._inspectType=i}get quality(){return this._quality}set quality(i){this._quality=i>1?1:i<.1?.1:i,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout(()=>{this.quality=this._quality/this.qualityRatio},6e4))}constructor(i){super(),_e(this,"name","AgoraRTCVideoContentInspect"),_e(this,"_connectionState",OS.CONNECTING),_e(this,"_innerConnectionState",void 0),_e(this,"sequence",0),_e(this,"inspectStartTime",void 0),_e(this,"workerManagerConnection",void 0),_e(this,"workerConnection",void 0),_e(this,"workerMessageLengthLimit",void 0),_e(this,"inspectIntervalMinimum",void 0),_e(this,"qualityRatio",void 0),_e(this,"_connectInfo",void 0),_e(this,"_cancelTokenSource",aS.CancelToken.source()),_e(this,"_retryConfig",void 0),_e(this,"wmSequence",0),_e(this,"inspectInterval",void 0),_e(this,"inspectTimer",null),_e(this,"ossFilePrefix",void 0),_e(this,"extraInfo",void 0),_e(this,"_inspectType",void 0),_e(this,"_inspectMode",void 0),_e(this,"_quality",1),_e(this,"qualityTimer",null),_e(this,"_inspectId",void 0),_e(this,"_needWorkUrlOnly",!1),_e(this,"inspectImage",()=>{if(this.connectionState!==OS.CONNECTED)throw new hE(_p.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===OS.CONNECTED?this.requestToInspectImage():Gi.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)},this.inspectInterval{this._innerConnectionState=o,Gi.debug("[".concat(this._inspectId,"] Inspect operation :").concat(NS[o]," ").concat(p||""))}),this.handleWorkerManagerEvents(),this.workerConnection=new zO("worker-"+this._inspectId,$_),this.handleWorkerEvents()}async init(i,o){this.emit(a0.STATE_CHANGE,NS.CONNECT_AP),this._connectInfo=i;const p=this._cancelTokenSource.token;return this._retryConfig=o,new pE((g,b)=>{this.on(a0.CONNECTION_STATE_CHANGE,(A,j)=>{j===OS.CONNECTED&&g()}),this.requestAP(i,p,o).then(A=>{this.connectWorkerManager(A)}).catch(A=>{b(A)})})}async requestAP(i,o,p){const g=nE("WEBCS_DOMAIN").map(j=>"https://".concat(j,"/api/v1")),b=await function(j,H,z,$){let{appId:Vt,areaCode:_r,cname:Fi,sid:_l,token:_u,uid:_h}=H;aO++;const _g="image_moderation_api",eE={service_name:_g,json_body:JSON.stringify({appId:Vt,areaCode:_r,cname:Fi,command:"allocateEdge",requestId:aO,seq:aO,sid:_l,token:_u,ts:Date.now(),uid:_h+""})};let oE,SE,vE=j[0];return vT(async()=>{oE=Date.now();const fE=await nR(vE,{data:eE,cancelToken:z,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(SE=Date.now()-oE,fE.code!==0){const OE=new hE(_p.UNEXPECTED_RESPONSE,"image inspect ap error, code"+fE.code,{retry:!0,responseTime:SE});throw Gi.error(OE.toString()),OE}const mE=JSON.parse(fE.json_body);if(mE.code!==200){const OE=new hE(_p.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(mE.code,", reason: ").concat(mE.reason),{code:mE.code,responseTime:SE});throw Gi.error(OE.toString()),OE}if(!mE.servers||!Array.isArray(mE.servers)||mE.servers.length===0){const OE=new hE(_p.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:mE.code,responseTime:SE});throw Gi.error(OE.toString()),OE}const EE=nE("VIDEO_INSPECT_WORKER_MANAGER_HOST"),PE=nE("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:mE.servers.map(OE=>{let{address:$E,wss:s_}=OE;if($E&&s_)return"wss://".concat($E.replace(/\./g,"-"),".").concat(EE,":").concat(PE||s_)}).filter(OE=>!!OE),workerToken:mE.workerToken,vid:mE.vid,responseTime:SE}},(fE,mE)=>(jE.apworkerEvent(_l,{success:!0,sc:200,serviceName:_g,responseDetail:JSON.stringify(fE.addressList),firstSuccess:mE===0,responseTime:SE,serverIp:j[mE%j.length]}),!1),(fE,mE)=>(jE.apworkerEvent(_l,{success:!1,sc:fE.data&&fE.data.code||200,serviceName:_g,responseTime:SE,serverIp:j[mE%j.length]}),!!(fE.code!==_p.OPERATION_ABORTED&&fE.code!==_p.UNEXPECTED_RESPONSE||fE.data&&fE.data.retry)&&(vE=j[(mE+1)%j.length],!0)),$)}(g,i,o,p);this.emit(a0.STATE_CHANGE,NS.AP_CONNECTED);const{addressList:A}=b;return this.wmSequence++,A}async connectWorkerManager(i){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this._needWorkUrlOnly=o,this.emit(a0.STATE_CHANGE,NS.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(i,1e4)}async connectWorker(i){await this.workerConnection.init([i])}handleWorkerManagerEvents(){this.workerManagerConnection.on(zE.CONNECTED,async()=>{this.emit(a0.STATE_CHANGE,NS.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.19.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(zE.CLOSED,()=>{this._innerConnectionState{this._innerConnectionState{this._innerConnectionState{this.emit(a0.STATE_CHANGE,NS.GET_WORKER_MANAGER_RESPONSE);const o=this.workerManagerConnection.url;this.workerManagerConnection.close();const p=JSON.parse(i.data);if(p.code!==200)throw Gi.error("[".concat(this._inspectId,"] Unexpected code ").concat(p.code," from worker manager")),new hE(_p.UNEXPECTED_RESPONSE,"response code of worker is unexpected",p);if(!(p.serverResponse&&p.serverResponse.portWss&&o))throw Gi.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(p))),new hE(_p.UNEXPECTED_RESPONSE,"response content of worker is unexpected",p);{const g=nE("VIDEO_INSPECT_WORKER_PORT")||p.serverResponse.portWss,b=o.replace(/:\d+\/?$/,":".concat(g));this.emit(a0.STATE_CHANGE,NS.CONNECT_WORKER,b),this._needWorkUrlOnly?this.emit(a0.REQUEST_NEW_WORKER_URL,b):await this.connectWorker(b)}}),this.workerManagerConnection.on(zE.WILL_RECONNECT,(i,o,p)=>{p(i)}),this.workerManagerConnection.on(zE.REQUEST_NEW_URLS,(i,o)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(i).catch(o)})}handleWorkerEvents(){this.workerConnection.on(zE.CONNECTED,async()=>{this.emit(a0.STATE_CHANGE,NS.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=OS.CONNECTED}),this.workerConnection.on(zE.ON_MESSAGE,async i=>{if(i.data instanceof ArrayBuffer){const p=Wet(new Uint8Array(i.data));if(nE("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&Gi.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(p)),p.code===200){if(Array.isArray(this.inspectType)&&this.inspectType.length===1&&this.inspectType[0]==="supervise")return void this.emit(a0.INSPECT_RESULT,void 0,void 0);if(p.data&&p.data.scorePorn&&p.data.scoreSexy&&p.data.scoreNeutral){var o;const g={porn:p.data.scorePorn,sexy:p.data.scoreSexy,neutral:p.data.scoreNeutral},b=_C(o=Object.keys(g)).call(o,(j,H)=>g[j]>g[H]?j:H,"porn"),A=Object.keys(g).find(j=>j===b);this.emit(a0.INSPECT_RESULT,A)}else this.emit(a0.INSPECT_RESULT,void 0,new hE(_p.UNEXPECTED_RESPONSE,p.code+"","There is an unexpected data on message"))}else this.emit(a0.INSPECT_RESULT,void 0,new hE(_p.UNEXPECTED_RESPONSE,p.code+"",p.msg))}else Gi.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(a0.INSPECT_RESULT,void 0,new hE(_p.UNEXPECTED_RESPONSE,"invalid worker message type"))}),this.workerConnection.on(zE.CLOSED,()=>{this.connectionState=OS.CLOSED}),this.workerConnection.on(zE.FAILED,()=>{this.connectionState=OS.CLOSED}),this.workerConnection.on(zE.RECONNECTING,()=>{this.connectionState=this.connectionState===OS.CONNECTED?OS.RECONNECTING:OS.CONNECTING}),this.workerConnection.on(zE.WILL_RECONNECT,(i,o,p)=>{i==="recover"&&p(i),p("tryNext")}),this.workerConnection.on(zE.REQUEST_NEW_URLS,(i,o)=>{this.workerManagerConnection.close(),this.once(a0.REQUEST_NEW_WORKER_URL,p=>{i([p])}),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(p=>{this.connectWorkerManager(p,!0)}).catch(p=>{o(p)})})}static intToLong(i){return{low:i|=0,high:i>>31,unsigned:i>=0}}async requestToInspectImage(){this.sequence++;const i=oS(this,a0.CLIENT_LOCAL_VIDEO_TRACK),o={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(i){if(!i.isPlaying)return void this.emit(a0.INSPECT_RESULT,void 0,new hE(_p.INVALID_OPERATION,"Only the track being played can be inspected"));const p=await this.generateRequestData(i,o);this.workerConnection.sendMessage(p,!0,!0)}else this.emit(a0.INSPECT_RESULT,void 0,new hE(_p.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(i,o){let{appId:p,cname:g,cid:b,vid:A,sid:j,uid:H}=o;const z=Date.now(),$=await i.getCurrentFrameImage("image/jpeg",this.quality),Vt=await a4($,p,g),_r=this.sequence+"-"+b+"-"+H+"-"+z+"-"+T_(12,""),Fi={appId:p,cid:b,cname:g,deviceId:"",elapse:bP.intToLong(Number(z-this.inspectStartTime)),fileSize:Vt.byteLength,jpgEncryption:2,height:$.height,width:$.width,jpg:Vt,networkType:6,osType:7,requestId:_r,sdkVersion:"4.19.3",sequence:this.sequence,sid:j,timestamp:bP.intToLong(z),uid:H,vid:A,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};this.extraInfo===void 0&&delete Fi.callbackData,this.ossFilePrefix===void 0&&delete Fi.ossFilePrefix;const _l=qet(Fi);if(_l.byteLength>>3){case 0:break t;case 1:p.code=E1(o);break;case 2:p.msg=v8(o,E1(o));break;case 3:p.requestId=v8(o,E1(o));break;case 4:p.timestamp=rnt(o,!1);break;default:tnt(o,7&g)}}return p}({bytes:i=l,offset:0,limit:i.length});var i}function tnt(l,i){switch(i){case 0:for(;128&pT(l););break;case 2:D2(l,E1(l));break;case 5:D2(l,4);break;case 1:D2(l,8);break;default:throw new Error("Unimplemented type: "+i)}}function hO(l){return{low:l|=0,high:l>>31,unsigned:l>=0}}let ent=[];function D2(l,i){if(l.offset+i>l.limit)throw new Error("Skip past limit");l.offset+=i}function nnt(l){return l.offset>=l.limit}function SP(l,i){let o=l.bytes,p=l.offset,g=l.limit,b=p+i;if(b>o.length){let A=new Uint8Array(2*b);A.set(o),l.bytes=A}return l.offset=b,b>g&&(l.limit=b),p}function g8(l,i){let o=l.offset;if(o+i>l.limit)throw new Error("Read past limit");return l.offset+=i,o}function E8(l,i){let o=SP(l,i.length);l.bytes.set(i,o)}function v8(l,i){let o=g8(l,i),p=String.fromCharCode,g=l.bytes,b="�",A="";for(let j=0;j=i?A+=b:(H=g[j+o+1],(192&H)!=128?A+=b:(Vt=(31&_r)<<6|63&H,Vt<128?A+=b:(A+=p(Vt),j++))):(240&_r)==224?j+2>=i?A+=b:(H=g[j+o+1],z=g[j+o+2],(49344&(H|z<<8))!=32896?A+=b:(Vt=(15&_r)<<12|(63&H)<<6|63&z,Vt<2048||Vt>=55296&&Vt<=57343?A+=b:(A+=p(Vt),j+=2))):(248&_r)==240?j+3>=i?A+=b:(H=g[j+o+1],z=g[j+o+2],$=g[j+o+3],(12632256&(H|z<<8|$<<16))!=8421504?A+=b:(Vt=(7&_r)<<18|(63&H)<<12|(63&z)<<6|63&$,Vt<65536||Vt>1114111?A+=b:(Vt-=65536,A+=p(55296+(Vt>>10),56320+(1023&Vt)),j+=3))):A+=b:A+=p(_r)}return A}function vI(l,i){let o=i.length,p=0;for(let A=0;A=55296&&j<=56319&&A+1=55296&&j<=56319&&A+1>6&31|192:(j<65536?b[g++]=j>>12&15|224:(b[g++]=j>>18&7|240,b[g++]=j>>12&63|128),b[g++]=j>>6&63|128),b[g++]=63&j|128)}}function pT(l){return l.bytes[g8(l,1)]}function _8(l,i){let o=SP(l,1);l.bytes[o]=i}function E1(l){let i,o=0,p=0;do i=pT(l),o<32&&(p|=(127&i)<>>=0;i>=128;)_8(l,127&i|128),i>>>=7;_8(l,i)}function rnt(l,i){let o,p=0,g=0,b=0;return o=pT(l),p=127&o,128&o&&(o=pT(l),p|=(127&o)<<7,128&o&&(o=pT(l),p|=(127&o)<<14,128&o&&(o=pT(l),p|=(127&o)<<21,128&o&&(o=pT(l),g=127&o,128&o&&(o=pT(l),g|=(127&o)<<7,128&o&&(o=pT(l),g|=(127&o)<<14,128&o&&(o=pT(l),g|=(127&o)<<21,128&o&&(o=pT(l),b=127&o,128&o&&(o=pT(l),b|=(127&o)<<7))))))))),{low:p|g<<28,high:g>>>4|b<<24,unsigned:i}}function kR(l,i){let o=i.low>>>0,p=(i.low>>>28|i.high<<4)>>>0,g=i.high>>>24,b=g===0?p===0?o<16384?o<128?1:2:o<1<<21?3:4:p<16384?p<128?5:6:p<1<<21?7:8:g<128?9:10,A=SP(l,b),j=l.bytes;switch(b){case 10:j[A+9]=g>>>7&1;case 9:j[A+8]=b!==9?128|g:127&g;case 8:j[A+7]=b!==8?p>>>21|128:p>>>21&127;case 7:j[A+6]=b!==7?p>>>14|128:p>>>14&127;case 6:j[A+5]=b!==6?p>>>7|128:p>>>7&127;case 5:j[A+4]=b!==5?128|p:127&p;case 4:j[A+3]=b!==4?o>>>21|128:o>>>21&127;case 3:j[A+2]=b!==3?o>>>14|128:o>>>14&127;case 2:j[A+1]=b!==2?o>>>7|128:o>>>7&127;case 1:j[A]=b!==1?128|o:127&o}}const y8={},b8={},TP=4294967296,S8=TP*TP,T8=S8/2,L2=C8(0,!0),R8=C8(0),int=pO(0,-2147483648,!1),snt=pO(-1,2147483647,!1),ont=pO(-1,-1,!0);function C8(l,i){let o,p,g;return i?(g=0<=(l>>>=0)&&l<256)&&(p=b8[l],p)?p:(o=pO(l,0,!0),g&&(b8[l]=o),o):(g=-128<=(l|=0)&&l<128)&&(p=y8[l],p)?p:(o=pO(l,l<0?-1:0,!1),g&&(y8[l]=o),o)}function pO(l,i,o){return{low:0|l,high:0|i,unsigned:!!o}}function ant(l,i){if(isNaN(l))return i?L2:R8;if(i){if(l<0)return L2;if(l>=S8)return ont}else{if(l<=-T8)return int;if(l+1>=T8)return snt}return l<0?i?L2:R8:pO(l%TP|0,l/TP|0,i)}function I8(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}class x2 extends D_{get connectionState(){return this._connectionState}set connectionState(i){if(this._connectionState===i)return;const o=this._connectionState;this._connectionState=i,this.emit(HS.CONNECTION_STATE_CHANGE,i,o)}get quality(){return this._quality}set quality(i){this._quality=i>1?1:i<.1?.1:i,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout(()=>{this.quality=this._quality/this._qualityRatio},6e4))}constructor(i){var o;super(),_e(this,"name","AgoraRTCImageModeration"),_e(this,"_connectionState",ES.CONNECTING),_e(this,"_sequence",0),_e(this,"_moderationStartTime",void 0),_e(this,"_workerConnection",void 0),_e(this,"_workerMessageLengthLimit",void 0),_e(this,"_qualityRatio",void 0),_e(this,"_connectInfo",void 0),_e(this,"_cancelTokenSource",aS.CancelToken.source()),_e(this,"_retryConfig",void 0),_e(this,"_moderationInterval",void 0),_e(this,"_moderationTimer",null),_e(this,"_moderationMode",1),_e(this,"_quality",1),_e(this,"_qualityTimer",null),_e(this,"_ticket",void 0),_e(this,"_moderationIntervalMinimum",void 0),_e(this,"_uploadFailedNum",0),_e(this,"_uploadNum",0),_e(this,"_uploadTimer",null),_e(this,"_moderationId",void 0),_e(this,"inspectImage",()=>{if(this.connectionState!==ES.CONNECTED)throw new hE(_p.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===ES.CONNECTED?this.requestToInspectImage():Gi.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)},this._moderationInterval{Gi.debug("[".concat(this._moderationId,"] Moderation operation :").concat(ER[p]," ").concat(g||""))}),this.handleWorkerEvents()}async init(i,o){this.emit(HS.STATE_CHANGE,ER.CONNECT_AP),this._connectInfo=i;const p=this._cancelTokenSource.token;return this._retryConfig=o,new pE((g,b)=>{this.on(HS.CONNECTION_STATE_CHANGE,(A,j)=>{A===ES.CONNECTED&&g()}),this.requestAP(i,p,o).then(A=>{this.connectWorker(A)}).catch(A=>{b(A)})})}updateConfig(i){var o;this._moderationInterval=(o=i.interval)!==null&&o!==void 0?o:1e3,Gi.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(i))),this.connectionState===ES.CONNECTED&&this.inspectImage()}async requestAP(i,o,p){const g=nE("WEBCS_DOMAIN").map(H=>"https://".concat(H,"/api/v1")),b=await function(H,z,$,Vt){let{appId:_r,areaCode:Fi,cname:_l,sid:_u,token:_h,uid:_g}=z;aO++;const eE="moderation_plugin",oE={service_name:eE,json_body:JSON.stringify({appId:_r,areaCode:Fi,cname:_l,command:"allocateEdge",requestId:aO,seq:aO,sid:_u,appToken:_h,ts:Date.now(),uid:_g+""})};let SE,vE,fE=H[0];return vT(async()=>{SE=Date.now();const mE=await nR(fE,{data:oE,cancelToken:$,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(vE=Date.now()-SE,mE.code!==0){const OE=new hE(_p.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+mE.code,{retry:!0,responseTime:vE});throw Gi.error(OE.toString()),OE}const EE=JSON.parse(mE.json_body);if(EE.code!==200){const OE=new hE(_p.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(EE.code,", reason: ").concat(EE.reason),{code:EE.code,responseTime:vE});throw Gi.error(OE.toString()),OE}if(!EE.servers||!Array.isArray(EE.servers)||EE.servers.length===0){const OE=new hE(_p.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:EE.code,responseTime:vE});throw Gi.error(OE.toString()),OE}if(!EE.servers.some(OE=>!!OE.wss)){const OE=new hE(_p.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:EE.code,responseTime:vE});throw Gi.error(OE.toString()),OE}const PE=nE("IMAGE_MODERATION_WORKER_HOST");return{addressList:EE.servers.map(OE=>{let{address:$E,wss:s_}=OE;if($E&&s_)return"wss://".concat($E.replace(/\./g,"-"),".").concat(PE,":").concat(s_,"/moderation")}).filter(OE=>!!OE),workerToken:EE.workerToken,vid:EE.vid,ticket:EE.appTicket,responseTime:vE}},(mE,EE)=>(jE.apworkerEvent(_u,{success:!0,sc:200,serviceName:eE,responseDetail:JSON.stringify(mE.addressList),firstSuccess:EE===0,responseTime:vE,serverIp:H[EE%H.length]}),!1),(mE,EE)=>(jE.apworkerEvent(_u,{success:!1,sc:mE.data&&mE.data.code||200,serviceName:eE,responseTime:vE,serverIp:H[EE%H.length]}),!!(mE.code!==_p.OPERATION_ABORTED&&mE.code!==_p.UNEXPECTED_RESPONSE||mE.data&&mE.data.retry)&&(fE=H[(EE+1)%H.length],!0)),Vt)}(g,i,o,p);this.emit(HS.STATE_CHANGE,ER.AP_CONNECTED);const{addressList:A,ticket:j}=b;return this._ticket=j,A}async connectWorker(i){this.emit(HS.STATE_CHANGE,ER.CONNECT_WORKER),await this._workerConnection.init(i,1e4)}handleWorkerEvents(){this._workerConnection.on(zE.CONNECTED,async()=>{this.emit(HS.STATE_CHANGE,ER.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=ES.CONNECTED}),this._workerConnection.on(zE.CLOSED,()=>{this.connectionState=ES.CLOSED}),this._workerConnection.on(zE.FAILED,()=>{this.connectionState=ES.CLOSED}),this._workerConnection.on(zE.RECONNECTING,()=>{this.connectionState=this.connectionState===ES.CONNECTED?ES.RECONNECTING:ES.CONNECTING}),this._workerConnection.on(zE.ON_MESSAGE,async i=>{if(i.data instanceof ArrayBuffer){const o=Zet(new Uint8Array(i.data));nE("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&Gi.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(o)),this._uploadNum++,o.code===void 0||o.code===0||(this._uploadFailedNum++,Gi.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(o.code,", msg is ").concat(o.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout(()=>{jE.reportApiInvoke(this._connectInfo.sid||null,{name:e0.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,o.code],tag:x_.TRACER}).onError(new hE(_p.IMAGE_MODERATION_UPLOAD_FAILED,o.msg)),this._uploadTimer=null},nE("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else Gi.error("[".concat(this._moderationId,"] Unexpected message type from worker"))}),this._workerConnection.on(zE.WILL_RECONNECT,(i,o,p)=>{i==="recover"&&p(i),p("tryNext")}),this._workerConnection.on(zE.REQUEST_NEW_URLS,(i,o)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(i).catch(o)})}static intToLong(i){return{low:i|=0,high:i>>31,unsigned:i>=0}}async requestToInspectImage(){const i=oS(this,HS.CLIENT_LOCAL_VIDEO_TRACK),o={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(i){if(!i.isPlaying)return void(nE("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&Gi.debug("Only the track being played can be inspected"));this._sequence++;const p=await this.generateRequestData(i,o);this._workerConnection.sendMessage(p,!0,!0)}else nE("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&Gi.debug("Only the track being published can be inspected")}async generateRequestData(i,o){let{appId:p,cname:g,cid:b,vid:A,sid:j,uid:H}=o;const z=Date.now(),$=await i.getCurrentFrameImage("image/jpeg",this.quality),Vt=await a4($,p,g),_r=this._sequence+"-"+b+"-"+H+"-"+z+"-"+T_(12,""),Fi={appId:p,cid:b,cname:g,deviceId:"",elapse:x2.intToLong(Number(z-this._moderationStartTime)),fileSize:$.buffer.byteLength,height:$.height,width:$.width,jpg:Vt,networkType:6,osType:7,requestId:_r,sdkVersion:"4.19.3",sequence:this._sequence,sid:j,timestamp:ant(z),uid:H,vid:A,service:this._moderationMode,ticket:this._ticket},_l=$et(Fi);if(_l.byteLength{const A=this.peerConnection.addTransceiver(b._mediaStreamTrack,{direction:"sendonly"});o.push(A)}),N_()&&nE("SIMULCAST")===!0&&await this.applySimulcastForFirefox(o,i),await this.applySimulcastEncodings(o,i),await this.applySendEncodings(o,i);const p=await this.peerConnection.createOffer();if(await this.peerConnection.setLocalDescription(p),!p.sdp)throw new Error("Cannot get offer.sdp when trying to send PeerConnection.");const g=o.map(b=>{const A=this.getLocalSSRC(b.mid,p.sdp);if(!A)throw new Error("Cannot get ssrc when trying to send PeerConnection.");return{mid:b.mid,localSSRC:[{ssrcId:A}]}});return{sdp:p.sdp,trackMessage:g}}catch(o){throw o instanceof yE?o:new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(o.toString()))}}async stopSending(i,o){const p=o?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{const g=this.peerConnection.getTransceivers().filter(A=>i.indexOf(A.mid)!==-1);if(g.length!==i.length)throw new Error("Transceivers' length (".concat(g.length,") doesn't match mids' length (").concat(i.length,") when trying to call P2PConnection.stopSending."));g.map(A=>{var j;A.direction="inactive",(j=A.stop)===null||j===void 0||j.call(A),this.peerConnection.removeTrack(A.sender)});const b=await this.peerConnection.createOffer();if(await this.peerConnection.setLocalDescription(b),!b.sdp)throw new Error("Cannot get offer.sdp when trying to send PeerConnection.");return b.sdp}catch(g){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(g.toString()))}finally{p&&p()}}async receive(i,o,p){try{await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const g=await this.peerConnection.createAnswer();if(!g.sdp)throw new Error("Cannot get answer sdp when trying to receive track.");await this.peerConnection.setLocalDescription(g),Gi.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(i," by exchanging SDP."));const b=this.getRemoteMid(p,o);if(b===void 0)throw new Error("Cannot get transceiver mid when trying to receive track.");const A=this.peerConnection.getTransceivers().find(j=>j.mid===b);if(!A||A.mid===null)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:A.receiver.track,mid:A.mid,sdp:g.sdp}}catch(g){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(g.toString()))}}async setDescription(i,o){try{if(i==="remote"){await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const p=await this.peerConnection.createAnswer();if(!p.sdp)throw new Error("Cannot get answer sdp when trying to receive track.");return await this.peerConnection.setLocalDescription(p),Gi.debug("[".concat(this.store.clientId,"] [P2PConnection] exchanging SDP, type is ").concat(i)),p.sdp}await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(p){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection.setDescription failed; ".concat(p.toString()))}}async stopReceiving(i,o){try{const p=this.peerConnection.getTransceivers().filter(b=>i.indexOf(b.mid)!==-1);if(p.length!==i.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");p.map(b=>{var A;b.direction="inactive",(A=b.stop)===null||A===void 0||A.call(b)}),await this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const g=await this.peerConnection.createAnswer();if(await this.peerConnection.setLocalDescription(g),!g.sdp)throw new Error("Cannot get answer sdp when trying to receive track.");return g.sdp}catch(p){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(p.toString()))}}async restartICE(){try{const i=await this.peerConnection.createOffer({iceRestart:!0});if(!i.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");return this.store.descriptionStart(),await this.peerConnection.setLocalDescription(i),i.sdp}catch(i){throw new yE(_p.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(i.toString()))}}close(){var i;this.peerConnection.close(),(i=this.onConnectionStateChange)===null||i===void 0||i.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.transportEventReceiver=void 0,this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(i){return this.statsFilter.getVideoIsReady(i)}async updateEncoderConfig(i,o){}async updateSendParameters(i,o){const p=this.peerConnection.getTransceivers().filter(g=>g.mid===i);p.length===1&&(this.isVP8Simulcast(o)?N_()||await this.applySimulcastEncodings(p,[o]):await this.applySendEncodings(p,[o]))}setStatsRemoteVideoIsReady(i,o){this.statsFilter.setVideoIsReady2(i,o)}async replaceTrack(i,o){const p=this.peerConnection.getTransceivers().find(g=>g.mid===o);p&&await p.sender.replaceTrack(i._mediaStreamTrack)}async getSelectedCandidatePair(){const i=this.peerConnection.getReceivers();if(i.length>0&&i[0].transport&&i[0].transport.iceTransport&&i[0].transport.iceTransport.getSelectedCandidatePair&&i[0].transport.iceTransport.getSelectedCandidatePair()){const o=i[0].transport.iceTransport,{local:p,remote:g}=o.getSelectedCandidatePair();return{local:RP(RP({},FT),{},{candidateType:p.type,protocol:p.protocol,address:p.address,port:p.port}),remote:RP(RP({},FT),{},{candidateType:g.type,protocol:g.protocol,address:g.address,port:g.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var i;(i=this.onICEConnectionStateChange)===null||i===void 0||i.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var i;(i=this.onConnectionStateChange)===null||i===void 0||i.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=i=>{var o;i.candidate&&((o=this.onLocalCandidate)===null||o===void 0||o.call(this,i.candidate)),i.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,Gi.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,Gi.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},nE("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(i){const o={iceServers:[]};return i.iceServers?o.iceServers=i.iceServers:i.turnServer&&i.turnServer.mode!=="off"&&(VI(i.turnServer.servers)?o.iceServers=i.turnServer.servers:(o.iceServers&&o.iceServers.push(...Lb.turnServerConfigToIceServers(i.turnServer.servers)),nE("USE_TURN_SERVER_OF_GATEWAY")&&o.iceServers&&i.turnServer.serversFromGateway&&o.iceServers.push(...Lb.turnServerConfigToIceServers(i.turnServer.serversFromGateway)),nE("FORCE_TURN_TCP")?o.iceTransportPolicy="relay":i.turnServer.servers.concat(i.turnServer.serversFromGateway||[]).forEach(p=>{p.forceturn&&(o.iceTransportPolicy="relay")}))),nE("ENABLE_ENCODED_TRANSFORM")&&I_().supportWebRTCEncodedTransform&&(o.encodedInsertableStreams=!0),o}static turnServerConfigToIceServers(i){const o=[];return i.forEach(p=>{p.tcpport&&(o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turns:".concat(d1(p.turnServerURL),":").concat(p.tcpport,"?transport=tcp")}),o.push({username:p.username,credential:p.password,credentialType:"password",urls:"turn:".concat(p.turnServerURL,":").concat(p.tcpport,"?transport=udp")}),o.push({username:p.username,credential:p.password,credentialType:"password",urls:"stun:".concat(p.turnServerURL,":").concat(p.tcpport)}))}),o}tryBindTransportEvents(i){const o=i.transport;if(o){this.transportEventReceiver=i,o.onstatechange=()=>{var g;o!=null&&o.state&&((g=this.onDTLSTransportStateChange)===null||g===void 0||g.call(this,o.state))},o.onerror=g=>{var b;(b=this.onDTLSTransportError)===null||b===void 0||b.call(this,"error"in g?g.error:g)};const p=o.iceTransport;p&&(p.onstatechange=()=>{const g=o==null?void 0:o.iceTransport.state;var b;g&&((b=this.onICETransportStateChange)===null||b===void 0||b.call(this,g))},p.getSelectedCandidatePair&&(p.onselectedcandidatepairchange=()=>{if(p.getSelectedCandidatePair()){const{local:g,remote:b}=p.getSelectedCandidatePair();Gi.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:g.type,protocol:g.protocol}),", remote ").concat(JSON.stringify({candidateType:b.type,protocol:b.protocol,address:b.address,port:b.port})," )"))}}))}}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(i,o){var p;if(o||(o=this.peerConnection.getSenders().find($=>$.track===i._mediaStreamTrack)),!o)return Gi.warn("[".concat(i.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(i))return Gi.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!I_().supportSetRtpSenderParameters)return Gi.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const g={},b={};switch(i._optimizationMode){case"motion":g.degradationPreference="maintain-framerate";break;case"detail":g.degradationPreference="maintain-resolution";break;default:g.degradationPreference="balanced"}if(i._encoderConfig){var A;const{bitrateMax:$,frameRate:Vt,scaleResolutionDownBy:_r}=i._encoderConfig;$&&(b.maxBitrate=1e3*$),VE(A=i._hints).call(A,A_.LOW_STREAM)&&(Vt&&(b.maxFramerate=US(Vt)),_r&&_r>=1&&(b.scaleResolutionDownBy=_r))}if(nE("DSCP_TYPE")&&dR()){var j;const $=nE("DSCP_TYPE");VE(j=["very-low","low","medium","high"]).call(j,$)&&(b.networkPriority=$)}const H=o.getParameters(),z=(p=H.encodings)===null||p===void 0?void 0:p[0];N_()&&!z&&(g.encodings=[b]),z&&Object.assign(z,b),Object.assign(H,g),Gi.debug("[".concat(i.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(H.encodings))),await o.setParameters(H)}async applySendEncodings(i,o){try{if(!I_().supportSetRtpSenderParameters||i.length!==o.length)return;for(let p=0;p{const j=p[A],H=g.mediaDescriptions.find(z=>z.attributes.mid===j);H&&(gI(H,b),S2(H,b,this.store.codec))}),q_.print(g)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=i=>{var o;(o=this.onFirstAudioReceived)===null||o===void 0||o.call(this,i)},this.statsFilter.onFirstVideoReceived=i=>{var o;(o=this.onFirstVideoReceived)===null||o===void 0||o.call(this,i)},this.statsFilter.onFirstAudioDecoded=i=>{var o;(o=this.onFirstAudioDecoded)===null||o===void 0||o.call(this,i)},this.statsFilter.onFirstVideoDecoded=(i,o,p)=>{var g;(g=this.onFirstVideoDecoded)===null||g===void 0||g.call(this,i,o,p)},this.statsFilter.onSelectedLocalCandidateChanged=(i,o)=>{var p;(p=this.onSelectedLocalCandidateChanged)===null||p===void 0||p.call(this,i,o)},this.statsFilter.onSelectedRemoteCandidateChanged=(i,o)=>{var p;(p=this.onSelectedRemoteCandidateChanged)===null||p===void 0||p.call(this,i,o)},this.statsFilter.onFirstVideoDecodedTimeout=i=>{var o;(o=this.onFirstVideoDecodedTimeout)===null||o===void 0||o.call(this,i)}}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(i,o){if(i.length===o.length)for(let H=0;H200&&(A=$._scalabilityMode)!==null&&A!==void 0&&A.numSpatialLayers&&((j=$._scalabilityMode)===null||j===void 0?void 0:j.numSpatialLayers)>1&&this.store.codec==="vp8"){const Vt={},_r={high:1e3*($._encoderConfig.bitrateMax-50),medium:5e4};Vt.encodings=[{rid:"m",active:!0,maxBitrate:_r.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:_r.high}];const Fi=z.sender.getParameters();await z.sender.setParameters(Object.assign(Fi,Vt))}}}async applySimulcastEncodings(i,o){if(!N_()&&i.length===o.length)for(let p=0;p200&&(b=i._scalabilityMode)!==null&&b!==void 0&&b.numSpatialLayers&&((A=i._scalabilityMode)===null||A===void 0?void 0:A.numSpatialLayers)>1)}logSDPExchange(i,o,p,g){if(nE("SDP_LOGGING"))return Gi.upload("[".concat(this.store.clientId,"] exchanging ").concat(p," ").concat(o," SDP during P2PConnection.").concat(g,` +`),i),o==="offer"?b=>{this.logSDPExchange(b,"answer",p==="local"?"remote":"local",g)}:void 0}getLocalSSRC(i,o){var p,g;if(o=(p=o)!==null&&p!==void 0?p:(g=this.currentLocalDescription)===null||g===void 0?void 0:g.sdp){var b;const A=(b=q_.parse(o).mediaDescriptions.find(j=>j.attributes.mid===i))===null||b===void 0?void 0:b.attributes.ssrcs;return A==null?void 0:A[0].ssrcId}}getRemoteMid(i,o){var p,g;if(o=(p=o)!==null&&p!==void 0?p:(g=this.currentRemoteDescription)===null||g===void 0?void 0:g.sdp){var b;return(b=q_.parse(o).mediaDescriptions.find(A=>A.attributes.ssrcs.some(j=>j.ssrcId===i)))===null||b===void 0?void 0:b.attributes.mid}}async getRemoteSSRC(i,o){var p,g;if(o=(p=o)!==null&&p!==void 0?p:(g=this.currentRemoteDescription)===null||g===void 0?void 0:g.sdp){var b;const A=(b=q_.parse(o).mediaDescriptions.find(j=>j.attributes.mid===i))===null||b===void 0?void 0:b.attributes.ssrcs;return A==null?void 0:A[0].ssrcId}}}function fT(l,i,o){const p=l[i];if(typeof p!="function")throw new Error("Cannot use mutex on object property.");return o.value=async function(){const g=this.mutex,b=await g.lock("From P2PConnection.".concat(i));try{for(var A=arguments.length,j=new Array(A),H=0;H{const A=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==u_.Connected)return void b(new yE(_p.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established."));const z=this.filterTobeMutedTracks(p);if(z.length===0)return void g();const $=z.find(_g=>_g[0]==="videoLowTrack");$&&$[1].track._originMediaStreamTrack.stop();let Vt=!1;var j,H;p.trackMediaType==="video"?Vt=!((j=this.localTrackMap.get(TE.LocalAudioTrack))===null||j===void 0||!j.track._muted):Vt=((H=this.localTrackMap.get(TE.LocalVideoTrack))===null||H===void 0?void 0:H.id)===void 0;const _r=z.filter(_g=>{let[eE,oE]=_g;return(eE!==TE.LocalAudioTrack||Vt)&&oE.id!==void 0}).map(_g=>{let[,eE]=_g;return eE});let Fi;_r.length>0&&(Fi=await this.sendConnection.stopSending(_r.map(_g=>_g.id)),_r.forEach(_g=>{_g.id=void 0,_g.ssrcs=void 0}));const _l=this.createMuteMessage(z),_u=p.trackMediaType==="video"?PT.MUTE_LOCAL_VIDEO:PT.MUTE_LOCAL_AUDIO,_h=await U_(this,WE.RequestP2PMuteLocal,{action:_u,sdp:Fi,message:_l,isMuteAll:Vt});_h&&await this.sendConnection.setDescription("local",_h),(Fi||p.trackMediaType==="audio")&&await S_(this,WE.RequestMuteLocal,_l),g()}catch(z){b(z)}finally{A()}}),_e(this,"handleUnmuteLocalTrack",async(p,g,b)=>{const A=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==u_.Connected)return void b(new yE(_p.INVALID_OPERATION,"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established."));const j=this.filterTobeUnmutedTracks(p);if(j.length===0)return void g();const H=this.createUnmuteMessage(j),z=p.trackMediaType==="video"?PT.UNMUTE_LOCAL_VIDEO:PT.UNMUTE_LOCAL_AUDIO;await S_(this,WE.RequestP2PMuteLocal,{action:z,message:H}),g()}catch(j){b(j)}finally{A()}}),_e(this,"handleUpdateVideoEncoder",async(p,g,b)=>{const A=await this.sendMutex.lock("Locking from P2PChannel2.handleSetVideoEncoder");try{const j=this.localTrackMap.get(TE.LocalVideoTrack);if(!this.sendConnection||!j||j.track!==p||this.state!==u_.Connected)return void g();const{id:H,track:z}=j;H&&(await this.sendConnection.updateSendParameters(H,z),await this.sendConnection.updateEncoderConfig(H,z),this.emit(WE.UpdateVideoEncoder,z)),g()}catch(j){b(j)}finally{A()}}),_e(this,"handleSetOptimizationMode",async(p,g,b)=>{const A=await this.sendMutex.lock("Locking from P2PChannel2.handleSetOptimizationMode");try{const j=this.localTrackMap.get(TE.LocalVideoTrack);if(!this.sendConnection||!j||j.track!==p||this.state!==u_.Connected)return;const{id:H,track:z}=j;H&&await this.sendConnection.updateSendParameters(H,z),g()}catch(j){b(j)}finally{A()}}),_e(this,"handleReplaceTrack",async(p,g,b,A)=>{let j;Gi.debug("[".concat(this.store.clientId,"] P2PChannel2 handleReplaceTrack for [track-id-").concat(p.getTrackId(),"]")),typeof A=="boolean"&&A||(j=await this.sendMutex.lock("From P2PChannel2.handleReplaceTrack"));try{var H;const $=Array.from(this.localTrackMap.entries()).find(Vt=>{let[,{track:_r}]=Vt;return p===_r});if(!this.sendConnection||!$||$[1].id===void 0||this.state!==u_.Connected)return void g();if(await((H=this.sendConnection)===null||H===void 0?void 0:H.replaceTrack(p,$[1].id)),$[0]===TE.LocalVideoTrack&&I_().supportDualStreamEncoding){const Vt=this.localTrackMap.get(TE.LocalVideoLowTrack);if(Vt){const _r=p._mediaStreamTrack.clone();Vt.track._originMediaStreamTrack.stop(),Vt.track._mediaStreamTrack=_r,Vt.track._originMediaStreamTrack=_r,await new pE((Fi,_l)=>{this.handleReplaceTrack(Vt.track,Fi,_l,!0)})}}g()}catch($){b($)}finally{var z;(z=j)===null||z===void 0||z()}}),_e(this,"handleGetLocalVideoStats",p=>{p(this.statsCollector.getLocalVideoTrackStats())}),_e(this,"handleGetLocalAudioStats",p=>{p(this.statsCollector.getLocalAudioTrackStats())}),_e(this,"handleGetRemoteVideoStats",p=>this.statsCollector.getRemoteVideoTrackStats(p.uid)[p.uid]),_e(this,"handleGetRemoteAudioStats",p=>this.statsCollector.getRemoteAudioTrackStats(p.uid)[p.uid]),this.store=i,this.statsCollector=o,this.statsCollector.addP2PChannel(this),this.statsUploader=new s8,this.bindStatsUploaderEvents()}async startP2PConnection(i,o){throw new yE(_p.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.")}async connect(i,o,p,g,b,A){throw new yE(_p.NOT_SUPPORTED,"p2p mode does not support connect.")}async startP2P(i,o){if(this.state=u_.New,this.sendConnection&&(Gi.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset P2PConnection.")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),this.recvConnection&&(Gi.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset P2PConnection.")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),this.sendConnection=new Lb(i,this.store),this.bindConnectionEvents(this.sendConnection),this.recvConnection=new Lb(i,this.store,YI.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection),o){this.store.peerConnectionStart(),await this.recvConnection.establish(o);const p=await this.sendConnection.establish(o);return this.statsUploader.startUploadTransportStats(!0),this.statsUploader.startUploadExtensionUsageStats(),this.state=u_.Connected,p}return await this.recvConnection.establish(o),this.sendConnection.establish(o)}async p2pConnect(i){if(!this.sendConnection||!this.recvConnection)throw new yE(_p.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.recvConnection.connect(i),await this.sendConnection.connect(i),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=u_.Connected}async addRemoteCandidate(i){if(!this.sendConnection||!this.recvConnection)throw new yE(_p.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(i),await this.sendConnection.addRemoteCandidate(i)}async publish(i,o,p){if(!this.sendConnection||this.state!==u_.Connected){this.throwIfTrackTypeNotMatch(i);const A=i.filter(j=>this.pendingLocalTracks.indexOf(j)===-1);return void(this.pendingLocalTracks=this.pendingLocalTracks.concat(A))}this.store.pubId=this.store.pubId+1,k0.markPublishStart(this.store.clientId,this.store.pubId);const g=this.filterTobePublishedTracks(i,o,p);if(g.length===0)return void await this.tryToUnmuteAudio(i);g.forEach(A=>{let{track:j,type:H}=A;const z=Date.now();this.store.publish(j.getTrackId(),H===TE.LocalAudioTrack?"audio":"video",z)}),this.bindLocalTrackEvents(g);const b=this.createGatewayPublishMessage(g);return this.assignLocalTracks(g),g.forEach(A=>{let{track:j,type:H}=A;const z=Date.now();this.store.publish(j.getTrackId(),H===TE.LocalAudioTrack?"audio":"video",void 0,z)}),b}async dopublish(i){if(!this.sendConnection||this.state!==u_.Connected)return;const o=this.localTrackMap.get(i);if(o){const{sdp:p,trackMessage:g}=await this.sendConnection.send([o.track]),{mid:b,localSSRC:A}=g[0];o.id=b,o.ssrcs=A,this.statsCollector.addLocalStats(i),this.statsUploader.startUploadUplinkStats();const j=await U_(this,WE.RequestP2PPublish,{kind:i===TE.LocalAudioTrack?ME.AUDIO:ME.VIDEO,sdp:p,ssrcId:A[0].ssrcId});await this.sendConnection.setDescription("local",j);const H=this.createUnmuteMessage([[i,o]]);await S_(this,WE.RequestUnmuteLocal,H)}}async setDescription(i,o){let p,g;i==="local"?(p=await this.sendMutex.lock("From P2PChannel.restartICE"),g=this.sendConnection):(p=await this.recvMutex.lock("From P2PChannel.restartICE"),g=this.recvConnection);try{return!g||this.state!==u_.Connected?void 0:await g.setDescription(i,o)}finally{p()}}publishLowStream(i){return JS(function*(){throw new yE(_p.NOT_SUPPORTED,"p2p mode does not support publishLowStream.")})()}async republish(){this.pendingLocalTracks.length>0&&(Gi.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await U_(this,WE.RequestRePublish,this.pendingLocalTracks),this.emit(WE.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async unpublish(i){if(!this.sendConnection||this.state!==u_.Connected)return void(i.length===0?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter(H=>!VE(i).call(i,H)));const o=this.filterTobeUnpublishedTracks(i);if(o.length===0)return;this.unbindLocalTrackEvents(o.map(H=>{let[z,{track:$}]=H;return{type:z,track:$}}));const p=o.filter(H=>{let[,{id:z}]=H;return z!==void 0});if(!this.sendConnection||this.state!==u_.Connected)return void i.forEach(H=>{const z=this.pendingLocalTracks.indexOf(H);z!==-1&&this.pendingLocalTracks.splice(z,1)});const g=o.find(H=>H[0]==="videoLowTrack");g&&g[1].track.close();let b;const A=this.createGatewayUnpublishMessage(o);p.length>0&&(b=await this.sendConnection.stopSending(p.map(H=>{let[,{id:z}]=H;return z}))),this.withdrawLocalTracks(o),this.unbindLocalTrackEvents(o.map(H=>{let[z,{track:$}]=H;return{type:z,track:$}})),o.forEach(H=>{let[z]=H;this.statsCollector.removeLocalStats(z)}),this.localTrackMap.size===0&&this.statsUploader.stopUploadUplinkStats();const j=this.createMuteMessage(o);return await pE.all(j.map(async H=>{await S_(this,WE.RequestMuteLocal,[H])})),{sdp:b,unpubMsg:A}}async unpublishLowStream(){throw new yE(_p.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.")}async doUnpublish(i){if(!this.sendConnection||this.state!==u_.Connected)return;const o=[];if(i!==ME.AUDIO){const p=this.localTrackMap.get(TE.LocalVideoTrack);(p==null?void 0:p.id)!==void 0&&o.push([TE.LocalVideoTrack,p]);const g=this.localTrackMap.get(TE.LocalVideoLowTrack);(g==null?void 0:g.id)!==void 0&&o.push([TE.LocalVideoLowTrack,g]),this.statsCollector.removeLocalStats(TE.LocalVideoTrack),this.statsCollector.removeLocalStats(TE.LocalVideoLowTrack)}if(i!==ME.VIDEO){const p=this.localTrackMap.get(TE.LocalAudioTrack);(p==null?void 0:p.id)!==void 0&&o.push([TE.LocalAudioTrack,p]),this.statsCollector.removeLocalStats(TE.LocalAudioTrack)}if(o.length>0){const p=await this.sendConnection.stopSending(o.map(A=>{let[,j]=A;return j.id}));o.forEach(A=>{let[,j]=A;j.id=void 0,j.ssrcs=void 0});const g=await U_(this,WE.RequestP2PUnPublish,{sdp:p,kind:i});await this.sendConnection.setDescription("local",g);const b=this.createMuteMessage(o);await pE.all(b.map(async A=>{await S_(this,WE.RequestMuteLocal,[A])}))}}async subscribe(i,o,p,g){var b;if(!this.recvConnection||this.state!==u_.Connected)throw new yE(_p.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");if((b=this.remoteUserMap.get(i))!==null&&b!==void 0&&b.has(o))return;const{track:A,mid:j,sdp:H}=await this.recvConnection.receive(o,p,g);o===ME.AUDIO?(i._audioSSRC=g,i._audioTrack?i._audioTrack._updateOriginMediaStreamTrack(A):(i._audioTrack=new cT(A,i.uid,i._uintid,this.store),Gi.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(i._audioTrack.getTrackId()))),this.bindRemoteTrackEvents(i,i._audioTrack)):(i._videoSSRC=g,i._videoTrack?i._videoTrack._updateOriginMediaStreamTrack(A):(i._videoTrack=new DT(A,i.uid,i._uintid,this.store),Gi.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(i._videoTrack.getTrackId()))),this.bindRemoteTrackEvents(i,i._videoTrack));const z=this.remoteUserMap.get(i);z?z.set(o,j):this.remoteUserMap.set(i,new Map([[o,j]])),this.statsCollector.addRemoteStats(i.uid),this.statsUploader.startUploadDownlinkStats(),await S_(this,WE.RequestP2PUnmuteRemote,o);const $=this.pendingRemoteTracks.findIndex(Vt=>{let{user:_r,kind:Fi}=Vt;return _r.uid===i.uid&&o===Fi});return $!==-1&&(this.pendingRemoteTracks.splice($,1),this.emit(WE.MediaReconnectEnd,i.uid)),H}async unsubscribe(i,o,p,g){const b=this.pendingRemoteTracks.filter(H=>{let{user:z,kind:$}=H;return p!==void 0?z.uid===i.uid&&p===$:z.uid===i.uid});if(b.forEach(H=>{const z=this.pendingRemoteTracks.indexOf(H);this.pendingRemoteTracks.splice(z,1)}),this.recvConnection&&this.state===u_.Connected||g||b.forEach(H=>{let{kind:z}=H;var $;if(z===ME.AUDIO)($=i._audioTrack)===null||$===void 0||$._destroy(),i._audioTrack=void 0;else if(z===ME.VIDEO){var Vt;(Vt=i._videoTrack)===null||Vt===void 0||Vt._destroy(),i._videoTrack=void 0}}),!this.recvConnection||this.state!==u_.Connected)return;const A=this.filterTobeUnSubscribedTracks(i,p);if(A.length===0)return void(p!==ME.VIDEO&&S_(this,WE.RequestP2PMuteRemote,ME.AUDIO));const j=await this.recvConnection.stopReceiving(A.map(H=>{let[,{id:z}]=H;return z}),o);return this.withdrawRemoteTracks(A),this.remoteUserMap.size===0&&this.statsUploader.stopUploadDownlinkStats(),A.forEach(H=>{let[z,{kind:$}]=H;var Vt,_r;if($===ME.VIDEO&&z._videoSSRC&&((Vt=this.recvConnection)===null||Vt===void 0||Vt.setStatsRemoteVideoIsReady(z._videoSSRC,!1)),$===ME.VIDEO)this.unbindRemoteTrackEvents(z._videoTrack),g||((_r=z._videoTrack)===null||_r===void 0||_r._destroy(),z._videoTrack=void 0);else if($===ME.AUDIO){var Fi;this.unbindRemoteTrackEvents(z._audioTrack),!g&&((Fi=z._audioTrack)===null||Fi===void 0||Fi._destroy(),z._audioTrack=void 0)}}),A.filter(H=>{let[,{kind:z}]=H;return z!==ME.AUDIO}).forEach(H=>{let[,{kind:z}]=H;S_(this,WE.RequestP2PMuteRemote,z)}),p!==ME.VIDEO&&S_(this,WE.RequestP2PMuteRemote,ME.AUDIO),j}getAllDataChannels(){return this.localDataChannels}async massSubscribe(i){throw new yE(_p.NOT_SUPPORTED,"p2p mode does not support massSubscribe.")}async massSubscribeNoLock(i){throw new yE(_p.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.")}async massUnsubscribe(i){throw new yE(_p.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.")}async massUnsubscribeNoLock(i){throw new yE(_p.NOT_SUPPORTED,"p2p mode does not support massUnsubscribeNoLock.")}async muteRemote(i,o){if(!this.recvConnection)return;const p=this.remoteUserMap.get(i);if(!p)return void Gi.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(i.uid,"."));if(!p.get(o))return void Gi.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(i.uid," media type ").concat(o,"."));const g=o===ME.VIDEO?i._videoSSRC:i._audioSSRC;g!==void 0&&this.recvConnection.setStatsRemoteVideoIsReady(g,!1)}async unmuteRemote(i,o){return this.unmuteRemoteNoLock(i,o)}async unmuteRemoteNoLock(i,o){if(!this.recvConnection)return;const p=this.remoteUserMap.get(i);if(!p)return void Gi.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(i.uid,"."));p.get(o)||Gi.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(i.uid," media type ").concat(o,"."))}getAllTracks(i){const o=this.localTrackMap.get(TE.LocalAudioTrack);if((o==null?void 0:o.track)instanceof Z_){const p=o.track;return Array.from(this.localTrackMap.entries()).filter(g=>{let[b]=g;return b!==TE.LocalAudioTrack}).filter(g=>{let[b]=g;return!(i&&b===TE.LocalVideoLowTrack)}).map(g=>{let[,{track:b}]=g;return b}).concat(p.trackList)}return Array.from(this.localTrackMap.entries()).filter(p=>{let[g]=p;return!(i&&g===TE.LocalVideoLowTrack)}).map(p=>{let[,{track:g}]=p;return g})}reportPublishEvent(i,o,p,g,b){if(i){const j=this.localTrackMap.get(TE.LocalAudioTrack),H=g?this.localTrackMap.get(TE.LocalVideoLowTrack):this.localTrackMap.get(TE.LocalVideoTrack);jE.publish(this.store.sessionId,{eventElapse:k0.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:i,ec:o,audioName:j==null?void 0:j.track.getTrackLabel(),videoName:H==null?void 0:H.track.getTrackLabel(),screenshare:(H==null?void 0:H.track._hints.indexOf(A_.SCREEN_TRACK))!==-1,audio:!!j,video:!!H,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:b})}else{var A;p||(p=[]);const j=p.find(z=>z instanceof g_),H=g?(A=this.localTrackMap.get(TE.LocalVideoTrack))===null||A===void 0?void 0:A.track:p.find(z=>z instanceof ZE);jE.publish(this.store.sessionId,{eventElapse:k0.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:i,ec:o,audioName:j==null?void 0:j.getTrackLabel(),videoName:H==null?void 0:H.getTrackLabel(),screenshare:(H==null?void 0:H._hints.indexOf(A_.SCREEN_TRACK))!==-1,audio:!!j,video:!!H,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:b})}}reportSubscribeEvent(i,o,p,g){const b=g===ME.VIDEO?p._videoSSRC:p._audioSSRC;b&&jE.subscribe(this.store.sessionId,{succ:i,ec:o,video:g===ME.VIDEO,audio:g===ME.AUDIO,peerid:p.uid,subscribeRequestid:g===ME.VIDEO?p._videoSSRC:p._audioSSRC,p2pid:this.store.p2pId,eventElapse:k0.measureFromSubscribeStart(this.store.clientId,b)})}reset(){Gi.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new E0("P2PChannel2-send-mutex"),this.sendMutex=new E0("P2PChannel2-recv-mutex"),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.stopUploadUplinkStats(),this.statsUploader.stopUploadDownlinkStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const i=this.localTrackMap.get(TE.LocalAudioTrack);if((i==null?void 0:i.track)instanceof Z_){if(i.track.trackList.length>0){const o=i.track;i.track.trackList.forEach(p=>{o.removeAudioTrack(p)})}i.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.state=u_.Disconnected}getStats(i){var o,p;return i?(p=this.recvConnection)===null||p===void 0?void 0:p.getStats():(o=this.sendConnection)===null||o===void 0?void 0:o.getStats()}getRemoteVideoIsReady(i){var o;return((o=this.recvConnection)===null||o===void 0?void 0:o.getRemoteVideoIsReady(i))||!1}getLocalAudioVolume(){const i=this.localTrackMap.get(TE.LocalAudioTrack);if(i)return i.track.getVolumeLevel()}getLocalVideoSize(){const i=this.localTrackMap.get(TE.LocalVideoTrack);if(i)return{width:i.track._videoWidth||0,height:i.track._videoHeight||0}}getEncoderConfig(i){const o=this.localTrackMap.get(i);return o&&o.track instanceof ZE||o&&o.track instanceof g_?o.track._encoderConfig:void 0}getLocalMedia(i){return this.localTrackMap.get(i)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(i,o){if(!i)return this.remoteUserMap.size>0;const p=this.remoteUserMap.get(i);return!!p&&(!o||p.has(o))}async hasRemoteMediaWithLock(i,o){if(!i)return this.remoteUserMap.size>0;const p=this.remoteUserMap.get(i);return!!p&&(!o||p.has(o))}getRemoteMedia(i){var o;const p=Array.from(CS(o=this.remoteUserMap).call(o)).find(g=>g.uid===i);return p?{audioTrack:p.audioTrack,audioSSRC:p._audioSSRC,videoTrack:p.videoTrack,videoSSRC:p._videoSSRC}:{}}getAudioLevels(){let i=Array.from(this.remoteUserMap.entries()).map(p=>{let[g]=p;return{uid:g.uid,level:g.audioTrack?100*g.audioTrack._source.getAccurateVolumeLevel():0}});const o=this.localTrackMap.get(TE.LocalAudioTrack);return o&&i.push({level:100*o.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),i=AO(i).call(i,(p,g)=>p.level-g.level),i}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(Gi.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=u_.Reconnecting,nE("KEEP_LAST_FRAME")&&this.remoteUserMap.size!==0&&Array.from(this.remoteUserMap.entries()).forEach(i=>{let[o]=i;var p;o._videoTrack&&o._videoTrack._player&&((p=o._videoTrack._player.getVideoElement())===null||p===void 0||p.pause(),o._videoTrack._player.isKeepLastFrame=!0,o._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(i=>{var o;let[p,{track:g}]=i;switch(p){case TE.LocalVideoTrack:VE(o=g._hints).call(o,A_.LOW_STREAM)?g.close():this.pendingLocalTracks.push(g);break;case TE.LocalAudioTrack:g instanceof Z_?this.pendingLocalTracks=this.pendingLocalTracks.concat(g.trackList):this.pendingLocalTracks.push(g);case TE.LocalVideoLowTrack:}}),this.emit(WE.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),this.remoteUserMap.size!==0&&Array.from(this.remoteUserMap.entries()).forEach(i=>{let[o,p]=i;Array.from(CS(p).call(p)).forEach(g=>{this.setPendingRemoteMedia(o,g)}),this.emit(WE.MediaReconnectStart,o.uid)}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.statsUploader.stopUploadUplinkStats(),this.statsUploader.stopUploadDownlinkStats(),this.statsUploader.stopUploadTransportStats(),Gi.debug("[".concat(this.store.clientId,"] P2PChannel2 disconnected, waiting to reconnect.")))}hasPendingRemoteMedia(i,o){for(const p of this.pendingRemoteTracks){const{user:g,kind:b}=p;if((i instanceof D0?i.uid:i)===g.uid&&o===b)return!0}return!1}setPendingRemoteMedia(i,o){this.hasPendingRemoteMedia(i,o)||this.pendingRemoteTracks.push({user:i,kind:o})}async restartICE(i){let o;o=i.direction===YI.SEND_ONLY?await this.sendMutex.lock("From P2PChannel.restartICE"):await this.recvMutex.lock("From P2PChannel.restartICE");try{const p=await i.restartICE(),g=await U_(this,WE.RequestP2PRestartICE,p);i.setDescription("local",g)}finally{o()}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const i=this.sendConnection.getStats(),o=this.localTrackMap.get(TE.LocalVideoTrack),p=this.localTrackMap.get(TE.LocalAudioTrack),g=i.videoSend.find(_l=>{var _u;return _l.ssrc===(o==null||(_u=o.ssrcs)===null||_u===void 0?void 0:_u[0].ssrcId)}),b=i.audioSend.find(_l=>{var _u;return _l.ssrc===(p==null||(_u=p.ssrcs)===null||_u===void 0?void 0:_u[0].ssrcId)});if(!g||!b)return 1;const A=oS(this,WE.NeedSignalRTT),j=g?g.rttMs:void 0,H=b?b.rttMs:void 0,z=j&&H?(j+H)/2:j||H,$=(z&&A?(z+A)/2:z||A)||0,Vt=100*i.sendPacketLossRate*.7/50+.3*$/1500,_r=Vt<.17?1:Vt<.36?2:Vt<.59?3:Vt<.1?4:5,Fi=o==null?void 0:o.track;if(Fi&&Fi._encoderConfig&&Fi._hints.indexOf(A_.SCREEN_TRACK)===-1){const _l=Fi._encoderConfig.bitrateMax,_u=i.bitrate.actualEncoded;if(_l&&_u){const _h=(1e3*_l-_u)/(1e3*_l);return h6[_h<.15?0:_h<.3?1:_h<.45?2:_h<.6?3:4][_r]}}return _r}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;const i=this.recvConnection.getStats();let o=0;return Array.from(this.remoteUserMap.entries()).forEach(p=>{let[g]=p;const b=g._audioSSRC,A=g._videoSSRC,j=i.audioRecv.find(_u=>_u.ssrc===b),H=i.videoRecv.find(_u=>_u.ssrc===A);if(!j&&!H)return void(o+=1);const z=oS(this,WE.NeedSignalRTT),$=i.rtt,Vt=($&&z?($+z)/2:$||z)||0,_r=j?j.jitterMs:void 0,Fi=i.recvPacketLossRate;let _l=.7*Fi*100/50+.3*Vt/1500;_r&&(_l=.6*Fi*100/50+.2*Vt/1500+.2*_r/400),o+=_l<.1?1:_l<.17?2:_l<.36?3:_l<.59?4:5}),this.remoteUserMap.size>0?Math.round(o/this.remoteUserMap.size):o}async muteLocalTrack(i){return new pE((o,p)=>{this.handleMuteLocalTrack(i,o,p)})}filterTobePublishedTracks(i,o,p){const g=[],b=I_(),A=this.getAllTracks();i=BI(i=i.filter(z=>A.indexOf(z)===-1));let j=!1,H=!1;for(const z of i){if(z instanceof ZE&&(this.localTrackMap.has(TE.LocalVideoTrack)||j?new yE(_p.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(g.push({track:z,type:TE.LocalVideoTrack}),j=!0),o)){const $=this.getLowVideoTrack(z,p);g.push({track:$,type:TE.LocalVideoLowTrack})}if(z instanceof g_){const $=this.localTrackMap.get(TE.LocalAudioTrack);if($){if(!($.track instanceof Z_))throw new yE(_p.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(z._bypassWebAudio)throw new yE(_p.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");$.track.addAudioTrack(z),this.bindLocalAudioTrackEvents(z,!0)}else if(H){const Vt=g.find(_r=>{let{type:Fi}=_r;return Fi===TE.LocalAudioTrack});if(!(Vt.track instanceof Z_))throw new yE(_p.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(z._bypassWebAudio)throw new yE(_p.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");Vt.track.addAudioTrack(z)}else{if(!b.webAudioMediaStreamDest||z instanceof Z_||z._bypassWebAudio)g.push({track:z,type:TE.LocalAudioTrack});else{const Vt=new Z_;Vt.addAudioTrack(z),g.push({track:Vt,type:TE.LocalAudioTrack})}H=!0}}}return g}filterTobeUnpublishedTracks(i){const o=[],p=this.getAllTracks();i=BI(i=i.filter(g=>p.indexOf(g)!==-1));for(const g of i){if(g instanceof g_){const b=this.localTrackMap.get(TE.LocalAudioTrack);if(!b)continue;b.track instanceof Z_?(b.track.removeAudioTrack(g),this.unbindLocalAudioTrackEvents(g),b.track.trackList.length===0&&(o.push([TE.LocalAudioTrack,b]),b.track.close())):o.push([TE.LocalAudioTrack,b])}if(g instanceof ZE){const b=this.localTrackMap.get(TE.LocalVideoTrack);if(!b)continue;o.push([TE.LocalVideoTrack,b]);const A=this.localTrackMap.get(TE.LocalVideoLowTrack);A&&o.push([TE.LocalVideoLowTrack,A])}}return o}bindLocalTrackEvents(i){i.forEach(o=>{let{track:p,type:g}=o;switch(g){case TE.LocalVideoTrack:p.addListener(xE.GET_STATS,this.handleGetLocalVideoStats),p.addListener(xE.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),p.addListener(xE.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),p.addListener(xE.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),p.addListener(xE.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),p.addListener(xE.NEED_REPLACE_TRACK,this.handleReplaceTrack),p.addListener(xE.NEED_MUTE_TRACK,this.handleMuteLocalTrack),p.addListener(xE.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case TE.LocalAudioTrack:this.bindLocalAudioTrackEvents(p);case TE.LocalVideoLowTrack:}})}bindLocalAudioTrackEvents(i,o){i instanceof Z_?i.trackList.forEach(p=>{p.addListener(xE.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),p.addListener(xE.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),p.addListener(xE.GET_STATS,this.handleGetLocalAudioStats),p.addListener(xE.NEED_MUTE_TRACK,this.handleMuteLocalTrack),p.addListener(xE.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(i.addListener(xE.GET_STATS,this.handleGetLocalAudioStats),i.addListener(xE.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),i.addListener(xE.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),i.addListener(xE.NEED_MUTE_TRACK,this.handleMuteLocalTrack),i.addListener(xE.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),o||i.addListener(xE.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(i){i||(i=Array.from(this.localTrackMap.entries()).map(o=>{let[p,{track:g}]=o;return{track:g,type:p}})),i.forEach(o=>{let{track:p,type:g}=o;switch(g){case TE.LocalVideoTrack:p.off(xE.GET_STATS,this.handleGetLocalVideoStats),p.off(xE.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),p.off(xE.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),p.off(xE.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),p.off(xE.SET_OPTIMIZATION_MODE,this.handleSetOptimizationMode),p.off(xE.NEED_REPLACE_TRACK,this.handleReplaceTrack),p.off(xE.NEED_MUTE_TRACK,this.handleMuteLocalTrack),p.off(xE.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case TE.LocalAudioTrack:this.unbindLocalAudioTrackEvents(p);case TE.LocalVideoLowTrack:}})}unbindLocalAudioTrackEvents(i){i instanceof Z_?i.trackList.forEach(o=>{o.off(xE.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),o.off(xE.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),o.off(xE.GET_STATS,this.handleGetLocalAudioStats),o.off(xE.NEED_MUTE_TRACK,this.handleMuteLocalTrack),o.off(xE.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(i.off(xE.GET_STATS,this.handleGetLocalAudioStats),i.off(xE.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),i.off(xE.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),i.off(xE.NEED_REPLACE_TRACK,this.handleReplaceTrack),i.off(xE.NEED_MUTE_TRACK,this.handleMuteLocalTrack),i.off(xE.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(i,o){o instanceof DT&&o.addListener(xE.GET_STATS,p=>{p(this.handleGetRemoteVideoStats(i))}),o instanceof cT&&o.addListener(xE.GET_STATS,p=>{p(this.handleGetRemoteAudioStats(i))})}unbindRemoteTrackEvents(i){i&&i.removeAllListeners(xE.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(i=>{let[o,p]=i;p.has(ME.AUDIO)&&this.unbindRemoteTrackEvents(o._audioTrack),p.has(ME.VIDEO)&&this.unbindRemoteTrackEvents(o._videoTrack)})}createGatewayPublishMessage(i){return i.map(o=>{var p;let g,b,{track:A,type:j}=o;switch(j){case TE.LocalAudioTrack:g=v_.Audio,b={dtx:A instanceof yR&&A._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case TE.LocalVideoTrack:g=VE(p=A._hints).call(p,A_.SCREEN_TRACK)?v_.Screen:v_.High,b=DR(DR({},rP(A)),{},{codec:this.store.codec});break;case TE.LocalVideoLowTrack:g=v_.Low,b=DR(DR({},rP(A)),{},{codec:this.store.codec})}return{kind:j===TE.LocalAudioTrack?ME.AUDIO:ME.VIDEO,stream_type:g,attributes:b,isMuted:A.muted||!A.enabled}})}createGatewayUnpublishMessage(i){return i.map(o=>{var p;let g,[b,{track:A,ssrcs:j,id:H}]=o;switch(b){case TE.LocalVideoTrack:g=VE(p=A._hints).call(p,A_.SCREEN_TRACK)?v_.Screen:v_.High;break;case TE.LocalAudioTrack:g=v_.Audio;break;case TE.LocalVideoLowTrack:g=v_.Low}return{stream_type:g,ssrcs:j,mid:H}})}assignLocalTracks(i){i.forEach(o=>{let{track:p,type:g}=o;this.localTrackMap.set(g,{track:p})})}withdrawLocalTracks(i){i.forEach(o=>{let[p]=o;this.localTrackMap.delete(p)})}bindConnectionEvents(i){i.onConnectionStateChange=async o=>{var p;if(Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(o,")")),this.emit(WE.PeerConnectionStateChange,o),o!=="connected"||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),VE(p=this._restartStates).call(p,o)||i.direction===YI.SEND_ONLY){if(this._restartTimer)return;const g=()=>{(i.iceConnectionState==="disconnected"||i.iceConnectionState==="checking"||i.iceConnectionState==="failed")&&(Gi.debug("[".concat(this.store.clientId,"] [P2PChannel] start use restartICE")),oS(this,WE.QueryClientConnectionState)==="CONNECTED"&&this.restartICE(i))};this._restartTimer=window.setTimeout(()=>{g(),this._restartTimer=void 0},800)}},i.onICEConnectionStateChange=o=>{o!=="connected"||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(o,")")),jE.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:o,tag:x_.TRACER}).onSuccess(),this.emit(WE.IceConnectionStateChange,o)},i.onICETransportStateChange=o=>{Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(o,")"))},i.onDTLSTransportStateChange=o=>{Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(o,")"))},i.onDTLSTransportError=o=>{Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(o,")"))},i.onFirstAudioDecoded=o=>{var p;const g=Array.from(CS(p=this.remoteUserMap).call(p)).find(A=>A._audioSSRC===o);var b;g&&(this.store.subscribe(g.uid,"audio",void 0,void 0,void 0,Date.now()),(b=g.audioTrack)===null||b===void 0||b.emit(sI.FIRST_FRAME_DECODED),jE.firstRemoteFrame(this.store.sessionId,p0.FIRST_AUDIO_DECODE,L_.FIRST_AUDIO_DECODE,{peer:g._uintid,subscribeElapse:k0.measureFromSubscribeStart(this.store.clientId,o),subscribeRequestid:o,p2pid:this.store.p2pId}))},i.onFirstAudioReceived=o=>{var p;const g=Array.from(CS(p=this.remoteUserMap).call(p)).find(b=>b._audioSSRC===o);g&&jE.firstRemoteFrame(this.store.sessionId,p0.FIRST_AUDIO_RECEIVED,L_.FIRST_AUDIO_RECEIVED,{peer:g._uintid,subscribeElapse:k0.measureFromSubscribeStart(this.store.clientId,o),subscribeRequestid:o,p2pid:this.store.p2pId})},i.onFirstVideoDecoded=(o,p,g)=>{this.reportVideoFirstFrameDecoded(o,p,g)},i.onFirstVideoReceived=o=>{var p;const g=Array.from(CS(p=this.remoteUserMap).call(p)).find(b=>b._videoSSRC===o);g&&jE.firstRemoteFrame(this.store.sessionId,p0.FIRST_VIDEO_RECEIVED,L_.FIRST_VIDEO_RECEIVED,{peer:g._uintid,subscribeElapse:k0.measureFromSubscribeStart(this.store.clientId,o),subscribeRequestid:o,p2pid:this.store.p2pId})},i.onSelectedLocalCandidateChanged=(o,p)=>{const g=o.candidateType==="relay",b=p.candidateType==="relay";p.candidateType!=="unknown"&&g===b||this.emit(WE.ConnectionTypeChange,g),Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(wR(p))," -> ").concat(JSON.stringify(wR(o)),")"))},i.onSelectedRemoteCandidateChanged=(o,p)=>{Gi.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(wR(p))," -> ").concat(JSON.stringify(wR(o)),")"))},i.onFirstVideoDecodedTimeout=o=>{this.reportVideoFirstFrameDecoded(o,void 0,void 0,!0)},i.onLocalCandidate=o=>{this.emit(WE.LocalCandidate,o)}}unbindConnectionEvents(i){i.onConnectionStateChange=void 0,i.onICEConnectionStateChange=void 0,i.onICETransportStateChange=void 0,i.onDTLSTransportStateChange=void 0,i.onDTLSTransportError=void 0,i.onFirstAudioDecoded=void 0,i.onFirstAudioReceived=void 0,i.onFirstVideoDecoded=void 0,i.onFirstVideoReceived=void 0,i.onSelectedLocalCandidateChanged=void 0,i.onSelectedRemoteCandidateChanged=void 0,i.onFirstVideoDecodedTimeout=void 0,i.onLocalCandidate=void 0}filterTobeMutedTracks(i){const o=[];if(this.getAllTracks().indexOf(i)===-1)return o;const p=this.localTrackMap.get(TE.LocalAudioTrack);if(i instanceof g_&&(p==null?void 0:p.track)instanceof Z_)return p.track.isActive||o.push([TE.LocalAudioTrack,p]),o;const g=Array.from(this.localTrackMap.entries()).find(b=>{let[,{track:A}]=b;return i===A});if(g&&(o.push(g),g[0]===TE.LocalVideoTrack)){const b=this.localTrackMap.get(TE.LocalVideoLowTrack);b&&o.push([TE.LocalVideoLowTrack,b])}return o}filterTobeUnmutedTracks(i){const o=[],p=this.localTrackMap.get(TE.LocalAudioTrack);if(i instanceof g_&&(p==null?void 0:p.track)instanceof Z_)return p.track.isActive&&o.push([TE.LocalAudioTrack,p]),o;const g=Array.from(this.localTrackMap.entries()).find(b=>{let[,{track:A}]=b;return i===A});if(g)if(g[0]===TE.LocalVideoTrack){o.push(g);const b=this.localTrackMap.get(TE.LocalVideoLowTrack);b&&o.push([TE.LocalVideoLowTrack,b])}else o.push(g);return o}createMuteMessage(i){return i.map(o=>{var p;let g,[b,{track:A,ssrcs:j,id:H}]=o;switch(b){case TE.LocalAudioTrack:g=v_.Audio;break;case TE.LocalVideoTrack:g=VE(p=A._hints).call(p,A_.SCREEN_TRACK)?v_.Screen:v_.High;break;case TE.LocalVideoLowTrack:g=v_.Low}return{stream_type:g,ssrcs:j,mid:H}})}createUnmuteMessage(i){return i.map(o=>{var p;let g,[b,{track:A,ssrcs:j,id:H}]=o;switch(b){case TE.LocalAudioTrack:g=v_.Audio;break;case TE.LocalVideoTrack:g=VE(p=A._hints).call(p,A_.SCREEN_TRACK)?v_.Screen:v_.High;break;case TE.LocalVideoLowTrack:g=v_.Low}return{stream_type:g,ssrcs:j,mid:H}})}filterTobeUnSubscribedTracks(i,o){const p=[],g=this.remoteUserMap.get(i);if(!g)return p;if(o){const b=g.get(o);if(!b)return p;p.push([i,{kind:o,id:b}])}else Array.from(g.entries()).forEach(b=>{let[A,j]=b;p.push([i,{kind:A,id:j}])});return p}createUnsubscribeMessage(i){const o=[];return i.forEach(p=>{let[g,{kind:b,id:A}]=p;switch(b){case ME.VIDEO:return void(g._videoSSRC&&o.push({stream_type:ME.VIDEO,ssrcId:g._videoSSRC}));case ME.AUDIO:return void(g._audioSSRC&&o.push({stream_type:ME.AUDIO,ssrcId:g._audioSSRC}))}}),o}withdrawRemoteTracks(i){i.forEach(o=>{let[p,{kind:g}]=o;const b=this.remoteUserMap.get(p);b&&(b.delete(g),Array.from(b.entries()).length===0&&this.remoteUserMap.delete(p))})}async updateBitrateLimit(i){const o=this.localTrackMap.get(TE.LocalVideoTrack),p=this.localTrackMap.get(TE.LocalVideoLowTrack);o&&await o.track.setBitrateLimit(i.uplink),p&&i.low_stream_uplink&&await p.track.setBitrateLimit({max_bitrate:i.low_stream_uplink.bitrate,min_bitrate:i.low_stream_uplink.bitrate||0})}isP2PDisconnected(){if(this.sendConnection&&this.recvConnection){const i=this.sendConnection.peerConnectionState,o=this.recvConnection.peerConnectionState;return i!=="connected"&&o!=="connected"}return!0}async tryToUnmuteAudio(i){for(let o=0;othis.getStats(i),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter(i=>{let[,{ssrcs:o}]=i;return!!o}),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=i=>{var o;return!((o=this.recvConnection)===null||o===void 0||!o.getRemoteVideoIsReady(i))},this.statsUploader.requestUpload=(i,o)=>this.emit(WE.RequestUploadStats,i,o),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 w0(mN(this.dtlsFailedCount,$_)),this.emit(WE.RequestReconnect)}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(TE.LocalVideoTrack)||this.pendingLocalTracks.some(i=>i instanceof ZE)}throwIfTrackTypeNotMatch(i){if(i.filter(o=>o instanceof ZE).length>1)throw new yE(_p.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(i.filter(o=>o instanceof g_).length>1&&(i.some(o=>o instanceof g_&&o._bypassWebAudio)||!I_().webAudioMediaStreamDest))throw new yE(_p.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const o of i){if(o instanceof ZE&&this.pendingLocalTracks.some(p=>p instanceof ZE))throw new yE(_p.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(o instanceof g_&&this.pendingLocalTracks.some(p=>p instanceof g_)&&(!I_().webAudioMediaStreamDest||o._bypassWebAudio||this.pendingLocalTracks.some(p=>p instanceof g_&&p._bypassWebAudio)))throw new yE(_p.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(i,o){const p=!nE("DISABLE_DUAL_STREAM_USE_ENCODING")&&I_().supportDualStreamEncoding,g=DR(DR({},{width:160,height:120,framerate:15,bitrate:50}),o);let b;b=p?i._mediaStreamTrack.clone():C2(i,g);const A=T_(8,"track-low-"),j=new ZE(b,DR(DR({},p&&{scaleResolutionDownBy:c2(g,i)}),{},{frameRate:g.framerate,bitrateMax:g.bitrate,bitrateMin:g.bitrate}),void 0,void 0,A);return j.on($I.TRANSCEIVER_UPDATED,H=>{i._updateRtpTransceiver(H,vR.LOW_STREAM)}),j._hints.push(A_.LOW_STREAM),i.addListener(xE.NEED_CLOSE,()=>{j.close()}),j}async globalLock(){return this.recvMutex.lock("From P2PChannel2.globalLock")}reportVideoFirstFrameDecoded(i,o,p,g){var b;const A=Array.from(CS(b=this.remoteUserMap).call(b)).find(j=>j._videoSSRC===i);if(A){g||this.store.subscribe(A.uid,"video",void 0,void 0,void 0,void 0,Date.now());const j=this.store.keyMetrics,H=j.subscribe.find(z=>z.userId===A.uid&&z.type==="video");jE.firstRemoteVideoDecode(this.store.sessionId,p0.FIRST_VIDEO_DECODE,L_.FIRST_VIDEO_DECODE,{peer:A._uintid,videowidth:o,videoheight:p,subscribeElapse:k0.measureFromSubscribeStart(this.store.clientId,i),subscribeRequestid:i,p2pid:this.store.p2pId,apEnd:j.requestAPEnd||0,apStart:j.requestAPStart||0,joinGwEnd:j.joinGatewayEnd||0,joinGwStart:j.joinGatewayStart||0,pcEnd:j.peerConnectionEnd||0,pcStart:j.peerConnectionStart||0,subscriberEnd:(H==null?void 0:H.subscribeEnd)||0,subscriberStart:(H==null?void 0:H.subscribeStart)||0,videoAddNotify:(H==null?void 0:H.streamAdded)||0,state:g?1:0})}}async remoteMediaSsrcChanged(i,o,p){if(!this.recvConnection)return!1;const g=this.remoteUserMap.get(i);if(!g)return!1;const b=g.get(o);if(!b)return!1;const A=await this.recvConnection.getRemoteSSRC(b);return A!==void 0&&A!==p}resetConnection(i){Gi.debug("[".concat(this.store.clientId,"] [P2PChannel2] reset connection to ").concat(i)),this.state===u_.Connected?(Gi.debug("[".concat(this.store.clientId,"] [P2PChannel2] fallback to websocket but P2PChannel2 state still connected, disconnect first")),this.disconnectForReconnect()):(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))}async publishDataChannel(i){throw new yE(_p.NOT_SUPPORTED)}async unpublishDataChannel(i){throw new yE(_p.NOT_SUPPORTED)}async subscribeDataChannel(i,o){throw new yE(_p.NOT_SUPPORTED)}async unsubscribeDataChannel(i,o){throw new yE(_p.NOT_SUPPORTED)}hasPendingRemoteDataChannel(i,o){throw new yE(_p.NOT_SUPPORTED)}setPendingRemoteDataChannel(i,o){throw new yE(_p.NOT_SUPPORTED)}async preConnect(i,o,p,g,b,A){throw new yE(_p.NOT_SUPPORTED)}getEstablishParams(){throw new yE(_p.NOT_SUPPORTED)}async reSubscribe(i){throw new yE(_p.NOT_SUPPORTED)}async updateVideoStreamParameter(i,o){throw new yE(_p.NOT_SUPPORTED)}unbindRtpTransceiver(){this.localTrackMap.size!==0&&Array.from(this.localTrackMap.entries()).forEach(i=>{let[o,{track:p}]=i;o===TE.LocalVideoLowTrack?p._updateRtpTransceiver(void 0,vR.LOW_STREAM):p._updateRtpTransceiver(void 0)})}}function ZS(l){return function(i,o,p){const g=i[o];if(typeof g!="function")throw new Error("Cannot use mutex on object property.");return p.value=async function(){for(var b=arguments.length,A=new Array(b),j=0;j0&&(p.firstRecvTs=Date.now()-b);let j=o.mediaDelay+A;j<=0?(i.pop(),k8(o.context,g),j=0):j=Math.min(j,unt),setTimeout(()=>i.length&&P8(l),j)}function k8(l,i){l.safeEmit(n_.STREAM_MESSAGE,i.uid,i.payload),l.onStreamMessage&&l.onStreamMessage(i)}function lnt(l){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=arguments.length>2?arguments[2]:void 0;if(!l.syncWithAudio)return k8(o,{uid:l.uid,payload:dN(l.payload)});const p="".concat(o.id,"-").concat(l.uid),g=M2.get(p)||[],b=g.findIndex(z=>l.sendTs>=z.sendTs),A=N8(N8({},l),{},{context:o,mediaDelay:i,recvTs:Date.now()});b===-1?g.push(A):g.splice(b,0,A),M2.set(p,g);let j=!1;var H;CP.has(p)?j=!((H=CP.get(p))===null||H===void 0||!H.isSyncing):CP.set(p,{isSyncing:j,firstRecvTs:0,firstSendTs:0}),j||P8(p)}const dnt=l_().name;function hnt(){return!function(l,i,o){const p=l_();if(p.os!==l0.IOS||!p.osVersion)return!1;const g=p.osVersion.split(".");return o?i&&Number(g[0])===l&&Number(g[1]){this.publish(p,!1).then(g).catch(b)}),_e(this,"_handleLocalTrackDisable",(p,g,b)=>{this.unpublish(p).then(g).catch(b)}),_e(this,"_handleUserOnline",p=>{if(nE("BLOCK_LOCAL_CLIENT")&&nI(p.uid,this.channelName))return void Gi.debug("[".concat(p.uid,"] will be ignored in local"));this.isStringUID&&typeof p.uid!="string"&&Gi.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));const g=this._users.find(b=>b.uid===p.uid);if(g)g._trust_in_room_=!0;else{const b=new D0(p.uid,p.uint_id||p.uid);this._users.push(b),Gi.debug("[".concat(this._clientId,"] user online"),p.uid),this.safeEmit(n_.USER_JOINED,b)}}),_e(this,"_handleUserOffline",p=>{if(nE("BLOCK_LOCAL_CLIENT")&&nI(p.uid,this.channelName))return;const g=this._users.find(b=>b.uid===p.uid);g&&(this._handleRemoveStream(p),this._handleRemoveDataChannels(p),VL(this._users,g),this._remoteStreamTypeCacheMap.delete(g.uid),this._streamFallbackTypeCacheMap.delete(g.uid),Gi.debug("[".concat(this._clientId,"] user offline"),p.uid,"reason:",p.reason),this.safeEmit(n_.USER_LEAVED,g,p.reason))}),_e(this,"_handleAddAudioOrVideoStream",(p,g,b,A,j,H,z)=>{if(nE("BLOCK_LOCAL_CLIENT")&&nI(g,this.channelName))return;const $=this._users.find(_r=>_r.uid===g);if(!$)return void Gi.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));Gi.debug("[".concat(this._clientId,"] stream added with uid ").concat(g,", type ").concat(p)),this.store.subscribe($.uid,p,void 0,void 0,void 0,Date.now());const Vt=p==="audio"?$.hasAudio:$.hasVideo;$._uintid||($._uintid=j||g),p==="audio"?$._trust_audio_stream_added_state_=!0:$._trust_video_stream_added_state_=!0,p==="audio"?($._audio_added_=!0,b!==void 0&&($._audioSSRC=b),A!==void 0&&($._cname=A),H&&($._audioOrtc=H)):($._video_added_=!0,b!==void 0&&($._videoSSRC=b),A!==void 0&&($._cname=A),z!==void 0&&($._rtxSsrcId=z),H&&($._videoOrtc=H)),(p==="audio"?$.hasAudio:$.hasVideo)&&!Vt&&(Gi.info("[".concat(this._clientId,"] remote user ").concat($.uid," published ").concat(p)),this.safeEmit(n_.USER_PUBLISHED,$,p)),p==="video"?jE.onGatewayStream(this._sessionId,p0.ON_ADD_VIDEO_STREAM,L_.ON_ADD_VIDEO_STREAM,{peer:j||g,ssrc:$._videoSSRC}):jE.onGatewayStream(this._sessionId,p0.ON_ADD_AUDIO_STREAM,L_.ON_ADD_AUDIO_STREAM,{peer:j||g,ssrc:$._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged($,p,b).then(_r=>{if(_r&&(Gi.debug("[".concat(this._clientId,"] resubscribe ").concat(p," for user ").concat($.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof S0))return this._p2pChannel.unsubscribe($,p,!0).then(()=>this._subscribe($,p,!0).catch(Fi=>{Gi.error("[".concat(this._clientId,"] resubscribe error"),Fi.toString())}))}),this._p2pChannel.hasPendingRemoteMedia($,p)&&(Gi.debug("[".concat(this._clientId,"] resubscribe ").concat(p," for user ").concat($.uid," after reconnect.")),this._subscribe($,p,!0).catch(_r=>{Gi.error("[".concat(this._clientId,"] resubscribe error"),_r.toString())}))}),_e(this,"_handleRemoveStream",(p,g,b)=>{if(nE("BLOCK_LOCAL_CLIENT")&&nI(p.uid,this.channelName))return;const A=this._users.find(H=>H.uid===p.uid);if(!A)return void Gi.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));Gi.debug("[".concat(this._clientId,"] stream removed with uid ").concat(p.uid));let j=()=>{};if(A.hasAudio&&A.hasVideo?j=()=>{Gi.info("[".concat(this._clientId,"] remote user ").concat(A.uid," unpublished audio track")),this.safeEmit(n_.USER_UNPUBLISHED,A,"audio"),Gi.info("[".concat(this._clientId,"] remote user ").concat(A.uid," unpublished video track")),this.safeEmit(n_.USER_UNPUBLISHED,A,"video")}:A.hasVideo?j=()=>{Gi.info("[".concat(this._clientId,"] remote user ").concat(A.uid," unpublished video track")),this.safeEmit(n_.USER_UNPUBLISHED,A,"video")}:A.hasAudio&&(j=()=>{Gi.info("[".concat(this._clientId,"] remote user ").concat(A.uid," unpublished audio track")),this.safeEmit(n_.USER_UNPUBLISHED,A,"audio")}),A._trust_audio_stream_added_state_=!0,A._trust_video_stream_added_state_=!0,A._audio_added_=!1,A._video_added_=!1,this._p2pChannel instanceof S0)this._p2pChannel.unsubscribe(A).then(H=>{if(H)return this._gateway.unsubscribe(H,A.uid)});else if(g&&b)if(p.sdp){const{sdp:H}=p;this._p2pChannel.unsubscribe(A,H).then(z=>{z&&g(z)}).catch(b)}else g&&g();A._audioSSRC=void 0,A._videoSSRC=void 0,A._audioOrtc=void 0,A._videoOrtc=void 0,A._rtxSsrcId=void 0,jE.onGatewayStream(this._sessionId,p0.ON_REMOVE_STREAM,L_.ON_REMOVE_STREAM,{peer:p.uint_id||p.uid}),j()}),_e(this,"_handleSetStreamLocalEnable",(p,g,b)=>{if(nE("BLOCK_LOCAL_CLIENT")&&nI(g,this.channelName))return;const A=this._users.find(z=>z.uid===g);if(!A)return void Gi.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));Gi.debug("[".concat(this._clientId,"] local ").concat(p," ").concat(b?"enabled":"disabled"," with uid ").concat(g));const j=p==="audio"?A.hasAudio:A.hasVideo;if(p==="audio"){A._trust_audio_enabled_state_=!0;const z=A._audio_enabled_;if(A._audio_enabled_=b,A._audio_enabled_===z)return;{const $=A._audio_enabled_?"enable-local-audio":"disable-local-audio";Gi.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(g,", msg: ").concat($)),this.safeEmit(n_.USER_INFO_UPDATED,g,$)}}else{A._trust_video_enabled_state_=!0;const z=A._video_enabled_;if(A._video_enabled_=b,A._video_enabled_===z)return;{const $=A._video_enabled_?"enable-local-video":"disable-local-video";Gi.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(g,", msg: ").concat($)),this.safeEmit(n_.USER_INFO_UPDATED,g,$)}}const H=p==="audio"?A.hasAudio:A.hasVideo;return j!==H?!j&&H?(Gi.info("[".concat(this._clientId,"] remote user ").concat(g," published ").concat(p)),void this.safeEmit(n_.USER_PUBLISHED,A,p)):(p==="video"&&A._videoTrack&&A._videoTrack._destroy(),p==="audio"&&A._audioTrack,this._p2pChannel.muteRemote(A,p),Gi.info("[".concat(this._clientId,"] remote user ").concat(g," unpublished ").concat(p)),void this.safeEmit(n_.USER_UNPUBLISHED,A,p)):void 0}),_e(this,"_handleMuteStream",(p,g,b,A,j,H)=>{if(nE("BLOCK_LOCAL_CLIENT")&&nI(p,this.channelName))return;Gi.debug("[".concat(this._clientId,"] receive mute message"),p,g,b);const z=this._users.find(_r=>_r.uid===p);if(!z)return void Gi.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(p));const $=g==="audio"?z.hasAudio:z.hasVideo;if(g==="audio"){z._trust_audio_mute_state_=!0;const _r=z._audio_muted_;if(z._audio_muted_=b,z._audio_muted_===_r)return;{const Fi=z._audio_muted_?"mute-audio":"unmute-audio";Gi.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(p,", msg: ").concat(Fi)),this.safeEmit(n_.USER_INFO_UPDATED,p,Fi)}}else{z._trust_video_mute_state_=!0;const _r=z._video_muted_;if(z._video_muted_=b,z._video_muted_===_r)return;{const Fi=z._video_muted_?"mute-video":"unmute-video";Gi.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(p,", msg: ").concat(Fi)),this.safeEmit(n_.USER_INFO_UPDATED,p,Fi)}}const Vt=g==="audio"?z.hasAudio:z.hasVideo;if($!==Vt){if(!$&&Vt)return!this.store.useP2P&&!(g==="audio"?z._audioSSRC:z._videoSSRC)?void Gi.warning("[".concat(this._clientId,"] remote user ").concat(p," receive ").concat(g," unmute message before add stream message, ").concat(g," SSRC doesn't exist yet.")):(Gi.info("[".concat(this._clientId,"] remote user ").concat(p," published ").concat(g)),void this.safeEmit(n_.USER_PUBLISHED,z,g));g==="video"&&z._videoTrack&&z._videoTrack._destroy(),g==="audio"&&z._audioTrack,j&&H&&this._p2pChannel instanceof V_&&(A?this._p2pChannel.unsubscribe(z,A,g).then(_r=>{j(_r)}).catch(H):j()),this._p2pChannel.muteRemote(z,g),Gi.info("[".concat(this._clientId,"] remote user ").concat(p," unpublished ").concat(g)),this.safeEmit(n_.USER_UNPUBLISHED,z,g)}}),_e(this,"_handleP2PLost",async p=>{Gi.debug("[".concat(this._clientId,"] receive p2p lost"),p),parseInt(p.p2pid,10)===this.store.p2pId?await this._p2pChannel.requestReconnect():Gi.warning("[".concat(this._clientId,"] P2PLost stream not found"),p)}),_e(this,"_handleTokenWillExpire",()=>{Gi.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(n_.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)}),_e(this,"_handleBeforeUnload",p=>{p.type==="beforeunload"&&p.returnValue!==void 0&&p.returnValue!==""||(this.leave(),Gi.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))}),_e(this,"_handleUpdateNetworkQuality",()=>{if(this._networkQualitySensitivity==="normal")return;if(navigator&&navigator.onLine!==void 0&&!navigator.onLine)return void this.safeEmit(n_.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const p={downlinkNetworkQuality:0,uplinkNetworkQuality:0};p.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),p.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(n_.NETWORK_QUALITY,p)}),_e(this,"_handleP2PAddAudioOrVideoStream",(p,g)=>{const b=this._users.find(j=>j.uid===g);if(!b)return void Gi.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));Gi.debug("[".concat(this._clientId,"] stream added with uid ").concat(g,", type ").concat(p)),this.store.subscribe(b.uid,p,void 0,void 0,void 0,Date.now());const A=p==="audio"?b.hasAudio:b.hasVideo;p==="audio"?b._trust_audio_stream_added_state_=!0:b._trust_video_stream_added_state_=!0,p==="audio"?b._audio_added_=!0:b._video_added_=!0,(p==="audio"?b.hasAudio:b.hasVideo)&&!A&&(Gi.info("[".concat(this._clientId,"] remote user ").concat(b.uid," published ").concat(p)),this.safeEmit(n_.USER_PUBLISHED,b,p)),this._p2pChannel.hasPendingRemoteMedia(b,p)&&(Gi.debug("[".concat(this._clientId,"] resubscribe ").concat(p," for user ").concat(b.uid," after reconnect.")),this._subscribe(b,p,!0).catch(j=>{Gi.error("[".concat(this._clientId,"] resubscribe error"),j.toString())}))}),this._config=i,this._clientId=T_(5,"client-"),this.store=new mZ(i.codec,i.audioCodec,i.mode,this._clientId),this.store.clientCreated(),i.proxyServer&&this.setProxyServer(i.proxyServer,!0),i.turnServer&&this.setTurnServer(i.turnServer,!0),Gi.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(qS," build: ").concat(uM,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),i.clientRoleOptions)try{_B(i.clientRoleOptions),o=Object.assign({},i.clientRoleOptions)}catch(p){Gi.warning("[".concat(this._clientId,"] ").concat(p.toString()))}this._statsCollector=new oO(this.store),this._statsCollector.onStatsException=(p,g,b)=>{Gi.debug("[".concat(this._clientId,"] receive exception msg, code: ").concat(p,", msg: ").concat(g,", uid: ").concat(b)),this.safeEmit(n_.EXCEPTION,{code:p,msg:g,uid:b})},this._statsCollector.onUploadPublishDuration=(p,g,b,A)=>{const j=this._users.find(H=>H.uid===p);j&&jE.peerPublishStatus(this._sessionId,{subscribeElapse:A,audioPublishDuration:g,videoPublishDuration:b,peer:j._uintid})},this.store.useDataChannel=I_().supportDataChannel&&nE("SIGNAL_CHANNEL"),this.store.useP2P=nE("P2P"),this._gateway=new _et(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:i.websocketRetryConfig||$_,httpRetryConfig:i.httpRetryConfig||$_,forceWaitGatewayResponse:i.forceWaitGatewayResponse===void 0||i.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:i.role,clientRoleOptions:o}),this._configDistribute=new Oet,this.store.useP2P?(this._p2pChannel=new V_(this.store,this._statsCollector),this._handleP2PEvents()):this._p2pChannel=new S0(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}async joinMeta(i,o,p,g,b){let A=!(arguments.length>5&&arguments[5]!==void 0)||arguments[5],j=arguments.length>6&&arguments[6]!==void 0&&arguments[6];y_("JOIN_GATEWAY_USE_443PORT_ONLY",A),y_("JOIN_GATEWAY_USE_DUAL_DOMAIN",j);const H=this._gateway.signal.websocket;return H instanceof HO&&(H.use443PortOnly=A,H.tryDoubleDomain=j),async function(z,$,Vt){sN.get(z)||sN.set(z,[]),oN.get(z)||oN.set(z,$),IT.get(z)||IT.set(z,0);const _r=sN.get(z),Fi=oN.get(z);if(!_r||!Fi)throw new Error("concurrent: deferQueue or maxConcurrency is null");if(IT.get(z)===Fi){const eE=UO();_r.push(eE),await eE.promise}IT.set(z,IT.get(z)+1);for(var _l=arguments.length,_u=new Array(_l>3?_l-3:0),_h=3;_h<_l;_h++)_u[_h-3]=arguments[_h];const _g=await Vt(..._u);return IT.set(z,IT.get(z)-1),IT.get(z)===Fi-1&&_r.length>0&&(_r[0].resolve(),_r.shift()),IT.get(z)===0&&(sN.set(z,[]),oN.set(z,0),IT.set(z,0)),_g}("client.join",nE("JOIN_MAX_CONCURRENCY"),this.join.bind(this),i,o,p,g,b)}async join(i,o,p,g,b){const A=++this._numberOfJoinCount;this.store.joinStart(),g&&(this.store.uid=g);const j=fZ(),H=r6()?window.isSecureContext:"Browser Not Support";if(!r6()&&!j||!window.isSecureContext){const _u="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";Gi.warning(_u)}const z=BL();this.connectionState==="DISCONNECTED"&&(this.store.avoidJoinStart=Math.round(Date.now()),Gi.debug("[".concat(this._clientId,"] set avoidJoinStart to ").concat(this.store.avoidJoinStart)));const $=jE.reportApiInvoke(z,{name:e0.JOIN,options:[i,o,p,g],states:{isHttps:j,isSecureContext:H},tag:x_.TRACER});jE.setAppId(i);try{if(!p&&p!==null)throw new hE(_p.INVALID_PARAMS,"Invalid token: ".concat(p,". If you don not use token, set it to null"));p&&O0(p,"token",1,2047),O0(i,"appid",1,2047),pM(o),g&&fM(g),b&&O0(b,"optionalInfo",1,2047)}catch(_u){throw $.onError(_u),_u}if(Gi.info("[".concat(this._clientId,"] start join channel ").concat(o,", join number: ").concat(A)),this._leaveMutex.isLocked&&(Gi.debug("[".concat(this._clientId,"] join: waiting leave operation")),(await this._leaveMutex.lock())(),Gi.debug("[".concat(this._clientId,"] join: continue"))),this._joinAndNotLeaveYet=!0,this.connectionState!=="DISCONNECTED"){const _u=new hE(_p.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw $.onError(_u),_u}this._sessionId||(this._sessionId=z,this.store.sessionId=this._sessionId),this._gateway.state="CONNECTING";const Vt=v1({clientId:this._clientId,appId:i,sid:this._sessionId,cname:o,uid:typeof g!="string"?g:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:p||i,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:b,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint},this._remoteDefaultVideoStreamType!==void 0&&{defaultVideoStream:this._remoteDefaultVideoStreamType});if(this._useLocalAccessPoint&&(Vt.setLocalAPVersion=this._setLocalAPVersion),typeof g=="string"&&(Vt.stringUid=g,this._uintUid?(Vt.uid=this._uintUid,this._uintUid=void 0):Vt.uid=0),this._encryptionMode!=="none"&&this._encryptionSecret){if(Vt.aesmode=this._encryptionMode,Vt.aespassword=await S$(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new hE(_p.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(Vt.aessalt=this._encryptionSalt)}this._startSession(this._sessionId,{channel:o,appId:i});const _r=this._sessionId;setTimeout(()=>{this.connectionState==="CONNECTING"&&_r===this._sessionId&&jE.joinChannelTimeout(this._sessionId,5)},5e3);try{var Fi;let _u;const _h=Vt.cloudProxyServer;if(VE(Fi=["proxy3","proxy4","proxy5"]).call(Fi,_h)){const SE=nE("PROXY_SERVER_TYPE3");Array.isArray(SE)?Vt.proxyServer=SE[0]:Vt.proxyServer=SE}if(jE.setProxyServer(Vt.proxyServer),Gi.setProxyServer(Vt.proxyServer),this.store.requestAPStart(),Vt.stringUid&&!Vt.uid){const SE=await _5(Vt.stringUid,Vt,this._axiosCancelSource.token,this._config.httpRetryConfig||$_,this.store);Gi.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(Vt.stringUid," => ").concat(SE)),Vt.uid=SE,_u=await v5(Vt,this._axiosCancelSource.token,this._config.httpRetryConfig||$_,!0,this.store)}else _u=await v5(Vt,this._axiosCancelSource.token,this._config.httpRetryConfig||$_,!0,this.store);if(!this._joinAndNotLeaveYet)throw new hE(_p.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this.store.requestAPEnd(),setTimeout(()=>{this._configDistribute.startGetConfigDistribute(Vt,this._axiosCancelSource.token),this._configDistribute.on(WO.UPDATE_BITRATE_LIMIT,SE=>{this._p2pChannel.updateBitrateLimit(SE)})},0),this._key=p||i;const _g=_u.gatewayInfo;this._joinInfo=v1(v1({},Vt),{},{cid:_g.cid,uid:Vt.uid?Vt.uid:_g.uid,vid:_g.vid,apResponse:_g.res,uni_lbs_ip:_g.uni_lbs_ip,gatewayAddrs:_g.gatewayAddrs});const eE=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new hE(_p.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));$.onSuccess(eE),this._appId=i,this._channelName=Vt.cname,this._uid=eE,this.store.uid=eE,setTimeout(()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),window.addEventListener(H0()?"beforeunload":"pagehide",this._handleBeforeUnload)},0);const oE=Vt.stringUid?"string uid: ".concat(Vt.stringUid,",uid: ").concat(Vt.uid):"uid: ".concat(this._uid);return Gi.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(o,",").concat(oE)),setTimeout(()=>{Gi.startUpload()},5e3),this.store.joinEnd(),_l=this,VE(fR).call(fR,_l)||fR.push(_l),eE}catch(_u){const _h=Array.isArray(_u)?_u[0]:_u;throw _h&&_h.code===_p.OPERATION_ABORTED?Gi.warning("[".concat(this._clientId,"] join number: ").concat(A,", Joining channel failed, rollback"),_h):Gi.error("[".concat(this._clientId,"] join number: ").concat(A,", Joining channel failed, rollback"),_h),_h.code!==_p.OPERATION_ABORTED&&this._numberOfJoinCount===A&&(this._gateway.state="DISCONNECTED",this._reset()),$.onError(_h),_h}var _l}_joinGateway(){if(!this._joinInfo||!this._key)throw new hE(_p.INVALID_OPERATION);return this._gateway.join(this._joinInfo,this._key,!(this._joinInfo.cloudProxyServer!=="disabled"||this._joinInfo.proxyServer||!nE("JOIN_WITH_FALLBACK_SIGNAL_PROXY"))).then(i=>i).catch(i=>{if(i.code===_p.INIT_WEBSOCKET_TIMEOUT)return this._gateway.leave(!0,e_.FALLBACK),i;if(i.code===_p.INIT_DATACHANNEL_TIMEOUT)return this._gateway.leave(!0,e_.FALLBACK),i;throw i}).then(i=>{if(i instanceof hE){if(i.code===_p.INIT_WEBSOCKET_TIMEOUT){if(Gi.info("[".concat(this._clientId,"] join timeout, fallback to proxy")),!this._joinInfo||!this._key)throw new hE(_p.INVALID_OPERATION);this._joinInfo.cloudProxyServer="fallback",this._cloudProxyServerMode="fallback",this.store.cloudProxyServerMode="fallback";const o=nE("PROXY_SERVER_TYPE3");if(Array.isArray(o))if(this._joinInfo.apUrl){const g=/^https?:\/\/(.+?)(\/.*)?$/.exec(this._joinInfo.apUrl)[1].split("."),b=g.slice(g.length-2).join(".");o.forEach(A=>{this._joinInfo&&VE(A).call(A,b)&&(this._joinInfo.proxyServer=A)}),this._joinInfo.proxyServer||(this._joinInfo.proxyServer=o[0])}else this._joinInfo.proxyServer=o[0];else this._joinInfo.proxyServer=o;const p=nE("LOG_UPLOAD_SERVER").match(/.+:(\d{1,5})$/);return p&&p[1]&&p[1]!=="443"&&Gi.setProxyServer(this._joinInfo.proxyServer),nE("STATS_COLLECTOR_PORT").toString()!=="443"&&jE.setProxyServer(this._joinInfo.proxyServer),jE.reportApiInvoke(this._sessionId,{name:e0.JOIN_FALLBACK_TO_PROXY,options:[this._joinInfo.proxyServer],tag:x_.TRACER}).onSuccess(),this.safeEmit(n_.JOIN_FALLBACK_TO_PROXY,this._joinInfo.proxyServer),nE("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&this._joinInfo.turnServer.servers.forEach(g=>{"forceturn"in g&&(g.forceturn=!0)}),this._gateway.join(this._joinInfo,this._key)}if(Gi.info("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new hE(_p.INVALID_OPERATION);return jE.reportApiInvoke(this._sessionId,{name:e0.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:x_.TRACER}).onSuccess(),this._joinGateway()}return i}).then(i=>i)}async leave(){Gi.info("[".concat(this._clientId,"] Leaving channel")),window.removeEventListener(H0()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(o){const p=fR.indexOf(o);p!==-1&&fR.splice(p,1)}(this);const i=await this._leaveMutex.lock();if(this.connectionState==="DISCONNECTED")return Gi.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void i();await this._gateway.leave(this.connectionState!=="CONNECTED"),Gi.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),i()}async publish(i){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!Array.isArray(i)){if(!(i instanceof P0))return this._publishDataChannel(i);i=[i]}if(i.length===0)throw new hE(_p.INVALID_PARAMS,"param list is empty");const p=i;if(this._gateway.role==="audience")throw new hE(_p.INVALID_OPERATION,"audience can not publish stream");for(const b of p){if(!(b instanceof P0))throw new hE(_p.INVALID_PARAMS,"parameter is not local track");if(!b._enabled&&o)throw new hE(_p.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(b.getTrackId()))}Gi.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(p.map(b=>"".concat(b.getTrackId()," "))));const g=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),o&&p.forEach(b=>{const A=this._configDistribute.getBitrateLimit();b instanceof ZE&&A&&b.setBitrateLimit(A.uplink)});try{await this._publishHighStream(p),Gi.info("[".concat(this._clientId,"] Publish success, id ").concat(p.map(b=>"".concat(b.getTrackId()," "))))}catch(b){throw Gi.error("[".concat(this._clientId,"] publish error"),b.toString()),b}finally{g()}}async _publishDataChannel(i){b_(i.id,"id",0,65535,!0),QR(i.ordered,"ordered"),O0(i.metadata,"metadata",0,512),Gi.info("[".concat(this._clientId,"] Publishing datachannels, id ").concat(i.id));const o=await this._publishMutex.lock();try{if(this._p2pChannel.getAllDataChannels().findIndex(g=>g.id===i.id)!==-1)throw new hE(_p.INVALID_PARAMS,"Invalid id: ".concat(i.id,". If you want to republish the datachannel, unpublish first"));if(!this._joinInfo||this._uid===void 0)throw new hE(_p.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if(this._turnServer.mode==="auto"&&nE("FORCE_TURN")&&!nE("TURN_ENABLE_TCP")&&!nE("TURN_ENABLE_UDP"))throw new hE(_p.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const p=new Z4(i);await this._p2pChannel.publishDataChannel([p]);try{const g={streamId:i.id,ordered:i.ordered,maxRetransmits:nE("DATASTREAM_MAX_RETRANSMITS"),metadata:i.metadata,channelId:p._originDataChannelId};await this._gateway.publishDataChannel(this._uid,g,!0)}catch(g){if(g.code!==_p.DISCONNECT_P2P)throw g}return await p._waitTillOpen(),Gi.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(p.id)),p}catch(p){throw Gi.error("[".concat(this._clientId,"] publish datachannels error"),p.toString()),p}finally{o()}}async unpublish(i){if(!this._joinInfo||this._uid===void 0)throw new hE(_p.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let o=[];if(i)if(Array.isArray(i))o=i;else{if(!(i instanceof P0))return this._unpublishDataChannel([i]);o=[i]}else this.store.useP2P||await this._unpublishDataChannel(),o=this._p2pChannel.getAllTracks(!0);Gi.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(o.map(g=>"".concat(g.getTrackId()," "))," "));const p=await this._publishMutex.lock();try{if(this._p2pChannel instanceof V_){const g=await this._p2pChannel.unpublish(o);if(g){const b=await this._gateway.sendExtensionMessage(w_.UNPUBLISH,g);b&&await this._p2pChannel.setDescription("local",b)}}else{const g=await this._p2pChannel.unpublish(o);g&&await this._gateway.unpublish(g,this._uid),Gi.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(o.map(b=>"".concat(b.getTrackId()))))}}catch(g){throw Gi.error("[".concat(this._clientId,"] unpublish error"),g.toString()),g}finally{p&&p()}}async _unpublishDataChannel(i){i!==void 0&&i.length!==0||(i=this._p2pChannel.getAllDataChannels()),Gi.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(i.map(p=>"".concat(p.id," "))," "));const o=await this._publishMutex.lock();try{const p=await this._p2pChannel.unpublishDataChannel(i);p&&await this._gateway.unpublishDataChannel(p),Gi.info("[".concat(this._clientId,"] Unpublish dataChannel success,dataChannel ").concat(i.map(g=>"".concat(g.id))))}catch(p){throw Gi.error("[".concat(this._clientId,"] unpublish dataChannel error"),p.toString()),p}finally{o&&o()}}async subscribe(i,o,p){return o==="datachannel"?this._subscribeDataChannel(i,p):this._subscribe(i,o)}async _subscribeDataChannel(i,o){var p;if(b_(o,"channelId",0,65535,!0),!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));if(!this._users.find(j=>j===i))throw Gi.error("[".concat(this._clientId,"] can not subscribe ").concat(i.uid,", this user is not in the channel")),new hE(_p.INVALID_REMOTE_USER,"user is not in the channel");if(!i.hasAudio&&!i.hasVideo&&i._dataChannels.length===0)throw Gi.error("[".concat(this._clientId,"] can not subscribe ").concat(i.uid,", user is not published")),new hE(_p.INVALID_REMOTE_USER,"user is not published");const g=(p=i._dataChannels)===null||p===void 0?void 0:p.find(j=>j.id===o);if(!g)throw Gi.error("[".concat(this._clientId,"] can not subscribe ").concat(i.uid," with mediaType datachannel, remote datachannel is not published")),new hE(_p.REMOTE_USER_IS_NOT_PUBLISHED);const b=await this._subscribeMutex.lock();Gi.info("[".concat(this._clientId,"] subscribe user ").concat(i.uid,", mediaType: datachannel"));try{const j=await this._p2pChannel.subscribeDataChannel(i,[g]);if(j&&VE(j).call(j,g.id))try{var A;if(!g._originDataChannelId)throw Gi.error("[".concat(this._clientId,"] can not subscribe ").concat(i.uid," with mediaType datachannel, cannot get RTCDatachannel")),new hE(_p.REMOTE_USER_IS_NOT_PUBLISHED);const H={id:g.id,datachannelId:g._originDataChannelId,ordered:g.ordered,maxRetransmits:g.maxRetransmits,metadata:(A=g.metadata)!==null&&A!==void 0?A:""};await this._gateway.subscribeDataChannel(i.uid,H,!0)}catch(H){if((H==null?void 0:H.code)!==_p.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(i,[g]),H;await this._p2pChannel.unsubscribeDataChannel(i,[g]),this._p2pChannel.setPendingRemoteDataChannel(i,g.id)}return await g._waitTillOpen(),Gi.info("[".concat(this._clientId,"] subscribe success user ").concat(i.uid,", mediaType: datachannel")),g}finally{b()}}async _p2pSubscribe(i,o,p){if(d0(o,"mediaType",["audio","video"]),!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"Can't subscribe stream, not joined");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(A=>A===i)){const A=new hE(_p.INVALID_REMOTE_USER,"user is not in the channel");throw Gi.error("[".concat(this._clientId,"] can not subscribe ").concat(i.uid,", this user is not in the channel")),A}if(!i.hasAudio&&!i.hasVideo){const A=new hE(_p.INVALID_REMOTE_USER,"user is not published");throw Gi.error("[".concat(this._clientId,"] can not subscribe ").concat(i.uid,", user is not published")),A}if(!p&&(o==="audio"&&!i.hasAudio||o==="video"&&!i.hasVideo)){const A=new hE(_p.REMOTE_USER_IS_NOT_PUBLISHED);throw Gi.error("[".concat(this._clientId,"] can not subscribe ").concat(i.uid," with mediaType ").concat(o,", remote track is not published")),A}const g=await this._subscribeMutex.lock();Gi.info("[".concat(this._clientId,"] subscribe user ").concat(i.uid,", mediaType: ").concat(o));const b=o==="audio"?TE.LocalAudioTrack:this._joinInfo.defaultVideoStream===LN.LOW_STREAM?TE.LocalVideoLowTrack:TE.LocalVideoTrack;try{await this._p2pChannel.hasRemoteMediaWithLock(i,o)?await this._p2pChannel.unmuteRemote(i,o):(this.store.subscribe(i.uid,o,Date.now()),this._p2pChannel instanceof V_&&await this._gateway.sendExtensionMessage(w_.SUBSCRIBE,{trackType:b})),Gi.info("[".concat(this._clientId,"] subscribe success user ").concat(i.uid,", mediaType: ").concat(o)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(i.uid,this._defaultStreamFallbackType).catch(j=>{Gi.warning("[".concat(this._clientId,"] auto set fallback failed"),j)});const A=o==="audio"?i._audioTrack:i._videoTrack;if(!A)throw new hE(_p.UNEXPECTED_ERROR,"can not find remote track in user object");return A}catch(A){throw Gi.error("[".concat(this._clientId,"] subscribe user ").concat(i.uid," error"),A),A}finally{g()}}async _subscribe(i,o,p){if(this._p2pChannel instanceof V_)return this._p2pSubscribe(i,o);if(d0(o,"mediaType",["audio","video"]),!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"Can't subscribe stream, not joined");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(z=>z===i)){const z=new hE(_p.INVALID_REMOTE_USER,"user is not in the channel");throw Gi.error("[".concat(this._clientId,"] can not subscribe ").concat(i.uid,", this user is not in the channel")),z}if(!i.hasAudio&&!i.hasVideo){const z=new hE(_p.INVALID_REMOTE_USER,"user is not published");throw Gi.error("[".concat(this._clientId,"] can not subscribe ").concat(i.uid,", user is not published")),z}if(!(p||(o!=="audio"||i.hasAudio&&i._audioSSRC!==void 0)&&(o!=="video"||i.hasVideo&&i._videoSSRC!==void 0))){const z=new hE(_p.REMOTE_USER_IS_NOT_PUBLISHED);throw Gi.error("[".concat(this._clientId,"] can not subscribe ").concat(i.uid," with mediaType ").concat(o,", remote track is not published")),z}let g=o==="audio"?i._audioSSRC:i._videoSSRC,b=o==="audio"?i._audioOrtc:i._videoOrtc,A=o==="video"?i._rtxSsrcId:void 0,j={stream_type:o==="audio"?ME.AUDIO:ME.VIDEO,ssrcId:g};const H=await this._subscribeMutex.lock();Gi.info("[".concat(this._clientId,"] subscribe user ").concat(i.uid,", mediaType: ").concat(o));try{if(await this._p2pChannel.hasRemoteMediaWithLock(i,o))await this._p2pChannel.unmuteRemote(i,o);else try{const $=o==="audio"?i._audioSSRC:i._videoSSRC;$!==void 0&&$!==g&&(g=$,b=o==="audio"?i._audioOrtc:i._videoOrtc,A=o==="video"?i._rtxSsrcId:void 0,j={stream_type:o==="audio"?ME.AUDIO:ME.VIDEO,ssrcId:g}),k0.markSubscribeStart(this.store.clientId,g),this.store.subscribe(i.uid,o,Date.now()),await this._p2pChannel.subscribe(i,o,g,A,b);try{await this._gateway.subscribe(i.uid,j,!0)}catch(Vt){if((Vt==null?void 0:Vt.code)!==_p.WS_ABORT)throw await this._p2pChannel.unsubscribe(i,o),Vt;await this._p2pChannel.unsubscribe(i,o,!0),this._p2pChannel.setPendingRemoteMedia(i,o)}this.store.subscribe(i.uid,o,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,i,o)}catch($){throw this._p2pChannel.reportSubscribeEvent(!1,$==null?void 0:$.code,i,o),$}Gi.info("[".concat(this._clientId,"] subscribe success user ").concat(i.uid,", mediaType: ").concat(o)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(i.uid,this._defaultStreamFallbackType).catch($=>{Gi.warning("[".concat(this._clientId,"] auto set fallback failed"),$)});const z=o==="audio"?i._audioTrack:i._videoTrack;if(!z)throw new hE(_p.UNEXPECTED_ERROR,"can not find remote track in user object");return z}catch(z){throw Gi.error("[".concat(this._clientId,"] subscribe user ").concat(i.uid," error"),z),z}finally{H()}}async massSubscribe(i){if(KT(i,"subscribeList"),!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"Can't subscribe stream, not joined");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const o=Date.now(),p=new Map,g=await this._subscribeMutex.lock();Gi.info("[".concat(this._clientId,"]start massSubscribe user ").concat(i.map(H=>{let{user:z,mediaType:$}=H;return"user: ".concat(z==null?void 0:z.uid,", mediaType: ").concat($)}).join("; ")));const b=(i=[...i]).map(H=>{let{user:z,mediaType:$}=H;return{user:z,mediaType:$}}),A=await this._p2pChannel.globalLock();try{var j;for(let z=i.length-1;z>=0;z--){const $=i[z],{user:Vt,mediaType:_r}=$;if(d0(_r,"mediaType",["audio","video"]),!Vt){const _u=new hE(_p.INVALID_PARAMS,"user property does not exist in subscribeList item");throw Gi.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),_u}if(!this._users.find(_u=>_u===Vt)){const _u=new hE(_p.INVALID_REMOTE_USER,"user is not in the channel");Gi.error("[".concat(this._clientId,"] can not massSubscribe ").concat(Vt.uid,", this user is not in the channel")),b[z].error=_u,i.splice(z,1);continue}if(_r==="audio"&&(!Vt.hasAudio||Vt._audioSSRC===void 0)||_r==="video"&&(!Vt.hasVideo||Vt._videoSSRC===void 0)){const _u=new hE(_p.REMOTE_USER_IS_NOT_PUBLISHED);Gi.error("[".concat(this._clientId,"] can not subscribe ").concat(Vt.uid," with mediaType ").concat(_r,", remote user is not published")),b[z].error=_u,i.splice(z,1);continue}const Fi=n0.Video|n0.LwoVideo,_l=p.get(Vt);if(_l){if(_r==="video"?_l&Fi:_l&n0.Audio){i.splice(z,1),Gi.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(Vt.uid,", mediaType:").concat(_r," twice"));continue}p.set(Vt,_l|(_r==="video"?Fi:n0.Audio))}else p.set(Vt,_r==="video"?Fi:n0.Audio)}for(let z=i.length-1;z>=0;z--){const $=i[z],{user:Vt,mediaType:_r}=$,Fi=n0.Video|n0.LwoVideo;if(this._p2pChannel.hasRemoteMedia(Vt,_r)){await this._p2pChannel.unmuteRemoteNoLock(Vt,_r);const _l=p.get(Vt);p.set(Vt,_r==="video"?_l^Fi:_l^n0.Audio),i.splice(z,1)}}this.store.massSubscribe(i.map(z=>({userId:z.user.uid,type:z.mediaType})),o);const H=_C(j=Array.from(p.entries())).call(j,(z,$)=>{let[Vt,_r]=$;if(_r===0)return z;const Fi={stream_id:Vt.uid,stream_type:_r};return _r&n0.Audio&&(Fi.audio_ssrc=Vt._audioSSRC),_r&n0.Video&&(Fi.video_ssrc=Vt._videoSSRC),z.push(Fi),z},[]);try{i.length>0&&await this._p2pChannel.massSubscribeNoLock(i.map($=>{let{user:Vt,mediaType:_r}=$;return{user:Vt,mediaType:_r,ssrcId:_r===ME.VIDEO?Vt._videoSSRC:Vt._audioSSRC,rtxSsrcId:_r===ME.VIDEO?Vt._rtxSsrcId:void 0}}));const z=new Map;if(H.length>0){const $=await this._gateway.subscribeAll(H,!0);(($==null?void 0:$.users)||[]).forEach(Vt=>{let{stream_id:_r,video_error_code:Fi,audio_error_code:_l,error_code:_u}=Vt;(Fi||_l||_u)&&z.set(_r,{video_error_code:Fi,audio_error_code:_l,error_code:_u})})}if(Array.from(z.entries()).length>0){const $=Array.from(z.entries()).map(Vt=>{let _r,[Fi,_l]=Vt;return _l.error_code||_l.video_error_code&&_l.audio_error_code?_r=void 0:_l.video_error_code?_r=ME.VIDEO:_l.audio_error_code&&(_r=ME.AUDIO),{user:this.remoteUsers.find(_u=>_u.uid===Fi),mediaType:_r}});await this._p2pChannel.massUnsubscribeNoLock($)}for(const $ of b){const Vt=z.get($.user.uid);if(Vt){const _r=Vt.error_code||$.mediaType==="audio"&&Vt.audio_error_code||$.mediaType==="video"&&Vt.video_error_code;if(_r){const Fi=iI(_r);Gi.error("user:".concat($.user.uid," mediaType:").concat($.mediaType," has massSubscribe error ").concat(Fi.desc)),$.error=new hE(_p.SUBSCRIBE_FAILED,"code ".concat(_r,": ").concat(Fi.desc))}}$.error||($.mediaType==="video"?$.track=$.user.videoTrack:$.track=$.user.audioTrack)}return this.store.massSubscribe(b.filter($=>!$.error).map($=>({userId:$.user.uid,type:$.mediaType})),void 0,Date.now()),b.forEach($=>{var Vt;jE.subscribe(this.store.sessionId,{succ:!!$.error,ec:((Vt=$.error)===null||Vt===void 0?void 0:Vt.code)||null,video:$.mediaType===ME.VIDEO,audio:$.mediaType===ME.AUDIO,peerid:$.user.uid,subscribeRequestid:$.mediaType===ME.VIDEO?$.user._videoSSRC:$.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-o)},!0)}),Gi.info("[".concat(this._clientId,"] massSubscribe success ").concat(i.map($=>{let{user:Vt,mediaType:_r}=$;return"user: ".concat(Vt==null?void 0:Vt.uid,", mediaType: ").concat(_r)}).join("; "))),b}catch(z){throw await this._p2pChannel.massUnsubscribeNoLock(i),z}}finally{A(),g()}}async unsubscribe(i,o,p){if(o||this.store.useP2P){if(o==="datachannel")return this._unsubscribeDataChannel(i,p)}else await this._unsubscribeDataChannel(i,p);if(o&&d0(o,"mediaType",["audio","video"]),!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");if(!this._users.find(b=>b===i)){const b=new hE(_p.INVALID_REMOTE_USER,"user is not in the channel");throw Gi.error("[".concat(this._clientId,"] can not unsubscribe ").concat(i.uid,", user is not in the channel")),b}Gi.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(i.uid,", mediaType: ").concat(o));const g=await this._subscribeMutex.lock();try{if(this._p2pChannel instanceof V_)await this._gateway.sendExtensionMessage(w_.UNSUBSCRIBE,{mediaType:o});else{const b=await this._p2pChannel.unsubscribe(i,o);b&&await this._gateway.unsubscribe(b,i.uid),Gi.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(i.uid,", mediaType: ").concat(o))}}catch(b){if(b.code===_p.DISCONNECT_P2P)return void Gi.warning("disconnecting p2p, abort unsubscribe request.");throw Gi.error("[".concat(this._clientId,"] unsubscribe user ").concat(i.uid," error"),b.toString()),b}finally{g()}}async _unsubscribeDataChannel(i,o){if(o&&b_(o,"id",0,65535,!0),!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");if(!this._users.find(g=>g===i)){const g=new hE(_p.INVALID_REMOTE_USER,"user is not in the channel");throw Gi.error("[".concat(this._clientId,"] can not unsubscribe ").concat(i.uid,", user is not in the channel")),g}let p;if(typeof o=="number"){const g=i._dataChannels.find(b=>b.id===o);g&&(p=[g])}else p=i._dataChannels;if(p===void 0){const g=new hE(_p.REMOTE_USER_IS_NOT_PUBLISHED);throw Gi.error("[".concat(this._clientId,"] can not unsubscribe ").concat(i.uid," with channelId ").concat(o,", remote datachannel is not published")),g}Gi.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(i.uid,", mediaType: datachannel, ids: ").concat(p.map(g=>g.id)));try{const g=await this._p2pChannel.unsubscribeDataChannel(i,p);g&&await this._gateway.unsubscribeDataChannel(g,i.uid),Gi.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(i.uid,", mediaType: datachannel, ids: ").concat(g))}catch(g){if(g.code===_p.DISCONNECT_P2P)return void Gi.warning("disconnecting p2p, abort unsubscribe request.");throw Gi.error("[".concat(this._clientId,"] unsubscribe user ").concat(i.uid," error"),g.toString()),g}}async massUnsubscribe(i){if(KT(i,"unsubscribeList"),!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");Gi.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(i.map(p=>{let{user:g,mediaType:b}=p;return"user: ".concat(g==null?void 0:g.uid,", mediaType: ").concat(b,";")}).join())),i=[...i];const o=new Map;for(let p=i.length-1;p>=0;p--){const{user:g,mediaType:b}=i[p];if(!g){const j=new hE(_p.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw Gi.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),j}if(d0(b,"mediaType",["video","audio",void 0]),!this._users.find(j=>j===g)){Gi.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(g.uid,", user is not in the channel")),i.splice(p,1);continue}const A=n0.Video|n0.LwoVideo;if(o.has(g)){const j=o.get(g);let H;switch(b){case"video":H=j&A;break;case"audio":H=j&n0.Audio;break;default:H=j&(n0.Audio|A)}if(H){Gi.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(g.uid,",mediaType:").concat(b," twice.")),i.splice(p,1);continue}b?b==="audio"?o.set(g,j|n0.Audio):b==="video"&&o.set(g,j|A):o.set(g,j|n0.Audio|A)}else b?b==="audio"?o.set(g,n0.Audio):b==="video"&&o.set(g,A):o.set(g,n0.Audio|A)}try{const p=await this._p2pChannel.massUnsubscribe(i);p&&await this._gateway.massUnsubscribe(p),Gi.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(i.map(g=>{let{user:b,mediaType:A}=g;return"user: ".concat(b==null?void 0:b.uid,", mediaType: ").concat(A,";")}).join()))}catch(p){if(p.code===_p.DISCONNECT_P2P)return void Gi.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw Gi.error("[".concat(this._clientId,"] massUnsubscribe error"),p.toString()),p}}async setLowStreamParameter(i){(function(p){if(!p)throw new yE(_p.INVALID_PARAMS);M_(p.width)||UL(p.width,"streamParameter.width"),M_(p.height)||UL(p.height,"streamParameter.height"),M_(p.framerate)||UL(p.framerate,"streamParameter.framerate"),M_(p.bitrate)||b_(p.bitrate,"streamParameter.bitrate")})(i),(!i.width&&i.height||i.width&&!i.height)&&Gi.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),Gi.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(i));const o=this._configDistribute.getLowStreamConfigDistribute();if(o&&o.bitrate&&i.bitrate&&o.bitrate1e3+o.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?p:0}getNtpWallTimeInMs(){return document.visibilityState==="visible"&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(i,o){if(O0(i,"proxyServer"),!o){if(this.connectionState!=="DISCONNECTED")throw new hE(_p.INVALID_OPERATION,"Set proxy server before join channel");if(this._cloudProxyServerMode!=="disabled"||this._useLocalAccessPoint)throw new hE(_p.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=i,jE.setProxyServer(this._proxyServer),Gi.setProxyServer(this._proxyServer),Gi.info("[".concat(this._clientId,"] Set proxy server ").concat(o?"by initialize call":""," success."))}setTurnServer(i,o){if(Array.isArray(i)||(i=[i]),!o){if(this.connectionState!=="DISCONNECTED")throw new hE(_p.INVALID_OPERATION,"Set turn server before join channel");if(this._cloudProxyServerMode!=="disabled"||this._useLocalAccessPoint)throw new hE(_p.INVALID_OPERATION,"You have already set the proxy")}if(VI(i))return this._turnServer={servers:i,mode:"original-manual"},void Gi.info("[".concat(this._clientId,"] Set original turnserver ").concat(o?"by initialize call":""," success: ").concat(i.map(p=>p.urls).join(","),"."));i.forEach(p=>ZV(p)),this._turnServer={servers:i,mode:"manual"},Gi.info("[".concat(this._clientId,"] Set turnserver ").concat(o?"by initialize call":""," success."))}setLicense(i){if(this.connectionState!=="DISCONNECTED")throw new hE(_p.INVALID_OPERATION,"you should set license before join channel");if(O0(i,"license",32,32),!/^[A-Za-z\d]+$/.test(i))throw new hE(_p.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=i,Gi.info("[".concat(this._clientId,"] set license success"),i)}startProxyServer(i){if(this.connectionState!=="DISCONNECTED")throw new hE(_p.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||this._turnServer.mode==="manual"||this._useLocalAccessPoint)throw new hE(_p.INVALID_OPERATION,"You have already set the proxy");const o=[3,4,5];let p;switch(i===void 0&&(i=3),i){case 1:case 2:throw new hE(_p.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:p="proxy3";break;case 4:p="proxy4";break;case 5:p="proxy5";break;default:throw new hE(_p.INVALID_PARAMS,"proxy server mode must be ".concat(o.join("|")))}this._cloudProxyServerMode=p,this.store.cloudProxyServerMode=p,Gi.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if(this.connectionState!=="DISCONNECTED")throw new hE(_p.INVALID_OPERATION,"Stop proxy server after leave channel");jE.setProxyServer(),Gi.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",Gi.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode),this._proxyServer=void 0,this._turnServer={mode:"auto",servers:[]}}setLocalAccessPointsV2(i){if(!i.accessPoints)throw new hE(_p.INVALID_PARAMS,"accessPoints is required.");KT(i.accessPoints.serverList,"accessPoints.serverList"),O0(i.accessPoints.domain,"accessPoints.domain");const o=(Fi,_l)=>{b_(Fi,_l,0,65535,!0)};let p=443;if(i.accessPoints.port&&(o(i.accessPoints.port,"accessPoints.port"),p=i.accessPoints.port),this._proxyServer||this._cloudProxyServerMode!=="disabled")throw new hE(_p.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");nE("CLOSE_AFB_FOR_LOCAL_AP")&&(y_("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),y_("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const g=/^((\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])$/,b=i.accessPoints.domain,A=i.accessPoints.serverList.map(Fi=>g.test(Fi)?"".concat(Fi.replace(/\./g,"-"),".").concat(b):Fi),j=A.map(Fi=>"".concat(Fi,":").concat(p));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,y_("WEBCS_DOMAIN",j),y_("WEBCS_DOMAIN_BACKUP_LIST",j),y_("GATEWAY_DOMAINS",[b]),i.report&&i.report.hostname&&Array.isArray(i.report.hostname)&&i.report.hostname.length?(KT(i.report.hostname,"report.hostname"),y_("EVENT_REPORT_DOMAIN",i.report.hostname[0]),y_("EVENT_REPORT_BACKUP_DOMAIN",i.report.hostname[1]||i.report.hostname[0])):(y_("EVENT_REPORT_DOMAIN",A[0]),y_("EVENT_REPORT_BACKUP_DOMAIN",A[1]||A[0]));let H=6443;i.report&&i.report.port&&(o(i.report.port,"report.port"),H=i.report.port),y_("STATS_COLLECTOR_PORT",H),i.report?y_("ENABLE_EVENT_REPORT",!0):y_("ENABLE_EVENT_REPORT",!1);let z="";i.log&&i.log.hostname&&Array.isArray(i.log.hostname)&&i.log.hostname.length?(KT(i.log.hostname,"log.hostname"),z=i.log.hostname[0]):z=A[0];let $=6444;i.log&&i.log.port&&(o(i.log.port,"log.port"),$=i.log.port),y_("LOG_UPLOAD_SERVER","".concat(z,":").concat($));let Vt=[];i.cds&&i.cds.hostname&&Array.isArray(i.cds.hostname)&&i.cds.hostname.length?(KT(i.cds.hostname,"cds.hostname"),Vt=i.cds.hostname):Vt=A;let _r=443;i.cds&&i.cds.port&&(o(i.cds.port,"cds.port"),_r=i.cds.port),y_("CDS_AP",Vt.map(Fi=>"".concat(Fi,":").concat(_r))),i.cds?y_("ENABLE_CONFIG_DISTRIBUTE",!0):y_("ENABLE_CONFIG_DISTRIBUTE",!1),Gi.info("set local access point v2 success")}setLocalAccessPoints(i,o){if(KT(i,"serverList"),O0(o,"domain"),this._proxyServer||this._cloudProxyServerMode!=="disabled")throw new hE(_p.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");const p=/^(\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])$/;i=i.map(g=>p.test(g)?"".concat(g.replace(/\./g,"-"),".").concat(o):g),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,y_("WEBCS_DOMAIN",i),y_("WEBCS_DOMAIN_BACKUP_LIST",i),y_("GATEWAY_DOMAINS",[o]),y_("EVENT_REPORT_DOMAIN",i[0]),y_("EVENT_REPORT_BACKUP_DOMAIN",i[1]||i[0]),y_("LOG_UPLOAD_SERVER","".concat(i[0],":6444")),Gi.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(i){if(d0(i,"streamType",[0,1]),this._remoteDefaultVideoStreamType=i,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(i),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(o){throw Gi.error("[".concat(this._clientId,"] set default remote video stream type error"),o.toString()),o}else Gi.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(i))}async setRemoteVideoStreamType(i,o){d0(o,"streamType",[0,1]);try{await this._gateway.setRemoteVideoStreamType(i,o),setTimeout(()=>{const p=this._users.find(g=>g.uid===i);p&&p.videoTrack&&p.videoTrack.updateMediaStreamTrackResolution()},2e3)}catch(p){throw Gi.error("[".concat(this._clientId,"] set remote video stream type error"),p.toString()),p}Gi.info("[".concat(this._clientId,"] set remote ").concat(i," video stream type to ").concat(o)),this._remoteStreamTypeCacheMap.set(i,o)}async setStreamFallbackOption(i,o){d0(o,"fallbackType",[0,1,2]);try{await this._gateway.setStreamFallbackOption(i,o)}catch(p){throw Gi.error("[".concat(this._clientId,"] set stream fallback option"),p.toString()),p}Gi.info("[".concat(this._clientId,"] set remote ").concat(i," stream fallback type to ").concat(o)),this._streamFallbackTypeCacheMap.set(i,o)}setEncryptionConfig(i,o,p){(function(b){d0(b,"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"])})(i),O0(o,"secret");const g=["aes-128-gcm2","aes-256-gcm2"];if(VE(g).call(g,i)){if(!p||!(p instanceof Uint8Array&&p.length===32))throw new hE(_p.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(p)throw new hE(_p.INVALID_PARAMS,"current encrypt mode does not need salt");new RegExp(`^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'"|{}\\[\\]])(?=.{8,})`).test(o)||Gi.warning(`The secret is not strong: + The secret must contain at least 1 lowercase alphabetical character, + The secret must contain at least 1 uppercase alphabetical character, + The secret must contain at least 1 numeric character, + The secret must contain at least one special character, + The secret must be eight characters or longer. + `),this._encryptionMode=i,this._encryptionSecret=o,p&&(this._encryptionSalt=hN(p))}async renewToken(i){if(O0(i,"token",1,2047),!this._key||!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"renewToken should not be called before user join");const o=this._key;this._key=i,this._joinInfo&&(this._joinInfo.token=i);const p=await this._renewTokenMutex.lock();try{if(nE("USE_NEW_TOKEN")){Gi.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const g=await Aet(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||$_);Gi.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:i,ticket:g})}else Gi.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:i});Gi.debug("[".concat(this._clientId,"] renewToken success"))}catch(g){throw this._key=o,this._joinInfo.token=o,Gi.error("[".concat(this._clientId,"] renewToken failed"),g.toString()),g}finally{p()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?Gi.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval(()=>{const i=this._p2pChannel.getAudioLevels();this.safeEmit(n_.VOLUME_INDICATOR,i)},nE("AUDIO_VOLUME_INDICATION_INTERVAL")||2e3)}getRTCStats(){const i=this._statsCollector.getRTCStats(),o=this._gateway.getInChannelInfo();return i.Duration=Math.round(o.duration/1e3),i}async startLiveStreaming(i,o){if(!o){if(this.codec!=="h264")throw new hE(_p.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new hE(_p.LIVE_STREAMING_INVALID_RAW_STREAM,"can not find stream to raw streaming")}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(i)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(i))throw new hE(_p.LIVE_STREAMING_TASK_CONFLICT);const p=o?o0.TRANSCODE:o0.RAW;return this._createLiveStreamingClient(p).startLiveStreamingTask(i,p)}setLiveTranscoding(i){return this._createLiveStreamingClient(o0.TRANSCODE).setTranscodingConfig(i)}async stopLiveStreaming(i){const o=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter(p=>p&&p.hasUrl(i));if(!o.length)throw new hE(_p.INVALID_PARAMS,"can not find live streaming url to stop");await pE.all(o.map(p=>p&&p.stopLiveStreamingTask(i)))}async addInjectStreamUrl(i,o){if(!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"can not addInjectStreamUrl, no joininfo");const p=this._createLiveStreamingClient(o0.INJECT);p.setInjectStreamConfig(o,0),await p.startLiveStreamingTask(i,o0.INJECT)}async removeInjectStreamUrl(){var i;const o=this._createLiveStreamingClient(o0.INJECT),p=Array.from(OT(i=o.streamingTasks).call(i)).find(g=>g.mode===o0.INJECT);if(!this._joinInfo||!p)throw new hE(_p.INVALID_OPERATION,"can remove addInjectStreamUrl, no joininfo or inject task");await o.stopLiveStreamingTask(p.url)}async startChannelMediaRelay(i){I5(i),await this._createChannelMediaRelayClient().startChannelMediaRelay(i)}async updateChannelMediaRelay(i){I5(i),await this._createChannelMediaRelayClient().updateChannelMediaRelay(i)}async stopChannelMediaRelay(){await this._createChannelMediaRelayClient().stopChannelMediaRelay(),this._statsCollector.onStatsChanged&&(this._statsCollector.onStatsChanged=void 0)}sendStreamMessage(i){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"can not send data stream, not joined");if((typeof i=="string"||i instanceof Uint8Array)&&(i={payload:i}),typeof i.payload=="string"){const p=new TextEncoder;i.payload=p.encode(i.payload)}if(new Blob([i.payload]).size>1024)throw new hE(_p.INVALID_PARAMS,"stream message out of range.");return this._gateway.signal.request(FE.DATA_STREAM,{payload:hN(i.payload),syncWithAudio:i.syncWithAudio,sendTs:Date.now()-cnt},!o)}sendMetadata(i){if(!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([i]).size>1024)throw new hE(_p.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(FE.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:hN(i)})}async sendCustomReportMessage(i){if(Array.isArray(i)||(i=[i]),i.forEach(EZ),!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"can not send custom report, not joined");await jE.sendCustomReportMessage(this._joinInfo.sid,i)}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats()}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats()}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats()}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats()}getRemoteNetworkQuality(){return this._statsCollector.getRemoteNetworkQualityStats()}async pickSVCLayer(i,o){d0(o.spatialLayer,"spatialLayer",[0,1,2,3]),d0(o.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(i,o)}catch(p){throw Gi.error("[".concat(this._clientId,"] pick SVC layer failed"),p.toString()),p}}setRTM2Flag(i){if(d0(i,"flag",[0,1]),!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"Can't setRtm2Flag, not joined");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"Can't setRtm2Flag in ".concat(this.connectionState," state"));return this._gateway.setRTM2Flag(i)}_reset(){if(Gi.debug("[".concat(this._clientId,"] reset client")),this._axiosCancelSource.cancel(),this._axiosCancelSource=aS.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId=null,this.store.sessionId=null,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._pendingPublishedUsers=[],this._users.forEach(i=>{i._audioTrack&&i._audioTrack._destroy(),i._videoTrack&&i._videoTrack._destroy(),i._dataChannels&&(i._dataChannels.forEach(o=>o._close()),i._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 E0("client-publish"),this._subscribeMutex=new E0("client-subscribe"),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._injectStreamingClient&&(this._injectStreamingClient.terminate(),this._injectStreamingClient.removeAllListeners(),this._injectStreamingClient=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(i,o){const p=i||BL();i?Gi.debug("[".concat(this._clientId,"] new Session ").concat(p)):Gi.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(p)),this._sessionId=p,this.store.sessionId=p,o?jE.sessionInit(this._sessionId,{lts:new Date().getTime(),cname:o.channel,appid:o.appId,mode:this.mode}):this._joinInfo?jE.sessionInit(this._sessionId,{lts:new Date().getTime(),cname:this._joinInfo.cname,appid:this._joinInfo.appId,mode:this.mode}):this._gateway.joinInfo&&jE.sessionInit(this._sessionId,{lts:new Date().getTime(),cname:this._gateway.joinInfo.cname,appid:this._gateway.joinInfo.appId,mode:this.mode}),this._joinInfo&&(this._joinInfo.sid=p),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=p)}async _publishHighStream(i){if(!this._joinInfo||this._uid===void 0)throw new hE(_p.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if(this._turnServer.mode==="auto"&&nE("FORCE_TURN")&&!nE("TURN_ENABLE_TCP")&&!nE("TURN_ENABLE_UDP"))throw new hE(_p.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");Gi.debug("[".concat(this._clientId,"] publish high stream"));try{if(this._p2pChannel instanceof V_){const p=await this._p2pChannel.publish(i,this._isDualStreamEnabled,this._lowStreamParameter);if(p)try{await this._gateway.sendExtensionMessage(w_.PUBLISH,p)}catch(g){throw this._p2pChannel.unpublish(i),g}}else{const p=await this._p2pChannel.publish(i,this._isDualStreamEnabled,this._lowStreamParameter),g=(await p.next()).value;if(g){var o;let b;try{b=await this._gateway.publish(this._uid,g,!0)}catch(A){if(A.code!==_p.DISCONNECT_P2P)throw p.throw(A),A}await p.next(((o=b)===null||o===void 0?void 0:o.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const b of i)b instanceof ZE&&b._encoderConfig&&this._gateway.setVideoProfile(b._encoderConfig),!b.muted&&b.enabled||await this._p2pChannel.muteLocalTrack(b)}}catch(p){if(this._p2pChannel.reportPublishEvent(!1,p==null?void 0:p.code,i),(p==null?void 0:p.code)===_p.WS_ABORT)return;throw p}}async _publishLowStream(){if(!this._joinInfo||this._uid===void 0)throw new hE(_p.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new hE(_p.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));Gi.debug("[".concat(this._clientId,"] publish low stream"));const i=this._configDistribute.getLowStreamConfigDistribute();i&&i.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&i.bitratenew Pet(this._joinInfo,this._config.websocketRetryConfig||$_,this._config.httpRetryConfig||$_),p=g=>{g.onLiveStreamError=(b,A)=>{jE.reportApiInvoke(this._sessionId,{name:e0.ON_LIVE_STREAM_ERROR,options:[b,A],tag:x_.TRACER}).onSuccess(),this.safeEmit(n_.LIVE_STREAMING_ERROR,b,A)},g.onLiveStreamWarning=(b,A)=>{jE.reportApiInvoke(this._sessionId,{name:e0.ON_LIVE_STREAM_WARNING,options:[b,A],tag:x_.TRACER}).onSuccess(),this.safeEmit(n_.LIVE_STREAMING_WARNING,b,A)},g.on(JI.REQUEST_WORKER_MANAGER_LIST,(b,A,j)=>{if(!this._joinInfo)return j(new hE(_p.INVALID_OPERATION,"can not find join info to get worker manager"));b5(b,this._joinInfo,this._axiosCancelSource.token,$_).then(A).catch(j)})};switch(i){case o0.RAW:return this._liveRawStreamingClient||(this._liveRawStreamingClient=o(),p(this._liveRawStreamingClient)),this._liveRawStreamingClient;case o0.TRANSCODE:return this._liveTranscodeStreamingClient||(this._liveTranscodeStreamingClient=o(),p(this._liveTranscodeStreamingClient)),this._liveTranscodeStreamingClient;case o0.INJECT:return this._injectStreamingClient||(this._injectStreamingClient=o(),this._injectStreamingClient.on(JI.REQUEST_WORKER_MANAGER_LIST,(g,b,A)=>{if(!this._joinInfo)return A(new hE(_p.INVALID_OPERATION,"can not find join info to get worker manager"));b5(g,this._joinInfo,this._axiosCancelSource.token,$_).then(b).catch(A)}),this._injectStreamingClient.onInjectStatusChange=(g,b,A)=>{this.safeEmit(n_.INJECT_STREAM_STATUS,g,b,A)}),this._injectStreamingClient}}_createChannelMediaRelayClient(){if(!this._joinInfo)return new hE(_p.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw();if(!this._channelMediaRelayClient){const{sendResolutionWidth:i,sendResolutionHeight:o}=this.getLocalVideoStats(),p={width:i,height:o};this._channelMediaRelayClient=new Det(this._joinInfo,this._clientId,this._config.websocketRetryConfig||$_,this._config.httpRetryConfig||$_,p),this._channelMediaRelayClient.on("state",g=>{g===Z0.RELAY_STATE_FAILURE&&this._channelMediaRelayClient&&this._channelMediaRelayClient.dispose(),this.safeEmit(n_.CHANNEL_MEDIA_RELAY_STATE,g)}),this._channelMediaRelayClient.on("event",g=>{this.safeEmit(n_.CHANNEL_MEDIA_RELAY_EVENT,g)}),this._statsCollector.onStatsChanged=(g,b)=>{var A;g==="resolution"&&((A=this._channelMediaRelayClient)===null||A===void 0||A.setVideoProfile(b))}}return this._channelMediaRelayClient}_handleUpdateDataChannel(i,o){const{added:p,deleted:g}=i,b=[];Array.isArray(p)&&p.length>0&&p.forEach(A=>{const{uid:j,stream_id:H,ordered:z,max_retrans_times:$,metadata:Vt}=A,_r=this._users.find(Fi=>Fi._uintid===j);if(!_r)return void Gi.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));if(Gi.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(j)),VE(b).call(b,_r)||b.push(_r),_r._uintid||(_r._uintid=j),_r._dataChannels.findIndex(Fi=>Fi.id===A.stream_id)===-1){const Fi={id:H,ordered:!!z,maxRetransmits:$,metadata:Vt},_l=new fet(Fi);_r._dataChannels.push(_l),Gi.info("[".concat(this._clientId,"] remote user ").concat(_r.uid," published datachannel")),o||this.safeEmit(n_.USER_PUBLISHED,_r,"datachannel",Fi)}this._p2pChannel.hasPendingRemoteDataChannel(_r,A.stream_id)&&(Gi.debug("[".concat(this._clientId,"] resubscribe datachannel for user ").concat(_r.uid," after reconnect.")),this._subscribeDataChannel(_r,A.stream_id).catch(Fi=>{Gi.error("[".concat(this._clientId,"] resubscribe datachannel error"),Fi.toString())}))}),o&&(this.safeEmit(n_.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]),Array.isArray(g)&&g.length>0&&g.forEach(A=>{const{uid:j,stream_id:H}=A,z=this._users.find(Vt=>Vt._uintid===j);if(!z)return void Gi.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const $=z._dataChannels.find(Vt=>Vt.id===A.stream_id);$&&(Gi.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(j)),this._p2pChannel.unsubscribeDataChannel(z,[$]).then(Vt=>{if(Vt)return z._dataChannels=z._dataChannels.filter(_r=>_r!==$),this._gateway.unsubscribeDataChannel(Vt,z.uid)}),Gi.info("[".concat(this._clientId,"] remote user ").concat(j," unpublished datachannel ,id:").concat($.id)),this.safeEmit(n_.USER_UNPUBLISHED,z,"datachannel",$._config))})}_handleRemoveDataChannels(i){const o=this._users.find(p=>p.uid===i.uid);if(o){if(o._dataChannels!==void 0&&o._dataChannels.length>0){Gi.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(i.uid));const p=()=>{Gi.info("[".concat(this._clientId,"] remote user ").concat(o.uid," unpublished datachannel")),o._dataChannels.forEach(g=>{this.safeEmit(n_.USER_UNPUBLISHED,o,"datachannel",g._config)})};this._p2pChannel.unsubscribeDataChannel(o,o._dataChannels).then(g=>{if(g)return this._gateway.unsubscribeDataChannel(g,o.uid)}),p()}}else Gi.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(j_.DISCONNECT_P2P,async()=>{await this._p2pChannel.disconnectForReconnect()}),this._gateway.on(j_.CONNECTION_STATE_CHANGE,(i,o,p)=>{var g;if(p===e_.FALLBACK)return;const b=()=>{this.safeEmit(n_.CONNECTION_STATE_CHANGE,i,o,p)};if(jE.reportApiInvoke(this._sessionId||((g=this._gateway.joinInfo)===null||g===void 0?void 0:g.sid)||null,{name:e0.CONNECTION_STATE_CHANGE,options:[i,o,p],tag:x_.TRACER}).onSuccess(JSON.stringify({cur:i,prev:o,reason:p})),Gi.info("[".concat(this._clientId,"] connection state change: ").concat(o," -> ").concat(i)),i==="DISCONNECTED")return this._reset(),void b();if(i==="RECONNECTING")this._users.forEach(j=>{j._trust_in_room_=!1,j._trust_audio_enabled_state_=!1,j._trust_video_enabled_state_=!1,j._trust_audio_mute_state_=!1,j._trust_video_mute_state_=!1,j._trust_audio_stream_added_state_=!1,j._trust_video_stream_added_state_=!1,j._audioSSRC=void 0,j._videoSSRC=void 0,j._videoOrtc=void 0,j._audioOrtc=void 0,j._cname=void 0,j._rtxSsrcId=void 0}),this._userOfflineTimeout&&window.clearTimeout(this._userOfflineTimeout),this._streamRemovedTimeout&&window.clearTimeout(this._streamRemovedTimeout),this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0;else if(i==="CONNECTED"){var A;this._streamFallbackTypeCacheMap.forEach((j,H)=>{this._gateway.setStreamFallbackOption(H,j).catch(z=>{Gi.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),z)})}),this._remoteStreamTypeCacheMap.forEach((j,H)=>{this._gateway.setRemoteVideoStreamType(H,j).catch(z=>{Gi.warning("[".concat(this._clientId,"] auto set remote stream type failed"),z)})}),this._remoteDefaultVideoStreamType!==void 0&&((A=this._joinInfo)===null||A===void 0?void 0:A.defaultVideoStream)===void 0&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then(()=>{Gi.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))}).catch(j=>{Gi.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(j))}),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout(()=>{this.connectionState==="CONNECTED"&&(this._userOfflineTimeout=void 0,this._users.filter(j=>!j._trust_in_room_).forEach(j=>{Gi.debug("[".concat(this._clientId,"] user offline timeout, emit user offline ").concat(j.uid)),this._handleUserOffline({uid:j.uid})}))},3e3),this._streamRemovedTimeout=window.setTimeout(()=>{this.connectionState==="CONNECTED"&&(this._streamRemovedTimeout=void 0,this._users.forEach(j=>{j._trust_audio_mute_state_||(Gi.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(j.uid)),this._handleMuteStream(j.uid,ME.AUDIO,!1)),j._trust_video_mute_state_||(Gi.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(j.uid)),this._handleMuteStream(j.uid,ME.VIDEO,!1)),j._trust_audio_enabled_state_||(Gi.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(j.uid)),this._handleSetStreamLocalEnable("audio",j.uid,!0)),j._trust_video_enabled_state_||(Gi.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(j.uid)),this._handleSetStreamLocalEnable("video",j.uid,!0)),j._trust_video_stream_added_state_||(Gi.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(j.uid)),this._handleResetAddStream(j,"video")),j._trust_audio_stream_added_state_||(Gi.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(j.uid)),this._handleResetAddStream(j,"audio")),j._video_added_||j._audio_added_||(Gi.debug("[".concat(this._clientId,"] auto dispatch stream remove ").concat(j.uid)),this._handleRemoveStream({uid:j.uid,uint_id:j._uintid}))}))},1e3))}b()}),this._gateway.on(j_.REQUEST_NEW_GATEWAY_LIST,(i,o)=>{if(!this._joinInfo)return o(new hE(_p.UNEXPECTED_ERROR,"can not recover, no join info"));g2(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||$_,this.store).then(p=>{this._joinInfo&&(this._joinInfo.apResponse=p.gatewayInfo.res,this._joinInfo.gatewayAddrs=p.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=p.gatewayInfo.uni_lbs_ip);const g=[];p.gatewayInfo.gatewayAddrs.forEach(b=>{let{address:A}=b;const[j,H]=A.split(":");this._joinInfo&&this._joinInfo.proxyServer?g.push({proxy:this._joinInfo.proxyServer,host:j,port:H}):g.push({host:j,port:H})}),i(g)}).catch(o)}),this._gateway.on(j_.NETWORK_QUALITY,i=>{this._networkQualitySensitivity==="normal"&&this.safeEmit(n_.NETWORK_QUALITY,i)}),this._gateway.on(j_.STREAM_TYPE_CHANGE,(i,o)=>{this.safeEmit(n_.STREAM_TYPE_CHANGED,i,o),jE.reportApiInvoke(this._sessionId,{name:e0.STREAM_TYPE_CHANGE,options:[i,o],tag:x_.TRACER}).onSuccess(JSON.stringify({uid:i,streamType:o}))}),this._gateway.on(j_.IS_P2P_DISCONNECTED,i=>{this._p2pChannel.isP2PDisconnected()?i(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?i(!1):i(!0)}),this._gateway.on(j_.NEED_RENEW_SESSION,()=>{this._startSession()}),this._gateway.on(j_.REQUEST_P2P_CONNECTION_PARAMS,async(i,o,p)=>{try{o(await this._p2pChannel.startP2PConnection(i))}catch(g){p(g)}}),this._gateway.on(j_.JOIN_RESPONSE,(i,o)=>{if(this.store.useP2P)return;const{dtlsParameters:p,iceParameters:g,candidates:b,rtpCapabilities:A,setup:j,cname:H}=D5(i.ortc,o);this._p2pChannel.connect(g,p,b,A,j,H)}),this._gateway.on(j_.REQUEST_DC_CONNECTION_PARAMS,i=>{i(this._p2pChannel.getEstablishParams())}),this._gateway.on(j_.RESET_SIGNAL,i=>{this._p2pChannel.resetConnection(i),this._handleGatewaySignalEvents()}),this._gateway.on(j_.DATACHANNEL_FAILBACK,()=>{this._joinGateway()}),this._gateway.on(j_.DATACHANNEL_PRECONNECT,async(i,o,p,g)=>{var b,A,j,H,z,$;await this._p2pChannel.startP2PConnection({turnServer:(b=this._joinInfo)===null||b===void 0?void 0:b.turnServer},!0);const Vt=function(_r,Fi){let _l;return Fi&&Fi.ip&&typeof Fi.port=="number"?(_l=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:Fi.ip,port:Fi.port.toString(),type:"host",extension:{}}],Gi.debug("Using remote candidate from AP ".concat(Fi.ip,":").concat(Fi.port)),Fi.ip6&&(_l.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:Fi.ip6,port:Fi.port.toString(),type:"host",extension:{}}),Gi.debug("Using IPV6 remote candidate from AP ".concat(Fi.ip6,":").concat(Fi.port)))):_l=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:_r.ip,port:_r.port.toString(),type:"host",extension:{}}],_l}(i,o);return this._p2pChannel.preConnect({iceUfrag:"".concat((A=this._joinInfo)===null||A===void 0?void 0:A.apResponse.cid,"_").concat((j=this._joinInfo)===null||j===void 0?void 0:j.apResponse.cert),icePwd:"".concat((H=this._joinInfo)===null||H===void 0?void 0:H.apResponse.cid,"_").concat((z=this._joinInfo)===null||z===void 0?void 0:z.apResponse.cert)},{fingerprints:[{hashFunction:"sha-256",fingerprint:($=nE("FINGERPRINT"))!==null&&$!==void 0?$:i.fingerprint}]},Vt,{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},"active","o/i14u9pJrxRKAsu").then(p).catch(g)})}_handleGatewaySignalEvents(){this._gateway.signal.on(JE.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(JE.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(JE.ON_ADD_AUDIO_STREAM,i=>this._handleAddAudioOrVideoStream("audio",i.uid,i.ssrcId,i.cname,i.uint_id,i.ortc)),this._gateway.signal.on(JE.ON_ADD_VIDEO_STREAM,i=>this._handleAddAudioOrVideoStream("video",i.uid,i.ssrcId,i.cname,i.uint_id,i.ortc,i.rtxSsrcId)),this._gateway.signal.on(JE.ON_REMOTE_DATASTREAM_UPDATE,i=>{this._handleUpdateDataChannel(i)}),this._gateway.signal.on(JE.ON_REMOTE_FULL_DATASTREAM_INFO,i=>{this._handleUpdateDataChannel({added:i.datastreams,deleted:[]},!0)}),this._gateway.signal.on(JE.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(JE.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(JE.MUTE_AUDIO,i=>this._handleMuteStream(i.uid,ME.AUDIO,!0)),this._gateway.signal.on(JE.UNMUTE_AUDIO,i=>this._handleMuteStream(i.uid,ME.AUDIO,!1)),this._gateway.signal.on(JE.MUTE_VIDEO,i=>this._handleMuteStream(i.uid,ME.VIDEO,!0)),this._gateway.signal.on(JE.UNMUTE_VIDEO,i=>this._handleMuteStream(i.uid,ME.VIDEO,!1)),this._gateway.signal.on(JE.RECEIVE_METADATA,i=>{const o=dN(i.metadata);this.safeEmit(n_.RECEIVE_METADATA,i.uid,o)}),this._gateway.signal.on(JE.ON_DATA_STREAM,async i=>{if(!i)return;let o=0;if(i.ordered||i.syncWithAudio){const p=this._p2pChannel.getStats(),g=this.remoteUsers.find(A=>A.uid===i.uid),b=p==null?void 0:p.audioRecv.find(A=>A.ssrc===(g==null?void 0:g._audioSSRC));o=b==null?void 0:b.jitterBufferMs}o==null&&(o=0),lnt(i,o,{id:this._clientId,onStreamMessage:typeof this.onStreamMessage=="function"?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)})}),this._gateway.signal.on(JE.ON_CRYPT_ERROR,()=>{VO(()=>{Gi.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(n_.CRYPT_ERROR)},this._sessionId)}),this._gateway.signal.on(JE.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(JE.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{Gi.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,e_.TOKEN_EXPIRE),this.safeEmit(n_.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()}),this._gateway.signal.on(JE.ON_STREAM_FALLBACK_UPDATE,i=>{Gi.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(i.stream_id,", attr: ").concat(i.stream_type)),this.safeEmit(n_.STREAM_FALLBACK,i.stream_id,i.stream_type===1?"fallback":"recover")}),this._gateway.signal.on(JE.ON_PUBLISH_STREAM,i=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:i.proxy})),Gi.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(i))))}),this._gateway.signal.on(JE.ENABLE_LOCAL_VIDEO,i=>{this._handleSetStreamLocalEnable("video",i.uid,!0)}),this._gateway.signal.on(JE.DISABLE_LOCAL_VIDEO,i=>{this._handleSetStreamLocalEnable("video",i.uid,!1)}),this._gateway.signal.on(kE.REQUEST_TIMEOUT,(i,o)=>{if(this._joinInfo)switch(i){case FE.PUBLISH:{if(!o)return;const b=o.ortc;if(b){var p,g;const A=b.some(z=>{let{stream_type:$}=z;return $===v_.Audio}),j=b.some(z=>{let{stream_type:$}=z;return $!==v_.Audio}),H=b.some(z=>{let{stream_type:$}=z;return $===v_.Screen||$===v_.ScreenLow});o.state==="offer"&&jE.publish(this._joinInfo.sid,{eventElapse:k0.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:_p.TIMEOUT,audio:A,video:j,p2pid:o.p2p_id,publishRequestid:this.store.pubId,screenshare:H,audioName:A?(p=b.find(z=>{let{stream_type:$}=z;return $===v_.Audio}))===null||p===void 0||(p=p.ssrcs[0])===null||p===void 0?void 0:p.ssrcId.toString():void 0,videoName:j?(g=b.find(z=>{let{stream_type:$}=z;return $!==v_.Audio}))===null||g===void 0||(g=g.ssrcs[0])===null||g===void 0?void 0:g.ssrcId.toString():void 0})}break}case FE.SUBSCRIBE:o&&jE.subscribe(this._joinInfo.sid,{succ:!1,ec:_p.TIMEOUT,audio:o.stream_type===ME.AUDIO,video:o.stream_type===ME.VIDEO,peerid:o.stream_id,subscribeRequestid:o.ssrcId,p2pid:this.store.p2pId,eventElapse:k0.measureFromSubscribeStart(this.store.clientId,o.ssrcId)})}}),this._gateway.signal.on(JE.ON_P2P_OK,i=>{this.uid,this._uid}),this._gateway.signal.on(JE.ON_PUBLISHED_USER_LIST,i=>{if(i==null||!i.users)return;nE("BLOCK_LOCAL_CLIENT")&&(i.users=i.users.filter(g=>!nI(g.string_id||g.stream_id,this.channelName)));const o=[],p=[];for(const g of i.users){let b=this._users.find(Vt=>Vt._uintid===g.stream_id);b?b._trust_in_room_=!0:(b=new D0(g.string_id||g.stream_id,g.stream_id),this._users.push(b),this.getListeners(n_.PUBLISHED_USER_LIST).length===0&&(Gi.debug("[".concat(this._clientId,"] user online"),g.stream_id),this.safeEmit(n_.USER_JOINED,b)));const A=n0.Audio&g.stream_type,j=(n0.Video|n0.LwoVideo)&g.stream_type,H=(65280&g.stream_type)!=0,z=A&&b.hasAudio,$=j&&b.hasVideo;j&&(b._trust_video_stream_added_state_=!0,b._video_added_=!0,b._videoSSRC=g.video_ssrc,b._rtxSsrcId=g.video_rtx),A&&(b._trust_audio_stream_added_state_=!0,b._audio_added_=!0,b._audioSSRC=g.audio_ssrc),A&&!z&&this.getListeners(n_.PUBLISHED_USER_LIST).length===0&&(Gi.info("[".concat(this._clientId,"] remote user ").concat(b.uid," published audio")),this.safeEmit(n_.USER_PUBLISHED,b,"audio")),j&&!$&&this.getListeners(n_.PUBLISHED_USER_LIST).length===0&&(Gi.info("[".concat(this._clientId,"] remote user ").concat(b.uid," published video")),this.safeEmit(n_.USER_PUBLISHED,b,"video")),(A&&!z||j&&!$||H)&&o.push(b),j&&this._p2pChannel.hasPendingRemoteMedia(b,"video")&&p.push({user:b,mediaType:"video"}),A&&this._p2pChannel.hasPendingRemoteMedia(b,"audio")&&p.push({user:b,mediaType:"audio"})}p.length>0&&(Gi.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(p.map(g=>"user: ".concat(g.user.uid,", mediaType: ").concat(g.mediaType)).join("; ")," ")),this.massSubscribe(p).catch(g=>{Gi.error("[".concat(this._clientId,"] mass resubscribe error"),g.toString())})),this.getListeners(n_.PUBLISHED_USER_LIST).length>0?nE("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=o:(Gi.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(o.map(g=>g.uid).join(", "))),this.safeEmit(n_.PUBLISHED_USER_LIST,o)):Gi.info("[".concat(this._clientId,"] client not emit user-list event case there is no user-list listener, users: ").concat(o.map(g=>g.uid).join(", ")))}),this._gateway.signal.on(JE.ON_RTP_CAPABILITY_CHANGE,i=>{const{video_codec:o}=i;this._p2pChannel instanceof S0&&this._p2pChannel.updateRemoteRTPCapabilities(o.map(p=>p.toLowerCase()).filter(p=>{var g;return VE(g=Object.keys(eI)).call(g,p)}))})}_handleP2PEvents(){this._gateway.signal.on(JE.ON_USER_OFFLINE,()=>{this._p2pChannel.disconnectForReconnect()}),this._gateway.signal.on(w_.PUBLISH,async(i,o)=>{i.forEach(p=>p.kind===ME.VIDEO?(this._handleP2PAddAudioOrVideoStream("video",o),p.isMuted?this._handleMuteStream(o,ME.VIDEO,!0):this._handleMuteStream(o,ME.VIDEO,!1)):(this._handleP2PAddAudioOrVideoStream("audio",o),p.isMuted?this._handleMuteStream(o,ME.AUDIO,!0):this._handleMuteStream(o,ME.AUDIO,!1)))}),this._gateway.signal.on(kE.P2P_START,async(i,o)=>{if(this._p2pChannel instanceof V_){var p;o(await this._p2pChannel.startP2P({turnServer:(p=this._joinInfo)===null||p===void 0?void 0:p.turnServer},i))}}),this._gateway.signal.on(kE.P2P_CONNECTION,async i=>{this._p2pChannel instanceof V_&&await this._p2pChannel.p2pConnect(i)}),this._gateway.signal.on(kE.P2P_REMOTE_CANDIDATE_UPDATE,i=>{this._p2pChannel instanceof V_&&this._p2pChannel.addRemoteCandidate(JSON.parse(i))}),this._gateway.signal.on(w_.SUBSCRIBE,async(i,o,p)=>{if(this._p2pChannel instanceof V_){const{trackType:g}=JSON.parse(i);try{await this._p2pChannel.dopublish(g),o()}catch(b){p(b)}}}),this._gateway.signal.on(w_.UNSUBSCRIBE,async(i,o,p)=>{if(this._p2pChannel instanceof V_){const{mediaType:g}=JSON.parse(i);try{await this._p2pChannel.doUnpublish(g),o()}catch(b){p(b)}}}),this._gateway.signal.on(w_.EXCHANGE_SDP,async(i,o,p)=>{if(this._p2pChannel instanceof V_){const{type:g,sdp:b}=JSON.parse(i);try{o(await this._p2pChannel.setDescription(g,b))}catch(A){p(A)}}}),this._gateway.signal.on(w_.UNPUBLISH,async(i,o,p)=>{if(this._p2pChannel instanceof V_){const{unpubMsg:g,uid:b}=i;if(g.length===1){const A=g[0].stream_type===v_.Audio?ME.AUDIO:ME.VIDEO;this._handleMuteStream(b,A,!0);const{sdp:j}=i;if(this._p2pChannel instanceof V_&&j){const H=this._users.find(z=>z.uid===b);if(!H)return Gi.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(b)),void o();this._p2pChannel.unsubscribe(H,j,A).then(z=>{z&&o(z)}).catch(p)}else o()}else this._handleRemoveStream(i,o,p)}}),this._gateway.signal.on(w_.CONTROL,async(i,o,p)=>{const{action:g,sdp:b,isMuteAll:A,uid:j}=i;switch(g){case PT.MUTE_LOCAL_VIDEO:this._handleMuteStream(j,ME.VIDEO,!0,b,o,p);break;case PT.MUTE_LOCAL_AUDIO:o(),this._handleMuteStream(j,ME.AUDIO,!0);break;case PT.UNMUTE_LOCAL_VIDEO:o(),this._handleP2PAddAudioOrVideoStream("video",j),this._handleMuteStream(j,ME.VIDEO,!1);break;case PT.UNMUTE_LOCAL_AUDIO:o(),this._handleP2PAddAudioOrVideoStream("audio",j),this._handleMuteStream(j,ME.AUDIO,!1)}A&&this._handleRemoveStream(i,o,p)}),this._gateway.signal.on(w_.DO_SUBSCRIBE,async(i,o,p)=>{if(this._p2pChannel instanceof V_){const{kind:g,sdp:b,ssrcId:A,uid:j}=i,H=this._users.find(z=>z.uid===j);if(!H)return Gi.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)")),void o();try{o(await this._p2pChannel.subscribe(H,g,b,A))}catch(z){p(z)}}}),this._gateway.signal.on(w_.DO_UNSUBSCRIBE,async(i,o,p)=>{if(this._p2pChannel instanceof V_){const{uid:g,kind:b,sdp:A}=i,j=this._users.find(H=>H.uid===g);if(!j)return Gi.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)")),void o();try{o(await this._p2pChannel.unsubscribe(j,A,b))}catch(H){p(H)}}}),this._gateway.signal.on(w_.RESTART_ICE,async(i,o,p)=>{if(this._p2pChannel instanceof V_)try{o(await this._p2pChannel.setDescription("remote",i))}catch(g){p(g)}}),this._p2pChannel.on(WE.RequestP2PRestartICE,async(i,o,p)=>{try{o(await this._gateway.sendExtensionMessage(w_.RESTART_ICE,i))}catch(g){p(g)}}),this._p2pChannel.on(WE.LocalCandidate,i=>{this._gateway.sendExtensionMessage(w_.CANDIDATE,JSON.stringify(i))}),this._p2pChannel.on(WE.RequestP2PMuteLocal,async(i,o,p)=>{try{o(await this._gateway.sendExtensionMessage(w_.CONTROL,i))}catch(g){p(g)}}),this._p2pChannel.on(WE.RequestP2PPublish,async(i,o,p)=>{try{o(await this._gateway.sendExtensionMessage(w_.DO_SUBSCRIBE,i))}catch(g){p(g)}}),this._p2pChannel.on(WE.RequestP2PUnPublish,async(i,o,p)=>{try{o(await this._gateway.sendExtensionMessage(w_.DO_UNSUBSCRIBE,i))}catch(g){p(g)}}),this._p2pChannel.on(WE.RequestP2PUnmuteRemote,async(i,o,p)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(i,this._joinInfo.stringUid||this._joinInfo.uid),o()}catch(g){g.code===_p.DISCONNECT_P2P?o():p(g)}else o()}),this._p2pChannel.on(WE.RequestP2PMuteRemote,async(i,o,p)=>{if(this._joinInfo)try{await this._gateway.muteRemote(i,this._joinInfo.stringUid||this._joinInfo.uid),o()}catch(g){g.code===_p.DISCONNECT_P2P?o():p(g)}else o()}),this._p2pChannel.on(WE.StateChange,(i,o)=>{o===u_.Connected&&this._p2pChannel.republish()})}_handleP2PChannelEvents(){this._p2pChannel.on(WE.RequestMuteLocal,async(i,o,p)=>{if(this._joinInfo)try{await this._gateway.muteLocal(i,this._joinInfo.stringUid||this._joinInfo.uid),o()}catch(g){g.code===_p.DISCONNECT_P2P?o():p(g)}else o()}),this._p2pChannel.on(WE.RequestUnmuteLocal,async(i,o,p)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(i,this._joinInfo.stringUid||this._joinInfo.uid),o()}catch(g){g.code===_p.DISCONNECT_P2P?o():p(g)}else o()}),this._p2pChannel.on(WE.RequestRePublish,(i,o,p)=>{this.publish(i,!1).then(o).catch(p)}),this._p2pChannel.on(WE.RequestRePublishDataChannel,(i,o,p)=>{pE.all(i.map(async g=>{await this._p2pChannel.publishDataChannel([g]);const b={streamId:g.id,ordered:g.ordered,maxRetransmits:g.maxRetransmits,metadata:g.metadata,channelId:g._originDataChannelId};try{await this._gateway.publishDataChannel(this._uid,b,!0)}catch(A){if(A.code!==_p.DISCONNECT_P2P)throw A}})).then(o).catch(p)}),this._p2pChannel.on(WE.RequestReSubscribe,async(i,o,p)=>{try{for(const{user:g,kind:b}of i)b===ME.VIDEO?await this.subscribe(g,"video"):await this.subscribe(g,"audio");o()}catch(g){p(g)}}),this._p2pChannel.on(WE.RequestUploadStats,(i,o)=>{this._gateway.uploadStats(i,o)}),this._p2pChannel.on(WE.MediaReconnectStart,i=>{this.safeEmit(n_.MEDIA_RECONNECT_START,i)}),this._p2pChannel.on(WE.MediaReconnectEnd,i=>{this.safeEmit(n_.MEDIA_RECONNECT_END,i)}),this._p2pChannel.on(WE.NeedSignalRTT,i=>{i(this._gateway.getSignalRTT())}),this._p2pChannel.on(WE.RequestRestartICE,async i=>{if(this._p2pChannel instanceof V_)return;const o=await this._p2pChannel.restartICE(i),p=await o.next();if(p.done)return;const g=p.value;let b;try{b=await this._gateway.restartICE({iceParameters:g})}catch(j){return void o.throw(j)}const{iceParameters:A}=function(j){const H=j.iceParameters;return{iceParameters:{iceUfrag:H.iceUfrag,icePwd:H.icePwd}}}(b);await o.next({remoteIceParameters:A})}),this._p2pChannel.on(WE.RequestReconnect,async()=>{this._gateway.reconnect()}),this._p2pChannel.on(WE.RequestReconnectPC,async()=>{var i;const{iceParameters:o,dtlsParameters:p,rtpCapabilities:g}=await this._p2pChannel.startP2PConnection({turnServer:(i=this._joinInfo)===null||i===void 0?void 0:i.turnServer}),{gatewayEstablishParams:b,gatewayAddress:A}=await this._gateway.reconnectPC({iceParameters:o,dtlsParameters:p,rtpCapabilities:g}),{dtlsParameters:j,iceParameters:H,candidates:z,rtpCapabilities:$,setup:Vt,cname:_r}=D5(b,A);await this._p2pChannel.connect(H,j,z,$,Vt,_r),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()}),this._p2pChannel.on(WE.RequestUnpublishForReconnectPC,async(i,o,p)=>{this._joinInfo&&this._uid!==void 0?(await this._gateway.unpublish(i,this._uid),o()):p()}),this._p2pChannel.on(WE.P2PLost,()=>{this.safeEmit(n_.P2P_LOST,this.store.uid)}),this._p2pChannel.on(WE.UpdateVideoEncoder,i=>{i._encoderConfig&&this._gateway.setVideoProfile(i._encoderConfig)}),this._p2pChannel.on(WE.ConnectionTypeChange,i=>{this.safeEmit(n_.IS_USING_CLOUD_PROXY,i)}),this._p2pChannel.on(WE.RequestLowStreamParameter,i=>{i(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})}),this._p2pChannel.on(WE.QueryClientConnectionState,i=>{i(this.connectionState)})}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(i){if(this.connectionState!=="CONNECTED"||!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"[".concat(this._clientId,"] Client did not join channel"));if(this._inspect)throw new hE(_p.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));if(!i)throw new hE(_p.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig is necessary"));if(!i.inspectType||!Array.isArray(i.inspectType))throw new hE(_p.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig.inspectType is necessary and is an instance of Array."));{const o=[...new Set(i.inspectType)];o.forEach(p=>{var g;if(!VE(g=["supervise","moderation"]).call(g,p))throw new hE(_p.INVALID_PARAMS,"[".concat(this._clientId,"] ").concat(p," is not a valid inspect type."))}),i.inspectType=o}if(i&&i.extraInfo&&i.extraInfo.length>1024)throw new hE(_p.INVALID_PARAMS,"[".concat(this._clientId,"] inspectConfig.extraInfo length cannot exceed 1024 bytes"));try{const o=new bP(i);this._inspect=o,this.handleVideoInspectEvents(this._inspect),await o.init({appId:this._joinInfo.appId,areaCode:"",cname:this._joinInfo.cname,sid:this._joinInfo.sid,token:this._joinInfo.token,uid:this._joinInfo.uid,cid:this._joinInfo.cid,vid:this._joinInfo.vid?Number(this._joinInfo.vid):0},$_)}catch(o){throw Array.isArray(o)?o[0]:o}}async disableContentInspect(){if(!this._inspect)throw new hE(_p.INVALID_OPERATION,"[".concat(this._clientId,"] inspectVideoContent not started"));try{this._inspect.close(),this._inspect=void 0}catch(i){throw Array.isArray(i)?i[0]:i}}async setImageModeration(i,o){if(QR(i,"enabled"),i){if(!o)throw new hE(_p.INVALID_PARAMS,"[".concat(this._clientId,"] config is necessary"));if(b_(o.interval,"interval",1e3,1/0),this.connectionState!=="CONNECTED"||!this._joinInfo)throw new hE(_p.INVALID_OPERATION,"[".concat(this._clientId,'] can not enable image moderation, not joined"'));try{if(this._moderation)return void this._moderation.updateConfig(o);const p=new x2(o);this._moderation=p,this.handleImageModerationEvents(this._moderation),await p.init({appId:this._joinInfo.appId,areaCode:"",cname:this._joinInfo.cname,sid:this._joinInfo.sid,token:this._joinInfo.token,uid:this._joinInfo.uid,cid:this._joinInfo.cid,vid:this._joinInfo.vid?Number(this._joinInfo.vid):0},$_)}catch(p){throw Array.isArray(p)?p[0]:p}}else{if(!this._moderation)throw new hE(_p.INVALID_OPERATION,"[".concat(this._clientId,"] image moderation not started"));try{this._moderation.close(),this._moderation.removeAllListeners(),this._moderation=void 0}catch(p){throw Array.isArray(p)?p[0]:p}}}handleImageModerationEvents(i){i.on(HS.CONNECTION_STATE_CHANGE,(o,p)=>{if(this.safeEmit(n_.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,o,p),o===ES.CONNECTED){if(this.connectionState!=="CONNECTED")throw this.setImageModeration(!1),new hE(_p.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");i.inspectImage()}}),i.on(HS.CLIENT_LOCAL_VIDEO_TRACK,o=>{o(this.localTracks.filter(p=>p.trackMediaType==="video")[0])})}handleVideoInspectEvents(i){i.on(a0.CONNECTION_STATE_CHANGE,(o,p)=>{if(this.safeEmit(n_.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,o,p),p===OS.CONNECTED){if(this.connectionState!=="CONNECTED")return void this.safeEmit(n_.CONTENT_INSPECT_ERROR,new hE(_p.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));i.inspectImage()}}),i.on(a0.INSPECT_RESULT,(o,p)=>{var g;if((p==null?void 0:p.code)===_p.INVALID_OPERATION&&this.connectionState==="DISCONNECTED")return Gi.debug("Stop inspect content because that has left channel"),this==null||(g=this._inspect)===null||g===void 0||g.close(),void(this._inspect=void 0);this.safeEmit(n_.CONTENT_INSPECT_RESULT,o,p)}),i.on(a0.CLIENT_LOCAL_VIDEO_TRACK,o=>{o(this.localTracks.filter(p=>p.trackMediaType==="video")[0])})}getJoinChannelServiceRecords(){return Gi.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(i){QR(i,"enabled"),y_("ENABLE_PUBLISH_AUDIO_FILTER",i),this._joinInfo&&await this._gateway.setPublishAudioFilterEnabled(i)}_handleResetAddStream(i,o){switch(o){case"audio":i._audio_added_=!1,i._trust_audio_stream_added_state_=!0;break;case"video":i._video_added_=!1,i._trust_video_stream_added_state_=!0}}}bE([HE(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",pE)],R_.prototype,"leave",null),bE([HE({argsMap:(l,i)=>{if(!Array.isArray(i)){if(!(i instanceof P0))return[i];i=[i]}return i.map(o=>o?Object(o).toString():"null")}}),kc("design:type",Function),kc("design:paramtypes",[Object,Boolean]),kc("design:returntype",pE)],R_.prototype,"publish",null),bE([HE({argsMap:(l,i)=>(i||(i=[]),i instanceof Z4?[i.getChannelId()]:(Array.isArray(i)||(i=[i]),i.map(o=>o.getTrackId())))}),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",pE)],R_.prototype,"unpublish",null),bE([HE({argsMap:(l,i,o,p)=>[i.uid,o,p]}),kc("design:type",Function),kc("design:paramtypes",[D0,String,Number]),kc("design:returntype",pE)],R_.prototype,"subscribe",null),bE([HE({argsMap:(l,i)=>i.map(o=>{let{user:p,mediaType:g}=o;return[p==null?void 0:p.uid,g]})}),kc("design:type",Function),kc("design:paramtypes",[Array]),kc("design:returntype",pE)],R_.prototype,"massSubscribe",null),bE([HE({argsMap:(l,i,o,p)=>[i.uid,o,p]}),kc("design:type",Function),kc("design:paramtypes",[D0,String,Number]),kc("design:returntype",pE)],R_.prototype,"unsubscribe",null),bE([HE({argsMap:(l,i)=>i.map(o=>{let{user:p,mediaType:g}=o;return{uid:p==null?void 0:p.uid,mediaType:g}})}),kc("design:type",Function),kc("design:paramtypes",[Array]),kc("design:returntype",pE)],R_.prototype,"massUnsubscribe",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",pE)],R_.prototype,"setLowStreamParameter",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",pE)],R_.prototype,"enableDualStream",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",pE)],R_.prototype,"disableDualStream",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[String,Object]),kc("design:returntype",pE)],R_.prototype,"setClientRole",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[String,Boolean]),kc("design:returntype",void 0)],R_.prototype,"setProxyServer",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Object,Boolean]),kc("design:returntype",void 0)],R_.prototype,"setTurnServer",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[String]),kc("design:returntype",void 0)],R_.prototype,"setLicense",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Number]),kc("design:returntype",void 0)],R_.prototype,"startProxyServer",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],R_.prototype,"stopProxyServer",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",void 0)],R_.prototype,"setLocalAccessPointsV2",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Array,String]),kc("design:returntype",void 0)],R_.prototype,"setLocalAccessPoints",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Number]),kc("design:returntype",pE)],R_.prototype,"setRemoteDefaultVideoStreamType",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Object,Number]),kc("design:returntype",pE)],R_.prototype,"setRemoteVideoStreamType",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Object,Number]),kc("design:returntype",pE)],R_.prototype,"setStreamFallbackOption",null),bE([HE({argsMap:(l,i)=>[i]}),kc("design:type",Function),kc("design:paramtypes",[String,String,Uint8Array]),kc("design:returntype",void 0)],R_.prototype,"setEncryptionConfig",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[String]),kc("design:returntype",pE)],R_.prototype,"renewToken",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",void 0)],R_.prototype,"enableAudioVolumeIndicator",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[String,Boolean]),kc("design:returntype",pE)],R_.prototype,"startLiveStreaming",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",pE)],R_.prototype,"setLiveTranscoding",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[String]),kc("design:returntype",pE)],R_.prototype,"stopLiveStreaming",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[String,Object]),kc("design:returntype",pE)],R_.prototype,"addInjectStreamUrl",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",pE)],R_.prototype,"removeInjectStreamUrl",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[uP]),kc("design:returntype",pE)],R_.prototype,"startChannelMediaRelay",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[uP]),kc("design:returntype",pE)],R_.prototype,"updateChannelMediaRelay",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",pE)],R_.prototype,"stopChannelMediaRelay",null),bE([HE({argsMap:(l,i)=>(Array.isArray(i)||(i=[i]),[JSON.stringify(i)])}),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",pE)],R_.prototype,"sendCustomReportMessage",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Object,Object]),kc("design:returntype",pE)],R_.prototype,"pickSVCLayer",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Number]),kc("design:returntype",pE)],R_.prototype,"setRTM2Flag",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Object]),kc("design:returntype",pE)],R_.prototype,"enableContentInspect",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",pE)],R_.prototype,"disableContentInspect",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Boolean,Object]),kc("design:returntype",pE)],R_.prototype,"setImageModeration",null),bE([HE({reportResult:!0}),kc("design:type",Function),kc("design:paramtypes",[]),kc("design:returntype",Array)],R_.prototype,"getJoinChannelServiceRecords",null),bE([HE(),kc("design:type",Function),kc("design:paramtypes",[Boolean]),kc("design:returntype",pE)],R_.prototype,"setPublishAudioFilterEnabled",null);class _1{constructor(i,o){_e(this,"id",0),_e(this,"element",void 0),_e(this,"peerPair",void 0),_e(this,"context",void 0),_e(this,"audioPlayerElement",void 0),_e(this,"audioTrack",void 0),_1.count+=1,this.id=_1.count,this.element=i,this.context=o}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=i=>{const o=document.createElement("audio");o.srcObject=new MediaStream([i.track]),o.play(),this.audioPlayerElement=o}}async switchSdp(){if(!this.peerPair)return;const i=async(p,g)=>{const b=g==="offer"?await p.createOffer():await p.createAnswer();return await p.setLocalDescription(b),p.iceGatheringState==="complete"?p.localDescription:new pE(A=>{p.onicegatheringstatechange=()=>{p.iceGatheringState==="complete"&&A(p.localDescription)}})},o=async(p,g)=>await p.setRemoteDescription(g);try{const p=await i(this.peerPair[0],"offer");await o(this.peerPair[1],p);const g=await i(this.peerPair[1],"answer");await o(this.peerPair[0],g)}catch(p){throw new hE(_p.LOCAL_AEC_ERROR,p.toString()).print()}}async getTracksFromMediaElement(i){if(this.audioTrack)return this.audioTrack;let o;try{i instanceof HTMLVideoElement&&(i.captureStream?i.captureStream():i.mozCaptureStream()),o=this.context.createMediaStreamDestination(),this.context.createMediaElementSource(i).connect(o)}catch(g){throw new hE(_p.LOCAL_AEC_ERROR,g.toString()).print()}if(!o)throw new hE(_p.LOCAL_AEC_ERROR,"no dest node when local aec").print();const p=o.stream.getAudioTracks()[0];return this.audioTrack=p,p}getElement(){return this.element}async startEchoCancellation(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();const i=this.element,o=await this.getTracksFromMediaElement(i);this.peerPair&&this.peerPair[0].addTrack(o),await this.switchSdp()}close(){Gi.debug("close echo cancellation unit, id is",this.id),this.audioPlayerElement&&this.audioPlayerElement.pause(),this.peerPair&&this.peerPair.forEach(i=>{i.close()}),this.peerPair=void 0,this.audioPlayerElement=void 0}}_e(_1,"count",0);const pnt=window.AudioContext||window.webkitAudioContext;class L8{constructor(){_e(this,"units",[]),_e(this,"context",void 0)}processExternalMediaAEC(i){if(!this._doesEnvironmentNeedAEC())return Gi.debug("the system does not need to process local aec"),-1;this.context||(this.context=new pnt);let o=this.units.find(p=>p&&p.getElement()===i);return o||(o=new _1(i,this.context),this.units.push(o)),o.startEchoCancellation(),Gi.debug("start processing local audio echo cancellation, id is",o.id),o.id}_doesEnvironmentNeedAEC(){return l_().name!==m_.SAFARI}}bE([HE({report:jE}),kc("design:type",Function),kc("design:paramtypes",[HTMLAudioElement]),kc("design:returntype",Number)],L8.prototype,"processExternalMediaAEC",null);const fnt=new L8;function x8(l,i){var o=Object.keys(l);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(l);i&&(p=p.filter(function(g){return Object.getOwnPropertyDescriptor(l,g).enumerable})),o.push.apply(o,p)}return o}function M8(l){for(var i=1;i1&&arguments[1]!==void 0&&arguments[1];if(!U2)return;const o=f0._cspEventHandlerPointer;if(o&&i)return void console.error(o,i);const p=g=>{if(!(g&&g.blockedURI&&(f0.onSecurityPolicyViolation||f0.getListeners(bT.SECURITY_POLICY_VIOLATION).length>0)))return;const b=g.blockedURI;nE("CSP_DETECTED_HOSTNAME_LIST").some(A=>VE(b).call(b,A))&&(f0.onSecurityPolicyViolation&&typeof f0.onSecurityPolicyViolation=="function"&&f0.onSecurityPolicyViolation(g),f0.getListeners(bT.SECURITY_POLICY_VIOLATION).length>0&&f0.safeEmit(bT.SECURITY_POLICY_VIOLATION,g))};o&&U2.removeEventListener("securitypolicyviolation",o),(i||l&&typeof l=="function"||f0.getListeners(bT.SECURITY_POLICY_VIOLATION).length>0)&&U2.addEventListener("securitypolicyviolation",p),f0._cspEventHandlerPointer=p}y_("PROCESS_ID","process-".concat(T_(8,""),"-").concat(T_(4,""),"-").concat(T_(4,""),"-").concat(T_(4,""),"-").concat(T_(12,""))),function(){const l=l_();G0.getDisplayMedia=function(i){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)}(),G0.getStreamFromExtension=l.name===m_.CHROME&&Number(l.version)>34,G0.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;const i=new RTCPeerConnection;let o=!1;try{i.addTransceiver("audio"),o=!0}catch{}return i.close(),o}(),G0.supportMinBitrate=l.name===m_.CHROME||l.name===m_.EDGE,G0.supportSetRtpSenderParameters=function(){const i=l_();return!window.RTCRtpSender||!window.RTCRtpSender.prototype.setParameters||!window.RTCRtpSender.prototype.getParameters?!1:!!dR()||!(!H0()&&!cN())||i.name===m_.FIREFOX&&Number(i.version)>=64}(),l.name===m_.SAFARI&&(Number(l.version)>=14?G0.supportDualStream=!0:G0.supportDualStream=!1),G0.webAudioMediaStreamDest=function(){const i=l_();return!(i.name===m_.SAFARI&&Number(i.version)<12)}(),G0.supportReplaceTrack=function(){return window.RTCRtpSender?typeof RTCRtpSender.prototype.replaceTrack=="function":!1}(),G0.supportWebGL=typeof WebGLRenderingContext<"u",G0.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,dR()||(G0.webAudioWithAEC=!0),G0.supportShareAudio=function(){const i=l_();return(i.os===l0.WIN_10||i.os===l0.WIN_81||i.os===l0.WIN_7||i.os===l0.LINUX||i.os===l0.MAC_OS)&&i.name===m_.CHROME&&Number(i.version)>=74}(),G0.supportDataChannel=function(){return!!(xL(76)||function(i){const o=l_();return!(o.name!==m_.FIREFOX||!o.osVersion)&&Number(o.version)>=i}(68)||function(i){const o=l_();return!(o.name!==m_.SAFARI||!o.osVersion)&&Number(o.version)>=i}(14))}(),G0.supportPCSetConfiguration=function(){const i=window.RTCPeerConnection;return!N_()&&!!i&&i.prototype.setConfiguration instanceof Function}(),G0.supportWebRTCEncodedTransform=function(){const i=l_();return i.name==="Chrome"&&Number(i.version)>=86}(),G0.supportWebRTCInsertableStream=function(){const i=l_();return(i.name===m_.CHROME||i.name===m_.EDGE)&&Number(i.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),sT(()=>{G0.supportDualStreamEncoding=function(){const i=l_();return nE("DISABLE_WEBAUDIO")?!0:i.name==="Safari"&&Number(i.version)>=14||!!(i.name==="Chrome"&&/Windows/i.test(i.os||"")&&Number(i.version)>=100&&nE("CHROME_DUAL_STREAM_USE_ENCODING"))}(),Gi.info("browser compatibility",JSON.stringify(G0),JSON.stringify(l))})}(),function(){let l;try{l=window.localStorage.getItem("websdk_ng_global_parameter")}catch(i){return void Gi.error("Error loading sdk config",i.message)}if(l)try{const i=JSON.parse(window.atob(l)),o=Date.now();Gi.debug("Loading global parameters from cache",i),Object.keys(i).forEach(p=>{if(Object.prototype.hasOwnProperty.call($0,p)){const{value:g,expires:b}=i[p];if(b&&b<=o)return;pR[p]=g,$0[p]=g}})}catch(i){Gi.error("Error loading mutableParamsCache: ".concat(l),i.message)}}(),Array.isArray(pR.AREAS)&&pR.AREAS.length>0&&h2(pR.AREAS,!0);const f0=function(l){const i=new D_,o=l,p={getListeners:i.getListeners.bind(i),on:(g,b)=>(function(A,j){A===bT.SECURITY_POLICY_VIOLATION&&U8(j,!0)}(g,b),i.on.bind(i)(g,b)),addListener:i.addListener.bind(i),once:i.once.bind(i),off:i.off.bind(i),removeAllListeners:i.removeAllListeners.bind(i),emit:i.emit.bind(i),safeEmit:i.safeEmit.bind(i)};return M8(M8({},o),p)}({__TRACK_LIST__:QI,VERSION:qS,BUILD:uM,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:(l,i,o)=>{Gi.debug("setParameter key:".concat(l,", value:").concat(JSON.stringify(i))),y_(l,i,o)},getParameter:nE,getSupportedCodec:async function(){let l={audio:[],video:[]};try{let i=new RTCPeerConnection;i.addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"});const o=(await i.createOffer()).sdp;if(!o)return l;i.close(),i=null,l=function(p){const g={video:[],audio:[]};return p.match(/ VP8/i)&&g.video.push("VP8"),p.match(/ VP9/i)&&g.video.push("VP9"),p.match(/ AV1/i)&&g.video.push("AV1"),p.match(/ H264/i)&&g.video.push("H264"),p.match(/ H265/i)&&g.video.push("H265"),p.match(/ opus/i)&&g.audio.push("OPUS"),p.match(/ PCMU/i)&&g.audio.push("PCMU"),p.match(/ PCMA/i)&&g.audio.push("PCMA"),p.match(/ G722/i)&&g.audio.push("G722"),g}(o)}catch(i){throw new hE(_p.CREATE_OFFER_FAILED,i.toString&&i.toString()).print()}return l},checkSystemRequirements:function(){const l=jE.reportApiInvoke(null,{name:e0.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:x_.TRACER});let i=!1;try{const b=window.RTCPeerConnection,A=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,j=window.WebSocket;i=!!(b&&A&&j)}catch(b){return Gi.error("check system requirement failed: ",b),!1}let o=!1;const p=l_();p.name===m_.CHROME&&Number(p.version)>=58&&(!b$()||y$())&&(o=!0),p.name===m_.FIREFOX&&Number(p.version)>=56&&(o=!0),p.name===m_.OPERA&&Number(p.version)>=45&&(o=!0),p.name===m_.SAFARI&&Number(p.version)>=11&&(o=!0),(WV()||l_().name===m_.QQ)&&(o=!0),Gi.debug("checkSystemRequirements, api:",i,"browser",o);const g=i&&o;return l.onSuccess(g),g},getDevices:function(l){return DS.enumerateDevices(!0,!0,l)},getMicrophones:function(l){return DS.getRecordingDevices(l)},getCameras:function(l){return DS.getCamerasDevices(l)},getElectronScreenSources:B6,getPlaybackDevices:function(l){return DS.getSpeakers(l)},createClient:function(){let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const i=jE.reportApiInvoke(null,{name:e0.CREATE_CLIENT,options:[l],tag:x_.TRACER});try{(function(o){d0(o.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),d0(o.mode,"config.mode",["rtc","live"]),o.audioCodec!==void 0&&d0(o.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),o.proxyServer!==void 0&&O0(o.proxyServer,"config.proxyServer",1,1e4),o.turnServer!==void 0&&ZV(o.turnServer),o.httpRetryConfig!==void 0&&$V(o.httpRetryConfig),o.websocketRetryConfig!==void 0&&$V(o.websocketRetryConfig)})(l)}catch(o){throw i.onError(o),o}return hnt()||(l.codec==="vp9"&&(l.codec="vp8",Gi.debug("browser not support vp9, force use vp8")),y_("UNSUPPORTED_VIDEO_CODEC",["vp9"])),l.audioCodec===void 0&&(l.audioCodec="opus"),i.onSuccess(),new R_(v1(v1({forceWaitGatewayResponse:!0},l),{},{role:l.mode==="rtc"?"host":l.role||"audience"}))},createCameraVideoTrack:async function(){let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const i=jE.reportApiInvoke(null,{tag:x_.TRACER,name:e0.CREATE_CAM_VIDEO_TRACK,options:[BN({},l)]}),o=VN(l),p=T_(8,"track-cam-");let g=null;const b=l.encoderConfig==="720p_auto";Gi.info("start create camera video track with config",JSON.stringify(l),"trackId",p);try{g=(await kS({video:o},p)).getVideoTracks()[0]||null}catch(j){throw i.onError(j),j}if(!g){const j=new yE(_p.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(j),j.throw(Gi)}l.optimizationMode&&FM(p,g,l,kT(l.encoderConfig));const A=new SR(g,l,o,l.scalabiltyMode?kN(l.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},l.optimizationMode,p);return b&&A.startMonitorStats(),i.onSuccess(A.getTrackId()),Gi.info("create camera video success, trackId:",p),A},createCustomVideoTrack:function(l){const i=jE.reportApiInvoke(null,{tag:x_.TRACER,name:e0.CREATE_CUSTOM_VIDEO_TRACK,options:[l]}),o=new ZE(l.mediaStreamTrack,{width:l.width,height:l.height,frameRate:l.frameRate,bitrateMax:l.bitrateMax,bitrateMin:l.bitrateMin},l.scalabiltyMode?kN(l.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},l.optimizationMode,T_(8,"track-cus-"),[A_.CUSTOM_TRACK]);return i.onSuccess(o.getTrackId()),Gi.info("create custom video track success with config",l,"trackId",o.getTrackId()),o},createScreenVideoTrack:async function(){let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"disable";const o=jE.reportApiInvoke(null,{tag:x_.TRACER,name:e0.CREATE_SCREEN_VIDEO_TRACK,options:[BN({},l),i]}),p=l.encoderConfig==="720p_auto";l.encoderConfig?typeof l.encoderConfig=="string"||l.encoderConfig.width&&l.encoderConfig.height||(l.encoderConfig.width={max:1920},l.encoderConfig.height={max:1080}):l.encoderConfig="1080p_2";const g=function(Vt){const _r={};Vt.screenSourceType&&(_r.mediaSource=Vt.screenSourceType),Vt.extensionId&&LL()&&(_r.extensionId=Vt.extensionId);const{displaySurface:Fi,selfBrowserSurface:_l,surfaceSwitching:_u,systemAudio:_h}=Vt;(xL(107)||jV(107)||VV(93))&&(Fi&&(d0(Fi,"displaySurface",["browser","window","monitor"]),_r.displaySurface=Fi),_l?(d0(_l,"selfBrowserSurface",["exclude","include"]),_r.selfBrowserSurface=_l):_r.selfBrowserSurface="include",_u&&(d0(_u,"surfaceSwitching",["exclude","include"]),_r.surfaceSwitching=_u)),(xL(105)||jV(105)||VV(91))&&_h&&(d0(_h,"systemAudio",["exclude","include"]),_r.systemAudio=_h),Vt.electronScreenSourceId&&(_r.sourceId=Vt.electronScreenSourceId);const _g=Vt.encoderConfig?TM(Vt.encoderConfig):null;return _r.mandatory={chromeMediaSource:"desktop",maxWidth:_g?_g.width:void 0,maxHeight:_g?_g.height:void 0},_g&&(_g.frameRate&&(typeof _g.frameRate=="number"?(_r.mandatory.maxFrameRate=_g.frameRate,_r.mandatory.minFrameRate=_g.frameRate):(_r.mandatory.maxFrameRate=_g.frameRate.max||_g.frameRate.ideal||_g.frameRate.exact||void 0,_r.mandatory.minFrameRate=_g.frameRate.min||_g.frameRate.ideal||_g.frameRate.exact||void 0),_r.frameRate=_g.frameRate),_g.width&&(_r.width=_g.width),_g.height&&(_r.height=_g.height)),_r}(l),b=T_(8,"track-scr-v-");let A=null,j=null;const H=I_();if(!H.supportShareAudio&&i==="enable"){const Vt=new yE(_p.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return o.onError(Vt),Vt.throw(Gi)}Gi.info("start create screen video track with config",l,"withAudio",i,"trackId",b);try{const Vt=await kS({screen:g,screenAudio:i==="auto"?H.supportShareAudio:i==="enable"},b);A=Vt.getVideoTracks()[0]||null,j=Vt.getAudioTracks()[0]||null}catch(Vt){throw o.onError(Vt),Vt}if(!A){const Vt=new yE(_p.UNEXPECTED_ERROR,"can not find track in media stream");return o.onError(Vt),Vt.throw(Gi)}if(!j&&i==="enable"){A&&A.stop();const Vt=new yE(_p.SHARE_AUDIO_NOT_ALLOWED);return o.onError(Vt),Vt.throw(Gi)}l.optimizationMode||(l.optimizationMode="detail"),l.optimizationMode&&(FM(b,A,l,l.encoderConfig&&TM(l.encoderConfig)||void 0),l.encoderConfig&&typeof l.encoderConfig!="string"&&(l.encoderConfig.bitrateMin=l.encoderConfig.bitrateMax));const z=new ZE(A,l.encoderConfig?TM(l.encoderConfig):{},l.scalabiltyMode?kN(l.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},l.optimizationMode,b,[A_.SCREEN_TRACK]);if(p&&z.startMonitorStats(),!j)return o.onSuccess(z.getTrackId()),Gi.info("create screen video track success","video:",z.getTrackId()),z;const $=new g_(j,void 0,T_(8,"track-scr-a-"),!1,!0);return o.onSuccess([z.getTrackId(),$.getTrackId()]),Gi.info("create screen video track success","video:",z.getTrackId(),"audio:",$.getTrackId()),[z,$]},createMicrophoneAndCameraTracks:async function(){let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const o=jE.reportApiInvoke(null,{tag:x_.TRACER,name:e0.CREATE_MIC_AND_CAM_TRACKS,options:[l,i]}),p=i.encoderConfig==="720p_auto",g=VN(i),b=Z6(l),A=T_(8,"track-mic-"),j=T_(8,"track-cam-");let H=null,z=null;Gi.info("start create camera video track(".concat(j,") and microphone audio track(").concat(A,") with config, audio: ").concat(JSON.stringify(l),", video: ").concat(JSON.stringify(i)));try{const _r=await kS({audio:b,video:g},"".concat(A,"-").concat(j));H=_r.getAudioTracks()[0],z=_r.getVideoTracks()[0]}catch(_r){throw o.onError(_r),_r}if(!H||!z){const _r=new yE(_p.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(_r),_r.throw(Gi)}i.optimizationMode&&FM(j,z,i,kT(i.encoderConfig));const $=new yR(H,l,b,A),Vt=new SR(z,i,g,i.scalabiltyMode?kN(i.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},i.optimizationMode,j);return p&&Vt.startMonitorStats(),o.onSuccess([$.getTrackId(),Vt.getTrackId()]),Gi.info("create camera video track(".concat(j,") and microphone audio track(").concat(A,") success")),[$,Vt]},createMicrophoneAudioTrack:async function(){let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const i=jE.reportApiInvoke(null,{tag:x_.TRACER,name:e0.CREATE_MIC_AUDIO_TRACK,options:[l]}),o=Z6(l),p=T_(8,"track-mic-");let g=null;Gi.info("start create microphone audio track with config",JSON.stringify(l),"trackId",p);try{g=(await kS({audio:o},p)).getAudioTracks()[0]||null}catch(A){throw i.onError(A),A}if(!g){const A=new yE(_p.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(A),A.throw(Gi)}const b=new yR(g,l,o,p);return i.onSuccess(b.getTrackId()),Gi.info("create microphone audio track success, trackId:",p),b},createCustomAudioTrack:function(l){const i=jE.reportApiInvoke(null,{tag:x_.TRACER,name:e0.CREATE_CUSTOM_AUDIO_TRACK,options:[l]}),o=new g_(l.mediaStreamTrack,l.encoderConfig?DN(l.encoderConfig):{},T_(8,"track-cus-"),!1,!0);return Gi.info("create custom audio track success with config",l,"trackId",o.getTrackId()),i.onSuccess(o.getTrackId()),o},createBufferSourceAudioTrack:async function(l){var i;const{cacheOnlineFile:o,encoderConfig:p}=l;let{source:g}=l;const b={source:g instanceof AudioBuffer?"AudioBuffer":g instanceof File?(i=File.name)!==null&&i!==void 0?i:"File":g,cacheOnlineFile:o,encoderConfig:p},A=jE.reportApiInvoke(null,{tag:x_.TRACER,name:e0.CREATE_BUFFER_AUDIO_TRACK,options:[b]});if(nE("DISABLE_WEBAUDIO"))throw new yE(_p.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");const j=T_(8,"track-buf-");Gi.info("start create buffer source audio track with config",JSON.stringify(b),"trackId",j);const H=g;if(!(g instanceof AudioBuffer))try{g=await ott(g,o)}catch(Vt){return A.onError(Vt),Vt.throw(Gi)}const z=new stt(g),$=new bR(H,z,p?DN(p):{},j);return Gi.info("create buffer source audio track success, trackId:",j),A.onSuccess($.getTrackId()),$},setAppType:function(l){if(Gi.debug("setAppType: ".concat(l)),!(Number.isInteger(l)&&l>=0))throw Gi.debug("Invalid appType"),new hE(_p.INVALID_PARAMS,"invalid app type",l);y_("APP_TYPE",Math.floor(l))},setLogLevel:function(l){Gi.setLogLevel(l)},enableLogUpload:function(){nE("USE_NEW_LOG")?y_("UPLOAD_LOG",!0):Gi.enableLogUpload()},disableLogUpload:function(){nE("USE_NEW_LOG")?y_("UPLOAD_LOG",!1):Gi.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new uP},checkAudioTrackIsActive:async function(l){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;const o=jE.reportApiInvoke(null,{tag:x_.TRACER,name:e0.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[i]});if(!(l instanceof g_||l instanceof cT)){const H=new hE(_p.INVALID_TRACK,"the parameter is not a audio track");return o.onError(H),H.throw()}i&&i<1e3&&(i=1e3);const p=l instanceof g_?l.getTrackLabel():"remote_track",g=l.getVolumeLevel();let b=g,A=g;const j=Date.now();return new pE(H=>{const z=setInterval(()=>{const $=l.getVolumeLevel();b=$>b?$:b,A=$1e-4,_r=Date.now()-j;if(Vt||_r>i){clearInterval(z);const Fi=Vt,_l={duration:_r,deviceLabel:p,maxVolumeLevel:b,result:Fi};Gi.info("[track-".concat(l.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(_l))),o.onSuccess(_l),H(Fi)}},200)})},checkVideoTrackIsActive:async function(l){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;const o=jE.reportApiInvoke(null,{tag:x_.TRACER,name:e0.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[i]});if(!(l instanceof ZE||l instanceof DT)){const Vt=new hE(_p.INVALID_TRACK,"the parameter is not a video track");return o.onError(Vt),Vt.throw()}i&&i<1e3&&(i=1e3);const p=l instanceof ZE?l.getTrackLabel():"remote_track",g=l.getMediaStreamTrack(!0),b=document.createElement("video");b.style.width="1px",b.style.height="1px",b.setAttribute("muted",""),b.muted=!0,b.setAttribute("playsinline",""),b.controls=!1,(H0()||cN())&&(b.style.opacity="0.01",b.style.position="fixed",b.style.left="0",b.style.top="0",document.body.appendChild(b)),b.srcObject=new MediaStream([g]),b.play();const A=document.createElement("canvas");A.width=160,A.height=120;let j=0,H=0;try{const Vt=Date.now();j=await function(_r,Fi,_l,_u){let _h,_g=0,eE=null;return new pE((oE,SE)=>{function vE(){_g>_u&&_h&&(_h(),oE(_g));const fE=_l.getContext("2d");if(!fE){const PE=new hE(_p.UNEXPECTED_ERROR,"can not get canvas 2d context.");return Gi.error(PE.toString()),void SE(PE)}fE.drawImage(_r,0,0,160,120);const mE=fE.getImageData(0,0,_l.width,_l.height),EE=Math.floor(mE.data.length/3);if(eE){for(let PE=0;PE{_h&&(_h(),oE(_g))},Fi),_h=OM(()=>{vE()},30)})}(b,i,A,4),H=Date.now()-Vt}catch(Vt){throw o.onError(Vt),Vt}dnt===m_.SAFARI&&(b.pause(),b.remove()),b.srcObject=null;const z=j>4,$={duration:H,changedPicNum:j,deviceLabel:p,result:z};return Gi.info("[track-".concat(l.getTrackId(),"] check video track active completed. ").concat(JSON.stringify($))),o.onSuccess($),z},setArea:h2,audioElementPlayCenter:vS,processExternalMediaAEC:function(l){fnt.processExternalMediaAEC(l)},registerExtensions:function(l){l.forEach(i=>{const o=i;o.__registered__=!0,o.logger.hookLog=Gi.extLog,o.reporter.hookApiInvoke=jE.extApiInvoke,o.parameters&&Object.keys(o.parameters).forEach(p=>{o.parameters[p]=nE(p)})})},ChannelMediaRelayError:gR,ChannelMediaRelayEvent:_T,ChannelMediaRelayState:Z0,RemoteStreamFallbackType:RM,RemoteStreamType:LN,ConnectionDisconnectedReason:e_,AudienceLatencyLevelType:jL,AREAS:c_});return Object.defineProperties(f0,{onAudioAutoplayFailed:{get:()=>LS.onAudioAutoplayFailed,set:l=>{LS.onAudioAutoplayFailed=l}},onAutoplayFailed:{get:()=>LS.onAutoplayFailed,set:l=>{LS.onAutoplayFailed=l}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>f0._onSecurityPolicyViolation,set(l){f0._onSecurityPolicyViolation=l,U8(l)}},__CLIENT_LIST__:{get:()=>nE("SHOW_GLOBAL_CLIENT_LIST")?fR:[]}}),DS.on(XT.CAMERA_DEVICE_CHANGED,l=>{Gi.info("camera device changed",JSON.stringify(l)),f0.onCameraChanged&&f0.onCameraChanged(l),f0.safeEmit(bT.CAMERA_CHANGED,l)}),DS.on(XT.RECORDING_DEVICE_CHANGED,l=>{Gi.info("microphone device changed",JSON.stringify(l)),f0.onMicrophoneChanged&&f0.onMicrophoneChanged(l),f0.safeEmit(bT.MICROPHONE_CHANGED,l)}),DS.on(XT.PLAYOUT_DEVICE_CHANGED,l=>{Gi.debug("playout device changed",JSON.stringify(l)),f0.onPlaybackDeviceChanged&&f0.onPlaybackDeviceChanged(l),f0.safeEmit(bT.PLAYBACK_DEVICE_CHANGED,l)}),vS.onAutoplayFailed=()=>{Gi.info("detect audio element autoplay failed"),LS.onAudioAutoplayFailed&&LS.onAudioAutoplayFailed()},__.on("autoplay-failed",()=>{Gi.info("detect webaudio autoplay failed"),LS.onAudioAutoplayFailed&&LS.onAudioAutoplayFailed(),f0.safeEmit(bT.AUTOPLAY_FAILED)}),X_.on(YT.NETWORK_STATE_CHANGE,(l,i)=>{Gi.info("[network-indicator] network state changed, ".concat(i," => ").concat(l))}),window&&(window.__ARTC__=f0),f0})})(AgoraRTC_NProduction);var AgoraRTC_NProductionExports=AgoraRTC_NProduction.exports;const AgoraRTC__default=getDefaultExportFromCjs(AgoraRTC_NProductionExports);function _objectWithoutPropertiesLoose(e,r){if(e==null)return{};var s={},d=Object.keys(e),f,_;for(_=0;_=0)&&(s[f]=e[f]);return s}var AgoraRTCErrorCode;(function(e){e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",e.TIMEOUT="TIMEOUT",e.INVALID_PARAMS="INVALID_PARAMS",e.NOT_SUPPORTED="NOT_SUPPORTED",e.INVALID_OPERATION="INVALID_OPERATION",e.OPERATION_ABORTED="OPERATION_ABORTED",e.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",e.NETWORK_ERROR="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.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",e.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",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.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.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.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"})(AgoraRTCErrorCode||(AgoraRTCErrorCode={}));var createClient=function e(r){var s;function d(){return s||(s=AgoraRTC__default.createClient(r)),s}return function(){return d()}};function createMicrophoneAndCameraTracks(e,r){var s=function(){try{return Promise.resolve(AgoraRTC__default.createMicrophoneAndCameraTracks(e,r)).then(function(_){return d=_,d})}catch(_){return Promise.reject(_)}},d=null;return function(){var _=reactExports.useState(!1),C=_[0],P=_[1],x=reactExports.useState(null),B=x[0],_t=x[1],ue=reactExports.useRef(d);return reactExports.useEffect(function(){return ue.current===null?s().then(function(Wt){ue.current=Wt,P(!0)},function(Wt){_t(Wt)}):P(!0),function(){d=null}},[]),{ready:C,tracks:ue.current,error:B}}}var AgoraVideoPlayer=function e(r){var s=reactExports.useRef(null),d=r.videoTrack,f=r.config,_=_objectWithoutPropertiesLoose(r,["videoTrack","config"]);return reactExports.useLayoutEffect(function(){return s.current!==null&&d.play(s.current,f),function(){d.stop()}},[d]),React.createElement("div",Object.assign({},_,{ref:s}))},agoraRtmSdk={exports:{}};/* + @preserve + AgoraRTM Web SDK 1.4.3-203 - commit: v1.4.3-17-g1e27aa38 + Copyright (C) 2018-2021 Agora Lab. + This file is licensed under the AGORA, INC. SDK LICENSE AGREEMENT + A copy of this license may be found at https://www.agora.io/en/sdk-license-agreement/ +*/agoraRtmSdk.exports;(function(module,exports){(function(e,r){module.exports=r()})(commonjsGlobal,function(){function be(e,r){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(e);r&&(d=d.filter(function(f){return Object.getOwnPropertyDescriptor(e,f).enumerable})),s.push.apply(s,d)}return s}function ua(e){for(var r=1;r"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Sh(e,r,s){return(Sh=ul()?Reflect.construct:function(d,f,_){var C=[null];return C.push.apply(C,f),d=new(Function.bind.apply(d,C)),_&&df(d,_.prototype),d}).apply(null,arguments)}function ef(e){var r=typeof Map=="function"?new Map:void 0;return(ef=function(s){function d(){return Sh(s,arguments,wd(this).constructor)}if(s===null||Function.toString.call(s).indexOf("[native code]")===-1)return s;if(typeof s!="function")throw new TypeError("Super expression must either be null or a function");if(r!==void 0){if(r.has(s))return r.get(s);r.set(s,d)}return d.prototype=Object.create(s.prototype,{constructor:{value:d,enumerable:!1,writable:!0,configurable:!0}}),df(d,s)})(e)}function ff(e,r){if(e==null)return{};if(e==null)var s={};else{s={};var d,f=Object.keys(e);for(d=0;de.length)&&(r=e.length);for(var s=0,d=Array(r);sarguments.length?e:arguments[2];return va(e)===d?e[r]:(s=Fb.f(e,r))?Q(s,"value")?s.value:s.get===void 0?void 0:s.get.call(d):ha(s=Vb(e))?wl(s,r,d):void 0}function rs(e){var r=e.charCodeAt(0)<<24,s=0|ss(~r),d=0,f=0|e.length,_="";if(5>s&&f>=s){for(r=r<>>24+s,d=1;d=r?_+=xd(r):1114111>=r?_+=xd(55296+((r=r-65536|0)>>10)|0,56320+(1023&r)|0):d=0}for(;d=r){var s=0|e.charCodeAt(1);if(!(s==s&&56320<=s&&57343>=s))return xd(239,191,189);if(65535<(r=(r-55296<<10)+s-56320+65536|0))return xd(240|r>>>18,128|r>>>12&63,128|r>>>6&63,128|63&r)}return 127>=r?e:2047>=r?xd(192|r>>>6,128|63&r):xd(224|r>>>12,128|r>>>6&63,128|63&r)}function yl(){}function ea(){ea.init.call(this)}function ng(e){if(typeof e!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+X(e))}function zl(e,r,s,d){ng(s);var f=e._events;if(f===void 0)f=e._events=Object.create(null),e._eventsCount=0;else{f.newListener!==void 0&&(e.emit("newListener",r,s.listener?s.listener:s),f=e._events);var _=f[r]}return _===void 0?(f[r]=s,++e._eventsCount):(typeof _=="function"?_=f[r]=d?[s,_]:[_,s]:d?_.unshift(s):_.push(s),0<(s=e._maxListeners===void 0?ea.defaultMaxListeners:e._maxListeners)&&_.length>s&&!_.warned&&(_.warned=!0,(s=Error("Possible EventEmitter memory leak detected. "+_.length+" "+String(r)+" listeners added. Use emitter.setMaxListeners() to increase limit")).name="MaxListenersExceededWarning",s.emitter=e,s.type=r,s.count=_.length,console&&console.warn&&console.warn(s))),e}function us(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Al(e,r,s){return e={fired:!1,wrapFn:void 0,target:e,type:r,listener:s},(r=us.bind(e)).listener=s,e.wrapFn=r}function Bl(e,r,s){if((e=e._events)===void 0)return[];if((r=e[r])===void 0)return[];if(typeof r=="function")return s?[r.listener||r]:[r];if(s)for(s=Array(r.length),e=0;e>>=0)&&256>e)&&(s=Rl[e]))return s;s=ya(e,0>(0|e)?-1:0,!0),r&&(Rl[e]=s)}else{if((r=-128<=(e|=0)&&128>e)&&(s=Sl[e]))return s;s=ya(e,0>e?-1:0,!1),r&&(Sl[e]=s)}return s}function Gb(e,r){if(isNaN(e))return r?Cd:Hb;if(r){if(0>e)return Cd;if(e>=Tl)return Ul}else{if(e<=-Vl)return nb;if(e+1>=Vl)return Wl}return 0>e?Gb(-e,r).neg():ya(e%ke|0,e/ke|0,r)}function ya(e,r,s){return new xa(e,r,s)}function ci(e,r,s){if(e.length===0)throw Error("empty string");if(e==="NaN"||e==="Infinity"||e==="+Infinity"||e==="-Infinity")return Hb;if(typeof r=="number"?(s=r,r=!1):r=!!r,2>(s=s||10)||36C?(C=Gb(sg(s,C)),f=f.mul(C).add(Gb(P))):f=(f=f.mul(d)).add(Gb(P))}return f.unsigned=r,f}function Wb(e,r){return typeof e=="number"?Gb(e,r):typeof e=="string"?ci(e,r):ya(e.low,e.high,typeof r=="boolean"?r:e.unsigned)}function O(e,r){function s(){this.constructor=e}di(e,r),e.prototype=r===null?Object.create(r):(s.prototype=r.prototype,new s)}function le(e){return typeof e=="function"}function me(e){setTimeout(function(){throw e},0)}function ei(e){return e!==null&&X(e)==="object"}function Xl(e){return e.reduce(function(r,s){return r.concat(s instanceof lf?s.errors:s)},[])}function fi(e){for(;e;){var r=e.destination,s=e.isStopped;if(e.closed||s)return!1;e=r&&r instanceof ia?r:null}return!0}function Yc(e){return e}function gi(){for(var e=[],r=0;r=B.length?B[0]:B),_.complete()}]))}catch(B){fi(_)?_.error(B):console.warn(B)}}return _.subscribe(x)})}}function Ts(e){var r=this,s=e.args,d=e.subscriber,f=e.params;e=f.callbackFunc;var _=f.context,C=f.scheduler,P=f.subject;if(!P){P=f.subject=new of,f=function(){for(var x=[],B=0;B=x.length?x[0]:x,subject:P}))};try{e.apply(_,s.concat([f]))}catch(x){P.error(x)}}this.add(P.subscribe(d))}function Us(e){var r=e.subject;r.next(e.value),r.complete()}function dm(e,r,s){if(r){if(!Zc(r))return function(){for(var d=[],f=0;f=B.length?B[0]:B),x.complete())}]))}catch(B){fi(x)?x.error(B):console.warn(B)}}return x.subscribe(C)})}}function Vs(e){var r=this,s=e.params,d=e.subscriber;e=e.context;var f=s.callbackFunc,_=s.args,C=s.scheduler,P=s.subject;if(!P){P=s.subject=new of,s=function(){for(var x=[],B=0;B=x.length?x[0]:x,subject:P}))};try{f.apply(e,_.concat([s]))}catch(x){this.add(C.schedule(em,0,{err:x,subject:P}))}}this.add(P.subscribe(d))}function Ws(e){var r=e.subject;r.next(e.value),r.complete()}function em(e){e.subject.error(e.err)}function fm(e){return!!e&&typeof e.subscribe!="function"&&typeof e.then=="function"}function ji(e,r,s,d,f){if(f===void 0&&(f=new Xs(e,s,d)),!f.closed)return r instanceof Y?r.subscribe(f):pf(r)(f)}function Ys(e,r){return new Y(function(s){var d=new Oa;return d.add(r.schedule(function(){var f=e[ne]();d.add(f.subscribe({next:function(_){d.add(r.schedule(function(){return s.next(_)}))},error:function(_){d.add(r.schedule(function(){return s.error(_)}))},complete:function(){d.add(r.schedule(function(){return s.complete()}))}}))})),d})}function Zs(e,r){return new Y(function(s){var d=new Oa;return d.add(r.schedule(function(){return e.then(function(f){d.add(r.schedule(function(){s.next(f),d.add(r.schedule(function(){return s.complete()}))}))},function(f){d.add(r.schedule(function(){return s.error(f)}))})})),d})}function $s(e,r){if(!e)throw Error("Iterable cannot be null");return new Y(function(s){var d,f=new Oa;return f.add(function(){d&&typeof d.return=="function"&&d.return()}),f.add(r.schedule(function(){d=e[$c](),f.add(r.schedule(function(){if(!s.closed){try{var _=d.next(),C=_.value,P=_.done}catch(x){return void s.error(x)}P?s.complete():(s.next(C),this.schedule())}}))})),f})}function gm(e,r){if(e!=null){if(e&&typeof e[ne]=="function")return Ys(e,r);if(fm(e))return Zs(e,r);if(hm(e))return hi(e,r);if(e&&typeof e[$c]=="function"||typeof e=="string")return $s(e,r)}throw new TypeError((e!==null&&X(e)||e)+" is not observable")}function Kb(e,r){return r?gm(e,r):e instanceof Y?e:new Y(pf(e))}function ic(e,r){if(!r.closed){if(e instanceof Y)return e.subscribe(r);try{var s=pf(e)(r)}catch(d){r.error(d)}return s}}function cb(e,r,s){return s===void 0&&(s=Number.POSITIVE_INFINITY),typeof r=="function"?function(d){return d.pipe(cb(function(f,_){return Kb(e(f,_)).pipe(ba(function(C,P){return r(f,C,_,P)}))},s))}:(typeof r=="number"&&(s=r),function(d){return d.lift(new at(e,s))})}function tg(e){return e===void 0&&(e=Number.POSITIVE_INFINITY),cb(Yc,e)}function im(){for(var e=[],r=0;re)&&(e=0),r&&typeof r.schedule=="function"||(r=bd),new Y(function(s){return s.add(r.schedule(ct,e,{subscriber:s,counter:0,period:e})),s})}function ct(e){var r=e.subscriber,s=e.counter;e=e.period,r.next(s),this.schedule({subscriber:r,counter:s+1,period:e},e)}function Xb(){for(var e=[],r=0;r=e.count?d.complete():(d.next(r),d.closed||(e.index=s+1,e.start=r+1,this.schedule(e)))}function Bc(e,r,s){e===void 0&&(e=0);var d=-1;return ki(r)?d=1>Number(r)?1:Number(r):Zc(r)&&(s=r),Zc(s)||(s=bd),new Y(function(f){var _=ki(e)?e:+e-s.now();return s.schedule(it,_,{index:0,period:d,subscriber:f})})}function it(e){var r=e.index,s=e.period,d=e.subscriber;if(d.next(r),!d.closed){if(s===-1)return d.complete();e.index=r+1,this.schedule(e,s)}}function mi(){for(var e=[],r=0;r=arguments.length?0:arguments.length-1)==1?typeof(1>=arguments.length?void 0:arguments[1])=="number"?r=1>=arguments.length?void 0:arguments[1]:s=1>=arguments.length?void 0:arguments[1]:(1>=arguments.length?0:arguments.length-1)==2&&(r=1>=arguments.length?void 0:arguments[1],s=2>=arguments.length?void 0:arguments[2]);var d=r||1;return function(f){return f.pipe(xg(function(_,C){var P=s.now(),x=P-e;if((_=_.filter(function(ue){return ue.until>x})).length>=d){var B=_[_.length-1],_t=_[0].until+e*Math.floor(_.length/d);_.push({delay:B.untilf?1:0;if(P&&(f=-f),f===0)d(0<1/f?0:2147483648,_,C);else if(isNaN(f))d(2143289344,_,C);else if(34028234663852886e22>>0,_,C);else if(11754943508222875e-54>f)d((P<<31|Math.round(f/1401298464324817e-60))>>>0,_,C);else{var x=Math.floor(Math.log(f)/Math.LN2);d((P<<31|x+127<<23|8388607&Math.round(f*Math.pow(2,-x)*8388608))>>>0,_,C)}}function s(d,f,_){return _=d(f,_),d=2*(_>>31)+1,f=_>>>23&255,_&=8388607,f===255?_?NaN:1/0*d:f===0?1401298464324817e-60*d*_:d*Math.pow(2,f-150)*(_+8388608)}e.writeFloatLE=r.bind(null,Am),e.writeFloatBE=r.bind(null,Bm),e.readFloatLE=s.bind(null,Cm),e.readFloatBE=s.bind(null,Dm)}(),typeof Float64Array<"u"?function(){function r(x,B,_t){_[0]=x,B[_t]=C[0],B[_t+1]=C[1],B[_t+2]=C[2],B[_t+3]=C[3],B[_t+4]=C[4],B[_t+5]=C[5],B[_t+6]=C[6],B[_t+7]=C[7]}function s(x,B,_t){_[0]=x,B[_t]=C[7],B[_t+1]=C[6],B[_t+2]=C[5],B[_t+3]=C[4],B[_t+4]=C[3],B[_t+5]=C[2],B[_t+6]=C[1],B[_t+7]=C[0]}function d(x,B){return C[0]=x[B],C[1]=x[B+1],C[2]=x[B+2],C[3]=x[B+3],C[4]=x[B+4],C[5]=x[B+5],C[6]=x[B+6],C[7]=x[B+7],_[0]}function f(x,B){return C[7]=x[B],C[6]=x[B+1],C[5]=x[B+2],C[4]=x[B+3],C[3]=x[B+4],C[2]=x[B+5],C[1]=x[B+6],C[0]=x[B+7],_[0]}var _=new Float64Array([-0]),C=new Uint8Array(_.buffer),P=C[7]===128;e.writeDoubleLE=P?r:s,e.writeDoubleBE=P?s:r,e.readDoubleLE=P?d:f,e.readDoubleBE=P?f:d}():function(){function r(d,f,_,C,P,x){var B=0>C?1:0;if(B&&(C=-C),C===0)d(0,P,x+f),d(0<1/C?0:2147483648,P,x+_);else if(isNaN(C))d(0,P,x+f),d(2146959360,P,x+_);else if(17976931348623157e292>>0,P,x+_);else if(22250738585072014e-324>C)d((C/=5e-324)>>>0,P,x+f),d((B<<31|C/4294967296)>>>0,P,x+_);else{var _t=Math.floor(Math.log(C)/Math.LN2);_t===1024&&(_t=1023),d(4503599627370496*(C*=Math.pow(2,-_t))>>>0,P,x+f),d((B<<31|_t+1023<<20|1048576*C&1048575)>>>0,P,x+_)}}function s(d,f,_,C,P){return f=d(C,P+f),C=d(C,P+_),d=2*(C>>31)+1,f=4294967296*(1048575&C)+f,(_=C>>>20&2047)===2047?f?NaN:1/0*d:_===0?5e-324*d*f:d*Math.pow(2,_-1075)*(f+4503599627370496)}e.writeDoubleLE=r.bind(null,Am,0,4),e.writeDoubleBE=r.bind(null,Bm,4,0),e.readDoubleLE=s.bind(null,Cm,0,4),e.readDoubleBE=s.bind(null,Dm,4,0)}(),e}function Am(e,r,s){r[s]=255&e,r[s+1]=e>>>8&255,r[s+2]=e>>>16&255,r[s+3]=e>>>24}function Bm(e,r,s){r[s]=e>>>24,r[s+1]=e>>>16&255,r[s+2]=e>>>8&255,r[s+3]=255&e}function Cm(e,r){return(e[r]|e[r+1]<<8|e[r+2]<<16|e[r+3]<<24)>>>0}function Dm(e,r){return(e[r]<<24|e[r+1]<<16|e[r+2]<<8|e[r+3])>>>0}function Wa(e,r){this.lo=e>>>0,this.hi=r>>>0}function sf(e,r,s){this.fn=e,this.len=r,this.next=void 0,this.val=s}function si(){}function Tt(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function ja(){this.len=0,this.tail=this.head=new sf(si,0,0),this.states=null}function ti(e,r,s){r[s]=255&e}function ui(e,r){this.len=e,this.next=void 0,this.val=r}function vi(e,r,s){for(;e.hi;)r[s++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;127>>=7;r[s++]=e.lo}function wi(e,r,s){r[s]=255&e,r[s+1]=e>>>8&255,r[s+2]=e>>>16&255,r[s+3]=e>>>24}function jc(){xi.call(this)}function Ut(e,r,s){40>e.length?V.utf8.write(e,r,s):r.utf8Write?r.utf8Write(e,s):r.write(e,s)}function Yb(e,r){return RangeError("index out of range: "+e.pos+" + "+(r||1)+" > "+e.len)}function La(e){this.buf=e,this.pos=0,this.len=e.length}function yi(){var e=new Em(0,0),r=0;if(!(4r;++r){if(this.pos>=this.len)throw Yb(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*r)>>>0,128>this.buf[this.pos++])return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*r)>>>0,e}for(;4>r;++r)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*r)>>>0,128>this.buf[this.pos++])return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,128>this.buf[this.pos++])return e;if(r=0,4r;++r)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*r+3)>>>0,128>this.buf[this.pos++])return e}else for(;5>r;++r){if(this.pos>=this.len)throw Yb(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*r+3)>>>0,128>this.buf[this.pos++])return e}throw Error("invalid varint encoding")}function zg(e,r){return(e[r-4]|e[r-3]<<8|e[r-2]<<16|e[r-1]<<24)>>>0}function Fm(){if(this.pos+8>this.len)throw Yb(this,8);return new Em(zg(this.buf,this.pos+=4),zg(this.buf,this.pos+=4))}function Fd(e){zi.call(this,e)}function tf(e,r,s){if(typeof e!="function")throw TypeError("rpcImpl must be a function");V.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=!!r,this.responseDelimited=!!s}function za(e){return typeof e=="string"&&/^[\s\w!#$%&()+,.:;<=>?@[\]^{|}~-]{1,64}$/.test(e)&&e!=="null"}function Gm(e){try{var r=e.split(".").map(function(d){return Number(d)})}catch{return!1}if(r.length!==4||r[0]===0)return!1;for(e=0;es||255d)throw new ib("Exceed the limit of ".concat(d," attributes"),se);if(Object.keys(r).length===0)throw new I("The attributes is an empty object",Ja);var _=0,C=0;for(r=Object.entries(r);Cf)throw new ib("Invalid attribute value, over the limit of ".concat(f," bytes"),se);if(typeof x!="string"||x.length===0)throw new I("Invalid attribute value",Ja);_+=P,_+=B}if(_>e)throw new ib("The attributes size overflow",se);if(s!==void 0){if(Object.keys(s).length>d)throw new ib("Exceed the limit of ".concat(d," attributes"),se);for(_=d=0,s=Object.entries(s);_f)throw new ib("Invalid attribute value, over the limit of ".concat(f," bytes"),se);d+=r,d+=C}if(d>e)throw new ib("The attributes size overflow",se)}}function Ag(e,r){return Math.floor(Math.random()*(Math.floor(r)-Math.ceil(e)+1))+e}function Bg(){var e=Ag(0,4294967295),r=Ag(1,4294967295);return new U(e,r,!0)}function Xa(e){return e.toString().padEnd(32,"0")}function Im(e,r){return new TypeError("Unexpected ".concat(e,": ").concat(r))}function Jm(e,r){return e=e.split(".").map(function(s){return Number(s)}),r=r.split(".").map(function(s){return Number(s)}),Math.sqrt(1e3*Math.pow(e[0]-r[0],2)+100*Math.pow(e[1]-r[1],2)+10*Math.pow(e[2]-r[2],2)+1*Math.pow(e[3]-r[3],2))}function Km(e){return e.lessThanOrEqual(Number.MAX_SAFE_INTEGER)?e.toNumber():e.toString()}function Ai(e,r){r="".concat(e).concat(r||"");var s=Lm.get(r)||1;return Lm.set(r,s+1),"".concat(e).concat(s)}function Mm(e,r){var s=typeof r=="number"?r:r!==void 0&&typeof r!="string"?r.code:void 0;return r=typeof r!="number"&&typeof r!="string"&&r!==void 0&&r.serverCode!==void 0?r.serverCode:void 0,s="".concat(s!==void 0?" Error Code ".concat(s):"").concat(r!==void 0?", server Code ".concat(r):""),e=typeof e=="string"&&e?Cg(e):Array.isArray(e)&&typeof e[0]=="string"&&e[0]?Cg(Nm.apply(void 0,[e[0]].concat(G(e.slice(1))))):"","".concat(s===""?"":"".concat(s," - ")).concat(e)}function Om(e){return Bi.apply(this,arguments)}function Bi(){return(Bi=J(w.mark(function e(r){return w.wrap(function(s){for(;;)switch(s.prev=s.next){case 0:return s.abrupt("return",new Promise(function(d){setTimeout(function(){d()},r)}));case 1:case"end":return s.stop()}},e)}))).apply(this,arguments)}function Pm(e){return e instanceof Blob||Object.prototype.toString.call(e)==="[object Blob]"}function Dg(e){var r=255&e,s=e>>8&255,d=e>>16&255;return"".concat(e>>24&255,".").concat(d,".").concat(s,".").concat(r)}function te(e,r,s){return Ci.apply(this,arguments)}function Ci(){return(Ci=J(w.mark(function e(r,s,d){var f,_,C,P,x,B,_t,ue,Wt,_n,_i,Ei,_a,Di,_o,_s,_c,_m,Qm,tE,aE,RE,lE,gE,cE,_E;return w.wrap(function(iE){for(;;)switch(iE.prev=iE.next){case 0:if(f=s.body,_=s.headers,C=_===void 0?{}:_,P=s.timeout,x=P===void 0?1e4:P,B=s.signal,_t=s.withCredentials,ue=_t!==void 0&&_t,Wt=(d||{}).useBinaryResponse,_n=Wt!==void 0&&Wt,(_i=new XMLHttpRequest).open("POST",r,!0),_i.responseType=_n?"arraybuffer":"text",_i.withCredentials=ue,_i.timeout=x,Ei=f instanceof FormData,_a=f instanceof Uint8Array,!(1<(Di=Object.keys(C).filter(function(rE){return rE.toLowerCase()==="content-type"})).length)){iE.next=14;break}throw new RangeError("multiple content-type");case 14:Di.length===0&&(_a?C["Content-Type"]="application/octet-stream":Ei||(C["Content-Type"]="application/json"));case 15:if("setRequestHeader"in _i){iE.next=46;break}return _i.abort(),iE.next=19,fetch(r,{body:Ei||_a?f:JSON.stringify(f),cache:"no-cache",credentials:ue?"include":"same-origin",headers:C,method:"POST",mode:"cors",referrer:"no-referrer",signal:B});case 19:if(_o=iE.sent,!(200<=(_s=_o.status)&&300>_s||_s===304)){iE.next=31;break}if(!_n){iE.next=27;break}return iE.next=25,_o.arrayBuffer();case 25:return _c=iE.sent,iE.abrupt("return",{status:_s,responseData:_c});case 27:return iE.next=29,_o.text();case 29:return _m=iE.sent,iE.abrupt("return",{status:_s,responseText:_m});case 31:return Qm=new da(["Post XHR failure, status %d",_s]),iE.prev=32,iE.next=35,_o.text();case 35:throw tE=iE.sent,Qm.statusCode=_s,Qm.message=tE||"Request failed, status ".concat(_s),Qm;case 41:throw iE.prev=41,iE.t0=iE.catch(32),Qm.statusCode=_s,Qm.message="Request failed, status ".concat(_s),Qm;case 46:if(Object.keys(C).length!==0)for(aE=0,RE=Object.entries(C);aEFg||Fg===304)rE(_n?{status:Fg,responseData:_i.response}:{status:Fg,responseText:_i.responseText});else{var _d=new da(["Post XHR failure, status %d",Fg]);_d.statusCode=Fg,_d.message=_i.response||"Request failed, status ".concat(_i.status),vf(_d)}},_i.ontimeout=function(Fg){vf(new db(["XHR request timed out after %d ms",x],{originalError:Fg}))},_i.onerror=function(){var Fg=new da(["Post XHR failure, status %d",_i.status]);Fg.statusCode=_i.status,Fg.message=_i.response||"Request failed, status ".concat(_i.status),vf(Fg)},_i.onabort=function(){try{vf(new DOMException("The request aborted.","AbortError"))}catch{var Fg=Error("The request aborted.");Fg.name="AbortError",vf(Fg)}}}));case 50:case"end":return iE.stop()}},e,null,[[32,41]])}))).apply(this,arguments)}function Rm(e){return Hi.apply(this,arguments)}function Hi(){return(Hi=J(w.mark(function e(r){var s;return w.wrap(function(d){for(;;)switch(d.prev=d.next){case 0:return(s=new Image).src=r,d.abrupt("return",new Promise(function(f,_){s.onload=function(){f({width:s.width,height:s.height})},s.onerror=_}));case 3:case"end":return d.stop()}},e)}))).apply(this,arguments)}function Xt(e,r){return Ii.apply(this,arguments)}function Ii(){return(Ii=J(w.mark(function e(r,s){var d,f,_,C,P,x,B,_t,ue,Wt;return w.wrap(function(_n){for(;;)switch(_n.prev=_n.next){case 0:if(d=r.thumbnailHeight,f=d===void 0?0:d,_=r.thumbnailWidth,C=_===void 0?0:_,P=r.width,x=P===void 0?0:P,B=r.height,_t=B===void 0?0:B,ue=r.thumbnail,Wt=[],typeof f=="number"&&typeof C=="number"&&typeof x=="number"&&typeof _t=="number"){_n.next=5;break}throw new I("Invalid message params",wf);case 5:return 0>=x&&0>=_t&&Wt.push(Rm(Sm(s)).then(function(_i){x=_i.width,_t=_i.height})),0>=C&&0>=f&&ue!==void 0&&Wt.push(Ji(ue).then(function(){var _i=J(w.mark(function Ei(_a){var Di;return w.wrap(function(_o){for(;;)switch(_o.prev=_o.next){case 0:return _o.next=2,Rm(Sm(_a));case 2:Di=_o.sent,C=Di.width,f=Di.height;case 5:case"end":return _o.stop()}},Ei)}));return function(Ei){return _i.apply(this,arguments)}}())),_n.next=9,Promise.all(Wt).catch(function(){});case 9:return _n.abrupt("return",{width:x,height:_t,thumbnailWidth:C,thumbnailHeight:f});case 10:case"end":return _n.stop()}},e)}))).apply(this,arguments)}function Tm(e,r){if(!yd(e))throw new I("message object is not a plain object",r);if(e.messageType===void 0)if(e.rawMessage instanceof Uint8Array){if(e.messageType="RAW",e.text!==void 0)throw new I("Raw messages cannot have text property. Use description instead",r)}else{if(typeof e.text!="string")throw new I("messageType is undefined",r);if(e.messageType="TEXT",e.rawMessage!==void 0)throw new I("Text messages cannot have rawMessage property",r)}}function Gg(e){return Ki.apply(this,arguments)}function Ki(){return(Ki=J(w.mark(function e(r){var s,d,f,_,C,P,x,B,_t,ue,Wt,_n,_i,Ei,_a,Di,_o,_s,_c,_m,Qm;return w.wrap(function(tE){for(;;)switch(tE.prev=tE.next){case 0:if(s=r.message,d=r.peerId,f=r.toPeer,_=r.session,C=r.errorCodes,P=r.diff,x=r.logger,B=r.options,_!==void 0){tE.next=3;break}throw new K("The client is not logged in. Cannot do the operation",C.NOT_LOGGED_IN);case 3:if(_t=!1,s.messageType!=="TEXT"||!s.text.startsWith("AgoraRTMLegacyEndcallCompatibleMessagePrefix")||!f){tE.next=11;break}if(ue=s.text.split("_"),Wt=ra(ue,3),_n=Wt[0],_i=Wt[1],Wt[2]!==void 0&&za(_i)&&_n==="AgoraRTMLegacyEndcallCompatibleMessagePrefix"){tE.next=10;break}throw new I("Message is not valid",ve);case 10:_t=!0;case 11:if(Ei=Date.now(),_a=_.messageSentTimes.length-1,!((Di=_.messageSentTimes[_a])&&Di+3e3=1.5*s?"s":"")}function bu(e){var r=e.areas,s=e.excludedArea;if(r.length===1&&r[0]===F.GLOBAL&&s===F.CHINA)return xe([F.OVERSEA]);if(r.includes(F.GLOBAL)){if(e=xf(Kg).filter(function(_){return _!==F.GLOBAL&&_!==F.OVERSEA}),s in yf){r=yf[s];var d=[].concat(G(r??[]),[s]);return xe(e.filter(function(_){return!d.includes(_)}))}if(Zm(s)){var f=cu(s);return xe(e.filter(function(_){return _!==s&&_!==f}))}}if(Zm(s)||s in yf)return xe(r);throw new I("Invalid excludedArea area config")}function Ma(e,r,s){s===void 0&&(s=Object.getOwnPropertyDescriptor(e,r));var d=s.value;return s.value=function(){for(var f=this,_=arguments.length,C=Array(_),P=0;P<_;P++)C[P]=arguments[P];this.invokeTracker.apply(this,["%s: ".concat(0arguments.length?mn(y[e])||mn(y[e]):y[e]&&y[e][r]||y[e]&&y[e][r]},uu=Math.ceil,vu=Math.floor,$b=function(e){return isNaN(e=+e)?0:(0(e=$b(e))?xu(e+r,0):yu(e,r)},nn=function(e){return function(r,s,d){r=qb(r);var f=ta(r.length);if(d=xb(d,f),e&&s!=s){for(;f>d;)if((s=r[d++])!=s)return!0}else for(;f>d;d++)if((e||d in r)&&r[d]===s)return e||d||0;return!e&&-1}},on=nn(!0),Si=nn(!1),pn=function(e,r){e=qb(e);var s,d=0,f=[];for(s in e)!Q(Be,s)&&Q(e,s)&&f.push(s);for(;r.length>d;)Q(e,s=r[d++])&&(~Si(f,s)||f.push(s));return f},Rg="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" "),zu=Rg.concat("length","prototype"),Hd={f:Object.getOwnPropertyNames||function(e){return pn(e,zu)}},Bf={f:Object.getOwnPropertySymbols},qn=mc("Reflect","ownKeys")||function(e){var r=Hd.f(va(e)),s=Bf.f;return s?r.concat(s(e)):r},rn=function(e,r){for(var s=qn(r),d=Ra.f,f=Fb.f,_=0;_hd[0]?1:hd[0]+hd[1];else De&&(hd=De.match(/Edge\/(\d+)/),(!hd||74<=hd[1])&&(hd=De.match(/Chrome\/(\d+)/))&&(Ti=hd[1]));var id=Ti&&+Ti,oc=!!Object.getOwnPropertySymbols&&!R(function(){return!String(Symbol())||!Symbol.sham&&id&&41>id}),vn=oc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Cf=fd("wks"),Df=y.Symbol,Gu=vn?Df:Df&&Df.withoutSetter||Ae,qa=function(e){return Q(Cf,e)&&(oc||typeof Cf[e]=="string")||(oc&&Q(Df,e)?Cf[e]=Df[e]:Cf[e]=Gu("Symbol."+e)),Cf[e]},Hu=qa("species"),Sg=function(e,r){if(gd(e)){var s=e.constructor;typeof s!="function"||s!==Array&&!gd(s.prototype)?ha(s)&&(s=s[Hu])===null&&(s=void 0):s=void 0}return new(s===void 0?Array:s)(r===0?0:r)},wn=[].push,jd=function(e){var r=e==1,s=e==2,d=e==3,f=e==4,_=e==6,C=e==7,P=e==5||_;return function(x,B,_t,ue){var Wt=Qa(x),_n=Af(Wt);B=Id(B,_t,3),_t=ta(_n.length);var _i,Ei=0;for(ue=ue||Sg,x=r?ue(x,_t):s||C?ue(x,0):void 0;_t>Ei;Ei++)if((P||Ei in _n)&&(_i=B(ue=_n[Ei],Ei,Wt),e))if(r)x[Ei]=_i;else if(_i)switch(e){case 3:return!0;case 5:return ue;case 6:return Ei;case 2:wn.call(x,ue)}else switch(e){case 4:return!1;case 7:wn.call(x,ue)}return _?-1:d||f?f:x}},Jd=jd(0),xn=jd(1),yn=jd(2),Iu=jd(3),Ju=jd(4),zn=jd(5),An=jd(6),Ku=qa("species"),Ef=function(e){return 51<=id||!R(function(){var r=[];return(r.constructor={})[Ku]=function(){return{foo:1}},r[e](Boolean).foo!==1})},Lu=Ef("filter");N({target:"Array",proto:!0,forced:!Lu},{filter:function(e){return yn(this,e,1x;x++)P=C?_(s[x],x):s[x],Ge(d,x,P)}else for(f=(s=P.call(s)).next,d=new d;!(r=f.call(s)).done;x++){if(C){P=s;var _t=_;r=[r.value,x];try{B=_t(va(r)[0],r[1])}catch(ue){throw Ui(P),ue}}else B=r.value;Ge(d,x,P=B)}return d.length=x,d}});var Fn=function(e){return function(r,s){r=String(jb(r)),s=$b(s);var d,f=r.length;if(0>s||s>=f)return e?"":void 0;var _=r.charCodeAt(s);return 55296>_||56319<_||s+1===f||56320>(d=r.charCodeAt(s+1))||57343_;)Ra.f(e,s=d[_++],r[s]);return e},Zi=mc("document","documentElement"),Mn=Pg("IE_PROTO"),$i=function(){},aj,Wg=function(){try{aj=document.domain&&new ActiveXObject("htmlfile")}catch{}if(aj){var e=aj;e.write(" - + +
diff --git a/client/src/Components/Skeletons/HomePageLoading.tsx b/client/src/Components/Skeletons/HomePageLoading.tsx index 3e4b834..7705059 100644 --- a/client/src/Components/Skeletons/HomePageLoading.tsx +++ b/client/src/Components/Skeletons/HomePageLoading.tsx @@ -1,4 +1,3 @@ -import ChatLoading from "./ChatLoading"; import PostCardLoading from "./PostCardLoading"; const HomePageLoading = () => {