@cloudflare/realtimekit-react 1.1.3-staging.1 → 1.1.3-staging.3

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 n=s&&!!i;r&&r.endsWith("00")&&i&&(n=!0),n&&i.error("Dyt
14
14
 
15
15
  ${t}`}const na={maxInvocations:5,period:1};function Bt(t,e){return function(r,i,s){const n=s.value;let o=0,c=Date.now();return s.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,n.apply(this,d)},s}}var gD=Object.defineProperty,fD=Object.getOwnPropertyDescriptor,ft=(t,e,r,i)=>{for(var s=i>1?void 0:i?fD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&gD(e,r,s),s};const vD=["text","image","file","custom","poll"],Xc={maxInvocations:180,period:60};var ee,Js,ze,Ks,zs,tu,Zm,wc,ru,eg;let st=(eg=class extends Xt{constructor(t,e,r,i,s){const n=t.getValue("logger");super(n),g(this,tu),g(this,wc),p(this,"messages"),p(this,"channels",[]),g(this,ee,void 0),g(this,Js,void 0),g(this,ze,void 0),g(this,Ks,void 0),g(this,zs,void 0),p(this,"maxTextLimit",2e3),f(this,zs,t),f(this,ze,e),f(this,Ks,r),f(this,ee,i),f(this,Js,s),this.messages=[]}get telemetry(){return a(this,zs).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}sendMessageInternal(t,e,r){return u(this,arguments,function*(i,s,n,o={}){switch(i.type){case"text":{const c=o.replyTo&&o.replyTo.type==="text"?mD(i.message,o.replyTo.message):i.message;yield this.sendTextMessageInternal(c,s,n);break}case"image":yield this.sendImageMessageInternal(i.image,s,n);break;case"file":yield this.sendFileMessageInternal(i.file,s,n);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,s,n,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,ee).permissions)!=null&&i.chatPrivate.canSend)||!((s=a(this,ee).permissions)!=null&&s.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new I("Could not send message to private chat.","0501")}else if(!((o=(n=a(this,ee).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,ee).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,ee).id),l=a(this,Js).joined.toArray().filter(h=>e.includes(h.id)).map(h=>h.userId),l.push(a(this,ee).userId)),a(this,ze).sendMessage(t,_t.TEXT,e)})}sendImageMessageInternal(t,e,r){return u(this,null,function*(){var i,s,n,o,c,d;if(e&&e.length>0){if(!((i=a(this,ee).permissions)!=null&&i.chatPrivate.canSend)||!((s=a(this,ee).permissions)!=null&&s.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,ee).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,ee).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=ht(),{getLocation:h,putLocation:m}=yield l.getPresignedUrls(t.name,a(this,ee).config.viewType);if(yield l.uploadFile(t,m),r){a(this,ze).sendMessageToChannel(h,_t.IMAGE,r);return}let v=[];e&&e.length>0&&(e.push(a(this,ee).id),v=a(this,Js).joined.toArray().filter(S=>e.includes(S.id)).map(S=>S.userId),v.push(a(this,ee).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,s,n,o,c,d;if(e&&e.length>0){if(!((i=a(this,ee).permissions)!=null&&i.chatPrivate.canSend)||!((s=a(this,ee).permissions)!=null&&s.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,ee).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,ee).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=ht(),{getLocation:h,putLocation:m}=yield l.getPresignedUrls(t.name,a(this,ee).config.viewType);if(yield l.uploadFile(t,m),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,ee).id),v=a(this,Js).joined.toArray().filter(T=>e.includes(T.id)).map(T=>T.userId),v.push(a(this,ee).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 Xc}updateRateLimits(t,e){Xc.maxInvocations=t,Xc.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,s,n,o,c,d,l,h,m,v,S,T,M,b;if(e&&e.length>0){if(!((r=a(this,ee).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,ee).permissions)!=null&&i.chatPrivate.files)||!((s=a(this,ee).permissions)!=null&&s.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,ee).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,ee).permissions)==null?void 0:c.chatPublic)!=null&&d.files)||!((h=(l=a(this,ee).permissions)==null?void 0:l.chatPublic)!=null&&h.text)){this.logger.error("sendCustomMessage::permission_denied");return}const R=W=>u(this,null,function*(){try{if(typeof W=="string")return{link:W};const w=ht(),{getLocation:te,putLocation:re}=yield w.getPresignedUrls(W.name,a(this,ee).config.viewType);return yield w.uploadFile(W,re),{link:te,type:W.type,name:W.name,size:W.size}}catch{throw new I("Error sending image message.","0500",this.logger)}}),j=q(V({},t),{files:yield Promise.all((v=(m=t.files)!=null?m:[])==null?void 0:v.map(W=>u(this,null,function*(){return R(W)}))),images:yield Promise.all((T=(S=t.images)!=null?S:[])==null?void 0:T.map(W=>u(this,null,function*(){return R(W)}))),videos:yield Promise.all((b=(M=t.videos)!=null?M:[])==null?void 0:b.map(W=>u(this,null,function*(){return R(W)})))});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,s,n,o,c,d;if(((s=(i=a(this,ee).permissions)==null?void 0:i.chatMessage)==null?void 0:s.canEdit)==="NONE")throw new I("Not permitted to edit messages","0501");if(!((o=(n=a(this,ee).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,ee).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,s,n,o;if(!((s=(i=a(this,ee).permissions)==null?void 0:i.chatPublic)!=null&&s.canSend)||!((o=(n=a(this,ee).permissions)==null?void 0:n.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=ht(),{getLocation:d,putLocation:l}=yield c.getPresignedUrls(e.name,a(this,ee).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,s,n,o;if(!((s=(i=a(this,ee).permissions)==null?void 0:i.chatPublic)!=null&&s.canSend)||!((o=(n=a(this,ee).permissions)==null?void 0:n.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=ht(),{getLocation:d,putLocation:l}=yield c.getPresignedUrls(e.name,a(this,ee).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,ee).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,wc,ru))throw new I("Can`t pin message without joining room","0505");if(!a(this,ee).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,wc,ru))throw new I("Can`t unpin message without joining room","0505");if(!a(this,ee).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,s=void 0){return u(this,null,function*(){const n=yield a(this,ze).getChatMessagesPaginated(t,e,r,i,s);return{messages:n.messages.map(o=>ai.formatSocketServiceMessage(o)),next:n.next}})}createChannel(t,e){return u(this,arguments,function*(r,i,s={}){var n;const o=(n=a(this,ee).permissions)==null?void 0:n.chatChannel;if(o){if(o.canCreate==="NONE")throw new I("Not permitted to create channels","0501");if(s.visibility==="public"&&!(o.canCreate==="PUBLIC"||o.canCreate==="ALL"))throw new I("Not permitted to create public channels","0501");if(s.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,ee).userId])];return yield a(this,Ks).createChannel(r.trim(),c,s.displayPictureUrl,s.visibility,s.isDirectMessage)})}updateChannel(t,e){var r,i,s,n,o;const c=this.channels.find(h=>h.id===t),d=(r=a(this,ee).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:(s=e.displayName)!=null?s:c.displayName,displayPictureUrl:(n=e.displayPictureUrl)!=null?n:c.displayPictureUrl,visibility:(o=e.visibility)!=null?o:c.visibility};return a(this,Ks).updateChannel(t,l)}sendMessageToChannel(t,e){return u(this,arguments,function*(r,i,s={}){return this.sendMessageInternal(r,null,i,s)})}getChannelMembers(t){return u(this,null,function*(){return a(this,Ks).getChannelMembers(t)})}searchMessages(t){return u(this,arguments,function*(e,r={}){if(!a(this,zs).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(ai.formatSocketServiceMessage)})}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(s=>s.id===t?i:s),this.emit("channelMessageUpdate",i)}})}get pinned(){return this.messages.filter(t=>t.pinned)}},ee=new WeakMap,Js=new WeakMap,ze=new WeakMap,Ks=new WeakMap,zs=new WeakMap,tu=new WeakSet,Zm=function(){return a(this,zs).getValue("connectionHandler")},wc=new WeakSet,ru=function(){return a(this,tu,Zm).socketJoined===!0},eg);ft([k.trace("DyteChat.sendTextMessage"),Bt(Xc)],st.prototype,"sendTextMessage",1);ft([k.trace("DyteChat.sendImageMessage"),Bt({maxInvocations:20,period:60})],st.prototype,"sendImageMessage",1);ft([k.trace("DyteChat.sendFileMessage"),Bt({maxInvocations:20,period:60})],st.prototype,"sendFileMessage",1);ft([k.trace("DyteChat.sendMessage"),Bt({maxInvocations:180,period:60})],st.prototype,"sendMessage",1);ft([k.trace("DyteChat.editTextMessage")],st.prototype,"editTextMessage",1);ft([k.trace("DyteChat.editImageMessage")],st.prototype,"editImageMessage",1);ft([k.trace("DyteChat.editFileMessage")],st.prototype,"editFileMessage",1);ft([k.trace("DyteChat.editMessage")],st.prototype,"editMessage",1);ft([k.trace("DyteChat.deleteMessage")],st.prototype,"deleteMessage",1);ft([k.trace("DyteChat.createChannel")],st.prototype,"createChannel",1);ft([k.trace("DyteChat.updateChannel")],st.prototype,"updateChannel",1);ft([k.trace("DyteChat.sendMessageToChannel")],st.prototype,"sendMessageToChannel",1);ft([k.trace("DyteChat.getChannelMembers")],st.prototype,"getChannelMembers",1);ft([k.trace("DyteChat.searchMessages")],st.prototype,"searchMessages",1);ft([k.trace("DyteChat.markLastReadMessage")],st.prototype,"markLastReadMessage",1);st=ft([gt("0500")],st);var yD=Object.defineProperty,SD=Object.getOwnPropertyDescriptor,ED=(t,e,r,i)=>{for(var s=i>1?void 0:i?SD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&yD(e,r,s),s},Qi,tg;const ds=(tg=class{constructor(t,e,r,i,s){p(this,"chat"),p(this,"chatSocketHandler"),p(this,"chatChannelSocketHandler"),p(this,"self"),g(this,Qi,void 0),f(this,Qi,t),this.chatSocketHandler=e,this.chatChannelSocketHandler=r,this.chat=new st(t,e,r,i,s),this.self=i,this.setupEvents()}get telemetry(){return a(this,Qi).getValue("telemetry")}get logger(){return a(this,Qi).getValue("logger")}static init(t,e,r,i,s){return u(this,null,function*(){return new ds(t,e,r,i,s)})}static formatMessage(t){return q(V({},t),{time:new Date(t.time),type:vD[t.type]})}static formatSocketServiceMessage(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:s,size:n}=JSON.parse(t.payload);r.link=i,r.name=s,r.size=n;break}case _t.CUSTOM:{const{html:i,images:s,message:n,videos:o,files:c}=JSON.parse(t.payload);r.message=n,r.html=i,r.images=s,r.videos=o,r.files=c;break}}return ds.formatMessage(r)}getChatMessages(){return u(this,null,function*(){if(this.self.config.viewType==="LIVESTREAM"||this.self.config.viewType==="CHAT"||a(this,Qi).getValue("flagsmith").hasFeature(Z.FEAT_PAGINATED_CHAT))return;const t=yield this.chatSocketHandler.getChatMessages();if(!(t!=null&&t.payload))return;const e=Hv.fromBinary(t.payload).messages;this.chat.messages=e.map(r=>ds.formatSocketServiceMessage(r))})}setupEvents(){a(this,Qi).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){this.getChatMessages()})),this.chatSocketHandler.on(De.sendMessageToRoom,t=>{const e=ds.formatSocketServiceMessage(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=ds.formatSocketServiceMessage(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=ds.formatSocketServiceMessage(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(ws.createChatChannel,t=>{const[e]=t.chatChannels,r=Ls.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(ws.updateChatChannel,t=>{const[e]=t.chatChannels,r=Ls.formatChannel(e);this.chat.channels=this.chat.channels.map(i=>i.id===r.id?r:i),this.chat.emit("channelUpdate",r)})}},Qi=new WeakMap,tg);let ai=ds;ED([k.trace("ChatController.setupEvents")],ai.prototype,"setupEvents",1);var kD=Object.defineProperty,TD=Object.getOwnPropertyDescriptor,bD=(t,e,r,i)=>{for(var s=i>1?void 0:i?TD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&kD(e,r,s),s},iu,rg,su,ig,Ia,Ca,_c,sg;let eh=(sg=class extends Xt{constructor(t,e,r){const i=t.getValue("logger");super(i),g(this,iu),g(this,su),p(this,"items"),g(this,Ia,void 0),g(this,Ca,void 0),g(this,_c,void 0),f(this,_c,t),f(this,Ia,e),f(this,Ca,r),this.items=[]}create(t,e,r=!1,i=!1){return u(this,null,function*(){if(!a(this,su,ig))throw new I("Can't create polls without joining room","0705");if(!a(this,Ia).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,Ca).createPoll(t,e,r,i)})}vote(t,e){return u(this,null,function*(){if(!a(this,Ia).permissions.polls.canVote){this.logger.error("DytePolls::vote::permission_denied");return}yield a(this,Ca).votePoll(t,e)})}},iu=new WeakSet,rg=function(){return a(this,_c).getValue("connectionHandler")},su=new WeakSet,ig=function(){var t;return((t=a(this,iu,rg))==null?void 0:t.socketJoined)===!0},Ia=new WeakMap,Ca=new WeakMap,_c=new WeakMap,sg);eh=bD([gt("0700")],eh);var wD=Object.defineProperty,_D=Object.getOwnPropertyDescriptor,ID=(t,e,r,i)=>{for(var s=i>1?void 0:i?_D(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&wD(e,r,s),s},Xi,Pa,Ys,ng;const Sn=(ng=class{constructor(t,e,r){p(this,"polls"),g(this,Xi,void 0),g(this,Pa,void 0),g(this,Ys,void 0),this.polls=new eh(t,e,r),f(this,Pa,e),f(this,Xi,t),f(this,Ys,r),this.setupEvents()}get telemetry(){return a(this,Xi).getValue("telemetry")}get logger(){return a(this,Xi).getValue("logger")}static init(t,e,r){return u(this,null,function*(){return new Sn(t,e,r)})}canViewPolls(){return a(this,Pa).permissions.polls.canView}setupEvents(){const t={[Zr.createPoll]:i=>{i.poll&&this.updatePoll(Sn.formatSocketServicePoll(i.poll))},[Zr.updatePoll]:i=>{i.poll&&this.updatePoll(Sn.formatSocketServicePoll(i.poll))},[Zr.votePoll]:i=>{i.poll&&this.updatePoll(Sn.formatSocketServicePoll(i.poll))}},e=()=>{a(this,Xi).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(i=>{a(this,Ys).on(i,t[i])})},r=()=>{a(this,Xi).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(i=>{a(this,Ys).removeListeners(i)})};a(this,Pa).permissions.on("permissionsUpdate",i=>u(this,null,function*(){var s;(s=i==null?void 0:i.polls)!=null&&s.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,Ys).getPolls();if(!(t!=null&&t.payload))return;const{polls:e}=xA.fromBinary(t.payload);this.polls.items=e.map(r=>Sn.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}}},Xi=new WeakMap,Pa=new WeakMap,Ys=new WeakMap,ng);let Kv=Sn;ID([k.trace("PollController.setupEvents")],Kv.prototype,"setupEvents",1);var CD=Object.defineProperty,PD=Object.getOwnPropertyDescriptor,RD=(t,e,r,i)=>{for(var s=i>1?void 0:i?PD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&CD(e,r,s),s},zv=(t=>(t[t.User=0]="User",t[t.Meeting=1]="Meeting",t))(zv||{}),Ra,Ic,nu,Qs,Cc,ag;let th=(ag=class extends Xt{constructor(t,e,r,i,s){const n=t.getValue("logger");super(n),g(this,Ic),p(this,"selfActiveTab"),p(this,"broadcastTabChanges"),g(this,Ra,void 0),g(this,Qs,void 0),g(this,Cc,void 0),p(this,"viewType"),p(this,"meetingStartedTimestamp"),p(this,"meetingTitle"),p(this,"sessionId"),f(this,Ra,t),f(this,Qs,e),this.viewType=r,f(this,Cc,i),this.meetingTitle=s,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,Ic,nu).socketState}get mediaState(){return a(this,Ic,nu).mediaState}get meetingId(){return a(this,Ra).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,Qs).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,Qs).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,Cc).broadcastMessage("spotlight",{userId:a(this,Qs).userId,currentTab:this.selfActiveTab})}},Ra=new WeakMap,Ic=new WeakSet,nu=function(){return a(this,Ra).getValue("connectionHandler")},Qs=new WeakMap,Cc=new WeakMap,ag);th=RD([gt("0800")],th);function MD(t){let e="",r=[""];const i=[r];let s=0,n=0,o=!0,c;for(c of t)c==='"'?(o&&c===e&&(r[s]+=c),o=!o):c===","&&o?c=r[++s]="":c===`
16
16
  `&&o?(e==="\r"&&(r[s]=r[s].slice(0,-1)),r=i[++n]=[c=""],s=0):r[s]+=c,e=c;return i}var AD=Object.defineProperty,DD=Object.getOwnPropertyDescriptor,Yv=(t,e,r,i)=>{for(var s=i>1?void 0:i?DD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&AD(e,r,s),s},Pc,og;let Wi=(og=class extends Xt{constructor(t){const e=t.getValue("logger");super(e),p(this,"transcripts"),g(this,Pc,void 0),f(this,Pc,t),this.transcripts=[]}get telemetry(){return a(this,Pc).getValue("telemetry")}static init(t,e){return u(this,null,function*(){const r=new Wi(t),i=t.getValue("logger");try{e&&r.getActiveTranscript()}catch(s){i.error("Error fetching active transcriptions ",s)}return r})}static parseTranscript(t,e=!1){if(!t)return;const[[r,i,s,n,o,c]]=MD(t);return{id:Ns(),name:o,peerId:i,userId:s,customParticipantId:n,transcript:c,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}static parseTranscripts(t){return t?t.split(`
17
- `).map(e=>Wi.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=ht(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=Wi.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)})}},Pc=new WeakMap,og);Yv([k.trace("DyteAi.getActiveTranscript")],Wi.prototype,"getActiveTranscript",1);Wi=Yv([gt("0000")],Wi);var OD=Object.defineProperty,ND=Object.getOwnPropertyDescriptor,VD=(t,e,r,i)=>{for(var s=i>1?void 0:i?ND(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&OD(e,r,s),s},Zi,Ma,rr,cg;const Qv=(cg=class{constructor(t,e,r,i,s,n){p(this,"meta"),p(this,"ai"),g(this,Zi,void 0),g(this,Ma,void 0),p(this,"aiSocketHandler"),g(this,rr,void 0),f(this,rr,t),this.meta=new th(t,e,e.config.viewType,r,n),this.ai=i,f(this,Zi,e),f(this,Ma,r),this.aiSocketHandler=s,e.config.viewType!==Ft.Chat&&this.setupEvents()}get telemetry(){return a(this,rr).getValue("telemetry")}get logger(){return a(this,rr).getValue("logger")}static init(t,e,r,i,s){return u(this,null,function*(){const n=yield Wi.init(t,e.permissions.transcriptionEnabled);return new Qv(t,e,r,n,i,s)})}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,zv.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){a(this,rr).getValue("peerSessionStore").on(P.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),a(this,rr).getValue("peerSessionStore").on(P.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),a(this,rr).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,rr).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),a(this,Zi).permissions.canSpotlight&&(this.logger.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,Ma).broadcastMessage("spotlight",{userId:a(this,Zi).userId,currentTab:this.meta.selfActiveTab})),a(this,rr).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){a(this,Zi).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,Ma).broadcastToPeers("spotlight",[t.id],{userId:a(this,Zi).userId,currentTab:this.meta.selfActiveTab})})),a(this,rr).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,rr).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 s;try{s=Wi.parseTranscript(r,i)}catch(d){this.logger.error(`Failed to parse transcript: ${r}`,d)}if(!s){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(s),this.meta.emit("transcript",s);const{peerId:n,name:o,transcript:c}=s;this.logger.debug(`${e} Received transcript for peer ${n} - ${o}: ${c}`)})}},Zi=new WeakMap,Ma=new WeakMap,rr=new WeakMap,cg);let Xv=Qv;VD([k.trace("MetaController.setupEvents")],Xv.prototype,"setupEvents",1);var LD=Object.defineProperty,xD=Object.getOwnPropertyDescriptor,Gs=(t,e,r,i)=>{for(var s=i>1?void 0:i?xD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&LD(e,r,s),s},vr,co,ce,Zc,Kr,wt,ed,rh,lo,td;class qi extends Xt{constructor(e,r,i,s,n){const o=e.getValue("logger");super(o),g(this,ed),g(this,lo),g(this,vr,void 0),g(this,co,void 0),g(this,ce,void 0),g(this,Zc,void 0),g(this,Kr,void 0),g(this,wt,void 0),f(this,wt,e),f(this,vr,s),f(this,co,n),f(this,ce,r),f(this,Zc,i),f(this,Kr,[]),this.setupEvents()}get telemetry(){return a(this,wt).getValue("telemetry")}get status(){return a(this,wt).getValue("stageStatus")}setupEvents(){const e={[P.GET_STAGE_REQUESTS]:s=>u(this,null,function*(){f(this,Kr,s)}),[P.UPDATE_STAGE_REQUESTS]:s=>u(this,[s],function*({add:n}){const o=a(this,Kr).length,{stageRequests:c}=this.getAccessRequests();(n||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)})},r=()=>{Object.entries(e).forEach(([s,n])=>{a(this,wt).getValue("peerSessionStore").onAsync(s,n)})},i=()=>{Object.entries(e).forEach(([s,n])=>{a(this,wt).getValue("peerSessionStore").removeListener(s,n)})};a(this,ce).permissions.on("permissionsUpdate",s=>{const{canAcceptProductionRequests:n}=s;n!==void 0&&(a(this,ce).permissions.acceptStageRequests?(r(),a(this,vr).getStageRequests()):(i(),f(this,Kr,[]),this.emit("stageAccessRequestUpdate",a(this,Kr))))}),a(this,ce).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,ce).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ce).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,Zc).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return f(this,Kr,e),{stageRequests:a(this,Kr)}}requestAccess(){return u(this,null,function*(){if(!a(this,ce).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,ce).permissions.stageAccess===G.Allowed){U(this,lo,td).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,vr).requestAccess(),U(this,lo,td).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return u(this,null,function*(){if(!a(this,ce).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");a(this,vr).cancelRequestAccess(),U(this,lo,td).call(this,"OFF_STAGE")})}grantAccess(e){if(!a(this,ce).roomJoined)throw new I("Can`t grant for participant without joining room");if(!a(this,ce).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ce).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,vr).grantAccess(e)}denyAccess(e){if(!a(this,ce).roomJoined)throw new I("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,ce).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ce).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,vr).denyAccess(e)}join(){return u(this,null,function*(){const e=a(this,wt).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,ce).permissions.stageAccess===G.NotAllowed)throw new I(`Unable to join stage you are currently ${this.status}`,"2006");if(yield a(this,vr).joinStage(),e===Ft.Livestream){yield a(this,co).joinRoom(a(this,ce));const{peers:r}=yield a(this,co).getStagePeers();a(this,wt).getValue("peerSessionStore").emit(P.SOCKET_PEERS,r)}a(this,wt).setValue("stageStatus","ON_STAGE"),a(this,ce).audioEnabled&&a(this,ed,rh).shareMic(a(this,ce).audioTrack),a(this,ce).videoEnabled&&a(this,ed,rh).shareWebcam(a(this,ce).videoTrack)})}leave(){return u(this,null,function*(){if(!a(this,ce).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,ce).setIsPinned(!1),yield a(this,vr).leaveStage(a(this,ce).userId),a(this,wt).setValue("stageStatus","OFF_STAGE",!1),yield a(this,wt).getValue("peerSessionStore").emitAsync(P.LEAVE_MEDIA_ROOM,"stageLeft"),a(this,wt).notify("stageStatus")})}kick(e){return u(this,null,function*(){if(!a(this,ce).roomJoined)throw new I("Can`t kick participant without joining room","2005");if(!a(this,ce).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ce).permissions.acceptStageRequests)throw this.logger.error("DyteStage::kick::permission_denied"),new I("You do not have permissions for kick","2001");return a(this,vr).kick(e)})}}vr=new WeakMap,co=new WeakMap,ce=new WeakMap,Zc=new WeakMap,Kr=new WeakMap,wt=new WeakMap,ed=new WeakSet,rh=function(){return a(this,wt).getValue("roomNodeClient")},lo=new WeakSet,td=function(t){return u(this,null,function*(){this.status!==t&&a(this,wt).setValue("stageStatus",t)})};Gs([k.trace("DyteStage.getStageRequests")],qi.prototype,"getAccessRequests",1);Gs([k.trace("DyteStage.requestAccess")],qi.prototype,"requestAccess",1);Gs([k.trace("DyteStage.cancelRequestAccess")],qi.prototype,"cancelRequestAccess",1);Gs([k.trace("DyteStage.grantAccess")],qi.prototype,"grantAccess",1);Gs([k.trace("DyteStage.denyAccess")],qi.prototype,"denyAccess",1);Gs([k.trace("DyteStage.joinStage")],qi.prototype,"join",1);Gs([k.trace("DyteStage.leaveStage")],qi.prototype,"leave",1);function UD(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function gp(t){switch(t){case ii.UNSPECIFIED:return"OFF_STAGE";case ii.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case ii.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case ii.OFF_STAGE:return"OFF_STAGE";case ii.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var FD=Object.defineProperty,BD=Object.getOwnPropertyDescriptor,WD=(t,e,r,i)=>{for(var s=i>1?void 0:i?BD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&FD(e,r,s),s},ls,En,us,rd,Lt;class Zv{constructor(e,r,i,s,n){p(this,"stage"),g(this,ls,void 0),g(this,En,void 0),g(this,us,void 0),g(this,rd,0),g(this,Lt,void 0),f(this,Lt,e),this.stage=new qi(e,s,n,r,i),f(this,us,r),f(this,ls,s),f(this,En,n),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,us).on(F.grantStageAccess,()=>{a(this,ls).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,us).on(F.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===a(this,ls).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),a(this,us).on(F.denyStageAccess,()=>{a(this,ls).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,us).on(F.getStageRequests,e=>u(this,null,function*(){var r;if(a(this,ls).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,rd)<i.length&&i.length>0&&this.stage.emit("newStageRequest",{count:i.length}),f(this,rd,i.length),this.stage.emit("stageAccessRequestUpdate",i)}))}getCurrentStageRequests(){return a(this,En).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=gp(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,En).joined.get(e.peerId),i=a(this,En).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);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);break}a(this,Lt).getValue("peerSessionStore").emit(P.UPDATE_PEER_STAGE_STATUS,{id:r.id,status:r.stageStatus})})}}ls=new WeakMap,En=new WeakMap,us=new WeakMap,rd=new WeakMap,Lt=new WeakMap;WD([k.trace("DyteStage.setupEvents")],Zv.prototype,"setupEvents",1);var jD=Object.defineProperty,HD=Object.getOwnPropertyDescriptor,Cl=(t,e,r,i)=>{for(var s=i>1?void 0:i?HD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&jD(e,r,s),s};const Ve={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};var vt,ir,Aa,Da,pi,Oa,es,Na,dg;let ta=(dg=class extends ia{constructor(t,{baseURL:e,createdAt:r,description:i,id:s,name:n,organizationId:o,picture:c,private:d,published:l,staggered:h,tags:m,type:v,updatedAt:S},T,M,b,R,j){const W=t.getValue("logger");super(W),g(this,vt,void 0),p(this,"baseURL"),p(this,"createdAt"),p(this,"description"),p(this,"id"),p(this,"name"),g(this,ir,void 0),g(this,Aa,void 0),g(this,Da,void 0),p(this,"organizationId"),p(this,"picture"),p(this,"private"),p(this,"published"),p(this,"staggered"),p(this,"tags"),p(this,"type"),p(this,"updatedAt"),g(this,pi,void 0),p(this,"config"),g(this,Oa,void 0),p(this,"active"),p(this,"iframes"),p(this,"enabledBy"),g(this,es,void 0),g(this,Na,void 0),f(this,es,t),this.baseURL=e,this.createdAt=new Date(r),this.description=i,this.id=s,this.name=n,f(this,ir,M),this.organizationId=o,this.picture=c,this.private=d,this.published=l,this.staggered=h,this.tags=m,this.type=v,this.updatedAt=new Date(S),this.active=!1,this.iframes=new Map,f(this,vt,T),f(this,Aa,b),f(this,Da,R),this.enabledBy="",f(this,Na,j)}get telemetry(){return a(this,es).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:s,type:n}=r;switch(n){case $.customPluginEventToRoom:{a(this,vt).customPluginEventToRoom(this.id,i,s);break}case $.customPluginEventToPeers:{a(this,vt).customPluginEventToPeers(this.id,i.peerIds,i,s);break}case $.enablePluginForRoom:{a(this,vt).enablePluginForRoom(this.id,s);break}case $.enablePluginForPeers:{a(this,vt).enablePluginForPeers(this.id,i.peerIds,s);break}case $.disablePluginForRoom:{a(this,vt).disablePluginForRoom(this.id,s);break}case $.disablePluginForPeers:{a(this,vt).disablePluginForPeers(this.id,i.peerIds,s);break}case $.storeInsertKeys:{a(this,vt).storeInsertKeys(this.id,i.store,i.insertKeys,s);break}case $.storeGetKeys:{a(this,vt).storeGetKeys(this.id,i.store,i.getKeys,s);break}case $.storeDeleteKeys:{a(this,vt).storeDeleteKeys(this.id,i.store,i.deleteKeys,s);break}case $.storeDelete:{a(this,vt).storeDelete(this.id,i.store,s);break}case Ve.chatMessage:{const{messagePayload:o,peerIds:c}=i;if(!a(this,Da)){this.sendIframeEvent({type:Ve.chatMessage,uuid:r.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield a(this,Da).sendMessage(o,c),this.sendIframeEvent({type:Ve.chatMessage,uuid:r.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:Ve.chatMessage,uuid:r.uuid,payload:{error:d}})}break}case Ve.getPeer:{let o;const{peerId:c}=i,d=q(V({},a(this,ir)),{id:a(this,ir).id,isRecorder:(e=a(this,ir).permissions)==null?void 0:e.isRecorder,isHidden:a(this,ir).permissions.hiddenParticipant,stageStatus:a(this,ir).stageStatus});c?(o=a(this,Aa).joined.get(i.peerId),a(this,ir).id===c&&(o=d)):o=d,this.sendIframeEvent({type:Ve.getPeer,payload:{peer:o&&Xd(o)},uuid:r.uuid});break}case Ve.getPeers:{const o=a(this,Aa).joined.toArray().map(c=>Xd(c));this.sendIframeEvent({type:Ve.getPeers,payload:{peers:o},uuid:r.uuid});break}case Ve.getPluginInitiator:{this.sendIframeEvent({type:Ve.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:r.uuid});break}case Ve.getDisplayTitle:{this.sendIframeEvent({type:Ve.getDisplayTitle,payload:{displayTitle:a(this,Na)},uuid:r.uuid});break}case Ve.getRoomName:{this.sendIframeEvent({type:Ve.getRoomName,payload:{roomName:a(this,es).getValue("meetingId")},uuid:r.uuid});break}case Ve.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:Ve.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,Oa))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,s=new URL(this.baseURL),n={auth:a(this,Oa),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:a(this,es).getValue("apiBase"),pluginId:this.id,roomName:(r=a(this,es).getValue("meetingId"))!=null?r:"",displayTitle:a(this,Na)};if(Object.keys(n).forEach(o=>{s.searchParams.set(o,n[o])}),i.src=s.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=ht(),e=yield t.authorizePlugin(this.id);f(this,Oa,e),f(this,pi,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,pi,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,ir).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(a(this,vt).addPlugin(this.id,this.staggered),f(this,pi,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,ir).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==a(this,ir).id||(a(this,vt).removePlugin(this.id),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:a(this,pi)?new Date().getTime()-a(this,pi).getTime():0}}),f(this,pi,void 0)))})}},vt=new WeakMap,ir=new WeakMap,Aa=new WeakMap,Da=new WeakMap,pi=new WeakMap,Oa=new WeakMap,es=new WeakMap,Na=new WeakMap,dg);Cl([Bt({maxInvocations:5,period:1})],ta.prototype,"sendData",1);Cl([k.trace("DytePlugin.activatePlugin")],ta.prototype,"activate",1);Cl([k.trace("DytePlugin.deactivatePlugin")],ta.prototype,"deactivate",1);ta=Cl([gt("0600")],ta);var Ke,kn;class ey extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:s,onClearEvent:n}=e;super(),g(this,Ke,void 0),g(this,kn,void 0),p(this,"onAddEvent"),p(this,"onDeleteEvent"),p(this,"onClearEvent"),f(this,Ke,new ia(r)),this.onAddEvent=i,this.onDeleteEvent=s,this.onClearEvent=n,f(this,kn,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 s=super.set(e,r),n=(o,...c)=>{this.emit(o,r,...c)};return a(this,kn).set(e,n),r.on("*",n),i&&a(this,Ke).emit(this.onAddEvent,r),s}delete(e,r=!0,i=!1){const s=this.get(e);if(!s)return!1;s.removeListener("*",a(this,kn).get(e));const n=super.delete(e);return i&&s.removeAllListeners(),r&&a(this,Ke).emit(this.onDeleteEvent,s),n}clear(e=!0,r=!1){this.forEach(s=>{s.removeListener("*",a(this,kn).get(s.id)),r&&s.removeAllListeners()});const i=super.clear();return e&&a(this,Ke).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Ke=new WeakMap,kn=new WeakMap;class lg extends ey{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 GD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,$D=(t,e,r,i)=>{for(var s=i>1?void 0:i?qD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&GD(e,r,s),s};let ih=class{constructor(t){p(this,"all"),p(this,"active"),this.all=new lg(t),this.active=new lg(t)}};ih=$D([gt("0600")],ih);var JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,Pl=(t,e,r,i)=>{for(var s=i>1?void 0:i?KD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&JD(e,r,s),s},ur,Va,Ar,ug;const ty=(ug=class{constructor(t,e,r,i){p(this,"plugins"),g(this,ur,void 0),g(this,Va,void 0),g(this,Ar,void 0),f(this,ur,e),f(this,Va,r),f(this,Ar,t),this.plugins=i,this.setupEvents()}get telemetry(){return a(this,Ar).getValue("telemetry")}get logger(){return a(this,Ar).getValue("logger")}static init(t,e,r,i,s,n,o,c){return u(this,null,function*(){const d=t.getValue("logger"),l=new ih(d);return e.forEach(h=>{const m=new ta(t,h,r,n,o,s,c);l.all.add(m)}),new ty(t,r,i,l)})}getRoomPlugins(){return u(this,null,function*(){var t;const{plugins:e}=yield a(this,ur).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 s=this.plugins.all.get(e);s&&s.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,Ar).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,ur).on($.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,ur).on($.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}))})),[$.enablePluginForPeers,$.enablePluginForRoom].forEach(t=>{a(this,ur).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{enabledBy:e.enabledBy})}))}),[$.disablePluginForPeers,$.disablePluginForRoom].forEach(t=>{a(this,ur).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{disabledBy:e.disabledBy})}))}),[$.customPluginEventToPeers,$.customPluginEventToRoom].forEach(t=>{a(this,ur).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[$.storeInsertKeys,$.storeGetKeys,$.storeDeleteKeys].forEach(t=>{a(this,ur).on(t,(e,r)=>u(this,null,function*(){var i;const s=(i=e.storeItems)==null?void 0:i.map(n=>{var o;return{timestamp:n.timestamp,peerId:n.peerId,payload:JSON.parse((o=n.payload)!=null&&o.length?new TextDecoder().decode(n.payload):"{}"),key:n.storeKey}});this.sendIframeEvent(t,e.pluginId,r,{storeName:e.storeName,storeItems:s})}))}),a(this,ur).on($.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent($.storeDelete,t.pluginId,e,{storeName:t.storeName})})),a(this,Va).on(De.sendMessageToPeers,t=>{const e=ai==null?void 0:ai.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ve.chatMessage,{message:e})}),a(this,Va).on(De.sendMessageToRoom,t=>{const e=ai==null?void 0:ai.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ve.chatMessage,{message:e})}),a(this,Ar).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,t=>{const e=Xd(t);this.broadcastIframeEvent(Ve.peerJoined,e)}),a(this,Ar).getValue("peerSessionStore").on(P.PEER_CLOSED,t=>{this.broadcastIframeEvent(Ve.peerLeft,t)}),a(this,Ar).getValue("peerSessionStore").on(P.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(Ve.peerStageStatusUpdate,t)}),a(this,Ar).subscribe("stageStatus",t=>{this.broadcastIframeEvent(Ve.stageStatusUpdate,t)})}},ur=new WeakMap,Va=new WeakMap,Ar=new WeakMap,ug);let ac=ty;Pl([k.trace("PluginController.getRoomPlugins")],ac.prototype,"getRoomPlugins",1);Pl([k.trace("PluginController.enableForSelf")],ac.prototype,"enablePlugin",1);Pl([k.trace("PluginController.disableForSelf")],ac.prototype,"disablePlugin",1);Pl([k.trace("PluginController.setupEvents")],ac.prototype,"setupEvents",1);var id;class zD{constructor(e){p(this,"mediaJoined"),p(this,"socketJoined"),p(this,"socketJoinAttempted"),p(this,"mediaJoinAttempted"),p(this,"socketState"),p(this,"mediaState"),g(this,id,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,id,e)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(e,r){let i;const{reconnected:s}=this.socketState;switch(e){case"connected":i={state:"connected",reconnected:s,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:s,reconnectionAttempt:0};break;case"reconnectAttempt":i={state:"reconnecting",reconnected:s,reconnectionAttempt:r};break;case"failed":i={state:"failed",reconnected:s,reconnectionAttempt:void 0},this.socketJoined=!1;break}i&&(a(this,id).getValue("peerSessionStore").emit(P.SOCKET_STATE_UPDATE,i),this.socketState=i)}}id=new WeakMap;var YD=Object.defineProperty,QD=Object.getOwnPropertyDescriptor,oc=(t,e,r,i)=>{for(var s=i>1?void 0:i?QD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&YD(e,r,s),s},La,xa,Ua,Rc,hg;let xs=(hg=class extends Xt{constructor(t,e){const r=t.getValue("logger");super(r),g(this,Ua),g(this,La,void 0),g(this,xa,void 0),p(this,"recordingPeerIds",[]),p(this,"recordings",[]),f(this,xa,t),f(this,La,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,xa).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}start(t){return u(this,null,function*(){if(!a(this,La).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=ht(),{recording:r={}}=a(this,xa).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,Ua,Rc).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield U(this,Ua,Rc).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield U(this,Ua,Rc).call(this,"resume",["PAUSED"],t)})}},La=new WeakMap,xa=new WeakMap,Ua=new WeakSet,Rc=function(t,e,r){return u(this,null,function*(){if(!a(this,La).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 s=this.recordings.find(n=>n.id===r);if(s===void 0)throw new I("Could not find the specified recording","1004");if(e.includes(s.state)){this.logger.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:s.state}});return}i.push(s)}else i=this.recordings.filter(s=>e.includes(s.state));i.forEach(s=>u(this,null,function*(){const n=s.state;t==="stop"&&(s.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield ht().updateRecording(s.id,t)}catch(o){throw this.logger.error("DyteRecording::stop::recording_failed_to_stop",{error:o}),s.state!==n&&(s.state=n,this.emit("recordingUpdate",n)),new I("Error while stopping recording","1000",this.logger)}}))})},hg);oc([k.trace("DyteRecording.start")],xs.prototype,"start",1);oc([k.trace("DyteRecording.stop")],xs.prototype,"stop",1);oc([k.trace("DyteRecording.stop")],xs.prototype,"pause",1);oc([k.trace("DyteRecording.stop")],xs.prototype,"resume",1);xs=oc([gt("1000")],xs);var XD=Object.defineProperty,ZD=Object.getOwnPropertyDescriptor,eO=(t,e,r,i)=>{for(var s=i>1?void 0:i?ZD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&XD(e,r,s),s},Tn;class ry{constructor(e,r,i){p(this,"recording"),p(this,"room"),g(this,Tn,void 0),f(this,Tn,e),this.recording=new xs(e,r),this.room=i,this.setupEvents()}get telemetry(){return a(this,Tn).getValue("telemetry")}get logger(){return a(this,Tn).getValue("logger")}getRecordingTypeFromProtoType(e){let r;switch(e){case Os.BROWSER:r="BROWSER";break;case Os.COMPOSITE:r="COMPOSITE";break;case Os.TRACK:r="TRACK";break;default:r="BROWSER"}return r}setupEvents(){a(this,Tn).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(s=>{s.id===e.recordingId&&(r=!0,s.state="RECORDING")}),r===!1){const s=this.getRecordingTypeFromProtoType(e.recordingType);i.push({id:e.recordingId,state:"RECORDING",type:s})}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)})}}Tn=new WeakMap;eO([k.trace("RecordingController.setupEvents")],ry.prototype,"setupEvents",1);var bn;class tO{constructor(e){g(this,bn,void 0),f(this,bn,e)}hasFeature(e){var r;return(r=a(this,bn).getValue("flagsmith").hasFeature(e))!=null?r:!1}getFeatureValue(e){return a(this,bn).getValue("flagsmith").getValue(e)}getAllFeatures(){return a(this,bn).getValue("flagsmith").getAllFlags()}}bn=new WeakMap;class fp{constructor(e,r,i){p(this,"logger"),p(this,"features"),p(this,"browserSpecs"),p(this,"callStats"),this.logger=e,this.features=r,this.browserSpecs=Ie,this.callStats=i}static init(e){return new fp(e.getValue("logger"),new tO(e),e.getValue("callstats"))}}class vp{constructor(e){p(this,"internals"),this.internals=e}static init(e){return u(this,null,function*(){const r=fp.init(e);return new vp(r)})}}var rO=Object.defineProperty,iO=Object.getOwnPropertyDescriptor,er=(t,e,r,i)=>{for(var s=i>1?void 0:i?iO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&rO(e,r,s),s},tt,Ce,be,Ii,yr,sd,Be;class Wt extends ia{constructor(e,r,i=sh,s=!0){const n=e.getValue("logger");super(n),g(this,tt,void 0),g(this,Ce,void 0),g(this,be,void 0),g(this,Ii,void 0),g(this,yr,void 0),g(this,sd,void 0),g(this,Be,void 0),p(this,"audioUpdateInProgress"),p(this,"videoUpdateInProgress"),f(this,Be,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,f(this,tt,new iy(e,r)),f(this,Ce,new _O(e,a(this,tt),void 0,i)),f(this,be,new DO(e,a(this,tt),void 0,i)),f(this,yr,new RO(a(this,Be),a(this,tt))),f(this,Ii,new CO(a(this,tt))),f(this,sd,s),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,yr).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,Be).getValue("telemetry")}set context(e){f(this,Be,e)}onVisibilityChange(){return u(this,null,function*(){a(this,Be).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,Be).getValue("callstats").browserBackgrounded():(a(this,Be).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 s;r?a(this,Be).getValue("callstats").audioOn():a(this,Be).getValue("callstats").audioOff(),i?a(this,Be).getValue("callstats").videoOn():a(this,Be).getValue("callstats").videoOff();let n,o;if(r&&i)try{const c=yield a(this,tt).getAudioAndVideoTrack(a(this,Ce).userSelectedDevice,a(this,be).userSelectedDevice);n=c.audioTrack,o=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!n&&r)try{n=yield a(this,tt).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,tt).getVideoTrack(a(this,be).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}r&&!n&&a(this,Be).getValue("callstats").audioOff(),i&&!o&&a(this,Be).getValue("callstats").videoOff(),yield a(this,Ce).setMediaTrack(n),yield a(this,be).setMediaTrack(o);try{this.setupSpeaker()}catch{}if(o){const c=yield this.getDeviceById(o.getSettings().deviceId);a(this,Be).getValue("callstats").selectedDevice("VIDEO",c)}if(n){const c=yield this.getDeviceById(n.getSettings().deviceId);a(this,Be).getValue("callstats").selectedDevice("AUDIO",c)}(s=a(this,Ii).currentDevice)!=null&&s.deviceId&&a(this,Be).getValue("callstats").selectedDevice("SPEAKER",a(this,Ii).currentDevice),a(this,tt).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})})}getCurrentDevices(){return{audio:a(this,Ce).currentDevice,video:a(this,be).currentDevice,speaker:a(this,Ii).currentDevice}}get permissions(){return a(this,tt).permissions}getAllDevices(){return a(this,tt).getAvailableDevices()}getDeviceById(e,r){return a(this,tt).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,tt).getAudioInputDevices(e)}setAudioDevice(e){return u(this,null,function*(){yield a(this,Ce).setDevice(e),e!=null&&e.deviceId&&a(this,Be).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return u(this,null,function*(){yield a(this,Ii).setupSpeaker();const{speaker:e}=this.getCurrentDevices();e&&this.emit("DEVICE_CHANGE",{device:e})})}setSpeakerDevice(e){return u(this,null,function*(){yield a(this,Ii).setupSpeaker(e),e!=null&&e.deviceId&&a(this,Be).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,tt).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield a(this,be).setDevice(e),e!=null&&e.deviceId&&a(this,Be).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,yr).audioMediaTrack,video:a(this,yr).videoMediaTrack}}get screenShareEnabled(){return a(this,yr).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield a(this,yr).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){a(this,yr).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield a(this,yr).updateConstraints(e)})}getSpeakerDevices(e){return a(this,tt).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,yr).disableScreenShare(),a(this,tt).destruct()}onDeviceChange(e,r){return u(this,null,function*(){var i,s;this.emit("DEVICE_LIST_UPDATED",e),!(r||!a(this,sd))&&((i=e==null?void 0:e.added)==null||i.forEach(n=>u(this,null,function*(){var o;n&&!sh(n)&&(n.kind==="audioinput"&&((o=this.audioTrack)==null?void 0:o.enabled)===!0?yield this.setAudioDevice(n):n.kind==="audiooutput"&&(yield this.setSpeakerDevice(n)))})),(s=e==null?void 0:e.removed)==null||s.forEach(n=>u(this,null,function*(){var o;if(n.kind==="audiooutput"&&((o=this.getCurrentDevices().speaker)==null?void 0:o.deviceId)===n.deviceId){const c=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==n.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)})}}tt=new WeakMap,Ce=new WeakMap,be=new WeakMap,Ii=new WeakMap,yr=new WeakMap,sd=new WeakMap,Be=new WeakMap;er([k.trace("MediaHandler.setupStreams")],Wt.prototype,"setupStreams",1);er([k.trace("MediaHandler.enableAudio")],Wt.prototype,"enableAudio",1);er([k.trace("MediaHandler.disableAudio")],Wt.prototype,"disableAudio",1);er([k.trace("MediaHandler.setAudioDevice")],Wt.prototype,"setAudioDevice",1);er([k.trace("MediaHandler.enableVideo")],Wt.prototype,"enableVideo",1);er([k.trace("MediaHandler.disableVideo")],Wt.prototype,"disableVideo",1);er([k.trace("MediaHandler.setVideoDevice")],Wt.prototype,"setVideoDevice",1);er([k.trace("MediaHandler.updateVideoConstraints")],Wt.prototype,"updateVideoConstraints",1);er([k.trace("MediaHandler.enableScreenShare")],Wt.prototype,"enableScreenShare",1);er([k.trace("MediaHandler.disableScreenShare")],Wt.prototype,"disableScreenShare",1);er([k.trace("MediaHandler.updateScreenshareConstraints")],Wt.prototype,"updateScreenshareConstraints",1);er([k.trace("MediaHandler.destruct")],Wt.prototype,"destruct",1);er([k.trace("MediaHandler.onDeviceChange")],Wt.prototype,"onDeviceChange",1);function Mc(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 sO=["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:sO.some(s=>i==null?void 0:i.includes(s))}function nO(t,e,r){return u(this,null,function*(){if(!(e!=null&&e.length))return r;const i=t.getValue("logger"),s=new AudioContext,n=yield Promise.all(e==null?void 0:e.map(d=>d(s))),o=s.createMediaStreamSource(new MediaStream([r])),c=s.createMediaStreamDestination();try{let d=o;for(let l=0;l<n.length;l+=1)d.connect(n[l]),d=n[l];d.connect(c)}catch(d){return i.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),r}return c.stream.getAudioTracks()[0]})}var wn,nd;class aO{constructor(e){g(this,wn,void 0),g(this,nd,void 0),f(this,nd,e)}get logger(){return a(this,nd).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,wn))try{Bn(a(this,wn)),f(this,wn,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 s=document.createElement("canvas"),n=yield Promise.all(e==null?void 0:e.map(m=>m({canvas:s,WorkerTimers:$S})));if(i.disablePerFrameCanvasRendering){const m=s.captureStream().getVideoTracks()[0];return Object.defineProperty(m,"originalSettings",{value:r.getSettings()}),m}const o=document.createElement("video"),c=new MediaStream;c.addTrack(r);const d=s.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(),s.remove();return}try{d.drawImage(o,0,0);for(let m=0;m<n.length;m+=1)typeof n[m]=="function"&&(yield n[m](s,d))}catch(m){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:m})}});try{o.play()}catch{}o.addEventListener("play",()=>{s.width=o.width||r.getSettings().width,s.height=o.width||r.getSettings().height,f(this,wn,Wd(l,50))},!1);const h=s.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:r.getSettings()}),h})}}wn=new WeakMap,nd=new WeakMap;const pg={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}}},oO=[[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"}]]],cO=(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 s=oO;t.getValue("flagsmith").hasFeature(Z.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)&&(s=JSON.parse(t.getValue("flagsmith").getValue(Z.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)));const n=s.map(([d])=>d).sort((d,l)=>d-l);let o=Number.MAX_VALUE,c=0;return n.forEach((d,l)=>{Math.abs(d-i)<o&&(o=Math.abs(d-i),c=l)}),s[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 dO=Zw(),Xs=_r(dO.config.media);function lO(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 _n,zr;class uO{constructor(e,r){g(this,_n,void 0),g(this,zr,void 0),p(this,"getScreenShareConstraints",()=>{var i,s,n,o,c,d,l,h,m,v,S;const T=(i=a(this,_n))==null?void 0:i.screenshare,M=(n=(s=T==null?void 0:T.width)==null?void 0:s.max)!=null?n: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=(m=(h=T==null?void 0:T.frameRate)==null?void 0:h.ideal)!=null?m:5;const W=T==null?void 0:T.displaySurface,w=T==null?void 0:T.selfBrowserSurface;a(this,zr).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE)&&(j=parseInt((v=a(this,zr).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE))==null?void 0:v.toString(),10));let te={width:{max:M},height:{max:b},frameRate:{ideal:j,max:R}};if(a(this,zr).getValue("flagsmith").hasFeature(Z.SCREENSHARE_CONSTRAINTS)){const re=(S=a(this,zr).getValue("flagsmith").getValue(Z.SCREENSHARE_CONSTRAINTS))==null?void 0:S.toString();te=JSON.parse(re)}return W!==void 0&&["monitor","browser","window"].includes(W)&&(te=q(V({},te),{displaySurface:W})),w!==void 0&&(te=q(V({},te),{selfBrowserSurface:w})),{audio:!0,video:te}}),p(this,"getAudioConstraints",i=>{var s,n,o,c,d,l,h,m;const v={},S=(s=a(this,_n))==null?void 0:s.audio,T=S!=null&&S.enableStereo?2:1;return Ie.isFirefox()||Ie.isWebKitBased()?(v.audio={deviceId:i,autoGainControl:(n=S==null?void 0:S.autoGainControl)!=null?n:!0,echoCancellation:(o=S==null?void 0:S.echoCancellation)!=null?o:!0,noiseSuppression:(c=S==null?void 0:S.noiseSupression)!=null?c:!0,channelCount:T},v):(v.audio={},v.audio.optional=[i?{sourceId:i}:{sourceId:"default"},{channelCount:T},{echoCancellation:(d=S==null?void 0:S.echoCancellation)!=null?d:!0},{googEchoCancellation:(l=S==null?void 0:S.echoCancellation)!=null?l:!0},{googAutoGainControl:(h=S==null?void 0:S.autoGainControl)!=null?h:!0},{googNoiseSuppression:(m=S==null?void 0:S.noiseSupression)!=null?m:!0},{googHighpassFilter:!0}],v)}),p(this,"getVideoConstraints",i=>{var s,n,o,c;const d={},l=(s=a(this,_n))==null?void 0:s.video;let h=pg.vga;if(typeof l=="string"?h=pg[l]:l!==void 0&&(h.height.ideal=l.height.ideal,h.width.ideal=l.width.ideal),h.frameRate={ideal:(o=(n=h.frameRate)==null?void 0:n.ideal)!=null?o:24},Ie.isChromiumBased()&&(h.frameRate.max=30),a(this,zr).getValue("flagsmith").hasFeature(Z.VIDEO_CONSTRAINTS)){const m=(c=a(this,zr).getValue("flagsmith").getValue(Z.VIDEO_CONSTRAINTS))==null?void 0:c.toString();h=JSON.parse(m)}return d.video=h,typeof d.video=="boolean"||(i?d.video.deviceId={exact:i}:d.video.facingMode="user"),d}),f(this,zr,e),f(this,_n,r)}getUpdatedVideoConstraints(e){return e}}_n=new WeakMap,zr=new WeakMap;class au extends Error{constructor(e,r,i){super(r),p(this,"constraints"),p(this,"name"),this.name=e,this.constraints=i}}class hO{constructor(){p(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 pO=Object.defineProperty,mO=Object.getOwnPropertyDescriptor,Mr=(t,e,r,i)=>{for(var s=i>1?void 0:i?mO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&pO(e,r,s),s},Fa,hr,Ge,mg;let Qt=(mg=class extends hO{constructor(t,e){super(),p(this,"availableDevices"),g(this,Fa,void 0),g(this,hr,void 0),g(this,Ge,void 0),f(this,Ge,t),f(this,hr,new uO(t,e)),f(this,Fa,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get telemetry(){return a(this,Ge).getValue("telemetry")}get logger(){return a(this,Ge).getValue("logger")}get constraintsBuilder(){return a(this,hr)}destruct(){return u(this,null,function*(){var t;(t=a(this,Fa))==null||t.abort()})}handlePermissionErrors(t,e){const r=Mc(t,e.name,e.message);return this.permissions[t]=r,a(this,Ge).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,hr).getAudioConstraints(t).audio,video:a(this,hr).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 s=i.getAudioTracks()[0];let n=i.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",a(this,Ge).getValue("flagsmith").hasFeature(Z.OBS_QUALITY)&&n.label.includes("OBS Virtual")){const o=(yield this.getVideoInputDevices()).find(c=>c.label.includes("OBS Virtual"));n=yield this.getVideoTrack(o.deviceId)}return a(this,Ge).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,Ge).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:s,videoTrack:n}}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,Ge).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new I("No audio devices available","1606");const i=s=>u(this,null,function*(){let n;try{r=r.filter(c=>c.deviceId!==s),n=a(this,hr).getAudioConstraints(s),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(n)});const[o]=(yield navigator.mediaDevices.getUserMedia(n)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(n)}),o}catch(o){const c=Mc("audio",o.name,o.message),d=new au(o.name,o.message,n);if(c==="COULD_NOT_START"){const l=r.shift();if(!l)throw d;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(n),error:o});const h=a(this,hr).getAudioConstraints(l.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(h)}),i(l.deviceId)}throw d}});try{const s=yield i(e);return s.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,Ge).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),s}catch(s){throw s.constraints&&this.handlePermissionErrors("audio",s),new I(s.message,"1601")}})}getVideoTrack(t){return u(this,null,function*(){var e;const r=a(this,Ge).getValue("flagsmith").hasFeature(Z.OBS_QUALITY),i=(e=yield this.getCurrentDeviceLabel(t))==null?void 0:e.includes("OBS Virtual"),s=r&&i,n=yield this.getVideoInputDevices();if(n.length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",a(this,Ge).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;s&&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(s&&typeof l!="boolean"&&typeof l.width=="object"){const{width:m,height:v}=h.getSettings(),{ideal:S}=l.width;h.applyConstraints({width:{ideal:S},height:{ideal:Math.floor(v*S/m)},frameRate:l.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(d)}),h}catch(d){const l=Mc("video",d.name,d.message),h=new au(d.name,d.message,c);if(l==="COULD_NOT_START"){const m=n.shift();if(!m)throw h;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(c),error:d});const v=a(this,hr).getVideoConstraints(m.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,hr).getVideoConstraints(t),d=yield o(c);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,Ge).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,Ge).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=Mc("video",r.name,r.message),s=new au(r.name,r.message,e),n={video:!0};if(k0(e,n)||!a(this,Ge).getValue("flagsmith").hasFeature(Z.SCREEENSHARE_CONSTRAINTS_RETRY))throw s;if(i==="COULD_NOT_START")return t(n);throw s}});try{const e=a(this,hr).getScreenShareConstraints(),r=yield t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,Ge).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 s=h=>`${h.kind}-${h.deviceId}-${h.groupId}`,n=this.availableDevices,o=new Set(n.map(h=>s(h))),c=yield this.getAvailableDevices(),d=new Set(c.map(h=>s(h))),l={added:c.filter(h=>!o.has(s(h))),removed:n.filter(h=>!d.has(s(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(m=>m.kind==="audioinput")&&a(this,Ge).getValue("callstats").devices("AUDIO",c==null?void 0:c.filter(m=>m.kind==="audioinput")),h.some(m=>m.kind==="videoinput")&&a(this,Ge).getValue("callstats").devices("VIDEO",c==null?void 0:c.filter(m=>m.kind==="videoinput")),h.some(m=>m.kind==="audiooutput")&&a(this,Ge).getValue("callstats").devices("SPEAKER",c==null?void 0:c.filter(m=>m.kind==="audiooutput")),t(e,l,!1)}}),{signal:a(this,Fa).signal})})}},Fa=new WeakMap,hr=new WeakMap,Ge=new WeakMap,mg);Mr([k.trace("WebMediaInterface.destruct")],Qt.prototype,"destruct",1);Mr([k.trace("WebMediaInterface.handlePermissionErrors")],Qt.prototype,"handlePermissionErrors",1);Mr([k.trace("WebMediaInterface.getAudioAndVideoTrack")],Qt.prototype,"getAudioAndVideoTrack",1);Mr([k.trace("WebMediaInterface.getAudioTrack")],Qt.prototype,"getAudioTrack",1);Mr([k.trace("WebMediaInterface.getVideoTrack")],Qt.prototype,"getVideoTrack",1);Mr([k.trace("WebMediaInterface.getScreenShareTracks")],Qt.prototype,"getScreenShareTracks",1);Mr([k.trace("WebMediaInterface.getAvailableDevices")],Qt.prototype,"getAvailableDevices",1);Mr([k.trace("WebMediaInterface.getAvailableDevicesByKind")],Qt.prototype,"getAvailableDevicesByKind",1);Mr([k.trace("WebMediaInterface.getDevice")],Qt.prototype,"getDevice",1);Mr([k.trace("WebMediaInterface.onDeviceChange")],Qt.prototype,"onDeviceChange",1);Qt=Mr([gt("1600")],Qt);const iy=Qt,xo={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}},gO=(t=0)=>new Promise(e=>setTimeout(e,t)),fO=(t,e,r)=>{const i=typeof r=="number"?r:250,s=t.createMediaStreamSource(e),n=t.createAnalyser();n.fftSize=2048,s.connect(n);const o=new Uint8Array(n.fftSize);let c=!1;setTimeout(()=>{c=!0},i);function d(){return c?Promise.resolve(!0):(n.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):gO().then(d))}return d().then(l=>(s.disconnect(),l),l=>{throw s.disconnect(),l})},vO=typeof AudioContext!="undefined"?AudioContext:null;class yp{constructor(e){p(this,"_AudioContext"),p(this,"audioContext"),p(this,"_audioContextRefContainers");const r=V({AudioContext:vO},e);Object.defineProperties(this,{_AudioContext:{value:r.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:yp}})}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 gg=new yp,yO=3,SO=250;function EO(t){const e={},r=gg.getOrCreate(e);let i=yO;function s(){return i-=1,fO(r,t.srcObject,SO).then(n=>n?i>0?s():!0:!1).catch(()=>!0)}return s().finally(()=>{gg.release(e)})}function fg(t,e){return u(this,null,function*(){const r=new Audio,i=new MediaStream;i.addTrack(e),r.srcObject=i;let s=!1;try{const n=r.play();n&&(yield n),s=yield EO(r),s&&t.info("checkIfAudioTrackIsSilent::silence_detected")}catch(n){t.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:n})}finally{r.pause(),r.remove()}return s})}var kO=Object.defineProperty,TO=Object.getOwnPropertyDescriptor,sy=(t,e,r,i)=>{for(var s=i>1?void 0:i?TO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&kO(e,r,s),s};let Zd=class extends ia{constructor(t,e,r,i){var s;const n=t.getValue("logger");super(n),p(this,"constructorName",this.constructor.name),p(this,"userSelectedDevice"),p(this,"mediaInterface"),p(this,"isNonPreferredDevice"),p(this,"_mediaTrack"),p(this,"transformedMediaTrack"),p(this,"middlewares",[]),p(this,"currentDevice"),p(this,"userPreferredDeviceKey",`Dyte::${this.constructorName}::UserDeviceID`),p(this,"setUserPreferredDevice",o=>xo.setItem(this.userPreferredDeviceKey,o,this.logger)),p(this,"getUserPreferredDevice",()=>xo.getItem(this.userPreferredDeviceKey,this.logger)),p(this,"isCustomTrack",!1),p(this,"context"),this.context=t,this.mediaInterface=e,r&&this.setMediaTrack(r),this.userSelectedDevice=(s=this.getUserPreferredDevice())!=null?s: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){return u(this,null,function*(){const e=r=>{this.logger.error(`${this.constructorName}.setMediaTrack.error`,{error:r})};try{this.disableTrack()}catch(r){e(r)}this._mediaTrack=yield this.conditionallyChangeTrack(t),yield this.setTransformedTrack();try{this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(r){e(r)}})}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,e;const{kind:r}=this.mediaTrack;switch(r){case"audio":{const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(e=(t=i==null?void 0:i.deviceId)!=null?t:i==null?void 0:i.advanced[0].deviceId)!=null?e:this.mediaTrack.getSettings().deviceId:this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}setCurrentDevice(){return u(this,null,function*(){var t;if(!this.mediaTrack){this.currentDevice=void 0;return}const e=this.getCurrentDeviceId();((t=this.currentDevice)==null?void 0:t.deviceId)!==e&&(this.currentDevice=yield this.mediaInterface.getDevice(e))})}setDevice(t){return u(this,null,function*(){if(!t)throw 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()&&!jw.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))}};sy([k.trace("BaseMediaHandler.unmuteTrack")],Zd.prototype,"unmuteTrack",1);Zd=sy([gt("1600")],Zd);const ny=Zd;var bO=Object.defineProperty,wO=Object.getOwnPropertyDescriptor,Sp=(t,e,r,i)=>{for(var s=i>1?void 0:i?wO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&bO(e,r,s),s};const ou="[Dyte]nonSilentDeviceLabels";class Rl extends ny{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)),this.userSelectedDevice=void 0}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);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 nO(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){return u(this,null,function*(){var r;if(!e||this.userSelectedDevice)return e;let i=e;const s=yield this.mediaInterface.getAudioInputDevices(),n=this.isNonPreferredDevice?s.filter(d=>d&&!this.isNonPreferredDevice(d)):s;if(!(n!=null&&n.length))return i;n.find(d=>d.deviceId===e.getSettings().deviceId)||(i.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),i=yield this.mediaInterface.getAudioTrack(!1,n[0].deviceId));const o=JSON.parse(xo.getItem(ou,this.logger));if(o!=null&&o.devices.some(d=>d.label===i.label))return i;if(!(yield fg(this.logger,i))){const d=(r=o==null?void 0:o.devices.concat({label:i.label}))!=null?r:[{label:i.label}];return xo.setItem(ou,JSON.stringify({devices:d}),this.logger),i}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=i.getSettings().deviceId;return n.filter(d=>d.deviceId!==c).some(d=>u(this,null,function*(){if(i=yield this.mediaInterface.getAudioTrack(!1,d.deviceId),!(yield fg(this.logger,i))){const l=o.devices.concat({label:i.label});return xo.setItem(ou,JSON.stringify({devices:l}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),i})}}Sp([k.trace("AudioMediaHandler.setTransformedTrack")],Rl.prototype,"setTransformedTrack",1);Sp([k.trace("AudioMediaHandler.onTrackEnded")],Rl.prototype,"onTrackEnded",1);Sp([k.trace("AudioMediaHandler.conditionallyChangeTrack")],Rl.prototype,"conditionallyChangeTrack",1);const _O=Rl;var uo;class IO{constructor(e){g(this,uo,void 0),p(this,"currentDevice"),f(this,uo,e)}setupSpeaker(e){return u(this,null,function*(){var r,i;if(!(a(this,uo)instanceof iy))return;let s=e;if(e||([s]=(yield a(this,uo).getAvailableDevicesByKind("audiooutput")).filter(o=>!sh(o))),!s)throw new I("No speaker found","1608");if(((r=this.currentDevice)==null?void 0:r.deviceId)===s.deviceId)return;this.currentDevice=s;const n=document.querySelectorAll("audio");(i=n[0])!=null&&i.setSinkId&&n.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{}}))})}}uo=new WeakMap;const CO=IO;var ad;class PO extends ia{constructor(e,r){const i=e.getValue("logger");super(i),p(this,"mediaInterface"),p(this,"audioMediaTrack"),p(this,"videoMediaTrack"),g(this,ad,void 0),f(this,ad,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}enableScreenShare(){return u(this,null,function*(){var e,r;try{const{audioTrack:i,videoTrack:s}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=s,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,ad).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")}}ad=new WeakMap;const RO=PO;var MO=Object.defineProperty,AO=Object.getOwnPropertyDescriptor,Ml=(t,e,r,i)=>{for(var s=i>1?void 0:i?AO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&MO(e,r,s),s},ho,od;class cc extends ny{constructor(e,r,i,s){super(e,r,i,s),g(this,ho,void 0),g(this,od,{disablePerFrameCanvasRendering:!1}),f(this,ho,new aO(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);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,ho).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,od)),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,od,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,ho).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){return u(this,null,function*(){if(!e||this.userSelectedDevice)return e;let r=e;const i=yield this.mediaInterface.getVideoInputDevices(),s=this.isNonPreferredDevice?i.filter(n=>!this.isNonPreferredDevice(n)):i;return!(s!=null&&s.length)||window.FAST_DYTE||s.find(n=>n.deviceId===e.getSettings().deviceId)||(r.stop(),this.logger.info("localmediahandler::setupstreams::found_video_non_preferred"),r=yield this.mediaInterface.getVideoTrack(s[0].deviceId)),r})}}ho=new WeakMap,od=new WeakMap;Ml([k.trace("VideoMediaHandler.setTransformedTrack")],cc.prototype,"setTransformedTrack",1);Ml([k.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],cc.prototype,"setVideoMiddlewareGlobalConfig",1);Ml([k.trace("VideoMediaHandler.onTrackEnded")],cc.prototype,"onTrackEnded",1);Ml([k.trace("VideoMediaHandler.conditionallyChangeTrack")],cc.prototype,"conditionallyChangeTrack",1);const DO=cc,vg=_r(dp());var Jt,In,cd,po;const mo=class{constructor(t){if(g(this,Jt,void 0),g(this,In,void 0),g(this,cd,void 0),g(this,po,void 0),!t)throw new I("Could not load preset.","0904");f(this,Jt,t.config),f(this,cd,t.name),f(this,In,t.ui||_r(dp().ui)),f(this,po,t.permissions.plugins.config)}static fromResponse(t){return new mo(t)}static default(){return new mo(vg)}static init(t,e=!0){return!t||e?new mo(vg):new mo(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,In).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,po)).filter(t=>a(this,po)[t].disabled)}get designTokens(){return a(this,In).designTokens}get configDiff(){return a(this,In).configDiff}get mediaConstraints(){var t,e,r,i,s,n,o,c,d,l,h,m,v,S,T,M,b,R,j,W,w,te,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:Xs.audio.enableStereo,enableHighBitrate:(c=(o=(n=(s=a(this,Jt))==null?void 0:s.media)==null?void 0:n.audio)==null?void 0:o.enableHighBitrate)!=null?c:Xs.audio.enableHighBitrate},video:{quality:(m=(h=(l=(d=a(this,Jt))==null?void 0:d.media)==null?void 0:l.video)==null?void 0:h.quality)!=null?m:Xs.video.quality,frameRate:(M=(T=(S=(v=a(this,Jt))==null?void 0:v.media)==null?void 0:S.video)==null?void 0:T.frameRate)!=null?M:Xs.video.frameRate},screenshare:{quality:(W=(j=(R=(b=a(this,Jt))==null?void 0:b.media)==null?void 0:R.screenshare)==null?void 0:j.quality)!=null?W:Xs.screenshare.quality,frameRate:(ae=(re=(te=(w=a(this,Jt))==null?void 0:w.media)==null?void 0:te.screenshare)==null?void 0:re.frameRate)!=null?ae:Xs.screenshare.frameRate}}}get name(){return a(this,cd)}};let OO=mo;Jt=new WeakMap,In=new WeakMap,cd=new WeakMap,po=new WeakMap;var NO=Object.defineProperty,VO=Object.getOwnPropertyDescriptor,ay=(t,e,r,i)=>{for(var s=i>1?void 0:i?VO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&NO(e,r,s),s},go,dd;class Ep extends Xt{constructor(e,r){const i=e.getValue("logger");super(i),g(this,go,void 0),p(this,"state","IDLE"),p(this,"playbackUrl"),p(this,"ingestionCredentials"),p(this,"viewerCount"),g(this,dd,void 0),f(this,go,r),f(this,dd,e),this.viewerCount=0}get telemetry(){return a(this,dd).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,go).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=ht(),{playbackUrl:i,ingestionCredentials:s}=yield r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=s,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,go).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 ht().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)}})}}go=new WeakMap,dd=new WeakMap;ay([k.trace("livestream.start")],Ep.prototype,"start",1);ay([k.trace("livestream.stop")],Ep.prototype,"stop",1);var LO=Object.defineProperty,xO=Object.getOwnPropertyDescriptor,UO=(t,e,r,i)=>{for(var s=i>1?void 0:i?xO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&LO(e,r,s),s},fo,vo,Ci,Yr;class oy{constructor(e,r,i){p(this,"livestream"),g(this,fo,void 0),g(this,vo,void 0),g(this,Ci,void 0),g(this,Yr,void 0),f(this,Yr,e),f(this,vo,r),this.livestream=new Ep(e,r),f(this,Ci,i),this.setupEvents()}get logger(){return a(this,Yr).getValue("logger")}get telemetry(){return a(this,Yr).getValue("telemetry")}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=ht(),{status:r,playbackUrl:i,manualIngest:s,ingestionCredentials:n}=yield e.getActiveLivestream();this.livestream.playbackUrl=i,this.livestream.ingestionCredentials=n,r==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),r==="INVOKED"&&s&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")})}setupEvents(){a(this,Ci).on(F.startedLivestream,e=>u(this,null,function*(){this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,vo).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}})),a(this,Ci).on(F.livestreamingInvoked,e=>u(this,null,function*(){if(e.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,vo).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}})),a(this,Ci).on(F.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,Ci).on(F.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,Ci).on(F.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),a(this,Yr).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,fo,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),a(this,Yr).getValue("peerSessionStore").on(P.PEER_CLOSED,e=>{e.id===a(this,fo)&&(f(this,fo,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,Yr).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){this.livestream.playbackUrl||(this.logger.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),a(this,Yr).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch{this.logger.error("Error: LivestreamController.fetchLivestream")}}))}}fo=new WeakMap,vo=new WeakMap,Ci=new WeakMap,Yr=new WeakMap;UO([k.trace("LivestreamController.setupEvents")],oy.prototype,"setupEvents",1);var FO=Object.defineProperty,BO=Object.getOwnPropertyDescriptor,dc=(t,e,r,i)=>{for(var s=i>1?void 0:i?BO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&FO(e,r,s),s},bt,hs,ps,nh,cy;class aa{constructor({name:e,socketHandler:r,meetingId:i}){g(this,nh),p(this,"name",""),g(this,bt,{}),g(this,hs,""),g(this,ps,void 0),p(this,"rateLimitConfig",{maxInvocations:5,period:1}),p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1}),p(this,"listeners",{}),this.name=e,f(this,ps,r),f(this,hs,i)}set(e,r,i=!0,s=!1){return u(this,null,function*(){a(this,bt)[e]=r,i&&this.remoteSet(e,r),s&&(this.listeners[e]&&this.listeners[e].forEach(n=>n({[e]:a(this,bt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[e]:a(this,bt)[e]})))})}remoteSet(e,r){a(this,ps).storeInsertKeys(a(this,hs),this.name,[{key:e,payload:r}])}bulkSet(e){return u(this,null,function*(){e.forEach(({key:r,payload:i})=>{a(this,bt)[r]=i}),a(this,ps).storeInsertKeys(a(this,hs),this.name,e)})}update(e,r,i=!0){return u(this,null,function*(){U(this,nh,cy).call(this,e,r,i)})}delete(e,r=!0,i=!1){return u(this,null,function*(){if(a(this,bt)[e]&&delete a(this,bt)[e],r)return a(this,ps).storeDeleteKeys(a(this,hs),this.name,[{key:e}]);i&&(this.listeners[e]&&(this.listeners[e].forEach(s=>s({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:void 0})))})}bulkDelete(e){return u(this,null,function*(){return e.forEach(({key:r})=>{a(this,bt)[r]&&delete a(this,bt)[r]}),a(this,ps).storeDeleteKeys(a(this,hs),this.name,e)})}get(e){if(a(this,bt)[e])return a(this,bt)[e]}getAll(){return a(this,bt)}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(s=>s!==r))||[];return}this.listeners[e]&&delete this.listeners[e]}populate(e){f(this,bt,e)}}bt=new WeakMap,hs=new WeakMap,ps=new WeakMap,nh=new WeakSet,cy=function(t,e,r=!0){let i;const s=a(this,bt)[t],n=Object.prototype.toString.call(e),o=Object.prototype.toString.call(s);if(n!==o){this.set(t,e);return}switch(o){case"[object Array]":i=[...s,...e];break;case"[object Object]":i=V(V({},s),e);break;case"[object Map]":i=new Map([...s,...e]);break;case"[object Set]":i=new Set([...s,...e]);break;default:i=e;break}this.set(t,i,r)};dc([Bt(na,"rateLimitConfig")],aa.prototype,"remoteSet",1);dc([Bt(na,"bulkRateLimitConfig")],aa.prototype,"bulkSet",1);dc([Bt(na,"rateLimitConfig")],aa.prototype,"update",1);dc([Bt(na,"rateLimitConfig")],aa.prototype,"delete",1);dc([Bt(na,"bulkRateLimitConfig")],aa.prototype,"bulkDelete",1);var Wn,jn,ld,cu,el,_s,ah,dy;class WO{constructor(e,r){g(this,ld),g(this,ah),p(this,"stores",new Map),g(this,Wn,void 0),g(this,jn,""),g(this,el,void 0),g(this,_s,new Map),f(this,Wn,r),f(this,jn,e.getValue("meetingId")),f(this,el,e),U(this,ah,dy).call(this)}create(e){const r=new aa({name:e,socketHandler:a(this,Wn),meetingId:a(this,jn)});return a(this,Wn).storeGetKeys(a(this,jn),e,[]),new Promise((i,s)=>{const n=setTimeout(()=>s(Error("Failed")),3e3);a(this,_s).set(e,{rejectTimeout:n,resolve:i,store:r})})}}Wn=new WeakMap,jn=new WeakMap,ld=new WeakSet,cu=function(){return a(this,el).getValue("peerId")},el=new WeakMap,_s=new WeakMap,ah=new WeakSet,dy=function(){[$.storeInsertKeys,$.storeGetKeys,$.storeDeleteKeys].forEach(t=>{a(this,Wn).on(t,e=>u(this,null,function*(){var r,i;if(e.pluginId!==a(this,jn))return;const s=(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===$.storeGetKeys){const o=a(this,_s).get(e.storeName),c=this.stores.get(e.storeName)||(o==null?void 0:o.store);a(this,_s).get(e.storeName)&&(this.stores.set(e.storeName,o.store),o.resolve(c),clearTimeout(o.rejectTimeout),a(this,_s).delete(e.storeName)),s.forEach(d=>{c.set(d.key,d.payload,!1,!1)});return}const n=this.stores.get(e.storeName)||((i=a(this,_s).get(e.storeName))==null?void 0:i.store);n!==void 0&&(t===$.storeInsertKeys&&s.forEach(({key:o,peerId:c,payload:d})=>{c!==a(this,ld,cu)&&n.set(o,d,!1,!0)}),t===$.storeDeleteKeys&&s.forEach(({key:o,peerId:c})=>{c!==a(this,ld,cu)&&n.delete(o,!1,!0)}))}))})};function Is(t){var e,r,i,s,n,o,c,d,l,h,m,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?(s=t.mediaPermissions)==null?void 0:s.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(n=t.mediaPermissions)==null?void 0:n.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:(m=(h=t.screenShareTracks)==null?void 0:h.video)==null?void 0:m.enabled,trackId:(S=(v=t.screenShareTracks)==null?void 0:v.video)==null?void 0:S.id}}}}:{}}var jO=Object.defineProperty,HO=Object.getOwnPropertyDescriptor,oa=(t,e,r,i)=>{for(var s=i>1?void 0:i?HO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&jO(e,r,s),s};const GO=.8,qO=1.2;var Ba,Wa,sr,Zs,ja,ts,en,tn,Ha,du,yg,mi,Ac,rs,rn,Ga,gi,lu,Dc,uu,hu,Sg,pu,Eg,kg;let li=(kg=class extends Xt{constructor(t,e,r,i){const s=t.getValue("logger");super(s),g(this,Zs),g(this,ts),g(this,tn),g(this,du),g(this,rn),g(this,Dc),g(this,hu),g(this,pu),p(this,"id"),p(this,"userId"),p(this,"name"),p(this,"picture"),p(this,"isHost"),p(this,"customParticipantId"),p(this,"flags"),p(this,"device"),p(this,"videoTrack"),p(this,"audioTrack"),p(this,"screenShareTracks"),p(this,"videoEnabled"),p(this,"audioEnabled"),p(this,"screenShareEnabled"),p(this,"producers"),p(this,"manualProducerConfig"),g(this,Ba,void 0),p(this,"supportsRemoteControl",!1),g(this,Wa,void 0),p(this,"presetName"),g(this,sr,void 0),g(this,mi,void 0),g(this,Ac,void 0),g(this,rs,new Map),g(this,gi,1),g(this,lu,lp(te=>{if(!this.videoTrack)return;const{clientWidth:re,clientHeight:ae}=te,{width:Ae,height:Xe}=this.videoTrack.getSettings();if(!Ae||!Xe)return;const jt=Xe/ae,A=Ae/re,E=Math.max(jt,A);E>qO&&a(this,gi)===1?(f(this,gi,0),a(this,sr).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,gi)})):E<GO&&a(this,gi)===0&&(f(this,gi,1),a(this,sr).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,gi)}))},2e3)),f(this,sr,t);const{id:n,userId:o,displayName:c,device:d,picture:l,isHost:h,flags:m,clientSpecificId:v,stageStatus:S,customParticipantId:T,audioMuted:M,audioTrack:b,videoEnabled:R=!1,videoTrack:j,producers:W,metadata:w}=e;this.id=n,this.userId=o,this.name=c,this.device=d,this.picture=l,this.isHost=h,this.flags=m,this.manualProducerConfig=_0,f(this,Wa,S!=null?S:"ON_STAGE"),this.customParticipantId=T!=null?T:v,this.audioEnabled=!M,this.audioTrack=b,this.videoEnabled=R,this.videoTrack=j,this.screenShareTracks={audio:void 0,video:void 0},this.producers=W!=null?W:[],this.presetName=w==null?void 0:w.preset_name,f(this,Ba,!1),f(this,mi,r),f(this,Ac,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),U(this,Dc,uu).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return a(this,Wa)}get telemetry(){return a(this,sr).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("DyteParticipant::setVideoEnabled::videoUpdate",V({},Is(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({},Is(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,Dc,uu)),a(this,ts,en)&&(this.on("audioUpdate",U(this,hu,Sg)),this.on("screenShareUpdate",U(this,pu,Eg)))}pin(){return u(this,null,function*(){if(!a(this,tn,Ha))throw new I("Can`t pin participant without joining room","1205");if(!a(this,mi).permissions.pinParticipant)throw new I("You do not have permission to pin participants.","1201");return a(this,Zs,ja).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!a(this,tn,Ha))throw new I("Can`t unpin participant without joining room","1205");if(!a(this,mi).permissions.pinParticipant)throw new I("You do not have permission to unpin participants.","1201");return a(this,Zs,ja).pinPeer(null)})}setIsPinned(t,e=!0){var r;f(this,Ba,t);const i=t?"pinned":"unpinned";(r=a(this,rn,Ga))==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,tn,Ha))throw new I("Can`t disable participant audio without joining room","1205");if(a(this,mi).permissions.canDisableParticipantAudio)return a(this,Zs,ja).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,yg))throw new I("Can`t kick participant without joining room","1205");if(a(this,mi).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,tn,Ha))throw new I("Can`t disable participant video without joining room","1205");if(a(this,mi).permissions.canDisableParticipantVideo)return a(this,Zs,ja).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,Ac).getUserPermissions(this.userId)})}setStageStatus(t){f(this,Wa,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,Ba)}registerVideoElement(t){var e,r,i,s;if(!t)return;let n;(r=(e=a(this,rs).get(t))==null?void 0:e.observer)==null||r.disconnect(),"ResizeObserver"in window&&(n=new ResizeObserver(()=>a(this,lu).call(this,t)),n.observe(t)),a(this,rs).set(t,{observer:n}),this.updateVideo(t),(s=a(this,rn,Ga))==null||s.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(i=this.raised)!=null?i:!1)}deregisterVideoElement(t){var e,r,i,s;if(!t){(e=a(this,rn,Ga))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,rs).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,rs).delete(t),(s=a(this,rn,Ga))==null||s.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"}},Ba=new WeakMap,Wa=new WeakMap,sr=new WeakMap,Zs=new WeakSet,ja=function(){return a(this,sr).getValue("roomNodeClient")},ts=new WeakSet,en=function(){return a(this,sr).getValue("audioPlayback")},tn=new WeakSet,Ha=function(){return a(this,sr).getValue("connectionHandler").mediaJoined},du=new WeakSet,yg=function(){return a(this,sr).getValue("connectionHandler").socketJoined},mi=new WeakMap,Ac=new WeakMap,rs=new WeakMap,rn=new WeakSet,Ga=function(){return a(this,sr).getValue("pip")},gi=new WeakMap,lu=new WeakMap,Dc=new WeakSet,uu=function(){Array.from(a(this,rs).keys()).forEach(this.updateVideo)},hu=new WeakSet,Sg=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,ts,en))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,ts,en))==null||e.removeParticipantTrack(this.id)},pu=new WeakSet,Eg=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,ts,en))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,ts,en))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},kg);oa([k.trace("DyteParticipant.disableAudio")],li.prototype,"disableAudio",1);oa([k.trace("DyteParticipant.kick")],li.prototype,"kick",1);oa([k.trace("DyteParticipant.disableVideo")],li.prototype,"disableVideo",1);oa([k.trace("DyteParticipant.getPermissions")],li.prototype,"getPermissions",1);oa([k.trace("DyteParticipant.setStageStatus")],li.prototype,"setStageStatus",1);li=oa([gt("1200")],li);class Cs extends ey{constructor(e,r){const{onAddEvent:i="participantJoined",onDeleteEvent:s="participantLeft",onClearEvent:n="participantsCleared"}=r!=null?r:{};super({onAddEvent:i,onDeleteEvent:s,onClearEvent:n},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 ms;class $O extends ia{constructor(e){super(e),g(this,ms,void 0),f(this,ms,new Map)}__set(e,r){return a(this,ms).set(e,r)}__clear(){return a(this,ms).clear()}get(e){return a(this,ms).get(e)}toArray(){return Array.from(a(this,ms).values())}}ms=new WeakMap;class JO{constructor(){p(this,"_orderedArray"),p(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 s=this.add(e,r);return i!==s?s:-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 KO{constructor(){p(this,"_activeSpeakerPeers"),p(this,"_compulsoryPeers"),this._activeSpeakerPeers=new JO,this._compulsoryPeers=new Set}add(e,r,i){if(!e)return-1;if(r<0)return this._compulsoryPeers.add(e),0;const s=i.getValue("logger");if(this.compulsoryPeers.includes(e)&&(r>0||r===246267631)){if(s.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 ly=new KO;var zO=Object.defineProperty,YO=Object.getOwnPropertyDescriptor,tr=(t,e,r,i)=>{for(var s=i>1?void 0:i?YO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&zO(e,r,s),s};const QO=["ACTIVE_GRID","PAGINATED","MANUAL"];var qe,sn,qa,nn,$a,Ja,Oc,an,Ht,Tg;let Rt=(Tg=class extends Xt{constructor(t,e,r){const i=t.getValue("logger");super(i),g(this,sn),g(this,nn),g(this,Ja),p(this,"waitlisted"),p(this,"joined"),p(this,"active"),p(this,"videoSubscribed"),p(this,"audioSubscribed"),p(this,"pinned"),p(this,"all"),g(this,qe,void 0),g(this,an,void 0),g(this,Ht,void 0),p(this,"rateLimitConfig",{maxInvocations:5,period:1}),p(this,"viewMode"),p(this,"currentPage"),p(this,"lastActiveSpeaker"),p(this,"selectedPeers",ly),f(this,qe,t),f(this,an,e),f(this,Ht,r),this.waitlisted=new Cs(i),this.joined=new Cs(i),this.videoSubscribed=new Cs(i),this.audioSubscribed=new Cs(i),this.active=this.videoSubscribed,this.pinned=new Cs(i),this.all=new $O(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,qe).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,qe).getValue("telemetry")}setupEvents(){a(this,qe).getValue("peerSessionStore").on(P.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,qe).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,qe).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,qe))==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,qe).setValue("maxPreferredStreams",t),a(this,Ja,Oc)&&a(this,qe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE)}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,nn,$a))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,s;return(s=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?s:r});return a(this,Ht).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return u(this,null,function*(){var e,r;if(!a(this,nn,$a))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=>QO.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}if(t==="MANUAL")throw new I("Manual Subscription is not enabled for your Organization. Please contact support.","1208");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,a(this,qe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,a(this,qe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE)),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");const i=[];e.forEach(s=>{const n=this.joined.get(s);if(n){if(r.includes("audio")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{audio:!0}),this.videoSubscribed.add(n);const o=n.producers.find(c=>c.kind==="audio"&&!c.screenShare);o&&i.push(o)}if(r.includes("video")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{video:!0}),this.audioSubscribed.add(n);const o=n.producers.find(c=>c.kind==="video"&&!c.screenShare);o&&i.push(o)}if(r.includes("screenshareAudio")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareAudio:!0});const o=n.producers.find(c=>c.kind==="audio"&&c.screenShare);i.push(o)}if(r.includes("screenshareVideo")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareVideo:!0});const o=n.producers.find(c=>c.kind==="video"&&c.screenShare);i.push(o)}}}),yield a(this,sn,qa).createConsumers(i)})}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");const i=[];e.forEach(s=>{const n=this.joined.get(s);if(n){if(r.includes("audio")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{audio:!1});const o=n.producers.find(c=>c.kind==="audio"&&!c.screenShare);o&&i.push(o)}if(r.includes("video")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{video:!1});const o=n.producers.find(c=>c.kind==="video"&&!c.screenShare);o&&i.push(o)}if(r.includes("screenshareAudio")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareAudio:!1});const o=n.producers.find(c=>c.kind==="audio"&&c.screenShare);i.push(o)}if(r.includes("screenshareVideo")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareVideo:!1});const o=n.producers.find(c=>c.kind==="video"&&c.screenShare);i.push(o)}}}),yield a(this,sn,qa).closeConsumers(i)})}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)),s=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),n=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(s,n))}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,qe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{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,Ja,Oc))throw new I("Can`t disable all audio without joining room","1205");if(a(this,an).permissions.canAllowParticipantAudio)return a(this,sn,qa).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,Ja,Oc))throw new I("Can`t disable all video without joining room","1205");if(a(this,an).permissions.canAllowParticipantVideo)return a(this,sn,qa).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,qe).getValue("peerSessionStore").emitAsync(P.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(this.logger.info("DyteParticipants::kick_all"),a(this,qe).getValue("viewType")!=="LIVESTREAM"&&!a(this,nn,$a))throw new I("Can`t kick all without joining room","1205");if(!a(this,an).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,qe).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,nn,$a))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(s=>{var n;return(n=r.presetNames)==null?void 0:n.includes(s.presetName)}).map(s=>s.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(hi.formatSocketServiceMessage)})}updatePermissions(t,e){return u(this,null,function*(){const r=this.joined.toArray().filter(s=>t.includes(s.id)).map(s=>s.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()})}},qe=new WeakMap,sn=new WeakSet,qa=function(){return a(this,qe).getValue("roomNodeClient")},nn=new WeakSet,$a=function(){var t;return((t=a(this,qe).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Ja=new WeakSet,Oc=function(){var t;return((t=a(this,qe).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},an=new WeakMap,Ht=new WeakMap,Tg);tr([k.trace("DyteParticipants.setViewMode")],Rt.prototype,"setViewMode",1);tr([k.trace("DyteParticipants.setPage")],Rt.prototype,"setPage",1);tr([k.trace("DyteParticipants.disableAllAudio")],Rt.prototype,"disableAllAudio",1);tr([k.trace("DyteParticipants.disableAllVideo")],Rt.prototype,"disableAllVideo",1);tr([k.trace("DyteParticipants.disablePeerAudio")],Rt.prototype,"disableAudio",1);tr([k.trace("DyteParticipants.disablePeerVideo")],Rt.prototype,"disableVideo",1);tr([k.trace("DyteParticipants.kickPeer")],Rt.prototype,"kick",1);tr([k.trace("DyteParticipants.kickAll")],Rt.prototype,"kickAll",1);tr([k.trace("DyteParticipants.broadcastMessage"),Bt(na,"rateLimitConfig")],Rt.prototype,"broadcastMessage",1);tr([k.trace("DyteParticipants.getAllJoinedPeers"),Bt({maxInvocations:10,period:60})],Rt.prototype,"getAllJoinedPeers",1);tr([k.trace("DyteParticipant.updatePermissions"),Bt({maxInvocations:1e3,period:60})],Rt.prototype,"updatePermissions",1);tr([k.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],Rt.prototype,"getParticipantsInMeetingPreJoin",1);Rt=tr([gt("1200")],Rt);var ra=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t.CLOSED="closed",t))(ra||{}),Me=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(Me||{}),XO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,qs=(t,e,r,i)=>{for(var s=i>1?void 0:i?ZO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&XO(e,r,s),s},fi,on,cn,dn,Ka,bg;const ud=(bg=class{constructor(t,e,r,i){p(this,"participants"),p(this,"self"),p(this,"selectedPeers",ly),p(this,"maxSpatialLayerUpdates",new Map),p(this,"consumerPeerMap"),p(this,"events"),p(this,"roomSocketHandler"),p(this,"context"),p(this,"videoPeerConsumerMap",new Map),g(this,fi,{mode:"ACTIVE_GRID",page:0}),g(this,on,void 0),g(this,cn,void 0),g(this,dn,!1),g(this,Ka,!1),p(this,"updateConsumerSpatialLayers",lp(()=>{const n={},o=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(o.entries()).forEach(([c,d])=>{n[d]===void 0&&(n[d]={layer:d,consumerIds:[]}),n[d].consumerIds.push(c)}),Object.keys(n).forEach(c=>{const d=n[c];this.logger.log(`Switching max spatial layer to ${d.layer}`,{consumerIds:d.consumerIds}),this.roomNodeClient.switchConsumersToLayer(d.consumerIds,d.layer)})},2e3)),p(this,"updateConsumers",(n,o)=>u(this,null,function*(){try{n.length!==0&&(this.logger.info("Queueing create consumers for producers",{producers:n}),yield this.roomNodeClient.createConsumers(n))}catch(c){this.logger.error("Error activating peers",{error:c})}try{o.length!==0&&(this.logger.info("Queueing close consumers for producers",{producers:o}),yield this.roomNodeClient.closeConsumers(o))}catch(c){this.logger.error("Error deactivating peers",{error:c})}})),this.context=t;const s=t.getValue("logger");switch(f(this,on,new Cs(s)),f(this,cn,new Cs(s)),this.roomSocketHandler=r,this.participants=new Rt(t,e,this.roomSocketHandler),this.self=e,this.consumerPeerMap=new Map,i){case Me.HIVE:{this.events=cr;break}case Me.CF:{this.events=br;break}default:this.events=cr}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.onParticipantJoined(this.fromSocketService(r))}),e&&this.logger.info("Processed socket peers")})),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:t})=>{this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN)&&this.logger.info("events.peerJoinedBroadcast",{peers:t.peerId}),this.onMediaJoined(t.peerId,t.producerStates,t.capabilities)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:t,selectedPeers:e,roomState:r})=>{if(this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN)){const n=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(o=>o.peerId))}:void 0;this.logger.info("events.selfJoinComplete",n)}t.forEach(({peerId:n,producerStates:o,capabilities:c})=>this.onMediaJoined(n,o,c));const{audioPeers:i,compulsoryPeers:s}=e!=null?e:{};r.pinnedPeerIds.length!==0&&this.onParticipantPinned(r.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),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.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:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}},dyteParticipant:{id:t}});return}if(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:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}}),this.participants.viewMode==="MANUAL"){let i=!1;const s=e.kind==="audio",n=e.kind==="video",o=r.manualProducerConfig;(s&&(o.audio&&!e.screenShare||o.screenshareAudio&&e.screenShare)||n&&(o.video&&!e.screenShare||o.screenshareVideo&&e.screenShare))&&(i=!0),i?this.roomNodeClient.createConsumers([e]):this.logger.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}});return}(e==null?void 0:e.kind)==="audio"&&this.participants.audioSubscribed.get(t)||(e==null?void 0:e.kind)==="video"&&this.participants.videoSubscribed.get(t)||e!=null&&e.screenShare?this.roomNodeClient.createConsumers([e]).catch(i=>{this.logger.error("ParticipantController::createConsumer failed",{error:i})}):this.logger.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}})}),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 s=this.participants.joined.get(t);if(s){i==="audio"&&s.setAudioEnabled(!r);const n=s.producers.find(o=>o.producerId===e);n&&(n.pause=r)}}),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.roomNodeClient.activatePeers(i.producers).catch(s=>{this.logger.error("unable to create consumers",{error:s})})}),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(s=>s.userId===i.userId)),r=this.participants.waitlisted.toArray().filter(i=>!t.requests.find(s=>s.userId===i.userId));e.forEach(i=>this.participants.waitlisted.add(new li(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)),s=Array.from(this.participants.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),n=Math.max((t-1)*(this.maxPreferredStreams-r.length-i.length)),o=t*(this.maxPreferredStreams-r.length-i.length);return r.concat(i,s.slice(n,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,s=this.participants.pinned.toArray().reduce((h,m)=>(m.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(m.id):h.push(m.id),h),[]),n=this.self.stageStatus==="ON_STAGE"?1:0,o=t-n,c=new Set(i.concat(s).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(m=>!c.has(m)&&m!==this.self.id).slice(0,l);d=Array.from(c).concat(h)}else d=d.slice(0,o);return d}updateSubscriptions(t,e){const{page:r,createAllConsumers:i}=e!=null?e:{};t&&a(this,fi).mode!==t&&(a(this,fi).mode=t),r&&a(this,fi).page!==r&&(a(this,fi).page=r);const{mode:s,page:n}=a(this,fi);switch(i&&(a(this,on).clear(),a(this,cn).clear()),s){case"PAGINATED":{if(!n)return;const o=this.selectPagePeers(n),c=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,o),this.updateParticipantsMap(this.participants.audioSubscribed,c),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:o});break}case"ACTIVE_GRID":{const o=this.selectActivePeers(this.participants.maxActiveParticipantsCount),c=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,o),this.updateParticipantsMap(this.participants.audioSubscribed,c);break}default:throw new Error(`View mode ${t} not supported`)}setTimeout(()=>this.syncConsumers(),a(this,fi).mode==="PAGINATED"&&!a(this,dn)?200:0)}syncConsumers(){return u(this,null,function*(){var t,e,r;if(((r=(e=(t=this.context.getValue("connectionHandler"))==null?void 0:t.mediaState)==null?void 0:e.recv)==null?void 0:r.state)!=="connected")return;if(a(this,dn)){f(this,Ka,!0);return}f(this,dn,!0),f(this,Ka,!1);const[i,s]=ud.mapDiff(a(this,on),this.participants.videoSubscribed);this.updateParticipantsMap(a(this,on),this.participants.videoSubscribed.toArray().filter(({videoEnabled:l})=>!!l).map(({id:l})=>l));const[n,o]=ud.mapDiff(a(this,cn),this.participants.audioSubscribed);this.updateParticipantsMap(a(this,cn),this.participants.audioSubscribed.toArray().filter(({audioEnabled:l})=>!!l).map(({id:l})=>l));const c=[...this.mapPeerIdsToProducers(i,["video"]),...this.mapPeerIdsToProducers(n,["audio"])],d=[...this.mapPeerIdsToProducers(s,["video"]),...this.mapPeerIdsToProducers(o,["audio"])];try{(c.length>0||d.length>0)&&(yield this.updateConsumers(c,d))}finally{f(this,dn,!1)}a(this,Ka)&&this.syncConsumers()})}static mapDiff(t,e){const r=[],i=[],s=Array.from(t.keys()),n=Array.from(e.keys());return s.forEach(o=>{n.includes(o)||i.push(o)}),n.forEach(o=>{s.includes(o)||r.push(o)}),[r,i]}computeActivateParticipants(t,e){const r=t.map((s,n)=>({peerId:s,priority:n+1})),i=e==null?void 0:e.map((s,n)=>({peerId:s,priority:-(n+1)}));r.push(...i!=null?i:[]),r.length>0&&this.updateActiveParticipantsWithPriorities(r)}fromSocketService(t){const e=ud.formatSocketServiceMessage(t);return new li(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)}onMediaJoined(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}e.forEach(s=>{s.kind===jr.AUDIO&&!s.screenShare?i.setAudioEnabled(!s.pause):s.kind===jr.VIDEO&&!s.screenShare&&(i.setVideoEnabled(!s.pause),this.updatePipSource(i.id,!s.pause)),i.producers.push(q(V({},s),{producingTransportId:s.producingTransportId,kind:s.kind===jr.AUDIO?"audio":"video",producingPeerId:t,mimeType:s.mimeType}))}),this.roomNodeClient.handlePeerCapabilities(t,r),this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||this.roomNodeClient.shareWebcam(this.self.videoTrack),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE)}updateParticipantsMapMinReplacement(t,e){const r=Array.from(t.keys()),i=new Map(t),s=new Set(e),n=[];r.forEach((o,c)=>{(!s.has(o)||!this.participants.joined.get(o))&&n.push(c)}),e.forEach(o=>{if(t.get(o))return;if(r.length<e.length){r.push(o);return}const c=n.shift();r[c]=o}),n.forEach(o=>{r.splice(o,1)}),Array.from(t.keys()).forEach(o=>{t.delete(o,!s.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.onParticipantJoined(this.fromSocketService(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:s})=>{var n;const o=e==="video"&&((n=r==null?void 0:r.screenShare)!=null?n:!1),c=this.participants.joined.get(i);c&&(c.emit("mediaScoreUpdate",{kind:e,isScreenshare:o,score:t,participantId:i,scoreStats:s}),this.participants.emit("mediaScoreUpdate",{kind:e,isScreenshare:o,score:t,participantId:i,scoreStats:s}))}),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*({page:e,createAllConsumers:r}={}){this.updateSubscriptions(e?"PAGINATED":"ACTIVE_GRID",{page:e,createAllConsumers:r})}))}onParticipantPinned(t){return u(this,null,function*(){if(!t){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(t===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const e=this.participants.joined.get(t);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),e.setIsPinned(!0),this.participants.pinned.add(e)})}onParticipantJoined(t){return u(this,null,function*(){var e,r,i;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),s=this.participants.videoSubscribed.get(t);i===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=i?r===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(r-1):s&&this.updateSubscriptions(r?"PAGINATED":"ACTIVE_GRID",{page:r})})}processMedia(t){var e;const r=this.roomNodeClient.getConsumers(),{peerId:i,kind:s,appData:n,track:o,producerId:c,rtpReceiver:d,paused:l}=(e=r.get(t))!=null?e:{};if(!i)return this.logger.warn("processMedia::Peer ID is undefined",{consumer:{id:t,kind:s,peerId:i,appData:{supportsRemoteControl:!!(n!=null&&n.supportsRemoteControl),screenShare:!!(n!=null&&n.screenShare)},remotelyPaused:l,producerId:c}}),{};const h=n;return s==="video"&&h.screenShare!==!0&&this.videoPeerConsumerMap.set(i,t),this.logger.info("ParticipantController::processMedia",{consumer:{id:t,peerId:i,kind:s,appData:h,remotelyPaused:l,producerId:c}}),this.consumerPeerMap.set(t,{type:s,peerId:i,appData:h,remotelyPaused:l,producerId:c}),{peerId:i,kind:s,appData:h,remotelyPaused:l,track:o,producerId:c,rtpReceiver:d}}processConsumerClosed(t){const{peerId:e,type:r,appData:i,remotelyPaused:s,producerId:n}=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:s,producerId:n}}),this.consumerPeerMap.delete(t),r==="video"&&i.screenShare!==!0&&this.videoPeerConsumerMap.delete(e),!o)return;const c=[];i&&i.screenShare?(o.setScreenShareEnabled(!1),this.context.getValue("callstats").consumerSharedMediaState(t,{screen:!1}),o.screenShareTracks.video&&c.push(o.screenShareTracks.video.id),o.screenShareTracks.audio&&c.push(o.screenShareTracks.audio.id),o.screenShareTracks={audio:void 0,video:void 0}):r==="audio"?(o.setAudioEnabled(!1),o.audioTrack&&c.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&&c.push(o.videoTrack.id),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!1}),o.videoTrack=void 0),i.e2ee&&c.forEach(d=>{this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:d})})}processConsumerResumed(t){var e;const{peerId:r,kind:i,appData:s,track:n,remotelyPaused:o,producerId:c,rtpReceiver:d}=this.processMedia(t);if(!r)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:t,peerId:r,kind:i,appData:s,remotelyPaused:o,producerId:c}});const l=this.participants.joined.get(r);if(l){if(s.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:r,rtpReceiver:d,track:n}),s.screenShare){i==="video"?l.screenShareTracks.video=n:i==="audio"&&(l.screenShareTracks.audio=n),l.setScreenShareEnabled(!0),(e=this.context)==null||e.getValue("callstats").consumerSharedMediaState(t,{screen:!0});return}i==="video"?(l.videoTrack=n,l.setVideoEnabled(!0),this.updatePipSource(l.id,!0),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!0})):i==="audio"&&(l.audioTrack=n,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:l.audioEnabled}))}}processConsumerPaused(t){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${t}`);const{peerId:e,kind:r,track:i,appData:s,remotelyPaused:n,producerId:o}=this.processMedia(t);if(!e)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:t,peerId:e,kind:r,appData:s,remotelyPaused:n,producerId:o}});const c=this.participants.joined.get(e);c&&(i&&s.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:i.id}),r==="video"?(c.videoTrack=i,c.setVideoEnabled(!1),this.updatePipSource(c.id,!1),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!1})):r==="audio"&&(c.audioTrack=i,c.setAudioEnabled(c.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:c.audioEnabled})))}processNewConsumer(t){const{peerId:e,kind:r,remotelyPaused:i,track:s,appData:n,producerId:o,rtpReceiver:c}=this.processMedia(t);if(!e)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:t,peerId:e,kind:r,remotelyPaused:i,appData:n,producerId:o}});const d=this.participants.joined.get(e);if(d){if(n.screenShare){r==="video"?d.screenShareTracks.video=s:r==="audio"&&(d.screenShareTracks.audio=s),(!i||this.self.permissions.isRecorder||this.context.getValue("flagsmith").hasFeature(Z.SCREEENSHARE_ERR_HACK))&&d.setScreenShareEnabled(!0),n.supportsRemoteControl&&(d.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:n,producerId:o}});return}r==="video"?(d.videoTrack=s,i||(d.setVideoEnabled(!0),this.updatePipSource(d.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!i})):r==="audio"&&(d.audioTrack=s,i||d.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:!i})),!i&&n.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:s})}}static formatSocketServiceMessage(t){var e,r,i,s,n,o;if(!t)return;const c=gp(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:(s=t.flags)==null?void 0:s.hiddenParticipant,recorder:((n=t.flags)==null?void 0:n.recorderType)!==void 0&&((o=t.flags)==null?void 0:o.recorderType)!=="NONE"}}}mapPeerIdsToProducers(t,e){const r=(i,s)=>i.filter(({kind:n,screenShare:o})=>s.includes(n)||o&&s.includes("screenshare"));return t.flatMap(i=>{const s=this.participants.joined.get(i);if(s)return r(s.producers,e)}).filter(i=>!!i)}onSelectedPeers(t,e){return u(this,null,function*(){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(t,e)})}updateActiveParticipantsWithPriorities(t,e=!1){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.updateSubscriptions(this.participants.viewMode)}},fi=new WeakMap,on=new WeakMap,cn=new WeakMap,dn=new WeakMap,Ka=new WeakMap,bg);let hi=ud;qs([k.trace("ParticipantController.setupEvents")],hi.prototype,"setupEvents",1);qs([k.trace("ParticipantController.setupEvents")],hi.prototype,"setupEventsGlobal",1);qs([k.trace("ParticipantController.processMedia")],hi.prototype,"processMedia",1);qs([k.trace("ParticipantController.processConsumerClosed")],hi.prototype,"processConsumerClosed",1);qs([k.trace("ParticipantController.processConsumerResumed")],hi.prototype,"processConsumerResumed",1);qs([k.trace("ParticipantController.processConsumerPaused")],hi.prototype,"processConsumerPaused",1);qs([k.trace("ParticipantController.processNewConsumer")],hi.prototype,"processNewConsumer",1);const ye=_r(dp().permissions);var H,yo,Hn,oh,xt,Kt;const So=class extends Xt{constructor(t,e,r,i=!1){const s=t.getValue("logger");if(super(s),g(this,xt),g(this,H,void 0),g(this,yo,void 0),g(this,Hn,void 0),g(this,oh,n=>{var o,c,d;const l=n,{chat:h,connectedMeetings:m,plugins:v,polls:S,media:T}=l,M=vl(l,["chat","connectedMeetings","plugins","polls","media"]);if(h&&(h.private&&bi(a(this,H).chat.private,h.private),h.public&&bi(a(this,H).chat.public,h.public),this.emit("chatUpdate")),m&&bi(a(this,H).connectedMeetings,m),T){const b=j=>{switch(j){case Ui.NONE:return G.Allowed;case Ui.ALLOWED:return G.Allowed;case Ui.NOT_ALLOWED:return G.NotAllowed;case Ui.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)}),bi(a(this,H).media,R)}v&&(bi(a(this,H).plugins,v),this.emit("pluginsUpdate")),S&&(bi(a(this,H).polls,S),this.emit("pollsUpdate")),Object.keys(M).length!==0&&bi(a(this,H),M),this.emit("permissionsUpdate",n)}),!e)throw this.logger.error("DytePermissionsPreset::load_preset_permissions_failed"),new I("Could not load preset permissions.","0904");f(this,Hn,t),f(this,yo,r),f(this,H,e),i&&this.setupEvents()}setupEvents(){a(this,Hn).getValue("peerSessionStore").on(P.UPDATE_PERMISSIONS,a(this,oh))}static fromResponse(t,e,r){return new So(r,t,e,!0)}static default(t,e){return new So(t,ye,e)}static init(t,e,r){let i;return r?i=new So(t,r,e,!0):i=new So(t,ye,e),i}get mediaRoomType(){const{sfu:t}=a(this,Hn).getValue("roomNodeOptions");return t===Me.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=a(this,H))==null?void 0:t.stageEnabled)||a(this,yo)===Ft.Webinar||a(this,yo)===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 e1=So;H=new WeakMap,yo=new WeakMap,Hn=new WeakMap,oh=new WeakMap,xt=new WeakSet,Kt=function(){return a(this,Hn).getValue("stageStatus")};var Vr;class uy extends Xt{constructor(){super(...arguments),p(this,"localMediaHandler"),g(this,Vr,void 0)}updatePermission(){return u(this,null,function*(){var e,r;const i=(l,h)=>{this.mediaPermissions[l]=h;const m={message:this.mediaPermissions[l],kind:l};h==="DENIED"?a(this,Vr).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_ERROR,m):a(this,Vr).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,m)};if(Ie.getName()==="firefox")return;const s="microphone",n="camera",o=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:s}),c=yield(r=navigator==null?void 0:navigator.permissions)==null?void 0:r.query({name:n}),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 s,n,o,c;switch(i){case"audio":{(s=a(this,Vr))==null||s.getValue("callstats").mediaPermission("AUDIO",r),(n=a(this,Vr))==null||n.getValue("callstats").mediaPermission("SPEAKER",r);break}case"video":{(o=a(this,Vr))==null||o.getValue("callstats").mediaPermission("VIDEO",r);break}case"screenshare":{(c=a(this,Vr))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",r);break}}})}get peerId(){var e;return(e=a(this,Vr))==null?void 0:e.getValue("peerId")}init(){return u(this,arguments,function*(e={},r=!1,i=null){var s,n,o,c,d,l,h;if(Ie.init(),!this.localMediaHandler)try{let m=!0;if((s=i==null?void 0:i.getValue("defaults"))!=null&&s.mediaHandler)m=!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,(n=i==null?void 0:i.getValue("defaults"))==null?void 0:n.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:M}=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:M,mediaPermissionsErrors:{kind:S,message:T}}),this.emit("mediaPermissionError",v),this.emit("mediaPermissionUpdate",{message:T,kind:S})})),m){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(m){this.logger.error("DyteSelf::init::Failed To Setup Streams",{error:{name:m.name,message:m.message}})}})}set context(e){f(this,Vr,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})})}}Vr=new WeakMap;const za={},$i={executeWithLock({methodName:t,lockName:e,timeout:r}){return(i,s,n)=>{const o=n.value;return n.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:"",m=`${e}-${h}`,v=this==null?void 0:this.logger;if(za[m]){const M=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw M.name="UnsupportedConcurrentMethodExecution",v==null||v.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:M.stack},dyteLocker:{methodName:t,lockName:m}}),M}za[m]=!0;const S=setTimeout(()=>delete za[m],r),T=o.apply(this,c);return Promise.resolve(T).then(()=>{delete za[m],clearTimeout(S)}).catch(()=>{delete za[m],clearTimeout(S)}),T},n}}};var t1=Object.defineProperty,r1=Object.getOwnPropertyDescriptor,Mt=(t,e,r,i)=>{for(var s=i>1?void 0:i?r1(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&t1(e,r,s),s},Ya,At,Qa,Ye,vi,is,Ze,at,Xa,Nc,$e,Qe,Za,eo,Vc,mu,wg;let nt=(wg=class extends uy{constructor(t,e,r,i,s){var n;const o=t.getValue("logger");super(o),g(this,vi),g(this,Ze),g(this,Xa),g(this,$e),g(this,Vc),p(this,"name"),p(this,"picture"),p(this,"customParticipantId"),p(this,"waitlistStatus"),g(this,Ya,void 0),g(this,At,void 0),g(this,Qa,void 0),p(this,"role"),p(this,"userId"),p(this,"organizationId"),p(this,"supportsRemoteControl",!1),p(this,"device"),g(this,Ye,void 0),p(this,"hidden",!1),p(this,"presetName"),p(this,"roomState","init"),g(this,Za,new Set),g(this,eo,new Set),f(this,Ye,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(n=e.customParticipantId)!=null?n:e.clientSpecificId,this.waitlistStatus="none",f(this,At,r),f(this,Ya,i),this.hidden=!1,f(this,Qa,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Ie.isElectron(),this.device=Ie.getDeviceInfo(),this.presetName=s,i.viewType!==Ft.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),U(this,Vc,mu).call(this)}get telemetry(){return a(this,Ye).getValue("telemetry")}get stageStatus(){return a(this,Ye).getValue("stageStatus")}get id(){return this.peerId}get peerId(){return a(this,Ye).getValue("peerId")}static __init__(t,e,r,i,s,n=!1){return u(this,null,function*(){var o,c,d,l,h,m;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 nt(t,e,r,i,s);if(i.viewType===Ft.Chat)return T;const M=lO(i.mediaConstraints);bi(M,(h=t.getValue("defaults"))==null?void 0:h.mediaConfiguration);const b=(m=t.getValue("defaults"))==null?void 0:m.mediaHandler;return b&&(b.context=t),yield T.init({audio:v,video:S,constraints:M},n,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,Vc,mu));const t=a(this,Xa,Nc);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({},Is(this))),a(this,$e,Qe)&&this.audioEnabled)try{yield a(this,Ze,at).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({},Is(this))),a(this,$e,Qe)&&this.rawVideoTrack===void 0)this.logger.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,$e,Qe))try{const e=yield a(this,Ze,at).shareWebcam(this.videoTrack);e&&e.id!==this.videoTrack.id&&a(this,Ye).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&(yield a(this,Ze,at).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,Xa,Nc))==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,Qe)){this.logger.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield a(this,Ze,at).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({},Is(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({},Is(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,Qe)&&(yield a(this,Ze,at).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,s;(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}`)),(s=e==null?void 0:e.media)!=null&&s.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,Ya)}get roomJoined(){var t;return a(this,Ya).viewType===Ft.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,Ye).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,$e,Qe)}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,Qe)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield a(this,Ze,at).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,Ze,at).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,Qe)&&this.stageStatus==="ON_STAGE")try{yield a(this,Ze,at).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({},Is(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,Qe))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,Ze,at).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,Qe)&&a(this,Ze,at).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,Qe)&&(yield a(this,Ze,at).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,Qe)&&(yield a(this,Ze,at).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var r;f(this,Qa,t);const i=t?"pinned":"unpinned";(r=a(this,vi,is))==null||r.updateSource(this.id,{pinned:t}),e&&this.emit(i,this)}get isPinned(){return a(this,Qa)}pin(){return u(this,null,function*(){if(!a(this,$e,Qe))throw new I("Can`t pin participants without joining room","1105");return this.show(),a(this,Ze,at).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!a(this,$e,Qe))throw new I("Can`t unpin participants without joining room","1105");return a(this,Ze,at).pinPeer(null)})}hide(){return u(this,null,function*(){if(!a(this,$e,Qe))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,Qe))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 s=this.getCurrentDevices();if(t.deviceId&&(((e=s==null?void 0:s.audio)==null?void 0:e.deviceId)===t.deviceId||((r=s==null?void 0:s.video)==null?void 0:r.deviceId)===t.deviceId||((i=s==null?void 0:s.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,Qe)&&(yield a(this,Ze,at).muteSelf()),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":yield this.localMediaHandler.setSpeakerDevice(t);break;case"videoinput":try{yield this.localMediaHandler.setVideoDevice(t)}catch{a(this,$e,Qe)&&(yield a(this,Ze,at).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,Xa,Nc))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,Za).add(t):a(this,eo).add(t),this.updateVideo(t),e||(i=a(this,vi,is))==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,vi,is).removeSource(this.id);return}t.srcObject=void 0,e?a(this,Za).delete(t):(a(this,eo).delete(t),a(this,vi,is).removeSource(this.id))}updateVideo(t,e=!1){var r,i,s;if(this.videoEnabled){if(this.videoTrack==null)return;const n=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((n==null?void 0:n.id)===this.videoTrack.id)return;const o=new MediaStream;o.addTrack(this.videoTrack),t.srcObject=o,e||(i=a(this,vi,is))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(s=a(this,vi,is))==null||s.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Ya=new WeakMap,At=new WeakMap,Qa=new WeakMap,Ye=new WeakMap,vi=new WeakSet,is=function(){return a(this,Ye).getValue("pip")},Ze=new WeakSet,at=function(){return a(this,Ye).getValue("roomNodeClient")},Xa=new WeakSet,Nc=function(){return a(this,Ye).getValue("audioPlayback")},$e=new WeakSet,Qe=function(){var t;return((t=a(this,Ye).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Za=new WeakMap,eo=new WeakMap,Vc=new WeakSet,mu=function(){Array.from(a(this,eo)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,Za)).forEach(t=>this.updateVideo(t,!0))},wg);Mt([k.trace("DyteSelf.cleanupEvents")],nt.prototype,"cleanupEvents",1);Mt([k.trace("DyteSelf.setupEvents")],nt.prototype,"setupEvents",1);Mt([k.trace("DyteSelf.setupTracks")],nt.prototype,"setupTracks",1);Mt([k.trace("DyteSelf.destructMediaHandler")],nt.prototype,"destructMediaHandler",1);Mt([k.trace("DyteSelf.removeDocumentEventListeners")],nt.prototype,"removeDocumentEventListeners",1);Mt([$i.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),k.trace("DyteSelf.enableAudio")],nt.prototype,"enableAudio",1);Mt([$i.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),k.trace("DyteSelf.enableVideo")],nt.prototype,"enableVideo",1);Mt([k.trace("DyteSelf.updateVideoConstraints")],nt.prototype,"updateVideoConstraints",1);Mt([k.trace("DyteSelf.enableScreenShare"),$i.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],nt.prototype,"enableScreenShare",1);Mt([k.trace("DyteSelf.updateScreenshareConstraints")],nt.prototype,"updateScreenshareConstraints",1);Mt([$i.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),k.trace("DyteSelf.disableAudio")],nt.prototype,"disableAudio",1);Mt([$i.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),k.trace("DyteSelf.disableVideo")],nt.prototype,"disableVideo",1);Mt([$i.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),k.trace("DyteSelf.disableScreenShare")],nt.prototype,"disableScreenShare",1);Mt([k.trace("DyteSelf.setDevice")],nt.prototype,"setDevice",1);nt=Mt([gt("1100")],nt);class kp extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,kp)}}class Tp extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Tp)}}var hd;class ch{constructor(e,r=!1){p(this,"pendingTasks",new Map),p(this,"nextTaskId",0),p(this,"stopping",!1),g(this,hd,void 0),this.log=r,f(this,hd,{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((s,n)=>{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),s(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),n(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 kp);this.stopping=!1}remove(e){const r=Array.from(this.pendingTasks.values())[e];r&&r.reject(new Tp)}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(),s=Date.now();a(this,hd).info(`AwaitQueue.push(${e.name})_timings`,{awaitQueueTask:{id:e.id,metadata:e.metadata,queueSizeAtStart:r,execTime:(s-e.executedAt)/1e3,taskStartTime:(e.executedAt-e.enqueuedAt)/1e3}}),e.resolve(i)}catch(r){e.reject(r)}})}}hd=new WeakMap;function i1(t,e){const r=new Error(e);return r.name=t,r}class ec extends I{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,ec):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 Ps extends I{constructor(e){super(e),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ut):this.stack=new Error(e).stack}}const _g=t=>new Promise(e=>setTimeout(e,t));function hy(t,e){return u(this,null,function*(){return new Promise((r,i)=>u(this,null,function*(){const{strategy:s,maxRetryCount:n,delayTime:o}=V({strategy:"linear",maxRetryCount:3,delayTime:10},e);let c=0,d,l=!1;const h=m=>{l=!0,i(m)};for(;c<n;){try{const m=yield t(c,h);return r(m)}catch(m){if(d=m,l)break;if(c<n)s==="linear"?yield _g(o*(c+1)):s==="exponential"&&(yield _g(o*(c+Math.max(0,c-1))));else break}c+=1}return i(d)}))})}function s1(t){return t.map(e=>({channels:e.channels,clockRate:e.clockRate,mimeType:e.mimeType,sdpFmtpLine:e.sdpFmtpLine}))}function n1(t){return t.map(e=>({uri:e.uri}))}function Lc(t){return{codecs:s1(t.codecs),headerExtensions:n1(t.headerExtensions?t.headerExtensions:[])}}function a1(t){const e=RTCRtpReceiver.getCapabilities("audio"),r=RTCRtpReceiver.getCapabilities("video"),i=RTCRtpSender.getCapabilities("audio"),s=RTCRtpSender.getCapabilities("video");t&&(r.codecs=r.codecs.filter(({mimeType:o})=>t===o),s.codecs=s.codecs.filter(({mimeType:o})=>t===o));const n={audio:Lc(e),video:Lc(r)};return{sender:{audio:Lc(i),video:Lc(s)},receiver:n}}var ct;class o1{constructor(e,r){g(this,ct,void 0),p(this,"events"),p(this,"sfuType"),f(this,ct,e),this.sfuType=r,this.events=r===Me.CF?br:cr}joinRoom(e,r,i,s=!1,n=null){return u(this,null,function*(){const o={roomUuid:e,displayName:r,prejoined:s,capabilities:i};return n&&(o.location=n),(yield a(this,ct).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:SI.toBinary(o),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield a(this,ct).sendMessagePromise(this.events.createWebRTCTransport,J0.toBinary(e))).payload,{transportId:i,description:s,producerIds:n}=Dv.fromBinary(r),o={sdp:s==null?void 0:s.sdp,type:s.type};return{transportId:i,answer:o,producerIds:n}})}produce(e){return u(this,null,function*(){var r,i;const s=(yield a(this,ct).sendMessagePromise(this.events.produce,NI.toBinary(e))).payload,n=fC.fromBinary(s);return{answer:{sdp:(r=n==null?void 0:n.description)==null?void 0:r.sdp,type:(i=n==null?void 0:n.description)==null?void 0:i.type},producerId:n.producerId}})}consume(e){return u(this,null,function*(){if(this.sfuType===Me.HIVE)throw new Error("Hive does not support socket consumer operations");const r=(yield a(this,ct).sendMessagePromise(this.events.consume,PI.toBinary(e))).payload,{consumerIdsMap:{map:i},description:s}=mC.fromBinary(r);return{consumerStateMap:i,sessionDescription:s}})}closeProducer(e){return u(this,null,function*(){const r=(yield a(this,ct).sendMessagePromise(this.events.closeProducer,WI.toBinary(e))).payload,{description:i}=bC.fromBinary(r);return i})}closeConsumer(e){return u(this,null,function*(){if(this.sfuType===Me.HIVE)throw new Error("Hive does not support socket consumer operations");return(yield a(this,ct).sendMessagePromise(this.events.closeConsumer,HI.toBinary(e))).payload})}updateConsumersSimulcastConfig(e){return u(this,null,function*(){if(this.sfuType===Me.HIVE)throw new Error("Method not implemented");return(yield a(this,ct).sendMessagePromise(this.events.updateConsumersSimulcastConfig,DI.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const i={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},s=(yield a(this,ct).sendMessagePromise(this.events.hostControlPeer,zI.toBinary(i))).payload;if(!s)return!1;const{status:n}=MC.fromBinary(s);return n==="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,QI.toBinary(r))).payload;if(!i)return!1;const{status:s}=DC.fromBinary(i);return s==="success"})}kickAll(){return u(this,null,function*(){const e={propagateKickAcrossRooms:!1};a(this,ct).sendMessagePromise(F.kickAll,Lv.toBinary(e))})}kickPeer(e){return u(this,null,function*(){a(this,ct).sendMessagePromise(F.kick,Wv.toBinary(e))})}changeDisplayName(e){return u(this,null,function*(){const r=(yield a(this,ct).sendMessagePromise(this.events.changeDisplayName,JI.toBinary(e))).payload;if(!r)return!1;const{status:i}=NC.fromBinary(r);return i==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield a(this,ct).sendMessagePromise(this.events.selfJoinComplete,kI.toBinary(e))).payload;return qu.fromBinary(r)})}audioActivity(e){return u(this,null,function*(){a(this,ct).sendMessage(this.events.audioActivity,z0.toBinary(e))})}}ct=new WeakMap;var pd;class Al extends mt.EventEmitter{constructor(e){super(),g(this,pd,void 0),f(this,pd,e),this.setMaxListeners(1/0)}get logger(){return a(this,pd).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(s){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:s}),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((s,n)=>{setTimeout(n,r,"event request timeout");try{this.emit(e.toString(),...i,s,n)}catch(o){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:o}),n(o)}})})}}pd=new WeakMap;class bp extends Al{constructor(){super(...arguments),p(this,"_sendWebStream",new MediaStream),p(this,"_sendScreenShareStream",new MediaStream),p(this,"_direction"),p(this,"pc"),p(this,"_transportReady",!1),p(this,"_mapMidTransceiver",new Map),p(this,"enableHighBitrate",!1),p(this,"enableStereo",!1),p(this,"enableDtx",!0),p(this,"sfu",Me.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:s,proprietaryConstraints:n,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"},s),n),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}connect(){return u(this,null,function*(){let e;this.sfu===Me.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:s=>u(this,null,function*(){this.logger.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(s)}]`),yield this.pc.setRemoteDescription(s),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 s=i.sender.getParameters();s.encodings.forEach((n,o)=>{o<=r?n.active=!0:n.active=!1}),yield i.sender.setParameters(s)})}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 s=i.sender.getParameters();s.encodings.forEach((n,o)=>{s.encodings[o]=V(V({},n),r)}),yield i.sender.setParameters(s)})}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 wp extends bp{static createFactory(e){return()=>new wp(e)}get name(){return"Chrome74"}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:s,proprietaryConstraints:n,onTrackHandler:o}){this._direction=e,this.pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},s),n),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}send(e){return u(this,arguments,function*({track:r,encodings:i,codecOptions:s,screenShare:n}){this._assertSendDirection();const o=this.pc.addTransceiver(r,{direction:"sendonly",streams:[n?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=[];s&&s.length&&s.forEach(m=>{var v;const S=l.codecs.find(T=>T.mimeType.includes(m.name));if(m.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(m.parameters)}`);const T=((v=S.sdpFmtpLine)==null?void 0:v.split(";"))||[];T.push(...m.parameters);const M=Array.from(new Set(T).values());S.sdpFmtpLine=M.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),s&&s.findIndex(({name:l})=>l==="opus")>=0){const{enableDtx:l,enableStereo:h}=this,m=this.enableHighBitrate?h?128e3:64e3:h?64e3:32e3;c.sdp=c.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${l?"usedtx=1;":""}${h?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${m}`),c.sdp+=`a=rtcp-fb:111 nack\r
17
+ `).map(e=>Wi.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=ht(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=Wi.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)})}},Pc=new WeakMap,og);Yv([k.trace("DyteAi.getActiveTranscript")],Wi.prototype,"getActiveTranscript",1);Wi=Yv([gt("0000")],Wi);var OD=Object.defineProperty,ND=Object.getOwnPropertyDescriptor,VD=(t,e,r,i)=>{for(var s=i>1?void 0:i?ND(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&OD(e,r,s),s},Zi,Ma,rr,cg;const Qv=(cg=class{constructor(t,e,r,i,s,n){p(this,"meta"),p(this,"ai"),g(this,Zi,void 0),g(this,Ma,void 0),p(this,"aiSocketHandler"),g(this,rr,void 0),f(this,rr,t),this.meta=new th(t,e,e.config.viewType,r,n),this.ai=i,f(this,Zi,e),f(this,Ma,r),this.aiSocketHandler=s,e.config.viewType!==Ft.Chat&&this.setupEvents()}get telemetry(){return a(this,rr).getValue("telemetry")}get logger(){return a(this,rr).getValue("logger")}static init(t,e,r,i,s){return u(this,null,function*(){const n=yield Wi.init(t,e.permissions.transcriptionEnabled);return new Qv(t,e,r,n,i,s)})}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,zv.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){a(this,rr).getValue("peerSessionStore").on(P.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),a(this,rr).getValue("peerSessionStore").on(P.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),a(this,rr).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,rr).getValue("peerSessionStore").on(P.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),a(this,Zi).permissions.canSpotlight&&(this.logger.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,Ma).broadcastMessage("spotlight",{userId:a(this,Zi).userId,currentTab:this.meta.selfActiveTab})),a(this,rr).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){a(this,Zi).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,Ma).broadcastToPeers("spotlight",[t.id],{userId:a(this,Zi).userId,currentTab:this.meta.selfActiveTab})})),a(this,rr).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,rr).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 s;try{s=Wi.parseTranscript(r,i)}catch(d){this.logger.error(`Failed to parse transcript: ${r}`,d)}if(!s){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(s),this.meta.emit("transcript",s);const{peerId:n,name:o,transcript:c}=s;this.logger.debug(`${e} Received transcript for peer ${n} - ${o}: ${c}`)})}},Zi=new WeakMap,Ma=new WeakMap,rr=new WeakMap,cg);let Xv=Qv;VD([k.trace("MetaController.setupEvents")],Xv.prototype,"setupEvents",1);var LD=Object.defineProperty,xD=Object.getOwnPropertyDescriptor,Gs=(t,e,r,i)=>{for(var s=i>1?void 0:i?xD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&LD(e,r,s),s},vr,co,ce,Zc,Kr,wt,ed,rh,lo,td;class qi extends Xt{constructor(e,r,i,s,n){const o=e.getValue("logger");super(o),g(this,ed),g(this,lo),g(this,vr,void 0),g(this,co,void 0),g(this,ce,void 0),g(this,Zc,void 0),g(this,Kr,void 0),g(this,wt,void 0),f(this,wt,e),f(this,vr,s),f(this,co,n),f(this,ce,r),f(this,Zc,i),f(this,Kr,[]),this.setupEvents()}get telemetry(){return a(this,wt).getValue("telemetry")}get status(){return a(this,wt).getValue("stageStatus")}setupEvents(){const e={[P.GET_STAGE_REQUESTS]:s=>u(this,null,function*(){f(this,Kr,s)}),[P.UPDATE_STAGE_REQUESTS]:s=>u(this,[s],function*({add:n}){const o=a(this,Kr).length,{stageRequests:c}=this.getAccessRequests();(n||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)})},r=()=>{Object.entries(e).forEach(([s,n])=>{a(this,wt).getValue("peerSessionStore").onAsync(s,n)})},i=()=>{Object.entries(e).forEach(([s,n])=>{a(this,wt).getValue("peerSessionStore").removeListener(s,n)})};a(this,ce).permissions.on("permissionsUpdate",s=>{const{canAcceptProductionRequests:n}=s;n!==void 0&&(a(this,ce).permissions.acceptStageRequests?(r(),a(this,vr).getStageRequests()):(i(),f(this,Kr,[]),this.emit("stageAccessRequestUpdate",a(this,Kr))))}),a(this,ce).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,ce).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ce).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,Zc).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return f(this,Kr,e),{stageRequests:a(this,Kr)}}requestAccess(){return u(this,null,function*(){if(!a(this,ce).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,ce).permissions.stageAccess===G.Allowed){U(this,lo,td).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,vr).requestAccess(),U(this,lo,td).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return u(this,null,function*(){if(!a(this,ce).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");a(this,vr).cancelRequestAccess(),U(this,lo,td).call(this,"OFF_STAGE")})}grantAccess(e){if(!a(this,ce).roomJoined)throw new I("Can`t grant for participant without joining room");if(!a(this,ce).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ce).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,vr).grantAccess(e)}denyAccess(e){if(!a(this,ce).roomJoined)throw new I("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,ce).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ce).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,vr).denyAccess(e)}join(){return u(this,null,function*(){const e=a(this,wt).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,ce).permissions.stageAccess===G.NotAllowed)throw new I(`Unable to join stage you are currently ${this.status}`,"2006");if(yield a(this,vr).joinStage(),e===Ft.Livestream){yield a(this,co).joinRoom(a(this,ce));const{peers:r}=yield a(this,co).getStagePeers();a(this,wt).getValue("peerSessionStore").emit(P.SOCKET_PEERS,r)}a(this,wt).setValue("stageStatus","ON_STAGE"),a(this,ce).audioEnabled&&a(this,ed,rh).shareMic(a(this,ce).audioTrack),a(this,ce).videoEnabled&&a(this,ed,rh).shareWebcam(a(this,ce).videoTrack)})}leave(){return u(this,null,function*(){if(!a(this,ce).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,ce).setIsPinned(!1),yield a(this,vr).leaveStage(a(this,ce).userId),a(this,wt).setValue("stageStatus","OFF_STAGE",!1),yield a(this,wt).getValue("peerSessionStore").emitAsync(P.LEAVE_MEDIA_ROOM,"stageLeft"),a(this,wt).notify("stageStatus")})}kick(e){return u(this,null,function*(){if(!a(this,ce).roomJoined)throw new I("Can`t kick participant without joining room","2005");if(!a(this,ce).permissions.stageEnabled)throw this.logger.error("DyteStage::stage_disabled"),new I("Stage is disabled","2003");if(!a(this,ce).permissions.acceptStageRequests)throw this.logger.error("DyteStage::kick::permission_denied"),new I("You do not have permissions for kick","2001");return a(this,vr).kick(e)})}}vr=new WeakMap,co=new WeakMap,ce=new WeakMap,Zc=new WeakMap,Kr=new WeakMap,wt=new WeakMap,ed=new WeakSet,rh=function(){return a(this,wt).getValue("roomNodeClient")},lo=new WeakSet,td=function(t){return u(this,null,function*(){this.status!==t&&a(this,wt).setValue("stageStatus",t)})};Gs([k.trace("DyteStage.getStageRequests")],qi.prototype,"getAccessRequests",1);Gs([k.trace("DyteStage.requestAccess")],qi.prototype,"requestAccess",1);Gs([k.trace("DyteStage.cancelRequestAccess")],qi.prototype,"cancelRequestAccess",1);Gs([k.trace("DyteStage.grantAccess")],qi.prototype,"grantAccess",1);Gs([k.trace("DyteStage.denyAccess")],qi.prototype,"denyAccess",1);Gs([k.trace("DyteStage.joinStage")],qi.prototype,"join",1);Gs([k.trace("DyteStage.leaveStage")],qi.prototype,"leave",1);function UD(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function gp(t){switch(t){case ii.UNSPECIFIED:return"OFF_STAGE";case ii.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case ii.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case ii.OFF_STAGE:return"OFF_STAGE";case ii.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var FD=Object.defineProperty,BD=Object.getOwnPropertyDescriptor,WD=(t,e,r,i)=>{for(var s=i>1?void 0:i?BD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&FD(e,r,s),s},ls,En,us,rd,Lt;class Zv{constructor(e,r,i,s,n){p(this,"stage"),g(this,ls,void 0),g(this,En,void 0),g(this,us,void 0),g(this,rd,0),g(this,Lt,void 0),f(this,Lt,e),this.stage=new qi(e,s,n,r,i),f(this,us,r),f(this,ls,s),f(this,En,n),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,us).on(F.grantStageAccess,()=>{a(this,ls).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,us).on(F.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===a(this,ls).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),a(this,us).on(F.denyStageAccess,()=>{a(this,ls).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,us).on(F.getStageRequests,e=>u(this,null,function*(){var r;if(a(this,ls).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,rd)<i.length&&i.length>0&&this.stage.emit("newStageRequest",{count:i.length}),f(this,rd,i.length),this.stage.emit("stageAccessRequestUpdate",i)}))}getCurrentStageRequests(){return a(this,En).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=gp(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,En).joined.get(e.peerId),i=a(this,En).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);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);break}a(this,Lt).getValue("peerSessionStore").emit(P.UPDATE_PEER_STAGE_STATUS,{id:r.id,status:r.stageStatus})})}}ls=new WeakMap,En=new WeakMap,us=new WeakMap,rd=new WeakMap,Lt=new WeakMap;WD([k.trace("DyteStage.setupEvents")],Zv.prototype,"setupEvents",1);var jD=Object.defineProperty,HD=Object.getOwnPropertyDescriptor,Cl=(t,e,r,i)=>{for(var s=i>1?void 0:i?HD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&jD(e,r,s),s};const Ve={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};var vt,ir,Aa,Da,pi,Oa,es,Na,dg;let ta=(dg=class extends ia{constructor(t,{baseURL:e,createdAt:r,description:i,id:s,name:n,organizationId:o,picture:c,private:d,published:l,staggered:h,tags:m,type:v,updatedAt:S},T,M,b,R,j){const W=t.getValue("logger");super(W),g(this,vt,void 0),p(this,"baseURL"),p(this,"createdAt"),p(this,"description"),p(this,"id"),p(this,"name"),g(this,ir,void 0),g(this,Aa,void 0),g(this,Da,void 0),p(this,"organizationId"),p(this,"picture"),p(this,"private"),p(this,"published"),p(this,"staggered"),p(this,"tags"),p(this,"type"),p(this,"updatedAt"),g(this,pi,void 0),p(this,"config"),g(this,Oa,void 0),p(this,"active"),p(this,"iframes"),p(this,"enabledBy"),g(this,es,void 0),g(this,Na,void 0),f(this,es,t),this.baseURL=e,this.createdAt=new Date(r),this.description=i,this.id=s,this.name=n,f(this,ir,M),this.organizationId=o,this.picture=c,this.private=d,this.published=l,this.staggered=h,this.tags=m,this.type=v,this.updatedAt=new Date(S),this.active=!1,this.iframes=new Map,f(this,vt,T),f(this,Aa,b),f(this,Da,R),this.enabledBy="",f(this,Na,j)}get telemetry(){return a(this,es).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:s,type:n}=r;switch(n){case $.customPluginEventToRoom:{a(this,vt).customPluginEventToRoom(this.id,i,s);break}case $.customPluginEventToPeers:{a(this,vt).customPluginEventToPeers(this.id,i.peerIds,i,s);break}case $.enablePluginForRoom:{a(this,vt).enablePluginForRoom(this.id,s);break}case $.enablePluginForPeers:{a(this,vt).enablePluginForPeers(this.id,i.peerIds,s);break}case $.disablePluginForRoom:{a(this,vt).disablePluginForRoom(this.id,s);break}case $.disablePluginForPeers:{a(this,vt).disablePluginForPeers(this.id,i.peerIds,s);break}case $.storeInsertKeys:{a(this,vt).storeInsertKeys(this.id,i.store,i.insertKeys,s);break}case $.storeGetKeys:{a(this,vt).storeGetKeys(this.id,i.store,i.getKeys,s);break}case $.storeDeleteKeys:{a(this,vt).storeDeleteKeys(this.id,i.store,i.deleteKeys,s);break}case $.storeDelete:{a(this,vt).storeDelete(this.id,i.store,s);break}case Ve.chatMessage:{const{messagePayload:o,peerIds:c}=i;if(!a(this,Da)){this.sendIframeEvent({type:Ve.chatMessage,uuid:r.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield a(this,Da).sendMessage(o,c),this.sendIframeEvent({type:Ve.chatMessage,uuid:r.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:Ve.chatMessage,uuid:r.uuid,payload:{error:d}})}break}case Ve.getPeer:{let o;const{peerId:c}=i,d=q(V({},a(this,ir)),{id:a(this,ir).id,isRecorder:(e=a(this,ir).permissions)==null?void 0:e.isRecorder,isHidden:a(this,ir).permissions.hiddenParticipant,stageStatus:a(this,ir).stageStatus});c?(o=a(this,Aa).joined.get(i.peerId),a(this,ir).id===c&&(o=d)):o=d,this.sendIframeEvent({type:Ve.getPeer,payload:{peer:o&&Xd(o)},uuid:r.uuid});break}case Ve.getPeers:{const o=a(this,Aa).joined.toArray().map(c=>Xd(c));this.sendIframeEvent({type:Ve.getPeers,payload:{peers:o},uuid:r.uuid});break}case Ve.getPluginInitiator:{this.sendIframeEvent({type:Ve.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:r.uuid});break}case Ve.getDisplayTitle:{this.sendIframeEvent({type:Ve.getDisplayTitle,payload:{displayTitle:a(this,Na)},uuid:r.uuid});break}case Ve.getRoomName:{this.sendIframeEvent({type:Ve.getRoomName,payload:{roomName:a(this,es).getValue("meetingId")},uuid:r.uuid});break}case Ve.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:Ve.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,Oa))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,s=new URL(this.baseURL),n={auth:a(this,Oa),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:a(this,es).getValue("apiBase"),pluginId:this.id,roomName:(r=a(this,es).getValue("meetingId"))!=null?r:"",displayTitle:a(this,Na)};if(Object.keys(n).forEach(o=>{s.searchParams.set(o,n[o])}),i.src=s.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=ht(),e=yield t.authorizePlugin(this.id);f(this,Oa,e),f(this,pi,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,pi,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,ir).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(a(this,vt).addPlugin(this.id,this.staggered),f(this,pi,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,ir).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==a(this,ir).id||(a(this,vt).removePlugin(this.id),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:a(this,pi)?new Date().getTime()-a(this,pi).getTime():0}}),f(this,pi,void 0)))})}},vt=new WeakMap,ir=new WeakMap,Aa=new WeakMap,Da=new WeakMap,pi=new WeakMap,Oa=new WeakMap,es=new WeakMap,Na=new WeakMap,dg);Cl([Bt({maxInvocations:5,period:1})],ta.prototype,"sendData",1);Cl([k.trace("DytePlugin.activatePlugin")],ta.prototype,"activate",1);Cl([k.trace("DytePlugin.deactivatePlugin")],ta.prototype,"deactivate",1);ta=Cl([gt("0600")],ta);var Ke,kn;class ey extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:s,onClearEvent:n}=e;super(),g(this,Ke,void 0),g(this,kn,void 0),p(this,"onAddEvent"),p(this,"onDeleteEvent"),p(this,"onClearEvent"),f(this,Ke,new ia(r)),this.onAddEvent=i,this.onDeleteEvent=s,this.onClearEvent=n,f(this,kn,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 s=super.set(e,r),n=(o,...c)=>{this.emit(o,r,...c)};return a(this,kn).set(e,n),r.on("*",n),i&&a(this,Ke).emit(this.onAddEvent,r),s}delete(e,r=!0,i=!1){const s=this.get(e);if(!s)return!1;s.removeListener("*",a(this,kn).get(e));const n=super.delete(e);return i&&s.removeAllListeners(),r&&a(this,Ke).emit(this.onDeleteEvent,s),n}clear(e=!0,r=!1){this.forEach(s=>{s.removeListener("*",a(this,kn).get(s.id)),r&&s.removeAllListeners()});const i=super.clear();return e&&a(this,Ke).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Ke=new WeakMap,kn=new WeakMap;class lg extends ey{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 GD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,$D=(t,e,r,i)=>{for(var s=i>1?void 0:i?qD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&GD(e,r,s),s};let ih=class{constructor(t){p(this,"all"),p(this,"active"),this.all=new lg(t),this.active=new lg(t)}};ih=$D([gt("0600")],ih);var JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,Pl=(t,e,r,i)=>{for(var s=i>1?void 0:i?KD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&JD(e,r,s),s},ur,Va,Ar,ug;const ty=(ug=class{constructor(t,e,r,i){p(this,"plugins"),g(this,ur,void 0),g(this,Va,void 0),g(this,Ar,void 0),f(this,ur,e),f(this,Va,r),f(this,Ar,t),this.plugins=i,this.setupEvents()}get telemetry(){return a(this,Ar).getValue("telemetry")}get logger(){return a(this,Ar).getValue("logger")}static init(t,e,r,i,s,n,o,c){return u(this,null,function*(){const d=t.getValue("logger"),l=new ih(d);return e.forEach(h=>{const m=new ta(t,h,r,n,o,s,c);l.all.add(m)}),new ty(t,r,i,l)})}getRoomPlugins(){return u(this,null,function*(){var t;const{plugins:e}=yield a(this,ur).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 s=this.plugins.all.get(e);s&&s.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,Ar).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,ur).on($.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,ur).on($.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}))})),[$.enablePluginForPeers,$.enablePluginForRoom].forEach(t=>{a(this,ur).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{enabledBy:e.enabledBy})}))}),[$.disablePluginForPeers,$.disablePluginForRoom].forEach(t=>{a(this,ur).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{disabledBy:e.disabledBy})}))}),[$.customPluginEventToPeers,$.customPluginEventToRoom].forEach(t=>{a(this,ur).on(t,(e,r)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,r,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[$.storeInsertKeys,$.storeGetKeys,$.storeDeleteKeys].forEach(t=>{a(this,ur).on(t,(e,r)=>u(this,null,function*(){var i;const s=(i=e.storeItems)==null?void 0:i.map(n=>{var o;return{timestamp:n.timestamp,peerId:n.peerId,payload:JSON.parse((o=n.payload)!=null&&o.length?new TextDecoder().decode(n.payload):"{}"),key:n.storeKey}});this.sendIframeEvent(t,e.pluginId,r,{storeName:e.storeName,storeItems:s})}))}),a(this,ur).on($.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent($.storeDelete,t.pluginId,e,{storeName:t.storeName})})),a(this,Va).on(De.sendMessageToPeers,t=>{const e=ai==null?void 0:ai.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ve.chatMessage,{message:e})}),a(this,Va).on(De.sendMessageToRoom,t=>{const e=ai==null?void 0:ai.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Ve.chatMessage,{message:e})}),a(this,Ar).getValue("peerSessionStore").on(P.PEER_JOINED_INTERNAL,t=>{const e=Xd(t);this.broadcastIframeEvent(Ve.peerJoined,e)}),a(this,Ar).getValue("peerSessionStore").on(P.PEER_CLOSED,t=>{this.broadcastIframeEvent(Ve.peerLeft,t)}),a(this,Ar).getValue("peerSessionStore").on(P.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(Ve.peerStageStatusUpdate,t)}),a(this,Ar).subscribe("stageStatus",t=>{this.broadcastIframeEvent(Ve.stageStatusUpdate,t)})}},ur=new WeakMap,Va=new WeakMap,Ar=new WeakMap,ug);let ac=ty;Pl([k.trace("PluginController.getRoomPlugins")],ac.prototype,"getRoomPlugins",1);Pl([k.trace("PluginController.enableForSelf")],ac.prototype,"enablePlugin",1);Pl([k.trace("PluginController.disableForSelf")],ac.prototype,"disablePlugin",1);Pl([k.trace("PluginController.setupEvents")],ac.prototype,"setupEvents",1);var id;class zD{constructor(e){p(this,"mediaJoined"),p(this,"socketJoined"),p(this,"socketJoinAttempted"),p(this,"mediaJoinAttempted"),p(this,"socketState"),p(this,"mediaState"),g(this,id,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,id,e)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(e,r){let i;const{reconnected:s}=this.socketState;switch(e){case"connected":i={state:"connected",reconnected:s,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:s,reconnectionAttempt:0};break;case"reconnectAttempt":i={state:"reconnecting",reconnected:s,reconnectionAttempt:r};break;case"failed":i={state:"failed",reconnected:s,reconnectionAttempt:void 0},this.socketJoined=!1;break}i&&(a(this,id).getValue("peerSessionStore").emit(P.SOCKET_STATE_UPDATE,i),this.socketState=i)}}id=new WeakMap;var YD=Object.defineProperty,QD=Object.getOwnPropertyDescriptor,oc=(t,e,r,i)=>{for(var s=i>1?void 0:i?QD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&YD(e,r,s),s},La,xa,Ua,Rc,hg;let xs=(hg=class extends Xt{constructor(t,e){const r=t.getValue("logger");super(r),g(this,Ua),g(this,La,void 0),g(this,xa,void 0),p(this,"recordingPeerIds",[]),p(this,"recordings",[]),f(this,xa,t),f(this,La,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,xa).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}start(t){return u(this,null,function*(){if(!a(this,La).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=ht(),{recording:r={}}=a(this,xa).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,Ua,Rc).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield U(this,Ua,Rc).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield U(this,Ua,Rc).call(this,"resume",["PAUSED"],t)})}},La=new WeakMap,xa=new WeakMap,Ua=new WeakSet,Rc=function(t,e,r){return u(this,null,function*(){if(!a(this,La).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 s=this.recordings.find(n=>n.id===r);if(s===void 0)throw new I("Could not find the specified recording","1004");if(e.includes(s.state)){this.logger.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:s.state}});return}i.push(s)}else i=this.recordings.filter(s=>e.includes(s.state));i.forEach(s=>u(this,null,function*(){const n=s.state;t==="stop"&&(s.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield ht().updateRecording(s.id,t)}catch(o){throw this.logger.error("DyteRecording::stop::recording_failed_to_stop",{error:o}),s.state!==n&&(s.state=n,this.emit("recordingUpdate",n)),new I("Error while stopping recording","1000",this.logger)}}))})},hg);oc([k.trace("DyteRecording.start")],xs.prototype,"start",1);oc([k.trace("DyteRecording.stop")],xs.prototype,"stop",1);oc([k.trace("DyteRecording.stop")],xs.prototype,"pause",1);oc([k.trace("DyteRecording.stop")],xs.prototype,"resume",1);xs=oc([gt("1000")],xs);var XD=Object.defineProperty,ZD=Object.getOwnPropertyDescriptor,eO=(t,e,r,i)=>{for(var s=i>1?void 0:i?ZD(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&XD(e,r,s),s},Tn;class ry{constructor(e,r,i){p(this,"recording"),p(this,"room"),g(this,Tn,void 0),f(this,Tn,e),this.recording=new xs(e,r),this.room=i,this.setupEvents()}get telemetry(){return a(this,Tn).getValue("telemetry")}get logger(){return a(this,Tn).getValue("logger")}getRecordingTypeFromProtoType(e){let r;switch(e){case Os.BROWSER:r="BROWSER";break;case Os.COMPOSITE:r="COMPOSITE";break;case Os.TRACK:r="TRACK";break;default:r="BROWSER"}return r}setupEvents(){a(this,Tn).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(s=>{s.id===e.recordingId&&(r=!0,s.state="RECORDING")}),r===!1){const s=this.getRecordingTypeFromProtoType(e.recordingType);i.push({id:e.recordingId,state:"RECORDING",type:s})}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)})}}Tn=new WeakMap;eO([k.trace("RecordingController.setupEvents")],ry.prototype,"setupEvents",1);var bn;class tO{constructor(e){g(this,bn,void 0),f(this,bn,e)}hasFeature(e){var r;return(r=a(this,bn).getValue("flagsmith").hasFeature(e))!=null?r:!1}getFeatureValue(e){return a(this,bn).getValue("flagsmith").getValue(e)}getAllFeatures(){return a(this,bn).getValue("flagsmith").getAllFlags()}}bn=new WeakMap;class fp{constructor(e,r,i){p(this,"logger"),p(this,"features"),p(this,"browserSpecs"),p(this,"callStats"),this.logger=e,this.features=r,this.browserSpecs=Ie,this.callStats=i}static init(e){return new fp(e.getValue("logger"),new tO(e),e.getValue("callstats"))}}class vp{constructor(e){p(this,"internals"),this.internals=e}static init(e){return u(this,null,function*(){const r=fp.init(e);return new vp(r)})}}var rO=Object.defineProperty,iO=Object.getOwnPropertyDescriptor,er=(t,e,r,i)=>{for(var s=i>1?void 0:i?iO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&rO(e,r,s),s},tt,Ce,be,Ii,yr,sd,Be;class Wt extends ia{constructor(e,r,i=sh,s=!0){const n=e.getValue("logger");super(n),g(this,tt,void 0),g(this,Ce,void 0),g(this,be,void 0),g(this,Ii,void 0),g(this,yr,void 0),g(this,sd,void 0),g(this,Be,void 0),p(this,"audioUpdateInProgress"),p(this,"videoUpdateInProgress"),f(this,Be,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,f(this,tt,new iy(e,r)),f(this,Ce,new _O(e,a(this,tt),void 0,i)),f(this,be,new DO(e,a(this,tt),void 0,i)),f(this,yr,new RO(a(this,Be),a(this,tt))),f(this,Ii,new CO(a(this,tt))),f(this,sd,s),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,yr).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,Be).getValue("telemetry")}set context(e){f(this,Be,e)}onVisibilityChange(){return u(this,null,function*(){a(this,Be).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,Be).getValue("callstats").browserBackgrounded():(a(this,Be).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 s;r?a(this,Be).getValue("callstats").audioOn():a(this,Be).getValue("callstats").audioOff(),i?a(this,Be).getValue("callstats").videoOn():a(this,Be).getValue("callstats").videoOff();let n,o;if(r&&i)try{const c=yield a(this,tt).getAudioAndVideoTrack(a(this,Ce).userSelectedDevice,a(this,be).userSelectedDevice);n=c.audioTrack,o=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!n&&r)try{n=yield a(this,tt).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,tt).getVideoTrack(a(this,be).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}r&&!n&&a(this,Be).getValue("callstats").audioOff(),i&&!o&&a(this,Be).getValue("callstats").videoOff(),yield a(this,Ce).setMediaTrack(n),yield a(this,be).setMediaTrack(o);try{this.setupSpeaker()}catch{}if(o){const c=yield this.getDeviceById(o.getSettings().deviceId);a(this,Be).getValue("callstats").selectedDevice("VIDEO",c)}if(n){const c=yield this.getDeviceById(n.getSettings().deviceId);a(this,Be).getValue("callstats").selectedDevice("AUDIO",c)}(s=a(this,Ii).currentDevice)!=null&&s.deviceId&&a(this,Be).getValue("callstats").selectedDevice("SPEAKER",a(this,Ii).currentDevice),a(this,tt).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})})}getCurrentDevices(){return{audio:a(this,Ce).currentDevice,video:a(this,be).currentDevice,speaker:a(this,Ii).currentDevice}}get permissions(){return a(this,tt).permissions}getAllDevices(){return a(this,tt).getAvailableDevices()}getDeviceById(e,r){return a(this,tt).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,tt).getAudioInputDevices(e)}setAudioDevice(e){return u(this,null,function*(){yield a(this,Ce).setDevice(e),e!=null&&e.deviceId&&a(this,Be).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return u(this,null,function*(){yield a(this,Ii).setupSpeaker();const{speaker:e}=this.getCurrentDevices();e&&this.emit("DEVICE_CHANGE",{device:e})})}setSpeakerDevice(e){return u(this,null,function*(){yield a(this,Ii).setupSpeaker(e),e!=null&&e.deviceId&&a(this,Be).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,tt).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield a(this,be).setDevice(e),e!=null&&e.deviceId&&a(this,Be).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,yr).audioMediaTrack,video:a(this,yr).videoMediaTrack}}get screenShareEnabled(){return a(this,yr).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield a(this,yr).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){a(this,yr).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield a(this,yr).updateConstraints(e)})}getSpeakerDevices(e){return a(this,tt).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,yr).disableScreenShare(),a(this,tt).destruct()}onDeviceChange(e,r){return u(this,null,function*(){var i,s;this.emit("DEVICE_LIST_UPDATED",e),!(r||!a(this,sd))&&((i=e==null?void 0:e.added)==null||i.forEach(n=>u(this,null,function*(){var o;n&&!sh(n)&&(n.kind==="audioinput"&&((o=this.audioTrack)==null?void 0:o.enabled)===!0?yield this.setAudioDevice(n):n.kind==="audiooutput"&&(yield this.setSpeakerDevice(n)))})),(s=e==null?void 0:e.removed)==null||s.forEach(n=>u(this,null,function*(){var o;if(n.kind==="audiooutput"&&((o=this.getCurrentDevices().speaker)==null?void 0:o.deviceId)===n.deviceId){const c=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==n.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)})}}tt=new WeakMap,Ce=new WeakMap,be=new WeakMap,Ii=new WeakMap,yr=new WeakMap,sd=new WeakMap,Be=new WeakMap;er([k.trace("MediaHandler.setupStreams")],Wt.prototype,"setupStreams",1);er([k.trace("MediaHandler.enableAudio")],Wt.prototype,"enableAudio",1);er([k.trace("MediaHandler.disableAudio")],Wt.prototype,"disableAudio",1);er([k.trace("MediaHandler.setAudioDevice")],Wt.prototype,"setAudioDevice",1);er([k.trace("MediaHandler.enableVideo")],Wt.prototype,"enableVideo",1);er([k.trace("MediaHandler.disableVideo")],Wt.prototype,"disableVideo",1);er([k.trace("MediaHandler.setVideoDevice")],Wt.prototype,"setVideoDevice",1);er([k.trace("MediaHandler.updateVideoConstraints")],Wt.prototype,"updateVideoConstraints",1);er([k.trace("MediaHandler.enableScreenShare")],Wt.prototype,"enableScreenShare",1);er([k.trace("MediaHandler.disableScreenShare")],Wt.prototype,"disableScreenShare",1);er([k.trace("MediaHandler.updateScreenshareConstraints")],Wt.prototype,"updateScreenshareConstraints",1);er([k.trace("MediaHandler.destruct")],Wt.prototype,"destruct",1);er([k.trace("MediaHandler.onDeviceChange")],Wt.prototype,"onDeviceChange",1);function Mc(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 sO=["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:sO.some(s=>i==null?void 0:i.includes(s))}function nO(t,e,r){return u(this,null,function*(){if(!(e!=null&&e.length))return r;const i=t.getValue("logger"),s=new AudioContext,n=yield Promise.all(e==null?void 0:e.map(d=>d(s))),o=s.createMediaStreamSource(new MediaStream([r])),c=s.createMediaStreamDestination();try{let d=o;for(let l=0;l<n.length;l+=1)d.connect(n[l]),d=n[l];d.connect(c)}catch(d){return i.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),r}return c.stream.getAudioTracks()[0]})}var wn,nd;class aO{constructor(e){g(this,wn,void 0),g(this,nd,void 0),f(this,nd,e)}get logger(){return a(this,nd).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,wn))try{Bn(a(this,wn)),f(this,wn,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 s=document.createElement("canvas"),n=yield Promise.all(e==null?void 0:e.map(m=>m({canvas:s,WorkerTimers:$S})));if(i.disablePerFrameCanvasRendering){const m=s.captureStream().getVideoTracks()[0];return Object.defineProperty(m,"originalSettings",{value:r.getSettings()}),m}const o=document.createElement("video"),c=new MediaStream;c.addTrack(r);const d=s.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(),s.remove();return}try{d.drawImage(o,0,0);for(let m=0;m<n.length;m+=1)typeof n[m]=="function"&&(yield n[m](s,d))}catch(m){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:m})}});try{o.play()}catch{}o.addEventListener("play",()=>{s.width=o.width||r.getSettings().width,s.height=o.width||r.getSettings().height,f(this,wn,Wd(l,50))},!1);const h=s.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:r.getSettings()}),h})}}wn=new WeakMap,nd=new WeakMap;const pg={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}}},oO=[[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"}]]],cO=(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 s=oO;t.getValue("flagsmith").hasFeature(Z.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)&&(s=JSON.parse(t.getValue("flagsmith").getValue(Z.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)));const n=s.map(([d])=>d).sort((d,l)=>d-l);let o=Number.MAX_VALUE,c=0;return n.forEach((d,l)=>{Math.abs(d-i)<o&&(o=Math.abs(d-i),c=l)}),s[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 dO=Zw(),Xs=_r(dO.config.media);function lO(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 _n,zr;class uO{constructor(e,r){g(this,_n,void 0),g(this,zr,void 0),p(this,"getScreenShareConstraints",()=>{var i,s,n,o,c,d,l,h,m,v,S;const T=(i=a(this,_n))==null?void 0:i.screenshare,M=(n=(s=T==null?void 0:T.width)==null?void 0:s.max)!=null?n: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=(m=(h=T==null?void 0:T.frameRate)==null?void 0:h.ideal)!=null?m:5;const W=T==null?void 0:T.displaySurface,w=T==null?void 0:T.selfBrowserSurface;a(this,zr).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE)&&(j=parseInt((v=a(this,zr).getValue("flagsmith").getValue(Z.VAL_MIN_FRAMERATE))==null?void 0:v.toString(),10));let te={width:{max:M},height:{max:b},frameRate:{ideal:j,max:R}};if(a(this,zr).getValue("flagsmith").hasFeature(Z.SCREENSHARE_CONSTRAINTS)){const re=(S=a(this,zr).getValue("flagsmith").getValue(Z.SCREENSHARE_CONSTRAINTS))==null?void 0:S.toString();te=JSON.parse(re)}return W!==void 0&&["monitor","browser","window"].includes(W)&&(te=q(V({},te),{displaySurface:W})),w!==void 0&&(te=q(V({},te),{selfBrowserSurface:w})),{audio:!0,video:te}}),p(this,"getAudioConstraints",i=>{var s,n,o,c,d,l,h,m;const v={},S=(s=a(this,_n))==null?void 0:s.audio,T=S!=null&&S.enableStereo?2:1;return Ie.isFirefox()||Ie.isWebKitBased()?(v.audio={deviceId:i,autoGainControl:(n=S==null?void 0:S.autoGainControl)!=null?n:!0,echoCancellation:(o=S==null?void 0:S.echoCancellation)!=null?o:!0,noiseSuppression:(c=S==null?void 0:S.noiseSupression)!=null?c:!0,channelCount:T},v):(v.audio={},v.audio.optional=[i?{sourceId:i}:{sourceId:"default"},{channelCount:T},{echoCancellation:(d=S==null?void 0:S.echoCancellation)!=null?d:!0},{googEchoCancellation:(l=S==null?void 0:S.echoCancellation)!=null?l:!0},{googAutoGainControl:(h=S==null?void 0:S.autoGainControl)!=null?h:!0},{googNoiseSuppression:(m=S==null?void 0:S.noiseSupression)!=null?m:!0},{googHighpassFilter:!0}],v)}),p(this,"getVideoConstraints",i=>{var s,n,o,c;const d={},l=(s=a(this,_n))==null?void 0:s.video;let h=pg.vga;if(typeof l=="string"?h=pg[l]:l!==void 0&&(h.height.ideal=l.height.ideal,h.width.ideal=l.width.ideal),h.frameRate={ideal:(o=(n=h.frameRate)==null?void 0:n.ideal)!=null?o:24},Ie.isChromiumBased()&&(h.frameRate.max=30),a(this,zr).getValue("flagsmith").hasFeature(Z.VIDEO_CONSTRAINTS)){const m=(c=a(this,zr).getValue("flagsmith").getValue(Z.VIDEO_CONSTRAINTS))==null?void 0:c.toString();h=JSON.parse(m)}return d.video=h,typeof d.video=="boolean"||(i?d.video.deviceId={exact:i}:d.video.facingMode="user"),d}),f(this,zr,e),f(this,_n,r)}getUpdatedVideoConstraints(e){return e}}_n=new WeakMap,zr=new WeakMap;class au extends Error{constructor(e,r,i){super(r),p(this,"constraints"),p(this,"name"),this.name=e,this.constraints=i}}class hO{constructor(){p(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 pO=Object.defineProperty,mO=Object.getOwnPropertyDescriptor,Mr=(t,e,r,i)=>{for(var s=i>1?void 0:i?mO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&pO(e,r,s),s},Fa,hr,Ge,mg;let Qt=(mg=class extends hO{constructor(t,e){super(),p(this,"availableDevices"),g(this,Fa,void 0),g(this,hr,void 0),g(this,Ge,void 0),f(this,Ge,t),f(this,hr,new uO(t,e)),f(this,Fa,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get telemetry(){return a(this,Ge).getValue("telemetry")}get logger(){return a(this,Ge).getValue("logger")}get constraintsBuilder(){return a(this,hr)}destruct(){return u(this,null,function*(){var t;(t=a(this,Fa))==null||t.abort()})}handlePermissionErrors(t,e){const r=Mc(t,e.name,e.message);return this.permissions[t]=r,a(this,Ge).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,hr).getAudioConstraints(t).audio,video:a(this,hr).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 s=i.getAudioTracks()[0];let n=i.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",a(this,Ge).getValue("flagsmith").hasFeature(Z.OBS_QUALITY)&&n.label.includes("OBS Virtual")){const o=(yield this.getVideoInputDevices()).find(c=>c.label.includes("OBS Virtual"));n=yield this.getVideoTrack(o.deviceId)}return a(this,Ge).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,Ge).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:s,videoTrack:n}}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,Ge).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new I("No audio devices available","1606");const i=s=>u(this,null,function*(){let n;try{r=r.filter(c=>c.deviceId!==s),n=a(this,hr).getAudioConstraints(s),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(n)});const[o]=(yield navigator.mediaDevices.getUserMedia(n)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(n)}),o}catch(o){const c=Mc("audio",o.name,o.message),d=new au(o.name,o.message,n);if(c==="COULD_NOT_START"){const l=r.shift();if(!l)throw d;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(n),error:o});const h=a(this,hr).getAudioConstraints(l.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(h)}),i(l.deviceId)}throw d}});try{const s=yield i(e);return s.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,Ge).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),s}catch(s){throw s.constraints&&this.handlePermissionErrors("audio",s),new I(s.message,"1601")}})}getVideoTrack(t){return u(this,null,function*(){var e;const r=a(this,Ge).getValue("flagsmith").hasFeature(Z.OBS_QUALITY),i=(e=yield this.getCurrentDeviceLabel(t))==null?void 0:e.includes("OBS Virtual"),s=r&&i,n=yield this.getVideoInputDevices();if(n.length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",a(this,Ge).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;s&&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(s&&typeof l!="boolean"&&typeof l.width=="object"){const{width:m,height:v}=h.getSettings(),{ideal:S}=l.width;h.applyConstraints({width:{ideal:S},height:{ideal:Math.floor(v*S/m)},frameRate:l.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(d)}),h}catch(d){const l=Mc("video",d.name,d.message),h=new au(d.name,d.message,c);if(l==="COULD_NOT_START"){const m=n.shift();if(!m)throw h;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(c),error:d});const v=a(this,hr).getVideoConstraints(m.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,hr).getVideoConstraints(t),d=yield o(c);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,Ge).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,Ge).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=Mc("video",r.name,r.message),s=new au(r.name,r.message,e),n={video:!0};if(k0(e,n)||!a(this,Ge).getValue("flagsmith").hasFeature(Z.SCREEENSHARE_CONSTRAINTS_RETRY))throw s;if(i==="COULD_NOT_START")return t(n);throw s}});try{const e=a(this,hr).getScreenShareConstraints(),r=yield t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,Ge).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 s=h=>`${h.kind}-${h.deviceId}-${h.groupId}`,n=this.availableDevices,o=new Set(n.map(h=>s(h))),c=yield this.getAvailableDevices(),d=new Set(c.map(h=>s(h))),l={added:c.filter(h=>!o.has(s(h))),removed:n.filter(h=>!d.has(s(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(m=>m.kind==="audioinput")&&a(this,Ge).getValue("callstats").devices("AUDIO",c==null?void 0:c.filter(m=>m.kind==="audioinput")),h.some(m=>m.kind==="videoinput")&&a(this,Ge).getValue("callstats").devices("VIDEO",c==null?void 0:c.filter(m=>m.kind==="videoinput")),h.some(m=>m.kind==="audiooutput")&&a(this,Ge).getValue("callstats").devices("SPEAKER",c==null?void 0:c.filter(m=>m.kind==="audiooutput")),t(e,l,!1)}}),{signal:a(this,Fa).signal})})}},Fa=new WeakMap,hr=new WeakMap,Ge=new WeakMap,mg);Mr([k.trace("WebMediaInterface.destruct")],Qt.prototype,"destruct",1);Mr([k.trace("WebMediaInterface.handlePermissionErrors")],Qt.prototype,"handlePermissionErrors",1);Mr([k.trace("WebMediaInterface.getAudioAndVideoTrack")],Qt.prototype,"getAudioAndVideoTrack",1);Mr([k.trace("WebMediaInterface.getAudioTrack")],Qt.prototype,"getAudioTrack",1);Mr([k.trace("WebMediaInterface.getVideoTrack")],Qt.prototype,"getVideoTrack",1);Mr([k.trace("WebMediaInterface.getScreenShareTracks")],Qt.prototype,"getScreenShareTracks",1);Mr([k.trace("WebMediaInterface.getAvailableDevices")],Qt.prototype,"getAvailableDevices",1);Mr([k.trace("WebMediaInterface.getAvailableDevicesByKind")],Qt.prototype,"getAvailableDevicesByKind",1);Mr([k.trace("WebMediaInterface.getDevice")],Qt.prototype,"getDevice",1);Mr([k.trace("WebMediaInterface.onDeviceChange")],Qt.prototype,"onDeviceChange",1);Qt=Mr([gt("1600")],Qt);const iy=Qt,xo={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}},gO=(t=0)=>new Promise(e=>setTimeout(e,t)),fO=(t,e,r)=>{const i=typeof r=="number"?r:250,s=t.createMediaStreamSource(e),n=t.createAnalyser();n.fftSize=2048,s.connect(n);const o=new Uint8Array(n.fftSize);let c=!1;setTimeout(()=>{c=!0},i);function d(){return c?Promise.resolve(!0):(n.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):gO().then(d))}return d().then(l=>(s.disconnect(),l),l=>{throw s.disconnect(),l})},vO=typeof AudioContext!="undefined"?AudioContext:null;class yp{constructor(e){p(this,"_AudioContext"),p(this,"audioContext"),p(this,"_audioContextRefContainers");const r=V({AudioContext:vO},e);Object.defineProperties(this,{_AudioContext:{value:r.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:yp}})}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 gg=new yp,yO=3,SO=250;function EO(t){const e={},r=gg.getOrCreate(e);let i=yO;function s(){return i-=1,fO(r,t.srcObject,SO).then(n=>n?i>0?s():!0:!1).catch(()=>!0)}return s().finally(()=>{gg.release(e)})}function fg(t,e){return u(this,null,function*(){const r=new Audio,i=new MediaStream;i.addTrack(e),r.srcObject=i;let s=!1;try{const n=r.play();n&&(yield n),s=yield EO(r),s&&t.info("checkIfAudioTrackIsSilent::silence_detected")}catch(n){t.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:n})}finally{r.pause(),r.remove()}return s})}var kO=Object.defineProperty,TO=Object.getOwnPropertyDescriptor,sy=(t,e,r,i)=>{for(var s=i>1?void 0:i?TO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&kO(e,r,s),s};let Zd=class extends ia{constructor(t,e,r,i){var s;const n=t.getValue("logger");super(n),p(this,"constructorName",this.constructor.name),p(this,"userSelectedDevice"),p(this,"mediaInterface"),p(this,"isNonPreferredDevice"),p(this,"_mediaTrack"),p(this,"transformedMediaTrack"),p(this,"middlewares",[]),p(this,"currentDevice"),p(this,"userPreferredDeviceKey",`Dyte::${this.constructorName}::UserDeviceID`),p(this,"setUserPreferredDevice",o=>xo.setItem(this.userPreferredDeviceKey,o,this.logger)),p(this,"getUserPreferredDevice",()=>xo.getItem(this.userPreferredDeviceKey,this.logger)),p(this,"isCustomTrack",!1),p(this,"context"),this.context=t,this.mediaInterface=e,r&&this.setMediaTrack(r),this.userSelectedDevice=(s=this.getUserPreferredDevice())!=null?s: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,e;const{kind:r}=this.mediaTrack;switch(r){case"audio":{const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(e=(t=i==null?void 0:i.deviceId)!=null?t:i==null?void 0:i.advanced[0].deviceId)!=null?e:this.mediaTrack.getSettings().deviceId:this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}setCurrentDevice(){return u(this,null,function*(){var t;if(!this.mediaTrack){this.currentDevice=void 0;return}const e=this.getCurrentDeviceId();((t=this.currentDevice)==null?void 0:t.deviceId)!==e&&(this.currentDevice=yield this.mediaInterface.getDevice(e))})}setDevice(t){return u(this,null,function*(){if(!t)throw 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()&&!jw.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))}};sy([k.trace("BaseMediaHandler.unmuteTrack")],Zd.prototype,"unmuteTrack",1);Zd=sy([gt("1600")],Zd);const ny=Zd;var bO=Object.defineProperty,wO=Object.getOwnPropertyDescriptor,Sp=(t,e,r,i)=>{for(var s=i>1?void 0:i?wO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&bO(e,r,s),s};const ou="[Dyte]nonSilentDeviceLabels";class Rl extends ny{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)),this.userSelectedDevice=void 0}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 nO(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 s=e;const n=yield this.mediaInterface.getAudioInputDevices(),o=this.isNonPreferredDevice?n.filter(l=>l&&!this.isNonPreferredDevice(l)):n;if(!(o!=null&&o.length))return s;o.find(l=>l.deviceId===e.getSettings().deviceId)||(s.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),s=yield this.mediaInterface.getAudioTrack(!1,o[0].deviceId));const c=JSON.parse(xo.getItem(ou,this.logger));if(c!=null&&c.devices.some(l=>l.label===s.label))return s;if(!(yield fg(this.logger,s))){const l=(i=c==null?void 0:c.devices.concat({label:s.label}))!=null?i:[{label:s.label}];return xo.setItem(ou,JSON.stringify({devices:l}),this.logger),s}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const d=s.getSettings().deviceId;return o.filter(l=>l.deviceId!==d).some(l=>u(this,null,function*(){if(s=yield this.mediaInterface.getAudioTrack(!1,l.deviceId),!(yield fg(this.logger,s))){const h=c.devices.concat({label:s.label});return xo.setItem(ou,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),s})}}Sp([k.trace("AudioMediaHandler.setTransformedTrack")],Rl.prototype,"setTransformedTrack",1);Sp([k.trace("AudioMediaHandler.onTrackEnded")],Rl.prototype,"onTrackEnded",1);Sp([k.trace("AudioMediaHandler.conditionallyChangeTrack")],Rl.prototype,"conditionallyChangeTrack",1);const _O=Rl;var uo;class IO{constructor(e){g(this,uo,void 0),p(this,"currentDevice"),f(this,uo,e)}setupSpeaker(e){return u(this,null,function*(){var r,i;if(!(a(this,uo)instanceof iy))return;let s=e;if(e||([s]=(yield a(this,uo).getAvailableDevicesByKind("audiooutput")).filter(o=>!sh(o))),!s)throw new I("No speaker found","1608");if(((r=this.currentDevice)==null?void 0:r.deviceId)===s.deviceId)return;this.currentDevice=s;const n=document.querySelectorAll("audio");(i=n[0])!=null&&i.setSinkId&&n.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{}}))})}}uo=new WeakMap;const CO=IO;var ad;class PO extends ia{constructor(e,r){const i=e.getValue("logger");super(i),p(this,"mediaInterface"),p(this,"audioMediaTrack"),p(this,"videoMediaTrack"),g(this,ad,void 0),f(this,ad,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}enableScreenShare(){return u(this,null,function*(){var e,r;try{const{audioTrack:i,videoTrack:s}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=s,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,ad).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")}}ad=new WeakMap;const RO=PO;var MO=Object.defineProperty,AO=Object.getOwnPropertyDescriptor,Ml=(t,e,r,i)=>{for(var s=i>1?void 0:i?AO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&MO(e,r,s),s},ho,od;class cc extends ny{constructor(e,r,i,s){super(e,r,i,s),g(this,ho,void 0),g(this,od,{disablePerFrameCanvasRendering:!1}),f(this,ho,new aO(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,ho).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,od)),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,od,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,ho).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 s=yield this.mediaInterface.getVideoInputDevices(),n=this.isNonPreferredDevice?s.filter(o=>!this.isNonPreferredDevice(o)):s;return!(n!=null&&n.length)||window.FAST_DYTE||n.find(o=>o.deviceId===e.getSettings().deviceId)||(i.stop(),this.logger.info("localmediahandler::setupstreams::found_video_non_preferred"),i=yield this.mediaInterface.getVideoTrack(n[0].deviceId)),i})}}ho=new WeakMap,od=new WeakMap;Ml([k.trace("VideoMediaHandler.setTransformedTrack")],cc.prototype,"setTransformedTrack",1);Ml([k.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],cc.prototype,"setVideoMiddlewareGlobalConfig",1);Ml([k.trace("VideoMediaHandler.onTrackEnded")],cc.prototype,"onTrackEnded",1);Ml([k.trace("VideoMediaHandler.conditionallyChangeTrack")],cc.prototype,"conditionallyChangeTrack",1);const DO=cc,vg=_r(dp());var Jt,In,cd,po;const mo=class{constructor(t){if(g(this,Jt,void 0),g(this,In,void 0),g(this,cd,void 0),g(this,po,void 0),!t)throw new I("Could not load preset.","0904");f(this,Jt,t.config),f(this,cd,t.name),f(this,In,t.ui||_r(dp().ui)),f(this,po,t.permissions.plugins.config)}static fromResponse(t){return new mo(t)}static default(){return new mo(vg)}static init(t,e=!0){return!t||e?new mo(vg):new mo(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,In).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,po)).filter(t=>a(this,po)[t].disabled)}get designTokens(){return a(this,In).designTokens}get configDiff(){return a(this,In).configDiff}get mediaConstraints(){var t,e,r,i,s,n,o,c,d,l,h,m,v,S,T,M,b,R,j,W,w,te,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:Xs.audio.enableStereo,enableHighBitrate:(c=(o=(n=(s=a(this,Jt))==null?void 0:s.media)==null?void 0:n.audio)==null?void 0:o.enableHighBitrate)!=null?c:Xs.audio.enableHighBitrate},video:{quality:(m=(h=(l=(d=a(this,Jt))==null?void 0:d.media)==null?void 0:l.video)==null?void 0:h.quality)!=null?m:Xs.video.quality,frameRate:(M=(T=(S=(v=a(this,Jt))==null?void 0:v.media)==null?void 0:S.video)==null?void 0:T.frameRate)!=null?M:Xs.video.frameRate},screenshare:{quality:(W=(j=(R=(b=a(this,Jt))==null?void 0:b.media)==null?void 0:R.screenshare)==null?void 0:j.quality)!=null?W:Xs.screenshare.quality,frameRate:(ae=(re=(te=(w=a(this,Jt))==null?void 0:w.media)==null?void 0:te.screenshare)==null?void 0:re.frameRate)!=null?ae:Xs.screenshare.frameRate}}}get name(){return a(this,cd)}};let OO=mo;Jt=new WeakMap,In=new WeakMap,cd=new WeakMap,po=new WeakMap;var NO=Object.defineProperty,VO=Object.getOwnPropertyDescriptor,ay=(t,e,r,i)=>{for(var s=i>1?void 0:i?VO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&NO(e,r,s),s},go,dd;class Ep extends Xt{constructor(e,r){const i=e.getValue("logger");super(i),g(this,go,void 0),p(this,"state","IDLE"),p(this,"playbackUrl"),p(this,"ingestionCredentials"),p(this,"viewerCount"),g(this,dd,void 0),f(this,go,r),f(this,dd,e),this.viewerCount=0}get telemetry(){return a(this,dd).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,go).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=ht(),{playbackUrl:i,ingestionCredentials:s}=yield r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=s,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,go).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 ht().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)}})}}go=new WeakMap,dd=new WeakMap;ay([k.trace("livestream.start")],Ep.prototype,"start",1);ay([k.trace("livestream.stop")],Ep.prototype,"stop",1);var LO=Object.defineProperty,xO=Object.getOwnPropertyDescriptor,UO=(t,e,r,i)=>{for(var s=i>1?void 0:i?xO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&LO(e,r,s),s},fo,vo,Ci,Yr;class oy{constructor(e,r,i){p(this,"livestream"),g(this,fo,void 0),g(this,vo,void 0),g(this,Ci,void 0),g(this,Yr,void 0),f(this,Yr,e),f(this,vo,r),this.livestream=new Ep(e,r),f(this,Ci,i),this.setupEvents()}get logger(){return a(this,Yr).getValue("logger")}get telemetry(){return a(this,Yr).getValue("telemetry")}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=ht(),{status:r,playbackUrl:i,manualIngest:s,ingestionCredentials:n}=yield e.getActiveLivestream();this.livestream.playbackUrl=i,this.livestream.ingestionCredentials=n,r==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),r==="INVOKED"&&s&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")})}setupEvents(){a(this,Ci).on(F.startedLivestream,e=>u(this,null,function*(){this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,vo).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}})),a(this,Ci).on(F.livestreamingInvoked,e=>u(this,null,function*(){if(e.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,vo).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch{this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}})),a(this,Ci).on(F.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,Ci).on(F.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,Ci).on(F.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),a(this,Yr).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,fo,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),a(this,Yr).getValue("peerSessionStore").on(P.PEER_CLOSED,e=>{e.id===a(this,fo)&&(f(this,fo,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,Yr).getValue("peerSessionStore").onAsync(P.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){this.livestream.playbackUrl||(this.logger.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),a(this,Yr).getValue("peerSessionStore").on(P.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch{this.logger.error("Error: LivestreamController.fetchLivestream")}}))}}fo=new WeakMap,vo=new WeakMap,Ci=new WeakMap,Yr=new WeakMap;UO([k.trace("LivestreamController.setupEvents")],oy.prototype,"setupEvents",1);var FO=Object.defineProperty,BO=Object.getOwnPropertyDescriptor,dc=(t,e,r,i)=>{for(var s=i>1?void 0:i?BO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&FO(e,r,s),s},bt,hs,ps,nh,cy;class aa{constructor({name:e,socketHandler:r,meetingId:i}){g(this,nh),p(this,"name",""),g(this,bt,{}),g(this,hs,""),g(this,ps,void 0),p(this,"rateLimitConfig",{maxInvocations:5,period:1}),p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1}),p(this,"listeners",{}),this.name=e,f(this,ps,r),f(this,hs,i)}set(e,r,i=!0,s=!1){return u(this,null,function*(){a(this,bt)[e]=r,i&&this.remoteSet(e,r),s&&(this.listeners[e]&&this.listeners[e].forEach(n=>n({[e]:a(this,bt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[e]:a(this,bt)[e]})))})}remoteSet(e,r){a(this,ps).storeInsertKeys(a(this,hs),this.name,[{key:e,payload:r}])}bulkSet(e){return u(this,null,function*(){e.forEach(({key:r,payload:i})=>{a(this,bt)[r]=i}),a(this,ps).storeInsertKeys(a(this,hs),this.name,e)})}update(e,r,i=!0){return u(this,null,function*(){U(this,nh,cy).call(this,e,r,i)})}delete(e,r=!0,i=!1){return u(this,null,function*(){if(a(this,bt)[e]&&delete a(this,bt)[e],r)return a(this,ps).storeDeleteKeys(a(this,hs),this.name,[{key:e}]);i&&(this.listeners[e]&&(this.listeners[e].forEach(s=>s({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:void 0})))})}bulkDelete(e){return u(this,null,function*(){return e.forEach(({key:r})=>{a(this,bt)[r]&&delete a(this,bt)[r]}),a(this,ps).storeDeleteKeys(a(this,hs),this.name,e)})}get(e){if(a(this,bt)[e])return a(this,bt)[e]}getAll(){return a(this,bt)}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(s=>s!==r))||[];return}this.listeners[e]&&delete this.listeners[e]}populate(e){f(this,bt,e)}}bt=new WeakMap,hs=new WeakMap,ps=new WeakMap,nh=new WeakSet,cy=function(t,e,r=!0){let i;const s=a(this,bt)[t],n=Object.prototype.toString.call(e),o=Object.prototype.toString.call(s);if(n!==o){this.set(t,e);return}switch(o){case"[object Array]":i=[...s,...e];break;case"[object Object]":i=V(V({},s),e);break;case"[object Map]":i=new Map([...s,...e]);break;case"[object Set]":i=new Set([...s,...e]);break;default:i=e;break}this.set(t,i,r)};dc([Bt(na,"rateLimitConfig")],aa.prototype,"remoteSet",1);dc([Bt(na,"bulkRateLimitConfig")],aa.prototype,"bulkSet",1);dc([Bt(na,"rateLimitConfig")],aa.prototype,"update",1);dc([Bt(na,"rateLimitConfig")],aa.prototype,"delete",1);dc([Bt(na,"bulkRateLimitConfig")],aa.prototype,"bulkDelete",1);var Wn,jn,ld,cu,el,_s,ah,dy;class WO{constructor(e,r){g(this,ld),g(this,ah),p(this,"stores",new Map),g(this,Wn,void 0),g(this,jn,""),g(this,el,void 0),g(this,_s,new Map),f(this,Wn,r),f(this,jn,e.getValue("meetingId")),f(this,el,e),U(this,ah,dy).call(this)}create(e){const r=new aa({name:e,socketHandler:a(this,Wn),meetingId:a(this,jn)});return a(this,Wn).storeGetKeys(a(this,jn),e,[]),new Promise((i,s)=>{const n=setTimeout(()=>s(Error("Failed")),3e3);a(this,_s).set(e,{rejectTimeout:n,resolve:i,store:r})})}}Wn=new WeakMap,jn=new WeakMap,ld=new WeakSet,cu=function(){return a(this,el).getValue("peerId")},el=new WeakMap,_s=new WeakMap,ah=new WeakSet,dy=function(){[$.storeInsertKeys,$.storeGetKeys,$.storeDeleteKeys].forEach(t=>{a(this,Wn).on(t,e=>u(this,null,function*(){var r,i;if(e.pluginId!==a(this,jn))return;const s=(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===$.storeGetKeys){const o=a(this,_s).get(e.storeName),c=this.stores.get(e.storeName)||(o==null?void 0:o.store);a(this,_s).get(e.storeName)&&(this.stores.set(e.storeName,o.store),o.resolve(c),clearTimeout(o.rejectTimeout),a(this,_s).delete(e.storeName)),s.forEach(d=>{c.set(d.key,d.payload,!1,!1)});return}const n=this.stores.get(e.storeName)||((i=a(this,_s).get(e.storeName))==null?void 0:i.store);n!==void 0&&(t===$.storeInsertKeys&&s.forEach(({key:o,peerId:c,payload:d})=>{c!==a(this,ld,cu)&&n.set(o,d,!1,!0)}),t===$.storeDeleteKeys&&s.forEach(({key:o,peerId:c})=>{c!==a(this,ld,cu)&&n.delete(o,!1,!0)}))}))})};function Is(t){var e,r,i,s,n,o,c,d,l,h,m,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?(s=t.mediaPermissions)==null?void 0:s.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(n=t.mediaPermissions)==null?void 0:n.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:(m=(h=t.screenShareTracks)==null?void 0:h.video)==null?void 0:m.enabled,trackId:(S=(v=t.screenShareTracks)==null?void 0:v.video)==null?void 0:S.id}}}}:{}}var jO=Object.defineProperty,HO=Object.getOwnPropertyDescriptor,oa=(t,e,r,i)=>{for(var s=i>1?void 0:i?HO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&jO(e,r,s),s};const GO=.8,qO=1.2;var Ba,Wa,sr,Zs,ja,ts,en,tn,Ha,du,yg,mi,Ac,rs,rn,Ga,gi,lu,Dc,uu,hu,Sg,pu,Eg,kg;let li=(kg=class extends Xt{constructor(t,e,r,i){const s=t.getValue("logger");super(s),g(this,Zs),g(this,ts),g(this,tn),g(this,du),g(this,rn),g(this,Dc),g(this,hu),g(this,pu),p(this,"id"),p(this,"userId"),p(this,"name"),p(this,"picture"),p(this,"isHost"),p(this,"customParticipantId"),p(this,"flags"),p(this,"device"),p(this,"videoTrack"),p(this,"audioTrack"),p(this,"screenShareTracks"),p(this,"videoEnabled"),p(this,"audioEnabled"),p(this,"screenShareEnabled"),p(this,"producers"),p(this,"manualProducerConfig"),g(this,Ba,void 0),p(this,"supportsRemoteControl",!1),g(this,Wa,void 0),p(this,"presetName"),g(this,sr,void 0),g(this,mi,void 0),g(this,Ac,void 0),g(this,rs,new Map),g(this,gi,1),g(this,lu,lp(te=>{if(!this.videoTrack)return;const{clientWidth:re,clientHeight:ae}=te,{width:Ae,height:Xe}=this.videoTrack.getSettings();if(!Ae||!Xe)return;const jt=Xe/ae,A=Ae/re,E=Math.max(jt,A);E>qO&&a(this,gi)===1?(f(this,gi,0),a(this,sr).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,gi)})):E<GO&&a(this,gi)===0&&(f(this,gi,1),a(this,sr).getValue("peerSessionStore").emit(P.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,gi)}))},2e3)),f(this,sr,t);const{id:n,userId:o,displayName:c,device:d,picture:l,isHost:h,flags:m,clientSpecificId:v,stageStatus:S,customParticipantId:T,audioMuted:M,audioTrack:b,videoEnabled:R=!1,videoTrack:j,producers:W,metadata:w}=e;this.id=n,this.userId=o,this.name=c,this.device=d,this.picture=l,this.isHost=h,this.flags=m,this.manualProducerConfig=_0,f(this,Wa,S!=null?S:"ON_STAGE"),this.customParticipantId=T!=null?T:v,this.audioEnabled=!M,this.audioTrack=b,this.videoEnabled=R,this.videoTrack=j,this.screenShareTracks={audio:void 0,video:void 0},this.producers=W!=null?W:[],this.presetName=w==null?void 0:w.preset_name,f(this,Ba,!1),f(this,mi,r),f(this,Ac,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),U(this,Dc,uu).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return a(this,Wa)}get telemetry(){return a(this,sr).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("DyteParticipant::setVideoEnabled::videoUpdate",V({},Is(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({},Is(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,Dc,uu)),a(this,ts,en)&&(this.on("audioUpdate",U(this,hu,Sg)),this.on("screenShareUpdate",U(this,pu,Eg)))}pin(){return u(this,null,function*(){if(!a(this,tn,Ha))throw new I("Can`t pin participant without joining room","1205");if(!a(this,mi).permissions.pinParticipant)throw new I("You do not have permission to pin participants.","1201");return a(this,Zs,ja).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!a(this,tn,Ha))throw new I("Can`t unpin participant without joining room","1205");if(!a(this,mi).permissions.pinParticipant)throw new I("You do not have permission to unpin participants.","1201");return a(this,Zs,ja).pinPeer(null)})}setIsPinned(t,e=!0){var r;f(this,Ba,t);const i=t?"pinned":"unpinned";(r=a(this,rn,Ga))==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,tn,Ha))throw new I("Can`t disable participant audio without joining room","1205");if(a(this,mi).permissions.canDisableParticipantAudio)return a(this,Zs,ja).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,yg))throw new I("Can`t kick participant without joining room","1205");if(a(this,mi).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,tn,Ha))throw new I("Can`t disable participant video without joining room","1205");if(a(this,mi).permissions.canDisableParticipantVideo)return a(this,Zs,ja).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,Ac).getUserPermissions(this.userId)})}setStageStatus(t){f(this,Wa,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,Ba)}registerVideoElement(t){var e,r,i,s;if(!t)return;let n;(r=(e=a(this,rs).get(t))==null?void 0:e.observer)==null||r.disconnect(),"ResizeObserver"in window&&(n=new ResizeObserver(()=>a(this,lu).call(this,t)),n.observe(t)),a(this,rs).set(t,{observer:n}),this.updateVideo(t),(s=a(this,rn,Ga))==null||s.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(i=this.raised)!=null?i:!1)}deregisterVideoElement(t){var e,r,i,s;if(!t){(e=a(this,rn,Ga))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,rs).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,rs).delete(t),(s=a(this,rn,Ga))==null||s.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"}},Ba=new WeakMap,Wa=new WeakMap,sr=new WeakMap,Zs=new WeakSet,ja=function(){return a(this,sr).getValue("roomNodeClient")},ts=new WeakSet,en=function(){return a(this,sr).getValue("audioPlayback")},tn=new WeakSet,Ha=function(){return a(this,sr).getValue("connectionHandler").mediaJoined},du=new WeakSet,yg=function(){return a(this,sr).getValue("connectionHandler").socketJoined},mi=new WeakMap,Ac=new WeakMap,rs=new WeakMap,rn=new WeakSet,Ga=function(){return a(this,sr).getValue("pip")},gi=new WeakMap,lu=new WeakMap,Dc=new WeakSet,uu=function(){Array.from(a(this,rs).keys()).forEach(this.updateVideo)},hu=new WeakSet,Sg=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,ts,en))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,ts,en))==null||e.removeParticipantTrack(this.id)},pu=new WeakSet,Eg=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,ts,en))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,ts,en))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},kg);oa([k.trace("DyteParticipant.disableAudio")],li.prototype,"disableAudio",1);oa([k.trace("DyteParticipant.kick")],li.prototype,"kick",1);oa([k.trace("DyteParticipant.disableVideo")],li.prototype,"disableVideo",1);oa([k.trace("DyteParticipant.getPermissions")],li.prototype,"getPermissions",1);oa([k.trace("DyteParticipant.setStageStatus")],li.prototype,"setStageStatus",1);li=oa([gt("1200")],li);class Cs extends ey{constructor(e,r){const{onAddEvent:i="participantJoined",onDeleteEvent:s="participantLeft",onClearEvent:n="participantsCleared"}=r!=null?r:{};super({onAddEvent:i,onDeleteEvent:s,onClearEvent:n},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 ms;class $O extends ia{constructor(e){super(e),g(this,ms,void 0),f(this,ms,new Map)}__set(e,r){return a(this,ms).set(e,r)}__clear(){return a(this,ms).clear()}get(e){return a(this,ms).get(e)}toArray(){return Array.from(a(this,ms).values())}}ms=new WeakMap;class JO{constructor(){p(this,"_orderedArray"),p(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 s=this.add(e,r);return i!==s?s:-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 KO{constructor(){p(this,"_activeSpeakerPeers"),p(this,"_compulsoryPeers"),this._activeSpeakerPeers=new JO,this._compulsoryPeers=new Set}add(e,r,i){if(!e)return-1;if(r<0)return this._compulsoryPeers.add(e),0;const s=i.getValue("logger");if(this.compulsoryPeers.includes(e)&&(r>0||r===246267631)){if(s.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 ly=new KO;var zO=Object.defineProperty,YO=Object.getOwnPropertyDescriptor,tr=(t,e,r,i)=>{for(var s=i>1?void 0:i?YO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&zO(e,r,s),s};const QO=["ACTIVE_GRID","PAGINATED","MANUAL"];var qe,sn,qa,nn,$a,Ja,Oc,an,Ht,Tg;let Rt=(Tg=class extends Xt{constructor(t,e,r){const i=t.getValue("logger");super(i),g(this,sn),g(this,nn),g(this,Ja),p(this,"waitlisted"),p(this,"joined"),p(this,"active"),p(this,"videoSubscribed"),p(this,"audioSubscribed"),p(this,"pinned"),p(this,"all"),g(this,qe,void 0),g(this,an,void 0),g(this,Ht,void 0),p(this,"rateLimitConfig",{maxInvocations:5,period:1}),p(this,"viewMode"),p(this,"currentPage"),p(this,"lastActiveSpeaker"),p(this,"selectedPeers",ly),f(this,qe,t),f(this,an,e),f(this,Ht,r),this.waitlisted=new Cs(i),this.joined=new Cs(i),this.videoSubscribed=new Cs(i),this.audioSubscribed=new Cs(i),this.active=this.videoSubscribed,this.pinned=new Cs(i),this.all=new $O(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,qe).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,qe).getValue("telemetry")}setupEvents(){a(this,qe).getValue("peerSessionStore").on(P.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,qe).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,qe).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,qe))==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,qe).setValue("maxPreferredStreams",t),a(this,Ja,Oc)&&a(this,qe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE)}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,nn,$a))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,s;return(s=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?s:r});return a(this,Ht).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return u(this,null,function*(){var e,r;if(!a(this,nn,$a))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=>QO.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}if(t==="MANUAL")throw new I("Manual Subscription is not enabled for your Organization. Please contact support.","1208");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,a(this,qe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,a(this,qe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE)),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");const i=[];e.forEach(s=>{const n=this.joined.get(s);if(n){if(r.includes("audio")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{audio:!0}),this.videoSubscribed.add(n);const o=n.producers.find(c=>c.kind==="audio"&&!c.screenShare);o&&i.push(o)}if(r.includes("video")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{video:!0}),this.audioSubscribed.add(n);const o=n.producers.find(c=>c.kind==="video"&&!c.screenShare);o&&i.push(o)}if(r.includes("screenshareAudio")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareAudio:!0});const o=n.producers.find(c=>c.kind==="audio"&&c.screenShare);i.push(o)}if(r.includes("screenshareVideo")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareVideo:!0});const o=n.producers.find(c=>c.kind==="video"&&c.screenShare);i.push(o)}}}),yield a(this,sn,qa).createConsumers(i)})}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");const i=[];e.forEach(s=>{const n=this.joined.get(s);if(n){if(r.includes("audio")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{audio:!1});const o=n.producers.find(c=>c.kind==="audio"&&!c.screenShare);o&&i.push(o)}if(r.includes("video")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{video:!1});const o=n.producers.find(c=>c.kind==="video"&&!c.screenShare);o&&i.push(o)}if(r.includes("screenshareAudio")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareAudio:!1});const o=n.producers.find(c=>c.kind==="audio"&&c.screenShare);i.push(o)}if(r.includes("screenshareVideo")){n.manualProducerConfig=q(V({},n.manualProducerConfig),{screenshareVideo:!1});const o=n.producers.find(c=>c.kind==="video"&&c.screenShare);i.push(o)}}}),yield a(this,sn,qa).closeConsumers(i)})}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)),s=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),n=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(s,n))}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,qe).getValue("peerSessionStore").emit(P.UPDATE_ACTIVE,{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,Ja,Oc))throw new I("Can`t disable all audio without joining room","1205");if(a(this,an).permissions.canAllowParticipantAudio)return a(this,sn,qa).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,Ja,Oc))throw new I("Can`t disable all video without joining room","1205");if(a(this,an).permissions.canAllowParticipantVideo)return a(this,sn,qa).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,qe).getValue("peerSessionStore").emitAsync(P.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(this.logger.info("DyteParticipants::kick_all"),a(this,qe).getValue("viewType")!=="LIVESTREAM"&&!a(this,nn,$a))throw new I("Can`t kick all without joining room","1205");if(!a(this,an).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,qe).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,nn,$a))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(s=>{var n;return(n=r.presetNames)==null?void 0:n.includes(s.presetName)}).map(s=>s.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(hi.formatSocketServiceMessage)})}updatePermissions(t,e){return u(this,null,function*(){const r=this.joined.toArray().filter(s=>t.includes(s.id)).map(s=>s.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()})}},qe=new WeakMap,sn=new WeakSet,qa=function(){return a(this,qe).getValue("roomNodeClient")},nn=new WeakSet,$a=function(){var t;return((t=a(this,qe).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Ja=new WeakSet,Oc=function(){var t;return((t=a(this,qe).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},an=new WeakMap,Ht=new WeakMap,Tg);tr([k.trace("DyteParticipants.setViewMode")],Rt.prototype,"setViewMode",1);tr([k.trace("DyteParticipants.setPage")],Rt.prototype,"setPage",1);tr([k.trace("DyteParticipants.disableAllAudio")],Rt.prototype,"disableAllAudio",1);tr([k.trace("DyteParticipants.disableAllVideo")],Rt.prototype,"disableAllVideo",1);tr([k.trace("DyteParticipants.disablePeerAudio")],Rt.prototype,"disableAudio",1);tr([k.trace("DyteParticipants.disablePeerVideo")],Rt.prototype,"disableVideo",1);tr([k.trace("DyteParticipants.kickPeer")],Rt.prototype,"kick",1);tr([k.trace("DyteParticipants.kickAll")],Rt.prototype,"kickAll",1);tr([k.trace("DyteParticipants.broadcastMessage"),Bt(na,"rateLimitConfig")],Rt.prototype,"broadcastMessage",1);tr([k.trace("DyteParticipants.getAllJoinedPeers"),Bt({maxInvocations:10,period:60})],Rt.prototype,"getAllJoinedPeers",1);tr([k.trace("DyteParticipant.updatePermissions"),Bt({maxInvocations:1e3,period:60})],Rt.prototype,"updatePermissions",1);tr([k.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],Rt.prototype,"getParticipantsInMeetingPreJoin",1);Rt=tr([gt("1200")],Rt);var ra=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t.CLOSED="closed",t))(ra||{}),Me=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(Me||{}),XO=Object.defineProperty,ZO=Object.getOwnPropertyDescriptor,qs=(t,e,r,i)=>{for(var s=i>1?void 0:i?ZO(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&XO(e,r,s),s},fi,on,cn,dn,Ka,bg;const ud=(bg=class{constructor(t,e,r,i){p(this,"participants"),p(this,"self"),p(this,"selectedPeers",ly),p(this,"maxSpatialLayerUpdates",new Map),p(this,"consumerPeerMap"),p(this,"events"),p(this,"roomSocketHandler"),p(this,"context"),p(this,"videoPeerConsumerMap",new Map),g(this,fi,{mode:"ACTIVE_GRID",page:0}),g(this,on,void 0),g(this,cn,void 0),g(this,dn,!1),g(this,Ka,!1),p(this,"updateConsumerSpatialLayers",lp(()=>{const n={},o=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(o.entries()).forEach(([c,d])=>{n[d]===void 0&&(n[d]={layer:d,consumerIds:[]}),n[d].consumerIds.push(c)}),Object.keys(n).forEach(c=>{const d=n[c];this.logger.log(`Switching max spatial layer to ${d.layer}`,{consumerIds:d.consumerIds}),this.roomNodeClient.switchConsumersToLayer(d.consumerIds,d.layer)})},2e3)),p(this,"updateConsumers",(n,o)=>u(this,null,function*(){try{n.length!==0&&(this.logger.info("Queueing create consumers for producers",{producers:n}),yield this.roomNodeClient.createConsumers(n))}catch(c){this.logger.error("Error activating peers",{error:c})}try{o.length!==0&&(this.logger.info("Queueing close consumers for producers",{producers:o}),yield this.roomNodeClient.closeConsumers(o))}catch(c){this.logger.error("Error deactivating peers",{error:c})}})),this.context=t;const s=t.getValue("logger");switch(f(this,on,new Cs(s)),f(this,cn,new Cs(s)),this.roomSocketHandler=r,this.participants=new Rt(t,e,this.roomSocketHandler),this.self=e,this.consumerPeerMap=new Map,i){case Me.HIVE:{this.events=cr;break}case Me.CF:{this.events=br;break}default:this.events=cr}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.onParticipantJoined(this.fromSocketService(r))}),e&&this.logger.info("Processed socket peers")})),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:t})=>{this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN)&&this.logger.info("events.peerJoinedBroadcast",{peers:t.peerId}),this.onMediaJoined(t.peerId,t.producerStates,t.capabilities)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:t,selectedPeers:e,roomState:r})=>{if(this.context.getValue("flagsmith").hasFeature(Z.DEBUG_SOCKET_JOIN)){const n=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(o=>o.peerId))}:void 0;this.logger.info("events.selfJoinComplete",n)}t.forEach(({peerId:n,producerStates:o,capabilities:c})=>this.onMediaJoined(n,o,c));const{audioPeers:i,compulsoryPeers:s}=e!=null?e:{};r.pinnedPeerIds.length!==0&&this.onParticipantPinned(r.pinnedPeerIds[0]),this.computeActivateParticipants(i!=null?i:[],s),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.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:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}},dyteParticipant:{id:t}});return}if(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:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}}),this.participants.viewMode==="MANUAL"){let i=!1;const s=e.kind==="audio",n=e.kind==="video",o=r.manualProducerConfig;(s&&(o.audio&&!e.screenShare||o.screenshareAudio&&e.screenShare)||n&&(o.video&&!e.screenShare||o.screenshareVideo&&e.screenShare))&&(i=!0),i?this.roomNodeClient.createConsumers([e]):this.logger.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}});return}(e==null?void 0:e.kind)==="audio"&&this.participants.audioSubscribed.get(t)||(e==null?void 0:e.kind)==="video"&&this.participants.videoSubscribed.get(t)||e!=null&&e.screenShare?this.roomNodeClient.createConsumers([e]).catch(i=>{this.logger.error("ParticipantController::createConsumer failed",{error:i})}):this.logger.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}})}),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 s=this.participants.joined.get(t);if(s){i==="audio"&&s.setAudioEnabled(!r);const n=s.producers.find(o=>o.producerId===e);n&&(n.pause=r)}}),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.roomNodeClient.activatePeers(i.producers).catch(s=>{this.logger.error("unable to create consumers",{error:s})})}),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(s=>s.userId===i.userId)),r=this.participants.waitlisted.toArray().filter(i=>!t.requests.find(s=>s.userId===i.userId));e.forEach(i=>this.participants.waitlisted.add(new li(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)),s=Array.from(this.participants.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),n=Math.max((t-1)*(this.maxPreferredStreams-r.length-i.length)),o=t*(this.maxPreferredStreams-r.length-i.length);return r.concat(i,s.slice(n,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,s=this.participants.pinned.toArray().reduce((h,m)=>(m.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(m.id):h.push(m.id),h),[]),n=this.self.stageStatus==="ON_STAGE"?1:0,o=t-n,c=new Set(i.concat(s).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(m=>!c.has(m)&&m!==this.self.id).slice(0,l);d=Array.from(c).concat(h)}else d=d.slice(0,o);return d}updateSubscriptions(t,e){const{page:r,createAllConsumers:i}=e!=null?e:{};t&&a(this,fi).mode!==t&&(a(this,fi).mode=t),r&&a(this,fi).page!==r&&(a(this,fi).page=r);const{mode:s,page:n}=a(this,fi);switch(i&&(a(this,on).clear(),a(this,cn).clear()),s){case"PAGINATED":{if(!n)return;const o=this.selectPagePeers(n),c=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,o),this.updateParticipantsMap(this.participants.audioSubscribed,c),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:o});break}case"ACTIVE_GRID":{const o=this.selectActivePeers(this.participants.maxActiveParticipantsCount),c=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,o),this.updateParticipantsMap(this.participants.audioSubscribed,c);break}default:throw new Error(`View mode ${t} not supported`)}setTimeout(()=>this.syncConsumers(),a(this,fi).mode==="PAGINATED"&&!a(this,dn)?200:0)}syncConsumers(){return u(this,null,function*(){var t,e,r;if(((r=(e=(t=this.context.getValue("connectionHandler"))==null?void 0:t.mediaState)==null?void 0:e.recv)==null?void 0:r.state)!=="connected")return;if(a(this,dn)){f(this,Ka,!0);return}f(this,dn,!0),f(this,Ka,!1);const[i,s]=ud.mapDiff(a(this,on),this.participants.videoSubscribed);this.updateParticipantsMap(a(this,on),this.participants.videoSubscribed.toArray().filter(({videoEnabled:l})=>!!l).map(({id:l})=>l));const[n,o]=ud.mapDiff(a(this,cn),this.participants.audioSubscribed);this.updateParticipantsMap(a(this,cn),this.participants.audioSubscribed.toArray().filter(({audioEnabled:l})=>!!l).map(({id:l})=>l));const c=[...this.mapPeerIdsToProducers(i,["video"]),...this.mapPeerIdsToProducers(n,["audio"])],d=[...this.mapPeerIdsToProducers(s,["video"]),...this.mapPeerIdsToProducers(o,["audio"])];try{(c.length>0||d.length>0)&&(yield this.updateConsumers(c,d))}finally{f(this,dn,!1)}a(this,Ka)&&this.syncConsumers()})}static mapDiff(t,e){const r=[],i=[],s=Array.from(t.keys()),n=Array.from(e.keys());return s.forEach(o=>{n.includes(o)||i.push(o)}),n.forEach(o=>{s.includes(o)||r.push(o)}),[r,i]}computeActivateParticipants(t,e){const r=t.map((s,n)=>({peerId:s,priority:n+1})),i=e==null?void 0:e.map((s,n)=>({peerId:s,priority:-(n+1)}));r.push(...i!=null?i:[]),r.length>0&&this.updateActiveParticipantsWithPriorities(r)}fromSocketService(t){const e=ud.formatSocketServiceMessage(t);return new li(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)}onMediaJoined(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}e.forEach(s=>{s.kind===jr.AUDIO&&!s.screenShare?i.setAudioEnabled(!s.pause):s.kind===jr.VIDEO&&!s.screenShare&&(i.setVideoEnabled(!s.pause),this.updatePipSource(i.id,!s.pause)),i.producers.push(q(V({},s),{producingTransportId:s.producingTransportId,kind:s.kind===jr.AUDIO?"audio":"video",producingPeerId:t,mimeType:s.mimeType}))}),this.roomNodeClient.handlePeerCapabilities(t,r),this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||this.roomNodeClient.shareWebcam(this.self.videoTrack),this.context.getValue("peerSessionStore").emit(P.UPDATE_ACTIVE)}updateParticipantsMapMinReplacement(t,e){const r=Array.from(t.keys()),i=new Map(t),s=new Set(e),n=[];r.forEach((o,c)=>{(!s.has(o)||!this.participants.joined.get(o))&&n.push(c)}),e.forEach(o=>{if(t.get(o))return;if(r.length<e.length){r.push(o);return}const c=n.shift();r[c]=o}),n.forEach(o=>{r.splice(o,1)}),Array.from(t.keys()).forEach(o=>{t.delete(o,!s.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.onParticipantJoined(this.fromSocketService(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:s})=>{var n;const o=e==="video"&&((n=r==null?void 0:r.screenShare)!=null?n:!1),c=this.participants.joined.get(i);c&&(c.emit("mediaScoreUpdate",{kind:e,isScreenshare:o,score:t,participantId:i,scoreStats:s}),this.participants.emit("mediaScoreUpdate",{kind:e,isScreenshare:o,score:t,participantId:i,scoreStats:s}))}),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*({page:e,createAllConsumers:r}={}){this.updateSubscriptions(e?"PAGINATED":"ACTIVE_GRID",{page:e,createAllConsumers:r})}))}onParticipantPinned(t){return u(this,null,function*(){if(!t){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(t===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const e=this.participants.joined.get(t);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),e.setIsPinned(!0),this.participants.pinned.add(e)})}onParticipantJoined(t){return u(this,null,function*(){var e,r,i;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),s=this.participants.videoSubscribed.get(t);i===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=i?r===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(r-1):s&&this.updateSubscriptions(r?"PAGINATED":"ACTIVE_GRID",{page:r})})}processMedia(t){var e;const r=this.roomNodeClient.getConsumers(),{peerId:i,kind:s,appData:n,track:o,producerId:c,rtpReceiver:d,paused:l}=(e=r.get(t))!=null?e:{};if(!i)return this.logger.warn("processMedia::Peer ID is undefined",{consumer:{id:t,kind:s,peerId:i,appData:{supportsRemoteControl:!!(n!=null&&n.supportsRemoteControl),screenShare:!!(n!=null&&n.screenShare)},remotelyPaused:l,producerId:c}}),{};const h=n;return s==="video"&&h.screenShare!==!0&&this.videoPeerConsumerMap.set(i,t),this.logger.info("ParticipantController::processMedia",{consumer:{id:t,peerId:i,kind:s,appData:h,remotelyPaused:l,producerId:c}}),this.consumerPeerMap.set(t,{type:s,peerId:i,appData:h,remotelyPaused:l,producerId:c}),{peerId:i,kind:s,appData:h,remotelyPaused:l,track:o,producerId:c,rtpReceiver:d}}processConsumerClosed(t){const{peerId:e,type:r,appData:i,remotelyPaused:s,producerId:n}=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:s,producerId:n}}),this.consumerPeerMap.delete(t),r==="video"&&i.screenShare!==!0&&this.videoPeerConsumerMap.delete(e),!o)return;const c=[];i&&i.screenShare?(o.setScreenShareEnabled(!1),this.context.getValue("callstats").consumerSharedMediaState(t,{screen:!1}),o.screenShareTracks.video&&c.push(o.screenShareTracks.video.id),o.screenShareTracks.audio&&c.push(o.screenShareTracks.audio.id),o.screenShareTracks={audio:void 0,video:void 0}):r==="audio"?(o.setAudioEnabled(!1),o.audioTrack&&c.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&&c.push(o.videoTrack.id),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!1}),o.videoTrack=void 0),i.e2ee&&c.forEach(d=>{this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:d})})}processConsumerResumed(t){var e;const{peerId:r,kind:i,appData:s,track:n,remotelyPaused:o,producerId:c,rtpReceiver:d}=this.processMedia(t);if(!r)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:t,peerId:r,kind:i,appData:s,remotelyPaused:o,producerId:c}});const l=this.participants.joined.get(r);if(l){if(s.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:r,rtpReceiver:d,track:n}),s.screenShare){i==="video"?l.screenShareTracks.video=n:i==="audio"&&(l.screenShareTracks.audio=n),l.setScreenShareEnabled(!0),(e=this.context)==null||e.getValue("callstats").consumerSharedMediaState(t,{screen:!0});return}i==="video"?(l.videoTrack=n,l.setVideoEnabled(!0),this.updatePipSource(l.id,!0),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!0})):i==="audio"&&(l.audioTrack=n,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:l.audioEnabled}))}}processConsumerPaused(t){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${t}`);const{peerId:e,kind:r,track:i,appData:s,remotelyPaused:n,producerId:o}=this.processMedia(t);if(!e)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:t,peerId:e,kind:r,appData:s,remotelyPaused:n,producerId:o}});const c=this.participants.joined.get(e);c&&(i&&s.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:i.id}),r==="video"?(c.videoTrack=i,c.setVideoEnabled(!1),this.updatePipSource(c.id,!1),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!1})):r==="audio"&&(c.audioTrack=i,c.setAudioEnabled(c.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:c.audioEnabled})))}processNewConsumer(t){const{peerId:e,kind:r,remotelyPaused:i,track:s,appData:n,producerId:o,rtpReceiver:c}=this.processMedia(t);if(!e)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:t,peerId:e,kind:r,remotelyPaused:i,appData:n,producerId:o}});const d=this.participants.joined.get(e);if(d){if(n.screenShare){r==="video"?d.screenShareTracks.video=s:r==="audio"&&(d.screenShareTracks.audio=s),(!i||this.self.permissions.isRecorder||this.context.getValue("flagsmith").hasFeature(Z.SCREEENSHARE_ERR_HACK))&&d.setScreenShareEnabled(!0),n.supportsRemoteControl&&(d.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:n,producerId:o}});return}r==="video"?(d.videoTrack=s,i||(d.setVideoEnabled(!0),this.updatePipSource(d.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(t,{video:!i})):r==="audio"&&(d.audioTrack=s,i||d.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(t,{audio:!i})),!i&&n.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:s})}}static formatSocketServiceMessage(t){var e,r,i,s,n,o;if(!t)return;const c=gp(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:(s=t.flags)==null?void 0:s.hiddenParticipant,recorder:((n=t.flags)==null?void 0:n.recorderType)!==void 0&&((o=t.flags)==null?void 0:o.recorderType)!=="NONE"}}}mapPeerIdsToProducers(t,e){const r=(i,s)=>i.filter(({kind:n,screenShare:o})=>s.includes(n)||o&&s.includes("screenshare"));return t.flatMap(i=>{const s=this.participants.joined.get(i);if(s)return r(s.producers,e)}).filter(i=>!!i)}onSelectedPeers(t,e){return u(this,null,function*(){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(t,e)})}updateActiveParticipantsWithPriorities(t,e=!1){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.updateSubscriptions(this.participants.viewMode)}},fi=new WeakMap,on=new WeakMap,cn=new WeakMap,dn=new WeakMap,Ka=new WeakMap,bg);let hi=ud;qs([k.trace("ParticipantController.setupEvents")],hi.prototype,"setupEvents",1);qs([k.trace("ParticipantController.setupEvents")],hi.prototype,"setupEventsGlobal",1);qs([k.trace("ParticipantController.processMedia")],hi.prototype,"processMedia",1);qs([k.trace("ParticipantController.processConsumerClosed")],hi.prototype,"processConsumerClosed",1);qs([k.trace("ParticipantController.processConsumerResumed")],hi.prototype,"processConsumerResumed",1);qs([k.trace("ParticipantController.processConsumerPaused")],hi.prototype,"processConsumerPaused",1);qs([k.trace("ParticipantController.processNewConsumer")],hi.prototype,"processNewConsumer",1);const ye=_r(dp().permissions);var H,yo,Hn,oh,xt,Kt;const So=class extends Xt{constructor(t,e,r,i=!1){const s=t.getValue("logger");if(super(s),g(this,xt),g(this,H,void 0),g(this,yo,void 0),g(this,Hn,void 0),g(this,oh,n=>{var o,c,d;const l=n,{chat:h,connectedMeetings:m,plugins:v,polls:S,media:T}=l,M=vl(l,["chat","connectedMeetings","plugins","polls","media"]);if(h&&(h.private&&bi(a(this,H).chat.private,h.private),h.public&&bi(a(this,H).chat.public,h.public),this.emit("chatUpdate")),m&&bi(a(this,H).connectedMeetings,m),T){const b=j=>{switch(j){case Ui.NONE:return G.Allowed;case Ui.ALLOWED:return G.Allowed;case Ui.NOT_ALLOWED:return G.NotAllowed;case Ui.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)}),bi(a(this,H).media,R)}v&&(bi(a(this,H).plugins,v),this.emit("pluginsUpdate")),S&&(bi(a(this,H).polls,S),this.emit("pollsUpdate")),Object.keys(M).length!==0&&bi(a(this,H),M),this.emit("permissionsUpdate",n)}),!e)throw this.logger.error("DytePermissionsPreset::load_preset_permissions_failed"),new I("Could not load preset permissions.","0904");f(this,Hn,t),f(this,yo,r),f(this,H,e),i&&this.setupEvents()}setupEvents(){a(this,Hn).getValue("peerSessionStore").on(P.UPDATE_PERMISSIONS,a(this,oh))}static fromResponse(t,e,r){return new So(r,t,e,!0)}static default(t,e){return new So(t,ye,e)}static init(t,e,r){let i;return r?i=new So(t,r,e,!0):i=new So(t,ye,e),i}get mediaRoomType(){const{sfu:t}=a(this,Hn).getValue("roomNodeOptions");return t===Me.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=a(this,H))==null?void 0:t.stageEnabled)||a(this,yo)===Ft.Webinar||a(this,yo)===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 e1=So;H=new WeakMap,yo=new WeakMap,Hn=new WeakMap,oh=new WeakMap,xt=new WeakSet,Kt=function(){return a(this,Hn).getValue("stageStatus")};var Vr;class uy extends Xt{constructor(){super(...arguments),p(this,"localMediaHandler"),g(this,Vr,void 0)}updatePermission(){return u(this,null,function*(){var e,r;const i=(l,h)=>{this.mediaPermissions[l]=h;const m={message:this.mediaPermissions[l],kind:l};h==="DENIED"?a(this,Vr).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_ERROR,m):a(this,Vr).getValue("peerSessionStore").emit(P.MEDIA_PERMISSION_UPDATE,m)};if(Ie.getName()==="firefox")return;const s="microphone",n="camera",o=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:s}),c=yield(r=navigator==null?void 0:navigator.permissions)==null?void 0:r.query({name:n}),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 s,n,o,c;switch(i){case"audio":{(s=a(this,Vr))==null||s.getValue("callstats").mediaPermission("AUDIO",r),(n=a(this,Vr))==null||n.getValue("callstats").mediaPermission("SPEAKER",r);break}case"video":{(o=a(this,Vr))==null||o.getValue("callstats").mediaPermission("VIDEO",r);break}case"screenshare":{(c=a(this,Vr))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",r);break}}})}get peerId(){var e;return(e=a(this,Vr))==null?void 0:e.getValue("peerId")}init(){return u(this,arguments,function*(e={},r=!1,i=null){var s,n,o,c,d,l,h;if(Ie.init(),!this.localMediaHandler)try{let m=!0;if((s=i==null?void 0:i.getValue("defaults"))!=null&&s.mediaHandler)m=!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,(n=i==null?void 0:i.getValue("defaults"))==null?void 0:n.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:M}=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:M,mediaPermissionsErrors:{kind:S,message:T}}),this.emit("mediaPermissionError",v),this.emit("mediaPermissionUpdate",{message:T,kind:S})})),m){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(m){this.logger.error("DyteSelf::init::Failed To Setup Streams",{error:{name:m.name,message:m.message}})}})}set context(e){f(this,Vr,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})})}}Vr=new WeakMap;const za={},$i={executeWithLock({methodName:t,lockName:e,timeout:r}){return(i,s,n)=>{const o=n.value;return n.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:"",m=`${e}-${h}`,v=this==null?void 0:this.logger;if(za[m]){const M=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw M.name="UnsupportedConcurrentMethodExecution",v==null||v.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:M.stack},dyteLocker:{methodName:t,lockName:m}}),M}za[m]=!0;const S=setTimeout(()=>delete za[m],r),T=o.apply(this,c);return Promise.resolve(T).then(()=>{delete za[m],clearTimeout(S)}).catch(()=>{delete za[m],clearTimeout(S)}),T},n}}};var t1=Object.defineProperty,r1=Object.getOwnPropertyDescriptor,Mt=(t,e,r,i)=>{for(var s=i>1?void 0:i?r1(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&t1(e,r,s),s},Ya,At,Qa,Ye,vi,is,Ze,at,Xa,Nc,$e,Qe,Za,eo,Vc,mu,wg;let nt=(wg=class extends uy{constructor(t,e,r,i,s){var n;const o=t.getValue("logger");super(o),g(this,vi),g(this,Ze),g(this,Xa),g(this,$e),g(this,Vc),p(this,"name"),p(this,"picture"),p(this,"customParticipantId"),p(this,"waitlistStatus"),g(this,Ya,void 0),g(this,At,void 0),g(this,Qa,void 0),p(this,"role"),p(this,"userId"),p(this,"organizationId"),p(this,"supportsRemoteControl",!1),p(this,"device"),g(this,Ye,void 0),p(this,"hidden",!1),p(this,"presetName"),p(this,"roomState","init"),g(this,Za,new Set),g(this,eo,new Set),f(this,Ye,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(n=e.customParticipantId)!=null?n:e.clientSpecificId,this.waitlistStatus="none",f(this,At,r),f(this,Ya,i),this.hidden=!1,f(this,Qa,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Ie.isElectron(),this.device=Ie.getDeviceInfo(),this.presetName=s,i.viewType!==Ft.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),U(this,Vc,mu).call(this)}get telemetry(){return a(this,Ye).getValue("telemetry")}get stageStatus(){return a(this,Ye).getValue("stageStatus")}get id(){return this.peerId}get peerId(){return a(this,Ye).getValue("peerId")}static __init__(t,e,r,i,s,n=!1){return u(this,null,function*(){var o,c,d,l,h,m;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 nt(t,e,r,i,s);if(i.viewType===Ft.Chat)return T;const M=lO(i.mediaConstraints);bi(M,(h=t.getValue("defaults"))==null?void 0:h.mediaConfiguration);const b=(m=t.getValue("defaults"))==null?void 0:m.mediaHandler;return b&&(b.context=t),yield T.init({audio:v,video:S,constraints:M},n,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,Vc,mu));const t=a(this,Xa,Nc);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({},Is(this))),a(this,$e,Qe)&&this.audioEnabled)try{yield a(this,Ze,at).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({},Is(this))),a(this,$e,Qe)&&this.rawVideoTrack===void 0)this.logger.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,$e,Qe))try{const e=yield a(this,Ze,at).shareWebcam(this.videoTrack);e&&e.id!==this.videoTrack.id&&a(this,Ye).getValue("flagsmith").hasFeature(Z.EXP_RESHARE)&&(yield a(this,Ze,at).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,Xa,Nc))==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,Qe)){this.logger.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield a(this,Ze,at).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({},Is(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({},Is(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,Qe)&&(yield a(this,Ze,at).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,s;(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}`)),(s=e==null?void 0:e.media)!=null&&s.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,Ya)}get roomJoined(){var t;return a(this,Ya).viewType===Ft.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,Ye).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,$e,Qe)}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,Qe)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield a(this,Ze,at).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,Ze,at).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,Qe)&&this.stageStatus==="ON_STAGE")try{yield a(this,Ze,at).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({},Is(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,Qe))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,Ze,at).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,Qe)&&a(this,Ze,at).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,Qe)&&(yield a(this,Ze,at).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,Qe)&&(yield a(this,Ze,at).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var r;f(this,Qa,t);const i=t?"pinned":"unpinned";(r=a(this,vi,is))==null||r.updateSource(this.id,{pinned:t}),e&&this.emit(i,this)}get isPinned(){return a(this,Qa)}pin(){return u(this,null,function*(){if(!a(this,$e,Qe))throw new I("Can`t pin participants without joining room","1105");return this.show(),a(this,Ze,at).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!a(this,$e,Qe))throw new I("Can`t unpin participants without joining room","1105");return a(this,Ze,at).pinPeer(null)})}hide(){return u(this,null,function*(){if(!a(this,$e,Qe))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,Qe))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 s=this.getCurrentDevices();if(t.deviceId&&(((e=s==null?void 0:s.audio)==null?void 0:e.deviceId)===t.deviceId||((r=s==null?void 0:s.video)==null?void 0:r.deviceId)===t.deviceId||((i=s==null?void 0:s.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,Qe)&&(yield a(this,Ze,at).muteSelf()),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":yield this.localMediaHandler.setSpeakerDevice(t);break;case"videoinput":try{yield this.localMediaHandler.setVideoDevice(t)}catch{a(this,$e,Qe)&&(yield a(this,Ze,at).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,Xa,Nc))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,Za).add(t):a(this,eo).add(t),this.updateVideo(t),e||(i=a(this,vi,is))==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,vi,is).removeSource(this.id);return}t.srcObject=void 0,e?a(this,Za).delete(t):(a(this,eo).delete(t),a(this,vi,is).removeSource(this.id))}updateVideo(t,e=!1){var r,i,s;if(this.videoEnabled){if(this.videoTrack==null)return;const n=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((n==null?void 0:n.id)===this.videoTrack.id)return;const o=new MediaStream;o.addTrack(this.videoTrack),t.srcObject=o,e||(i=a(this,vi,is))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(s=a(this,vi,is))==null||s.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Ya=new WeakMap,At=new WeakMap,Qa=new WeakMap,Ye=new WeakMap,vi=new WeakSet,is=function(){return a(this,Ye).getValue("pip")},Ze=new WeakSet,at=function(){return a(this,Ye).getValue("roomNodeClient")},Xa=new WeakSet,Nc=function(){return a(this,Ye).getValue("audioPlayback")},$e=new WeakSet,Qe=function(){var t;return((t=a(this,Ye).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Za=new WeakMap,eo=new WeakMap,Vc=new WeakSet,mu=function(){Array.from(a(this,eo)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,Za)).forEach(t=>this.updateVideo(t,!0))},wg);Mt([k.trace("DyteSelf.cleanupEvents")],nt.prototype,"cleanupEvents",1);Mt([k.trace("DyteSelf.setupEvents")],nt.prototype,"setupEvents",1);Mt([k.trace("DyteSelf.setupTracks")],nt.prototype,"setupTracks",1);Mt([k.trace("DyteSelf.destructMediaHandler")],nt.prototype,"destructMediaHandler",1);Mt([k.trace("DyteSelf.removeDocumentEventListeners")],nt.prototype,"removeDocumentEventListeners",1);Mt([$i.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),k.trace("DyteSelf.enableAudio")],nt.prototype,"enableAudio",1);Mt([$i.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),k.trace("DyteSelf.enableVideo")],nt.prototype,"enableVideo",1);Mt([k.trace("DyteSelf.updateVideoConstraints")],nt.prototype,"updateVideoConstraints",1);Mt([k.trace("DyteSelf.enableScreenShare"),$i.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],nt.prototype,"enableScreenShare",1);Mt([k.trace("DyteSelf.updateScreenshareConstraints")],nt.prototype,"updateScreenshareConstraints",1);Mt([$i.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),k.trace("DyteSelf.disableAudio")],nt.prototype,"disableAudio",1);Mt([$i.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),k.trace("DyteSelf.disableVideo")],nt.prototype,"disableVideo",1);Mt([$i.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),k.trace("DyteSelf.disableScreenShare")],nt.prototype,"disableScreenShare",1);Mt([k.trace("DyteSelf.setDevice")],nt.prototype,"setDevice",1);nt=Mt([gt("1100")],nt);class kp extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,kp)}}class Tp extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Tp)}}var hd;class ch{constructor(e,r=!1){p(this,"pendingTasks",new Map),p(this,"nextTaskId",0),p(this,"stopping",!1),g(this,hd,void 0),this.log=r,f(this,hd,{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((s,n)=>{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),s(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),n(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 kp);this.stopping=!1}remove(e){const r=Array.from(this.pendingTasks.values())[e];r&&r.reject(new Tp)}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(),s=Date.now();a(this,hd).info(`AwaitQueue.push(${e.name})_timings`,{awaitQueueTask:{id:e.id,metadata:e.metadata,queueSizeAtStart:r,execTime:(s-e.executedAt)/1e3,taskStartTime:(e.executedAt-e.enqueuedAt)/1e3}}),e.resolve(i)}catch(r){e.reject(r)}})}}hd=new WeakMap;function i1(t,e){const r=new Error(e);return r.name=t,r}class ec extends I{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,ec):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 Ps extends I{constructor(e){super(e),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ut):this.stack=new Error(e).stack}}const _g=t=>new Promise(e=>setTimeout(e,t));function hy(t,e){return u(this,null,function*(){return new Promise((r,i)=>u(this,null,function*(){const{strategy:s,maxRetryCount:n,delayTime:o}=V({strategy:"linear",maxRetryCount:3,delayTime:10},e);let c=0,d,l=!1;const h=m=>{l=!0,i(m)};for(;c<n;){try{const m=yield t(c,h);return r(m)}catch(m){if(d=m,l)break;if(c<n)s==="linear"?yield _g(o*(c+1)):s==="exponential"&&(yield _g(o*(c+Math.max(0,c-1))));else break}c+=1}return i(d)}))})}function s1(t){return t.map(e=>({channels:e.channels,clockRate:e.clockRate,mimeType:e.mimeType,sdpFmtpLine:e.sdpFmtpLine}))}function n1(t){return t.map(e=>({uri:e.uri}))}function Lc(t){return{codecs:s1(t.codecs),headerExtensions:n1(t.headerExtensions?t.headerExtensions:[])}}function a1(t){const e=RTCRtpReceiver.getCapabilities("audio"),r=RTCRtpReceiver.getCapabilities("video"),i=RTCRtpSender.getCapabilities("audio"),s=RTCRtpSender.getCapabilities("video");t&&(r.codecs=r.codecs.filter(({mimeType:o})=>t===o),s.codecs=s.codecs.filter(({mimeType:o})=>t===o));const n={audio:Lc(e),video:Lc(r)};return{sender:{audio:Lc(i),video:Lc(s)},receiver:n}}var ct;class o1{constructor(e,r){g(this,ct,void 0),p(this,"events"),p(this,"sfuType"),f(this,ct,e),this.sfuType=r,this.events=r===Me.CF?br:cr}joinRoom(e,r,i,s=!1,n=null){return u(this,null,function*(){const o={roomUuid:e,displayName:r,prejoined:s,capabilities:i};return n&&(o.location=n),(yield a(this,ct).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:SI.toBinary(o),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const r=(yield a(this,ct).sendMessagePromise(this.events.createWebRTCTransport,J0.toBinary(e))).payload,{transportId:i,description:s,producerIds:n}=Dv.fromBinary(r),o={sdp:s==null?void 0:s.sdp,type:s.type};return{transportId:i,answer:o,producerIds:n}})}produce(e){return u(this,null,function*(){var r,i;const s=(yield a(this,ct).sendMessagePromise(this.events.produce,NI.toBinary(e))).payload,n=fC.fromBinary(s);return{answer:{sdp:(r=n==null?void 0:n.description)==null?void 0:r.sdp,type:(i=n==null?void 0:n.description)==null?void 0:i.type},producerId:n.producerId}})}consume(e){return u(this,null,function*(){if(this.sfuType===Me.HIVE)throw new Error("Hive does not support socket consumer operations");const r=(yield a(this,ct).sendMessagePromise(this.events.consume,PI.toBinary(e))).payload,{consumerIdsMap:{map:i},description:s}=mC.fromBinary(r);return{consumerStateMap:i,sessionDescription:s}})}closeProducer(e){return u(this,null,function*(){const r=(yield a(this,ct).sendMessagePromise(this.events.closeProducer,WI.toBinary(e))).payload,{description:i}=bC.fromBinary(r);return i})}closeConsumer(e){return u(this,null,function*(){if(this.sfuType===Me.HIVE)throw new Error("Hive does not support socket consumer operations");return(yield a(this,ct).sendMessagePromise(this.events.closeConsumer,HI.toBinary(e))).payload})}updateConsumersSimulcastConfig(e){return u(this,null,function*(){if(this.sfuType===Me.HIVE)throw new Error("Method not implemented");return(yield a(this,ct).sendMessagePromise(this.events.updateConsumersSimulcastConfig,DI.toBinary(e))).payload})}hostControlForPeer(e,r){return u(this,null,function*(){const i={audio:r==="audio",screeShare:!1,video:r==="video",participantId:e},s=(yield a(this,ct).sendMessagePromise(this.events.hostControlPeer,zI.toBinary(i))).payload;if(!s)return!1;const{status:n}=MC.fromBinary(s);return n==="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,QI.toBinary(r))).payload;if(!i)return!1;const{status:s}=DC.fromBinary(i);return s==="success"})}kickAll(){return u(this,null,function*(){const e={propagateKickAcrossRooms:!1};a(this,ct).sendMessagePromise(F.kickAll,Lv.toBinary(e))})}kickPeer(e){return u(this,null,function*(){a(this,ct).sendMessagePromise(F.kick,Wv.toBinary(e))})}changeDisplayName(e){return u(this,null,function*(){const r=(yield a(this,ct).sendMessagePromise(this.events.changeDisplayName,JI.toBinary(e))).payload;if(!r)return!1;const{status:i}=NC.fromBinary(r);return i==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},r=(yield a(this,ct).sendMessagePromise(this.events.selfJoinComplete,kI.toBinary(e))).payload;return qu.fromBinary(r)})}audioActivity(e){return u(this,null,function*(){a(this,ct).sendMessage(this.events.audioActivity,z0.toBinary(e))})}}ct=new WeakMap;var pd;class Al extends mt.EventEmitter{constructor(e){super(),g(this,pd,void 0),f(this,pd,e),this.setMaxListeners(1/0)}get logger(){return a(this,pd).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(s){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:s}),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((s,n)=>{setTimeout(n,r,"event request timeout");try{this.emit(e.toString(),...i,s,n)}catch(o){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:o}),n(o)}})})}}pd=new WeakMap;class bp extends Al{constructor(){super(...arguments),p(this,"_sendWebStream",new MediaStream),p(this,"_sendScreenShareStream",new MediaStream),p(this,"_direction"),p(this,"pc"),p(this,"_transportReady",!1),p(this,"_mapMidTransceiver",new Map),p(this,"enableHighBitrate",!1),p(this,"enableStereo",!1),p(this,"enableDtx",!0),p(this,"sfu",Me.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:s,proprietaryConstraints:n,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"},s),n),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}connect(){return u(this,null,function*(){let e;this.sfu===Me.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:s=>u(this,null,function*(){this.logger.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(s)}]`),yield this.pc.setRemoteDescription(s),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 s=i.sender.getParameters();s.encodings.forEach((n,o)=>{o<=r?n.active=!0:n.active=!1}),yield i.sender.setParameters(s)})}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 s=i.sender.getParameters();s.encodings.forEach((n,o)=>{s.encodings[o]=V(V({},n),r)}),yield i.sender.setParameters(s)})}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 wp extends bp{static createFactory(e){return()=>new wp(e)}get name(){return"Chrome74"}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:s,proprietaryConstraints:n,onTrackHandler:o}){this._direction=e,this.pc=new RTCPeerConnection(V({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},s),n),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}send(e){return u(this,arguments,function*({track:r,encodings:i,codecOptions:s,screenShare:n}){this._assertSendDirection();const o=this.pc.addTransceiver(r,{direction:"sendonly",streams:[n?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=[];s&&s.length&&s.forEach(m=>{var v;const S=l.codecs.find(T=>T.mimeType.includes(m.name));if(m.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(m.parameters)}`);const T=((v=S.sdpFmtpLine)==null?void 0:v.split(";"))||[];T.push(...m.parameters);const M=Array.from(new Set(T).values());S.sdpFmtpLine=M.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),s&&s.findIndex(({name:l})=>l==="opus")>=0){const{enableDtx:l,enableStereo:h}=this,m=this.enableHighBitrate?h?128e3:64e3:h?64e3:32e3;c.sdp=c.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${l?"usedtx=1;":""}${h?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${m}`),c.sdp+=`a=rtcp-fb:111 nack\r
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 tl extends bp{constructor(e,r){super(e),p(this,"supportsSendEncodings",!1),this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new tl(e,r)}get name(){return"Firefox60"}send(e){return u(this,arguments,function*({track:r,encodings:i,codecOptions:s,screenShare:n}){this._assertSendDirection();const o=this.supportsSendEncodings&&i!==void 0?{sendEncodings:i}:{},c=this.pc.addTransceiver(r,V({direction:"sendonly",streams:[n?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,m)=>{var v;const S=bs(h),T=S.media[S.media.length-1],M=T.rtp.filter(W=>m.some(w=>w.name===W.codec)),b=T.fmtp.filter(W=>M.some(w=>w.payload===W.payload)),R=(v=T.rtcpFb)==null?void 0:v.filter(W=>M.some(w=>w.payload===W.payload)),j=M.map(W=>W.payload);return S.media[S.media.length-1].rtp=M,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(" "),qc(S)},l=yield this.pc.createOffer();if(l.sdp=d(l.sdp,s),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:m}=this,v=this.enableHighBitrate?m?128e3:64e3:m?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${m?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${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 s=i.sender.getParameters(),n=s.encodings.length-1-r;s.encodings.forEach((o,c)=>{c>=n?o.active=!0:o.active=!1}),yield i.sender.setParameters(s)})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=i=>u(this,null,function*(){const s=yield i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(s)))})})}}class _p extends bp{static createFactory(e){return()=>new _p(e)}get name(){return"Safari12"}send(e){return u(this,arguments,function*({track:r,encodings:i,codecOptions:s,screenShare:n}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const o=this.pc.addTransceiver(r,{direction:"sendonly",streams:[n?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=[];s&&s.length>0&&s.forEach(h=>{var m;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=((m=v.sdpFmtpLine)==null?void 0:m.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:m}=this,v=this.enableHighBitrate?h?128e3:64e3:h?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${m?"usedtx=1;":""}${h?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${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 s=String.fromCharCode(...new Uint8Array(i.data));this.safeEmit("datachannel",e.channel,s)})}}}function c1(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}var md,Cn,Qr,dh,ei,Li,gd,gu,lh,py,uh,my;class d1 extends Al{constructor(e,r){var i;super(e),g(this,ei),g(this,gd),g(this,lh),g(this,uh),p(this,"rtpReceiver"),p(this,"id"),p(this,"localId"),p(this,"producerId"),p(this,"producingTransportId"),p(this,"mimeType"),p(this,"track"),p(this,"peerId"),p(this,"appData"),p(this,"transceiver"),g(this,md,void 0),g(this,Cn,void 0),g(this,Qr,void 0),g(this,dh,void 0),this.id=r.id,this.localId=r.localId,f(this,md,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Qr,!1),this.producerId=r.producerId,this.track=r.track,f(this,Cn,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,U(this,lh,py).call(this),f(this,dh,e)}get closed(){return a(this,Qr)}get kind(){return this.track.kind}get paused(){return a(this,Cn)}close(e,r){a(this,Qr)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,ei,Li)),f(this,Qr,!0),r&&(U(this,uh,my).call(this),this.transceiver.stop()),this.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(a(this,Qr))throw new Ut("closed");return a(this,md).getReceiverStats(this.localId)})}pause(){if(this.logger.debug("consumer::pause()",a(this,ei,Li)),a(this,Qr)){this.logger.error("consumer::pause() | Consumer closed",a(this,ei,Li));return}f(this,Cn,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,ei,Li)),a(this,Qr)){this.logger.error("Consumer::resume() | Consumer closed",a(this,ei,Li));return}f(this,Cn,!1),this.track.enabled=!0,this.safeEmit("resume")}}md=new WeakMap,Cn=new WeakMap,Qr=new WeakMap,dh=new WeakMap,ei=new WeakSet,Li=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},gd=new WeakSet,gu=function(){this.logger.debug('Consumer::track "ended" event',a(this,ei,Li)),this.safeEmit("trackended")},lh=new WeakSet,py=function(){this.track.addEventListener("ended",U(this,gd,gu).bind(this))},uh=new WeakSet,my=function(){try{this.track.removeEventListener("ended",U(this,gd,gu)),this.track.stop()}catch(t){this.logger.error("Consumer::destroyTrack()",q(V({},a(this,ei,Li)),{error:t}))}};var Lr,Eo,ko,Pn,Sr,ut,gs,To,hh,nr,Er;class l1 extends Al{constructor(e,r){var i,s;super(e),g(this,nr),p(this,"id"),p(this,"localId"),g(this,Lr,void 0),p(this,"kind"),p(this,"appData"),p(this,"rtpSender"),g(this,Eo,void 0),g(this,ko,void 0),g(this,Pn,void 0),g(this,Sr,!1),g(this,ut,void 0),g(this,gs,void 0),g(this,To,void 0),g(this,hh,void 0),this.id=r.id,this.localId=r.localId,f(this,ut,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,gs,r.disableTrackOnPause?!((s=r.track)!=null&&s.enabled):!1),f(this,To,void 0),f(this,Eo,r.stopTracks),f(this,ko,r.disableTrackOnPause),f(this,Pn,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,Lr,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,hh,e)}get closed(){return a(this,Sr)}get track(){return a(this,ut)}get paused(){return a(this,gs)}get maxSpatialLayer(){return a(this,To)}close(e){return u(this,null,function*(){if(a(this,Sr))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,nr,Er)),f(this,Sr,!0),this._destroyTrack(),e===rl){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=yield a(this,Lr).stopSending(this.localId),{answer:s}=yield this.safeEmitAsPromise("close",{offer:r,reason:e});i(s)})}getStats(){return u(this,null,function*(){if(a(this,Sr))throw new Ut("closed");return a(this,Lr).getSenderStats(this.localId)})}pause(){this.logger.debug("Producer::pause()",a(this,nr,Er)),a(this,Sr)&&this.logger.error("Producer::pause() | Producer closed",a(this,nr,Er)),f(this,gs,!0),a(this,ut)&&a(this,ko)&&(a(this,ut).enabled=!1),a(this,Pn)&&a(this,Lr).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,nr,Er)),a(this,Sr)){this.logger.error("Producer::resume() | Producer closed",a(this,nr,Er));return}f(this,gs,!1),a(this,ut)&&a(this,ko)&&(a(this,ut).enabled=!0),a(this,Pn)&&a(this,Lr).replaceTrack(this.localId,a(this,ut)),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,nr,Er)),a(this,Sr)){if(r&&a(this,Eo))try{r.stop()}catch(i){this.logger.error("Producer::replaceTrack",q(V({},a(this,nr,Er)),{error:i}))}throw new Ut("closed")}else if(r&&r.readyState==="ended")throw new Ut("track ended");if(r===a(this,ut)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${r.id}`,a(this,nr,Er));return}(!a(this,Pn)||!a(this,gs))&&(yield a(this,Lr).replaceTrack(this.localId,r)),this._destroyTrack(),f(this,ut,r),this._handleTrack()})}setMaxSpatialLayer(e){return u(this,null,function*(){if(a(this,Sr))throw new Ut("closed");if(this.kind!=="video")throw new ec("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield a(this,Lr).setMaxSpatialLayer(this.localId,e),f(this,To,e)})}setRtpEncodingParameters(e){return u(this,null,function*(){if(a(this,Sr))throw new Ut("closed");if(typeof e!="object")throw new TypeError("invalid params");yield a(this,Lr).setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,nr,Er)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,ut)&&a(this,ut).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,ut))try{a(this,ut).removeEventListener("ended",this._onTrackEnded),a(this,Eo)&&a(this,ut).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,q(V({},a(this,nr,Er)),{error:r}))}}}Lr=new WeakMap,Eo=new WeakMap,ko=new WeakMap,Pn=new WeakMap,Sr=new WeakMap,ut=new WeakMap,gs=new WeakMap,To=new WeakMap,hh=new WeakMap,nr=new WeakSet,Er=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function gy(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function ph(t){return Math.random().toString(36).substring(2,2+t)}const xc=1;function Ig(t){const e=t;return delete e.payload._bolt,e}function u1(t){return t.payload&&gy(t.payload)}function fy(t){var e,r;return u1(t)&&(r=(e=t.payload._bolt)==null?void 0:e.id)!=null?r:""}var fs,mh,Rn;const bo=class extends mt.EventEmitter{constructor(t,e,r,i){super(),p(this,"channel"),p(this,"queue"),p(this,"serverProtocolVersion"),g(this,fs,new Map),g(this,mh,void 0),g(this,Rn,void 0),p(this,"respond",(s,n,o=!1)=>{let c;o?c=bo.createErrorResponse(s,n):c=bo.createResponse(s,n),this.channel.send(JSON.stringify(c))}),p(this,"notify",s=>{const n=bo.createNotification(s);this.channel.send(JSON.stringify(n))}),p(this,"request",s=>u(this,null,function*(){const n=bo.createRequest(s),o=new Promise((c,d)=>{const{id:l}=n.payload._bolt,h={id:l,method:n.type,resolve:m=>{this.queue.delete(l)&&(clearTimeout(h.timer),c(m))},timer:setTimeout(()=>{this.queue.delete(l)&&d(new Error(`request timeout for message id: ${l}`))},2e4),cancel:m=>{this.queue.delete(l)&&(clearTimeout(h.timer),d(m))}};this.queue.set(l,h)});return this.channel.send(JSON.stringify(n)),o})),p(this,"send",s=>{const n=JSON.stringify(s),o=16384;if(n.length>o){const c=o-200,d=Math.ceil(n.length/c),l=[];for(let m=0;m<d;m+=1){const v=m*c,S=(m+1)*c;l.push(n.slice(v,S))}const h=Ns();for(let m=0;m<d;m+=1){const v=l[m],S=JSON.stringify({id:h,count:d,chunkIndex:m,chunk:v});a(this,Rn).debug(`Sending message chunk over dc: ${S}`),this.channel.send(S)}}else a(this,Rn).debug(`Sending message over dc: ${n}`),this.channel.send(n)}),p(this,"processMessage",s=>{var n;a(this,fs).has(s.id)||a(this,fs).set(s.id,[]);const o=a(this,fs).get(s.id);if(o[s.chunkIndex]=s,(o==null?void 0:o.length)===s.count&&!o.some(c=>c===void 0)){const c=a(this,fs).get(s.id),d=c==null?void 0:c.reduce((h,m)=>h+m.chunk,"");a(this,fs).delete(s.id);const l=JSON.parse(d);if(!l.payload||!gy(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=(n=l.payload._bolt)==null?void 0:n.version,!this.processResponseMsg(l))return l}}),p(this,"processResponseMsg",s=>{const{id:n}=s.payload._bolt,o=this.queue.get(n);return o?(a(this,Rn).debug(`resolving pending request with id: ${n}, complete response: ${JSON.stringify(s)}`),s.type==="error"?o.cancel(Ig(s)):o.resolve(Ig(s)),!0):!1}),p(this,"processBoltHandshake",s=>{var n,o;return s.type==="_bolt"||s.type==="handshake"?(this.respond((o=(n=s.payload._bolt)==null?void 0:n.id)!=null?o:ph(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=r,this.transportId=i,f(this,mh,t),f(this,Rn,t.getValue("logger")),this.channel=e,this.queue=new Map}};let wo=bo;fs=new WeakMap,mh=new WeakMap,Rn=new WeakMap,p(wo,"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:ph(8),type:"REQUEST",version:xc}})}}),p(wo,"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:xc}})}}),p(wo,"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:ph(8),type:"NOTIFY",version:xc}})}}),p(wo,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:xc}}}));const rl="transport closed";var Mn,An;const _o=class extends Al{constructor(t,e,{id:r,direction:i,handlerFactory:s,iceServers:n,iceTransportPolicy:o,proprietaryConstraints:c,additionalSettings:d,appData:l,config:h}){var m,v,S;super(t),p(this,"awaitQueue"),p(this,"observer"),g(this,Mn,void 0),p(this,"id"),p(this,"serverId"),p(this,"direction"),p(this,"maxSctpMessageSize"),p(this,"handler"),p(this,"connectionState","new"),p(this,"producers"),p(this,"consumers"),p(this,"datachannels"),p(this,"connected",!1),p(this,"eventsDCReadyPromise"),p(this,"eventsDCReadyPromiseResolver"),p(this,"eventsDCFailureTimer"),p(this,"transportConnectionPromise"),p(this,"consumerTrackEvents"),p(this,"unknownTracksMap"),p(this,"appData"),g(this,An,void 0),f(this,An,t);const T=t.getValue("logger");T.debug(`constructor() [id: ${r}, direction: ${i}]`),f(this,Mn,e),this.id=r,this.direction=i;const M=c1(d,{});delete M.iceServers,delete M.iceTransportPolicy,delete M.bundlePolicy,delete M.rtcpMuxPolicy,delete M.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new ch(T,!0),this.handler=s(),this.handler.enableHighBitrate=(m=h==null?void 0:h.enableHighBitrate)!=null?m:!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,Mn),this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:n,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 wo(a(this,An),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 W=JSON.parse(R);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:W.id,count:W.count,chunkIndex:W.chunkIndex,chunk:W.chunk,transprtId:this.serverId}});const w=j.processMessage(W);if(!w)return;this.logger.debug(`datachannel message with id:${W.id} on transport:${this.serverId}complete - ${JSON.stringify(w)}`),this.emit(`datachannel:${b.label}`,j.label,w)}catch(W){this.logger.error("error parsing message",{error:W})}})}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(rl).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(t=>{t.close(rl)}),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:s}=yield t(e);this.setServerId(i),yield r(s)})),!(yield this.transportConnectionPromise))throw new Error("ice connection failed");if(a(this,Mn)===Me.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 ec("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 Ps("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:s,stopTracks:n=!0,disableTrackOnPause:o=!0,zeroRtpOnPause:c=!1,appData:d={}}=t;this.logger.debug(`produce() [track:${r.id}]`);const{producerId:l,localId:h,rtpSender:m}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:v,callback:S,sender:T,mid:M}=yield this.handler.send({track:r,encodings:i,codecOptions:s,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:M}),codecOptions:s,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:n,disableTrackOnPause:o,zeroRtpOnPause:c,appData:d,handler:this.handler,rtpSender:m})})}createProducerObject(t){return u(this,null,function*(){const e=new l1(a(this,An),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 ec("not a receiving transport");if(!(yield this.transportConnectionPromise))throw new Ps("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:s,sessionDescription:n,failedProducers:o}=yield e(t);s.forEach((d,l)=>{i[l]=this.createConsumerObjectAndWaitForTrack(q(V({},d),{producerId:l}))}),n&&(this.logger.info("Session description found, sending negotiation request"),yield r(n));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=bs(t.sdp),i={};return r.media.forEach(s=>{e.includes(s.mid.toString())&&(i[s.mid.toString()]={rtp:s.rtp,fmtp:s.fmtp,payloads:s.payloads,rtcpFb:s.rtcpFb})}),i}static setCodecAndFmtpMappings(t,e,r){const i=bs(t.sdp);return i.media=i.media.map(s=>{if(e.includes(s.mid.toString())){const n=V({},s);return n.rtp=r[s.mid.toString()].rtp,n.fmtp=r[s.mid.toString()].fmtp,n.payloads=r[s.mid.toString()].payloads,n.rtcpFb=r[s.mid.toString()].rtcpFb,n}return s}),q(V({},t),{sdp:qc(i)})}static parseHeaderExtensionMappings(t){const e=bs(t.sdp),r={};return e.media.forEach(i=>{r[i.mid]=i.ext}),r}static setHeaderExtensionMappings(t,e){const r=bs(t.sdp);return r.media=r.media.map(i=>{const s=V({},i);return s.ext=e[i.mid],s}),q(V({},t),{sdp:qc(r)})}closeConsumers(t,e){return u(this,null,function*(){try{const r=t.map(c=>c.transceiver.mid),i=_o.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,r),s=_o.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 n=yield this.handler.pc.createOffer();this.logger.info("Created offer for closing consumers",{sdp:n.sdp}),n=_o.setCodecAndFmtpMappings(n,r,i),n=_o.setHeaderExtensionMappings(n,s),this.logger.info("Updated codec and fmtp mappings in close consumer offer",{sdp:n.sdp}),yield this.setLocalDescription(n),this.logger.info("Successfully set local description in close consumers");const o=yield e(t,n);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=bs(e.sdp);return r.media=r.media.map(i=>{if(i.type==="audio"){const s=V({},i),n=s.fmtp.find(o=>o.payload===111);return n&&(n.config+=";stereo=1;sprop-stereo=1"),s.rtcpFb||(s.rtcpFb=[]),s.rtcpFb.some(o=>o.type==="nack")||s.rtcpFb.push({payload:parseInt(s.payloads,10),type:"nack"}),s}return i}),e.sdp=qc(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 s;a(this,Mn)===Me.HIVE?s=`${i[0].id}:${e.kind}`:s=`${r.mid}:${e.kind}`,e.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${e.id}]`),this.unknownTracksMap.delete(s)});const n=this.consumerTrackEvents.get(s);n?(n(e,r),this.consumerTrackEvents.delete(s)):(this.logger.warn(`track event handler not found ${s}`),this.unknownTracksMap.set(s,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:s,streamId:n,paused:o,screenShare:c,appData:d,kind:l,mimeType:h}=t,m=`${n}:${l}`,v=q(V({},t),{name:"consumer creation task error",message:"consumer creation failed"});return new Promise((S,T)=>u(this,null,function*(){const M=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${m} producingPeerId: ${i}`),this.consumerTrackEvents.delete(m),v.isTimedout=!0,T(v)},5e3),b=(j,W)=>{try{if(j.readyState==="ended")clearTimeout(M),T(v);else{const w=j;w.enabled=!0,this.handler.midTransceiverMap.set(W.mid,W);const te=new d1(a(this,An),{id:e,localId:W.mid,transceiver:W,track:w,paused:o,producerId:r,producingPeerId:i,producingTransportId:s,handler:this.handler,appData:q(V({},d),{screenShare:c,peerId:i}),rtpReceiver:W.receiver,mimeType:h});this.consumers.set(e,te),te.once("close",()=>{this.consumers.delete(te.id),this.handler.midTransceiverMap.delete(W.mid)}),this.logger.info("consumer created for ",{consumer:{id:e,kind:l,appData:{screenShare:c},peerId:i,producerId:r}}),this.emit("newconsumer",te),clearTimeout(M),S(te)}}catch(w){this.logger.warn("error while creating consumer:",w),clearTimeout(M),T(v)}},R=this.unknownTracksMap.get(m);R?(this.logger.info(`track event already received [trackId: ${R.track.id}] [mid: ${R.transceiver.mid}]`),this.unknownTracksMap.delete(m),b(R.track,R.transceiver)):(this.logger.info(`Registering onTrack handler for key ${m} [producingPeerId: ${i}]`),this.consumerTrackEvents.set(m,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 i1("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 h1=_o;Mn=new WeakMap,An=new WeakMap;function p1(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=rf.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 s=e.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return s?Number(s[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 fd,Pi,Dn;class m1{constructor(e,r,{handlerName:i,handlerFactory:s}={}){p(this,"handlerFactory"),g(this,fd,void 0),g(this,Pi,void 0),g(this,Dn,void 0);const n=e.getValue("logger");if(n.debug("constructor()"),f(this,Pi,e),f(this,Dn,n),f(this,fd,r),i&&s)throw new TypeError("just one of handlerName or handlerInterface can be given");if(s)this.handlerFactory=s;else{if(i)a(this,Dn).debug(`Device::constructor() | handler given: ${i}`);else if(i=p1(a(this,Dn)),i)a(this,Dn).debug(`Device::constructor() | detected handler: ${i}`);else throw new Error("device not supported");switch(i){case"Chrome74":this.handlerFactory=wp.createFactory(a(this,Pi));break;case"Safari12":this.handlerFactory=_p.createFactory(a(this,Pi));break;case"Firefox60":this.handlerFactory=tl.createFactory(a(this,Pi),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=tl.createFactory(a(this,Pi),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${i}"`)}}}createTransport(e){const r=Ns();return new h1(a(this,Pi),a(this,fd),q(V({id:r},e),{handlerFactory:this.handlerFactory}))}}fd=new WeakMap,Pi=new WeakMap,Dn=new WeakMap;const g1=2e3;var Uo,It,Ct,vd,yd,$n,Fo,Io,Co,On,ti,Bo,Wo,Sd,Ed,gh,fh,vy,kd,vh,yh,Cg,Sh,Pg,Eh,Rg,kh,Mg,Th,Ag,Td,fu,bd,vu;class f1 extends mt.EventEmitter{constructor(e,r,i){switch(super(),g(this,Wo),g(this,Ed),g(this,fh),g(this,kd),g(this,yh),g(this,Sh),g(this,Eh),g(this,kh),g(this,Th),g(this,Td),g(this,bd),p(this,"context"),g(this,Uo,void 0),g(this,It,void 0),g(this,Ct,void 0),g(this,vd,void 0),g(this,yd,void 0),g(this,$n,void 0),g(this,Fo,void 0),g(this,Io,void 0),g(this,Co,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0}),g(this,On,void 0),g(this,ti,"all"),g(this,Bo,void 0),this.context=e,f(this,$n,r),f(this,Bo,i),f(this,Uo,new m1(e,i)),f(this,Fo,new o1(r,i)),i){case Me.CF:{f(this,Io,br);break}case Me.HIVE:default:{f(this,Io,cr);break}}a(this,Wo,Sd).mediaState={send:{state:ra.NEW},recv:{state:ra.NEW}},(ea(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(Z.FORCE_RELAY))&&f(this,ti,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,ti)}`),U(this,Ed,gh).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,$n)}get socketHandler(){return a(this,Fo)}get sendTransport(){return a(this,It)}get recvTransport(){return a(this,Ct)}get events(){return a(this,Io)}get nodeType(){return a(this,Bo)}set sendTransportConnectedCallback(e){f(this,vd,e)}set recvTransportConnectedCallback(e){f(this,yd,e)}setupTransports(e){return u(this,null,function*(){yield U(this,fh,vy).call(this,e);let r,i;e.send&&(r=U(this,kd,vh).call(this,a(this,It)).then(s=>{try{a(this,vd).call(this,s)}catch{this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=U(this,kd,vh).call(this,a(this,Ct)).then(s=>{try{a(this,yd).call(this,s)}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:s,serverId:n,direction:o}=a(this,It);this.logger.info("Closing send transport",{transport:{id:s,serverId:n,type:o}}),a(this,It).close(),a(this,It).removeAllListeners(),f(this,It,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:s,serverId:n,direction:o}=a(this,Ct);this.logger.info("Closing recv transport",{transport:{id:s,serverId:n,type:o}}),(r=a(this,Ct))==null||r.close(),(i=a(this,Ct))==null||i.removeAllListeners(),f(this,Ct,void 0)}U(this,Ed,gh).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}Uo=new WeakMap,It=new WeakMap,Ct=new WeakMap,vd=new WeakMap,yd=new WeakMap,$n=new WeakMap,Fo=new WeakMap,Io=new WeakMap,Co=new WeakMap,On=new WeakMap,ti=new WeakMap,Bo=new WeakMap,Wo=new WeakSet,Sd=function(){return this.context.getValue("connectionHandler")},Ed=new WeakSet,gh=function(){f(this,On,{send:void 0,recv:void 0})},fh=new WeakSet,vy=function(t){return u(this,null,function*(){var e,r,i,s,n,o,c,d;(ea(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(Z.FORCE_RELAY))&&f(this,ti,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,ti)}`);const l=yield ht().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,Sh,Pg).call(this,{iceServers:l,additionalSettings:{encodedInsertableStreams:(e=this.context.getValue("modules").e2ee)==null?void 0:e.enabled},config:{enableHighBitrate:(s=(i=(r=this.context.getValue("defaults").mediaConfiguration)==null?void 0:r.audio)==null?void 0:i.enableHighBitrate)!=null?s:!1,enableStereo:(c=(o=(n=this.context.getValue("defaults").mediaConfiguration)==null?void 0:n.audio)==null?void 0:o.enableStereo)!=null?c:!1,enableDtx:a(this,Bo)===Me.HIVE?!0:!!h},iceTransportPolicy:a(this,ti)})}t.recv&&U(this,Eh,Rg).call(this,{iceServers:l,additionalSettings:{encodedInsertableStreams:(d=this.context.getValue("modules").e2ee)==null?void 0:d.enabled},iceTransportPolicy:a(this,ti)})})},kd=new WeakSet,vh=function(t){return u(this,null,function*(){const{id:e,serverId:r,direction:i}=t;U(this,kh,Mg).call(this,t);try{const s=this.context.getValue("flagsmith").hasFeature(Z.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3;return yield hy((n,o)=>u(this,null,function*(){n>0&&this.logger.debug(`Retrying transport connect, count: ${n}`,{transport:{id:e,serverId:r,type:i}});try{if(t.closed)throw new Ps("Cannot reconnect closed transport");yield U(this,yh,Cg).call(this,t)}catch(c){if(c instanceof Ps){o(c);return}throw this.logger.error("Failed to connect transport, retrying",{transport:t,error:c}),c}}),{delayTime:100,strategy:"exponential",maxRetryCount:s}),t}catch(s){throw this.logger.error(`Failed to connect send transport after retry: ${t.id}`,{error:s,transport:{id:e,serverId:r,type:i}}),t.close(),t.removeAllListeners(),s}})},yh=new WeakSet,Cg=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,$n).isConnected)throw new Ps("Socket is not connected");if(t.connectionState==="closed")throw new Ps("Transport is closed");try{yield t.connect(i=>U(this,Th,Ag).call(this,r,i)),this.logger.info(`Connected ${r} transport`,{transport:{id:e,serverId:t.serverId,type:r}})}catch(i){throw a(this,Co).transportFailureCount[r]+=1,i.message==="ice connection failed"?new Ps(i.message):i}})},Sh=new WeakSet,Pg=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,Uo).createTransport(q(V({},t),{direction:"send"}))),this.context.getValue("callstats").configureSendTransport(a(this,It))},Eh=new WeakSet,Rg=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,Uo).createTransport(q(V({},t),{direction:"recv"}))),this.context.getValue("callstats").configureRecvTransport(a(this,Ct))},kh=new WeakSet,Mg=function(t){const{direction:e,id:r}=t;t.on("connectionstatechange",i=>u(this,null,function*(){U(this,bd,vu).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 s=()=>{const n=a(this,On)[e];n!==void 0&&(clearTimeout(n),a(this,On)[e]=void 0)};switch(i){case"connected":s(),a(this,Co).lastConnectionTime=performance.now();break;case"disconnected":a(this,On)[e]=setTimeout(()=>u(this,null,function*(){yield U(this,Td,fu).call(this,t.direction)}),g1);break;case"failed":if(t.closed)return;s(),yield U(this,Td,fu).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,s)=>u(this,null,function*(){var n,o;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:i,message:s}});try{switch(s.type){case"handshake":{const c={type:"handshake",payload:{message:"pong"}};t.sendResponseOverDC(i,fy(s),c);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(n=s.payload)==null?void 0:n.full_reconnect}`),((o=s.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"))})},Th=new WeakSet,Ag=function(t,e){return u(this,null,function*(){const r=t==="recv";try{const{sdp:i,type:s}=e,n={consuming:r,description:{sdp:i,type:s,target:r?di.SUBSCRIBER:di.PUBLISHER},producers:[]};return a(this,Fo).connectTransport(n)}catch(i){throw this.logger.error(`Error in ${t} transport connection:`,{error:i,country:k.location.country}),i}})},Td=new WeakSet,fu=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,$n).isConnected&&a(this,Co).transportFailureCount[t]>2&&(this.logger.warn(`Multiple disconnections in ${t} transport, forcing relay`),f(this,ti,"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,bd,vu).call(this,{state:ra.CONNECTED,direction:t})})},bd=new WeakSet,vu=function(t){const{state:e,direction:r}=t;a(this,Wo,Sd).mediaState[r]={state:e},this.context.getValue("peerSessionStore").emit(P.TRANSPORT_STATE_UPDATE,V({transport:r},a(this,Wo,Sd).mediaState[r]))};var wd,bh,yy;class v1{constructor(e,r){g(this,bh),g(this,wd,void 0),this.recvTransport=r,U(this,bh,yy).call(this),f(this,wd,e)}get logger(){return a(this,wd).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),s=new Map;e.forEach(o=>s.set(o.producerId,o));const n=new Map;return Object.entries(i).forEach(([o,c])=>{const d=s.get(c.producerId);d&&n.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:n}})}negotiate(e,r,i){return u(this,null,function*(){try{this.logger.debug(`Received offer over dc: ${e.sdp} for transport`);const s=yield this.recvTransport.setRemoteOffer(e),n={type:"answer",payload:{type:s.type,sdp:s.sdp}};return this.logger.debug(`datachannel answer: ${JSON.stringify(n)}`),this.recvTransport.sendResponseOverDC(i,r,n),s}catch(s){throw this.logger.error("datachannel:events::Error:",s),s.code!=="DC_NOT_FOUND"&&this.recvTransport.sendErrorOverDC(i,r,s),s}})}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}},s=yield this.recvTransport.sendDataChannelMessage("events",i),{failedConsumers:n}=s;return{failedConsumers:n}})}switchConsumersToLayer(e,r){return u(this,null,function*(){var i;const s=this.recvTransport.getDatachannel("events");if(!s){this.logger.warn("events datachannel not found");return}const n=(i=e==null?void 0:e.map(({id:c})=>c))!=null?i:[],o={type:"switch_consumer_layer",payload:{consumerIds:n,layer:r}};yield s.request(o),this.logger.info(`Consumers switched layers to ${r}`,{consumerIds:n})})}}wd=new WeakMap,bh=new WeakSet,yy=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,fy(e),t);break}default:break}}catch{this.logger.error(`Unable to handle the incoming datachannel message on channel ${t}`)}}))};var _d,kr;class y1{constructor(e,r,i,s,n){g(this,_d,void 0),g(this,kr,void 0),this.events=r,this.recvTransport=i,this.socket=s,this.socketHandler=n,f(this,_d,e),f(this,kr,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:m}=d,v=a(this,_d).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:m},v))});const s=yield this.socketHandler.consume({requests:i,consumingTransportId:this.recvTransport.serverId}),n=new Map;e.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(s.consumerStateMap).forEach(([d,l])=>{const h=n.get(d);if(!h)return;if(l.errorCode){a(this,kr).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push(q(V({},h),{errorCode:l.errorCode}));return}let m={};try{m=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:m})}),{consumerStates:o,sessionDescription:s.sessionDescription,failedProducers:c}})}negotiate(e){return u(this,null,function*(){try{a(this,kr).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,kr).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:di.SUBSCRIBER}};return a(this,kr).debug(`sending renegotiate request: ${JSON.stringify(i)} on recvTransport`,{transport:this.recvTransport}),yield this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,X0.toBinary(i)),a(this,kr).info("Renegotiation done",{transport:this.recvTransport}),r}catch(r){a(this,kr).error("Failed to renegotiate",{error:r});return}})}close(e){return u(this,null,function*(){if(!e.length)return{};const r=(i,s)=>u(this,null,function*(){const n=i.map(l=>l.localId);a(this,kr).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:s.sdp,type:s.type,target:di.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=yield this.socketHandler.closeConsumer(o),d=_C.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};e.forEach(({id:s,producingTransportId:n,localId:o})=>{i.requests.push({producerId:s,producingTransportId:n,mid:o,simulcast:{preferredRid:r===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),yield this.socketHandler.updateConsumersSimulcastConfig(i),a(this,kr).info(`Consumers switched layers to ${r}`,{consumerIds:e==null?void 0:e.map(({id:s})=>s)})})}}_d=new WeakMap,kr=new WeakMap;class Ip{constructor(e){this.socketHandler=e}static getMSIDFromSDP(e,r){return bs(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:s,appData:n,codecOptions:o,producingTransportId:c}){var d,l;const h=Ip.getMSIDFromSDP(r.sdp,i),m={description:{sdp:r.sdp,type:r.type,target:di.PUBLISHER},paused:s,kind:i,msid:h,appData:JSON.stringify(n),screenShare:(d=n.screenShare)!=null?d:!1,mimeType:`${i}/${(l=o[0])==null?void 0:l.name}`,producingTransportId:c},{answer:v,producerId:S}=yield this.socketHandler.produce(m);return{answer:v,producerId:S}})}}var Gn,Rs,Po,il,Fr,wh,xi,jo,sl,_h,Ih,Sy,Ch,Ey,Ph,Dg,Rh,Og;class S1 extends f1{constructor(e,r,i){super(e,r,i),g(this,sl),g(this,Ih),g(this,Ch),g(this,Ph),g(this,Rh),g(this,Gn,void 0),g(this,Rs,void 0),g(this,Po,void 0),g(this,il,void 0),g(this,Fr,void 0),g(this,wh,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0}),g(this,xi,[]),g(this,jo,void 0),this.context=e,this.sendTransportConnectedCallback=()=>u(this,null,function*(){f(this,il,new Ip(this.socketHandler))}),this.recvTransportConnectedCallback=s=>u(this,null,function*(){switch(a(this,Po).clear(),this.nodeType){case Me.CF:{f(this,Fr,new y1(this.context,this.events,s,this.socket,this.socketHandler));break}case Me.HIVE:default:f(this,Fr,new v1(this.context,s))}}),this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,Gn)}get consumers(){return a(this,Rs)}get producerIdToConsumerIdMap(){return a(this,Po)}get logger(){return this.context.getValue("logger")}reset(){f(this,Gn,new Map),f(this,Rs,new Map),f(this,Po,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 s=yield this.sendTransport.produce(e,U(this,Ih,Sy).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(P.E2EE_ACTIVE_PRODUCER,s),U(this,Ch,Ey).call(this,s,r),s}catch(s){throw this.logger.error("Failed to create producer",{error:s}),a(this,wh).producerCreationFailureCount+=1,s}})}closeProducer(e,r){return u(this,null,function*(){var i;const s=this.producers.get(e);if(!s){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&s.track.stop();try{yield this.sendTransport.closeProducer(s),(i=this.context.getValue("modules").e2ee)!=null&&i.enabled&&this.context.getValue("peerSessionStore").emit(P.E2EE_INACTIVE_PRODUCER,s)}catch(n){this.logger.error("Failed to close producer on server",{error:n,producer:s})}})}closeAllProducers(){return Promise.all(Array.from(a(this,Gn).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}createConsumers(e){return u(this,null,function*(){a(this,jo)||clearTimeout(a(this,jo)),f(this,xi,a(this,xi).concat(e)),yield U(this,sl,_h).call(this)})}closeConsumer(e){return this.closeConsumers([e])}closeConsumers(e){return u(this,null,function*(){if(!a(this,Fr))return;const r=e.map(s=>this.consumers.get(s)).filter(s=>s!==void 0);if(r.length===0)return;const{failedConsumers:i}=yield a(this,Fr).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,Rs).keys()))}switchConsumersToLayer(e,r){return u(this,null,function*(){a(this,Fr).switchConsumersToLayer(e,r)})}}Gn=new WeakMap,Rs=new WeakMap,Po=new WeakMap,il=new WeakMap,Fr=new WeakMap,wh=new WeakMap,xi=new WeakMap,jo=new WeakMap,sl=new WeakSet,_h=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,xi).splice(0,a(this,xi).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:s,failedProducers:n}=yield this.recvTransport.consume(i,U(this,Ph,Dg).bind(this),a(this,Fr).negotiate.bind(a(this,Fr)));if(s.forEach(U(this,Rh,Og).bind(this)),n!=null&&n.length){this.logger.error("Failed to create consumers for producers",{producers:n});const o=n.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,xi,a(this,xi).concat(o)),f(this,jo,setTimeout(U(this,sl,_h).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})}}})},Ih=new WeakSet,Sy=function(t){return a(this,il).create(t)},Ch=new WeakSet,Ey=function(t,e){t.on("close",(r,i)=>u(this,null,function*(){const{offer:s,reason:n}=r;if(this.logger.info("producer::closing",{debuggingHint:n,producer:q(V({},t),{status:"closing"})}),n!==rl){const o={producerId:t.id,description:{sdp:s.sdp,type:s.type,target:di.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,Gn).set(t.id,t)},Ph=new WeakSet,Dg=function(t){return u(this,null,function*(){try{return yield this.recvTransport.canConsume(),yield a(this,Fr).create(t)}catch(e){throw this.logger.error("Error in consume request",{error:e}),e}})},Rh=new WeakSet,Og=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,Rs).delete(t.id),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:t.id})})),a(this,Rs).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 Id,Cd,Pd,Ro,Ho,Go,nl,al,Mo,Yt,Br,Ur,vs,ys,Vi,ol,Mh,ky,Ah,Ty,Dh,by,Oh,wy;const Nh=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:s=.95,voiceAdaptationRate:n=.99,minEnergyThreshold:o=.005,maxEnergyThreshold:c=.2,energyRatioThreshold:d=1.5,noiseHistorySize:l=50}={}){g(this,Mh),g(this,Ah),g(this,Id,void 0),g(this,Cd,void 0),g(this,Pd,void 0),g(this,Ro,void 0),g(this,Ho,void 0),g(this,Go,void 0),g(this,nl,void 0),g(this,al,void 0),g(this,Mo,void 0),g(this,Yt,void 0),g(this,Br,void 0),g(this,Ur,!1),g(this,vs,0),g(this,ys,0),g(this,Vi,[]),g(this,ol,void 0),f(this,Ro,t),f(this,Yt,t),f(this,Id,e),f(this,Cd,r),f(this,Pd,i),f(this,Ho,s),f(this,Go,n),f(this,nl,o),f(this,al,c),f(this,Mo,d),f(this,ol,l),f(this,Br,t/2)}get voiceDetected(){return a(this,Ur)}processAudioChunk(t){var e,r;const i=U(e=Nh,Dh,by).call(e,t),s=U(r=Nh,Oh,wy).call(r,t);return U(this,Mh,ky).call(this,i),i/a(this,Br)>a(this,Mo)&&i>a(this,Yt)&&s>a(this,Id)?(f(this,vs,a(this,vs)+1),f(this,ys,a(this,Pd)),a(this,vs)>=a(this,Cd)&&f(this,Ur,!0)):(f(this,vs,0),a(this,ys)>0?f(this,ys,a(this,ys)-1):a(this,Ur)&&f(this,Ur,!1),a(this,Ur)||U(this,Ah,Ty).call(this,i)),{energy:i,isVoice:a(this,Ur)}}reset(){f(this,Ur,!1),f(this,vs,0),f(this,ys,0),f(this,Yt,a(this,Ro)),f(this,Br,a(this,Ro)/2),f(this,Vi,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Yt),backgroundNoiseEnergy:a(this,Br),energyRatioThreshold:a(this,Mo)}}};let Vh=Nh;Id=new WeakMap,Cd=new WeakMap,Pd=new WeakMap,Ro=new WeakMap,Ho=new WeakMap,Go=new WeakMap,nl=new WeakMap,al=new WeakMap,Mo=new WeakMap,Yt=new WeakMap,Br=new WeakMap,Ur=new WeakMap,vs=new WeakMap,ys=new WeakMap,Vi=new WeakMap,ol=new WeakMap,Mh=new WeakSet,ky=function(t){a(this,Ur)?f(this,Yt,a(this,Go)*a(this,Yt)+(1-a(this,Go))*t):f(this,Yt,a(this,Ho)*a(this,Yt)+(1-a(this,Ho))*a(this,Br)),f(this,Yt,Math.max(a(this,nl),Math.min(a(this,al),a(this,Yt))))},Ah=new WeakSet,Ty=function(t){if(t<a(this,Yt)*1.2)if(a(this,Vi).push(t),a(this,Vi).length>a(this,ol)&&a(this,Vi).shift(),a(this,Vi).length>=10){const e=[...a(this,Vi)].sort((i,s)=>i-s),r=Math.floor(e.length/2);f(this,Br,e[r])}else f(this,Br,.95*a(this,Br)+.05*t)},Dh=new WeakSet,by=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Oh=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(Vh,Dh),g(Vh,Oh);const E1=60,k1=400;var Ri,Mi,Wr,Ms,As,Ao,Jn,qo,Ai,Ss,$o,Kn,Lh,_y,Rd,xh,Uh,Iy,yu,Ng;const cl=class{constructor(t,e){g(this,Lh),g(this,Uh),g(this,Ri,void 0),g(this,Mi,void 0),g(this,Wr,void 0),g(this,Ms,void 0),g(this,As,void 0),g(this,Ao,void 0),g(this,Jn,void 0),g(this,qo,void 0),g(this,Ai,void 0),g(this,Ss,void 0),g(this,$o,void 0),g(this,Kn,void 0),this.reportRequest=e,f(this,Ms,new AudioContext),f(this,As,a(this,Ms).createAnalyser()),a(this,As).fftSize=2048,f(this,qo,new Vh),f(this,Kn,t)}get logger(){return a(this,Kn).getValue("logger")}set producerId(t){f(this,Wr,t)}set audioTrack(t){f(this,Ao,t);const e=new MediaStream;e.addTrack(a(this,Ao)),a(this,Ms).createMediaStreamSource(e).connect(a(this,As))}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Wr)}`),a(this,Ri)&&Bn(a(this,Ri)),f(this,Ri,Wd(()=>u(this,null,function*(){var t;if(!a(this,Ao)||!a(this,Wr))return;const{energy:e}=U(this,Lh,_y).call(this),r=U(t=cl,Rd,xh).call(t,e);let i=.9;a(this,$o)!==r&&a(this,$o)?i=.9:r?i=.3:i=.5,f(this,Jn,(a(this,Jn)||0)*(1-i)+e*i)}),E1)),a(this,Mi)&&Bn(a(this,Mi)),f(this,Mi,Wd(U(this,Uh,Iy).bind(this),k1))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Wr)}`),a(this,Ri)&&(Bn(a(this,Ri)),f(this,Ri,void 0)),a(this,Mi)&&(Bn(a(this,Mi)),f(this,Mi,void 0))}catch{}a(this,qo).reset()}};let Fh=cl;Ri=new WeakMap,Mi=new WeakMap,Wr=new WeakMap,Ms=new WeakMap,As=new WeakMap,Ao=new WeakMap,Jn=new WeakMap,qo=new WeakMap,Ai=new WeakMap,Ss=new WeakMap,$o=new WeakMap,Kn=new WeakMap,Lh=new WeakSet,_y=function(){var t;a(this,Ms).state==="suspended"&&a(this,Ms).resume().then(()=>{this.logger.debug("AudioActivityReporter: AudioContext forced resumed")}).catch(n=>{this.logger.error("AudioActivityReporter: Error resuming AudioContext",n)});const e=new Float32Array(a(this,As).frequencyBinCount);a(this,As).getFloatTimeDomainData(e);const{energy:r,isVoice:i}=a(this,qo).processAudioChunk(e),s=U(t=cl,yu,Ng).call(t,r);return a(this,Kn).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: producer: ${a(this,Wr)}, energy: ${a(this,Jn)},
19
19
  slogScale: ${s}, isVoice: ${i}, minEnergy: ${a(this,Ai)},
20
20
  maxEnergy: ${a(this,Ss)}`),s===-1/0||r<1e-6?{energy:0,isVoice:!1}:((!a(this,Ai)||s<a(this,Ai))&&f(this,Ai,s),(!a(this,Ss)||s>a(this,Ss))&&f(this,Ss,s),{energy:(s-a(this,Ai))/(a(this,Ss)-a(this,Ai))*10||0,isVoice:i})},Rd=new WeakSet,xh=function(t){return t<5},Uh=new WeakSet,Iy=function(t=a(this,Jn)){var e;if(!a(this,Wr)||!t){a(this,Kn).getValue("flagsmith").hasFeature(Z.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,Wr)}`);return}const r={producerId:a(this,Wr),energy:Math.round(t),silent:U(e=cl,Rd,xh).call(e,t)};f(this,$o,r.silent),this.reportRequest(r)},yu=new WeakSet,Ng=function(t){const e=Math.log10(t);return Math.round(e)},g(Fh,Rd),g(Fh,yu);const T1=(t=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const r=new window.MediaStreamTrackGenerator({kind:"audio"}),i=r.writable.getWriter(),s=48e3,n=128,o=1;let c=0,d=null;const l=()=>u(void 0,null,function*(){try{const m=new Float32Array(n*o),v=new window.AudioData({format:"f32",sampleRate:s,numberOfFrames:n,numberOfChannels:o,timestamp:c,data:m});c+=n/s*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 s=r.createGain();s.gain.value=0,i.connect(s);const n=r.createMediaStreamDestination();s.connect(n),i.start();const o=n.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=t,o):void 0}catch{return}},b1=(t=!1)=>{var e,r;const i=new MediaStream().getVideoTracks()[0],s=document.createElement("canvas");s.height=(e=i==null?void 0:i.getSettings().height)!=null?e:720,s.width=(r=i==null?void 0:i.getSettings().width)!=null?r:1280;const n=s.getContext("2d");n.fillStyle="black",n.fillRect(0,0,s.width,s.height),setInterval(()=>{n.fillStyle="black",n.fillRect(0,0,s.width,s.height)},1e3);const o=s.captureStream().getVideoTracks()[0];return Object.assign(o,{fakeTracks:"fakeTracks:fakeVideoTrack"}),o.enabled=t,o};var w1=Object.defineProperty,_1=Object.getOwnPropertyDescriptor,me=(t,e,r,i)=>{for(var s=i>1?void 0:i?_1(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&w1(e,r,s),s};const Gt=["video/VP9","video/VP8"];var Uc,Fc,yt,J,to,Dr,Dt,ln,un,hn,Bc,pr,yi,ro,pn,mn,Ot,qt,ss,gn,Su,Vg,Eu,Lg,ku,xg,Wc,Tu,bu,wu,Ug,_u,Fg,Iu,Bg,Cu,Wg,dt,St,fn,io,Pu,jg,Ru,Hg,Mu,Gg;const Cy=(wu=class{constructor(t,e,r){g(this,ss),g(this,Su),g(this,Eu),g(this,ku),g(this,Wc),g(this,_u),g(this,Iu),g(this,Cu),g(this,dt),g(this,fn),g(this,Pu),g(this,Ru),g(this,Mu),p(this,"context"),p(this,"authToken"),p(this,"e2ee"),g(this,Uc,void 0),g(this,Fc,void 0),g(this,yt,void 0),g(this,J,void 0),g(this,to,void 0),g(this,Dr,void 0),g(this,Dt,void 0),g(this,ln,void 0),g(this,un,void 0),g(this,hn,void 0),g(this,Bc,void 0),g(this,pr,null),g(this,yi,void 0),g(this,ro,void 0),g(this,pn,void 0),g(this,mn,void 0),g(this,Ot,void 0),g(this,qt,void 0);var i,s;this.context=t;const{socket:n}=r;this.mediaJoined=!1,f(this,pn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,mn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Dr,e),f(this,yt,n),f(this,ln,!1),f(this,J,new S1(t,n,e)),f(this,Dt,a(this,J).events),f(this,yi,new Set),f(this,Ot,new Map),f(this,un,!1),f(this,hn,new ch(t.getValue("logger"))),e===Me.CF&&!navigator.isReactNative&&f(this,qt,new Fh(this.context,a(this,J).socketHandler.audioActivity.bind(a(this,J).socketHandler))),this.e2ee=(s=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?s:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Bc,lp(()=>u(this,null,function*(){if(!a(this,ss,gn).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,Fc),a(this,Uc),!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,ss,gn).mediaJoined}set mediaJoined(t){a(this,ss,gn).mediaJoined=t}reset(){a(this,J).closeAllProducers(),a(this,J).closeAllConsumers(),a(this,Ot).clear(),a(this,yi).clear(),f(this,pr,null),a(this,hn).stop(),a(this,J).stopAllTransports(),a(this,J).reset(),f(this,hn,new ch)}joinRoom(t,e){return u(this,arguments,function*(r,i,s=!1,n=!1,o={}){a(this,ss,gn).mediaJoinAttempted=!0,f(this,ln,!0),s&&this.reset();try{return yield a(this,hn).push(()=>U(this,Su,Vg).call(this,r,i,n,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,s=!1,n={}){return a(this,pr)?a(this,pr):(f(this,pr,(()=>u(this,null,function*(){try{yield U(this,Wc,Tu).call(this,r,i,s,n)}catch(o){throw f(this,pr,null),o}}))()),a(this,pr))})}getConsumers(){return a(this,J).consumers}leaveRoom(){return u(this,null,function*(){var t;a(this,J).stopAllTransports(),f(this,un,!1),a(this,ss,gn).mediaJoinAttempted=!1;const e={closeRoom:!1};if(a(this,Dr)!==Me.CF){try{const r=yield a(this,yt).sendMessagePromise(a(this,Dt).leaveRoom,bI.toBinary(e));(t=uC.fromBinary(r.payload))!=null&&t.closed||this.logger.warn("weird state on peer closed and should not happen")}catch(r){this.logger.error("error on sending leave room request",{error:r})}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,J).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((r,i)=>{const s=a(this,J).producerIdToConsumerIdMap.get(i.producerId);return s?(r.push(s),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);yield a(this,J).closeConsumers(e)})}_shareWebcam(t,e){return u(this,null,function*(){const r=e==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,i=U(this,dt,St).call(this,r);if(i){const h=yield i;if(a(this,J).producers.has(h)){const m=a(this,J).producers.get(h);if(!m.closed)return yield m.replaceTrack({track:t}),yield this.resumeWebcam(r),t;yield this.disableWebcam(e)}return this._shareWebcam(t,e)}const s=[e].concat(Gt.filter(h=>h!==e)),n=U(this,Mu,Gg).call(this,t,s),o=ea(this.context,"disableSimulcast"),c=a(this,Dr)===Me.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,Dr)}`),n.encodings=cO(this.context,t)):this.logger.info(`Simulcast disabled for webcam producer, SFU: ${a(this,Dr)}`),this.context.getValue("flagsmith").hasFeature(Z.TRACK_HINT)&&(n.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,J).createProducer(n,d);return U(this,fn,io).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(s=>{var n,o;return((o=(n=a(this,to).sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===s))>=0&&a(this,mn).get(s).size>0});return i.length===0&&i.push(Gt[0]),yield Promise.all(i.map(s=>(this.logger.debug(`Calling _shareWebcam with video codec: ${s}`),this._shareWebcam(t,s)))),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},s=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ot).delete(Se.SCREENSHARE_VIDEO),a(this,Ot).delete(Se.SCREENSHARE_AUDIO)},n=a(this,J).createProducer(i,s);U(this,fn,io).call(this,Se.SCREENSHARE_VIDEO,n.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,Dr)!==Me.CF},d=()=>{};o=a(this,J).createProducer(c,d),U(this,fn,io).call(this,Se.SCREENSHARE_AUDIO,o.then(l=>l.id))}yield Promise.all([n,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,dt,St).call(this,Se.MIC);if(e){const n=yield e;if(a(this,J).producers.has(n)){const o=a(this,J).producers.get(n);if(!o.closed){yield o.replaceTrack({track:t}),yield this.resumeMic(),a(this,qt)&&(a(this,qt).audioTrack=t,a(this,qt).producerId=n,a(this,qt).start());return}yield a(this,J).closeProducer(n,{stopTrack:!1})}yield this.shareMic(t);return}const r=U(this,Ru,Hg).call(this,t),i=()=>{a(this,Ot).delete(Se.MIC)},s=a(this,J).createProducer(r,i);U(this,fn,io).call(this,Se.MIC,s.then(n=>n.id)),yield s.then(n=>{a(this,qt)&&(a(this,qt).audioTrack=n.track,a(this,qt).producerId=n.id,a(this,qt).start())})}catch(e){throw new I(e)}})}pauseMic(){return u(this,null,function*(){var t;const e=yield U(this,dt,St).call(this,Se.MIC),r=a(this,J).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,yt).sendMessage(a(this,Dt).toggleProducer,Ec.toBinary(i))})}pauseWebcam(){return u(this,null,function*(){const t=yield U(this,dt,St).call(this,Se.WEBCAM),e=yield U(this,dt,St).call(this,Se.WEBCAM_BACKUP),r=a(this,J).producers.get(t),i=a(this,J).producers.get(e);if(!r&&!i){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const s=n=>{const o={producerId:n.id,pause:!0};a(this,yt).sendMessage(a(this,Dt).toggleProducer,Ec.toBinary(o))};r&&(r.pause(),s(r)),i&&(i.pause(),s(i))})}resumeMic(){return u(this,null,function*(){const t=yield U(this,dt,St).call(this,Se.MIC),e=a(this,J).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,yt).sendMessage(a(this,Dt).toggleProducer,Ec.toBinary(r))})}resumeWebcam(){return u(this,arguments,function*(t=Se.WEBCAM){const e=yield U(this,dt,St).call(this,t),r=a(this,J).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,yt).sendMessage(a(this,Dt).toggleProducer,Ec.toBinary(i))})}disableWebcam(t){return u(this,null,function*(){const e=t==="video/VP9"?Se.WEBCAM:Se.WEBCAM_BACKUP,r=yield U(this,dt,St).call(this,e);U(this,Pu,jg).call(this,e),r&&(yield a(this,J).closeProducer(r))})}disableMic(){return u(this,null,function*(){var t;const e=yield U(this,dt,St).call(this,Se.MIC);e&&(yield a(this,J).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,dt,St).call(this,Se.SCREENSHARE_VIDEO),e=yield U(this,dt,St).call(this,Se.SCREENSHARE_AUDIO);t&&(yield a(this,J).closeProducer(t)),e&&(yield a(this,J).closeProducer(e)),a(this,yi).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,dt,St).call(this,Se.WEBCAM),i=yield U(this,dt,St).call(this,Se.WEBCAM_BACKUP);yield a(this,J).closeProducer(r,{stopTrack:!1}),yield a(this,J).closeProducer(i,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=yield U(this,dt,St).call(this,Se.SCREENSHARE_VIDEO);yield a(this,J).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,J).socketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,J).socketHandler.kickPeer(e)}kickAll(){a(this,J).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,J).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,yt).sendMessagePromise(a(this,Dt).globalPinPeer,xI.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,J).producers.get(t.producerId)&&a(this,yi).add(t.consumerPeerId),a(this,yi).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const r=t.map(i=>this.getConsumers().get(i));a(this,J).switchConsumersToLayer(r,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,yt).on(a(this,Dt).peerProducerCreateBroadcast,({payload:t})=>{var e,r;if(this.mediaJoined)try{const{participantId:i,producerState:s}=WC.fromBinary(t);if(i===this.peerId)return;if(s!=null&&s.mimeType||(s.mimeType=s.kind===jr.AUDIO?"audio/opus":"video/VP8"),s.kind===jr.VIDEO&&!s.screenShare&&((r=(e=a(this,to).receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(n=>n.mimeType===Gt[0]))>=0&&a(this,pn).get(Gt[0]).has(i)&&s.mimeType!==Gt[0]){this.logger.warn(`Ignoring producer: ${s.producerId}`);return}this.logger.info(`producer created broadcast: ${i}, producer state: ${s}`),this.context.getValue("peerSessionStore").emit(P.NEW_PRODUCER,{peerId:i,producer:q(V({},s),{kind:s.kind===jr.AUDIO?"audio":"video",producingPeerId:i})})}catch(i){this.logger.error("error in peer-producer-create-broadcast",{error:i})}}),a(this,yt).on(a(this,Dt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:s,producerId:n}}=Om.fromBinary(t),o=i===jr.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${n}, kind:${o}, paused:${s} payload: ${JSON.stringify(Om.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&s&&this.context.getValue("peerSessionStore").emit(o==="audio"?P.MUTE_SELF:P.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(P.PRODUCER_TOGGLE,{peerId:e,producerId:n,paused:s,kind:o}),Array.from(this.getConsumers().values()).filter(c=>c.producerId===n).forEach(c=>{c.paused!==s&&(this.logger.debug(`consumer state mismatched for ${c.id}. updating consumer pause state ${c.paused} to ${s}`),s?(c.pause(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_PAUSED,{id:c.id})):(c.resume(),this.context.getValue("peerSessionStore").emit(P.CONSUMER_RESUMED,{id:c.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,yt).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,yi).delete(e),a(this,J).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,yt).on(a(this,Dt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=GC.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,J).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,J).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,J).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(P.CONSUMER_CLOSED,{id:i})}).catch(s=>{this.logger.error("error closing consumer",{error:s})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,yt).on(a(this,Dt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,ln)&&!a(this,un)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(P.ROOM_NODE_DISCONNECTED),a(this,Bc).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,J).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,J).producers.values()).find(s=>s.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,s,n;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,mn).get(c).add(t);break}}for(let o=0;o<=Gt.length;o+=1){const c=Gt[o];if(((n=(s=e==null?void 0:e.sender)==null?void 0:s.video)==null?void 0:n.codecs.findIndex(d=>d.mimeType===c))>=0||o===Gt.length-1){a(this,pn).get(c).add(t);break}}}handlePeerLeaving(t){this.context.getValue("flagsmith").hasFeature(Z.FORCE_VIDEO_CODEC)||(a(this,pn).forEach(e=>e.delete(t)),a(this,mn).forEach((e,r)=>{e.delete(t),!(e.size!==0||r===Gt[0])&&this.disableWebcam(r)}))}},Uc=new WeakMap,Fc=new WeakMap,yt=new WeakMap,J=new WeakMap,to=new WeakMap,Dr=new WeakMap,Dt=new WeakMap,ln=new WeakMap,un=new WeakMap,hn=new WeakMap,Bc=new WeakMap,pr=new WeakMap,yi=new WeakMap,ro=new WeakMap,pn=new WeakMap,mn=new WeakMap,Ot=new WeakMap,qt=new WeakMap,ss=new WeakSet,gn=function(){return this.context.getValue("connectionHandler")},Su=new WeakSet,Vg=function(t,e,r,i){return u(this,null,function*(){f(this,Fc,t);try{return a(this,pr)?yield a(this,pr):yield U(this,Wc,Tu).call(this,t,e,r,i),U(this,ku,xg).call(this,e),{roomJoined:yield U(this,Eu,Lg).call(this)}}catch(s){return this.logger.error("Failed to complete room join",{error:s}),{roomJoined:!1}}finally{f(this,pr,null)}})},Eu=new WeakSet,Lg=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,J).socketHandler.notifySelfJoinComplete();return f(this,Uc,t.roomUuid),f(this,un,!0),f(this,ln,!1),!0}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,!1}})},ku=new WeakSet,xg=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)},Wc=new WeakSet,Tu=function(t,e,r,i){return u(this,null,function*(){var s,n;try{(n=a(this,ro))!=null||f(this,ro,U(s=Cy,bu,Ug).call(s));const o=U(this,_u,Fg).call(this);yield U(this,Iu,Bg).call(this,t,e,r,o),yield a(this,J).setupTransports({send:!0,recv:!0}),yield U(this,Cu,Wg).call(this,i)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}})},bu=new WeakSet,Ug=function(){const{ipInfo:t}=ht();if(!(t!=null&&t.loc))return;const[e,r]=t.loc.split(",").map(parseFloat);return{latitude:e,longitude:r}},_u=new WeakSet,Fg=function(){var t;const e=(t=this.context.getValue("flagsmith").getValue(Z.FORCE_VIDEO_CODEC))==null?void 0:t.toString(),r=a1(e);return f(this,to,r),r},Iu=new WeakSet,Bg=function(t,e,r,i){return u(this,null,function*(){yield hy((s,n)=>u(this,null,function*(){if(!a(this,yt).isConnected){n(new Error("Socket is not connected"));return}s>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${s}`});try{yield a(this,J).socketHandler.joinRoom(e,t,i,r,a(this,ro))}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})})},Cu=new WeakSet,Wg=function(t){return u(this,null,function*(){if(!(a(this,Dr)===Me.HIVE||!this.context.getValue("flagsmith").hasFeature(Z.PRECREATE_PRODUCERS)||!t))try{const e=[];if(t.canProduceVideo===G.Allowed&&e.push(this.shareWebcam(b1(!1))),t.canProduceAudio===G.Allowed){const r=T1(!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})}})},dt=new WeakSet,St=function(t){return a(this,Ot).get(t)},fn=new WeakSet,io=function(t,e){return a(this,Ot).set(t,e)},Pu=new WeakSet,jg=function(t){return a(this,Ot).delete(t)},Ru=new WeakSet,Hg=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:a(this,Dr)!==Me.CF}},Mu=new WeakSet,Gg=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(wu,bu),wu);let le=Cy;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 Py(t,e,r){const i=t.getValue("roomNodeClient");if(i){if(i)return i;throw new Error("Room node client already set up.")}const s=new le(t,e,r);return t.setValue("roomNodeClient",s),s}function Ry(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch{t.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var I1=Object.defineProperty,C1=Object.getOwnPropertyDescriptor,$s=(t,e,r,i)=>{for(var s=i>1?void 0:i?C1(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&I1(e,r,s),s},ns,Or,ie,Nt,$t,qg;const My=(qg=class{constructor(t,e,r,i){g(this,Nt),p(this,"self"),p(this,"authToken"),g(this,ns,void 0),p(this,"viewType"),g(this,Or,void 0),g(this,ie,void 0);const{socket:s}=r,n=t.getValue("authToken");this.self=e,f(this,ie,t),this.viewType=i,this.authToken=n,f(this,ns,s),f(this,Or,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,s){return u(this,null,function*(){const n=ht(),o=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield nt.__init__(t,r,i,s,s.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 m=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(m)}),t.getValue("callstats").devices("AUDIO",m==null?void 0:m.filter(v=>v.kind==="audioinput")),t.getValue("callstats").devices("VIDEO",m==null?void 0:m.filter(v=>v.kind==="videoinput")),t.getValue("callstats").devices("SPEAKER",m==null?void 0:m.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 n.getICEServers(),apiBase:t.getValue("apiBase"),flags:t.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Pv(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 My(t,d,e,s.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:r,permissions:i,audioEnabled:s,videoEnabled:n,screenShareEnabled:o,screenShareTracks:c}=this.self;if(i.canProduceAudio===G.Allowed&&s)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&&n)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=Ns()),a(this,ns).updateURL(e),a(this,ie).getValue("telemetry").resetPeerId(e),ht().setHeader("dyte-tracing-id",e),ni.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,Or).on(F.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Or).on(Qc.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&a(this,ie).getValue("peerSessionStore").emit(P.UPDATE_PERMISSIONS,e.patch)})}),a(this,Or).on(F.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Or).on(F.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Or).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 s;const n=(s=r==null?void 0:r.screenShare)!=null?s:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:n,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,Or).joinRoom(this.self);a(this,Or).socket.flush();const r=gp(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(t==="rejected"){try{(e=a(this,ns))==null||e.disconnect()}catch{this.logger.error("SelfController::leaveRoom::socketDisconnect")}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,ns))==null||r.disconnect()}catch{this.logger.error("SelfController::leaveRoom::socketDisconnect")}Ry(a(this,ie)),yield a(this,ie).getValue("roomSocketHandler").cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,r;const{peerId:i,viewType:s,meetingId:n,stageStatus:o,roomNodeOptions:c}=a(this,ie).getAllValues(),{sfu:d}=c;try{if(s===Ft.Livestream){if(o!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}Py(a(this,ie),d,{socket:a(this,ns),peerId:i})}const{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}=this.self.permissions,{roomJoined:v}=(r=yield(e=a(this,Nt,$t))==null?void 0:e.joinRoom(this.self.name,n,t,t,{canProduceAudio:l,canProduceVideo:h,canProduceScreenshare:m}))!=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()})}},ns=new WeakMap,Or=new WeakMap,ie=new WeakMap,Nt=new WeakSet,$t=function(){return a(this,ie).getValue("roomNodeClient")},qg);let Ji=My;$s([k.trace("SelfController.resetSelf")],Ji.prototype,"resetSelf",1);$s([k.trace("SelfController.setupEvents")],Ji.prototype,"setupEvents",1);$s([k.trace("SelfController.joinRoom")],Ji.prototype,"joinRoom",1);$s([k.trace("SelfController.leaveRoom")],Ji.prototype,"leaveRoom",1);$s([k.trace("SelfController.joinMediaRoom")],Ji.prototype,"joinMediaRoom",1);$s([k.trace("SelfController.leaveMediaRoom")],Ji.prototype,"leaveMediaRoom",1);$s([k.trace("SelfController.init")],Ji,"init",1);var Md;class P1{constructor(e){g(this,Md,void 0),f(this,Md,e)}on(e,r){let i;e===F.roomPeerCount?i=Lm.fromBinary.bind(Lm):i=Jm.fromBinary.bind(Jm),a(this,Md).on(e,({payload:s})=>{const n=i(s);return r(n)})}}Md=new WeakMap;var Ad,Dd;class R1{constructor(e,r){g(this,Ad,void 0),g(this,Dd,void 0),f(this,Ad,r),f(this,Dd,e)}get logger(){return a(this,Dd).getValue("logger")}on(e,r){let i,s;switch(e){case F.transcript:{i=Kl.fromBinary.bind(Kl),s=Kl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Ad).on(e,({payload:n})=>{let o=s;try{o=i(n)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return r(o)})}}Ad=new WeakMap,Dd=new WeakMap;var M1=Object.defineProperty,A1=Object.getOwnPropertyDescriptor,Cp=(t,e,r,i)=>{for(var s=i>1?void 0:i?A1(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&M1(e,r,s),s},Di,Do;class Dl{constructor(e,r){g(this,Di,void 0),g(this,Do,void 0),f(this,Di,r),f(this,Do,e)}get logger(){return a(this,Do).getValue("logger")}get telemetry(){return a(this,Do).getValue("telemetry")}getPolls(){return a(this,Di).sendMessagePromise(Zr.getPolls)}createPoll(e,r,i=!1,s=!1){const n={anonymous:i,hideVotes:s,question:e,options:r};return a(this,Di).sendMessage(Zr.createPoll,DA.toBinary(n))}votePoll(e,r){const i={index:r,pollId:e};return a(this,Di).sendMessage(Zr.votePoll,NA.toBinary(i))}on(e,r){let i,s;switch(e){case Zr.updatePoll:case Zr.createPoll:case Zr.votePoll:{i=eu.fromBinary.bind(eu),s=eu.create();break}}a(this,Di).on(e,({payload:n})=>{let o=s;try{o=i(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return r(o)})}removeListeners(e){a(this,Di).removeListeners(e)}}Di=new WeakMap,Do=new WeakMap;Cp([k.trace("PollSocketHandler.getPolls")],Dl.prototype,"getPolls",1);Cp([k.trace("PollSocketHandler.createPoll")],Dl.prototype,"createPoll",1);Cp([k.trace("PollSocketHandler.votePoll")],Dl.prototype,"votePoll",1);var D1=Object.defineProperty,O1=Object.getOwnPropertyDescriptor,N1=(t,e,r,i)=>{for(var s=i>1?void 0:i?O1(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&D1(e,r,s),s},ar;class Ay{constructor(e,r){p(this,"socket"),g(this,ar,void 0),f(this,ar,e),this.socket=r,this.handleSocketEvents(),a(this,ar).setValue("roomSocketHandler",this)}get telemetry(){return a(this,ar).getValue("telemetry")}get logger(){return a(this,ar).getValue("logger")}cleanup(){return u(this,null,function*(){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:""},s=this.socket.sendMessagePromise(F.joinRoom,SP.toBinary(i));try{const{peer:n}=yn.fromBinary((yield s).payload);a(this,ar).getValue("connectionHandler").socketJoined=!0,a(this,ar).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return a(this,ar).getValue("peerSessionStore").emit(P.ROOM_STATE,d),a(this,ar).getValue("peerSessionStore").emit(P.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),new I("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,n)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return iR.fromBinary((yield this.socket.sendMessagePromise(F.getAllAddedParticipants)).payload).participants.map(e=>{var r=e,{id:i}=r,s=vl(r,["id"]);return q(V({},s),{userId:i})})}catch{return[]}})}getRoomPeers(e,r,i){return u(this,null,function*(){let s;try{const n={seachQuery:e,limit:r,offset:i},o=yield this.socket.sendMessagePromise(F.getRoomPeersInfo,dP.toBinary(n));s=zl.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return s})}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,Fv.toBinary({peerId:e}));r=yn.fromBinary(i.payload)}catch(i){this.logger.error("getPeerInfo::binary_decode_error",{error:i})}return r})}getRoomState(){return u(this,null,function*(){let e=xm.create();try{const r=yield this.socket.sendMessagePromise(F.getRoomInfo);e=xm.fromBinary(r.payload)}catch(r){this.logger.error("getRoomState::binary_decode_error",{error:r})}return e})}getRoomStageState(){return u(this,null,function*(){let e=Wm.create();try{const r=yield this.socket.sendMessagePromise(F.getRoomStageState);e=Wm.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,wa.toBinary(i))})}broadcastToMeetings(e,r,i){return u(this,null,function*(){const s={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:r,broadcastType:1};return this.socket.sendMessagePromise(F.broadcastToEntity,wa.toBinary(s))})}broadcastToPeers(e,r,i){return u(this,null,function*(){const s={type:e,payload:new TextEncoder().encode(JSON.stringify(i)),timestamp:Date.now(),ids:r,broadcastType:0};return this.socket.sendMessage(F.broadcastToEntity,wa.toBinary(s))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(F.leaveRoom,kP.toBinary({}))})}kick(e){return u(this,null,function*(){const r={peerIds:[e]};this.socket.sendMessage(F.kick,Wv.toBinary(r))})}kickAll(e=!1){return u(this,null,function*(){const r={propagateKickAcrossRooms:e};this.socket.sendMessage(F.kickAll,Lv.toBinary(r))})}getWaitingRoomRequests(){this.socket.sendMessage(F.getWaitingRoomRequests)}acceptWaitingRoomRequest(e){const r={userIds:e};this.socket.sendMessage(F.acceptWaitingRoomRequests,dR.toBinary(r))}rejectWaitingRoomRequest(e){const r={userIds:e};this.socket.sendMessage(F.denyWaitingRoomRequests,uR.toBinary(r))}updatePermissions(e,r){return u(this,null,function*(){const i={updatePeersPresets:[]};return e.forEach(s=>{i.updatePeersPresets.push({userIds:s,patch:r})}),this.socket.sendMessagePromise(Qc.updateUserPreset,BR.toBinary(i))})}handleSocketEvents(){this.socket.on(F.broadcastMessage,({payload:e})=>{try{const r=wa.fromBinary(e);a(this,ar).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=wa.fromBinary(e);a(this,ar).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,s;switch(e){case F.joinRoom:case F.leaveRoom:case F.kick:case F.kickAll:{i=yn.fromBinary.bind(yn),s=yn.create();break}case F.getWaitingRoomRequests:{i=(n,o)=>n?Bm.fromBinary(n,o):{requests:[]},s=Bm.create();break}case F.recordingPaused:case F.recordingStarted:case F.recordingStopped:{i=Ym.fromBinary.bind(Ym);break}case Qc.updateUserPreset:{i=jm.fromBinary.bind(jm);break}case br.peerJoinedBroadcast:case cr.peerJoinedBroadcast:{i=Am.fromBinary.bind(Am);break}case br.selfJoinComplete:case cr.selfJoinComplete:{i=qu.fromBinary.bind(qu);break}case br.globalPeerPinBroadcast:case cr.globalPeerPinBroadcast:{i=Nm.fromBinary.bind(Nm);break}case br.selectedPeer:case cr.selectedPeer:{i=Gu.fromBinary.bind(Gu);break}case br.selectedPeerDiff:case cr.selectedPeerDiff:{i=Mm.fromBinary.bind(Mm);break}case br.leaveRoom:case cr.leaveRoom:{i=$u.fromBinary.bind($u);break}}this.socket.on(e,({payload:n})=>{let o=s;if(!i)return r(void 0);try{o=i(n)}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(Qc.getUserPresets,OR.toBinary(r)),s=xR.fromBinary(i.payload).peerPresets[0],n=new TextDecoder().decode(s.preset),o=JSON.parse(n).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}})}}ar=new WeakMap;N1([k.trace("RoomSocketHandler.joinRoom")],Ay.prototype,"joinRoom",1);var zt;class V1{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,TA.toBinary(r))})}denyAccess(e){return u(this,null,function*(){const r={userIds:e};a(this,zt).sendMessage(F.denyStageAccess,wA.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,zm.toBinary(r),void 0,F.peerStageStatusUpdate)}kick(e){const r={userIds:e};return a(this,zt).sendMessagePromise(F.leaveStage,zm.toBinary(r))}on(e,r){let i;switch(e){case F.grantStageAccess:case F.denyStageAccess:{i=void 0;break}case F.getStagePeers:{i=Km.fromBinary.bind(Km);break}case F.getStageRequests:case F.requestStageAccess:case F.cancelStageRequest:{i=Zl.fromBinary.bind(Zl);break}case F.peerStageStatusUpdate:{i=Vm.fromBinary.bind(Vm);break}}a(this,zt).on(e,({payload:s,id:n})=>{if(!s||!i)return r(void 0,n);const o=i(s);return r(o,n)})}getPeerInfo(e){return u(this,null,function*(){const r=yield a(this,zt).sendMessagePromise(F.getPeerInfo,Fv.toBinary({peerId:e}));return yn.fromBinary(r.payload)})}}zt=new WeakMap;var rt,Od;class L1{constructor(e,r){g(this,rt,void 0),g(this,Od,void 0),f(this,rt,r),f(this,Od,e)}get logger(){return a(this,Od).getValue("logger")}addPlugin(e,r){a(this,rt).sendMessage($.addPlugin,FM.toBinary({pluginId:e,staggered:r}))}removePlugin(e){a(this,rt).sendMessage($.removePlugin,WM.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield a(this,rt).sendMessagePromise($.getPlugins);return e?lA.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,r,i){const s={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,rt).sendMessage($.customPluginEventToRoom,QM.toBinary(s),i)}customPluginEventToPeers(e,r,i,s){const n={pluginId:e,peerIds:r,pluginData:new TextEncoder().encode(JSON.stringify(i))};a(this,rt).sendMessage($.customPluginEventToPeers,ZM.toBinary(n),s)}enablePluginForRoom(e,r){a(this,rt).sendMessage($.enablePluginForRoom,HM.toBinary({pluginId:e}),r)}enablePluginForPeers(e,r,i){a(this,rt).sendMessage($.enablePluginForPeers,JM.toBinary({pluginId:e,peerIds:r}),i)}disablePluginForRoom(e,r){a(this,rt).sendMessage($.disablePluginForRoom,qM.toBinary({pluginId:e}),r)}disablePluginForPeers(e,r,i){a(this,rt).sendMessage($.disablePluginForPeers,zM.toBinary({pluginId:e,peerIds:r}),i)}storeInsertKeys(e,r,i,s){const n={pluginId:e,storeName:r,insertKeys:i.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,rt).sendMessage($.storeInsertKeys,Hm.toBinary(n),s)}storeGetKeys(e,r,i,s){const n={pluginId:e,storeName:r,getKeys:i.map(o=>({storeKey:o.key}))};a(this,rt).sendMessage($.storeGetKeys,iA.toBinary(n),s)}storeDeleteKeys(e,r,i,s){const n={pluginId:e,storeName:r,deleteKeys:i.map(o=>({storeKey:o.key}))};a(this,rt).sendMessage($.storeDeleteKeys,nA.toBinary(n),s)}storeDelete(e,r,i){a(this,rt).sendMessage($.storeDelete,oA.toBinary({pluginId:e,storeName:r}),i)}getPluginDataOld(e,r){this.logger.info("getPluginDataOld",{plugin:{id:e,storeName:r}})}storePluginDataOld(e,r,i){const s={pluginId:e,storeName:r,insertKeys:[{storeKey:i.key,payload:new TextEncoder().encode(JSON.stringify(i))}]};a(this,rt).sendMessage($.storeInsertKeys,Hm.toBinary(s))}on(e,r){let i;switch(e){case $.addPlugin:case $.enablePluginForPeers:case $.enablePluginForRoom:{i=Yu.fromBinary.bind(Yu);break}case $.removePlugin:case $.disablePluginForPeers:case $.disablePluginForRoom:{i=Gm.fromBinary.bind(Gm);break}case $.customPluginEventToPeers:case $.customPluginEventToRoom:{i=$m.fromBinary.bind($m);break}case $.storeInsertKeys:case $.storeGetKeys:case $.storeDeleteKeys:case $.storeDelete:{i=qm.fromBinary.bind(qm);break}}a(this,rt).on(e,({payload:s,id:n})=>{const o=i(s);return r(o,n)})}}rt=new WeakMap,Od=new WeakMap;var x1=Object.defineProperty,U1=(t,e,r)=>e in t?x1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,F1=(t,e,r)=>(U1(t,typeof e!="symbol"?e+"":e,r),r),Pp=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)},N=(t,e,r)=>(Pp(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)=>(Pp(t,e,"write to private field"),i?i.call(t,r):e.set(t,r),r),Re=(t,e,r)=>(Pp(t,e,"access private method"),r),dl={},B1={get exports(){return dl},set exports(t){dl=t}},zn=typeof Reflect=="object"?Reflect:null,$g=zn&&typeof zn.apply=="function"?zn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Nd;zn&&typeof zn.ownKeys=="function"?Nd=zn.ownKeys:Object.getOwnPropertySymbols?Nd=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Nd=function(t){return Object.getOwnPropertyNames(t)};function W1(t){console&&console.warn&&console.warn(t)}var Dy=Number.isNaN||function(t){return t!==t};function pe(){pe.init.call(this)}B1.exports=pe;dl.once=q1;pe.EventEmitter=pe;pe.prototype._events=void 0;pe.prototype._eventsCount=0;pe.prototype._maxListeners=void 0;var Jg=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 Jg},set:function(t){if(typeof t!="number"||t<0||Dy(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Jg=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||Dy(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 Oy(t){return t._maxListeners===void 0?pe.defaultMaxListeners:t._maxListeners}pe.prototype.getMaxListeners=function(){return Oy(this)};pe.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var i=t==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var n;if(e.length>0&&(n=e[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=s[t];if(c===void 0)return!1;if(typeof c=="function")$g(c,this,e);else for(var d=c.length,l=Uy(c,d),r=0;r<d;++r)$g(l[r],this,e);return!0};function Ny(t,e,r,i){var s,n,o;if(Ol(r),n=t._events,n===void 0?(n=t._events=Object.create(null),t._eventsCount=0):(n.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),n=t._events),o=n[e]),o===void 0)o=n[e]=r,++t._eventsCount;else if(typeof o=="function"?o=n[e]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),s=Oy(t),s>0&&o.length>s&&!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,W1(c)}return t}pe.prototype.addListener=function(t,e){return Ny(this,t,e,!1)};pe.prototype.on=pe.prototype.addListener;pe.prototype.prependListener=function(t,e){return Ny(this,t,e,!0)};function j1(){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 Vy(t,e,r){var i={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},s=j1.bind(i);return s.listener=r,i.wrapFn=s,s}pe.prototype.once=function(t,e){return Ol(e),this.on(t,Vy(this,t,e)),this};pe.prototype.prependOnceListener=function(t,e){return Ol(e),this.prependListener(t,Vy(this,t,e)),this};pe.prototype.removeListener=function(t,e){var r,i,s,n,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(s=-1,n=r.length-1;n>=0;n--)if(r[n]===e||r[n].listener===e){o=r[n].listener,s=n;break}if(s<0)return this;s===0?r.shift():H1(r,s),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 s=Object.keys(r),n;for(i=0;i<s.length;++i)n=s[i],n!=="removeListener"&&this.removeAllListeners(n);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 Ly(t,e,r){var i=t._events;if(i===void 0)return[];var s=i[e];return s===void 0?[]:typeof s=="function"?r?[s.listener||s]:[s]:r?G1(s):Uy(s,s.length)}pe.prototype.listeners=function(t){return Ly(this,t,!0)};pe.prototype.rawListeners=function(t){return Ly(this,t,!1)};pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):xy.call(t,e)};pe.prototype.listenerCount=xy;function xy(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?Nd(this._events):[]};function Uy(t,e){for(var r=new Array(e),i=0;i<e;++i)r[i]=t[i];return r}function H1(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function G1(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function q1(t,e){return new Promise(function(r,i){function s(o){t.removeListener(e,n),i(o)}function n(){typeof t.removeListener=="function"&&t.removeListener("error",s),r([].slice.call(arguments))}Fy(t,e,n,{once:!0}),e!=="error"&&$1(t,s,{once:!0})})}function $1(t,e,r){typeof t.on=="function"&&Fy(t,"error",e,r)}function Fy(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 s(n){i.once&&t.removeEventListener(e,s),r(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class J1 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 Kg=new J1;class By{static encode(e){return Kg.toBinary(e)}static decode(e){return Kg.fromBinary(new Uint8Array(e))}}function K1(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Oi;class z1{constructor(e={}){F1(this,"opts"),we(this,Oi,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},de(this,Oi,0)}wait(){return u(this,null,function*(){de(this,Oi,N(this,Oi)+1);const e=K1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*sE(2,N(this,Oi))));yield new Promise(r=>{setTimeout(r,e)})})}getAttempts(){return N(this,Oi)}reset(){de(this,Oi,0)}}Oi=new WeakMap;const Si={debug:0,info:1,warn:2,error:3};var Es,ks;class Y1{constructor(e){we(this,Es,void 0),we(this,ks,void 0),de(this,Es,console),de(this,ks,e)}debug(...e){Si[N(this,ks)]>Si.debug||N(this,Es).debug("[Sockrates]:",...e)}info(...e){Si[N(this,ks)]>Si.info||N(this,Es).info("[Sockrates]:",...e)}warn(...e){Si[N(this,ks)]>Si.warn||N(this,Es).warn("[Sockrates]:",...e)}error(...e){Si[N(this,ks)]>Si.error||N(this,Es).error("[Sockrates]:",...e)}}Es=new WeakMap,ks=new WeakMap;var Wy=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(Wy||{});const Q1="2",X1="3";var Le,Nn,Pe,je,Ni,it,si,Fi,Tr,Vn,Xr,Bh,jy,Oo,Vd,Wh,Hy,jh,zg,ll,Hh,Gh,Gy,Jo,Ld,Ko,ul,hl,qh,Yn,zo,Yo,pl;class Z1{constructor(e,r){var i;we(this,Bh),we(this,Oo),we(this,Wh),we(this,jh),we(this,ll),we(this,Gh),we(this,Jo),we(this,Ko),we(this,hl),we(this,Yn),we(this,Yo),we(this,Le,void 0),we(this,Nn,void 0),we(this,Pe,void 0),we(this,je,void 0),we(this,Ni,void 0),we(this,it,void 0),we(this,si,void 0),we(this,Fi,void 0),we(this,Tr,void 0),we(this,Vn,void 0),we(this,Xr,void 0);var s,n,o,c,d,l,h,m,v;de(this,Nn,e),de(this,Ni,[]),de(this,it,new dl),de(this,si,!0),de(this,Tr,!1),de(this,Pe,r!=null?r:{}),(s=N(this,Pe)).autoReconnect!=null||(s.autoReconnect=!0),(n=N(this,Pe)).retryConnectionInterval!=null||(n.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),(m=N(this,Pe)).queueOnDisconnect!=null||(m.queueOnDisconnect=!1),(v=N(this,Pe)).flushOnReconnect!=null||(v.flushOnReconnect=!1),de(this,Fi,{code:void 0,reason:void 0}),de(this,je,(i=N(this,Pe).logger)!=null?i:new Y1(N(this,Pe).debug?"debug":"info")),de(this,Xr,new z1)}get readyState(){var e;return(e=N(this,Le))==null?void 0:e.readyState}get url(){return N(this,Nn)}updateURL(e){de(this,Nn,e),Re(this,Gh,Gy).call(this)}get config(){return N(this,Pe)}get sendQueue(){return N(this,Ni)}flush(){if(!N(this,Pe).queueOnDisconnect)return!1;const e=[];return N(this,Ni).forEach(r=>{this.send(r.event,r.id,r.payload,r.metadata)||e.push(r)}),de(this,Ni,e),N(this,Ni)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){N(this,je).debug("Websocket was already connecting or connected.");return}if(N(this,si)!==!1)return new Promise((r,i)=>{Re(this,Yn,zo).call(this),Re(this,Yo,pl).call(this);try{de(this,Le,new WebSocket(Re(this,Bh,jy).call(this,N(this,Nn)))),N(this,Le).binaryType="arraybuffer",N(this,je).debug("Connecting");const s=setTimeout(()=>{N(this,je).debug("Connection timeout. Closing socket"),de(this,si,!0),Re(this,Yo,pl).call(this),N(this,Le).close(3001,"Connection Timeout"),N(this,Pe).autoReconnect&&!N(this,Tr)&&(N(this,it).emit("reconnecting"),Re(this,Jo,Ld).call(this)),i(new Error("Connection timed out!"))},N(this,Pe).connectionTimeout);N(this,Le).onopen=()=>{N(this,je).debug(`Ready State: ${Wy[N(this,Le).readyState]}`),s&&clearTimeout(s),Re(this,hl,qh).call(this),de(this,Fi,{code:void 0,reason:void 0}),N(this,it).emit("connected"),N(this,Pe).flushOnReconnect&&this.flush(),r()},N(this,Le).onclose=n=>{try{s&&clearTimeout(s);const{code:o,reason:c}=n;i(c),N(this,je).debug("Socket closed. Close event:",{event:n}),N(this,je).debug(`Connection closed code: ${o}`),N(this,je).debug(`Connection closed reason: ${c}`),N(this,Tr)||Re(this,ll,Hh).call(this,o,c)}catch(o){Re(this,Oo,Vd).call(this,o)}},N(this,Le).onerror=n=>{Re(this,Oo,Vd).call(this,n)},N(this,Le).onmessage=n=>Re(this,Wh,Hy).call(this,n)}catch(s){Re(this,Oo,Vd).call(this,s,i)}})})}send(e,r,i,s){const n={event:e,id:r,payload:i,metadata:s};if(N(this,Pe).queueOnDisconnect&&(!N(this,Le)||N(this,Le).readyState!==1))return N(this,je).debug("Queuing message since socket is not connected!",n),N(this,Ni).push(n),!1;const o=By.encode(n);return Re(this,Ko,ul).call(this,o)}emit(e,r,i,s){return this.send(e,r,i,s)}sendRaw(e){return Re(this,Ko,ul).call(this,e)}receive(e,r){return N(this,it).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,it).on(e,r);return}this.receive(e,r)}removeAllListeners(){N(this,it).removeAllListeners()}removeReceiver(e,r){this.removeListener(e,r)}removeListener(e,r){N(this,it).removeListener(e.toString(),r)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){N(this,it).listeners(e.toString()).map(r=>this.removeListener(e,r))}disconnect(){de(this,si,!1),Re(this,Yn,zo).call(this),this.removeAllListeners(),de(this,Fi,{code:1e3,reason:"Sockrates disconnect method called"}),N(this,Le).close(1e3,"Sockrates disconnect method called.")}}Le=new WeakMap,Nn=new WeakMap,Pe=new WeakMap,je=new WeakMap,Ni=new WeakMap,it=new WeakMap,si=new WeakMap,Fi=new WeakMap,Tr=new WeakMap,Vn=new WeakMap,Xr=new WeakMap,Bh=new WeakSet,jy=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)://.")},Oo=new WeakSet,Vd=function(t,e){N(this,je).error("Error:",{error:t}),N(this,it).emit("errored",{error:t}),e==null||e(t)},Wh=new WeakSet,Hy=function(t){if(Re(this,hl,qh).call(this),t.data===Q1){N(this,je).debug("Received ping from server"),Re(this,Ko,ul).call(this,X1);return}const e=By.decode(t.data),{id:r,payload:i}=e;N(this,je).debug("Received message",{event:e.event,messageID:r}),N(this,it).emit(e.event.toString(),{id:r,payload:i})},jh=new WeakSet,zg=function(){return N(this,Le).readyState===1},ll=new WeakSet,Hh=function(t,e){de(this,Fi,{reason:e,code:t}),N(this,it).emit("disconnected",{code:t,reason:e})},Gh=new WeakSet,Gy=function(){const{reason:t,code:e}=N(this,Fi);e&&e!==1e3&&N(this,si)&&N(this,Pe).autoReconnect&&!N(this,Tr)&&(N(this,je).debug(`Triggering reconnection due to ${t}.`),N(this,it).emit("reconnecting"),Re(this,Jo,Ld).call(this))},Jo=new WeakSet,Ld=function(t=!0){return u(this,null,function*(){if(t&&N(this,Tr)){N(this,je).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(N(this,Tr)||N(this,Xr).reset(),N(this,Pe).maxReconnectionAttempts!==null&&N(this,Xr).getAttempts()>=N(this,Pe).maxReconnectionAttempts){N(this,it).emit("failed"),de(this,Tr,!1);return}de(this,Tr,!0),Re(this,Yo,pl).call(this),Re(this,Yn,zo).call(this);try{if(yield N(this,Xr).wait(),N(this,si)===!1)return;if(N(this,je).debug(`Reconnection attempt ${N(this,Xr).getAttempts()}`),N(this,it).emit("reconnectAttempt",{attempt:N(this,Xr).getAttempts()}),yield this.connect(),!Re(this,jh,zg).call(this))throw Error("Reconnect Failed");de(this,Tr,!1),de(this,Fi,{code:void 0,reason:void 0}),N(this,it).emit("reconnected")}catch{N(this,je).debug("Failed to reconnect."),N(this,it).emit("reconnectFailure",{attempt:N(this,Xr).getAttempts()}),Re(this,Jo,Ld).call(this,!1)}})},Ko=new WeakSet,ul=function(t){try{return N(this,Le).send(t),!0}catch(e){return N(this,je).error(e.message),!1}},hl=new WeakSet,qh=function(){this.config.disconnectOnPingTimeout&&(N(this,je).debug("Resetting ping timeout"),Re(this,Yn,zo).call(this),de(this,Vn,setTimeout(()=>{var t;N(this,je).debug("Disconnecting the socket due to ping timeout"),de(this,si,!0);const e=3002,r="Ping timeout";(t=N(this,Le))==null||t.close(e,r),Re(this,ll,Hh).call(this,e,r)},N(this,Pe).pingTimeout)))},Yn=new WeakSet,zo=function(){N(this,Vn)&&(clearTimeout(N(this,Vn)),de(this,Vn,void 0))},Yo=new WeakSet,pl=function(){N(this,Le)&&(N(this,Le).onopen=void 0,N(this,Le).onerror=void 0,N(this,Le).onmessage=void 0,N(this,Le).onclose=void 0)};var eN=Object.defineProperty,tN=Object.getOwnPropertyDescriptor,Nl=(t,e,r,i)=>{for(var s=i>1?void 0:i?tN(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&eN(e,r,s),s};const Yg=65535,rN=3e3;var as,Oe,Ne,xe,mr,lt,jc,Au,Hc,Du,Qg;const qy=(Qg=class{constructor(t,{peerId:e,meetingId:r,authToken:i,capabilities:s}){g(this,Ne),g(this,jc),g(this,Hc),g(this,as,void 0),g(this,Oe,void 0),p(this,"roomName"),p(this,"authToken"),p(this,"capabilities"),g(this,mr,void 0),g(this,lt,void 0);var n;if(!e||!r||!i)throw new I("peerId, meetingId, or authToken can not be empty","0404");f(this,mr,void 0),f(this,lt,t),this.capabilities=s,this.roomName=r,this.authToken=i,f(this,as,U(this,jc,Au).call(this,e)),f(this,Oe,new Z1(a(this,as),{autoReconnect:!0,disconnectOnPingTimeout:(n=s.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Ne,xe).socketJoinAttempted}set joinAttempted(t){a(this,Ne,xe).socketJoinAttempted=t}get telemetry(){return a(this,lt).getValue("telemetry")}get logger(){return a(this,lt).getValue("logger")}get peerId(){return a(this,lt).getValue("peerId")}updateURL(t){t!==this.peerId&&(f(this,as,U(this,jc,Au).call(this,t)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Oe).updateURL(a(this,as))}static getSocketEdgeDomain(t){return Ds({servicePrefix:"socket-edge",baseURI:t})}get url(){return a(this,as)}connect(){return u(this,null,function*(){a(this,Ne,xe).socketJoinAttempted=!0,yield a(this,Oe).connect(),a(this,Ne,xe).socketJoinAttempted=!0,a(this,Ne,xe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){a(this,Ne,xe).socketJoinAttempted=!1,a(this,Oe).disconnect(),a(this,Ne,xe).socketJoinAttempted=!0,a(this,Ne,xe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return a(this,Oe).readyState===1}catch{return!1}}sendMessage(t,e,r){const i={};return a(this,lt).getValue("telemetry").injectContext(i),a(this,Oe).send(t,r!=null?r:U(this,Hc,Du).call(this),e,new TextEncoder().encode(JSON.stringify(i)))}sendMessagePromise(t,e,r,i){const s=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:s,protobuf:e,messageId:r,resp:i})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:r,messageId:i,resp:s}){const n=s!=null?s:t;return new Promise((o,c)=>{const d=(S,T)=>{a(this,Oe).removeListener(n,S),a(this,Oe).removeListener(Yg,T),a(this,Oe).removeListener(cr.errorResponse,T),a(this,Oe).removeListener(br.errorResponse,T)},l=i!=null?i:U(this,Hc,Du).call(this),h={};a(this,lt).getValue("telemetry").injectContext(h);const m=({id:S,payload:T})=>{if(l===S){let M;try{const b=tC.fromBinary(T);M=new Error(b.errorMessage)}catch(b){M=new Error("failed to parse error message",{cause:b});try{const R=rP.fromBinary(T);M=new Error(R.message)}catch(R){M=new Error("failed to parse error message",{cause:R})}}c(M),d(v,m)}},v=({id:S,payload:T})=>{l===S&&(o({id:S,payload:T}),d(v,m))};a(this,Oe).on(n,v),a(this,Oe).on(Yg,m),a(this,Oe).on(cr.errorResponse,m),a(this,Oe).on(br.errorResponse,m),setTimeout(()=>{d(v,m),c(new Error(`request timeout for callback eventId:${t}`))},e),a(this,Oe).send(t,l,r,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){a(this,Oe).on(t,e)}onStateEvent(t,e){a(this,Oe).on(t,e)}removeListener(t,e){a(this,Oe).removeListener(t,e)}removeListeners(t){a(this,Oe).removeListeners(t)}flush(){return a(this,Oe).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),a(this,mr)&&(clearTimeout(a(this,mr)),f(this,mr,void 0)),a(this,Ne,xe).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:s}=(r=a(this,Ne,xe).mediaState)!=null?r:{};i!=null&&i.state&&(i==null?void 0:i.state)!==ra.CONNECTED||s!=null&&s.state&&(s==null?void 0:s.state)!==ra.CONNECTED?a(this,lt).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ne,xe).joinAttempted}):f(this,mr,setTimeout(()=>{a(this,lt).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ne,xe).joinAttempted}),f(this,mr,void 0)},rN)),a(this,Ne,xe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge",{country:k.location.country}),a(this,Ne,xe).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,Ne,xe).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),a(this,Ne,xe).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Ne,xe).mediaJoinAttempted}}),a(this,mr)&&(clearTimeout(a(this,mr)),f(this,mr,void 0)),a(this,lt).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Ne,xe).mediaJoinAttempted}),a(this,Ne,xe).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,lt).getValue("peerSessionStore").emit(P.SOCKET_SERVICE_FAILED),a(this,Ne,xe).updateSocketConnectionState("failed")}))}},as=new WeakMap,Oe=new WeakMap,Ne=new WeakSet,xe=function(){return a(this,lt).getValue("connectionHandler")},mr=new WeakMap,lt=new WeakMap,jc=new WeakSet,Au=function(t){let e=qy.getSocketEdgeDomain(a(this,lt).getValue("baseURI"));typeof ea(a(this,lt),"socket_server_base")=="string"&&(e=ea(a(this,lt),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),s=this.peerId,n=q(V({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},s!==t&&{oldPeerID:s}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Qd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(n).forEach(([o,c])=>{i.searchParams.append(o,c.toString())}),i.href},Hc=new WeakSet,Du=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Qg);let lc=qy;Nl([k.trace("SocketService.connect")],lc.prototype,"connect",1);Nl([k.trace("SocketService.disconnect")],lc.prototype,"disconnect",1);Nl([k.trace("SocketService.sendMessagePromise")],lc.prototype,"sendMessagePromise",1);Nl([k.trace("SocketService.sendMessagePromiseWithTimeout")],lc.prototype,"sendMessagePromiseWithTimeout",1);class iN{constructor(e){p(this,"socketService"),this.socketService=e}handleConnectedRoomsDumpRaw({payload:e}){var r;const i=RP.fromBinary(e),s=i.meetings.map(n=>{var o;return{id:n.id,title:n.title,participants:(o=n.participants)!=null?o:[]}});return{parentMeeting:{id:i.parentMeeting.id,title:i.parentMeeting.title,participants:(r=i.parentMeeting.participants)!=null?r:[]},meetings:s}}handleTransferPeerRaw({payload:e}){const r=tR.fromBinary(e);return{authToken:r.authToken,meetingId:r.meetingId}}handleMovedPeerRaw({payload:e}){const r=Bv.fromBinary(e);return{meetingId:r.meetingId,customParticipantId:r.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:e}){return Fm.fromBinary(e).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:e}){return qP.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,OP.toBinary({payloads:e}));return Fm.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(s=>({id:s})),i=yield this.socketService.sendMessagePromise(F.deleteConnectedRooms,HP.toBinary({payloads:r}));return this.handleConnectedRoomsDeletedRaw(i)})}movePeersBetweenRooms(e){return u(this,null,function*(){try{const r=yield this.socketService.sendMessagePromise(F.movePeers,QP.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 sN=Object.defineProperty,nN=Object.getOwnPropertyDescriptor,aN=(t,e,r,i)=>{for(var s=i>1?void 0:i?nN(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&sN(e,r,s),s},xr;class $y extends Xt{constructor(e){const r=e.getValue("logger");super(r),p(this,"meetings",[]),p(this,"parentMeeting",null),g(this,xr,void 0),f(this,xr,e)}get supportsConnectedMeetings(){return a(this,xr).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,xr).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield a(this,xr).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(r=>({id:r.id,title:r.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield a(this,xr).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(s=>s.id)):Promise.resolve());return yield Promise.all(r),yield a(this,xr).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)})}moveParticipants(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction();const s=yield a(this,xr).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(n=>({id:n}))});return s.success&&this.moveSuccessHandler(e,r,i),s})}moveParticipantsWithCustomPreset(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction();const s=yield a(this,xr).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return s.success&&this.moveSuccessHandler(e,r,i.map(n=>n.id)),s})}moveSuccessHandler(e,r,i){const s=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(n=>n.participants)].forEach(n=>s.set(n.id,n)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(n=>s.get(n)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(n=>!i.includes(n.id))),this.meetings=this.meetings.map(n=>{if(r===n.id){const o=n.participants.concat(i.map(c=>s.get(c)));return q(V({},n),{participants:o})}if(e===n.id){const o=n.participants.filter(c=>!i.includes(c.id));return q(V({},n),{participants:o})}return n})}}xr=new WeakMap;aN([Bt({maxInvocations:60,period:60})],$y.prototype,"getConnectedMeetings",1);var oN=Object.defineProperty,cN=Object.getOwnPropertyDescriptor,Rp=(t,e,r,i)=>{for(var s=i>1?void 0:i?cN(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&oN(e,r,s),s},Te,Xg;const Jy=(Xg=class{constructor(t){p(this,"connectedMeetings"),g(this,Te,void 0),f(this,Te,t),this.connectedMeetings=new $y(t)}get telemetry(){return a(this,Te).getValue("telemetry")}get logger(){return a(this,Te).getValue("logger")}static init(t){const e=new Jy(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,s,n,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: ${(s=(i=a(this,Te).getValue("meeting"))==null?void 0:i.meta)==null?void 0:s.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${r}`);const d=yield zy.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: ${(n=d==null?void 0:d.meta)==null?void 0:n.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,Xg);let Vl=Jy;Rp([k.trace("ConnectedMeetingsController.getConnectedMeetings")],Vl.prototype,"getConnectedMeetings",1);Rp([k.trace("ConnectedMeetingsController.setupEvents")],Vl.prototype,"setupEvents",1);Rp([k.trace("ConnectedMeetingsController.switchMeeting")],Vl.prototype,"switchMeeting",1);var dN=Object.defineProperty,lN=Object.getOwnPropertyDescriptor,Ll=(t,e,r,i)=>{for(var s=i>1?void 0:i?lN(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&dN(e,r,s),s};const Ln=class{constructor(t,e,r){p(this,"apiBase"),p(this,"selfController"),p(this,"pollController"),p(this,"chatController"),p(this,"metaController"),p(this,"storesManager"),p(this,"stageController"),p(this,"pluginController"),p(this,"internalsController"),p(this,"recordingController"),p(this,"livestreamController"),p(this,"participantController"),p(this,"connectedMeetingsController"),p(this,"telemetry"),p(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:s,authToken:n,meetingId:o,organizationId:c,cachedUserDetails:d,logger:l}=t.getAllValues();if(Ry(t),Ie.isSupported()===!1)throw new I("Browser not supported","0010",l,!0);const h=pD(t,{authToken:n,baseURL:s,cachedUserDetails:d});h.setRoomName(o),h.setRoomUUID(o),h.setOrganizationId(c),h.setHeader("dyte-tracing-id",i),t.setValue("apiClient",h);const m=new zD(t);t.setValue("connectionHandler",m);const v=Ln.createSocketService(t),S=v.connect(),T=h.getUserDetails(),M=h.getPlugins();let b=Me.HIVE,R,j="";try{yield Ln.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 W=OO.init(R.preset,!t.getValue("modules").theme),w=e1.init(t,W.viewType,R.preset.permissions),te=Ln.setupControllers(v,t,R,M,j,W,w);UD(W)&&((e=Ln.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 te;return V0(),new Ln(s,re,t)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:r,baseURI:i,overrides:s,meetingId:n,organizationId:o,logger:c}=t.getAllValues(),d=N0(n),l=q(V({entity:Hu.PEER,clientId:o,isAnonUser:!o,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:d,roomName:n},Ie.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const h=(e=s==null?void 0:s.whitelabelled_flags_endpoint)==null||e?Ds({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,s,n,o){return u(this,null,function*(){var c,d,l;const h=e.getValue("modules"),{participant:m}=r,v=e.getValue("defaults"),S=e.getValue("logger"),{sfu:T}=e.getValue("roomNodeOptions"),{viewType:M,mediaConstraints:{audio:b}}=n;e.setValue("viewType",M),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()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let R,j,W,w,te,re,ae,Ae,Xe;const jt=new R1(e,t),A=new iN(t);e.setValue("connectedMeetingsSocketHandler",A);const E=new Dl(e,t),_=new dr(e,t),B=new V1(t),oe=new Ay(e,t),He=new L1(e,t),x=new P1(t),C=new Ls(e,t),ue=yield Ji.init(e,oe,m,o,n),Ki=yield Xv.init(e,ue.self,oe,jt,s);if(h.participant&&(Ae=new hi(e,ue.self,oe,T)),(l=h.e2ee)!=null&&l.enabled&&h.e2ee.manager.init(S,e.getValue("peerSessionStore")),h.chat&&(j=yield ai.init(e,_,C,ue.self,Ae.participants)),h.internals&&(te=yield vp.init(e)),h.livestream&&n.viewType===Ft.Livestream&&e.getValue("flagsmith").hasFeature(Z.LIVESTREAM)&&(ae=new oy(e,ue.self,x)),n.viewType!==Ft.Chat){if(h.poll&&(R=yield Kv.init(e,ue.self,E)),h.recording&&(re=new ry(e,ue.self,oe)),h.stage&&(W=new Zv(e,B,oe,ue.self,Ae.participants)),h.plugin){if(!Ae)throw new I("The plugin module cannot be initialized without the `participant` module","0102");const $r=yield i;w=yield ac.init(e,$r,He,_,j==null?void 0:j.chat,ue.self,Ae.participants,s)}if(h.connectedMeetings&&(Xe=yield Vl.init(e)),h.pip){const $r=yield U0._init(e,ue.self);e.setValue("pip",$r)}}const zi={storesManager:new WO(e,He),pollController:R,selfController:ue,metaController:Ki,chatController:j,stageController:W,pluginController:w,recordingController:re,internalsController:te,livestreamController:ae,participantController:Ae,connectedMeetingsController:Xe};return{theme:n,permissions:o,controllers:zi}})}static createRoomNodeClient(t,e){const{peerId:r,roomNodeOptions:i}=t.getAllValues(),{sfu:s}=i;return Py(t,s,{socket:e,peerId:r})}static createSocketService(t){const{peerId:e,meetingId:r,authToken:i}=t.getAllValues(),s=["PING"];return new lc(t,{peerId:e,meetingId:r,authToken:i,capabilities:s})}};let uc=Ln;Ll([k.trace("Controller.init")],uc,"init",1);Ll([k.trace("setupFlagsmith")],uc,"setupFlagsmith",1);Ll([k.trace("Controller.createRoomNodeClient")],uc,"createRoomNodeClient",1);Ll([k.trace("Controller.createSocketService")],uc,"createSocketService",1);class uN{constructor(){p(this,"battery"),p(this,"logger"),p(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)}})),p(this,"updateChargeInfo",()=>{var e;this.logger.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)}),p(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 Zg=new uN;function hN(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:s}=JSON.parse(atob(t.split(".")[1]));if(!r)throw Error(`Received V1 auth token ${t}`);let n="dyte.io";e&&(n=e);const o=`https://${Ds({servicePrefix:"rtk",baseURI:n})}`;return{meetingId:r,orgId:i,participantId:s,baseURI:n,apiBase:o}}catch{throw new I("Invalid auth token","0004")}}var Ts,xn,Un,ml,$h,Ky;class pN{constructor(){g(this,$h),g(this,Ts,new Audio),g(this,xn,new MediaStream),g(this,Un,new Map),g(this,ml,void 0),a(this,Ts).srcObject=a(this,xn),a(this,Ts).autoplay=!0}playTracks(e){return u(this,null,function*(){return e.forEach(r=>{a(this,Un).has(r.id)||(a(this,xn).addTrack(r),a(this,Un).set(r.id,r))}),this.play()})}setSpeakerDevice(e){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,Ts).setSinkId(e)}removeTrack(e){const r=a(this,Un).get(e);r&&(a(this,xn).removeTrack(r),a(this,Un).delete(e))}play(){return u(this,null,function*(){return a(this,Ts).srcObject=a(this,xn),a(this,Ts).play().catch(e=>{U(this,$h,Ky).call(this,e)})})}onError(e){f(this,ml,e)}}Ts=new WeakMap,xn=new WeakMap,Un=new WeakMap,ml=new WeakMap,$h=new WeakSet,Ky=function(t){var e;(e=a(this,ml))==null||e.call(this,t)};var Fn;class mN extends pN{constructor(){super(),g(this,Fn,void 0),f(this,Fn,new Map)}addParticipantTrack(e,r){a(this,Fn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,Fn).get(e);r&&this.removeTrack(r),a(this,Fn).delete(e)}}Fn=new WeakMap;var gN=Object.defineProperty,fN=Object.getOwnPropertyDescriptor,xl=(t,e,r,i)=>{for(var s=i>1?void 0:i?fN(e,r):e,n=t.length-1,o;n>=0;n--)(o=t[n])&&(s=(i?o(e,r,s):o(s))||s);return i&&s&&gN(e,r,s),s},et,os,ef;let Gi=(ef=class{constructor(t,e){g(this,et,void 0),g(this,os,void 0),f(this,os,t),f(this,et,e)}get peerId(){return a(this,os).getValue("peerId")}static initMedia(t={},e=!1,r=void 0){var i;const s=(i=r==null?void 0:r.peerId)!=null?i:Ns(),n=ni.createContext(s,{peerId:s}),o=n.getValue("logger");o.init(n);const c=new uy(o);return c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static init(t){return u(this,null,function*(){var e,r,i,s,n,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:Ns()),{authToken:h,baseURI:m}=t,v=hN(h,m),{meetingId:S}=v,T=vl(v,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const M=Gi.setupContext(l,t,S,T),b=M.getValue("telemetry"),R=M.getValue("logger");cE(R),Zg.init(R),b.init(M,{roomName:S,userId:T.participantId,organizationId:T.orgId,peerId:l},(n=(s=t.modules)==null?void 0:s.tracing)!=null?n:!0),R.init(M),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 uc.init(M),W=new Gi(M,j);return M.setValue("meeting",W),W})}static setupContext(t,e,r,i){var s,n;const o=ni.createContext(t,e),c=V(V({},I0),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",(s=e.overrides)!=null?s:{}),o.setValue("env",C0({baseURI:i.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",_r(e.cachedUserDetails)),o.setValue("sdkVersion","VERSION_PLACEHOLDER"),(n=e.modules)!=null&&n.experimentalAudioPlayback&&o.setValue("audioPlayback",new mN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,et);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Zg.cleanup(),a(this,os).getValue("peerSessionStore").reset(),(e=a(this,os).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:r}=a(this,et);return r.leaveRoom(t)})}get participants(){var t;return(t=a(this,et).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,et).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,et).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,et).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,et).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,et).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,et).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,et).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,et).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,et).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,et).stageController)==null?void 0:t.stage}get stores(){return a(this,et).storesManager}get audio(){return a(this,os).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,et).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)})}},et=new WeakMap,os=new WeakMap,ef);xl([gt("0002"),$i.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Gi.prototype,"join",1);xl([gt("0003")],Gi.prototype,"leave",1);xl([gt("0001"),$i.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Gi,"init",1);Gi=xl([gt("0000")],Gi);const zy=Gi;class vN{constructor(e){hc(this,"meeting");hc(this,"l");hc(this,"onUpdate",()=>{this.l.forEach(e=>{e()})});var r,i,s,n,o,c,d,l,h,m,v,S,T,M,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),(s=this.meeting.participants)==null||s.addListener("*",this.onUpdate),(o=(n=this.meeting.participants)==null?void 0:n.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),(m=this.meeting.stage)==null||m.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),(M=this.meeting.recording)==null||M.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,s,n,o,c,d,l,h,m,v,S,T,M,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),(n=(s=this.meeting.participants)==null?void 0:s.joined)==null||n.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),(m=this.meeting.livestream)==null||m.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),(M=this.meeting.connectedMeetings)==null||M.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 yN({value:t,children:e,fallback:r}){const[i,s]=Pt.useState(),n=Pt.useRef();return Pt.useEffect(()=>(t&&s(new vN(t)),()=>{var o;(o=n.current)==null||o.clean()}),[t]),Zy.default.createElement(Ul.Provider,{value:{meeting:t,updates:i}},t?e:r)}const SN=()=>{const{meeting:t}=Pt.useContext(Ul);if(!t)throw new Error("useDyteMeeting must be used within the DyteProvider");return{meeting:t}},EN=t=>{const e=Pt.useRef(!1),[r,i]=Pt.useState(),s=t==null?void 0:t.resetOnLeave,n=Pt.useCallback(async o=>{if(!e.current)return e.current=!0,zy.init(o).then(c=>(i(c),c)).finally(()=>{e.current=!1})},[]);return Pt.useEffect(()=>{if(!r||!s)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,n]},kN=(t,e)=>!!(t!==e||Array.isArray(t)&&Array.isArray(e)&&t.length!==e.length),TN=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)),[,s]=Pt.useReducer(n=>n+1,0);return Pt.useEffect(()=>{const n=e&&t(e),o=()=>{const c=e&&t(e);kN(i.current,c)&&(i.current=c,s())};return n&&typeof n=="object"&&"addListener"in n?(n.addListener("*",s),()=>{n.removeListener("*",s)}):(r==null||r.addListener(o),()=>{r==null||r.removeListener(o)})},[e,r]),i.current};exports.RealtimeKitContext=Ul;exports.RealtimeKitProvider=yN;exports.useRealtimeKitClient=EN;exports.useRealtimeKitMeeting=SN;exports.useRealtimeKitSelector=TN;
23
+ ${(c=t.authToken)==null?void 0:c.slice(-10)}`})});const j=yield uc.init(M),W=new Gi(M,j);return M.setValue("meeting",W),W})}static setupContext(t,e,r,i){var s,n;const o=ni.createContext(t,e),c=V(V({},I0),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",(s=e.overrides)!=null?s:{}),o.setValue("env",C0({baseURI:i.baseURI})),o.setValue("defaults",d),o.setValue("onError",e.onError||(()=>{})),o.setValue("cachedUserDetails",_r(e.cachedUserDetails)),o.setValue("sdkVersion","3.1.3-staging.3"),(n=e.modules)!=null&&n.experimentalAudioPlayback&&o.setValue("audioPlayback",new mN),o}join(){return u(this,null,function*(){const{selfController:t}=a(this,et);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){var e;Zg.cleanup(),a(this,os).getValue("peerSessionStore").reset(),(e=a(this,os).getValue("roomSocketHandler"))==null||e.cleanup();const{selfController:r}=a(this,et);return r.leaveRoom(t)})}get participants(){var t;return(t=a(this,et).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,et).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,et).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,et).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,et).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,et).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,et).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,et).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,et).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,et).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,et).stageController)==null?void 0:t.stage}get stores(){return a(this,et).storesManager}get audio(){return a(this,os).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,et).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)})}},et=new WeakMap,os=new WeakMap,ef);xl([gt("0002"),$i.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Gi.prototype,"join",1);xl([gt("0003")],Gi.prototype,"leave",1);xl([gt("0001"),$i.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Gi,"init",1);Gi=xl([gt("0000")],Gi);const zy=Gi;class vN{constructor(e){hc(this,"meeting");hc(this,"l");hc(this,"onUpdate",()=>{this.l.forEach(e=>{e()})});var r,i,s,n,o,c,d,l,h,m,v,S,T,M,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),(s=this.meeting.participants)==null||s.addListener("*",this.onUpdate),(o=(n=this.meeting.participants)==null?void 0:n.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),(m=this.meeting.stage)==null||m.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),(M=this.meeting.recording)==null||M.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,s,n,o,c,d,l,h,m,v,S,T,M,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),(n=(s=this.meeting.participants)==null?void 0:s.joined)==null||n.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),(m=this.meeting.livestream)==null||m.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),(M=this.meeting.connectedMeetings)==null||M.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 yN({value:t,children:e,fallback:r}){const[i,s]=Pt.useState(),n=Pt.useRef();return Pt.useEffect(()=>(t&&s(new vN(t)),()=>{var o;(o=n.current)==null||o.clean()}),[t]),Zy.default.createElement(Ul.Provider,{value:{meeting:t,updates:i}},t?e:r)}const SN=()=>{const{meeting:t}=Pt.useContext(Ul);if(!t)throw new Error("useDyteMeeting must be used within the DyteProvider");return{meeting:t}},EN=t=>{const e=Pt.useRef(!1),[r,i]=Pt.useState(),s=t==null?void 0:t.resetOnLeave,n=Pt.useCallback(async o=>{if(!e.current)return e.current=!0,zy.init(o).then(c=>(i(c),c)).finally(()=>{e.current=!1})},[]);return Pt.useEffect(()=>{if(!r||!s)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,n]},kN=(t,e)=>!!(t!==e||Array.isArray(t)&&Array.isArray(e)&&t.length!==e.length),TN=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)),[,s]=Pt.useReducer(n=>n+1,0);return Pt.useEffect(()=>{const n=e&&t(e),o=()=>{const c=e&&t(e);kN(i.current,c)&&(i.current=c,s())};return n&&typeof n=="object"&&"addListener"in n?(n.addListener("*",s),()=>{n.removeListener("*",s)}):(r==null||r.addListener(o),()=>{r==null||r.removeListener(o)})},[e,r]),i.current};exports.RealtimeKitContext=Ul;exports.RealtimeKitProvider=yN;exports.useRealtimeKitClient=EN;exports.useRealtimeKitMeeting=SN;exports.useRealtimeKitSelector=TN;