@cloudflare/realtimekit-react 1.2.0-staging.13 → 1.2.0-staging.15

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/index.cjs.js CHANGED
@@ -14,10 +14,10 @@ ${this.message}`;try{let s=n&&!!i;r&&r.endsWith("00")&&i&&(s=!0),s&&i.error("Dyt
14
14
 
15
15
  ${t}`}const ta={maxInvocations:5,period:1};function Bt(t,e){return function(r,i,n){const s=n.value;let o=0,c=Date.now();return n.value=function(...d){const l=Date.now(),h=e?this[e]:t;if(l-c>h.period*1e3&&(c=l,o=0),o>=h.maxInvocations)throw new I(`Method rate limit ${h.maxInvocations} invocations/${h.period}sec exceeded`,"0013");return o+=1,s.apply(this,d)},n}}var fO=Object.defineProperty,vO=Object.getOwnPropertyDescriptor,vt=(t,e,r,i)=>{for(var n=i>1?void 0:i?vO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&fO(e,r,n),n};const yO=["text","image","file","custom","poll"],zc={maxInvocations:180,period:60};var te,Kn,ze,zn,Yn,tu,og,Ec,ru,cg;let st=(cg=class extends Zt{constructor(t,e,r,i,n){const s=t.getValue("logger");super(s),g(this,tu),g(this,Ec),m(this,"messages"),m(this,"channels",[]),g(this,te,void 0),g(this,Kn,void 0),g(this,ze,void 0),g(this,zn,void 0),g(this,Yn,void 0),m(this,"maxTextLimit",2e3),f(this,Yn,t),f(this,ze,e),f(this,zn,r),f(this,te,i),f(this,Kn,n),this.messages=[]}get telemetry(){return a(this,Yn).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}sendMessageInternal(t,e,r){return u(this,arguments,function*(i,n,s,o={}){switch(i.type){case"text":{const c=o.replyTo&&o.replyTo.type==="text"?gO(i.message,o.replyTo.message):i.message;yield this.sendTextMessageInternal(c,n,s);break}case"image":yield this.sendImageMessageInternal(i.image,n,s);break;case"file":yield this.sendFileMessageInternal(i.file,n,s);break;default:this.logger.error("sendMessage::message_type_not_supported",{dyteChat:{messageType:i.type}});break}})}sendTextMessageInternal(t,e,r){return u(this,null,function*(){var i,n,s,o,c,d;if(t.length>this.maxTextLimit)throw new I("Max character limit breached","0503");if(e&&e.length>0){if(!((i=a(this,te).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,te).permissions)!=null&&n.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new I("Could not send message to private chat.","0501")}else if(!((o=(s=a(this,te).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,te).permissions)==null?void 0:c.chatPublic)!=null&&d.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new I("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new I("Message can not be empty.","0502");if(r){a(this,ze).sendMessageToChannel(t,_t.TEXT,r);return}let l=[];e&&e.length>0&&(e.push(a(this,te).id),l=a(this,Kn).joined.toArray().filter(h=>e.includes(h.id)).map(h=>h.userId),l.push(a(this,te).userId)),a(this,ze).sendMessage(t,_t.TEXT,e)})}sendImageMessageInternal(t,e,r){return u(this,null,function*(){var i,n,s,o,c,d;if(e&&e.length>0){if(!((i=a(this,te).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,te).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((o=(s=a(this,te).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,te).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){this.logger.error("sendImageMessage::permission_denied");return}if(!t){this.logger.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){this.logger.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:t.type}});return}try{const l=pt(),{getLocation:h,putLocation:p}=yield l.getPresignedUrls(t.name,a(this,te).config.viewType);if(yield l.uploadFile(t,p),r){a(this,ze).sendMessageToChannel(h,_t.IMAGE,r);return}let v=[];e&&e.length>0&&(e.push(a(this,te).id),v=a(this,Kn).joined.toArray().filter(S=>e.includes(S.id)).map(S=>S.userId),v.push(a(this,te).userId)),a(this,ze).sendMessage(h,_t.IMAGE,e)}catch{throw new I("Error sending image message.","0500",this.logger)}})}sendFileMessageInternal(t,e,r){return u(this,null,function*(){var i,n,s,o,c,d;if(e&&e.length>0){if(!((i=a(this,te).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,te).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(s=a(this,te).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,te).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!t){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const l=pt(),{getLocation:h,putLocation:p}=yield l.getPresignedUrls(t.name,a(this,te).config.viewType);if(yield l.uploadFile(t,p),r){a(this,ze).sendMessageToChannel(JSON.stringify({link:h,name:t.name,size:"size"in t?t.size:0}),_t.FILE,r);return}let v=[];e&&e.length>0&&(e.push(a(this,te).id),v=a(this,Kn).joined.toArray().filter(T=>e.includes(T.id)).map(T=>T.userId),v.push(a(this,te).userId));const S=JSON.stringify({link:h,name:t.name,size:"size"in t?t.size:0});a(this,ze).sendMessage(S,_t.FILE,e)}catch{throw new I("Error sending file message.","0500",this.logger)}})}get rateLimits(){return zc}updateRateLimits(t,e){zc.maxInvocations=t,zc.period=e}sendTextMessage(t,e){return u(this,null,function*(){return this.sendTextMessageInternal(t,e)})}sendCustomMessage(t,e){return u(this,null,function*(){var r,i,n,s,o,c,d,l,h,p,v,S,T,C,b;if(e&&e.length>0){if(!((r=a(this,te).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,te).permissions)!=null&&i.chatPrivate.files)||!((n=a(this,te).permissions)!=null&&n.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((o=(s=a(this,te).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,te).permissions)==null?void 0:c.chatPublic)!=null&&d.files)||!((h=(l=a(this,te).permissions)==null?void 0:l.chatPublic)!=null&&h.text)){this.logger.error("sendCustomMessage::permission_denied");return}const R=B=>u(this,null,function*(){try{if(typeof B=="string")return{link:B};const w=pt(),{getLocation:ee,putLocation:re}=yield w.getPresignedUrls(B.name,a(this,te).config.viewType);return yield w.uploadFile(B,re),{link:ee,type:B.type,name:B.name,size:B.size}}catch{throw new I("Error sending image message.","0500",this.logger)}}),j=q(V({},t),{files:yield Promise.all((v=(p=t.files)!=null?p:[])==null?void 0:v.map(B=>u(this,null,function*(){return R(B)}))),images:yield Promise.all((T=(S=t.images)!=null?S:[])==null?void 0:T.map(B=>u(this,null,function*(){return R(B)}))),videos:yield Promise.all((b=(C=t.videos)!=null?C:[])==null?void 0:b.map(B=>u(this,null,function*(){return R(B)})))});a(this,ze).sendMessage(JSON.stringify(j),_t.CUSTOM,e)})}sendImageMessage(t,e){return u(this,null,function*(){return this.sendImageMessageInternal(t,e)})}sendFileMessage(t,e){return u(this,null,function*(){return this.sendFileMessageInternal(t,e)})}sendMessage(t,e){return u(this,null,function*(){return this.sendMessageInternal(t,e)})}editTextMessage(t,e,r){return u(this,null,function*(){var i,n,s,o,c,d;if(((n=(i=a(this,te).permissions)==null?void 0:i.chatMessage)==null?void 0:n.canEdit)==="NONE")throw new I("Not permitted to edit messages","0501");if(!((o=(s=a(this,te).permissions)==null?void 0:s.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,te).permissions)==null?void 0:c.chatPublic)!=null&&d.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}a(this,ze).editMessage(t,e,_t.TEXT,r)})}editImageMessage(t,e,r){return u(this,null,function*(){var i,n,s,o;if(!((n=(i=a(this,te).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((o=(s=a(this,te).permissions)==null?void 0:s.chatPublic)!=null&&o.files)){this.logger.error("editImageMessage::permission_denied");return}if(!e){this.logger.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){this.logger.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:e.type}});return}try{const c=pt(),{getLocation:d,putLocation:l}=yield c.getPresignedUrls(e.name,a(this,te).config.viewType);yield c.uploadFile(e,l),a(this,ze).editMessage(t,d,_t.IMAGE,r)}catch{throw new I("Error editing image message.","0500",this.logger)}})}editFileMessage(t,e,r){return u(this,null,function*(){var i,n,s,o;if(!((n=(i=a(this,te).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((o=(s=a(this,te).permissions)==null?void 0:s.chatPublic)!=null&&o.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!e){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=pt(),{getLocation:d,putLocation:l}=yield c.getPresignedUrls(e.name,a(this,te).config.viewType);yield c.uploadFile(e,l),a(this,ze).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),_t.FILE,r)}catch{throw new I("Error editing file message.","0500",this.logger)}})}editMessage(t,e,r){return u(this,null,function*(){switch(e.type){case"text":{this.editTextMessage(t,e.message,r);break}case"image":{this.editImageMessage(t,e.image,r);break}case"file":{this.editFileMessage(t,e.file,r);break}default:{this.logger.error("editMessage::message_type_not_supported",{dyteChat:{messageType:e.type}});break}}})}deleteMessage(t,e){return u(this,null,function*(){var r,i;if(((i=(r=a(this,te).permissions)==null?void 0:r.chatMessage)==null?void 0:i.canDelete)==="NONE")throw new I("Not permitted to delete messages","0501");a(this,ze).deleteMessage(t,e)})}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}pin(t){return u(this,null,function*(){if(!a(this,Ec,ru))throw new I("Can`t pin message without joining room","0505");if(!a(this,te).permissions.pinParticipant)throw new I("You do not have permission to pin messages.","0501");const e=this.messages.find(r=>r.id===t);if(e){a(this,ze).setPinState(e,!0);return}throw new I(`No message found with id: ${t}`,"0504")})}unpin(t){return u(this,null,function*(){if(!a(this,Ec,ru))throw new I("Can`t unpin message without joining room","0505");if(!a(this,te).permissions.pinParticipant)throw new I("You do not have permission to unpin messages.","0501");const e=this.messages.find(r=>r.id===t);if(e){a(this,ze).setPinState(e,!1);return}throw new I(`No message found with id: ${t}`,"0504")})}getMessages(t,e,r,i=0,n=void 0){return u(this,null,function*(){const s=yield a(this,ze).getChatMessagesPaginated(t,e,r,i,n);return{messages:s.messages.map(o=>hi.formatSocketPeerMessage(o)),next:s.next}})}createChannel(t,e){return u(this,arguments,function*(r,i,n={}){var s;const o=(s=a(this,te).permissions)==null?void 0:s.chatChannel;if(o){if(o.canCreate==="NONE")throw new I("Not permitted to create channels","0501");if(n.visibility==="public"&&!(o.canCreate==="PUBLIC"||o.canCreate==="ALL"))throw new I("Not permitted to create public channels","0501");if(n.visibility==="private"&&!(o.canCreate==="PRIVATE"||o.canCreate==="ALL"))throw new I("Not permitted to create private channels","0501")}if(!r||r.trim().length===0)throw new I("channel name cannot be empty.","0510");const c=[...new Set([...i,a(this,te).userId])];return yield a(this,zn).createChannel(r.trim(),c,n.displayPictureUrl,n.visibility,n.isDirectMessage)})}updateChannel(t,e){var r,i,n,s,o;const c=this.channels.find(h=>h.id===t),d=(r=a(this,te).permissions)==null?void 0:r.chatChannel;if(d){if(d.canUpdate==="NONE")throw new I("Not permitted to update channels","0501");if(c.visibility==="public"&&!(d.canUpdate==="PUBLIC"||d.canUpdate==="ALL"))throw new I("Not permitted to update public channels","0501");if(c.visibility==="private"&&!(d.canUpdate==="PRIVATE"||d.canUpdate==="ALL"))throw new I("Not permitted to update private channels","0501")}const l={memberIds:(i=e.memberIds)!=null?i:c.memberIds,displayName:(n=e.displayName)!=null?n:c.displayName,displayPictureUrl:(s=e.displayPictureUrl)!=null?s:c.displayPictureUrl,visibility:(o=e.visibility)!=null?o:c.visibility};return a(this,zn).updateChannel(t,l)}sendMessageToChannel(t,e){return u(this,arguments,function*(r,i,n={}){return this.sendMessageInternal(r,null,i,n)})}getChannelMembers(t){return u(this,null,function*(){return a(this,zn).getChannelMembers(t)})}searchMessages(t){return u(this,arguments,function*(e,r={}){if(!a(this,Yn).getValue("flagsmith").hasFeature(Z.FEAT_CHAT_SDK_SEARCH))throw new I("searchMessages is temporarily disabled!","0506");return(yield a(this,ze).searchMessages(e,r)).map(hi.formatSocketPeerMessage)})}markLastReadMessage(t,e){return u(this,null,function*(){yield a(this,ze).markLastReadMessage(t,e);const r=this.channels.find(i=>i.id===t);if(r){const i=q(V({},r),{unreadCount:0});this.channels=this.channels.map(n=>n.id===t?i:n),this.emit("channelMessageUpdate",i)}})}get pinned(){return this.messages.filter(t=>t.pinned)}},te=new WeakMap,Kn=new WeakMap,ze=new WeakMap,zn=new WeakMap,Yn=new WeakMap,tu=new WeakSet,og=function(){return a(this,Yn).getValue("connectionHandler")},Ec=new WeakSet,ru=function(){return a(this,tu,og).socketJoined===!0},cg);vt([k.trace("DyteChat.sendTextMessage"),Bt(zc)],st.prototype,"sendTextMessage",1);vt([k.trace("DyteChat.sendImageMessage"),Bt({maxInvocations:20,period:60})],st.prototype,"sendImageMessage",1);vt([k.trace("DyteChat.sendFileMessage"),Bt({maxInvocations:20,period:60})],st.prototype,"sendFileMessage",1);vt([k.trace("DyteChat.sendMessage"),Bt({maxInvocations:180,period:60})],st.prototype,"sendMessage",1);vt([k.trace("DyteChat.editTextMessage")],st.prototype,"editTextMessage",1);vt([k.trace("DyteChat.editImageMessage")],st.prototype,"editImageMessage",1);vt([k.trace("DyteChat.editFileMessage")],st.prototype,"editFileMessage",1);vt([k.trace("DyteChat.editMessage")],st.prototype,"editMessage",1);vt([k.trace("DyteChat.deleteMessage")],st.prototype,"deleteMessage",1);vt([k.trace("DyteChat.createChannel")],st.prototype,"createChannel",1);vt([k.trace("DyteChat.updateChannel")],st.prototype,"updateChannel",1);vt([k.trace("DyteChat.sendMessageToChannel")],st.prototype,"sendMessageToChannel",1);vt([k.trace("DyteChat.getChannelMembers")],st.prototype,"getChannelMembers",1);vt([k.trace("DyteChat.searchMessages")],st.prototype,"searchMessages",1);vt([k.trace("DyteChat.markLastReadMessage")],st.prototype,"markLastReadMessage",1);st=vt([ft("0500")],st);var SO=Object.defineProperty,EO=Object.getOwnPropertyDescriptor,kO=(t,e,r,i)=>{for(var n=i>1?void 0:i?EO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&SO(e,r,n),n},nn,dg;const mn=(dg=class{constructor(t,e,r,i,n){m(this,"chat"),m(this,"chatSocketHandler"),m(this,"chatChannelSocketHandler"),m(this,"self"),g(this,nn,void 0),f(this,nn,t),this.chatSocketHandler=e,this.chatChannelSocketHandler=r,this.chat=new st(t,e,r,i,n),this.self=i,this.setupEvents()}get telemetry(){return a(this,nn).getValue("telemetry")}get logger(){return a(this,nn).getValue("logger")}static init(t,e,r,i,n){return u(this,null,function*(){return new mn(t,e,r,i,n)})}static formatMessage(t){return q(V({},t),{time:new Date(t.time),type:yO[t.type]})}static formatSocketPeerMessage(t){const e=t.createdAt*1e3,r={displayName:t.displayName,id:t.chatId,time:e,timeMs:t.createdAtMs,type:t.payloadType,isEdited:t.isEdited,userId:t.userId,targetUserIds:t.targetUserIds,channelId:t.channelId,channelIndex:t.channelIndex,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:t.pinned};switch(r.type){case _t.TEXT:{r.message=t.payload;break}case _t.IMAGE:{r.link=t.payload;break}case _t.FILE:{const{link:i,name:n,size:s}=JSON.parse(t.payload);r.link=i,r.name=n,r.size=s;break}case _t.CUSTOM:{const{html:i,images:n,message:s,videos:o,files:c}=JSON.parse(t.payload);r.message=s,r.html=i,r.images=n,r.videos=o,r.files=c;break}}return mn.formatMessage(r)}getChatMessages(){return u(this,null,function*(){if(this.self.config.viewType==="LIVESTREAM"||this.self.config.viewType==="CHAT"||a(this,nn).getValue("flagsmith").hasFeature(Z.FEAT_PAGINATED_CHAT))return;const t=yield this.chatSocketHandler.getChatMessages();if(!(t!=null&&t.payload))return;const e=sy.fromBinary(t.payload).messages;this.chat.messages=e.map(r=>mn.formatSocketPeerMessage(r))})}setupEvents(){a(this,nn).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){this.getChatMessages()})),this.chatSocketHandler.on(De.sendMessageToRoom,t=>{const e=mn.formatSocketPeerMessage(t.message);if(!e.channelId)this.chat.messages=[...this.chat.messages,e];else{const r=this.chat.channels.find(i=>i.id===e.channelId);r&&(r.latestMessage=e,r.unreadCount+=1,this.chat.emit("channelMessageUpdate",r))}this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(De.sendMessageToPeers,t=>{const e=mn.formatSocketPeerMessage(t.message);this.chat.messages=[...this.chat.messages,e],this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(De.editMessage,t=>{const e=mn.formatSocketPeerMessage(t.message);if(e.channelId){this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages});return}const r=this.chat.messages.findIndex(i=>i.id===e.id);r!==-1&&(this.chat.messages[r]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}))}),this.chatSocketHandler.on(De.deleteMessage,t=>{if(t.channelId){this.chat.emit("chatUpdate",{action:"delete",message:{id:t.chatId,channelId:t.channelId},messages:this.chat.messages});return}const e=this.chat.messages.findIndex(i=>i.id===t.chatId);if(e===-1)return;const[r]=this.chat.messages.splice(e,1);this.chat.emit("chatUpdate",{action:"delete",message:r,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(Rn.createChatChannel,t=>{const[e]=t.chatChannels,r=Un.formatChannel(e);this.chat.channels.push(r),this.chat.emit("channelCreate",r)}),this.chatSocketHandler.on(De.pinMessage,t=>{const e=this.chat.messages.findIndex(i=>i.id===t.chatId);if(e===-1)return;const r=this.chat.messages[e];r.pinned=t.pinned,this.chat.messages[e]=r,this.chat.emit("chatUpdate",{action:"edit",message:r,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(Rn.updateChatChannel,t=>{const[e]=t.chatChannels,r=Un.formatChannel(e);this.chat.channels=this.chat.channels.map(i=>i.id===r.id?r:i),this.chat.emit("channelUpdate",r)})}},nn=new WeakMap,dg);let hi=mn;kO([k.trace("ChatController.setupEvents")],hi.prototype,"setupEvents",1);var TO=Object.defineProperty,bO=Object.getOwnPropertyDescriptor,wO=(t,e,r,i)=>{for(var n=i>1?void 0:i?bO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&TO(e,r,n),n},iu,lg,nu,ug,Ta,ba,kc,hg;let eh=(hg=class extends Zt{constructor(t,e,r){const i=t.getValue("logger");super(i),g(this,iu),g(this,nu),m(this,"items"),g(this,Ta,void 0),g(this,ba,void 0),g(this,kc,void 0),f(this,kc,t),f(this,Ta,e),f(this,ba,r),this.items=[]}create(t,e,r=!1,i=!1){return u(this,null,function*(){if(!a(this,nu,ug))throw new I("Can't create polls without joining room","0705");if(!a(this,Ta).permissions.polls.canCreate){this.logger.error("DytePolls::create::permission_denied");return}if(!t||!e){this.logger.error("DytePolls::question_and_options_can_not_be_empty",{dytePolls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){this.logger.error("DytePolls::there_must_be_at_least_two_options",{dytePolls:{hasQuestion:!!t,optionsLength:e.length}});return}yield a(this,ba).createPoll(t,e,r,i)})}vote(t,e){return u(this,null,function*(){if(!a(this,Ta).permissions.polls.canVote){this.logger.error("DytePolls::vote::permission_denied");return}yield a(this,ba).votePoll(t,e)})}},iu=new WeakSet,lg=function(){return a(this,kc).getValue("connectionHandler")},nu=new WeakSet,ug=function(){var t;return((t=a(this,iu,lg))==null?void 0:t.socketJoined)===!0},Ta=new WeakMap,ba=new WeakMap,kc=new WeakMap,hg);eh=wO([ft("0700")],eh);var _O=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,CO=(t,e,r,i)=>{for(var n=i>1?void 0:i?IO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&_O(e,r,n),n},sn,wa,Qn,pg;const vs=(pg=class{constructor(t,e,r){m(this,"polls"),g(this,sn,void 0),g(this,wa,void 0),g(this,Qn,void 0),this.polls=new eh(t,e,r),f(this,wa,e),f(this,sn,t),f(this,Qn,r),this.setupEvents()}get telemetry(){return a(this,sn).getValue("telemetry")}get logger(){return a(this,sn).getValue("logger")}static init(t,e,r){return u(this,null,function*(){return new vs(t,e,r)})}canViewPolls(){return a(this,wa).permissions.polls.canView}setupEvents(){const t={[si.createPoll]:i=>{i.poll&&this.updatePoll(vs.formatSocketServicePoll(i.poll))},[si.updatePoll]:i=>{i.poll&&this.updatePoll(vs.formatSocketServicePoll(i.poll))},[si.votePoll]:i=>{i.poll&&this.updatePoll(vs.formatSocketServicePoll(i.poll))}},e=()=>{a(this,sn).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(i=>{a(this,Qn).on(i,t[i])})},r=()=>{a(this,sn).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(i=>{a(this,Qn).removeListeners(i)})};a(this,wa).permissions.on("permissionsUpdate",i=>u(this,null,function*(){var n;i!=null&&i.polls&&((n=i==null?void 0:i.polls)!=null&&n.canView?(yield this.getPolls(),e()):(this.polls.items=[],r()))})),this.canViewPolls()&&e()}updatePoll(t){if(!this.canViewPolls())return;const e=this.polls.items.findIndex(r=>r.id===t.id);if(e>-1){const r=JSON.stringify(this.polls.items[e]);this.polls.items[e]=t,r!==JSON.stringify(t)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,t],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}getPolls(){return u(this,null,function*(){const t=yield a(this,Qn).getPolls();if(!(t!=null&&t.payload))return;const{polls:e}=UD.fromBinary(t.payload);this.polls.items=e.map(r=>vs.formatSocketServicePoll(r))})}static formatSocketServicePoll(t){const e=t.options.map(r=>({count:r.count,text:r.text,votes:r.votes.map(i=>({id:i.userId,name:i.name}))}));return{anonymous:t.anonymous,createdBy:t.createdBy,createdByUserId:t.createdByUserId,hideVotes:t.hideVotes,id:t.pollId,options:e,question:t.question,voted:t.votes}}},sn=new WeakMap,wa=new WeakMap,Qn=new WeakMap,pg);let ly=vs;CO([k.trace("PollController.setupEvents")],ly.prototype,"setupEvents",1);var PO=Object.defineProperty,RO=Object.getOwnPropertyDescriptor,MO=(t,e,r,i)=>{for(var n=i>1?void 0:i?RO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&PO(e,r,n),n},uy=(t=>(t[t.User=0]="User",t[t.Meeting=1]="Meeting",t))(uy||{}),_a,Tc,su,Xn,bc,mg;let th=(mg=class extends Zt{constructor(t,e,r,i,n){const s=t.getValue("logger");super(s),g(this,Tc),m(this,"selfActiveTab"),m(this,"broadcastTabChanges"),g(this,_a,void 0),g(this,Xn,void 0),g(this,bc,void 0),m(this,"viewType"),m(this,"meetingStartedTimestamp"),m(this,"meetingTitle"),m(this,"sessionId"),f(this,_a,t),f(this,Xn,e),this.viewType=r,f(this,bc,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,Tc,su).socketState}get mediaState(){return a(this,Tc,su).mediaState}get meetingId(){return a(this,_a).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,Xn).permissions.canSpotlight)throw this.logger.error("DyteSpotlight::setSpotlighted::permission_denied"),new I("User does not have permission to toggle spotlight","0801");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;this.logger.info("DyteSpotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=a(this,Xn).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,bc).broadcastMessage("spotlight",{userId:a(this,Xn).userId,currentTab:this.selfActiveTab})}},_a=new WeakMap,Tc=new WeakSet,su=function(){return a(this,_a).getValue("connectionHandler")},Xn=new WeakMap,bc=new WeakMap,mg);th=MO([ft("0800")],th);function AO(t){let e="",r=[""];const i=[r];let n=0,s=0,o=!0,c;for(c of t)c==='"'?(o&&c===e&&(r[n]+=c),o=!o):c===","&&o?c=r[++n]="":c===`
16
16
  `&&o?(e==="\r"&&(r[n]=r[n].slice(0,-1)),r=i[++s]=[c=""],n=0):r[n]+=c,e=c;return i}var DO=Object.defineProperty,OO=Object.getOwnPropertyDescriptor,hy=(t,e,r,i)=>{for(var n=i>1?void 0:i?OO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&DO(e,r,n),n},wc,gg;let Yi=(gg=class extends Zt{constructor(t){const e=t.getValue("logger");super(e),m(this,"transcripts"),g(this,wc,void 0),f(this,wc,t),this.transcripts=[]}get telemetry(){return a(this,wc).getValue("telemetry")}static init(t,e){return u(this,null,function*(){const r=new Yi(t),i=t.getValue("logger");try{e&&r.getActiveTranscript()}catch(n){i.error("Error fetching active transcriptions ",n)}return r})}static parseTranscript(t,e=!1){if(!t)return;const[[r,i,n,s,o,c]]=AO(t);return{id:Ln(),name:o,peerId:i,userId:n,customParticipantId:s,transcript:c,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}static parseTranscripts(t){return t?t.split(`
17
- `).map(e=>Yi.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=pt(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=Yi.parseTranscripts(e)}catch{}})}onTranscript(t){return u(this,null,function*(){var e;const r=this.transcripts.filter(({peerId:i})=>i===t.peerId);if((e=r==null?void 0:r.at(-1))!=null&&e.isPartialTranscript){const i=r.at(-1);i.transcript=t.transcript,i.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",i);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)})}},wc=new WeakMap,gg);hy([k.trace("DyteAi.getActiveTranscript")],Yi.prototype,"getActiveTranscript",1);Yi=hy([ft("0000")],Yi);var NO=Object.defineProperty,VO=Object.getOwnPropertyDescriptor,LO=(t,e,r,i)=>{for(var n=i>1?void 0:i?VO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&NO(e,r,n),n},an,Ia,ir,fg;const py=(fg=class{constructor(t,e,r,i,n,s){m(this,"meta"),m(this,"ai"),g(this,an,void 0),g(this,Ia,void 0),m(this,"aiSocketHandler"),g(this,ir,void 0),f(this,ir,t),this.meta=new th(t,e,e.config.viewType,r,s),this.ai=i,f(this,an,e),f(this,Ia,r),this.aiSocketHandler=n,e.config.viewType!==Ft.Chat&&this.setupEvents()}get telemetry(){return a(this,ir).getValue("telemetry")}get logger(){return a(this,ir).getValue("logger")}static init(t,e,r,i,n){return u(this,null,function*(){const s=yield Yi.init(t,e.permissions.transcriptionEnabled);return new py(t,e,r,s,i,n)})}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,uy.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){a(this,ir).getValue("peerSessionStore").on(P.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),a(this,ir).getValue("peerSessionStore").on(P.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),a(this,ir).getValue("peerSessionStore").on(P.ROOM_STATE,({createdAt:t,roomUuid:e})=>{const r=this.meta.meetingStartedTimestamp;if(e&&(this.meta.sessionId=e),t&&!r){const i=new Date(t*1e3);this.meta.meetingStartedTimestamp=i,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),a(this,ir).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),a(this,an).permissions.canSpotlight&&(this.logger.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,Ia).broadcastMessage("spotlight",{userId:a(this,an).userId,currentTab:this.meta.selfActiveTab})),a(this,ir).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){a(this,an).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,Ia).broadcastToPeers("spotlight",[t.id],{userId:a(this,an).userId,currentTab:this.meta.selfActiveTab})})),a(this,ir).getValue("peerSessionStore").on(P.ROOM_MESSAGE,t=>{var e,r;let i;if("type"in t){if(t.type!=="spotlight")return;i=V(V({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;i=t}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:i.userId},currentTab:{id:(e=i.currentTab)==null?void 0:e.id,type:(r=i.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(i)}),a(this,ir).getValue("peerSessionStore").on(P.MESSAGE,t=>{var e,r;let i;if("type"in t){if(t.type!=="spotlight")return;i=V(V({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;i=t}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:i.userId},currentTab:{id:(e=i.currentTab)==null?void 0:e.id,type:(r=i.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(i)}),this.aiSocketHandler.on(F.transcript,t=>{const{meetingId:e,transcript:r,isPartial:i}=t;let n;try{n=Yi.parseTranscript(r,i)}catch(d){this.logger.error(`Failed to parse transcript: ${r}`,d)}if(!n){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(n),this.meta.emit("transcript",n);const{peerId:s,name:o,transcript:c}=n;this.logger.debug(`${e} Received transcript for peer ${s} - ${o}: ${c}`)})}},an=new WeakMap,Ia=new WeakMap,ir=new WeakMap,fg);let my=py;LO([k.trace("MetaController.setupEvents")],my.prototype,"setupEvents",1);const Ca={},Si={executeWithLock({methodName:t,lockName:e,timeout:r}){return(i,n,s)=>{const o=s.value;return s.value=function(...c){var d,l;const h=(l=(this==null?void 0:this.peerId)||((d=c[0])==null?void 0:d.authToken))!=null?l:"",p=`${e}-${h}`,v=this==null?void 0:this.logger;if(Ca[p]){const C=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw C.name="UnsupportedConcurrentMethodExecution",v==null||v.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:C.stack},dyteLocker:{methodName:t,lockName:p}}),C}Ca[p]=!0;const S=setTimeout(()=>delete Ca[p],r),T=o.apply(this,c);return Promise.resolve(T).then(()=>{delete Ca[p],clearTimeout(S)}).catch(()=>{delete Ca[p],clearTimeout(S)}),T},s}}};var xO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,qn=(t,e,r,i)=>{for(var n=i>1?void 0:i?UO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&xO(e,r,n),n},Er,rh,ue,Yc,Zr,dt,Qc,ih,no,Xc;class Xi extends Zt{constructor(e,r,i,n,s){const o=e.getValue("logger");super(o),g(this,Qc),g(this,no),g(this,Er,void 0),g(this,rh,void 0),g(this,ue,void 0),g(this,Yc,void 0),g(this,Zr,void 0),g(this,dt,void 0),f(this,dt,e),f(this,Er,n),f(this,rh,s),f(this,ue,r),f(this,Yc,i),f(this,Zr,[]),this.setupEvents()}get telemetry(){return a(this,dt).getValue("telemetry")}get status(){return a(this,dt).getValue("stageStatus")}setupEvents(){const e={[P.GET_STAGE_REQUESTS]:n=>u(this,null,function*(){f(this,Zr,n)}),[P.UPDATE_STAGE_REQUESTS]:n=>u(this,[n],function*({add:s}){const o=a(this,Zr).length,{stageRequests:c}=this.getAccessRequests();(s||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)})},r=()=>{Object.entries(e).forEach(([n,s])=>{a(this,dt).getValue("peerSessionStore").onAsync(n,s)})},i=()=>{Object.entries(e).forEach(([n,s])=>{a(this,dt).getValue("peerSessionStore").removeListener(n,s)})};a(this,ue).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:s}=n;s!==void 0&&(a(this,ue).permissions.acceptStageRequests?(r(),a(this,Er).getStageRequests()):(i(),f(this,Zr,[]),this.emit("stageAccessRequestUpdate",a(this,Zr))))}),a(this,ue).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,ue).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ue).permissions.acceptStageRequests)throw this.logger.error("DyteStage::get_access_request::permission_denied"),new I("You do not have permission to perform this action","2001");const e=a(this,Yc).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return f(this,Zr,e),{stageRequests:a(this,Zr)}}requestAccess(){return u(this,null,function*(){if(!a(this,ue).permissions.stageEnabled)throw this.logger.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(a(this,ue).permissions.stageAccess===G.Allowed){U(this,no,Xc).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,Er).requestAccess(),U(this,no,Xc).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return u(this,null,function*(){if(!a(this,ue).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");a(this,Er).cancelRequestAccess(),U(this,no,Xc).call(this,"OFF_STAGE")})}grantAccess(e){if(!a(this,ue).roomJoined)throw new I("Can`t grant for participant without joining room");if(!a(this,ue).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ue).permissions.acceptStageRequests)throw this.logger.error("DyteStage::grant_access::permission_denied"),new I("You do not have permission to perform this action","2001");return a(this,Er).grantAccess(e)}denyAccess(e){if(!a(this,ue).roomJoined)throw new I("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,ue).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ue).permissions.acceptStageRequests)throw this.logger.error("DyteStage::deny_access::permission_denied"),new I("You do not have permission to perform this action","2001");return a(this,Er).denyAccess(e)}get peerId(){return a(this,dt).getValue("peerId")}join(){return u(this,null,function*(){const e=a(this,dt).getValue("viewType");if(this.status==="ON_STAGE")throw new I("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,ue).permissions.stageAccess===G.NotAllowed)throw new I(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,dt).setValue("stageStatus","ON_STAGE",!1),yield a(this,Er).joinStage(),e===Ft.Livestream){yield a(this,dt).getValue("selfController").joinRoom();return}a(this,dt).notify("stageStatus"),a(this,ue).audioEnabled&&a(this,Qc,ih).shareMic(a(this,ue).audioTrack),a(this,ue).videoEnabled&&a(this,Qc,ih).shareWebcam(a(this,ue).videoTrack)})}leave(){return u(this,null,function*(){if(!a(this,ue).permissions.stageEnabled)throw this.logger.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");a(this,ue).setIsPinned(!1),a(this,dt).setValue("stageStatus","OFF_STAGE",!1),yield a(this,Er).leaveStage(a(this,ue).userId);try{yield a(this,dt).getValue("peerSessionStore").emitAsync(P.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("DyteStage::leave::emitAsync::failed",{error:e})}a(this,dt).notify("stageStatus")})}kick(e){return u(this,null,function*(){if(!a(this,ue).roomJoined)throw new I("Can`t kick participant without joining room","2005");if(!a(this,ue).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ue).permissions.acceptStageRequests)throw this.logger.error("DyteStage::kick::permission_denied"),new I("You do not have permissions for kick","2001");return a(this,Er).kick(e)})}}Er=new WeakMap,rh=new WeakMap,ue=new WeakMap,Yc=new WeakMap,Zr=new WeakMap,dt=new WeakMap,Qc=new WeakSet,ih=function(){return a(this,dt).getValue("roomNodeClient")},no=new WeakSet,Xc=function(t){return u(this,null,function*(){this.status!==t&&a(this,dt).setValue("stageStatus",t)})};qn([k.trace("DyteStage.getStageRequests")],Xi.prototype,"getAccessRequests",1);qn([k.trace("DyteStage.requestAccess")],Xi.prototype,"requestAccess",1);qn([k.trace("DyteStage.cancelRequestAccess")],Xi.prototype,"cancelRequestAccess",1);qn([k.trace("DyteStage.grantAccess")],Xi.prototype,"grantAccess",1);qn([k.trace("DyteStage.denyAccess")],Xi.prototype,"denyAccess",1);qn([Si.executeWithLock({methodName:"joinStage",lockName:"DyteStage.join",timeout:5e3}),k.trace("DyteStage.joinStage")],Xi.prototype,"join",1);qn([k.trace("DyteStage.leaveStage")],Xi.prototype,"leave",1);function FO(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function kp(t){switch(t){case di.UNSPECIFIED:return"OFF_STAGE";case di.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case di.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case di.OFF_STAGE:return"OFF_STAGE";case di.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var BO=Object.defineProperty,WO=Object.getOwnPropertyDescriptor,jO=(t,e,r,i)=>{for(var n=i>1?void 0:i?WO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&BO(e,r,n),n},gn,Ur,fn,Zc,Lt;class gy{constructor(e,r,i,n,s){m(this,"stage"),g(this,gn,void 0),g(this,Ur,void 0),g(this,fn,void 0),g(this,Zc,0),g(this,Lt,void 0),f(this,Lt,e),this.stage=new Xi(e,n,s,r,i),f(this,fn,r),f(this,gn,n),f(this,Ur,s),this.setupEvents()}get telemetry(){return a(this,Lt).getValue("telemetry")}get logger(){return a(this,Lt).getValue("logger")}setupEvents(){a(this,Lt).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),a(this,fn).on(F.grantStageAccess,()=>{a(this,gn).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,fn).on(F.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===a(this,gn).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),a(this,fn).on(F.denyStageAccess,()=>{a(this,gn).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,fn).on(F.getStageRequests,e=>u(this,null,function*(){var r;if(a(this,gn).permissions.stageAccess!==G.Allowed)return;const i=(r=e==null?void 0:e.stageRequests)!=null?r:[];yield a(this,Lt).getValue("peerSessionStore").emitAsync(P.GET_STAGE_REQUESTS,i),a(this,Zc)<i.length&&i.length>0&&this.stage.emit("newStageRequest",{count:i.length}),f(this,Zc,i.length),this.stage.emit("stageAccessRequestUpdate",i)}))}getCurrentStageRequests(){return a(this,Ur).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&&a(this,Lt).setValue("stageStatus",e)})}selfStageStatusHandler(e){const r=kp(e.stageType),i=a(this,Lt).getValue("stageStatus");if(i!==r)switch(e.stageType){case 1:a(this,Lt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(i);break;case 0:case 4:default:a(this,Lt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return u(this,null,function*(){const r=a(this,Ur).joined.get(e.peerId),i=a(this,Ur).viewMode==="ACTIVE_GRID";if(!r){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:r.setStageStatus("ON_STAGE"),i&&a(this,Lt).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:a(this,Ur).viewMode,page:a(this,Ur).currentPage});break;case 2:r.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:r.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:r.setStageStatus("OFF_STAGE"),i&&a(this,Lt).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:a(this,Ur).viewMode,page:a(this,Ur).currentPage});break}a(this,Lt).getValue("peerSessionStore").emit(P.UPDATE_PEER_STAGE_STATUS,{id:r.id,status:r.stageStatus})})}}gn=new WeakMap,Ur=new WeakMap,fn=new WeakMap,Zc=new WeakMap,Lt=new WeakMap;jO([k.trace("DyteStage.setupEvents")],gy.prototype,"setupEvents",1);var HO=Object.defineProperty,GO=Object.getOwnPropertyDescriptor,Cl=(t,e,r,i)=>{for(var n=i>1?void 0:i?GO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&HO(e,r,n),n};const Le={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,nr,Pa,Ra,ki,Ma,on,Aa,vg;let Qs=(vg=class extends Zs{constructor(t,{baseURL:e,createdAt:r,description:i,id:n,name:s,organizationId:o,picture:c,private:d,published:l,staggered:h,tags:p,type:v,updatedAt:S},T,C,b,R,j){const B=t.getValue("logger");super(B),g(this,yt,void 0),m(this,"baseURL"),m(this,"createdAt"),m(this,"description"),m(this,"id"),m(this,"name"),g(this,nr,void 0),g(this,Pa,void 0),g(this,Ra,void 0),m(this,"organizationId"),m(this,"picture"),m(this,"private"),m(this,"published"),m(this,"staggered"),m(this,"tags"),m(this,"type"),m(this,"updatedAt"),g(this,ki,void 0),m(this,"config"),g(this,Ma,void 0),m(this,"active"),m(this,"iframes"),m(this,"enabledBy"),g(this,on,void 0),g(this,Aa,void 0),f(this,on,t),this.baseURL=e,this.createdAt=new Date(r),this.description=i,this.id=n,this.name=s,f(this,nr,C),this.organizationId=o,this.picture=c,this.private=d,this.published=l,this.staggered=h,this.tags=p,this.type=v,this.updatedAt=new Date(S),this.active=!1,this.iframes=new Map,f(this,yt,T),f(this,Pa,b),f(this,Ra,R),this.enabledBy="",f(this,Aa,j)}get telemetry(){return a(this,on).getValue("telemetry")}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}handleIframeMessage(t){return u(this,null,function*(){var e;if(!this.active)return;const r=t,{payload:i,uuid:n,type:s}=r;switch(s){case J.customPluginEventToRoom:{a(this,yt).customPluginEventToRoom(this.id,i,n);break}case J.customPluginEventToPeers:{a(this,yt).customPluginEventToPeers(this.id,i.peerIds,i,n);break}case J.enablePluginForRoom:{a(this,yt).enablePluginForRoom(this.id,n);break}case J.enablePluginForPeers:{a(this,yt).enablePluginForPeers(this.id,i.peerIds,n);break}case J.disablePluginForRoom:{a(this,yt).disablePluginForRoom(this.id,n);break}case J.disablePluginForPeers:{a(this,yt).disablePluginForPeers(this.id,i.peerIds,n);break}case J.storeInsertKeys:{a(this,yt).storeInsertKeys(this.id,i.store,i.insertKeys,n);break}case J.storeGetKeys:{a(this,yt).storeGetKeys(this.id,i.store,i.getKeys,n);break}case J.storeDeleteKeys:{a(this,yt).storeDeleteKeys(this.id,i.store,i.deleteKeys,n);break}case J.storeDelete:{a(this,yt).storeDelete(this.id,i.store,n);break}case Le.chatMessage:{const{messagePayload:o,peerIds:c}=i;if(!a(this,Ra)){this.sendIframeEvent({type:Le.chatMessage,uuid:r.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield a(this,Ra).sendMessage(o,c),this.sendIframeEvent({type:Le.chatMessage,uuid:r.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:Le.chatMessage,uuid:r.uuid,payload:{error:d}})}break}case Le.getPeer:{let o;const{peerId:c}=i,d=q(V({},a(this,nr)),{id:a(this,nr).id,isRecorder:(e=a(this,nr).permissions)==null?void 0:e.isRecorder,isHidden:a(this,nr).permissions.hiddenParticipant,stageStatus:a(this,nr).stageStatus});c?(o=a(this,Pa).joined.get(i.peerId),a(this,nr).id===c&&(o=d)):o=d,this.sendIframeEvent({type:Le.getPeer,payload:{peer:o&&Kd(o)},uuid:r.uuid});break}case Le.getPeers:{const o=a(this,Pa).joined.toArray().map(c=>Kd(c));this.sendIframeEvent({type:Le.getPeers,payload:{peers:o},uuid:r.uuid});break}case Le.getPluginInitiator:{this.sendIframeEvent({type:Le.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:r.uuid});break}case Le.getDisplayTitle:{this.sendIframeEvent({type:Le.getDisplayTitle,payload:{displayTitle:a(this,Aa)},uuid:r.uuid});break}case Le.getRoomName:{this.sendIframeEvent({type:Le.getRoomName,payload:{roomName:a(this,on).getValue("meetingId")},uuid:r.uuid});break}case Le.customPluginEventToParent:{this.emit(r.payload.eventName,r.payload.data);break}}})}sendData(t){this.active&&(this.logger.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Le.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var e;const{iframe:r,listener:i}=(e=this.iframes.get(t))!=null?e:{};(r||i)&&(navigator.isReactNative?r.props.onMessage=void 0:window.removeEventListener("message",i),this.iframes.delete(t))}addPluginView(t,e="default"){var r;if(!a(this,Ma))throw this.logger.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new I("No auth token set for plugin.","0602");if(!t)throw this.logger.error("DytePlugin::addPluginView::iframe_was_not_provided"),new I("Iframe was not provided.","0603");this.removePluginView(e);const i=t,n=new URL(this.baseURL),s={auth:a(this,Ma),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:a(this,on).getValue("apiBase"),pluginId:this.id,roomName:(r=a(this,on).getValue("meetingId"))!=null?r:"",displayTitle:a(this,Aa)};if(Object.keys(s).forEach(o=>{n.searchParams.set(o,s[o])}),i.src=n.href,i.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",i.title=e,navigator.isReactNative)i.props.onMessage=o=>{this.handleIframeMessage(JSON.parse(o.nativeEvent.data))},this.iframes.set(e,{iframe:i});else{const o=c=>u(this,null,function*(){c.source===t.contentWindow&&(yield this.handleIframeMessage(c.data))});window.addEventListener("message",o),this.iframes.set(e,{iframe:i,listener:o})}}setActive(t){var e,r;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:(r=this.config)==null?void 0:r.views})}activateForSelf(){return u(this,null,function*(){const t=pt(),e=yield t.authorizePlugin(this.id);f(this,Ma,e),f(this,ki,new Date);try{const r=yield t.getPluginConfig(this.baseURL);this.config=r}catch(r){this.logger.error("DytePlugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")})}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),f(this,ki,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=a(this,nr).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(a(this,yt).addPlugin(this.id,this.staggered),f(this,ki,new Date),this.logger.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=a(this,nr).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==a(this,nr).id||(a(this,yt).removePlugin(this.id),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:a(this,ki)?new Date().getTime()-a(this,ki).getTime():0}}),f(this,ki,void 0)))})}},yt=new WeakMap,nr=new WeakMap,Pa=new WeakMap,Ra=new WeakMap,ki=new WeakMap,Ma=new WeakMap,on=new WeakMap,Aa=new WeakMap,vg);Cl([Bt({maxInvocations:5,period:1})],Qs.prototype,"sendData",1);Cl([k.trace("DytePlugin.activatePlugin")],Qs.prototype,"activate",1);Cl([k.trace("DytePlugin.deactivatePlugin")],Qs.prototype,"deactivate",1);Qs=Cl([ft("0600")],Qs);var Ke,ys;class fy extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:s}=e;super(),g(this,Ke,void 0),g(this,ys,void 0),m(this,"onAddEvent"),m(this,"onDeleteEvent"),m(this,"onClearEvent"),f(this,Ke,new Zs(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=s,f(this,ys,new Map)}emit(e,...r){return a(this,Ke).emit(e,...r)}on(e,r){return a(this,Ke).on(e,r)}addListener(e,r){return a(this,Ke).addListener(e,r)}off(e,r){return a(this,Ke).off(e,r)}once(e,r){return a(this,Ke).once(e,r)}prependListener(e,r){return a(this,Ke).prependListener(e,r)}prependOnceListener(e,r){return a(this,Ke).prependOnceListener(e,r)}removeListener(e,r){return a(this,Ke).removeListener(e,r)}removeAllListeners(e){return a(this,Ke).removeAllListeners(e)}listeners(e){return a(this,Ke).listeners(e)}listenerCount(e){return a(this,Ke).listenerCount(e)}getMaxListeners(){return a(this,Ke).getMaxListeners()}setMaxListeners(e){return a(this,Ke).setMaxListeners(e)}eventNames(){return a(this,Ke).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const n=super.set(e,r),s=(o,...c)=>{this.emit(o,r,...c)};return a(this,ys).set(e,s),r.on("*",s),i&&a(this,Ke).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,ys).get(e));const s=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,Ke).emit(this.onDeleteEvent,n),s}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,ys).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,Ke).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Ke=new WeakMap,ys=new WeakMap;class yg extends fy{constructor(e){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"},e)}add(e,r=!0){return super.add(e,r)}delete(e,r=!0,i=!1){return super.delete(e,r,i)}}var qO=Object.defineProperty,$O=Object.getOwnPropertyDescriptor,JO=(t,e,r,i)=>{for(var n=i>1?void 0:i?$O(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&qO(e,r,n),n};let nh=class{constructor(t){m(this,"all"),m(this,"active"),this.all=new yg(t),this.active=new yg(t)}};nh=JO([ft("0600")],nh);var KO=Object.defineProperty,zO=Object.getOwnPropertyDescriptor,Pl=(t,e,r,i)=>{for(var n=i>1?void 0:i?zO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&KO(e,r,n),n},pr,Da,Nr,Sg;const vy=(Sg=class{constructor(t,e,r,i){m(this,"plugins"),g(this,pr,void 0),g(this,Da,void 0),g(this,Nr,void 0),f(this,pr,e),f(this,Da,r),f(this,Nr,t),this.plugins=i,this.setupEvents()}get telemetry(){return a(this,Nr).getValue("telemetry")}get logger(){return a(this,Nr).getValue("logger")}static init(t,e,r,i,n,s,o,c){return u(this,null,function*(){const d=t.getValue("logger"),l=new nh(d);return e.forEach(h=>{const p=new Qs(t,h,r,s,o,n,c);l.all.add(p)}),new vy(t,r,i,l)})}getRoomPlugins(){return u(this,null,function*(){var t;const{plugins:e}=yield a(this,pr).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(r=>{this.disablePlugin({id:r.id})}),yield Promise.all(e.map(r=>this.enablePlugin({id:r.pluginId,enabledBy:r.enabledBy})))})}enablePlugin(t){return u(this,arguments,function*({id:e,enabledBy:r}){const i=this.plugins.all.get(e);i&&(yield i.activateForSelf(),i.enabledBy=r)})}disablePlugin(t){return u(this,arguments,function*({id:e}){const r=this.plugins.all.get(e);r&&r.deactivateForSelf()})}sendIframeEvent(t,e,r,i){const n=this.plugins.all.get(e);n&&n.sendIframeEvent({type:t,uuid:r,payload:i})}broadcastIframeEvent(t,e){this.plugins.active.forEach(r=>{this.sendIframeEvent(t,r.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)}),a(this,Nr).getValue("peerSessionStore").onAsync(P.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){yield this.getRoomPlugins(),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),a(this,pr).on(J.addPlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active||(yield this.enablePlugin({id:r,enabledBy:t.enabledBy}))})),a(this,pr).on(J.removePlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active&&(yield this.disablePlugin({id:r}))})),[J.enablePluginForPeers,J.enablePluginForRoom].forEach(t=>{a(this,pr).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{enabledBy:e.enabledBy})}))}),[J.disablePluginForPeers,J.disablePluginForRoom].forEach(t=>{a(this,pr).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{disabledBy:e.disabledBy})}))}),[J.customPluginEventToPeers,J.customPluginEventToRoom].forEach(t=>{a(this,pr).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[J.storeInsertKeys,J.storeGetKeys,J.storeDeleteKeys].forEach(t=>{a(this,pr).on(t,(e,r)=>u(this,null,function*(){var i;const n=(i=e.storeItems)==null?void 0:i.map(s=>{var o;return{timestamp:s.timestamp,peerId:s.peerId,payload:JSON.parse((o=s.payload)!=null&&o.length?new TextDecoder().decode(s.payload):"{}"),key:s.storeKey}});this.sendIframeEvent(t,e.pluginId,r,{storeName:e.storeName,storeItems:n})}))}),a(this,pr).on(J.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent(J.storeDelete,t.pluginId,e,{storeName:t.storeName})})),a(this,Da).on(De.sendMessageToPeers,t=>{const e=hi==null?void 0:hi.formatSocketPeerMessage(t.message);this.broadcastIframeEvent(Le.chatMessage,{message:e})}),a(this,Da).on(De.sendMessageToRoom,t=>{const e=hi==null?void 0:hi.formatSocketPeerMessage(t.message);this.broadcastIframeEvent(Le.chatMessage,{message:e})}),a(this,Nr).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,t=>{const e=Kd(t);this.broadcastIframeEvent(Le.peerJoined,e)}),a(this,Nr).getValue("peerSessionStore").on(P.PEER_CLOSED,t=>{this.broadcastIframeEvent(Le.peerLeft,t)}),a(this,Nr).getValue("peerSessionStore").on(P.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(Le.peerStageStatusUpdate,t)}),a(this,Nr).subscribe("stageStatus",t=>{this.broadcastIframeEvent(Le.stageStatusUpdate,t)})}},pr=new WeakMap,Da=new WeakMap,Nr=new WeakMap,Sg);let rc=vy;Pl([k.trace("PluginController.getRoomPlugins")],rc.prototype,"getRoomPlugins",1);Pl([k.trace("PluginController.enableForSelf")],rc.prototype,"enablePlugin",1);Pl([k.trace("PluginController.disableForSelf")],rc.prototype,"disablePlugin",1);Pl([k.trace("PluginController.setupEvents")],rc.prototype,"setupEvents",1);var ed;class YO{constructor(e){m(this,"mediaJoined"),m(this,"socketJoined"),m(this,"socketJoinAttempted"),m(this,"mediaJoinAttempted"),m(this,"socketState"),m(this,"mediaState"),g(this,ed,void 0),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},f(this,ed,e)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(e,r){let i;const{reconnected:n}=this.socketState;switch(e){case"connected":i={state:"connected",reconnected:n,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:n,reconnectionAttempt:0};break;case"reconnectAttempt":i={state:"reconnecting",reconnected:n,reconnectionAttempt:r};break;case"failed":i={state:"failed",reconnected:n,reconnectionAttempt:void 0},this.socketJoined=!1;break}i&&(a(this,ed).getValue("peerSessionStore").emit(P.SOCKET_STATE_UPDATE,i),this.socketState=i)}}ed=new WeakMap;var QO=Object.defineProperty,XO=Object.getOwnPropertyDescriptor,ic=(t,e,r,i)=>{for(var n=i>1?void 0:i?XO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&QO(e,r,n),n},Oa,Na,Va,_c,Eg;let Fn=(Eg=class extends Zt{constructor(t,e){const r=t.getValue("logger");super(r),g(this,Va),g(this,Oa,void 0),g(this,Na,void 0),m(this,"recordingPeerIds",[]),m(this,"recordings",[]),f(this,Na,t),f(this,Oa,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"}get telemetry(){return a(this,Na).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}start(t){return u(this,null,function*(){if(!a(this,Oa).permissions.canRecord)throw this.logger.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 this.logger.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new I(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=pt(),{recording:r={}}=a(this,Na).getValue("defaults"),i=yield e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw this.logger.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new I("Error while starting recording","1000",this.logger)}})}stop(t){return u(this,null,function*(){yield U(this,Va,_c).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield U(this,Va,_c).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield U(this,Va,_c).call(this,"resume",["PAUSED"],t)})}},Oa=new WeakMap,Na=new WeakMap,Va=new WeakSet,_c=function(t,e,r){return u(this,null,function*(){if(!a(this,Oa).permissions.canRecord)throw this.logger.error("DyteRecording::stop::permission_denied"),new I("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const n=this.recordings.find(s=>s.id===r);if(n===void 0)throw new I("Could not find the specified recording","1004");if(e.includes(n.state)){this.logger.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:n.state}});return}i.push(n)}else i=this.recordings.filter(n=>e.includes(n.state));i.forEach(n=>u(this,null,function*(){const s=n.state;t==="stop"&&(n.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield pt().updateRecording(n.id,t)}catch(o){throw this.logger.error("DyteRecording::stop::recording_failed_to_stop",{error:o}),n.state!==s&&(n.state=s,this.emit("recordingUpdate",s)),new I("Error while stopping recording","1000",this.logger)}}))})},Eg);ic([k.trace("DyteRecording.start")],Fn.prototype,"start",1);ic([k.trace("DyteRecording.stop")],Fn.prototype,"stop",1);ic([k.trace("DyteRecording.stop")],Fn.prototype,"pause",1);ic([k.trace("DyteRecording.stop")],Fn.prototype,"resume",1);Fn=ic([ft("1000")],Fn);var ZO=Object.defineProperty,e1=Object.getOwnPropertyDescriptor,t1=(t,e,r,i)=>{for(var n=i>1?void 0:i?e1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&ZO(e,r,n),n},Ss;class yy{constructor(e,r,i){m(this,"recording"),m(this,"room"),g(this,Ss,void 0),f(this,Ss,e),this.recording=new Fn(e,r),this.room=i,this.setupEvents()}get telemetry(){return a(this,Ss).getValue("telemetry")}get logger(){return a(this,Ss).getValue("logger")}getRecordingTypeFromProtoType(e){let r;switch(e){case Vn.BROWSER:r="BROWSER";break;case Vn.COMPOSITE:r="COMPOSITE";break;case Vn.TRACK:r="TRACK";break;default:r="BROWSER"}return r}setupEvents(){a(this,Ss).getValue("peerSessionStore").on(P.ROOM_STATE,e=>{e.activeRecordings.length!==0?this.recording.updateRecordings(e.activeRecordings.map(r=>{const i=this.getRecordingTypeFromProtoType(r.recordingType);return{id:r.recordingId,state:r.recordingStatus,type:i}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(F.recordingStarted,e=>{let r=!1;const i=[...this.recording.recordings];if(i.forEach(n=>{n.id===e.recordingId&&(r=!0,n.state="RECORDING")}),r===!1){const n=this.getRecordingTypeFromProtoType(e.recordingType);i.push({id:e.recordingId,state:"RECORDING",type:n})}this.recording.updateRecordings(i)}),this.room.on(F.recordingPaused,e=>{const r=[...this.recording.recordings];r.forEach(i=>{i.id===e.recordingId&&(i.state="PAUSED")}),this.recording.updateRecordings(r)}),this.room.on(F.recordingStopped,e=>{const r=[...this.recording.recordings.filter(i=>i.id!==e.recordingId)];this.recording.updateRecordings(r)})}}Ss=new WeakMap;t1([k.trace("RecordingController.setupEvents")],yy.prototype,"setupEvents",1);var Es;class r1{constructor(e){g(this,Es,void 0),f(this,Es,e)}hasFeature(e){var r;return(r=a(this,Es).getValue("flagsmith").hasFeature(e))!=null?r:!1}getFeatureValue(e){return a(this,Es).getValue("flagsmith").getValue(e)}getAllFeatures(){return a(this,Es).getValue("flagsmith").getAllFlags()}}Es=new WeakMap;class Tp{constructor(e,r,i){m(this,"logger"),m(this,"features"),m(this,"browserSpecs"),m(this,"callStats"),this.logger=e,this.features=r,this.browserSpecs=Ie,this.callStats=i}static init(e){return new Tp(e.getValue("logger"),new r1(e),e.getValue("callstats"))}}class bp{constructor(e){m(this,"internals"),this.internals=e}static init(e){return u(this,null,function*(){const r=Tp.init(e);return new bp(r)})}}var i1=Object.defineProperty,n1=Object.getOwnPropertyDescriptor,tr=(t,e,r,i)=>{for(var n=i>1?void 0:i?n1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&i1(e,r,n),n},rt,Ce,be,Oi,kr,td,We;class Wt extends Zs{constructor(e,r,i=sh,n=!0){const s=e.getValue("logger");super(s),g(this,rt,void 0),g(this,Ce,void 0),g(this,be,void 0),g(this,Oi,void 0),g(this,kr,void 0),g(this,td,void 0),g(this,We,void 0),m(this,"audioUpdateInProgress"),m(this,"videoUpdateInProgress"),f(this,We,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,f(this,rt,new Sy(e,r)),f(this,Ce,new I1(e,a(this,rt),void 0,i)),f(this,be,new O1(e,a(this,rt),void 0,i)),f(this,kr,new M1(a(this,We),a(this,rt))),f(this,Oi,new P1(a(this,rt))),f(this,td,n),a(this,Ce).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,Ce).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,be).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,be).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,kr).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,We).getValue("telemetry")}set context(e){f(this,We,e)}onVisibilityChange(){return u(this,null,function*(){a(this,We).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,We).getValue("callstats").browserBackgrounded():(a(this,We).getValue("callstats").browserForegrounded(),yield this.setupSpeaker())})}repopulateAvailableDevices(){return u(this,null,function*(){return!0})}setupStreams(e){return u(this,arguments,function*({audio:r,video:i}){var n;r?a(this,We).getValue("callstats").audioOn():a(this,We).getValue("callstats").audioOff(),i?a(this,We).getValue("callstats").videoOn():a(this,We).getValue("callstats").videoOff();let s,o;if(r&&i)try{const c=yield a(this,rt).getAudioAndVideoTrack(a(this,Ce).userSelectedDevice,a(this,be).userSelectedDevice);s=c.audioTrack,o=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!s&&r)try{s=yield a(this,rt).getAudioTrack(!1,a(this,Ce).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!o&&i)try{o=yield a(this,rt).getVideoTrack(a(this,be).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}r&&!s&&a(this,We).getValue("callstats").audioOff(),i&&!o&&a(this,We).getValue("callstats").videoOff(),yield a(this,Ce).setMediaTrack(s),yield a(this,be).setMediaTrack(o);try{this.setupSpeaker()}catch{}if(o){const c=yield this.getDeviceById(o.getSettings().deviceId);a(this,We).getValue("callstats").selectedDevice("VIDEO",c)}if(s){const c=yield this.getDeviceById(s.getSettings().deviceId);a(this,We).getValue("callstats").selectedDevice("AUDIO",c)}(n=a(this,Oi).currentDevice)!=null&&n.deviceId&&a(this,We).getValue("callstats").selectedDevice("SPEAKER",a(this,Oi).currentDevice),a(this,rt).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})})}getCurrentDevices(){return{audio:a(this,Ce).currentDevice,video:a(this,be).currentDevice,speaker:a(this,Oi).currentDevice}}get permissions(){return a(this,rt).permissions}getAllDevices(){return a(this,rt).getAvailableDevices()}getDeviceById(e,r){return a(this,rt).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,Ce).mediaTrack}get audioTrack(){return a(this,Ce).transformedMediaTrack}get audioEnabled(){return a(this,Ce).trackEnabled}enableAudio(e){return u(this,null,function*(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?yield a(this,Ce).enableTrack(!1,e):yield a(this,Ce).unmuteTrack()}catch{}finally{this.audioUpdateInProgress=!1}}})}disableAudio(){a(this,Ce).mediaTrack&&!a(this,Ce).isCustomTrack?a(this,Ce).muteTrack():a(this,Ce).disableTrack()}getAudioDevices(e){return a(this,rt).getAudioInputDevices(e)}setAudioDevice(e){return u(this,null,function*(){yield a(this,Ce).setDevice(e),e!=null&&e.deviceId&&a(this,We).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return u(this,null,function*(){const{speaker:e}=this.getCurrentDevices();yield a(this,Oi).setupSpeaker();const{speaker:r}=this.getCurrentDevices();(e==null?void 0:e.deviceId)!==(r==null?void 0:r.deviceId)&&r&&this.emit("DEVICE_CHANGE",{device:r})})}setSpeakerDevice(e){return u(this,null,function*(){yield a(this,Oi).setupSpeaker(e),e!=null&&e.deviceId&&a(this,We).getValue("callstats").selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return a(this,be).mediaTrack}get videoTrack(){return a(this,be).transformedMediaTrack}get videoEnabled(){return a(this,be).trackEnabled}enableVideo(e){return u(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?yield a(this,be).enableTrack(!1,e):yield a(this,be).unmuteTrack()}catch{}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){a(this,be).disableTrack()}getVideoDevices(e){return a(this,rt).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield a(this,be).setDevice(e),e!=null&&e.deviceId&&a(this,We).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}updateVideoConstraints(e){return u(this,null,function*(){yield a(this,be).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,kr).audioMediaTrack,video:a(this,kr).videoMediaTrack}}get screenShareEnabled(){return a(this,kr).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield a(this,kr).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){a(this,kr).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield a(this,kr).updateConstraints(e)})}getSpeakerDevices(e){return a(this,rt).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,Ce).addMiddleware(e)}removeAudioMiddleware(e){return a(this,Ce).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,Ce).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,be).addMiddleware(e)}removeVideoMiddleware(e){return a(this,be).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,be).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,be).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,Ce).disableTrack(),a(this,be).disableTrack(),a(this,be).terminateMiddlewareWebWorker(),a(this,kr).disableScreenShare(),a(this,rt).destruct()}onDeviceChange(e,r){return u(this,null,function*(){var i,n;this.emit("DEVICE_LIST_UPDATED",e),!(r||!a(this,td))&&((i=e==null?void 0:e.added)==null||i.forEach(s=>u(this,null,function*(){var o;s&&!sh(s)&&(s.kind==="audioinput"&&((o=this.audioTrack)==null?void 0:o.enabled)===!0?yield this.setAudioDevice(s):s.kind==="audiooutput"&&(yield this.setSpeakerDevice(s)))})),(n=e==null?void 0:e.removed)==null||n.forEach(s=>u(this,null,function*(){var o;if(s.kind==="audiooutput"&&((o=this.getCurrentDevices().speaker)==null?void 0:o.deviceId)===s.deviceId){const c=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==s.deviceId);c&&(yield this.setSpeakerDevice(c))}})))})}removeAllTracks(){this.destruct()}removeAudioTrack(){a(this,Ce).disableTrack()}removeVideoTrack(){a(this,be).disableTrack(),a(this,be).terminateMiddlewareWebWorker()}removeDocumentEventListeners(){return u(this,null,function*(){document.removeEventListener("visibilitychange",this.onVisibilityChange)})}}rt=new WeakMap,Ce=new WeakMap,be=new WeakMap,Oi=new WeakMap,kr=new WeakMap,td=new WeakMap,We=new WeakMap;tr([k.trace("MediaHandler.setupStreams")],Wt.prototype,"setupStreams",1);tr([k.trace("MediaHandler.enableAudio")],Wt.prototype,"enableAudio",1);tr([k.trace("MediaHandler.disableAudio")],Wt.prototype,"disableAudio",1);tr([k.trace("MediaHandler.setAudioDevice")],Wt.prototype,"setAudioDevice",1);tr([k.trace("MediaHandler.enableVideo")],Wt.prototype,"enableVideo",1);tr([k.trace("MediaHandler.disableVideo")],Wt.prototype,"disableVideo",1);tr([k.trace("MediaHandler.setVideoDevice")],Wt.prototype,"setVideoDevice",1);tr([k.trace("MediaHandler.updateVideoConstraints")],Wt.prototype,"updateVideoConstraints",1);tr([k.trace("MediaHandler.enableScreenShare")],Wt.prototype,"enableScreenShare",1);tr([k.trace("MediaHandler.disableScreenShare")],Wt.prototype,"disableScreenShare",1);tr([k.trace("MediaHandler.updateScreenshareConstraints")],Wt.prototype,"updateScreenshareConstraints",1);tr([k.trace("MediaHandler.destruct")],Wt.prototype,"destruct",1);tr([k.trace("MediaHandler.onDeviceChange")],Wt.prototype,"onDeviceChange",1);function Ic(t,e,r){switch(!0){case Ie.isChromiumBased():switch(e){case"NotAllowedError":return r.includes("by system")?"SYSTEM_DENIED":t==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Ie.isSafari():switch(e){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Ie.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 s1=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function sh(t){var e,r;const i=(e=t.label)==null?void 0:e.toLowerCase();return((r=Ie._bowser)==null?void 0:r.getOSName())==="macOS"&&i.includes("iphone")?!0:s1.some(n=>i==null?void 0:i.includes(n))}function a1(t,e,r){return u(this,null,function*(){if(!(e!=null&&e.length))return r;const i=t.getValue("logger"),n=new AudioContext,s=yield Promise.all(e==null?void 0:e.map(d=>d(n))),o=n.createMediaStreamSource(new MediaStream([r])),c=n.createMediaStreamDestination();try{let d=o;for(let l=0;l<s.length;l+=1)d.connect(s[l]),d=s[l];d.connect(c)}catch(d){return i.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),r}return c.stream.getAudioTracks()[0]})}var ks,rd;class o1{constructor(e){g(this,ks,void 0),g(this,rd,void 0),f(this,rd,e)}get logger(){return a(this,rd).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,ks))try{Tf(a(this,ks)),f(this,ks,void 0)}catch{this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}getTransformedVideoTrack(e,r,i){return u(this,null,function*(){if(!(e!=null&&e.length))return r;const n=document.createElement("canvas"),s=yield Promise.all(e==null?void 0:e.map(p=>p({canvas:n,WorkerTimers:wf})));if(i.disablePerFrameCanvasRendering){const p=n.captureStream().getVideoTracks()[0];return Object.defineProperty(p,"originalSettings",{value:r.getSettings()}),p}const o=document.createElement("video"),c=new MediaStream;c.addTrack(r);const d=n.getContext("2d");o.srcObject=c,o.autoplay=!0,this.terminateMiddlewareWebWorker();const l=()=>u(this,null,function*(){if(r.enabled===!1||r.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),n.remove();return}try{d.drawImage(o,0,0);for(let p=0;p<s.length;p+=1)typeof s[p]=="function"&&(yield s[p](n,d))}catch(p){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:p})}});try{o.play()}catch{}o.addEventListener("play",()=>{n.width=o.width||r.getSettings().width,n.height=o.width||r.getSettings().height,f(this,ks,bf(l,50))},!1);const h=n.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:r.getSettings()}),h})}}ks=new WeakMap,rd=new WeakMap;const kg={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}}},c1=[[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"}]]],d1=(t,e)=>{var r;const i="getSettings"in e&&e.getSettings().width||"getConstraints"in e&&e.getConstraints().width||"originalSettings"in e&&((r=e.originalSettings)==null?void 0:r.width);let n=c1;t.getValue("flagsmith").hasFeature(Z.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)&&(n=JSON.parse(t.getValue("flagsmith").getValue(Z.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)));const s=n.map(([d])=>d).sort((d,l)=>d-l);let o=Number.MAX_VALUE,c=0;return s.forEach((d,l)=>{Math.abs(d-i)<o&&(o=Math.abs(d-i),c=l)}),n[c][1]};var Se=(t=>(t.WEBCAM="webcam",t.WEBCAM_BACKUP="webcam_backup",t.MIC="mic",t.SCREENSHARE_VIDEO="screenshare_video",t.SCREENSHARE_AUDIO="screenshare_audio",t))(Se||{});const l1=R_(),Zn=Pr(l1.config.media);function u1(t){var e,r;const i={};return t.audio&&(i.audio={enableStereo:(e=t.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=t.audio.enableHighBitrate)!=null?r:!1}),i.video=t.video.quality,i}var Ts,ei;class h1{constructor(e,r){g(this,Ts,void 0),g(this,ei,void 0),m(this,"getScreenShareConstraints",()=>{var i,n,s,o,c,d,l,h,p,v,S;const T=(i=a(this,Ts))==null?void 0:i.screenshare,C=(s=(n=T==null?void 0:T.width)==null?void 0:n.max)!=null?s:1920,b=(c=(o=T==null?void 0:T.height)==null?void 0:o.max)!=null?c:1080,R=(l=(d=T==null?void 0:T.frameRate)==null?void 0:d.max)!=null?l:5;let j=(p=(h=T==null?void 0:T.frameRate)==null?void 0:h.ideal)!=null?p:5;const B=T==null?void 0:T.displaySurface,w=T==null?void 0:T.selfBrowserSurface;a(this,ei).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE)&&(j=parseInt((v=a(this,ei).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE))==null?void 0:v.toString(),10));let ee={width:{max:C},height:{max:b},frameRate:{ideal:j,max:R}};if(a(this,ei).getValue("flagsmith").hasFeature(Z.SCREENSHARE_CONSTRAINTS)){const re=(S=a(this,ei).getValue("flagsmith").getValue(Z.SCREENSHARE_CONSTRAINTS))==null?void 0:S.toString();ee=JSON.parse(re)}return B!==void 0&&["monitor","browser","window"].includes(B)&&(ee=q(V({},ee),{displaySurface:B})),w!==void 0&&(ee=q(V({},ee),{selfBrowserSurface:w})),{audio:!0,video:ee}}),m(this,"getAudioConstraints",i=>{var n,s,o,c,d,l,h;const p={},v=(n=a(this,Ts))==null?void 0:n.audio,S=v!=null&&v.enableStereo?2:1;return Ie.isFirefox()||Ie.isWebKitBased()?(p.audio={deviceId:i,autoGainControl:(s=v==null?void 0:v.autoGainControl)!=null?s:!0,echoCancellation:(o=v==null?void 0:v.echoCancellation)!=null?o:!0,noiseSuppression:(c=v==null?void 0:v.noiseSupression)!=null?c:!0,channelCount:S},p):(p.audio={autoGainControl:(d=v==null?void 0:v.autoGainControl)!=null?d:!0,echoCancellation:(l=v==null?void 0:v.echoCancellation)!=null?l:!0,noiseSuppression:(h=v==null?void 0:v.noiseSupression)!=null?h:!0,channelCount:S},i&&i!=="default"&&(p.audio.deviceId={exact:i}),p)}),m(this,"getVideoConstraints",i=>{var n,s,o,c;const d={},l=(n=a(this,Ts))==null?void 0:n.video;let h=kg.vga;if(typeof l=="string"?h=kg[l]:l!==void 0&&(h.height.ideal=l.height.ideal,h.width.ideal=l.width.ideal),h.frameRate={ideal:(o=(s=h.frameRate)==null?void 0:s.ideal)!=null?o:24},Ie.isChromiumBased()&&(h.frameRate.max=30),a(this,ei).getValue("flagsmith").hasFeature(Z.VIDEO_CONSTRAINTS)){const p=(c=a(this,ei).getValue("flagsmith").getValue(Z.VIDEO_CONSTRAINTS))==null?void 0:c.toString();h=JSON.parse(p)}return d.video=h,typeof d.video=="boolean"||(i?d.video.deviceId={exact:i}:d.video.facingMode="user"),d}),f(this,ei,e),f(this,Ts,r)}getUpdatedVideoConstraints(e){return e}}Ts=new WeakMap,ei=new WeakMap;class au extends Error{constructor(e,r,i){super(r),m(this,"constraints"),m(this,"name"),this.name=e,this.constraints=i}}class p1{constructor(){m(this,"permissions"),this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}getAudioInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(i=>i.kind==="audioinput")})}getVideoInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(i=>i.kind==="videoinput")})}getAudioOutputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(i=>i.kind==="audiooutput")})}}var m1=Object.defineProperty,g1=Object.getOwnPropertyDescriptor,Or=(t,e,r,i)=>{for(var n=i>1?void 0:i?g1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&m1(e,r,n),n},La,mr,qe,Tg;let Xt=(Tg=class extends p1{constructor(t,e){super(),m(this,"availableDevices"),g(this,La,void 0),g(this,mr,void 0),g(this,qe,void 0),f(this,qe,t),f(this,mr,new h1(t,e)),f(this,La,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get telemetry(){return a(this,qe).getValue("telemetry")}get logger(){return a(this,qe).getValue("logger")}get constraintsBuilder(){return a(this,mr)}destruct(){return u(this,null,function*(){var t;(t=a(this,La))==null||t.abort()})}handlePermissionErrors(t,e){const r=Ic(t,e.name,e.message);return this.permissions[t]=r,a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}getAudioAndVideoTrack(t,e){return u(this,null,function*(){const r={audio:a(this,mr).getAudioConstraints(t).audio,video:a(this,mr).getVideoConstraints(e).video};try{this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(r)});const i=yield navigator.mediaDevices.getUserMedia(r);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(r)});const n=i.getAudioTracks()[0];let s=i.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",a(this,qe).getValue("flagsmith").hasFeature(Z.OBS_QUALITY)&&s.label.includes("OBS Virtual")){const o=(yield this.getVideoInputDevices()).find(c=>c.label.includes("OBS Virtual"));s=yield this.getVideoTrack(o.deviceId)}return a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:n,videoTrack:s}}catch(i){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:i}),new I("Couldnt fetch audio and video track","1605")}})}getAudioTrack(t,e){return u(this,null,function*(){let r=yield this.getAudioInputDevices();if(r.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new I("No audio devices available","1606");const i=n=>u(this,null,function*(){let s;try{r=r.filter(c=>c.deviceId!==n),s=a(this,mr).getAudioConstraints(n),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(s)});const[o]=(yield navigator.mediaDevices.getUserMedia(s)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(s)}),o}catch(o){const c=Ic("audio",o.name,o.message),d=new au(o.name,o.message,s);if(c==="COULD_NOT_START"){const l=r.shift();if(!l)throw d;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(s),error:o});const h=a(this,mr).getAudioConstraints(l.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(h)}),i(l.deviceId)}throw d}});try{const n=yield i(e);return n.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),n}catch(n){throw n.constraints&&this.handlePermissionErrors("audio",n),new I(n.message,"1601")}})}getVideoTrack(t){return u(this,null,function*(){var e;const r=a(this,qe).getValue("flagsmith").hasFeature(Z.OBS_QUALITY),i=(e=yield this.getCurrentDeviceLabel(t))==null?void 0:e.includes("OBS Virtual"),n=r&&i,s=yield this.getVideoInputDevices();if(s.length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new I("No video devices available","1607");const o=c=>u(this,null,function*(){try{let d=c;const{video:l}=d;n&&typeof l!="boolean"&&(d={video:{deviceId:l.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(d)});const[h]=(yield navigator.mediaDevices.getUserMedia(d)).getVideoTracks();if(n&&typeof l!="boolean"&&typeof l.width=="object"){const{width:p,height:v}=h.getSettings(),{ideal:S}=l.width;h.applyConstraints({width:{ideal:S},height:{ideal:Math.floor(v*S/p)},frameRate:l.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(d)}),h}catch(d){const l=Ic("video",d.name,d.message),h=new au(d.name,d.message,c);if(l==="COULD_NOT_START"){const p=s.shift();if(!p)throw h;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(c),error:d});const v=a(this,mr).getVideoConstraints(p.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(v)}),o({video:v.video})}throw h}});try{const c=a(this,mr).getVideoConstraints(t),d=yield o(c);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,qe).getValue("peerSessionStore").emit(P.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{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,qe).getValue("callstats").screenShareRequested();const r=yield navigator.mediaDevices.getDisplayMedia(e);return this.logger.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const i=Ic("video",r.name,r.message),n=new au(r.name,r.message,e),s={video:!0};if(fI(e,s)||!a(this,qe).getValue("flagsmith").hasFeature(Z.SCREEENSHARE_CONSTRAINTS_RETRY))throw n;if(i==="COULD_NOT_START")return t(s);throw n}});try{const e=a(this,mr).getScreenShareConstraints(),r=yield t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.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 this.logger.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 this.logger.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 this.logger.error("enumerate_devices_failed",{error:e}),new I("Failed to get device","1609")}})}onDeviceChange(t){return u(this,null,function*(){Ie.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",e=>u(this,null,function*(){var r,i;const n=h=>`${h.kind}-${h.deviceId}-${h.groupId}`,s=this.availableDevices,o=new Set(s.map(h=>n(h))),c=yield this.getAvailableDevices(),d=new Set(c.map(h=>n(h))),l={added:c.filter(h=>!o.has(n(h))),removed:s.filter(h=>!d.has(n(h))),devices:c};if((r=l.added)!=null&&r.length||(i=l.removed)!=null&&i.length){this.logger.info("repopulated_full_device_list",{devices:JSON.stringify(c)});const h=[...l.added,...l.removed];h.some(p=>p.kind==="audioinput")&&a(this,qe).getValue("callstats").devices("AUDIO",c==null?void 0:c.filter(p=>p.kind==="audioinput")),h.some(p=>p.kind==="videoinput")&&a(this,qe).getValue("callstats").devices("VIDEO",c==null?void 0:c.filter(p=>p.kind==="videoinput")),h.some(p=>p.kind==="audiooutput")&&a(this,qe).getValue("callstats").devices("SPEAKER",c==null?void 0:c.filter(p=>p.kind==="audiooutput")),t(e,l,!1)}}),{signal:a(this,La).signal})})}},La=new WeakMap,mr=new WeakMap,qe=new WeakMap,Tg);Or([k.trace("WebMediaInterface.destruct")],Xt.prototype,"destruct",1);Or([k.trace("WebMediaInterface.handlePermissionErrors")],Xt.prototype,"handlePermissionErrors",1);Or([k.trace("WebMediaInterface.getAudioAndVideoTrack")],Xt.prototype,"getAudioAndVideoTrack",1);Or([k.trace("WebMediaInterface.getAudioTrack")],Xt.prototype,"getAudioTrack",1);Or([k.trace("WebMediaInterface.getVideoTrack")],Xt.prototype,"getVideoTrack",1);Or([k.trace("WebMediaInterface.getScreenShareTracks")],Xt.prototype,"getScreenShareTracks",1);Or([k.trace("WebMediaInterface.getAvailableDevices")],Xt.prototype,"getAvailableDevices",1);Or([k.trace("WebMediaInterface.getAvailableDevicesByKind")],Xt.prototype,"getAvailableDevicesByKind",1);Or([k.trace("WebMediaInterface.getDevice")],Xt.prototype,"getDevice",1);Or([k.trace("WebMediaInterface.onDeviceChange")],Xt.prototype,"onDeviceChange",1);Xt=Or([ft("1600")],Xt);const Sy=Xt,Ao={setItem:(t,e,r)=>{try{localStorage.setItem(t,e)}catch(i){r==null||r.error("LocalStorage::setItem::crashed",{error:i,localStorage:{key:t,value:e}})}},getItem:(t,e)=>{try{return localStorage.getItem(t)}catch(r){e==null||e.error("LocalStorage::getItem::crashed",{error:r,localStorage:{key:t}})}return null}},f1=(t=0)=>new Promise(e=>setTimeout(e,t)),v1=(t,e,r)=>{const i=typeof r=="number"?r:250,n=t.createMediaStreamSource(e),s=t.createAnalyser();s.fftSize=2048,n.connect(s);const o=new Uint8Array(s.fftSize);let c=!1;setTimeout(()=>{c=!0},i);function d(){return c?Promise.resolve(!0):(s.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):f1().then(d))}return d().then(l=>(n.disconnect(),l),l=>{throw n.disconnect(),l})},y1=typeof AudioContext!="undefined"?AudioContext:null;class wp{constructor(e){m(this,"_AudioContext"),m(this,"audioContext"),m(this,"_audioContextRefContainers");const r=V({AudioContext:y1},e);Object.defineProperties(this,{_AudioContext:{value:r.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:wp}})}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 bg=new wp,S1=3,E1=250;function k1(t){const e={},r=bg.getOrCreate(e);let i=S1;function n(){return i-=1,v1(r,t.srcObject,E1).then(s=>s?i>0?n():!0:!1).catch(()=>!0)}return n().finally(()=>{bg.release(e)})}function wg(t,e){return u(this,null,function*(){const r=new Audio,i=new MediaStream;i.addTrack(e),r.srcObject=i;let n=!1;try{const s=r.play();s&&(yield s),n=yield k1(r),n&&t.info("checkIfAudioTrackIsSilent::silence_detected")}catch(s){t.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:s})}finally{r.pause(),r.remove()}return n})}var T1=Object.defineProperty,b1=Object.getOwnPropertyDescriptor,Ey=(t,e,r,i)=>{for(var n=i>1?void 0:i?b1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&T1(e,r,n),n};let zd=class extends Zs{constructor(t,e,r,i){var n;const s=t.getValue("logger");super(s),m(this,"constructorName",this.constructor.name),m(this,"userSelectedDevice"),m(this,"mediaInterface"),m(this,"isNonPreferredDevice"),m(this,"_mediaTrack"),m(this,"transformedMediaTrack"),m(this,"middlewares",[]),m(this,"currentDevice"),m(this,"userPreferredDeviceKey",`Dyte::${this.constructorName}::UserDeviceID`),m(this,"setUserPreferredDevice",o=>Ao.setItem(this.userPreferredDeviceKey,o,this.logger)),m(this,"getUserPreferredDevice",()=>Ao.getItem(this.userPreferredDeviceKey,this.logger)),m(this,"isCustomTrack",!1),m(this,"context"),this.context=t,this.mediaInterface=e,r&&this.setMediaTrack(r),this.userSelectedDevice=(n=this.getUserPreferredDevice())!=null?n:void 0,this.isNonPreferredDevice=i,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}get telemetry(){return this.context.getValue("telemetry")}disableTrack(){var t,e;this.removeMediaTrackListeners(),this.isCustomTrack||(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,e=!1){return u(this,null,function*(){const r=i=>{this.logger.error(`${this.constructorName}.setMediaTrack.error`,{error:i})};try{this.disableTrack()}catch(i){r(i)}this._mediaTrack=yield this.conditionallyChangeTrack(t,e),yield this.setTransformedTrack();try{this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(i){r(i)}})}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){this.logger.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 this.logger.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new I("Failed to unmute track","1611")}})}getCurrentDeviceId(){var t;const{kind:e}=this.mediaTrack;switch(e){case"audio":{const{deviceId:r}=this.mediaTrack.getSettings();if(r)return r;const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(i&&typeof i.deviceId=="object"&&"exact"in i.deviceId?i.deviceId.exact:i.deviceId)||((t=i==null?void 0:i.advanced)==null?void 0:t[0].deviceId)||"default":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 this.logger.warn(`${this.constructorName}.setDevice No device received`),new I("No device received!","1603");this.userSelectedDevice=t.deviceId,this.setUserPreferredDevice(t.deviceId),yield this.onSetDevice(t)})}addMiddleware(t){return u(this,null,function*(){if(Ie.isWebKitBased()&&!y_.hasFeature(Z.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 this.logger.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(r){return this.logger.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.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 this.logger.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,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.logger.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};Ey([k.trace("BaseMediaHandler.unmuteTrack")],zd.prototype,"unmuteTrack",1);zd=Ey([ft("1600")],zd);const ky=zd;var w1=Object.defineProperty,_1=Object.getOwnPropertyDescriptor,_p=(t,e,r,i)=>{for(var n=i>1?void 0:i?_1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&w1(e,r,n),n};const ou="[Dyte]nonSilentDeviceLabels";class Rl extends ky{onSetDevice(e){return u(this,null,function*(){if(!e)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new I("No device received!","1603");if(e.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new I("Non audio device received while setting device!","1603");try{const r=this.trackEnabled;yield this.setMediaTrack(yield this.mediaInterface.getAudioTrack(!r,this.userSelectedDevice))}catch(r){throw this.logger.error("AudioMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new I(r.message,"1604")}})}enableTrack(e,r){return u(this,null,function*(){if(this.trackEnabled){this.logger.warn("AudioMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,yield this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=yield this.mediaInterface.getAudioTrack(e,this.userSelectedDevice);yield this.setMediaTrack(i)})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield a1(this.context,this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(i){this.logger.error("AudioMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}})}onTrackEnded(){return u(this,null,function*(){this.logger.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const e=this.mediaTrack.enabled;this.disableTrack(),yield this.enableTrack(!e),yield this.setTransformedTrack(),this.emit("trackChanged")})}onTrackMuted(){this.logger.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e,r=!1){return u(this,null,function*(){var i;if(!e||this.userSelectedDevice||r)return e;let n=e;const s=yield this.mediaInterface.getAudioInputDevices(),o=this.isNonPreferredDevice?s.filter(l=>l&&!this.isNonPreferredDevice(l)):s;if(!(o!=null&&o.length))return n;o.find(l=>l.deviceId===e.getSettings().deviceId)||(n.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),n=yield this.mediaInterface.getAudioTrack(!1,o[0].deviceId));const c=JSON.parse(Ao.getItem(ou,this.logger));if(c!=null&&c.devices.some(l=>l.label===n.label))return n;if(!(yield wg(this.logger,n))){const l=(i=c==null?void 0:c.devices.concat({label:n.label}))!=null?i:[{label:n.label}];return Ao.setItem(ou,JSON.stringify({devices:l}),this.logger),n}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const d=n.getSettings().deviceId;return o.filter(l=>l.deviceId!==d).some(l=>u(this,null,function*(){var h;if(n=yield this.mediaInterface.getAudioTrack(!1,l.deviceId),!(yield wg(this.logger,n))){const p=(h=c==null?void 0:c.devices.concat({label:n.label}))!=null?h:[{label:n.label}];return Ao.setItem(ou,JSON.stringify({devices:p}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),n})}}_p([k.trace("AudioMediaHandler.setTransformedTrack")],Rl.prototype,"setTransformedTrack",1);_p([k.trace("AudioMediaHandler.onTrackEnded")],Rl.prototype,"onTrackEnded",1);_p([k.trace("AudioMediaHandler.conditionallyChangeTrack")],Rl.prototype,"conditionallyChangeTrack",1);const I1=Rl;var so;class C1{constructor(e){g(this,so,void 0),m(this,"currentDevice"),f(this,so,e)}setupSpeaker(e){return u(this,null,function*(){var r,i;if(!(a(this,so)instanceof Sy))return;let n=e;if(e||([n]=(yield a(this,so).getAvailableDevicesByKind("audiooutput")).filter(o=>!sh(o))),!n)throw new I("No speaker found","1608");if(((r=this.currentDevice)==null?void 0:r.deviceId)===n.deviceId)return;this.currentDevice=n;const s=document.querySelectorAll("audio");(i=s[0])!=null&&i.setSinkId&&s.forEach(o=>u(this,null,function*(){if(typeof o.sinkId!="undefined"&&this.currentDevice.deviceId&&o.sinkId!==this.currentDevice.deviceId)try{yield o.setSinkId(this.currentDevice.deviceId)}catch{}}))})}}so=new WeakMap;const P1=C1;var id;class R1 extends Zs{constructor(e,r){const i=e.getValue("logger");super(i),m(this,"mediaInterface"),m(this,"audioMediaTrack"),m(this,"videoMediaTrack"),g(this,id,void 0),f(this,id,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}enableScreenShare(){return u(this,null,function*(){var e,r;try{const{audioTrack:i,videoTrack:n}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=n,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",a(this,id).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch{}})}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.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 r=this.mediaInterface;if(!r.constraintsBuilder)throw new I("update constraints not supported for non web clients","1100",this.logger);try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){this.logger.error("ScreenShareHandler.updateConstraints.error",{error:i})}})}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),Ie.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}id=new WeakMap;const M1=R1;var A1=Object.defineProperty,D1=Object.getOwnPropertyDescriptor,Ml=(t,e,r,i)=>{for(var n=i>1?void 0:i?D1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&A1(e,r,n),n},ao,nd;class nc extends ky{constructor(e,r,i,n){super(e,r,i,n),g(this,ao,void 0),g(this,nd,{disablePerFrameCanvasRendering:!1}),f(this,ao,new o1(e))}onSetDevice(e){return u(this,null,function*(){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new I("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.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)){this.logger.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(r){throw this.logger.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new I("Failed to change device","1600",this.logger)}})}enableTrack(e,r){return u(this,null,function*(){if(this.trackEnabled){this.logger.warn("VideoMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,yield this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=yield this.mediaInterface.getVideoTrack(this.userSelectedDevice);yield this.setMediaTrack(i)})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield a(this,ao).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,nd)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return u(this,null,function*(){f(this,nd,e)})}updateConstraints(e){return u(this,null,function*(){if(!this._mediaTrack)throw new I("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new I("update constraints not supported for non web clients","1100",this.logger);try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),yield this.setTransformedTrack(),this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(i){this.logger.error("VideoMediaHandler.updateConstraints.error",{error:i})}})}terminateMiddlewareWebWorker(){a(this,ao).terminateMiddlewareWebWorker()}onTrackEnded(){return u(this,null,function*(){this.logger.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")})}onTrackMuted(){this.logger.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e,r=!1){return u(this,null,function*(){if(!e||this.userSelectedDevice||r)return e;let i=e;const n=yield this.mediaInterface.getVideoInputDevices(),s=this.isNonPreferredDevice?n.filter(o=>!this.isNonPreferredDevice(o)):n;return!(s!=null&&s.length)||window.FAST_DYTE||s.find(o=>o.deviceId===e.getSettings().deviceId)||(i.stop(),this.logger.info("localmediahandler::setupstreams::found_video_non_preferred"),i=yield this.mediaInterface.getVideoTrack(s[0].deviceId)),i})}}ao=new WeakMap,nd=new WeakMap;Ml([k.trace("VideoMediaHandler.setTransformedTrack")],nc.prototype,"setTransformedTrack",1);Ml([k.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],nc.prototype,"setVideoMiddlewareGlobalConfig",1);Ml([k.trace("VideoMediaHandler.onTrackEnded")],nc.prototype,"onTrackEnded",1);Ml([k.trace("VideoMediaHandler.conditionallyChangeTrack")],nc.prototype,"conditionallyChangeTrack",1);const O1=nc,_g=Pr(pp());var Jt,bs,sd,oo;const co=class{constructor(t){if(g(this,Jt,void 0),g(this,bs,void 0),g(this,sd,void 0),g(this,oo,void 0),!t)throw new I("Could not load preset.","0904");f(this,Jt,t.config),f(this,sd,t.name),f(this,bs,t.ui||Pr(pp().ui)),f(this,oo,t.permissions.plugins.config)}static fromResponse(t){return new co(t)}static default(){return new co(_g)}static init(t,e=!0){return!t||e?new co(_g):new co(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:a(this,bs).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,Jt).viewType}get livestreamViewerQualities(){return a(this,Jt).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,Jt).maxVideoStreams}get maxScreenShareCount(){return a(this,Jt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,oo)).filter(t=>a(this,oo)[t].disabled)}get designTokens(){return a(this,bs).designTokens}get configDiff(){return a(this,bs).configDiff}get mediaConstraints(){var t,e,r,i,n,s,o,c,d,l,h,p,v,S,T,C,b,R,j,B,w,ee,re,ae;return{audio:{enableStereo:(i=(r=(e=(t=a(this,Jt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:Zn.audio.enableStereo,enableHighBitrate:(c=(o=(s=(n=a(this,Jt))==null?void 0:n.media)==null?void 0:s.audio)==null?void 0:o.enableHighBitrate)!=null?c:Zn.audio.enableHighBitrate},video:{quality:(p=(h=(l=(d=a(this,Jt))==null?void 0:d.media)==null?void 0:l.video)==null?void 0:h.quality)!=null?p:Zn.video.quality,frameRate:(C=(T=(S=(v=a(this,Jt))==null?void 0:v.media)==null?void 0:S.video)==null?void 0:T.frameRate)!=null?C:Zn.video.frameRate},screenshare:{quality:(B=(j=(R=(b=a(this,Jt))==null?void 0:b.media)==null?void 0:R.screenshare)==null?void 0:j.quality)!=null?B:Zn.screenshare.quality,frameRate:(ae=(re=(ee=(w=a(this,Jt))==null?void 0:w.media)==null?void 0:ee.screenshare)==null?void 0:re.frameRate)!=null?ae:Zn.screenshare.frameRate}}}get name(){return a(this,sd)}};let N1=co;Jt=new WeakMap,bs=new WeakMap,sd=new WeakMap,oo=new WeakMap;var V1=Object.defineProperty,L1=Object.getOwnPropertyDescriptor,Ty=(t,e,r,i)=>{for(var n=i>1?void 0:i?L1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&V1(e,r,n),n},lo,ad;class Ip extends Zt{constructor(e,r){const i=e.getValue("logger");super(i),g(this,lo,void 0),m(this,"state","IDLE"),m(this,"playbackUrl"),m(this,"ingestionCredentials"),m(this,"viewerCount"),g(this,ad,void 0),f(this,lo,r),f(this,ad,e),this.viewerCount=0}get telemetry(){return a(this,ad).getValue("telemetry")}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}start(){return u(this,arguments,function*(e={manualIngestion:!1}){if(!a(this,lo).permissions.canLivestream)throw this.logger.error("DyteLivestream::start::permission_denied"),new I("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=pt(),{playbackUrl:i,ingestionCredentials:n}=yield r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=n,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw this.logger.error("DyteRecording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new I("Error while starting livestream","1900",this.logger)}})}stop(){return u(this,null,function*(){if(!a(this,lo).permissions.canLivestream)throw this.logger.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 this.logger.error("DyteLivestream::stop::inconsistent_state"),new I("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),yield pt().stopLivestreaming()}catch(e){throw this.logger.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new I("Error while stopping livestream","1900",this.logger)}})}}lo=new WeakMap,ad=new WeakMap;Ty([k.trace("livestream.start")],Ip.prototype,"start",1);Ty([k.trace("livestream.stop")],Ip.prototype,"stop",1);var x1=Object.defineProperty,U1=Object.getOwnPropertyDescriptor,F1=(t,e,r,i)=>{for(var n=i>1?void 0:i?U1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&x1(e,r,n),n},uo,ho,Ni,ti;class by{constructor(e,r,i){m(this,"livestream"),g(this,uo,void 0),g(this,ho,void 0),g(this,Ni,void 0),g(this,ti,void 0),f(this,ti,e),f(this,ho,r),this.livestream=new Ip(e,r),f(this,Ni,i),this.setupEvents()}get logger(){return a(this,ti).getValue("logger")}get telemetry(){return a(this,ti).getValue("telemetry")}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=pt(),{status:r,playbackUrl:i,manualIngest:n,ingestionCredentials:s}=yield e.getActiveLivestream();this.livestream.playbackUrl=i,this.livestream.ingestionCredentials=s,r==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),r==="INVOKED"&&n&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")})}setupEvents(){a(this,Ni).on(F.startedLivestream,e=>u(this,null,function*(){this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,ho).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}})),a(this,Ni).on(F.livestreamingInvoked,e=>u(this,null,function*(){if(e.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,ho).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}})),a(this,Ni).on(F.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,Ni).on(F.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,Ni).on(F.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),a(this,ti).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,e=>u(this,null,function*(){var r;((r=e.flags)==null?void 0:r.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(f(this,uo,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),a(this,ti).getValue("peerSessionStore").on(P.PEER_CLOSED,e=>{e.id===a(this,uo)&&(f(this,uo,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,ti).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){if(!this.livestream.playbackUrl){this.logger.info("Fetching livestreaming state on leave stage");try{yield this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Failed to fetch livestreaming state on leave stage",{error:e})}}})),a(this,ti).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch{this.logger.error("Error: LivestreamController.fetchLivestream")}}))}}uo=new WeakMap,ho=new WeakMap,Ni=new WeakMap,ti=new WeakMap;F1([k.trace("LivestreamController.setupEvents")],by.prototype,"setupEvents",1);var B1=Object.defineProperty,W1=Object.getOwnPropertyDescriptor,sc=(t,e,r,i)=>{for(var n=i>1?void 0:i?W1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&B1(e,r,n),n},wt,vn,yn,ah,wy;class ra{constructor({name:e,socketHandler:r,meetingId:i}){g(this,ah),m(this,"name",""),g(this,wt,{}),g(this,vn,""),g(this,yn,void 0),m(this,"rateLimitConfig",{maxInvocations:5,period:1}),m(this,"bulkRateLimitConfig",{maxInvocations:5,period:1}),m(this,"listeners",{}),this.name=e,f(this,yn,r),f(this,vn,i)}set(e,r,i=!0,n=!1){return u(this,null,function*(){a(this,wt)[e]=r,i&&this.remoteSet(e,r),n&&(this.listeners[e]&&this.listeners[e].forEach(s=>s({[e]:a(this,wt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:a(this,wt)[e]})))})}remoteSet(e,r){a(this,yn).storeInsertKeys(a(this,vn),this.name,[{key:e,payload:r}])}bulkSet(e){return u(this,null,function*(){e.forEach(({key:r,payload:i})=>{a(this,wt)[r]=i}),a(this,yn).storeInsertKeys(a(this,vn),this.name,e)})}update(e,r,i=!0){return u(this,null,function*(){U(this,ah,wy).call(this,e,r,i)})}delete(e,r=!0,i=!1){return u(this,null,function*(){if(a(this,wt)[e]&&delete a(this,wt)[e],r)return a(this,yn).storeDeleteKeys(a(this,vn),this.name,[{key:e}]);i&&(this.listeners[e]&&(this.listeners[e].forEach(n=>n({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[e]:void 0})))})}bulkDelete(e){return u(this,null,function*(){return e.forEach(({key:r})=>{a(this,wt)[r]&&delete a(this,wt)[r]}),a(this,yn).storeDeleteKeys(a(this,vn),this.name,e)})}get(e){if(a(this,wt)[e])return a(this,wt)[e]}getAll(){return a(this,wt)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(e,r){this.rateLimitConfig.maxInvocations=e,this.rateLimitConfig.period=r}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(e,r){this.bulkRateLimitConfig.maxInvocations=e,this.bulkRateLimitConfig.period=r}subscribe(e,r){if(this.listeners[e]){this.listeners[e].push(r);return}this.listeners[e]=[r]}unsubscribe(e,r){var i;if(r){this.listeners[e]=((i=this.listeners[e])==null?void 0:i.filter(n=>n!==r))||[];return}this.listeners[e]&&delete this.listeners[e]}populate(e){f(this,wt,e)}}wt=new WeakMap,vn=new WeakMap,yn=new WeakMap,ah=new WeakSet,wy=function(t,e,r=!0){let i;const n=a(this,wt)[t],s=Object.prototype.toString.call(e),o=Object.prototype.toString.call(n);if(s!==o){this.set(t,e);return}switch(o){case"[object Array]":i=[...n,...e];break;case"[object Object]":i=V(V({},n),e);break;case"[object Map]":i=new Map([...n,...e]);break;case"[object Set]":i=new Set([...n,...e]);break;default:i=e;break}this.set(t,i,r)};sc([Bt(ta,"rateLimitConfig")],ra.prototype,"remoteSet",1);sc([Bt(ta,"bulkRateLimitConfig")],ra.prototype,"bulkSet",1);sc([Bt(ta,"rateLimitConfig")],ra.prototype,"update",1);sc([Bt(ta,"rateLimitConfig")],ra.prototype,"delete",1);sc([Bt(ta,"bulkRateLimitConfig")],ra.prototype,"bulkDelete",1);var xs,Us,od,cu,Yd,Mn,oh,_y;class j1{constructor(e,r){g(this,od),g(this,oh),m(this,"stores",new Map),g(this,xs,void 0),g(this,Us,""),g(this,Yd,void 0),g(this,Mn,new Map),f(this,xs,r),f(this,Us,e.getValue("meetingId")),f(this,Yd,e),U(this,oh,_y).call(this)}create(e){const r=new ra({name:e,socketHandler:a(this,xs),meetingId:a(this,Us)});return a(this,xs).storeGetKeys(a(this,Us),e,[]),new Promise((i,n)=>{const s=setTimeout(()=>n(Error("Failed")),3e3);a(this,Mn).set(e,{rejectTimeout:s,resolve:i,store:r})})}}xs=new WeakMap,Us=new WeakMap,od=new WeakSet,cu=function(){return a(this,Yd).getValue("peerId")},Yd=new WeakMap,Mn=new WeakMap,oh=new WeakSet,_y=function(){[J.storeInsertKeys,J.storeGetKeys,J.storeDeleteKeys].forEach(t=>{a(this,xs).on(t,e=>u(this,null,function*(){var r,i;if(e.pluginId!==a(this,Us))return;const n=(r=e.storeItems)==null?void 0:r.map(o=>{var c;return{timestamp:o.timestamp,peerId:o.peerId,payload:JSON.parse((c=o.payload)!=null&&c.length?new TextDecoder().decode(o.payload):"{}"),key:o.storeKey}});if(t===J.storeGetKeys){const o=a(this,Mn).get(e.storeName),c=this.stores.get(e.storeName)||(o==null?void 0:o.store);a(this,Mn).get(e.storeName)&&(this.stores.set(e.storeName,o.store),o.resolve(c),clearTimeout(o.rejectTimeout),a(this,Mn).delete(e.storeName)),n.forEach(d=>{c.set(d.key,d.payload,!1,!1)});return}const s=this.stores.get(e.storeName)||((i=a(this,Mn).get(e.storeName))==null?void 0:i.store);s!==void 0&&(t===J.storeInsertKeys&&n.forEach(({key:o,peerId:c,payload:d})=>{c!==a(this,od,cu)&&s.set(o,d,!1,!0)}),t===J.storeDeleteKeys&&n.forEach(({key:o,peerId:c})=>{c!==a(this,od,cu)&&s.delete(o,!1,!0)}))}))})};function An(t){var e,r,i,n,s,o,c,d,l,h,p,v,S;return t?{media:{audio:{enabled:t.audioEnabled,trackId:(e=t.audioTrack)==null?void 0:e.id,permission:"mediaPermissions"in t?(r=t.mediaPermissions)==null?void 0:r.audio:null},video:{enabled:t.videoEnabled,trackId:(i=t.videoTrack)==null?void 0:i.id,permission:"mediaPermissions"in t?(n=t.mediaPermissions)==null?void 0:n.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(s=t.mediaPermissions)==null?void 0:s.screenshare:null,audio:{enabled:(c=(o=t.screenShareTracks)==null?void 0:o.audio)==null?void 0:c.enabled,trackId:(l=(d=t.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(p=(h=t.screenShareTracks)==null?void 0:h.video)==null?void 0:p.enabled,trackId:(S=(v=t.screenShareTracks)==null?void 0:v.video)==null?void 0:S.id}}}}:{}}var H1=Object.defineProperty,G1=Object.getOwnPropertyDescriptor,ia=(t,e,r,i)=>{for(var n=i>1?void 0:i?G1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&H1(e,r,n),n};const q1=.8,$1=1.2;var xa,Ua,sr,es,Fa,cn,ts,rs,Ba,du,Ig,Ti,Cc,dn,is,Wa,bi,lu,Pc,uu,hu,Cg,pu,Pg,Rg;let fi=(Rg=class extends Zt{constructor(t,e,r,i){const n=t.getValue("logger");super(n),g(this,es),g(this,cn),g(this,rs),g(this,du),g(this,is),g(this,Pc),g(this,hu),g(this,pu),m(this,"id"),m(this,"userId"),m(this,"name"),m(this,"picture"),m(this,"isHost"),m(this,"customParticipantId"),m(this,"flags"),m(this,"device"),m(this,"videoTrack"),m(this,"audioTrack"),m(this,"screenShareTracks"),m(this,"videoEnabled"),m(this,"audioEnabled"),m(this,"screenShareEnabled"),m(this,"producers"),m(this,"manualProducerConfig"),g(this,xa,void 0),m(this,"supportsRemoteControl",!1),g(this,Ua,void 0),m(this,"presetName"),g(this,sr,void 0),g(this,Ti,void 0),g(this,Cc,void 0),g(this,dn,new Map),g(this,bi,1),g(this,lu,fp(ee=>{if(!this.videoTrack)return;const{clientWidth:re,clientHeight:ae}=ee,{width:Me,height:Ze}=this.videoTrack.getSettings();if(!Me||!Ze)return;const jt=Ze/ae,A=Me/re,E=Math.max(jt,A);E>$1&&a(this,bi)===1?(f(this,bi,0),a(this,sr).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,bi)})):E<q1&&a(this,bi)===0&&(f(this,bi,1),a(this,sr).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,bi)}))},2e3)),f(this,sr,t);const{id:s,userId:o,displayName:c,device:d,picture:l,isHost:h,flags:p,clientSpecificId:v,stageStatus:S,customParticipantId:T,audioMuted:C,audioTrack:b,videoEnabled:R=!1,videoTrack:j,producers:B,metadata:w}=e;this.id=s,this.userId=o,this.name=c,this.device=d,this.picture=l,this.isHost=h,this.flags=p,this.manualProducerConfig=II,f(this,Ua,S!=null?S:"ON_STAGE"),this.customParticipantId=T!=null?T:v,this.audioEnabled=!C,this.audioTrack=b,this.videoEnabled=R,this.videoTrack=j,this.screenShareTracks={audio:void 0,video:void 0},this.producers=B!=null?B:[],this.presetName=w==null?void 0:w.preset_name,f(this,xa,!1),f(this,Ti,r),f(this,Cc,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),U(this,Pc,uu).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return a(this,Ua)}get telemetry(){return a(this,sr).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("DyteParticipant::setVideoEnabled::videoUpdate",V({},An(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("DyteParticipant::setAudioEnabled::audioUpdate",V({},An(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",U(this,Pc,uu)),a(this,cn,ts)&&(this.on("audioUpdate",U(this,hu,Cg)),this.on("screenShareUpdate",U(this,pu,Pg)))}pin(){return u(this,null,function*(){if(!a(this,rs,Ba))throw new I("Can`t pin participant without joining room","1205");if(!a(this,Ti).permissions.pinParticipant)throw new I("You do not have permission to pin participants.","1201");return a(this,es,Fa).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!a(this,rs,Ba))throw new I("Can`t unpin participant without joining room","1205");if(!a(this,Ti).permissions.pinParticipant)throw new I("You do not have permission to unpin participants.","1201");return a(this,es,Fa).pinPeer(null)})}setIsPinned(t,e=!0){var r;f(this,xa,t);const i=t?"pinned":"unpinned";(r=a(this,is,Wa))==null||r.updateSource(this.id,{pinned:t}),e&&this.emit(i,this)}disableAudio(){return u(this,null,function*(){const t=this.id;if(this.logger.info("DyteParticipant::disable_audio",{dyteParticipant:{id:t}}),!a(this,rs,Ba))throw new I("Can`t disable participant audio without joining room","1205");if(a(this,Ti).permissions.canDisableParticipantAudio)return a(this,es,Fa).disableAudio(t);throw this.logger.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(this.logger.info("DyteParticipant::kick",{dyteParticipant:{id:t}}),!a(this,du,Ig))throw new I("Can`t kick participant without joining room","1205");if(a(this,Ti).permissions.kickParticipant){yield a(this,sr).getValue("peerSessionStore").emitAsync(P.KICK_PEER,{peerId:t});return}throw this.logger.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(this.logger.info("DyteParticipant::disable_video",{dyteParticipant:{id:t}}),!a(this,rs,Ba))throw new I("Can`t disable participant video without joining room","1205");if(a(this,Ti).permissions.canDisableParticipantVideo)return a(this,es,Fa).disableVideo(t);throw this.logger.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 a(this,Cc).getUserPermissions(this.userId)})}setStageStatus(t){f(this,Ua,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,xa)}registerVideoElement(t){var e,r,i,n;if(!t)return;let s;(r=(e=a(this,dn).get(t))==null?void 0:e.observer)==null||r.disconnect(),"ResizeObserver"in window&&(s=new ResizeObserver(()=>a(this,lu).call(this,t)),s.observe(t)),a(this,dn).set(t,{observer:s}),this.updateVideo(t),(n=a(this,is,Wa))==null||n.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(i=this.raised)!=null?i:!1)}deregisterVideoElement(t){var e,r,i,n;if(!t){(e=a(this,is,Wa))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,dn).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,dn).delete(t),(n=a(this,is,Wa))==null||n.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((r==null?void 0:r.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"}},xa=new WeakMap,Ua=new WeakMap,sr=new WeakMap,es=new WeakSet,Fa=function(){return a(this,sr).getValue("roomNodeClient")},cn=new WeakSet,ts=function(){return a(this,sr).getValue("audioPlayback")},rs=new WeakSet,Ba=function(){return a(this,sr).getValue("connectionHandler").mediaJoined},du=new WeakSet,Ig=function(){return a(this,sr).getValue("connectionHandler").socketJoined},Ti=new WeakMap,Cc=new WeakMap,dn=new WeakMap,is=new WeakSet,Wa=function(){return a(this,sr).getValue("pip")},bi=new WeakMap,lu=new WeakMap,Pc=new WeakSet,uu=function(){Array.from(a(this,dn).keys()).forEach(this.updateVideo)},hu=new WeakSet,Cg=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,cn,ts))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,cn,ts))==null||e.removeParticipantTrack(this.id)},pu=new WeakSet,Pg=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,cn,ts))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,cn,ts))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},Rg);ia([k.trace("DyteParticipant.disableAudio")],fi.prototype,"disableAudio",1);ia([k.trace("DyteParticipant.kick")],fi.prototype,"kick",1);ia([k.trace("DyteParticipant.disableVideo")],fi.prototype,"disableVideo",1);ia([k.trace("DyteParticipant.getPermissions")],fi.prototype,"getPermissions",1);ia([k.trace("DyteParticipant.setStageStatus")],fi.prototype,"setStageStatus",1);fi=ia([ft("1200")],fi);class ja extends fy{constructor(e,r){const{onAddEvent:i="participantJoined",onDeleteEvent:n="participantLeft",onClearEvent:s="participantsCleared"}=r!=null?r:{};super({onAddEvent:i,onDeleteEvent:n,onClearEvent:s},e)}add(e,r=!0){return this.has(e.id)&&Object.is(this.get(e.id),e)===!1&&this.delete(e.id),super.add(e,r)}clear(e=!0,r=!1){return super.clear(e,r)}delete(e,r=!0,i=!1){return super.delete(e,r,i)}}var Sn;class J1 extends Zs{constructor(e){super(e),g(this,Sn,void 0),f(this,Sn,new Map)}__set(e,r){return a(this,Sn).set(e,r)}__clear(){return a(this,Sn).clear()}get(e){return a(this,Sn).get(e)}toArray(){return Array.from(a(this,Sn).values())}}Sn=new WeakMap;class K1{constructor(){m(this,"_orderedArray"),m(this,"_map"),this._map=new Map,this._orderedArray=[]}add(e,r){if(!this._map.has(e))return this._map.set(e,{peerId:e,priority:r}),this._orderedArray.splice(Math.max(r-1,0),0,e),this.index(e);const i=this.index(e);this.delete(e);const n=this.add(e,r);return i!==n?n:-1}delete(e){if(this._map.has(e)){const r=this.index(e);this._map.delete(e),this._orderedArray.splice(r,1)}}index(e){return this._map.has(e)?this._orderedArray.indexOf(e):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class z1{constructor(){m(this,"_activeSpeakerPeers"),m(this,"_compulsoryPeers"),this._activeSpeakerPeers=new K1,this._compulsoryPeers=new Set}add(e,r,i){if(!e)return-1;if(r<0)return this._compulsoryPeers.add(e),0;const n=i.getValue("logger");if(this.compulsoryPeers.includes(e)&&(r>0||r===246267631)){if(n.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),r===246267631)return-1}else if(r===229490415)return this.delete(e,i),-1;return this._activeSpeakerPeers.add(e,r)}delete(e,r){const i=r==null?void 0:r.getValue("logger");i==null||i.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 Iy=new z1;var Y1=Object.defineProperty,Q1=Object.getOwnPropertyDescriptor,rr=(t,e,r,i)=>{for(var n=i>1?void 0:i?Q1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&Y1(e,r,n),n};const X1=["ACTIVE_GRID","PAGINATED","MANUAL"];var Ae,Rc,mu,ns,Ha,Ga,Mc,ss,Ht,Mg;let Rt=(Mg=class extends Zt{constructor(t,e,r){const i=t.getValue("logger");super(i),g(this,Rc),g(this,ns),g(this,Ga),m(this,"waitlisted"),m(this,"joined"),m(this,"active"),m(this,"videoSubscribed"),m(this,"audioSubscribed"),m(this,"pinned"),m(this,"all"),g(this,Ae,void 0),g(this,ss,void 0),g(this,Ht,void 0),m(this,"rateLimitConfig",{maxInvocations:5,period:1}),m(this,"viewMode"),m(this,"currentPage"),m(this,"lastActiveSpeaker"),m(this,"selectedPeers",Iy),f(this,Ae,t),f(this,ss,e),f(this,Ht,r),this.waitlisted=new ja(i),this.joined=new ja(i),this.videoSubscribed=new ja(i),this.audioSubscribed=new ja(i),this.active=this.videoSubscribed,this.pinned=new ja(i),this.all=new J1(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,Ae).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,Ae).getValue("telemetry")}setupEvents(){a(this,Ae).getValue("peerSessionStore").on(P.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,Ae).getValue("modules").e2ee)==null?void 0:r.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${e}, but encryption wasn't enabled in init.defaults`,code:"1702"})});const t=a(this,Ae).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=a(this,Ae))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new I("0 <= Max active participants count limit <= 24","1203");a(this,Ae).setValue("maxPreferredStreams",t),a(this,Ga,Mc)&&a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(r=>r.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var e,r;if(!a(this,ns,Ha))throw new I("Can`t accept waiting room request without joining room","1205");const i=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;return a(this,Ht).acceptWaitingRoomRequest([i])}acceptAllWaitingRoomRequest(t){return u(this,null,function*(){const e=t.map(r=>{var i,n;return(n=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?n:r});return a(this,Ht).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return u(this,null,function*(){var e,r;if(!a(this,ns,Ha))throw new I("Can`t reject waiting room request without joining room","1205");const i=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;a(this,Ht).rejectWaitingRoomRequest([i])})}setViewMode(t){return u(this,null,function*(){if(this.logger.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(e=>X1.includes(e))(t))throw this.logger.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){this.logger.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})})}subscribe(t){return u(this,arguments,function*(e,r=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new I("MANUAL subscription mode was not activated.","1206");e.forEach(i=>{const n=this.joined.get(i);n&&(r.includes("audio")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{audio:!0}),this.audioSubscribed.has(n.id)||this.audioSubscribed.add(n)),r.includes("video")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{video:!0}),this.videoSubscribed.has(n.id)||this.videoSubscribed.add(n)),r.includes("screenshareAudio")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareAudio:!0}),this.audioSubscribed.has(n.id)||this.audioSubscribed.add(n)),r.includes("screenshareVideo")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareVideo:!0}),this.videoSubscribed.has(n.id)||this.videoSubscribed.add(n)))}),a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})})}unsubscribe(t){return u(this,arguments,function*(e,r=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new I("MANUAL subscription mode was not activated.","1206");e.forEach(i=>{const n=this.joined.get(i);n&&(r.includes("audio")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{audio:!1}),n.manualProducerConfig.screenshareAudio||this.audioSubscribed.delete(n.id)),r.includes("video")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{video:!1}),n.manualProducerConfig.screenshareVideo||this.videoSubscribed.delete(n.id)),r.includes("screenshareAudio")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareAudio:!1}),n.manualProducerConfig.audio||this.audioSubscribed.delete(n.id)),r.includes("screenshareVideo")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareVideo:!1}),n.manualProducerConfig.video||this.videoSubscribed.delete(n.id)))}),a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})})}getPeerIdsForCurrentPage(){this.logger.info("DyteParticipants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(o=>this.joined.has(o)),r=Array.from(this.pinned.keys()).filter(o=>!e.includes(o)),i=Array.from(this.joined.toArray().filter(o=>o.stageStatus==="ON_STAGE").map(o=>o.id)),n=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),s=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(n,s))}setPage(t){return u(this,null,function*(){if(this.logger.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 this.logger.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,a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}})}disableAllAudio(t){return u(this,null,function*(){if(this.logger.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!a(this,Ga,Mc))throw new I("Can`t disable all audio without joining room","1205");if(a(this,ss).permissions.canAllowParticipantAudio)return a(this,Rc,mu).muteAll(t);throw this.logger.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(this.logger.info("DyteParticipants::disable_all_video"),!a(this,Ga,Mc))throw new I("Can`t disable all video without joining room","1205");if(a(this,ss).permissions.canAllowParticipantVideo)return a(this,Rc,mu).muteAllVideo();throw this.logger.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 a(this,Ae).getValue("peerSessionStore").emitAsync(P.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(this.logger.info("DyteParticipants::kick_all"),a(this,Ae).getValue("viewType")!=="LIVESTREAM"&&!a(this,ns,Ha))throw new I("Can`t kick all without joining room","1205");if(!a(this,ss).permissions.kickParticipant)throw this.logger.error("DyteParticipants::unauthorized_kick_all"),new I("Unauthorized: User does not have permission to kick peers.","1201");const t=a(this,Ae).getValue("flagsmith").hasFeature(Z.PROPAGATE_KICK_ALL);a(this,Ht).kickAll(t)})}broadcastMessage(t,e,r){return u(this,null,function*(){if(this.logger.info("DyteParticipants::broadcastMessage"),!a(this,ns,Ha))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(r)if("meetingIds"in r)yield a(this,Ht).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(n=>{var s;return(s=r.presetNames)==null?void 0:s.includes(n.presetName)}).map(n=>n.id),yield a(this,Ht).broadcastToPeers(t,i,e)}else yield a(this,Ht).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,r){return u(this,null,function*(){return(yield a(this,Ht).getRoomPeers(t,e,r)).peers.map(Ei.formatSocketPeerMessage)})}updatePermissions(t,e){return u(this,null,function*(){const r=this.joined.toArray().filter(n=>t.includes(n.id)).map(n=>n.userId),i=[...new Set(r)];if(!i.length)throw new I("Cannot update permissions, no valid userIDs found","1204");a(this,Ht).updatePermissions(i,e)})}getParticipantsInMeetingPreJoin(){return u(this,null,function*(){return a(this,Ht).getRoomPeersNonPaginated()})}},Ae=new WeakMap,Rc=new WeakSet,mu=function(){return a(this,Ae).getValue("roomNodeClient")},ns=new WeakSet,Ha=function(){var t;return((t=a(this,Ae).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Ga=new WeakSet,Mc=function(){var t;return((t=a(this,Ae).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},ss=new WeakMap,Ht=new WeakMap,Mg);rr([k.trace("DyteParticipants.setViewMode")],Rt.prototype,"setViewMode",1);rr([k.trace("DyteParticipants.setPage")],Rt.prototype,"setPage",1);rr([k.trace("DyteParticipants.disableAllAudio")],Rt.prototype,"disableAllAudio",1);rr([k.trace("DyteParticipants.disableAllVideo")],Rt.prototype,"disableAllVideo",1);rr([k.trace("DyteParticipants.disablePeerAudio")],Rt.prototype,"disableAudio",1);rr([k.trace("DyteParticipants.disablePeerVideo")],Rt.prototype,"disableVideo",1);rr([k.trace("DyteParticipants.kickPeer")],Rt.prototype,"kick",1);rr([k.trace("DyteParticipants.kickAll")],Rt.prototype,"kickAll",1);rr([k.trace("DyteParticipants.broadcastMessage"),Bt(ta,"rateLimitConfig")],Rt.prototype,"broadcastMessage",1);rr([k.trace("DyteParticipants.getAllJoinedPeers"),Bt({maxInvocations:10,period:60})],Rt.prototype,"getAllJoinedPeers",1);rr([k.trace("DyteParticipant.updatePermissions"),Bt({maxInvocations:1e3,period:60})],Rt.prototype,"updatePermissions",1);rr([k.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],Rt.prototype,"getParticipantsInMeetingPreJoin",1);Rt=rr([ft("1200")],Rt);var Xs=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t.CLOSED="closed",t))(Xs||{}),Oe=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(Oe||{}),Z1=Object.defineProperty,eN=Object.getOwnPropertyDescriptor,$n=(t,e,r,i)=>{for(var n=i>1?void 0:i?eN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&Z1(e,r,n),n},gr,Vr,qa,Ag;const Cy=(Ag=class{constructor(t,e,r,i){switch(m(this,"participants"),m(this,"self"),m(this,"selectedPeers",Iy),m(this,"maxSpatialLayerUpdates",new Map),m(this,"consumerPeerMap"),m(this,"events"),m(this,"roomSocketHandler"),m(this,"context"),m(this,"videoPeerConsumerMap",new Map),g(this,gr,{mode:"ACTIVE_GRID",page:0}),g(this,Vr,!1),g(this,qa,!1),m(this,"updateConsumerSpatialLayers",fp(()=>{const n={},s=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(s.entries()).forEach(([o,c])=>{n[c]===void 0&&(n[c]={layer:c,consumerIds:[]}),n[c].consumerIds.push(o)}),Object.keys(n).forEach(o=>{const c=n[o];this.logger.log(`Switching max spatial layer to ${c.layer}`,{consumerIds:c.consumerIds}),this.roomNodeClient.switchConsumersToLayer(c.consumerIds,c.layer)})},2e3)),m(this,"updateConsumers",(n,s)=>u(this,null,function*(){this.logger.info(`updateConsumers: Starting consumer updates - AddProducers: ${n.length}, RemoveProducers: ${s.length}, ConsumersSyncing: ${a(this,Vr)}`);try{n.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for ${n.length} producers: [${n.map(o=>o.producerId).join(", ")}]`),yield this.roomNodeClient.createConsumers(n),this.logger.info("updateConsumers: Successfully created consumers."))}catch(o){this.logger.error("updateConsumers: Error creating consumers",{error:o})}try{s.length!==0&&(this.logger.info(`updateConsumers: Closing consumers for ${s.length} producers: [${s.map(o=>o.producerId).join(", ")}]`),yield this.roomNodeClient.closeConsumers(s),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(o){this.logger.error("updateConsumers: Error closing consumers",{error:o})}this.logger.info("updateConsumers: Completed consumer updates.")})),this.context=t,this.roomSocketHandler=r,this.participants=new Rt(t,e,this.roomSocketHandler),this.self=e,this.consumerPeerMap=new Map,i){case Oe.HIVE:{this.events=dr;break}case Oe.CF:{this.events=Ir;break}default:this.events=dr}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")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}setupEvents(){this.roomSocketHandler.on(F.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(P.SOCKET_PEERS,t=>u(this,null,function*(){const e=this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN);if(e){const r=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(i=>i.peerId))}:void 0;this.logger.info("Processing socket peers",r)}t==null||t.forEach(r=>{r.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(r))}),e&&this.logger.info("Processed socket peers")})),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:t})=>{this.logger.info("events.peerJoinedBroadcast",{peers:t.peerId}),this.onParticipantMediaJoined(t.peerId,t.producerStates,t.capabilities)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:t,selectedPeers:e,roomState:r})=>{if(this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN)){const s=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(o=>o.peerId))}:void 0;this.logger.info("events.selfJoinComplete",s)}t.forEach(({peerId:s,producerStates:o,capabilities:c})=>this.onParticipantMediaJoined(s,o,c));const{audioPeers:i,compulsoryPeers:n}=e!=null?e:{};r.pinnedPeerIds.length!==0&&this.onParticipantPinned(r.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],n),this.logger.info("selfJoinComplete: Emitting UPDATE_ACTIVE with createAllConsumers=true"),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{createAllConsumers:!0})}),this.context.getValue("peerSessionStore").on(P.MAX_SPATIAL_LAYER_CHANGE,({peerId:t,maxSpatialLayer:e})=>{const r=this.videoPeerConsumerMap.get(t);r&&(this.context.getValue("flagsmith").hasFeature(Z.DISABLE_LAYER_SWITCH)||(this.maxSpatialLayerUpdates.set(r,e),this.updateConsumerSpatialLayers()))}),this.context.getValue("peerSessionStore").on(P.NEW_PRODUCER,({peerId:t,producer:e})=>{const r=this.participants.joined.get(t);if(!r){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:e==null?void 0:e.producerId,kind:e==null?void 0:e.kind,status:"not_initialized",appData:{screenShare:e==null?void 0:e.screenShare}},dyteParticipant:{id:t}});return}r.producers.push(e),this.logger.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:"not_initialized",appData:{screenShare:e==null?void 0:e.screenShare}}}),(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.logger.info(`NEW_PRODUCER: scheduling syncConsumer (AUTO mode) - Producer: ${e.producerId}, Peer: ${t}, Kind: ${e.kind}, ScreenShare: ${e.screenShare}, ConsumersSyncing: ${a(this,Vr)}, VideoSub: ${e.kind==="video"?this.participants.videoSubscribed.has(t):"N/A"}, AudioSub: ${e.kind==="audio"?this.participants.audioSubscribed.has(t):"N/A"}`),this.scheduleSyncConsumers({source:"NEW_PRODUCER_AUTO"})):this.logger.info("ParticipantController::NEW_PRODUCER::not_consuming_producer_auto",{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.context.getValue("peerSessionStore").on(P.PRODUCER_CLOSED,({peerId:t,producerId:e})=>{const r=this.participants.joined.get(t);if(!r){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:t}});return}r.producers=r.producers.filter(i=>i.producerId!==e)}),this.context.getValue("peerSessionStore").on(P.PRODUCER_TOGGLE,({peerId:t,producerId:e,paused:r,kind:i})=>{const n=this.participants.joined.get(t);if(n){i==="audio"&&n.setAudioEnabled(!r);const s=n.producers.find(o=>o.producerId===e);s&&(s.pause=r),i==="video"&&this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,t=>{let e;if(t&&(e=t.participantId),!this.mediaJoined)return;const r=e;this.onParticipantPinned(r);const i=this.participants.joined.get(r);i&&(this.logger.info(`globalPeerPinBroadcast: Scheduling audio/video consumer sync for pinned participant ${r} - ProducerCount: ${i.producers.length}, ConsumersSyncing: ${a(this,Vr)}, ProducerIds: [${i.producers.map(n=>n.producerId).join(", ")}]`),this.scheduleSyncConsumers({source:"GLOBAL_PEER_PIN"}))}),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(r=>({peerId:r.peerId,priority:r.priority}));this.updateActiveParticipantsWithPriorities(e,!0)})}waitingRoomRequestHandler(t){const e=t.requests.filter(i=>!this.participants.waitlisted.toArray().find(n=>n.userId===i.userId)),r=this.participants.waitlisted.toArray().filter(i=>!t.requests.find(n=>n.userId===i.userId));e.forEach(i=>this.participants.waitlisted.add(new fi(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))),r.forEach(i=>this.participants.waitlisted.delete(i.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(t){const{compulsoryPeers:e}=this.selectedPeers,r=e.filter(c=>this.participants.joined.has(c)),i=Array.from(this.participants.pinned.keys()).filter(c=>!r.includes(c)),n=Array.from(this.participants.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),s=Math.max((t-1)*(this.maxPreferredStreams-r.length-i.length)),o=t*(this.maxPreferredStreams-r.length-i.length);return r.concat(i,n.slice(s,o))}selectActivePeers(t){const e=new Map,r=Array.from(this.participants.joined.toArray().filter(h=>h.stageStatus==="ON_STAGE").map(h=>(e.set(h.id,!0),h.id))),i=this.selectedPeers.peers,n=this.participants.pinned.toArray().reduce((h,p)=>(p.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(p.id):h.push(p.id),h),[]),s=this.self.stageStatus==="ON_STAGE"?1:0,o=t-s,c=new Set(i.concat(n).filter(h=>h!==this.self.id&&e.has(h)));let d=Array.from(c);const l=o-c.size;if(l>=0){const h=r.filter(p=>!c.has(p)&&p!==this.self.id).slice(0,l);d=Array.from(c).concat(h)}else d=d.slice(0,o);return d}updateMediaSubscribedMaps(t,e){const{page:r}=e!=null?e:{};t&&a(this,gr).mode!==t&&(a(this,gr).mode=t),r&&a(this,gr).page!==r&&(a(this,gr).page=r);const{mode:i,page:n}=a(this,gr);switch(i){case"PAGINATED":{if(!n)return;const s=this.selectPagePeers(n),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,s),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:s});break}case"ACTIVE_GRID":{const s=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,s),this.updateParticipantsMap(this.participants.audioSubscribed,o);break}case"MANUAL":break;default:throw new Error(`View mode ${t} not supported`)}}scheduleSyncConsumers(t){return u(this,arguments,function*({source:e}){var r,i,n;const s=((r=a(this,gr))==null?void 0:r.mode)==="PAGINATED"&&!a(this,Vr)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${e}, ViewMode: ${(i=a(this,gr))==null?void 0:i.mode}, ConsumersSyncing: ${a(this,Vr)}, Delay: ${s}, Page: ${(n=a(this,gr))==null?void 0:n.page}`),setTimeout(()=>this.syncConsumers(),s)})}syncConsumers(){return u(this,null,function*(){var t,e,r,i,n;if(((r=(e=(t=this.context.getValue("connectionHandler"))==null?void 0:t.mediaState)==null?void 0:e.recv)==null?void 0:r.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(a(this,Vr)){f(this,qa,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),f(this,Vr,!0),f(this,qa,!1);let s=[];this.participants.videoSubscribed.forEach(p=>{var v,S;const T=this.participants.joined.get(p.id),C=(S=(v=p.producers)==null?void 0:v.filter(b=>b.kind==="video"))!=null?S:[];T&&C!=null&&C.length&&C.forEach(b=>{var R,j,B,w;const ee=((j=(R=T.manualProducerConfig)==null?void 0:R.video)!=null?j:!0)&&b.kind==="video"&&!b.screenShare,re=((w=(B=T.manualProducerConfig)==null?void 0:B.screenshareVideo)!=null?w:!0)&&b.kind==="video"&&b.screenShare;(ee||re)&&(b.pause||s.push(b))})}),this.participants.audioSubscribed.forEach(p=>{var v,S;const T=this.participants.joined.get(p.id),C=(S=(v=p.producers)==null?void 0:v.filter(b=>b.kind==="audio"))!=null?S:[];T&&C!=null&&C.length&&C.forEach(b=>{var R,j,B,w;const ee=((j=(R=T.manualProducerConfig)==null?void 0:R.audio)!=null?j:!0)&&b.kind==="audio"&&!b.screenShare,re=((w=(B=T.manualProducerConfig)==null?void 0:B.screenshareAudio)!=null?w:!0)&&b.kind==="audio"&&b.screenShare;(ee||re)&&s.push(b)})}),s=bI(s,p=>p.producerId);const o=new Map;s.forEach(p=>{o.set(p.producerId,p)});const c=(i=this.roomNodeClient)==null?void 0:i.getConsumers(),d=s.filter(p=>!(c!=null&&c.has(p.producerId))),l=[];let h=Array.from((n=c==null?void 0:c.values())!=null?n:[]).map(p=>p.peerId);h=TI(h),h==null||h.forEach(p=>{var v;const S=this.participants.joined.get(p);if(!S){this.logger.warn(`Peer with ${p} doesn't exist in joined list but producers of it are being consumed.`);return}(v=S.producers)!=null&&v.length&&S.producers.forEach(T=>{const C=T.consumer&&c.has(T.consumer.id);!o.has(T.producerId)&&(c.has(T.producerId)||C)&&l.push(T)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${d.length} [${d.map(p=>p.producerId).join(", ")}], RemoveProducers: ${l.length} [${l.map(p=>p.producerId).join(", ")}]`.substring(0,5e3));try{d.length>0||l.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${d.length} and removing ${l.length}.`),yield this.updateConsumers(d,l),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(p){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:p})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),f(this,Vr,!1)}a(this,qa)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())})}computeActivateParticipants(t,e){const r=t.map((n,s)=>({peerId:n,priority:s+1})),i=e==null?void 0:e.map((n,s)=>({peerId:n,priority:-(s+1)}));r.push(...i!=null?i:[]),r.length>0&&this.updateActiveParticipantsWithPriorities(r)}createParticipantObjFromSocketPeer(t){const e=Cy.formatSocketPeerMessage(t);return new fi(this.context,q(V({},e),{isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0}),this.self,this.roomSocketHandler)}updatePipSource(t,e){var r,i;e?(r=this.pip)==null||r.enableSource(t):(i=this.pip)==null||i.disableSource(t)}onParticipantMediaJoined(t,e,r){if(!this.mediaJoined||t===this.self.id)return;const i=this.participants.joined.get(t);if(!i){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${t}`);return}this.logger.info(`onParticipantMediaJoined: peer ${t} has joined media room. Processing.`),e.forEach(n=>{n.kind===$r.AUDIO&&!n.screenShare?i.setAudioEnabled(!n.pause):n.kind===$r.VIDEO&&!n.screenShare&&(i.setVideoEnabled(!n.pause),this.updatePipSource(i.id,!n.pause)),i.producers.push(q(V({},n),{producingTransportId:n.producingTransportId,kind:n.kind===$r.AUDIO?"audio":"video",producingPeerId:t,mimeType:n.mimeType}))}),this.roomNodeClient.handlePeerCapabilities(t,r),this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||this.roomNodeClient.shareWebcam(this.self.videoTrack),this.logger.info(`onParticipantMediaJoined: Emitting UPDATE_ACTIVE for peer ${t}`),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}updateParticipantsMapMinReplacement(t,e){const r=Array.from(t.keys()),i=new Map(t),n=new Set(e),s=[];r.forEach((o,c)=>{(!n.has(o)||!this.participants.joined.get(o))&&s.push(c)}),e.forEach(o=>{if(t.get(o))return;if(r.length<e.length){r.push(o);return}const c=s.shift();r[c]=o}),s.forEach(o=>{r.splice(o,1)}),Array.from(t.keys()).forEach(o=>{t.delete(o,!n.has(o))}),r.forEach(o=>{if(!this.participants.joined.get(o)){this.logger.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:o}});return}t.add(this.participants.joined.get(o),!i.get(o))}),t.emit("participantsUpdate")}updateParticipantsMap(t,e){Array.from(t.keys()).forEach(r=>{e.includes(r)||t.delete(r,!0)}),e.forEach(r=>{t.get(r)||t.add(this.participants.joined.get(r),!0)}),t.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(t=>{t.setIsPinned(!1),this.participants.pinned.delete(t.id)})}setupEventsGlobal(){this.roomSocketHandler.on(F.joinRoom,({peer:t})=>{if(!t.waitlisted){const e=this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN);e&&this.logger.info("Processing socket join",{peers:t.peerId}),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(t)),e&&this.logger.info("Processed socket join",{peers:t.peerId})}}),this.roomSocketHandler.on(F.leaveRoom,t=>{const{peerId:e}=t.peer;this.selectedPeers.delete(e,this.context),this.onParticipantLeave(e)}),this.context.getValue("peerSessionStore").on(P.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())}),this.context.getValue("peerSessionStore").on(P.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})}),this.context.getValue("peerSessionStore").on(P.CONSUMER_PAUSED,({id:t})=>{this.processConsumerPaused(t)}),this.context.getValue("peerSessionStore").on(P.CONSUMER_RESUMED,({id:t})=>{this.processConsumerResumed(t)}),this.context.getValue("peerSessionStore").on(P.NEW_CONSUMER,({id:t})=>{this.processNewConsumer(t)}),this.context.getValue("peerSessionStore").on(P.CONSUMER_CLOSED,({id:t})=>{this.processConsumerClosed(t)}),this.context.getValue("peerSessionStore").on(P.ROOM_MESSAGE,t=>u(this,[t],function*({payload:e,type:r,timestamp:i}){this.participants.emit("broadcastedMessage",{type:r,payload:e,timestamp:i})})),this.context.getValue("peerSessionStore").on(P.MESSAGE,t=>u(this,[t],function*({payload:e,type:r,timestamp:i}){r!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:r,payload:e,timestamp:i})})),this.context.getValue("peerSessionStore").on(P.LOW_CONSUMER_SCORE,({peerId:t,score:e,kind:r})=>{const i=this.participants.joined.get(t);i&&(i.emit("poorConnection",{score:e,kind:r}),this.participants.emit("poorConnection",{participantId:t,score:e,kind:r}))}),this.context.getValue("peerSessionStore").on(P.CONSUMER_SCORE_UPDATE,({score:t,kind:e,appData:r,peerId:i,scoreStats:n})=>{var s;const o=e==="video"&&((s=r==null?void 0:r.screenShare)!=null?s:!1),c=this.participants.joined.get(i);c&&(c.emit("mediaScoreUpdate",{kind:e,isScreenshare:o,score:t,participantId:i,scoreStats:n}),this.participants.emit("mediaScoreUpdate",{kind:e,isScreenshare:o,score:t,participantId:i,scoreStats:n}))}),this.context.getValue("peerSessionStore").onAsync(P.KICK_PEER,t=>u(this,[t],function*({peerId:e}){const r=this.participants.joined.get(e);this.roomNodeClient.kick(e),yield this.roomSocketHandler.kick(e),r?r.emit("kicked"):this.participants.joined.emit("kicked",{id:e})})),this.context.getValue("peerSessionStore").on(P.UPDATE_ACTIVE,(...t)=>u(this,[...t],function*({viewMode:e,page:r,createAllConsumers:i}={viewMode:"ACTIVE_GRID",page:0,createAllConsumers:!1}){this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${a(this,gr).mode}, page: ${r}, CreateAllConsumers: ${i}`),i&&(this.logger.info(`UPDATE_ACTIVE viewMode: ${e}, Page: ${r}, Removing existing subscriptions.`),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear()),this.updateMediaSubscribedMaps(e,{page:r}),this.scheduleSyncConsumers({source:"UPDATE_ACTIVE"})}))}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)})}onParticipantSocketJoined(t){return u(this,null,function*(){var e,r,i;this.logger.info(`onParticipantSocketJoined: peer ${t.id} has joined socket edge. Processing.`),this.self.id!==t.id&&!((e=t.flags)!=null&&e.recorder)&&!((r=t.flags)!=null&&r.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"&&this.context.getValue("peerSessionStore").emit(P.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!0})),this.context.getValue("peerSessionStore").emit(P.PEER_JOINED_INTERNAL,t)})}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"&&this.context.getValue("peerSessionStore").emit(P.UPDATE_STAGE_REQUESTS,{request:{displayName:e.name,userId:e.userId,peerId:e.id},add:!1});const{currentPage:r}=this.participants,i=this.maxPreferredStreams*(r-1),n=this.participants.videoSubscribed.get(t);this.participants.viewMode==="MANUAL"?this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:r}):i===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=i?r===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(r-1):n&&this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:r})})}processMedia(t){var e;const r=this.roomNodeClient.getConsumers(),{peerId:i,kind:n,appData:s,track:o,producerId:c,rtpReceiver:d,paused:l,localId:h}=(e=r.get(t))!=null?e:{};if(!i)return this.logger.warn("processMedia::Peer ID is undefined",{consumer:{id:t,kind:n,peerId:i,appData:{supportsRemoteControl:!!(s!=null&&s.supportsRemoteControl),screenShare:!!(s!=null&&s.screenShare)},remotelyPaused:l,producerId:c}}),{};const p=s;return n==="video"&&p.screenShare!==!0&&this.videoPeerConsumerMap.set(i,t),this.logger.info("ParticipantController::processMedia",{consumer:{id:t,peerId:i,kind:n,appData:p,remotelyPaused:l,producerId:c}}),this.consumerPeerMap.set(t,{type:n,peerId:i,appData:p,remotelyPaused:l,producerId:c}),{peerId:i,kind:n,appData:p,remotelyPaused:l,track:o,producerId:c,rtpReceiver:d,localId:h}}processConsumerClosed(t){const{peerId:e,type:r,appData:i,remotelyPaused:n,producerId:s}=this.consumerPeerMap.get(t)||{},o=this.participants.joined.get(e);if(this.logger.info("ParticipantController::processConsumerClosed",{consumer:{id:t,peerId:e,appData:i,kind:r,remotelyPaused:n,producerId:s}}),this.consumerPeerMap.delete(t),r==="video"&&i.screenShare!==!0&&this.videoPeerConsumerMap.delete(e),!o)return;const c=o.producers.find(l=>l.producerId===s);c&&(c.consumer={id:t,peerId:e,kind:void 0,appData:i,paused:n,producerId:s,rtpReceiver:void 0,localId:void 0});const d=[];i&&i.screenShare?(o.setScreenShareEnabled(!1),this.context.getValue("callstats").consumerSharedMediaState(t,{screen:!1}),o.screenShareTracks.video&&d.push(o.screenShareTracks.video.id),o.screenShareTracks.audio&&d.push(o.screenShareTracks.audio.id),o.screenShareTracks={audio:void 0,video:void 0}):r==="audio"?(o.setAudioEnabled(!1),o.audioTrack&&d.push(o.audioTrack.id),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:!1}),o.audioTrack=void 0):r==="video"&&(o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),o.videoTrack&&d.push(o.videoTrack.id),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!1}),o.videoTrack=void 0),i.e2ee&&d.forEach(l=>{this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:l})})}processConsumerResumed(t){var e;const r=this.processMedia(t),{peerId:i,kind:n,appData:s,track:o,remotelyPaused:c,producerId:d,rtpReceiver:l,localId:h}=r;if(!i)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:t,peerId:i,kind:n,appData:s,remotelyPaused:c,producerId:d}});const p=this.participants.joined.get(i);if(!p)return;const v=p.producers.find(S=>S.producerId===d);if(v&&(v.consumer={id:t,peerId:i,kind:n,appData:s,paused:c,producerId:d,rtpReceiver:l,localId:h}),s.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:i,rtpReceiver:l,track:o}),s.screenShare){n==="video"?p.screenShareTracks.video=o:n==="audio"&&(p.screenShareTracks.audio=o),p.setScreenShareEnabled(!0),(e=this.context)==null||e.getValue("callstats").consumerSharedMediaState(t,{screen:!0});return}n==="video"?(p.videoTrack=o,p.setVideoEnabled(!0),this.updatePipSource(p.id,!0),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!0})):n==="audio"&&(p.audioTrack=o,p.setAudioEnabled(p.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:p.audioEnabled}))}processConsumerPaused(t){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${t}`);const{peerId:e,kind:r,track:i,appData:n,remotelyPaused:s,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(t);if(!e)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:t,peerId:e,kind:r,appData:n,remotelyPaused:s,producerId:o}});const l=this.participants.joined.get(e);if(!l)return;const h=l.producers.find(p=>p.producerId===o);h&&(h.consumer={id:t,peerId:e,kind:r,appData:n,paused:s,producerId:o,rtpReceiver:c,localId:d}),i&&n.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:i.id}),r==="video"?(l.videoTrack=i,l.setVideoEnabled(!1),this.updatePipSource(l.id,!1),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!1})):r==="audio"&&(l.audioTrack=i,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:l.audioEnabled}))}processNewConsumer(t){const{peerId:e,kind:r,remotelyPaused:i,track:n,appData:s,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(t);if(!e)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:t,peerId:e,kind:r,remotelyPaused:i,appData:s,producerId:o}});const l=this.participants.joined.get(e);if(!l)return;const h=l.producers.find(p=>p.producerId===o);if(h&&(h.consumer={id:t,peerId:e,kind:r,appData:s,paused:i,producerId:o,rtpReceiver:c,localId:d}),s.screenShare){r==="video"?l.screenShareTracks.video=n:r==="audio"&&(l.screenShareTracks.audio=n),(!i||this.self.permissions.isRecorder||this.context.getValue("flagsmith").hasFeature(Z.SCREEENSHARE_ERR_HACK))&&l.setScreenShareEnabled(!0),s.supportsRemoteControl&&(l.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:e,screenShare:!0,consumerId:t,consumerPeerId:this.self.id}),this.logger.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:t,peerId:e,kind:r,remotelyPaused:i,appData:s,producerId:o}});return}r==="video"?(l.videoTrack=n,i||(l.setVideoEnabled(!0),this.updatePipSource(l.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!i})):r==="audio"&&(l.audioTrack=n,i||l.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:!i})),!i&&s.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:n})}static formatSocketPeerMessage(t){var e,r,i,n,s,o;if(!t)return;const c=kp(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:(r=t.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(i=t.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(n=t.flags)==null?void 0:n.hiddenParticipant,recorder:((s=t.flags)==null?void 0:s.recorderType)!==void 0&&((o=t.flags)==null?void 0:o.recorderType)!=="NONE"}}}onSelectedPeers(t,e){return u(this,null,function*(){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(t,e)})}updateActiveParticipantsWithPriorities(t,e=!1){if(this.participants.viewMode==="MANUAL")return;if(!this.mediaJoined){this.logger.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}t.forEach(i=>{this.selectedPeers.add(i.peerId,i.priority,this.context)});const r=this.selectedPeers.activeSpeakerPeers.at(0);r!==void 0&&r!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=r,this.participants.emit("activeSpeaker",{peerId:r,volume:1})),e&&this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},gr=new WeakMap,Vr=new WeakMap,qa=new WeakMap,Ag);let Ei=Cy;$n([k.trace("ParticipantController.setupEvents")],Ei.prototype,"setupEvents",1);$n([k.trace("ParticipantController.setupEvents")],Ei.prototype,"setupEventsGlobal",1);$n([k.trace("ParticipantController.processMedia")],Ei.prototype,"processMedia",1);$n([k.trace("ParticipantController.processConsumerClosed")],Ei.prototype,"processConsumerClosed",1);$n([k.trace("ParticipantController.processConsumerResumed")],Ei.prototype,"processConsumerResumed",1);$n([k.trace("ParticipantController.processConsumerPaused")],Ei.prototype,"processConsumerPaused",1);$n([k.trace("ParticipantController.processNewConsumer")],Ei.prototype,"processNewConsumer",1);const ye=Pr(pp().permissions);var H,po,Fs,ch,xt,Kt;const mo=class extends Zt{constructor(t,e,r,i=!1){const n=t.getValue("logger");if(super(n),g(this,xt),g(this,H,void 0),g(this,po,void 0),g(this,Fs,void 0),g(this,ch,s=>{var o,c,d;const l=s,{chat:h,connectedMeetings:p,plugins:v,polls:S,media:T}=l,C=pl(l,["chat","connectedMeetings","plugins","polls","media"]);if(h&&(h.private&&Mi(a(this,H).chat.private,h.private),h.public&&Mi(a(this,H).chat.public,h.public),this.emit("chatUpdate")),p&&Mi(a(this,H).connectedMeetings,p),T){const b=j=>{switch(j){case Ji.NONE:return G.Allowed;case Ji.ALLOWED:return G.Allowed;case Ji.NOT_ALLOWED:return G.NotAllowed;case Ji.CAN_REQUEST:return G.CanRequest;default:return}},R={audio:void 0,video:void 0,screenshare:void 0};(o=T.audio)!=null&&o.canProduce&&(R.audio={canProduce:b(T.audio.canProduce)}),(c=T.video)!=null&&c.canProduce&&(R.video={canProduce:b(T.video.canProduce)}),(d=T.screenshare)!=null&&d.canProduce&&(R.screenshare={canProduce:b(T.screenshare.canProduce)}),Mi(a(this,H).media,R)}v&&(Mi(a(this,H).plugins,v),this.emit("pluginsUpdate")),S&&(Mi(a(this,H).polls,S),this.emit("pollsUpdate")),Object.keys(C).length!==0&&Mi(a(this,H),C),this.emit("permissionsUpdate",s)}),!e)throw this.logger.error("DytePermissionsPreset::load_preset_permissions_failed"),new I("Could not load preset permissions.","0904");f(this,Fs,t),f(this,po,r),f(this,H,e),i&&this.setupEvents()}setupEvents(){a(this,Fs).getValue("peerSessionStore").on(P.UPDATE_PERMISSIONS,a(this,ch))}static fromResponse(t,e,r){return new mo(r,t,e,!0)}static default(t,e){return new mo(t,ye,e)}static init(t,e,r){let i;return r?i=new mo(t,r,e,!0):i=new mo(t,ye,e),i}get mediaRoomType(){const{sfu:t}=a(this,Fs).getValue("roomNodeOptions");return t===Oe.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=a(this,H))==null?void 0:t.stageEnabled)||a(this,po)===Ft.Webinar||a(this,po)===Ft.Livestream}get acceptStageRequests(){var t,e;return this.stageEnabled?((t=a(this,H))==null?void 0:t.acceptStageRequests)||((e=a(this,H))==null?void 0:e.canAcceptProductionRequests):!1}get stageAccess(){var t,e,r;return((t=a(this,H))==null?void 0:t.stageAccess)===G.NotAllowed?G.NotAllowed:((e=a(this,H))==null?void 0:e.stageAccess)===G.CanRequest?G.CanRequest:((r=a(this,H))==null?void 0:r.stageAccess)===G.Allowed||a(this,H).media.audio.canProduce===G.Allowed||a(this,H).media.video.canProduce===G.Allowed||a(this,H).media.screenshare.canProduce===G.Allowed?G.Allowed:a(this,H).media.audio.canProduce===G.CanRequest||a(this,H).media.video.canProduce===G.CanRequest||a(this,H).media.screenshare.canProduce===G.CanRequest?G.CanRequest:G.NotAllowed}get acceptWaitingRequests(){var t,e;return(e=(t=a(this,H))==null?void 0:t.acceptWaitingRequests)!=null?e:ye.acceptWaitingRequests}get requestProduceVideo(){var t,e,r;return((r=(e=(t=a(this,H))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.canProduce)===G.CanRequest}get requestProduceAudio(){var t,e,r;return((r=(e=(t=a(this,H))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.canProduce)===G.CanRequest}get requestProduceScreenshare(){var t,e,r;return((r=(e=(t=a(this,H))==null?void 0:t.media)==null?void 0:e.screenshare)==null?void 0:r.canProduce)===G.CanRequest}get canAllowParticipantAudio(){var t,e;return(e=(t=a(this,H))==null?void 0:t.disableParticipantAudio)!=null?e:ye.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=a(this,H))==null?void 0:t.canAcceptProductionRequests)!=null?e:ye.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=a(this,H))==null?void 0:t.disableParticipantVideo)!=null?e:ye.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var t,e;return(e=(t=a(this,H))==null?void 0:t.kickParticipant)!=null?e:ye.kickParticipant}get pinParticipant(){var t,e;return(e=(t=a(this,H))==null?void 0:t.pinParticipant)!=null?e:ye.pinParticipant}get canRecord(){var t,e;return(e=(t=a(this,H))==null?void 0:t.canRecord)!=null?e:ye.canRecord}get waitingRoomType(){var t,e;return(e=(t=a(this,H))==null?void 0:t.waitingRoomType)!=null?e:ye.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=a(this,H))==null?void 0:t.waitingRoomType)!=null?e:ye.waitingRoomType}get plugins(){var t,e;return(e=(t=a(this,H))==null?void 0:t.plugins)!=null?e:ye.plugins}get polls(){var t,e;return(e=(t=a(this,H))==null?void 0:t.polls)!=null?e:ye.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return a(this,H).media.audio.canProduce===G.CanRequest||a(this,H).media.video.canProduce===G.CanRequest||a(this,H).media.screenshare.canProduce===G.CanRequest}get canProduceVideo(){var t;const e=(t=a(this,H).media.video.canProduce)!=null?t:ye.media.video.canProduce;return this.stageEnabled&&(a(this,xt,Kt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,xt,Kt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,xt,Kt)==="OFF_STAGE"||a(this,xt,Kt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var t;const e=(t=a(this,H).media.screenshare.canProduce)!=null?t:ye.media.screenshare.canProduce;return this.stageEnabled&&(a(this,xt,Kt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,xt,Kt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,xt,Kt)==="OFF_STAGE"||a(this,xt,Kt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var t;const e=(t=a(this,H).media.audio.canProduce)!=null?t:ye.media.audio.canProduce;return this.stageEnabled&&(a(this,xt,Kt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,xt,Kt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,xt,Kt)==="OFF_STAGE"||a(this,xt,Kt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get chatPublic(){var t,e,r;return(r=(e=(t=a(this,H))==null?void 0:t.chat)==null?void 0:e.public)!=null?r:ye.chat.public}get chatPrivate(){var t,e,r;return(r=(e=(t=a(this,H))==null?void 0:t.chat)==null?void 0:e.private)!=null?r:ye.chat.private}get chatChannel(){var t,e,r;return(r=(e=(t=a(this,H))==null?void 0:t.chat)==null?void 0:e.channel)!=null?r:ye.chat.channel}get chatMessage(){var t,e,r;return(r=(e=(t=a(this,H))==null?void 0:t.chat)==null?void 0:e.message)!=null?r:ye.chat.message}get connectedMeetings(){var t,e;return(e=(t=a(this,H))==null?void 0:t.connectedMeetings)!=null?e:ye==null?void 0:ye.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=a(this,H))==null?void 0:t.hiddenParticipant)!=null?e:ye.hiddenParticipant}get showParticipantList(){var t;return(t=a(this,H).showParticipantList)!=null?t:ye.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=a(this,H))==null?void 0:t.canChangeParticipantPermissions)!=null?e:ye.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=a(this,H))==null?void 0:t.canChangeParticipantPermissions)!=null?e:ye.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return a(this,H).media.audio.canProduce===G.Allowed||a(this,H).media.video.canProduce===G.Allowed||a(this,H).media.screenshare.canProduce===G.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var t;return(t=a(this,H).canEditDisplayName)!=null?t:!1}get maxScreenShareCount(){return 1}get isRecorder(){return a(this,H).isRecorder}get canSpotlight(){return a(this,H).canSpotlight}get canLivestream(){return a(this,H).canLivestream}get transcriptionEnabled(){return a(this,H).transcriptionEnabled}};let tN=mo;H=new WeakMap,po=new WeakMap,Fs=new WeakMap,ch=new WeakMap,xt=new WeakSet,Kt=function(){return a(this,Fs).getValue("stageStatus")};var Fr;class Py extends Zt{constructor(){super(...arguments),m(this,"localMediaHandler"),g(this,Fr,void 0)}updatePermission(){return u(this,null,function*(){var e,r;const i=(l,h)=>{this.mediaPermissions[l]=h;const p={message:this.mediaPermissions[l],kind:l};h==="DENIED"?a(this,Fr).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_ERROR,p):a(this,Fr).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,p)};if(Ie.getName()==="firefox")return;const n="microphone",s="camera",o=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:n}),c=yield(r=navigator==null?void 0:navigator.permissions)==null?void 0:r.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()};o&&(o.onchange=()=>d("audio",o.state)),c&&(c.onchange=()=>d("video",c.state))})}populateMediaPermissionsInCallstats(e){return u(this,arguments,function*({message:r,kind:i}){var n,s,o,c;switch(i){case"audio":{(n=a(this,Fr))==null||n.getValue("callstats").mediaPermission("AUDIO",r),(s=a(this,Fr))==null||s.getValue("callstats").mediaPermission("SPEAKER",r);break}case"video":{(o=a(this,Fr))==null||o.getValue("callstats").mediaPermission("VIDEO",r);break}case"screenshare":{(c=a(this,Fr))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",r);break}}})}get peerId(){var e;return(e=a(this,Fr))==null?void 0:e.getValue("peerId")}init(){return u(this,arguments,function*(e={},r=!1,i=null){var n,s,o,c,d,l,h;if(Ie.init(),!this.localMediaHandler)try{let p=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)p=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:v}=navigator;this.localMediaHandler=yield v.init(e)}else this.localMediaHandler=new Wt(i,e.constraints,(s=i==null?void 0:i.getValue("defaults"))==null?void 0:s.isNonPreferredDevice,(o=i==null?void 0:i.getValue("defaults"))==null?void 0:o.autoSwitchAudioDevice);if(i==null||i.getValue("peerSessionStore").on(P.MEDIA_PERMISSION_UPDATE,v=>u(this,null,function*(){if(this.populateMediaPermissionsInCallstats({message:v.message,kind:v.kind}),v.message==="NOT_REQUESTED")switch(v==null?void 0:v.kind){case"audio":this.rawAudioTrack&&(this.logger.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(this.logger.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",v)})),i==null||i.getValue("peerSessionStore").on(P.MEDIA_PERMISSION_ERROR,v=>u(this,null,function*(){const{kind:S,message:T,constraints:C}=v;this.populateMediaPermissionsInCallstats({message:T,kind:S}),S==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):S==="video"&&(this.logger.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),this.logger.error("SelfController::mediaPermissionError",{error:{message:T},constraints:C,mediaPermissionsErrors:{kind:S,message:T}}),this.emit("mediaPermissionError",v),this.emit("mediaPermissionUpdate",{message:T,kind:S})})),p){this.logger.info(`Setting up DyteSelfMedia streams using media handler. audio:${(c=e==null?void 0:e.audio)!=null?c:!0} video:${(d=e==null?void 0:e.video)!=null?d:!0}`);const v=this.localMediaHandler.setupStreams({video:(l=e==null?void 0:e.video)!=null?l:!0,audio:(h=e==null?void 0:e.audio)!=null?h:!0});r||(yield v)}}catch(p){this.logger.error("DyteSelf::init::Failed To Setup Streams",{error:{name:p.name,message:p.message}})}})}set context(e){f(this,Fr,e),this.localMediaHandler.context=e}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,r){let i;return r==="audio"?i="audioinput":r==="video"?i="videoinput":r==="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})})}}Fr=new WeakMap;var rN=Object.defineProperty,iN=Object.getOwnPropertyDescriptor,Mt=(t,e,r,i)=>{for(var n=i>1?void 0:i?iN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&rN(e,r,n),n},$a,At,Ja,Ye,wi,ln,Qe,et,Ka,Ac,$e,Xe,za,Ya,Dc,gu,Dg;let at=(Dg=class extends Py{constructor(t,e,r,i,n){var s;const o=t.getValue("logger");super(o),g(this,wi),g(this,Qe),g(this,Ka),g(this,$e),g(this,Dc),m(this,"name"),m(this,"picture"),m(this,"customParticipantId"),m(this,"waitlistStatus"),g(this,$a,void 0),g(this,At,void 0),g(this,Ja,void 0),m(this,"role"),m(this,"userId"),m(this,"organizationId"),m(this,"supportsRemoteControl",!1),m(this,"device"),g(this,Ye,void 0),m(this,"hidden",!1),m(this,"presetName"),m(this,"roomState","init"),g(this,za,new Set),g(this,Ya,new Set),f(this,Ye,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",f(this,At,r),f(this,$a,i),this.hidden=!1,f(this,Ja,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Ie.isElectron(),this.device=Ie.getDeviceInfo(),this.presetName=n,i.viewType!==Ft.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),U(this,Dc,gu).call(this)}get telemetry(){return a(this,Ye).getValue("telemetry")}get stageStatus(){return a(this,Ye).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,Qe,et).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,Ye).getValue("peerId")}static __init__(t,e,r,i,n,s=!1){return u(this,null,function*(){var o,c,d,l,h,p;let v=(c=(o=t.getValue("defaults"))==null?void 0:o.audio)!=null?c:!0,S=(l=(d=t.getValue("defaults"))==null?void 0:d.video)!=null?l:!0;r.canProduceAudio!=="ALLOWED"&&(v=!1),r.canProduceVideo!=="ALLOWED"&&(S=!1);const T=new at(t,e,r,i,n);if(i.viewType===Ft.Chat)return T;const C=u1(i.mediaConstraints);Mi(C,(h=t.getValue("defaults"))==null?void 0:h.mediaConfiguration);const b=(p=t.getValue("defaults"))==null?void 0:p.mediaHandler;return b&&(b.context=t),yield T.init({audio:v,video:S,constraints:C},s,t),T.setupEvents(),T})}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"),a(this,At).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",U(this,Dc,gu));const t=a(this,Ka,Ac);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>u(this,null,function*(){if(this.logger.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",V({},An(this))),a(this,$e,Xe)&&this.audioEnabled)try{yield a(this,Qe,et).shareMic(this.audioTrack)}catch(e){this.logger.error("DyteSelf::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",()=>u(this,null,function*(){if(this.logger.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",V({},An(this))),a(this,$e,Xe)&&this.rawVideoTrack===void 0)this.logger.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,$e,Xe))try{const e=yield a(this,Qe,et).shareWebcam(this.videoTrack);e&&e.id!==this.videoTrack.id&&a(this,Ye).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&(yield a(this,Qe,et).shareWebcam(this.videoTrack))}catch(e){this.logger.error("DyteSelf::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&(yield this.localMediaHandler.disableVideo())}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})),this.localMediaHandler.on("DEVICE_CHANGE",e=>u(this,[e],function*({device:r}){var i;this.emit("deviceUpdate",{device:r}),r.kind==="audiooutput"&&typeof HTMLAudioElement.prototype.setSinkId=="function"&&((i=a(this,Ka,Ac))==null||i.setSpeakerDevice(r.deviceId))})),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",()=>u(this,null,function*(){if(!a(this,$e,Xe)){this.logger.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield a(this,Qe,et).shareScreen(this.screenShareTracks)}catch(e){this.logger.error("DyteSelf::setupEvents::Error while sharing screen",{error:e}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}this.logger.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",V({},An(this))),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})),this.localMediaHandler.on("SCREENSHARE_ENDED",()=>u(this,null,function*(){this.logger.log("Disabling screenshare due to SCREENSHARE_ENDED"),yield this.disableScreenShare(),this.logger.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",V({},An(this)))})),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=a(this,Ye))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",()=>u(this,null,function*(){var e;a(this,$e,Xe)&&(yield a(this,Qe,et).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,Ye))==null||e.getValue("callstats").videoOff()})),a(this,At).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,At).canProduceAudio!==G.Allowed&&(this.disableAudio(),this.logger.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(i=e==null?void 0:e.media)!=null&&i.video&&a(this,At).canProduceVideo!==G.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=e==null?void 0:e.media)!=null&&n.screenshare&&a(this,At).canProduceScreenshare!==G.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,At)}get config(){return a(this,$a)}get roomJoined(){var t;return a(this,$a).viewType===Ft.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,Ye).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,$e,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(t){return u(this,null,function*(){var e;if(this.permissions.canProduceAudio!==G.NotAllowed&&!(a(this,At).canProduceAudio===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,Ye))==null||e.getValue("callstats").audioOn(),yield this.localMediaHandler.enableAudio(t),a(this,$e,Xe)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield a(this,Qe,et).shareMic(this.audioTrack)}catch(r){this.logger.error("DyteSelf::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;a(this,Qe,et).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}})}enableVideo(t){return u(this,null,function*(){var e;if(a(this,At).canProduceVideo!==G.NotAllowed&&!(a(this,At).canProduceVideo===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,Ye))==null||e.getValue("callstats").videoOn(),yield this.localMediaHandler.enableVideo(t),a(this,$e,Xe)&&this.stageStatus==="ON_STAGE")try{yield a(this,Qe,et).shareWebcam(this.videoTrack)}catch(r){this.logger.error("DyteSelf::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("DyteSelf.enableVideo",V({},An(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(!a(this,$e,Xe))throw new I("Can`t enable screenshare without joining room","1105");if(a(this,At).canProduceScreenshare!==G.NotAllowed&&!(a(this,At).canProduceScreenshare===G.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 a(this,Qe,et).shareScreen(this.screenShareTracks)}catch(t){this.logger.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*(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,$e,Xe)&&a(this,Qe,et).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,Ye))==null||t.getValue("callstats").audioOff())})}disableVideo(){return u(this,null,function*(){var t;this.videoEnabled&&(yield this.localMediaHandler.disableVideo(),a(this,$e,Xe)&&(yield a(this,Qe,et).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,Ye))==null||t.getValue("callstats").videoOff())})}disableScreenShare(){return u(this,null,function*(){this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare(),a(this,$e,Xe)&&(yield a(this,Qe,et).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var r;f(this,Ja,t);const i=t?"pinned":"unpinned";(r=a(this,wi,ln))==null||r.updateSource(this.id,{pinned:t}),e&&this.emit(i,this)}get isPinned(){return a(this,Ja)}pin(){return u(this,null,function*(){if(!a(this,$e,Xe))throw new I("Can`t pin participants without joining room","1105");return this.show(),a(this,Qe,et).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!a(this,$e,Xe))throw new I("Can`t unpin participants without joining room","1105");return a(this,Qe,et).pinPeer(null)})}hide(){return u(this,null,function*(){if(!a(this,$e,Xe))throw new I("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})})}show(){if(!a(this,$e,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,r,i;if(!t)throw new I("No device selected","1104");const n=this.getCurrentDevices();if(t.deviceId&&(((e=n==null?void 0:n.audio)==null?void 0:e.deviceId)===t.deviceId||((r=n==null?void 0:n.video)==null?void 0:r.deviceId)===t.deviceId||((i=n==null?void 0:n.speaker)==null?void 0:i.deviceId)===t.deviceId)&&(this.logger.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),a(this,Ye).getValue("flagsmith").hasFeature(Z.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{a(this,$e,Xe)&&(yield a(this,Qe,et).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{a(this,$e,Xe)&&(yield a(this,Qe,et).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}})}cleanUpTracks(){var t,e,r,i;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(i=this.rawVideoTrack)==null||i.stop()}playAudio(){var t;return(t=a(this,Ka,Ac))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,za).add(t):a(this,Ya).add(t),this.updateVideo(t),e||(i=a(this,wi,ln))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1))}deregisterVideoElement(t,e=!1){if(!t){a(this,wi,ln).removeSource(this.id);return}t.srcObject=void 0,e?a(this,za).delete(t):(a(this,Ya).delete(t),a(this,wi,ln).removeSource(this.id))}updateVideo(t,e=!1){var r,i,n;if(this.videoEnabled){if(this.videoTrack==null)return;const s=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((s==null?void 0:s.id)===this.videoTrack.id)return;const o=new MediaStream;o.addTrack(this.videoTrack),t.srcObject=o,e||(i=a(this,wi,ln))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,wi,ln))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},$a=new WeakMap,At=new WeakMap,Ja=new WeakMap,Ye=new WeakMap,wi=new WeakSet,ln=function(){return a(this,Ye).getValue("pip")},Qe=new WeakSet,et=function(){return a(this,Ye).getValue("roomNodeClient")},Ka=new WeakSet,Ac=function(){return a(this,Ye).getValue("audioPlayback")},$e=new WeakSet,Xe=function(){var t;return((t=a(this,Ye).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},za=new WeakMap,Ya=new WeakMap,Dc=new WeakSet,gu=function(){Array.from(a(this,Ya)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,za)).forEach(t=>this.updateVideo(t,!0))},Dg);Mt([k.trace("DyteSelf.cleanupEvents")],at.prototype,"cleanupEvents",1);Mt([k.trace("DyteSelf.setupEvents")],at.prototype,"setupEvents",1);Mt([k.trace("DyteSelf.setupTracks")],at.prototype,"setupTracks",1);Mt([k.trace("DyteSelf.destructMediaHandler")],at.prototype,"destructMediaHandler",1);Mt([k.trace("DyteSelf.removeDocumentEventListeners")],at.prototype,"removeDocumentEventListeners",1);Mt([Si.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),k.trace("DyteSelf.enableAudio")],at.prototype,"enableAudio",1);Mt([Si.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),k.trace("DyteSelf.enableVideo")],at.prototype,"enableVideo",1);Mt([k.trace("DyteSelf.updateVideoConstraints")],at.prototype,"updateVideoConstraints",1);Mt([k.trace("DyteSelf.enableScreenShare"),Si.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],at.prototype,"enableScreenShare",1);Mt([k.trace("DyteSelf.updateScreenshareConstraints")],at.prototype,"updateScreenshareConstraints",1);Mt([Si.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),k.trace("DyteSelf.disableAudio")],at.prototype,"disableAudio",1);Mt([Si.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),k.trace("DyteSelf.disableVideo")],at.prototype,"disableVideo",1);Mt([Si.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),k.trace("DyteSelf.disableScreenShare")],at.prototype,"disableScreenShare",1);Mt([k.trace("DyteSelf.setDevice")],at.prototype,"setDevice",1);at=Mt([ft("1100")],at);class Cp extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Cp)}}class Pp extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Pp)}}var cd;class dh{constructor(e,r=!1){m(this,"pendingTasks",new Map),m(this,"nextTaskId",0),m(this,"stopping",!1),g(this,cd,void 0),this.log=r,f(this,cd,{info:r&&e?e.info:()=>{}})}get size(){return this.pendingTasks.size}push(e,r,i){return u(this,null,function*(){if(r=r!=null?r:e.name,typeof e!="function")throw new TypeError("given task is not a function");if(r)try{Object.defineProperty(e,"name",{value:r})}catch{}return new Promise((n,s)=>{const o={id:this.nextTaskId++,task:e,metadata:i,name:r,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:c=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),n(c);const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)},reject:c=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),s(c),!this.stopping)){const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})})}stop(){this.stopping=!0;for(const e of this.pendingTasks.values())e.reject(new Cp);this.stopping=!1}remove(e){const r=Array.from(this.pendingTasks.values())[e];r&&r.reject(new Pp)}get(e){return Array.from(this.pendingTasks.values())[e]}dump(){const e=Date.now();let r=0;return Array.from(this.pendingTasks.values()).map(i=>({idx:r++,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(e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const r=this.pendingTasks.size,i=yield e.task(),n=Date.now();a(this,cd).info(`AwaitQueue.push(${e.name})_timings`,{awaitQueueTask:{id:e.id,metadata:e.metadata,queueSizeAtStart:r,execTime:(n-e.executedAt)/1e3,taskStartTime:(e.executedAt-e.enqueuedAt)/1e3}}),e.resolve(i)}catch(r){e.reject(r)}})}}cd=new WeakMap;function nN(t,e){const r=new Error(e);return r.name=t,r}class Yo extends I{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Yo):this.stack=new Error(e).stack}}class Ut extends I{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ut):this.stack=new Error(e).stack}}class Dn extends I{constructor(e){super(e),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ut):this.stack=new Error(e).stack}}const Og=t=>new Promise(e=>setTimeout(e,t));function Ry(t,e){return u(this,null,function*(){return new Promise((r,i)=>u(this,null,function*(){const{strategy:n,maxRetryCount:s,delayTime:o}=V({strategy:"linear",maxRetryCount:3,delayTime:10},e);let c=0,d,l=!1;const h=p=>{l=!0,i(p)};for(;c<s;){try{const p=yield t(c,h);return r(p)}catch(p){if(d=p,l)break;if(c<s)n==="linear"?yield Og(o*(c+1)):n==="exponential"&&(yield Og(o*(c+Math.max(0,c-1))));else break}c+=1}return i(d)}))})}function sN(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 Oc(t){return{codecs:sN(t.codecs),headerExtensions:aN(t.headerExtensions?t.headerExtensions:[])}}function oN(t){const e=RTCRtpReceiver.getCapabilities("audio"),r=RTCRtpReceiver.getCapabilities("video"),i=RTCRtpSender.getCapabilities("audio"),n=RTCRtpSender.getCapabilities("video");t&&(r.codecs=r.codecs.filter(({mimeType:o})=>t===o),n.codecs=n.codecs.filter(({mimeType:o})=>t===o));const s={audio:Oc(e),video:Oc(r)};return{sender:{audio:Oc(i),video:Oc(n)},receiver:s}}var ct;class cN{constructor(e,r){g(this,ct,void 0),m(this,"events"),m(this,"sfuType"),f(this,ct,e),this.sfuType=r,this.events=r===Oe.CF?Ir:dr}joinRoom(e,r,i,n=!1,s=null){return u(this,null,function*(){const o={roomUuid:e,displayName:r,prejoined:n,capabilities:i};return s&&(o.location=s),(yield a(this,ct).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:EC.toBinary(o),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield a(this,ct).sendMessagePromise(this.events.createWebRTCTransport,KI.toBinary(e))).payload,{transportId:i,description:n,producerIds:s}=Kv.fromBinary(r),o={sdp:n==null?void 0:n.sdp,type:n.type};return{transportId:i,answer:o,producerIds:s}})}produce(e){return u(this,null,function*(){var r,i;const n=(yield a(this,ct).sendMessagePromise(this.events.produce,VC.toBinary(e))).payload,s=vP.fromBinary(n);return{answer:{sdp:(r=s==null?void 0:s.description)==null?void 0:r.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===Oe.HIVE)throw new Error("Hive does not support socket consumer operations");const r=(yield a(this,ct).sendMessagePromise(this.events.consume,RC.toBinary(e))).payload,{consumerIdsMap:{map:i},description:n}=gP.fromBinary(r);return{consumerStateMap:i,sessionDescription:n}})}closeProducer(e){return u(this,null,function*(){const r=(yield a(this,ct).sendMessagePromise(this.events.closeProducer,jC.toBinary(e))).payload,{description:i}=wP.fromBinary(r);return i})}closeConsumer(e){return u(this,null,function*(){if(this.sfuType===Oe.HIVE)throw new Error("Hive does not support socket consumer operations");return(yield a(this,ct).sendMessagePromise(this.events.closeConsumer,GC.toBinary(e))).payload})}updateConsumersSimulcastConfig(e){return u(this,null,function*(){if(this.sfuType===Oe.HIVE)throw new Error("Method not implemented");return(yield a(this,ct).sendMessagePromise(this.events.updateConsumersSimulcastConfig,OC.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const i={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},n=(yield a(this,ct).sendMessagePromise(this.events.hostControlPeer,YC.toBinary(i))).payload;if(!n)return!1;const{status:s}=AP.fromBinary(n);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const r={audio:e==="audio",screenShare:!1,video:e==="video"},i=(yield a(this,ct).sendMessagePromise(this.events.hostControlAllPeers,XC.toBinary(r))).payload;if(!i)return!1;const{status:n}=OP.fromBinary(i);return n==="success"})}kickAll(){return u(this,null,function*(){const e={propagateKickAcrossRooms:!1};a(this,ct).sendMessagePromise(F.kickAll,Xv.toBinary(e))})}kickPeer(e){return u(this,null,function*(){a(this,ct).sendMessagePromise(F.kick,iy.toBinary(e))})}changeDisplayName(e){return u(this,null,function*(){const r=(yield a(this,ct).sendMessagePromise(this.events.changeDisplayName,KC.toBinary(e))).payload;if(!r)return!1;const{status:i}=VP.fromBinary(r);return i==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield a(this,ct).sendMessagePromise(this.events.selfJoinComplete,TC.toBinary(e))).payload;return qu.fromBinary(r)})}audioActivity(e){return u(this,null,function*(){a(this,ct).sendMessage(this.events.audioActivity,YI.toBinary(e))})}}ct=new WeakMap;var dd;class Al extends gt.EventEmitter{constructor(e){super(),g(this,dd,void 0),f(this,dd,e),this.setMaxListeners(1/0)}get logger(){return a(this,dd).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(n){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:n}),Boolean(i)}}safeEmitAsPromise(e,...r){return u(this,null,function*(){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...r)})}safeEmitAsPromiseWithTimeout(e,r,...i){return u(this,null,function*(){return new Promise((n,s)=>{setTimeout(s,r,"event request timeout");try{this.emit(e.toString(),...i,n,s)}catch(o){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:o}),s(o)}})})}}dd=new WeakMap;class Rp extends Al{constructor(){super(...arguments),m(this,"_sendWebStream",new MediaStream),m(this,"_sendScreenShareStream",new MediaStream),m(this,"_direction"),m(this,"pc"),m(this,"_transportReady",!1),m(this,"_mapMidTransceiver",new Map),m(this,"enableHighBitrate",!1),m(this,"enableStereo",!1),m(this,"enableDtx",!0),m(this,"sfu",Oe.HIVE)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(this.logger.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){this.logger.error(`${this.name}::pc.close()`,{error:e})}}restartIce(){return u(this,null,function*(){this.logger.debug(`${this.name}::restartIce()`);const e=yield this.pc.createOffer({iceRestart:!0});return this.logger.debug(`${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){this.logger.info(`${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this.pc.setRemoteDescription(r)})}})}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:n,proprietaryConstraints:s,onTrackHandler:o}){this.logger.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},n),s),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}connect(){return u(this,null,function*(){let e;this.sfu===Oe.CF?this.pc.addTransceiver("video",{direction:"sendonly"}):e=this.pc.createDataChannel("dyte");const r=yield this.pc.createOffer();return yield this.pc.setLocalDescription(r),this.logger.info(`connect offer: ${JSON.stringify(r)}`),{offerSdp:r,callback:i=>u(this,null,function*(){this.logger.debug(`${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this.pc.setRemoteDescription(i),e==null||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 r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),this.logger.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this.pc.removeTrack(r.sender),r.direction="inactive";const i=yield this.pc.createOffer();return this.logger.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),yield this.pc.setLocalDescription(i),{offerSdp:i,callback:n=>u(this,null,function*(){this.logger.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this.pc.setRemoteDescription(n),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?this.logger.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):this.logger.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(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((s,o)=>{o<=r?s.active=!0:s.active=!1}),yield i.sender.setParameters(n)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),this.logger.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((s,o)=>{n.encodings[o]=V(V({},s),r)}),yield i.sender.setParameters(n)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.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:this.logger.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),this.logger.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":this.logger.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":this.logger.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{this.logger.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this.pc.addEventListener("datachannel",e=>{this.logger.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{this.logger.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{this.logger.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{this.logger.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class Mp extends Rp{static createFactory(e){return()=>new Mp(e)}get name(){return"Chrome74"}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:n,proprietaryConstraints:s,onTrackHandler:o}){this._direction=e,this.pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},n),s),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}send(e){return u(this,arguments,function*({track:r,encodings:i,codecOptions:n,screenShare:s}){this._assertSendDirection();const o=this.pc.addTransceiver(r,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:i});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const l=RTCRtpSender.getCapabilities(typeof r=="string"?r:r.kind);this.logger.info(`senders available params: ${JSON.stringify(l)}`);const h=[];n&&n.length&&n.forEach(p=>{var v;const S=l.codecs.find(T=>T.mimeType.includes(p.name));if(p.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(p.parameters)}`);const T=((v=S.sdpFmtpLine)==null?void 0:v.split(";"))||[];T.push(...p.parameters);const C=Array.from(new Set(T).values());S.sdpFmtpLine=C.join(";")}h.push(S)}),this.logger.info(`selected codecs: ${JSON.stringify(h)}`),o.setCodecPreferences(h)}const c=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(c),n&&n.findIndex(({name:l})=>l==="opus")>=0){const{enableDtx:l,enableStereo:h}=this,p=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=${p}`),c.sdp+=`a=rtcp-fb:111 nack\r
17
+ `).map(e=>Yi.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=pt(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=Yi.parseTranscripts(e)}catch{}})}onTranscript(t){return u(this,null,function*(){var e;const r=this.transcripts.filter(({peerId:i})=>i===t.peerId);if((e=r==null?void 0:r.at(-1))!=null&&e.isPartialTranscript){const i=r.at(-1);i.transcript=t.transcript,i.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",i);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)})}},wc=new WeakMap,gg);hy([k.trace("DyteAi.getActiveTranscript")],Yi.prototype,"getActiveTranscript",1);Yi=hy([ft("0000")],Yi);var NO=Object.defineProperty,VO=Object.getOwnPropertyDescriptor,LO=(t,e,r,i)=>{for(var n=i>1?void 0:i?VO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&NO(e,r,n),n},an,Ia,ir,fg;const py=(fg=class{constructor(t,e,r,i,n,s){m(this,"meta"),m(this,"ai"),g(this,an,void 0),g(this,Ia,void 0),m(this,"aiSocketHandler"),g(this,ir,void 0),f(this,ir,t),this.meta=new th(t,e,e.config.viewType,r,s),this.ai=i,f(this,an,e),f(this,Ia,r),this.aiSocketHandler=n,e.config.viewType!==Ft.Chat&&this.setupEvents()}get telemetry(){return a(this,ir).getValue("telemetry")}get logger(){return a(this,ir).getValue("logger")}static init(t,e,r,i,n){return u(this,null,function*(){const s=yield Yi.init(t,e.permissions.transcriptionEnabled);return new py(t,e,r,s,i,n)})}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,uy.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){a(this,ir).getValue("peerSessionStore").on(P.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),a(this,ir).getValue("peerSessionStore").on(P.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),a(this,ir).getValue("peerSessionStore").on(P.ROOM_STATE,({createdAt:t,roomUuid:e})=>{const r=this.meta.meetingStartedTimestamp;if(e&&(this.meta.sessionId=e),t&&!r){const i=new Date(t*1e3);this.meta.meetingStartedTimestamp=i,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),a(this,ir).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),a(this,an).permissions.canSpotlight&&(this.logger.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,Ia).broadcastMessage("spotlight",{userId:a(this,an).userId,currentTab:this.meta.selfActiveTab})),a(this,ir).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){a(this,an).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,Ia).broadcastToPeers("spotlight",[t.id],{userId:a(this,an).userId,currentTab:this.meta.selfActiveTab})})),a(this,ir).getValue("peerSessionStore").on(P.ROOM_MESSAGE,t=>{var e,r;let i;if("type"in t){if(t.type!=="spotlight")return;i=V(V({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;i=t}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:i.userId},currentTab:{id:(e=i.currentTab)==null?void 0:e.id,type:(r=i.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(i)}),a(this,ir).getValue("peerSessionStore").on(P.MESSAGE,t=>{var e,r;let i;if("type"in t){if(t.type!=="spotlight")return;i=V(V({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;i=t}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:i.userId},currentTab:{id:(e=i.currentTab)==null?void 0:e.id,type:(r=i.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(i)}),this.aiSocketHandler.on(F.transcript,t=>{const{meetingId:e,transcript:r,isPartial:i}=t;let n;try{n=Yi.parseTranscript(r,i)}catch(d){this.logger.error(`Failed to parse transcript: ${r}`,d)}if(!n){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(n),this.meta.emit("transcript",n);const{peerId:s,name:o,transcript:c}=n;this.logger.debug(`${e} Received transcript for peer ${s} - ${o}: ${c}`)})}},an=new WeakMap,Ia=new WeakMap,ir=new WeakMap,fg);let my=py;LO([k.trace("MetaController.setupEvents")],my.prototype,"setupEvents",1);const Ca={},Si={executeWithLock({methodName:t,lockName:e,timeout:r}){return(i,n,s)=>{const o=s.value;return s.value=function(...c){var d,l;const h=(l=(this==null?void 0:this.peerId)||((d=c[0])==null?void 0:d.authToken))!=null?l:"",p=`${e}-${h}`,v=this==null?void 0:this.logger;if(Ca[p]){const C=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw C.name="UnsupportedConcurrentMethodExecution",v==null||v.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:C.stack},dyteLocker:{methodName:t,lockName:p}}),C}Ca[p]=!0;const S=setTimeout(()=>delete Ca[p],r),T=o.apply(this,c);return Promise.resolve(T).then(()=>{delete Ca[p],clearTimeout(S)}).catch(()=>{delete Ca[p],clearTimeout(S)}),T},s}}};var xO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,qn=(t,e,r,i)=>{for(var n=i>1?void 0:i?UO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&xO(e,r,n),n},Er,rh,ue,Yc,Zr,dt,Qc,ih,no,Xc;class Xi extends Zt{constructor(e,r,i,n,s){const o=e.getValue("logger");super(o),g(this,Qc),g(this,no),g(this,Er,void 0),g(this,rh,void 0),g(this,ue,void 0),g(this,Yc,void 0),g(this,Zr,void 0),g(this,dt,void 0),f(this,dt,e),f(this,Er,n),f(this,rh,s),f(this,ue,r),f(this,Yc,i),f(this,Zr,[]),this.setupEvents()}get telemetry(){return a(this,dt).getValue("telemetry")}get status(){return a(this,dt).getValue("stageStatus")}setupEvents(){const e={[P.GET_STAGE_REQUESTS]:n=>u(this,null,function*(){f(this,Zr,n)}),[P.UPDATE_STAGE_REQUESTS]:n=>u(this,[n],function*({add:s}){const o=a(this,Zr).length,{stageRequests:c}=this.getAccessRequests();(s||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)})},r=()=>{Object.entries(e).forEach(([n,s])=>{a(this,dt).getValue("peerSessionStore").onAsync(n,s)})},i=()=>{Object.entries(e).forEach(([n,s])=>{a(this,dt).getValue("peerSessionStore").removeListener(n,s)})};a(this,ue).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:s}=n;s!==void 0&&(a(this,ue).permissions.acceptStageRequests?(r(),a(this,Er).getStageRequests()):(i(),f(this,Zr,[]),this.emit("stageAccessRequestUpdate",a(this,Zr))))}),a(this,ue).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,ue).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ue).permissions.acceptStageRequests)throw this.logger.error("DyteStage::get_access_request::permission_denied"),new I("You do not have permission to perform this action","2001");const e=a(this,Yc).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return f(this,Zr,e),{stageRequests:a(this,Zr)}}requestAccess(){return u(this,null,function*(){if(!a(this,ue).permissions.stageEnabled)throw this.logger.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(a(this,ue).permissions.stageAccess===G.Allowed){U(this,no,Xc).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,Er).requestAccess(),U(this,no,Xc).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return u(this,null,function*(){if(!a(this,ue).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");a(this,Er).cancelRequestAccess(),U(this,no,Xc).call(this,"OFF_STAGE")})}grantAccess(e){if(!a(this,ue).roomJoined)throw new I("Can`t grant for participant without joining room");if(!a(this,ue).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ue).permissions.acceptStageRequests)throw this.logger.error("DyteStage::grant_access::permission_denied"),new I("You do not have permission to perform this action","2001");return a(this,Er).grantAccess(e)}denyAccess(e){if(!a(this,ue).roomJoined)throw new I("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,ue).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ue).permissions.acceptStageRequests)throw this.logger.error("DyteStage::deny_access::permission_denied"),new I("You do not have permission to perform this action","2001");return a(this,Er).denyAccess(e)}get peerId(){return a(this,dt).getValue("peerId")}join(){return u(this,null,function*(){const e=a(this,dt).getValue("viewType");if(this.status==="ON_STAGE")throw new I("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,ue).permissions.stageAccess===G.NotAllowed)throw new I(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,dt).setValue("stageStatus","ON_STAGE",!1),yield a(this,Er).joinStage(),e===Ft.Livestream){yield a(this,dt).getValue("selfController").joinRoom();return}a(this,dt).notify("stageStatus"),a(this,ue).audioEnabled&&a(this,Qc,ih).shareMic(a(this,ue).audioTrack),a(this,ue).videoEnabled&&a(this,Qc,ih).shareWebcam(a(this,ue).videoTrack)})}leave(){return u(this,null,function*(){if(!a(this,ue).permissions.stageEnabled)throw this.logger.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");a(this,ue).setIsPinned(!1),a(this,dt).setValue("stageStatus","OFF_STAGE",!1),yield a(this,Er).leaveStage(a(this,ue).userId);try{yield a(this,dt).getValue("peerSessionStore").emitAsync(P.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("DyteStage::leave::emitAsync::failed",{error:e})}a(this,dt).notify("stageStatus")})}kick(e){return u(this,null,function*(){if(!a(this,ue).roomJoined)throw new I("Can`t kick participant without joining room","2005");if(!a(this,ue).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ue).permissions.acceptStageRequests)throw this.logger.error("DyteStage::kick::permission_denied"),new I("You do not have permissions for kick","2001");return a(this,Er).kick(e)})}}Er=new WeakMap,rh=new WeakMap,ue=new WeakMap,Yc=new WeakMap,Zr=new WeakMap,dt=new WeakMap,Qc=new WeakSet,ih=function(){return a(this,dt).getValue("roomNodeClient")},no=new WeakSet,Xc=function(t){return u(this,null,function*(){this.status!==t&&a(this,dt).setValue("stageStatus",t)})};qn([k.trace("DyteStage.getStageRequests")],Xi.prototype,"getAccessRequests",1);qn([k.trace("DyteStage.requestAccess")],Xi.prototype,"requestAccess",1);qn([k.trace("DyteStage.cancelRequestAccess")],Xi.prototype,"cancelRequestAccess",1);qn([k.trace("DyteStage.grantAccess")],Xi.prototype,"grantAccess",1);qn([k.trace("DyteStage.denyAccess")],Xi.prototype,"denyAccess",1);qn([Si.executeWithLock({methodName:"joinStage",lockName:"DyteStage.join",timeout:5e3}),k.trace("DyteStage.joinStage")],Xi.prototype,"join",1);qn([k.trace("DyteStage.leaveStage")],Xi.prototype,"leave",1);function FO(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function kp(t){switch(t){case di.UNSPECIFIED:return"OFF_STAGE";case di.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case di.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case di.OFF_STAGE:return"OFF_STAGE";case di.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var BO=Object.defineProperty,WO=Object.getOwnPropertyDescriptor,jO=(t,e,r,i)=>{for(var n=i>1?void 0:i?WO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&BO(e,r,n),n},gn,Ur,fn,Zc,Lt;class gy{constructor(e,r,i,n,s){m(this,"stage"),g(this,gn,void 0),g(this,Ur,void 0),g(this,fn,void 0),g(this,Zc,0),g(this,Lt,void 0),f(this,Lt,e),this.stage=new Xi(e,n,s,r,i),f(this,fn,r),f(this,gn,n),f(this,Ur,s),this.setupEvents()}get telemetry(){return a(this,Lt).getValue("telemetry")}get logger(){return a(this,Lt).getValue("logger")}setupEvents(){a(this,Lt).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),a(this,fn).on(F.grantStageAccess,()=>{a(this,gn).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,fn).on(F.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===a(this,gn).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),a(this,fn).on(F.denyStageAccess,()=>{a(this,gn).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,fn).on(F.getStageRequests,e=>u(this,null,function*(){var r;if(a(this,gn).permissions.stageAccess!==G.Allowed)return;const i=(r=e==null?void 0:e.stageRequests)!=null?r:[];yield a(this,Lt).getValue("peerSessionStore").emitAsync(P.GET_STAGE_REQUESTS,i),a(this,Zc)<i.length&&i.length>0&&this.stage.emit("newStageRequest",{count:i.length}),f(this,Zc,i.length),this.stage.emit("stageAccessRequestUpdate",i)}))}getCurrentStageRequests(){return a(this,Ur).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&&a(this,Lt).setValue("stageStatus",e)})}selfStageStatusHandler(e){const r=kp(e.stageType),i=a(this,Lt).getValue("stageStatus");if(i!==r)switch(e.stageType){case 1:a(this,Lt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(i);break;case 0:case 4:default:a(this,Lt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return u(this,null,function*(){const r=a(this,Ur).joined.get(e.peerId),i=a(this,Ur).viewMode==="ACTIVE_GRID";if(!r){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:r.setStageStatus("ON_STAGE"),i&&a(this,Lt).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:a(this,Ur).viewMode,page:a(this,Ur).currentPage});break;case 2:r.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:r.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:r.setStageStatus("OFF_STAGE"),i&&a(this,Lt).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:a(this,Ur).viewMode,page:a(this,Ur).currentPage});break}a(this,Lt).getValue("peerSessionStore").emit(P.UPDATE_PEER_STAGE_STATUS,{id:r.id,status:r.stageStatus})})}}gn=new WeakMap,Ur=new WeakMap,fn=new WeakMap,Zc=new WeakMap,Lt=new WeakMap;jO([k.trace("DyteStage.setupEvents")],gy.prototype,"setupEvents",1);var HO=Object.defineProperty,GO=Object.getOwnPropertyDescriptor,Cl=(t,e,r,i)=>{for(var n=i>1?void 0:i?GO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&HO(e,r,n),n};const Le={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,nr,Pa,Ra,ki,Ma,on,Aa,vg;let Qs=(vg=class extends Zs{constructor(t,{baseURL:e,createdAt:r,description:i,id:n,name:s,organizationId:o,picture:c,private:d,published:l,staggered:h,tags:p,type:v,updatedAt:S},T,C,b,R,j){const B=t.getValue("logger");super(B),g(this,yt,void 0),m(this,"baseURL"),m(this,"createdAt"),m(this,"description"),m(this,"id"),m(this,"name"),g(this,nr,void 0),g(this,Pa,void 0),g(this,Ra,void 0),m(this,"organizationId"),m(this,"picture"),m(this,"private"),m(this,"published"),m(this,"staggered"),m(this,"tags"),m(this,"type"),m(this,"updatedAt"),g(this,ki,void 0),m(this,"config"),g(this,Ma,void 0),m(this,"active"),m(this,"iframes"),m(this,"enabledBy"),g(this,on,void 0),g(this,Aa,void 0),f(this,on,t),this.baseURL=e,this.createdAt=new Date(r),this.description=i,this.id=n,this.name=s,f(this,nr,C),this.organizationId=o,this.picture=c,this.private=d,this.published=l,this.staggered=h,this.tags=p,this.type=v,this.updatedAt=new Date(S),this.active=!1,this.iframes=new Map,f(this,yt,T),f(this,Pa,b),f(this,Ra,R),this.enabledBy="",f(this,Aa,j)}get telemetry(){return a(this,on).getValue("telemetry")}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}handleIframeMessage(t){return u(this,null,function*(){var e;if(!this.active)return;const r=t,{payload:i,uuid:n,type:s}=r;switch(s){case J.customPluginEventToRoom:{a(this,yt).customPluginEventToRoom(this.id,i,n);break}case J.customPluginEventToPeers:{a(this,yt).customPluginEventToPeers(this.id,i.peerIds,i,n);break}case J.enablePluginForRoom:{a(this,yt).enablePluginForRoom(this.id,n);break}case J.enablePluginForPeers:{a(this,yt).enablePluginForPeers(this.id,i.peerIds,n);break}case J.disablePluginForRoom:{a(this,yt).disablePluginForRoom(this.id,n);break}case J.disablePluginForPeers:{a(this,yt).disablePluginForPeers(this.id,i.peerIds,n);break}case J.storeInsertKeys:{a(this,yt).storeInsertKeys(this.id,i.store,i.insertKeys,n);break}case J.storeGetKeys:{a(this,yt).storeGetKeys(this.id,i.store,i.getKeys,n);break}case J.storeDeleteKeys:{a(this,yt).storeDeleteKeys(this.id,i.store,i.deleteKeys,n);break}case J.storeDelete:{a(this,yt).storeDelete(this.id,i.store,n);break}case Le.chatMessage:{const{messagePayload:o,peerIds:c}=i;if(!a(this,Ra)){this.sendIframeEvent({type:Le.chatMessage,uuid:r.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield a(this,Ra).sendMessage(o,c),this.sendIframeEvent({type:Le.chatMessage,uuid:r.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:Le.chatMessage,uuid:r.uuid,payload:{error:d}})}break}case Le.getPeer:{let o;const{peerId:c}=i,d=q(V({},a(this,nr)),{id:a(this,nr).id,isRecorder:(e=a(this,nr).permissions)==null?void 0:e.isRecorder,isHidden:a(this,nr).permissions.hiddenParticipant,stageStatus:a(this,nr).stageStatus});c?(o=a(this,Pa).joined.get(i.peerId),a(this,nr).id===c&&(o=d)):o=d,this.sendIframeEvent({type:Le.getPeer,payload:{peer:o&&Kd(o)},uuid:r.uuid});break}case Le.getPeers:{const o=a(this,Pa).joined.toArray().map(c=>Kd(c));this.sendIframeEvent({type:Le.getPeers,payload:{peers:o},uuid:r.uuid});break}case Le.getPluginInitiator:{this.sendIframeEvent({type:Le.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:r.uuid});break}case Le.getDisplayTitle:{this.sendIframeEvent({type:Le.getDisplayTitle,payload:{displayTitle:a(this,Aa)},uuid:r.uuid});break}case Le.getRoomName:{this.sendIframeEvent({type:Le.getRoomName,payload:{roomName:a(this,on).getValue("meetingId")},uuid:r.uuid});break}case Le.customPluginEventToParent:{this.emit(r.payload.eventName,r.payload.data);break}}})}sendData(t){this.active&&(this.logger.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Le.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var e;const{iframe:r,listener:i}=(e=this.iframes.get(t))!=null?e:{};(r||i)&&(navigator.isReactNative?r.props.onMessage=void 0:window.removeEventListener("message",i),this.iframes.delete(t))}addPluginView(t,e="default"){var r;if(!a(this,Ma))throw this.logger.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new I("No auth token set for plugin.","0602");if(!t)throw this.logger.error("DytePlugin::addPluginView::iframe_was_not_provided"),new I("Iframe was not provided.","0603");this.removePluginView(e);const i=t,n=new URL(this.baseURL),s={auth:a(this,Ma),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:a(this,on).getValue("apiBase"),pluginId:this.id,roomName:(r=a(this,on).getValue("meetingId"))!=null?r:"",displayTitle:a(this,Aa)};if(Object.keys(s).forEach(o=>{n.searchParams.set(o,s[o])}),i.src=n.href,i.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",i.title=e,navigator.isReactNative)i.props.onMessage=o=>{this.handleIframeMessage(JSON.parse(o.nativeEvent.data))},this.iframes.set(e,{iframe:i});else{const o=c=>u(this,null,function*(){c.source===t.contentWindow&&(yield this.handleIframeMessage(c.data))});window.addEventListener("message",o),this.iframes.set(e,{iframe:i,listener:o})}}setActive(t){var e,r;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:(r=this.config)==null?void 0:r.views})}activateForSelf(){return u(this,null,function*(){const t=pt(),e=yield t.authorizePlugin(this.id);f(this,Ma,e),f(this,ki,new Date);try{const r=yield t.getPluginConfig(this.baseURL);this.config=r}catch(r){this.logger.error("DytePlugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")})}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),f(this,ki,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=a(this,nr).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(a(this,yt).addPlugin(this.id,this.staggered),f(this,ki,new Date),this.logger.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=a(this,nr).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==a(this,nr).id||(a(this,yt).removePlugin(this.id),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:a(this,ki)?new Date().getTime()-a(this,ki).getTime():0}}),f(this,ki,void 0)))})}},yt=new WeakMap,nr=new WeakMap,Pa=new WeakMap,Ra=new WeakMap,ki=new WeakMap,Ma=new WeakMap,on=new WeakMap,Aa=new WeakMap,vg);Cl([Bt({maxInvocations:5,period:1})],Qs.prototype,"sendData",1);Cl([k.trace("DytePlugin.activatePlugin")],Qs.prototype,"activate",1);Cl([k.trace("DytePlugin.deactivatePlugin")],Qs.prototype,"deactivate",1);Qs=Cl([ft("0600")],Qs);var Ke,ys;class fy extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:s}=e;super(),g(this,Ke,void 0),g(this,ys,void 0),m(this,"onAddEvent"),m(this,"onDeleteEvent"),m(this,"onClearEvent"),f(this,Ke,new Zs(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=s,f(this,ys,new Map)}emit(e,...r){return a(this,Ke).emit(e,...r)}on(e,r){return a(this,Ke).on(e,r)}addListener(e,r){return a(this,Ke).addListener(e,r)}off(e,r){return a(this,Ke).off(e,r)}once(e,r){return a(this,Ke).once(e,r)}prependListener(e,r){return a(this,Ke).prependListener(e,r)}prependOnceListener(e,r){return a(this,Ke).prependOnceListener(e,r)}removeListener(e,r){return a(this,Ke).removeListener(e,r)}removeAllListeners(e){return a(this,Ke).removeAllListeners(e)}listeners(e){return a(this,Ke).listeners(e)}listenerCount(e){return a(this,Ke).listenerCount(e)}getMaxListeners(){return a(this,Ke).getMaxListeners()}setMaxListeners(e){return a(this,Ke).setMaxListeners(e)}eventNames(){return a(this,Ke).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const n=super.set(e,r),s=(o,...c)=>{this.emit(o,r,...c)};return a(this,ys).set(e,s),r.on("*",s),i&&a(this,Ke).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,ys).get(e));const s=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,Ke).emit(this.onDeleteEvent,n),s}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,ys).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,Ke).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Ke=new WeakMap,ys=new WeakMap;class yg extends fy{constructor(e){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"},e)}add(e,r=!0){return super.add(e,r)}delete(e,r=!0,i=!1){return super.delete(e,r,i)}}var qO=Object.defineProperty,$O=Object.getOwnPropertyDescriptor,JO=(t,e,r,i)=>{for(var n=i>1?void 0:i?$O(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&qO(e,r,n),n};let nh=class{constructor(t){m(this,"all"),m(this,"active"),this.all=new yg(t),this.active=new yg(t)}};nh=JO([ft("0600")],nh);var KO=Object.defineProperty,zO=Object.getOwnPropertyDescriptor,Pl=(t,e,r,i)=>{for(var n=i>1?void 0:i?zO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&KO(e,r,n),n},pr,Da,Nr,Sg;const vy=(Sg=class{constructor(t,e,r,i){m(this,"plugins"),g(this,pr,void 0),g(this,Da,void 0),g(this,Nr,void 0),f(this,pr,e),f(this,Da,r),f(this,Nr,t),this.plugins=i,this.setupEvents()}get telemetry(){return a(this,Nr).getValue("telemetry")}get logger(){return a(this,Nr).getValue("logger")}static init(t,e,r,i,n,s,o,c){return u(this,null,function*(){const d=t.getValue("logger"),l=new nh(d);return e.forEach(h=>{const p=new Qs(t,h,r,s,o,n,c);l.all.add(p)}),new vy(t,r,i,l)})}getRoomPlugins(){return u(this,null,function*(){var t;const{plugins:e}=yield a(this,pr).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(r=>{this.disablePlugin({id:r.id})}),yield Promise.all(e.map(r=>this.enablePlugin({id:r.pluginId,enabledBy:r.enabledBy})))})}enablePlugin(t){return u(this,arguments,function*({id:e,enabledBy:r}){const i=this.plugins.all.get(e);i&&(yield i.activateForSelf(),i.enabledBy=r)})}disablePlugin(t){return u(this,arguments,function*({id:e}){const r=this.plugins.all.get(e);r&&r.deactivateForSelf()})}sendIframeEvent(t,e,r,i){const n=this.plugins.all.get(e);n&&n.sendIframeEvent({type:t,uuid:r,payload:i})}broadcastIframeEvent(t,e){this.plugins.active.forEach(r=>{this.sendIframeEvent(t,r.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)}),a(this,Nr).getValue("peerSessionStore").onAsync(P.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){yield this.getRoomPlugins(),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),a(this,pr).on(J.addPlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active||(yield this.enablePlugin({id:r,enabledBy:t.enabledBy}))})),a(this,pr).on(J.removePlugin,t=>u(this,null,function*(){var e;const r=t.pluginId;(e=this.plugins.all.get(r))!=null&&e.active&&(yield this.disablePlugin({id:r}))})),[J.enablePluginForPeers,J.enablePluginForRoom].forEach(t=>{a(this,pr).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{enabledBy:e.enabledBy})}))}),[J.disablePluginForPeers,J.disablePluginForRoom].forEach(t=>{a(this,pr).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{disabledBy:e.disabledBy})}))}),[J.customPluginEventToPeers,J.customPluginEventToRoom].forEach(t=>{a(this,pr).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[J.storeInsertKeys,J.storeGetKeys,J.storeDeleteKeys].forEach(t=>{a(this,pr).on(t,(e,r)=>u(this,null,function*(){var i;const n=(i=e.storeItems)==null?void 0:i.map(s=>{var o;return{timestamp:s.timestamp,peerId:s.peerId,payload:JSON.parse((o=s.payload)!=null&&o.length?new TextDecoder().decode(s.payload):"{}"),key:s.storeKey}});this.sendIframeEvent(t,e.pluginId,r,{storeName:e.storeName,storeItems:n})}))}),a(this,pr).on(J.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent(J.storeDelete,t.pluginId,e,{storeName:t.storeName})})),a(this,Da).on(De.sendMessageToPeers,t=>{const e=hi==null?void 0:hi.formatSocketPeerMessage(t.message);this.broadcastIframeEvent(Le.chatMessage,{message:e})}),a(this,Da).on(De.sendMessageToRoom,t=>{const e=hi==null?void 0:hi.formatSocketPeerMessage(t.message);this.broadcastIframeEvent(Le.chatMessage,{message:e})}),a(this,Nr).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,t=>{const e=Kd(t);this.broadcastIframeEvent(Le.peerJoined,e)}),a(this,Nr).getValue("peerSessionStore").on(P.PEER_CLOSED,t=>{this.broadcastIframeEvent(Le.peerLeft,t)}),a(this,Nr).getValue("peerSessionStore").on(P.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(Le.peerStageStatusUpdate,t)}),a(this,Nr).subscribe("stageStatus",t=>{this.broadcastIframeEvent(Le.stageStatusUpdate,t)})}},pr=new WeakMap,Da=new WeakMap,Nr=new WeakMap,Sg);let rc=vy;Pl([k.trace("PluginController.getRoomPlugins")],rc.prototype,"getRoomPlugins",1);Pl([k.trace("PluginController.enableForSelf")],rc.prototype,"enablePlugin",1);Pl([k.trace("PluginController.disableForSelf")],rc.prototype,"disablePlugin",1);Pl([k.trace("PluginController.setupEvents")],rc.prototype,"setupEvents",1);var ed;class YO{constructor(e){m(this,"mediaJoined"),m(this,"socketJoined"),m(this,"socketJoinAttempted"),m(this,"mediaJoinAttempted"),m(this,"socketState"),m(this,"mediaState"),g(this,ed,void 0),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},f(this,ed,e)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(e,r){let i;const{reconnected:n}=this.socketState;switch(e){case"connected":i={state:"connected",reconnected:n,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:n,reconnectionAttempt:0};break;case"reconnectAttempt":i={state:"reconnecting",reconnected:n,reconnectionAttempt:r};break;case"failed":i={state:"failed",reconnected:n,reconnectionAttempt:void 0},this.socketJoined=!1;break}i&&(a(this,ed).getValue("peerSessionStore").emit(P.SOCKET_STATE_UPDATE,i),this.socketState=i)}}ed=new WeakMap;var QO=Object.defineProperty,XO=Object.getOwnPropertyDescriptor,ic=(t,e,r,i)=>{for(var n=i>1?void 0:i?XO(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&QO(e,r,n),n},Oa,Na,Va,_c,Eg;let Fn=(Eg=class extends Zt{constructor(t,e){const r=t.getValue("logger");super(r),g(this,Va),g(this,Oa,void 0),g(this,Na,void 0),m(this,"recordingPeerIds",[]),m(this,"recordings",[]),f(this,Na,t),f(this,Oa,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"}get telemetry(){return a(this,Na).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}start(t){return u(this,null,function*(){if(!a(this,Oa).permissions.canRecord)throw this.logger.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 this.logger.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new I(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=pt(),{recording:r={}}=a(this,Na).getValue("defaults"),i=yield e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw this.logger.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new I("Error while starting recording","1000",this.logger)}})}stop(t){return u(this,null,function*(){yield U(this,Va,_c).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield U(this,Va,_c).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield U(this,Va,_c).call(this,"resume",["PAUSED"],t)})}},Oa=new WeakMap,Na=new WeakMap,Va=new WeakSet,_c=function(t,e,r){return u(this,null,function*(){if(!a(this,Oa).permissions.canRecord)throw this.logger.error("DyteRecording::stop::permission_denied"),new I("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const n=this.recordings.find(s=>s.id===r);if(n===void 0)throw new I("Could not find the specified recording","1004");if(e.includes(n.state)){this.logger.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:n.state}});return}i.push(n)}else i=this.recordings.filter(n=>e.includes(n.state));i.forEach(n=>u(this,null,function*(){const s=n.state;t==="stop"&&(n.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield pt().updateRecording(n.id,t)}catch(o){throw this.logger.error("DyteRecording::stop::recording_failed_to_stop",{error:o}),n.state!==s&&(n.state=s,this.emit("recordingUpdate",s)),new I("Error while stopping recording","1000",this.logger)}}))})},Eg);ic([k.trace("DyteRecording.start")],Fn.prototype,"start",1);ic([k.trace("DyteRecording.stop")],Fn.prototype,"stop",1);ic([k.trace("DyteRecording.stop")],Fn.prototype,"pause",1);ic([k.trace("DyteRecording.stop")],Fn.prototype,"resume",1);Fn=ic([ft("1000")],Fn);var ZO=Object.defineProperty,e1=Object.getOwnPropertyDescriptor,t1=(t,e,r,i)=>{for(var n=i>1?void 0:i?e1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&ZO(e,r,n),n},Ss;class yy{constructor(e,r,i){m(this,"recording"),m(this,"room"),g(this,Ss,void 0),f(this,Ss,e),this.recording=new Fn(e,r),this.room=i,this.setupEvents()}get telemetry(){return a(this,Ss).getValue("telemetry")}get logger(){return a(this,Ss).getValue("logger")}getRecordingTypeFromProtoType(e){let r;switch(e){case Vn.BROWSER:r="BROWSER";break;case Vn.COMPOSITE:r="COMPOSITE";break;case Vn.TRACK:r="TRACK";break;default:r="BROWSER"}return r}setupEvents(){a(this,Ss).getValue("peerSessionStore").on(P.ROOM_STATE,e=>{e.activeRecordings.length!==0?this.recording.updateRecordings(e.activeRecordings.map(r=>{const i=this.getRecordingTypeFromProtoType(r.recordingType);return{id:r.recordingId,state:r.recordingStatus,type:i}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(F.recordingStarted,e=>{let r=!1;const i=[...this.recording.recordings];if(i.forEach(n=>{n.id===e.recordingId&&(r=!0,n.state="RECORDING")}),r===!1){const n=this.getRecordingTypeFromProtoType(e.recordingType);i.push({id:e.recordingId,state:"RECORDING",type:n})}this.recording.updateRecordings(i)}),this.room.on(F.recordingPaused,e=>{const r=[...this.recording.recordings];r.forEach(i=>{i.id===e.recordingId&&(i.state="PAUSED")}),this.recording.updateRecordings(r)}),this.room.on(F.recordingStopped,e=>{const r=[...this.recording.recordings.filter(i=>i.id!==e.recordingId)];this.recording.updateRecordings(r)})}}Ss=new WeakMap;t1([k.trace("RecordingController.setupEvents")],yy.prototype,"setupEvents",1);var Es;class r1{constructor(e){g(this,Es,void 0),f(this,Es,e)}hasFeature(e){var r;return(r=a(this,Es).getValue("flagsmith").hasFeature(e))!=null?r:!1}getFeatureValue(e){return a(this,Es).getValue("flagsmith").getValue(e)}getAllFeatures(){return a(this,Es).getValue("flagsmith").getAllFlags()}}Es=new WeakMap;class Tp{constructor(e,r,i){m(this,"logger"),m(this,"features"),m(this,"browserSpecs"),m(this,"callStats"),this.logger=e,this.features=r,this.browserSpecs=Ie,this.callStats=i}static init(e){return new Tp(e.getValue("logger"),new r1(e),e.getValue("callstats"))}}class bp{constructor(e){m(this,"internals"),this.internals=e}static init(e){return u(this,null,function*(){const r=Tp.init(e);return new bp(r)})}}var i1=Object.defineProperty,n1=Object.getOwnPropertyDescriptor,tr=(t,e,r,i)=>{for(var n=i>1?void 0:i?n1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&i1(e,r,n),n},rt,Ce,be,Oi,kr,td,We;class Wt extends Zs{constructor(e,r,i=sh,n=!0){const s=e.getValue("logger");super(s),g(this,rt,void 0),g(this,Ce,void 0),g(this,be,void 0),g(this,Oi,void 0),g(this,kr,void 0),g(this,td,void 0),g(this,We,void 0),m(this,"audioUpdateInProgress"),m(this,"videoUpdateInProgress"),f(this,We,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,f(this,rt,new Sy(e,r)),f(this,Ce,new I1(e,a(this,rt),void 0,i)),f(this,be,new O1(e,a(this,rt),void 0,i)),f(this,kr,new M1(a(this,We),a(this,rt))),f(this,Oi,new P1(a(this,rt))),f(this,td,n),a(this,Ce).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,Ce).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,be).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,be).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,kr).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,We).getValue("telemetry")}set context(e){f(this,We,e)}onVisibilityChange(){return u(this,null,function*(){a(this,We).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,We).getValue("callstats").browserBackgrounded():(a(this,We).getValue("callstats").browserForegrounded(),yield this.setupSpeaker())})}repopulateAvailableDevices(){return u(this,null,function*(){return!0})}setupStreams(e){return u(this,arguments,function*({audio:r,video:i}){var n;r?a(this,We).getValue("callstats").audioOn():a(this,We).getValue("callstats").audioOff(),i?a(this,We).getValue("callstats").videoOn():a(this,We).getValue("callstats").videoOff();let s,o;if(r&&i)try{const c=yield a(this,rt).getAudioAndVideoTrack(a(this,Ce).userSelectedDevice,a(this,be).userSelectedDevice);s=c.audioTrack,o=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!s&&r)try{s=yield a(this,rt).getAudioTrack(!1,a(this,Ce).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!o&&i)try{o=yield a(this,rt).getVideoTrack(a(this,be).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}r&&!s&&a(this,We).getValue("callstats").audioOff(),i&&!o&&a(this,We).getValue("callstats").videoOff(),yield a(this,Ce).setMediaTrack(s),yield a(this,be).setMediaTrack(o);try{yield this.setupSpeaker()}catch{}if(o){const c=yield this.getDeviceById(o.getSettings().deviceId);a(this,We).getValue("callstats").selectedDevice("VIDEO",c)}if(s){const c=yield this.getDeviceById(s.getSettings().deviceId);a(this,We).getValue("callstats").selectedDevice("AUDIO",c)}(n=a(this,Oi).currentDevice)!=null&&n.deviceId&&a(this,We).getValue("callstats").selectedDevice("SPEAKER",a(this,Oi).currentDevice),a(this,rt).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})})}getCurrentDevices(){return{audio:a(this,Ce).currentDevice,video:a(this,be).currentDevice,speaker:a(this,Oi).currentDevice}}get permissions(){return a(this,rt).permissions}getAllDevices(){return a(this,rt).getAvailableDevices()}getDeviceById(e,r){return a(this,rt).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,Ce).mediaTrack}get audioTrack(){return a(this,Ce).transformedMediaTrack}get audioEnabled(){return a(this,Ce).trackEnabled}enableAudio(e){return u(this,null,function*(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?yield a(this,Ce).enableTrack(!1,e):yield a(this,Ce).unmuteTrack()}catch{}finally{this.audioUpdateInProgress=!1}}})}disableAudio(){a(this,Ce).mediaTrack&&!a(this,Ce).isCustomTrack?a(this,Ce).muteTrack():a(this,Ce).disableTrack()}getAudioDevices(e){return a(this,rt).getAudioInputDevices(e)}setAudioDevice(e){return u(this,null,function*(){yield a(this,Ce).setDevice(e),e!=null&&e.deviceId&&a(this,We).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return u(this,null,function*(){const{speaker:e}=this.getCurrentDevices();yield a(this,Oi).setupSpeaker();const{speaker:r}=this.getCurrentDevices();(e==null?void 0:e.deviceId)!==(r==null?void 0:r.deviceId)&&r&&this.emit("DEVICE_CHANGE",{device:r})})}setSpeakerDevice(e){return u(this,null,function*(){yield a(this,Oi).setupSpeaker(e),e!=null&&e.deviceId&&a(this,We).getValue("callstats").selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return a(this,be).mediaTrack}get videoTrack(){return a(this,be).transformedMediaTrack}get videoEnabled(){return a(this,be).trackEnabled}enableVideo(e){return u(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?yield a(this,be).enableTrack(!1,e):yield a(this,be).unmuteTrack()}catch{}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){a(this,be).disableTrack()}getVideoDevices(e){return a(this,rt).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield a(this,be).setDevice(e),e!=null&&e.deviceId&&a(this,We).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}updateVideoConstraints(e){return u(this,null,function*(){yield a(this,be).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,kr).audioMediaTrack,video:a(this,kr).videoMediaTrack}}get screenShareEnabled(){return a(this,kr).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield a(this,kr).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){a(this,kr).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield a(this,kr).updateConstraints(e)})}getSpeakerDevices(e){return a(this,rt).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,Ce).addMiddleware(e)}removeAudioMiddleware(e){return a(this,Ce).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,Ce).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,be).addMiddleware(e)}removeVideoMiddleware(e){return a(this,be).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,be).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,be).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,Ce).disableTrack(),a(this,be).disableTrack(),a(this,be).terminateMiddlewareWebWorker(),a(this,kr).disableScreenShare(),a(this,rt).destruct()}onDeviceChange(e,r){return u(this,null,function*(){var i,n;this.emit("DEVICE_LIST_UPDATED",e),!(r||!a(this,td))&&((i=e==null?void 0:e.added)==null||i.forEach(s=>u(this,null,function*(){var o;s&&!sh(s)&&(s.kind==="audioinput"&&((o=this.audioTrack)==null?void 0:o.enabled)===!0?yield this.setAudioDevice(s):s.kind==="audiooutput"&&(yield this.setSpeakerDevice(s)))})),(n=e==null?void 0:e.removed)==null||n.forEach(s=>u(this,null,function*(){var o;if(s.kind==="audiooutput"&&((o=this.getCurrentDevices().speaker)==null?void 0:o.deviceId)===s.deviceId){const c=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==s.deviceId);c&&(yield this.setSpeakerDevice(c))}})))})}removeAllTracks(){this.destruct()}removeAudioTrack(){a(this,Ce).disableTrack()}removeVideoTrack(){a(this,be).disableTrack(),a(this,be).terminateMiddlewareWebWorker()}removeDocumentEventListeners(){return u(this,null,function*(){document.removeEventListener("visibilitychange",this.onVisibilityChange)})}}rt=new WeakMap,Ce=new WeakMap,be=new WeakMap,Oi=new WeakMap,kr=new WeakMap,td=new WeakMap,We=new WeakMap;tr([k.trace("MediaHandler.setupStreams")],Wt.prototype,"setupStreams",1);tr([k.trace("MediaHandler.enableAudio")],Wt.prototype,"enableAudio",1);tr([k.trace("MediaHandler.disableAudio")],Wt.prototype,"disableAudio",1);tr([k.trace("MediaHandler.setAudioDevice")],Wt.prototype,"setAudioDevice",1);tr([k.trace("MediaHandler.enableVideo")],Wt.prototype,"enableVideo",1);tr([k.trace("MediaHandler.disableVideo")],Wt.prototype,"disableVideo",1);tr([k.trace("MediaHandler.setVideoDevice")],Wt.prototype,"setVideoDevice",1);tr([k.trace("MediaHandler.updateVideoConstraints")],Wt.prototype,"updateVideoConstraints",1);tr([k.trace("MediaHandler.enableScreenShare")],Wt.prototype,"enableScreenShare",1);tr([k.trace("MediaHandler.disableScreenShare")],Wt.prototype,"disableScreenShare",1);tr([k.trace("MediaHandler.updateScreenshareConstraints")],Wt.prototype,"updateScreenshareConstraints",1);tr([k.trace("MediaHandler.destruct")],Wt.prototype,"destruct",1);tr([k.trace("MediaHandler.onDeviceChange")],Wt.prototype,"onDeviceChange",1);function Ic(t,e,r){switch(!0){case Ie.isChromiumBased():switch(e){case"NotAllowedError":return r.includes("by system")?"SYSTEM_DENIED":t==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Ie.isSafari():switch(e){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Ie.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 s1=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function sh(t){var e,r;const i=(e=t.label)==null?void 0:e.toLowerCase();return((r=Ie._bowser)==null?void 0:r.getOSName())==="macOS"&&i.includes("iphone")?!0:s1.some(n=>i==null?void 0:i.includes(n))}function a1(t,e,r){return u(this,null,function*(){if(!(e!=null&&e.length))return r;const i=t.getValue("logger"),n=new AudioContext,s=yield Promise.all(e==null?void 0:e.map(d=>d(n))),o=n.createMediaStreamSource(new MediaStream([r])),c=n.createMediaStreamDestination();try{let d=o;for(let l=0;l<s.length;l+=1)d.connect(s[l]),d=s[l];d.connect(c)}catch(d){return i.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),r}return c.stream.getAudioTracks()[0]})}var ks,rd;class o1{constructor(e){g(this,ks,void 0),g(this,rd,void 0),f(this,rd,e)}get logger(){return a(this,rd).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,ks))try{Tf(a(this,ks)),f(this,ks,void 0)}catch{this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}getTransformedVideoTrack(e,r,i){return u(this,null,function*(){if(!(e!=null&&e.length))return r;const n=document.createElement("canvas"),s=yield Promise.all(e==null?void 0:e.map(p=>p({canvas:n,WorkerTimers:wf})));if(i.disablePerFrameCanvasRendering){const p=n.captureStream().getVideoTracks()[0];return Object.defineProperty(p,"originalSettings",{value:r.getSettings()}),p}const o=document.createElement("video"),c=new MediaStream;c.addTrack(r);const d=n.getContext("2d");o.srcObject=c,o.autoplay=!0,this.terminateMiddlewareWebWorker();const l=()=>u(this,null,function*(){if(r.enabled===!1||r.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),n.remove();return}try{d.drawImage(o,0,0);for(let p=0;p<s.length;p+=1)typeof s[p]=="function"&&(yield s[p](n,d))}catch(p){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:p})}});try{o.play()}catch{}o.addEventListener("play",()=>{n.width=o.width||r.getSettings().width,n.height=o.width||r.getSettings().height,f(this,ks,bf(l,50))},!1);const h=n.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:r.getSettings()}),h})}}ks=new WeakMap,rd=new WeakMap;const kg={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}}},c1=[[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"}]]],d1=(t,e)=>{var r;const i="getSettings"in e&&e.getSettings().width||"getConstraints"in e&&e.getConstraints().width||"originalSettings"in e&&((r=e.originalSettings)==null?void 0:r.width);let n=c1;t.getValue("flagsmith").hasFeature(Z.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)&&(n=JSON.parse(t.getValue("flagsmith").getValue(Z.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)));const s=n.map(([d])=>d).sort((d,l)=>d-l);let o=Number.MAX_VALUE,c=0;return s.forEach((d,l)=>{Math.abs(d-i)<o&&(o=Math.abs(d-i),c=l)}),n[c][1]};var Se=(t=>(t.WEBCAM="webcam",t.WEBCAM_BACKUP="webcam_backup",t.MIC="mic",t.SCREENSHARE_VIDEO="screenshare_video",t.SCREENSHARE_AUDIO="screenshare_audio",t))(Se||{});const l1=R_(),Zn=Pr(l1.config.media);function u1(t){var e,r;const i={};return t.audio&&(i.audio={enableStereo:(e=t.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=t.audio.enableHighBitrate)!=null?r:!1}),i.video=t.video.quality,i}var Ts,ei;class h1{constructor(e,r){g(this,Ts,void 0),g(this,ei,void 0),m(this,"getScreenShareConstraints",()=>{var i,n,s,o,c,d,l,h,p,v,S;const T=(i=a(this,Ts))==null?void 0:i.screenshare,C=(s=(n=T==null?void 0:T.width)==null?void 0:n.max)!=null?s:1920,b=(c=(o=T==null?void 0:T.height)==null?void 0:o.max)!=null?c:1080,R=(l=(d=T==null?void 0:T.frameRate)==null?void 0:d.max)!=null?l:5;let j=(p=(h=T==null?void 0:T.frameRate)==null?void 0:h.ideal)!=null?p:5;const B=T==null?void 0:T.displaySurface,w=T==null?void 0:T.selfBrowserSurface;a(this,ei).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE)&&(j=parseInt((v=a(this,ei).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE))==null?void 0:v.toString(),10));let ee={width:{max:C},height:{max:b},frameRate:{ideal:j,max:R}};if(a(this,ei).getValue("flagsmith").hasFeature(Z.SCREENSHARE_CONSTRAINTS)){const re=(S=a(this,ei).getValue("flagsmith").getValue(Z.SCREENSHARE_CONSTRAINTS))==null?void 0:S.toString();ee=JSON.parse(re)}return B!==void 0&&["monitor","browser","window"].includes(B)&&(ee=q(V({},ee),{displaySurface:B})),w!==void 0&&(ee=q(V({},ee),{selfBrowserSurface:w})),{audio:!0,video:ee}}),m(this,"getAudioConstraints",i=>{var n,s,o,c,d,l,h;const p={},v=(n=a(this,Ts))==null?void 0:n.audio,S=v!=null&&v.enableStereo?2:1;return Ie.isFirefox()||Ie.isWebKitBased()?(p.audio={deviceId:i,autoGainControl:(s=v==null?void 0:v.autoGainControl)!=null?s:!0,echoCancellation:(o=v==null?void 0:v.echoCancellation)!=null?o:!0,noiseSuppression:(c=v==null?void 0:v.noiseSupression)!=null?c:!0,channelCount:S},p):(p.audio={autoGainControl:(d=v==null?void 0:v.autoGainControl)!=null?d:!0,echoCancellation:(l=v==null?void 0:v.echoCancellation)!=null?l:!0,noiseSuppression:(h=v==null?void 0:v.noiseSupression)!=null?h:!0,channelCount:S},i&&i!=="default"&&(p.audio.deviceId={exact:i}),p)}),m(this,"getVideoConstraints",i=>{var n,s,o,c;const d={},l=(n=a(this,Ts))==null?void 0:n.video;let h=kg.vga;if(typeof l=="string"?h=kg[l]:l!==void 0&&(h.height.ideal=l.height.ideal,h.width.ideal=l.width.ideal),h.frameRate={ideal:(o=(s=h.frameRate)==null?void 0:s.ideal)!=null?o:24},Ie.isChromiumBased()&&(h.frameRate.max=30),a(this,ei).getValue("flagsmith").hasFeature(Z.VIDEO_CONSTRAINTS)){const p=(c=a(this,ei).getValue("flagsmith").getValue(Z.VIDEO_CONSTRAINTS))==null?void 0:c.toString();h=JSON.parse(p)}return d.video=h,typeof d.video=="boolean"||(i?d.video.deviceId={exact:i}:d.video.facingMode="user"),d}),f(this,ei,e),f(this,Ts,r)}getUpdatedVideoConstraints(e){return e}}Ts=new WeakMap,ei=new WeakMap;class au extends Error{constructor(e,r,i){super(r),m(this,"constraints"),m(this,"name"),this.name=e,this.constraints=i}}class p1{constructor(){m(this,"permissions"),this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}getAudioInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(i=>i.kind==="audioinput")})}getVideoInputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(i=>i.kind==="videoinput")})}getAudioOutputDevices(e){return u(this,null,function*(){let r=e;return e||(r=yield this.getAvailableDevices()),r.filter(i=>i.kind==="audiooutput")})}}var m1=Object.defineProperty,g1=Object.getOwnPropertyDescriptor,Or=(t,e,r,i)=>{for(var n=i>1?void 0:i?g1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&m1(e,r,n),n},La,mr,qe,Tg;let Xt=(Tg=class extends p1{constructor(t,e){super(),m(this,"availableDevices"),g(this,La,void 0),g(this,mr,void 0),g(this,qe,void 0),f(this,qe,t),f(this,mr,new h1(t,e)),f(this,La,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get telemetry(){return a(this,qe).getValue("telemetry")}get logger(){return a(this,qe).getValue("logger")}get constraintsBuilder(){return a(this,mr)}destruct(){return u(this,null,function*(){var t;(t=a(this,La))==null||t.abort()})}handlePermissionErrors(t,e){const r=Ic(t,e.name,e.message);return this.permissions[t]=r,a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}getAudioAndVideoTrack(t,e){return u(this,null,function*(){const r={audio:a(this,mr).getAudioConstraints(t).audio,video:a(this,mr).getVideoConstraints(e).video};try{this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(r)});const i=yield navigator.mediaDevices.getUserMedia(r);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(r)});const n=i.getAudioTracks()[0];let s=i.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",a(this,qe).getValue("flagsmith").hasFeature(Z.OBS_QUALITY)&&s.label.includes("OBS Virtual")){const o=(yield this.getVideoInputDevices()).find(c=>c.label.includes("OBS Virtual"));s=yield this.getVideoTrack(o.deviceId)}return a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:n,videoTrack:s}}catch(i){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:i}),new I("Couldnt fetch audio and video track","1605")}})}getAudioTrack(t,e){return u(this,null,function*(){let r=yield this.getAudioInputDevices();if(r.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new I("No audio devices available","1606");const i=n=>u(this,null,function*(){let s;try{r=r.filter(c=>c.deviceId!==n),s=a(this,mr).getAudioConstraints(n),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(s)});const[o]=(yield navigator.mediaDevices.getUserMedia(s)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(s)}),o}catch(o){const c=Ic("audio",o.name,o.message),d=new au(o.name,o.message,s);if(c==="COULD_NOT_START"){const l=r.shift();if(!l)throw d;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(s),error:o});const h=a(this,mr).getAudioConstraints(l.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(h)}),i(l.deviceId)}throw d}});try{const n=yield i(e);return n.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),n}catch(n){throw n.constraints&&this.handlePermissionErrors("audio",n),new I(n.message,"1601")}})}getVideoTrack(t){return u(this,null,function*(){var e;const r=a(this,qe).getValue("flagsmith").hasFeature(Z.OBS_QUALITY),i=(e=yield this.getCurrentDeviceLabel(t))==null?void 0:e.includes("OBS Virtual"),n=r&&i,s=yield this.getVideoInputDevices();if(s.length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new I("No video devices available","1607");const o=c=>u(this,null,function*(){try{let d=c;const{video:l}=d;n&&typeof l!="boolean"&&(d={video:{deviceId:l.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(d)});const[h]=(yield navigator.mediaDevices.getUserMedia(d)).getVideoTracks();if(n&&typeof l!="boolean"&&typeof l.width=="object"){const{width:p,height:v}=h.getSettings(),{ideal:S}=l.width;h.applyConstraints({width:{ideal:S},height:{ideal:Math.floor(v*S/p)},frameRate:l.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(d)}),h}catch(d){const l=Ic("video",d.name,d.message),h=new au(d.name,d.message,c);if(l==="COULD_NOT_START"){const p=s.shift();if(!p)throw h;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(c),error:d});const v=a(this,mr).getVideoConstraints(p.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(v)}),o({video:v.video})}throw h}});try{const c=a(this,mr).getVideoConstraints(t),d=yield o(c);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,qe).getValue("peerSessionStore").emit(P.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{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,qe).getValue("callstats").screenShareRequested();const r=yield navigator.mediaDevices.getDisplayMedia(e);return this.logger.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const i=Ic("video",r.name,r.message),n=new au(r.name,r.message,e),s={video:!0};if(fI(e,s)||!a(this,qe).getValue("flagsmith").hasFeature(Z.SCREEENSHARE_CONSTRAINTS_RETRY))throw n;if(i==="COULD_NOT_START")return t(s);throw n}});try{const e=a(this,mr).getScreenShareConstraints(),r=yield t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,qe).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.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 this.logger.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 this.logger.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 this.logger.error("enumerate_devices_failed",{error:e}),new I("Failed to get device","1609")}})}onDeviceChange(t){return u(this,null,function*(){Ie.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",e=>u(this,null,function*(){var r,i;const n=h=>`${h.kind}-${h.deviceId}-${h.groupId}`,s=this.availableDevices,o=new Set(s.map(h=>n(h))),c=yield this.getAvailableDevices(),d=new Set(c.map(h=>n(h))),l={added:c.filter(h=>!o.has(n(h))),removed:s.filter(h=>!d.has(n(h))),devices:c};if((r=l.added)!=null&&r.length||(i=l.removed)!=null&&i.length){this.logger.info("repopulated_full_device_list",{devices:JSON.stringify(c)});const h=[...l.added,...l.removed];h.some(p=>p.kind==="audioinput")&&a(this,qe).getValue("callstats").devices("AUDIO",c==null?void 0:c.filter(p=>p.kind==="audioinput")),h.some(p=>p.kind==="videoinput")&&a(this,qe).getValue("callstats").devices("VIDEO",c==null?void 0:c.filter(p=>p.kind==="videoinput")),h.some(p=>p.kind==="audiooutput")&&a(this,qe).getValue("callstats").devices("SPEAKER",c==null?void 0:c.filter(p=>p.kind==="audiooutput")),t(e,l,!1)}}),{signal:a(this,La).signal})})}},La=new WeakMap,mr=new WeakMap,qe=new WeakMap,Tg);Or([k.trace("WebMediaInterface.destruct")],Xt.prototype,"destruct",1);Or([k.trace("WebMediaInterface.handlePermissionErrors")],Xt.prototype,"handlePermissionErrors",1);Or([k.trace("WebMediaInterface.getAudioAndVideoTrack")],Xt.prototype,"getAudioAndVideoTrack",1);Or([k.trace("WebMediaInterface.getAudioTrack")],Xt.prototype,"getAudioTrack",1);Or([k.trace("WebMediaInterface.getVideoTrack")],Xt.prototype,"getVideoTrack",1);Or([k.trace("WebMediaInterface.getScreenShareTracks")],Xt.prototype,"getScreenShareTracks",1);Or([k.trace("WebMediaInterface.getAvailableDevices")],Xt.prototype,"getAvailableDevices",1);Or([k.trace("WebMediaInterface.getAvailableDevicesByKind")],Xt.prototype,"getAvailableDevicesByKind",1);Or([k.trace("WebMediaInterface.getDevice")],Xt.prototype,"getDevice",1);Or([k.trace("WebMediaInterface.onDeviceChange")],Xt.prototype,"onDeviceChange",1);Xt=Or([ft("1600")],Xt);const Sy=Xt,Ao={setItem:(t,e,r)=>{try{localStorage.setItem(t,e)}catch(i){r==null||r.error("LocalStorage::setItem::crashed",{error:i,localStorage:{key:t,value:e}})}},getItem:(t,e)=>{try{return localStorage.getItem(t)}catch(r){e==null||e.error("LocalStorage::getItem::crashed",{error:r,localStorage:{key:t}})}return null}},f1=(t=0)=>new Promise(e=>setTimeout(e,t)),v1=(t,e,r)=>{const i=typeof r=="number"?r:250,n=t.createMediaStreamSource(e),s=t.createAnalyser();s.fftSize=2048,n.connect(s);const o=new Uint8Array(s.fftSize);let c=!1;setTimeout(()=>{c=!0},i);function d(){return c?Promise.resolve(!0):(s.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):f1().then(d))}return d().then(l=>(n.disconnect(),l),l=>{throw n.disconnect(),l})},y1=typeof AudioContext!="undefined"?AudioContext:null;class wp{constructor(e){m(this,"_AudioContext"),m(this,"audioContext"),m(this,"_audioContextRefContainers");const r=V({AudioContext:y1},e);Object.defineProperties(this,{_AudioContext:{value:r.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:wp}})}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 bg=new wp,S1=3,E1=250;function k1(t){const e={},r=bg.getOrCreate(e);let i=S1;function n(){return i-=1,v1(r,t.srcObject,E1).then(s=>s?i>0?n():!0:!1).catch(()=>!0)}return n().finally(()=>{bg.release(e)})}function wg(t,e){return u(this,null,function*(){const r=new Audio,i=new MediaStream;i.addTrack(e),r.srcObject=i;let n=!1;try{const s=r.play();s&&(yield s),n=yield k1(r),n&&t.info("checkIfAudioTrackIsSilent::silence_detected")}catch(s){t.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:s})}finally{r.pause(),r.remove()}return n})}var T1=Object.defineProperty,b1=Object.getOwnPropertyDescriptor,Ey=(t,e,r,i)=>{for(var n=i>1?void 0:i?b1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&T1(e,r,n),n};let zd=class extends Zs{constructor(t,e,r,i){var n;const s=t.getValue("logger");super(s),m(this,"constructorName",this.constructor.name),m(this,"userSelectedDevice"),m(this,"mediaInterface"),m(this,"isNonPreferredDevice"),m(this,"_mediaTrack"),m(this,"transformedMediaTrack"),m(this,"middlewares",[]),m(this,"currentDevice"),m(this,"userPreferredDeviceKey",`Dyte::${this.constructorName}::UserDeviceID`),m(this,"setUserPreferredDevice",o=>Ao.setItem(this.userPreferredDeviceKey,o,this.logger)),m(this,"getUserPreferredDevice",()=>Ao.getItem(this.userPreferredDeviceKey,this.logger)),m(this,"isCustomTrack",!1),m(this,"context"),this.context=t,this.mediaInterface=e,r&&this.setMediaTrack(r),this.userSelectedDevice=(n=this.getUserPreferredDevice())!=null?n:void 0,this.isNonPreferredDevice=i,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}get telemetry(){return this.context.getValue("telemetry")}disableTrack(){var t,e;this.removeMediaTrackListeners(),this.isCustomTrack||(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,e=!1){return u(this,null,function*(){const r=i=>{this.logger.error(`${this.constructorName}.setMediaTrack.error`,{error:i})};try{this.disableTrack()}catch(i){r(i)}this._mediaTrack=yield this.conditionallyChangeTrack(t,e),yield this.setTransformedTrack();try{this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(i){r(i)}})}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){this.logger.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 this.logger.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new I("Failed to unmute track","1611")}})}getCurrentDeviceId(){var t;const{kind:e}=this.mediaTrack;switch(e){case"audio":{const{deviceId:r}=this.mediaTrack.getSettings();if(r)return r;const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(i&&typeof i.deviceId=="object"&&"exact"in i.deviceId?i.deviceId.exact:i.deviceId)||((t=i==null?void 0:i.advanced)==null?void 0:t[0].deviceId)||"default":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 this.logger.warn(`${this.constructorName}.setDevice No device received`),new I("No device received!","1603");this.userSelectedDevice=t.deviceId,this.setUserPreferredDevice(t.deviceId),yield this.onSetDevice(t)})}addMiddleware(t){return u(this,null,function*(){if(Ie.isWebKitBased()&&!y_.hasFeature(Z.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 this.logger.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(r){return this.logger.error("While removing middleware",{error:r}),{success:!1,message:r==null?void 0:r.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 this.logger.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,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(r=this.mediaTrack)==null?void 0:r.kind}`),this.logger.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};Ey([k.trace("BaseMediaHandler.unmuteTrack")],zd.prototype,"unmuteTrack",1);zd=Ey([ft("1600")],zd);const ky=zd;var w1=Object.defineProperty,_1=Object.getOwnPropertyDescriptor,_p=(t,e,r,i)=>{for(var n=i>1?void 0:i?_1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&w1(e,r,n),n};const ou="[Dyte]nonSilentDeviceLabels";class Rl extends ky{onSetDevice(e){return u(this,null,function*(){if(!e)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new I("No device received!","1603");if(e.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new I("Non audio device received while setting device!","1603");try{const r=this.trackEnabled;yield this.setMediaTrack(yield this.mediaInterface.getAudioTrack(!r,this.userSelectedDevice))}catch(r){throw this.logger.error("AudioMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new I(r.message,"1604")}})}enableTrack(e,r){return u(this,null,function*(){if(this.trackEnabled){this.logger.warn("AudioMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,yield this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=yield this.mediaInterface.getAudioTrack(e,this.userSelectedDevice);yield this.setMediaTrack(i)})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield a1(this.context,this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(i){this.logger.error("AudioMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}})}onTrackEnded(){return u(this,null,function*(){this.logger.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const e=this.mediaTrack.enabled;this.disableTrack(),yield this.enableTrack(!e),yield this.setTransformedTrack(),this.emit("trackChanged")})}onTrackMuted(){this.logger.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e,r=!1){return u(this,null,function*(){var i;if(!e||this.userSelectedDevice||r)return e;let n=e;const s=yield this.mediaInterface.getAudioInputDevices(),o=this.isNonPreferredDevice?s.filter(l=>l&&!this.isNonPreferredDevice(l)):s;if(!(o!=null&&o.length))return n;o.find(l=>l.deviceId===e.getSettings().deviceId)||(n.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),n=yield this.mediaInterface.getAudioTrack(!1,o[0].deviceId));const c=JSON.parse(Ao.getItem(ou,this.logger));if(c!=null&&c.devices.some(l=>l.label===n.label))return n;if(!(yield wg(this.logger,n))){const l=(i=c==null?void 0:c.devices.concat({label:n.label}))!=null?i:[{label:n.label}];return Ao.setItem(ou,JSON.stringify({devices:l}),this.logger),n}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const d=n.getSettings().deviceId;return o.filter(l=>l.deviceId!==d).some(l=>u(this,null,function*(){var h;if(n=yield this.mediaInterface.getAudioTrack(!1,l.deviceId),!(yield wg(this.logger,n))){const p=(h=c==null?void 0:c.devices.concat({label:n.label}))!=null?h:[{label:n.label}];return Ao.setItem(ou,JSON.stringify({devices:p}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),n})}}_p([k.trace("AudioMediaHandler.setTransformedTrack")],Rl.prototype,"setTransformedTrack",1);_p([k.trace("AudioMediaHandler.onTrackEnded")],Rl.prototype,"onTrackEnded",1);_p([k.trace("AudioMediaHandler.conditionallyChangeTrack")],Rl.prototype,"conditionallyChangeTrack",1);const I1=Rl;var so;class C1{constructor(e){g(this,so,void 0),m(this,"currentDevice"),f(this,so,e)}setupSpeaker(e){return u(this,null,function*(){var r,i;if(!(a(this,so)instanceof Sy))return;let n=e;if(e||([n]=(yield a(this,so).getAvailableDevicesByKind("audiooutput")).filter(o=>!sh(o))),!n)throw new I("No speaker found","1608");if(((r=this.currentDevice)==null?void 0:r.deviceId)===n.deviceId)return;this.currentDevice=n;const s=document.querySelectorAll("audio");(i=s[0])!=null&&i.setSinkId&&s.forEach(o=>u(this,null,function*(){if(typeof o.sinkId!="undefined"&&this.currentDevice.deviceId&&o.sinkId!==this.currentDevice.deviceId)try{yield o.setSinkId(this.currentDevice.deviceId)}catch{}}))})}}so=new WeakMap;const P1=C1;var id;class R1 extends Zs{constructor(e,r){const i=e.getValue("logger");super(i),m(this,"mediaInterface"),m(this,"audioMediaTrack"),m(this,"videoMediaTrack"),g(this,id,void 0),f(this,id,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}enableScreenShare(){return u(this,null,function*(){var e,r;try{const{audioTrack:i,videoTrack:n}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=n,this.addMediaTrackListeners(),((r=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:r.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",a(this,id).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch{}})}disableScreenShare(){var e,r;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(r=this.videoMediaTrack)==null||r.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 r=this.mediaInterface;if(!r.constraintsBuilder)throw new I("update constraints not supported for non web clients","1100",this.logger);try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){this.logger.error("ScreenShareHandler.updateConstraints.error",{error:i})}})}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),Ie.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}id=new WeakMap;const M1=R1;var A1=Object.defineProperty,D1=Object.getOwnPropertyDescriptor,Ml=(t,e,r,i)=>{for(var n=i>1?void 0:i?D1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&A1(e,r,n),n},ao,nd;class nc extends ky{constructor(e,r,i,n){super(e,r,i,n),g(this,ao,void 0),g(this,nd,{disablePerFrameCanvasRendering:!1}),f(this,ao,new o1(e))}onSetDevice(e){return u(this,null,function*(){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new I("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.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)){this.logger.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(r){throw this.logger.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new I("Failed to change device","1600",this.logger)}})}enableTrack(e,r){return u(this,null,function*(){if(this.trackEnabled){this.logger.warn("VideoMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,yield this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=yield this.mediaInterface.getVideoTrack(this.userSelectedDevice);yield this.setMediaTrack(i)})}setTransformedTrack(e){return u(this,null,function*(){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield a(this,ao).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,nd)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return u(this,null,function*(){f(this,nd,e)})}updateConstraints(e){return u(this,null,function*(){if(!this._mediaTrack)throw new I("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new I("update constraints not supported for non web clients","1100",this.logger);try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),yield this.setTransformedTrack(),this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(i){this.logger.error("VideoMediaHandler.updateConstraints.error",{error:i})}})}terminateMiddlewareWebWorker(){a(this,ao).terminateMiddlewareWebWorker()}onTrackEnded(){return u(this,null,function*(){this.logger.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")})}onTrackMuted(){this.logger.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e,r=!1){return u(this,null,function*(){if(!e||this.userSelectedDevice||r)return e;let i=e;const n=yield this.mediaInterface.getVideoInputDevices(),s=this.isNonPreferredDevice?n.filter(o=>!this.isNonPreferredDevice(o)):n;return!(s!=null&&s.length)||window.FAST_DYTE||s.find(o=>o.deviceId===e.getSettings().deviceId)||(i.stop(),this.logger.info("localmediahandler::setupstreams::found_video_non_preferred"),i=yield this.mediaInterface.getVideoTrack(s[0].deviceId)),i})}}ao=new WeakMap,nd=new WeakMap;Ml([k.trace("VideoMediaHandler.setTransformedTrack")],nc.prototype,"setTransformedTrack",1);Ml([k.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],nc.prototype,"setVideoMiddlewareGlobalConfig",1);Ml([k.trace("VideoMediaHandler.onTrackEnded")],nc.prototype,"onTrackEnded",1);Ml([k.trace("VideoMediaHandler.conditionallyChangeTrack")],nc.prototype,"conditionallyChangeTrack",1);const O1=nc,_g=Pr(pp());var Jt,bs,sd,oo;const co=class{constructor(t){if(g(this,Jt,void 0),g(this,bs,void 0),g(this,sd,void 0),g(this,oo,void 0),!t)throw new I("Could not load preset.","0904");f(this,Jt,t.config),f(this,sd,t.name),f(this,bs,t.ui||Pr(pp().ui)),f(this,oo,t.permissions.plugins.config)}static fromResponse(t){return new co(t)}static default(){return new co(_g)}static init(t,e=!0){return!t||e?new co(_g):new co(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:a(this,bs).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,Jt).viewType}get livestreamViewerQualities(){return a(this,Jt).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,Jt).maxVideoStreams}get maxScreenShareCount(){return a(this,Jt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,oo)).filter(t=>a(this,oo)[t].disabled)}get designTokens(){return a(this,bs).designTokens}get configDiff(){return a(this,bs).configDiff}get mediaConstraints(){var t,e,r,i,n,s,o,c,d,l,h,p,v,S,T,C,b,R,j,B,w,ee,re,ae;return{audio:{enableStereo:(i=(r=(e=(t=a(this,Jt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:Zn.audio.enableStereo,enableHighBitrate:(c=(o=(s=(n=a(this,Jt))==null?void 0:n.media)==null?void 0:s.audio)==null?void 0:o.enableHighBitrate)!=null?c:Zn.audio.enableHighBitrate},video:{quality:(p=(h=(l=(d=a(this,Jt))==null?void 0:d.media)==null?void 0:l.video)==null?void 0:h.quality)!=null?p:Zn.video.quality,frameRate:(C=(T=(S=(v=a(this,Jt))==null?void 0:v.media)==null?void 0:S.video)==null?void 0:T.frameRate)!=null?C:Zn.video.frameRate},screenshare:{quality:(B=(j=(R=(b=a(this,Jt))==null?void 0:b.media)==null?void 0:R.screenshare)==null?void 0:j.quality)!=null?B:Zn.screenshare.quality,frameRate:(ae=(re=(ee=(w=a(this,Jt))==null?void 0:w.media)==null?void 0:ee.screenshare)==null?void 0:re.frameRate)!=null?ae:Zn.screenshare.frameRate}}}get name(){return a(this,sd)}};let N1=co;Jt=new WeakMap,bs=new WeakMap,sd=new WeakMap,oo=new WeakMap;var V1=Object.defineProperty,L1=Object.getOwnPropertyDescriptor,Ty=(t,e,r,i)=>{for(var n=i>1?void 0:i?L1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&V1(e,r,n),n},lo,ad;class Ip extends Zt{constructor(e,r){const i=e.getValue("logger");super(i),g(this,lo,void 0),m(this,"state","IDLE"),m(this,"playbackUrl"),m(this,"ingestionCredentials"),m(this,"viewerCount"),g(this,ad,void 0),f(this,lo,r),f(this,ad,e),this.viewerCount=0}get telemetry(){return a(this,ad).getValue("telemetry")}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}start(){return u(this,arguments,function*(e={manualIngestion:!1}){if(!a(this,lo).permissions.canLivestream)throw this.logger.error("DyteLivestream::start::permission_denied"),new I("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=pt(),{playbackUrl:i,ingestionCredentials:n}=yield r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=n,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw this.logger.error("DyteRecording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new I("Error while starting livestream","1900",this.logger)}})}stop(){return u(this,null,function*(){if(!a(this,lo).permissions.canLivestream)throw this.logger.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 this.logger.error("DyteLivestream::stop::inconsistent_state"),new I("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),yield pt().stopLivestreaming()}catch(e){throw this.logger.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new I("Error while stopping livestream","1900",this.logger)}})}}lo=new WeakMap,ad=new WeakMap;Ty([k.trace("livestream.start")],Ip.prototype,"start",1);Ty([k.trace("livestream.stop")],Ip.prototype,"stop",1);var x1=Object.defineProperty,U1=Object.getOwnPropertyDescriptor,F1=(t,e,r,i)=>{for(var n=i>1?void 0:i?U1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&x1(e,r,n),n},uo,ho,Ni,ti;class by{constructor(e,r,i){m(this,"livestream"),g(this,uo,void 0),g(this,ho,void 0),g(this,Ni,void 0),g(this,ti,void 0),f(this,ti,e),f(this,ho,r),this.livestream=new Ip(e,r),f(this,Ni,i),this.setupEvents()}get logger(){return a(this,ti).getValue("logger")}get telemetry(){return a(this,ti).getValue("telemetry")}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=pt(),{status:r,playbackUrl:i,manualIngest:n,ingestionCredentials:s}=yield e.getActiveLivestream();this.livestream.playbackUrl=i,this.livestream.ingestionCredentials=s,r==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),r==="INVOKED"&&n&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")})}setupEvents(){a(this,Ni).on(F.startedLivestream,e=>u(this,null,function*(){this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,ho).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}})),a(this,Ni).on(F.livestreamingInvoked,e=>u(this,null,function*(){if(e.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,ho).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}})),a(this,Ni).on(F.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,Ni).on(F.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,Ni).on(F.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),a(this,ti).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,e=>u(this,null,function*(){var r;((r=e.flags)==null?void 0:r.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(f(this,uo,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),a(this,ti).getValue("peerSessionStore").on(P.PEER_CLOSED,e=>{e.id===a(this,uo)&&(f(this,uo,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,ti).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){if(!this.livestream.playbackUrl){this.logger.info("Fetching livestreaming state on leave stage");try{yield this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Failed to fetch livestreaming state on leave stage",{error:e})}}})),a(this,ti).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch{this.logger.error("Error: LivestreamController.fetchLivestream")}}))}}uo=new WeakMap,ho=new WeakMap,Ni=new WeakMap,ti=new WeakMap;F1([k.trace("LivestreamController.setupEvents")],by.prototype,"setupEvents",1);var B1=Object.defineProperty,W1=Object.getOwnPropertyDescriptor,sc=(t,e,r,i)=>{for(var n=i>1?void 0:i?W1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&B1(e,r,n),n},wt,vn,yn,ah,wy;class ra{constructor({name:e,socketHandler:r,meetingId:i}){g(this,ah),m(this,"name",""),g(this,wt,{}),g(this,vn,""),g(this,yn,void 0),m(this,"rateLimitConfig",{maxInvocations:5,period:1}),m(this,"bulkRateLimitConfig",{maxInvocations:5,period:1}),m(this,"listeners",{}),this.name=e,f(this,yn,r),f(this,vn,i)}set(e,r,i=!0,n=!1){return u(this,null,function*(){a(this,wt)[e]=r,i&&this.remoteSet(e,r),n&&(this.listeners[e]&&this.listeners[e].forEach(s=>s({[e]:a(this,wt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:a(this,wt)[e]})))})}remoteSet(e,r){a(this,yn).storeInsertKeys(a(this,vn),this.name,[{key:e,payload:r}])}bulkSet(e){return u(this,null,function*(){e.forEach(({key:r,payload:i})=>{a(this,wt)[r]=i}),a(this,yn).storeInsertKeys(a(this,vn),this.name,e)})}update(e,r,i=!0){return u(this,null,function*(){U(this,ah,wy).call(this,e,r,i)})}delete(e,r=!0,i=!1){return u(this,null,function*(){if(a(this,wt)[e]&&delete a(this,wt)[e],r)return a(this,yn).storeDeleteKeys(a(this,vn),this.name,[{key:e}]);i&&(this.listeners[e]&&(this.listeners[e].forEach(n=>n({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[e]:void 0})))})}bulkDelete(e){return u(this,null,function*(){return e.forEach(({key:r})=>{a(this,wt)[r]&&delete a(this,wt)[r]}),a(this,yn).storeDeleteKeys(a(this,vn),this.name,e)})}get(e){if(a(this,wt)[e])return a(this,wt)[e]}getAll(){return a(this,wt)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(e,r){this.rateLimitConfig.maxInvocations=e,this.rateLimitConfig.period=r}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(e,r){this.bulkRateLimitConfig.maxInvocations=e,this.bulkRateLimitConfig.period=r}subscribe(e,r){if(this.listeners[e]){this.listeners[e].push(r);return}this.listeners[e]=[r]}unsubscribe(e,r){var i;if(r){this.listeners[e]=((i=this.listeners[e])==null?void 0:i.filter(n=>n!==r))||[];return}this.listeners[e]&&delete this.listeners[e]}populate(e){f(this,wt,e)}}wt=new WeakMap,vn=new WeakMap,yn=new WeakMap,ah=new WeakSet,wy=function(t,e,r=!0){let i;const n=a(this,wt)[t],s=Object.prototype.toString.call(e),o=Object.prototype.toString.call(n);if(s!==o){this.set(t,e);return}switch(o){case"[object Array]":i=[...n,...e];break;case"[object Object]":i=V(V({},n),e);break;case"[object Map]":i=new Map([...n,...e]);break;case"[object Set]":i=new Set([...n,...e]);break;default:i=e;break}this.set(t,i,r)};sc([Bt(ta,"rateLimitConfig")],ra.prototype,"remoteSet",1);sc([Bt(ta,"bulkRateLimitConfig")],ra.prototype,"bulkSet",1);sc([Bt(ta,"rateLimitConfig")],ra.prototype,"update",1);sc([Bt(ta,"rateLimitConfig")],ra.prototype,"delete",1);sc([Bt(ta,"bulkRateLimitConfig")],ra.prototype,"bulkDelete",1);var xs,Us,od,cu,Yd,Mn,oh,_y;class j1{constructor(e,r){g(this,od),g(this,oh),m(this,"stores",new Map),g(this,xs,void 0),g(this,Us,""),g(this,Yd,void 0),g(this,Mn,new Map),f(this,xs,r),f(this,Us,e.getValue("meetingId")),f(this,Yd,e),U(this,oh,_y).call(this)}create(e){const r=new ra({name:e,socketHandler:a(this,xs),meetingId:a(this,Us)});return a(this,xs).storeGetKeys(a(this,Us),e,[]),new Promise((i,n)=>{const s=setTimeout(()=>n(Error("Failed")),3e3);a(this,Mn).set(e,{rejectTimeout:s,resolve:i,store:r})})}}xs=new WeakMap,Us=new WeakMap,od=new WeakSet,cu=function(){return a(this,Yd).getValue("peerId")},Yd=new WeakMap,Mn=new WeakMap,oh=new WeakSet,_y=function(){[J.storeInsertKeys,J.storeGetKeys,J.storeDeleteKeys].forEach(t=>{a(this,xs).on(t,e=>u(this,null,function*(){var r,i;if(e.pluginId!==a(this,Us))return;const n=(r=e.storeItems)==null?void 0:r.map(o=>{var c;return{timestamp:o.timestamp,peerId:o.peerId,payload:JSON.parse((c=o.payload)!=null&&c.length?new TextDecoder().decode(o.payload):"{}"),key:o.storeKey}});if(t===J.storeGetKeys){const o=a(this,Mn).get(e.storeName),c=this.stores.get(e.storeName)||(o==null?void 0:o.store);a(this,Mn).get(e.storeName)&&(this.stores.set(e.storeName,o.store),o.resolve(c),clearTimeout(o.rejectTimeout),a(this,Mn).delete(e.storeName)),n.forEach(d=>{c.set(d.key,d.payload,!1,!1)});return}const s=this.stores.get(e.storeName)||((i=a(this,Mn).get(e.storeName))==null?void 0:i.store);s!==void 0&&(t===J.storeInsertKeys&&n.forEach(({key:o,peerId:c,payload:d})=>{c!==a(this,od,cu)&&s.set(o,d,!1,!0)}),t===J.storeDeleteKeys&&n.forEach(({key:o,peerId:c})=>{c!==a(this,od,cu)&&s.delete(o,!1,!0)}))}))})};function An(t){var e,r,i,n,s,o,c,d,l,h,p,v,S;return t?{media:{audio:{enabled:t.audioEnabled,trackId:(e=t.audioTrack)==null?void 0:e.id,permission:"mediaPermissions"in t?(r=t.mediaPermissions)==null?void 0:r.audio:null},video:{enabled:t.videoEnabled,trackId:(i=t.videoTrack)==null?void 0:i.id,permission:"mediaPermissions"in t?(n=t.mediaPermissions)==null?void 0:n.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(s=t.mediaPermissions)==null?void 0:s.screenshare:null,audio:{enabled:(c=(o=t.screenShareTracks)==null?void 0:o.audio)==null?void 0:c.enabled,trackId:(l=(d=t.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(p=(h=t.screenShareTracks)==null?void 0:h.video)==null?void 0:p.enabled,trackId:(S=(v=t.screenShareTracks)==null?void 0:v.video)==null?void 0:S.id}}}}:{}}var H1=Object.defineProperty,G1=Object.getOwnPropertyDescriptor,ia=(t,e,r,i)=>{for(var n=i>1?void 0:i?G1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&H1(e,r,n),n};const q1=.8,$1=1.2;var xa,Ua,sr,es,Fa,cn,ts,rs,Ba,du,Ig,Ti,Cc,dn,is,Wa,bi,lu,Pc,uu,hu,Cg,pu,Pg,Rg;let fi=(Rg=class extends Zt{constructor(t,e,r,i){const n=t.getValue("logger");super(n),g(this,es),g(this,cn),g(this,rs),g(this,du),g(this,is),g(this,Pc),g(this,hu),g(this,pu),m(this,"id"),m(this,"userId"),m(this,"name"),m(this,"picture"),m(this,"isHost"),m(this,"customParticipantId"),m(this,"flags"),m(this,"device"),m(this,"videoTrack"),m(this,"audioTrack"),m(this,"screenShareTracks"),m(this,"videoEnabled"),m(this,"audioEnabled"),m(this,"screenShareEnabled"),m(this,"producers"),m(this,"manualProducerConfig"),g(this,xa,void 0),m(this,"supportsRemoteControl",!1),g(this,Ua,void 0),m(this,"presetName"),g(this,sr,void 0),g(this,Ti,void 0),g(this,Cc,void 0),g(this,dn,new Map),g(this,bi,1),g(this,lu,fp(ee=>{if(!this.videoTrack)return;const{clientWidth:re,clientHeight:ae}=ee,{width:Me,height:Ze}=this.videoTrack.getSettings();if(!Me||!Ze)return;const jt=Ze/ae,A=Me/re,E=Math.max(jt,A);E>$1&&a(this,bi)===1?(f(this,bi,0),a(this,sr).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,bi)})):E<q1&&a(this,bi)===0&&(f(this,bi,1),a(this,sr).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,bi)}))},2e3)),f(this,sr,t);const{id:s,userId:o,displayName:c,device:d,picture:l,isHost:h,flags:p,clientSpecificId:v,stageStatus:S,customParticipantId:T,audioMuted:C,audioTrack:b,videoEnabled:R=!1,videoTrack:j,producers:B,metadata:w}=e;this.id=s,this.userId=o,this.name=c,this.device=d,this.picture=l,this.isHost=h,this.flags=p,this.manualProducerConfig=II,f(this,Ua,S!=null?S:"ON_STAGE"),this.customParticipantId=T!=null?T:v,this.audioEnabled=!C,this.audioTrack=b,this.videoEnabled=R,this.videoTrack=j,this.screenShareTracks={audio:void 0,video:void 0},this.producers=B!=null?B:[],this.presetName=w==null?void 0:w.preset_name,f(this,xa,!1),f(this,Ti,r),f(this,Cc,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),U(this,Pc,uu).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return a(this,Ua)}get telemetry(){return a(this,sr).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("DyteParticipant::setVideoEnabled::videoUpdate",V({},An(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("DyteParticipant::setAudioEnabled::audioUpdate",V({},An(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",U(this,Pc,uu)),a(this,cn,ts)&&(this.on("audioUpdate",U(this,hu,Cg)),this.on("screenShareUpdate",U(this,pu,Pg)))}pin(){return u(this,null,function*(){if(!a(this,rs,Ba))throw new I("Can`t pin participant without joining room","1205");if(!a(this,Ti).permissions.pinParticipant)throw new I("You do not have permission to pin participants.","1201");return a(this,es,Fa).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!a(this,rs,Ba))throw new I("Can`t unpin participant without joining room","1205");if(!a(this,Ti).permissions.pinParticipant)throw new I("You do not have permission to unpin participants.","1201");return a(this,es,Fa).pinPeer(null)})}setIsPinned(t,e=!0){var r;f(this,xa,t);const i=t?"pinned":"unpinned";(r=a(this,is,Wa))==null||r.updateSource(this.id,{pinned:t}),e&&this.emit(i,this)}disableAudio(){return u(this,null,function*(){const t=this.id;if(this.logger.info("DyteParticipant::disable_audio",{dyteParticipant:{id:t}}),!a(this,rs,Ba))throw new I("Can`t disable participant audio without joining room","1205");if(a(this,Ti).permissions.canDisableParticipantAudio)return a(this,es,Fa).disableAudio(t);throw this.logger.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(this.logger.info("DyteParticipant::kick",{dyteParticipant:{id:t}}),!a(this,du,Ig))throw new I("Can`t kick participant without joining room","1205");if(a(this,Ti).permissions.kickParticipant){yield a(this,sr).getValue("peerSessionStore").emitAsync(P.KICK_PEER,{peerId:t});return}throw this.logger.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(this.logger.info("DyteParticipant::disable_video",{dyteParticipant:{id:t}}),!a(this,rs,Ba))throw new I("Can`t disable participant video without joining room","1205");if(a(this,Ti).permissions.canDisableParticipantVideo)return a(this,es,Fa).disableVideo(t);throw this.logger.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 a(this,Cc).getUserPermissions(this.userId)})}setStageStatus(t){f(this,Ua,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,xa)}registerVideoElement(t){var e,r,i,n;if(!t)return;let s;(r=(e=a(this,dn).get(t))==null?void 0:e.observer)==null||r.disconnect(),"ResizeObserver"in window&&(s=new ResizeObserver(()=>a(this,lu).call(this,t)),s.observe(t)),a(this,dn).set(t,{observer:s}),this.updateVideo(t),(n=a(this,is,Wa))==null||n.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(i=this.raised)!=null?i:!1)}deregisterVideoElement(t){var e,r,i,n;if(!t){(e=a(this,is,Wa))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,dn).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,dn).delete(t),(n=a(this,is,Wa))==null||n.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((r==null?void 0:r.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"}},xa=new WeakMap,Ua=new WeakMap,sr=new WeakMap,es=new WeakSet,Fa=function(){return a(this,sr).getValue("roomNodeClient")},cn=new WeakSet,ts=function(){return a(this,sr).getValue("audioPlayback")},rs=new WeakSet,Ba=function(){return a(this,sr).getValue("connectionHandler").mediaJoined},du=new WeakSet,Ig=function(){return a(this,sr).getValue("connectionHandler").socketJoined},Ti=new WeakMap,Cc=new WeakMap,dn=new WeakMap,is=new WeakSet,Wa=function(){return a(this,sr).getValue("pip")},bi=new WeakMap,lu=new WeakMap,Pc=new WeakSet,uu=function(){Array.from(a(this,dn).keys()).forEach(this.updateVideo)},hu=new WeakSet,Cg=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,cn,ts))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,cn,ts))==null||e.removeParticipantTrack(this.id)},pu=new WeakSet,Pg=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,cn,ts))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,cn,ts))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},Rg);ia([k.trace("DyteParticipant.disableAudio")],fi.prototype,"disableAudio",1);ia([k.trace("DyteParticipant.kick")],fi.prototype,"kick",1);ia([k.trace("DyteParticipant.disableVideo")],fi.prototype,"disableVideo",1);ia([k.trace("DyteParticipant.getPermissions")],fi.prototype,"getPermissions",1);ia([k.trace("DyteParticipant.setStageStatus")],fi.prototype,"setStageStatus",1);fi=ia([ft("1200")],fi);class ja extends fy{constructor(e,r){const{onAddEvent:i="participantJoined",onDeleteEvent:n="participantLeft",onClearEvent:s="participantsCleared"}=r!=null?r:{};super({onAddEvent:i,onDeleteEvent:n,onClearEvent:s},e)}add(e,r=!0){return this.has(e.id)&&Object.is(this.get(e.id),e)===!1&&this.delete(e.id),super.add(e,r)}clear(e=!0,r=!1){return super.clear(e,r)}delete(e,r=!0,i=!1){return super.delete(e,r,i)}}var Sn;class J1 extends Zs{constructor(e){super(e),g(this,Sn,void 0),f(this,Sn,new Map)}__set(e,r){return a(this,Sn).set(e,r)}__clear(){return a(this,Sn).clear()}get(e){return a(this,Sn).get(e)}toArray(){return Array.from(a(this,Sn).values())}}Sn=new WeakMap;class K1{constructor(){m(this,"_orderedArray"),m(this,"_map"),this._map=new Map,this._orderedArray=[]}add(e,r){if(!this._map.has(e))return this._map.set(e,{peerId:e,priority:r}),this._orderedArray.splice(Math.max(r-1,0),0,e),this.index(e);const i=this.index(e);this.delete(e);const n=this.add(e,r);return i!==n?n:-1}delete(e){if(this._map.has(e)){const r=this.index(e);this._map.delete(e),this._orderedArray.splice(r,1)}}index(e){return this._map.has(e)?this._orderedArray.indexOf(e):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class z1{constructor(){m(this,"_activeSpeakerPeers"),m(this,"_compulsoryPeers"),this._activeSpeakerPeers=new K1,this._compulsoryPeers=new Set}add(e,r,i){if(!e)return-1;if(r<0)return this._compulsoryPeers.add(e),0;const n=i.getValue("logger");if(this.compulsoryPeers.includes(e)&&(r>0||r===246267631)){if(n.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),r===246267631)return-1}else if(r===229490415)return this.delete(e,i),-1;return this._activeSpeakerPeers.add(e,r)}delete(e,r){const i=r==null?void 0:r.getValue("logger");i==null||i.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 Iy=new z1;var Y1=Object.defineProperty,Q1=Object.getOwnPropertyDescriptor,rr=(t,e,r,i)=>{for(var n=i>1?void 0:i?Q1(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&Y1(e,r,n),n};const X1=["ACTIVE_GRID","PAGINATED","MANUAL"];var Ae,Rc,mu,ns,Ha,Ga,Mc,ss,Ht,Mg;let Rt=(Mg=class extends Zt{constructor(t,e,r){const i=t.getValue("logger");super(i),g(this,Rc),g(this,ns),g(this,Ga),m(this,"waitlisted"),m(this,"joined"),m(this,"active"),m(this,"videoSubscribed"),m(this,"audioSubscribed"),m(this,"pinned"),m(this,"all"),g(this,Ae,void 0),g(this,ss,void 0),g(this,Ht,void 0),m(this,"rateLimitConfig",{maxInvocations:5,period:1}),m(this,"viewMode"),m(this,"currentPage"),m(this,"lastActiveSpeaker"),m(this,"selectedPeers",Iy),f(this,Ae,t),f(this,ss,e),f(this,Ht,r),this.waitlisted=new ja(i),this.joined=new ja(i),this.videoSubscribed=new ja(i),this.audioSubscribed=new ja(i),this.active=this.videoSubscribed,this.pinned=new ja(i),this.all=new J1(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,Ae).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,Ae).getValue("telemetry")}setupEvents(){a(this,Ae).getValue("peerSessionStore").on(P.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,Ae).getValue("modules").e2ee)==null?void 0:r.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${e}, but encryption wasn't enabled in init.defaults`,code:"1702"})});const t=a(this,Ae).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=a(this,Ae))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new I("0 <= Max active participants count limit <= 24","1203");a(this,Ae).setValue("maxPreferredStreams",t),a(this,Ga,Mc)&&a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(r=>r.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var e,r;if(!a(this,ns,Ha))throw new I("Can`t accept waiting room request without joining room","1205");const i=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;return a(this,Ht).acceptWaitingRoomRequest([i])}acceptAllWaitingRoomRequest(t){return u(this,null,function*(){const e=t.map(r=>{var i,n;return(n=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?n:r});return a(this,Ht).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return u(this,null,function*(){var e,r;if(!a(this,ns,Ha))throw new I("Can`t reject waiting room request without joining room","1205");const i=(r=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?r:t;a(this,Ht).rejectWaitingRoomRequest([i])})}setViewMode(t){return u(this,null,function*(){if(this.logger.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(e=>X1.includes(e))(t))throw this.logger.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){this.logger.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})})}subscribe(t){return u(this,arguments,function*(e,r=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new I("MANUAL subscription mode was not activated.","1206");e.forEach(i=>{const n=this.joined.get(i);n&&(r.includes("audio")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{audio:!0}),this.audioSubscribed.has(n.id)||this.audioSubscribed.add(n)),r.includes("video")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{video:!0}),this.videoSubscribed.has(n.id)||this.videoSubscribed.add(n)),r.includes("screenshareAudio")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareAudio:!0}),this.audioSubscribed.has(n.id)||this.audioSubscribed.add(n)),r.includes("screenshareVideo")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareVideo:!0}),this.videoSubscribed.has(n.id)||this.videoSubscribed.add(n)))}),a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})})}unsubscribe(t){return u(this,arguments,function*(e,r=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new I("MANUAL subscription mode was not activated.","1206");e.forEach(i=>{const n=this.joined.get(i);n&&(r.includes("audio")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{audio:!1}),n.manualProducerConfig.screenshareAudio||this.audioSubscribed.delete(n.id)),r.includes("video")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{video:!1}),n.manualProducerConfig.screenshareVideo||this.videoSubscribed.delete(n.id)),r.includes("screenshareAudio")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareAudio:!1}),n.manualProducerConfig.audio||this.audioSubscribed.delete(n.id)),r.includes("screenshareVideo")&&(n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareVideo:!1}),n.manualProducerConfig.video||this.videoSubscribed.delete(n.id)))}),a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})})}getPeerIdsForCurrentPage(){this.logger.info("DyteParticipants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(o=>this.joined.has(o)),r=Array.from(this.pinned.keys()).filter(o=>!e.includes(o)),i=Array.from(this.joined.toArray().filter(o=>o.stageStatus==="ON_STAGE").map(o=>o.id)),n=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),s=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(n,s))}setPage(t){return u(this,null,function*(){if(this.logger.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 this.logger.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,a(this,Ae).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.viewMode,page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}})}disableAllAudio(t){return u(this,null,function*(){if(this.logger.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!a(this,Ga,Mc))throw new I("Can`t disable all audio without joining room","1205");if(a(this,ss).permissions.canAllowParticipantAudio)return a(this,Rc,mu).muteAll(t);throw this.logger.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(this.logger.info("DyteParticipants::disable_all_video"),!a(this,Ga,Mc))throw new I("Can`t disable all video without joining room","1205");if(a(this,ss).permissions.canAllowParticipantVideo)return a(this,Rc,mu).muteAllVideo();throw this.logger.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 a(this,Ae).getValue("peerSessionStore").emitAsync(P.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(this.logger.info("DyteParticipants::kick_all"),a(this,Ae).getValue("viewType")!=="LIVESTREAM"&&!a(this,ns,Ha))throw new I("Can`t kick all without joining room","1205");if(!a(this,ss).permissions.kickParticipant)throw this.logger.error("DyteParticipants::unauthorized_kick_all"),new I("Unauthorized: User does not have permission to kick peers.","1201");const t=a(this,Ae).getValue("flagsmith").hasFeature(Z.PROPAGATE_KICK_ALL);a(this,Ht).kickAll(t)})}broadcastMessage(t,e,r){return u(this,null,function*(){if(this.logger.info("DyteParticipants::broadcastMessage"),!a(this,ns,Ha))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(r)if("meetingIds"in r)yield a(this,Ht).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(n=>{var s;return(s=r.presetNames)==null?void 0:s.includes(n.presetName)}).map(n=>n.id),yield a(this,Ht).broadcastToPeers(t,i,e)}else yield a(this,Ht).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,r){return u(this,null,function*(){return(yield a(this,Ht).getRoomPeers(t,e,r)).peers.map(Ei.formatSocketPeerMessage)})}updatePermissions(t,e){return u(this,null,function*(){const r=this.joined.toArray().filter(n=>t.includes(n.id)).map(n=>n.userId),i=[...new Set(r)];if(!i.length)throw new I("Cannot update permissions, no valid userIDs found","1204");a(this,Ht).updatePermissions(i,e)})}getParticipantsInMeetingPreJoin(){return u(this,null,function*(){return a(this,Ht).getRoomPeersNonPaginated()})}},Ae=new WeakMap,Rc=new WeakSet,mu=function(){return a(this,Ae).getValue("roomNodeClient")},ns=new WeakSet,Ha=function(){var t;return((t=a(this,Ae).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Ga=new WeakSet,Mc=function(){var t;return((t=a(this,Ae).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},ss=new WeakMap,Ht=new WeakMap,Mg);rr([k.trace("DyteParticipants.setViewMode")],Rt.prototype,"setViewMode",1);rr([k.trace("DyteParticipants.setPage")],Rt.prototype,"setPage",1);rr([k.trace("DyteParticipants.disableAllAudio")],Rt.prototype,"disableAllAudio",1);rr([k.trace("DyteParticipants.disableAllVideo")],Rt.prototype,"disableAllVideo",1);rr([k.trace("DyteParticipants.disablePeerAudio")],Rt.prototype,"disableAudio",1);rr([k.trace("DyteParticipants.disablePeerVideo")],Rt.prototype,"disableVideo",1);rr([k.trace("DyteParticipants.kickPeer")],Rt.prototype,"kick",1);rr([k.trace("DyteParticipants.kickAll")],Rt.prototype,"kickAll",1);rr([k.trace("DyteParticipants.broadcastMessage"),Bt(ta,"rateLimitConfig")],Rt.prototype,"broadcastMessage",1);rr([k.trace("DyteParticipants.getAllJoinedPeers"),Bt({maxInvocations:10,period:60})],Rt.prototype,"getAllJoinedPeers",1);rr([k.trace("DyteParticipant.updatePermissions"),Bt({maxInvocations:1e3,period:60})],Rt.prototype,"updatePermissions",1);rr([k.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],Rt.prototype,"getParticipantsInMeetingPreJoin",1);Rt=rr([ft("1200")],Rt);var Xs=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t.CLOSED="closed",t))(Xs||{}),Oe=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(Oe||{}),Z1=Object.defineProperty,eN=Object.getOwnPropertyDescriptor,$n=(t,e,r,i)=>{for(var n=i>1?void 0:i?eN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&Z1(e,r,n),n},gr,Vr,qa,Ag;const Cy=(Ag=class{constructor(t,e,r,i){switch(m(this,"participants"),m(this,"self"),m(this,"selectedPeers",Iy),m(this,"maxSpatialLayerUpdates",new Map),m(this,"consumerPeerMap"),m(this,"events"),m(this,"roomSocketHandler"),m(this,"context"),m(this,"videoPeerConsumerMap",new Map),g(this,gr,{mode:"ACTIVE_GRID",page:0}),g(this,Vr,!1),g(this,qa,!1),m(this,"updateConsumerSpatialLayers",fp(()=>{const n={},s=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(s.entries()).forEach(([o,c])=>{n[c]===void 0&&(n[c]={layer:c,consumerIds:[]}),n[c].consumerIds.push(o)}),Object.keys(n).forEach(o=>{const c=n[o];this.logger.log(`Switching max spatial layer to ${c.layer}`,{consumerIds:c.consumerIds}),this.roomNodeClient.switchConsumersToLayer(c.consumerIds,c.layer)})},2e3)),m(this,"updateConsumers",(n,s)=>u(this,null,function*(){this.logger.info(`updateConsumers: Starting consumer updates - AddProducers: ${n.length}, RemoveProducers: ${s.length}, ConsumersSyncing: ${a(this,Vr)}`);try{n.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for ${n.length} producers: [${n.map(o=>o.producerId).join(", ")}]`),yield this.roomNodeClient.createConsumers(n),this.logger.info("updateConsumers: Successfully created consumers."))}catch(o){this.logger.error("updateConsumers: Error creating consumers",{error:o})}try{s.length!==0&&(this.logger.info(`updateConsumers: Closing consumers for ${s.length} producers: [${s.map(o=>o.producerId).join(", ")}]`),yield this.roomNodeClient.closeConsumers(s),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(o){this.logger.error("updateConsumers: Error closing consumers",{error:o})}this.logger.info("updateConsumers: Completed consumer updates.")})),this.context=t,this.roomSocketHandler=r,this.participants=new Rt(t,e,this.roomSocketHandler),this.self=e,this.consumerPeerMap=new Map,i){case Oe.HIVE:{this.events=dr;break}case Oe.CF:{this.events=Ir;break}default:this.events=dr}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")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}setupEvents(){this.roomSocketHandler.on(F.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(P.SOCKET_PEERS,t=>u(this,null,function*(){const e=this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN);if(e){const r=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(i=>i.peerId))}:void 0;this.logger.info("Processing socket peers",r)}t==null||t.forEach(r=>{r.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(r))}),e&&this.logger.info("Processed socket peers")})),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:t})=>{this.logger.info("PEER_INFO:::MEDIA_JOIN",{dyteParticipant:{id:t.peerId,maskedName:[...(t==null?void 0:t.displayName)||""].map((e,r)=>r%2?"*":e).join("")}}),this.logger.info("events.peerJoinedBroadcast",{peers:t.peerId}),this.onParticipantMediaJoined(t.peerId,t.producerStates,t.capabilities)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:t,selectedPeers:e,roomState:r})=>{if(this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN)){const s=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(o=>o.peerId))}:void 0;this.logger.info("events.selfJoinComplete",s)}t.forEach(({peerId:s,producerStates:o,capabilities:c})=>this.onParticipantMediaJoined(s,o,c));const{audioPeers:i,compulsoryPeers:n}=e!=null?e:{};r.pinnedPeerIds.length!==0&&this.onParticipantPinned(r.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],n),this.logger.info("selfJoinComplete: Emitting UPDATE_ACTIVE with createAllConsumers=true"),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{createAllConsumers:!0})}),this.context.getValue("peerSessionStore").on(P.MAX_SPATIAL_LAYER_CHANGE,({peerId:t,maxSpatialLayer:e})=>{const r=this.videoPeerConsumerMap.get(t);r&&(this.context.getValue("flagsmith").hasFeature(Z.DISABLE_LAYER_SWITCH)||(this.maxSpatialLayerUpdates.set(r,e),this.updateConsumerSpatialLayers()))}),this.context.getValue("peerSessionStore").on(P.NEW_PRODUCER,({peerId:t,producer:e})=>{const r=this.participants.joined.get(t);if(!r){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:e==null?void 0:e.producerId,kind:e==null?void 0:e.kind,status:"not_initialized",appData:{screenShare:e==null?void 0:e.screenShare}},dyteParticipant:{id:t}});return}r.producers.push(e),this.logger.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:"not_initialized",appData:{screenShare:e==null?void 0:e.screenShare}}}),(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.logger.info(`NEW_PRODUCER: scheduling syncConsumer (AUTO mode) - Producer: ${e.producerId}, Peer: ${t}, Kind: ${e.kind}, ScreenShare: ${e.screenShare}, ConsumersSyncing: ${a(this,Vr)}, VideoSub: ${e.kind==="video"?this.participants.videoSubscribed.has(t):"N/A"}, AudioSub: ${e.kind==="audio"?this.participants.audioSubscribed.has(t):"N/A"}`),this.scheduleSyncConsumers({source:"NEW_PRODUCER_AUTO"})):this.logger.info("ParticipantController::NEW_PRODUCER::not_consuming_producer_auto",{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.context.getValue("peerSessionStore").on(P.PRODUCER_CLOSED,({peerId:t,producerId:e})=>{const r=this.participants.joined.get(t);if(!r){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:t}});return}r.producers=r.producers.filter(i=>i.producerId!==e)}),this.context.getValue("peerSessionStore").on(P.PRODUCER_TOGGLE,({peerId:t,producerId:e,paused:r,kind:i})=>{const n=this.participants.joined.get(t);if(n){i==="audio"&&n.setAudioEnabled(!r);const s=n.producers.find(o=>o.producerId===e);s&&(s.pause=r),i==="video"&&this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,t=>{let e;if(t&&(e=t.participantId),!this.mediaJoined)return;const r=e;this.onParticipantPinned(r);const i=this.participants.joined.get(r);i&&(this.logger.info(`globalPeerPinBroadcast: Scheduling audio/video consumer sync for pinned participant ${r} - ProducerCount: ${i.producers.length}, ConsumersSyncing: ${a(this,Vr)}, ProducerIds: [${i.producers.map(n=>n.producerId).join(", ")}]`),this.scheduleSyncConsumers({source:"GLOBAL_PEER_PIN"}))}),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(r=>({peerId:r.peerId,priority:r.priority}));this.updateActiveParticipantsWithPriorities(e,!0)})}waitingRoomRequestHandler(t){const e=t.requests.filter(i=>!this.participants.waitlisted.toArray().find(n=>n.userId===i.userId)),r=this.participants.waitlisted.toArray().filter(i=>!t.requests.find(n=>n.userId===i.userId));e.forEach(i=>this.participants.waitlisted.add(new fi(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))),r.forEach(i=>this.participants.waitlisted.delete(i.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(t){const{compulsoryPeers:e}=this.selectedPeers,r=e.filter(c=>this.participants.joined.has(c)),i=Array.from(this.participants.pinned.keys()).filter(c=>!r.includes(c)),n=Array.from(this.participants.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),s=Math.max((t-1)*(this.maxPreferredStreams-r.length-i.length)),o=t*(this.maxPreferredStreams-r.length-i.length);return r.concat(i,n.slice(s,o))}selectActivePeers(t){const e=new Map,r=Array.from(this.participants.joined.toArray().filter(h=>h.stageStatus==="ON_STAGE").map(h=>(e.set(h.id,!0),h.id))),i=this.selectedPeers.peers,n=this.participants.pinned.toArray().reduce((h,p)=>(p.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(p.id):h.push(p.id),h),[]),s=this.self.stageStatus==="ON_STAGE"?1:0,o=t-s,c=new Set(i.concat(n).filter(h=>h!==this.self.id&&e.has(h)));let d=Array.from(c);const l=o-c.size;if(l>=0){const h=r.filter(p=>!c.has(p)&&p!==this.self.id).slice(0,l);d=Array.from(c).concat(h)}else d=d.slice(0,o);return d}updateMediaSubscribedMaps(t,e){const{page:r}=e!=null?e:{};t&&a(this,gr).mode!==t&&(a(this,gr).mode=t),r&&a(this,gr).page!==r&&(a(this,gr).page=r);const{mode:i,page:n}=a(this,gr);switch(i){case"PAGINATED":{if(!n)return;const s=this.selectPagePeers(n),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,s),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:s});break}case"ACTIVE_GRID":{const s=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,s),this.updateParticipantsMap(this.participants.audioSubscribed,o);break}case"MANUAL":break;default:throw new Error(`View mode ${t} not supported`)}}scheduleSyncConsumers(t){return u(this,arguments,function*({source:e}){var r,i,n;const s=((r=a(this,gr))==null?void 0:r.mode)==="PAGINATED"&&!a(this,Vr)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${e}, ViewMode: ${(i=a(this,gr))==null?void 0:i.mode}, ConsumersSyncing: ${a(this,Vr)}, Delay: ${s}, Page: ${(n=a(this,gr))==null?void 0:n.page}`),setTimeout(()=>this.syncConsumers(),s)})}syncConsumers(){return u(this,null,function*(){var t,e,r,i,n;if(((r=(e=(t=this.context.getValue("connectionHandler"))==null?void 0:t.mediaState)==null?void 0:e.recv)==null?void 0:r.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(a(this,Vr)){f(this,qa,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),f(this,Vr,!0),f(this,qa,!1);let s=[];this.participants.videoSubscribed.forEach(p=>{var v,S;const T=this.participants.joined.get(p.id),C=(S=(v=p.producers)==null?void 0:v.filter(b=>b.kind==="video"))!=null?S:[];T&&C!=null&&C.length&&C.forEach(b=>{var R,j,B,w;const ee=((j=(R=T.manualProducerConfig)==null?void 0:R.video)!=null?j:!0)&&b.kind==="video"&&!b.screenShare,re=((w=(B=T.manualProducerConfig)==null?void 0:B.screenshareVideo)!=null?w:!0)&&b.kind==="video"&&b.screenShare;(ee||re)&&(b.pause||s.push(b))})}),this.participants.audioSubscribed.forEach(p=>{var v,S;const T=this.participants.joined.get(p.id),C=(S=(v=p.producers)==null?void 0:v.filter(b=>b.kind==="audio"))!=null?S:[];T&&C!=null&&C.length&&C.forEach(b=>{var R,j,B,w;const ee=((j=(R=T.manualProducerConfig)==null?void 0:R.audio)!=null?j:!0)&&b.kind==="audio"&&!b.screenShare,re=((w=(B=T.manualProducerConfig)==null?void 0:B.screenshareAudio)!=null?w:!0)&&b.kind==="audio"&&b.screenShare;(ee||re)&&s.push(b)})}),s=bI(s,p=>p.producerId);const o=new Map;s.forEach(p=>{o.set(p.producerId,p)});const c=(i=this.roomNodeClient)==null?void 0:i.getConsumers(),d=s.filter(p=>!(c!=null&&c.has(p.producerId))),l=[];let h=Array.from((n=c==null?void 0:c.values())!=null?n:[]).map(p=>p.peerId);h=TI(h),h==null||h.forEach(p=>{var v;const S=this.participants.joined.get(p);if(!S){this.logger.warn(`Peer with ${p} doesn't exist in joined list but producers of it are being consumed.`);return}(v=S.producers)!=null&&v.length&&S.producers.forEach(T=>{const C=T.consumer&&c.has(T.consumer.id);!o.has(T.producerId)&&(c.has(T.producerId)||C)&&l.push(T)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${d.length} [${d.map(p=>p.producerId).join(", ")}], RemoveProducers: ${l.length} [${l.map(p=>p.producerId).join(", ")}]`.substring(0,5e3));try{d.length>0||l.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${d.length} and removing ${l.length}.`),yield this.updateConsumers(d,l),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(p){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:p})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),f(this,Vr,!1)}a(this,qa)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())})}computeActivateParticipants(t,e){const r=t.map((n,s)=>({peerId:n,priority:s+1})),i=e==null?void 0:e.map((n,s)=>({peerId:n,priority:-(s+1)}));r.push(...i!=null?i:[]),r.length>0&&this.updateActiveParticipantsWithPriorities(r)}createParticipantObjFromSocketPeer(t){const e=Cy.formatSocketPeerMessage(t);return new fi(this.context,q(V({},e),{isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0}),this.self,this.roomSocketHandler)}updatePipSource(t,e){var r,i;e?(r=this.pip)==null||r.enableSource(t):(i=this.pip)==null||i.disableSource(t)}onParticipantMediaJoined(t,e,r){if(!this.mediaJoined||t===this.self.id)return;const i=this.participants.joined.get(t);if(this.logger.info("PEER_INFO:::SOCKET_ON_MEDIA_JOIN",{dyteParticipant:{id:i.id,maskedName:[...(i==null?void 0:i.name)||""].map((n,s)=>s%2?"*":n).join("")}}),!i){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${t}`);return}this.logger.info(`onParticipantMediaJoined: peer ${t} has joined media room. Processing.`),e.forEach(n=>{n.kind===$r.AUDIO&&!n.screenShare?i.setAudioEnabled(!n.pause):n.kind===$r.VIDEO&&!n.screenShare&&(i.setVideoEnabled(!n.pause),this.updatePipSource(i.id,!n.pause)),i.producers.push(q(V({},n),{producingTransportId:n.producingTransportId,kind:n.kind===$r.AUDIO?"audio":"video",producingPeerId:t,mimeType:n.mimeType}))}),this.roomNodeClient.handlePeerCapabilities(t,r),this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||this.roomNodeClient.shareWebcam(this.self.videoTrack),this.logger.info(`onParticipantMediaJoined: Emitting UPDATE_ACTIVE for peer ${t}`),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}updateParticipantsMapMinReplacement(t,e){const r=Array.from(t.keys()),i=new Map(t),n=new Set(e),s=[];r.forEach((o,c)=>{(!n.has(o)||!this.participants.joined.get(o))&&s.push(c)}),e.forEach(o=>{if(t.get(o))return;if(r.length<e.length){r.push(o);return}const c=s.shift();r[c]=o}),s.forEach(o=>{r.splice(o,1)}),Array.from(t.keys()).forEach(o=>{t.delete(o,!n.has(o))}),r.forEach(o=>{if(!this.participants.joined.get(o)){this.logger.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:o}});return}t.add(this.participants.joined.get(o),!i.get(o))}),t.emit("participantsUpdate")}updateParticipantsMap(t,e){Array.from(t.keys()).forEach(r=>{e.includes(r)||t.delete(r,!0)}),e.forEach(r=>{t.get(r)||t.add(this.participants.joined.get(r),!0)}),t.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(t=>{t.setIsPinned(!1),this.participants.pinned.delete(t.id)})}setupEventsGlobal(){this.roomSocketHandler.on(F.joinRoom,({peer:t})=>{if(!t.waitlisted){const e=this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN);e&&this.logger.info("Processing socket join",{peers:t.peerId}),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(t)),e&&this.logger.info("Processed socket join",{peers:t.peerId})}}),this.roomSocketHandler.on(F.leaveRoom,t=>{const{peerId:e}=t.peer;this.selectedPeers.delete(e,this.context),this.onParticipantLeave(e)}),this.context.getValue("peerSessionStore").on(P.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())}),this.context.getValue("peerSessionStore").on(P.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})}),this.context.getValue("peerSessionStore").on(P.CONSUMER_PAUSED,({id:t})=>{this.processConsumerPaused(t)}),this.context.getValue("peerSessionStore").on(P.CONSUMER_RESUMED,({id:t})=>{this.processConsumerResumed(t)}),this.context.getValue("peerSessionStore").on(P.NEW_CONSUMER,({id:t})=>{this.processNewConsumer(t)}),this.context.getValue("peerSessionStore").on(P.CONSUMER_CLOSED,({id:t})=>{this.processConsumerClosed(t)}),this.context.getValue("peerSessionStore").on(P.ROOM_MESSAGE,t=>u(this,[t],function*({payload:e,type:r,timestamp:i}){this.participants.emit("broadcastedMessage",{type:r,payload:e,timestamp:i})})),this.context.getValue("peerSessionStore").on(P.MESSAGE,t=>u(this,[t],function*({payload:e,type:r,timestamp:i}){r!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:r,payload:e,timestamp:i})})),this.context.getValue("peerSessionStore").on(P.LOW_CONSUMER_SCORE,({peerId:t,score:e,kind:r})=>{const i=this.participants.joined.get(t);i&&(i.emit("poorConnection",{score:e,kind:r}),this.participants.emit("poorConnection",{participantId:t,score:e,kind:r}))}),this.context.getValue("peerSessionStore").on(P.CONSUMER_SCORE_UPDATE,({score:t,kind:e,appData:r,peerId:i,scoreStats:n})=>{var s;const o=e==="video"&&((s=r==null?void 0:r.screenShare)!=null?s:!1),c=this.participants.joined.get(i);c&&(c.emit("mediaScoreUpdate",{kind:e,isScreenshare:o,score:t,participantId:i,scoreStats:n}),this.participants.emit("mediaScoreUpdate",{kind:e,isScreenshare:o,score:t,participantId:i,scoreStats:n}))}),this.context.getValue("peerSessionStore").onAsync(P.KICK_PEER,t=>u(this,[t],function*({peerId:e}){const r=this.participants.joined.get(e);this.roomNodeClient.kick(e),yield this.roomSocketHandler.kick(e),r?r.emit("kicked"):this.participants.joined.emit("kicked",{id:e})})),this.context.getValue("peerSessionStore").on(P.UPDATE_ACTIVE,(...t)=>u(this,[...t],function*({viewMode:e,page:r,createAllConsumers:i}={viewMode:"ACTIVE_GRID",page:0,createAllConsumers:!1}){this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${a(this,gr).mode}, page: ${r}, CreateAllConsumers: ${i}`),i&&(this.logger.info(`UPDATE_ACTIVE viewMode: ${e}, Page: ${r}, Removing existing subscriptions.`),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear()),this.updateMediaSubscribedMaps(e,{page:r}),this.scheduleSyncConsumers({source:"UPDATE_ACTIVE"})}))}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)})}onParticipantSocketJoined(t){return u(this,null,function*(){var e,r,i;this.logger.info(`onParticipantSocketJoined: peer ${t.id} has joined socket edge. Processing.`),this.self.id!==t.id&&!((e=t.flags)!=null&&e.recorder)&&!((r=t.flags)!=null&&r.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"&&this.context.getValue("peerSessionStore").emit(P.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!0})),this.context.getValue("peerSessionStore").emit(P.PEER_JOINED_INTERNAL,t)})}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"&&this.context.getValue("peerSessionStore").emit(P.UPDATE_STAGE_REQUESTS,{request:{displayName:e.name,userId:e.userId,peerId:e.id},add:!1});const{currentPage:r}=this.participants,i=this.maxPreferredStreams*(r-1),n=this.participants.videoSubscribed.get(t);this.participants.viewMode==="MANUAL"?this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:r}):i===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=i?r===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(r-1):n&&this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:r})})}processMedia(t){var e;const r=this.roomNodeClient.getConsumers(),{peerId:i,kind:n,appData:s,track:o,producerId:c,rtpReceiver:d,paused:l,localId:h}=(e=r.get(t))!=null?e:{};if(!i)return this.logger.warn("processMedia::Peer ID is undefined",{consumer:{id:t,kind:n,peerId:i,appData:{supportsRemoteControl:!!(s!=null&&s.supportsRemoteControl),screenShare:!!(s!=null&&s.screenShare)},remotelyPaused:l,producerId:c}}),{};const p=s;return n==="video"&&p.screenShare!==!0&&this.videoPeerConsumerMap.set(i,t),this.logger.info("ParticipantController::processMedia",{consumer:{id:t,peerId:i,kind:n,appData:p,remotelyPaused:l,producerId:c}}),this.consumerPeerMap.set(t,{type:n,peerId:i,appData:p,remotelyPaused:l,producerId:c}),{peerId:i,kind:n,appData:p,remotelyPaused:l,track:o,producerId:c,rtpReceiver:d,localId:h}}processConsumerClosed(t){const{peerId:e,type:r,appData:i,remotelyPaused:n,producerId:s}=this.consumerPeerMap.get(t)||{},o=this.participants.joined.get(e);if(this.logger.info("ParticipantController::processConsumerClosed",{consumer:{id:t,peerId:e,appData:i,kind:r,remotelyPaused:n,producerId:s}}),this.consumerPeerMap.delete(t),r==="video"&&i.screenShare!==!0&&this.videoPeerConsumerMap.delete(e),!o)return;const c=o.producers.find(l=>l.producerId===s);c&&(c.consumer={id:t,peerId:e,kind:void 0,appData:i,paused:n,producerId:s,rtpReceiver:void 0,localId:void 0});const d=[];i&&i.screenShare?(o.setScreenShareEnabled(!1),this.context.getValue("callstats").consumerSharedMediaState(t,{screen:!1}),o.screenShareTracks.video&&d.push(o.screenShareTracks.video.id),o.screenShareTracks.audio&&d.push(o.screenShareTracks.audio.id),o.screenShareTracks={audio:void 0,video:void 0}):r==="audio"?(o.setAudioEnabled(!1),o.audioTrack&&d.push(o.audioTrack.id),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:!1}),o.audioTrack=void 0):r==="video"&&(o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),o.videoTrack&&d.push(o.videoTrack.id),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!1}),o.videoTrack=void 0),i.e2ee&&d.forEach(l=>{this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:l})})}processConsumerResumed(t){var e;const r=this.processMedia(t),{peerId:i,kind:n,appData:s,track:o,remotelyPaused:c,producerId:d,rtpReceiver:l,localId:h}=r;if(!i)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:t,peerId:i,kind:n,appData:s,remotelyPaused:c,producerId:d}});const p=this.participants.joined.get(i);if(!p)return;const v=p.producers.find(S=>S.producerId===d);if(v&&(v.consumer={id:t,peerId:i,kind:n,appData:s,paused:c,producerId:d,rtpReceiver:l,localId:h}),s.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:i,rtpReceiver:l,track:o}),s.screenShare){n==="video"?p.screenShareTracks.video=o:n==="audio"&&(p.screenShareTracks.audio=o),p.setScreenShareEnabled(!0),(e=this.context)==null||e.getValue("callstats").consumerSharedMediaState(t,{screen:!0});return}n==="video"?(p.videoTrack=o,p.setVideoEnabled(!0),this.updatePipSource(p.id,!0),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!0})):n==="audio"&&(p.audioTrack=o,p.setAudioEnabled(p.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:p.audioEnabled}))}processConsumerPaused(t){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${t}`);const{peerId:e,kind:r,track:i,appData:n,remotelyPaused:s,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(t);if(!e)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:t,peerId:e,kind:r,appData:n,remotelyPaused:s,producerId:o}});const l=this.participants.joined.get(e);if(!l)return;const h=l.producers.find(p=>p.producerId===o);h&&(h.consumer={id:t,peerId:e,kind:r,appData:n,paused:s,producerId:o,rtpReceiver:c,localId:d}),i&&n.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:i.id}),r==="video"?(l.videoTrack=i,l.setVideoEnabled(!1),this.updatePipSource(l.id,!1),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!1})):r==="audio"&&(l.audioTrack=i,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:l.audioEnabled}))}processNewConsumer(t){const{peerId:e,kind:r,remotelyPaused:i,track:n,appData:s,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(t);if(!e)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:t,peerId:e,kind:r,remotelyPaused:i,appData:s,producerId:o}});const l=this.participants.joined.get(e);if(!l)return;const h=l.producers.find(p=>p.producerId===o);if(h&&(h.consumer={id:t,peerId:e,kind:r,appData:s,paused:i,producerId:o,rtpReceiver:c,localId:d}),s.screenShare){r==="video"?l.screenShareTracks.video=n:r==="audio"&&(l.screenShareTracks.audio=n),(!i||this.self.permissions.isRecorder||this.context.getValue("flagsmith").hasFeature(Z.SCREEENSHARE_ERR_HACK))&&l.setScreenShareEnabled(!0),s.supportsRemoteControl&&(l.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:e,screenShare:!0,consumerId:t,consumerPeerId:this.self.id}),this.logger.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:t,peerId:e,kind:r,remotelyPaused:i,appData:s,producerId:o}});return}r==="video"?(l.videoTrack=n,i||(l.setVideoEnabled(!0),this.updatePipSource(l.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!i})):r==="audio"&&(l.audioTrack=n,i||l.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:!i})),!i&&s.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:n})}static formatSocketPeerMessage(t){var e,r,i,n,s,o;if(!t)return;const c=kp(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:(r=t.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(i=t.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(n=t.flags)==null?void 0:n.hiddenParticipant,recorder:((s=t.flags)==null?void 0:s.recorderType)!==void 0&&((o=t.flags)==null?void 0:o.recorderType)!=="NONE"}}}onSelectedPeers(t,e){return u(this,null,function*(){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(t,e)})}updateActiveParticipantsWithPriorities(t,e=!1){if(this.participants.viewMode==="MANUAL")return;if(!this.mediaJoined){this.logger.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}t.forEach(i=>{this.selectedPeers.add(i.peerId,i.priority,this.context)});const r=this.selectedPeers.activeSpeakerPeers.at(0);r!==void 0&&r!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=r,this.participants.emit("activeSpeaker",{peerId:r,volume:1})),e&&this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},gr=new WeakMap,Vr=new WeakMap,qa=new WeakMap,Ag);let Ei=Cy;$n([k.trace("ParticipantController.setupEvents")],Ei.prototype,"setupEvents",1);$n([k.trace("ParticipantController.setupEvents")],Ei.prototype,"setupEventsGlobal",1);$n([k.trace("ParticipantController.processMedia")],Ei.prototype,"processMedia",1);$n([k.trace("ParticipantController.processConsumerClosed")],Ei.prototype,"processConsumerClosed",1);$n([k.trace("ParticipantController.processConsumerResumed")],Ei.prototype,"processConsumerResumed",1);$n([k.trace("ParticipantController.processConsumerPaused")],Ei.prototype,"processConsumerPaused",1);$n([k.trace("ParticipantController.processNewConsumer")],Ei.prototype,"processNewConsumer",1);const ye=Pr(pp().permissions);var H,po,Fs,ch,xt,Kt;const mo=class extends Zt{constructor(t,e,r,i=!1){const n=t.getValue("logger");if(super(n),g(this,xt),g(this,H,void 0),g(this,po,void 0),g(this,Fs,void 0),g(this,ch,s=>{var o,c,d;const l=s,{chat:h,connectedMeetings:p,plugins:v,polls:S,media:T}=l,C=pl(l,["chat","connectedMeetings","plugins","polls","media"]);if(h&&(h.private&&Mi(a(this,H).chat.private,h.private),h.public&&Mi(a(this,H).chat.public,h.public),this.emit("chatUpdate")),p&&Mi(a(this,H).connectedMeetings,p),T){const b=j=>{switch(j){case Ji.NONE:return G.Allowed;case Ji.ALLOWED:return G.Allowed;case Ji.NOT_ALLOWED:return G.NotAllowed;case Ji.CAN_REQUEST:return G.CanRequest;default:return}},R={audio:void 0,video:void 0,screenshare:void 0};(o=T.audio)!=null&&o.canProduce&&(R.audio={canProduce:b(T.audio.canProduce)}),(c=T.video)!=null&&c.canProduce&&(R.video={canProduce:b(T.video.canProduce)}),(d=T.screenshare)!=null&&d.canProduce&&(R.screenshare={canProduce:b(T.screenshare.canProduce)}),Mi(a(this,H).media,R)}v&&(Mi(a(this,H).plugins,v),this.emit("pluginsUpdate")),S&&(Mi(a(this,H).polls,S),this.emit("pollsUpdate")),Object.keys(C).length!==0&&Mi(a(this,H),C),this.emit("permissionsUpdate",s)}),!e)throw this.logger.error("DytePermissionsPreset::load_preset_permissions_failed"),new I("Could not load preset permissions.","0904");f(this,Fs,t),f(this,po,r),f(this,H,e),i&&this.setupEvents()}setupEvents(){a(this,Fs).getValue("peerSessionStore").on(P.UPDATE_PERMISSIONS,a(this,ch))}static fromResponse(t,e,r){return new mo(r,t,e,!0)}static default(t,e){return new mo(t,ye,e)}static init(t,e,r){let i;return r?i=new mo(t,r,e,!0):i=new mo(t,ye,e),i}get mediaRoomType(){const{sfu:t}=a(this,Fs).getValue("roomNodeOptions");return t===Oe.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=a(this,H))==null?void 0:t.stageEnabled)||a(this,po)===Ft.Webinar||a(this,po)===Ft.Livestream}get acceptStageRequests(){var t,e;return this.stageEnabled?((t=a(this,H))==null?void 0:t.acceptStageRequests)||((e=a(this,H))==null?void 0:e.canAcceptProductionRequests):!1}get stageAccess(){var t,e,r;return((t=a(this,H))==null?void 0:t.stageAccess)===G.NotAllowed?G.NotAllowed:((e=a(this,H))==null?void 0:e.stageAccess)===G.CanRequest?G.CanRequest:((r=a(this,H))==null?void 0:r.stageAccess)===G.Allowed||a(this,H).media.audio.canProduce===G.Allowed||a(this,H).media.video.canProduce===G.Allowed||a(this,H).media.screenshare.canProduce===G.Allowed?G.Allowed:a(this,H).media.audio.canProduce===G.CanRequest||a(this,H).media.video.canProduce===G.CanRequest||a(this,H).media.screenshare.canProduce===G.CanRequest?G.CanRequest:G.NotAllowed}get acceptWaitingRequests(){var t,e;return(e=(t=a(this,H))==null?void 0:t.acceptWaitingRequests)!=null?e:ye.acceptWaitingRequests}get requestProduceVideo(){var t,e,r;return((r=(e=(t=a(this,H))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.canProduce)===G.CanRequest}get requestProduceAudio(){var t,e,r;return((r=(e=(t=a(this,H))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.canProduce)===G.CanRequest}get requestProduceScreenshare(){var t,e,r;return((r=(e=(t=a(this,H))==null?void 0:t.media)==null?void 0:e.screenshare)==null?void 0:r.canProduce)===G.CanRequest}get canAllowParticipantAudio(){var t,e;return(e=(t=a(this,H))==null?void 0:t.disableParticipantAudio)!=null?e:ye.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=a(this,H))==null?void 0:t.canAcceptProductionRequests)!=null?e:ye.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=a(this,H))==null?void 0:t.disableParticipantVideo)!=null?e:ye.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var t,e;return(e=(t=a(this,H))==null?void 0:t.kickParticipant)!=null?e:ye.kickParticipant}get pinParticipant(){var t,e;return(e=(t=a(this,H))==null?void 0:t.pinParticipant)!=null?e:ye.pinParticipant}get canRecord(){var t,e;return(e=(t=a(this,H))==null?void 0:t.canRecord)!=null?e:ye.canRecord}get waitingRoomType(){var t,e;return(e=(t=a(this,H))==null?void 0:t.waitingRoomType)!=null?e:ye.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=a(this,H))==null?void 0:t.waitingRoomType)!=null?e:ye.waitingRoomType}get plugins(){var t,e;return(e=(t=a(this,H))==null?void 0:t.plugins)!=null?e:ye.plugins}get polls(){var t,e;return(e=(t=a(this,H))==null?void 0:t.polls)!=null?e:ye.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return a(this,H).media.audio.canProduce===G.CanRequest||a(this,H).media.video.canProduce===G.CanRequest||a(this,H).media.screenshare.canProduce===G.CanRequest}get canProduceVideo(){var t;const e=(t=a(this,H).media.video.canProduce)!=null?t:ye.media.video.canProduce;return this.stageEnabled&&(a(this,xt,Kt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,xt,Kt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,xt,Kt)==="OFF_STAGE"||a(this,xt,Kt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var t;const e=(t=a(this,H).media.screenshare.canProduce)!=null?t:ye.media.screenshare.canProduce;return this.stageEnabled&&(a(this,xt,Kt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,xt,Kt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,xt,Kt)==="OFF_STAGE"||a(this,xt,Kt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var t;const e=(t=a(this,H).media.audio.canProduce)!=null?t:ye.media.audio.canProduce;return this.stageEnabled&&(a(this,xt,Kt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,xt,Kt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,xt,Kt)==="OFF_STAGE"||a(this,xt,Kt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get chatPublic(){var t,e,r;return(r=(e=(t=a(this,H))==null?void 0:t.chat)==null?void 0:e.public)!=null?r:ye.chat.public}get chatPrivate(){var t,e,r;return(r=(e=(t=a(this,H))==null?void 0:t.chat)==null?void 0:e.private)!=null?r:ye.chat.private}get chatChannel(){var t,e,r;return(r=(e=(t=a(this,H))==null?void 0:t.chat)==null?void 0:e.channel)!=null?r:ye.chat.channel}get chatMessage(){var t,e,r;return(r=(e=(t=a(this,H))==null?void 0:t.chat)==null?void 0:e.message)!=null?r:ye.chat.message}get connectedMeetings(){var t,e;return(e=(t=a(this,H))==null?void 0:t.connectedMeetings)!=null?e:ye==null?void 0:ye.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=a(this,H))==null?void 0:t.hiddenParticipant)!=null?e:ye.hiddenParticipant}get showParticipantList(){var t;return(t=a(this,H).showParticipantList)!=null?t:ye.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=a(this,H))==null?void 0:t.canChangeParticipantPermissions)!=null?e:ye.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=a(this,H))==null?void 0:t.canChangeParticipantPermissions)!=null?e:ye.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return a(this,H).media.audio.canProduce===G.Allowed||a(this,H).media.video.canProduce===G.Allowed||a(this,H).media.screenshare.canProduce===G.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var t;return(t=a(this,H).canEditDisplayName)!=null?t:!1}get maxScreenShareCount(){return 1}get isRecorder(){return a(this,H).isRecorder}get canSpotlight(){return a(this,H).canSpotlight}get canLivestream(){return a(this,H).canLivestream}get transcriptionEnabled(){return a(this,H).transcriptionEnabled}};let tN=mo;H=new WeakMap,po=new WeakMap,Fs=new WeakMap,ch=new WeakMap,xt=new WeakSet,Kt=function(){return a(this,Fs).getValue("stageStatus")};var Fr;class Py extends Zt{constructor(){super(...arguments),m(this,"localMediaHandler"),g(this,Fr,void 0)}updatePermission(){return u(this,null,function*(){var e,r;const i=(l,h)=>{this.mediaPermissions[l]=h;const p={message:this.mediaPermissions[l],kind:l};h==="DENIED"?a(this,Fr).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_ERROR,p):a(this,Fr).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,p)};if(Ie.getName()==="firefox")return;const n="microphone",s="camera",o=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:n}),c=yield(r=navigator==null?void 0:navigator.permissions)==null?void 0:r.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()};o&&(o.onchange=()=>d("audio",o.state)),c&&(c.onchange=()=>d("video",c.state))})}populateMediaPermissionsInCallstats(e){return u(this,arguments,function*({message:r,kind:i}){var n,s,o,c;switch(i){case"audio":{(n=a(this,Fr))==null||n.getValue("callstats").mediaPermission("AUDIO",r),(s=a(this,Fr))==null||s.getValue("callstats").mediaPermission("SPEAKER",r);break}case"video":{(o=a(this,Fr))==null||o.getValue("callstats").mediaPermission("VIDEO",r);break}case"screenshare":{(c=a(this,Fr))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",r);break}}})}get peerId(){var e;return(e=a(this,Fr))==null?void 0:e.getValue("peerId")}init(){return u(this,arguments,function*(e={},r=!1,i=null){var n,s,o,c,d,l,h;if(Ie.init(),!this.localMediaHandler)try{let p=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)p=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:v}=navigator;this.localMediaHandler=yield v.init(e)}else this.localMediaHandler=new Wt(i,e.constraints,(s=i==null?void 0:i.getValue("defaults"))==null?void 0:s.isNonPreferredDevice,(o=i==null?void 0:i.getValue("defaults"))==null?void 0:o.autoSwitchAudioDevice);if(i==null||i.getValue("peerSessionStore").on(P.MEDIA_PERMISSION_UPDATE,v=>u(this,null,function*(){if(this.populateMediaPermissionsInCallstats({message:v.message,kind:v.kind}),v.message==="NOT_REQUESTED")switch(v==null?void 0:v.kind){case"audio":this.rawAudioTrack&&(this.logger.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(this.logger.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",v)})),i==null||i.getValue("peerSessionStore").on(P.MEDIA_PERMISSION_ERROR,v=>u(this,null,function*(){const{kind:S,message:T,constraints:C}=v;this.populateMediaPermissionsInCallstats({message:T,kind:S}),S==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):S==="video"&&(this.logger.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),this.logger.error("SelfController::mediaPermissionError",{error:{message:T},constraints:C,mediaPermissionsErrors:{kind:S,message:T}}),this.emit("mediaPermissionError",v),this.emit("mediaPermissionUpdate",{message:T,kind:S})})),p){this.logger.info(`Setting up DyteSelfMedia streams using media handler. audio:${(c=e==null?void 0:e.audio)!=null?c:!0} video:${(d=e==null?void 0:e.video)!=null?d:!0}`);const v=this.localMediaHandler.setupStreams({video:(l=e==null?void 0:e.video)!=null?l:!0,audio:(h=e==null?void 0:e.audio)!=null?h:!0});r||(yield v)}}catch(p){this.logger.error("DyteSelf::init::Failed To Setup Streams",{error:{name:p.name,message:p.message}})}})}set context(e){f(this,Fr,e),this.localMediaHandler.context=e}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,r){let i;return r==="audio"?i="audioinput":r==="video"?i="videoinput":r==="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})})}}Fr=new WeakMap;var rN=Object.defineProperty,iN=Object.getOwnPropertyDescriptor,Mt=(t,e,r,i)=>{for(var n=i>1?void 0:i?iN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&rN(e,r,n),n},$a,At,Ja,Ye,wi,ln,Qe,et,Ka,Ac,$e,Xe,za,Ya,Dc,gu,Dg;let at=(Dg=class extends Py{constructor(t,e,r,i,n){var s;const o=t.getValue("logger");super(o),g(this,wi),g(this,Qe),g(this,Ka),g(this,$e),g(this,Dc),m(this,"name"),m(this,"picture"),m(this,"customParticipantId"),m(this,"waitlistStatus"),g(this,$a,void 0),g(this,At,void 0),g(this,Ja,void 0),m(this,"role"),m(this,"userId"),m(this,"organizationId"),m(this,"supportsRemoteControl",!1),m(this,"device"),g(this,Ye,void 0),m(this,"hidden",!1),m(this,"presetName"),m(this,"roomState","init"),g(this,za,new Set),g(this,Ya,new Set),f(this,Ye,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",f(this,At,r),f(this,$a,i),this.hidden=!1,f(this,Ja,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Ie.isElectron(),this.device=Ie.getDeviceInfo(),this.presetName=n,i.viewType!==Ft.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),U(this,Dc,gu).call(this)}get telemetry(){return a(this,Ye).getValue("telemetry")}get stageStatus(){return a(this,Ye).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,Qe,et).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,Ye).getValue("peerId")}static __init__(t,e,r,i,n,s=!1){return u(this,null,function*(){var o,c,d,l,h,p;let v=(c=(o=t.getValue("defaults"))==null?void 0:o.audio)!=null?c:!0,S=(l=(d=t.getValue("defaults"))==null?void 0:d.video)!=null?l:!0;r.canProduceAudio!=="ALLOWED"&&(v=!1),r.canProduceVideo!=="ALLOWED"&&(S=!1);const T=new at(t,e,r,i,n);if(i.viewType===Ft.Chat)return T;const C=u1(i.mediaConstraints);Mi(C,(h=t.getValue("defaults"))==null?void 0:h.mediaConfiguration);const b=(p=t.getValue("defaults"))==null?void 0:p.mediaHandler;return b&&(b.context=t),yield T.init({audio:v,video:S,constraints:C},s,t),T.setupEvents(),T})}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"),a(this,At).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",U(this,Dc,gu));const t=a(this,Ka,Ac);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>u(this,null,function*(){if(this.logger.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",V({},An(this))),a(this,$e,Xe)&&this.audioEnabled)try{yield a(this,Qe,et).shareMic(this.audioTrack)}catch(e){this.logger.error("DyteSelf::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",()=>u(this,null,function*(){if(this.logger.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",V({},An(this))),a(this,$e,Xe)&&this.rawVideoTrack===void 0)this.logger.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,$e,Xe))try{const e=yield a(this,Qe,et).shareWebcam(this.videoTrack);e&&e.id!==this.videoTrack.id&&a(this,Ye).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&(yield a(this,Qe,et).shareWebcam(this.videoTrack))}catch(e){this.logger.error("DyteSelf::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&(yield this.localMediaHandler.disableVideo())}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})),this.localMediaHandler.on("DEVICE_CHANGE",e=>u(this,[e],function*({device:r}){var i;this.emit("deviceUpdate",{device:r}),r.kind==="audiooutput"&&typeof HTMLAudioElement.prototype.setSinkId=="function"&&((i=a(this,Ka,Ac))==null||i.setSpeakerDevice(r.deviceId))})),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",()=>u(this,null,function*(){if(!a(this,$e,Xe)){this.logger.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield a(this,Qe,et).shareScreen(this.screenShareTracks)}catch(e){this.logger.error("DyteSelf::setupEvents::Error while sharing screen",{error:e}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}this.logger.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",V({},An(this))),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})),this.localMediaHandler.on("SCREENSHARE_ENDED",()=>u(this,null,function*(){this.logger.log("Disabling screenshare due to SCREENSHARE_ENDED"),yield this.disableScreenShare(),this.logger.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",V({},An(this)))})),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=a(this,Ye))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",()=>u(this,null,function*(){var e;a(this,$e,Xe)&&(yield a(this,Qe,et).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,Ye))==null||e.getValue("callstats").videoOff()})),a(this,At).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,At).canProduceAudio!==G.Allowed&&(this.disableAudio(),this.logger.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(i=e==null?void 0:e.media)!=null&&i.video&&a(this,At).canProduceVideo!==G.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=e==null?void 0:e.media)!=null&&n.screenshare&&a(this,At).canProduceScreenshare!==G.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,At)}get config(){return a(this,$a)}get roomJoined(){var t;return a(this,$a).viewType===Ft.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,Ye).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,$e,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(t){return u(this,null,function*(){var e;if(this.permissions.canProduceAudio!==G.NotAllowed&&!(a(this,At).canProduceAudio===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,Ye))==null||e.getValue("callstats").audioOn(),yield this.localMediaHandler.enableAudio(t),a(this,$e,Xe)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield a(this,Qe,et).shareMic(this.audioTrack)}catch(r){this.logger.error("DyteSelf::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;a(this,Qe,et).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}})}enableVideo(t){return u(this,null,function*(){var e;if(a(this,At).canProduceVideo!==G.NotAllowed&&!(a(this,At).canProduceVideo===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,Ye))==null||e.getValue("callstats").videoOn(),yield this.localMediaHandler.enableVideo(t),a(this,$e,Xe)&&this.stageStatus==="ON_STAGE")try{yield a(this,Qe,et).shareWebcam(this.videoTrack)}catch(r){this.logger.error("DyteSelf::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("DyteSelf.enableVideo",V({},An(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(!a(this,$e,Xe))throw new I("Can`t enable screenshare without joining room","1105");if(a(this,At).canProduceScreenshare!==G.NotAllowed&&!(a(this,At).canProduceScreenshare===G.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 a(this,Qe,et).shareScreen(this.screenShareTracks)}catch(t){this.logger.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*(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,$e,Xe)&&a(this,Qe,et).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,Ye))==null||t.getValue("callstats").audioOff())})}disableVideo(){return u(this,null,function*(){var t;this.videoEnabled&&(yield this.localMediaHandler.disableVideo(),a(this,$e,Xe)&&(yield a(this,Qe,et).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,Ye))==null||t.getValue("callstats").videoOff())})}disableScreenShare(){return u(this,null,function*(){this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare(),a(this,$e,Xe)&&(yield a(this,Qe,et).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var r;f(this,Ja,t);const i=t?"pinned":"unpinned";(r=a(this,wi,ln))==null||r.updateSource(this.id,{pinned:t}),e&&this.emit(i,this)}get isPinned(){return a(this,Ja)}pin(){return u(this,null,function*(){if(!a(this,$e,Xe))throw new I("Can`t pin participants without joining room","1105");return this.show(),a(this,Qe,et).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!a(this,$e,Xe))throw new I("Can`t unpin participants without joining room","1105");return a(this,Qe,et).pinPeer(null)})}hide(){return u(this,null,function*(){if(!a(this,$e,Xe))throw new I("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})})}show(){if(!a(this,$e,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,r,i;if(!t)throw new I("No device selected","1104");const n=this.getCurrentDevices();if(t.deviceId&&(((e=n==null?void 0:n.audio)==null?void 0:e.deviceId)===t.deviceId||((r=n==null?void 0:n.video)==null?void 0:r.deviceId)===t.deviceId||((i=n==null?void 0:n.speaker)==null?void 0:i.deviceId)===t.deviceId)&&(this.logger.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),a(this,Ye).getValue("flagsmith").hasFeature(Z.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{a(this,$e,Xe)&&(yield a(this,Qe,et).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{a(this,$e,Xe)&&(yield a(this,Qe,et).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}})}cleanUpTracks(){var t,e,r,i;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(i=this.rawVideoTrack)==null||i.stop()}playAudio(){var t;return(t=a(this,Ka,Ac))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,za).add(t):a(this,Ya).add(t),this.updateVideo(t),e||(i=a(this,wi,ln))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1))}deregisterVideoElement(t,e=!1){if(!t){a(this,wi,ln).removeSource(this.id);return}t.srcObject=void 0,e?a(this,za).delete(t):(a(this,Ya).delete(t),a(this,wi,ln).removeSource(this.id))}updateVideo(t,e=!1){var r,i,n;if(this.videoEnabled){if(this.videoTrack==null)return;const s=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((s==null?void 0:s.id)===this.videoTrack.id)return;const o=new MediaStream;o.addTrack(this.videoTrack),t.srcObject=o,e||(i=a(this,wi,ln))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,wi,ln))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},$a=new WeakMap,At=new WeakMap,Ja=new WeakMap,Ye=new WeakMap,wi=new WeakSet,ln=function(){return a(this,Ye).getValue("pip")},Qe=new WeakSet,et=function(){return a(this,Ye).getValue("roomNodeClient")},Ka=new WeakSet,Ac=function(){return a(this,Ye).getValue("audioPlayback")},$e=new WeakSet,Xe=function(){var t;return((t=a(this,Ye).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},za=new WeakMap,Ya=new WeakMap,Dc=new WeakSet,gu=function(){Array.from(a(this,Ya)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,za)).forEach(t=>this.updateVideo(t,!0))},Dg);Mt([k.trace("DyteSelf.cleanupEvents")],at.prototype,"cleanupEvents",1);Mt([k.trace("DyteSelf.setupEvents")],at.prototype,"setupEvents",1);Mt([k.trace("DyteSelf.setupTracks")],at.prototype,"setupTracks",1);Mt([k.trace("DyteSelf.destructMediaHandler")],at.prototype,"destructMediaHandler",1);Mt([k.trace("DyteSelf.removeDocumentEventListeners")],at.prototype,"removeDocumentEventListeners",1);Mt([Si.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),k.trace("DyteSelf.enableAudio")],at.prototype,"enableAudio",1);Mt([Si.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),k.trace("DyteSelf.enableVideo")],at.prototype,"enableVideo",1);Mt([k.trace("DyteSelf.updateVideoConstraints")],at.prototype,"updateVideoConstraints",1);Mt([k.trace("DyteSelf.enableScreenShare"),Si.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],at.prototype,"enableScreenShare",1);Mt([k.trace("DyteSelf.updateScreenshareConstraints")],at.prototype,"updateScreenshareConstraints",1);Mt([Si.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),k.trace("DyteSelf.disableAudio")],at.prototype,"disableAudio",1);Mt([Si.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),k.trace("DyteSelf.disableVideo")],at.prototype,"disableVideo",1);Mt([Si.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),k.trace("DyteSelf.disableScreenShare")],at.prototype,"disableScreenShare",1);Mt([k.trace("DyteSelf.setDevice")],at.prototype,"setDevice",1);at=Mt([ft("1100")],at);class Cp extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Cp)}}class Pp extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Pp)}}var cd;class dh{constructor(e,r=!1){m(this,"pendingTasks",new Map),m(this,"nextTaskId",0),m(this,"stopping",!1),g(this,cd,void 0),this.log=r,f(this,cd,{info:r&&e?e.info:()=>{}})}get size(){return this.pendingTasks.size}push(e,r,i){return u(this,null,function*(){if(r=r!=null?r:e.name,typeof e!="function")throw new TypeError("given task is not a function");if(r)try{Object.defineProperty(e,"name",{value:r})}catch{}return new Promise((n,s)=>{const o={id:this.nextTaskId++,task:e,metadata:i,name:r,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:c=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),n(c);const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)},reject:c=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),s(c),!this.stopping)){const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})})}stop(){this.stopping=!0;for(const e of this.pendingTasks.values())e.reject(new Cp);this.stopping=!1}remove(e){const r=Array.from(this.pendingTasks.values())[e];r&&r.reject(new Pp)}get(e){return Array.from(this.pendingTasks.values())[e]}dump(){const e=Date.now();let r=0;return Array.from(this.pendingTasks.values()).map(i=>({idx:r++,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(e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const r=this.pendingTasks.size,i=yield e.task(),n=Date.now();a(this,cd).info(`AwaitQueue.push(${e.name})_timings`,{awaitQueueTask:{id:e.id,metadata:e.metadata,queueSizeAtStart:r,execTime:(n-e.executedAt)/1e3,taskStartTime:(e.executedAt-e.enqueuedAt)/1e3}}),e.resolve(i)}catch(r){e.reject(r)}})}}cd=new WeakMap;function nN(t,e){const r=new Error(e);return r.name=t,r}class Yo extends I{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Yo):this.stack=new Error(e).stack}}class Ut extends I{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ut):this.stack=new Error(e).stack}}class Dn extends I{constructor(e){super(e),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ut):this.stack=new Error(e).stack}}const Og=t=>new Promise(e=>setTimeout(e,t));function Ry(t,e){return u(this,null,function*(){return new Promise((r,i)=>u(this,null,function*(){const{strategy:n,maxRetryCount:s,delayTime:o}=V({strategy:"linear",maxRetryCount:3,delayTime:10},e);let c=0,d,l=!1;const h=p=>{l=!0,i(p)};for(;c<s;){try{const p=yield t(c,h);return r(p)}catch(p){if(d=p,l)break;if(c<s)n==="linear"?yield Og(o*(c+1)):n==="exponential"&&(yield Og(o*(c+Math.max(0,c-1))));else break}c+=1}return i(d)}))})}function sN(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 Oc(t){return{codecs:sN(t.codecs),headerExtensions:aN(t.headerExtensions?t.headerExtensions:[])}}function oN(t){const e=RTCRtpReceiver.getCapabilities("audio"),r=RTCRtpReceiver.getCapabilities("video"),i=RTCRtpSender.getCapabilities("audio"),n=RTCRtpSender.getCapabilities("video");t&&(r.codecs=r.codecs.filter(({mimeType:o})=>t===o),n.codecs=n.codecs.filter(({mimeType:o})=>t===o));const s={audio:Oc(e),video:Oc(r)};return{sender:{audio:Oc(i),video:Oc(n)},receiver:s}}var ct;class cN{constructor(e,r){g(this,ct,void 0),m(this,"events"),m(this,"sfuType"),f(this,ct,e),this.sfuType=r,this.events=r===Oe.CF?Ir:dr}joinRoom(e,r,i,n=!1,s=null){return u(this,null,function*(){const o={roomUuid:e,displayName:r,prejoined:n,capabilities:i};return s&&(o.location=s),(yield a(this,ct).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:EC.toBinary(o),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield a(this,ct).sendMessagePromise(this.events.createWebRTCTransport,KI.toBinary(e))).payload,{transportId:i,description:n,producerIds:s}=Kv.fromBinary(r),o={sdp:n==null?void 0:n.sdp,type:n.type};return{transportId:i,answer:o,producerIds:s}})}produce(e){return u(this,null,function*(){var r,i;const n=(yield a(this,ct).sendMessagePromise(this.events.produce,VC.toBinary(e))).payload,s=vP.fromBinary(n);return{answer:{sdp:(r=s==null?void 0:s.description)==null?void 0:r.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===Oe.HIVE)throw new Error("Hive does not support socket consumer operations");const r=(yield a(this,ct).sendMessagePromise(this.events.consume,RC.toBinary(e))).payload,{consumerIdsMap:{map:i},description:n}=gP.fromBinary(r);return{consumerStateMap:i,sessionDescription:n}})}closeProducer(e){return u(this,null,function*(){const r=(yield a(this,ct).sendMessagePromise(this.events.closeProducer,jC.toBinary(e))).payload,{description:i}=wP.fromBinary(r);return i})}closeConsumer(e){return u(this,null,function*(){if(this.sfuType===Oe.HIVE)throw new Error("Hive does not support socket consumer operations");return(yield a(this,ct).sendMessagePromise(this.events.closeConsumer,GC.toBinary(e))).payload})}updateConsumersSimulcastConfig(e){return u(this,null,function*(){if(this.sfuType===Oe.HIVE)throw new Error("Method not implemented");return(yield a(this,ct).sendMessagePromise(this.events.updateConsumersSimulcastConfig,OC.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const i={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},n=(yield a(this,ct).sendMessagePromise(this.events.hostControlPeer,YC.toBinary(i))).payload;if(!n)return!1;const{status:s}=AP.fromBinary(n);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const r={audio:e==="audio",screenShare:!1,video:e==="video"},i=(yield a(this,ct).sendMessagePromise(this.events.hostControlAllPeers,XC.toBinary(r))).payload;if(!i)return!1;const{status:n}=OP.fromBinary(i);return n==="success"})}kickAll(){return u(this,null,function*(){const e={propagateKickAcrossRooms:!1};a(this,ct).sendMessagePromise(F.kickAll,Xv.toBinary(e))})}kickPeer(e){return u(this,null,function*(){a(this,ct).sendMessagePromise(F.kick,iy.toBinary(e))})}changeDisplayName(e){return u(this,null,function*(){const r=(yield a(this,ct).sendMessagePromise(this.events.changeDisplayName,KC.toBinary(e))).payload;if(!r)return!1;const{status:i}=VP.fromBinary(r);return i==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield a(this,ct).sendMessagePromise(this.events.selfJoinComplete,TC.toBinary(e))).payload;return qu.fromBinary(r)})}audioActivity(e){return u(this,null,function*(){a(this,ct).sendMessage(this.events.audioActivity,YI.toBinary(e))})}}ct=new WeakMap;var dd;class Al extends gt.EventEmitter{constructor(e){super(),g(this,dd,void 0),f(this,dd,e),this.setMaxListeners(1/0)}get logger(){return a(this,dd).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(n){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:n}),Boolean(i)}}safeEmitAsPromise(e,...r){return u(this,null,function*(){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...r)})}safeEmitAsPromiseWithTimeout(e,r,...i){return u(this,null,function*(){return new Promise((n,s)=>{setTimeout(s,r,"event request timeout");try{this.emit(e.toString(),...i,n,s)}catch(o){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:o}),s(o)}})})}}dd=new WeakMap;class Rp extends Al{constructor(){super(...arguments),m(this,"_sendWebStream",new MediaStream),m(this,"_sendScreenShareStream",new MediaStream),m(this,"_direction"),m(this,"pc"),m(this,"_transportReady",!1),m(this,"_mapMidTransceiver",new Map),m(this,"enableHighBitrate",!1),m(this,"enableStereo",!1),m(this,"enableDtx",!0),m(this,"sfu",Oe.HIVE)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(this.logger.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){this.logger.error(`${this.name}::pc.close()`,{error:e})}}restartIce(){return u(this,null,function*(){this.logger.debug(`${this.name}::restartIce()`);const e=yield this.pc.createOffer({iceRestart:!0});return this.logger.debug(`${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:r=>u(this,null,function*(){this.logger.info(`${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this.pc.setRemoteDescription(r)})}})}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:n,proprietaryConstraints:s,onTrackHandler:o}){this.logger.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},n),s),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}connect(){return u(this,null,function*(){let e;this.sfu===Oe.CF?this.pc.addTransceiver("video",{direction:"sendonly"}):e=this.pc.createDataChannel("dyte");const r=yield this.pc.createOffer();return yield this.pc.setLocalDescription(r),this.logger.info(`connect offer: ${JSON.stringify(r)}`),{offerSdp:r,callback:i=>u(this,null,function*(){this.logger.debug(`${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this.pc.setRemoteDescription(i),e==null||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 r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),this.logger.debug(`stopSending() [localId:${e}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");r.sender.replaceTrack(null),this.pc.removeTrack(r.sender),r.direction="inactive";const i=yield this.pc.createOffer();return this.logger.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),yield this.pc.setLocalDescription(i),{offerSdp:i,callback:n=>u(this,null,function*(){this.logger.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this.pc.setRemoteDescription(n),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,r){return u(this,null,function*(){this._assertSendDirection(),r?this.logger.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):this.logger.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(r)})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((s,o)=>{o<=r?s.active=!0:s.active=!1}),yield i.sender.setParameters(n)})}setRtpEncodingParameters(e,r){return u(this,null,function*(){this._assertSendDirection(),this.logger.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((s,o)=>{n.encodings[o]=V(V({},s),r)}),yield i.sender.setParameters(n)})}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.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:this.logger.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),this.logger.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":this.logger.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":this.logger.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{this.logger.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this.pc.addEventListener("datachannel",e=>{this.logger.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{this.logger.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{this.logger.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{this.logger.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class Mp extends Rp{static createFactory(e){return()=>new Mp(e)}get name(){return"Chrome74"}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:n,proprietaryConstraints:s,onTrackHandler:o}){this._direction=e,this.pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},n),s),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}send(e){return u(this,arguments,function*({track:r,encodings:i,codecOptions:n,screenShare:s}){this._assertSendDirection();const o=this.pc.addTransceiver(r,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:i});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const l=RTCRtpSender.getCapabilities(typeof r=="string"?r:r.kind);this.logger.info(`senders available params: ${JSON.stringify(l)}`);const h=[];n&&n.length&&n.forEach(p=>{var v;const S=l.codecs.find(T=>T.mimeType.includes(p.name));if(p.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(p.parameters)}`);const T=((v=S.sdpFmtpLine)==null?void 0:v.split(";"))||[];T.push(...p.parameters);const C=Array.from(new Set(T).values());S.sdpFmtpLine=C.join(";")}h.push(S)}),this.logger.info(`selected codecs: ${JSON.stringify(h)}`),o.setCodecPreferences(h)}const c=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(c),n&&n.findIndex(({name:l})=>l==="opus")>=0){const{enableDtx:l,enableStereo:h}=this,p=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=${p}`),c.sdp+=`a=rtcp-fb:111 nack\r
18
18
  `}this.midTransceiverMap.set(o.mid,o);const d=l=>u(this,null,function*(){return this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(l)}]`),yield this.pc.setRemoteDescription(l),o.mid});return this.logger.debug(`send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(c,void 0,2)}]`),{offerSdp:c,callback:d,sender:o.sender,mid:o.mid}})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=i=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(i.data)))}})}}class Qd extends Rp{constructor(e,r){super(e),m(this,"supportsSendEncodings",!1),this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Qd(e,r)}get name(){return"Firefox60"}send(e){return u(this,arguments,function*({track:r,encodings:i,codecOptions:n,screenShare:s}){this._assertSendDirection();const o=this.supportsSendEncodings&&i!==void 0?{sendEncodings:i}:{},c=this.pc.addTransceiver(r,V({direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream]},o));if(!this.supportsSendEncodings&&i){i.reverse();const h=c.sender.getParameters();h.encodings=i,yield c.sender.setParameters(h)}const d=(h,p)=>{var v;const S=Pn(h),T=S.media[S.media.length-1],C=T.rtp.filter(B=>p.some(w=>w.name===B.codec)),b=T.fmtp.filter(B=>C.some(w=>w.payload===B.payload)),R=(v=T.rtcpFb)==null?void 0:v.filter(B=>C.some(w=>w.payload===B.payload)),j=C.map(B=>B.payload);return S.media[S.media.length-1].rtp=C,S.media[S.media.length-1].fmtp=b,S.media[S.media.length-1].rtcpFb=R,S.media[S.media.length-1].payloads=j.join(" "),jc(S)},l=yield this.pc.createOffer();if(l.sdp=d(l.sdp,n),this.logger.debug(`send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),yield this.pc.setLocalDescription(l),r==="audio"||r.kind==="audio"){const{enableDtx:h,enableStereo:p}=this,v=this.enableHighBitrate?p?128e3:64e3:p?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${p?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${v}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:h=>u(this,null,function*(){return this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this.pc.setRemoteDescription(h),c.mid}),sender:c.sender,mid:c.mid}})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters(),s=n.encodings.length-1-r;n.encodings.forEach((o,c)=>{c>=s?o.active=!0:o.active=!1}),yield i.sender.setParameters(n)})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=i=>u(this,null,function*(){const n=yield i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n)))})})}}class Ap extends Rp{static createFactory(e){return()=>new Ap(e)}get name(){return"Safari12"}send(e){return u(this,arguments,function*({track:r,encodings:i,codecOptions:n,screenShare:s}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const o=this.pc.addTransceiver(r,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:i}),c=RTCRtpSender.getCapabilities(typeof r=="string"?r:r.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(c)}`);const d=[];n&&n.length>0&&n.forEach(h=>{var p;const v=c.codecs.find(S=>S.mimeType.includes(h.name));if(h.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(h.parameters)}`);const S=((p=v.sdpFmtpLine)==null?void 0:p.split(";"))||[];S.push(...h.parameters);const T=[...new Set(S).values()];v.sdpFmtpLine=T.join(";")}d.push(v)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(d)}`),o.setCodecPreferences(d);const l=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(l),r==="audio"||r.kind==="audio"){const{enableStereo:h,enableDtx:p}=this,v=this.enableHighBitrate?h?128e3:64e3:h?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${h?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${v}`)}return this.midTransceiverMap.set(o.mid,o),{offerSdp:l,callback:h=>u(this,null,function*(){return this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this.pc.setRemoteDescription(h),o.mid}),sender:o.sender,mid:o.mid}})}addCustomEventListeners(){this.pc.ondatachannel=e=>{const{channel:r}=e;r.onmessage=i=>u(this,null,function*(){const n=String.fromCharCode(...new Uint8Array(i.data));this.safeEmit("datachannel",e.channel,n)})}}}function dN(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}var ld,ws,ri,lh,ai,Gi,ud,fu,uh,My,hh,Ay;class lN extends Al{constructor(e,r){var i;super(e),g(this,ai),g(this,ud),g(this,uh),g(this,hh),m(this,"rtpReceiver"),m(this,"id"),m(this,"localId"),m(this,"producerId"),m(this,"producingTransportId"),m(this,"mimeType"),m(this,"track"),m(this,"peerId"),m(this,"appData"),m(this,"transceiver"),g(this,ld,void 0),g(this,ws,void 0),g(this,ri,void 0),g(this,lh,void 0),this.id=r.id,this.localId=r.localId,f(this,ld,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,ri,!1),this.producerId=r.producerId,this.track=r.track,f(this,ws,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,U(this,uh,My).call(this),f(this,lh,e)}get closed(){return a(this,ri)}get kind(){return this.track.kind}get paused(){return a(this,ws)}close(e,r){a(this,ri)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,ai,Gi)),f(this,ri,!0),r&&(U(this,hh,Ay).call(this),this.transceiver.stop()),this.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(a(this,ri))throw new Ut("closed");return a(this,ld).getReceiverStats(this.localId)})}pause(){if(this.logger.debug("consumer::pause()",a(this,ai,Gi)),a(this,ri)){this.logger.error("consumer::pause() | Consumer closed",a(this,ai,Gi));return}f(this,ws,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,ai,Gi)),a(this,ri)){this.logger.error("Consumer::resume() | Consumer closed",a(this,ai,Gi));return}f(this,ws,!1),this.track.enabled=!0,this.safeEmit("resume")}}ld=new WeakMap,ws=new WeakMap,ri=new WeakMap,lh=new WeakMap,ai=new WeakSet,Gi=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},ud=new WeakSet,fu=function(){this.logger.debug('Consumer::track "ended" event',a(this,ai,Gi)),this.safeEmit("trackended")},uh=new WeakSet,My=function(){this.track.addEventListener("ended",U(this,ud,fu).bind(this))},hh=new WeakSet,Ay=function(){try{this.track.removeEventListener("ended",U(this,ud,fu)),this.track.stop()}catch(t){this.logger.error("Consumer::destroyTrack()",q(V({},a(this,ai,Gi)),{error:t}))}};var Br,go,fo,_s,Tr,ht,En,vo,ph,ar,br;class uN extends Al{constructor(e,r){var i,n;super(e),g(this,ar),m(this,"id"),m(this,"localId"),g(this,Br,void 0),m(this,"kind"),m(this,"appData"),m(this,"rtpSender"),g(this,go,void 0),g(this,fo,void 0),g(this,_s,void 0),g(this,Tr,!1),g(this,ht,void 0),g(this,En,void 0),g(this,vo,void 0),g(this,ph,void 0),this.id=r.id,this.localId=r.localId,f(this,ht,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,En,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,vo,void 0),f(this,go,r.stopTracks),f(this,fo,r.disableTrackOnPause),f(this,_s,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,Br,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,ph,e)}get closed(){return a(this,Tr)}get track(){return a(this,ht)}get paused(){return a(this,En)}get maxSpatialLayer(){return a(this,vo)}close(e){return u(this,null,function*(){if(a(this,Tr))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,ar,br)),f(this,Tr,!0),this._destroyTrack(),e===Xd){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=yield a(this,Br).stopSending(this.localId),{answer:n}=yield this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)})}getStats(){return u(this,null,function*(){if(a(this,Tr))throw new Ut("closed");return a(this,Br).getSenderStats(this.localId)})}pause(){this.logger.debug("Producer::pause()",a(this,ar,br)),a(this,Tr)&&this.logger.error("Producer::pause() | Producer closed",a(this,ar,br)),f(this,En,!0),a(this,ht)&&a(this,fo)&&(a(this,ht).enabled=!1),a(this,_s)&&a(this,Br).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,ar,br)),a(this,Tr)){this.logger.error("Producer::resume() | Producer closed",a(this,ar,br));return}f(this,En,!1),a(this,ht)&&a(this,fo)&&(a(this,ht).enabled=!0),a(this,_s)&&a(this,Br).replaceTrack(this.localId,a(this,ht)),this.emit("resume")}replaceTrack(e){return u(this,arguments,function*({track:r}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${r==null?void 0:r.id}`,a(this,ar,br)),a(this,Tr)){if(r&&a(this,go))try{r.stop()}catch(i){this.logger.error("Producer::replaceTrack",q(V({},a(this,ar,br)),{error:i}))}throw new Ut("closed")}else if(r&&r.readyState==="ended")throw new Ut("track ended");if(r===a(this,ht)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${r.id}`,a(this,ar,br));return}(!a(this,_s)||!a(this,En))&&(yield a(this,Br).replaceTrack(this.localId,r)),this._destroyTrack(),f(this,ht,r),this._handleTrack()})}setMaxSpatialLayer(e){return u(this,null,function*(){if(a(this,Tr))throw new Ut("closed");if(this.kind!=="video")throw new Yo("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield a(this,Br).setMaxSpatialLayer(this.localId,e),f(this,vo,e)})}setRtpEncodingParameters(e){return u(this,null,function*(){if(a(this,Tr))throw new Ut("closed");if(typeof e!="object")throw new TypeError("invalid params");yield a(this,Br).setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,ar,br)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,ht)&&a(this,ht).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,ht))try{a(this,ht).removeEventListener("ended",this._onTrackEnded),a(this,go)&&a(this,ht).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,q(V({},a(this,ar,br)),{error:r}))}}}Br=new WeakMap,go=new WeakMap,fo=new WeakMap,_s=new WeakMap,Tr=new WeakMap,ht=new WeakMap,En=new WeakMap,vo=new WeakMap,ph=new WeakMap,ar=new WeakSet,br=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function Dy(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function mh(t){return Math.random().toString(36).substring(2,2+t)}const Nc=1;function Ng(t){const e=t;return delete e.payload._bolt,e}function hN(t){return t.payload&&Dy(t.payload)}function Oy(t){var e,r;return hN(t)&&(r=(e=t.payload._bolt)==null?void 0:e.id)!=null?r:""}var kn,gh,Is;const yo=class extends gt.EventEmitter{constructor(t,e,r,i){super(),m(this,"channel"),m(this,"queue"),m(this,"serverProtocolVersion"),g(this,kn,new Map),g(this,gh,void 0),g(this,Is,void 0),m(this,"respond",(n,s,o=!1)=>{let c;o?c=yo.createErrorResponse(n,s):c=yo.createResponse(n,s),this.channel.send(JSON.stringify(c))}),m(this,"notify",n=>{const s=yo.createNotification(n);this.channel.send(JSON.stringify(s))}),m(this,"request",n=>u(this,null,function*(){const s=yo.createRequest(n),o=new Promise((c,d)=>{const{id:l}=s.payload._bolt,h={id:l,method:s.type,resolve:p=>{this.queue.delete(l)&&(clearTimeout(h.timer),c(p))},timer:setTimeout(()=>{this.queue.delete(l)&&d(new Error(`request timeout for message id: ${l}`))},2e4),cancel:p=>{this.queue.delete(l)&&(clearTimeout(h.timer),d(p))}};this.queue.set(l,h)});return this.channel.send(JSON.stringify(s)),o})),m(this,"send",n=>{const s=JSON.stringify(n),o=16384;if(s.length>o){const c=o-200,d=Math.ceil(s.length/c),l=[];for(let p=0;p<d;p+=1){const v=p*c,S=(p+1)*c;l.push(s.slice(v,S))}const h=Ln();for(let p=0;p<d;p+=1){const v=l[p],S=JSON.stringify({id:h,count:d,chunkIndex:p,chunk:v});a(this,Is).debug(`Sending message chunk over dc: ${S}`),this.channel.send(S)}}else a(this,Is).debug(`Sending message over dc: ${s}`),this.channel.send(s)}),m(this,"processMessage",n=>{var s;a(this,kn).has(n.id)||a(this,kn).set(n.id,[]);const o=a(this,kn).get(n.id);if(o[n.chunkIndex]=n,(o==null?void 0:o.length)===n.count&&!o.some(c=>c===void 0)){const c=a(this,kn).get(n.id),d=c==null?void 0:c.reduce((h,p)=>h+p.chunk,"");a(this,kn).delete(n.id);const l=JSON.parse(d);if(!l.payload||!Dy(l.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:l}});if(this.processBoltHandshake(l))return;if(this.serverProtocolVersion=(s=l.payload._bolt)==null?void 0:s.version,!this.processResponseMsg(l))return l}}),m(this,"processResponseMsg",n=>{const{id:s}=n.payload._bolt,o=this.queue.get(s);return o?(a(this,Is).debug(`resolving pending request with id: ${s}, complete response: ${JSON.stringify(n)}`),n.type==="error"?o.cancel(Ng(n)):o.resolve(Ng(n)),!0):!1}),m(this,"processBoltHandshake",n=>{var s,o;return n.type==="_bolt"||n.type==="handshake"?(this.respond((o=(s=n.payload._bolt)==null?void 0:s.id)!=null?o:mh(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=r,this.transportId=i,f(this,gh,t),f(this,Is,t.getValue("logger")),this.channel=e,this.queue=new Map}};let So=yo;kn=new WeakMap,gh=new WeakMap,Is=new WeakMap,m(So,"createRequest",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:q(V({},t.payload),{_bolt:{id:mh(8),type:"REQUEST",version:Nc}})}}),m(So,"createResponse",(t,e)=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:q(V({},e.payload),{_bolt:{id:t,type:"RESPONSE",version:Nc}})}}),m(So,"createNotification",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:q(V({},t.payload),{bolt:{id:mh(8),type:"NOTIFY",version:Nc}})}}),m(So,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:Nc}}}));const Xd="transport closed";var Cs,Ps;const Eo=class extends Al{constructor(t,e,{id:r,direction:i,handlerFactory:n,iceServers:s,iceTransportPolicy:o,proprietaryConstraints:c,additionalSettings:d,appData:l,config:h}){var p,v,S;super(t),m(this,"awaitQueue"),m(this,"observer"),g(this,Cs,void 0),m(this,"id"),m(this,"serverId"),m(this,"direction"),m(this,"maxSctpMessageSize"),m(this,"handler"),m(this,"connectionState","new"),m(this,"producers"),m(this,"consumers"),m(this,"datachannels"),m(this,"connected",!1),m(this,"eventsDCReadyPromise"),m(this,"eventsDCReadyPromiseResolver"),m(this,"eventsDCFailureTimer"),m(this,"transportConnectionPromise"),m(this,"consumerTrackEvents"),m(this,"unknownTracksMap"),m(this,"appData"),g(this,Ps,void 0),f(this,Ps,t);const T=t.getValue("logger");T.debug(`constructor() [id: ${r}, direction: ${i}]`),f(this,Cs,e),this.id=r,this.direction=i;const C=dN(d,{});delete C.iceServers,delete C.iceTransportPolicy,delete C.bundlePolicy,delete C.rtcpMuxPolicy,delete C.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new dh(T,!0),this.handler=n(),this.handler.enableHighBitrate=(p=h==null?void 0:h.enableHighBitrate)!=null?p:!1,this.handler.enableStereo=(v=h==null?void 0:h.enableStereo)!=null?v:!1,this.handler.enableDtx=(S=h==null?void 0:h.enableDtx)!=null?S:!0,this.handler.sfu=a(this,Cs),this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:s,iceTransportPolicy:o,additionalSettings:d,proprietaryConstraints:c}),this.appData=l||{},this.transportConnectionPromise=new Promise(b=>{this.once("connected",()=>{b(!0)}),this.once("disconnect",()=>{b(!1)}),this.once("close",()=>{b(!1)})}),this.eventsDCReadyPromise=new Promise(b=>{this.eventsDCReadyPromiseResolver=b}),this.handler.on("@connectionstatechange",b=>{b!==this.connectionState&&(this.logger.debug(`connection state changed to ${b}`),this.connectionState=b,b==="connected"&&(this.connected=!0,this.emit("connected")),b==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(b==="failed"||b==="closed")&&(this.connected=!1,this.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 R=this.datachannels.get(b.label);R||(R||(R=new So(a(this,Ps),b,b.label,this.serverId),this.datachannels.set(b.label,R)),this.eventsDCFailureTimer=setTimeout(()=>{b.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",b.label))},5e3))}),this.handler.on("datachannel",(b,R)=>{b.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const j=this.datachannels.get(b.label);if(!j){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:b.label,message:R}});return}try{const B=JSON.parse(R);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:B.id,count:B.count,chunkIndex:B.chunkIndex,chunk:B.chunk,transprtId:this.serverId}});const w=j.processMessage(B);if(!w)return;this.logger.debug(`datachannel message with id:${B.id} on transport:${this.serverId}complete - ${JSON.stringify(w)}`),this.emit(`datachannel:${b.label}`,j.label,w)}catch(B){this.logger.error("error parsing message",{error:B})}})}get closed(){return this.connectionState==="closed"}setServerId(t){this.serverId=t}getDatachannel(t){return this.datachannels.get(t)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(t=>{t.close(Xd).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(t=>{t.close(Xd)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}getStats(){return u(this,null,function*(){if(this.closed)throw new Ut("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:r}=yield this.handler.connect(),{transportId:i,answer:n}=yield t(e);this.setServerId(i),yield r(n)})),!(yield this.transportConnectionPromise))throw new Error("ice connection failed");if(a(this,Cs)===Oe.HIVE&&!(yield this.isEventsDCReady))throw new Error("events datachannel not open")}catch(e){throw this.logger.error("transport failed to connect:",{error:e}),e}})}restartIce(){return u(this,null,function*(){if(this.logger.debug("restartIce()"),this.closed)throw new Ut("closed");return this.handler.restartIce()})}canProduce(t){return u(this,null,function*(){const{track:e,appData:r}=t;if(e){if(this.direction!=="send")throw new Yo("not a sending Transport");if(e.readyState==="ended")throw new Ut("track ended");if(r&&typeof r!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.transportConnectionPromise))throw new Dn("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:r,encodings:i,codecOptions:n,stopTracks:s=!0,disableTrackOnPause:o=!0,zeroRtpOnPause:c=!1,appData:d={}}=t;this.logger.debug(`produce() [track:${r.id}]`);const{producerId:l,localId:h,rtpSender:p}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:v,callback:S,sender:T,mid:C}=yield this.handler.send({track:r,encodings:i,codecOptions:n,screenShare:d==null?void 0:d.screenShare}),{answer:b,producerId:R}=yield e({offer:v,kind:r.kind,paused:o?!r.enabled||Object.hasOwn(r,"fakeTracks"):!1,appData:q(V({},d||{}),{mid:C}),codecOptions:n,producingTransportId:this.serverId}),j=yield S(b);return{producerId:R,localId:j,rtpSender:T}}),"Transport.produce");return this.createProducerObject({id:l,localId:h,track:r,stopTracks:s,disableTrackOnPause:o,zeroRtpOnPause:c,appData:d,handler:this.handler,rtpSender:p})})}createProducerObject(t){return u(this,null,function*(){const e=new uN(a(this,Ps),t);return this.producers.set(e.id,e),e.once("close",()=>{this.producers.delete(e.id)}),this.emit("newproducer",e),e})}closeProducer(t){return u(this,null,function*(){yield this.awaitQueue.push(t.close.bind(t),"Transport.closeProducer")})}canConsume(){return u(this,null,function*(){if(this.closed)throw new Ut("closed");if(this.direction!=="recv")throw new Yo("not a receiving transport");if(!(yield this.transportConnectionPromise))throw new Dn("transport not connected");return!0})}consume(t,e,r){return u(this,null,function*(){return this.awaitQueue.push(()=>u(this,null,function*(){const i={},{consumerStates:n,sessionDescription:s,failedProducers:o}=yield e(t);n.forEach((d,l)=>{i[l]=this.createConsumerObjectAndWaitForTrack(q(V({},d),{producerId:l}))}),s&&(this.logger.info("Session description found, sending negotiation request"),yield r(s));const c=[];return yield Promise.all(Object.entries(i).map(([d,l])=>l.then(h=>c.push(h)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${d}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:c,failedProducers:o}}),"Transport.consume",{producersLength:t.length})})}static parseCodecAndFmtpMappings(t,e){const r=Pn(t.sdp),i={};return r.media.forEach(n=>{e.includes(n.mid.toString())&&(i[n.mid.toString()]={rtp:n.rtp,fmtp:n.fmtp,payloads:n.payloads,rtcpFb:n.rtcpFb})}),i}static setCodecAndFmtpMappings(t,e,r){const i=Pn(t.sdp);return i.media=i.media.map(n=>{if(e.includes(n.mid.toString())){const s=V({},n);return s.rtp=r[n.mid.toString()].rtp,s.fmtp=r[n.mid.toString()].fmtp,s.payloads=r[n.mid.toString()].payloads,s.rtcpFb=r[n.mid.toString()].rtcpFb,s}return n}),q(V({},t),{sdp:jc(i)})}static parseHeaderExtensionMappings(t){const e=Pn(t.sdp),r={};return e.media.forEach(i=>{r[i.mid]=i.ext}),r}static setHeaderExtensionMappings(t,e){const r=Pn(t.sdp);return r.media=r.media.map(i=>{const n=V({},i);return n.ext=e[i.mid],n}),q(V({},t),{sdp:jc(r)})}closeConsumers(t,e){return u(this,null,function*(){try{const r=t.map(c=>c.transceiver.mid),i=Eo.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,r),n=Eo.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:t.map(({id:c})=>c)}),t.forEach(c=>c.close(void 0,!0));let s=yield this.handler.pc.createOffer();this.logger.info("Created offer for closing consumers",{sdp:s.sdp}),s=Eo.setCodecAndFmtpMappings(s,r,i),s=Eo.setHeaderExtensionMappings(s,n),this.logger.info("Updated codec and fmtp mappings in close consumer offer",{sdp:s.sdp}),yield this.setLocalDescription(s),this.logger.info("Successfully set local description in close consumers");const o=yield e(t,s);this.logger.info("Received answer in close consumers",{sdp:o.sdp}),yield this.setRemoteDescription(o),this.logger.info("Remote description was set successfully in close consumers",{sdp:o.sdp})}catch(r){this.logger.error("Failed to close consumers",{error:r})}})}setRemoteOffer(t){return u(this,null,function*(){try{this.logger.info("Received offer from SFU",{sdp:t.sdp}),yield this.setRemoteDescription(t);const e=yield this.handler.pc.createAnswer();this.logger.info("Created answer corresponding to received offer",{sdp:e.sdp});const r=Pn(e.sdp);return r.media=r.media.map(i=>{if(i.type==="audio"){const n=V({},i),s=n.fmtp.find(o=>o.payload===111);return s&&(s.config+=";stereo=1;sprop-stereo=1"),n.rtcpFb||(n.rtcpFb=[]),n.rtcpFb.some(o=>o.type==="nack")||n.rtcpFb.push({payload:parseInt(n.payloads,10),type:"nack"}),n}return i}),e.sdp=jc(r),this.logger.info("Setting munged SDP",{sdp:e.sdp}),yield this.setLocalDescription(e),this.logger.info("Successfully set local description",{sdp:e.sdp}),e}catch(e){throw this.logger.error("Set remote offer failed",{error:e}),e}})}_ontrack(t){const{track:e,transceiver:r,streams:i}=t;this.logger.info(`track event received [trackId: ${e.id}] [mid: ${r.mid}]`);let n;a(this,Cs)===Oe.HIVE?n=`${i[0].id}:${e.kind}`:n=`${r.mid}:${e.kind}`,e.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${e.id}]`),this.unknownTracksMap.delete(n)});const s=this.consumerTrackEvents.get(n);s?(s(e,r),this.consumerTrackEvents.delete(n)):(this.logger.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,t))}sendErrorOverDC(t,e,r){const i=this.getDatachannel(t);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});i.respond(e,r,!0)}sendResponseOverDC(t,e,r){const i=this.getDatachannel(t);if(!i)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});i.respond(e,r)}createConsumerObjectAndWaitForTrack(t){return u(this,null,function*(){const{consumerId:e,producerId:r,producingPeerId:i,producingTransportId:n,streamId:s,paused:o,screenShare:c,appData:d,kind:l,mimeType:h}=t,p=`${s}:${l}`,v=q(V({},t),{name:"consumer creation task error",message:"consumer creation failed"});return new Promise((S,T)=>u(this,null,function*(){const C=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${p} producingPeerId: ${i}`),this.consumerTrackEvents.delete(p),v.isTimedout=!0,T(v)},5e3),b=(j,B)=>{try{if(j.readyState==="ended")clearTimeout(C),T(v);else{const w=j;w.enabled=!0,this.handler.midTransceiverMap.set(B.mid,B);const ee=new lN(a(this,Ps),{id:e,localId:B.mid,transceiver:B,track:w,paused:o,producerId:r,producingPeerId:i,producingTransportId:n,handler:this.handler,appData:q(V({},d),{screenShare:c,peerId:i}),rtpReceiver:B.receiver,mimeType:h});this.consumers.set(e,ee),ee.once("close",()=>{this.consumers.delete(ee.id),this.handler.midTransceiverMap.delete(B.mid)}),this.logger.info("consumer created for ",{consumer:{id:e,kind:l,appData:{screenShare:c},peerId:i,producerId:r}}),this.emit("newconsumer",ee),clearTimeout(C),S(ee)}}catch(w){this.logger.warn("error while creating consumer:",w),clearTimeout(C),T(v)}},R=this.unknownTracksMap.get(p);R?(this.logger.info(`track event already received [trackId: ${R.track.id}] [mid: ${R.transceiver.mid}]`),this.unknownTracksMap.delete(p),b(R.track,R.transceiver)):(this.logger.info(`Registering onTrack handler for key ${p} [producingPeerId: ${i}]`),this.consumerTrackEvents.set(p,b))}))})}setRemoteDescription(t){return u(this,null,function*(){yield this.handler.pc.setRemoteDescription(t)})}setLocalDescription(t){return u(this,null,function*(){this.logger.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(t)}]`),yield this.handler.pc.setLocalDescription(t)})}sendDataChannelMessage(t,e){return u(this,null,function*(){const r=this.getDatachannel(t);if(!r)throw nN("DC_NOT_READY",`${t} datachannel not ready`);const i=(yield r.request(e)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(i)}`),i})}};let pN=Eo;Cs=new WeakMap,Ps=new WeakMap;function mN(t){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){t.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return t.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const e=navigator.userAgent,r=pf.getParser(e),i=r.getEngine();if(r.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(r.satisfies({chrome:">=55",chromium:">=55"}))return;if(r.satisfies({firefox:">=110"}))return"Firefox110";if(r.satisfies({firefox:">=60"}))return"Firefox60";if(r.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||r.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(r.satisfies({safari:">=11"})||r.satisfies({"microsoft edge":">=11"})&&r.satisfies({"microsoft edge":"<=18"}))return;if(i.name&&i.name.toLowerCase()==="blink"){const n=e.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return n?Number(n[1])>=74?"Chrome74":void 0:"Chrome74"}if(i.name.toLowerCase()==="webkit"&&r.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;t.warn("Device::this._detectDevice() | browser not supported");return}t.warn("Device::this._detectDevice() | unknown device")}var hd,Vi,Rs;class gN{constructor(e,r,{handlerName:i,handlerFactory:n}={}){m(this,"handlerFactory"),g(this,hd,void 0),g(this,Vi,void 0),g(this,Rs,void 0);const s=e.getValue("logger");if(s.debug("constructor()"),f(this,Vi,e),f(this,Rs,s),f(this,hd,r),i&&n)throw new TypeError("just one of handlerName or handlerInterface can be given");if(n)this.handlerFactory=n;else{if(i)a(this,Rs).debug(`Device::constructor() | handler given: ${i}`);else if(i=mN(a(this,Rs)),i)a(this,Rs).debug(`Device::constructor() | detected handler: ${i}`);else throw new Error("device not supported");switch(i){case"Chrome74":this.handlerFactory=Mp.createFactory(a(this,Vi));break;case"Safari12":this.handlerFactory=Ap.createFactory(a(this,Vi));break;case"Firefox60":this.handlerFactory=Qd.createFactory(a(this,Vi),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Qd.createFactory(a(this,Vi),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${i}"`)}}}createTransport(e){const r=Ln();return new pN(a(this,Vi),a(this,hd),q(V({id:r},e),{handlerFactory:this.handlerFactory}))}}hd=new WeakMap,Vi=new WeakMap,Rs=new WeakMap;const fN=2e3;var Do,It,Ct,pd,md,Hs,Oo,ko,To,Ms,oi,No,Vo,gd,fd,fh,vh,Ny,vd,yh,Sh,Vg,Eh,Lg,kh,xg,Th,Ug,bh,Fg,yd,vu,Sd,yu;class vN extends gt.EventEmitter{constructor(e,r,i){switch(super(),g(this,Vo),g(this,fd),g(this,vh),g(this,vd),g(this,Sh),g(this,Eh),g(this,kh),g(this,Th),g(this,bh),g(this,yd),g(this,Sd),m(this,"context"),g(this,Do,void 0),g(this,It,void 0),g(this,Ct,void 0),g(this,pd,void 0),g(this,md,void 0),g(this,Hs,void 0),g(this,Oo,void 0),g(this,ko,void 0),g(this,To,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0}),g(this,Ms,void 0),g(this,oi,"all"),g(this,No,void 0),this.context=e,f(this,Hs,r),f(this,No,i),f(this,Do,new gN(e,i)),f(this,Oo,new cN(r,i)),i){case Oe.CF:{f(this,ko,Ir);break}case Oe.HIVE:default:{f(this,ko,dr);break}}a(this,Vo,gd).mediaState={send:{state:Xs.NEW},recv:{state:Xs.NEW}},(Ys(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(Z.FORCE_RELAY))&&f(this,oi,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,oi)}`),U(this,fd,fh).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,Hs)}get socketHandler(){return a(this,Oo)}get sendTransport(){return a(this,It)}get recvTransport(){return a(this,Ct)}get events(){return a(this,ko)}get nodeType(){return a(this,No)}set sendTransportConnectedCallback(e){f(this,pd,e)}set recvTransportConnectedCallback(e){f(this,md,e)}setupTransports(e){return u(this,null,function*(){yield U(this,vh,Ny).call(this,e);let r,i;e.send&&(r=U(this,vd,yh).call(this,a(this,It)).then(n=>{try{a(this,pd).call(this,n)}catch{this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=U(this,vd,yh).call(this,a(this,Ct)).then(n=>{try{a(this,md).call(this,n)}catch{this.logger.error("Failed to run recv transport callback")}})),yield Promise.all([r,i])})}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:n,serverId:s,direction:o}=a(this,It);this.logger.info("Closing send transport",{transport:{id:n,serverId:s,type:o}}),a(this,It).close(),a(this,It).removeAllListeners(),f(this,It,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:s,direction:o}=a(this,Ct);this.logger.info("Closing recv transport",{transport:{id:n,serverId:s,type:o}}),(r=a(this,Ct))==null||r.close(),(i=a(this,Ct))==null||i.removeAllListeners(),f(this,Ct,void 0)}U(this,fd,fh).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}Do=new WeakMap,It=new WeakMap,Ct=new WeakMap,pd=new WeakMap,md=new WeakMap,Hs=new WeakMap,Oo=new WeakMap,ko=new WeakMap,To=new WeakMap,Ms=new WeakMap,oi=new WeakMap,No=new WeakMap,Vo=new WeakSet,gd=function(){return this.context.getValue("connectionHandler")},fd=new WeakSet,fh=function(){f(this,Ms,{send:void 0,recv:void 0})},vh=new WeakSet,Ny=function(t){return u(this,null,function*(){var e,r,i,n,s,o,c,d;(Ys(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(Z.FORCE_RELAY))&&f(this,oi,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,oi)}`);const l=yield pt().getICEServers().catch(h=>(this.logger.warn(`failed to get iceservers from server: ${h.message}`),[]));if(t.send){const h=this.context.getValue("flagsmith").hasFeature(Z.DISABLE_OPUS_DTX_CF);U(this,Eh,Lg).call(this,{iceServers:l,additionalSettings:{encodedInsertableStreams:(e=this.context.getValue("modules").e2ee)==null?void 0:e.enabled},config:{enableHighBitrate:(n=(i=(r=this.context.getValue("defaults").mediaConfiguration)==null?void 0:r.audio)==null?void 0:i.enableHighBitrate)!=null?n:!1,enableStereo:(c=(o=(s=this.context.getValue("defaults").mediaConfiguration)==null?void 0:s.audio)==null?void 0:o.enableStereo)!=null?c:!1,enableDtx:a(this,No)===Oe.HIVE?!0:!!h},iceTransportPolicy:a(this,oi)})}t.recv&&U(this,kh,xg).call(this,{iceServers:l,additionalSettings:{encodedInsertableStreams:(d=this.context.getValue("modules").e2ee)==null?void 0:d.enabled},iceTransportPolicy:a(this,oi)})})},vd=new WeakSet,yh=function(t){return u(this,null,function*(){const{id:e,serverId:r,direction:i}=t;U(this,Th,Ug).call(this,t);try{const n=this.context.getValue("flagsmith").hasFeature(Z.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3;return yield Ry((s,o)=>u(this,null,function*(){s>0&&this.logger.debug(`Retrying transport connect, count: ${s}`,{transport:{id:e,serverId:r,type:i}});try{if(t.closed)throw new Dn("Cannot reconnect closed transport");yield U(this,Sh,Vg).call(this,t)}catch(c){if(c instanceof Dn){o(c);return}throw this.logger.error("Failed to connect transport, retrying",{transport:t,error:c}),c}}),{delayTime:100,strategy:"exponential",maxRetryCount:n}),t}catch(n){throw this.logger.error(`Failed to connect send transport after retry: ${t.id}`,{error:n,transport:{id:e,serverId:r,type:i}}),t.close(),t.removeAllListeners(),n}})},Sh=new WeakSet,Vg=function(t){return u(this,null,function*(){const{id:e,direction:r}=t;if(this.logger.info(`Connecting ${r} transport`,{transport:{id:e,type:r}}),!a(this,Hs).isConnected)throw new Dn("Socket is not connected");if(t.connectionState==="closed")throw new Dn("Transport is closed");try{yield t.connect(i=>U(this,bh,Fg).call(this,r,i)),this.logger.info(`Connected ${r} transport`,{transport:{id:e,serverId:t.serverId,type:r}})}catch(i){throw a(this,To).transportFailureCount[r]+=1,i.message==="ice connection failed"?new Dn(i.message):i}})},Eh=new WeakSet,Lg=function(t){var e,r;if(a(this,It)&&a(this,It).connected){this.logger.info("Transport send is already connected",{transport:{id:(e=a(this,It))==null?void 0:e.id,serverId:(r=a(this,It))==null?void 0:r.serverId,type:"send"}});return}f(this,It,a(this,Do).createTransport(q(V({},t),{direction:"send"}))),this.context.getValue("callstats").configureSendTransport(a(this,It))},kh=new WeakSet,xg=function(t){var e,r;if(a(this,Ct)&&a(this,Ct).connected){this.logger.info("Transport recv is already connected",{transport:{id:(e=a(this,Ct))==null?void 0:e.id,serverId:(r=a(this,Ct))==null?void 0:r.serverId,type:"recv"}});return}f(this,Ct,a(this,Do).createTransport(q(V({},t),{direction:"recv"}))),this.context.getValue("callstats").configureRecvTransport(a(this,Ct))},Th=new WeakSet,Ug=function(t){const{direction:e,id:r}=t;t.on("connectionstatechange",i=>u(this,null,function*(){U(this,Sd,yu).call(this,{state:i,direction:e}),this.logger.info(`Transport connection state changed for ${e} transport`,{transport:{id:r,serverId:t.serverId,type:e,status:i}});const n=()=>{const s=a(this,Ms)[e];s!==void 0&&(clearTimeout(s),a(this,Ms)[e]=void 0)};switch(i){case"connected":n(),a(this,To).lastConnectionTime=performance.now();break;case"disconnected":a(this,Ms)[e]=setTimeout(()=>u(this,null,function*(){this.logger.warn(`${e} transport is in disconnected state, reconnecting transport`,{transport:{id:r,serverId:t.serverId,type:e}}),yield U(this,yd,vu).call(this,t.direction)}),fN);break;case"failed":if(t.closed)return;n(),this.logger.warn(`${e} transport is in failed state, reconnecting transport`,{transport:{id:r,serverId:t.serverId,type:e}}),yield U(this,yd,vu).call(this,t.direction);break}})),t.on("icecandidate",i=>u(this,null,function*(){this.logger.debug("Sending iceCandidate:",{iceCandidate:i})})),t.on("datachannel:events",(i,n)=>u(this,null,function*(){var s,o;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:i,message:n}});try{switch(n.type){case"handshake":{const c={type:"handshake",payload:{message:"pong"}};t.sendResponseOverDC(i,Oy(n),c);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(s=n.payload)==null?void 0:s.full_reconnect}`),((o=n.payload)==null?void 0:o.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch{this.logger.error(`Unable to handle the incoming datachannel message on channel ${i}`)}})),t.on("dc_error",()=>{t.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s",{country:k.location.country}),this.handleErrors("reconnectRecvTransport"))})},bh=new WeakSet,Fg=function(t,e){return u(this,null,function*(){const r=t==="recv";try{const{sdp:i,type:n}=e,s={consuming:r,description:{sdp:i,type:n,target:r?gi.SUBSCRIBER:gi.PUBLISHER},producers:[]};return a(this,Oo).connectTransport(s)}catch(i){throw this.logger.error(`Error in ${t} transport connection:`,{error:i,country:k.location.country}),i}})},yd=new WeakSet,vu=function(t){return u(this,null,function*(){switch(this.logger.info("Called reconnect transport",{transport:{type:t}}),this.stopTransports({[t]:!0}),this.context.getValue("flagsmith").hasFeature(Z.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED)&&a(this,Hs).isConnected&&a(this,To).transportFailureCount[t]>2&&(this.logger.warn(`Multiple disconnections in ${t} transport, forcing relay`),f(this,oi,"relay")),yield this.setupTransports({[t]:!0}),t){case"send":{this.logger.info("Transport reconnected",{transport:a(this,It)}),this.context.getValue("peerSessionStore").emit(P.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,Ct)}),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:t}})}U(this,Sd,yu).call(this,{state:Xs.CONNECTED,direction:t})})},Sd=new WeakSet,yu=function(t){const{state:e,direction:r}=t;a(this,Vo,gd).mediaState[r]={state:e},this.context.getValue("peerSessionStore").emit(P.TRANSPORT_STATE_UPDATE,V({transport:r},a(this,Vo,gd).mediaState[r]))};var Ed,wh,Vy;class yN{constructor(e,r){g(this,wh),g(this,Ed,void 0),this.recvTransport=r,U(this,wh,Vy).call(this),f(this,Ed,e)}get logger(){return a(this,Ed).getValue("logger")}create(e){return u(this,null,function*(){if(!e||e&&e.length===0)throw new Error("List of producers is required");const r={type:"create_consumer",payload:{producers:e.map(({producerId:o,producingTransportId:c,kind:d,mimeType:l})=>({producerId:o,producingTransportId:c,preferredCodec:V(V({},d==="video"&&l?{video:l}:{}),d==="audio"&&l?{audio:l}:{})}))}},i=yield this.recvTransport.sendDataChannelMessage("events",r),n=new Map;e.forEach(o=>n.set(o.producerId,o));const s=new Map;return Object.entries(i).forEach(([o,c])=>{const d=n.get(c.producerId);d&&s.set(c.producerId,{consumerId:o,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,r,i){return u(this,null,function*(){try{this.logger.debug(`Received offer over dc: ${e.sdp} for transport`);const n=yield this.recvTransport.setRemoteOffer(e),s={type:"answer",payload:{type:n.type,sdp:n.sdp}};return this.logger.debug(`datachannel answer: ${JSON.stringify(s)}`),this.recvTransport.sendResponseOverDC(i,r,s),n}catch(n){throw this.logger.error("datachannel:events::Error:",n),n.code!=="DC_NOT_FOUND"&&this.recvTransport.sendErrorOverDC(i,r,n),n}})}close(e){return u(this,null,function*(){if(!e.length)return{};const r=e.map(o=>o.id);this.logger.info(`Closing consumers: ${JSON.stringify(r)}`);const i={type:"close_consumers",payload:{consumers:r}},n=yield this.recvTransport.sendDataChannelMessage("events",i),{failedConsumers:s}=n;return{failedConsumers:s}})}switchConsumersToLayer(e,r){return u(this,null,function*(){var i;const n=this.recvTransport.getDatachannel("events");if(!n){this.logger.warn("events datachannel not found");return}const s=(i=e==null?void 0:e.map(({id:c})=>c))!=null?i:[],o={type:"switch_consumer_layer",payload:{consumerIds:s,layer:r}};yield n.request(o),this.logger.info(`Consumers switched layers to ${r}`,{consumerIds:s})})}}Ed=new WeakMap,wh=new WeakSet,Vy=function(){this.recvTransport.on("datachannel:events",(t,e)=>u(this,null,function*(){try{switch(e.type){case"negotiation":{const{sdp:r}=e.payload,i={sdp:r,type:"offer"};this.negotiate(i,Oy(e),t);break}default:break}}catch{this.logger.error(`Unable to handle the incoming datachannel message on channel ${t}`)}}))};var kd,wr;class SN{constructor(e,r,i,n,s){g(this,kd,void 0),g(this,wr,void 0),this.events=r,this.recvTransport=i,this.socket=n,this.socketHandler=s,f(this,kd,e),f(this,wr,e.getValue("logger"))}create(e){return u(this,null,function*(){if(!e||e&&e.length===0)throw new Error("List of producers is required");const r=new Map,i=[];e.forEach(d=>{const{producingPeerId:l,producerId:h,producingTransportId:p}=d,v=a(this,kd).getValue("flagsmith").hasFeature(Z.ENABLE_CF_SIMULCAST)?{simulcast:{preferredRid:"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}}:{};r.set(h,l),i.push(V({producingPeerId:l,producerId:h,producingTransportId:p},v))});const n=yield this.socketHandler.consume({requests:i,consumingTransportId:this.recvTransport.serverId}),s=new Map;e.forEach(d=>s.set(d.producerId,d));const o=new Map,c=[];return Object.entries(n.consumerStateMap).forEach(([d,l])=>{const h=s.get(d);if(!h)return;if(l.errorCode){a(this,wr).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push(q(V({},h),{errorCode:l.errorCode}));return}let p={};try{p=JSON.parse(l.producerState.appData)}catch{}o.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:p})}),{consumerStates:o,sessionDescription:n.sessionDescription,failedProducers:c}})}negotiate(e){return u(this,null,function*(){try{a(this,wr).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,wr).debug(`setting remote offer: ${JSON.stringify(e)} on recvTransport`,{transport:this.recvTransport});const r=yield this.recvTransport.setRemoteOffer(e),i={transportId:this.recvTransport.serverId,description:{sdp:r.sdp,type:r.type,target:gi.SUBSCRIBER}};return a(this,wr).debug(`sending renegotiate request: ${JSON.stringify(i)} on recvTransport`,{transport:this.recvTransport}),yield this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,ZI.toBinary(i)),a(this,wr).info("Renegotiation done",{transport:this.recvTransport}),r}catch(r){a(this,wr).error("Failed to renegotiate",{error:r});return}})}close(e){return u(this,null,function*(){if(!e.length)return{};const r=(i,n)=>u(this,null,function*(){const s=i.map(l=>l.localId);a(this,wr).info(`Closing consumers: ${JSON.stringify(s)}`);const o={description:{sdp:n.sdp,type:n.type,target:gi.SUBSCRIBER},consumerIds:s,consumingTransportId:this.recvTransport.serverId},c=yield this.socketHandler.closeConsumer(o),d=IP.fromBinary(c).description;return{sdp:d.sdp,type:d.type}});return yield this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(e,r),"ConsumerStrategy.close",{consumersLength:e.length}),{}})}switchConsumersToLayer(e,r){return u(this,null,function*(){const i={requests:[],consumingTransportId:this.recvTransport.serverId},n=e.filter(s=>s&&s.id);n.forEach(({id:s,producingTransportId:o,localId:c})=>{i.requests.push({producerId:s,producingTransportId:o,mid:c,simulcast:{preferredRid:r===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),yield this.socketHandler.updateConsumersSimulcastConfig(i),a(this,wr).info(`Consumers switched layers to ${r}`,{consumerIds:n==null?void 0:n.map(({id:s})=>s)})})}}kd=new WeakMap,wr=new WeakMap;class Dp{constructor(e){this.socketHandler=e}static getMSIDFromSDP(e,r){return Pn(e).media.filter(i=>r==="video"?i.type==="video":i.type==="audio").at(-1).msid}create(e){return u(this,arguments,function*({offer:r,kind:i,paused:n,appData:s,codecOptions:o,producingTransportId:c}){var d,l;const h=Dp.getMSIDFromSDP(r.sdp,i),p={description:{sdp:r.sdp,type:r.type,target:gi.PUBLISHER},paused:n,kind:i,msid:h,appData:JSON.stringify(s),screenShare:(d=s.screenShare)!=null?d:!1,mimeType:`${i}/${(l=o[0])==null?void 0:l.name}`,producingTransportId:c},{answer:v,producerId:S}=yield this.socketHandler.produce(p);return{answer:v,producerId:S}})}}var Bs,On,bo,Zd,Hr,_h,qi,Lo,el,Ih,Ch,Ly,Ph,xy,Rh,Bg,Mh,Wg;class EN extends vN{constructor(e,r,i){super(e,r,i),g(this,el),g(this,Ch),g(this,Ph),g(this,Rh),g(this,Mh),g(this,Bs,void 0),g(this,On,void 0),g(this,bo,void 0),g(this,Zd,void 0),g(this,Hr,void 0),g(this,_h,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0}),g(this,qi,[]),g(this,Lo,void 0),this.context=e,this.sendTransportConnectedCallback=()=>u(this,null,function*(){f(this,Zd,new Dp(this.socketHandler))}),this.recvTransportConnectedCallback=n=>u(this,null,function*(){switch(a(this,bo).clear(),this.nodeType){case Oe.CF:{f(this,Hr,new SN(this.context,this.events,n,this.socket,this.socketHandler));break}case Oe.HIVE:default:f(this,Hr,new yN(this.context,n))}}),this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,Bs)}get consumers(){return a(this,On)}get producerIdToConsumerIdMap(){return a(this,bo)}get logger(){return this.context.getValue("logger")}reset(){f(this,Bs,new Map),f(this,On,new Map),f(this,bo,new Map)}createProducer(e,r){return u(this,null,function*(){var i;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const n=yield this.sendTransport.produce(e,U(this,Ch,Ly).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,n),U(this,Ph,xy).call(this,n,r),n}catch(n){throw this.logger.error("Failed to create producer",{error:n}),a(this,_h).producerCreationFailureCount+=1,n}})}closeProducer(e,r){return u(this,null,function*(){var i;const n=this.producers.get(e);if(!n){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&n.track.stop();try{yield this.sendTransport.closeProducer(n),(i=this.context.getValue("modules").e2ee)!=null&&i.enabled&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_PRODUCER,n)}catch(s){this.logger.error("Failed to close producer on server",{error:s,producer:n})}})}closeAllProducers(){return Promise.all(Array.from(a(this,Bs).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}createConsumers(e){return u(this,null,function*(){a(this,Lo)||clearTimeout(a(this,Lo)),f(this,qi,a(this,qi).concat(e)),yield U(this,el,Ih).call(this)})}closeConsumer(e){return this.closeConsumers([e])}closeConsumers(e){return u(this,null,function*(){if(!a(this,Hr))return;const r=e.map(n=>this.consumers.get(n)).filter(n=>n!==void 0);if(r.length===0)return;const{failedConsumers:i}=yield a(this,Hr).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,On).keys()))}switchConsumersToLayer(e,r){return u(this,null,function*(){a(this,Hr).switchConsumersToLayer(e,r)})}}Bs=new WeakMap,On=new WeakMap,bo=new WeakMap,Zd=new WeakMap,Hr=new WeakMap,_h=new WeakMap,qi=new WeakMap,Lo=new WeakMap,el=new WeakSet,Ih=function(){return u(this,null,function*(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const t=500,e=a(this,qi).splice(0,a(this,qi).length);try{const r=new Set(Array.from(this.consumers.values()).map(({producerId:o})=>o)),i=e.filter(({producerId:o})=>!this.producers.get(o)&&!r.has(o));if(i.length===0)return;const{consumers:n,failedProducers:s}=yield this.recvTransport.consume(i,U(this,Rh,Bg).bind(this),a(this,Hr).negotiate.bind(a(this,Hr)));if(n.forEach(U(this,Mh,Wg).bind(this)),s!=null&&s.length){this.logger.error("Failed to create consumers for producers",{producers:s});const o=s.filter(({errorCode:c,producerId:d})=>c==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${d}. This will not be retried.`),!1):c==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);f(this,qi,a(this,qi).concat(o)),f(this,Lo,setTimeout(U(this,el,Ih).bind(this),t))}}catch(r){if(this.logger.error("failed to consume on transport",{error:r}),r.errorCode==="internal_error"&&r.errorDescription==="Backend error"||r.errorCode==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:r.errorCode,message:r.errorDescription}});try{this.stopTransports({recv:!0})}catch{}yield this.setupTransports({recv:!0})}}})},Ch=new WeakSet,Ly=function(t){return a(this,Zd).create(t)},Ph=new WeakSet,xy=function(t,e){t.on("close",(r,i)=>u(this,null,function*(){const{offer:n,reason:s}=r;if(this.logger.info("producer::closing",{debuggingHint:s,producer:q(V({},t),{status:"closing"})}),s!==Xd){const o={producerId:t.id,description:{sdp:n.sdp,type:n.type,target:gi.PUBLISHER}};try{const c=yield this.socketHandler.closeProducer(o),d={sdp:c==null?void 0:c.sdp,type:c==null?void 0:c.type};this.logger.info("producer::closed",{producer:q(V({},t),{status:"closed"})}),i({answer:d})}catch(c){this.logger.error("producer close error",c)}}this.producers.delete(t.id),e()})),t.on("trackended",()=>{this.logger.info("producer::trackended",{producer:q(V({},t),{status:"UNKNOWN"})})}),a(this,Bs).set(t.id,t)},Rh=new WeakSet,Bg=function(t){return u(this,null,function*(){try{return yield this.recvTransport.canConsume(),yield a(this,Hr).create(t)}catch(e){throw this.logger.error("Error in consume request",{error:e}),e}})},Mh=new WeakSet,Wg=function(t){t.on("close",e=>u(this,null,function*(){this.logger.debug("consumer closed",{consumer:{closureReason:e,id:t.id,kind:t.kind,appData:t.appData}}),a(this,On).delete(t.id),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:t.id})})),a(this,On).set(t.id,t),this.producerIdToConsumerIdMap.set(t.producerId,t.id),this.context.getValue("peerSessionStore").emit(P.NEW_CONSUMER,{id:t.id,appData:t.appData,peerId:t.peerId})};var Td,bd,wd,wo,xo,Uo,tl,rl,_o,Yt,Gr,jr,Tn,bn,ji,il,Ah,Uy,Dh,Fy,Oh,By,Nh,Wy;const Vh=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:n=.95,voiceAdaptationRate:s=.99,minEnergyThreshold:o=.005,maxEnergyThreshold:c=.2,energyRatioThreshold:d=1.5,noiseHistorySize:l=50}={}){g(this,Ah),g(this,Dh),g(this,Td,void 0),g(this,bd,void 0),g(this,wd,void 0),g(this,wo,void 0),g(this,xo,void 0),g(this,Uo,void 0),g(this,tl,void 0),g(this,rl,void 0),g(this,_o,void 0),g(this,Yt,void 0),g(this,Gr,void 0),g(this,jr,!1),g(this,Tn,0),g(this,bn,0),g(this,ji,[]),g(this,il,void 0),f(this,wo,t),f(this,Yt,t),f(this,Td,e),f(this,bd,r),f(this,wd,i),f(this,xo,n),f(this,Uo,s),f(this,tl,o),f(this,rl,c),f(this,_o,d),f(this,il,l),f(this,Gr,t/2)}get voiceDetected(){return a(this,jr)}processAudioChunk(t){var e,r;const i=U(e=Vh,Oh,By).call(e,t),n=U(r=Vh,Nh,Wy).call(r,t);return U(this,Ah,Uy).call(this,i),i/a(this,Gr)>a(this,_o)&&i>a(this,Yt)&&n>a(this,Td)?(f(this,Tn,a(this,Tn)+1),f(this,bn,a(this,wd)),a(this,Tn)>=a(this,bd)&&f(this,jr,!0)):(f(this,Tn,0),a(this,bn)>0?f(this,bn,a(this,bn)-1):a(this,jr)&&f(this,jr,!1),a(this,jr)||U(this,Dh,Fy).call(this,i)),{energy:i,isVoice:a(this,jr)}}reset(){f(this,jr,!1),f(this,Tn,0),f(this,bn,0),f(this,Yt,a(this,wo)),f(this,Gr,a(this,wo)/2),f(this,ji,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Yt),backgroundNoiseEnergy:a(this,Gr),energyRatioThreshold:a(this,_o)}}};let Lh=Vh;Td=new WeakMap,bd=new WeakMap,wd=new WeakMap,wo=new WeakMap,xo=new WeakMap,Uo=new WeakMap,tl=new WeakMap,rl=new WeakMap,_o=new WeakMap,Yt=new WeakMap,Gr=new WeakMap,jr=new WeakMap,Tn=new WeakMap,bn=new WeakMap,ji=new WeakMap,il=new WeakMap,Ah=new WeakSet,Uy=function(t){a(this,jr)?f(this,Yt,a(this,Uo)*a(this,Yt)+(1-a(this,Uo))*t):f(this,Yt,a(this,xo)*a(this,Yt)+(1-a(this,xo))*a(this,Gr)),f(this,Yt,Math.max(a(this,tl),Math.min(a(this,rl),a(this,Yt))))},Dh=new WeakSet,Fy=function(t){if(t<a(this,Yt)*1.2)if(a(this,ji).push(t),a(this,ji).length>a(this,il)&&a(this,ji).shift(),a(this,ji).length>=10){const e=[...a(this,ji)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,Gr,e[r])}else f(this,Gr,.95*a(this,Gr)+.05*t)},Oh=new WeakSet,By=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Nh=new WeakSet,Wy=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},g(Lh,Oh),g(Lh,Nh);var _d;class jg{constructor(e){m(this,"RNAudioSampleHandler"),g(this,_d,void 0),f(this,_d,e);const{RNAudioSampleHandlerImpl:r}=navigator;r==null||r.init().then(i=>{this.RNAudioSampleHandler=i}).catch(i=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",i)})}get logger(){return a(this,_d).getValue("logger")}get samples(){var e;const r=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(r),r}stop(){var e;(e=this.RNAudioSampleHandler)==null||e.destructor()}}_d=new WeakMap;var Id;class Hg{constructor(e){m(this,"audioContext"),m(this,"analyser"),g(this,Id,void 0),f(this,Id,e),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,Id).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(r){this.logger.error("AudioContextSampler: Failed to resume audio context",r)}const e=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(e),e}set audioTrack(e){const r=new MediaStream;r.addTrack(e),this.audioContext.createMediaStreamSource(r).connect(this.analyser)}}Id=new WeakMap;class kN{static setInterval(e,r=0,...i){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(e,r,...i):global.setInterval(e,r,...i)}static clearInterval(e){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(e):global.clearInterval(e)}static setTimeout(e,r=0,...i){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(e,r,...i):global.setTimeout(e,r,...i)}static clearTimeout(e){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(e):global.clearTimeout(e)}}const TN=60,bN=400;var Li,xi,qr,Cd,Gs,Fo,Ui,wn,Bo,$i,Hi,ii,xh,jy,Pd,Uh,Fh,Hy,Su,Gg;const nl=class{constructor(t,e){g(this,xh),g(this,Fh),g(this,Li,void 0),g(this,xi,void 0),g(this,qr,void 0),g(this,Cd,void 0),g(this,Gs,void 0),g(this,Fo,void 0),g(this,Ui,void 0),g(this,wn,void 0),g(this,Bo,void 0),g(this,$i,void 0),g(this,Hi,void 0),g(this,ii,void 0),this.reportRequest=e,f(this,$i,t),f(this,Fo,new Lh);const{isReactNative:r}=navigator;f(this,Hi,r?new jg(a(this,$i)):new Hg(a(this,$i))),f(this,ii,r?kN:wf)}get logger(){return a(this,$i).getValue("logger")}set producerId(t){f(this,qr,t)}set audioTrack(t){f(this,Cd,t),a(this,Hi)instanceof Hg&&(a(this,Hi).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,qr)}`),a(this,Li)&&a(this,ii).clearInterval(a(this,Li)),f(this,Li,a(this,ii).setInterval(()=>u(this,null,function*(){var t;if(!a(this,Cd)||!a(this,qr))return;const{energy:e}=U(this,xh,jy).call(this),r=U(t=nl,Pd,Uh).call(t,e);let i=.9;a(this,Bo)!==r&&a(this,Bo)?i=.9:r?i=.3:i=.5,f(this,Gs,(a(this,Gs)||0)*(1-i)+e*i)}),TN)),a(this,xi)&&a(this,ii).clearInterval(a(this,xi)),f(this,xi,a(this,ii).setInterval(U(this,Fh,Hy).bind(this),bN))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,qr)}`),a(this,Li)&&(a(this,ii).clearInterval(a(this,Li)),f(this,Li,void 0)),a(this,xi)&&(a(this,ii).clearInterval(a(this,xi)),f(this,xi,void 0))}catch{}a(this,Fo).reset(),a(this,Hi)instanceof jg&&a(this,Hi).stop()}};let Bh=nl;Li=new WeakMap,xi=new WeakMap,qr=new WeakMap,Cd=new WeakMap,Gs=new WeakMap,Fo=new WeakMap,Ui=new WeakMap,wn=new WeakMap,Bo=new WeakMap,$i=new WeakMap,Hi=new WeakMap,ii=new WeakMap,xh=new WeakSet,jy=function(){var t;const{samples:e}=a(this,Hi),{energy:r,isVoice:i}=a(this,Fo).processAudioChunk(e),n=U(t=nl,Su,Gg).call(t,r);return a(this,$i).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: producer: ${a(this,qr)}, energy: ${a(this,Gs)},
19
19
  slogScale: ${n}, isVoice: ${i}, minEnergy: ${a(this,Ui)},
20
20
  maxEnergy: ${a(this,wn)}`),n===-1/0||r<1e-6?{energy:0,isVoice:!1}:((!a(this,Ui)||n<a(this,Ui))&&f(this,Ui,n),(!a(this,wn)||n>a(this,wn))&&f(this,wn,n),{energy:(n-a(this,Ui))/(a(this,wn)-a(this,Ui))*10||0,isVoice:i})},Pd=new WeakSet,Uh=function(t){return t<5},Fh=new WeakSet,Hy=function(t=a(this,Gs)){var e;if(!a(this,qr)||!t){a(this,$i).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,qr)}`);return}const r={producerId:a(this,qr),energy:Math.round(t),silent:U(e=nl,Pd,Uh).call(e,t)};f(this,Bo,r.silent),this.reportRequest(r)},Su=new WeakSet,Gg=function(t){const e=Math.log10(t);return Math.round(e)},g(Bh,Pd),g(Bh,Su);const wN=(t=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const r=new window.MediaStreamTrackGenerator({kind:"audio"}),i=r.writable.getWriter(),n=48e3,s=128,o=1;let c=0,d=null;const l=()=>u(void 0,null,function*(){try{const p=new Float32Array(s*o),v=new window.AudioData({format:"f32",sampleRate:n,numberOfFrames:s,numberOfChannels:o,timestamp:c,data:p});c+=s/n*1e6,yield i.ready,yield i.write(v)}catch{d&&clearInterval(d),i.releaseLock(),r.writable.abort()}});d=window.setInterval(l,100);const h=new MediaStream([r]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),i.releaseLock(),r.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=t,h}catch{}const e=window.AudioContext||window.webkitAudioContext;if(e)try{const r=new e;if(!r||r.state!=="running"||!r.destination)return;const i=r.createOscillator();i.frequency.value=0,i.type="sine";const n=r.createGain();n.gain.value=0,i.connect(n);const s=r.createMediaStreamDestination();n.connect(s),i.start();const o=s.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=t,o):void 0}catch{return}},_N=(t=!1)=>{var e,r;const i=new MediaStream().getVideoTracks()[0],n=document.createElement("canvas");n.height=(e=i==null?void 0:i.getSettings().height)!=null?e:720,n.width=(r=i==null?void 0:i.getSettings().width)!=null?r:1280;const s=n.getContext("2d");s.fillStyle="black",s.fillRect(0,0,n.width,n.height),setInterval(()=>{s.fillStyle="black",s.fillRect(0,0,n.width,n.height)},1e3);const o=n.captureStream().getVideoTracks()[0];return Object.assign(o,{fakeTracks:"fakeTracks:fakeVideoTrack"}),o.enabled=t,o};var IN=Object.defineProperty,CN=Object.getOwnPropertyDescriptor,me=(t,e,r,i)=>{for(var n=i>1?void 0:i?CN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&IN(e,r,n),n};const Gt=["video/VP9","video/VP8"];var Vc,Lc,St,$,Qa,Qr,Dt,as,os,cs,xc,fr,_i,Xa,ds,ls,Ot,qt,un,us,Eu,qg,ku,$g,Tu,Jg,Uc,bu,wu,_u,Kg,Iu,zg,Cu,Yg,Pu,Qg,lt,Et,hs,Za,Ru,Xg,Mu,Zg,Au,ef;const Gy=(_u=class{constructor(t,e,r){g(this,un),g(this,Eu),g(this,ku),g(this,Tu),g(this,Uc),g(this,Iu),g(this,Cu),g(this,Pu),g(this,lt),g(this,hs),g(this,Ru),g(this,Mu),g(this,Au),m(this,"context"),m(this,"authToken"),m(this,"e2ee"),g(this,Vc,void 0),g(this,Lc,void 0),g(this,St,void 0),g(this,$,void 0),g(this,Qa,void 0),g(this,Qr,void 0),g(this,Dt,void 0),g(this,as,void 0),g(this,os,void 0),g(this,cs,void 0),g(this,xc,void 0),g(this,fr,null),g(this,_i,void 0),g(this,Xa,void 0),g(this,ds,void 0),g(this,ls,void 0),g(this,Ot,void 0),g(this,qt,void 0);var i,n;this.context=t;const{socket:s}=r;this.mediaJoined=!1,f(this,ds,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,ls,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Qr,e),f(this,St,s),f(this,as,!1),f(this,$,new EN(t,s,e)),f(this,Dt,a(this,$).events),f(this,_i,new Set),f(this,Ot,new Map),f(this,os,!1),f(this,cs,new dh(t.getValue("logger"))),e===Oe.CF&&f(this,qt,new Bh(this.context,a(this,$).socketHandler.audioActivity.bind(a(this,$).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,xc,fp(()=>u(this,null,function*(){if(!a(this,un,us).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,Lc),a(this,Vc),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(P.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,un,us).mediaJoined}set mediaJoined(t){a(this,un,us).mediaJoined=t}reset(){a(this,$).closeAllProducers(),a(this,$).closeAllConsumers(),a(this,Ot).clear(),a(this,_i).clear(),f(this,fr,null),a(this,cs).stop(),a(this,$).stopAllTransports(),a(this,$).reset(),f(this,cs,new dh)}joinRoom(t,e){return u(this,arguments,function*(r,i,n=!1,s=!1,o={}){a(this,un,us).mediaJoinAttempted=!0,f(this,as,!0),n&&this.reset();try{return yield a(this,cs).push(()=>U(this,Eu,qg).call(this,r,i,s,o),"joinRoom")}catch(c){return this.logger.error("Error in room joining process",{error:c}),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_FAILED),{roomJoined:!1}}})}initializeConnection(t,e){return u(this,arguments,function*(r,i,n=!1,s={}){return a(this,fr)?a(this,fr):(f(this,fr,(()=>u(this,null,function*(){try{yield U(this,Uc,bu).call(this,r,i,n,s)}catch(o){throw f(this,fr,null),o}}))()),a(this,fr))})}getConsumers(){return a(this,$).consumers}getProducers(){return a(this,$).producers}leaveRoom(){return u(this,null,function*(){a(this,$).stopAllTransports(),f(this,os,!1),a(this,un,us).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,St).sendMessagePromise(a(this,Dt).leaveRoom,wC.toBinary(t)).then(e=>{var r;(r=hP.fromBinary(e.payload))!=null&&r.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(e=>{this.logger.error("error on sending leave room request",{error:e})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()})}activatePeers(t){return u(this,null,function*(){return this.createConsumers(t)})}createConsumers(t){return u(this,null,function*(){return t.length===0?Promise.resolve():a(this,$).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,$).producerIdToConsumerIdMap.get(i.producerId);return n?(r.push(n),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);yield a(this,$).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const r=e==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,i=U(this,lt,Et).call(this,r);if(i){const h=yield i;if(a(this,$).producers.has(h)){const p=a(this,$).producers.get(h);if(!p.closed)return yield p.replaceTrack({track:t}),yield this.resumeWebcam(r),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const n=[e].concat(Gt.filter(h=>h!==e)),s=U(this,Au,ef).call(this,t,n),o=Ys(this.context,"disableSimulcast"),c=a(this,Qr)===Oe.CF?Z.ENABLE_CF_SIMULCAST:Z.ENABLE_HIVE_SIMULCAST;!o&&this.context.getValue("flagsmith").hasFeature(c)?(this.logger.info(`Simulcast enabled for SFU: ${a(this,Qr)}`),s.encodings=d1(this.context,t)):this.logger.info(`Simulcast disabled for webcam producer, SFU: ${a(this,Qr)}`),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(s.track.contentHint=this.context.getValue("flagsmith").getValue(Z.TRACK_HINT));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ot).delete(r)},l=a(this,$).createProducer(s,d);return U(this,hs,Za).call(this,r,l.then(h=>h.id)),l.then(h=>h.track)})}shareWebcam(t){return u(this,null,function*(){var e;if(t===void 0)return null;const r=(e=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:e.toString();if(r)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${r}`),this._shareWebcam(t,r);const i=Gt.filter(n=>{var s,o;return((o=(s=a(this,Qa).sender)==null?void 0:s.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===n))>=0&&a(this,ls).get(n).size>0});return i.length===0&&i.push(Gt[0]),yield Promise.all(i.map(n=>(this.logger.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(t,n)))),t})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:r}=t;if(e===void 0)return;const i={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ot).delete(Se.SCREENSHARE_VIDEO),a(this,Ot).delete(Se.SCREENSHARE_AUDIO)},s=a(this,$).createProducer(i,n);U(this,hs,Za).call(this,Se.SCREENSHARE_VIDEO,s.then(c=>c.id));let o;if(r){const c={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1,zeroRtpOnPause:a(this,Qr)!==Oe.CF},d=()=>{};o=a(this,$).createProducer(c,d),U(this,hs,Za).call(this,Se.SCREENSHARE_AUDIO,o.then(l=>l.id))}yield Promise.all([s,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new Ut("track undefined");const e=U(this,lt,Et).call(this,Se.MIC);if(e){const s=yield e;if(a(this,$).producers.has(s)){const o=a(this,$).producers.get(s);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,qt)&&(a(this,qt).audioTrack=t,a(this,qt).producerId=s,a(this,qt).start());return}yield a(this,$).closeProducer(s,{stopTrack:!1})}yield this.shareMic(t);return}const r=U(this,Mu,Zg).call(this,t),i=()=>{a(this,Ot).delete(Se.MIC)},n=a(this,$).createProducer(r,i);U(this,hs,Za).call(this,Se.MIC,n.then(s=>s.id)),yield n.then(s=>{a(this,qt)&&(a(this,qt).audioTrack=s.track,a(this,qt).producerId=s.id,a(this,qt).start())})}catch(e){throw new I(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield U(this,lt,Et).call(this,Se.MIC),r=a(this,$).producers.get(e);if(!r){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(r.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}r.pause(),(t=a(this,qt))==null||t.stop();const i={producerId:r.id,pause:!0};a(this,St).sendMessage(a(this,Dt).toggleProducer,fc.toBinary(i))})}pauseWebcam(){return u(this,null,function*(){const t=yield U(this,lt,Et).call(this,Se.WEBCAM),e=yield U(this,lt,Et).call(this,Se.WEBCAM_BACKUP),r=a(this,$).producers.get(t),i=a(this,$).producers.get(e);if(!r&&!i){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const n=s=>{const o={producerId:s.id,pause:!0};a(this,St).sendMessage(a(this,Dt).toggleProducer,fc.toBinary(o))};r&&(r.pause(),n(r)),i&&(i.pause(),n(i))})}resumeMic(){return u(this,null,function*(){const t=yield U(this,lt,Et).call(this,Se.MIC),e=a(this,$).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,St).sendMessage(a(this,Dt).toggleProducer,fc.toBinary(r))})}resumeWebcam(){return u(this,arguments,function*(t=Se.WEBCAM){const e=yield U(this,lt,Et).call(this,t),r=a(this,$).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,St).sendMessage(a(this,Dt).toggleProducer,fc.toBinary(i))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,r=yield U(this,lt,Et).call(this,e);U(this,Ru,Xg).call(this,e),r&&(yield a(this,$).closeProducer(r))})}disableMic(){return u(this,null,function*(){var t;const e=yield U(this,lt,Et).call(this,Se.MIC);e&&(yield a(this,$).closeProducer(e)),(t=a(this,qt))==null||t.stop(),a(this,Ot).delete(Se.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=yield U(this,lt,Et).call(this,Se.SCREENSHARE_VIDEO),e=yield U(this,lt,Et).call(this,Se.SCREENSHARE_AUDIO);t&&(yield a(this,$).closeProducer(t)),e&&(yield a(this,$).closeProducer(e)),a(this,_i).clear(),a(this,Ot).delete(Se.SCREENSHARE_VIDEO),a(this,Ot).delete(Se.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(t,e){return u(this,null,function*(){if(t){const r=yield U(this,lt,Et).call(this,Se.WEBCAM),i=yield U(this,lt,Et).call(this,Se.WEBCAM_BACKUP);yield a(this,$).closeProducer(r,{stopTrack:!1}),yield a(this,$).closeProducer(i,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=yield U(this,lt,Et).call(this,Se.SCREENSHARE_VIDEO);yield a(this,$).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}})}changeDisplayName(t,e){return u(this,null,function*(){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield a(this,$).socketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,$).socketHandler.kickPeer(e)}kickAll(){a(this,$).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,$).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,$).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,$).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,$).socketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield a(this,St).sendMessagePromise(a(this,Dt).globalPinPeer,UC.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,$).producers.get(t.producerId)&&a(this,_i).add(t.consumerPeerId),a(this,_i).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const r=t.map(i=>this.getConsumers().get(i));a(this,$).switchConsumersToLayer(r,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,St).on(a(this,Dt).peerProducerCreateBroadcast,({payload:t})=>{var e,r;if(this.mediaJoined)try{const{participantId:i,producerState:n}=jP.fromBinary(t);if(i===this.peerId)return;if(n!=null&&n.mimeType||(n.mimeType=n.kind===$r.AUDIO?"audio/opus":"video/VP8"),n.kind===$r.VIDEO&&!n.screenShare&&((r=(e=a(this,Qa).receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(s=>s.mimeType===Gt[0]))>=0&&a(this,ds).get(Gt[0]).has(i)&&n.mimeType!==Gt[0]){this.logger.warn(`Ignoring producer: ${n.producerId}`);return}this.logger.info(`producer created broadcast: ${i}, producer state: ${n}`),this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:i,producer:q(V({},n),{kind:n.kind===$r.AUDIO?"audio":"video",producingPeerId:i})})}catch(i){this.logger.error("error in peer-producer-create-broadcast",{error:i})}}),a(this,St).on(a(this,Dt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:s,screenShare:o}}=Wm.fromBinary(t);if(o)return;const c=i===$r.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${s}, kind:${c}, paused:${n} payload: ${JSON.stringify(Wm.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(c==="audio"?P.MUTE_SELF:P.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(P.PRODUCER_TOGGLE,{peerId:e,producerId:s,paused:n,kind:c}),Array.from(this.getConsumers().values()).filter(d=>d.producerId===s).forEach(d=>{d.kind==="video"&&n||d.paused!==n&&(this.logger.debug(`consumer state mismatched for ${d.id}. updating consumer pause state ${d.paused} to ${n}`),n?(d.pause(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_PAUSED,{id:d.id})):(d.resume(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_RESUMED,{id:d.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,St).on(a(this,Dt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=$u.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,_i).delete(e),a(this,$).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(P.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,St).on(a(this,Dt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=qP.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(P.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=a(this,$).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),a(this,$).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,$).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:i})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,St).on(a(this,Dt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,as)&&!a(this,os)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_DISCONNECTED),a(this,xc).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,$).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(P.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(a(this,$).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(P.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}handlePeerCapabilities(t,e){var r,i,n,s;for(let o=0;o<=Gt.length;o+=1){const c=Gt[o];if(((i=(r=e==null?void 0:e.receiver)==null?void 0:r.video)==null?void 0:i.codecs.findIndex(d=>d.mimeType===c))>=0||o===Gt.length-1){a(this,ls).get(c).add(t);break}}for(let o=0;o<=Gt.length;o+=1){const c=Gt[o];if(((s=(n=e==null?void 0:e.sender)==null?void 0:n.video)==null?void 0:s.codecs.findIndex(d=>d.mimeType===c))>=0||o===Gt.length-1){a(this,ds).get(c).add(t);break}}}handlePeerLeaving(t){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(a(this,ds).forEach(e=>e.delete(t)),a(this,ls).forEach((e,r)=>{e.delete(t),!(e.size!==0||r===Gt[0])&&this.disableWebcam(r)}))}},Vc=new WeakMap,Lc=new WeakMap,St=new WeakMap,$=new WeakMap,Qa=new WeakMap,Qr=new WeakMap,Dt=new WeakMap,as=new WeakMap,os=new WeakMap,cs=new WeakMap,xc=new WeakMap,fr=new WeakMap,_i=new WeakMap,Xa=new WeakMap,ds=new WeakMap,ls=new WeakMap,Ot=new WeakMap,qt=new WeakMap,un=new WeakSet,us=function(){return this.context.getValue("connectionHandler")},Eu=new WeakSet,qg=function(t,e,r,i){return u(this,null,function*(){f(this,Lc,t);try{return a(this,fr)?yield a(this,fr):yield U(this,Uc,bu).call(this,t,e,r,i),U(this,Tu,Jg).call(this,e),{roomJoined:yield U(this,ku,$g).call(this)}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1}}finally{f(this,fr,null)}})},ku=new WeakSet,$g=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,$).socketHandler.notifySelfJoinComplete();return f(this,Vc,t.roomUuid),f(this,os,!0),f(this,as,!1),!0}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},Tu=new WeakSet,Jg=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:q(V({},Ie.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(e)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Uc=new WeakSet,bu=function(t,e,r,i){return u(this,null,function*(){var n,s;try{(s=a(this,Xa))!=null||f(this,Xa,U(n=Gy,wu,Kg).call(n));const o=U(this,Iu,zg).call(this);yield U(this,Cu,Yg).call(this,t,e,r,o),yield a(this,$).setupTransports({send:!0,recv:!0}),yield U(this,Pu,Qg).call(this,i)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},wu=new WeakSet,Kg=function(){const{ipInfo:t}=pt();if(!(t!=null&&t.loc))return;const[e,r]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:r}},Iu=new WeakSet,zg=function(){var t;const e=(t=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),r=oN(e);return f(this,Qa,r),r},Cu=new WeakSet,Yg=function(t,e,r,i){return u(this,null,function*(){yield Ry((n,s)=>u(this,null,function*(){if(!a(this,St).isConnected){s(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{yield a(this,$).socketHandler.joinRoom(e,t,i,r,a(this,Xa))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:this.context.getValue("flagsmith").hasFeature(Z.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3})})},Pu=new WeakSet,Qg=function(t){return u(this,null,function*(){if(!(a(this,Qr)===Oe.HIVE||!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===G.Allowed&&e.push(this.shareWebcam(_N(!1))),t.canProduceAudio===G.Allowed){const r=wN(!1);r&&e.push(this.shareMic(r))}e.length>0&&(yield Promise.all(e))}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}})},lt=new WeakSet,Et=function(t){return a(this,Ot).get(t)},hs=new WeakSet,Za=function(t,e){return a(this,Ot).set(t,e)},Ru=new WeakSet,Xg=function(t){return a(this,Ot).delete(t)},Mu=new WeakSet,Zg=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,Qr)!==Oe.CF}},Au=new WeakSet,ef=function(t,e){return{track:t,codecOptions:e?e.map(r=>({name:r.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},g(_u,wu),_u);let le=Gy;me([k.trace("MediaNodeClient.reset",{country:k.location.country})],le.prototype,"reset",1);me([k.trace("MediaNodeClient.joinRoom")],le.prototype,"joinRoom",1);me([k.trace("MediaNodeClient.leaveRoom")],le.prototype,"leaveRoom",1);me([k.trace("MediaNodeClient.activatePeers")],le.prototype,"activatePeers",1);me([k.trace("MediaNodeClient.createConsumers")],le.prototype,"createConsumers",1);me([k.trace("MediaNodeClient.closeConsumers")],le.prototype,"closeConsumers",1);me([k.trace("MediaNodeClient._shareWebcam")],le.prototype,"_shareWebcam",1);me([k.trace("MediaNodeClient.shareWebcam")],le.prototype,"shareWebcam",1);me([k.trace("MediaNodeClient.shareScreen")],le.prototype,"shareScreen",1);me([k.trace("MediaNodeClient.shareMic")],le.prototype,"shareMic",1);me([k.trace("MediaNodeClient.pauseMic")],le.prototype,"pauseMic",1);me([k.trace("MediaNodeClient.pauseWebcam")],le.prototype,"pauseWebcam",1);me([k.trace("MediaNodeClient.resumeMic")],le.prototype,"resumeMic",1);me([k.trace("MediaNodeClient.resumeWebcam")],le.prototype,"resumeWebcam",1);me([k.trace("MediaNodeClient.disableWebcam")],le.prototype,"disableWebcam",1);me([k.trace("HiveClient.disableMic")],le.prototype,"disableMic",1);me([k.trace("HiveClient.disableScreenShare")],le.prototype,"disableScreenShare",1);me([k.trace("MediaNodeClient.muteSelf")],le.prototype,"muteSelf",1);me([k.trace("MediaNodeClient.resetVideoProducers")],le.prototype,"resetVideoProducers",1);me([k.trace("MediaNodeClient.changeDisplayName")],le.prototype,"changeDisplayName",1);me([k.trace("MediaNodeClient.kickPeer")],le.prototype,"kick",1);me([k.trace("MediaNodeClient.kickAllPeers")],le.prototype,"kickAll",1);me([k.trace("MediaNodeClient.muteAll")],le.prototype,"muteAll",1);me([k.trace("MediaNodeClient.muteAllVideo")],le.prototype,"muteAllVideo",1);me([k.trace("MediaNodeClient.disableAudio")],le.prototype,"disableAudio",1);me([k.trace("MediaNodeClient.disableVideo")],le.prototype,"disableVideo",1);me([k.trace("MediaNodeClient.pinPeer")],le.prototype,"pinPeer",1);me([k.trace("MediaNodeClient.validateScreenShare")],le.prototype,"validateScreenShare",1);function qy(t,e,r){const i=t.getValue("roomNodeClient");if(i){if(i)return i;throw new Error("Room node client already set up.")}const n=new le(t,e,r);return t.setValue("roomNodeClient",n),n}function $y(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch{t.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var PN=Object.defineProperty,RN=Object.getOwnPropertyDescriptor,Jn=(t,e,r,i)=>{for(var n=i>1?void 0:i?RN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&PN(e,r,n),n},ps,Lr,ie,Nt,$t,tf;const Jy=(tf=class{constructor(t,e,r,i){g(this,Nt),m(this,"self"),m(this,"authToken"),g(this,ps,void 0),m(this,"viewType"),g(this,Lr,void 0),g(this,ie,void 0);const{socket:n}=r,s=t.getValue("authToken");this.self=e,f(this,ie,t),this.viewType=i,this.authToken=s,f(this,ps,n),f(this,Lr,r),e.config.viewType!==Ft.Chat&&this.setupEvents()}get peerId(){return a(this,ie).getValue("peerId")}get telemetry(){return a(this,ie).getValue("telemetry")}get logger(){return a(this,ie).getValue("logger")}get mediaJoined(){return a(this,ie).getValue("connectionHandler").mediaJoined}static init(t,e,r,i,n){return u(this,null,function*(){const s=pt(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield at.__init__(t,r,i,n,n.name,c);t.setValue("self",d);const l=t.getValue("logger");if(navigator.product!=="ReactNative"){const h=!t.getValue("flagsmith").hasFeature(Z.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const p=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),t.getValue("callstats").devices("AUDIO",p==null?void 0:p.filter(v=>v.kind==="audioinput")),t.getValue("callstats").devices("VIDEO",p==null?void 0:p.filter(v=>v.kind==="videoinput")),t.getValue("callstats").devices("SPEAKER",p==null?void 0:p.filter(v=>v.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield t.getValue("callstats").initialize({peerId:o,engineName:Ie.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:t.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Gv(t),skipConnectivityChecks:h}),l.info("Callstats:: initialized")}catch(v){l.error("Callstats:: initialization failed",{error:v})}}),0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new Jy(t,d,e,n.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:r,permissions:i,audioEnabled:n,videoEnabled:s,screenShareEnabled:o,screenShareTracks:c}=this.self;if(i.canProduceAudio===G.Allowed&&n)try{yield a(this,Nt,$t).shareMic(e),this.self.audioEnabled||a(this,Nt,$t).pauseMic()}catch{this.self.disableAudio()}if(i.canProduceVideo===G.Allowed&&s)try{const d=yield a(this,Nt,$t).shareWebcam(r);d&&d.id!==r.id&&a(this,ie).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&(yield a(this,Nt,$t).shareWebcam(d)),this.self.videoEnabled||a(this,Nt,$t).pauseWebcam()}catch{this.self.disableVideo()}if(i.canProduceScreenshare===G.Allowed&&o)try{yield(t=a(this,Nt,$t))==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(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){a(this,ie).getValue("callstats").callEnded(),a(this,Nt,$t).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){a(this,ie).getValue("peerSessionStore").on(P.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),a(this,ie).getValue("peerSessionStore").on(P.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ie).getValue("peerSessionStore").on(P.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ie).getValue("peerSessionStore").on(P.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ie).getValue("peerSessionStore").on(P.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),a(this,ie).getValue("peerSessionStore").on(P.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&a(this,ie).getValue("flagsmith").hasFeature(Z.REFRESH_ID_ON_DISCONNECTION)&&(e=Ln()),a(this,ps).updateURL(e),a(this,ie).getValue("telemetry").resetPeerId(e),pt().setHeader("dyte-tracing-id",e),ui.remapContext(e,a(this,ie)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,ie).getValue("peerSessionStore").on(P.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Lr).on(F.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Lr).on(Kc.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&a(this,ie).getValue("peerSessionStore").emit(P.UPDATE_PERMISSIONS,e.patch)})}),a(this,Lr).on(F.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Lr).on(F.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Lr).on(F.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,ie).getValue("peerSessionStore").onAsync(P.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,ie).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:r,scoreStats:i})=>{var n;const s=(n=r==null?void 0:r.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:i})}),a(this,ie).getValue("peerSessionStore").on(P.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),a(this,ie).getValue("callstats").audioOff())})),a(this,ie).getValue("peerSessionStore").on(P.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),a(this,ie).getValue("callstats").videoOff())})),a(this,ie).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,ie).getValue("peerSessionStore").on(P.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield a(this,Lr).joinRoom(this.self);a(this,Lr).socket.flush();const r=kp(e.stageType);if(a(this,ie).setValue("stageStatus",r,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),a(this,ie).notify("stageStatus")}catch(e){throw this.logger.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,r;if(this.logger.info(`Leaving room with state: ${t}`),(e=a(this,ie).getValue("roomSocketHandler"))==null||e.cleanup(),t==="rejected"){this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),a(this,ie).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),a(this,ie).notify("stageStatus");try{(r=a(this,ps))==null||r.disconnect()}catch{this.logger.error("SelfController::leaveRoom::socketDisconnect")}$y(a(this,ie)),this.self.roomState=t,this.self.emit("roomLeft",{state:t}),this.logger.info(`roomLeft event emitted with state: ${t}`)})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,r;const{peerId:i,viewType:n,meetingId:s,stageStatus:o,roomNodeOptions:c}=a(this,ie).getAllValues(),{sfu:d}=c;try{if(n===Ft.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}qy(a(this,ie),d,{socket:a(this,ps),peerId:i})}const{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:p}=this.self.permissions,{roomJoined:v}=(r=yield(e=a(this,Nt,$t))==null?void 0:e.joinRoom(this.self.name,s,t,t,{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:p}))!=null?r:{};if(!v)return;o==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:l}),new I("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=a(this,ie).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===Ft.Webinar)&&a(this,Nt,$t)&&(a(this,Nt,$t).mediaJoined&&t!=="disconnected"&&(yield a(this,Nt,$t).leaveRoom()),!(t==="stageLeft"&&e===Ft.Livestream)&&(a(this,Nt,$t).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()})}},ps=new WeakMap,Lr=new WeakMap,ie=new WeakMap,Nt=new WeakSet,$t=function(){return a(this,ie).getValue("roomNodeClient")},tf);let Zi=Jy;Jn([k.trace("SelfController.resetSelf")],Zi.prototype,"resetSelf",1);Jn([k.trace("SelfController.setupEvents")],Zi.prototype,"setupEvents",1);Jn([k.trace("SelfController.joinRoom")],Zi.prototype,"joinRoom",1);Jn([k.trace("SelfController.leaveRoom")],Zi.prototype,"leaveRoom",1);Jn([k.trace("SelfController.joinMediaRoom")],Zi.prototype,"joinMediaRoom",1);Jn([k.trace("SelfController.leaveMediaRoom")],Zi.prototype,"leaveMediaRoom",1);Jn([k.trace("SelfController.init")],Zi,"init",1);var Rd;class MN{constructor(e){g(this,Rd,void 0),f(this,Rd,e)}on(e,r){let i;e===F.roomPeerCount?i=Gm.fromBinary.bind(Gm):i=tg.fromBinary.bind(tg),a(this,Rd).on(e,({payload:n})=>{if(e===F.roomPeerCount&&!n)return;const s=i(n);r(s)})}}Rd=new WeakMap;var Md,Ad;class AN{constructor(e,r){g(this,Md,void 0),g(this,Ad,void 0),f(this,Md,r),f(this,Ad,e)}get logger(){return a(this,Ad).getValue("logger")}on(e,r){let i,n;switch(e){case F.transcript:{i=Kl.fromBinary.bind(Kl),n=Kl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Md).on(e,({payload:s})=>{let o=n;try{o=i(s)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return r(o)})}}Md=new WeakMap,Ad=new WeakMap;var DN=Object.defineProperty,ON=Object.getOwnPropertyDescriptor,Op=(t,e,r,i)=>{for(var n=i>1?void 0:i?ON(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&DN(e,r,n),n},Fi,Io;class Dl{constructor(e,r){g(this,Fi,void 0),g(this,Io,void 0),f(this,Fi,r),f(this,Io,e)}get logger(){return a(this,Io).getValue("logger")}get telemetry(){return a(this,Io).getValue("telemetry")}getPolls(){return a(this,Fi).sendMessagePromise(si.getPolls)}createPoll(e,r,i=!1,n=!1){const s={anonymous:i,hideVotes:n,question:e,options:r};return a(this,Fi).sendMessage(si.createPoll,OD.toBinary(s))}votePoll(e,r){const i={index:r,pollId:e};return a(this,Fi).sendMessage(si.votePoll,VD.toBinary(i))}on(e,r){let i,n;switch(e){case si.updatePoll:case si.createPoll:case si.votePoll:{i=eu.fromBinary.bind(eu),n=eu.create();break}}a(this,Fi).on(e,({payload:s})=>{let o=n;try{o=i(s)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return r(o)})}removeListeners(e){a(this,Fi).removeListeners(e)}}Fi=new WeakMap,Io=new WeakMap;Op([k.trace("PollSocketHandler.getPolls")],Dl.prototype,"getPolls",1);Op([k.trace("PollSocketHandler.createPoll")],Dl.prototype,"createPoll",1);Op([k.trace("PollSocketHandler.votePoll")],Dl.prototype,"votePoll",1);var NN=Object.defineProperty,VN=Object.getOwnPropertyDescriptor,LN=(t,e,r,i)=>{for(var n=i>1?void 0:i?VN(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&NN(e,r,n),n},or;class Ky{constructor(e,r){m(this,"socket"),g(this,or,void 0),f(this,or,e),this.socket=r,this.handleSocketEvents(),a(this,or).setValue("roomSocketHandler",this)}get telemetry(){return a(this,or).getValue("telemetry")}get logger(){return a(this,or).getValue("logger")}cleanup(){var e;try{(e=this.socket)==null||e.disconnect()}catch{this.logger.error("roomSocketHandler::cleanup")}}joinRoom(e){return u(this,null,function*(){var r;this.socket.joinAttempted=!0;const i={capabilities:[],peer:{displayName:(r=e.name)!=null?r:"Participant",customParticipantId:e.customParticipantId,peerId:e.id,userId:e.userId,displayPictureUrl:e.picture,waitlisted:!1},roomUuid:""},n=this.socket.sendMessagePromise(F.joinRoom,ER.toBinary(i));try{const{peer:s}=fs.fromBinary((yield n).payload);a(this,or).getValue("connectionHandler").socketJoined=!0,a(this,or).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_ROOM_JOINED,{peer:s});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return a(this,or).getValue("peerSessionStore").emit(P.ROOM_STATE,d),a(this,or).getValue("peerSessionStore").emit(P.SOCKET_PEERS,l),{peer:s}}catch(s){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:s}),new I("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,s)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return nM.fromBinary((yield this.socket.sendMessagePromise(F.getAllAddedParticipants)).payload).participants.map(e=>{var r=e,{id:i}=r,n=pl(r,["id"]);return q(V({},n),{userId:i})})}catch{return[]}})}getRoomPeers(e,r,i){return u(this,null,function*(){let n;try{const s={seachQuery:e,limit:r,offset:i},o=yield this.socket.sendMessagePromise(F.getRoomPeersInfo,lR.toBinary(s));n=zl.fromBinary(o.payload)}catch(s){this.logger.error("getRoomPeers::binary_decode_error",{error:s})}return n})}getRoomPeersNonPaginated(){return u(this,null,function*(){let e;try{const r=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=zl.fromBinary(r.payload)}catch(r){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:r})}return e})}getStagePeers(){return u(this,null,function*(){let e;try{const r=yield this.socket.sendMessagePromise(F.getRoomPeersInfo);e=zl.fromBinary(r.payload)}catch(r){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:r})}return e})}getPeerInfo(e){return u(this,null,function*(){let r;try{const i=yield this.socket.sendMessagePromise(F.getPeerInfo,ty.toBinary({peerId:e}));r=fs.fromBinary(i.payload)}catch(i){this.logger.error("getPeerInfo::binary_decode_error",{error:i})}return r})}getRoomState(){return u(this,null,function*(){let e=qm.create();try{const r=yield this.socket.sendMessagePromise(F.getRoomInfo);e=qm.fromBinary(r.payload)}catch(r){this.logger.error("getRoomState::binary_decode_error",{error:r})}return e})}getRoomStageState(){return u(this,null,function*(){let e=zm.create();try{const r=yield this.socket.sendMessagePromise(F.getRoomStageState);e=zm.fromBinary(r.payload)}catch(r){this.logger.error("getRoomStageState::binary_decode_error",{error:r})}return e})}broadcastMessage(e,r){return u(this,null,function*(){const i={type:e,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(F.broadcastMessage,Ea.toBinary(i))})}broadcastToMeetings(e,r,i){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:r,broadcastType:1};return this.socket.sendMessagePromise(F.broadcastToEntity,Ea.toBinary(n))})}broadcastToPeers(e,r,i){return u(this,null,function*(){const n={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:r,broadcastType:0};return this.socket.sendMessage(F.broadcastToEntity,Ea.toBinary(n))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(F.leaveRoom,TR.toBinary({}))})}kick(e){return u(this,null,function*(){const r={peerIds:[e]};this.socket.sendMessage(F.kick,iy.toBinary(r))})}kickAll(e=!1){return u(this,null,function*(){const r={propagateKickAcrossRooms:e};this.socket.sendMessage(F.kickAll,Xv.toBinary(r))})}getWaitingRoomRequests(){this.socket.sendMessage(F.getWaitingRoomRequests)}acceptWaitingRoomRequest(e){const r={userIds:e};this.socket.sendMessage(F.acceptWaitingRoomRequests,lM.toBinary(r))}rejectWaitingRoomRequest(e){const r={userIds:e};this.socket.sendMessage(F.denyWaitingRoomRequests,hM.toBinary(r))}updatePermissions(e,r){return u(this,null,function*(){const i={updatePeersPresets:[]};return e.forEach(n=>{i.updatePeersPresets.push({userIds:n,patch:r})}),this.socket.sendMessagePromise(Kc.updateUserPreset,WM.toBinary(i))})}handleSocketEvents(){this.socket.on(F.broadcastMessage,({payload:e})=>{try{const r=Ea.fromBinary(e);a(this,or).getValue("peerSessionStore").emit(P.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(r.payload)),type:r.type,timestamp:r.timestamp})}catch(r){this.logger.error("failed to decode broadcast message:",r)}}),this.socket.on(F.broadcastToEntity,({payload:e})=>{try{const r=Ea.fromBinary(e);a(this,or).getValue("peerSessionStore").emit(P.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(r.payload)),type:r.type,timestamp:r.timestamp})}catch(r){this.logger.error("failed to decode peer broadcast message:",r)}})}on(e,r){let i,n;switch(e){case F.joinRoom:case F.leaveRoom:case F.kick:case F.kickAll:{i=fs.fromBinary.bind(fs),n=fs.create();break}case F.getWaitingRoomRequests:{i=(s,o)=>s?Km.fromBinary(s,o):{requests:[]},n=Km.create();break}case F.recordingPaused:case F.recordingStarted:case F.recordingStopped:{i=ng.fromBinary.bind(ng);break}case Kc.updateUserPreset:{i=Ym.fromBinary.bind(Ym);break}case Ir.peerJoinedBroadcast:case dr.peerJoinedBroadcast:{i=Fm.fromBinary.bind(Fm);break}case Ir.selfJoinComplete:case dr.selfJoinComplete:{i=qu.fromBinary.bind(qu);break}case Ir.globalPeerPinBroadcast:case dr.globalPeerPinBroadcast:{i=jm.fromBinary.bind(jm);break}case Ir.selectedPeer:case dr.selectedPeer:{i=Gu.fromBinary.bind(Gu);break}case Ir.selectedPeerDiff:case dr.selectedPeerDiff:{i=Um.fromBinary.bind(Um);break}case Ir.leaveRoom:case dr.leaveRoom:{i=$u.fromBinary.bind($u);break}}this.socket.on(e,({payload:s})=>{let o=n;if(!i)return r(void 0);try{o=i(s)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return r(o)})}getUserPermissions(e){return u(this,null,function*(){const r={userIds:[e]};try{const i=yield this.socket.sendMessagePromise(Kc.getUserPresets,NM.toBinary(r)),n=UM.fromBinary(i.payload).peerPresets[0],s=new TextDecoder().decode(n.preset),o=JSON.parse(s).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(i){throw this.logger.error("Error in getting user preset",{error:i}),i}})}}or=new WeakMap;LN([k.trace("RoomSocketHandler.joinRoom")],Ky.prototype,"joinRoom",1);var zt;class xN{constructor(e){g(this,zt,void 0),f(this,zt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield a(this,zt).sendMessagePromise(F.getStageRequests);return e?Zl.fromBinary(e):{stageRequests:[]}})}requestAccess(){a(this,zt).sendMessage(F.requestStageAccess)}cancelRequestAccess(){a(this,zt).sendMessage(F.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const r={userIds:e};a(this,zt).sendMessage(F.grantStageAccess,bD.toBinary(r))})}denyAccess(e){return u(this,null,function*(){const r={userIds:e};a(this,zt).sendMessage(F.denyStageAccess,_D.toBinary(r))})}joinStage(){return a(this,zt).sendMessagePromise(F.joinStage,void 0,void 0,F.peerStageStatusUpdate)}leaveStage(e){const r={userIds:[e]};return a(this,zt).sendMessagePromise(F.leaveStage,ig.toBinary(r),void 0,F.peerStageStatusUpdate)}kick(e){const r={userIds:e};return a(this,zt).sendMessagePromise(F.leaveStage,ig.toBinary(r))}on(e,r){let i;switch(e){case F.grantStageAccess:case F.denyStageAccess:{i=void 0;break}case F.getStagePeers:{i=rg.fromBinary.bind(rg);break}case F.getStageRequests:case F.requestStageAccess:case F.cancelStageRequest:{i=Zl.fromBinary.bind(Zl);break}case F.peerStageStatusUpdate:{i=Hm.fromBinary.bind(Hm);break}}a(this,zt).on(e,({payload:n,id:s})=>{if(!n||!i)return r(void 0,s);const o=i(n);return r(o,s)})}getPeerInfo(e){return u(this,null,function*(){const r=yield a(this,zt).sendMessagePromise(F.getPeerInfo,ty.toBinary({peerId:e}));return fs.fromBinary(r.payload)})}}zt=new WeakMap;var it,Dd;class UN{constructor(e,r){g(this,it,void 0),g(this,Dd,void 0),f(this,it,r),f(this,Dd,e)}get logger(){return a(this,Dd).getValue("logger")}addPlugin(e,r){a(this,it).sendMessage(J.addPlugin,BA.toBinary({pluginId:e,staggered:r}))}removePlugin(e){a(this,it).sendMessage(J.removePlugin,jA.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,it).sendMessagePromise(J.getPlugins);return e?uD.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,r,i){const n={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,it).sendMessage(J.customPluginEventToRoom,XA.toBinary(n),i)}customPluginEventToPeers(e,r,i,n){const s={pluginId:e,peerIds:r,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,it).sendMessage(J.customPluginEventToPeers,eD.toBinary(s),n)}enablePluginForRoom(e,r){a(this,it).sendMessage(J.enablePluginForRoom,GA.toBinary({pluginId:e}),r)}enablePluginForPeers(e,r,i){a(this,it).sendMessage(J.enablePluginForPeers,KA.toBinary({pluginId:e,peerIds:r}),i)}disablePluginForRoom(e,r){a(this,it).sendMessage(J.disablePluginForRoom,$A.toBinary({pluginId:e}),r)}disablePluginForPeers(e,r,i){a(this,it).sendMessage(J.disablePluginForPeers,YA.toBinary({pluginId:e,peerIds:r}),i)}storeInsertKeys(e,r,i,n){const s={pluginId:e,storeName:r,insertKeys:i.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,it).sendMessage(J.storeInsertKeys,Qm.toBinary(s),n)}storeGetKeys(e,r,i,n){const s={pluginId:e,storeName:r,getKeys:i.map(o=>({storeKey:o.key}))};a(this,it).sendMessage(J.storeGetKeys,nD.toBinary(s),n)}storeDeleteKeys(e,r,i,n){const s={pluginId:e,storeName:r,deleteKeys:i.map(o=>({storeKey:o.key}))};a(this,it).sendMessage(J.storeDeleteKeys,aD.toBinary(s),n)}storeDelete(e,r,i){a(this,it).sendMessage(J.storeDelete,cD.toBinary({pluginId:e,storeName:r}),i)}getPluginDataOld(e,r){this.logger.info("getPluginDataOld",{plugin:{id:e,storeName:r}})}storePluginDataOld(e,r,i){const n={pluginId:e,storeName:r,insertKeys:[{storeKey:i.key,payload:new TextEncoder().encode(JSON.stringify(i))}]};a(this,it).sendMessage(J.storeInsertKeys,Qm.toBinary(n))}on(e,r){let i;switch(e){case J.addPlugin:case J.enablePluginForPeers:case J.enablePluginForRoom:{i=Yu.fromBinary.bind(Yu);break}case J.removePlugin:case J.disablePluginForPeers:case J.disablePluginForRoom:{i=Xm.fromBinary.bind(Xm);break}case J.customPluginEventToPeers:case J.customPluginEventToRoom:{i=eg.fromBinary.bind(eg);break}case J.storeInsertKeys:case J.storeGetKeys:case J.storeDeleteKeys:case J.storeDelete:{i=Zm.fromBinary.bind(Zm);break}}a(this,it).on(e,({payload:n,id:s})=>{const o=i(n);return r(o,s)})}}it=new WeakMap,Dd=new WeakMap;var FN=Object.defineProperty,BN=(t,e,r)=>e in t?FN(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,WN=(t,e,r)=>(BN(t,typeof e!="symbol"?e+"":e,r),r),Np=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},N=(t,e,r)=>(Np(t,e,"read from private field"),r?r.call(t):e.get(t)),we=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},de=(t,e,r,i)=>(Np(t,e,"write to private field"),i?i.call(t,r):e.set(t,r),r),Re=(t,e,r)=>(Np(t,e,"access private method"),r),sl={},jN={get exports(){return sl},set exports(t){sl=t}},qs=typeof Reflect=="object"?Reflect:null,rf=qs&&typeof qs.apply=="function"?qs.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Od;qs&&typeof qs.ownKeys=="function"?Od=qs.ownKeys:Object.getOwnPropertySymbols?Od=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Od=function(t){return Object.getOwnPropertyNames(t)};function HN(t){console&&console.warn&&console.warn(t)}var zy=Number.isNaN||function(t){return t!==t};function pe(){pe.init.call(this)}jN.exports=pe;sl.once=JN;pe.EventEmitter=pe;pe.prototype._events=void 0;pe.prototype._eventsCount=0;pe.prototype._maxListeners=void 0;var nf=10;function Ol(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(pe,"defaultMaxListeners",{enumerable:!0,get:function(){return nf},set:function(t){if(typeof t!="number"||t<0||zy(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");nf=t}});pe.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};pe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||zy(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 Yy(t){return t._maxListeners===void 0?pe.defaultMaxListeners:t._maxListeners}pe.prototype.getMaxListeners=function(){return Yy(this)};pe.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var i=t==="error",n=this._events;if(n!==void 0)i=i&&n.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 o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var c=n[t];if(c===void 0)return!1;if(typeof c=="function")rf(c,this,e);else for(var d=c.length,l=tS(c,d),r=0;r<d;++r)rf(l[r],this,e);return!0};function Qy(t,e,r,i){var n,s,o;if(Ol(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),n=Yy(t),n>0&&o.length>n&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=o.length,HN(c)}return t}pe.prototype.addListener=function(t,e){return Qy(this,t,e,!1)};pe.prototype.on=pe.prototype.addListener;pe.prototype.prependListener=function(t,e){return Qy(this,t,e,!0)};function GN(){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 Xy(t,e,r){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},n=GN.bind(i);return n.listener=r,i.wrapFn=n,n}pe.prototype.once=function(t,e){return Ol(e),this.on(t,Xy(this,t,e)),this};pe.prototype.prependOnceListener=function(t,e){return Ol(e),this.prependListener(t,Xy(this,t,e)),this};pe.prototype.removeListener=function(t,e){var r,i,n,s,o;if(Ol(e),i=this._events,i===void 0)return this;if(r=i[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(n=-1,s=r.length-1;s>=0;s--)if(r[s]===e||r[s].listener===e){o=r[s].listener,n=s;break}if(n<0)return this;n===0?r.shift():qN(r,n),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,o||e)}return this};pe.prototype.off=pe.prototype.removeListener;pe.prototype.removeAllListeners=function(t){var e,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[t]),this;if(arguments.length===0){var n=Object.keys(r),s;for(i=0;i<n.length;++i)s=n[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=r[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 Zy(t,e,r){var i=t._events;if(i===void 0)return[];var n=i[e];return n===void 0?[]:typeof n=="function"?r?[n.listener||n]:[n]:r?$N(n):tS(n,n.length)}pe.prototype.listeners=function(t){return Zy(this,t,!0)};pe.prototype.rawListeners=function(t){return Zy(this,t,!1)};pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):eS.call(t,e)};pe.prototype.listenerCount=eS;function eS(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}pe.prototype.eventNames=function(){return this._eventsCount>0?Od(this._events):[]};function tS(t,e){for(var r=new Array(e),i=0;i<e;++i)r[i]=t[i];return r}function qN(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function $N(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function JN(t,e){return new Promise(function(r,i){function n(o){t.removeListener(e,s),i(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",n),r([].slice.call(arguments))}rS(t,e,s,{once:!0}),e!=="error"&&KN(t,n,{once:!0})})}function KN(t,e,r){typeof t.on=="function"&&rS(t,"error",e,r)}function rS(t,e,r,i){if(typeof t.on=="function")i.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function n(s){i.once&&t.removeEventListener(e,n),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class zN extends y{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 sf=new zN;class iS{static encode(e){return sf.toBinary(e)}static decode(e){return sf.fromBinary(new Uint8Array(e))}}function YN(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Bi;class QN{constructor(e={}){WN(this,"opts"),we(this,Bi,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},de(this,Bi,0)}wait(){return u(this,null,function*(){de(this,Bi,N(this,Bi)+1);const e=YN(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*EE(2,N(this,Bi))));yield new Promise(r=>{setTimeout(r,e)})})}getAttempts(){return N(this,Bi)}reset(){de(this,Bi,0)}}Bi=new WeakMap;const Ii={debug:0,info:1,warn:2,error:3};var _n,In;class XN{constructor(e){we(this,_n,void 0),we(this,In,void 0),de(this,_n,console),de(this,In,e)}debug(...e){Ii[N(this,In)]>Ii.debug||N(this,_n).debug("[Sockrates]:",...e)}info(...e){Ii[N(this,In)]>Ii.info||N(this,_n).info("[Sockrates]:",...e)}warn(...e){Ii[N(this,In)]>Ii.warn||N(this,_n).warn("[Sockrates]:",...e)}error(...e){Ii[N(this,In)]>Ii.error||N(this,_n).error("[Sockrates]:",...e)}}_n=new WeakMap,In=new WeakMap;var nS=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(nS||{});const ZN="2",eV="3";var xe,As,Pe,He,Wi,nt,li,Ki,_r,Ds,ni,Wh,sS,Co,Nd,jh,aS,Hh,af,al,Gh,qh,oS,Wo,Vd,jo,ol,cl,$h,$s,Ho,Go,dl;class tV{constructor(e,r){var i;we(this,Wh),we(this,Co),we(this,jh),we(this,Hh),we(this,al),we(this,qh),we(this,Wo),we(this,jo),we(this,cl),we(this,$s),we(this,Go),we(this,xe,void 0),we(this,As,void 0),we(this,Pe,void 0),we(this,He,void 0),we(this,Wi,void 0),we(this,nt,void 0),we(this,li,void 0),we(this,Ki,void 0),we(this,_r,void 0),we(this,Ds,void 0),we(this,ni,void 0);var n,s,o,c,d,l,h,p,v;de(this,As,e),de(this,Wi,[]),de(this,nt,new sl),de(this,li,!0),de(this,_r,!1),de(this,Pe,r!=null?r:{}),(n=N(this,Pe)).autoReconnect!=null||(n.autoReconnect=!0),(s=N(this,Pe)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(o=N(this,Pe)).pingTimeout!=null||(o.pingTimeout=3e4),(c=N(this,Pe)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=N(this,Pe)).debug!=null||(d.debug=!0),(l=N(this,Pe)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(h=N(this,Pe)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(p=N(this,Pe)).queueOnDisconnect!=null||(p.queueOnDisconnect=!1),(v=N(this,Pe)).flushOnReconnect!=null||(v.flushOnReconnect=!1),de(this,Ki,{code:void 0,reason:void 0}),de(this,He,(i=N(this,Pe).logger)!=null?i:new XN(N(this,Pe).debug?"debug":"info")),de(this,ni,new QN)}get readyState(){var e;return(e=N(this,xe))==null?void 0:e.readyState}get url(){return N(this,As)}updateURL(e){de(this,As,e),Re(this,qh,oS).call(this)}get config(){return N(this,Pe)}get sendQueue(){return N(this,Wi)}flush(){if(!N(this,Pe).queueOnDisconnect)return!1;const e=[];return N(this,Wi).forEach(r=>{this.send(r.event,r.id,r.payload,r.metadata)||e.push(r)}),de(this,Wi,e),N(this,Wi)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){N(this,He).debug("Websocket was already connecting or connected.");return}if(N(this,li)!==!1)return new Promise((r,i)=>{Re(this,$s,Ho).call(this),Re(this,Go,dl).call(this);try{de(this,xe,new WebSocket(Re(this,Wh,sS).call(this,N(this,As)))),N(this,xe).binaryType="arraybuffer",N(this,He).debug("Connecting");const n=setTimeout(()=>{N(this,He).debug("Connection timeout. Closing socket"),de(this,li,!0),Re(this,Go,dl).call(this),N(this,xe).close(3001,"Connection Timeout"),N(this,Pe).autoReconnect&&!N(this,_r)&&(N(this,nt).emit("reconnecting"),Re(this,Wo,Vd).call(this)),i(new Error("Connection timed out!"))},N(this,Pe).connectionTimeout);N(this,xe).onopen=()=>{N(this,He).debug(`Ready State: ${nS[N(this,xe).readyState]}`),n&&clearTimeout(n),Re(this,cl,$h).call(this),de(this,Ki,{code:void 0,reason:void 0}),N(this,nt).emit("connected"),N(this,Pe).flushOnReconnect&&this.flush(),r()},N(this,xe).onclose=s=>{try{n&&clearTimeout(n);const{code:o,reason:c}=s;i(c),N(this,He).debug("Socket closed. Close event:",{event:s}),N(this,He).debug(`Connection closed code: ${o}`),N(this,He).debug(`Connection closed reason: ${c}`),N(this,_r)||Re(this,al,Gh).call(this,o,c)}catch(o){Re(this,Co,Nd).call(this,o)}},N(this,xe).onerror=s=>{Re(this,Co,Nd).call(this,s)},N(this,xe).onmessage=s=>Re(this,jh,aS).call(this,s)}catch(n){Re(this,Co,Nd).call(this,n,i)}})})}send(e,r,i,n){const s={event:e,id:r,payload:i,metadata:n};if(N(this,Pe).queueOnDisconnect&&(!N(this,xe)||N(this,xe).readyState!==1))return N(this,He).debug("Queuing message since socket is not connected!",s),N(this,Wi).push(s),!1;const o=iS.encode(s);return Re(this,jo,ol).call(this,o)}emit(e,r,i,n){return this.send(e,r,i,n)}sendRaw(e){return Re(this,jo,ol).call(this,e)}receive(e,r){return N(this,nt).on(e.toString(),r)}on(e,r){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){N(this,nt).on(e,r);return}this.receive(e,r)}removeAllListeners(){N(this,nt).removeAllListeners()}removeReceiver(e,r){this.removeListener(e,r)}removeListener(e,r){N(this,nt).removeListener(e.toString(),r)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){N(this,nt).listeners(e.toString()).map(r=>this.removeListener(e,r))}disconnect(){de(this,li,!1),Re(this,$s,Ho).call(this),this.removeAllListeners(),de(this,Ki,{code:1e3,reason:"Sockrates disconnect method called"}),N(this,xe).close(1e3,"Sockrates disconnect method called.")}}xe=new WeakMap,As=new WeakMap,Pe=new WeakMap,He=new WeakMap,Wi=new WeakMap,nt=new WeakMap,li=new WeakMap,Ki=new WeakMap,_r=new WeakMap,Ds=new WeakMap,ni=new WeakMap,Wh=new WeakSet,sS=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)://.")},Co=new WeakSet,Nd=function(t,e){N(this,He).error("Error:",{error:t}),N(this,nt).emit("errored",{error:t}),e==null||e(t)},jh=new WeakSet,aS=function(t){if(Re(this,cl,$h).call(this),t.data===ZN){N(this,He).debug("Received ping from server"),Re(this,jo,ol).call(this,eV);return}const e=iS.decode(t.data),{id:r,payload:i}=e;N(this,He).debug("Received message",{event:e.event,messageID:r}),N(this,nt).emit(e.event.toString(),{id:r,payload:i})},Hh=new WeakSet,af=function(){return N(this,xe).readyState===1},al=new WeakSet,Gh=function(t,e){de(this,Ki,{reason:e,code:t}),N(this,nt).emit("disconnected",{code:t,reason:e})},qh=new WeakSet,oS=function(){const{reason:t,code:e}=N(this,Ki);e&&e!==1e3&&N(this,li)&&N(this,Pe).autoReconnect&&!N(this,_r)&&(N(this,He).debug(`Triggering reconnection due to ${t}.`),N(this,nt).emit("reconnecting"),Re(this,Wo,Vd).call(this))},Wo=new WeakSet,Vd=function(t=!0){return u(this,null,function*(){if(t&&N(this,_r)){N(this,He).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(N(this,_r)||N(this,ni).reset(),N(this,Pe).maxReconnectionAttempts!==null&&N(this,ni).getAttempts()>=N(this,Pe).maxReconnectionAttempts){N(this,nt).emit("failed"),de(this,_r,!1);return}de(this,_r,!0),Re(this,Go,dl).call(this),Re(this,$s,Ho).call(this);try{if(yield N(this,ni).wait(),N(this,li)===!1)return;if(N(this,He).debug(`Reconnection attempt ${N(this,ni).getAttempts()}`),N(this,nt).emit("reconnectAttempt",{attempt:N(this,ni).getAttempts()}),yield this.connect(),!Re(this,Hh,af).call(this))throw Error("Reconnect Failed");de(this,_r,!1),de(this,Ki,{code:void 0,reason:void 0}),N(this,nt).emit("reconnected")}catch{N(this,He).debug("Failed to reconnect."),N(this,nt).emit("reconnectFailure",{attempt:N(this,ni).getAttempts()}),Re(this,Wo,Vd).call(this,!1)}})},jo=new WeakSet,ol=function(t){try{return N(this,xe).send(t),!0}catch(e){return N(this,He).error(e.message),!1}},cl=new WeakSet,$h=function(){this.config.disconnectOnPingTimeout&&(N(this,He).debug("Resetting ping timeout"),Re(this,$s,Ho).call(this),de(this,Ds,setTimeout(()=>{var t;N(this,He).debug("Disconnecting the socket due to ping timeout"),de(this,li,!0);const e=3002,r="Ping timeout";(t=N(this,xe))==null||t.close(e,r),Re(this,al,Gh).call(this,e,r)},N(this,Pe).pingTimeout)))},$s=new WeakSet,Ho=function(){N(this,Ds)&&(clearTimeout(N(this,Ds)),de(this,Ds,void 0))},Go=new WeakSet,dl=function(){N(this,xe)&&(N(this,xe).onopen=void 0,N(this,xe).onerror=void 0,N(this,xe).onmessage=void 0,N(this,xe).onclose=void 0)};var rV=Object.defineProperty,iV=Object.getOwnPropertyDescriptor,Nl=(t,e,r,i)=>{for(var n=i>1?void 0:i?iV(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&rV(e,r,n),n};const of=65535,nV=3e3;var hn,Ne,Ve,Ue,vr,ut,Fc,Du,Bc,Ou,cf;const cS=(cf=class{constructor(t,{peerId:e,meetingId:r,authToken:i,capabilities:n}){g(this,Ve),g(this,Fc),g(this,Bc),g(this,hn,void 0),g(this,Ne,void 0),m(this,"roomName"),m(this,"authToken"),m(this,"capabilities"),g(this,vr,void 0),g(this,ut,void 0);var s;if(!e||!r||!i)throw new I("peerId, meetingId, or authToken can not be empty","0404");f(this,vr,void 0),f(this,ut,t),this.capabilities=n,this.roomName=r,this.authToken=i,f(this,hn,U(this,Fc,Du).call(this,e)),f(this,Ne,new tV(a(this,hn),{autoReconnect:!0,disconnectOnPingTimeout:(s=n.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Ve,Ue).socketJoinAttempted}set joinAttempted(t){a(this,Ve,Ue).socketJoinAttempted=t}get telemetry(){return a(this,ut).getValue("telemetry")}get logger(){return a(this,ut).getValue("logger")}get peerId(){return a(this,ut).getValue("peerId")}updateURL(t){t!==this.peerId&&(f(this,hn,U(this,Fc,Du).call(this,t)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ne).updateURL(a(this,hn))}static getSocketEdgeDomain(t){return Nn({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,hn)}connect(){return u(this,null,function*(){a(this,Ve,Ue).socketJoinAttempted=!0,yield a(this,Ne).connect(),a(this,Ve,Ue).socketJoinAttempted=!0,a(this,Ve,Ue).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){a(this,Ve,Ue).socketJoinAttempted=!1,a(this,Ne).disconnect(),a(this,Ve,Ue).socketJoinAttempted=!0,a(this,Ve,Ue).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ne).readyState===1}catch{return!1}}sendMessage(t,e,r){const i={};return a(this,ut).getValue("telemetry").injectContext(i),a(this,Ne).send(t,r!=null?r:U(this,Bc,Ou).call(this),e,new TextEncoder().encode(JSON.stringify(i)))}sendMessagePromise(t,e,r,i){const n=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:n,protobuf:e,messageId:r,resp:i})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:r,messageId:i,resp:n}){const s=n!=null?n:t;return new Promise((o,c)=>{const d=(S,T)=>{a(this,Ne).removeListener(s,S),a(this,Ne).removeListener(of,T),a(this,Ne).removeListener(dr.errorResponse,T),a(this,Ne).removeListener(Ir.errorResponse,T)},l=i!=null?i:U(this,Bc,Ou).call(this),h={};a(this,ut).getValue("telemetry").injectContext(h);const p=({id:S,payload:T})=>{if(l===S){let C;try{const b=rP.fromBinary(T);C=new Error(b.errorMessage)}catch(b){C=new Error("failed to parse error message",{cause:b});try{const R=iR.fromBinary(T);C=new Error(R.message)}catch(R){C=new Error("failed to parse error message",{cause:R})}}c(C),d(v,p)}},v=({id:S,payload:T})=>{l===S&&(o({id:S,payload:T}),d(v,p))};a(this,Ne).on(s,v),a(this,Ne).on(of,p),a(this,Ne).on(dr.errorResponse,p),a(this,Ne).on(Ir.errorResponse,p),setTimeout(()=>{d(v,p),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,Ne).send(t,l,r,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){a(this,Ne).on(t,e)}onStateEvent(t,e){a(this,Ne).on(t,e)}removeListener(t,e){a(this,Ne).removeListener(t,e)}removeListeners(t){a(this,Ne).removeListeners(t)}flush(){return a(this,Ne).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),a(this,vr)&&(clearTimeout(a(this,vr)),f(this,vr,void 0)),a(this,Ve,Ue).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var r;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:k.location.country});const{recv:i,send:n}=(r=a(this,Ve,Ue).mediaState)!=null?r:{};i!=null&&i.state&&(i==null?void 0:i.state)!==Xs.CONNECTED||n!=null&&n.state&&(n==null?void 0:n.state)!==Xs.CONNECTED?a(this,ut).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ve,Ue).joinAttempted}):f(this,vr,setTimeout(()=>{a(this,ut).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ve,Ue).joinAttempted}),f(this,vr,void 0)},nV)),a(this,Ve,Ue).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:k.location.country}),a(this,Ve,Ue).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),a(this,Ve,Ue).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,Ve,Ue).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Ve,Ue).mediaJoinAttempted}}),a(this,vr)&&(clearTimeout(a(this,vr)),f(this,vr,void 0)),a(this,ut).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Ve,Ue).mediaJoinAttempted}),a(this,Ve,Ue).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){this.logger.info("SocketService::Failed to connect to socket-edge",{country:k.location.country}),a(this,ut).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_FAILED),a(this,Ve,Ue).updateSocketConnectionState("failed")}))}},hn=new WeakMap,Ne=new WeakMap,Ve=new WeakSet,Ue=function(){return a(this,ut).getValue("connectionHandler")},vr=new WeakMap,ut=new WeakMap,Fc=new WeakSet,Du=function(t){let e=cS.getSocketEdgeDomain(a(this,ut).getValue("baseURI"));typeof Ys(a(this,ut),"socket_server_base")=="string"&&(e=Ys(a(this,ut),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),n=this.peerId,s=q(V({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},n!==t&&{oldPeerID:n}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Jd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(s).forEach(([o,c])=>{i.searchParams.append(o,c.toString())}),i.href},Bc=new WeakSet,Ou=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},cf);let ac=cS;Nl([k.trace("SocketService.connect")],ac.prototype,"connect",1);Nl([k.trace("SocketService.disconnect")],ac.prototype,"disconnect",1);Nl([k.trace("SocketService.sendMessagePromise")],ac.prototype,"sendMessagePromise",1);Nl([k.trace("SocketService.sendMessagePromiseWithTimeout")],ac.prototype,"sendMessagePromiseWithTimeout",1);class sV{constructor(e){m(this,"socketService"),this.socketService=e}handleConnectedRoomsDumpRaw({payload:e}){var r;const i=MR.fromBinary(e),n=i.meetings.map(s=>{var o;return{id:s.id,title:s.title,participants:(o=s.participants)!=null?o:[]}});return{parentMeeting:{id:i.parentMeeting.id,title:i.parentMeeting.title,participants:(r=i.parentMeeting.participants)!=null?r:[]},meetings:n}}handleTransferPeerRaw({payload:e}){const r=rM.fromBinary(e);return{authToken:r.authToken,meetingId:r.meetingId}}handleMovedPeerRaw({payload:e}){const r=ry.fromBinary(e);return{meetingId:r.meetingId,customParticipantId:r.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:e}){return Jm.fromBinary(e).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:e}){return $R.fromBinary(e).payloads}getConnectedRoomsDump(){return u(this,null,function*(){const e=yield this.socketService.sendMessagePromise(F.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(e)})}createConnectedRooms(e){return u(this,null,function*(){const{payload:r}=yield this.socketService.sendMessagePromise(F.createConnectedRooms,NR.toBinary({payloads:e}));return Jm.fromBinary(r).payloads.map(i=>({id:i.id,title:i.title}))})}updateConnectedRooms(e){return u(this,null,function*(){})}disableConnectedRooms(e){return u(this,null,function*(){const r=e.map(n=>({id:n})),i=yield this.socketService.sendMessagePromise(F.deleteConnectedRooms,GR.toBinary({payloads:r}));return this.handleConnectedRoomsDeletedRaw(i)})}movePeersBetweenRooms(e){return u(this,null,function*(){try{const r=yield this.socketService.sendMessagePromise(F.movePeers,XR.toBinary({sourceMeetingId:e.sourceMeetingId,destinationMeetingId:e.destinationMeetingId,participants:e.participants}));return new TextDecoder().decode(r.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(r){return{success:!1,error:r}}})}}var aV=Object.defineProperty,oV=Object.getOwnPropertyDescriptor,cV=(t,e,r,i)=>{for(var n=i>1?void 0:i?oV(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&aV(e,r,n),n},Wr;class dS extends Zt{constructor(e){const r=e.getValue("logger");super(r),m(this,"meetings",[]),m(this,"parentMeeting",null),g(this,Wr,void 0),f(this,Wr,e)}get supportsConnectedMeetings(){return a(this,Wr).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}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 a(this,Wr).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield a(this,Wr).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(r=>({id:r.id,title:r.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield a(this,Wr).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const r=this.meetings.map(i=>e.includes(i.id)&&i.participants.length!==0?this.moveParticipants(i.id,this.parentMeeting.id,i.participants.map(n=>n.id)):Promise.resolve());return yield Promise.all(r),yield a(this,Wr).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)})}moveParticipants(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Wr).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(s=>({id:s}))});return n.success&&this.moveSuccessHandler(e,r,i),n})}moveParticipantsWithCustomPreset(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=yield a(this,Wr).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success&&this.moveSuccessHandler(e,r,i.map(s=>s.id)),n})}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>n.set(s.id,s)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(s=>n.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(r===s.id){const o=s.participants.concat(i.map(c=>n.get(c)));return q(V({},s),{participants:o})}if(e===s.id){const o=s.participants.filter(c=>!i.includes(c.id));return q(V({},s),{participants:o})}return s})}}Wr=new WeakMap;cV([Bt({maxInvocations:60,period:60})],dS.prototype,"getConnectedMeetings",1);var dV=Object.defineProperty,lV=Object.getOwnPropertyDescriptor,Vp=(t,e,r,i)=>{for(var n=i>1?void 0:i?lV(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&dV(e,r,n),n},Te,df;const lS=(df=class{constructor(t){m(this,"connectedMeetings"),g(this,Te,void 0),f(this,Te,t),this.connectedMeetings=new dS(t)}get telemetry(){return a(this,Te).getValue("telemetry")}get logger(){return a(this,Te).getValue("logger")}static init(t){const e=new lS(t);return e.connectedMeetings.supportsConnectedMeetings&&(e.setupEvents(),t.getValue("self").once("roomJoined",()=>e.getConnectedMeetings())),e}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.transferPeer,this.handleTransferPeer.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.movedPeer,this.handleMovedPeer.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Te).getValue("connectedMeetingsSocketHandler").socketService.on(F.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(t){const e=a(this,Te).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:r}){var i,n,s,o;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
22
22
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",r);const c={video:a(this,Te).getValue("self").videoEnabled,audio:a(this,Te).getValue("self").audioEnabled};try{a(this,Te).getValue("self").cleanupEvents(),yield a(this,Te).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,Te).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${r}`);const d=yield hS.init(q(V({},a(this,Te).getValue("options")),{cachedUserDetails:null,defaults:q(V(V({},a(this,Te).getValue("options").defaults),c),{mediaHandler:a(this,Te).getValue("self")}),authToken:e}));this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:l}=a(this,Te).getValue("self");d.self.setName(a(this,Te).getValue("self").name),yield d.join(),l&&d.self.hide()}catch(l){this.logger.error("ConnectedMeetingsController.joinRoom",{error:l})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(o=d==null?void 0:d.meta)==null?void 0:o.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),d})}handleConnectedRoomsDump(t){const e=a(this,Te).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(r=>({id:r.id,title:r.title,participants:r.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return a(this,Te).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=a(this,Te).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(t),r=new Map;this.connectedMeetings.meetings.forEach(i=>{r.set(i.id,i)}),e.forEach(i=>{r.has(i.id)?r.get(i.id).title=i.title:r.set(i.id,q(V({},i),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(r.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=a(this,Te).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(t).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Te=new WeakMap,df);let Vl=lS;Vp([k.trace("ConnectedMeetingsController.getConnectedMeetings")],Vl.prototype,"getConnectedMeetings",1);Vp([k.trace("ConnectedMeetingsController.setupEvents")],Vl.prototype,"setupEvents",1);Vp([k.trace("ConnectedMeetingsController.switchMeeting")],Vl.prototype,"switchMeeting",1);var uV=Object.defineProperty,hV=Object.getOwnPropertyDescriptor,Ll=(t,e,r,i)=>{for(var n=i>1?void 0:i?hV(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&uV(e,r,n),n};const Os=class{constructor(t,e,r){m(this,"apiBase"),m(this,"selfController"),m(this,"pollController"),m(this,"chatController"),m(this,"metaController"),m(this,"storesManager"),m(this,"stageController"),m(this,"pluginController"),m(this,"internalsController"),m(this,"recordingController"),m(this,"livestreamController"),m(this,"participantController"),m(this,"connectedMeetingsController"),m(this,"telemetry"),m(this,"logger"),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,this.connectedMeetingsController=e.connectedMeetingsController,this.telemetry=r.getValue("telemetry"),this.logger=r.getValue("logger")}static init(t){return u(this,null,function*(){var e,r;const{peerId:i,apiBase:n,authToken:s,meetingId:o,organizationId:c,cachedUserDetails:d,logger:l}=t.getAllValues();if($y(t),Ie.isSupported()===!1)throw new I("Browser not supported","0010",l,!0);const h=mO(t,{authToken:s,baseURL:n,cachedUserDetails:d});h.setRoomName(o),h.setRoomUUID(o),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",i),t.setValue("apiClient",h);const p=new YO(t);t.setValue("connectionHandler",p);const v=Os.createSocketService(t),S=v.connect(),T=h.getUserDetails(),C=h.getPlugins();let b=Oe.HIVE,R,j="";try{yield Os.setupFlagsmith(t)}catch(ae){l.error("Failed to setup flagsmith",{error:ae})}try{yield S}catch(ae){l.error("[Controller]: Failed to connect to socket server:",{error:ae})}try{({sfu:b,meetingTitle:j}=yield h.getRoomNodeData()),R=yield T,l.info(`SFU ${b} is being used.`),t.setValue("presetName",R.preset.name),t.setValue("roomNodeOptions",{sfu:b})}catch(ae){l.error("Failed to get room metadata",{error:ae})}const B=N1.init(R.preset,!t.getValue("modules").theme),w=tN.init(t,B.viewType,R.preset.permissions),ee=Os.setupControllers(v,t,R,C,j,B,w);FO(B)&&((e=Os.createRoomNodeClient(t,v).initializeConnection(R.participant.name,o,!1,w))==null||e.catch(ae=>{l.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),k.location.country=(r=h.ipInfo)==null?void 0:r.country;const{controllers:re}=yield ee;return LI(),new Os(n,re,t)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:r,baseURI:i,overrides:n,meetingId:s,organizationId:o,logger:c}=t.getAllValues(),d=VI(s),l=q(V({entity:Hu.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:d,roomName:s},Ie.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=n==null?void 0:n.whitelabelled_flags_endpoint)==null||e?Nn({servicePrefix:"flags",baseURI:i}):"edge.api.flagsmith.com";yield t.getValue("flagsmith").identify(`${Hu.PEER}_${r}`,JSON.parse(JSON.stringify(l)),!1,5e3,h,c),c.info("flagsmith::allFlags",{flags:JSON.stringify(t.getValue("flagsmith").getAllFlags())},!0)}catch{c.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,r,i,n,s,o){return u(this,null,function*(){var c,d,l;const h=e.getValue("modules"),{participant:p}=r,v=e.getValue("defaults"),S=e.getValue("logger"),{sfu:T}=e.getValue("roomNodeOptions"),{viewType:C,mediaConstraints:{audio:b}}=s;e.setValue("viewType",C),e.setValue("defaults",V({mediaConfiguration:{audio:{enableHighBitrate:(c=b.enableHighBitrate)!=null?c:!1,enableStereo:(d=b.enableStereo)!=null?d:!1}}},v)),e.setValue("maxPreferredStreams",Ie.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let R,j,B,w,ee,re,ae,Me,Ze;const jt=new AN(e,t),A=new sV(t);e.setValue("connectedMeetingsSocketHandler",A);const E=new Dl(e,t),_=new ur(e,t),W=new xN(t),oe=new Ky(e,t),Ge=new UN(e,t),x=new MN(t),M=new Un(e,t),ce=yield Zi.init(e,oe,p,o,s);e.setValue("selfController",ce);const en=yield my.init(e,ce.self,oe,jt,n);if(h.participant&&(Me=new Ei(e,ce.self,oe,T)),(l=h.e2ee)!=null&&l.enabled&&h.e2ee.manager.init(S,e.getValue("peerSessionStore")),h.chat&&(j=yield hi.init(e,_,M,ce.self,Me.participants)),h.internals&&(ee=yield bp.init(e)),h.livestream&&s.viewType===Ft.Livestream&&e.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&(ae=new by(e,ce.self,x)),s.viewType!==Ft.Chat){if(h.poll&&(R=yield ly.init(e,ce.self,E)),h.recording&&(re=new yy(e,ce.self,oe)),h.stage&&(B=new gy(e,W,oe,ce.self,Me.participants)),h.plugin){if(!Me)throw new I("The plugin module cannot be initialized without the `participant` module","0102");const Yr=yield i;w=yield rc.init(e,Yr,Ge,_,j==null?void 0:j.chat,ce.self,Me.participants,n)}if(h.connectedMeetings&&(Ze=yield Vl.init(e)),h.pip){const Yr=yield FI._init(e,ce.self);e.setValue("pip",Yr)}}const tn={storesManager:new j1(e,Ge),pollController:R,selfController:ce,metaController:en,chatController:j,stageController:B,pluginController:w,recordingController:re,internalsController:ee,livestreamController:ae,participantController:Me,connectedMeetingsController:Ze};return{theme:s,permissions:o,controllers:tn}})}static createRoomNodeClient(t,e){const{peerId:r,roomNodeOptions:i}=t.getAllValues(),{sfu:n}=i;return qy(t,n,{socket:e,peerId:r})}static createSocketService(t){const{peerId:e,meetingId:r,authToken:i}=t.getAllValues(),n=["PING"];return new ac(t,{peerId:e,meetingId:r,authToken:i,capabilities:n})}};let oc=Os;Ll([k.trace("Controller.init")],oc,"init",1);Ll([k.trace("setupFlagsmith")],oc,"setupFlagsmith",1);Ll([k.trace("Controller.createRoomNodeClient")],oc,"createRoomNodeClient",1);Ll([k.trace("Controller.createSocketService")],oc,"createSocketService",1);class pV{constructor(){m(this,"battery"),m(this,"logger"),m(this,"init",e=>u(this,null,function*(){this.logger=e;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(r){e.error("Error getting battery",r)}})),m(this,"updateChargeInfo",()=>{var e;this.logger.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),m(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)}),m(this,"cleanup",()=>{var e,r;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(r=this.battery)==null||r.removeEventListener("levelchange",this.updateLevelInfo))})}}const lf=new pV;function mV(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:r,orgId:i,participantId:n}=JSON.parse(atob(t.split(".")[1]));if(!r)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const o=`https://${Nn({servicePrefix:"api",baseURI:s})}`;return{meetingId:r,orgId:i,participantId:n,baseURI:s,apiBase:o}}catch{throw new I("Invalid auth token","0004")}}var Cn,Ns,Vs,ll,Jh,uS;class gV{constructor(){g(this,Jh),g(this,Cn,new Audio),g(this,Ns,new MediaStream),g(this,Vs,new Map),g(this,ll,void 0),a(this,Cn).srcObject=a(this,Ns),a(this,Cn).autoplay=!0}playTracks(e){return u(this,null,function*(){return e.forEach(r=>{a(this,Vs).has(r.id)||(a(this,Ns).addTrack(r),a(this,Vs).set(r.id,r))}),this.play()})}setSpeakerDevice(e){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,Cn).setSinkId(e)}removeTrack(e){const r=a(this,Vs).get(e);r&&(a(this,Ns).removeTrack(r),a(this,Vs).delete(e))}play(){return u(this,null,function*(){return a(this,Cn).srcObject=a(this,Ns),a(this,Cn).play().catch(e=>{U(this,Jh,uS).call(this,e)})})}onError(e){f(this,ll,e)}}Cn=new WeakMap,Ns=new WeakMap,Vs=new WeakMap,ll=new WeakMap,Jh=new WeakSet,uS=function(t){var e;(e=a(this,ll))==null||e.call(this,t)};var Ls;class fV extends gV{constructor(){super(),g(this,Ls,void 0),f(this,Ls,new Map)}addParticipantTrack(e,r){a(this,Ls).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,Ls).get(e);r&&this.removeTrack(r),a(this,Ls).delete(e)}}Ls=new WeakMap;var vV=Object.defineProperty,yV=Object.getOwnPropertyDescriptor,xl=(t,e,r,i)=>{for(var n=i>1?void 0:i?yV(e,r):e,s=t.length-1,o;s>=0;s--)(o=t[s])&&(n=(i?o(e,r,n):o(n))||n);return i&&n&&vV(e,r,n),n},tt,ms,uf;let Qi=(uf=class{constructor(t,e){g(this,tt,void 0),g(this,ms,void 0),f(this,ms,t),f(this,tt,e)}get peerId(){return a(this,ms).getValue("peerId")}static initMedia(t={},e=!1,r=void 0){var i;const n=(i=r==null?void 0:r.peerId)!=null?i:Ln(),s=ui.createContext(n,{peerId:n}),o=s.getValue("logger");o.init(s);const c=new Py(o);return c.init(t,e,s),s.setValue("defaults",{mediaHandler:c}),c}static init(t){return u(this,null,function*(){var e,r,i,n,s,o,c;Ie.init();const{mediaHandler:d}=(e=t.defaults)!=null?e:{},l=(d==null?void 0:d.peerId)||((i=(r=t==null?void 0:t.cachedUserDetails)==null?void 0:r.peerId)!=null?i:Ln()),{authToken:h,baseURI:p}=t,v=mV(h,p),{meetingId:S}=v,T=pl(v,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const C=Qi.setupContext(l,t,S,T),b=C.getValue("telemetry"),R=C.getValue("logger");wE(R),lf.init(R),b.init(C,{roomName:S,userId:T.participantId,organizationId:T.orgId,peerId:l},(s=(n=t.modules)==null?void 0:n.tracing)!=null?s:!0),R.init(C),R.info("DyteClient::init::options",{dyteClientInitOptions:q(V({},t),{authToken:`${(o=t.authToken)==null?void 0:o.slice(0,10)}...
23
- ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield oc.init(C),B=new Qi(C,j);return C.setValue("meeting",B),B})}static setupContext(t,e,r,i){var n,s;const o=ui.createContext(t,e),c=V(V({},CI),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",r),o.setValue("apiBase",i.apiBase),o.setValue("baseURI",i.baseURI),o.setValue("userId",i.participantId),o.setValue("organizationId",i.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",PI({baseURI:i.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",Pr(e.cachedUserDetails)),o.setValue("sdkVersion","3.2.0-staging.13"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new fV),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,tt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){lf.cleanup(),a(this,ms).getValue("peerSessionStore").reset();const{selfController:e}=a(this,tt);return e.leaveRoom(t)})}get participants(){var t;return(t=a(this,tt).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,tt).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,tt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,tt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,tt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,tt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,tt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,tt).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,tt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,tt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,tt).stageController)==null?void 0:t.stage}get stores(){return a(this,tt).storesManager}get audio(){return a(this,ms).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,tt).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)})}},tt=new WeakMap,ms=new WeakMap,uf);xl([ft("0002"),Si.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Qi.prototype,"join",1);xl([ft("0003")],Qi.prototype,"leave",1);xl([ft("0001"),Si.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Qi,"init",1);Qi=xl([ft("0000")],Qi);const hS=Qi;class SV{constructor(e){cc(this,"meeting");cc(this,"l");cc(this,"onUpdate",()=>{this.l.forEach(e=>{e()})});var r,i,n,s,o,c,d,l,h,p,v,S,T,C,b,R;this.meeting=e,this.l=new Set,(r=this.meeting.self)==null||r.addListener("*",this.onUpdate),(i=this.meeting.meta)==null||i.addListener("*",this.onUpdate),(n=this.meeting.participants)==null||n.addListener("*",this.onUpdate),(o=(s=this.meeting.participants)==null?void 0:s.joined)==null||o.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),(p=this.meeting.stage)==null||p.addListener("*",this.onUpdate),(v=this.meeting.livestream)==null||v.addListener("*",this.onUpdate),(S=this.meeting.chat)==null||S.addListener("*",this.onUpdate),(T=this.meeting.plugins)==null||T.all.addListener("*",this.onUpdate),(C=this.meeting.recording)==null||C.addListener("*",this.onUpdate),(b=this.meeting.connectedMeetings)==null||b.addListener("*",this.onUpdate),(R=this.meeting.polls)==null||R.addListener("*",this.onUpdate)}clean(){var e,r,i,n,s,o,c,d,l,h,p,v,S,T,C,b;(e=this.meeting.self)==null||e.removeListener("*",this.onUpdate),(r=this.meeting.meta)==null||r.removeListener("*",this.onUpdate),(i=this.meeting.participants)==null||i.removeListener("*",this.onUpdate),(s=(n=this.meeting.participants)==null?void 0:n.joined)==null||s.removeListener("*",this.onUpdate),(c=(o=this.meeting.participants)==null?void 0:o.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),(p=this.meeting.livestream)==null||p.removeListener("*",this.onUpdate),(v=this.meeting.chat)==null||v.removeListener("*",this.onUpdate),(S=this.meeting.plugins)==null||S.all.removeListener("*",this.onUpdate),(T=this.meeting.recording)==null||T.removeListener("*",this.onUpdate),(C=this.meeting.connectedMeetings)==null||C.removeListener("*",this.onUpdate),(b=this.meeting.polls)==null||b.removeListener("*",this.onUpdate)}addListener(e){this.l.add(e)}removeListener(e){this.l.delete(e)}}const Ul=Pt.createContext({meeting:void 0,updates:void 0});function EV({value:t,children:e,fallback:r}){const[i,n]=Pt.useState(),s=Pt.useRef();return Pt.useEffect(()=>(t&&n(new SV(t)),()=>{var o;(o=s.current)==null||o.clean()}),[t]),fS.default.createElement(Ul.Provider,{value:{meeting:t,updates:i}},t?e:r)}const kV=()=>{const{meeting:t}=Pt.useContext(Ul);if(!t)throw new Error("useDyteMeeting must be used within the DyteProvider");return{meeting:t}},TV=t=>{const e=Pt.useRef(!1),[r,i]=Pt.useState(),n=t==null?void 0:t.resetOnLeave,s=Pt.useCallback(async o=>{if(!e.current)return e.current=!0,hS.init(o).then(c=>(i(c),c)).finally(()=>{e.current=!1})},[]);return Pt.useEffect(()=>{if(!r||!n)return()=>{};const o=({state:c})=>{c!=="connected-meeting"&&c!=="disconnected"&&i(void 0)};return r.self.on("roomLeft",o),()=>{r.self.removeListener("roomLeft",o)}},[r]),Pt.useEffect(()=>{if(!r||!r.connectedMeetings)return()=>{};const o=c=>{i(void 0),setTimeout(()=>{i(c)},100)};return r.connectedMeetings.on("meetingChanged",o),()=>{r.connectedMeetings.removeListener("meetingChanged",o)}},[r]),[r,s]},bV=(t,e)=>!!(t!==e||Array.isArray(t)&&Array.isArray(e)&&t.length!==e.length),wV=t=>{const{meeting:e,updates:r}=Pt.useContext(Ul);if(!e)throw new Error("useDyteSelector must be used within the DyteProvider");const i=Pt.useRef(t(e)),[,n]=Pt.useReducer(s=>s+1,0);return Pt.useEffect(()=>{const s=e&&t(e),o=()=>{const c=e&&t(e);bV(i.current,c)&&(i.current=c,n())};return s&&typeof s=="object"&&"addListener"in s?(s.addListener("*",n),()=>{s.removeListener("*",n)}):(r==null||r.addListener(o),()=>{r==null||r.removeListener(o)})},[e,r]),i.current};exports.RealtimeKitContext=Ul;exports.RealtimeKitProvider=EV;exports.useRealtimeKitClient=TV;exports.useRealtimeKitMeeting=kV;exports.useRealtimeKitSelector=wV;
23
+ ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield oc.init(C),B=new Qi(C,j);return C.setValue("meeting",B),B})}static setupContext(t,e,r,i){var n,s;const o=ui.createContext(t,e),c=V(V({},CI),e==null?void 0:e.modules),d=e.defaults||{audio:!0,video:!0};return o.setValue("options",e),o.setValue("peerId",t),o.setValue("modules",c),o.setValue("sdkName","web-core"),o.setValue("meetingId",r),o.setValue("apiBase",i.apiBase),o.setValue("baseURI",i.baseURI),o.setValue("userId",i.participantId),o.setValue("organizationId",i.orgId),o.setValue("authToken",e.authToken),o.setValue("overrides",(n=e.overrides)!=null?n:{}),o.setValue("env",PI({baseURI:i.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",Pr(e.cachedUserDetails)),o.setValue("sdkVersion","3.2.0-staging.15"),(s=e.modules)!=null&&s.experimentalAudioPlayback&&o.setValue("audioPlayback",new fV),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,tt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){lf.cleanup(),a(this,ms).getValue("peerSessionStore").reset();const{selfController:e}=a(this,tt);return e.leaveRoom(t)})}get participants(){var t;return(t=a(this,tt).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,tt).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,tt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,tt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,tt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,tt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,tt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,tt).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,tt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,tt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,tt).stageController)==null?void 0:t.stage}get stores(){return a(this,tt).storesManager}get audio(){return a(this,ms).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,tt).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)})}},tt=new WeakMap,ms=new WeakMap,uf);xl([ft("0002"),Si.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Qi.prototype,"join",1);xl([ft("0003")],Qi.prototype,"leave",1);xl([ft("0001"),Si.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Qi,"init",1);Qi=xl([ft("0000")],Qi);const hS=Qi;class SV{constructor(e){cc(this,"meeting");cc(this,"l");cc(this,"onUpdate",()=>{this.l.forEach(e=>{e()})});var r,i,n,s,o,c,d,l,h,p,v,S,T,C,b,R;this.meeting=e,this.l=new Set,(r=this.meeting.self)==null||r.addListener("*",this.onUpdate),(i=this.meeting.meta)==null||i.addListener("*",this.onUpdate),(n=this.meeting.participants)==null||n.addListener("*",this.onUpdate),(o=(s=this.meeting.participants)==null?void 0:s.joined)==null||o.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),(p=this.meeting.stage)==null||p.addListener("*",this.onUpdate),(v=this.meeting.livestream)==null||v.addListener("*",this.onUpdate),(S=this.meeting.chat)==null||S.addListener("*",this.onUpdate),(T=this.meeting.plugins)==null||T.all.addListener("*",this.onUpdate),(C=this.meeting.recording)==null||C.addListener("*",this.onUpdate),(b=this.meeting.connectedMeetings)==null||b.addListener("*",this.onUpdate),(R=this.meeting.polls)==null||R.addListener("*",this.onUpdate)}clean(){var e,r,i,n,s,o,c,d,l,h,p,v,S,T,C,b;(e=this.meeting.self)==null||e.removeListener("*",this.onUpdate),(r=this.meeting.meta)==null||r.removeListener("*",this.onUpdate),(i=this.meeting.participants)==null||i.removeListener("*",this.onUpdate),(s=(n=this.meeting.participants)==null?void 0:n.joined)==null||s.removeListener("*",this.onUpdate),(c=(o=this.meeting.participants)==null?void 0:o.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),(p=this.meeting.livestream)==null||p.removeListener("*",this.onUpdate),(v=this.meeting.chat)==null||v.removeListener("*",this.onUpdate),(S=this.meeting.plugins)==null||S.all.removeListener("*",this.onUpdate),(T=this.meeting.recording)==null||T.removeListener("*",this.onUpdate),(C=this.meeting.connectedMeetings)==null||C.removeListener("*",this.onUpdate),(b=this.meeting.polls)==null||b.removeListener("*",this.onUpdate)}addListener(e){this.l.add(e)}removeListener(e){this.l.delete(e)}}const Ul=Pt.createContext({meeting:void 0,updates:void 0});function EV({value:t,children:e,fallback:r}){const[i,n]=Pt.useState(),s=Pt.useRef();return Pt.useEffect(()=>(t&&n(new SV(t)),()=>{var o;(o=s.current)==null||o.clean()}),[t]),fS.default.createElement(Ul.Provider,{value:{meeting:t,updates:i}},t?e:r)}const kV=()=>{const{meeting:t}=Pt.useContext(Ul);if(!t)throw new Error("useDyteMeeting must be used within the DyteProvider");return{meeting:t}},TV=t=>{const e=Pt.useRef(!1),[r,i]=Pt.useState(),n=t==null?void 0:t.resetOnLeave,s=Pt.useCallback(async o=>{if(!e.current)return e.current=!0,hS.init(o).then(c=>(i(c),c)).finally(()=>{e.current=!1})},[]);return Pt.useEffect(()=>{if(!r||!n)return()=>{};const o=({state:c})=>{c!=="connected-meeting"&&c!=="disconnected"&&i(void 0)};return r.self.on("roomLeft",o),()=>{r.self.removeListener("roomLeft",o)}},[r]),Pt.useEffect(()=>{if(!r||!r.connectedMeetings)return()=>{};const o=c=>{i(void 0),setTimeout(()=>{i(c)},100)};return r.connectedMeetings.on("meetingChanged",o),()=>{r.connectedMeetings.removeListener("meetingChanged",o)}},[r]),[r,s]},bV=(t,e)=>!!(t!==e||Array.isArray(t)&&Array.isArray(e)&&t.length!==e.length),wV=t=>{const{meeting:e,updates:r}=Pt.useContext(Ul);if(!e)throw new Error("useDyteSelector must be used within the DyteProvider");const i=Pt.useRef(t(e)),[,n]=Pt.useReducer(s=>s+1,0);return Pt.useEffect(()=>{const s=e&&t(e),o=()=>{const c=e&&t(e);bV(i.current,c)&&(i.current=c,n())};return s&&typeof s=="object"&&"addListener"in s?(s.addListener("*",n),()=>{s.removeListener("*",n)}):(r==null||r.addListener(o),()=>{r==null||r.removeListener(o)})},[e,r]),i.current};exports.RealtimeKitContext=Ul;exports.RealtimeKitProvider=EV;exports.useRealtimeKitClient=TV;exports.useRealtimeKitMeeting=kV;exports.useRealtimeKitSelector=wV;