@cloudflare/realtimekit 1.2.1-staging.6 → 1.2.1-staging.7

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,7 +17,7 @@ ${s}`}const $n={maxInvocations:5,period:1};function Lt(s,t){return function(e,r,
17
17
  `)+`\r
18
18
  `},Li=fS,kD=RD,ul=kD,xi=Li.parse;Li.parseParams,Li.parseFmtpConfig,Li.parsePayloads,Li.parseRemoteCandidates,Li.parseImageAttributes,Li.parseSimulcastStreamList;class hl extends Jh{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new hl(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,g)=>{var B;const S=xi(h),E=S.media[S.media.length-1],b=E.rtp.filter(N=>g.some($=>$.name===N.codec)),_=E.fmtp.filter(N=>b.some($=>$.payload===N.payload)),w=(B=E.rtcpFb)==null?void 0:B.filter(N=>b.some($=>$.payload===N.payload)),F=b.map(N=>N.payload);return S.media[S.media.length-1].rtp=b,S.media[S.media.length-1].fmtp=_,S.media[S.media.length-1].rtcpFb=w,S.media[S.media.length-1].payloads=F.join(" "),ul(S)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:h,enableStereo:g}=this,S=this.enableHighBitrate?g?128e3:64e3:g?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${g?"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 Yh extends Jh{static createFactory(t){return()=>new Yh(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 g;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=((g=h.sdpFmtpLine)==null?void 0:g.split(";"))||[];S.push(...u.parameters);const E=[...new Set(S).values()];h.sdpFmtpLine=E.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,g=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=${g}`)}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 ID(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class AD extends dl{constructor(e,r){var i;super(e);m(this,Qs);m(this,uc);m(this,$l);m(this,Hl);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,lc,void 0);m(this,cn,void 0);m(this,Ys,void 0);m(this,Bl,void 0);this.id=r.id,this.localId=r.localId,f(this,lc,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Ys,!1),this.producerId=r.producerId,this.track=r.track,f(this,cn,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,x(this,$l,Pv).call(this),f(this,Bl,e)}get closed(){return a(this,Ys)}get kind(){return this.track.kind}get paused(){return a(this,cn)}close(e,r){a(this,Ys)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,Qs,Si)),f(this,Ys,!0),r&&(x(this,Hl,Cv).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Ys))throw new Ut("closed");return a(this,lc).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,Qs,Si)),a(this,Ys)){this.logger.error("consumer::pause() | Consumer closed",a(this,Qs,Si));return}f(this,cn,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,Qs,Si)),a(this,Ys)){this.logger.error("Consumer::resume() | Consumer closed",a(this,Qs,Si));return}f(this,cn,!1),this.track.enabled=!0,this.safeEmit("resume")}}lc=new WeakMap,cn=new WeakMap,Ys=new WeakMap,Bl=new WeakMap,Qs=new WeakSet,Si=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},uc=new WeakSet,Ep=function(){this.logger.debug('Consumer::track "ended" event',a(this,Qs,Si)),this.safeEmit("trackended")},$l=new WeakSet,Pv=function(){this.track.addEventListener("ended",x(this,uc,Ep).bind(this))},Hl=new WeakSet,Cv=function(){try{this.track.removeEventListener("ended",x(this,uc,Ep)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,Qs,Si),error:e})}};class MD extends dl{constructor(e,r){var i,n;super(e);m(this,es);p(this,"id");p(this,"localId");m(this,Ns,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");m(this,Ua,void 0);m(this,Fa,void 0);m(this,dn,void 0);m(this,fs,!1);m(this,at,void 0);m(this,di,void 0);m(this,Ba,void 0);m(this,ql,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,di,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,Ba,void 0),f(this,Ua,r.stopTracks),f(this,Fa,r.disableTrackOnPause),f(this,dn,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,Ns,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,ql,e)}get closed(){return a(this,fs)}get track(){return a(this,at)}get paused(){return a(this,di)}get maxSpatialLayer(){return a(this,Ba)}async close(e){if(a(this,fs))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,es,Hs)),f(this,fs,!0),this._destroyTrack(),e===gl){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,Ns).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,fs))throw new Ut("closed");return a(this,Ns).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,es,Hs)),a(this,fs)&&this.logger.error("Producer::pause() | Producer closed",a(this,es,Hs)),f(this,di,!0),a(this,at)&&a(this,Fa)&&(a(this,at).enabled=!1),a(this,dn)&&a(this,Ns).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,es,Hs)),a(this,fs)){this.logger.error("Producer::resume() | Producer closed",a(this,es,Hs));return}f(this,di,!1),a(this,at)&&a(this,Fa)&&(a(this,at).enabled=!0),a(this,dn)&&a(this,Ns).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,es,Hs)),a(this,fs)){if(e&&a(this,Ua))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,es,Hs),error:r})}throw new Ut("closed")}else if(e&&e.readyState==="ended")throw new Ut("track ended");if(e===a(this,at)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,es,Hs));return}(!a(this,dn)||!a(this,di))&&await a(this,Ns).replaceTrack(this.localId,e),this._destroyTrack(),f(this,at,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,fs))throw new Ut("closed");if(this.kind!=="video")throw new Io("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,Ns).setMaxSpatialLayer(this.localId,e),f(this,Ba,e)}async setRtpEncodingParameters(e){if(a(this,fs))throw new Ut("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,Ns).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,es,Hs)),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,Ua)&&a(this,at).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,es,Hs),error:r})}}}Ns=new WeakMap,Ua=new WeakMap,Fa=new WeakMap,dn=new WeakMap,fs=new WeakMap,at=new WeakMap,di=new WeakMap,Ba=new WeakMap,ql=new WeakMap,es=new WeakSet,Hs=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function vS(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Qh(s){return Math.random().toString(36).substring(2,2+s)}const pl=1;function TS(s){const t=s;return delete t.payload._bolt,t}function OD(s){return s.payload&&vS(s.payload)}function DD(s){var t,e;return OD(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}const $a=class extends lt.EventEmitter{constructor(e,r,i,n){super();p(this,"channel");p(this,"queue");p(this,"serverProtocolVersion");m(this,li,new Map);m(this,jl,void 0);m(this,ln,void 0);p(this,"respond",(e,r,i=!1)=>{let n;i?n=$a.createErrorResponse(e,r):n=$a.createResponse(e,r),this.channel.send(JSON.stringify(n))});p(this,"notify",e=>{const r=$a.createNotification(e);this.channel.send(JSON.stringify(r))});p(this,"request",async e=>{const r=$a.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=vi();for(let l=0;l<o;l+=1){const u=c[l],g=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});a(this,ln).debug(`Sending message chunk over dc: ${g}`),this.channel.send(g)}}else a(this,ln).debug(`Sending message over dc: ${r}`),this.channel.send(r)});p(this,"processMessage",e=>{var i;a(this,li).has(e.id)||a(this,li).set(e.id,[]);const r=a(this,li).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,li).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,li).delete(e.id);const c=JSON.parse(o);if(!c.payload||!vS(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,ln).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(TS(e)):i.resolve(TS(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:Qh(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,f(this,jl,e),f(this,ln,e.getValue("logger")),this.channel=r,this.queue=new Map}};let Ui=$a;li=new WeakMap,jl=new WeakMap,ln=new WeakMap,p(Ui,"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:Qh(8),type:"REQUEST",version:pl}}}}),p(Ui,"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:pl}}}}),p(Ui,"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:Qh(8),type:"NOTIFY",version:pl}}}}),p(Ui,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:pl}}}));const gl="transport closed",Ha=class extends dl{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var E,b,_;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,un,void 0);f(this,un,e);const g=e.getValue("logger");g.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const S=ID(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 Wh(g,!0),this.handler=n(),this.handler.enableHighBitrate=(E=h==null?void 0:h.enableHighBitrate)!=null?E:!1,this.handler.enableStereo=(b=h==null?void 0:h.enableStereo)!=null?b:!1,this.handler.enableDtx=(_=h==null?void 0:h.enableDtx)!=null?_:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{},this.transportConnectionPromise=new Promise(w=>{this.once("connected",()=>{w(!0)}),this.once("disconnect",()=>{w(!1)}),this.once("close",()=>{w(!1)})}),this.eventsDCReadyPromise=new Promise(w=>{this.eventsDCReadyPromiseResolver=w}),this.handler.on("@connectionstatechange",w=>{w!==this.connectionState&&(this.logger.debug(`connection state changed to ${w}`),this.connectionState=w,w==="connected"&&(this.connected=!0,this.emit("connected")),w==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(w==="failed"||w==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",w))}),this.handler.on("@icecandidate",({candidate:w})=>{this.closed||this.safeEmit("icecandidate",w)}),this.handler.on("dc_open",w=>{let F=this.datachannels.get(w.label);F||(F||(F=new Ui(a(this,un),w,w.label,this.serverId),this.datachannels.set(w.label,F)),this.eventsDCFailureTimer=setTimeout(()=>{w.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",w.label))},5e3))}),this.handler.on("datachannel",(w,F)=>{w.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const B=this.datachannels.get(w.label);if(!B){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:w.label,message:F}});return}try{const N=JSON.parse(F);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:N.id,count:N.count,chunkIndex:N.chunkIndex,chunk:N.chunk,transprtId:this.serverId}});const $=B.processMessage(N);if(!$)return;this.logger.debug(`datachannel message with id:${N.id} on transport:${this.serverId}complete - ${JSON.stringify($)}`),this.emit(`datachannel:${w.label}`,B.label,$)}catch(N){this.logger.error("error parsing message",{error:N})}})}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(gl).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(gl)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new Ut("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 Ut("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new Io("not a sending Transport");if(r.readyState==="ended")throw new Ut("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 Vi("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:g,localId:S,rtpSender:E}=await this.awaitQueue.push(async()=>{const{offerSdp:b,callback:_,sender:w,mid:F}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:B,producerId:N}=await r({offer:b,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:F},codecOptions:c,producingTransportId:this.serverId}),$=await _(B);return{producerId:N,localId:$,rtpSender:w}},"Transport.produce");return this.createProducerObject({id:g,localId:S,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:E})}async createProducerObject(e){const r=new MD(a(this,un),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 Ut("closed");if(this.direction!=="recv")throw new Io("not a receiving transport");if(!await this.transportConnectionPromise)throw new Vi("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(g=>l.push(g)).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=xi(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=xi(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:ul(n)}}static parseHeaderExtensionMappings(e){const r=xi(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=xi(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:ul(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=Ha.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Ha.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("Created offer for closing consumers",{sdp:c.sdp}),c=Ha.setCodecAndFmtpMappings(c,i,n),c=Ha.setHeaderExtensionMappings(c,o),this.logger.info("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("Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("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("Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("Created answer corresponding to received offer",{sdp:r.sdp});const i=xi(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=ul(i),this.logger.info("Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("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:g}=e,S=`${c}:${h}`,E={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(b,_)=>{const w=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${n}`),this.consumerTrackEvents.delete(S),E.isTimedout=!0,_(E)},5e3),F=(N,$)=>{try{if(N.readyState==="ended")clearTimeout(w),_(E);else{const Y=N;Y.enabled=!0,this.handler.midTransceiverMap.set($.mid,$);const ae=new AD(a(this,un),{id:r,localId:$.mid,transceiver:$,track:Y,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:$.receiver,mimeType:g});this.consumers.set(r,ae),ae.once("close",()=>{this.consumers.delete(ae.id),this.handler.midTransceiverMap.delete($.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",ae),clearTimeout(w),b(ae)}}catch(Y){this.logger.warn("error while creating consumer:",Y),clearTimeout(w),_(E)}},B=this.unknownTracksMap.get(S);B?(this.logger.info(`track event already received [trackId: ${B.track.id}] [mid: ${B.transceiver.mid}]`),this.unknownTracksMap.delete(S),F(B.track,B.transceiver)):(this.logger.info(`Registering onTrack handler for key ${S} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(S,F))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`${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 SD("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 Xh=Ha;un=new WeakMap;function ND(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=Dp.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 VD{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");m(this,Cr,void 0);m(this,hn,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,Cr,t),f(this,hn,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,hn).debug(`Device::constructor() | handler given: ${e}`);else if(e=ND(a(this,hn)),e)a(this,hn).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Kh.createFactory(a(this,Cr));break;case"Safari12":this.handlerFactory=Yh.createFactory(a(this,Cr));break;case"Firefox60":this.handlerFactory=hl.createFactory(a(this,Cr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=hl.createFactory(a(this,Cr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=vi();return new Xh(a(this,Cr),{id:e,...t,handlerFactory:this.handlerFactory})}}Cr=new WeakMap,hn=new WeakMap;const LD=2e3;class xD extends lt.EventEmitter{constructor(e,r){super();m(this,Wa);m(this,mc);m(this,Gl);m(this,fc);m(this,Wl);m(this,Jl);m(this,Kl);m(this,zl);m(this,Yl);m(this,Sc);m(this,vc);p(this,"context");m(this,qa,void 0);m(this,Tt,void 0);m(this,yt,void 0);m(this,hc,void 0);m(this,pc,void 0);m(this,pn,void 0);m(this,ja,void 0);m(this,gc,void 0);m(this,Ga,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});m(this,gn,void 0);m(this,Xs,"all");this.context=e,f(this,pn,r),f(this,qa,new VD(e)),f(this,ja,new ED(r)),f(this,gc,_s),a(this,Wa,Pu).mediaState={send:{state:Jn.NEW},recv:{state:Jn.NEW}},(xn(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(X.FORCE_RELAY))&&f(this,Xs,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,Xs)}`),x(this,mc,bp).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,pn)}get socketHandler(){return a(this,ja)}get sendTransport(){return a(this,Tt)}get recvTransport(){return a(this,yt)}get events(){return a(this,gc)}set sendTransportConnectedCallback(e){f(this,hc,e)}set recvTransportConnectedCallback(e){f(this,pc,e)}async setupTransports(e){await x(this,Gl,Rv).call(this,e);let r,i;e.send&&(r=x(this,fc,wp).call(this,a(this,Tt)).then(n=>{try{a(this,hc).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=x(this,fc,wp).call(this,a(this,yt)).then(n=>{try{a(this,pc).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,Tt);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,Tt).close(),a(this,Tt).removeAllListeners(),f(this,Tt,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,yt);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,yt))==null||r.close(),(i=a(this,yt))==null||i.removeAllListeners(),f(this,yt,void 0)}x(this,mc,bp).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}qa=new WeakMap,Tt=new WeakMap,yt=new WeakMap,hc=new WeakMap,pc=new WeakMap,pn=new WeakMap,ja=new WeakMap,gc=new WeakMap,Ga=new WeakMap,gn=new WeakMap,Xs=new WeakMap,Wa=new WeakSet,Pu=function(){return this.context.getValue("connectionHandler")},mc=new WeakSet,bp=function(){f(this,gn,{send:void 0,recv:void 0})},Gl=new WeakSet,Rv=async function(e){var o,c,d,l,u,h,g,S;(xn(this.context,"forceRelay")||this.context.getValue("flagsmith").hasFeature(X.FORCE_RELAY))&&f(this,Xs,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,Xs)}`);const n=await pt().getICEServers().catch(E=>(this.logger.warn(`failed to get iceservers from server: ${E.message}`),[]));if(e.send){const E=this.context.getValue("flagsmith").hasFeature(X.DISABLE_OPUS_DTX_CF);x(this,Jl,Iv).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:(g=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?g:!1,enableDtx:!!E},iceTransportPolicy:a(this,Xs)})}e.recv&&x(this,Kl,Av).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,Xs)})},fc=new WeakSet,wp=async function(e){const{id:r,serverId:i,direction:n}=e;x(this,zl,Mv).call(this,e);try{return await mS(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 Vi("Cannot reconnect closed transport");await x(this,Wl,kv).call(this,e)}catch(l){if(l instanceof Vi){d(l);return}throw this.logger.error("Failed to connect transport, retrying",{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:1/0}),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}},Wl=new WeakSet,kv=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,pn).isConnected)throw new Vi("Socket is not connected");if(e.connectionState==="closed")throw new Vi("Transport is closed");try{await e.connect(n=>x(this,Yl,Ov).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,Ga).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Vi(n.message):n}},Jl=new WeakSet,Iv=function(e){var r,i;if(a(this,Tt)&&a(this,Tt).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,Tt))==null?void 0:r.id,serverId:(i=a(this,Tt))==null?void 0:i.serverId,type:"send"}});return}f(this,Tt,a(this,qa).createTransport({...e,direction:"send"})),this.context.getValue("callstats").configureSendTransport(a(this,Tt))},Kl=new WeakSet,Av=function(e){var r,i;if(a(this,yt)&&a(this,yt).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,yt))==null?void 0:r.id,serverId:(i=a(this,yt))==null?void 0:i.serverId,type:"recv"}});return}f(this,yt,a(this,qa).createTransport({...e,direction:"recv"})),this.context.getValue("callstats").configureRecvTransport(a(this,yt))},zl=new WeakSet,Mv=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",async n=>{x(this,vc,Pp).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,gn)[r];c!==void 0&&(clearTimeout(c),a(this,gn)[r]=void 0)};switch(n){case"connected":o(),a(this,Ga).lastConnectionTime=performance.now();break;case"disconnected":a(this,gn)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await x(this,Sc,_p).call(this,e.direction)},LD);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 x(this,Sc,_p).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,DD(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",{country:y.location.country}),this.handleErrors("reconnectRecvTransport"))})},Yl=new WeakSet,Ov=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?or.SUBSCRIBER:or.PUBLISHER},producers:[]};return a(this,ja).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n,country:y.location.country}),n}},Sc=new WeakSet,_p=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),this.context.getValue("flagsmith").hasFeature(X.CF_TRANSPORT_FORCE_RELAY_ON_ICE_FAILED)&&a(this,pn).isConnected&&a(this,Ga).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,Xs,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,Tt)}),this.context.getValue("peerSessionStore").emit(R.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,yt)}),this.context.getValue("peerSessionStore").emit(R.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}x(this,vc,Pp).call(this,{state:Jn.CONNECTED,direction:e})},vc=new WeakSet,Pp=function(e){const{state:r,direction:i}=e;a(this,Wa,Pu).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(R.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Wa,Pu).mediaState[i]})};class UD{constructor(t,e,r,i,n){m(this,Tc,void 0);m(this,Ss,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,Tc,t),f(this,Ss,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,g=a(this,Tc).getValue("flagsmith").hasFeature(X.ENABLE_CF_SIMULCAST)?{simulcast:{preferredRid:"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}}:{};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...g})});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,Ss).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(g){}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,Ss).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,Ss).debug(`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:or.SUBSCRIBER}};return a(this,Ss).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,cR.toBinary(r)),a(this,Ss).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,Ss).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,Ss).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:or.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=Vk.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,Ss).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}Tc=new WeakMap,Ss=new WeakMap;class Zh{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return xi(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,g;const c=Zh.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:or.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(g=n[0])==null?void 0:g.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}class FD extends xD{constructor(e,r){super(e,r);m(this,Ec);m(this,Xl);m(this,Zl);m(this,eu);m(this,tu);m(this,mn,void 0);m(this,ui,void 0);m(this,Ja,void 0);m(this,yc,void 0);m(this,Zs,void 0);m(this,Ql,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});m(this,Rr,[]);m(this,Ka,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,yc,new Zh(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,Ja).clear(),f(this,Zs,new UD(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,mn)}get consumers(){return a(this,ui)}get producerIdToConsumerIdMap(){return a(this,Ja)}get logger(){return this.context.getValue("logger")}reset(){f(this,mn,new Map),f(this,ui,new Map),f(this,Ja,new Map)}async createProducer(e,r){var i;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const n=await this.sendTransport.produce(e,x(this,Xl,Dv).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,n),x(this,Zl,Nv).call(this,n,r),n}catch(n){throw this.logger.error("Failed to create producer",{error:n}),a(this,Ql).producerCreationFailureCount+=1,n}}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(R.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,mn).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,Ka)||clearTimeout(a(this,Ka)),f(this,Rr,a(this,Rr).concat(e)),await x(this,Ec,Cp).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,Zs))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,Zs).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,ui).keys()))}async switchConsumersToLayer(e,r){a(this,Zs).switchConsumersToLayer(e,r)}}mn=new WeakMap,ui=new WeakMap,Ja=new WeakMap,yc=new WeakMap,Zs=new WeakMap,Ql=new WeakMap,Rr=new WeakMap,Ka=new WeakMap,Ec=new WeakSet,Cp=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,Rr).splice(0,a(this,Rr).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,x(this,eu,Vv).bind(this),a(this,Zs).negotiate.bind(a(this,Zs)));if(o.forEach(x(this,tu,Lv).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,Rr,a(this,Rr).concat(d)),f(this,Ka,setTimeout(x(this,Ec,Cp).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})}}},Xl=new WeakSet,Dv=function(e){return a(this,yc).create(e)},Zl=new WeakSet,Nv=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!==gl){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:or.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,mn).set(e.id,e)},eu=new WeakSet,Vv=async function(e){try{return await this.recvTransport.canConsume(),await a(this,Zs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},tu=new WeakSet,Lv=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,ui).delete(e.id),this.context.getValue("peerSessionStore").emit(R.CONSUMER_CLOSED,{id:e.id})}),a(this,ui).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(R.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};const au=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}={}){m(this,su);m(this,ru);m(this,bc,void 0);m(this,wc,void 0);m(this,_c,void 0);m(this,za,void 0);m(this,Ya,void 0);m(this,Qa,void 0);m(this,Pc,void 0);m(this,Cc,void 0);m(this,Xa,void 0);m(this,$t,void 0);m(this,Vs,void 0);m(this,Ls,!1);m(this,fn,0);m(this,Sn,0);m(this,kr,[]);m(this,Rc,void 0);f(this,za,t),f(this,$t,t),f(this,bc,e),f(this,wc,r),f(this,_c,i),f(this,Ya,n),f(this,Qa,o),f(this,Pc,c),f(this,Cc,d),f(this,Xa,l),f(this,Rc,u),f(this,Vs,t/2)}get voiceDetected(){return a(this,Ls)}processAudioChunk(t){var o,c;const e=x(o=au,iu,Fv).call(o,t),r=x(c=au,nu,Bv).call(c,t);return x(this,su,xv).call(this,e),e/a(this,Vs)>a(this,Xa)&&e>a(this,$t)&&r>a(this,bc)?(f(this,fn,a(this,fn)+1),f(this,Sn,a(this,_c)),a(this,fn)>=a(this,wc)&&f(this,Ls,!0)):(f(this,fn,0),a(this,Sn)>0?f(this,Sn,a(this,Sn)-1):a(this,Ls)&&f(this,Ls,!1),a(this,Ls)||x(this,ru,Uv).call(this,e)),{energy:e,isVoice:a(this,Ls)}}reset(){f(this,Ls,!1),f(this,fn,0),f(this,Sn,0),f(this,$t,a(this,za)),f(this,Vs,a(this,za)/2),f(this,kr,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,$t),backgroundNoiseEnergy:a(this,Vs),energyRatioThreshold:a(this,Xa)}}};let Mo=au;bc=new WeakMap,wc=new WeakMap,_c=new WeakMap,za=new WeakMap,Ya=new WeakMap,Qa=new WeakMap,Pc=new WeakMap,Cc=new WeakMap,Xa=new WeakMap,$t=new WeakMap,Vs=new WeakMap,Ls=new WeakMap,fn=new WeakMap,Sn=new WeakMap,kr=new WeakMap,Rc=new WeakMap,su=new WeakSet,xv=function(t){a(this,Ls)?f(this,$t,a(this,Qa)*a(this,$t)+(1-a(this,Qa))*t):f(this,$t,a(this,Ya)*a(this,$t)+(1-a(this,Ya))*a(this,Vs)),f(this,$t,Math.max(a(this,Pc),Math.min(a(this,Cc),a(this,$t))))},ru=new WeakSet,Uv=function(t){if(t<a(this,$t)*1.2)if(a(this,kr).push(t),a(this,kr).length>a(this,Rc)&&a(this,kr).shift(),a(this,kr).length>=10){const e=[...a(this,kr)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,Vs,e[r])}else f(this,Vs,.95*a(this,Vs)+.05*t)},iu=new WeakSet,Fv=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},nu=new WeakSet,Bv=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(Mo,iu),m(Mo,nu);class yS{constructor(t){p(this,"RNAudioSampleHandler");m(this,kc,void 0);f(this,kc,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,kc).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()}}kc=new WeakMap;class ES{constructor(t){p(this,"audioContext");p(this,"analyser");m(this,Ic,void 0);f(this,Ic,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,Ic).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)}}Ic=new WeakMap;class BD{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 $D=60,HD=400,Oc=class{constructor(t,e){m(this,ou);m(this,cu);m(this,Ir,void 0);m(this,Ar,void 0);m(this,xs,void 0);m(this,Ac,void 0);m(this,vn,void 0);m(this,Za,void 0);m(this,Mr,void 0);m(this,hi,void 0);m(this,eo,void 0);m(this,Or,void 0);m(this,Dr,void 0);m(this,er,void 0);this.reportRequest=e,f(this,Or,t),f(this,Za,new Mo);const{isReactNative:r}=navigator;f(this,Dr,r?new yS(a(this,Or)):new ES(a(this,Or))),f(this,er,r?BD:tS)}get logger(){return a(this,Or).getValue("logger")}set producerId(t){f(this,xs,t)}set audioTrack(t){f(this,Ac,t),a(this,Dr)instanceof ES&&(a(this,Dr).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,xs)}`),a(this,Ir)&&a(this,er).clearInterval(a(this,Ir)),f(this,Ir,a(this,er).setInterval(async()=>{var i;if(!a(this,Ac)||!a(this,xs))return;const{energy:t}=x(this,ou,$v).call(this),e=x(i=Oc,Mc,Rp).call(i,t);let r=.9;a(this,eo)!==e&&a(this,eo)?r=.9:e?r=.3:r=.5,f(this,vn,(a(this,vn)||0)*(1-r)+t*r)},$D)),a(this,Ar)&&a(this,er).clearInterval(a(this,Ar)),f(this,Ar,a(this,er).setInterval(x(this,cu,Hv).bind(this),HD))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,xs)}`),a(this,Ir)&&(a(this,er).clearInterval(a(this,Ir)),f(this,Ir,void 0)),a(this,Ar)&&(a(this,er).clearInterval(a(this,Ar)),f(this,Ar,void 0))}catch(t){}a(this,Za).reset(),a(this,Dr)instanceof yS&&a(this,Dr).stop()}};let Oo=Oc;Ir=new WeakMap,Ar=new WeakMap,xs=new WeakMap,Ac=new WeakMap,vn=new WeakMap,Za=new WeakMap,Mr=new WeakMap,hi=new WeakMap,eo=new WeakMap,Or=new WeakMap,Dr=new WeakMap,er=new WeakMap,ou=new WeakSet,$v=function(){var o;const{samples:t}=a(this,Dr),{energy:e,isVoice:r}=a(this,Za).processAudioChunk(t),i=x(o=Oc,du,qv).call(o,e);return a(this,Or).getValue("flagsmith").hasFeature(X.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: producer: ${a(this,xs)}, energy: ${a(this,vn)},
19
19
  slogScale: ${i}, isVoice: ${r}, minEnergy: ${a(this,Mr)},
20
- maxEnergy: ${a(this,hi)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,Mr)||i<a(this,Mr))&&f(this,Mr,i),(!a(this,hi)||i>a(this,hi))&&f(this,hi,i),{energy:(i-a(this,Mr))/(a(this,hi)-a(this,Mr))*10||0,isVoice:r})},Mc=new WeakSet,Rp=function(t){return t<5},cu=new WeakSet,Hv=function(t=a(this,vn)){var r;if(!a(this,xs)||!t){a(this,Or).getValue("flagsmith").hasFeature(X.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,xs)}`);return}const e={producerId:a(this,xs),energy:Math.round(t),silent:x(r=Oc,Mc,Rp).call(r,t)};f(this,eo,e.silent),this.reportRequest(e)},du=new WeakSet,qv=function(t){const e=Math.log10(t);return Math.round(e)},m(Oo,Mc),m(Oo,du);const qD=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,n=128,o=1;let c=0,d=null;const l=async()=>{try{const g=new Float32Array(n*o),S=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:n,numberOfChannels:o,timestamp:c,data:g});c+=n/i*1e6,await r.ready,await r.write(S)}catch(g){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const h=new MediaStream([e]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=s,h}catch(e){}const t=window.AudioContext||window.webkitAudioContext;if(t)try{const e=new t;if(!e||e.state!=="running"||!e.destination)return;const r=e.createOscillator();r.frequency.value=0,r.type="sine";const i=e.createGain();i.gain.value=0,r.connect(i);const n=e.createMediaStreamDestination();i.connect(n),r.start();const o=n.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},jD=(s=!1)=>{var n,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(n=t==null?void 0:t.getSettings().height)!=null?n:720,e.width=(o=t==null?void 0:t.getSettings().width)!=null?o:1280;const r=e.getContext("2d");r.fillStyle="black",r.fillRect(0,0,e.width,e.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,e.width,e.height)},1e3);const i=e.captureStream().getVideoTracks()[0];return Object.assign(i,{fakeTracks:"fakeTracks:fakeVideoTrack"}),i.enabled=s,i};var GD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,ce=(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&&GD(t,e,i),i};const Yt=["video/VP9","video/VP8"],bS=(up=class{constructor(s,t){m(this,pi);m(this,lu);m(this,uu);m(this,hu);m(this,xc);m(this,gu);m(this,mu);m(this,fu);m(this,ot);m(this,_n);m(this,Su);m(this,vu);m(this,Tu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Dc,void 0);m(this,Nc,void 0);m(this,Et,void 0);m(this,j,void 0);m(this,to,void 0);m(this,Mt,void 0);m(this,Tn,void 0);m(this,yn,void 0);m(this,En,void 0);m(this,Vc,void 0);m(this,vs,null);m(this,Nr,void 0);m(this,Lc,void 0);m(this,bn,void 0);m(this,wn,void 0);m(this,Ot,void 0);m(this,Ht,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,f(this,bn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,wn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Et,e),f(this,Tn,!1),f(this,j,new FD(s,e)),f(this,Mt,a(this,j).events),f(this,Nr,new Set),f(this,Ot,new Map),f(this,yn,!1),f(this,En,new Wh(s.getValue("logger"))),f(this,Ht,new Oo(this.context,a(this,j).socketHandler.audioActivity.bind(a(this,j).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Vc,Zu(async()=>{if(!a(this,pi,io).mediaJoinAttempted)return;const{roomJoined:n}=await this.joinRoom(a(this,Nc),a(this,Dc),!0,!0);n&&(this.context.getValue("peerSessionStore").emit(R.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(R.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,pi,io).mediaJoined}set mediaJoined(s){a(this,pi,io).mediaJoined=s}reset(){a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,Ot).clear(),a(this,Nr).clear(),f(this,vs,null),a(this,En).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),f(this,En,new Wh)}async joinRoom(s,t,e=!1,r=!1,i={}){a(this,pi,io).mediaJoinAttempted=!0,f(this,Tn,!0),e&&this.reset();try{return await a(this,En).push(()=>x(this,lu,jv).call(this,s,t,r,i),"joinRoom")}catch(n){return this.logger.error("Error in room joining process",{error:n}),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_FAILED),{roomJoined:!1}}}async initializeConnection(s,t,e=!1,r={}){return a(this,vs)?a(this,vs):(f(this,vs,(async()=>{try{await x(this,xc,kp).call(this,s,t,e,r)}catch(i){throw f(this,vs,null),i}})()),a(this,vs))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}async leaveRoom(){a(this,j).stopAllTransports(),f(this,yn,!1),a(this,pi,io).mediaJoinAttempted=!1;const s={closeRoom:!1};a(this,Et).sendMessagePromise(a(this,Mt).leaveRoom,DR.toBinary(s)).then(e=>{var r;(r=Ek.fromBinary(e.payload))!=null&&r.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(e=>{this.logger.error("error on sending leave room request",{error:e})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()}async activatePeers(s){return this.createConsumers(s)}async createConsumers(s){return s.length===0?Promise.resolve():a(this,j).createConsumers(s)}async closeConsumers(s){if(!s.length)return;const t=s.reduce((e,r)=>{const i=a(this,j).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);await a(this,j).closeConsumers(t)}async _shareWebcam(s,t){var h,g;const e=t==="video/VP9"?fe.WEBCAM:fe.WEBCAM_BACKUP,r=x(this,ot,Nt).call(this,e);if(r){const S=await r;if(a(this,j).producers.has(S)){const E=a(this,j).producers.get(S);if(!E.closed)return await E.replaceTrack({track:s}),await this.resumeWebcam(e),s;await this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(Yt.filter(S=>S!==t)),n=x(this,Tu,Zv).call(this,s,i),o=xn(this.context,"disableSimulcast"),c=(g=(h=this.context)==null?void 0:h.getValue("overrides"))==null?void 0:g.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(X.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),n.encodings=_1(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(X.TRACK_HINT)&&(n.track.contentHint=this.context.getValue("flagsmith").getValue(X.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ot).delete(e)},u=a(this,j).createProducer(n,l);return x(this,_n,dd).call(this,e,u.then(S=>S.id)),u.then(S=>S.track)}async shareWebcam(s){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:r.toString();if(t)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${t}`),this._shareWebcam(s,t);const e=Yt.filter(i=>{var n,o;return((o=(n=a(this,to).sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&a(this,wn).get(i).size>0});return e.length===0&&e.push(Yt[0]),await Promise.all(e.map(i=>(this.logger.debug(`Calling _shareWebcam with video codec: ${i}`),this._shareWebcam(s,i)))),s}async shareScreen(s){const{video:t,audio:e}=s;if(t===void 0)return;const r={track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ot).delete(fe.SCREENSHARE_VIDEO),a(this,Ot).delete(fe.SCREENSHARE_AUDIO)},n=a(this,j).createProducer(r,i);x(this,_n,dd).call(this,fe.SCREENSHARE_VIDEO,n.then(c=>c.id));let o;if(e){const c={track:e,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=a(this,j).createProducer(c,d),x(this,_n,dd).call(this,fe.SCREENSHARE_AUDIO,o.then(l=>l.id))}await Promise.all([n,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(s){try{if(s===void 0)throw new Ut("track undefined");const t=x(this,ot,Nt).call(this,fe.MIC);if(t){const n=await t;if(a(this,j).producers.has(n)){const o=a(this,j).producers.get(n);if(!o.closed){await o.replaceTrack({track:s}),await this.resumeMic(),a(this,Ht)&&(a(this,Ht).audioTrack=s,a(this,Ht).producerId=n,a(this,Ht).start());return}await a(this,j).closeProducer(n,{stopTrack:!1})}await this.shareMic(s);return}const e=x(this,vu,Xv).call(this,s),r=()=>{a(this,Ot).delete(fe.MIC)},i=a(this,j).createProducer(e,r);x(this,_n,dd).call(this,fe.MIC,i.then(n=>n.id)),await i.then(n=>{a(this,Ht)&&(a(this,Ht).audioTrack=n.track,a(this,Ht).producerId=n.id,a(this,Ht).start())})}catch(t){throw new C(t)}}async pauseMic(){var r;const s=await x(this,ot,Nt).call(this,fe.MIC),t=a(this,j).producers.get(s);if(!t){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}t.pause(),(r=a(this,Ht))==null||r.stop();const e={producerId:t.id,pause:!0};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(e))}async pauseWebcam(){const s=await x(this,ot,Nt).call(this,fe.WEBCAM),t=await x(this,ot,Nt).call(this,fe.WEBCAM_BACKUP),e=a(this,j).producers.get(s),r=a(this,j).producers.get(t);if(!e&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const i=n=>{const o={producerId:n.id,pause:!0};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await x(this,ot,Nt).call(this,fe.MIC),t=a(this,j).producers.get(s);if(!t){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(e))}async resumeWebcam(s=fe.WEBCAM){const t=await x(this,ot,Nt).call(this,s),e=a(this,j).producers.get(t);if(!e){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!e.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?fe.WEBCAM:fe.WEBCAM_BACKUP,e=await x(this,ot,Nt).call(this,t);x(this,Su,Qv).call(this,t),e&&await a(this,j).closeProducer(e)}async disableMic(){var t;const s=await x(this,ot,Nt).call(this,fe.MIC);s&&await a(this,j).closeProducer(s),(t=a(this,Ht))==null||t.stop(),a(this,Ot).delete(fe.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await x(this,ot,Nt).call(this,fe.SCREENSHARE_VIDEO),t=await x(this,ot,Nt).call(this,fe.SCREENSHARE_AUDIO);s&&await a(this,j).closeProducer(s),t&&await a(this,j).closeProducer(t),a(this,Nr).clear(),a(this,Ot).delete(fe.SCREENSHARE_VIDEO),a(this,Ot).delete(fe.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await x(this,ot,Nt).call(this,fe.WEBCAM),r=await x(this,ot,Nt).call(this,fe.WEBCAM_BACKUP);await a(this,j).closeProducer(e,{stopTrack:!1}),await a(this,j).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=await x(this,ot,Nt).call(this,fe.SCREENSHARE_VIDEO);await a(this,j).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}}async changeDisplayName(s,t){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!await a(this,j).socketHandler.changeDisplayName(e))throw new Error("failed to change display name!")}kick(s){const t={peerIds:[s]};a(this,j).socketHandler.kickPeer(t)}kickAll(){a(this,j).socketHandler.kickAll()}async muteAll(s){if(!await a(this,j).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,j).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(s){if(!await a(this,j).socketHandler.hostControlForPeer(s,"audio"))throw new Error("failed to mute given participant")}async disableVideo(s){if(!await a(this,j).socketHandler.hostControlForPeer(s,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(s){const t={participantId:s!=null?s:""};try{await a(this,Et).sendMessagePromise(a(this,Mt).globalPinPeer,JR.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}}validateScreenShare(s){return this.peerId===s.peerId&&a(this,j).producers.get(s.producerId)&&a(this,Nr).add(s.consumerPeerId),a(this,Nr).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));a(this,j).switchConsumersToLayer(e,t)}async handleSocketEvents(){a(this,Et).on(a(this,Mt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Qk.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===Ws.AUDIO?"audio/opus":"video/VP8"),i.kind===Ws.VIDEO&&!i.screenShare&&((e=(t=a(this,to).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(n=>n.mimeType===Yt[0]))>=0&&a(this,bn).get(Yt[0]).has(r)&&i.mimeType!==Yt[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(R.NEW_PRODUCER,{peerId:r,producer:{...i,kind:i.kind===Ws.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,Et).on(a(this,Mt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:n,screenShare:o}}=lf.fromBinary(s);if(o)return;const c=r===Ws.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${n}, kind:${c}, paused:${i} payload: ${JSON.stringify(lf.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(R.PRODUCER_TOGGLE,{peerId:t,producerId:n,paused:i,kind:c}),Array.from(this.getConsumers().values()).filter(l=>l.producerId===n).forEach(l=>{l.kind==="video"&&i||l.paused!==i&&(this.logger.debug(`consumer state mismatched for ${l.id}. updating consumer pause state ${l.paused} to ${i}`),i?(l.pause(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),a(this,Et).on(a(this,Mt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=hh.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),a(this,Nr).delete(t),a(this,j).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(R.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),a(this,Et).on(a(this,Mt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=eI.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(R.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=a(this,j).producerIdToConsumerIdMap.get(e);if(!r){this.logger.warn(`no consumer found for producer:${e}`);return}this.logger.info(`closing consumer ${r}, producer id: ${e}`),a(this,j).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,j).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(R.CONSUMER_CLOSED,{id:r})}).catch(i=>{this.logger.error("error closing consumer",{error:i})})}catch(t){this.logger.error("error on producer close broadcast",{error:t})}}),a(this,Et).on(a(this,Mt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Tn)&&!a(this,yn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_DISCONNECTED),a(this,Vc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=a(this,j).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(R.CONSUMER_SCORE_UPDATE,{id:e,kind:r.kind,peerId:r.peerId,score:t.score,scoreStats:t})})}),this.context.getValue("callstats").onProducerScore(s=>{s.forEach((t,e)=>{const r=Array.from(a(this,j).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(R.PRODUCER_SCORE_UPDATE,{id:e,kind:r.kind,appData:r.appData,score:t.score,scoreStats:t})})})}handlePeerCapabilities(s,t){var e,r,i,n;for(let o=0;o<=Yt.length;o+=1){const c=Yt[o];if(((r=(e=t==null?void 0:t.receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Yt.length-1){a(this,wn).get(c).add(s);break}}for(let o=0;o<=Yt.length;o+=1){const c=Yt[o];if(((n=(i=t==null?void 0:t.sender)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(d=>d.mimeType===c))>=0||o===Yt.length-1){a(this,bn).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(X.FORCE_VIDEO_CODEC)||(a(this,bn).forEach(t=>t.delete(s)),a(this,wn).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===Yt[0])&&this.disableWebcam(e)}))}},Dc=new WeakMap,Nc=new WeakMap,Et=new WeakMap,j=new WeakMap,to=new WeakMap,Mt=new WeakMap,Tn=new WeakMap,yn=new WeakMap,En=new WeakMap,Vc=new WeakMap,vs=new WeakMap,Nr=new WeakMap,Lc=new WeakMap,bn=new WeakMap,wn=new WeakMap,Ot=new WeakMap,Ht=new WeakMap,pi=new WeakSet,io=function(){return this.context.getValue("connectionHandler")},lu=new WeakSet,jv=async function(s,t,e,r){f(this,Nc,s);try{return a(this,vs)?await a(this,vs):await x(this,xc,kp).call(this,s,t,e,r),x(this,hu,Wv).call(this,t),{roomJoined:await x(this,uu,Gv).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{f(this,vs,null)}},uu=new WeakSet,Gv=async function(){try{this.mediaJoined=!0;const{roomState:s}=await a(this,j).socketHandler.notifySelfJoinComplete();return f(this,Dc,s.roomUuid),f(this,yn,!0),f(this,Tn,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},hu=new WeakSet,Wv=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...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(e)}catch(t){this.logger.error("Error reporting room joined analytics",{error:t})}},0)},xc=new WeakSet,kp=async function(s,t,e,r){var i,n;try{(n=a(this,Lc))!=null||f(this,Lc,x(i=bS,pu,Jv).call(i));const o=x(this,gu,Kv).call(this);await x(this,mu,zv).call(this,s,t,e,o),await a(this,j).setupTransports({send:!0,recv:!0}),await x(this,fu,Yv).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},pu=new WeakSet,Jv=function(){const{ipInfo:s}=pt();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},gu=new WeakSet,Kv=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=yD(s);return f(this,to,t),t},mu=new WeakSet,zv=async function(s,t,e,r){await mS(async(i,n)=>{if(!a(this,Et).isConnected){n(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{await a(this,j).socketHandler.joinRoom(t,s,r,e,a(this,Lc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})},fu=new WeakSet,Yv=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(X.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===H.Allowed&&e.push(this.shareWebcam(jD(!1))),s.canProduceAudio===H.Allowed){const r=qD(!1);r&&e.push(this.shareMic(r))}e.length>0&&await Promise.all(e)}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}},ot=new WeakSet,Nt=function(s){return a(this,Ot).get(s)},_n=new WeakSet,dd=function(s,t){return a(this,Ot).set(s,t)},Su=new WeakSet,Qv=function(s){return a(this,Ot).delete(s)},vu=new WeakSet,Xv=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},Tu=new WeakSet,Zv=function(s,t){return{track:s,codecOptions:t?t.map(e=>({name:e.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},m(up,pu),up);let re=bS;ce([y.trace("MediaNodeClient.reset",{country:y.location.country})],re.prototype,"reset",1),ce([y.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1),ce([y.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1),ce([y.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1),ce([y.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1),ce([y.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1),ce([y.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1),ce([y.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1),ce([y.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1),ce([y.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1),ce([y.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1),ce([y.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1),ce([y.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1),ce([y.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1),ce([y.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1),ce([y.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1),ce([y.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1),ce([y.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1),ce([y.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1),ce([y.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1),ce([y.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1),ce([y.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1),ce([y.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1),ce([y.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1),ce([y.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1),ce([y.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1),ce([y.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1),ce([y.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function wS(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 _S(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 JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,Fi=(s,t,e,r)=>{for(var i=r>1?void 0:r?KD(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&&JD(t,e,i),i};const PS=(pv=class{constructor(s,t,e,r){m(this,Dt);p(this,"self");p(this,"authToken");m(this,Pn,void 0);p(this,"viewType");m(this,Us,void 0);m(this,ee,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,ee,s),this.viewType=r,this.authToken=n,f(this,Pn,i),f(this,Us,e),t.config.viewType!==Vt.Chat&&this.setupEvents()}get peerId(){return a(this,ee).getValue("peerId")}get telemetry(){return a(this,ee).getValue("telemetry")}get logger(){return a(this,ee).getValue("logger")}get mediaJoined(){return a(this,ee).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=pt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await tt.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const u=!s.getValue("flagsmith").hasFeature(X.PRECALL_BANDWIDTH_TEST);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(g=>g.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(g=>g.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:Te.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Mm(s),skipConnectivityChecks:u}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new PS(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,Dt,rs).shareMic(s),this.self.audioEnabled||a(this,Dt,rs).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=await a(this,Dt,rs).shareWebcam(t);d&&d.id!==t.id&&a(this,ee).getValue("flagsmith").hasFeature(X.EXP_RESHARE)&&await a(this,Dt,rs).shareWebcam(d),this.self.videoEnabled||a(this,Dt,rs).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,Dt,rs))==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,ee).getValue("callstats").callEnded(),a(this,Dt,rs).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,ee).getValue("peerSessionStore").on(R.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,ee).getValue("flagsmith").hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(t=vi()),a(this,Pn).updateURL(t),a(this,ee).getValue("telemetry").resetPeerId(t),pt().setHeader("tracing-id",t),nr.remapContext(t,a(this,ee)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Us).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Us).on(Yd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,ee).getValue("peerSessionStore").emit(R.UPDATE_PERMISSIONS,t.patch)})}),a(this,Us).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Us).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Us).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,ee).getValue("peerSessionStore").onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(R.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,ee).getValue("peerSessionStore").on(R.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,ee).getValue("callstats").audioOff())}),a(this,ee).getValue("peerSessionStore").on(R.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,ee).getValue("callstats").videoOff())}),a(this,ee).getValue("peerSessionStore").onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(R.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,Us).joinRoom(this.self);a(this,Us).socket.flush();const e=Dh(t.stageType);if(a(this,ee).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),a(this,ee).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=a(this,ee).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,ee).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,ee).notify("stageStatus");try{(e=a(this,Pn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}_S(a(this,ee)),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,ee).getAllValues();try{if(e===Vt.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}wS(a(this,ee),{socket:a(this,Pn),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u}=(o=await((n=a(this,Dt,rs))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)return;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:c}),new C("Error: could not join media room","0002")}}async leaveMediaRoom(s){const t=a(this,ee).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Vt.Webinar)&&a(this,Dt,rs)&&(a(this,Dt,rs).mediaJoined&&s!=="disconnected"&&await a(this,Dt,rs).leaveRoom(),!(s==="stageLeft"&&t===Vt.Livestream)&&(a(this,Dt,rs).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()}},Pn=new WeakMap,Us=new WeakMap,ee=new WeakMap,Dt=new WeakSet,rs=function(){return a(this,ee).getValue("roomNodeClient")},pv);let jr=PS;Fi([y.trace("SelfController.resetSelf")],jr.prototype,"resetSelf",1),Fi([y.trace("SelfController.setupEvents")],jr.prototype,"setupEvents",1),Fi([y.trace("SelfController.joinRoom")],jr.prototype,"joinRoom",1),Fi([y.trace("SelfController.leaveRoom")],jr.prototype,"leaveRoom",1),Fi([y.trace("SelfController.joinMediaRoom")],jr.prototype,"joinMediaRoom",1),Fi([y.trace("SelfController.leaveMediaRoom")],jr.prototype,"leaveMediaRoom",1),Fi([y.trace("SelfController.init")],jr,"init",1);class zD{constructor(t){m(this,Uc,void 0);f(this,Uc,t)}on(t,e){let r;t===U.roomPeerCount?r=pf.fromBinary.bind(pf):r=Af.fromBinary.bind(Af),a(this,Uc).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Uc=new WeakMap;class YD{constructor(t,e){m(this,Fc,void 0);m(this,Bc,void 0);f(this,Fc,e),f(this,Bc,t)}get logger(){return a(this,Bc).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=ph.fromBinary.bind(ph),i=ph.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Fc).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Fc=new WeakMap,Bc=new WeakMap;var QD=Object.defineProperty,XD=Object.getOwnPropertyDescriptor,ep=(s,t,e,r)=>{for(var i=r>1?void 0:r?XD(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&&QD(t,e,i),i};class ml{constructor(t,e){m(this,Vr,void 0);m(this,so,void 0);f(this,Vr,e),f(this,so,t)}get logger(){return a(this,so).getValue("logger")}get telemetry(){return a(this,so).getValue("telemetry")}getPolls(){return a(this,Vr).sendMessagePromise(lr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Vr).sendMessage(lr.createPoll,HM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Vr).sendMessage(lr.votePoll,jM.toBinary(r))}on(t,e){let r,i;switch(t){case lr.updatePoll:case lr.createPoll:case lr.votePoll:{r=Ch.fromBinary.bind(Ch),i=Ch.create();break}}a(this,Vr).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,Vr).removeListeners(t)}}Vr=new WeakMap,so=new WeakMap,ep([y.trace("PollSocketHandler.getPolls")],ml.prototype,"getPolls",1),ep([y.trace("PollSocketHandler.createPoll")],ml.prototype,"createPoll",1),ep([y.trace("PollSocketHandler.votePoll")],ml.prototype,"votePoll",1);var ZD=Object.defineProperty,eN=Object.getOwnPropertyDescriptor,tN=(s,t,e,r)=>{for(var i=r>1?void 0:r?eN(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&&ZD(t,e,i),i};class CS{constructor(t,e){p(this,"socket");m(this,ts,void 0);f(this,ts,t),this.socket=e,this.handleSocketEvents(),a(this,ts).setValue("roomSocketHandler",this)}get telemetry(){return a(this,ts).getValue("telemetry")}get logger(){return a(this,ts).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(U.joinRoom,II.toBinary(e));try{const{peer:n}=Fn.fromBinary((await r).payload);a(this,ts).getValue("connectionHandler").socketJoined=!0,a(this,ts).getValue("peerSessionStore").emit(R.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,ts).getValue("peerSessionStore").emit(R.ROOM_STATE,d),a(this,ts).getValue("peerSessionStore").emit(R.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),new C("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,n)}}async getAllAddedParticipants(){try{return pA.fromBinary((await this.socket.sendMessagePromise(U.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(U.getRoomPeersInfo,TI.toBinary(n));i=fh.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(U.getRoomPeersInfo);t=fh.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(U.getRoomPeersInfo);t=fh.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(U.getPeerInfo,ff.toBinary({peerId:t}));e=Fn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=mf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomInfo);t=mf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=bf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomStageState);t=bf.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(U.broadcastMessage,Eo.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(U.broadcastToEntity,Eo.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(U.broadcastToEntity,Eo.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,MI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(U.kick,yf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,nf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,TA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,EA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Yd.updateUserPreset,YA.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=Eo.fromBinary(t);a(this,ts).getValue("peerSessionStore").emit(R.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=Eo.fromBinary(t);a(this,ts).getValue("peerSessionStore").emit(R.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=Fn.fromBinary.bind(Fn),i=Fn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?Ef.fromBinary(n,o):{requests:[]},i=Ef.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=Nf.fromBinary.bind(Nf);break}case Yd.updateUserPreset:{r=_f.fromBinary.bind(_f);break}case _s.peerJoinedBroadcast:case $r.peerJoinedBroadcast:{r=cf.fromBinary.bind(cf);break}case _s.selfJoinComplete:case $r.selfJoinComplete:{r=uh.fromBinary.bind(uh);break}case _s.globalPeerPinBroadcast:case $r.globalPeerPinBroadcast:{r=uf.fromBinary.bind(uf);break}case _s.selectedPeer:case $r.selectedPeer:{r=lh.fromBinary.bind(lh);break}case _s.selectedPeerDiff:case $r.selectedPeerDiff:{r=of.fromBinary.bind(of);break}case _s.leaveRoom:case $r.leaveRoom:{r=hh.fromBinary.bind(hh);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(Yd.getUserPresets,qA.toBinary(e)),i=JA.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}}}ts=new WeakMap,tN([y.trace("RoomSocketHandler.joinRoom")],CS.prototype,"joinRoom",1);class sN{constructor(t){m(this,qt,void 0);f(this,qt,t)}async getStageRequests(){const{payload:t}=await a(this,qt).sendMessagePromise(U.getStageRequests);return t?Ph.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,qt).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,qt).sendMessage(U.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,qt).sendMessage(U.grantStageAccess,OM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,qt).sendMessage(U.denyStageAccess,NM.toBinary(e))}joinStage(){return a(this,qt).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,qt).sendMessagePromise(U.leaveStage,Of.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,qt).sendMessagePromise(U.leaveStage,Of.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=Mf.fromBinary.bind(Mf);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=Ph.fromBinary.bind(Ph);break}case U.peerStageStatusUpdate:{r=hf.fromBinary.bind(hf);break}}a(this,qt).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,qt).sendMessagePromise(U.getPeerInfo,ff.toBinary({peerId:t}));return Fn.fromBinary(e.payload)}}qt=new WeakMap;class rN{constructor(t,e){m(this,Qe,void 0);m(this,$c,void 0);f(this,Qe,e),f(this,$c,t)}get logger(){return a(this,$c).getValue("logger")}addPlugin(t,e){a(this,Qe).sendMessage(G.addPlugin,z0.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,Qe).sendMessage(G.removePlugin,Q0.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,Qe).sendMessagePromise(G.getPlugins);return t?yM.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,Qe).sendMessage(G.customPluginEventToRoom,oM.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,Qe).sendMessage(G.customPluginEventToPeers,dM.toBinary(n),i)}enablePluginForRoom(t,e){a(this,Qe).sendMessage(G.enablePluginForRoom,Z0.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,Qe).sendMessage(G.enablePluginForPeers,rM.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,Qe).sendMessage(G.disablePluginForRoom,tM.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,Qe).sendMessage(G.disablePluginForPeers,nM.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,Qe).sendMessage(G.storeInsertKeys,Cf.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,Qe).sendMessage(G.storeGetKeys,pM.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,Qe).sendMessage(G.storeDeleteKeys,mM.toBinary(n),i)}storeDelete(t,e,r){a(this,Qe).sendMessage(G.storeDelete,SM.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,Qe).sendMessage(G.storeInsertKeys,Cf.toBinary(i))}on(t,e){let r;switch(t){case G.addPlugin:case G.enablePluginForPeers:case G.enablePluginForRoom:{r=_h.fromBinary.bind(_h);break}case G.removePlugin:case G.disablePluginForPeers:case G.disablePluginForRoom:{r=Rf.fromBinary.bind(Rf);break}case G.customPluginEventToPeers:case G.customPluginEventToRoom:{r=If.fromBinary.bind(If);break}case G.storeInsertKeys:case G.storeGetKeys:case G.storeDeleteKeys:case G.storeDelete:{r=kf.fromBinary.bind(kf);break}}a(this,Qe).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Qe=new WeakMap,$c=new WeakMap;var iN=Object.defineProperty,nN=(s,t,e)=>t in s?iN(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,aN=(s,t,e)=>(nN(s,typeof t!="symbol"?t+"":t,e),e),tp=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},O=(s,t,e)=>(tp(s,t,"read from private field"),e?e.call(s):t.get(s)),Ee=(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)=>(tp(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Pe=(s,t,e)=>(tp(s,t,"access private method"),e),fl={},oN={get exports(){return fl},set exports(s){fl=s}},Kn=typeof Reflect=="object"?Reflect:null,RS=Kn&&typeof Kn.apply=="function"?Kn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},Sl;Kn&&typeof Kn.ownKeys=="function"?Sl=Kn.ownKeys:Object.getOwnPropertySymbols?Sl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:Sl=function(s){return Object.getOwnPropertyNames(s)};function cN(s){console&&console.warn&&console.warn(s)}var kS=Number.isNaN||function(s){return s!==s};function de(){de.init.call(this)}oN.exports=de,fl.once=hN,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var IS=10;function vl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(de,"defaultMaxListeners",{enumerable:!0,get:function(){return IS},set:function(s){if(typeof s!="number"||s<0||kS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");IS=s}}),de.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},de.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||kS(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 AS(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return AS(this)},de.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")RS(c,this,t);else for(var d=c.length,l=VS(c,d),e=0;e<d;++e)RS(l[e],this,t);return!0};function MS(s,t,e,r){var i,n,o;if(vl(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=AS(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,cN(c)}return s}de.prototype.addListener=function(s,t){return MS(this,s,t,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(s,t){return MS(this,s,t,!0)};function dN(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function OS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=dN.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(s,t){return vl(t),this.on(s,OS(this,s,t)),this},de.prototype.prependOnceListener=function(s,t){return vl(t),this.prependListener(s,OS(this,s,t)),this},de.prototype.removeListener=function(s,t){var e,r,i,n,o;if(vl(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():lN(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},de.prototype.off=de.prototype.removeListener,de.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 DS(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?uN(i):VS(i,i.length)}de.prototype.listeners=function(s){return DS(this,s,!0)},de.prototype.rawListeners=function(s){return DS(this,s,!1)},de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):NS.call(s,t)},de.prototype.listenerCount=NS;function NS(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}de.prototype.eventNames=function(){return this._eventsCount>0?Sl(this._events):[]};function VS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function lN(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function uN(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function hN(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))}LS(s,t,n,{once:!0}),t!=="error"&&pN(s,i,{once:!0})})}function pN(s,t,e){typeof s.on=="function"&&LS(s,"error",t,e)}function LS(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 gN 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 xS=new gN;class US{static encode(t){return xS.toBinary(t)}static decode(t){return xS.fromBinary(new Uint8Array(t))}}function mN(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Gr;class fN{constructor(t={}){aN(this,"opts"),Ee(this,Gr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Gr,0)}async wait(){ie(this,Gr,O(this,Gr)+1);const t=mN(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**O(this,Gr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return O(this,Gr)}reset(){ie(this,Gr,0)}}Gr=new WeakMap;const Wr={debug:0,info:1,warn:2,error:3};var Bi,$i;class SN{constructor(t){Ee(this,Bi,void 0),Ee(this,$i,void 0),ie(this,Bi,console),ie(this,$i,t)}debug(...t){Wr[O(this,$i)]>Wr.debug||O(this,Bi).debug("[Sockrates]:",...t)}info(...t){Wr[O(this,$i)]>Wr.info||O(this,Bi).info("[Sockrates]:",...t)}warn(...t){Wr[O(this,$i)]>Wr.warn||O(this,Bi).warn("[Sockrates]:",...t)}error(...t){Wr[O(this,$i)]>Wr.error||O(this,Bi).error("[Sockrates]:",...t)}}Bi=new WeakMap,$i=new WeakMap;var FS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(FS||{});const vN="2",TN="3";var Ne,zn,Ce,Fe,Jr,st,gr,Kr,Is,Yn,mr,sp,BS,Do,Tl,rp,$S,ip,HS,yl,np,ap,qS,No,El,Vo,bl,wl,op,Qn,Lo,xo,_l;class yN{constructor(t,e){var g,S,E,b,_,w,F,B,N,$;Ee(this,sp),Ee(this,Do),Ee(this,rp),Ee(this,ip),Ee(this,yl),Ee(this,ap),Ee(this,No),Ee(this,Vo),Ee(this,wl),Ee(this,Qn),Ee(this,xo),Ee(this,Ne,void 0),Ee(this,zn,void 0),Ee(this,Ce,void 0),Ee(this,Fe,void 0),Ee(this,Jr,void 0),Ee(this,st,void 0),Ee(this,gr,void 0),Ee(this,Kr,void 0),Ee(this,Is,void 0),Ee(this,Yn,void 0),Ee(this,mr,void 0);var r,i,n,o,c,d,l,u,h;ie(this,zn,t),ie(this,Jr,[]),ie(this,st,new fl),ie(this,gr,!0),ie(this,Is,!1),ie(this,Ce,e!=null?e:{}),(g=(r=O(this,Ce)).autoReconnect)!=null||(r.autoReconnect=!0),(S=(i=O(this,Ce)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(n=O(this,Ce)).pingTimeout)!=null||(n.pingTimeout=3e4),(b=(o=O(this,Ce)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(_=(c=O(this,Ce)).debug)!=null||(c.debug=!0),(w=(d=O(this,Ce)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(F=(l=O(this,Ce)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(B=(u=O(this,Ce)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(N=(h=O(this,Ce)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ie(this,Kr,{code:void 0,reason:void 0}),ie(this,Fe,($=O(this,Ce).logger)!=null?$:new SN(O(this,Ce).debug?"debug":"info")),ie(this,mr,new fN)}get readyState(){var t;return(t=O(this,Ne))==null?void 0:t.readyState}get url(){return O(this,zn)}updateURL(t){ie(this,zn,t),Pe(this,ap,qS).call(this)}get config(){return O(this,Ce)}get sendQueue(){return O(this,Jr)}flush(){if(!O(this,Ce).queueOnDisconnect)return!1;const t=[];return O(this,Jr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Jr,t),O(this,Jr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){O(this,Fe).debug("Websocket was already connecting or connected.");return}if(O(this,gr)!==!1)return new Promise((e,r)=>{Pe(this,Qn,Lo).call(this),Pe(this,xo,_l).call(this);try{ie(this,Ne,new WebSocket(Pe(this,sp,BS).call(this,O(this,zn)))),O(this,Ne).binaryType="arraybuffer",O(this,Fe).debug("Connecting");const i=setTimeout(()=>{O(this,Fe).debug("Connection timeout. Closing socket"),ie(this,gr,!0),Pe(this,xo,_l).call(this),O(this,Ne).close(3001,"Connection Timeout"),O(this,Ce).autoReconnect&&!O(this,Is)&&(O(this,st).emit("reconnecting"),Pe(this,No,El).call(this)),r(new Error("Connection timed out!"))},O(this,Ce).connectionTimeout);O(this,Ne).onopen=()=>{O(this,Fe).debug(`Ready State: ${FS[O(this,Ne).readyState]}`),i&&clearTimeout(i),Pe(this,wl,op).call(this),ie(this,Kr,{code:void 0,reason:void 0}),O(this,st).emit("connected"),O(this,Ce).flushOnReconnect&&this.flush(),e()},O(this,Ne).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),O(this,Fe).debug("Socket closed. Close event:",{event:n}),O(this,Fe).debug(`Connection closed code: ${o}`),O(this,Fe).debug(`Connection closed reason: ${c}`),O(this,Is)||Pe(this,yl,np).call(this,o,c)}catch(o){Pe(this,Do,Tl).call(this,o)}},O(this,Ne).onerror=n=>{Pe(this,Do,Tl).call(this,n)},O(this,Ne).onmessage=n=>Pe(this,rp,$S).call(this,n)}catch(i){Pe(this,Do,Tl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(O(this,Ce).queueOnDisconnect&&(!O(this,Ne)||O(this,Ne).readyState!==1))return O(this,Fe).debug("Queuing message since socket is not connected!",n),O(this,Jr).push(n),!1;const o=US.encode(n);return Pe(this,Vo,bl).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,Vo,bl).call(this,t)}receive(t,e){return O(this,st).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")){O(this,st).on(t,e);return}this.receive(t,e)}removeAllListeners(){O(this,st).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){O(this,st).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){O(this,st).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,gr,!1),Pe(this,Qn,Lo).call(this),this.removeAllListeners(),ie(this,Kr,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,Ne).close(1e3,"Sockrates disconnect method called.")}}Ne=new WeakMap,zn=new WeakMap,Ce=new WeakMap,Fe=new WeakMap,Jr=new WeakMap,st=new WeakMap,gr=new WeakMap,Kr=new WeakMap,Is=new WeakMap,Yn=new WeakMap,mr=new WeakMap,sp=new WeakSet,BS=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)://.")},Do=new WeakSet,Tl=function(s,t){O(this,Fe).error("Error:",{error:s}),O(this,st).emit("errored",{error:s}),t==null||t(s)},rp=new WeakSet,$S=function(s){if(Pe(this,wl,op).call(this),s.data===vN){O(this,Fe).debug("Received ping from server"),Pe(this,Vo,bl).call(this,TN);return}const t=US.decode(s.data),{id:e,payload:r}=t;O(this,Fe).debug("Received message",{event:t.event,messageID:e}),O(this,st).emit(t.event.toString(),{id:e,payload:r})},ip=new WeakSet,HS=function(){return O(this,Ne).readyState===1},yl=new WeakSet,np=function(s,t){ie(this,Kr,{reason:t,code:s}),O(this,st).emit("disconnected",{code:s,reason:t})},ap=new WeakSet,qS=function(){const{reason:s,code:t}=O(this,Kr);t&&t!==1e3&&O(this,gr)&&O(this,Ce).autoReconnect&&!O(this,Is)&&(O(this,Fe).debug(`Triggering reconnection due to ${s}.`),O(this,st).emit("reconnecting"),Pe(this,No,El).call(this))},No=new WeakSet,El=async function(s=!0){if(s&&O(this,Is)){O(this,Fe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,Is)||O(this,mr).reset(),O(this,Ce).maxReconnectionAttempts!==null&&O(this,mr).getAttempts()>=O(this,Ce).maxReconnectionAttempts){O(this,st).emit("failed"),ie(this,Is,!1);return}ie(this,Is,!0),Pe(this,xo,_l).call(this),Pe(this,Qn,Lo).call(this);try{if(await O(this,mr).wait(),O(this,gr)===!1)return;if(O(this,Fe).debug(`Reconnection attempt ${O(this,mr).getAttempts()}`),O(this,st).emit("reconnectAttempt",{attempt:O(this,mr).getAttempts()}),await this.connect(),!Pe(this,ip,HS).call(this))throw Error("Reconnect Failed");ie(this,Is,!1),ie(this,Kr,{code:void 0,reason:void 0}),O(this,st).emit("reconnected")}catch(t){O(this,Fe).debug("Failed to reconnect."),O(this,st).emit("reconnectFailure",{attempt:O(this,mr).getAttempts()}),Pe(this,No,El).call(this,!1)}},Vo=new WeakSet,bl=function(s){try{return O(this,Ne).send(s),!0}catch(t){return O(this,Fe).error(t.message),!1}},wl=new WeakSet,op=function(){this.config.disconnectOnPingTimeout&&(O(this,Fe).debug("Resetting ping timeout"),Pe(this,Qn,Lo).call(this),ie(this,Yn,setTimeout(()=>{var s;O(this,Fe).debug("Disconnecting the socket due to ping timeout"),ie(this,gr,!0);const t=3002,e="Ping timeout";(s=O(this,Ne))==null||s.close(t,e),Pe(this,yl,np).call(this,t,e)},O(this,Ce).pingTimeout)))},Qn=new WeakSet,Lo=function(){O(this,Yn)&&(clearTimeout(O(this,Yn)),ie(this,Yn,void 0))},xo=new WeakSet,_l=function(){O(this,Ne)&&(O(this,Ne).onopen=void 0,O(this,Ne).onerror=void 0,O(this,Ne).onmessage=void 0,O(this,Ne).onclose=void 0)};var EN=Object.defineProperty,bN=Object.getOwnPropertyDescriptor,Pl=(s,t,e,r)=>{for(var i=r>1?void 0:r?bN(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&&EN(t,e,i),i};const jS=65535,wN=3e3,GS=(gv=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,Oe);m(this,Hc);m(this,qc);m(this,gi,void 0);m(this,Me,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,Ts,void 0);m(this,ct,void 0);var n;if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");f(this,Ts,void 0),f(this,ct,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,gi,x(this,Hc,Ip).call(this,t)),f(this,Me,new yN(a(this,gi),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Oe,je).socketJoinAttempted}set joinAttempted(s){a(this,Oe,je).socketJoinAttempted=s}get telemetry(){return a(this,ct).getValue("telemetry")}get logger(){return a(this,ct).getValue("logger")}get peerId(){return a(this,ct).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,gi,x(this,Hc,Ip).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Me).updateURL(a(this,gi))}static getSocketEdgeDomain(s){return _i({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,gi)}async connect(){a(this,Oe,je).socketJoinAttempted=!0,await a(this,Me).connect(),a(this,Oe,je).socketJoinAttempted=!0,a(this,Oe,je).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Oe,je).socketJoinAttempted=!1,a(this,Me).disconnect(),a(this,Oe,je).socketJoinAttempted=!0,a(this,Oe,je).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Me).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,ct).getValue("telemetry").injectContext(r),a(this,Me).send(s,e!=null?e:x(this,qc,Ap).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,b)=>{a(this,Me).removeListener(n,E),a(this,Me).removeListener(jS,b),a(this,Me).removeListener($r.errorResponse,b),a(this,Me).removeListener(_s.errorResponse,b)},l=r!=null?r:x(this,qc,Ap).call(this),u={};a(this,ct).getValue("telemetry").injectContext(u);const g=({id:E,payload:b})=>{if(l===E){let _;try{const w=uk.fromBinary(b);_=new Error(w.errorMessage)}catch(w){_=new Error("failed to parse error message",{cause:w});try{const F=hI.fromBinary(b);_=new Error(F.message)}catch(F){_=new Error("failed to parse error message",{cause:F})}}c(_),d(S,g)}},S=({id:E,payload:b})=>{l===E&&(o({id:E,payload:b}),d(S,g))};a(this,Me).on(n,S),a(this,Me).on(jS,g),a(this,Me).on($r.errorResponse,g),a(this,Me).on(_s.errorResponse,g),setTimeout(()=>{d(S,g),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Me).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Me).on(s,t)}onStateEvent(s,t){a(this,Me).on(s,t)}removeListener(s,t){a(this,Me).removeListener(s,t)}removeListeners(s){a(this,Me).removeListeners(s)}flush(){return a(this,Me).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,Ts)&&(clearTimeout(a(this,Ts)),f(this,Ts,void 0)),a(this,Oe,je).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t},country:y.location.country});const{recv:e,send:r}=(i=a(this,Oe,je).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Jn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Jn.CONNECTED?a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Oe,je).joinAttempted}):f(this,Ts,setTimeout(()=>{a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Oe,je).joinAttempted}),f(this,Ts,void 0)},wN)),a(this,Oe,je).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:y.location.country}),a(this,Oe,je).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Oe,je).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Oe,je).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Oe,je).mediaJoinAttempted}}),a(this,Ts)&&(clearTimeout(a(this,Ts)),f(this,Ts,void 0)),a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Oe,je).mediaJoinAttempted}),a(this,Oe,je).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:y.location.country}),a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_FAILED),a(this,Oe,je).updateSocketConnectionState("failed")})}},gi=new WeakMap,Me=new WeakMap,Oe=new WeakSet,je=function(){return a(this,ct).getValue("connectionHandler")},Ts=new WeakMap,ct=new WeakMap,Hc=new WeakSet,Ip=function(s){let t=GS.getSocketEdgeDomain(a(this,ct).getValue("baseURI"));typeof xn(a(this,ct),"socket_server_base")=="string"&&(t=xn(a(this,ct),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,n={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...i!==s&&{oldPeerID:i},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Gd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(n).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},qc=new WeakSet,Ap=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},gv);let Uo=GS;Pl([y.trace("SocketService.connect")],Uo.prototype,"connect",1),Pl([y.trace("SocketService.disconnect")],Uo.prototype,"disconnect",1),Pl([y.trace("SocketService.sendMessagePromise")],Uo.prototype,"sendMessagePromise",1),Pl([y.trace("SocketService.sendMessagePromiseWithTimeout")],Uo.prototype,"sendMessagePromiseWithTimeout",1);class _N{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=FI.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=uA.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Tf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return vf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return tA.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(U.createConnectedRooms,qI.toBinary({payloads:t}));return vf.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(U.deleteConnectedRooms,ZI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,oA.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 PN=Object.defineProperty,CN=Object.getOwnPropertyDescriptor,RN=(s,t,e,r)=>{for(var i=r>1?void 0:r?CN(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&&PN(t,e,i),i};class WS extends Gt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Fs,void 0);f(this,Fs,e)}get supportsConnectedMeetings(){return a(this,Fs).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.
20
+ maxEnergy: ${a(this,hi)}`),i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,Mr)||i<a(this,Mr))&&f(this,Mr,i),(!a(this,hi)||i>a(this,hi))&&f(this,hi,i),{energy:(i-a(this,Mr))/(a(this,hi)-a(this,Mr))*10||0,isVoice:r})},Mc=new WeakSet,Rp=function(t){return t<5},cu=new WeakSet,Hv=function(t=a(this,vn)){var r;if(!a(this,xs)||!t){a(this,Or).getValue("flagsmith").hasFeature(X.ENABLE_AUDIO_ACTIVITY_DEBUG_LOGS)&&this.logger.debug(`AudioActivityReporter: No producerId or energy to report: ${a(this,xs)}`);return}const e={producerId:a(this,xs),energy:Math.round(t),silent:x(r=Oc,Mc,Rp).call(r,t)};f(this,eo,e.silent),this.reportRequest(e)},du=new WeakSet,qv=function(t){const e=Math.log10(t);return Math.round(e)},m(Oo,Mc),m(Oo,du);const qD=(s=!1)=>{if("MediaStreamTrackGenerator"in window&&"AudioData"in window)try{const e=new window.MediaStreamTrackGenerator({kind:"audio"}),r=e.writable.getWriter(),i=48e3,n=128,o=1;let c=0,d=null;const l=async()=>{try{const g=new Float32Array(n*o),S=new window.AudioData({format:"f32",sampleRate:i,numberOfFrames:n,numberOfChannels:o,timestamp:c,data:g});c+=n/i*1e6,await r.ready,await r.write(S)}catch(g){d&&clearInterval(d),r.releaseLock(),e.writable.abort()}};d=window.setInterval(l,100);const h=new MediaStream([e]).getAudioTracks()[0];return h.addEventListener("ended",()=>{d&&clearInterval(d),r.releaseLock(),e.writable.abort()}),Object.assign(h,{fakeTracks:"fakeTracks:fakeAudioTrack"}),h.enabled=s,h}catch(e){}const t=window.AudioContext||window.webkitAudioContext;if(t)try{const e=new t;if(!e||e.state!=="running"||!e.destination)return;const r=e.createOscillator();r.frequency.value=0,r.type="sine";const i=e.createGain();i.gain.value=0,r.connect(i);const n=e.createMediaStreamDestination();i.connect(n),r.start();const o=n.stream.getAudioTracks()[0];return o?(Object.assign(o,{fakeTracks:"fakeTracks:fakeAudioTrack"}),o.enabled=s,o):void 0}catch(e){return}},jD=(s=!1)=>{var n,o;const t=new MediaStream().getVideoTracks()[0],e=document.createElement("canvas");e.height=(n=t==null?void 0:t.getSettings().height)!=null?n:720,e.width=(o=t==null?void 0:t.getSettings().width)!=null?o:1280;const r=e.getContext("2d");r.fillStyle="black",r.fillRect(0,0,e.width,e.height),setInterval(()=>{r.fillStyle="black",r.fillRect(0,0,e.width,e.height)},1e3);const i=e.captureStream().getVideoTracks()[0];return Object.assign(i,{fakeTracks:"fakeTracks:fakeVideoTrack"}),i.enabled=s,i};var GD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,ce=(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&&GD(t,e,i),i};const Yt=["video/VP9","video/VP8"],bS=(up=class{constructor(s,t){m(this,pi);m(this,lu);m(this,uu);m(this,hu);m(this,xc);m(this,gu);m(this,mu);m(this,fu);m(this,ot);m(this,_n);m(this,Su);m(this,vu);m(this,Tu);p(this,"context");p(this,"authToken");p(this,"e2ee");m(this,Dc,void 0);m(this,Nc,void 0);m(this,Et,void 0);m(this,j,void 0);m(this,to,void 0);m(this,Mt,void 0);m(this,Tn,void 0);m(this,yn,void 0);m(this,En,void 0);m(this,Vc,void 0);m(this,vs,null);m(this,Nr,void 0);m(this,Lc,void 0);m(this,bn,void 0);m(this,wn,void 0);m(this,Ot,void 0);m(this,Ht,void 0);var r,i;this.context=s;const{socket:e}=t;this.mediaJoined=!1,f(this,bn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,wn,new Map([["video/VP9",new Set],["video/VP8",new Set]])),f(this,Et,e),f(this,Tn,!1),f(this,j,new FD(s,e)),f(this,Mt,a(this,j).events),f(this,Nr,new Set),f(this,Ot,new Map),f(this,yn,!1),f(this,En,new Wh(s.getValue("logger"))),f(this,Ht,new Oo(this.context,a(this,j).socketHandler.audioActivity.bind(a(this,j).socketHandler))),this.e2ee=(i=(r=s.getValue("modules").e2ee)==null?void 0:r.enabled)!=null?i:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,Vc,Zu(async()=>{if(!a(this,pi,io).mediaJoinAttempted)return;const{roomJoined:n}=await this.joinRoom(a(this,Nc),a(this,Dc),!0,!0);n&&(this.context.getValue("peerSessionStore").emit(R.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(R.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,pi,io).mediaJoined}set mediaJoined(s){a(this,pi,io).mediaJoined=s}reset(){a(this,j).closeAllProducers(),a(this,j).closeAllConsumers(),a(this,Ot).clear(),a(this,Nr).clear(),f(this,vs,null),a(this,En).stop(),a(this,j).stopAllTransports(),a(this,j).reset(),f(this,En,new Wh)}async joinRoom(s,t,e=!1,r=!1,i={}){a(this,pi,io).mediaJoinAttempted=!0,f(this,Tn,!0),e&&this.reset();try{return await a(this,En).push(()=>x(this,lu,jv).call(this,s,t,r,i),"joinRoom")}catch(n){return this.logger.error("Error in room joining process",{error:n}),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_FAILED),{roomJoined:!1}}}async initializeConnection(s,t,e=!1,r={}){return a(this,vs)?a(this,vs):(f(this,vs,(async()=>{try{await x(this,xc,kp).call(this,s,t,e,r)}catch(i){throw f(this,vs,null),i}})()),a(this,vs))}getConsumers(){return a(this,j).consumers}getProducers(){return a(this,j).producers}async leaveRoom(){a(this,j).stopAllTransports(),f(this,yn,!1),a(this,pi,io).mediaJoinAttempted=!1;const s={closeRoom:!1};a(this,Et).sendMessagePromise(a(this,Mt).leaveRoom,DR.toBinary(s)).then(e=>{var r;(r=Ek.fromBinary(e.payload))!=null&&r.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(e=>{this.logger.error("error on sending leave room request",{error:e})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct()}async activatePeers(s){return this.createConsumers(s)}async createConsumers(s){return s.length===0?Promise.resolve():a(this,j).createConsumers(s)}async closeConsumers(s){if(!s.length)return;const t=s.reduce((e,r)=>{const i=a(this,j).producerIdToConsumerIdMap.get(r.producerId);return i?(e.push(i),e):(this.logger.warn(`consumer not found in close consumers: ${r.producerId}`),e)},[]);await a(this,j).closeConsumers(t)}async _shareWebcam(s,t){var h,g;const e=t==="video/VP9"?fe.WEBCAM:fe.WEBCAM_BACKUP,r=x(this,ot,Nt).call(this,e);if(r){const S=await r;if(a(this,j).producers.has(S)){const E=a(this,j).producers.get(S);if(!E.closed)return await E.replaceTrack({track:s}),await this.resumeWebcam(e),s;await this.disableWebcam(t)}return this._shareWebcam(s,t)}const i=[t].concat(Yt.filter(S=>S!==t)),n=x(this,Tu,Zv).call(this,s,i),o=xn(this.context,"disableSimulcast"),c=(g=(h=this.context)==null?void 0:h.getValue("overrides"))==null?void 0:g.simulcastConfig;!(o||c&&c.disable)&&this.context.getValue("flagsmith").hasFeature(X.ENABLE_CF_SIMULCAST)?(this.logger.info("Simulcast enabled for SFU: CF"),n.encodings=_1(this.context,s)):this.logger.info("Simulcast disabled for webcam producer, SFU: CF"),this.context.getValue("flagsmith").hasFeature(X.TRACK_HINT)&&(n.track.contentHint=this.context.getValue("flagsmith").getValue(X.TRACK_HINT));const l=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,Ot).delete(e)},u=a(this,j).createProducer(n,l);return x(this,_n,dd).call(this,e,u.then(S=>S.id)),u.then(S=>S.track)}async shareWebcam(s){var r;if(s===void 0)return null;const t=(r=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:r.toString();if(t)return this.logger.debug(`Calling _shareWebcam with forced video codec: ${t}`),this._shareWebcam(s,t);const e=Yt.filter(i=>{var n,o;return((o=(n=a(this,to).sender)==null?void 0:n.video)==null?void 0:o.codecs.findIndex(c=>c.mimeType===i))>=0&&a(this,wn).get(i).size>0});return e.length===0&&e.push(Yt[0]),await Promise.all(e.map(i=>(this.logger.debug(`Calling _shareWebcam with video codec: ${i}`),this._shareWebcam(s,i)))),s}async shareScreen(s){const{video:t,audio:e}=s;if(t===void 0)return;const r={track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1},i=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Ot).delete(fe.SCREENSHARE_VIDEO),a(this,Ot).delete(fe.SCREENSHARE_AUDIO)},n=a(this,j).createProducer(r,i);x(this,_n,dd).call(this,fe.SCREENSHARE_VIDEO,n.then(c=>c.id));let o;if(e){const c={track:e,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},d=()=>{};o=a(this,j).createProducer(c,d),x(this,_n,dd).call(this,fe.SCREENSHARE_AUDIO,o.then(l=>l.id))}await Promise.all([n,o||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(s){try{if(s===void 0)throw new Ut("track undefined");const t=x(this,ot,Nt).call(this,fe.MIC);if(t){const n=await t;if(a(this,j).producers.has(n)){const o=a(this,j).producers.get(n);if(!o.closed){await o.replaceTrack({track:s}),await this.resumeMic(),a(this,Ht)&&(a(this,Ht).audioTrack=s,a(this,Ht).producerId=n,a(this,Ht).start());return}await a(this,j).closeProducer(n,{stopTrack:!1})}await this.shareMic(s);return}const e=x(this,vu,Xv).call(this,s),r=()=>{a(this,Ot).delete(fe.MIC)},i=a(this,j).createProducer(e,r);x(this,_n,dd).call(this,fe.MIC,i.then(n=>n.id)),await i.then(n=>{a(this,Ht)&&(a(this,Ht).audioTrack=n.track,a(this,Ht).producerId=n.id,a(this,Ht).start())})}catch(t){throw new C(t)}}async pauseMic(){var r;const s=await x(this,ot,Nt).call(this,fe.MIC),t=a(this,j).producers.get(s);if(!t){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(t.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}t.pause(),(r=a(this,Ht))==null||r.stop();const e={producerId:t.id,pause:!0};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(e))}async pauseWebcam(){const s=await x(this,ot,Nt).call(this,fe.WEBCAM),t=await x(this,ot,Nt).call(this,fe.WEBCAM_BACKUP),e=a(this,j).producers.get(s),r=a(this,j).producers.get(t);if(!e&&!r){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}const i=n=>{const o={producerId:n.id,pause:!0};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(o))};e&&(e.pause(),i(e)),r&&(r.pause(),i(r))}async resumeMic(){const s=await x(this,ot,Nt).call(this,fe.MIC),t=a(this,j).producers.get(s);if(!t){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!t.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}t.resume(),t.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,t);const e={producerId:t.id,pause:!1};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(e))}async resumeWebcam(s=fe.WEBCAM){const t=await x(this,ot,Nt).call(this,s),e=a(this,j).producers.get(t);if(!e){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!e.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(R.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,Et).sendMessage(a(this,Mt).toggleProducer,jd.toBinary(r))}async disableWebcam(s){const t=s==="video/VP9"?fe.WEBCAM:fe.WEBCAM_BACKUP,e=await x(this,ot,Nt).call(this,t);x(this,Su,Qv).call(this,t),e&&await a(this,j).closeProducer(e)}async disableMic(){var t;const s=await x(this,ot,Nt).call(this,fe.MIC);s&&await a(this,j).closeProducer(s),(t=a(this,Ht))==null||t.stop(),a(this,Ot).delete(fe.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const s=await x(this,ot,Nt).call(this,fe.SCREENSHARE_VIDEO),t=await x(this,ot,Nt).call(this,fe.SCREENSHARE_AUDIO);s&&await a(this,j).closeProducer(s),t&&await a(this,j).closeProducer(t),a(this,Nr).clear(),a(this,Ot).delete(fe.SCREENSHARE_VIDEO),a(this,Ot).delete(fe.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(s,t){if(s){const e=await x(this,ot,Nt).call(this,fe.WEBCAM),r=await x(this,ot,Nt).call(this,fe.WEBCAM_BACKUP);await a(this,j).closeProducer(e,{stopTrack:!1}),await a(this,j).closeProducer(r,{stopTrack:!1}),this.shareWebcam(s)}if(t){const e=await x(this,ot,Nt).call(this,fe.SCREENSHARE_VIDEO);await a(this,j).closeProducer(e,{stopTrack:!1}),this.shareScreen({video:t})}}async changeDisplayName(s,t){const e={displayName:s,participantId:t!=null?t:this.peerId};if(!await a(this,j).socketHandler.changeDisplayName(e))throw new Error("failed to change display name!")}kick(s){const t={peerIds:[s]};a(this,j).socketHandler.kickPeer(t)}kickAll(){a(this,j).socketHandler.kickAll()}async muteAll(s){if(!await a(this,j).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,j).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(s){if(!await a(this,j).socketHandler.hostControlForPeer(s,"audio"))throw new Error("failed to mute given participant")}async disableVideo(s){if(!await a(this,j).socketHandler.hostControlForPeer(s,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(s){const t={participantId:s!=null?s:""};try{await a(this,Et).sendMessagePromise(a(this,Mt).globalPinPeer,JR.toBinary(t))}catch(e){this.logger.error("Error in pinning peer:",{error:e})}}validateScreenShare(s){return this.peerId===s.peerId&&a(this,j).producers.get(s.producerId)&&a(this,Nr).add(s.consumerPeerId),a(this,Nr).size}async switchConsumersToLayer(s,t){const e=s.map(r=>this.getConsumers().get(r));a(this,j).switchConsumersToLayer(e,t)}async handleSocketEvents(){a(this,Et).on(a(this,Mt).peerProducerCreateBroadcast,({payload:s})=>{var t,e;if(this.mediaJoined)try{const{participantId:r,producerState:i}=Qk.fromBinary(s);if(r===this.peerId)return;if(i!=null&&i.mimeType||(i.mimeType=i.kind===Ws.AUDIO?"audio/opus":"video/VP8"),i.kind===Ws.VIDEO&&!i.screenShare&&((e=(t=a(this,to).receiver)==null?void 0:t.video)==null?void 0:e.codecs.findIndex(n=>n.mimeType===Yt[0]))>=0&&a(this,bn).get(Yt[0]).has(r)&&i.mimeType!==Yt[0]){this.logger.warn(`Ignoring producer: ${i.producerId}`);return}this.logger.info(`producer created broadcast: ${r}, producer state: ${i}`),this.context.getValue("peerSessionStore").emit(R.NEW_PRODUCER,{peerId:r,producer:{...i,kind:i.kind===Ws.AUDIO?"audio":"video",producingPeerId:r}})}catch(r){this.logger.error("error in peer-producer-create-broadcast",{error:r})}}),a(this,Et).on(a(this,Mt).peerProducerToggleBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,initiatorParticipantId:e,producerState:{kind:r,pause:i,producerId:n,screenShare:o}}=lf.fromBinary(s);if(o)return;const c=r===Ws.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${t}, producerId: ${n}, kind:${c}, paused:${i} payload: ${JSON.stringify(lf.fromBinary(s))}`),t===this.peerId&&e!==this.peerId&&i&&this.context.getValue("peerSessionStore").emit(c==="audio"?R.MUTE_SELF:R.MUTE_SELF_VIDEO),t===this.peerId)return;this.context.getValue("peerSessionStore").emit(R.PRODUCER_TOGGLE,{peerId:t,producerId:n,paused:i,kind:c}),Array.from(this.getConsumers().values()).filter(l=>l.producerId===n).forEach(l=>{l.kind==="video"&&i||l.paused!==i&&(this.logger.debug(`consumer state mismatched for ${l.id}. updating consumer pause state ${l.paused} to ${i}`),i?(l.pause(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_PAUSED,{id:l.id})):(l.resume(),this.context.getValue("peerSessionStore").emit(R.CONSUMER_RESUMED,{id:l.id})))})}catch(t){this.logger.error("error in producer toggle broadcast handler",{error:t})}}),a(this,Et).on(a(this,Mt).peerLeaveBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t}=hh.fromBinary(s);if(t===this.peerId)return;this.logger.info(`peer left broadcast:${t}`),a(this,Nr).delete(t),a(this,j).consumers.forEach(e=>{e.peerId===t&&e.close()}),this.context.getValue("peerSessionStore").emit(R.PEER_CLOSED,{id:t})}catch(t){this.logger.error("error in peer left broadcast",{error:t})}}),a(this,Et).on(a(this,Mt).peerProducerCloseBroadcast,({payload:s})=>{if(this.mediaJoined)try{const{participantId:t,producerState:{producerId:e}}=eI.fromBinary(s);if(t===this.peerId)return;this.logger.info(`producer closed broadcast:${t}`),this.context.getValue("peerSessionStore").emit(R.PRODUCER_CLOSED,{peerId:t,producerId:e});const r=a(this,j).producerIdToConsumerIdMap.get(e);if(!r){this.logger.warn(`no consumer found for producer:${e}`);return}this.logger.info(`closing consumer ${r}, producer id: ${e}`),a(this,j).closeConsumer(r).then(()=>{this.logger.info(`closed consumer: ${r}`),a(this,j).producerIdToConsumerIdMap.delete(e),this.context.getValue("peerSessionStore").emit(R.CONSUMER_CLOSED,{id:r})}).catch(i=>{this.logger.error("error closing consumer",{error:i})})}catch(t){this.logger.error("error on producer close broadcast",{error:t})}}),a(this,Et).on(a(this,Mt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,Tn)&&!a(this,yn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(R.ROOM_NODE_DISCONNECTED),a(this,Vc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(s=>{s.forEach((t,e)=>{const r=a(this,j).consumers.get(e);r&&this.context.getValue("peerSessionStore").emit(R.CONSUMER_SCORE_UPDATE,{id:e,kind:r.kind,peerId:r.peerId,score:t.score,scoreStats:t})})}),this.context.getValue("callstats").onProducerScore(s=>{s.forEach((t,e)=>{const r=Array.from(a(this,j).producers.values()).find(i=>i.id===e);r&&this.context.getValue("peerSessionStore").emit(R.PRODUCER_SCORE_UPDATE,{id:e,kind:r.kind,appData:r.appData,score:t.score,scoreStats:t})})})}handlePeerCapabilities(s,t){var e,r,i,n;for(let o=0;o<=Yt.length;o+=1){const c=Yt[o];if(((r=(e=t==null?void 0:t.receiver)==null?void 0:e.video)==null?void 0:r.codecs.findIndex(d=>d.mimeType===c))>=0||o===Yt.length-1){a(this,wn).get(c).add(s);break}}for(let o=0;o<=Yt.length;o+=1){const c=Yt[o];if(((n=(i=t==null?void 0:t.sender)==null?void 0:i.video)==null?void 0:n.codecs.findIndex(d=>d.mimeType===c))>=0||o===Yt.length-1){a(this,bn).get(c).add(s);break}}}handlePeerLeaving(s){this.context.getValue("flagsmith").hasFeature(X.FORCE_VIDEO_CODEC)||(a(this,bn).forEach(t=>t.delete(s)),a(this,wn).forEach((t,e)=>{t.delete(s),!(t.size!==0||e===Yt[0])&&this.disableWebcam(e)}))}},Dc=new WeakMap,Nc=new WeakMap,Et=new WeakMap,j=new WeakMap,to=new WeakMap,Mt=new WeakMap,Tn=new WeakMap,yn=new WeakMap,En=new WeakMap,Vc=new WeakMap,vs=new WeakMap,Nr=new WeakMap,Lc=new WeakMap,bn=new WeakMap,wn=new WeakMap,Ot=new WeakMap,Ht=new WeakMap,pi=new WeakSet,io=function(){return this.context.getValue("connectionHandler")},lu=new WeakSet,jv=async function(s,t,e,r){f(this,Nc,s);try{return a(this,vs)?await a(this,vs):await x(this,xc,kp).call(this,s,t,e,r),x(this,hu,Wv).call(this,t),{roomJoined:await x(this,uu,Gv).call(this)}}catch(i){return this.logger.error("Failed to complete room join",{error:i}),{roomJoined:!1}}finally{f(this,vs,null)}},uu=new WeakSet,Gv=async function(){try{this.mediaJoined=!0;const{roomState:s}=await a(this,j).socketHandler.notifySelfJoinComplete();return f(this,Dc,s.roomUuid),f(this,yn,!0),f(this,Tn,!1),!0}catch(s){return this.logger.error("Error completing room join",{error:s}),this.mediaJoined=!1,!1}},hu=new WeakSet,Wv=function(s){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const e={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:s,roomViewType:"groupCall",deviceInfo:{...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(e)}catch(t){this.logger.error("Error reporting room joined analytics",{error:t})}},0)},xc=new WeakSet,kp=async function(s,t,e,r){var i,n;try{(n=a(this,Lc))!=null||f(this,Lc,x(i=bS,pu,Jv).call(i));const o=x(this,gu,Kv).call(this);await x(this,mu,zv).call(this,s,t,e,o),await a(this,j).setupTransports({send:!0,recv:!0}),await x(this,fu,Yv).call(this,r)}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},pu=new WeakSet,Jv=function(){const{ipInfo:s}=pt();if(!(s!=null&&s.loc))return;const[t,e]=s.loc.split(",").map(parseFloat);return{latitude:t,longitude:e}},gu=new WeakSet,Kv=function(){var e;const s=(e=this.context.getValue("flagsmith").getValue(X.FORCE_VIDEO_CODEC))==null?void 0:e.toString(),t=yD(s);return f(this,to,t),t},mu=new WeakSet,zv=async function(s,t,e,r){await mS(async(i,n)=>{if(!a(this,Et).isConnected){n(new Error("Socket is not connected"));return}i>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${i}`});try{await a(this,j).socketHandler.joinRoom(t,s,r,e,a(this,Lc))}catch(o){throw this.logger.error("Failed to send joinRoom message after retries",{error:o}),o}},{delayTime:1e3,strategy:"exponential",maxRetryCount:1/0})},fu=new WeakSet,Yv=async function(s){if(!(!this.context.getValue("flagsmith").hasFeature(X.PRECREATE_PRODUCERS)||!s))try{const e=[];if(s.canProduceVideo===H.Allowed&&e.push(this.shareWebcam(jD(!1))),s.canProduceAudio===H.Allowed){const r=qD(!1);r&&e.push(this.shareMic(r))}e.length>0&&await Promise.all(e)}catch(e){this.logger.warn("Failed to precreate producers",{error:e})}},ot=new WeakSet,Nt=function(s){return a(this,Ot).get(s)},_n=new WeakSet,dd=function(s,t){return a(this,Ot).set(s,t)},Su=new WeakSet,Qv=function(s){return a(this,Ot).delete(s)},vu=new WeakSet,Xv=function(s){return{track:s,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},Tu=new WeakSet,Zv=function(s,t){return{track:s,codecOptions:t?t.map(e=>({name:e.split("/")[1]})):[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},m(up,pu),up);let re=bS;ce([y.trace("MediaNodeClient.reset",{country:y.location.country})],re.prototype,"reset",1),ce([y.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1),ce([y.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1),ce([y.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1),ce([y.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1),ce([y.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1),ce([y.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1),ce([y.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1),ce([y.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1),ce([y.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1),ce([y.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1),ce([y.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1),ce([y.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1),ce([y.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1),ce([y.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1),ce([y.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1),ce([y.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1),ce([y.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1),ce([y.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1),ce([y.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1),ce([y.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1),ce([y.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1),ce([y.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1),ce([y.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1),ce([y.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1),ce([y.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1),ce([y.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1),ce([y.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function wS(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 _S(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 JD=Object.defineProperty,KD=Object.getOwnPropertyDescriptor,Fi=(s,t,e,r)=>{for(var i=r>1?void 0:r?KD(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&&JD(t,e,i),i};const PS=(pv=class{constructor(s,t,e,r){m(this,Dt);p(this,"self");p(this,"authToken");m(this,Pn,void 0);p(this,"viewType");m(this,Us,void 0);m(this,ee,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,ee,s),this.viewType=r,this.authToken=n,f(this,Pn,i),f(this,Us,e),t.config.viewType!==Vt.Chat&&this.setupEvents()}get peerId(){return a(this,ee).getValue("peerId")}get telemetry(){return a(this,ee).getValue("telemetry")}get logger(){return a(this,ee).getValue("logger")}get mediaJoined(){return a(this,ee).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=pt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await tt.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");if(navigator.product!=="ReactNative"){const u=!s.getValue("flagsmith").hasFeature(X.PRECALL_BANDWIDTH_TEST);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(g=>g.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(g=>g.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(g=>g.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:Te.getDeviceInfo().engineName,env:s.getValue("env"),iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:s.getValue("flagsmith").getAllFlags(),logger:l,apiHostnames:Mm(s),skipConnectivityChecks:u}),l.info("Callstats:: initialized")}catch(g){l.error("Callstats:: initialization failed",{error:g})}},0)}else l.info("Callstats:: Skipped initialization due to navigator product being ReactNative.");return new PS(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,Dt,rs).shareMic(s),this.self.audioEnabled||a(this,Dt,rs).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{const d=await a(this,Dt,rs).shareWebcam(t);d&&d.id!==t.id&&a(this,ee).getValue("flagsmith").hasFeature(X.EXP_RESHARE)&&await a(this,Dt,rs).shareWebcam(d),this.self.videoEnabled||a(this,Dt,rs).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,Dt,rs))==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,ee).getValue("callstats").callEnded(),a(this,Dt,rs).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,ee).getValue("peerSessionStore").on(R.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(R.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;let{peerId:t}=this;s&&a(this,ee).getValue("flagsmith").hasFeature(X.REFRESH_ID_ON_DISCONNECTION)&&(t=vi()),a(this,Pn).updateURL(t),a(this,ee).getValue("telemetry").resetPeerId(t),pt().setHeader("tracing-id",t),nr.remapContext(t,a(this,ee)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,ee).getValue("peerSessionStore").on(R.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Us).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,Us).on(Yd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,ee).getValue("peerSessionStore").emit(R.UPDATE_PERMISSIONS,t.patch)})}),a(this,Us).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,Us).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,Us).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,ee).getValue("peerSessionStore").onAsync(R.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(R.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,ee).getValue("peerSessionStore").on(R.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,ee).getValue("callstats").audioOff())}),a(this,ee).getValue("peerSessionStore").on(R.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,ee).getValue("callstats").videoOff())}),a(this,ee).getValue("peerSessionStore").onAsync(R.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(R.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,Us).joinRoom(this.self);a(this,Us).socket.flush();const e=Dh(t.stageType);if(a(this,ee).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}await this.joinMediaRoom(s),a(this,ee).notify("stageStatus")}catch(t){throw this.logger.error("Error in joinRoom",{error:t}),t}}async leaveRoom(s="left"){var t,e;if(this.logger.info(`Leaving room with state: ${s}`),(t=a(this,ee).getValue("roomSocketHandler"))==null||t.cleanup(),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,ee).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,ee).notify("stageStatus");try{(e=a(this,Pn))==null||e.disconnect()}catch(r){this.logger.error("SelfController::leaveRoom::socketDisconnect")}_S(a(this,ee)),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,ee).getAllValues();try{if(e===Vt.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}wS(a(this,ee),{socket:a(this,Pn),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u}=(o=await((n=a(this,Dt,rs))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)return;i==="ON_STAGE"&&await this.shareMediaTracks(),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("Error:SelfController.mediaRoomJoin",{error:c}),new C("Error: could not join media room","0002")}}async leaveMediaRoom(s){const t=a(this,ee).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Vt.Webinar)&&a(this,Dt,rs)&&(a(this,Dt,rs).mediaJoined&&s!=="disconnected"&&await a(this,Dt,rs).leaveRoom(),!(s==="stageLeft"&&t===Vt.Livestream)&&(a(this,Dt,rs).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()}},Pn=new WeakMap,Us=new WeakMap,ee=new WeakMap,Dt=new WeakSet,rs=function(){return a(this,ee).getValue("roomNodeClient")},pv);let jr=PS;Fi([y.trace("SelfController.resetSelf")],jr.prototype,"resetSelf",1),Fi([y.trace("SelfController.setupEvents")],jr.prototype,"setupEvents",1),Fi([y.trace("SelfController.joinRoom")],jr.prototype,"joinRoom",1),Fi([y.trace("SelfController.leaveRoom")],jr.prototype,"leaveRoom",1),Fi([y.trace("SelfController.joinMediaRoom")],jr.prototype,"joinMediaRoom",1),Fi([y.trace("SelfController.leaveMediaRoom")],jr.prototype,"leaveMediaRoom",1),Fi([y.trace("SelfController.init")],jr,"init",1);class zD{constructor(t){m(this,Uc,void 0);f(this,Uc,t)}on(t,e){let r;t===U.roomPeerCount?r=pf.fromBinary.bind(pf):r=Af.fromBinary.bind(Af),a(this,Uc).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Uc=new WeakMap;class YD{constructor(t,e){m(this,Fc,void 0);m(this,Bc,void 0);f(this,Fc,e),f(this,Bc,t)}get logger(){return a(this,Bc).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=ph.fromBinary.bind(ph),i=ph.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,Fc).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)})}}Fc=new WeakMap,Bc=new WeakMap;var QD=Object.defineProperty,XD=Object.getOwnPropertyDescriptor,ep=(s,t,e,r)=>{for(var i=r>1?void 0:r?XD(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&&QD(t,e,i),i};class ml{constructor(t,e){m(this,Vr,void 0);m(this,so,void 0);f(this,Vr,e),f(this,so,t)}get logger(){return a(this,so).getValue("logger")}get telemetry(){return a(this,so).getValue("telemetry")}getPolls(){return a(this,Vr).sendMessagePromise(lr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Vr).sendMessage(lr.createPoll,HM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Vr).sendMessage(lr.votePoll,jM.toBinary(r))}on(t,e){let r,i;switch(t){case lr.updatePoll:case lr.createPoll:case lr.votePoll:{r=Ch.fromBinary.bind(Ch),i=Ch.create();break}}a(this,Vr).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,Vr).removeListeners(t)}}Vr=new WeakMap,so=new WeakMap,ep([y.trace("PollSocketHandler.getPolls")],ml.prototype,"getPolls",1),ep([y.trace("PollSocketHandler.createPoll")],ml.prototype,"createPoll",1),ep([y.trace("PollSocketHandler.votePoll")],ml.prototype,"votePoll",1);var ZD=Object.defineProperty,eN=Object.getOwnPropertyDescriptor,tN=(s,t,e,r)=>{for(var i=r>1?void 0:r?eN(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&&ZD(t,e,i),i};class CS{constructor(t,e){p(this,"socket");m(this,ts,void 0);f(this,ts,t),this.socket=e,this.handleSocketEvents(),a(this,ts).setValue("roomSocketHandler",this)}get telemetry(){return a(this,ts).getValue("telemetry")}get logger(){return a(this,ts).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(U.joinRoom,II.toBinary(e));try{const{peer:n}=Fn.fromBinary((await r).payload);a(this,ts).getValue("connectionHandler").socketJoined=!0,a(this,ts).getValue("peerSessionStore").emit(R.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,ts).getValue("peerSessionStore").emit(R.ROOM_STATE,d),a(this,ts).getValue("peerSessionStore").emit(R.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),new C("Error: RoomSocketHandler.joinRoom failed.","0002",this.logger,n)}}async getAllAddedParticipants(){try{return pA.fromBinary((await this.socket.sendMessagePromise(U.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(U.getRoomPeersInfo,TI.toBinary(n));i=fh.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(U.getRoomPeersInfo);t=fh.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(U.getRoomPeersInfo);t=fh.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(U.getPeerInfo,ff.toBinary({peerId:t}));e=Fn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=mf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomInfo);t=mf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=bf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomStageState);t=bf.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(U.broadcastMessage,Eo.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(U.broadcastToEntity,Eo.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(U.broadcastToEntity,Eo.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,MI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(U.kick,yf.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,nf.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,TA.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,EA.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Yd.updateUserPreset,YA.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=Eo.fromBinary(t);a(this,ts).getValue("peerSessionStore").emit(R.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=Eo.fromBinary(t);a(this,ts).getValue("peerSessionStore").emit(R.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=Fn.fromBinary.bind(Fn),i=Fn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?Ef.fromBinary(n,o):{requests:[]},i=Ef.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=Nf.fromBinary.bind(Nf);break}case Yd.updateUserPreset:{r=_f.fromBinary.bind(_f);break}case _s.peerJoinedBroadcast:case $r.peerJoinedBroadcast:{r=cf.fromBinary.bind(cf);break}case _s.selfJoinComplete:case $r.selfJoinComplete:{r=uh.fromBinary.bind(uh);break}case _s.globalPeerPinBroadcast:case $r.globalPeerPinBroadcast:{r=uf.fromBinary.bind(uf);break}case _s.selectedPeer:case $r.selectedPeer:{r=lh.fromBinary.bind(lh);break}case _s.selectedPeerDiff:case $r.selectedPeerDiff:{r=of.fromBinary.bind(of);break}case _s.leaveRoom:case $r.leaveRoom:{r=hh.fromBinary.bind(hh);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(Yd.getUserPresets,qA.toBinary(e)),i=JA.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}}}ts=new WeakMap,tN([y.trace("RoomSocketHandler.joinRoom")],CS.prototype,"joinRoom",1);class sN{constructor(t){m(this,qt,void 0);f(this,qt,t)}async getStageRequests(){const{payload:t}=await a(this,qt).sendMessagePromise(U.getStageRequests);return t?Ph.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,qt).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,qt).sendMessage(U.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,qt).sendMessage(U.grantStageAccess,OM.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,qt).sendMessage(U.denyStageAccess,NM.toBinary(e))}joinStage(){return a(this,qt).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,qt).sendMessagePromise(U.leaveStage,Of.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,qt).sendMessagePromise(U.leaveStage,Of.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=Mf.fromBinary.bind(Mf);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=Ph.fromBinary.bind(Ph);break}case U.peerStageStatusUpdate:{r=hf.fromBinary.bind(hf);break}}a(this,qt).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,qt).sendMessagePromise(U.getPeerInfo,ff.toBinary({peerId:t}));return Fn.fromBinary(e.payload)}}qt=new WeakMap;class rN{constructor(t,e){m(this,Qe,void 0);m(this,$c,void 0);f(this,Qe,e),f(this,$c,t)}get logger(){return a(this,$c).getValue("logger")}addPlugin(t,e){a(this,Qe).sendMessage(G.addPlugin,z0.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,Qe).sendMessage(G.removePlugin,Q0.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,Qe).sendMessagePromise(G.getPlugins);return t?yM.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,Qe).sendMessage(G.customPluginEventToRoom,oM.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,Qe).sendMessage(G.customPluginEventToPeers,dM.toBinary(n),i)}enablePluginForRoom(t,e){a(this,Qe).sendMessage(G.enablePluginForRoom,Z0.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,Qe).sendMessage(G.enablePluginForPeers,rM.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,Qe).sendMessage(G.disablePluginForRoom,tM.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,Qe).sendMessage(G.disablePluginForPeers,nM.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,Qe).sendMessage(G.storeInsertKeys,Cf.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,Qe).sendMessage(G.storeGetKeys,pM.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,Qe).sendMessage(G.storeDeleteKeys,mM.toBinary(n),i)}storeDelete(t,e,r){a(this,Qe).sendMessage(G.storeDelete,SM.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,Qe).sendMessage(G.storeInsertKeys,Cf.toBinary(i))}on(t,e){let r;switch(t){case G.addPlugin:case G.enablePluginForPeers:case G.enablePluginForRoom:{r=_h.fromBinary.bind(_h);break}case G.removePlugin:case G.disablePluginForPeers:case G.disablePluginForRoom:{r=Rf.fromBinary.bind(Rf);break}case G.customPluginEventToPeers:case G.customPluginEventToRoom:{r=If.fromBinary.bind(If);break}case G.storeInsertKeys:case G.storeGetKeys:case G.storeDeleteKeys:case G.storeDelete:{r=kf.fromBinary.bind(kf);break}}a(this,Qe).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}Qe=new WeakMap,$c=new WeakMap;var iN=Object.defineProperty,nN=(s,t,e)=>t in s?iN(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,aN=(s,t,e)=>(nN(s,typeof t!="symbol"?t+"":t,e),e),tp=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},O=(s,t,e)=>(tp(s,t,"read from private field"),e?e.call(s):t.get(s)),Ee=(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)=>(tp(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Pe=(s,t,e)=>(tp(s,t,"access private method"),e),fl={},oN={get exports(){return fl},set exports(s){fl=s}},Kn=typeof Reflect=="object"?Reflect:null,RS=Kn&&typeof Kn.apply=="function"?Kn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},Sl;Kn&&typeof Kn.ownKeys=="function"?Sl=Kn.ownKeys:Object.getOwnPropertySymbols?Sl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:Sl=function(s){return Object.getOwnPropertyNames(s)};function cN(s){console&&console.warn&&console.warn(s)}var kS=Number.isNaN||function(s){return s!==s};function de(){de.init.call(this)}oN.exports=de,fl.once=hN,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var IS=10;function vl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(de,"defaultMaxListeners",{enumerable:!0,get:function(){return IS},set:function(s){if(typeof s!="number"||s<0||kS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");IS=s}}),de.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},de.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||kS(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 AS(s){return s._maxListeners===void 0?de.defaultMaxListeners:s._maxListeners}de.prototype.getMaxListeners=function(){return AS(this)},de.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")RS(c,this,t);else for(var d=c.length,l=VS(c,d),e=0;e<d;++e)RS(l[e],this,t);return!0};function MS(s,t,e,r){var i,n,o;if(vl(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=AS(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,cN(c)}return s}de.prototype.addListener=function(s,t){return MS(this,s,t,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(s,t){return MS(this,s,t,!0)};function dN(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function OS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=dN.bind(r);return i.listener=e,r.wrapFn=i,i}de.prototype.once=function(s,t){return vl(t),this.on(s,OS(this,s,t)),this},de.prototype.prependOnceListener=function(s,t){return vl(t),this.prependListener(s,OS(this,s,t)),this},de.prototype.removeListener=function(s,t){var e,r,i,n,o;if(vl(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():lN(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},de.prototype.off=de.prototype.removeListener,de.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 DS(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?uN(i):VS(i,i.length)}de.prototype.listeners=function(s){return DS(this,s,!0)},de.prototype.rawListeners=function(s){return DS(this,s,!1)},de.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):NS.call(s,t)},de.prototype.listenerCount=NS;function NS(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}de.prototype.eventNames=function(){return this._eventsCount>0?Sl(this._events):[]};function VS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function lN(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function uN(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function hN(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))}LS(s,t,n,{once:!0}),t!=="error"&&pN(s,i,{once:!0})})}function pN(s,t,e){typeof s.on=="function"&&LS(s,"error",t,e)}function LS(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 gN 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 xS=new gN;class US{static encode(t){return xS.toBinary(t)}static decode(t){return xS.fromBinary(new Uint8Array(t))}}function mN(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Gr;class fN{constructor(t={}){aN(this,"opts"),Ee(this,Gr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Gr,0)}async wait(){ie(this,Gr,O(this,Gr)+1);const t=mN(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**O(this,Gr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return O(this,Gr)}reset(){ie(this,Gr,0)}}Gr=new WeakMap;const Wr={debug:0,info:1,warn:2,error:3};var Bi,$i;class SN{constructor(t){Ee(this,Bi,void 0),Ee(this,$i,void 0),ie(this,Bi,console),ie(this,$i,t)}debug(...t){Wr[O(this,$i)]>Wr.debug||O(this,Bi).debug("[Sockrates]:",...t)}info(...t){Wr[O(this,$i)]>Wr.info||O(this,Bi).info("[Sockrates]:",...t)}warn(...t){Wr[O(this,$i)]>Wr.warn||O(this,Bi).warn("[Sockrates]:",...t)}error(...t){Wr[O(this,$i)]>Wr.error||O(this,Bi).error("[Sockrates]:",...t)}}Bi=new WeakMap,$i=new WeakMap;var FS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(FS||{});const vN="2",TN="3";var Ne,zn,Ce,Fe,Jr,st,gr,Kr,Is,Yn,mr,sp,BS,Do,Tl,rp,$S,ip,HS,yl,np,ap,qS,No,El,Vo,bl,wl,op,Qn,Lo,xo,_l;class yN{constructor(t,e){var g,S,E,b,_,w,F,B,N,$;Ee(this,sp),Ee(this,Do),Ee(this,rp),Ee(this,ip),Ee(this,yl),Ee(this,ap),Ee(this,No),Ee(this,Vo),Ee(this,wl),Ee(this,Qn),Ee(this,xo),Ee(this,Ne,void 0),Ee(this,zn,void 0),Ee(this,Ce,void 0),Ee(this,Fe,void 0),Ee(this,Jr,void 0),Ee(this,st,void 0),Ee(this,gr,void 0),Ee(this,Kr,void 0),Ee(this,Is,void 0),Ee(this,Yn,void 0),Ee(this,mr,void 0);var r,i,n,o,c,d,l,u,h;ie(this,zn,t),ie(this,Jr,[]),ie(this,st,new fl),ie(this,gr,!0),ie(this,Is,!1),ie(this,Ce,e!=null?e:{}),(g=(r=O(this,Ce)).autoReconnect)!=null||(r.autoReconnect=!0),(S=(i=O(this,Ce)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(E=(n=O(this,Ce)).pingTimeout)!=null||(n.pingTimeout=3e4),(b=(o=O(this,Ce)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(_=(c=O(this,Ce)).debug)!=null||(c.debug=!0),(w=(d=O(this,Ce)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(F=(l=O(this,Ce)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(B=(u=O(this,Ce)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(N=(h=O(this,Ce)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ie(this,Kr,{code:void 0,reason:void 0}),ie(this,Fe,($=O(this,Ce).logger)!=null?$:new SN(O(this,Ce).debug?"debug":"info")),ie(this,mr,new fN)}get readyState(){var t;return(t=O(this,Ne))==null?void 0:t.readyState}get url(){return O(this,zn)}updateURL(t){ie(this,zn,t),Pe(this,ap,qS).call(this)}get config(){return O(this,Ce)}get sendQueue(){return O(this,Jr)}flush(){if(!O(this,Ce).queueOnDisconnect)return!1;const t=[];return O(this,Jr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Jr,t),O(this,Jr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){O(this,Fe).debug("Websocket was already connecting or connected.");return}if(O(this,gr)!==!1)return new Promise((e,r)=>{Pe(this,Qn,Lo).call(this),Pe(this,xo,_l).call(this);try{ie(this,Ne,new WebSocket(Pe(this,sp,BS).call(this,O(this,zn)))),O(this,Ne).binaryType="arraybuffer",O(this,Fe).debug("Connecting");const i=setTimeout(()=>{O(this,Fe).debug("Connection timeout. Closing socket"),ie(this,gr,!0),Pe(this,xo,_l).call(this),O(this,Ne).close(3001,"Connection Timeout"),O(this,Ce).autoReconnect&&!O(this,Is)&&(O(this,st).emit("reconnecting"),Pe(this,No,El).call(this)),r(new Error("Connection timed out!"))},O(this,Ce).connectionTimeout);O(this,Ne).onopen=()=>{O(this,Fe).debug(`Ready State: ${FS[O(this,Ne).readyState]}`),i&&clearTimeout(i),Pe(this,wl,op).call(this),ie(this,Kr,{code:void 0,reason:void 0}),O(this,st).emit("connected"),O(this,Ce).flushOnReconnect&&this.flush(),e()},O(this,Ne).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),O(this,Fe).debug("Socket closed. Close event:",{event:n}),O(this,Fe).debug(`Connection closed code: ${o}`),O(this,Fe).debug(`Connection closed reason: ${c}`),O(this,Is)||Pe(this,yl,np).call(this,o,c)}catch(o){Pe(this,Do,Tl).call(this,o)}},O(this,Ne).onerror=n=>{Pe(this,Do,Tl).call(this,n)},O(this,Ne).onmessage=n=>Pe(this,rp,$S).call(this,n)}catch(i){Pe(this,Do,Tl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(O(this,Ce).queueOnDisconnect&&(!O(this,Ne)||O(this,Ne).readyState!==1))return O(this,Fe).debug("Queuing message since socket is not connected!",n),O(this,Jr).push(n),!1;const o=US.encode(n);return Pe(this,Vo,bl).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Pe(this,Vo,bl).call(this,t)}receive(t,e){return O(this,st).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")){O(this,st).on(t,e);return}this.receive(t,e)}removeAllListeners(){O(this,st).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){O(this,st).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){O(this,st).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,gr,!1),Pe(this,Qn,Lo).call(this),this.removeAllListeners(),ie(this,Kr,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,Ne).close(1e3,"Sockrates disconnect method called.")}}Ne=new WeakMap,zn=new WeakMap,Ce=new WeakMap,Fe=new WeakMap,Jr=new WeakMap,st=new WeakMap,gr=new WeakMap,Kr=new WeakMap,Is=new WeakMap,Yn=new WeakMap,mr=new WeakMap,sp=new WeakSet,BS=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)://.")},Do=new WeakSet,Tl=function(s,t){O(this,Fe).error("Error:",{error:s}),O(this,st).emit("errored",{error:s}),t==null||t(s)},rp=new WeakSet,$S=function(s){if(Pe(this,wl,op).call(this),s.data===vN){O(this,Fe).debug("Received ping from server"),Pe(this,Vo,bl).call(this,TN);return}const t=US.decode(s.data),{id:e,payload:r}=t;O(this,Fe).debug("Received message",{event:t.event,messageID:e}),O(this,st).emit(t.event.toString(),{id:e,payload:r})},ip=new WeakSet,HS=function(){return O(this,Ne).readyState===1},yl=new WeakSet,np=function(s,t){ie(this,Kr,{reason:t,code:s}),O(this,st).emit("disconnected",{code:s,reason:t})},ap=new WeakSet,qS=function(){const{reason:s,code:t}=O(this,Kr);t&&t!==1e3&&O(this,gr)&&O(this,Ce).autoReconnect&&!O(this,Is)&&(O(this,Fe).debug(`Triggering reconnection due to ${s}.`),O(this,st).emit("reconnecting"),Pe(this,No,El).call(this))},No=new WeakSet,El=async function(s=!0){if(s&&O(this,Is)){O(this,Fe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,Is)||O(this,mr).reset(),O(this,Ce).maxReconnectionAttempts!==null&&O(this,mr).getAttempts()>=O(this,Ce).maxReconnectionAttempts){O(this,st).emit("failed"),ie(this,Is,!1);return}ie(this,Is,!0),Pe(this,xo,_l).call(this),Pe(this,Qn,Lo).call(this);try{if(await O(this,mr).wait(),O(this,gr)===!1)return;if(O(this,Fe).debug(`Reconnection attempt ${O(this,mr).getAttempts()}`),O(this,st).emit("reconnectAttempt",{attempt:O(this,mr).getAttempts()}),await this.connect(),!Pe(this,ip,HS).call(this))throw Error("Reconnect Failed");ie(this,Is,!1),ie(this,Kr,{code:void 0,reason:void 0}),O(this,st).emit("reconnected")}catch(t){O(this,Fe).debug("Failed to reconnect."),O(this,st).emit("reconnectFailure",{attempt:O(this,mr).getAttempts()}),Pe(this,No,El).call(this,!1)}},Vo=new WeakSet,bl=function(s){try{return O(this,Ne).send(s),!0}catch(t){return O(this,Fe).error(t.message),!1}},wl=new WeakSet,op=function(){this.config.disconnectOnPingTimeout&&(O(this,Fe).debug("Resetting ping timeout"),Pe(this,Qn,Lo).call(this),ie(this,Yn,setTimeout(()=>{var s;O(this,Fe).debug("Disconnecting the socket due to ping timeout"),ie(this,gr,!0);const t=3002,e="Ping timeout";(s=O(this,Ne))==null||s.close(t,e),Pe(this,yl,np).call(this,t,e)},O(this,Ce).pingTimeout)))},Qn=new WeakSet,Lo=function(){O(this,Yn)&&(clearTimeout(O(this,Yn)),ie(this,Yn,void 0))},xo=new WeakSet,_l=function(){O(this,Ne)&&(O(this,Ne).onopen=void 0,O(this,Ne).onerror=void 0,O(this,Ne).onmessage=void 0,O(this,Ne).onclose=void 0)};var EN=Object.defineProperty,bN=Object.getOwnPropertyDescriptor,Pl=(s,t,e,r)=>{for(var i=r>1?void 0:r?bN(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&&EN(t,e,i),i};const jS=65535,wN=3e3,GS=(gv=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){m(this,Oe);m(this,Hc);m(this,qc);m(this,gi,void 0);m(this,Me,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");m(this,Ts,void 0);m(this,ct,void 0);var n;if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");f(this,Ts,void 0),f(this,ct,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,gi,x(this,Hc,Ip).call(this,t)),f(this,Me,new yN(a(this,gi),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Oe,je).socketJoinAttempted}set joinAttempted(s){a(this,Oe,je).socketJoinAttempted=s}get telemetry(){return a(this,ct).getValue("telemetry")}get logger(){return a(this,ct).getValue("logger")}get peerId(){return a(this,ct).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,gi,x(this,Hc,Ip).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Me).updateURL(a(this,gi))}static getSocketEdgeDomain(s){return _i({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,gi)}async connect(){a(this,Oe,je).socketJoinAttempted=!0,await a(this,Me).connect(),a(this,Oe,je).socketJoinAttempted=!0,a(this,Oe,je).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Oe,je).socketJoinAttempted=!1,a(this,Me).disconnect(),a(this,Oe,je).socketJoinAttempted=!0,a(this,Oe,je).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Me).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,ct).getValue("telemetry").injectContext(r),a(this,Me).send(s,e!=null?e:x(this,qc,Ap).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,b)=>{a(this,Me).removeListener(n,E),a(this,Me).removeListener(jS,b),a(this,Me).removeListener($r.errorResponse,b),a(this,Me).removeListener(_s.errorResponse,b)},l=r!=null?r:x(this,qc,Ap).call(this),u={};a(this,ct).getValue("telemetry").injectContext(u);const g=({id:E,payload:b})=>{if(l===E){let _;try{const w=uk.fromBinary(b);_=new Error(w.errorMessage)}catch(w){_=new Error("failed to parse error message",{cause:w});try{const F=hI.fromBinary(b);_=new Error(F.message)}catch(F){_=new Error("failed to parse error message",{cause:F})}}c(_),d(S,g)}},S=({id:E,payload:b})=>{l===E&&(o({id:E,payload:b}),d(S,g))};a(this,Me).on(n,S),a(this,Me).on(jS,g),a(this,Me).on($r.errorResponse,g),a(this,Me).on(_s.errorResponse,g),setTimeout(()=>{d(S,g),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Me).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Me).on(s,t)}onStateEvent(s,t){a(this,Me).on(s,t)}removeListener(s,t){a(this,Me).removeListener(s,t)}removeListeners(s){a(this,Me).removeListeners(s)}flush(){return a(this,Me).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,Ts)&&(clearTimeout(a(this,Ts)),f(this,Ts,void 0)),a(this,Oe,je).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t},country:y.location.country});const{recv:e,send:r}=(i=a(this,Oe,je).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Jn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Jn.CONNECTED?a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Oe,je).joinAttempted}):f(this,Ts,setTimeout(()=>{a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Oe,je).joinAttempted}),f(this,Ts,void 0)},wN)),a(this,Oe,je).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge",{country:y.location.country}),a(this,Oe,je).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Oe,je).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Oe,je).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Oe,je).mediaJoinAttempted}}),a(this,Ts)&&(clearTimeout(a(this,Ts)),f(this,Ts,void 0)),a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Oe,je).mediaJoinAttempted}),a(this,Oe,je).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge",{country:y.location.country}),a(this,ct).getValue("peerSessionStore").emit(R.SOCKET_SERVICE_FAILED),a(this,Oe,je).updateSocketConnectionState("failed")})}},gi=new WeakMap,Me=new WeakMap,Oe=new WeakSet,je=function(){return a(this,ct).getValue("connectionHandler")},Ts=new WeakMap,ct=new WeakMap,Hc=new WeakSet,Ip=function(s){let t=GS.getSocketEdgeDomain(a(this,ct).getValue("baseURI"));typeof xn(a(this,ct),"socket_server_base")=="string"&&(t=xn(a(this,ct),"socket_server_base"));const e=`wss://${t}`,r=new URL(`${e}/ws`),i=this.peerId,n={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...i!==s&&{oldPeerID:i},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(o=>Gd[o]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(n).forEach(([o,c])=>{r.searchParams.append(o,c.toString())}),r.href},qc=new WeakSet,Ap=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},gv);let Uo=GS;Pl([y.trace("SocketService.connect")],Uo.prototype,"connect",1),Pl([y.trace("SocketService.disconnect")],Uo.prototype,"disconnect",1),Pl([y.trace("SocketService.sendMessagePromise")],Uo.prototype,"sendMessagePromise",1),Pl([y.trace("SocketService.sendMessagePromiseWithTimeout")],Uo.prototype,"sendMessagePromiseWithTimeout",1);class _N{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=FI.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=uA.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Tf.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return vf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return tA.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(U.createConnectedRooms,qI.toBinary({payloads:t}));return vf.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(U.deleteConnectedRooms,ZI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,oA.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 PN=Object.defineProperty,CN=Object.getOwnPropertyDescriptor,RN=(s,t,e,r)=>{for(var i=r>1?void 0:r?CN(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&&PN(t,e,i),i};class WS extends Gt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);m(this,Fs,void 0);f(this,Fs,e)}get supportsConnectedMeetings(){return a(this,Fs).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
21
21
  Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){return this.validateConnectedMeetingsAction(),await a(this,Fs).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump()}async createMeetings(e){return this.validateConnectedMeetingsAction(),(await a(this,Fs).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e)).map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateConnectedMeetingsAction(),await a(this,Fs).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title})))}async deleteMeetings(e){this.validateConnectedMeetingsAction();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());return await Promise.all(r),await a(this,Fs).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e)}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction();const n=await a(this,Fs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success&&this.moveSuccessHandler(e,r,i),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateConnectedMeetingsAction();const n=await a(this,Fs).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success&&this.moveSuccessHandler(e,r,i.map(o=>o.id)),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})}}Fs=new WeakMap,RN([Lt({maxInvocations:60,period:60})],WS.prototype,"getConnectedMeetings",1);var kN=Object.defineProperty,IN=Object.getOwnPropertyDescriptor,cp=(s,t,e,r)=>{for(var i=r>1?void 0:r?IN(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&&kN(t,e,i),i};const JS=(mv=class{constructor(s){p(this,"connectedMeetings");m(this,ve,void 0);f(this,ve,s),this.connectedMeetings=new WS(s)}get telemetry(){return a(this,ve).getValue("telemetry")}get logger(){return a(this,ve).getValue("logger")}static init(s){const t=new JS(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.transferPeer,this.handleTransferPeer.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.movedPeer,this.handleMovedPeer.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){const t=a(this,ve).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return 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.
22
22
  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,ve).getValue("self").videoEnabled,audio:a(this,ve).getValue("self").audioEnabled};try{a(this,ve).getValue("self").cleanupEvents(),await a(this,ve).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,ve).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 zS.init({...a(this,ve).getValue("options"),cachedUserDetails:null,defaults:{...a(this,ve).getValue("options").defaults,...e,mediaHandler:a(this,ve).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,ve).getValue("self");r.self.setName(a(this,ve).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,ve).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,ve).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,ve).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,ve).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})}},ve=new WeakMap,mv);let Cl=JS;cp([y.trace("ConnectedMeetingsController.getConnectedMeetings")],Cl.prototype,"getConnectedMeetings",1),cp([y.trace("ConnectedMeetingsController.setupEvents")],Cl.prototype,"setupEvents",1),cp([y.trace("ConnectedMeetingsController.switchMeeting")],Cl.prototype,"switchMeeting",1);var AN=Object.defineProperty,MN=Object.getOwnPropertyDescriptor,Rl=(s,t,e,r)=>{for(var i=r>1?void 0:r?MN(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&&AN(t,e,i),i};const Xn=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 N,$;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(_S(s),Te.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=wO(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 n1(s);s.setValue("connectionHandler",l);const u=Xn.createSocketService(s),h=u.connect(),g=d.getUserDetails(),S=d.getPlugins();let E,b="";try{await Xn.setupFlagsmith(s)}catch(Y){c.error("Failed to setup flagsmith",{error:Y})}try{await h}catch(Y){c.error("[Controller]: Failed to connect to socket server:",{error:Y})}try{({meetingTitle:b}=await d.getRoomNodeData()),E=await g,c.info("CF SFU is being used."),s.setValue("presetName",E.preset.name)}catch(Y){c.error("Failed to get room metadata",{error:Y})}const _=$h.init(E.preset,!s.getValue("modules").theme),w=qh.init(s,_.viewType,E.preset.permissions),F=Xn.setupControllers(u,s,E,S,b,_,w);KO(_)&&((N=Xn.createRoomNodeClient(s,u).initializeConnection(E.participant.name,i,!1,w))==null||N.catch(ae=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ae})})),y.location.country=($=d.ipInfo)==null?void 0:$.country;const{controllers:B}=await F;return TC(),new Xn(e,B,s)}static async setupFlagsmith(s){var l;const{peerId:t,baseURI:e,overrides:r,meetingId:i,organizationId:n,logger:o}=s.getAllValues(),c=vC(i),d={entity:sh.PEER,clientId:n,isAnonUser:!n,sdkVersion:s.getValue("sdkVersion"),presetName:s.getValue("presetName"),meetingHash:c,roomName:i,...Te.getDeviceInfo(),isReactNative:navigator.isReactNative};try{const u=(l=r==null?void 0:r.whitelabelled_flags_endpoint)==null||l?_i({servicePrefix:"flags",baseURI:e}):"edge.api.flagsmith.com";await s.getValue("flagsmith").identify(`${sh.PEER}_${t}`,JSON.parse(JSON.stringify(d)),!1,5e3,u,o),o.info("flagsmith::allFlags",{flags:JSON.stringify(s.getValue("flagsmith").getAllFlags())},!0)}catch(u){o.error("Failed to fetch flagsmith flags")}}static async setupControllers(s,t,e,r,i,n,o){var k,Ke,fi;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),u=t.getValue("logger"),{viewType:h,mediaConstraints:{audio:g}}=n;t.setValue("viewType",h),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(k=g.enableHighBitrate)!=null?k:!1,enableStereo:(Ke=g.enableStereo)!=null?Ke:!1}},...l}),t.setValue("maxPreferredStreams",Te.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let S,E,b,_,w,F,B,N,$;const Y=new YD(t,s),ae=new _N(s);t.setValue("connectedMeetingsSocketHandler",ae);const bt=new ml(t,s),Bs=new as(t,s),An=new sN(s),$s=new CS(t,s),I=new rN(t,s),T=new zD(s),P=new Ii(t,s),L=await jr.init(t,$s,d,o,n);t.setValue("selfController",L);const we=await qf.init(t,L.self,$s,Y,i);if(c.participant&&(N=new pr(t,L.self,$s)),(fi=c.e2ee)!=null&&fi.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(E=await Rs.init(t,Bs,P,L.self,N.participants)),c.internals&&(w=await Lh.init(t)),c.livestream&&n.viewType===Vt.Livestream&&t.getValue("flagsmith").hasFeature(X.LIVESTREAM)&&(B=new lS(t,L.self,T)),n.viewType!==Vt.Chat){if(c.poll&&(S=await Ff.init(t,L.self,bt)),c.recording&&(F=new Kf(t,L.self,$s)),c.stage&&(b=new jf(t,An,$s,L.self,N.participants)),c.plugin){if(!N)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const Lr=await r;_=await wo.init(t,Lr,I,Bs,E==null?void 0:E.chat,L.self,N.participants,i)}if(c.connectedMeetings&&($=await Cl.init(t)),c.pip){const Lr=await rh._init(t,L.self);t.setValue("pip",Lr)}}const V={storesManager:new sD(t,I),pollController:S,selfController:L,metaController:we,chatController:E,stageController:b,pluginController:_,recordingController:F,internalsController:w,livestreamController:B,participantController:N,connectedMeetingsController:$};return{theme:n,permissions:o,controllers:V}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return wS(s,{socket:t,peerId:e})}static createSocketService(s){const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),i=["PING"];return new Uo(s,{peerId:t,meetingId:e,authToken:r,capabilities:i})}};let Fo=Xn;Rl([y.trace("Controller.init")],Fo,"init",1),Rl([y.trace("setupFlagsmith")],Fo,"setupFlagsmith",1),Rl([y.trace("Controller.createRoomNodeClient")],Fo,"createRoomNodeClient",1),Rl([y.trace("Controller.createSocketService")],Fo,"createSocketService",1);class ON{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 KS=new ON;function DN(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=Pi.baseURI.prod;t&&(n=t);const o=`https://${_i({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}class NN{constructor(){m(this,yu);m(this,mi,new Audio);m(this,Cn,new MediaStream);m(this,Rn,new Map);m(this,jc,void 0);a(this,mi).srcObject=a(this,Cn),a(this,mi).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,Rn).has(e.id)||(a(this,Cn).addTrack(e),a(this,Rn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,mi).setSinkId(t)}removeTrack(t){const e=a(this,Rn).get(t);e&&(a(this,Cn).removeTrack(e),a(this,Rn).delete(t))}async play(){return a(this,mi).srcObject=a(this,Cn),a(this,mi).play().catch(t=>{x(this,yu,eT).call(this,t)})}onError(t){f(this,jc,t)}}mi=new WeakMap,Cn=new WeakMap,Rn=new WeakMap,jc=new WeakMap,yu=new WeakSet,eT=function(t){var e;(e=a(this,jc))==null||e.call(this,t)};class VN extends NN{constructor(){super();m(this,kn,void 0);f(this,kn,new Map)}addParticipantTrack(e,r){a(this,kn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,kn).get(e);r&&this.removeTrack(r),a(this,kn).delete(e)}}kn=new WeakMap;var LN=Object.defineProperty,xN=Object.getOwnPropertyDescriptor,kl=(s,t,e,r)=>{for(var i=r>1?void 0:r?xN(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&&LN(t,e,i),i};let zr=(fv=class{constructor(t,e){m(this,Xe,void 0);m(this,In,void 0);f(this,In,t),f(this,Xe,e)}get peerId(){return a(this,In).getValue("peerId")}static initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:vi(),n=nr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new pS(o);return c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var S,E,b,_,w,F,B;Te.init();const{mediaHandler:e}=(S=t.defaults)!=null?S:{},r=(e==null?void 0:e.peerId)||((b=(E=t==null?void 0:t.cachedUserDetails)==null?void 0:E.peerId)!=null?b:vi()),{authToken:i,baseURI:n}=t,{meetingId:o,...c}=DN(i,n);window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const d=zr.setupContext(r,t,o,c),l=d.getValue("telemetry"),u=d.getValue("logger");iT(u),KS.init(u),l.init(d,{roomName:o,userId:c.participantId,organizationId:c.orgId,peerId:r},(w=(_=t.modules)==null?void 0:_.tracing)!=null?w:!0),u.init(d),u.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(F=t.authToken)==null?void 0:F.slice(0,10)}...
23
- ${(B=t.authToken)==null?void 0:B.slice(-10)}`}});const h=await Fo.init(d),g=new zr(d,h);return d.setValue("meeting",g),g}static setupContext(t,e,r,i){var d,l;const n=nr.createContext(t,e),o={...cC,...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",dC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Cs(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.1-staging.6"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new VN),n}async join(){const{selfController:t}=a(this,Xe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){KS.cleanup(),a(this,In).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Xe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Xe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Xe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Xe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Xe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Xe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Xe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Xe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Xe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Xe).stageController)==null?void 0:t.stage}get stores(){return a(this,Xe).storesManager}get audio(){return a(this,In).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Xe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Xe=new WeakMap,In=new WeakMap,fv);kl([ut("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1),kl([ut("0003")],zr.prototype,"leave",1),kl([ut("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1),zr=kl([ut("0000")],zr);const zS=zr;return zS}();
23
+ ${(B=t.authToken)==null?void 0:B.slice(-10)}`}});const h=await Fo.init(d),g=new zr(d,h);return d.setValue("meeting",g),g}static setupContext(t,e,r,i){var d,l;const n=nr.createContext(t,e),o={...cC,...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",dC({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Cs(e.cachedUserDetails)),n.setValue("sdkVersion","1.2.1-staging.7"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new VN),n}async join(){const{selfController:t}=a(this,Xe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){KS.cleanup(),a(this,In).getValue("peerSessionStore").reset();const{selfController:e}=a(this,Xe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,Xe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,Xe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,Xe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,Xe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,Xe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,Xe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,Xe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,Xe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,Xe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,Xe).stageController)==null?void 0:t.stage}get stores(){return a(this,Xe).storesManager}get audio(){return a(this,In).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,Xe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},Xe=new WeakMap,In=new WeakMap,fv);kl([ut("0002"),ur.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],zr.prototype,"join",1),kl([ut("0003")],zr.prototype,"leave",1),kl([ut("0001"),ur.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],zr,"init",1),zr=kl([ut("0000")],zr);const zS=zr;return zS}();
@@ -1,5 +1,5 @@
1
1
  Name: @cloudflare/realtimekit
2
- Version: 1.2.1-staging.5
2
+ Version: 1.2.1-staging.6
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.