opensips-js-vue 0.1.10 → 0.1.12

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.
@@ -155,6 +155,6 @@ a=accept-types:text/plain text/html
155
155
  a=path:${n.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization_user}.${this._ua._configuration.realm}:2856/${this.auth_id};ws
156
156
  `),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,new yr(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:a=>{this.onTransportError(),console.log(a)},onAuthenticated:a=>{this._request=a},onReceiveResponse:a=>{this._receiveInviteResponse(a),a.status_code===200&&(a.parseSDP(!0),this._status=ye.STATUS_CONFIRMED,this.target_addr=a.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=ye.STATUS_INVITE_SENT}terminate(n={}){const s=n.cause||U.causes.BYE,i=ke.cloneArray(n.extraHeaders),a=n.body;let e,d=n.status_code,_=n.reason_phrase;if(this._status===ye.STATUS_TERMINATED)throw new Kn.InvalidStateError(this._status);switch(this.status="terminated",this._status){case ye.STATUS_NULL:case ye.STATUS_INVITE_SENT:case ye.STATUS_1XX_RECEIVED:if(d&&(d<200||d>=700))throw new TypeError(`Invalid status_code: ${d}`);d&&(_=_||U.REASON_PHRASE[d]||"",e=`SIP ;cause=${d} ;text="${_}"`),this._status===ye.STATUS_NULL||this._status===ye.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=e):this._status===ye.STATUS_1XX_RECEIVED&&this._request.cancel(e),this._status=ye.STATUS_CANCELED,this._failed("local",null,U.causes.CANCELED);break;case ye.STATUS_WAITING_FOR_ANSWER:case ye.STATUS_ANSWERED:if(d=d||480,d<300||d>=700)throw new TypeError(`Invalid status_code: ${d}`);this._request.reply(d,_,i,a),this._failed("local",null,U.causes.REJECTED);break;case ye.STATUS_WAITING_FOR_ACK:case ye.STATUS_CONFIRMED:if(_=n.reason_phrase||U.REASON_PHRASE[d]||"",d&&(d<200||d>=700))throw new TypeError(`Invalid status_code: ${d}`);if(d&&i.push(`Reason: SIP ;cause=${d}; text="${_}"`),this._status===ye.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==jt.C.STATUS_TERMINATED){const u=this._dialog;this.receiveRequest=({method:g})=>{g===U.ACK&&(this.sendRequest(U.BYE,{extraHeaders:i,body:a}),u.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===jt.C.STATUS_TERMINATED&&(this.sendRequest(U.BYE,{extraHeaders:i,body:a}),u.terminate())}),this._ended("local",null,s),this._dialog=u,this._ua.newDialog(u)}else this.sendRequest(U.BYE,{extraHeaders:i,body:a}),this._ended("local",null,s)}}sendRequest(n,s){return this._dialog.sendRequest(n,s)}authenticate(n){this.status="auth";let s=new Gs("");s.method="AUTH",s.addHeader("To-Path",`msrp://${this._ua._configuration.realm}:2856;ws`),s.addHeader("From-Path",`msrp://${this.credentials.username}.${this.credentials.realm}:2856/${this.auth_id};ws`),n&&s.addHeader("Authorization",n.toString());let i=s.toString(),a=[];for(var e=0;e<i.length;e++)a.push(i.charCodeAt(e).toString(16));this._connection.send(s.toString())}onmessage(n){const s=new Gs(n.data);if(this.status==="auth"&&s.code===401){const i=this.parseAuth(s.getHeader("WWW-Authenticate")),a=new yg(this.credentials);a.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},i,ke.createRandomToken(12)),this.authenticate(a)}this.status==="auth"&&s.code===200&&this._direction==="outgoing"?(this.my_addr.push(s.getHeader("To-Path")),this.my_addr.push(s.getHeader("Use-Path")),this.status="active",this.inviteParty(s)):this.status==="auth"&&s.code===200&&this._direction==="incoming"?(this.my_addr.push(s.getHeader("To-Path")),this.my_addr.push(s.getHeader("Use-Path")),this.status="active",this.acceptParty(s),this.emit("confirmed")):s.method==="SEND"&&(this._sendOk(s),this._sendReport(s),s.direction="incoming",this.emit("newMessage",s),this._msgHistory.push(s),this.emit("msgHistoryUpdate",this._msgHistory)),s.code===480&&this._close()}onclose(){console.log("close")}onopen(){const n=new RTCPeerConnection({iceServers:[]});n.createDataChannel(""),n.createOffer().then(n.setLocalDescription.bind(n)),n.onicecandidate=s=>{if(!s||!s.candidate||!s.candidate.candidate)return;const i=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,a=s.candidate.candidate.match(i);this.my_ip=a&&a[1],n.onicecandidate=()=>{},this.authenticate(null)}}onerror(n){console.log(n)}_receiveInviteResponse(n){if(console.log("resp0000000000000",n),this._dialog&&n.status_code>=200&&n.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===n.call_id&&this._dialog.id.local_tag===n.from_tag&&this._dialog.id.remote_tag===n.to_tag){this.sendRequest(U.ACK);return}else{const s=new _l(this,n,"UAC");if(s.error!==void 0){console.log(s.error);return}this.sendRequest(U.ACK),this.sendRequest(U.BYE);return}if(this._is_canceled){n.status_code>=100&&n.status_code<200?this._request.cancel(this._cancel_reason):n.status_code>=200&&n.status_code<299&&this._acceptAndTerminate(n);return}if(!(this._status!==ye.STATUS_INVITE_SENT&&this._status!==ye.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(n.status_code):this._status=ye.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(n.status_code):{if(!n.to_tag){console.log("1xx response received without to tag");break}if(n.hasHeader("contact")&&!this._createDialog(n,"UAC",!0))break;if(this._status=ye.STATUS_1XX_RECEIVED,!n.body){this._progress("remote",n);break}const s={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",s);const i=new RTCSessionDescription({type:"answer",sdp:s.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(i)).then(()=>this._progress("remote",n)).catch(a=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)});break}case/^2[0-9]{2}$/.test(n.status_code):{if(console.log("maybe here???"),this._status=ye.STATUS_CONFIRMED,!n.body){this._acceptAndTerminate(n,400,U.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",n,U.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(n,"UAC"))break;const s={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",s),new RTCSessionDescription({type:"answer",sdp:s.sdp}),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(i=>this._connection.setLocalDescription(i)).catch(i=>{this._acceptAndTerminate(n,500,i.toString()),console.log("failed 4"),this._failed("local",n,U.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(n),this._accepted("remote",n),this.sendRequest(U.ACK),this._confirmed("local",null)});break}default:{const s=ke.sipErrorCause(n.status_code);console.log("failed 5"),this._failed("remote",n,s)}}}sendMSRP(n){const s=new Gs("");s.method="SEND",s.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),s.addHeader("From-Path",`${this.my_addr[0]}`),s.addHeader("Message-ID",ke.createRandomToken(10)),s.addHeader("Byte-Range","1-25/25"),s.addHeader("Content-Type","text/plain"),s.addHeader("Success-Report","yes"),s.addHeader("Failure-Report","yes"),s.body=n;let i=s.toString();console.log(i);let a=[];for(var e=0;e<i.length;e++)a.push(i.charCodeAt(e).toString(16));console.log(a),this._connection.send(s.toString()),s.direction="outgoing",this.emit("newMessage",s),this._msgHistory.push(s),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(n){let s=n.ident,i=n.getHeader("Message-ID"),a=new Gs("");a.method="200 OK",a.addHeader("To-Path",`${this.my_addr[1]}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",i),a.ident=s;let e=a.toString();console.log(e);let d=[];for(var _=0;_<e.length;_++)d.push(e.charCodeAt(_).toString(16));console.log(d),this._connection.send(a.toString())}_sendReport(n){let s=n.ident,i=n.getHeader("Message-ID"),a=new Gs("");a.method="REPORT",a.addHeader("To-Path",`${n.getHeader("From-Path")}`),a.addHeader("From-Path",`${this.my_addr[0]}`),a.addHeader("Message-ID",i),a.addHeader("Byte-Range","1-25/25"),a.addHeader("Status","000 200 OK"),a.ident=s;let e=a.toString();console.log(e);let d=[];for(var _=0;_<e.length;_++)d.push(e.charCodeAt(_).toString(16));console.log(d),this._connection.send(a.toString())}parseAuth(n){const s={},i=n.replace("Digest","").split(",");for(const a of i){const e=a.trim().split("=");s[e[0]]=e[1].match('^"(.+)"$')[1]}return s}init_incoming(n,s){let i;const a=n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0;if(n.body&&a!=="application/sdp"){n.reply(415);return}if(this._status=ye.STATUS_INVITE_RECEIVED,this._from_tag=n.from_tag,this._id=n.call_id+this._from_tag,this._request=n,this._contact=this._ua.contact.toString(),n.hasHeader("expires")&&(i=n.getHeader("expires")*1e3),n.to_tag=ke.newTag(),!this._createDialog(n,"UAS",!0)){n.reply(500,"Missing Contact header field");return}n.body?this._late_sdp=!1:this._late_sdp=!0,this._status=ye.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{n.reply(408),console.log("failed 6"),this._failed("local",null,U.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),i&&(this._timers.expiresTimer=setTimeout(()=>{this._status===ye.STATUS_WAITING_FOR_ANSWER&&(n.reply(487),console.log("failed 7"),this._failed("system",null,U.causes.EXPIRES))},i)),this._direction="incoming",this._local_identity=n.to,this._remote_identity=n.from,s&&s(this),n.parseSDP(!0),this.target_addr=n.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",n),this._status!==ye.STATUS_TERMINATED&&(n.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(n,s,i){this.emit("_failed",{originator:n,message:s||null,cause:i}),this._close(),this.emit("failed",{originator:n,message:s||null,cause:i})}_close(){if(console.log("CLOSE SESSION"),this._status!==ye.STATUS_TERMINATED){if(this._status=ye.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(n){console.log("close() | error closing the RTCPeerConnection: %o",n)}for(const n in this._timers)Object.prototype.hasOwnProperty.call(this._timers,n)&&clearTimeout(this._timers[n]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const n in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,n)&&(this._earlyDialogs[n].terminate(),delete this._earlyDialogs[n]);for(const n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyMSRPSession(this)}}_createDialog(n,s,i){const a=s==="UAS"?n.to_tag:n.from_tag,e=s==="UAS"?n.from_tag:n.to_tag,d=n.call_id+a+e;let _=this._earlyDialogs[d];if(i)return _?!0:(_=new _l(this,n,s,_l.C.STATUS_EARLY),_.error?(console.log("failed 8"),this._failed("remote",n,U.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[d]=_,!0));{if(this._from_tag=n.from_tag,this._to_tag=n.to_tag,_)return _.update(n,s),this._dialog=_,delete this._earlyDialogs[d],!0;const u=new _l(this,n,s);return u.error?(console.log("failed 9"),this._failed("remote",n,U.causes.INTERNAL_ERROR),!1):(this._dialog=u,!0)}}_newMSRPSession(n,s){this._ua.newMSRPSession(this,{originator:n,session:this,request:s})}_progress(n,s){this.emit("progress",{originator:n,response:s||null})}isEnded(){switch(this._status){case ye.STATUS_CANCELED:case ye.STATUS_TERMINATED:return!0;default:return!1}}_accepted(n,s){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:n,response:s||null})}_confirmed(n,s){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:n,ack:s||null})}_ended(n,s,i){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:n,message:s||null,cause:i})}_handleSessionTimersInIncomingResponse(n){if(!this._sessionTimers.enabled)return;let s;n.session_expires&&n.session_expires>=U.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=n.session_expires,s=n.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,s="uac"),this._sessionTimers.refresher=s==="uac",this._runSessionTimer()}receiveRequest(n){if(console.log("receiveRequest()"),n.method===U.CANCEL)(this._status===ye.STATUS_WAITING_FOR_ANSWER||this._status===ye.STATUS_ANSWERED)&&(this._status=ye.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",n,U.causes.CANCELED));else switch(n.method){case U.ACK:if(this._status!==ye.STATUS_WAITING_FOR_ACK)return;if(this._status=ye.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!n.body){this.terminate({cause:U.causes.MISSING_SDP,status_code:400});break}const s={originator:"remote",type:"answer",sdp:n.body};console.log('emit "sdp"'),this.emit("sdp",s);const i=new RTCSessionDescription({type:"answer",sdp:s.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(i)).then(()=>{this._is_confirmed||this._confirmed("remote",n)}).catch(a=>{this.terminate({cause:U.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',a),this.emit("peerconnection:setremotedescriptionfailed",a)})}else this._is_confirmed||this._confirmed("remote",n);break;case U.BYE:this._status===ye.STATUS_CONFIRMED||this._status===ye.STATUS_WAITING_FOR_ACK?(n.reply(200),this._ended("remote",n,U.causes.BYE)):this._status===ye.STATUS_INVITE_RECEIVED||this._status===ye.STATUS_WAITING_FOR_ANSWER?(n.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",n,U.causes.BYE)):n.reply(403,"Wrong Status");break;case U.INVITE:this._status===ye.STATUS_CONFIRMED?n.hasHeader("replaces")?this._receiveReplaces(n):this._receiveReinvite(n):n.reply(403,"Wrong Status");break;case U.INFO:this._status===ye.STATUS_1XX_RECEIVED||this._status===ye.STATUS_WAITING_FOR_ANSWER||this._status===ye.STATUS_ANSWERED||this._status===ye.STATUS_WAITING_FOR_ACK||this._status===ye.STATUS_CONFIRMED?(n.hasHeader("Content-Type")?n.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new Ha(this).init_incoming(n):n.reply(415):n.reply(403,"Wrong Status");break;case U.UPDATE:this._status===ye.STATUS_CONFIRMED?this._receiveUpdate(n):n.reply(403,"Wrong Status");break;case U.REFER:this._status===ye.STATUS_CONFIRMED?this._receiveRefer(n):n.reply(403,"Wrong Status");break;case U.NOTIFY:this._status===ye.STATUS_CONFIRMED?this._receiveNotify(n):n.reply(403,"Wrong Status");break;default:n.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==ye.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:U.causes.CONNECTION_ERROR,cause:U.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==ye.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:U.causes.REQUEST_TIMEOUT,cause:U.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==ye.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:U.causes.DIALOG_ERROR,cause:U.causes.DIALOG_ERROR})}}var uv=Bt();const su=We(uv),bl=new ll("Parser"),cv=(l,n)=>{let s,i,a=l.indexOf(`\r
157
157
  `);if(a===-1){bl.warn("parseMessage() | no CRLF found, not a SIP message");return}const e=l.substring(0,a);let d=su.parse(e,"Request_Response");if(d===-1){bl.warn(`parseMessage() | error parsing first line of SIP message: "${e}"`);return}else d.status_code?(s=new $s.IncomingResponse,s.status_code=d.status_code,s.reason_phrase=d.reason_phrase):(s=new $s.IncomingRequest(n),s.method=d.method,s.ruri=d.uri);s.data=l;let _=a+2;for(;;){if(a=hv(l,_),a===-2){i=_+2;break}else if(a===-1){bl.warn("parseMessage() | malformed message");return}if(d=dv(s,l,_,a),d!==!0){bl.warn("parseMessage() |",d.error);return}_=a+2}if(s.hasHeader("content-length")){const u=s.getHeader("content-length");s.body=l.substr(i,u)}else s.body=l.substring(i);return s};function hv(l,n){let s=n,i=0,a=0;if(l.substring(s,s+2).match(/(^\r\n)/))return-2;for(;i===0;){if(a=l.indexOf(`\r
