@cloudflare/realtimekit 1.5.0-staging.5 → 1.5.0-staging.8

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
@@ -17,4 +17,4 @@ ${this.message}`;try{let d=n&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("Cli
17
17
  `},Pi=Yf,GD=jD,zd=GD,_i=Pi.parse;Pi.parseParams,Pi.parseFmtpConfig,Pi.parsePayloads,Pi.parseRemoteCandidates,Pi.parseImageAttributes,Pi.parseSimulcastStreamList;class Yd extends Ih{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Yd(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:n}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[n?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const h=c.sender.getParameters();h.encodings=r,await c.sender.setParameters(h)}const d=(h,m)=>{var $;const S=_i(h),y=S.media[S.media.length-1],w=y.rtp.filter(L=>m.some(F=>F.name===L.codec)),P=y.fmtp.filter(L=>w.some(F=>F.payload===L.payload)),C=($=y.rtcpFb)==null?void 0:$.filter(L=>w.some(F=>F.payload===L.payload)),O=w.map(L=>L.payload);return S.media[S.media.length-1].rtp=w,S.media[S.media.length-1].fmtp=P,S.media[S.media.length-1].rtcpFb=C,S.media[S.media.length-1].payloads=O.join(" "),zd(S)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:h,enableStereo:m}=this,S=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=${S}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async h=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this.pc.setRemoteDescription(h),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters(),o=n.encodings.length-1-r;n.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(n)}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=async i=>{const n=await i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n)))}})}}class Dh extends Ih{static createFactory(t){return()=>new Dh(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const n=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var m;const h=o.codecs.find(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const S=((m=h.sdpFmtpLine)==null?void 0:m.split(";"))||[];S.push(...u.parameters);const y=[...new Set(S).values()];h.sdpFmtpLine=y.join(";")}c.push(h)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),n.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:h}=this,m=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${m}`)}return this.midTransceiverMap.set(n.mid,n),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),n.mid),sender:n.sender,mid:n.mid}}addCustomEventListeners(){this.pc.ondatachannel=t=>{const{channel:e}=t;e.onmessage=async r=>{const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",t.channel,i)}}}}function WD(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class JD extends Jd{constructor(e,r){var i;super(e);g(this,qs);g(this,Qo);g(this,kl);g(this,Rl);p(this,"rtpReceiver");p(this,"id");p(this,"localId");p(this,"producerId");p(this,"producingTransportId");p(this,"mimeType");p(this,"track");p(this,"peerId");p(this,"appData");p(this,"transceiver");g(this,Yo,void 0);g(this,zi,void 0);g(this,Hs,void 0);g(this,_l,void 0);this.id=r.id,this.localId=r.localId,f(this,Yo,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Hs,!1),this.producerId=r.producerId,this.track=r.track,f(this,zi,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,U(this,kl,rv).call(this),f(this,_l,e)}get closed(){return a(this,Hs)}get kind(){return this.track.kind}get paused(){return a(this,zi)}close(e,r){a(this,Hs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,qs,ui)),f(this,Hs,!0),r&&(U(this,Rl,iv).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Hs))throw new Mt("closed");return a(this,Yo).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,qs,ui)),a(this,Hs)){this.logger.error("consumer::pause() | Consumer closed",a(this,qs,ui));return}f(this,zi,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,qs,ui)),a(this,Hs)){this.logger.error("Consumer::resume() | Consumer closed",a(this,qs,ui));return}f(this,zi,!1),this.track.enabled=!0,this.safeEmit("resume")}}Yo=new WeakMap,zi=new WeakMap,Hs=new WeakMap,_l=new WeakMap,qs=new WeakSet,ui=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Qo=new WeakSet,sp=function(){this.logger.debug('Consumer::track "ended" event',a(this,qs,ui)),this.safeEmit("trackended")},kl=new WeakSet,rv=function(){this.track.addEventListener("ended",U(this,Qo,sp).bind(this))},Rl=new WeakSet,iv=function(){try{this.track.removeEventListener("ended",U(this,Qo,sp)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,qs,ui),error:e})}};class KD extends Jd{constructor(e,r){var i,n;super(e);g(this,Kt);p(this,"id");p(this,"localId");g(this,Rs,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");g(this,Pa,void 0);g(this,_a,void 0);g(this,Yi,void 0);g(this,ds,!1);g(this,at,void 0);g(this,ii,void 0);g(this,ka,void 0);g(this,Cl,void 0);this.id=r.id,this.localId=r.localId,f(this,at,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,ii,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,ka,void 0),f(this,Pa,r.stopTracks),f(this,_a,r.disableTrackOnPause),f(this,Yi,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,Rs,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,Cl,e)}get closed(){return a(this,ds)}get track(){return a(this,at)}get paused(){return a(this,ii)}get maxSpatialLayer(){return a(this,ka)}async close(e){if(a(this,ds))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Kt,Ns)),f(this,ds,!0),this._destroyTrack(),e===Xd){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,Rs).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,ds))throw new Mt("closed");return a(this,Rs).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Kt,Ns)),a(this,ds)&&this.logger.error("Producer::pause() | Producer closed",a(this,Kt,Ns)),f(this,ii,!0),a(this,at)&&a(this,_a)&&(a(this,at).enabled=!1),a(this,Yi)&&a(this,Rs).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Kt,Ns)),a(this,ds)){this.logger.error("Producer::resume() | Producer closed",a(this,Kt,Ns));return}f(this,ii,!1),a(this,at)&&a(this,_a)&&(a(this,at).enabled=!0),a(this,Yi)&&a(this,Rs).replaceTrack(this.localId,a(this,at)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Kt,Ns)),a(this,ds)){if(e&&a(this,Pa))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Kt,Ns),error:r})}throw new Mt("closed")}else if(e&&e.readyState==="ended")throw new Mt("track ended");if(e===a(this,at)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Kt,Ns));return}(!a(this,Yi)||!a(this,ii))&&await a(this,Rs).replaceTrack(this.localId,e),this._destroyTrack(),f(this,at,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,ds))throw new Mt("closed");if(this.kind!=="video")throw new go("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,Rs).setMaxSpatialLayer(this.localId,e),f(this,ka,e)}async setRtpEncodingParameters(e){if(a(this,ds))throw new Mt("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,Rs).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Kt,Ns)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,at)&&a(this,at).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,at))try{a(this,at).removeEventListener("ended",this._onTrackEnded),a(this,Pa)&&a(this,at).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Kt,Ns),error:r})}}}Rs=new WeakMap,Pa=new WeakMap,_a=new WeakMap,Yi=new WeakMap,ds=new WeakMap,at=new WeakMap,ii=new WeakMap,ka=new WeakMap,Cl=new WeakMap,Kt=new WeakSet,Ns=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function Xf(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Oh(s){return Math.random().toString(36).substring(2,2+s)}const Qd=1;function Zf(s){const t=s;return delete t.payload._bolt,t}function zD(s){return s.payload&&Xf(s.payload)}function YD(s){var t,e;return zD(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}const Ra=class extends ot.EventEmitter{constructor(e,r,i,n){super();p(this,"channel");p(this,"queue");p(this,"serverProtocolVersion");g(this,ni,new Map);g(this,Il,void 0);g(this,Qi,void 0);p(this,"respond",(e,r,i=!1)=>{let n;i?n=Ra.createErrorResponse(e,r):n=Ra.createResponse(e,r),this.channel.send(JSON.stringify(n))});p(this,"notify",e=>{const r=Ra.createNotification(e);this.channel.send(JSON.stringify(r))});p(this,"request",async e=>{const r=Ra.createRequest(e),i=new Promise((n,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),n(u))},timer:setTimeout(()=>{this.queue.delete(d)&&o(new Error(`request timeout for message id: ${d}`))},2e4),cancel:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(u))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),i});p(this,"send",e=>{const r=JSON.stringify(e),i=16384;if(r.length>i){const n=i-200,o=Math.ceil(r.length/n),c=[];for(let l=0;l<o;l+=1){const u=l*n,h=(l+1)*n;c.push(r.slice(u,h))}const d=Tn();for(let l=0;l<o;l+=1){const u=c[l],m=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});a(this,Qi).debug(`Sending message chunk over dc: ${m}`),this.channel.send(m)}}else a(this,Qi).debug(`Sending message over dc: ${r}`),this.channel.send(r)});p(this,"processMessage",e=>{var i;a(this,ni).has(e.id)||a(this,ni).set(e.id,[]);const r=a(this,ni).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(n=>n===void 0)){const n=a(this,ni).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,ni).delete(e.id);const c=JSON.parse(o);if(!c.payload||!Xf(c.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:c}});if(this.processBoltHandshake(c))return;if(this.serverProtocolVersion=(i=c.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(c))return c}});p(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,i=this.queue.get(r);return i?(a(this,Qi).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(Zf(e)):i.resolve(Zf(e)),!0):!1});p(this,"processBoltHandshake",e=>{var r,i;return e.type==="_bolt"||e.type==="handshake"?(this.respond((i=(r=e.payload._bolt)==null?void 0:r.id)!=null?i:Oh(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,f(this,Il,e),f(this,Qi,e.getValue("logger")),this.channel=r,this.queue=new Map}};let ki=Ra;ni=new WeakMap,Il=new WeakMap,Qi=new WeakMap,p(ki,"createRequest",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,_bolt:{id:Oh(8),type:"REQUEST",version:Qd}}}}),p(ki,"createResponse",(e,r)=>{var i;if((i=r.payload)!=null&&i._bolt)throw new Error("rpc fields are internal values");return{type:r.type,payload:{...r.payload,_bolt:{id:e,type:"RESPONSE",version:Qd}}}}),p(ki,"createNotification",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,bolt:{id:Oh(8),type:"NOTIFY",version:Qd}}}}),p(ki,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:Qd}}}));const Xd="transport closed",Ca=class extends Jd{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var w,P,C;super(e);p(this,"awaitQueue");p(this,"observer");p(this,"id");p(this,"serverId");p(this,"direction");p(this,"maxSctpMessageSize");p(this,"handler");p(this,"connectionState","new");p(this,"producers");p(this,"consumers");p(this,"datachannels");p(this,"connected",!1);p(this,"eventsDCReadyPromise");p(this,"eventsDCReadyPromiseResolver");p(this,"eventsDCFailureTimer");p(this,"transportConnectionPromise");p(this,"consumerTrackEvents");p(this,"unknownTracksMap");p(this,"appData");g(this,Xi,void 0);f(this,Xi,e);const m=e.getValue("logger");m.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const S=WD(l,{});delete S.iceServers,delete S.iceTransportPolicy,delete S.bundlePolicy,delete S.rtcpMuxPolicy,delete S.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Ch(m,!0),this.handler=n(),this.handler.enableHighBitrate=(w=h==null?void 0:h.enableHighBitrate)!=null?w:!1,this.handler.enableStereo=(P=h==null?void 0:h.enableStereo)!=null?P:!1,this.handler.enableDtx=(C=h==null?void 0:h.enableDtx)!=null?C:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const y=3e4;this.transportConnectionPromise=new Promise(O=>{const $=setTimeout(()=>{m.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),O(!1)},y);this.once("connected",()=>{clearTimeout($),O(!0)}),this.once("disconnect",()=>{clearTimeout($),O(!1)}),this.once("close",()=>{clearTimeout($),O(!1)})}),this.eventsDCReadyPromise=new Promise(O=>{this.eventsDCReadyPromiseResolver=O}),this.handler.on("@connectionstatechange",O=>{O!==this.connectionState&&(this.logger.debug(`connection state changed to ${O}`),this.connectionState=O,O==="connected"&&(this.connected=!0,this.emit("connected")),O==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(O==="failed"||O==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",O))}),this.handler.on("@icecandidate",({candidate:O})=>{this.closed||this.safeEmit("icecandidate",O)}),this.handler.on("dc_open",O=>{let $=this.datachannels.get(O.label);$||($||($=new ki(a(this,Xi),O,O.label,this.serverId),this.datachannels.set(O.label,$)),this.eventsDCFailureTimer=setTimeout(()=>{O.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",O.label))},5e3))}),this.handler.on("datachannel",(O,$)=>{O.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const L=this.datachannels.get(O.label);if(!L){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:O.label,message:$}});return}try{const F=JSON.parse($);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:F.id,count:F.count,chunkIndex:F.chunkIndex,chunk:F.chunk,transprtId:this.serverId}});const Q=L.processMessage(F);if(!Q)return;this.logger.debug(`datachannel message with id:${F.id} on transport:${this.serverId}complete - ${JSON.stringify(Q)}`),this.emit(`datachannel:${O.label}`,L.label,Q)}catch(F){this.logger.error("error parsing message",{error:F})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(Xd).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Xd)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new Mt("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:n,answer:o}=await e(r);this.setServerId(n),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new Mt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new go("not a sending Transport");if(r.readyState==="ended")throw new Mt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new Br("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:n,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:h={}}=e;this.logger.debug(`produce() [track:${n.id}]`);const{producerId:m,localId:S,rtpSender:y}=await this.awaitQueue.push(async()=>{const{offerSdp:w,callback:P,sender:C,mid:O}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:$,producerId:L}=await r({offer:w,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:O},codecOptions:c,producingTransportId:this.serverId}),F=await P($);return{producerId:L,localId:F,rtpSender:C}},"Transport.produce");return this.createProducerObject({id:m,localId:S,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:y})}async createProducerObject(e){const r=new KD(a(this,Xi),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new Mt("closed");if(this.direction!=="recv")throw new go("not a receiving transport");if(!await this.transportConnectionPromise)throw new Br("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const n={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,h)=>{n[h]=this.createConsumerObjectAndWaitForTrack({...u,producerId:h})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(n).map(([u,h])=>h.then(m=>l.push(m)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=_i(e.sdp),n={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(n[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),n}static setCodecAndFmtpMappings(e,r,i){const n=_i(e.sdp);return n.media=n.media.map(c=>{if(r.includes(c.mid.toString())){const d={...c};return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),{...e,sdp:zd(n)}}static parseHeaderExtensionMappings(e){const r=_i(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=_i(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:zd(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=Ca.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Ca.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=await this.handler.pc.createOffer();this.logger.info("[SDP] Created offer for closing consumers",{sdp:c.sdp}),c=Ca.setCodecAndFmtpMappings(c,i,n),c=Ca.setHeaderExtensionMappings(c,o),this.logger.info("[SDP] Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),await this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=await r(e,c);this.logger.info("[SDP] Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("[SDP] Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}}async setRemoteOffer(e){try{this.logger.info("[SDP] Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("[SDP] Created answer corresponding to received offer",{sdp:r.sdp});const i=_i(r.sdp);return i.media=i.media.map(n=>{if(n.type==="audio"){const o={...n},c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return n}),r.sdp=zd(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const n=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(n)});const o=this.consumerTrackEvents.get(n);o?(o(r,i),this.consumerTrackEvents.delete(n)):(this.logger.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,e))}sendErrorOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i,!0)}sendResponseOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i)}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:n,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:h,mimeType:m}=e,S=`${c}:${h}`,y={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(w,P)=>{const C=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${n}`),this.consumerTrackEvents.delete(S),y.isTimedout=!0,P(y)},5e3),O=(L,F)=>{try{if(L.readyState==="ended")clearTimeout(C),P(y);else{const Q=L;Q.enabled=!0,this.handler.midTransceiverMap.set(F.mid,F);const X=new JD(a(this,Xi),{id:r,localId:F.mid,transceiver:F,track:Q,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:F.receiver,mimeType:m});this.consumers.set(r,X),X.once("close",()=>{this.consumers.delete(X.id),this.handler.midTransceiverMap.delete(F.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",X),clearTimeout(C),w(X)}}catch(Q){this.logger.warn("error while creating consumer:",Q),clearTimeout(C),P(y)}},$=this.unknownTracksMap.get(S);$?(this.logger.info(`track event already received [trackId: ${$.track.id}] [mid: ${$.transceiver.mid}]`),this.unknownTracksMap.delete(S),O($.track,$.transceiver)):(this.logger.info(`Registering onTrack handler for key ${S} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(S,O))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}async sendDataChannelMessage(e,r){const i=this.getDatachannel(e);if(!i)throw ND("DC_NOT_READY",`${e} datachannel not ready`);const n=(await i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(n)}`),n}};let Nh=Ca;Xi=new WeakMap;function QD(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=mp.getParser(t),r=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(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}class XD{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");g(this,Tr,void 0);g(this,Zi,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,Tr,t),f(this,Zi,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)a(this,Zi).debug(`Device::constructor() | handler given: ${e}`);else if(e=QD(a(this,Zi)),e)a(this,Zi).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Ah.createFactory(a(this,Tr));break;case"Safari12":this.handlerFactory=Dh.createFactory(a(this,Tr));break;case"Firefox60":this.handlerFactory=Yd.createFactory(a(this,Tr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Yd.createFactory(a(this,Tr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=Tn();return new Nh(a(this,Tr),{id:e,...t,handlerFactory:this.handlerFactory})}}Tr=new WeakMap,Zi=new WeakMap;const ZD=2e3;class eO extends ot.EventEmitter{constructor(e,r){super();g(this,Da);g(this,tc);g(this,Al);g(this,sc);g(this,Ml);g(this,Dl);g(this,Ol);g(this,Nl);g(this,Vl);g(this,rc);g(this,ic);p(this,"context");g(this,Ia,void 0);g(this,pt,void 0);g(this,mt,void 0);g(this,Xo,void 0);g(this,Zo,void 0);g(this,en,void 0);g(this,Aa,void 0);g(this,ec,void 0);g(this,Ma,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,tn,void 0);g(this,js,"all");this.context=e,f(this,en,r),f(this,Ia,new XD(e)),f(this,Aa,new UD(r)),f(this,ec,vs),a(this,Da,lu).mediaState={send:{state:Vn.NEW},recv:{state:Vn.NEW}},_n(this.context,"forceRelay")&&f(this,js,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,js)}`),U(this,tc,rp).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,en)}get socketHandler(){return a(this,Aa)}get sendTransport(){return a(this,pt)}get recvTransport(){return a(this,mt)}get events(){return a(this,ec)}set sendTransportConnectedCallback(e){f(this,Xo,e)}set recvTransportConnectedCallback(e){f(this,Zo,e)}async setupTransports(e){await U(this,Al,nv).call(this,e);let r,i;e.send&&(r=U(this,sc,ip).call(this,a(this,pt)).then(n=>{try{a(this,Xo).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=U(this,sc,ip).call(this,a(this,mt)).then(n=>{try{a(this,Zo).call(this,n)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,pt);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,pt).close(),a(this,pt).removeAllListeners(),f(this,pt,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,mt);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,mt))==null||r.close(),(i=a(this,mt))==null||i.removeAllListeners(),f(this,mt,void 0)}U(this,tc,rp).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}Ia=new WeakMap,pt=new WeakMap,mt=new WeakMap,Xo=new WeakMap,Zo=new WeakMap,en=new WeakMap,Aa=new WeakMap,ec=new WeakMap,Ma=new WeakMap,tn=new WeakMap,js=new WeakMap,Da=new WeakSet,lu=function(){return this.context.getValue("connectionHandler")},tc=new WeakSet,rp=function(){f(this,tn,{send:void 0,recv:void 0})},Al=new WeakSet,nv=async function(e){var o,c,d,l,u,h,m,S;_n(this.context,"forceRelay")&&f(this,js,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,js)}`);const n=await vt().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));e.send&&U(this,Dl,ov).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(m=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?m:!1,enableDtx:!1},iceTransportPolicy:a(this,js)}),e.recv&&U(this,Ol,cv).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,js)})},sc=new WeakSet,ip=async function(e){const{id:r,serverId:i,direction:n}=e;U(this,Nl,dv).call(this,e);try{return await zf(async(c,d)=>{c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:n}});try{if(e.closed)throw new Br("Cannot reconnect closed transport");await U(this,Ml,av).call(this,e)}catch(l){if(l instanceof Br){d(l);return}throw this.logger.error("Failed to connect transport, retrying",{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect send transport after retry: ${e.id}`,{error:o,transport:{id:r,serverId:i,type:n}}),e.close(),e.removeAllListeners(),o}},Ml=new WeakSet,av=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,en).isConnected)throw new Br("Socket is not connected");if(e.connectionState==="closed")throw new Br("Transport is closed");try{await e.connect(n=>U(this,Vl,lv).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,Ma).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Br(n.message):n}},Dl=new WeakSet,ov=function(e){var r,i;if(a(this,pt)&&a(this,pt).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,pt))==null?void 0:r.id,serverId:(i=a(this,pt))==null?void 0:i.serverId,type:"send"}});return}f(this,pt,a(this,Ia).createTransport({...e,direction:"send"})),this.context.getValue("callstats").configureSendTransport(a(this,pt))},Ol=new WeakSet,cv=function(e){var r,i;if(a(this,mt)&&a(this,mt).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,mt))==null?void 0:r.id,serverId:(i=a(this,mt))==null?void 0:i.serverId,type:"recv"}});return}f(this,mt,a(this,Ia).createTransport({...e,direction:"recv"})),this.context.getValue("callstats").configureRecvTransport(a(this,mt))},Nl=new WeakSet,dv=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",async n=>{U(this,ic,ap).call(this,{state:n,direction:r}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,tn)[r];c!==void 0&&(clearTimeout(c),a(this,tn)[r]=void 0)};switch(n){case"connected":o(),a(this,Ma).lastConnectionTime=performance.now();break;case"disconnected":a(this,tn)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await U(this,rc,np).call(this,e.direction)},ZD);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await U(this,rc,np).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})}),e.on("datachannel:events",async(n,o)=>{var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:n,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,YD(o),l);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(c=o.payload)==null?void 0:c.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(l){this.logger.error(`Unable to handle the incoming datachannel message on channel ${n}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s"),this.handleErrors("reconnectRecvTransport"))})},Vl=new WeakSet,lv=async function(e,r){const i=e==="recv";try{const{sdp:n,type:o}=r,c={consuming:i,description:{sdp:n,type:o,target:i?Zs.SUBSCRIBER:Zs.PUBLISHER},producers:[]};return a(this,Aa).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},rc=new WeakSet,np=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,en).isConnected&&a(this,Ma).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,js,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,pt)}),this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,mt)}),this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}U(this,ic,ap).call(this,{state:Vn.CONNECTED,direction:e})},ic=new WeakSet,ap=function(e){const{state:r,direction:i}=e;a(this,Da,lu).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(_.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Da,lu).mediaState[i]})};class tO{constructor(t,e,r,i,n){g(this,Ll,void 0);g(this,ls,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,Ll,t),f(this,ls,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:h}=d,m={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...m})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),n=new Map;t.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=n.get(d);if(!u)return;if(l.errorCode){a(this,ls).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let h={};try{h=JSON.parse(l.producerState.appData)}catch(m){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:h})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{a(this,ls).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ls).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:Zs.SUBSCRIBER}};return a(this,ls).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,Nk.toBinary(r)),a(this,ls).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ls).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return{};const e=async(r,i)=>{const n=r.map(l=>l.localId);a(this,ls).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:Zs.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=oC.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};return await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"ConsumerStrategy.close",{consumersLength:t.length}),{}}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(n=>n&&n.id);i.forEach(({id:n,producingTransportId:o,localId:c})=>{r.requests.push({producerId:n,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),a(this,ls).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}Ll=new WeakMap,ls=new WeakMap;class Vh{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return _i(t).media.filter(n=>e==="video"?n.type==="video":n.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:n,producingTransportId:o}){var h,m;const c=Vh.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:Zs.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(m=n[0])==null?void 0:m.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}class sO extends eO{constructor(e,r){super(e,r);g(this,ac);g(this,Ul);g(this,$l);g(this,Bl);g(this,Fl);g(this,sn,void 0);g(this,ai,void 0);g(this,Oa,void 0);g(this,nc,void 0);g(this,Gs,void 0);g(this,xl,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,yr,[]);g(this,Na,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,nc,new Vh(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,Oa).clear(),f(this,Gs,new tO(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,sn)}get consumers(){return a(this,ai)}get producerIdToConsumerIdMap(){return a(this,Oa)}get logger(){return this.context.getValue("logger")}reset(){f(this,sn,new Map),f(this,ai,new Map),f(this,Oa,new Map)}async createProducer(e,r){var i,n;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const o=await this.sendTransport.produce(e,U(this,Ul,uv).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,o),U(this,$l,hv).call(this,o,r),o}catch(o){throw this.logger.error(`Failed to create ${((n=e==null?void 0:e.track)==null?void 0:n.kind)||"unknown"} producer`,{error:o}),a(this,xl).producerCreationFailureCount+=1,o}}async closeProducer(e,r){var n;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),(n=this.context.getValue("modules").e2ee)!=null&&n.enabled&&this.context.getValue("peerSessionStore").emit(_.E2EE_INACTIVE_PRODUCER,i)}catch(o){this.logger.error("Failed to close producer on server",{error:o,producer:i})}}closeAllProducers(){return Promise.all(Array.from(a(this,sn).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,Na)||clearTimeout(a(this,Na)),f(this,yr,a(this,yr).concat(e)),await U(this,ac,op).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,Gs))return;const r=e.map(n=>this.consumers.get(n)).filter(n=>n!==void 0);if(r.length===0)return;const{failedConsumers:i}=await a(this,Gs).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,ai).keys()))}async switchConsumersToLayer(e,r){a(this,Gs).switchConsumersToLayer(e,r)}}sn=new WeakMap,ai=new WeakMap,Oa=new WeakMap,nc=new WeakMap,Gs=new WeakMap,xl=new WeakMap,yr=new WeakMap,Na=new WeakMap,ac=new WeakSet,op=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,yr).splice(0,a(this,yr).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),n=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(n.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(n,U(this,Bl,pv).bind(this),a(this,Gs).negotiate.bind(a(this,Gs)));if(o.forEach(U(this,Fl,mv).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);f(this,yr,a(this,yr).concat(d)),f(this,Na,setTimeout(U(this,ac,op).bind(this),e))}}catch(i){if(this.logger.error("failed to consume on transport",{error:i}),i.errorCode==="internal_error"&&i.errorDescription==="Backend error"||i.errorCode==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:i.errorCode,message:i.errorDescription}});try{this.stopTransports({recv:!0})}catch(n){}await this.setupTransports({recv:!0})}}},Ul=new WeakSet,uv=function(e){return a(this,nc).create(e)},$l=new WeakSet,hv=function(e,r){e.on("close",async(i,n)=>{const{offer:o,reason:c}=i;if(this.logger.info("producer::closing",{debuggingHint:c,producer:{...e,status:"closing"}}),c!==Xd){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:Zs.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),u={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),n({answer:u})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),a(this,sn).set(e.id,e)},Bl=new WeakSet,pv=async function(e){try{return await this.recvTransport.canConsume(),await a(this,Gs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},Fl=new WeakSet,mv=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),a(this,ai).delete(e.id),this.context.getValue("peerSessionStore").emit(_.CONSUMER_CLOSED,{id:e.id})}),a(this,ai).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(_.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};const Wl=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:n=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){g(this,Hl);g(this,ql);g(this,oc,void 0);g(this,cc,void 0);g(this,dc,void 0);g(this,Va,void 0);g(this,La,void 0);g(this,xa,void 0);g(this,lc,void 0);g(this,uc,void 0);g(this,Ua,void 0);g(this,Ot,void 0);g(this,Cs,void 0);g(this,Is,!1);g(this,rn,0);g(this,nn,0);g(this,Er,[]);g(this,hc,void 0);f(this,Va,t),f(this,Ot,t),f(this,oc,e),f(this,cc,r),f(this,dc,i),f(this,La,n),f(this,xa,o),f(this,lc,c),f(this,uc,d),f(this,Ua,l),f(this,hc,u),f(this,Cs,t/2)}get voiceDetected(){return a(this,Is)}processAudioChunk(t){var o,c;const e=U(o=Wl,jl,Sv).call(o,t),r=U(c=Wl,Gl,vv).call(c,t);return U(this,Hl,gv).call(this,e),e/a(this,Cs)>a(this,Ua)&&e>a(this,Ot)&&r>a(this,oc)?(f(this,rn,a(this,rn)+1),f(this,nn,a(this,dc)),a(this,rn)>=a(this,cc)&&f(this,Is,!0)):(f(this,rn,0),a(this,nn)>0?f(this,nn,a(this,nn)-1):a(this,Is)&&f(this,Is,!1),a(this,Is)||U(this,ql,fv).call(this,e)),{energy:e,isVoice:a(this,Is)}}reset(){f(this,Is,!1),f(this,rn,0),f(this,nn,0),f(this,Ot,a(this,Va)),f(this,Cs,a(this,Va)/2),f(this,Er,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Ot),backgroundNoiseEnergy:a(this,Cs),energyRatioThreshold:a(this,Ua)}}};let So=Wl;oc=new WeakMap,cc=new WeakMap,dc=new WeakMap,Va=new WeakMap,La=new WeakMap,xa=new WeakMap,lc=new WeakMap,uc=new WeakMap,Ua=new WeakMap,Ot=new WeakMap,Cs=new WeakMap,Is=new WeakMap,rn=new WeakMap,nn=new WeakMap,Er=new WeakMap,hc=new WeakMap,Hl=new WeakSet,gv=function(t){a(this,Is)?f(this,Ot,a(this,xa)*a(this,Ot)+(1-a(this,xa))*t):f(this,Ot,a(this,La)*a(this,Ot)+(1-a(this,La))*a(this,Cs)),f(this,Ot,Math.max(a(this,lc),Math.min(a(this,uc),a(this,Ot))))},ql=new WeakSet,fv=function(t){if(t<a(this,Ot)*1.2)if(a(this,Er).push(t),a(this,Er).length>a(this,hc)&&a(this,Er).shift(),a(this,Er).length>=10){const e=[...a(this,Er)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,Cs,e[r])}else f(this,Cs,.95*a(this,Cs)+.05*t)},jl=new WeakSet,Sv=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Gl=new WeakSet,vv=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},g(So,jl),g(So,Gl);class eS{constructor(t){p(this,"RNAudioSampleHandler");g(this,pc,void 0);f(this,pc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return a(this,pc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}pc=new WeakMap;class tS{constructor(t){p(this,"audioContext");p(this,"analyser");g(this,mc,void 0);f(this,mc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,mc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}mc=new WeakMap;class rO{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const iO=60,nO=400,Sc=class{constructor(t,e){g(this,Jl);g(this,Kl);g(this,br,void 0);g(this,wr,void 0);g(this,Pr,void 0);g(this,gc,void 0);g(this,$a,void 0);g(this,Ba,void 0);g(this,oi,void 0);g(this,an,void 0);g(this,Fa,void 0);g(this,on,void 0);g(this,_r,void 0);g(this,Ws,void 0);this.reportRequest=e,f(this,on,t),f(this,Ba,new So);const{isReactNative:r}=navigator;f(this,_r,r?new eS(a(this,on)):new tS(a(this,on))),f(this,Ws,r?rO:Lf)}get logger(){return a(this,on).getValue("logger")}set producerId(t){f(this,Pr,t)}set audioTrack(t){f(this,gc,t),a(this,_r)instanceof tS&&(a(this,_r).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Pr)}`),a(this,br)&&a(this,Ws).clearInterval(a(this,br)),f(this,br,a(this,Ws).setInterval(async()=>{var i;if(!a(this,gc)||!a(this,Pr))return;const{energy:t}=U(this,Jl,Tv).call(this),e=U(i=Sc,fc,cp).call(i,t);let r=.9;a(this,Fa)!==e&&a(this,Fa)?r=.9:e?r=.3:r=.5,f(this,$a,(a(this,$a)||0)*(1-r)+t*r)},iO)),a(this,wr)&&a(this,Ws).clearInterval(a(this,wr)),f(this,wr,a(this,Ws).setInterval(U(this,Kl,yv).bind(this),nO))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Pr)}`),a(this,br)&&(a(this,Ws).clearInterval(a(this,br)),f(this,br,void 0)),a(this,wr)&&(a(this,Ws).clearInterval(a(this,wr)),f(this,wr,void 0))}catch(t){}a(this,Ba).reset(),a(this,_r)instanceof eS&&a(this,_r).stop()}};let vo=Sc;br=new WeakMap,wr=new WeakMap,Pr=new WeakMap,gc=new WeakMap,$a=new WeakMap,Ba=new WeakMap,oi=new WeakMap,an=new WeakMap,Fa=new WeakMap,on=new WeakMap,_r=new WeakMap,Ws=new WeakMap,Jl=new WeakSet,Tv=function(){var o;const{samples:t}=a(this,_r),{energy:e,isVoice:r}=a(this,Ba).processAudioChunk(t),i=U(o=Sc,zl,Ev).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,oi)||i<a(this,oi))&&f(this,oi,i),(!a(this,an)||i>a(this,an))&&f(this,an,i),{energy:(i-a(this,oi))/(a(this,an)-a(this,oi))*10||0,isVoice:r})},fc=new WeakSet,cp=function(t){return t<5},Kl=new WeakSet,yv=function(t=a(this,$a)){var r;if(!a(this,Pr)||!t)return;const e={producerId:a(this,Pr),energy:Math.round(t),silent:U(r=Sc,fc,cp).call(r,t)};f(this,Fa,e.silent),this.reportRequest(e)},zl=new WeakSet,Ev=function(t){const e=Math.log10(t);return Math.round(e)},g(vo,fc),g(vo,zl);var aO=Object.defineProperty,oO=Object.getOwnPropertyDescriptor,oe=(s,t,e,r)=>{for(var i=r>1?void 0:r?oO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&aO(t,e,i),i};class re{constructor(t,e){g(this,ci);g(this,Ql);g(this,Xl);g(this,Zl);g(this,Ec);g(this,eu);g(this,tu);g(this,Ct);g(this,un);g(this,su);g(this,ru);g(this,iu);p(this,"context");p(this,"authToken");p(this,"e2ee");g(this,vc,void 0);g(this,Tc,void 0);g(this,gt,void 0);g(this,G,void 0);g(this,Yl,void 0);g(this,kt,void 0);g(this,cn,void 0);g(this,dn,void 0);g(this,ln,void 0);g(this,yc,void 0);g(this,us,null);g(this,kr,void 0);g(this,Rt,void 0);g(this,Nt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,gt,r),f(this,cn,!1),f(this,G,new sO(t,r)),f(this,kt,a(this,G).events),f(this,kr,new Set),f(this,Rt,new Map),f(this,dn,!1),f(this,ln,new Ch(t.getValue("logger"))),f(this,Nt,new vo(this.context,a(this,G).socketHandler.audioActivity.bind(a(this,G).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,yc,Lu(async()=>{if(!a(this,ci,ja).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,Tc),a(this,vc),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,ci,ja).mediaJoined}set mediaJoined(t){a(this,ci,ja).mediaJoined=t}reset(){a(this,G).closeAllProducers(),a(this,G).closeAllConsumers(),a(this,Rt).clear(),a(this,kr).clear(),f(this,us,null),a(this,ln).stop(),a(this,G).stopAllTransports(),a(this,G).reset(),f(this,ln,new Ch)}async joinRoom(t,e,r=!1,i=!1,n={}){a(this,ci,ja).mediaJoinAttempted=!0,f(this,cn,!0),r&&this.reset();try{return await a(this,ln).push(()=>U(this,Ql,bv).call(this,t,e,i,n),"joinRoom")}catch(o){return this.logger.error("Error in room joining process",{error:o}),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return a(this,us)?a(this,us):(f(this,us,(async()=>{try{await U(this,Ec,dp).call(this,t,e,r,i)}catch(n){throw f(this,us,null),n}})()),a(this,us))}getConsumers(){return a(this,G).consumers}getProducers(){return a(this,G).producers}async leaveRoom(){a(this,G).stopAllTransports(),f(this,dn,!1),a(this,ci,ja).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,gt).sendMessagePromise(a(this,kt).leaveRoom,nR.toBinary(t)).then(r=>{var i;(i=JR.fromBinary(r.payload))!=null&&i.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(r=>{this.logger.error("error on sending leave room request",{error:r})}),this.context.getValue("callstats").callEnded(),await this.context.getValue("telemetry").destruct()}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,G).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,G).producerIdToConsumerIdMap.get(i.producerId);return n?(r.push(n),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);await a(this,G).closeConsumers(e)}async _shareWebcam(t){var u,h,m,S;const e=Me.WEBCAM,r=U(this,Ct,Qt).call(this,e);if(r){const y=await r;if(a(this,G).producers.has(y)){const w=a(this,G).producers.get(y);if(!w.closed)return await w.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=U(this,iu,Iv).call(this,t),n=_n(this.context,"disableSimulcast"),o=(h=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:h.simulcastConfig;n||o&&o.disable||!((S=(m=this.context)==null?void 0:m.getValue("theme"))!=null&&S.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=F1(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Rt).delete(e)},l=a(this,G).createProducer(i,d);return U(this,un,Kc).call(this,e,l.then(y=>y.id)),l.then(y=>y.track)}async shareWebcam(t){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:fe.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Rt).delete(Me.SCREENSHARE_VIDEO),a(this,Rt).delete(Me.SCREENSHARE_AUDIO)},o=a(this,G).createProducer(i,n);U(this,un,Kc).call(this,Me.SCREENSHARE_VIDEO,o.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:fe.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=a(this,G).createProducer(d,l),U(this,un,Kc).call(this,Me.SCREENSHARE_AUDIO,c.then(u=>u.id))}await Promise.all([o,c||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new Mt("track undefined");const e=U(this,Ct,Qt).call(this,Me.MIC);if(e){const o=await e;if(a(this,G).producers.has(o)){const c=a(this,G).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,Nt)&&(a(this,Nt).audioTrack=t,a(this,Nt).producerId=o,a(this,Nt).start());return}await a(this,G).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=U(this,ru,Cv).call(this,t),i=()=>{a(this,Rt).delete(Me.MIC)},n=a(this,G).createProducer(r,i);U(this,un,Kc).call(this,Me.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,Nt)&&(a(this,Nt).audioTrack=o.track,a(this,Nt).producerId=o.id,a(this,Nt).start())})}catch(e){throw new k(e)}}async pauseMic(){var i;const t=await U(this,Ct,Qt).call(this,Me.MIC),e=a(this,G).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=a(this,Nt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,gt).sendMessage(a(this,kt).toggleProducer,Cd.toBinary(r))}async pauseWebcam(){const t=await U(this,Ct,Qt).call(this,Me.WEBCAM),e=a(this,G).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};a(this,gt).sendMessage(a(this,kt).toggleProducer,Cd.toBinary(r))}async resumeMic(){const t=await U(this,Ct,Qt).call(this,Me.MIC),e=a(this,G).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,gt).sendMessage(a(this,kt).toggleProducer,Cd.toBinary(r))}async resumeWebcam(t=Me.WEBCAM){const e=await U(this,Ct,Qt).call(this,t),r=a(this,G).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,gt).sendMessage(a(this,kt).toggleProducer,Cd.toBinary(i))}async disableWebcam(){const t=Me.WEBCAM,e=await U(this,Ct,Qt).call(this,t);U(this,su,Rv).call(this,t),e&&await a(this,G).closeProducer(e)}async disableMic(){var e;const t=await U(this,Ct,Qt).call(this,Me.MIC);t&&await a(this,G).closeProducer(t),(e=a(this,Nt))==null||e.stop(),a(this,Rt).delete(Me.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await U(this,Ct,Qt).call(this,Me.SCREENSHARE_VIDEO),e=await U(this,Ct,Qt).call(this,Me.SCREENSHARE_AUDIO);t&&await a(this,G).closeProducer(t),e&&await a(this,G).closeProducer(e),a(this,kr).clear(),a(this,Rt).delete(Me.SCREENSHARE_VIDEO),a(this,Rt).delete(Me.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await U(this,Ct,Qt).call(this,Me.WEBCAM);await a(this,G).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await U(this,Ct,Qt).call(this,Me.SCREENSHARE_VIDEO);await a(this,G).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await a(this,G).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,G).socketHandler.kickPeer(e)}kickAll(){a(this,G).socketHandler.kickAll()}async muteAll(t){if(!await a(this,G).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,G).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,G).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,G).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await a(this,gt).sendMessagePromise(a(this,kt).globalPinPeer,TR.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,G).producers.get(t.producerId)&&a(this,kr).add(t.consumerPeerId),a(this,kr).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,G).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,gt).on(a(this,kt).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=wC.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===er.AUDIO?"audio/opus":"video/VP8"),this.logger.info(`producer created broadcast: ${e}, producer state: ${r}`),this.context.getValue("peerSessionStore").emit(_.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===er.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,gt).on(a(this,kt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=jg.fromBinary(t);if(c)return;const d=i===er.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(jg.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(d==="audio"?_.MUTE_SELF:_.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(_.PRODUCER_TOGGLE,{peerId:e,producerId:o,paused:n,kind:d}),Array.from(this.getConsumers().values()).filter(u=>u.producerId===o).forEach(u=>{u.kind==="video"&&n||u.paused!==n&&(this.logger.debug(`consumer state mismatched for ${u.id}. updating consumer pause state ${u.paused} to ${n}`),n?(u.pause(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_RESUMED,{id:u.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,gt).on(a(this,kt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=zu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,kr).delete(e),a(this,G).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(_.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,gt).on(a(this,kt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=kC.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(_.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=a(this,G).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),a(this,G).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,G).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(_.CONSUMER_CLOSED,{id:i})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,gt).on(a(this,kt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,cn)&&!a(this,dn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_DISCONNECTED),a(this,yc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,G).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(_.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(a(this,G).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(_.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}vc=new WeakMap,Tc=new WeakMap,gt=new WeakMap,G=new WeakMap,Yl=new WeakMap,kt=new WeakMap,cn=new WeakMap,dn=new WeakMap,ln=new WeakMap,yc=new WeakMap,us=new WeakMap,kr=new WeakMap,Rt=new WeakMap,Nt=new WeakMap,ci=new WeakSet,ja=function(){return this.context.getValue("connectionHandler")},Ql=new WeakSet,bv=async function(t,e,r,i){f(this,Tc,t);try{a(this,us)?await a(this,us):await U(this,Ec,dp).call(this,t,e,r,i),U(this,Zl,Pv).call(this,e);const{joined:n,error:o}=await U(this,Xl,wv).call(this);return{roomJoined:n,error:o}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1,error:n}}finally{f(this,us,null)}},Xl=new WeakSet,wv=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,G).socketHandler.notifySelfJoinComplete();return f(this,vc,t.roomUuid),f(this,dn,!0),f(this,cn,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},Zl=new WeakSet,Pv=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...fe.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},Ec=new WeakSet,dp=async function(t,e,r,i){try{const n=U(this,eu,_v).call(this);await U(this,tu,kv).call(this,t,e,r,n),await a(this,G).setupTransports({send:!0,recv:!0})}catch(n){throw this.logger.error("Failed to initialize connection",{error:n}),n}},eu=new WeakSet,_v=function(){const t=xD("video/VP8");return f(this,Yl,t),t},tu=new WeakSet,kv=async function(t,e,r,i){await zf(async(n,o)=>{if(!a(this,gt).isConnected){o(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{await a(this,G).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},Ct=new WeakSet,Qt=function(t){return a(this,Rt).get(t)},un=new WeakSet,Kc=function(t,e){return a(this,Rt).set(t,e)},su=new WeakSet,Rv=function(t){return a(this,Rt).delete(t)},ru=new WeakSet,Cv=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},iu=new WeakSet,Iv=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},oe([E.trace("MediaNodeClient.reset")],re.prototype,"reset",1),oe([E.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1),oe([E.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1),oe([E.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1),oe([E.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1),oe([E.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1),oe([E.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1),oe([E.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1),oe([E.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1),oe([E.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1),oe([E.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1),oe([E.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1),oe([E.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1),oe([E.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1),oe([E.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1),oe([E.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1),oe([E.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1),oe([E.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1),oe([E.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1),oe([E.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1),oe([E.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1),oe([E.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1),oe([E.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1),oe([E.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1),oe([E.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1),oe([E.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1),oe([E.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1),oe([E.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function sS(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new re(s,t);return s.setValue("roomNodeClient",r),r}function rS(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var cO=Object.defineProperty,dO=Object.getOwnPropertyDescriptor,Ri=(s,t,e,r)=>{for(var i=r>1?void 0:r?dO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&cO(t,e,i),i};const iS=(GS=class{constructor(s,t,e,r){g(this,Vt);p(this,"self");p(this,"authToken");g(this,hn,void 0);p(this,"viewType");g(this,As,void 0);g(this,Z,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,Z,s),this.viewType=r,this.authToken=n,f(this,hn,i),f(this,As,e),this.setupEvents()}get peerId(){return a(this,Z).getValue("peerId")}get telemetry(){return a(this,Z).getValue("telemetry")}get logger(){return a(this,Z).getValue("logger")}get mediaJoined(){return a(this,Z).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=vt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await ze.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),s.getValue("callstats").devices("AUDIO",h==null?void 0:h.filter(m=>m.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(m=>m.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(m=>m.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:fe.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:l,apiHostnames:P_(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),l.info("Callstats:: initialized")}catch(m){l.error("Callstats:: initialization failed",{error:m})}},0):l.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new iS(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===H.Allowed&&r)try{await a(this,Vt,ps).shareMic(s),this.self.audioEnabled||a(this,Vt,ps).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{await a(this,Vt,ps).shareWebcam(t),this.self.videoEnabled||a(this,Vt,ps).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,Vt,ps))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){a(this,Z).getValue("callstats").callEnded(),a(this,Vt,ps).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,Z).getValue("peerSessionStore").on(_.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,Z).getValue("peerSessionStore").on(_.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,Z).getValue("peerSessionStore").on(_.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,Z).getValue("peerSessionStore").on(_.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Z).getValue("peerSessionStore").on(_.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,Z).getValue("peerSessionStore").on(_.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;const{peerId:t}=this;a(this,hn).updateURL(t),a(this,Z).getValue("telemetry").resetPeerId(t),vt().setHeader("tracing-id",t),Dr.remapContext(t,a(this,Z)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,Z).getValue("peerSessionStore").on(_.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,As).on(x.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,As).on(Nd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,Z).getValue("peerSessionStore").emit(_.UPDATE_PERMISSIONS,t.patch)})}),a(this,As).on(x.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,As).on(x.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,As).on(x.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,Z).getValue("peerSessionStore").onAsync(_.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,Z).getValue("peerSessionStore").on(_.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,Z).getValue("peerSessionStore").on(_.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,Z).getValue("callstats").audioOff())}),a(this,Z).getValue("peerSessionStore").on(_.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,Z).getValue("callstats").videoOff())}),a(this,Z).getValue("peerSessionStore").onAsync(_.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,Z).getValue("peerSessionStore").on(_.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,As).joinRoom(this.self);a(this,As).socket.flush();const e=gh(t.stageType);if(a(this,Z).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new k("Check the network and try again.","0002")}try{await this.joinMediaRoom(s),a(this,Z).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof Br&&t.message==="ice connection failed"?new k("A firewall or network restriction may be blocking the connection.","0014"):new k("Check the network and try again.","0014")}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=a(this,Z).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,Z).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,Z).notify("stageStatus");try{(e=a(this,hn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}rS(a(this,Z)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,Z).getAllValues();try{if(e===Qs.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}sS(a(this,Z),{socket:a(this,hn),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,Vt,ps))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw h!=null?h:new Error("Could not connect to media server");i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=a(this,Z).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Qs.Webinar)&&a(this,Vt,ps)&&(a(this,Vt,ps).mediaJoined&&s!=="disconnected"&&await a(this,Vt,ps).leaveRoom(),!(s==="stageLeft"&&t===Qs.Livestream)&&(a(this,Vt,ps).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},hn=new WeakMap,As=new WeakMap,Z=new WeakMap,Vt=new WeakSet,ps=function(){return a(this,Z).getValue("roomNodeClient")},GS);let Fr=iS;Ri([E.trace("SelfController.resetSelf")],Fr.prototype,"resetSelf",1),Ri([E.trace("SelfController.setupEvents")],Fr.prototype,"setupEvents",1),Ri([E.trace("SelfController.joinRoom")],Fr.prototype,"joinRoom",1),Ri([E.trace("SelfController.leaveRoom")],Fr.prototype,"leaveRoom",1),Ri([E.trace("SelfController.joinMediaRoom")],Fr.prototype,"joinMediaRoom",1),Ri([E.trace("SelfController.leaveMediaRoom")],Fr.prototype,"leaveMediaRoom",1),Ri([E.trace("SelfController.init")],Fr,"init",1);class lO{constructor(t){g(this,bc,void 0);f(this,bc,t)}on(t,e){let r;t===x.roomPeerCount?r=Jg.fromBinary.bind(Jg):r=uf.fromBinary.bind(uf),a(this,bc).on(t,({payload:i})=>{if(t===x.roomPeerCount&&!i)return;const n=r(i);e(n)})}}bc=new WeakMap;class uO{constructor(t,e){g(this,wc,void 0);g(this,Pc,void 0);f(this,wc,e),f(this,Pc,t)}get logger(){return a(this,Pc).getValue("logger")}on(t,e){let r,i;switch(t){case x.transcript:{r=Yu.fromBinary.bind(Yu),i=Yu.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,wc).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}wc=new WeakMap,Pc=new WeakMap;var hO=Object.defineProperty,pO=Object.getOwnPropertyDescriptor,Lh=(s,t,e,r)=>{for(var i=r>1?void 0:r?pO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&hO(t,e,i),i};class Zd{constructor(t,e){g(this,Rr,void 0);g(this,Ha,void 0);f(this,Rr,e),f(this,Ha,t)}get logger(){return a(this,Ha).getValue("logger")}get telemetry(){return a(this,Ha).getValue("telemetry")}getPolls(){return a(this,Rr).sendMessagePromise(sr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Rr).sendMessage(sr.createPoll,dM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Rr).sendMessage(sr.votePoll,uM.toBinary(r))}on(t,e){let r,i;switch(t){case sr.updatePoll:case sr.createPoll:case sr.votePoll:{r=dh.fromBinary.bind(dh),i=dh.create();break}}a(this,Rr).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,Rr).removeListeners(t)}}Rr=new WeakMap,Ha=new WeakMap,Lh([E.trace("PollSocketHandler.getPolls")],Zd.prototype,"getPolls",1),Lh([E.trace("PollSocketHandler.createPoll")],Zd.prototype,"createPoll",1),Lh([E.trace("PollSocketHandler.votePoll")],Zd.prototype,"votePoll",1);var mO=Object.defineProperty,gO=Object.getOwnPropertyDescriptor,fO=(s,t,e,r)=>{for(var i=r>1?void 0:r?gO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mO(t,e,i),i};class nS{constructor(t,e){p(this,"socket");g(this,zt,void 0);f(this,zt,t),this.socket=e,this.handleSocketEvents(),a(this,zt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,zt).getValue("telemetry")}get logger(){return a(this,zt).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(x.joinRoom,t0.toBinary(e));try{const{peer:n}=Cn.fromBinary((await r).payload);a(this,zt).getValue("connectionHandler").socketJoined=!0,a(this,zt).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,zt).getValue("peerSessionStore").emit(_.ROOM_STATE,d),a(this,zt).getValue("peerSessionStore").emit(_.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return $0.fromBinary((await this.socket.sendMessagePromise(x.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const n={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(x.getRoomPeersInfo,GC.toBinary(n));i=Zu.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(x.getRoomPeersInfo);t=Zu.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(x.getRoomPeersInfo);t=Zu.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(x.getPeerInfo,Yg.toBinary({peerId:t}));e=Cn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=zg.create();try{const e=await this.socket.sendMessagePromise(x.getRoomInfo);t=zg.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=sf.create();try{const e=await this.socket.sendMessagePromise(x.getRoomStageState);t=sf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(x.broadcastMessage,ao.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(x.broadcastToEntity,ao.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(x.broadcastToEntity,ao.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(x.leaveRoom,r0.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(x.kick,ef.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(x.kickAll,$g.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(x.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.acceptWaitingRoomRequests,G0.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.denyWaitingRoomRequests,J0.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Nd.updateUserPreset,bI.toBinary(r))}handleSocketEvents(){this.socket.on(x.broadcastMessage,({payload:t})=>{try{const e=ao.fromBinary(t);a(this,zt).getValue("peerSessionStore").emit(_.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(x.broadcastToEntity,({payload:t})=>{try{const e=ao.fromBinary(t);a(this,zt).getValue("peerSessionStore").emit(_.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case x.joinRoom:case x.leaveRoom:case x.kick:case x.kickAll:{r=Cn.fromBinary.bind(Cn),i=Cn.create();break}case x.getWaitingRoomRequests:{r=(n,o)=>n?tf.fromBinary(n,o):{requests:[]},i=tf.create();break}case x.recordingPaused:case x.recordingStarted:case x.recordingStopped:{r=gf.fromBinary.bind(gf);break}case Nd.updateUserPreset:{r=nf.fromBinary.bind(nf);break}case vs.peerJoinedBroadcast:case Vr.peerJoinedBroadcast:{r=Hg.fromBinary.bind(Hg);break}case vs.selfJoinComplete:case Vr.selfJoinComplete:{r=Ku.fromBinary.bind(Ku);break}case vs.globalPeerPinBroadcast:case Vr.globalPeerPinBroadcast:{r=Gg.fromBinary.bind(Gg);break}case vs.selectedPeer:case Vr.selectedPeer:{r=Ju.fromBinary.bind(Ju);break}case vs.selectedPeerDiff:case Vr.selectedPeerDiff:{r=Fg.fromBinary.bind(Fg);break}case vs.leaveRoom:case Vr.leaveRoom:{r=zu.fromBinary.bind(zu);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Nd.getUserPresets,gI.toBinary(e)),i=TI.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}zt=new WeakMap,fO([E.trace("RoomSocketHandler.joinRoom")],nS.prototype,"joinRoom",1);class SO{constructor(t){g(this,Lt,void 0);f(this,Lt,t)}async getStageRequests(){const{payload:t}=await a(this,Lt).sendMessagePromise(x.getStageRequests);return t?ch.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,Lt).sendMessage(x.requestStageAccess)}cancelRequestAccess(){a(this,Lt).sendMessage(x.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,Lt).sendMessage(x.grantStageAccess,ZA.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Lt).sendMessage(x.denyStageAccess,tM.toBinary(e))}joinStage(){return a(this,Lt).sendMessagePromise(x.joinStage,void 0,void 0,x.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Lt).sendMessagePromise(x.leaveStage,pf.toBinary(e),void 0,x.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Lt).sendMessagePromise(x.leaveStage,pf.toBinary(e))}on(t,e){let r;switch(t){case x.grantStageAccess:case x.denyStageAccess:{r=void 0;break}case x.getStagePeers:{r=hf.fromBinary.bind(hf);break}case x.getStageRequests:case x.requestStageAccess:case x.cancelStageRequest:{r=ch.fromBinary.bind(ch);break}case x.peerStageStatusUpdate:{r=Wg.fromBinary.bind(Wg);break}}a(this,Lt).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,Lt).sendMessagePromise(x.getPeerInfo,Yg.toBinary({peerId:t}));return Cn.fromBinary(e.payload)}}Lt=new WeakMap;class vO{constructor(t,e){g(this,We,void 0);g(this,_c,void 0);f(this,We,e),f(this,_c,t)}get logger(){return a(this,_c).getValue("logger")}addPlugin(t,e){a(this,We).sendMessage(j.addPlugin,fA.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,We).sendMessage(j.removePlugin,vA.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,We).sendMessagePromise(j.getPlugins);return t?FA.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,We).sendMessage(j.customPluginEventToRoom,CA.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,We).sendMessage(j.customPluginEventToPeers,AA.toBinary(n),i)}enablePluginForRoom(t,e){a(this,We).sendMessage(j.enablePluginForRoom,yA.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,We).sendMessage(j.enablePluginForPeers,PA.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,We).sendMessage(j.disablePluginForRoom,bA.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,We).sendMessage(j.disablePluginForPeers,kA.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,We).sendMessage(j.storeInsertKeys,of.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,We).sendMessage(j.storeGetKeys,NA.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,We).sendMessage(j.storeDeleteKeys,LA.toBinary(n),i)}storeDelete(t,e,r){a(this,We).sendMessage(j.storeDelete,UA.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,We).sendMessage(j.storeInsertKeys,of.toBinary(i))}on(t,e){let r;switch(t){case j.addPlugin:case j.enablePluginForPeers:case j.enablePluginForRoom:{r=oh.fromBinary.bind(oh);break}case j.removePlugin:case j.disablePluginForPeers:case j.disablePluginForRoom:{r=cf.fromBinary.bind(cf);break}case j.customPluginEventToPeers:case j.customPluginEventToRoom:{r=lf.fromBinary.bind(lf);break}case j.storeInsertKeys:case j.storeGetKeys:case j.storeDeleteKeys:case j.storeDelete:{r=df.fromBinary.bind(df);break}}a(this,We).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}We=new WeakMap,_c=new WeakMap;var TO=Object.defineProperty,yO=(s,t,e)=>t in s?TO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,EO=(s,t,e)=>(yO(s,typeof t!="symbol"?t+"":t,e),e),xh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},D=(s,t,e)=>(xh(s,t,"read from private field"),e?e.call(s):t.get(s)),Te=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ie=(s,t,e,r)=>(xh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),be=(s,t,e)=>(xh(s,t,"access private method"),e),el={},bO={get exports(){return el},set exports(s){el=s}},Ln=typeof Reflect=="object"?Reflect:null,aS=Ln&&typeof Ln.apply=="function"?Ln.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},tl;Ln&&typeof Ln.ownKeys=="function"?tl=Ln.ownKeys:Object.getOwnPropertySymbols?tl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:tl=function(s){return Object.getOwnPropertyNames(s)};function wO(s){console&&console.warn&&console.warn(s)}var oS=Number.isNaN||function(s){return s!==s};function ce(){ce.init.call(this)}bO.exports=ce,el.once=RO,ce.EventEmitter=ce,ce.prototype._events=void 0,ce.prototype._eventsCount=0,ce.prototype._maxListeners=void 0;var cS=10;function sl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ce,"defaultMaxListeners",{enumerable:!0,get:function(){return cS},set:function(s){if(typeof s!="number"||s<0||oS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");cS=s}}),ce.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},ce.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||oS(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function dS(s){return s._maxListeners===void 0?ce.defaultMaxListeners:s._maxListeners}ce.prototype.getMaxListeners=function(){return dS(this)},ce.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")aS(c,this,t);else for(var d=c.length,l=mS(c,d),e=0;e<d;++e)aS(l[e],this,t);return!0};function lS(s,t,e,r){var i,n,o;if(sl(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=dS(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,wO(c)}return s}ce.prototype.addListener=function(s,t){return lS(this,s,t,!1)},ce.prototype.on=ce.prototype.addListener,ce.prototype.prependListener=function(s,t){return lS(this,s,t,!0)};function PO(){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 uS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=PO.bind(r);return i.listener=e,r.wrapFn=i,i}ce.prototype.once=function(s,t){return sl(t),this.on(s,uS(this,s,t)),this},ce.prototype.prependOnceListener=function(s,t){return sl(t),this.prependListener(s,uS(this,s,t)),this},ce.prototype.removeListener=function(s,t){var e,r,i,n,o;if(sl(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():_O(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},ce.prototype.off=ce.prototype.removeListener,ce.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function hS(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?kO(i):mS(i,i.length)}ce.prototype.listeners=function(s){return hS(this,s,!0)},ce.prototype.rawListeners=function(s){return hS(this,s,!1)},ce.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):pS.call(s,t)},ce.prototype.listenerCount=pS;function pS(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ce.prototype.eventNames=function(){return this._eventsCount>0?tl(this._events):[]};function mS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function _O(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function kO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function RO(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}gS(s,t,n,{once:!0}),t!=="error"&&CO(s,i,{once:!0})})}function CO(s,t,e){typeof s.on=="function"&&gS(s,"error",t,e)}function gS(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class IO extends v{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 fS=new IO;class SS{static encode(t){return fS.toBinary(t)}static decode(t){return fS.fromBinary(new Uint8Array(t))}}function AO(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Hr;class MO{constructor(t={}){EO(this,"opts"),Te(this,Hr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Hr,0)}async wait(){ie(this,Hr,D(this,Hr)+1);const t=AO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**D(this,Hr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return D(this,Hr)}reset(){ie(this,Hr,0)}}Hr=new WeakMap;const qr={debug:0,info:1,warn:2,error:3};var Ci,Ii;class DO{constructor(t){Te(this,Ci,void 0),Te(this,Ii,void 0),ie(this,Ci,console),ie(this,Ii,t)}debug(...t){qr[D(this,Ii)]>qr.debug||D(this,Ci).debug("[Sockrates]:",...t)}info(...t){qr[D(this,Ii)]>qr.info||D(this,Ci).info("[Sockrates]:",...t)}warn(...t){qr[D(this,Ii)]>qr.warn||D(this,Ci).warn("[Sockrates]:",...t)}error(...t){qr[D(this,Ii)]>qr.error||D(this,Ci).error("[Sockrates]:",...t)}}Ci=new WeakMap,Ii=new WeakMap;var vS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(vS||{});const OO="2",NO="3";var De,xn,we,xe,jr,Ye,or,Gr,bs,Un,cr,Uh,TS,To,rl,$h,yS,Bh,ES,il,Fh,Hh,bS,yo,nl,Eo,al,ol,qh,$n,bo,wo,cl;class VO{constructor(t,e){var m,S,y,w,P,C,O,$,L,F;Te(this,Uh),Te(this,To),Te(this,$h),Te(this,Bh),Te(this,il),Te(this,Hh),Te(this,yo),Te(this,Eo),Te(this,ol),Te(this,$n),Te(this,wo),Te(this,De,void 0),Te(this,xn,void 0),Te(this,we,void 0),Te(this,xe,void 0),Te(this,jr,void 0),Te(this,Ye,void 0),Te(this,or,void 0),Te(this,Gr,void 0),Te(this,bs,void 0),Te(this,Un,void 0),Te(this,cr,void 0);var r,i,n,o,c,d,l,u,h;ie(this,xn,t),ie(this,jr,[]),ie(this,Ye,new el),ie(this,or,!0),ie(this,bs,!1),ie(this,we,e!=null?e:{}),(m=(r=D(this,we)).autoReconnect)!=null||(r.autoReconnect=!0),(S=(i=D(this,we)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(y=(n=D(this,we)).pingTimeout)!=null||(n.pingTimeout=3e4),(w=(o=D(this,we)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(P=(c=D(this,we)).debug)!=null||(c.debug=!0),(C=(d=D(this,we)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(O=(l=D(this,we)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),($=(u=D(this,we)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(L=(h=D(this,we)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ie(this,Gr,{code:void 0,reason:void 0}),ie(this,xe,(F=D(this,we).logger)!=null?F:new DO(D(this,we).debug?"debug":"info")),ie(this,cr,new MO)}get readyState(){var t;return(t=D(this,De))==null?void 0:t.readyState}get url(){return D(this,xn)}updateURL(t){ie(this,xn,t),be(this,Hh,bS).call(this)}get config(){return D(this,we)}get sendQueue(){return D(this,jr)}flush(){if(!D(this,we).queueOnDisconnect)return!1;const t=[];return D(this,jr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,jr,t),D(this,jr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){D(this,xe).debug("Websocket was already connecting or connected.");return}if(D(this,or)!==!1)return new Promise((e,r)=>{be(this,$n,bo).call(this),be(this,wo,cl).call(this);try{ie(this,De,new WebSocket(be(this,Uh,TS).call(this,D(this,xn)))),D(this,De).binaryType="arraybuffer",D(this,xe).debug("Connecting");const i=setTimeout(()=>{D(this,xe).debug("Connection timeout. Closing socket"),ie(this,or,!0),be(this,wo,cl).call(this),D(this,De).close(3001,"Connection Timeout"),D(this,we).autoReconnect&&!D(this,bs)&&(D(this,Ye).emit("reconnecting"),be(this,yo,nl).call(this)),r(new Error("Connection timed out!"))},D(this,we).connectionTimeout);D(this,De).onopen=()=>{D(this,xe).debug(`Ready State: ${vS[D(this,De).readyState]}`),i&&clearTimeout(i),be(this,ol,qh).call(this),ie(this,Gr,{code:void 0,reason:void 0}),D(this,Ye).emit("connected"),D(this,we).flushOnReconnect&&this.flush(),e()},D(this,De).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),D(this,xe).debug("Socket closed. Close event:",{event:n}),D(this,xe).debug(`Connection closed code: ${o}`),D(this,xe).debug(`Connection closed reason: ${c}`),D(this,bs)||be(this,il,Fh).call(this,o,c)}catch(o){be(this,To,rl).call(this,o)}},D(this,De).onerror=n=>{be(this,To,rl).call(this,n)},D(this,De).onmessage=n=>be(this,$h,yS).call(this,n)}catch(i){be(this,To,rl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(D(this,we).queueOnDisconnect&&(!D(this,De)||D(this,De).readyState!==1))return D(this,xe).debug("Queuing message since socket is not connected!",n),D(this,jr).push(n),!1;const o=SS.encode(n);return be(this,Eo,al).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return be(this,Eo,al).call(this,t)}receive(t,e){return D(this,Ye).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){D(this,Ye).on(t,e);return}this.receive(t,e)}removeAllListeners(){D(this,Ye).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){D(this,Ye).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){D(this,Ye).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,or,!1),be(this,$n,bo).call(this),this.removeAllListeners(),ie(this,Gr,{code:1e3,reason:"Sockrates disconnect method called"}),D(this,De).close(1e3,"Sockrates disconnect method called.")}}De=new WeakMap,xn=new WeakMap,we=new WeakMap,xe=new WeakMap,jr=new WeakMap,Ye=new WeakMap,or=new WeakMap,Gr=new WeakMap,bs=new WeakMap,Un=new WeakMap,cr=new WeakMap,Uh=new WeakSet,TS=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},To=new WeakSet,rl=function(s,t){D(this,xe).error("Error:",{error:s}),D(this,Ye).emit("errored",{error:s}),t==null||t(s)},$h=new WeakSet,yS=function(s){if(be(this,ol,qh).call(this),s.data===OO){D(this,xe).debug("Received ping from server"),be(this,Eo,al).call(this,NO);return}const t=SS.decode(s.data),{id:e,payload:r}=t;D(this,xe).debug("Received message",{event:t.event,messageID:e}),D(this,Ye).emit(t.event.toString(),{id:e,payload:r})},Bh=new WeakSet,ES=function(){return D(this,De).readyState===1},il=new WeakSet,Fh=function(s,t){ie(this,Gr,{reason:t,code:s}),D(this,Ye).emit("disconnected",{code:s,reason:t})},Hh=new WeakSet,bS=function(){const{reason:s,code:t}=D(this,Gr);t&&t!==1e3&&D(this,or)&&D(this,we).autoReconnect&&!D(this,bs)&&(D(this,xe).debug(`Triggering reconnection due to ${s}.`),D(this,Ye).emit("reconnecting"),be(this,yo,nl).call(this))},yo=new WeakSet,nl=async function(s=!0){if(s&&D(this,bs)){D(this,xe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(D(this,bs)||D(this,cr).reset(),D(this,we).maxReconnectionAttempts!==null&&D(this,cr).getAttempts()>=D(this,we).maxReconnectionAttempts){D(this,Ye).emit("failed"),ie(this,bs,!1);return}ie(this,bs,!0),be(this,wo,cl).call(this),be(this,$n,bo).call(this);try{if(await D(this,cr).wait(),D(this,or)===!1)return;if(D(this,xe).debug(`Reconnection attempt ${D(this,cr).getAttempts()}`),D(this,Ye).emit("reconnectAttempt",{attempt:D(this,cr).getAttempts()}),await this.connect(),!be(this,Bh,ES).call(this))throw Error("Reconnect Failed");ie(this,bs,!1),ie(this,Gr,{code:void 0,reason:void 0}),D(this,Ye).emit("reconnected")}catch(t){D(this,xe).debug("Failed to reconnect."),D(this,Ye).emit("reconnectFailure",{attempt:D(this,cr).getAttempts()}),be(this,yo,nl).call(this,!1)}},Eo=new WeakSet,al=function(s){try{return D(this,De).send(s),!0}catch(t){return D(this,xe).error(t.message),!1}},ol=new WeakSet,qh=function(){this.config.disconnectOnPingTimeout&&(D(this,xe).debug("Resetting ping timeout"),be(this,$n,bo).call(this),ie(this,Un,setTimeout(()=>{var s;D(this,xe).debug("Disconnecting the socket due to ping timeout"),ie(this,or,!0);const t=3002,e="Ping timeout";(s=D(this,De))==null||s.close(t,e),be(this,il,Fh).call(this,t,e)},D(this,we).pingTimeout)))},$n=new WeakSet,bo=function(){D(this,Un)&&(clearTimeout(D(this,Un)),ie(this,Un,void 0))},wo=new WeakSet,cl=function(){D(this,De)&&(D(this,De).onopen=void 0,D(this,De).onerror=void 0,D(this,De).onmessage=void 0,D(this,De).onclose=void 0)};var LO=Object.defineProperty,xO=Object.getOwnPropertyDescriptor,dl=(s,t,e,r)=>{for(var i=r>1?void 0:r?xO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&LO(t,e,i),i};const wS=65535,UO=3e3,PS=(WS=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Ie);g(this,kc);g(this,Rc);g(this,di,void 0);g(this,Ce,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");g(this,hs,void 0);g(this,rt,void 0);var n;if(!t||!e||!r)throw new k("peerId, meetingId, or authToken can not be empty","0404");f(this,hs,void 0),f(this,rt,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,di,U(this,kc,lp).call(this,t)),f(this,Ce,new VO(a(this,di),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Ie,He).socketJoinAttempted}set joinAttempted(s){a(this,Ie,He).socketJoinAttempted=s}get telemetry(){return a(this,rt).getValue("telemetry")}get logger(){return a(this,rt).getValue("logger")}get peerId(){return a(this,rt).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,di,U(this,kc,lp).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ce).updateURL(a(this,di))}static getSocketEdgeDomain(s){return kn({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,di)}async connect(){a(this,Ie,He).socketJoinAttempted=!0,await a(this,Ce).connect(),a(this,Ie,He).socketJoinAttempted=!0,a(this,Ie,He).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Ie,He).socketJoinAttempted=!1,a(this,Ce).disconnect(),a(this,Ie,He).socketJoinAttempted=!0,a(this,Ie,He).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ce).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,rt).getValue("telemetry").injectContext(r),a(this,Ce).send(s,e!=null?e:U(this,Rc,up).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const n=i!=null?i:s;return new Promise((o,c)=>{const d=(y,w)=>{a(this,Ce).removeListener(n,y),a(this,Ce).removeListener(wS,w),a(this,Ce).removeListener(Vr.errorResponse,w),a(this,Ce).removeListener(vs.errorResponse,w)},l=r!=null?r:U(this,Rc,up).call(this),u={};a(this,rt).getValue("telemetry").injectContext(u);const m=({id:y,payload:w})=>{if(l===y){let P;try{const C=xR.fromBinary(w);P=new Error(C.errorMessage)}catch(C){P=new Error("failed to parse error message",{cause:C});try{const O=UC.fromBinary(w);P=new Error(O.message)}catch(O){P=new Error("failed to parse error message",{cause:O})}}c(P),d(S,m)}},S=({id:y,payload:w})=>{l===y&&(o({id:y,payload:w}),d(S,m))};a(this,Ce).on(n,S),a(this,Ce).on(wS,m),a(this,Ce).on(Vr.errorResponse,m),a(this,Ce).on(vs.errorResponse,m),setTimeout(()=>{d(S,m),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ce).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Ce).on(s,t)}onStateEvent(s,t){a(this,Ce).on(s,t)}removeListener(s,t){a(this,Ce).removeListener(s,t)}removeListeners(s){a(this,Ce).removeListeners(s)}flush(){return a(this,Ce).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,hs)&&(clearTimeout(a(this,hs)),f(this,hs,void 0)),a(this,Ie,He).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}});const{recv:e,send:r}=(i=a(this,Ie,He).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Vn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Vn.CONNECTED?a(this,rt).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ie,He).joinAttempted}):f(this,hs,setTimeout(()=>{a(this,rt).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ie,He).joinAttempted}),f(this,hs,void 0)},UO)),a(this,Ie,He).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),a(this,Ie,He).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Ie,He).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Ie,He).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Ie,He).mediaJoinAttempted}}),a(this,hs)&&(clearTimeout(a(this,hs)),f(this,hs,void 0)),a(this,rt).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Ie,He).mediaJoinAttempted}),a(this,Ie,He).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),a(this,rt).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_FAILED),a(this,Ie,He).updateSocketConnectionState("failed")})}},di=new WeakMap,Ce=new WeakMap,Ie=new WeakSet,He=function(){return a(this,rt).getValue("connectionHandler")},hs=new WeakMap,rt=new WeakMap,kc=new WeakSet,lp=function(s){const t=a(this,rt).getValue("socketBaseURI")||a(this,rt).getValue("baseURI");let e=PS.getSocketEdgeDomain(t);typeof _n(a(this,rt),"socket_server_base")=="string"&&(e=_n(a(this,rt),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),n=this.peerId,o={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n!==s&&{oldPeerID:n},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(c=>Id[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},Rc=new WeakSet,up=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},WS);let Po=PS;dl([E.trace("SocketService.connect")],Po.prototype,"connect",1),dl([E.trace("SocketService.disconnect")],Po.prototype,"disconnect",1),dl([E.trace("SocketService.sendMessagePromise")],Po.prototype,"sendMessagePromise",1),dl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Po.prototype,"sendMessagePromiseWithTimeout",1);class $O{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=u0.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=x0.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Zg.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Xg.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return R0.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(x.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(x.createConnectedRooms,g0.toBinary({payloads:t}));return Xg.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(x.deleteConnectedRooms,_0.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(x.movePeers,O0.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}}}}var BO=Object.defineProperty,FO=Object.getOwnPropertyDescriptor,HO=(s,t,e,r)=>{for(var i=r>1?void 0:r?FO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&BO(t,e,i),i};class _S extends Ut{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);g(this,Ms,void 0);f(this,Ms,e)}get supportsConnectedMeetings(){return a(this,Ms).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
18
18
  Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await a(this,Ms).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,Ms).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,Ms).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await a(this,Ms).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Ms).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,Ms).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>n.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}Ms=new WeakMap,HO([It({maxInvocations:60,period:60})],_S.prototype,"getConnectedMeetings",1);var qO=Object.defineProperty,jO=Object.getOwnPropertyDescriptor,jh=(s,t,e,r)=>{for(var i=r>1?void 0:r?jO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&qO(t,e,i),i};const kS=(JS=class{constructor(s){p(this,"connectedMeetings");g(this,ge,void 0);f(this,ge,s),this.connectedMeetings=new _S(s)}get telemetry(){return a(this,ge).getValue("telemetry")}get logger(){return a(this,ge).getValue("logger")}static init(s){const t=new kS(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on(x.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on(x.transferPeer,this.handleTransferPeer.bind(this)),a(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on(x.movedPeer,this.handleMovedPeer.bind(this)),a(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,ge).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,ge).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,n,o,c;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
19
19
  Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,ge).getValue("self").videoEnabled,audio:a(this,ge).getValue("self").audioEnabled};try{a(this,ge).getValue("self").cleanupEvents(),await a(this,ge).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,ge).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await CS.init({...a(this,ge).getValue("options"),cachedUserDetails:null,defaults:{...a(this,ge).getValue("options").defaults,...e,mediaHandler:a(this,ge).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,ge).getValue("self");r.self.setName(a(this,ge).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,ge).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,ge).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,ge).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,ge).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},ge=new WeakMap,JS);let ll=kS;jh([E.trace("ConnectedMeetingsController.getConnectedMeetings")],ll.prototype,"getConnectedMeetings",1),jh([E.trace("ConnectedMeetingsController.setupEvents")],ll.prototype,"setupEvents",1),jh([E.trace("ConnectedMeetingsController.switchMeeting")],ll.prototype,"switchMeeting",1);var GO=Object.defineProperty,WO=Object.getOwnPropertyDescriptor,Gh=(s,t,e,r)=>{for(var i=r>1?void 0:r?WO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&GO(t,e,i),i};const _o=class{constructor(s,t,e){p(this,"apiBase");p(this,"selfController");p(this,"pollController");p(this,"chatController");p(this,"metaController");p(this,"storesManager");p(this,"stageController");p(this,"pluginController");p(this,"internalsController");p(this,"recordingController");p(this,"livestreamController");p(this,"participantController");p(this,"connectedMeetingsController");p(this,"telemetry");p(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var L,F,Q;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(rS(s),fe.isSupported()===!1)throw new k("Browser not supported","0010",c,!0);const d=BM(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new E1(s);s.setValue("connectionHandler",l);let u="",h="",m=null;c.info("CF SFU is being used.");try{m=await d.getUserDetails(),u=((L=m.meeting)==null?void 0:L.title)||"",h=((F=m.socket)==null?void 0:F.baseUri)||s.getValue("baseURI"),s.setValue("presetName",m.preset.name),s.setValue("socketBaseURI",h),c.info(`Socket Base URI ${h} is being used`)}catch(X){throw c.error("Failed to get user details",{error:X}),X instanceof uh?X.status===401?new k("Unauthorized. The auth token may be invalid or expired. (401)","0004"):X.status===403?new k("Access denied. Insufficient permissions to join the meeting. (403)","0004"):X.status===404?new k("The auth token is not associated with an active participant in this meeting. The meeting may have ended, or the participant may no longer exist. (404)","0004"):X.status>=500?new k(`The server encountered an error. Try again. (${X.status})`,"0001"):X.isHttpError?new k(`Request rejected by the server. (${X.status})`,"0001"):X.isTimeout?new k("Connection timed out. Check the network and try again.","0001"):new k("Unable to connect to the server. Check the internet connection.","0001"):new k((X==null?void 0:X.message)||"Failed to initialize.","0001")}const S=_o.createSocketService(s),y=S.connect(),w=d.getPlugins();try{await y}catch(X){c.error("[Controller]: Failed to connect to socket server:",{error:X})}const P=wh.init(m.preset,!s.getValue("modules").theme);s.setValue("theme",P);const C=_h.init(s,P.viewType,m.preset.permissions),O=_o.setupControllers(S,s,m,w,u,P,C);l1(P)&&((Q=_o.createRoomNodeClient(s,S).initializeConnection(m.participant.name,i,!1,C))==null||Q.catch(it=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:it})}));const{controllers:$}=await O;return G_(),new _o(e,$,s)}static async setupControllers(s,t,e,r,i,n,o){var V,R,je;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),u=t.getValue("logger"),{viewType:h,mediaConstraints:{audio:m}}=n;t.setValue("viewType",h),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(V=m.enableHighBitrate)!=null?V:!1,enableStereo:(R=m.enableStereo)!=null?R:!1}},...l}),t.setValue("maxPreferredStreams",fe.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let S,y,w,P,C,O,$,L,F;const Q=new uO(t,s),X=new $O(s);t.setValue("connectedMeetingsSocketHandler",X);const it=new Zd(t,s),Ds=new rr(t,s),Sn=new SO(s),Os=new nS(t,s),I=new vO(t,s),T=new lO(s),b=await Fr.init(t,Os,d,o,n);t.setValue("selfController",b);const B=await Pf.init(t,b.self,Os,Q,i);if(c.participant&&(L=new ar(t,b.self,Os)),(je=c.e2ee)!=null&&je.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(y=await ts.init(t,Ds,b.self,L.participants)),c.internals&&(C=await vh.init(t)),c.livestream&&n.viewType===Qs.Livestream&&($=new jf(t,b.self,T)),c.poll&&(S=await yf.init(t,b.self,it)),c.recording&&(O=new If(t,b.self,Os)),c.stage&&(w=new _f(t,Sn,Os,b.self,L.participants)),c.plugin){if(!L)throw new k("The plugin module cannot be initialized without the `participant` module","0102");const Cr=await r;P=await lo.init(t,Cr,I,Ds,y==null?void 0:y.chat,b.self,L.participants,i)}if(c.connectedMeetings&&(F=await ll.init(t)),c.pip){const Cr=await Bu._init(t,b.self);t.setValue("pip",Cr)}const Fe={storesManager:new TD(t,I),pollController:S,selfController:b,metaController:B,chatController:y,stageController:w,pluginController:P,recordingController:O,internalsController:C,livestreamController:$,participantController:L,connectedMeetingsController:F};return{theme:n,permissions:o,controllers:Fe}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return sS(s,{socket:t,peerId:e})}static createSocketService(s){var d;const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),o=((d=s.getValue("socketBaseURI"))!=null?d:"").includes("realtime.cloudflare.com")?[]:["PING"];return s.getValue("logger").info(`Socket service capabilities: ${JSON.stringify(o)}`),new Po(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let ul=_o;Gh([E.trace("Controller.init")],ul,"init",1),Gh([E.trace("Controller.createRoomNodeClient")],ul,"createRoomNodeClient",1),Gh([E.trace("Controller.createSocketService")],ul,"createSocketService",1);class JO{constructor(){p(this,"battery");p(this,"logger");p(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});p(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});p(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const RS=new JO;function KO(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.realtime.cloudflare.com/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let n=Si.baseURI.prod;t&&(n=t);const o=`https://${kn({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new k("Invalid auth token","0004")}}class zO{constructor(){g(this,nu);g(this,li,new Audio);g(this,pn,new MediaStream);g(this,mn,new Map);g(this,Cc,void 0);a(this,li).srcObject=a(this,pn),a(this,li).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,mn).has(e.id)||(a(this,pn).addTrack(e),a(this,mn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,li).setSinkId(t)}removeTrack(t){const e=a(this,mn).get(t);e&&(a(this,pn).removeTrack(e),a(this,mn).delete(t))}async play(){return a(this,li).srcObject=a(this,pn),a(this,li).play().catch(t=>{U(this,nu,Av).call(this,t)})}onError(t){f(this,Cc,t)}}li=new WeakMap,pn=new WeakMap,mn=new WeakMap,Cc=new WeakMap,nu=new WeakSet,Av=function(t){var e;(e=a(this,Cc))==null||e.call(this,t)};class YO extends zO{constructor(){super();g(this,gn,void 0);f(this,gn,new Map)}addParticipantTrack(e,r){a(this,gn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,gn).get(e);r&&this.removeTrack(r),a(this,gn).delete(e)}}gn=new WeakMap;var QO=Object.defineProperty,XO=Object.getOwnPropertyDescriptor,hl=(s,t,e,r)=>{for(var i=r>1?void 0:r?XO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&QO(t,e,i),i};let Wr=(KS=class{constructor(t,e){g(this,Je,void 0);g(this,fn,void 0);f(this,fn,t),f(this,Je,e)}get peerId(){return a(this,fn).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:Tn(),n=Dr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new Jf(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var m,S,y,w,P,C,O,$,L;fe.init();const e=(S=(m=t==null?void 0:t.cachedUserDetails)==null?void 0:m.peerId)!=null?S:Tn(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=KO(r,i);if((y=o.baseURI)!=null&&y.includes("dyte.io"))throw new k("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Wr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");Nv(l),RS.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(P=(w=t.modules)==null?void 0:w.tracing)!=null?P:!0,(O=(C=t==null?void 0:t.modules)==null?void 0:C.devTools)==null?void 0:O.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${($=t.authToken)==null?void 0:$.slice(0,10)}...
20
- ${(L=t.authToken)==null?void 0:L.slice(-10)}`}});const u=await ul.init(c),h=new Wr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=Dr.createContext(t,e),o={...b_,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",w_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Us(e.cachedUserDetails)),n.setValue("sdkVersion","1.5.0-staging.5"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new YO),n}async join(){const{selfController:t}=a(this,Je);return t.self.roomJoined?null:t.joinRoom()}async leave(t){RS.cleanup(),a(this,fn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Je);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Je).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Je).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Je).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Je).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Je).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Je).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Je).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Je).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Je).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Je).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Je).stageController)==null?void 0:t.stage}get stores(){return a(this,Je).storesManager}get audio(){return a(this,fn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Je).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Je=new WeakMap,fn=new WeakMap,KS);hl([ct("0002"),ir.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Wr.prototype,"join",1),hl([ct("0003")],Wr.prototype,"leave",1),hl([ct("0001"),ir.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Wr,"init",1),Wr=hl([ct("0000")],Wr);const CS=Wr;return CS}();
20
+ ${(L=t.authToken)==null?void 0:L.slice(-10)}`}});const u=await ul.init(c),h=new Wr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=Dr.createContext(t,e),o={...b_,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",w_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Us(e.cachedUserDetails)),n.setValue("sdkVersion","1.5.0-staging.8"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new YO),n}async join(){const{selfController:t}=a(this,Je);return t.self.roomJoined?null:t.joinRoom()}async leave(t){RS.cleanup(),a(this,fn).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Je);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Je).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Je).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Je).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Je).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Je).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Je).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Je).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Je).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Je).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Je).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Je).stageController)==null?void 0:t.stage}get stores(){return a(this,Je).storesManager}get audio(){return a(this,fn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Je).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Je=new WeakMap,fn=new WeakMap,KS);hl([ct("0002"),ir.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Wr.prototype,"join",1),hl([ct("0003")],Wr.prototype,"leave",1),hl([ct("0001"),ir.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Wr,"init",1),Wr=hl([ct("0000")],Wr);const CS=Wr;return CS}();
@@ -1,5 +1,5 @@
1
1
  Name: @cloudflare/realtimekit
2
- Version: 1.5.0-staging.4
2
+ Version: 1.5.0-staging.8
3
3
  License: Apache-2.0
4
4
  Private: false
5
5
  Description: A real-time video and audio SDK for building custom, collaborative communication experiences.
package/dist/index.cjs.js CHANGED
@@ -9,4 +9,4 @@ ${this.message}`;try{let d=n&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("Cli
9
9
  `}this.midTransceiverMap.set(o.mid,o);const d=l=>u(this,null,function*(){return this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(l)}]`),yield this.pc.setRemoteDescription(l),o.mid});return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(c,void 0,2)}]`),{offerSdp:c,callback:d,sender:o.sender,mid:o.mid}})}addCustomEventListeners(){this.pc.addEventListener("datachannel",t=>{const{channel:e}=t;e.onmessage=r=>{this.safeEmit("datachannel",t.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}class pd extends Ph{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new pd(e,r)}get name(){return"Firefox60"}send(o){return u(this,arguments,function*({track:e,encodings:r,codecOptions:i,screenShare:n}){this._assertSendDirection();const c=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},d=this.pc.addTransceiver(e,O({direction:"sendonly",streams:[n?this._sendScreenShareStream:this._sendWebStream]},c));if(!this.supportsSendEncodings&&r){r.reverse();const T=d.sender.getParameters();T.encodings=r,yield d.sender.setParameters(T)}const l=(T,v)=>{var V;const E=as.parse(T),w=E.media[E.media.length-1],b=w.rtp.filter(H=>v.some(j=>j.name===H.codec)),M=w.fmtp.filter(H=>b.some(j=>j.payload===H.payload)),D=(V=w.rtcpFb)==null?void 0:V.filter(H=>b.some(j=>j.payload===H.payload)),$=b.map(H=>H.payload);return E.media[E.media.length-1].rtp=b,E.media[E.media.length-1].fmtp=M,E.media[E.media.length-1].rtcpFb=D,E.media[E.media.length-1].payloads=$.join(" "),as.write(E)},h=yield this.pc.createOffer();if(h.sdp=l(h.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(h)}]`),yield this.pc.setLocalDescription(h),e==="audio"||e.kind==="audio"){const{enableDtx:T,enableStereo:v}=this,E=this.enableHighBitrate?v?128e3:64e3:v?64e3:32e3;h.sdp=h.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${T?"usedtx=1;":""}${v?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${E}`)}return this.midTransceiverMap.set(d.mid,d),{offerSdp:h,callback:T=>u(this,null,function*(){return this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(T)}]`),yield this.pc.setRemoteDescription(T),d.mid}),sender:d.sender,mid:d.mid}})}setMaxSpatialLayer(e,r){return u(this,null,function*(){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters(),o=n.encodings.length-1-r;n.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),yield i.sender.setParameters(n)})}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=i=>u(this,null,function*(){const n=yield i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n)))})})}}class _h extends Ph{static createFactory(t){return()=>new _h(t)}get name(){return"Safari12"}send(n){return u(this,arguments,function*({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const o=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),c=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(c)}`);const d=[];r&&r.length>0&&r.forEach(g=>{var v;const T=c.codecs.find(E=>E.mimeType.includes(g.name));if(g.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(g.parameters)}`);const E=((v=T.sdpFmtpLine)==null?void 0:v.split(";"))||[];E.push(...g.parameters);const w=[...new Set(E).values()];T.sdpFmtpLine=w.join(";")}d.push(T)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(d)}`),o.setCodecPreferences(d);const l=yield this.pc.createOffer();if(yield this.pc.setLocalDescription(l),t==="audio"||t.kind==="audio"){const{enableStereo:g,enableDtx:T}=this,v=this.enableHighBitrate?g?128e3:64e3:g?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${T?"usedtx=1;":""}${g?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${v}`)}return this.midTransceiverMap.set(o.mid,o),{offerSdp:l,callback:g=>u(this,null,function*(){return this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(g)}]`),yield this.pc.setRemoteDescription(g),o.mid}),sender:o.sender,mid:o.mid}})}addCustomEventListeners(){this.pc.ondatachannel=t=>{const{channel:e}=t;e.onmessage=r=>u(this,null,function*(){const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",t.channel,i)})}}}function cD(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}var Fo,Ci,Cs,Dd,Rs,vr,qo,Au,Od,Lf,Nd,Vf;class dD extends Il{constructor(e,r){var i;super(e);m(this,Rs);m(this,qo);m(this,Od);m(this,Nd);p(this,"rtpReceiver");p(this,"id");p(this,"localId");p(this,"producerId");p(this,"producingTransportId");p(this,"mimeType");p(this,"track");p(this,"peerId");p(this,"appData");p(this,"transceiver");m(this,Fo,void 0);m(this,Ci,void 0);m(this,Cs,void 0);m(this,Dd,void 0);this.id=r.id,this.localId=r.localId,f(this,Fo,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Cs,!1),this.producerId=r.producerId,this.track=r.track,f(this,Ci,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,x(this,Od,Lf).call(this),f(this,Dd,e)}get closed(){return a(this,Cs)}get kind(){return this.track.kind}get paused(){return a(this,Ci)}close(e,r){a(this,Cs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,Rs,vr)),f(this,Cs,!0),r&&(x(this,Nd,Vf).call(this),this.transceiver.stop()),this.safeEmit("close",e))}getStats(){return u(this,null,function*(){if(a(this,Cs))throw new bt("closed");return a(this,Fo).getReceiverStats(this.localId)})}pause(){if(this.logger.debug("consumer::pause()",a(this,Rs,vr)),a(this,Cs)){this.logger.error("consumer::pause() | Consumer closed",a(this,Rs,vr));return}f(this,Ci,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,Rs,vr)),a(this,Cs)){this.logger.error("Consumer::resume() | Consumer closed",a(this,Rs,vr));return}f(this,Ci,!1),this.track.enabled=!0,this.safeEmit("resume")}}Fo=new WeakMap,Ci=new WeakMap,Cs=new WeakMap,Dd=new WeakMap,Rs=new WeakSet,vr=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},qo=new WeakSet,Au=function(){this.logger.debug('Consumer::track "ended" event',a(this,Rs,vr)),this.safeEmit("trackended")},Od=new WeakSet,Lf=function(){this.track.addEventListener("ended",x(this,qo,Au).bind(this))},Nd=new WeakSet,Vf=function(){try{this.track.removeEventListener("ended",x(this,qo,Au)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",G(O({},a(this,Rs,vr)),{error:e}))}};var us,ra,ia,Ri,Yt,Qe,Lr,na,Ld,Ot,ns;class lD extends Il{constructor(e,r){var i,n;super(e);m(this,Ot);p(this,"id");p(this,"localId");m(this,us,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");m(this,ra,void 0);m(this,ia,void 0);m(this,Ri,void 0);m(this,Yt,!1);m(this,Qe,void 0);m(this,Lr,void 0);m(this,na,void 0);m(this,Ld,void 0);this.id=r.id,this.localId=r.localId,f(this,Qe,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,Lr,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,na,void 0),f(this,ra,r.stopTracks),f(this,ia,r.disableTrackOnPause),f(this,Ri,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,us,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,Ld,e)}get closed(){return a(this,Yt)}get track(){return a(this,Qe)}get paused(){return a(this,Lr)}get maxSpatialLayer(){return a(this,na)}close(e){return u(this,null,function*(){if(a(this,Yt))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Ot,ns)),f(this,Yt,!0),this._destroyTrack(),e===gd){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=yield a(this,us).stopSending(this.localId),{answer:n}=yield this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)})}getStats(){return u(this,null,function*(){if(a(this,Yt))throw new bt("closed");return a(this,us).getSenderStats(this.localId)})}pause(){this.logger.debug("Producer::pause()",a(this,Ot,ns)),a(this,Yt)&&this.logger.error("Producer::pause() | Producer closed",a(this,Ot,ns)),f(this,Lr,!0),a(this,Qe)&&a(this,ia)&&(a(this,Qe).enabled=!1),a(this,Ri)&&a(this,us).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Ot,ns)),a(this,Yt)){this.logger.error("Producer::resume() | Producer closed",a(this,Ot,ns));return}f(this,Lr,!1),a(this,Qe)&&a(this,ia)&&(a(this,Qe).enabled=!0),a(this,Ri)&&a(this,us).replaceTrack(this.localId,a(this,Qe)),this.emit("resume")}replaceTrack(r){return u(this,arguments,function*({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Ot,ns)),a(this,Yt)){if(e&&a(this,ra))try{e.stop()}catch(i){this.logger.error("Producer::replaceTrack",G(O({},a(this,Ot,ns)),{error:i}))}throw new bt("closed")}else if(e&&e.readyState==="ended")throw new bt("track ended");if(e===a(this,Qe)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Ot,ns));return}(!a(this,Ri)||!a(this,Lr))&&(yield a(this,us).replaceTrack(this.localId,e)),this._destroyTrack(),f(this,Qe,e),this._handleTrack()})}setMaxSpatialLayer(e){return u(this,null,function*(){if(a(this,Yt))throw new bt("closed");if(this.kind!=="video")throw new To("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");yield a(this,us).setMaxSpatialLayer(this.localId,e),f(this,na,e)})}setRtpEncodingParameters(e){return u(this,null,function*(){if(a(this,Yt))throw new bt("closed");if(typeof e!="object")throw new TypeError("invalid params");yield a(this,us).setRtpEncodingParameters(this.localId,e)})}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Ot,ns)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,Qe)&&a(this,Qe).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,Qe))try{a(this,Qe).removeEventListener("ended",this._onTrackEnded),a(this,ra)&&a(this,Qe).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,G(O({},a(this,Ot,ns)),{error:r}))}}}us=new WeakMap,ra=new WeakMap,ia=new WeakMap,Ri=new WeakMap,Yt=new WeakMap,Qe=new WeakMap,Lr=new WeakMap,na=new WeakMap,Ld=new WeakMap,Ot=new WeakSet,ns=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function xf(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Zl(s){return Math.random().toString(36).substring(2,2+s)}const Fc=1;function Zp(s){const t=s;return delete t.payload._bolt,t}function uD(s){return s.payload&&xf(s.payload)}function hD(s){var t,e;return uD(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}var Vr,Vd,ki;const pn=class extends nt.EventEmitter{constructor(e,r,i,n){super();p(this,"channel");p(this,"queue");p(this,"serverProtocolVersion");m(this,Vr,new Map);m(this,Vd,void 0);m(this,ki,void 0);p(this,"respond",(e,r,i=!1)=>{let n;i?n=pn.createErrorResponse(e,r):n=pn.createResponse(e,r),this.channel.send(JSON.stringify(n))});p(this,"notify",e=>{const r=pn.createNotification(e);this.channel.send(JSON.stringify(r))});p(this,"request",e=>u(this,null,function*(){const r=pn.createRequest(e),i=new Promise((n,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:h=>{this.queue.delete(d)&&(clearTimeout(l.timer),n(h))},timer:setTimeout(()=>{this.queue.delete(d)&&o(new Error(`request timeout for message id: ${d}`))},2e4),cancel:h=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(h))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),i}));p(this,"send",e=>{const r=JSON.stringify(e),i=16384;if(r.length>i){const n=i-200,o=Math.ceil(r.length/n),c=[];for(let l=0;l<o;l+=1){const h=l*n,g=(l+1)*n;c.push(r.slice(h,g))}const d=Jr.v4();for(let l=0;l<o;l+=1){const h=c[l],T=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:h});a(this,ki).debug(`Sending message chunk over dc: ${T}`),this.channel.send(T)}}else a(this,ki).debug(`Sending message over dc: ${r}`),this.channel.send(r)});p(this,"processMessage",e=>{var i;a(this,Vr).has(e.id)||a(this,Vr).set(e.id,[]);const r=a(this,Vr).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(n=>n===void 0)){const n=a(this,Vr).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,Vr).delete(e.id);const c=JSON.parse(o);if(!c.payload||!xf(c.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:c}});if(this.processBoltHandshake(c))return;if(this.serverProtocolVersion=(i=c.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(c))return c}});p(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,i=this.queue.get(r);return i?(a(this,ki).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(Zp(e)):i.resolve(Zp(e)),!0):!1});p(this,"processBoltHandshake",e=>{var r,i;return e.type==="_bolt"||e.type==="handshake"?(this.respond((i=(r=e.payload._bolt)==null?void 0:r.id)!=null?i:Zl(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,f(this,Vd,e),f(this,ki,e.getValue("logger")),this.channel=r,this.queue=new Map}};let si=pn;Vr=new WeakMap,Vd=new WeakMap,ki=new WeakMap,p(si,"createRequest",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:G(O({},e.payload),{_bolt:{id:Zl(8),type:"REQUEST",version:Fc}})}}),p(si,"createResponse",(e,r)=>{var i;if((i=r.payload)!=null&&i._bolt)throw new Error("rpc fields are internal values");return{type:r.type,payload:G(O({},r.payload),{_bolt:{id:e,type:"RESPONSE",version:Fc}})}}),p(si,"createNotification",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:G(O({},e.payload),{bolt:{id:Zl(8),type:"NOTIFY",version:Fc}})}}),p(si,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:Fc}}}));const gd="transport closed";var Mi;const gn=class extends Il{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:h,config:g}){var w,b,M;super(e);p(this,"awaitQueue");p(this,"observer");p(this,"id");p(this,"serverId");p(this,"direction");p(this,"maxSctpMessageSize");p(this,"handler");p(this,"connectionState","new");p(this,"producers");p(this,"consumers");p(this,"datachannels");p(this,"connected",!1);p(this,"eventsDCReadyPromise");p(this,"eventsDCReadyPromiseResolver");p(this,"eventsDCFailureTimer");p(this,"transportConnectionPromise");p(this,"consumerTrackEvents");p(this,"unknownTracksMap");p(this,"appData");m(this,Mi,void 0);f(this,Mi,e);const T=e.getValue("logger");T.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const v=cD(l,{});delete v.iceServers,delete v.iceTransportPolicy,delete v.bundlePolicy,delete v.rtcpMuxPolicy,delete v.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Iu(T,!0),this.handler=n(),this.handler.enableHighBitrate=(w=g==null?void 0:g.enableHighBitrate)!=null?w:!1,this.handler.enableStereo=(b=g==null?void 0:g.enableStereo)!=null?b:!1,this.handler.enableDtx=(M=g==null?void 0:g.enableDtx)!=null?M:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=h||{};const E=3e4;this.transportConnectionPromise=new Promise(D=>{const $=setTimeout(()=>{T.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),D(!1)},E);this.once("connected",()=>{clearTimeout($),D(!0)}),this.once("disconnect",()=>{clearTimeout($),D(!1)}),this.once("close",()=>{clearTimeout($),D(!1)})}),this.eventsDCReadyPromise=new Promise(D=>{this.eventsDCReadyPromiseResolver=D}),this.handler.on("@connectionstatechange",D=>{D!==this.connectionState&&(this.logger.debug(`connection state changed to ${D}`),this.connectionState=D,D==="connected"&&(this.connected=!0,this.emit("connected")),D==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(D==="failed"||D==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",D))}),this.handler.on("@icecandidate",({candidate:D})=>{this.closed||this.safeEmit("icecandidate",D)}),this.handler.on("dc_open",D=>{let $=this.datachannels.get(D.label);$||($||($=new si(a(this,Mi),D,D.label,this.serverId),this.datachannels.set(D.label,$)),this.eventsDCFailureTimer=setTimeout(()=>{D.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",D.label))},5e3))}),this.handler.on("datachannel",(D,$)=>{D.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const V=this.datachannels.get(D.label);if(!V){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:D.label,message:$}});return}try{const H=JSON.parse($);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:H.id,count:H.count,chunkIndex:H.chunkIndex,chunk:H.chunk,transprtId:this.serverId}});const j=V.processMessage(H);if(!j)return;this.logger.debug(`datachannel message with id:${H.id} on transport:${this.serverId}complete - ${JSON.stringify(j)}`),this.emit(`datachannel:${D.label}`,V.label,j)}catch(H){this.logger.error("error parsing message",{error:H})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(gd).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(gd)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}getStats(){return u(this,null,function*(){if(this.closed)throw new bt("closed");return this.handler.getTransportStats()})}connect(e){return u(this,null,function*(){try{if(yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:r,callback:i}=yield this.handler.connect(),{transportId:n,answer:o}=yield e(r);this.setServerId(n),yield i(o)})),!(yield this.transportConnectionPromise))throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}})}restartIce(){return u(this,null,function*(){if(this.logger.debug("restartIce()"),this.closed)throw new bt("closed");return this.handler.restartIce()})}canProduce(e){return u(this,null,function*(){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new To("not a sending Transport");if(r.readyState==="ended")throw new bt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!(yield this.transportConnectionPromise))throw new br("transport not connected");return!0})}produce(e,r){return u(this,null,function*(){if(!(yield this.canProduce(e)))throw new Error("Cannot produce");const{track:n,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:h=!1,appData:g={}}=e;this.logger.debug(`produce() [track:${n.id}]`);const{producerId:T,localId:v,rtpSender:E}=yield this.awaitQueue.push(()=>u(this,null,function*(){const{offerSdp:w,callback:b,sender:M,mid:D}=yield this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:g==null?void 0:g.screenShare}),{answer:$,producerId:V}=yield r({offer:w,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:G(O({},g||{}),{mid:D}),codecOptions:c,producingTransportId:this.serverId}),H=yield b($);return{producerId:V,localId:H,rtpSender:M}}),"Transport.produce");return this.createProducerObject({id:T,localId:v,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:h,appData:g,handler:this.handler,rtpSender:E})})}createProducerObject(e){return u(this,null,function*(){const r=new lD(a(this,Mi),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r})}closeProducer(e){return u(this,null,function*(){yield this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")})}canConsume(){return u(this,null,function*(){if(this.closed)throw new bt("closed");if(this.direction!=="recv")throw new To("not a receiving transport");if(!(yield this.transportConnectionPromise))throw new br("transport not connected");return!0})}consume(e,r,i){return u(this,null,function*(){return this.awaitQueue.push(()=>u(this,null,function*(){const n={},{consumerStates:o,sessionDescription:c,failedProducers:d}=yield r(e);o.forEach((h,g)=>{n[g]=this.createConsumerObjectAndWaitForTrack(G(O({},h),{producerId:g}))}),c&&(this.logger.info("Session description found, sending negotiation request"),yield i(c));const l=[];return yield Promise.all(Object.entries(n).map(([h,g])=>g.then(T=>l.push(T)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${h}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}}),"Transport.consume",{producersLength:e.length})})}static parseCodecAndFmtpMappings(e,r){const i=as.parse(e.sdp),n={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(n[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),n}static setCodecAndFmtpMappings(e,r,i){const n=as.parse(e.sdp);return n.media=n.media.map(c=>{if(r.includes(c.mid.toString())){const d=O({},c);return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),G(O({},e),{sdp:as.write(n)})}static parseHeaderExtensionMappings(e){const r=as.parse(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=as.parse(e.sdp);return i.media=i.media.map(o=>{const c=O({},o);return c.ext=r[o.mid],c}),G(O({},e),{sdp:as.write(i)})}closeConsumers(e,r){return u(this,null,function*(){try{const i=e.map(l=>l.transceiver.mid),n=gn.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=gn.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=yield this.handler.pc.createOffer();this.logger.info("[SDP] Created offer for closing consumers",{sdp:c.sdp}),c=gn.setCodecAndFmtpMappings(c,i,n),c=gn.setHeaderExtensionMappings(c,o),this.logger.info("[SDP] Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),yield this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=yield r(e,c);this.logger.info("[SDP] Received answer in close consumers",{sdp:d.sdp}),yield this.setRemoteDescription(d),this.logger.info("[SDP] Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}})}setRemoteOffer(e){return u(this,null,function*(){try{this.logger.info("[SDP] Received offer from SFU",{sdp:e.sdp}),yield this.setRemoteDescription(e);const r=yield this.handler.pc.createAnswer();this.logger.info("[SDP] Created answer corresponding to received offer",{sdp:r.sdp});const i=as.parse(r.sdp);return i.media=i.media.map(n=>{if(n.type==="audio"){const o=O({},n),c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return n}),r.sdp=as.write(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),yield this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}})}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const n=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(n)});const o=this.consumerTrackEvents.get(n);o?(o(r,i),this.consumerTrackEvents.delete(n)):(this.logger.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,e))}sendErrorOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i,!0)}sendResponseOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i)}createConsumerObjectAndWaitForTrack(e){return u(this,null,function*(){const{consumerId:r,producerId:i,producingPeerId:n,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:h,kind:g,mimeType:T}=e,v=`${c}:${g}`,E=G(O({},e),{name:"consumer creation task error",message:"consumer creation failed"});return new Promise((w,b)=>u(this,null,function*(){const M=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${v} producingPeerId: ${n}`),this.consumerTrackEvents.delete(v),E.isTimedout=!0,b(E)},5e3),D=(V,H)=>{try{if(V.readyState==="ended")clearTimeout(M),b(E);else{const j=V;j.enabled=!0,this.handler.midTransceiverMap.set(H.mid,H);const Z=new dD(a(this,Mi),{id:r,localId:H.mid,transceiver:H,track:j,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:G(O({},h),{screenShare:l,peerId:n}),rtpReceiver:H.receiver,mimeType:T});this.consumers.set(r,Z),Z.once("close",()=>{this.consumers.delete(Z.id),this.handler.midTransceiverMap.delete(H.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:g,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",Z),clearTimeout(M),w(Z)}}catch(j){this.logger.warn("error while creating consumer:",j),clearTimeout(M),b(E)}},$=this.unknownTracksMap.get(v);$?(this.logger.info(`track event already received [trackId: ${$.track.id}] [mid: ${$.transceiver.mid}]`),this.unknownTracksMap.delete(v),D($.track,$.transceiver)):(this.logger.info(`Registering onTrack handler for key ${v} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(v,D))}))})}setRemoteDescription(e){return u(this,null,function*(){yield this.handler.pc.setRemoteDescription(e)})}setLocalDescription(e){return u(this,null,function*(){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),yield this.handler.pc.setLocalDescription(e)})}sendDataChannelMessage(e,r){return u(this,null,function*(){const i=this.getDatachannel(e);if(!i)throw rD("DC_NOT_READY",`${e} datachannel not ready`);const n=(yield i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(n)}`),n})}};let Du=gn;Mi=new WeakMap;function pD(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=kg.getParser(t),r=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(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}var Ks,Ii;class gD{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");m(this,Ks,void 0);m(this,Ii,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,Ks,t),f(this,Ii,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)a(this,Ii).debug(`Device::constructor() | handler given: ${e}`);else if(e=pD(a(this,Ii)),e)a(this,Ii).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=bh.createFactory(a(this,Ks));break;case"Safari12":this.handlerFactory=_h.createFactory(a(this,Ks));break;case"Firefox60":this.handlerFactory=pd.createFactory(a(this,Ks),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=pd.createFactory(a(this,Ks),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=Jr.v4();return new Du(a(this,Ks),G(O({id:e},t),{handlerFactory:this.handlerFactory}))}}Ks=new WeakMap,Ii=new WeakMap;const mD=2e3;var aa,st,rt,jo,Go,Ai,oa,Wo,ca,Di,ks,da,Zc,Jo,Ou,xd,Uf,Ko,Nu,Ud,$f,$d,Bf,Bd,Hf,Hd,Ff,Fd,qf,zo,Lu,Yo,Vu;class fD extends nt.EventEmitter{constructor(e,r){super();m(this,da);m(this,Jo);m(this,xd);m(this,Ko);m(this,Ud);m(this,$d);m(this,Bd);m(this,Hd);m(this,Fd);m(this,zo);m(this,Yo);p(this,"context");m(this,aa,void 0);m(this,st,void 0);m(this,rt,void 0);m(this,jo,void 0);m(this,Go,void 0);m(this,Ai,void 0);m(this,oa,void 0);m(this,Wo,void 0);m(this,ca,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});m(this,Di,void 0);m(this,ks,"all");this.context=e,f(this,Ai,r),f(this,aa,new gD(e)),f(this,oa,new oD(r)),f(this,Wo,Ts),a(this,da,Zc).mediaState={send:{state:Sn.NEW},recv:{state:Sn.NEW}},ba(this.context,"forceRelay")&&f(this,ks,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,ks)}`),x(this,Jo,Ou).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,Ai)}get socketHandler(){return a(this,oa)}get sendTransport(){return a(this,st)}get recvTransport(){return a(this,rt)}get events(){return a(this,Wo)}set sendTransportConnectedCallback(e){f(this,jo,e)}set recvTransportConnectedCallback(e){f(this,Go,e)}setupTransports(e){return u(this,null,function*(){yield x(this,xd,Uf).call(this,e);let r,i;e.send&&(r=x(this,Ko,Nu).call(this,a(this,st)).then(n=>{try{a(this,jo).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=x(this,Ko,Nu).call(this,a(this,rt)).then(n=>{try{a(this,Go).call(this,n)}catch(o){this.logger.error("Failed to run recv transport callback")}})),yield Promise.all([r,i])})}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,st);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,st).close(),a(this,st).removeAllListeners(),f(this,st,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,rt);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,rt))==null||r.close(),(i=a(this,rt))==null||i.removeAllListeners(),f(this,rt,void 0)}x(this,Jo,Ou).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}aa=new WeakMap,st=new WeakMap,rt=new WeakMap,jo=new WeakMap,Go=new WeakMap,Ai=new WeakMap,oa=new WeakMap,Wo=new WeakMap,ca=new WeakMap,Di=new WeakMap,ks=new WeakMap,da=new WeakSet,Zc=function(){return this.context.getValue("connectionHandler")},Jo=new WeakSet,Ou=function(){f(this,Di,{send:void 0,recv:void 0})},xd=new WeakSet,Uf=function(e){return u(this,null,function*(){var o,c,d,l,h,g,T,v;ba(this.context,"forceRelay")&&f(this,ks,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,ks)}`);const n=yield mt().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));e.send&&x(this,$d,Bf).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(T=(g=(h=this.context.getValue("defaults").mediaConfiguration)==null?void 0:h.audio)==null?void 0:g.enableStereo)!=null?T:!1,enableDtx:!1},iceTransportPolicy:a(this,ks)}),e.recv&&x(this,Bd,Hf).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(v=this.context.getValue("modules").e2ee)==null?void 0:v.enabled},iceTransportPolicy:a(this,ks)})})},Ko=new WeakSet,Nu=function(e){return u(this,null,function*(){const{id:r,serverId:i,direction:n}=e;x(this,Hd,Ff).call(this,e);try{return yield Nf((c,d)=>u(this,null,function*(){c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:n}});try{if(e.closed)throw new br("Cannot reconnect closed transport");yield x(this,Ud,$f).call(this,e)}catch(l){if(l instanceof br){d(l);return}throw this.logger.error("Failed to connect transport, retrying",{transport:e,error:l}),l}}),{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect send transport after retry: ${e.id}`,{error:o,transport:{id:r,serverId:i,type:n}}),e.close(),e.removeAllListeners(),o}})},Ud=new WeakSet,$f=function(e){return u(this,null,function*(){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,Ai).isConnected)throw new br("Socket is not connected");if(e.connectionState==="closed")throw new br("Transport is closed");try{yield e.connect(n=>x(this,Fd,qf).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,ca).transportFailureCount[i]+=1,n.message==="ice connection failed"?new br(n.message):n}})},$d=new WeakSet,Bf=function(e){var r,i;if(a(this,st)&&a(this,st).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,st))==null?void 0:r.id,serverId:(i=a(this,st))==null?void 0:i.serverId,type:"send"}});return}f(this,st,a(this,aa).createTransport(G(O({},e),{direction:"send"}))),this.context.getValue("callstats").configureSendTransport(a(this,st))},Bd=new WeakSet,Hf=function(e){var r,i;if(a(this,rt)&&a(this,rt).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,rt))==null?void 0:r.id,serverId:(i=a(this,rt))==null?void 0:i.serverId,type:"recv"}});return}f(this,rt,a(this,aa).createTransport(G(O({},e),{direction:"recv"}))),this.context.getValue("callstats").configureRecvTransport(a(this,rt))},Hd=new WeakSet,Ff=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",n=>u(this,null,function*(){x(this,Yo,Vu).call(this,{state:n,direction:r}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,Di)[r];c!==void 0&&(clearTimeout(c),a(this,Di)[r]=void 0)};switch(n){case"connected":o(),a(this,ca).lastConnectionTime=performance.now();break;case"disconnected":a(this,Di)[r]=setTimeout(()=>u(this,null,function*(){this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),yield x(this,zo,Lu).call(this,e.direction)}),mD);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),yield x(this,zo,Lu).call(this,e.direction);break}})),e.on("icecandidate",n=>u(this,null,function*(){this.logger.debug("Sending iceCandidate:",{iceCandidate:n})})),e.on("datachannel:events",(n,o)=>u(this,null,function*(){var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:n,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,hD(o),l);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(c=o.payload)==null?void 0:c.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(l){this.logger.error(`Unable to handle the incoming datachannel message on channel ${n}`)}})),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s"),this.handleErrors("reconnectRecvTransport"))})},Fd=new WeakSet,qf=function(e,r){return u(this,null,function*(){const i=e==="recv";try{const{sdp:n,type:o}=r,c={consuming:i,description:{sdp:n,type:o,target:i?dr.SUBSCRIBER:dr.PUBLISHER},producers:[]};return a(this,oa).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}})},zo=new WeakSet,Lu=function(e){return u(this,null,function*(){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,Ai).isConnected&&a(this,ca).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,ks,"relay")),yield this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,st)}),this.context.getValue("peerSessionStore").emit(C.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,rt)}),this.context.getValue("peerSessionStore").emit(C.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}x(this,Yo,Vu).call(this,{state:Sn.CONNECTED,direction:e})})},Yo=new WeakSet,Vu=function(e){const{state:r,direction:i}=e;a(this,da,Zc).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(C.TRANSPORT_STATE_UPDATE,O({transport:i},a(this,da,Zc).mediaState[i]))};var qd,Qt;class TD{constructor(t,e,r,i,n){m(this,qd,void 0);m(this,Qt,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,qd,t),f(this,Qt,t.getValue("logger"))}create(t){return u(this,null,function*(){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:h,producingTransportId:g}=d,T={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(h,l),r.push(O({producingPeerId:l,producerId:h,producingTransportId:g},T))});const i=yield this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),n=new Map;t.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const h=n.get(d);if(!h)return;if(l.errorCode){a(this,Qt).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push(G(O({},h),{errorCode:l.errorCode}));return}let g={};try{g=JSON.parse(l.producerState.appData)}catch(T){}o.set(d,{consumerId:l.consumerId,producingTransportId:h.producingTransportId,producingPeerId:h.producingPeerId,kind:h.kind,paused:h.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:h.screenShare,mimeType:h.mimeType,appData:g})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}})}negotiate(t){return u(this,null,function*(){try{a(this,Qt).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,Qt).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=yield this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:dr.SUBSCRIBER}};return a(this,Qt).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),yield this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,dw.toBinary(r)),a(this,Qt).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,Qt).error("Failed to renegotiate",{error:e});return}})}close(t){return u(this,null,function*(){if(!t.length)return{};const e=(r,i)=>u(this,null,function*(){const n=r.map(l=>l.localId);a(this,Qt).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:dr.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=yield this.socketHandler.closeConsumer(o),d=VC.fromBinary(c).description;return{sdp:d.sdp,type:d.type}});return yield this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"ConsumerStrategy.close",{consumersLength:t.length}),{}})}switchConsumersToLayer(t,e){return u(this,null,function*(){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(n=>n&&n.id);i.forEach(({id:n,producingTransportId:o,localId:c})=>{r.requests.push({producerId:n,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),yield this.socketHandler.updateConsumersSimulcastConfig(r),a(this,Qt).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})})}}qd=new WeakMap,Qt=new WeakMap;class wh{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return as.parse(t).media.filter(n=>e==="video"?n.type==="video":n.type==="audio").at(-1).msid}create(c){return u(this,arguments,function*({offer:t,kind:e,paused:r,appData:i,codecOptions:n,producingTransportId:o}){var T,v;const d=wh.getMSIDFromSDP(t.sdp,e),l={description:{sdp:t.sdp,type:t.type,target:dr.PUBLISHER},paused:r,kind:e,msid:d,appData:JSON.stringify(i),screenShare:(T=i.screenShare)!=null?T:!1,mimeType:`${e}/${(v=n[0])==null?void 0:v.name}`,producingTransportId:o},{answer:h,producerId:g}=yield this.socketHandler.produce(l);return{answer:h,producerId:g}})}}var Oi,xr,la,Qo,Ms,jd,zs,ua,Xo,xu,Gd,jf,Wd,Gf,Jd,Wf,Kd,Jf;class SD extends fD{constructor(e,r){super(e,r);m(this,Xo);m(this,Gd);m(this,Wd);m(this,Jd);m(this,Kd);m(this,Oi,void 0);m(this,xr,void 0);m(this,la,void 0);m(this,Qo,void 0);m(this,Ms,void 0);m(this,jd,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});m(this,zs,[]);m(this,ua,void 0);this.context=e,this.sendTransportConnectedCallback=()=>u(this,null,function*(){f(this,Qo,new wh(this.socketHandler))}),this.recvTransportConnectedCallback=i=>u(this,null,function*(){a(this,la).clear(),f(this,Ms,new TD(this.context,this.events,i,this.socket,this.socketHandler))}),this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,Oi)}get consumers(){return a(this,xr)}get producerIdToConsumerIdMap(){return a(this,la)}get logger(){return this.context.getValue("logger")}reset(){f(this,Oi,new Map),f(this,xr,new Map),f(this,la,new Map)}createProducer(e,r){return u(this,null,function*(){var i,n;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const o=yield this.sendTransport.produce(e,x(this,Gd,jf).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(C.E2EE_ACTIVE_PRODUCER,o),x(this,Wd,Gf).call(this,o,r),o}catch(o){throw this.logger.error(`Failed to create ${((n=e==null?void 0:e.track)==null?void 0:n.kind)||"unknown"} producer`,{error:o}),a(this,jd).producerCreationFailureCount+=1,o}})}closeProducer(e,r){return u(this,null,function*(){var n;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{yield this.sendTransport.closeProducer(i),(n=this.context.getValue("modules").e2ee)!=null&&n.enabled&&this.context.getValue("peerSessionStore").emit(C.E2EE_INACTIVE_PRODUCER,i)}catch(o){this.logger.error("Failed to close producer on server",{error:o,producer:i})}})}closeAllProducers(){return Promise.all(Array.from(a(this,Oi).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}createConsumers(e){return u(this,null,function*(){a(this,ua)||clearTimeout(a(this,ua)),f(this,zs,a(this,zs).concat(e)),yield x(this,Xo,xu).call(this)})}closeConsumer(e){return this.closeConsumers([e])}closeConsumers(e){return u(this,null,function*(){if(!a(this,Ms))return;const r=e.map(n=>this.consumers.get(n)).filter(n=>n!==void 0);if(r.length===0)return;const{failedConsumers:i}=yield a(this,Ms).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,xr).keys()))}switchConsumersToLayer(e,r){return u(this,null,function*(){a(this,Ms).switchConsumersToLayer(e,r)})}}Oi=new WeakMap,xr=new WeakMap,la=new WeakMap,Qo=new WeakMap,Ms=new WeakMap,jd=new WeakMap,zs=new WeakMap,ua=new WeakMap,Xo=new WeakSet,xu=function(){return u(this,null,function*(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,zs).splice(0,a(this,zs).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),n=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(n.length===0)return;const{consumers:o,failedProducers:c}=yield this.recvTransport.consume(n,x(this,Jd,Wf).bind(this),a(this,Ms).negotiate.bind(a(this,Ms)));if(o.forEach(x(this,Kd,Jf).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:h})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${h}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);f(this,zs,a(this,zs).concat(d)),f(this,ua,setTimeout(x(this,Xo,xu).bind(this),e))}}catch(i){if(this.logger.error("failed to consume on transport",{error:i}),i.errorCode==="internal_error"&&i.errorDescription==="Backend error"||i.errorCode==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:i.errorCode,message:i.errorDescription}});try{this.stopTransports({recv:!0})}catch(n){}yield this.setupTransports({recv:!0})}}})},Gd=new WeakSet,jf=function(e){return a(this,Qo).create(e)},Wd=new WeakSet,Gf=function(e,r){e.on("close",(i,n)=>u(this,null,function*(){const{offer:o,reason:c}=i;if(this.logger.info("producer::closing",{debuggingHint:c,producer:G(O({},e),{status:"closing"})}),c!==gd){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:dr.PUBLISHER}};try{const l=yield this.socketHandler.closeProducer(d),h={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:G(O({},e),{status:"closed"})}),n({answer:h})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()})),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:G(O({},e),{status:"UNKNOWN"})})}),a(this,Oi).set(e.id,e)},Jd=new WeakSet,Wf=function(e){return u(this,null,function*(){try{return yield this.recvTransport.canConsume(),yield a(this,Ms).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}})},Kd=new WeakSet,Jf=function(e){e.on("close",r=>u(this,null,function*(){this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),a(this,xr).delete(e.id),this.context.getValue("peerSessionStore").emit(C.CONSUMER_CLOSED,{id:e.id})})),a(this,xr).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(C.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};var Zo,ec,tc,ha,pa,ga,sc,rc,ma,vt,hs,ps,Ni,Li,Ys,ic,zd,Kf,Yd,zf,Qd,Yf,Xd,Qf;const Zd=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:n=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:h=50}={}){m(this,zd);m(this,Yd);m(this,Zo,void 0);m(this,ec,void 0);m(this,tc,void 0);m(this,ha,void 0);m(this,pa,void 0);m(this,ga,void 0);m(this,sc,void 0);m(this,rc,void 0);m(this,ma,void 0);m(this,vt,void 0);m(this,hs,void 0);m(this,ps,!1);m(this,Ni,0);m(this,Li,0);m(this,Ys,[]);m(this,ic,void 0);f(this,ha,t),f(this,vt,t),f(this,Zo,e),f(this,ec,r),f(this,tc,i),f(this,pa,n),f(this,ga,o),f(this,sc,c),f(this,rc,d),f(this,ma,l),f(this,ic,h),f(this,hs,t/2)}get voiceDetected(){return a(this,ps)}processAudioChunk(t){var o,c;const e=x(o=Zd,Qd,Yf).call(o,t),r=x(c=Zd,Xd,Qf).call(c,t);return x(this,zd,Kf).call(this,e),e/a(this,hs)>a(this,ma)&&e>a(this,vt)&&r>a(this,Zo)?(f(this,Ni,a(this,Ni)+1),f(this,Li,a(this,tc)),a(this,Ni)>=a(this,ec)&&f(this,ps,!0)):(f(this,Ni,0),a(this,Li)>0?f(this,Li,a(this,Li)-1):a(this,ps)&&f(this,ps,!1),a(this,ps)||x(this,Yd,zf).call(this,e)),{energy:e,isVoice:a(this,ps)}}reset(){f(this,ps,!1),f(this,Ni,0),f(this,Li,0),f(this,vt,a(this,ha)),f(this,hs,a(this,ha)/2),f(this,Ys,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,vt),backgroundNoiseEnergy:a(this,hs),energyRatioThreshold:a(this,ma)}}};let Za=Zd;Zo=new WeakMap,ec=new WeakMap,tc=new WeakMap,ha=new WeakMap,pa=new WeakMap,ga=new WeakMap,sc=new WeakMap,rc=new WeakMap,ma=new WeakMap,vt=new WeakMap,hs=new WeakMap,ps=new WeakMap,Ni=new WeakMap,Li=new WeakMap,Ys=new WeakMap,ic=new WeakMap,zd=new WeakSet,Kf=function(t){a(this,ps)?f(this,vt,a(this,ga)*a(this,vt)+(1-a(this,ga))*t):f(this,vt,a(this,pa)*a(this,vt)+(1-a(this,pa))*a(this,hs)),f(this,vt,Math.max(a(this,sc),Math.min(a(this,rc),a(this,vt))))},Yd=new WeakSet,zf=function(t){if(t<a(this,vt)*1.2)if(a(this,Ys).push(t),a(this,Ys).length>a(this,ic)&&a(this,Ys).shift(),a(this,Ys).length>=10){const e=[...a(this,Ys)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,hs,e[r])}else f(this,hs,.95*a(this,hs)+.05*t)},Qd=new WeakSet,Yf=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Xd=new WeakSet,Qf=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},m(Za,Qd),m(Za,Xd);var nc;class eg{constructor(t){p(this,"RNAudioSampleHandler");m(this,nc,void 0);f(this,nc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return a(this,nc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}nc=new WeakMap;var ac;class tg{constructor(t){p(this,"audioContext");p(this,"analyser");m(this,ac,void 0);f(this,ac,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,ac).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}ac=new WeakMap;class vD{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const yD=60,ED=400;var Qs,Xs,Zs,oc,fa,Ta,Ur,Vi,Sa,xi,er,Is,el,Xf,cc,Uu,tl,Zf,sl,eT;const uo=class{constructor(t,e){m(this,el);m(this,tl);m(this,Qs,void 0);m(this,Xs,void 0);m(this,Zs,void 0);m(this,oc,void 0);m(this,fa,void 0);m(this,Ta,void 0);m(this,Ur,void 0);m(this,Vi,void 0);m(this,Sa,void 0);m(this,xi,void 0);m(this,er,void 0);m(this,Is,void 0);this.reportRequest=e,f(this,xi,t),f(this,Ta,new Za);const{isReactNative:r}=navigator;f(this,er,r?new eg(a(this,xi)):new tg(a(this,xi))),f(this,Is,r?vD:qc)}get logger(){return a(this,xi).getValue("logger")}set producerId(t){f(this,Zs,t)}set audioTrack(t){f(this,oc,t),a(this,er)instanceof tg&&(a(this,er).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Zs)}`),a(this,Qs)&&a(this,Is).clearInterval(a(this,Qs)),f(this,Qs,a(this,Is).setInterval(()=>u(this,null,function*(){var i;if(!a(this,oc)||!a(this,Zs))return;const{energy:t}=x(this,el,Xf).call(this),e=x(i=uo,cc,Uu).call(i,t);let r=.9;a(this,Sa)!==e&&a(this,Sa)?r=.9:e?r=.3:r=.5,f(this,fa,(a(this,fa)||0)*(1-r)+t*r)}),yD)),a(this,Xs)&&a(this,Is).clearInterval(a(this,Xs)),f(this,Xs,a(this,Is).setInterval(x(this,tl,Zf).bind(this),ED))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Zs)}`),a(this,Qs)&&(a(this,Is).clearInterval(a(this,Qs)),f(this,Qs,void 0)),a(this,Xs)&&(a(this,Is).clearInterval(a(this,Xs)),f(this,Xs,void 0))}catch(t){}a(this,Ta).reset(),a(this,er)instanceof eg&&a(this,er).stop()}};let eo=uo;Qs=new WeakMap,Xs=new WeakMap,Zs=new WeakMap,oc=new WeakMap,fa=new WeakMap,Ta=new WeakMap,Ur=new WeakMap,Vi=new WeakMap,Sa=new WeakMap,xi=new WeakMap,er=new WeakMap,Is=new WeakMap,el=new WeakSet,Xf=function(){var o;const{samples:t}=a(this,er),{energy:e,isVoice:r}=a(this,Ta).processAudioChunk(t),i=x(o=uo,sl,eT).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,Ur)||i<a(this,Ur))&&f(this,Ur,i),(!a(this,Vi)||i>a(this,Vi))&&f(this,Vi,i),{energy:(i-a(this,Ur))/(a(this,Vi)-a(this,Ur))*10||0,isVoice:r})},cc=new WeakSet,Uu=function(t){return t<5},tl=new WeakSet,Zf=function(t=a(this,fa)){var r;if(!a(this,Zs)||!t)return;const e={producerId:a(this,Zs),energy:Math.round(t),silent:x(r=uo,cc,Uu).call(r,t)};f(this,Sa,e.silent),this.reportRequest(e)},sl=new WeakSet,eT=function(t){const e=Math.log10(t);return Math.round(e)},m(eo,cc),m(eo,sl);var PD=Object.defineProperty,bD=Object.getOwnPropertyDescriptor,ce=(s,t,e,r)=>{for(var i=r>1?void 0:r?bD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&PD(t,e,i),i},dc,lc,it,J,rl,ht,Ui,$i,Bi,uc,Xt,tr,pt,yt,$r,cn,il,tT,nl,sT,al,rT,hc,$u,ol,iT,cl,nT,gt,Rt,Hi,to,dl,aT,ll,oT,ul,cT;class ne{constructor(t,e){m(this,$r);m(this,il);m(this,nl);m(this,al);m(this,hc);m(this,ol);m(this,cl);m(this,gt);m(this,Hi);m(this,dl);m(this,ll);m(this,ul);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,dc,void 0);m(this,lc,void 0);m(this,it,void 0);m(this,J,void 0);m(this,rl,void 0);m(this,ht,void 0);m(this,Ui,void 0);m(this,$i,void 0);m(this,Bi,void 0);m(this,uc,void 0);m(this,Xt,null);m(this,tr,void 0);m(this,pt,void 0);m(this,yt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,it,r),f(this,Ui,!1),f(this,J,new SD(t,r)),f(this,ht,a(this,J).events),f(this,tr,new Set),f(this,pt,new Map),f(this,$i,!1),f(this,Bi,new Iu(t.getValue("logger"))),f(this,yt,new eo(this.context,a(this,J).socketHandler.audioActivity.bind(a(this,J).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,uc,dh(()=>u(this,null,function*(){if(!a(this,$r,cn).mediaJoinAttempted)return;const{roomJoined:o}=yield this.joinRoom(a(this,lc),a(this,dc),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(C.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(C.ROOM_NODE_RECONNECTED))}),5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,$r,cn).mediaJoined}set mediaJoined(t){a(this,$r,cn).mediaJoined=t}reset(){a(this,J).closeAllProducers(),a(this,J).closeAllConsumers(),a(this,pt).clear(),a(this,tr).clear(),f(this,Xt,null),a(this,Bi).stop(),a(this,J).stopAllTransports(),a(this,J).reset(),f(this,Bi,new Iu)}joinRoom(o,c){return u(this,arguments,function*(t,e,r=!1,i=!1,n={}){a(this,$r,cn).mediaJoinAttempted=!0,f(this,Ui,!0),r&&this.reset();try{return yield a(this,Bi).push(()=>x(this,il,tT).call(this,t,e,i,n),"joinRoom")}catch(d){return this.logger.error("Error in room joining process",{error:d}),this.context.getValue("peerSessionStore").emit(C.ROOM_NODE_FAILED),{roomJoined:!1,error:d}}})}initializeConnection(n,o){return u(this,arguments,function*(t,e,r=!1,i={}){return a(this,Xt)?a(this,Xt):(f(this,Xt,(()=>u(this,null,function*(){try{yield x(this,hc,$u).call(this,t,e,r,i)}catch(c){throw f(this,Xt,null),c}}))()),a(this,Xt))})}getConsumers(){return a(this,J).consumers}getProducers(){return a(this,J).producers}leaveRoom(){return u(this,null,function*(){a(this,J).stopAllTransports(),f(this,$i,!1),a(this,$r,cn).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,it).sendMessagePromise(a(this,ht).leaveRoom,Nw.toBinary(t)).then(r=>{var i;(i=PC.fromBinary(r.payload))!=null&&i.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(r=>{this.logger.error("error on sending leave room request",{error:r})}),this.context.getValue("callstats").callEnded(),yield this.context.getValue("telemetry").destruct()})}activatePeers(t){return u(this,null,function*(){return this.createConsumers(t)})}createConsumers(t){return u(this,null,function*(){return t.length===0?Promise.resolve():a(this,J).createConsumers(t)})}closeConsumers(t){return u(this,null,function*(){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,J).producerIdToConsumerIdMap.get(i.producerId);return n?(r.push(n),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);yield a(this,J).closeConsumers(e)})}_shareWebcam(t){return u(this,null,function*(){var h,g,T,v;const e=_e.WEBCAM,r=x(this,gt,Rt).call(this,e);if(r){const E=yield r;if(a(this,J).producers.has(E)){const w=a(this,J).producers.get(E);if(!w.closed)return yield w.replaceTrack({track:t}),yield this.resumeWebcam(e),t;yield this.disableWebcam()}return this._shareWebcam(t)}const i=x(this,ul,cT).call(this,t),n=ba(this.context,"disableSimulcast"),o=(g=(h=this.context)==null?void 0:h.getValue("overrides"))==null?void 0:g.simulcastConfig;n||o&&o.disable||!((v=(T=this.context)==null?void 0:T.getValue("theme"))!=null&&v.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=l0(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,pt).delete(e)},l=a(this,J).createProducer(i,d);return x(this,Hi,to).call(this,e,l.then(E=>E.id)),l.then(E=>E.track)})}shareWebcam(t){return u(this,null,function*(){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))})}shareScreen(t){return u(this,null,function*(){const{video:e,audio:r}=t;if(e===void 0)return;const i={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,pt).delete(_e.SCREENSHARE_VIDEO),a(this,pt).delete(_e.SCREENSHARE_AUDIO)},o=a(this,J).createProducer(i,n);x(this,Hi,to).call(this,_e.SCREENSHARE_VIDEO,o.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=a(this,J).createProducer(d,l),x(this,Hi,to).call(this,_e.SCREENSHARE_AUDIO,c.then(h=>h.id))}yield Promise.all([o,c||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()})}shareMic(t){return u(this,null,function*(){try{if(t===void 0)throw new bt("track undefined");const e=x(this,gt,Rt).call(this,_e.MIC);if(e){const o=yield e;if(a(this,J).producers.has(o)){const c=a(this,J).producers.get(o);if(!c.closed){yield c.replaceTrack({track:t}),yield this.resumeMic(),a(this,yt)&&(a(this,yt).audioTrack=t,a(this,yt).producerId=o,a(this,yt).start());return}yield a(this,J).closeProducer(o,{stopTrack:!1})}yield this.shareMic(t);return}const r=x(this,ll,oT).call(this,t),i=()=>{a(this,pt).delete(_e.MIC)},n=a(this,J).createProducer(r,i);x(this,Hi,to).call(this,_e.MIC,n.then(o=>o.id)),yield n.then(o=>{a(this,yt)&&(a(this,yt).audioTrack=o.track,a(this,yt).producerId=o.id,a(this,yt).start())})}catch(e){throw new R(e)}})}pauseMic(){return u(this,null,function*(){var i;const t=yield x(this,gt,Rt).call(this,_e.MIC),e=a(this,J).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=a(this,yt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,it).sendMessage(a(this,ht).toggleProducer,Vc.toBinary(r))})}pauseWebcam(){return u(this,null,function*(){const t=yield x(this,gt,Rt).call(this,_e.WEBCAM),e=a(this,J).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};a(this,it).sendMessage(a(this,ht).toggleProducer,Vc.toBinary(r))})}resumeMic(){return u(this,null,function*(){const t=yield x(this,gt,Rt).call(this,_e.MIC),e=a(this,J).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(C.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,it).sendMessage(a(this,ht).toggleProducer,Vc.toBinary(r))})}resumeWebcam(){return u(this,arguments,function*(t=_e.WEBCAM){const e=yield x(this,gt,Rt).call(this,t),r=a(this,J).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(C.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,it).sendMessage(a(this,ht).toggleProducer,Vc.toBinary(i))})}disableWebcam(){return u(this,null,function*(){const t=_e.WEBCAM,e=yield x(this,gt,Rt).call(this,t);x(this,dl,aT).call(this,t),e&&(yield a(this,J).closeProducer(e))})}disableMic(){return u(this,null,function*(){var e;const t=yield x(this,gt,Rt).call(this,_e.MIC);t&&(yield a(this,J).closeProducer(t)),(e=a(this,yt))==null||e.stop(),a(this,pt).delete(_e.MIC)})}disableScreenShare(){return u(this,null,function*(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=yield x(this,gt,Rt).call(this,_e.SCREENSHARE_VIDEO),e=yield x(this,gt,Rt).call(this,_e.SCREENSHARE_AUDIO);t&&(yield a(this,J).closeProducer(t)),e&&(yield a(this,J).closeProducer(e)),a(this,tr).clear(),a(this,pt).delete(_e.SCREENSHARE_VIDEO),a(this,pt).delete(_e.SCREENSHARE_AUDIO)})}muteSelf(){return u(this,null,function*(){this.pauseMic()})}resetVideoProducers(t,e){return u(this,null,function*(){if(t){const r=yield x(this,gt,Rt).call(this,_e.WEBCAM);yield a(this,J).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=yield x(this,gt,Rt).call(this,_e.SCREENSHARE_VIDEO);yield a(this,J).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}})}changeDisplayName(t,e){return u(this,null,function*(){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!(yield a(this,J).socketHandler.changeDisplayName(r)))throw new Error("failed to change display name!")})}kick(t){const e={peerIds:[t]};a(this,J).socketHandler.kickPeer(e)}kickAll(){a(this,J).socketHandler.kickAll()}muteAll(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("audio")))throw new Error("failed to mute all participant")})}muteAllVideo(){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForAll("video")))throw new Error("failed to mute all video participant")})}disableAudio(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"audio")))throw new Error("failed to mute given participant")})}disableVideo(t){return u(this,null,function*(){if(!(yield a(this,J).socketHandler.hostControlForPeer(t,"video")))throw new Error("failed to mute video of given participant")})}pinPeer(t){return u(this,null,function*(){const e={participantId:t!=null?t:""};try{yield a(this,it).sendMessagePromise(a(this,ht).globalPinPeer,Kw.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}})}validateScreenShare(t){return this.peerId===t.peerId&&a(this,J).producers.get(t.producerId)&&a(this,tr).add(t.consumerPeerId),a(this,tr).size}switchConsumersToLayer(t,e){return u(this,null,function*(){const r=t.map(i=>this.getConsumers().get(i));a(this,J).switchConsumersToLayer(r,e)})}handleSocketEvents(){return u(this,null,function*(){a(this,it).on(a(this,ht).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=XC.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===or.AUDIO?"audio/opus":"video/VP8"),this.logger.info(`producer created broadcast: ${e}, producer state: ${r}`),this.context.getValue("peerSessionStore").emit(C.NEW_PRODUCER,{peerId:e,producer:G(O({},r),{kind:r.kind===or.AUDIO?"audio":"video",producingPeerId:e})})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,it).on(a(this,ht).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=Mp.fromBinary(t);if(c)return;const d=i===or.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(Mp.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(d==="audio"?C.MUTE_SELF:C.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(C.PRODUCER_TOGGLE,{peerId:e,producerId:o,paused:n,kind:d}),Array.from(this.getConsumers().values()).filter(h=>h.producerId===o).forEach(h=>{h.kind==="video"&&n||h.paused!==n&&(this.logger.debug(`consumer state mismatched for ${h.id}. updating consumer pause state ${h.paused} to ${n}`),n?(h.pause(),this.context.getValue("peerSessionStore").emit(C.CONSUMER_PAUSED,{id:h.id})):(h.resume(),this.context.getValue("peerSessionStore").emit(C.CONSUMER_RESUMED,{id:h.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,it).on(a(this,ht).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=lu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,tr).delete(e),a(this,J).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(C.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,it).on(a(this,ht).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=tR.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(C.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=a(this,J).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),a(this,J).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,J).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(C.CONSUMER_CLOSED,{id:i})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,it).on(a(this,ht).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Ui)&&!a(this,$i)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(C.ROOM_NODE_DISCONNECTED),a(this,uc).call(this))})})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,J).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(C.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(a(this,J).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(C.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}dc=new WeakMap,lc=new WeakMap,it=new WeakMap,J=new WeakMap,rl=new WeakMap,ht=new WeakMap,Ui=new WeakMap,$i=new WeakMap,Bi=new WeakMap,uc=new WeakMap,Xt=new WeakMap,tr=new WeakMap,pt=new WeakMap,yt=new WeakMap,$r=new WeakSet,cn=function(){return this.context.getValue("connectionHandler")},il=new WeakSet,tT=function(t,e,r,i){return u(this,null,function*(){f(this,lc,t);try{a(this,Xt)?yield a(this,Xt):yield x(this,hc,$u).call(this,t,e,r,i),x(this,al,rT).call(this,e);const{joined:n,error:o}=yield x(this,nl,sT).call(this);return{roomJoined:n,error:o}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1,error:n}}finally{f(this,Xt,null)}})},nl=new WeakSet,sT=function(){return u(this,null,function*(){try{this.mediaJoined=!0;const{roomState:t}=yield a(this,J).socketHandler.notifySelfJoinComplete();return f(this,dc,t.roomUuid),f(this,$i,!0),f(this,Ui,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}})},al=new WeakSet,rT=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:G(O({},Te.getDeviceInfo()),{userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency}),sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},hc=new WeakSet,$u=function(t,e,r,i){return u(this,null,function*(){try{const n=x(this,ol,iT).call(this);yield x(this,cl,nT).call(this,t,e,r,n),yield a(this,J).setupTransports({send:!0,recv:!0})}catch(n){throw this.logger.error("Failed to initialize connection",{error:n}),n}})},ol=new WeakSet,iT=function(){const t=aD("video/VP8");return f(this,rl,t),t},cl=new WeakSet,nT=function(t,e,r,i){return u(this,null,function*(){yield Nf((n,o)=>u(this,null,function*(){if(!a(this,it).isConnected){o(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{yield a(this,J).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}}),{delayTime:1e3,strategy:"exponential",maxRetryCount:15})})},gt=new WeakSet,Rt=function(t){return a(this,pt).get(t)},Hi=new WeakSet,to=function(t,e){return a(this,pt).set(t,e)},dl=new WeakSet,aT=function(t){return a(this,pt).delete(t)},ll=new WeakSet,oT=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},ul=new WeakSet,cT=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}};ce([P.trace("MediaNodeClient.reset")],ne.prototype,"reset",1);ce([P.trace("MediaNodeClient.joinRoom")],ne.prototype,"joinRoom",1);ce([P.trace("MediaNodeClient.leaveRoom")],ne.prototype,"leaveRoom",1);ce([P.trace("MediaNodeClient.activatePeers")],ne.prototype,"activatePeers",1);ce([P.trace("MediaNodeClient.createConsumers")],ne.prototype,"createConsumers",1);ce([P.trace("MediaNodeClient.closeConsumers")],ne.prototype,"closeConsumers",1);ce([P.trace("MediaNodeClient._shareWebcam")],ne.prototype,"_shareWebcam",1);ce([P.trace("MediaNodeClient.shareWebcam")],ne.prototype,"shareWebcam",1);ce([P.trace("MediaNodeClient.shareScreen")],ne.prototype,"shareScreen",1);ce([P.trace("MediaNodeClient.shareMic")],ne.prototype,"shareMic",1);ce([P.trace("MediaNodeClient.pauseMic")],ne.prototype,"pauseMic",1);ce([P.trace("MediaNodeClient.pauseWebcam")],ne.prototype,"pauseWebcam",1);ce([P.trace("MediaNodeClient.resumeMic")],ne.prototype,"resumeMic",1);ce([P.trace("MediaNodeClient.resumeWebcam")],ne.prototype,"resumeWebcam",1);ce([P.trace("MediaNodeClient.disableWebcam")],ne.prototype,"disableWebcam",1);ce([P.trace("MediaNodeClient.disableMic")],ne.prototype,"disableMic",1);ce([P.trace("MediaNodeClient.disableScreenShare")],ne.prototype,"disableScreenShare",1);ce([P.trace("MediaNodeClient.muteSelf")],ne.prototype,"muteSelf",1);ce([P.trace("MediaNodeClient.resetVideoProducers")],ne.prototype,"resetVideoProducers",1);ce([P.trace("MediaNodeClient.changeDisplayName")],ne.prototype,"changeDisplayName",1);ce([P.trace("MediaNodeClient.kickPeer")],ne.prototype,"kick",1);ce([P.trace("MediaNodeClient.kickAllPeers")],ne.prototype,"kickAll",1);ce([P.trace("MediaNodeClient.muteAll")],ne.prototype,"muteAll",1);ce([P.trace("MediaNodeClient.muteAllVideo")],ne.prototype,"muteAllVideo",1);ce([P.trace("MediaNodeClient.disableAudio")],ne.prototype,"disableAudio",1);ce([P.trace("MediaNodeClient.disableVideo")],ne.prototype,"disableVideo",1);ce([P.trace("MediaNodeClient.pinPeer")],ne.prototype,"pinPeer",1);ce([P.trace("MediaNodeClient.validateScreenShare")],ne.prototype,"validateScreenShare",1);function dT(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new ne(s,t);return s.setValue("roomNodeClient",r),r}function lT(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var _D=Object.defineProperty,wD=Object.getOwnPropertyDescriptor,sn=(s,t,e,r)=>{for(var i=r>1?void 0:r?wD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&_D(t,e,i),i},Fi,gs,te,Et,Ht,_g;const uT=(_g=class{constructor(s,t,e,r){m(this,Et);p(this,"self");p(this,"authToken");m(this,Fi,void 0);p(this,"viewType");m(this,gs,void 0);m(this,te,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,te,s),this.viewType=r,this.authToken=n,f(this,Fi,i),f(this,gs,e),this.setupEvents()}get peerId(){return a(this,te).getValue("peerId")}get telemetry(){return a(this,te).getValue("telemetry")}get logger(){return a(this,te).getValue("logger")}get mediaJoined(){return a(this,te).getValue("connectionHandler").mediaJoined}static init(s,t,e,r,i){return u(this,null,function*(){const n=mt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=yield Ye.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(()=>u(this,null,function*(){const g=yield d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(g)}),s.getValue("callstats").devices("AUDIO",g==null?void 0:g.filter(T=>T.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",g==null?void 0:g.filter(T=>T.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",g==null?void 0:g.filter(T=>T.kind==="audiooutput")),l.info("Callstats:: initializing");try{yield s.getValue("callstats").initialize({peerId:o,engineName:Te.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:yield n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:l,apiHostnames:C_(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),l.info("Callstats:: initialized")}catch(T){l.error("Callstats:: initialization failed",{error:T})}}),0):l.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new uT(s,d,t,i.viewType)})}shareMediaTracks(){return u(this,null,function*(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===q.Allowed&&r)try{yield a(this,Et,Ht).shareMic(s),this.self.audioEnabled||a(this,Et,Ht).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===q.Allowed&&i)try{yield a(this,Et,Ht).shareWebcam(t),this.self.videoEnabled||a(this,Et,Ht).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===q.Allowed&&n)try{yield(c=a(this,Et,Ht))==null?void 0:c.shareScreen({video:o.video,audio:o.audio})}catch(d){this.self.disableScreenShare()}})}kickHandler(s){return u(this,null,function*(){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)})}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}resetSelf(s){return u(this,null,function*(){a(this,te).getValue("callstats").callEnded(),a(this,Et,Ht).reset(),s&&(yield this.joinRoom(s))})}setupEvents(){a(this,te).getValue("peerSessionStore").on(C.RESET_PRODUCER_STATE,()=>u(this,null,function*(){this.mediaJoined&&this.shareMediaTracks()})),a(this,te).getValue("peerSessionStore").on(C.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,te).getValue("peerSessionStore").on(C.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,te).getValue("peerSessionStore").on(C.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,te).getValue("peerSessionStore").on(C.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,te).getValue("peerSessionStore").on(C.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;const{peerId:t}=this;a(this,Fi).updateURL(t),a(this,te).getValue("telemetry").resetPeerId(t),mt().setHeader("tracing-id",t),Gr.remapContext(t,a(this,te)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,te).getValue("peerSessionStore").on(C.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,gs).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,gs).on(Jc.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,te).getValue("peerSessionStore").emit(C.UPDATE_PERMISSIONS,t.patch)})}),a(this,gs).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,gs).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,gs).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,te).getValue("peerSessionStore").onAsync(C.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,te).getValue("peerSessionStore").on(C.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,te).getValue("peerSessionStore").on(C.MUTE_SELF,()=>u(this,null,function*(){this.self.audioEnabled&&(yield this.self.disableAudio(),a(this,te).getValue("callstats").audioOff())})),a(this,te).getValue("peerSessionStore").on(C.MUTE_SELF_VIDEO,()=>u(this,null,function*(){this.self.videoEnabled&&(yield this.self.disableVideo(),a(this,te).getValue("callstats").videoOff())})),a(this,te).getValue("peerSessionStore").onAsync(C.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,te).getValue("peerSessionStore").on(C.PIP_HANGUP,this.leaveRoom.bind(this))}joinRoom(s=!1){return u(this,null,function*(){try{const{peer:t}=yield a(this,gs).joinRoom(this.self);a(this,gs).socket.flush();const e=gh(t.stageType);if(a(this,te).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new R("Check the network and try again.","0002")}try{yield this.joinMediaRoom(s),a(this,te).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof br&&t.message==="ice connection failed"?new R("A firewall or network restriction may be blocking the connection.","0014"):new R("Check the network and try again.","0014")}})}leaveRoom(s="left"){return u(this,null,function*(){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=a(this,te).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,te).setValue("stageStatus","OFF_STAGE",!1),yield this.leaveMediaRoom(s),a(this,te).notify("stageStatus");try{(e=a(this,Fi))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}lT(a(this,te)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)})}joinMediaRoom(s=!1){return u(this,null,function*(){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,te).getAllValues();try{if(e===ar.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}dT(a(this,te),{socket:a(this,Fi),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:h,error:g}=(o=yield(n=a(this,Et,Ht))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}))!=null?o:{};if(!h)throw g!=null?g:new Error("Could not connect to media server");i==="ON_STAGE"&&(yield this.shareMediaTracks()),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}})}leaveMediaRoom(s){return u(this,null,function*(){const t=a(this,te).getValue("viewType");s!=="connected-meeting"&&(yield this.cleanupSelf()),!(s==="stageLeft"&&t===ar.Webinar)&&a(this,Et,Ht)&&(a(this,Et,Ht).mediaJoined&&s!=="disconnected"&&(yield a(this,Et,Ht).leaveRoom()),!(s==="stageLeft"&&t===ar.Livestream)&&(a(this,Et,Ht).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()})}},Fi=new WeakMap,gs=new WeakMap,te=new WeakMap,Et=new WeakSet,Ht=function(){return a(this,te).getValue("roomNodeClient")},_g);let Xr=uT;sn([P.trace("SelfController.resetSelf")],Xr.prototype,"resetSelf",1);sn([P.trace("SelfController.setupEvents")],Xr.prototype,"setupEvents",1);sn([P.trace("SelfController.joinRoom")],Xr.prototype,"joinRoom",1);sn([P.trace("SelfController.leaveRoom")],Xr.prototype,"leaveRoom",1);sn([P.trace("SelfController.joinMediaRoom")],Xr.prototype,"joinMediaRoom",1);sn([P.trace("SelfController.leaveMediaRoom")],Xr.prototype,"leaveMediaRoom",1);sn([P.trace("SelfController.init")],Xr,"init",1);var pc;class CD{constructor(t){m(this,pc,void 0);f(this,pc,t)}on(t,e){let r;t===U.roomPeerCount?r=Dp.fromBinary.bind(Dp):r=qp.fromBinary.bind(qp),a(this,pc).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}pc=new WeakMap;var gc,mc;class RD{constructor(t,e){m(this,gc,void 0);m(this,mc,void 0);f(this,gc,e),f(this,mc,t)}get logger(){return a(this,mc).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=jl.fromBinary.bind(jl),i=jl.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,gc).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}gc=new WeakMap,mc=new WeakMap;var kD=Object.defineProperty,MD=Object.getOwnPropertyDescriptor,Ch=(s,t,e,r)=>{for(var i=r>1?void 0:r?MD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&kD(t,e,i),i},sr,va;class Al{constructor(t,e){m(this,sr,void 0);m(this,va,void 0);f(this,sr,e),f(this,va,t)}get logger(){return a(this,va).getValue("logger")}get telemetry(){return a(this,va).getValue("telemetry")}getPolls(){return a(this,sr).sendMessagePromise(xs.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,sr).sendMessage(xs.createPoll,UI.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,sr).sendMessage(xs.votePoll,BI.toBinary(r))}on(t,e){let r,i;switch(t){case xs.updatePoll:case xs.createPoll:case xs.votePoll:{r=Yl.fromBinary.bind(Yl),i=Yl.create();break}}a(this,sr).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,sr).removeListeners(t)}}sr=new WeakMap,va=new WeakMap;Ch([P.trace("PollSocketHandler.getPolls")],Al.prototype,"getPolls",1);Ch([P.trace("PollSocketHandler.createPoll")],Al.prototype,"createPoll",1);Ch([P.trace("PollSocketHandler.votePoll")],Al.prototype,"votePoll",1);var ID=Object.defineProperty,AD=Object.getOwnPropertyDescriptor,DD=(s,t,e,r)=>{for(var i=r>1?void 0:r?AD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ID(t,e,i),i},Nt;class hT{constructor(t,e){p(this,"socket");m(this,Nt,void 0);f(this,Nt,t),this.socket=e,this.handleSocketEvents(),a(this,Nt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Nt).getValue("telemetry")}get logger(){return a(this,Nt).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}joinRoom(t){return u(this,null,function*(){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(U.joinRoom,IR.toBinary(e));try{const{peer:n}=nn.fromBinary((yield r).payload);a(this,Nt).getValue("connectionHandler").socketJoined=!0,a(this,Nt).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=yield Promise.all([o,c]);return a(this,Nt).getValue("peerSessionStore").emit(C.ROOM_STATE,d),a(this,Nt).getValue("peerSessionStore").emit(C.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}})}getAllAddedParticipants(){return u(this,null,function*(){try{return gk.fromBinary((yield this.socket.sendMessagePromise(U.getAllAddedParticipants)).payload).participants.map(i=>{var n=i,{id:e}=n,r=Dc(n,["id"]);return G(O({},r),{userId:e})})}catch(t){return[]}})}getRoomPeers(t,e,r){return u(this,null,function*(){let i;try{const n={seachQuery:t,limit:e,offset:r},o=yield this.socket.sendMessagePromise(U.getRoomPeersInfo,yR.toBinary(n));i=Gl.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i})}getRoomPeersNonPaginated(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(U.getRoomPeersInfo);t=Gl.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getStagePeers(){return u(this,null,function*(){let t;try{const e=yield this.socket.sendMessagePromise(U.getRoomPeersInfo);t=Gl.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t})}getPeerInfo(t){return u(this,null,function*(){let e;try{const r=yield this.socket.sendMessagePromise(U.getPeerInfo,Zm.toBinary({peerId:t}));e=nn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e})}getRoomState(){return u(this,null,function*(){let t=Op.create();try{const e=yield this.socket.sendMessagePromise(U.getRoomInfo);t=Op.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t})}getRoomStageState(){return u(this,null,function*(){let t=xp.create();try{const e=yield this.socket.sendMessagePromise(U.getRoomStageState);t=xp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t})}broadcastMessage(t,e){return u(this,null,function*(){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(U.broadcastMessage,Wa.toBinary(r))})}broadcastToMeetings(t,e,r){return u(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(U.broadcastToEntity,Wa.toBinary(i))})}broadcastToPeers(t,e,r){return u(this,null,function*(){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(U.broadcastToEntity,Wa.toBinary(i))})}leaveRoom(){return u(this,null,function*(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,DR.toBinary({}))})}kick(t){return u(this,null,function*(){const e={peerIds:[t]};this.socket.sendMessage(U.kick,tf.toBinary(e))})}kickAll(t=!1){return u(this,null,function*(){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,Ym.toBinary(e))})}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,yk.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,Pk.toBinary(e))}updatePermissions(t,e){return u(this,null,function*(){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Jc.updateUserPreset,Qk.toBinary(r))})}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=Wa.fromBinary(t);a(this,Nt).getValue("peerSessionStore").emit(C.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(U.broadcastToEntity,({payload:t})=>{try{const e=Wa.fromBinary(t);a(this,Nt).getValue("peerSessionStore").emit(C.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case U.joinRoom:case U.leaveRoom:case U.kick:case U.kickAll:{r=nn.fromBinary.bind(nn),i=nn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?Vp.fromBinary(n,o):{requests:[]},i=Vp.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=Wp.fromBinary.bind(Wp);break}case Jc.updateUserPreset:{r=Up.fromBinary.bind(Up);break}case Ts.peerJoinedBroadcast:case Pr.peerJoinedBroadcast:{r=Rp.fromBinary.bind(Rp);break}case Ts.selfJoinComplete:case Pr.selfJoinComplete:{r=du.fromBinary.bind(du);break}case Ts.globalPeerPinBroadcast:case Pr.globalPeerPinBroadcast:{r=Ip.fromBinary.bind(Ip);break}case Ts.selectedPeer:case Pr.selectedPeer:{r=cu.fromBinary.bind(cu);break}case Ts.selectedPeerDiff:case Pr.selectedPeerDiff:{r=Cp.fromBinary.bind(Cp);break}case Ts.leaveRoom:case Pr.leaveRoom:{r=lu.fromBinary.bind(lu);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}getUserPermissions(t){return u(this,null,function*(){const e={userIds:[t]};try{const r=yield this.socket.sendMessagePromise(Jc.getUserPresets,jk.toBinary(e)),i=Kk.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}})}}Nt=new WeakMap;DD([P.trace("RoomSocketHandler.joinRoom")],hT.prototype,"joinRoom",1);var Pt;class OD{constructor(t){m(this,Pt,void 0);f(this,Pt,t)}getStageRequests(){return u(this,null,function*(){const{payload:t}=yield a(this,Pt).sendMessagePromise(U.getStageRequests);return t?zl.fromBinary(t):{stageRequests:[]}})}requestAccess(){a(this,Pt).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,Pt).sendMessage(U.cancelStageRequest)}grantAccess(t){return u(this,null,function*(){const e={userIds:t};a(this,Pt).sendMessage(U.grantStageAccess,kI.toBinary(e))})}denyAccess(t){return u(this,null,function*(){const e={userIds:t};a(this,Pt).sendMessage(U.denyStageAccess,II.toBinary(e))})}joinStage(){return a(this,Pt).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Pt).sendMessagePromise(U.leaveStage,Gp.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Pt).sendMessagePromise(U.leaveStage,Gp.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=jp.fromBinary.bind(jp);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=zl.fromBinary.bind(zl);break}case U.peerStageStatusUpdate:{r=Ap.fromBinary.bind(Ap);break}}a(this,Pt).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}getPeerInfo(t){return u(this,null,function*(){const e=yield a(this,Pt).sendMessagePromise(U.getPeerInfo,Zm.toBinary({peerId:t}));return nn.fromBinary(e.payload)})}}Pt=new WeakMap;var $e,fc;class ND{constructor(t,e){m(this,$e,void 0);m(this,fc,void 0);f(this,$e,e),f(this,fc,t)}get logger(){return a(this,fc).getValue("logger")}addPlugin(t,e){a(this,$e).sendMessage(W.addPlugin,GM.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,$e).sendMessage(W.removePlugin,JM.toBinary({pluginId:t,staggered:!1}))}getActivePlugins(){return u(this,null,function*(){const{payload:t}=yield a(this,$e).sendMessagePromise(W.getPlugins);return t?fI.fromBinary(t):{plugins:[]}})}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,$e).sendMessage(W.customPluginEventToRoom,rI.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,$e).sendMessage(W.customPluginEventToPeers,nI.toBinary(n),i)}enablePluginForRoom(t,e){a(this,$e).sendMessage(W.enablePluginForRoom,zM.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,$e).sendMessage(W.enablePluginForPeers,ZM.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,$e).sendMessage(W.disablePluginForRoom,QM.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,$e).sendMessage(W.disablePluginForPeers,tI.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,$e).sendMessage(W.storeInsertKeys,$p.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,$e).sendMessage(W.storeGetKeys,dI.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,$e).sendMessage(W.storeDeleteKeys,uI.toBinary(n),i)}storeDelete(t,e,r){a(this,$e).sendMessage(W.storeDelete,pI.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,$e).sendMessage(W.storeInsertKeys,$p.toBinary(i))}on(t,e){let r;switch(t){case W.addPlugin:case W.enablePluginForPeers:case W.enablePluginForRoom:{r=gu.fromBinary.bind(gu);break}case W.removePlugin:case W.disablePluginForPeers:case W.disablePluginForRoom:{r=Bp.fromBinary.bind(Bp);break}case W.customPluginEventToPeers:case W.customPluginEventToRoom:{r=Fp.fromBinary.bind(Fp);break}case W.storeInsertKeys:case W.storeGetKeys:case W.storeDeleteKeys:case W.storeDelete:{r=Hp.fromBinary.bind(Hp);break}}a(this,$e).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}$e=new WeakMap,fc=new WeakMap;var LD=Object.defineProperty,VD=(s,t,e)=>t in s?LD(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,xD=(s,t,e)=>(VD(s,typeof t!="symbol"?t+"":t,e),e),Rh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},A=(s,t,e)=>(Rh(s,t,"read from private field"),e?e.call(s):t.get(s)),ge=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ie=(s,t,e,r)=>(Rh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),ye=(s,t,e)=>(Rh(s,t,"access private method"),e),md={},UD={get exports(){return md},set exports(s){md=s}},vn=typeof Reflect=="object"?Reflect:null,sg=vn&&typeof vn.apply=="function"?vn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},ed;vn&&typeof vn.ownKeys=="function"?ed=vn.ownKeys:Object.getOwnPropertySymbols?ed=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:ed=function(s){return Object.getOwnPropertyNames(s)};function $D(s){console&&console.warn&&console.warn(s)}var pT=Number.isNaN||function(s){return s!==s};function oe(){oe.init.call(this)}UD.exports=oe;md.once=qD;oe.EventEmitter=oe;oe.prototype._events=void 0;oe.prototype._eventsCount=0;oe.prototype._maxListeners=void 0;var rg=10;function Dl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(oe,"defaultMaxListeners",{enumerable:!0,get:function(){return rg},set:function(s){if(typeof s!="number"||s<0||pT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");rg=s}});oe.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};oe.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||pT(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function gT(s){return s._maxListeners===void 0?oe.defaultMaxListeners:s._maxListeners}oe.prototype.getMaxListeners=function(){return gT(this)};oe.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")sg(c,this,t);else for(var d=c.length,l=vT(c,d),e=0;e<d;++e)sg(l[e],this,t);return!0};function mT(s,t,e,r){var i,n,o;if(Dl(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=gT(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,$D(c)}return s}oe.prototype.addListener=function(s,t){return mT(this,s,t,!1)};oe.prototype.on=oe.prototype.addListener;oe.prototype.prependListener=function(s,t){return mT(this,s,t,!0)};function BD(){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 fT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=BD.bind(r);return i.listener=e,r.wrapFn=i,i}oe.prototype.once=function(s,t){return Dl(t),this.on(s,fT(this,s,t)),this};oe.prototype.prependOnceListener=function(s,t){return Dl(t),this.prependListener(s,fT(this,s,t)),this};oe.prototype.removeListener=function(s,t){var e,r,i,n,o;if(Dl(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():HD(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};oe.prototype.off=oe.prototype.removeListener;oe.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function TT(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?FD(i):vT(i,i.length)}oe.prototype.listeners=function(s){return TT(this,s,!0)};oe.prototype.rawListeners=function(s){return TT(this,s,!1)};oe.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):ST.call(s,t)};oe.prototype.listenerCount=ST;function ST(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}oe.prototype.eventNames=function(){return this._eventsCount>0?ed(this._events):[]};function vT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function HD(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function FD(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function qD(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}yT(s,t,n,{once:!0}),t!=="error"&&jD(s,i,{once:!0})})}function jD(s,t,e){typeof s.on=="function"&&yT(s,"error",t,e)}function yT(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class GD extends S.MessageType{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 ig=new GD;class ET{static encode(t){return ig.toBinary(t)}static decode(t){return ig.fromBinary(new Uint8Array(t))}}function WD(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var yr;class JD{constructor(t={}){xD(this,"opts"),ge(this,yr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,yr,0)}wait(){return u(this,null,function*(){ie(this,yr,A(this,yr)+1);const t=WD(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*Nh(2,A(this,yr))));yield new Promise(e=>{setTimeout(e,t)})})}getAttempts(){return A(this,yr)}reset(){ie(this,yr,0)}}yr=new WeakMap;const fr={debug:0,info:1,warn:2,error:3};var ri,ii;class KD{constructor(t){ge(this,ri,void 0),ge(this,ii,void 0),ie(this,ri,console),ie(this,ii,t)}debug(...t){fr[A(this,ii)]>fr.debug||A(this,ri).debug("[Sockrates]:",...t)}info(...t){fr[A(this,ii)]>fr.info||A(this,ri).info("[Sockrates]:",...t)}warn(...t){fr[A(this,ii)]>fr.warn||A(this,ri).warn("[Sockrates]:",...t)}error(...t){fr[A(this,ii)]>fr.error||A(this,ri).error("[Sockrates]:",...t)}}ri=new WeakMap,ii=new WeakMap;var PT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(PT||{});const zD="2",YD="3";var ke,dn,ve,Ne,Er,ze,ir,qr,fs,ln,Vs,Bu,bT,so,td,Hu,_T,Fu,ng,fd,qu,ju,wT,ao,sd,oo,Td,Sd,Gu,yn,co,lo,vd;class QD{constructor(t,e){var T,v,E,w,b,M,D,$,V,H;ge(this,Bu),ge(this,so),ge(this,Hu),ge(this,Fu),ge(this,fd),ge(this,ju),ge(this,ao),ge(this,oo),ge(this,Sd),ge(this,yn),ge(this,lo),ge(this,ke,void 0),ge(this,dn,void 0),ge(this,ve,void 0),ge(this,Ne,void 0),ge(this,Er,void 0),ge(this,ze,void 0),ge(this,ir,void 0),ge(this,qr,void 0),ge(this,fs,void 0),ge(this,ln,void 0),ge(this,Vs,void 0);var r,i,n,o,c,d,l,h,g;ie(this,dn,t),ie(this,Er,[]),ie(this,ze,new md),ie(this,ir,!0),ie(this,fs,!1),ie(this,ve,e!=null?e:{}),(T=(r=A(this,ve)).autoReconnect)!=null||(r.autoReconnect=!0),(v=(i=A(this,ve)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(n=A(this,ve)).pingTimeout)!=null||(n.pingTimeout=3e4),(w=(o=A(this,ve)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(b=(c=A(this,ve)).debug)!=null||(c.debug=!0),(M=(d=A(this,ve)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(D=(l=A(this,ve)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),($=(h=A(this,ve)).queueOnDisconnect)!=null||(h.queueOnDisconnect=!1),(V=(g=A(this,ve)).flushOnReconnect)!=null||(g.flushOnReconnect=!1),ie(this,qr,{code:void 0,reason:void 0}),ie(this,Ne,(H=A(this,ve).logger)!=null?H:new KD(A(this,ve).debug?"debug":"info")),ie(this,Vs,new JD)}get readyState(){var t;return(t=A(this,ke))==null?void 0:t.readyState}get url(){return A(this,dn)}updateURL(t){ie(this,dn,t),ye(this,ju,wT).call(this)}get config(){return A(this,ve)}get sendQueue(){return A(this,Er)}flush(){if(!A(this,ve).queueOnDisconnect)return!1;const t=[];return A(this,Er).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Er,t),A(this,Er)}connect(t=!1){return u(this,null,function*(){if(!t&&[0,1].includes(this.readyState)){A(this,Ne).debug("Websocket was already connecting or connected.");return}if(A(this,ir)!==!1)return new Promise((e,r)=>{ye(this,yn,co).call(this),ye(this,lo,vd).call(this);try{ie(this,ke,new WebSocket(ye(this,Bu,bT).call(this,A(this,dn)))),A(this,ke).binaryType="arraybuffer",A(this,Ne).debug("Connecting");const i=setTimeout(()=>{A(this,Ne).debug("Connection timeout. Closing socket"),ie(this,ir,!0),ye(this,lo,vd).call(this),A(this,ke).close(3001,"Connection Timeout"),A(this,ve).autoReconnect&&!A(this,fs)&&(A(this,ze).emit("reconnecting"),ye(this,ao,sd).call(this)),r(new Error("Connection timed out!"))},A(this,ve).connectionTimeout);A(this,ke).onopen=()=>{A(this,Ne).debug(`Ready State: ${PT[A(this,ke).readyState]}`),i&&clearTimeout(i),ye(this,Sd,Gu).call(this),ie(this,qr,{code:void 0,reason:void 0}),A(this,ze).emit("connected"),A(this,ve).flushOnReconnect&&this.flush(),e()},A(this,ke).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),A(this,Ne).debug("Socket closed. Close event:",{event:n}),A(this,Ne).debug(`Connection closed code: ${o}`),A(this,Ne).debug(`Connection closed reason: ${c}`),A(this,fs)||ye(this,fd,qu).call(this,o,c)}catch(o){ye(this,so,td).call(this,o)}},A(this,ke).onerror=n=>{ye(this,so,td).call(this,n)},A(this,ke).onmessage=n=>ye(this,Hu,_T).call(this,n)}catch(i){ye(this,so,td).call(this,i,r)}})})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(A(this,ve).queueOnDisconnect&&(!A(this,ke)||A(this,ke).readyState!==1))return A(this,Ne).debug("Queuing message since socket is not connected!",n),A(this,Er).push(n),!1;const o=ET.encode(n);return ye(this,oo,Td).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return ye(this,oo,Td).call(this,t)}receive(t,e){return A(this,ze).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){A(this,ze).on(t,e);return}this.receive(t,e)}removeAllListeners(){A(this,ze).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){A(this,ze).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){A(this,ze).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,ir,!1),ye(this,yn,co).call(this),this.removeAllListeners(),ie(this,qr,{code:1e3,reason:"Sockrates disconnect method called"}),A(this,ke).close(1e3,"Sockrates disconnect method called.")}}ke=new WeakMap,dn=new WeakMap,ve=new WeakMap,Ne=new WeakMap,Er=new WeakMap,ze=new WeakMap,ir=new WeakMap,qr=new WeakMap,fs=new WeakMap,ln=new WeakMap,Vs=new WeakMap,Bu=new WeakSet,bT=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},so=new WeakSet,td=function(s,t){A(this,Ne).error("Error:",{error:s}),A(this,ze).emit("errored",{error:s}),t==null||t(s)},Hu=new WeakSet,_T=function(s){if(ye(this,Sd,Gu).call(this),s.data===zD){A(this,Ne).debug("Received ping from server"),ye(this,oo,Td).call(this,YD);return}const t=ET.decode(s.data),{id:e,payload:r}=t;A(this,Ne).debug("Received message",{event:t.event,messageID:e}),A(this,ze).emit(t.event.toString(),{id:e,payload:r})},Fu=new WeakSet,ng=function(){return A(this,ke).readyState===1},fd=new WeakSet,qu=function(s,t){ie(this,qr,{reason:t,code:s}),A(this,ze).emit("disconnected",{code:s,reason:t})},ju=new WeakSet,wT=function(){const{reason:s,code:t}=A(this,qr);t&&t!==1e3&&A(this,ir)&&A(this,ve).autoReconnect&&!A(this,fs)&&(A(this,Ne).debug(`Triggering reconnection due to ${s}.`),A(this,ze).emit("reconnecting"),ye(this,ao,sd).call(this))},ao=new WeakSet,sd=function(s=!0){return u(this,null,function*(){if(s&&A(this,fs)){A(this,Ne).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(A(this,fs)||A(this,Vs).reset(),A(this,ve).maxReconnectionAttempts!==null&&A(this,Vs).getAttempts()>=A(this,ve).maxReconnectionAttempts){A(this,ze).emit("failed"),ie(this,fs,!1);return}ie(this,fs,!0),ye(this,lo,vd).call(this),ye(this,yn,co).call(this);try{if(yield A(this,Vs).wait(),A(this,ir)===!1)return;if(A(this,Ne).debug(`Reconnection attempt ${A(this,Vs).getAttempts()}`),A(this,ze).emit("reconnectAttempt",{attempt:A(this,Vs).getAttempts()}),yield this.connect(),!ye(this,Fu,ng).call(this))throw Error("Reconnect Failed");ie(this,fs,!1),ie(this,qr,{code:void 0,reason:void 0}),A(this,ze).emit("reconnected")}catch(t){A(this,Ne).debug("Failed to reconnect."),A(this,ze).emit("reconnectFailure",{attempt:A(this,Vs).getAttempts()}),ye(this,ao,sd).call(this,!1)}})},oo=new WeakSet,Td=function(s){try{return A(this,ke).send(s),!0}catch(t){return A(this,Ne).error(t.message),!1}},Sd=new WeakSet,Gu=function(){this.config.disconnectOnPingTimeout&&(A(this,Ne).debug("Resetting ping timeout"),ye(this,yn,co).call(this),ie(this,ln,setTimeout(()=>{var s;A(this,Ne).debug("Disconnecting the socket due to ping timeout"),ie(this,ir,!0);const t=3002,e="Ping timeout";(s=A(this,ke))==null||s.close(t,e),ye(this,fd,qu).call(this,t,e)},A(this,ve).pingTimeout)))},yn=new WeakSet,co=function(){A(this,ln)&&(clearTimeout(A(this,ln)),ie(this,ln,void 0))},lo=new WeakSet,vd=function(){A(this,ke)&&(A(this,ke).onopen=void 0,A(this,ke).onerror=void 0,A(this,ke).onmessage=void 0,A(this,ke).onclose=void 0)};var XD=Object.defineProperty,ZD=Object.getOwnPropertyDescriptor,Ol=(s,t,e,r)=>{for(var i=r>1?void 0:r?ZD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&XD(t,e,i),i};const ag=65535,e1=3e3;var Br,Pe,be,Ie,Zt,Ke,Tc,Wu,Sc,Ju,wg;const CT=(wg=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,be);m(this,Tc);m(this,Sc);m(this,Br,void 0);m(this,Pe,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,Zt,void 0);m(this,Ke,void 0);var n;if(!t||!e||!r)throw new R("peerId, meetingId, or authToken can not be empty","0404");f(this,Zt,void 0),f(this,Ke,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,Br,x(this,Tc,Wu).call(this,t)),f(this,Pe,new QD(a(this,Br),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,be,Ie).socketJoinAttempted}set joinAttempted(s){a(this,be,Ie).socketJoinAttempted=s}get telemetry(){return a(this,Ke).getValue("telemetry")}get logger(){return a(this,Ke).getValue("logger")}get peerId(){return a(this,Ke).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,Br,x(this,Tc,Wu).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Pe).updateURL(a(this,Br))}static getSocketEdgeDomain(s){return Tn({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,Br)}connect(){return u(this,null,function*(){a(this,be,Ie).socketJoinAttempted=!0,yield a(this,Pe).connect(),a(this,be,Ie).socketJoinAttempted=!0,a(this,be,Ie).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}})}disconnect(){a(this,be,Ie).socketJoinAttempted=!1,a(this,Pe).disconnect(),a(this,be,Ie).socketJoinAttempted=!0,a(this,be,Ie).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Pe).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,Ke).getValue("telemetry").injectContext(r),a(this,Pe).send(s,e!=null?e:x(this,Sc,Ju).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const n=i!=null?i:s;return new Promise((o,c)=>{const d=(E,w)=>{a(this,Pe).removeListener(n,E),a(this,Pe).removeListener(ag,w),a(this,Pe).removeListener(Pr.errorResponse,w),a(this,Pe).removeListener(Ts.errorResponse,w)},l=r!=null?r:x(this,Sc,Ju).call(this),h={};a(this,Ke).getValue("telemetry").injectContext(h);const T=({id:E,payload:w})=>{if(l===E){let b;try{const M=hC.fromBinary(w);b=new Error(M.errorMessage)}catch(M){b=new Error("failed to parse error message",{cause:M});try{const D=pR.fromBinary(w);b=new Error(D.message)}catch(D){b=new Error("failed to parse error message",{cause:D})}}c(b),d(v,T)}},v=({id:E,payload:w})=>{l===E&&(o({id:E,payload:w}),d(v,T))};a(this,Pe).on(n,v),a(this,Pe).on(ag,T),a(this,Pe).on(Pr.errorResponse,T),a(this,Pe).on(Ts.errorResponse,T),setTimeout(()=>{d(v,T),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Pe).send(s,l,e,new TextEncoder().encode(JSON.stringify(h)))})}on(s,t){a(this,Pe).on(s,t)}onStateEvent(s,t){a(this,Pe).on(s,t)}removeListener(s,t){a(this,Pe).removeListener(s,t)}removeListeners(s){a(this,Pe).removeListeners(s)}flush(){return a(this,Pe).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",()=>u(this,null,function*(){this.logger.info("SocketService::Connected to socket-edge"),a(this,Zt)&&(clearTimeout(a(this,Zt)),f(this,Zt,void 0)),a(this,be,Ie).updateSocketConnectionState("connected")})),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}});const{recv:e,send:r}=(i=a(this,be,Ie).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Sn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Sn.CONNECTED?a(this,Ke).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,be,Ie).joinAttempted}):f(this,Zt,setTimeout(()=>{a(this,Ke).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,be,Ie).joinAttempted}),f(this,Zt,void 0)},e1)),a(this,be,Ie).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnecting to socket-edge"),a(this,be,Ie).updateSocketConnectionState("reconnecting")})),this.onStateEvent("reconnectAttempt",t=>u(this,[t],function*({attempt:s}){this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,be,Ie).updateSocketConnectionState("reconnectAttempt",s)})),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,be,Ie).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",()=>u(this,null,function*(){this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,be,Ie).mediaJoinAttempted}}),a(this,Zt)&&(clearTimeout(a(this,Zt)),f(this,Zt,void 0)),a(this,Ke).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,be,Ie).mediaJoinAttempted}),a(this,be,Ie).updateSocketConnectionState("reconnected")})),this.onStateEvent("failed",()=>u(this,null,function*(){this.logger.info("SocketService::Failed to connect to socket-edge"),a(this,Ke).getValue("peerSessionStore").emit(C.SOCKET_SERVICE_FAILED),a(this,be,Ie).updateSocketConnectionState("failed")}))}},Br=new WeakMap,Pe=new WeakMap,be=new WeakSet,Ie=function(){return a(this,Ke).getValue("connectionHandler")},Zt=new WeakMap,Ke=new WeakMap,Tc=new WeakSet,Wu=function(s){const t=a(this,Ke).getValue("socketBaseURI")||a(this,Ke).getValue("baseURI");let e=CT.getSocketEdgeDomain(t);typeof ba(a(this,Ke),"socket_server_base")=="string"&&(e=ba(a(this,Ke),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),n=this.peerId,o=G(O({roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0},n!==s&&{oldPeerID:n}),{ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(c=>dd[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0});return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},Sc=new WeakSet,Ju=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},wg);let Ic=CT;Ol([P.trace("SocketService.connect")],Ic.prototype,"connect",1);Ol([P.trace("SocketService.disconnect")],Ic.prototype,"disconnect",1);Ol([P.trace("SocketService.sendMessagePromise")],Ic.prototype,"sendMessagePromise",1);Ol([P.trace("SocketService.sendMessagePromiseWithTimeout")],Ic.prototype,"sendMessagePromiseWithTimeout",1);class t1{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=BR.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=hk.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=ef.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Lp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return sk.fromBinary(t).payloads}getConnectedRoomsDump(){return u(this,null,function*(){const t=yield this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)})}createConnectedRooms(t){return u(this,null,function*(){const{payload:e}=yield this.socketService.sendMessagePromise(U.createConnectedRooms,jR.toBinary({payloads:t}));return Lp.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))})}updateConnectedRooms(t){return u(this,null,function*(){})}disableConnectedRooms(t){return u(this,null,function*(){const e=t.map(i=>({id:i})),r=yield this.socketService.sendMessagePromise(U.deleteConnectedRooms,ek.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)})}movePeersBetweenRooms(t){return u(this,null,function*(){try{const e=yield this.socketService.sendMessagePromise(U.movePeers,ck.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}}})}}var s1=Object.defineProperty,r1=Object.getOwnPropertyDescriptor,i1=(s,t,e,r)=>{for(var i=r>1?void 0:r?r1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&s1(t,e,i),i},ms;class RT extends Ut{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,ms,void 0);f(this,ms,e)}get supportsConnectedMeetings(){return a(this,ms).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
10
10
  Please connect with our support team to enable connected meetings.`)}getConnectedMeetings(){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=yield a(this,ms).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e})}createMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=yield a(this,ms).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))})}updateMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),yield a(this,ms).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)})}deleteMeetings(e){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),yield Promise.all(r);const i=yield a(this,ms).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i})}moveParticipants(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=yield a(this,ms).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),n})}moveParticipantsWithCustomPreset(e,r,i){return u(this,null,function*(){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=yield a(this,ms).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),n})}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>n.get(d)));return G(O({},o),{participants:c})}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return G(O({},o),{participants:c})}return o})}}ms=new WeakMap;i1([_t({maxInvocations:60,period:60})],RT.prototype,"getConnectedMeetings",1);var n1=Object.defineProperty,a1=Object.getOwnPropertyDescriptor,kh=(s,t,e,r)=>{for(var i=r>1?void 0:r?a1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&n1(t,e,i),i},ue,Cg;const kT=(Cg=class{constructor(s){p(this,"connectedMeetings");m(this,ue,void 0);f(this,ue,s),this.connectedMeetings=new RT(s)}get telemetry(){return a(this,ue).getValue("telemetry")}get logger(){return a(this,ue).getValue("logger")}static init(s){const t=new kT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(U.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(U.transferPeer,this.handleTransferPeer.bind(this)),a(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(U.movedPeer,this.handleMovedPeer.bind(this)),a(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,ue).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,ue).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}switchMeeting(e){return u(this,arguments,function*({authToken:s,meetingId:t}){var n,o,c,d;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
11
11
  Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const r={video:a(this,ue).getValue("self").videoEnabled,audio:a(this,ue).getValue("self").audioEnabled};try{a(this,ue).getValue("self").cleanupEvents(),yield a(this,ue).getValue("meeting").leave("connected-meeting")}catch(l){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(o=(n=a(this,ue).getValue("meeting"))==null?void 0:n.meta)==null?void 0:o.meetingId}`,{error:l})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const i=yield IT.init(G(O({},a(this,ue).getValue("options")),{cachedUserDetails:null,defaults:G(O(O({},a(this,ue).getValue("options").defaults),r),{mediaHandler:a(this,ue).getValue("self")}),authToken:s}));this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(c=i==null?void 0:i.meta)==null?void 0:c.meetingId}`);try{const{hidden:l}=a(this,ue).getValue("self");i.self.setName(a(this,ue).getValue("self").name),yield i.join(),l&&i.self.hide()}catch(l){this.logger.error("ConnectedMeetingsController.joinRoom",{error:l})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(d=i==null?void 0:i.meta)==null?void 0:d.meetingId}`),this.connectedMeetings.emit("meetingChanged",i),i})}handleConnectedRoomsDump(s){const t=a(this,ue).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,ue).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,ue).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,G(O({},r),{participants:[]}))}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,ue).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},ue=new WeakMap,Cg);let Nl=kT;kh([P.trace("ConnectedMeetingsController.getConnectedMeetings")],Nl.prototype,"getConnectedMeetings",1);kh([P.trace("ConnectedMeetingsController.setupEvents")],Nl.prototype,"setupEvents",1);kh([P.trace("ConnectedMeetingsController.switchMeeting")],Nl.prototype,"switchMeeting",1);var o1=Object.defineProperty,c1=Object.getOwnPropertyDescriptor,Mh=(s,t,e,r)=>{for(var i=r>1?void 0:r?c1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&o1(t,e,i),i};const ro=class{constructor(s,t,e){p(this,"apiBase");p(this,"selfController");p(this,"pollController");p(this,"chatController");p(this,"metaController");p(this,"storesManager");p(this,"stageController");p(this,"pluginController");p(this,"internalsController");p(this,"recordingController");p(this,"livestreamController");p(this,"participantController");p(this,"connectedMeetingsController");p(this,"telemetry");p(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static init(s){return u(this,null,function*(){var V,H,j;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(lT(s),Te.isSupported()===!1)throw new R("Browser not supported","0010",c,!0);const d=mA(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new YA(s);s.setValue("connectionHandler",l);let h="",g="",T=null;c.info("CF SFU is being used.");try{T=yield d.getUserDetails(),h=((V=T.meeting)==null?void 0:V.title)||"",g=((H=T.socket)==null?void 0:H.baseUri)||s.getValue("baseURI"),s.setValue("presetName",T.preset.name),s.setValue("socketBaseURI",g),c.info(`Socket Base URI ${g} is being used`)}catch(Z){throw c.error("Failed to get user details",{error:Z}),Z instanceof fu?Z.status===401?new R("Unauthorized. The auth token may be invalid or expired. (401)","0004"):Z.status===403?new R("Access denied. Insufficient permissions to join the meeting. (403)","0004"):Z.status===404?new R("The auth token is not associated with an active participant in this meeting. The meeting may have ended, or the participant may no longer exist. (404)","0004"):Z.status>=500?new R(`The server encountered an error. Try again. (${Z.status})`,"0001"):Z.isHttpError?new R(`Request rejected by the server. (${Z.status})`,"0001"):Z.isTimeout?new R("Connection timed out. Check the network and try again.","0001"):new R("Unable to connect to the server. Check the internet connection.","0001"):new R((Z==null?void 0:Z.message)||"Failed to initialize.","0001")}const v=ro.createSocketService(s),E=v.connect(),w=d.getPlugins();try{yield E}catch(Z){c.error("[Controller]: Failed to connect to socket server:",{error:Z})}const b=_u.init(T.preset,!s.getValue("modules").theme);s.setValue("theme",b);const M=ku.init(s,b.viewType,T.preset.permissions),D=ro.setupControllers(v,s,T,w,h,b,M);$A(b)&&((j=ro.createRoomNodeClient(s,v).initializeConnection(T.participant.name,i,!1,M))==null||j.catch(He=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:He})}));const{controllers:$}=yield D;return J_(),new ro(e,$,s)})}static setupControllers(s,t,e,r,i,n,o){return u(this,null,function*(){var L,k,Le;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),h=t.getValue("logger"),{viewType:g,mediaConstraints:{audio:T}}=n;t.setValue("viewType",g),t.setValue("defaults",O({mediaConfiguration:{audio:{enableHighBitrate:(L=T.enableHighBitrate)!=null?L:!1,enableStereo:(k=T.enableStereo)!=null?k:!1}}},l)),t.setValue("maxPreferredStreams",Te.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let v,E,w,b,M,D,$,V,H;const j=new RD(t,s),Z=new t1(s);t.setValue("connectedMeetingsSocketHandler",Z);const He=new Al(t,s),rs=new pr(t,s),Zr=new OD(s),is=new hT(t,s),I=new ND(t,s),y=new CD(s),_=yield Xr.init(t,is,d,o,n);t.setValue("selfController",_);const B=yield ff.init(t,_.self,is,j,i);if(c.participant&&(V=new mr(t,_.self,is)),(Le=c.e2ee)!=null&&Le.enabled&&c.e2ee.manager.init(h,t.getValue("peerSessionStore")),c.chat&&(E=yield ts.init(t,rs,_.self,V.participants)),c.internals&&(M=yield fh.init(t)),c.livestream&&n.viewType===ar.Livestream&&($=new wf(t,_.self,y)),c.poll&&(v=yield hf.init(t,_.self,He)),c.recording&&(D=new yf(t,_.self,is)),c.stage&&(w=new Tf(t,Zr,is,_.self,V.participants)),c.plugin){if(!V)throw new R("The plugin module cannot be initialized without the `participant` module","0102");const Ls=yield r;b=yield Cc.init(t,Ls,I,rs,E==null?void 0:E.chat,_.self,V.participants,i)}if(c.connectedMeetings&&(H=yield Nl.init(t)),c.pip){const Ls=yield ou._init(t,_.self);t.setValue("pip",Ls)}const Me={storesManager:new F0(t,I),pollController:v,selfController:_,metaController:B,chatController:E,stageController:w,pluginController:b,recordingController:D,internalsController:M,livestreamController:$,participantController:V,connectedMeetingsController:H};return{theme:n,permissions:o,controllers:Me}})}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return dT(s,{socket:t,peerId:e})}static createSocketService(s){var d;const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),o=((d=s.getValue("socketBaseURI"))!=null?d:"").includes("realtime.cloudflare.com")?[]:["PING"];return s.getValue("logger").info(`Socket service capabilities: ${JSON.stringify(o)}`),new Ic(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let Ll=ro;Mh([P.trace("Controller.init")],Ll,"init",1);Mh([P.trace("Controller.createRoomNodeClient")],Ll,"createRoomNodeClient",1);Mh([P.trace("Controller.createSocketService")],Ll,"createSocketService",1);class d1{constructor(){p(this,"battery");p(this,"logger");p(this,"init",t=>u(this,null,function*(){this.logger=t;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){t.error("Error getting battery",e)}}));p(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});p(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const og=new d1;function l1(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.realtime.cloudflare.com/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let n=ai.baseURI.prod;t&&(n=t);const o=`https://${Tn({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new R("Invalid auth token","0004")}}var Hr,qi,ji,vc,hl,MT;class u1{constructor(){m(this,hl);m(this,Hr,new Audio);m(this,qi,new MediaStream);m(this,ji,new Map);m(this,vc,void 0);a(this,Hr).srcObject=a(this,qi),a(this,Hr).autoplay=!0}playTracks(t){return u(this,null,function*(){return t.forEach(e=>{a(this,ji).has(e.id)||(a(this,qi).addTrack(e),a(this,ji).set(e.id,e))}),this.play()})}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,Hr).setSinkId(t)}removeTrack(t){const e=a(this,ji).get(t);e&&(a(this,qi).removeTrack(e),a(this,ji).delete(t))}play(){return u(this,null,function*(){return a(this,Hr).srcObject=a(this,qi),a(this,Hr).play().catch(t=>{x(this,hl,MT).call(this,t)})})}onError(t){f(this,vc,t)}}Hr=new WeakMap,qi=new WeakMap,ji=new WeakMap,vc=new WeakMap,hl=new WeakSet,MT=function(t){var e;(e=a(this,vc))==null||e.call(this,t)};var Gi;class h1 extends u1{constructor(){super();m(this,Gi,void 0);f(this,Gi,new Map)}addParticipantTrack(e,r){a(this,Gi).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,Gi).get(e);r&&this.removeTrack(r),a(this,Gi).delete(e)}}Gi=new WeakMap;var p1=Object.defineProperty,g1=Object.getOwnPropertyDescriptor,Vl=(s,t,e,r)=>{for(var i=r>1?void 0:r?g1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&p1(t,e,i),i},Be,Wi,Rg;let Kr=(Rg=class{constructor(t,e){m(this,Be,void 0);m(this,Wi,void 0);f(this,Wi,t),f(this,Be,e)}get peerId(){return a(this,Wi).getValue("peerId")}static initMedia(){return u(this,arguments,function*(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:Jr.v4(),n=Gr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new Of(n,o);return yield c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c})}static init(t){return u(this,null,function*(){var T,v,w,b,M,D,$,V,H;Te.init();const e=(v=(T=t==null?void 0:t.cachedUserDetails)==null?void 0:T.peerId)!=null?v:Jr.v4(),{authToken:r,baseURI:i}=t,E=l1(r,i),{meetingId:n}=E,o=Dc(E,["meetingId"]);if((w=o.baseURI)!=null&&w.includes("dyte.io"))throw new R("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Kr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");BT(l),og.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(M=(b=t.modules)==null?void 0:b.tracing)!=null?M:!0,($=(D=t==null?void 0:t.modules)==null?void 0:D.devTools)==null?void 0:$.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:G(O({},t),{authToken:`${(V=t.authToken)==null?void 0:V.slice(0,10)}...
12
- ${(H=t.authToken)==null?void 0:H.slice(-10)}`})});const h=yield Ll.init(c),g=new Kr(c,h);return c.setValue("meeting",g),g})}static setupContext(t,e,r,i){var d,l;const n=Gr.createContext(t,e),o=O(O({},__),e==null?void 0:e.modules),c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",w_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",As(e.cachedUserDetails)),n.setValue("sdkVersion","1.5.0-staging.5"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new h1),n}join(){return u(this,null,function*(){const{selfController:t}=a(this,Be);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){og.cleanup(),a(this,Wi).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Be);return e.leaveRoom(t)})}get participants(){var t;return(t=a(this,Be).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Be).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Be).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Be).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Be).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Be).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Be).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Be).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Be).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Be).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Be).stageController)==null?void 0:t.stage}get stores(){return a(this,Be).storesManager}get audio(){return a(this,Wi).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Be).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)})}},Be=new WeakMap,Wi=new WeakMap,Rg);Vl([at("0002"),gr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Kr.prototype,"join",1);Vl([at("0003")],Kr.prototype,"leave",1);Vl([at("0001"),gr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Kr,"init",1);Kr=Vl([at("0000")],Kr);const IT=Kr;module.exports=IT;
12
+ ${(H=t.authToken)==null?void 0:H.slice(-10)}`})});const h=yield Ll.init(c),g=new Kr(c,h);return c.setValue("meeting",g),g})}static setupContext(t,e,r,i){var d,l;const n=Gr.createContext(t,e),o=O(O({},__),e==null?void 0:e.modules),c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",w_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",As(e.cachedUserDetails)),n.setValue("sdkVersion","1.5.0-staging.8"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new h1),n}join(){return u(this,null,function*(){const{selfController:t}=a(this,Be);return t.self.roomJoined?null:t.joinRoom()})}leave(t){return u(this,null,function*(){og.cleanup(),a(this,Wi).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Be);return e.leaveRoom(t)})}get participants(){var t;return(t=a(this,Be).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Be).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Be).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Be).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Be).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Be).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Be).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Be).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Be).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Be).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Be).stageController)==null?void 0:t.stage}get stores(){return a(this,Be).storesManager}get audio(){return a(this,Wi).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Be).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)})}},Be=new WeakMap,Wi=new WeakMap,Rg);Vl([at("0002"),gr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Kr.prototype,"join",1);Vl([at("0003")],Kr.prototype,"leave",1);Vl([at("0001"),gr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Kr,"init",1);Kr=Vl([at("0000")],Kr);const IT=Kr;module.exports=IT;
package/dist/index.es.js CHANGED
@@ -28089,7 +28089,7 @@ let Jr = (kg = class {
28089
28089
  video: !0
28090
28090
  };
28091
28091
  return n.setValue("options", e), n.setValue("peerId", t), n.setValue("modules", o), n.setValue("sdkName", "web-core"), n.setValue("meetingId", r), n.setValue("apiBase", i.apiBase), n.setValue("baseURI", i.baseURI), n.setValue("userId", i.participantId), n.setValue("organizationId", i.orgId), n.setValue("authToken", e.authToken), n.setValue("overrides", (d = e.overrides) != null ? d : {}), n.setValue("env", __({ baseURI: i.baseURI })), n.setValue("defaults", c), n.setValue("onError", e.onError || (() => {
28092
- })), n.setValue("cachedUserDetails", Ms(e.cachedUserDetails)), n.setValue("sdkVersion", "1.5.0-staging.5"), (l = e.modules) != null && l.experimentalAudioPlayback && n.setValue("audioPlayback", new u1()), n;
28092
+ })), n.setValue("cachedUserDetails", Ms(e.cachedUserDetails)), n.setValue("sdkVersion", "1.5.0-staging.8"), (l = e.modules) != null && l.experimentalAudioPlayback && n.setValue("audioPlayback", new u1()), n;
28093
28093
  }
