@cloudflare/realtimekit 0.5.0-staging.89 → 0.5.0-staging.90

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/browser.js CHANGED
@@ -16,7 +16,7 @@ ${this.message}`;try{let i=r;n&&n.endsWith("00")&&(i=!0),i&&p.error("DyteError",
16
16
  ${t}`}const rs={maxInvocations:5,period:1};function Nt(t,e){return function(n,r,i){const s=i.value;let a=0,c=Date.now();return i.value=function(...d){const l=Date.now(),h=e?this[e]:t;if(l-c>h.period*1e3&&(c=l,a=0),a>=h.maxInvocations)throw new _(`Method rate limit ${h.maxInvocations} invocations/${h.period}sec exceeded`,"0013");return a+=1,s.apply(this,d)},i}}var xD=Object.defineProperty,VD=Object.getOwnPropertyDescriptor,pt=(t,e,n,r)=>{for(var i=r>1?void 0:r?VD(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&xD(e,n,i),i};const UD=["text","image","file","custom","poll"],sd={maxInvocations:180,period:60};var se,is,ze,ss,ad,eh,Vv,od,th,Uv;let Ze=(Uv=class extends jt{constructor(t,e,n,r,i){super(),f(this,eh),f(this,od),g(this,"messages"),g(this,"channels",[]),f(this,se,void 0),f(this,is,void 0),f(this,ze,void 0),f(this,ss,void 0),f(this,ad,void 0),g(this,"maxTextLimit",2e3),v(this,ad,t),v(this,ze,e),v(this,ss,n),v(this,se,r),v(this,is,i),this.messages=[]}setMaxTextLimit(t){this.maxTextLimit=t}sendMessageInternal(t,e,n){return u(this,arguments,function*(r,i,s,a={}){switch(r.type){case"text":{const c=a.replyTo&&a.replyTo.type==="text"?LD(r.message,a.replyTo.message):r.message;yield this.sendTextMessageInternal(c,i,s);break}case"image":yield this.sendImageMessageInternal(r.image,i,s);break;case"file":yield this.sendFileMessageInternal(r.file,i,s);break;default:p.error("sendMessage::message_type_not_supported",{dyteChat:{messageType:r.type}});break}})}sendTextMessageInternal(t,e,n){return u(this,null,function*(){var r,i,s,a,c,d;if(t.length>this.maxTextLimit)throw new _("Max character limit breached","0503");if(e&&e.length>0){if(!((r=o(this,se).permissions)!=null&&r.chatPrivate.canSend)||!((i=o(this,se).permissions)!=null&&i.chatPrivate.text))throw p.error("sendTextMessage::private_chat_permission_denied"),new _("Could not send message to private chat.","0501")}else if(!((a=(s=o(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,se).permissions)==null?void 0:c.chatPublic)!=null&&d.text))throw p.error("sendTextMessage::public_chat_permission_denied"),new _("Could not send message to public chat.","0501");if(!t)throw p.error("sendTextMessage::message_can_not_be_empty"),new _("Message can not be empty.","0502");if(n){o(this,ze).sendMessageToChannel(t,Et.TEXT,n);return}let l=[];e&&e.length>0&&(e.push(o(this,se).id),l=o(this,is).joined.toArray().filter(h=>e.includes(h.id)).map(h=>h.userId),l.push(o(this,se).userId)),o(this,ze).sendMessage(t,Et.TEXT,e)})}sendImageMessageInternal(t,e,n){return u(this,null,function*(){var r,i,s,a,c,d;if(e&&e.length>0){if(!((r=o(this,se).permissions)!=null&&r.chatPrivate.canSend)||!((i=o(this,se).permissions)!=null&&i.chatPrivate.files)){p.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((a=(s=o(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,se).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){p.error("sendImageMessage::permission_denied");return}if(!t){p.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){p.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:t.type}});return}try{const l=ot(),{getLocation:h,putLocation:m}=yield l.getPresignedUrls(t.name,o(this,se).config.viewType);if(yield l.uploadFile(t,m),n){o(this,ze).sendMessageToChannel(h,Et.IMAGE,n);return}let y=[];e&&e.length>0&&(e.push(o(this,se).id),y=o(this,is).joined.toArray().filter(T=>e.includes(T.id)).map(T=>T.userId),y.push(o(this,se).userId)),o(this,ze).sendMessage(h,Et.IMAGE,e)}catch(l){throw new _("Error sending image message.","0500")}})}sendFileMessageInternal(t,e,n){return u(this,null,function*(){var r,i,s,a,c,d;if(e&&e.length>0){if(!((r=o(this,se).permissions)!=null&&r.chatPrivate.canSend)||!((i=o(this,se).permissions)!=null&&i.chatPrivate.files)){p.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((a=(s=o(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,se).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){p.error("sendFileMessage::permission_denied");return}if(!t){p.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const l=ot(),{getLocation:h,putLocation:m}=yield l.getPresignedUrls(t.name,o(this,se).config.viewType);if(yield l.uploadFile(t,m),n){o(this,ze).sendMessageToChannel(JSON.stringify({link:h,name:t.name,size:"size"in t?t.size:0}),Et.FILE,n);return}let y=[];e&&e.length>0&&(e.push(o(this,se).id),y=o(this,is).joined.toArray().filter(b=>e.includes(b.id)).map(b=>b.userId),y.push(o(this,se).userId));const T=JSON.stringify({link:h,name:t.name,size:"size"in t?t.size:0});o(this,ze).sendMessage(T,Et.FILE,e)}catch(l){throw new _("Error sending file message.","0500")}})}get rateLimits(){return sd}updateRateLimits(t,e){sd.maxInvocations=t,sd.period=e}sendTextMessage(t,e){return u(this,null,function*(){return this.sendTextMessageInternal(t,e)})}sendCustomMessage(t,e){return u(this,null,function*(){var n,r,i,s,a,c,d,l,h,m,y,T,b,O,M;if(e&&e.length>0){if(!((n=o(this,se).permissions)!=null&&n.chatPrivate.canSend)||!((r=o(this,se).permissions)!=null&&r.chatPrivate.files)||!((i=o(this,se).permissions)!=null&&i.chatPrivate.text)){p.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((a=(s=o(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,se).permissions)==null?void 0:c.chatPublic)!=null&&d.files)||!((h=(l=o(this,se).permissions)==null?void 0:l.chatPublic)!=null&&h.text)){p.error("sendCustomMessage::permission_denied");return}const F=K=>u(this,null,function*(){try{if(typeof K=="string")return{link:K};const I=ot(),{getLocation:Z,putLocation:ae}=yield I.getPresignedUrls(K.name,o(this,se).config.viewType);return yield I.uploadFile(K,ae),{link:Z,type:K.type,name:K.name,size:K.size}}catch(I){throw new _("Error sending image message.","0500")}}),V=G(x({},t),{files:yield Promise.all((y=(m=t.files)!=null?m:[])==null?void 0:y.map(K=>u(this,null,function*(){return F(K)}))),images:yield Promise.all((b=(T=t.images)!=null?T:[])==null?void 0:b.map(K=>u(this,null,function*(){return F(K)}))),videos:yield Promise.all((M=(O=t.videos)!=null?O:[])==null?void 0:M.map(K=>u(this,null,function*(){return F(K)})))});o(this,ze).sendMessage(JSON.stringify(V),Et.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,n){return u(this,null,function*(){var r,i,s,a,c,d;if(((i=(r=o(this,se).permissions)==null?void 0:r.chatMessage)==null?void 0:i.canEdit)==="NONE")throw new _("Not permitted to edit messages","0501");if(!((a=(s=o(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.canSend)||!((d=(c=o(this,se).permissions)==null?void 0:c.chatPublic)!=null&&d.text)){p.error("editTextMessage::permission_denied");return}if(!e){p.error("editTextMessage::message_can_not_be_empty");return}o(this,ze).editMessage(t,e,Et.TEXT,n)})}editImageMessage(t,e,n){return u(this,null,function*(){var r,i,s,a;if(!((i=(r=o(this,se).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((a=(s=o(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.files)){p.error("editImageMessage::permission_denied");return}if(!e){p.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){p.error("sendImageMessage::image_type_not_supported",{dyteChat:{imageType:e.type}});return}try{const c=ot(),{getLocation:d,putLocation:l}=yield c.getPresignedUrls(e.name,o(this,se).config.viewType);yield c.uploadFile(e,l),o(this,ze).editMessage(t,d,Et.IMAGE,n)}catch(c){throw new _("Error editing image message.","0500")}})}editFileMessage(t,e,n){return u(this,null,function*(){var r,i,s,a;if(!((i=(r=o(this,se).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((a=(s=o(this,se).permissions)==null?void 0:s.chatPublic)!=null&&a.files)){p.error("sendFileMessage::permission_denied");return}if(!e){p.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=ot(),{getLocation:d,putLocation:l}=yield c.getPresignedUrls(e.name,o(this,se).config.viewType);yield c.uploadFile(e,l),o(this,ze).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),Et.FILE,n)}catch(c){throw new _("Error editing file message.","0500")}})}editMessage(t,e,n){return u(this,null,function*(){switch(e.type){case"text":{this.editTextMessage(t,e.message,n);break}case"image":{this.editImageMessage(t,e.image,n);break}case"file":{this.editFileMessage(t,e.file,n);break}default:{p.error("editMessage::message_type_not_supported",{dyteChat:{messageType:e.type}});break}}})}deleteMessage(t,e){return u(this,null,function*(){var n,r;if(((r=(n=o(this,se).permissions)==null?void 0:n.chatMessage)==null?void 0:r.canDelete)==="NONE")throw new _("Not permitted to delete messages","0501");o(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(!o(this,od,th))throw new _("Can`t pin message without joining room","0505");if(!o(this,se).permissions.pinParticipant)throw new _("You do not have permission to pin messages.","0501");const e=this.messages.find(n=>n.id===t);if(e){o(this,ze).setPinState(e,!0);return}throw new _(`No message found with id: ${t}`,"0504")})}unpin(t){return u(this,null,function*(){if(!o(this,od,th))throw new _("Can`t unpin message without joining room","0505");if(!o(this,se).permissions.pinParticipant)throw new _("You do not have permission to unpin messages.","0501");const e=this.messages.find(n=>n.id===t);if(e){o(this,ze).setPinState(e,!1);return}throw new _(`No message found with id: ${t}`,"0504")})}getMessages(t,e,n,r=0,i=void 0){return u(this,null,function*(){const s=yield o(this,ze).getChatMessagesPaginated(t,e,n,r,i);return{messages:s.messages.map(a=>Zn.formatSocketServiceMessage(a)),next:s.next}})}createChannel(t,e){return u(this,arguments,function*(n,r,i={}){var s;const a=(s=o(this,se).permissions)==null?void 0:s.chatChannel;if(a){if(a.canCreate==="NONE")throw new _("Not permitted to create channels","0501");if(i.visibility==="public"&&!(a.canCreate==="PUBLIC"||a.canCreate==="ALL"))throw new _("Not permitted to create public channels","0501");if(i.visibility==="private"&&!(a.canCreate==="PRIVATE"||a.canCreate==="ALL"))throw new _("Not permitted to create private channels","0501")}if(!n||n.trim().length===0)throw new _("channel name cannot be empty.","0510");const c=[...new Set([...r,o(this,se).userId])];return yield o(this,ss).createChannel(n.trim(),c,i.displayPictureUrl,i.visibility,i.isDirectMessage)})}updateChannel(t,e){var n,r,i,s,a;const c=this.channels.find(h=>h.id===t),d=(n=o(this,se).permissions)==null?void 0:n.chatChannel;if(d){if(d.canUpdate==="NONE")throw new _("Not permitted to update channels","0501");if(c.visibility==="public"&&!(d.canUpdate==="PUBLIC"||d.canUpdate==="ALL"))throw new _("Not permitted to update public channels","0501");if(c.visibility==="private"&&!(d.canUpdate==="PRIVATE"||d.canUpdate==="ALL"))throw new _("Not permitted to update private channels","0501")}const l={memberIds:(r=e.memberIds)!=null?r:c.memberIds,displayName:(i=e.displayName)!=null?i:c.displayName,displayPictureUrl:(s=e.displayPictureUrl)!=null?s:c.displayPictureUrl,visibility:(a=e.visibility)!=null?a:c.visibility};return o(this,ss).updateChannel(t,l)}sendMessageToChannel(t,e){return u(this,arguments,function*(n,r,i={}){return this.sendMessageInternal(n,null,r,i)})}getChannelMembers(t){return u(this,null,function*(){return o(this,ss).getChannelMembers(t)})}searchMessages(t){return u(this,arguments,function*(e,n={}){if(!X.hasFeature(ie.FEAT_CHAT_SDK_SEARCH))throw new _("searchMessages is temporarily disabled!","0506");return(yield o(this,ze).searchMessages(e,n)).map(Zn.formatSocketServiceMessage)})}markLastReadMessage(t,e){return u(this,null,function*(){yield o(this,ze).markLastReadMessage(t,e);const n=this.channels.find(r=>r.id===t);if(n){const r=G(x({},n),{unreadCount:0});this.channels=this.channels.map(i=>i.id===t?r:i),this.emit("channelMessageUpdate",r)}})}get pinned(){return this.messages.filter(t=>t.pinned)}},se=new WeakMap,is=new WeakMap,ze=new WeakMap,ss=new WeakMap,ad=new WeakMap,eh=new WeakSet,Vv=function(){return o(this,ad).getValue("connectionHandler")},od=new WeakSet,th=function(){return o(this,eh,Vv).socketJoined===!0},Uv);pt([S.trace("DyteChat.sendTextMessage"),Nt(sd)],Ze.prototype,"sendTextMessage",1),pt([S.trace("DyteChat.sendImageMessage"),Nt({maxInvocations:20,period:60})],Ze.prototype,"sendImageMessage",1),pt([S.trace("DyteChat.sendFileMessage"),Nt({maxInvocations:20,period:60})],Ze.prototype,"sendFileMessage",1),pt([S.trace("DyteChat.sendMessage"),Nt({maxInvocations:180,period:60})],Ze.prototype,"sendMessage",1),pt([S.trace("DyteChat.editTextMessage")],Ze.prototype,"editTextMessage",1),pt([S.trace("DyteChat.editImageMessage")],Ze.prototype,"editImageMessage",1),pt([S.trace("DyteChat.editFileMessage")],Ze.prototype,"editFileMessage",1),pt([S.trace("DyteChat.editMessage")],Ze.prototype,"editMessage",1),pt([S.trace("DyteChat.deleteMessage")],Ze.prototype,"deleteMessage",1),pt([S.trace("DyteChat.createChannel")],Ze.prototype,"createChannel",1),pt([S.trace("DyteChat.updateChannel")],Ze.prototype,"updateChannel",1),pt([S.trace("DyteChat.sendMessageToChannel")],Ze.prototype,"sendMessageToChannel",1),pt([S.trace("DyteChat.getChannelMembers")],Ze.prototype,"getChannelMembers",1),pt([S.trace("DyteChat.searchMessages")],Ze.prototype,"searchMessages",1),pt([S.trace("DyteChat.markLastReadMessage")],Ze.prototype,"markLastReadMessage",1),Ze=pt([ht("0500")],Ze);var FD=Object.defineProperty,BD=Object.getOwnPropertyDescriptor,WD=(t,e,n,r)=>{for(var i=r>1?void 0:r?BD(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&FD(e,n,i),i},nh,Fv;const di=(Fv=class{constructor(t,e,n,r,i){g(this,"chat"),g(this,"chatSocketHandler"),g(this,"chatChannelSocketHandler"),g(this,"self"),f(this,nh,void 0),v(this,nh,t),this.chatSocketHandler=e,this.chatChannelSocketHandler=n,this.chat=new Ze(t,e,n,r,i),this.self=r,this.setupEvents()}static init(t,e,n,r,i){return u(this,null,function*(){return new di(t,e,n,r,i)})}static formatMessage(t){return G(x({},t),{time:new Date(t.time),type:UD[t.type]})}static formatSocketServiceMessage(t){const e=t.createdAt*1e3,n={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(n.type){case Et.TEXT:{n.message=t.payload;break}case Et.IMAGE:{n.link=t.payload;break}case Et.FILE:{const{link:r,name:i,size:s}=JSON.parse(t.payload);n.link=r,n.name=i,n.size=s;break}case Et.CUSTOM:{const{html:r,images:i,message:s,videos:a,files:c}=JSON.parse(t.payload);n.message=s,n.html=r,n.images=i,n.videos=a,n.files=c;break}}return di.formatMessage(n)}getChatMessages(){return u(this,null,function*(){if(this.self.config.viewType==="LIVESTREAM"||this.self.config.viewType==="CHAT"||X.hasFeature(ie.FEAT_PAGINATED_CHAT))return;const t=yield this.chatSocketHandler.getChatMessages();if(!(t!=null&&t.payload))return;const e=kv.fromBinary(t.payload).messages;this.chat.messages=e.map(n=>di.formatSocketServiceMessage(n))})}setupEvents(){P.on(R.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){this.getChatMessages()})),this.chatSocketHandler.on(Oe.sendMessageToRoom,t=>{const e=di.formatSocketServiceMessage(t.message);if(!e.channelId)this.chat.messages=[...this.chat.messages,e];else{const n=this.chat.channels.find(r=>r.id===e.channelId);n&&(n.latestMessage=e,n.unreadCount+=1,this.chat.emit("channelMessageUpdate",n))}this.chat.emit("chatUpdate",{action:"add",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Oe.sendMessageToPeers,t=>{const e=di.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(Oe.editMessage,t=>{const e=di.formatSocketServiceMessage(t.message);if(e.channelId){this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages});return}const n=this.chat.messages.findIndex(r=>r.id===e.id);n!==-1&&(this.chat.messages[n]=e,this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}))}),this.chatSocketHandler.on(Oe.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(r=>r.id===t.chatId);if(e===-1)return;const[n]=this.chat.messages.splice(e,1);this.chat.emit("chatUpdate",{action:"delete",message:n,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(ai.createChatChannel,t=>{const[e]=t.chatChannels,n=ci.formatChannel(e);this.chat.channels.push(n),this.chat.emit("channelCreate",n)}),this.chatSocketHandler.on(Oe.pinMessage,t=>{const e=this.chat.messages.findIndex(r=>r.id===t.chatId);if(e===-1)return;const n=this.chat.messages[e];n.pinned=t.pinned,this.chat.messages[e]=n,this.chat.emit("chatUpdate",{action:"edit",message:n,messages:this.chat.messages})}),this.chatChannelSocketHandler.on(ai.updateChatChannel,t=>{const[e]=t.chatChannels,n=ci.formatChannel(e);this.chat.channels=this.chat.channels.map(r=>r.id===n.id?n:r),this.chat.emit("channelUpdate",n)})}},nh=new WeakMap,Fv);let Zn=di;WD([S.trace("ChatController.setupEvents")],Zn.prototype,"setupEvents",1);var jD=Object.defineProperty,HD=Object.getOwnPropertyDescriptor,qD=(t,e,n,r)=>{for(var i=r>1?void 0:r?HD(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&jD(e,n,i),i},rh,Bv,ih,Wv,pa,ma,cd,jv;let sh=(jv=class extends jt{constructor(t,e,n){super(),f(this,rh),f(this,ih),g(this,"items"),f(this,pa,void 0),f(this,ma,void 0),f(this,cd,void 0),v(this,cd,t),v(this,pa,e),v(this,ma,n),this.items=[]}create(t,e,n=!1,r=!1){return u(this,null,function*(){if(!o(this,ih,Wv))throw new _("Can't create polls without joining room","0705");if(!o(this,pa).permissions.polls.canCreate){p.error("DytePolls::create::permission_denied");return}if(!t||!e){p.error("DytePolls::question_and_options_can_not_be_empty",{dytePolls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){p.error("DytePolls::there_must_be_at_least_two_options",{dytePolls:{hasQuestion:!!t,optionsLength:e.length}});return}yield o(this,ma).createPoll(t,e,n,r)})}vote(t,e){return u(this,null,function*(){if(!o(this,pa).permissions.polls.canVote){p.error("DytePolls::vote::permission_denied");return}yield o(this,ma).votePoll(t,e)})}},rh=new WeakSet,Bv=function(){return o(this,cd).getValue("connectionHandler")},ih=new WeakSet,Wv=function(){var t;return((t=o(this,rh,Bv))==null?void 0:t.socketJoined)===!0},pa=new WeakMap,ma=new WeakMap,cd=new WeakMap,jv);sh=qD([ht("0700")],sh);var GD=Object.defineProperty,JD=Object.getOwnPropertyDescriptor,$D=(t,e,n,r)=>{for(var i=r>1?void 0:r?JD(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&GD(e,n,i),i},ga,as,Hv;const os=(Hv=class{constructor(t,e,n){g(this,"polls"),f(this,ga,void 0),f(this,as,void 0),this.polls=new sh(t,e,n),v(this,ga,e),v(this,as,n),this.setupEvents()}static init(t,e,n){return u(this,null,function*(){return new os(t,e,n)})}canViewPolls(){return o(this,ga).permissions.polls.canView}setupEvents(){const t={[Xn.createPoll]:r=>{r.poll&&this.updatePoll(os.formatSocketServicePoll(r.poll))},[Xn.updatePoll]:r=>{r.poll&&this.updatePoll(os.formatSocketServicePoll(r.poll))},[Xn.votePoll]:r=>{r.poll&&this.updatePoll(os.formatSocketServicePoll(r.poll))}},e=()=>{P.on(R.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(r=>{o(this,as).on(r,t[r])})},n=()=>{P.on(R.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(t).map(Number).forEach(r=>{o(this,as).removeListeners(r)})};o(this,ga).permissions.on("permissionsUpdate",r=>u(this,null,function*(){var i;(i=r==null?void 0:r.polls)!=null&&i.canView?(yield this.getPolls(),e()):(this.polls.items=[],n())})),this.canViewPolls()&&e()}updatePoll(t){if(!this.canViewPolls())return;const e=this.polls.items.findIndex(n=>n.id===t.id);if(e>-1){const n=JSON.stringify(this.polls.items[e]);this.polls.items[e]=t,n!==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 o(this,as).getPolls();if(!(t!=null&&t.payload))return;const{polls:e}=iD.fromBinary(t.payload);this.polls.items=e.map(n=>os.formatSocketServicePoll(n))})}static formatSocketServicePoll(t){const e=t.options.map(n=>({count:n.count,text:n.text,votes:n.votes.map(r=>({id:r.userId,name:r.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}}},ga=new WeakMap,as=new WeakMap,Hv);let qv=os;$D([S.trace("PollController.setupEvents")],qv.prototype,"setupEvents",1);var KD=Object.defineProperty,zD=Object.getOwnPropertyDescriptor,YD=(t,e,n,r)=>{for(var i=r>1?void 0:r?zD(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&KD(e,n,i),i},Gv=(t=>(t[t.User=0]="User",t[t.Meeting=1]="Meeting",t))(Gv||{}),fa,dd,ah,cs,ld,Jv;let oh=(Jv=class extends jt{constructor(t,e,n,r,i){super(),f(this,dd),g(this,"selfActiveTab"),g(this,"broadcastTabChanges"),f(this,fa,void 0),f(this,cs,void 0),f(this,ld,void 0),g(this,"viewType"),g(this,"meetingStartedTimestamp"),g(this,"meetingTitle"),g(this,"sessionId"),v(this,fa,t),v(this,cs,e),this.viewType=n,v(this,ld,r),this.meetingTitle=i,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return o(this,dd,ah).socketState}get mediaState(){return o(this,dd,ah).mediaState}get meetingId(){return o(this,fa).getValue("meetingId")}setBroadcastTabChanges(t){if(!o(this,cs).permissions.canSpotlight)throw p.error("DyteSpotlight::setSpotlighted::permission_denied"),new _("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 n;p.info("DyteSpotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(n=o(this,cs).permissions)!=null&&n.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){o(this,ld).broadcastMessage("spotlight",{userId:o(this,cs).userId,currentTab:this.selfActiveTab})}},fa=new WeakMap,dd=new WeakSet,ah=function(){return o(this,fa).getValue("connectionHandler")},cs=new WeakMap,ld=new WeakMap,Jv);oh=YD([ht("0800")],oh);function QD(t){let e="",n=[""];const r=[n];let i=0,s=0,a=!0,c;for(c of t)c==='"'?(a&&c===e&&(n[i]+=c),a=!a):c===","&&a?c=n[++i]="":c===`
17
17
  `&&a?(e==="\r"&&(n[i]=n[i].slice(0,-1)),n=r[++s]=[c=""],i=0):n[i]+=c,e=c;return r}var XD=Object.defineProperty,ZD=Object.getOwnPropertyDescriptor,$v=(t,e,n,r)=>{for(var i=r>1?void 0:r?ZD(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&XD(e,n,i),i};let kr=class extends jt{constructor(){super(),g(this,"transcripts"),this.transcripts=[]}static init(t){return u(this,null,function*(){const e=new kr;try{t&&e.getActiveTranscript()}catch(n){p.error("Error fetching active transcriptions ",n)}return e})}static parseTranscript(t,e=!1){try{if(!t)return;const[[n,r,i,s,a,c]]=QD(t);return{id:Gi(),name:a,peerId:r,userId:i,customParticipantId:s,transcript:c,isPartialTranscript:e,date:new Date(parseInt(n,10)*1e3)}}catch(n){p.error(`Failed to parse transcript: ${t}`,n);return}}static parseTranscripts(t){return t?t.split(`
18
18
  `).map(e=>kr.parseTranscript(e,!1)).filter(Boolean):[]}getActiveTranscript(){return u(this,null,function*(){try{const t=ot(),{transcript:e}=yield t.getActiveTranscript();this.transcripts=kr.parseTranscripts(e)}catch(t){}})}onTranscript(t){return u(this,null,function*(){var e;const n=this.transcripts.filter(({peerId:r})=>r===t.peerId);if((e=n==null?void 0:n.at(-1))!=null&&e.isPartialTranscript){const r=n.at(-1);r.transcript=t.transcript,r.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",r);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)})}};$v([S.trace("DyteAi.getActiveTranscript")],kr.prototype,"getActiveTranscript",1),kr=$v([ht("0000")],kr);var eO=Object.defineProperty,tO=Object.getOwnPropertyDescriptor,nO=(t,e,n,r)=>{for(var i=r>1?void 0:r?tO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&eO(e,n,i),i},li,va,ch,Kv;const zv=(Kv=class{constructor(t,e,n,r,i,s){g(this,"meta"),g(this,"ai"),f(this,li,void 0),f(this,va,void 0),g(this,"aiSocketHandler"),f(this,ch,void 0),v(this,ch,t),this.meta=new oh(t,e,e.config.viewType,n,s),this.ai=r,v(this,li,e),v(this,va,n),this.aiSocketHandler=i,e.config.viewType!==yt.Chat&&this.setupEvents()}static init(t,e,n,r,i){return u(this,null,function*(){const s=yield kr.init(e.permissions.transcriptionEnabled);return new zv(t,e,n,s,r,i)})}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,Gv.Meeting),this.meta.emit("activeTabUpdate",t.currentTab))}setupEvents(){P.on(R.TRANSPORT_STATE_UPDATE,t=>{this.meta.emit("mediaConnectionUpdate",t)}),P.on(R.SOCKET_STATE_UPDATE,t=>{this.meta.emit("socketConnectionUpdate",t)}),P.on(R.ROOM_STATE,({createdAt:t,roomUuid:e})=>{const n=this.meta.meetingStartedTimestamp;if(e&&(this.meta.sessionId=e),t&&!n){const r=new Date(t*1e3);this.meta.meetingStartedTimestamp=r,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),P.on(R.PRODUCER_SCORE_UPDATE,({score:t})=>{t<5&&this.meta.emit("poorConnection",{score:t})}),o(this,li).permissions.canSpotlight&&(p.info("DyteMetaController::Asserting Spotlight"),this.meta.selfActiveTab&&o(this,va).broadcastMessage("spotlight",{userId:o(this,li).userId,currentTab:this.meta.selfActiveTab})),P.on(R.PEER_JOINED_INTERNAL,t=>u(this,null,function*(){o(this,li).permissions.canSpotlight&&this.meta.selfActiveTab&&o(this,va).broadcastToPeers("spotlight",[t.id],{userId:o(this,li).userId,currentTab:this.meta.selfActiveTab})})),P.on(R.ROOM_MESSAGE,t=>{var e,n;let r;if("type"in t){if(t.type!=="spotlight")return;r=x(x({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;r=t}else return;p.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:r.userId},currentTab:{id:(e=r.currentTab)==null?void 0:e.id,type:(n=r.currentTab)==null?void 0:n.type}}}),this.conditionallySetActiveTab(r)}),P.on(R.MESSAGE,t=>{var e,n;let r;if("type"in t){if(t.type!=="spotlight")return;r=x(x({},t),t.payload)}else if("roomMessageType"in t){if(t.roomMessageType!=="spotlight")return;r=t}else return;p.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:r.userId},currentTab:{id:(e=r.currentTab)==null?void 0:e.id,type:(n=r.currentTab)==null?void 0:n.type}}}),this.conditionallySetActiveTab(r)}),this.aiSocketHandler.on(W.transcript,t=>{const{meetingId:e,transcript:n,isPartial:r}=t,i=kr.parseTranscript(n,r);if(!i){p.warn("Received empty transcript data");return}this.ai.onTranscript(i),this.meta.emit("transcript",i);const{peerId:s,name:a,transcript:c}=i;p.debug(`${e} Received transcript for peer ${s} - ${a}: ${c}`)})}},li=new WeakMap,va=new WeakMap,ch=new WeakMap,Kv);let Yv=zv;nO([S.trace("MetaController.setupEvents")],Yv.prototype,"setupEvents",1);var rO=Object.defineProperty,iO=Object.getOwnPropertyDescriptor,ui=(t,e,n,r)=>{for(var i=r>1?void 0:r?iO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&rO(e,n,i),i},fn,ya,pe,ud,er,xn,hd,dh,Sa,pd;class br extends jt{constructor(e,n,r,i,s){super(),f(this,hd),f(this,Sa),f(this,fn,void 0),f(this,ya,void 0),f(this,pe,void 0),f(this,ud,void 0),f(this,er,void 0),f(this,xn,void 0),v(this,xn,e),v(this,fn,i),v(this,ya,s),v(this,pe,n),v(this,ud,r),v(this,er,[]),this.setupEvents()}get status(){return o(this,xn).getValue("stageStatus")}setupEvents(){const e={[R.GET_STAGE_REQUESTS]:i=>u(this,null,function*(){v(this,er,i)}),[R.UPDATE_STAGE_REQUESTS]:i=>u(this,[i],function*({add:s}){const a=o(this,er).length,{stageRequests:c}=this.getAccessRequests();(s||c.length>a)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)})},n=()=>{Object.entries(e).forEach(([i,s])=>{P.onAsync(i,s)})},r=()=>{Object.entries(e).forEach(([i,s])=>{P.removeListener(i,s)})};o(this,pe).permissions.on("permissionsUpdate",i=>{const{canAcceptProductionRequests:s}=i;s!==void 0&&(o(this,pe).permissions.acceptStageRequests?(n(),o(this,fn).getStageRequests()):(r(),v(this,er,[]),this.emit("stageAccessRequestUpdate",o(this,er))))}),o(this,pe).permissions.acceptStageRequests&&n()}getAccessRequests(){if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");if(!o(this,pe).permissions.acceptStageRequests)throw p.error("DyteStage::get_access_request::permission_denied"),new _("You do not have permission to perform this action","2001");const e=o(this,ud).joined.toArray().filter(n=>n.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(n=>({displayName:n.name,userId:n.userId,peerId:n.id}));return v(this,er,e),{stageRequests:o(this,er)}}requestAccess(){return u(this,null,function*(){if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new _(`Unable to request access you are currently ${this.status}`,"2006");if(o(this,pe).permissions.stageAccess===Y.Allowed){H(this,Sa,pd).call(this,"ACCEPTED_TO_JOIN_STAGE");return}o(this,fn).requestAccess(),H(this,Sa,pd).call(this,"REQUESTED_TO_JOIN_STAGE")})}cancelRequestAccess(){return u(this,null,function*(){if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");o(this,fn).cancelRequestAccess(),H(this,Sa,pd).call(this,"OFF_STAGE")})}grantAccess(e){if(!o(this,pe).roomJoined)throw new _("Can`t grant for participant without joining room");if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");if(!o(this,pe).permissions.acceptStageRequests)throw p.error("DyteStage::grant_access::permission_denied"),new _("You do not have permission to perform this action","2001");return o(this,fn).grantAccess(e)}denyAccess(e){if(!o(this,pe).roomJoined)throw new _("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");if(!o(this,pe).permissions.acceptStageRequests)throw p.error("DyteStage::deny_access::permission_denied"),new _("You do not have permission to perform this action","2001");return o(this,fn).denyAccess(e)}join(){return u(this,null,function*(){const e=o(this,xn).getValue("viewType");if(this.status==="ON_STAGE")throw new _("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||o(this,pe).permissions.stageAccess===Y.NotAllowed)throw new _(`Unable to join stage you are currently ${this.status}`,"2006");if(yield o(this,fn).joinStage(),e===yt.Livestream){yield o(this,ya).joinRoom(o(this,pe));const{peers:n}=yield o(this,ya).getStagePeers();P.emit(R.SOCKET_PEERS,n)}o(this,xn).setValue("stageStatus","ON_STAGE"),o(this,pe).audioEnabled&&o(this,hd,dh).shareMic(o(this,pe).audioTrack),o(this,pe).videoEnabled&&o(this,hd,dh).shareWebcam(o(this,pe).videoTrack)})}leave(){return u(this,null,function*(){if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new _(`Unable to leave stage you are currently ${this.status}`,"2006");o(this,pe).setIsPinned(!1),yield o(this,fn).leaveStage(o(this,pe).userId),o(this,xn).setValue("stageStatus","OFF_STAGE",!1),yield P.emitAsync(R.LEAVE_MEDIA_ROOM,"stageLeft"),o(this,xn).notify("stageStatus")})}kick(e){return u(this,null,function*(){if(!o(this,pe).roomJoined)throw new _("Can`t kick participant without joining room","2005");if(!o(this,pe).permissions.stageEnabled)throw p.error("DyteStage::stage_disabled"),new _("Stage is disabled","2003");if(!o(this,pe).permissions.acceptStageRequests)throw p.error("DyteStage::kick::permission_denied"),new _("You do not have permissions for kick","2001");return o(this,fn).kick(e)})}}fn=new WeakMap,ya=new WeakMap,pe=new WeakMap,ud=new WeakMap,er=new WeakMap,xn=new WeakMap,hd=new WeakSet,dh=function(){return o(this,xn).getValue("roomNodeClient")},Sa=new WeakSet,pd=function(t){return u(this,null,function*(){this.status!==t&&o(this,xn).setValue("stageStatus",t)})},ui([S.trace("DyteStage.getStageRequests")],br.prototype,"getAccessRequests",1),ui([S.trace("DyteStage.requestAccess")],br.prototype,"requestAccess",1),ui([S.trace("DyteStage.cancelRequestAccess")],br.prototype,"cancelRequestAccess",1),ui([S.trace("DyteStage.grantAccess")],br.prototype,"grantAccess",1),ui([S.trace("DyteStage.denyAccess")],br.prototype,"denyAccess",1),ui([S.trace("DyteStage.joinStage")],br.prototype,"join",1),ui([S.trace("DyteStage.leaveStage")],br.prototype,"leave",1);function sO(t){return!(t.viewType==="LIVESTREAM"||t.viewType==="CHAT")}function lh(t){switch(t){case Yn.UNSPECIFIED:return"OFF_STAGE";case Yn.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Yn.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Yn.OFF_STAGE:return"OFF_STAGE";case Yn.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var aO=Object.defineProperty,oO=Object.getOwnPropertyDescriptor,cO=(t,e,n,r)=>{for(var i=r>1?void 0:r?oO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&aO(e,n,i),i},hi,ds,pi,md,wr;class Qv{constructor(e,n,r,i,s){g(this,"stage"),f(this,hi,void 0),f(this,ds,void 0),f(this,pi,void 0),f(this,md,0),f(this,wr,void 0),v(this,wr,e),this.stage=new br(e,i,s,n,r),v(this,pi,n),v(this,hi,i),v(this,ds,s),this.setupEvents()}setupEvents(){o(this,wr).subscribe("stageStatus",e=>{this.stage.emit("stageStatusUpdate",e)}),o(this,pi).on(W.grantStageAccess,()=>{o(this,hi).permissions.stageAccess!==Y.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),o(this,pi).on(W.peerStageStatusUpdate,e=>{e!==void 0&&(e.peerId===o(this,hi).id?this.selfStageStatusHandler(e):this.peerStageStatusHandler(e))}),o(this,pi).on(W.denyStageAccess,()=>{o(this,hi).permissions.stageAccess!==Y.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),o(this,pi).on(W.getStageRequests,e=>u(this,null,function*(){var n;if(o(this,hi).permissions.stageAccess!==Y.Allowed)return;const r=(n=e==null?void 0:e.stageRequests)!=null?n:[];yield P.emitAsync(R.GET_STAGE_REQUESTS,r),o(this,md)<r.length&&r.length>0&&this.stage.emit("newStageRequest",{count:r.length}),v(this,md,r.length),this.stage.emit("stageAccessRequestUpdate",r)}))}getCurrentStageRequests(){return o(this,ds).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}setStageStatus(e){return u(this,null,function*(){this.stage.status!==e&&o(this,wr).setValue("stageStatus",e)})}selfStageStatusHandler(e){const n=lh(e.stageType),r=o(this,wr).getValue("stageStatus");if(r!==n)switch(e.stageType){case 1:o(this,wr).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:o(this,wr).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}peerStageStatusHandler(e){return u(this,null,function*(){const n=o(this,ds).joined.get(e.peerId),r=o(this,ds).viewMode==="ACTIVE_GRID";if(!n){p.warn("err::peerStageStatusUpdate: participant not found");return}switch(e.stageType){case 1:n.setStageStatus("ON_STAGE"),r&&P.emit(R.UPDATE_ACTIVE);break;case 2:n.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:n.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:n.setStageStatus("OFF_STAGE"),r&&P.emit(R.UPDATE_ACTIVE);break}P.emit(R.UPDATE_PEER_STAGE_STATUS,{id:n.id,status:n.stageStatus})})}}hi=new WeakMap,ds=new WeakMap,pi=new WeakMap,md=new WeakMap,wr=new WeakMap,cO([S.trace("DyteStage.setupEvents")],Qv.prototype,"setupEvents",1);var dO=Object.defineProperty,lO=Object.getOwnPropertyDescriptor,gd=(t,e,n,r)=>{for(var i=r>1?void 0:r?lO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&dO(e,n,i),i};const Le={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};var kt,rn,Ea,Ta,_r,ka,ls,ba,Xv;let us=(Xv=class extends es{constructor(t,{baseURL:e,createdAt:n,description:r,id:i,name:s,organizationId:a,picture:c,private:d,published:l,staggered:h,tags:m,type:y,updatedAt:T},b,O,M,F,V){super(),f(this,kt,void 0),g(this,"baseURL"),g(this,"createdAt"),g(this,"description"),g(this,"id"),g(this,"name"),f(this,rn,void 0),f(this,Ea,void 0),f(this,Ta,void 0),g(this,"organizationId"),g(this,"picture"),g(this,"private"),g(this,"published"),g(this,"staggered"),g(this,"tags"),g(this,"type"),g(this,"updatedAt"),f(this,_r,void 0),g(this,"config"),f(this,ka,void 0),g(this,"active"),g(this,"iframes"),g(this,"enabledBy"),f(this,ls,void 0),f(this,ba,void 0),v(this,ls,t),this.baseURL=e,this.createdAt=new Date(n),this.description=r,this.id=i,this.name=s,v(this,rn,O),this.organizationId=a,this.picture=c,this.private=d,this.published=l,this.staggered=h,this.tags=m,this.type=y,this.updatedAt=new Date(T),this.active=!1,this.iframes=new Map,v(this,kt,b),v(this,Ea,M),v(this,Ta,F),this.enabledBy="",v(this,ba,V)}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:n}=e;n&&(navigator.isReactNative?n.postMessage(JSON.stringify(t)):n.contentWindow.postMessage(t,"*"))})}handleIframeMessage(t){return u(this,null,function*(){var e;if(!this.active)return;const n=t,{payload:r,uuid:i,type:s}=n;switch(s){case z.customPluginEventToRoom:{o(this,kt).customPluginEventToRoom(this.id,r,i);break}case z.customPluginEventToPeers:{o(this,kt).customPluginEventToPeers(this.id,r.peerIds,r,i);break}case z.enablePluginForRoom:{o(this,kt).enablePluginForRoom(this.id,i);break}case z.enablePluginForPeers:{o(this,kt).enablePluginForPeers(this.id,r.peerIds,i);break}case z.disablePluginForRoom:{o(this,kt).disablePluginForRoom(this.id,i);break}case z.disablePluginForPeers:{o(this,kt).disablePluginForPeers(this.id,r.peerIds,i);break}case z.storeInsertKeys:{o(this,kt).storeInsertKeys(this.id,r.store,r.insertKeys,i);break}case z.storeGetKeys:{o(this,kt).storeGetKeys(this.id,r.store,r.getKeys,i);break}case z.storeDeleteKeys:{o(this,kt).storeDeleteKeys(this.id,r.store,r.deleteKeys,i);break}case z.storeDelete:{o(this,kt).storeDelete(this.id,r.store,i);break}case Le.chatMessage:{const{messagePayload:a,peerIds:c}=r;if(!o(this,Ta)){this.sendIframeEvent({type:Le.chatMessage,uuid:n.uuid,payload:{error:"Chat is disabled for this room."}});return}try{yield o(this,Ta).sendMessage(a,c),this.sendIframeEvent({type:Le.chatMessage,uuid:n.uuid,payload:{success:!0}})}catch(d){this.sendIframeEvent({type:Le.chatMessage,uuid:n.uuid,payload:{error:d}})}break}case Le.getPeer:{let a;const{peerId:c}=r,d=G(x({},o(this,rn)),{id:o(this,rn).id,isRecorder:(e=o(this,rn).permissions)==null?void 0:e.isRecorder,isHidden:o(this,rn).permissions.hiddenParticipant,stageStatus:o(this,rn).stageStatus});c?(a=o(this,Ea).joined.get(r.peerId),o(this,rn).id===c&&(a=d)):a=d,this.sendIframeEvent({type:Le.getPeer,payload:{peer:a&&id(a)},uuid:n.uuid});break}case Le.getPeers:{const a=o(this,Ea).joined.toArray().map(c=>id(c));this.sendIframeEvent({type:Le.getPeers,payload:{peers:a},uuid:n.uuid});break}case Le.getPluginInitiator:{this.sendIframeEvent({type:Le.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:n.uuid});break}case Le.getDisplayTitle:{this.sendIframeEvent({type:Le.getDisplayTitle,payload:{displayTitle:o(this,ba)},uuid:n.uuid});break}case Le.getRoomName:{this.sendIframeEvent({type:Le.getRoomName,payload:{roomName:o(this,ls).getValue("meetingId")},uuid:n.uuid});break}case Le.customPluginEventToParent:{this.emit(n.payload.eventName,n.payload.data);break}}})}sendData(t){this.active&&(p.info("DytePlugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Le.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var e;const{iframe:n,listener:r}=(e=this.iframes.get(t))!=null?e:{};(n||r)&&(navigator.isReactNative?n.props.onMessage=void 0:window.removeEventListener("message",r),this.iframes.delete(t))}addPluginView(t,e="default"){var n;if(!o(this,ka))throw p.error("DytePlugin::addPluginView::no_auth_token_set_for_plugin"),new _("No auth token set for plugin.","0602");if(!t)throw p.error("DytePlugin::addPluginView::iframe_was_not_provided"),new _("Iframe was not provided.","0603");this.removePluginView(e);const r=t,i=new URL(this.baseURL),s={auth:o(this,ka),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:o(this,ls).getValue("apiBase"),pluginId:this.id,roomName:(n=o(this,ls).getValue("meetingId"))!=null?n:"",displayTitle:o(this,ba)};if(Object.keys(s).forEach(a=>{i.searchParams.set(a,s[a])}),r.src=i.href,r.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",r.title=e,navigator.isReactNative)r.props.onMessage=a=>{this.handleIframeMessage(JSON.parse(a.nativeEvent.data))},this.iframes.set(e,{iframe:r});else{const a=c=>u(this,null,function*(){c.source===t.contentWindow&&(yield this.handleIframeMessage(c.data))});window.addEventListener("message",a),this.iframes.set(e,{iframe:r,listener:a})}}setActive(t){var e,n;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(n=this.config)==null?void 0:n.views})}activateForSelf(){return u(this,null,function*(){const t=ot(),e=yield t.authorizePlugin(this.id);v(this,ka,e),v(this,_r,new Date);try{const n=yield t.getPluginConfig(this.baseURL);this.config=n}catch(n){p.error("DytePlugin::activateForSelf",{error:n})}this.setActive(!0),this.emit("enabled")})}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),v(this,_r,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}enable(){return u(this,null,function*(){return this.activateForSelf()})}disable(){return this.deactivateForSelf()}activate(){return u(this,null,function*(){var t,e;this.active||(e=(t=o(this,rn).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(o(this,kt).addPlugin(this.id,this.staggered),v(this,_r,new Date),p.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))})}deactivate(){return u(this,null,function*(){var t,e;this.active&&(!((e=(t=o(this,rn).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==o(this,rn).id||(o(this,kt).removePlugin(this.id),p.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:o(this,_r)?new Date().getTime()-o(this,_r).getTime():0}}),v(this,_r,void 0)))})}},kt=new WeakMap,rn=new WeakMap,Ea=new WeakMap,Ta=new WeakMap,_r=new WeakMap,ka=new WeakMap,ls=new WeakMap,ba=new WeakMap,Xv);gd([Nt({maxInvocations:5,period:1})],us.prototype,"sendData",1),gd([S.trace("DytePlugin.activatePlugin")],us.prototype,"activate",1),gd([S.trace("DytePlugin.deactivatePlugin")],us.prototype,"deactivate",1),us=gd([ht("0600")],us);var Je,hs;class Zv extends Map{constructor(e){const{onAddEvent:n,onDeleteEvent:r,onClearEvent:i}=e;super(),f(this,Je,void 0),f(this,hs,void 0),g(this,"onAddEvent"),g(this,"onDeleteEvent"),g(this,"onClearEvent"),v(this,Je,new es),this.onAddEvent=n,this.onDeleteEvent=r,this.onClearEvent=i,v(this,hs,new Map)}emit(e,...n){return o(this,Je).emit(e,...n)}on(e,n){return o(this,Je).on(e,n)}addListener(e,n){return o(this,Je).addListener(e,n)}off(e,n){return o(this,Je).off(e,n)}once(e,n){return o(this,Je).once(e,n)}prependListener(e,n){return o(this,Je).prependListener(e,n)}prependOnceListener(e,n){return o(this,Je).prependOnceListener(e,n)}removeListener(e,n){return o(this,Je).removeListener(e,n)}removeAllListeners(e){return o(this,Je).removeAllListeners(e)}listeners(e){return o(this,Je).listeners(e)}listenerCount(e){return o(this,Je).listenerCount(e)}getMaxListeners(){return o(this,Je).getMaxListeners()}setMaxListeners(e){return o(this,Je).setMaxListeners(e)}eventNames(){return o(this,Je).eventNames()}add(e,n=!0){return this.set(e.id,e,n)}set(e,n,r=!0){const i=super.set(e,n),s=(a,...c)=>{this.emit(a,n,...c)};return o(this,hs).set(e,s),n.on("*",s),r&&o(this,Je).emit(this.onAddEvent,n),i}delete(e,n=!0,r=!1){const i=this.get(e);if(!i)return!1;i.removeListener("*",o(this,hs).get(e));const s=super.delete(e);return r&&i.removeAllListeners(),n&&o(this,Je).emit(this.onDeleteEvent,i),s}clear(e=!0,n=!1){this.forEach(i=>{i.removeListener("*",o(this,hs).get(i.id)),n&&i.removeAllListeners()});const r=super.clear();return e&&o(this,Je).emit(this.onClearEvent),r}toArray(){return Array.from(this.values())}}Je=new WeakMap,hs=new WeakMap;class ey extends Zv{constructor(){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"})}add(e,n=!0){return super.add(e,n)}delete(e,n=!0,r=!1){return super.delete(e,n,r)}}var uO=Object.defineProperty,hO=Object.getOwnPropertyDescriptor,pO=(t,e,n,r)=>{for(var i=r>1?void 0:r?hO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&uO(e,n,i),i};let uh=class{constructor(){g(this,"all"),g(this,"active"),this.all=new ey,this.active=new ey}};uh=pO([ht("0600")],uh);var mO=Object.defineProperty,gO=Object.getOwnPropertyDescriptor,fd=(t,e,n,r)=>{for(var i=r>1?void 0:r?gO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&mO(e,n,i),i},vn,wa,vd,ty;const ny=(ty=class{constructor(t,e,n,r){g(this,"plugins"),f(this,vn,void 0),f(this,wa,void 0),f(this,vd,void 0),v(this,vn,e),v(this,wa,n),v(this,vd,t),this.plugins=r,this.setupEvents()}static init(t,e,n,r,i,s,a,c){return u(this,null,function*(){const d=new uh;return e.forEach(l=>{const h=new us(t,l,n,s,a,i,c);d.all.add(h)}),new ny(t,n,r,d)})}getRoomPlugins(){return u(this,null,function*(){var t;const{plugins:e}=yield o(this,vn).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(n=>{this.disablePlugin({id:n.id})}),yield Promise.all(e.map(n=>this.enablePlugin({id:n.pluginId,enabledBy:n.enabledBy})))})}enablePlugin(t){return u(this,arguments,function*({id:e,enabledBy:n}){const r=this.plugins.all.get(e);r&&(yield r.activateForSelf(),r.enabledBy=n)})}disablePlugin(t){return u(this,arguments,function*({id:e}){const n=this.plugins.all.get(e);n&&n.deactivateForSelf()})}sendIframeEvent(t,e,n,r){const i=this.plugins.all.get(e);i&&i.sendIframeEvent({type:t,uuid:n,payload:r})}broadcastIframeEvent(t,e){this.plugins.active.forEach(n=>{this.sendIframeEvent(t,n.id,"",e)})}setupEvents(){this.plugins.all.on("stateUpdate",({active:t,id:e})=>{if(t){this.plugins.active.add(this.plugins.all.get(e));return}this.plugins.active.delete(e)}),P.onAsync(R.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){yield this.getRoomPlugins(),p.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")})),o(this,vn).on(z.addPlugin,t=>u(this,null,function*(){var e;const n=t.pluginId;(e=this.plugins.all.get(n))!=null&&e.active||(yield this.enablePlugin({id:n,enabledBy:t.enabledBy}))})),o(this,vn).on(z.removePlugin,t=>u(this,null,function*(){var e;const n=t.pluginId;(e=this.plugins.all.get(n))!=null&&e.active&&(yield this.disablePlugin({id:n}))})),[z.enablePluginForPeers,z.enablePluginForRoom].forEach(t=>{o(this,vn).on(t,(e,n)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,n,{enabledBy:e.enabledBy})}))}),[z.disablePluginForPeers,z.disablePluginForRoom].forEach(t=>{o(this,vn).on(t,(e,n)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,n,{disabledBy:e.disabledBy})}))}),[z.customPluginEventToPeers,z.customPluginEventToRoom].forEach(t=>{o(this,vn).on(t,(e,n)=>u(this,null,function*(){this.sendIframeEvent(t,e.pluginId,n,{data:JSON.parse(new TextDecoder().decode(e.pluginData))})}))}),[z.storeInsertKeys,z.storeGetKeys,z.storeDeleteKeys].forEach(t=>{o(this,vn).on(t,(e,n)=>u(this,null,function*(){var r;const i=(r=e.storeItems)==null?void 0:r.map(s=>{var a;return{timestamp:s.timestamp,peerId:s.peerId,payload:JSON.parse((a=s.payload)!=null&&a.length?new TextDecoder().decode(s.payload):"{}"),key:s.storeKey}});this.sendIframeEvent(t,e.pluginId,n,{storeName:e.storeName,storeItems:i})}))}),o(this,vn).on(z.storeDelete,(t,e)=>u(this,null,function*(){this.sendIframeEvent(z.storeDelete,t.pluginId,e,{storeName:t.storeName})})),o(this,wa).on(Oe.sendMessageToPeers,t=>{const e=Zn==null?void 0:Zn.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Le.chatMessage,{message:e})}),o(this,wa).on(Oe.sendMessageToRoom,t=>{const e=Zn==null?void 0:Zn.formatSocketServiceMessage(t.message);this.broadcastIframeEvent(Le.chatMessage,{message:e})}),P.on(R.PEER_JOINED_INTERNAL,t=>{const e=id(t);this.broadcastIframeEvent(Le.peerJoined,e)}),P.on(R.PEER_CLOSED,t=>{this.broadcastIframeEvent(Le.peerLeft,t)}),P.on(R.UPDATE_PEER_STAGE_STATUS,t=>{this.broadcastIframeEvent(Le.peerStageStatusUpdate,t)}),o(this,vd).subscribe("stageStatus",t=>{this.broadcastIframeEvent(Le.stageStatusUpdate,t)})}},vn=new WeakMap,wa=new WeakMap,vd=new WeakMap,ty);let _a=ny;fd([S.trace("PluginController.getRoomPlugins")],_a.prototype,"getRoomPlugins",1),fd([S.trace("PluginController.enableForSelf")],_a.prototype,"enablePlugin",1),fd([S.trace("PluginController.disableForSelf")],_a.prototype,"disablePlugin",1),fd([S.trace("PluginController.setupEvents")],_a.prototype,"setupEvents",1);class fO{constructor(){g(this,"mediaJoined"),g(this,"socketJoined"),g(this,"socketJoinAttempted"),g(this,"mediaJoinAttempted"),g(this,"socketState"),g(this,"mediaState"),this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0}}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(e,n){let r;const{reconnected:i}=this.socketState;switch(e){case"connected":r={state:"connected",reconnected:i,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:i,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:i,reconnectionAttempt:n};break;case"failed":r={state:"failed",reconnected:i,reconnectionAttempt:void 0},this.socketJoined=!1;break}r&&(P.emit(R.SOCKET_STATE_UPDATE,r),this.socketState=r)}}var vO=Object.defineProperty,yO=Object.getOwnPropertyDescriptor,Ia=(t,e,n,r)=>{for(var i=r>1?void 0:r?yO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&vO(e,n,i),i},Ca,yd,Pa,Sd,ry;let mi=(ry=class extends jt{constructor(t,e){super(),f(this,Pa),f(this,Ca,void 0),f(this,yd,void 0),g(this,"recordingPeerIds",[]),g(this,"recordings",[]),v(this,yd,t),v(this,Ca,e)}get recordingState(){return this.recordings.some(t=>t.state==="RECORDING")?"RECORDING":this.recordings.some(t=>t.state==="PAUSED")?"PAUSED":this.recordings.some(t=>t.state==="STARTING")?"STARTING":this.recordings.some(t=>t.state==="STOPPING")?"STOPPING":"IDLE"}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}start(t){return u(this,null,function*(){if(!o(this,Ca).permissions.canRecord)throw p.error("DyteRecording::start::permission_denied"),new _("User does not have permission to start recording","1001");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw p.error("DyteRecording::start::recording_in_progress",{recording:{state:this.recordingState}}),new _(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=ot(),{recording:n={}}=o(this,yd).getValue("defaults"),r=yield e.startRecording(n,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:r,state:"STARTING",type:"BROWSER"}])}catch(e){throw p.error("DyteRecording::stop::recording_failed_to_start",{error:e}),new _("Error while starting recording","1000")}})}stop(t){return u(this,null,function*(){yield H(this,Pa,Sd).call(this,"stop",["RECORDING","PAUSED"],t)})}pause(t){return u(this,null,function*(){yield H(this,Pa,Sd).call(this,"pause",["RECORDING"],t)})}resume(t){return u(this,null,function*(){yield H(this,Pa,Sd).call(this,"resume",["PAUSED"],t)})}},Ca=new WeakMap,yd=new WeakMap,Pa=new WeakSet,Sd=function(t,e,n){return u(this,null,function*(){if(!o(this,Ca).permissions.canRecord)throw p.error("DyteRecording::stop::permission_denied"),new _("User does not have permission to stop recording","1001");let r=[];if(n!==void 0){const i=this.recordings.find(s=>s.id===n);if(i===void 0)throw new _("Could not find the specified recording","1004");if(e.includes(i.state)){p.error("DyteRecording::stop::recording_not_in_expected_state",{recording:{state:i.state}});return}r.push(i)}else r=this.recordings.filter(i=>e.includes(i.state));r.forEach(i=>u(this,null,function*(){const s=i.state;t==="stop"&&(i.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{yield ot().updateRecording(i.id,t)}catch(a){throw p.error("DyteRecording::stop::recording_failed_to_stop",{error:a}),i.state!==s&&(i.state=s,this.emit("recordingUpdate",s)),new _("Error while stopping recording","1000")}}))})},ry);Ia([S.trace("DyteRecording.start")],mi.prototype,"start",1),Ia([S.trace("DyteRecording.stop")],mi.prototype,"stop",1),Ia([S.trace("DyteRecording.stop")],mi.prototype,"pause",1),Ia([S.trace("DyteRecording.stop")],mi.prototype,"resume",1),mi=Ia([ht("1000")],mi);var SO=Object.defineProperty,EO=Object.getOwnPropertyDescriptor,TO=(t,e,n,r)=>{for(var i=r>1?void 0:r?EO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&SO(e,n,i),i},hh;class iy{constructor(e,n,r){g(this,"recording"),g(this,"room"),f(this,hh,void 0),v(this,hh,e),this.recording=new mi(e,n),this.room=r,this.setupEvents()}getRecordingTypeFromProtoType(e){let n;switch(e){case ii.BROWSER:n="BROWSER";break;case ii.COMPOSITE:n="COMPOSITE";break;case ii.TRACK:n="TRACK";break;default:n="BROWSER"}return n}setupEvents(){P.on(R.ROOM_STATE,e=>{e.activeRecordings.length!==0?this.recording.updateRecordings(e.activeRecordings.map(n=>{const r=this.getRecordingTypeFromProtoType(n.recordingType);return{id:n.recordingId,state:n.recordingStatus,type:r}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(W.recordingStarted,e=>{let n=!1;const r=[...this.recording.recordings];if(r.forEach(i=>{i.id===e.recordingId&&(n=!0,i.state="RECORDING")}),n===!1){const i=this.getRecordingTypeFromProtoType(e.recordingType);r.push({id:e.recordingId,state:"RECORDING",type:i})}this.recording.updateRecordings(r)}),this.room.on(W.recordingPaused,e=>{const n=[...this.recording.recordings];n.forEach(r=>{r.id===e.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(n)}),this.room.on(W.recordingStopped,e=>{const n=[...this.recording.recordings.filter(r=>r.id!==e.recordingId)];this.recording.updateRecordings(n)})}}hh=new WeakMap,TO([S.trace("RecordingController.setupEvents")],iy.prototype,"setupEvents",1);class kO{static hasFeature(e){var n;return(n=X.hasFeature(e))!=null?n:!1}static getFeatureValue(e){return X.getValue(e)}static getAllFeatures(){return X.getAllFlags()}}class ph{constructor(e,n,r){g(this,"logger"),g(this,"features"),g(this,"browserSpecs"),g(this,"callStats"),this.logger=e,this.features=n,this.browserSpecs=Ie,this.callStats=r}static init(e){return new ph(p,kO,e)}}class mh{constructor(e){g(this,"internals"),this.internals=e}static init(){return u(this,null,function*(){const e=ph.init(J);return new mh(e)})}}var bO=Object.defineProperty,wO=Object.getOwnPropertyDescriptor,qt=(t,e,n,r)=>{for(var i=r>1?void 0:r?wO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&bO(e,n,i),i},et,$e,Re,tr,yn,Ed,gh;class Lt extends es{constructor(e,n,r=fh,i=!0){super(),f(this,et,void 0),f(this,$e,void 0),f(this,Re,void 0),f(this,tr,void 0),f(this,yn,void 0),f(this,Ed,void 0),f(this,gh,void 0),g(this,"audioUpdateInProgress"),g(this,"videoUpdateInProgress"),v(this,gh,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,v(this,et,new oy(e,n)),v(this,$e,new JO(o(this,et),void 0,r)),v(this,Re,new ZO(o(this,et),void 0,r)),v(this,yn,new YO(o(this,et))),v(this,tr,new KO(o(this,et))),v(this,Ed,i),o(this,$e).on("trackMuted",this.onAudioTrackMuted.bind(this)),o(this,$e).on("trackChanged",this.onAudioTrackChanged.bind(this)),o(this,Re).on("trackChanged",this.onVideoTrackChanged.bind(this)),o(this,Re).on("trackEnded",this.onVideoTrackEnded.bind(this)),o(this,yn).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}onVisibilityChange(){return u(this,null,function*(){J.tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?J.browserBackgrounded():(J.browserForegrounded(),yield this.setupSpeaker())})}repopulateAvailableDevices(){return u(this,null,function*(){return!0})}setupStreams(e){return u(this,arguments,function*({audio:n,video:r}){var i;n?J.audioOn():J.audioOff(),r?J.videoOn():J.videoOff();let s,a;if(n&&r)try{const c=yield o(this,et).getAudioAndVideoTrack(o(this,$e).userSelectedDevice,o(this,Re).userSelectedDevice);s=c.audioTrack,a=c.videoTrack}catch(c){p.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!s&&n)try{s=yield o(this,et).getAudioTrack(!1,o(this,$e).userSelectedDevice)}catch(c){p.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!a&&r)try{a=yield o(this,et).getVideoTrack(o(this,Re).userSelectedDevice)}catch(c){p.error("LocalMediaHandler::init::Failed to get video track",{error:c})}n&&!s&&J.audioOff(),r&&!a&&J.videoOff(),yield o(this,$e).setMediaTrack(s),yield o(this,Re).setMediaTrack(a);try{yield o(this,tr).setupSpeaker()}catch(c){}if(a){const c=yield this.getDeviceById(a.getSettings().deviceId);J.selectedDevice("VIDEO",c)}if(s){const c=yield this.getDeviceById(s.getSettings().deviceId);J.selectedDevice("AUDIO",c)}(i=o(this,tr).currentDevice)!=null&&i.deviceId&&J.selectedDevice("SPEAKER",o(this,tr).currentDevice),o(this,et).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})})}getCurrentDevices(){return{audio:o(this,$e).currentDevice,video:o(this,Re).currentDevice,speaker:o(this,tr).currentDevice}}get permissions(){return o(this,et).permissions}getAllDevices(){return o(this,et).getAvailableDevices()}getDeviceById(e,n){return o(this,et).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return o(this,$e).mediaTrack}get audioTrack(){return o(this,$e).transformedMediaTrack}get audioEnabled(){return o(this,$e).trackEnabled}enableAudio(){return u(this,null,function*(){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{yield o(this,$e).unmuteTrack()}catch(e){}finally{this.audioUpdateInProgress=!1}}})}disableAudio(){o(this,$e).muteTrack()}getAudioDevices(e){return o(this,et).getAudioInputDevices(e)}setAudioDevice(e){return u(this,null,function*(){yield o(this,$e).setDevice(e),e!=null&&e.deviceId&&J.selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}setupSpeaker(){return o(this,tr).setupSpeaker()}setSpeakerDevice(e){return u(this,null,function*(){yield o(this,tr).setupSpeaker(e),e!=null&&e.deviceId&&J.selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return o(this,Re).mediaTrack}get videoTrack(){return o(this,Re).transformedMediaTrack}get videoEnabled(){return o(this,Re).trackEnabled}enableVideo(){return u(this,null,function*(){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{yield o(this,Re).unmuteTrack()}catch(e){}finally{this.videoUpdateInProgress=!1}}})}disableVideo(){o(this,Re).disableTrack()}getVideoDevices(e){return o(this,et).getVideoInputDevices(e)}setVideoDevice(e){return u(this,null,function*(){yield o(this,Re).setDevice(e),e!=null&&e.deviceId&&J.selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})})}updateVideoConstraints(e){return u(this,null,function*(){yield o(this,Re).updateConstraints(e)})}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:o(this,yn).audioMediaTrack,video:o(this,yn).videoMediaTrack}}get screenShareEnabled(){return o(this,yn).trackEnabled}enableScreenShare(){return u(this,null,function*(){yield o(this,yn).enableScreenShare()})}disableScreenShare(){return u(this,null,function*(){o(this,yn).disableScreenShare()})}updateScreenshareConstraints(e){return u(this,null,function*(){yield o(this,yn).updateConstraints(e)})}getSpeakerDevices(e){return o(this,et).getAudioOutputDevices(e)}addAudioMiddleware(e){return o(this,$e).addMiddleware(e)}removeAudioMiddleware(e){return o(this,$e).removeMiddleware(e)}removeAllAudioMiddlewares(){return o(this,$e).removeAllMiddlewares()}addVideoMiddleware(e){return o(this,Re).addMiddleware(e)}removeVideoMiddleware(e){return o(this,Re).removeMiddleware(e)}removeAllVideoMiddlewares(){return o(this,Re).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return o(this,Re).setVideoMiddlewareGlobalConfig(e)}destruct(){o(this,$e).disableTrack(),o(this,Re).disableTrack(),o(this,Re).terminateMiddlewareWebWorker(),o(this,yn).disableScreenShare(),o(this,et).destruct()}onDeviceChange(e,n){return u(this,null,function*(){var r,i;this.emit("DEVICE_LIST_UPDATED",e),!(n||!o(this,Ed))&&((r=e==null?void 0:e.added)==null||r.forEach(s=>u(this,null,function*(){var a;s&&!fh(s)&&(s.kind==="audioinput"&&((a=this.audioTrack)==null?void 0:a.enabled)===!0?yield this.setAudioDevice(s):s.kind==="audiooutput"&&(yield this.setSpeakerDevice(s)))})),(i=e==null?void 0:e.removed)==null||i.forEach(s=>u(this,null,function*(){var a;if(s.kind==="audiooutput"&&((a=this.getCurrentDevices().speaker)==null?void 0:a.deviceId)===s.deviceId){const c=(yield this.getSpeakerDevices()).find(d=>d.deviceId!==s.deviceId);c&&(yield this.setSpeakerDevice(c))}})))})}removeAllTracks(){this.destruct()}removeAudioTrack(){o(this,$e).disableTrack()}removeVideoTrack(){o(this,Re).disableTrack(),o(this,Re).terminateMiddlewareWebWorker()}removeDocumentEventListeners(){return u(this,null,function*(){document.removeEventListener("visibilitychange",this.onVisibilityChange)})}}et=new WeakMap,$e=new WeakMap,Re=new WeakMap,tr=new WeakMap,yn=new WeakMap,Ed=new WeakMap,gh=new WeakMap,qt([S.trace("MediaHandler.setupStreams")],Lt.prototype,"setupStreams",1),qt([S.trace("MediaHandler.enableAudio")],Lt.prototype,"enableAudio",1),qt([S.trace("MediaHandler.disableAudio")],Lt.prototype,"disableAudio",1),qt([S.trace("MediaHandler.setAudioDevice")],Lt.prototype,"setAudioDevice",1),qt([S.trace("MediaHandler.enableVideo")],Lt.prototype,"enableVideo",1),qt([S.trace("MediaHandler.disableVideo")],Lt.prototype,"disableVideo",1),qt([S.trace("MediaHandler.setVideoDevice")],Lt.prototype,"setVideoDevice",1),qt([S.trace("MediaHandler.updateVideoConstraints")],Lt.prototype,"updateVideoConstraints",1),qt([S.trace("MediaHandler.enableScreenShare")],Lt.prototype,"enableScreenShare",1),qt([S.trace("MediaHandler.disableScreenShare")],Lt.prototype,"disableScreenShare",1),qt([S.trace("MediaHandler.updateScreenshareConstraints")],Lt.prototype,"updateScreenshareConstraints",1),qt([S.trace("MediaHandler.destruct")],Lt.prototype,"destruct",1),qt([S.trace("MediaHandler.onDeviceChange")],Lt.prototype,"onDeviceChange",1);function Td(t,e,n){switch(!0){case Ie.isChromiumBased():switch(e){case"NotAllowedError":return n.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 _O=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function fh(t){var e,n;const r=(e=t.label)==null?void 0:e.toLowerCase();return((n=Ie._bowser)==null?void 0:n.getOSName())==="macOS"&&r.includes("iphone")?(p.log("isVirtualDevice::ignore_macos_continuity"),!0):_O.some(i=>r==null?void 0:r.includes(i))}function IO(t,e){return u(this,null,function*(){if(!(t!=null&&t.length))return e;const n=new AudioContext,r=yield Promise.all(t==null?void 0:t.map(a=>a(n))),i=n.createMediaStreamSource(new MediaStream([e])),s=n.createMediaStreamDestination();try{let a=i;for(let c=0;c<r.length;c+=1)a.connect(r[c]),a=r[c];a.connect(s)}catch(a){return p.error("getTransformedAudioTrack::middleware_execution_failed",{error:a}),e}return s.stream.getAudioTracks()[0]})}var ps;class CO{constructor(){f(this,ps,void 0)}terminateMiddlewareWebWorker(){if(o(this,ps))try{Jr(o(this,ps)),v(this,ps,void 0)}catch(e){p.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}getTransformedVideoTrack(e,n,r){return u(this,null,function*(){if(!(e!=null&&e.length))return n;const i=document.createElement("canvas"),s=yield Promise.all(e==null?void 0:e.map(m=>m({canvas:i,WorkerTimers:yE})));if(r.disablePerFrameCanvasRendering){const m=i.captureStream().getVideoTracks()[0];return Object.defineProperty(m,"originalSettings",{value:n.getSettings()}),m}const a=document.createElement("video"),c=new MediaStream;c.addTrack(n);const d=i.getContext("2d");a.srcObject=c,a.autoplay=!0,this.terminateMiddlewareWebWorker();const l=()=>u(this,null,function*(){if(n.enabled===!1||n.readyState==="ended"){this.terminateMiddlewareWebWorker(),a.remove(),i.remove();return}try{d.drawImage(a,0,0);for(let m=0;m<s.length;m+=1)typeof s[m]=="function"&&(yield s[m](i,d))}catch(m){p.error("getTransformedVideoTrack::middleware_execution_failed",{error:m})}});try{a.play()}catch(m){}a.addEventListener("play",()=>{i.width=a.width||n.getSettings().width,i.height=a.width||n.getSettings().height,v(this,ps,$s(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:n.getSettings()}),h})}}ps=new WeakMap;const sy={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}}},PO=[[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"}]]],RO=t=>{var e;const n="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((e=t.originalSettings)==null?void 0:e.width);let r=PO;X.hasFeature(ie.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)&&(r=JSON.parse(X.getValue(ie.OVERRIDE_HIVE_SIMULCAST_DYNAMIC)));const i=r.map(([c])=>c).sort((c,d)=>c-d);let s=Number.MAX_VALUE,a=0;return i.forEach((c,d)=>{Math.abs(c-n)<s&&(s=Math.abs(c-n),a=d)}),r[a][1]};var ke=(t=>(t.WEBCAM="webcam",t.WEBCAM_BACKUP="webcam_backup",t.MIC="mic",t.SCREENSHARE_VIDEO="screenshare_video",t.SCREENSHARE_AUDIO="screenshare_audio",t))(ke||{});const MO=g_(),ms=gn(MO.config.media);function AO(t){var e,n;const r={};return t.audio&&(r.audio={enableStereo:(e=t.audio.enableStereo)!=null?e:!1,enableHighBitrate:(n=t.audio.enableHighBitrate)!=null?n:!1}),r.video=t.video.quality,r}var gs,vh;class DO{constructor(e,n){f(this,gs,void 0),f(this,vh,void 0),g(this,"getScreenShareConstraints",()=>{var r,i,s,a,c,d,l,h,m,y,T;const b=(r=o(this,gs))==null?void 0:r.screenshare,O=(s=(i=b==null?void 0:b.width)==null?void 0:i.max)!=null?s:1920,M=(c=(a=b==null?void 0:b.height)==null?void 0:a.max)!=null?c:1080,F=(l=(d=b==null?void 0:b.frameRate)==null?void 0:d.max)!=null?l:5;let V=(m=(h=b==null?void 0:b.frameRate)==null?void 0:h.ideal)!=null?m:5;const K=b==null?void 0:b.displaySurface,I=b==null?void 0:b.selfBrowserSurface;X.getValue(ie.VAL_MIN_FRAMERATE)&&(V=parseInt((y=X.getValue(ie.VAL_MIN_FRAMERATE))==null?void 0:y.toString(),10));let Z={width:{max:O},height:{max:M},frameRate:{ideal:V,max:F}};if(X.hasFeature(ie.SCREENSHARE_CONSTRAINTS)){const ae=(T=X.getValue(ie.SCREENSHARE_CONSTRAINTS))==null?void 0:T.toString();Z=JSON.parse(ae)}return K!==void 0&&["monitor","browser","window"].includes(K)&&(Z=G(x({},Z),{displaySurface:K})),I!==void 0&&(Z=G(x({},Z),{selfBrowserSurface:I})),{audio:!0,video:Z}}),g(this,"getAudioConstraints",r=>{var i,s,a,c,d,l,h,m;const y={},T=(i=o(this,gs))==null?void 0:i.audio,b=T!=null&&T.enableStereo?2:1;return Ie.isFirefox()||Ie.isWebKitBased()?(y.audio={deviceId:r,autoGainControl:(s=T==null?void 0:T.autoGainControl)!=null?s:!0,echoCancellation:(a=T==null?void 0:T.echoCancellation)!=null?a:!0,noiseSuppression:(c=T==null?void 0:T.noiseSupression)!=null?c:!0,channelCount:b},y):(y.audio={},y.audio.optional=[r?{sourceId:r}:{sourceId:"default"},{channelCount:b},{echoCancellation:(d=T==null?void 0:T.echoCancellation)!=null?d:!0},{googEchoCancellation:(l=T==null?void 0:T.echoCancellation)!=null?l:!0},{googAutoGainControl:(h=T==null?void 0:T.autoGainControl)!=null?h:!0},{googNoiseSuppression:(m=T==null?void 0:T.noiseSupression)!=null?m:!0},{googHighpassFilter:!0}],y)}),g(this,"getVideoConstraints",r=>{var i,s,a,c;const d={},l=(i=o(this,gs))==null?void 0:i.video;let h=sy.vga;if(typeof l=="string"?h=sy[l]:l!==void 0&&(h.height.ideal=l.height.ideal,h.width.ideal=l.width.ideal),h.frameRate={ideal:(a=(s=h.frameRate)==null?void 0:s.ideal)!=null?a:24},Ie.isChromiumBased()&&(h.frameRate.max=30),X.hasFeature(ie.VIDEO_CONSTRAINTS)){const m=(c=X.getValue(ie.VIDEO_CONSTRAINTS))==null?void 0:c.toString();h=JSON.parse(m)}return d.video=h,typeof d.video=="boolean"||(r?d.video.deviceId={exact:r}:d.video.facingMode="user"),d}),v(this,vh,e),v(this,gs,n)}getUpdatedVideoConstraints(e){return e}}gs=new WeakMap,vh=new WeakMap;class yh extends Error{constructor(e,n,r){super(n),g(this,"constraints"),g(this,"name"),this.name=e,this.constraints=r}}class OO{constructor(){g(this,"permissions"),this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}getAudioInputDevices(e){return u(this,null,function*(){let n=e;return e||(n=yield this.getAvailableDevices()),n.filter(r=>r.kind==="audioinput")})}getVideoInputDevices(e){return u(this,null,function*(){let n=e;return e||(n=yield this.getAvailableDevices()),n.filter(r=>r.kind==="videoinput")})}getAudioOutputDevices(e){return u(this,null,function*(){let n=e;return e||(n=yield this.getAvailableDevices()),n.filter(r=>r.kind==="audiooutput")})}}var NO=Object.defineProperty,LO=Object.getOwnPropertyDescriptor,Sn=(t,e,n,r)=>{for(var i=r>1?void 0:r?LO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&NO(e,n,i),i},Ra,En,Sh,ay;let Gt=(ay=class extends OO{constructor(t,e){super(),g(this,"availableDevices"),f(this,Ra,void 0),f(this,En,void 0),f(this,Sh,void 0),v(this,Sh,t),v(this,En,new DO(t,e)),v(this,Ra,new AbortController),this.availableDevices=[],this.getAvailableDevices()}get constraintsBuilder(){return o(this,En)}destruct(){return u(this,null,function*(){var t;(t=o(this,Ra))==null||t.abort()})}handlePermissionErrors(t,e){const n=Td(t,e.name,e.message);return this.permissions[t]=n,P.emit(R.MEDIA_PERMISSION_ERROR,{message:n,constraints:e.constraints,kind:t}),n}getAudioAndVideoTrack(t,e){return u(this,null,function*(){const n={audio:o(this,En).getAudioConstraints(t).audio,video:o(this,En).getVideoConstraints(e).video};try{p.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(n)});const r=yield navigator.mediaDevices.getUserMedia(n);p.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(n)});const i=r.getAudioTracks()[0];let s=r.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",X.hasFeature(ie.OBS_QUALITY)&&s.label.includes("OBS Virtual")){const a=(yield this.getVideoInputDevices()).find(c=>c.label.includes("OBS Virtual"));s=yield this.getVideoTrack(a.deviceId)}return P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:i,videoTrack:s}}catch(r){throw p.error("WebMediaInterface.getAudioAndVideoTrack",{error:r}),new _("Couldnt fetch audio and video track","1605")}})}getAudioTrack(t,e){return u(this,null,function*(){let n=yield this.getAudioInputDevices();if(n.length===0)throw this.permissions.audio="NO_DEVICES_AVAILABLE",P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new _("No audio devices available","1606");const r=i=>u(this,null,function*(){let s;try{n=n.filter(c=>c.deviceId!==i),s=o(this,En).getAudioConstraints(i),p.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(s)});const[a]=(yield navigator.mediaDevices.getUserMedia(s)).getAudioTracks();return p.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(s)}),a}catch(a){const c=Td("audio",a.name,a.message),d=new yh(a.name,a.message,s);if(c==="COULD_NOT_START"){const l=n.shift();if(!l)throw d;p.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(s),error:a});const h=o(this,En).getAudioConstraints(l.deviceId);return p.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(h)}),r(l.deviceId)}throw d}});try{const i=yield r(e);return i.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),i}catch(i){throw i.constraints&&this.handlePermissionErrors("audio",i),new _(i.message,"1601")}})}getVideoTrack(t){return u(this,null,function*(){var e;const n=X.hasFeature(ie.OBS_QUALITY),r=(e=yield this.getCurrentDeviceLabel(t))==null?void 0:e.includes("OBS Virtual"),i=n&&r,s=yield this.getVideoInputDevices();if(s.length===0)throw this.permissions.video="NO_DEVICES_AVAILABLE",P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new _("No video devices available","1607");const a=c=>u(this,null,function*(){try{let d=c;const{video:l}=d;i&&typeof l!="boolean"&&(d={video:{deviceId:l.deviceId}}),p.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(d)});const[h]=(yield navigator.mediaDevices.getUserMedia(d)).getVideoTracks();if(i&&typeof l!="boolean"&&typeof l.width=="object"){const{width:m,height:y}=h.getSettings(),{ideal:T}=l.width;h.applyConstraints({width:{ideal:T},height:{ideal:Math.floor(y*T/m)},frameRate:l.frameRate})}return p.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(d)}),h}catch(d){const l=Td("video",d.name,d.message),h=new yh(d.name,d.message,c);if(l==="COULD_NOT_START"){const m=s.shift();if(!m)throw h;p.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(c),error:d});const y=o(this,En).getVideoConstraints(m.deviceId);return p.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(y)}),a({video:y.video})}throw h}});try{const c=o(this,En).getVideoConstraints(t),d=yield a(c);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),d}catch(c){throw c.constraints&&this.handlePermissionErrors("video",c),new _(c.message,"1602")}})}getScreenShareTracks(){return u(this,null,function*(){const t=e=>u(this,null,function*(){try{p.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),J.screenShareRequested();const n=yield navigator.mediaDevices.getDisplayMedia(e);return p.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),n}catch(n){const r=Td("video",n.name,n.message),i=new yh(n.name,n.message,e),s={video:!0};if(LI(e,s)||!X.hasFeature(ie.SCREEENSHARE_CONSTRAINTS_RETRY))throw i;if(r==="COULD_NOT_START")return t(s);throw i}});try{const e=o(this,En).getScreenShareConstraints(),n=yield t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:n.getAudioTracks()[0],videoTrack:n.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new _(e.message,"1612")}})}getCurrentDeviceLabel(t){return u(this,null,function*(){const e=yield this.getDevice(t||"default");return e==null?void 0:e.label})}getAvailableDevices(){return u(this,null,function*(){try{const t=yield navigator.mediaDevices.enumerateDevices();return this.availableDevices=t,t}catch(t){throw p.error("enumerate_devices_failed",{error:t}),new _("Failed to get available devices","1609")}})}getAvailableDevicesByKind(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(({kind:e})=>t===e)}catch(e){throw p.error("enumerate_devices_failed",{error:e}),new _("Failed to get available devices by kind","1609")}})}getDevice(t){return u(this,null,function*(){try{return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.deviceId===t)[0]}catch(e){throw p.error("enumerate_devices_failed",{error:e}),new _("Failed to get device","1609")}})}onDeviceChange(t){return u(this,null,function*(){Ie.supportsDeviceChangeEvent()&&navigator.mediaDevices.addEventListener("devicechange",e=>u(this,null,function*(){var n,r;const i=h=>`${h.kind}-${h.deviceId}-${h.groupId}`,s=this.availableDevices,a=new Set(s.map(h=>i(h))),c=yield this.getAvailableDevices(),d=new Set(c.map(h=>i(h))),l={added:c.filter(h=>!a.has(i(h))),removed:s.filter(h=>!d.has(i(h))),devices:c};if((n=l.added)!=null&&n.length||(r=l.removed)!=null&&r.length){p.info("repopulated_full_device_list",{devices:JSON.stringify(c)});const h=[...l.added,...l.removed];h.some(m=>m.kind==="audioinput")&&J.devices("AUDIO",c==null?void 0:c.filter(m=>m.kind==="audioinput")),h.some(m=>m.kind==="videoinput")&&J.devices("VIDEO",c==null?void 0:c.filter(m=>m.kind==="videoinput")),h.some(m=>m.kind==="audiooutput")&&J.devices("SPEAKER",c==null?void 0:c.filter(m=>m.kind==="audiooutput")),t(e,l,!1)}}),{signal:o(this,Ra).signal})})}},Ra=new WeakMap,En=new WeakMap,Sh=new WeakMap,ay);Sn([S.trace("WebMediaInterface.destruct")],Gt.prototype,"destruct",1),Sn([S.trace("WebMediaInterface.handlePermissionErrors")],Gt.prototype,"handlePermissionErrors",1),Sn([S.trace("WebMediaInterface.getAudioAndVideoTrack")],Gt.prototype,"getAudioAndVideoTrack",1),Sn([S.trace("WebMediaInterface.getAudioTrack")],Gt.prototype,"getAudioTrack",1),Sn([S.trace("WebMediaInterface.getVideoTrack")],Gt.prototype,"getVideoTrack",1),Sn([S.trace("WebMediaInterface.getScreenShareTracks")],Gt.prototype,"getScreenShareTracks",1),Sn([S.trace("WebMediaInterface.getAvailableDevices")],Gt.prototype,"getAvailableDevices",1),Sn([S.trace("WebMediaInterface.getAvailableDevicesByKind")],Gt.prototype,"getAvailableDevicesByKind",1),Sn([S.trace("WebMediaInterface.getDevice")],Gt.prototype,"getDevice",1),Sn([S.trace("WebMediaInterface.onDeviceChange")],Gt.prototype,"onDeviceChange",1),Gt=Sn([ht("1600")],Gt);const oy=Gt,Ma={setItem:(t,e)=>{try{localStorage.setItem(t,e)}catch(n){p.error("LocalStorage::setItem::crashed",{error:n,localStorage:{key:t,value:e}})}},getItem:t=>{try{return localStorage.getItem(t)}catch(e){p.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:t}})}return null}},xO=(t=0)=>new Promise(e=>setTimeout(e,t)),VO=(t,e,n)=>{const r=typeof n=="number"?n:250,i=t.createMediaStreamSource(e),s=t.createAnalyser();s.fftSize=2048,i.connect(s);const a=new Uint8Array(s.fftSize);let c=!1;setTimeout(()=>{c=!0},r);function d(){return c?Promise.resolve(!0):(s.getByteTimeDomainData(a),a.some(l=>l!==128&&l!==0)?Promise.resolve(!1):xO().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},UO=typeof AudioContext!="undefined"?AudioContext:null;class Eh{constructor(e){g(this,"_AudioContext"),g(this,"audioContext"),g(this,"_audioContextRefContainers");const n=x({AudioContext:UO},e);Object.defineProperties(this,{_AudioContext:{value:n.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:Eh}})}getOrCreate(e){if(!this._audioContextRefContainers.has(e)&&(this._audioContextRefContainers.add(e),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(n){}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 cy=new Eh,FO=3,BO=250;function WO(t){const e={},n=cy.getOrCreate(e);let r=FO;function i(){return r-=1,VO(n,t.srcObject,BO).then(s=>s?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{cy.release(e)})}function dy(t){return u(this,null,function*(){const e=new Audio,n=new MediaStream;n.addTrack(t),e.srcObject=n;let r=!1;try{const i=e.play();i&&(yield i),r=yield WO(e),r&&p.info("checkIfAudioTrackIsSilent::silence_detected")}catch(i){p.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:i})}finally{e.pause(),e.remove()}return r})}var jO=Object.defineProperty,HO=Object.getOwnPropertyDescriptor,ly=(t,e,n,r)=>{for(var i=r>1?void 0:r?HO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&jO(e,n,i),i};let kd=class extends es{constructor(t,e,n){var r;super(),g(this,"constructorName",this.constructor.name),g(this,"userSelectedDevice"),g(this,"mediaInterface"),g(this,"isNonPreferredDevice"),g(this,"_mediaTrack"),g(this,"transformedMediaTrack"),g(this,"middlewares",[]),g(this,"currentDevice"),g(this,"userPreferredDeviceKey",`Dyte::${this.constructorName}::UserDeviceID`),g(this,"setUserPreferredDevice",i=>Ma.setItem(this.userPreferredDeviceKey,i)),g(this,"getUserPreferredDevice",()=>Ma.getItem(this.userPreferredDeviceKey)),this.mediaInterface=t,e&&this.setMediaTrack(e),this.userSelectedDevice=(r=this.getUserPreferredDevice())!=null?r:void 0,this.isNonPreferredDevice=n,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}disableTrack(){var t,e;this.removeMediaTrackListeners(),(t=this._mediaTrack)==null||t.stop(),this._mediaTrack=void 0,(e=this.transformedMediaTrack)==null||e.stop(),this.transformedMediaTrack=void 0}get mediaTrack(){return this._mediaTrack}setMediaTrack(t){return u(this,null,function*(){const e=n=>{p.error(`${this.constructorName}.setMediaTrack.error`,{error:n})};try{this.disableTrack()}catch(n){e(n)}this._mediaTrack=yield this.conditionallyChangeTrack(t),yield this.setTransformedTrack();try{this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(n){e(n)}})}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){p.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}unmuteTrack(){return u(this,null,function*(){try{this.mediaTrack?this.mediaTrack.enabled=!0:yield this.enableTrack(!1)}catch(t){throw p.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new _("Failed to unmute track","1611")}})}getCurrentDeviceId(){var t,e;const{kind:n}=this.mediaTrack;switch(n){case"audio":{const r=this.mediaTrack.getConstraints();return this.userSelectedDevice?(e=(t=r==null?void 0:r.deviceId)!=null?t:r==null?void 0:r.advanced[0].deviceId)!=null?e:this.mediaTrack.getSettings().deviceId:this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}setCurrentDevice(){return u(this,null,function*(){var t;if(!this.mediaTrack){this.currentDevice=void 0;return}const e=this.getCurrentDeviceId();((t=this.currentDevice)==null?void 0:t.deviceId)!==e&&(this.currentDevice=yield this.mediaInterface.getDevice(e))})}setDevice(t){return u(this,null,function*(){if(!t)throw p.warn(`${this.constructorName}.setDevice No device received`),new _("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()&&!X.hasFeature(ie.ALLOW_SAFARI_MEDIA_MIDDLEWARES))return{success:!1,message:"Middlewares are not supported in this WebKit engine based browser."};if(this.middlewares.includes(t))return{success:!1,message:"This middleware has been applied, already. Skipping."};try{return this.middlewares.push(t),this.trackEnabled&&(yield this.setTransformedTrack()),{success:!0,message:"Successfully added the middleware."}}catch(e){return p.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}})}removeMiddleware(t){return u(this,null,function*(){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),yield this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(n){return p.error("While removing middleware",{error:n}),{success:!1,message:n==null?void 0:n.message}}return{success:!1,message:"No such middleware was found. Skipping."}})}removeAllMiddlewares(){return u(this,null,function*(){var t;if((t=this.middlewares)!=null&&t.length)try{return this.middlewares=[],yield this.setTransformedTrack(!0),{success:!0,message:"Successfully removed all the middlewares."}}catch(e){return p.error("While removing all the middlewares",{error:e}),{success:!1,message:e==null?void 0:e.message}}return{success:!1,message:"No middlewares were found. Skipping."}})}addMediaTrackListeners(){var t,e,n;this.mediaTrack&&(p.info(`${this.constructorName}.addMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(n=this.mediaTrack)==null?void 0:n.kind}`),this.mediaTrack.addEventListener("ended",this.onTrackEnded),this.mediaTrack.addEventListener("mute",this.onTrackMuted))}removeMediaTrackListeners(){var t,e,n;this.mediaTrack&&(p.info(`${this.constructorName}.removeMediaTrackListeners for deviceId ${(e=(t=this.mediaTrack)==null?void 0:t.getSettings())==null?void 0:e.deviceId} of type ${(n=this.mediaTrack)==null?void 0:n.kind}`),p.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};ly([S.trace("BaseMediaHandler.unmuteTrack")],kd.prototype,"unmuteTrack",1),kd=ly([ht("1600")],kd);const uy=kd;var qO=Object.defineProperty,GO=Object.getOwnPropertyDescriptor,Th=(t,e,n,r)=>{for(var i=r>1?void 0:r?GO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&qO(e,n,i),i};const kh="[Dyte]nonSilentDeviceLabels";class bd extends uy{onSetDevice(e){return u(this,null,function*(){if(!e)throw p.warn("AudioMediaHandler.setDevice No device received"),new _("No device received!","1603");if(e.kind!=="audioinput")throw p.warn("AudioMediaHandler.setDevice Received non audio device"),new _("Non audio device received while setting device!","1603");try{const n=this.trackEnabled;yield this.setMediaTrack(yield this.mediaInterface.getAudioTrack(!n,this.userSelectedDevice)),this.userSelectedDevice=void 0}catch(n){throw p.error("AudioMediaHandler.setDevice.error",{error:n}),this.disableTrack(),new _(n.message,"1604")}})}enableTrack(e){return u(this,null,function*(){if(this.trackEnabled){p.warn("AudioMediaHandler.enableTrack Track already enabled!");return}const n=yield this.mediaInterface.getAudioTrack(e,this.userSelectedDevice);yield this.setMediaTrack(n)})}setTransformedTrack(e){return u(this,null,function*(){var n;if(!e&&!((n=this.middlewares)!=null&&n.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield IO(this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(r){p.error("AudioMediaHandler.setTransformedTrack",{error:r}),this.transformedMediaTrack=this.mediaTrack}})}onTrackEnded(){return u(this,null,function*(){p.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const e=this.mediaTrack.enabled;this.disableTrack(),yield this.enableTrack(!e),yield this.setTransformedTrack(),this.emit("trackChanged")})}onTrackMuted(){p.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){var n;if(!e||this.userSelectedDevice)return e;let r=e;const i=yield this.mediaInterface.getAudioInputDevices(),s=this.isNonPreferredDevice?i.filter(d=>d&&!this.isNonPreferredDevice(d)):i;if(!(s!=null&&s.length))return r;s.find(d=>d.deviceId===e.getSettings().deviceId)||(r.stop(),p.info("localmediahandler::setupstreams::found_audio_non_preferred"),r=yield this.mediaInterface.getAudioTrack(!1,s[0].deviceId));const a=JSON.parse(Ma.getItem(kh));if(a!=null&&a.devices.some(d=>d.label===r.label))return r;if(!(yield dy(r))){const d=(n=a==null?void 0:a.devices.concat({label:r.label}))!=null?n:[{label:r.label}];return Ma.setItem(kh,JSON.stringify({devices:d})),r}p.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return s.filter(d=>d.deviceId!==c).some(d=>u(this,null,function*(){if(r=yield this.mediaInterface.getAudioTrack(!1,d.deviceId),!(yield dy(r))){const l=a.devices.concat({label:r.label});return Ma.setItem(kh,JSON.stringify({devices:l})),p.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return p.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1})),r})}}Th([S.trace("AudioMediaHandler.setTransformedTrack")],bd.prototype,"setTransformedTrack",1),Th([S.trace("AudioMediaHandler.onTrackEnded")],bd.prototype,"onTrackEnded",1),Th([S.trace("AudioMediaHandler.conditionallyChangeTrack")],bd.prototype,"conditionallyChangeTrack",1);const JO=bd;var Aa;class $O{constructor(e){f(this,Aa,void 0),g(this,"currentDevice"),v(this,Aa,e)}setupSpeaker(e){return u(this,null,function*(){var n,r;if(!(o(this,Aa)instanceof oy))return;let i=e;if(e||([i]=(yield o(this,Aa).getAvailableDevicesByKind("audiooutput")).filter(a=>!fh(a))),!i)throw new _("No speaker found","1608");if(((n=this.currentDevice)==null?void 0:n.deviceId)===i.deviceId)return;this.currentDevice=i;const s=document.querySelectorAll("audio");(r=s[0])!=null&&r.setSinkId&&s.forEach(a=>u(this,null,function*(){if(typeof a.sinkId!="undefined"&&this.currentDevice.deviceId&&a.sinkId!==this.currentDevice.deviceId)try{yield a.setSinkId(this.currentDevice.deviceId)}catch(c){}}))})}}Aa=new WeakMap;const KO=$O;class zO extends es{constructor(e){super(),g(this,"mediaInterface"),g(this,"audioMediaTrack"),g(this,"videoMediaTrack"),this.mediaInterface=e}get trackEnabled(){return!!this.videoMediaTrack}enableScreenShare(){return u(this,null,function*(){var e,n;try{const{audioTrack:r,videoTrack:i}=yield this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=r,this.videoMediaTrack=i,this.addMediaTrackListeners(),((n=(e=this.mediaInterface)==null?void 0:e.permissions)==null?void 0:n.screenshare)==="ACCEPTED")return;this.mediaInterface.permissions&&(this.mediaInterface.permissions.screenshare="ACCEPTED",P.emit(R.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(r){}})}disableScreenShare(){var e,n;this.removeMediaTrackListeners(),(e=this.audioMediaTrack)==null||e.stop(),(n=this.videoMediaTrack)==null||n.stop(),this.videoMediaTrack=void 0,this.audioMediaTrack=void 0}updateConstraints(e){return u(this,null,function*(){if(!this.videoMediaTrack)throw new _("No media track enabled!","1610");const n=this.mediaInterface;if(!n.constraintsBuilder)throw new _("update constraints not supported for non web clients","1100");try{this.videoMediaTrack.applyConstraints(n.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(r){p.error("ScreenShareHandler.updateConstraints.error",{error:r})}})}addMediaTrackListeners(){var e,n;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),Ie.isWebKitBased()&&((n=this.videoMediaTrack)==null||n.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,n;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(n=this.videoMediaTrack)==null||n.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}const YO=zO;var QO=Object.defineProperty,XO=Object.getOwnPropertyDescriptor,wd=(t,e,n,r)=>{for(var i=r>1?void 0:r?XO(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&QO(e,n,i),i},Da,_d;class Oa extends uy{constructor(e,n,r){super(e,n,r),f(this,Da,void 0),f(this,_d,{disablePerFrameCanvasRendering:!1}),v(this,Da,new CO)}onSetDevice(e){return u(this,null,function*(){if(!e)throw p.warn("VideoMediaHandler.setDevice No device received"),new _("No device received!","1603");if(e.kind!=="videoinput")throw p.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new _("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){p.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(n){throw p.error("VideoMediaHandler.setDevice.error",{error:n}),this.disableTrack(),new _("Failed to change device","1600")}})}enableTrack(){return u(this,null,function*(){if(this.trackEnabled){p.warn("VideoMediaHandler.enableTrack Track already enabled!");return}yield this.setMediaTrack(yield this.mediaInterface.getVideoTrack(this.userSelectedDevice))})}setTransformedTrack(e){return u(this,null,function*(){var n;if(!e&&!((n=this.middlewares)!=null&&n.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=yield o(this,Da).getTransformedVideoTrack(this.middlewares,this.mediaTrack,o(this,_d)),this.emit("trackChanged")}catch(r){p.error("VideoMediaHandler.setTransformedTrack",{error:r}),this.transformedMediaTrack=this.mediaTrack}})}setVideoMiddlewareGlobalConfig(e){return u(this,null,function*(){v(this,_d,e)})}updateConstraints(e){return u(this,null,function*(){if(!this._mediaTrack)throw new _("No media track enabled!","1610");const n=this.mediaInterface;if(!n.constraintsBuilder)throw new _("update constraints not supported for non web clients","1100");try{this._mediaTrack.applyConstraints(n.constraintsBuilder.getUpdatedVideoConstraints(e)),yield this.setTransformedTrack(),this.addMediaTrackListeners(),yield this.setCurrentDevice()}catch(r){p.error("VideoMediaHandler.updateConstraints.error",{error:r})}})}terminateMiddlewareWebWorker(){o(this,Da).terminateMiddlewareWebWorker()}onTrackEnded(){return u(this,null,function*(){p.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")})}onTrackMuted(){p.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}conditionallyChangeTrack(e){return u(this,null,function*(){if(!e||this.userSelectedDevice)return e;let n=e;const r=yield this.mediaInterface.getVideoInputDevices(),i=this.isNonPreferredDevice?r.filter(s=>!this.isNonPreferredDevice(s)):r;return!(i!=null&&i.length)||window.FAST_DYTE||i.find(s=>s.deviceId===e.getSettings().deviceId)||(n.stop(),p.info("localmediahandler::setupstreams::found_video_non_preferred"),n=yield this.mediaInterface.getVideoTrack(i[0].deviceId)),n})}}Da=new WeakMap,_d=new WeakMap,wd([S.trace("VideoMediaHandler.setTransformedTrack")],Oa.prototype,"setTransformedTrack",1),wd([S.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],Oa.prototype,"setVideoMiddlewareGlobalConfig",1),wd([S.trace("VideoMediaHandler.onTrackEnded")],Oa.prototype,"onTrackEnded",1),wd([S.trace("VideoMediaHandler.conditionallyChangeTrack")],Oa.prototype,"conditionallyChangeTrack",1);const ZO=Oa,hy=gn(Iu());var Jt,fs,Id,Na;const La=class{constructor(t){if(f(this,Jt,void 0),f(this,fs,void 0),f(this,Id,void 0),f(this,Na,void 0),!t)throw new _("Could not load preset.","0904");v(this,Jt,t.config),v(this,Id,t.name),v(this,fs,t.ui||gn(Iu().ui)),v(this,Na,t.permissions.plugins.config)}static fromResponse(t){return new La(t)}static default(){return new La(hy)}static init(t,e=!0){return!t||e?new La(hy):new La(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:o(this,fs).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return o(this,Jt).viewType}get livestreamViewerQualities(){return o(this,Jt).livestreamViewerQualities||[]}get maxVideoStreams(){return o(this,Jt).maxVideoStreams}get maxScreenShareCount(){return o(this,Jt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(o(this,Na)).filter(t=>o(this,Na)[t].disabled)}get designTokens(){return o(this,fs).designTokens}get configDiff(){return o(this,fs).configDiff}get mediaConstraints(){var t,e,n,r,i,s,a,c,d,l,h,m,y,T,b,O,M,F,V,K,I,Z,ae,we;return{audio:{enableStereo:(r=(n=(e=(t=o(this,Jt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:n.enableStereo)!=null?r:ms.audio.enableStereo,enableHighBitrate:(c=(a=(s=(i=o(this,Jt))==null?void 0:i.media)==null?void 0:s.audio)==null?void 0:a.enableHighBitrate)!=null?c:ms.audio.enableHighBitrate},video:{quality:(m=(h=(l=(d=o(this,Jt))==null?void 0:d.media)==null?void 0:l.video)==null?void 0:h.quality)!=null?m:ms.video.quality,frameRate:(O=(b=(T=(y=o(this,Jt))==null?void 0:y.media)==null?void 0:T.video)==null?void 0:b.frameRate)!=null?O:ms.video.frameRate},screenshare:{quality:(K=(V=(F=(M=o(this,Jt))==null?void 0:M.media)==null?void 0:F.screenshare)==null?void 0:V.quality)!=null?K:ms.screenshare.quality,frameRate:(we=(ae=(Z=(I=o(this,Jt))==null?void 0:I.media)==null?void 0:Z.screenshare)==null?void 0:ae.frameRate)!=null?we:ms.screenshare.frameRate}}}get name(){return o(this,Id)}};let eN=La;Jt=new WeakMap,fs=new WeakMap,Id=new WeakMap,Na=new WeakMap;var tN=Object.defineProperty,nN=Object.getOwnPropertyDescriptor,py=(t,e,n,r)=>{for(var i=r>1?void 0:r?nN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&tN(e,n,i),i},xa;class bh extends jt{constructor(e){super(),f(this,xa,void 0),g(this,"state","IDLE"),g(this,"playbackUrl"),g(this,"ingestionCredentials"),g(this,"viewerCount"),v(this,xa,e),this.viewerCount=0}setLivestreamState(e){const n=this.state;this.state=e,n!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}start(){return u(this,arguments,function*(e={manualIngestion:!1}){if(!o(this,xa).permissions.canLivestream)throw p.error("DyteLivestream::start::permission_denied"),new _("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const n=ot(),{playbackUrl:r,ingestionCredentials:i}=yield n.startLivestreaming(e);this.playbackUrl=r,this.ingestionCredentials=i,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(n){throw p.error("DyteRecording::stop::livestream_failed_to_start",{error:n}),this.setLivestreamState("IDLE"),new _("Error while starting livestream","1900")}})}stop(){return u(this,null,function*(){if(!o(this,xa).permissions.canLivestream)throw p.error("DyteLivestream::stop::permission_denied"),new _("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw p.error("DyteLivestream::stop::inconsistent_state"),new _("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),yield ot().stopLivestreaming()}catch(e){throw p.error("DyteLivestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new _("Error while stopping livestream","1900")}})}}xa=new WeakMap,py([S.trace("livestream.start")],bh.prototype,"start",1),py([S.trace("livestream.stop")],bh.prototype,"stop",1);var rN=Object.defineProperty,iN=Object.getOwnPropertyDescriptor,sN=(t,e,n,r)=>{for(var i=r>1?void 0:r?iN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&rN(e,n,i),i},Va,Ua,Ir;class my{constructor(e,n){g(this,"livestream"),f(this,Va,void 0),f(this,Ua,void 0),f(this,Ir,void 0),v(this,Ua,e),this.livestream=new bh(e),v(this,Ir,n),this.setupEvents()}fetchInitialLivestreamingState(){return u(this,null,function*(){const e=ot(),{status:n,playbackUrl:r,manualIngest:i,ingestionCredentials:s}=yield e.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=s,n==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),n==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")})}setupEvents(){o(this,Ir).on(W.startedLivestream,e=>u(this,null,function*(){this.livestream.playbackUrl=e.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{o(this,Ua).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch(n){p.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}})),o(this,Ir).on(W.livestreamingInvoked,e=>u(this,null,function*(){if(e.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{o(this,Ua).permissions.canLivestream&&(yield this.fetchInitialLivestreamingState())}catch(n){p.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}})),o(this,Ir).on(W.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),o(this,Ir).on(W.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),o(this,Ir).on(W.roomPeerCount,e=>{this.livestream.viewerCount=e.count,this.livestream.emit("viewerCountUpdate",e.count)}),P.on(R.PEER_JOINED_INTERNAL,e=>u(this,null,function*(){var n;((n=e.flags)==null?void 0:n.hiddenParticipant)===!0&&e.recorderType==="LIVESTREAMER"&&(v(this,Va,e.id),this.livestream.setLivestreamState("LIVESTREAMING"))})),P.on(R.PEER_CLOSED,e=>{e.id===o(this,Va)&&(v(this,Va,void 0),this.livestream.setLivestreamState("IDLE"))}),P.onAsync(R.LEAVE_MEDIA_ROOM,()=>u(this,null,function*(){this.livestream.playbackUrl||(p.info("Fetching livestreaming state on leave stage"),yield this.fetchInitialLivestreamingState())})),P.on(R.SOCKET_SERVICE_ROOM_JOINED,()=>u(this,null,function*(){try{yield this.fetchInitialLivestreamingState()}catch(e){p.error("Error: LivestreamController.fetchLivestream")}}))}}Va=new WeakMap,Ua=new WeakMap,Ir=new WeakMap,sN([S.trace("LivestreamController.setupEvents")],my.prototype,"setupEvents",1);var aN=Object.defineProperty,oN=Object.getOwnPropertyDescriptor,Fa=(t,e,n,r)=>{for(var i=r>1?void 0:r?oN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&aN(e,n,i),i},bt,gi,fi,wh,gy;class vs{constructor({name:e,socketHandler:n,meetingId:r}){f(this,wh),g(this,"name",""),f(this,bt,{}),f(this,gi,""),f(this,fi,void 0),g(this,"rateLimitConfig",{maxInvocations:5,period:1}),g(this,"bulkRateLimitConfig",{maxInvocations:5,period:1}),g(this,"listeners",{}),this.name=e,v(this,fi,n),v(this,gi,r)}set(e,n,r=!0,i=!1){return u(this,null,function*(){o(this,bt)[e]=n,r&&this.remoteSet(e,n),i&&(this.listeners[e]&&this.listeners[e].forEach(s=>s({[e]:o(this,bt)[e]})),this.listeners["*"]&&this.listeners["*"].forEach(s=>s({[e]:o(this,bt)[e]})))})}remoteSet(e,n){o(this,fi).storeInsertKeys(o(this,gi),this.name,[{key:e,payload:n}])}bulkSet(e){return u(this,null,function*(){e.forEach(({key:n,payload:r})=>{o(this,bt)[n]=r}),o(this,fi).storeInsertKeys(o(this,gi),this.name,e)})}update(e,n,r=!0){return u(this,null,function*(){H(this,wh,gy).call(this,e,n,r)})}delete(e,n=!0,r=!1){return u(this,null,function*(){if(o(this,bt)[e]&&delete o(this,bt)[e],n)return o(this,fi).storeDeleteKeys(o(this,gi),this.name,[{key:e}]);r&&(this.listeners[e]&&(this.listeners[e].forEach(i=>i({[e]:void 0})),delete this.listeners[e]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[e]:void 0})))})}bulkDelete(e){return u(this,null,function*(){return e.forEach(({key:n})=>{o(this,bt)[n]&&delete o(this,bt)[n]}),o(this,fi).storeDeleteKeys(o(this,gi),this.name,e)})}get(e){if(o(this,bt)[e])return o(this,bt)[e]}getAll(){return o(this,bt)}get rateLimits(){return this.rateLimitConfig}updateRateLimits(e,n){this.rateLimitConfig.maxInvocations=e,this.rateLimitConfig.period=n}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(e,n){this.bulkRateLimitConfig.maxInvocations=e,this.bulkRateLimitConfig.period=n}subscribe(e,n){if(this.listeners[e]){this.listeners[e].push(n);return}this.listeners[e]=[n]}unsubscribe(e,n){var r;if(n){this.listeners[e]=((r=this.listeners[e])==null?void 0:r.filter(i=>i!==n))||[];return}this.listeners[e]&&delete this.listeners[e]}populate(e){v(this,bt,e)}}bt=new WeakMap,gi=new WeakMap,fi=new WeakMap,wh=new WeakSet,gy=function(t,e,n=!0){let r;const i=o(this,bt)[t],s=Object.prototype.toString.call(e),a=Object.prototype.toString.call(i);if(s!==a){this.set(t,e);return}switch(a){case"[object Array]":r=[...i,...e];break;case"[object Object]":r=x(x({},i),e);break;case"[object Map]":r=new Map([...i,...e]);break;case"[object Set]":r=new Set([...i,...e]);break;default:r=e;break}this.set(t,r,n)},Fa([Nt(rs,"rateLimitConfig")],vs.prototype,"remoteSet",1),Fa([Nt(rs,"bulkRateLimitConfig")],vs.prototype,"bulkSet",1),Fa([Nt(rs,"rateLimitConfig")],vs.prototype,"update",1),Fa([Nt(rs,"rateLimitConfig")],vs.prototype,"delete",1),Fa([Nt(rs,"bulkRateLimitConfig")],vs.prototype,"bulkDelete",1);var ys,Ss,Cd,_h,Pd,vi,Ih,fy;class cN{constructor(e,n){f(this,Cd),f(this,Ih),g(this,"stores",new Map),f(this,ys,void 0),f(this,Ss,""),f(this,Pd,void 0),f(this,vi,new Map),v(this,ys,n),v(this,Ss,e.getValue("meetingId")),v(this,Pd,e),H(this,Ih,fy).call(this)}create(e){const n=new vs({name:e,socketHandler:o(this,ys),meetingId:o(this,Ss)});return o(this,ys).storeGetKeys(o(this,Ss),e,[]),new Promise((r,i)=>{const s=setTimeout(()=>i(Error("Failed")),3e3);o(this,vi).set(e,{rejectTimeout:s,resolve:r,store:n})})}}ys=new WeakMap,Ss=new WeakMap,Cd=new WeakSet,_h=function(){return o(this,Pd).getValue("peerId")},Pd=new WeakMap,vi=new WeakMap,Ih=new WeakSet,fy=function(){[z.storeInsertKeys,z.storeGetKeys,z.storeDeleteKeys].forEach(t=>{o(this,ys).on(t,e=>u(this,null,function*(){var n,r;if(e.pluginId!==o(this,Ss))return;const i=(n=e.storeItems)==null?void 0:n.map(a=>{var c;return{timestamp:a.timestamp,peerId:a.peerId,payload:JSON.parse((c=a.payload)!=null&&c.length?new TextDecoder().decode(a.payload):"{}"),key:a.storeKey}});if(t===z.storeGetKeys){const a=o(this,vi).get(e.storeName),c=this.stores.get(e.storeName)||(a==null?void 0:a.store);o(this,vi).get(e.storeName)&&(this.stores.set(e.storeName,a.store),a.resolve(c),clearTimeout(a.rejectTimeout),o(this,vi).delete(e.storeName)),i.forEach(d=>{c.set(d.key,d.payload,!1,!1)});return}const s=this.stores.get(e.storeName)||((r=o(this,vi).get(e.storeName))==null?void 0:r.store);s!==void 0&&(t===z.storeInsertKeys&&i.forEach(({key:a,peerId:c,payload:d})=>{c!==o(this,Cd,_h)&&s.set(a,d,!1,!0)}),t===z.storeDeleteKeys&&i.forEach(({key:a,peerId:c})=>{c!==o(this,Cd,_h)&&s.delete(a,!1,!0)}))}))})};function yi(t){var e,n,r,i,s,a,c,d,l,h,m,y,T;return t?{media:{audio:{enabled:t.audioEnabled,trackId:(e=t.audioTrack)==null?void 0:e.id,permission:"mediaPermissions"in t?(n=t.mediaPermissions)==null?void 0:n.audio:null},video:{enabled:t.videoEnabled,trackId:(r=t.videoTrack)==null?void 0:r.id,permission:"mediaPermissions"in t?(i=t.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:t.screenShareEnabled,permission:"mediaPermissions"in t?(s=t.mediaPermissions)==null?void 0:s.screenshare:null,audio:{enabled:(c=(a=t.screenShareTracks)==null?void 0:a.audio)==null?void 0:c.enabled,trackId:(l=(d=t.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(m=(h=t.screenShareTracks)==null?void 0:h.video)==null?void 0:m.enabled,trackId:(T=(y=t.screenShareTracks)==null?void 0:y.video)==null?void 0:T.id}}}}:{}}var dN=Object.defineProperty,lN=Object.getOwnPropertyDescriptor,Es=(t,e,n,r)=>{for(var i=r>1?void 0:r?lN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&dN(e,n,i),i};const uN=.8,hN=1.2;var Ba,Wa,Si,Ts,ja,ks,Ha,Ch,vy,Cr,Rd,Ei,qa,Md,Pr,Ph,Ad,Rh,yy;let nr=(yy=class extends jt{constructor(t,e,n,r){super(),f(this,Ts),f(this,ks),f(this,Ch),f(this,qa),f(this,Ad),g(this,"id"),g(this,"userId"),g(this,"name"),g(this,"picture"),g(this,"isHost"),g(this,"customParticipantId"),g(this,"flags"),g(this,"device"),g(this,"videoTrack"),g(this,"audioTrack"),g(this,"screenShareTracks"),g(this,"videoEnabled"),g(this,"audioEnabled"),g(this,"screenShareEnabled"),g(this,"producers"),g(this,"manualProducerConfig"),f(this,Ba,void 0),g(this,"supportsRemoteControl",!1),f(this,Wa,void 0),g(this,"presetName"),f(this,Si,void 0),f(this,Cr,void 0),f(this,Rd,void 0),f(this,Ei,new Map),f(this,Pr,1),f(this,Ph,qc(I=>{if(!this.videoTrack)return;const{clientWidth:Z,clientHeight:ae}=I,{width:we,height:ce}=this.videoTrack.getSettings();if(!we||!ce)return;const De=ce/ae,At=we/Z,A=Math.max(De,At);A>hN&&o(this,Pr)===1?(v(this,Pr,0),P.emit(R.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:o(this,Pr)})):A<uN&&o(this,Pr)===0&&(v(this,Pr,1),P.emit(R.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:o(this,Pr)}))},2e3)),v(this,Si,t);const{id:i,userId:s,displayName:a,device:c,picture:d,isHost:l,flags:h,clientSpecificId:m,stageStatus:y,customParticipantId:T,audioMuted:b,audioTrack:O,videoEnabled:M=!1,videoTrack:F,producers:V,metadata:K}=e;this.id=i,this.userId=s,this.name=a,this.device=c,this.picture=d,this.isHost=l,this.flags=h,this.manualProducerConfig=GI,v(this,Wa,y!=null?y:"ON_STAGE"),this.customParticipantId=T!=null?T:m,this.audioEnabled=!b,this.audioTrack=O,this.videoEnabled=M,this.videoTrack=F,this.screenShareTracks={audio:void 0,video:void 0},this.producers=V!=null?V:[],this.presetName=K==null?void 0:K.preset_name,v(this,Ba,!1),v(this,Cr,n),v(this,Rd,r),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),H(this,Ad,Rh).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return o(this,Wa)}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(p.info("DyteParticipant::setVideoEnabled::videoUpdate",x({},yi(this))),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(p.info("DyteParticipant::setAudioEnabled::audioUpdate",x({},yi(this))),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}))}setScreenShareEnabled(t,e=!0){this.screenShareEnabled=t,e&&this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}setupEvents(){this.on("videoUpdate",H(this,Ad,Rh))}pin(){return u(this,null,function*(){if(!o(this,ks,Ha))throw new _("Can`t pin participant without joining room","1205");if(!o(this,Cr).permissions.pinParticipant)throw new _("You do not have permission to pin participants.","1201");return o(this,Ts,ja).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!o(this,ks,Ha))throw new _("Can`t unpin participant without joining room","1205");if(!o(this,Cr).permissions.pinParticipant)throw new _("You do not have permission to unpin participants.","1201");return o(this,Ts,ja).pinPeer(null)})}setIsPinned(t,e=!0){var n;v(this,Ba,t);const r=t?"pinned":"unpinned";(n=o(this,qa,Md))==null||n.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}disableAudio(){return u(this,null,function*(){const t=this.id;if(p.info("DyteParticipant::disable_audio",{dyteParticipant:{id:t}}),!o(this,ks,Ha))throw new _("Can`t disable participant audio without joining room","1205");if(o(this,Cr).permissions.canDisableParticipantAudio)return o(this,Ts,ja).disableAudio(t);throw p.error("DyteParticipant::unauthorized_disable_audio",{dyteParticipant:{id:t}}),new _("Unauthorized: User does not have permission to disable participant audio.","1201")})}kick(){return u(this,null,function*(){const t=this.id;if(p.info("DyteParticipant::kick",{dyteParticipant:{id:t}}),!o(this,Ch,vy))throw new _("Can`t kick participant without joining room","1205");if(o(this,Cr).permissions.kickParticipant){yield P.emitAsync(R.KICK_PEER,{peerId:t});return}throw p.error("DyteParticipant::unauthorized_kick",{dyteParticipant:{id:t}}),new _("Unauthorized: User does not have permission to kick participants.","1201")})}disableVideo(){return u(this,null,function*(){const t=this.id;if(p.info("DyteParticipant::disable_video",{dyteParticipant:{id:t}}),!o(this,ks,Ha))throw new _("Can`t disable participant video without joining room","1205");if(o(this,Cr).permissions.canDisableParticipantVideo)return o(this,Ts,ja).disableVideo(t);throw p.error("DyteParticipant::unauthorized_disable_video",{dyteParticipant:{id:t}}),new _("Unauthorized: User does not have permission to disable participant video.","1201")})}getPermissions(){return u(this,null,function*(){return o(this,Rd).getUserPermissions(this.userId)})}setStageStatus(t){v(this,Wa,t),this.emit("stageStatusUpdate",this)}get isPinned(){return o(this,Ba)}registerVideoElement(t){var e,n,r,i;let s;(n=(e=o(this,Ei).get(t))==null?void 0:e.observer)==null||n.disconnect(),"ResizeObserver"in window&&(s=new ResizeObserver(()=>o(this,Ph).call(this,t)),s.observe(t)),o(this,Ei).set(t,{observer:s}),this.updateVideo(t),(i=o(this,qa,Md))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1)}deregisterVideoElement(t){var e,n,r;t.srcObject=void 0,(n=(e=o(this,Ei).get(t))==null?void 0:e.observer)==null||n.disconnect(),o(this,Ei).delete(t),(r=o(this,qa,Md))==null||r.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const n=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((n==null?void 0:n.id)===this.videoTrack.id)return;const r=new MediaStream;r.addTrack(this.videoTrack),t.srcObject=r}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},Ba=new WeakMap,Wa=new WeakMap,Si=new WeakMap,Ts=new WeakSet,ja=function(){return o(this,Si).getValue("roomNodeClient")},ks=new WeakSet,Ha=function(){return o(this,Si).getValue("connectionHandler").mediaJoined},Ch=new WeakSet,vy=function(){return o(this,Si).getValue("connectionHandler").socketJoined},Cr=new WeakMap,Rd=new WeakMap,Ei=new WeakMap,qa=new WeakSet,Md=function(){return o(this,Si).getValue("pip")},Pr=new WeakMap,Ph=new WeakMap,Ad=new WeakSet,Rh=function(){Array.from(o(this,Ei).keys()).forEach(this.updateVideo)},yy);Es([S.trace("DyteParticipant.disableAudio")],nr.prototype,"disableAudio",1),Es([S.trace("DyteParticipant.kick")],nr.prototype,"kick",1),Es([S.trace("DyteParticipant.disableVideo")],nr.prototype,"disableVideo",1),Es([S.trace("DyteParticipant.getPermissions")],nr.prototype,"getPermissions",1),Es([S.trace("DyteParticipant.setStageStatus")],nr.prototype,"setStageStatus",1),nr=Es([ht("1200")],nr);class Ga extends Zv{constructor(e){const{onAddEvent:n="participantJoined",onDeleteEvent:r="participantLeft",onClearEvent:i="participantsCleared"}=e!=null?e:{};super({onAddEvent:n,onDeleteEvent:r,onClearEvent:i})}add(e,n=!0){return this.has(e.id)&&Object.is(this.get(e.id),e)===!1&&this.delete(e.id),super.add(e,n)}clear(e=!0,n=!1){return super.clear(e,n)}delete(e,n=!0,r=!1){return super.delete(e,n,r)}}var Ti;class pN extends es{constructor(){super(),f(this,Ti,void 0),v(this,Ti,new Map)}__set(e,n){return o(this,Ti).set(e,n)}__clear(){return o(this,Ti).clear()}get(e){return o(this,Ti).get(e)}toArray(){return Array.from(o(this,Ti).values())}}Ti=new WeakMap;class mN{constructor(){g(this,"_orderedArray"),g(this,"_map"),this._map=new Map,this._orderedArray=[]}add(e,n){if(!this._map.has(e))return this._map.set(e,{peerId:e,priority:n}),this._orderedArray.splice(Math.max(n-1,0),0,e),this.index(e);const r=this.index(e);this.delete(e);const i=this.add(e,n);return r!==i?i:-1}delete(e){if(this._map.has(e)){const n=this.index(e);this._map.delete(e),this._orderedArray.splice(n,1)}}index(e){return this._map.has(e)?this._orderedArray.indexOf(e):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class gN{constructor(){g(this,"_activeSpeakerPeers"),g(this,"_compulsoryPeers"),this._activeSpeakerPeers=new mN,this._compulsoryPeers=new Set}add(e,n){if(!e)return-1;if(n<0)return this._compulsoryPeers.add(e),0;if(this.compulsoryPeers.includes(e)&&(n>0||n===246267631)){if(p.info("DyteSelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),n===246267631)return-1}else if(n===229490415)return this.delete(e),-1;return this._activeSpeakerPeers.add(e,n)}delete(e){p.info("DyteSelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:e}}),this._removeFromCompulsoryPeer(e),this._activeSpeakerPeers.delete(e)}index(e){return this._activeSpeakerPeers.index(e)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(e){this._compulsoryPeers.delete(e)}}const Sy=new gN;var fN=Object.defineProperty,vN=Object.getOwnPropertyDescriptor,$t=(t,e,n,r)=>{for(var i=r>1?void 0:r?vN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&fN(e,n,i),i};const yN=["ACTIVE_GRID","PAGINATED","MANUAL"];var Tn,bs,Ja,ws,$a,Ka,Dd,_s,Kt,Ey;let wt=(Ey=class extends jt{constructor(t,e,n){super(),f(this,bs),f(this,ws),f(this,Ka),g(this,"waitlisted"),g(this,"joined"),g(this,"active"),g(this,"videoSubscribed"),g(this,"audioSubscribed"),g(this,"pinned"),g(this,"all"),f(this,Tn,void 0),f(this,_s,void 0),f(this,Kt,void 0),g(this,"rateLimitConfig",{maxInvocations:5,period:1}),g(this,"viewMode"),g(this,"currentPage"),g(this,"lastActiveSpeaker"),g(this,"selectedPeers",Sy),v(this,Tn,t),v(this,_s,e),v(this,Kt,n),this.waitlisted=new Ga,this.joined=new Ga,this.videoSubscribed=new Ga,this.audioSubscribed=new Ga,this.active=this.videoSubscribed,this.pinned=new Ga,this.all=new pN,this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return o(this,Tn).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}setupEvents(){P.on(R.E2EE_ACTIVE_CONSUMER,({peerId:t})=>{var e;((e=o(this,Tn).getValue("modules").e2ee)==null?void 0:e.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${t}, but encryption wasn't enabled in init.defaults`,code:"1702"})})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=o(this,Tn))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new _("0 <= Max active participants count limit <= 24","1203");o(this,Tn).setValue("maxPreferredStreams",t),o(this,Ka,Dd)&&P.emit(R.UPDATE_ACTIVE)}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(n=>n.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var e,n;if(!o(this,ws,$a))throw new _("Can`t accept waiting room request without joining room","1205");const r=(n=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?n:t;return o(this,Kt).acceptWaitingRoomRequest([r])}acceptAllWaitingRoomRequest(t){return u(this,null,function*(){const e=t.map(n=>{var r,i;return(i=(r=this.waitlisted.get(n))==null?void 0:r.userId)!=null?i:n});return o(this,Kt).acceptWaitingRoomRequest(e)})}rejectWaitingRoomRequest(t){return u(this,null,function*(){var e,n;if(!o(this,ws,$a))throw new _("Can`t reject waiting room request without joining room","1205");const r=(n=(e=this.waitlisted.get(t))==null?void 0:e.userId)!=null?n:t;o(this,Kt).rejectWaitingRoomRequest([r])})}setViewMode(t){return u(this,null,function*(){if(p.info("DyteParticipants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(e=>yN.includes(e))(t))throw p.error("DyteParticipants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new _(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){p.info("DyteParticipants::setViewMode::view_mode_same_as_previous");return}if(t==="MANUAL")throw new _("Manual Subscription is not enabled for your Organization. Please contact support.","1208");this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,P.emit(R.UPDATE_ACTIVE,{page:this.currentPage})):t==="ACTIVE_GRID"&&(this.currentPage=0,P.emit(R.UPDATE_ACTIVE)),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})})}subscribe(t){return u(this,arguments,function*(e,n=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new _("MANUAL subscription mode was not activated.","1206");const r=[];e.forEach(i=>{const s=this.joined.get(i);if(s){if(n.includes("audio")){s.manualProducerConfig=G(x({},s.manualProducerConfig),{audio:!0}),this.videoSubscribed.add(s);const a=s.producers.find(c=>c.kind==="audio"&&!c.screenShare);a&&r.push(a)}if(n.includes("video")){s.manualProducerConfig=G(x({},s.manualProducerConfig),{video:!0}),this.audioSubscribed.add(s);const a=s.producers.find(c=>c.kind==="video"&&!c.screenShare);a&&r.push(a)}if(n.includes("screenshareAudio")){s.manualProducerConfig=G(x({},s.manualProducerConfig),{screenshareAudio:!0});const a=s.producers.find(c=>c.kind==="audio"&&c.screenShare);r.push(a)}if(n.includes("screenshareVideo")){s.manualProducerConfig=G(x({},s.manualProducerConfig),{screenshareVideo:!0});const a=s.producers.find(c=>c.kind==="video"&&c.screenShare);r.push(a)}}}),yield o(this,bs,Ja).createConsumers(r)})}unsubscribe(t){return u(this,arguments,function*(e,n=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new _("MANUAL subscription mode was not activated.","1206");const r=[];e.forEach(i=>{const s=this.joined.get(i);if(s){if(n.includes("audio")){s.manualProducerConfig=G(x({},s.manualProducerConfig),{audio:!1});const a=s.producers.find(c=>c.kind==="audio"&&!c.screenShare);a&&r.push(a)}if(n.includes("video")){s.manualProducerConfig=G(x({},s.manualProducerConfig),{video:!1});const a=s.producers.find(c=>c.kind==="video"&&!c.screenShare);a&&r.push(a)}if(n.includes("screenshareAudio")){s.manualProducerConfig=G(x({},s.manualProducerConfig),{screenshareAudio:!1});const a=s.producers.find(c=>c.kind==="audio"&&c.screenShare);r.push(a)}if(n.includes("screenshareVideo")){s.manualProducerConfig=G(x({},s.manualProducerConfig),{screenshareVideo:!1});const a=s.producers.find(c=>c.kind==="video"&&c.screenShare);r.push(a)}}}),yield o(this,bs,Ja).closeConsumers(r)})}getPeerIdsForCurrentPage(){p.info("DyteParticipants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(a=>this.joined.has(a)),n=Array.from(this.pinned.keys()).filter(a=>!e.includes(a)),r=Array.from(this.joined.toArray().filter(a=>a.stageStatus==="ON_STAGE").map(a=>a.id)),i=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-n.length)),s=this.currentPage*(this.maxActiveParticipantsCount-e.length-n.length);return e.concat(n,r.slice(i,s))}setPage(t){return u(this,null,function*(){if(p.info("DyteParticipants::set_page",{pageNavigation:{settingPage:t,viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),this.viewMode==="PAGINATED"){if(!Number.isInteger(t))throw p.error("DyteParticipants::invalid_page_number"),new _(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,P.emit(R.UPDATE_ACTIVE,{page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}})}disableAllAudio(t){return u(this,null,function*(){if(p.info("DyteParticipants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!o(this,Ka,Dd))throw new _("Can`t disable all audio without joining room","1205");if(o(this,_s).permissions.canAllowParticipantAudio)return o(this,bs,Ja).muteAll(t);throw p.error("DyteParticipants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new _("Unauthorized: User does not have permission to disable peer audio.","1201")})}disableAllVideo(){return u(this,null,function*(){if(p.info("DyteParticipants::disable_all_video"),!o(this,Ka,Dd))throw new _("Can`t disable all video without joining room","1205");if(o(this,_s).permissions.canAllowParticipantVideo)return o(this,bs,Ja).muteAllVideo();throw p.error("DyteParticipants::unauthorized_disable_all_video"),new _("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 P.emitAsync(R.KICK_PEER,{peerId:t})})}kickAll(){return u(this,null,function*(){if(p.info("DyteParticipants::kick_all"),o(this,Tn).getValue("viewType")!=="LIVESTREAM"&&!o(this,ws,$a))throw new _("Can`t kick all without joining room","1205");if(!o(this,_s).permissions.kickParticipant)throw p.error("DyteParticipants::unauthorized_kick_all"),new _("Unauthorized: User does not have permission to kick peers.","1201");const t=X.hasFeature(ie.PROPAGATE_KICK_ALL);o(this,Kt).kickAll(t)})}broadcastMessage(t,e,n){return u(this,null,function*(){if(p.info("DyteParticipants::broadcastMessage"),!o(this,ws,$a))throw new _("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new _("`type` must be a non-empty string.","1209");if(n)if("meetingIds"in n)yield o(this,Kt).broadcastToMeetings(t,n.meetingIds,e);else{let r=[];"participantIds"in n?r=n.participantIds:r=this.joined.toArray().filter(i=>{var s;return(s=n.presetNames)==null?void 0:s.includes(i.presetName)}).map(i=>i.id),yield o(this,Kt).broadcastToPeers(t,r,e)}else yield o(this,Kt).broadcastMessage(t,e)})}getAllJoinedPeers(t,e,n){return u(this,null,function*(){return(yield o(this,Kt).getRoomPeers(t,e,n)).peers.map(rr.formatSocketServiceMessage)})}updatePermissions(t,e){return u(this,null,function*(){const n=this.joined.toArray().filter(i=>t.includes(i.id)).map(i=>i.userId),r=[...new Set(n)];if(!r.length)throw new _("Cannot update permissions, no valid userIDs found","1204");o(this,Kt).updatePermissions(r,e)})}getParticipantsInMeetingPreJoin(){return u(this,null,function*(){return o(this,Kt).getRoomPeersNonPaginated()})}},Tn=new WeakMap,bs=new WeakSet,Ja=function(){return o(this,Tn).getValue("roomNodeClient")},ws=new WeakSet,$a=function(){var t;return((t=o(this,Tn).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},Ka=new WeakSet,Dd=function(){var t;return((t=o(this,Tn).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},_s=new WeakMap,Kt=new WeakMap,Ey);$t([S.trace("DyteParticipants.setViewMode")],wt.prototype,"setViewMode",1),$t([S.trace("DyteParticipants.setPage")],wt.prototype,"setPage",1),$t([S.trace("DyteParticipants.disableAllAudio")],wt.prototype,"disableAllAudio",1),$t([S.trace("DyteParticipants.disableAllVideo")],wt.prototype,"disableAllVideo",1),$t([S.trace("DyteParticipants.disablePeerAudio")],wt.prototype,"disableAudio",1),$t([S.trace("DyteParticipants.disablePeerVideo")],wt.prototype,"disableVideo",1),$t([S.trace("DyteParticipants.kickPeer")],wt.prototype,"kick",1),$t([S.trace("DyteParticipants.kickAll")],wt.prototype,"kickAll",1),$t([S.trace("DyteParticipants.broadcastMessage"),Nt(rs,"rateLimitConfig")],wt.prototype,"broadcastMessage",1),$t([S.trace("DyteParticipants.getAllJoinedPeers"),Nt({maxInvocations:10,period:60})],wt.prototype,"getAllJoinedPeers",1),$t([S.trace("DyteParticipant.updatePermissions"),Nt({maxInvocations:1e3,period:60})],wt.prototype,"updatePermissions",1),$t([S.trace("DyteParticipants.getParticipantsInMeetingPreJoin")],wt.prototype,"getParticipantsInMeetingPreJoin",1),wt=$t([ht("1200")],wt);var Rr=(t=>(t.NEW="new",t.CONNECTING="connecting",t.RECONNECTING="reconnecting",t.DISCONNECTED="disconnected",t.CONNECTED="connected",t.FAILED="failed",t.CLOSED="closed",t))(Rr||{}),tt=(t=>(t[t.HIVE=1]="HIVE",t[t.ROOM_NODE=2]="ROOM_NODE",t[t.CF=3]="CF",t))(tt||{}),SN=Object.defineProperty,EN=Object.getOwnPropertyDescriptor,ki=(t,e,n,r)=>{for(var i=r>1?void 0:r?EN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&SN(e,n,i),i};const Ty=class{constructor(t,e,n,r){switch(g(this,"participants"),g(this,"self"),g(this,"selectedPeers",Sy),g(this,"maxSpatialLayerUpdates",new Map),g(this,"consumerPeerMap"),g(this,"events"),g(this,"roomSocketHandler"),g(this,"context"),g(this,"videoPeerConsumerMap",new Map),g(this,"updateConsumerSpatialLayers",qc(()=>{const i={},s=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(s.entries()).forEach(([a,c])=>{i[c]===void 0&&(i[c]={layer:c,consumerIds:[]}),i[c].consumerIds.push(a)}),Object.keys(i).forEach(a=>{const c=i[a];p.log(`Switching max spatial layer to ${c.layer}`,{consumerIds:c.consumerIds}),this.roomNodeClient.switchConsumersToLayer(c.consumerIds,c.layer)})},2e3)),g(this,"updateConsumers",(i,s)=>{let a=Promise.resolve();s.length>0&&(p.info("Closing consumers for producers",{producers:s}),a=this.roomNodeClient.closeConsumers(s)),a.then(()=>{i.length!==0&&(p.info("Consuming producers",{producers:i}),this.roomNodeClient.createConsumers(i).catch(c=>p.error("Error activating peers",{error:c})))}).catch(c=>p.error("Error deactivating peers",{error:c}))}),g(this,"updateConsumersDebounced",qc(this.updateConsumers,200,{trailing:!0})),this.context=t,this.roomSocketHandler=n,this.participants=new wt(t,e,this.roomSocketHandler),this.self=e,this.consumerPeerMap=new Map,r){case tt.HIVE:{this.events=en;break}case tt.CF:{this.events=pn;break}default:this.events=en}e.config.viewType!=="CHAT"&&this.setupEventsGlobal(),this.setupEvents()}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var t;return((t=this.roomNodeClient)==null?void 0:t.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}setupEvents(){this.roomSocketHandler.on(W.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),P.on(R.SOCKET_PEERS,t=>u(this,null,function*(){const e=X.hasFeature(ie.DEBUG_SOCKET_JOIN);if(e){const n=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(r=>r.peerId))}:void 0;p.info("Processing socket peers",n)}t==null||t.forEach(n=>{n.waitlisted||this.onParticipantJoined(this.fromSocketService(n))}),e&&p.info("Processed socket peers")})),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:t})=>{X.hasFeature(ie.DEBUG_SOCKET_JOIN)&&p.info("events.peerJoinedBroadcast",{peers:t.peerId}),this.onMediaJoined(t.peerId,t.producerStates,t.capabilities)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:t,selectedPeers:e,roomState:n})=>{if(X.hasFeature(ie.DEBUG_SOCKET_JOIN)){const s=t&&(t==null?void 0:t.length)<20?{peers:JSON.stringify(t.map(a=>a.peerId))}:void 0;p.info("events.selfJoinComplete",s)}t.forEach(({peerId:s,producerStates:a,capabilities:c})=>this.onMediaJoined(s,a,c));const{audioPeers:r,compulsoryPeers:i}=e!=null?e:{};n.pinnedPeerIds.length!==0&&this.onParticipantPinned(n.pinnedPeerIds[0]),this.computeActivateParticipants(r!=null?r:[],i),P.emit(R.UPDATE_ACTIVE,{createAllConsumers:!0})}),P.on(R.MAX_SPATIAL_LAYER_CHANGE,({peerId:t,maxSpatialLayer:e})=>{const n=this.videoPeerConsumerMap.get(t);n&&(this.maxSpatialLayerUpdates.set(n,e),this.updateConsumerSpatialLayers())}),P.on(R.NEW_PRODUCER,({peerId:t,producer:e})=>{const n=this.participants.joined.get(t);if(!n){p.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:e==null?void 0:e.producerId,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}},dyteParticipant:{id:t}});return}if(n.producers.push(e),p.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}}),this.participants.viewMode==="MANUAL"){let r=!1;const i=e.kind==="audio",s=e.kind==="video",a=n.manualProducerConfig;(i&&(a.audio&&!e.screenShare||a.screenshareAudio&&e.screenShare)||s&&(a.video&&!e.screenShare||a.screenshareVideo&&e.screenShare))&&(r=!0),r?this.roomNodeClient.createConsumers([e]):p.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}});return}(e==null?void 0:e.kind)==="audio"&&this.participants.audioSubscribed.get(t)||(e==null?void 0:e.kind)==="video"&&this.participants.videoSubscribed.get(t)||e!=null&&e.screenShare?this.roomNodeClient.createConsumers([e]).catch(r=>{p.error("ParticipantController::createConsumer failed",{error:r})}):p.info("ParticipantController::NEW_PRODUCER::not_consuming_producer",{producer:{id:e==null?void 0:e.producerId,peerId:t,kind:e==null?void 0:e.kind,status:"UNKNOWN",appData:{screenShare:e==null?void 0:e.screenShare}}})}),P.on(R.PRODUCER_CLOSED,({peerId:t,producerId:e})=>{const n=this.participants.joined.get(t);if(!n){p.warn("ParticipantController::NEW_PRODUCER::participant not found",{dyteParticipant:{id:t}});return}n.producers=n.producers.filter(r=>r.producerId!==e)}),P.on(R.PRODUCER_TOGGLE,({peerId:t,producerId:e,paused:n,kind:r})=>{const i=this.participants.joined.get(t);if(i){r==="audio"&&i.setAudioEnabled(!n);const s=i.producers.find(a=>a.producerId===e);s&&(s.pause=n)}}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,t=>{let e;if(t&&(e=t.participantId),!this.mediaJoined)return;const n=e;this.onParticipantPinned(n);const r=this.participants.joined.get(n);r&&this.roomNodeClient.activatePeers(r.producers).catch(i=>{p.error("unable to create consumers",{error:i})})}),this.roomSocketHandler.on(this.events.selectedPeer,({audioPeers:t,compulsoryPeers:e})=>{this.mediaJoined&&this.onSelectedPeers(e.concat(t))}),this.roomSocketHandler.on(this.events.selectedPeerDiff,({entries:t})=>{if(!this.mediaJoined)return;const e=t.map(n=>({peerId:n.peerId,priority:n.priority}));this.updateActiveParticipantsWithPriorities(e,!0)})}waitingRoomRequestHandler(t){const e=t.requests.filter(r=>!this.participants.waitlisted.toArray().find(i=>i.userId===r.userId)),n=this.participants.waitlisted.toArray().filter(r=>!t.requests.find(i=>i.userId===r.userId));e.forEach(r=>this.participants.waitlisted.add(new nr(this.context,{id:r.peerId,displayName:r.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:r.userId,flags:{},isHost:!1,customParticipantId:r.customParticipantId,picture:r.picture,metadata:{preset_name:r.presetName}},this.self,this.roomSocketHandler))),n.forEach(r=>this.participants.waitlisted.delete(r.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(t){return u(this,null,function*(){const{compulsoryPeers:e}=this.selectedPeers,n=e.filter(c=>this.participants.joined.has(c)),r=Array.from(this.participants.pinned.keys()).filter(c=>!n.includes(c)),i=Array.from(this.participants.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),s=Math.max((t-1)*(this.maxPreferredStreams-n.length-r.length)),a=t*(this.maxPreferredStreams-n.length-r.length);return n.concat(r,i.slice(s,a))})}selectActivePeers(){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(l=>l.stageStatus==="ON_STAGE").map(l=>(t.set(l.id,!0),l.id))),n=this.selectedPeers.peers,r=this.participants.pinned.toArray().reduce((l,h)=>(h.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(h.id):l.push(h.id),l),[]),i=this.self.stageStatus==="ON_STAGE"?1:0,s=this.participants.maxActiveParticipantsCount-i,a=new Set(n.concat(r).filter(l=>l!==this.self.id&&t.has(l)));let c=Array.from(a);const d=s-a.size;if(d>=0){const l=e.filter(h=>!a.has(h)&&h!==this.self.id).slice(0,d);c=Array.from(a).concat(l)}else c=c.slice(0,s);return c}updateActive(t,e){return u(this,null,function*(){const{page:n,createAllConsumers:r}=e!=null?e:{};let{strategies:i}=e!=null?e:{},s,a;switch(t){case"PAGINATED":{if(!n)return;s=yield this.selectPagePeers(n),p.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:s}),i!=null||(i={video:this.updateParticipantsMap.bind(this)}),a=this.updateConsumersDebounced;break}case"ACTIVE_GRID":{s=this.selectActivePeers(),p.debug("ParticipantController::updateActive::updating_current_selected_peers",{peerIds:s}),i!=null||(i={video:this.updateParticipantsMapMinReplacement.bind(this),audio:this.updateParticipantsMap.bind(this)}),a=this.updateConsumers;break}default:throw new Error(`View mode ${t} not supported`)}let c,d;const l=this.updateGrid(s,i);r?(c=this.mapPeerIdsToProducers(s,["audio","video","screenshare"]),d=[]):(c=[...this.mapPeerIdsToProducers([...l.video.add],["video"]),...this.mapPeerIdsToProducers([...l.audio.add],["audio"])],d=[...this.mapPeerIdsToProducers([...l.video.remove],["video"]),...this.mapPeerIdsToProducers([...l.audio.remove],["audio"])]),!(c.length===0&&d.length===0)&&a(c,d)})}computeActivateParticipants(t,e){const n=t.map((i,s)=>({peerId:i,priority:s+1})),r=e==null?void 0:e.map((i,s)=>({peerId:i,priority:-(s+1)}));n.push(...r!=null?r:[]),n.length>0&&this.updateActiveParticipantsWithPriorities(n)}fromSocketService(t){const e=Ty.formatSocketServiceMessage(t);return new nr(this.context,G(x({},e),{isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0}),this.self,this.roomSocketHandler)}updatePipSource(t,e){var n,r;e?(n=this.pip)==null||n.enableSource(t):(r=this.pip)==null||r.disableSource(t)}onMediaJoined(t,e,n){if(!this.mediaJoined||t===this.self.id)return;const r=this.participants.joined.get(t);if(!r){p.warn(`Received media.peerJoinedBroadcast for non-existent peer ${t}`);return}e.forEach(i=>{i.kind===Ln.AUDIO&&!i.screenShare?r.setAudioEnabled(!i.pause):i.kind===Ln.VIDEO&&!i.screenShare&&(r.setVideoEnabled(!i.pause),this.updatePipSource(r.id,!i.pause)),r.producers.push(G(x({},i),{producingTransportId:i.producingTransportId,kind:i.kind===Ln.AUDIO?"audio":"video",producingPeerId:t,mimeType:i.mimeType}))}),this.roomNodeClient.handlePeerCapabilities(t,n),X.hasFeature(ie.FORCE_VIDEO_CODEC)||this.roomNodeClient.shareWebcam(this.self.videoTrack)}updateParticipantsMapMinReplacement(t,e){const n=Array.from(t.keys()),r=new Map(t),i=[],s=[],a=new Set(e),c=[];return n.forEach((d,l)=>{(!a.has(d)||!this.participants.joined.get(d))&&c.push(l)}),e.forEach(d=>{if(t.get(d))return;if(n.length<e.length){n.push(d),i.push(d);return}const l=c.shift();s.push(n[l]),n[l]=d,i.push(n[l])}),n.forEach((d,l)=>{a.has(d)||s.concat(n.splice(l,1))}),Array.from(t.keys()).forEach(d=>{t.delete(d,!a.has(d))}),n.forEach(d=>{if(!this.participants.joined.get(d)){p.warn("updateActiveParticipants::participant_not_in_joined_list",{dyteParticipant:{id:d}});return}t.add(this.participants.joined.get(d),!r.get(d))}),t.emit("participantsUpdate"),[i,s]}updateParticipantsMap(t,e){const n=Array.from(t.keys()),r=[],i=[];return n.forEach(s=>{e.includes(s)||(t.delete(s,!0),i.push(s))}),e.forEach(s=>{t.get(s)||(t.add(this.participants.joined.get(s)),r.push(s))}),t.emit("participantsUpdate"),[r,i]}updatePinnedParticipants(){this.participants.pinned.forEach(t=>{t.setIsPinned(!1),this.participants.pinned.delete(t.id)})}setupEventsGlobal(){this.roomSocketHandler.on(W.joinRoom,({peer:t})=>{if(!t.waitlisted){const e=X.hasFeature(ie.DEBUG_SOCKET_JOIN);e&&p.info("Processing socket join",{peers:t.peerId}),this.onParticipantJoined(this.fromSocketService(t)),e&&p.info("Processed socket join",{peers:t.peerId})}}),this.roomSocketHandler.on(W.leaveRoom,t=>{const{peerId:e}=t.peer;this.selectedPeers.delete(e),this.onParticipantLeave(e)}),P.on(R.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())}),P.on(R.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})}),P.on(R.CONSUMER_PAUSED,({id:t})=>{this.processConsumerPaused(t)}),P.on(R.CONSUMER_RESUMED,({id:t})=>{this.processConsumerResumed(t)}),P.on(R.NEW_CONSUMER,({id:t})=>{this.processNewConsumer(t)}),P.on(R.CONSUMER_CLOSED,({id:t})=>{this.processConsumerClosed(t)}),P.on(R.ROOM_MESSAGE,t=>u(this,[t],function*({payload:e,type:n,timestamp:r}){this.participants.emit("broadcastedMessage",{type:n,payload:e,timestamp:r})})),P.on(R.MESSAGE,t=>u(this,[t],function*({payload:e,type:n,timestamp:r}){n!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:n,payload:e,timestamp:r})})),P.on(R.LOW_CONSUMER_SCORE,({peerId:t,score:e,kind:n})=>{const r=this.participants.joined.get(t);r&&(r.emit("poorConnection",{score:e,kind:n}),this.participants.emit("poorConnection",{participantId:t,score:e,kind:n}))}),P.on(R.CONSUMER_SCORE_UPDATE,({score:t,kind:e,appData:n,peerId:r,scoreStats:i})=>{var s;const a=e==="video"&&((s=n==null?void 0:n.screenShare)!=null?s:!1),c=this.participants.joined.get(r);c&&(c.emit("mediaScoreUpdate",{kind:e,isScreenshare:a,score:t,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:e,isScreenshare:a,score:t,participantId:r,scoreStats:i}))}),P.onAsync(R.KICK_PEER,t=>u(this,[t],function*({peerId:e}){const n=this.participants.joined.get(e);yield this.roomNodeClient.kick(e),yield this.roomSocketHandler.kick(e),n?n.emit("kicked"):this.participants.joined.emit("kicked",{id:e})})),P.on(R.UPDATE_ACTIVE,(...t)=>u(this,[...t],function*({page:e,createAllConsumers:n}={}){yield this.updateActive(e?"PAGINATED":"ACTIVE_GRID",{page:e,createAllConsumers:n})}))}onParticipantPinned(t){return u(this,null,function*(){if(!t){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(t===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const e=this.participants.joined.get(t);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),e.setIsPinned(!0),this.participants.pinned.add(e)})}onParticipantJoined(t){return u(this,null,function*(){var e,n,r;if(this.self.id!==t.id&&!((e=t.flags)!=null&&e.recorder)&&!((n=t.flags)!=null&&n.hidden_participant)&&!((r=t.flags)!=null&&r.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"&&P.emit(R.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!0})),P.emit(R.PEER_JOINED_INTERNAL,t),this.self.config.viewType===yt.Webinar&&t.stageStatus!=="ON_STAGE"||this.roomNodeClient===void 0||this.participants.videoSubscribed.size>=this.maxPreferredStreams)return;const i=this.participants.currentPage;this.updateActive(i?"PAGINATED":"ACTIVE_GRID",{page:i})})}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"&&P.emit(R.UPDATE_STAGE_REQUESTS,{request:{displayName:e.name,userId:e.userId,peerId:e.id},add:!1});const{currentPage:n}=this.participants,r=this.maxPreferredStreams*(n-1),i=this.participants.videoSubscribed.get(t);r===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=r?n===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(n-1):i&&this.updateActive(n?"PAGINATED":"ACTIVE_GRID",{page:n})})}processMedia(t){var e;const n=this.roomNodeClient.getConsumers(),{peerId:r,kind:i,appData:s,track:a,producerId:c,rtpReceiver:d,paused:l}=(e=n.get(t))!=null?e:{};if(!r)return p.warn("processMedia::Peer ID is undefined",{consumer:{id:t,kind:i,peerId:r,appData:{supportsRemoteControl:!!(s!=null&&s.supportsRemoteControl),screenShare:!!(s!=null&&s.screenShare)},remotelyPaused:l,producerId:c}}),{};const h=s;return i==="video"&&h.screenShare!==!0&&this.videoPeerConsumerMap.set(r,t),p.info("ParticipantController::processMedia",{consumer:{id:t,peerId:r,kind:i,appData:h,remotelyPaused:l,producerId:c}}),this.consumerPeerMap.set(t,{type:i,peerId:r,appData:h,remotelyPaused:l,producerId:c}),{peerId:r,kind:i,appData:h,remotelyPaused:l,track:a,producerId:c,rtpReceiver:d}}processConsumerClosed(t){const{peerId:e,type:n,appData:r,remotelyPaused:i,producerId:s}=this.consumerPeerMap.get(t)||{},a=this.participants.joined.get(e);if(p.info("ParticipantController::processConsumerClosed",{consumer:{id:t,peerId:e,appData:r,kind:n,remotelyPaused:i,producerId:s}}),this.consumerPeerMap.delete(t),n==="video"&&r.screenShare!==!0&&this.videoPeerConsumerMap.delete(e),!a)return;const c=[];r&&r.screenShare?(a.setScreenShareEnabled(!1),J.consumerSharedMediaState(t,{screen:!1}),a.screenShareTracks.video&&c.push(a.screenShareTracks.video.id),a.screenShareTracks.audio&&c.push(a.screenShareTracks.audio.id),a.screenShareTracks={audio:void 0,video:void 0}):n==="audio"?(a.setAudioEnabled(!1),a.audioTrack&&c.push(a.audioTrack.id),J.consumerSharedMediaState(t,{audio:!1}),a.audioTrack=void 0):n==="video"&&(a.setVideoEnabled(!1),this.updatePipSource(a.id,!1),a.videoTrack&&c.push(a.videoTrack.id),J.consumerSharedMediaState(t,{video:!1}),a.videoTrack=void 0),r.e2ee&&c.forEach(d=>{P.emit(R.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:d})})}processConsumerResumed(t){const{peerId:e,kind:n,appData:r,track:i,remotelyPaused:s,producerId:a,rtpReceiver:c}=this.processMedia(t);if(!e)return;p.info("ParticipantController::processConsumerResumed",{consumer:{id:t,peerId:e,kind:n,appData:r,remotelyPaused:s,producerId:a}});const d=this.participants.joined.get(e);if(d){if(r.e2ee&&P.emit(R.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:i}),r.screenShare){n==="video"?d.screenShareTracks.video=i:n==="audio"&&(d.screenShareTracks.audio=i),d.setScreenShareEnabled(!0),J.consumerSharedMediaState(t,{screen:!0});return}n==="video"?(d.videoTrack=i,d.setVideoEnabled(!0),this.updatePipSource(d.id,!0),J.consumerSharedMediaState(t,{video:!0})):n==="audio"&&(d.audioTrack=i,d.setAudioEnabled(d.audioEnabled),J.consumerSharedMediaState(t,{audio:d.audioEnabled}))}}processConsumerPaused(t){p.info(`ParticipantController::processConsumerPaused called for consumerId: ${t}`);const{peerId:e,kind:n,track:r,appData:i,remotelyPaused:s,producerId:a}=this.processMedia(t);if(!e)return;p.info("ParticipantController::processConsumerPaused",{consumer:{id:t,peerId:e,kind:n,appData:i,remotelyPaused:s,producerId:a}});const c=this.participants.joined.get(e);c&&(r&&i.e2ee&&P.emit(R.E2EE_INACTIVE_CONSUMER,{peerId:e,trackId:r.id}),n==="video"?(c.videoTrack=r,c.setVideoEnabled(!1),this.updatePipSource(c.id,!1),J.consumerSharedMediaState(t,{video:!1})):n==="audio"&&(c.audioTrack=r,c.setAudioEnabled(c.audioEnabled),J.consumerSharedMediaState(t,{audio:c.audioEnabled})))}processNewConsumer(t){const{peerId:e,kind:n,remotelyPaused:r,track:i,appData:s,producerId:a,rtpReceiver:c}=this.processMedia(t);if(!e)return;p.info("ParticipantController::processNewConsumer",{consumer:{id:t,peerId:e,kind:n,remotelyPaused:r,appData:s,producerId:a}});const d=this.participants.joined.get(e);if(d){if(s.screenShare){n==="video"?d.screenShareTracks.video=i:n==="audio"&&(d.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder||X.hasFeature(ie.SCREEENSHARE_ERR_HACK))&&d.setScreenShareEnabled(!0),s.supportsRemoteControl&&(d.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:a,peerId:e,screenShare:!0,consumerId:t,consumerPeerId:this.self.id}),p.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:t,peerId:e,kind:n,remotelyPaused:r,appData:s,producerId:a}});return}n==="video"?(d.videoTrack=i,r||(d.setVideoEnabled(!0),this.updatePipSource(d.id,!0)),J.consumerSharedMediaState(t,{video:!r})):n==="audio"&&(d.audioTrack=i,r||d.setAudioEnabled(!0),J.consumerSharedMediaState(t,{audio:!r})),!r&&s.e2ee&&P.emit(R.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:c,track:i})}}static formatSocketServiceMessage(t){var e,n,r,i,s,a;if(!t)return;const c=lh(t.stageType);return{id:t.peerId,userId:t.userId,name:t.displayName,displayName:t.displayName,stageType:c,customParticipantId:t.customParticipantId,presetId:t.presetId,picture:t.displayPictureUrl,waitlisted:t.waitlisted,stageStatus:c,metadata:{preset_name:(e=t.flags)==null?void 0:e.presetName},recorderType:(n=t.flags)==null?void 0:n.recorderType,flags:{hiddenParticipant:(r=t.flags)==null?void 0:r.hiddenParticipant,hidden_participant:(i=t.flags)==null?void 0:i.hiddenParticipant,recorder:((s=t.flags)==null?void 0:s.recorderType)!==void 0&&((a=t.flags)==null?void 0:a.recorderType)!=="NONE"}}}mapPeerIdsToProducers(t,e){const n=(r,i)=>r.filter(({kind:s,screenShare:a})=>i.includes(s)||a&&i.includes("screenshare"));return t.flatMap(r=>{const i=this.participants.joined.get(r);if(i)return n(i.producers,e)}).filter(r=>!!r)}updateGrid(t,e){let n=[],r=[],i=[],s=[];return e.video&&([n,i]=e.video(this.participants.videoSubscribed,t)),e.audio&&([r,s]=e.audio(this.participants.audioSubscribed,t)),{video:{add:n,remove:i},audio:{add:r,remove:s}}}onSelectedPeers(t,e){return u(this,null,function*(){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(t,e)})}updateActiveParticipantsWithPriorities(t,e=!1){if(!this.mediaJoined){p.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}t.forEach(r=>{this.selectedPeers.add(r.peerId,r.priority)});const n=this.selectedPeers.activeSpeakerPeers.at(0);n!==void 0&&n!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=n,this.participants.emit("activeSpeaker",{peerId:n,volume:1})),e&&(this.participants.viewMode==="ACTIVE_GRID"?this.updateActive("ACTIVE_GRID"):this.participants.viewMode==="PAGINATED"&&this.updateActive("ACTIVE_GRID",{strategies:{audio:this.updateParticipantsMap.bind(this)}}))}};let rr=Ty;ki([S.trace("ParticipantController.setupEvents")],rr.prototype,"setupEvents",1),ki([S.trace("ParticipantController.setupEvents")],rr.prototype,"setupEventsGlobal",1),ki([S.trace("ParticipantController.processMedia")],rr.prototype,"processMedia",1),ki([S.trace("ParticipantController.processConsumerClosed")],rr.prototype,"processConsumerClosed",1),ki([S.trace("ParticipantController.processConsumerResumed")],rr.prototype,"processConsumerResumed",1),ki([S.trace("ParticipantController.processConsumerPaused")],rr.prototype,"processConsumerPaused",1),ki([S.trace("ParticipantController.processNewConsumer")],rr.prototype,"processNewConsumer",1);const be=gn(Iu().permissions);var q,za,Ya,Mh,xt,zt;const Qa=class extends jt{constructor(t,e,n,r=!1){if(super(),f(this,xt),f(this,q,void 0),f(this,za,void 0),f(this,Ya,void 0),f(this,Mh,i=>{var s,a,c;const d=i,{chat:l,connectedMeetings:h,plugins:m,polls:y,media:T}=d,b=fc(d,["chat","connectedMeetings","plugins","polls","media"]);if(l&&(l.private&&fr(o(this,q).chat.private,l.private),l.public&&fr(o(this,q).chat.public,l.public),this.emit("chatUpdate")),h&&fr(o(this,q).connectedMeetings,h),T){const O=F=>{switch(F){case Tr.NONE:return Y.Allowed;case Tr.ALLOWED:return Y.Allowed;case Tr.NOT_ALLOWED:return Y.NotAllowed;case Tr.CAN_REQUEST:return Y.CanRequest;default:return}},M={audio:void 0,video:void 0,screenshare:void 0};(s=T.audio)!=null&&s.canProduce&&(M.audio={canProduce:O(T.audio.canProduce)}),(a=T.video)!=null&&a.canProduce&&(M.video={canProduce:O(T.video.canProduce)}),(c=T.screenshare)!=null&&c.canProduce&&(M.screenshare={canProduce:O(T.screenshare.canProduce)}),fr(o(this,q).media,M)}m&&(fr(o(this,q).plugins,m),this.emit("pluginsUpdate")),y&&(fr(o(this,q).polls,y),this.emit("pollsUpdate")),Object.keys(b).length!==0&&fr(o(this,q),b),this.emit("permissionsUpdate",i)}),!e)throw p.error("DytePermissionsPreset::load_preset_permissions_failed"),new _("Could not load preset permissions.","0904");v(this,Ya,t),v(this,za,n),v(this,q,e),r&&this.setupEvents()}setupEvents(){P.on(R.UPDATE_PERMISSIONS,o(this,Mh))}static fromResponse(t,e,n){return new Qa(n,t,e,!0)}static default(t,e){return new Qa(t,be,e)}static init(t,e,n){let r;return n?r=new Qa(t,n,e,!0):r=new Qa(t,be,e),r}get mediaRoomType(){const{sfu:t}=o(this,Ya).getValue("roomNodeOptions");return t===tt.CF?"CF":"HIVE"}get stageEnabled(){var t;return((t=o(this,q))==null?void 0:t.stageEnabled)||o(this,za)===yt.Webinar||o(this,za)===yt.Livestream}get acceptStageRequests(){var t,e;return this.stageEnabled?((t=o(this,q))==null?void 0:t.acceptStageRequests)||((e=o(this,q))==null?void 0:e.canAcceptProductionRequests):!1}get stageAccess(){var t,e,n;return((t=o(this,q))==null?void 0:t.stageAccess)===Y.NotAllowed?Y.NotAllowed:((e=o(this,q))==null?void 0:e.stageAccess)===Y.CanRequest?Y.CanRequest:((n=o(this,q))==null?void 0:n.stageAccess)===Y.Allowed||o(this,q).media.audio.canProduce===Y.Allowed||o(this,q).media.video.canProduce===Y.Allowed||o(this,q).media.screenshare.canProduce===Y.Allowed?Y.Allowed:o(this,q).media.audio.canProduce===Y.CanRequest||o(this,q).media.video.canProduce===Y.CanRequest||o(this,q).media.screenshare.canProduce===Y.CanRequest?Y.CanRequest:Y.NotAllowed}get acceptWaitingRequests(){var t,e;return(e=(t=o(this,q))==null?void 0:t.acceptWaitingRequests)!=null?e:be.acceptWaitingRequests}get requestProduceVideo(){var t,e,n;return((n=(e=(t=o(this,q))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:n.canProduce)===Y.CanRequest}get requestProduceAudio(){var t,e,n;return((n=(e=(t=o(this,q))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:n.canProduce)===Y.CanRequest}get requestProduceScreenshare(){var t,e,n;return((n=(e=(t=o(this,q))==null?void 0:t.media)==null?void 0:e.screenshare)==null?void 0:n.canProduce)===Y.CanRequest}get canAllowParticipantAudio(){var t,e;return(e=(t=o(this,q))==null?void 0:t.disableParticipantAudio)!=null?e:be.disableParticipantAudio}get canAllowParticipantScreensharing(){var t,e;return(e=(t=o(this,q))==null?void 0:t.canAcceptProductionRequests)!=null?e:be.canAcceptProductionRequests}get canAllowParticipantVideo(){var t,e;return(e=(t=o(this,q))==null?void 0:t.disableParticipantVideo)!=null?e:be.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var t,e;return(e=(t=o(this,q))==null?void 0:t.kickParticipant)!=null?e:be.kickParticipant}get pinParticipant(){var t,e;return(e=(t=o(this,q))==null?void 0:t.pinParticipant)!=null?e:be.pinParticipant}get canRecord(){var t,e;return(e=(t=o(this,q))==null?void 0:t.canRecord)!=null?e:be.canRecord}get waitingRoomType(){var t,e;return(e=(t=o(this,q))==null?void 0:t.waitingRoomType)!=null?e:be.waitingRoomType}get waitingRoomBehaviour(){var t,e;return(e=(t=o(this,q))==null?void 0:t.waitingRoomType)!=null?e:be.waitingRoomType}get plugins(){var t,e;return(e=(t=o(this,q))==null?void 0:t.plugins)!=null?e:be.plugins}get polls(){var t,e;return(e=(t=o(this,q))==null?void 0:t.polls)!=null?e:be.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return o(this,q).media.audio.canProduce===Y.CanRequest||o(this,q).media.video.canProduce===Y.CanRequest||o(this,q).media.screenshare.canProduce===Y.CanRequest}get canProduceVideo(){var t;const e=(t=o(this,q).media.video.canProduce)!=null?t:be.media.video.canProduce;return this.stageEnabled&&(o(this,xt,zt)==="ACCEPTED_TO_JOIN_STAGE"||o(this,xt,zt)==="ON_STAGE")&&e===Y.CanRequest?Y.Allowed:this.stageEnabled&&(o(this,xt,zt)==="OFF_STAGE"||o(this,xt,zt)==="REQUESTED_TO_JOIN_STAGE")&&e===Y.Allowed?Y.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var t;const e=(t=o(this,q).media.screenshare.canProduce)!=null?t:be.media.screenshare.canProduce;return this.stageEnabled&&(o(this,xt,zt)==="ACCEPTED_TO_JOIN_STAGE"||o(this,xt,zt)==="ON_STAGE")&&e===Y.CanRequest?Y.Allowed:this.stageEnabled&&(o(this,xt,zt)==="OFF_STAGE"||o(this,xt,zt)==="REQUESTED_TO_JOIN_STAGE")&&e===Y.Allowed?Y.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var t;const e=(t=o(this,q).media.audio.canProduce)!=null?t:be.media.audio.canProduce;return this.stageEnabled&&(o(this,xt,zt)==="ACCEPTED_TO_JOIN_STAGE"||o(this,xt,zt)==="ON_STAGE")&&e===Y.CanRequest?Y.Allowed:this.stageEnabled&&(o(this,xt,zt)==="OFF_STAGE"||o(this,xt,zt)==="REQUESTED_TO_JOIN_STAGE")&&e===Y.Allowed?Y.NotAllowed:e}get chatPublic(){var t,e,n;return(n=(e=(t=o(this,q))==null?void 0:t.chat)==null?void 0:e.public)!=null?n:be.chat.public}get chatPrivate(){var t,e,n;return(n=(e=(t=o(this,q))==null?void 0:t.chat)==null?void 0:e.private)!=null?n:be.chat.private}get chatChannel(){var t,e,n;return(n=(e=(t=o(this,q))==null?void 0:t.chat)==null?void 0:e.channel)!=null?n:be.chat.channel}get chatMessage(){var t,e,n;return(n=(e=(t=o(this,q))==null?void 0:t.chat)==null?void 0:e.message)!=null?n:be.chat.message}get connectedMeetings(){var t,e;return(e=(t=o(this,q))==null?void 0:t.connectedMeetings)!=null?e:be==null?void 0:be.connectedMeetings}get hiddenParticipant(){var t,e;return(e=(t=o(this,q))==null?void 0:t.hiddenParticipant)!=null?e:be.hiddenParticipant}get showParticipantList(){var t;return(t=o(this,q).showParticipantList)!=null?t:be.showParticipantList}get canChangeParticipantRole(){var t,e;return(e=(t=o(this,q))==null?void 0:t.canChangeParticipantPermissions)!=null?e:be.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var t,e;return(e=(t=o(this,q))==null?void 0:t.canChangeParticipantPermissions)!=null?e:be.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return o(this,q).media.audio.canProduce===Y.Allowed||o(this,q).media.video.canProduce===Y.Allowed||o(this,q).media.screenshare.canProduce===Y.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var t;return(t=o(this,q).canEditDisplayName)!=null?t:!1}get maxScreenShareCount(){return 1}get isRecorder(){return o(this,q).isRecorder}get canSpotlight(){return o(this,q).canSpotlight}get canLivestream(){return o(this,q).canLivestream}get transcriptionEnabled(){return o(this,q).transcriptionEnabled}};let TN=Qa;q=new WeakMap,za=new WeakMap,Ya=new WeakMap,Mh=new WeakMap,xt=new WeakSet,zt=function(){return o(this,Ya).getValue("stageStatus")};var ky;class kN extends jt{constructor(){super(...arguments),g(this,"localMediaHandler"),f(this,ky,void 0)}updatePermission(){return u(this,null,function*(){var e,n;const r=(l,h)=>{this.mediaPermissions[l]=h;const m={message:this.mediaPermissions[l],kind:l};h==="DENIED"?P.emit(R.MEDIA_PERMISSION_ERROR,m):P.emit(R.MEDIA_PERMISSION_UPDATE,m)};if(Ie.getName()==="firefox")return;const i="microphone",s="camera",a=yield(e=navigator==null?void 0:navigator.permissions)==null?void 0:e.query({name:i}),c=yield(n=navigator==null?void 0:navigator.permissions)==null?void 0:n.query({name:s}),d=(l,h)=>{switch(h){case"granted":r(l,"ACCEPTED");break;case"denied":r(l,"DENIED");break;case"prompt":r(l,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};a&&(a.onchange=()=>d("audio",a.state)),c&&(c.onchange=()=>d("video",c.state))})}populateMediaPermissionsInCallstats(e){return u(this,arguments,function*({message:n,kind:r}){switch(r){case"audio":{J.mediaPermission("AUDIO",n),J.mediaPermission("SPEAKER",n);break}case"video":{J.mediaPermission("VIDEO",n);break}case"screenshare":{J.mediaPermission("SCREENSHARE",n);break}}})}init(){return u(this,arguments,function*(e={},n=!1,r=null){var i,s,a,c,d,l;if(Ie.init(),!this.localMediaHandler)try{let h=!0;if(r!=null&&r.getValue("defaults").mediaHandler)h=!1,this.localMediaHandler=r.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:m}=navigator;this.localMediaHandler=yield m.init()}else this.localMediaHandler=new Lt(r,e.constraints,(i=r==null?void 0:r.getValue("defaults"))==null?void 0:i.isNonPreferredDevice,(s=r==null?void 0:r.getValue("defaults"))==null?void 0:s.autoSwitchAudioDevice);if(P.on(R.MEDIA_PERMISSION_UPDATE,m=>u(this,null,function*(){if(this.populateMediaPermissionsInCallstats({message:m.message,kind:m.kind}),m.message==="NOT_REQUESTED")switch(m==null?void 0:m.kind){case"audio":this.rawAudioTrack&&(p.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(p.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",m)})),P.on(R.MEDIA_PERMISSION_ERROR,m=>u(this,null,function*(){const{kind:y,message:T,constraints:b}=m;this.populateMediaPermissionsInCallstats({message:T,kind:y}),y==="audio"?(p.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):y==="video"&&(p.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),p.error("SelfController::mediaPermissionError",{error:{message:T},constraints:b,mediaPermissionsErrors:{kind:y,message:T}}),this.emit("mediaPermissionError",m),this.emit("mediaPermissionUpdate",{message:T,kind:y})})),h){p.info(`Setting up DyteSelfMedia streams using media handler. audio:${(a=e==null?void 0:e.audio)!=null?a:!0} video:${(c=e==null?void 0:e.video)!=null?c:!0}`);const m=this.localMediaHandler.setupStreams({video:(d=e==null?void 0:e.video)!=null?d:!0,audio:(l=e==null?void 0:e.audio)!=null?l:!0});n||(yield m)}}catch(h){p.error("DyteSelf::init::Failed To Setup Streams",{error:{name:h.name,message:h.message}})}})}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}addAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addAudioMiddleware(e)})}removeAudioMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeAudioMiddleware(e)})}removeAllAudioMiddlewares(){return u(this,null,function*(){return this.localMediaHandler.removeAllAudioMiddlewares()})}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}addVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.addVideoMiddleware(e)})}setVideoMiddlewareGlobalConfig(){return u(this,arguments,function*(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)})}removeVideoMiddleware(e){return u(this,null,function*(){return this.localMediaHandler.removeVideoMiddleware(e)})}removeAllVideoMiddlewares(){return u(this,null,function*(){return this.localMediaHandler.removeAllVideoMiddlewares()})}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}enableAudio(){return u(this,null,function*(){yield this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableVideo(){return u(this,null,function*(){yield this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}disableAudio(){return u(this,null,function*(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})}enableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableScreenShare(){return u(this,null,function*(){yield this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})}disableVideo(){return u(this,null,function*(){yield this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}getAudioDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getAudioDevices()})}getVideoDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getVideoDevices()})}getSpeakerDevices(){return u(this,null,function*(){return yield this.localMediaHandler.getSpeakerDevices()})}getDeviceById(e,n){let r;return n==="audio"?r="audioinput":n==="video"?r="videoinput":n==="speaker"&&(r="audiooutput"),this.localMediaHandler.getDeviceById(e,r)}setDevice(e){return u(this,null,function*(){switch(e.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(e)}catch(n){}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(n){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})})}}ky=new WeakMap;const Xa={},Mr={executeWithLock({methodName:t,lockName:e,timeout:n}){return(r,i,s)=>{const a=s.value;return s.value=function(...c){if(Xa[e]){const h=new Error(`Unsupported concurrent calls on Dyte method: ${t}.`);throw h.name="UnsupportedConcurrentMethodExecution",p.error("DyteLocker::UnsupportedConcurrentMethodExecution",{error:{stack:h.stack},dyteLocker:{methodName:t,lockName:e}}),h}Xa[e]=!0;const d=setTimeout(()=>delete Xa[e],n),l=a.apply(this,c);return Promise.resolve(l).then(()=>{delete Xa[e],clearTimeout(d)}).catch(()=>{delete Xa[e],clearTimeout(d)}),l},s}}};var bN=Object.defineProperty,wN=Object.getOwnPropertyDescriptor,_t=(t,e,n,r)=>{for(var i=r>1?void 0:r?wN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&bN(e,n,i),i},Za,Vt,eo,ir,bi,Is,nt,ct,Ke,Ye,to,no,Od,Ah,by;let rt=(by=class extends kN{constructor(t,e,n,r,i){var s;super(),f(this,bi),f(this,nt),f(this,Ke),f(this,Od),g(this,"name"),g(this,"picture"),g(this,"customParticipantId"),g(this,"waitlistStatus"),f(this,Za,void 0),f(this,Vt,void 0),f(this,eo,void 0),g(this,"role"),g(this,"userId"),g(this,"organizationId"),g(this,"supportsRemoteControl",!1),g(this,"device"),f(this,ir,void 0),g(this,"hidden",!1),g(this,"presetName"),g(this,"roomState","init"),f(this,to,new Set),f(this,no,new Set),v(this,ir,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(s=e.customParticipantId)!=null?s:e.clientSpecificId,this.waitlistStatus="none",v(this,Vt,n),v(this,Za,r),this.hidden=!1,v(this,eo,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Ie.isElectron(),this.device=Ie.getDeviceInfo(),this.presetName=i,r.viewType!==yt.Chat&&this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),H(this,Od,Ah).call(this)}get stageStatus(){return o(this,ir).getValue("stageStatus")}get id(){return o(this,ir).getValue("peerId")}static __init__(t,e,n,r,i,s=!1){return u(this,null,function*(){var a,c,d,l,h;let m=(c=(a=t.getValue("defaults"))==null?void 0:a.audio)!=null?c:!0,y=(l=(d=t.getValue("defaults"))==null?void 0:d.video)!=null?l:!0;n.canProduceAudio!=="ALLOWED"&&(m=!1),n.canProduceVideo!=="ALLOWED"&&(y=!1);const T=new rt(t,e,n,r,i);if(r.viewType===yt.Chat)return T;const b=AO(r.mediaConstraints);return fr(b,(h=t.getValue("defaults"))==null?void 0:h.mediaConfiguration),yield T.init({audio:m,video:y,constraints:b},s,t),T.setupEvents(),T})}cleanupEvents(){this.removeAllListeners("videoUpdate"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("VIDEO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_LIST_UPDATED"),this.localMediaHandler.removeAllListeners("SCREENSHARE_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("SCREENSHARE_ENDED"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_SILENT"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_AUDIO"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_VIDEO"),o(this,Vt).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",H(this,Od,Ah)),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",()=>u(this,null,function*(){if(p.info("DyteSelf::setupEvents::AUDIO_TRACK_CHANGE",x({},yi(this))),o(this,Ke,Ye)&&this.audioEnabled)try{yield o(this,nt,ct).shareMic(this.audioTrack)}catch(t){p.error("DyteSelf::setupEvents::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})})),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",()=>u(this,null,function*(){if(p.info("DyteSelf::setupEvents::VIDEO_TRACK_CHANGE",x({},yi(this))),o(this,Ke,Ye)&&this.rawVideoTrack===void 0)p.info("DyteSelf::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&o(this,Ke,Ye))try{const t=yield o(this,nt,ct).shareWebcam(this.videoTrack);t&&t.id!==this.videoTrack.id&&X.hasFeature(ie.EXP_RESHARE)&&(yield o(this,nt,ct).shareWebcam(this.videoTrack))}catch(t){p.error("DyteSelf::setupEvents::failed shareWebcam",{error:t}),this.videoEnabled&&(yield this.localMediaHandler.disableVideo())}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})})),this.localMediaHandler.on("DEVICE_CHANGE",t=>u(this,[t],function*({device:e}){this.emit("deviceUpdate",{device:e})})),this.localMediaHandler.on("DEVICE_LIST_UPDATED",t=>{this.emit("deviceListUpdate",t)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",()=>u(this,null,function*(){if(!o(this,Ke,Ye)){p.error("DyteSelf.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{yield o(this,nt,ct).shareScreen(this.screenShareTracks)}catch(t){p.error("DyteSelf::setupEvents::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}p.info("DyteSelf::setupEvents::SCREENSHARE_TRACK_CHANGE",x({},yi(this))),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})})),this.localMediaHandler.on("SCREENSHARE_ENDED",()=>u(this,null,function*(){p.log("Disabling screenshare due to SCREENSHARE_ENDED"),yield this.disableScreenShare(),p.info("DyteSelf::setupEvents::SCREENSHARE_ENDED",x({},yi(this)))})),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{J.mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",()=>u(this,null,function*(){o(this,Ke,Ye)&&(yield o(this,nt,ct).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),J.videoOff()})),o(this,Vt).on("permissionsUpdate",t=>{var e,n,r;(e=t==null?void 0:t.media)!=null&&e.audio&&o(this,Vt).canProduceAudio!==Y.Allowed&&(this.disableAudio(),p.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(n=t==null?void 0:t.media)!=null&&n.video&&o(this,Vt).canProduceVideo!==Y.Allowed&&(this.disableVideo(),p.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(r=t==null?void 0:t.media)!=null&&r.screenshare&&o(this,Vt).canProduceScreenshare!==Y.Allowed&&(this.disableScreenShare(),p.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return o(this,Vt)}get config(){return o(this,Za)}get roomJoined(){var t;return o(this,Za).viewType===yt.Livestream&&this.stageStatus!=="ON_STAGE"?((t=o(this,ir).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:o(this,Ke,Ye)}setName(t){if(!t)throw new _("Name cannot be empty.","1103");this.name=t}setupTracks(){return u(this,arguments,function*(t={}){t.forceReset,yield this.disableAudio(),yield this.disableVideo(),this.localMediaHandler.removeAudioTrack(),this.localMediaHandler.removeVideoTrack(),t.audio&&(yield this.enableAudio()),t.video&&(yield this.enableVideo())})}destructMediaHandler(){return u(this,null,function*(){return this.localMediaHandler.destruct()})}removeDocumentEventListeners(){return u(this,null,function*(){return this.localMediaHandler.removeDocumentEventListeners()})}enableAudio(){return u(this,null,function*(){if(this.permissions.canProduceAudio!==Y.NotAllowed&&!(o(this,Vt).canProduceAudio===Y.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if(J.audioOn(),yield this.localMediaHandler.enableAudio(),o(this,Ke,Ye)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{yield o(this,nt,ct).shareMic(this.audioTrack)}catch(t){p.error("DyteSelf::enableAudio::Error while sharing mic",{error:t}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return;o(this,nt,ct).unmuteSelf()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}})}enableVideo(){return u(this,null,function*(){if(o(this,Vt).canProduceVideo!==Y.NotAllowed&&!(o(this,Vt).canProduceVideo===Y.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if(J.videoOn(),yield this.localMediaHandler.enableVideo(),o(this,Ke,Ye)&&this.stageStatus==="ON_STAGE")try{yield o(this,nt,ct).shareWebcam(this.videoTrack)}catch(t){p.error("DyteSelf::enableVideo::Error while sharing video",{error:t}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),p.info("DyteSelf.enableVideo",x({},yi(this)))}})}updateVideoConstraints(t){return u(this,null,function*(){if(!this.localMediaHandler.updateVideoConstraints)throw new _("Unsupported","1102");yield this.localMediaHandler.updateVideoConstraints(t)})}enableScreenShare(){return u(this,null,function*(){if(!o(this,Ke,Ye))throw new _("Can`t enable screenshare without joining room","1105");if(o(this,Vt).canProduceScreenshare!==Y.NotAllowed&&!(o(this,Vt).canProduceScreenshare===Y.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(yield this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{yield o(this,nt,ct).shareScreen(this.screenShareTracks)}catch(t){p.error("DyteSelf::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare())}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}})}updateScreenshareConstraints(t){return u(this,null,function*(){if(!this.localMediaHandler.updateScreenshareConstraints)throw new _("Unsupported","1102");yield this.localMediaHandler.updateScreenshareConstraints(t)})}disableAudio(){return u(this,null,function*(){this.audioEnabled&&(this.localMediaHandler.disableAudio(),o(this,Ke,Ye)&&o(this,nt,ct).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),J.audioOff())})}disableVideo(){return u(this,null,function*(){this.videoEnabled&&(yield this.localMediaHandler.disableVideo(),o(this,Ke,Ye)&&(yield o(this,nt,ct).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),J.videoOff())})}disableScreenShare(){return u(this,null,function*(){this.screenShareEnabled&&(yield this.localMediaHandler.disableScreenShare(),o(this,Ke,Ye)&&(yield o(this,nt,ct).disableScreenShare()),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))})}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var n;v(this,eo,t);const r=t?"pinned":"unpinned";(n=o(this,bi,Is))==null||n.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return o(this,eo)}pin(){return u(this,null,function*(){if(!o(this,Ke,Ye))throw new _("Can`t pin participants without joining room","1105");return this.show(),o(this,nt,ct).pinPeer(this.id)})}unpin(){return u(this,null,function*(){if(!o(this,Ke,Ye))throw new _("Can`t unpin participants without joining room","1105");return o(this,nt,ct).pinPeer(null)})}hide(){return u(this,null,function*(){if(!o(this,Ke,Ye))throw new _("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})})}show(){if(!o(this,Ke,Ye))throw new _("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}setDevice(t){return u(this,null,function*(){var e,n,r;if(!t)throw new _("No device selected","1104");const i=this.getCurrentDevices();if(t.deviceId&&(((e=i==null?void 0:i.audio)==null?void 0:e.deviceId)===t.deviceId||((n=i==null?void 0:i.video)==null?void 0:n.deviceId)===t.deviceId||((r=i==null?void 0:i.speaker)==null?void 0:r.deviceId)===t.deviceId)&&(p.warn("DyteSelf.setDevice.setting_to_in_use_device",{devices:[t]}),X.hasFeature(ie.SKIP_SETTING_IN_USE_DEVICE)))throw new _("Cannot set device currently in use","1106");switch(t.kind){case"audioinput":try{yield this.localMediaHandler.setAudioDevice(t)}catch(s){o(this,Ke,Ye)&&(yield o(this,nt,ct).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(s){o(this,Ke,Ye)&&(yield o(this,nt,ct).pauseWebcam()),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}})}cleanUpTracks(){var t,e,n,r;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(n=this.videoTrack)==null||n.stop(),(r=this.rawVideoTrack)==null||r.stop()}registerVideoElement(t,e=!1){var n,r;e?o(this,to).add(t):o(this,no).add(t),this.updateVideo(t),e||(r=o(this,bi,Is))==null||r.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t,e=!1){t.srcObject=void 0,e?o(this,to).delete(t):(o(this,no).delete(t),o(this,bi,Is).removeSource(this.id))}updateVideo(t,e=!1){var n,r,i;if(this.videoEnabled){if(this.videoTrack==null)return;const s=(n=t.srcObject)==null?void 0:n.getTracks()[0];if((s==null?void 0:s.id)===this.videoTrack.id)return;const a=new MediaStream;a.addTrack(this.videoTrack),t.srcObject=a,e||(r=o(this,bi,Is))==null||r.enableSource(this.id)}else t.srcObject=void 0,e||(i=o(this,bi,Is))==null||i.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},Za=new WeakMap,Vt=new WeakMap,eo=new WeakMap,ir=new WeakMap,bi=new WeakSet,Is=function(){return o(this,ir).getValue("pip")},nt=new WeakSet,ct=function(){return o(this,ir).getValue("roomNodeClient")},Ke=new WeakSet,Ye=function(){var t;return((t=o(this,ir).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},to=new WeakMap,no=new WeakMap,Od=new WeakSet,Ah=function(){Array.from(o(this,no)).forEach(t=>this.updateVideo(t,!1)),Array.from(o(this,to)).forEach(t=>this.updateVideo(t,!0))},by);_t([S.trace("DyteSelf.cleanupEvents")],rt.prototype,"cleanupEvents",1),_t([S.trace("DyteSelf.setupEvents")],rt.prototype,"setupEvents",1),_t([S.trace("DyteSelf.setupTracks")],rt.prototype,"setupTracks",1),_t([S.trace("DyteSelf.destructMediaHandler")],rt.prototype,"destructMediaHandler",1),_t([S.trace("DyteSelf.removeDocumentEventListeners")],rt.prototype,"removeDocumentEventListeners",1),_t([Mr.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),S.trace("DyteSelf.enableAudio")],rt.prototype,"enableAudio",1),_t([Mr.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),S.trace("DyteSelf.enableVideo")],rt.prototype,"enableVideo",1),_t([S.trace("DyteSelf.updateVideoConstraints")],rt.prototype,"updateVideoConstraints",1),_t([S.trace("DyteSelf.enableScreenShare"),Mr.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3})],rt.prototype,"enableScreenShare",1),_t([S.trace("DyteSelf.updateScreenshareConstraints")],rt.prototype,"updateScreenshareConstraints",1),_t([Mr.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"DyteSelf.toggleAudio",timeout:3e3}),S.trace("DyteSelf.disableAudio")],rt.prototype,"disableAudio",1),_t([Mr.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"DyteSelf.toggleVideo",timeout:3e3}),S.trace("DyteSelf.disableVideo")],rt.prototype,"disableVideo",1),_t([Mr.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"DyteSelf.toggleScreenShare",timeout:3e3}),S.trace("DyteSelf.disableScreenShare")],rt.prototype,"disableScreenShare",1),_t([S.trace("DyteSelf.setDevice")],rt.prototype,"setDevice",1),rt=_t([ht("1100")],rt);var _N=Object.defineProperty,IN=Object.getOwnPropertyDescriptor,CN=(t,e,n,r)=>{for(var i=r>1?void 0:r?IN(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&_N(e,n,i),i};let Cs;var Nd,wy;const _y=(wy=class{constructor(t,e){g(this,"socket"),f(this,Nd,void 0),v(this,Nd,e),this.socket=t,this.handleSocketEvents()}static create(t,e){return Cs||(Cs=new _y(t,e)),Cs}static cleanup(){var t;try{(t=Cs==null?void 0:Cs.socket)==null||t.disconnect()}catch(e){p.error("roomSocketHandler::cleanup")}Cs=void 0}joinRoom(t){return u(this,null,function*(){var e;this.socket.joinAttempted=!0;const n={capabilities:[],peer:{displayName:(e=t.name)!=null?e:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(W.joinRoom,FR.toBinary(n));try{const{peer:i}=ts.fromBinary((yield r).payload);o(this,Nd).getValue("connectionHandler").socketJoined=!0,P.emit(R.SOCKET_SERVICE_ROOM_JOINED,{peer:i});const s=this.getRoomState(),a=this.getRoomPeersNonPaginated(),[{room:c},{peers:d}]=yield Promise.all([s,a]);return P.emit(R.ROOM_STATE,c),P.emit(R.SOCKET_PEERS,d),{peer:i}}catch(i){throw p.error("RoomSocketHandler.joinRoom.failed",{error:i}),new _("Error: RoomSocketHandler.joinRoom failed.","0002",i)}})}getAllAddedParticipants(){return u(this,null,function*(){try{return bM.fromBinary((yield this.socket.sendMessagePromise(W.getAllAddedParticipants)).payload).participants.map(t=>{var e=t,{id:n}=e,r=fc(e,["id"]);return G(x({},r),{userId:n})})}catch(t){return[]}})}getRoomPeers(t,e,n){return u(this,null,function*(){let r;try{const i={seachQuery:t,limit:e,offset:n},s=yield this.socket.sendMessagePromise(W.getRoomPeersInfo,RR.toBinary(i));r=Fu.fromBinary(s.payload)}catch(i){p.error("getRoomPeers::binary_decode_error",{error:i})}return r})}getRoomPeersNonPaginated(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(W.getRoomPeersInfo);t=Fu.fromBinary(e.payload)}catch(e){p.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(W.getRoomPeersInfo);t=Fu.fromBinary(e.payload)}catch(e){p.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return u(this,null,function*(){let e;try{const n=yield this.socket.sendMessagePromise(W.getPeerInfo,mv.toBinary({peerId:t}));e=ts.fromBinary(n.payload)}catch(n){p.error("getPeerInfo::binary_decode_error",{error:n})}return e})}getRoomState(){return u(this,null,function*(){let t=pv.create();try{const e=yield this.socket.sendMessagePromise(W.getRoomInfo);t=pv.fromBinary(e.payload)}catch(e){p.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=Sv.create();try{const e=yield this.socket.sendMessagePromise(W.getRoomStageState);t=Sv.fromBinary(e.payload)}catch(e){p.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return u(this,null,function*(){const n={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(W.broadcastMessage,ha.toBinary(n))})}broadcastToMeetings(t,e,n){return u(this,null,function*(){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(n)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(W.broadcastToEntity,ha.toBinary(r))})}broadcastToPeers(t,e,n){return u(this,null,function*(){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(n)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(W.broadcastToEntity,ha.toBinary(r))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(W.leaveRoom,WR.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(W.kick,CM.toBinary(e))})}kickAll(t=!1){return u(this,null,function*(){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(W.kickAll,rv.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage(W.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(W.acceptWaitingRoomRequests,MM.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(W.denyWaitingRoomRequests,DM.toBinary(e))}updatePermissions(t,e){return u(this,null,function*(){const n={updatePeersPresets:[]};return t.forEach(r=>{n.updatePeersPresets.push({userIds:r,patch:e})}),this.socket.sendMessagePromise(rd.updateUserPreset,oA.toBinary(n))})}handleSocketEvents(){this.socket.on(W.broadcastMessage,({payload:t})=>{try{const e=ha.fromBinary(t);P.emit(R.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){p.error("failed to decode broadcast message:",e)}}),this.socket.on(W.broadcastToEntity,({payload:t})=>{try{const e=ha.fromBinary(t);P.emit(R.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){p.error("failed to decode peer broadcast message:",e)}})}on(t,e){let n,r;switch(t){case W.joinRoom:case W.leaveRoom:case W.kick:case W.kickAll:{n=ts.fromBinary.bind(ts),r=ts.create();break}case W.getWaitingRoomRequests:{n=(i,s)=>i?yv.fromBinary(i,s):{requests:[]},r=yv.create();break}case W.recordingPaused:case W.recordingStarted:case W.recordingStopped:{n=Av.fromBinary.bind(Av);break}case rd.updateUserPreset:{n=Tv.fromBinary.bind(Tv);break}case pn.peerJoinedBroadcast:case en.peerJoinedBroadcast:{n=av.fromBinary.bind(av);break}case pn.selfJoinComplete:case en.selfJoinComplete:{n=Nu.fromBinary.bind(Nu);break}case pn.globalPeerPinBroadcast:case en.globalPeerPinBroadcast:{n=dv.fromBinary.bind(dv);break}case pn.selectedPeer:case en.selectedPeer:{n=Ou.fromBinary.bind(Ou);break}case pn.selectedPeerDiff:case en.selectedPeerDiff:{n=sv.fromBinary.bind(sv);break}case pn.leaveRoom:case en.leaveRoom:{n=Lu.fromBinary.bind(Lu);break}}this.socket.on(t,({payload:i})=>{let s=r;if(!n)return e(void 0);try{s=n(i)}catch(a){p.error("roomSocketHandler::on::binary_decode_error",{error:a})}return e(s)})}getUserPermissions(t){return u(this,null,function*(){const e={userIds:[t]};try{const n=yield this.socket.sendMessagePromise(rd.getUserPresets,eA.toBinary(e)),r=iA.fromBinary(n.payload).peerPresets[0],i=new TextDecoder().decode(r.preset),s=JSON.parse(i).permissions;return{chat:s.chat,polls:s.polls,plugins:s.plugins}}catch(n){throw p.error("Error in getting user preset",{error:n}),n}})}},Nd=new WeakMap,wy);let Ld=_y;CN([S.trace("RoomSocketHandler.joinRoom")],Ld.prototype,"joinRoom",1);var wi={},xd={};Object.defineProperty(xd,"__esModule",{value:!0}),xd.Logger=void 0;class PN{constructor(e){}debug(){}warn(){}error(){}}xd.Logger=PN,Object.defineProperty(wi,"__esModule",{value:!0});var Vd=wi.AwaitQueue=wi.AwaitQueueRemovedTaskError=wi.AwaitQueueStoppedError=void 0;const RN=xd,Ar=new RN.Logger;class Dh extends Error{constructor(e){super(e!=null?e:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Dh)}}wi.AwaitQueueStoppedError=Dh;class Ud extends Error{constructor(e){super(e!=null?e:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Ud)}}wi.AwaitQueueRemovedTaskError=Ud;class MN{constructor(){this.pendingTasks=new Map,this.nextTaskId=0,this.stopping=!1}get size(){return this.pendingTasks.size}push(e,n){return u(this,null,function*(){if(n=n!=null?n:e.name,Ar.debug(`push() [name:${n}]`),typeof e!="function")throw new TypeError("given task is not a function");if(n)try{Object.defineProperty(e,"name",{value:n})}catch(r){}return new Promise((r,i)=>{const s={id:this.nextTaskId++,task:e,name:n,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(s.completed)return;s.completed=!0,this.pendingTasks.delete(s.id),Ar.debug(`resolving task [name:${s.name}]`),r(a);const[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)},reject:a=>{if(!s.completed&&(s.completed=!0,this.pendingTasks.delete(s.id),Ar.debug(`rejecting task [name:${s.name}]: %s`,String(a)),i(a),!this.stopping)){const[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)}}};this.pendingTasks.set(s.id,s),this.pendingTasks.size===1&&this.execute(s)})})}stop(){Ar.debug("stop()"),this.stopping=!0;for(const e of this.pendingTasks.values())Ar.debug(`stop() | stopping task [name:${e.name}]`);this.stopping=!1}remove(e){Ar.debug(`remove() [taskIdx:${e}]`);const n=Array.from(this.pendingTasks.values())[e];if(!n){Ar.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}n.reject(new Ud)}dump(){const e=Date.now();let n=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:n++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:e-r.enqueuedAt,executionTime:r.executedAt?e-r.executedAt:0}))}execute(e){return u(this,null,function*(){if(Ar.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{const n=yield e.task();e.resolve(n)}catch(n){e.reject(n)}})}}Vd=wi.AwaitQueue=MN;function AN(t,e){const n=new Error(e);return n.name=t,n}class ro extends _{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,ro):this.stack=new Error(e).stack}}class Ut extends _{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ut):this.stack=new Error(e).stack}}class _i extends _{constructor(e){super(e),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ut):this.stack=new Error(e).stack}}const Iy=t=>new Promise(e=>setTimeout(e,t));function Oh(t,e){return u(this,null,function*(){return new Promise((n,r)=>u(this,null,function*(){const{strategy:i,maxRetryCount:s,delayTime:a}=x({strategy:"linear",maxRetryCount:3,delayTime:10},e);let c=0,d,l=!1;const h=m=>{l=!0,r(m)};for(;c<s;){try{const m=yield t(c,h);return n(m)}catch(m){if(d=m,l)break;if(c<s)i==="linear"?yield Iy(a*(c+1)):i==="exponential"&&(yield Iy(a*(c+Math.max(0,c-1))));else break}c+=1}return r(d)}))})}function DN(t){return t.map(e=>({channels:e.channels,clockRate:e.clockRate,mimeType:e.mimeType,sdpFmtpLine:e.sdpFmtpLine}))}function ON(t){return t.map(e=>({uri:e.uri}))}function Fd(t){return{codecs:DN(t.codecs),headerExtensions:ON(t.headerExtensions)}}function NN(t){const e=RTCRtpReceiver.getCapabilities("audio"),n=RTCRtpReceiver.getCapabilities("video"),r=RTCRtpSender.getCapabilities("audio"),i=RTCRtpSender.getCapabilities("video");t&&(n.codecs=n.codecs.filter(({mimeType:a})=>t===a),i.codecs=i.codecs.filter(({mimeType:a})=>t===a));const s={audio:Fd(e),video:Fd(n)};return{sender:{audio:Fd(r),video:Fd(i)},receiver:s}}var mt;class LN{constructor(e,n){f(this,mt,void 0),g(this,"events"),g(this,"sfuType"),v(this,mt,e),this.sfuType=n,this.events=n===tt.CF?pn:en}joinRoom(e,n,r,i=!1,s=null){return u(this,null,function*(){const a={roomUuid:e,displayName:n,prejoined:i,capabilities:r};return s&&(a.location=s),(yield o(this,mt).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:BC.toBinary(a),timeout:5e3})).payload})}connectTransport(e){return u(this,null,function*(){const n=(yield o(this,mt).sendMessagePromise(this.events.createWebRTCTransport,gC.toBinary(e))).payload,{transportId:r,description:i,producerIds:s}=Xf.fromBinary(n),a={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:a,producerIds:s}})}produce(e){return u(this,null,function*(){var n,r;const i=(yield o(this,mt).sendMessagePromise(this.events.produce,QC.toBinary(e))).payload,s=NP.fromBinary(i);return{answer:{sdp:(n=s==null?void 0:s.description)==null?void 0:n.sdp,type:(r=s==null?void 0:s.description)==null?void 0:r.type},producerId:s.producerId}})}consume(e){return u(this,null,function*(){if(this.sfuType===tt.HIVE)throw new Error("Hive does not support socket consumer operations");const n=(yield o(this,mt).sendMessagePromise(this.events.consume,zC.toBinary(e))).payload,{consumerIdsMap:{map:r},description:i}=DP.fromBinary(n);return{consumerStateMap:r,sessionDescription:i}})}closeProducer(e){return u(this,null,function*(){const n=(yield o(this,mt).sendMessagePromise(this.events.closeProducer,iP.toBinary(e))).payload,{description:r}=WP.fromBinary(n);return r})}closeConsumer(e){return u(this,null,function*(){if(this.sfuType===tt.HIVE)throw new Error("Hive does not support socket consumer operations");return(yield o(this,mt).sendMessagePromise(this.events.closeConsumer,aP.toBinary(e))).payload})}hostControlForPeer(e,n){return u(this,null,function*(){const r={audio:n==="audio",screeShare:!1,video:n==="video",participantId:e},i=(yield o(this,mt).sendMessagePromise(this.events.hostControlPeer,pP.toBinary(r))).payload;if(!i)return!1;const{status:s}=YP.fromBinary(i);return s==="success"})}hostControlForAll(e){return u(this,null,function*(){const n={audio:e==="audio",screenShare:!1,video:e==="video"},r=(yield o(this,mt).sendMessagePromise(this.events.hostControlAllPeers,gP.toBinary(n))).payload;if(!r)return!1;const{status:i}=XP.fromBinary(r);return i==="success"})}kickAll(){return u(this,null,function*(){const e={propagateKickAcrossRooms:!1},n=(yield o(this,mt).sendMessagePromise(this.events.kickAll,rv.toBinary(e))).payload;if(!n)return!1;const{status:r}=KP.fromBinary(n);return r==="success"})}kickPeer(e){return u(this,null,function*(){const n=(yield o(this,mt).sendMessagePromise(this.events.kickPeer,cP.toBinary(e))).payload;if(!n)return!1;const{status:r}=JP.fromBinary(n);return r==="success"})}changeDisplayName(e){return u(this,null,function*(){const n=(yield o(this,mt).sendMessagePromise(this.events.changeDisplayName,uP.toBinary(e))).payload;if(!n)return!1;const{status:r}=eR.fromBinary(n);return r==="success"})}notifySelfJoinComplete(){return u(this,null,function*(){const e={},n=(yield o(this,mt).sendMessagePromise(this.events.selfJoinComplete,jC.toBinary(e))).payload;return Nu.fromBinary(n)})}audioActivity(e){return u(this,null,function*(){o(this,mt).sendMessage(this.events.audioActivity,vC.toBinary(e))})}}mt=new WeakMap;class io extends ut.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}safeEmit(e,...n){const r=this.listenerCount(e);try{return this.emit(e,...n)}catch(i){return p.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:i}),Boolean(r)}}safeEmitAsPromise(e,...n){return u(this,null,function*(){const r={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,r,...n)})}safeEmitAsPromiseWithTimeout(e,n,...r){return u(this,null,function*(){return new Promise((i,s)=>{setTimeout(s,n,"event request timeout");try{this.emit(e.toString(),...r,i,s)}catch(a){p.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:a}),s(a)}})})}}class Nh extends io{constructor(){super(...arguments),g(this,"_sendWebStream",new MediaStream),g(this,"_sendScreenShareStream",new MediaStream),g(this,"_direction"),g(this,"pc"),g(this,"_transportReady",!1),g(this,"_mapMidTransceiver",new Map),g(this,"enableHighBitrate",!1),g(this,"enableStereo",!1),g(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(p.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){p.error(`${this.name}::pc.close()`,{error:e})}}restartIce(){return u(this,null,function*(){p.debug(`${this.name}::restartIce()`);const e=yield this.pc.createOffer({iceRestart:!0});return p.debug(`${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:n=>u(this,null,function*(){p.info(`${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(n)}]`),yield this.pc.setRemoteDescription(n)})}})}init({direction:e,iceServers:n,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:a}){p.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection(x({iceServers:n||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"},i),s),a&&this.pc.addEventListener("track",c=>{a(c)}),this._addEventListeners()}connect(){return u(this,null,function*(){const e=this.pc.createDataChannel("dyte"),n=yield this.pc.createOffer();return yield this.pc.setLocalDescription(n),p.info(`connect offer: ${JSON.stringify(n)}`),{offerSdp:n,callback:r=>u(this,null,function*(){p.debug(`${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(r)}]`),yield this.pc.setRemoteDescription(r),e.close()})}})}getTransportStats(){return u(this,null,function*(){return this.pc.getStats()})}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}getReceiverStats(e){return u(this,null,function*(){this._assertRecvDirection();const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");return n.receiver.getStats()})}stopSending(e){return u(this,null,function*(){this._assertSendDirection(),p.debug(`stopSending() [localId:${e}]`);const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");n.sender.replaceTrack(null),this.pc.removeTrack(n.sender),n.direction="inactive";const r=yield this.pc.createOffer();return p.debug(`stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(r)}]`),yield this.pc.setLocalDescription(r),{offerSdp:r,callback:i=>u(this,null,function*(){p.debug(`stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),yield this.pc.setRemoteDescription(i),this.midTransceiverMap.delete(e)})}})}replaceTrack(e,n){return u(this,null,function*(){this._assertSendDirection(),n?p.debug(`replaceTrack() [localId:${e}, track.id:${n.id}]`):p.debug(`replaceTrack() [localId:${e}, no track]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");yield r.sender.replaceTrack(n)})}setMaxSpatialLayer(e,n){return u(this,null,function*(){this._assertSendDirection(),p.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${n}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((s,a)=>{a<=n?s.active=!0:s.active=!1}),yield r.sender.setParameters(i)})}setRtpEncodingParameters(e,n){return u(this,null,function*(){this._assertSendDirection(),p.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(n)}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters();i.encodings.forEach((s,a)=>{i.encodings[a]=x(x({},s),n)}),yield r.sender.setParameters(i)})}getSenderStats(e){this._assertSendDirection();const n=this.midTransceiverMap.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");return n.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:p.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),p.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":p.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":p.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:p.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{p.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this.pc.addEventListener("datachannel",e=>{p.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:n}=e;n.onopen=()=>{p.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},n.onclose=()=>{p.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},n.onerror=()=>{p.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class Lh extends Nh{static createFactory(){return()=>new Lh}get name(){return"Chrome74"}init({direction:e,iceServers:n,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:s,onTrackHandler:a}){this._direction=e,this.pc=new RTCPeerConnection(x({iceServers:n||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan"},i),s),a&&this.pc.addEventListener("track",c=>{a(c)}),this._addEventListeners()}send(e){return u(this,arguments,function*({track:n,encodings:r,codecOptions:i,screenShare:s}){this._assertSendDirection();const a=this.pc.addTransceiver(n,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:r});if(!navigator.isReactNative){p.debug("creating new transceiver");const l=RTCRtpSender.getCapabilities(typeof n=="string"?n:n.kind);p.info(`senders available params: ${JSON.stringify(l)}`);const h=[];i&&i.length&&i.forEach(m=>{var y;const T=l.codecs.find(b=>b.mimeType.includes(m.name));if(m.parameters){p.debug(`codecOption.parameters:${JSON.stringify(m.parameters)}`);const b=((y=T.sdpFmtpLine)==null?void 0:y.split(";"))||[];b.push(...m.parameters);const O=Array.from(new Set(b).values());T.sdpFmtpLine=O.join(";")}h.push(T)}),p.info(`selected codecs: ${JSON.stringify(h)}`),a.setCodecPreferences(h)}const c=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(c),i&&i.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
19
- `}this.midTransceiverMap.set(a.mid,a);const d=l=>u(this,null,function*(){return p.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(l)}]`),yield this.pc.setRemoteDescription(l),a.mid});return p.debug(`send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(c,void 0,2)}]`),{offerSdp:c,callback:d,sender:a.sender,mid:a.mid}})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:n}=e;n.onmessage=r=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}class Bd extends Nh{constructor(e){super(),g(this,"supportsSendEncodings",!1),this.supportsSendEncodings=e.supportsSendEncodings}static createFactory(e){return()=>new Bd(e)}get name(){return"Firefox60"}send(e){return u(this,arguments,function*({track:n,encodings:r,codecOptions:i,screenShare:s}){this._assertSendDirection();const a=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(n,x({direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream]},a));if(!this.supportsSendEncodings&&r){r.reverse();const h=c.sender.getParameters();h.encodings=r,yield c.sender.setParameters(h)}const d=(h,m)=>{var y;const T=Kr(h),b=T.media[T.media.length-1],O=b.rtp.filter(K=>m.some(I=>I.name===K.codec)),M=b.fmtp.filter(K=>O.some(I=>I.payload===K.payload)),F=(y=b.rtcpFb)==null?void 0:y.filter(K=>O.some(I=>I.payload===K.payload)),V=O.map(K=>K.payload);return T.media[T.media.length-1].rtp=O,T.media[T.media.length-1].fmtp=M,T.media[T.media.length-1].rtcpFb=F,T.media[T.media.length-1].payloads=V.join(" "),mc(T)},l=yield this.pc.createOffer();if(l.sdp=d(l.sdp,i),p.debug(`send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),yield this.pc.setLocalDescription(l),n==="audio"||n.kind==="audio"){const{enableDtx:h,enableStereo:m}=this,y=this.enableHighBitrate?m?128e3:64e3:m?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${m?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${y}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:h=>u(this,null,function*(){return p.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this.pc.setRemoteDescription(h),c.mid}),sender:c.sender,mid:c.mid}})}setMaxSpatialLayer(e,n){return u(this,null,function*(){this._assertSendDirection(),p.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${n}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters(),s=i.encodings.length-1-n;i.encodings.forEach((a,c)=>{c>=s?a.active=!0:a.active=!1}),yield r.sender.setParameters(i)})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:n}=e;n.onmessage=r=>u(this,null,function*(){const i=yield r.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(i)))})})}}class xh extends Nh{static createFactory(){return()=>new xh}get name(){return"Safari12"}send(e){return u(this,arguments,function*({track:n,encodings:r,codecOptions:i,screenShare:s}){this._assertSendDirection(),p.debug("Safari12::creating new transceiver");const a=this.pc.addTransceiver(n,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:r}),c=RTCRtpSender.getCapabilities(typeof n=="string"?n:n.kind);p.info(`Safari12::senders available params: ${JSON.stringify(c)}`);const d=[];i&&i.length>0&&i.forEach(h=>{var m;const y=c.codecs.find(T=>T.mimeType.includes(h.name));if(h.parameters){p.info(`Safari12::codecOption.parameters:, ${JSON.stringify(h.parameters)}`);const T=((m=y.sdpFmtpLine)==null?void 0:m.split(";"))||[];T.push(...h.parameters);const b=[...new Set(T).values()];y.sdpFmtpLine=b.join(";")}d.push(y)}),p.info(`Safari12::selected codecs: ${JSON.stringify(d)}`),a.setCodecPreferences(d);const l=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(l),n==="audio"||n.kind==="audio"){const{enableStereo:h,enableDtx:m}=this,y=this.enableHighBitrate?h?128e3:64e3:h?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${m?"usedtx=1;":""}${h?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${y}`)}return this.midTransceiverMap.set(a.mid,a),{offerSdp:l,callback:h=>u(this,null,function*(){return p.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this.pc.setRemoteDescription(h),a.mid}),sender:a.sender,mid:a.mid}})}addCustomEventListeners(){this.pc.ondatachannel=e=>{const{channel:n}=e;n.onmessage=r=>u(this,null,function*(){const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",e.channel,i)})}}}function xN(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}var Wd,Ps,sr,ar,Dr,jd,Vh,Uh,Cy,Fh,Py;class VN extends io{constructor(e){var n;super(),f(this,ar),f(this,jd),f(this,Uh),f(this,Fh),g(this,"rtpReceiver"),g(this,"id"),g(this,"localId"),g(this,"producerId"),g(this,"producingTransportId"),g(this,"mimeType"),g(this,"track"),g(this,"peerId"),g(this,"appData"),g(this,"transceiver"),f(this,Wd,void 0),f(this,Ps,void 0),f(this,sr,void 0),this.id=e.id,this.localId=e.localId,v(this,Wd,e.handler),this.appData=e.appData,this.peerId=e.producingPeerId,this.producingTransportId=e.producingTransportId,v(this,sr,!1),this.producerId=e.producerId,this.track=e.track,v(this,Ps,(n=e.paused)!=null?n:!1),this.mimeType=e.mimeType,this.transceiver=e.transceiver,this.rtpReceiver=e.rtpReceiver,H(this,Uh,Cy).call(this)}get closed(){return o(this,sr)}get kind(){return this.track.kind}get paused(){return o(this,Ps)}close(e,n){o(this,sr)||(p.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,o(this,ar,Dr)),v(this,sr,!0),n&&(H(this,Fh,Py).call(this),this.transceiver.stop()),this.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(o(this,sr))throw new Ut("closed");return o(this,Wd).getReceiverStats(this.localId)})}pause(){if(p.debug("consumer::pause()",o(this,ar,Dr)),o(this,sr)){p.error("consumer::pause() | Consumer closed",o(this,ar,Dr));return}v(this,Ps,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(p.debug("consumer::resume()",o(this,ar,Dr)),o(this,sr)){p.error("Consumer::resume() | Consumer closed",o(this,ar,Dr));return}v(this,Ps,!1),this.track.enabled=!0,this.safeEmit("resume")}}Wd=new WeakMap,Ps=new WeakMap,sr=new WeakMap,ar=new WeakSet,Dr=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},jd=new WeakSet,Vh=function(){p.debug('Consumer::track "ended" event',o(this,ar,Dr)),this.safeEmit("trackended")},Uh=new WeakSet,Cy=function(){this.track.addEventListener("ended",H(this,jd,Vh).bind(this))},Fh=new WeakSet,Py=function(){try{this.track.removeEventListener("ended",H(this,jd,Vh)),this.track.stop()}catch(t){p.error("Consumer::destroyTrack()",G(x({},o(this,ar,Dr)),{error:t}))}};var Vn,so,ao,Rs,kn,gt,Ii,oo,sn,bn;class UN extends io{constructor(e){var n,r;super(),f(this,sn),g(this,"id"),g(this,"localId"),f(this,Vn,void 0),g(this,"kind"),g(this,"appData"),g(this,"rtpSender"),f(this,so,void 0),f(this,ao,void 0),f(this,Rs,void 0),f(this,kn,!1),f(this,gt,void 0),f(this,Ii,void 0),f(this,oo,void 0),this.id=e.id,this.localId=e.localId,v(this,gt,e.track),this.kind=(n=e.track)==null?void 0:n.kind,v(this,Ii,e.disableTrackOnPause?!((r=e.track)!=null&&r.enabled):!1),v(this,oo,void 0),v(this,so,e.stopTracks),v(this,ao,e.disableTrackOnPause),v(this,Rs,e.zeroRtpOnPause),this.appData=e.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),v(this,Vn,e.handler),this.rtpSender=e.rtpSender,this._handleTrack()}get closed(){return o(this,kn)}get track(){return o(this,gt)}get paused(){return o(this,Ii)}get maxSpatialLayer(){return o(this,oo)}close(e){return u(this,null,function*(){if(o(this,kn))return;if(p.debug(`Producer::close() ${e?`with reason ${e}`:""}`,o(this,sn,bn)),v(this,kn,!0),this._destroyTrack(),e===qd){this.safeEmit("close",{reason:e});return}const{offerSdp:n,callback:r}=yield o(this,Vn).stopSending(this.localId),{answer:i}=yield this.safeEmitAsPromise("close",{offer:n,reason:e});r(i)})}getStats(){return u(this,null,function*(){if(o(this,kn))throw new Ut("closed");return o(this,Vn).getSenderStats(this.localId)})}pause(){p.debug("Producer::pause()",o(this,sn,bn)),o(this,kn)&&p.error("Producer::pause() | Producer closed",o(this,sn,bn)),v(this,Ii,!0),o(this,gt)&&o(this,ao)&&(o(this,gt).enabled=!1),o(this,Rs)&&o(this,Vn).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(p.debug("Producer::resume()",o(this,sn,bn)),o(this,kn)){p.error("Producer::resume() | Producer closed",o(this,sn,bn));return}v(this,Ii,!1),o(this,gt)&&o(this,ao)&&(o(this,gt).enabled=!0),o(this,Rs)&&o(this,Vn).replaceTrack(this.localId,o(this,gt)),this.emit("resume")}replaceTrack(e){return u(this,arguments,function*({track:n}){if(p.debug(`Producer::replaceTrack() trackId: ${n==null?void 0:n.id}`,o(this,sn,bn)),o(this,kn)){if(n&&o(this,so))try{n.stop()}catch(r){p.error("Producer::replaceTrack",G(x({},o(this,sn,bn)),{error:r}))}throw new Ut("closed")}else if(n&&n.readyState==="ended")throw new Ut("track ended");if(n===o(this,gt)){p.debug(`replaceTrack() | same track, ignored trackId: ${n.id}`,o(this,sn,bn));return}(!o(this,Rs)||!o(this,Ii))&&(yield o(this,Vn).replaceTrack(this.localId,n)),this._destroyTrack(),v(this,gt,n),this._handleTrack()})}setMaxSpatialLayer(e){return u(this,null,function*(){if(o(this,kn))throw new Ut("closed");if(this.kind!=="video")throw new ro("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield o(this,Vn).setMaxSpatialLayer(this.localId,e),v(this,oo,e)})}setRtpEncodingParameters(e){return u(this,null,function*(){if(o(this,kn))throw new Ut("closed");if(typeof e!="object")throw new TypeError("invalid params");yield o(this,Vn).setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){p.debug(`Producer::track "ended" event trackId: ${this.track.id}`,o(this,sn,bn)),this.safeEmit("trackended",this.track.id)}_handleTrack(){o(this,gt)&&o(this,gt).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(o(this,gt))try{o(this,gt).removeEventListener("ended",this._onTrackEnded),o(this,so)&&o(this,gt).stop()}catch(n){p.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,G(x({},o(this,sn,bn)),{error:n}))}}}Vn=new WeakMap,so=new WeakMap,ao=new WeakMap,Rs=new WeakMap,kn=new WeakMap,gt=new WeakMap,Ii=new WeakMap,oo=new WeakMap,sn=new WeakSet,bn=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function Ry(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function Bh(t){return Math.random().toString(36).substring(2,2+t)}const Hd=1;function My(t){const e=t;return delete e.payload._bolt,e}function FN(t){return t.payload&&Ry(t.payload)}function Ay(t){var e,n;return FN(t)&&(n=(e=t.payload._bolt)==null?void 0:e.id)!=null?n:""}var Ci;const co=class extends ut.EventEmitter{constructor(t,e,n){super(),g(this,"channel"),g(this,"queue"),g(this,"serverProtocolVersion"),f(this,Ci,new Map),g(this,"respond",(r,i,s=!1)=>{let a;s?a=co.createErrorResponse(r,i):a=co.createResponse(r,i),this.channel.send(JSON.stringify(a))}),g(this,"notify",r=>{const i=co.createNotification(r);this.channel.send(JSON.stringify(i))}),g(this,"request",r=>u(this,null,function*(){const i=co.createRequest(r),s=new Promise((a,c)=>{const{id:d}=i.payload._bolt,l={id:d,method:i.type,resolve:h=>{this.queue.delete(d)&&(clearTimeout(l.timer),a(h))},timer:setTimeout(()=>{this.queue.delete(d)&&c(new Error(`request timeout for message id: ${d}`))},2e4),cancel:h=>{this.queue.delete(d)&&(clearTimeout(l.timer),c(h))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(i)),s})),g(this,"send",r=>{const i=JSON.stringify(r),s=16384;if(i.length>s){const a=s-200,c=Math.ceil(i.length/a),d=[];for(let h=0;h<c;h+=1){const m=h*a,y=(h+1)*a;d.push(i.slice(m,y))}const l=Gi();for(let h=0;h<c;h+=1){const m=d[h],y=JSON.stringify({id:l,count:c,chunkIndex:h,chunk:m});p.debug(`Sending message chunk over dc: ${y}`),this.channel.send(y)}}else p.debug(`Sending message over dc: ${i}`),this.channel.send(i)}),g(this,"processMessage",r=>{var i;o(this,Ci).has(r.id)||o(this,Ci).set(r.id,[]);const s=o(this,Ci).get(r.id);if(s[r.chunkIndex]=r,(s==null?void 0:s.length)===r.count&&!s.some(a=>a===void 0)){const a=o(this,Ci).get(r.id),c=a==null?void 0:a.reduce((l,h)=>l+h.chunk,"");o(this,Ci).delete(r.id);const d=JSON.parse(c);if(!d.payload||!Ry(d.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:d}});if(this.processBoltHandshake(d))return;if(this.serverProtocolVersion=(i=d.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(d))return d}}),g(this,"processResponseMsg",r=>{const{id:i}=r.payload._bolt,s=this.queue.get(i);return s?(p.debug(`resolving pending request with id: ${i}, complete response: ${JSON.stringify(r)}`),r.type==="error"?s.cancel(My(r)):s.resolve(My(r)),!0):!1}),g(this,"processBoltHandshake",r=>{var i,s;return r.type==="_bolt"||r.type==="handshake"?(this.respond((s=(i=r.payload._bolt)==null?void 0:i.id)!=null?s:Bh(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=e,this.transportId=n,this.channel=t,this.queue=new Map}};let lo=co;Ci=new WeakMap,g(lo,"createRequest",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:G(x({},t.payload),{_bolt:{id:Bh(8),type:"REQUEST",version:Hd}})}}),g(lo,"createResponse",(t,e)=>{var n;if((n=e.payload)!=null&&n._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:G(x({},e.payload),{_bolt:{id:t,type:"RESPONSE",version:Hd}})}}),g(lo,"createNotification",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:G(x({},t.payload),{bolt:{id:Bh(8),type:"NOTIFY",version:Hd}})}}),g(lo,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:Hd}}}));function BN(t){if(Promise.allSettled)return Promise.allSettled(t);const e=t.map(n=>n.then(r=>({status:"fulfilled",value:r})).catch(r=>({status:"rejected",reason:r})));return Promise.all(e)}const qd="transport closed";var uo;const ho=class extends io{constructor(t,{id:e,direction:n,handlerFactory:r,iceServers:i,iceTransportPolicy:s,proprietaryConstraints:a,additionalSettings:c,appData:d,config:l}){var h,m,y;super(),g(this,"awaitQueue"),g(this,"observer"),f(this,uo,void 0),g(this,"id"),g(this,"serverId"),g(this,"direction"),g(this,"maxSctpMessageSize"),g(this,"handler"),g(this,"connectionState","new"),g(this,"producers"),g(this,"consumers"),g(this,"datachannels"),g(this,"connected",!1),g(this,"eventsDCReadyPromise"),g(this,"eventsDCReadyPromiseResolver"),g(this,"eventsDCFailureTimer"),g(this,"transportConnectionPromise"),g(this,"consumerTrackEvents"),g(this,"unknownTracksMap"),g(this,"appData"),p.debug(`constructor() [id: ${e}, direction: ${n}]`),v(this,uo,t),this.id=e,this.direction=n;const T=xN(c,{});delete T.iceServers,delete T.iceTransportPolicy,delete T.bundlePolicy,delete T.rtcpMuxPolicy,delete T.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Vd,this.observer=new io,this.handler=r(),this.handler.enableHighBitrate=(h=l==null?void 0:l.enableHighBitrate)!=null?h:!1,this.handler.enableStereo=(m=l==null?void 0:l.enableStereo)!=null?m:!1,this.handler.enableDtx=(y=l==null?void 0:l.enableDtx)!=null?y:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:n,iceServers:i,iceTransportPolicy:s,additionalSettings:c,proprietaryConstraints:a}),this.appData=d||{},this.transportConnectionPromise=new Promise(b=>{this.observer.once("connected",()=>{b(!0)}),this.observer.once("disconnect",()=>{b(!1)}),this.observer.once("close",()=>{b(!1)})}),this.eventsDCReadyPromise=new Promise(b=>{this.eventsDCReadyPromiseResolver=b}),this.handler.on("@connectionstatechange",b=>{b!==this.connectionState&&(p.debug(`connection state changed to ${b}`),this.connectionState=b,b==="connected"&&(this.connected=!0,this.observer.emit("connected")),b==="disconnected"&&(this.connected=!1,this.observer.emit("disconnect")),(b==="failed"||b==="closed")&&(this.connected=!1,this.observer.emit("close")),this.closed||this.safeEmit("connectionstatechange",b))}),this.handler.on("@icecandidate",({candidate:b})=>{this.closed||this.safeEmit("icecandidate",b)}),this.handler.on("dc_open",b=>{let O=this.datachannels.get(b.label);O||(O||(O=new lo(b,b.label,this.serverId),this.datachannels.set(b.label,O)),this.eventsDCFailureTimer=setTimeout(()=>{b.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",b.label))},5e3))}),this.handler.on("datachannel",(b,O)=>{b.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const M=this.datachannels.get(b.label);if(!M){p.error("unregistered datachannel for message",{rtcChannel:{label:b.label,message:O}});return}try{const F=JSON.parse(O);p.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:F.id,count:F.count,chunkIndex:F.chunkIndex,chunk:F.chunk,transprtId:this.serverId}});const V=M.processMessage(F);if(!V)return;p.debug(`datachannel message with id:${F.id} on transport:${this.serverId}complete - ${JSON.stringify(V)}`),this.emit(`datachannel:${b.label}`,M.label,V)}catch(F){p.error("error parsing message",{error:F})}})}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||(p.debug("Transport close called"),this.connectionState="closed",this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(t=>{t.close(qd).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(t=>{t.close(qd)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"),this.observer.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:n}=yield this.handler.connect(),{transportId:r,answer:i}=yield t(e);this.setServerId(r),yield n(i)})),!(yield this.transportConnectionPromise))throw new Error("ice connection failed");if(o(this,uo)===tt.HIVE&&!(yield this.isEventsDCReady))throw new Error("events datachannel not open")}catch(e){throw p.error("transport failed to connect:",{error:e}),e}})}restartIce(){return u(this,null,function*(){if(p.debug("restartIce()"),this.closed)throw new Ut("closed");return this.handler.restartIce()})}canProduce(t){return u(this,null,function*(){const{track:e,appData:n}=t;if(e){if(this.direction!=="send")throw new ro("not a sending Transport");if(e.readyState==="ended")throw new Ut("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(n&&typeof n!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.transportConnectionPromise))throw new _i("transport not connected");return!0})}produce(t,e){return u(this,null,function*(){if(!(yield this.canProduce(t)))throw new Error("Cannot produce");const{track:n,encodings:r,codecOptions:i,stopTracks:s=!0,disableTrackOnPause:a=!0,zeroRtpOnPause:c=!1,appData:d={}}=t;p.debug(`produce() [track:${n.id}]`);const{producerId:l,localId:h,rtpSender:m}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:y,callback:T,sender:b,mid:O}=yield this.handler.send({track:n,encodings:r,codecOptions:i,screenShare:d==null?void 0:d.screenShare}),{answer:M,producerId:F}=yield e({offer:y,kind:n.kind,paused:a?!n.enabled:!1,appData:G(x({},d||{}),{mid:O}),codecOptions:i,producingTransportId:this.serverId}),V=yield T(M);return{producerId:F,localId:V,rtpSender:b}}),"producer");return this.createProducerObject({id:l,localId:h,track:n,stopTracks:s,disableTrackOnPause:a,zeroRtpOnPause:c,appData:d,handler:this.handler,rtpSender:m})})}createProducerObject(t){return u(this,null,function*(){const e=new UN(t);return this.producers.set(e.id,e),e.once("close",()=>{this.producers.delete(e.id)}),e})}closeProducer(t){return u(this,null,function*(){yield this.awaitQueue.push(t.close.bind(t),"producer")})}canConsume(){return u(this,null,function*(){if(this.closed)throw new Ut("closed");if(this.direction!=="recv")throw new ro("not a receiving transport");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!(yield this.transportConnectionPromise))throw new _i("transport not connected");return!0})}consume(t,e,n){return u(this,null,function*(){return this.awaitQueue.push(()=>u(this,null,function*(){const r={},{consumerStates:i,sessionDescription:s,failedProducers:a}=yield e(t);i.forEach((l,h)=>{r[h]=this.createConsumerObjectAndWaitForTrack(G(x({},l),{producerId:h}))});const c=a;s&&(p.info("Session description found, sending negotiation request"),yield n(s));const d=[];return yield Promise.all(Object.entries(r).map(([l,h])=>h.then(m=>d.push(m)).catch(()=>{p.error(`Failed to create consumer object, producer: ${l}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:d,failedProducers:c}}),"consumer")})}static parseHeaderExtensionMappings(t,e){const n=Kr(t.sdp),r={};return n.media.forEach(i=>{e.includes(i.mid.toString())&&(r[i.mid]=i.ext)}),r}static setHeaderExtensionMappings(t,e,n){const r=Kr(t.sdp);return r.media=r.media.map(i=>{if(e.includes(i.mid.toString())){const s=x({},i);return s.ext=n[i.mid],s}return i}),G(x({},t),{sdp:mc(r)})}static parseCodecAndFmtpMappings(t,e){const n=Kr(t.sdp),r={};return n.media.forEach(i=>{e.includes(i.mid.toString())&&(r[i.mid.toString()]={rtp:i.rtp,fmtp:i.fmtp,payloads:i.payloads,rtcpFb:i.rtcpFb})}),r}static setCodecAndFmtpMappings(t,e,n){const r=Kr(t.sdp);return r.media=r.media.map(i=>{if(e.includes(i.mid.toString())){const s=x({},i);return s.rtp=n[i.mid.toString()].rtp,s.fmtp=n[i.mid.toString()].fmtp,s.payloads=n[i.mid.toString()].payloads,s.rtcpFb=n[i.mid.toString()].rtcpFb,s}return i}),G(x({},t),{sdp:mc(r)})}closeConsumers(t,e){return u(this,null,function*(){const n=t.map(c=>c.transceiver.mid),r=ho.parseHeaderExtensionMappings(this.handler.pc.remoteDescription,n),i=ho.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,n);t.forEach(c=>c.close(void 0,!0));let s=yield this.handler.pc.createOffer();s=ho.setHeaderExtensionMappings(s,n,r),s=ho.setCodecAndFmtpMappings(s,n,i),yield this.setLocalDescription(s);const a=yield e(t,s);yield this.setRemoteDescription(a)})}setRemoteOffer(t){return u(this,null,function*(){yield this.setRemoteDescription(t);const e=yield this.handler.pc.createAnswer(),n=Kr(e.sdp);return n.media=n.media.map(r=>{if(r.type==="audio"){const i=x({},r),s=i.fmtp.find(a=>a.payload===111);return s&&(s.config+=";stereo=1;sprop-stereo=1"),i.rtcpFb||(i.rtcpFb=[]),i.rtcpFb.some(a=>a.type==="nack")||i.rtcpFb.push({payload:parseInt(i.payloads,10),type:"nack"}),i}return r}),e.sdp=mc(n),yield this.setLocalDescription(e),e})}_ontrack(t){const{track:e,transceiver:n,streams:r}=t;p.info(`track event received [trackId: ${e.id}]`);let i;o(this,uo)===tt.HIVE?i=`${r[0].id}:${e.kind}`:i=`${n.mid}:${e.kind}`,e.addEventListener("ended",()=>{p.info(`rtc consumer track ended [trackId: ${e.id}]`),this.unknownTracksMap.delete(i)});const s=this.consumerTrackEvents.get(i);s?(s(e,n),this.consumerTrackEvents.delete(i)):(p.warn(`track event handler not found ${i}`),this.unknownTracksMap.set(i,t))}sendErrorOverDC(t,e,n){const r=this.getDatachannel(t);if(!r)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});r.respond(e,n,!0)}sendResponseOverDC(t,e,n){const r=this.getDatachannel(t);if(!r)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});r.respond(e,n)}createConsumerObjectAndWaitForTrack(t){return u(this,null,function*(){const{consumerId:e,producerId:n,producingPeerId:r,producingTransportId:i,streamId:s,paused:a,screenShare:c,appData:d,kind:l,mimeType:h}=t,m=`${s}:${l}`,y=G(x({},t),{name:"consumer creation task error",message:"consumer creation failed"});return new Promise((T,b)=>u(this,null,function*(){const O=setTimeout(()=>{this.consumerTrackEvents.delete(m),y.isTimedout=!0,b(y)},5e3),M=(V,K)=>{try{if(V.readyState==="ended")clearTimeout(O),b(y);else{const I=V;I.enabled=!0,this.handler.midTransceiverMap.set(K.mid,K);const Z=new VN({id:e,localId:K.mid,transceiver:K,track:I,paused:a,producerId:n,producingPeerId:r,producingTransportId:i,handler:this.handler,appData:G(x({},d),{screenShare:c,peerId:r}),rtpReceiver:K.receiver,mimeType:h});this.consumers.set(e,Z),Z.once("close",()=>{this.consumers.delete(Z.id),this.handler.midTransceiverMap.delete(K.mid)}),p.info("consumer created for ",{consumer:{id:e,kind:l,appData:{screenShare:c},peerId:r,producerId:n}}),this.observer.emit("newconsumer",Z),clearTimeout(O),T(Z)}}catch(I){p.warn("error while creating consumer:",I),clearTimeout(O),b(y)}},F=this.unknownTracksMap.get(m);F?(this.unknownTracksMap.delete(m),M(F.track,F.transceiver)):this.consumerTrackEvents.set(m,M)}))})}setRemoteDescription(t){return u(this,null,function*(){yield this.handler.pc.setRemoteDescription(t)})}setLocalDescription(t){return u(this,null,function*(){p.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(t)}]`),yield this.handler.pc.setLocalDescription(t)})}retryFailedConsumerCreationTasks(t){return u(this,null,function*(){return BN(t.map(e=>u(this,null,function*(){return Oh(n=>u(this,null,function*(){return n>0&&p.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.createConsumerObjectAndWaitForTrack(x({},e))}))})))})}sendDataChannelMessage(t,e){return u(this,null,function*(){const n=this.getDatachannel(t);if(!n)throw AN("DC_NOT_READY",`${t} datachannel not ready`);const r=(yield n.request(e)).payload;return p.info(`sendDataChannelMessage::response ${JSON.stringify(r)}`),r})}};let WN=ho;uo=new WeakMap;function jN(){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){p.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return p.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=Up.getParser(t),n=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(n.name&&n.name.toLowerCase()==="blink"){const r=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return r?Number(r[1])>=74?"Chrome74":void 0:"Chrome74"}if(n.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;p.warn("Device::this._detectDevice() | browser not supported");return}p.warn("Device::this._detectDevice() | unknown device")}var Gd;class HN{constructor(e,{handlerName:n,handlerFactory:r}={}){if(g(this,"handlerFactory"),f(this,Gd,void 0),p.debug("constructor()"),v(this,Gd,e),n&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(n)p.debug(`Device::constructor() | handler given: ${n}`);else if(n=jN(),n)p.debug(`Device::constructor() | detected handler: ${n}`);else throw new Error("device not supported");switch(n){case"Chrome74":this.handlerFactory=Lh.createFactory();break;case"Safari12":this.handlerFactory=xh.createFactory();break;case"Firefox60":this.handlerFactory=Bd.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Bd.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${n}"`)}}}createTransport(e){const n=Gi();return new WN(o(this,Gd),G(x({id:n},e),{handlerFactory:this.handlerFactory}))}}Gd=new WeakMap;const qN=2e3;var Or,po,It,Ct,Ms,mo,go,fo,As,Pi,vo,yo,Jd,$d,Wh,jh,Dy,Hh,Oy,qh,Ny,Gh,Ly,Jh,xy,Kd,$h,zd,Kh;class GN extends ut.EventEmitter{constructor(e,n,r){switch(super(),f(this,yo),f(this,$d),f(this,jh),f(this,Hh),f(this,qh),f(this,Gh),f(this,Jh),f(this,Kd),f(this,zd),f(this,Or,void 0),f(this,po,void 0),f(this,It,void 0),f(this,Ct,void 0),f(this,Ms,void 0),f(this,mo,void 0),f(this,go,void 0),f(this,fo,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0}),f(this,As,void 0),f(this,Pi,"all"),f(this,vo,void 0),v(this,Or,e),v(this,Ms,n),v(this,vo,r),v(this,po,new HN(r)),v(this,mo,new LN(n,r)),r){case tt.CF:{v(this,go,pn);break}case tt.HIVE:default:{v(this,go,en);break}}o(this,yo,Jd).mediaState={send:{state:Rr.NEW,reconnected:!1},recv:{state:Rr.NEW,reconnected:!1}},X.hasFeature(ie.FORCE_RELAY)&&v(this,Pi,"relay"),H(this,$d,Wh).call(this)}get socket(){return o(this,Ms)}get socketHandler(){return o(this,mo)}get sendTransport(){return o(this,It)}get recvTransport(){return o(this,Ct)}get events(){return o(this,go)}get nodeType(){return o(this,vo)}createTransports(e){return u(this,null,function*(){var n,r,i,s,a,c,d,l;X.hasFeature(ie.FORCE_RELAY)&&(p.info("ICE Transport Policy set to relay"),v(this,Pi,"relay"));const h=yield ot().getICEServers().catch(y=>(p.warn(`failed to get iceservers from server: ${y.message}`),[])),m=[];if(e.send){const y=X.hasFeature(ie.DISABLE_OPUS_DTX_CF),T=H(this,Hh,Oy).call(this,{iceServers:h,additionalSettings:{encodedInsertableStreams:(n=o(this,Or).getValue("modules").e2ee)==null?void 0:n.enabled},config:{enableHighBitrate:(s=(i=(r=o(this,Or).getValue("defaults").mediaConfiguration)==null?void 0:r.audio)==null?void 0:i.enableHighBitrate)!=null?s:!1,enableStereo:(d=(c=(a=o(this,Or).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:c.enableStereo)!=null?d:!1,enableDtx:o(this,vo)===tt.HIVE?!0:!!y},iceTransportPolicy:o(this,Pi)});m.push(T)}if(e.recv){const y=H(this,qh,Ny).call(this,{iceServers:h,additionalSettings:{encodedInsertableStreams:(l=o(this,Or).getValue("modules").e2ee)==null?void 0:l.enabled},iceTransportPolicy:o(this,Pi)});m.push(y)}yield Promise.all(m)})}stopTransports(e){var n,r;if(e.send&&this.sendTransport!==void 0){const{id:i,serverId:s,direction:a}=o(this,It);p.info("Closing send transport",{transport:{id:i,serverId:s,type:a}}),o(this,It).close(),o(this,It).removeAllListeners(),v(this,It,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:i,serverId:s,direction:a}=o(this,Ct);p.info("Closing recv transport",{transport:{id:i,serverId:s,type:a}}),(n=o(this,Ct))==null||n.close(),(r=o(this,Ct))==null||r.removeAllListeners(),v(this,Ct,void 0)}H(this,$d,Wh).call(this)}stopAllTransports(){p.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}connectTransportWithRetry(e){return u(this,null,function*(){const{id:n,serverId:r,direction:i}=e;H(this,Gh,Ly).call(this,e);try{const s=X.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3;return yield Oh((a,c)=>u(this,null,function*(){a>0&&p.debug(`Retrying transport connect, count: ${a}`,{transport:{id:n,serverId:r,type:i}});try{if(e.closed)throw new _i("Cannot reconnect closed transport");yield H(this,jh,Dy).call(this,e)}catch(d){if(d instanceof _i){c(d);return}throw p.error("Failed to connect transport, retrying",{transport:e,error:d}),d}}),{delayTime:100,strategy:"exponential",maxRetryCount:s}),e}catch(s){throw p.error(`Failed to connect send transport after retry: ${e.id}`,{error:s,transport:{id:n,serverId:r,type:i}}),e.close(),e.removeAllListeners(),s}})}handleErrors(e){throw new Error("Method not implemented.")}}Or=new WeakMap,po=new WeakMap,It=new WeakMap,Ct=new WeakMap,Ms=new WeakMap,mo=new WeakMap,go=new WeakMap,fo=new WeakMap,As=new WeakMap,Pi=new WeakMap,vo=new WeakMap,yo=new WeakSet,Jd=function(){return o(this,Or).getValue("connectionHandler")},$d=new WeakSet,Wh=function(){v(this,As,{send:void 0,recv:void 0})},jh=new WeakSet,Dy=function(t){return u(this,null,function*(){const{id:e,direction:n}=t;if(p.info(`Connecting ${n} transport`,{transport:{id:e,type:n}}),!o(this,Ms).isConnected)throw new _i("Socket is not connected");if(t.connectionState==="closed")throw new _i("Transport is closed");try{yield t.connect(r=>H(this,Jh,xy).call(this,n,r)),p.info(`Connected ${n} transport`,{transport:{id:e,serverId:t.serverId,type:n}})}catch(r){throw o(this,fo).transportFailureCount[n]+=1,r.message==="ice connection failed"?new _i(r.message):r}})},Hh=new WeakSet,Oy=function(t){return u(this,null,function*(){var e,n;if(o(this,It)&&o(this,It).connected){p.info("Transport send is already connected",{transport:{id:(e=o(this,It))==null?void 0:e.id,serverId:(n=o(this,It))==null?void 0:n.serverId,type:"send"}});return}v(this,It,o(this,po).createTransport(G(x({},t),{direction:"send"}))),J.configureSendTransport(o(this,It))})},qh=new WeakSet,Ny=function(t){return u(this,null,function*(){var e,n;if(o(this,Ct)&&o(this,Ct).connected){p.info("Transport recv is already connected",{transport:{id:(e=o(this,Ct))==null?void 0:e.id,serverId:(n=o(this,Ct))==null?void 0:n.serverId,type:"recv"}});return}v(this,Ct,o(this,po).createTransport(G(x({},t),{direction:"recv"}))),J.configureRecvTransport(o(this,Ct))})},Gh=new WeakSet,Ly=function(t){const{direction:e,id:n}=t;t.on("connectionstatechange",r=>u(this,null,function*(){H(this,zd,Kh).call(this,{state:r,direction:e}),p.info(`Transport connection state changed for ${e} transport`,{transport:{id:n,serverId:t.serverId,type:e,status:r}});const i=()=>{const s=o(this,As)[e];s!==void 0&&(clearTimeout(s),o(this,As)[e]=void 0)};switch(r){case"connected":i(),o(this,fo).lastConnectionTime=performance.now();break;case"disconnected":o(this,As)[e]=setTimeout(()=>u(this,null,function*(){yield H(this,Kd,$h).call(this,t)}),qN);break;case"failed":if(t.closed)return;i(),yield H(this,Kd,$h).call(this,t);break}})),t.on("icecandidate",r=>u(this,null,function*(){p.debug("Sending iceCandidate:",{iceCandidate:r})})),t.on("datachannel:events",(r,i)=>u(this,null,function*(){var s,a;p.debug("Got data channel message on event:",{rtcChannel:{label:r,message:i}});try{switch(i.type){case"handshake":{const c={type:"handshake",payload:{message:"pong"}};t.sendResponseOverDC(r,Ay(i),c);break}case"hub-disconnect":{p.debug(`media hub disconnected, full_reconnect: ${(s=i.payload)==null?void 0:s.full_reconnect}`),((a=i.payload)==null?void 0:a.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(c){p.error(`Unable to handle the incoming datachannel message on channel ${r}`)}})),t.on("dc_error",()=>{t.direction==="recv"&&(p.warn("Events datachannel did not open in 5s",{country:S.location.country}),this.handleErrors("reconnectRecvTransport"))})},Jh=new WeakSet,xy=function(t,e){return u(this,null,function*(){const n=t==="recv";try{const{sdp:r,type:i}=e,s={consuming:n,description:{sdp:r,type:i,target:n?zn.SUBSCRIBER:zn.PUBLISHER},producers:[]};return o(this,mo).connectTransport(s)}catch(r){throw p.error(`Error in ${t} transport connection:`,{error:r,country:S.location.country}),r}})},Kd=new WeakSet,$h=function(t){return u(this,null,function*(){p.info("Called reconnect transport",{transport:t}),t.close(),t.removeAllListeners();const{direction:e}=t;switch(X.hasFeature(ie.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED)&&o(this,Ms).isConnected&&o(this,fo).transportFailureCount[e]>2&&(p.warn(`Multiple disconnections in ${e} transport, forcing relay`),v(this,Pi,"relay")),yield this.createTransports({[e]:!0}),e){case"send":{yield this.connectTransportWithRetry(o(this,It)),p.info("Transport reconnected",{transport:o(this,It)}),P.emit(R.RESET_PRODUCER_STATE);break}case"recv":{yield this.connectTransportWithRetry(o(this,Ct)),p.info("Transport reconnected",{transport:o(this,Ct)}),P.emit(R.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:p.warn("Unknown transport direction",{transport:t})}H(this,zd,Kh).call(this,{state:Rr.CONNECTED,direction:e})})},zd=new WeakSet,Kh=function(t){const{state:e,direction:n}=t;o(this,yo,Jd).mediaState[n]={state:e,reconnected:!0},P.emit(R.TRANSPORT_STATE_UPDATE,x({transport:n},o(this,yo,Jd).mediaState[n]))};var zh,Vy;class JN{constructor(e){f(this,zh),this.recvTransport=e,H(this,zh,Vy).call(this)}create(e){return u(this,null,function*(){if(!e||e&&e.length===0)throw new Error("List of producers is required");const n={type:"create_consumer",payload:{producers:e.map(({producerId:a,producingTransportId:c,kind:d,mimeType:l})=>({producerId:a,producingTransportId:c,preferredCodec:x(x({},d==="video"&&l?{video:l}:{}),d==="audio"&&l?{audio:l}:{})}))}},r=yield this.recvTransport.sendDataChannelMessage("events",n),i=new Map;e.forEach(a=>i.set(a.producerId,a));const s=new Map;return Object.entries(r).forEach(([a,c])=>{const d=i.get(c.producerId);d&&s.set(c.producerId,{consumerId:a,producingTransportId:d.producingTransportId,producingPeerId:d.producingPeerId,kind:d.kind,paused:d.pause,streamId:c.streamId,trackId:c.trackId,screenShare:d.screenShare,mimeType:d.mimeType,appData:{}})}),{consumerStates:s}})}negotiate(e,n,r){return u(this,null,function*(){try{p.debug(`Received offer over dc: ${e.sdp} for transport`);const i=yield this.recvTransport.setRemoteOffer(e),s={type:"answer",payload:{type:i.type,sdp:i.sdp}};return p.debug(`datachannel answer: ${JSON.stringify(s)}`),this.recvTransport.sendResponseOverDC(r,n,s),i}catch(i){throw p.error("datachannel:events::Error:",i),i.code!=="DC_NOT_FOUND"&&this.recvTransport.sendErrorOverDC(r,n,i),i}})}close(e){return u(this,null,function*(){if(!e.length)return{};const n=e.map(a=>a.id);p.info(`Closing consumers: ${JSON.stringify(n)}`);const r={type:"close_consumers",payload:{consumers:n}},i=yield this.recvTransport.sendDataChannelMessage("events",r),{failedConsumers:s}=i;return{failedConsumers:s}})}}zh=new WeakSet,Vy=function(){this.recvTransport.on("datachannel:events",(t,e)=>u(this,null,function*(){try{switch(e.type){case"negotiation":{const{sdp:n}=e.payload,r={sdp:n,type:"offer"};this.negotiate(r,Ay(e),t);break}default:break}}catch(n){p.error(`Unable to handle the incoming datachannel message on channel ${t}`)}}))};class $N{constructor(e,n,r,i){this.events=e,this.recvTransport=n,this.socket=r,this.socketHandler=i}create(e){return u(this,null,function*(){if(!e||e&&e.length===0)throw new Error("List of producers is required");const n=new Map,r=[];e.forEach(d=>{const{producingPeerId:l,producerId:h,producingTransportId:m}=d;n.set(h,l),r.push({producingPeerId:l,producerId:h,producingTransportId:m})});const i=yield this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),s=new Map;e.forEach(d=>s.set(d.producerId,d));const a=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const h=s.get(d);if(!h)return;if(l.errorCode){if(p.warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),l.errorCode==="not_found_track_error"){p.error(`Track not found for producer: ${h.producerId}. This will not be retried.`);return}c.push(h);return}let m={};try{m=JSON.parse(l.producerState.appData)}catch(y){}a.set(d,{consumerId:l.consumerId,producingTransportId:h.producingTransportId,producingPeerId:h.producingPeerId,kind:h.kind,paused:h.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:h.screenShare,mimeType:h.mimeType,appData:m})}),{consumerStates:a,sessionDescription:i.sessionDescription,failedProducers:c}})}negotiate(e){return u(this,null,function*(){p.info("Negotiating socket consumer",{transport:this.recvTransport}),p.debug(`setting remote offer: ${JSON.stringify(e)} on recvTransport`,{transport:this.recvTransport});const n=yield this.recvTransport.setRemoteOffer(e),r={transportId:this.recvTransport.serverId,description:{sdp:n.sdp,type:n.type,target:zn.SUBSCRIBER}};return p.debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),yield this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,EC.toBinary(r)),p.info("Renegotiation done",{transport:this.recvTransport}),n})}close(e){return u(this,null,function*(){if(!e.length)return{};const n=(r,i)=>u(this,null,function*(){const s=r.map(l=>l.localId);p.info(`Closing consumers: ${JSON.stringify(s)}`);const a={description:{sdp:i.sdp,type:i.type,target:zn.SUBSCRIBER},consumerIds:s,consumingTransportId:this.recvTransport.serverId},c=yield this.socketHandler.closeConsumer(a),d=HP.fromBinary(c).description;return{sdp:d.sdp,type:d.type}});return this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(e,n),"close_consumer"),{}})}}class Yh{constructor(e){this.socketHandler=e}static getMSIDFromSDP(e,n){return Kr(e).media.filter(r=>n==="video"?r.type==="video":r.type==="audio").at(-1).msid}create(e){return u(this,arguments,function*({offer:n,kind:r,paused:i,appData:s,codecOptions:a,producingTransportId:c}){var d,l;const h=Yh.getMSIDFromSDP(n.sdp,r),m={description:{sdp:n.sdp,type:n.type,target:zn.PUBLISHER},paused:i,kind:r,msid:h,appData:JSON.stringify(s),screenShare:(d=s.screenShare)!=null?d:!1,mimeType:`${r}/${(l=a[0])==null?void 0:l.name}`,producingTransportId:c},{answer:y,producerId:T}=yield this.socketHandler.produce(m);return{answer:y,producerId:T}})}}var So,Ds,Ri,Eo,Yd,or,Qh,Nr,To,Xh,Uy,Qd,Zh,ep,Fy,tp,By,np,Wy,rp,jy,ip,Hy,sp,qy;class KN extends GN{constructor(e,n,r){super(e,n,r),f(this,Xh),f(this,Qd),f(this,ep),f(this,tp),f(this,np),f(this,rp),f(this,ip),f(this,sp),f(this,So,void 0),f(this,Ds,void 0),f(this,Ri,void 0),f(this,Eo,void 0),f(this,Yd,void 0),f(this,or,void 0),f(this,Qh,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0}),f(this,Nr,[]),f(this,To,void 0),v(this,So,e),o(this,Xh,Uy).mediaState={send:{state:Rr.NEW,reconnected:!1},recv:{state:Rr.NEW,reconnected:!1}},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return o(this,Ds)}get consumers(){return o(this,Ri)}get producerIdToConsumerIdMap(){return o(this,Eo)}reset(){v(this,Ds,new Map),v(this,Ri,new Map),v(this,Eo,new Map)}setupTransports(e){return u(this,null,function*(){yield this.createTransports(e);let n,r;e.send&&(n=H(this,ep,Fy).call(this)),e.recv&&(r=H(this,tp,By).call(this)),yield Promise.all([n,r])})}createProducer(e,n){return u(this,null,function*(){var r;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const i=yield this.sendTransport.produce(e,H(this,np,Wy).bind(this));return(r=e.appData)!=null&&r.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,i),H(this,rp,jy).call(this,i,n),i}catch(i){throw p.error("Failed to create producer",{error:i}),o(this,Qh).producerCreationFailureCount+=1,i}})}closeProducer(e,n){return u(this,null,function*(){var r;const i=this.producers.get(e);if(!i){p.warn(`Producer with ID ${e} was not found`);return}n!=null&&n.stopTrack&&i.track.stop();try{yield this.sendTransport.closeProducer(i),(r=o(this,So).getValue("modules").e2ee)!=null&&r.enabled&&P.emit(R.E2EE_INACTIVE_PRODUCER,i)}catch(s){p.error("Failed to close producer on server",{error:s,producer:i})}})}closeAllProducers(){return Promise.all(Array.from(o(this,Ds).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}createConsumers(e){return u(this,null,function*(){o(this,To)||clearTimeout(o(this,To)),v(this,Nr,o(this,Nr).concat(e)),yield H(this,Qd,Zh).call(this)})}closeConsumer(e){return this.closeConsumers([e])}closeConsumers(e){return u(this,null,function*(){if(!o(this,or))return;const n=e.map(i=>this.consumers.get(i)).filter(i=>i!==void 0);if(n.length===0)return;const{failedConsumers:r}=yield o(this,or).close(n);r!=null&&r.length&&p.warn("Failed to close some consumers",{consumerIds:r})})}closeAllConsumers(){return this.closeConsumers(Array.from(o(this,Ri).keys()))}switchConsumersToLayer(e,n){return u(this,null,function*(){const r=this.recvTransport.getDatachannel("events");if(!r){p.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:n}};yield r.request(i),p.info(`Consumers switched layers to ${n}`,{consumerIds:e})})}}So=new WeakMap,Ds=new WeakMap,Ri=new WeakMap,Eo=new WeakMap,Yd=new WeakMap,or=new WeakMap,Qh=new WeakMap,Nr=new WeakMap,To=new WeakMap,Xh=new WeakSet,Uy=function(){return o(this,So).getValue("connectionHandler")},Qd=new WeakSet,Zh=function(){return u(this,null,function*(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const t=500,e=o(this,Nr).splice(0,o(this,Nr).length);try{const n=e.filter(({producerId:s})=>!this.producers.get(s));if(n.length===0)return;const{consumers:r,failedProducers:i}=yield this.recvTransport.consume(n,H(this,ip,Hy).bind(this),o(this,or).negotiate.bind(o(this,or)));r.forEach(H(this,sp,qy).bind(this)),i!=null&&i.length&&(p.error("Failed to create consumers for producers",{producers:i}),v(this,Nr,o(this,Nr).concat(i)),v(this,To,setTimeout(H(this,Qd,Zh).bind(this),t)))}catch(n){p.error("failed to consume on transport",{error:n})}})},ep=new WeakSet,Fy=function(){return u(this,null,function*(){yield this.connectTransportWithRetry(this.sendTransport),v(this,Yd,new Yh(this.socketHandler))})},tp=new WeakSet,By=function(){return u(this,null,function*(){switch(this.recvTransport.on("connect",()=>{o(this,Eo).clear()}),yield this.connectTransportWithRetry(this.recvTransport),this.nodeType){case tt.CF:{v(this,or,new $N(this.events,this.recvTransport,this.socket,this.socketHandler));break}case tt.HIVE:default:v(this,or,new JN(this.recvTransport))}})},np=new WeakSet,Wy=function(t){return o(this,Yd).create(t)},rp=new WeakSet,jy=function(t,e){t.on("close",(n,r)=>u(this,null,function*(){const{offer:i,reason:s}=n;if(p.info("producer::closing",{debuggingHint:s,producer:G(x({},t),{status:"closing"})}),s!==qd){const a={producerId:t.id,description:{sdp:i.sdp,type:i.type,target:zn.PUBLISHER}};try{const c=yield this.socketHandler.closeProducer(a),d={sdp:c==null?void 0:c.sdp,type:c==null?void 0:c.type};p.info("producer::closed",{producer:G(x({},t),{status:"closed"})}),r({answer:d})}catch(c){p.error("producer close error",c)}}this.producers.delete(t.id),e()})),t.on("trackended",()=>{p.info("producer::trackended",{producer:G(x({},t),{status:"UNKNOWN"})})}),o(this,Ds).set(t.id,t)},ip=new WeakSet,Hy=function(t){return u(this,null,function*(){try{return yield this.recvTransport.canConsume(),yield o(this,or).create(t)}catch(e){throw p.error("Error in consume request",{error:e}),e}})},sp=new WeakSet,qy=function(t){t.on("close",e=>u(this,null,function*(){p.debug("consumer closed",{consumer:{closureReason:e,id:t.id,kind:t.kind,appData:t.appData}}),o(this,Ri).delete(t.id),P.emit(R.CONSUMER_CLOSED,{id:t.id})})),o(this,Ri).set(t.id,t),this.producerIdToConsumerIdMap.set(t.producerId,t.id),P.emit(R.NEW_CONSUMER,{id:t.id,appData:t.appData,peerId:t.peerId})};var Xd,Zd,el,ko,bo,wo,tl,nl,_o,Yt,Un,Fn,Mi,Ai,Lr,rl,ap,Gy,op,Jy,cp,$y,dp,Ky;const lp=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:n=3,hangoverFrames:r=5,noiseAdaptationRate:i=.95,voiceAdaptationRate:s=.99,minEnergyThreshold:a=.005,maxEnergyThreshold:c=.2,energyRatioThreshold:d=1.5,noiseHistorySize:l=50}={}){f(this,ap),f(this,op),f(this,Xd,void 0),f(this,Zd,void 0),f(this,el,void 0),f(this,ko,void 0),f(this,bo,void 0),f(this,wo,void 0),f(this,tl,void 0),f(this,nl,void 0),f(this,_o,void 0),f(this,Yt,void 0),f(this,Un,void 0),f(this,Fn,!1),f(this,Mi,0),f(this,Ai,0),f(this,Lr,[]),f(this,rl,void 0),v(this,ko,t),v(this,Yt,t),v(this,Xd,e),v(this,Zd,n),v(this,el,r),v(this,bo,i),v(this,wo,s),v(this,tl,a),v(this,nl,c),v(this,_o,d),v(this,rl,l),v(this,Un,t/2)}get voiceDetected(){return o(this,Fn)}processAudioChunk(t){var e,n;const r=H(e=lp,cp,$y).call(e,t),i=H(n=lp,dp,Ky).call(n,t);return H(this,ap,Gy).call(this,r),r/o(this,Un)>o(this,_o)&&r>o(this,Yt)&&i>o(this,Xd)?(v(this,Mi,o(this,Mi)+1),v(this,Ai,o(this,el)),o(this,Mi)>=o(this,Zd)&&v(this,Fn,!0)):(v(this,Mi,0),o(this,Ai)>0?v(this,Ai,o(this,Ai)-1):o(this,Fn)&&v(this,Fn,!1),o(this,Fn)||H(this,op,Jy).call(this,r)),{energy:r,isVoice:o(this,Fn)}}reset(){v(this,Fn,!1),v(this,Mi,0),v(this,Ai,0),v(this,Yt,o(this,ko)),v(this,Un,o(this,ko)/2),v(this,Lr,[])}getThresholdInfo(){return{currentEnergyThreshold:o(this,Yt),backgroundNoiseEnergy:o(this,Un),energyRatioThreshold:o(this,_o)}}};let up=lp;Xd=new WeakMap,Zd=new WeakMap,el=new WeakMap,ko=new WeakMap,bo=new WeakMap,wo=new WeakMap,tl=new WeakMap,nl=new WeakMap,_o=new WeakMap,Yt=new WeakMap,Un=new WeakMap,Fn=new WeakMap,Mi=new WeakMap,Ai=new WeakMap,Lr=new WeakMap,rl=new WeakMap,ap=new WeakSet,Gy=function(t){o(this,Fn)?v(this,Yt,o(this,wo)*o(this,Yt)+(1-o(this,wo))*t):v(this,Yt,o(this,bo)*o(this,Yt)+(1-o(this,bo))*o(this,Un)),v(this,Yt,Math.max(o(this,tl),Math.min(o(this,nl),o(this,Yt))))},op=new WeakSet,Jy=function(t){if(t<o(this,Yt)*1.2)if(o(this,Lr).push(t),o(this,Lr).length>o(this,rl)&&o(this,Lr).shift(),o(this,Lr).length>=10){const e=[...o(this,Lr)].sort((r,i)=>r-i),n=Math.floor(e.length/2);v(this,Un,e[n])}else v(this,Un,.95*o(this,Un)+.05*t)},cp=new WeakSet,$y=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,n)=>e+n)/t.length)},dp=new WeakSet,Ky=function(t){let e=0;for(let n=1;n<t.length;n+=1)(t[n]>=0&&t[n-1]<0||t[n]<0&&t[n-1]>=0)&&(e+=1);return e},f(up,cp),f(up,dp);const zN=60,YN=400;var Di,Oi,Io,Bn,Co,Ni,Po,Os,Ro,Li,Ns,Mo,hp,zy,il,pp,mp,Yy,gp,Qy;const sl=class{constructor(t){f(this,hp),f(this,mp),f(this,Di,void 0),f(this,Oi,void 0),f(this,Io,void 0),f(this,Bn,void 0),f(this,Co,void 0),f(this,Ni,void 0),f(this,Po,void 0),f(this,Os,void 0),f(this,Ro,void 0),f(this,Li,void 0),f(this,Ns,void 0),f(this,Mo,void 0),this.reportRequest=t,v(this,Co,new AudioContext),v(this,Ni,o(this,Co).createAnalyser()),o(this,Ni).fftSize=2048,v(this,Ro,new up)}set producerId(t){v(this,Bn,t)}set audioTrack(t){v(this,Po,t);const e=new MediaStream;e.addTrack(o(this,Po)),o(this,Co).createMediaStreamSource(e).connect(o(this,Ni))}start(){p.debug(`AudioActivityReporter: Starting audio activity reporter: ${o(this,Bn)}`),o(this,Di)&&Jr(o(this,Di)),v(this,Di,$s(()=>u(this,null,function*(){var t;if(!o(this,Po)||!o(this,Bn))return;const{energy:e}=H(this,hp,zy).call(this),n=H(t=sl,il,pp).call(t,e);let r=.9;o(this,Mo)!==n&&o(this,Mo)?r=.9:n?r=.3:r=.5,v(this,Os,(o(this,Os)||0)*(1-r)+e*r)}),zN)),o(this,Oi)&&Jr(o(this,Oi)),v(this,Oi,$s(H(this,mp,Yy).bind(this),YN)),v(this,Io,$s(()=>{p.debug(`AudioActivityReporter: producer: ${o(this,Bn)} energy: ${o(this,Os)}`)},5e3))}stop(){p.debug(`AudioActivityReporter: Stopping audio activity reporter: ${o(this,Bn)}`),o(this,Di)&&Jr(o(this,Di)),o(this,Oi)&&Jr(o(this,Oi)),o(this,Io)&&Jr(o(this,Io)),o(this,Ro).reset()}};let fp=sl;Di=new WeakMap,Oi=new WeakMap,Io=new WeakMap,Bn=new WeakMap,Co=new WeakMap,Ni=new WeakMap,Po=new WeakMap,Os=new WeakMap,Ro=new WeakMap,Li=new WeakMap,Ns=new WeakMap,Mo=new WeakMap,hp=new WeakSet,zy=function(){var t;const e=new Float32Array(o(this,Ni).frequencyBinCount);o(this,Ni).getFloatTimeDomainData(e);const{energy:n,isVoice:r}=o(this,Ro).processAudioChunk(e),i=H(t=sl,gp,Qy).call(t,n);return i===-1/0||n<1e-6?{energy:0,isVoice:!1}:((!o(this,Li)||i<o(this,Li))&&v(this,Li,i),(!o(this,Ns)||i>o(this,Ns))&&v(this,Ns,i),{energy:(i-o(this,Li))/(o(this,Ns)-o(this,Li))*10||0,isVoice:r})},il=new WeakSet,pp=function(t){return t<5},mp=new WeakSet,Yy=function(t=o(this,Os)){var e;if(!o(this,Bn)||!t){p.debug(`AudioActivityReporter: No producerId or energy to report: ${o(this,Bn)}`);return}const n={producerId:o(this,Bn),energy:Math.round(t),silent:H(e=sl,il,pp).call(e,t)};v(this,Mo,n.silent),this.reportRequest(n)},gp=new WeakSet,Qy=function(t){const e=Math.log10(t);return Math.round(e)},f(fp,il),f(fp,gp);const QN=()=>{const t=new window.AudioContext,e=t.createOscillator();e.type="triangle",e.frequency.setValueAtTime(20,t.currentTime);const n=t.createGain();n.gain.setValueAtTime(0,t.currentTime),e.connect(n);const r=t.createMediaStreamDestination();return n.connect(r),e.start(),r.stream.getAudioTracks()[0]},XN=()=>{var t,e;const n=new MediaStream().getVideoTracks()[0],r=document.createElement("canvas");r.height=(t=n==null?void 0:n.getSettings().height)!=null?t:720,r.width=(e=n==null?void 0:n.getSettings().width)!=null?e:1280;const i=r.getContext("2d");return i.fillStyle="black",i.fillRect(0,0,r.width,r.height),setInterval(()=>{i.fillStyle="black",i.fillRect(0,0,r.width,r.height)},1e3),r.captureStream().getVideoTracks()[0]};var ZN=Object.defineProperty,eL=Object.getOwnPropertyDescriptor,he=(t,e,n,r)=>{for(var i=r>1?void 0:r?eL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&ZN(e,n,i),i};const Wn=["video/VP9","video/VP8"];var al,ol,Pt,$,Ao,xi,Ft,Ls,xs,Vi,cl,xr,Do,Vs,Us,Bt,Qt,Ui,Fs,ft,Rt,Bs,Oo,vp,Xy,yp,Zy,Sp,eS;class ue{constructor(e,n,r){f(this,Ui),f(this,ft),f(this,Bs),f(this,vp),f(this,yp),f(this,Sp),g(this,"context"),g(this,"authToken"),g(this,"e2ee"),f(this,al,void 0),f(this,ol,void 0),f(this,Pt,void 0),f(this,$,void 0),f(this,Ao,void 0),f(this,xi,void 0),f(this,Ft,void 0),f(this,Ls,void 0),f(this,xs,void 0),f(this,Vi,void 0),f(this,cl,void 0),f(this,xr,void 0),f(this,Do,void 0),f(this,Vs,void 0),f(this,Us,void 0),f(this,Bt,void 0),f(this,Qt,void 0),g(this,"partialJoinRoomPromise");var i,s;this.context=e;const{socket:a}=r;this.mediaJoined=!1,v(this,Vs,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,Us,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,xi,n),v(this,Pt,a),v(this,Ls,!1),v(this,$,new KN(e,a,n)),v(this,Ft,o(this,$).events),v(this,xr,new Set),v(this,Bt,new Map),v(this,xs,!1),v(this,Vi,new Vd),n===tt.CF&&v(this,Qt,new fp(o(this,$).socketHandler.audioActivity.bind(o(this,$).socketHandler))),this.e2ee=(s=(i=e.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?s:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),v(this,cl,qc(()=>u(this,null,function*(){if(!o(this,Ui,Fs).mediaJoinAttempted)return;const{roomJoined:c}=yield this.joinRoom(o(this,ol),o(this,al),{},!0,!0);c&&(P.emit(R.RESET_PRODUCER_STATE),P.emit(R.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get mediaJoined(){return o(this,Ui,Fs).mediaJoined}set mediaJoined(e){o(this,Ui,Fs).mediaJoined=e}reset(e=!0){o(this,$).closeAllProducers(),o(this,$).closeAllConsumers(),o(this,Bt).clear(),o(this,xr).clear(),e&&(this.partialJoinRoomPromise=void 0,o(this,Vi).stop(),o(this,$).stopAllTransports(),o(this,$).reset(),v(this,Vi,new Vd))}joinRoom(e,n){return u(this,arguments,function*(r,i,s={},a=!1,c=!1){o(this,Ui,Fs).mediaJoinAttempted=!0,v(this,Ls,!0),this.reset(a);const d=ot().ipInfo;if(d!=null&&d.loc&&!o(this,Do)){const h=d.loc.split(",");v(this,Do,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let l;try{return l=yield o(this,Vi).push(()=>this._joinRoom(r,i,s,c,o(this,Do)),"joinRoom"),l}catch(h){l={roomJoined:!1}}return l.roomJoined||P.emit(R.ROOM_NODE_FAILED),l})}_partialJoinRoom(e,n,r=!1,i=void 0){return u(this,null,function*(){var s;const{ipInfo:a}=ot();let c=i;if(a!=null&&a.loc&&!i){const[h,m]=a.loc.split(",").map(parseFloat);c={latitude:h,longitude:m}}const d=(s=X.getValue(ie.FORCE_VIDEO_CODEC))==null?void 0:s.toString(),l=NN(d);v(this,Ao,l),yield Oh((h,m)=>u(this,null,function*(){if(!o(this,Pt).isConnected){m(new Error("socket is not connected"));return}h>0&&p.warn(`retrying sending join room request, count: ${h}`);try{yield o(this,$).socketHandler.joinRoom(n,e,l,r,c)}catch(y){throw p.error("failed to send join room request, error:",{error:y}),y}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:X.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),yield o(this,$).setupTransports({send:!0,recv:!0}),o(this,xi)!==tt.HIVE&&X.hasFeature(ie.PRECREATE_PRODUCERS)&&(this.shareWebcam(XN()),this.shareMic(QN()))})}partialJoinRoom(e,n,r=!1,i=void 0){return u(this,null,function*(){return this.partialJoinRoomPromise=o(this,Vi).push(()=>this._partialJoinRoom(e,n,r,i)),this.partialJoinRoomPromise})}_joinRoom(e,n){return u(this,arguments,function*(r,i,s={},a=!1,c=null){v(this,ol,r);try{this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,i,a,c)}catch(d){p.error("error in partial join room",{error:d})}finally{this.partialJoinRoomPromise=void 0}try{return navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const d={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:i,roomViewType:"groupCall",deviceInfo:G(x({},Ie.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};J.roomJoined(d)})),{roomJoined:yield this.completeJoinRoom()}}catch(d){return p.error("error on sending join room request",{error:d}),{roomJoined:!1}}})}completeJoinRoom(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:e}=yield o(this,$).socketHandler.notifySelfJoinComplete();return v(this,al,e.roomUuid),v(this,xs,!0),v(this,Ls,!1),!0}catch(e){return p.error("error on completing join room:",{error:e}),this.mediaJoined=!1,!1}})}leaveRoom(){return u(this,null,function*(){o(this,$).stopAllTransports(),v(this,xs,!1),o(this,Ui,Fs).mediaJoinAttempted=!1;const e={closeRoom:!1};o(this,Pt).sendMessagePromise(o(this,Ft).leaveRoom,qC.toBinary(e)).then(n=>{var r;(r=RP.fromBinary(n.payload))!=null&&r.closed||p.warn("weird state on peer closed and should not happen")}).catch(n=>{p.error("error on sending leave room request",{error:n})}),J.callEnded(),S.destruct()})}getConsumers(){return o(this,$).consumers}activatePeers(e){return u(this,null,function*(){return this.createConsumers(e)})}deactivatePeers(e,n="default"){return u(this,null,function*(){const r=new Set;e.forEach(s=>{s.screenShare&&s.kind==="video"&&r.add(s.producingPeerId)});const i=n==="default"?e.filter(s=>!r.has(s.producingPeerId)).filter(s=>s.kind!=="audio"):e;yield Promise.all(i.map(s=>{const a=o(this,$).producerIdToConsumerIdMap.get(s.producerId);if(!a){p.warn(`consumer not found in deactivate producers: ${s.producerId}`);return}return o(this,$).closeConsumer(a)}))})}createConsumers(e){return u(this,null,function*(){return e.length===0?Promise.resolve():o(this,$).createConsumers(e)})}closeConsumers(e){return u(this,null,function*(){if(!e.length)return;const n=e.reduce((r,i)=>{const s=o(this,$).producerIdToConsumerIdMap.get(i.producerId);return s?(r.push(s),r):(p.warn(`consumer not found in deactivate producers: ${i.producerId}`),r)},[]);yield o(this,$).closeConsumers(n)})}_shareWebcam(e,n){return u(this,null,function*(){const r=n==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,i=H(this,ft,Rt).call(this,r);if(i){const h=yield i;if(o(this,$).producers.has(h)){const m=o(this,$).producers.get(h);if(!m.closed&&!navigator.isReactNative)return yield m.replaceTrack({track:e}),yield this.resumeWebcam(r),e;yield this.disableWebcam(n)}return this._shareWebcam(e,n)}const s=H(this,Sp,eS).call(this,e,n),a=$c(this.context,"disableSimulcast"),c=o(this,xi)===tt.CF?ie.ENABLE_CF_SIMULCAST:ie.ENABLE_HIVE_SIMULCAST;!a&&X.hasFeature(c)?(p.info(`Simulcast enabled for SFU: ${o(this,xi)}`),s.encodings=RO(e)):p.info(`Simulcast disabled for webcam producer, SFU: ${o(this,xi)}`),X.hasFeature(ie.TRACK_HINT)&&(s.track.contentHint=X.getValue(ie.TRACK_HINT));const d=()=>{p.info("Disabling video due to the producer closure"),o(this,Bt).delete(r)},l=o(this,$).createProducer(s,d);return H(this,Bs,Oo).call(this,r,l.then(h=>h.id)),l.then(h=>h.track)})}shareWebcam(e){return u(this,null,function*(){if(e===void 0)return null;if(X.hasFeature(ie.FORCE_VIDEO_CODEC)){const n=X.getValue(ie.FORCE_VIDEO_CODEC).toString();if(n)return p.debug(`Calling _shareWebcam with forced video codec: ${n}`),this._shareWebcam(e,n)}return yield Promise.all(Wn.map(n=>{var r,i;return((i=(r=o(this,Ao).sender)==null?void 0:r.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===n))>=0&&o(this,Us).get(n).size>0?(p.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(e,n)):e})),e})}shareScreen(e){return u(this,null,function*(){const{video:n,audio:r}=e;if(n===void 0)return;const i={track:n,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1},s=()=>{p.info("Disabling screenShare due to the producer closure"),o(this,Bt).delete(ke.SCREENSHARE_VIDEO),o(this,Bt).delete(ke.SCREENSHARE_AUDIO)},a=o(this,$).createProducer(i,s);H(this,Bs,Oo).call(this,ke.SCREENSHARE_VIDEO,a.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1,zeroRtpOnPause:!0},l=()=>{};c=o(this,$).createProducer(d,l),H(this,Bs,Oo).call(this,ke.SCREENSHARE_AUDIO,c.then(h=>h.id))}yield Promise.all([a,c||Promise.resolve()]),J.screenShareStart()})}shareMic(e){return u(this,null,function*(){try{if(e===void 0)throw new Ut("track undefined");const n=H(this,ft,Rt).call(this,ke.MIC);if(n){const a=yield n;if(o(this,$).producers.has(a)){const c=o(this,$).producers.get(a);if(!c.closed&&!navigator.isReactNative){yield c.replaceTrack({track:e}),yield this.resumeMic(),o(this,Qt)&&(o(this,Qt).audioTrack=e,o(this,Qt).producerId=a,o(this,Qt).start());return}yield o(this,$).closeProducer(a,{stopTrack:!1})}yield this.shareMic(e);return}const r=H(this,yp,Zy).call(this,e),i=()=>{o(this,Bt).delete(ke.MIC)},s=o(this,$).createProducer(r,i);H(this,Bs,Oo).call(this,ke.MIC,s.then(a=>a.id)),yield s.then(a=>{o(this,Qt)&&(o(this,Qt).audioTrack=a.track,o(this,Qt).producerId=a.id,o(this,Qt).start())})}catch(n){throw new _(n)}})}pauseMic(){return u(this,null,function*(){const e=yield H(this,ft,Rt).call(this,ke.MIC),n=o(this,$).producers.get(e);if(!n){p.error("pauseMic::could_not_find_mic_producer");return}if(n.paused){p.info("pauseMic::mic_producer_already_paused");return}n.pause(),o(this,Qt).stop();const r={producerId:n.id,pause:!0};o(this,Pt).sendMessage(o(this,Ft).toggleProducer,Qc.toBinary(r))})}pauseWebcam(){return u(this,null,function*(){const e=yield H(this,ft,Rt).call(this,ke.WEBCAM),n=yield H(this,ft,Rt).call(this,ke.WEBCAM_BACKUP),r=o(this,$).producers.get(e),i=o(this,$).producers.get(n);if(!r&&!i){p.error("pauseWebcam::could_not_find_webcam_producer");return}const s=a=>{const c={producerId:a.id,pause:!0};o(this,Pt).sendMessage(o(this,Ft).toggleProducer,Qc.toBinary(c))};r&&(r.pause(),s(r)),i&&(i.pause(),s(i))})}resumeMic(){return u(this,null,function*(){const e=yield H(this,ft,Rt).call(this,ke.MIC),n=o(this,$).producers.get(e);if(!n){p.error("resumeMic::could_not_find_mic_producer");return}if(!n.pause){p.info("resumeMic::mic_producer_already_resumed");return}n.resume(),n.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,n);const r={producerId:n.id,pause:!1};o(this,Pt).sendMessage(o(this,Ft).toggleProducer,Qc.toBinary(r))})}resumeWebcam(){return u(this,arguments,function*(e=ke.WEBCAM){const n=yield H(this,ft,Rt).call(this,e),r=o(this,$).producers.get(n);if(!r){p.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){p.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};o(this,Pt).sendMessage(o(this,Ft).toggleProducer,Qc.toBinary(i))})}disableWebcam(e){return u(this,null,function*(){const n=e==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,r=yield H(this,ft,Rt).call(this,n);H(this,vp,Xy).call(this,n),r&&(yield o(this,$).closeProducer(r))})}disableMic(){return u(this,null,function*(){var e;const n=yield H(this,ft,Rt).call(this,ke.MIC);n&&(yield o(this,$).closeProducer(n)),(e=o(this,Qt))==null||e.stop(),o(this,Bt).delete(ke.MIC)})}disableScreenShare(){return u(this,null,function*(){p.info("screen_sharing_stopped"),J.screenShareStop();const e=yield H(this,ft,Rt).call(this,ke.SCREENSHARE_VIDEO),n=yield H(this,ft,Rt).call(this,ke.SCREENSHARE_AUDIO);e&&(yield o(this,$).closeProducer(e)),n&&(yield o(this,$).closeProducer(n)),o(this,xr).clear(),o(this,Bt).delete(ke.SCREENSHARE_VIDEO),o(this,Bt).delete(ke.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(e,n){return u(this,null,function*(){if(e){const r=yield H(this,ft,Rt).call(this,ke.WEBCAM),i=yield H(this,ft,Rt).call(this,ke.WEBCAM_BACKUP);yield o(this,$).closeProducer(r,{stopTrack:!1}),yield o(this,$).closeProducer(i,{stopTrack:!1}),this.shareWebcam(e)}if(n){const r=yield H(this,ft,Rt).call(this,ke.SCREENSHARE_VIDEO);yield o(this,$).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:n})}})}changeDisplayName(e,n){return u(this,null,function*(){const r={displayName:e,participantId:n!=null?n:this.peerId};if(!(yield o(this,$).socketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(e){return u(this,null,function*(){const n={participantId:e};if(!(yield o(this,$).socketHandler.kickPeer(n)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForPeer(e,"audio")))throw new Error("failed to mute given participant")})}disableVideo(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForPeer(e,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(e){return u(this,null,function*(){const n={participantId:e!=null?e:""};try{yield o(this,Pt).sendMessagePromise(o(this,Ft).globalPinPeer,eP.toBinary(n))}catch(r){p.error("Error in pinning peer:",{error:r})}})}validateScreenShare(e){return this.peerId===e.peerId&&o(this,$).producers.get(e.producerId)&&o(this,xr).add(e.consumerPeerId),o(this,xr).size}switchConsumersToLayer(e,n){return u(this,null,function*(){o(this,$).switchConsumersToLayer(e,n)})}handleSocketEvents(){return u(this,null,function*(){o(this,Pt).on(o(this,Ft).peerProducerCreateBroadcast,({payload:e})=>{var n,r;if(this.mediaJoined)try{const{participantId:i,producerState:s}=oR.fromBinary(e);if(i===this.peerId)return;if(s!=null&&s.mimeType||(s.mimeType=s.kind===Ln.AUDIO?"audio/opus":"video/VP8"),s.kind===Ln.VIDEO&&!s.screenShare&&((r=(n=o(this,Ao).receiver)==null?void 0:n.video)==null?void 0:r.codecs.findIndex(a=>a.mimeType===Wn[0]))>=0&&o(this,Vs).get(Wn[0]).has(i)&&s.mimeType!==Wn[0]){p.warn(`Ignoring producer: ${s.producerId}`);return}p.info(`producer created broadcast: ${i}, producer state: ${s}`),P.emit(R.NEW_PRODUCER,{peerId:i,producer:G(x({},s),{kind:s.kind===Ln.AUDIO?"audio":"video",producingPeerId:i})})}catch(i){p.error("error in peer-producer-create-broadcast",{error:i})}}),o(this,Pt).on(o(this,Ft).peerProducerToggleBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,initiatorParticipantId:r,producerState:{kind:i,pause:s,producerId:a}}=cv.fromBinary(e),c=i===Ln.AUDIO?"audio":"video";if(p.info(`producer toggle broadcast: ${n}, producerId: ${a}, kind:${c}, paused:${s} payload: ${JSON.stringify(cv.fromBinary(e))}`),n===this.peerId&&r!==this.peerId&&s&&P.emit(c==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),n===this.peerId)return;P.emit(R.PRODUCER_TOGGLE,{peerId:n,producerId:a,paused:s,kind:c}),Array.from(this.getConsumers().values()).filter(d=>d.producerId===a).forEach(d=>{d.paused!==s&&(p.debug(`consumer state mismatched for ${d.id}. updating consumer pause state ${d.paused} to ${s}`),s?(d.pause(),P.emit(R.CONSUMER_PAUSED,{id:d.id})):(d.resume(),P.emit(R.CONSUMER_RESUMED,{id:d.id})))})}catch(n){p.error("error in producer toggle broadcast handler",{error:n})}}),o(this,Pt).on(o(this,Ft).peerLeaveBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n}=Lu.fromBinary(e);if(n===this.peerId)return;p.info(`peer left broadcast:${n}`),o(this,xr).delete(n),o(this,$).consumers.forEach(r=>{r.peerId===n&&r.close()}),P.emit(R.PEER_CLOSED,{id:n})}catch(n){p.error("error in peer left broadcast",{error:n})}}),o(this,Pt).on(o(this,Ft).peerProducerCloseBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,producerState:{producerId:r}}=lR.fromBinary(e);if(n===this.peerId)return;p.info(`producer closed broadcast:${n}`),P.emit(R.PRODUCER_CLOSED,{peerId:n,producerId:r});const i=o(this,$).producerIdToConsumerIdMap.get(r);if(!i){p.warn(`no consumer found for producer:${r}`);return}p.info(`closing consumer ${i}, producer id: ${r}`),o(this,$).closeConsumer(i).then(()=>{p.info(`closed consumer: ${i}`),o(this,$).producerIdToConsumerIdMap.delete(r),P.emit(R.CONSUMER_CLOSED,{id:i})}).catch(s=>{p.error("error closing consumer",{error:s})})}catch(n){p.error("error on producer close broadcast",{error:n})}}),o(this,Pt).on(o(this,Ft).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!o(this,Ls)&&!o(this,xs)||(p.warn("media hub termination broadcast received, rejoining room"),P.emit(R.ROOM_NODE_DISCONNECTED),o(this,cl).call(this))})})}handleCallstatsEvents(){J.onConsumerScore(e=>{e.forEach((n,r)=>{const i=o(this,$).consumers.get(r);i&&P.emit(R.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:n.score,scoreStats:n})})}),J.onProducerScore(e=>{e.forEach((n,r)=>{const i=Array.from(o(this,$).producers.values()).find(s=>s.id===r);i&&P.emit(R.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:n.score,scoreStats:n})})})}handlePeerCapabilities(e,n){var r,i,s,a;for(let c=0;c<=Wn.length;c+=1){const d=Wn[c];if(((i=(r=n==null?void 0:n.receiver)==null?void 0:r.video)==null?void 0:i.codecs.findIndex(l=>l.mimeType===d))>=0||c===Wn.length-1){o(this,Us).get(d).add(e);break}}for(let c=0;c<=Wn.length;c+=1){const d=Wn[c];if(((a=(s=n==null?void 0:n.sender)==null?void 0:s.video)==null?void 0:a.codecs.findIndex(l=>l.mimeType===d))>=0||c===Wn.length-1){o(this,Vs).get(d).add(e);break}}}handlePeerLeaving(e){X.hasFeature(ie.FORCE_VIDEO_CODEC)||(o(this,Vs).forEach(n=>n.delete(e)),o(this,Us).forEach((n,r)=>{n.delete(e),n.size===0&&this.disableWebcam(r)}))}}al=new WeakMap,ol=new WeakMap,Pt=new WeakMap,$=new WeakMap,Ao=new WeakMap,xi=new WeakMap,Ft=new WeakMap,Ls=new WeakMap,xs=new WeakMap,Vi=new WeakMap,cl=new WeakMap,xr=new WeakMap,Do=new WeakMap,Vs=new WeakMap,Us=new WeakMap,Bt=new WeakMap,Qt=new WeakMap,Ui=new WeakSet,Fs=function(){return this.context.getValue("connectionHandler")},ft=new WeakSet,Rt=function(t){return o(this,Bt).get(t)},Bs=new WeakSet,Oo=function(t,e){return o(this,Bt).set(t,e)},vp=new WeakSet,Xy=function(t){return o(this,Bt).delete(t)},yp=new WeakSet,Zy=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0}},Sp=new WeakSet,eS=function(t,e){return{track:t,codecOptions:[{name:e?e.split("/")[1]:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},he([S.trace("MediaNodeClient.reset",{country:S.location.country})],ue.prototype,"reset",1),he([S.trace("MediaNodeClient.joinRoom")],ue.prototype,"joinRoom",1),he([S.trace("MediaNodeClient.completeJoinRoom")],ue.prototype,"completeJoinRoom",1),he([S.trace("MediaNodeClient.leaveRoom")],ue.prototype,"leaveRoom",1),he([S.trace("MediaNodeClient.activatePeers")],ue.prototype,"activatePeers",1),he([S.trace("MediaNodeClient.deactivatePeers")],ue.prototype,"deactivatePeers",1),he([S.trace("MediaNodeClient.createConsumers")],ue.prototype,"createConsumers",1),he([S.trace("MediaNodeClient.closeConsumers")],ue.prototype,"closeConsumers",1),he([S.trace("MediaNodeClient._shareWebcam")],ue.prototype,"_shareWebcam",1),he([S.trace("MediaNodeClient.shareWebcam")],ue.prototype,"shareWebcam",1),he([S.trace("MediaNodeClient.shareScreen")],ue.prototype,"shareScreen",1),he([S.trace("MediaNodeClient.shareMic")],ue.prototype,"shareMic",1),he([S.trace("MediaNodeClient.pauseMic")],ue.prototype,"pauseMic",1),he([S.trace("MediaNodeClient.pauseWebcam")],ue.prototype,"pauseWebcam",1),he([S.trace("MediaNodeClient.resumeMic")],ue.prototype,"resumeMic",1),he([S.trace("MediaNodeClient.resumeWebcam")],ue.prototype,"resumeWebcam",1),he([S.trace("MediaNodeClient.disableWebcam")],ue.prototype,"disableWebcam",1),he([S.trace("HiveClient.disableMic")],ue.prototype,"disableMic",1),he([S.trace("HiveClient.disableScreenShare")],ue.prototype,"disableScreenShare",1),he([S.trace("MediaNodeClient.muteSelf")],ue.prototype,"muteSelf",1),he([S.trace("MediaNodeClient.resetVideoProducers")],ue.prototype,"resetVideoProducers",1),he([S.trace("MediaNodeClient.changeDisplayName")],ue.prototype,"changeDisplayName",1),he([S.trace("MediaNodeClient.kickPeer")],ue.prototype,"kick",1),he([S.trace("MediaNodeClient.kickAllPeers")],ue.prototype,"kickAll",1),he([S.trace("MediaNodeClient.muteAll")],ue.prototype,"muteAll",1),he([S.trace("MediaNodeClient.muteAllVideo")],ue.prototype,"muteAllVideo",1),he([S.trace("MediaNodeClient.disableAudio")],ue.prototype,"disableAudio",1),he([S.trace("MediaNodeClient.disableVideo")],ue.prototype,"disableVideo",1),he([S.trace("MediaNodeClient.pinPeer")],ue.prototype,"pinPeer",1),he([S.trace("MediaNodeClient.validateScreenShare")],ue.prototype,"validateScreenShare",1);function tS(t,e,n){const r=t.getValue("roomNodeClient");if(r){if(r)return r;throw new Error("Room node client already set up.")}const i=new ue(t,e,n);return t.setValue("roomNodeClient",i),i}function nS(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(n){p.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var tL=Object.defineProperty,nL=Object.getOwnPropertyDescriptor,Fi=(t,e,n,r)=>{for(var i=r>1?void 0:r?nL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&tL(e,n,i),i},Bi,jn,Mt,an,wn,rS;const iS=(rS=class{constructor(t,e,n,r){f(this,an),g(this,"self"),g(this,"authToken"),f(this,Bi,void 0),g(this,"viewType"),f(this,jn,void 0),f(this,Mt,void 0);const{socket:i}=n,s=t.getValue("authToken");this.self=e,v(this,Mt,t),this.viewType=r,this.authToken=s,v(this,Bi,i),v(this,jn,n),e.config.viewType!==yt.Chat&&this.setupEvents()}get peerId(){return o(this,Mt).getValue("peerId")}get mediaJoined(){return o(this,Mt).getValue("connectionHandler").mediaJoined}static init(t,e,n,r,i){return u(this,null,function*(){const s=ot(),a=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield rt.__init__(t,n,r,i,i.name,c);if(navigator.product!=="ReactNative"){const l=!X.hasFeature(ie.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const h=yield d.getAllDevices();p.info("populated_full_device_list",{devices:JSON.stringify(h)}),J.devices("AUDIO",h==null?void 0:h.filter(m=>m.kind==="audioinput")),J.devices("VIDEO",h==null?void 0:h.filter(m=>m.kind==="videoinput")),J.devices("SPEAKER",h==null?void 0:h.filter(m=>m.kind==="audiooutput")),p.info("Callstats:: initializing");try{yield J.initialize({peerId:a,engineName:Ie.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:X.getAllFlags(),logger:p,apiHostnames:Gf(t),skipConnectivityChecks:l}),p.info("Callstats:: initialized")}catch(m){p.error("Callstats:: initialization failed",{error:m})}}),0)}else p.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new iS(t,d,e,i.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:n,permissions:r,audioEnabled:i,videoEnabled:s,screenShareEnabled:a,screenShareTracks:c}=this.self;if(r.canProduceAudio&&i)try{yield o(this,an,wn).shareMic(e)}catch(d){this.self.disableAudio()}if(r.canProduceVideo&&s)try{const d=yield o(this,an,wn).shareWebcam(n);d&&d.id!==n.id&&X.hasFeature(ie.EXP_RESHARE)&&(yield o(this,an,wn).shareWebcam(d))}catch(d){this.self.disableVideo()}if(r.canProduceScreenshare&&a)try{yield(t=o(this,an,wn))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}waitlistedHandler(){p.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(p.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){p.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(p.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){p.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){J.callEnded(),o(this,an,wn).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){P.on(R.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),P.on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),P.on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),P.on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),P.on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),P.on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&X.hasFeature(ie.REFRESH_ID_ON_DISCONNECTION)&&(e=Gi()),o(this,Bi).updateURL(e),S.resetPeerId(e),ot().setHeader("dyte-tracing-id",e),ri.remapContext(e,o(this,Mt)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),P.on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),o(this,jn).on(W.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),o(this,jn).on(rd.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&P.emit(R.UPDATE_PERMISSIONS,e.patch)})}),o(this,jn).on(W.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),o(this,jn).on(W.kick,()=>{this.kickHandler({kickType:"kick"})}),o(this,jn).on(W.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),P.onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),P.on(R.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:n,scoreStats:r})=>{var i;const s=(i=n==null?void 0:n.screenShare)!=null?i:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:r})}),P.on(R.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),J.audioOff())})),P.on(R.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),J.videoOff())})),P.onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),P.on(R.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield o(this,jn).joinRoom(this.self);o(this,jn).socket.flush();const n=lh(e.stageType);if(o(this,Mt).setValue("stageStatus",n,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),o(this,Mt).notify("stageStatus")}catch(e){throw p.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,n;if(t==="rejected"){try{(e=o(this,Bi))==null||e.disconnect()}catch(r){p.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),o(this,Mt).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),o(this,Mt).notify("stageStatus");try{(n=o(this,Bi))==null||n.disconnect()}catch(r){p.error("SelfController::leaveRoom::socketDisconnect")}nS(o(this,Mt)),Ld.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,n;const{peerId:r,viewType:i,meetingId:s,stageStatus:a,roomNodeOptions:c}=o(this,Mt).getAllValues(),{sfu:d}=c;try{if(i===yt.Livestream){if(a!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}tS(o(this,Mt),d,{socket:o(this,Bi),peerId:r})}const{roomJoined:l}=(n=yield(e=o(this,an,wn))==null?void 0:e.joinRoom(this.self.name,s,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},t,t))!=null?n:{};if(!l)return;a==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw p.error("Error:SelfController.mediaRoomJoin",{error:l}),new _("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=o(this,Mt).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===yt.Webinar)&&o(this,an,wn)&&(o(this,an,wn).mediaJoined&&t!=="disconnected"&&(yield o(this,an,wn).leaveRoom()),!(t==="stageLeft"&&e===yt.Livestream)&&(o(this,an,wn).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()})}},Bi=new WeakMap,jn=new WeakMap,Mt=new WeakMap,an=new WeakSet,wn=function(){return o(this,Mt).getValue("roomNodeClient")},rS);let Vr=iS;Fi([S.trace("SelfController.resetSelf")],Vr.prototype,"resetSelf",1),Fi([S.trace("SelfController.setupEvents")],Vr.prototype,"setupEvents",1),Fi([S.trace("SelfController.joinRoom")],Vr.prototype,"joinRoom",1),Fi([S.trace("SelfController.leaveRoom")],Vr.prototype,"leaveRoom",1),Fi([S.trace("SelfController.joinMediaRoom")],Vr.prototype,"joinMediaRoom",1),Fi([S.trace("SelfController.leaveMediaRoom")],Vr.prototype,"leaveMediaRoom",1),Fi([S.trace("SelfController.init")],Vr,"init",1);var dl;class rL{constructor(e){f(this,dl,void 0),v(this,dl,e)}on(e,n){let r;e===W.roomPeerCount?r=uv.fromBinary.bind(uv):r=Cv.fromBinary.bind(Cv),o(this,dl).on(e,({payload:i})=>{const s=r(i);return n(s)})}}dl=new WeakMap;var ll;class iL{constructor(e){f(this,ll,void 0),v(this,ll,e)}on(e,n){let r,i;switch(e){case W.transcript:{r=xu.fromBinary.bind(xu),i=xu.create();break}default:{p.debug("AISocketHandler switch case hit default, event not accounted for.");break}}o(this,ll).on(e,({payload:s})=>{let a=i;try{a=r(s)}catch(c){p.error("chatSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}}ll=new WeakMap;var sL=Object.defineProperty,aL=Object.getOwnPropertyDescriptor,Ep=(t,e,n,r)=>{for(var i=r>1?void 0:r?aL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&sL(e,n,i),i},Ur;class ul{constructor(e){f(this,Ur,void 0),v(this,Ur,e)}getPolls(){return o(this,Ur).sendMessagePromise(Xn.getPolls)}createPoll(e,n,r=!1,i=!1){const s={anonymous:r,hideVotes:i,question:e,options:n};return o(this,Ur).sendMessage(Xn.createPoll,Z1.toBinary(s))}votePoll(e,n){const r={index:n,pollId:e};return o(this,Ur).sendMessage(Xn.votePoll,tD.toBinary(r))}on(e,n){let r,i;switch(e){case Xn.updatePoll:case Xn.createPoll:case Xn.votePoll:{r=zu.fromBinary.bind(zu),i=zu.create();break}}o(this,Ur).on(e,({payload:s})=>{let a=i;try{a=r(s)}catch(c){p.error("pollSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}removeListeners(e){o(this,Ur).removeListeners(e)}}Ur=new WeakMap,Ep([S.trace("PollSocketHandler.getPolls")],ul.prototype,"getPolls",1),Ep([S.trace("PollSocketHandler.createPoll")],ul.prototype,"createPoll",1),Ep([S.trace("PollSocketHandler.votePoll")],ul.prototype,"votePoll",1);var Xt;class oL{constructor(e){f(this,Xt,void 0),v(this,Xt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield o(this,Xt).sendMessagePromise(W.getStageRequests);return e?Ku.fromBinary(e):{stageRequests:[]}})}requestAccess(){o(this,Xt).sendMessage(W.requestStageAccess)}cancelRequestAccess(){o(this,Xt).sendMessage(W.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const n={userIds:e};o(this,Xt).sendMessage(W.grantStageAccess,H1.toBinary(n))})}denyAccess(e){return u(this,null,function*(){const n={userIds:e};o(this,Xt).sendMessage(W.denyStageAccess,G1.toBinary(n))})}joinStage(){return o(this,Xt).sendMessagePromise(W.joinStage,void 0,void 0,W.peerStageStatusUpdate)}leaveStage(e){const n={userIds:[e]};return o(this,Xt).sendMessagePromise(W.leaveStage,Rv.toBinary(n),void 0,W.peerStageStatusUpdate)}kick(e){const n={userIds:e};return o(this,Xt).sendMessagePromise(W.leaveStage,Rv.toBinary(n))}on(e,n){let r;switch(e){case W.grantStageAccess:case W.denyStageAccess:{r=void 0;break}case W.getStagePeers:{r=Pv.fromBinary.bind(Pv);break}case W.getStageRequests:case W.requestStageAccess:case W.cancelStageRequest:{r=Ku.fromBinary.bind(Ku);break}case W.peerStageStatusUpdate:{r=lv.fromBinary.bind(lv);break}}o(this,Xt).on(e,({payload:i,id:s})=>{if(!i||!r)return n(void 0,s);const a=r(i);return n(a,s)})}getPeerInfo(e){return u(this,null,function*(){const n=yield o(this,Xt).sendMessagePromise(W.getPeerInfo,mv.toBinary({peerId:e}));return ts.fromBinary(n.payload)})}}Xt=new WeakMap;var it;class cL{constructor(e){f(this,it,void 0),v(this,it,e)}addPlugin(e,n){o(this,it).sendMessage(z.addPlugin,a1.toBinary({pluginId:e,staggered:n}))}removePlugin(e){o(this,it).sendMessage(z.removePlugin,c1.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield o(this,it).sendMessagePromise(z.getPlugins);return e?A1.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,n,r){const i={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(n))};o(this,it).sendMessage(z.customPluginEventToRoom,y1.toBinary(i),r)}customPluginEventToPeers(e,n,r,i){const s={pluginId:e,peerIds:n,pluginData:new TextEncoder().encode(JSON.stringify(r))};o(this,it).sendMessage(z.customPluginEventToPeers,E1.toBinary(s),i)}enablePluginForRoom(e,n){o(this,it).sendMessage(z.enablePluginForRoom,l1.toBinary({pluginId:e}),n)}enablePluginForPeers(e,n,r){o(this,it).sendMessage(z.enablePluginForPeers,m1.toBinary({pluginId:e,peerIds:n}),r)}disablePluginForRoom(e,n){o(this,it).sendMessage(z.disablePluginForRoom,h1.toBinary({pluginId:e}),n)}disablePluginForPeers(e,n,r){o(this,it).sendMessage(z.disablePluginForPeers,f1.toBinary({pluginId:e,peerIds:n}),r)}storeInsertKeys(e,n,r,i){const s={pluginId:e,storeName:n,insertKeys:r.map(a=>({storeKey:a.key,payload:new TextEncoder().encode(JSON.stringify(a.payload))}))};o(this,it).sendMessage(z.storeInsertKeys,bv.toBinary(s),i)}storeGetKeys(e,n,r,i){const s={pluginId:e,storeName:n,getKeys:r.map(a=>({storeKey:a.key}))};o(this,it).sendMessage(z.storeGetKeys,w1.toBinary(s),i)}storeDeleteKeys(e,n,r,i){const s={pluginId:e,storeName:n,deleteKeys:r.map(a=>({storeKey:a.key}))};o(this,it).sendMessage(z.storeDeleteKeys,I1.toBinary(s),i)}storeDelete(e,n,r){o(this,it).sendMessage(z.storeDelete,P1.toBinary({pluginId:e,storeName:n}),r)}getPluginDataOld(e,n){p.info("getPluginDataOld",{plugin:{id:e,storeName:n}})}storePluginDataOld(e,n,r){const i={pluginId:e,storeName:n,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};o(this,it).sendMessage(z.storeInsertKeys,bv.toBinary(i))}on(e,n){let r;switch(e){case z.addPlugin:case z.enablePluginForPeers:case z.enablePluginForRoom:{r=$u.fromBinary.bind($u);break}case z.removePlugin:case z.disablePluginForPeers:case z.disablePluginForRoom:{r=wv.fromBinary.bind(wv);break}case z.customPluginEventToPeers:case z.customPluginEventToRoom:{r=Iv.fromBinary.bind(Iv);break}case z.storeInsertKeys:case z.storeGetKeys:case z.storeDeleteKeys:case z.storeDelete:{r=_v.fromBinary.bind(_v);break}}o(this,it).on(e,({payload:i,id:s})=>{const a=r(i);return n(a,s)})}}it=new WeakMap;var dL=Object.defineProperty,lL=(t,e,n)=>e in t?dL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,uL=(t,e,n)=>(lL(t,typeof e!="symbol"?e+"":e,n),n),Tp=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)},L=(t,e,n)=>(Tp(t,e,"read from private field"),n?n.call(t):e.get(t)),Ce=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},me=(t,e,n,r)=>(Tp(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Me=(t,e,n)=>(Tp(t,e,"access private method"),n),hl={},hL={get exports(){return hl},set exports(t){hl=t}},Ws=typeof Reflect=="object"?Reflect:null,sS=Ws&&typeof Ws.apply=="function"?Ws.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)},pl;Ws&&typeof Ws.ownKeys=="function"?pl=Ws.ownKeys:Object.getOwnPropertySymbols?pl=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:pl=function(t){return Object.getOwnPropertyNames(t)};function pL(t){console&&console.warn&&console.warn(t)}var aS=Number.isNaN||function(t){return t!==t};function fe(){fe.init.call(this)}hL.exports=fe,hl.once=vL,fe.EventEmitter=fe,fe.prototype._events=void 0,fe.prototype._eventsCount=0,fe.prototype._maxListeners=void 0;var oS=10;function ml(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(fe,"defaultMaxListeners",{enumerable:!0,get:function(){return oS},set:function(t){if(typeof t!="number"||t<0||aS(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");oS=t}}),fe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},fe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||aS(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 cS(t){return t._maxListeners===void 0?fe.defaultMaxListeners:t._maxListeners}fe.prototype.getMaxListeners=function(){return cS(this)},fe.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var r=t==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=i[t];if(c===void 0)return!1;if(typeof c=="function")sS(c,this,e);else for(var d=c.length,l=pS(c,d),n=0;n<d;++n)sS(l[n],this,e);return!0};function dS(t,e,n,r){var i,s,a;if(ml(n),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),s=t._events),a=s[e]),a===void 0)a=s[e]=n,++t._eventsCount;else if(typeof a=="function"?a=s[e]=r?[n,a]:[a,n]:r?a.unshift(n):a.push(n),i=cS(t),i>0&&a.length>i&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=a.length,pL(c)}return t}fe.prototype.addListener=function(t,e){return dS(this,t,e,!1)},fe.prototype.on=fe.prototype.addListener,fe.prototype.prependListener=function(t,e){return dS(this,t,e,!0)};function mL(){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 lS(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=mL.bind(r);return i.listener=n,r.wrapFn=i,i}fe.prototype.once=function(t,e){return ml(e),this.on(t,lS(this,t,e)),this},fe.prototype.prependOnceListener=function(t,e){return ml(e),this.prependListener(t,lS(this,t,e)),this},fe.prototype.removeListener=function(t,e){var n,r,i,s,a;if(ml(e),r=this._events,r===void 0)return this;if(n=r[t],n===void 0)return this;if(n===e||n.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,n.listener||e));else if(typeof n!="function"){for(i=-1,s=n.length-1;s>=0;s--)if(n[s]===e||n[s].listener===e){a=n[s].listener,i=s;break}if(i<0)return this;i===0?n.shift():gL(n,i),n.length===1&&(r[t]=n[0]),r.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this},fe.prototype.off=fe.prototype.removeListener,fe.prototype.removeAllListeners=function(t){var e,n,r;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var i=Object.keys(n),s;for(r=0;r<i.length;++r)s=i[r],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=n[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(r=e.length-1;r>=0;r--)this.removeListener(t,e[r]);return this};function uS(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?fL(i):pS(i,i.length)}fe.prototype.listeners=function(t){return uS(this,t,!0)},fe.prototype.rawListeners=function(t){return uS(this,t,!1)},fe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):hS.call(t,e)},fe.prototype.listenerCount=hS;function hS(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}fe.prototype.eventNames=function(){return this._eventsCount>0?pl(this._events):[]};function pS(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function gL(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function fL(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function vL(t,e){return new Promise(function(n,r){function i(a){t.removeListener(e,s),r(a)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),n([].slice.call(arguments))}mS(t,e,s,{once:!0}),e!=="error"&&yL(t,i,{once:!0})})}function yL(t,e,n){typeof t.on=="function"&&mS(t,"error",e,n)}function mS(t,e,n,r){if(typeof t.on=="function")r.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){r.once&&t.removeEventListener(e,i),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class SL extends E{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 gS=new SL;class fS{static encode(e){return gS.toBinary(e)}static decode(e){return gS.fromBinary(new Uint8Array(e))}}function EL(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Fr;class TL{constructor(e={}){uL(this,"opts"),Ce(this,Fr,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},me(this,Fr,0)}wait(){return u(this,null,function*(){me(this,Fr,L(this,Fr)+1);const e=EL(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*ME(2,L(this,Fr))));yield new Promise(n=>{setTimeout(n,e)})})}getAttempts(){return L(this,Fr)}reset(){me(this,Fr,0)}}Fr=new WeakMap;const Br={debug:0,info:1,warn:2,error:3};var Wi,ji;class kL{constructor(e){Ce(this,Wi,void 0),Ce(this,ji,void 0),me(this,Wi,console),me(this,ji,e)}debug(...e){Br[L(this,ji)]>Br.debug||L(this,Wi).debug("[Sockrates]:",...e)}info(...e){Br[L(this,ji)]>Br.info||L(this,Wi).info("[Sockrates]:",...e)}warn(...e){Br[L(this,ji)]>Br.warn||L(this,Wi).warn("[Sockrates]:",...e)}error(...e){Br[L(this,ji)]>Br.error||L(this,Wi).error("[Sockrates]:",...e)}}Wi=new WeakMap,ji=new WeakMap;var vS=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(vS||{});const bL="2",wL="3";var xe,js,Ae,He,Wr,st,cr,jr,_n,Hs,dr,kp,yS,No,gl,bp,SS,wp,ES,fl,_p,Ip,TS,Lo,vl,xo,yl,Sl,Cp,qs,Vo,Uo,El;class _L{constructor(e,n){var r;Ce(this,kp),Ce(this,No),Ce(this,bp),Ce(this,wp),Ce(this,fl),Ce(this,Ip),Ce(this,Lo),Ce(this,xo),Ce(this,Sl),Ce(this,qs),Ce(this,Uo),Ce(this,xe,void 0),Ce(this,js,void 0),Ce(this,Ae,void 0),Ce(this,He,void 0),Ce(this,Wr,void 0),Ce(this,st,void 0),Ce(this,cr,void 0),Ce(this,jr,void 0),Ce(this,_n,void 0),Ce(this,Hs,void 0),Ce(this,dr,void 0);var i,s,a,c,d,l,h,m,y;me(this,js,e),me(this,Wr,[]),me(this,st,new hl),me(this,cr,!0),me(this,_n,!1),me(this,Ae,n!=null?n:{}),(i=L(this,Ae)).autoReconnect!=null||(i.autoReconnect=!0),(s=L(this,Ae)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(a=L(this,Ae)).pingTimeout!=null||(a.pingTimeout=3e4),(c=L(this,Ae)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=L(this,Ae)).debug!=null||(d.debug=!0),(l=L(this,Ae)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(h=L(this,Ae)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(m=L(this,Ae)).queueOnDisconnect!=null||(m.queueOnDisconnect=!1),(y=L(this,Ae)).flushOnReconnect!=null||(y.flushOnReconnect=!1),me(this,jr,{code:void 0,reason:void 0}),me(this,He,(r=L(this,Ae).logger)!=null?r:new kL(L(this,Ae).debug?"debug":"info")),me(this,dr,new TL)}get readyState(){var e;return(e=L(this,xe))==null?void 0:e.readyState}get url(){return L(this,js)}updateURL(e){me(this,js,e),Me(this,Ip,TS).call(this)}get config(){return L(this,Ae)}get sendQueue(){return L(this,Wr)}flush(){if(!L(this,Ae).queueOnDisconnect)return!1;const e=[];return L(this,Wr).forEach(n=>{this.send(n.event,n.id,n.payload,n.metadata)||e.push(n)}),me(this,Wr,e),L(this,Wr)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){L(this,He).debug("Websocket was already connecting or connected.");return}if(L(this,cr)!==!1)return new Promise((n,r)=>{Me(this,qs,Vo).call(this),Me(this,Uo,El).call(this);try{me(this,xe,new WebSocket(Me(this,kp,yS).call(this,L(this,js)))),L(this,xe).binaryType="arraybuffer",L(this,He).debug("Connecting");const i=setTimeout(()=>{L(this,He).debug("Connection timeout. Closing socket"),me(this,cr,!0),Me(this,Uo,El).call(this),L(this,xe).close(3001,"Connection Timeout"),L(this,Ae).autoReconnect&&!L(this,_n)&&(L(this,st).emit("reconnecting"),Me(this,Lo,vl).call(this)),r(new Error("Connection timed out!"))},L(this,Ae).connectionTimeout);L(this,xe).onopen=()=>{L(this,He).debug(`Ready State: ${vS[L(this,xe).readyState]}`),i&&clearTimeout(i),Me(this,Sl,Cp).call(this),me(this,jr,{code:void 0,reason:void 0}),L(this,st).emit("connected"),L(this,Ae).flushOnReconnect&&this.flush(),n()},L(this,xe).onclose=s=>{try{i&&clearTimeout(i);const{code:a,reason:c}=s;r(c),L(this,He).debug("Socket closed. Close event:",{event:s}),L(this,He).debug(`Connection closed code: ${a}`),L(this,He).debug(`Connection closed reason: ${c}`),L(this,_n)||Me(this,fl,_p).call(this,a,c)}catch(a){Me(this,No,gl).call(this,a)}},L(this,xe).onerror=s=>{Me(this,No,gl).call(this,s)},L(this,xe).onmessage=s=>Me(this,bp,SS).call(this,s)}catch(i){Me(this,No,gl).call(this,i,r)}})})}send(e,n,r,i){const s={event:e,id:n,payload:r,metadata:i};if(L(this,Ae).queueOnDisconnect&&(!L(this,xe)||L(this,xe).readyState!==1))return L(this,He).debug("Queuing message since socket is not connected!",s),L(this,Wr).push(s),!1;const a=fS.encode(s);return Me(this,xo,yl).call(this,a)}emit(e,n,r,i){return this.send(e,n,r,i)}sendRaw(e){return Me(this,xo,yl).call(this,e)}receive(e,n){return L(this,st).on(e.toString(),n)}on(e,n){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){L(this,st).on(e,n);return}this.receive(e,n)}removeAllListeners(){L(this,st).removeAllListeners()}removeReceiver(e,n){this.removeListener(e,n)}removeListener(e,n){L(this,st).removeListener(e.toString(),n)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){L(this,st).listeners(e.toString()).map(n=>this.removeListener(e,n))}disconnect(){me(this,cr,!1),Me(this,qs,Vo).call(this),this.removeAllListeners(),me(this,jr,{code:1e3,reason:"Sockrates disconnect method called"}),L(this,xe).close(1e3,"Sockrates disconnect method called.")}}xe=new WeakMap,js=new WeakMap,Ae=new WeakMap,He=new WeakMap,Wr=new WeakMap,st=new WeakMap,cr=new WeakMap,jr=new WeakMap,_n=new WeakMap,Hs=new WeakMap,dr=new WeakMap,kp=new WeakSet,yS=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)://.")},No=new WeakSet,gl=function(t,e){L(this,He).error("Error:",{error:t}),L(this,st).emit("errored",{error:t}),e==null||e(t)},bp=new WeakSet,SS=function(t){if(Me(this,Sl,Cp).call(this),t.data===bL){L(this,He).debug("Received ping from server"),Me(this,xo,yl).call(this,wL);return}const e=fS.decode(t.data),{id:n,payload:r}=e;L(this,He).debug("Received message",{event:e.event,messageID:n}),L(this,st).emit(e.event.toString(),{id:n,payload:r})},wp=new WeakSet,ES=function(){return L(this,xe).readyState===1},fl=new WeakSet,_p=function(t,e){me(this,jr,{reason:e,code:t}),L(this,st).emit("disconnected",{code:t,reason:e})},Ip=new WeakSet,TS=function(){const{reason:t,code:e}=L(this,jr);e&&e!==1e3&&L(this,cr)&&L(this,Ae).autoReconnect&&!L(this,_n)&&(L(this,He).debug(`Triggering reconnection due to ${t}.`),L(this,st).emit("reconnecting"),Me(this,Lo,vl).call(this))},Lo=new WeakSet,vl=function(t=!0){return u(this,null,function*(){if(t&&L(this,_n)){L(this,He).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(L(this,_n)||L(this,dr).reset(),L(this,Ae).maxReconnectionAttempts!==null&&L(this,dr).getAttempts()>=L(this,Ae).maxReconnectionAttempts){L(this,st).emit("failed"),me(this,_n,!1);return}me(this,_n,!0),Me(this,Uo,El).call(this),Me(this,qs,Vo).call(this);try{if(yield L(this,dr).wait(),L(this,cr)===!1)return;if(L(this,He).debug(`Reconnection attempt ${L(this,dr).getAttempts()}`),L(this,st).emit("reconnectAttempt",{attempt:L(this,dr).getAttempts()}),yield this.connect(),!Me(this,wp,ES).call(this))throw Error("Reconnect Failed");me(this,_n,!1),me(this,jr,{code:void 0,reason:void 0}),L(this,st).emit("reconnected")}catch(e){L(this,He).debug("Failed to reconnect."),L(this,st).emit("reconnectFailure",{attempt:L(this,dr).getAttempts()}),Me(this,Lo,vl).call(this,!1)}})},xo=new WeakSet,yl=function(t){try{return L(this,xe).send(t),!0}catch(e){return L(this,He).error(e.message),!1}},Sl=new WeakSet,Cp=function(){this.config.disconnectOnPingTimeout&&(L(this,He).debug("Resetting ping timeout"),Me(this,qs,Vo).call(this),me(this,Hs,setTimeout(()=>{var t;L(this,He).debug("Disconnecting the socket due to ping timeout"),me(this,cr,!0);const e=3002,n="Ping timeout";(t=L(this,xe))==null||t.close(e,n),Me(this,fl,_p).call(this,e,n)},L(this,Ae).pingTimeout)))},qs=new WeakSet,Vo=function(){L(this,Hs)&&(clearTimeout(L(this,Hs)),me(this,Hs,void 0))},Uo=new WeakSet,El=function(){L(this,xe)&&(L(this,xe).onopen=void 0,L(this,xe).onerror=void 0,L(this,xe).onmessage=void 0,L(this,xe).onclose=void 0)};var IL=Object.defineProperty,CL=Object.getOwnPropertyDescriptor,Tl=(t,e,n,r)=>{for(var i=r>1?void 0:r?CL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&IL(e,n,i),i};const kS=65535,PL=3e3;var Hi,Ve,Ue,qe,In,Hr,kl,Pp,bl,Rp,bS;const wS=(bS=class{constructor(t,{peerId:e,meetingId:n,authToken:r,capabilities:i}){f(this,Ue),f(this,kl),f(this,bl),f(this,Hi,void 0),f(this,Ve,void 0),g(this,"roomName"),g(this,"authToken"),g(this,"capabilities"),f(this,In,void 0),f(this,Hr,void 0);var s;if(!e||!n||!r)throw new _("peerId, meetingId, or authToken can not be empty","0404");v(this,In,void 0),v(this,Hr,t),this.capabilities=i,this.roomName=n,this.authToken=r,v(this,Hi,H(this,kl,Pp).call(this,e)),v(this,Ve,new _L(o(this,Hi),{autoReconnect:!0,disconnectOnPingTimeout:(s=i.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:p})),this.handleSocketConnectionEvents()}get joinAttempted(){return o(this,Ue,qe).socketJoinAttempted}set joinAttempted(t){o(this,Ue,qe).socketJoinAttempted=t}get peerId(){return o(this,Hr).getValue("peerId")}updateURL(t){t!==this.peerId&&(v(this,Hi,H(this,kl,Pp).call(this,t)),p.debug("SocketService:: Connection URL updated.")),o(this,Ve).updateURL(o(this,Hi))}static getSocketEdgeDomain(t){return Zi({servicePrefix:"socket-edge",baseURI:t})}get url(){return o(this,Hi)}connect(){return u(this,null,function*(){o(this,Ue,qe).socketJoinAttempted=!0,yield o(this,Ve).connect(),o(this,Ue,qe).socketJoinAttempted=!0,o(this,Ue,qe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){o(this,Ue,qe).socketJoinAttempted=!1,o(this,Ve).disconnect(),o(this,Ue,qe).socketJoinAttempted=!0,o(this,Ue,qe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return o(this,Ve).readyState===1}catch(t){return!1}}sendMessage(t,e,n){const r={};return S.injectContext(r),o(this,Ve).send(t,n!=null?n:H(this,bl,Rp).call(this),e,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(t,e,n,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:i,protobuf:e,messageId:n,resp:r})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:n,messageId:r,resp:i}){const s=i!=null?i:t;return new Promise((a,c)=>{const d=(T,b)=>{o(this,Ve).removeListener(s,T),o(this,Ve).removeListener(kS,b),o(this,Ve).removeListener(en.errorResponse,b),o(this,Ve).removeListener(pn.errorResponse,b)},l=r!=null?r:H(this,bl,Rp).call(this),h={};S.injectContext(h);const m=({id:T,payload:b})=>{if(l===T){let O;try{const M=SP.fromBinary(b);O=new Error(M.errorMessage)}catch(M){O=new Error("failed to parse error message",{cause:M});try{const F=kR.fromBinary(b);O=new Error(F.message)}catch(F){O=new Error("failed to parse error message",{cause:F})}}c(O),d(y,m)}},y=({id:T,payload:b})=>{l===T&&(a({id:T,payload:b}),d(y,m))};o(this,Ve).on(s,y),o(this,Ve).on(kS,m),o(this,Ve).on(en.errorResponse,m),o(this,Ve).on(pn.errorResponse,m),setTimeout(()=>{d(y,m),c(new Error(`request timeout for callback eventId:${t}`))},e),o(this,Ve).send(t,l,n,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){o(this,Ve).on(t,e)}onStateEvent(t,e){o(this,Ve).on(t,e)}removeListener(t,e){o(this,Ve).removeListener(t,e)}removeListeners(t){o(this,Ve).removeListeners(t)}flush(){return o(this,Ve).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){p.info("SocketService::Connected to socket-edge"),o(this,In)&&(clearTimeout(o(this,In)),v(this,In,void 0)),o(this,Ue,qe).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var n;p.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:S.location.country});const{recv:r,send:i}=(n=o(this,Ue,qe).mediaState)!=null?n:{};r!=null&&r.state&&(r==null?void 0:r.state)!==Rr.CONNECTED||i!=null&&i.state&&(i==null?void 0:i.state)!==Rr.CONNECTED?P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,Ue,qe).joinAttempted}):v(this,In,setTimeout(()=>{P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,Ue,qe).joinAttempted}),v(this,In,void 0)},PL)),o(this,Ue,qe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){p.info("SocketService::Reconnecting to socket-edge",{country:S.location.country}),o(this,Ue,qe).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){p.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),o(this,Ue,qe).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{p.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),o(this,Ue,qe).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){p.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:o(this,Ue,qe).mediaJoinAttempted}}),o(this,In)&&(clearTimeout(o(this,In)),v(this,In,void 0)),P.emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:o(this,Ue,qe).mediaJoinAttempted}),o(this,Ue,qe).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){p.info("SocketService::Failed to connect to socket-edge",{country:S.location.country}),P.emit(R.SOCKET_SERVICE_FAILED),o(this,Ue,qe).updateSocketConnectionState("failed")}))}},Hi=new WeakMap,Ve=new WeakMap,Ue=new WeakSet,qe=function(){return o(this,Hr).getValue("connectionHandler")},In=new WeakMap,Hr=new WeakMap,kl=new WeakSet,Pp=function(t){let e=wS.getSocketEdgeDomain(o(this,Hr).getValue("baseURI"));typeof $c(o(this,Hr),"socket_server_base")=="string"&&(e=$c(o(this,Hr),"socket_server_base"));const n=`wss://${e}`,r=new URL(`${n}/ws`),i=this.peerId,s=G(x({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},i!==t&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>Xc[a]).join(" "),joinWithDetails:!0,useCfWorker:!0});return Object.entries(s).forEach(([a,c])=>{r.searchParams.append(a,c.toString())}),r.href},bl=new WeakSet,Rp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},bS);let Fo=wS;Tl([S.trace("SocketService.connect")],Fo.prototype,"connect",1),Tl([S.trace("SocketService.disconnect")],Fo.prototype,"disconnect",1),Tl([S.trace("SocketService.sendMessagePromise")],Fo.prototype,"sendMessagePromise",1),Tl([S.trace("SocketService.sendMessagePromiseWithTimeout")],Fo.prototype,"sendMessagePromiseWithTimeout",1);const qi=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const n=zR.fromBinary(t),r=n.meetings.map(i=>{var s;return{id:i.id,title:i.title,participants:(s=i.participants)!=null?s:[]}});return{parentMeeting:{id:n.parentMeeting.id,title:n.parentMeeting.title,participants:(e=n.parentMeeting.participants)!=null?e:[]},meetings:r}}static handleTransferPeerRaw({payload:t}){const e=TM.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=vv.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return fv.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return uM.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield qi.socketService.sendMessagePromise(W.getConnectedRoomsDump);return qi.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield qi.socketService.sendMessagePromise(W.createConnectedRooms,ZR.toBinary({payloads:t}));return fv.fromBinary(e).payloads.map(n=>({id:n.id,title:n.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(r=>({id:r})),n=yield qi.socketService.sendMessagePromise(W.deleteConnectedRooms,dM.toBinary({payloads:e}));return qi.handleConnectedRoomsDeletedRaw(n)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield qi.socketService.sendMessagePromise(W.movePeers,vM.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}};let Ne=qi;g(Ne,"socketService"),g(Ne,"currentMeetingId");var RL=Object.defineProperty,ML=Object.getOwnPropertyDescriptor,wl=(t,e,n,r)=>{for(var i=r>1?void 0:r?ML(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&RL(e,n,i),i};const Gs=class{constructor(t,e){g(this,"apiBase"),g(this,"selfController"),g(this,"pollController"),g(this,"chatController"),g(this,"metaController"),g(this,"storesManager"),g(this,"stageController"),g(this,"pluginController"),g(this,"internalsController"),g(this,"recordingController"),g(this,"livestreamController"),g(this,"participantController"),this.apiBase=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController}static init(t){return u(this,null,function*(){var e,n;const{peerId:r,apiBase:i,authToken:s,meetingId:a,organizationId:c,cachedUserDetails:d}=t.getAllValues();if(P.reset(),Ld.cleanup(),nS(t),Ie.isSupported()===!1)throw new _("Browser not supported","0010",!0);const l=ND(t,{authToken:s,baseURL:i,cachedUserDetails:d});l.setRoomName(a),l.setRoomUUID(a),l.setOrganizationId(c),l.setHeader("dyte-tracing-id",r),t.setValue("apiClient",l);const h=new fO;t.setValue("connectionHandler",h);const m=Gs.createSocketService(t),y=m.connect(),T=l.getUserDetails(),b=l.getPlugins();let O=tt.HIVE,M,F="";try{yield Gs.setupFlagsmith(t)}catch(Z){p.error("Failed to setup flagsmith",{error:Z})}try{yield y}catch(Z){p.error("[Controller]: Failed to connect to socket server:",{error:Z})}try{({sfu:O,meetingTitle:F}=yield l.getRoomNodeData()),M=yield T,p.info(`SFU ${O} is being used.`),t.setValue("presetName",M.preset.name),t.setValue("roomNodeOptions",{sfu:O})}catch(Z){p.error("Failed to get room metadata",{error:Z})}const V=eN.init(M.preset,!t.getValue("modules").theme),K=Gs.setupControllers(m,t,M,b,F,V);sO(V)&&((e=Gs.createRoomNodeClient(t,m).partialJoinRoom(M.participant.name,a,void 0))==null||e.catch(Z=>{p.error("[Controller]: Failed to queue partial media room promise:",{error:Z})})),S.location.country=(n=l.ipInfo)==null?void 0:n.country;const{controllers:I}=yield K;return rC(),new Gs(i,I)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:n,baseURI:r,overrides:i,meetingId:s,organizationId:a}=t.getAllValues(),c=tC(s),d=G(x({entity:Au.PEER,clientId:a,isAnonUser:!a,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:c,roomName:s},Ie.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const l=(e=i==null?void 0:i.whitelabelled_flags_endpoint)==null||e?Zi({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield X.identify(`${Au.PEER}_${n}`,JSON.parse(JSON.stringify(d)),!1,5e3,l,p),p.info("flagsmith::allFlags",{flags:JSON.stringify(X.getAllFlags())},!0)}catch(l){p.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,n,r,i,s){return u(this,null,function*(){var a,c,d;const l=e.getValue("modules"),{preset:h,participant:m}=n,y=e.getValue("defaults"),{sfu:T}=e.getValue("roomNodeOptions"),{viewType:b,mediaConstraints:{audio:O}}=s;e.setValue("viewType",b),e.setValue("defaults",x({mediaConfiguration:{audio:{enableHighBitrate:(a=O.enableHighBitrate)!=null?a:!1,enableStereo:(c=O.enableStereo)!=null?c:!1}}},y));const M=TN.init(e,b,h.permissions);e.setValue("maxPreferredStreams",Ie.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let F,V,K,I,Z,ae,we,ce;const De=new iL(t);Ne.socketService=t;const At=new ul(t),A=new tn(t),k=new oL(t),w=Ld.create(t,e),j=new cL(t),Pe=new rL(t),Qe=new ci(t),B=yield Vr.init(e,w,m,M,s),C=yield Yv.init(e,B.self,w,De,i);if(l.participant&&(ce=new rr(e,B.self,w,T)),(d=l.e2ee)!=null&&d.enabled&&l.e2ee.manager.init(p,P),l.chat&&(V=yield Zn.init(e,A,Qe,B.self,ce.participants)),l.internals&&(Z=yield mh.init()),l.livestream&&s.viewType===yt.Livestream&&X.hasFeature(ie.LIVESTREAM)&&(we=new my(B.self,Pe)),s.viewType!==yt.Chat){if(l.poll&&(F=yield qv.init(e,B.self,At)),l.recording&&(ae=new iy(e,B.self,w)),l.stage&&(K=new Qv(e,k,w,B.self,ce.participants)),l.plugin){if(!ce)throw new _("The plugin module cannot be initialized without the `participant` module","0102");const lr=yield r;I=yield _a.init(e,lr,j,A,V==null?void 0:V.chat,B.self,ce.participants,i)}if(l.pip){const lr=yield aC._init(e,B.self);e.setValue("pip",lr)}}const Xe={storesManager:new cN(e,j),pollController:F,selfController:B,metaController:C,chatController:V,stageController:K,pluginController:I,recordingController:ae,internalsController:Z,livestreamController:we,participantController:ce};return{theme:s,permissions:M,controllers:Xe}})}static createRoomNodeClient(t,e){const{peerId:n,roomNodeOptions:r}=t.getAllValues(),{sfu:i}=r;return tS(t,i,{socket:e,peerId:n})}static createSocketService(t){const{peerId:e,meetingId:n,authToken:r}=t.getAllValues(),i=["PING"];return new Fo(t,{peerId:e,meetingId:n,authToken:r,capabilities:i})}};let Bo=Gs;wl([S.trace("Controller.init")],Bo,"init",1),wl([S.trace("setupFlagsmith")],Bo,"setupFlagsmith",1),wl([S.trace("Controller.createRoomNodeClient")],Bo,"createRoomNodeClient",1),wl([S.trace("Controller.createSocketService")],Bo,"createSocketService",1);var AL=Object.defineProperty,DL=Object.getOwnPropertyDescriptor,OL=(t,e,n,r)=>{for(var i=r>1?void 0:r?DL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&AL(e,n,i),i},_l,Mp;class _S extends jt{constructor(e,n){super(),f(this,_l,void 0),g(this,"meetings",[]),g(this,"parentMeeting",null),f(this,Mp,void 0),v(this,Mp,e),v(this,_l,n.self)}get supportsConnectedMeetings(){return o(this,_l).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Ne.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
19
+ `}this.midTransceiverMap.set(a.mid,a);const d=l=>u(this,null,function*(){return p.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(l)}]`),yield this.pc.setRemoteDescription(l),a.mid});return p.debug(`send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(c,void 0,2)}]`),{offerSdp:c,callback:d,sender:a.sender,mid:a.mid}})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:n}=e;n.onmessage=r=>{this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}class Bd extends Nh{constructor(e){super(),g(this,"supportsSendEncodings",!1),this.supportsSendEncodings=e.supportsSendEncodings}static createFactory(e){return()=>new Bd(e)}get name(){return"Firefox60"}send(e){return u(this,arguments,function*({track:n,encodings:r,codecOptions:i,screenShare:s}){this._assertSendDirection();const a=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(n,x({direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream]},a));if(!this.supportsSendEncodings&&r){r.reverse();const h=c.sender.getParameters();h.encodings=r,yield c.sender.setParameters(h)}const d=(h,m)=>{var y;const T=Kr(h),b=T.media[T.media.length-1],O=b.rtp.filter(K=>m.some(I=>I.name===K.codec)),M=b.fmtp.filter(K=>O.some(I=>I.payload===K.payload)),F=(y=b.rtcpFb)==null?void 0:y.filter(K=>O.some(I=>I.payload===K.payload)),V=O.map(K=>K.payload);return T.media[T.media.length-1].rtp=O,T.media[T.media.length-1].fmtp=M,T.media[T.media.length-1].rtcpFb=F,T.media[T.media.length-1].payloads=V.join(" "),mc(T)},l=yield this.pc.createOffer();if(l.sdp=d(l.sdp,i),p.debug(`send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),yield this.pc.setLocalDescription(l),n==="audio"||n.kind==="audio"){const{enableDtx:h,enableStereo:m}=this,y=this.enableHighBitrate?m?128e3:64e3:m?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${m?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${y}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:h=>u(this,null,function*(){return p.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this.pc.setRemoteDescription(h),c.mid}),sender:c.sender,mid:c.mid}})}setMaxSpatialLayer(e,n){return u(this,null,function*(){this._assertSendDirection(),p.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${n}]`);const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");const i=r.sender.getParameters(),s=i.encodings.length-1-n;i.encodings.forEach((a,c)=>{c>=s?a.active=!0:a.active=!1}),yield r.sender.setParameters(i)})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:n}=e;n.onmessage=r=>u(this,null,function*(){const i=yield r.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(i)))})})}}class xh extends Nh{static createFactory(){return()=>new xh}get name(){return"Safari12"}send(e){return u(this,arguments,function*({track:n,encodings:r,codecOptions:i,screenShare:s}){this._assertSendDirection(),p.debug("Safari12::creating new transceiver");const a=this.pc.addTransceiver(n,{direction:"sendonly",streams:[s?this._sendScreenShareStream:this._sendWebStream],sendEncodings:r}),c=RTCRtpSender.getCapabilities(typeof n=="string"?n:n.kind);p.info(`Safari12::senders available params: ${JSON.stringify(c)}`);const d=[];i&&i.length>0&&i.forEach(h=>{var m;const y=c.codecs.find(T=>T.mimeType.includes(h.name));if(h.parameters){p.info(`Safari12::codecOption.parameters:, ${JSON.stringify(h.parameters)}`);const T=((m=y.sdpFmtpLine)==null?void 0:m.split(";"))||[];T.push(...h.parameters);const b=[...new Set(T).values()];y.sdpFmtpLine=b.join(";")}d.push(y)}),p.info(`Safari12::selected codecs: ${JSON.stringify(d)}`),a.setCodecPreferences(d);const l=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(l),n==="audio"||n.kind==="audio"){const{enableStereo:h,enableDtx:m}=this,y=this.enableHighBitrate?h?128e3:64e3:h?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${m?"usedtx=1;":""}${h?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${y}`)}return this.midTransceiverMap.set(a.mid,a),{offerSdp:l,callback:h=>u(this,null,function*(){return p.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),yield this.pc.setRemoteDescription(h),a.mid}),sender:a.sender,mid:a.mid}})}addCustomEventListeners(){this.pc.ondatachannel=e=>{const{channel:n}=e;n.onmessage=r=>u(this,null,function*(){const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",e.channel,i)})}}}function xN(t,e){return typeof t=="undefined"?e:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(t):JSON.parse(JSON.stringify(t))}var Wd,Ps,sr,ar,Dr,jd,Vh,Uh,Cy,Fh,Py;class VN extends io{constructor(e){var n;super(),f(this,ar),f(this,jd),f(this,Uh),f(this,Fh),g(this,"rtpReceiver"),g(this,"id"),g(this,"localId"),g(this,"producerId"),g(this,"producingTransportId"),g(this,"mimeType"),g(this,"track"),g(this,"peerId"),g(this,"appData"),g(this,"transceiver"),f(this,Wd,void 0),f(this,Ps,void 0),f(this,sr,void 0),this.id=e.id,this.localId=e.localId,v(this,Wd,e.handler),this.appData=e.appData,this.peerId=e.producingPeerId,this.producingTransportId=e.producingTransportId,v(this,sr,!1),this.producerId=e.producerId,this.track=e.track,v(this,Ps,(n=e.paused)!=null?n:!1),this.mimeType=e.mimeType,this.transceiver=e.transceiver,this.rtpReceiver=e.rtpReceiver,H(this,Uh,Cy).call(this)}get closed(){return o(this,sr)}get kind(){return this.track.kind}get paused(){return o(this,Ps)}close(e,n){o(this,sr)||(p.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,o(this,ar,Dr)),v(this,sr,!0),n&&(H(this,Fh,Py).call(this),this.transceiver.stop()),this.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(o(this,sr))throw new Ut("closed");return o(this,Wd).getReceiverStats(this.localId)})}pause(){if(p.debug("consumer::pause()",o(this,ar,Dr)),o(this,sr)){p.error("consumer::pause() | Consumer closed",o(this,ar,Dr));return}v(this,Ps,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(p.debug("consumer::resume()",o(this,ar,Dr)),o(this,sr)){p.error("Consumer::resume() | Consumer closed",o(this,ar,Dr));return}v(this,Ps,!1),this.track.enabled=!0,this.safeEmit("resume")}}Wd=new WeakMap,Ps=new WeakMap,sr=new WeakMap,ar=new WeakSet,Dr=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},jd=new WeakSet,Vh=function(){p.debug('Consumer::track "ended" event',o(this,ar,Dr)),this.safeEmit("trackended")},Uh=new WeakSet,Cy=function(){this.track.addEventListener("ended",H(this,jd,Vh).bind(this))},Fh=new WeakSet,Py=function(){try{this.track.removeEventListener("ended",H(this,jd,Vh)),this.track.stop()}catch(t){p.error("Consumer::destroyTrack()",G(x({},o(this,ar,Dr)),{error:t}))}};var Vn,so,ao,Rs,kn,gt,Ii,oo,sn,bn;class UN extends io{constructor(e){var n,r;super(),f(this,sn),g(this,"id"),g(this,"localId"),f(this,Vn,void 0),g(this,"kind"),g(this,"appData"),g(this,"rtpSender"),f(this,so,void 0),f(this,ao,void 0),f(this,Rs,void 0),f(this,kn,!1),f(this,gt,void 0),f(this,Ii,void 0),f(this,oo,void 0),this.id=e.id,this.localId=e.localId,v(this,gt,e.track),this.kind=(n=e.track)==null?void 0:n.kind,v(this,Ii,e.disableTrackOnPause?!((r=e.track)!=null&&r.enabled):!1),v(this,oo,void 0),v(this,so,e.stopTracks),v(this,ao,e.disableTrackOnPause),v(this,Rs,e.zeroRtpOnPause),this.appData=e.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),v(this,Vn,e.handler),this.rtpSender=e.rtpSender,this._handleTrack()}get closed(){return o(this,kn)}get track(){return o(this,gt)}get paused(){return o(this,Ii)}get maxSpatialLayer(){return o(this,oo)}close(e){return u(this,null,function*(){if(o(this,kn))return;if(p.debug(`Producer::close() ${e?`with reason ${e}`:""}`,o(this,sn,bn)),v(this,kn,!0),this._destroyTrack(),e===qd){this.safeEmit("close",{reason:e});return}const{offerSdp:n,callback:r}=yield o(this,Vn).stopSending(this.localId),{answer:i}=yield this.safeEmitAsPromise("close",{offer:n,reason:e});r(i)})}getStats(){return u(this,null,function*(){if(o(this,kn))throw new Ut("closed");return o(this,Vn).getSenderStats(this.localId)})}pause(){p.debug("Producer::pause()",o(this,sn,bn)),o(this,kn)&&p.error("Producer::pause() | Producer closed",o(this,sn,bn)),v(this,Ii,!0),o(this,gt)&&o(this,ao)&&(o(this,gt).enabled=!1),o(this,Rs)&&o(this,Vn).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(p.debug("Producer::resume()",o(this,sn,bn)),o(this,kn)){p.error("Producer::resume() | Producer closed",o(this,sn,bn));return}v(this,Ii,!1),o(this,gt)&&o(this,ao)&&(o(this,gt).enabled=!0),o(this,Rs)&&o(this,Vn).replaceTrack(this.localId,o(this,gt)),this.emit("resume")}replaceTrack(e){return u(this,arguments,function*({track:n}){if(p.debug(`Producer::replaceTrack() trackId: ${n==null?void 0:n.id}`,o(this,sn,bn)),o(this,kn)){if(n&&o(this,so))try{n.stop()}catch(r){p.error("Producer::replaceTrack",G(x({},o(this,sn,bn)),{error:r}))}throw new Ut("closed")}else if(n&&n.readyState==="ended")throw new Ut("track ended");if(n===o(this,gt)){p.debug(`replaceTrack() | same track, ignored trackId: ${n.id}`,o(this,sn,bn));return}(!o(this,Rs)||!o(this,Ii))&&(yield o(this,Vn).replaceTrack(this.localId,n)),this._destroyTrack(),v(this,gt,n),this._handleTrack()})}setMaxSpatialLayer(e){return u(this,null,function*(){if(o(this,kn))throw new Ut("closed");if(this.kind!=="video")throw new ro("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield o(this,Vn).setMaxSpatialLayer(this.localId,e),v(this,oo,e)})}setRtpEncodingParameters(e){return u(this,null,function*(){if(o(this,kn))throw new Ut("closed");if(typeof e!="object")throw new TypeError("invalid params");yield o(this,Vn).setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){p.debug(`Producer::track "ended" event trackId: ${this.track.id}`,o(this,sn,bn)),this.safeEmit("trackended",this.track.id)}_handleTrack(){o(this,gt)&&o(this,gt).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(o(this,gt))try{o(this,gt).removeEventListener("ended",this._onTrackEnded),o(this,so)&&o(this,gt).stop()}catch(n){p.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,G(x({},o(this,sn,bn)),{error:n}))}}}Vn=new WeakMap,so=new WeakMap,ao=new WeakMap,Rs=new WeakMap,kn=new WeakMap,gt=new WeakMap,Ii=new WeakMap,oo=new WeakMap,sn=new WeakSet,bn=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function Ry(t){return typeof t=="object"&&!Array.isArray(t)&&t!==null}function Bh(t){return Math.random().toString(36).substring(2,2+t)}const Hd=1;function My(t){const e=t;return delete e.payload._bolt,e}function FN(t){return t.payload&&Ry(t.payload)}function Ay(t){var e,n;return FN(t)&&(n=(e=t.payload._bolt)==null?void 0:e.id)!=null?n:""}var Ci;const co=class extends ut.EventEmitter{constructor(t,e,n){super(),g(this,"channel"),g(this,"queue"),g(this,"serverProtocolVersion"),f(this,Ci,new Map),g(this,"respond",(r,i,s=!1)=>{let a;s?a=co.createErrorResponse(r,i):a=co.createResponse(r,i),this.channel.send(JSON.stringify(a))}),g(this,"notify",r=>{const i=co.createNotification(r);this.channel.send(JSON.stringify(i))}),g(this,"request",r=>u(this,null,function*(){const i=co.createRequest(r),s=new Promise((a,c)=>{const{id:d}=i.payload._bolt,l={id:d,method:i.type,resolve:h=>{this.queue.delete(d)&&(clearTimeout(l.timer),a(h))},timer:setTimeout(()=>{this.queue.delete(d)&&c(new Error(`request timeout for message id: ${d}`))},2e4),cancel:h=>{this.queue.delete(d)&&(clearTimeout(l.timer),c(h))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(i)),s})),g(this,"send",r=>{const i=JSON.stringify(r),s=16384;if(i.length>s){const a=s-200,c=Math.ceil(i.length/a),d=[];for(let h=0;h<c;h+=1){const m=h*a,y=(h+1)*a;d.push(i.slice(m,y))}const l=Gi();for(let h=0;h<c;h+=1){const m=d[h],y=JSON.stringify({id:l,count:c,chunkIndex:h,chunk:m});p.debug(`Sending message chunk over dc: ${y}`),this.channel.send(y)}}else p.debug(`Sending message over dc: ${i}`),this.channel.send(i)}),g(this,"processMessage",r=>{var i;o(this,Ci).has(r.id)||o(this,Ci).set(r.id,[]);const s=o(this,Ci).get(r.id);if(s[r.chunkIndex]=r,(s==null?void 0:s.length)===r.count&&!s.some(a=>a===void 0)){const a=o(this,Ci).get(r.id),c=a==null?void 0:a.reduce((l,h)=>l+h.chunk,"");o(this,Ci).delete(r.id);const d=JSON.parse(c);if(!d.payload||!Ry(d.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:d}});if(this.processBoltHandshake(d))return;if(this.serverProtocolVersion=(i=d.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(d))return d}}),g(this,"processResponseMsg",r=>{const{id:i}=r.payload._bolt,s=this.queue.get(i);return s?(p.debug(`resolving pending request with id: ${i}, complete response: ${JSON.stringify(r)}`),r.type==="error"?s.cancel(My(r)):s.resolve(My(r)),!0):!1}),g(this,"processBoltHandshake",r=>{var i,s;return r.type==="_bolt"||r.type==="handshake"?(this.respond((s=(i=r.payload._bolt)==null?void 0:i.id)!=null?s:Bh(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1}),this.label=e,this.transportId=n,this.channel=t,this.queue=new Map}};let lo=co;Ci=new WeakMap,g(lo,"createRequest",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:G(x({},t.payload),{_bolt:{id:Bh(8),type:"REQUEST",version:Hd}})}}),g(lo,"createResponse",(t,e)=>{var n;if((n=e.payload)!=null&&n._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:G(x({},e.payload),{_bolt:{id:t,type:"RESPONSE",version:Hd}})}}),g(lo,"createNotification",t=>{var e;if((e=t.payload)!=null&&e._bolt)throw new Error("rpc fields are internal values");return{type:t.type,payload:G(x({},t.payload),{bolt:{id:Bh(8),type:"NOTIFY",version:Hd}})}}),g(lo,"createErrorResponse",(t,e)=>({type:"error",payload:{error:e.message,_bolt:{id:t,type:"RESPONSE",version:Hd}}}));function BN(t){if(Promise.allSettled)return Promise.allSettled(t);const e=t.map(n=>n.then(r=>({status:"fulfilled",value:r})).catch(r=>({status:"rejected",reason:r})));return Promise.all(e)}const qd="transport closed";var uo;const ho=class extends io{constructor(t,{id:e,direction:n,handlerFactory:r,iceServers:i,iceTransportPolicy:s,proprietaryConstraints:a,additionalSettings:c,appData:d,config:l}){var h,m,y;super(),g(this,"awaitQueue"),g(this,"observer"),f(this,uo,void 0),g(this,"id"),g(this,"serverId"),g(this,"direction"),g(this,"maxSctpMessageSize"),g(this,"handler"),g(this,"connectionState","new"),g(this,"producers"),g(this,"consumers"),g(this,"datachannels"),g(this,"connected",!1),g(this,"eventsDCReadyPromise"),g(this,"eventsDCReadyPromiseResolver"),g(this,"eventsDCFailureTimer"),g(this,"transportConnectionPromise"),g(this,"consumerTrackEvents"),g(this,"unknownTracksMap"),g(this,"appData"),p.debug(`constructor() [id: ${e}, direction: ${n}]`),v(this,uo,t),this.id=e,this.direction=n;const T=xN(c,{});delete T.iceServers,delete T.iceTransportPolicy,delete T.bundlePolicy,delete T.rtcpMuxPolicy,delete T.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Vd,this.observer=new io,this.handler=r(),this.handler.enableHighBitrate=(h=l==null?void 0:l.enableHighBitrate)!=null?h:!1,this.handler.enableStereo=(m=l==null?void 0:l.enableStereo)!=null?m:!1,this.handler.enableDtx=(y=l==null?void 0:l.enableDtx)!=null?y:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:n,iceServers:i,iceTransportPolicy:s,additionalSettings:c,proprietaryConstraints:a}),this.appData=d||{},this.transportConnectionPromise=new Promise(b=>{this.observer.once("connected",()=>{b(!0)}),this.observer.once("disconnect",()=>{b(!1)}),this.observer.once("close",()=>{b(!1)})}),this.eventsDCReadyPromise=new Promise(b=>{this.eventsDCReadyPromiseResolver=b}),this.handler.on("@connectionstatechange",b=>{b!==this.connectionState&&(p.debug(`connection state changed to ${b}`),this.connectionState=b,b==="connected"&&(this.connected=!0,this.observer.emit("connected")),b==="disconnected"&&(this.connected=!1,this.observer.emit("disconnect")),(b==="failed"||b==="closed")&&(this.connected=!1,this.observer.emit("close")),this.closed||this.safeEmit("connectionstatechange",b))}),this.handler.on("@icecandidate",({candidate:b})=>{this.closed||this.safeEmit("icecandidate",b)}),this.handler.on("dc_open",b=>{let O=this.datachannels.get(b.label);O||(O||(O=new lo(b,b.label,this.serverId),this.datachannels.set(b.label,O)),this.eventsDCFailureTimer=setTimeout(()=>{b.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",b.label))},5e3))}),this.handler.on("datachannel",(b,O)=>{b.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const M=this.datachannels.get(b.label);if(!M){p.error("unregistered datachannel for message",{rtcChannel:{label:b.label,message:O}});return}try{const F=JSON.parse(O);p.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:F.id,count:F.count,chunkIndex:F.chunkIndex,chunk:F.chunk,transprtId:this.serverId}});const V=M.processMessage(F);if(!V)return;p.debug(`datachannel message with id:${F.id} on transport:${this.serverId}complete - ${JSON.stringify(V)}`),this.emit(`datachannel:${b.label}`,M.label,V)}catch(F){p.error("error parsing message",{error:F})}})}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||(p.debug("Transport close called"),this.connectionState="closed",this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(t=>{t.close(qd).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(t=>{t.close(qd)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"),this.observer.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:n}=yield this.handler.connect(),{transportId:r,answer:i}=yield t(e);this.setServerId(r),yield n(i)})),!(yield this.transportConnectionPromise))throw new Error("ice connection failed");if(o(this,uo)===tt.HIVE&&!(yield this.isEventsDCReady))throw new Error("events datachannel not open")}catch(e){throw p.error("transport failed to connect:",{error:e}),e}})}restartIce(){return u(this,null,function*(){if(p.debug("restartIce()"),this.closed)throw new Ut("closed");return this.handler.restartIce()})}canProduce(t){return u(this,null,function*(){const{track:e,appData:n}=t;if(e){if(this.direction!=="send")throw new ro("not a sending Transport");if(e.readyState==="ended")throw new Ut("track ended");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(n&&typeof n!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.transportConnectionPromise))throw new _i("transport not connected");return!0})}produce(t,e){return u(this,null,function*(){if(!(yield this.canProduce(t)))throw new Error("Cannot produce");const{track:n,encodings:r,codecOptions:i,stopTracks:s=!0,disableTrackOnPause:a=!0,zeroRtpOnPause:c=!1,appData:d={}}=t;p.debug(`produce() [track:${n.id}]`);const{producerId:l,localId:h,rtpSender:m}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:y,callback:T,sender:b,mid:O}=yield this.handler.send({track:n,encodings:r,codecOptions:i,screenShare:d==null?void 0:d.screenShare}),{answer:M,producerId:F}=yield e({offer:y,kind:n.kind,paused:a?!n.enabled:!1,appData:G(x({},d||{}),{mid:O}),codecOptions:i,producingTransportId:this.serverId}),V=yield T(M);return{producerId:F,localId:V,rtpSender:b}}),"producer");return this.createProducerObject({id:l,localId:h,track:n,stopTracks:s,disableTrackOnPause:a,zeroRtpOnPause:c,appData:d,handler:this.handler,rtpSender:m})})}createProducerObject(t){return u(this,null,function*(){const e=new UN(t);return this.producers.set(e.id,e),e.once("close",()=>{this.producers.delete(e.id)}),e})}closeProducer(t){return u(this,null,function*(){yield this.awaitQueue.push(t.close.bind(t),"producer")})}canConsume(){return u(this,null,function*(){if(this.closed)throw new Ut("closed");if(this.direction!=="recv")throw new ro("not a receiving transport");if(this.listenerCount("connect")===0&&this.connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(!(yield this.transportConnectionPromise))throw new _i("transport not connected");return!0})}consume(t,e,n){return u(this,null,function*(){return this.awaitQueue.push(()=>u(this,null,function*(){const r={},{consumerStates:i,sessionDescription:s,failedProducers:a}=yield e(t);i.forEach((l,h)=>{r[h]=this.createConsumerObjectAndWaitForTrack(G(x({},l),{producerId:h}))});const c=a;s&&(p.info("Session description found, sending negotiation request"),yield n(s));const d=[];return yield Promise.all(Object.entries(r).map(([l,h])=>h.then(m=>d.push(m)).catch(()=>{p.error(`Failed to create consumer object, producer: ${l}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:d,failedProducers:c}}),"consumer")})}static parseHeaderExtensionMappings(t,e){const n=Kr(t.sdp),r={};return n.media.forEach(i=>{e.includes(i.mid.toString())&&(r[i.mid]=i.ext)}),r}static setHeaderExtensionMappings(t,e,n){const r=Kr(t.sdp);return r.media=r.media.map(i=>{if(e.includes(i.mid.toString())){const s=x({},i);return s.ext=n[i.mid],s}return i}),G(x({},t),{sdp:mc(r)})}static parseCodecAndFmtpMappings(t,e){const n=Kr(t.sdp),r={};return n.media.forEach(i=>{e.includes(i.mid.toString())&&(r[i.mid.toString()]={rtp:i.rtp,fmtp:i.fmtp,payloads:i.payloads,rtcpFb:i.rtcpFb})}),r}static setCodecAndFmtpMappings(t,e,n){const r=Kr(t.sdp);return r.media=r.media.map(i=>{if(e.includes(i.mid.toString())){const s=x({},i);return s.rtp=n[i.mid.toString()].rtp,s.fmtp=n[i.mid.toString()].fmtp,s.payloads=n[i.mid.toString()].payloads,s.rtcpFb=n[i.mid.toString()].rtcpFb,s}return i}),G(x({},t),{sdp:mc(r)})}closeConsumers(t,e){return u(this,null,function*(){const n=t.map(c=>c.transceiver.mid),r=ho.parseHeaderExtensionMappings(this.handler.pc.remoteDescription,n),i=ho.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,n);t.forEach(c=>c.close(void 0,!0));let s=yield this.handler.pc.createOffer();s=ho.setHeaderExtensionMappings(s,n,r),s=ho.setCodecAndFmtpMappings(s,n,i),yield this.setLocalDescription(s);const a=yield e(t,s);yield this.setRemoteDescription(a)})}setRemoteOffer(t){return u(this,null,function*(){yield this.setRemoteDescription(t);const e=yield this.handler.pc.createAnswer(),n=Kr(e.sdp);return n.media=n.media.map(r=>{if(r.type==="audio"){const i=x({},r),s=i.fmtp.find(a=>a.payload===111);return s&&(s.config+=";stereo=1;sprop-stereo=1"),i.rtcpFb||(i.rtcpFb=[]),i.rtcpFb.some(a=>a.type==="nack")||i.rtcpFb.push({payload:parseInt(i.payloads,10),type:"nack"}),i}return r}),e.sdp=mc(n),yield this.setLocalDescription(e),e})}_ontrack(t){const{track:e,transceiver:n,streams:r}=t;p.info(`track event received [trackId: ${e.id}]`);let i;o(this,uo)===tt.HIVE?i=`${r[0].id}:${e.kind}`:i=`${n.mid}:${e.kind}`,e.addEventListener("ended",()=>{p.info(`rtc consumer track ended [trackId: ${e.id}]`),this.unknownTracksMap.delete(i)});const s=this.consumerTrackEvents.get(i);s?(s(e,n),this.consumerTrackEvents.delete(i)):(p.warn(`track event handler not found ${i}`),this.unknownTracksMap.set(i,t))}sendErrorOverDC(t,e,n){const r=this.getDatachannel(t);if(!r)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});r.respond(e,n,!0)}sendResponseOverDC(t,e,n){const r=this.getDatachannel(t);if(!r)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:t}}});r.respond(e,n)}createConsumerObjectAndWaitForTrack(t){return u(this,null,function*(){const{consumerId:e,producerId:n,producingPeerId:r,producingTransportId:i,streamId:s,paused:a,screenShare:c,appData:d,kind:l,mimeType:h}=t,m=`${s}:${l}`,y=G(x({},t),{name:"consumer creation task error",message:"consumer creation failed"});return new Promise((T,b)=>u(this,null,function*(){const O=setTimeout(()=>{this.consumerTrackEvents.delete(m),y.isTimedout=!0,b(y)},5e3),M=(V,K)=>{try{if(V.readyState==="ended")clearTimeout(O),b(y);else{const I=V;I.enabled=!0,this.handler.midTransceiverMap.set(K.mid,K);const Z=new VN({id:e,localId:K.mid,transceiver:K,track:I,paused:a,producerId:n,producingPeerId:r,producingTransportId:i,handler:this.handler,appData:G(x({},d),{screenShare:c,peerId:r}),rtpReceiver:K.receiver,mimeType:h});this.consumers.set(e,Z),Z.once("close",()=>{this.consumers.delete(Z.id),this.handler.midTransceiverMap.delete(K.mid)}),p.info("consumer created for ",{consumer:{id:e,kind:l,appData:{screenShare:c},peerId:r,producerId:n}}),this.observer.emit("newconsumer",Z),clearTimeout(O),T(Z)}}catch(I){p.warn("error while creating consumer:",I),clearTimeout(O),b(y)}},F=this.unknownTracksMap.get(m);F?(this.unknownTracksMap.delete(m),M(F.track,F.transceiver)):this.consumerTrackEvents.set(m,M)}))})}setRemoteDescription(t){return u(this,null,function*(){yield this.handler.pc.setRemoteDescription(t)})}setLocalDescription(t){return u(this,null,function*(){p.debug(`${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(t)}]`),yield this.handler.pc.setLocalDescription(t)})}retryFailedConsumerCreationTasks(t){return u(this,null,function*(){return BN(t.map(e=>u(this,null,function*(){return Oh(n=>u(this,null,function*(){return n>0&&p.warn(`retrying failed consumer creation task: ${JSON.stringify(e)}`),this.createConsumerObjectAndWaitForTrack(x({},e))}))})))})}sendDataChannelMessage(t,e){return u(this,null,function*(){const n=this.getDatachannel(t);if(!n)throw AN("DC_NOT_READY",`${t} datachannel not ready`);const r=(yield n.request(e)).payload;return p.info(`sendDataChannelMessage::response ${JSON.stringify(r)}`),r})}};let WN=ho;uo=new WeakMap;function jN(){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){p.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return p.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=Up.getParser(t),n=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(n.name&&n.name.toLowerCase()==="blink"){const r=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return r?Number(r[1])>=74?"Chrome74":void 0:"Chrome74"}if(n.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;p.warn("Device::this._detectDevice() | browser not supported");return}p.warn("Device::this._detectDevice() | unknown device")}var Gd;class HN{constructor(e,{handlerName:n,handlerFactory:r}={}){if(g(this,"handlerFactory"),f(this,Gd,void 0),p.debug("constructor()"),v(this,Gd,e),n&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(n)p.debug(`Device::constructor() | handler given: ${n}`);else if(n=jN(),n)p.debug(`Device::constructor() | detected handler: ${n}`);else throw new Error("device not supported");switch(n){case"Chrome74":this.handlerFactory=Lh.createFactory();break;case"Safari12":this.handlerFactory=xh.createFactory();break;case"Firefox60":this.handlerFactory=Bd.createFactory({supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Bd.createFactory({supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${n}"`)}}}createTransport(e){const n=Gi();return new WN(o(this,Gd),G(x({id:n},e),{handlerFactory:this.handlerFactory}))}}Gd=new WeakMap;const qN=2e3;var Or,po,It,Ct,Ms,mo,go,fo,As,Pi,vo,yo,Jd,$d,Wh,jh,Dy,Hh,Oy,qh,Ny,Gh,Ly,Jh,xy,Kd,$h,zd,Kh;class GN extends ut.EventEmitter{constructor(e,n,r){switch(super(),f(this,yo),f(this,$d),f(this,jh),f(this,Hh),f(this,qh),f(this,Gh),f(this,Jh),f(this,Kd),f(this,zd),f(this,Or,void 0),f(this,po,void 0),f(this,It,void 0),f(this,Ct,void 0),f(this,Ms,void 0),f(this,mo,void 0),f(this,go,void 0),f(this,fo,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0}),f(this,As,void 0),f(this,Pi,"all"),f(this,vo,void 0),v(this,Or,e),v(this,Ms,n),v(this,vo,r),v(this,po,new HN(r)),v(this,mo,new LN(n,r)),r){case tt.CF:{v(this,go,pn);break}case tt.HIVE:default:{v(this,go,en);break}}o(this,yo,Jd).mediaState={send:{state:Rr.NEW,reconnected:!1},recv:{state:Rr.NEW,reconnected:!1}},X.hasFeature(ie.FORCE_RELAY)&&v(this,Pi,"relay"),H(this,$d,Wh).call(this)}get socket(){return o(this,Ms)}get socketHandler(){return o(this,mo)}get sendTransport(){return o(this,It)}get recvTransport(){return o(this,Ct)}get events(){return o(this,go)}get nodeType(){return o(this,vo)}createTransports(e){return u(this,null,function*(){var n,r,i,s,a,c,d,l;X.hasFeature(ie.FORCE_RELAY)&&(p.info("ICE Transport Policy set to relay"),v(this,Pi,"relay"));const h=yield ot().getICEServers().catch(y=>(p.warn(`failed to get iceservers from server: ${y.message}`),[])),m=[];if(e.send){const y=X.hasFeature(ie.DISABLE_OPUS_DTX_CF),T=H(this,Hh,Oy).call(this,{iceServers:h,additionalSettings:{encodedInsertableStreams:(n=o(this,Or).getValue("modules").e2ee)==null?void 0:n.enabled},config:{enableHighBitrate:(s=(i=(r=o(this,Or).getValue("defaults").mediaConfiguration)==null?void 0:r.audio)==null?void 0:i.enableHighBitrate)!=null?s:!1,enableStereo:(d=(c=(a=o(this,Or).getValue("defaults").mediaConfiguration)==null?void 0:a.audio)==null?void 0:c.enableStereo)!=null?d:!1,enableDtx:o(this,vo)===tt.HIVE?!0:!!y},iceTransportPolicy:o(this,Pi)});m.push(T)}if(e.recv){const y=H(this,qh,Ny).call(this,{iceServers:h,additionalSettings:{encodedInsertableStreams:(l=o(this,Or).getValue("modules").e2ee)==null?void 0:l.enabled},iceTransportPolicy:o(this,Pi)});m.push(y)}yield Promise.all(m)})}stopTransports(e){var n,r;if(e.send&&this.sendTransport!==void 0){const{id:i,serverId:s,direction:a}=o(this,It);p.info("Closing send transport",{transport:{id:i,serverId:s,type:a}}),o(this,It).close(),o(this,It).removeAllListeners(),v(this,It,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:i,serverId:s,direction:a}=o(this,Ct);p.info("Closing recv transport",{transport:{id:i,serverId:s,type:a}}),(n=o(this,Ct))==null||n.close(),(r=o(this,Ct))==null||r.removeAllListeners(),v(this,Ct,void 0)}H(this,$d,Wh).call(this)}stopAllTransports(){p.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}connectTransportWithRetry(e){return u(this,null,function*(){const{id:n,serverId:r,direction:i}=e;H(this,Gh,Ly).call(this,e);try{const s=X.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3;return yield Oh((a,c)=>u(this,null,function*(){a>0&&p.debug(`Retrying transport connect, count: ${a}`,{transport:{id:n,serverId:r,type:i}});try{if(e.closed)throw new _i("Cannot reconnect closed transport");yield H(this,jh,Dy).call(this,e)}catch(d){if(d instanceof _i){c(d);return}throw p.error("Failed to connect transport, retrying",{transport:e,error:d}),d}}),{delayTime:100,strategy:"exponential",maxRetryCount:s}),e}catch(s){throw p.error(`Failed to connect send transport after retry: ${e.id}`,{error:s,transport:{id:n,serverId:r,type:i}}),e.close(),e.removeAllListeners(),s}})}handleErrors(e){throw new Error("Method not implemented.")}}Or=new WeakMap,po=new WeakMap,It=new WeakMap,Ct=new WeakMap,Ms=new WeakMap,mo=new WeakMap,go=new WeakMap,fo=new WeakMap,As=new WeakMap,Pi=new WeakMap,vo=new WeakMap,yo=new WeakSet,Jd=function(){return o(this,Or).getValue("connectionHandler")},$d=new WeakSet,Wh=function(){v(this,As,{send:void 0,recv:void 0})},jh=new WeakSet,Dy=function(t){return u(this,null,function*(){const{id:e,direction:n}=t;if(p.info(`Connecting ${n} transport`,{transport:{id:e,type:n}}),!o(this,Ms).isConnected)throw new _i("Socket is not connected");if(t.connectionState==="closed")throw new _i("Transport is closed");try{yield t.connect(r=>H(this,Jh,xy).call(this,n,r)),p.info(`Connected ${n} transport`,{transport:{id:e,serverId:t.serverId,type:n}})}catch(r){throw o(this,fo).transportFailureCount[n]+=1,r.message==="ice connection failed"?new _i(r.message):r}})},Hh=new WeakSet,Oy=function(t){return u(this,null,function*(){var e,n;if(o(this,It)&&o(this,It).connected){p.info("Transport send is already connected",{transport:{id:(e=o(this,It))==null?void 0:e.id,serverId:(n=o(this,It))==null?void 0:n.serverId,type:"send"}});return}v(this,It,o(this,po).createTransport(G(x({},t),{direction:"send"}))),J.configureSendTransport(o(this,It))})},qh=new WeakSet,Ny=function(t){return u(this,null,function*(){var e,n;if(o(this,Ct)&&o(this,Ct).connected){p.info("Transport recv is already connected",{transport:{id:(e=o(this,Ct))==null?void 0:e.id,serverId:(n=o(this,Ct))==null?void 0:n.serverId,type:"recv"}});return}v(this,Ct,o(this,po).createTransport(G(x({},t),{direction:"recv"}))),J.configureRecvTransport(o(this,Ct))})},Gh=new WeakSet,Ly=function(t){const{direction:e,id:n}=t;t.on("connectionstatechange",r=>u(this,null,function*(){H(this,zd,Kh).call(this,{state:r,direction:e}),p.info(`Transport connection state changed for ${e} transport`,{transport:{id:n,serverId:t.serverId,type:e,status:r}});const i=()=>{const s=o(this,As)[e];s!==void 0&&(clearTimeout(s),o(this,As)[e]=void 0)};switch(r){case"connected":i(),o(this,fo).lastConnectionTime=performance.now();break;case"disconnected":o(this,As)[e]=setTimeout(()=>u(this,null,function*(){yield H(this,Kd,$h).call(this,t)}),qN);break;case"failed":if(t.closed)return;i(),yield H(this,Kd,$h).call(this,t);break}})),t.on("icecandidate",r=>u(this,null,function*(){p.debug("Sending iceCandidate:",{iceCandidate:r})})),t.on("datachannel:events",(r,i)=>u(this,null,function*(){var s,a;p.debug("Got data channel message on event:",{rtcChannel:{label:r,message:i}});try{switch(i.type){case"handshake":{const c={type:"handshake",payload:{message:"pong"}};t.sendResponseOverDC(r,Ay(i),c);break}case"hub-disconnect":{p.debug(`media hub disconnected, full_reconnect: ${(s=i.payload)==null?void 0:s.full_reconnect}`),((a=i.payload)==null?void 0:a.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(c){p.error(`Unable to handle the incoming datachannel message on channel ${r}`)}})),t.on("dc_error",()=>{t.direction==="recv"&&(p.warn("Events datachannel did not open in 5s",{country:S.location.country}),this.handleErrors("reconnectRecvTransport"))})},Jh=new WeakSet,xy=function(t,e){return u(this,null,function*(){const n=t==="recv";try{const{sdp:r,type:i}=e,s={consuming:n,description:{sdp:r,type:i,target:n?zn.SUBSCRIBER:zn.PUBLISHER},producers:[]};return o(this,mo).connectTransport(s)}catch(r){throw p.error(`Error in ${t} transport connection:`,{error:r,country:S.location.country}),r}})},Kd=new WeakSet,$h=function(t){return u(this,null,function*(){p.info("Called reconnect transport",{transport:t}),t.close(),t.removeAllListeners();const{direction:e}=t;switch(X.hasFeature(ie.HIVE_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED)&&o(this,Ms).isConnected&&o(this,fo).transportFailureCount[e]>2&&(p.warn(`Multiple disconnections in ${e} transport, forcing relay`),v(this,Pi,"relay")),yield this.createTransports({[e]:!0}),e){case"send":{yield this.connectTransportWithRetry(o(this,It)),p.info("Transport reconnected",{transport:o(this,It)}),P.emit(R.RESET_PRODUCER_STATE);break}case"recv":{yield this.connectTransportWithRetry(o(this,Ct)),p.info("Transport reconnected",{transport:o(this,Ct)}),P.emit(R.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:p.warn("Unknown transport direction",{transport:t})}H(this,zd,Kh).call(this,{state:Rr.CONNECTED,direction:e})})},zd=new WeakSet,Kh=function(t){const{state:e,direction:n}=t;o(this,yo,Jd).mediaState[n]={state:e,reconnected:!0},P.emit(R.TRANSPORT_STATE_UPDATE,x({transport:n},o(this,yo,Jd).mediaState[n]))};var zh,Vy;class JN{constructor(e){f(this,zh),this.recvTransport=e,H(this,zh,Vy).call(this)}create(e){return u(this,null,function*(){if(!e||e&&e.length===0)throw new Error("List of producers is required");const n={type:"create_consumer",payload:{producers:e.map(({producerId:a,producingTransportId:c,kind:d,mimeType:l})=>({producerId:a,producingTransportId:c,preferredCodec:x(x({},d==="video"&&l?{video:l}:{}),d==="audio"&&l?{audio:l}:{})}))}},r=yield this.recvTransport.sendDataChannelMessage("events",n),i=new Map;e.forEach(a=>i.set(a.producerId,a));const s=new Map;return Object.entries(r).forEach(([a,c])=>{const d=i.get(c.producerId);d&&s.set(c.producerId,{consumerId:a,producingTransportId:d.producingTransportId,producingPeerId:d.producingPeerId,kind:d.kind,paused:d.pause,streamId:c.streamId,trackId:c.trackId,screenShare:d.screenShare,mimeType:d.mimeType,appData:{}})}),{consumerStates:s}})}negotiate(e,n,r){return u(this,null,function*(){try{p.debug(`Received offer over dc: ${e.sdp} for transport`);const i=yield this.recvTransport.setRemoteOffer(e),s={type:"answer",payload:{type:i.type,sdp:i.sdp}};return p.debug(`datachannel answer: ${JSON.stringify(s)}`),this.recvTransport.sendResponseOverDC(r,n,s),i}catch(i){throw p.error("datachannel:events::Error:",i),i.code!=="DC_NOT_FOUND"&&this.recvTransport.sendErrorOverDC(r,n,i),i}})}close(e){return u(this,null,function*(){if(!e.length)return{};const n=e.map(a=>a.id);p.info(`Closing consumers: ${JSON.stringify(n)}`);const r={type:"close_consumers",payload:{consumers:n}},i=yield this.recvTransport.sendDataChannelMessage("events",r),{failedConsumers:s}=i;return{failedConsumers:s}})}}zh=new WeakSet,Vy=function(){this.recvTransport.on("datachannel:events",(t,e)=>u(this,null,function*(){try{switch(e.type){case"negotiation":{const{sdp:n}=e.payload,r={sdp:n,type:"offer"};this.negotiate(r,Ay(e),t);break}default:break}}catch(n){p.error(`Unable to handle the incoming datachannel message on channel ${t}`)}}))};class $N{constructor(e,n,r,i){this.events=e,this.recvTransport=n,this.socket=r,this.socketHandler=i}create(e){return u(this,null,function*(){if(!e||e&&e.length===0)throw new Error("List of producers is required");const n=new Map,r=[];e.forEach(d=>{const{producingPeerId:l,producerId:h,producingTransportId:m}=d;n.set(h,l),r.push({producingPeerId:l,producerId:h,producingTransportId:m})});const i=yield this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),s=new Map;e.forEach(d=>s.set(d.producerId,d));const a=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const h=s.get(d);if(!h)return;if(l.errorCode){if(p.warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),l.errorCode==="not_found_track_error"){p.error(`Track not found for producer: ${h.producerId}. This will not be retried.`);return}c.push(h);return}let m={};try{m=JSON.parse(l.producerState.appData)}catch(y){}a.set(d,{consumerId:l.consumerId,producingTransportId:h.producingTransportId,producingPeerId:h.producingPeerId,kind:h.kind,paused:h.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:h.screenShare,mimeType:h.mimeType,appData:m})}),{consumerStates:a,sessionDescription:i.sessionDescription,failedProducers:c}})}negotiate(e){return u(this,null,function*(){p.info("Negotiating socket consumer",{transport:this.recvTransport}),p.debug(`setting remote offer: ${JSON.stringify(e)} on recvTransport`,{transport:this.recvTransport});const n=yield this.recvTransport.setRemoteOffer(e),r={transportId:this.recvTransport.serverId,description:{sdp:n.sdp,type:n.type,target:zn.SUBSCRIBER}};return p.debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),yield this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,EC.toBinary(r)),p.info("Renegotiation done",{transport:this.recvTransport}),n})}close(e){return u(this,null,function*(){if(!e.length)return{};const n=(r,i)=>u(this,null,function*(){const s=r.map(l=>l.localId);p.info(`Closing consumers: ${JSON.stringify(s)}`);const a={description:{sdp:i.sdp,type:i.type,target:zn.SUBSCRIBER},consumerIds:s,consumingTransportId:this.recvTransport.serverId},c=yield this.socketHandler.closeConsumer(a),d=HP.fromBinary(c).description;return{sdp:d.sdp,type:d.type}});return this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(e,n),"close_consumer"),{}})}}class Yh{constructor(e){this.socketHandler=e}static getMSIDFromSDP(e,n){return Kr(e).media.filter(r=>n==="video"?r.type==="video":r.type==="audio").at(-1).msid}create(e){return u(this,arguments,function*({offer:n,kind:r,paused:i,appData:s,codecOptions:a,producingTransportId:c}){var d,l;const h=Yh.getMSIDFromSDP(n.sdp,r),m={description:{sdp:n.sdp,type:n.type,target:zn.PUBLISHER},paused:i,kind:r,msid:h,appData:JSON.stringify(s),screenShare:(d=s.screenShare)!=null?d:!1,mimeType:`${r}/${(l=a[0])==null?void 0:l.name}`,producingTransportId:c},{answer:y,producerId:T}=yield this.socketHandler.produce(m);return{answer:y,producerId:T}})}}var So,Ds,Ri,Eo,Yd,or,Qh,Nr,To,Xh,Uy,Qd,Zh,ep,Fy,tp,By,np,Wy,rp,jy,ip,Hy,sp,qy;class KN extends GN{constructor(e,n,r){super(e,n,r),f(this,Xh),f(this,Qd),f(this,ep),f(this,tp),f(this,np),f(this,rp),f(this,ip),f(this,sp),f(this,So,void 0),f(this,Ds,void 0),f(this,Ri,void 0),f(this,Eo,void 0),f(this,Yd,void 0),f(this,or,void 0),f(this,Qh,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0}),f(this,Nr,[]),f(this,To,void 0),v(this,So,e),o(this,Xh,Uy).mediaState={send:{state:Rr.NEW,reconnected:!1},recv:{state:Rr.NEW,reconnected:!1}},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return o(this,Ds)}get consumers(){return o(this,Ri)}get producerIdToConsumerIdMap(){return o(this,Eo)}reset(){v(this,Ds,new Map),v(this,Ri,new Map),v(this,Eo,new Map)}setupTransports(e){return u(this,null,function*(){yield this.createTransports(e);let n,r;e.send&&(n=H(this,ep,Fy).call(this)),e.recv&&(r=H(this,tp,By).call(this)),yield Promise.all([n,r])})}createProducer(e,n){return u(this,null,function*(){var r;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const i=yield this.sendTransport.produce(e,H(this,np,Wy).bind(this));return(r=e.appData)!=null&&r.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,i),H(this,rp,jy).call(this,i,n),i}catch(i){throw p.error("Failed to create producer",{error:i}),o(this,Qh).producerCreationFailureCount+=1,i}})}closeProducer(e,n){return u(this,null,function*(){var r;const i=this.producers.get(e);if(!i){p.warn(`Producer with ID ${e} was not found`);return}n!=null&&n.stopTrack&&i.track.stop();try{yield this.sendTransport.closeProducer(i),(r=o(this,So).getValue("modules").e2ee)!=null&&r.enabled&&P.emit(R.E2EE_INACTIVE_PRODUCER,i)}catch(s){p.error("Failed to close producer on server",{error:s,producer:i})}})}closeAllProducers(){return Promise.all(Array.from(o(this,Ds).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}createConsumers(e){return u(this,null,function*(){o(this,To)||clearTimeout(o(this,To)),v(this,Nr,o(this,Nr).concat(e)),yield H(this,Qd,Zh).call(this)})}closeConsumer(e){return this.closeConsumers([e])}closeConsumers(e){return u(this,null,function*(){if(!o(this,or))return;const n=e.map(i=>this.consumers.get(i)).filter(i=>i!==void 0);if(n.length===0)return;const{failedConsumers:r}=yield o(this,or).close(n);r!=null&&r.length&&p.warn("Failed to close some consumers",{consumerIds:r})})}closeAllConsumers(){return this.closeConsumers(Array.from(o(this,Ri).keys()))}switchConsumersToLayer(e,n){return u(this,null,function*(){const r=this.recvTransport.getDatachannel("events");if(!r){p.warn("events datachannel not found");return}const i={type:"switch_consumer_layer",payload:{consumerIds:e,layer:n}};yield r.request(i),p.info(`Consumers switched layers to ${n}`,{consumerIds:e})})}}So=new WeakMap,Ds=new WeakMap,Ri=new WeakMap,Eo=new WeakMap,Yd=new WeakMap,or=new WeakMap,Qh=new WeakMap,Nr=new WeakMap,To=new WeakMap,Xh=new WeakSet,Uy=function(){return o(this,So).getValue("connectionHandler")},Qd=new WeakSet,Zh=function(){return u(this,null,function*(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const t=500,e=o(this,Nr).splice(0,o(this,Nr).length);try{const n=e.filter(({producerId:s})=>!this.producers.get(s));if(n.length===0)return;const{consumers:r,failedProducers:i}=yield this.recvTransport.consume(n,H(this,ip,Hy).bind(this),o(this,or).negotiate.bind(o(this,or)));r.forEach(H(this,sp,qy).bind(this)),i!=null&&i.length&&(p.error("Failed to create consumers for producers",{producers:i}),v(this,Nr,o(this,Nr).concat(i)),v(this,To,setTimeout(H(this,Qd,Zh).bind(this),t)))}catch(n){p.error("failed to consume on transport",{error:n})}})},ep=new WeakSet,Fy=function(){return u(this,null,function*(){yield this.connectTransportWithRetry(this.sendTransport),v(this,Yd,new Yh(this.socketHandler))})},tp=new WeakSet,By=function(){return u(this,null,function*(){switch(this.recvTransport.on("connect",()=>{o(this,Eo).clear()}),yield this.connectTransportWithRetry(this.recvTransport),this.nodeType){case tt.CF:{v(this,or,new $N(this.events,this.recvTransport,this.socket,this.socketHandler));break}case tt.HIVE:default:v(this,or,new JN(this.recvTransport))}})},np=new WeakSet,Wy=function(t){return o(this,Yd).create(t)},rp=new WeakSet,jy=function(t,e){t.on("close",(n,r)=>u(this,null,function*(){const{offer:i,reason:s}=n;if(p.info("producer::closing",{debuggingHint:s,producer:G(x({},t),{status:"closing"})}),s!==qd){const a={producerId:t.id,description:{sdp:i.sdp,type:i.type,target:zn.PUBLISHER}};try{const c=yield this.socketHandler.closeProducer(a),d={sdp:c==null?void 0:c.sdp,type:c==null?void 0:c.type};p.info("producer::closed",{producer:G(x({},t),{status:"closed"})}),r({answer:d})}catch(c){p.error("producer close error",c)}}this.producers.delete(t.id),e()})),t.on("trackended",()=>{p.info("producer::trackended",{producer:G(x({},t),{status:"UNKNOWN"})})}),o(this,Ds).set(t.id,t)},ip=new WeakSet,Hy=function(t){return u(this,null,function*(){try{return yield this.recvTransport.canConsume(),yield o(this,or).create(t)}catch(e){throw p.error("Error in consume request",{error:e}),e}})},sp=new WeakSet,qy=function(t){t.on("close",e=>u(this,null,function*(){p.debug("consumer closed",{consumer:{closureReason:e,id:t.id,kind:t.kind,appData:t.appData}}),o(this,Ri).delete(t.id),P.emit(R.CONSUMER_CLOSED,{id:t.id})})),o(this,Ri).set(t.id,t),this.producerIdToConsumerIdMap.set(t.producerId,t.id),P.emit(R.NEW_CONSUMER,{id:t.id,appData:t.appData,peerId:t.peerId})};var Xd,Zd,el,ko,bo,wo,tl,nl,_o,Yt,Un,Fn,Mi,Ai,Lr,rl,ap,Gy,op,Jy,cp,$y,dp,Ky;const lp=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:n=3,hangoverFrames:r=5,noiseAdaptationRate:i=.95,voiceAdaptationRate:s=.99,minEnergyThreshold:a=.005,maxEnergyThreshold:c=.2,energyRatioThreshold:d=1.5,noiseHistorySize:l=50}={}){f(this,ap),f(this,op),f(this,Xd,void 0),f(this,Zd,void 0),f(this,el,void 0),f(this,ko,void 0),f(this,bo,void 0),f(this,wo,void 0),f(this,tl,void 0),f(this,nl,void 0),f(this,_o,void 0),f(this,Yt,void 0),f(this,Un,void 0),f(this,Fn,!1),f(this,Mi,0),f(this,Ai,0),f(this,Lr,[]),f(this,rl,void 0),v(this,ko,t),v(this,Yt,t),v(this,Xd,e),v(this,Zd,n),v(this,el,r),v(this,bo,i),v(this,wo,s),v(this,tl,a),v(this,nl,c),v(this,_o,d),v(this,rl,l),v(this,Un,t/2)}get voiceDetected(){return o(this,Fn)}processAudioChunk(t){var e,n;const r=H(e=lp,cp,$y).call(e,t),i=H(n=lp,dp,Ky).call(n,t);return H(this,ap,Gy).call(this,r),r/o(this,Un)>o(this,_o)&&r>o(this,Yt)&&i>o(this,Xd)?(v(this,Mi,o(this,Mi)+1),v(this,Ai,o(this,el)),o(this,Mi)>=o(this,Zd)&&v(this,Fn,!0)):(v(this,Mi,0),o(this,Ai)>0?v(this,Ai,o(this,Ai)-1):o(this,Fn)&&v(this,Fn,!1),o(this,Fn)||H(this,op,Jy).call(this,r)),{energy:r,isVoice:o(this,Fn)}}reset(){v(this,Fn,!1),v(this,Mi,0),v(this,Ai,0),v(this,Yt,o(this,ko)),v(this,Un,o(this,ko)/2),v(this,Lr,[])}getThresholdInfo(){return{currentEnergyThreshold:o(this,Yt),backgroundNoiseEnergy:o(this,Un),energyRatioThreshold:o(this,_o)}}};let up=lp;Xd=new WeakMap,Zd=new WeakMap,el=new WeakMap,ko=new WeakMap,bo=new WeakMap,wo=new WeakMap,tl=new WeakMap,nl=new WeakMap,_o=new WeakMap,Yt=new WeakMap,Un=new WeakMap,Fn=new WeakMap,Mi=new WeakMap,Ai=new WeakMap,Lr=new WeakMap,rl=new WeakMap,ap=new WeakSet,Gy=function(t){o(this,Fn)?v(this,Yt,o(this,wo)*o(this,Yt)+(1-o(this,wo))*t):v(this,Yt,o(this,bo)*o(this,Yt)+(1-o(this,bo))*o(this,Un)),v(this,Yt,Math.max(o(this,tl),Math.min(o(this,nl),o(this,Yt))))},op=new WeakSet,Jy=function(t){if(t<o(this,Yt)*1.2)if(o(this,Lr).push(t),o(this,Lr).length>o(this,rl)&&o(this,Lr).shift(),o(this,Lr).length>=10){const e=[...o(this,Lr)].sort((r,i)=>r-i),n=Math.floor(e.length/2);v(this,Un,e[n])}else v(this,Un,.95*o(this,Un)+.05*t)},cp=new WeakSet,$y=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,n)=>e+n)/t.length)},dp=new WeakSet,Ky=function(t){let e=0;for(let n=1;n<t.length;n+=1)(t[n]>=0&&t[n-1]<0||t[n]<0&&t[n-1]>=0)&&(e+=1);return e},f(up,cp),f(up,dp);const zN=60,YN=400;var Di,Oi,Io,Bn,Co,Ni,Po,Os,Ro,Li,Ns,Mo,hp,zy,il,pp,mp,Yy,gp,Qy;const sl=class{constructor(t){f(this,hp),f(this,mp),f(this,Di,void 0),f(this,Oi,void 0),f(this,Io,void 0),f(this,Bn,void 0),f(this,Co,void 0),f(this,Ni,void 0),f(this,Po,void 0),f(this,Os,void 0),f(this,Ro,void 0),f(this,Li,void 0),f(this,Ns,void 0),f(this,Mo,void 0),this.reportRequest=t,v(this,Co,new AudioContext),v(this,Ni,o(this,Co).createAnalyser()),o(this,Ni).fftSize=2048,v(this,Ro,new up)}set producerId(t){v(this,Bn,t)}set audioTrack(t){v(this,Po,t);const e=new MediaStream;e.addTrack(o(this,Po)),o(this,Co).createMediaStreamSource(e).connect(o(this,Ni))}start(){p.debug(`AudioActivityReporter: Starting audio activity reporter: ${o(this,Bn)}`),o(this,Di)&&Jr(o(this,Di)),v(this,Di,$s(()=>u(this,null,function*(){var t;if(!o(this,Po)||!o(this,Bn))return;const{energy:e}=H(this,hp,zy).call(this),n=H(t=sl,il,pp).call(t,e);let r=.9;o(this,Mo)!==n&&o(this,Mo)?r=.9:n?r=.3:r=.5,v(this,Os,(o(this,Os)||0)*(1-r)+e*r)}),zN)),o(this,Oi)&&Jr(o(this,Oi)),v(this,Oi,$s(H(this,mp,Yy).bind(this),YN)),v(this,Io,$s(()=>{p.debug(`AudioActivityReporter: producer: ${o(this,Bn)} energy: ${o(this,Os)}`)},5e3))}stop(){p.debug(`AudioActivityReporter: Stopping audio activity reporter: ${o(this,Bn)}`),o(this,Di)&&Jr(o(this,Di)),o(this,Oi)&&Jr(o(this,Oi)),o(this,Io)&&Jr(o(this,Io)),o(this,Ro).reset()}};let fp=sl;Di=new WeakMap,Oi=new WeakMap,Io=new WeakMap,Bn=new WeakMap,Co=new WeakMap,Ni=new WeakMap,Po=new WeakMap,Os=new WeakMap,Ro=new WeakMap,Li=new WeakMap,Ns=new WeakMap,Mo=new WeakMap,hp=new WeakSet,zy=function(){var t;const e=new Float32Array(o(this,Ni).frequencyBinCount);o(this,Ni).getFloatTimeDomainData(e);const{energy:n,isVoice:r}=o(this,Ro).processAudioChunk(e),i=H(t=sl,gp,Qy).call(t,n);return i===-1/0||n<1e-6?{energy:0,isVoice:!1}:((!o(this,Li)||i<o(this,Li))&&v(this,Li,i),(!o(this,Ns)||i>o(this,Ns))&&v(this,Ns,i),{energy:(i-o(this,Li))/(o(this,Ns)-o(this,Li))*10||0,isVoice:r})},il=new WeakSet,pp=function(t){return t<5},mp=new WeakSet,Yy=function(t=o(this,Os)){var e;if(!o(this,Bn)||!t){p.debug(`AudioActivityReporter: No producerId or energy to report: ${o(this,Bn)}`);return}const n={producerId:o(this,Bn),energy:Math.round(t),silent:H(e=sl,il,pp).call(e,t)};v(this,Mo,n.silent),this.reportRequest(n)},gp=new WeakSet,Qy=function(t){const e=Math.log10(t);return Math.round(e)},f(fp,il),f(fp,gp);const QN=()=>{const t=new window.AudioContext,e=t.createOscillator();e.type="triangle",e.frequency.setValueAtTime(20,t.currentTime);const n=t.createGain();n.gain.setValueAtTime(0,t.currentTime),e.connect(n);const r=t.createMediaStreamDestination();return n.connect(r),e.start(),r.stream.getAudioTracks()[0]},XN=()=>{var t,e;const n=new MediaStream().getVideoTracks()[0],r=document.createElement("canvas");r.height=(t=n==null?void 0:n.getSettings().height)!=null?t:720,r.width=(e=n==null?void 0:n.getSettings().width)!=null?e:1280;const i=r.getContext("2d");return i.fillStyle="black",i.fillRect(0,0,r.width,r.height),setInterval(()=>{i.fillStyle="black",i.fillRect(0,0,r.width,r.height)},1e3),r.captureStream().getVideoTracks()[0]};var ZN=Object.defineProperty,eL=Object.getOwnPropertyDescriptor,he=(t,e,n,r)=>{for(var i=r>1?void 0:r?eL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&ZN(e,n,i),i};const Wn=["video/VP9","video/VP8"];var al,ol,Pt,$,Ao,xi,Ft,Ls,xs,Vi,cl,xr,Do,Vs,Us,Bt,Qt,Ui,Fs,ft,Rt,Bs,Oo,vp,Xy,yp,Zy,Sp,eS;class ue{constructor(e,n,r){f(this,Ui),f(this,ft),f(this,Bs),f(this,vp),f(this,yp),f(this,Sp),g(this,"context"),g(this,"authToken"),g(this,"e2ee"),f(this,al,void 0),f(this,ol,void 0),f(this,Pt,void 0),f(this,$,void 0),f(this,Ao,void 0),f(this,xi,void 0),f(this,Ft,void 0),f(this,Ls,void 0),f(this,xs,void 0),f(this,Vi,void 0),f(this,cl,void 0),f(this,xr,void 0),f(this,Do,void 0),f(this,Vs,void 0),f(this,Us,void 0),f(this,Bt,void 0),f(this,Qt,void 0),g(this,"partialJoinRoomPromise");var i,s;this.context=e;const{socket:a}=r;this.mediaJoined=!1,v(this,Vs,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,Us,new Map([["video/VP9",new Set],["video/VP8",new Set]])),v(this,xi,n),v(this,Pt,a),v(this,Ls,!1),v(this,$,new KN(e,a,n)),v(this,Ft,o(this,$).events),v(this,xr,new Set),v(this,Bt,new Map),v(this,xs,!1),v(this,Vi,new Vd),n===tt.CF&&v(this,Qt,new fp(o(this,$).socketHandler.audioActivity.bind(o(this,$).socketHandler))),this.e2ee=(s=(i=e.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?s:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),v(this,cl,qc(()=>u(this,null,function*(){if(!o(this,Ui,Fs).mediaJoinAttempted)return;const{roomJoined:c}=yield this.joinRoom(o(this,ol),o(this,al),{},!0,!0);c&&(P.emit(R.RESET_PRODUCER_STATE),P.emit(R.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get mediaJoined(){return o(this,Ui,Fs).mediaJoined}set mediaJoined(e){o(this,Ui,Fs).mediaJoined=e}reset(e=!0){o(this,$).closeAllProducers(),o(this,$).closeAllConsumers(),o(this,Bt).clear(),o(this,xr).clear(),e&&(this.partialJoinRoomPromise=void 0,o(this,Vi).stop(),o(this,$).stopAllTransports(),o(this,$).reset(),v(this,Vi,new Vd))}joinRoom(e,n){return u(this,arguments,function*(r,i,s={},a=!1,c=!1){o(this,Ui,Fs).mediaJoinAttempted=!0,v(this,Ls,!0),this.reset(a);const d=ot().ipInfo;if(d!=null&&d.loc&&!o(this,Do)){const h=d.loc.split(",");v(this,Do,{latitude:parseFloat(h[0]),longitude:parseFloat(h[1])})}let l;try{return l=yield o(this,Vi).push(()=>this._joinRoom(r,i,s,c,o(this,Do)),"joinRoom"),l}catch(h){l={roomJoined:!1}}return l.roomJoined||P.emit(R.ROOM_NODE_FAILED),l})}_partialJoinRoom(e,n,r=!1,i=void 0){return u(this,null,function*(){var s;const{ipInfo:a}=ot();let c=i;if(a!=null&&a.loc&&!i){const[h,m]=a.loc.split(",").map(parseFloat);c={latitude:h,longitude:m}}const d=(s=X.getValue(ie.FORCE_VIDEO_CODEC))==null?void 0:s.toString(),l=NN(d);v(this,Ao,l),yield Oh((h,m)=>u(this,null,function*(){if(!o(this,Pt).isConnected){m(new Error("socket is not connected"));return}h>0&&p.warn(`retrying sending join room request, count: ${h}`);try{yield o(this,$).socketHandler.joinRoom(n,e,l,r,c)}catch(y){throw p.error("failed to send join room request, error:",{error:y}),y}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:X.hasFeature(ie.ENABLE_HIVE_INFINITE_RETRIES)?1/0:3}),yield o(this,$).setupTransports({send:!0,recv:!0}),o(this,xi)!==tt.HIVE&&X.hasFeature(ie.PRECREATE_PRODUCERS)&&(this.shareWebcam(XN()),this.shareMic(QN()))})}partialJoinRoom(e,n,r=!1,i=void 0){return u(this,null,function*(){return this.partialJoinRoomPromise=o(this,Vi).push(()=>this._partialJoinRoom(e,n,r,i)),this.partialJoinRoomPromise})}_joinRoom(e,n){return u(this,arguments,function*(r,i,s={},a=!1,c=null){v(this,ol,r);try{this.partialJoinRoomPromise?yield this.partialJoinRoomPromise:yield this._partialJoinRoom(r,i,a,c)}catch(d){p.error("error in partial join room",{error:d})}finally{this.partialJoinRoomPromise=void 0}try{return navigator.product!=="ReactNative"&&setTimeout(()=>u(this,null,function*(){const d={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:i,roomViewType:"groupCall",deviceInfo:G(x({},Ie.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};J.roomJoined(d)})),{roomJoined:yield this.completeJoinRoom()}}catch(d){return p.error("error on sending join room request",{error:d}),{roomJoined:!1}}})}completeJoinRoom(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:e}=yield o(this,$).socketHandler.notifySelfJoinComplete();return v(this,al,e.roomUuid),v(this,xs,!0),v(this,Ls,!1),!0}catch(e){return p.error("error on completing join room:",{error:e}),this.mediaJoined=!1,!1}})}leaveRoom(){return u(this,null,function*(){o(this,$).stopAllTransports(),v(this,xs,!1),o(this,Ui,Fs).mediaJoinAttempted=!1;const e={closeRoom:!1};o(this,Pt).sendMessagePromise(o(this,Ft).leaveRoom,qC.toBinary(e)).then(n=>{var r;(r=RP.fromBinary(n.payload))!=null&&r.closed||p.warn("weird state on peer closed and should not happen")}).catch(n=>{p.error("error on sending leave room request",{error:n})}),J.callEnded(),S.destruct()})}getConsumers(){return o(this,$).consumers}activatePeers(e){return u(this,null,function*(){return this.createConsumers(e)})}deactivatePeers(e,n="default"){return u(this,null,function*(){const r=new Set;e.forEach(s=>{s.screenShare&&s.kind==="video"&&r.add(s.producingPeerId)});const i=n==="default"?e.filter(s=>!r.has(s.producingPeerId)).filter(s=>s.kind!=="audio"):e;yield Promise.all(i.map(s=>{const a=o(this,$).producerIdToConsumerIdMap.get(s.producerId);if(!a){p.warn(`consumer not found in deactivate producers: ${s.producerId}`);return}return o(this,$).closeConsumer(a)}))})}createConsumers(e){return u(this,null,function*(){return e.length===0?Promise.resolve():o(this,$).createConsumers(e)})}closeConsumers(e){return u(this,null,function*(){if(!e.length)return;const n=e.reduce((r,i)=>{const s=o(this,$).producerIdToConsumerIdMap.get(i.producerId);return s?(r.push(s),r):(p.warn(`consumer not found in deactivate producers: ${i.producerId}`),r)},[]);yield o(this,$).closeConsumers(n)})}_shareWebcam(e,n){return u(this,null,function*(){const r=n==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,i=H(this,ft,Rt).call(this,r);if(i){const h=yield i;if(o(this,$).producers.has(h)){const m=o(this,$).producers.get(h);if(!m.closed&&!navigator.isReactNative)return yield m.replaceTrack({track:e}),yield this.resumeWebcam(r),e;yield this.disableWebcam(n)}return this._shareWebcam(e,n)}const s=H(this,Sp,eS).call(this,e,n),a=$c(this.context,"disableSimulcast"),c=o(this,xi)===tt.CF?ie.ENABLE_CF_SIMULCAST:ie.ENABLE_HIVE_SIMULCAST;!a&&X.hasFeature(c)?(p.info(`Simulcast enabled for SFU: ${o(this,xi)}`),s.encodings=RO(e)):p.info(`Simulcast disabled for webcam producer, SFU: ${o(this,xi)}`),X.hasFeature(ie.TRACK_HINT)&&(s.track.contentHint=X.getValue(ie.TRACK_HINT));const d=()=>{p.info("Disabling video due to the producer closure"),o(this,Bt).delete(r)},l=o(this,$).createProducer(s,d);return H(this,Bs,Oo).call(this,r,l.then(h=>h.id)),l.then(h=>h.track)})}shareWebcam(e){return u(this,null,function*(){if(e===void 0)return null;if(X.hasFeature(ie.FORCE_VIDEO_CODEC)){const n=X.getValue(ie.FORCE_VIDEO_CODEC).toString();if(n)return p.debug(`Calling _shareWebcam with forced video codec: ${n}`),this._shareWebcam(e,n)}return yield Promise.all(Wn.map(n=>{var r,i;return((i=(r=o(this,Ao).sender)==null?void 0:r.video)==null?void 0:i.codecs.findIndex(s=>s.mimeType===n))>=0&&o(this,Us).get(n).size>0?(p.debug(`Calling _shareWebcam with video codec: ${n}`),this._shareWebcam(e,n)):e})),e})}shareScreen(e){return u(this,null,function*(){const{video:n,audio:r}=e;if(n===void 0)return;const i={track:n,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1},s=()=>{p.info("Disabling screenShare due to the producer closure"),o(this,Bt).delete(ke.SCREENSHARE_VIDEO),o(this,Bt).delete(ke.SCREENSHARE_AUDIO)},a=o(this,$).createProducer(i,s);H(this,Bs,Oo).call(this,ke.SCREENSHARE_VIDEO,a.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Ie.isElectron()},stopTracks:!1,zeroRtpOnPause:!0},l=()=>{};c=o(this,$).createProducer(d,l),H(this,Bs,Oo).call(this,ke.SCREENSHARE_AUDIO,c.then(h=>h.id))}yield Promise.all([a,c||Promise.resolve()]),J.screenShareStart()})}shareMic(e){return u(this,null,function*(){try{if(e===void 0)throw new Ut("track undefined");const n=H(this,ft,Rt).call(this,ke.MIC);if(n){const a=yield n;if(o(this,$).producers.has(a)){const c=o(this,$).producers.get(a);if(!c.closed&&!navigator.isReactNative){yield c.replaceTrack({track:e}),yield this.resumeMic(),o(this,Qt)&&(o(this,Qt).audioTrack=e,o(this,Qt).producerId=a,o(this,Qt).start());return}yield o(this,$).closeProducer(a,{stopTrack:!1})}yield this.shareMic(e);return}const r=H(this,yp,Zy).call(this,e),i=()=>{o(this,Bt).delete(ke.MIC)},s=o(this,$).createProducer(r,i);H(this,Bs,Oo).call(this,ke.MIC,s.then(a=>a.id)),yield s.then(a=>{o(this,Qt)&&(o(this,Qt).audioTrack=a.track,o(this,Qt).producerId=a.id,o(this,Qt).start())})}catch(n){throw new _(n)}})}pauseMic(){return u(this,null,function*(){var e;const n=yield H(this,ft,Rt).call(this,ke.MIC),r=o(this,$).producers.get(n);if(!r){p.error("pauseMic::could_not_find_mic_producer");return}if(r.paused){p.info("pauseMic::mic_producer_already_paused");return}r.pause(),(e=o(this,Qt))==null||e.stop();const i={producerId:r.id,pause:!0};o(this,Pt).sendMessage(o(this,Ft).toggleProducer,Qc.toBinary(i))})}pauseWebcam(){return u(this,null,function*(){const e=yield H(this,ft,Rt).call(this,ke.WEBCAM),n=yield H(this,ft,Rt).call(this,ke.WEBCAM_BACKUP),r=o(this,$).producers.get(e),i=o(this,$).producers.get(n);if(!r&&!i){p.error("pauseWebcam::could_not_find_webcam_producer");return}const s=a=>{const c={producerId:a.id,pause:!0};o(this,Pt).sendMessage(o(this,Ft).toggleProducer,Qc.toBinary(c))};r&&(r.pause(),s(r)),i&&(i.pause(),s(i))})}resumeMic(){return u(this,null,function*(){const e=yield H(this,ft,Rt).call(this,ke.MIC),n=o(this,$).producers.get(e);if(!n){p.error("resumeMic::could_not_find_mic_producer");return}if(!n.pause){p.info("resumeMic::mic_producer_already_resumed");return}n.resume(),n.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,n);const r={producerId:n.id,pause:!1};o(this,Pt).sendMessage(o(this,Ft).toggleProducer,Qc.toBinary(r))})}resumeWebcam(){return u(this,arguments,function*(e=ke.WEBCAM){const n=yield H(this,ft,Rt).call(this,e),r=o(this,$).producers.get(n);if(!r){p.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){p.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&P.emit(R.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};o(this,Pt).sendMessage(o(this,Ft).toggleProducer,Qc.toBinary(i))})}disableWebcam(e){return u(this,null,function*(){const n=e==="video/VP9"?ke.WEBCAM:ke.WEBCAM_BACKUP,r=yield H(this,ft,Rt).call(this,n);H(this,vp,Xy).call(this,n),r&&(yield o(this,$).closeProducer(r))})}disableMic(){return u(this,null,function*(){var e;const n=yield H(this,ft,Rt).call(this,ke.MIC);n&&(yield o(this,$).closeProducer(n)),(e=o(this,Qt))==null||e.stop(),o(this,Bt).delete(ke.MIC)})}disableScreenShare(){return u(this,null,function*(){p.info("screen_sharing_stopped"),J.screenShareStop();const e=yield H(this,ft,Rt).call(this,ke.SCREENSHARE_VIDEO),n=yield H(this,ft,Rt).call(this,ke.SCREENSHARE_AUDIO);e&&(yield o(this,$).closeProducer(e)),n&&(yield o(this,$).closeProducer(n)),o(this,xr).clear(),o(this,Bt).delete(ke.SCREENSHARE_VIDEO),o(this,Bt).delete(ke.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}unmuteSelf(){return u(this,null,function*(){})}resetVideoProducers(e,n){return u(this,null,function*(){if(e){const r=yield H(this,ft,Rt).call(this,ke.WEBCAM),i=yield H(this,ft,Rt).call(this,ke.WEBCAM_BACKUP);yield o(this,$).closeProducer(r,{stopTrack:!1}),yield o(this,$).closeProducer(i,{stopTrack:!1}),this.shareWebcam(e)}if(n){const r=yield H(this,ft,Rt).call(this,ke.SCREENSHARE_VIDEO);yield o(this,$).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:n})}})}changeDisplayName(e,n){return u(this,null,function*(){const r={displayName:e,participantId:n!=null?n:this.peerId};if(!(yield o(this,$).socketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(e){return u(this,null,function*(){const n={participantId:e};if(!(yield o(this,$).socketHandler.kickPeer(n)))throw new Error("failed to kickout the participant!")})}kickAll(){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.kickAll()))throw new Error("failed to kickout all participant!")})}muteAll(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForPeer(e,"audio")))throw new Error("failed to mute given participant")})}disableVideo(e){return u(this,null,function*(){if(!(yield o(this,$).socketHandler.hostControlForPeer(e,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(e){return u(this,null,function*(){const n={participantId:e!=null?e:""};try{yield o(this,Pt).sendMessagePromise(o(this,Ft).globalPinPeer,eP.toBinary(n))}catch(r){p.error("Error in pinning peer:",{error:r})}})}validateScreenShare(e){return this.peerId===e.peerId&&o(this,$).producers.get(e.producerId)&&o(this,xr).add(e.consumerPeerId),o(this,xr).size}switchConsumersToLayer(e,n){return u(this,null,function*(){o(this,$).switchConsumersToLayer(e,n)})}handleSocketEvents(){return u(this,null,function*(){o(this,Pt).on(o(this,Ft).peerProducerCreateBroadcast,({payload:e})=>{var n,r;if(this.mediaJoined)try{const{participantId:i,producerState:s}=oR.fromBinary(e);if(i===this.peerId)return;if(s!=null&&s.mimeType||(s.mimeType=s.kind===Ln.AUDIO?"audio/opus":"video/VP8"),s.kind===Ln.VIDEO&&!s.screenShare&&((r=(n=o(this,Ao).receiver)==null?void 0:n.video)==null?void 0:r.codecs.findIndex(a=>a.mimeType===Wn[0]))>=0&&o(this,Vs).get(Wn[0]).has(i)&&s.mimeType!==Wn[0]){p.warn(`Ignoring producer: ${s.producerId}`);return}p.info(`producer created broadcast: ${i}, producer state: ${s}`),P.emit(R.NEW_PRODUCER,{peerId:i,producer:G(x({},s),{kind:s.kind===Ln.AUDIO?"audio":"video",producingPeerId:i})})}catch(i){p.error("error in peer-producer-create-broadcast",{error:i})}}),o(this,Pt).on(o(this,Ft).peerProducerToggleBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,initiatorParticipantId:r,producerState:{kind:i,pause:s,producerId:a}}=cv.fromBinary(e),c=i===Ln.AUDIO?"audio":"video";if(p.info(`producer toggle broadcast: ${n}, producerId: ${a}, kind:${c}, paused:${s} payload: ${JSON.stringify(cv.fromBinary(e))}`),n===this.peerId&&r!==this.peerId&&s&&P.emit(c==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),n===this.peerId)return;P.emit(R.PRODUCER_TOGGLE,{peerId:n,producerId:a,paused:s,kind:c}),Array.from(this.getConsumers().values()).filter(d=>d.producerId===a).forEach(d=>{d.paused!==s&&(p.debug(`consumer state mismatched for ${d.id}. updating consumer pause state ${d.paused} to ${s}`),s?(d.pause(),P.emit(R.CONSUMER_PAUSED,{id:d.id})):(d.resume(),P.emit(R.CONSUMER_RESUMED,{id:d.id})))})}catch(n){p.error("error in producer toggle broadcast handler",{error:n})}}),o(this,Pt).on(o(this,Ft).peerLeaveBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n}=Lu.fromBinary(e);if(n===this.peerId)return;p.info(`peer left broadcast:${n}`),o(this,xr).delete(n),o(this,$).consumers.forEach(r=>{r.peerId===n&&r.close()}),P.emit(R.PEER_CLOSED,{id:n})}catch(n){p.error("error in peer left broadcast",{error:n})}}),o(this,Pt).on(o(this,Ft).peerProducerCloseBroadcast,({payload:e})=>{if(this.mediaJoined)try{const{participantId:n,producerState:{producerId:r}}=lR.fromBinary(e);if(n===this.peerId)return;p.info(`producer closed broadcast:${n}`),P.emit(R.PRODUCER_CLOSED,{peerId:n,producerId:r});const i=o(this,$).producerIdToConsumerIdMap.get(r);if(!i){p.warn(`no consumer found for producer:${r}`);return}p.info(`closing consumer ${i}, producer id: ${r}`),o(this,$).closeConsumer(i).then(()=>{p.info(`closed consumer: ${i}`),o(this,$).producerIdToConsumerIdMap.delete(r),P.emit(R.CONSUMER_CLOSED,{id:i})}).catch(s=>{p.error("error closing consumer",{error:s})})}catch(n){p.error("error on producer close broadcast",{error:n})}}),o(this,Pt).on(o(this,Ft).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!o(this,Ls)&&!o(this,xs)||(p.warn("media hub termination broadcast received, rejoining room"),P.emit(R.ROOM_NODE_DISCONNECTED),o(this,cl).call(this))})})}handleCallstatsEvents(){J.onConsumerScore(e=>{e.forEach((n,r)=>{const i=o(this,$).consumers.get(r);i&&P.emit(R.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:n.score,scoreStats:n})})}),J.onProducerScore(e=>{e.forEach((n,r)=>{const i=Array.from(o(this,$).producers.values()).find(s=>s.id===r);i&&P.emit(R.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:n.score,scoreStats:n})})})}handlePeerCapabilities(e,n){var r,i,s,a;for(let c=0;c<=Wn.length;c+=1){const d=Wn[c];if(((i=(r=n==null?void 0:n.receiver)==null?void 0:r.video)==null?void 0:i.codecs.findIndex(l=>l.mimeType===d))>=0||c===Wn.length-1){o(this,Us).get(d).add(e);break}}for(let c=0;c<=Wn.length;c+=1){const d=Wn[c];if(((a=(s=n==null?void 0:n.sender)==null?void 0:s.video)==null?void 0:a.codecs.findIndex(l=>l.mimeType===d))>=0||c===Wn.length-1){o(this,Vs).get(d).add(e);break}}}handlePeerLeaving(e){X.hasFeature(ie.FORCE_VIDEO_CODEC)||(o(this,Vs).forEach(n=>n.delete(e)),o(this,Us).forEach((n,r)=>{n.delete(e),n.size===0&&this.disableWebcam(r)}))}}al=new WeakMap,ol=new WeakMap,Pt=new WeakMap,$=new WeakMap,Ao=new WeakMap,xi=new WeakMap,Ft=new WeakMap,Ls=new WeakMap,xs=new WeakMap,Vi=new WeakMap,cl=new WeakMap,xr=new WeakMap,Do=new WeakMap,Vs=new WeakMap,Us=new WeakMap,Bt=new WeakMap,Qt=new WeakMap,Ui=new WeakSet,Fs=function(){return this.context.getValue("connectionHandler")},ft=new WeakSet,Rt=function(t){return o(this,Bt).get(t)},Bs=new WeakSet,Oo=function(t,e){return o(this,Bt).set(t,e)},vp=new WeakSet,Xy=function(t){return o(this,Bt).delete(t)},yp=new WeakSet,Zy=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!0}},Sp=new WeakSet,eS=function(t,e){return{track:t,codecOptions:[{name:e?e.split("/")[1]:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},he([S.trace("MediaNodeClient.reset",{country:S.location.country})],ue.prototype,"reset",1),he([S.trace("MediaNodeClient.joinRoom")],ue.prototype,"joinRoom",1),he([S.trace("MediaNodeClient.completeJoinRoom")],ue.prototype,"completeJoinRoom",1),he([S.trace("MediaNodeClient.leaveRoom")],ue.prototype,"leaveRoom",1),he([S.trace("MediaNodeClient.activatePeers")],ue.prototype,"activatePeers",1),he([S.trace("MediaNodeClient.deactivatePeers")],ue.prototype,"deactivatePeers",1),he([S.trace("MediaNodeClient.createConsumers")],ue.prototype,"createConsumers",1),he([S.trace("MediaNodeClient.closeConsumers")],ue.prototype,"closeConsumers",1),he([S.trace("MediaNodeClient._shareWebcam")],ue.prototype,"_shareWebcam",1),he([S.trace("MediaNodeClient.shareWebcam")],ue.prototype,"shareWebcam",1),he([S.trace("MediaNodeClient.shareScreen")],ue.prototype,"shareScreen",1),he([S.trace("MediaNodeClient.shareMic")],ue.prototype,"shareMic",1),he([S.trace("MediaNodeClient.pauseMic")],ue.prototype,"pauseMic",1),he([S.trace("MediaNodeClient.pauseWebcam")],ue.prototype,"pauseWebcam",1),he([S.trace("MediaNodeClient.resumeMic")],ue.prototype,"resumeMic",1),he([S.trace("MediaNodeClient.resumeWebcam")],ue.prototype,"resumeWebcam",1),he([S.trace("MediaNodeClient.disableWebcam")],ue.prototype,"disableWebcam",1),he([S.trace("HiveClient.disableMic")],ue.prototype,"disableMic",1),he([S.trace("HiveClient.disableScreenShare")],ue.prototype,"disableScreenShare",1),he([S.trace("MediaNodeClient.muteSelf")],ue.prototype,"muteSelf",1),he([S.trace("MediaNodeClient.resetVideoProducers")],ue.prototype,"resetVideoProducers",1),he([S.trace("MediaNodeClient.changeDisplayName")],ue.prototype,"changeDisplayName",1),he([S.trace("MediaNodeClient.kickPeer")],ue.prototype,"kick",1),he([S.trace("MediaNodeClient.kickAllPeers")],ue.prototype,"kickAll",1),he([S.trace("MediaNodeClient.muteAll")],ue.prototype,"muteAll",1),he([S.trace("MediaNodeClient.muteAllVideo")],ue.prototype,"muteAllVideo",1),he([S.trace("MediaNodeClient.disableAudio")],ue.prototype,"disableAudio",1),he([S.trace("MediaNodeClient.disableVideo")],ue.prototype,"disableVideo",1),he([S.trace("MediaNodeClient.pinPeer")],ue.prototype,"pinPeer",1),he([S.trace("MediaNodeClient.validateScreenShare")],ue.prototype,"validateScreenShare",1);function tS(t,e,n){const r=t.getValue("roomNodeClient");if(r){if(r)return r;throw new Error("Room node client already set up.")}const i=new ue(t,e,n);return t.setValue("roomNodeClient",i),i}function nS(t){const e=t.getValue("roomNodeClient");try{e==null||e.leaveRoom()}catch(n){p.error("roomNodeClient::cleanupRoomNodeClient")}t.setValue("roomNodeClient",void 0)}var tL=Object.defineProperty,nL=Object.getOwnPropertyDescriptor,Fi=(t,e,n,r)=>{for(var i=r>1?void 0:r?nL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&tL(e,n,i),i},Bi,jn,Mt,an,wn,rS;const iS=(rS=class{constructor(t,e,n,r){f(this,an),g(this,"self"),g(this,"authToken"),f(this,Bi,void 0),g(this,"viewType"),f(this,jn,void 0),f(this,Mt,void 0);const{socket:i}=n,s=t.getValue("authToken");this.self=e,v(this,Mt,t),this.viewType=r,this.authToken=s,v(this,Bi,i),v(this,jn,n),e.config.viewType!==yt.Chat&&this.setupEvents()}get peerId(){return o(this,Mt).getValue("peerId")}get mediaJoined(){return o(this,Mt).getValue("connectionHandler").mediaJoined}static init(t,e,n,r,i){return u(this,null,function*(){const s=ot(),a=t.getValue("peerId"),c=!!t.getValue("cachedUserDetails"),d=yield rt.__init__(t,n,r,i,i.name,c);if(navigator.product!=="ReactNative"){const l=!X.hasFeature(ie.PRECALL_BANDWIDTH_TEST);setTimeout(()=>u(this,null,function*(){const h=yield d.getAllDevices();p.info("populated_full_device_list",{devices:JSON.stringify(h)}),J.devices("AUDIO",h==null?void 0:h.filter(m=>m.kind==="audioinput")),J.devices("VIDEO",h==null?void 0:h.filter(m=>m.kind==="videoinput")),J.devices("SPEAKER",h==null?void 0:h.filter(m=>m.kind==="audiooutput")),p.info("Callstats:: initializing");try{yield J.initialize({peerId:a,engineName:Ie.getDeviceInfo().engineName,env:t.getValue("env"),iceServers:yield s.getICEServers(),apiBase:t.getValue("apiBase"),flags:X.getAllFlags(),logger:p,apiHostnames:Gf(t),skipConnectivityChecks:l}),p.info("Callstats:: initialized")}catch(m){p.error("Callstats:: initialization failed",{error:m})}}),0)}else p.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new iS(t,d,e,i.viewType)})}shareMediaTracks(){return u(this,null,function*(){var t;const{audioTrack:e,videoTrack:n,permissions:r,audioEnabled:i,videoEnabled:s,screenShareEnabled:a,screenShareTracks:c}=this.self;if(r.canProduceAudio&&i)try{yield o(this,an,wn).shareMic(e)}catch(d){this.self.disableAudio()}if(r.canProduceVideo&&s)try{const d=yield o(this,an,wn).shareWebcam(n);d&&d.id!==n.id&&X.hasFeature(ie.EXP_RESHARE)&&(yield o(this,an,wn).shareWebcam(d))}catch(d){this.self.disableVideo()}if(r.canProduceScreenshare&&a)try{yield(t=o(this,an,wn))==null?void 0:t.shareScreen({video:c.video,audio:c.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(t){return u(this,null,function*(){let e="kicked";(t==null?void 0:t.kickType)==="kickAll"&&(e="ended"),this.leaveRoom(e)})}waitlistedHandler(){p.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(p.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){p.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(p.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){p.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(t){return u(this,null,function*(){J.callEnded(),o(this,an,wn).reset(),t&&(yield this.joinRoom(t))})}setupEvents(){P.on(R.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),P.on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),P.on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),P.on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),P.on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:t})=>{t===!1&&(this.self.roomState="init"),this.resetSelf(t)}),P.on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:t})=>{if(this.self.roomState==="disconnected")return;let{peerId:e}=this;t&&X.hasFeature(ie.REFRESH_ID_ON_DISCONNECTION)&&(e=Gi()),o(this,Bi).updateURL(e),S.resetPeerId(e),ot().setHeader("dyte-tracing-id",e),ri.remapContext(e,o(this,Mt)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),P.on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),o(this,jn).on(W.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),o(this,jn).on(rd.updateUserPreset,t=>{t.updatePeersPresets.forEach(e=>{e.userIds===this.self.userId&&P.emit(R.UPDATE_PERMISSIONS,e.patch)})}),o(this,jn).on(W.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),o(this,jn).on(W.kick,()=>{this.kickHandler({kickType:"kick"})}),o(this,jn).on(W.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),P.onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),P.on(R.PRODUCER_SCORE_UPDATE,({score:t,kind:e,appData:n,scoreStats:r})=>{var i;const s=(i=n==null?void 0:n.screenShare)!=null?i:!1;this.self.emit("mediaScoreUpdate",{kind:e,isScreenshare:s,score:t,participantId:this.self.id,scoreStats:r})}),P.on(R.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),J.audioOff())})),P.on(R.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),J.videoOff())})),P.onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),P.on(R.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(t=!1){return u(this,null,function*(){try{const{peer:e}=yield o(this,jn).joinRoom(this.self);o(this,jn).socket.flush();const n=lh(e.stageType);if(o(this,Mt).setValue("stageStatus",n,!1),e.waitlisted){this.waitlistedHandler();return}yield this.joinMediaRoom(t),o(this,Mt).notify("stageStatus")}catch(e){throw p.error("Error in joinRoom",{error:e}),e}})}leaveRoom(t="left"){return u(this,null,function*(){var e,n;if(t==="rejected"){try{(e=o(this,Bi))==null||e.disconnect()}catch(r){p.error("SelfController::leaveRoom::socketDisconnect")}this.self.roomState=t,this.self.emit("roomLeft",{state:t});return}this.self.setIsPinned(!1),o(this,Mt).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(t),o(this,Mt).notify("stageStatus");try{(n=o(this,Bi))==null||n.disconnect()}catch(r){p.error("SelfController::leaveRoom::socketDisconnect")}nS(o(this,Mt)),Ld.cleanup(),this.self.roomState=t,this.self.emit("roomLeft",{state:t})})}joinMediaRoom(t=!1){return u(this,null,function*(){var e,n;const{peerId:r,viewType:i,meetingId:s,stageStatus:a,roomNodeOptions:c}=o(this,Mt).getAllValues(),{sfu:d}=c;try{if(i===yt.Livestream){if(a!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t});return}tS(o(this,Mt),d,{socket:o(this,Bi),peerId:r})}const{roomJoined:l}=(n=yield(e=o(this,an,wn))==null?void 0:e.joinRoom(this.self.name,s,{audio:this.self.audioEnabled,video:this.self.videoEnabled,screen:this.self.screenShareEnabled},t,t))!=null?n:{};if(!l)return;a==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:t})}catch(l){throw p.error("Error:SelfController.mediaRoomJoin",{error:l}),new _("Error: could not join media room","0002")}})}leaveMediaRoom(t){return u(this,null,function*(){const e=o(this,Mt).getValue("viewType");t!=="connected-meeting"&&(yield this.cleanupSelf()),!(t==="stageLeft"&&e===yt.Webinar)&&o(this,an,wn)&&(o(this,an,wn).mediaJoined&&t!=="disconnected"&&(yield o(this,an,wn).leaveRoom()),!(t==="stageLeft"&&e===yt.Livestream)&&(o(this,an,wn).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()})}},Bi=new WeakMap,jn=new WeakMap,Mt=new WeakMap,an=new WeakSet,wn=function(){return o(this,Mt).getValue("roomNodeClient")},rS);let Vr=iS;Fi([S.trace("SelfController.resetSelf")],Vr.prototype,"resetSelf",1),Fi([S.trace("SelfController.setupEvents")],Vr.prototype,"setupEvents",1),Fi([S.trace("SelfController.joinRoom")],Vr.prototype,"joinRoom",1),Fi([S.trace("SelfController.leaveRoom")],Vr.prototype,"leaveRoom",1),Fi([S.trace("SelfController.joinMediaRoom")],Vr.prototype,"joinMediaRoom",1),Fi([S.trace("SelfController.leaveMediaRoom")],Vr.prototype,"leaveMediaRoom",1),Fi([S.trace("SelfController.init")],Vr,"init",1);var dl;class rL{constructor(e){f(this,dl,void 0),v(this,dl,e)}on(e,n){let r;e===W.roomPeerCount?r=uv.fromBinary.bind(uv):r=Cv.fromBinary.bind(Cv),o(this,dl).on(e,({payload:i})=>{const s=r(i);return n(s)})}}dl=new WeakMap;var ll;class iL{constructor(e){f(this,ll,void 0),v(this,ll,e)}on(e,n){let r,i;switch(e){case W.transcript:{r=xu.fromBinary.bind(xu),i=xu.create();break}default:{p.debug("AISocketHandler switch case hit default, event not accounted for.");break}}o(this,ll).on(e,({payload:s})=>{let a=i;try{a=r(s)}catch(c){p.error("chatSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}}ll=new WeakMap;var sL=Object.defineProperty,aL=Object.getOwnPropertyDescriptor,Ep=(t,e,n,r)=>{for(var i=r>1?void 0:r?aL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&sL(e,n,i),i},Ur;class ul{constructor(e){f(this,Ur,void 0),v(this,Ur,e)}getPolls(){return o(this,Ur).sendMessagePromise(Xn.getPolls)}createPoll(e,n,r=!1,i=!1){const s={anonymous:r,hideVotes:i,question:e,options:n};return o(this,Ur).sendMessage(Xn.createPoll,Z1.toBinary(s))}votePoll(e,n){const r={index:n,pollId:e};return o(this,Ur).sendMessage(Xn.votePoll,tD.toBinary(r))}on(e,n){let r,i;switch(e){case Xn.updatePoll:case Xn.createPoll:case Xn.votePoll:{r=zu.fromBinary.bind(zu),i=zu.create();break}}o(this,Ur).on(e,({payload:s})=>{let a=i;try{a=r(s)}catch(c){p.error("pollSocketHandler::on::binary_decode_error",{error:c})}return n(a)})}removeListeners(e){o(this,Ur).removeListeners(e)}}Ur=new WeakMap,Ep([S.trace("PollSocketHandler.getPolls")],ul.prototype,"getPolls",1),Ep([S.trace("PollSocketHandler.createPoll")],ul.prototype,"createPoll",1),Ep([S.trace("PollSocketHandler.votePoll")],ul.prototype,"votePoll",1);var Xt;class oL{constructor(e){f(this,Xt,void 0),v(this,Xt,e)}getStageRequests(){return u(this,null,function*(){const{payload:e}=yield o(this,Xt).sendMessagePromise(W.getStageRequests);return e?Ku.fromBinary(e):{stageRequests:[]}})}requestAccess(){o(this,Xt).sendMessage(W.requestStageAccess)}cancelRequestAccess(){o(this,Xt).sendMessage(W.cancelStageRequest)}grantAccess(e){return u(this,null,function*(){const n={userIds:e};o(this,Xt).sendMessage(W.grantStageAccess,H1.toBinary(n))})}denyAccess(e){return u(this,null,function*(){const n={userIds:e};o(this,Xt).sendMessage(W.denyStageAccess,G1.toBinary(n))})}joinStage(){return o(this,Xt).sendMessagePromise(W.joinStage,void 0,void 0,W.peerStageStatusUpdate)}leaveStage(e){const n={userIds:[e]};return o(this,Xt).sendMessagePromise(W.leaveStage,Rv.toBinary(n),void 0,W.peerStageStatusUpdate)}kick(e){const n={userIds:e};return o(this,Xt).sendMessagePromise(W.leaveStage,Rv.toBinary(n))}on(e,n){let r;switch(e){case W.grantStageAccess:case W.denyStageAccess:{r=void 0;break}case W.getStagePeers:{r=Pv.fromBinary.bind(Pv);break}case W.getStageRequests:case W.requestStageAccess:case W.cancelStageRequest:{r=Ku.fromBinary.bind(Ku);break}case W.peerStageStatusUpdate:{r=lv.fromBinary.bind(lv);break}}o(this,Xt).on(e,({payload:i,id:s})=>{if(!i||!r)return n(void 0,s);const a=r(i);return n(a,s)})}getPeerInfo(e){return u(this,null,function*(){const n=yield o(this,Xt).sendMessagePromise(W.getPeerInfo,mv.toBinary({peerId:e}));return ts.fromBinary(n.payload)})}}Xt=new WeakMap;var it;class cL{constructor(e){f(this,it,void 0),v(this,it,e)}addPlugin(e,n){o(this,it).sendMessage(z.addPlugin,a1.toBinary({pluginId:e,staggered:n}))}removePlugin(e){o(this,it).sendMessage(z.removePlugin,c1.toBinary({pluginId:e,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:e}=yield o(this,it).sendMessagePromise(z.getPlugins);return e?A1.fromBinary(e):{plugins:[]}})}customPluginEventToRoom(e,n,r){const i={pluginId:e,pluginData:new TextEncoder().encode(JSON.stringify(n))};o(this,it).sendMessage(z.customPluginEventToRoom,y1.toBinary(i),r)}customPluginEventToPeers(e,n,r,i){const s={pluginId:e,peerIds:n,pluginData:new TextEncoder().encode(JSON.stringify(r))};o(this,it).sendMessage(z.customPluginEventToPeers,E1.toBinary(s),i)}enablePluginForRoom(e,n){o(this,it).sendMessage(z.enablePluginForRoom,l1.toBinary({pluginId:e}),n)}enablePluginForPeers(e,n,r){o(this,it).sendMessage(z.enablePluginForPeers,m1.toBinary({pluginId:e,peerIds:n}),r)}disablePluginForRoom(e,n){o(this,it).sendMessage(z.disablePluginForRoom,h1.toBinary({pluginId:e}),n)}disablePluginForPeers(e,n,r){o(this,it).sendMessage(z.disablePluginForPeers,f1.toBinary({pluginId:e,peerIds:n}),r)}storeInsertKeys(e,n,r,i){const s={pluginId:e,storeName:n,insertKeys:r.map(a=>({storeKey:a.key,payload:new TextEncoder().encode(JSON.stringify(a.payload))}))};o(this,it).sendMessage(z.storeInsertKeys,bv.toBinary(s),i)}storeGetKeys(e,n,r,i){const s={pluginId:e,storeName:n,getKeys:r.map(a=>({storeKey:a.key}))};o(this,it).sendMessage(z.storeGetKeys,w1.toBinary(s),i)}storeDeleteKeys(e,n,r,i){const s={pluginId:e,storeName:n,deleteKeys:r.map(a=>({storeKey:a.key}))};o(this,it).sendMessage(z.storeDeleteKeys,I1.toBinary(s),i)}storeDelete(e,n,r){o(this,it).sendMessage(z.storeDelete,P1.toBinary({pluginId:e,storeName:n}),r)}getPluginDataOld(e,n){p.info("getPluginDataOld",{plugin:{id:e,storeName:n}})}storePluginDataOld(e,n,r){const i={pluginId:e,storeName:n,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};o(this,it).sendMessage(z.storeInsertKeys,bv.toBinary(i))}on(e,n){let r;switch(e){case z.addPlugin:case z.enablePluginForPeers:case z.enablePluginForRoom:{r=$u.fromBinary.bind($u);break}case z.removePlugin:case z.disablePluginForPeers:case z.disablePluginForRoom:{r=wv.fromBinary.bind(wv);break}case z.customPluginEventToPeers:case z.customPluginEventToRoom:{r=Iv.fromBinary.bind(Iv);break}case z.storeInsertKeys:case z.storeGetKeys:case z.storeDeleteKeys:case z.storeDelete:{r=_v.fromBinary.bind(_v);break}}o(this,it).on(e,({payload:i,id:s})=>{const a=r(i);return n(a,s)})}}it=new WeakMap;var dL=Object.defineProperty,lL=(t,e,n)=>e in t?dL(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,uL=(t,e,n)=>(lL(t,typeof e!="symbol"?e+"":e,n),n),Tp=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)},L=(t,e,n)=>(Tp(t,e,"read from private field"),n?n.call(t):e.get(t)),Ce=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)},me=(t,e,n,r)=>(Tp(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Me=(t,e,n)=>(Tp(t,e,"access private method"),n),hl={},hL={get exports(){return hl},set exports(t){hl=t}},Ws=typeof Reflect=="object"?Reflect:null,sS=Ws&&typeof Ws.apply=="function"?Ws.apply:function(t,e,n){return Function.prototype.apply.call(t,e,n)},pl;Ws&&typeof Ws.ownKeys=="function"?pl=Ws.ownKeys:Object.getOwnPropertySymbols?pl=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:pl=function(t){return Object.getOwnPropertyNames(t)};function pL(t){console&&console.warn&&console.warn(t)}var aS=Number.isNaN||function(t){return t!==t};function fe(){fe.init.call(this)}hL.exports=fe,hl.once=vL,fe.EventEmitter=fe,fe.prototype._events=void 0,fe.prototype._eventsCount=0,fe.prototype._maxListeners=void 0;var oS=10;function ml(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(fe,"defaultMaxListeners",{enumerable:!0,get:function(){return oS},set:function(t){if(typeof t!="number"||t<0||aS(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");oS=t}}),fe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},fe.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||aS(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 cS(t){return t._maxListeners===void 0?fe.defaultMaxListeners:t._maxListeners}fe.prototype.getMaxListeners=function(){return cS(this)},fe.prototype.emit=function(t){for(var e=[],n=1;n<arguments.length;n++)e.push(arguments[n]);var r=t==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var s;if(e.length>0&&(s=e[0]),s instanceof Error)throw s;var a=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw a.context=s,a}var c=i[t];if(c===void 0)return!1;if(typeof c=="function")sS(c,this,e);else for(var d=c.length,l=pS(c,d),n=0;n<d;++n)sS(l[n],this,e);return!0};function dS(t,e,n,r){var i,s,a;if(ml(n),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),s=t._events),a=s[e]),a===void 0)a=s[e]=n,++t._eventsCount;else if(typeof a=="function"?a=s[e]=r?[n,a]:[a,n]:r?a.unshift(n):a.push(n),i=cS(t),i>0&&a.length>i&&!a.warned){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=a.length,pL(c)}return t}fe.prototype.addListener=function(t,e){return dS(this,t,e,!1)},fe.prototype.on=fe.prototype.addListener,fe.prototype.prependListener=function(t,e){return dS(this,t,e,!0)};function mL(){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 lS(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=mL.bind(r);return i.listener=n,r.wrapFn=i,i}fe.prototype.once=function(t,e){return ml(e),this.on(t,lS(this,t,e)),this},fe.prototype.prependOnceListener=function(t,e){return ml(e),this.prependListener(t,lS(this,t,e)),this},fe.prototype.removeListener=function(t,e){var n,r,i,s,a;if(ml(e),r=this._events,r===void 0)return this;if(n=r[t],n===void 0)return this;if(n===e||n.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete r[t],r.removeListener&&this.emit("removeListener",t,n.listener||e));else if(typeof n!="function"){for(i=-1,s=n.length-1;s>=0;s--)if(n[s]===e||n[s].listener===e){a=n[s].listener,i=s;break}if(i<0)return this;i===0?n.shift():gL(n,i),n.length===1&&(r[t]=n[0]),r.removeListener!==void 0&&this.emit("removeListener",t,a||e)}return this},fe.prototype.off=fe.prototype.removeListener,fe.prototype.removeAllListeners=function(t){var e,n,r;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var i=Object.keys(n),s;for(r=0;r<i.length;++r)s=i[r],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(e=n[t],typeof e=="function")this.removeListener(t,e);else if(e!==void 0)for(r=e.length-1;r>=0;r--)this.removeListener(t,e[r]);return this};function uS(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?fL(i):pS(i,i.length)}fe.prototype.listeners=function(t){return uS(this,t,!0)},fe.prototype.rawListeners=function(t){return uS(this,t,!1)},fe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):hS.call(t,e)},fe.prototype.listenerCount=hS;function hS(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}fe.prototype.eventNames=function(){return this._eventsCount>0?pl(this._events):[]};function pS(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function gL(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function fL(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function vL(t,e){return new Promise(function(n,r){function i(a){t.removeListener(e,s),r(a)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),n([].slice.call(arguments))}mS(t,e,s,{once:!0}),e!=="error"&&yL(t,i,{once:!0})})}function yL(t,e,n){typeof t.on=="function"&&mS(t,"error",e,n)}function mS(t,e,n,r){if(typeof t.on=="function")r.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){r.once&&t.removeEventListener(e,i),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}class SL extends E{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 gS=new SL;class fS{static encode(e){return gS.toBinary(e)}static decode(e){return gS.fromBinary(new Uint8Array(e))}}function EL(t,e){return Math.floor(Math.random()*(e-t+1)+t)}var Fr;class TL{constructor(e={}){uL(this,"opts"),Ce(this,Fr,void 0),this.opts={initialTimeout:e.initialTimeout||1e3,maxTimeout:e.maxTimeout||1e4,factor:e.factor||2},me(this,Fr,0)}wait(){return u(this,null,function*(){me(this,Fr,L(this,Fr)+1);const e=EL(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*ME(2,L(this,Fr))));yield new Promise(n=>{setTimeout(n,e)})})}getAttempts(){return L(this,Fr)}reset(){me(this,Fr,0)}}Fr=new WeakMap;const Br={debug:0,info:1,warn:2,error:3};var Wi,ji;class kL{constructor(e){Ce(this,Wi,void 0),Ce(this,ji,void 0),me(this,Wi,console),me(this,ji,e)}debug(...e){Br[L(this,ji)]>Br.debug||L(this,Wi).debug("[Sockrates]:",...e)}info(...e){Br[L(this,ji)]>Br.info||L(this,Wi).info("[Sockrates]:",...e)}warn(...e){Br[L(this,ji)]>Br.warn||L(this,Wi).warn("[Sockrates]:",...e)}error(...e){Br[L(this,ji)]>Br.error||L(this,Wi).error("[Sockrates]:",...e)}}Wi=new WeakMap,ji=new WeakMap;var vS=(t=>(t[t.CONNECTING=0]="CONNECTING",t[t.OPEN=1]="OPEN",t[t.CLOSING=2]="CLOSING",t[t.CLOSED=3]="CLOSED",t))(vS||{});const bL="2",wL="3";var xe,js,Ae,He,Wr,st,cr,jr,_n,Hs,dr,kp,yS,No,gl,bp,SS,wp,ES,fl,_p,Ip,TS,Lo,vl,xo,yl,Sl,Cp,qs,Vo,Uo,El;class _L{constructor(e,n){var r;Ce(this,kp),Ce(this,No),Ce(this,bp),Ce(this,wp),Ce(this,fl),Ce(this,Ip),Ce(this,Lo),Ce(this,xo),Ce(this,Sl),Ce(this,qs),Ce(this,Uo),Ce(this,xe,void 0),Ce(this,js,void 0),Ce(this,Ae,void 0),Ce(this,He,void 0),Ce(this,Wr,void 0),Ce(this,st,void 0),Ce(this,cr,void 0),Ce(this,jr,void 0),Ce(this,_n,void 0),Ce(this,Hs,void 0),Ce(this,dr,void 0);var i,s,a,c,d,l,h,m,y;me(this,js,e),me(this,Wr,[]),me(this,st,new hl),me(this,cr,!0),me(this,_n,!1),me(this,Ae,n!=null?n:{}),(i=L(this,Ae)).autoReconnect!=null||(i.autoReconnect=!0),(s=L(this,Ae)).retryConnectionInterval!=null||(s.retryConnectionInterval=1e3),(a=L(this,Ae)).pingTimeout!=null||(a.pingTimeout=3e4),(c=L(this,Ae)).connectionTimeout!=null||(c.connectionTimeout=5e3),(d=L(this,Ae)).debug!=null||(d.debug=!0),(l=L(this,Ae)).maxReconnectionAttempts!=null||(l.maxReconnectionAttempts=10),(h=L(this,Ae)).disconnectOnPingTimeout!=null||(h.disconnectOnPingTimeout=!0),(m=L(this,Ae)).queueOnDisconnect!=null||(m.queueOnDisconnect=!1),(y=L(this,Ae)).flushOnReconnect!=null||(y.flushOnReconnect=!1),me(this,jr,{code:void 0,reason:void 0}),me(this,He,(r=L(this,Ae).logger)!=null?r:new kL(L(this,Ae).debug?"debug":"info")),me(this,dr,new TL)}get readyState(){var e;return(e=L(this,xe))==null?void 0:e.readyState}get url(){return L(this,js)}updateURL(e){me(this,js,e),Me(this,Ip,TS).call(this)}get config(){return L(this,Ae)}get sendQueue(){return L(this,Wr)}flush(){if(!L(this,Ae).queueOnDisconnect)return!1;const e=[];return L(this,Wr).forEach(n=>{this.send(n.event,n.id,n.payload,n.metadata)||e.push(n)}),me(this,Wr,e),L(this,Wr)}connect(e=!1){return u(this,null,function*(){if(!e&&[0,1].includes(this.readyState)){L(this,He).debug("Websocket was already connecting or connected.");return}if(L(this,cr)!==!1)return new Promise((n,r)=>{Me(this,qs,Vo).call(this),Me(this,Uo,El).call(this);try{me(this,xe,new WebSocket(Me(this,kp,yS).call(this,L(this,js)))),L(this,xe).binaryType="arraybuffer",L(this,He).debug("Connecting");const i=setTimeout(()=>{L(this,He).debug("Connection timeout. Closing socket"),me(this,cr,!0),Me(this,Uo,El).call(this),L(this,xe).close(3001,"Connection Timeout"),L(this,Ae).autoReconnect&&!L(this,_n)&&(L(this,st).emit("reconnecting"),Me(this,Lo,vl).call(this)),r(new Error("Connection timed out!"))},L(this,Ae).connectionTimeout);L(this,xe).onopen=()=>{L(this,He).debug(`Ready State: ${vS[L(this,xe).readyState]}`),i&&clearTimeout(i),Me(this,Sl,Cp).call(this),me(this,jr,{code:void 0,reason:void 0}),L(this,st).emit("connected"),L(this,Ae).flushOnReconnect&&this.flush(),n()},L(this,xe).onclose=s=>{try{i&&clearTimeout(i);const{code:a,reason:c}=s;r(c),L(this,He).debug("Socket closed. Close event:",{event:s}),L(this,He).debug(`Connection closed code: ${a}`),L(this,He).debug(`Connection closed reason: ${c}`),L(this,_n)||Me(this,fl,_p).call(this,a,c)}catch(a){Me(this,No,gl).call(this,a)}},L(this,xe).onerror=s=>{Me(this,No,gl).call(this,s)},L(this,xe).onmessage=s=>Me(this,bp,SS).call(this,s)}catch(i){Me(this,No,gl).call(this,i,r)}})})}send(e,n,r,i){const s={event:e,id:n,payload:r,metadata:i};if(L(this,Ae).queueOnDisconnect&&(!L(this,xe)||L(this,xe).readyState!==1))return L(this,He).debug("Queuing message since socket is not connected!",s),L(this,Wr).push(s),!1;const a=fS.encode(s);return Me(this,xo,yl).call(this,a)}emit(e,n,r,i){return this.send(e,n,r,i)}sendRaw(e){return Me(this,xo,yl).call(this,e)}receive(e,n){return L(this,st).on(e.toString(),n)}on(e,n){if(typeof e=="string"&&(e==="connected"||e==="disconnected"||e==="errored"||e==="reconnected"||e==="reconnecting"||e==="reconnectAttempt"||e==="reconnectFailure"||e==="failed")){L(this,st).on(e,n);return}this.receive(e,n)}removeAllListeners(){L(this,st).removeAllListeners()}removeReceiver(e,n){this.removeListener(e,n)}removeListener(e,n){L(this,st).removeListener(e.toString(),n)}removeReceivers(e){this.removeListeners(e)}removeListeners(e){L(this,st).listeners(e.toString()).map(n=>this.removeListener(e,n))}disconnect(){me(this,cr,!1),Me(this,qs,Vo).call(this),this.removeAllListeners(),me(this,jr,{code:1e3,reason:"Sockrates disconnect method called"}),L(this,xe).close(1e3,"Sockrates disconnect method called.")}}xe=new WeakMap,js=new WeakMap,Ae=new WeakMap,He=new WeakMap,Wr=new WeakMap,st=new WeakMap,cr=new WeakMap,jr=new WeakMap,_n=new WeakMap,Hs=new WeakMap,dr=new WeakMap,kp=new WeakSet,yS=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)://.")},No=new WeakSet,gl=function(t,e){L(this,He).error("Error:",{error:t}),L(this,st).emit("errored",{error:t}),e==null||e(t)},bp=new WeakSet,SS=function(t){if(Me(this,Sl,Cp).call(this),t.data===bL){L(this,He).debug("Received ping from server"),Me(this,xo,yl).call(this,wL);return}const e=fS.decode(t.data),{id:n,payload:r}=e;L(this,He).debug("Received message",{event:e.event,messageID:n}),L(this,st).emit(e.event.toString(),{id:n,payload:r})},wp=new WeakSet,ES=function(){return L(this,xe).readyState===1},fl=new WeakSet,_p=function(t,e){me(this,jr,{reason:e,code:t}),L(this,st).emit("disconnected",{code:t,reason:e})},Ip=new WeakSet,TS=function(){const{reason:t,code:e}=L(this,jr);e&&e!==1e3&&L(this,cr)&&L(this,Ae).autoReconnect&&!L(this,_n)&&(L(this,He).debug(`Triggering reconnection due to ${t}.`),L(this,st).emit("reconnecting"),Me(this,Lo,vl).call(this))},Lo=new WeakSet,vl=function(t=!0){return u(this,null,function*(){if(t&&L(this,_n)){L(this,He).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(L(this,_n)||L(this,dr).reset(),L(this,Ae).maxReconnectionAttempts!==null&&L(this,dr).getAttempts()>=L(this,Ae).maxReconnectionAttempts){L(this,st).emit("failed"),me(this,_n,!1);return}me(this,_n,!0),Me(this,Uo,El).call(this),Me(this,qs,Vo).call(this);try{if(yield L(this,dr).wait(),L(this,cr)===!1)return;if(L(this,He).debug(`Reconnection attempt ${L(this,dr).getAttempts()}`),L(this,st).emit("reconnectAttempt",{attempt:L(this,dr).getAttempts()}),yield this.connect(),!Me(this,wp,ES).call(this))throw Error("Reconnect Failed");me(this,_n,!1),me(this,jr,{code:void 0,reason:void 0}),L(this,st).emit("reconnected")}catch(e){L(this,He).debug("Failed to reconnect."),L(this,st).emit("reconnectFailure",{attempt:L(this,dr).getAttempts()}),Me(this,Lo,vl).call(this,!1)}})},xo=new WeakSet,yl=function(t){try{return L(this,xe).send(t),!0}catch(e){return L(this,He).error(e.message),!1}},Sl=new WeakSet,Cp=function(){this.config.disconnectOnPingTimeout&&(L(this,He).debug("Resetting ping timeout"),Me(this,qs,Vo).call(this),me(this,Hs,setTimeout(()=>{var t;L(this,He).debug("Disconnecting the socket due to ping timeout"),me(this,cr,!0);const e=3002,n="Ping timeout";(t=L(this,xe))==null||t.close(e,n),Me(this,fl,_p).call(this,e,n)},L(this,Ae).pingTimeout)))},qs=new WeakSet,Vo=function(){L(this,Hs)&&(clearTimeout(L(this,Hs)),me(this,Hs,void 0))},Uo=new WeakSet,El=function(){L(this,xe)&&(L(this,xe).onopen=void 0,L(this,xe).onerror=void 0,L(this,xe).onmessage=void 0,L(this,xe).onclose=void 0)};var IL=Object.defineProperty,CL=Object.getOwnPropertyDescriptor,Tl=(t,e,n,r)=>{for(var i=r>1?void 0:r?CL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&IL(e,n,i),i};const kS=65535,PL=3e3;var Hi,Ve,Ue,qe,In,Hr,kl,Pp,bl,Rp,bS;const wS=(bS=class{constructor(t,{peerId:e,meetingId:n,authToken:r,capabilities:i}){f(this,Ue),f(this,kl),f(this,bl),f(this,Hi,void 0),f(this,Ve,void 0),g(this,"roomName"),g(this,"authToken"),g(this,"capabilities"),f(this,In,void 0),f(this,Hr,void 0);var s;if(!e||!n||!r)throw new _("peerId, meetingId, or authToken can not be empty","0404");v(this,In,void 0),v(this,Hr,t),this.capabilities=i,this.roomName=n,this.authToken=r,v(this,Hi,H(this,kl,Pp).call(this,e)),v(this,Ve,new _L(o(this,Hi),{autoReconnect:!0,disconnectOnPingTimeout:(s=i.includes("PING"))!=null?s:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:p})),this.handleSocketConnectionEvents()}get joinAttempted(){return o(this,Ue,qe).socketJoinAttempted}set joinAttempted(t){o(this,Ue,qe).socketJoinAttempted=t}get peerId(){return o(this,Hr).getValue("peerId")}updateURL(t){t!==this.peerId&&(v(this,Hi,H(this,kl,Pp).call(this,t)),p.debug("SocketService:: Connection URL updated.")),o(this,Ve).updateURL(o(this,Hi))}static getSocketEdgeDomain(t){return Zi({servicePrefix:"socket-edge",baseURI:t})}get url(){return o(this,Hi)}connect(){return u(this,null,function*(){o(this,Ue,qe).socketJoinAttempted=!0,yield o(this,Ve).connect(),o(this,Ue,qe).socketJoinAttempted=!0,o(this,Ue,qe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){return u(this,null,function*(){o(this,Ue,qe).socketJoinAttempted=!1,o(this,Ve).disconnect(),o(this,Ue,qe).socketJoinAttempted=!0,o(this,Ue,qe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}})}get isConnected(){try{return o(this,Ve).readyState===1}catch(t){return!1}}sendMessage(t,e,n){const r={};return S.injectContext(r),o(this,Ve).send(t,n!=null?n:H(this,bl,Rp).call(this),e,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(t,e,n,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:t,timeout:i,protobuf:e,messageId:n,resp:r})}sendMessagePromiseWithTimeout({event:t,timeout:e,protobuf:n,messageId:r,resp:i}){const s=i!=null?i:t;return new Promise((a,c)=>{const d=(T,b)=>{o(this,Ve).removeListener(s,T),o(this,Ve).removeListener(kS,b),o(this,Ve).removeListener(en.errorResponse,b),o(this,Ve).removeListener(pn.errorResponse,b)},l=r!=null?r:H(this,bl,Rp).call(this),h={};S.injectContext(h);const m=({id:T,payload:b})=>{if(l===T){let O;try{const M=SP.fromBinary(b);O=new Error(M.errorMessage)}catch(M){O=new Error("failed to parse error message",{cause:M});try{const F=kR.fromBinary(b);O=new Error(F.message)}catch(F){O=new Error("failed to parse error message",{cause:F})}}c(O),d(y,m)}},y=({id:T,payload:b})=>{l===T&&(a({id:T,payload:b}),d(y,m))};o(this,Ve).on(s,y),o(this,Ve).on(kS,m),o(this,Ve).on(en.errorResponse,m),o(this,Ve).on(pn.errorResponse,m),setTimeout(()=>{d(y,m),c(new Error(`request timeout for callback eventId:${t}`))},e),o(this,Ve).send(t,l,n,new TextEncoder().encode(JSON.stringify(h)))})}on(t,e){o(this,Ve).on(t,e)}onStateEvent(t,e){o(this,Ve).on(t,e)}removeListener(t,e){o(this,Ve).removeListener(t,e)}removeListeners(t){o(this,Ve).removeListeners(t)}flush(){return o(this,Ve).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){p.info("SocketService::Connected to socket-edge"),o(this,In)&&(clearTimeout(o(this,In)),v(this,In,void 0)),o(this,Ue,qe).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:t,reason:e})=>{var n;p.info("SocketService::Disconnected from socket-edge",{error:{code:t,reason:e},country:S.location.country});const{recv:r,send:i}=(n=o(this,Ue,qe).mediaState)!=null?n:{};r!=null&&r.state&&(r==null?void 0:r.state)!==Rr.CONNECTED||i!=null&&i.state&&(i==null?void 0:i.state)!==Rr.CONNECTED?P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,Ue,qe).joinAttempted}):v(this,In,setTimeout(()=>{P.emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:o(this,Ue,qe).joinAttempted}),v(this,In,void 0)},PL)),o(this,Ue,qe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){p.info("SocketService::Reconnecting to socket-edge",{country:S.location.country}),o(this,Ue,qe).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:e}){p.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:e}}),o(this,Ue,qe).updateSocketConnectionState("reconnectAttempt",e)})),this.onStateEvent("reconnectFailure",({attempt:t})=>{p.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:t}}),o(this,Ue,qe).updateSocketConnectionState("reconnectFailure",t)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){p.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:o(this,Ue,qe).mediaJoinAttempted}}),o(this,In)&&(clearTimeout(o(this,In)),v(this,In,void 0)),P.emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:o(this,Ue,qe).mediaJoinAttempted}),o(this,Ue,qe).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){p.info("SocketService::Failed to connect to socket-edge",{country:S.location.country}),P.emit(R.SOCKET_SERVICE_FAILED),o(this,Ue,qe).updateSocketConnectionState("failed")}))}},Hi=new WeakMap,Ve=new WeakMap,Ue=new WeakSet,qe=function(){return o(this,Hr).getValue("connectionHandler")},In=new WeakMap,Hr=new WeakMap,kl=new WeakSet,Pp=function(t){let e=wS.getSocketEdgeDomain(o(this,Hr).getValue("baseURI"));typeof $c(o(this,Hr),"socket_server_base")=="string"&&(e=$c(o(this,Hr),"socket_server_base"));const n=`wss://${e}`,r=new URL(`${n}/ws`),i=this.peerId,s=G(x({roomID:this.roomName,peerID:t,authToken:this.authToken,useMediaV2:!0},i!==t&&{oldPeerID:i}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(a=>Xc[a]).join(" "),joinWithDetails:!0,useCfWorker:!0});return Object.entries(s).forEach(([a,c])=>{r.searchParams.append(a,c.toString())}),r.href},bl=new WeakSet,Rp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},bS);let Fo=wS;Tl([S.trace("SocketService.connect")],Fo.prototype,"connect",1),Tl([S.trace("SocketService.disconnect")],Fo.prototype,"disconnect",1),Tl([S.trace("SocketService.sendMessagePromise")],Fo.prototype,"sendMessagePromise",1),Tl([S.trace("SocketService.sendMessagePromiseWithTimeout")],Fo.prototype,"sendMessagePromiseWithTimeout",1);const qi=class{static handleConnectedRoomsDumpRaw({payload:t}){var e;const n=zR.fromBinary(t),r=n.meetings.map(i=>{var s;return{id:i.id,title:i.title,participants:(s=i.participants)!=null?s:[]}});return{parentMeeting:{id:n.parentMeeting.id,title:n.parentMeeting.title,participants:(e=n.parentMeeting.participants)!=null?e:[]},meetings:r}}static handleTransferPeerRaw({payload:t}){const e=TM.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}static handleMovedPeerRaw({payload:t}){const e=vv.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}static handleConnectedRoomsUpdatedRaw({payload:t}){return fv.fromBinary(t).payloads.map(e=>({id:e.id,title:e.title}))}static handleConnectedRoomsDeletedRaw({payload:t}){return uM.fromBinary(t).payloads}static getConnectedRoomsDump(){return u(this,null,function*(){const t=yield qi.socketService.sendMessagePromise(W.getConnectedRoomsDump);return qi.handleConnectedRoomsDumpRaw(t)})}static createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield qi.socketService.sendMessagePromise(W.createConnectedRooms,ZR.toBinary({payloads:t}));return fv.fromBinary(e).payloads.map(n=>({id:n.id,title:n.title}))})}static updateConnectedRooms(t){return u(this,null,function*(){})}static disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(r=>({id:r})),n=yield qi.socketService.sendMessagePromise(W.deleteConnectedRooms,dM.toBinary({payloads:e}));return qi.handleConnectedRoomsDeletedRaw(n)})}static movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield qi.socketService.sendMessagePromise(W.movePeers,vM.toBinary({sourceMeetingId:t.sourceMeetingId,destinationMeetingId:t.destinationMeetingId,participants:t.participants}));return new TextDecoder().decode(e.payload).includes("error")?{success:!1,error:"failed to move participants"}:{success:!0}}catch(e){return{success:!1,error:e}}})}};let Ne=qi;g(Ne,"socketService"),g(Ne,"currentMeetingId");var RL=Object.defineProperty,ML=Object.getOwnPropertyDescriptor,wl=(t,e,n,r)=>{for(var i=r>1?void 0:r?ML(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&RL(e,n,i),i};const Gs=class{constructor(t,e){g(this,"apiBase"),g(this,"selfController"),g(this,"pollController"),g(this,"chatController"),g(this,"metaController"),g(this,"storesManager"),g(this,"stageController"),g(this,"pluginController"),g(this,"internalsController"),g(this,"recordingController"),g(this,"livestreamController"),g(this,"participantController"),this.apiBase=t,this.storesManager=e.storesManager,this.metaController=e.metaController,this.selfController=e.selfController,this.chatController=e.chatController,this.pollController=e.pollController,this.stageController=e.stageController,this.pluginController=e.pluginController,this.recordingController=e.recordingController,this.internalsController=e.internalsController,this.participantController=e.participantController,this.livestreamController=e.livestreamController}static init(t){return u(this,null,function*(){var e,n;const{peerId:r,apiBase:i,authToken:s,meetingId:a,organizationId:c,cachedUserDetails:d}=t.getAllValues();if(P.reset(),Ld.cleanup(),nS(t),Ie.isSupported()===!1)throw new _("Browser not supported","0010",!0);const l=ND(t,{authToken:s,baseURL:i,cachedUserDetails:d});l.setRoomName(a),l.setRoomUUID(a),l.setOrganizationId(c),l.setHeader("dyte-tracing-id",r),t.setValue("apiClient",l);const h=new fO;t.setValue("connectionHandler",h);const m=Gs.createSocketService(t),y=m.connect(),T=l.getUserDetails(),b=l.getPlugins();let O=tt.HIVE,M,F="";try{yield Gs.setupFlagsmith(t)}catch(Z){p.error("Failed to setup flagsmith",{error:Z})}try{yield y}catch(Z){p.error("[Controller]: Failed to connect to socket server:",{error:Z})}try{({sfu:O,meetingTitle:F}=yield l.getRoomNodeData()),M=yield T,p.info(`SFU ${O} is being used.`),t.setValue("presetName",M.preset.name),t.setValue("roomNodeOptions",{sfu:O})}catch(Z){p.error("Failed to get room metadata",{error:Z})}const V=eN.init(M.preset,!t.getValue("modules").theme),K=Gs.setupControllers(m,t,M,b,F,V);sO(V)&&((e=Gs.createRoomNodeClient(t,m).partialJoinRoom(M.participant.name,a,void 0))==null||e.catch(Z=>{p.error("[Controller]: Failed to queue partial media room promise:",{error:Z})})),S.location.country=(n=l.ipInfo)==null?void 0:n.country;const{controllers:I}=yield K;return rC(),new Gs(i,I)})}static setupFlagsmith(t){return u(this,null,function*(){var e;const{peerId:n,baseURI:r,overrides:i,meetingId:s,organizationId:a}=t.getAllValues(),c=tC(s),d=G(x({entity:Au.PEER,clientId:a,isAnonUser:!a,sdkVersion:t.getValue("sdkVersion"),presetName:t.getValue("presetName"),meetingHash:c,roomName:s},Ie.getDeviceInfo()),{isReactNative:navigator.isReactNative});try{const l=(e=i==null?void 0:i.whitelabelled_flags_endpoint)==null||e?Zi({servicePrefix:"flags",baseURI:r}):"edge.api.flagsmith.com";yield X.identify(`${Au.PEER}_${n}`,JSON.parse(JSON.stringify(d)),!1,5e3,l,p),p.info("flagsmith::allFlags",{flags:JSON.stringify(X.getAllFlags())},!0)}catch(l){p.error("Failed to fetch flagsmith flags")}})}static setupControllers(t,e,n,r,i,s){return u(this,null,function*(){var a,c,d;const l=e.getValue("modules"),{preset:h,participant:m}=n,y=e.getValue("defaults"),{sfu:T}=e.getValue("roomNodeOptions"),{viewType:b,mediaConstraints:{audio:O}}=s;e.setValue("viewType",b),e.setValue("defaults",x({mediaConfiguration:{audio:{enableHighBitrate:(a=O.enableHighBitrate)!=null?a:!1,enableStereo:(c=O.enableStereo)!=null?c:!1}}},y));const M=TN.init(e,b,h.permissions);e.setValue("maxPreferredStreams",Ie.isMobile()?s.maxVideoStreams.mobile:s.maxVideoStreams.desktop);let F,V,K,I,Z,ae,we,ce;const De=new iL(t);Ne.socketService=t;const At=new ul(t),A=new tn(t),k=new oL(t),w=Ld.create(t,e),j=new cL(t),Pe=new rL(t),Qe=new ci(t),B=yield Vr.init(e,w,m,M,s),C=yield Yv.init(e,B.self,w,De,i);if(l.participant&&(ce=new rr(e,B.self,w,T)),(d=l.e2ee)!=null&&d.enabled&&l.e2ee.manager.init(p,P),l.chat&&(V=yield Zn.init(e,A,Qe,B.self,ce.participants)),l.internals&&(Z=yield mh.init()),l.livestream&&s.viewType===yt.Livestream&&X.hasFeature(ie.LIVESTREAM)&&(we=new my(B.self,Pe)),s.viewType!==yt.Chat){if(l.poll&&(F=yield qv.init(e,B.self,At)),l.recording&&(ae=new iy(e,B.self,w)),l.stage&&(K=new Qv(e,k,w,B.self,ce.participants)),l.plugin){if(!ce)throw new _("The plugin module cannot be initialized without the `participant` module","0102");const lr=yield r;I=yield _a.init(e,lr,j,A,V==null?void 0:V.chat,B.self,ce.participants,i)}if(l.pip){const lr=yield aC._init(e,B.self);e.setValue("pip",lr)}}const Xe={storesManager:new cN(e,j),pollController:F,selfController:B,metaController:C,chatController:V,stageController:K,pluginController:I,recordingController:ae,internalsController:Z,livestreamController:we,participantController:ce};return{theme:s,permissions:M,controllers:Xe}})}static createRoomNodeClient(t,e){const{peerId:n,roomNodeOptions:r}=t.getAllValues(),{sfu:i}=r;return tS(t,i,{socket:e,peerId:n})}static createSocketService(t){const{peerId:e,meetingId:n,authToken:r}=t.getAllValues(),i=["PING"];return new Fo(t,{peerId:e,meetingId:n,authToken:r,capabilities:i})}};let Bo=Gs;wl([S.trace("Controller.init")],Bo,"init",1),wl([S.trace("setupFlagsmith")],Bo,"setupFlagsmith",1),wl([S.trace("Controller.createRoomNodeClient")],Bo,"createRoomNodeClient",1),wl([S.trace("Controller.createSocketService")],Bo,"createSocketService",1);var AL=Object.defineProperty,DL=Object.getOwnPropertyDescriptor,OL=(t,e,n,r)=>{for(var i=r>1?void 0:r?DL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&AL(e,n,i),i},_l,Mp;class _S extends jt{constructor(e,n){super(),f(this,_l,void 0),g(this,"meetings",[]),g(this,"parentMeeting",null),f(this,Mp,void 0),v(this,Mp,e),v(this,_l,n.self)}get supportsConnectedMeetings(){return o(this,_l).id!==""}get isActive(){return this.meetings.length!==0}get currentMeetingId(){return Ne.currentMeetingId}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
20
20
  Please connect with Dyte team to move you to V2 APIs & to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),yield Ne.getConnectedRoomsDump()})}createMeetings(e){return u(this,null,function*(){return this.validateConnectedMeetingsAction(),(yield Ne.createConnectedRooms(e)).map(n=>({id:n.id,title:n.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),yield Ne.updateConnectedRooms(e.map(n=>({meetingId:n.id,title:n.title})))})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction();const n=this.meetings.map(r=>e.includes(r.id)&&r.participants.length!==0?this.moveParticipants(r.id,this.parentMeeting.id,r.participants.map(i=>i.id)):Promise.resolve());return yield Promise.all(n),yield Ne.disableConnectedRooms(e)})}moveParticipants(e,n,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:n,participants:r.map(s=>({id:s}))});return i.success&&this.moveSuccessHandler(e,n,r),i})}moveParticipantsWithCustomPreset(e,n,r){return u(this,null,function*(){this.validateConnectedMeetingsAction();const i=yield Ne.movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:n,participants:r});return i.success&&this.moveSuccessHandler(e,n,r.map(s=>s.id)),i})}moveSuccessHandler(e,n,r){const i=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(s=>s.participants)].forEach(s=>i.set(s.id,s)),n===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(r.map(s=>i.get(s)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(s=>!r.includes(s.id))),this.meetings=this.meetings.map(s=>{if(n===s.id){const a=s.participants.concat(r.map(c=>i.get(c)));return G(x({},s),{participants:a})}if(e===s.id){const a=s.participants.filter(c=>!r.includes(c.id));return G(x({},s),{participants:a})}return s})}}_l=new WeakMap,Mp=new WeakMap,OL([Nt({maxInvocations:60,period:60})],_S.prototype,"getConnectedMeetings",1);var NL=Object.defineProperty,LL=Object.getOwnPropertyDescriptor,Ap=(t,e,n,r)=>{for(var i=r>1?void 0:r?LL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&NL(e,n,i),i},Wo,Cn,Dp,Op;const qr=(Dp=class{constructor(t,e,n){g(this,"connectedMeetings"),f(this,Wo,void 0),f(this,Cn,void 0),f(this,Op,void 0),v(this,Op,t),v(this,Wo,n),this.connectedMeetings=new _S(t,e),this.setCurrentMeeting(e)}static init(t,e,n){return qr.instance||(qr.instance=new qr(t,e,n)),qr.instance.connectedMeetings.supportsConnectedMeetings&&(qr.instance.setupEvents(),e.self.once("roomJoined",()=>qr.instance.getConnectedMeetings())),qr.instance}setCurrentMeeting(t){v(this,Cn,t),Ne.currentMeetingId=t.meta.meetingId}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){Ne.socketService&&(Ne.socketService.on(W.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),Ne.socketService.on(W.transferPeer,this.handleTransferPeer.bind(this)),Ne.socketService.on(W.movedPeer,this.handleMovedPeer.bind(this)),Ne.socketService.on(W.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),Ne.socketService.on(W.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this)))}handleTransferPeer(t){const e=Ne.handleTransferPeerRaw(t);return this.switchMeeting(e)}switchMeeting(t){return u(this,arguments,function*({authToken:e,meetingId:n}){var r,i,s,a;if(!this.connectedMeetings.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.`);p.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",n);const c={video:o(this,Cn).self.videoEnabled,audio:o(this,Cn).self.audioEnabled};try{o(this,Cn).self.cleanupEvents(),yield o(this,Cn).leave("connected-meeting")}catch(l){p.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(i=(r=o(this,Cn))==null?void 0:r.meta)==null?void 0:i.meetingId}`,{error:l})}Ne.socketService=void 0,p.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${n}`);const d=yield RS.init(G(x({},o(this,Wo)),{cachedUserDetails:null,defaults:G(x(x({},o(this,Wo).defaults),c),{mediaHandler:o(this,Cn).self}),authToken:e}));p.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(s=d==null?void 0:d.meta)==null?void 0:s.meetingId}`);try{const{hidden:l}=o(this,Cn).self;d.self.setName(o(this,Cn).self.name),yield d.join(),l&&d.self.hide()}catch(l){p.error("ConnectedMeetingsController.joinRoom",{error:l})}return p.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(a=d==null?void 0:d.meta)==null?void 0:a.meetingId}`),this.connectedMeetings.emit("meetingChanged",d),this.setCurrentMeeting(d),d})}handleConnectedRoomsDump(t){const e=Ne.handleConnectedRoomsDumpRaw(t);this.connectedMeetings.meetings=e.meetings.map(n=>({id:n.id,title:n.title,participants:n.participants||[]})),this.connectedMeetings.parentMeeting={id:e.parentMeeting.id,title:e.parentMeeting.title,participants:e.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(t){return Ne.handleMovedPeerRaw(t)}handleConnectedRoomsUpdated(t){const e=Ne.handleConnectedRoomsUpdatedRaw(t),n=new Map;this.connectedMeetings.meetings.forEach(r=>{n.set(r.id,r)}),e.forEach(r=>{n.has(r.id)?n.get(r.id).title=r.title:n.set(r.id,G(x({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(n.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(t){const e=Ne.handleConnectedRoomsDeletedRaw(t).map(n=>n.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(n=>!e.includes(n.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Wo=new WeakMap,Cn=new WeakMap,Op=new WeakMap,g(Dp,"instance"),Dp);let Il=qr;Ap([S.trace("ConnectedMeetingsController.getConnectedMeetings")],Il.prototype,"getConnectedMeetings",1),Ap([S.trace("ConnectedMeetingsController.setupEvents")],Il.prototype,"setupEvents",1),Ap([S.trace("ConnectedMeetingsController.switchMeeting")],Il.prototype,"switchMeeting",1);class xL{constructor(){g(this,"battery"),g(this,"init",()=>u(this,null,function*(){try{"getBattery"in navigator&&(this.battery=yield navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){p.error("Error getting battery",e)}})),g(this,"updateChargeInfo",()=>{var e;p.log(`Battery charging? ${(e=this.battery)!=null&&e.charging?"Yes":"No"}`)}),g(this,"updateLevelInfo",()=>{if(!this.battery){p.log("Battery level: Not known");return}p.log(`Battery level: ${this.battery.level*100}%`)}),g(this,"cleanup",()=>{var e,n;"getBattery"in navigator&&((e=this.battery)==null||e.removeEventListener("chargingchange",this.updateChargeInfo),(n=this.battery)==null||n.removeEventListener("levelchange",this.updateLevelInfo))})}}const IS=new xL;function VL(t,e){t.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c \u2014 not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.dyte.io/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:n,orgId:r,participantId:i}=JSON.parse(atob(t.split(".")[1]));if(!n)throw Error(`Received V1 auth token ${t}`);let s="dyte.io";e&&(s=e);const a=`https://api.${s}`;return{meetingId:n,orgId:r,participantId:i,baseURI:s,apiBase:a}}catch(n){throw p.error("constants::decodeAuthToken",{error:n,debuggingHint:`Unable to decode auth token: ${t}`},!0),new _("Invalid auth token","0004")}}var UL=Object.defineProperty,FL=Object.getOwnPropertyDescriptor,Cl=(t,e,n,r)=>{for(var i=r>1?void 0:r?FL(e,n):e,s=t.length-1,a;s>=0;s--)(a=t[s])&&(i=(r?a(e,n,i):a(i))||i);return r&&i&&UL(e,n,i),i},dt,Pl,Rl,Np,CS,PS;let Gr=(PS=class{constructor(t,e){f(this,Np),f(this,dt,void 0),f(this,Pl,void 0),f(this,Rl,void 0),v(this,Rl,t),v(this,dt,e)}static init(t){return u(this,null,function*(){var e,n,r,i,s,a,c;XI(),Ie.init();const d=(n=(e=t==null?void 0:t.cachedUserDetails)==null?void 0:e.peerId)!=null?n:Gi();IS.init();const{authToken:l,baseURI:h}=t,m=VL(l,h),{meetingId:y}=m,T=fc(m,["meetingId"]);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const b=Gr.setupContext(d,t,y,T);S.meetingMetadata.roomName=y,S.meetingMetadata.userId=T.participantId,S.meetingMetadata.organizationId=T.orgId,S.init(b,(i=(r=t.modules)==null?void 0:r.tracing)!=null?i:!0),p.info("DyteClient::init::options",{dyteClientInitOptions:G(x({},t),{authToken:`${(s=t.authToken)==null?void 0:s.slice(0,10)}...
22
- ${(a=t.authToken)==null?void 0:a.slice(-10)}`})});const O=yield Bo.init(b),M=new Gr(b,O);return H(c=M,Np,CS).call(c,t),M})}static setupContext(t,e,n,r){var i;const s=ri.createContext(t,e),a=x(x({},JI),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",a),s.setValue("sdkName","web-core"),s.setValue("meetingId",n),s.setValue("apiBase",r.apiBase),s.setValue("baseURI",r.baseURI),s.setValue("userId",r.participantId),s.setValue("organizationId",r.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(i=e.overrides)!=null?i:{}),s.setValue("env",$I({baseURI:r.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",gn(e.cachedUserDetails)),s.setValue("sdkVersion","2.5.0-staging.89"),s}join(){return u(this,null,function*(){const{selfController:t}=o(this,dt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){IS.cleanup();const{selfController:e}=o(this,dt);return e.leaveRoom(t)})}get participants(){var t;return(t=o(this,dt).participantController)==null?void 0:t.participants}get self(){var t;return(t=o(this,dt).selfController)==null?void 0:t.self}get meta(){var t;return(t=o(this,dt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=o(this,dt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=o(this,dt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=o(this,dt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=o(this,dt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=o(this,Pl))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=o(this,dt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=o(this,dt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=o(this,dt).stageController)==null?void 0:t.stage}get stores(){return o(this,dt).storesManager}get __internals__(){var t;return(t=o(this,dt).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)})}},dt=new WeakMap,Pl=new WeakMap,Rl=new WeakMap,Np=new WeakSet,CS=function(t){v(this,Pl,Il.init(o(this,Rl),this,t))},PS);Cl([ht("0002"),Mr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Gr.prototype,"join",1),Cl([ht("0003")],Gr.prototype,"leave",1),Cl([ht("0001"),Mr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Gr,"init",1),Gr=Cl([ht("0000")],Gr);const RS=Gr;return RS}();
22
+ ${(a=t.authToken)==null?void 0:a.slice(-10)}`})});const O=yield Bo.init(b),M=new Gr(b,O);return H(c=M,Np,CS).call(c,t),M})}static setupContext(t,e,n,r){var i;const s=ri.createContext(t,e),a=x(x({},JI),e==null?void 0:e.modules);return s.setValue("peerId",t),s.setValue("modules",a),s.setValue("sdkName","web-core"),s.setValue("meetingId",n),s.setValue("apiBase",r.apiBase),s.setValue("baseURI",r.baseURI),s.setValue("userId",r.participantId),s.setValue("organizationId",r.orgId),s.setValue("authToken",e.authToken),s.setValue("overrides",(i=e.overrides)!=null?i:{}),s.setValue("env",$I({baseURI:r.baseURI})),s.setValue("defaults",e.defaults||{audio:!0,video:!0}),s.setValue("onError",e.onError||(()=>{})),s.setValue("cachedUserDetails",gn(e.cachedUserDetails)),s.setValue("sdkVersion","2.5.0-staging.90"),s}join(){return u(this,null,function*(){const{selfController:t}=o(this,dt);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){IS.cleanup();const{selfController:e}=o(this,dt);return e.leaveRoom(t)})}get participants(){var t;return(t=o(this,dt).participantController)==null?void 0:t.participants}get self(){var t;return(t=o(this,dt).selfController)==null?void 0:t.self}get meta(){var t;return(t=o(this,dt).metaController)==null?void 0:t.meta}get ai(){var t;return(t=o(this,dt).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=o(this,dt).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=o(this,dt).chatController)==null?void 0:t.chat}get polls(){var t;return(t=o(this,dt).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=o(this,Pl))==null?void 0:t.connectedMeetings}get recording(){var t;return(t=o(this,dt).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=o(this,dt).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=o(this,dt).stageController)==null?void 0:t.stage}get stores(){return o(this,dt).storesManager}get __internals__(){var t;return(t=o(this,dt).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)})}},dt=new WeakMap,Pl=new WeakMap,Rl=new WeakMap,Np=new WeakSet,CS=function(t){v(this,Pl,Il.init(o(this,Rl),this,t))},PS);Cl([ht("0002"),Mr.executeWithLock({methodName:"meeting.join",lockName:"DyteClient.join",timeout:3e3})],Gr.prototype,"join",1),Cl([ht("0003")],Gr.prototype,"leave",1),Cl([ht("0001"),Mr.executeWithLock({methodName:"DyteClient.init",lockName:"DyteClient.init",timeout:3e3})],Gr,"init",1),Gr=Cl([ht("0000")],Gr);const RS=Gr;return RS}();