158
- `,s),a===-1)return a;!l.substring(a+2,a+4).match(/(^\r\n)/)&&l.charAt(a+2).match(/(^\s+)/)?s=a+2:i=a}return i}function dv(l,n,s,i){let a;const e=n.indexOf(":",s),d=n.substring(s,e).trim(),_=n.substring(e+1,i).trim();switch(d.toLowerCase()){case"via":case"v":l.addHeader("via",_),l.getHeaders("via").length===1?(a=l.parseHeader("Via"),a&&(l.via=a,l.via_branch=a.branch)):a=0;break;case"from":case"f":l.setHeader("from",_),a=l.parseHeader("from"),a&&(l.from=a,l.from_tag=a.getParam("tag"));break;case"to":case"t":l.setHeader("to",_),a=l.parseHeader("to"),a&&(l.to=a,l.to_tag=a.getParam("tag"));break;case"record-route":if(a=su.parse(_,"Record_Route"),a===-1)a=void 0;else for(const u of a)l.addHeader("record-route",_.substring(u.possition,u.offset)),l.headers["Record-Route"][l.getHeaders("record-route").length-1].parsed=u.parsed;break;case"call-id":case"i":l.setHeader("call-id",_),a=l.parseHeader("call-id"),a&&(l.call_id=_);break;case"contact":case"m":if(a=su.parse(_,"Contact"),a===-1)a=void 0;else for(const u of a)l.addHeader("contact",_.substring(u.possition,u.offset)),l.headers.Contact[l.getHeaders("contact").length-1].parsed=u.parsed;break;case"content-length":case"l":l.setHeader("content-length",_),a=l.parseHeader("content-length");break;case"content-type":case"c":l.setHeader("content-type",_),a=l.parseHeader("content-type");break;case"cseq":l.setHeader("cseq",_),a=l.parseHeader("cseq"),a&&(l.cseq=a.value),l instanceof $s.IncomingResponse&&(l.method=a.method);break;case"max-forwards":l.setHeader("max-forwards",_),a=l.parseHeader("max-forwards");break;case"www-authenticate":l.setHeader("www-authenticate",_),a=l.parseHeader("www-authenticate");break;case"proxy-authenticate":l.setHeader("proxy-authenticate",_),a=l.parseHeader("proxy-authenticate");break;case"session-expires":case"x":l.setHeader("session-expires",_),a=l.parseHeader("session-expires"),a&&(l.session_expires=a.expires,l.session_expires_refresher=a.refresher);break;case"refer-to":case"r":l.setHeader("refer-to",_),a=l.parseHeader("refer-to"),a&&(l.refer_to=a);break;case"replaces":l.setHeader("replaces",_),a=l.parseHeader("replaces"),a&&(l.replaces=a);break;case"event":case"o":l.setHeader("event",_),a=l.parseHeader("event"),a&&(l.event=a);break;default:l.addHeader(d,_),a=0}return a===void 0?{error:`error parsing header "${d}"`}:!0}const _v={parseMessage:cv},Nr=new ll("Registrator"),Rl=10;class pv{constructor(n,s){this._reg_id=1,this._ua=n,this._transport=s,this._registrar=n.configuration.registrar_server,this._expires=n.configuration.register_expires,this._call_id=En.createRandomToken(22),this._cseq=0,this._to_uri=n.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const i=this._contact.indexOf(">");if(i!==-1){const a=this._contact.slice(0,i)+this._contact.slice(i+1,this._contact.length);this._contact=a}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(n){Array.isArray(n)||(n=[]),this._extraHeaders=n.slice()}setExtraContactParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const s in n)if(Object.prototype.hasOwnProperty.call(n,s)){const i=n[s];this._extraContactParams+=`;${s}`,i&&(this._extraContactParams+=`=${i}`)}}setExtraContactUriParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const s in n)if(Object.prototype.hasOwnProperty.call(n,s)){const i=n[s];this._extraContactParams+=`;${s}`,i&&(this._extraContactParams+=`=${i}`)}}register(){if(this._registering){Nr.debug("Register request in progress...");return}const n=this._extraHeaders.slice();n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),n.push(`Expires: ${this._expires}`);const s=new gt.OutgoingRequest(U.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n),i=new yr(this._ua,s,{onRequestTimeout:()=>{this._registrationFailure(null,U.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,U.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{if(a.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):{if(this._registering=!1,!a.hasHeader("Contact")){Nr.debug("no Contact header in response to REGISTER, response ignored");break}const e=a.headers.Contact.reduce((g,f)=>g.concat(f.parsed),[]);let d=e.find(g=>this._sipInstance===g.getParam("+sip.instance")&&this._reg_id===parseInt(g.getParam("reg-id")));if(d||(d=e.find(g=>g.uri.user===this._ua.contact.uri.user)),!d){Nr.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let _=d.getParam("expires");!_&&a.hasHeader("expires")&&(_=a.getHeader("expires")),_||(_=this._expires),_=Number(_),_<Rl&&(_=Rl);const u=_>64?_*1e3/2+Math.floor((_/2-32)*1e3*Math.random()):_*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},u),d.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=d.getParam("temp-gruu").replace(/"/g,"")),d.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=d.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:a}));break}case/^423$/.test(a.status_code):{a.hasHeader("min-expires")?(this._expires=Number(a.getHeader("min-expires")),this._expires<Rl&&(this._expires=Rl),this.register()):(Nr.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,U.causes.SIP_FAILURE_CODE));break}default:{const e=En.sipErrorCause(a.status_code);this._registrationFailure(a,e)}}}});this._registering=!0,i.send()}unregister(n={}){if(!this._registered){Nr.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const s=this._extraHeaders.slice();n.all?s.push(`Contact: *${this._extraContactParams}`):s.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),s.push("Expires: 0");const i=new gt.OutgoingRequest(U.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},s);new yr(this._ua,i,{onRequestTimeout:()=>{this._unregistered(null,U.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,U.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{switch(!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):this._unregistered(a);break;default:{const e=En.sipErrorCause(a.status_code);this._unregistered(a,e)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(n,s){this._registering=!1,this._ua.registrationFailed({response:n||null,cause:s}),this._registered&&(this._registered=!1,this._ua.unregistered({response:n||null,cause:s}))}_unregistered(n,s){this._registering=!1,this._registered=!1,this._ua.unregistered({response:n||null,cause:s||null})}}const et=console,zn={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},fv=tv;class mv extends fv{constructor(n){super(n),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this.optionsInterval=null,this.lastOptionsTimestamp=null,this.lastRegisterTimestamp=null,this._registrator=new pv(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(n,s){return super.call(n,s)}joinVideoCall(n,s,i){et.debug("call()");const a=new Cl(this);return a.configureMedia({audio:!0,video:!0}),a.connect(n,s,i),a}startScreenShare(){et.debug("startScreenShare()");for(const n in this._janus_sessions)this._janus_sessions[n].connectScreenShare()}changeMediaConstraints(n){for(const s in this._janus_sessions)this._janus_sessions[s].changeMediaConstraints(n)}startBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].connectBlur()}stopBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].stopBlur()}_loadConfig(n){try{Or.load(this._configuration,n)}catch(e){throw e}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=En.newUUID());let s;typeof window<"u"&&typeof window.document<"u"?s=window?.navigator.userAgent:typeof self<"u"&&self.navigator&&(s=self.navigator.userAgent),s+=" "+Ie.USER_AGENT,this._configuration.user_agent=n.overrideUserAgent&&typeof n.overrideUserAgent=="function"?n.overrideUserAgent(s):s,n.onTransportCallback&&typeof n.onTransportCallback=="function"&&(this.onTransportCallback=n.onTransportCallback),this._configuration.jssip_id=En.createRandomToken(5);const i=this._configuration.uri.clone();i.user=null,this._configuration.hostport_params=i.toString().replace(/^sip:/i,"");try{this._transport=new IT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=gv.bind(this),this._transport.onconnect=Tv.bind(this),this._transport.ondisconnect=vv.bind(this),this._transport.ondata=yv.bind(this)}catch(e){throw et.warn(e),new Kn.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const e=this._configuration.uri.clone();e.user=null,e.clearParams(),e.clearHeaders(),this._configuration.registrar_server=e}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ls("sip",En.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(e={}){const d=e.anonymous||null,_=e.outbound||null;let u="<";return d?u+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":u+=this.pub_gruu||this.uri.toString(),_&&(d?!this.temp_gruu:!this.pub_gruu)&&(u+=";ob"),u+=">",u}};const a=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const e in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,e)&&(a.indexOf(e)!==-1?Object.defineProperty(this._configuration,e,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,e,{writable:!1,configurable:!1}));et.debug("configuration parameters after validation:");for(const e in this._configuration)if(Object.prototype.hasOwnProperty.call(Or.settings,e))switch(e){case"uri":case"registrar_server":et.debug(`- ${e}: ${this._configuration[e]}`);break;case"password":case"ha1":case"authorization_jwt":et.debug(`- ${e}: NOT SHOWN`);break;default:et.debug(`- ${e}: ${JSON.stringify(this._configuration[e])}`)}}newMSRPSession(n,s){n.on("msgHistoryUpdate",i=>{console.log(i)}),this._msrp_sessions[n.id]=n,this.emit("newMSRPSession",s)}newJanusSession(n,s){this._janus_sessions[n.id]=n,this.newStreamPlugins.forEach(i=>{i.setSession(n)}),this.processStreamPlugins.forEach(i=>{i.setSession(n)}),this.emit("newJanusSession",s)}kill(){}destroyMSRPSession(n){delete this._msrp_sessions[n.id]}destroyJanusSession(n){delete this._janus_sessions[n.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(n){var s,i,a,e;const d=n.method;if(n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){et.debug("Request-URI does not point to us"),n.method!==Ie.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===Ie.SIPS){n.reply_sl(416);return}if(jt.checkTransaction(this,n))return;if(d===Ie.INVITE?new jt.InviteServerTransaction(this,this._transport,n):d!==Ie.ACK&&d!==Ie.CANCEL&&new jt.NonInviteServerTransaction(this,this._transport,n),d===Ie.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const g=Date.now(),f=this.lastOptionsTimestamp>g-35e3,T=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>g;f&&T&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){n.reply(200);return}new Ph.Options(this).init_incoming(n)}else if(d===Ie.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new Ph.Message(this).init_incoming(n)}else if(d===Ie.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let _,u;if(n.to_tag)if(_=this._findDialog(n.call_id,n.from_tag,n.to_tag),_)_.receiveRequest(n);else if(d===Ie.NOTIFY)if(u=this._findSession(n),u)u.receiveRequest(n);else{if(n.body)try{const g=JSON.parse(n.body)||{};(i=(s=g.plugindata)==null?void 0:s.data)!=null&&i.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(g),(e=(a=g.plugindata)==null?void 0:a.data)!=null&&e.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(g.plugindata.data.unpublished)}catch(g){console.error(g)}n.reply(200)}else d!==Ie.ACK&&n.reply(481);else switch(d){case Ie.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const g=n.replaces;_=this._findDialog(g.call_id,g.from_tag,g.to_tag),_?(u=_.owner,u.isEnded()?n.reply(603):u.receiveRequest(n)):n.reply(481)}else n.body.search(/MSRP/ig)>-1?(u=new nu(this),u.init_incoming(n)):n.body.search(/JANUS/ig)>-1||(u=new hT(this),u.init_incoming(n));else et.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case Ie.BYE:n.reply(481);break;case Ie.CANCEL:u=this._findSession(n),u?u.receiveRequest(n):et.debug("received CANCEL request for a non existent session");break;case Ie.ACK:break;case Ie.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}startMSRP(n,s){et.debug("startMSRP()",s);const i=new nu(this);return i.connect(n),i}startJanus(n,s){et.debug("startJanus()",s);const i=new nu(this);return i.connect(n),i}terminateMSRPSessions(n){et.debug("terminateSessions()");for(const s in this._msrp_sessions)this._msrp_sessions[s].isEnded()||this._msrp_sessions[s].terminate(n)}terminateJanusSessions(n){et.debug("terminateSessions()");for(const s in this._janus_sessions)this._janus_sessions[s].isEnded()||this._janus_sessions[s].terminate(n)}enableJanusAudio(n){et.debug("enableJanusAudio()");for(const s in this._janus_sessions)this._janus_sessions[s].isEnded()||(n?this._janus_sessions[s].startAudio():this._janus_sessions[s].stopAudio())}enableJanusVideo(n){et.debug("enableJanusVideo()");for(const s in this._janus_sessions)this._janus_sessions[s].isEnded()||(n?this._janus_sessions[s].startVideo():this._janus_sessions[s].stopVideo())}terminateAllSessions(){for(const n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){et.debug(`closing session ${n}`);try{this._sessions[n].terminate()}catch(s){console.error(s)}}}stop(n=!0){if(et.debug("stop()"),this._dynConfiguration={},this._status===zn.STATUS_USER_CLOSED){et.debug("UA already closed");return}this._registrator.close();const s=Object.keys(this._sessions).length;n&&this.terminateAllSessions();for(const i in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,i)){et.debug(`closing session ${i}`);try{this._msrp_sessions[i].terminate()}catch(a){console.error(a)}}for(const i in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,i)){et.debug(`closing session ${i}`);try{this._janus_sessions[i].terminate()}catch(a){console.error(a)}}for(const i in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,i))try{this._applicants[i].close()}catch(a){console.error(a)}this._status=zn.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&s===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function gv(l){this.emit("connecting",l)}function Tv(l){this._status!==zn.STATUS_USER_CLOSED&&(this._status=zn.STATUS_READY,this._error=null,this.emit("connected",l),this._dynConfiguration.register&&this._registrator.register())}function vv(l){const n=["nict","ict","nist","ist"];for(const s of n)for(const i in this._transactions[s])Object.prototype.hasOwnProperty.call(this._transactions[s],i)&&this._transactions[s][i].onTransportError();this.emit("disconnected",l),this._registrator.onTransportClosed(),this._status!==zn.STATUS_USER_CLOSED&&(this._status=zn.STATUS_NOT_READY,this._error=zn.NETWORK_ERROR)}function yv(l){const n=l.transport;let s=l.message;const i=s;if(s=_v.parseMessage(s,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(s,i),!!s&&!(this._status===zn.STATUS_USER_CLOSED&&s instanceof $s.IncomingRequest)&&$T(s,this,n)){if(s instanceof $s.IncomingRequest)s.transport=n,this.receiveRequest(s);else if(s instanceof $s.IncomingResponse){let a;switch(s.method){case Ie.INVITE:a=this._transactions.ict[s.via_branch],a&&a.receiveResponse(s);break;case Ie.ACK:break;default:a=this._transactions.nict[s.via_branch],a&&a.receiveResponse(s);break}}}}const Ev=["roomId","_audioMuted","_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","_localHold","_videoMuted","status","start_time","_remote_identity","audioTag","isOnHold","localMuted","autoAnswer","putOnHoldTimestamp"],Sv=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function Dd(l){const n={};return Ev.forEach(s=>{l[s]!==void 0&&(n[s]=l[s])}),n.localHold=l._localHold,n}function kd(l){const n={};return Sv.forEach(s=>{l[s]!==void 0&&(n[s]=l[s])}),n}async function ru(l,n,s){const i=l.createMediaStreamSource(n),a=l.createMediaStreamDestination(),e=l.createGain();return i.connect(e),e.connect(a),e.gain.value=s,a.stream}function Av(l,n,s,i){if(Ud())return;const a=document.createElement("audio");a.id=n._id,a.className="audioTag",a.srcObject=l,a.setSinkId(s),a.volume=i,a.play(),n.audioTag=a}function Cv(l){if(l&&typeof l.log=="function"&&typeof l.warn=="function"&&typeof l.error=="function")return!0}function Ud(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const bv=ot,Rv=Bt(),It=new bv("WebSocketInterface");var Iv=class{constructor(l){It.debug('new() [url:"%s"]',l),this._url=l,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=Rv.parse(l,"absoluteURI");if(n===-1)throw It.warn(`invalid WebSocket URI: ${l}`),new TypeError(`Invalid argument: ${l}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw It.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${l}`);this._sip_uri=`sip:${n.host}${n.port?`:${n.port}`:""};transport=ws`,this._via_transport=n.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(l){this._via_transport=l.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(It.debug("connect()"),this.isConnected()){It.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){It.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),It.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(l){this._onError(l)}}disconnect(){It.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(l){return It.debug("send()"),this.isConnected()?(this._ws.send(l),!0):(It.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){It.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:l,code:n,reason:s}){It.debug(`WebSocket ${this._url} closed`),l===!1&&It.debug("WebSocket abrupt disconnection"),this.ondisconnect(!l,n,s)}_onMessage({data:l}){It.debug("received WebSocket message"),this.ondata(l)}_onError(l){It.warn(`WebSocket ${this._url} error: `,l)}};const iu=So,wv=Ie,Ov=yn,Nv=ft(),Dv=wd,kv=gn(),Uv=ba(),Mv=Bt(),Pv=Iv;xs("JsSIP")("version %s",iu.version);var xv={C:wv,Exceptions:Ov,Utils:Nv,UA:Dv,URI:kv,NameAddrHeader:Uv,WebSocketInterface:Pv,Grammar:Mv,debug:xs,get name(){return iu.title},get version(){return iu.version}};const Lv=We(xv);function ou(l){return l<10?`0${l}`:`${l}`}function Hv(l){let n=l.hours||0,s=l.minutes||0,i=l.seconds||0;i++,i===60&&(i=0,s++,s===60&&(s=0,n++));const a=`${ou(n)}:${ou(s)}:${ou(i)}`;return{seconds:i,minutes:s,hours:n,formatted:a}}function qv(l){let n=0;for(let s=0;s<l.length;s++)n+=l[s]*l[s];return Math.sqrt(n/l.length)}async function Fv(l,n,s=150){const i=n.createMediaStreamSource(l),a=n.createDelay();a.delayTime.value=s/1e3;const e=n.createGain();e.gain.value=0;const d=n.createMediaStreamDestination();return i.connect(a).connect(e).connect(d),{stream:d.stream,setSpeaking:_=>{e.gain.value=_?1:0}}}var Et={};Et.forEach=async(l,n,s)=>{const i=[];for(let a=0;a<l.length;a++)if(a in l){const e=Promise.resolve(l[a]).then(d=>n.call(s||globalThis,d,a,l));i.push(e)}await Promise.all(i)},Et.forEachSeries=async(l,n,s)=>{for(let i=0;i<l.length;i++)i in l&&await n.call(s||globalThis,await l[i],i,l)},Et.map=async(l,n,s)=>{const i=[];for(let a=0;a<l.length;a++)a in l&&(i[a]=Promise.resolve(l[a]).then(e=>n.call(s||globalThis,e,a,l)));return Promise.all(i)},Et.mapSeries=async(l,n,s)=>{const i=[];for(let a=0;a<l.length;a++)a in l&&(i[a]=await n.call(s||globalThis,await l[a],a,l));return i},Et.find=(l,n,s)=>new Promise((i,a)=>{if(l.length===0)return i();let e=1;for(let d=0;d<l.length;d++){const _=u=>{u?i(l[d]):e===l.length&&i(),e++};Promise.resolve(l[d]).then(u=>n.call(s||globalThis,u,d,l)).then(_).catch(a)}}),Et.findSeries=async(l,n,s)=>{for(let i=0;i<l.length;i++)if(await n.call(s||globalThis,await l[i],i,l))return l[i]},Et.findIndex=(l,n,s)=>new Promise((i,a)=>{if(l.length===0)return i(-1);let e=1;for(let d=0;d<l.length;d++){const _=u=>{u?i(d):e===l.length&&i(-1),e++};Promise.resolve(l[d]).then(u=>n.call(s||globalThis,u,d,l)).then(_).catch(a)}}),Et.findIndexSeries=async(l,n,s)=>{for(let i=0;i<l.length;i++)if(await n.call(s||globalThis,await l[i],i,l))return i},Et.some=(l,n,s)=>new Promise((i,a)=>{if(l.length===0)return i(!1);let e=1;for(let d=0;d<l.length;d++){if(!(d in l)){e++;continue}const _=u=>{u?i(!0):e===l.length&&i(!1),e++};Promise.resolve(l[d]).then(u=>n.call(s||globalThis,u,d,l)).then(_).catch(a)}}),Et.someSeries=async(l,n,s)=>{for(let i=0;i<l.length;i++)if(i in l&&await n.call(s||globalThis,await l[i],i,l))return!0;return!1},Et.every=(l,n,s)=>new Promise((i,a)=>{if(l.length===0)return i(!0);let e=1;for(let d=0;d<l.length;d++){if(!(d in l)){e++;continue}const _=u=>{u?e===l.length&&i(!0):i(!1),e++};Promise.resolve(l[d]).then(u=>n.call(s||globalThis,u,d,l)).then(_).catch(a)}}),Et.everySeries=async(l,n,s)=>{for(let i=0;i<l.length;i++)if(i in l&&!await n.call(s||globalThis,await l[i],i,l))return!1;return!0},Et.filter=(l,n,s)=>new Promise(async(i,a)=>{const e=[];for(let _=0;_<l.length;_++)_ in l&&(e[_]=Promise.resolve(l[_]).then(u=>n.call(s||globalThis,u,_,l)).catch(a));const d=[];for(let _=0;_<e.length;_++)await e[_]&&d.push(await l[_]);i(d)}),Et.filterSeries=async(l,n,s)=>{const i=[];for(let a=0;a<l.length;a++)a in l&&await n.call(s||globalThis,await l[a],a,l)&&i.push(await l[a]);return i},Et.reduce=async(l,n,s)=>{if(l.length===0&&s===void 0)throw TypeError("Reduce of empty array with no initial value");let i,a;for(s!==void 0?(a=s,i=0):(a=l[0],i=1),i;i<l.length;i++)i in l&&(a=await n(await a,await l[i],i,l));return a};var Md={};(function(l){const n=Et;Object.keys(n).forEach(s=>{const i=s.charAt(0).toUpperCase()+s.slice(1);l[`async${i}`]=async function(...a){return n[s](this,...a)}})})(Md);var jv=Object.assign(Et,{instanceMethods:Md});const Wt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var $v={exports:{}};(function(l){var n=function(s){var i=Object.prototype,a=i.hasOwnProperty,e=Object.defineProperty||function(Q,V,k){Q[V]=k.value},d,_=typeof Symbol=="function"?Symbol:{},u=_.iterator||"@@iterator",g=_.asyncIterator||"@@asyncIterator",f=_.toStringTag||"@@toStringTag";function T(Q,V,k){return Object.defineProperty(Q,V,{value:k,enumerable:!0,configurable:!0,writable:!0}),Q[V]}try{T({},"")}catch{T=function(Q,V,k){return Q[V]=k}}function y(Q,V,k,ve){var _e=V&&V.prototype instanceof me?V:me,Ae=Object.create(_e.prototype),Ue=new X(ve||[]);return e(Ae,"_invoke",{value:P(Q,k,Ue)}),Ae}s.wrap=y;function A(Q,V,k){try{return{type:"normal",arg:Q.call(V,k)}}catch(ve){return{type:"throw",arg:ve}}}var w="suspendedStart",b="suspendedYield",R="executing",G="completed",x={};function me(){}function O(){}function $(){}var de={};T(de,u,function(){return this});var fe=Object.getPrototypeOf,N=fe&&fe(fe(te([])));N&&N!==i&&a.call(N,u)&&(de=N);var H=$.prototype=me.prototype=Object.create(de);O.prototype=$,e(H,"constructor",{value:$,configurable:!0}),e($,"constructor",{value:O,configurable:!0}),O.displayName=T($,f,"GeneratorFunction");function j(Q){["next","throw","return"].forEach(function(V){T(Q,V,function(k){return this._invoke(V,k)})})}s.isGeneratorFunction=function(Q){var V=typeof Q=="function"&&Q.constructor;return V?V===O||(V.displayName||V.name)==="GeneratorFunction":!1},s.mark=function(Q){return Object.setPrototypeOf?Object.setPrototypeOf(Q,$):(Q.__proto__=$,T(Q,f,"GeneratorFunction")),Q.prototype=Object.create(H),Q},s.awrap=function(Q){return{__await:Q}};function F(Q,V){function k(Ae,Ue,ce,re){var Ge=A(Q[Ae],Q,Ue);if(Ge.type==="throw")re(Ge.arg);else{var tt=Ge.arg,ge=tt.value;return ge&&typeof ge=="object"&&a.call(ge,"__await")?V.resolve(ge.__await).then(function(pe){k("next",pe,ce,re)},function(pe){k("throw",pe,ce,re)}):V.resolve(ge).then(function(pe){tt.value=pe,ce(tt)},function(pe){return k("throw",pe,ce,re)})}}var ve;function _e(Ae,Ue){function ce(){return new V(function(re,Ge){k(Ae,Ue,re,Ge)})}return ve=ve?ve.then(ce,ce):ce()}e(this,"_invoke",{value:_e})}j(F.prototype),T(F.prototype,g,function(){return this}),s.AsyncIterator=F,s.async=function(Q,V,k,ve,_e){_e===void 0&&(_e=Promise);var Ae=new F(y(Q,V,k,ve),_e);return s.isGeneratorFunction(V)?Ae:Ae.next().then(function(Ue){return Ue.done?Ue.value:Ae.next()})};function P(Q,V,k){var ve=w;return function(_e,Ae){if(ve===R)throw new Error("Generator is already running");if(ve===G){if(_e==="throw")throw Ae;return Ke()}for(k.method=_e,k.arg=Ae;;){var Ue=k.delegate;if(Ue){var ce=W(Ue,k);if(ce){if(ce===x)continue;return ce}}if(k.method==="next")k.sent=k._sent=k.arg;else if(k.method==="throw"){if(ve===w)throw ve=G,k.arg;k.dispatchException(k.arg)}else k.method==="return"&&k.abrupt("return",k.arg);ve=R;var re=A(Q,V,k);if(re.type==="normal"){if(ve=k.done?G:b,re.arg===x)continue;return{value:re.arg,done:k.done}}else re.type==="throw"&&(ve=G,k.method="throw",k.arg=re.arg)}}}function W(Q,V){var k=V.method,ve=Q.iterator[k];if(ve===d)return V.delegate=null,k==="throw"&&Q.iterator.return&&(V.method="return",V.arg=d,W(Q,V),V.method==="throw")||k!=="return"&&(V.method="throw",V.arg=new TypeError("The iterator does not provide a '"+k+"' method")),x;var _e=A(ve,Q.iterator,V.arg);if(_e.type==="throw")return V.method="throw",V.arg=_e.arg,V.delegate=null,x;var Ae=_e.arg;if(!Ae)return V.method="throw",V.arg=new TypeError("iterator result is not an object"),V.delegate=null,x;if(Ae.done)V[Q.resultName]=Ae.value,V.next=Q.nextLoc,V.method!=="return"&&(V.method="next",V.arg=d);else return Ae;return V.delegate=null,x}j(H),T(H,f,"Generator"),T(H,u,function(){return this}),T(H,"toString",function(){return"[object Generator]"});function ee(Q){var V={tryLoc:Q[0]};1 in Q&&(V.catchLoc=Q[1]),2 in Q&&(V.finallyLoc=Q[2],V.afterLoc=Q[3]),this.tryEntries.push(V)}function I(Q){var V=Q.completion||{};V.type="normal",delete V.arg,Q.completion=V}function X(Q){this.tryEntries=[{tryLoc:"root"}],Q.forEach(ee,this),this.reset(!0)}s.keys=function(Q){var V=Object(Q),k=[];for(var ve in V)k.push(ve);return k.reverse(),function _e(){for(;k.length;){var Ae=k.pop();if(Ae in V)return _e.value=Ae,_e.done=!1,_e}return _e.done=!0,_e}};function te(Q){if(Q){var V=Q[u];if(V)return V.call(Q);if(typeof Q.next=="function")return Q;if(!isNaN(Q.length)){var k=-1,ve=function _e(){for(;++k<Q.length;)if(a.call(Q,k))return _e.value=Q[k],_e.done=!1,_e;return _e.value=d,_e.done=!0,_e};return ve.next=ve}}return{next:Ke}}s.values=te;function Ke(){return{value:d,done:!0}}return X.prototype={constructor:X,reset:function(Q){if(this.prev=0,this.next=0,this.sent=this._sent=d,this.done=!1,this.delegate=null,this.method="next",this.arg=d,this.tryEntries.forEach(I),!Q)for(var V in this)V.charAt(0)==="t"&&a.call(this,V)&&!isNaN(+V.slice(1))&&(this[V]=d)},stop:function(){this.done=!0;var Q=this.tryEntries[0],V=Q.completion;if(V.type==="throw")throw V.arg;return this.rval},dispatchException:function(Q){if(this.done)throw Q;var V=this;function k(re,Ge){return Ae.type="throw",Ae.arg=Q,V.next=re,Ge&&(V.method="next",V.arg=d),!!Ge}for(var ve=this.tryEntries.length-1;ve>=0;--ve){var _e=this.tryEntries[ve],Ae=_e.completion;if(_e.tryLoc==="root")return k("end");if(_e.tryLoc<=this.prev){var Ue=a.call(_e,"catchLoc"),ce=a.call(_e,"finallyLoc");if(Ue&&ce){if(this.prev<_e.catchLoc)return k(_e.catchLoc,!0);if(this.prev<_e.finallyLoc)return k(_e.finallyLoc)}else if(Ue){if(this.prev<_e.catchLoc)return k(_e.catchLoc,!0)}else if(ce){if(this.prev<_e.finallyLoc)return k(_e.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Q,V){for(var k=this.tryEntries.length-1;k>=0;--k){var ve=this.tryEntries[k];if(ve.tryLoc<=this.prev&&a.call(ve,"finallyLoc")&&this.prev<ve.finallyLoc){var _e=ve;break}}_e&&(Q==="break"||Q==="continue")&&_e.tryLoc<=V&&V<=_e.finallyLoc&&(_e=null);var Ae=_e?_e.completion:{};return Ae.type=Q,Ae.arg=V,_e?(this.method="next",this.next=_e.finallyLoc,x):this.complete(Ae)},complete:function(Q,V){if(Q.type==="throw")throw Q.arg;return Q.type==="break"||Q.type==="continue"?this.next=Q.arg:Q.type==="return"?(this.rval=this.arg=Q.arg,this.method="return",this.next="end"):Q.type==="normal"&&V&&(this.next=V),x},finish:function(Q){for(var V=this.tryEntries.length-1;V>=0;--V){var k=this.tryEntries[V];if(k.finallyLoc===Q)return this.complete(k.completion,k.afterLoc),I(k),x}},catch:function(Q){for(var V=this.tryEntries.length-1;V>=0;--V){var k=this.tryEntries[V];if(k.tryLoc===Q){var ve=k.completion;if(ve.type==="throw"){var _e=ve.arg;I(k)}return _e}}throw new Error("illegal catch attempt")},delegateYield:function(Q,V,k){return this.delegate={iterator:te(Q),resultName:V,nextLoc:k},this.method==="next"&&(this.arg=d),x}},s}(l.exports);try{regeneratorRuntime=n}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}})($v);var Pd={exports:{}};(function(l){(function(n,s){l.exports?l.exports=s():n.log=s()})(__,function(){var n=function(){},s="undefined",i=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function e(b,R){var G=b[R];if(typeof G.bind=="function")return G.bind(b);try{return Function.prototype.bind.call(G,b)}catch{return function(){return Function.prototype.apply.apply(G,[b,arguments])}}}function d(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function _(b){return b==="debug"&&(b="log"),typeof console===s?!1:b==="trace"&&i?d:console[b]!==void 0?e(console,b):console.log!==void 0?e(console,"log"):n}function u(b,R){for(var G=0;G<a.length;G++){var x=a[G];this[x]=G<b?n:this.methodFactory(x,b,R)}this.log=this.debug}function g(b,R,G){return function(){typeof console!==s&&(u.call(this,R,G),this[b].apply(this,arguments))}}function f(b,R,G){return _(b)||g.apply(this,arguments)}function T(b,R,G){var x=this,me;R=R??"WARN";var O="loglevel";typeof b=="string"?O+=":"+b:typeof b=="symbol"&&(O=void 0);function $(H){var j=(a[H]||"silent").toUpperCase();if(!(typeof window===s||!O)){try{window.localStorage[O]=j;return}catch{}try{window.document.cookie=encodeURIComponent(O)+"="+j+";"}catch{}}}function de(){var H;if(!(typeof window===s||!O)){try{H=window.localStorage[O]}catch{}if(typeof H===s)try{var j=window.document.cookie,F=j.indexOf(encodeURIComponent(O)+"=");F!==-1&&(H=/^([^;]+)/.exec(j.slice(F))[1])}catch{}return x.levels[H]===void 0&&(H=void 0),H}}function fe(){if(!(typeof window===s||!O)){try{window.localStorage.removeItem(O);return}catch{}try{window.document.cookie=encodeURIComponent(O)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}x.name=b,x.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},x.methodFactory=G||f,x.getLevel=function(){return me},x.setLevel=function(H,j){if(typeof H=="string"&&x.levels[H.toUpperCase()]!==void 0&&(H=x.levels[H.toUpperCase()]),typeof H=="number"&&H>=0&&H<=x.levels.SILENT){if(me=H,j!==!1&&$(H),u.call(x,H,b),typeof console===s&&H<x.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+H},x.setDefaultLevel=function(H){R=H,de()||x.setLevel(H,!1)},x.resetLevel=function(){x.setLevel(R,!1),fe()},x.enableAll=function(H){x.setLevel(x.levels.TRACE,H)},x.disableAll=function(H){x.setLevel(x.levels.SILENT,H)};var N=de();N==null&&(N=R),x.setLevel(N,!1)}var y=new T,A={};y.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var R=A[b];return R||(R=A[b]=new T(b,y.getLevel(),y.methodFactory)),R};var w=typeof window!==s?window.log:void 0;return y.noConflict=function(){return typeof window!==s&&window.log===y&&(window.log=w),y},y.getLoggers=function(){return A},y.default=y,y})})(Pd);var Ct=Pd.exports;const Sn=()=>`${new Date().toISOString()} | metrics`,An=(l,n,s)=>`${l} | ${n} | ${s}`;Ct.setDefaultLevel(Ct.levels.TRACE);const Vv=l=>{Ct.info(An(Sn(),"log ",`set log level to ${l?"verbose":"info"}`)),Ct.setLevel(l?Ct.levels.TRACE:Ct.levels.INFO)},Bv=l=>{const n=[...Object.keys(Ct.levels)];n.includes(l)?(Ct.info(An(Sn(),"log ",`update log level to ${l.toLowerCase()}`)),Ct.setLevel(l)):Ct.warn(An(Sn(),"log ","Incorrect log level please choose one of "),n)},Ne=(l,n,s)=>{s?Ct.debug(An(Sn(),l,n),s):Ct.debug(An(Sn(),l,n))},lu=(l,n)=>{Ct.info(An(Sn(),l,n))},as=(l,n)=>{Ct.info(An(Sn(),l,n))},Il=(l,n)=>{Ct.warn(An(Sn(),l,n))},Ws=(l,n)=>{Ct.error(An(Sn(),l,n))};function Kv(l){return Math.floor(Math.random()*l).toString()}function xd(l,n){let s=n;return l.forEach(i=>{s=s.replace(i,"")}),s}function Gv(l,n){let s="";for(let i=0;i<n;i+=1)s+=l[Kv(l.length)];return s}function Wv({length:l=20,useLetters:n=!0,useNumbers:s=!0,includeSymbols:i=[],excludeSymbols:a=[]}={}){let e="abcdefghijklmnopqrstuvwxyz",d="0123456789",_=[],u=[],g=[];return n&&(a.length&&(e=xd(a,e)),u=e.split("")),s&&(a.length&&(d=xd(a,d)),g=d.split("")),_=[...u,...g,...i],Gv(_,l)}var Yv=Wv;const Dr=We(Yv),zv=()=>"WebRTCMetrics",Jv=()=>"5.0.3",Pe={INBOUND:"inbound",OUTBOUND:"outbound"},Cn={IDLE:"idle",RUNNING:"running",MUTED:"muted"},kr={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},Xv=()=>({delta_time_to_measure_probes_ms:0,delta_time_consumed_to_measure_ms:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,total_time_decoded_in:0,total_time_encoded_out:0,probes:[]}),Ld={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:Pe.INBOUND},Hd={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:Pe.OUTBOUND},qd={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:Pe.INBOUND},Fd={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:Pe.OUTBOUND},Qv=l=>{const n={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(l){const s={...l,audio:{},video:{},data:{...l.data},network:{...l.network},experimental:{...l.experimental}};return Object.keys(l.audio).forEach(i=>{s.audio[i]={...l.audio[i]}}),Object.keys(l.video).forEach(i=>{s.video[i]={...l.video[i]}}),s}return{...n,audio:{},video:{},data:{...n.data},network:{...n.network},experimental:{...n.experimental}}},Zv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Dr()}`,cid:`c-${Dr()}`,uid:`u-${Dr()}`,record:!1,ticket:!0},Yt={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},q={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},D={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Ur={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},au={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},se={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},uu="config ",ey=(l,n={},s)=>{const i={...s,...n};return n.pname||Il(uu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${s.pname}'`),n.cid||Il(uu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${s.cid}'`),n.uid||Il(uu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${s.uid}'`),i.pc=l,i},ty=(l={})=>{const n={...Zv,...l};return n.name=zv(),n.version=Jv(),n},Mr=(l,n,s,i=!1,a)=>{let e=l.map(d=>{if(!s)return d[n];if(!a)return d[n][s];const _=d[n][a];return _?_[s]:null});return e=e.filter(d=>i?Number.isFinite(d)&&d>0:Number.isFinite(d)),e.length===0?[]:e},Jn=l=>l.reduce((n,s)=>n+s,0)/l.length,ny=()=>`probe-${Dr()}`,sy=()=>`coltr-${Dr()}`,jd=l=>new Promise(n=>setTimeout(n,l)),cu=(l,n,s)=>{n?l.call(n,s):l(s)},Ye=(l,n,s,i)=>{const a=Mr(l,n,s,!0,i);if(a.length===0)return null;const e=a.reduce((d,_)=>d+_,0)/a.length;return e===0?null:a.map(d=>Math.abs(e-d)).reduce((d,_)=>d+_,0)/a.length*100/e},Xe=(l,n,s,i=!1,a)=>{const e=Mr(l,n,s,i,a);return e.length===0?null:e.reduce((d,_)=>d+_,0)/e.length},us=(l,n,s)=>Mr(l,n,s).reduce((i,a)=>i+a,0),ze=(l,n,s,i)=>{const a=Mr(l,n,s,!0,i);return a.length===0?null:Math.min(...a)},Je=(l,n,s,i)=>{const a=Mr(l,n,s,!1,i);return a.length===0?null:Math.max(...a)},St=(l,n,s,i)=>{const a=l.slice().pop();if(!a)return null;if(!s)return a[n];if(!i)return a[n][s];const e=a[n][i];return e?e[s]:null},ry=l=>l.slice().pop(),ht=(l,n,s)=>{if(!n)return null;const i={};let a=n[D.AUDIO][l];a||(a=s===Pe.INBOUND?{...Ld}:{...Hd}),i[D.AUDIO]=a;let e=n[D.VIDEO][l];return e||(e=s===Pe.INBOUND?{...qd}:{...Fd}),i[D.VIDEO]=e,i},Pr="exporter ",iy="2.0",$d=(l,n,s)=>{if(!l||l.length===0)return 0;const i=l[l.length-1];if(!i)return 0;const a=i[n][s];if(a){const e=a.total_rtt_ms_out,d=a.total_rtt_measure_out;return!d||!e?Xe(l,n,"delta_rtt_ms_out",!1,s):Number(e/d)}return null},oy=(l,n)=>{if(!l||l.length===0)return 0;const s=l[l.length-1];if(!s)return 0;const i=s[n].total_rtt_connectivity_ms,a=s[n].total_rtt_connectivity_measure;return!a||!i?Xe(l,n,"delta_rtt_connectivity_ms"):Number(i/a)},ly=l=>St(l,"network","local_candidate_type")!=="relay"?`direct/${St(l,"network","local_candidate_protocol")}`:`turn/${St(l,"network","local_candidate_relay_protocol")}`,ay=l=>{const n=St(l,"network","remote_candidate_type"),s=St(l,"network","remote_candidate_protocol");return n!=="relay"?`direct/${s}`:`turn/${s}`};class uy{constructor(n){this._start=null,this._end=null,this._cfg=n,this._referenceReport=null,this._reports=[],this._events=[]}start(){lu(Pr,"start() - start exporter...");const n=new Date;return this._start=n.toJSON(),n}stop(){lu(Pr,"stop() - stop exporter...");const n=new Date;return this._end=n.toJSON(),n}saveReferenceReport(n){this._referenceReport=n}getReferenceReport(){return this._referenceReport}addReport(n){this._cfg.ticket&&(Ne(Pr,`addReport() - add report to exporter at ${n.timestamp}`),this._reports.push(n))}addCustomEvent(n){this._events.push(n)}reset(){lu(Pr,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Ne(Pr,"ticket() - generate ticket");const n=St(this._reports,"audio","total_packets_lost_in"),s=St(this._reports,"audio","total_packets_in"),i=St(this._reports,"video","total_packets_lost_in"),a=St(this._reports,"video","total_packets_in"),e={},d=ry(this._reports);return d&&(Object.keys(d[D.AUDIO]).forEach(_=>{const u=d[D.AUDIO][_];if(e[u.ssrc]={type:D.AUDIO,direction:u.direction},u.direction===Pe.INBOUND){const g={avg:Xe(this._reports,D.AUDIO,"delta_jitter_ms_in",!1,_),min:ze(this._reports,D.AUDIO,"delta_jitter_ms_in",_),max:Je(this._reports,D.AUDIO,"delta_jitter_ms_in",_),volatility:Ye(this._reports,D.AUDIO,"delta_jitter_ms_in",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},f={avg:Xe(this._reports,D.AUDIO,"delta_kbs_in",!1,_),min:ze(this._reports,D.AUDIO,"delta_kbs_in",_),max:Je(this._reports,D.AUDIO,"delta_kbs_in",_),volatility:Ye(this._reports,D.AUDIO,"delta_kbs_in",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,D.AUDIO,"delta_KBytes_in",!1,_),min:ze(this._reports,D.AUDIO,"delta_KBytes_in",_),max:Je(this._reports,D.AUDIO,"delta_KBytes_in",_),volatility:Ye(this._reports,D.AUDIO,"delta_KBytes_in",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},y={emodel:{avg:Xe(this._reports,D.AUDIO,"mos_emodel_in",!1,_),min:ze(this._reports,D.AUDIO,"mos_emodel_in",_),max:Je(this._reports,D.AUDIO,"mos_emodel_in",_),volatility:Ye(this._reports,D.AUDIO,"mos_emodel_in",_)},effective:{avg:Xe(this._reports,D.AUDIO,"mos_in",!1,_),min:ze(this._reports,D.AUDIO,"mos_in",_),max:Je(this._reports,D.AUDIO,"mos_in",_),volatility:Ye(this._reports,D.AUDIO,"mos_in",_)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},A=St(this._reports,D.AUDIO,"total_packets_lost_in",_),w=St(this._reports,D.AUDIO,"total_packets_in",_),b={lost:A,avg:Math.round((A/(A+w)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[_].jitter=g,e[_].mos=y,e[_].traffic=T,e[_].bitrate=f,e[_].loss=b}else{const g={avg:Xe(this._reports,D.AUDIO,"delta_jitter_ms_out",!1,_),min:ze(this._reports,D.AUDIO,"delta_jitter_ms_out",_),max:Je(this._reports,D.AUDIO,"delta_jitter_ms_out",_),volatility:Ye(this._reports,D.AUDIO,"delta_jitter_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},f={avg:Xe(this._reports,D.AUDIO,"delta_kbs_out",!1,_),min:ze(this._reports,D.AUDIO,"delta_kbs_out",_),max:Je(this._reports,D.AUDIO,"delta_kbs_out",_),volatility:Ye(this._reports,D.AUDIO,"delta_kbs_out",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,D.AUDIO,"delta_KBytes_out",!1,_),min:ze(this._reports,D.AUDIO,"delta_KBytes_out",_),max:Je(this._reports,D.AUDIO,"delta_KBytes_out",_),volatility:Ye(this._reports,D.AUDIO,"delta_KBytes_out",_),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},y={avg:$d(this._reports,D.AUDIO,_),min:ze(this._reports,D.AUDIO,"delta_rtt_ms_out",_),max:Je(this._reports,D.AUDIO,"delta_rtt_ms_out",_),volatility:Ye(this._reports,D.AUDIO,"delta_rtt_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},A=St(this._reports,D.AUDIO,"total_packets_lost_out",_),w=St(this._reports,D.AUDIO,"total_packets_out",_),b={lost:A,avg:Math.round((A/(A+w)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},R={emodel:{avg:Xe(this._reports,D.AUDIO,"mos_emodel_out",!1,_),min:ze(this._reports,D.AUDIO,"mos_emodel_out",_),max:Je(this._reports,D.AUDIO,"mos_emodel_out",_),volatility:Ye(this._reports,D.AUDIO,"mos_emodel_out",_)},effective:{avg:Xe(this._reports,D.AUDIO,"mos_out",!1,_),min:ze(this._reports,D.AUDIO,"mos_out",_),max:Je(this._reports,D.AUDIO,"mos_out",_),volatility:Ye(this._reports,D.AUDIO,"mos_out",_)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};e[_].jitter=g,e[_].rtt=y,e[_].traffic=T,e[_].bitrate=f,e[_].loss=b,e[_].mos=R}}),Object.keys(d[D.VIDEO]).forEach(_=>{const u=d[D.VIDEO][_];if(e[_]={type:D.VIDEO,direction:u.direction},u.direction===Pe.INBOUND){const g={avg:Xe(this._reports,D.VIDEO,"delta_jitter_ms_in",!1,_),min:ze(this._reports,D.VIDEO,"delta_jitter_ms_in",_),max:Je(this._reports,D.VIDEO,"delta_jitter_ms_in",_),volatility:Ye(this._reports,D.VIDEO,"delta_jitter_ms_in",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},f={avg:Xe(this._reports,D.VIDEO,"delta_kbs_in",!1,_),min:ze(this._reports,D.VIDEO,"delta_kbs_in",_),max:Je(this._reports,D.VIDEO,"delta_kbs_in",_),volatility:Ye(this._reports,D.VIDEO,"delta_kbs_in",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,D.VIDEO,"delta_KBytes_in",!1,_),min:ze(this._reports,D.VIDEO,"delta_KBytes_in",_),max:Je(this._reports,D.VIDEO,"delta_KBytes_in",_),volatility:Ye(this._reports,D.VIDEO,"delta_KBytes_in",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},y=St(this._reports,D.VIDEO,"total_packets_lost_in",_),A=St(this._reports,D.VIDEO,"total_packets_in",_),w={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[_].jitter=g,e[_].traffic=T,e[_].bitrate=f,e[_].loss=w}else{const g={avg:Xe(this._reports,D.VIDEO,"delta_jitter_ms_out",!1,_),min:ze(this._reports,D.VIDEO,"delta_jitter_ms_out",_),max:Je(this._reports,D.VIDEO,"delta_jitter_ms_out",_),volatility:Ye(this._reports,D.VIDEO,"delta_jitter_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},f={avg:Xe(this._reports,D.VIDEO,"delta_kbs_out",!1,_),min:ze(this._reports,D.VIDEO,"delta_kbs_out",_),max:Je(this._reports,D.VIDEO,"delta_kbs_out",_),volatility:Ye(this._reports,D.VIDEO,"delta_kbs_out",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,D.VIDEO,"delta_KBytes_out",!1,_),min:ze(this._reports,D.VIDEO,"delta_KBytes_out",_),max:Je(this._reports,D.VIDEO,"delta_KBytes_out",_),volatility:Ye(this._reports,D.VIDEO,"delta_KBytes_out",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},y={avg:$d(this._reports,D.VIDEO,_),min:ze(this._reports,D.VIDEO,"delta_rtt_ms_out",_),max:Je(this._reports,D.VIDEO,"delta_rtt_ms_out",_),volatility:Ye(this._reports,D.VIDEO,"delta_rtt_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},A=St(this._reports,D.VIDEO,"total_packets_lost_out",_),w=St(this._reports,D.VIDEO,"total_packets_out",_),b={lost:A,avg:Math.round((A/(A+w)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[_].jitter=g,e[_].rtt=y,e[_].traffic=T,e[_].bitrate=f,e[_].loss=b}})),{version:iy,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:e,data:{rtt:{avg:oy(this._reports,"data"),min:ze(this._reports,"data","delta_rtt_connectivity_ms"),max:Je(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Ye(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((n/(n+s)*100||0)*100)/100}},video:{in:{avg:Math.round((i/(i+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Xe(this._reports,"data","delta_kbs_in"),min:ze(this._reports,"data","delta_kbs_in"),max:Je(this._reports,"data","delta_kbs_in"),volatility:Ye(this._reports,"data","delta_kbs_in")},out:{avg:Xe(this._reports,"data","delta_kbs_out"),min:ze(this._reports,"data","delta_kbs_out"),max:Je(this._reports,"data","delta_kbs_out"),volatility:Ye(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Xe(this._reports,"data","delta_KBytes_in"),min:ze(this._reports,"data","delta_KBytes_in"),max:Je(this._reports,"data","delta_KBytes_in"),volatility:Ye(this._reports,"data","delta_KBytes_in")},out:{avg:Xe(this._reports,"data","delta_KBytes_out"),min:ze(this._reports,"data","delta_KBytes_out"),max:Je(this._reports,"data","delta_KBytes_out"),volatility:Ye(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:ly(this._reports),remoteConnection:ay(this._reports)}}}}updateConfig(n){this._cfg=n}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const n=this._reports.slice();return n.pop(),n.pop()||null}getReportsNumber(){return this._reports.length}}const Xn="extractor ",Vd=(l,n,s,i)=>{let a=!1;const e=i[n].total_rtt_ms_out,d=i[n].total_rtt_measure_out,_=s?s[n].total_rtt_ms_out:0,u=s?s[n].total_rtt_measure_out:0,g={rtt:null,totalRTT:e,totalRTTMeasurements:d};if(l[q.TIMESTAMP]===i[n].timestamp_out||!Object.prototype.hasOwnProperty.call(l,q.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(l,q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(l[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(l[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-u===d))return g;const f=1e3*Number(l[q.ROUND_TRIP_TIME]);let T=e+f,y=d+1;return a&&(T=1e3*Number(l[q.TOTAL_ROUND_TRIP_TIME])-_,y=Number(l[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-u),{rtt:f,totalRTT:T,totalRTTMeasurements:y}},cy=(l,n,s,i)=>{if(!Object.prototype.hasOwnProperty.call(l,q.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:i[n].total_rtt_connectivity_ms,totalRTTMeasurements:i[n].total_rtt_connectivity_measure};const a=1e3*Number(l[q.CURRENT_ROUND_TRIP_TIME]);let e=i[n].total_rtt_connectivity_ms+a,d=i[n].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(l,q.TOTAL_ROUND_TRIP_TIME)&&(e=1e3*Number(l[q.TOTAL_ROUND_TRIP_TIME])-(s?s[n].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(l,q.RESPONSES_RECEIVED)&&(d=Number(l[q.RESPONSES_RECEIVED])-(s?s[n].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:e,totalRTTMeasurements:d}},wl=(l,n,s)=>l[q.TIMESTAMP]===s[n].timestamp_out||!Object.prototype.hasOwnProperty.call(l,q.JITTER)?null:1e3*(Number(l[q.JITTER])||0),hy=(l,n)=>{if(!Object.prototype.hasOwnProperty.call(l,q.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(l,q.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:n[D.VIDEO].delta_ms_decode_frame_in,frames_decoded:n[D.VIDEO].total_frames_decoded_in,total_decode_time:n[D.VIDEO].total_time_decoded_in};const s=l[q.FRAMES_DECODED],i=l[q.TOTAL_DECODE_TIME],a=i-n[D.VIDEO].total_time_decoded_in,e=s-n[D.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:e>0?a*1e3/e:0,frames_decoded:s,total_decode_time:i}},dy=(l,n)=>{if(!Object.prototype.hasOwnProperty.call(l,q.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(l,q.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:n[D.VIDEO].delta_ms_encode_frame_out,frames_encoded:n[D.VIDEO].total_frames_encoded_out,total_encode_time:n[D.VIDEO].total_time_encoded_out};const s=l[q.FRAMES_ENCODED],i=l[q.TOTAL_ENCODE_TIME],a=i-n[D.VIDEO].total_time_encoded_out,e=s-n[D.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:e>0&&a?a*1e3/e:0,frames_encoded:s,total_encode_time:i}},Bd=(l,n,s,i)=>{if(!Object.prototype.hasOwnProperty.call(l,q.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(l,q.BYTES_SENT))return{packetsSent:s[n].total_packets_out,packetsLost:s[n].total_packets_lost_out,bytesSent:s[n].total_KBytes_out};const a=Number(l[q.PACKETS_SENT])||0-(i?i[n].total_packets_out:0),e=a-s[n].total_packets_out,d=Number(l[q.BYTES_SENT])/1024-(i?i[n].total_KBytes_out:0),_=d-s[n].total_KBytes_out,u=l[q.TIMESTAMP]||Date.now(),g=i?i.timestamp:null;let f=s.timestamp;!f&&g&&(f=g);const T=f?u-f:0,y=T>0?_*.008*1024/T*1e3:0;return{packetsSent:a,deltaPacketsSent:e,KBytesSent:d,deltaKBytesSent:_,kbsSent:y}},Kd=(l,n,s,i)=>{let a=s[n].total_packets_lost_out,e=0,d=0;return Object.prototype.hasOwnProperty.call(l,q.PACKETS_LOST)&&(a=Number(l[q.PACKETS_LOST])||0-(i?i[n].total_packets_lost_out:0),e=a-s[n].total_packets_lost_out),Object.prototype.hasOwnProperty.call(l,q.FRACTION_LOST)&&(d=Number(100*l[q.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:e,fractionLost:d}},Gd=(l,n,s,i)=>{if(!Object.prototype.hasOwnProperty.call(l,q.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(l,q.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(l,q.BYTES_RECEIVED))return{percent_packets_lost:s[n].percent_packets_lost_in,packetsReceived:s[n].total_packets_in,packetsLost:s[n].total_packets_lost_in,bytesReceived:s[n].total_KBytes_in};const a=Number(l[q.PACKETS_RECEIVED])||0-(i?i[n].total_packets_in:0),e=Number(l[q.PACKETS_LOST])||0-(i?i[n].total_packets_lost_in:0),d=e-s[n].total_packets_lost_in,_=a-s[n].total_packets_in,u=a!==s[n].total_packets_in?d*100/(d+_):0,g=Number(l[q.BYTES_RECEIVED])/1024-(i?i[n].total_KBytes_in:0),f=g-s[n].total_KBytes_in,T=l[q.TIMESTAMP]||Date.now(),y=i?i.timestamp:null;let A=s.timestamp;!A&&y&&(A=y);const w=A?T-A:0,b=w>0?f*.008*1024/w*1e3:0;return{percentPacketsLost:u,packetsReceived:a,deltaPacketsReceived:_,packetsLost:e,deltaPacketsLost:d,KBytesReceived:g,deltaKBytesReceived:f,kbsReceived:b}},_y=l=>l[q.CANDIDATE_TYPE]!=="relay"?"":l[q.RELAY_PROTOCOL]||"",py=l=>{if(!Object.prototype.hasOwnProperty.call(l,q.NETWORK_TYPE))return Ur.WIFI;switch(l[q.NETWORK_TYPE]){case au.ETHERNET:return Ur.ETHERNET;case au.CELLULAR_4G:return Ur.CELLULAR_4G;case au.WIFI:return Ur.WIFI;default:return Ur.CELLULAR}},Wd=l=>!Object.prototype.hasOwnProperty.call(l,q.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(l,q.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:l[q.FRAME_WIDTH]||null,height:l[q.FRAME_HEIGHT]||null,framerate:l[q.FRAMES_PER_SECOND]},fy=l=>{const n=Object.prototype.hasOwnProperty.call(l,q.QUALITY_LIMITATION_REASON)?l[q.QUALITY_LIMITATION_REASON]:null,s=Object.prototype.hasOwnProperty.call(l,q.QUALITY_LIMITATION_RESOLUTION_CHANGES)?l[q.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,i=Object.prototype.hasOwnProperty.call(l,q.QUALITY_LIMITATION_DURATIONS)?l[q.QUALITY_LIMITATION_DURATIONS]:null;return i&&Object.keys(i).forEach(a=>{i[a]>1e3&&(i[a]=Number(i[a]/1e3))}),{reason:n,durations:i,resolutionChanges:s}},my=(l,n,s)=>{if(!Object.prototype.hasOwnProperty.call(l,q.PLI)||!Object.prototype.hasOwnProperty.call(l,q.NACK))return{pliCount:n.total_pli_sent_in,nackCount:n.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const i=(l[q.PLI]||0)-(s?s[D.VIDEO].total_pli_sent_in:0),a=(l[q.NACK]||0)-(s?s[D.VIDEO].total_nack_sent_in:0);return{pliCount:i,nackCount:a,deltaPliCount:i-n[D.VIDEO].total_pli_sent_in,deltaNackCount:a-n[D.VIDEO].total_nack_sent_in}},gy=(l,n,s)=>{if(!Object.prototype.hasOwnProperty.call(l,q.PLI)||!Object.prototype.hasOwnProperty.call(l,q.NACK))return{pliCount:n.total_pli_received_out,nackCount:n.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const i=(l[q.PLI]||0)-(s?s[D.VIDEO].total_pli_received_out:0),a=(l[q.NACK]||0)-(s?s[D.VIDEO].total_nack_received_out:0);return{pliCount:i,nackCount:a,deltaPliCount:i-n[D.VIDEO].total_pli_received_out,deltaNackCount:a-n[D.VIDEO].total_nack_received_out}},Ty=l=>({channels:l[q.CHANNELS]||null,clock_rate:l[q.CLOCK_RATE]||null,mime_type:l[q.MIME_TYPE]||null,sdp_fmtp_line:l[q.SDP_FMTP_LINE]||null}),vy=l=>({clock_rate:l[q.CLOCK_RATE]||null,mime_type:l[q.MIME_TYPE]||null}),yy=(l,n,s)=>{const i=(l[q.BYTES_RECEIVED]||0)/1024-(s?s.data.total_KBytes_in:0),a=(l[q.BYTES_SENT]||0)/1024-(s?s.data.total_KBytes_out:0),e=l[q.TIMESTAMP]||Date.now(),d=i-n.data.total_KBytes_in,_=a-n.data.total_KBytes_out,u=s?s.timestamp:null;let g=n.timestamp;!g&&u&&(g=u);const f=g?e-g:0,T=f>0?d*.008*1024/f*1e3:0,y=f>0?_*.008*1024/f*1e3:0;return{total_KBytes_received:i,total_KBytes_sent:a,delta_KBytes_received:d,delta_KBytes_sent:_,kbs_speed_received:T,kbs_speed_sent:y}},Ey=l=>{const n=l[q.AVAILABLE_INCOMING_BITRATE]/1024||0,s=l[q.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:n,kbs_outgoing_bandwidth:s}},Sy=(l,n,s,i)=>{if(!l)return[];switch(l[q.TYPE]){case Yt.CANDIDATE_PAIR:let a=!1;if(l[q.NOMINATED]&&l[q.STATE]===D.SUCCEEDED&&(a=!0,Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l),q.SELECTED in l&&!l[q.SELECTED]&&(a=!1)),a){const d=l[q.LOCAL_CANDIDATE_ID],_=l[q.REMOTE_CANDIDATE_ID],u=yy(l,n,i),g=Ey(l),f=cy(l,"data",i,n);return[{type:se.NETWORK,value:{local_candidate_id:d}},{type:se.NETWORK,value:{remote_candidate_id:_}},{type:se.DATA,value:{total_KBytes_in:u.total_KBytes_received}},{type:se.DATA,value:{total_KBytes_out:u.total_KBytes_sent}},{type:se.DATA,value:{delta_KBytes_in:u.delta_KBytes_received}},{type:se.DATA,value:{delta_KBytes_out:u.delta_KBytes_sent}},{type:se.DATA,value:{delta_kbs_in:u.kbs_speed_received}},{type:se.DATA,value:{delta_kbs_out:u.kbs_speed_sent}},{type:se.DATA,value:{delta_kbs_bandwidth_in:g.kbs_incoming_bandwidth}},{type:se.DATA,value:{delta_kbs_bandwidth_out:g.kbs_outgoing_bandwidth}},{type:se.DATA,value:{delta_rtt_connectivity_ms:f.rtt}},{type:se.DATA,value:{total_rtt_connectivity_ms:f.totalRTT}},{type:se.DATA,value:{total_rtt_connectivity_measure:f.totalRTTMeasurements}}]}break;case Yt.LOCAL_CANDIDATE:if(l[q.ID]===n.network.local_candidate_id)return[{type:se.NETWORK,value:{infrastructure:py(l)}},{type:se.NETWORK,value:{local_candidate_type:l[q.CANDIDATE_TYPE]||""}},{type:se.NETWORK,value:{local_candidate_protocol:l[q.PROTOCOL]||""}},{type:se.NETWORK,value:{local_candidate_relay_protocol:_y(l)}}];break;case Yt.REMOTE_CANDIDATE:if(l[q.ID]===n.network.remote_candidate_id)return[{type:se.NETWORK,value:{remote_candidate_type:l[q.CANDIDATE_TYPE]||""}},{type:se.NETWORK,value:{remote_candidate_protocol:l[q.PROTOCOL]||""}}];break;case Yt.INBOUND_RTP:{Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);const d=l[q.SSRC],_=ht(d,n,Pe.INBOUND);_&&(_.timestamp=n.timestamp);const u=ht(d,i,Pe.INBOUND);if(u&&(u.timestamp=i.timestamp),l[q.MEDIA_TYPE]===D.AUDIO){const g=Gd(l,D.AUDIO,_,u),f=wl(l,D.AUDIO,_),T=l[q.CODEC_ID]||"";return[{ssrc:d,type:se.AUDIO,value:{codec_id_in:T}},{ssrc:d,type:se.AUDIO,value:{total_packets_in:g.packetsReceived}},{ssrc:d,type:se.AUDIO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:d,type:se.AUDIO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:d,type:se.AUDIO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:d,type:se.AUDIO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:d,type:se.AUDIO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:d,type:se.AUDIO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:d,type:se.AUDIO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:d,type:se.AUDIO,value:{delta_jitter_ms_in:f}}]}if(l[q.MEDIA_TYPE]===D.VIDEO){const g=hy(l,_),f=Gd(l,D.VIDEO,_,u),T=wl(l,D.VIDEO,_),y=l[q.DECODER_IMPLEMENTATION]||null,A=l[q.CODEC_ID]||null,w=Wd(l),b=my(l,_,u);return[{ssrc:d,type:se.VIDEO,value:{codec_id_in:A}},{ssrc:d,type:se.VIDEO,value:{total_packets_in:f.packetsReceived}},{ssrc:d,type:se.VIDEO,value:{delta_packets_in:f.deltaPacketsReceived}},{ssrc:d,type:se.VIDEO,value:{total_packets_lost_in:f.packetsLost}},{ssrc:d,type:se.VIDEO,value:{delta_packets_lost_in:f.deltaPacketsLost}},{ssrc:d,type:se.VIDEO,value:{percent_packets_lost_in:f.percentPacketsLost}},{ssrc:d,type:se.VIDEO,value:{total_KBytes_in:f.KBytesReceived}},{ssrc:d,type:se.VIDEO,value:{delta_KBytes_in:f.deltaKBytesReceived}},{ssrc:d,type:se.VIDEO,value:{delta_kbs_in:f.kbsReceived}},{ssrc:d,type:se.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:d,type:se.VIDEO,value:{decoder_in:y}},{ssrc:d,type:se.VIDEO,value:{delta_ms_decode_frame_in:g.delta_ms_decode_frame}},{ssrc:d,type:se.VIDEO,value:{total_frames_decoded_in:g.frames_decoded}},{ssrc:d,type:se.VIDEO,value:{total_time_decoded_in:g.total_decode_time}},{ssrc:d,type:se.VIDEO,value:{total_nack_sent_in:b.nackCount}},{ssrc:d,type:se.VIDEO,value:{delta_nack_sent_in:b.deltaNackCount}},{ssrc:d,type:se.VIDEO,value:{total_pli_sent_in:b.pliCount}},{ssrc:d,type:se.VIDEO,value:{delta_pli_sent_in:b.deltaPliCount}},{ssrc:d,type:se.VIDEO,value:{size_in:w}}]}break}case Yt.OUTBOUND_RTP:{Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);const d=l[q.SSRC],_=ht(d,n,Pe.OUTBOUND);_&&(_.timestamp=n.timestamp);const u=ht(d,i,Pe.OUTBOUND);if(u&&(u.timestamp=i.timestamp),l[q.MEDIA_TYPE]===D.AUDIO){const g=l[q.CODEC_ID]||null,f=Bd(l,D.AUDIO,_,u);return[{ssrc:d,type:se.AUDIO,value:{codec_id_out:g}},{ssrc:d,type:se.AUDIO,value:{total_packets_out:f.packetsSent}},{ssrc:d,type:se.AUDIO,value:{delta_packets_out:f.deltaPacketsSent}},{ssrc:d,type:se.AUDIO,value:{total_KBytes_out:f.KBytesSent}},{ssrc:d,type:se.AUDIO,value:{delta_KBytes_out:f.deltaKBytesSent}},{ssrc:d,type:se.AUDIO,value:{delta_kbs_out:f.kbsSent}}]}if(l[q.MEDIA_TYPE]===D.VIDEO){const g=l[q.ENCODER_IMPLEMENTATION]||null,f=l[q.CODEC_ID]||null,T=dy(l,_),y=Wd(l),A=fy(l),w=gy(l,_,u),b=Bd(l,D.VIDEO,_,u);return[{ssrc:d,type:se.VIDEO,value:{codec_id_out:f}},{ssrc:d,type:se.VIDEO,value:{total_packets_out:b.packetsSent}},{ssrc:d,type:se.VIDEO,value:{delta_packets_out:b.deltaPacketsSent}},{ssrc:d,type:se.VIDEO,value:{total_KBytes_out:b.KBytesSent}},{ssrc:d,type:se.VIDEO,value:{delta_KBytes_out:b.deltaKBytesSent}},{ssrc:d,type:se.VIDEO,value:{delta_kbs_out:b.kbsSent}},{ssrc:d,type:se.VIDEO,value:{encoder_out:g}},{ssrc:d,type:se.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:d,type:se.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:d,type:se.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:d,type:se.VIDEO,value:{total_nack_received_out:w.nackCount}},{ssrc:d,type:se.VIDEO,value:{delta_nack_received_out:w.deltaNackCount}},{ssrc:d,type:se.VIDEO,value:{total_pli_received_out:w.pliCount}},{ssrc:d,type:se.VIDEO,value:{delta_pli_received_out:w.deltaPliCount}},{ssrc:d,type:se.VIDEO,value:{size_out:y}},{ssrc:d,type:se.VIDEO,value:{limitation_out:A}}]}break}case Yt.MEDIA_SOURCE:{Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);break}case Yt.TRACK:{Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);break}case Yt.CODEC:const e=[];return Object.keys(n[D.AUDIO]).forEach(d=>{const _=n[D.AUDIO][d];if(_.codec_id_in===l[q.ID]||_.codec_id_out===l[q.ID]){Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);const u=Ty(l);l[q.ID]===_.codec_id_in?e.push({ssrc:_.ssrc,type:se.AUDIO,value:{codec_in:u}}):e.push({ssrc:_.ssrc,type:se.AUDIO,value:{codec_out:u}})}}),Object.keys(n[D.VIDEO]).forEach(d=>{const _=n[D.VIDEO][d];if(_.codec_id_in===l[q.ID]||_.codec_id_out===l[q.ID]){Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);const u=vy(l);l[q.ID]===_.codec_id_in?e.push({ssrc:_.ssrc,type:se.VIDEO,value:{codec_in:u}}):e.push({ssrc:_.ssrc,type:se.VIDEO,value:{codec_out:u}})}}),e;case Yt.REMOTE_INBOUND_RTP:{Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);const d=l[q.SSRC],_=ht(d,n,Pe.OUTBOUND),u=ht(d,i,Pe.OUTBOUND);if(l[q.KIND]===D.AUDIO){const g=Vd(l,D.AUDIO,u,_),f=wl(l,D.AUDIO,_),T=Kd(l,D.AUDIO,_,u);return[{ssrc:d,type:se.AUDIO,value:{delta_rtt_ms_out:g.rtt}},{ssrc:d,type:se.AUDIO,value:{total_rtt_ms_out:g.totalRTT}},{ssrc:d,type:se.AUDIO,value:{total_rtt_measure_out:g.totalRTTMeasurements}},{ssrc:d,type:se.AUDIO,value:{delta_jitter_ms_out:f}},{ssrc:d,type:se.AUDIO,value:{timestamp_out:l[q.TIMESTAMP]}},{ssrc:d,type:se.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:d,type:se.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:d,type:se.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(l[q.KIND]===D.VIDEO){const g=Vd(l,D.VIDEO,u,_),f=wl(l,D.VIDEO,_),T=Kd(l,D.VIDEO,_,u);return[{ssrc:d,type:se.VIDEO,value:{delta_rtt_ms_out:g.rtt}},{ssrc:d,type:se.VIDEO,value:{total_rtt_ms_out:g.totalRTT}},{ssrc:d,type:se.VIDEO,value:{total_rtt_measure_out:g.totalRTTMeasurements}},{ssrc:d,type:se.VIDEO,value:{delta_jitter_ms_out:f}},{ssrc:d,type:se.VIDEO,value:{timestamp_out:l[q.TIMESTAMP]}},{ssrc:d,type:se.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:d,type:se.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:d,type:se.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},Ol=l=>l<0?1:l>100?4.5:1+.035*l+7/1e6*l*(l-60)*(100-l),Ay=(l,n=D.AUDIO,s,i,a)=>{const e=ht(a,l,Pe.INBOUND),d=ht(a,s,Pe.INBOUND),_=ht(a,i,Pe.INBOUND),u=[],g=[],f=e[n].percent_packets_lost_in,T=e[n].delta_jitter_ms_in,y=d&&d[n].delta_jitter_ms_in||null,A=_&&_[n].delta_jitter_ms_in||null,w=l.data.delta_rtt_connectivity_ms,b=s&&s.data.delta_rtt_connectivity_ms||null,R=i&&i.data.delta_rtt_connectivity_ms||null;w&&u.push(w),b&&u.push(b),R&&u.push(R),T&&g.push(T),s&&y&&g.push(y),i&&A&&g.push(A);const G=u.length>0?Jn(u):100,x=g.length>0?Jn(g):10,me=93.2-f,O=.18*me*me-27.9*me+1126.62,$=(G+x)/2,de=$-177.3<0?0:1,fe=.024*$+.11*($-177.3)*de,N=O-fe;return Ol(N)},Cy=(l,n=D.AUDIO,s,i,a)=>{const e=ht(a,l,Pe.OUTBOUND),d=ht(a,s,Pe.OUTBOUND),_=ht(a,i,Pe.OUTBOUND),u=[],g=[],f=e[n].percent_packets_lost_out,T=e[n].delta_rtt_ms_out,y=d&&d[n].delta_rtt_ms_out||null,A=_&&_[n].delta_rtt_ms_out||null,w=e[n].delta_jitter_ms_out,b=d&&d[n].delta_jitter_ms_out||null,R=_&&_[n].delta_jitter_ms_out||null,G=l.data.delta_rtt_connectivity_ms,x=s&&s.data.delta_rtt_connectivity_ms||null,me=i&&i.data.delta_rtt_connectivity_ms||null;T?u.push(T):G&&u.push(G),y?u.push(y):x&&u.push(x),A?u.push(A):me&&u.push(me),w&&g.push(w),s&&b&&g.push(b),i&&R&&g.push(R);const O=u.length>0?Jn(u):100,$=g.length>0?Jn(g):10,de=93.2-f,fe=.18*de*de-27.9*de+1126.62,N=(O+$)/2,H=N-177.3<0?0:1,j=.024*N+.11*(N-177.3)*H,F=fe-j;return Ol(F)},by=(l,n=D.AUDIO,s,i,a)=>{const e=ht(a,l,Pe.INBOUND),d=ht(a,s,Pe.INBOUND),_=ht(a,i,Pe.INBOUND),u=[],g=[],f=e[n].percent_packets_lost_in/100,T=e[n].delta_jitter_ms_in,y=d&&d[n].delta_jitter_ms_in||null,A=_&&_[n].delta_jitter_ms_in||null,w=l.data.delta_rtt_connectivity_ms,b=s&&s.data.delta_rtt_connectivity_ms||null,R=i&&i.data.delta_rtt_connectivity_ms||null;w&&u.push(w),b&&u.push(b),R&&u.push(R),T&&g.push(T),d&&y&&g.push(y),_&&A&&g.push(A);const G=u.length>0?Jn(u):100,x=g.length>0?Jn(g):10,me=0,O=19.8,$=29.7,de=30,fe=(G+x)/2+de,N=fe-177.3<0?0:1,H=.024*fe+.11*(fe-177.3)*N,j=93.2-(me+O*Math.log(1+$*f)+H);return Ol(j)},Ry=(l,n=D.AUDIO,s,i,a)=>{const e=ht(a,l,Pe.OUTBOUND),d=ht(a,s,Pe.OUTBOUND),_=ht(a,i,Pe.OUTBOUND),u=[],g=[],f=e[n].percent_packets_lost_out/100,T=e[n].delta_rtt_ms_out,y=d&&d[n].delta_rtt_ms_out||null,A=_&&_[n].delta_rtt_ms_out||null,w=e[n].delta_jitter_ms_out,b=d&&d[n].delta_jitter_ms_out||null,R=_&&_[n].delta_jitter_ms_out||null,G=l.data.delta_rtt_connectivity_ms,x=s&&s.data.delta_rtt_connectivity_ms||null,me=i&&i.data.delta_rtt_connectivity_ms||null;T?u.push(T):G&&u.push(G),y?u.push(y):x&&u.push(x),A?u.push(A):me&&u.push(me),w&&g.push(w),d&&b&&g.push(b),_&&R&&g.push(R);const O=u.length>0?Jn(u):100,$=g.length>0?Jn(g):10,de=0,fe=19.8,N=29.7,H=30,j=(O+$)/2+H,F=j-177.3<0?0:1,P=.024*j+.11*(j-177.3)*F,W=93.2-(de+fe*Math.log(1+N*f)+P);return Ol(W)};class Iy{constructor(n,s){this._callbacks={onreport:null,onticket:null},this._id=sy(),this._moduleName=this._id,this._probeId=s,this._config=n,this._exporter=new uy(n),this._state=Cn.IDLE,this.registerToPCEvents(),as(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(n,s,i,a){const e=(u,g)=>u===D.AUDIO?g===Yt.INBOUND_RTP?{...Ld}:{...Hd}:g===Yt.INBOUND_RTP?{...qd}:{...Fd},d=Qv(s);d.pname=this._config.pname,d.call_id=this._config.cid,d.user_id=this._config.uid,d.count=s?s.count+1:1;let _=null;return n.forEach(u=>{!_&&u.timestamp&&(_=u.timestamp),Sy(u,d,d.pname,a).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let f=d[g.type][g.ssrc];f||(f=e(g.type,u.type),f.ssrc=g.ssrc,d[g.type][g.ssrc]=f),Object.keys(g.value).forEach(T=>{f[T]=g.value[T]})}else Object.keys(g.value).forEach(f=>{d[g.type][f]=g.value[f]})})}),d.timestamp=_,Object.keys(d[D.AUDIO]).forEach(u=>{const g=d[D.AUDIO][u];g.direction===Pe.INBOUND?(g.mos_emodel_in=Ay(d,D.AUDIO,s,i,g.ssrc),g.mos_in=by(d,D.AUDIO,s,i,g.ssrc)):(g.mos_emodel_out=Cy(d,D.AUDIO,s,i,g.ssrc),g.mos_out=Ry(d,D.AUDIO,s,i,g.ssrc))}),d}async takeReferenceStats(){return new Promise((n,s)=>{const i=Date.now();setTimeout(async()=>{try{const a=Date.now()-i,e=Date.now(),d=await this._config.pc.getStats(),_=this.analyze(d,null,null,null),u=Date.now();_.experimental.time_to_measure_ms=u-e,_.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(_),Ne(this._moduleName,`got reference report for probe ${this._probeId}`),n()}catch(a){s(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Cn.RUNNING||!this._config.pc)return Ne(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const n=Date.now(),s=await this._config.pc.getStats(),i=this.analyze(s,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return i.experimental.time_to_measure_ms=a-n,this._exporter.addReport(i),Ne(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(i),i}catch(n){return Ws(this._moduleName,`got error ${n}`),null}}async start(){Ne(this._moduleName,"starting"),this.state=Cn.RUNNING,this._startedTime=this._exporter.start(),Ne(this._moduleName,"started")}async mute(){this.state=Cn.MUTED,Ne(this._moduleName,"muted")}async unmute(){this.state=Cn.RUNNING,Ne(this._moduleName,"unmuted")}async stop(n){if(Ne(this._moduleName,`stopping${n?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Cn.IDLE,this._config.ticket){const{ticket:s}=this._exporter;this.fireOnTicket(s)}this._exporter.reset(),Ne(this._moduleName,"stopped")}registerCallback(n,s,i){n in this._callbacks?(this._callbacks[n]={callback:s,context:i},Ne(this._moduleName,`registered callback '${n}'`)):Ws(this._moduleName,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Ne(this._moduleName,`unregistered callback '${n}'`)):Ws(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReport(n){this._callbacks.onreport&&cu(this._callbacks.onreport.callback,this._callbacks.onreport.context,n)}fireOnTicket(n){this._callbacks.onticket&&cu(this._callbacks.onticket.callback,this._callbacks.onticket.context,n)}updateConfig(n){this._config=n,this._exporter.updateConfig(n)}get state(){return this._state}set state(n){this._state=n,Ne(this._moduleName,`state changed to ${n}`)}addCustomEvent(n,s,i,a){this._exporter.addCustomEvent({at:typeof n=="object"?n.toJSON():n,category:s,name:i,description:a})}async registerToPCEvents(){const{pc:n}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const s=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${s.length} devices found`,"Media Devices state")}catch{Ws(this._moduleName,"can't get devices")}},n){n.oniceconnectionstatechange=()=>{const i=n.iceConnectionState;i===kr.CONNECTED||i===kr.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",i,"ICE connection state"):i===kr.DISCONNECTED||i===kr.FAILED?this.addCustomEvent(new Date().toJSON(),"call",i,"ICE connection state"):i===kr.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},n.onicegatheringstatechange=()=>{const i=n.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",i,"ICE gathering state")},n.ontrack=i=>{this.addCustomEvent(new Date().toJSON(),"call",`${i.track.kind}track`,"MediaStreamTrack received")},n.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const s=n.getReceivers();if(s&&s.length>0){const i=s[0],{transport:a}=i;if(a){const{iceTransport:e}=a;e&&(e.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class wy{constructor(n){this._id=n.pname&&n.pname.substr(0,12).padEnd(12," ")||ny(),this._moduleName=this._id,as(this._moduleName,"probe created"),this._config=n,this._collector=new Iy(this._config,this._id)}set onreport(n){n?this._collector.registerCallback("onreport",n):this._collector.unregisterCallback("onreport")}set onticket(n){n?this._collector.registerCallback("onticket",n):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(n){this._collector.state=n}addCustomEvent(n,s,i,a=new Date().toJSON()){this._collector.addCustomEvent(a,s,n,i)}get isRunning(){return this._collector.state===Cn.RUNNING}get isIdle(){return this._collector.state===Cn.IDLE}updateUserId(n){this._config.uid=n,this._collector.updateConfig(this._config)}updateCallId(n){this._config.cid=n,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Il(this._moduleName,"probe is already running");return}this._collector.start()}stop(n=!1){this.isRunning&&this._collector.stop(n)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const bt="engine ";class Oy{constructor(n){this._config=n,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},as(bt,`configured for probing every ${this._config.refreshEvery}ms`),as(bt,`configured for starting after ${this._config.startAfter}ms`),as(bt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Ne(bt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(n=>n.isRunning)}get isIdle(){return this._probes.every(n=>n.isIdle)}addNewProbe(n,s){if(!n)throw new Error("undefined peer connection");const i=ey(n,s,this._config),a=new wy(i);return this._probes.push(a),Ne(bt,`${this._probes.length} probes registered`),a}removeExistingProbe(n){if(!n)throw new Error("undefined probe");n.state===Cn.RUNNING&&n.stop(),this._probes=this._probes.filter(s=>n.id!==s.id)}async start(){const n=()=>{this._probes.forEach(e=>e.start())},s=async()=>Promise.all(this._probes.map(e=>e.takeReferenceStats())),i=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const e=Xv(),d=this._probes.filter(_=>_.isRunning);for(const _ of d){const u=await _.collectStats();u&&e.probes.push(u),Ne(bt,`got probe ${_.id}`),await jd(0)}return e.delta_time_to_measure_probes_ms=us(e.probes,"experimental","time_to_measure_ms"),e.delta_KBytes_in=us(e.probes,"data","delta_KBytes_in"),e.delta_KBytes_out=us(e.probes,"data","delta_KBytes_out"),e.delta_kbs_in=us(e.probes,"data","delta_kbs_in"),e.delta_kbs_out=us(e.probes,"data","delta_kbs_out"),e.total_time_decoded_in=us(e.probes,"video","total_time_decoded_in"),e.total_time_encoded_out=us(e.probes,"video","total_time_encoded_out"),e};for(Ne(bt,"starting to collect"),n(),Ne(bt,"generating reference reports..."),await s(),Ne(bt,"reference reports generated"),this._startedTime=Date.now();i();)if(Ne(bt,`wait ${this._config.refreshEvery}ms before collecting`),await jd(this._config.refreshEvery),i()){Ne(bt,"collecting...");const e=Date.now(),d=await a(),_=Date.now();d.delta_time_consumed_to_measure_ms=_-e,this.fireOnReports(d),Ne(bt,"collected")}Ne(bt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(n){const s=i=>{this._probes.forEach(a=>{a.stop(i)})};as(bt,"stop collecting"),s(n)}registerCallback(n,s,i){n in this._callbacks?(this._callbacks[n]={callback:s,context:i},Ne(bt,`registered callback '${n}'`)):Ws(bt,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Ne(this._moduleName,`unregistered callback '${n}'`)):Ws(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReports(n){this._callbacks.onresult&&n.probes.length>0&&cu(this._callbacks.onresult.callback,this._callbacks.onresult.context,n)}}const Ny="interface ";class Dy{constructor(n){this._config=ty(n),as(Ny,`welcome to ${this._config.name} version ${this._config.version}`),Vv(this._config.verbose||!1),this._engine=new Oy(this._config)}setupLogLevel(n){Bv(n)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(n,s){return this._engine.addNewProbe(n,s)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(n){this._engine.removeExistingProbe(n)}set onresult(n){n?this._engine.registerCallback("onresult",n):this._engine.unregisterCallback("onresult")}}function ky(l,n){return Object.keys(l).filter(s=>n.includes(s)).reduce((s,i)=>{const a=i;return{...s,[a]:l[a]}},{})}const Uy=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],My={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class Py{constructor(n){this.intervals={},this.analysers={},this.emitInterval=n.emitInterval||200,this.onChangeFunction=n.onChangeFunction}async start(n,s,i){s&&s.getTracks().length&&await this.beginCalculation(n,s,i)}stop(n){this.clearVolumeInterval(n),this.analysers[n]&&typeof this.analysers[n].disconnect=="function"&&(this.analysers[n].disconnect(),delete this.analysers[n])}clearVolumeInterval(n){this.intervals[n]&&(clearInterval(this.intervals[n]),delete this.intervals[n])}clearAllIntervals(){Object.keys(this.intervals).forEach(n=>{this.stop(n)}),this.intervals={},this.analysers={}}async beginCalculation(n,s,i){this.clearVolumeInterval(i);const a=n.createAnalyser(),e=n.createMediaStreamSource(s);a.smoothingTimeConstant=.8,a.fftSize=1024,e.connect(a),this.analysers[i]=a,this.intervals[i]=setInterval(()=>{const d=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(d);let _=0;const u=d.length;for(let f=0;f<u;f++)_+=d[f];const g=_/u;this.onChangeFunction(i,g)},this.emitInterval)}}class xy{constructor(){this.resumePromise=null,this.context=new AudioContext}async getContext(){return this.context.state==="suspended"&&(this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(n=>{throw this.resumePromise=null,n})),await this.resumePromise),this.context}}const Nl={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},Ly=0;class Hy{constructor(n){var s;if(this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.isCallWaitingEnabled=!0,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.conferenceNodes={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.vadSessions={},this.vadSessionsState={},this.vadIntervals={},this.vadMrsIntervals={},this.managedAudioContext=new xy,this.context=n,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new Py({onChangeFunction:this.emitVolumeChange.bind(this)}),this.processVADConfiguration(),this.initializeMediaDevices(),["enabled","dynamic"].includes(this.noiseReduction.mode)){const i=(s=this.context.options.configuration)==null?void 0:s.vadModule;i&&i.MicVAD?(this.MicVAD=i.MicVAD,console.log("✅ VAD module loaded successfully")):(console.warn("⚠️ Noise reduction is enabled but VAD module is not provided. To use VAD features, please install @ricky0123/vad-web and pass it via configuration.vadModule option."),this.noiseReduction.mode="disabled")}}processVADConfiguration(){var n;const s=((n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)||{};this.noiseReduction={mode:s.mode||"disabled",checkEveryMs:s.checkEveryMs||500,noiseCheckInterval:s.noiseCheckInterval||2e3,noiseThreshold:s.noiseThreshold||.004,vadConfig:s.vadConfig||{}}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(n){this.currentActiveRoomIdValue=n,this.context.emit("currentActiveRoomChanged",n)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(n){this.isCallAddingInProgress=n,this.context.emit("callAddingInProgressChanged",n)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get isCallWaiting(){return this.isCallWaitingEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get hasActiveAnsweredCalls(){return Object.values(this.activeRooms).filter(n=>!n.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audiooutput")}get getUserMediaConstraints(){return Ud()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input},echoCancellation:!0,echoCancellationType:"system",noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,latency:.01},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(n){this.availableMediaDevices=n,this.context.emit("changeAvailableDeviceList",n)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const n=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(n)}async initializeMediaDevices(){const n=localStorage.getItem(Nl.SELECTED_INPUT_DEVICE)||"default",s=localStorage.getItem(Nl.SELECTED_OUTPUT_DEVICE)||"default";try{const i=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(n),await this.setSpeaker(s),navigator.mediaDevices.addEventListener("devicechange",async()=>{const e=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(e)}),i.getTracks().forEach(e=>e.stop())}catch(i){console.error(i)}}async cleanupConferenceNodes(n){const s=this.conferenceNodes[n];if(!s)return;let i=0;s.sources.forEach((d,_)=>{try{d.disconnect(),i++}catch(u){console.error(`[cleanupConferenceNodes] Error disconnecting source ${_}:`,u)}});let a=0;s.destinations.forEach((d,_)=>{try{d.disconnect(),a++}catch(u){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${_}:`,u)}});let e=0;s.gains.forEach((d,_)=>{try{d.disconnect(),e++}catch(u){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${_}:`,u)}}),delete this.conferenceNodes[n]}setCallTime(n){const s={...n};delete s.callId,this.callTime={...this.callTime,[n.callId]:s},this.context.emit("changeCallTime",this.callTime)}removeCallTime(n){const s={...this.callTime};delete s[n],this.callTime={...s},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(n,s){this.timeIntervals={...this.timeIntervals,[n]:s}}removeTimeInterval(n){const s={...this.timeIntervals};s[n]&&(clearInterval(s[n]),delete s[n],this.timeIntervals={...s})}stopCallTimer(n){this.removeTimeInterval(n),this.removeCallTime(n)}emitVolumeChange(n,s){this.context.emit("changeCallVolume",{callId:n,volume:s})}setMetricsConfig(n){this.metricConfig={...this.metricConfig,...n}}sendDTMF(n,s){if(!/^[A-D0-9*#]+$/g.test(s))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[n].sendDTMF(s)}setIsMuted(n){this.muted=n,this.context.emit("changeIsMuted",n)}processMute(n){const s=this.currentActiveRoomId;this.setIsMuted(n),this.initialStreamValue.getTracks().forEach(i=>i.enabled=!n),this.roomReconfigure(s)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:n,toHold:s,automatic:i}){const a=this.extendedCalls[n];if(!a)return;a._automaticHold=i??!1;const e=new Promise((d,_)=>{const u=setTimeout(()=>{_(new Error("Hold operation timeout"))},5e3),g=()=>{clearTimeout(u),a.putOnHoldTimestamp=s?Date.now():void 0,d()},f=T=>{clearTimeout(u),_(T)};try{s?(this.stopSessionVad(a._id),a.hold({},g)):a.unhold({},g)}catch(T){f(T)}});try{await e,this.updateCall(a);const d=Object.values(this.extendedCalls).filter(_=>_.roomId===a.roomId&&(s?n!==_._id:!0));d.length>1&&await this.doConference(d)}catch(d){throw console.error("Hold operation failed:",d),d}}holdCall(n,s=!1){return this.processHold({callId:n,automatic:s,toHold:!0})}unholdCall(n){return this.processHold({callId:n,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(n=>n.direction==="outgoing"&&n.status===Ly).forEach(n=>this.terminateCall(n._id))}answerCall(n){const s=this.extendedCalls[n];this.cancelAllOutgoingUnanswered(),s.answer(this.sipOptions),this.updateCall(s),this.setActiveRoom(s.roomId),s.connection.addEventListener("track",i=>{this.triggerAddStream(i,s)})}async moveCall(n,s){this.updateCallStatus({callId:n,isMoving:!0}),await this.processRoomChange({callId:n,roomId:s}),this.updateCallStatus({callId:n,isMoving:!1})}updateCall(n){this.activeCalls[n._id]=Dd(n),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(n){const s={...this.activeRooms[n.roomId],...n};this.activeRooms={...this.activeRooms,[n.roomId]:{...s}},this.context.emit("updateRoom",{room:s,roomList:this.activeRooms})}hasAutoAnswerHeaders(n){const s=/answer-after=0/,i=n.request.getHeader("Call-Info");return i&&s.test(i)}addCall(n,s=!0){this.activeCalls={...this.activeCalls,[n._id]:Dd(n)},this.extendedCalls[n._id]=n,s&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(n){this.callStatus={...this.callStatus,[n]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(n){const s={...this.callStatus[n.callId]};n.isMoving!==void 0&&(s.isMoving=n.isMoving),n.isTransferring!==void 0&&(s.isTransferring=n.isTransferring),n.isMerging!==void 0&&(s.isMerging=n.isMerging),n.isTransferred!==void 0&&(s.isTransferred=n.isTransferred),this.callStatus={...this.callStatus,[n.callId]:{...s}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(n){const s={...this.callStatus};delete s[n],this.callStatus={...s},this.context.emit("changeCallStatus",this.callStatus)}addRoom(n){this.activeRooms={...this.activeRooms,[n.roomId]:n},this.context.emit("addRoom",{room:n,roomList:this.activeRooms})}async setupActiveStream(){const n=await ru(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);n.getTracks().forEach(s=>s.enabled=!this.isMuted),await this.setActiveStream(n)}async getActiveStream(){const n=await ru(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return n.getTracks().forEach(s=>s.enabled=!this.isMuted),await this.setActiveStream(n),n}async setMicrophone(n){if(!this.getInputDeviceList.find(({deviceId:i})=>i===n)||(this.setSelectedInputDevice(n),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const s=Object.values(this.extendedCalls).filter(i=>i.roomId===this.currentActiveRoomId);s.length===1?Object.values(s).forEach(async i=>{await this.setupActiveStream();const a=this.activeStream;i.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(i)}):await this.doConference(s)}async setActiveStream(n){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(n,"origin"),this.activeStreamValue=n,this.context.emit("changeActiveStream",n)}async setSpeaker(n){if(!this.getOutputDeviceList.find(({deviceId:a})=>a===n))return;this.setSelectedOutputDevice(n);const s=Object.values(this.extendedCalls);if(s.length===0)return;const i=s.filter(a=>a.roomId===this.currentActiveRoomId);i.length===1?s.forEach(a=>{var e;(e=a.audioTag)==null||e.setSinkId(n),this.updateCall(a)}):await this.doConference(i)}removeRoom(n){const s={...this.activeRooms},i={...s[n]};delete s[n],this.activeRooms={...s},this.context.emit("removeRoom",{room:i,roomList:this.activeRooms})}deleteRoomIfEmpty(n){n!==void 0&&Object.values(this.extendedCalls).filter(s=>s.roomId===n).length===0&&(this.removeRoom(n),this.currentActiveRoomId===n&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(n){this.muted?n.mute({audio:!0}):n.unmute({audio:!0})}startNoiseMonitor({sessionId:n,stream:s,onNoiseDetected:i,onNoiseStop:a}){const e=new AudioContext,d=e.createMediaStreamSource(s.clone()),_=e.createAnalyser();_.fftSize=1024;const u=new Float32Array(_.fftSize);d.connect(_);const g=[];this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),this.vadIntervals[n]=null),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),this.vadMrsIntervals[n]=null),this.vadMrsIntervals[n]=setInterval(()=>{_.getFloatTimeDomainData(u);const f=qv(u);g.push(f);const T=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);g.length>T&&g.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[n]=setInterval(()=>{if(g.length===0)return;const f=g.reduce((A,w)=>A+w,0)/g.length,T=this.vadSessionsState[n],y=f>this.noiseReduction.noiseThreshold;T.isSpeaking||(y&&T.currentMode==="clean"?(T.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!0}),i()):!y&&T.currentMode==="noisy"&&(T.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!1}),a()))},this.noiseReduction.noiseCheckInterval)}async processVAD(n,s){const i=s.clone();this.stopSessionVad(n._id),this.vadSessionsState[n._id]={currentMode:"clean",isSpeaking:!1};const a=await this.managedAudioContext.getContext(),e=await Fv(i,a,150);let d=!1;const _=await this.MicVAD.new({getStream:()=>new Promise(u=>u(i)),...My,...this.noiseReduction.vadConfig,baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.28/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/",onFrameProcessed:()=>{if(!d){if(d=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){n.connection.getSenders()[0]&&n.connection.getSenders()[0].replaceTrack(e.stream.getAudioTracks()[0]);return}this.startNoiseMonitor({sessionId:n._id,stream:i,onNoiseDetected:async()=>{var u;console.log("Replace track with Vad Controlled"),await((u=n.connection.getSenders()[0])==null?void 0:u.replaceTrack(e.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const u=n.connection.getSenders()[0];u&&u.track&&u.transport&&u.transport.state!=="closed"&&u.transport.state!=="failed"&&(console.log("Replace track with Original"),await u.replaceTrack(i.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var u;console.log("🎤 Speech started"),e.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((u=n.connection.getSenders()[0])==null||u.replaceTrack(e.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!0},onSpeechEnd:()=>{var u;console.log("🛑 Speech end"),e.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((u=n.connection.getSenders()[0])==null||u.replaceTrack(e.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!1}});this.vadSessions[n._id]&&(this.vadSessions[n._id].pause(),delete this.vadSessions[n._id]),this.vadSessions[n._id]=_,_.start()}stopSessionVad(n){this.vadSessions[n]&&(this.vadSessions[n].pause(),delete this.vadSessions[n]),this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),delete this.vadIntervals[n]),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),delete this.vadMrsIntervals[n]),this.vadSessionsState[n]&&delete this.vadSessionsState[n]}async roomReconfigure(n){var s;if(n===void 0)return;const i=Object.values(this.extendedCalls).filter(e=>e.roomId===n),a=this.currentActiveRoomId===n;if(i.forEach((e,d)=>{if(e.audioTag){e.connection.getReceivers().forEach(u=>{u.track.enabled=!e.localMuted}),a&&this.muteReconfigure(e);const _=!a;e.audioTag.muted=_,this.updateCall(e)}}),i.length===0){this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n),this.deleteRoomIfEmpty(n);return}if(i.length===1&&!a){const e=i[0];e.isOnHold().local||await this.holdCall(e._id,!0),this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}if(i.length===1&&a){const e=i[0];e.isOnHold().local&&e._automaticHold&&await this.unholdCall(e._id);const d=(((s=e.connection)==null?void 0:s.getSenders())||[])[0];if(e.connection&&d)try{await this.setupActiveStream();const _=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(i[0],_);const u=_.getTracks();await d.replaceTrack(u[0]),this.muteReconfigure(e)}catch(_){console.error(_)}this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}i.length>1&&await this.doConference(i)}async doConference(n){if(n.length===0)return;const s=n[0].roomId,i=this.currentActiveRoomId===s;if(n.find(_=>_.roomId!==s))return;const a=await this.managedAudioContext.getContext();if(a.state!=="running"){console.error(`[doConference] ERROR: AudioContext is not running! State: ${a.state}`);return}await this.cleanupConferenceNodes(s),this.conferenceNodes[s]={sources:new Map,destinations:new Map,gains:new Map};const e=this.conferenceNodes[s],d=new Map;n.forEach((_,u)=>{_&&_.connection&&_.connection.getReceivers().forEach((g,f)=>{var T,y,A;g.track.enabled=!_.localMuted;const w=(T=g.track)==null?void 0:T.id;(y=g.track)==null||y.readyState,(A=g.track)==null||A.kind;const b=`${_._id}-${w}`;g.track&&g.track.readyState==="live"&&d.set(b,g.track)})}),await this.setupActiveStream(),await jv.forEach(n,async(_,u)=>{if(!_||!_.connection)return;const g=a.createMediaStreamDestination();e.destinations.set(_._id,g);let f=0;if(d.forEach((A,w)=>{if(!w.startsWith(_._id))try{const b=a.createMediaStreamSource(new MediaStream([A])),R=a.createGain(),G=`${_._id}-${w}`;b.connect(R),R.connect(g),e.sources.set(G,b),e.gains.set(G,R),f++}catch(b){console.error(b)}}),i&&this.activeStreamValue)try{const A=this.activeStream,w=a.createMediaStreamSource(A),b=a.createGain(),R=`${_._id}-local`;w.connect(b),b.connect(g),e.sources.set(R,w),e.gains.set(R,b)}catch(A){console.error(A)}else i&&console.error(`Host room but no activeStreamValue - skipping host microphone for session ${_._id}`);const T=_.connection.getSenders()[0],y=g.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(_,g.stream),T&&y[0])try{await T.replaceTrack(y[0]),this.muteReconfigure(_)}catch(A){console.error(A)}})}processCallerMute(n,s){const i=this.extendedCalls[n];i&&i.connection.getReceivers().length&&(i.localMuted=s,i.connection.getReceivers().forEach(a=>{a.track.enabled=!s}),this.updateCall(i))}muteCaller(n){this.processCallerMute(n,!0)}unmuteCaller(n){this.processCallerMute(n,!1)}terminateCall(n){const s=this.extendedCalls[n];s._status===4?s.terminate({status_code:603,reason_phrase:"Decline"}):s._status!==8&&s.terminate()}transferCall(n,s){if(s.toString().length===0)return new Error("Target must be passed");const i=this.extendedCalls[n];if(!i._is_confirmed&&!i._is_canceled){const a=`sip:${s}@${this.context.sipDomain}`;i.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:n,isTransferring:!0,isTransferred:!1}),i.refer(`sip:${s}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(i)}mergeCall(n){const s=Object.values(this.extendedCalls).filter(e=>e.roomId===n);if(s.length!==2)return;const i=s[0],a=s[1];!i||!a||(this.updateCallStatus({callId:i._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),i.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(i))}mergeCallByIds(n,s){const i=Object.values(this.extendedCalls).find(e=>e._id===n),a=Object.values(this.extendedCalls).find(e=>e._id===s);if(!i||!a)throw new Error("Call ID is not provided");this.updateCallStatus({callId:n,isMerging:!0}),this.updateCallStatus({callId:s,isMerging:!0}),i.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(i)}setDND(n){this.isDNDEnabled=n,this.context.emit("changeIsDND",n)}setCallWaiting(n){this.isCallWaitingEnabled=n,this.context.emit("changeIsCallWaiting",n)}startCallTimer(n){this.removeTimeInterval(n);const s={callId:n,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(s);const i=setInterval(()=>{const a={...this.callTime[n]},e=Hv(a);this.setCallTime({callId:n,...e})},1e3);this.setTimeInterval(n,i)}async setActiveRoom(n){const s=this.currentActiveRoomId;n!==s&&(this.currentActiveRoomId=n,await this.roomReconfigure(s),await this.roomReconfigure(n))}getNewRoomId(){const n=Object.keys(this.activeRooms);return n.length===0?1:parseInt(n.sort()[n.length-1])+1}async setupCall(n){var s,i;const a=n.session;if(this.getActiveCalls[a.id]!==void 0)return;const e=this.getNewRoomId(),d={started:new Date,incomingInProgress:!1,roomId:e};a.direction==="incoming"?(this.context.logger.log("New incoming call from",(i=(s=a._remote_identity)==null?void 0:s._uri)==null?void 0:i._user),d.incomingInProgress=!0,this.context.subscribe(Wt.CALL_CONFIRMED,f=>{a.id===f.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.startCallTimer(a.id))}),this.context.subscribe(Wt.CALL_FAILED,f=>{a.id===f.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.deleteRoomIfEmpty(e))})):a.direction==="outgoing"&&(a.once("confirmed",()=>{this.startCallTimer(a.id)}),this.startCallTimer(a.id));const _=a,u=this.hasAutoAnswerHeaders(n),g=_.direction==="incoming"&&!this.hasActiveCalls&&(u||this.autoAnswer);_.roomId=e,_.localMuted=!1,_.autoAnswer=g,g?this.addCall(_,!1):this.addCall(_),this.addCallStatus(a.id),this.addRoom(d),g&&this.answerCall(_._id)}removeCall(n){const s={...this.activeCalls};delete s[n],this.activeCalls={...s};const i={...this.extendedCalls};delete i[n],this.extendedCalls={...i},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(n){const s=this.extendedCalls[n._id];if(!s)return;this.stopVUMeter("origin"),this.stopVUMeter(n._id);const i=s.roomId;this.removeCall(n._id),this.roomReconfigure(i).then(()=>{}).catch(a=>{console.error("Error reconfiguring room after call removal:",a)})}shouldTerminateNewSession(n){if(n.session.direction==="outgoing")return!1;const s=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||s}async newRTCSessionCallback(n){const s=n.session;if(this.shouldTerminateNewSession(n)){s.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Wt.NEW_CALL,session:s,event:n}),s.on("ended",i=>{var a,e,d;this.stopVUMeter(s.id),this.context.logger.log("Session ended for",(e=(a=s._remote_identity)==null?void 0:a._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Wt.CALL_ENDED,session:s,event:i}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(s._id);const _=this.getActiveCalls[s.id];_&&this.activeCallListRemove(_),this.stopCallTimer(s.id),this.removeCallStatus(s.id),this.removeCallMetrics(s.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(u=>u.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),s.on("progress",i=>{var a,e;this.context.logger.log("Session in progress for",(e=(a=s._remote_identity)==null?void 0:a._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Wt.CALL_PROGRESS,session:s,event:i})}),s.on("failed",i=>{var a,e,d;this.stopVUMeter(s.id),this.context.logger.log("Session failed for",(e=(a=s._remote_identity)==null?void 0:a._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Wt.CALL_FAILED,session:s,event:i}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(s._id),s.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const _=this.getActiveCalls[s.id];_&&this.activeCallListRemove(_),this.stopCallTimer(s.id),this.removeCallStatus(s.id),this.removeCallMetrics(s.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(u=>u.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),s.on("confirmed",i=>{var a,e;this.context.logger.log("Session confirmed for",(e=(a=s._remote_identity)==null?void 0:a._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Wt.CALL_CONFIRMED,session:s,event:i}),this.updateCall(s),s.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(n),s.direction==="outgoing"){const i=this.getActiveCalls[s.id].roomId;await this.setActiveRoom(i)}}setMuteWhenJoin(n){this.muteWhenJoinEnabled=n,this.context.emit("changeMuteWhenJoin",n)}setMicrophoneSensitivity(n){if(n<0||n>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=n,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(n){this.speakerVolumeValue=n,Object.values(this.extendedCalls).forEach(s=>{s.audioTag&&(s.audioTag.volume=n,this.updateCall(s))})}setAutoAnswer(n){this.isAutoAnswer=n}setSelectedInputDevice(n){localStorage.setItem(Nl.SELECTED_INPUT_DEVICE,n),this.selectedMediaDevices.input=n,this.context.emit("changeActiveInputMediaDevice",n)}setSelectedOutputDevice(n){localStorage.setItem(Nl.SELECTED_OUTPUT_DEVICE,n),this.selectedMediaDevices.output=n,this.context.emit("changeActiveOutputMediaDevice",n)}setCallMetrics(n){const s={...n};delete s.callId,this.callMetrics={...this.callMetrics,[n.callId]:s},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(n){const s={...this.callMetrics};delete s[n],this.callMetrics={...s},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(n){const s=new Dy(this.metricConfig),i=s.createProbe(n.connection,{cid:n._id}),a=[];let e;i.onreport=d=>{Object.entries(d.audio).forEach(([g,f])=>{f.direction==="inbound"&&!a.includes(g)&&(a.push(g),e=g)});const _=d.audio[e];if(!_)return;const u=ky(_,Uy);u.callId=n._id,this.setCallMetrics(u)},this.context.subscribe(Wt.CALL_ENDED,d=>{d._id===n._id&&s.stopAllProbes()}),s.startAllProbes()}async setupVUMeter(n,s){await this.VUMeter.start(await this.managedAudioContext.getContext(),n,s)}stopVUMeter(n){this.VUMeter.stop(n)}async setupStream(){try{const n=Date.now(),s=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((i,a)=>{i.stop()}),this.initialStreamValue=null),this.initialStreamValue=s}catch(n){throw n}}async triggerAddStream(n,s){const i=this.muteWhenJoin||this.isMuted;this.setIsMuted(i),this.initialStreamValue||await this.setupStream();const a=await this.managedAudioContext.getContext(),e=await ru(a,this.initialStreamValue,this.microphoneInputLevel*2),d=this.isMuted||this.muteWhenJoin;e.getTracks().forEach(g=>{g.enabled=!d}),await this.setActiveStream(e),await s.connection.getSenders()[0].replaceTrack(e.getTracks()[0]);const _=new MediaStream([n.track]);!Object.values(this.extendedCalls).find(g=>g.audioTag&&g.audioTag.id===s._id)&&Av(_,s,this.selectedOutputDevice,this.speakerVolume);const u=s.roomId===this.currentActiveRoomId;s.audioTag&&(s.audioTag.muted=!u),await this.setupVUMeter(_,s._id),this.getCallQuality(s),this.updateCall(s),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(s,e)}initCall(n,s,i=!1){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`);const a=this.context.call(`sip:${n}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=a.id,s&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:a.id,roomId:this.currentActiveRoomId}),i)){const e=Object.values(this.extendedCalls).filter(d=>d.roomId===this.currentActiveRoomId&&d._id!==a.id);for(const d of e)this.holdCall(d._id,!0)}a.connection.addEventListener("track",e=>{this.triggerAddStream(e,a)})}async processRoomChange({callId:n,roomId:s}){const i=this.extendedCalls[n];if(!i)return;const a=i.roomId;i.roomId=s,this.updateCall(i),await this.roomReconfigure(a),await this.roomReconfigure(s)}}class qy{constructor(n){this.context=n}get sipOptions(){return{...this.context.options.sipOptions}}initCall(n,s){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${n}@${this.context.sipDomain}`,s,this.sipOptions)}stop(n={}){this.context.terminateJanusSessions(n)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(n){this.context.changeMediaConstraints(n)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class Fy{constructor(n){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=n,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(n){const s=this.extendedMessages[n];this.updateMSRPSession(s)}updateMSRPSession(n){this.activeMessages[n._id]=kd(n),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(n){this.activeMessages={...this.activeMessages,[n._id]:kd(n)},this.extendedMessages[n._id]=n,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(n,s){const i=this.msrpHistory[s.id]||[];i.push(n),this.msrpHistory={...this.msrpHistory,[s.id]:[...i]},this.context.emit("newMSRPMessage",{message:n,session:s})}messageTerminate(n){const s=this.extendedMessages[n];s._status!==8&&s.terminate()}addMessageSession(n){if(!n._id||this.getActiveMessages[n._id]!==void 0)return;const s=n;this.addMMSRPSession(s)}triggerMSRPListener({listenerType:n,session:s,event:i}){const a=this.context.listenersList[n];!a||!a.length||a.forEach(e=>{e(s,i)})}removeMMSRPSession(n){const s={...this.activeMessages};delete s[n],this.activeMessages={...s};const i={...this.extendedMessages};delete i[n],this.extendedMessages={...i},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(n){this.removeMMSRPSession(n._id)}newMSRPSessionCallback(n){const s=n.session;s.on("ended",i=>{this.triggerMSRPListener({listenerType:Wt.CALL_ENDED,session:s,event:i});const a=this.getActiveMessages[s.id];this.activeMessageListRemove(a)}),s.on("failed",i=>{this.triggerMSRPListener({listenerType:Wt.CALL_FAILED,session:s,event:i});const a=this.getActiveMessages[s.id];this.activeMessageListRemove(a)}),s.on("confirmed",i=>{this.triggerMSRPListener({listenerType:Wt.CALL_CONFIRMED,session:s,event:i}),this.updateMSRPSession(s)}),s.on("newMessage",i=>{this.addMSRPMessage(i,s)}),this.addMessageSession(s)}setIsMSRPInitializing(n){this.isMSRPInitializingValue=n,this.context.emit("isMSRPInitializingChanged",n)}initMSRP(n,s,i){if(n.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(n,i);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(s),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(n,s){const i=this.extendedMessages[n];if(!i)throw new Error(`MSRP session with id ${n} doesn't exist!`);i.sendMSRP(s)}}const Dl={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Yd{constructor(n){this.opensips=null,this.session=null,this.name=null,this.name=n}setOpensips(n){this.opensips=n}setSession(n){this.session=n}kill(){this.opensips.kill(this.name)}}class jy extends Yd{constructor(n,s){super(n),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=s}connect(n={}){this.opaqueId=this.session.generateOpaqueId();const s=ke.cloneArray(n.extraHeaders),i={from_tag:this.session._from_tag};n.fromUserName&&(i.from_uri=new ls("sip",n.fromUserName,this.session._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(i.from_display_name=n.fromDisplayName),s.push(`Contact: ${this.session._contact}`),s.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&s.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new gt.InitialOutgoingInviteRequest(this.session.target,this.session._ua,i,s),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let n;this._connection.onicecandidate=s=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||s.candidate&&(this._candidates.push(s.candidate),clearTimeout(n),n=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(n){n.forEach(s=>{this._connection.addTrack(s)})}async _sendInitialRequest(){const n=new yr(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const s={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(s),await this._connection.setLocalDescription(this.jsep_offer);const i={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},a=JSON.stringify(i);this._request.body=a,n.send()}_receiveInviteResponse(n){if(this._publisherSubscribeSent||!n.body)return;const s=JSON.parse(n.body);this.handleId=s.data.id;const i={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},a=[this.session.getPTypeHeader(Mt.PUBLISHER)];this.session.sendRequest(U.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(i),eventHandlers:{onSuccessResponse:async e=>{var d,_,u,g;if(e.status_code===200){if(this._subscribeSent=!0,e.body)try{const f=JSON.parse(e.body)||{};((_=(d=f.plugindata)==null?void 0:d.data)==null?void 0:_.videoroom)==="joined"&&this.session.myFeedList.push(f.plugindata.data.id),(g=(u=f.plugindata)==null?void 0:u.data)!=null&&g.publishers&&this.session.receivePublishers(f)}catch(f){console.error(f)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(n){const s=this._candidates.map(e=>({janus:"trickle",candidate:e,handle_id:this.handleId,session_id:this.session.session_id})),i={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...n},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...s]},a=["Content-Type: application/json",this.session.getPTypeHeader(Mt.ICE)];this.session.sendRequest(U.INFO,{extraHeaders:a,body:JSON.stringify(i),eventHandlers:{onSuccessResponse:async e=>{this._configureSent=!0;const d=e.data.split(`\r
159
- `),_=d[d.length-1],u=JSON.parse(_);await this._connection.setRemoteDescription(u.jsep),this._candidates=[]}}})}_sendDetach(){const n={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},s=[this.session.getPTypeHeader(Mt.DETACH)];this.session.sendRequest(U.INFO,{extraHeaders:s,body:JSON.stringify(n)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const n=this._connection.getSenders();n.forEach(s=>{const i=s.track;i&&i.stop()}),n.forEach(s=>{this._connection.removeTrack(s)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class $y extends Yd{constructor(n,s,i={}){super(n),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=i.immediate||!1,this.type=s}start(n){return n}stop(){throw new Error("stop method is not implemented")}async process(n){if(this.immediate){const s=await this.start(n);return this.running=!0,s}return n}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}class Vy extends mv{constructor(n,s){if(!n.modules.length)throw new Error("options.modules should include at least 1 module");const i={...n.configuration,sockets:n.socketInterfaces.map(a=>new Lv.WebSocketInterface(a))};super(i),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.waitingForSessionHangup=!1,this.waitingForSessionTimeout=null,this.reconnectionAttemptsLimit=1/0,this.reconnectionAttemptsCounter=0,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],n.pnExtraHeaders&&Object.keys(n.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(n.pnExtraHeaders),this.options=n,this.modules=n.modules,n.configuration.reconnectionAttemptsLimit&&(this.reconnectionAttemptsLimit=n.configuration.reconnectionAttemptsLimit),s&&Cv(s)&&(this.logger=s)}isWaitingForSessionHangup(){return this.waitingForSessionHangup}stopSessionAfterWaiting(){this.setInitialized(!1),this.waitingForSessionHangup=!1,clearTimeout(this.waitingForSessionTimeout),this.waitingForSessionTimeout=null,this.activeConnection&&this.reconnect()}get hasActiveSessions(){return this.modules.includes(Dl.AUDIO)?this.audio.hasActiveAnsweredCalls:!1}on(n,s){return super.on(n,s)}off(n,s){return super.off(n,s)}emit(n,s){return super.emit(n,s)}get sipDomain(){return this.options.sipDomain}use(n){if(this.newStreamPlugins.find(s=>s.name===n.name)||this.processStreamPlugins.find(s=>s.name===n.name))throw new Error(`Plugin with name ${n.name} already exists`);if(n instanceof jy)n.setOpensips(this),this.newStreamPlugins.push(n);else if(n instanceof $y)n.setOpensips(this),this.processStreamPlugins.push(n);else throw new Error("Wrong plugin instance")}getPlugin(n){return this.newStreamPlugins.find(s=>s.name===n)||this.processStreamPlugins.find(s=>s.name===n)}reconnect(){if(this.reconnectionAttemptsCounter<this.reconnectionAttemptsLimit){const n=5e3*Math.pow(2,this.reconnectionAttemptsCounter);this.reconnectionAttemptsCounter++,setTimeout(this.start.bind(this),n)}else this.emit("reconnectionAttemptsLimitReached",void 0)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(Dl.AUDIO)&&(this.audio=new Hy(this)),this.modules.includes(Dl.MSRP)&&(this.msrp=new Fy(this)),this.modules.includes(Dl.VIDEO)&&(this.video=new qy(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.setReconnecting(!1),this.activeConnection=!0,this.waitingForSessionHangup=!1,this.reconnectionAttemptsCounter=0}),this.on(this.disconnectedEventName,()=>{this.setConnected(!1),!this.isReconnecting&&(this.setReconnecting(!0),this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.hasActiveSessions?(this.waitingForSessionHangup=!0,this.stop(!1),this.waitingForSessionTimeout=setTimeout(()=>{this.terminateAllSessions(),this.setInitialized(!1),this.waitingForSessionHangup=!1,this.activeConnection&&this.reconnect()},12e5)):(this.stop(),this.setInitialized(!1),this.activeConnection&&this.reconnect()))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(n,s){const i=!this.listenersList[n]||!this.listenersList[n].length?[s]:[...this.listenersList[n],s];this.listenersList={...this.listenersList,[n]:i}}removeIListener(n){const s={...this.listenersList};delete s[n],this.listenersList={...s}}triggerListener({listenerType:n,session:s,event:i}){const a=this.listenersList[n];!a||!a.length||a.forEach(e=>{e(s,i)})}setInitialized(n){this.initialized=n,this.emit("ready",n)}setConnected(n){this.connected=n,this.emit("connection",n)}setReconnecting(n){this.isReconnecting=n,this.emit("reconnecting",n)}}let Oe;const zd=Ce.ref(!1),Jd=Ce.ref(!1),Xd=Ce.ref(!1),Qd=Ce.ref({}),Zd=Ce.ref({}),e_=Ce.ref(!1),t_=Ce.ref(void 0),kl=Ce.ref({}),hu=Ce.ref({}),Ul=Ce.ref([]),du=Ce.ref("default"),_u=Ce.ref("default"),pu=Ce.ref(!1),fu=Ce.ref(!1),mu=Ce.ref(!0),n_=Ce.ref(!1),s_=Ce.ref(null),Ys=Ce.ref(void 0),r_=Ce.ref(!1),gu=Ce.ref(2),Tu=Ce.ref(1),vu=Ce.ref({}),i_=Ce.ref({}),o_=Ce.ref({}),yu=Ce.computed(()=>{const l={};return Object.entries(Qd.value).forEach(([n,s])=>{vu.value[n]?.isTransferred||(l[n]=s)}),l}),By=Ce.computed(()=>{const l={},n=Object.values(yu.value).map(s=>s.roomId);return Object.entries(kl.value).forEach(([s,i])=>{n.includes(i.roomId)&&(l[s]=i)}),l}),Ky=Ce.computed(()=>Ul.value.filter(l=>l.kind==="audioinput").map(l=>({deviceId:l.deviceId,kind:l.kind,groupId:l.groupId,label:l.label}))),Gy=Ce.computed(()=>Ul.value.filter(l=>l.kind==="audiooutput").map(l=>({deviceId:l.deviceId,kind:l.kind,groupId:l.groupId,label:l.label}))),l_=Ce.computed(()=>Object.values(yu.value).filter(l=>l.roomId===Ys.value));Ce.watch(l_,l=>{!l.length&&Ys.value&&(Ys.value=void 0)}),Ce.watch(_u,async l=>{await zt.actions.setMicrophone(l)}),Ce.watch(du,async l=>{await zt.actions.setSpeaker(l)}),Ce.watch(pu,l=>{zt.actions.setMuteWhenJoin(l)}),Ce.watch(fu,l=>{zt.actions.setDND(l)}),Ce.watch(mu,l=>{zt.actions.setCallWaiting(l)}),Ce.watch(gu,l=>{zt.actions.setMicrophoneSensitivity(l)}),Ce.watch(Tu,l=>{zt.actions.setSpeakerVolume(l)}),Ce.watch(Ys,async l=>{await zt.actions.setActiveRoom(l)});const zt={state:{isInitialized:zd,isOpenSIPSReady:Jd,isOpenSIPSReconnecting:Xd,activeCalls:yu,callsInActiveRoom:l_,activeMessages:Zd,addCallToCurrentRoom:e_,callAddingInProgress:t_,activeRooms:By,msrpHistory:hu,availableMediaDevices:Ul,inputMediaDeviceList:Ky,outputMediaDeviceList:Gy,selectedOutputDevice:du,selectedInputDevice:_u,muteWhenJoin:pu,isDND:fu,isCallWaitingEnabled:mu,isMuted:n_,originalStream:s_,currentActiveRoomId:Ys,callStatus:vu,callTime:i_,callMetrics:o_,autoAnswer:r_,microphoneInputLevel:gu,speakerVolume:Tu},actions:{init(l,n,s={}){return new Promise((i,a)=>{try{const e={...s,session_timers:!1,uri:`sip:${l.username}@${l.domain}`,password:l.password};l.authorization_jwt&&(e.authorization_jwt=l.authorization_jwt),Oe=new Vy({configuration:e,socketInterfaces:[`wss://${l.domain}`],sipDomain:`${l.domain}`,sipOptions:{session_timers:!1,extraHeaders:["X-Bar: bar"],pcConfig:{}},modules:l.modules,pnExtraHeaders:n}),Oe.on("connection",d=>{e_.value=!1,zd.value=!0,Jd.value=d,i(Oe)}).on("reconnecting",d=>{Xd.value=d}).on("changeActiveCalls",d=>{Qd.value={...d}}).on("changeActiveMessages",d=>{Zd.value={...d}}).on("newMSRPMessage",d=>{const _=d.session._id,u=hu.value[_]||[];u.push(d.message),hu.value[_]=[...u]}).on("callAddingInProgressChanged",d=>{t_.value=d}).on("changeAvailableDeviceList",d=>{Ul.value=[...d]}).on("changeActiveInputMediaDevice",d=>{_u.value=d}).on("changeActiveOutputMediaDevice",d=>{du.value=d}).on("changeMuteWhenJoin",d=>{pu.value=d}).on("changeIsCallWaiting",d=>{mu.value=d}).on("changeIsDND",d=>{fu.value=d}).on("changeIsMuted",d=>{n_.value=d}).on("changeActiveStream",d=>{s_.value=d}).on("currentActiveRoomChanged",d=>{Ys.value=d}).on("addRoom",({roomList:d})=>{kl.value={...d}}).on("updateRoom",({roomList:d})=>{kl.value={...d}}).on("removeRoom",({roomList:d})=>{kl.value={...d}}).on("changeCallStatus",d=>{vu.value={...d}}).on("changeCallTime",d=>{i_.value={...d}}).on("changeCallMetrics",d=>{o_.value={...d}}).begin(),i(Oe)}catch(e){console.error(e),a()}})},unregister(){Oe?.unregister()},register(){Oe?.register()},disconnect(){Oe?.disconnect()},initCall(l,n=!1,s=!1){Oe?.audio.initCall(l,n,s)},answerCall(l){Oe?.audio.answerCall(l)},terminateCall(l){Oe?.audio.terminateCall(l)},mute(){Oe?.audio.mute()},unmute(){Oe?.audio.unmute()},transferCall(l,n){Oe?.audio.transferCall(l,n)},mergeCall(l){Oe?.audio.mergeCall(l)},mergeCallByIds(l,n){Oe?.audio.mergeCallByIds(l,n)},holdCall(l,n){Oe?.audio.holdCall(l,n)},unholdCall(l){Oe?.audio.unholdCall(l)},async moveCall(l,n){await Oe?.audio.moveCall(l,n)},muteCaller(l){Oe?.audio.muteCaller(l)},unmuteCaller(l){Oe?.audio.unmuteCaller(l)},setMuteWhenJoin(l){Oe?.audio.setMuteWhenJoin(l)},setDND(l){Oe?.audio.setDND(l)},setCallWaiting(l){Oe?.audio.setCallWaiting(l)},async setMicrophone(l){await Oe?.audio.setMicrophone(l)},async setSpeaker(l){await Oe?.audio.setSpeaker(l)},sendDTMF(l,n){Oe?.audio.sendDTMF(l,n)},async setActiveRoom(l){await Oe?.audio.setActiveRoom(l)},setMicrophoneSensitivity(l){gu.value=l,Oe?.audio.setMicrophoneSensitivity(l)},setSpeakerVolume(l){Tu.value=l,Oe?.audio.setSpeakerVolume(l)},setAutoAnswer(l){r_.value=l,Oe?.audio.setAutoAnswer(l)},setMetricsConfig(l){Oe?.audio.setMetricsConfig(l)},msrpAnswer(l){Oe?.msrp.msrpAnswer(l)},messageTerminate(l){Oe?.msrp.messageTerminate(l)},sendMSRP(l,n){Oe?.msrp.sendMSRP(l,n)},initMSRP(l,n,s){Oe?.msrp.initMSRP(l,n,s)}}},a_=Symbol();function Wy(){return Ce.provide(a_,zt),zt}function Yy(){const l=Ce.inject(a_);if(!l)throw new Error("useVsipInject() is called without provider, please call useVsipProvide() first");return l}dn.useVsipInject=Yy,dn.useVsipProvide=Wy,dn.vsipAPI=zt,Object.defineProperty(dn,Symbol.toStringTag,{value:"Module"})});
158
+ `,s),a===-1)return a;!l.substring(a+2,a+4).match(/(^\r\n)/)&&l.charAt(a+2).match(/(^\s+)/)?s=a+2:i=a}return i}function dv(l,n,s,i){let a;const e=n.indexOf(":",s),d=n.substring(s,e).trim(),_=n.substring(e+1,i).trim();switch(d.toLowerCase()){case"via":case"v":l.addHeader("via",_),l.getHeaders("via").length===1?(a=l.parseHeader("Via"),a&&(l.via=a,l.via_branch=a.branch)):a=0;break;case"from":case"f":l.setHeader("from",_),a=l.parseHeader("from"),a&&(l.from=a,l.from_tag=a.getParam("tag"));break;case"to":case"t":l.setHeader("to",_),a=l.parseHeader("to"),a&&(l.to=a,l.to_tag=a.getParam("tag"));break;case"record-route":if(a=su.parse(_,"Record_Route"),a===-1)a=void 0;else for(const u of a)l.addHeader("record-route",_.substring(u.possition,u.offset)),l.headers["Record-Route"][l.getHeaders("record-route").length-1].parsed=u.parsed;break;case"call-id":case"i":l.setHeader("call-id",_),a=l.parseHeader("call-id"),a&&(l.call_id=_);break;case"contact":case"m":if(a=su.parse(_,"Contact"),a===-1)a=void 0;else for(const u of a)l.addHeader("contact",_.substring(u.possition,u.offset)),l.headers.Contact[l.getHeaders("contact").length-1].parsed=u.parsed;break;case"content-length":case"l":l.setHeader("content-length",_),a=l.parseHeader("content-length");break;case"content-type":case"c":l.setHeader("content-type",_),a=l.parseHeader("content-type");break;case"cseq":l.setHeader("cseq",_),a=l.parseHeader("cseq"),a&&(l.cseq=a.value),l instanceof $s.IncomingResponse&&(l.method=a.method);break;case"max-forwards":l.setHeader("max-forwards",_),a=l.parseHeader("max-forwards");break;case"www-authenticate":l.setHeader("www-authenticate",_),a=l.parseHeader("www-authenticate");break;case"proxy-authenticate":l.setHeader("proxy-authenticate",_),a=l.parseHeader("proxy-authenticate");break;case"session-expires":case"x":l.setHeader("session-expires",_),a=l.parseHeader("session-expires"),a&&(l.session_expires=a.expires,l.session_expires_refresher=a.refresher);break;case"refer-to":case"r":l.setHeader("refer-to",_),a=l.parseHeader("refer-to"),a&&(l.refer_to=a);break;case"replaces":l.setHeader("replaces",_),a=l.parseHeader("replaces"),a&&(l.replaces=a);break;case"event":case"o":l.setHeader("event",_),a=l.parseHeader("event"),a&&(l.event=a);break;default:l.addHeader(d,_),a=0}return a===void 0?{error:`error parsing header "${d}"`}:!0}const _v={parseMessage:cv},Nr=new ll("Registrator"),Rl=10;class pv{constructor(n,s){this._reg_id=1,this._ua=n,this._transport=s,this._registrar=n.configuration.registrar_server,this._expires=n.configuration.register_expires,this._call_id=En.createRandomToken(22),this._cseq=0,this._to_uri=n.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const i=this._contact.indexOf(">");if(i!==-1){const a=this._contact.slice(0,i)+this._contact.slice(i+1,this._contact.length);this._contact=a}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(n){Array.isArray(n)||(n=[]),this._extraHeaders=n.slice()}setExtraContactParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const s in n)if(Object.prototype.hasOwnProperty.call(n,s)){const i=n[s];this._extraContactParams+=`;${s}`,i&&(this._extraContactParams+=`=${i}`)}}setExtraContactUriParams(n){n instanceof Object||(n={}),this._extraContactParams="";for(const s in n)if(Object.prototype.hasOwnProperty.call(n,s)){const i=n[s];this._extraContactParams+=`;${s}`,i&&(this._extraContactParams+=`=${i}`)}}register(){if(this._registering){Nr.debug("Register request in progress...");return}const n=this._extraHeaders.slice();n.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),n.push(`Expires: ${this._expires}`);const s=new gt.OutgoingRequest(U.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},n),i=new yr(this._ua,s,{onRequestTimeout:()=>{this._registrationFailure(null,U.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,U.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{if(a.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):{if(this._registering=!1,!a.hasHeader("Contact")){Nr.debug("no Contact header in response to REGISTER, response ignored");break}const e=a.headers.Contact.reduce((g,f)=>g.concat(f.parsed),[]);let d=e.find(g=>this._sipInstance===g.getParam("+sip.instance")&&this._reg_id===parseInt(g.getParam("reg-id")));if(d||(d=e.find(g=>g.uri.user===this._ua.contact.uri.user)),!d){Nr.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let _=d.getParam("expires");!_&&a.hasHeader("expires")&&(_=a.getHeader("expires")),_||(_=this._expires),_=Number(_),_<Rl&&(_=Rl);const u=_>64?_*1e3/2+Math.floor((_/2-32)*1e3*Math.random()):_*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},u),d.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=d.getParam("temp-gruu").replace(/"/g,"")),d.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=d.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:a}));break}case/^423$/.test(a.status_code):{a.hasHeader("min-expires")?(this._expires=Number(a.getHeader("min-expires")),this._expires<Rl&&(this._expires=Rl),this.register()):(Nr.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(a,U.causes.SIP_FAILURE_CODE));break}default:{const e=En.sipErrorCause(a.status_code);this._registrationFailure(a,e)}}}});this._registering=!0,i.send()}unregister(n={}){if(!this._registered){Nr.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const s=this._extraHeaders.slice();n.all?s.push(`Contact: *${this._extraContactParams}`):s.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),s.push("Expires: 0");const i=new gt.OutgoingRequest(U.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},s);new yr(this._ua,i,{onRequestTimeout:()=>{this._unregistered(null,U.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,U.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:a=>{switch(!0){case/^1[0-9]{2}$/.test(a.status_code):break;case/^2[0-9]{2}$/.test(a.status_code):this._unregistered(a);break;default:{const e=En.sipErrorCause(a.status_code);this._unregistered(a,e)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(n,s){this._registering=!1,this._ua.registrationFailed({response:n||null,cause:s}),this._registered&&(this._registered=!1,this._ua.unregistered({response:n||null,cause:s}))}_unregistered(n,s){this._registering=!1,this._registered=!1,this._ua.unregistered({response:n||null,cause:s||null})}}const et=console,zn={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},fv=tv;class mv extends fv{constructor(n){super(n),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this.optionsInterval=null,this.lastOptionsTimestamp=null,this.lastRegisterTimestamp=null,this._registrator=new pv(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(n,s){return super.call(n,s)}joinVideoCall(n,s,i){et.debug("call()");const a=new Cl(this);return a.configureMedia({audio:!0,video:!0}),a.connect(n,s,i),a}startScreenShare(){et.debug("startScreenShare()");for(const n in this._janus_sessions)this._janus_sessions[n].connectScreenShare()}changeMediaConstraints(n){for(const s in this._janus_sessions)this._janus_sessions[s].changeMediaConstraints(n)}startBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].connectBlur()}stopBlur(){for(const n in this._janus_sessions)this._janus_sessions[n].stopBlur()}_loadConfig(n){try{Or.load(this._configuration,n)}catch(e){throw e}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=En.newUUID());let s;typeof window<"u"&&typeof window.document<"u"?s=window?.navigator.userAgent:typeof self<"u"&&self.navigator&&(s=self.navigator.userAgent),s+=" "+Ie.USER_AGENT,this._configuration.user_agent=n.overrideUserAgent&&typeof n.overrideUserAgent=="function"?n.overrideUserAgent(s):s,n.onTransportCallback&&typeof n.onTransportCallback=="function"&&(this.onTransportCallback=n.onTransportCallback),this._configuration.jssip_id=En.createRandomToken(5);const i=this._configuration.uri.clone();i.user=null,this._configuration.hostport_params=i.toString().replace(/^sip:/i,"");try{this._transport=new IT(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=gv.bind(this),this._transport.onconnect=Tv.bind(this),this._transport.ondisconnect=vv.bind(this),this._transport.ondata=yv.bind(this)}catch(e){throw et.warn(e),new Kn.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const e=this._configuration.uri.clone();e.user=null,e.clearParams(),e.clearHeaders(),this._configuration.registrar_server=e}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new ls("sip",En.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(e={}){const d=e.anonymous||null,_=e.outbound||null;let u="<";return d?u+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":u+=this.pub_gruu||this.uri.toString(),_&&(d?!this.temp_gruu:!this.pub_gruu)&&(u+=";ob"),u+=">",u}};const a=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const e in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,e)&&(a.indexOf(e)!==-1?Object.defineProperty(this._configuration,e,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,e,{writable:!1,configurable:!1}));et.debug("configuration parameters after validation:");for(const e in this._configuration)if(Object.prototype.hasOwnProperty.call(Or.settings,e))switch(e){case"uri":case"registrar_server":et.debug(`- ${e}: ${this._configuration[e]}`);break;case"password":case"ha1":case"authorization_jwt":et.debug(`- ${e}: NOT SHOWN`);break;default:et.debug(`- ${e}: ${JSON.stringify(this._configuration[e])}`)}}newMSRPSession(n,s){n.on("msgHistoryUpdate",i=>{console.log(i)}),this._msrp_sessions[n.id]=n,this.emit("newMSRPSession",s)}newJanusSession(n,s){this._janus_sessions[n.id]=n,this.newStreamPlugins.forEach(i=>{i.setSession(n)}),this.processStreamPlugins.forEach(i=>{i.setSession(n)}),this.emit("newJanusSession",s)}kill(){}destroyMSRPSession(n){delete this._msrp_sessions[n.id]}destroyJanusSession(n){delete this._janus_sessions[n.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(n){var s,i,a,e;const d=n.method;if(n.ruri.user!==this._configuration.uri.user&&n.ruri.user!==this._contact.uri.user){et.debug("Request-URI does not point to us"),n.method!==Ie.ACK&&n.reply_sl(404);return}if(n.ruri.scheme===Ie.SIPS){n.reply_sl(416);return}if(jt.checkTransaction(this,n))return;if(d===Ie.INVITE?new jt.InviteServerTransaction(this,this._transport,n):d!==Ie.ACK&&d!==Ie.CANCEL&&new jt.NonInviteServerTransaction(this,this._transport,n),d===Ie.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const g=Date.now(),f=this.lastOptionsTimestamp>g-35e3,T=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>g;f&&T&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){n.reply(200);return}new Ph.Options(this).init_incoming(n)}else if(d===Ie.MESSAGE){if(this.listeners("newMessage").length===0){n.reply(405);return}new Ph.Message(this).init_incoming(n)}else if(d===Ie.INVITE&&!n.to_tag&&this.listeners("newRTCSession").length===0){n.reply(405);return}let _,u;if(n.to_tag)if(_=this._findDialog(n.call_id,n.from_tag,n.to_tag),_)_.receiveRequest(n);else if(d===Ie.NOTIFY)if(u=this._findSession(n),u)u.receiveRequest(n);else{if(n.body)try{const g=JSON.parse(n.body)||{};(i=(s=g.plugindata)==null?void 0:s.data)!=null&&i.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(g),(e=(a=g.plugindata)==null?void 0:a.data)!=null&&e.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(g.plugindata.data.unpublished)}catch(g){console.error(g)}n.reply(200)}else d!==Ie.ACK&&n.reply(481);else switch(d){case Ie.INVITE:if(window.RTCPeerConnection)if(n.hasHeader("replaces")){const g=n.replaces;_=this._findDialog(g.call_id,g.from_tag,g.to_tag),_?(u=_.owner,u.isEnded()?n.reply(603):u.receiveRequest(n)):n.reply(481)}else n.body.search(/MSRP/ig)>-1?(u=new nu(this),u.init_incoming(n)):n.body.search(/JANUS/ig)>-1||(u=new hT(this),u.init_incoming(n));else et.warn("INVITE received but WebRTC is not supported"),n.reply(488);break;case Ie.BYE:n.reply(481);break;case Ie.CANCEL:u=this._findSession(n),u?u.receiveRequest(n):et.debug("received CANCEL request for a non existent session");break;case Ie.ACK:break;case Ie.NOTIFY:this.emit("sipEvent",{event:n.event,request:n}),n.reply(200);break;default:n.reply(405);break}}startMSRP(n,s){et.debug("startMSRP()",s);const i=new nu(this);return i.connect(n),i}startJanus(n,s){et.debug("startJanus()",s);const i=new nu(this);return i.connect(n),i}terminateMSRPSessions(n){et.debug("terminateSessions()");for(const s in this._msrp_sessions)this._msrp_sessions[s].isEnded()||this._msrp_sessions[s].terminate(n)}terminateJanusSessions(n){et.debug("terminateSessions()");for(const s in this._janus_sessions)this._janus_sessions[s].isEnded()||this._janus_sessions[s].terminate(n)}enableJanusAudio(n){et.debug("enableJanusAudio()");for(const s in this._janus_sessions)this._janus_sessions[s].isEnded()||(n?this._janus_sessions[s].startAudio():this._janus_sessions[s].stopAudio())}enableJanusVideo(n){et.debug("enableJanusVideo()");for(const s in this._janus_sessions)this._janus_sessions[s].isEnded()||(n?this._janus_sessions[s].startVideo():this._janus_sessions[s].stopVideo())}terminateAllSessions(){for(const n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){et.debug(`closing session ${n}`);try{this._sessions[n].terminate()}catch(s){console.error(s)}}}stop(n=!0){if(et.debug("stop()"),this._dynConfiguration={},this._status===zn.STATUS_USER_CLOSED){et.debug("UA already closed");return}this._registrator.close();const s=Object.keys(this._sessions).length;n&&this.terminateAllSessions();for(const i in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,i)){et.debug(`closing session ${i}`);try{this._msrp_sessions[i].terminate()}catch(a){console.error(a)}}for(const i in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,i)){et.debug(`closing session ${i}`);try{this._janus_sessions[i].terminate()}catch(a){console.error(a)}}for(const i in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,i))try{this._applicants[i].close()}catch(a){console.error(a)}this._status=zn.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&s===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}}function gv(l){this.emit("connecting",l)}function Tv(l){this._status!==zn.STATUS_USER_CLOSED&&(this._status=zn.STATUS_READY,this._error=null,this.emit("connected",l),this._dynConfiguration.register&&this._registrator.register())}function vv(l){const n=["nict","ict","nist","ist"];for(const s of n)for(const i in this._transactions[s])Object.prototype.hasOwnProperty.call(this._transactions[s],i)&&this._transactions[s][i].onTransportError();this.emit("disconnected",l),this._registrator.onTransportClosed(),this._status!==zn.STATUS_USER_CLOSED&&(this._status=zn.STATUS_NOT_READY,this._error=zn.NETWORK_ERROR)}function yv(l){const n=l.transport;let s=l.message;const i=s;if(s=_v.parseMessage(s,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(s,i),!!s&&!(this._status===zn.STATUS_USER_CLOSED&&s instanceof $s.IncomingRequest)&&$T(s,this,n)){if(s instanceof $s.IncomingRequest)s.transport=n,this.receiveRequest(s);else if(s instanceof $s.IncomingResponse){let a;switch(s.method){case Ie.INVITE:a=this._transactions.ict[s.via_branch],a&&a.receiveResponse(s);break;case Ie.ACK:break;default:a=this._transactions.nict[s.via_branch],a&&a.receiveResponse(s);break}}}}const Ev=["roomId","_audioMuted","_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","_localHold","_videoMuted","status","start_time","_remote_identity","audioTag","isOnHold","localMuted","autoAnswer","putOnHoldTimestamp"],Sv=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function Dd(l){const n={};return Ev.forEach(s=>{l[s]!==void 0&&(n[s]=l[s])}),n.localHold=l._localHold,n}function kd(l){const n={};return Sv.forEach(s=>{l[s]!==void 0&&(n[s]=l[s])}),n}async function ru(l,n,s){const i=l.createMediaStreamSource(n),a=l.createMediaStreamDestination(),e=l.createGain();return i.connect(e),e.connect(a),e.gain.value=s,a.stream}function Av(l,n,s,i){if(Ud())return;const a=document.createElement("audio");a.id=n._id,a.className="audioTag",a.srcObject=l,a.setSinkId(s),a.volume=i,a.play(),n.audioTag=a}function Cv(l){if(l&&typeof l.log=="function"&&typeof l.warn=="function"&&typeof l.error=="function")return!0}function Ud(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const bv=ot,Rv=Bt(),It=new bv("WebSocketInterface");var Iv=class{constructor(l){It.debug('new() [url:"%s"]',l),this._url=l,this._sip_uri=null,this._via_transport=null,this._ws=null;const n=Rv.parse(l,"absoluteURI");if(n===-1)throw It.warn(`invalid WebSocket URI: ${l}`),new TypeError(`Invalid argument: ${l}`);if(n.scheme!=="wss"&&n.scheme!=="ws")throw It.warn(`invalid WebSocket URI scheme: ${n.scheme}`),new TypeError(`Invalid argument: ${l}`);this._sip_uri=`sip:${n.host}${n.port?`:${n.port}`:""};transport=ws`,this._via_transport=n.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(l){this._via_transport=l.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(It.debug("connect()"),this.isConnected()){It.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){It.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),It.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(l){this._onError(l)}}disconnect(){It.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(l){return It.debug("send()"),this.isConnected()?(this._ws.send(l),!0):(It.warn("unable to send message, WebSocket is not open"),!1)}isConnected(){return this._ws&&this._ws.readyState===this._ws.OPEN}isConnecting(){return this._ws&&this._ws.readyState===this._ws.CONNECTING}_onOpen(){It.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:l,code:n,reason:s}){It.debug(`WebSocket ${this._url} closed`),l===!1&&It.debug("WebSocket abrupt disconnection"),this.ondisconnect(!l,n,s)}_onMessage({data:l}){It.debug("received WebSocket message"),this.ondata(l)}_onError(l){It.warn(`WebSocket ${this._url} error: `,l)}};const iu=So,wv=Ie,Ov=yn,Nv=ft(),Dv=wd,kv=gn(),Uv=ba(),Mv=Bt(),Pv=Iv;xs("JsSIP")("version %s",iu.version);var xv={C:wv,Exceptions:Ov,Utils:Nv,UA:Dv,URI:kv,NameAddrHeader:Uv,WebSocketInterface:Pv,Grammar:Mv,debug:xs,get name(){return iu.title},get version(){return iu.version}};const Lv=We(xv);function ou(l){return l<10?`0${l}`:`${l}`}function Hv(l){let n=l.hours||0,s=l.minutes||0,i=l.seconds||0;i++,i===60&&(i=0,s++,s===60&&(s=0,n++));const a=`${ou(n)}:${ou(s)}:${ou(i)}`;return{seconds:i,minutes:s,hours:n,formatted:a}}function qv(l){let n=0;for(let s=0;s<l.length;s++)n+=l[s]*l[s];return Math.sqrt(n/l.length)}async function Fv(l,n,s=150){const i=n.createMediaStreamSource(l),a=n.createDelay();a.delayTime.value=s/1e3;const e=n.createGain();e.gain.value=0;const d=n.createMediaStreamDestination();return i.connect(a).connect(e).connect(d),{stream:d.stream,setSpeaking:_=>{e.gain.value=_?1:0}}}var Et={};Et.forEach=async(l,n,s)=>{const i=[];for(let a=0;a<l.length;a++)if(a in l){const e=Promise.resolve(l[a]).then(d=>n.call(s||globalThis,d,a,l));i.push(e)}await Promise.all(i)},Et.forEachSeries=async(l,n,s)=>{for(let i=0;i<l.length;i++)i in l&&await n.call(s||globalThis,await l[i],i,l)},Et.map=async(l,n,s)=>{const i=[];for(let a=0;a<l.length;a++)a in l&&(i[a]=Promise.resolve(l[a]).then(e=>n.call(s||globalThis,e,a,l)));return Promise.all(i)},Et.mapSeries=async(l,n,s)=>{const i=[];for(let a=0;a<l.length;a++)a in l&&(i[a]=await n.call(s||globalThis,await l[a],a,l));return i},Et.find=(l,n,s)=>new Promise((i,a)=>{if(l.length===0)return i();let e=1;for(let d=0;d<l.length;d++){const _=u=>{u?i(l[d]):e===l.length&&i(),e++};Promise.resolve(l[d]).then(u=>n.call(s||globalThis,u,d,l)).then(_).catch(a)}}),Et.findSeries=async(l,n,s)=>{for(let i=0;i<l.length;i++)if(await n.call(s||globalThis,await l[i],i,l))return l[i]},Et.findIndex=(l,n,s)=>new Promise((i,a)=>{if(l.length===0)return i(-1);let e=1;for(let d=0;d<l.length;d++){const _=u=>{u?i(d):e===l.length&&i(-1),e++};Promise.resolve(l[d]).then(u=>n.call(s||globalThis,u,d,l)).then(_).catch(a)}}),Et.findIndexSeries=async(l,n,s)=>{for(let i=0;i<l.length;i++)if(await n.call(s||globalThis,await l[i],i,l))return i},Et.some=(l,n,s)=>new Promise((i,a)=>{if(l.length===0)return i(!1);let e=1;for(let d=0;d<l.length;d++){if(!(d in l)){e++;continue}const _=u=>{u?i(!0):e===l.length&&i(!1),e++};Promise.resolve(l[d]).then(u=>n.call(s||globalThis,u,d,l)).then(_).catch(a)}}),Et.someSeries=async(l,n,s)=>{for(let i=0;i<l.length;i++)if(i in l&&await n.call(s||globalThis,await l[i],i,l))return!0;return!1},Et.every=(l,n,s)=>new Promise((i,a)=>{if(l.length===0)return i(!0);let e=1;for(let d=0;d<l.length;d++){if(!(d in l)){e++;continue}const _=u=>{u?e===l.length&&i(!0):i(!1),e++};Promise.resolve(l[d]).then(u=>n.call(s||globalThis,u,d,l)).then(_).catch(a)}}),Et.everySeries=async(l,n,s)=>{for(let i=0;i<l.length;i++)if(i in l&&!await n.call(s||globalThis,await l[i],i,l))return!1;return!0},Et.filter=(l,n,s)=>new Promise(async(i,a)=>{const e=[];for(let _=0;_<l.length;_++)_ in l&&(e[_]=Promise.resolve(l[_]).then(u=>n.call(s||globalThis,u,_,l)).catch(a));const d=[];for(let _=0;_<e.length;_++)await e[_]&&d.push(await l[_]);i(d)}),Et.filterSeries=async(l,n,s)=>{const i=[];for(let a=0;a<l.length;a++)a in l&&await n.call(s||globalThis,await l[a],a,l)&&i.push(await l[a]);return i},Et.reduce=async(l,n,s)=>{if(l.length===0&&s===void 0)throw TypeError("Reduce of empty array with no initial value");let i,a;for(s!==void 0?(a=s,i=0):(a=l[0],i=1),i;i<l.length;i++)i in l&&(a=await n(await a,await l[i],i,l));return a};var Md={};(function(l){const n=Et;Object.keys(n).forEach(s=>{const i=s.charAt(0).toUpperCase()+s.slice(1);l[`async${i}`]=async function(...a){return n[s](this,...a)}})})(Md);var jv=Object.assign(Et,{instanceMethods:Md});const Wt={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var $v={exports:{}};(function(l){var n=function(s){var i=Object.prototype,a=i.hasOwnProperty,e=Object.defineProperty||function(Q,V,k){Q[V]=k.value},d,_=typeof Symbol=="function"?Symbol:{},u=_.iterator||"@@iterator",g=_.asyncIterator||"@@asyncIterator",f=_.toStringTag||"@@toStringTag";function T(Q,V,k){return Object.defineProperty(Q,V,{value:k,enumerable:!0,configurable:!0,writable:!0}),Q[V]}try{T({},"")}catch{T=function(Q,V,k){return Q[V]=k}}function y(Q,V,k,ve){var _e=V&&V.prototype instanceof me?V:me,Ae=Object.create(_e.prototype),Ue=new X(ve||[]);return e(Ae,"_invoke",{value:P(Q,k,Ue)}),Ae}s.wrap=y;function A(Q,V,k){try{return{type:"normal",arg:Q.call(V,k)}}catch(ve){return{type:"throw",arg:ve}}}var w="suspendedStart",b="suspendedYield",R="executing",G="completed",x={};function me(){}function O(){}function $(){}var de={};T(de,u,function(){return this});var fe=Object.getPrototypeOf,N=fe&&fe(fe(te([])));N&&N!==i&&a.call(N,u)&&(de=N);var H=$.prototype=me.prototype=Object.create(de);O.prototype=$,e(H,"constructor",{value:$,configurable:!0}),e($,"constructor",{value:O,configurable:!0}),O.displayName=T($,f,"GeneratorFunction");function j(Q){["next","throw","return"].forEach(function(V){T(Q,V,function(k){return this._invoke(V,k)})})}s.isGeneratorFunction=function(Q){var V=typeof Q=="function"&&Q.constructor;return V?V===O||(V.displayName||V.name)==="GeneratorFunction":!1},s.mark=function(Q){return Object.setPrototypeOf?Object.setPrototypeOf(Q,$):(Q.__proto__=$,T(Q,f,"GeneratorFunction")),Q.prototype=Object.create(H),Q},s.awrap=function(Q){return{__await:Q}};function F(Q,V){function k(Ae,Ue,ce,re){var Ge=A(Q[Ae],Q,Ue);if(Ge.type==="throw")re(Ge.arg);else{var tt=Ge.arg,ge=tt.value;return ge&&typeof ge=="object"&&a.call(ge,"__await")?V.resolve(ge.__await).then(function(pe){k("next",pe,ce,re)},function(pe){k("throw",pe,ce,re)}):V.resolve(ge).then(function(pe){tt.value=pe,ce(tt)},function(pe){return k("throw",pe,ce,re)})}}var ve;function _e(Ae,Ue){function ce(){return new V(function(re,Ge){k(Ae,Ue,re,Ge)})}return ve=ve?ve.then(ce,ce):ce()}e(this,"_invoke",{value:_e})}j(F.prototype),T(F.prototype,g,function(){return this}),s.AsyncIterator=F,s.async=function(Q,V,k,ve,_e){_e===void 0&&(_e=Promise);var Ae=new F(y(Q,V,k,ve),_e);return s.isGeneratorFunction(V)?Ae:Ae.next().then(function(Ue){return Ue.done?Ue.value:Ae.next()})};function P(Q,V,k){var ve=w;return function(_e,Ae){if(ve===R)throw new Error("Generator is already running");if(ve===G){if(_e==="throw")throw Ae;return Ke()}for(k.method=_e,k.arg=Ae;;){var Ue=k.delegate;if(Ue){var ce=W(Ue,k);if(ce){if(ce===x)continue;return ce}}if(k.method==="next")k.sent=k._sent=k.arg;else if(k.method==="throw"){if(ve===w)throw ve=G,k.arg;k.dispatchException(k.arg)}else k.method==="return"&&k.abrupt("return",k.arg);ve=R;var re=A(Q,V,k);if(re.type==="normal"){if(ve=k.done?G:b,re.arg===x)continue;return{value:re.arg,done:k.done}}else re.type==="throw"&&(ve=G,k.method="throw",k.arg=re.arg)}}}function W(Q,V){var k=V.method,ve=Q.iterator[k];if(ve===d)return V.delegate=null,k==="throw"&&Q.iterator.return&&(V.method="return",V.arg=d,W(Q,V),V.method==="throw")||k!=="return"&&(V.method="throw",V.arg=new TypeError("The iterator does not provide a '"+k+"' method")),x;var _e=A(ve,Q.iterator,V.arg);if(_e.type==="throw")return V.method="throw",V.arg=_e.arg,V.delegate=null,x;var Ae=_e.arg;if(!Ae)return V.method="throw",V.arg=new TypeError("iterator result is not an object"),V.delegate=null,x;if(Ae.done)V[Q.resultName]=Ae.value,V.next=Q.nextLoc,V.method!=="return"&&(V.method="next",V.arg=d);else return Ae;return V.delegate=null,x}j(H),T(H,f,"Generator"),T(H,u,function(){return this}),T(H,"toString",function(){return"[object Generator]"});function ee(Q){var V={tryLoc:Q[0]};1 in Q&&(V.catchLoc=Q[1]),2 in Q&&(V.finallyLoc=Q[2],V.afterLoc=Q[3]),this.tryEntries.push(V)}function I(Q){var V=Q.completion||{};V.type="normal",delete V.arg,Q.completion=V}function X(Q){this.tryEntries=[{tryLoc:"root"}],Q.forEach(ee,this),this.reset(!0)}s.keys=function(Q){var V=Object(Q),k=[];for(var ve in V)k.push(ve);return k.reverse(),function _e(){for(;k.length;){var Ae=k.pop();if(Ae in V)return _e.value=Ae,_e.done=!1,_e}return _e.done=!0,_e}};function te(Q){if(Q){var V=Q[u];if(V)return V.call(Q);if(typeof Q.next=="function")return Q;if(!isNaN(Q.length)){var k=-1,ve=function _e(){for(;++k<Q.length;)if(a.call(Q,k))return _e.value=Q[k],_e.done=!1,_e;return _e.value=d,_e.done=!0,_e};return ve.next=ve}}return{next:Ke}}s.values=te;function Ke(){return{value:d,done:!0}}return X.prototype={constructor:X,reset:function(Q){if(this.prev=0,this.next=0,this.sent=this._sent=d,this.done=!1,this.delegate=null,this.method="next",this.arg=d,this.tryEntries.forEach(I),!Q)for(var V in this)V.charAt(0)==="t"&&a.call(this,V)&&!isNaN(+V.slice(1))&&(this[V]=d)},stop:function(){this.done=!0;var Q=this.tryEntries[0],V=Q.completion;if(V.type==="throw")throw V.arg;return this.rval},dispatchException:function(Q){if(this.done)throw Q;var V=this;function k(re,Ge){return Ae.type="throw",Ae.arg=Q,V.next=re,Ge&&(V.method="next",V.arg=d),!!Ge}for(var ve=this.tryEntries.length-1;ve>=0;--ve){var _e=this.tryEntries[ve],Ae=_e.completion;if(_e.tryLoc==="root")return k("end");if(_e.tryLoc<=this.prev){var Ue=a.call(_e,"catchLoc"),ce=a.call(_e,"finallyLoc");if(Ue&&ce){if(this.prev<_e.catchLoc)return k(_e.catchLoc,!0);if(this.prev<_e.finallyLoc)return k(_e.finallyLoc)}else if(Ue){if(this.prev<_e.catchLoc)return k(_e.catchLoc,!0)}else if(ce){if(this.prev<_e.finallyLoc)return k(_e.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Q,V){for(var k=this.tryEntries.length-1;k>=0;--k){var ve=this.tryEntries[k];if(ve.tryLoc<=this.prev&&a.call(ve,"finallyLoc")&&this.prev<ve.finallyLoc){var _e=ve;break}}_e&&(Q==="break"||Q==="continue")&&_e.tryLoc<=V&&V<=_e.finallyLoc&&(_e=null);var Ae=_e?_e.completion:{};return Ae.type=Q,Ae.arg=V,_e?(this.method="next",this.next=_e.finallyLoc,x):this.complete(Ae)},complete:function(Q,V){if(Q.type==="throw")throw Q.arg;return Q.type==="break"||Q.type==="continue"?this.next=Q.arg:Q.type==="return"?(this.rval=this.arg=Q.arg,this.method="return",this.next="end"):Q.type==="normal"&&V&&(this.next=V),x},finish:function(Q){for(var V=this.tryEntries.length-1;V>=0;--V){var k=this.tryEntries[V];if(k.finallyLoc===Q)return this.complete(k.completion,k.afterLoc),I(k),x}},catch:function(Q){for(var V=this.tryEntries.length-1;V>=0;--V){var k=this.tryEntries[V];if(k.tryLoc===Q){var ve=k.completion;if(ve.type==="throw"){var _e=ve.arg;I(k)}return _e}}throw new Error("illegal catch attempt")},delegateYield:function(Q,V,k){return this.delegate={iterator:te(Q),resultName:V,nextLoc:k},this.method==="next"&&(this.arg=d),x}},s}(l.exports);try{regeneratorRuntime=n}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=n:Function("r","regeneratorRuntime = r")(n)}})($v);var Pd={exports:{}};(function(l){(function(n,s){l.exports?l.exports=s():n.log=s()})(__,function(){var n=function(){},s="undefined",i=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),a=["trace","debug","info","warn","error"];function e(b,R){var G=b[R];if(typeof G.bind=="function")return G.bind(b);try{return Function.prototype.bind.call(G,b)}catch{return function(){return Function.prototype.apply.apply(G,[b,arguments])}}}function d(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function _(b){return b==="debug"&&(b="log"),typeof console===s?!1:b==="trace"&&i?d:console[b]!==void 0?e(console,b):console.log!==void 0?e(console,"log"):n}function u(b,R){for(var G=0;G<a.length;G++){var x=a[G];this[x]=G<b?n:this.methodFactory(x,b,R)}this.log=this.debug}function g(b,R,G){return function(){typeof console!==s&&(u.call(this,R,G),this[b].apply(this,arguments))}}function f(b,R,G){return _(b)||g.apply(this,arguments)}function T(b,R,G){var x=this,me;R=R??"WARN";var O="loglevel";typeof b=="string"?O+=":"+b:typeof b=="symbol"&&(O=void 0);function $(H){var j=(a[H]||"silent").toUpperCase();if(!(typeof window===s||!O)){try{window.localStorage[O]=j;return}catch{}try{window.document.cookie=encodeURIComponent(O)+"="+j+";"}catch{}}}function de(){var H;if(!(typeof window===s||!O)){try{H=window.localStorage[O]}catch{}if(typeof H===s)try{var j=window.document.cookie,F=j.indexOf(encodeURIComponent(O)+"=");F!==-1&&(H=/^([^;]+)/.exec(j.slice(F))[1])}catch{}return x.levels[H]===void 0&&(H=void 0),H}}function fe(){if(!(typeof window===s||!O)){try{window.localStorage.removeItem(O);return}catch{}try{window.document.cookie=encodeURIComponent(O)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}x.name=b,x.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},x.methodFactory=G||f,x.getLevel=function(){return me},x.setLevel=function(H,j){if(typeof H=="string"&&x.levels[H.toUpperCase()]!==void 0&&(H=x.levels[H.toUpperCase()]),typeof H=="number"&&H>=0&&H<=x.levels.SILENT){if(me=H,j!==!1&&$(H),u.call(x,H,b),typeof console===s&&H<x.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+H},x.setDefaultLevel=function(H){R=H,de()||x.setLevel(H,!1)},x.resetLevel=function(){x.setLevel(R,!1),fe()},x.enableAll=function(H){x.setLevel(x.levels.TRACE,H)},x.disableAll=function(H){x.setLevel(x.levels.SILENT,H)};var N=de();N==null&&(N=R),x.setLevel(N,!1)}var y=new T,A={};y.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var R=A[b];return R||(R=A[b]=new T(b,y.getLevel(),y.methodFactory)),R};var w=typeof window!==s?window.log:void 0;return y.noConflict=function(){return typeof window!==s&&window.log===y&&(window.log=w),y},y.getLoggers=function(){return A},y.default=y,y})})(Pd);var Ct=Pd.exports;const Sn=()=>`${new Date().toISOString()} | metrics`,An=(l,n,s)=>`${l} | ${n} | ${s}`;Ct.setDefaultLevel(Ct.levels.TRACE);const Vv=l=>{Ct.info(An(Sn(),"log ",`set log level to ${l?"verbose":"info"}`)),Ct.setLevel(l?Ct.levels.TRACE:Ct.levels.INFO)},Bv=l=>{const n=[...Object.keys(Ct.levels)];n.includes(l)?(Ct.info(An(Sn(),"log ",`update log level to ${l.toLowerCase()}`)),Ct.setLevel(l)):Ct.warn(An(Sn(),"log ","Incorrect log level please choose one of "),n)},Ne=(l,n,s)=>{s?Ct.debug(An(Sn(),l,n),s):Ct.debug(An(Sn(),l,n))},lu=(l,n)=>{Ct.info(An(Sn(),l,n))},as=(l,n)=>{Ct.info(An(Sn(),l,n))},Il=(l,n)=>{Ct.warn(An(Sn(),l,n))},Ws=(l,n)=>{Ct.error(An(Sn(),l,n))};function Kv(l){return Math.floor(Math.random()*l).toString()}function xd(l,n){let s=n;return l.forEach(i=>{s=s.replace(i,"")}),s}function Gv(l,n){let s="";for(let i=0;i<n;i+=1)s+=l[Kv(l.length)];return s}function Wv({length:l=20,useLetters:n=!0,useNumbers:s=!0,includeSymbols:i=[],excludeSymbols:a=[]}={}){let e="abcdefghijklmnopqrstuvwxyz",d="0123456789",_=[],u=[],g=[];return n&&(a.length&&(e=xd(a,e)),u=e.split("")),s&&(a.length&&(d=xd(a,d)),g=d.split("")),_=[...u,...g,...i],Gv(_,l)}var Yv=Wv;const Dr=We(Yv),zv=()=>"WebRTCMetrics",Jv=()=>"5.0.3",Pe={INBOUND:"inbound",OUTBOUND:"outbound"},Cn={IDLE:"idle",RUNNING:"running",MUTED:"muted"},kr={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},Xv=()=>({delta_time_to_measure_probes_ms:0,delta_time_consumed_to_measure_ms:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,total_time_decoded_in:0,total_time_encoded_out:0,probes:[]}),Ld={level_in:0,codec_id_in:"",codec_in:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,mos_in:0,mos_emodel_in:0,ssrc:"",direction:Pe.INBOUND},Hd={level_out:0,codec_id_out:"",codec_out:{mime_type:null,clock_rate:null,sdp_fmtp_line:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,timestamp_out:null,mos_out:0,mos_emodel_out:0,ssrc:"",direction:Pe.OUTBOUND},qd={codec_id_in:"",size_in:{width:null,height:null,framerate:null},codec_in:{mime_type:null,clock_rate:null},delta_jitter_ms_in:0,percent_packets_lost_in:0,delta_packets_in:0,delta_packets_lost_in:0,total_packets_in:0,total_packets_lost_in:0,total_KBytes_in:0,delta_KBytes_in:0,delta_kbs_in:0,decoder_in:null,delta_ms_decode_frame_in:0,total_frames_decoded_in:0,total_time_decoded_in:0,delta_nack_sent_in:0,delta_pli_sent_in:0,total_nack_sent_in:0,total_pli_sent_in:0,ssrc:"",direction:Pe.INBOUND},Fd={codec_id_out:"",size_out:{width:null,height:null,framerate:null},codec_out:{mime_type:null,clock_rate:null},delta_jitter_ms_out:0,delta_rtt_ms_out:null,total_rtt_ms_out:0,total_rtt_measure_out:0,percent_packets_lost_out:0,delta_packets_out:0,delta_packets_lost_out:0,total_packets_out:0,total_packets_lost_out:0,total_KBytes_out:0,delta_KBytes_out:0,delta_kbs_out:0,encoder_out:null,delta_ms_encode_frame_out:0,total_time_encoded_out:0,total_frames_encoded_out:0,delta_nack_received_out:0,delta_pli_received_out:0,total_nack_received_out:0,total_pli_received_out:0,limitation_out:{reason:null,durations:null,resolutionChanges:0},timestamp_out:null,ssrc:"",direction:Pe.OUTBOUND},Qv=l=>{const n={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(l){const s={...l,audio:{},video:{},data:{...l.data},network:{...l.network},experimental:{...l.experimental}};return Object.keys(l.audio).forEach(i=>{s.audio[i]={...l.audio[i]}}),Object.keys(l.video).forEach(i=>{s.video[i]={...l.video[i]}}),s}return{...n,audio:{},video:{},data:{...n.data},network:{...n.network},experimental:{...n.experimental}}},Zv={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${Dr()}`,cid:`c-${Dr()}`,uid:`u-${Dr()}`,record:!1,ticket:!0},Yt={CANDIDATE_PAIR:"candidate-pair",CODEC:"codec",INBOUND_RTP:"inbound-rtp",LOCAL_CANDIDATE:"local-candidate",MEDIA_SOURCE:"media-source",OUTBOUND_RTP:"outbound-rtp",REMOTE_CANDIDATE:"remote-candidate",REMOTE_INBOUND_RTP:"remote-inbound-rtp",TRACK:"track"},q={AUDIO_LEVEL:"audioLevel",AVAILABLE_OUTGOING_BITRATE:"availableOutgoingBitrate",AVAILABLE_INCOMING_BITRATE:"availableIncomingBitrate",BYTES_RECEIVED:"bytesReceived",BYTES_SENT:"bytesSent",CANDIDATE_TYPE:"candidateType",CHANNELS:"channels",CLOCK_RATE:"clockRate",CODEC_ID:"codecId",CURRENT_ROUND_TRIP_TIME:"currentRoundTripTime",ROUND_TRIP_TIME:"roundTripTime",FRACTION_LOST:"fractionLost",FRAME_HEIGHT:"frameHeight",FRAME_WIDTH:"frameWidth",QUALITY_LIMITATION_REASON:"qualityLimitationReason",QUALITY_LIMITATION_DURATIONS:"qualityLimitationDurations",QUALITY_LIMITATION_RESOLUTION_CHANGES:"qualityLimitationResolutionChanges",ID:"id",JITTER:"jitter",KIND:"kind",MEDIA_TYPE:"mediaType",MIME_TYPE:"mimeType",LOCAL_CANDIDATE_ID:"localCandidateId",NETWORK_TYPE:"networkType",RELAY_PROTOCOL:"relayProtocol",NOMINATED:"nominated",PACKETS_LOST:"packetsLost",PACKETS_RECEIVED:"packetsReceived",PACKETS_SENT:"packetsSent",PROTOCOL:"protocol",PORT:"port",REMOTE_CANDIDATE_ID:"remoteCandidateId",REMOTE_SOURCE:"remoteSource",RESPONSES_RECEIVED:"responsesReceived",SDP_FMTP_LINE:"sdpFmtpLine",SSRC:"ssrc",SELECTED:"selected",STATE:"state",TIMESTAMP:"timestamp",TOTAL_ROUND_TRIP_TIME:"totalRoundTripTime",TOTAL_ROUND_TRIP_TIME_MEASUREMENTS:"roundTripTimeMeasurements",TYPE:"type",DECODER_IMPLEMENTATION:"decoderImplementation",ENCODER_IMPLEMENTATION:"encoderImplementation",FRAMES_DECODED:"framesDecoded",FRAMES_ENCODED:"framesEncoded",FRAMES_PER_SECOND:"framesPerSecond",TOTAL_DECODE_TIME:"totalDecodeTime",TOTAL_ENCODE_TIME:"totalEncodeTime",PLI:"pliCount",NACK:"nackCount"},D={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},Ur={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},au={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},se={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},uu="config ",ey=(l,n={},s)=>{const i={...s,...n};return n.pname||Il(uu,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${s.pname}'`),n.cid||Il(uu,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${s.cid}'`),n.uid||Il(uu,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${s.uid}'`),i.pc=l,i},ty=(l={})=>{const n={...Zv,...l};return n.name=zv(),n.version=Jv(),n},Mr=(l,n,s,i=!1,a)=>{let e=l.map(d=>{if(!s)return d[n];if(!a)return d[n][s];const _=d[n][a];return _?_[s]:null});return e=e.filter(d=>i?Number.isFinite(d)&&d>0:Number.isFinite(d)),e.length===0?[]:e},Jn=l=>l.reduce((n,s)=>n+s,0)/l.length,ny=()=>`probe-${Dr()}`,sy=()=>`coltr-${Dr()}`,jd=l=>new Promise(n=>setTimeout(n,l)),cu=(l,n,s)=>{n?l.call(n,s):l(s)},Ye=(l,n,s,i)=>{const a=Mr(l,n,s,!0,i);if(a.length===0)return null;const e=a.reduce((d,_)=>d+_,0)/a.length;return e===0?null:a.map(d=>Math.abs(e-d)).reduce((d,_)=>d+_,0)/a.length*100/e},Xe=(l,n,s,i=!1,a)=>{const e=Mr(l,n,s,i,a);return e.length===0?null:e.reduce((d,_)=>d+_,0)/e.length},us=(l,n,s)=>Mr(l,n,s).reduce((i,a)=>i+a,0),ze=(l,n,s,i)=>{const a=Mr(l,n,s,!0,i);return a.length===0?null:Math.min(...a)},Je=(l,n,s,i)=>{const a=Mr(l,n,s,!1,i);return a.length===0?null:Math.max(...a)},St=(l,n,s,i)=>{const a=l.slice().pop();if(!a)return null;if(!s)return a[n];if(!i)return a[n][s];const e=a[n][i];return e?e[s]:null},ry=l=>l.slice().pop(),ht=(l,n,s)=>{if(!n)return null;const i={};let a=n[D.AUDIO][l];a||(a=s===Pe.INBOUND?{...Ld}:{...Hd}),i[D.AUDIO]=a;let e=n[D.VIDEO][l];return e||(e=s===Pe.INBOUND?{...qd}:{...Fd}),i[D.VIDEO]=e,i},Pr="exporter ",iy="2.0",$d=(l,n,s)=>{if(!l||l.length===0)return 0;const i=l[l.length-1];if(!i)return 0;const a=i[n][s];if(a){const e=a.total_rtt_ms_out,d=a.total_rtt_measure_out;return!d||!e?Xe(l,n,"delta_rtt_ms_out",!1,s):Number(e/d)}return null},oy=(l,n)=>{if(!l||l.length===0)return 0;const s=l[l.length-1];if(!s)return 0;const i=s[n].total_rtt_connectivity_ms,a=s[n].total_rtt_connectivity_measure;return!a||!i?Xe(l,n,"delta_rtt_connectivity_ms"):Number(i/a)},ly=l=>St(l,"network","local_candidate_type")!=="relay"?`direct/${St(l,"network","local_candidate_protocol")}`:`turn/${St(l,"network","local_candidate_relay_protocol")}`,ay=l=>{const n=St(l,"network","remote_candidate_type"),s=St(l,"network","remote_candidate_protocol");return n!=="relay"?`direct/${s}`:`turn/${s}`};class uy{constructor(n){this._start=null,this._end=null,this._cfg=n,this._referenceReport=null,this._reports=[],this._events=[]}start(){lu(Pr,"start() - start exporter...");const n=new Date;return this._start=n.toJSON(),n}stop(){lu(Pr,"stop() - stop exporter...");const n=new Date;return this._end=n.toJSON(),n}saveReferenceReport(n){this._referenceReport=n}getReferenceReport(){return this._referenceReport}addReport(n){this._cfg.ticket&&(Ne(Pr,`addReport() - add report to exporter at ${n.timestamp}`),this._reports.push(n))}addCustomEvent(n){this._events.push(n)}reset(){lu(Pr,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Ne(Pr,"ticket() - generate ticket");const n=St(this._reports,"audio","total_packets_lost_in"),s=St(this._reports,"audio","total_packets_in"),i=St(this._reports,"video","total_packets_lost_in"),a=St(this._reports,"video","total_packets_in"),e={},d=ry(this._reports);return d&&(Object.keys(d[D.AUDIO]).forEach(_=>{const u=d[D.AUDIO][_];if(e[u.ssrc]={type:D.AUDIO,direction:u.direction},u.direction===Pe.INBOUND){const g={avg:Xe(this._reports,D.AUDIO,"delta_jitter_ms_in",!1,_),min:ze(this._reports,D.AUDIO,"delta_jitter_ms_in",_),max:Je(this._reports,D.AUDIO,"delta_jitter_ms_in",_),volatility:Ye(this._reports,D.AUDIO,"delta_jitter_ms_in",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},f={avg:Xe(this._reports,D.AUDIO,"delta_kbs_in",!1,_),min:ze(this._reports,D.AUDIO,"delta_kbs_in",_),max:Je(this._reports,D.AUDIO,"delta_kbs_in",_),volatility:Ye(this._reports,D.AUDIO,"delta_kbs_in",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,D.AUDIO,"delta_KBytes_in",!1,_),min:ze(this._reports,D.AUDIO,"delta_KBytes_in",_),max:Je(this._reports,D.AUDIO,"delta_KBytes_in",_),volatility:Ye(this._reports,D.AUDIO,"delta_KBytes_in",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},y={emodel:{avg:Xe(this._reports,D.AUDIO,"mos_emodel_in",!1,_),min:ze(this._reports,D.AUDIO,"mos_emodel_in",_),max:Je(this._reports,D.AUDIO,"mos_emodel_in",_),volatility:Ye(this._reports,D.AUDIO,"mos_emodel_in",_)},effective:{avg:Xe(this._reports,D.AUDIO,"mos_in",!1,_),min:ze(this._reports,D.AUDIO,"mos_in",_),max:Je(this._reports,D.AUDIO,"mos_in",_),volatility:Ye(this._reports,D.AUDIO,"mos_in",_)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},A=St(this._reports,D.AUDIO,"total_packets_lost_in",_),w=St(this._reports,D.AUDIO,"total_packets_in",_),b={lost:A,avg:Math.round((A/(A+w)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[_].jitter=g,e[_].mos=y,e[_].traffic=T,e[_].bitrate=f,e[_].loss=b}else{const g={avg:Xe(this._reports,D.AUDIO,"delta_jitter_ms_out",!1,_),min:ze(this._reports,D.AUDIO,"delta_jitter_ms_out",_),max:Je(this._reports,D.AUDIO,"delta_jitter_ms_out",_),volatility:Ye(this._reports,D.AUDIO,"delta_jitter_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},f={avg:Xe(this._reports,D.AUDIO,"delta_kbs_out",!1,_),min:ze(this._reports,D.AUDIO,"delta_kbs_out",_),max:Je(this._reports,D.AUDIO,"delta_kbs_out",_),volatility:Ye(this._reports,D.AUDIO,"delta_kbs_out",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,D.AUDIO,"delta_KBytes_out",!1,_),min:ze(this._reports,D.AUDIO,"delta_KBytes_out",_),max:Je(this._reports,D.AUDIO,"delta_KBytes_out",_),volatility:Ye(this._reports,D.AUDIO,"delta_KBytes_out",_),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},y={avg:$d(this._reports,D.AUDIO,_),min:ze(this._reports,D.AUDIO,"delta_rtt_ms_out",_),max:Je(this._reports,D.AUDIO,"delta_rtt_ms_out",_),volatility:Ye(this._reports,D.AUDIO,"delta_rtt_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},A=St(this._reports,D.AUDIO,"total_packets_lost_out",_),w=St(this._reports,D.AUDIO,"total_packets_out",_),b={lost:A,avg:Math.round((A/(A+w)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},R={emodel:{avg:Xe(this._reports,D.AUDIO,"mos_emodel_out",!1,_),min:ze(this._reports,D.AUDIO,"mos_emodel_out",_),max:Je(this._reports,D.AUDIO,"mos_emodel_out",_),volatility:Ye(this._reports,D.AUDIO,"mos_emodel_out",_)},effective:{avg:Xe(this._reports,D.AUDIO,"mos_out",!1,_),min:ze(this._reports,D.AUDIO,"mos_out",_),max:Je(this._reports,D.AUDIO,"mos_out",_),volatility:Ye(this._reports,D.AUDIO,"mos_out",_)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};e[_].jitter=g,e[_].rtt=y,e[_].traffic=T,e[_].bitrate=f,e[_].loss=b,e[_].mos=R}}),Object.keys(d[D.VIDEO]).forEach(_=>{const u=d[D.VIDEO][_];if(e[_]={type:D.VIDEO,direction:u.direction},u.direction===Pe.INBOUND){const g={avg:Xe(this._reports,D.VIDEO,"delta_jitter_ms_in",!1,_),min:ze(this._reports,D.VIDEO,"delta_jitter_ms_in",_),max:Je(this._reports,D.VIDEO,"delta_jitter_ms_in",_),volatility:Ye(this._reports,D.VIDEO,"delta_jitter_ms_in",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},f={avg:Xe(this._reports,D.VIDEO,"delta_kbs_in",!1,_),min:ze(this._reports,D.VIDEO,"delta_kbs_in",_),max:Je(this._reports,D.VIDEO,"delta_kbs_in",_),volatility:Ye(this._reports,D.VIDEO,"delta_kbs_in",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,D.VIDEO,"delta_KBytes_in",!1,_),min:ze(this._reports,D.VIDEO,"delta_KBytes_in",_),max:Je(this._reports,D.VIDEO,"delta_KBytes_in",_),volatility:Ye(this._reports,D.VIDEO,"delta_KBytes_in",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},y=St(this._reports,D.VIDEO,"total_packets_lost_in",_),A=St(this._reports,D.VIDEO,"total_packets_in",_),w={lost:y,avg:Math.round((y/(y+A)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[_].jitter=g,e[_].traffic=T,e[_].bitrate=f,e[_].loss=w}else{const g={avg:Xe(this._reports,D.VIDEO,"delta_jitter_ms_out",!1,_),min:ze(this._reports,D.VIDEO,"delta_jitter_ms_out",_),max:Je(this._reports,D.VIDEO,"delta_jitter_ms_out",_),volatility:Ye(this._reports,D.VIDEO,"delta_jitter_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},f={avg:Xe(this._reports,D.VIDEO,"delta_kbs_out",!1,_),min:ze(this._reports,D.VIDEO,"delta_kbs_out",_),max:Je(this._reports,D.VIDEO,"delta_kbs_out",_),volatility:Ye(this._reports,D.VIDEO,"delta_kbs_out",_),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},T={avg:Xe(this._reports,D.VIDEO,"delta_KBytes_out",!1,_),min:ze(this._reports,D.VIDEO,"delta_KBytes_out",_),max:Je(this._reports,D.VIDEO,"delta_KBytes_out",_),volatility:Ye(this._reports,D.VIDEO,"delta_KBytes_out",_),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},y={avg:$d(this._reports,D.VIDEO,_),min:ze(this._reports,D.VIDEO,"delta_rtt_ms_out",_),max:Je(this._reports,D.VIDEO,"delta_rtt_ms_out",_),volatility:Ye(this._reports,D.VIDEO,"delta_rtt_ms_out",_),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},A=St(this._reports,D.VIDEO,"total_packets_lost_out",_),w=St(this._reports,D.VIDEO,"total_packets_out",_),b={lost:A,avg:Math.round((A/(A+w)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};e[_].jitter=g,e[_].rtt=y,e[_].traffic=T,e[_].bitrate=f,e[_].loss=b}})),{version:iy,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:e,data:{rtt:{avg:oy(this._reports,"data"),min:ze(this._reports,"data","delta_rtt_connectivity_ms"),max:Je(this._reports,"data","delta_rtt_connectivity_ms"),volatility:Ye(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((n/(n+s)*100||0)*100)/100}},video:{in:{avg:Math.round((i/(i+a)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:Xe(this._reports,"data","delta_kbs_in"),min:ze(this._reports,"data","delta_kbs_in"),max:Je(this._reports,"data","delta_kbs_in"),volatility:Ye(this._reports,"data","delta_kbs_in")},out:{avg:Xe(this._reports,"data","delta_kbs_out"),min:ze(this._reports,"data","delta_kbs_out"),max:Je(this._reports,"data","delta_kbs_out"),volatility:Ye(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:Xe(this._reports,"data","delta_KBytes_in"),min:ze(this._reports,"data","delta_KBytes_in"),max:Je(this._reports,"data","delta_KBytes_in"),volatility:Ye(this._reports,"data","delta_KBytes_in")},out:{avg:Xe(this._reports,"data","delta_KBytes_out"),min:ze(this._reports,"data","delta_KBytes_out"),max:Je(this._reports,"data","delta_KBytes_out"),volatility:Ye(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:ly(this._reports),remoteConnection:ay(this._reports)}}}}updateConfig(n){this._cfg=n}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const n=this._reports.slice();return n.pop(),n.pop()||null}getReportsNumber(){return this._reports.length}}const Xn="extractor ",Vd=(l,n,s,i)=>{let a=!1;const e=i[n].total_rtt_ms_out,d=i[n].total_rtt_measure_out,_=s?s[n].total_rtt_ms_out:0,u=s?s[n].total_rtt_measure_out:0,g={rtt:null,totalRTT:e,totalRTTMeasurements:d};if(l[q.TIMESTAMP]===i[n].timestamp_out||!Object.prototype.hasOwnProperty.call(l,q.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(l,q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(a=!0,Number(l[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(l[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-u===d))return g;const f=1e3*Number(l[q.ROUND_TRIP_TIME]);let T=e+f,y=d+1;return a&&(T=1e3*Number(l[q.TOTAL_ROUND_TRIP_TIME])-_,y=Number(l[q.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-u),{rtt:f,totalRTT:T,totalRTTMeasurements:y}},cy=(l,n,s,i)=>{if(!Object.prototype.hasOwnProperty.call(l,q.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:i[n].total_rtt_connectivity_ms,totalRTTMeasurements:i[n].total_rtt_connectivity_measure};const a=1e3*Number(l[q.CURRENT_ROUND_TRIP_TIME]);let e=i[n].total_rtt_connectivity_ms+a,d=i[n].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(l,q.TOTAL_ROUND_TRIP_TIME)&&(e=1e3*Number(l[q.TOTAL_ROUND_TRIP_TIME])-(s?s[n].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(l,q.RESPONSES_RECEIVED)&&(d=Number(l[q.RESPONSES_RECEIVED])-(s?s[n].total_rtt_connectivity_measure:0)),{rtt:a,totalRTT:e,totalRTTMeasurements:d}},wl=(l,n,s)=>l[q.TIMESTAMP]===s[n].timestamp_out||!Object.prototype.hasOwnProperty.call(l,q.JITTER)?null:1e3*(Number(l[q.JITTER])||0),hy=(l,n)=>{if(!Object.prototype.hasOwnProperty.call(l,q.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(l,q.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:n[D.VIDEO].delta_ms_decode_frame_in,frames_decoded:n[D.VIDEO].total_frames_decoded_in,total_decode_time:n[D.VIDEO].total_time_decoded_in};const s=l[q.FRAMES_DECODED],i=l[q.TOTAL_DECODE_TIME],a=i-n[D.VIDEO].total_time_decoded_in,e=s-n[D.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:e>0?a*1e3/e:0,frames_decoded:s,total_decode_time:i}},dy=(l,n)=>{if(!Object.prototype.hasOwnProperty.call(l,q.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(l,q.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:n[D.VIDEO].delta_ms_encode_frame_out,frames_encoded:n[D.VIDEO].total_frames_encoded_out,total_encode_time:n[D.VIDEO].total_time_encoded_out};const s=l[q.FRAMES_ENCODED],i=l[q.TOTAL_ENCODE_TIME],a=i-n[D.VIDEO].total_time_encoded_out,e=s-n[D.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:e>0&&a?a*1e3/e:0,frames_encoded:s,total_encode_time:i}},Bd=(l,n,s,i)=>{if(!Object.prototype.hasOwnProperty.call(l,q.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(l,q.BYTES_SENT))return{packetsSent:s[n].total_packets_out,packetsLost:s[n].total_packets_lost_out,bytesSent:s[n].total_KBytes_out};const a=Number(l[q.PACKETS_SENT])||0-(i?i[n].total_packets_out:0),e=a-s[n].total_packets_out,d=Number(l[q.BYTES_SENT])/1024-(i?i[n].total_KBytes_out:0),_=d-s[n].total_KBytes_out,u=l[q.TIMESTAMP]||Date.now(),g=i?i.timestamp:null;let f=s.timestamp;!f&&g&&(f=g);const T=f?u-f:0,y=T>0?_*.008*1024/T*1e3:0;return{packetsSent:a,deltaPacketsSent:e,KBytesSent:d,deltaKBytesSent:_,kbsSent:y}},Kd=(l,n,s,i)=>{let a=s[n].total_packets_lost_out,e=0,d=0;return Object.prototype.hasOwnProperty.call(l,q.PACKETS_LOST)&&(a=Number(l[q.PACKETS_LOST])||0-(i?i[n].total_packets_lost_out:0),e=a-s[n].total_packets_lost_out),Object.prototype.hasOwnProperty.call(l,q.FRACTION_LOST)&&(d=Number(100*l[q.FRACTION_LOST])),{packetsLost:a,deltaPacketsLost:e,fractionLost:d}},Gd=(l,n,s,i)=>{if(!Object.prototype.hasOwnProperty.call(l,q.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(l,q.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(l,q.BYTES_RECEIVED))return{percent_packets_lost:s[n].percent_packets_lost_in,packetsReceived:s[n].total_packets_in,packetsLost:s[n].total_packets_lost_in,bytesReceived:s[n].total_KBytes_in};const a=Number(l[q.PACKETS_RECEIVED])||0-(i?i[n].total_packets_in:0),e=Number(l[q.PACKETS_LOST])||0-(i?i[n].total_packets_lost_in:0),d=e-s[n].total_packets_lost_in,_=a-s[n].total_packets_in,u=a!==s[n].total_packets_in?d*100/(d+_):0,g=Number(l[q.BYTES_RECEIVED])/1024-(i?i[n].total_KBytes_in:0),f=g-s[n].total_KBytes_in,T=l[q.TIMESTAMP]||Date.now(),y=i?i.timestamp:null;let A=s.timestamp;!A&&y&&(A=y);const w=A?T-A:0,b=w>0?f*.008*1024/w*1e3:0;return{percentPacketsLost:u,packetsReceived:a,deltaPacketsReceived:_,packetsLost:e,deltaPacketsLost:d,KBytesReceived:g,deltaKBytesReceived:f,kbsReceived:b}},_y=l=>l[q.CANDIDATE_TYPE]!=="relay"?"":l[q.RELAY_PROTOCOL]||"",py=l=>{if(!Object.prototype.hasOwnProperty.call(l,q.NETWORK_TYPE))return Ur.WIFI;switch(l[q.NETWORK_TYPE]){case au.ETHERNET:return Ur.ETHERNET;case au.CELLULAR_4G:return Ur.CELLULAR_4G;case au.WIFI:return Ur.WIFI;default:return Ur.CELLULAR}},Wd=l=>!Object.prototype.hasOwnProperty.call(l,q.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(l,q.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:l[q.FRAME_WIDTH]||null,height:l[q.FRAME_HEIGHT]||null,framerate:l[q.FRAMES_PER_SECOND]},fy=l=>{const n=Object.prototype.hasOwnProperty.call(l,q.QUALITY_LIMITATION_REASON)?l[q.QUALITY_LIMITATION_REASON]:null,s=Object.prototype.hasOwnProperty.call(l,q.QUALITY_LIMITATION_RESOLUTION_CHANGES)?l[q.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,i=Object.prototype.hasOwnProperty.call(l,q.QUALITY_LIMITATION_DURATIONS)?l[q.QUALITY_LIMITATION_DURATIONS]:null;return i&&Object.keys(i).forEach(a=>{i[a]>1e3&&(i[a]=Number(i[a]/1e3))}),{reason:n,durations:i,resolutionChanges:s}},my=(l,n,s)=>{if(!Object.prototype.hasOwnProperty.call(l,q.PLI)||!Object.prototype.hasOwnProperty.call(l,q.NACK))return{pliCount:n.total_pli_sent_in,nackCount:n.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const i=(l[q.PLI]||0)-(s?s[D.VIDEO].total_pli_sent_in:0),a=(l[q.NACK]||0)-(s?s[D.VIDEO].total_nack_sent_in:0);return{pliCount:i,nackCount:a,deltaPliCount:i-n[D.VIDEO].total_pli_sent_in,deltaNackCount:a-n[D.VIDEO].total_nack_sent_in}},gy=(l,n,s)=>{if(!Object.prototype.hasOwnProperty.call(l,q.PLI)||!Object.prototype.hasOwnProperty.call(l,q.NACK))return{pliCount:n.total_pli_received_out,nackCount:n.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const i=(l[q.PLI]||0)-(s?s[D.VIDEO].total_pli_received_out:0),a=(l[q.NACK]||0)-(s?s[D.VIDEO].total_nack_received_out:0);return{pliCount:i,nackCount:a,deltaPliCount:i-n[D.VIDEO].total_pli_received_out,deltaNackCount:a-n[D.VIDEO].total_nack_received_out}},Ty=l=>({channels:l[q.CHANNELS]||null,clock_rate:l[q.CLOCK_RATE]||null,mime_type:l[q.MIME_TYPE]||null,sdp_fmtp_line:l[q.SDP_FMTP_LINE]||null}),vy=l=>({clock_rate:l[q.CLOCK_RATE]||null,mime_type:l[q.MIME_TYPE]||null}),yy=(l,n,s)=>{const i=(l[q.BYTES_RECEIVED]||0)/1024-(s?s.data.total_KBytes_in:0),a=(l[q.BYTES_SENT]||0)/1024-(s?s.data.total_KBytes_out:0),e=l[q.TIMESTAMP]||Date.now(),d=i-n.data.total_KBytes_in,_=a-n.data.total_KBytes_out,u=s?s.timestamp:null;let g=n.timestamp;!g&&u&&(g=u);const f=g?e-g:0,T=f>0?d*.008*1024/f*1e3:0,y=f>0?_*.008*1024/f*1e3:0;return{total_KBytes_received:i,total_KBytes_sent:a,delta_KBytes_received:d,delta_KBytes_sent:_,kbs_speed_received:T,kbs_speed_sent:y}},Ey=l=>{const n=l[q.AVAILABLE_INCOMING_BITRATE]/1024||0,s=l[q.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:n,kbs_outgoing_bandwidth:s}},Sy=(l,n,s,i)=>{if(!l)return[];switch(l[q.TYPE]){case Yt.CANDIDATE_PAIR:let a=!1;if(l[q.NOMINATED]&&l[q.STATE]===D.SUCCEEDED&&(a=!0,Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l),q.SELECTED in l&&!l[q.SELECTED]&&(a=!1)),a){const d=l[q.LOCAL_CANDIDATE_ID],_=l[q.REMOTE_CANDIDATE_ID],u=yy(l,n,i),g=Ey(l),f=cy(l,"data",i,n);return[{type:se.NETWORK,value:{local_candidate_id:d}},{type:se.NETWORK,value:{remote_candidate_id:_}},{type:se.DATA,value:{total_KBytes_in:u.total_KBytes_received}},{type:se.DATA,value:{total_KBytes_out:u.total_KBytes_sent}},{type:se.DATA,value:{delta_KBytes_in:u.delta_KBytes_received}},{type:se.DATA,value:{delta_KBytes_out:u.delta_KBytes_sent}},{type:se.DATA,value:{delta_kbs_in:u.kbs_speed_received}},{type:se.DATA,value:{delta_kbs_out:u.kbs_speed_sent}},{type:se.DATA,value:{delta_kbs_bandwidth_in:g.kbs_incoming_bandwidth}},{type:se.DATA,value:{delta_kbs_bandwidth_out:g.kbs_outgoing_bandwidth}},{type:se.DATA,value:{delta_rtt_connectivity_ms:f.rtt}},{type:se.DATA,value:{total_rtt_connectivity_ms:f.totalRTT}},{type:se.DATA,value:{total_rtt_connectivity_measure:f.totalRTTMeasurements}}]}break;case Yt.LOCAL_CANDIDATE:if(l[q.ID]===n.network.local_candidate_id)return[{type:se.NETWORK,value:{infrastructure:py(l)}},{type:se.NETWORK,value:{local_candidate_type:l[q.CANDIDATE_TYPE]||""}},{type:se.NETWORK,value:{local_candidate_protocol:l[q.PROTOCOL]||""}},{type:se.NETWORK,value:{local_candidate_relay_protocol:_y(l)}}];break;case Yt.REMOTE_CANDIDATE:if(l[q.ID]===n.network.remote_candidate_id)return[{type:se.NETWORK,value:{remote_candidate_type:l[q.CANDIDATE_TYPE]||""}},{type:se.NETWORK,value:{remote_candidate_protocol:l[q.PROTOCOL]||""}}];break;case Yt.INBOUND_RTP:{Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);const d=l[q.SSRC],_=ht(d,n,Pe.INBOUND);_&&(_.timestamp=n.timestamp);const u=ht(d,i,Pe.INBOUND);if(u&&(u.timestamp=i.timestamp),l[q.MEDIA_TYPE]===D.AUDIO){const g=Gd(l,D.AUDIO,_,u),f=wl(l,D.AUDIO,_),T=l[q.CODEC_ID]||"";return[{ssrc:d,type:se.AUDIO,value:{codec_id_in:T}},{ssrc:d,type:se.AUDIO,value:{total_packets_in:g.packetsReceived}},{ssrc:d,type:se.AUDIO,value:{delta_packets_in:g.deltaPacketsReceived}},{ssrc:d,type:se.AUDIO,value:{total_packets_lost_in:g.packetsLost}},{ssrc:d,type:se.AUDIO,value:{delta_packets_lost_in:g.deltaPacketsLost}},{ssrc:d,type:se.AUDIO,value:{percent_packets_lost_in:g.percentPacketsLost}},{ssrc:d,type:se.AUDIO,value:{total_KBytes_in:g.KBytesReceived}},{ssrc:d,type:se.AUDIO,value:{delta_KBytes_in:g.deltaKBytesReceived}},{ssrc:d,type:se.AUDIO,value:{delta_kbs_in:g.kbsReceived}},{ssrc:d,type:se.AUDIO,value:{delta_jitter_ms_in:f}}]}if(l[q.MEDIA_TYPE]===D.VIDEO){const g=hy(l,_),f=Gd(l,D.VIDEO,_,u),T=wl(l,D.VIDEO,_),y=l[q.DECODER_IMPLEMENTATION]||null,A=l[q.CODEC_ID]||null,w=Wd(l),b=my(l,_,u);return[{ssrc:d,type:se.VIDEO,value:{codec_id_in:A}},{ssrc:d,type:se.VIDEO,value:{total_packets_in:f.packetsReceived}},{ssrc:d,type:se.VIDEO,value:{delta_packets_in:f.deltaPacketsReceived}},{ssrc:d,type:se.VIDEO,value:{total_packets_lost_in:f.packetsLost}},{ssrc:d,type:se.VIDEO,value:{delta_packets_lost_in:f.deltaPacketsLost}},{ssrc:d,type:se.VIDEO,value:{percent_packets_lost_in:f.percentPacketsLost}},{ssrc:d,type:se.VIDEO,value:{total_KBytes_in:f.KBytesReceived}},{ssrc:d,type:se.VIDEO,value:{delta_KBytes_in:f.deltaKBytesReceived}},{ssrc:d,type:se.VIDEO,value:{delta_kbs_in:f.kbsReceived}},{ssrc:d,type:se.VIDEO,value:{delta_jitter_ms_in:T}},{ssrc:d,type:se.VIDEO,value:{decoder_in:y}},{ssrc:d,type:se.VIDEO,value:{delta_ms_decode_frame_in:g.delta_ms_decode_frame}},{ssrc:d,type:se.VIDEO,value:{total_frames_decoded_in:g.frames_decoded}},{ssrc:d,type:se.VIDEO,value:{total_time_decoded_in:g.total_decode_time}},{ssrc:d,type:se.VIDEO,value:{total_nack_sent_in:b.nackCount}},{ssrc:d,type:se.VIDEO,value:{delta_nack_sent_in:b.deltaNackCount}},{ssrc:d,type:se.VIDEO,value:{total_pli_sent_in:b.pliCount}},{ssrc:d,type:se.VIDEO,value:{delta_pli_sent_in:b.deltaPliCount}},{ssrc:d,type:se.VIDEO,value:{size_in:w}}]}break}case Yt.OUTBOUND_RTP:{Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);const d=l[q.SSRC],_=ht(d,n,Pe.OUTBOUND);_&&(_.timestamp=n.timestamp);const u=ht(d,i,Pe.OUTBOUND);if(u&&(u.timestamp=i.timestamp),l[q.MEDIA_TYPE]===D.AUDIO){const g=l[q.CODEC_ID]||null,f=Bd(l,D.AUDIO,_,u);return[{ssrc:d,type:se.AUDIO,value:{codec_id_out:g}},{ssrc:d,type:se.AUDIO,value:{total_packets_out:f.packetsSent}},{ssrc:d,type:se.AUDIO,value:{delta_packets_out:f.deltaPacketsSent}},{ssrc:d,type:se.AUDIO,value:{total_KBytes_out:f.KBytesSent}},{ssrc:d,type:se.AUDIO,value:{delta_KBytes_out:f.deltaKBytesSent}},{ssrc:d,type:se.AUDIO,value:{delta_kbs_out:f.kbsSent}}]}if(l[q.MEDIA_TYPE]===D.VIDEO){const g=l[q.ENCODER_IMPLEMENTATION]||null,f=l[q.CODEC_ID]||null,T=dy(l,_),y=Wd(l),A=fy(l),w=gy(l,_,u),b=Bd(l,D.VIDEO,_,u);return[{ssrc:d,type:se.VIDEO,value:{codec_id_out:f}},{ssrc:d,type:se.VIDEO,value:{total_packets_out:b.packetsSent}},{ssrc:d,type:se.VIDEO,value:{delta_packets_out:b.deltaPacketsSent}},{ssrc:d,type:se.VIDEO,value:{total_KBytes_out:b.KBytesSent}},{ssrc:d,type:se.VIDEO,value:{delta_KBytes_out:b.deltaKBytesSent}},{ssrc:d,type:se.VIDEO,value:{delta_kbs_out:b.kbsSent}},{ssrc:d,type:se.VIDEO,value:{encoder_out:g}},{ssrc:d,type:se.VIDEO,value:{delta_ms_encode_frame_out:T.delta_ms_encode_frame}},{ssrc:d,type:se.VIDEO,value:{total_frames_encoded_out:T.frames_encoded}},{ssrc:d,type:se.VIDEO,value:{total_time_encoded_out:T.total_encode_time}},{ssrc:d,type:se.VIDEO,value:{total_nack_received_out:w.nackCount}},{ssrc:d,type:se.VIDEO,value:{delta_nack_received_out:w.deltaNackCount}},{ssrc:d,type:se.VIDEO,value:{total_pli_received_out:w.pliCount}},{ssrc:d,type:se.VIDEO,value:{delta_pli_received_out:w.deltaPliCount}},{ssrc:d,type:se.VIDEO,value:{size_out:y}},{ssrc:d,type:se.VIDEO,value:{limitation_out:A}}]}break}case Yt.MEDIA_SOURCE:{Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);break}case Yt.TRACK:{Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);break}case Yt.CODEC:const e=[];return Object.keys(n[D.AUDIO]).forEach(d=>{const _=n[D.AUDIO][d];if(_.codec_id_in===l[q.ID]||_.codec_id_out===l[q.ID]){Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);const u=Ty(l);l[q.ID]===_.codec_id_in?e.push({ssrc:_.ssrc,type:se.AUDIO,value:{codec_in:u}}):e.push({ssrc:_.ssrc,type:se.AUDIO,value:{codec_out:u}})}}),Object.keys(n[D.VIDEO]).forEach(d=>{const _=n[D.VIDEO][d];if(_.codec_id_in===l[q.ID]||_.codec_id_out===l[q.ID]){Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);const u=vy(l);l[q.ID]===_.codec_id_in?e.push({ssrc:_.ssrc,type:se.VIDEO,value:{codec_in:u}}):e.push({ssrc:_.ssrc,type:se.VIDEO,value:{codec_out:u}})}}),e;case Yt.REMOTE_INBOUND_RTP:{Ne(Xn,`analyze() - got stats ${l[q.TYPE]} for ${s}`,l);const d=l[q.SSRC],_=ht(d,n,Pe.OUTBOUND),u=ht(d,i,Pe.OUTBOUND);if(l[q.KIND]===D.AUDIO){const g=Vd(l,D.AUDIO,u,_),f=wl(l,D.AUDIO,_),T=Kd(l,D.AUDIO,_,u);return[{ssrc:d,type:se.AUDIO,value:{delta_rtt_ms_out:g.rtt}},{ssrc:d,type:se.AUDIO,value:{total_rtt_ms_out:g.totalRTT}},{ssrc:d,type:se.AUDIO,value:{total_rtt_measure_out:g.totalRTTMeasurements}},{ssrc:d,type:se.AUDIO,value:{delta_jitter_ms_out:f}},{ssrc:d,type:se.AUDIO,value:{timestamp_out:l[q.TIMESTAMP]}},{ssrc:d,type:se.AUDIO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:d,type:se.AUDIO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:d,type:se.AUDIO,value:{percent_packets_lost_out:T.fractionLost}}]}if(l[q.KIND]===D.VIDEO){const g=Vd(l,D.VIDEO,u,_),f=wl(l,D.VIDEO,_),T=Kd(l,D.VIDEO,_,u);return[{ssrc:d,type:se.VIDEO,value:{delta_rtt_ms_out:g.rtt}},{ssrc:d,type:se.VIDEO,value:{total_rtt_ms_out:g.totalRTT}},{ssrc:d,type:se.VIDEO,value:{total_rtt_measure_out:g.totalRTTMeasurements}},{ssrc:d,type:se.VIDEO,value:{delta_jitter_ms_out:f}},{ssrc:d,type:se.VIDEO,value:{timestamp_out:l[q.TIMESTAMP]}},{ssrc:d,type:se.VIDEO,value:{total_packets_lost_out:T.packetsLost}},{ssrc:d,type:se.VIDEO,value:{delta_packets_lost_out:T.deltaPacketsLost}},{ssrc:d,type:se.VIDEO,value:{percent_packets_lost_out:T.fractionLost}}]}break}}return[]},Ol=l=>l<0?1:l>100?4.5:1+.035*l+7/1e6*l*(l-60)*(100-l),Ay=(l,n=D.AUDIO,s,i,a)=>{const e=ht(a,l,Pe.INBOUND),d=ht(a,s,Pe.INBOUND),_=ht(a,i,Pe.INBOUND),u=[],g=[],f=e[n].percent_packets_lost_in,T=e[n].delta_jitter_ms_in,y=d&&d[n].delta_jitter_ms_in||null,A=_&&_[n].delta_jitter_ms_in||null,w=l.data.delta_rtt_connectivity_ms,b=s&&s.data.delta_rtt_connectivity_ms||null,R=i&&i.data.delta_rtt_connectivity_ms||null;w&&u.push(w),b&&u.push(b),R&&u.push(R),T&&g.push(T),s&&y&&g.push(y),i&&A&&g.push(A);const G=u.length>0?Jn(u):100,x=g.length>0?Jn(g):10,me=93.2-f,O=.18*me*me-27.9*me+1126.62,$=(G+x)/2,de=$-177.3<0?0:1,fe=.024*$+.11*($-177.3)*de,N=O-fe;return Ol(N)},Cy=(l,n=D.AUDIO,s,i,a)=>{const e=ht(a,l,Pe.OUTBOUND),d=ht(a,s,Pe.OUTBOUND),_=ht(a,i,Pe.OUTBOUND),u=[],g=[],f=e[n].percent_packets_lost_out,T=e[n].delta_rtt_ms_out,y=d&&d[n].delta_rtt_ms_out||null,A=_&&_[n].delta_rtt_ms_out||null,w=e[n].delta_jitter_ms_out,b=d&&d[n].delta_jitter_ms_out||null,R=_&&_[n].delta_jitter_ms_out||null,G=l.data.delta_rtt_connectivity_ms,x=s&&s.data.delta_rtt_connectivity_ms||null,me=i&&i.data.delta_rtt_connectivity_ms||null;T?u.push(T):G&&u.push(G),y?u.push(y):x&&u.push(x),A?u.push(A):me&&u.push(me),w&&g.push(w),s&&b&&g.push(b),i&&R&&g.push(R);const O=u.length>0?Jn(u):100,$=g.length>0?Jn(g):10,de=93.2-f,fe=.18*de*de-27.9*de+1126.62,N=(O+$)/2,H=N-177.3<0?0:1,j=.024*N+.11*(N-177.3)*H,F=fe-j;return Ol(F)},by=(l,n=D.AUDIO,s,i,a)=>{const e=ht(a,l,Pe.INBOUND),d=ht(a,s,Pe.INBOUND),_=ht(a,i,Pe.INBOUND),u=[],g=[],f=e[n].percent_packets_lost_in/100,T=e[n].delta_jitter_ms_in,y=d&&d[n].delta_jitter_ms_in||null,A=_&&_[n].delta_jitter_ms_in||null,w=l.data.delta_rtt_connectivity_ms,b=s&&s.data.delta_rtt_connectivity_ms||null,R=i&&i.data.delta_rtt_connectivity_ms||null;w&&u.push(w),b&&u.push(b),R&&u.push(R),T&&g.push(T),d&&y&&g.push(y),_&&A&&g.push(A);const G=u.length>0?Jn(u):100,x=g.length>0?Jn(g):10,me=0,O=19.8,$=29.7,de=30,fe=(G+x)/2+de,N=fe-177.3<0?0:1,H=.024*fe+.11*(fe-177.3)*N,j=93.2-(me+O*Math.log(1+$*f)+H);return Ol(j)},Ry=(l,n=D.AUDIO,s,i,a)=>{const e=ht(a,l,Pe.OUTBOUND),d=ht(a,s,Pe.OUTBOUND),_=ht(a,i,Pe.OUTBOUND),u=[],g=[],f=e[n].percent_packets_lost_out/100,T=e[n].delta_rtt_ms_out,y=d&&d[n].delta_rtt_ms_out||null,A=_&&_[n].delta_rtt_ms_out||null,w=e[n].delta_jitter_ms_out,b=d&&d[n].delta_jitter_ms_out||null,R=_&&_[n].delta_jitter_ms_out||null,G=l.data.delta_rtt_connectivity_ms,x=s&&s.data.delta_rtt_connectivity_ms||null,me=i&&i.data.delta_rtt_connectivity_ms||null;T?u.push(T):G&&u.push(G),y?u.push(y):x&&u.push(x),A?u.push(A):me&&u.push(me),w&&g.push(w),d&&b&&g.push(b),_&&R&&g.push(R);const O=u.length>0?Jn(u):100,$=g.length>0?Jn(g):10,de=0,fe=19.8,N=29.7,H=30,j=(O+$)/2+H,F=j-177.3<0?0:1,P=.024*j+.11*(j-177.3)*F,W=93.2-(de+fe*Math.log(1+N*f)+P);return Ol(W)};class Iy{constructor(n,s){this._callbacks={onreport:null,onticket:null},this._id=sy(),this._moduleName=this._id,this._probeId=s,this._config=n,this._exporter=new uy(n),this._state=Cn.IDLE,this.registerToPCEvents(),as(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(n,s,i,a){const e=(u,g)=>u===D.AUDIO?g===Yt.INBOUND_RTP?{...Ld}:{...Hd}:g===Yt.INBOUND_RTP?{...qd}:{...Fd},d=Qv(s);d.pname=this._config.pname,d.call_id=this._config.cid,d.user_id=this._config.uid,d.count=s?s.count+1:1;let _=null;return n.forEach(u=>{!_&&u.timestamp&&(_=u.timestamp),Sy(u,d,d.pname,a).forEach(g=>{if(g.value&&g.type)if(g.ssrc){let f=d[g.type][g.ssrc];f||(f=e(g.type,u.type),f.ssrc=g.ssrc,d[g.type][g.ssrc]=f),Object.keys(g.value).forEach(T=>{f[T]=g.value[T]})}else Object.keys(g.value).forEach(f=>{d[g.type][f]=g.value[f]})})}),d.timestamp=_,Object.keys(d[D.AUDIO]).forEach(u=>{const g=d[D.AUDIO][u];g.direction===Pe.INBOUND?(g.mos_emodel_in=Ay(d,D.AUDIO,s,i,g.ssrc),g.mos_in=by(d,D.AUDIO,s,i,g.ssrc)):(g.mos_emodel_out=Cy(d,D.AUDIO,s,i,g.ssrc),g.mos_out=Ry(d,D.AUDIO,s,i,g.ssrc))}),d}async takeReferenceStats(){return new Promise((n,s)=>{const i=Date.now();setTimeout(async()=>{try{const a=Date.now()-i,e=Date.now(),d=await this._config.pc.getStats(),_=this.analyze(d,null,null,null),u=Date.now();_.experimental.time_to_measure_ms=u-e,_.experimental.time_to_wait_ms=a,this._exporter.saveReferenceReport(_),Ne(this._moduleName,`got reference report for probe ${this._probeId}`),n()}catch(a){s(a)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Cn.RUNNING||!this._config.pc)return Ne(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const n=Date.now(),s=await this._config.pc.getStats(),i=this.analyze(s,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),a=Date.now();return i.experimental.time_to_measure_ms=a-n,this._exporter.addReport(i),Ne(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(i),i}catch(n){return Ws(this._moduleName,`got error ${n}`),null}}async start(){Ne(this._moduleName,"starting"),this.state=Cn.RUNNING,this._startedTime=this._exporter.start(),Ne(this._moduleName,"started")}async mute(){this.state=Cn.MUTED,Ne(this._moduleName,"muted")}async unmute(){this.state=Cn.RUNNING,Ne(this._moduleName,"unmuted")}async stop(n){if(Ne(this._moduleName,`stopping${n?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Cn.IDLE,this._config.ticket){const{ticket:s}=this._exporter;this.fireOnTicket(s)}this._exporter.reset(),Ne(this._moduleName,"stopped")}registerCallback(n,s,i){n in this._callbacks?(this._callbacks[n]={callback:s,context:i},Ne(this._moduleName,`registered callback '${n}'`)):Ws(this._moduleName,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Ne(this._moduleName,`unregistered callback '${n}'`)):Ws(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReport(n){this._callbacks.onreport&&cu(this._callbacks.onreport.callback,this._callbacks.onreport.context,n)}fireOnTicket(n){this._callbacks.onticket&&cu(this._callbacks.onticket.callback,this._callbacks.onticket.context,n)}updateConfig(n){this._config=n,this._exporter.updateConfig(n)}get state(){return this._state}set state(n){this._state=n,Ne(this._moduleName,`state changed to ${n}`)}addCustomEvent(n,s,i,a){this._exporter.addCustomEvent({at:typeof n=="object"?n.toJSON():n,category:s,name:i,description:a})}async registerToPCEvents(){const{pc:n}=this._config;if(navigator.mediaDevices.ondevicechange=async()=>{try{const s=await navigator.mediaDevices.enumerateDevices();this.addCustomEvent(new Date().toJSON(),"device",`${s.length} devices found`,"Media Devices state")}catch{Ws(this._moduleName,"can't get devices")}},n){n.oniceconnectionstatechange=()=>{const i=n.iceConnectionState;i===kr.CONNECTED||i===kr.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",i,"ICE connection state"):i===kr.DISCONNECTED||i===kr.FAILED?this.addCustomEvent(new Date().toJSON(),"call",i,"ICE connection state"):i===kr.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},n.onicegatheringstatechange=()=>{const i=n.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",i,"ICE gathering state")},n.ontrack=i=>{this.addCustomEvent(new Date().toJSON(),"call",`${i.track.kind}track`,"MediaStreamTrack received")},n.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const s=n.getReceivers();if(s&&s.length>0){const i=s[0],{transport:a}=i;if(a){const{iceTransport:e}=a;e&&(e.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class wy{constructor(n){this._id=n.pname&&n.pname.substr(0,12).padEnd(12," ")||ny(),this._moduleName=this._id,as(this._moduleName,"probe created"),this._config=n,this._collector=new Iy(this._config,this._id)}set onreport(n){n?this._collector.registerCallback("onreport",n):this._collector.unregisterCallback("onreport")}set onticket(n){n?this._collector.registerCallback("onticket",n):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(n){this._collector.state=n}addCustomEvent(n,s,i,a=new Date().toJSON()){this._collector.addCustomEvent(a,s,n,i)}get isRunning(){return this._collector.state===Cn.RUNNING}get isIdle(){return this._collector.state===Cn.IDLE}updateUserId(n){this._config.uid=n,this._collector.updateConfig(this._config)}updateCallId(n){this._config.cid=n,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){Il(this._moduleName,"probe is already running");return}this._collector.start()}stop(n=!1){this.isRunning&&this._collector.stop(n)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const bt="engine ";class Oy{constructor(n){this._config=n,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},as(bt,`configured for probing every ${this._config.refreshEvery}ms`),as(bt,`configured for starting after ${this._config.startAfter}ms`),as(bt,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Ne(bt,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(n=>n.isRunning)}get isIdle(){return this._probes.every(n=>n.isIdle)}addNewProbe(n,s){if(!n)throw new Error("undefined peer connection");const i=ey(n,s,this._config),a=new wy(i);return this._probes.push(a),Ne(bt,`${this._probes.length} probes registered`),a}removeExistingProbe(n){if(!n)throw new Error("undefined probe");n.state===Cn.RUNNING&&n.stop(),this._probes=this._probes.filter(s=>n.id!==s.id)}async start(){const n=()=>{this._probes.forEach(e=>e.start())},s=async()=>Promise.all(this._probes.map(e=>e.takeReferenceStats())),i=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,a=async()=>{const e=Xv(),d=this._probes.filter(_=>_.isRunning);for(const _ of d){const u=await _.collectStats();u&&e.probes.push(u),Ne(bt,`got probe ${_.id}`),await jd(0)}return e.delta_time_to_measure_probes_ms=us(e.probes,"experimental","time_to_measure_ms"),e.delta_KBytes_in=us(e.probes,"data","delta_KBytes_in"),e.delta_KBytes_out=us(e.probes,"data","delta_KBytes_out"),e.delta_kbs_in=us(e.probes,"data","delta_kbs_in"),e.delta_kbs_out=us(e.probes,"data","delta_kbs_out"),e.total_time_decoded_in=us(e.probes,"video","total_time_decoded_in"),e.total_time_encoded_out=us(e.probes,"video","total_time_encoded_out"),e};for(Ne(bt,"starting to collect"),n(),Ne(bt,"generating reference reports..."),await s(),Ne(bt,"reference reports generated"),this._startedTime=Date.now();i();)if(Ne(bt,`wait ${this._config.refreshEvery}ms before collecting`),await jd(this._config.refreshEvery),i()){Ne(bt,"collecting...");const e=Date.now(),d=await a(),_=Date.now();d.delta_time_consumed_to_measure_ms=_-e,this.fireOnReports(d),Ne(bt,"collected")}Ne(bt,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(n){const s=i=>{this._probes.forEach(a=>{a.stop(i)})};as(bt,"stop collecting"),s(n)}registerCallback(n,s,i){n in this._callbacks?(this._callbacks[n]={callback:s,context:i},Ne(bt,`registered callback '${n}'`)):Ws(bt,`can't register callback for '${n}' - not found`)}unregisterCallback(n){n in this._callbacks?(this._callbacks[n]=null,delete this._callbacks[n],Ne(this._moduleName,`unregistered callback '${n}'`)):Ws(this._moduleName,`can't unregister callback for '${n}' - not found`)}fireOnReports(n){this._callbacks.onresult&&n.probes.length>0&&cu(this._callbacks.onresult.callback,this._callbacks.onresult.context,n)}}const Ny="interface ";class Dy{constructor(n){this._config=ty(n),as(Ny,`welcome to ${this._config.name} version ${this._config.version}`),Vv(this._config.verbose||!1),this._engine=new Oy(this._config)}setupLogLevel(n){Bv(n)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(n,s){return this._engine.addNewProbe(n,s)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(n){this._engine.removeExistingProbe(n)}set onresult(n){n?this._engine.registerCallback("onresult",n):this._engine.unregisterCallback("onresult")}}function ky(l,n){return Object.keys(l).filter(s=>n.includes(s)).reduce((s,i)=>{const a=i;return{...s,[a]:l[a]}},{})}const Uy=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],My={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class Py{constructor(n){this.intervals={},this.analysers={},this.emitInterval=n.emitInterval||200,this.onChangeFunction=n.onChangeFunction}async start(n,s,i){s&&s.getTracks().length&&await this.beginCalculation(n,s,i)}stop(n){this.clearVolumeInterval(n),this.analysers[n]&&typeof this.analysers[n].disconnect=="function"&&(this.analysers[n].disconnect(),delete this.analysers[n])}clearVolumeInterval(n){this.intervals[n]&&(clearInterval(this.intervals[n]),delete this.intervals[n])}clearAllIntervals(){Object.keys(this.intervals).forEach(n=>{this.stop(n)}),this.intervals={},this.analysers={}}async beginCalculation(n,s,i){this.clearVolumeInterval(i);const a=n.createAnalyser(),e=n.createMediaStreamSource(s);a.smoothingTimeConstant=.8,a.fftSize=1024,e.connect(a),this.analysers[i]=a,this.intervals[i]=setInterval(()=>{const d=new Uint8Array(a.frequencyBinCount);a.getByteFrequencyData(d);let _=0;const u=d.length;for(let f=0;f<u;f++)_+=d[f];const g=_/u;this.onChangeFunction(i,g)},this.emitInterval)}}class xy{constructor(){this.resumePromise=null,this.context=new AudioContext}async getContext(){return this.context.state==="suspended"&&(this.resumePromise||(this.resumePromise=this.context.resume().then(()=>{this.resumePromise=null}).catch(n=>{throw this.resumePromise=null,n})),await this.resumePromise),this.context}}const Nl={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},Ly=0;class Hy{constructor(n){var s,i;if(this.isAutoAnswer=!1,this.muteWhenJoinEnabled=!1,this.isDNDEnabled=!1,this.isCallWaitingEnabled=!0,this.muted=!1,this.microphoneInputLevelValue=1,this.speakerVolumeValue=1,this.activeRooms={},this.activeCalls={},this.extendedCalls={},this.conferenceNodes={},this.availableMediaDevices=[],this.selectedMediaDevices={input:"default",output:"default"},this.callStatus={},this.callTime={},this.callMetrics={},this.timeIntervals={},this.metricConfig={refreshEvery:1e3},this.activeStreamValue=null,this.initialStreamValue=null,this.vadSessions={},this.vadSessionsState={},this.vadIntervals={},this.vadMrsIntervals={},this.managedAudioContext=new xy,this.context=n,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new Py({onChangeFunction:this.emitVolumeChange.bind(this)}),this.processVADConfiguration(),this.initializeMediaDevices(),["enabled","dynamic"].includes(this.noiseReduction.mode)){const a=(i=(s=this.context.options.configuration)==null?void 0:s.noiseReductionOptions)==null?void 0:i.vadModule;a&&a.MicVAD?(this.MicVAD=a.MicVAD,console.log("✅ VAD module loaded successfully")):(console.warn("⚠️ Noise reduction is enabled but VAD module is not provided. To use VAD features, please install @ricky0123/vad-web and pass it via configuration.noiseReductionOptions.vadModule option."),this.noiseReduction.mode="disabled")}}processVADConfiguration(){var n;const s=((n=this.context.options.configuration)==null?void 0:n.noiseReductionOptions)||{};this.noiseReduction={mode:s.mode||"disabled",checkEveryMs:s.checkEveryMs||500,noiseCheckInterval:s.noiseCheckInterval||2e3,noiseThreshold:s.noiseThreshold||.004,vadConfig:s.vadConfig||{}}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(n){this.currentActiveRoomIdValue=n,this.context.emit("currentActiveRoomChanged",n)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(n){this.isCallAddingInProgress=n,this.context.emit("callAddingInProgressChanged",n)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get isCallWaiting(){return this.isCallWaitingEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get hasActiveAnsweredCalls(){return Object.values(this.activeRooms).filter(n=>!n.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(n=>n.kind==="audiooutput")}get getUserMediaConstraints(){return Ud()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input},echoCancellation:!0,echoCancellationType:"system",noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,latency:.01},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(n){this.availableMediaDevices=n,this.context.emit("changeAvailableDeviceList",n)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const n=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(n)}async initializeMediaDevices(){const n=localStorage.getItem(Nl.SELECTED_INPUT_DEVICE)||"default",s=localStorage.getItem(Nl.SELECTED_OUTPUT_DEVICE)||"default";try{const i=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),a=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(a),await this.setMicrophone(n),await this.setSpeaker(s),navigator.mediaDevices.addEventListener("devicechange",async()=>{const e=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(e)}),i.getTracks().forEach(e=>e.stop())}catch(i){console.error(i)}}async cleanupConferenceNodes(n){const s=this.conferenceNodes[n];if(!s)return;let i=0;s.sources.forEach((d,_)=>{try{d.disconnect(),i++}catch(u){console.error(`[cleanupConferenceNodes] Error disconnecting source ${_}:`,u)}});let a=0;s.destinations.forEach((d,_)=>{try{d.disconnect(),a++}catch(u){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${_}:`,u)}});let e=0;s.gains.forEach((d,_)=>{try{d.disconnect(),e++}catch(u){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${_}:`,u)}}),delete this.conferenceNodes[n]}setCallTime(n){const s={...n};delete s.callId,this.callTime={...this.callTime,[n.callId]:s},this.context.emit("changeCallTime",this.callTime)}removeCallTime(n){const s={...this.callTime};delete s[n],this.callTime={...s},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(n,s){this.timeIntervals={...this.timeIntervals,[n]:s}}removeTimeInterval(n){const s={...this.timeIntervals};s[n]&&(clearInterval(s[n]),delete s[n],this.timeIntervals={...s})}stopCallTimer(n){this.removeTimeInterval(n),this.removeCallTime(n)}emitVolumeChange(n,s){this.context.emit("changeCallVolume",{callId:n,volume:s})}setMetricsConfig(n){this.metricConfig={...this.metricConfig,...n}}sendDTMF(n,s){if(!/^[A-D0-9*#]+$/g.test(s))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[n].sendDTMF(s)}setIsMuted(n){this.muted=n,this.context.emit("changeIsMuted",n)}processMute(n){const s=this.currentActiveRoomId;this.setIsMuted(n),this.initialStreamValue.getTracks().forEach(i=>i.enabled=!n),this.roomReconfigure(s)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:n,toHold:s,automatic:i}){const a=this.extendedCalls[n];if(!a)return;a._automaticHold=i??!1;const e=new Promise((d,_)=>{const u=setTimeout(()=>{_(new Error("Hold operation timeout"))},5e3),g=()=>{clearTimeout(u),a.putOnHoldTimestamp=s?Date.now():void 0,d()},f=T=>{clearTimeout(u),_(T)};try{s?(this.stopSessionVad(a._id),a.hold({},g)):a.unhold({},g)}catch(T){f(T)}});try{await e,this.updateCall(a);const d=Object.values(this.extendedCalls).filter(_=>_.roomId===a.roomId&&(s?n!==_._id:!0));d.length>1&&await this.doConference(d)}catch(d){throw console.error("Hold operation failed:",d),d}}holdCall(n,s=!1){return this.processHold({callId:n,automatic:s,toHold:!0})}unholdCall(n){return this.processHold({callId:n,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(n=>n.direction==="outgoing"&&n.status===Ly).forEach(n=>this.terminateCall(n._id))}answerCall(n){const s=this.extendedCalls[n];this.cancelAllOutgoingUnanswered(),s.answer(this.sipOptions),this.updateCall(s),this.setActiveRoom(s.roomId),s.connection.addEventListener("track",i=>{this.triggerAddStream(i,s)})}async moveCall(n,s){this.updateCallStatus({callId:n,isMoving:!0}),await this.processRoomChange({callId:n,roomId:s}),this.updateCallStatus({callId:n,isMoving:!1})}updateCall(n){this.activeCalls[n._id]=Dd(n),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(n){const s={...this.activeRooms[n.roomId],...n};this.activeRooms={...this.activeRooms,[n.roomId]:{...s}},this.context.emit("updateRoom",{room:s,roomList:this.activeRooms})}hasAutoAnswerHeaders(n){const s=/answer-after=0/,i=n.request.getHeader("Call-Info");return i&&s.test(i)}addCall(n,s=!0){this.activeCalls={...this.activeCalls,[n._id]:Dd(n)},this.extendedCalls[n._id]=n,s&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(n){this.callStatus={...this.callStatus,[n]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(n){const s={...this.callStatus[n.callId]};n.isMoving!==void 0&&(s.isMoving=n.isMoving),n.isTransferring!==void 0&&(s.isTransferring=n.isTransferring),n.isMerging!==void 0&&(s.isMerging=n.isMerging),n.isTransferred!==void 0&&(s.isTransferred=n.isTransferred),this.callStatus={...this.callStatus,[n.callId]:{...s}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(n){const s={...this.callStatus};delete s[n],this.callStatus={...s},this.context.emit("changeCallStatus",this.callStatus)}addRoom(n){this.activeRooms={...this.activeRooms,[n.roomId]:n},this.context.emit("addRoom",{room:n,roomList:this.activeRooms})}async setupActiveStream(){const n=await ru(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);n.getTracks().forEach(s=>s.enabled=!this.isMuted),await this.setActiveStream(n)}async getActiveStream(){const n=await ru(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return n.getTracks().forEach(s=>s.enabled=!this.isMuted),await this.setActiveStream(n),n}async setMicrophone(n){if(!this.getInputDeviceList.find(({deviceId:i})=>i===n)||(this.setSelectedInputDevice(n),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const s=Object.values(this.extendedCalls).filter(i=>i.roomId===this.currentActiveRoomId);s.length===1?Object.values(s).forEach(async i=>{await this.setupActiveStream();const a=this.activeStream;i.connection.getSenders()[0].replaceTrack(a.getTracks()[0]),this.updateCall(i)}):await this.doConference(s)}async setActiveStream(n){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(n,"origin"),this.activeStreamValue=n,this.context.emit("changeActiveStream",n)}async setSpeaker(n){if(!this.getOutputDeviceList.find(({deviceId:a})=>a===n))return;this.setSelectedOutputDevice(n);const s=Object.values(this.extendedCalls);if(s.length===0)return;const i=s.filter(a=>a.roomId===this.currentActiveRoomId);i.length===1?s.forEach(a=>{var e;(e=a.audioTag)==null||e.setSinkId(n),this.updateCall(a)}):await this.doConference(i)}removeRoom(n){const s={...this.activeRooms},i={...s[n]};delete s[n],this.activeRooms={...s},this.context.emit("removeRoom",{room:i,roomList:this.activeRooms})}deleteRoomIfEmpty(n){n!==void 0&&Object.values(this.extendedCalls).filter(s=>s.roomId===n).length===0&&(this.removeRoom(n),this.currentActiveRoomId===n&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(n){this.muted?n.mute({audio:!0}):n.unmute({audio:!0})}startNoiseMonitor({sessionId:n,stream:s,onNoiseDetected:i,onNoiseStop:a}){const e=new AudioContext,d=e.createMediaStreamSource(s.clone()),_=e.createAnalyser();_.fftSize=1024;const u=new Float32Array(_.fftSize);d.connect(_);const g=[];this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),this.vadIntervals[n]=null),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),this.vadMrsIntervals[n]=null),this.vadMrsIntervals[n]=setInterval(()=>{_.getFloatTimeDomainData(u);const f=qv(u);g.push(f);const T=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);g.length>T&&g.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[n]=setInterval(()=>{if(g.length===0)return;const f=g.reduce((A,w)=>A+w,0)/g.length,T=this.vadSessionsState[n],y=f>this.noiseReduction.noiseThreshold;T.isSpeaking||(y&&T.currentMode==="clean"?(T.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!0}),i()):!y&&T.currentMode==="noisy"&&(T.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:n,enabled:!1}),a()))},this.noiseReduction.noiseCheckInterval)}async processVAD(n,s){const i=s.clone();this.stopSessionVad(n._id),this.vadSessionsState[n._id]={currentMode:"clean",isSpeaking:!1};const a=await this.managedAudioContext.getContext(),e=await Fv(i,a,150);let d=!1;const _=await this.MicVAD.new({getStream:()=>new Promise(u=>u(i)),...My,...this.noiseReduction.vadConfig,baseAssetPath:"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.28/dist/",onnxWASMBasePath:"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/",onFrameProcessed:()=>{if(!d){if(d=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){n.connection.getSenders()[0]&&n.connection.getSenders()[0].replaceTrack(e.stream.getAudioTracks()[0]);return}this.startNoiseMonitor({sessionId:n._id,stream:i,onNoiseDetected:async()=>{var u;console.log("Replace track with Vad Controlled"),await((u=n.connection.getSenders()[0])==null?void 0:u.replaceTrack(e.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const u=n.connection.getSenders()[0];u&&u.track&&u.transport&&u.transport.state!=="closed"&&u.transport.state!=="failed"&&(console.log("Replace track with Original"),await u.replaceTrack(i.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var u;console.log("🎤 Speech started"),e.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((u=n.connection.getSenders()[0])==null||u.replaceTrack(e.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!0},onSpeechEnd:()=>{var u;console.log("🛑 Speech end"),e.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((u=n.connection.getSenders()[0])==null||u.replaceTrack(e.stream.getAudioTracks()[0])),this.vadSessionsState[n._id].isSpeaking=!1}});this.vadSessions[n._id]&&(this.vadSessions[n._id].pause(),delete this.vadSessions[n._id]),this.vadSessions[n._id]=_,_.start()}stopSessionVad(n){this.vadSessions[n]&&(this.vadSessions[n].pause(),delete this.vadSessions[n]),this.vadIntervals[n]&&(clearInterval(this.vadIntervals[n]),delete this.vadIntervals[n]),this.vadMrsIntervals[n]&&(clearInterval(this.vadMrsIntervals[n]),delete this.vadMrsIntervals[n]),this.vadSessionsState[n]&&delete this.vadSessionsState[n]}async roomReconfigure(n){var s;if(n===void 0)return;const i=Object.values(this.extendedCalls).filter(e=>e.roomId===n),a=this.currentActiveRoomId===n;if(i.forEach((e,d)=>{if(e.audioTag){e.connection.getReceivers().forEach(u=>{u.track.enabled=!e.localMuted}),a&&this.muteReconfigure(e);const _=!a;e.audioTag.muted=_,this.updateCall(e)}}),i.length===0){this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n),this.deleteRoomIfEmpty(n);return}if(i.length===1&&!a){const e=i[0];e.isOnHold().local||await this.holdCall(e._id,!0),this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}if(i.length===1&&a){const e=i[0];e.isOnHold().local&&e._automaticHold&&await this.unholdCall(e._id);const d=(((s=e.connection)==null?void 0:s.getSenders())||[])[0];if(e.connection&&d)try{await this.setupActiveStream();const _=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(i[0],_);const u=_.getTracks();await d.replaceTrack(u[0]),this.muteReconfigure(e)}catch(_){console.error(_)}this.conferenceNodes[n]&&await this.cleanupConferenceNodes(n);return}i.length>1&&await this.doConference(i)}async doConference(n){if(n.length===0)return;const s=n[0].roomId,i=this.currentActiveRoomId===s;if(n.find(_=>_.roomId!==s))return;const a=await this.managedAudioContext.getContext();if(a.state!=="running"){console.error(`[doConference] ERROR: AudioContext is not running! State: ${a.state}`);return}await this.cleanupConferenceNodes(s),this.conferenceNodes[s]={sources:new Map,destinations:new Map,gains:new Map};const e=this.conferenceNodes[s],d=new Map;n.forEach((_,u)=>{_&&_.connection&&_.connection.getReceivers().forEach((g,f)=>{var T,y,A;g.track.enabled=!_.localMuted;const w=(T=g.track)==null?void 0:T.id;(y=g.track)==null||y.readyState,(A=g.track)==null||A.kind;const b=`${_._id}-${w}`;g.track&&g.track.readyState==="live"&&d.set(b,g.track)})}),await this.setupActiveStream(),await jv.forEach(n,async(_,u)=>{if(!_||!_.connection)return;const g=a.createMediaStreamDestination();e.destinations.set(_._id,g);let f=0;if(d.forEach((A,w)=>{if(!w.startsWith(_._id))try{const b=a.createMediaStreamSource(new MediaStream([A])),R=a.createGain(),G=`${_._id}-${w}`;b.connect(R),R.connect(g),e.sources.set(G,b),e.gains.set(G,R),f++}catch(b){console.error(b)}}),i&&this.activeStreamValue)try{const A=this.activeStream,w=a.createMediaStreamSource(A),b=a.createGain(),R=`${_._id}-local`;w.connect(b),b.connect(g),e.sources.set(R,w),e.gains.set(R,b)}catch(A){console.error(A)}else i&&console.error(`Host room but no activeStreamValue - skipping host microphone for session ${_._id}`);const T=_.connection.getSenders()[0],y=g.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(_,g.stream),T&&y[0])try{await T.replaceTrack(y[0]),this.muteReconfigure(_)}catch(A){console.error(A)}})}processCallerMute(n,s){const i=this.extendedCalls[n];i&&i.connection.getReceivers().length&&(i.localMuted=s,i.connection.getReceivers().forEach(a=>{a.track.enabled=!s}),this.updateCall(i))}muteCaller(n){this.processCallerMute(n,!0)}unmuteCaller(n){this.processCallerMute(n,!1)}terminateCall(n){const s=this.extendedCalls[n];s._status===4?s.terminate({status_code:603,reason_phrase:"Decline"}):s._status!==8&&s.terminate()}transferCall(n,s){if(s.toString().length===0)return new Error("Target must be passed");const i=this.extendedCalls[n];if(!i._is_confirmed&&!i._is_canceled){const a=`sip:${s}@${this.context.sipDomain}`;i.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${a}`]});return}this.updateCallStatus({callId:n,isTransferring:!0,isTransferred:!1}),i.refer(`sip:${s}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:n,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(i)}mergeCall(n){const s=Object.values(this.extendedCalls).filter(e=>e.roomId===n);if(s.length!==2)return;const i=s[0],a=s[1];!i||!a||(this.updateCallStatus({callId:i._id,isMerging:!0}),this.updateCallStatus({callId:a._id,isMerging:!0}),i.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(i))}mergeCallByIds(n,s){const i=Object.values(this.extendedCalls).find(e=>e._id===n),a=Object.values(this.extendedCalls).find(e=>e._id===s);if(!i||!a)throw new Error("Call ID is not provided");this.updateCallStatus({callId:n,isMerging:!0}),this.updateCallStatus({callId:s,isMerging:!0}),i.refer(a.remote_identity.uri.toString(),{replaces:a}),this.updateCall(i)}setDND(n){this.isDNDEnabled=n,this.context.emit("changeIsDND",n)}setCallWaiting(n){this.isCallWaitingEnabled=n,this.context.emit("changeIsCallWaiting",n)}startCallTimer(n){this.removeTimeInterval(n);const s={callId:n,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(s);const i=setInterval(()=>{const a={...this.callTime[n]},e=Hv(a);this.setCallTime({callId:n,...e})},1e3);this.setTimeInterval(n,i)}async setActiveRoom(n){const s=this.currentActiveRoomId;n!==s&&(this.currentActiveRoomId=n,await this.roomReconfigure(s),await this.roomReconfigure(n))}getNewRoomId(){const n=Object.keys(this.activeRooms);return n.length===0?1:parseInt(n.sort()[n.length-1])+1}async setupCall(n){var s,i;const a=n.session;if(this.getActiveCalls[a.id]!==void 0)return;const e=this.getNewRoomId(),d={started:new Date,incomingInProgress:!1,roomId:e};a.direction==="incoming"?(this.context.logger.log("New incoming call from",(i=(s=a._remote_identity)==null?void 0:s._uri)==null?void 0:i._user),d.incomingInProgress=!0,this.context.subscribe(Wt.CALL_CONFIRMED,f=>{a.id===f.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.startCallTimer(a.id))}),this.context.subscribe(Wt.CALL_FAILED,f=>{a.id===f.id&&(this.updateRoom({incomingInProgress:!1,roomId:e}),this.deleteRoomIfEmpty(e))})):a.direction==="outgoing"&&(a.once("confirmed",()=>{this.startCallTimer(a.id)}),this.startCallTimer(a.id));const _=a,u=this.hasAutoAnswerHeaders(n),g=_.direction==="incoming"&&!this.hasActiveCalls&&(u||this.autoAnswer);_.roomId=e,_.localMuted=!1,_.autoAnswer=g,g?this.addCall(_,!1):this.addCall(_),this.addCallStatus(a.id),this.addRoom(d),g&&this.answerCall(_._id)}removeCall(n){const s={...this.activeCalls};delete s[n],this.activeCalls={...s};const i={...this.extendedCalls};delete i[n],this.extendedCalls={...i},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(n){const s=this.extendedCalls[n._id];if(!s)return;this.stopVUMeter("origin"),this.stopVUMeter(n._id);const i=s.roomId;this.removeCall(n._id),this.roomReconfigure(i).then(()=>{}).catch(a=>{console.error("Error reconfiguring room after call removal:",a)})}shouldTerminateNewSession(n){if(n.session.direction==="outgoing")return!1;const s=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||s}async newRTCSessionCallback(n){const s=n.session;if(this.shouldTerminateNewSession(n)){s.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Wt.NEW_CALL,session:s,event:n}),s.on("ended",i=>{var a,e,d;this.stopVUMeter(s.id),this.context.logger.log("Session ended for",(e=(a=s._remote_identity)==null?void 0:a._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Wt.CALL_ENDED,session:s,event:i}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(s._id);const _=this.getActiveCalls[s.id];_&&this.activeCallListRemove(_),this.stopCallTimer(s.id),this.removeCallStatus(s.id),this.removeCallMetrics(s.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(u=>u.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),s.on("progress",i=>{var a,e;this.context.logger.log("Session in progress for",(e=(a=s._remote_identity)==null?void 0:a._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Wt.CALL_PROGRESS,session:s,event:i})}),s.on("failed",i=>{var a,e,d;this.stopVUMeter(s.id),this.context.logger.log("Session failed for",(e=(a=s._remote_identity)==null?void 0:a._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Wt.CALL_FAILED,session:s,event:i}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(s._id),s.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const _=this.getActiveCalls[s.id];_&&this.activeCallListRemove(_),this.stopCallTimer(s.id),this.removeCallStatus(s.id),this.removeCallMetrics(s.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(d=this.initialStreamValue)==null||d.getTracks().forEach(u=>u.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),s.on("confirmed",i=>{var a,e;this.context.logger.log("Session confirmed for",(e=(a=s._remote_identity)==null?void 0:a._uri)==null?void 0:e._user),this.context.triggerListener({listenerType:Wt.CALL_CONFIRMED,session:s,event:i}),this.updateCall(s),s.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(n),s.direction==="outgoing"){const i=this.getActiveCalls[s.id].roomId;await this.setActiveRoom(i)}}setMuteWhenJoin(n){this.muteWhenJoinEnabled=n,this.context.emit("changeMuteWhenJoin",n)}setMicrophoneSensitivity(n){if(n<0||n>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=n,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(n){this.speakerVolumeValue=n,Object.values(this.extendedCalls).forEach(s=>{s.audioTag&&(s.audioTag.volume=n,this.updateCall(s))})}setAutoAnswer(n){this.isAutoAnswer=n}setSelectedInputDevice(n){localStorage.setItem(Nl.SELECTED_INPUT_DEVICE,n),this.selectedMediaDevices.input=n,this.context.emit("changeActiveInputMediaDevice",n)}setSelectedOutputDevice(n){localStorage.setItem(Nl.SELECTED_OUTPUT_DEVICE,n),this.selectedMediaDevices.output=n,this.context.emit("changeActiveOutputMediaDevice",n)}setCallMetrics(n){const s={...n};delete s.callId,this.callMetrics={...this.callMetrics,[n.callId]:s},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(n){const s={...this.callMetrics};delete s[n],this.callMetrics={...s},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(n){const s=new Dy(this.metricConfig),i=s.createProbe(n.connection,{cid:n._id}),a=[];let e;i.onreport=d=>{Object.entries(d.audio).forEach(([g,f])=>{f.direction==="inbound"&&!a.includes(g)&&(a.push(g),e=g)});const _=d.audio[e];if(!_)return;const u=ky(_,Uy);u.callId=n._id,this.setCallMetrics(u)},this.context.subscribe(Wt.CALL_ENDED,d=>{d._id===n._id&&s.stopAllProbes()}),s.startAllProbes()}async setupVUMeter(n,s){await this.VUMeter.start(await this.managedAudioContext.getContext(),n,s)}stopVUMeter(n){this.VUMeter.stop(n)}async setupStream(){try{const n=Date.now(),s=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((i,a)=>{i.stop()}),this.initialStreamValue=null),this.initialStreamValue=s}catch(n){throw n}}async triggerAddStream(n,s){const i=this.muteWhenJoin||this.isMuted;this.setIsMuted(i),this.initialStreamValue||await this.setupStream();const a=await this.managedAudioContext.getContext(),e=await ru(a,this.initialStreamValue,this.microphoneInputLevel*2),d=this.isMuted||this.muteWhenJoin;e.getTracks().forEach(g=>{g.enabled=!d}),await this.setActiveStream(e),await s.connection.getSenders()[0].replaceTrack(e.getTracks()[0]);const _=new MediaStream([n.track]);!Object.values(this.extendedCalls).find(g=>g.audioTag&&g.audioTag.id===s._id)&&Av(_,s,this.selectedOutputDevice,this.speakerVolume);const u=s.roomId===this.currentActiveRoomId;s.audioTag&&(s.audioTag.muted=!u),await this.setupVUMeter(_,s._id),this.getCallQuality(s),this.updateCall(s),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(s,e)}initCall(n,s,i=!1){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`);const a=this.context.call(`sip:${n}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=a.id,s&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:a.id,roomId:this.currentActiveRoomId}),i)){const e=Object.values(this.extendedCalls).filter(d=>d.roomId===this.currentActiveRoomId&&d._id!==a.id);for(const d of e)this.holdCall(d._id,!0)}a.connection.addEventListener("track",e=>{this.triggerAddStream(e,a)})}async processRoomChange({callId:n,roomId:s}){const i=this.extendedCalls[n];if(!i)return;const a=i.roomId;i.roomId=s,this.updateCall(i),await this.roomReconfigure(a),await this.roomReconfigure(s)}}class qy{constructor(n){this.context=n}get sipOptions(){return{...this.context.options.sipOptions}}initCall(n,s){if(n.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${n}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${n}@${this.context.sipDomain}`,s,this.sipOptions)}stop(n={}){this.context.terminateJanusSessions(n)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(n){this.context.changeMediaConstraints(n)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class Fy{constructor(n){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=n,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(n){const s=this.extendedMessages[n];this.updateMSRPSession(s)}updateMSRPSession(n){this.activeMessages[n._id]=kd(n),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(n){this.activeMessages={...this.activeMessages,[n._id]:kd(n)},this.extendedMessages[n._id]=n,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(n,s){const i=this.msrpHistory[s.id]||[];i.push(n),this.msrpHistory={...this.msrpHistory,[s.id]:[...i]},this.context.emit("newMSRPMessage",{message:n,session:s})}messageTerminate(n){const s=this.extendedMessages[n];s._status!==8&&s.terminate()}addMessageSession(n){if(!n._id||this.getActiveMessages[n._id]!==void 0)return;const s=n;this.addMMSRPSession(s)}triggerMSRPListener({listenerType:n,session:s,event:i}){const a=this.context.listenersList[n];!a||!a.length||a.forEach(e=>{e(s,i)})}removeMMSRPSession(n){const s={...this.activeMessages};delete s[n],this.activeMessages={...s};const i={...this.extendedMessages};delete i[n],this.extendedMessages={...i},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(n){this.removeMMSRPSession(n._id)}newMSRPSessionCallback(n){const s=n.session;s.on("ended",i=>{this.triggerMSRPListener({listenerType:Wt.CALL_ENDED,session:s,event:i});const a=this.getActiveMessages[s.id];this.activeMessageListRemove(a)}),s.on("failed",i=>{this.triggerMSRPListener({listenerType:Wt.CALL_FAILED,session:s,event:i});const a=this.getActiveMessages[s.id];this.activeMessageListRemove(a)}),s.on("confirmed",i=>{this.triggerMSRPListener({listenerType:Wt.CALL_CONFIRMED,session:s,event:i}),this.updateMSRPSession(s)}),s.on("newMessage",i=>{this.addMSRPMessage(i,s)}),this.addMessageSession(s)}setIsMSRPInitializing(n){this.isMSRPInitializingValue=n,this.context.emit("isMSRPInitializingChanged",n)}initMSRP(n,s,i){if(n.length===0)return console.error("Target must be a valid string");const a=this.context.startMSRP(n,i);a.on("active",()=>{this.addMessageSession(a),a.sendMSRP(s),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(n,s){const i=this.extendedMessages[n];if(!i)throw new Error(`MSRP session with id ${n} doesn't exist!`);i.sendMSRP(s)}}const Dl={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Yd{constructor(n){this.opensips=null,this.session=null,this.name=null,this.name=n}setOpensips(n){this.opensips=n}setSession(n){this.session=n}kill(){this.opensips.kill(this.name)}}class jy extends Yd{constructor(n,s){super(n),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=s}connect(n={}){this.opaqueId=this.session.generateOpaqueId();const s=ke.cloneArray(n.extraHeaders),i={from_tag:this.session._from_tag};n.fromUserName&&(i.from_uri=new ls("sip",n.fromUserName,this.session._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),n.fromDisplayName&&(i.from_display_name=n.fromDisplayName),s.push(`Contact: ${this.session._contact}`),s.push("Content-Type: application/json"),this.session._sessionTimers.enabled&&s.push(`Session-Expires: ${this.session._sessionTimers.defaultExpires}${this.session._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new gt.InitialOutgoingInviteRequest(this.session.target,this.session._ua,i,s),this._createRTCConnection(),this._sendInitialRequest()}getStream(){return this.stream}getConnection(){return this._connection}_createRTCConnection(){this._connection=new RTCPeerConnection({iceServers:[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}]});let n;this._connection.onicecandidate=s=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||s.candidate&&(this._candidates.push(s.candidate),clearTimeout(n),n=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(n){n.forEach(s=>{this._connection.addTrack(s)})}async _sendInitialRequest(){const n=new yr(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:e=>{this._request=e},onReceiveResponse:e=>{this._receiveInviteResponse(e)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const s={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(s),await this._connection.setLocalDescription(this.jsep_offer);const i={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},a=JSON.stringify(i);this._request.body=a,n.send()}_receiveInviteResponse(n){if(this._publisherSubscribeSent||!n.body)return;const s=JSON.parse(n.body);this.handleId=s.data.id;const i={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},a=[this.session.getPTypeHeader(Mt.PUBLISHER)];this.session.sendRequest(U.SUBSCRIBE,{extraHeaders:a,body:JSON.stringify(i),eventHandlers:{onSuccessResponse:async e=>{var d,_,u,g;if(e.status_code===200){if(this._subscribeSent=!0,e.body)try{const f=JSON.parse(e.body)||{};((_=(d=f.plugindata)==null?void 0:d.data)==null?void 0:_.videoroom)==="joined"&&this.session.myFeedList.push(f.plugindata.data.id),(g=(u=f.plugindata)==null?void 0:u.data)!=null&&g.publishers&&this.session.receivePublishers(f)}catch(f){console.error(f)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(n){const s=this._candidates.map(e=>({janus:"trickle",candidate:e,handle_id:this.handleId,session_id:this.session.session_id})),i={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...n},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...s]},a=["Content-Type: application/json",this.session.getPTypeHeader(Mt.ICE)];this.session.sendRequest(U.INFO,{extraHeaders:a,body:JSON.stringify(i),eventHandlers:{onSuccessResponse:async e=>{this._configureSent=!0;const d=e.data.split(`\r
159
+ `),_=d[d.length-1],u=JSON.parse(_);await this._connection.setRemoteDescription(u.jsep),this._candidates=[]}}})}_sendDetach(){const n={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},s=[this.session.getPTypeHeader(Mt.DETACH)];this.session.sendRequest(U.INFO,{extraHeaders:s,body:JSON.stringify(n)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const n=this._connection.getSenders();n.forEach(s=>{const i=s.track;i&&i.stop()}),n.forEach(s=>{this._connection.removeTrack(s)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class $y extends Yd{constructor(n,s,i={}){super(n),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=i.immediate||!1,this.type=s}start(n){return n}stop(){throw new Error("stop method is not implemented")}async process(n){if(this.immediate){const s=await this.start(n);return this.running=!0,s}return n}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}class Vy extends mv{constructor(n,s){if(!n.modules.length)throw new Error("options.modules should include at least 1 module");const i={...n.configuration,sockets:n.socketInterfaces.map(a=>new Lv.WebSocketInterface(a))};super(i),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.waitingForSessionHangup=!1,this.waitingForSessionTimeout=null,this.reconnectionAttemptsLimit=1/0,this.reconnectionAttemptsCounter=0,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],n.pnExtraHeaders&&Object.keys(n.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(n.pnExtraHeaders),this.options=n,this.modules=n.modules,n.configuration.reconnectionAttemptsLimit&&(this.reconnectionAttemptsLimit=n.configuration.reconnectionAttemptsLimit),s&&Cv(s)&&(this.logger=s)}isWaitingForSessionHangup(){return this.waitingForSessionHangup}stopSessionAfterWaiting(){this.setInitialized(!1),this.waitingForSessionHangup=!1,clearTimeout(this.waitingForSessionTimeout),this.waitingForSessionTimeout=null,this.activeConnection&&this.reconnect()}get hasActiveSessions(){return this.modules.includes(Dl.AUDIO)?this.audio.hasActiveAnsweredCalls:!1}on(n,s){return super.on(n,s)}off(n,s){return super.off(n,s)}emit(n,s){return super.emit(n,s)}get sipDomain(){return this.options.sipDomain}use(n){if(this.newStreamPlugins.find(s=>s.name===n.name)||this.processStreamPlugins.find(s=>s.name===n.name))throw new Error(`Plugin with name ${n.name} already exists`);if(n instanceof jy)n.setOpensips(this),this.newStreamPlugins.push(n);else if(n instanceof $y)n.setOpensips(this),this.processStreamPlugins.push(n);else throw new Error("Wrong plugin instance")}getPlugin(n){return this.newStreamPlugins.find(s=>s.name===n)||this.processStreamPlugins.find(s=>s.name===n)}reconnect(){if(this.reconnectionAttemptsCounter<this.reconnectionAttemptsLimit){const n=5e3*Math.pow(2,this.reconnectionAttemptsCounter);this.reconnectionAttemptsCounter++,setTimeout(this.start.bind(this),n)}else this.emit("reconnectionAttemptsLimitReached",void 0)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(Dl.AUDIO)&&(this.audio=new Hy(this)),this.modules.includes(Dl.MSRP)&&(this.msrp=new Fy(this)),this.modules.includes(Dl.VIDEO)&&(this.video=new qy(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.setReconnecting(!1),this.activeConnection=!0,this.waitingForSessionHangup=!1,this.reconnectionAttemptsCounter=0}),this.on(this.disconnectedEventName,()=>{this.setConnected(!1),!this.isReconnecting&&(this.setReconnecting(!0),this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.hasActiveSessions?(this.waitingForSessionHangup=!0,this.stop(!1),this.waitingForSessionTimeout=setTimeout(()=>{this.terminateAllSessions(),this.setInitialized(!1),this.waitingForSessionHangup=!1,this.activeConnection&&this.reconnect()},12e5)):(this.stop(),this.setInitialized(!1),this.activeConnection&&this.reconnect()))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(n,s){const i=!this.listenersList[n]||!this.listenersList[n].length?[s]:[...this.listenersList[n],s];this.listenersList={...this.listenersList,[n]:i}}removeIListener(n){const s={...this.listenersList};delete s[n],this.listenersList={...s}}triggerListener({listenerType:n,session:s,event:i}){const a=this.listenersList[n];!a||!a.length||a.forEach(e=>{e(s,i)})}setInitialized(n){this.initialized=n,this.emit("ready",n)}setConnected(n){this.connected=n,this.emit("connection",n)}setReconnecting(n){this.isReconnecting=n,this.emit("reconnecting",n)}}let Oe;const zd=Ce.ref(!1),Jd=Ce.ref(!1),Xd=Ce.ref(!1),Qd=Ce.ref({}),Zd=Ce.ref({}),e_=Ce.ref(!1),t_=Ce.ref(void 0),kl=Ce.ref({}),hu=Ce.ref({}),Ul=Ce.ref([]),du=Ce.ref("default"),_u=Ce.ref("default"),pu=Ce.ref(!1),fu=Ce.ref(!1),mu=Ce.ref(!0),n_=Ce.ref(!1),s_=Ce.ref(null),Ys=Ce.ref(void 0),r_=Ce.ref(!1),gu=Ce.ref(2),Tu=Ce.ref(1),vu=Ce.ref({}),i_=Ce.ref({}),o_=Ce.ref({}),yu=Ce.computed(()=>{const l={};return Object.entries(Qd.value).forEach(([n,s])=>{vu.value[n]?.isTransferred||(l[n]=s)}),l}),By=Ce.computed(()=>{const l={},n=Object.values(yu.value).map(s=>s.roomId);return Object.entries(kl.value).forEach(([s,i])=>{n.includes(i.roomId)&&(l[s]=i)}),l}),Ky=Ce.computed(()=>Ul.value.filter(l=>l.kind==="audioinput").map(l=>({deviceId:l.deviceId,kind:l.kind,groupId:l.groupId,label:l.label}))),Gy=Ce.computed(()=>Ul.value.filter(l=>l.kind==="audiooutput").map(l=>({deviceId:l.deviceId,kind:l.kind,groupId:l.groupId,label:l.label}))),l_=Ce.computed(()=>Object.values(yu.value).filter(l=>l.roomId===Ys.value));Ce.watch(l_,l=>{!l.length&&Ys.value&&(Ys.value=void 0)}),Ce.watch(_u,async(l,n)=>{l!==n&&await zt.actions.setMicrophone(l)}),Ce.watch(du,async(l,n)=>{l!==n&&await zt.actions.setSpeaker(l)}),Ce.watch(pu,l=>{zt.actions.setMuteWhenJoin(l)}),Ce.watch(fu,l=>{zt.actions.setDND(l)}),Ce.watch(mu,l=>{zt.actions.setCallWaiting(l)}),Ce.watch(gu,l=>{zt.actions.setMicrophoneSensitivity(l)}),Ce.watch(Tu,l=>{zt.actions.setSpeakerVolume(l)}),Ce.watch(Ys,async l=>{await zt.actions.setActiveRoom(l)});const zt={state:{isInitialized:zd,isOpenSIPSReady:Jd,isOpenSIPSReconnecting:Xd,activeCalls:yu,callsInActiveRoom:l_,activeMessages:Zd,addCallToCurrentRoom:e_,callAddingInProgress:t_,activeRooms:By,msrpHistory:hu,availableMediaDevices:Ul,inputMediaDeviceList:Ky,outputMediaDeviceList:Gy,selectedOutputDevice:du,selectedInputDevice:_u,muteWhenJoin:pu,isDND:fu,isCallWaitingEnabled:mu,isMuted:n_,originalStream:s_,currentActiveRoomId:Ys,callStatus:vu,callTime:i_,callMetrics:o_,autoAnswer:r_,microphoneInputLevel:gu,speakerVolume:Tu},actions:{init(l,n,s={}){return new Promise((i,a)=>{try{const e={...s,session_timers:!1,uri:`sip:${l.username}@${l.domain}`,password:l.password};l.authorization_jwt&&(e.authorization_jwt=l.authorization_jwt),Oe=new Vy({configuration:e,socketInterfaces:[`wss://${l.domain}`],sipDomain:`${l.domain}`,sipOptions:{session_timers:!1,extraHeaders:["X-Bar: bar"],pcConfig:{}},modules:l.modules,pnExtraHeaders:n}),Oe.on("connection",d=>{e_.value=!1,zd.value=!0,Jd.value=d,i(Oe)}).on("reconnecting",d=>{Xd.value=d}).on("changeActiveCalls",d=>{Qd.value={...d}}).on("changeActiveMessages",d=>{Zd.value={...d}}).on("newMSRPMessage",d=>{const _=d.session._id,u=hu.value[_]||[];u.push(d.message),hu.value[_]=[...u]}).on("callAddingInProgressChanged",d=>{t_.value=d}).on("changeAvailableDeviceList",d=>{Ul.value=[...d]}).on("changeActiveInputMediaDevice",d=>{_u.value=d}).on("changeActiveOutputMediaDevice",d=>{du.value=d}).on("changeMuteWhenJoin",d=>{pu.value=d}).on("changeIsCallWaiting",d=>{mu.value=d}).on("changeIsDND",d=>{fu.value=d}).on("changeIsMuted",d=>{n_.value=d}).on("changeActiveStream",d=>{s_.value=d}).on("currentActiveRoomChanged",d=>{Ys.value=d}).on("addRoom",({roomList:d})=>{kl.value={...d}}).on("updateRoom",({roomList:d})=>{kl.value={...d}}).on("removeRoom",({roomList:d})=>{kl.value={...d}}).on("changeCallStatus",d=>{vu.value={...d}}).on("changeCallTime",d=>{i_.value={...d}}).on("changeCallMetrics",d=>{o_.value={...d}}).begin(),i(Oe)}catch(e){console.error(e),a()}})},unregister(){Oe?.unregister()},register(){Oe?.register()},disconnect(){Oe?.disconnect()},initCall(l,n=!1,s=!1){Oe?.audio.initCall(l,n,s)},answerCall(l){Oe?.audio.answerCall(l)},terminateCall(l){Oe?.audio.terminateCall(l)},mute(){Oe?.audio.mute()},unmute(){Oe?.audio.unmute()},transferCall(l,n){Oe?.audio.transferCall(l,n)},mergeCall(l){Oe?.audio.mergeCall(l)},mergeCallByIds(l,n){Oe?.audio.mergeCallByIds(l,n)},holdCall(l,n){Oe?.audio.holdCall(l,n)},unholdCall(l){Oe?.audio.unholdCall(l)},async moveCall(l,n){await Oe?.audio.moveCall(l,n)},muteCaller(l){Oe?.audio.muteCaller(l)},unmuteCaller(l){Oe?.audio.unmuteCaller(l)},setMuteWhenJoin(l){Oe?.audio.setMuteWhenJoin(l)},setDND(l){Oe?.audio.setDND(l)},setCallWaiting(l){Oe?.audio.setCallWaiting(l)},async setMicrophone(l){await Oe?.audio.setMicrophone(l)},async setSpeaker(l){await Oe?.audio.setSpeaker(l)},sendDTMF(l,n){Oe?.audio.sendDTMF(l,n)},async setActiveRoom(l){await Oe?.audio.setActiveRoom(l)},setMicrophoneSensitivity(l){gu.value=l,Oe?.audio.setMicrophoneSensitivity(l)},setSpeakerVolume(l){Tu.value=l,Oe?.audio.setSpeakerVolume(l)},setAutoAnswer(l){r_.value=l,Oe?.audio.setAutoAnswer(l)},setMetricsConfig(l){Oe?.audio.setMetricsConfig(l)},msrpAnswer(l){Oe?.msrp.msrpAnswer(l)},messageTerminate(l){Oe?.msrp.messageTerminate(l)},sendMSRP(l,n){Oe?.msrp.sendMSRP(l,n)},initMSRP(l,n,s){Oe?.msrp.initMSRP(l,n,s)}}},a_=Symbol();function Wy(){return Ce.provide(a_,zt),zt}function Yy(){const l=Ce.inject(a_);if(!l)throw new Error("useVsipInject() is called without provider, please call useVsipProvide() first");return l}dn.useVsipInject=Yy,dn.useVsipProvide=Wy,dn.vsipAPI=zt,Object.defineProperty(dn,Symbol.toStringTag,{value:"Module"})});
160
160
  //# sourceMappingURL=super.umd.js.map