@cloudflare/realtimekit 0.5.0-staging.72 → 0.5.0-staging.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.cjs.js CHANGED
@@ -19,5 +19,5 @@ ${t}`}const js={maxInvocations:5,period:1};function Ft(t,e){return function(n,i,
19
19
  `).map(e=>Ui.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=dt(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=Ui.parseTranscripts(e)}catch{}})}onTranscript(t){return u(this,null,function*(){var e;const n=this.transcripts.filter(({peerId:i})=>i===t.peerId);if((e=n==null?void 0:n.at(-1))!=null&&e.isPartialTranscript){const i=n.at(-1);i.transcript=t.transcript,i.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",i);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)})}};gy([E.trace("DyteAi.getActiveTranscript")],Ui.prototype,"getActiveTranscript",1);Ui=gy([gt("0000")],Ui);var QD=Object.defineProperty,XD=Object.getOwnPropertyDescriptor,ZD=(t,e,n,i)=>{for(var r=i>1?void 0:i?XD(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&QD(e,n,r),r},Ki,ma,nu,Dg;const fy=(Dg=class{constructor(t,e,n,i,r,s){g(this,"meta"),g(this,"ai"),f(this,Ki,void 0),f(this,ma,void 0),g(this,"aiSocketHandler"),f(this,nu,void 0),v(this,nu,t),this.meta=new Yu(t,e,e.config.viewType,n,s),this.ai=i,v(this,Ki,e),v(this,ma,n),this.aiSocketHandler=r,e.config.viewType!==Rt.Chat&&this.setupEvents()}static init(t,e,n,i,r){return u(this,null,function*(){const s=yield Ui.init(e.permissions.transcriptionEnabled);return new fy(t,e,n,s,i,r)})}conditionallySetActiveTab(t){var e;t!=null&&t.currentTab&&((e=this.meta.selfActiveTab)==null?void 0:e.id)!==t.currentTab.id&&(this.meta.setSelfActiveTab(t.currentTab,my.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){R.on(M.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),R.on(M.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),R.on(M.ROOM_STATE,({createdAt:t,roomUuid:e})=>{const n=this.meta.meetingStartedTimestamp;if(e&&(this.meta.sessionId=e),t&&!n){const i=new Date(t*1e3);this.meta.meetingStartedTimestamp=i,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),R.on(M.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),o(this,Ki).permissions.canSpotlight&&(p.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&o(this,ma).broadcastMessage("spotlight",{userId:o(this,Ki).userId,currentTab:this.meta.selfActiveTab})),R.on(M.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){o(this,Ki).permissions.canSpotlight&&this.meta.selfActiveTab&&o(this,ma).broadcastToPeers("spotlight",[t.id],{userId:o(this,Ki).userId,currentTab:this.meta.selfActiveTab})})),R.on(M.ROOM_MESSAGE,t=>{var e,n;let i;if("type"in t){if(t.type!=="spotlight")return;i=U(U({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;i=t}else return;p.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:i.userId},currentTab:{id:(e=i.currentTab)==null?void 0:e.id,type:(n=i.currentTab)==null?void 0:n.type}}}),this.conditionallySetActiveTab(i)}),R.on(M.MESSAGE,t=>{var e,n;let i;if("type"in t){if(t.type!=="spotlight")return;i=U(U({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;i=t}else return;p.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:i.userId},currentTab:{id:(e=i.currentTab)==null?void 0:e.id,type:(n=i.currentTab)==null?void 0:n.type}}}),this.conditionallySetActiveTab(i)}),this.aiSocketHandler.on(j.transcript,t=>{const{meetingId:e,transcript:n,isPartial:i}=t,r=Ui.parseTranscript(n,i);if(!r){p.warn("Received empty transcript data");return}this.ai.onTranscript(r),this.meta.emit("transcript",r);const{peerId:s,name:a,transcript:c}=r;p.debug(`${e} Received transcript for peer ${s} - ${a}: ${c}`)})}},Ki=new WeakMap,ma=new WeakMap,nu=new WeakMap,Dg);let vy=fy;ZD([E.trace("MetaController.setupEvents")],vy.prototype,"setupEvents",1);var eO=Object.defineProperty,tO=Object.getOwnPropertyDescriptor,Wr=(t,e,n,i)=>{for(var r=i>1?void 0:i?tO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&eO(e,n,r),r},gn,Ua,pe,Vc,Jn,Ln,Uc,Qu,Fa,Fc;class qi extends zt{constructor(e,n,i,r,s){super(),f(this,Uc),f(this,Fa),f(this,gn,void 0),f(this,Ua,void 0),f(this,pe,void 0),f(this,Vc,void 0),f(this,Jn,void 0),f(this,Ln,void 0),v(this,Ln,e),v(this,gn,r),v(this,Ua,s),v(this,pe,n),v(this,Vc,i),v(this,Jn,[]),this.setupEvents()}get status(){return o(this,Ln).getValue("stageStatus")}setupEvents(){const e={[M.GET_STAGE_REQUESTS]:r=>u(this,null,function*(){v(this,Jn,r)}),[M.UPDATE_STAGE_REQUESTS]:r=>u(this,[r],function*({add:s}){const a=o(this,Jn).length,{stageRequests:c}=this.getAccessRequests();(s||c.length>a)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)})},n=()=>{Object.entries(e).forEach(([r,s])=>{R.onAsync(r,s)})},i=()=>{Object.entries(e).forEach(([r,s])=>{R.removeListener(r,s)})};o(this,pe).permissions.on("permissionsUpdate",r=>{const{canAcceptProductionRequests:s}=r;s!==void 0&&(o(this,pe).permissions.acceptStageRequests?(n(),o(this,gn).getStageRequests()):(i(),v(this,Jn,[]),this.emit("stageAccessRequestUpdate",o(this,Jn))))}),o(this,pe).permissions.acceptStageRequests&&n()}getAccessRequests(){if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!o(this,pe).permissions.acceptStageRequests)throw p.error("DyteStage::get_access_request::permission_denied"),new I("You do not have permission to perform this action","2001");const e=o(this,Vc).joined.toArray().filter(n=>n.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(n=>({displayName:n.name,userId:n.userId,peerId:n.id}));return v(this,Jn,e),{stageRequests:o(this,Jn)}}requestAccess(){return u(this,null,function*(){if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new I(`Unable to request access you are currently ${this.status}`,"2006");if(o(this,pe).permissions.stageAccess===Y.Allowed){H(this,Fa,Fc).call(this,"ACCEPTED_TO_JOIN_STAGE");return}o(this,gn).requestAccess(),H(this,Fa,Fc).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return u(this,null,function*(){if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");o(this,gn).cancelRequestAccess(),H(this,Fa,Fc).call(this,"OFF_STAGE")})}grantAccess(e){if(!o(this,pe).roomJoined)throw new I("Can`t grant for participant without joining room");if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!o(this,pe).permissions.acceptStageRequests)throw p.error("DyteStage::grant_access::permission_denied"),new I("You do not have permission to perform this action","2001");return o(this,gn).grantAccess(e)}denyAccess(e){if(!o(this,pe).roomJoined)throw new I("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!o(this,pe).permissions.acceptStageRequests)throw p.error("DyteStage::deny_access::permission_denied"),new I("You do not have permission to perform this action","2001");return o(this,gn).denyAccess(e)}join(){return u(this,null,function*(){const e=o(this,Ln).getValue("viewType");if(this.status==="ON_STAGE")throw new I("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||o(this,pe).permissions.stageAccess===Y.NotAllowed)throw new I(`Unable to join stage you are currently ${this.status}`,"2006");if(yield o(this,gn).joinStage(),e===Rt.Livestream){yield o(this,Ua).joinRoom(o(this,pe));const{peers:n}=yield o(this,Ua).getStagePeers();R.emit(M.SOCKET_PEERS,n)}o(this,Ln).setValue("stageStatus","ON_STAGE"),o(this,pe).audioEnabled&&o(this,Uc,Qu).shareMic(o(this,pe).audioTrack),o(this,pe).videoEnabled&&o(this,Uc,Qu).shareWebcam(o(this,pe).videoTrack)})}leave(){return u(this,null,function*(){if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new I(`Unable to leave stage you are currently ${this.status}`,"2006");o(this,pe).setIsPinned(!1),yield o(this,gn).leaveStage(o(this,pe).userId),o(this,Ln).setValue("stageStatus","OFF_STAGE",!1),yield R.emitAsync(M.LEAVE_MEDIA_ROOM,"stageLeft"),o(this,Ln).notify("stageStatus")})}kick(e){return u(this,null,function*(){if(!o(this,pe).roomJoined)throw new I("Can`t kick participant without joining room","2005");if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!o(this,pe).permissions.acceptStageRequests)throw p.error("DyteStage::kick::permission_denied"),new I("You do not have permissions for kick","2001");return o(this,gn).kick(e)})}}gn=new WeakMap,Ua=new WeakMap,pe=new WeakMap,Vc=new WeakMap,Jn=new WeakMap,Ln=new WeakMap,Uc=new WeakSet,Qu=function(){return o(this,Ln).getValue("roomNodeClient")},Fa=new WeakSet,Fc=function(t){return u(this,null,function*(){this.status!==t&&o(this,Ln).setValue("stageStatus",t)})};Wr([E.trace("DyteStage.getStageRequests")],qi.prototype,"getAccessRequests",1);Wr([E.trace("DyteStage.requestAccess")],qi.prototype,"requestAccess",1);Wr([E.trace("DyteStage.cancelRequestAccess")],qi.prototype,"cancelRequestAccess",1);Wr([E.trace("DyteStage.grantAccess")],qi.prototype,"grantAccess",1);Wr([E.trace("DyteStage.denyAccess")],qi.prototype,"denyAccess",1);Wr([E.trace("DyteStage.joinStage")],qi.prototype,"join",1);Wr([E.trace("DyteStage.leaveStage")],qi.prototype,"leave",1);function nO(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function pp(t){switch(t){case ei.UNSPECIFIED:return"OFF_STAGE";case ei.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case ei.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case ei.OFF_STAGE:return"OFF_STAGE";case ei.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var iO=Object.defineProperty,rO=Object.getOwnPropertyDescriptor,sO=(t,e,n,i)=>{for(var r=i>1?void 0:i?rO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&iO(e,n,r),r},ir,rs,rr,Bc,_i;class yy{constructor(e,n,i,r,s){g(this,"stage"),f(this,ir,void 0),f(this,rs,void 0),f(this,rr,void 0),f(this,Bc,0),f(this,_i,void 0),v(this,_i,e),this.stage=new qi(e,r,s,n,i),v(this,rr,n),v(this,ir,r),v(this,rs,s),this.setupEvents()}setupEvents(){o(this,_i).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),o(this,rr).on(j.grantStageAccess,()=>{o(this,ir).permissions.stageAccess!==Y.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),o(this,rr).on(j.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===o(this,ir).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),o(this,rr).on(j.denyStageAccess,()=>{o(this,ir).permissions.stageAccess!==Y.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),o(this,rr).on(j.getStageRequests,e=>u(this,null,function*(){var n;if(o(this,ir).permissions.stageAccess!==Y.Allowed)return;const i=(n=e==null?void 0:e.stageRequests)!=null?n:[];yield R.emitAsync(M.GET_STAGE_REQUESTS,i),o(this,Bc)<i.length&&i.length>0&&this.stage.emit("newStageRequest",{count:i.length}),v(this,Bc,i.length),this.stage.emit("stageAccessRequestUpdate",i)}))}getCurrentStageRequests(){return o(this,rs).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}setStageStatus(e){return u(this,null,function*(){this.stage.status!==e&&o(this,_i).setValue("stageStatus",e)})}selfStageStatusHandler(e){const n=pp(e.stageType),i=o(this,_i).getValue("stageStatus");if(i!==n)switch(e.stageType){case 1:o(this,_i).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(i);break;case 0:case 4:default:o(this,_i).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return u(this,null,function*(){const n=o(this,rs).joined.get(e.peerId),i=o(this,rs).viewMode==="ACTIVE_GRID";if(!n){p.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:n.setStageStatus("ON_STAGE"),i&&R.emit(M.UPDATE_ACTIVE);break;case 2:n.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:n.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:n.setStageStatus("OFF_STAGE"),i&&R.emit(M.UPDATE_ACTIVE);break}R.emit(M.UPDATE_PEER_STAGE_STATUS,{id:n.id,status:n.stageStatus})})}}ir=new WeakMap,rs=new WeakMap,rr=new WeakMap,Bc=new WeakMap,_i=new WeakMap;sO([E.trace("DyteStage.setupEvents")],yy.prototype,"setupEvents",1);var aO=Object.defineProperty,oO=Object.getOwnPropertyDescriptor,ul=(t,e,n,i)=>{for(var r=i>1?void 0:i?oO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&aO(e,n,r),r};const Ve={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};var yt,Zt,ga,fa,ui,va,Yr,ya,Og;let Us=(Og=class extends Bs{constructor(t,{baseURL:e,createdAt:n,description:i,id:r,name:s,organizationId:a,picture:c,private:d,published:l,staggered:h,tags:m,type:y,updatedAt:S},b,D,C,V,L){super(),f(this,yt,void 0),g(this,"baseURL"),g(this,"createdAt"),g(this,"description"),g(this,"id"),g(this,"name"),f(this,Zt,void 0),f(this,ga,void 0),f(this,fa,void 0),g(this,"organizationId"),g(this,"picture"),g(this,"private"),g(this,"published"),g(this,"staggered"),g(this,"tags"),g(this,"type"),g(this,"updatedAt"),f(this,ui,void 0),g(this,"config"),f(this,va,void 0),g(this,"active"),g(this,"iframes"),g(this,"enabledBy"),f(this,Yr,void 0),f(this,ya,void 0),v(this,Yr,t),this.baseURL=e,this.createdAt=new Date(n),this.description=i,this.id=r,this.name=s,v(this,Zt,D),this.organizationId=a,this.picture=c,this.private=d,this.published=l,this.staggered=h,this.tags=m,this.type=y,this.updatedAt=new Date(S),this.active=!1,this.iframes=new Map,v(this,yt,b),v(this,ga,C),v(this,fa,V),this.enabledBy="",v(this,ya,L)}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:n}=e;n&&(navigator.isReactNative?n.postMessage(JSON.stringify(t)):n.contentWindow.postMessage(t,"*"))})}handleIframeMessage(t){return u(this,null,function*(){var e;if(!this.active)return;const n=t,{payload:i,uuid:r,type:s}=n;switch(s){case z.customPluginEventToRoom:{o(this,yt).customPluginEventToRoom(this.id,i,r);break}case z.customPluginEventToPeers:{o(this,yt).customPluginEventToPeers(this.id,i.peerIds,i,r);break}case z.enablePluginForRoom:{o(this,yt).enablePluginForRoom(this.id,r);break}case z.enablePluginForPeers:{o(this,yt).enablePluginForPeers(this.id,i.peerIds,r);break}case z.disablePluginForRoom:{o(this,yt).disablePluginForRoom(this.id,r);break}case z.disablePluginForPeers:{o(this,yt).disablePluginForPeers(this.id,i.peerIds,r);break}case z.storeInsertKeys:{o(this,yt).storeInsertKeys(this.id,i.store,i.insertKeys,r);break}case z.storeGetKeys:{o(this,yt).storeGetKeys(this.id,i.store,i.getKeys,r);break}case z.storeDeleteKeys:{o(this,yt).storeDeleteKeys(this.id,i.store,i.deleteKeys,r);break}case z.storeDelete:{o(this,yt).storeDelete(this.id,i.store,r);break}case Ve.chatMessage:{const{messagePayload:a,peerIds:c}=i;if(!o(this,fa)){this.sendIframeEvent({type:Ve.chatMessage,uuid:n.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield o(this,fa).sendMessage(a,c),this.sendIframeEvent({type:Ve.chatMessage,uuid:n.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:Ve.chatMessage,uuid:n.uuid,payload:{error:d}})}break}case Ve.getPeer:{let a;const{peerId:c}=i,d=J(U({},o(this,Zt)),{id:o(this,Zt).id,isRecorder:(e=o(this,Zt).permissions)==null?void 0:e.isRecorder,isHidden:o(this,Zt).permissions.hiddenParticipant,stageStatus:o(this,Zt).stageStatus});c?(a=o(this,ga).joined.get(i.peerId),o(this,Zt).id===c&&(a=d)):a=d,this.sendIframeEvent({type:Ve.getPeer,payload:{peer:a&&Dd(a)},uuid:n.uuid});break}case Ve.getPeers:{const a=o(this,ga).joined.toArray().map(c=>Dd(c));this.sendIframeEvent({type:Ve.getPeers,payload:{peers:a},uuid:n.uuid});break}case Ve.getPluginInitiator:{this.sendIframeEvent({type:Ve.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:n.uuid});break}case Ve.getDisplayTitle:{this.sendIframeEvent({type:Ve.getDisplayTitle,payload:{displayTitle:o(this,ya)},uuid:n.uuid});break}case Ve.getRoomName:{this.sendIframeEvent({type:Ve.getRoomName,payload:{roomName:o(this,Yr).getValue("meetingId")},uuid:n.uuid});break}case Ve.customPluginEventToParent:{this.emit(n.payload.eventName,n.payload.data);break}}})}sendData(t){this.active&&(p.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Ve.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var e;const{iframe:n,listener:i}=(e=this.iframes.get(t))!=null?e:{};(n||i)&&(navigator.isReactNative?n.props.onMessage=void 0:window.removeEventListener("message",i),this.iframes.delete(t))}addPluginView(t,e="default"){var n;if(!o(this,va))throw p.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new I("No auth token set for plugin.","0602");if(!t)throw p.error("DytePlugin::addPluginView::iframe_was_not_provided"),new I("Iframe was not provided.","0603");this.removePluginView(e);const i=t,r=new URL(this.baseURL),s={auth:o(this,va),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:o(this,Yr).getValue("apiBase"),pluginId:this.id,roomName:(n=o(this,Yr).getValue("meetingId"))!=null?n:"",displayTitle:o(this,ya)};if(Object.keys(s).forEach(a=>{r.searchParams.set(a,s[a])}),i.src=r.href,i.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",i.title=e,navigator.isReactNative)i.props.onMessage=a=>{this.handleIframeMessage(JSON.parse(a.nativeEvent.data))},this.iframes.set(e,{iframe:i});else{const a=c=>u(this,null,function*(){c.source===t.contentWindow&&(yield this.handleIframeMessage(c.data))});window.addEventListener("message",a),this.iframes.set(e,{iframe:i,listener:a})}}setActive(t){var e,n;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(n=this.config)==null?void 0:n.views})}activateForSelf(){return u(this,null,function*(){const t=dt(),e=yield t.authorizePlugin(this.id);v(this,va,e),v(this,ui,new Date);try{const n=yield t.getPluginConfig(this.baseURL);this.config=n}catch(n){p.error("DytePlugin::activateForSelf",{error:n})}this.setActive(!0),this.emit("enabled")})}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),v(this,ui,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}enable(){return u(this,null,function*(){return this.activateForSelf()})}disable(){return this.deactivateForSelf()}activate(){return u(this,null,function*(){var t,e;this.active||(e=(t=o(this,Zt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(o(this,yt).addPlugin(this.id,this.staggered),v(this,ui,new Date),p.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))})}deactivate(){return u(this,null,function*(){var t,e;this.active&&(!((e=(t=o(this,Zt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==o(this,Zt).id||(o(this,yt).removePlugin(this.id),p.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:o(this,ui)?new Date().getTime()-o(this,ui).getTime():0}}),v(this,ui,void 0)))})}},yt=new WeakMap,Zt=new WeakMap,ga=new WeakMap,fa=new WeakMap,ui=new WeakMap,va=new WeakMap,Yr=new WeakMap,ya=new WeakMap,Og);ul([Ft({maxInvocations:5,period:1})],Us.prototype,"sendData",1);ul([E.trace("DytePlugin.activatePlugin")],Us.prototype,"activate",1);ul([E.trace("DytePlugin.deactivatePlugin")],Us.prototype,"deactivate",1);Us=ul([gt("0600")],Us);var $e,ss;class Sy extends Map{constructor(e){const{onAddEvent:n,onDeleteEvent:i,onClearEvent:r}=e;super(),f(this,$e,void 0),f(this,ss,void 0),g(this,"onAddEvent"),g(this,"onDeleteEvent"),g(this,"onClearEvent"),v(this,$e,new Bs),this.onAddEvent=n,this.onDeleteEvent=i,this.onClearEvent=r,v(this,ss,new Map)}emit(e,...n){return o(this,$e).emit(e,...n)}on(e,n){return o(this,$e).on(e,n)}addListener(e,n){return o(this,$e).addListener(e,n)}off(e,n){return o(this,$e).off(e,n)}once(e,n){return o(this,$e).once(e,n)}prependListener(e,n){return o(this,$e).prependListener(e,n)}prependOnceListener(e,n){return o(this,$e).prependOnceListener(e,n)}removeListener(e,n){return o(this,$e).removeListener(e,n)}removeAllListeners(e){return o(this,$e).removeAllListeners(e)}listeners(e){return o(this,$e).listeners(e)}listenerCount(e){return o(this,$e).listenerCount(e)}getMaxListeners(){return o(this,$e).getMaxListeners()}setMaxListeners(e){return o(this,$e).setMaxListeners(e)}eventNames(){return o(this,$e).eventNames()}add(e,n=!0){return this.set(e.id,e,n)}set(e,n,i=!0){const r=super.set(e,n),s=(a,...c)=>{this.emit(a,n,...c)};return o(this,ss).set(e,s),n.on("*",s),i&&o(this,$e).emit(this.onAddEvent,n),r}delete(e,n=!0,i=!1){const r=this.get(e);if(!r)return!1;r.removeListener("*",o(this,ss).get(e));const s=super.delete(e);return i&&r.removeAllListeners(),n&&o(this,$e).emit(this.onDeleteEvent,r),s}clear(e=!0,n=!1){this.forEach(r=>{r.removeListener("*",o(this,ss).get(r.id)),n&&r.removeAllListeners()});const i=super.clear();return e&&o(this,$e).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}$e=new WeakMap,ss=new WeakMap;class Ng extends Sy{constructor(){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"})}add(e,n=!0){return super.add(e,n)}delete(e,n=!0,i=!1){return super.delete(e,n,i)}}var cO=Object.defineProperty,dO=Object.getOwnPropertyDescriptor,lO=(t,e,n,i)=>{for(var r=i>1?void 0:i?dO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&cO(e,n,r),r};let Xu=class{constructor(){g(this,"all"),g(this,"active"),this.all=new Ng,this.active=new Ng}};Xu=lO([gt("0600")],Xu);var uO=Object.defineProperty,hO=Object.getOwnPropertyDescriptor,hl=(t,e,n,i)=>{for(var r=i>1?void 0:i?hO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&uO(e,n,r),r},cn,Sa,hc,Lg;const Ey=(Lg=class{constructor(t,e,n,i){g(this,"plugins"),f(this,cn,void 0),f(this,Sa,void 0),f(this,hc,void 0),v(this,cn,e),v(this,Sa,n),v(this,hc,t),this.plugins=i,this.setupEvents()}static init(t,e,n,i,r,s,a,c){return u(this,null,function*(){const d=new Xu;return e.forEach(l=>{const h=new Us(t,l,n,s,a,r,c);d.all.add(h)}),new Ey(t,n,i,d)})}getRoomPlugins(){return u(this,null,function*(){var t;const{plugins:e}=yield o(this,cn).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(n=>{this.disablePlugin({id:n.id})}),yield Promise.all(e.map(n=>this.enablePlugin({id:n.pluginId,enabledBy:n.enabledBy})))})}enablePlugin(t){return u(this,arguments,function*({id:e,enabledBy:n}){const i=this.plugins.all.get(e);i&&(yield i.activateForSelf(),i.enabledBy=n)})}disablePlugin(t){return u(this,arguments,function*({id:e}){const n=this.plugins.all.get(e);n&&n.deactivateForSelf()})}sendIframeEvent(t,e,n,i){const r=this.plugins.all.get(e);r&&r.sendIframeEvent({type:t,uuid:n,payload:i})}broadcastIframeEvent(t,e){this.plugins.active.forEach(n=>{this.sendIframeEvent(t,n.id,"",e)})}setupEvents(){this.plugins.all.on("stateUpdate",({active:t,id:e})=>{if(t){this.plugins.active.add(this.plugins.all.get(e));return}this.plugins.active.delete(e)}),R.onAsync(M.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){yield this.getRoomPlugins(),p.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),o(this,cn).on(z.addPlugin,t=>u(this,null,function*(){var e;const n=t.pluginId;(e=this.plugins.all.get(n))!=null&&e.active||(yield this.enablePlugin({id:n,enabledBy:t.enabledBy}))})),o(this,cn).on(z.removePlugin,t=>u(this,null,function*(){var e;const n=t.pluginId;(e=this.plugins.all.get(n))!=null&&e.active&&(yield this.disablePlugin({id:n}))})),[z.enablePluginForPeers,z.enablePluginForRoom].forEach(t=>{o(this,cn).on(t,(e,n)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,n,{enabledBy:e.enabledBy})}))}),[z.disablePluginForPeers,z.disablePluginForRoom].forEach(t=>{o(this,cn).on(t,(e,n)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,n,{disabledBy:e.disabledBy})}))}),[z.customPluginEventToPeers,z.customPluginEventToRoom].forEach(t=>{o(this,cn).on(t,(e,n)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,n,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[z.storeInsertKeys,z.storeGetKeys,z.storeDeleteKeys].forEach(t=>{o(this,cn).on(t,(e,n)=>u(this,null,function*(){var i;const r=(i=e.storeItems)==null?void 0:i.map(s=>{var a;return{timestamp:s.timestamp,peerId:s.peerId,payload:JSON.parse((a=s.payload)!=null&&a.length?new TextDecoder().decode(s.payload):"{}"),key:s.storeKey}});this.sendIframeEvent(t,e.pluginId,n,{storeName:e.storeName,storeItems:r})}))}),o(this,cn).on(z.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent(z.storeDelete,t.pluginId,e,{storeName:t.storeName})})),o(this,Sa).on(Oe.sendMessageToPeers,t=>{const e=ii==null?void 0:ii.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ve.chatMessage,{message:e})}),o(this,Sa).on(Oe.sendMessageToRoom,t=>{const e=ii==null?void 0:ii.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ve.chatMessage,{message:e})}),R.on(M.PEER_JOINED_INTERNAL,t=>{const e=Dd(t);this.broadcastIframeEvent(Ve.peerJoined,e)}),R.on(M.PEER_CLOSED,t=>{this.broadcastIframeEvent(Ve.peerLeft,t)}),R.on(M.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(Ve.peerStageStatusUpdate,t)}),o(this,hc).subscribe("stageStatus",t=>{this.broadcastIframeEvent(Ve.stageStatusUpdate,t)})}},cn=new WeakMap,Sa=new WeakMap,hc=new WeakMap,Lg);let qo=Ey;hl([E.trace("PluginController.getRoomPlugins")],qo.prototype,"getRoomPlugins",1);hl([E.trace("PluginController.enableForSelf")],qo.prototype,"enablePlugin",1);hl([E.trace("PluginController.disableForSelf")],qo.prototype,"disablePlugin",1);hl([E.trace("PluginController.setupEvents")],qo.prototype,"setupEvents",1);class pO{constructor(){g(this,"mediaJoined"),g(this,"socketJoined"),g(this,"socketJoinAttempted"),g(this,"mediaJoinAttempted"),g(this,"socketState"),g(this,"mediaState"),this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0}}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(e,n){let i;const{reconnected:r}=this.socketState;switch(e){case"connected":i={state:"connected",reconnected:r,reconnectionAttempt:void 0};break;case"disconnected":i={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":i={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":i={state:"reconnecting",reconnected:r,reconnectionAttempt:0};break;case"reconnectAttempt":i={state:"reconnecting",reconnected:r,reconnectionAttempt:n};break;case"failed":i={state:"failed",reconnected:r,reconnectionAttempt:void 0},this.socketJoined=!1;break}i&&(R.emit(M.SOCKET_STATE_UPDATE,i),this.socketState=i)}}var mO=Object.defineProperty,gO=Object.getOwnPropertyDescriptor,Go=(t,e,n,i)=>{for(var r=i>1?void 0:i?gO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&mO(e,n,r),r},Ea,pc,Ta,mc,xg;let Nr=(xg=class extends zt{constructor(t,e){super(),f(this,Ta),f(this,Ea,void 0),f(this,pc,void 0),g(this,"recordingPeerIds",[]),g(this,"recordings",[]),v(this,pc,t),v(this,Ea,e)}get recordingState(){return this.recordings.some(t=>t.state==="RECORDING")?"RECORDING":this.recordings.some(t=>t.state==="PAUSED")?"PAUSED":this.recordings.some(t=>t.state==="STARTING")?"STARTING":this.recordings.some(t=>t.state==="STOPPING")?"STOPPING":"IDLE"}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}start(t){return u(this,null,function*(){if(!o(this,Ea).permissions.canRecord)throw p.error("DyteRecording::start::permission_denied"),new I("User does not have permission to start recording","1001");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw p.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new I(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=dt(),{recording:n={}}=o(this,pc).getValue("defaults"),i=yield e.startRecording(n,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw p.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new I("Error while starting recording","1000")}})}stop(t){return u(this,null,function*(){yield H(this,Ta,mc).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield H(this,Ta,mc).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield H(this,Ta,mc).call(this,"resume",["PAUSED"],t)})}},Ea=new WeakMap,pc=new WeakMap,Ta=new WeakSet,mc=function(t,e,n){return u(this,null,function*(){if(!o(this,Ea).permissions.canRecord)throw p.error("DyteRecording::stop::permission_denied"),new I("User does not have permission to stop recording","1001");let i=[];if(n!==void 0){const r=this.recordings.find(s=>s.id===n);if(r===void 0)throw new I("Could not find the specified recording","1004");if(e.includes(r.state)){p.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:r.state}});return}i.push(r)}else i=this.recordings.filter(r=>e.includes(r.state));i.forEach(r=>u(this,null,function*(){const s=r.state;t==="stop"&&(r.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield dt().updateRecording(r.id,t)}catch(a){throw p.error("DyteRecording::stop::recording_failed_to_stop",{error:a}),r.state!==s&&(r.state=s,this.emit("recordingUpdate",s)),new I("Error while stopping recording","1000")}}))})},xg);Go([E.trace("DyteRecording.start")],Nr.prototype,"start",1);Go([E.trace("DyteRecording.stop")],Nr.prototype,"stop",1);Go([E.trace("DyteRecording.stop")],Nr.prototype,"pause",1);Go([E.trace("DyteRecording.stop")],Nr.prototype,"resume",1);Nr=Go([gt("1000")],Nr);var fO=Object.defineProperty,vO=Object.getOwnPropertyDescriptor,yO=(t,e,n,i)=>{for(var r=i>1?void 0:i?vO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&fO(e,n,r),r},Zu;class Ty{constructor(e,n,i){g(this,"recording"),g(this,"room"),f(this,Zu,void 0),v(this,Zu,e),this.recording=new Nr(e,n),this.room=i,this.setupEvents()}getRecordingTypeFromProtoType(e){let n;switch(e){case Mr.BROWSER:n="BROWSER";break;case Mr.COMPOSITE:n="COMPOSITE";break;case Mr.TRACK:n="TRACK";break;default:n="BROWSER"}return n}setupEvents(){R.on(M.ROOM_STATE,e=>{e.activeRecordings.length!==0?this.recording.updateRecordings(e.activeRecordings.map(n=>{const i=this.getRecordingTypeFromProtoType(n.recordingType);return{id:n.recordingId,state:n.recordingStatus,type:i}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(j.recordingStarted,e=>{let n=!1;const i=[...this.recording.recordings];if(i.forEach(r=>{r.id===e.recordingId&&(n=!0,r.state="RECORDING")}),n===!1){const r=this.getRecordingTypeFromProtoType(e.recordingType);i.push({id:e.recordingId,state:"RECORDING",type:r})}this.recording.updateRecordings(i)}),this.room.on(j.recordingPaused,e=>{const n=[...this.recording.recordings];n.forEach(i=>{i.id===e.recordingId&&(i.state="PAUSED")}),this.recording.updateRecordings(n)}),this.room.on(j.recordingStopped,e=>{const n=[...this.recording.recordings.filter(i=>i.id!==e.recordingId)];this.recording.updateRecordings(n)})}}Zu=new WeakMap;yO([E.trace("RecordingController.setupEvents")],Ty.prototype,"setupEvents",1);class SO{static hasFeature(e){var n;return(n=Z.hasFeature(e))!=null?n:!1}static getFeatureValue(e){return Z.getValue(e)}static getAllFeatures(){return Z.getAllFlags()}}class mp{constructor(e,n,i){g(this,"logger"),g(this,"features"),g(this,"browserSpecs"),g(this,"callStats"),this.logger=e,this.features=n,this.browserSpecs=Pe,this.callStats=i}static init(e){return new mp(p,SO,e)}}class gp{constructor(e){g(this,"internals"),this.internals=e}static init(){return u(this,null,function*(){const e=mp.init(K);return new gp(e)})}}var EO=Object.defineProperty,TO=Object.getOwnPropertyDescriptor,Qt=(t,e,n,i)=>{for(var r=i>1?void 0:i?TO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&EO(e,n,r),r},et,Ke,Me,$n,fn,Wc,eh;class Bt extends Bs{constructor(e,n,i=th,r=!0){super(),f(this,et,void 0),f(this,Ke,void 0),f(this,Me,void 0),f(this,$n,void 0),f(this,fn,void 0),f(this,Wc,void 0),f(this,eh,void 0),g(this,"audioUpdateInProgress"),g(this,"videoUpdateInProgress"),v(this,eh,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,v(this,et,new ky(e,n)),v(this,Ke,new HO(o(this,et),void 0,i)),v(this,Me,new YO(o(this,et),void 0,i)),v(this,fn,new $O(o(this,et))),v(this,$n,new GO(o(this,et))),v(this,Wc,r),o(this,Ke).on("trackMuted",this.onAudioTrackMuted.bind(this)),o(this,Ke).on("trackChanged",this.onAudioTrackChanged.bind(this)),o(this,Me).on("trackChanged",this.onVideoTrackChanged.bind(this)),o(this,Me).on("trackEnded",this.onVideoTrackEnded.bind(this)),o(this,fn).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}onVisibilityChange(){return u(this,null,function*(){K.tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?K.browserBackgrounded():(K.browserForegrounded(),yield this.setupSpeaker())})}repopulateAvailableDevices(){return u(this,null,function*(){return!0})}setupStreams(e){return u(this,arguments,function*({audio:n,video:i}){var r;n?K.audioOn():K.audioOff(),i?K.videoOn():K.videoOff();let s,a;if(n&&i)try{const c=yield o(this,et).getAudioAndVideoTrack(o(this,Ke).userSelectedDevice,o(this,Me).userSelectedDevice);s=c.audioTrack,a=c.videoTrack}catch(c){p.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!s&&n)try{s=yield o(this,et).getAudioTrack(!1,o(this,Ke).userSelectedDevice)}catch(c){p.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!a&&i)try{a=yield o(this,et).getVideoTrack(o(this,Me).userSelectedDevice)}catch(c){p.error("LocalMediaHandler::init::Failed to get video track",{error:c})}n&&!s&&K.audioOff(),i&&!a&&K.videoOff(),yield o(this,Ke).setMediaTrack(s),yield o(this,Me).setMediaTrack(a);try{yield o(this,$n).setupSpeaker()}catch{}if(a){const c=yield this.getDeviceById(a.getSettings().deviceId);K.selectedDevice("VIDEO",c)}if(s){const c=yield this.getDeviceById(s.getSettings().deviceId);K.selectedDevice("AUDIO",c)}(r=o(this,$n).currentDevice)!=null&&r.deviceId&&K.selectedDevice("SPEAKER",o(this,$n).currentDevice),o(this,et).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})})}getCurrentDevices(){return{audio:o(this,Ke).currentDevice,video:o(this,Me).currentDevice,speaker:o(this,$n).currentDevice}}get permissions(){return o(this,et).permissions}getAllDevices(){return o(this,et).getAvailableDevices()}getDeviceById(e,n){return o(this,et).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return o(this,Ke).mediaTrack}get audioTrack(){return o(this,Ke).transformedMediaTrack}get audioEnabled(){return o(this,Ke).trackEnabled}enableAudio(){return u(this,null,function*(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{yield o(this,Ke).unmuteTrack()}catch{}finally{this.audioUpdateInProgress=!1}}})}disableAudio(){o(this,Ke).muteTrack()}getAudioDevices(e){return o(this,et).getAudioInputDevices(e)}setAudioDevice(e){return u(this,null,function*(){yield o(this,Ke).setDevice(e),e!=null&&e.deviceId&&K.selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return o(this,$n).setupSpeaker()}setSpeakerDevice(e){return u(this,null,function*(){yield o(this,$n).setupSpeaker(e),e!=null&&e.deviceId&&K.selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return o(this,Me).mediaTrack}get videoTrack(){return o(this,Me).transformedMediaTrack}get videoEnabled(){return o(this,Me).trackEnabled}enableVideo(){return u(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{yield o(this,Me).unmuteTrack()}catch{}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){o(this,Me).disableTrack()}getVideoDevices(e){return o(this,et).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield o(this,Me).setDevice(e),e!=null&&e.deviceId&&K.selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}updateVideoConstraints(e){return u(this,null,function*(){yield o(this,Me).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:o(this,fn).audioMediaTrack,video:o(this,fn).videoMediaTrack}}get screenShareEnabled(){return o(this,fn).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield o(this,fn).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){o(this,fn).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield o(this,fn).updateConstraints(e)})}getSpeakerDevices(e){return o(this,et).getAudioOutputDevices(e)}addAudioMiddleware(e){return o(this,Ke).addMiddleware(e)}removeAudioMiddleware(e){return o(this,Ke).removeMiddleware(e)}removeAllAudioMiddlewares(){return o(this,Ke).removeAllMiddlewares()}addVideoMiddleware(e){return o(this,Me).addMiddleware(e)}removeVideoMiddleware(e){return o(this,Me).removeMiddleware(e)}removeAllVideoMiddlewares(){return o(this,Me).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return o(this,Me).setVideoMiddlewareGlobalConfig(e)}destruct(){o(this,Ke).disableTrack(),o(this,Me).disableTrack(),o(this,Me).terminateMiddlewareWebWorker(),o(this,fn).disableScreenShare(),o(this,et).destruct()}onDeviceChange(e,n){return u(this,null,function*(){var i,r;this.emit("DEVICE_LIST_UPDATED",e),!(n||!o(this,Wc))&&((i=e==null?void 0:e.added)==null||i.forEach(s=>u(this,null,function*(){var a;s&&!th(s)&&(s.kind==="audioinput"&&((a=this.audioTrack)==null?void 0:a.enabled)===!0?yield this.setAudioDevice(s):s.kind==="audiooutput"&&(yield this.setSpeakerDevice(s)))})),(r=e==null?void 0:e.removed)==null||r.forEach(s=>u(this,null,function*(){var a;if(s.kind==="audiooutput"&&((a=this.getCurrentDevices().speaker)==null?void 0:a.deviceId)===s.deviceId){const c=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==s.deviceId);c&&(yield this.setSpeakerDevice(c))}})))})}removeAllTracks(){this.destruct()}removeAudioTrack(){o(this,Ke).disableTrack()}removeVideoTrack(){o(this,Me).disableTrack(),o(this,Me).terminateMiddlewareWebWorker()}removeDocumentEventListeners(){return u(this,null,function*(){document.removeEventListener("visibilitychange",this.onVisibilityChange)})}}et=new WeakMap,Ke=new WeakMap,Me=new WeakMap,$n=new WeakMap,fn=new WeakMap,Wc=new WeakMap,eh=new WeakMap;Qt([E.trace("MediaHandler.setupStreams")],Bt.prototype,"setupStreams",1);Qt([E.trace("MediaHandler.enableAudio")],Bt.prototype,"enableAudio",1);Qt([E.trace("MediaHandler.disableAudio")],Bt.prototype,"disableAudio",1);Qt([E.trace("MediaHandler.setAudioDevice")],Bt.prototype,"setAudioDevice",1);Qt([E.trace("MediaHandler.enableVideo")],Bt.prototype,"enableVideo",1);Qt([E.trace("MediaHandler.disableVideo")],Bt.prototype,"disableVideo",1);Qt([E.trace("MediaHandler.setVideoDevice")],Bt.prototype,"setVideoDevice",1);Qt([E.trace("MediaHandler.updateVideoConstraints")],Bt.prototype,"updateVideoConstraints",1);Qt([E.trace("MediaHandler.enableScreenShare")],Bt.prototype,"enableScreenShare",1);Qt([E.trace("MediaHandler.disableScreenShare")],Bt.prototype,"disableScreenShare",1);Qt([E.trace("MediaHandler.updateScreenshareConstraints")],Bt.prototype,"updateScreenshareConstraints",1);Qt([E.trace("MediaHandler.destruct")],Bt.prototype,"destruct",1);Qt([E.trace("MediaHandler.onDeviceChange")],Bt.prototype,"onDeviceChange",1);function gc(t,e,n){switch(!0){case Pe.isChromiumBased():switch(e){case"NotAllowedError":return n.includes("by system")?"SYSTEM_DENIED":t==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Pe.isSafari():switch(e){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Pe.isFirefox():switch(e){case"NotFoundError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const kO=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function th(t){var e,n;const i=(e=t.label)==null?void 0:e.toLowerCase();return((n=Pe._bowser)==null?void 0:n.getOSName())==="macOS"&&i.includes("iphone")?(p.log("isVirtualDevice::ignore_macos_continuity"),!0):kO.some(r=>i==null?void 0:i.includes(r))}function bO(t,e){return u(this,null,function*(){if(!(t!=null&&t.length))return e;const n=new AudioContext,i=yield Promise.all(t==null?void 0:t.map(a=>a(n))),r=n.createMediaStreamSource(new MediaStream([e])),s=n.createMediaStreamDestination();try{let a=r;for(let c=0;c<i.length;c+=1)a.connect(i[c]),a=i[c];a.connect(s)}catch(a){return p.error("getTransformedAudioTrack::middleware_execution_failed",{error:a}),e}return s.stream.getAudioTracks()[0]})}var as;class _O{constructor(){f(this,as,void 0)}terminateMiddlewareWebWorker(){if(o(this,as))try{ks(o(this,as)),v(this,as,void 0)}catch{p.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}getTransformedVideoTrack(e,n,i){return u(this,null,function*(){if(!(e!=null&&e.length))return n;const r=document.createElement("canvas"),s=yield Promise.all(e==null?void 0:e.map(m=>m({canvas:r,WorkerTimers:mE})));if(i.disablePerFrameCanvasRendering){const m=r.captureStream().getVideoTracks()[0];return Object.defineProperty(m,"originalSettings",{value:n.getSettings()}),m}const a=document.createElement("video"),c=new MediaStream;c.addTrack(n);const d=r.getContext("2d");a.srcObject=c,a.autoplay=!0,this.terminateMiddlewareWebWorker();const l=()=>u(this,null,function*(){if(n.enabled===!1||n.readyState==="ended"){this.terminateMiddlewareWebWorker(),a.remove(),r.remove();return}try{d.drawImage(a,0,0);for(let m=0;m<s.length;m+=1)typeof s[m]=="function"&&(yield s[m](r,d))}catch(m){p.error("getTransformedVideoTrack::middleware_execution_failed",{error:m})}});try{a.play()}catch{}a.addEventListener("play",()=>{r.width=a.width||n.getSettings().width,r.height=a.width||n.getSettings().height,v(this,as,yd(l,50))},!1);const h=r.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:n.getSettings()}),h})}}as=new WeakMap;const Vg={gross:{width:{ideal:192},height:{ideal:144}},qvga:{width:{ideal:384},height:{ideal:288}},pvga:{width:{ideal:480},height:{ideal:360}},vga:{width:{ideal:640},height:{ideal:480}},hd:{width:{ideal:1280},height:{ideal:720}},hd_cropped:{width:{ideal:900},height:{ideal:720}},fhd:{width:{ideal:1920},height:{ideal:1080}}},wO=[[320,[{rid:"q",maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"}]],[640,[{rid:"q",scaleResolutionDownBy:2,maxBitrate:25e4,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:7e5,maxFramerate:30,scalabilityMode:"L1T1"}]],[1280,[{rid:"q",scaleResolutionDownBy:2,maxBitrate:5e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:13e5,maxFramerate:30,scalabilityMode:"L1T1"}]],[1920,[{rid:"q",scaleResolutionDownBy:2,maxBitrate:9e5,maxFramerate:24,scalabilityMode:"L1T1"},{rid:"h",maxBitrate:15e5,maxFramerate:30,scalabilityMode:"L1T1"}]]],IO=t=>{var e;const n="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((e=t.originalSettings)==null?void 0:e.width);let i=wO;Z.hasFeature(re.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)&&(i=JSON.parse(Z.getValue(re.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)));const r=i.map(([c])=>c).sort((c,d)=>c-d);let s=Number.MAX_VALUE,a=0;return r.forEach((c,d)=>{Math.abs(c-n)<s&&(s=Math.abs(c-n),a=d)}),i[a][1]};var ke=(t=>(t.WEBCAM="webcam",t.WEBCAM_BACKUP="webcam_backup",t.MIC="mic",t.SCREENSHARE_VIDEO="screenshare_video",t.SCREENSHARE_AUDIO="screenshare_audio",t))(ke||{});const CO=uw(),Qr=kn(CO.config.media);function PO(t){var e,n;const i={};return t.audio&&(i.audio={enableStereo:(e=t.audio.enableStereo)!=null?e:!1,enableHighBitrate:(n=t.audio.enableHighBitrate)!=null?n:!1}),i.video=t.video.quality,i}var os,nh;class RO{constructor(e,n){f(this,os,void 0),f(this,nh,void 0),g(this,"getScreenShareConstraints",()=>{var i,r,s,a,c,d,l,h,m,y,S;const b=(i=o(this,os))==null?void 0:i.screenshare,D=(s=(r=b==null?void 0:b.width)==null?void 0:r.max)!=null?s:1920,C=(c=(a=b==null?void 0:b.height)==null?void 0:a.max)!=null?c:1080,V=(l=(d=b==null?void 0:b.frameRate)==null?void 0:d.max)!=null?l:5;let L=(m=(h=b==null?void 0:b.frameRate)==null?void 0:h.ideal)!=null?m:5;const q=b==null?void 0:b.displaySurface,w=b==null?void 0:b.selfBrowserSurface;Z.getValue(re.VAL_MIN_FRAMERATE)&&(L=parseInt((y=Z.getValue(re.VAL_MIN_FRAMERATE))==null?void 0:y.toString(),10));let X={width:{max:D},height:{max:C},frameRate:{ideal:L,max:V}};if(Z.hasFeature(re.SCREENSHARE_CONSTRAINTS)){const ae=(S=Z.getValue(re.SCREENSHARE_CONSTRAINTS))==null?void 0:S.toString();X=JSON.parse(ae)}return q!==void 0&&["monitor","browser","window"].includes(q)&&(X=J(U({},X),{displaySurface:q})),w!==void 0&&(X=J(U({},X),{selfBrowserSurface:w})),{audio:!0,video:X}}),g(this,"getAudioConstraints",i=>{var r,s,a,c,d,l,h,m;const y={},S=(r=o(this,os))==null?void 0:r.audio,b=S!=null&&S.enableStereo?2:1;return Pe.isFirefox()||Pe.isWebKitBased()?(y.audio={deviceId:i,autoGainControl:(s=S==null?void 0:S.autoGainControl)!=null?s:!0,echoCancellation:(a=S==null?void 0:S.echoCancellation)!=null?a:!0,noiseSuppression:(c=S==null?void 0:S.noiseSupression)!=null?c:!0,channelCount:b},y):(y.audio={},y.audio.optional=[i?{sourceId:i}:{sourceId:"default"},{channelCount:b},{echoCancellation:(d=S==null?void 0:S.echoCancellation)!=null?d:!0},{googEchoCancellation:(l=S==null?void 0:S.echoCancellation)!=null?l:!0},{googAutoGainControl:(h=S==null?void 0:S.autoGainControl)!=null?h:!0},{googNoiseSuppression:(m=S==null?void 0:S.noiseSupression)!=null?m:!0},{googHighpassFilter:!0}],y)}),g(this,"getVideoConstraints",i=>{var r,s,a,c;const d={},l=(r=o(this,os))==null?void 0:r.video;let h=Vg.vga;if(typeof l=="string"?h=Vg[l]:l!==void 0&&(h.height.ideal=l.height.ideal,h.width.ideal=l.width.ideal),h.frameRate={ideal:(a=(s=h.frameRate)==null?void 0:s.ideal)!=null?a:24},Pe.isChromiumBased()&&(h.frameRate.max=30),Z.hasFeature(re.VIDEO_CONSTRAINTS)){const m=(c=Z.getValue(re.VIDEO_CONSTRAINTS))==null?void 0:c.toString();h=JSON.parse(m)}return d.video=h,typeof d.video=="boolean"||(i?d.video.deviceId={exact:i}:d.video.facingMode="user"),d}),v(this,nh,e),v(this,os,n)}getUpdatedVideoConstraints(e){return e}}os=new WeakMap,nh=new WeakMap;class iu extends Error{constructor(e,n,i){super(n),g(this,"constraints"),g(this,"name"),this.name=e,this.constraints=i}}class MO{constructor(){g(this,"permissions"),this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}getAudioInputDevices(e){return u(this,null,function*(){let n=e;return e||(n=yield this.getAvailableDevices()),n.filter(i=>i.kind==="audioinput")})}getVideoInputDevices(e){return u(this,null,function*(){let n=e;return e||(n=yield this.getAvailableDevices()),n.filter(i=>i.kind==="videoinput")})}getAudioOutputDevices(e){return u(this,null,function*(){let n=e;return e||(n=yield this.getAvailableDevices()),n.filter(i=>i.kind==="audiooutput")})}}var AO=Object.defineProperty,DO=Object.getOwnPropertyDescriptor,Cn=(t,e,n,i)=>{for(var r=i>1?void 0:i?DO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&AO(e,n,r),r},ka,dn,ru,Ug;let Kt=(Ug=class extends MO{constructor(t,e){super(),g(this,"availableDevices"),f(this,ka,void 0),f(this,dn,void 0),f(this,ru,void 0),v(this,ru,t),v(this,dn,new RO(t,e)),v(this,ka,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return o(this,dn)}destruct(){return u(this,null,function*(){var t;(t=o(this,ka))==null||t.abort()})}handlePermissionErrors(t,e){const n=gc(t,e.name,e.message);return this.permissions[t]=n,R.emit(M.MEDIA_PERMISSION_ERROR,{message:n,constraints:e.constraints,kind:t}),n}getAudioAndVideoTrack(t,e){return u(this,null,function*(){const n={audio:o(this,dn).getAudioConstraints(t).audio,video:o(this,dn).getVideoConstraints(e).video};try{p.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(n)});const i=yield navigator.mediaDevices.getUserMedia(n);p.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(n)});const r=i.getAudioTracks()[0];let s=i.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",Z.hasFeature(re.OBS_QUALITY)&&s.label.includes("OBS Virtual")){const a=(yield this.getVideoInputDevices()).find(c=>c.label.includes("OBS Virtual"));s=yield this.getVideoTrack(a.deviceId)}return R.emit(M.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),R.emit(M.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:r,videoTrack:s}}catch(i){throw p.error("WebMediaInterface.getAudioAndVideoTrack",{error:i}),new I("Couldnt fetch audio and video track","1605")}})}getAudioTrack(t,e){return u(this,null,function*(){let n=yield this.getAudioInputDevices();if(n.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",R.emit(M.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new I("No audio devices available","1606");const i=r=>u(this,null,function*(){let s;try{n=n.filter(c=>c.deviceId!==r),s=o(this,dn).getAudioConstraints(r),p.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(s)});const[a]=(yield navigator.mediaDevices.getUserMedia(s)).getAudioTracks();return p.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(s)}),a}catch(a){const c=gc("audio",a.name,a.message),d=new iu(a.name,a.message,s);if(c==="COULD_NOT_START"){const l=n.shift();if(!l)throw d;p.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(s),error:a});const h=o(this,dn).getAudioConstraints(l.deviceId);return p.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(h)}),i(l.deviceId)}throw d}});try{const r=yield i(e);return r.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",R.emit(M.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),r}catch(r){throw r.constraints&&this.handlePermissionErrors("audio",r),new I(r.message,"1601")}})}getVideoTrack(t){return u(this,null,function*(){var e;const n=Z.hasFeature(re.OBS_QUALITY),i=(e=yield this.getCurrentDeviceLabel(t))==null?void 0:e.includes("OBS Virtual"),r=n&&i,s=yield this.getVideoInputDevices();if(s.length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",R.emit(M.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new I("No video devices available","1607");const a=c=>u(this,null,function*(){try{let d=c;const{video:l}=d;r&&typeof l!="boolean"&&(d={video:{deviceId:l.deviceId}}),p.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(d)});const[h]=(yield navigator.mediaDevices.getUserMedia(d)).getVideoTracks();if(r&&typeof l!="boolean"&&typeof l.width=="object"){const{width:m,height:y}=h.getSettings(),{ideal:S}=l.width;h.applyConstraints({width:{ideal:S},height:{ideal:Math.floor(y*S/m)},frameRate:l.frameRate})}return p.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(d)}),h}catch(d){const l=gc("video",d.name,d.message),h=new iu(d.name,d.message,c);if(l==="COULD_NOT_START"){const m=s.shift();if(!m)throw h;p.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(c),error:d});const y=o(this,dn).getVideoConstraints(m.deviceId);return p.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(y)}),a({video:y.video})}throw h}});try{const c=o(this,dn).getVideoConstraints(t),d=yield a(c);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",R.emit(M.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),d}catch(c){throw c.constraints&&this.handlePermissionErrors("video",c),new I(c.message,"1602")}})}getScreenShareTracks(){return u(this,null,function*(){const t=e=>u(this,null,function*(){try{p.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),K.screenShareRequested();const n=yield navigator.mediaDevices.getDisplayMedia(e);return p.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),n}catch(n){const i=gc("video",n.name,n.message),r=new iu(n.name,n.message,e),s={video:!0};if(DI(e,s)||!Z.hasFeature(re.SCREEENSHARE_CONSTRAINTS_RETRY))throw r;if(i==="COULD_NOT_START")return t(s);throw r}});try{const e=o(this,dn).getScreenShareConstraints(),n=yield t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",R.emit(M.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:n.getAudioTracks()[0],videoTrack:n.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new I(e.message,"1612")}})}getCurrentDeviceLabel(t){return u(this,null,function*(){const e=yield this.getDevice(t||"default");return e==null?void 0:e.label})}getAvailableDevices(){return u(this,null,function*(){try{const t=yield navigator.mediaDevices.enumerateDevices();return this.availableDevices=t,t}catch(t){throw p.error("enumerate_devices_failed",{error:t}),new I("Failed to get available devices","1609")}})}getAvailableDevicesByKind(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(({kind:e})=>t===e)}catch(e){throw p.error("enumerate_devices_failed",{error:e}),new I("Failed to get available devices by kind","1609")}})}getDevice(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.deviceId===t)[0]}catch(e){throw p.error("enumerate_devices_failed",{error:e}),new I("Failed to get device","1609")}})}onDeviceChange(t){return u(this,null,function*(){Pe.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",e=>u(this,null,function*(){var n,i;const r=h=>`${h.kind}-${h.deviceId}-${h.groupId}`,s=this.availableDevices,a=new Set(s.map(h=>r(h))),c=yield this.getAvailableDevices(),d=new Set(c.map(h=>r(h))),l={added:c.filter(h=>!a.has(r(h))),removed:s.filter(h=>!d.has(r(h))),devices:c};if((n=l.added)!=null&&n.length||(i=l.removed)!=null&&i.length){p.info("repopulated_full_device_list",{devices:JSON.stringify(c)});const h=[...l.added,...l.removed];h.some(m=>m.kind==="audioinput")&&K.devices("AUDIO",c==null?void 0:c.filter(m=>m.kind==="audioinput")),h.some(m=>m.kind==="videoinput")&&K.devices("VIDEO",c==null?void 0:c.filter(m=>m.kind==="videoinput")),h.some(m=>m.kind==="audiooutput")&&K.devices("SPEAKER",c==null?void 0:c.filter(m=>m.kind==="audiooutput")),t(e,l,!1)}}),{signal:o(this,ka).signal})})}},ka=new WeakMap,dn=new WeakMap,ru=new WeakMap,Ug);Cn([E.trace("WebMediaInterface.destruct")],Kt.prototype,"destruct",1);Cn([E.trace("WebMediaInterface.handlePermissionErrors")],Kt.prototype,"handlePermissionErrors",1);Cn([E.trace("WebMediaInterface.getAudioAndVideoTrack")],Kt.prototype,"getAudioAndVideoTrack",1);Cn([E.trace("WebMediaInterface.getAudioTrack")],Kt.prototype,"getAudioTrack",1);Cn([E.trace("WebMediaInterface.getVideoTrack")],Kt.prototype,"getVideoTrack",1);Cn([E.trace("WebMediaInterface.getScreenShareTracks")],Kt.prototype,"getScreenShareTracks",1);Cn([E.trace("WebMediaInterface.getAvailableDevices")],Kt.prototype,"getAvailableDevices",1);Cn([E.trace("WebMediaInterface.getAvailableDevicesByKind")],Kt.prototype,"getAvailableDevicesByKind",1);Cn([E.trace("WebMediaInterface.getDevice")],Kt.prototype,"getDevice",1);Cn([E.trace("WebMediaInterface.onDeviceChange")],Kt.prototype,"onDeviceChange",1);Kt=Cn([gt("1600")],Kt);const ky=Kt,fo={setItem:(t,e)=>{try{localStorage.setItem(t,e)}catch(n){p.error("LocalStorage::setItem::crashed",{error:n,localStorage:{key:t,value:e}})}},getItem:t=>{try{return localStorage.getItem(t)}catch(e){p.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:t}})}return null}},OO=(t=0)=>new Promise(e=>setTimeout(e,t)),NO=(t,e,n)=>{const i=typeof n=="number"?n:250,r=t.createMediaStreamSource(e),s=t.createAnalyser();s.fftSize=2048,r.connect(s);const a=new Uint8Array(s.fftSize);let c=!1;setTimeout(()=>{c=!0},i);function d(){return c?Promise.resolve(!0):(s.getByteTimeDomainData(a),a.some(l=>l!==128&&l!==0)?Promise.resolve(!1):OO().then(d))}return d().then(l=>(r.disconnect(),l),l=>{throw r.disconnect(),l})},LO=typeof AudioContext!="undefined"?AudioContext:null;class fp{constructor(e){g(this,"_AudioContext"),g(this,"audioContext"),g(this,"_audioContextRefContainers");const n=U({AudioContext:LO},e);Object.defineProperties(this,{_AudioContext:{value:n.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:fp}})}getOrCreate(e){if(!this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.add(e),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch{}return this.audioContext}release(e){this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.delete(e),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const Fg=new fp,xO=3,VO=250;function UO(t){const e={},n=Fg.getOrCreate(e);let i=xO;function r(){return i-=1,NO(n,t.srcObject,VO).then(s=>s?i>0?r():!0:!1).catch(()=>!0)}return r().finally(()=>{Fg.release(e)})}function Bg(t){return u(this,null,function*(){const e=new Audio,n=new MediaStream;n.addTrack(t),e.srcObject=n;let i=!1;try{const r=e.play();r&&(yield r),i=yield UO(e),i&&p.info("checkIfAudioTrackIsSilent::silence_detected")}catch(r){p.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:r})}finally{e.pause(),e.remove()}return i})}var FO=Object.defineProperty,BO=Object.getOwnPropertyDescriptor,by=(t,e,n,i)=>{for(var r=i>1?void 0:i?BO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&FO(e,n,r),r};let Od=class extends Bs{constructor(t,e,n){var i;super(),g(this,"constructorName",this.constructor.name),g(this,"userSelectedDevice"),g(this,"mediaInterface"),g(this,"isNonPreferredDevice"),g(this,"_mediaTrack"),g(this,"transformedMediaTrack"),g(this,"middlewares",[]),g(this,"currentDevice"),g(this,"userPreferredDeviceKey",`Dyte::${this.constructorName}::UserDeviceID`),g(this,"setUserPreferredDevice",r=>fo.setItem(this.userPreferredDeviceKey,r)),g(this,"getUserPreferredDevice",()=>fo.getItem(this.userPreferredDeviceKey)),this.mediaInterface=t,e&&this.setMediaTrack(e),this.userSelectedDevice=(i=this.getUserPreferredDevice())!=null?i:void 0,this.isNonPreferredDevice=n,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}disableTrack(){var t,e;this.removeMediaTrackListeners(),(t=this._mediaTrack)==null||t.stop(),this._mediaTrack=void 0,(e=this.transformedMediaTrack)==null||e.stop(),this.transformedMediaTrack=void 0}get mediaTrack(){return this._mediaTrack}setMediaTrack(t){return u(this,null,function*(){const e=n=>{p.error(`${this.constructorName}.setMediaTrack.error`,{error:n})};try{this.disableTrack()}catch(n){e(n)}this._mediaTrack=yield this.conditionallyChangeTrack(t),yield this.setTransformedTrack();try{this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(n){e(n)}})}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){p.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}unmuteTrack(){return u(this,null,function*(){try{this.mediaTrack?this.mediaTrack.enabled=!0:yield this.enableTrack(!1)}catch(t){throw p.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new I("Failed to unmute track","1611")}})}getCurrentDeviceId(){var t,e;const{kind:n}=this.mediaTrack;switch(n){case"audio":{const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(e=(t=i==null?void 0:i.deviceId)!=null?t:i==null?void 0:i.advanced[0].deviceId)!=null?e:this.mediaTrack.getSettings().deviceId:this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}setCurrentDevice(){return u(this,null,function*(){var t;if(!this.mediaTrack){this.currentDevice=void 0;return}const e=this.getCurrentDeviceId();((t=this.currentDevice)==null?void 0:t.deviceId)!==e&&(this.currentDevice=yield this.mediaInterface.getDevice(e))})}setDevice(t){return u(this,null,function*(){if(!t)throw p.warn(`${this.constructorName}.setDevice No device received`),new I("No device received!","1603");this.userSelectedDevice=t.deviceId,this.setUserPreferredDevice(t.deviceId),this.onSetDevice(t)})}addMiddleware(t){return u(this,null,function*(){if(Pe.isWebKitBased()&&!Z.hasFeature(re.ALLOW_SAFARI_MEDIA_MIDDLEWARES))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&(yield this.setTransformedTrack()),{success:!0,message:"Successfully added the middleware."}}catch(e){return p.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}})}removeMiddleware(t){return u(this,null,function*(){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),yield this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(n){return p.error("While removing middleware",{error:n}),{success:!1,message:n==null?void 0:n.message}}return{success:!1,message:"No such middleware was found. Skipping."}})}removeAllMiddlewares(){return u(this,null,function*(){var t;if((t=this.middlewares)!=null&&t.length)try{return this.middlewares=[],yield this.setTransformedTrack(!0),{success:!0,message:"Successfully removed all the middlewares."}}catch(e){return p.error("While removing all the middlewares",{error:e}),{success:!1,message:e==null?void 0:e.message}}return{success:!1,message:"No middlewares were found. Skipping."}})}addMediaTrackListeners(){var t,e,n;this.mediaTrack&&(p.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(n=this.mediaTrack)==null?void 0:n.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,n;this.mediaTrack&&(p.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(n=this.mediaTrack)==null?void 0:n.kind}`),p.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};by([E.trace("BaseMediaHandler.unmuteTrack")],Od.prototype,"unmuteTrack",1);Od=by([gt("1600")],Od);const _y=Od;var WO=Object.defineProperty,jO=Object.getOwnPropertyDescriptor,vp=(t,e,n,i)=>{for(var r=i>1?void 0:i?jO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&WO(e,n,r),r};const su="[Dyte]nonSilentDeviceLabels";class pl extends _y{onSetDevice(e){return u(this,null,function*(){if(!e)throw p.warn("AudioMediaHandler.setDevice No device received"),new I("No device received!","1603");if(e.kind!=="audioinput")throw p.warn("AudioMediaHandler.setDevice Received non audio device"),new I("Non audio device received while setting device!","1603");try{const n=this.trackEnabled;yield this.setMediaTrack(yield this.mediaInterface.getAudioTrack(!n,this.userSelectedDevice)),this.userSelectedDevice=void 0}catch(n){throw p.error("AudioMediaHandler.setDevice.error",{error:n}),this.disableTrack(),new I(n.message,"1604")}})}enableTrack(e){return u(this,null,function*(){if(this.trackEnabled){p.warn("AudioMediaHandler.enableTrack Track already enabled!");return}const n=yield this.mediaInterface.getAudioTrack(e,this.userSelectedDevice);yield this.setMediaTrack(n)})}setTransformedTrack(e){return u(this,null,function*(){var n;if(!e&&!((n=this.middlewares)!=null&&n.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield bO(this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(i){p.error("AudioMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}})}onTrackEnded(){return u(this,null,function*(){p.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const e=this.mediaTrack.enabled;this.disableTrack(),yield this.enableTrack(!e),yield this.setTransformedTrack(),this.emit("trackChanged")})}onTrackMuted(){p.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){var n;if(!e||this.userSelectedDevice)return e;let i=e;const r=yield this.mediaInterface.getAudioInputDevices(),s=this.isNonPreferredDevice?r.filter(d=>d&&!this.isNonPreferredDevice(d)):r;if(!(s!=null&&s.length))return i;s.find(d=>d.deviceId===e.getSettings().deviceId)||(i.stop(),p.info("localmediahandler::setupstreams::found_audio_non_preferred"),i=yield this.mediaInterface.getAudioTrack(!1,s[0].deviceId));const a=JSON.parse(fo.getItem(su));if(a!=null&&a.devices.some(d=>d.label===i.label))return i;if(!(yield Bg(i))){const d=(n=a==null?void 0:a.devices.concat({label:i.label}))!=null?n:[{label:i.label}];return fo.setItem(su,JSON.stringify({devices:d})),i}p.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=i.getSettings().deviceId;return s.filter(d=>d.deviceId!==c).some(d=>u(this,null,function*(){if(i=yield this.mediaInterface.getAudioTrack(!1,d.deviceId),!(yield Bg(i))){const l=a.devices.concat({label:i.label});return fo.setItem(su,JSON.stringify({devices:l})),p.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return p.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),i})}}vp([E.trace("AudioMediaHandler.setTransformedTrack")],pl.prototype,"setTransformedTrack",1);vp([E.trace("AudioMediaHandler.onTrackEnded")],pl.prototype,"onTrackEnded",1);vp([E.trace("AudioMediaHandler.conditionallyChangeTrack")],pl.prototype,"conditionallyChangeTrack",1);const HO=pl;var Ba;class qO{constructor(e){f(this,Ba,void 0),g(this,"currentDevice"),v(this,Ba,e)}setupSpeaker(e){return u(this,null,function*(){var n,i;if(!(o(this,Ba)instanceof ky))return;let r=e;if(e||([r]=(yield o(this,Ba).getAvailableDevicesByKind("audiooutput")).filter(a=>!th(a))),!r)throw new I("No speaker found","1608");if(((n=this.currentDevice)==null?void 0:n.deviceId)===r.deviceId)return;this.currentDevice=r;const s=document.querySelectorAll("audio");(i=s[0])!=null&&i.setSinkId&&s.forEach(a=>u(this,null,function*(){if(typeof a.sinkId!="undefined"&&this.currentDevice.deviceId&&a.sinkId!==this.currentDevice.deviceId)try{yield a.setSinkId(this.currentDevice.deviceId)}catch{}}))})}}Ba=new WeakMap;const GO=qO;class JO extends Bs{constructor(e){super(),g(this,"mediaInterface"),g(this,"audioMediaTrack"),g(this,"videoMediaTrack"),this.mediaInterface=e}get trackEnabled(){return!!this.videoMediaTrack}enableScreenShare(){return u(this,null,function*(){var e,n;try{const{audioTrack:i,videoTrack:r}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=r,this.addMediaTrackListeners(),((n=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:n.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",R.emit(M.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch{}})}disableScreenShare(){var e,n;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(n=this.videoMediaTrack)==null||n.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}updateConstraints(e){return u(this,null,function*(){if(!this.videoMediaTrack)throw new I("No media track enabled!","1610");const n=this.mediaInterface;if(!n.constraintsBuilder)throw new I("update constraints not supported for non web clients","1100");try{this.videoMediaTrack.applyConstraints(n.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){p.error("ScreenShareHandler.updateConstraints.error",{error:i})}})}addMediaTrackListeners(){var e,n;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),Pe.isWebKitBased()&&((n=this.videoMediaTrack)==null||n.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,n;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(n=this.videoMediaTrack)==null||n.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}const $O=JO;var KO=Object.defineProperty,zO=Object.getOwnPropertyDescriptor,ml=(t,e,n,i)=>{for(var r=i>1?void 0:i?zO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&KO(e,n,r),r},Wa,jc;class Jo extends _y{constructor(e,n,i){super(e,n,i),f(this,Wa,void 0),f(this,jc,{disablePerFrameCanvasRendering:!1}),v(this,Wa,new _O)}onSetDevice(e){return u(this,null,function*(){if(!e)throw p.warn("VideoMediaHandler.setDevice No device received"),new I("No device received!","1603");if(e.kind!=="videoinput")throw p.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new I("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){p.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(n){throw p.error("VideoMediaHandler.setDevice.error",{error:n}),this.disableTrack(),new I("Failed to change device","1600")}})}enableTrack(){return u(this,null,function*(){if(this.trackEnabled){p.warn("VideoMediaHandler.enableTrack Track already enabled!");return}yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))})}setTransformedTrack(e){return u(this,null,function*(){var n;if(!e&&!((n=this.middlewares)!=null&&n.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield o(this,Wa).getTransformedVideoTrack(this.middlewares,this.mediaTrack,o(this,jc)),this.emit("trackChanged")}catch(i){p.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return u(this,null,function*(){v(this,jc,e)})}updateConstraints(e){return u(this,null,function*(){if(!this._mediaTrack)throw new I("No media track enabled!","1610");const n=this.mediaInterface;if(!n.constraintsBuilder)throw new I("update constraints not supported for non web clients","1100");try{this._mediaTrack.applyConstraints(n.constraintsBuilder.getUpdatedVideoConstraints(e)),yield this.setTransformedTrack(),this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(i){p.error("VideoMediaHandler.updateConstraints.error",{error:i})}})}terminateMiddlewareWebWorker(){o(this,Wa).terminateMiddlewareWebWorker()}onTrackEnded(){return u(this,null,function*(){p.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")})}onTrackMuted(){p.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){if(!e||this.userSelectedDevice)return e;let n=e;const i=yield this.mediaInterface.getVideoInputDevices(),r=this.isNonPreferredDevice?i.filter(s=>!this.isNonPreferredDevice(s)):i;return!(r!=null&&r.length)||window.FAST_DYTE||r.find(s=>s.deviceId===e.getSettings().deviceId)||(n.stop(),p.info("localmediahandler::setupstreams::found_video_non_preferred"),n=yield this.mediaInterface.getVideoTrack(r[0].deviceId)),n})}}Wa=new WeakMap,jc=new WeakMap;ml([E.trace("VideoMediaHandler.setTransformedTrack")],Jo.prototype,"setTransformedTrack",1);ml([E.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],Jo.prototype,"setVideoMiddlewareGlobalConfig",1);ml([E.trace("VideoMediaHandler.onTrackEnded")],Jo.prototype,"onTrackEnded",1);ml([E.trace("VideoMediaHandler.conditionallyChangeTrack")],Jo.prototype,"conditionallyChangeTrack",1);const YO=Jo,Wg=kn(op());var Ht,cs,Hc,ja;const Ha=class{constructor(t){if(f(this,Ht,void 0),f(this,cs,void 0),f(this,Hc,void 0),f(this,ja,void 0),!t)throw new I("Could not load preset.","0904");v(this,Ht,t.config),v(this,Hc,t.name),v(this,cs,t.ui||kn(op().ui)),v(this,ja,t.permissions.plugins.config)}static fromResponse(t){return new Ha(t)}static default(){return new Ha(Wg)}static init(t,e=!0){return!t||e?new Ha(Wg):new Ha(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:o(this,cs).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return o(this,Ht).viewType}get livestreamViewerQualities(){return o(this,Ht).livestreamViewerQualities||[]}get maxVideoStreams(){return o(this,Ht).maxVideoStreams}get maxScreenShareCount(){return o(this,Ht).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(o(this,ja)).filter(t=>o(this,ja)[t].disabled)}get designTokens(){return o(this,cs).designTokens}get configDiff(){return o(this,cs).configDiff}get mediaConstraints(){var t,e,n,i,r,s,a,c,d,l,h,m,y,S,b,D,C,V,L,q,w,X,ae,Ee;return{audio:{enableStereo:(i=(n=(e=(t=o(this,Ht))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:n.enableStereo)!=null?i:Qr.audio.enableStereo,enableHighBitrate:(c=(a=(s=(r=o(this,Ht))==null?void 0:r.media)==null?void 0:s.audio)==null?void 0:a.enableHighBitrate)!=null?c:Qr.audio.enableHighBitrate},video:{quality:(m=(h=(l=(d=o(this,Ht))==null?void 0:d.media)==null?void 0:l.video)==null?void 0:h.quality)!=null?m:Qr.video.quality,frameRate:(D=(b=(S=(y=o(this,Ht))==null?void 0:y.media)==null?void 0:S.video)==null?void 0:b.frameRate)!=null?D:Qr.video.frameRate},screenshare:{quality:(q=(L=(V=(C=o(this,Ht))==null?void 0:C.media)==null?void 0:V.screenshare)==null?void 0:L.quality)!=null?q:Qr.screenshare.quality,frameRate:(Ee=(ae=(X=(w=o(this,Ht))==null?void 0:w.media)==null?void 0:X.screenshare)==null?void 0:ae.frameRate)!=null?Ee:Qr.screenshare.frameRate}}}get name(){return o(this,Hc)}};let QO=Ha;Ht=new WeakMap,cs=new WeakMap,Hc=new WeakMap,ja=new WeakMap;var XO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,wy=(t,e,n,i)=>{for(var r=i>1?void 0:i?ZO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&XO(e,n,r),r},qa;class yp extends zt{constructor(e){super(),f(this,qa,void 0),g(this,"state","IDLE"),g(this,"playbackUrl"),g(this,"ingestionCredentials"),g(this,"viewerCount"),v(this,qa,e),this.viewerCount=0}setLivestreamState(e){const n=this.state;this.state=e,n!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}start(){return u(this,arguments,function*(e={manualIngestion:!1}){if(!o(this,qa).permissions.canLivestream)throw p.error("DyteLivestream::start::permission_denied"),new I("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const n=dt(),{playbackUrl:i,ingestionCredentials:r}=yield n.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=r,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(n){throw p.error("DyteRecording::stop::livestream_failed_to_start",{error:n}),this.setLivestreamState("IDLE"),new I("Error while starting livestream","1900")}})}stop(){return u(this,null,function*(){if(!o(this,qa).permissions.canLivestream)throw p.error("DyteLivestream::stop::permission_denied"),new I("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw p.error("DyteLivestream::stop::inconsistent_state"),new I("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),yield dt().stopLivestreaming()}catch(e){throw p.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new I("Error while stopping livestream","1900")}})}}qa=new WeakMap;wy([E.trace("livestream.start")],yp.prototype,"start",1);wy([E.trace("livestream.stop")],yp.prototype,"stop",1);var eN=Object.defineProperty,tN=Object.getOwnPropertyDescriptor,nN=(t,e,n,i)=>{for(var r=i>1?void 0:i?tN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&eN(e,n,r),r},Ga,Ja,wi;class Iy{constructor(e,n){g(this,"livestream"),f(this,Ga,void 0),f(this,Ja,void 0),f(this,wi,void 0),v(this,Ja,e),this.livestream=new yp(e),v(this,wi,n),this.setupEvents()}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=dt(),{status:n,playbackUrl:i,manualIngest:r,ingestionCredentials:s}=yield e.getActiveLivestream();this.livestream.playbackUrl=i,this.livestream.ingestionCredentials=s,n==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),n==="INVOKED"&&r&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")})}setupEvents(){o(this,wi).on(j.startedLivestream,e=>u(this,null,function*(){this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{o(this,Ja).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{p.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}})),o(this,wi).on(j.livestreamingInvoked,e=>u(this,null,function*(){if(e.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{o(this,Ja).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{p.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}})),o(this,wi).on(j.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),o(this,wi).on(j.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),o(this,wi).on(j.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),R.on(M.PEER_JOINED_INTERNAL,e=>u(this,null,function*(){var n;((n=e.flags)==null?void 0:n.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(v(this,Ga,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),R.on(M.PEER_CLOSED,e=>{e.id===o(this,Ga)&&(v(this,Ga,void 0),this.livestream.setLivestreamState("IDLE"))}),R.onAsync(M.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){this.livestream.playbackUrl||(p.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),R.on(M.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch{p.error("Error: LivestreamController.fetchLivestream")}}))}}Ga=new WeakMap,Ja=new WeakMap,wi=new WeakMap;nN([E.trace("LivestreamController.setupEvents")],Iy.prototype,"setupEvents",1);var iN=Object.defineProperty,rN=Object.getOwnPropertyDescriptor,$o=(t,e,n,i)=>{for(var r=i>1?void 0:i?rN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&iN(e,n,r),r},wt,sr,ar,ih,Cy;class Hs{constructor({name:e,socketHandler:n,meetingId:i}){f(this,ih),g(this,"name",""),f(this,wt,{}),f(this,sr,""),f(this,ar,void 0),g(this,"rateLimitConfig",{maxInvocations:5,period:1}),g(this,"bulkRateLimitConfig",{maxInvocations:5,period:1}),g(this,"listeners",{}),this.name=e,v(this,ar,n),v(this,sr,i)}set(e,n,i=!0,r=!1){return u(this,null,function*(){o(this,wt)[e]=n,i&&this.remoteSet(e,n),r&&(this.listeners[e]&&this.listeners[e].forEach(s=>s({[e]:o(this,wt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:o(this,wt)[e]})))})}remoteSet(e,n){o(this,ar).storeInsertKeys(o(this,sr),this.name,[{key:e,payload:n}])}bulkSet(e){return u(this,null,function*(){e.forEach(({key:n,payload:i})=>{o(this,wt)[n]=i}),o(this,ar).storeInsertKeys(o(this,sr),this.name,e)})}update(e,n,i=!0){return u(this,null,function*(){H(this,ih,Cy).call(this,e,n,i)})}delete(e,n=!0,i=!1){return u(this,null,function*(){if(o(this,wt)[e]&&delete o(this,wt)[e],n)return o(this,ar).storeDeleteKeys(o(this,sr),this.name,[{key:e}]);i&&(this.listeners[e]&&(this.listeners[e].forEach(r=>r({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(r=>r({[e]:void 0})))})}bulkDelete(e){return u(this,null,function*(){return e.forEach(({key:n})=>{o(this,wt)[n]&&delete o(this,wt)[n]}),o(this,ar).storeDeleteKeys(o(this,sr),this.name,e)})}get(e){if(o(this,wt)[e])return o(this,wt)[e]}getAll(){return o(this,wt)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(e,n){this.rateLimitConfig.maxInvocations=e,this.rateLimitConfig.period=n}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(e,n){this.bulkRateLimitConfig.maxInvocations=e,this.bulkRateLimitConfig.period=n}subscribe(e,n){if(this.listeners[e]){this.listeners[e].push(n);return}this.listeners[e]=[n]}unsubscribe(e,n){var i;if(n){this.listeners[e]=((i=this.listeners[e])==null?void 0:i.filter(r=>r!==n))||[];return}this.listeners[e]&&delete this.listeners[e]}populate(e){v(this,wt,e)}}wt=new WeakMap,sr=new WeakMap,ar=new WeakMap,ih=new WeakSet,Cy=function(t,e,n=!0){let i;const r=o(this,wt)[t],s=Object.prototype.toString.call(e),a=Object.prototype.toString.call(r);if(s!==a){this.set(t,e);return}switch(a){case"[object Array]":i=[...r,...e];break;case"[object Object]":i=U(U({},r),e);break;case"[object Map]":i=new Map([...r,...e]);break;case"[object Set]":i=new Set([...r,...e]);break;default:i=e;break}this.set(t,i,n)};$o([Ft(js,"rateLimitConfig")],Hs.prototype,"remoteSet",1);$o([Ft(js,"bulkRateLimitConfig")],Hs.prototype,"bulkSet",1);$o([Ft(js,"rateLimitConfig")],Hs.prototype,"update",1);$o([Ft(js,"rateLimitConfig")],Hs.prototype,"delete",1);$o([Ft(js,"bulkRateLimitConfig")],Hs.prototype,"bulkDelete",1);var bs,_s,qc,au,Nd,kr,rh,Py;class sN{constructor(e,n){f(this,qc),f(this,rh),g(this,"stores",new Map),f(this,bs,void 0),f(this,_s,""),f(this,Nd,void 0),f(this,kr,new Map),v(this,bs,n),v(this,_s,e.getValue("meetingId")),v(this,Nd,e),H(this,rh,Py).call(this)}create(e){const n=new Hs({name:e,socketHandler:o(this,bs),meetingId:o(this,_s)});return o(this,bs).storeGetKeys(o(this,_s),e,[]),new Promise((i,r)=>{const s=setTimeout(()=>r(Error("Failed")),3e3);o(this,kr).set(e,{rejectTimeout:s,resolve:i,store:n})})}}bs=new WeakMap,_s=new WeakMap,qc=new WeakSet,au=function(){return o(this,Nd).getValue("peerId")},Nd=new WeakMap,kr=new WeakMap,rh=new WeakSet,Py=function(){[z.storeInsertKeys,z.storeGetKeys,z.storeDeleteKeys].forEach(t=>{o(this,bs).on(t,e=>u(this,null,function*(){var n,i;if(e.pluginId!==o(this,_s))return;const r=(n=e.storeItems)==null?void 0:n.map(a=>{var c;return{timestamp:a.timestamp,peerId:a.peerId,payload:JSON.parse((c=a.payload)!=null&&c.length?new TextDecoder().decode(a.payload):"{}"),key:a.storeKey}});if(t===z.storeGetKeys){const a=o(this,kr).get(e.storeName),c=this.stores.get(e.storeName)||(a==null?void 0:a.store);o(this,kr).get(e.storeName)&&(this.stores.set(e.storeName,a.store),a.resolve(c),clearTimeout(a.rejectTimeout),o(this,kr).delete(e.storeName)),r.forEach(d=>{c.set(d.key,d.payload,!1,!1)});return}const s=this.stores.get(e.storeName)||((i=o(this,kr).get(e.storeName))==null?void 0:i.store);s!==void 0&&(t===z.storeInsertKeys&&r.forEach(({key:a,peerId:c,payload:d})=>{c!==o(this,qc,au)&&s.set(a,d,!1,!0)}),t===z.storeDeleteKeys&&r.forEach(({key:a,peerId:c})=>{c!==o(this,qc,au)&&s.delete(a,!1,!0)}))}))})};function br(t){var e,n,i,r,s,a,c,d,l,h,m,y,S;return t?{media:{audio:{enabled:t.audioEnabled,trackId:(e=t.audioTrack)==null?void 0:e.id,permission:"mediaPermissions"in t?(n=t.mediaPermissions)==null?void 0:n.audio:null},video:{enabled:t.videoEnabled,trackId:(i=t.videoTrack)==null?void 0:i.id,permission:"mediaPermissions"in t?(r=t.mediaPermissions)==null?void 0:r.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(s=t.mediaPermissions)==null?void 0:s.screenshare:null,audio:{enabled:(c=(a=t.screenShareTracks)==null?void 0:a.audio)==null?void 0:c.enabled,trackId:(l=(d=t.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(m=(h=t.screenShareTracks)==null?void 0:h.video)==null?void 0:m.enabled,trackId:(S=(y=t.screenShareTracks)==null?void 0:y.video)==null?void 0:S.id}}}}:{}}var aN=Object.defineProperty,oN=Object.getOwnPropertyDescriptor,qs=(t,e,n,i)=>{for(var r=i>1?void 0:i?oN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&aN(e,n,r),r};const cN=.8,dN=1.2;var ba,_a,zi,Xr,wa,hi,fc,Yi,Ia,vc,pi,ou,yc,cu,jg;let oi=(jg=class extends zt{constructor(t,e,n,i){super(),f(this,Xr),f(this,Ia),f(this,yc),g(this,"id"),g(this,"userId"),g(this,"name"),g(this,"picture"),g(this,"isHost"),g(this,"customParticipantId"),g(this,"flags"),g(this,"device"),g(this,"videoTrack"),g(this,"audioTrack"),g(this,"screenShareTracks"),g(this,"videoEnabled"),g(this,"audioEnabled"),g(this,"screenShareEnabled"),g(this,"producers"),g(this,"manualProducerConfig"),f(this,ba,void 0),g(this,"supportsRemoteControl",!1),f(this,_a,void 0),g(this,"presetName"),f(this,zi,void 0),f(this,hi,void 0),f(this,fc,void 0),f(this,Yi,new Map),f(this,pi,1),f(this,ou,Pd(w=>{if(!this.videoTrack)return;const{clientWidth:X,clientHeight:ae}=w,{width:Ee,height:ce}=this.videoTrack.getSettings();if(!Ee||!ce)return;const Re=ce/ae,vt=Ee/X,A=Math.max(Re,vt);A>dN&&o(this,pi)===1?(v(this,pi,0),R.emit(M.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:o(this,pi)})):A<cN&&o(this,pi)===0&&(v(this,pi,1),R.emit(M.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:o(this,pi)}))},2e3)),v(this,zi,t);const{id:r,userId:s,displayName:a,device:c,picture:d,isHost:l,flags:h,clientSpecificId:m,stageStatus:y,customParticipantId:S,audioMuted:b,audioTrack:D,videoEnabled:C=!1,videoTrack:V,producers:L,metadata:q}=e;this.id=r,this.userId=s,this.name=a,this.device=c,this.picture=d,this.isHost=l,this.flags=h,this.manualProducerConfig=jI,v(this,_a,y!=null?y:"ON_STAGE"),this.customParticipantId=S!=null?S:m,this.audioEnabled=!b,this.audioTrack=D,this.videoEnabled=C,this.videoTrack=V,this.screenShareTracks={audio:void 0,video:void 0},this.producers=L!=null?L:[],this.presetName=q==null?void 0:q.preset_name,v(this,ba,!1),v(this,hi,n),v(this,fc,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),H(this,yc,cu).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return o(this,_a)}get mediaJoined(){return o(this,zi).getValue("connectionHandler").mediaJoined}get socketJoined(){return o(this,zi).getValue("connectionHandler").socketJoined}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(p.info("DyteParticipant::setVideoEnabled::videoUpdate",U({},br(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(p.info("DyteParticipant::setAudioEnabled::audioUpdate",U({},br(this))),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){this.screenShareEnabled=t,e&&this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}setupEvents(){this.on("videoUpdate",H(this,yc,cu))}pin(){return u(this,null,function*(){if(!this.mediaJoined)throw new I("Can`t pin participant without joining room","1205");if(!o(this,hi).permissions.pinParticipant)throw new I("You do not have permission to pin participants.","1201");return o(this,Xr,wa).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!this.mediaJoined)throw new I("Can`t unpin participant without joining room","1205");if(!o(this,hi).permissions.pinParticipant)throw new I("You do not have permission to unpin participants.","1201");return o(this,Xr,wa).pinPeer(null)})}setIsPinned(t,e=!0){var n;v(this,ba,t);const i=t?"pinned":"unpinned";(n=o(this,Ia,vc))==null||n.updateSource(this.id,{pinned:t}),e&&this.emit(i,this)}disableAudio(){return u(this,null,function*(){const t=this.id;if(p.info("DyteParticipant::disable_audio",{dyteParticipant:{id:t}}),!this.mediaJoined)throw new I("Can`t disable participant audio without joining room","1205");if(o(this,hi).permissions.canDisableParticipantAudio)return o(this,Xr,wa).disableAudio(t);throw p.error("DyteParticipant::unauthorized_disable_audio",{dyteParticipant:{id:t}}),new I("Unauthorized: User does not have permission to disable participant audio.","1201")})}kick(){return u(this,null,function*(){const t=this.id;if(p.info("DyteParticipant::kick",{dyteParticipant:{id:t}}),!this.socketJoined)throw new I("Can`t kick participant without joining room","1205");if(o(this,hi).permissions.kickParticipant){yield R.emitAsync(M.KICK_PEER,{peerId:t});return}throw p.error("DyteParticipant::unauthorized_kick",{dyteParticipant:{id:t}}),new I("Unauthorized: User does not have permission to kick participants.","1201")})}disableVideo(){return u(this,null,function*(){const t=this.id;if(p.info("DyteParticipant::disable_video",{dyteParticipant:{id:t}}),!this.mediaJoined)throw new I("Can`t disable participant video without joining room","1205");if(o(this,hi).permissions.canDisableParticipantVideo)return o(this,Xr,wa).disableVideo(t);throw p.error("DyteParticipant::unauthorized_disable_video",{dyteParticipant:{id:t}}),new I("Unauthorized: User does not have permission to disable participant video.","1201")})}getPermissions(){return u(this,null,function*(){return o(this,fc).getUserPermissions(this.userId)})}setStageStatus(t){v(this,_a,t),this.emit("stageStatusUpdate",this)}get isPinned(){return o(this,ba)}registerVideoElement(t){var e,n,i,r;let s;(n=(e=o(this,Yi).get(t))==null?void 0:e.observer)==null||n.disconnect(),"ResizeObserver"in window&&(s=new ResizeObserver(()=>o(this,ou).call(this,t)),s.observe(t)),o(this,Yi).set(t,{observer:s}),this.updateVideo(t),(r=o(this,Ia,vc))==null||r.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(i=this.raised)!=null?i:!1)}deregisterVideoElement(t){var e,n,i;t.srcObject=void 0,(n=(e=o(this,Yi).get(t))==null?void 0:e.observer)==null||n.disconnect(),o(this,Yi).delete(t),(i=o(this,Ia,vc))==null||i.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const n=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((n==null?void 0:n.id)===this.videoTrack.id)return;const i=new MediaStream;i.addTrack(this.videoTrack),t.srcObject=i}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},ba=new WeakMap,_a=new WeakMap,zi=new WeakMap,Xr=new WeakSet,wa=function(){return o(this,zi).getValue("roomNodeClient")},hi=new WeakMap,fc=new WeakMap,Yi=new WeakMap,Ia=new WeakSet,vc=function(){return o(this,zi).getValue("pip")},pi=new WeakMap,ou=new WeakMap,yc=new WeakSet,cu=function(){Array.from(o(this,Yi).keys()).forEach(this.updateVideo)},jg);qs([E.trace("DyteParticipant.disableAudio")],oi.prototype,"disableAudio",1);qs([E.trace("DyteParticipant.kick")],oi.prototype,"kick",1);qs([E.trace("DyteParticipant.disableVideo")],oi.prototype,"disableVideo",1);qs([E.trace("DyteParticipant.getPermissions")],oi.prototype,"getPermissions",1);qs([E.trace("DyteParticipant.setStageStatus")],oi.prototype,"setStageStatus",1);oi=qs([gt("1200")],oi);class Ca extends Sy{constructor(e){const{onAddEvent:n="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:r="participantsCleared"}=e!=null?e:{};super({onAddEvent:n,onDeleteEvent:i,onClearEvent:r})}add(e,n=!0){return this.has(e.id)&&Object.is(this.get(e.id),e)===!1&&this.delete(e.id),super.add(e,n)}clear(e=!0,n=!1){return super.clear(e,n)}delete(e,n=!0,i=!1){return super.delete(e,n,i)}}var or;class lN extends Bs{constructor(){super(),f(this,or,void 0),v(this,or,new Map)}__set(e,n){return o(this,or).set(e,n)}__clear(){return o(this,or).clear()}get(e){return o(this,or).get(e)}toArray(){return Array.from(o(this,or).values())}}or=new WeakMap;class uN{constructor(){g(this,"_orderedArray"),g(this,"_map"),this._map=new Map,this._orderedArray=[]}add(e,n){if(!this._map.has(e))return this._map.set(e,{peerId:e,priority:n}),this._orderedArray.splice(Math.max(n-1,0),0,e),this.index(e);const i=this.index(e);this.delete(e);const r=this.add(e,n);return i!==r?r:-1}delete(e){if(this._map.has(e)){const n=this.index(e);this._map.delete(e),this._orderedArray.splice(n,1)}}index(e){return this._map.has(e)?this._orderedArray.indexOf(e):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class hN{constructor(){g(this,"_activeSpeakerPeers"),g(this,"_compulsoryPeers"),this._activeSpeakerPeers=new uN,this._compulsoryPeers=new Set}add(e,n){if(!e)return-1;if(n<0)return this._compulsoryPeers.add(e),0;if(this.compulsoryPeers.includes(e)&&(n>0||n===246267631)){if(p.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),n===246267631)return-1}else if(n===229490415)return this.delete(e),-1;return this._activeSpeakerPeers.add(e,n)}delete(e){p.info("DyteSelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),this._activeSpeakerPeers.delete(e)}index(e){return this._activeSpeakerPeers.index(e)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(e){this._compulsoryPeers.delete(e)}}const Ry=new hN;var pN=Object.defineProperty,mN=Object.getOwnPropertyDescriptor,Xt=(t,e,n,i)=>{for(var r=i>1?void 0:i?mN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&pN(e,n,r),r};const gN=["ACTIVE_GRID","PAGINATED","MANUAL"];var Hn,mi,Qi,Zr,jt,Hg;let Mt=(Hg=class extends zt{constructor(t,e,n){super(),f(this,mi),g(this,"waitlisted"),g(this,"joined"),g(this,"active"),g(this,"videoSubscribed"),g(this,"audioSubscribed"),g(this,"pinned"),g(this,"all"),f(this,Hn,void 0),f(this,Zr,void 0),f(this,jt,void 0),g(this,"rateLimitConfig",{maxInvocations:5,period:1}),g(this,"viewMode"),g(this,"currentPage"),g(this,"lastActiveSpeaker"),g(this,"selectedPeers",Ry),v(this,Hn,t),v(this,Zr,e),v(this,jt,n),this.waitlisted=new Ca,this.joined=new Ca,this.videoSubscribed=new Ca,this.audioSubscribed=new Ca,this.active=this.videoSubscribed,this.pinned=new Ca,this.all=new lN,this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return o(this,Hn).getValue("pip")}get socketJoined(){var t;return((t=o(this,Hn).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0}get mediaJoined(){var t;return((t=o(this,Hn).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}setupEvents(){R.on(M.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=o(this,Hn).getValue("modules").e2ee)==null?void 0:e.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${t}, but encryption wasn't enabled in init.defaults`,code:"1702"})})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=o(this,mi,Qi))==null?void 0:t.maxPreferredStreams}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new I("0 <= Max active participants count limit <= 24","1203");o(this,mi,Qi).maxPreferredStreams=t,this.mediaJoined&&R.emit(M.UPDATE_ACTIVE)}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(n=>n.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var e,n;if(!this.socketJoined)throw new I("Can`t accept waiting room request without joining room","1205");const i=(n=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?n:t;return o(this,jt).acceptWaitingRoomRequest([i])}acceptAllWaitingRoomRequest(t){return u(this,null,function*(){const e=t.map(n=>{var i,r;return(r=(i=this.waitlisted.get(n))==null?void 0:i.userId)!=null?r:n});return o(this,jt).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return u(this,null,function*(){var e,n;if(!this.socketJoined)throw new I("Can`t reject waiting room request without joining room","1205");const i=(n=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?n:t;o(this,jt).rejectWaitingRoomRequest([i])})}setViewMode(t){return u(this,null,function*(){if(p.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(e=>gN.includes(e))(t))throw p.error("DyteParticipants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new I(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){p.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}if(t==="MANUAL")throw new I("Manual Subscription is not enabled for your Organization. Please contact support.","1208");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,R.emit(M.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,R.emit(M.UPDATE_ACTIVE)),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})})}subscribe(t){return u(this,arguments,function*(e,n=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new I("MANUAL subscription mode was not activated.","1206");const i=[];e.forEach(r=>{const s=this.joined.get(r);if(s){if(n.includes("audio")){s.manualProducerConfig=J(U({},s.manualProducerConfig),{audio:!0}),this.videoSubscribed.add(s);const a=s.producers.find(c=>c.kind==="audio"&&!c.screenShare);a&&i.push(a)}if(n.includes("video")){s.manualProducerConfig=J(U({},s.manualProducerConfig),{video:!0}),this.audioSubscribed.add(s);const a=s.producers.find(c=>c.kind==="video"&&!c.screenShare);a&&i.push(a)}if(n.includes("screenshareAudio")){s.manualProducerConfig=J(U({},s.manualProducerConfig),{screenshareAudio:!0});const a=s.producers.find(c=>c.kind==="audio"&&c.screenShare);i.push(a)}if(n.includes("screenshareVideo")){s.manualProducerConfig=J(U({},s.manualProducerConfig),{screenshareVideo:!0});const a=s.producers.find(c=>c.kind==="video"&&c.screenShare);i.push(a)}}}),yield o(this,mi,Qi).createConsumers(i)})}unsubscribe(t){return u(this,arguments,function*(e,n=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new I("MANUAL subscription mode was not activated.","1206");const i=[];e.forEach(r=>{const s=this.joined.get(r);if(s){if(n.includes("audio")){s.manualProducerConfig=J(U({},s.manualProducerConfig),{audio:!1});const a=s.producers.find(c=>c.kind==="audio"&&!c.screenShare);a&&i.push(a)}if(n.includes("video")){s.manualProducerConfig=J(U({},s.manualProducerConfig),{video:!1});const a=s.producers.find(c=>c.kind==="video"&&!c.screenShare);a&&i.push(a)}if(n.includes("screenshareAudio")){s.manualProducerConfig=J(U({},s.manualProducerConfig),{screenshareAudio:!1});const a=s.producers.find(c=>c.kind==="audio"&&c.screenShare);i.push(a)}if(n.includes("screenshareVideo")){s.manualProducerConfig=J(U({},s.manualProducerConfig),{screenshareVideo:!1});const a=s.producers.find(c=>c.kind==="video"&&c.screenShare);i.push(a)}}}),yield o(this,mi,Qi).closeConsumers(i)})}getPeerIdsForCurrentPage(){p.info("DyteParticipants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(a=>this.joined.has(a)),n=Array.from(this.pinned.keys()).filter(a=>!e.includes(a)),i=Array.from(this.joined.toArray().filter(a=>a.stageStatus==="ON_STAGE").map(a=>a.id)),r=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-n.length)),s=this.currentPage*(this.maxActiveParticipantsCount-e.length-n.length);return e.concat(n,i.slice(r,s))}setPage(t){return u(this,null,function*(){if(p.info("DyteParticipants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw p.error("DyteParticipants::invalid_page_number"),new I(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,R.emit(M.UPDATE_ACTIVE,{page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}})}disableAllAudio(t){return u(this,null,function*(){if(p.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!this.mediaJoined)throw new I("Can`t disable all audio without joining room","1205");if(o(this,Zr).permissions.canAllowParticipantAudio)return o(this,mi,Qi).muteAll(t);throw p.error("DyteParticipants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new I("Unauthorized: User does not have permission to disable peer audio.","1201")})}disableAllVideo(){return u(this,null,function*(){if(p.info("DyteParticipants::disable_all_video"),!this.mediaJoined)throw new I("Can`t disable all video without joining room","1205");if(o(this,Zr).permissions.canAllowParticipantVideo)return o(this,mi,Qi).muteAllVideo();throw p.error("DyteParticipants::unauthorized_disable_all_video"),new I("Unauthorized: User does not have permission to disable peer video.","1201")})}disableAudio(t){return u(this,null,function*(){this.joined.get(t).disableAudio()})}disableVideo(t){return u(this,null,function*(){this.joined.get(t).disableVideo()})}kick(t){return u(this,null,function*(){yield R.emitAsync(M.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(p.info("DyteParticipants::kick_all"),o(this,Hn).getValue("viewType")!=="LIVESTREAM"&&!this.socketJoined)throw new I("Can`t kick all without joining room","1205");if(!o(this,Zr).permissions.kickParticipant)throw p.error("DyteParticipants::unauthorized_kick_all"),new I("Unauthorized: User does not have permission to kick peers.","1201");const t=Z.hasFeature(re.PROPAGATE_KICK_ALL);o(this,jt).kickAll(t)})}broadcastMessage(t,e,n){return u(this,null,function*(){if(p.info("DyteParticipants::broadcastMessage"),!this.socketJoined)throw new I("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new I("`type` must be a non-empty string.","1209");if(n)if("meetingIds"in n)yield o(this,jt).broadcastToMeetings(t,n.meetingIds,e);else{let i=[];"participantIds"in n?i=n.participantIds:i=this.joined.toArray().filter(r=>{var s;return(s=n.presetNames)==null?void 0:s.includes(r.presetName)}).map(r=>r.id),yield o(this,jt).broadcastToPeers(t,i,e)}else yield o(this,jt).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,n){return u(this,null,function*(){return(yield o(this,jt).getRoomPeers(t,e,n)).peers.map(li.formatSocketServiceMessage)})}updatePermissions(t,e){return u(this,null,function*(){const n=this.joined.toArray().filter(r=>t.includes(r.id)).map(r=>r.userId),i=[...new Set(n)];if(!i.length)throw new I("Cannot update permissions, no valid userIDs found","1204");o(this,jt).updatePermissions(i,e)})}getParticipantsInMeetingPreJoin(){return u(this,null,function*(){return o(this,jt).getRoomPeersNonPaginated()})}},Hn=new WeakMap,mi=new WeakSet,Qi=function(){return o(this,Hn).getValue("roomNodeClient")},Zr=new WeakMap,jt=new WeakMap,Hg);Xt([E.trace("DyteParticipants.setViewMode")],Mt.prototype,"setViewMode",1);Xt([E.trace("DyteParticipants.setPage")],Mt.prototype,"setPage",1);Xt([E.trace("DyteParticipants.disableAllAudio")],Mt.prototype,"disableAllAudio",1);Xt([E.trace("DyteParticipants.disableAllVideo")],Mt.prototype,"disableAllVideo",1);Xt([E.trace("DyteParticipants.disablePeerAudio")],Mt.prototype,"disableAudio",1);Xt([E.trace("DyteParticipants.disablePeerVideo")],Mt.prototype,"disableVideo",1);Xt([E.trace("DyteParticipants.kickPeer")],Mt.prototype,"kick",1);Xt([E.trace("DyteParticipants.kickAll")],Mt.prototype,"kickAll",1);Xt([E.trace("DyteParticipants.broadcastMessage"),Ft(js,"rateLimitConfig")],Mt.prototype,"broadcastMessage",1);Xt([E.trace("DyteParticipants.getAllJoinedPeers"),Ft({maxInvocations:10,period:60})],Mt.prototype,"getAllJoinedPeers",1);Xt([E.trace("DyteParticipant.updatePermissions"),Ft({maxInvocations:1e3,period:60})],Mt.prototype,"updatePermissions",1);Xt([E.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],Mt.prototype,"getParticipantsInMeetingPreJoin",1);Mt=Xt([gt("1200")],Mt);var Wi=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t.CLOSED="closed",t))(Wi||{}),it=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(it||{}),fN=Object.defineProperty,vN=Object.getOwnPropertyDescriptor,jr=(t,e,n,i)=>{for(var r=i>1?void 0:i?vN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&fN(e,n,r),r};const My=class{constructor(t,e,n,i){switch(g(this,"participants"),g(this,"self"),g(this,"selectedPeers",Ry),g(this,"maxSpatialLayerUpdates",new Map),g(this,"consumerPeerMap"),g(this,"events"),g(this,"roomSocketHandler"),g(this,"context"),g(this,"videoPeerConsumerMap",new Map),g(this,"updateConsumerSpatialLayers",Pd(()=>{const r={},s=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(s.entries()).forEach(([a,c])=>{r[c]===void 0&&(r[c]={layer:c,consumerIds:[]}),r[c].consumerIds.push(a)}),Object.keys(r).forEach(a=>{const c=r[a];p.log(`Switching max spatial layer to ${c.layer}`,{consumerIds:c.consumerIds}),this.roomNodeClient.switchConsumersToLayer(c.consumerIds,c.layer)})},2e3)),g(this,"updateConsumers",(r,s)=>{let a=Promise.resolve();s.length>0&&(p.info("Closing consumers for producers",{producers:s}),a=this.roomNodeClient.closeConsumers(s)),a.then(()=>{r.length!==0&&(p.info("Consuming producers",{producers:r}),this.roomNodeClient.createConsumers(r).catch(c=>p.error("Error activating peers",{error:c})))}).catch(c=>p.error("Error deactivating peers",{error:c}))}),g(this,"updateConsumersDebounced",Pd(this.updateConsumers,200,{trailing:!0})),this.context=t,this.roomSocketHandler=n,this.participants=new Mt(t,e,this.roomSocketHandler),this.self=e,this.consumerPeerMap=new Map,i){case it.HIVE:{this.events=sn;break}case it.CF:{this.events=En;break}default:this.events=sn}e.config.viewType!=="CHAT"&&this.setupEventsGlobal(),this.setupEvents()}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var t;return((t=this.roomNodeClient)==null?void 0:t.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}setupEvents(){this.roomSocketHandler.on(j.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),R.on(M.SOCKET_PEERS,t=>u(this,null,function*(){const e=Z.hasFeature(re.DEBUG_SOCKET_JOIN);if(e){const n=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(i=>i.peerId))}:void 0;p.info("Processing socket peers",n)}t==null||t.forEach(n=>{n.waitlisted||this.onParticipantJoined(this.fromSocketService(n))}),e&&p.info("Processed socket peers")})),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:t})=>{Z.hasFeature(re.DEBUG_SOCKET_JOIN)&&p.info("events.peerJoinedBroadcast",{peers:t.peerId}),this.onMediaJoined(t.peerId,t.producerStates,t.capabilities)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:t,selectedPeers:e,roomState:n})=>{if(Z.hasFeature(re.DEBUG_SOCKET_JOIN)){const s=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(a=>a.peerId))}:void 0;p.info("events.selfJoinComplete",s)}t.forEach(({peerId:s,producerStates:a,capabilities:c})=>this.onMediaJoined(s,a,c));const{audioPeers:i,compulsoryPeers:r}=e!=null?e:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],r),R.emit(M.UPDATE_ACTIVE,{createAllConsumers:!0})}),R.on(M.MAX_SPATIAL_LAYER_CHANGE,({peerId:t,maxSpatialLayer:e})=>{const n=this.videoPeerConsumerMap.get(t);n&&(this.maxSpatialLayerUpdates.set(n,e),this.updateConsumerSpatialLayers())}),R.on(M.NEW_PRODUCER,({peerId:t,producer:e})=>{const n=this.participants.joined.get(t);if(!n){p.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:e==null?void 0:e.producerId,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}},dyteParticipant:{id:t}});return}if(n.producers.push(e),p.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}}),this.participants.viewMode==="MANUAL"){let i=!1;const r=e.kind==="audio",s=e.kind==="video",a=n.manualProducerConfig;(r&&(a.audio&&!e.screenShare||a.screenshareAudio&&e.screenShare)||s&&(a.video&&!e.screenShare||a.screenshareVideo&&e.screenShare))&&(i=!0),i?this.roomNodeClient.createConsumers([e]):p.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}});return}(e==null?void 0:e.kind)==="audio"&&this.participants.audioSubscribed.get(t)||(e==null?void 0:e.kind)==="video"&&this.participants.videoSubscribed.get(t)||e!=null&&e.screenShare?this.roomNodeClient.createConsumers([e]).catch(i=>{p.error("ParticipantController::createConsumer failed",{error:i})}):p.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}})}),R.on(M.PRODUCER_CLOSED,({peerId:t,producerId:e})=>{const n=this.participants.joined.get(t);if(!n){p.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:t}});return}n.producers=n.producers.filter(i=>i.producerId!==e)}),R.on(M.PRODUCER_TOGGLE,({peerId:t,producerId:e,paused:n,kind:i})=>{const r=this.participants.joined.get(t);if(r){i==="audio"&&r.setAudioEnabled(!n);const s=r.producers.find(a=>a.producerId===e);s&&(s.pause=n)}}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,t=>{let e;if(t&&(e=t.participantId),!this.mediaJoined)return;const n=e;this.onParticipantPinned(n);const i=this.participants.joined.get(n);i&&this.roomNodeClient.activatePeers(i.producers).catch(r=>{p.error("unable to create consumers",{error:r})})}),this.roomSocketHandler.on(this.events.selectedPeer,({audioPeers:t,compulsoryPeers:e})=>{this.mediaJoined&&this.onSelectedPeers(e.concat(t))}),this.roomSocketHandler.on(this.events.selectedPeerDiff,({entries:t})=>{if(!this.mediaJoined)return;const e=t.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(e,!0)})}waitingRoomRequestHandler(t){const e=t.requests.filter(i=>!this.participants.waitlisted.toArray().find(r=>r.userId===i.userId)),n=this.participants.waitlisted.toArray().filter(i=>!t.requests.find(r=>r.userId===i.userId));e.forEach(i=>this.participants.waitlisted.add(new oi(this.context,{id:i.peerId,displayName:i.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:i.userId,flags:{},isHost:!1,customParticipantId:i.customParticipantId,picture:i.picture,metadata:{preset_name:i.presetName}},this.self,this.roomSocketHandler))),n.forEach(i=>this.participants.waitlisted.delete(i.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(t){return u(this,null,function*(){const{compulsoryPeers:e}=this.selectedPeers,n=e.filter(c=>this.participants.joined.has(c)),i=Array.from(this.participants.pinned.keys()).filter(c=>!n.includes(c)),r=Array.from(this.participants.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),s=Math.max((t-1)*(this.roomNodeClient.maxPreferredStreams-n.length-i.length)),a=t*(this.roomNodeClient.maxPreferredStreams-n.length-i.length);return n.concat(i,r.slice(s,a))})}selectActivePeers(){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(l=>l.stageStatus==="ON_STAGE").map(l=>(t.set(l.id,!0),l.id))),n=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((l,h)=>(h.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(h.id):l.push(h.id),l),[]),r=this.self.stageStatus==="ON_STAGE"?1:0,s=this.participants.maxActiveParticipantsCount-r,a=new Set(n.concat(i).filter(l=>l!==this.self.id&&t.has(l)));let c=Array.from(a);const d=s-a.size;if(d>=0){const l=e.filter(h=>!a.has(h)&&h!==this.self.id).slice(0,d);c=Array.from(a).concat(l)}else c=c.slice(0,s);return c}updateActive(t,e){return u(this,null,function*(){const{page:n,createAllConsumers:i}=e!=null?e:{};let{strategies:r}=e!=null?e:{},s,a;switch(t){case"PAGINATED":{if(!n)return;s=yield this.selectPagePeers(n),p.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:s}),r!=null||(r={video:this.updateParticipantsMap.bind(this)}),a=this.updateConsumersDebounced;break}case"ACTIVE_GRID":{s=this.selectActivePeers(),p.debug("ParticipantController::updateActive::updating_current_selected_peers",{peerIds:s}),r!=null||(r={video:this.updateParticipantsMapMinReplacement.bind(this),audio:this.updateParticipantsMap.bind(this)}),a=this.updateConsumers;break}default:throw new Error(`View mode ${t} not supported`)}let c,d;const l=this.updateGrid(s,r);i?(c=this.mapPeerIdsToProducers(s,["audio","video","screenshare"]),d=[]):(c=[...this.mapPeerIdsToProducers([...l.video.add],["video"]),...this.mapPeerIdsToProducers([...l.audio.add],["audio"])],d=[...this.mapPeerIdsToProducers([...l.video.remove],["video"]),...this.mapPeerIdsToProducers([...l.audio.remove],["audio"])]),!(c.length===0&&d.length===0)&&a(c,d)})}computeActivateParticipants(t,e){const n=t.map((r,s)=>({peerId:r,priority:s+1})),i=e==null?void 0:e.map((r,s)=>({peerId:r,priority:-(s+1)}));n.push(...i!=null?i:[]),n.length>0&&this.updateActiveParticipantsWithPriorities(n)}fromSocketService(t){const e=My.formatSocketServiceMessage(t);return new oi(this.context,J(U({},e),{isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0}),this.self,this.roomSocketHandler)}updatePipSource(t,e){var n,i;e?(n=this.pip)==null||n.enableSource(t):(i=this.pip)==null||i.disableSource(t)}onMediaJoined(t,e,n){if(!this.mediaJoined||t===this.self.id)return;const i=this.participants.joined.get(t);if(!i){p.warn(`Received media.peerJoinedBroadcast for non-existent peer ${t}`);return}e.forEach(r=>{r.kind===Vn.AUDIO&&!r.screenShare?i.setAudioEnabled(!r.pause):r.kind===Vn.VIDEO&&!r.screenShare&&(i.setVideoEnabled(!r.pause),this.updatePipSource(i.id,!r.pause)),i.producers.push(J(U({},r),{producingTransportId:r.producingTransportId,kind:r.kind===Vn.AUDIO?"audio":"video",producingPeerId:t,mimeType:r.mimeType}))}),this.roomNodeClient.handlePeerCapabilities(t,n),Z.hasFeature(re.FORCE_VIDEO_CODEC)||this.roomNodeClient.shareWebcam(this.self.videoTrack)}updateParticipantsMapMinReplacement(t,e){const n=Array.from(t.keys()),i=new Map(t),r=[],s=[],a=new Set(e),c=[];return n.forEach((d,l)=>{(!a.has(d)||!this.participants.joined.get(d))&&c.push(l)}),e.forEach(d=>{if(t.get(d))return;if(n.length<e.length){n.push(d),r.push(d);return}const l=c.shift();s.push(n[l]),n[l]=d,r.push(n[l])}),n.forEach((d,l)=>{a.has(d)||s.concat(n.splice(l,1))}),Array.from(t.keys()).forEach(d=>{t.delete(d,!a.has(d))}),n.forEach(d=>{if(!this.participants.joined.get(d)){p.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:d}});return}t.add(this.participants.joined.get(d),!i.get(d))}),t.emit("participantsUpdate"),[r,s]}updateParticipantsMap(t,e){const n=Array.from(t.keys()),i=[],r=[];return n.forEach(s=>{e.includes(s)||(t.delete(s,!0),r.push(s))}),e.forEach(s=>{t.get(s)||(t.add(this.participants.joined.get(s)),i.push(s))}),t.emit("participantsUpdate"),[i,r]}updatePinnedParticipants(){this.participants.pinned.forEach(t=>{t.setIsPinned(!1),this.participants.pinned.delete(t.id)})}setupEventsGlobal(){this.roomSocketHandler.on(j.joinRoom,({peer:t})=>{if(!t.waitlisted){const e=Z.hasFeature(re.DEBUG_SOCKET_JOIN);e&&p.info("Processing socket join",{peers:t.peerId}),this.onParticipantJoined(this.fromSocketService(t)),e&&p.info("Processed socket join",{peers:t.peerId})}}),this.roomSocketHandler.on(j.leaveRoom,t=>{const{peerId:e}=t.peer;this.selectedPeers.delete(e),this.onParticipantLeave(e)}),R.on(M.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",t=>{const{acceptWaitingRequests:e}=t;e!==void 0&&(e?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),R.on(M.SOCKET_SERVICE_DISCONNECTED,()=>{this.participants.joined.clear(),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount})}),R.on(M.CONSUMER_PAUSED,({id:t})=>{this.processConsumerPaused(t)}),R.on(M.CONSUMER_RESUMED,({id:t})=>{this.processConsumerResumed(t)}),R.on(M.NEW_CONSUMER,({id:t})=>{this.processNewConsumer(t)}),R.on(M.CONSUMER_CLOSED,({id:t})=>{this.processConsumerClosed(t)}),R.on(M.ROOM_MESSAGE,t=>u(this,[t],function*({payload:e,type:n,timestamp:i}){this.participants.emit("broadcastedMessage",{type:n,payload:e,timestamp:i})})),R.on(M.MESSAGE,t=>u(this,[t],function*({payload:e,type:n,timestamp:i}){n!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:n,payload:e,timestamp:i})})),R.on(M.LOW_CONSUMER_SCORE,({peerId:t,score:e,kind:n})=>{const i=this.participants.joined.get(t);i&&(i.emit("poorConnection",{score:e,kind:n}),this.participants.emit("poorConnection",{participantId:t,score:e,kind:n}))}),R.on(M.CONSUMER_SCORE_UPDATE,({score:t,kind:e,appData:n,peerId:i,scoreStats:r})=>{var s;const a=e==="video"&&((s=n==null?void 0:n.screenShare)!=null?s:!1),c=this.participants.joined.get(i);c&&(c.emit("mediaScoreUpdate",{kind:e,isScreenshare:a,score:t,participantId:i,scoreStats:r}),this.participants.emit("mediaScoreUpdate",{kind:e,isScreenshare:a,score:t,participantId:i,scoreStats:r}))}),R.onAsync(M.KICK_PEER,t=>u(this,[t],function*({peerId:e}){const n=this.participants.joined.get(e);yield this.roomNodeClient.kick(e),yield this.roomSocketHandler.kick(e),n?n.emit("kicked"):this.participants.joined.emit("kicked",{id:e})})),R.on(M.UPDATE_ACTIVE,(...t)=>u(this,[...t],function*({page:e,createAllConsumers:n}={}){yield this.updateActive(e?"PAGINATED":"ACTIVE_GRID",{page:e,createAllConsumers:n})}))}onParticipantPinned(t){return u(this,null,function*(){if(!t){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(t===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const e=this.participants.joined.get(t);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),e.setIsPinned(!0),this.participants.pinned.add(e)})}onParticipantJoined(t){return u(this,null,function*(){var e,n,i;if(this.self.id!==t.id&&!((e=t.flags)!=null&&e.recorder)&&!((n=t.flags)!=null&&n.hidden_participant)&&!((i=t.flags)!=null&&i.hiddenParticipant)&&(this.participants.videoSubscribed.delete(t.id),this.participants.audioSubscribed.delete(t.id),this.participants.joined.add(t),this.participants.waitlisted.delete(t.id),t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&R.emit(M.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!0})),R.emit(M.PEER_JOINED_INTERNAL,t),this.self.config.viewType===Rt.Webinar&&t.stageStatus!=="ON_STAGE"||this.roomNodeClient===void 0||this.participants.videoSubscribed.size>=this.roomNodeClient.maxPreferredStreams)return;const r=this.participants.currentPage;this.updateActive(r?"PAGINATED":"ACTIVE_GRID",{page:r})})}onParticipantLeave(t){return u(this,null,function*(){const e=this.participants.joined.get(t);this.participants.joined.delete(t,!0,!0),this.participants.pinned.delete(t,!0,!0),this.participants.waitlisted.delete(t,!0,!0),this.roomNodeClient&&(this.roomNodeClient.handlePeerLeaving(t),this.roomNodeClient.closeConsumers(e==null?void 0:e.producers)),e&&e.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&R.emit(M.UPDATE_STAGE_REQUESTS,{request:{displayName:e.name,userId:e.userId,peerId:e.id},add:!1});const{currentPage:n}=this.participants,i=this.maxPreferredStreams*(n-1),r=this.participants.videoSubscribed.get(t);i===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=i?n===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(n-1):r&&this.updateActive(n?"PAGINATED":"ACTIVE_GRID",{page:n})})}processMedia(t){var e;const n=this.roomNodeClient.getConsumers(),{peerId:i,kind:r,appData:s,track:a,producerId:c,rtpReceiver:d,paused:l}=(e=n.get(t))!=null?e:{};if(!i)return p.warn("processMedia::Peer ID is undefined",{consumer:{id:t,kind:r,peerId:i,appData:{supportsRemoteControl:!!(s!=null&&s.supportsRemoteControl),screenShare:!!(s!=null&&s.screenShare)},remotelyPaused:l,producerId:c}}),{};const h=s;return r==="video"&&h.screenShare!==!0&&this.videoPeerConsumerMap.set(i,t),p.info("ParticipantController::processMedia",{consumer:{id:t,peerId:i,kind:r,appData:h,remotelyPaused:l,producerId:c}}),this.consumerPeerMap.set(t,{type:r,peerId:i,appData:h,remotelyPaused:l,producerId:c}),{peerId:i,kind:r,appData:h,remotelyPaused:l,track:a,producerId:c,rtpReceiver:d}}processConsumerClosed(t){const{peerId:e,type:n,appData:i,remotelyPaused:r,producerId:s}=this.consumerPeerMap.get(t)||{},a=this.participants.joined.get(e);if(p.info("ParticipantController::processConsumerClosed",{consumer:{id:t,peerId:e,appData:i,kind:n,remotelyPaused:r,producerId:s}}),this.consumerPeerMap.delete(t),n==="video"&&i.screenShare!==!0&&this.videoPeerConsumerMap.delete(e),!a)return;const c=[];i&&i.screenShare?(a.setScreenShareEnabled(!1),K.consumerSharedMediaState(t,{screen:!1}),a.screenShareTracks.video&&c.push(a.screenShareTracks.video.id),a.screenShareTracks.audio&&c.push(a.screenShareTracks.audio.id),a.screenShareTracks={audio:void 0,video:void 0}):n==="audio"?(a.setAudioEnabled(!1),a.audioTrack&&c.push(a.audioTrack.id),K.consumerSharedMediaState(t,{audio:!1}),a.audioTrack=void 0):n==="video"&&(a.setVideoEnabled(!1),this.updatePipSource(a.id,!1),a.videoTrack&&c.push(a.videoTrack.id),K.consumerSharedMediaState(t,{video:!1}),a.videoTrack=void 0),i.e2ee&&c.forEach(d=>{R.emit(M.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:d})})}processConsumerResumed(t){const{peerId:e,kind:n,appData:i,track:r,remotelyPaused:s,producerId:a,rtpReceiver:c}=this.processMedia(t);if(!e)return;p.info("ParticipantController::processConsumerResumed",{consumer:{id:t,peerId:e,kind:n,appData:i,remotelyPaused:s,producerId:a}});const d=this.participants.joined.get(e);if(d){if(i.e2ee&&R.emit(M.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:r}),i.screenShare){n==="video"?d.screenShareTracks.video=r:n==="audio"&&(d.screenShareTracks.audio=r),d.setScreenShareEnabled(!0),K.consumerSharedMediaState(t,{screen:!0});return}n==="video"?(d.videoTrack=r,d.setVideoEnabled(!0),this.updatePipSource(d.id,!0),K.consumerSharedMediaState(t,{video:!0})):n==="audio"&&(d.audioTrack=r,d.setAudioEnabled(d.audioEnabled),K.consumerSharedMediaState(t,{audio:d.audioEnabled}))}}processConsumerPaused(t){p.info(`ParticipantController::processConsumerPaused called for consumerId: ${t}`);const{peerId:e,kind:n,track:i,appData:r,remotelyPaused:s,producerId:a}=this.processMedia(t);if(!e)return;p.info("ParticipantController::processConsumerPaused",{consumer:{id:t,peerId:e,kind:n,appData:r,remotelyPaused:s,producerId:a}});const c=this.participants.joined.get(e);c&&(i&&r.e2ee&&R.emit(M.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:i.id}),n==="video"?(c.videoTrack=i,c.setVideoEnabled(!1),this.updatePipSource(c.id,!1),K.consumerSharedMediaState(t,{video:!1})):n==="audio"&&(c.audioTrack=i,c.setAudioEnabled(c.audioEnabled),K.consumerSharedMediaState(t,{audio:c.audioEnabled})))}processNewConsumer(t){const{peerId:e,kind:n,remotelyPaused:i,track:r,appData:s,producerId:a,rtpReceiver:c}=this.processMedia(t);if(!e)return;p.info("ParticipantController::processNewConsumer",{consumer:{id:t,peerId:e,kind:n,remotelyPaused:i,appData:s,producerId:a}});const d=this.participants.joined.get(e);if(d){if(s.screenShare){n==="video"?d.screenShareTracks.video=r:n==="audio"&&(d.screenShareTracks.audio=r),(!i||this.self.permissions.isRecorder||Z.hasFeature(re.SCREEENSHARE_ERR_HACK))&&d.setScreenShareEnabled(!0),s.supportsRemoteControl&&(d.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:a,peerId:e,screenShare:!0,consumerId:t,consumerPeerId:this.self.id}),p.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:t,peerId:e,kind:n,remotelyPaused:i,appData:s,producerId:a}});return}n==="video"?(d.videoTrack=r,i||(d.setVideoEnabled(!0),this.updatePipSource(d.id,!0)),K.consumerSharedMediaState(t,{video:!i})):n==="audio"&&(d.audioTrack=r,i||d.setAudioEnabled(!0),K.consumerSharedMediaState(t,{audio:!i})),!i&&s.e2ee&&R.emit(M.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:r})}}static formatSocketServiceMessage(t){var e,n,i,r,s,a;if(!t)return;const c=pp(t.stageType);return{id:t.peerId,userId:t.userId,name:t.displayName,displayName:t.displayName,stageType:c,customParticipantId:t.customParticipantId,presetId:t.presetId,picture:t.displayPictureUrl,waitlisted:t.waitlisted,stageStatus:c,metadata:{preset_name:(e=t.flags)==null?void 0:e.presetName},recorderType:(n=t.flags)==null?void 0:n.recorderType,flags:{hiddenParticipant:(i=t.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(r=t.flags)==null?void 0:r.hiddenParticipant,recorder:((s=t.flags)==null?void 0:s.recorderType)!==void 0&&((a=t.flags)==null?void 0:a.recorderType)!=="NONE"}}}mapPeerIdsToProducers(t,e){const n=(i,r)=>i.filter(({kind:s,screenShare:a})=>r.includes(s)||a&&r.includes("screenshare"));return t.flatMap(i=>{const r=this.participants.joined.get(i);if(r)return n(r.producers,e)}).filter(i=>!!i)}updateGrid(t,e){let n=[],i=[],r=[],s=[];return e.video&&([n,r]=e.video(this.participants.videoSubscribed,t)),e.audio&&([i,s]=e.audio(this.participants.audioSubscribed,t)),{video:{add:n,remove:r},audio:{add:i,remove:s}}}onSelectedPeers(t,e){return u(this,null,function*(){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(t,e)})}updateActiveParticipantsWithPriorities(t,e=!1){if(!this.mediaJoined){p.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}t.forEach(i=>{this.selectedPeers.add(i.peerId,i.priority)});const n=this.selectedPeers.activeSpeakerPeers.at(0);n!==void 0&&n!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=n,this.participants.emit("activeSpeaker",{peerId:n,volume:1})),e&&(this.participants.viewMode==="ACTIVE_GRID"?this.updateActive("ACTIVE_GRID"):this.participants.viewMode==="PAGINATED"&&this.updateActive("ACTIVE_GRID",{strategies:{audio:this.updateParticipantsMap.bind(this)}}))}};let li=My;jr([E.trace("ParticipantController.setupEvents")],li.prototype,"setupEvents",1);jr([E.trace("ParticipantController.setupEvents")],li.prototype,"setupEventsGlobal",1);jr([E.trace("ParticipantController.processMedia")],li.prototype,"processMedia",1);jr([E.trace("ParticipantController.processConsumerClosed")],li.prototype,"processConsumerClosed",1);jr([E.trace("ParticipantController.processConsumerResumed")],li.prototype,"processConsumerResumed",1);jr([E.trace("ParticipantController.processConsumerPaused")],li.prototype,"processConsumerPaused",1);jr([E.trace("ParticipantController.processNewConsumer")],li.prototype,"processNewConsumer",1);const Te=kn(op().permissions);var G,$a,vo,sh,Nt,qt;const Ka=class extends zt{constructor(t,e,n,i=!1){if(super(),f(this,Nt),f(this,G,void 0),f(this,$a,void 0),f(this,vo,void 0),f(this,sh,r=>{var s,a,c;const d=r,{chat:l,connectedMeetings:h,plugins:m,polls:y,media:S}=d,b=Qd(d,["chat","connectedMeetings","plugins","polls","media"]);if(l&&(l.private&&Si(o(this,G).chat.private,l.private),l.public&&Si(o(this,G).chat.public,l.public),this.emit("chatUpdate")),h&&Si(o(this,G).connectedMeetings,h),S){const D=V=>{switch(V){case Li.NONE:return Y.Allowed;case Li.ALLOWED:return Y.Allowed;case Li.NOT_ALLOWED:return Y.NotAllowed;case Li.CAN_REQUEST:return Y.CanRequest;default:return}},C={audio:void 0,video:void 0,screenshare:void 0};(s=S.audio)!=null&&s.canProduce&&(C.audio={canProduce:D(S.audio.canProduce)}),(a=S.video)!=null&&a.canProduce&&(C.video={canProduce:D(S.video.canProduce)}),(c=S.screenshare)!=null&&c.canProduce&&(C.screenshare={canProduce:D(S.screenshare.canProduce)}),Si(o(this,G).media,C)}m&&(Si(o(this,G).plugins,m),this.emit("pluginsUpdate")),y&&(Si(o(this,G).polls,y),this.emit("pollsUpdate")),Object.keys(b).length!==0&&Si(o(this,G),b),this.emit("permissionsUpdate",r)}),!e)throw p.error("DytePermissionsPreset::load_preset_permissions_failed"),new I("Could not load preset permissions.","0904");v(this,vo,t),v(this,$a,n),v(this,G,e),i&&this.setupEvents()}setupEvents(){R.on(M.UPDATE_PERMISSIONS,o(this,sh))}static fromResponse(t,e,n){return new Ka(n,t,e,!0)}static default(t,e){return new Ka(t,Te,e)}static init(t,e,n){let i;return n?i=new Ka(t,n,e,!0):i=new Ka(t,Te,e),i}get mediaRoomType(){const{sfu:t}=o(this,vo).getValue("roomNodeOptions");return t===it.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=o(this,G))==null?void 0:t.stageEnabled)||o(this,$a)===Rt.Webinar||o(this,$a)===Rt.Livestream}get acceptStageRequests(){var t,e;return this.stageEnabled?((t=o(this,G))==null?void 0:t.acceptStageRequests)||((e=o(this,G))==null?void 0:e.canAcceptProductionRequests):!1}get stageAccess(){var t,e,n;return((t=o(this,G))==null?void 0:t.stageAccess)===Y.NotAllowed?Y.NotAllowed:((e=o(this,G))==null?void 0:e.stageAccess)===Y.CanRequest?Y.CanRequest:((n=o(this,G))==null?void 0:n.stageAccess)===Y.Allowed||o(this,G).media.audio.canProduce===Y.Allowed||o(this,G).media.video.canProduce===Y.Allowed||o(this,G).media.screenshare.canProduce===Y.Allowed?Y.Allowed:o(this,G).media.audio.canProduce===Y.CanRequest||o(this,G).media.video.canProduce===Y.CanRequest||o(this,G).media.screenshare.canProduce===Y.CanRequest?Y.CanRequest:Y.NotAllowed}get acceptWaitingRequests(){var t,e;return(e=(t=o(this,G))==null?void 0:t.acceptWaitingRequests)!=null?e:Te.acceptWaitingRequests}get requestProduceVideo(){var t,e,n;return((n=(e=(t=o(this,G))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:n.canProduce)===Y.CanRequest}get requestProduceAudio(){var t,e,n;return((n=(e=(t=o(this,G))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:n.canProduce)===Y.CanRequest}get requestProduceScreenshare(){var t,e,n;return((n=(e=(t=o(this,G))==null?void 0:t.media)==null?void 0:e.screenshare)==null?void 0:n.canProduce)===Y.CanRequest}get canAllowParticipantAudio(){var t,e;return(e=(t=o(this,G))==null?void 0:t.disableParticipantAudio)!=null?e:Te.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=o(this,G))==null?void 0:t.canAcceptProductionRequests)!=null?e:Te.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=o(this,G))==null?void 0:t.disableParticipantVideo)!=null?e:Te.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var t,e;return(e=(t=o(this,G))==null?void 0:t.kickParticipant)!=null?e:Te.kickParticipant}get pinParticipant(){var t,e;return(e=(t=o(this,G))==null?void 0:t.pinParticipant)!=null?e:Te.pinParticipant}get canRecord(){var t,e;return(e=(t=o(this,G))==null?void 0:t.canRecord)!=null?e:Te.canRecord}get waitingRoomType(){var t,e;return(e=(t=o(this,G))==null?void 0:t.waitingRoomType)!=null?e:Te.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=o(this,G))==null?void 0:t.waitingRoomType)!=null?e:Te.waitingRoomType}get plugins(){var t,e;return(e=(t=o(this,G))==null?void 0:t.plugins)!=null?e:Te.plugins}get polls(){var t,e;return(e=(t=o(this,G))==null?void 0:t.polls)!=null?e:Te.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return o(this,G).media.audio.canProduce===Y.CanRequest||o(this,G).media.video.canProduce===Y.CanRequest||o(this,G).media.screenshare.canProduce===Y.CanRequest}get canProduceVideo(){var t;const e=(t=o(this,G).media.video.canProduce)!=null?t:Te.media.video.canProduce;return this.stageEnabled&&(o(this,Nt,qt)==="ACCEPTED_TO_JOIN_STAGE"||o(this,Nt,qt)==="ON_STAGE")&&e===Y.CanRequest?Y.Allowed:this.stageEnabled&&(o(this,Nt,qt)==="OFF_STAGE"||o(this,Nt,qt)==="REQUESTED_TO_JOIN_STAGE")&&e===Y.Allowed?Y.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var t;const e=(t=o(this,G).media.screenshare.canProduce)!=null?t:Te.media.screenshare.canProduce;return this.stageEnabled&&(o(this,Nt,qt)==="ACCEPTED_TO_JOIN_STAGE"||o(this,Nt,qt)==="ON_STAGE")&&e===Y.CanRequest?Y.Allowed:this.stageEnabled&&(o(this,Nt,qt)==="OFF_STAGE"||o(this,Nt,qt)==="REQUESTED_TO_JOIN_STAGE")&&e===Y.Allowed?Y.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var t;const e=(t=o(this,G).media.audio.canProduce)!=null?t:Te.media.audio.canProduce;return this.stageEnabled&&(o(this,Nt,qt)==="ACCEPTED_TO_JOIN_STAGE"||o(this,Nt,qt)==="ON_STAGE")&&e===Y.CanRequest?Y.Allowed:this.stageEnabled&&(o(this,Nt,qt)==="OFF_STAGE"||o(this,Nt,qt)==="REQUESTED_TO_JOIN_STAGE")&&e===Y.Allowed?Y.NotAllowed:e}get chatPublic(){var t,e,n;return(n=(e=(t=o(this,G))==null?void 0:t.chat)==null?void 0:e.public)!=null?n:Te.chat.public}get chatPrivate(){var t,e,n;return(n=(e=(t=o(this,G))==null?void 0:t.chat)==null?void 0:e.private)!=null?n:Te.chat.private}get chatChannel(){var t,e,n;return(n=(e=(t=o(this,G))==null?void 0:t.chat)==null?void 0:e.channel)!=null?n:Te.chat.channel}get chatMessage(){var t,e,n;return(n=(e=(t=o(this,G))==null?void 0:t.chat)==null?void 0:e.message)!=null?n:Te.chat.message}get connectedMeetings(){var t,e;return(e=(t=o(this,G))==null?void 0:t.connectedMeetings)!=null?e:Te==null?void 0:Te.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=o(this,G))==null?void 0:t.hiddenParticipant)!=null?e:Te.hiddenParticipant}get showParticipantList(){var t;return(t=o(this,G).showParticipantList)!=null?t:Te.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=o(this,G))==null?void 0:t.canChangeParticipantPermissions)!=null?e:Te.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=o(this,G))==null?void 0:t.canChangeParticipantPermissions)!=null?e:Te.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return o(this,G).media.audio.canProduce===Y.Allowed||o(this,G).media.video.canProduce===Y.Allowed||o(this,G).media.screenshare.canProduce===Y.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var t;return(t=o(this,G).canEditDisplayName)!=null?t:!1}get maxScreenShareCount(){return 1}get isRecorder(){return o(this,G).isRecorder}get canSpotlight(){return o(this,G).canSpotlight}get canLivestream(){return o(this,G).canLivestream}get transcriptionEnabled(){return o(this,G).transcriptionEnabled}};let yN=Ka;G=new WeakMap,$a=new WeakMap,vo=new WeakMap,sh=new WeakMap,Nt=new WeakSet,qt=function(){return o(this,vo).getValue("stageStatus")};var Ay;class SN extends zt{constructor(){super(...arguments),g(this,"localMediaHandler"),f(this,Ay,void 0)}updatePermission(){return u(this,null,function*(){var e,n;const i=(l,h)=>{this.mediaPermissions[l]=h;const m={message:this.mediaPermissions[l],kind:l};h==="DENIED"?R.emit(M.MEDIA_PERMISSION_ERROR,m):R.emit(M.MEDIA_PERMISSION_UPDATE,m)};if(Pe.getName()==="firefox")return;const r="microphone",s="camera",a=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:r}),c=yield(n=navigator==null?void 0:navigator.permissions)==null?void 0:n.query({name:s}),d=(l,h)=>{switch(h){case"granted":i(l,"ACCEPTED");break;case"denied":i(l,"DENIED");break;case"prompt":i(l,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};a&&(a.onchange=()=>d("audio",a.state)),c&&(c.onchange=()=>d("video",c.state))})}populateMediaPermissionsInCallstats(e){return u(this,arguments,function*({message:n,kind:i}){switch(i){case"audio":{K.mediaPermission("AUDIO",n),K.mediaPermission("SPEAKER",n);break}case"video":{K.mediaPermission("VIDEO",n);break}case"screenshare":{K.mediaPermission("SCREENSHARE",n);break}}})}init(){return u(this,arguments,function*(e={},n=!1,i=null){var r,s,a,c,d,l;if(Pe.init(),!this.localMediaHandler)try{let h=!0;if(i!=null&&i.getValue("defaults").mediaHandler)h=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:m}=navigator;this.localMediaHandler=yield m.init()}else this.localMediaHandler=new Bt(i,e.constraints,(r=i==null?void 0:i.getValue("defaults"))==null?void 0:r.isNonPreferredDevice,(s=i==null?void 0:i.getValue("defaults"))==null?void 0:s.autoSwitchAudioDevice);if(R.on(M.MEDIA_PERMISSION_UPDATE,m=>u(this,null,function*(){if(this.populateMediaPermissionsInCallstats({message:m.message,kind:m.kind}),m.message==="NOT_REQUESTED")switch(m==null?void 0:m.kind){case"audio":this.rawAudioTrack&&(p.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(p.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",m)})),R.on(M.MEDIA_PERMISSION_ERROR,m=>u(this,null,function*(){const{kind:y,message:S,constraints:b}=m;this.populateMediaPermissionsInCallstats({message:S,kind:y}),y==="audio"?(p.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):y==="video"&&(p.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),p.error("SelfController::mediaPermissionError",{error:{message:S},constraints:b,mediaPermissionsErrors:{kind:y,message:S}}),this.emit("mediaPermissionError",m),this.emit("mediaPermissionUpdate",{message:S,kind:y})})),h){p.info(`Setting up DyteSelfMedia streams using media handler. audio:${(a=e==null?void 0:e.audio)!=null?a:!0} video:${(c=e==null?void 0:e.video)!=null?c:!0}`);const m=this.localMediaHandler.setupStreams({video:(d=e==null?void 0:e.video)!=null?d:!0,audio:(l=e==null?void 0:e.audio)!=null?l:!0});n||(yield m)}}catch(h){p.error("DyteSelf::init::Failed To Setup Streams",{error:{name:h.name,message:h.message}})}})}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}addAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addAudioMiddleware(e)})}removeAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeAudioMiddleware(e)})}removeAllAudioMiddlewares(){return u(this,null,function*(){return this.localMediaHandler.removeAllAudioMiddlewares()})}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}addVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addVideoMiddleware(e)})}setVideoMiddlewareGlobalConfig(){return u(this,arguments,function*(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)})}removeVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeVideoMiddleware(e)})}removeAllVideoMiddlewares(){return u(this,null,function*(){return this.localMediaHandler.removeAllVideoMiddlewares()})}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}enableAudio(){return u(this,null,function*(){yield this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableVideo(){return u(this,null,function*(){yield this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}disableAudio(){return u(this,null,function*(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableVideo(){return u(this,null,function*(){yield this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}getAudioDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getAudioDevices()})}getVideoDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getVideoDevices()})}getSpeakerDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getSpeakerDevices()})}getDeviceById(e,n){let i;return n==="audio"?i="audioinput":n==="video"?i="videoinput":n==="speaker"&&(i="audiooutput"),this.localMediaHandler.getDeviceById(e,i)}setDevice(e){return u(this,null,function*(){switch(e.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(e)}catch{}finally{this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":yield this.localMediaHandler.setSpeakerDevice(e);break;case"videoinput":try{yield this.localMediaHandler.setVideoDevice(e)}catch{}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})})}}Ay=new WeakMap;const Pa={},Gi={executeWithLock({methodName:t,lockName:e,timeout:n}){return(i,r,s)=>{const a=s.value;return s.value=function(...c){if(Pa[e]){const h=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw h.name="UnsupportedConcurrentMethodExecution",p.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:h.stack},dyteLocker:{methodName:t,lockName:e}}),h}Pa[e]=!0;const d=setTimeout(()=>delete Pa[e],n),l=a.apply(this,c);return Promise.resolve(l).then(()=>{delete Pa[e],clearTimeout(d)}).catch(()=>{delete Pa[e],clearTimeout(d)}),l},s}}};var EN=Object.defineProperty,TN=Object.getOwnPropertyDescriptor,At=(t,e,n,i)=>{for(var r=i>1?void 0:i?TN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&EN(e,n,r),r},Ra,Dt,Ma,qn,Xi,es,Ze,at,Ge,Xe,Aa,Da,Sc,du,qg;let st=(qg=class extends SN{constructor(t,e,n,i,r){var s;super(),f(this,Xi),f(this,Ze),f(this,Ge),f(this,Sc),g(this,"name"),g(this,"picture"),g(this,"customParticipantId"),g(this,"waitlistStatus"),f(this,Ra,void 0),f(this,Dt,void 0),f(this,Ma,void 0),g(this,"role"),g(this,"userId"),g(this,"organizationId"),g(this,"supportsRemoteControl",!1),g(this,"device"),f(this,qn,void 0),g(this,"hidden",!1),g(this,"presetName"),g(this,"roomState","init"),f(this,Aa,new Set),f(this,Da,new Set),v(this,qn,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(s=e.customParticipantId)!=null?s:e.clientSpecificId,this.waitlistStatus="none",v(this,Dt,n),v(this,Ra,i),this.hidden=!1,v(this,Ma,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Pe.isElectron(),this.device=Pe.getDeviceInfo(),this.presetName=r,i.viewType!==Rt.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),H(this,Sc,du).call(this)}get stageStatus(){return o(this,qn).getValue("stageStatus")}get id(){return o(this,qn).getValue("peerId")}static __init__(t,e,n,i,r,s=!1){return u(this,null,function*(){var a,c,d,l,h;let m=(c=(a=t.getValue("defaults"))==null?void 0:a.audio)!=null?c:!0,y=(l=(d=t.getValue("defaults"))==null?void 0:d.video)!=null?l:!0;n.canProduceAudio!=="ALLOWED"&&(m=!1),n.canProduceVideo!=="ALLOWED"&&(y=!1);const S=new st(t,e,n,i,r);if(i.viewType===Rt.Chat)return S;const b=PO(i.mediaConstraints);return Si(b,(h=t.getValue("defaults"))==null?void 0:h.mediaConfiguration),yield S.init({audio:m,video:y,constraints:b},s,t),S.setupEvents(),S})}cleanupEvents(){this.removeAllListeners("videoUpdate"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("VIDEO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_LIST_UPDATED"),this.localMediaHandler.removeAllListeners("SCREENSHARE_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("SCREENSHARE_ENDED"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_SILENT"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_AUDIO"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_VIDEO"),o(this,Dt).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",H(this,Sc,du)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>u(this,null,function*(){if(p.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",U({},br(this))),o(this,Ge,Xe)&&this.audioEnabled)try{yield o(this,Ze,at).shareMic(this.audioTrack)}catch(t){p.error("DyteSelf::setupEvents::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",()=>u(this,null,function*(){if(p.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",U({},br(this))),o(this,Ge,Xe)&&this.rawVideoTrack===void 0)p.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&o(this,Ge,Xe))try{const t=yield o(this,Ze,at).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&Z.hasFeature(re.EXP_RESHARE)&&(yield o(this,Ze,at).shareWebcam(this.videoTrack))}catch(t){p.error("DyteSelf::setupEvents::failed shareWebcam",{error:t}),this.videoEnabled&&(yield this.localMediaHandler.disableVideo())}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})),this.localMediaHandler.on("DEVICE_CHANGE",t=>u(this,[t],function*({device:e}){this.emit("deviceUpdate",{device:e})})),this.localMediaHandler.on("DEVICE_LIST_UPDATED",t=>{this.emit("deviceListUpdate",t)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",()=>u(this,null,function*(){if(!o(this,Ge,Xe)){p.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield o(this,Ze,at).shareScreen(this.screenShareTracks)}catch(t){p.error("DyteSelf::setupEvents::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}p.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",U({},br(this))),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})),this.localMediaHandler.on("SCREENSHARE_ENDED",()=>u(this,null,function*(){p.log("Disabling screenshare due to SCREENSHARE_ENDED"),yield this.disableScreenShare(),p.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",U({},br(this)))})),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{K.mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",()=>u(this,null,function*(){o(this,Ge,Xe)&&(yield o(this,Ze,at).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),K.videoOff()})),o(this,Dt).on("permissionsUpdate",t=>{var e,n,i;(e=t==null?void 0:t.media)!=null&&e.audio&&o(this,Dt).canProduceAudio!==Y.Allowed&&(this.disableAudio(),p.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(n=t==null?void 0:t.media)!=null&&n.video&&o(this,Dt).canProduceVideo!==Y.Allowed&&(this.disableVideo(),p.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(i=t==null?void 0:t.media)!=null&&i.screenshare&&o(this,Dt).canProduceScreenshare!==Y.Allowed&&(this.disableScreenShare(),p.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return o(this,Dt)}get config(){return o(this,Ra)}get roomJoined(){var t;return o(this,Ra).viewType===Rt.Livestream&&this.stageStatus!=="ON_STAGE"?((t=o(this,qn).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:o(this,Ge,Xe)}setName(t){if(!t)throw new I("Name cannot be empty.","1103");this.name=t}setupTracks(){return u(this,arguments,function*(t={}){t.forceReset,yield this.disableAudio(),yield this.disableVideo(),this.localMediaHandler.removeAudioTrack(),this.localMediaHandler.removeVideoTrack(),t.audio&&(yield this.enableAudio()),t.video&&(yield this.enableVideo())})}destructMediaHandler(){return u(this,null,function*(){return this.localMediaHandler.destruct()})}removeDocumentEventListeners(){return u(this,null,function*(){return this.localMediaHandler.removeDocumentEventListeners()})}enableAudio(){return u(this,null,function*(){if(this.permissions.canProduceAudio!==Y.NotAllowed&&!(o(this,Dt).canProduceAudio===Y.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if(K.audioOn(),yield this.localMediaHandler.enableAudio(),o(this,Ge,Xe)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield o(this,Ze,at).shareMic(this.audioTrack)}catch(t){p.error("DyteSelf::enableAudio::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;o(this,Ze,at).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}})}enableVideo(){return u(this,null,function*(){if(o(this,Dt).canProduceVideo!==Y.NotAllowed&&!(o(this,Dt).canProduceVideo===Y.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if(K.videoOn(),yield this.localMediaHandler.enableVideo(),o(this,Ge,Xe)&&this.stageStatus==="ON_STAGE")try{yield o(this,Ze,at).shareWebcam(this.videoTrack)}catch(t){p.error("DyteSelf::enableVideo::Error while sharing video",{error:t}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),p.info("DyteSelf.enableVideo",U({},br(this)))}})}updateVideoConstraints(t){return u(this,null,function*(){if(!this.localMediaHandler.updateVideoConstraints)throw new I("Unsupported","1102");yield this.localMediaHandler.updateVideoConstraints(t)})}enableScreenShare(){return u(this,null,function*(){if(!o(this,Ge,Xe))throw new I("Can`t enable screenshare without joining room","1105");if(o(this,Dt).canProduceScreenshare!==Y.NotAllowed&&!(o(this,Dt).canProduceScreenshare===Y.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(yield this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{yield o(this,Ze,at).shareScreen(this.screenShareTracks)}catch(t){p.error("DyteSelf::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}})}updateScreenshareConstraints(t){return u(this,null,function*(){if(!this.localMediaHandler.updateScreenshareConstraints)throw new I("Unsupported","1102");yield this.localMediaHandler.updateScreenshareConstraints(t)})}disableAudio(){return u(this,null,function*(){this.audioEnabled&&(this.localMediaHandler.disableAudio(),o(this,Ge,Xe)&&o(this,Ze,at).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),K.audioOff())})}disableVideo(){return u(this,null,function*(){this.videoEnabled&&(yield this.localMediaHandler.disableVideo(),o(this,Ge,Xe)&&(yield o(this,Ze,at).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),K.videoOff())})}disableScreenShare(){return u(this,null,function*(){this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare(),o(this,Ge,Xe)&&(yield o(this,Ze,at).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var n;v(this,Ma,t);const i=t?"pinned":"unpinned";(n=o(this,Xi,es))==null||n.updateSource(this.id,{pinned:t}),e&&this.emit(i,this)}get isPinned(){return o(this,Ma)}pin(){return u(this,null,function*(){if(!o(this,Ge,Xe))throw new I("Can`t pin participants without joining room","1105");return this.show(),o(this,Ze,at).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!o(this,Ge,Xe))throw new I("Can`t unpin participants without joining room","1105");return o(this,Ze,at).pinPeer(null)})}hide(){return u(this,null,function*(){if(!o(this,Ge,Xe))throw new I("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})})}show(){if(!o(this,Ge,Xe))throw new I("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}setDevice(t){return u(this,null,function*(){var e,n,i;if(!t)throw new I("No device selected","1104");const r=this.getCurrentDevices();if(t.deviceId&&(((e=r==null?void 0:r.audio)==null?void 0:e.deviceId)===t.deviceId||((n=r==null?void 0:r.video)==null?void 0:n.deviceId)===t.deviceId||((i=r==null?void 0:r.speaker)==null?void 0:i.deviceId)===t.deviceId)&&(p.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),Z.hasFeature(re.SKIP_SETTING_IN_USE_DEVICE)))throw new I("Cannot set device currently in use","1106");switch(t.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(t)}catch{o(this,Ge,Xe)&&(yield o(this,Ze,at).muteSelf()),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":yield this.localMediaHandler.setSpeakerDevice(t);break;case"videoinput":try{yield this.localMediaHandler.setVideoDevice(t)}catch{o(this,Ge,Xe)&&(yield o(this,Ze,at).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}})}cleanUpTracks(){var t,e,n,i;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(n=this.videoTrack)==null||n.stop(),(i=this.rawVideoTrack)==null||i.stop()}registerVideoElement(t,e=!1){var n,i;e?o(this,Aa).add(t):o(this,Da).add(t),this.updateVideo(t),e||(i=o(this,Xi,es))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t,e=!1){t.srcObject=void 0,e?o(this,Aa).delete(t):(o(this,Da).delete(t),o(this,Xi,es).removeSource(this.id))}updateVideo(t,e=!1){var n,i,r;if(this.videoEnabled){if(this.videoTrack==null)return;const s=(n=t.srcObject)==null?void 0:n.getTracks()[0];if((s==null?void 0:s.id)===this.videoTrack.id)return;const a=new MediaStream;a.addTrack(this.videoTrack),t.srcObject=a,e||(i=o(this,Xi,es))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(r=o(this,Xi,es))==null||r.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Ra=new WeakMap,Dt=new WeakMap,Ma=new WeakMap,qn=new WeakMap,Xi=new WeakSet,es=function(){return o(this,qn).getValue("pip")},Ze=new WeakSet,at=function(){return o(this,qn).getValue("roomNodeClient")},Ge=new WeakSet,Xe=function(){var t;return((t=o(this,qn).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Aa=new WeakMap,Da=new WeakMap,Sc=new WeakSet,du=function(){Array.from(o(this,Da)).forEach(t=>this.updateVideo(t,!1)),Array.from(o(this,Aa)).forEach(t=>this.updateVideo(t,!0))},qg);At([E.trace("DyteSelf.cleanupEvents")],st.prototype,"cleanupEvents",1);At([E.trace("DyteSelf.setupEvents")],st.prototype,"setupEvents",1);At([E.trace("DyteSelf.setupTracks")],st.prototype,"setupTracks",1);At([E.trace("DyteSelf.destructMediaHandler")],st.prototype,"destructMediaHandler",1);At([E.trace("DyteSelf.removeDocumentEventListeners")],st.prototype,"removeDocumentEventListeners",1);At([Gi.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),E.trace("DyteSelf.enableAudio")],st.prototype,"enableAudio",1);At([Gi.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),E.trace("DyteSelf.enableVideo")],st.prototype,"enableVideo",1);At([E.trace("DyteSelf.updateVideoConstraints")],st.prototype,"updateVideoConstraints",1);At([E.trace("DyteSelf.enableScreenShare"),Gi.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],st.prototype,"enableScreenShare",1);At([E.trace("DyteSelf.updateScreenshareConstraints")],st.prototype,"updateScreenshareConstraints",1);At([Gi.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),E.trace("DyteSelf.disableAudio")],st.prototype,"disableAudio",1);At([Gi.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),E.trace("DyteSelf.disableVideo")],st.prototype,"disableVideo",1);At([Gi.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),E.trace("DyteSelf.disableScreenShare")],st.prototype,"disableScreenShare",1);At([E.trace("DyteSelf.setDevice")],st.prototype,"setDevice",1);st=At([gt("1100")],st);var kN=Object.defineProperty,bN=Object.getOwnPropertyDescriptor,_N=(t,e,n,i)=>{for(var r=i>1?void 0:i?bN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&kN(e,n,r),r};let ts;var Ec,Gg;const Dy=(Gg=class{constructor(t,e){g(this,"socket"),f(this,Ec,void 0),v(this,Ec,e),this.socket=t,this.handleSocketEvents()}static create(t,e){return ts||(ts=new Dy(t,e)),ts}static cleanup(){var t;try{(t=ts==null?void 0:ts.socket)==null||t.disconnect()}catch{p.error("roomSocketHandler::cleanup")}ts=void 0}joinRoom(t){return u(this,null,function*(){var e;this.socket.joinAttempted=!0;const n={capabilities:[],peer:{displayName:(e=t.name)!=null?e:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},i=this.socket.sendMessagePromise(j.joinRoom,xR.toBinary(n));try{const{peer:r}=ns.fromBinary((yield i).payload);o(this,Ec).getValue("connectionHandler").socketJoined=!0,R.emit(M.SOCKET_SERVICE_ROOM_JOINED,{peer:r});const s=this.getRoomState(),a=this.getRoomPeersNonPaginated(),[{room:c},{peers:d}]=yield Promise.all([s,a]);return R.emit(M.ROOM_STATE,c),R.emit(M.SOCKET_PEERS,d),{peer:r}}catch(r){throw p.error("RoomSocketHandler.joinRoom.failed",{error:r}),new I("Error: RoomSocketHandler.joinRoom failed.","0002",r)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return EM.fromBinary((yield this.socket.sendMessagePromise(j.getAllAddedParticipants)).payload).participants.map(t=>{var e=t,{id:n}=e,i=Qd(e,["id"]);return J(U({},i),{userId:n})})}catch{return[]}})}getRoomPeers(t,e,n){return u(this,null,function*(){let i;try{const r={seachQuery:t,limit:e,offset:n},s=yield this.socket.sendMessagePromise(j.getRoomPeersInfo,IR.toBinary(r));i=Jl.fromBinary(s.payload)}catch(r){p.error("getRoomPeers::binary_decode_error",{error:r})}return i})}getRoomPeersNonPaginated(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(j.getRoomPeersInfo);t=Jl.fromBinary(e.payload)}catch(e){p.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(j.getRoomPeersInfo);t=Jl.fromBinary(e.payload)}catch(e){p.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return u(this,null,function*(){let e;try{const n=yield this.socket.sendMessagePromise(j.getPeerInfo,sy.toBinary({peerId:t}));e=ns.fromBinary(n.payload)}catch(n){p.error("getPeerInfo::binary_decode_error",{error:n})}return e})}getRoomState(){return u(this,null,function*(){let t=dg.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomInfo);t=dg.fromBinary(e.payload)}catch(e){p.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=pg.create();try{const e=yield this.socket.sendMessagePromise(j.getRoomStageState);t=pg.fromBinary(e.payload)}catch(e){p.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return u(this,null,function*(){const n={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(j.broadcastMessage,da.toBinary(n))})}broadcastToMeetings(t,e,n){return u(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(n)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(j.broadcastToEntity,da.toBinary(i))})}broadcastToPeers(t,e,n){return u(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(n)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(j.broadcastToEntity,da.toBinary(i))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(j.leaveRoom,UR.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(j.kick,_M.toBinary(e))})}kickAll(t=!1){return u(this,null,function*(){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(j.kickAll,ny.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage(j.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.acceptWaitingRoomRequests,CM.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(j.denyWaitingRoomRequests,RM.toBinary(e))}updatePermissions(t,e){return u(this,null,function*(){const n={updatePeersPresets:[]};return t.forEach(i=>{n.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Lc.updateUserPreset,rA.toBinary(n))})}handleSocketEvents(){this.socket.on(j.broadcastMessage,({payload:t})=>{try{const e=da.fromBinary(t);R.emit(M.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){p.error("failed to decode broadcast message:",e)}}),this.socket.on(j.broadcastToEntity,({payload:t})=>{try{const e=da.fromBinary(t);R.emit(M.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){p.error("failed to decode peer broadcast message:",e)}})}on(t,e){let n,i;switch(t){case j.joinRoom:case j.leaveRoom:case j.kick:case j.kickAll:{n=ns.fromBinary.bind(ns),i=ns.create();break}case j.getWaitingRoomRequests:{n=(r,s)=>r?hg.fromBinary(r,s):{requests:[]},i=hg.create();break}case j.recordingPaused:case j.recordingStarted:case j.recordingStopped:{n=kg.fromBinary.bind(kg);break}case Lc.updateUserPreset:{n=mg.fromBinary.bind(mg);break}case En.peerJoinedBroadcast:case sn.peerJoinedBroadcast:{n=ig.fromBinary.bind(ig);break}case En.selfJoinComplete:case sn.selfJoinComplete:{n=Bu.fromBinary.bind(Bu);break}case En.globalPeerPinBroadcast:case sn.globalPeerPinBroadcast:{n=ag.fromBinary.bind(ag);break}case En.selectedPeer:case sn.selectedPeer:{n=Fu.fromBinary.bind(Fu);break}case En.selectedPeerDiff:case sn.selectedPeerDiff:{n=ng.fromBinary.bind(ng);break}case En.leaveRoom:case sn.leaveRoom:{n=Wu.fromBinary.bind(Wu);break}}this.socket.on(t,({payload:r})=>{let s=i;if(!n)return e(void 0);try{s=n(r)}catch(a){p.error("roomSocketHandler::on::binary_decode_error",{error:a})}return e(s)})}getUserPermissions(t){return u(this,null,function*(){const e={userIds:[t]};try{const n=yield this.socket.sendMessagePromise(Lc.getUserPresets,QM.toBinary(e)),i=tA.fromBinary(n.payload).peerPresets[0],r=new TextDecoder().decode(i.preset),s=JSON.parse(r).permissions;return{chat:s.chat,polls:s.polls,plugins:s.plugins}}catch(n){throw p.error("Error in getting user preset",{error:n}),n}})}},Ec=new WeakMap,Gg);let Ld=Dy;_N([E.trace("RoomSocketHandler.joinRoom")],Ld.prototype,"joinRoom",1);var Ar={},gl={};Object.defineProperty(gl,"__esModule",{value:!0});gl.Logger=void 0;class wN{constructor(e){}debug(){}warn(){}error(){}}gl.Logger=wN;Object.defineProperty(Ar,"__esModule",{value:!0});var xd=Ar.AwaitQueue=Ar.AwaitQueueRemovedTaskError=Ar.AwaitQueueStoppedError=void 0;const IN=gl,gi=new IN.Logger;class Sp extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Sp)}}Ar.AwaitQueueStoppedError=Sp;class fl extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,fl)}}Ar.AwaitQueueRemovedTaskError=fl;class CN{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}push(e,n){return u(this,null,function*(){if(n=n!=null?n:e.name,gi.debug(`push() [name:${n}]`),typeof e!="function")throw new TypeError("given task is not a function");if(n)try{Object.defineProperty(e,"name",{value:n})}catch{}return new Promise((i,r)=>{const s={id:this.nextTaskId++,task:e,name:n,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(s.completed)return;s.completed=!0,this.pendingTasks.delete(s.id),gi.debug(`resolving task [name:${s.name}]`),i(a);const[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)},reject:a=>{if(!s.completed&&(s.completed=!0,this.pendingTasks.delete(s.id),gi.debug(`rejecting task [name:${s.name}]: %s`,String(a)),r(a),!this.stopping)){const[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)}}};this.pendingTasks.set(s.id,s),this.pendingTasks.size===1&&this.execute(s)})})}stop(){gi.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())gi.debug(`stop() | stopping task [name:${e.name}]`);this.stopping=!1}remove(e){gi.debug(`remove() [taskIdx:${e}]`);const n=Array.from(this.pendingTasks.values())[e];if(!n){gi.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}n.reject(new fl)}dump(){const e=Date.now();let n=0;return Array.from(this.pendingTasks.values()).map(i=>({idx:n++,task:i.task,name:i.name,enqueuedTime:i.executedAt?i.executedAt-i.enqueuedAt:e-i.enqueuedAt,executionTime:i.executedAt?e-i.executedAt:0}))}execute(e){return u(this,null,function*(){if(gi.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const n=yield e.task();e.resolve(n)}catch(n){e.reject(n)}})}}xd=Ar.AwaitQueue=CN;function PN(t,e){const n=new Error(e);return n.name=t,n}class xo extends I{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,xo):this.stack=new Error(e).stack}}class Pt extends I{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Pt):this.stack=new Error(e).stack}}class Ms extends I{constructor(e){super(e),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Pt):this.stack=new Error(e).stack}}class RN extends I{constructor(e){super(e),this.name="DataChannelRequestError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Pt):this.stack=new Error(e).stack}}const Jg=t=>new Promise(e=>setTimeout(e,t));function Ep(t,e){return u(this,null,function*(){return new Promise((n,i)=>u(this,null,function*(){const{strategy:r,maxRetryCount:s,delayTime:a}=U({strategy:"linear",maxRetryCount:3,delayTime:10},e);let c=0,d,l=!1;const h=m=>{l=!0,i(m)};for(;c<s;){try{const m=yield t(c,h);return n(m)}catch(m){if(d=m,l)break;if(c<s)r==="linear"?yield Jg(a*(c+1)):r==="exponential"&&(yield Jg(a*(c+Math.max(0,c-1))));else break}c+=1}return i(d)}))})}function MN(t){return t.map(e=>({channels:e.channels,clockRate:e.clockRate,mimeType:e.mimeType,sdpFmtpLine:e.sdpFmtpLine}))}function AN(t){return t.map(e=>({uri:e.uri}))}function Tc(t){return{codecs:MN(t.codecs),headerExtensions:AN(t.headerExtensions)}}function DN(t){const e=RTCRtpReceiver.getCapabilities("audio"),n=RTCRtpReceiver.getCapabilities("video"),i=RTCRtpSender.getCapabilities("audio"),r=RTCRtpSender.getCapabilities("video");t&&(n.codecs=n.codecs.filter(({mimeType:a})=>t===a),r.codecs=r.codecs.filter(({mimeType:a})=>t===a));const s={audio:Tc(e),video:Tc(n)};return{sender:{audio:Tc(i),video:Tc(r)},receiver:s}}var lt;class ON{constructor(e,n){f(this,lt,void 0),g(this,"events"),g(this,"sfuType"),v(this,lt,e),this.sfuType=n,this.events=n===it.CF?En:sn}joinRoom(e,n,i,r=!1,s=null){return u(this,null,function*(){const a={roomUuid:e,displayName:n,prejoined:r,capabilities:i};return s&&(a.location=s),(yield o(this,lt).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:VC.toBinary(a),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const n=(yield o(this,lt).sendMessagePromise(this.events.createWebRTCTransport,hC.toBinary(e))).payload,{transportId:i,description:r,producerIds:s}=Zv.fromBinary(n),a={sdp:r==null?void 0:r.sdp,type:r.type};return{transportId:i,answer:a,producerIds:s}})}produce(e){return u(this,null,function*(){var n,i;const r=(yield o(this,lt).sendMessagePromise(this.events.produce,KC.toBinary(e))).payload,s=AP.fromBinary(r);return{answer:{sdp:(n=s==null?void 0:s.description)==null?void 0:n.sdp,type:(i=s==null?void 0:s.description)==null?void 0:i.type},producerId:s.producerId}})}consume(e){return u(this,null,function*(){if(this.sfuType===it.HIVE)throw new Error("Hive does not support socket consumer operations");const n=(yield o(this,lt).sendMessagePromise(this.events.consume,JC.toBinary(e))).payload,{consumerIdsMap:{map:i},description:r}=RP.fromBinary(n);return{consumerStateMap:i,sessionDescription:r}})}closeProducer(e){return u(this,null,function*(){const n=(yield o(this,lt).sendMessagePromise(this.events.closeProducer,tP.toBinary(e))).payload,{description:i}=UP.fromBinary(n);return i})}closeConsumer(e){return u(this,null,function*(){if(this.sfuType===it.HIVE)throw new Error("Hive does not support socket consumer operations");return(yield o(this,lt).sendMessagePromise(this.events.closeConsumer,iP.toBinary(e))).payload})}hostControlForPeer(e,n){return u(this,null,function*(){const i={audio:n==="audio",screeShare:!1,video:n==="video",participantId:e},r=(yield o(this,lt).sendMessagePromise(this.events.hostControlPeer,lP.toBinary(i))).payload;if(!r)return!1;const{status:s}=$P.fromBinary(r);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const n={audio:e==="audio",screenShare:!1,video:e==="video"},i=(yield o(this,lt).sendMessagePromise(this.events.hostControlAllPeers,hP.toBinary(n))).payload;if(!i)return!1;const{status:r}=zP.fromBinary(i);return r==="success"})}kickAll(){return u(this,null,function*(){const e={propagateKickAcrossRooms:!1},n=(yield o(this,lt).sendMessagePromise(this.events.kickAll,ny.toBinary(e))).payload;if(!n)return!1;const{status:i}=GP.fromBinary(n);return i==="success"})}kickPeer(e){return u(this,null,function*(){const n=(yield o(this,lt).sendMessagePromise(this.events.kickPeer,sP.toBinary(e))).payload;if(!n)return!1;const{status:i}=HP.fromBinary(n);return i==="success"})}changeDisplayName(e){return u(this,null,function*(){const n=(yield o(this,lt).sendMessagePromise(this.events.changeDisplayName,cP.toBinary(e))).payload;if(!n)return!1;const{status:i}=QP.fromBinary(n);return i==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},n=(yield o(this,lt).sendMessagePromise(this.events.selfJoinComplete,FC.toBinary(e))).payload;return Bu.fromBinary(n)})}audioActivity(e){return u(this,null,function*(){o(this,lt).sendMessage(this.events.audioActivity,mC.toBinary(e))})}}lt=new WeakMap;class Vo extends mt.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}safeEmit(e,...n){const i=this.listenerCount(e);try{return this.emit(e,...n)}catch(r){return p.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:r}),Boolean(i)}}safeEmitAsPromise(e,...n){return u(this,null,function*(){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...n)})}safeEmitAsPromiseWithTimeout(e,n,...i){return u(this,null,function*(){return new Promise((r,s)=>{setTimeout(s,n,"event request timeout");try{this.emit(e.toString(),...i,r,s)}catch(a){p.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:a}),s(a)}})})}}class Tp extends Vo{constructor(){super(...arguments),g(this,"_sendWebStream",new MediaStream),g(this,"_sendScreenShareStream",new MediaStream),g(this,"_direction"),g(this,"pc"),g(this,"_transportReady",!1),g(this,"_mapMidTransceiver",new Map),g(this,"enableHighBitrate",!1),g(this,"enableStereo",!1),g(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(p.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){p.error(`${this.name}::pc.close()`,{error:e})}}restartIce(){return u(this,null,function*(){p.debug(`${this.name}::restartIce()`);const e=yield this.pc.createOffer({iceRestart:!0});return p.debug(`${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:n=>u(this,null,function*(){p.info(`${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this.pc.setRemoteDescription(n)})}})}init({direction:e,iceServers:n,iceTransportPolicy:i,additionalSettings:r,proprietaryConstraints:s,onTrackHandler:a}){p.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection(U({iceServers:n||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},r),s),a&&this.pc.addEventListener("track",c=>{a(c)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this.pc.createDataChannel("dyte"),n=yield this.pc.createOffer();return yield this.pc.setLocalDescription(n),p.info(`connect offer: ${JSON.stringify(n)}`),{offerSdp:n,callback:i=>u(this,null,function*(){p.debug(`${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this.pc.setRemoteDescription(i),e.close()})}})}getTransportStats(){return u(this,null,function*(){return this.pc.getStats()})}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");return n.receiver.getStats()})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),p.debug(`stopSending() [localId:${e}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");n.sender.replaceTrack(null),this.pc.removeTrack(n.sender),n.direction="inactive";const i=yield this.pc.createOffer();return p.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),yield this.pc.setLocalDescription(i),{offerSdp:i,callback:r=>u(this,null,function*(){p.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this.pc.setRemoteDescription(r),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,n){return u(this,null,function*(){this._assertSendDirection(),n?p.debug(`replaceTrack() [localId:${e}, track.id:${n.id}]`):p.debug(`replaceTrack() [localId:${e}, no track]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");yield i.sender.replaceTrack(n)})}setMaxSpatialLayer(e,n){return u(this,null,function*(){this._assertSendDirection(),p.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${n}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const r=i.sender.getParameters();r.encodings.forEach((s,a)=>{a<=n?s.active=!0:s.active=!1}),yield i.sender.setParameters(r)})}setRtpEncodingParameters(e,n){return u(this,null,function*(){this._assertSendDirection(),p.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(n)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const r=i.sender.getParameters();r.encodings.forEach((s,a)=>{r.encodings[a]=U(U({},s),n)}),yield i.sender.setParameters(r)})}getSenderStats(e){this._assertSendDirection();const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");return n.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:p.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),p.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":p.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":p.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:p.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{p.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this.pc.addEventListener("datachannel",e=>{p.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:n}=e;n.onopen=()=>{p.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},n.onclose=()=>{p.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},n.onerror=()=>{p.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class kp extends Tp{static createFactory(){return()=>new kp}get name(){return"Chrome74"}init({direction:e,iceServers:n,iceTransportPolicy:i,additionalSettings:r,proprietaryConstraints:s,onTrackHandler:a}){this._direction=e,this.pc=new RTCPeerConnection(U({iceServers:n||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},r),s),a&&this.pc.addEventListener("track",c=>{a(c)}),this._addEventListeners()}send(e){return u(this,arguments,function*({track:n,encodings:i,codecOptions:r,screenShare:s}){this._assertSendDirection();const a=this.pc.addTransceiver(n,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:i});if(!navigator.isReactNative){p.debug("creating new transceiver");const l=RTCRtpSender.getCapabilities(typeof n=="string"?n:n.kind);p.info(`senders available params: ${JSON.stringify(l)}`);const h=[];r&&r.length&&r.forEach(m=>{var y;const S=l.codecs.find(b=>b.mimeType.includes(m.name));if(m.parameters){p.debug(`codecOption.parameters:${JSON.stringify(m.parameters)}`);const b=((y=S.sdpFmtpLine)==null?void 0:y.split(";"))||[];b.push(...m.parameters);const D=Array.from(new Set(b).values());S.sdpFmtpLine=D.join(";")}h.push(S)}),p.info(`selected codecs: ${JSON.stringify(h)}`),a.setCodecPreferences(h)}const c=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(c),r&&r.findIndex(({name:l})=>l==="opus")>=0){const{enableDtx:l,enableStereo:h}=this,m=this.enableHighBitrate?h?128e3:64e3:h?64e3:32e3;c.sdp=c.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${l?"usedtx=1;":""}${h?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${m}`),c.sdp+=`a=rtcp-fb:111 nack\r
20
20
  `}this.midTransceiverMap.set(a.mid,a);const d=l=>u(this,null,function*(){return p.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(l)}]`),yield this.pc.setRemoteDescription(l),a.mid});return p.debug(`send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(c,void 0,2)}]`),{offerSdp:c,callback:d,sender:a.sender,mid:a.mid}})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:n}=e;n.onmessage=i=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(i.data)))}})}}class Vd extends Tp{constructor(e){super(),g(this,"supportsSendEncodings",!1),this.supportsSendEncodings=e.supportsSendEncodings}static createFactory(e){return()=>new Vd(e)}get name(){return"Firefox60"}send(e){return u(this,arguments,function*({track:n,encodings:i,codecOptions:r,screenShare:s}){this._assertSendDirection();const a=this.supportsSendEncodings&&i!==void 0?{sendEncodings:i}:{},c=this.pc.addTransceiver(n,U({direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream]},a));if(!this.supportsSendEncodings&&i){i.reverse();const h=c.sender.getParameters();h.encodings=i,yield c.sender.setParameters(h)}const d=(h,m)=>{var y;const S=po(h),b=S.media[S.media.length-1],D=b.rtp.filter(q=>m.some(w=>w.name===q.codec)),C=b.fmtp.filter(q=>D.some(w=>w.payload===q.payload)),V=(y=b.rtcpFb)==null?void 0:y.filter(q=>D.some(w=>w.payload===q.payload)),L=D.map(q=>q.payload);return S.media[S.media.length-1].rtp=D,S.media[S.media.length-1].fmtp=C,S.media[S.media.length-1].rtcpFb=V,S.media[S.media.length-1].payloads=L.join(" "),_u(S)},l=yield this.pc.createOffer();if(l.sdp=d(l.sdp,r),p.debug(`send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),yield this.pc.setLocalDescription(l),n==="audio"||n.kind==="audio"){const{enableDtx:h,enableStereo:m}=this,y=this.enableHighBitrate?m?128e3:64e3:m?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${m?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${y}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:h=>u(this,null,function*(){return p.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this.pc.setRemoteDescription(h),c.mid}),sender:c.sender,mid:c.mid}})}setMaxSpatialLayer(e,n){return u(this,null,function*(){this._assertSendDirection(),p.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${n}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const r=i.sender.getParameters(),s=r.encodings.length-1-n;r.encodings.forEach((a,c)=>{c>=s?a.active=!0:a.active=!1}),yield i.sender.setParameters(r)})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:n}=e;n.onmessage=i=>u(this,null,function*(){const r=yield i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(r)))})})}}class bp extends Tp{static createFactory(){return()=>new bp}get name(){return"Chrome74"}send(e){return u(this,arguments,function*({track:n,encodings:i,codecOptions:r,screenShare:s}){this._assertSendDirection(),p.debug("Safari12::creating new transceiver");const a=this.pc.addTransceiver(n,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:i}),c=RTCRtpSender.getCapabilities(typeof n=="string"?n:n.kind);p.info(`Safari12::senders available params: ${JSON.stringify(c)}`);const d=[];r&&r.length>0&&r.forEach(h=>{var m;const y=c.codecs.find(S=>S.mimeType.includes(h.name));if(h.parameters){p.info(`Safari12::codecOption.parameters:, ${JSON.stringify(h.parameters)}`);const S=((m=y.sdpFmtpLine)==null?void 0:m.split(";"))||[];S.push(...h.parameters);const b=[...new Set(S).values()];y.sdpFmtpLine=b.join(";")}d.push(y)}),p.info(`Safari12::selected codecs: ${JSON.stringify(d)}`),a.setCodecPreferences(d);const l=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(l),n==="audio"||n.kind==="audio"){const{enableStereo:h,enableDtx:m}=this,y=this.enableHighBitrate?h?128e3:64e3:h?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${m?"usedtx=1;":""}${h?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${y}`)}return this.midTransceiverMap.set(a.mid,a),{offerSdp:l,callback:h=>u(this,null,function*(){return p.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this.pc.setRemoteDescription(h),a.mid}),sender:a.sender,mid:a.mid}})}addCustomEventListeners(){this.pc.ondatachannel=e=>{const{channel:n}=e;n.onmessage=i=>u(this,null,function*(){const r=String.fromCharCode(...new Uint8Array(i.data));this.safeEmit("datachannel",e.channel,r)})}}}function NN(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}var Gc,ds,Kn,Qn,Oi,Jc,lu,ah,Oy,oh,Ny;class LN extends Vo{constructor(e){var n;super(),f(this,Qn),f(this,Jc),f(this,ah),f(this,oh),g(this,"rtpReceiver"),g(this,"id"),g(this,"localId"),g(this,"producerId"),g(this,"producingTransportId"),g(this,"mimeType"),g(this,"track"),g(this,"peerId"),g(this,"appData"),g(this,"transceiver"),f(this,Gc,void 0),f(this,ds,void 0),f(this,Kn,void 0),this.id=e.id,this.localId=e.localId,v(this,Gc,e.handler),this.appData=e.appData,this.peerId=e.producingPeerId,this.producingTransportId=e.producingTransportId,v(this,Kn,!1),this.producerId=e.producerId,this.track=e.track,v(this,ds,(n=e.paused)!=null?n:!1),this.mimeType=e.mimeType,this.transceiver=e.transceiver,this.rtpReceiver=e.rtpReceiver,H(this,ah,Oy).call(this)}get closed(){return o(this,Kn)}get kind(){return this.track.kind}get paused(){return o(this,ds)}close(e,n){o(this,Kn)||(p.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,o(this,Qn,Oi)),v(this,Kn,!0),n&&(H(this,oh,Ny).call(this),this.transceiver.stop()),this.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(o(this,Kn))throw new Pt("closed");return o(this,Gc).getReceiverStats(this.localId)})}pause(){if(p.debug("consumer::pause()",o(this,Qn,Oi)),o(this,Kn)){p.error("consumer::pause() | Consumer closed",o(this,Qn,Oi));return}v(this,ds,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(p.debug("consumer::resume()",o(this,Qn,Oi)),o(this,Kn)){p.error("Consumer::resume() | Consumer closed",o(this,Qn,Oi));return}v(this,ds,!1),this.track.enabled=!0,this.safeEmit("resume")}}Gc=new WeakMap,ds=new WeakMap,Kn=new WeakMap,Qn=new WeakSet,Oi=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Jc=new WeakSet,lu=function(){p.debug('Consumer::track "ended" event',o(this,Qn,Oi)),this.safeEmit("trackended")},ah=new WeakSet,Oy=function(){this.track.addEventListener("ended",H(this,Jc,lu).bind(this))},oh=new WeakSet,Ny=function(){try{this.track.removeEventListener("ended",H(this,Jc,lu)),this.track.stop()}catch(t){p.error("Consumer::destroyTrack()",J(U({},o(this,Qn,Oi)),{error:t}))}};var An,za,Ya,ls,vn,ut,cr,Qa,tn,yn;class xN extends Vo{constructor(e){var n,i;super(),f(this,tn),g(this,"id"),g(this,"localId"),f(this,An,void 0),g(this,"kind"),g(this,"appData"),g(this,"rtpSender"),f(this,za,void 0),f(this,Ya,void 0),f(this,ls,void 0),f(this,vn,!1),f(this,ut,void 0),f(this,cr,void 0),f(this,Qa,void 0),this.id=e.id,this.localId=e.localId,v(this,ut,e.track),this.kind=(n=e.track)==null?void 0:n.kind,v(this,cr,e.disableTrackOnPause?!((i=e.track)!=null&&i.enabled):!1),v(this,Qa,void 0),v(this,za,e.stopTracks),v(this,Ya,e.disableTrackOnPause),v(this,ls,e.zeroRtpOnPause),this.appData=e.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),v(this,An,e.handler),this.rtpSender=e.rtpSender,this._handleTrack()}get closed(){return o(this,vn)}get track(){return o(this,ut)}get paused(){return o(this,cr)}get maxSpatialLayer(){return o(this,Qa)}close(e){return u(this,null,function*(){if(o(this,vn))return;if(p.debug(`Producer::close() ${e?`with reason ${e}`:""}`,o(this,tn,yn)),v(this,vn,!0),this._destroyTrack(),e===dh){this.safeEmit("close");return}const{offerSdp:n,callback:i}=yield o(this,An).stopSending(this.localId),{answer:r}=yield this.safeEmitAsPromise("close",{offer:n,reason:e});i(r)})}getStats(){return u(this,null,function*(){if(o(this,vn))throw new Pt("closed");return o(this,An).getSenderStats(this.localId)})}pause(){p.debug("Producer::pause()",o(this,tn,yn)),o(this,vn)&&p.error("Producer::pause() | Producer closed",o(this,tn,yn)),v(this,cr,!0),o(this,ut)&&o(this,Ya)&&(o(this,ut).enabled=!1),o(this,ls)&&o(this,An).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(p.debug("Producer::resume()",o(this,tn,yn)),o(this,vn)){p.error("Producer::resume() | Producer closed",o(this,tn,yn));return}v(this,cr,!1),o(this,ut)&&o(this,Ya)&&(o(this,ut).enabled=!0),o(this,ls)&&o(this,An).replaceTrack(this.localId,o(this,ut)),this.emit("resume")}replaceTrack(e){return u(this,arguments,function*({track:n}){if(p.debug(`Producer::replaceTrack() trackId: ${n==null?void 0:n.id}`,o(this,tn,yn)),o(this,vn)){if(n&&o(this,za))try{n.stop()}catch(i){p.error("Producer::replaceTrack",J(U({},o(this,tn,yn)),{error:i}))}throw new Pt("closed")}else if(n&&n.readyState==="ended")throw new Pt("track ended");if(n===o(this,ut)){p.debug(`replaceTrack() | same track, ignored trackId: ${n.id}`,o(this,tn,yn));return}(!o(this,ls)||!o(this,cr))&&(yield o(this,An).replaceTrack(this.localId,n)),this._destroyTrack(),v(this,ut,n),this._handleTrack()})}setMaxSpatialLayer(e){return u(this,null,function*(){if(o(this,vn))throw new Pt("closed");if(this.kind!=="video")throw new xo("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield o(this,An).setMaxSpatialLayer(this.localId,e),v(this,Qa,e)})}setRtpEncodingParameters(e){return u(this,null,function*(){if(o(this,vn))throw new Pt("closed");if(typeof e!="object")throw new TypeError("invalid params");yield o(this,An).setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){p.debug(`Producer::track "ended" event trackId: ${this.track.id}`,o(this,tn,yn)),this.safeEmit("trackended",this.track.id)}_handleTrack(){o(this,ut)&&o(this,ut).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(o(this,ut))try{o(this,ut).removeEventListener("ended",this._onTrackEnded),o(this,za)&&o(this,ut).stop()}catch(n){p.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,J(U({},o(this,tn,yn)),{error:n}))}}}An=new WeakMap,za=new WeakMap,Ya=new WeakMap,ls=new WeakMap,vn=new WeakMap,ut=new WeakMap,cr=new WeakMap,Qa=new WeakMap,tn=new WeakSet,yn=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function Ly(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function ch(t){return Math.random().toString(36).substring(2,2+t)}const kc=1;function $g(t){const e=t;return delete e.payload._bolt,e}function VN(t){return t.payload&&Ly(t.payload)}function xy(t){var e,n;return VN(t)&&(n=(e=t.payload._bolt)==null?void 0:e.id)!=null?n:""}var dr;const Xa=class extends mt.EventEmitter{constructor(t,e,n){super(),g(this,"channel"),g(this,"queue"),g(this,"serverProtocolVersion"),f(this,dr,new Map),g(this,"respond",(i,r,s=!1)=>{let a;s?a=Xa.createErrorResponse(i,r):a=Xa.createResponse(i,r),this.channel.send(JSON.stringify(a))}),g(this,"notify",i=>{const r=Xa.createNotification(i);this.channel.send(JSON.stringify(r))}),g(this,"request",i=>u(this,null,function*(){const r=Xa.createRequest(i),s=new Promise((a,c)=>{const d=1e3*(5+.1*this.queue.size),{id:l}=r.payload._bolt,h={id:l,method:r.type,resolve:m=>{this.queue.delete(l)&&(clearTimeout(h.timer),a(m))},timer:setTimeout(()=>{this.queue.delete(l)&&c(new Error(`request timeout for message id: ${l}`))},d),cancel:m=>{this.queue.delete(l)&&(clearTimeout(h.timer),c(m))}};this.queue.set(l,h)});return this.channel.send(JSON.stringify(r)),s})),g(this,"send",i=>{const r=JSON.stringify(i),s=16384;if(r.length>s){const a=s-200,c=Math.ceil(r.length/a),d=[];for(let h=0;h<c;h+=1){const m=h*a,y=(h+1)*a;d.push(r.slice(m,y))}const l=Fs();for(let h=0;h<c;h+=1){const m=d[h],y=JSON.stringify({id:l,count:c,chunkIndex:h,chunk:m});p.debug(`Sending message chunk over dc: ${y}`),this.channel.send(y)}}else p.debug(`Sending message over dc: ${r}`),this.channel.send(r)}),g(this,"processMessage",i=>{var r;o(this,dr).has(i.id)||o(this,dr).set(i.id,[]);const s=o(this,dr).get(i.id);if(s[i.chunkIndex]=i,(s==null?void 0:s.length)===i.count&&!s.some(a=>a===void 0)){const a=o(this,dr).get(i.id),c=a==null?void 0:a.reduce((l,h)=>l+h.chunk,"");o(this,dr).delete(i.id);const d=JSON.parse(c);if(!d.payload||!Ly(d.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:d}});if(this.processBoltHandshake(d))return;if(this.serverProtocolVersion=(r=d.payload._bolt)==null?void 0:r.version,!this.processResponseMsg(d))return d}}),g(this,"processResponseMsg",i=>{const{id:r}=i.payload._bolt,s=this.queue.get(r);return s?(p.debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(i)}`),i.type==="error"?s.cancel($g(i)):s.resolve($g(i)),!0):!1}),g(this,"processBoltHandshake",i=>{var r,s;return i.type==="_bolt"||i.type==="handshake"?(this.respond((s=(r=i.payload._bolt)==null?void 0:r.id)!=null?s:ch(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=e,this.transportId=n,this.channel=t,this.queue=new Map}};let Za=Xa;dr=new WeakMap,g(Za,"createRequest",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:J(U({},t.payload),{_bolt:{id:ch(8),type:"REQUEST",version:kc}})}}),g(Za,"createResponse",(t,e)=>{var n;if((n=e.payload)!=null&&n._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:J(U({},e.payload),{_bolt:{id:t,type:"RESPONSE",version:kc}})}}),g(Za,"createNotification",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:J(U({},t.payload),{bolt:{id:ch(8),type:"NOTIFY",version:kc}})}}),g(Za,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:kc}}}));function UN(t){if(Promise.allSettled)return Promise.allSettled(t);const e=t.map(n=>n.then(i=>({status:"fulfilled",value:i})).catch(i=>({status:"rejected",reason:i})));return Promise.all(e)}const dh="transport closed";var eo;const lh=class extends Vo{constructor(t,{id:e,direction:n,handlerFactory:i,iceServers:r,iceTransportPolicy:s,proprietaryConstraints:a,additionalSettings:c,appData:d,config:l}){var h,m,y;super(),g(this,"awaitQueue"),g(this,"observer"),f(this,eo,void 0),g(this,"id"),g(this,"serverId"),g(this,"closed",!1),g(this,"direction"),g(this,"maxSctpMessageSize"),g(this,"handler"),g(this,"connectionState","new"),g(this,"producers"),g(this,"consumers"),g(this,"datachannels"),g(this,"connected",!1),g(this,"eventsDCReadyPromise"),g(this,"eventsDCReadyPromiseResolver"),g(this,"eventsDCFailureTimer"),g(this,"transportConnectionPromise"),g(this,"consumerTrackEvents"),g(this,"unknownTracksMap"),g(this,"appData"),p.debug(`constructor() [id: ${e}, direction: ${n}]`),v(this,eo,t),this.id=e,this.direction=n;const S=NN(c,{});delete S.iceServers,delete S.iceTransportPolicy,delete S.bundlePolicy,delete S.rtcpMuxPolicy,delete S.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new xd,this.observer=new Vo,this.handler=i(),this.handler.enableHighBitrate=(h=l==null?void 0:l.enableHighBitrate)!=null?h:!1,this.handler.enableStereo=(m=l==null?void 0:l.enableStereo)!=null?m:!1,this.handler.enableDtx=(y=l==null?void 0:l.enableDtx)!=null?y:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:n,iceServers:r,iceTransportPolicy:s,additionalSettings:c,proprietaryConstraints:a}),this.appData=d||{},this.transportConnectionPromise=new Promise(b=>{this.observer.once("connected",()=>{b(!0)}),this.observer.once("disconnect",()=>{b(!1)}),this.observer.once("close",()=>{b(!1)})}),this.eventsDCReadyPromise=new Promise(b=>{this.eventsDCReadyPromiseResolver=b}),this.handler.on("@connectionstatechange",b=>{b!==this.connectionState&&(p.debug(`connection state changed to ${b}`),this.connectionState=b,b==="connected"&&(this.connected=!0,this.observer.emit("connected")),b==="disconnected"&&(this.connected=!1,this.observer.emit("disconnect")),(b==="failed"||b==="closed")&&(this.connected=!1,this.observer.emit("close")),this.closed||this.safeEmit("connectionstatechange",b))}),this.handler.on("@icecandidate",({candidate:b})=>{this.closed||this.safeEmit("icecandidate",b)}),this.handler.on("dc_open",b=>{let D=this.datachannels.get(b.label);D||(D||(D=new Za(b,b.label,this.serverId),this.datachannels.set(b.label,D)),this.eventsDCFailureTimer=setTimeout(()=>{b.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",b.label))},5e3))}),this.handler.on("datachannel",(b,D)=>{b.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const C=this.datachannels.get(b.label);if(!C){p.error("unregistered datachannel for message",{rtcChannel:{label:b.label,message:D}});return}try{const V=JSON.parse(D);p.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:V.id,count:V.count,chunkIndex:V.chunkIndex,chunk:V.chunk,transprtId:this.serverId}});const L=C.processMessage(V);if(!L)return;p.debug(`datachannel message with id:${V.id} on transport:${this.serverId}complete - ${JSON.stringify(L)}`),this.emit(`datachannel:${b.label}`,C.label,L)}catch(V){p.error("error parsing message",{error:V})}})}setServerId(t){this.serverId=t}getDatachannel(t){return this.datachannels.get(t)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(p.debug("Transport close called"),this.connected=!1,this.closed=!0,this.handler.close(),Array.from(this.producers.values()).forEach(t=>{t.close(dh).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(t=>{t.close(dh)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"),this.observer.emit("close"))}getStats(){return u(this,null,function*(){if(this.closed)throw new Pt("closed");return this.handler.getTransportStats()})}connect(t){return u(this,null,function*(){try{if(yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:e,callback:n}=yield this.handler.connect(),{transportId:i,answer:r}=yield t(e);this.setServerId(i),yield n(r)})),!(yield this.transportConnectionPromise))throw new Error("ice connection failed");if(o(this,eo)===it.HIVE&&!(yield this.isEventsDCReady))throw new Error("events datachannel not open")}catch(e){throw p.error("transport failed to connect:",e),e}})}restartIce(){return u(this,null,function*(){if(p.debug("restartIce()"),this.closed)throw new Pt("closed");return this.handler.restartIce()})}canProduce(t){return u(this,null,function*(){const{track:e,appData:n}=t;if(e){if(this.direction!=="send")throw new xo("not a sending Transport");if(e.readyState==="ended")throw new Pt("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(n&&typeof n!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.transportConnectionPromise))throw new Ms("transport not connected");return!0})}produce(t,e){return u(this,null,function*(){if(!(yield this.canProduce(t)))throw new Error("Cannot produce");const{track:n,encodings:i,codecOptions:r,stopTracks:s=!0,disableTrackOnPause:a=!0,zeroRtpOnPause:c=!1,appData:d={}}=t;p.debug(`produce() [track:${n.id}]`);const{producerId:l,localId:h,rtpSender:m}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:y,callback:S,sender:b,mid:D}=yield this.handler.send({track:n,encodings:i,codecOptions:r,screenShare:d==null?void 0:d.screenShare}),{answer:C,producerId:V}=yield e({offer:y,kind:n.kind,paused:a?!n.enabled:!1,appData:J(U({},d||{}),{mid:D}),codecOptions:r,producingTransportId:this.serverId}),L=yield S(C);return{producerId:V,localId:L,rtpSender:b}}),"producer");return this.createProducerObject({id:l,localId:h,track:n,stopTracks:s,disableTrackOnPause:a,zeroRtpOnPause:c,appData:d,handler:this.handler,rtpSender:m})})}createProducerObject(t){return u(this,null,function*(){const e=new xN(t);return this.producers.set(e.id,e),e.once("close",()=>{this.producers.delete(e.id)}),e})}closeProducer(t){return u(this,null,function*(){yield this.awaitQueue.push(t.close.bind(t),"producer")})}canConsume(){return u(this,null,function*(){if(this.closed)throw new Pt("closed");if(this.direction!=="recv")throw new xo("not a receiving transport");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!(yield this.transportConnectionPromise))throw new Ms("transport not connected");return!0})}consume(t,e,n){return u(this,null,function*(){return this.awaitQueue.push(()=>u(this,null,function*(){const i={},{consumerStates:r,sessionDescription:s,failedProducers:a}=yield e(t);r.forEach((l,h)=>{i[h]=this.createConsumerObjectAndWaitForTrack(J(U({},l),{producerId:h}))});const c=a;s&&(yield n(s));const d=[];return yield Promise.all(Object.entries(i).map(([l,h])=>h.then(m=>d.push(m)).catch(()=>{p.error(`Failed consumer creation task, producer: ${l}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:d,failedProducers:c}}),"consumer")})}static parseHeaderExtensionMappings(t,e=[]){const n=po(t.sdp),i={},r=e.map(s=>s.transceiver.mid);return n.media.forEach(s=>{r.includes(s.mid.toString())&&(i[s.mid]=s.ext)}),i}static setHeaderExtensionMappings(t,e,n){const i=po(t.sdp),r=e.map(s=>s.transceiver.mid);return i.media=i.media.map(s=>{if(r.includes(s.mid.toString())){const a=U({},s);return a.ext=n[s.mid],a}return s}),J(U({},t),{sdp:_u(i)})}closeConsumers(t,e){return u(this,null,function*(){const n=lh.parseHeaderExtensionMappings(this.handler.pc.remoteDescription,t);t.forEach(s=>s.close(void 0,!0));let i=yield this.handler.pc.createOffer();i=lh.setHeaderExtensionMappings(i,t,n),yield this.setLocalDescription(i);const r=yield e(t,i);yield this.setRemoteDescription(r)})}setRemoteOffer(t){return u(this,null,function*(){yield this.setRemoteDescription(t);const e=yield this.handler.pc.createAnswer(),n=po(e.sdp);return n.media=n.media.map(i=>{if(i.type==="audio"){const r=U({},i),s=r.fmtp.find(a=>a.payload===111);return s&&(s.config+=";stereo=1;sprop-stereo=1"),r.rtcpFb||(r.rtcpFb=[]),r.rtcpFb.some(a=>a.type==="nack")||r.rtcpFb.push({payload:parseInt(r.payloads,10),type:"nack"}),r}return i}),e.sdp=_u(n),yield this.setLocalDescription(e),e})}_ontrack(t){const{track:e,transceiver:n,streams:i}=t;p.info(`track event received [trackId: ${e.id}]`);let r;o(this,eo)===it.HIVE?r=`${i[0].id}:${e.kind}`:r=`${n.mid}:${e.kind}`,e.addEventListener("ended",()=>{p.info(`rtc consumer track ended [trackId: ${e.id}]`),this.unknownTracksMap.delete(r)});const s=this.consumerTrackEvents.get(r);s?(s(e,n),this.consumerTrackEvents.delete(r)):(p.warn(`track event handler not found ${r}`),this.unknownTracksMap.set(r,t))}sendErrorOverDC(t,e,n){const i=this.getDatachannel(t);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});i.respond(e,n,!0)}sendResponseOverDC(t,e,n){const i=this.getDatachannel(t);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});i.respond(e,n)}createConsumerObjectAndWaitForTrack(t){return u(this,null,function*(){const{consumerId:e,producerId:n,producingPeerId:i,producingTransportId:r,streamId:s,paused:a,screenShare:c,appData:d,kind:l,mimeType:h}=t,m=`${s}:${l}`,y=J(U({},t),{name:"consumer creation task error",message:"consumer creation failed"});return new Promise((S,b)=>u(this,null,function*(){const D=setTimeout(()=>{this.consumerTrackEvents.delete(m),y.isTimedout=!0,b(y)},5e3),C=(L,q)=>{try{if(L.readyState==="ended")clearTimeout(D),b(y);else{const w=L;w.enabled=!0,this.handler.midTransceiverMap.set(q.mid,q);const X=new LN({id:e,localId:q.mid,transceiver:q,track:w,paused:a,producerId:n,producingPeerId:i,producingTransportId:r,handler:this.handler,appData:J(U({},d),{screenShare:c,peerId:i}),rtpReceiver:q.receiver,mimeType:h});this.consumers.set(e,X),X.once("close",()=>{this.consumers.delete(X.id),this.handler.midTransceiverMap.delete(q.mid)}),p.info("consumer created for ",{consumer:{id:e,kind:l,appData:{screenShare:c},peerId:i,producerId:n}}),this.observer.emit("newconsumer",X),clearTimeout(D),S(X)}}catch(w){p.warn("error while creating consumer:",w),clearTimeout(D),b(y)}},V=this.unknownTracksMap.get(m);V?(this.unknownTracksMap.delete(m),C(V.track,V.transceiver)):this.consumerTrackEvents.set(m,C)}))})}setRemoteDescription(t){return u(this,null,function*(){yield this.handler.pc.setRemoteDescription(t)})}setLocalDescription(t){return u(this,null,function*(){p.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(t)}]`),yield this.handler.pc.setLocalDescription(t)})}retryFailedConsumerCreationTasks(t){return u(this,null,function*(){return UN(t.map(e=>u(this,null,function*(){return Ep(n=>u(this,null,function*(){return n>0&&p.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.createConsumerObjectAndWaitForTrack(U({},e))}))})))})}sendDataChannelMessage(t,e){return u(this,null,function*(){const n=this.getDatachannel(t);if(!n)throw PN("DC_NOT_READY",`${t} datachannel not ready`);const i=(yield n.request(e)).payload;return p.info(`sendDataChannelMessage::response ${JSON.stringify(i)}`),i})}};let FN=lh;eo=new WeakMap;function BN(){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){p.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return p.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=lf.getParser(t),n=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(n.name&&n.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(n.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;p.warn("Device::this._detectDevice() | browser not supported");return}p.warn("Device::this._detectDevice() | unknown device")}var $c;class WN{constructor(e,{handlerName:n,handlerFactory:i}={}){if(g(this,"handlerFactory"),f(this,$c,void 0),p.debug("constructor()"),v(this,$c,e),n&&i)throw new TypeError("just one of handlerName or handlerInterface can be given");if(i)this.handlerFactory=i;else{if(n)p.debug(`Device::constructor() | handler given: ${n}`);else if(n=BN(),n)p.debug(`Device::constructor() | detected handler: ${n}`);else throw new Error("device not supported");switch(n){case"Chrome74":this.handlerFactory=kp.createFactory();break;case"Safari12":this.handlerFactory=bp.createFactory();break;case"Firefox60":this.handlerFactory=Vd.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Vd.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${n}"`)}}}createTransport(e){const n=Fs();return new FN(o(this,$c),J(U({id:n},e),{handlerFactory:this.handlerFactory}))}}$c=new WeakMap;const jN=2e3;var Ai,yo,xt,Vt,As,So,to,no,us,_r,io,Eo,Kc,zc,uh,hh,Vy,ph,Uy,mh,Fy,gh,By,fh,Kg,Yc,uu,Qc,hu;class HN extends mt.EventEmitter{constructor(e,n,i){switch(super(),f(this,Eo),f(this,zc),f(this,hh),f(this,ph),f(this,mh),f(this,gh),f(this,fh),f(this,Yc),f(this,Qc),f(this,Ai,void 0),f(this,yo,void 0),f(this,xt,void 0),f(this,Vt,void 0),f(this,As,void 0),f(this,So,void 0),f(this,to,void 0),f(this,no,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0}),f(this,us,void 0),f(this,_r,"all"),f(this,io,void 0),v(this,Ai,e),v(this,As,n),v(this,io,i),v(this,yo,new WN(i)),v(this,So,new ON(n,i)),i){case it.CF:{v(this,to,En);break}case it.HIVE:default:{v(this,to,sn);break}}o(this,Eo,Kc).mediaState={send:{state:Wi.NEW,reconnected:!1},recv:{state:Wi.NEW,reconnected:!1}},Z.hasFeature(re.FORCE_RELAY)&&v(this,_r,"relay"),H(this,zc,uh).call(this)}get socket(){return o(this,As)}get socketHandler(){return o(this,So)}get sendTransport(){return o(this,xt)}get recvTransport(){return o(this,Vt)}get events(){return o(this,to)}get nodeType(){return o(this,io)}createTransports(e){return u(this,null,function*(){var n,i,r,s,a,c,d,l;Z.hasFeature(re.FORCE_RELAY)&&(p.info("ICE Transport Policy set to relay"),v(this,_r,"relay"));const h=yield dt().getICEServers().catch(y=>(p.warn(`failed to get iceservers from server: ${y.message}`),[])),m=[];if(e.send){const y=Z.hasFeature(re.DISABLE_OPUS_DTX_CF),S=H(this,ph,Uy).call(this,{iceServers:h,additionalSettings:{encodedInsertableStreams:(n=o(this,Ai).getValue("modules").e2ee)==null?void 0:n.enabled},config:{enableHighBitrate:(s=(r=(i=o(this,Ai).getValue("defaults").mediaConfiguration)==null?void 0:i.audio)==null?void 0:r.enableHighBitrate)!=null?s:!1,enableStereo:(d=(c=(a=o(this,Ai).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:c.enableStereo)!=null?d:!1,enableDtx:o(this,io)===it.HIVE?!0:!!y},iceTransportPolicy:o(this,_r)});m.push(S)}if(e.recv){const y=H(this,mh,Fy).call(this,{iceServers:h,additionalSettings:{encodedInsertableStreams:(l=o(this,Ai).getValue("modules").e2ee)==null?void 0:l.enabled},iceTransportPolicy:o(this,_r)});m.push(y)}yield Promise.all(m)})}stopTransports(e){var n,i,r,s;e.send&&((n=o(this,xt))==null||n.close(),(i=o(this,xt))==null||i.removeAllListeners(),v(this,xt,void 0)),e.recv&&((r=o(this,Vt))==null||r.close(),(s=o(this,Vt))==null||s.removeAllListeners(),v(this,Vt,void 0)),H(this,zc,uh).call(this)}stopAllTransports(){p.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}connectTransportWithRetry(e){return u(this,null,function*(){const{id:n,serverId:i,direction:r}=e;H(this,gh,By).call(this,e);try{const s=Z.hasFeature(re.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3;return yield Ep((a,c)=>u(this,null,function*(){a>0&&p.debug(`Retrying transport connect, count: ${a}`,{transport:{id:n,serverId:i,type:r}});try{yield H(this,hh,Vy).call(this,e)}catch(d){if(d instanceof Ms){c(d);return}throw d}}),{delayTime:100,strategy:"exponential",maxRetryCount:s}),e}catch(s){throw p.error(`Failed to connect send transport after retry: ${e.id}`,{error:s,transport:{id:n,serverId:i,type:r}}),e.close(),e.removeAllListeners(),this.handleErrors("rejoin"),s}})}handleErrors(e){throw new Error("Method not implemented.")}}Ai=new WeakMap,yo=new WeakMap,xt=new WeakMap,Vt=new WeakMap,As=new WeakMap,So=new WeakMap,to=new WeakMap,no=new WeakMap,us=new WeakMap,_r=new WeakMap,io=new WeakMap,Eo=new WeakSet,Kc=function(){return o(this,Ai).getValue("connectionHandler")},zc=new WeakSet,uh=function(){v(this,us,{send:void 0,recv:void 0})},hh=new WeakSet,Vy=function(t){return u(this,null,function*(){const{id:e,serverId:n,direction:i}=t;if(p.info(`Connecting ${i} transport`,{transport:{id:e,serverId:n,type:i}}),!o(this,As).isConnected)throw new Ms("Socket is not connected");if(t.connectionState==="closed")throw new Ms("Transport is closed");try{yield t.connect(r=>H(this,fh,Kg).call(this,i,r)),p.info(`Connected ${i} transport`,{transport:{id:e,serverId:n,type:i}})}catch(r){throw o(this,no).transportFailureCount[i]+=1,r.message==="ice connection failed"?new Ms(r.message):r}})},ph=new WeakSet,Uy=function(t){return u(this,null,function*(){var e,n;if(o(this,xt)&&o(this,xt).connected){p.info("Transport send is already connected",{transport:{id:(e=o(this,xt))==null?void 0:e.id,serverId:(n=o(this,xt))==null?void 0:n.serverId,type:"send"}});return}v(this,xt,yield o(this,yo).createTransport(J(U({},t),{direction:"send"}))),K.configureSendTransport(o(this,xt))})},mh=new WeakSet,Fy=function(t){return u(this,null,function*(){var e,n;if(o(this,Vt)&&o(this,Vt).connected){p.info("Transport recv is already connected",{transport:{id:(e=o(this,Vt))==null?void 0:e.id,serverId:(n=o(this,Vt))==null?void 0:n.serverId,type:"recv"}});return}v(this,Vt,yield o(this,yo).createTransport(J(U({},t),{direction:"recv"}))),K.configureRecvTransport(o(this,Vt))})},gh=new WeakSet,By=function(t){const{direction:e,id:n}=t;t.on("connectionstatechange",i=>u(this,null,function*(){H(this,Qc,hu).call(this,{state:i,direction:e}),p.info(`Transport connection state changed for ${e} transport`,{transport:{id:n,serverId:t.serverId,type:e,status:i}});const r=()=>{const s=o(this,us)[e];s!==void 0&&(clearTimeout(s),o(this,us)[e]=void 0)};switch(i){case"connected":r(),o(this,no).lastConnectionTime=performance.now();break;case"disconnected":o(this,us)[e]=setTimeout(()=>u(this,null,function*(){yield H(this,Yc,uu).call(this,t)}),jN);break;case"failed":if(t.closed)return;r(),yield H(this,Yc,uu).call(this,t);break}})),t.on("icecandidate",i=>u(this,null,function*(){p.debug("Sending iceCandidate:",{iceCandidate:i})})),t.on("datachannel:events",(i,r)=>u(this,null,function*(){var s,a;p.debug("Got data channel message on event:",{rtcChannel:{label:i,message:r}});try{switch(r.type){case"handshake":{const c={type:"handshake",payload:{message:"pong"}};t.sendResponseOverDC(i,xy(r),c);break}case"hub-disconnect":{p.debug(`media hub disconnected, full_reconnect: ${(s=r.payload)==null?void 0:s.full_reconnect}`),((a=r.payload)==null?void 0:a.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch{p.error(`Unable to handle the incoming datachannel message on channel ${i}`)}})),t.on("dc_error",()=>{t.direction==="recv"&&(p.warn("Events datachannel did not open in 5s",{country:E.location.country}),this.handleErrors("reconnectRecvTransport"))})},fh=new WeakSet,Kg=function(t,e){return u(this,null,function*(){const n=t==="recv";try{const{sdp:i,type:r}=e,s={consuming:n,description:{sdp:i,type:r,target:n?ai.SUBSCRIBER:ai.PUBLISHER},producers:[]};return o(this,So).connectTransport(s)}catch(i){throw p.error(`Error in ${t} transport connection:`,{error:i,country:E.location.country}),i}})},Yc=new WeakSet,uu=function(t){return u(this,null,function*(){t.close(),t.removeAllListeners();const{direction:e}=t;switch(Z.hasFeature(re.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED)&&o(this,As).isConnected&&o(this,no).transportFailureCount[e]>2&&(p.warn(`Multiple disconnections in ${e} transport, forcing relay`),v(this,_r,"relay")),yield this.createTransports({[e]:!0}),e){case"send":{yield this.connectTransportWithRetry(o(this,xt)),p.info("Transport reconnected",{transport:o(this,xt)}),R.emit(M.RESET_PRODUCER_STATE);break}case"recv":{yield this.connectTransportWithRetry(o(this,Vt)),p.info("Transport reconnected",{transport:o(this,Vt)}),R.emit(M.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:p.warn("Unknown transport direction",{transport:t})}H(this,Qc,hu).call(this,{state:Wi.CONNECTED,direction:e})})},Qc=new WeakSet,hu=function(t){const{state:e,direction:n}=t;o(this,Eo,Kc).mediaState[n]={state:e,reconnected:!0},R.emit(M.TRANSPORT_STATE_UPDATE,U({transport:n},o(this,Eo,Kc).mediaState[n]))};var vh,Wy;class qN{constructor(e){f(this,vh),this.recvTransport=e,H(this,vh,Wy).call(this)}create(e){return u(this,null,function*(){if(!e||e&&e.length===0)throw new Error("List of producers is required");const n={type:"create_consumer",payload:{producers:e.map(({producerId:a,producingTransportId:c,kind:d,mimeType:l})=>({producerId:a,producingTransportId:c,preferredCodec:U(U({},d==="video"&&l?{video:l}:{}),d==="audio"&&l?{audio:l}:{})}))}},i=yield this.recvTransport.sendDataChannelMessage("events",n),r=new Map;e.forEach(a=>r.set(a.producerId,a));const s=new Map;return Object.entries(i).forEach(([a,c])=>{const d=r.get(c.producerId);d&&s.set(c.producerId,{consumerId:a,producingTransportId:d.producingTransportId,producingPeerId:d.producingPeerId,kind:d.kind,paused:d.pause,streamId:c.streamId,trackId:c.trackId,screenShare:d.screenShare,mimeType:d.mimeType,appData:{}})}),{consumerStates:s}})}negotiate(e,n,i){return u(this,null,function*(){try{p.debug(`Received offer over dc: ${e.sdp} for transport`);const r=yield this.recvTransport.setRemoteOffer(e),s={type:"answer",payload:{type:r.type,sdp:r.sdp}};return p.debug(`datachannel answer: ${JSON.stringify(s)}`),this.recvTransport.sendResponseOverDC(i,n,s),r}catch(r){throw p.error("datachannel:events::Error:",r),r.code!=="DC_NOT_FOUND"&&this.recvTransport.sendErrorOverDC(i,n,r),r}})}close(e){return u(this,null,function*(){if(!e.length)return{};const n=e.map(a=>a.id);p.info(`Closing consumers: ${JSON.stringify(n)}`);const i={type:"close_consumers",payload:{consumers:n}},r=yield this.recvTransport.sendDataChannelMessage("events",i),{failedConsumers:s}=r;return{failedConsumers:s}})}}vh=new WeakSet,Wy=function(){this.recvTransport.on("datachannel:events",(t,e)=>u(this,null,function*(){try{switch(e.type){case"negotiation":{const{sdp:n}=e.payload,i={sdp:n,type:"offer"};this.negotiate(i,xy(e),t);break}default:break}}catch{p.error(`Unable to handle the incoming datachannel message on channel ${t}`)}}))};class GN{constructor(e,n,i,r){this.events=e,this.recvTransport=n,this.socket=i,this.socketHandler=r}create(e){return u(this,null,function*(){if(!e||e&&e.length===0)throw new Error("List of producers is required");const n=new Map,i=[];e.forEach(d=>{const{producingPeerId:l,producerId:h,producingTransportId:m}=d;n.set(h,l),i.push({producingPeerId:l,producerId:h,producingTransportId:m})});const r=yield this.socketHandler.consume({requests:i,consumingTransportId:this.recvTransport.serverId}),s=new Map;e.forEach(d=>s.set(d.producerId,d));const a=new Map,c=[];return Object.entries(r.consumerStateMap).forEach(([d,l])=>{const h=s.get(d);if(!h)return;if(l.errorCode){p.warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push(h);return}let m={};try{m=JSON.parse(l.producerState.appData)}catch{}a.set(d,{consumerId:l.consumerId,producingTransportId:h.producingTransportId,producingPeerId:h.producingPeerId,kind:h.kind,paused:h.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:h.screenShare,mimeType:h.mimeType,appData:m})}),{consumerStates:a,sessionDescription:r.sessionDescription,failedProducers:c}})}negotiate(e){return u(this,null,function*(){p.debug(`setting remote offer: ${JSON.stringify(e)} on recvTransport`,{transport:this.recvTransport});const n=yield this.recvTransport.setRemoteOffer(e),i={transportId:this.recvTransport.serverId,description:{sdp:n.sdp,type:n.type,target:ai.SUBSCRIBER}};return p.debug(`sending renegotiate request: ${JSON.stringify(i)} on recvTransport`,{transport:this.recvTransport}),yield this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,vC.toBinary(i)),p.info("renegotiation done",{transport:this.recvTransport}),n})}close(e){return u(this,null,function*(){if(!e.length)return{};const n=(i,r)=>u(this,null,function*(){const s=i.map(l=>l.localId);p.info(`Closing consumers: ${JSON.stringify(s)}`);const a={description:{sdp:r.sdp,type:r.type,target:ai.SUBSCRIBER},consumerIds:s,consumingTransportId:this.recvTransport.serverId},c=yield this.socketHandler.closeConsumer(a),d=BP.fromBinary(c).description;return{sdp:d.sdp,type:d.type}});return this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(e,n),"close_consumer"),{}})}}class _p{constructor(e){this.socketHandler=e}static getMSIDFromSDP(e,n){return po(e).media.filter(i=>n==="video"?i.type==="video":i.type==="audio").at(-1).msid}create(e){return u(this,arguments,function*({offer:n,kind:i,paused:r,appData:s,codecOptions:a,producingTransportId:c}){var d,l;const h=_p.getMSIDFromSDP(n.sdp,i),m={description:{sdp:n.sdp,type:n.type,target:ai.PUBLISHER},paused:r,kind:i,msid:h,appData:JSON.stringify(s),screenShare:(d=s.screenShare)!=null?d:!1,mimeType:`${i}/${(l=a[0])==null?void 0:l.name}`,producingTransportId:c},{answer:y,producerId:S}=yield this.socketHandler.produce(m);return{answer:y,producerId:S}})}}const JN=3;var To,ws,Cr,ko,Xc,Xn,Ud,Ni,bo,yh,jy,Fd,Sh,Eh,Hy,Th,qy,kh,Gy,bh,Jy,Zc,pu,_h,zg;class $N extends HN{constructor(e,n,i){super(e,n,i),f(this,yh),f(this,Fd),f(this,Eh),f(this,Th),f(this,kh),f(this,bh),f(this,Zc),f(this,_h),f(this,To,void 0),f(this,ws,void 0),f(this,Cr,void 0),f(this,ko,void 0),f(this,Xc,void 0),f(this,Xn,void 0),f(this,Ud,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0}),f(this,Ni,[]),f(this,bo,void 0),v(this,To,e),o(this,yh,jy).mediaState={send:{state:Wi.NEW,reconnected:!1},recv:{state:Wi.NEW,reconnected:!1}},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return o(this,ws)}get consumers(){return o(this,Cr)}get producerIdToConsumerIdMap(){return o(this,ko)}reset(){v(this,ws,new Map),v(this,Cr,new Map),v(this,ko,new Map)}setupTransports(e){return u(this,null,function*(){yield this.createTransports(e);let n,i;e.send&&(n=H(this,Eh,Hy).call(this)),e.recv&&(i=H(this,Th,qy).call(this)),yield Promise.all([n,i])})}createProducer(e,n){return u(this,null,function*(){var i;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const r=yield this.sendTransport.produce(e,H(this,kh,Gy).bind(this));return(i=e.appData)!=null&&i.e2ee&&R.emit(M.E2EE_ACTIVE_PRODUCER,r),H(this,bh,Jy).call(this,r,n),r}catch(r){throw p.error("Failed to create producer",{error:r}),o(this,Ud).producerCreationFailureCount+=1,r}})}closeProducer(e,n){return u(this,null,function*(){var i;const r=this.producers.get(e);if(!r){p.warn(`Producer with ID ${e} was not found`);return}n!=null&&n.stopTrack&&r.track.stop();try{yield this.sendTransport.closeProducer(r),(i=o(this,To).getValue("modules").e2ee)!=null&&i.enabled&&R.emit(M.E2EE_INACTIVE_PRODUCER,r)}catch(s){p.error("Failed to close producer on server",{error:s,producer:r})}})}closeAllProducers(){return Promise.all(Array.from(o(this,ws).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}createConsumers(e){return u(this,null,function*(){o(this,bo)||clearTimeout(o(this,bo)),v(this,Ni,o(this,Ni).concat(e)),yield H(this,Fd,Sh).call(this)})}closeConsumer(e){return this.closeConsumers([e])}closeConsumers(e){return u(this,null,function*(){if(!o(this,Xn))return;const n=e.map(r=>this.consumers.get(r)).filter(r=>r!==void 0);if(n.length===0)return;const{failedConsumers:i}=yield o(this,Xn).close(n);i!=null&&i.length&&p.warn("Failed to close some consumers",{consumerIds:i})})}closeAllConsumers(){return this.closeConsumers(Array.from(o(this,Cr).keys()))}switchConsumersToLayer(e,n){return u(this,null,function*(){const i=this.recvTransport.getDatachannel("events");if(!i){p.warn("events datachannel not found");return}const r={type:"switch_consumer_layer",payload:{consumerIds:e,layer:n}};yield i.request(r),p.info(`Consumers switched layers to ${n}`,{consumerIds:e})})}}To=new WeakMap,ws=new WeakMap,Cr=new WeakMap,ko=new WeakMap,Xc=new WeakMap,Xn=new WeakMap,Ud=new WeakMap,Ni=new WeakMap,bo=new WeakMap,yh=new WeakSet,jy=function(){return o(this,To).getValue("connectionHandler")},Fd=new WeakSet,Sh=function(){return u(this,null,function*(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const t=500,e=o(this,Ni).splice(0,o(this,Ni).length);try{const n=e.filter(({producerId:s})=>!this.producers.get(s)),{consumers:i,failedProducers:r}=yield this.recvTransport.consume(n,H(this,Zc,pu).bind(this),o(this,Xn).negotiate.bind(o(this,Xn)));i.forEach(H(this,_h,zg).bind(this)),r!=null&&r.length&&(p.error("Failed to create consumers for producers",{producers:r}),v(this,Ni,o(this,Ni).concat(r)),v(this,bo,setTimeout(H(this,Fd,Sh).bind(this),t)))}catch{}})},Eh=new WeakSet,Hy=function(){return u(this,null,function*(){yield this.connectTransportWithRetry(this.sendTransport),v(this,Xc,new _p(this.socketHandler))})},Th=new WeakSet,qy=function(){return u(this,null,function*(){switch(this.recvTransport.on("connect",()=>{o(this,ko).clear()}),yield this.connectTransportWithRetry(this.recvTransport),this.nodeType){case it.CF:{v(this,Xn,new GN(this.events,this.recvTransport,this.socket,this.socketHandler));break}case it.HIVE:default:v(this,Xn,new qN(this.recvTransport))}})},kh=new WeakSet,Gy=function(t){return o(this,Xc).create(t)},bh=new WeakSet,Jy=function(t,e){t.on("close",(n,i)=>u(this,[n,i],function*({offer:r,reason:s},a){p.info("producer::closing",{debuggingHint:s,producer:J(U({},t),{status:"closing"})});const c={producerId:t.id,description:{sdp:r.sdp,type:r.type,target:ai.PUBLISHER}};try{const d=yield this.socketHandler.closeProducer(c),l={sdp:d==null?void 0:d.sdp,type:d==null?void 0:d.type};p.info("producer::closed",{producer:J(U({},t),{status:"closed"})}),a({answer:l})}catch(d){p.error("producer close error",d)}this.producers.delete(t.id),e()})),t.on("trackended",()=>{p.info("producer::trackended",{producer:J(U({},t),{status:"UNKNOWN"})})}),o(this,ws).set(t.id,t)},Zc=new WeakSet,pu=function(t,e=0){return u(this,null,function*(){try{return yield this.recvTransport.canConsume(),yield o(this,Xn).create(t)}catch(n){if(n instanceof RN&&(o(this,Ud).consumerCreationFailureCount+=1),e<=JN)return p.error(`Error in consume request attempt:${e}`,{error:n}),H(this,Zc,pu).call(this,t,e+1);throw p.error("Error in consume request",{error:n}),n}})},_h=new WeakSet,zg=function(t){t.on("close",e=>u(this,null,function*(){p.debug("consumer closed",{consumer:{closureReason:e,id:t.id,kind:t.kind,appData:t.appData}}),o(this,Cr).delete(t.id),R.emit(M.CONSUMER_CLOSED,{id:t.id})})),o(this,Cr).set(t.id,t),this.producerIdToConsumerIdMap.set(t.producerId,t.id),R.emit(M.NEW_CONSUMER,{id:t.id,appData:t.appData,peerId:t.peerId})};var ed,td,nd,ro,_o,wo,Bd,Wd,Is,$t,xn,Dn,lr,ur,Di,jd,wh,$y,Ih,Ky,Ch,zy,Ph,Yy;const Rh=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:n=3,hangoverFrames:i=5,noiseAdaptationRate:r=.95,voiceAdaptationRate:s=.99,minEnergyThreshold:a=.005,maxEnergyThreshold:c=.2,energyRatioThreshold:d=1.5,noiseHistorySize:l=50}={}){f(this,wh),f(this,Ih),f(this,ed,void 0),f(this,td,void 0),f(this,nd,void 0),f(this,ro,void 0),f(this,_o,void 0),f(this,wo,void 0),f(this,Bd,void 0),f(this,Wd,void 0),f(this,Is,void 0),f(this,$t,void 0),f(this,xn,void 0),f(this,Dn,!1),f(this,lr,0),f(this,ur,0),f(this,Di,[]),f(this,jd,void 0),v(this,ro,t),v(this,$t,t),v(this,ed,e),v(this,td,n),v(this,nd,i),v(this,_o,r),v(this,wo,s),v(this,Bd,a),v(this,Wd,c),v(this,Is,d),v(this,jd,l),v(this,xn,t/2)}get voiceDetected(){return o(this,Dn)}processAudioChunk(t){var e,n;const i=H(e=Rh,Ch,zy).call(e,t),r=H(n=Rh,Ph,Yy).call(n,t);return H(this,wh,$y).call(this,i),i/o(this,xn)>o(this,Is)&&i>o(this,$t)&&r>o(this,ed)?(v(this,lr,o(this,lr)+1),v(this,ur,o(this,nd)),o(this,lr)>=o(this,td)&&v(this,Dn,!0)):(v(this,lr,0),o(this,ur)>0?v(this,ur,o(this,ur)-1):o(this,Dn)&&v(this,Dn,!1),o(this,Dn)||H(this,Ih,Ky).call(this,i)),o(this,Dn)}reset(){v(this,Dn,!1),v(this,lr,0),v(this,ur,0),v(this,$t,o(this,ro)),v(this,xn,o(this,ro)/2),v(this,Di,[])}getThresholdInfo(){return{currentEnergyThreshold:o(this,$t),backgroundNoiseEnergy:o(this,xn),energyRatioThreshold:o(this,Is)}}};let Mh=Rh;ed=new WeakMap,td=new WeakMap,nd=new WeakMap,ro=new WeakMap,_o=new WeakMap,wo=new WeakMap,Bd=new WeakMap,Wd=new WeakMap,Is=new WeakMap,$t=new WeakMap,xn=new WeakMap,Dn=new WeakMap,lr=new WeakMap,ur=new WeakMap,Di=new WeakMap,jd=new WeakMap,wh=new WeakSet,$y=function(t){o(this,Dn)?v(this,$t,o(this,wo)*o(this,$t)+(1-o(this,wo))*t):v(this,$t,o(this,_o)*o(this,$t)+(1-o(this,_o))*(o(this,xn)*o(this,Is))),v(this,$t,Math.max(o(this,Bd),Math.min(o(this,Wd),o(this,$t))))},Ih=new WeakSet,Ky=function(t){if(t<o(this,$t)*1.2)if(o(this,Di).push(t),o(this,Di).length>o(this,jd)&&o(this,Di).shift(),o(this,Di).length>=10){const e=[...o(this,Di)].sort((i,r)=>i-r),n=Math.floor(e.length/2);v(this,xn,e[n])}else v(this,xn,.95*o(this,xn)+.05*t)},Ch=new WeakSet,zy=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,n)=>e+n)/t.length)},Ph=new WeakSet,Yy=function(t){let e=0;for(let n=1;n<t.length;n+=1)(t[n]>=0&&t[n-1]<0||t[n]<0&&t[n-1]>=0)&&(e+=1);return e},f(Mh,Ch),f(Mh,Ph);const KN=60,zN=400;var hr,pr,Ds,so,Pr,ao,Io,Hd,mr,hs,Co,Ah,Qy,id,Dh,Oh,Xy,mu,Yg,gu,Qg;const Po=class{constructor(t){f(this,Ah),f(this,Oh),f(this,hr,void 0),f(this,pr,void 0),f(this,Ds,void 0),f(this,so,void 0),f(this,Pr,void 0),f(this,ao,void 0),f(this,Io,void 0),f(this,Hd,void 0),f(this,mr,void 0),f(this,hs,void 0),f(this,Co,void 0),this.reportRequest=t,v(this,so,new AudioContext),v(this,Pr,o(this,so).createAnalyser()),o(this,Pr).fftSize=2048,v(this,Hd,new Mh)}set producerId(t){v(this,Ds,t)}set audioTrack(t){v(this,ao,t);const e=new MediaStream;e.addTrack(o(this,ao)),o(this,so).createMediaStreamSource(e).connect(o(this,Pr))}start(){o(this,hr)&&ks(o(this,hr)),v(this,hr,yd(()=>u(this,null,function*(){var t;if(!o(this,ao)||!o(this,Ds))return;const{energy:e}=H(this,Ah,Qy).call(this),n=H(t=Po,id,Dh).call(t,e);let i=.9;o(this,Co)!==n&&o(this,Co)?i=.9:n?i=.3:i=.5,v(this,Io,(o(this,Io)||0)*(1-i)+e*i)}),KN)),o(this,pr)&&ks(o(this,pr)),v(this,pr,yd(H(this,Oh,Xy).bind(this),zN))}stop(){o(this,hr)&&ks(o(this,hr)),o(this,pr)&&ks(o(this,pr))}};let rd=Po;hr=new WeakMap,pr=new WeakMap,Ds=new WeakMap,so=new WeakMap,Pr=new WeakMap,ao=new WeakMap,Io=new WeakMap,Hd=new WeakMap,mr=new WeakMap,hs=new WeakMap,Co=new WeakMap,Ah=new WeakSet,Qy=function(){var t,e;const n=new Float32Array(o(this,Pr).frequencyBinCount);o(this,Pr).getFloatTimeDomainData(n);const i=o(this,Hd).processAudioChunk(n),r=H(t=Po,mu,Yg).call(t,n),s=H(e=Po,gu,Qg).call(e,r);return(!o(this,mr)||s<o(this,mr))&&v(this,mr,s),(!o(this,hs)||s>o(this,hs))&&v(this,hs,s),{energy:(s-o(this,mr))/(o(this,hs)-o(this,mr))*10||0,isVoice:i}},id=new WeakSet,Dh=function(t){return t<5},Oh=new WeakSet,Xy=function(t=o(this,Io)){var e;if(!o(this,Ds)||!t)return;const n={producerId:o(this,Ds),energy:Math.round(t),silent:H(e=Po,id,Dh).call(e,t)};v(this,Co,n.silent),this.reportRequest(n)},mu=new WeakSet,Yg=function(t){return Math.sqrt(t.reduce((e,n)=>e+n*n,0)/t.length)},gu=new WeakSet,Qg=function(t){const e=Math.log10(t);return Math.round(e)},f(rd,id),f(rd,mu),f(rd,gu);const YN=()=>{const t=new window.AudioContext,e=t.createOscillator();e.type="triangle",e.frequency.setValueAtTime(20,t.currentTime);const n=t.createGain();n.gain.setValueAtTime(0,t.currentTime),e.connect(n);const i=t.createMediaStreamDestination();return n.connect(i),e.start(),i.stream.getAudioTracks()[0]},QN=()=>{var t,e;const n=new MediaStream().getVideoTracks()[0],i=document.createElement("canvas");i.height=(t=n==null?void 0:n.getSettings().height)!=null?t:720,i.width=(e=n==null?void 0:n.getSettings().width)!=null?e:1280;const r=i.getContext("2d");return r.fillStyle="black",r.fillRect(0,0,i.width,i.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,i.width,i.height)},1e3),i.captureStream().getVideoTracks()[0]};var XN=Object.defineProperty,ZN=Object.getOwnPropertyDescriptor,he=(t,e,n,i)=>{for(var r=i>1?void 0:i?ZN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&XN(e,n,r),r};const Pn=["video/VP9","video/VP8"];var sd,ad,bt,$,oo,gr,Lt,ps,ms,fr,od,Ii,co,gs,fs,Jt,nn,vr,vs,ht,_t,ys,lo,Nh,Zy,Lh,eS;class ue{constructor(e,n,i){f(this,vr),f(this,ht),f(this,ys),f(this,Nh),f(this,Lh),g(this,"context"),g(this,"authToken"),g(this,"e2ee"),f(this,sd,void 0),f(this,ad,void 0),f(this,bt,void 0),f(this,$,void 0),f(this,oo,void 0),f(this,gr,void 0),f(this,Lt,void 0),f(this,ps,void 0),f(this,ms,void 0),f(this,fr,void 0),f(this,od,void 0),f(this,Ii,void 0),g(this,"maxPreferredStreams"),f(this,co,void 0),f(this,gs,void 0),f(this,fs,void 0),f(this,Jt,void 0),f(this,nn,void 0),g(this,"partialJoinRoomPromise");var r,s;this.context=e;const{socket:a}=i;this.mediaJoined=!1,v(this,gs,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,fs,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,gr,n),v(this,bt,a),v(this,ps,!1),v(this,$,new $N(e,a,n)),v(this,Lt,o(this,$).events),this.maxPreferredStreams=6,v(this,Ii,new Set),v(this,Jt,new Map),v(this,ms,!1),v(this,fr,new xd),n===it.CF&&v(this,nn,new rd(o(this,$).socketHandler.audioActivity.bind(o(this,$).socketHandler))),this.e2ee=(s=(r=e.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?s:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),v(this,od,Pd(()=>u(this,null,function*(){if(!o(this,vr,vs).mediaJoinAttempted)return;const{roomJoined:c}=yield this.joinRoom(o(this,ad),o(this,sd),{},!0,!0);c&&(R.emit(M.RESET_PRODUCER_STATE),R.emit(M.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get mediaJoined(){return o(this,vr,vs).mediaJoined}set mediaJoined(e){o(this,vr,vs).mediaJoined=e}reset(e=!0){o(this,$).closeAllProducers(),o(this,$).closeAllConsumers(),o(this,Ii).clear(),e&&(this.partialJoinRoomPromise=void 0,o(this,fr).stop(),o(this,$).stopAllTransports(),o(this,$).reset(),v(this,fr,new xd))}joinRoom(e,n){return u(this,arguments,function*(i,r,s={},a=!1,c=!1){o(this,vr,vs).mediaJoinAttempted=!0,v(this,ps,!0),this.reset(a);const d=dt().ipInfo;if(d!=null&&d.loc&&!o(this,co)){const h=d.loc.split(",");v(this,co,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let l;try{return l=yield o(this,fr).push(()=>this._joinRoom(i,r,s,c,o(this,co)),"joinRoom"),l}catch{l={roomJoined:!1}}return l.roomJoined||R.emit(M.ROOM_NODE_FAILED),l})}_partialJoinRoom(e,n,i=!1,r=void 0){return u(this,null,function*(){var s;const{ipInfo:a}=dt();let c=r;if(a!=null&&a.loc&&!r){const[h,m]=a.loc.split(",").map(parseFloat);c={latitude:h,longitude:m}}const d=(s=Z.getValue(re.FORCE_VIDEO_CODEC))==null?void 0:s.toString(),l=DN(d);v(this,oo,l),this.maxPreferredStreams=this.context.getValue("maxPreferredStreams"),yield Ep((h,m)=>u(this,null,function*(){if(!o(this,bt).isConnected){m(new Error("socket is not connected"));return}h>0&&p.warn(`retrying sending join room request, count: ${h}`);try{yield o(this,$).socketHandler.joinRoom(n,e,l,i,c)}catch(y){throw p.error("failed to send join room request, error:",{error:y}),y}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:Z.hasFeature(re.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),yield o(this,$).setupTransports({send:!0,recv:!0}),o(this,gr)!==it.HIVE&&Z.hasFeature(re.PRECREATE_PRODUCERS)&&(this.shareWebcam(QN()),this.shareMic(YN()))})}partialJoinRoom(e,n,i=!1,r=void 0){return u(this,null,function*(){return this.partialJoinRoomPromise=o(this,fr).push(()=>this._partialJoinRoom(e,n,i,r)),this.partialJoinRoomPromise})}_joinRoom(e,n){return u(this,arguments,function*(i,r,s={},a=!1,c=null){v(this,ad,i);try{this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(i,r,a,c)}catch(d){p.error("error in partial join room",{error:d})}finally{this.partialJoinRoomPromise=void 0}try{return navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const d={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:r,roomViewType:"groupCall",deviceInfo:J(U({},Pe.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};K.roomJoined(d)})),{roomJoined:yield this.completeJoinRoom()}}catch(d){return p.error("error on sending join room request",{error:d}),{roomJoined:!1}}})}completeJoinRoom(){return u(this,null,function*(){try{this.mediaJoined=!0;const{maxPreferredStreams:e,roomState:n}=yield o(this,$).socketHandler.notifySelfJoinComplete();return v(this,sd,n.roomUuid),v(this,ms,!0),v(this,ps,!1),this.maxPreferredStreams=e!=null?e:6,!0}catch(e){return p.error("error on completing join room:",{error:e}),this.mediaJoined=!1,!1}})}leaveRoom(){return u(this,null,function*(){o(this,$).stopAllTransports(),v(this,ms,!1),o(this,vr,vs).mediaJoinAttempted=!1;const e={closeRoom:!1};o(this,bt).sendMessagePromise(o(this,Lt).leaveRoom,WC.toBinary(e)).then(n=>{var i;(i=IP.fromBinary(n.payload))!=null&&i.closed||p.warn("weird state on peer closed and should not happen")}).catch(n=>{p.error("error on sending leave room request",{error:n})}),K.callEnded(),E.destruct()})}getConsumers(){return o(this,$).consumers}activatePeers(e){return u(this,null,function*(){return this.createConsumers(e)})}deactivatePeers(e,n="default"){return u(this,null,function*(){const i=new Set;e.forEach(s=>{s.screenShare&&s.kind==="video"&&i.add(s.producingPeerId)});const r=n==="default"?e.filter(s=>!i.has(s.producingPeerId)).filter(s=>s.kind!=="audio"):e;yield Promise.all(r.map(s=>{const a=o(this,$).producerIdToConsumerIdMap.get(s.producerId);if(!a){p.warn(`consumer not found in deactivate producers: ${s.producerId}`);return}return o(this,$).closeConsumer(a)}))})}createConsumers(e){return u(this,null,function*(){return e.length===0?Promise.resolve():o(this,$).createConsumers(e)})}closeConsumers(e){return u(this,null,function*(){if(!e.length)return;const n=e.reduce((i,r)=>{const s=o(this,$).producerIdToConsumerIdMap.get(r.producerId);return s?(i.push(s),i):(p.warn(`consumer not found in deactivate producers: ${r.producerId}`),i)},[]);yield o(this,$).closeConsumers(n)})}_shareWebcam(e,n){return u(this,null,function*(){const i=n==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,r=H(this,ht,_t).call(this,i);if(r){const h=yield r;if(o(this,$).producers.has(h)){const m=o(this,$).producers.get(h);if(!m.closed&&!navigator.isReactNative)return yield m.replaceTrack({track:e}),yield this.resumeWebcam(i),e;yield this.disableWebcam(n)}return this._shareWebcam(e,n)}const s=H(this,Lh,eS).call(this,e,n),a=Md(this.context,"disableSimulcast"),c=o(this,gr)===it.CF?re.ENABLE_CF_SIMULCAST:re.ENABLE_HIVE_SIMULCAST;!a&&Z.hasFeature(c)?(p.info(`Simulcast enabled for SFU: ${o(this,gr)}`),s.encodings=IO(e)):p.info(`Simulcast disabled for webcam producer, SFU: ${o(this,gr)}`),Z.hasFeature(re.TRACK_HINT)&&(s.track.contentHint=Z.getValue(re.TRACK_HINT));const d=()=>{p.info("Disabling video due to the producer closure"),o(this,Jt).delete(i)},l=o(this,$).createProducer(s,d);return H(this,ys,lo).call(this,i,l.then(h=>h.id)),l.then(h=>h.track)})}shareWebcam(e){return u(this,null,function*(){if(e===void 0)return null;if(Z.hasFeature(re.FORCE_VIDEO_CODEC)){const n=Z.getValue(re.FORCE_VIDEO_CODEC).toString();if(n)return p.debug(`Calling _shareWebcam with forced video codec: ${n}`),this._shareWebcam(e,n)}return yield Promise.all(Pn.map(n=>{var i,r;return((r=(i=o(this,oo).sender)==null?void 0:i.video)==null?void 0:r.codecs.findIndex(s=>s.mimeType===n))>=0&&o(this,fs).get(n).size>0?(p.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(e,n)):e})),e})}shareScreen(e){return u(this,null,function*(){const{video:n,audio:i}=e;if(n===void 0)return;const r={track:n,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Pe.isElectron()},stopTracks:!1},s=()=>{p.info("Disabling screenShare due to the producer closure"),o(this,Jt).delete(ke.SCREENSHARE_VIDEO),o(this,Jt).delete(ke.SCREENSHARE_AUDIO)},a=o(this,$).createProducer(r,s);H(this,ys,lo).call(this,ke.SCREENSHARE_VIDEO,a.then(d=>d.id));let c;if(i){const d={track:i,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Pe.isElectron()},stopTracks:!1,zeroRtpOnPause:!0},l=()=>{};c=o(this,$).createProducer(d,l),H(this,ys,lo).call(this,ke.SCREENSHARE_AUDIO,c.then(h=>h.id))}yield Promise.all([a,c||Promise.resolve()]),K.screenShareStart()})}shareMic(e){return u(this,null,function*(){try{if(e===void 0)throw new Pt("track undefined");const n=H(this,ht,_t).call(this,ke.MIC);if(n){const a=yield n;if(o(this,$).producers.has(a)){const c=o(this,$).producers.get(a);if(!c.closed&&!navigator.isReactNative){yield c.replaceTrack({track:e}),yield this.resumeMic(),o(this,nn)&&(o(this,nn).audioTrack=e,o(this,nn).producerId=a,o(this,nn).start());return}yield o(this,$).closeProducer(a,{stopTrack:!1})}yield this.shareMic(e);return}const i=H(this,Nh,Zy).call(this,e),r=()=>{o(this,Jt).delete(ke.MIC)},s=o(this,$).createProducer(i,r);H(this,ys,lo).call(this,ke.MIC,s.then(a=>a.id)),yield s.then(a=>{o(this,nn)&&(o(this,nn).audioTrack=a.track,o(this,nn).producerId=a.id,o(this,nn).start())})}catch(n){throw new I(n)}})}pauseMic(){return u(this,null,function*(){const e=yield H(this,ht,_t).call(this,ke.MIC),n=o(this,$).producers.get(e);if(!n){p.error("pauseMic::could_not_find_mic_producer");return}if(n.paused){p.info("pauseMic::mic_producer_already_paused");return}n.pause();const i={producerId:n.id,pause:!0};o(this,bt).sendMessage(o(this,Lt).toggleProducer,rc.toBinary(i))})}pauseWebcam(){return u(this,null,function*(){const e=yield H(this,ht,_t).call(this,ke.WEBCAM),n=yield H(this,ht,_t).call(this,ke.WEBCAM_BACKUP),i=o(this,$).producers.get(e),r=o(this,$).producers.get(n);if(!i&&!r){p.error("pauseWebcam::could_not_find_webcam_producer");return}const s=a=>{const c={producerId:a.id,pause:!0};o(this,bt).sendMessage(o(this,Lt).toggleProducer,rc.toBinary(c))};i&&(i.pause(),s(i)),r&&(r.pause(),s(r))})}resumeMic(){return u(this,null,function*(){const e=yield H(this,ht,_t).call(this,ke.MIC),n=o(this,$).producers.get(e);if(!n){p.error("resumeMic::could_not_find_mic_producer");return}if(!n.pause){p.info("resumeMic::mic_producer_already_resumed");return}n.resume(),n.appData.e2ee&&R.emit(M.E2EE_ACTIVE_PRODUCER,n);const i={producerId:n.id,pause:!1};o(this,bt).sendMessage(o(this,Lt).toggleProducer,rc.toBinary(i))})}resumeWebcam(){return u(this,arguments,function*(e=ke.WEBCAM){const n=yield H(this,ht,_t).call(this,e),i=o(this,$).producers.get(n);if(!i){p.error("resumeWebcam::could_not_find_webcam_producer");return}if(!i.paused){p.info("resumeWebcam::webcam_producer_already_resumed");return}i.resume(),i.appData.e2ee&&R.emit(M.E2EE_ACTIVE_PRODUCER,i);const r={producerId:i.id,pause:!1};o(this,bt).sendMessage(o(this,Lt).toggleProducer,rc.toBinary(r))})}disableWebcam(e){return u(this,null,function*(){const n=e==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,i=yield H(this,ht,_t).call(this,n);i&&(yield o(this,$).closeProducer(i)),o(this,Jt).delete(n)})}disableMic(){return u(this,null,function*(){var e;const n=yield H(this,ht,_t).call(this,ke.MIC);n&&(yield o(this,$).closeProducer(n)),(e=o(this,nn))==null||e.stop(),o(this,Jt).delete(ke.MIC)})}disableScreenShare(){return u(this,null,function*(){p.info("screen_sharing_stopped"),K.screenShareStop();const e=yield H(this,ht,_t).call(this,ke.SCREENSHARE_VIDEO),n=yield H(this,ht,_t).call(this,ke.SCREENSHARE_AUDIO);e&&(yield o(this,$).closeProducer(e)),n&&(yield o(this,$).closeProducer(n)),o(this,Ii).clear(),o(this,Jt).delete(ke.SCREENSHARE_VIDEO),o(this,Jt).delete(ke.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(e,n){return u(this,null,function*(){if(e){const i=yield H(this,ht,_t).call(this,ke.WEBCAM),r=yield H(this,ht,_t).call(this,ke.WEBCAM_BACKUP);yield o(this,$).closeProducer(i,{stopTrack:!1}),yield o(this,$).closeProducer(r,{stopTrack:!1}),this.shareWebcam(e)}if(n){const i=yield H(this,ht,_t).call(this,ke.SCREENSHARE_VIDEO);yield o(this,$).closeProducer(i,{stopTrack:!1}),this.shareScreen({video:n})}})}changeDisplayName(e,n){return u(this,null,function*(){const i={displayName:e,participantId:n!=null?n:this.peerId};if(!(yield o(this,$).socketHandler.changeDisplayName(i)))throw new Error("failed to change display name!")})}kick(e){return u(this,null,function*(){const n={participantId:e};if(!(yield o(this,$).socketHandler.kickPeer(n)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForPeer(e,"audio")))throw new Error("failed to mute given participant")})}disableVideo(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForPeer(e,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(e){return u(this,null,function*(){const n={participantId:e!=null?e:""};try{yield o(this,bt).sendMessagePromise(o(this,Lt).globalPinPeer,QC.toBinary(n))}catch(i){p.error("Error in pinning peer:",{error:i})}})}validateScreenShare(e){return this.peerId===e.peerId&&o(this,$).producers.get(e.producerId)&&o(this,Ii).add(e.consumerPeerId),o(this,Ii).size}switchConsumersToLayer(e,n){return u(this,null,function*(){o(this,$).switchConsumersToLayer(e,n)})}handleSocketEvents(){return u(this,null,function*(){o(this,bt).on(o(this,Lt).peerProducerCreateBroadcast,({payload:e})=>{var n,i;if(this.mediaJoined)try{const{participantId:r,producerState:s}=rR.fromBinary(e);if(r===this.peerId)return;if(s!=null&&s.mimeType||(s.mimeType=s.kind===Vn.AUDIO?"audio/opus":"video/VP8"),s.kind===Vn.VIDEO&&!s.screenShare&&((i=(n=o(this,oo).receiver)==null?void 0:n.video)==null?void 0:i.codecs.findIndex(a=>a.mimeType===Pn[0]))>=0&&o(this,gs).get(Pn[0]).has(r)&&s.mimeType!==Pn[0]){p.warn(`Ignoring producer: ${s.producerId}`);return}p.info(`producer created broadcast: ${r}, producer state: ${s}`),R.emit(M.NEW_PRODUCER,{peerId:r,producer:J(U({},s),{kind:s.kind===Vn.AUDIO?"audio":"video",producingPeerId:r})})}catch(r){p.error("error in peer-producer-create-broadcast",{error:r})}}),o(this,bt).on(o(this,Lt).peerProducerToggleBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,initiatorParticipantId:i,producerState:{kind:r,pause:s,producerId:a}}=sg.fromBinary(e),c=r===Vn.AUDIO?"audio":"video";if(p.info(`producer toggle broadcast: ${n}, producerId: ${a}, kind:${c}, paused:${s} payload: ${JSON.stringify(sg.fromBinary(e))}`),n===this.peerId&&i!==this.peerId&&s&&R.emit(c==="audio"?M.MUTE_SELF:M.MUTE_SELF_VIDEO),n===this.peerId)return;R.emit(M.PRODUCER_TOGGLE,{peerId:n,producerId:a,paused:s,kind:c}),Array.from(this.getConsumers().values()).filter(d=>d.producerId===a).forEach(d=>{d.paused!==s&&(p.debug(`consumer state mismatched for ${d.id}. updating consumer pause state ${d.paused} to ${s}`),s?(d.pause(),R.emit(M.CONSUMER_PAUSED,{id:d.id})):(d.resume(),R.emit(M.CONSUMER_RESUMED,{id:d.id})))})}catch(n){p.error("error in producer toggle broadcast handler",{error:n})}}),o(this,bt).on(o(this,Lt).peerLeaveBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n}=Wu.fromBinary(e);if(n===this.peerId)return;p.info(`peer left broadcast:${n}`),o(this,Ii).delete(n),o(this,$).consumers.forEach(i=>{i.peerId===n&&i.close()}),R.emit(M.PEER_CLOSED,{id:n})}catch(n){p.error("error in peer left broadcast",{error:n})}}),o(this,bt).on(o(this,Lt).peerProducerCloseBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,producerState:{producerId:i}}=oR.fromBinary(e);if(n===this.peerId)return;p.info(`producer closed broadcast:${n}`),R.emit(M.PRODUCER_CLOSED,{peerId:n,producerId:i});const r=o(this,$).producerIdToConsumerIdMap.get(i);if(!r){p.warn(`no consumer found for producer:${i}`);return}p.info(`closing consumer ${r}, producer id: ${i}`),o(this,$).closeConsumer(r).then(()=>{p.info(`closed consumer: ${r}`),o(this,$).producerIdToConsumerIdMap.delete(i),R.emit(M.CONSUMER_CLOSED,{id:r})}).catch(s=>{p.error("error closing consumer",{error:s})})}catch(n){p.error("error on producer close broadcast",{error:n})}}),o(this,bt).on(o(this,Lt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!o(this,ps)&&!o(this,ms)||(p.warn("media hub termination broadcast received, rejoining room"),R.emit(M.ROOM_NODE_DISCONNECTED),o(this,od).call(this))})})}handleCallstatsEvents(){K.onConsumerScore(e=>{e.forEach((n,i)=>{const r=o(this,$).consumers.get(i);r&&R.emit(M.CONSUMER_SCORE_UPDATE,{id:i,kind:r.kind,peerId:r.peerId,score:n.score,scoreStats:n})})}),K.onProducerScore(e=>{e.forEach((n,i)=>{const r=Array.from(o(this,$).producers.values()).find(s=>s.id===i);r&&R.emit(M.PRODUCER_SCORE_UPDATE,{id:i,kind:r.kind,appData:r.appData,score:n.score,scoreStats:n})})})}handlePeerCapabilities(e,n){var i,r,s,a;for(let c=0;c<=Pn.length;c+=1){const d=Pn[c];if(((r=(i=n==null?void 0:n.receiver)==null?void 0:i.video)==null?void 0:r.codecs.findIndex(l=>l.mimeType===d))>=0||c===Pn.length-1){o(this,fs).get(d).add(e);break}}for(let c=0;c<=Pn.length;c+=1){const d=Pn[c];if(((a=(s=n==null?void 0:n.sender)==null?void 0:s.video)==null?void 0:a.codecs.findIndex(l=>l.mimeType===d))>=0||c===Pn.length-1){o(this,gs).get(d).add(e);break}}}handlePeerLeaving(e){Z.hasFeature(re.FORCE_VIDEO_CODEC)||(o(this,gs).forEach(n=>n.delete(e)),o(this,fs).forEach((n,i)=>{n.delete(e),n.size===0&&this.disableWebcam(i)}))}}sd=new WeakMap,ad=new WeakMap,bt=new WeakMap,$=new WeakMap,oo=new WeakMap,gr=new WeakMap,Lt=new WeakMap,ps=new WeakMap,ms=new WeakMap,fr=new WeakMap,od=new WeakMap,Ii=new WeakMap,co=new WeakMap,gs=new WeakMap,fs=new WeakMap,Jt=new WeakMap,nn=new WeakMap,vr=new WeakSet,vs=function(){return this.context.getValue("connectionHandler")},ht=new WeakSet,_t=function(t){return o(this,Jt).get(t)},ys=new WeakSet,lo=function(t,e){return o(this,Jt).set(t,e)},Nh=new WeakSet,Zy=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0}},Lh=new WeakSet,eS=function(t,e){return{track:t,codecOptions:[{name:e?e.split("/")[1]:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}};he([E.trace("MediaNodeClient.reset",{country:E.location.country})],ue.prototype,"reset",1);he([E.trace("MediaNodeClient.joinRoom")],ue.prototype,"joinRoom",1);he([E.trace("MediaNodeClient.completeJoinRoom")],ue.prototype,"completeJoinRoom",1);he([E.trace("MediaNodeClient.leaveRoom")],ue.prototype,"leaveRoom",1);he([E.trace("MediaNodeClient.activatePeers")],ue.prototype,"activatePeers",1);he([E.trace("MediaNodeClient.deactivatePeers")],ue.prototype,"deactivatePeers",1);he([E.trace("MediaNodeClient.createConsumers")],ue.prototype,"createConsumers",1);he([E.trace("MediaNodeClient.closeConsumers")],ue.prototype,"closeConsumers",1);he([E.trace("MediaNodeClient._shareWebcam")],ue.prototype,"_shareWebcam",1);he([E.trace("MediaNodeClient.shareWebcam")],ue.prototype,"shareWebcam",1);he([E.trace("MediaNodeClient.shareScreen")],ue.prototype,"shareScreen",1);he([E.trace("MediaNodeClient.shareMic")],ue.prototype,"shareMic",1);he([E.trace("MediaNodeClient.pauseMic")],ue.prototype,"pauseMic",1);he([E.trace("MediaNodeClient.pauseWebcam")],ue.prototype,"pauseWebcam",1);he([E.trace("MediaNodeClient.resumeMic")],ue.prototype,"resumeMic",1);he([E.trace("MediaNodeClient.resumeWebcam")],ue.prototype,"resumeWebcam",1);he([E.trace("MediaNodeClient.disableWebcam")],ue.prototype,"disableWebcam",1);he([E.trace("HiveClient.disableMic")],ue.prototype,"disableMic",1);he([E.trace("HiveClient.disableScreenShare")],ue.prototype,"disableScreenShare",1);he([E.trace("MediaNodeClient.muteSelf")],ue.prototype,"muteSelf",1);he([E.trace("MediaNodeClient.resetVideoProducers")],ue.prototype,"resetVideoProducers",1);he([E.trace("MediaNodeClient.changeDisplayName")],ue.prototype,"changeDisplayName",1);he([E.trace("MediaNodeClient.kickPeer")],ue.prototype,"kick",1);he([E.trace("MediaNodeClient.kickAllPeers")],ue.prototype,"kickAll",1);he([E.trace("MediaNodeClient.muteAll")],ue.prototype,"muteAll",1);he([E.trace("MediaNodeClient.muteAllVideo")],ue.prototype,"muteAllVideo",1);he([E.trace("MediaNodeClient.disableAudio")],ue.prototype,"disableAudio",1);he([E.trace("MediaNodeClient.disableVideo")],ue.prototype,"disableVideo",1);he([E.trace("MediaNodeClient.pinPeer")],ue.prototype,"pinPeer",1);he([E.trace("MediaNodeClient.validateScreenShare")],ue.prototype,"validateScreenShare",1);function tS(t,e,n){const i=t.getValue("roomNodeClient");if(i){if(i)return i;throw new Error("Room node client already set up.")}const r=new ue(t,e,n);return t.setValue("roomNodeClient",r),r}function nS(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch{p.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var eL=Object.defineProperty,tL=Object.getOwnPropertyDescriptor,Hr=(t,e,n,i)=>{for(var r=i>1?void 0:i?tL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&eL(e,n,r),r},Zi,Rn,St,en,ln,Xg;const iS=(Xg=class{constructor(t,e,n,i){f(this,en),g(this,"self"),g(this,"authToken"),f(this,Zi,void 0),g(this,"viewType"),f(this,Rn,void 0),f(this,St,void 0);const{socket:r}=n,s=t.getValue("authToken");this.self=e,v(this,St,t),this.viewType=i,this.authToken=s,v(this,Zi,r),v(this,Rn,n),e.config.viewType!==Rt.Chat&&this.setupEvents()}get peerId(){return o(this,St).getValue("peerId")}get mediaJoined(){return o(this,St).getValue("connectionHandler").mediaJoined}static init(t,e,n,i,r){return u(this,null,function*(){const s=dt(),a=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield st.__init__(t,n,i,r,r.name,c);if(navigator.product!=="ReactNative"){const l=!Z.hasFeature(re.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const h=yield d.getAllDevices();p.info("populated_full_device_list",{devices:JSON.stringify(h)}),K.devices("AUDIO",h==null?void 0:h.filter(m=>m.kind==="audioinput")),K.devices("VIDEO",h==null?void 0:h.filter(m=>m.kind==="videoinput")),K.devices("SPEAKER",h==null?void 0:h.filter(m=>m.kind==="audiooutput")),p.info("Callstats:: initializing");try{yield K.initialize({peerId:a,engineName:Pe.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:Z.getAllFlags(),logger:p,apiHostnames:zv(t),skipConnectivityChecks:l}),p.info("Callstats:: initialized")}catch(m){p.error("Callstats:: initialization failed",{error:m})}}),0)}else p.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new iS(t,d,e,r.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:n,permissions:i,audioEnabled:r,videoEnabled:s,screenShareEnabled:a,screenShareTracks:c}=this.self;if(i.canProduceAudio&&r)try{yield o(this,en,ln).shareMic(e)}catch{this.self.disableAudio()}if(i.canProduceVideo&&s)try{const d=yield o(this,en,ln).shareWebcam(n);d&&d.id!==n.id&&Z.hasFeature(re.EXP_RESHARE)&&(yield o(this,en,ln).shareWebcam(d))}catch{this.self.disableVideo()}if(i.canProduceScreenshare&&a)try{yield(t=o(this,en,ln))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch{this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}waitlistedHandler(){p.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(p.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){p.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(p.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){p.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){K.callEnded(),o(this,en,ln).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){R.on(M.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),R.on(M.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),R.on(M.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),R.on(M.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),R.on(M.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),R.on(M.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&Z.hasFeature(re.REFRESH_ID_ON_DISCONNECTION)&&(e=Fs()),o(this,Zi).updateURL(e),E.resetPeerId(e),dt().setHeader("dyte-tracing-id",e),Rr.remapContext(e,o(this,St)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),R.on(M.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),o(this,Rn).on(j.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),o(this,Rn).on(Lc.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&R.emit(M.UPDATE_PERMISSIONS,e.patch)})}),o(this,Rn).on(j.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),o(this,Rn).on(j.kick,()=>{this.kickHandler({kickType:"kick"})}),o(this,Rn).on(j.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),R.onAsync(M.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),R.on(M.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:n,scoreStats:i})=>{var r;const s=(r=n==null?void 0:n.screenShare)!=null?r:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:i})}),R.on(M.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),K.audioOff())})),R.on(M.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),K.videoOff())})),R.onAsync(M.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),R.on(M.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield o(this,Rn).joinRoom(this.self);o(this,Rn).socket.flush();const n=pp(e.stageType);if(o(this,St).setValue("stageStatus",n,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),o(this,St).notify("stageStatus")}catch(e){throw p.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,n;if(t==="rejected"){try{(e=o(this,Zi))==null||e.disconnect()}catch{p.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),o(this,St).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),o(this,St).notify("stageStatus");try{(n=o(this,Zi))==null||n.disconnect()}catch{p.error("SelfController::leaveRoom::socketDisconnect")}nS(o(this,St)),Ld.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,n;const{peerId:i,viewType:r,meetingId:s,stageStatus:a,roomNodeOptions:c}=o(this,St).getAllValues(),{sfu:d}=c;try{if(r===Rt.Livestream){if(a!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}tS(o(this,St),d,{socket:o(this,Zi),peerId:i})}const{roomJoined:l}=(n=yield(e=o(this,en,ln))==null?void 0:e.joinRoom(this.self.name,s,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},t,t))!=null?n:{};if(!l)return;a==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw p.error("Error:SelfController.mediaRoomJoin",l),new I("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=o(this,St).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Rt.Webinar)&&o(this,en,ln)&&(o(this,en,ln).mediaJoined&&t!=="disconnected"&&(yield o(this,en,ln).leaveRoom()),!(t==="stageLeft"&&e===Rt.Livestream)&&(o(this,en,ln).mediaJoined=!1))})}cleanupSelf(){return u(this,null,function*(){yield this.self.disableAudio(),yield this.self.disableVideo(),yield this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()})}},Zi=new WeakMap,Rn=new WeakMap,St=new WeakMap,en=new WeakSet,ln=function(){return o(this,St).getValue("roomNodeClient")},Xg);let Ji=iS;Hr([E.trace("SelfController.resetSelf")],Ji.prototype,"resetSelf",1);Hr([E.trace("SelfController.setupEvents")],Ji.prototype,"setupEvents",1);Hr([E.trace("SelfController.joinRoom")],Ji.prototype,"joinRoom",1);Hr([E.trace("SelfController.leaveRoom")],Ji.prototype,"leaveRoom",1);Hr([E.trace("SelfController.joinMediaRoom")],Ji.prototype,"joinMediaRoom",1);Hr([E.trace("SelfController.leaveMediaRoom")],Ji.prototype,"leaveMediaRoom",1);Hr([E.trace("SelfController.init")],Ji,"init",1);var cd;class nL{constructor(e){f(this,cd,void 0),v(this,cd,e)}on(e,n){let i;e===j.roomPeerCount?i=cg.fromBinary.bind(cg):i=Sg.fromBinary.bind(Sg),o(this,cd).on(e,({payload:r})=>{const s=i(r);return n(s)})}}cd=new WeakMap;var dd;class iL{constructor(e){f(this,dd,void 0),v(this,dd,e)}on(e,n){let i,r;switch(e){case j.transcript:{i=Gl.fromBinary.bind(Gl),r=Gl.create();break}default:{p.debug("AISocketHandler switch case hit default, event not accounted for.");break}}o(this,dd).on(e,({payload:s})=>{let a=r;try{a=i(s)}catch(c){p.error("chatSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}}dd=new WeakMap;var rL=Object.defineProperty,sL=Object.getOwnPropertyDescriptor,wp=(t,e,n,i)=>{for(var r=i>1?void 0:i?sL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&rL(e,n,r),r},Ci;class vl{constructor(e){f(this,Ci,void 0),v(this,Ci,e)}getPolls(){return o(this,Ci).sendMessagePromise(Yn.getPolls)}createPoll(e,n,i=!1,r=!1){const s={anonymous:i,hideVotes:r,question:e,options:n};return o(this,Ci).sendMessage(Yn.createPoll,Y1.toBinary(s))}votePoll(e,n){const i={index:n,pollId:e};return o(this,Ci).sendMessage(Yn.votePoll,X1.toBinary(i))}on(e,n){let i,r;switch(e){case Yn.updatePoll:case Yn.createPoll:case Yn.votePoll:{i=Ql.fromBinary.bind(Ql),r=Ql.create();break}}o(this,Ci).on(e,({payload:s})=>{let a=r;try{a=i(s)}catch(c){p.error("pollSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}removeListeners(e){o(this,Ci).removeListeners(e)}}Ci=new WeakMap;wp([E.trace("PollSocketHandler.getPolls")],vl.prototype,"getPolls",1);wp([E.trace("PollSocketHandler.createPoll")],vl.prototype,"createPoll",1);wp([E.trace("PollSocketHandler.votePoll")],vl.prototype,"votePoll",1);var Gt;class aL{constructor(e){f(this,Gt,void 0),v(this,Gt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield o(this,Gt).sendMessagePromise(j.getStageRequests);return e?Yl.fromBinary(e):{stageRequests:[]}})}requestAccess(){o(this,Gt).sendMessage(j.requestStageAccess)}cancelRequestAccess(){o(this,Gt).sendMessage(j.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const n={userIds:e};o(this,Gt).sendMessage(j.grantStageAccess,B1.toBinary(n))})}denyAccess(e){return u(this,null,function*(){const n={userIds:e};o(this,Gt).sendMessage(j.denyStageAccess,j1.toBinary(n))})}joinStage(){return o(this,Gt).sendMessagePromise(j.joinStage,void 0,void 0,j.peerStageStatusUpdate)}leaveStage(e){const n={userIds:[e]};return o(this,Gt).sendMessagePromise(j.leaveStage,Tg.toBinary(n),void 0,j.peerStageStatusUpdate)}kick(e){const n={userIds:e};return o(this,Gt).sendMessagePromise(j.leaveStage,Tg.toBinary(n))}on(e,n){let i;switch(e){case j.grantStageAccess:case j.denyStageAccess:{i=void 0;break}case j.getStagePeers:{i=Eg.fromBinary.bind(Eg);break}case j.getStageRequests:case j.requestStageAccess:case j.cancelStageRequest:{i=Yl.fromBinary.bind(Yl);break}case j.peerStageStatusUpdate:{i=og.fromBinary.bind(og);break}}o(this,Gt).on(e,({payload:r,id:s})=>{if(!r||!i)return n(void 0,s);const a=i(r);return n(a,s)})}getPeerInfo(e){return u(this,null,function*(){const n=yield o(this,Gt).sendMessagePromise(j.getPeerInfo,sy.toBinary({peerId:e}));return ns.fromBinary(n.payload)})}}Gt=new WeakMap;var tt;class oL{constructor(e){f(this,tt,void 0),v(this,tt,e)}addPlugin(e,n){o(this,tt).sendMessage(z.addPlugin,i1.toBinary({pluginId:e,staggered:n}))}removePlugin(e){o(this,tt).sendMessage(z.removePlugin,s1.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield o(this,tt).sendMessagePromise(z.getPlugins);return e?P1.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,n,i){const r={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(n))};o(this,tt).sendMessage(z.customPluginEventToRoom,g1.toBinary(r),i)}customPluginEventToPeers(e,n,i,r){const s={pluginId:e,peerIds:n,pluginData:new TextEncoder().encode(JSON.stringify(i))};o(this,tt).sendMessage(z.customPluginEventToPeers,v1.toBinary(s),r)}enablePluginForRoom(e,n){o(this,tt).sendMessage(z.enablePluginForRoom,o1.toBinary({pluginId:e}),n)}enablePluginForPeers(e,n,i){o(this,tt).sendMessage(z.enablePluginForPeers,u1.toBinary({pluginId:e,peerIds:n}),i)}disablePluginForRoom(e,n){o(this,tt).sendMessage(z.disablePluginForRoom,d1.toBinary({pluginId:e}),n)}disablePluginForPeers(e,n,i){o(this,tt).sendMessage(z.disablePluginForPeers,p1.toBinary({pluginId:e,peerIds:n}),i)}storeInsertKeys(e,n,i,r){const s={pluginId:e,storeName:n,insertKeys:i.map(a=>({storeKey:a.key,payload:new TextEncoder().encode(JSON.stringify(a.payload))}))};o(this,tt).sendMessage(z.storeInsertKeys,gg.toBinary(s),r)}storeGetKeys(e,n,i,r){const s={pluginId:e,storeName:n,getKeys:i.map(a=>({storeKey:a.key}))};o(this,tt).sendMessage(z.storeGetKeys,T1.toBinary(s),r)}storeDeleteKeys(e,n,i,r){const s={pluginId:e,storeName:n,deleteKeys:i.map(a=>({storeKey:a.key}))};o(this,tt).sendMessage(z.storeDeleteKeys,b1.toBinary(s),r)}storeDelete(e,n,i){o(this,tt).sendMessage(z.storeDelete,w1.toBinary({pluginId:e,storeName:n}),i)}getPluginDataOld(e,n){p.info("getPluginDataOld",{plugin:{id:e,storeName:n}})}storePluginDataOld(e,n,i){const r={pluginId:e,storeName:n,insertKeys:[{storeKey:i.key,payload:new TextEncoder().encode(JSON.stringify(i))}]};o(this,tt).sendMessage(z.storeInsertKeys,gg.toBinary(r))}on(e,n){let i;switch(e){case z.addPlugin:case z.enablePluginForPeers:case z.enablePluginForRoom:{i=Gu.fromBinary.bind(Gu);break}case z.removePlugin:case z.disablePluginForPeers:case z.disablePluginForRoom:{i=fg.fromBinary.bind(fg);break}case z.customPluginEventToPeers:case z.customPluginEventToRoom:{i=yg.fromBinary.bind(yg);break}case z.storeInsertKeys:case z.storeGetKeys:case z.storeDeleteKeys:case z.storeDelete:{i=vg.fromBinary.bind(vg);break}}o(this,tt).on(e,({payload:r,id:s})=>{const a=i(r);return n(a,s)})}}tt=new WeakMap;var cL=Object.defineProperty,dL=(t,e,n)=>e in t?cL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lL=(t,e,n)=>(dL(t,typeof e!="symbol"?e+"":e,n),n),Ip=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)},x=(t,e,n)=>(Ip(t,e,"read from private field"),n?n.call(t):e.get(t)),Ie=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},me=(t,e,n,i)=>(Ip(t,e,"write to private field"),i?i.call(t,n):e.set(t,n),n),De=(t,e,n)=>(Ip(t,e,"access private method"),n),qd={},uL={get exports(){return qd},set exports(t){qd=t}},Os=typeof Reflect=="object"?Reflect:null,Zg=Os&&typeof Os.apply=="function"?Os.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)},ld;Os&&typeof Os.ownKeys=="function"?ld=Os.ownKeys:Object.getOwnPropertySymbols?ld=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:ld=function(t){return Object.getOwnPropertyNames(t)};function hL(t){console&&console.warn&&console.warn(t)}var rS=Number.isNaN||function(t){return t!==t};function fe(){fe.init.call(this)}uL.exports=fe;qd.once=fL;fe.EventEmitter=fe;fe.prototype._events=void 0;fe.prototype._eventsCount=0;fe.prototype._maxListeners=void 0;var ef=10;function yl(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(fe,"defaultMaxListeners",{enumerable:!0,get:function(){return ef},set:function(t){if(typeof t!="number"||t<0||rS(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");ef=t}});fe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};fe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||rS(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function sS(t){return t._maxListeners===void 0?fe.defaultMaxListeners:t._maxListeners}fe.prototype.getMaxListeners=function(){return sS(this)};fe.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var i=t==="error",r=this._events;if(r!==void 0)i=i&&r.error===void 0;else if(!i)return!1;if(i){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=r[t];if(c===void 0)return!1;if(typeof c=="function")Zg(c,this,e);else for(var d=c.length,l=lS(c,d),n=0;n<d;++n)Zg(l[n],this,e);return!0};function aS(t,e,n,i){var r,s,a;if(yl(n),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),s=t._events),a=s[e]),a===void 0)a=s[e]=n,++t._eventsCount;else if(typeof a=="function"?a=s[e]=i?[n,a]:[a,n]:i?a.unshift(n):a.push(n),r=sS(t),r>0&&a.length>r&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=a.length,hL(c)}return t}fe.prototype.addListener=function(t,e){return aS(this,t,e,!1)};fe.prototype.on=fe.prototype.addListener;fe.prototype.prependListener=function(t,e){return aS(this,t,e,!0)};function pL(){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 oS(t,e,n){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},r=pL.bind(i);return r.listener=n,i.wrapFn=r,r}fe.prototype.once=function(t,e){return yl(e),this.on(t,oS(this,t,e)),this};fe.prototype.prependOnceListener=function(t,e){return yl(e),this.prependListener(t,oS(this,t,e)),this};fe.prototype.removeListener=function(t,e){var n,i,r,s,a;if(yl(e),i=this._events,i===void 0)return this;if(n=i[t],n===void 0)return this;if(n===e||n.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,n.listener||e));else if(typeof n!="function"){for(r=-1,s=n.length-1;s>=0;s--)if(n[s]===e||n[s].listener===e){a=n[s].listener,r=s;break}if(r<0)return this;r===0?n.shift():mL(n,r),n.length===1&&(i[t]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this};fe.prototype.off=fe.prototype.removeListener;fe.prototype.removeAllListeners=function(t){var e,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var r=Object.keys(n),s;for(i=0;i<r.length;++i)s=r[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=n[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function cS(t,e,n){var i=t._events;if(i===void 0)return[];var r=i[e];return r===void 0?[]:typeof r=="function"?n?[r.listener||r]:[r]:n?gL(r):lS(r,r.length)}fe.prototype.listeners=function(t){return cS(this,t,!0)};fe.prototype.rawListeners=function(t){return cS(this,t,!1)};fe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):dS.call(t,e)};fe.prototype.listenerCount=dS;function dS(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}fe.prototype.eventNames=function(){return this._eventsCount>0?ld(this._events):[]};function lS(t,e){for(var n=new Array(e),i=0;i<e;++i)n[i]=t[i];return n}function mL(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function gL(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function fL(t,e){return new Promise(function(n,i){function r(a){t.removeListener(e,s),i(a)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",r),n([].slice.call(arguments))}uS(t,e,s,{once:!0}),e!=="error"&&vL(t,r,{once:!0})})}function vL(t,e,n){typeof t.on=="function"&&uS(t,"error",e,n)}function uS(t,e,n,i){if(typeof t.on=="function")i.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function r(s){i.once&&t.removeEventListener(e,r),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class yL extends T{constructor(){super("message.v1.SocketMessage",[{no:1,name:"event",kind:"scalar",T:13},{no:2,name:"id",kind:"scalar",opt:!0,T:9},{no:3,name:"payload",kind:"scalar",opt:!0,T:12},{no:4,name:"metadata",kind:"scalar",opt:!0,T:12}])}}const tf=new yL;class hS{static encode(e){return tf.toBinary(e)}static decode(e){return tf.fromBinary(new Uint8Array(e))}}function SL(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Pi;class EL{constructor(e={}){lL(this,"opts"),Ie(this,Pi,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},me(this,Pi,0)}wait(){return u(this,null,function*(){me(this,Pi,x(this,Pi)+1);const e=SL(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*IE(2,x(this,Pi))));yield new Promise(n=>{setTimeout(n,e)})})}getAttempts(){return x(this,Pi)}reset(){me(this,Pi,0)}}Pi=new WeakMap;const fi={debug:0,info:1,warn:2,error:3};var yr,Sr;class TL{constructor(e){Ie(this,yr,void 0),Ie(this,Sr,void 0),me(this,yr,console),me(this,Sr,e)}debug(...e){fi[x(this,Sr)]>fi.debug||x(this,yr).debug("[Sockrates]:",...e)}info(...e){fi[x(this,Sr)]>fi.info||x(this,yr).info("[Sockrates]:",...e)}warn(...e){fi[x(this,Sr)]>fi.warn||x(this,yr).warn("[Sockrates]:",...e)}error(...e){fi[x(this,Sr)]>fi.error||x(this,yr).error("[Sockrates]:",...e)}}yr=new WeakMap,Sr=new WeakMap;var pS=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(pS||{});const kL="2",bL="3";var Ue,Ss,Ae,He,Ri,nt,ti,xi,Sn,Es,zn,xh,mS,uo,ud,Vh,gS,Uh,nf,Gd,Fh,Bh,fS,Ro,hd,Mo,Jd,$d,Wh,Ns,Ao,Do,Kd;class _L{constructor(e,n){var i;Ie(this,xh),Ie(this,uo),Ie(this,Vh),Ie(this,Uh),Ie(this,Gd),Ie(this,Bh),Ie(this,Ro),Ie(this,Mo),Ie(this,$d),Ie(this,Ns),Ie(this,Do),Ie(this,Ue,void 0),Ie(this,Ss,void 0),Ie(this,Ae,void 0),Ie(this,He,void 0),Ie(this,Ri,void 0),Ie(this,nt,void 0),Ie(this,ti,void 0),Ie(this,xi,void 0),Ie(this,Sn,void 0),Ie(this,Es,void 0),Ie(this,zn,void 0);var r,s,a,c,d,l,h,m,y;me(this,Ss,e),me(this,Ri,[]),me(this,nt,new qd),me(this,ti,!0),me(this,Sn,!1),me(this,Ae,n!=null?n:{}),(r=x(this,Ae)).autoReconnect!=null||(r.autoReconnect=!0),(s=x(this,Ae)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(a=x(this,Ae)).pingTimeout!=null||(a.pingTimeout=3e4),(c=x(this,Ae)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=x(this,Ae)).debug!=null||(d.debug=!0),(l=x(this,Ae)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(h=x(this,Ae)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(m=x(this,Ae)).queueOnDisconnect!=null||(m.queueOnDisconnect=!1),(y=x(this,Ae)).flushOnReconnect!=null||(y.flushOnReconnect=!1),me(this,xi,{code:void 0,reason:void 0}),me(this,He,(i=x(this,Ae).logger)!=null?i:new TL(x(this,Ae).debug?"debug":"info")),me(this,zn,new EL)}get readyState(){var e;return(e=x(this,Ue))==null?void 0:e.readyState}get url(){return x(this,Ss)}updateURL(e){me(this,Ss,e),De(this,Bh,fS).call(this)}get config(){return x(this,Ae)}get sendQueue(){return x(this,Ri)}flush(){if(!x(this,Ae).queueOnDisconnect)return!1;const e=[];return x(this,Ri).forEach(n=>{this.send(n.event,n.id,n.payload,n.metadata)||e.push(n)}),me(this,Ri,e),x(this,Ri)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){x(this,He).debug("Websocket was already connecting or connected.");return}if(x(this,ti)!==!1)return new Promise((n,i)=>{De(this,Ns,Ao).call(this),De(this,Do,Kd).call(this);try{me(this,Ue,new WebSocket(De(this,xh,mS).call(this,x(this,Ss)))),x(this,Ue).binaryType="arraybuffer",x(this,He).debug("Connecting");const r=setTimeout(()=>{x(this,He).debug("Connection timeout. Closing socket"),me(this,ti,!0),De(this,Do,Kd).call(this),x(this,Ue).close(3001,"Connection Timeout"),x(this,Ae).autoReconnect&&!x(this,Sn)&&(x(this,nt).emit("reconnecting"),De(this,Ro,hd).call(this)),i(new Error("Connection timed out!"))},x(this,Ae).connectionTimeout);x(this,Ue).onopen=()=>{x(this,He).debug(`Ready State: ${pS[x(this,Ue).readyState]}`),r&&clearTimeout(r),De(this,$d,Wh).call(this),me(this,xi,{code:void 0,reason:void 0}),x(this,nt).emit("connected"),x(this,Ae).flushOnReconnect&&this.flush(),n()},x(this,Ue).onclose=s=>{try{r&&clearTimeout(r);const{code:a,reason:c}=s;i(c),x(this,He).debug("Socket closed. Close event:",{event:s}),x(this,He).debug(`Connection closed code: ${a}`),x(this,He).debug(`Connection closed reason: ${c}`),x(this,Sn)||De(this,Gd,Fh).call(this,a,c)}catch(a){De(this,uo,ud).call(this,a)}},x(this,Ue).onerror=s=>{De(this,uo,ud).call(this,s)},x(this,Ue).onmessage=s=>De(this,Vh,gS).call(this,s)}catch(r){De(this,uo,ud).call(this,r,i)}})})}send(e,n,i,r){const s={event:e,id:n,payload:i,metadata:r};if(x(this,Ae).queueOnDisconnect&&(!x(this,Ue)||x(this,Ue).readyState!==1))return x(this,He).debug("Queuing message since socket is not connected!",s),x(this,Ri).push(s),!1;const a=hS.encode(s);return De(this,Mo,Jd).call(this,a)}emit(e,n,i,r){return this.send(e,n,i,r)}sendRaw(e){return De(this,Mo,Jd).call(this,e)}receive(e,n){return x(this,nt).on(e.toString(),n)}on(e,n){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){x(this,nt).on(e,n);return}this.receive(e,n)}removeAllListeners(){x(this,nt).removeAllListeners()}removeReceiver(e,n){this.removeListener(e,n)}removeListener(e,n){x(this,nt).removeListener(e.toString(),n)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){x(this,nt).listeners(e.toString()).map(n=>this.removeListener(e,n))}disconnect(){me(this,ti,!1),De(this,Ns,Ao).call(this),this.removeAllListeners(),me(this,xi,{code:1e3,reason:"Sockrates disconnect method called"}),x(this,Ue).close(1e3,"Sockrates disconnect method called.")}}Ue=new WeakMap,Ss=new WeakMap,Ae=new WeakMap,He=new WeakMap,Ri=new WeakMap,nt=new WeakMap,ti=new WeakMap,xi=new WeakMap,Sn=new WeakMap,Es=new WeakMap,zn=new WeakMap,xh=new WeakSet,mS=function(t){if(t.startsWith("ws://")||t.startsWith("wss://"))return t;if(t.startsWith("https://"))return`wss://${t.substring(8)}`;if(t.startsWith("http://"))return`ws://${t.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},uo=new WeakSet,ud=function(t,e){x(this,He).error("Error:",{error:t}),x(this,nt).emit("errored",{error:t}),e==null||e(t)},Vh=new WeakSet,gS=function(t){if(De(this,$d,Wh).call(this),t.data===kL){x(this,He).debug("Received ping from server"),De(this,Mo,Jd).call(this,bL);return}const e=hS.decode(t.data),{id:n,payload:i}=e;x(this,He).debug("Received message",{event:e.event,messageID:n}),x(this,nt).emit(e.event.toString(),{id:n,payload:i})},Uh=new WeakSet,nf=function(){return x(this,Ue).readyState===1},Gd=new WeakSet,Fh=function(t,e){me(this,xi,{reason:e,code:t}),x(this,nt).emit("disconnected",{code:t,reason:e})},Bh=new WeakSet,fS=function(){const{reason:t,code:e}=x(this,xi);e&&e!==1e3&&x(this,ti)&&x(this,Ae).autoReconnect&&!x(this,Sn)&&(x(this,He).debug(`Triggering reconnection due to ${t}.`),x(this,nt).emit("reconnecting"),De(this,Ro,hd).call(this))},Ro=new WeakSet,hd=function(t=!0){return u(this,null,function*(){if(t&&x(this,Sn)){x(this,He).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(x(this,Sn)||x(this,zn).reset(),x(this,Ae).maxReconnectionAttempts!==null&&x(this,zn).getAttempts()>=x(this,Ae).maxReconnectionAttempts){x(this,nt).emit("failed"),me(this,Sn,!1);return}me(this,Sn,!0),De(this,Do,Kd).call(this),De(this,Ns,Ao).call(this);try{if(yield x(this,zn).wait(),x(this,ti)===!1)return;if(x(this,He).debug(`Reconnection attempt ${x(this,zn).getAttempts()}`),x(this,nt).emit("reconnectAttempt",{attempt:x(this,zn).getAttempts()}),yield this.connect(),!De(this,Uh,nf).call(this))throw Error("Reconnect Failed");me(this,Sn,!1),me(this,xi,{code:void 0,reason:void 0}),x(this,nt).emit("reconnected")}catch{x(this,He).debug("Failed to reconnect."),x(this,nt).emit("reconnectFailure",{attempt:x(this,zn).getAttempts()}),De(this,Ro,hd).call(this,!1)}})},Mo=new WeakSet,Jd=function(t){try{return x(this,Ue).send(t),!0}catch(e){return x(this,He).error(e.message),!1}},$d=new WeakSet,Wh=function(){this.config.disconnectOnPingTimeout&&(x(this,He).debug("Resetting ping timeout"),De(this,Ns,Ao).call(this),me(this,Es,setTimeout(()=>{var t;x(this,He).debug("Disconnecting the socket due to ping timeout"),me(this,ti,!0);const e=3002,n="Ping timeout";(t=x(this,Ue))==null||t.close(e,n),De(this,Gd,Fh).call(this,e,n)},x(this,Ae).pingTimeout)))},Ns=new WeakSet,Ao=function(){x(this,Es)&&(clearTimeout(x(this,Es)),me(this,Es,void 0))},Do=new WeakSet,Kd=function(){x(this,Ue)&&(x(this,Ue).onopen=void 0,x(this,Ue).onerror=void 0,x(this,Ue).onmessage=void 0,x(this,Ue).onclose=void 0)};var wL=Object.defineProperty,IL=Object.getOwnPropertyDescriptor,Sl=(t,e,n,i)=>{for(var r=i>1?void 0:i?IL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&wL(e,n,r),r};const rf=65535,CL=3e3;var er,Le,xe,Fe,un,vi,bc,fu,_c,vu,sf;const vS=(sf=class{constructor(t,{peerId:e,meetingId:n,authToken:i,capabilities:r}){f(this,xe),f(this,bc),f(this,_c),f(this,er,void 0),f(this,Le,void 0),g(this,"roomName"),g(this,"authToken"),g(this,"capabilities"),f(this,un,void 0),f(this,vi,void 0);var s;if(!e||!n||!i)throw new I("peerId, meetingId, or authToken can not be empty","0404");v(this,un,void 0),v(this,vi,t),this.capabilities=r,this.roomName=n,this.authToken=i,v(this,er,H(this,bc,fu).call(this,e)),v(this,Le,new _L(o(this,er),{autoReconnect:!0,disconnectOnPingTimeout:(s=r.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:p})),this.handleSocketConnectionEvents()}get joinAttempted(){return o(this,xe,Fe).socketJoinAttempted}set joinAttempted(t){o(this,xe,Fe).socketJoinAttempted=t}get peerId(){return o(this,vi).getValue("peerId")}updateURL(t){t!==this.peerId&&(v(this,er,H(this,bc,fu).call(this,t)),p.debug("SocketService:: Connection URL updated.")),o(this,Le).updateURL(o(this,er))}static getSocketEdgeDomain(t){return Rs({servicePrefix:"socket-edge",baseURI:t})}get url(){return o(this,er)}connect(){return u(this,null,function*(){o(this,xe,Fe).socketJoinAttempted=!0,yield o(this,Le).connect(),o(this,xe,Fe).socketJoinAttempted=!0,o(this,xe,Fe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){o(this,xe,Fe).socketJoinAttempted=!1,o(this,Le).disconnect(),o(this,xe,Fe).socketJoinAttempted=!0,o(this,xe,Fe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return o(this,Le).readyState===1}catch{return!1}}sendMessage(t,e,n){const i={};return E.injectContext(i),o(this,Le).send(t,n!=null?n:H(this,_c,vu).call(this),e,new TextEncoder().encode(JSON.stringify(i)))}sendMessagePromise(t,e,n,i){const r=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:r,protobuf:e,messageId:n,resp:i})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:n,messageId:i,resp:r}){const s=r!=null?r:t;return new Promise((a,c)=>{const d=(S,b)=>{o(this,Le).removeListener(s,S),o(this,Le).removeListener(rf,b),o(this,Le).removeListener(sn.errorResponse,b),o(this,Le).removeListener(En.errorResponse,b)},l=i!=null?i:H(this,_c,vu).call(this),h={};E.injectContext(h);const m=({id:S,payload:b})=>{if(l===S){let D;try{const C=fP.fromBinary(b);D=new Error(C.errorMessage)}catch(C){D=new Error("failed to parse error message",{cause:C});try{const V=SR.fromBinary(b);D=new Error(V.message)}catch(V){D=new Error("failed to parse error message",{cause:V})}}c(D),d(y,m)}},y=({id:S,payload:b})=>{l===S&&(a({id:S,payload:b}),d(y,m))};o(this,Le).on(s,y),o(this,Le).on(rf,m),o(this,Le).on(sn.errorResponse,m),o(this,Le).on(En.errorResponse,m),setTimeout(()=>{d(y,m),c(new Error(`request timeout for callback eventId:${t}`))},e),o(this,Le).send(t,l,n,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){o(this,Le).on(t,e)}onStateEvent(t,e){o(this,Le).on(t,e)}removeListener(t,e){o(this,Le).removeListener(t,e)}removeListeners(t){o(this,Le).removeListeners(t)}flush(){return o(this,Le).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){p.info("SocketService::Connected to socket-edge"),o(this,un)&&(clearTimeout(o(this,un)),v(this,un,void 0)),o(this,xe,Fe).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var n;p.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:E.location.country});const{recv:i,send:r}=(n=o(this,xe,Fe).mediaState)!=null?n:{};i!=null&&i.state&&(i==null?void 0:i.state)!==Wi.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Wi.CONNECTED?R.emit(M.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,xe,Fe).joinAttempted}):v(this,un,setTimeout(()=>{R.emit(M.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,xe,Fe).joinAttempted}),v(this,un,void 0)},CL)),o(this,xe,Fe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){p.info("SocketService::Reconnecting to socket-edge",{country:E.location.country}),o(this,xe,Fe).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){p.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),o(this,xe,Fe).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{p.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),o(this,xe,Fe).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){p.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:o(this,xe,Fe).mediaJoinAttempted}}),o(this,un)&&(clearTimeout(o(this,un)),v(this,un,void 0)),R.emit(M.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:o(this,xe,Fe).mediaJoinAttempted}),o(this,xe,Fe).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){p.info("SocketService::Failed to connect to socket-edge",{country:E.location.country}),R.emit(M.SOCKET_SERVICE_FAILED),o(this,xe,Fe).updateSocketConnectionState("failed")}))}},er=new WeakMap,Le=new WeakMap,xe=new WeakSet,Fe=function(){return o(this,vi).getValue("connectionHandler")},un=new WeakMap,vi=new WeakMap,bc=new WeakSet,fu=function(t){let e=vS.getSocketEdgeDomain(o(this,vi).getValue("baseURI"));typeof Md(o(this,vi),"socket_server_base")=="string"&&(e=Md(o(this,vi),"socket_server_base"));const n=`wss://${e}`,i=new URL(`${n}/ws`),r=this.peerId,s=J(U({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},r!==t&&{oldPeerID:r}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>Ad[a]).join(" "),joinWithDetails:!0,useCfWorker:!0});return Object.entries(s).forEach(([a,c])=>{i.searchParams.append(a,c.toString())}),i.href},_c=new WeakSet,vu=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},sf);let Ko=vS;Sl([E.trace("SocketService.connect")],Ko.prototype,"connect",1);Sl([E.trace("SocketService.disconnect")],Ko.prototype,"disconnect",1);Sl([E.trace("SocketService.sendMessagePromise")],Ko.prototype,"sendMessagePromise",1);Sl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Ko.prototype,"sendMessagePromiseWithTimeout",1);const Er=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const n=JR.fromBinary(t),i=n.meetings.map(r=>{var s;return{id:r.id,title:r.title,participants:(s=r.participants)!=null?s:[]}});return{parentMeeting:{id:n.parentMeeting.id,title:n.parentMeeting.title,participants:(e=n.parentMeeting.participants)!=null?e:[]},meetings:i}}static handleTransferPeerRaw({payload:t}){const e=yM.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=ay.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return ug.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return cM.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield Er.socketService.sendMessagePromise(j.getConnectedRoomsDump);return Er.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield Er.socketService.sendMessagePromise(j.createConnectedRooms,YR.toBinary({payloads:t}));return ug.fromBinary(e).payloads.map(n=>({id:n.id,title:n.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(i=>({id:i})),n=yield Er.socketService.sendMessagePromise(j.deleteConnectedRooms,aM.toBinary({payloads:e}));return Er.handleConnectedRoomsDeletedRaw(n)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield Er.socketService.sendMessagePromise(j.movePeers,mM.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}};let Ne=Er;g(Ne,"socketService"),g(Ne,"currentMeetingId");var PL=Object.defineProperty,RL=Object.getOwnPropertyDescriptor,El=(t,e,n,i)=>{for(var r=i>1?void 0:i?RL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&PL(e,n,r),r};const Ts=class{constructor(t,e){g(this,"apiBase"),g(this,"selfController"),g(this,"pollController"),g(this,"chatController"),g(this,"metaController"),g(this,"storesManager"),g(this,"stageController"),g(this,"pluginController"),g(this,"internalsController"),g(this,"recordingController"),g(this,"livestreamController"),g(this,"participantController"),this.apiBase=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController}static init(t){return u(this,null,function*(){var e,n;const{peerId:i,apiBase:r,authToken:s,meetingId:a,organizationId:c,cachedUserDetails:d}=t.getAllValues();if(R.reset(),Ld.cleanup(),nS(t),Pe.isSupported()===!1)throw new I("Browser not supported","0010",!0);const l=AD(t,{authToken:s,baseURL:r,cachedUserDetails:d});l.setRoomName(a),l.setRoomUUID(a),l.setOrganizationId(c),l.setHeader("dyte-tracing-id",i),t.setValue("apiClient",l);const h=new pO;t.setValue("connectionHandler",h);const m=Ts.createSocketService(t),y=m.connect(),S=l.getUserDetails(),b=l.getPlugins();let D=it.HIVE,C,V="";try{yield Ts.setupFlagsmith(t)}catch(X){p.error("Failed to setup flagsmith",{error:X})}try{yield y}catch(X){p.error("[Controller]: Failed to connect to socket server:",{error:X})}try{({sfu:D,meetingTitle:V}=yield l.getRoomNodeData()),C=yield S,p.info(`SFU ${D} is being used.`),t.setValue("presetName",C.preset.name),t.setValue("roomNodeOptions",{sfu:D})}catch(X){p.error("Failed to get room metadata",{error:X})}const L=QO.init(C.preset,!t.getValue("modules").theme),q=Ts.setupControllers(m,t,C,b,V,L);nO(L)&&((e=Ts.createRoomNodeClient(t,m).partialJoinRoom(C.participant.name,a,void 0))==null||e.catch(X=>{p.error("[Controller]: Failed to queue partial media room promise:",{error:X})})),E.location.country=(n=l.ipInfo)==null?void 0:n.country;const{controllers:w}=yield q;return eC(),new Ts(r,w)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:n,baseURI:i,overrides:r,meetingId:s,organizationId:a}=t.getAllValues(),c=XI(s),d=J(U({entity:Uu.PEER,clientId:a,isAnonUser:!a,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:c,roomName:s},Pe.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const l=(e=r==null?void 0:r.whitelabelled_flags_endpoint)==null||e?Rs({servicePrefix:"flags",baseURI:i}):"edge.api.flagsmith.com";yield Z.identify(`${Uu.PEER}_${n}`,JSON.parse(JSON.stringify(d)),!1,5e3,l,p),p.info("flagsmith::allFlags",{flags:JSON.stringify(Z.getAllFlags())},!0)}catch{p.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,n,i,r,s){return u(this,null,function*(){var a,c,d;const l=e.getValue("modules"),{preset:h,participant:m}=n,y=e.getValue("defaults"),{sfu:S}=e.getValue("roomNodeOptions"),{viewType:b,mediaConstraints:{audio:D}}=s;e.setValue("viewType",b),e.setValue("defaults",U({mediaConfiguration:{audio:{enableHighBitrate:(a=D.enableHighBitrate)!=null?a:!1,enableStereo:(c=D.enableStereo)!=null?c:!1}}},y));const C=yN.init(e,b,h.permissions);e.setValue("maxPreferredStreams",Pe.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let V,L,q,w,X,ae,Ee,ce;const Re=new iL(t);Ne.socketService=t;const vt=new vl(t),A=new an(t),k=new aL(t),_=Ld.create(t,e),W=new oL(t),we=new nL(t),ze=new Or(t),B=yield Ji.init(e,_,m,C,s),P=yield vy.init(e,B.self,_,Re,r);if(l.participant&&(ce=new li(e,B.self,_,S)),(d=l.e2ee)!=null&&d.enabled&&l.e2ee.manager.init(p,R),l.chat&&(L=yield ii.init(e,A,ze,B.self,ce.participants)),l.internals&&(X=yield gp.init()),l.livestream&&s.viewType===Rt.Livestream&&Z.hasFeature(re.LIVESTREAM)&&(Ee=new Iy(B.self,we)),s.viewType!==Rt.Chat){if(l.poll&&(V=yield py.init(e,B.self,vt)),l.recording&&(ae=new Ty(e,B.self,_)),l.stage&&(q=new yy(e,k,_,B.self,ce.participants)),l.plugin){if(!ce)throw new I("The plugin module cannot be initialized without the `participant` module","0102");const jn=yield i;w=yield qo.init(e,jn,W,A,L==null?void 0:L.chat,B.self,ce.participants,r)}if(l.pip){const jn=yield iC._init(e,B.self);e.setValue("pip",jn)}}const Ye={storesManager:new sN(e,W),pollController:V,selfController:B,metaController:P,chatController:L,stageController:q,pluginController:w,recordingController:ae,internalsController:X,livestreamController:Ee,participantController:ce};return{theme:s,permissions:C,controllers:Ye}})}static createRoomNodeClient(t,e){const{peerId:n,roomNodeOptions:i}=t.getAllValues(),{sfu:r}=i;return tS(t,r,{socket:e,peerId:n})}static createSocketService(t){const{peerId:e,meetingId:n,authToken:i}=t.getAllValues(),r=["PING"];return new Ko(t,{peerId:e,meetingId:n,authToken:i,capabilities:r})}};let zo=Ts;El([E.trace("Controller.init")],zo,"init",1);El([E.trace("setupFlagsmith")],zo,"setupFlagsmith",1);El([E.trace("Controller.createRoomNodeClient")],zo,"createRoomNodeClient",1);El([E.trace("Controller.createSocketService")],zo,"createSocketService",1);var ML=Object.defineProperty,AL=Object.getOwnPropertyDescriptor,DL=(t,e,n,i)=>{for(var r=i>1?void 0:i?AL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&ML(e,n,r),r},pd,jh;class yS extends zt{constructor(e,n){super(),f(this,pd,void 0),g(this,"meetings",[]),g(this,"parentMeeting",null),f(this,jh,void 0),v(this,jh,e),v(this,pd,n.self)}get supportsConnectedMeetings(){return o(this,pd).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Ne.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
21
21
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield Ne.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Ne.createConnectedRooms(e)).map(n=>({id:n.id,title:n.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Ne.updateConnectedRooms(e.map(n=>({meetingId:n.id,title:n.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=this.meetings.map(i=>e.includes(i.id)&&i.participants.length!==0?this.moveParticipants(i.id,this.parentMeeting.id,i.participants.map(r=>r.id)):Promise.resolve());return yield Promise.all(n),yield Ne.disableConnectedRooms(e)})}moveParticipants(e,n,i){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:n,participants:i.map(s=>({id:s}))});return r.success&&this.moveSuccessHandler(e,n,i),r})}moveParticipantsWithCustomPreset(e,n,i){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:n,participants:i});return r.success&&this.moveSuccessHandler(e,n,i.map(s=>s.id)),r})}moveSuccessHandler(e,n,i){const r=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>r.set(s.id,s)),n===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(s=>r.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!i.includes(s.id))),this.meetings=this.meetings.map(s=>{if(n===s.id){const a=s.participants.concat(i.map(c=>r.get(c)));return J(U({},s),{participants:a})}if(e===s.id){const a=s.participants.filter(c=>!i.includes(c.id));return J(U({},s),{participants:a})}return s})}}pd=new WeakMap,jh=new WeakMap;DL([Ft({maxInvocations:60,period:60})],yS.prototype,"getConnectedMeetings",1);var OL=Object.defineProperty,NL=Object.getOwnPropertyDescriptor,Cp=(t,e,n,i)=>{for(var r=i>1?void 0:i?NL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&OL(e,n,r),r},Oa,hn,yu,Su;const Mi=(yu=class{constructor(t,e,n){g(this,"connectedMeetings"),f(this,Oa,void 0),f(this,hn,void 0),f(this,Su,void 0),v(this,Su,t),v(this,Oa,n),this.connectedMeetings=new yS(t,e),this.setCurrentMeeting(e)}static init(t,e,n){return Mi.instance||(Mi.instance=new Mi(t,e,n)),Mi.instance.connectedMeetings.supportsConnectedMeetings&&(Mi.instance.setupEvents(),e.self.once("roomJoined",()=>Mi.instance.getConnectedMeetings())),Mi.instance}setCurrentMeeting(t){v(this,hn,t),Ne.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Ne.socketService&&(Ne.socketService.on(j.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Ne.socketService.on(j.transferPeer,this.handleTransferPeer.bind(this)),Ne.socketService.on(j.movedPeer,this.handleMovedPeer.bind(this)),Ne.socketService.on(j.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Ne.socketService.on(j.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Ne.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:n}){var i,r,s,a;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
22
- Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);p.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",n);const c={video:o(this,hn).self.videoEnabled,audio:o(this,hn).self.audioEnabled};try{o(this,hn).self.cleanupEvents(),yield o(this,hn).leave("connected-meeting")}catch(l){p.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(r=(i=o(this,hn))==null?void 0:i.meta)==null?void 0:r.meetingId}`,{error:l})}Ne.socketService=void 0,p.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${n}`);const d=yield SS.init(J(U({},o(this,Oa)),{cachedUserDetails:null,defaults:J(U(U({},o(this,Oa).defaults),c),{mediaHandler:o(this,hn).self}),authToken:e}));p.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:l}=o(this,hn).self;d.self.setName(o(this,hn).self.name),yield d.join(),l&&d.self.hide()}catch(l){p.error("ConnectedMeetingsController.joinRoom",{error:l})}return p.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(a=d==null?void 0:d.meta)==null?void 0:a.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),this.setCurrentMeeting(d),d})}handleConnectedRoomsDump(t){const e=Ne.handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(n=>({id:n.id,title:n.title,participants:n.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return Ne.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Ne.handleConnectedRoomsUpdatedRaw(t),n=new Map;this.connectedMeetings.meetings.forEach(i=>{n.set(i.id,i)}),e.forEach(i=>{n.has(i.id)?n.get(i.id).title=i.title:n.set(i.id,J(U({},i),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(n.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Ne.handleConnectedRoomsDeletedRaw(t).map(n=>n.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(n=>!e.includes(n.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Oa=new WeakMap,hn=new WeakMap,Su=new WeakMap,g(yu,"instance"),yu);let Tl=Mi;Cp([E.trace("ConnectedMeetingsController.getConnectedMeetings")],Tl.prototype,"getConnectedMeetings",1);Cp([E.trace("ConnectedMeetingsController.setupEvents")],Tl.prototype,"setupEvents",1);Cp([E.trace("ConnectedMeetingsController.switchMeeting")],Tl.prototype,"switchMeeting",1);class LL{constructor(){g(this,"battery"),g(this,"init",()=>u(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){p.error("Error getting battery",e)}})),g(this,"updateChargeInfo",()=>{var e;p.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),g(this,"updateLevelInfo",()=>{if(!this.battery){p.log("Battery level: Not known");return}p.log(`Battery level: ${this.battery.level*100}%`)}),g(this,"cleanup",()=>{var e,n;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(n=this.battery)==null||n.removeEventListener("levelchange",this.updateLevelInfo))})}}const af=new LL;function xL(t,e){t.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c \u2014 not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.dyte.io/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:n,orgId:i,participantId:r}=JSON.parse(atob(t.split(".")[1]));if(!n)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const a=`https://api.${s}`;return{meetingId:n,orgId:i,participantId:r,baseURI:s,apiBase:a}}catch(n){throw p.error("constants::decodeAuthToken",{error:n,debuggingHint:`Unable to decode auth token: ${t}`},!0),new I("Invalid auth token","0004")}}var VL=Object.defineProperty,UL=Object.getOwnPropertyDescriptor,kl=(t,e,n,i)=>{for(var r=i>1?void 0:i?UL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&VL(e,n,r),r},ot,wc,Ic,Eu,of,cf;let ji=(cf=class{constructor(t,e){f(this,Eu),f(this,ot,void 0),f(this,wc,void 0),f(this,Ic,void 0),v(this,Ic,t),v(this,ot,e)}static init(t){return u(this,null,function*(){var e,n,i,r,s,a;zI(),Pe.init();const c=(e=t.cachedUserDetails.peerId)!=null?e:Fs();af.init();const{authToken:d,baseURI:l}=t,h=xL(d,l),{meetingId:m}=h,y=Qd(h,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const S=ji.setupContext(c,t,m,y);E.meetingMetadata.roomName=m,E.meetingMetadata.userId=y.participantId,E.meetingMetadata.organizationId=y.orgId,E.init(S,(i=(n=t.modules)==null?void 0:n.tracing)!=null?i:!0),p.info("DyteClient::init::options",{dyteClientInitOptions:J(U({},t),{authToken:`${(r=t.authToken)==null?void 0:r.slice(0,10)}...
23
- ${(s=t.authToken)==null?void 0:s.slice(-10)}`})});const b=yield zo.init(S),D=new ji(S,b);return H(a=D,Eu,of).call(a,t),D})}static setupContext(t,e,n,i){var r;const s=Rr.createContext(t,e),a=U(U({},HI),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",a),s.setValue("sdkName","web-core"),s.setValue("meetingId",n),s.setValue("apiBase",i.apiBase),s.setValue("baseURI",i.baseURI),s.setValue("userId",i.participantId),s.setValue("organizationId",i.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(r=e.overrides)!=null?r:{}),s.setValue("env",qI({baseURI:i.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",kn(e.cachedUserDetails)),s.setValue("sdkVersion","2.5.0-staging.70"),s}join(){return u(this,null,function*(){const{selfController:t}=o(this,ot);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){af.cleanup();const{selfController:e}=o(this,ot);return e.leaveRoom(t)})}get participants(){var t;return(t=o(this,ot).participantController)==null?void 0:t.participants}get self(){var t;return(t=o(this,ot).selfController)==null?void 0:t.self}get meta(){var t;return(t=o(this,ot).metaController)==null?void 0:t.meta}get ai(){var t;return(t=o(this,ot).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=o(this,ot).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=o(this,ot).chatController)==null?void 0:t.chat}get polls(){var t;return(t=o(this,ot).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=o(this,wc))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=o(this,ot).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=o(this,ot).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=o(this,ot).stageController)==null?void 0:t.stage}get stores(){return o(this,ot).storesManager}get __internals__(){var t;return(t=o(this,ot).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},ot=new WeakMap,wc=new WeakMap,Ic=new WeakMap,Eu=new WeakSet,of=function(t){v(this,wc,Tl.init(o(this,Ic),this,t))},cf);kl([gt("0002"),Gi.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],ji.prototype,"join",1);kl([gt("0003")],ji.prototype,"leave",1);kl([gt("0001"),Gi.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],ji,"init",1);ji=kl([gt("0000")],ji);const SS=ji;var FL=Object.defineProperty,BL=(t,e,n)=>e in t?FL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Tu=(t,e,n)=>(BL(t,typeof e!="symbol"?e+"":e,n),n);class WL{constructor(e){Tu(this,"meeting"),Tu(this,"l"),Tu(this,"onUpdate",()=>{this.l.forEach(w=>{w()})});var n,i,r,s,a,c,d,l,h,m,y,S,b,D,C,V,L,q;this.meeting=e,this.l=new Set,(n=this.meeting.self)==null||n.addListener("*",this.onUpdate),(i=this.meeting.meta)==null||i.addListener("*",this.onUpdate),(r=this.meeting.participants)==null||r.addListener("*",this.onUpdate),(a=(s=this.meeting.participants)==null?void 0:s.joined)==null||a.addListener("*",this.onUpdate),(d=(c=this.meeting.participants)==null?void 0:c.active)==null||d.addListener("*",this.onUpdate),(h=(l=this.meeting.participants)==null?void 0:l.waitlisted)==null||h.addListener("*",this.onUpdate),(m=this.meeting.stage)==null||m.addListener("*",this.onUpdate),(y=this.meeting.livestream)==null||y.addListener("*",this.onUpdate),(S=this.meeting.chat)==null||S.addListener("*",this.onUpdate),(b=this.meeting.plugins)==null||b.all.addListener("*",this.onUpdate),(D=this.meeting.recording)==null||D.addListener("*",this.onUpdate),(C=this.meeting.connectedMeetings)==null||C.addListener("*",this.onUpdate),(V=this.meeting.spotlight)==null||V.addListener("*",this.onUpdate),(L=this.meeting.remote)==null||L.addListener("*",this.onUpdate),(q=this.meeting.polls)==null||q.addListener("*",this.onUpdate)}clean(){var e,n,i,r,s,a,c,d,l,h,m,y,S,b,D,C,V,L;(e=this.meeting.self)==null||e.removeListener("*",this.onUpdate),(n=this.meeting.meta)==null||n.removeListener("*",this.onUpdate),(i=this.meeting.participants)==null||i.removeListener("*",this.onUpdate),(s=(r=this.meeting.participants)==null?void 0:r.joined)==null||s.removeListener("*",this.onUpdate),(c=(a=this.meeting.participants)==null?void 0:a.active)==null||c.removeListener("*",this.onUpdate),(l=(d=this.meeting.participants)==null?void 0:d.waitlisted)==null||l.removeListener("*",this.onUpdate),(h=this.meeting.stage)==null||h.removeListener("*",this.onUpdate),(m=this.meeting.livestream)==null||m.removeListener("*",this.onUpdate),(y=this.meeting.chat)==null||y.removeListener("*",this.onUpdate),(S=this.meeting.plugins)==null||S.all.removeListener("*",this.onUpdate),(b=this.meeting.recording)==null||b.removeListener("*",this.onUpdate),(D=this.meeting.connectedMeetings)==null||D.removeListener("*",this.onUpdate),(C=this.meeting.spotlight)==null||C.removeListener("*",this.onUpdate),(V=this.meeting.remote)==null||V.removeListener("*",this.onUpdate),(L=this.meeting.polls)==null||L.removeListener("*",this.onUpdate)}addListener(e){this.l.add(e)}removeListener(e){this.l.delete(e)}}const Pp=Ct.createContext({meeting:void 0,updates:void 0});function jL({value:t,children:e,fallback:n}){const[i,r]=Ct.useState(),s=Ct.useRef();return Ct.useEffect(()=>(t&&r(new WL(t)),()=>{var a;(a=s.current)==null||a.clean()}),[t]),TS.default.createElement(Pp.Provider,{value:{meeting:t,updates:i}},t?e:n)}const HL=()=>{const{meeting:t}=Ct.useContext(Pp);if(!t)throw new Error("useDyteMeeting must be used within the DyteProvider");return{meeting:t}},qL=t=>{const e=Ct.useRef(!1),[n,i]=Ct.useState(),r=t==null?void 0:t.resetOnLeave,s=Ct.useCallback(async a=>{if(!e.current)return e.current=!0,SS.init(a).then(c=>(i(c),c)).finally(()=>{e.current=!1})},[]);return Ct.useEffect(()=>{if(!n||!r)return()=>{};const a=({state:c})=>{c!=="connected-meeting"&&c!=="disconnected"&&i(void 0)};return n.self.on("roomLeft",a),()=>{n.self.removeListener("roomLeft",a)}},[n]),Ct.useEffect(()=>{if(!n||!n.connectedMeetings)return()=>{};const a=c=>{i(void 0),setTimeout(()=>{i(c)},100)};return n.connectedMeetings.on("meetingChanged",a),()=>{n.connectedMeetings.removeListener("meetingChanged",a)}},[n]),[n,s]},GL=(t,e)=>!!(t!==e||Array.isArray(t)&&Array.isArray(e)&&t.length!==e.length),JL=t=>{const{meeting:e,updates:n}=Ct.useContext(Pp);if(!e)throw new Error("useDyteSelector must be used within the DyteProvider");const i=Ct.useRef(t(e)),[,r]=Ct.useReducer(s=>s+1,0);return Ct.useEffect(()=>{const s=e&&t(e),a=()=>{const c=e&&t(e);GL(i.current,c)&&(i.current=c,r())};return s&&typeof s=="object"&&"addListener"in s?(s.addListener("*",r),()=>{s.removeListener("*",r)}):(n==null||n.addListener(a),()=>{n==null||n.removeListener(a)})},[e,n]),i.current},$L=t=>qL(t),KL=jL,zL=HL,YL=JL,QL=()=>zL(),XL=t=>YL(t);exports.RealtimeKitProvider=KL;exports.useRTKSelector=XL;exports.useRealtimeKitClient=$L;exports.useRealtimeKitMeeting=QL;
22
+ Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);p.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",n);const c={video:o(this,hn).self.videoEnabled,audio:o(this,hn).self.audioEnabled};try{o(this,hn).self.cleanupEvents(),yield o(this,hn).leave("connected-meeting")}catch(l){p.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(r=(i=o(this,hn))==null?void 0:i.meta)==null?void 0:r.meetingId}`,{error:l})}Ne.socketService=void 0,p.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${n}`);const d=yield SS.init(J(U({},o(this,Oa)),{cachedUserDetails:null,defaults:J(U(U({},o(this,Oa).defaults),c),{mediaHandler:o(this,hn).self}),authToken:e}));p.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:l}=o(this,hn).self;d.self.setName(o(this,hn).self.name),yield d.join(),l&&d.self.hide()}catch(l){p.error("ConnectedMeetingsController.joinRoom",{error:l})}return p.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(a=d==null?void 0:d.meta)==null?void 0:a.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),this.setCurrentMeeting(d),d})}handleConnectedRoomsDump(t){const e=Ne.handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(n=>({id:n.id,title:n.title,participants:n.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return Ne.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Ne.handleConnectedRoomsUpdatedRaw(t),n=new Map;this.connectedMeetings.meetings.forEach(i=>{n.set(i.id,i)}),e.forEach(i=>{n.has(i.id)?n.get(i.id).title=i.title:n.set(i.id,J(U({},i),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(n.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Ne.handleConnectedRoomsDeletedRaw(t).map(n=>n.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(n=>!e.includes(n.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Oa=new WeakMap,hn=new WeakMap,Su=new WeakMap,g(yu,"instance"),yu);let Tl=Mi;Cp([E.trace("ConnectedMeetingsController.getConnectedMeetings")],Tl.prototype,"getConnectedMeetings",1);Cp([E.trace("ConnectedMeetingsController.setupEvents")],Tl.prototype,"setupEvents",1);Cp([E.trace("ConnectedMeetingsController.switchMeeting")],Tl.prototype,"switchMeeting",1);class LL{constructor(){g(this,"battery"),g(this,"init",()=>u(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){p.error("Error getting battery",e)}})),g(this,"updateChargeInfo",()=>{var e;p.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),g(this,"updateLevelInfo",()=>{if(!this.battery){p.log("Battery level: Not known");return}p.log(`Battery level: ${this.battery.level*100}%`)}),g(this,"cleanup",()=>{var e,n;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(n=this.battery)==null||n.removeEventListener("levelchange",this.updateLevelInfo))})}}const af=new LL;function xL(t,e){t.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c \u2014 not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.dyte.io/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:n,orgId:i,participantId:r}=JSON.parse(atob(t.split(".")[1]));if(!n)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const a=`https://api.${s}`;return{meetingId:n,orgId:i,participantId:r,baseURI:s,apiBase:a}}catch(n){throw p.error("constants::decodeAuthToken",{error:n,debuggingHint:`Unable to decode auth token: ${t}`},!0),new I("Invalid auth token","0004")}}var VL=Object.defineProperty,UL=Object.getOwnPropertyDescriptor,kl=(t,e,n,i)=>{for(var r=i>1?void 0:i?UL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(r=(i?a(e,n,r):a(r))||r);return i&&r&&VL(e,n,r),r},ot,wc,Ic,Eu,of,cf;let ji=(cf=class{constructor(t,e){f(this,Eu),f(this,ot,void 0),f(this,wc,void 0),f(this,Ic,void 0),v(this,Ic,t),v(this,ot,e)}static init(t){return u(this,null,function*(){var e,n,i,r,s,a,c;zI(),Pe.init();const d=(n=(e=t==null?void 0:t.cachedUserDetails)==null?void 0:e.peerId)!=null?n:Fs();af.init();const{authToken:l,baseURI:h}=t,m=xL(l,h),{meetingId:y}=m,S=Qd(m,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const b=ji.setupContext(d,t,y,S);E.meetingMetadata.roomName=y,E.meetingMetadata.userId=S.participantId,E.meetingMetadata.organizationId=S.orgId,E.init(b,(r=(i=t.modules)==null?void 0:i.tracing)!=null?r:!0),p.info("DyteClient::init::options",{dyteClientInitOptions:J(U({},t),{authToken:`${(s=t.authToken)==null?void 0:s.slice(0,10)}...
23
+ ${(a=t.authToken)==null?void 0:a.slice(-10)}`})});const D=yield zo.init(b),C=new ji(b,D);return H(c=C,Eu,of).call(c,t),C})}static setupContext(t,e,n,i){var r;const s=Rr.createContext(t,e),a=U(U({},HI),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",a),s.setValue("sdkName","web-core"),s.setValue("meetingId",n),s.setValue("apiBase",i.apiBase),s.setValue("baseURI",i.baseURI),s.setValue("userId",i.participantId),s.setValue("organizationId",i.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(r=e.overrides)!=null?r:{}),s.setValue("env",qI({baseURI:i.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",kn(e.cachedUserDetails)),s.setValue("sdkVersion","2.5.0-staging.72"),s}join(){return u(this,null,function*(){const{selfController:t}=o(this,ot);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){af.cleanup();const{selfController:e}=o(this,ot);return e.leaveRoom(t)})}get participants(){var t;return(t=o(this,ot).participantController)==null?void 0:t.participants}get self(){var t;return(t=o(this,ot).selfController)==null?void 0:t.self}get meta(){var t;return(t=o(this,ot).metaController)==null?void 0:t.meta}get ai(){var t;return(t=o(this,ot).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=o(this,ot).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=o(this,ot).chatController)==null?void 0:t.chat}get polls(){var t;return(t=o(this,ot).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=o(this,wc))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=o(this,ot).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=o(this,ot).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=o(this,ot).stageController)==null?void 0:t.stage}get stores(){return o(this,ot).storesManager}get __internals__(){var t;return(t=o(this,ot).internalsController)==null?void 0:t.internals}joinRoom(){return u(this,null,function*(){return this.join()})}leaveRoom(t){return u(this,null,function*(){return this.leave(t)})}},ot=new WeakMap,wc=new WeakMap,Ic=new WeakMap,Eu=new WeakSet,of=function(t){v(this,wc,Tl.init(o(this,Ic),this,t))},cf);kl([gt("0002"),Gi.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],ji.prototype,"join",1);kl([gt("0003")],ji.prototype,"leave",1);kl([gt("0001"),Gi.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],ji,"init",1);ji=kl([gt("0000")],ji);const SS=ji;var FL=Object.defineProperty,BL=(t,e,n)=>e in t?FL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Tu=(t,e,n)=>(BL(t,typeof e!="symbol"?e+"":e,n),n);class WL{constructor(e){Tu(this,"meeting"),Tu(this,"l"),Tu(this,"onUpdate",()=>{this.l.forEach(w=>{w()})});var n,i,r,s,a,c,d,l,h,m,y,S,b,D,C,V,L,q;this.meeting=e,this.l=new Set,(n=this.meeting.self)==null||n.addListener("*",this.onUpdate),(i=this.meeting.meta)==null||i.addListener("*",this.onUpdate),(r=this.meeting.participants)==null||r.addListener("*",this.onUpdate),(a=(s=this.meeting.participants)==null?void 0:s.joined)==null||a.addListener("*",this.onUpdate),(d=(c=this.meeting.participants)==null?void 0:c.active)==null||d.addListener("*",this.onUpdate),(h=(l=this.meeting.participants)==null?void 0:l.waitlisted)==null||h.addListener("*",this.onUpdate),(m=this.meeting.stage)==null||m.addListener("*",this.onUpdate),(y=this.meeting.livestream)==null||y.addListener("*",this.onUpdate),(S=this.meeting.chat)==null||S.addListener("*",this.onUpdate),(b=this.meeting.plugins)==null||b.all.addListener("*",this.onUpdate),(D=this.meeting.recording)==null||D.addListener("*",this.onUpdate),(C=this.meeting.connectedMeetings)==null||C.addListener("*",this.onUpdate),(V=this.meeting.spotlight)==null||V.addListener("*",this.onUpdate),(L=this.meeting.remote)==null||L.addListener("*",this.onUpdate),(q=this.meeting.polls)==null||q.addListener("*",this.onUpdate)}clean(){var e,n,i,r,s,a,c,d,l,h,m,y,S,b,D,C,V,L;(e=this.meeting.self)==null||e.removeListener("*",this.onUpdate),(n=this.meeting.meta)==null||n.removeListener("*",this.onUpdate),(i=this.meeting.participants)==null||i.removeListener("*",this.onUpdate),(s=(r=this.meeting.participants)==null?void 0:r.joined)==null||s.removeListener("*",this.onUpdate),(c=(a=this.meeting.participants)==null?void 0:a.active)==null||c.removeListener("*",this.onUpdate),(l=(d=this.meeting.participants)==null?void 0:d.waitlisted)==null||l.removeListener("*",this.onUpdate),(h=this.meeting.stage)==null||h.removeListener("*",this.onUpdate),(m=this.meeting.livestream)==null||m.removeListener("*",this.onUpdate),(y=this.meeting.chat)==null||y.removeListener("*",this.onUpdate),(S=this.meeting.plugins)==null||S.all.removeListener("*",this.onUpdate),(b=this.meeting.recording)==null||b.removeListener("*",this.onUpdate),(D=this.meeting.connectedMeetings)==null||D.removeListener("*",this.onUpdate),(C=this.meeting.spotlight)==null||C.removeListener("*",this.onUpdate),(V=this.meeting.remote)==null||V.removeListener("*",this.onUpdate),(L=this.meeting.polls)==null||L.removeListener("*",this.onUpdate)}addListener(e){this.l.add(e)}removeListener(e){this.l.delete(e)}}const Pp=Ct.createContext({meeting:void 0,updates:void 0});function jL({value:t,children:e,fallback:n}){const[i,r]=Ct.useState(),s=Ct.useRef();return Ct.useEffect(()=>(t&&r(new WL(t)),()=>{var a;(a=s.current)==null||a.clean()}),[t]),TS.default.createElement(Pp.Provider,{value:{meeting:t,updates:i}},t?e:n)}const HL=()=>{const{meeting:t}=Ct.useContext(Pp);if(!t)throw new Error("useDyteMeeting must be used within the DyteProvider");return{meeting:t}},qL=t=>{const e=Ct.useRef(!1),[n,i]=Ct.useState(),r=t==null?void 0:t.resetOnLeave,s=Ct.useCallback(async a=>{if(!e.current)return e.current=!0,SS.init(a).then(c=>(i(c),c)).finally(()=>{e.current=!1})},[]);return Ct.useEffect(()=>{if(!n||!r)return()=>{};const a=({state:c})=>{c!=="connected-meeting"&&c!=="disconnected"&&i(void 0)};return n.self.on("roomLeft",a),()=>{n.self.removeListener("roomLeft",a)}},[n]),Ct.useEffect(()=>{if(!n||!n.connectedMeetings)return()=>{};const a=c=>{i(void 0),setTimeout(()=>{i(c)},100)};return n.connectedMeetings.on("meetingChanged",a),()=>{n.connectedMeetings.removeListener("meetingChanged",a)}},[n]),[n,s]},GL=(t,e)=>!!(t!==e||Array.isArray(t)&&Array.isArray(e)&&t.length!==e.length),JL=t=>{const{meeting:e,updates:n}=Ct.useContext(Pp);if(!e)throw new Error("useDyteSelector must be used within the DyteProvider");const i=Ct.useRef(t(e)),[,r]=Ct.useReducer(s=>s+1,0);return Ct.useEffect(()=>{const s=e&&t(e),a=()=>{const c=e&&t(e);GL(i.current,c)&&(i.current=c,r())};return s&&typeof s=="object"&&"addListener"in s?(s.addListener("*",r),()=>{s.removeListener("*",r)}):(n==null||n.addListener(a),()=>{n==null||n.removeListener(a)})},[e,n]),i.current},$L=t=>qL(t),KL=jL,zL=HL,YL=JL,QL=()=>zL(),XL=t=>YL(t);exports.RealtimeKitProvider=KL;exports.useRTKSelector=XL;exports.useRealtimeKitClient=$L;exports.useRealtimeKitMeeting=QL;