28094
28094
  join() {
28095
28095
  return u(this, null, function* () {
package/dist/index.rn.js CHANGED
@@ -9,4 +9,4 @@ ${this.message}`;try{let d=a&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("Cli
9
9
  `}this.midTransceiverMap.set(a.mid,a);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),a.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:a.sender,mid:a.mid}}addCustomEventListeners(){this.pc.addEventListener("datachannel",t=>{const{channel:e}=t;e.onmessage=r=>{this.safeEmit("datachannel",t.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}class cd extends mh{constructor(e,r){super(e);h(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new cd(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:a}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[a?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const p=c.sender.getParameters();p.encodings=r,await c.sender.setParameters(p)}const d=(p,f)=>{var x;const T=rs.parse(p),E=T.media[T.media.length-1],b=E.rtp.filter(N=>f.some($=>$.name===N.codec)),_=E.fmtp.filter(N=>b.some($=>$.payload===N.payload)),k=(x=E.rtcpFb)==null?void 0:x.filter(N=>b.some($=>$.payload===N.payload)),A=b.map(N=>N.payload);return T.media[T.media.length-1].rtp=b,T.media[T.media.length-1].fmtp=_,T.media[T.media.length-1].rtcpFb=k,T.media[T.media.length-1].payloads=A.join(" "),rs.write(T)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:p,enableStereo:f}=this,T=this.enableHighBitrate?f?128e3:64e3:f?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${f?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${T}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async p=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(p)}]`),await this.pc.setRemoteDescription(p),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const a=i.sender.getParameters(),o=a.encodings.length-1-r;a.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(a)}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=async i=>{const a=await i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(a)))}})}}class Th extends mh{static createFactory(t){return()=>new Th(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const a=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var f;const p=o.codecs.find(T=>T.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const T=((f=p.sdpFmtpLine)==null?void 0:f.split(";"))||[];T.push(...u.parameters);const E=[...new Set(T).values()];p.sdpFmtpLine=E.join(";")}c.push(p)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),a.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:p}=this,f=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${p?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${f}`)}return this.midTransceiverMap.set(a.mid,a),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),a.mid),sender:a.sender,mid:a.mid}}addCustomEventListeners(){this.pc.ondatachannel=t=>{const{channel:e}=t;e.onmessage=async r=>{const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",t.channel,i)}}}}function K0(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}var $o,bi,bs,Rd,_s,fr,Bo,_u,kd,bf,Md,_f;class z0 extends wl{constructor(e,r){var i;super(e);g(this,_s);g(this,Bo);g(this,kd);g(this,Md);h(this,"rtpReceiver");h(this,"id");h(this,"localId");h(this,"producerId");h(this,"producingTransportId");h(this,"mimeType");h(this,"track");h(this,"peerId");h(this,"appData");h(this,"transceiver");g(this,$o,void 0);g(this,bi,void 0);g(this,bs,void 0);g(this,Rd,void 0);this.id=r.id,this.localId=r.localId,m(this,$o,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,m(this,bs,!1),this.producerId=r.producerId,this.track=r.track,m(this,bi,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,L(this,kd,bf).call(this),m(this,Rd,e)}get closed(){return n(this,bs)}get kind(){return this.track.kind}get paused(){return n(this,bi)}close(e,r){n(this,bs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,n(this,_s,fr)),m(this,bs,!0),r&&(L(this,Md,_f).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(n(this,bs))throw new yt("closed");return n(this,$o).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",n(this,_s,fr)),n(this,bs)){this.logger.error("consumer::pause() | Consumer closed",n(this,_s,fr));return}m(this,bi,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",n(this,_s,fr)),n(this,bs)){this.logger.error("Consumer::resume() | Consumer closed",n(this,_s,fr));return}m(this,bi,!1),this.track.enabled=!0,this.safeEmit("resume")}}$o=new WeakMap,bi=new WeakMap,bs=new WeakMap,Rd=new WeakMap,_s=new WeakSet,fr=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Bo=new WeakSet,_u=function(){this.logger.debug('Consumer::track "ended" event',n(this,_s,fr)),this.safeEmit("trackended")},kd=new WeakSet,bf=function(){this.track.addEventListener("ended",L(this,Bo,_u).bind(this))},Md=new WeakSet,_f=function(){try{this.track.removeEventListener("ended",L(this,Bo,_u)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...n(this,_s,fr),error:e})}};var cs,ea,ta,_i,Jt,Ke,Dr,sa,Id,It,ss;class Y0 extends wl{constructor(e,r){var i,a;super(e);g(this,It);h(this,"id");h(this,"localId");g(this,cs,void 0);h(this,"kind");h(this,"appData");h(this,"rtpSender");g(this,ea,void 0);g(this,ta,void 0);g(this,_i,void 0);g(this,Jt,!1);g(this,Ke,void 0);g(this,Dr,void 0);g(this,sa,void 0);g(this,Id,void 0);this.id=r.id,this.localId=r.localId,m(this,Ke,r.track),this.kind=(i=r.track)==null?void 0:i.kind,m(this,Dr,r.disableTrackOnPause?!((a=r.track)!=null&&a.enabled):!1),m(this,sa,void 0),m(this,ea,r.stopTracks),m(this,ta,r.disableTrackOnPause),m(this,_i,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),m(this,cs,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),m(this,Id,e)}get closed(){return n(this,Jt)}get track(){return n(this,Ke)}get paused(){return n(this,Dr)}get maxSpatialLayer(){return n(this,sa)}async close(e){if(n(this,Jt))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,n(this,It,ss)),m(this,Jt,!0),this._destroyTrack(),e===dd){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await n(this,cs).stopSending(this.localId),{answer:a}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(a)}async getStats(){if(n(this,Jt))throw new yt("closed");return n(this,cs).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",n(this,It,ss)),n(this,Jt)&&this.logger.error("Producer::pause() | Producer closed",n(this,It,ss)),m(this,Dr,!0),n(this,Ke)&&n(this,ta)&&(n(this,Ke).enabled=!1),n(this,_i)&&n(this,cs).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",n(this,It,ss)),n(this,Jt)){this.logger.error("Producer::resume() | Producer closed",n(this,It,ss));return}m(this,Dr,!1),n(this,Ke)&&n(this,ta)&&(n(this,Ke).enabled=!0),n(this,_i)&&n(this,cs).replaceTrack(this.localId,n(this,Ke)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,n(this,It,ss)),n(this,Jt)){if(e&&n(this,ea))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...n(this,It,ss),error:r})}throw new yt("closed")}else if(e&&e.readyState==="ended")throw new yt("track ended");if(e===n(this,Ke)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,n(this,It,ss));return}(!n(this,_i)||!n(this,Dr))&&await n(this,cs).replaceTrack(this.localId,e),this._destroyTrack(),m(this,Ke,e),this._handleTrack()}async setMaxSpatialLayer(e){if(n(this,Jt))throw new yt("closed");if(this.kind!=="video")throw new go("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await n(this,cs).setMaxSpatialLayer(this.localId,e),m(this,sa,e)}async setRtpEncodingParameters(e){if(n(this,Jt))throw new yt("closed");if(typeof e!="object")throw new TypeError("invalid params");await n(this,cs).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,n(this,It,ss)),this.safeEmit("trackended",this.track.id)}_handleTrack(){n(this,Ke)&&n(this,Ke).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(n(this,Ke))try{n(this,Ke).removeEventListener("ended",this._onTrackEnded),n(this,ea)&&n(this,Ke).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...n(this,It,ss),error:r})}}}cs=new WeakMap,ea=new WeakMap,ta=new WeakMap,_i=new WeakMap,Jt=new WeakMap,Ke=new WeakMap,Dr=new WeakMap,sa=new WeakMap,Id=new WeakMap,It=new WeakSet,ss=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function wf(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Jl(s){return Math.random().toString(36).substring(2,2+s)}const xc=1;function Hp(s){const t=s;return delete t.payload._bolt,t}function Q0(s){return s.payload&&wf(s.payload)}function X0(s){var t,e;return Q0(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}var Or,Ad,wi;const ln=class extends st.EventEmitter{constructor(e,r,i,a){super();h(this,"channel");h(this,"queue");h(this,"serverProtocolVersion");g(this,Or,new Map);g(this,Ad,void 0);g(this,wi,void 0);h(this,"respond",(e,r,i=!1)=>{let a;i?a=ln.createErrorResponse(e,r):a=ln.createResponse(e,r),this.channel.send(JSON.stringify(a))});h(this,"notify",e=>{const r=ln.createNotification(e);this.channel.send(JSON.stringify(r))});h(this,"request",async e=>{const r=ln.createRequest(e),i=new Promise((a,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),a(u))},timer:setTimeout(()=>{this.queue.delete(d)&&o(new Error(`request timeout for message id: ${d}`))},2e4),cancel:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(u))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),i});h(this,"send",e=>{const r=JSON.stringify(e),i=16384;if(r.length>i){const a=i-200,o=Math.ceil(r.length/a),c=[];for(let l=0;l<o;l+=1){const u=l*a,p=(l+1)*a;c.push(r.slice(u,p))}const d=jr.v4();for(let l=0;l<o;l+=1){const u=c[l],f=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});n(this,wi).debug(`Sending message chunk over dc: ${f}`),this.channel.send(f)}}else n(this,wi).debug(`Sending message over dc: ${r}`),this.channel.send(r)});h(this,"processMessage",e=>{var i;n(this,Or).has(e.id)||n(this,Or).set(e.id,[]);const r=n(this,Or).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(a=>a===void 0)){const a=n(this,Or).get(e.id),o=a==null?void 0:a.reduce((d,l)=>d+l.chunk,"");n(this,Or).delete(e.id);const c=JSON.parse(o);if(!c.payload||!wf(c.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:c}});if(this.processBoltHandshake(c))return;if(this.serverProtocolVersion=(i=c.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(c))return c}});h(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,i=this.queue.get(r);return i?(n(this,wi).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(Hp(e)):i.resolve(Hp(e)),!0):!1});h(this,"processBoltHandshake",e=>{var r,i;return e.type==="_bolt"||e.type==="handshake"?(this.respond((i=(r=e.payload._bolt)==null?void 0:r.id)!=null?i:Jl(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=a,m(this,Ad,e),m(this,wi,e.getValue("logger")),this.channel=r,this.queue=new Map}};let Zr=ln;Or=new WeakMap,Ad=new WeakMap,wi=new WeakMap,h(Zr,"createRequest",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,_bolt:{id:Jl(8),type:"REQUEST",version:xc}}}}),h(Zr,"createResponse",(e,r)=>{var i;if((i=r.payload)!=null&&i._bolt)throw new Error("rpc fields are internal values");return{type:r.type,payload:{...r.payload,_bolt:{id:e,type:"RESPONSE",version:xc}}}}),h(Zr,"createNotification",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,bolt:{id:Jl(8),type:"NOTIFY",version:xc}}}}),h(Zr,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:xc}}}));const dd="transport closed";var Ci;const un=class extends wl{constructor(e,{id:r,direction:i,handlerFactory:a,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:p}){var b,_,k;super(e);h(this,"awaitQueue");h(this,"observer");h(this,"id");h(this,"serverId");h(this,"direction");h(this,"maxSctpMessageSize");h(this,"handler");h(this,"connectionState","new");h(this,"producers");h(this,"consumers");h(this,"datachannels");h(this,"connected",!1);h(this,"eventsDCReadyPromise");h(this,"eventsDCReadyPromiseResolver");h(this,"eventsDCFailureTimer");h(this,"transportConnectionPromise");h(this,"consumerTrackEvents");h(this,"unknownTracksMap");h(this,"appData");g(this,Ci,void 0);m(this,Ci,e);const f=e.getValue("logger");f.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const T=K0(l,{});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 bu(f,!0),this.handler=a(),this.handler.enableHighBitrate=(b=p==null?void 0:p.enableHighBitrate)!=null?b:!1,this.handler.enableStereo=(_=p==null?void 0:p.enableStereo)!=null?_:!1,this.handler.enableDtx=(k=p==null?void 0:p.enableDtx)!=null?k:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const E=3e4;this.transportConnectionPromise=new Promise(A=>{const x=setTimeout(()=>{f.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),A(!1)},E);this.once("connected",()=>{clearTimeout(x),A(!0)}),this.once("disconnect",()=>{clearTimeout(x),A(!1)}),this.once("close",()=>{clearTimeout(x),A(!1)})}),this.eventsDCReadyPromise=new Promise(A=>{this.eventsDCReadyPromiseResolver=A}),this.handler.on("@connectionstatechange",A=>{A!==this.connectionState&&(this.logger.debug(`connection state changed to ${A}`),this.connectionState=A,A==="connected"&&(this.connected=!0,this.emit("connected")),A==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(A==="failed"||A==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",A))}),this.handler.on("@icecandidate",({candidate:A})=>{this.closed||this.safeEmit("icecandidate",A)}),this.handler.on("dc_open",A=>{let x=this.datachannels.get(A.label);x||(x||(x=new Zr(n(this,Ci),A,A.label,this.serverId),this.datachannels.set(A.label,x)),this.eventsDCFailureTimer=setTimeout(()=>{A.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",A.label))},5e3))}),this.handler.on("datachannel",(A,x)=>{A.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const N=this.datachannels.get(A.label);if(!N){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:A.label,message:x}});return}try{const $=JSON.parse(x);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:$.id,count:$.count,chunkIndex:$.chunkIndex,chunk:$.chunk,transprtId:this.serverId}});const K=N.processMessage($);if(!K)return;this.logger.debug(`datachannel message with id:${$.id} on transport:${this.serverId}complete - ${JSON.stringify(K)}`),this.emit(`datachannel:${A.label}`,N.label,K)}catch($){this.logger.error("error parsing message",{error:$})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId=e}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(dd).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(dd)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new yt("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:a,answer:o}=await e(r);this.setServerId(a),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new yt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new go("not a sending Transport");if(r.readyState==="ended")throw new yt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new yr("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:a,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:p={}}=e;this.logger.debug(`produce() [track:${a.id}]`);const{producerId:f,localId:T,rtpSender:E}=await this.awaitQueue.push(async()=>{const{offerSdp:b,callback:_,sender:k,mid:A}=await this.handler.send({track:a,encodings:o,codecOptions:c,screenShare:p==null?void 0:p.screenShare}),{answer:x,producerId:N}=await r({offer:b,kind:a.kind,paused:l?!a.enabled||Object.hasOwn(a,"fakeTracks"):!1,appData:{...p||{},mid:A},codecOptions:c,producingTransportId:this.serverId}),$=await _(x);return{producerId:N,localId:$,rtpSender:k}},"Transport.produce");return this.createProducerObject({id:f,localId:T,track:a,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:p,handler:this.handler,rtpSender:E})}async createProducerObject(e){const r=new Y0(n(this,Ci),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new yt("closed");if(this.direction!=="recv")throw new go("not a receiving transport");if(!await this.transportConnectionPromise)throw new yr("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const a={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,p)=>{a[p]=this.createConsumerObjectAndWaitForTrack({...u,producerId:p})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(a).map(([u,p])=>p.then(f=>l.push(f)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=rs.parse(e.sdp),a={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(a[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),a}static setCodecAndFmtpMappings(e,r,i){const a=rs.parse(e.sdp);return a.media=a.media.map(c=>{if(r.includes(c.mid.toString())){const d={...c};return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),{...e,sdp:rs.write(a)}}static parseHeaderExtensionMappings(e){const r=rs.parse(e.sdp),i={};return r.media.forEach(a=>{i[a.mid]=a.ext}),i}static setHeaderExtensionMappings(e,r){const i=rs.parse(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:rs.write(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),a=un.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=un.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=await this.handler.pc.createOffer();this.logger.info("[SDP] Created offer for closing consumers",{sdp:c.sdp}),c=un.setCodecAndFmtpMappings(c,i,a),c=un.setHeaderExtensionMappings(c,o),this.logger.info("[SDP] Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),await this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=await r(e,c);this.logger.info("[SDP] Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("[SDP] Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}}async setRemoteOffer(e){try{this.logger.info("[SDP] Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("[SDP] Created answer corresponding to received offer",{sdp:r.sdp});const i=rs.parse(r.sdp);return i.media=i.media.map(a=>{if(a.type==="audio"){const o={...a},c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return a}),r.sdp=rs.write(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const a=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(a)});const o=this.consumerTrackEvents.get(a);o?(o(r,i),this.consumerTrackEvents.delete(a)):(this.logger.warn(`track event handler not found ${a}`),this.unknownTracksMap.set(a,e))}sendErrorOverDC(e,r,i){const a=this.getDatachannel(e);if(!a)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});a.respond(r,i,!0)}sendResponseOverDC(e,r,i){const a=this.getDatachannel(e);if(!a)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});a.respond(r,i)}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:a,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:p,mimeType:f}=e,T=`${c}:${p}`,E={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(b,_)=>{const k=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${T} producingPeerId: ${a}`),this.consumerTrackEvents.delete(T),E.isTimedout=!0,_(E)},5e3),A=(N,$)=>{try{if(N.readyState==="ended")clearTimeout(k),_(E);else{const K=N;K.enabled=!0,this.handler.midTransceiverMap.set($.mid,$);const Y=new z0(n(this,Ci),{id:r,localId:$.mid,transceiver:$,track:K,paused:d,producerId:i,producingPeerId:a,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:a},rtpReceiver:$.receiver,mimeType:f});this.consumers.set(r,Y),Y.once("close",()=>{this.consumers.delete(Y.id),this.handler.midTransceiverMap.delete($.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:p,appData:{screenShare:l},peerId:a,producerId:i}}),this.emit("newconsumer",Y),clearTimeout(k),b(Y)}}catch(K){this.logger.warn("error while creating consumer:",K),clearTimeout(k),_(E)}},x=this.unknownTracksMap.get(T);x?(this.logger.info(`track event already received [trackId: ${x.track.id}] [mid: ${x.transceiver.mid}]`),this.unknownTracksMap.delete(T),A(x.track,x.transceiver)):(this.logger.info(`Registering onTrack handler for key ${T} [producingPeerId: ${a}]`),this.consumerTrackEvents.set(T,A))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}async sendDataChannelMessage(e,r){const i=this.getDatachannel(e);if(!i)throw q0("DC_NOT_READY",`${e} datachannel not ready`);const a=(await i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(a)}`),a}};let wu=un;Ci=new WeakMap;function Z0(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=fg.getParser(t),r=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(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}var Gs,Ri;class eD{constructor(t,{handlerName:e,handlerFactory:r}={}){h(this,"handlerFactory");g(this,Gs,void 0);g(this,Ri,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),m(this,Gs,t),m(this,Ri,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)n(this,Ri).debug(`Device::constructor() | handler given: ${e}`);else if(e=Z0(n(this,Ri)),e)n(this,Ri).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=fh.createFactory(n(this,Gs));break;case"Safari12":this.handlerFactory=Th.createFactory(n(this,Gs));break;case"Firefox60":this.handlerFactory=cd.createFactory(n(this,Gs),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=cd.createFactory(n(this,Gs),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=jr.v4();return new wu(n(this,Gs),{id:e,...t,handlerFactory:this.handlerFactory})}}Gs=new WeakMap,Ri=new WeakMap;const tD=2e3;var ra,Ze,et,Ho,Fo,ki,ia,qo,na,Mi,ws,aa,Kc,jo,Cu,Dd,Cf,Go,Ru,Od,Rf,Nd,kf,Ld,Mf,Vd,If,xd,Af,Wo,ku,Jo,Mu;class sD extends st.EventEmitter{constructor(e,r){super();g(this,aa);g(this,jo);g(this,Dd);g(this,Go);g(this,Od);g(this,Nd);g(this,Ld);g(this,Vd);g(this,xd);g(this,Wo);g(this,Jo);h(this,"context");g(this,ra,void 0);g(this,Ze,void 0);g(this,et,void 0);g(this,Ho,void 0);g(this,Fo,void 0);g(this,ki,void 0);g(this,ia,void 0);g(this,qo,void 0);g(this,na,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,Mi,void 0);g(this,ws,"all");this.context=e,m(this,ki,r),m(this,ra,new eD(e)),m(this,ia,new J0(r)),m(this,qo,gs),n(this,aa,Kc).mediaState={send:{state:mn.NEW},recv:{state:mn.NEW}},ya(this.context,"forceRelay")&&m(this,ws,"relay"),this.logger.info(`ICE Transport Policy initially set to ${n(this,ws)}`),L(this,jo,Cu).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return n(this,ki)}get socketHandler(){return n(this,ia)}get sendTransport(){return n(this,Ze)}get recvTransport(){return n(this,et)}get events(){return n(this,qo)}set sendTransportConnectedCallback(e){m(this,Ho,e)}set recvTransportConnectedCallback(e){m(this,Fo,e)}async setupTransports(e){await L(this,Dd,Cf).call(this,e);let r,i;e.send&&(r=L(this,Go,Ru).call(this,n(this,Ze)).then(a=>{try{n(this,Ho).call(this,a)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=L(this,Go,Ru).call(this,n(this,et)).then(a=>{try{n(this,Fo).call(this,a)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,Ze);this.logger.info("Closing send transport",{transport:{id:a,serverId:o,type:c}}),n(this,Ze).close(),n(this,Ze).removeAllListeners(),m(this,Ze,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:a,serverId:o,direction:c}=n(this,et);this.logger.info("Closing recv transport",{transport:{id:a,serverId:o,type:c}}),(r=n(this,et))==null||r.close(),(i=n(this,et))==null||i.removeAllListeners(),m(this,et,void 0)}L(this,jo,Cu).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}ra=new WeakMap,Ze=new WeakMap,et=new WeakMap,Ho=new WeakMap,Fo=new WeakMap,ki=new WeakMap,ia=new WeakMap,qo=new WeakMap,na=new WeakMap,Mi=new WeakMap,ws=new WeakMap,aa=new WeakSet,Kc=function(){return this.context.getValue("connectionHandler")},jo=new WeakSet,Cu=function(){m(this,Mi,{send:void 0,recv:void 0})},Dd=new WeakSet,Cf=async function(e){var o,c,d,l,u,p,f,T;ya(this.context,"forceRelay")&&m(this,ws,"relay"),this.logger.info(`ICE Transport Policy set to ${n(this,ws)}`);const a=await ht().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));e.send&&L(this,Nd,kf).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(f=(p=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:p.enableStereo)!=null?f:!1,enableDtx:!1},iceTransportPolicy:n(this,ws)}),e.recv&&L(this,Ld,Mf).call(this,{iceServers:a,additionalSettings:{encodedInsertableStreams:(T=this.context.getValue("modules").e2ee)==null?void 0:T.enabled},iceTransportPolicy:n(this,ws)})},Go=new WeakSet,Ru=async function(e){const{id:r,serverId:i,direction:a}=e;L(this,Vd,If).call(this,e);try{return await Pf(async(c,d)=>{c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:a}});try{if(e.closed)throw new yr("Cannot reconnect closed transport");await L(this,Od,Rf).call(this,e)}catch(l){if(l instanceof yr){d(l);return}throw this.logger.error("Failed to connect transport, retrying",{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect send transport after retry: ${e.id}`,{error:o,transport:{id:r,serverId:i,type:a}}),e.close(),e.removeAllListeners(),o}},Od=new WeakSet,Rf=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!n(this,ki).isConnected)throw new yr("Socket is not connected");if(e.connectionState==="closed")throw new yr("Transport is closed");try{await e.connect(a=>L(this,xd,Af).call(this,i,a)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(a){throw n(this,na).transportFailureCount[i]+=1,a.message==="ice connection failed"?new yr(a.message):a}},Nd=new WeakSet,kf=function(e){var r,i;if(n(this,Ze)&&n(this,Ze).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=n(this,Ze))==null?void 0:r.id,serverId:(i=n(this,Ze))==null?void 0:i.serverId,type:"send"}});return}m(this,Ze,n(this,ra).createTransport({...e,direction:"send"})),this.context.getValue("callstats").configureSendTransport(n(this,Ze))},Ld=new WeakSet,Mf=function(e){var r,i;if(n(this,et)&&n(this,et).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=n(this,et))==null?void 0:r.id,serverId:(i=n(this,et))==null?void 0:i.serverId,type:"recv"}});return}m(this,et,n(this,ra).createTransport({...e,direction:"recv"})),this.context.getValue("callstats").configureRecvTransport(n(this,et))},Vd=new WeakSet,If=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",async a=>{L(this,Jo,Mu).call(this,{state:a,direction:r}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:a}});const o=()=>{const c=n(this,Mi)[r];c!==void 0&&(clearTimeout(c),n(this,Mi)[r]=void 0)};switch(a){case"connected":o(),n(this,na).lastConnectionTime=performance.now();break;case"disconnected":n(this,Mi)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await L(this,Wo,ku).call(this,e.direction)},tD);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await L(this,Wo,ku).call(this,e.direction);break}}),e.on("icecandidate",async a=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:a})}),e.on("datachannel:events",async(a,o)=>{var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:a,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(a,X0(o),l);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(c=o.payload)==null?void 0:c.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(l){this.logger.error(`Unable to handle the incoming datachannel message on channel ${a}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s"),this.handleErrors("reconnectRecvTransport"))})},xd=new WeakSet,Af=async function(e,r){const i=e==="recv";try{const{sdp:a,type:o}=r,c={consuming:i,description:{sdp:a,type:o,target:i?ar.SUBSCRIBER:ar.PUBLISHER},producers:[]};return n(this,ia).connectTransport(c)}catch(a){throw this.logger.error(`Error in ${e} transport connection:`,{error:a}),a}},Wo=new WeakSet,ku=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),n(this,ki).isConnected&&n(this,na).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),m(this,ws,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:n(this,Ze)}),this.context.getValue("peerSessionStore").emit(w.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:n(this,et)}),this.context.getValue("peerSessionStore").emit(w.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}L(this,Jo,Mu).call(this,{state:mn.CONNECTED,direction:e})},Jo=new WeakSet,Mu=function(e){const{state:r,direction:i}=e;n(this,aa,Kc).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(w.TRANSPORT_STATE_UPDATE,{transport:i,...n(this,aa,Kc).mediaState[i]})};var Ud,Kt;class rD{constructor(t,e,r,i,a){g(this,Ud,void 0);g(this,Kt,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=a,m(this,Ud,t),m(this,Kt,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:p}=d,f={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:p,...f})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),a=new Map;t.forEach(d=>a.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=a.get(d);if(!u)return;if(l.errorCode){n(this,Kt).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let p={};try{p=JSON.parse(l.producerState.appData)}catch(f){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:p})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{n(this,Kt).info("Negotiating socket consumer",{transport:this.recvTransport}),n(this,Kt).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:ar.SUBSCRIBER}};return n(this,Kt).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,z_.toBinary(r)),n(this,Kt).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){n(this,Kt).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return{};const e=async(r,i)=>{const a=r.map(l=>l.localId);n(this,Kt).info(`Closing consumers: ${JSON.stringify(a)}`);const o={description:{sdp:i.sdp,type:i.type,target:ar.SUBSCRIBER},consumerIds:a,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=PC.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};return await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"ConsumerStrategy.close",{consumersLength:t.length}),{}}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(a=>a&&a.id);i.forEach(({id:a,producingTransportId:o,localId:c})=>{r.requests.push({producerId:a,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),n(this,Kt).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:a})=>a)})}}Ud=new WeakMap,Kt=new WeakMap;class Sh{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return rs.parse(t).media.filter(a=>e==="video"?a.type==="video":a.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:a,producingTransportId:o}){var p,f;const c=Sh.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:ar.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(p=i.screenShare)!=null?p:!1,mimeType:`${e}/${(f=a[0])==null?void 0:f.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}var Ii,Nr,oa,Ko,Cs,$d,Ws,ca,zo,Iu,Bd,Df,Hd,Of,Fd,Nf,qd,Lf;class iD extends sD{constructor(e,r){super(e,r);g(this,zo);g(this,Bd);g(this,Hd);g(this,Fd);g(this,qd);g(this,Ii,void 0);g(this,Nr,void 0);g(this,oa,void 0);g(this,Ko,void 0);g(this,Cs,void 0);g(this,$d,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,Ws,[]);g(this,ca,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{m(this,Ko,new Sh(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{n(this,oa).clear(),m(this,Cs,new rD(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return n(this,Ii)}get consumers(){return n(this,Nr)}get producerIdToConsumerIdMap(){return n(this,oa)}get logger(){return this.context.getValue("logger")}reset(){m(this,Ii,new Map),m(this,Nr,new Map),m(this,oa,new Map)}async createProducer(e,r){var i,a;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const o=await this.sendTransport.produce(e,L(this,Bd,Df).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_PRODUCER,o),L(this,Hd,Of).call(this,o,r),o}catch(o){throw this.logger.error(`Failed to create ${((a=e==null?void 0:e.track)==null?void 0:a.kind)||"unknown"} producer`,{error:o}),n(this,$d).producerCreationFailureCount+=1,o}}async closeProducer(e,r){var a;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),(a=this.context.getValue("modules").e2ee)!=null&&a.enabled&&this.context.getValue("peerSessionStore").emit(w.E2EE_INACTIVE_PRODUCER,i)}catch(o){this.logger.error("Failed to close producer on server",{error:o,producer:i})}}closeAllProducers(){return Promise.all(Array.from(n(this,Ii).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){n(this,ca)||clearTimeout(n(this,ca)),m(this,Ws,n(this,Ws).concat(e)),await L(this,zo,Iu).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!n(this,Cs))return;const r=e.map(a=>this.consumers.get(a)).filter(a=>a!==void 0);if(r.length===0)return;const{failedConsumers:i}=await n(this,Cs).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(n(this,Nr).keys()))}async switchConsumersToLayer(e,r){n(this,Cs).switchConsumersToLayer(e,r)}}Ii=new WeakMap,Nr=new WeakMap,oa=new WeakMap,Ko=new WeakMap,Cs=new WeakMap,$d=new WeakMap,Ws=new WeakMap,ca=new WeakMap,zo=new WeakSet,Iu=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=n(this,Ws).splice(0,n(this,Ws).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),a=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(a.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(a,L(this,Fd,Nf).bind(this),n(this,Cs).negotiate.bind(n(this,Cs)));if(o.forEach(L(this,qd,Lf).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);m(this,Ws,n(this,Ws).concat(d)),m(this,ca,setTimeout(L(this,zo,Iu).bind(this),e))}}catch(i){if(this.logger.error("failed to consume on transport",{error:i}),i.errorCode==="internal_error"&&i.errorDescription==="Backend error"||i.errorCode==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:i.errorCode,message:i.errorDescription}});try{this.stopTransports({recv:!0})}catch(a){}await this.setupTransports({recv:!0})}}},Bd=new WeakSet,Df=function(e){return n(this,Ko).create(e)},Hd=new WeakSet,Of=function(e,r){e.on("close",async(i,a)=>{const{offer:o,reason:c}=i;if(this.logger.info("producer::closing",{debuggingHint:c,producer:{...e,status:"closing"}}),c!==dd){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:ar.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),u={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),a({answer:u})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),n(this,Ii).set(e.id,e)},Fd=new WeakSet,Nf=async function(e){try{return await this.recvTransport.canConsume(),await n(this,Cs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},qd=new WeakSet,Lf=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),n(this,Nr).delete(e.id),this.context.getValue("peerSessionStore").emit(w.CONSUMER_CLOSED,{id:e.id})}),n(this,Nr).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(w.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};var Yo,Qo,Xo,da,la,ua,Zo,ec,ha,ft,ds,ls,Ai,Di,Js,tc,jd,Vf,Gd,xf,Wd,Uf,Jd,$f;const Kd=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:a=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){g(this,jd);g(this,Gd);g(this,Yo,void 0);g(this,Qo,void 0);g(this,Xo,void 0);g(this,da,void 0);g(this,la,void 0);g(this,ua,void 0);g(this,Zo,void 0);g(this,ec,void 0);g(this,ha,void 0);g(this,ft,void 0);g(this,ds,void 0);g(this,ls,!1);g(this,Ai,0);g(this,Di,0);g(this,Js,[]);g(this,tc,void 0);m(this,da,t),m(this,ft,t),m(this,Yo,e),m(this,Qo,r),m(this,Xo,i),m(this,la,a),m(this,ua,o),m(this,Zo,c),m(this,ec,d),m(this,ha,l),m(this,tc,u),m(this,ds,t/2)}get voiceDetected(){return n(this,ls)}processAudioChunk(t){var o,c;const e=L(o=Kd,Wd,Uf).call(o,t),r=L(c=Kd,Jd,$f).call(c,t);return L(this,jd,Vf).call(this,e),e/n(this,ds)>n(this,ha)&&e>n(this,ft)&&r>n(this,Yo)?(m(this,Ai,n(this,Ai)+1),m(this,Di,n(this,Xo)),n(this,Ai)>=n(this,Qo)&&m(this,ls,!0)):(m(this,Ai,0),n(this,Di)>0?m(this,Di,n(this,Di)-1):n(this,ls)&&m(this,ls,!1),n(this,ls)||L(this,Gd,xf).call(this,e)),{energy:e,isVoice:n(this,ls)}}reset(){m(this,ls,!1),m(this,Ai,0),m(this,Di,0),m(this,ft,n(this,da)),m(this,ds,n(this,da)/2),m(this,Js,[])}getThresholdInfo(){return{currentEnergyThreshold:n(this,ft),backgroundNoiseEnergy:n(this,ds),energyRatioThreshold:n(this,ha)}}};let Ya=Kd;Yo=new WeakMap,Qo=new WeakMap,Xo=new WeakMap,da=new WeakMap,la=new WeakMap,ua=new WeakMap,Zo=new WeakMap,ec=new WeakMap,ha=new WeakMap,ft=new WeakMap,ds=new WeakMap,ls=new WeakMap,Ai=new WeakMap,Di=new WeakMap,Js=new WeakMap,tc=new WeakMap,jd=new WeakSet,Vf=function(t){n(this,ls)?m(this,ft,n(this,ua)*n(this,ft)+(1-n(this,ua))*t):m(this,ft,n(this,la)*n(this,ft)+(1-n(this,la))*n(this,ds)),m(this,ft,Math.max(n(this,Zo),Math.min(n(this,ec),n(this,ft))))},Gd=new WeakSet,xf=function(t){if(t<n(this,ft)*1.2)if(n(this,Js).push(t),n(this,Js).length>n(this,tc)&&n(this,Js).shift(),n(this,Js).length>=10){const e=[...n(this,Js)].sort((i,a)=>i-a),r=Math.floor(e.length/2);m(this,ds,e[r])}else m(this,ds,.95*n(this,ds)+.05*t)},Wd=new WeakSet,Uf=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Jd=new WeakSet,$f=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},g(Ya,Wd),g(Ya,Jd);var sc;class Fp{constructor(t){h(this,"RNAudioSampleHandler");g(this,sc,void 0);m(this,sc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return n(this,sc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}sc=new WeakMap;var rc;class qp{constructor(t){h(this,"audioContext");h(this,"analyser");g(this,rc,void 0);m(this,rc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return n(this,rc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}rc=new WeakMap;class nD{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const aD=60,oD=400;var Ks,zs,Ys,ic,pa,ga,Lr,Oi,ma,Ni,Qs,Rs,zd,Bf,nc,Au,Yd,Hf,Qd,Ff;const oo=class{constructor(t,e){g(this,zd);g(this,Yd);g(this,Ks,void 0);g(this,zs,void 0);g(this,Ys,void 0);g(this,ic,void 0);g(this,pa,void 0);g(this,ga,void 0);g(this,Lr,void 0);g(this,Oi,void 0);g(this,ma,void 0);g(this,Ni,void 0);g(this,Qs,void 0);g(this,Rs,void 0);this.reportRequest=e,m(this,Ni,t),m(this,ga,new Ya);const{isReactNative:r}=navigator;m(this,Qs,r?new Fp(n(this,Ni)):new qp(n(this,Ni))),m(this,Rs,r?nD:Uc)}get logger(){return n(this,Ni).getValue("logger")}set producerId(t){m(this,Ys,t)}set audioTrack(t){m(this,ic,t),n(this,Qs)instanceof qp&&(n(this,Qs).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${n(this,Ys)}`),n(this,Ks)&&n(this,Rs).clearInterval(n(this,Ks)),m(this,Ks,n(this,Rs).setInterval(async()=>{var i;if(!n(this,ic)||!n(this,Ys))return;const{energy:t}=L(this,zd,Bf).call(this),e=L(i=oo,nc,Au).call(i,t);let r=.9;n(this,ma)!==e&&n(this,ma)?r=.9:e?r=.3:r=.5,m(this,pa,(n(this,pa)||0)*(1-r)+t*r)},aD)),n(this,zs)&&n(this,Rs).clearInterval(n(this,zs)),m(this,zs,n(this,Rs).setInterval(L(this,Yd,Hf).bind(this),oD))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${n(this,Ys)}`),n(this,Ks)&&(n(this,Rs).clearInterval(n(this,Ks)),m(this,Ks,void 0)),n(this,zs)&&(n(this,Rs).clearInterval(n(this,zs)),m(this,zs,void 0))}catch(t){}n(this,ga).reset(),n(this,Qs)instanceof Fp&&n(this,Qs).stop()}};let Qa=oo;Ks=new WeakMap,zs=new WeakMap,Ys=new WeakMap,ic=new WeakMap,pa=new WeakMap,ga=new WeakMap,Lr=new WeakMap,Oi=new WeakMap,ma=new WeakMap,Ni=new WeakMap,Qs=new WeakMap,Rs=new WeakMap,zd=new WeakSet,Bf=function(){var o;const{samples:t}=n(this,Qs),{energy:e,isVoice:r}=n(this,ga).processAudioChunk(t),i=L(o=oo,Qd,Ff).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!n(this,Lr)||i<n(this,Lr))&&m(this,Lr,i),(!n(this,Oi)||i>n(this,Oi))&&m(this,Oi,i),{energy:(i-n(this,Lr))/(n(this,Oi)-n(this,Lr))*10||0,isVoice:r})},nc=new WeakSet,Au=function(t){return t<5},Yd=new WeakSet,Hf=function(t=n(this,pa)){var r;if(!n(this,Ys)||!t)return;const e={producerId:n(this,Ys),energy:Math.round(t),silent:L(r=oo,nc,Au).call(r,t)};m(this,ma,e.silent),this.reportRequest(e)},Qd=new WeakSet,Ff=function(t){const e=Math.log10(t);return Math.round(e)},g(Qa,nc),g(Qa,Qd);var cD=Object.defineProperty,dD=Object.getOwnPropertyDescriptor,ne=(s,t,e,r)=>{for(var i=r>1?void 0:r?dD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&cD(t,e,i),i},ac,oc,tt,q,Xd,dt,Li,Vi,xi,cc,zt,Xs,lt,Tt,Vr,nn,Zd,qf,el,jf,tl,Gf,dc,Du,sl,Wf,rl,Jf,ut,_t,Ui,Xa,il,Kf,nl,zf,al,Yf;class se{constructor(t,e){g(this,Vr);g(this,Zd);g(this,el);g(this,tl);g(this,dc);g(this,sl);g(this,rl);g(this,ut);g(this,Ui);g(this,il);g(this,nl);g(this,al);h(this,"context");h(this,"authToken");h(this,"e2ee");g(this,ac,void 0);g(this,oc,void 0);g(this,tt,void 0);g(this,q,void 0);g(this,Xd,void 0);g(this,dt,void 0);g(this,Li,void 0);g(this,Vi,void 0);g(this,xi,void 0);g(this,cc,void 0);g(this,zt,null);g(this,Xs,void 0);g(this,lt,void 0);g(this,Tt,void 0);var i,a;this.context=t;const{socket:r}=e;this.mediaJoined=!1,m(this,tt,r),m(this,Li,!1),m(this,q,new iD(t,r)),m(this,dt,n(this,q).events),m(this,Xs,new Set),m(this,lt,new Map),m(this,Vi,!1),m(this,xi,new bu(t.getValue("logger"))),m(this,Tt,new Qa(this.context,n(this,q).socketHandler.audioActivity.bind(n(this,q).socketHandler))),this.e2ee=(a=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?a:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),m(this,cc,sh(async()=>{if(!n(this,Vr,nn).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(n(this,oc),n(this,ac),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(w.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return n(this,Vr,nn).mediaJoined}set mediaJoined(t){n(this,Vr,nn).mediaJoined=t}reset(){n(this,q).closeAllProducers(),n(this,q).closeAllConsumers(),n(this,lt).clear(),n(this,Xs).clear(),m(this,zt,null),n(this,xi).stop(),n(this,q).stopAllTransports(),n(this,q).reset(),m(this,xi,new bu)}async joinRoom(t,e,r=!1,i=!1,a={}){n(this,Vr,nn).mediaJoinAttempted=!0,m(this,Li,!0),r&&this.reset();try{return await n(this,xi).push(()=>L(this,Zd,qf).call(this,t,e,i,a),"joinRoom")}catch(o){return this.logger.error("Error in room joining process",{error:o}),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return n(this,zt)?n(this,zt):(m(this,zt,(async()=>{try{await L(this,dc,Du).call(this,t,e,r,i)}catch(a){throw m(this,zt,null),a}})()),n(this,zt))}getConsumers(){return n(this,q).consumers}getProducers(){return n(this,q).producers}async leaveRoom(){n(this,q).stopAllTransports(),m(this,Vi,!1),n(this,Vr,nn).mediaJoinAttempted=!1;const t={closeRoom:!1};n(this,tt).sendMessagePromise(n(this,dt).leaveRoom,yw.toBinary(t)).then(r=>{var i;(i=cC.fromBinary(r.payload))!=null&&i.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(r=>{this.logger.error("error on sending leave room request",{error:r})}),this.context.getValue("callstats").callEnded(),await this.context.getValue("telemetry").destruct()}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():n(this,q).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const a=n(this,q).producerIdToConsumerIdMap.get(i.producerId);return a?(r.push(a),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);await n(this,q).closeConsumers(e)}async _shareWebcam(t){var u,p,f,T;const e=Ee.WEBCAM,r=L(this,ut,_t).call(this,e);if(r){const E=await r;if(n(this,q).producers.has(E)){const b=n(this,q).producers.get(E);if(!b.closed)return await b.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=L(this,al,Yf).call(this,t),a=ya(this.context,"disableSimulcast"),o=(p=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:p.simulcastConfig;a||o&&o.disable||!((T=(f=this.context)==null?void 0:f.getValue("theme"))!=null&&T.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=YA(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),n(this,lt).delete(e)},l=n(this,q).createProducer(i,d);return L(this,Ui,Xa).call(this,e,l.then(E=>E.id)),l.then(E=>E.track)}async shareWebcam(t){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ge.isElectron()},stopTracks:!1},a=()=>{this.logger.info("Disabling screenShare due to the producer closure"),n(this,lt).delete(Ee.SCREENSHARE_VIDEO),n(this,lt).delete(Ee.SCREENSHARE_AUDIO)},o=n(this,q).createProducer(i,a);L(this,Ui,Xa).call(this,Ee.SCREENSHARE_VIDEO,o.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:ge.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=n(this,q).createProducer(d,l),L(this,Ui,Xa).call(this,Ee.SCREENSHARE_AUDIO,c.then(u=>u.id))}await Promise.all([o,c||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new yt("track undefined");const e=L(this,ut,_t).call(this,Ee.MIC);if(e){const o=await e;if(n(this,q).producers.has(o)){const c=n(this,q).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),n(this,Tt)&&(n(this,Tt).audioTrack=t,n(this,Tt).producerId=o,n(this,Tt).start());return}await n(this,q).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=L(this,nl,zf).call(this,t),i=()=>{n(this,lt).delete(Ee.MIC)},a=n(this,q).createProducer(r,i);L(this,Ui,Xa).call(this,Ee.MIC,a.then(o=>o.id)),await a.then(o=>{n(this,Tt)&&(n(this,Tt).audioTrack=o.track,n(this,Tt).producerId=o.id,n(this,Tt).start())})}catch(e){throw new C(e)}}async pauseMic(){var i;const t=await L(this,ut,_t).call(this,Ee.MIC),e=n(this,q).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=n(this,Tt))==null||i.stop();const r={producerId:e.id,pause:!0};n(this,tt).sendMessage(n(this,dt).toggleProducer,Ac.toBinary(r))}async pauseWebcam(){const t=await L(this,ut,_t).call(this,Ee.WEBCAM),e=n(this,q).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};n(this,tt).sendMessage(n(this,dt).toggleProducer,Ac.toBinary(r))}async resumeMic(){const t=await L(this,ut,_t).call(this,Ee.MIC),e=n(this,q).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};n(this,tt).sendMessage(n(this,dt).toggleProducer,Ac.toBinary(r))}async resumeWebcam(t=Ee.WEBCAM){const e=await L(this,ut,_t).call(this,t),r=n(this,q).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(w.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};n(this,tt).sendMessage(n(this,dt).toggleProducer,Ac.toBinary(i))}async disableWebcam(){const t=Ee.WEBCAM,e=await L(this,ut,_t).call(this,t);L(this,il,Kf).call(this,t),e&&await n(this,q).closeProducer(e)}async disableMic(){var e;const t=await L(this,ut,_t).call(this,Ee.MIC);t&&await n(this,q).closeProducer(t),(e=n(this,Tt))==null||e.stop(),n(this,lt).delete(Ee.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await L(this,ut,_t).call(this,Ee.SCREENSHARE_VIDEO),e=await L(this,ut,_t).call(this,Ee.SCREENSHARE_AUDIO);t&&await n(this,q).closeProducer(t),e&&await n(this,q).closeProducer(e),n(this,Xs).clear(),n(this,lt).delete(Ee.SCREENSHARE_VIDEO),n(this,lt).delete(Ee.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await L(this,ut,_t).call(this,Ee.WEBCAM);await n(this,q).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await L(this,ut,_t).call(this,Ee.SCREENSHARE_VIDEO);await n(this,q).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await n(this,q).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};n(this,q).socketHandler.kickPeer(e)}kickAll(){n(this,q).socketHandler.kickAll()}async muteAll(t){if(!await n(this,q).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await n(this,q).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await n(this,q).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await n(this,q).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await n(this,tt).sendMessagePromise(n(this,dt).globalPinPeer,Nw.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&n(this,q).producers.get(t.producerId)&&n(this,Xs).add(t.consumerPeerId),n(this,Xs).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));n(this,q).switchConsumersToLayer(r,e)}async handleSocketEvents(){n(this,tt).on(n(this,dt).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=UC.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===ir.AUDIO?"audio/opus":"video/VP8"),this.logger.info(`producer created broadcast: ${e}, producer state: ${r}`),this.context.getValue("peerSessionStore").emit(w.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===ir.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),n(this,tt).on(n(this,dt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:a,producerId:o,screenShare:c}}=Tp.fromBinary(t);if(c)return;const d=i===ir.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${a} payload: ${JSON.stringify(Tp.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&a&&this.context.getValue("peerSessionStore").emit(d==="audio"?w.MUTE_SELF:w.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(w.PRODUCER_TOGGLE,{peerId:e,producerId:o,paused:a,kind:d}),Array.from(this.getConsumers().values()).filter(u=>u.producerId===o).forEach(u=>{u.kind==="video"&&a||u.paused!==a&&(this.logger.debug(`consumer state mismatched for ${u.id}. updating consumer pause state ${u.paused} to ${a}`),a?(u.pause(),this.context.getValue("peerSessionStore").emit(w.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(w.CONSUMER_RESUMED,{id:u.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),n(this,tt).on(n(this,dt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=ru.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),n(this,Xs).delete(e),n(this,q).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(w.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),n(this,tt).on(n(this,dt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=HC.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(w.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=n(this,q).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),n(this,q).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),n(this,q).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(w.CONSUMER_CLOSED,{id:i})}).catch(a=>{this.logger.error("error closing consumer",{error:a})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),n(this,tt).on(n(this,dt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!n(this,Li)&&!n(this,Vi)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(w.ROOM_NODE_DISCONNECTED),n(this,cc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=n(this,q).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(w.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(n(this,q).producers.values()).find(a=>a.id===r);i&&this.context.getValue("peerSessionStore").emit(w.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}ac=new WeakMap,oc=new WeakMap,tt=new WeakMap,q=new WeakMap,Xd=new WeakMap,dt=new WeakMap,Li=new WeakMap,Vi=new WeakMap,xi=new WeakMap,cc=new WeakMap,zt=new WeakMap,Xs=new WeakMap,lt=new WeakMap,Tt=new WeakMap,Vr=new WeakSet,nn=function(){return this.context.getValue("connectionHandler")},Zd=new WeakSet,qf=async function(t,e,r,i){m(this,oc,t);try{n(this,zt)?await n(this,zt):await L(this,dc,Du).call(this,t,e,r,i),L(this,tl,Gf).call(this,e);const{joined:a,error:o}=await L(this,el,jf).call(this);return{roomJoined:a,error:o}}catch(a){return this.logger.error("Failed to complete room join",{error:a}),{roomJoined:!1,error:a}}finally{m(this,zt,null)}},el=new WeakSet,jf=async function(){try{this.mediaJoined=!0;const{roomState:t}=await n(this,q).socketHandler.notifySelfJoinComplete();return m(this,ac,t.roomUuid),m(this,Vi,!0),m(this,Li,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},tl=new WeakSet,Gf=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...ge.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},dc=new WeakSet,Du=async function(t,e,r,i){try{const a=L(this,sl,Wf).call(this);await L(this,rl,Jf).call(this,t,e,r,a),await n(this,q).setupTransports({send:!0,recv:!0})}catch(a){throw this.logger.error("Failed to initialize connection",{error:a}),a}},sl=new WeakSet,Wf=function(){const t=W0("video/VP8");return m(this,Xd,t),t},rl=new WeakSet,Jf=async function(t,e,r,i){await Pf(async(a,o)=>{if(!n(this,tt).isConnected){o(new Error("Socket is not connected"));return}a>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${a}`});try{await n(this,q).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},ut=new WeakSet,_t=function(t){return n(this,lt).get(t)},Ui=new WeakSet,Xa=function(t,e){return n(this,lt).set(t,e)},il=new WeakSet,Kf=function(t){return n(this,lt).delete(t)},nl=new WeakSet,zf=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},al=new WeakSet,Yf=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}};ne([y.trace("MediaNodeClient.reset")],se.prototype,"reset",1);ne([y.trace("MediaNodeClient.joinRoom")],se.prototype,"joinRoom",1);ne([y.trace("MediaNodeClient.leaveRoom")],se.prototype,"leaveRoom",1);ne([y.trace("MediaNodeClient.activatePeers")],se.prototype,"activatePeers",1);ne([y.trace("MediaNodeClient.createConsumers")],se.prototype,"createConsumers",1);ne([y.trace("MediaNodeClient.closeConsumers")],se.prototype,"closeConsumers",1);ne([y.trace("MediaNodeClient._shareWebcam")],se.prototype,"_shareWebcam",1);ne([y.trace("MediaNodeClient.shareWebcam")],se.prototype,"shareWebcam",1);ne([y.trace("MediaNodeClient.shareScreen")],se.prototype,"shareScreen",1);ne([y.trace("MediaNodeClient.shareMic")],se.prototype,"shareMic",1);ne([y.trace("MediaNodeClient.pauseMic")],se.prototype,"pauseMic",1);ne([y.trace("MediaNodeClient.pauseWebcam")],se.prototype,"pauseWebcam",1);ne([y.trace("MediaNodeClient.resumeMic")],se.prototype,"resumeMic",1);ne([y.trace("MediaNodeClient.resumeWebcam")],se.prototype,"resumeWebcam",1);ne([y.trace("MediaNodeClient.disableWebcam")],se.prototype,"disableWebcam",1);ne([y.trace("MediaNodeClient.disableMic")],se.prototype,"disableMic",1);ne([y.trace("MediaNodeClient.disableScreenShare")],se.prototype,"disableScreenShare",1);ne([y.trace("MediaNodeClient.muteSelf")],se.prototype,"muteSelf",1);ne([y.trace("MediaNodeClient.resetVideoProducers")],se.prototype,"resetVideoProducers",1);ne([y.trace("MediaNodeClient.changeDisplayName")],se.prototype,"changeDisplayName",1);ne([y.trace("MediaNodeClient.kickPeer")],se.prototype,"kick",1);ne([y.trace("MediaNodeClient.kickAllPeers")],se.prototype,"kickAll",1);ne([y.trace("MediaNodeClient.muteAll")],se.prototype,"muteAll",1);ne([y.trace("MediaNodeClient.muteAllVideo")],se.prototype,"muteAllVideo",1);ne([y.trace("MediaNodeClient.disableAudio")],se.prototype,"disableAudio",1);ne([y.trace("MediaNodeClient.disableVideo")],se.prototype,"disableVideo",1);ne([y.trace("MediaNodeClient.pinPeer")],se.prototype,"pinPeer",1);ne([y.trace("MediaNodeClient.validateScreenShare")],se.prototype,"validateScreenShare",1);function Qf(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new se(s,t);return s.setValue("roomNodeClient",r),r}function Xf(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var lD=Object.defineProperty,uD=Object.getOwnPropertyDescriptor,Zi=(s,t,e,r)=>{for(var i=r>1?void 0:r?uD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&lD(t,e,i),i},$i,us,X,St,Ut,hg;const Zf=(hg=class{constructor(s,t,e,r){g(this,St);h(this,"self");h(this,"authToken");g(this,$i,void 0);h(this,"viewType");g(this,us,void 0);g(this,X,void 0);const{socket:i}=e,a=s.getValue("authToken");this.self=t,m(this,X,s),this.viewType=r,this.authToken=a,m(this,$i,i),m(this,us,e),this.setupEvents()}get peerId(){return n(this,X).getValue("peerId")}get telemetry(){return n(this,X).getValue("telemetry")}get logger(){return n(this,X).getValue("logger")}get mediaJoined(){return n(this,X).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const a=ht(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Je.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const p=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(p)}),s.getValue("callstats").devices("AUDIO",p==null?void 0:p.filter(f=>f.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",p==null?void 0:p.filter(f=>f.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",p==null?void 0:p.filter(f=>f.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:ge.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await a.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:l,apiHostnames:h_(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),l.info("Callstats:: initialized")}catch(f){l.error("Callstats:: initialization failed",{error:f})}},0):l.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new Zf(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:a,screenShareTracks:o}=this.self;if(e.canProduceAudio===H.Allowed&&r)try{await n(this,St,Ut).shareMic(s),this.self.audioEnabled||n(this,St,Ut).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{await n(this,St,Ut).shareWebcam(t),this.self.videoEnabled||n(this,St,Ut).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&a)try{await((c=n(this,St,Ut))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){n(this,X).getValue("callstats").callEnded(),n(this,St,Ut).reset(),s&&await this.joinRoom(s)}setupEvents(){n(this,X).getValue("peerSessionStore").on(w.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),n(this,X).getValue("peerSessionStore").on(w.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),n(this,X).getValue("peerSessionStore").on(w.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),n(this,X).getValue("peerSessionStore").on(w.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,X).getValue("peerSessionStore").on(w.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),n(this,X).getValue("peerSessionStore").on(w.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;const{peerId:t}=this;n(this,$i).updateURL(t),n(this,X).getValue("telemetry").resetPeerId(t),ht().setHeader("tracing-id",t),Fr.remapContext(t,n(this,X)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),n(this,X).getValue("peerSessionStore").on(w.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),n(this,us).on(V.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),n(this,us).on(Fc.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&n(this,X).getValue("peerSessionStore").emit(w.UPDATE_PERMISSIONS,t.patch)})}),n(this,us).on(V.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),n(this,us).on(V.kick,()=>{this.kickHandler({kickType:"kick"})}),n(this,us).on(V.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),n(this,X).getValue("peerSessionStore").onAsync(w.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),n(this,X).getValue("peerSessionStore").on(w.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var a;const i=(a=e==null?void 0:e.screenShare)!=null?a:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),n(this,X).getValue("peerSessionStore").on(w.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),n(this,X).getValue("callstats").audioOff())}),n(this,X).getValue("peerSessionStore").on(w.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),n(this,X).getValue("callstats").videoOff())}),n(this,X).getValue("peerSessionStore").onAsync(w.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),n(this,X).getValue("peerSessionStore").on(w.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await n(this,us).joinRoom(this.self);n(this,us).socket.flush();const e=oh(t.stageType);if(n(this,X).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new C("Check the network and try again.","0002")}try{await this.joinMediaRoom(s),n(this,X).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof yr&&t.message==="ice connection failed"?new C("A firewall or network restriction may be blocking the connection.","0014"):new C("Check the network and try again.","0014")}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=n(this,X).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),n(this,X).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),n(this,X).notify("stageStatus");try{(e=n(this,$i))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}Xf(n(this,X)),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var a,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=n(this,X).getAllValues();try{if(e===rr.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}Qf(n(this,X),{socket:n(this,$i),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:p}=(o=await((a=n(this,St,Ut))==null?void 0:a.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw p!=null?p:new Error("Could not connect to media server");i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=n(this,X).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===rr.Webinar)&&n(this,St,Ut)&&(n(this,St,Ut).mediaJoined&&s!=="disconnected"&&await n(this,St,Ut).leaveRoom(),!(s==="stageLeft"&&t===rr.Livestream)&&(n(this,St,Ut).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},$i=new WeakMap,us=new WeakMap,X=new WeakMap,St=new WeakSet,Ut=function(){return n(this,X).getValue("roomNodeClient")},hg);let zr=Zf;Zi([y.trace("SelfController.resetSelf")],zr.prototype,"resetSelf",1);Zi([y.trace("SelfController.setupEvents")],zr.prototype,"setupEvents",1);Zi([y.trace("SelfController.joinRoom")],zr.prototype,"joinRoom",1);Zi([y.trace("SelfController.leaveRoom")],zr.prototype,"leaveRoom",1);Zi([y.trace("SelfController.joinMediaRoom")],zr.prototype,"joinMediaRoom",1);Zi([y.trace("SelfController.leaveMediaRoom")],zr.prototype,"leaveMediaRoom",1);Zi([y.trace("SelfController.init")],zr,"init",1);var lc;class hD{constructor(t){g(this,lc,void 0);m(this,lc,t)}on(t,e){let r;t===V.roomPeerCount?r=yp.fromBinary.bind(yp):r=Ap.fromBinary.bind(Ap),n(this,lc).on(t,({payload:i})=>{if(t===V.roomPeerCount&&!i)return;const a=r(i);e(a)})}}lc=new WeakMap;var uc,hc;class pD{constructor(t,e){g(this,uc,void 0);g(this,hc,void 0);m(this,uc,e),m(this,hc,t)}get logger(){return n(this,hc).getValue("logger")}on(t,e){let r,i;switch(t){case V.transcript:{r=Ul.fromBinary.bind(Ul),i=Ul.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}n(this,uc).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}uc=new WeakMap,hc=new WeakMap;var gD=Object.defineProperty,mD=Object.getOwnPropertyDescriptor,vh=(s,t,e,r)=>{for(var i=r>1?void 0:r?mD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&gD(t,e,i),i},Zs,fa;class Cl{constructor(t,e){g(this,Zs,void 0);g(this,fa,void 0);m(this,Zs,e),m(this,fa,t)}get logger(){return n(this,fa).getValue("logger")}get telemetry(){return n(this,fa).getValue("telemetry")}getPolls(){return n(this,Zs).sendMessagePromise(Ns.getPolls)}createPoll(t,e,r=!1,i=!1){const a={anonymous:r,hideVotes:i,question:t,options:e};return n(this,Zs).sendMessage(Ns.createPoll,_I.toBinary(a))}votePoll(t,e){const r={index:e,pollId:t};return n(this,Zs).sendMessage(Ns.votePoll,CI.toBinary(r))}on(t,e){let r,i;switch(t){case Ns.updatePoll:case Ns.createPoll:case Ns.votePoll:{r=jl.fromBinary.bind(jl),i=jl.create();break}}n(this,Zs).on(t,({payload:a})=>{let o=i;try{o=r(a)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){n(this,Zs).removeListeners(t)}}Zs=new WeakMap,fa=new WeakMap;vh([y.trace("PollSocketHandler.getPolls")],Cl.prototype,"getPolls",1);vh([y.trace("PollSocketHandler.createPoll")],Cl.prototype,"createPoll",1);vh([y.trace("PollSocketHandler.votePoll")],Cl.prototype,"votePoll",1);var fD=Object.defineProperty,TD=Object.getOwnPropertyDescriptor,SD=(s,t,e,r)=>{for(var i=r>1?void 0:r?TD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&fD(t,e,i),i},At;class eT{constructor(t,e){h(this,"socket");g(this,At,void 0);m(this,At,t),this.socket=e,this.handleSocketEvents(),n(this,At).setValue("roomSocketHandler",this)}get telemetry(){return n(this,At).getValue("telemetry")}get logger(){return n(this,At).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(V.joinRoom,fR.toBinary(e));try{const{peer:a}=tn.fromBinary((await r).payload);n(this,At).getValue("connectionHandler").socketJoined=!0,n(this,At).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_ROOM_JOINED,{peer:a});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return n(this,At).getValue("peerSessionStore").emit(w.ROOM_STATE,d),n(this,At).getValue("peerSessionStore").emit(w.SOCKET_PEERS,l),{peer:a}}catch(a){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:a}),a}}async getAllAddedParticipants(){try{return ek.fromBinary((await this.socket.sendMessagePromise(V.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const a={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(V.getRoomPeersInfo,aR.toBinary(a));i=$l.fromBinary(o.payload)}catch(a){this.logger.error("getRoomPeers::binary_decode_error",{error:a})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(V.getRoomPeersInfo);t=$l.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(V.getRoomPeersInfo);t=$l.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(V.getPeerInfo,Hm.toBinary({peerId:t}));e=tn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Ep.create();try{const e=await this.socket.sendMessagePromise(V.getRoomInfo);t=Ep.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=wp.create();try{const e=await this.socket.sendMessagePromise(V.getRoomStageState);t=wp.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(V.broadcastMessage,qa.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(V.broadcastToEntity,qa.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(V.broadcastToEntity,qa.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(V.leaveRoom,SR.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(V.kick,qm.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(V.kickAll,Um.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(V.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(V.acceptWaitingRoomRequests,ak.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(V.denyWaitingRoomRequests,ck.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Fc.updateUserPreset,xk.toBinary(r))}handleSocketEvents(){this.socket.on(V.broadcastMessage,({payload:t})=>{try{const e=qa.fromBinary(t);n(this,At).getValue("peerSessionStore").emit(w.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(V.broadcastToEntity,({payload:t})=>{try{const e=qa.fromBinary(t);n(this,At).getValue("peerSessionStore").emit(w.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case V.joinRoom:case V.leaveRoom:case V.kick:case V.kickAll:{r=tn.fromBinary.bind(tn),i=tn.create();break}case V.getWaitingRoomRequests:{r=(a,o)=>a?_p.fromBinary(a,o):{requests:[]},i=_p.create();break}case V.recordingPaused:case V.recordingStarted:case V.recordingStopped:{r=Np.fromBinary.bind(Np);break}case Fc.updateUserPreset:{r=Cp.fromBinary.bind(Cp);break}case gs.peerJoinedBroadcast:case vr.peerJoinedBroadcast:{r=mp.fromBinary.bind(mp);break}case gs.selfJoinComplete:case vr.selfJoinComplete:{r=su.fromBinary.bind(su);break}case gs.globalPeerPinBroadcast:case vr.globalPeerPinBroadcast:{r=Sp.fromBinary.bind(Sp);break}case gs.selectedPeer:case vr.selectedPeer:{r=tu.fromBinary.bind(tu);break}case gs.selectedPeerDiff:case vr.selectedPeerDiff:{r=gp.fromBinary.bind(gp);break}case gs.leaveRoom:case vr.leaveRoom:{r=ru.fromBinary.bind(ru);break}}this.socket.on(t,({payload:a})=>{let o=i;if(!r)return e(void 0);try{o=r(a)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Fc.getUserPresets,Ik.toBinary(e)),i=Nk.fromBinary(r.payload).peerPresets[0],a=new TextDecoder().decode(i.preset),o=JSON.parse(a).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}At=new WeakMap;SD([y.trace("RoomSocketHandler.joinRoom")],eT.prototype,"joinRoom",1);var vt;class vD{constructor(t){g(this,vt,void 0);m(this,vt,t)}async getStageRequests(){const{payload:t}=await n(this,vt).sendMessagePromise(V.getStageRequests);return t?ql.fromBinary(t):{stageRequests:[]}}requestAccess(){n(this,vt).sendMessage(V.requestStageAccess)}cancelRequestAccess(){n(this,vt).sendMessage(V.cancelStageRequest)}async grantAccess(t){const e={userIds:t};n(this,vt).sendMessage(V.grantStageAccess,gI.toBinary(e))}async denyAccess(t){const e={userIds:t};n(this,vt).sendMessage(V.denyStageAccess,fI.toBinary(e))}joinStage(){return n(this,vt).sendMessagePromise(V.joinStage,void 0,void 0,V.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return n(this,vt).sendMessagePromise(V.leaveStage,Op.toBinary(e),void 0,V.peerStageStatusUpdate)}kick(t){const e={userIds:t};return n(this,vt).sendMessagePromise(V.leaveStage,Op.toBinary(e))}on(t,e){let r;switch(t){case V.grantStageAccess:case V.denyStageAccess:{r=void 0;break}case V.getStagePeers:{r=Dp.fromBinary.bind(Dp);break}case V.getStageRequests:case V.requestStageAccess:case V.cancelStageRequest:{r=ql.fromBinary.bind(ql);break}case V.peerStageStatusUpdate:{r=vp.fromBinary.bind(vp);break}}n(this,vt).on(t,({payload:i,id:a})=>{if(!i||!r)return e(void 0,a);const o=r(i);return e(o,a)})}async getPeerInfo(t){const e=await n(this,vt).sendMessagePromise(V.getPeerInfo,Hm.toBinary({peerId:t}));return tn.fromBinary(e.payload)}}vt=new WeakMap;var Ve,pc;class yD{constructor(t,e){g(this,Ve,void 0);g(this,pc,void 0);m(this,Ve,e),m(this,pc,t)}get logger(){return n(this,pc).getValue("logger")}addPlugin(t,e){n(this,Ve).sendMessage(F.addPlugin,AM.toBinary({pluginId:t,staggered:e}))}removePlugin(t){n(this,Ve).sendMessage(F.removePlugin,OM.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await n(this,Ve).sendMessagePromise(F.getPlugins);return t?sI.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};n(this,Ve).sendMessage(F.customPluginEventToRoom,qM.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const a={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};n(this,Ve).sendMessage(F.customPluginEventToPeers,GM.toBinary(a),i)}enablePluginForRoom(t,e){n(this,Ve).sendMessage(F.enablePluginForRoom,LM.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){n(this,Ve).sendMessage(F.enablePluginForPeers,$M.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){n(this,Ve).sendMessage(F.disablePluginForRoom,xM.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){n(this,Ve).sendMessage(F.disablePluginForPeers,HM.toBinary({pluginId:t,peerIds:e}),r)}storeInsertKeys(t,e,r,i){const a={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};n(this,Ve).sendMessage(F.storeInsertKeys,Rp.toBinary(a),i)}storeGetKeys(t,e,r,i){const a={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};n(this,Ve).sendMessage(F.storeGetKeys,zM.toBinary(a),i)}storeDeleteKeys(t,e,r,i){const a={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};n(this,Ve).sendMessage(F.storeDeleteKeys,QM.toBinary(a),i)}storeDelete(t,e,r){n(this,Ve).sendMessage(F.storeDelete,ZM.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};n(this,Ve).sendMessage(F.storeInsertKeys,Rp.toBinary(i))}on(t,e){let r;switch(t){case F.addPlugin:case F.enablePluginForPeers:case F.enablePluginForRoom:{r=ou.fromBinary.bind(ou);break}case F.removePlugin:case F.disablePluginForPeers:case F.disablePluginForRoom:{r=kp.fromBinary.bind(kp);break}case F.customPluginEventToPeers:case F.customPluginEventToRoom:{r=Ip.fromBinary.bind(Ip);break}case F.storeInsertKeys:case F.storeGetKeys:case F.storeDeleteKeys:case F.storeDelete:{r=Mp.fromBinary.bind(Mp);break}}n(this,Ve).on(t,({payload:i,id:a})=>{const o=r(i);return e(o,a)})}}Ve=new WeakMap,pc=new WeakMap;var ED=Object.defineProperty,PD=(s,t,e)=>t in s?ED(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,bD=(s,t,e)=>(PD(s,typeof t!="symbol"?t+"":t,e),e),yh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},I=(s,t,e)=>(yh(s,t,"read from private field"),e?e.call(s):t.get(s)),ue=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},te=(s,t,e,r)=>(yh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Te=(s,t,e)=>(yh(s,t,"access private method"),e),ld={},_D={get exports(){return ld},set exports(s){ld=s}},fn=typeof Reflect=="object"?Reflect:null,jp=fn&&typeof fn.apply=="function"?fn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},zc;fn&&typeof fn.ownKeys=="function"?zc=fn.ownKeys:Object.getOwnPropertySymbols?zc=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:zc=function(s){return Object.getOwnPropertyNames(s)};function wD(s){console&&console.warn&&console.warn(s)}var tT=Number.isNaN||function(s){return s!==s};function ie(){ie.init.call(this)}_D.exports=ie;ld.once=MD;ie.EventEmitter=ie;ie.prototype._events=void 0;ie.prototype._eventsCount=0;ie.prototype._maxListeners=void 0;var Gp=10;function Rl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ie,"defaultMaxListeners",{enumerable:!0,get:function(){return Gp},set:function(s){if(typeof s!="number"||s<0||tT(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Gp=s}});ie.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};ie.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||tT(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function sT(s){return s._maxListeners===void 0?ie.defaultMaxListeners:s._maxListeners}ie.prototype.getMaxListeners=function(){return sT(this)};ie.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var o=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw o.context=a,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")jp(c,this,t);else for(var d=c.length,l=oT(c,d),e=0;e<d;++e)jp(l[e],this,t);return!0};function rT(s,t,e,r){var i,a,o;if(Rl(e),a=s._events,a===void 0?(a=s._events=Object.create(null),s._eventsCount=0):(a.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),a=s._events),o=a[t]),o===void 0)o=a[t]=e,++s._eventsCount;else if(typeof o=="function"?o=a[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=sT(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,wD(c)}return s}ie.prototype.addListener=function(s,t){return rT(this,s,t,!1)};ie.prototype.on=ie.prototype.addListener;ie.prototype.prependListener=function(s,t){return rT(this,s,t,!0)};function CD(){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 iT(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=CD.bind(r);return i.listener=e,r.wrapFn=i,i}ie.prototype.once=function(s,t){return Rl(t),this.on(s,iT(this,s,t)),this};ie.prototype.prependOnceListener=function(s,t){return Rl(t),this.prependListener(s,iT(this,s,t)),this};ie.prototype.removeListener=function(s,t){var e,r,i,a,o;if(Rl(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,a=e.length-1;a>=0;a--)if(e[a]===t||e[a].listener===t){o=e[a].listener,i=a;break}if(i<0)return this;i===0?e.shift():RD(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this};ie.prototype.off=ie.prototype.removeListener;ie.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),a;for(r=0;r<i.length;++r)a=i[r],a!=="removeListener"&&this.removeAllListeners(a);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function nT(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?kD(i):oT(i,i.length)}ie.prototype.listeners=function(s){return nT(this,s,!0)};ie.prototype.rawListeners=function(s){return nT(this,s,!1)};ie.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):aT.call(s,t)};ie.prototype.listenerCount=aT;function aT(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ie.prototype.eventNames=function(){return this._eventsCount>0?zc(this._events):[]};function oT(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function RD(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function kD(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function MD(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,a),r(o)}function a(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}cT(s,t,a,{once:!0}),t!=="error"&&ID(s,i,{once:!0})})}function ID(s,t,e){typeof s.on=="function"&&cT(s,"error",t,e)}function cT(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(a){r.once&&s.removeEventListener(t,i),e(a)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class AD extends S.MessageType{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 Wp=new AD;class dT{static encode(t){return Wp.toBinary(t)}static decode(t){return Wp.fromBinary(new Uint8Array(t))}}function DD(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Tr;class OD{constructor(t={}){bD(this,"opts"),ue(this,Tr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},te(this,Tr,0)}async wait(){te(this,Tr,I(this,Tr)+1);const t=DD(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**I(this,Tr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return I(this,Tr)}reset(){te(this,Tr,0)}}Tr=new WeakMap;const pr={debug:0,info:1,warn:2,error:3};var ei,ti;class ND{constructor(t){ue(this,ei,void 0),ue(this,ti,void 0),te(this,ei,console),te(this,ti,t)}debug(...t){pr[I(this,ti)]>pr.debug||I(this,ei).debug("[Sockrates]:",...t)}info(...t){pr[I(this,ti)]>pr.info||I(this,ei).info("[Sockrates]:",...t)}warn(...t){pr[I(this,ti)]>pr.warn||I(this,ei).warn("[Sockrates]:",...t)}error(...t){pr[I(this,ti)]>pr.error||I(this,ei).error("[Sockrates]:",...t)}}ei=new WeakMap,ti=new WeakMap;var lT=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(lT||{});const LD="2",VD="3";var we,an,fe,Ae,Sr,We,tr,Br,ps,on,Os,Ou,uT,Za,Yc,Nu,hT,Lu,Jp,ud,Vu,xu,pT,ro,Qc,io,hd,pd,Uu,Tn,no,ao,gd;class xD{constructor(t,e){var f,T,E,b,_,k,A,x,N,$;ue(this,Ou),ue(this,Za),ue(this,Nu),ue(this,Lu),ue(this,ud),ue(this,xu),ue(this,ro),ue(this,io),ue(this,pd),ue(this,Tn),ue(this,ao),ue(this,we,void 0),ue(this,an,void 0),ue(this,fe,void 0),ue(this,Ae,void 0),ue(this,Sr,void 0),ue(this,We,void 0),ue(this,tr,void 0),ue(this,Br,void 0),ue(this,ps,void 0),ue(this,on,void 0),ue(this,Os,void 0);var r,i,a,o,c,d,l,u,p;te(this,an,t),te(this,Sr,[]),te(this,We,new ld),te(this,tr,!0),te(this,ps,!1),te(this,fe,e!=null?e:{}),(f=(r=I(this,fe)).autoReconnect)!=null||(r.autoReconnect=!0),(T=(i=I(this,fe)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(a=I(this,fe)).pingTimeout)!=null||(a.pingTimeout=3e4),(b=(o=I(this,fe)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(_=(c=I(this,fe)).debug)!=null||(c.debug=!0),(k=(d=I(this,fe)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(A=(l=I(this,fe)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(x=(u=I(this,fe)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(N=(p=I(this,fe)).flushOnReconnect)!=null||(p.flushOnReconnect=!1),te(this,Br,{code:void 0,reason:void 0}),te(this,Ae,($=I(this,fe).logger)!=null?$:new ND(I(this,fe).debug?"debug":"info")),te(this,Os,new OD)}get readyState(){var t;return(t=I(this,we))==null?void 0:t.readyState}get url(){return I(this,an)}updateURL(t){te(this,an,t),Te(this,xu,pT).call(this)}get config(){return I(this,fe)}get sendQueue(){return I(this,Sr)}flush(){if(!I(this,fe).queueOnDisconnect)return!1;const t=[];return I(this,Sr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),te(this,Sr,t),I(this,Sr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){I(this,Ae).debug("Websocket was already connecting or connected.");return}if(I(this,tr)!==!1)return new Promise((e,r)=>{Te(this,Tn,no).call(this),Te(this,ao,gd).call(this);try{te(this,we,new WebSocket(Te(this,Ou,uT).call(this,I(this,an)))),I(this,we).binaryType="arraybuffer",I(this,Ae).debug("Connecting");const i=setTimeout(()=>{I(this,Ae).debug("Connection timeout. Closing socket"),te(this,tr,!0),Te(this,ao,gd).call(this),I(this,we).close(3001,"Connection Timeout"),I(this,fe).autoReconnect&&!I(this,ps)&&(I(this,We).emit("reconnecting"),Te(this,ro,Qc).call(this)),r(new Error("Connection timed out!"))},I(this,fe).connectionTimeout);I(this,we).onopen=()=>{I(this,Ae).debug(`Ready State: ${lT[I(this,we).readyState]}`),i&&clearTimeout(i),Te(this,pd,Uu).call(this),te(this,Br,{code:void 0,reason:void 0}),I(this,We).emit("connected"),I(this,fe).flushOnReconnect&&this.flush(),e()},I(this,we).onclose=a=>{try{i&&clearTimeout(i);const{code:o,reason:c}=a;r(c),I(this,Ae).debug("Socket closed. Close event:",{event:a}),I(this,Ae).debug(`Connection closed code: ${o}`),I(this,Ae).debug(`Connection closed reason: ${c}`),I(this,ps)||Te(this,ud,Vu).call(this,o,c)}catch(o){Te(this,Za,Yc).call(this,o)}},I(this,we).onerror=a=>{Te(this,Za,Yc).call(this,a)},I(this,we).onmessage=a=>Te(this,Nu,hT).call(this,a)}catch(i){Te(this,Za,Yc).call(this,i,r)}})}send(t,e,r,i){const a={event:t,id:e,payload:r,metadata:i};if(I(this,fe).queueOnDisconnect&&(!I(this,we)||I(this,we).readyState!==1))return I(this,Ae).debug("Queuing message since socket is not connected!",a),I(this,Sr).push(a),!1;const o=dT.encode(a);return Te(this,io,hd).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Te(this,io,hd).call(this,t)}receive(t,e){return I(this,We).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){I(this,We).on(t,e);return}this.receive(t,e)}removeAllListeners(){I(this,We).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){I(this,We).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){I(this,We).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){te(this,tr,!1),Te(this,Tn,no).call(this),this.removeAllListeners(),te(this,Br,{code:1e3,reason:"Sockrates disconnect method called"}),I(this,we).close(1e3,"Sockrates disconnect method called.")}}we=new WeakMap,an=new WeakMap,fe=new WeakMap,Ae=new WeakMap,Sr=new WeakMap,We=new WeakMap,tr=new WeakMap,Br=new WeakMap,ps=new WeakMap,on=new WeakMap,Os=new WeakMap,Ou=new WeakSet,uT=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},Za=new WeakSet,Yc=function(s,t){I(this,Ae).error("Error:",{error:s}),I(this,We).emit("errored",{error:s}),t==null||t(s)},Nu=new WeakSet,hT=function(s){if(Te(this,pd,Uu).call(this),s.data===LD){I(this,Ae).debug("Received ping from server"),Te(this,io,hd).call(this,VD);return}const t=dT.decode(s.data),{id:e,payload:r}=t;I(this,Ae).debug("Received message",{event:t.event,messageID:e}),I(this,We).emit(t.event.toString(),{id:e,payload:r})},Lu=new WeakSet,Jp=function(){return I(this,we).readyState===1},ud=new WeakSet,Vu=function(s,t){te(this,Br,{reason:t,code:s}),I(this,We).emit("disconnected",{code:s,reason:t})},xu=new WeakSet,pT=function(){const{reason:s,code:t}=I(this,Br);t&&t!==1e3&&I(this,tr)&&I(this,fe).autoReconnect&&!I(this,ps)&&(I(this,Ae).debug(`Triggering reconnection due to ${s}.`),I(this,We).emit("reconnecting"),Te(this,ro,Qc).call(this))},ro=new WeakSet,Qc=async function(s=!0){if(s&&I(this,ps)){I(this,Ae).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(I(this,ps)||I(this,Os).reset(),I(this,fe).maxReconnectionAttempts!==null&&I(this,Os).getAttempts()>=I(this,fe).maxReconnectionAttempts){I(this,We).emit("failed"),te(this,ps,!1);return}te(this,ps,!0),Te(this,ao,gd).call(this),Te(this,Tn,no).call(this);try{if(await I(this,Os).wait(),I(this,tr)===!1)return;if(I(this,Ae).debug(`Reconnection attempt ${I(this,Os).getAttempts()}`),I(this,We).emit("reconnectAttempt",{attempt:I(this,Os).getAttempts()}),await this.connect(),!Te(this,Lu,Jp).call(this))throw Error("Reconnect Failed");te(this,ps,!1),te(this,Br,{code:void 0,reason:void 0}),I(this,We).emit("reconnected")}catch(t){I(this,Ae).debug("Failed to reconnect."),I(this,We).emit("reconnectFailure",{attempt:I(this,Os).getAttempts()}),Te(this,ro,Qc).call(this,!1)}},io=new WeakSet,hd=function(s){try{return I(this,we).send(s),!0}catch(t){return I(this,Ae).error(t.message),!1}},pd=new WeakSet,Uu=function(){this.config.disconnectOnPingTimeout&&(I(this,Ae).debug("Resetting ping timeout"),Te(this,Tn,no).call(this),te(this,on,setTimeout(()=>{var s;I(this,Ae).debug("Disconnecting the socket due to ping timeout"),te(this,tr,!0);const t=3002,e="Ping timeout";(s=I(this,we))==null||s.close(t,e),Te(this,ud,Vu).call(this,t,e)},I(this,fe).pingTimeout)))},Tn=new WeakSet,no=function(){I(this,on)&&(clearTimeout(I(this,on)),te(this,on,void 0))},ao=new WeakSet,gd=function(){I(this,we)&&(I(this,we).onopen=void 0,I(this,we).onerror=void 0,I(this,we).onmessage=void 0,I(this,we).onclose=void 0)};var UD=Object.defineProperty,$D=Object.getOwnPropertyDescriptor,kl=(s,t,e,r)=>{for(var i=r>1?void 0:r?$D(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&UD(t,e,i),i};const Kp=65535,BD=3e3;var xr,ve,ye,Re,Yt,Ge,gc,$u,mc,Bu,pg;const gT=(pg=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,ye);g(this,gc);g(this,mc);g(this,xr,void 0);g(this,ve,void 0);h(this,"roomName");h(this,"authToken");h(this,"capabilities");g(this,Yt,void 0);g(this,Ge,void 0);var a;if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");m(this,Yt,void 0),m(this,Ge,s),this.capabilities=i,this.roomName=e,this.authToken=r,m(this,xr,L(this,gc,$u).call(this,t)),m(this,ve,new xD(n(this,xr),{autoReconnect:!0,disconnectOnPingTimeout:(a=i.includes("PING"))!=null?a:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return n(this,ye,Re).socketJoinAttempted}set joinAttempted(s){n(this,ye,Re).socketJoinAttempted=s}get telemetry(){return n(this,Ge).getValue("telemetry")}get logger(){return n(this,Ge).getValue("logger")}get peerId(){return n(this,Ge).getValue("peerId")}updateURL(s){s!==this.peerId&&(m(this,xr,L(this,gc,$u).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),n(this,ve).updateURL(n(this,xr))}static getSocketEdgeDomain(s){return gn({servicePrefix:"socket-edge",baseURI:s})}get url(){return n(this,xr)}async connect(){n(this,ye,Re).socketJoinAttempted=!0,await n(this,ve).connect(),n(this,ye,Re).socketJoinAttempted=!0,n(this,ye,Re).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){n(this,ye,Re).socketJoinAttempted=!1,n(this,ve).disconnect(),n(this,ye,Re).socketJoinAttempted=!0,n(this,ye,Re).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return n(this,ve).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return n(this,Ge).getValue("telemetry").injectContext(r),n(this,ve).send(s,e!=null?e:L(this,mc,Bu).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const a=i!=null?i:s;return new Promise((o,c)=>{const d=(E,b)=>{n(this,ve).removeListener(a,E),n(this,ve).removeListener(Kp,b),n(this,ve).removeListener(vr.errorResponse,b),n(this,ve).removeListener(gs.errorResponse,b)},l=r!=null?r:L(this,mc,Bu).call(this),u={};n(this,Ge).getValue("telemetry").injectContext(u);const f=({id:E,payload:b})=>{if(l===E){let _;try{const k=Xw.fromBinary(b);_=new Error(k.errorMessage)}catch(k){_=new Error("failed to parse error message",{cause:k});try{const A=ZC.fromBinary(b);_=new Error(A.message)}catch(A){_=new Error("failed to parse error message",{cause:A})}}c(_),d(T,f)}},T=({id:E,payload:b})=>{l===E&&(o({id:E,payload:b}),d(T,f))};n(this,ve).on(a,T),n(this,ve).on(Kp,f),n(this,ve).on(vr.errorResponse,f),n(this,ve).on(gs.errorResponse,f),setTimeout(()=>{d(T,f),c(new Error(`request timeout for callback eventId:${s}`))},t),n(this,ve).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){n(this,ve).on(s,t)}onStateEvent(s,t){n(this,ve).on(s,t)}removeListener(s,t){n(this,ve).removeListener(s,t)}removeListeners(s){n(this,ve).removeListeners(s)}flush(){return n(this,ve).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),n(this,Yt)&&(clearTimeout(n(this,Yt)),m(this,Yt,void 0)),n(this,ye,Re).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}});const{recv:e,send:r}=(i=n(this,ye,Re).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==mn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==mn.CONNECTED?n(this,Ge).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,ye,Re).joinAttempted}):m(this,Yt,setTimeout(()=>{n(this,Ge).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:n(this,ye,Re).joinAttempted}),m(this,Yt,void 0)},BD)),n(this,ye,Re).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),n(this,ye,Re).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),n(this,ye,Re).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),n(this,ye,Re).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:n(this,ye,Re).mediaJoinAttempted}}),n(this,Yt)&&(clearTimeout(n(this,Yt)),m(this,Yt,void 0)),n(this,Ge).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:n(this,ye,Re).mediaJoinAttempted}),n(this,ye,Re).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),n(this,Ge).getValue("peerSessionStore").emit(w.SOCKET_SERVICE_FAILED),n(this,ye,Re).updateSocketConnectionState("failed")})}},xr=new WeakMap,ve=new WeakMap,ye=new WeakSet,Re=function(){return n(this,Ge).getValue("connectionHandler")},Yt=new WeakMap,Ge=new WeakMap,gc=new WeakSet,$u=function(s){const t=n(this,Ge).getValue("socketBaseURI")||n(this,Ge).getValue("baseURI");let e=gT.getSocketEdgeDomain(t);typeof ya(n(this,Ge),"socket_server_base")=="string"&&(e=ya(n(this,Ge),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),a=this.peerId,o={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...a!==s&&{oldPeerID:a},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(c=>id[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},mc=new WeakSet,Bu=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},pg);let Rc=gT;kl([y.trace("SocketService.connect")],Rc.prototype,"connect",1);kl([y.trace("SocketService.disconnect")],Rc.prototype,"disconnect",1);kl([y.trace("SocketService.sendMessagePromise")],Rc.prototype,"sendMessagePromise",1);kl([y.trace("SocketService.sendMessagePromiseWithTimeout")],Rc.prototype,"sendMessagePromiseWithTimeout",1);class HD{constructor(t){h(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var a;const e=CR.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(a=e.parentMeeting.participants)!=null?a:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=XR.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Fm.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return bp.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return FR.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(V.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(V.createConnectedRooms,IR.toBinary({payloads:t}));return bp.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(V.deleteConnectedRooms,BR.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(V.movePeers,KR.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}}}}var FD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,jD=(s,t,e,r)=>{for(var i=r>1?void 0:r?qD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&FD(t,e,i),i},hs;class mT extends Lt{constructor(e){const r=e.getValue("logger");super(r);h(this,"meetings",[]);h(this,"parentMeeting",null);g(this,hs,void 0);m(this,hs,e)}get supportsConnectedMeetings(){return n(this,hs).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
10
10
  Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await n(this,hs).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await n(this,hs).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await n(this,hs).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(a=>e.includes(a.id)&&a.participants.length!==0?this.moveParticipants(a.id,this.parentMeeting.id,a.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await n(this,hs).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,hs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return a.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),a}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const a=await n(this,hs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return a.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),a}moveSuccessHandler(e,r,i){const a=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>a.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>a.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>a.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}hs=new WeakMap;jD([Et({maxInvocations:60,period:60})],mT.prototype,"getConnectedMeetings",1);var GD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,Eh=(s,t,e,r)=>{for(var i=r>1?void 0:r?WD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&GD(t,e,i),i},ce,gg;const fT=(gg=class{constructor(s){h(this,"connectedMeetings");g(this,ce,void 0);m(this,ce,s),this.connectedMeetings=new mT(s)}get telemetry(){return n(this,ce).getValue("telemetry")}get logger(){return n(this,ce).getValue("logger")}static init(s){const t=new fT(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){n(this,ce).getValue("connectedMeetingsSocketHandler").socketService.on(V.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),n(this,ce).getValue("connectedMeetingsSocketHandler").socketService.on(V.transferPeer,this.handleTransferPeer.bind(this)),n(this,ce).getValue("connectedMeetingsSocketHandler").socketService.on(V.movedPeer,this.handleMovedPeer.bind(this)),n(this,ce).getValue("connectedMeetingsSocketHandler").socketService.on(V.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),n(this,ce).getValue("connectedMeetingsSocketHandler").socketService.on(V.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=n(this,ce).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,a,o,c;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
11
11
  Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:n(this,ce).getValue("self").videoEnabled,audio:n(this,ce).getValue("self").audioEnabled};try{n(this,ce).getValue("self").cleanupEvents(),await n(this,ce).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(a=(i=n(this,ce).getValue("meeting"))==null?void 0:i.meta)==null?void 0:a.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await ST.init({...n(this,ce).getValue("options"),cachedUserDetails:null,defaults:{...n(this,ce).getValue("options").defaults,...e,mediaHandler:n(this,ce).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=n(this,ce).getValue("self");r.self.setName(n(this,ce).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=n(this,ce).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return n(this,ce).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=n(this,ce).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=n(this,ce).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},ce=new WeakMap,gg);let Ml=fT;Eh([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Ml.prototype,"getConnectedMeetings",1);Eh([y.trace("ConnectedMeetingsController.setupEvents")],Ml.prototype,"setupEvents",1);Eh([y.trace("ConnectedMeetingsController.switchMeeting")],Ml.prototype,"switchMeeting",1);var JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,Ph=(s,t,e,r)=>{for(var i=r>1?void 0:r?KD(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&JD(t,e,i),i};const eo=class{constructor(s,t,e){h(this,"apiBase");h(this,"selfController");h(this,"pollController");h(this,"chatController");h(this,"metaController");h(this,"storesManager");h(this,"stageController");h(this,"pluginController");h(this,"internalsController");h(this,"recordingController");h(this,"livestreamController");h(this,"participantController");h(this,"connectedMeetingsController");h(this,"telemetry");h(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var N,$,K;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:a,cachedUserDetails:o,logger:c}=s.getAllValues();if(Xf(s),ge.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=tA(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(a),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new VA(s);s.setValue("connectionHandler",l);let u="",p="",f=null;c.info("CF SFU is being used.");try{f=await d.getUserDetails(),u=((N=f.meeting)==null?void 0:N.title)||"",p=(($=f.socket)==null?void 0:$.baseUri)||s.getValue("baseURI"),s.setValue("presetName",f.preset.name),s.setValue("socketBaseURI",p),c.info(`Socket Base URI ${p} is being used`)}catch(Y){throw c.error("Failed to get user details",{error:Y}),Y instanceof du?Y.status===401?new C("Unauthorized. The auth token may be invalid or expired. (401)","0004"):Y.status===403?new C("Access denied. Insufficient permissions to join the meeting. (403)","0004"):Y.status===404?new C("The auth token is not associated with an active participant in this meeting. The meeting may have ended, or the participant may no longer exist. (404)","0004"):Y.status>=500?new C(`The server encountered an error. Try again. (${Y.status})`,"0001"):Y.isHttpError?new C(`Request rejected by the server. (${Y.status})`,"0001"):Y.isTimeout?new C("Connection timed out. Check the network and try again.","0001"):new C("Unable to connect to the server. Check the internet connection.","0001"):new C((Y==null?void 0:Y.message)||"Failed to initialize.","0001")}const T=eo.createSocketService(s),E=T.connect(),b=d.getPlugins();try{await E}catch(Y){c.error("[Controller]: Failed to connect to socket server:",{error:Y})}const _=Tu.init(f.preset,!s.getValue("modules").theme);s.setValue("theme",_);const k=Eu.init(s,_.viewType,f.preset.permissions),A=eo.setupControllers(T,s,f,b,u,_,k);wA(_)&&((K=eo.createRoomNodeClient(s,T).initializeConnection(f.participant.name,i,!1,k))==null||K.catch(Ue=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:Ue})}));const{controllers:x}=await A;return O_(),new eo(e,x,s)}static async setupControllers(s,t,e,r,i,a,o){var O,R,De;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),u=t.getValue("logger"),{viewType:p,mediaConstraints:{audio:f}}=a;t.setValue("viewType",p),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(O=f.enableHighBitrate)!=null?O:!1,enableStereo:(R=f.enableStereo)!=null?R:!1}},...l}),t.setValue("maxPreferredStreams",ge.isMobile()?a.maxVideoStreams.mobile:a.maxVideoStreams.desktop);let T,E,b,_,k,A,x,N,$;const K=new pD(t,s),Y=new HD(s);t.setValue("connectedMeetingsSocketHandler",Y);const Ue=new Cl(t,s),es=new lr(t,s),Yr=new vD(s),ts=new eT(t,s),M=new yD(t,s),v=new hD(s),P=await zr.init(t,ts,d,o,a);t.setValue("selfController",P);const U=await rf.init(t,P.self,ts,K,i);if(c.participant&&(N=new hr(t,P.self,ts)),(De=c.e2ee)!=null&&De.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(E=await Xt.init(t,es,P.self,N.participants)),c.internals&&(k=await dh.init(t)),c.livestream&&a.viewType===rr.Livestream&&(x=new pf(t,P.self,v)),c.poll&&(T=await Zm.init(t,P.self,Ue)),c.recording&&(A=new cf(t,P.self,ts)),c.stage&&(b=new nf(t,Yr,ts,P.self,N.participants)),c.plugin){if(!N)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const Ds=await r;_=await bc.init(t,Ds,M,es,E==null?void 0:E.chat,P.self,N.participants,i)}if(c.connectedMeetings&&($=await Ml.init(t)),c.pip){const Ds=await eu._init(t,P.self);t.setValue("pip",Ds)}const Ce={storesManager:new k0(t,M),pollController:T,selfController:P,metaController:U,chatController:E,stageController:b,pluginController:_,recordingController:A,internalsController:k,livestreamController:x,participantController:N,connectedMeetingsController:$};return{theme:a,permissions:o,controllers:Ce}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return Qf(s,{socket:t,peerId:e})}static createSocketService(s){var d;const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),o=((d=s.getValue("socketBaseURI"))!=null?d:"").includes("realtime.cloudflare.com")?[]:["PING"];return s.getValue("logger").info(`Socket service capabilities: ${JSON.stringify(o)}`),new Rc(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let Il=eo;Ph([y.trace("Controller.init")],Il,"init",1);Ph([y.trace("Controller.createRoomNodeClient")],Il,"createRoomNodeClient",1);Ph([y.trace("Controller.createSocketService")],Il,"createSocketService",1);class zD{constructor(){h(this,"battery");h(this,"logger");h(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});h(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});h(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});h(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const zp=new zD;function YD(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.realtime.cloudflare.com/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let a=ri.baseURI.prod;t&&(a=t);const o=`https://${gn({servicePrefix:"api",baseURI:a})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:a,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}var Ur,Bi,Hi,fc,ol,TT;class QD{constructor(){g(this,ol);g(this,Ur,new Audio);g(this,Bi,new MediaStream);g(this,Hi,new Map);g(this,fc,void 0);n(this,Ur).srcObject=n(this,Bi),n(this,Ur).autoplay=!0}async playTracks(t){return t.forEach(e=>{n(this,Hi).has(e.id)||(n(this,Bi).addTrack(e),n(this,Hi).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&n(this,Ur).setSinkId(t)}removeTrack(t){const e=n(this,Hi).get(t);e&&(n(this,Bi).removeTrack(e),n(this,Hi).delete(t))}async play(){return n(this,Ur).srcObject=n(this,Bi),n(this,Ur).play().catch(t=>{L(this,ol,TT).call(this,t)})}onError(t){m(this,fc,t)}}Ur=new WeakMap,Bi=new WeakMap,Hi=new WeakMap,fc=new WeakMap,ol=new WeakSet,TT=function(t){var e;(e=n(this,fc))==null||e.call(this,t)};var Fi;class XD extends QD{constructor(){super();g(this,Fi,void 0);m(this,Fi,new Map)}addParticipantTrack(e,r){n(this,Fi).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=n(this,Fi).get(e);r&&this.removeTrack(r),n(this,Fi).delete(e)}}Fi=new WeakMap;var ZD=Object.defineProperty,e1=Object.getOwnPropertyDescriptor,Al=(s,t,e,r)=>{for(var i=r>1?void 0:r?e1(t,e):t,a=s.length-1,o;a>=0;a--)(o=s[a])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ZD(t,e,i),i},xe,qi,mg;let Gr=(mg=class{constructor(t,e){g(this,xe,void 0);g(this,qi,void 0);m(this,qi,t),m(this,xe,e)}get peerId(){return n(this,qi).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:jr.v4(),a=Fr.createContext(i,{peerId:i}),o=a.getValue("logger");o.init(a);const c=new Ef(a,o);return await c.init(t,e,a),a.setValue("defaults",{mediaHandler:c}),c}static async init(t){var f,T,E,b,_,k,A,x,N;ge.init();const e=(T=(f=t==null?void 0:t.cachedUserDetails)==null?void 0:f.peerId)!=null?T:jr.v4(),{authToken:r,baseURI:i}=t,{meetingId:a,...o}=YD(r,i);if((E=o.baseURI)!=null&&E.includes("dyte.io"))throw new C("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Gr.setupContext(e,t,a,o),d=c.getValue("telemetry"),l=c.getValue("logger");wT(l),zp.init(l),d.init(c,{roomName:a,userId:o.participantId,organizationId:o.orgId,peerId:e},(_=(b=t.modules)==null?void 0:b.tracing)!=null?_:!0,(A=(k=t==null?void 0:t.modules)==null?void 0:k.devTools)==null?void 0:A.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(x=t.authToken)==null?void 0:x.slice(0,10)}...
12
- ${(N=t.authToken)==null?void 0:N.slice(-10)}`}});const u=await Il.init(c),p=new Gr(c,u);return c.setValue("meeting",p),p}static setupContext(t,e,r,i){var d,l;const a=Fr.createContext(t,e),o={...l_,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",u_({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",ks(e.cachedUserDetails)),a.setValue("sdkVersion","1.5.0-staging.5"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new XD),a}async join(){const{selfController:t}=n(this,xe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){zp.cleanup(),n(this,qi).getValue("peerSessionStore").reset();const{selfController:e}=n(this,xe);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,xe).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,xe).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,xe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,xe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,xe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,xe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,xe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,xe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,xe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,xe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,xe).stageController)==null?void 0:t.stage}get stores(){return n(this,xe).storesManager}get audio(){return n(this,qi).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,xe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},xe=new WeakMap,qi=new WeakMap,mg);Al([rt("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Gr.prototype,"join",1);Al([rt("0003")],Gr.prototype,"leave",1);Al([rt("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Gr,"init",1);Gr=Al([rt("0000")],Gr);const ST=Gr;module.exports=ST;
12
+ ${(N=t.authToken)==null?void 0:N.slice(-10)}`}});const u=await Il.init(c),p=new Gr(c,u);return c.setValue("meeting",p),p}static setupContext(t,e,r,i){var d,l;const a=Fr.createContext(t,e),o={...l_,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return a.setValue("options",e),a.setValue("peerId",t),a.setValue("modules",o),a.setValue("sdkName","web-core"),a.setValue("meetingId",r),a.setValue("apiBase",i.apiBase),a.setValue("baseURI",i.baseURI),a.setValue("userId",i.participantId),a.setValue("organizationId",i.orgId),a.setValue("authToken",e.authToken),a.setValue("overrides",(d=e.overrides)!=null?d:{}),a.setValue("env",u_({baseURI:i.baseURI})),a.setValue("defaults",c),a.setValue("onError",e.onError||(()=>{})),a.setValue("cachedUserDetails",ks(e.cachedUserDetails)),a.setValue("sdkVersion","1.5.0-staging.8"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&a.setValue("audioPlayback",new XD),a}async join(){const{selfController:t}=n(this,xe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){zp.cleanup(),n(this,qi).getValue("peerSessionStore").reset();const{selfController:e}=n(this,xe);return e.leaveRoom(t)}get participants(){var t;return(t=n(this,xe).participantController)==null?void 0:t.participants}get self(){var t;return(t=n(this,xe).selfController)==null?void 0:t.self}get meta(){var t;return(t=n(this,xe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=n(this,xe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=n(this,xe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=n(this,xe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=n(this,xe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=n(this,xe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=n(this,xe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=n(this,xe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=n(this,xe).stageController)==null?void 0:t.stage}get stores(){return n(this,xe).storesManager}get audio(){return n(this,qi).getValue("audioPlayback")}get __internals__(){var t;return(t=n(this,xe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},xe=new WeakMap,qi=new WeakMap,mg);Al([rt("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Gr.prototype,"join",1);Al([rt("0003")],Gr.prototype,"leave",1);Al([rt("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Gr,"init",1);Gr=Al([rt("0000")],Gr);const ST=Gr;module.exports=ST;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/realtimekit",
3
- "version": "1.5.0-staging.5",
3
+ "version": "1.5.0-staging.8",
4
4
  "description": "A real-time video and audio SDK for building custom, collaborative communication experiences.",
5
5
  "main": "./dist/index.cjs.js",
6
6
  "module": "./dist/index.es.js",